Roc*_*etq 16 python regex sql sqlite parsing
所以假设我们有这样一个简单的查询:
Select a.col1, b.col2 from tb1 as a inner join tb2 as b on tb1.col7 = tb2.col8;
Run Code Online (Sandbox Code Playgroud)
结果应该是这样的:
tb1 col1
tb1 col7
tb2 col2
tb2 col8
Run Code Online (Sandbox Code Playgroud)
我尝试使用一些 python 库来解决这个问题:
1) 即使只使用提取表sqlparse也可能是一个大问题。例如,这本官方书籍根本无法正常工作。
2)使用正则表达式似乎真的很难实现。
3)但后来我发现了这个,这可能会有所帮助。但是问题是我无法连接到任何数据库并执行该查询。
有任何想法吗?
Dyl*_*ogg 27
sql-metadata是一个 Python 库,它使用由python-sqlparse返回的标记化查询并生成查询元数据。
此元数据可以从您提供的 SQL 查询中返回列名和表名。以下是sql-metadata github 自述文件中的几个示例:
>>> sql_metadata.get_query_columns("SELECT test, id FROM foo, bar")
[u'test', u'id']
>>> sql_metadata.get_query_tables("SELECT test, id FROM foo, bar")
[u'foo', u'bar']
>>> sql_metadata.get_query_limit_and_offset('SELECT foo_limit FROM bar_offset LIMIT 50 OFFSET 1000')
(50, 1000)
Run Code Online (Sandbox Code Playgroud)
moz-sql-parser是一个 Python 库,用于将 SQL-92 查询的某些子集转换为可 JSON 的解析树。也许这就是你想要的。
这是一个例子。
>>> parse("SELECT id,name FROM dual WHERE id>3 and id<10 ORDER BY name")
{'select': [{'value': 'id'}, {'value': 'name'}], 'from': 'dual', 'where': {'and': [{'gt': ['id', 3]}, {'lt': ['id', 10]}]}, 'orderby': {'value': 'name'}}
Run Code Online (Sandbox Code Playgroud)
真的,这不是一件容易的事。您可以使用词法分析器(在本例中为ply)并定义多个规则以从字符串中获取多个标记。以下代码为 SQL 字符串的不同部分定义了这些规则,并将它们重新组合在一起,因为输入字符串中可能存在别名。结果,您将获得一个result以不同表名作为键的字典 ( )。
import ply.lex as lex, re
tokens = (
"TABLE",
"JOIN",
"COLUMN",
"TRASH"
)
tables = {"tables": {}, "alias": {}}
columns = []
t_TRASH = r"Select|on|=|;|\s+|,|\t|\r"
def t_TABLE(t):
r"from\s(\w+)\sas\s(\w+)"
regex = re.compile(t_TABLE.__doc__)
m = regex.search(t.value)
if m is not None:
tbl = m.group(1)
alias = m.group(2)
tables["tables"][tbl] = ""
tables["alias"][alias] = tbl
return t
def t_JOIN(t):
r"inner\s+join\s+(\w+)\s+as\s+(\w+)"
regex = re.compile(t_JOIN.__doc__)
m = regex.search(t.value)
if m is not None:
tbl = m.group(1)
alias = m.group(2)
tables["tables"][tbl] = ""
tables["alias"][alias] = tbl
return t
def t_COLUMN(t):
r"(\w+\.\w+)"
regex = re.compile(t_COLUMN.__doc__)
m = regex.search(t.value)
if m is not None:
t.value = m.group(1)
columns.append(t.value)
return t
def t_error(t):
raise TypeError("Unknown text '%s'" % (t.value,))
t.lexer.skip(len(t.value))
# here is where the magic starts
def mylex(inp):
lexer = lex.lex()
lexer.input(inp)
for token in lexer:
pass
result = {}
for col in columns:
tbl, c = col.split('.')
if tbl in tables["alias"].keys():
key = tables["alias"][tbl]
else:
key = tbl
if key in result:
result[key].append(c)
else:
result[key] = list()
result[key].append(c)
print result
# {'tb1': ['col1', 'col7'], 'tb2': ['col2', 'col8']}
string = "Select a.col1, b.col2 from tb1 as a inner join tb2 as b on tb1.col7 = tb2.col8;"
mylex(string)
Run Code Online (Sandbox Code Playgroud)
我正在解决一个类似的问题,并找到了一个更简单的解决方案,它似乎运行良好。
import re
def tables_in_query(sql_str):
# remove the /* */ comments
q = re.sub(r"/\*[^*]*\*+(?:[^*/][^*]*\*+)*/", "", sql_str)
# remove whole line -- and # comments
lines = [line for line in q.splitlines() if not re.match("^\s*(--|#)", line)]
# remove trailing -- and # comments
q = " ".join([re.split("--|#", line)[0] for line in lines])
# split on blanks, parens and semicolons
tokens = re.split(r"[\s)(;]+", q)
# scan the tokens. if we see a FROM or JOIN, we set the get_next
# flag, and grab the next one (unless it's SELECT).
tables = set()
get_next = False
for tok in tokens:
if get_next:
if tok.lower() not in ["", "select"]:
tables.add(tok)
get_next = False
get_next = tok.lower() in ["from", "join"]
dictTables = dict()
for table in tables:
fields = []
for token in tokens:
if token.startswith(table):
if token != table:
fields.append(token)
if len(list(set(fields))) >= 1:
dictTables[table] = list(set(fields))
return dictTables
Run Code Online (Sandbox Code Playgroud)
代码改编自https://grisha.org/blog/2016/11/14/table-names-from-sql/