7

I am trying to load a postgres table (columns extracted using a select statement) from the python console in QGis:

The following works fine and the layer loads as expected:

uri = QgsDataSourceURI()
uri.setConnection("*****","***","****","****","*****")
uri.setDataSource("","mytable","geom","","id")
vlayer = QgsVectorLayer(uri.uri(),"LayerName","postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

if not vlayer.isValid():
    print "layer failed to load"

However, if I swap out the table name for an SQL select statement:

sql = "(select id from mytable)"
uri.setDataSource("",sql,"geom","","id")
vlayer = QgsVectorLayer(uri.uri(),"LayerName","postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

if not vlayer.isValid():
    print "layer failed to load"

Then the layer fails to load.

Also, if I use a very long SQL statement to try to select more columns, I get a message in the terminal window along the lines of:

NOTICE: identifier "(lonq sql text here)" will be truncated to"

Am I missing something? I am using QGis 2.4.

1

You missed the geom column in your SQL query!

So, if I rewrite the sql string to:

sql = "(select id, geom from mytable)"

it works for me...

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.