我在过去几周学习PyParsing。我打算用它来从SQL语句中获取表名。 我看过http://pyparsing.wikispaces.com/file/view/simpleSQL.py。但我打算保持语法简单,因为我不是试图解析select语句的每一部分,而是在寻找表名。此外,它还涉及为Teradata等任何商业现代数据库定义完整语法。
#!/usr/bin/env python
from pyparsing import *
import sys
semicolon = Combine(Literal(';') + lineEnd)
comma = Literal(',')
lparen = Literal('(')
rparen = Literal(')')
# Keyword definition
update_kw, volatile_kw, create_kw, table_kw, as_kw, from_kw, \
where_kw, join_kw, left_kw, right_kw, cross_kw, outer_kw, \
on_kw , insert_kw , into_kw= \
map(lambda x: Keyword(x, caseless=True), \
['UPDATE', 'VOLATILE', 'CREATE', 'TABLE', 'AS', 'FROM',
'WHERE', 'JOIN' , 'LEFT', 'RIGHT' , \
'CROSS', 'OUTER', 'ON', 'INSERT', 'INTO'])
# Teradata SQL allows SELECT and well as SEL keyword
select_kw = Keyword('SELECT', caseless=True) | Keyword('SEL' , caseless=True)
# list of reserved keywords
reserved_words = (update_kw | volatile_kw | create_kw | table_kw | as_kw |
select_kw | from_kw | where_kw | join_kw |
left_kw | right_kw | cross_kw | on_kw | insert_kw |
into_kw)
# Identifier can be used as table or column names. They can't be reserved words
ident = ~reserved_words + Word(alphas, alphanums + '_')
# Recursive definition for table
table = Forward()
# simple table name can be identifer or qualified identifier e.g. schema.table
simple_table = Combine(Optional(ident + Literal('.')) + ident)
# table name can also a complete select statement used as table
nested_table = lparen.suppress() + select_kw.suppress() + SkipTo(from_kw).suppress() + \
from_kw.suppress() + table + rparen.suppress()
# table can be simple table or nested table
table << (nested_table | simple_table)
# comma delimited list of tables
table_list = delimitedList(table)
# Building from clause only because table name(s) will always appears after that
from_clause = from_kw.suppress() + table_list
txt = """
SELECT p, (SELECT * FROM foo),e FROM a, d, (SELECT * FROM z), b
"""
for token, start, end in from_clause.scanString(txt):
print token
这里值得一提的事。我使用“SkipTo(from_kw)”跳过SQL语句中的列列表。这主要是为了避免为列列表定义语法,列列表可以是逗号分隔的标识符列表,许多函数名称,DW分析函数等等。使用这个语法,我能够解析上面的语句以及SELECT列列表或表列表中的任何嵌套级别。
['foo']
['a', 'd', 'z', 'b']
当SELECT有where子句时,我遇到了问题:
nested_table = lparen.suppress() + select_kw.suppress() + SkipTo(from_kw).suppress() + \
from_kw.suppress() + table + rparen.suppress()
当有WHERE子句时,相同的语句可能如下所示: SELECT ... FROM a,d,(SELECT * FROM z WHERE(c1 = 1)and(c2 = 3)),p 我想把“nested_table”定义改为:
nested_table = lparen.suppress() + select_kw.suppress() + SkipTo(from_kw).suppress() + \
from_kw.suppress() + table + Optional(where_kw + SkipTo(rparen)) + rparen
但这不起作用,因为它匹配“c = 1”后的右括号。我想知道的是如何在“SELECT * FROM z ...”之前跳到符合左括号的右括号我不知道如何使用PyParsing
另外,在另一个注释中,我寻求一些建议,以获取从复杂嵌套SQL获取表名的最佳方法。任何帮助都非常感谢。
由于 作者Abhijit
答案 0 :(得分:5)
考虑到你也试图解析嵌套的SELECT,我不认为你能够避免编写一个相当完整的SQL解析器。幸运的是,在Pyparsing wiki示例页面select_parser.py上有一个更完整的示例。我希望能让你更进一步。