Skip to content

Commit a3623b4

Browse files
committed
feat: add find_tables backport
1 parent 2f40fc5 commit a3623b4

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

sqlglot/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
condition as condition,
3030
delete as delete,
3131
except_ as except_,
32+
find_tables as find_tables,
3233
from_ as from_,
3334
func as func,
3435
insert as insert,

sqlglot/expressions.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8624,6 +8624,26 @@ def replace_tree(
86248624
return new_node
86258625

86268626

8627+
def find_tables(expression: Expression) -> t.Set[Table]:
8628+
"""
8629+
Find all tables referenced in a query.
8630+
8631+
Args:
8632+
expressions: The query to find the tables in.
8633+
8634+
Returns:
8635+
A set of all the tables.
8636+
"""
8637+
from sqlglot.optimizer.scope import traverse_scope
8638+
8639+
return {
8640+
table
8641+
for scope in traverse_scope(expression)
8642+
for table in scope.tables
8643+
if table.name and table.name not in scope.cte_sources
8644+
}
8645+
8646+
86278647
def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
86288648
"""
86298649
Return all table names referenced through columns in an expression.

0 commit comments

Comments
 (0)