【问题标题】:Extract JSON representation of SQL query where clause with sqlparse使用 sqlparse 提取 SQL 查询 where 子句的 JSON 表示
【发布时间】:2021-11-03 10:12:39
【问题描述】:

我正在尝试使用 python 库 sqlparse 从 SQL 语句中提取 WHERE 条件并以条件 JSON 格式表示它。我只对 SQL 条件感兴趣,所以起点是一个虚拟 SQL 语句,即 select * from Table where Col1= 'aaa' AND Col2 > 10,它应该被转换成这样的嵌套 JSON 格式:

{"and" : [
   {"eq": {"Col1","aaa"} },
   {"gt" : {"Col2",10}}
]}

我的想法是使用 WHERE 子句的 AST 来生成这个 JSON 结构,但我没能做到。我也愿意接受有关不同 python 库的建议。

该解决方案应该能够处理不同类型的运算符,例如 =、、>、

【问题讨论】:

    标签: json parsing nested where-clause sql-parser


    【解决方案1】:

    您可以使用我的库SQLGlot 获取 AST,然后将其转换为 JSON。

    import sqlglot
    import sqlglot.expressions as exp
    
    sql = """
    select * from x where  Col1= 'aaa' AND Col2 > 10
    """
    
    where = sqlglot.parse_one(sql).find(exp.Where)
    
    print(where)
    
    (WHERE this:
      (AND this:
        (EQ this:
          (COLUMN this:
            (IDENTIFIER this: Col1, quoted: False)), expression:
          (LITERAL this: aaa, is_string: True)), expression:
        (GT this:
          (COLUMN this:
            (IDENTIFIER this: Col2, quoted: False)), expression:
          (LITERAL this: 10, is_string: False))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 2015-10-30
      • 1970-01-01
      相关资源
      最近更新 更多