Skip to content
Permalink
Browse files

Allow to load a query-based SQLite layer without geometry

  • Loading branch information
Hugo Mercier
Hugo Mercier committed Feb 11, 2015
1 parent f76d730 commit 12a4e7dc8e103902e2d6868c6eac20228910894b
@@ -4145,7 +4145,7 @@ bool QgsSpatiaLiteProvider::checkLayerType()

QString sql;

if ( mGeometryColumn.isEmpty() )
if ( mGeometryColumn.isEmpty() && !(mQuery.startsWith( "(" ) && mQuery.endsWith( ")" )) )
{
// checking if is a non-spatial table
sql = QString( "SELECT type FROM sqlite_master "
@@ -70,6 +70,18 @@ def setUpClass(cls):
sql += "VALUES (1, 'toto', GeomFromText('POLYGON((0 0,1 0,1 1,0 1,0 0))', 4326))"
cur.execute(sql)

# simple table with primary key
sql = "CREATE TABLE test_q (id INTEGER NOT NULL PRIMARY KEY, name TEXT NOT NULL)"
cur.execute(sql)
sql = "SELECT AddGeometryColumn('test_q', 'geometry', 4326, 'POLYGON', 'XY')"
cur.execute(sql)
sql = "INSERT INTO test_q (id, name, geometry) "
sql += "VALUES (1, 'toto', GeomFromText('POLYGON((0 0,1 0,1 1,0 1,0 0))', 4326))"
cur.execute(sql)
sql = "INSERT INTO test_q (id, name, geometry) "
sql += "VALUES (2, 'toto', GeomFromText('POLYGON((0 0,1 0,1 1,0 1,0 0))', 4326))"
cur.execute(sql)

cur.execute( "COMMIT" )
con.close()

@@ -122,5 +134,36 @@ def xtest_SplitFeatureWithFailedCommit(self):
for c1, c2 in zip(p1, p2):
c1 == c2 or die("polygon has been altered by failed edition")

def test_queries(self):
"""Test loading of query-based layers"""

# a query with a geometry, but no unique id
# this allows to load a query without unique id
# however, functions relying on such a unique id would fail
l = QgsVectorLayer("dbname=%s table='(select * from test_q)' (geometry)" % self.dbname, "test_pg_query1", "spatialite")
assert(l.isValid())
# the id() is not consistent
sum_id1 = sum(f.id() for f in l.getFeatures())
# the attribute 'id' works
sum_id2 = sum(f.attributes()[0] for f in l.getFeatures())
assert(sum_id1 == 0)
assert(sum_id2 == 3)

# and now with an id declared
l = QgsVectorLayer("dbname=%s table='(select * from test_q)' (geometry) key='id'" % self.dbname, "test_pg_query1", "spatialite")
assert(l.isValid())
sum_id1 = sum(f.id() for f in l.getFeatures())
sum_id2 = sum(f.attributes()[0] for f in l.getFeatures())
assert(sum_id1 == 3)
assert(sum_id2 == 3)

# a query, but no geometry
l = QgsVectorLayer("dbname=%s table='(select id,name from test_q)' key='id'" % self.dbname, "test_pg_query1", "spatialite")
assert(l.isValid())
sum_id1 = sum(f.id() for f in l.getFeatures())
sum_id2 = sum(f.attributes()[0] for f in l.getFeatures())
assert(sum_id1 == 3)
assert(sum_id2 == 3)

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

0 comments on commit 12a4e7d

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