python determine the type of sql query

Viewed 45

I have a file with N>=1 SQL queries, in Oracle dialect.

I parse those queries by means of

with open(input_file_path, 'r') as file:
    raw     =   file.read()
    queries =   sqlparse.split(raw)

I have to determine if each sql is a SELECT, UPDATE, DELETE, MERGE, ALTER, etc, ahead of time, with no executing the query without known its type.

The number of libs I can use is limited, so ideally, I'd like to be able to use sqlalchemy and/or sqlparse.

Using sqlparse to get first token, such as in

spam   = 'SELECT * FROM Noexiste'
parsed = sqlparse.parse(spam)[0]
print(parsed.tokens)

is not a solution, cause a query using WITH statements might be inputted.

Any help would be much appreciated!

1 Answers

It seems there's a great, undocumented method in sqlparse:

query               =   'SELECT * FROM DUAL'
current_query_type  =   sqlparse.parse(query)[0].get_type()
#SELECT, DELETE, UPDATE, MERGE, ALTER, etc
Related