1

The Aim:
I am trying to insert a number of empty VIEWS into QGIS using PyQGIS. These VIEWS have been created and stored in a PostgreSQL database.

I want to also ensure i can successfully re-open the project at a later date whilst some of the layers are still empty or have become empty. These layers can at times be empty depending on what has been happening recently in the database.

The Problem:
QGIS does not like it when these layers are empty on inserting them, or when attempting to re-open the project. It either fails to insert the empty layer, or it informs the user that they are 'bad layers' and need to be deleted in order to continue. The layers can be inserted successfully when they contain data.

Python code used:
Note: "PlatformID" is the primary key.

uri = QgsDataSourceUri()
uri.setConnection(host, port, db_name, user, password)
uri.setDataSource("Data", "FieldOfViewIndex", "geom", "", "PlatformID")
vlayer = QgsVectorLayer(uri.uri(False), "FieldOfViewIndex", "postgres") 
QgsProject.instance().addMapLayer(vlayer)

Common error messages:

WARNING Geometry type and srid for empty column geom of "Data"."FieldOfViewIndex" undefined.

WARNING invalid PostgreSQL layer

In the PostgreSQL geometry_columns VIEW, their SRID is 0 and the geometry type is GEOMETRY.

asked Jul 17, 2019 at 15:32
1
  • 1
    Have you created the geom field with SELECT AddGeometryColumn (...) for explicit geometry and srid declaration ? doc. Commented Jul 17, 2019 at 15:52

1 Answer 1

1

You can force the geometry type and projection in the view definition by casting the geometry:

create view tv as 
 select geom::geometry(POINT, 4326)
 from myTable;
jgtest=> \d tv
 View "public.tv"
 Column | Type | Collation | Nullable | Default
------------+----------------------+-----------+----------+---------
 geom | geometry(Point,4326) | | |
answered Jul 17, 2019 at 16:08
1
  • Perfect. This has done it thank you. I didn't expect the answer to be so simple. Commented Jul 18, 2019 at 11:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.