Last active
October 18, 2016 17:00
-
-
Save NathanW2/4ab4c7eb81eccbf3825a7126a824c33e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
query = From(iface.activeLayer()) \ | |
.where('"Pit Type" = \'MH\'') \ | |
.limit(10) \ | |
.select("Pit Type", "SURVEY", "CATCHMENT", geometry=True) | |
query, layer = SQL("SELECT SURVEY, geometry FROM Pits GROUP BY Pit LIMIT 20", name="MyQuery") | |
query, layer = SQL("SELECT Pit, SURVEY, ST_UNION(ST_Buffer(geometry, 20)) as geometry FROM Pits GROUP BY Pit", | |
name="Buffers") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from qgis.core import QgsFeatureRequest | |
from PyQt4.QtCore import QUrl | |
class Query(object): | |
def __init__(self, layer): | |
self.rq = QgsFeatureRequest() | |
self.layer = layer | |
def where(self, expression): | |
self.rq.setFilterExpression(expression) | |
return self | |
def in_(self, *ids): | |
self.rq.setFilterFids(ids) | |
return self | |
def extent(self, rect): | |
self.rq.setFilterRect(rect) | |
return self | |
def no_geometry(self): | |
self.rq.setFlags(QgsFeatureRequest.NoGeometry) | |
return self | |
def limit(self, top): | |
self.rq.setLimit(top) | |
return self | |
def select(self, *fields, **kwargs): | |
if fields: | |
self.rq.setSubsetOfAttributes(fields, self.layer.pendingFields()) | |
if "geometry" in kwargs and not kwargs['geometry']: | |
self.no_geometry() | |
return self.layer.getFeatures(self.rq) | |
def SQL(sql, name="querylayer"): | |
sql = "?query={0}&geometry=geometry".format(sql) | |
query = QUrl(sql).toEncoded() | |
layer = QgsVectorLayer(str(query), name, "virtual") | |
if not layer.dataProvider().error().isEmpty(): | |
raise Exception(layer.dataProvider().error().message()) | |
return From(layer).select(), layer | |
def From(layer): | |
return Query(layer) |
Are you suggesting all three syntaxes be valid, or asking for opinions on which is best?
Gain readability and expressibility with an SQL like syntax.
Performances costs? (because ORM are now less use to fully take advantage of the underlying DB)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used to query a layer in pyqgis in a friendly way without worrying about the underlying pyqgis API. Wraps QgsFetaureRequest for the method chaining style and virtual layers for the raw SQL style.