1

In QGIS 3.2 (and 3.0), when trying to load a PostGIS layer into QGIS using a python function as follows:

def create_pg_layer(table,schema,geom_column='geom'):
    uri = QgsDataSourceUri()
    # set host name, port, database name, username and password
    uri.setConnection("localhost", "5432","","","")
    uri.setDataSource(schema, table, geom_column)
    vlayer = QgsVectorLayer(uri.uri(False), table, "postgres")
    return vlayer

It returns a None layer object, and fails to load the layer when the PostGIS table is empty, but succeed when the table contains a non-zero number of rows with non-empty geometry.

This is annoying because a PostGIS table can be treated as invalid (or valid) depending on its content.

Is there a way to allow an empty PostGIS table to be loaded into QGIS in above?

  • Does your empty table still have a corresponding row in geometry_columns? – user30184 Aug 10 '18 at 9:22
  • @user30184, yes, the empty table does show up in public.geometry_columns – tinlyx Aug 10 '18 at 13:12
  • What if table contains one row but with empty geometry? – user30184 Aug 10 '18 at 14:11
  • I have a feeling that QGIS wants to know the spatial extents of the layer and therefore fails when the table is empty. – user30184 Aug 10 '18 at 14:22
0

I can't say what goes wrong for you but this code adds an empty table into map project without any errors for me when I run it from the Python console:

uri = QgsDataSourceUri()
# set host name, port, database name, username and password
uri.setConnection("localhost", "5432", "mydb", "user", "passwd")
# set database schema, table name, geometry column and optionally
# subset (WHERE clause)
uri.setDataSource("public", "empty", "wkb_geometry", "")

vlayer = QgsVectorLayer(uri.uri(False), "empty_from_pg", "postgres")   
QgsProject.instance().addMapLayer(vlayer)

Attributes appear correctly and layer-properties show correct CRS and geometry type:

Encoding UTF-8
Geometry Polygon (Polygon)
CRS EPSG:4326 - WGS 84 - Geographic
Extent Empty
Unit degrees

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.