@@ -2029,15 +2029,41 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist, Flags flags )
2029
2029
delim = ' ,' ;
2030
2030
}
2031
2031
2032
- if ( mPrimaryKeyType == PktInt || mPrimaryKeyType == PktFidMap || mPrimaryKeyType == PktUint64 )
2032
+ // Optimization: if we have a single primary key column whose default value
2033
+ // is a sequence, and that none of the features have a value set for that
2034
+ // column, then we can completely omit inserting it.
2035
+ bool skipSinglePKField = false ;
2036
+
2037
+ if ( ( mPrimaryKeyType == PktInt || mPrimaryKeyType == PktFidMap || mPrimaryKeyType == PktUint64 ) )
2033
2038
{
2034
- Q_FOREACH ( int idx, mPrimaryKeyAttrs )
2039
+ if ( mPrimaryKeyAttrs .size () == 1 &&
2040
+ defaultValueClause ( mPrimaryKeyAttrs [0 ] ).startsWith ( " nextval(" ) )
2035
2041
{
2036
- insert += delim + quotedIdentifier ( field ( idx ).name () );
2037
- values += delim + QStringLiteral ( " $%1" ).arg ( defaultValues.size () + offset );
2038
- delim = ' ,' ;
2039
- fieldId << idx;
2040
- defaultValues << defaultValueClause ( idx );
2042
+ bool foundNonNullPK = false ;
2043
+ int idx = mPrimaryKeyAttrs [0 ];
2044
+ for ( int i = 0 ; i < flist.size (); i++ )
2045
+ {
2046
+ QgsAttributes attrs2 = flist[i].attributes ();
2047
+ QVariant v2 = attrs2.value ( idx, QVariant ( QVariant::Int ) );
2048
+ if ( !v2.isNull () )
2049
+ {
2050
+ foundNonNullPK = true ;
2051
+ break ;
2052
+ }
2053
+ }
2054
+ skipSinglePKField = !foundNonNullPK;
2055
+ }
2056
+
2057
+ if ( !skipSinglePKField )
2058
+ {
2059
+ for ( int idx : mPrimaryKeyAttrs )
2060
+ {
2061
+ insert += delim + quotedIdentifier ( field ( idx ).name () );
2062
+ values += delim + QStringLiteral ( " $%1" ).arg ( defaultValues.size () + offset );
2063
+ delim = ' ,' ;
2064
+ fieldId << idx;
2065
+ defaultValues << defaultValueClause ( idx );
2066
+ }
2041
2067
}
2042
2068
}
2043
2069
@@ -2048,6 +2074,8 @@ bool QgsPostgresProvider::addFeatures( QgsFeatureList &flist, Flags flags )
2048
2074
for ( int idx = 0 ; idx < attributevec.count (); ++idx )
2049
2075
{
2050
2076
QVariant v = attributevec.value ( idx, QVariant ( QVariant::Int ) ); // default to NULL for missing attributes
2077
+ if ( skipSinglePKField && idx == mPrimaryKeyAttrs [0 ] )
2078
+ continue ;
2051
2079
if ( fieldId.contains ( idx ) )
2052
2080
continue ;
2053
2081
0 commit comments