-2
有沒有可以解析SQL查詢(PostgreSQL類)的任何庫(可以在Python中使用),並給我一個結構化的表示形式?有sqlparse,但這不允許我輕鬆地找出(說)查詢正在使用的表。我只需要支持SELECT
查詢,但其中一些可能非常複雜。將SQL解析成層級結果來分析它
有沒有可以解析SQL查詢(PostgreSQL類)的任何庫(可以在Python中使用),並給我一個結構化的表示形式?有sqlparse,但這不允許我輕鬆地找出(說)查詢正在使用的表。我只需要支持SELECT
查詢,但其中一些可能非常複雜。將SQL解析成層級結果來分析它
select_parser.py自帶pyparsing的示例將爲您提供語句的ParseResults數據結構。下面是嵌入式測試情況:
select * from xyzzy where z > 100
select * from xyzzy where z > 100 order by zz
select * from xyzzy
select z.* from xyzzy
select a, b from test_table where 1=1 and b='yes'
select a, b from test_table where 1=1 and b in (select bb from foo)
select z.a, b from test_table where 1=1 and b in (select bb from foo)
select z.a, b from test_table where 1=1 and b in (select bb from foo) order by b,c desc,d
select z.a, b from test_table left join test2_table where 1=1 and b in (select bb from foo)
select a, db.table.b as BBB from db.table where 1=1 and BBB='yes'
select a, db.table.b as BBB from test_table,db.table where 1=1 and BBB='yes'
select a, db.table.b as BBB from test_table,db.table where 1=1 and BBB='yes' limit 50
結果被構造成在輸入語句的不同組件,以及類似的對象屬性的命名的字段可以被訪問(result.table
:'XYZZY'
,result.where_expr
:['z', '>', '100']
等)。以下是前3個的測試結果:
select * from xyzzy where z > 100
['SELECT', ['*'], 'FROM', 'xyzzy', 'WHERE', ['z', '>', '100']]
- columns: ['*']
- from: ['xyzzy']
- table: ['xyzzy']
- where_expr: ['z', '>', '100']
select * from xyzzy where z > 100 order by zz
['SELECT', ['*'], 'FROM', 'xyzzy', 'WHERE', ['z', '>', '100'], 'ORDER', 'BY', [['zz']]]
- columns: ['*']
- from: ['xyzzy']
- order_by_terms: [['zz']]
[0]:
['zz']
- order_key: zz
- table: ['xyzzy']
- where_expr: ['z', '>', '100']
select * from xyzzy
['SELECT', ['*'], 'FROM', 'xyzzy']
- columns: ['*']
- from: ['xyzzy']
- table: ['xyzzy']
它被寫入到SQL方言SQLite的,但適應Postgres的不應該是太可怕了。
你能舉出你要求的例子嗎? –