QGIS has some support for parsing of SQL-like expressions. Only a small subset of SQL syntax is supported. The expressions can be evaluated either as boolean predicates (returning True or False) or as functions (returning a scalar value). See Expressions in the User Manual for a complete list of available functions.
Three basic types are supported:
123
, 3.14
'hello world'
The following operations are available:
+
, -
, *
, /
, ^
(1 + 1) * 3
-12
, +5
sqrt
, sin
, cos
, tan
, asin
,
acos
, atan
to_int
, to_real
, to_string
, to_date
$area
, $length
$x
, $y
, $geometry
, num_geometries
, centroid
And the following predicates are supported:
=
, !=
, >
, >=
, <
, <=
LIKE
(using % and _), ~
(regular expressions)AND
, OR
, NOT
IS NULL
, IS NOT NULL
Examples of predicates:
1 + 2 = 3
sin(angle) > 0
'Hello' LIKE 'He%'
(x > 10 AND y > 10) OR z = 0
Examples of scalar expressions:
2 ^ 10
sqrt(val)
$length + 1
>>> exp = QgsExpression('1 + 1 = 2')
>>> exp.hasParserError()
False
>>> exp = QgsExpression('1 + 1 = ')
>>> exp.hasParserError()
True
>>> exp.parserErrorString()
PyQt4.QtCore.QString(u'syntax error, unexpected $end')
>>> exp = QgsExpression('1 + 1 = 2')
>>> value = exp.evaluate()
>>> value
1
The following example will evaluate the given expression against a feature. “Column” is the name of the field in the layer.
>>> exp = QgsExpression('Column = 99')
>>> value = exp.evaluate(feature, layer.pendingFields())
>>> bool(value)
True
You can also use QgsExpression.prepare() if you need check more than one feature. Using QgsExpression.prepare() will increase the speed that evaluate takes to run.
>>> exp = QgsExpression('Column = 99')
>>> exp.prepare(layer.pendingFields())
>>> value = exp.evaluate(feature)
>>> bool(value)
True
exp = QgsExpression("1 + 1 = 2 ")
if exp.hasParserError():
raise Exception(exp.parserErrorString())
value = exp.evaluate()
if exp.hasEvalError():
raise ValueError(exp.evalErrorString())
print value
The following example can be used to filter a layer and return any feature that matches a predicate.
def where(layer, exp):
print "Where"
exp = QgsExpression(exp)
if exp.hasParserError():
raise Exception(exp.parserErrorString())
exp.prepare(layer.pendingFields())
for feature in layer.getFeatures():
value = exp.evaluate(feature)
if exp.hasEvalError():
raise ValueError(exp.evalErrorString())
if bool(value):
yield feature
layer = qgis.utils.iface.activeLayer()
for f in where(layer, 'Test > 1.0'):
print f + " Matches expression"