Skip to content

Instantly share code, notes, and snippets.

@NathanW2
Last active January 16, 2017 13:24
Show Gist options
  • Save NathanW2/12ebe6a7a9596cf04d914db00f82a388 to your computer and use it in GitHub Desktop.
Save NathanW2/12ebe6a7a9596cf04d914db00f82a388 to your computer and use it in GitHub Desktop.
Walk a QgsExpression tree
def walk(node):
if node.nodeType() == QgsExpression.ntBinaryOperator:
handle_binary(node)
elif node.nodeType() == QgsExpression.ntUnaryOperator:
print("Unary")
elif node.nodeType() == QgsExpression.ntInOperator:
print("In")
elif node.nodeType() == QgsExpression.ntFunction:
handle_function(node)
elif node.nodeType() == QgsExpression.ntLiteral:
handle_literal(node)
elif node.nodeType() == QgsExpression.ntColumnRef:
print("ColumnRef")
elif node.nodeType() == QgsExpression.ntCondition:
print("Condition")
def handle_binary(node):
print("BINARY")
op = node.op()
ops = [
"OR", "AND",
"=", "<>", "<=", ">=", "<", ">", "~", "LIKE", "NOT LIKE", "ILIKE", "NOT ILIKE", "IS", "IS NOT",
"+", "-", "*", "/", "//", "%", "^",
"||"
]
left = node.opLeft()
right = node.opRight()
walk(left)
print(ops[op])
walk(right)
def handle_literal(node):
print("LITERAL")
print("Value:" + str(node.value()))
def handle_function(node):
print("FUNCTION")
fnIndex = node.fnIndex()
func = QgsExpression.Functions()[fnIndex]
args = node.args().list()
print(func.name())
for arg in args:
walk(arg)
exp = QgsExpression("1 = 2")
walk(exp.rootNode())
exp = QgsExpression("to_string(1 + 2)")
walk(exp.rootNode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment