andialbrecht / sqlparse

A non-validating SQL parser module for Python
BSD 3-Clause "New" or "Revised" License
3.71k stars 693 forks source link

Column Extract Doesn't Work with Column Name of 'Range' and 'Section' #751

Open jtnguyen2020 opened 10 months ago

jtnguyen2020 commented 10 months ago

Describe the bug select_query = 'select locid, locname, drn, pipelineid, pipelineshortname, loctype, subtype, facilitytype, town, range, section, segmentmilepost, milemarker, segmentname, locpro, zone, dirflow, statuscode, state, county, unsubscribedcapacity, latitude, longitude, pbgroupcode, enableparkloan, updwnpartydrn, scadastationcode, updatedt, createon, getdate() ap_import_time from table1'

To Reproduce I ran the function below to get the columns but "range" and "section" didn't return as expected.

def find_selected_columns(select_query): tokens = sqlparse.parse(query)[0].tokens found_select = False for token in tokens: if found_select: if isinstance(token, sqlparse.sql.IdentifierList): return [ col.value.split(" ")[-1].strip("`").rpartition('.')[-1] for col in token.tokens if isinstance(col, sqlparse.sql.Identifier) ] else: found_select = token.match( sqlparse.tokens.Keyword.DML, ["select", "SELECT"]) raise Exception("Could not find a select statement. Weird query :)")

Expected behavior Columns "range" and "section" needs to be returned.

Versions (please complete the following information):