Skip to content
Permalink
Browse files

Merge pull request #9939 from rouault/fix_opening_gpkg_with_fkey_viol…

…ation

Fix opening of GeoPackage datasets with foreign key violation
  • Loading branch information
m-kuhn committed May 8, 2019
2 parents 76b0932 + e48b64d commit c780ea87e66d6c2b4c8730ab8a2892cef36523ce
@@ -261,7 +261,16 @@ QgsRectangle QgsGdalProviderBase::extent( GDALDatasetH gdalDataset )const

GDALDatasetH QgsGdalProviderBase::gdalOpen( const char *pszFilename, GDALAccess eAccess )
{
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" );
}
GDALDatasetH hDS = GDALOpen( pszFilename, eAccess );
if ( modify_OGR_GPKG_FOREIGN_KEY_CHECK )
{
CPLSetThreadLocalConfigOption( "OGR_GPKG_FOREIGN_KEY_CHECK", nullptr );
}
return hDS;
}

@@ -3938,11 +3938,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 c780ea8

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