2025-02-13 06:15:54 +01:00
|
|
|
from sqlglot import alias, exp
|
|
|
|
from sqlglot.errors import OptimizeError
|
|
|
|
from sqlglot.optimizer.scope import traverse_scope
|
2025-02-13 15:07:05 +01:00
|
|
|
from sqlglot.schema import ensure_schema
|
2025-02-13 06:15:54 +01:00
|
|
|
|
|
|
|
|
2025-02-13 15:07:05 +01:00
|
|
|
def isolate_table_selects(expression, schema=None):
|
|
|
|
schema = ensure_schema(schema)
|
|
|
|
|
2025-02-13 06:15:54 +01:00
|
|
|
for scope in traverse_scope(expression):
|
|
|
|
if len(scope.selected_sources) == 1:
|
|
|
|
continue
|
|
|
|
|
2025-02-13 15:08:15 +01:00
|
|
|
for _, source in scope.selected_sources.values():
|
2025-02-13 15:07:05 +01:00
|
|
|
if not isinstance(source, exp.Table) or not schema.column_names(source):
|
2025-02-13 06:15:54 +01:00
|
|
|
continue
|
|
|
|
|
2025-02-13 14:48:46 +01:00
|
|
|
if not source.alias:
|
2025-02-13 08:04:41 +01:00
|
|
|
raise OptimizeError("Tables require an alias. Run qualify_tables optimization.")
|
2025-02-13 06:15:54 +01:00
|
|
|
|
2025-02-13 14:48:46 +01:00
|
|
|
source.replace(
|
2025-02-13 06:15:54 +01:00
|
|
|
exp.select("*")
|
|
|
|
.from_(
|
2025-02-13 14:48:46 +01:00
|
|
|
alias(source.copy(), source.name or source.alias, table=True),
|
2025-02-13 06:15:54 +01:00
|
|
|
copy=False,
|
|
|
|
)
|
2025-02-13 14:48:46 +01:00
|
|
|
.subquery(source.alias, copy=False)
|
2025-02-13 06:15:54 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
return expression
|