2015-04-12 64 views
1

我有一个sqlite数据库,由不同的进程填充。该过程在db中生成表格并用数据填充它们。解析SQL查询文本以提取表使用的名称

我想对这个数据库应用一组预先写好的查询,但我需要确保查询中引用的所有表都在数据库中创建,然后再运行它以防止出现错误。我试图确定在SQL中引用表的所有可能方式,以确保覆盖所有选项。

简单:

select col1 from table1 

加入:

select col1,col2 from table1 join table2 on col1 = col2 
select col1,col2 from table1 left outer join table2 on col1 = col2 
select col1,col2 from table1, table2 on col1 = col2 
select col1,col2 from table1, table2 where col1 = col2 

子查询:

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 

我正在考虑使用RegEx来确定少数事件。

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

此RegEx似乎解释了大部分差异。表名称出现在组2或第3组:

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

http://regexr.com/3aq8j

我的问题:

  • 我有没有标识的所有的一个表的可能的方式来在查询中使用?
  • 我的表情还有其他误报吗?
  • 我无法从别名部分获取所有表名。帮帮我?
  • 有没有比RegEx更好的方法?

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

回答

1

您可以使用positive look-behind

(?<=from|join)\s+(\w+)(,\s*(\w+))?(?:(\s*\w+,\s*(\w+))+)? 

,你需要使用分组correctly.In你的格局已推杆fromjoin组内,因此结果将包含这些内容。

+0

你能解释它是如何工作的吗? –