bobzhang/sqlglot/optimizer does not have a README file

    BinaryCoercion

    A binary coercion function: takes both sides and returns the resulting type.

    ExprMetadata

    Maps an expression kind to its type inference rule.

    Journal

    One recorded argument mutation: (node, arg_key, value before the mutation).

    ArgRef

    pub(all) enum ArgRef {
    Key(String)
    Node(
    Expr
    )
    }

    An argument reference for annotate_by_args: an arg key, or an expression.

    CopyBudget

    pub struct CopyBudget {
    expression :
    Expr

    max_copy_factor : Int?
    min_copy_budget : Int
    remaining : Int?
    }

    Caps the number of nodes copied by merges (relative to the statement size).

    CopyBudget::consume

    fn CopyBudget::consume(self : CopyBudget, outer_scope : Scope, inner_scope : Scope, alias : String) -> Bool

    Charges the copies needed to merge inner_scope into outer_scope, if they fit.

    CopyBudget::new

    fn CopyBudget::new(expression :
    Expr
    , max_copy_factor? : Int?, min_copy_budget? : Int) -> CopyBudget

    MappingSchema

    pub struct MappingSchema {
    mapping : Map[String, SchemaNode]
    udf_mapping : Map[String, SchemaNode]
    visible : Map[String, SchemaNode]
    normalize : Bool
    dialect :
    Dialect

    // private fields
    }

    Schema based on a nested mapping (Python MappingSchema).

    MappingSchema::add_table

    fn MappingSchema::add_table(self : MappingSchema, table :
    Expr
    , column_mapping? : Map[String, SchemaNode], dialect? :
    Dialect
    , normalize? : Bool, match_depth? : Bool) -> Unit raise
    SqlglotError

    Register or update a table.

    MappingSchema::add_table_str

    fn MappingSchema::add_table_str(self : MappingSchema, table : String, columns? : Array[String], column_types? : Map[String, SchemaNode], dialect? :
    Dialect
    , normalize? : Bool, match_depth? : Bool) -> Unit raise
    SqlglotError

    Adds a table given by name (parsed with the schema's dialect), with a list of columns.

    MappingSchema::column_names

    fn MappingSchema::column_names(self : MappingSchema, table :
    Expr
    , only_visible? : Bool, dialect? :
    Dialect
    , normalize? : Bool) -> Array[String] raise
    SqlglotError

    Get the column names for a table.

    MappingSchema::copy

    Returns a copy of this schema, optionally with a new mapping.

    MappingSchema::depth

    fn MappingSchema::depth(self : MappingSchema) -> Int

    MappingSchema::empty

    fn MappingSchema::empty(self : MappingSchema) -> Bool

    Whether the schema is empty.

    MappingSchema::find

    Returns the column mapping of a given table.

    MappingSchema::find_cache_size

    fn MappingSchema::find_cache_size(self : MappingSchema) -> Int

    The number of entries of the find cache (Python len(schema._find_cache)).

    MappingSchema::find_column_types

    find(table, raise_on_missing=False, ensure_data_types=True): the column types of a table (string types are converted to DataTypes).

    MappingSchema::get_column_type

    Get the DataType of a column in the schema.

    MappingSchema::get_column_type_str

    Get the DataType of a column given by name.

    MappingSchema::get_udf_type

    Get the return type of a UDF, or UNKNOWN if not found.

    MappingSchema::get_udf_type_str

    Get the return type of a UDF given as a string, e.g. "db.my_func(x)", or UNKNOWN if not found.

    MappingSchema::has_column

    Returns whether column appears in table's schema.

    MappingSchema::new

    fn MappingSchema::new(schema? : Map[String, SchemaNode], visible? : Map[String, SchemaNode], dialect? :
    Dialect
    , normalize? : Bool, udf_mapping? : Map[String, SchemaNode]) -> MappingSchema raise
    SqlglotError

    Creates a mapping schema.

    schema is a mapping in one of the forms {table: {col: type}}, {db: {table: {col: type}}} or {catalog: {db: {table: {col: type}}}}.

    MappingSchema::normalize_table

    Normalizes a table (parsing it if it's a string).

    MappingSchema::supported_table_args

    fn MappingSchema::supported_table_args(self : MappingSchema) -> Array[String] raise
    SqlglotError

    Table arguments this schema supports, e.g. ["this", "db", "catalog"].

    OptimizeOptions

    pub struct OptimizeOptions {
    schema : MappingSchema
    db : String?
    catalog : String?
    dialect :
    Dialect

    sql : String?
    isolate_tables : Bool
    quote_identifiers : Bool
    infer_schema : Bool?
    identify : Bool
    leave_tables_isolated : Bool
    validate_qualify_columns : Bool
    canonicalize_table_aliases : Bool
    expand_alias_refs : Bool
    expand_stars : Bool
    allow_partial_qualification : Bool
    on_qualify : (
    Expr
    ) -> Unit?
    constant_propagation : Bool
    coalesce_simplification : Bool
    }

    The keyword arguments optimize passes to its rules (Python's possible_kwargs).

    ProjectionReachability

    pub struct ProjectionReachability {
    scopes : Array[Scope]
    live : Map[Int, Int64]
    selections : Map[Int, Array[Int64]]
    is_agg : Map[Int, Bool]
    group_by_ordinals : Map[Int, Array[(
    Expr
    ,
    Expr
    )]]
    set_names : Map[Int, Array[String]]
    }

    Which root outputs reach each scope and output column through dependency edges.

    Resolver

    pub struct Resolver {
    scope : Scope
    schema : MappingSchema
    dialect :
    Dialect

    // private fields
    }

    Helper for resolving columns.

    Resolver::all_columns

    All available columns of all sources in this scope.

    Resolver::get_source_columns

    fn Resolver::get_source_columns(self : Resolver, name : String, only_visible? : Bool) -> Array[String] raise
    SqlglotError

    Resolve the source columns for a given source name.

    Resolver::get_source_columns_from_set_op

    fn Resolver::get_source_columns_from_set_op(self : Resolver, expression :
    Expr
    ) -> Array[String] raise
    SqlglotError

    Resolver::get_table

    Get the table for a column.

    Resolver::get_table_by_name

    fn Resolver::get_table_by_name(self : Resolver, column_name : String) ->
    Expr
    ? raise
    SqlglotError

    Get the table for a column name.

    Resolver::has_unknown_sources

    fn Resolver::has_unknown_sources(self : Resolver) -> Bool raise
    SqlglotError

    Whether some source's columns can't be determined.

    Resolver::new

    fn Resolver::new(scope : Scope, schema : MappingSchema, infer_schema? : Bool) -> Resolver

    Resolver::outer_resolvers

    fn Resolver::outer_resolvers(self : Resolver) -> Array[Resolver]

    Resolvers for the outer scopes a correlated subquery can reference, innermost first.

    Rule

    pub(all) enum Rule {
    Qualify
    QualifyTables
    QualifyColumns
    IsolateTableSelects
    PushdownProjections
    Normalize
    UnnestSubqueries
    PushdownPredicates
    OptimizeJoins
    EliminateSubqueries
    MergeSubqueries
    EliminateJoins
    EliminateCtes
    QuoteIdentifiers
    AnnotateTypes
    Canonicalize
    Simplify
    CanonicalizeInternalNames
    Custom((
    Expr
    , OptimizeOptions) ->
    Expr
    raise
    SqlglotError
    )
    }

    An optimizer rule.

    Rule::apply

    Applies a single rule with the given options.

    SchemaNode

    pub(all) enum SchemaNode {
    Dict(Map[String, SchemaNode])
    Type(String)
    DataType(
    Expr
    )
    Null
    Names(Array[String])
    }

    A node of a nested schema mapping (Python's nested dicts of the schema).

    SchemaNode::from_json

    Builds a schema mapping from JSON: objects become Dicts, strings become Types, null becomes Null and arrays of strings become Names. {"__nonnull__": "INT"} builds a non-nullable DataType.

    Scope

    pub struct Scope {
    id : Int
    expression :
    Expr

    sources : Map[String, Source]
    lateral_sources : Map[String, Source]
    cte_sources : Map[String, Source]
    outer_columns : Array[String]
    parent : Scope?
    scope_type : ScopeType
    subquery_scopes : Array[Scope]
    derived_table_scopes : Array[Scope]
    table_scopes : Array[Scope]
    cte_scopes : Array[Scope]
    set_operation_scopes : Array[Scope]
    udtf_scopes : Array[Scope]
    can_be_correlated : Bool
    // private fields
    }

    Selection scope.

    Scope::add_source

    fn Scope::add_source(self : Scope, name : String, source : Source) -> Unit

    Scope::branch

    fn Scope::branch(self : Scope, expression :
    Expr
    , scope_type : ScopeType, sources? : Map[String, Source], cte_sources? : Map[String, Source], lateral_sources? : Map[String, Source], outer_columns? : Array[String]) -> Scope

    Branch from the current scope to a new, inner scope.

    Scope::clear_cache

    fn Scope::clear_cache(self : Scope) -> Unit

    Scope::clear_column_cache

    fn Scope::clear_column_cache(self : Scope) -> Unit

    Invalidate the column-classification caches after columns are qualified in place.

    Scope::column_index

    fn Scope::column_index(self : Scope) ->
    Set
    [Int]

    Scope::columns

    List of columns in this scope, plus columns of correlated subqueries referencing it.

    Scope::ctes

    Scope::derived_tables

    fn Scope::derived_tables(self : Scope) -> Array[
    Expr
    ]

    Scope::external_columns

    fn Scope::external_columns(self : Scope) -> Array[
    Expr
    ]

    Columns that appear to reference sources in outer scopes.

    Scope::is_correlated_subquery

    fn Scope::is_correlated_subquery(self : Scope) -> Bool

    Scope::is_cte

    fn Scope::is_cte(self : Scope) -> Bool

    Scope::is_derived_table

    fn Scope::is_derived_table(self : Scope) -> Bool

    Scope::is_root

    fn Scope::is_root(self : Scope) -> Bool

    Scope::is_set_operation

    fn Scope::is_set_operation(self : Scope) -> Bool

    Scope::is_subquery

    fn Scope::is_subquery(self : Scope) -> Bool

    Scope::is_udtf

    fn Scope::is_udtf(self : Scope) -> Bool

    Scope::join_hints

    Scope::key

    fn Scope::key(self : Scope) -> Int

    Identity key of a scope as a source (Source::key of ScopeSource(scope)).

    Scope::local_columns

    fn Scope::local_columns(self : Scope) -> Array[
    Expr
    ]

    Columns in this scope that are not external.

    Scope::new

    fn Scope::new(expression :
    Expr
    , sources? : Map[String, Source], outer_columns? : Array[String], parent? : Scope, scope_type? : ScopeType, lateral_sources? : Map[String, Source], cte_sources? : Map[String, Source], can_be_correlated? : Bool) -> Scope

    Scope::pivots

    Scope::ref_count

    fn Scope::ref_count(self : Scope) -> Map[Int, Int]

    Count the number of times each source in this tree is referenced (keyed by Source::key).

    Scope::references

    fn Scope::references(self : Scope) -> Array[(String,
    Expr
    )]

    Scope::remove_source

    fn Scope::remove_source(self : Scope, name : String) -> Unit

    Scope::rename_source

    fn Scope::rename_source(self : Scope, old_name : String?, new_name : String) -> Unit

    Rename a source in this scope.

    Scope::replace

    Replace old with new, keeping the scope up to date.

    Scope::scans_all_subscope_columns

    fn Scope::scans_all_subscope_columns(self : Scope) -> Bool

    Scope::selected_sources

    Mapping of nodes and sources that are actually selected from in this scope.

    Scope::selected_sources_or_empty

    fn Scope::selected_sources_or_empty(self : Scope) -> Map[String, (
    Expr
    , Source)]

    selected_sources for callers that know it cannot fail (it was computed before).

    Scope::semi_or_anti_join_tables

    fn Scope::semi_or_anti_join_tables(self : Scope) ->
    Set
    [String]

    Scope::source_columns

    fn Scope::source_columns(self : Scope, source_name : String) -> Array[
    Expr
    ]

    Scope::stars

    Scope::subqueries

    Scope::table_columns

    fn Scope::table_columns(self : Scope) -> Array[
    Expr
    ]

    Scope::tables

    Scope::traverse

    fn Scope::traverse(self : Scope) -> Array[Scope]

    Traverse the scope tree from this node, in DFS post-order.

    Scope::udtfs

    Scope::unqualified_columns

    fn Scope::unqualified_columns(self : Scope) -> Array[
    Expr
    ]

    Scope::walk

    ScopeType

    pub(all) enum ScopeType {
    Root
    SubqueryScope
    DerivedTableScope
    CteScope
    SetOperationScope
    UdtfScope
    } derive(Eq,
    Debug
    )

    Simplifier

    pub struct Simplifier {
    dialect :
    Dialect

    annotate_new_expressions : Bool
    annotator : TypeAnnotator
    }

    Simplifier::absorb_and_eliminate

    Absorption and elimination.

    Simplifier::new

    fn Simplifier::new(dialect? :
    Dialect
    , annotate_new_expressions? : Bool) -> Simplifier

    Simplifier::remove_complements

    Removing complements: A AND NOT A -> FALSE (only for non-NULL A).

    Simplifier::rewrite_between

    Rewrite x between y and z to x >= y AND x <= z.

    Simplifier::simplify

    fn Simplifier::simplify(self : Simplifier, expression :
    Expr
    , constant_propagation? : Bool, coalesce_simplification? : Bool) ->
    Expr
    raise
    SqlglotError

    Simplifier::simplify_concat

    Reduces all groups that contain string literals by concatenating them.

    Simplifier::simplify_conditionals

    Simplifies expressions like IF, CASE if their condition is statically known.

    Simplifier::simplify_connectors

    Simplifier::simplify_datetrunc

    Simplify expressions like DATE_TRUNC('year', x) >= CAST('2021-01-01' AS DATE).

    Simplifier::simplify_equality

    Use the subtraction and addition properties of equality to simplify expressions.

    Simplifier::simplify_literals

    Simplifier::simplify_not

    Demorgan's Law.

    Simplifier::simplify_startswith

    Reduces a prefix check to TRUE or FALSE if both arguments are statically known.

    Simplifier::uniq_sort

    Uniq and sort a connector: C AND A AND B AND B -> A AND B AND C.

    Source

    pub enum Source {
    TableSource(
    Expr
    )
    ScopeSource(Scope)
    }

    A source of a scope: either a table or another scope.

    Source::as_scope

    fn Source::as_scope(self : Source) -> Scope?

    Source::as_table

    Source::expression

    fn Source::expression(self : Source) ->
    Expr
    ?

    source.expression (Python attribute access on either a Table or a Scope).

    Source::is_same

    fn Source::is_same(self : Source, other : Source) -> Bool

    Source::key

    fn Source::key(self : Source) -> Int

    Identity key of a source (Python id(source)).

    TType

    A type value: either a bare DType or a DataType expression (Python's exp.DataType | exp.DType).

    TypeAnnotator

    Infers the types of expressions.

    TypeAnnotator::annotate

    TypeAnnotator::annotate_binary

    TypeAnnotator::annotate_bracket

    fn TypeAnnotator::annotate_bracket(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_by_args

    fn TypeAnnotator::annotate_by_args(self : TypeAnnotator, expression :
    Expr
    , args : Array[ArgRef], promote? : Bool, array? : Bool) -> Unit

    TypeAnnotator::annotate_by_array_element

    fn TypeAnnotator::annotate_by_array_element(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_div

    fn TypeAnnotator::annotate_div(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_dot

    fn TypeAnnotator::annotate_dot(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_explode

    fn TypeAnnotator::annotate_explode(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_extract

    fn TypeAnnotator::annotate_extract(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_literal

    fn TypeAnnotator::annotate_literal(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_map

    fn TypeAnnotator::annotate_map(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_scope

    fn TypeAnnotator::annotate_scope(self : TypeAnnotator, scope : Scope) -> Unit raise
    SqlglotError

    TypeAnnotator::annotate_struct

    fn TypeAnnotator::annotate_struct(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_subquery

    fn TypeAnnotator::annotate_subquery(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_timeunit

    fn TypeAnnotator::annotate_timeunit(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_to_map

    fn TypeAnnotator::annotate_to_map(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_unary

    fn TypeAnnotator::annotate_unary(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_unnest

    fn TypeAnnotator::annotate_unnest(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::annotate_within_group

    fn TypeAnnotator::annotate_within_group(self : TypeAnnotator, expression :
    Expr
    ) -> Unit

    TypeAnnotator::clear

    fn TypeAnnotator::clear(self : TypeAnnotator) -> Unit

    TypeAnnotator::maybe_coerce

    fn TypeAnnotator::maybe_coerce(self : TypeAnnotator, type1 : TType, type2 : TType) -> TType

    Returns type2 if type1 can be coerced into it, otherwise type1.

    TypeAnnotator::set_dtype

    Sets the type of expression to a DType.

    TypeAnnotator::set_type

    fn TypeAnnotator::set_type(self : TypeAnnotator, expression :
    Expr
    , target_type : TType?) -> Unit

    Sets the type of expression (Python _set_type).

    TypeAnnotator::set_type_expr

    Sets the type of expression to a type expression (or UNKNOWN when None).

    TypeAnnotator::uncache

    fn TypeAnnotator::uncache(self : TypeAnnotator, expression :
    Expr
    , deep? : Bool) -> Unit

    Evicts expression (or its subtree, if deep) from the annotation caches.

    TypeSpec

    pub(all) enum TypeSpec {
    Returns(TType)
    Annotator((TypeAnnotator,
    Expr
    ) -> Unit raise
    SqlglotError
    )
    }

    An entry of the expression metadata (Python {"returns": ...} / {"annotator": ...}).

    annotate_types

    Infers the types of an expression, annotating its AST accordingly.

    base_expression_metadata

    let base_expression_metadata : Map[
    Kind
    , TypeSpec]

    The base dialect's expression metadata (Python sqlglot.typing.EXPRESSION_METADATA).

    build_scope

    Build a scope tree, returning the root scope.

    canonicalize

    Converts a sql expression into a standard form.

    canonicalize_internal_names

    Rewrite a query to a canonical structural form, renaming internal names (table aliases, CTE/subquery names, internal column aliases) to _tN / _cN.

    column_type_trace_calls

    let column_type_trace_calls :
    Ref
    [Int]

    The number of calls of Resolver::get_column_type_from_scope (Python Resolver._get_column_type_from_scope) so far; tests use it to check that the trace is memoized (Python's test patches the method to count its calls).

    default_binary_coercions

    TypeAnnotator.BINARY_COERCIONS.

    default_coerces_to

    TypeAnnotator.COERCES_TO: highest-to-lowest type precedence (Spark ANSI).

    default_selection

    fn default_selection(is_agg : Bool) ->
    Expr

    Selection to use if the selection list is empty.

    dialect_coerces_to

    The COERCES_TO of dialect (empty when the dialect uses the default one).

    dialect_expression_metadata

    The expression metadata of dialect (Python dialect.EXPRESSION_METADATA).

    eliminate_ctes

    Remove unused CTEs from an expression.

    eliminate_join_marks

    Remove Oracle-style (+) join marks by converting them into explicit LEFT JOINs.

    See https://docs.oracle.com/cd/B19306_01/server.102/b14200/queries006.htm#sthref3178

    1. You cannot specify the (+) operator in a query block that also contains FROM clause join syntax.
    2. The (+) operator can appear only in the WHERE clause or, in the context of left-correlation (that is, when specifying the TABLE clause) in the FROM clause, and can be applied only to a column of a table or view.

    The (+) operator does not produce an outer join if you specify one table in the outer query and the other table in an inner query. A WHERE condition containing the (+) operator cannot be combined with another condition using the OR logical operator, cannot use the IN comparison condition and cannot compare a marked column with a subquery.

    eliminate_joins

    Remove unused joins from an expression.

    eliminate_subqueries

    Rewrite derived tables as CTES, deduplicating if possible.

    ensure_schema

    Python ensure_schema: builds a MappingSchema from an optional mapping.

    expand

    Transforms an expression by expanding all referenced sources into subqueries.

    explode_projection_to_unnest

    fn explode_projection_to_unnest(index_offset? : Int, unnest_map? : Bool) -> ((
    Expr
    ) ->
    Expr
    raise
    SqlglotError
    )

    Convert explode/posexplode projections into unnests.

    extend_metadata

    Copies the metadata of a parent and applies updates (Python {**parent, ...}).

    find_all_in_scope

    Returns all nodes in this scope matching at least one of the kinds.

    find_in_scope

    Returns the first node in this scope matching at least one of the kinds.

    gen

    fn gen(expression :
    Expr
    , comments? : Bool) -> String raise
    SqlglotError

    Simple pseudo sql generator for quickly generating sortable and uniq strings.

    comments controls whether the expressions' comments are included.

    install

    fn install() -> Unit

    Installs the real annotate_types and simplify implementations into core.

    isolate_table_selects

    Wraps tables with known schemas in (SELECT * FROM t AS t) AS t when a scope selects from more than one source.

    join_condition

    Extract the join condition: (source keys, join keys, remaining predicate).

    merge_ctes

    fn merge_ctes(expression :
    Expr
    , leave_tables_isolated? : Bool, scopes? : Array[Scope], copy_budget? : CopyBudget) -> (
    Expr
    , Bool) raise
    SqlglotError

    merge_derived_tables

    fn merge_derived_tables(expression :
    Expr
    , leave_tables_isolated? : Bool, scopes? : Array[Scope], copy_budget? : CopyBudget) ->
    Expr
    raise
    SqlglotError

    merge_subqueries

    fn merge_subqueries(expression :
    Expr
    , leave_tables_isolated? : Bool, max_copy_factor? : Int?, min_copy_budget? : Int) ->
    Expr
    raise
    SqlglotError

    Rewrite the AST to merge derived tables into the outer query.

    normalization_distance

    fn normalization_distance(expression :
    Expr
    , dnf? : Bool, max? : Int) -> Int

    The difference in the number of predicates between a given expression and its normalized form.

    normalize

    Rewrite the AST into conjunctive normal form (or disjunctive normal form if dnf).

    normalize_identifier_str

    fn normalize_identifier_str(name : String, dialect? :
    Dialect
    ) ->
    Expr

    normalize_identifiers("name", dialect): parses name as an identifier first.

    normalize_identifiers

    fn normalize_identifiers(expression :
    Expr
    , dialect? :
    Dialect
    , store_original_column_identifiers? : Bool) ->
    Expr

    Normalize identifiers by converting them to either lower or upper case, ensuring the semantics are preserved in each case (e.g. by respecting case-sensitivity).

    normalize_name

    fn normalize_name(identifier : String, dialect? :
    Dialect
    , is_table? : Bool, normalize? : Bool) ->
    Expr

    Python normalize_name for a string identifier.

    normalize_name_ident

    fn normalize_name_ident(identifier :
    Expr
    , dialect :
    Dialect
    , is_table? : Bool) ->
    Expr

    Python normalize_name for an identifier expression (it is copied).

    normalize_table_name

    fn normalize_table_name(table :
    Expr
    , dialect? :
    Dialect
    , copy? : Bool) -> String

    Returns a case normalized table name without quotes.

    normalize_table_name_str

    fn normalize_table_name_str(table : String, dialect? :
    Dialect
    ) -> String raise
    SqlglotError

    normalize_table_name for a table name given as SQL.

    normalized

    fn normalized(expression :
    Expr
    , dnf? : Bool) -> Bool

    Checks whether a given expression is in a normal form of interest.

    optimize

    fn optimize(expression :
    Expr
    , schema? : MappingSchema, mapping? : Map[String, SchemaNode], db? : String, catalog? : String, dialect? :
    Dialect
    , rules? : Array[Rule], sql? : String, infer_schema? : Bool, identify? : Bool, leave_tables_isolated? : Bool, validate_qualify_columns? : Bool, canonicalize_table_aliases? : Bool, expand_alias_refs? : Bool, expand_stars? : Bool, allow_partial_qualification? : Bool, isolate_tables? : Bool, quote_identifiers? : Bool, on_qualify? : (
    Expr
    ) -> Unit, constant_propagation? : Bool, coalesce_simplification? : Bool) ->
    Expr
    raise
    SqlglotError

    Rewrite a sqlglot AST into an optimized form.

    identify only applies to the QuoteIdentifiers rule (the Qualify rule receives quote_identifiers=false, as in Python). Unless given, schema is built from mapping.

    optimize_joins

    Removes cross joins if possible and reorder joins based on predicate dependencies.

    optimize_sql

    fn optimize_sql(sql : String, schema? : MappingSchema, mapping? : Map[String, SchemaNode], dialect? :
    Dialect
    , rules? : Array[Rule], infer_schema? : Bool, identify? : Bool) ->
    Expr
    raise
    SqlglotError

    Parses sql (in dialect) and optimizes it.

    pivot_output_columns

    fn pivot_output_columns(pivot :
    Expr
    , pre_pivot_columns : Array[String]) -> Array[(String, String)]

    Pivot.output_columns: ordered (post-rename name, pre-rename name) pairs.

    projection_has_aggregate

    fn projection_has_aggregate(projection :
    Expr
    , windows : Array[
    Expr
    ]) -> Bool

    Port of optimizer.helpers.projection_has_aggregate.

    projection_reachability

    fn projection_reachability(expression :
    Expr
    , whole_query? : Bool) -> ProjectionReachability raise
    SqlglotError

    Find which scopes and projections each outermost output reaches through dependencies.

    prune_projections

    fn prune_projections(reachability : ProjectionReachability, root : Int, journal? : Array[(
    Expr
    , String,
    Value
    ?)], remove_ctes? : Bool) -> Unit

    Prune the analyzed tree to the scopes and projections reachable from output root.

    pushdown_cte_alias_columns

    fn pushdown_cte_alias_columns(scope : Scope) -> Unit

    Pushes down the CTE alias columns into the projection.

    pushdown_predicates

    Rewrite the AST to pushdown predicates in FROMS and JOINS.

    pushdown_projections

    Remove unused projections and CTEs while preserving all outermost outputs.

    qualify

    fn qualify(expression :
    Expr
    , dialect? :
    Dialect
    , db? : String, catalog? : String, schema? : MappingSchema, expand_alias_refs? : Bool, expand_stars? : Bool, infer_schema? : Bool, isolate_tables? : Bool, qualify_columns? : Bool, allow_partial_qualification? : Bool, validate_qualify_columns? : Bool, quote_identifiers? : Bool, identify? : Bool, canonicalize_table_aliases? : Bool, on_qualify? : (
    Expr
    ) -> Unit, sql? : String) ->
    Expr
    raise
    SqlglotError

    Rewrite the AST to have normalized and qualified tables and columns.

    qualify_columns

    fn qualify_columns(expression :
    Expr
    , schema : MappingSchema, expand_alias_refs? : Bool, expand_stars? : Bool, infer_schema? : Bool, allow_partial_qualification? : Bool) ->
    Expr
    raise
    SqlglotError

    Rewrite the AST to have fully qualified columns.

    qualify_outputs

    Ensure all output columns are aliased.

    qualify_outputs_scope

    fn qualify_outputs_scope(scope : Scope, dialect :
    Dialect
    ) -> Unit

    Ensure all output columns of a scope are aliased.

    qualify_tables

    fn qualify_tables(expression :
    Expr
    , db? : String, catalog? : String, on_qualify? : (
    Expr
    ) -> Unit, dialect? :
    Dialect
    , canonicalize_table_aliases? : Bool) ->
    Expr
    raise
    SqlglotError

    Rewrite the AST to have fully qualified tables. Join constructs such as (t1 JOIN t2) AS t will be expanded into (SELECT * FROM t1 AS t1, t2 AS t2) AS t.

    quote_identifiers

    fn quote_identifiers(expression :
    Expr
    , dialect? :
    Dialect
    , identify? : Bool) ->
    Expr

    Makes sure all identifiers that need to be quoted are quoted.

    record

    fn record(journal : Array[(
    Expr
    , String,
    Value
    ?)], node :
    Expr
    , arg_key : String) -> Unit

    Records the current value of node.args[arg_key] so revert can restore it.

    register_coerces_to

    fn register_coerces_to(dialect_name : String, build : () -> Map[
    DType
    ,
    Set
    [
    DType
    ]]) -> Unit

    Registers the COERCES_TO mapping of a dialect (by name).

    register_expression_metadata

    fn register_expression_metadata(dialect_name : String, build : () -> Map[
    Kind
    , TypeSpec]) -> Unit

    Registers the expression metadata of a dialect (by name). Dialects that don't register metadata inherit the metadata of their parent dialect.

    reorder_joins

    Reorder joins by topological sort order based on predicate references.

    replace_tree

    Python exp.replace_tree: replaces the tree with the results of fun on each node, leaves first; new nodes are traversed too.

    revert

    fn revert(journal : Array[(
    Expr
    , String,
    Value
    ?)], start? : Int) -> Unit

    Restores every argument recorded from start onwards, newest first.

    rules

    let rules : Array[Rule]

    The default optimizer rules (Python RULES), in order.

    schema_from_json_string

    fn schema_from_json_string(s : String) -> Map[String, SchemaNode] raise
    SqlglotError

    Parses a JSON string into a schema mapping (see SchemaNode::from_json).

    simplify

    fn simplify(expression :
    Expr
    , constant_propagation? : Bool, coalesce_simplification? : Bool, dialect? :
    Dialect
    ) ->
    Expr
    raise
    SqlglotError

    Rewrite the AST to simplify expressions.

    simplify_parens

    Removes redundant parentheses around expression when they're not needed.

    sql_of

    Generates SQL for e in dialect (Python e.sql(dialect=..., pretty=...)).

    traverse_scope

    Traverse an expression by its "scopes", in depth-first post-order.

    tsort

    fn tsort(dag : Array[(String, Array[String])]) -> Array[String] raise
    SqlglotError

    Python helper.tsort: topological sort of a DAG (name -> dependencies).

    unnest_subqueries

    Rewrite the AST to convert some predicates with subqueries into joins.

    validate_qualify_columns

    Raise an OptimizeError if any columns aren't qualified.

    walk_in_scope

    Visits all nodes in the syntax tree, stopping at nodes that start child scopes.