解析SQL查询文本以提取使用的表名

2024-03-29 07:08:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个由不同进程填充的sqlite数据库。这个过程在数据库中生成表并用数据填充它们。在

我试图对这个数据库应用一组预先编写的查询,但是我需要确保查询中引用的所有表在运行之前都是在数据库中创建的,以防止出错。我正在尝试确定在SQL中引用表的所有可能方式,以确保涵盖所有选项。在

简单:

select col1 from table1

加入:

^{pr2}$

子查询:

select col1,(select col2 from table2 where col1 = col2) as ag2 from table1
select col1 from table1 where col1 in (select col2 from table2)

别名:

select col1,col2 from table1 t1, table2 t2 where col1 = col2
select col1,col2,col3 from table1 t1, table2 t2,table3 t3 where col1 = col2

我正在考虑使用正则表达式来识别少数事件。在

from [table] [alias]
join [table] [alias]
from [table] [alias], [table] [alias]

这个正则表达式似乎解释了大部分的差异。表名出现在group2或group3中:

(from|join)\s+([\w]+)|,\s*([\w]+)\s*([\w]\s*)?(on|where)

http://regexr.com/3aq8j

我的问题:

  • 我是否确定了在查询中使用表的所有可能方式?在
  • 我的表情还有其他误报吗?在
  • 我无法从alias部分获取所有表名。帮忙吗?在
  • 有没有比RegEx更好的方法?在

如果这会影响RegEx的格式,我将在Python代码中使用它。在


Tags: from数据库方式tablealiaswhereselectregex