optimizer

package
v0.41.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

Rules ports RULES (optimizer/optimizer.py:40-55): the default rule sequence, in order.

Functions

func AnnotateTypes

func AnnotateTypes(expression exp.Expression, schemaArg schema.SchemaType, dialect dialects.DialectType) exp.Expression

AnnotateTypes ports annotate_types (annotate_types.py:46-83): it infers the types of expression and annotates its AST accordingly. schemaArg is a schema.SchemaType.

schema {"y": {"cola": "SMALLINT"}}
SELECT x.cola + 2.5 AS cola FROM (SELECT y.cola AS cola FROM y AS y) AS x
  -> the projection is annotated DOUBLE

func AnnotateTypesRule

func AnnotateTypesRule(expression exp.Expression, args *RuleArgs) exp.Expression

AnnotateTypesRule runs AnnotateTypes with the optimize arguments. The Go AnnotateTypes takes no expression_metadata, coerces_to or overwrite_types, so those keep their defaults.

func Canonicalize

func Canonicalize(expression exp.Expression, dialect dialects.DialectType) exp.Expression

Canonicalize ports canonicalize (optimizer/canonicalize.py:12-35): it converts a SQL expression into a standard form. Many of the conversions rely on annotate_types.

func CanonicalizeInternalNames added in v0.40.0

func CanonicalizeInternalNames(expression exp.Expression) exp.Expression

CanonicalizeInternalNames ports canonicalize_internal_names (optimizer/canonicalize_internal_names.py:13-359).

Rewrite a query to a canonical structural form. Preserves data-contract names (base-table names and columns, top-level output aliases) and canonicalizes internal names (table aliases, CTE/subquery names, internal column aliases) to sequential `_tN` / `_cN`. For set operations the top-level output is the leftmost leaf SELECT.

Assumes the expression has already been processed by qualify (or equivalent), so that columns are bound to sources and aliases exist on every projection / subquery / CTE.

func CanonicalizeRule

func CanonicalizeRule(expression exp.Expression, args *RuleArgs) exp.Expression

CanonicalizeRule runs Canonicalize with the optimize arguments.

func EliminateCTEs

func EliminateCTEs(expression exp.Expression, journal *Journal) exp.Expression

EliminateCTEs ports eliminate_ctes (optimizer/eliminate_ctes.py:13-58): it removes unused CTEs from expression, popping the whole WITH clause once its last CTE goes. When journal is non-nil, every mutation is recorded first so Journal.Revert can undo the pass.

WITH y AS (SELECT a FROM x) SELECT a FROM z  ->  SELECT a FROM z

func EliminateCTEsRule

func EliminateCTEsRule(expression exp.Expression, args *RuleArgs) exp.Expression

EliminateCTEsRule runs EliminateCTEs with the optimize arguments.

func EliminateJoins

func EliminateJoins(expression exp.Expression) exp.Expression

EliminateJoins ports eliminate_joins (optimizer/eliminate_joins.py:13-50): it removes joins whose source is unused, when the join condition can't produce duplicate rows.

SELECT x.a FROM x LEFT JOIN (SELECT DISTINCT y.b FROM y) AS y ON x.b = y.b  ->  SELECT x.a FROM x

func EliminateJoinsRule

func EliminateJoinsRule(expression exp.Expression, _ *RuleArgs) exp.Expression

EliminateJoinsRule runs EliminateJoins.

func EliminateSubqueries

func EliminateSubqueries(expression exp.Expression) exp.Expression

EliminateSubqueries ports eliminate_subqueries (optimizer/eliminate_subqueries.py:16-115): it rewrites derived tables as CTEs, deduplicating identical ones.

SELECT a FROM (SELECT * FROM x) AS y  ->  WITH y AS (SELECT * FROM x) SELECT a FROM y AS y

func EliminateSubqueriesRule

func EliminateSubqueriesRule(expression exp.Expression, _ *RuleArgs) exp.Expression

EliminateSubqueriesRule runs EliminateSubqueries.

func FindAllInScope

func FindAllInScope(expression exp.Expression, target any) []exp.Expression

func FindInScope

func FindInScope(expression exp.Expression, target any) exp.Expression

func IsolateTableSelects

func IsolateTableSelects(expression exp.Expression, schemaArg schema.SchemaType, dialect dialects.DialectType) exp.Expression

func MergeSubqueries

func MergeSubqueries(expression exp.Expression, leaveTablesIsolated bool) exp.Expression

MergeSubqueries ports merge_subqueries (optimizer/merge_subqueries.py:17-52): it merges derived tables into the outer query, and CTEs too when they are selected from only once. With leaveTablesIsolated, it does not merge when that would put several table selects in a single query.

SELECT a FROM (SELECT x.a FROM x) CROSS JOIN y  ->  SELECT x.a FROM x CROSS JOIN y

func MergeSubqueriesRule

func MergeSubqueriesRule(expression exp.Expression, args *RuleArgs) exp.Expression

MergeSubqueriesRule runs MergeSubqueries with the optimize arguments.

func Normalize

func Normalize(expression exp.Expression, dnf bool, maxDistance int) exp.Expression

Normalize ports normalize (optimizer/normalize.py:15-67): it rewrites the AST into conjunctive normal form, or disjunctive normal form when dnf is true. A connector whose estimated conversion distance exceeds maxDistance is left alone.

(x AND y) OR z  ->  (x OR z) AND (y OR z)

func NormalizeIdentifiers

func NormalizeIdentifiers(expression exp.Expression, dialect dialects.DialectType) exp.Expression

NormalizeIdentifiers folds unquoted identifiers per the dialect's normalization strategy, mirroring upstream sqlglot's normalize_identifiers(expression, dialect: DialectType).

The walker itself lives on dialects.Dialect so the parser can share it without an import cycle — see the note on Dialect.NormalizeIdentifiers (dialects/normalize_identifiers.go).

func NormalizeIdentifiersString

func NormalizeIdentifiersString(name string, dialect dialects.DialectType) exp.Expression

func NormalizeRule

func NormalizeRule(expression exp.Expression, args *RuleArgs) exp.Expression

NormalizeRule runs Normalize with the optimize arguments.

func Optimize

func Optimize(expression exp.Expression, opts OptimizeOpts) exp.Expression

Optimize ports optimize (optimizer/optimizer.py:58-114): it rewrites an AST into an optimized form by running each rule in turn on a copy of expression.

SELECT a FROM (SELECT x.a FROM x) AS y WHERE 1 + 1 = 2
  ->  SELECT "x"."a" AS "a" FROM "x" AS "x"

func OptimizeJoins

func OptimizeJoins(expression exp.Expression) exp.Expression

OptimizeJoins ports optimize_joins (optimizer/optimize_joins.py:13-55): it removes cross joins where possible and reorders joins based on predicate dependencies.

SELECT * FROM x CROSS JOIN y JOIN z ON x.a = z.a AND y.a = z.a
  ->  SELECT * FROM x JOIN z ON x.a = z.a AND TRUE JOIN y ON y.a = z.a

func OptimizeJoinsRule

func OptimizeJoinsRule(expression exp.Expression, _ *RuleArgs) exp.Expression

OptimizeJoinsRule runs OptimizeJoins.

func PushdownCTEAliasColumns

func PushdownCTEAliasColumns(scope *Scope)

func PushdownPredicates

func PushdownPredicates(expression exp.Expression, dialect dialects.DialectType) exp.Expression

PushdownPredicates ports pushdown_predicates (optimizer/pushdown_predicates.py:19-87): it pushes WHERE and JOIN predicates down into the FROMs, JOINs and subqueries they filter.

SELECT y.a AS a FROM (SELECT x.a AS a FROM x AS x) AS y WHERE y.a = 1
  ->  SELECT y.a AS a FROM (SELECT x.a AS a FROM x AS x WHERE x.a = 1) AS y WHERE TRUE

func PushdownPredicatesRule

func PushdownPredicatesRule(expression exp.Expression, args *RuleArgs) exp.Expression

PushdownPredicatesRule runs PushdownPredicates with the optimize arguments.

func PushdownProjections

func PushdownProjections(expression exp.Expression, schemaArg schema.SchemaType, removeUnusedSelections bool, dialect dialects.DialectType, journal *Journal) exp.Expression

PushdownProjections ports pushdown_projections (optimizer/pushdown_projections.py:46-148): it removes the projections no outer query uses. When journal is non-nil, the mutations are recorded so Journal.Revert can undo them.

SELECT y.a AS a FROM (SELECT x.a AS a, x.b AS b FROM x) AS y
  ->  SELECT y.a AS a FROM (SELECT x.a AS a FROM x) AS y

func PushdownProjectionsRule

func PushdownProjectionsRule(expression exp.Expression, args *RuleArgs) exp.Expression

PushdownProjectionsRule runs PushdownProjections with the optimize arguments.

func Qualify

func Qualify(expression exp.Expression, opts QualifyOpts) exp.Expression

func QualifyColumns

func QualifyColumns(expression exp.Expression, schemaArg schema.SchemaType, expandAliasRefs bool, expandStars bool, inferSchema *bool, allowPartialQualification bool, dialect dialects.DialectType) exp.Expression

func QualifyOutputs

func QualifyOutputs(scopeOrExpression any, dialectArg ...dialects.DialectType)

func QualifyRule

func QualifyRule(expression exp.Expression, args *RuleArgs) exp.Expression

QualifyRule runs Qualify with the optimize arguments.

func QualifyTables

func QualifyTables(expression exp.Expression, schemaName exp.IdentifierName, catalog exp.IdentifierName, dialect dialects.DialectType, canonicalizeTableAliases bool, onQualify func(exp.Expression), searchPath []string, s schema.Schema) exp.Expression

func QuoteIdentifiers

func QuoteIdentifiers(expression exp.Expression, dialect dialects.DialectType, identify bool) exp.Expression

func QuoteIdentifiersRule

func QuoteIdentifiersRule(expression exp.Expression, args *RuleArgs) exp.Expression

QuoteIdentifiersRule runs QuoteIdentifiers with the optimize arguments.

func ResolveEngineIdentities

func ResolveEngineIdentities(expression exp.Expression, catalog *EngineCatalog, dialect dialects.DialectType, searchPath []string, calls map[exp.Expression]ResolvedCall, relations map[exp.Expression]ResolvedRelation)

ResolveEngineIdentities classifies every Anonymous function call and every Table reference in the expression against the consumer-supplied catalog, writing into the non-nil report maps (keyed by the Anonymous / Table node). The AST is never modified. Through Qualify it runs AFTER the table passes, so a DefaultSchema stamp (applied without existence proof) becomes the relation's qualifier before classification — a stamped name absent from the catalogs reports Unknown; a consumer wanting engine-true relation resolution should pass SearchPath (proof-based) rather than DefaultSchema, or resolve on the unqualified AST. The per-dialect rules are the verified engine algorithms (see DEVIATIONS): MySQL native-priority + current-database scoping; PG search_path union with pg_catalog implicitly first unless explicitly listed, with the type-dependent residue (a name in more than one candidate schema) fail-closed to Unknown.

func Simplify

func Simplify(expression exp.Expression, constantPropagation, coalesceSimplification bool, dialect dialects.DialectType) exp.Expression

Simplify ports simplify (simplify.py:44-72).

TRUE AND TRUE  ->  TRUE

func SimplifyParens

func SimplifyParens(expression exp.Expression, dialect *dialects.Dialect) exp.Expression

SimplifyParens ports simplify_parens (simplify.py:133-177).

func SimplifyRule

func SimplifyRule(expression exp.Expression, args *RuleArgs) exp.Expression

SimplifyRule runs Simplify with the optimize arguments.

func UnnestSubqueries

func UnnestSubqueries(expression exp.Expression) exp.Expression

UnnestSubqueries ports unnest_subqueries (optimizer/unnest_subqueries.py:8-39): it rewrites predicates with subqueries into joins. Scalar subqueries become cross joins; correlated or vectorized subqueries become a grouped LEFT JOIN, so the join is not many to many.

SELECT * FROM x AS x WHERE (SELECT y.a AS a FROM y AS y WHERE x.a = y.a) = 1
  ->  SELECT * FROM x AS x LEFT JOIN (SELECT y.a AS a FROM y AS y WHERE TRUE GROUP BY y.a)
      AS _u_0 ON x.a = _u_0.a WHERE _u_0.a = 1

divergence (Go-forced): where upstream builds a condition from a SQL string (an f-string fed to exp.condition or Select.select), this builds the node that string parses to, because the optimizer does not depend on the parser. The generated SQL is the same.

func UnnestSubqueriesRule

func UnnestSubqueriesRule(expression exp.Expression, _ *RuleArgs) exp.Expression

UnnestSubqueriesRule runs UnnestSubqueries.

func ValidateQualifyColumns

func ValidateQualifyColumns(expression exp.Expression, sql string) exp.Expression

ValidateQualifyColumns validates the qualify-columns pass over expression. sql is the original statement text; it is accepted for upstream's error highlighting, which this port does not implement yet.

func WalkInScope

func WalkInScope(expression exp.Expression, prune func(exp.Expression) bool) []exp.Expression

Types

type CallKind

type CallKind int

CallKind classifies a resolved function call. Unknown is the zero value (fail-closed).

const (
	CallUnknown CallKind = iota
	CallBuiltin
	CallUDF
)

func (CallKind) String

func (k CallKind) String() string

type EngineCatalog

type EngineCatalog struct {
	// BuiltinFunctions is the priority builtin name set: MySQL natives (builtin > loadable >
	// stored — unshadowable), or PG's pg_catalog functions (implicitly first on the search
	// path unless pg_catalog is explicitly listed), or Athena's global builtin names.
	BuiltinFunctions map[string]bool
	// SystemFunctionSchemas classifies QUALIFIED calls: schema -> function names
	// (e.g. pg_catalog, information_schema).
	SystemFunctionSchemas map[string]map[string]bool
	// UDFSchemas is the user function catalog: schema (PG) / database (MySQL) -> names.
	UDFSchemas map[string]map[string]bool
	// LoadableFunctions is MySQL's loadable (plugin/UDF) function tier: global names ranking
	// below natives but above stored functions. Classified CallUDF (consumer-installed code,
	// grant-gated), never CallBuiltin.
	LoadableFunctions map[string]bool
	// SystemRelations: schema -> system relation names (pg_catalog/information_schema tables
	// and views; MySQL's mysql/information_schema/performance_schema/sys).
	SystemRelations map[string]map[string]bool
	// UserRelations is the user table/view catalog: schema (PG) / database (MySQL) -> names.
	// A qualified or path-resolved relation found in NEITHER SystemRelations nor UserRelations
	// is Unknown (fail-closed) — never asserted UserRelation without catalog evidence.
	UserRelations map[string]map[string]bool
	// TempRelations names the session's PG temporary relations. The engine searches the
	// implicit temporary schema BEFORE pg_catalog for relations (not functions), so a temp
	// table shadows a same-named system view — a consumer that cannot track temp objects must
	// deny temp-creating statements upstream or accept that shadow as unmodeled.
	TempRelations map[string]bool
	// CurrentDatabase scopes MySQL's unqualified stored functions and relations, and Athena's
	// unqualified relations, which resolve against the current database only.
	CurrentDatabase string
	// DefaultCatalog is the implicit catalog for three-level engines, supplied by the consumer.
	DefaultCatalog string
	// CatalogSystemRelations maps catalog -> database -> system relation names for three-level engines.
	CatalogSystemRelations map[string]map[string]map[string]bool
	// CatalogUserRelations maps catalog -> database -> user relation names for three-level engines.
	CatalogUserRelations map[string]map[string]map[string]bool
}

EngineCatalog is the NON-UPSTREAM, opt-in identity catalog for function/relation resolution (DEVIATIONS: opaque_functions companion). It is a PURE consumer input, introspected from the live target instance — sqlglot-go ships no name sets, only the resolution algorithm. All name keys are expected pre-folded: function names lowercase (function identifiers are case-insensitive in all supported engines), relation names folded per the dialect's strategy. A name missing from the catalog resolves Unknown (fail-closed).

type Journal

type Journal []JournalEntry

Journal ports journal.Journal (optimizer/journal.py:9): the recorded mutations a rule made, so Revert can undo them.

func (*Journal) Record

func (j *Journal) Record(node exp.Expression, argKey string)

Record ports record (optimizer/journal.py:12-19): it saves the current value of node's argKey arg so Revert can restore it. It must be called before the arg is mutated. List values are copied shallowly, so the caller may freely mutate or replace the list afterwards.

func (*Journal) Revert

func (j *Journal) Revert()

Revert ports revert (optimizer/journal.py:22-32): it restores every recorded arg, newest first, and empties the journal. Set reattaches the restored expressions (their parent, arg key and index), so rules that only detach or reorder nodes leave the tree exactly as it was before they ran. Rules that replace nodes with new ones can't be reverted this way.

type JournalEntry

type JournalEntry struct {
	Node   exp.Expression
	ArgKey string
	Value  any
}

JournalEntry ports journal.JournalEntry (optimizer/journal.py:8): one recorded argument mutation — the node, the arg key, and the value before the mutation.

type OptimizeOpts

type OptimizeOpts struct {
	// Schema is the column-metadata schema; see schema.SchemaType for the accepted forms.
	Schema schema.SchemaType
	// DefaultSchema is upstream's db: the default schema, as a USE statement might set it.
	DefaultSchema exp.IdentifierName
	// Catalog is the default catalog, as a USE CATALOG statement might set it.
	Catalog exp.IdentifierName
	Dialect dialects.DialectType
	// Rules is the rule sequence; nil means Rules. Many rules need qualified tables and
	// columns, so don't drop QualifyRule unless you know what you're doing.
	Rules []Rule
	// SQL is the original SQL string, for error highlighting.
	SQL string
	// Kwargs are the extra rule arguments (upstream's **kwargs). Its Schema, DefaultSchema,
	// Catalog, Dialect, SQL, IsolateTables and QuoteIdentifiers are set by Optimize.
	Kwargs RuleArgs
}

OptimizeOpts holds optimize's arguments. Its zero value runs the default rules with no schema under the base dialect.

type QualifyOpts

type QualifyOpts struct {
	// Dialect selects the dialect. See dialects.DialectType for the accepted forms
	// (nil | string | *dialects.Dialect). Mirrors upstream sqlglot's polymorphic dialect argument.
	Dialect dialects.DialectType
	// DefaultSchema is the fixed schema-level qualifier stamped on unqualified tables — upstream's
	// `db=` kwarg (renamed here for the same reason as the Table/Column `schema` arg; see
	// DEVIATIONS.md §7). Named DefaultSchema, not Schema, because Schema below is the column-metadata
	// mapping (upstream's `schema=`), mirroring upstream's own two distinct qualify() arguments.
	// A name-or-identifier value; see expressions.IdentifierName.
	DefaultSchema exp.IdentifierName
	// Catalog is the fixed catalog-level qualifier; a name-or-identifier, see expressions.IdentifierName.
	Catalog exp.IdentifierName
	// SearchPath is an ordered, opt-in schema search path. Its zero value preserves
	// upstream-compatible fixed DefaultSchema/Catalog qualification.
	SearchPath []string
	// Schema is the column-metadata schema. See schema.SchemaType for the accepted forms.
	Schema                    schema.SchemaType
	ExpandAliasRefs           bool
	ExpandStars               bool
	InferSchema               *bool
	IsolateTables             bool
	QualifyColumns            bool
	AllowPartialQualification bool
	ValidateQualifyColumns    bool
	QuoteIdentifiers          bool
	Identify                  bool
	CanonicalizeTableAliases  bool
	OnQualify                 func(exp.Expression)
	// ResolutionReport receives source classifications; nil disables all report work.
	ResolutionReport map[exp.Expression]ResolvedSource
	// EngineCatalog enables NON-UPSTREAM function/relation identity resolution (see
	// engine_catalog.go): with a non-nil catalog, CallReport/RelationReport (whichever are
	// non-nil) receive per-node classifications after the qualify passes run. Never rewrites
	// the AST. SearchPath doubles as the PG function search path.
	EngineCatalog  *EngineCatalog
	CallReport     map[exp.Expression]ResolvedCall
	RelationReport map[exp.Expression]ResolvedRelation
	SQL            string
}

func DefaultQualifyOpts

func DefaultQualifyOpts() QualifyOpts

type RelationKind

type RelationKind int

RelationKind classifies a resolved relation. Unknown is the zero value (fail-closed).

const (
	RelationUnknown RelationKind = iota
	SystemRelation
	UserRelation
)

func (RelationKind) String

func (k RelationKind) String() string

type ResolvedCall

type ResolvedCall struct {
	Kind     CallKind
	Identity string
}

ResolvedCall reports a folded function identity: schema.name, or a bare MySQL/Athena builtin name. Identity is empty when Unknown.

type ResolvedRelation

type ResolvedRelation struct {
	Kind     RelationKind
	Identity string
}

ResolvedRelation reports a folded schema.name identity, or catalog.database.name for Athena. Identity is empty when Unknown.

type ResolvedSource

type ResolvedSource struct {
	Catalog, Schema, Table string
	Kind                   SourceKind
}

ResolvedSource describes a resolved source. Identity fields are populated only for Physical sources.

type Resolver

type Resolver struct {
	// contains filtered or unexported fields
}

func NewResolver

func NewResolver(scope *Scope, s schema.Schema, inferSchema bool) *Resolver

func (*Resolver) AllColumns

func (r *Resolver) AllColumns() map[string]bool

func (*Resolver) GetSourceColumns

func (r *Resolver) GetSourceColumns(name string, onlyVisible ...bool) []string

func (*Resolver) GetSourceColumnsFromSetOp

func (r *Resolver) GetSourceColumnsFromSetOp(expression exp.Expression) []string

func (*Resolver) GetTable

func (r *Resolver) GetTable(column any) exp.Expression

type Rule

type Rule func(expression exp.Expression, args *RuleArgs) exp.Expression

Rule is an optimizer rule (upstream's OptimizerFn, optimizer/optimizer.py:25-37): it takes an expression and the optimize arguments, and returns the rewritten expression.

type RuleArgs

type RuleArgs struct {
	// Schema is the column-metadata schema, already ensured.
	Schema schema.Schema
	// DefaultSchema is upstream's db: the schema-level qualifier for unqualified tables (named
	// as in QualifyOpts, see DEVIATIONS.md §7).
	DefaultSchema exp.IdentifierName
	Catalog       exp.IdentifierName
	Dialect       dialects.DialectType
	SQL           string
	// IsolateTables and QuoteIdentifiers are the values optimize hands to qualify: true, as
	// other optimizations need it to perform well, and false, as quote_identifiers runs later.
	IsolateTables    bool
	QuoteIdentifiers bool

	// qualify
	ExpandAliasRefs           *bool
	ExpandStars               *bool
	InferSchema               *bool
	QualifyColumns            *bool
	AllowPartialQualification *bool
	ValidateQualifyColumns    *bool
	CanonicalizeTableAliases  *bool
	OnQualify                 func(exp.Expression)
	// Identify is read by qualify and quote_identifiers.
	Identify *bool
	// pushdown_projections
	RemoveUnusedSelections *bool
	// Journal is read by pushdown_projections and eliminate_ctes.
	Journal *Journal
	// normalize
	DNF         *bool
	MaxDistance *int
	// merge_subqueries
	LeaveTablesIsolated *bool
	// simplify
	ConstantPropagation    *bool
	CoalesceSimplification *bool
}

RuleArgs carries the keyword arguments optimize offers its rules: upstream's possible_kwargs (optimizer/optimizer.py:93-102). Upstream inspects each rule's signature and passes only the parameters it declares; in Go every rule receives the whole set and reads the fields it takes. A nil pointer field means "not passed", so the rule keeps its own default.

type Scope

type Scope struct {
	Expression exp.Expression
	Sources    map[string]any
	Parent     *Scope
	ScopeType  ScopeType

	SubqueryScopes     []*Scope
	DerivedTableScopes []*Scope
	TableScopes        []*Scope
	CTEScopes          []*Scope
	UnionScopes        []*Scope
	UDTFScopes         []*Scope

	LateralSources map[string]any
	CTESources     map[string]any
	OuterColumns   []string
	// contains filtered or unexported fields
}

func BuildScope

func BuildScope(expression exp.Expression) *Scope

func TraverseScope

func TraverseScope(expression exp.Expression) []*Scope

func (*Scope) AddSource

func (s *Scope) AddSource(name string, source any)

func (*Scope) CTEs

func (s *Scope) CTEs() []exp.Expression

func (*Scope) ColumnIndex

func (s *Scope) ColumnIndex() map[exp.Expression]bool

func (*Scope) Columns

func (s *Scope) Columns() []exp.Expression

func (*Scope) DerivedTables

func (s *Scope) DerivedTables() []exp.Expression

func (*Scope) ExternalColumns

func (s *Scope) ExternalColumns() []exp.Expression

func (*Scope) Find

func (s *Scope) Find(target any) exp.Expression

func (*Scope) FindAll

func (s *Scope) FindAll(target any) []exp.Expression

func (*Scope) IsCTE

func (s *Scope) IsCTE() bool

func (*Scope) IsCorrelatedSubquery

func (s *Scope) IsCorrelatedSubquery() bool

func (*Scope) IsDerivedTable

func (s *Scope) IsDerivedTable() bool

func (*Scope) IsRoot

func (s *Scope) IsRoot() bool

func (*Scope) IsSubquery

func (s *Scope) IsSubquery() bool

func (*Scope) IsUDTF

func (s *Scope) IsUDTF() bool

func (*Scope) IsUnion

func (s *Scope) IsUnion() bool

func (*Scope) JoinHints

func (s *Scope) JoinHints() []exp.Expression

func (*Scope) LocalColumns

func (s *Scope) LocalColumns() []exp.Expression

func (*Scope) Pivots

func (s *Scope) Pivots() []exp.Expression

func (*Scope) RefCount

func (s *Scope) RefCount() map[any]int

func (*Scope) References

func (s *Scope) References() []reference

func (*Scope) RemoveSource

func (s *Scope) RemoveSource(name string)

func (*Scope) RenameSource

func (s *Scope) RenameSource(oldName *string, newName string)

func (*Scope) Replace

func (s *Scope) Replace(old exp.Expression, new exp.Expression)

func (*Scope) ScansAllSubscopeColumns

func (s *Scope) ScansAllSubscopeColumns() bool

func (*Scope) SelectedSourceNames

func (s *Scope) SelectedSourceNames() []string

func (*Scope) SelectedSources

func (s *Scope) SelectedSources() map[string]selectedSource

func (*Scope) SemiOrAntiJoinTables

func (s *Scope) SemiOrAntiJoinTables() map[string]bool

func (*Scope) SourceColumns

func (s *Scope) SourceColumns(sourceName string) []exp.Expression

func (*Scope) Stars

func (s *Scope) Stars() []exp.Expression

func (*Scope) String

func (s *Scope) String() string

func (*Scope) Subqueries

func (s *Scope) Subqueries() []exp.Expression

func (*Scope) TableColumns

func (s *Scope) TableColumns() []exp.Expression

func (*Scope) Tables

func (s *Scope) Tables() []exp.Expression

func (*Scope) Traverse

func (s *Scope) Traverse() []*Scope

func (*Scope) UDTFs

func (s *Scope) UDTFs() []exp.Expression

func (*Scope) UnqualifiedColumns

func (s *Scope) UnqualifiedColumns() []exp.Expression

func (*Scope) Walk

func (s *Scope) Walk(prune func(exp.Expression) bool) []exp.Expression

type ScopeType

type ScopeType int
const (
	ScopeTypeRoot ScopeType = iota
	ScopeTypeSubquery
	ScopeTypeDerivedTable
	ScopeTypeCTE
	ScopeTypeUnion
	ScopeTypeUDTF
)

type Simplifier

type Simplifier struct {
	// contains filtered or unexported fields
}

Simplifier ports Simplifier (simplify.py:541-1590).

func NewSimplifier

func NewSimplifier(dialect dialects.DialectType, annotateNewExpressions bool) *Simplifier

NewSimplifier ports Simplifier.__init__ (simplify.py:542-548).

func (*Simplifier) Simplify

func (s *Simplifier) Simplify(expression exp.Expression, constantPropagation, coalesceSimplification bool) exp.Expression

Simplify ports Simplifier.simplify (simplify.py:642-710).

type SourceKind

type SourceKind int

SourceKind classifies an AST report entry by its resolved scope source.

const (
	// Unresolved is intentionally the zero value so missing report entries fail closed.
	Unresolved SourceKind = iota
	Physical
	CTE
	Derived
	Subquery
)

func (SourceKind) String

func (k SourceKind) String() string

type TypeAnnotator

type TypeAnnotator struct {
	// contains filtered or unexported fields
}

TypeAnnotator ports TypeAnnotator (annotate_types.py:158-1098).

func NewTypeAnnotator

func NewTypeAnnotator(s schema.Schema) *TypeAnnotator

NewTypeAnnotator ports TypeAnnotator.__init__ (annotate_types.py:197-229) with the default metadata, coercions and overwrite_types=True.

func (*TypeAnnotator) Annotate

func (a *TypeAnnotator) Annotate(expression exp.Expression, annotateScope bool) exp.Expression

Annotate ports TypeAnnotator.annotate (annotate_types.py:278-295). annotateScope false skips the scope traversal, annotating non-column expressions only.

func (*TypeAnnotator) AnnotateScope

func (a *TypeAnnotator) AnnotateScope(scope *Scope)

AnnotateScope ports annotate_scope (annotate_types.py:396-446).

func (*TypeAnnotator) Clear

func (a *TypeAnnotator) Clear()

Clear ports TypeAnnotator.clear (annotate_types.py:231-235).

func (*TypeAnnotator) Uncache

func (a *TypeAnnotator) Uncache(expression exp.Expression, deep bool)

Uncache ports TypeAnnotator.uncache (annotate_types.py:237-250): it evicts expression (or its subtree, if deep) from the annotation caches, before an annotated tree is mutated.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL