MCPcopy Create free account
hub / github.com/dbcli/mssql-cli / extract_tables

Function extract_tables

mssqlcli/packages/parseutils/tables.py:121–146  ·  view source on GitHub ↗

Extract the table names from an SQL statment. Returns a list of TableReference namedtuples

(sql)

Source from the content-addressed store, hash-verified

119
120# extract_tables is inspired from examples in the sqlparse lib.
121def extract_tables(sql):
122 """Extract the table names from an SQL statment.
123
124 Returns a list of TableReference namedtuples
125
126 """
127 parsed = sqlparse.parse(sql)
128 if not parsed:
129 return ()
130
131 # INSERT statements must stop looking for tables at the sign of first
132 # Punctuation. eg: INSERT INTO abc (col1, col2) VALUES (1, 2)
133 # abc is the table name, but if we don't stop at the first lparen, then
134 # we'll identify abc, col1 and col2 as table names.
135 insert_stmt = parsed[0].token_first().value.lower() == 'insert'
136 stream = extract_from_part(parsed[0], stop_at_punctuation=insert_stmt)
137
138 # Kludge: sqlparse mistakenly identifies insert statements as
139 # function calls due to the parenthesized column list, e.g. interprets
140 # "insert into foo (bar, baz)" as a function call to foo with arguments
141 # (bar, baz). So don't allow any identifiers in insert statements
142 # to have is_function=True
143 identifiers = extract_table_identifiers(stream,
144 allow_functions=not insert_stmt)
145 # In the case 'sche.<cursor>', we get an empty TableReference; remove that
146 return tuple(i for i in identifiers if i.name)

Calls 2

extract_from_partFunction · 0.85