Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit caa73e0

Browse files
nyalldawsongithub-actions[bot]
authored andcommittedJan 19, 2022
[mssql] Fix inserting features when pk attribute name contains special chars
Fixes #42290
1 parent e32083e commit caa73e0

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed
 

‎src/providers/mssql/qgsmssqlprovider.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,7 +1126,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList &flist, Flags flags )
11261126
type = QStringLiteral( "%1(%2,%3)" ).arg( type ).arg( fld.length() ).arg( fld.precision() );
11271127
}
11281128

1129-
statement += delim + QStringLiteral( "%1 %2" ).arg( fld.name(), type );
1129+
statement += delim + QStringLiteral( "[%1] %2" ).arg( fld.name(), type );
11301130
delim = ",";
11311131
}
11321132

@@ -1211,7 +1211,7 @@ bool QgsMssqlProvider::addFeatures( QgsFeatureList &flist, Flags flags )
12111211
for ( const auto idx : mPrimaryKeyAttrs )
12121212
{
12131213
const QgsField &fld = mAttributeFields.at( idx );
1214-
statement += delim + "inserted." + fld.name();
1214+
statement += delim + QStringLiteral( "inserted.[%1]" ).arg( fld.name() );
12151215
delim = QStringLiteral( "," );
12161216
}
12171217

‎tests/src/python/test_provider_mssql.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -821,6 +821,33 @@ def testExtentFromGeometryTable(self):
821821
self.assertEqual(extent.toString(1),
822822
QgsRectangle(0.0, 0.5, 5.5, 6.0).toString(1))
823823

824+
def test_insert_pk_escaping(self):
825+
"""
826+
Test that inserting features works with complex pk name
827+
see https://github.com/qgis/QGIS/issues/42290
828+
"""
829+
md = QgsProviderRegistry.instance().providerMetadata('mssql')
830+
conn = md.createConnection(self.dbconn, {})
831+
832+
conn.execSql('DROP TABLE IF EXISTS qgis_test.test_complex_pk_name')
833+
conn.execSql('CREATE TABLE qgis_test.test_complex_pk_name ([test-field] int)')
834+
835+
uri = '{} table="qgis_test"."test_complex_pk_name" sql='.format(self.dbconn)
836+
vl = QgsVectorLayer(uri, '', 'mssql')
837+
self.assertTrue(vl.isValid())
838+
839+
self.assertEqual(vl.primaryKeyAttributes(), [0])
840+
841+
vl.startEditing()
842+
f = QgsFeature(vl.fields())
843+
f.setAttributes([1])
844+
self.assertTrue(vl.addFeature(f))
845+
self.assertTrue(vl.commitChanges())
846+
847+
vl = QgsVectorLayer(uri, '', 'mssql')
848+
features = list(vl.getFeatures())
849+
self.assertEqual([f['test-field'] for f in features], [1])
850+
824851

825852
if __name__ == '__main__':
826853
unittest.main()

0 commit comments

Comments
 (0)
Please sign in to comment.