Extract the table names from an SQL statement. Returns a list of (schema, table, alias) tuples
(sql: str)
| 200 | |
| 201 | # extract_tables is inspired from examples in the sqlparse lib. |
| 202 | def extract_tables(sql: str) -> list[tuple[str | None, str, str]]: |
| 203 | """Extract the table names from an SQL statement. |
| 204 | |
| 205 | Returns a list of (schema, table, alias) tuples |
| 206 | |
| 207 | """ |
| 208 | parsed = sqlparse.parse(sql) |
| 209 | if not parsed: |
| 210 | return [] |
| 211 | |
| 212 | # INSERT statements must stop looking for tables at the sign of first |
| 213 | # Punctuation. eg: INSERT INTO abc (col1, col2) VALUES (1, 2) |
| 214 | # abc is the table name, but if we don't stop at the first lparen, then |
| 215 | # we'll identify abc, col1 and col2 as table names. |
| 216 | insert_stmt = parsed[0].token_first().value.lower() == "insert" |
| 217 | stream = extract_from_part(parsed[0], stop_at_punctuation=insert_stmt) |
| 218 | return list(extract_table_identifiers(stream)) |
| 219 | |
| 220 | |
| 221 | def extract_columns_from_select(sql: str) -> list[str]: |