【问题标题】:How can I extract table names from sub queries using sqlparse?如何使用 sqlparse 从子查询中提取表名?
【发布时间】:2021-02-18 03:08:34
【问题描述】:

我正在尝试使用 sqlparse 提取查询中的所有表名,但在子查询或插入括号中的语句时遇到问题。

我有以下疑问,

import sqlparse 
    
sql = """ 
          create test.test_table as (
                            select 1
                            from fake.table
                        );
        """
    

当我在括号中查找包含语句的标记时,使用

y = sqlparse.parse(sql)

for i in y[0].tokens:
    if isinstance(i, Identifier):
        print(i)
        print(i.get_real_name())

我得到以下结果,

test.test_table as (
                            select 1
                            from fake.table
                        )
test_table

结果仅作为一个标识符标记返回。当我尝试从括号内获取表名时,所有返回的是 test.test_table。我最终要做的是提取两个表名 test.test_table 和 fake.table

有没有人知道我该怎么做?

【问题讨论】:

    标签: python sql-parser


    【解决方案1】:

    这可能会有所帮助,我一直在使用其中包含子查询的 Select SQL 语句,因此通常格式为:

    Select blah from (select blah from table_name) alias
    

    所以我首先忽略第一个 Select 语句,并寻找包含单词 Select 的标记:

    for item in parsed.tokens:
    
        if 'SELECT' in identifier.value.upper():
            subquery = identifier.value
    

    子查询将返回

    (select blah from table_name) 别名

    然后我有一个单独的函数,它删除最外面的括号和别名,只给出子查询脚本:

    def subquery_parsing(subquery, full_tables, tables, alias):
        #print(subquery)
        #new subquery string ready to parse
        res_sub = """"""
    
        #captures the alias outside the parantheses
        alias = """"""
        
        #record the number of parentheses as they open and close
        paren_cnt = 0
    
    
        for char in subquery:
            #if ( and there's already been a ( , include it
            if char == '(' and paren_cnt > 0:
                res_sub += char
        
            #if (, add to the count
            if char == '(':
                paren_cnt += 1
       
            # if ) and there's at least 2 (, include it
            if char == ')' and paren_cnt > 1:
                res_sub += char
              
            # if ), subtract from the count        
            if char == ')':
                paren_cnt -= 1
        
            # capture the script
            if char != '(' and char != ')' and paren_cnt >0:
                res_sub += char
        
            # capture the alias
            if char != '(' and char != ')'  and char != ' ' and paren_cnt == 0:
                alias += char
    

    返回

    从表名中选择 blah

    然后您应该能够再次运行 sqlparse.parse 并获取表名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-16
      • 2023-02-25
      • 2016-06-08
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2019-06-29
      相关资源
      最近更新 更多