Last active
December 20, 2015 10:49
-
-
Save Stiivi/6118946 to your computer and use it in GitHub Desktop.
Lightweight Expressions: Example of simple SQLAlchemy expression compiler. For more information see https://github.com/Stiivi/expressions
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
class SQLAlchemyExpressionCompiler(object): | |
def __init__(self, statement): | |
# Context of this compiler is a SQLAlchemy statement object | |
self.statement = statement | |
def compile_literal(self, literal): | |
return literal | |
def compile_variable(self, variable): | |
# Get a column object from the statement | |
return self.statement.c[variable] | |
def compile_operator(self, operator, op1, op2): | |
if operator == "+": | |
return op1 + op2 | |
elif operator == "-": | |
return op1 - op2 | |
elif operator == "*": | |
return op1 * op2 | |
elif operator == "/": | |
return op1 / op2 | |
else: | |
raise SyntaxError("Unknown operator '%s'" % operator) | |
def compile_function(self, function, args): | |
raise NotImplementedError | |
# Assume that we have a `table` object which is instance of sqlalchemy `Table` class | |
compiler = SQLAlchemyExpressionCompiler(table) | |
expr = "(amount / transactions) * 2" | |
expr = Expression(expr) | |
selection = expr.compile(compiler) | |
statement = sqlalchemy.sql.expression.select([selection], table) | |
print(statement) | |
# Prints: | |
# | |
# SELECT (data.amount / data.transactions) * ? AS anon_1 | |
# FROM data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment