Skip to content
Permalink
Browse files

[OGR provider] Fix opening of GeoPackage datasets with foreign key vi…

…olation
  • Loading branch information
rouault committed May 6, 2019
1 parent 18559de commit 477b05d6f85eb498223cf446f1d7e91a05e55b97
Showing with 29 additions and 0 deletions.
  1. +10 −0 src/providers/ogr/qgsogrprovider.cpp
  2. +19 −0 tests/src/python/test_provider_ogr_gpkg.py
@@ -3845,11 +3845,21 @@ GDALDatasetH QgsOgrProviderUtils::GDALOpenWrapper( const char *pszPath, bool bUp
bIsLocalGpkg = true;
}

bool modify_OGR_GPKG_FOREIGN_KEY_CHECK = !CPLGetConfigOption( "OGR_GPKG_FOREIGN_KEY_CHECK", nullptr );
if ( modify_OGR_GPKG_FOREIGN_KEY_CHECK )
{
CPLSetThreadLocalConfigOption( "OGR_GPKG_FOREIGN_KEY_CHECK", "NO" );
}

const int nOpenFlags = GDAL_OF_VECTOR | ( bUpdate ? GDAL_OF_UPDATE : 0 );
GDALDatasetH hDS = GDALOpenEx( pszPath, nOpenFlags, nullptr, papszOpenOptions, nullptr );
CSLDestroy( papszOpenOptions );

CPLSetThreadLocalConfigOption( "OGR_SQLITE_JOURNAL", nullptr );
if ( modify_OGR_GPKG_FOREIGN_KEY_CHECK )
{
CPLSetThreadLocalConfigOption( "OGR_GPKG_FOREIGN_KEY_CHECK", nullptr );
}

if ( !hDS )
{
@@ -1344,6 +1344,25 @@ def testUniqueValuesOnFidColumn(self):
self.assertEqual(vl1.uniqueValues(0), {1, 2})
self.assertEqual(vl1.uniqueValues(1), {'one', 'two'})

def testForeignKeyViolation(self):
"""Test that we can open a dataset with a foreign key violation"""

tmpfile = os.path.join(self.basetestpath, 'testForeignKeyViolation.gpkg')
ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile)
lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint)
f = ogr.Feature(lyr.GetLayerDefn())
f.SetGeometry(ogr.CreateGeometryFromWkt('POINT(0 1)'))
lyr.CreateFeature(f)
ds.ExecuteSQL("PRAGMA foreign_keys = OFF")
ds.ExecuteSQL("CREATE TABLE foo(id INTEGER)")
ds.ExecuteSQL("CREATE TABLE bar(fkey INTEGER, CONSTRAINT fkey_constraint FOREIGN KEY (fkey) REFERENCES foo(id))")
ds.ExecuteSQL("INSERT INTO bar VALUES (1)")
ds = None
vl = QgsVectorLayer('{}'.format(tmpfile) + "|layername=" + "test", 'test', 'ogr')
self.assertTrue(vl.isValid())
fids = set([f['fid'] for f in vl.getFeatures()])
self.assertEqual(len(fids), 1)


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

0 comments on commit 477b05d

Please sign in to comment.
You can’t perform that action at this time.