Pyparsing SQL Selects:无法将复杂的 UNION 提取为 Dict

问题描述 投票:0回答:1

我正在尝试根据

select_parser.py
示例解析和读取复杂 select 语句的组件,但我似乎无法使其适用于带有 UNION 的 select 语句。

我的示例选择语句是

select x as foo from xyz where x='1' union select y from abc except select z from pqr

这个语句被正确解析,当我从解析结果中提取字典时,我希望有某种方法来区分这里的 3 个 select 语句。但是,该字典在内部被覆盖,并且仅返回最后一个 select 语句。

parseResults.asDict()
上述声明给了我

{'columns': [{'col': {'col': ['z']}}], 
'from': [{'table': [['xyz']]}, {'table': [['abc']]}, {'table': [['pqr']]}], 
'where_expr': [{'col': ['x']}, '=', '1']}

这看起来很混乱。理想情况下,我希望结果看起来像这样

{
  'select_core': {
    'columns': [
      {
        'col': {
          'col': [
            'x'
          ]
        }
      }
    ],
    'from': [
      {
        'table': [
          [
            'xyz'
          ]
        ]
      }
    ],
    'where_expr': [
      {
        'col': [
          'x'
        ]
      },
      '=',
      '1'
    ]
  },
  compund_operation: [
    {
      operation: 'UNION'
      'columns': [
        {
          'col': {
            'col': [
              'y'
            ]
          }
        }
      ],
      'from': [
        {
          'table': [
            [
              'abc'
            ]
          ]
        }
      ],
      'where_expr': []
    },
    {
      operation: 'EXCEPT'
      'columns': [
        {
          'col': {
            'col': [
              'z'
            ]
          }
        }
      ],
      'from': [
        {
          'table': [
            [
              'pqr'
            ]
          ]
        }
      ],
      'where_expr': []
    }
  ]
}

关于如何标记语法以便我可以获得与上面类似的结果有什么帮助吗?

我认为这与语句的标签方式有关。我尝试过标记 select 语句,但我无法正确标记

+ ZeroOrMore(compound_operator + select_core)
语句以提供我想要的嵌套字典。

pyparsing
1个回答
0
投票

写这个扩展做得很好。将

select_core
包裹在一个组中,以防止结果名称相互覆盖。我猜这个表达的完整形式类似于
select_core + ZeroOrMore(compound_operator + select_core)
。您可以重写为:

expr = Group(select_core) + ZeroOrMore(compound_operator + Group(select_core))

或者只是:

select_core = Group(select_core)
expr = select_core + ZeroOrMore(compound_operator + select_core)

无论哪种方式,将 select_core 包装在一个 Group 中都会使其拥有自己的名称。

© www.soinside.com 2019 - 2024. All rights reserved.