Skip to content

Commit ce48a2c

Browse files
committed
[OGR provider] Fix opening of GeoPackage datasets with foreign key violation
1 parent 253a882 commit ce48a2c

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/providers/ogr/qgsogrprovider.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3694,11 +3694,21 @@ GDALDatasetH QgsOgrProviderUtils::GDALOpenWrapper( const char *pszPath, bool bUp
36943694
bIsLocalGpkg = true;
36953695
}
36963696

3697+
bool modify_OGR_GPKG_FOREIGN_KEY_CHECK = !CPLGetConfigOption( "OGR_GPKG_FOREIGN_KEY_CHECK", nullptr );
3698+
if ( modify_OGR_GPKG_FOREIGN_KEY_CHECK )
3699+
{
3700+
CPLSetThreadLocalConfigOption( "OGR_GPKG_FOREIGN_KEY_CHECK", "NO" );
3701+
}
3702+
36973703
const int nOpenFlags = GDAL_OF_VECTOR | ( bUpdate ? GDAL_OF_UPDATE : 0 );
36983704
GDALDatasetH hDS = GDALOpenEx( pszPath, nOpenFlags, nullptr, papszOpenOptions, nullptr );
36993705
CSLDestroy( papszOpenOptions );
37003706

37013707
CPLSetThreadLocalConfigOption( "OGR_SQLITE_JOURNAL", nullptr );
3708+
if ( modify_OGR_GPKG_FOREIGN_KEY_CHECK )
3709+
{
3710+
CPLSetThreadLocalConfigOption( "OGR_GPKG_FOREIGN_KEY_CHECK", nullptr );
3711+
}
37023712

37033713
if ( !hDS )
37043714
{

tests/src/python/test_provider_ogr_gpkg.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1303,6 +1303,24 @@ def test_quote_identifier(self):
13031303
for i in range(1, len(vl.fields())):
13041304
self.assertEqual(vl.uniqueValues(i), {'a', 'b', 'c'})
13051305

1306+
def testForeignKeyViolation(self):
1307+
"""Test that we can open a dataset with a foreign key violation"""
1308+
1309+
tmpfile = os.path.join(self.basetestpath, 'testForeignKeyViolation.gpkg')
1310+
ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile)
1311+
lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint)
1312+
f = ogr.Feature(lyr.GetLayerDefn())
1313+
f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 1)'))
1314+
lyr.CreateFeature(f)
1315+
ds.ExecuteSQL("PRAGMA foreign_keys = OFF")
1316+
ds.ExecuteSQL("CREATE TABLE foo(id INTEGER)")
1317+
ds.ExecuteSQL("CREATE TABLE bar(fkey INTEGER, CONSTRAINT fkey_constraint FOREIGN KEY (fkey) REFERENCES foo(id))")
1318+
ds.ExecuteSQL("INSERT INTO bar VALUES (1)")
1319+
ds = None
1320+
vl = QgsVectorLayer('{}'.format(tmpfile) + "|layername=" + "test", 'test', 'ogr')
1321+
self.assertTrue(vl.isValid())
1322+
fids = set([f['fid'] for f in vl.getFeatures()])
1323+
self.assertEqual(len(fids), 1)
13061324

13071325
if __name__ == '__main__':
13081326
unittest.main()

0 commit comments

Comments
 (0)