Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[OGR provider] Fix opening of GeoPackage datasets with foreign key vi…
…olation
  • Loading branch information
rouault committed May 8, 2019
1 parent 253a882 commit ce48a2c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/providers/ogr/qgsogrprovider.cpp
Expand Up @@ -3694,11 +3694,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 )
{
Expand Down
18 changes: 18 additions & 0 deletions tests/src/python/test_provider_ogr_gpkg.py
Expand Up @@ -1303,6 +1303,24 @@ def test_quote_identifier(self):
for i in range(1, len(vl.fields())):
self.assertEqual(vl.uniqueValues(i), {'a', 'b', 'c'})

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 ce48a2c

Please sign in to comment.