我正在使用 Flask 和 Flask-SQLAlchemy 编写一个应用程序。我希望用户能够使用特定于域的查询语言来查询数据库,例如parent.name = "foo" AND (name = "bar" OR age = 11).我使用 Pyparsing 为这种语言编写了一个解析器:import pyparsing as ppquery = 'parent.name = "foo" AND (name = "bar" OR age = 11)'and_operator = pp.oneOf(['and', '&'], caseless=True)or_operator = pp.oneOf(['or', '|'], caseless=True)identifier = pp.Word(pp.alphas + '_', pp.alphas + '_.')comparison_operator = pp.oneOf(['=','!=','>','>=','<', '<='])integer = pp.Regex(r'[+-]?\d+').setParseAction(lambda t: int(t[0]))float_ = pp.Regex(r'[+-]?\d+\.\d*').setParseAction(lambda t: float(t[0]))string = pp.QuotedString('"')comparison_operand = string | identifier | float_ | integercomparison_expr = pp.Group(comparison_operand + comparison_operator + comparison_operand)grammar = pp.operatorPrecedence(comparison_expr, [ (and_operator, 2, pp.opAssoc.LEFT), (or_operator, 2, pp.opAssoc.LEFT) ])result = grammar.parseString(query)print(result.asList())这给了我以下输出:[[['parent.name', '=', 'foo'], 'and', [['name', '=', 'bar'], 'or', ['age', '=', 11]]]]现在我不知道该怎么办。如何动态生成 SQLAlchemy 查询?是否有任何图书馆可以帮助解决这个问题?生成原始 SQL 会更容易吗?
添加回答
举报
0/150
提交
取消