2015-04-12 58 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

你能解釋它是如何工作的嗎? –