Skip to content

Commit

Permalink
[ogr] Read field comments automatically on GDAL >= 3.7
Browse files Browse the repository at this point in the history
Specifically, this permits QGIS to automatically load comments
for fields which are stored in the GeoPackage "gpkg_data_columns"
metadata table.

The comment reading is abstracted through GDAL though, so there's
potentially other OGR formats which allow comments which will
be supported in future automatically.
  • Loading branch information
nyalldawson committed Apr 14, 2023
1 parent 15e6c77 commit de171ac
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/core/providers/ogr/qgsogrprovider.cpp
Expand Up @@ -814,6 +814,16 @@ void QgsOgrProvider::loadFields()
newField.setAlias( alias );
}

#if GDAL_VERSION_NUM >= GDAL_COMPUTE_VERSION(3,7,0)
{
const QString comment = textEncoding()->toUnicode( OGR_Fld_GetComment( fldDef ) );
if ( !comment.isEmpty() )
{
newField.setComment( comment );
}
}
#endif

// check if field is nullable
bool nullable = OGR_Fld_IsNullable( fldDef );
if ( !nullable )
Expand Down
43 changes: 43 additions & 0 deletions tests/src/python/test_provider_ogr.py
Expand Up @@ -3229,6 +3229,49 @@ def test_provider_set_field_alias(self):
self.assertEqual(fields['my_field'].alias(), 'my alias')
self.assertEqual(fields['my_field2'].alias(), 'my alias2')

@unittest.skipIf(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(3, 7, 0), "GDAL 3.7.0 required")
def testFieldComment(self):
"""Test reading field comments"""
with tempfile.TemporaryDirectory() as dest_dir:
database_path = os.path.join(dest_dir, 'new_gpkg.gpkg')
ds = ogr.GetDriverByName('GPKG').CreateDataSource(database_path)
lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint)
lyr.CreateField(ogr.FieldDefn('field1', ogr.OFTString))
lyr.CreateField(ogr.FieldDefn('field2', ogr.OFTString))

ds.ExecuteSQL(
"""CREATE TABLE gpkg_data_columns (
table_name TEXT NOT NULL,
column_name TEXT NOT NULL,
name TEXT,
title TEXT,
description TEXT,
mime_type TEXT,
constraint_name TEXT,
CONSTRAINT pk_gdc PRIMARY KEY (table_name, column_name),
CONSTRAINT gdc_tn UNIQUE (table_name, name)
)"""
)

ds.ExecuteSQL(
"INSERT INTO gpkg_data_columns('table_name', 'column_name', 'description') VALUES ('test', 'field1', 'my description')"
)

ds = None

vl = QgsVectorLayer(f'{database_path}|layername=test', 'test')
self.assertTrue(vl.isValid())

fields = vl.fields()

self.assertEqual(fields[0].name(), 'fid')

self.assertEqual(fields[1].name(), 'field1')
self.assertEqual(fields[1].comment(), 'my description')

self.assertEqual(fields[2].name(), 'field2')
self.assertEqual(fields[2].comment(), '')


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

0 comments on commit de171ac

Please sign in to comment.