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