sqlglot.optimizer.isolate_table_selects
1from sqlglot import alias, exp 2from sqlglot.errors import OptimizeError 3from sqlglot.optimizer.scope import traverse_scope 4from sqlglot.schema import ensure_schema 5 6 7def isolate_table_selects(expression, schema=None): 8 schema = ensure_schema(schema) 9 10 for scope in traverse_scope(expression): 11 if len(scope.selected_sources) == 1: 12 continue 13 14 for _, source in scope.selected_sources.values(): 15 if ( 16 not isinstance(source, exp.Table) 17 or not schema.column_names(source) 18 or isinstance(source.parent, exp.Subquery) 19 or isinstance(source.parent.parent, exp.Table) 20 ): 21 continue 22 23 if not source.alias: 24 raise OptimizeError("Tables require an alias. Run qualify_tables optimization.") 25 26 source.replace( 27 exp.select("*") 28 .from_( 29 alias(source, source.alias_or_name, table=True), 30 copy=False, 31 ) 32 .subquery(source.alias, copy=False) 33 ) 34 35 return expression
def
isolate_table_selects(expression, schema=None):
8def isolate_table_selects(expression, schema=None): 9 schema = ensure_schema(schema) 10 11 for scope in traverse_scope(expression): 12 if len(scope.selected_sources) == 1: 13 continue 14 15 for _, source in scope.selected_sources.values(): 16 if ( 17 not isinstance(source, exp.Table) 18 or not schema.column_names(source) 19 or isinstance(source.parent, exp.Subquery) 20 or isinstance(source.parent.parent, exp.Table) 21 ): 22 continue 23 24 if not source.alias: 25 raise OptimizeError("Tables require an alias. Run qualify_tables optimization.") 26 27 source.replace( 28 exp.select("*") 29 .from_( 30 alias(source, source.alias_or_name, table=True), 31 copy=False, 32 ) 33 .subquery(source.alias, copy=False) 34 ) 35 36 return expression