Last active
December 17, 2016 08:42
-
-
Save fy0/7364fb62d7c147205d4453d1b3b1b3f9 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
# 基于 peewee,需要传入 model 类和查询条件 | |
def parse_query(sheet_model, statements): | |
""" | |
statements: | |
['and', | |
['==', 'col1', val1], | |
['!=', 'col2', val2], | |
['and', | |
['==', 'col3', val3], | |
['!=', 'col4', val4], | |
] | |
] | |
""" | |
query = sheet_model.select() | |
bin_op = { | |
'==': '__eq__', | |
'!=': '__ne__', | |
} | |
logic_op = { | |
'and': '__and__', | |
#'or': '__or__', | |
} | |
def parse_binary_op(q, s): | |
if s[0] in bin_op: | |
col = getattr(sheet_model, s[1]) | |
return q.where(getattr(col, bin_op[s[0]])(s[2])) | |
else: | |
raise SyntaxError('查询格式异常:未识别的二元算符 %r' % s[0]) | |
def parse_logic_op(q, s): | |
if s[0] in logic_op: | |
for i in s[1:]: | |
q = parse_binary_op(q, i) | |
return q | |
raise SyntaxError('查询格式异常:未识别的逻辑符 %r' % s[0]) | |
def parse_stmt(q, s): | |
if len(s) == 0: | |
return q | |
if type(s[0]) == list: | |
for i in s: | |
q = parse_binary_op(q, i) | |
return q | |
else: | |
return parse_logic_op(q, s) | |
# 这里注意一点,where里能写表达式的真相,其实是对column的运算符重载,而不是通过反射获取了参数的表达式 | |
return parse_stmt(query, statements) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment