我正在使用pglast创建查询的抽象语法树(AST)。例如,在
from pglast import parse_sql
parse_sql("SELECT name, age FROM user as a WHERE age > 18;")
字符串
会给予我
(<RawStmt stmt=<SelectStmt targetList=(<ResTarget val=<ColumnRef fields=(<String sval='name'>,)>>, <ResTarget val=<ColumnRef fields=(<String sval='age'>,)>>) fromClause=(<RangeFunction lateral=False ordinality=False is_rowsfrom=False functions=((<SQLValueFunction op=<SQLValueFunctionOp.SVFOP_USER: 11> typmod=-1>, None),) alias=<Alias aliasname='a'>>,) whereClause=<A_Expr kind=<A_Expr_Kind.AEXPR_OP: 0> name=(<String sval='>'>,) lexpr=<ColumnRef fields=(<String sval='age'>,)> rexpr=<A_Const isnull=False val=<Integer ival=18>>> groupDistinct=False limitOption=<LimitOption.LIMIT_OPTION_DEFAULT: 0> op=<SetOperation.SETOP_NONE: 0> all=False> stmt_location=0 stmt_len=46>,)
型
我还需要从这个输出返回到原始查询。如何才能做到这一点?
包中还有另一个函数(parser.parse_sql_json
),该函数在json版本中生成AST,但在查询中添加了单词的位置信息。此查询的输出是否更容易返回原始查询
from pglast.parser import parse_sql_json
parse_sql_json('SELECT name, age FROM user as a WHERE age > 18;')
型
给了我
'{"version":150001,"stmts":[{"stmt":{"SelectStmt":{"targetList":[{"ResTarget":{"val":{"ColumnRef":{"fields":[{"String":{"sval":"name"}}],"location":7}},"location":7}},{"ResTarget":{"val":{"ColumnRef":{"fields":[{"String":{"sval":"age"}}],"location":13}},"location":13}}],"fromClause":[{"RangeFunction":{"functions":[{"List":{"items":[{"SQLValueFunction":{"op":"SVFOP_USER","typmod":-1,"location":22}},{}]}}],"alias":{"aliasname":"a"}}}],"whereClause":{"A_Expr":{"kind":"AEXPR_OP","name":[{"String":{"sval":"\\u003e"}}],"lexpr":{"ColumnRef":{"fields":[{"String":{"sval":"age"}}],"location":38}},"rexpr":{"A_Const":{"ival":{"ival":18},"location":44}},"location":42}},"limitOption":"LIMIT_OPTION_DEFAULT","op":"SETOP_NONE"}},"stmt_len":46}]}'
型
1条答案
按热度按时间44u64gxh1#
使用
Node
对象及其属性来导航AST并构建查询字符串,以根据pglast
生成的AST重新创建原始查询。该方法保证了原始查询的准确重建,并且使得操作其组件以进行附加分析或处理变得简单。类似地,可以使用Node
对象和属性以及parser.parse_sql_json
生成的AST的json版本来构建查询字符串。