2013-01-24 13 views
9

Abbiamo bisogno di una libreria di analisi o decomposizione SQL per Python. Vorremmo essere in grado di inserire una query di testo SQL e quindi ottenere le parti della query come risultato. Non ha bisogno di essere fantasioso, o altro, ma noi vorremmo evitare di fare il parsing da soli. Idealmente, si potrebbe fare qualcosa di simile:Libreria SQL Parsing per Python

the_query = "select something from some_table where blah = 'thing' limit 15" 
query_parts = the_library.parse(the_query) 
print query_parts.limit().val() 

>>> '15' 

E anche questo:

the_query = "select something from some_table where blah = 'thing'" 
query_parts = the_library.parse(the_query) 
print query_parts.limit().val() 

>>> None 

Qualcuno può darci tutti gli indicatori di questo? Se la funzionalità è più limitata, va bene anche questo.

Grazie mille!

+2

http://stackoverflow.com/questions/1394998/parsing-sql-with-python e http : //navarra.ca/? p = 538 –

+2

In effetti, stavo per suggerire di usare il pyparsing, ma la domanda collegata sopra lo fa già. –

risposta

6

Come si potrebbe dare un'occhiata a sqlparse

Palesemente rubato dalla loro homepage:

>>> # Parsing 
>>> res = sqlparse.parse('select * from "someschema"."mytable" where id = 1') 
>>> res 
<<< (<Statement 'select...' at 0x9ad08ec>,) 
>>> stmt = res[0] 
>>> stmt.to_unicode() # converting it back to unicode 
<<< u'select * from "someschema"."mytable" where id = 1' 
>>> # This is how the internal representation looks like: 
>>> stmt.tokens 
<<< 
(<DML 'select' at 0x9b63c34>, 
<Whitespace ' ' at 0x9b63e8c>, 
<Operator '*' at 0x9b63e64>, 
<Whitespace ' ' at 0x9b63c5c>, 
<Keyword 'from' at 0x9b63c84>, 
<Whitespace ' ' at 0x9b63cd4>, 
<Identifier '"somes...' at 0x9b5c62c>, 
<Whitespace ' ' at 0x9b63f04>, 
<Where 'where ...' at 0x9b5caac>) 
>>> 
+1

Esattamente quello di cui avevamo bisogno. Grazie! –