使用python从现有SQL查询中提取数据库模式



给定一个SQL查询,我如何以编程方式提取关于它正在查询的数据库的模式信息?理想情况下,我想使用Python来解析和提取信息。

例如,如下SQL:

SELECT
rc.dateCooked,
r.name,
i.ingredient
FROM recipeCooked rc
INNER JOIN recipe r ON r.recipeID = rc.recipeID
LEFT OUTER JOIN recipeIngredient ri ON ri.recipeID = r.recipeID
LEFT OUTER JOIN ingredient i ON i.ingredientID = ri.ingredientID;

将导致以下一组关系(显示为csv):

table1, key1, table2, key2, join_type
recipeCooked, recipeID, recipe, recipeID, INNER
recipe, recipeID, recipeIngredient, recipeID, LEFT OUTER
recipeIngredient, ingredientID, ingredient, ingredientID, LEFT OUTER

我正在寻找任何可能帮助我解决这个挑战的东西,包括代码片段,可能有用的工具推荐,值得谷歌搜索的概念,推荐的方法,或者只是其他人面临同样挑战的报告。

Python sqlparse库似乎是一个非常有用的工具,但它只给了我一部分的方法。

的背景:我定期查询一个包含20K个表的医疗保健关系数据库。它没有很好的文档记录,我获得有关它的信息的主要方式是查看其他数据分析师的SQL代码。现在我做了很多手工检查SQL代码和绘制数据库模式图的工作,但这可能很慢而且很乏味。我想让它自动化!

您可以使用我的库SQLGlot来解析SQL并提取信息。

这是一段代码片段,应该可以帮助你开始。

import sqlglot
import sqlglot.expressions as exp
sql = """
SELECT
rc.dateCooked,
r.name,
i.ingredient
FROM recipeCooked rc
INNER JOIN recipe r ON r.recipeID = rc.recipeID
LEFT OUTER JOIN recipeIngredient ri ON ri.recipeID = r.recipeID
LEFT OUTER JOIN ingredient i ON i.ingredientID = ri.ingredientID;
"""
node = sqlglot.parse_one(sql)
for join in node.args["joins"]:
table = join.find(exp.Table).text("this")
print(table)
print(join.args["on"])
print(join.args["kind"])

最新更新