import sqlparse
import re
sql = 'insert into table inser_tbl partition (dt = dt) select 1 as id, name, case when (name = "" or name = "") then 3 else 4 end as score from tbl where id > 10 limit 100'
stmts = sqlparse.parse(sql)[0].tokens
cols = []
tbls = []
froms = []
wheres = []
last_key = ''
for stmt in stmts:
if stmt.value == 'insert' or stmt.value == 'select' or stmt.value == 'from':
last_key = stmt.value
if stmt.ttype is sqlparse.tokens.Text.Whitespace:
continue
elif stmt.ttype is sqlparse.tokens.Keyword.DML:
dml = stmt.value
last_key = dml
elif isinstance(stmt, sqlparse.sql.IdentifierList):
if last_key == 'select':
for identifier in stmt.get_identifiers():
col_name = identifier.value
if re.search('as', col_name, re.I):
col_name = re.search('as (.*)', col_name, re.I).group(1).strip()
cols.append(col_name)
elif last_key == 'from':
for identifier in stmt.get_identifiers():
froms.append(identifier.value)
else:
for identifier in stmt.get_identifiers():
tbls.append(identifier.value)
elif isinstance(stmt, sqlparse.sql.Identifier):
if last_key == 'select':
cols.append(stmt.value)
elif last_key == 'from':
froms.append(stmt.value)
else:
tbls.append(stmt.value)
elif isinstance(stmt, sqlparse.sql.Where):
wheres.append(stmt.value)
print("cols:", cols)
print("tbls:", tbls)
print("froms:", froms)
print("wheres:", wheres)