parser

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 12 Imported by: 1 module, 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

This section is empty.

Functions

func ParseAnalysis

func ParseAnalysis(sql string) (*Statement, *DDLStatement, error)

ParseAnalysis parses query/DML or governance DDL once. Exactly one result is non-nil on success; statement kind is determined from the native AST.

func ParsePartitionKeyColumns

func ParsePartitionKeyColumns(definition string) ([]string, bool)

ParsePartitionKeyColumns extracts only direct partition-key column names.

func ResolveCTEReferences

func ResolveCTEReferences(statement *Statement) []int

ResolveCTEReferences classifies the statement's relation references using lexical WITH visibility. Each result corresponds to Statement.Relations at the same index and contains an index into Statement.CTEDefinitions, or -1 when the reference is not proven to name a visible CTE. Qualified relations and DML write targets always require physical relation resolution.

Types

type BoundColumn

type BoundColumn struct {
	Original               ColumnReference
	Fixed                  bool
	OID                    uint32
	Schema, Relation, Name string
	AttributeNumber        int16
}

BoundColumn separates original spelling from proven catalog identity. Fixed may identify a derived expression without proving any physical column.

func (BoundColumn) ActualName

func (column BoundColumn) ActualName() string

ActualName returns the resolved physical name when known, otherwise the original exposed name, including a fixed derived expression's output name.

type BoundOutputField

type BoundOutputField struct {
	Name         string
	QueryBlockID int
	Column       *BoundColumn
	FromWildcard bool
	OriginField  *Expression
	SourceField  *BoundOutputField
}

BoundOutputField identifies a SELECT output and the target that produced it. SourceField follows derived/CTE output identity, not predicate pushdown safety. OriginField points to immutable syntax; callers must not modify that object.

type BoundStatement

type BoundStatement struct {
	Statement *Statement
	Relations []RelationBinding
	// Outputs contains SELECT output bindings. Incomplete scopes never imply
	// missing catalog columns are absent. This evidence is not a wire AST field.
	Outputs map[int]OutputBinding `json:"-"`
}

BoundStatement is a PostgreSQL statement with relation identities resolved.

func Bind

func Bind(statement *Statement, catalog []RelationMetadata, searchPath []string) (*BoundStatement, error)

Bind resolves explicit schemas and unqualified relations in search_path order, while retaining CTE shadowing and aliases.

type CTEDefinition

type CTEDefinition struct {
	// Kind identifies the CTE body statement, independently of the root statement.
	Kind         StatementKind
	Name         Identifier
	QueryBlockID int
	// WithOrdinal is the zero-based definition order within the owning WITH.
	WithOrdinal int
	// WithRecursive makes all definitions in this WITH visible to each body.
	// It does not assert that this particular CTE is self-recursive.
	WithRecursive bool
	// DefinitionQueryBlockID identifies the SELECT/DML body; -1 means unavailable.
	DefinitionQueryBlockID int
	// Materialization is DEFAULT, MATERIALIZED, or NOT MATERIALIZED.
	Materialization string
	Location        Location
}

CTEDefinition records the query block in which a CTE name is visible.

type ClauseTerm

type ClauseTerm struct {
	Kind         ClauseTermKind
	QueryBlockID int
	Clause       string
	Column       ColumnReference
	Function     string
	Positional   bool
	Direction    string
	Location     Location
}

ClauseTerm retains source facts for grouping and ordering audits. Direction is populated only for ORDER BY; Function is normalized like PostgreSQL unquoted identifiers and may contain a qualified name.

type ClauseTermKind

type ClauseTermKind string

ClauseTermKind classifies one GROUP BY or ORDER BY source expression.

const (
	// ClauseTermColumn is a direct column reference.
	ClauseTermColumn ClauseTermKind = "COLUMN"
	// ClauseTermFunction is a function call.
	ClauseTermFunction ClauseTermKind = "FUNCTION"
	// ClauseTermConstant is a literal or positional ordinal.
	ClauseTermConstant ClauseTermKind = "CONSTANT"
	// ClauseTermExpression is any other retained expression shape.
	ClauseTermExpression ClauseTermKind = "EXPRESSION"
)

type ColumnAssignment

type ColumnAssignment struct {
	Column   Identifier
	Default  bool
	Clause   string
	Location Location
}

ColumnAssignment retains a root UPDATE or ON CONFLICT target column and whether PostgreSQL's DEFAULT keyword supplies its value.

type ColumnMetadata

type ColumnMetadata struct {
	Name   string
	Number int16
}

ColumnMetadata supplies catalog column order and physical attribute identity. Dropped/system attributes must be excluded by the catalog adapter.

type ColumnOrigin

type ColumnOrigin struct {
	Physical   ColumnReference
	CTEPath    []RelationRef
	Correlated bool
}

ColumnOrigin identifies a proven physical column and the CTE references traversed to reach it, starting with the innermost reference.

type ColumnReference

type ColumnReference struct {
	Schema       Identifier
	Relation     Identifier
	Column       Identifier
	QueryBlockID int
	Location     Location
}

ColumnReference retains a simple PostgreSQL column reference for binding and value-independent index design.

type Condition

type Condition struct {
	Kind           ConditionKind
	QueryBlockID   int
	Clause         string
	Column         ColumnReference
	Relations      []string
	Operator       string
	ValueCount     int
	Pattern        string
	ValueType      string
	ValueExplicit  bool
	FunctionSchema string
	FunctionName   string
	// ExpressionPeer retains the other direct function argument for an
	// expression/expression comparison; an empty column means literal operand.
	ExpressionPeer     ColumnReference
	PeerFunctionSchema string
	Negated            bool
	ContainsNull       bool
	ConstantKnown      bool
	ConstantValue      bool
	Location           Location
}

Condition is one source-located clause fact. Pattern stores an exact decoded string literal for pattern/padding checks; it is never logged by the library or used for persistent index design.

type ConditionKind

type ConditionKind string

ConditionKind identifies clause-scoped facts used by static auditing. Predicate facts exclude projections; string padding also covers source literals in projections, VALUES, assignments, and other clauses.

const (
	// ConditionINList identifies an IN/NOT IN literal-expression list.
	ConditionINList ConditionKind = "IN_LIST"
	// ConditionSubqueryWithoutWhere identifies an IN/NOT IN subquery with a
	// table source and no query-block WHERE clause.
	ConditionSubqueryWithoutWhere ConditionKind = "SUBQUERY_WITHOUT_WHERE"
	// ConditionLikePattern identifies a LIKE or ILIKE pattern literal.
	ConditionLikePattern ConditionKind = "LIKE_PATTERN"
	// ConditionStringPadding identifies a source-located string literal with
	// leading or trailing Unicode whitespace.
	ConditionStringPadding ConditionKind = "STRING_PADDING"
	// ConditionConstantComparison identifies a provably constant boolean or
	// integer comparison.
	ConditionConstantComparison ConditionKind = "CONSTANT_COMPARISON"
	// ConditionNullComparison identifies =, <>, or != against NULL.
	ConditionNullComparison ConditionKind = "NULL_COMPARISON"
	// ConditionScalarSubquery identifies a scalar subquery in a predicate
	// clause, not a projection.
	ConditionScalarSubquery ConditionKind = "SCALAR_SUBQUERY"
	// ConditionNotInSubquery identifies NOT IN or equivalent <> ALL subquery
	// semantics that are sensitive to NULL output.
	ConditionNotInSubquery ConditionKind = "NOT_IN_SUBQUERY"
	// ConditionPredicateExpression identifies a predicate comparison whose
	// column-bearing operand is not a direct ColumnRef.
	ConditionPredicateExpression ConditionKind = "PREDICATE_EXPRESSION"
	// ConditionORDifferentRelations identifies an OR expression whose branches
	// contain qualified column references to more than one relation.
	ConditionORDifferentRelations ConditionKind = "OR_DIFFERENT_RELATIONS"
	// ConditionSameColumnComparison identifies a comparison whose direct left
	// and right ColumnRef spell the same normalized reference.
	ConditionSameColumnComparison ConditionKind = "SAME_COLUMN_COMPARISON"
	// ConditionTypedValueComparison identifies a direct column compared with a
	// literal of known primitive type or an explicitly cast value.
	ConditionTypedValueComparison ConditionKind = "TYPED_VALUE_COMPARISON"
	// ConditionIndexPredicate retains a direct column in a positive comparison,
	// IN, BETWEEN or IS NULL filter reached only through AND/OR. It proves
	// clause ownership, not selectivity or operator-class applicability.
	ConditionIndexPredicate ConditionKind = "INDEX_PREDICATE"
	// ConditionSubqueryLookup identifies a direct column in positive IN or
	// = ANY subquery membership reached through AND/OR in WHERE or JOIN ON.
	// It is lookup-design evidence, not a literal predicate or NDV estimate.
	ConditionSubqueryLookup ConditionKind = "SUBQUERY_LOOKUP"
	// ConditionIndexExpression retains a direct single-column function key.
	ConditionIndexExpression ConditionKind = "INDEX_EXPRESSION"
	// ConditionPartialNull is a scalar NULL test implied by the clause.
	ConditionPartialNull ConditionKind = "PARTIAL_NULL"
	// ConditionTrgmPattern is a positive direct LIKE/ILIKE literal predicate.
	ConditionTrgmPattern ConditionKind = "TRGM_PATTERN"
	// ConditionConjunctKey is a direct comparison implied by the clause.
	ConditionConjunctKey ConditionKind = "CONJUNCT_KEY"
)

type DDLBatch

type DDLBatch struct {
	SQL        string
	Statements []*DDLStatement
}

DDLBatch is an ordered, non-executing summary of one migration script.

func ParseDDLBatch

func ParseDDLBatch(sql string) (*DDLBatch, error)

ParseDDLBatch accepts one or more PostgreSQL statements for governance review. Analyze, AnalyzeStatic, Parse, and ParseDDL remain one-statement.

type DDLCommand

type DDLCommand struct {
	Kind            DDLCommandKind
	Column          Identifier
	Constraint      Identifier
	ConstraintKind  string
	NewType         string
	NewTypeModifier string
	HasTypeModifier bool
	HasUsing        bool
	Cascade         bool
	MissingOK       bool
	SkipValidation  bool
	VolatileDefault bool
	GeneratedStored bool
	Concurrent      bool
	FKDeleteAction  string
	FKUpdateAction  string
	Location        Location
}

DDLCommand is source-derived evidence for one destructive ALTER TABLE subcommand. HasUsing records an explicit USING expression without retaining or evaluating that expression.

type DDLCommandKind

type DDLCommandKind string

DDLCommandKind identifies a supported destructive ALTER TABLE subcommand.

const (
	// DDLDropColumn identifies ALTER TABLE DROP COLUMN.
	DDLDropColumn DDLCommandKind = "DROP_COLUMN"
	// DDLAlterColumnType identifies ALTER TABLE ALTER COLUMN TYPE.
	DDLAlterColumnType DDLCommandKind = "ALTER_COLUMN_TYPE"
	// DDLDropConstraint identifies DROP CONSTRAINT and DROP NOT NULL.
	DDLDropConstraint DDLCommandKind = "DROP_CONSTRAINT"
	// DDLSetLogged identifies ALTER TABLE SET LOGGED.
	DDLSetLogged DDLCommandKind = "SET_LOGGED"
	// DDLSetUnlogged identifies ALTER TABLE SET UNLOGGED.
	DDLSetUnlogged DDLCommandKind = "SET_UNLOGGED"
	// DDLAddUniqueConstraint identifies ADD PRIMARY KEY or UNIQUE.
	DDLAddUniqueConstraint DDLCommandKind = "ADD_UNIQUE_CONSTRAINT"
	// DDLEnableRowSecurity identifies ALTER TABLE ENABLE ROW LEVEL SECURITY.
	DDLEnableRowSecurity DDLCommandKind = "ENABLE_ROW_SECURITY"
	// DDLAddColumn identifies ALTER TABLE ADD COLUMN.
	DDLAddColumn DDLCommandKind = "ADD_COLUMN"
	// DDLSetNotNull identifies ALTER TABLE SET NOT NULL.
	DDLSetNotNull DDLCommandKind = "SET_NOT_NULL"
	// DDLAddCheck identifies ADD CHECK.
	DDLAddCheck DDLCommandKind = "ADD_CHECK"
	// DDLAddForeignKey identifies ADD FOREIGN KEY.
	DDLAddForeignKey DDLCommandKind = "ADD_FOREIGN_KEY"
	// DDLAttachPartition identifies ATTACH PARTITION.
	DDLAttachPartition DDLCommandKind = "ATTACH_PARTITION"
	// DDLDetachPartition identifies DETACH PARTITION.
	DDLDetachPartition DDLCommandKind = "DETACH_PARTITION"
	// DDLValidateConstraint identifies VALIDATE CONSTRAINT.
	DDLValidateConstraint DDLCommandKind = "VALIDATE_CONSTRAINT"
	// DDLSetTableSpace identifies SET TABLESPACE.
	DDLSetTableSpace DDLCommandKind = "SET_TABLESPACE"
	// DDLForceRowSecurity identifies FORCE ROW LEVEL SECURITY.
	DDLForceRowSecurity DDLCommandKind = "FORCE_ROW_SECURITY"
)

type DDLKind

type DDLKind string

DDLKind identifies a destructive PostgreSQL DDL statement supported by the governance analyzer.

const (
	// DDLTruncate identifies TRUNCATE.
	DDLTruncate DDLKind = "TRUNCATE"
	// DDLDropTable identifies DROP TABLE.
	DDLDropTable DDLKind = "DROP_TABLE"
	// DDLDrop identifies DROP of a non-table object, used for CASCADE review.
	DDLDrop DDLKind = "DROP"
	// DDLDropDatabase identifies DROP DATABASE.
	DDLDropDatabase DDLKind = "DROP_DATABASE"
	// DDLAlterTable identifies ALTER TABLE with a supported critical command.
	DDLAlterTable DDLKind = "ALTER_TABLE"
	// DDLCopy identifies COPY.
	DDLCopy DDLKind = "COPY"
	// DDLVacuum identifies VACUUM FULL.
	DDLVacuum DDLKind = "VACUUM"
	// DDLCreateIndex identifies CREATE INDEX.
	DDLCreateIndex DDLKind = "CREATE_INDEX"
	// DDLRefreshMatView identifies REFRESH MATERIALIZED VIEW.
	DDLRefreshMatView DDLKind = "REFRESH_MATVIEW"
	// DDLCreateTable identifies CREATE UNLOGGED TABLE.
	DDLCreateTable DDLKind = "CREATE_TABLE"
	// DDLCreateFunction identifies CREATE FUNCTION or PROCEDURE.
	DDLCreateFunction DDLKind = "CREATE_FUNCTION"
	// DDLCreateExtension identifies CREATE EXTENSION.
	DDLCreateExtension DDLKind = "CREATE_EXTENSION"
	// DDLBegin identifies BEGIN/START TRANSACTION.
	DDLBegin DDLKind = "BEGIN"
	// DDLCommit identifies COMMIT.
	DDLCommit DDLKind = "COMMIT"
	// DDLRollback identifies ROLLBACK.
	DDLRollback DDLKind = "ROLLBACK"
	// DDLSavepoint identifies SAVEPOINT or RELEASE/ROLLBACK TO SAVEPOINT.
	DDLSavepoint DDLKind = "SAVEPOINT"
	// DDLAlterEnum identifies ALTER TYPE ... ADD VALUE.
	DDLAlterEnum DDLKind = "ALTER_ENUM"
	// DDLCreatePolicy identifies CREATE POLICY.
	DDLCreatePolicy DDLKind = "CREATE_POLICY"
	// DDLReindex identifies REINDEX.
	DDLReindex DDLKind = "REINDEX"
	// DDLDropIndex identifies DROP INDEX.
	DDLDropIndex DDLKind = "DROP_INDEX"
	// DDLOther retains a batch statement that is not a modeled governance root.
	DDLOther DDLKind = "OTHER"
	// DDLRename identifies ALTER ... RENAME.
	DDLRename DDLKind = "RENAME"
	// DDLCluster identifies CLUSTER.
	DDLCluster DDLKind = "CLUSTER"
	// DDLGrant identifies GRANT.
	DDLGrant DDLKind = "GRANT"
	// DDLVariableSet identifies SET.
	DDLVariableSet DDLKind = "VARIABLE_SET"
	// DDLCreateDomain identifies CREATE DOMAIN.
	DDLCreateDomain DDLKind = "CREATE_DOMAIN"
	// DDLAlterDomain identifies ALTER DOMAIN.
	DDLAlterDomain DDLKind = "ALTER_DOMAIN"
)

type DDLStatement

type DDLStatement struct {
	SQL                   string
	Kind                  DDLKind
	Location              Location
	Relations             []RelationRef
	Objects               []Identifier
	ObjectLocations       []Location
	Commands              []DDLCommand
	UnsupportedNodes      []string
	Cascade               bool
	MissingOK             bool
	Concurrent            bool
	Unique                bool
	Primary               bool
	Unlogged              bool
	VacuumFull            bool
	CopyProgram           bool
	CopyStdIO             bool
	SecurityDefiner       bool
	SearchPathSet         bool
	IndexAccessMethod     string
	IndexColumns          []Identifier
	IndexIncludeColumns   []Identifier
	IndexHasExpression    bool
	VolatileFunctionNames []string
	ExtensionSchema       Identifier
	FunctionName          Identifier
	EnumType              Identifier
	EnumValue             string
	PolicyName            Identifier
	StringLiterals        []string
	HasPrimaryKey         bool
	PrimaryKeyColumns     int
	LockTimeoutSet        bool
	StatementTimeoutSet   bool
	GrantPublic           bool
	GrantPrivilege        string
	Cluster               bool
	DomainConstraint      bool
}

DDLStatement is a PostgreSQL-owned semantic summary of one destructive DDL statement. It never contains an executable rewrite.

func ParseDDL

func ParseDDL(sql string) (*DDLStatement, error)

ParseDDL accepts exactly one destructive PostgreSQL DDL statement and converts only pg_query native AST fields. Query/DML parsing remains owned by Parse and its existing single-statement contract.

type DMLScope

type DMLScope struct {
	Kind                StatementKind
	QueryBlockID        int
	HasAdditionalSource bool
}

DMLScope retains query-block-local UPDATE/DELETE source shape. An additional source means UPDATE FROM or DELETE USING, whose plan input can contain more join candidates than distinct target tuples.

type Expression

type Expression struct {
	Kind      ExpressionKind
	Clause    string
	Location  Location
	Qualifier []Identifier
}

Expression is a source-preserving projection or RETURNING expression.

type ExpressionKind

type ExpressionKind string

ExpressionKind is the small expression subset needed by initial static rules. Unmodeled expressions are retained as ExpressionOther rather than converted to another engine's AST.

const (
	// ExpressionOther is a retained but not semantically inferred expression.
	ExpressionOther ExpressionKind = "OTHER"
	// ExpressionStar is a direct * or qualifier.* projection.
	ExpressionStar ExpressionKind = "STAR"
)

type Feature

type Feature string

Feature identifies PostgreSQL syntax retained by the semantic skeleton.

const (
	// FeatureCTE identifies a WITH clause.
	FeatureCTE Feature = "CTE"
	// FeatureSubquery identifies a CTE, SubLink, or range subquery.
	FeatureSubquery Feature = "SUBQUERY"
	// FeatureSetOperation identifies UNION, INTERSECT, or EXCEPT.
	FeatureSetOperation Feature = "SET_OPERATION"
	// FeatureDistinctOn identifies PostgreSQL DISTINCT ON.
	FeatureDistinctOn Feature = "DISTINCT_ON"
	// FeatureLateral identifies a LATERAL relation.
	FeatureLateral Feature = "LATERAL"
	// FeatureReturning identifies a DML RETURNING clause.
	FeatureReturning Feature = "RETURNING"
	// FeatureOnConflict identifies INSERT ON CONFLICT.
	FeatureOnConflict Feature = "ON_CONFLICT"
	// FeatureUpdateFrom identifies UPDATE FROM.
	FeatureUpdateFrom Feature = "UPDATE_FROM"
	// FeatureDeleteUsing identifies DELETE USING.
	FeatureDeleteUsing Feature = "DELETE_USING"
	// FeatureMerge identifies MERGE.
	FeatureMerge Feature = "MERGE"
	// FeatureRowLocking identifies SELECT FOR UPDATE/SHARE variants.
	FeatureRowLocking Feature = "ROW_LOCKING"
)

type FunctionCall

type FunctionCall struct {
	Name         string
	Parts        []Identifier
	QueryBlockID int
	Location     Location
}

FunctionCall retains a PostgreSQL-normalized function name and its source. Parts preserves identifier boundaries, including quoted names containing dots.

func (FunctionCall) CanonicalName

func (call FunctionCall) CanonicalName() string

CanonicalName returns a normalized name with unambiguous SQL identifier boundaries. Unlike Name, it distinguishes a.b from the single name "a.b".

type Identifier

type Identifier struct {
	Value    string
	Original string
	Quoted   bool
}

Identifier retains PostgreSQL's normalized value and original quoting.

type JoinClause

type JoinClause struct {
	QueryBlockID       int
	Cross              bool
	Natural            bool
	HasUsing           bool
	Lateral            bool
	UnqualifiedColumns []ColumnReference
	Location           Location
}

JoinClause retains source facts that are specific to an explicit JOIN node. Cross is false for NATURAL and USING joins; UnqualifiedColumns includes only ColumnRef nodes in the JOIN qualification itself.

type LimitClause

type LimitClause struct {
	QueryBlockID  int
	CountPresent  bool
	CountKnown    bool
	Count         int64
	OffsetPresent bool
	OffsetKnown   bool
	Offset        int64
	All           bool
	HasOrderBy    bool
	Location      Location
}

LimitClause retains one PostgreSQL LIMIT/OFFSET or FETCH clause without evaluating non-literal expressions. All is true for LIMIT NULL/LIMIT ALL, which PostgreSQL treats as no limit.

type Location

type Location struct {
	StartOffset int
	EndOffset   int
	Line        int
	Column      int
}

Location identifies a UTF-8 byte range and one-based display coordinates.

type MultipleStatementsError

type MultipleStatementsError struct {
	Count int
}

MultipleStatementsError rejects inputs that could otherwise change the safety boundary of connected EXPLAIN.

func (*MultipleStatementsError) Error

func (e *MultipleStatementsError) Error() string

Error implements error.

type OnConflictAction

type OnConflictAction string

OnConflictAction identifies the PostgreSQL INSERT conflict action retained for static DML auditing.

const (
	OnConflictNone    OnConflictAction = ""
	OnConflictNothing OnConflictAction = "NOTHING"
	OnConflictUpdate  OnConflictAction = "UPDATE"
)

type OrderTerm

type OrderTerm struct {
	Column       ColumnReference
	Direction    string
	Nulls        string
	QueryBlockID int
}

OrderTerm retains PostgreSQL direction and explicit/default NULL ordering.

type OutputBinding

type OutputBinding struct {
	Fields   []*BoundOutputField
	Complete bool
}

OutputBinding preserves output order and whether every output is known. Unknown wildcard sources and ambiguous column names make Complete false.

type ParameterizedSQLError

type ParameterizedSQLError struct {
	Number   int
	Location Location
}

ParameterizedSQLError indicates a PostgreSQL ParamRef such as $1.

func (*ParameterizedSQLError) Error

func (e *ParameterizedSQLError) Error() string

Error implements error.

type PartitionKeyDefinition

type PartitionKeyDefinition struct {
	Strategy string
	Columns  []string
}

PartitionKeyDefinition is the direct-column subset of PostgreSQL's pg_get_partkeydef output. Strategy is RANGE, LIST, or HASH.

func ParsePartitionKeyDefinition

func ParsePartitionKeyDefinition(definition string) (PartitionKeyDefinition, bool)

ParsePartitionKeyDefinition extracts a partition strategy and direct column names from PostgreSQL's pg_get_partkeydef output. Expression keys, explicit collations/operator classes, malformed definitions, and appended statements are unsupported.

type PlanFilterTerm

type PlanFilterTerm struct {
	Column   ColumnReference
	Operator string
}

PlanFilterTerm is one direct column predicate from a native Filter. The parser accepts only constant peers and retains qualifiers for bound matching.

func ParsePlanFilterTerms

func ParsePlanFilterTerms(expression string) ([]PlanFilterTerm, bool)

ParsePlanFilterTerms parses a native Filter as a boolean tree of direct column predicates. Functions, column peers, parameters, NOT, malformed expressions, and appended statements are rejected as a whole.

type PlanJoinEquality

type PlanJoinEquality struct {
	Left  PlanQualifiedColumn
	Right PlanQualifiedColumn
}

PlanJoinEquality is one AST-proven equality between two qualified columns.

func ParsePlanJoinEqualities

func ParsePlanJoinEqualities(expression string) ([]PlanJoinEquality, error)

ParsePlanJoinEqualities returns a flat conjunction of qualified column equalities. OR, ranges, literals, expressions, and unqualified columns yield no result so candidate join paths are never inferred from ambiguous text.

type PlanPredicateConnector

type PlanPredicateConnector string

PlanPredicateConnector identifies the top-level boolean relationship in a PostgreSQL EXPLAIN predicate. OTHER means ordering/access-path inference is unsafe for the retained shape.

const (
	PlanPredicateSingle PlanPredicateConnector = "SINGLE"
	PlanPredicateAnd    PlanPredicateConnector = "AND"
	PlanPredicateOr     PlanPredicateConnector = "OR"
	PlanPredicateOther  PlanPredicateConnector = "OTHER"
)

type PlanPredicateShape

type PlanPredicateShape struct {
	Connector PlanPredicateConnector
	Terms     []PlanPredicateTerm
}

PlanPredicateShape is a conservative projection of one PostgreSQL EXPLAIN Filter/Index Cond expression for transient candidate costing.

func ParsePlanPredicateShape

func ParsePlanPredicateShape(expression string) (PlanPredicateShape, error)

ParsePlanPredicateShape parses an EXPLAIN predicate through pg_query. It returns OTHER for NOT, mixed boolean nesting, expression operands, and other forms that cannot prove B-tree applicability. Scalar constants are retained only as current-statement costing evidence.

type PlanPredicateTerm

type PlanPredicateTerm struct {
	Column       string
	Operator     string
	Kind         PredicateKind
	Value        string
	HasValue     bool
	NumericValue *float64
}

PlanPredicateTerm retains the column and normalized operator required by candidate access-path costing. Constant evidence is transient: it may calibrate the current statement's cost but must not influence persistent index design selection.

type PlanQualifiedColumn

type PlanQualifiedColumn struct {
	Qualifier string
	Column    string
}

PlanQualifiedColumn identifies one qualified column in a native join condition. Unqualified references are intentionally not inferred because a plan node can contain multiple relations with the same column name.

func ParsePlanColumnReferences

func ParsePlanColumnReferences(expression string) ([]PlanQualifiedColumn, error)

ParsePlanColumnReferences returns simple column references contained in one PostgreSQL plan expression. It is used for plan-level index-only coverage; expression semantics are not rewritten or evaluated.

func ParsePlanMinMaxExpression

func ParsePlanMinMaxExpression(expression string) (string, PlanQualifiedColumn, bool, error)

ParsePlanMinMaxExpression recognizes one direct min(column) or max(column) expression. It rejects arithmetic, multiple arguments, and other aggregate functions so bounded B-tree costing remains semantics-preserving.

type Predicate

type Predicate struct {
	Column           ColumnReference
	RightColumn      ColumnReference
	Operator         string
	Kind             PredicateKind
	ColumnComparison bool
	NullComparison   bool
	Location         Location
}

Predicate retains column/operator structure but deliberately omits literal values from persistent index-design input.

type PredicateAtom

type PredicateAtom struct {
	Conditions  []Condition
	Comparisons []Predicate
	Columns     []ColumnReference
	// contains filtered or unexported fields
}

PredicateAtom retains one original Boolean leaf. Conditions preserve source locations; Comparisons contain only ordinary direct-column comparisons. The private immutable AST leaf can supply display text and comparison identity on demand; ordinary parsing does not eagerly render or clone it.

func (PredicateAtom) ExpressionSQL

func (atom PredicateAtom) ExpressionSQL() string

ExpressionSQL renders the original PostgreSQL leaf for display only. It is neither an executable rewrite nor proof of predicate pushdown.

func (PredicateAtom) Identity

func (atom PredicateAtom) Identity(unqualified bool) string

Identity excludes source positions. Removing column qualifiers is safe only when the consumer separately proves that every column belongs to one bound relation occurrence. The private original node is never mutated.

type PredicateClause

type PredicateClause struct {
	QueryBlockID int
	Clause       string
	Branches     [][]PredicateAtom
	Complete     bool
}

PredicateClause preserves the bounded disjunction of conjunctions for one WHERE or JOIN ON clause. Complete=false forbids branch-level implication: negation, unknown Boolean nodes and expansion limits are not flattened away.

type PredicateKind

type PredicateKind string

PredicateKind is the access-path-relevant shape of a predicate.

const (
	// PredicateEquality is an equality or scalar-array equality shape.
	PredicateEquality PredicateKind = "EQUALITY"
	// PredicateRange is a one-sided range shape.
	PredicateRange PredicateKind = "RANGE"
	// PredicateOther is retained without index-order inference.
	PredicateOther PredicateKind = "OTHER"
)

type QueryBlock

type QueryBlock struct {
	ID       int
	ParentID int
	Origin   QueryBlockOrigin
}

QueryBlock identifies one SELECT/DML namespace, its lexical parent, and its structural origin. The root is always block 0 with ParentID -1.

type QueryBlockOrigin

type QueryBlockOrigin string

QueryBlockOrigin identifies why a nested PostgreSQL SELECT owns a query block. Set-operation branches remain distinct for binding but are not counted as subqueries by static rules.

const (
	QueryBlockRoot         QueryBlockOrigin = "ROOT"
	QueryBlockCTE          QueryBlockOrigin = "CTE"
	QueryBlockDerived      QueryBlockOrigin = "DERIVED"
	QueryBlockSubLink      QueryBlockOrigin = "SUBLINK"
	QueryBlockSetBranch    QueryBlockOrigin = "SET_BRANCH"
	QueryBlockInsertSource QueryBlockOrigin = "INSERT_SOURCE"
	QueryBlockOther        QueryBlockOrigin = "OTHER"
)

type QueryDMLFact

type QueryDMLFact struct {
	Kind           QueryDMLFactKind
	QueryBlockID   int
	Clause         string
	FunctionSchema string
	FunctionName   string
	Alias          Identifier
	Column         ColumnReference
	HasPartition   bool
	HasOrder       bool
	ExplicitFrame  bool
	Location       Location
}

QueryDMLFact retains window, LATERAL, ctid, and volatile-filter evidence.

type QueryDMLFactKind

type QueryDMLFactKind string

QueryDMLFactKind identifies source evidence used by DQL/DML warning rules.

const (
	// QueryDMLWindow records one window function call and its resolved window shape.
	QueryDMLWindow QueryDMLFactKind = "WINDOW"
	// QueryDMLLateral records a LATERAL subquery or function range.
	QueryDMLLateral QueryDMLFactKind = "LATERAL"
	// QueryDMLVolatileFilter records a known pg_catalog VOLATILE function in a filter.
	QueryDMLVolatileFilter QueryDMLFactKind = "VOLATILE_FUNCTION_FILTER"
	// QueryDMLCTID records a ctid system-column reference.
	QueryDMLCTID QueryDMLFactKind = "CTID_REFERENCE"
	// QueryDMLTimeTZ records a time with time zone type name.
	QueryDMLTimeTZ QueryDMLFactKind = "TIME_WITH_TIME_ZONE"
	// QueryDMLMoney records a money type name.
	QueryDMLMoney QueryDMLFactKind = "MONEY_TYPE"
)

type QueryExpressionFact

type QueryExpressionFact struct {
	Kind               QueryExpressionFactKind
	QueryBlockID       int
	Clause             string
	Column             ColumnReference
	Operator           string
	OperatorSchema     string
	FunctionSchema     string
	FunctionName       string
	Alias              Identifier
	OperandTypes       []string
	EmptyInputPossible bool
	AggregateFilter    bool
	AggregateOrder     bool
	NamespaceComplete  bool
	MergedColumns      bool
	TargetOffset       int
	Location           Location
}

QueryExpressionFact retains source-scoped expression evidence without resolving PostgreSQL operators, functions, or physical column identities.

type QueryExpressionFactKind

type QueryExpressionFactKind string

QueryExpressionFactKind identifies source evidence used by expression and query-style review rules.

const (
	// QueryExpressionORScalarArray records a same-column equality OR chain.
	QueryExpressionORScalarArray QueryExpressionFactKind = "OR_SCALAR_ARRAY"
	// QueryExpressionMixedJoin records comma and explicit JOIN syntax in one block.
	QueryExpressionMixedJoin QueryExpressionFactKind = "MIXED_JOIN_SYNTAX"
	// QueryExpressionDuplicateAlias records a repeated explicit output alias.
	QueryExpressionDuplicateAlias QueryExpressionFactKind = "DUPLICATE_OUTPUT_ALIAS"
	// QueryExpressionDateLiteral records an untyped string comparison candidate.
	QueryExpressionDateLiteral QueryExpressionFactKind = "DATE_LITERAL_IMPLICIT_CAST"
	// QueryExpressionCountColumn records a direct-column count call.
	QueryExpressionCountColumn QueryExpressionFactKind = "COUNT_COLUMN"
	// QueryExpressionSumResult records a direct-column sum call.
	QueryExpressionSumResult QueryExpressionFactKind = "SUM_RESULT"
	// QueryExpressionAggregateScope records grouping context for aggregate-level resolution.
	QueryExpressionAggregateScope QueryExpressionFactKind = "AGGREGATE_SCOPE"
)

type QueryGroupingFact

type QueryGroupingFact struct {
	Kind            QueryGroupingFactKind
	QueryBlockID    int
	Clause          string
	Column          ColumnReference
	PredicateColumn ColumnReference
	PeerColumn      ColumnReference
	Operator        string
	OperatorSchema  string
	ValueType       string
	ValueExplicit   bool
	Location        Location
}

QueryGroupingFact retains one catalog-gated GROUP BY or HAVING review candidate in its owning query block. PredicateColumn is populated for the WHERE equality behind a redundant grouping candidate; PeerColumn is populated for a HAVING column-to-column comparison.

type QueryGroupingFactKind

type QueryGroupingFactKind string

QueryGroupingFactKind identifies a catalog-gated grouping review candidate.

const (
	// QueryGroupingRedundantEquality is a grouped column constrained by a
	// same-block direct equality to one non-NULL scalar literal.
	QueryGroupingRedundantEquality QueryGroupingFactKind = "REDUNDANT_GROUP_BY_EQUALITY"
	// QueryGroupingHavingRowFilter is a simple, non-aggregate HAVING
	// comparison whose columns are direct grouping keys.
	QueryGroupingHavingRowFilter QueryGroupingFactKind = "HAVING_ROW_FILTER_CANDIDATE"
)

type QueryJoinFact

type QueryJoinFact struct {
	Kind                  QueryJoinFactKind
	QueryBlockID          int
	Clause                string
	JoinType              string
	Relation              RelationRef
	LeftRelations         []RelationRef
	RightRelations        []RelationRef
	NullableRelations     []RelationRef
	PreservedRelations    []RelationRef
	JoinPredicates        []QueryJoinPredicate
	NullRejecting         []QueryJoinNullPredicate
	References            []ColumnReference
	Columns               []ColumnReference
	RelationsComplete     bool
	ExpressionsComplete   bool
	RelationReferenced    bool
	HasUnqualifiedStar    bool
	HasPagination         bool
	ProjectionIncludesAll bool
	Location              Location
}

QueryJoinFact retains only query-block-scoped source evidence needed by the catalog-backed query/join rules. Complex or derived relation inputs are marked incomplete so absence of metadata cannot become a proof.

type QueryJoinFactKind

type QueryJoinFactKind string

QueryJoinFactKind identifies catalog-backed query and join review evidence.

const (
	// QueryJoinOuter records an outer join and WHERE predicates that syntactically
	// reject NULL-extended rows from one or more of its nullable relations.
	QueryJoinOuter QueryJoinFactKind = "OUTER_JOIN"
	// QueryJoinNatural records a NATURAL join whose current implicit keys require
	// complete catalogs for both inputs.
	QueryJoinNatural QueryJoinFactKind = "NATURAL_JOIN"
	// QueryJoinUnusedOuter records a directly nullable outer-join relation and
	// all references that can affect whether removing it preserves semantics.
	QueryJoinUnusedOuter QueryJoinFactKind = "UNUSED_OUTER_JOIN"
	// QueryJoinLimitOrder records query-block-local pagination and ORDER BY keys.
	QueryJoinLimitOrder QueryJoinFactKind = "LIMIT_ORDER"
	// QueryJoinDistinct records an ordinary SELECT DISTINCT projection.
	QueryJoinDistinct QueryJoinFactKind = "DISTINCT"
)

type QueryJoinNullPredicate

type QueryJoinNullPredicate struct {
	Column        ColumnReference
	Peer          ColumnReference
	Operator      string
	ValueType     string
	ValueExplicit bool
	Clause        string
	Location      Location
}

QueryJoinNullPredicate is a syntactic null-rejection candidate. The optimizer must bind its column and validate built-in type/operator semantics before use.

type QueryJoinPredicate

type QueryJoinPredicate struct {
	Left     ColumnReference
	Right    ColumnReference
	Operator string
	Location Location
}

QueryJoinPredicate is a direct, unqualified-operator column equality retained for join multiplicity proofs. It does not by itself prove operator semantics.

type RelationBinding

type RelationBinding struct {
	Reference    RelationRef
	OID          uint32
	NamespaceOID uint32
	IsCTE        bool
}

RelationBinding associates one source reference with an OID or CTE scope.

type RelationMetadata

type RelationMetadata struct {
	OID          uint32
	NamespaceOID uint32
	Schema       string
	Name         string
	// Columns is optional catalog order; nil means column metadata is unavailable.
	Columns []ColumnMetadata
}

RelationMetadata is the binder-facing PostgreSQL catalog identity.

type RelationRef

type RelationRef struct {
	Catalog Identifier
	Schema  Identifier
	Name    Identifier
	Alias   Identifier
	// HasColumnAliases means a positional alias list changes exposed column names.
	HasColumnAliases bool `json:",omitempty"`
	// WriteTarget distinguishes a DML target from a readable CTE/table source.
	WriteTarget  bool
	QueryBlockID int
	Location     Location
}

RelationRef is an unbound PostgreSQL relation reference. OIDs are populated later by the connected binder.

type RowLockClause

type RowLockClause struct {
	QueryBlockID int
	Strength     string
	WaitPolicy   string
}

RowLockClause retains one SELECT row-locking clause. PostgreSQL exposes no source location for this raw AST node, so diagnostics use statement scope.

type SelectClause

type SelectClause struct {
	// WherePresent records syntax independently of predicate conversion support.
	WherePresent bool
	// HasFrom distinguishes relation queries from SELECT constants.
	HasFrom                bool
	QueryBlockID           int
	Distinct               bool
	DistinctOn             bool
	HasOrderBy             bool
	DistinctOnFingerprints []string
	OrderByFingerprints    []string
}

SelectClause retains query-block-level DISTINCT and ordering facts.

type SetOperationTerm

type SetOperationTerm struct {
	QueryBlockID int
	Operation    string
	All          bool
}

SetOperationTerm retains a UNION, INTERSECT, or EXCEPT node and whether ALL preserves duplicates at that node.

type Statement

type Statement struct {
	SQL string
	// StaticAuditFacts contains source-only advisory evidence, independent of index design.
	StaticAuditFacts []StaticAuditFact
	// QueryExpressionFacts retains scoped expression and query-style evidence.
	QueryExpressionFacts []QueryExpressionFact
	// QueryJoinFacts retains join, projection and uniqueness review evidence.
	QueryJoinFacts []QueryJoinFact
	// QueryGroupingFacts retains scoped GROUP BY and HAVING review evidence.
	QueryGroupingFacts []QueryGroupingFact
	// QueryDMLFacts retains window, LATERAL, ctid, and volatile-filter evidence.
	QueryDMLFacts []QueryDMLFact
	// FunctionCalls contains source-located function calls across all query blocks.
	FunctionCalls []FunctionCall
	// InsertTargetColumns preserves only explicitly supplied root INSERT names.
	InsertTargetColumns []Identifier
	// InsertValueDefaults records DEFAULT by VALUES row and ordinal. Without an
	// explicit target list these positions have no inferred catalog-column mapping.
	InsertValueDefaults [][]bool
	// InsertOverride is USER, SYSTEM, or empty when no OVERRIDING clause exists.
	InsertOverride string
	// UpdateAssignments retains root UPDATE and ON CONFLICT target assignments.
	UpdateAssignments []ColumnAssignment
	// DMLScopes retains query-block-local UPDATE/DELETE source evidence.
	DMLScopes         []DMLScope `json:"-"`
	Kind              StatementKind
	Location          Location
	Features          []Feature
	CTEs              []Identifier
	CTEDefinitions    []CTEDefinition
	QueryBlocks       []QueryBlock
	Relations         []RelationRef
	Projection        []Expression
	ProjectionColumns []ColumnReference
	Predicates        []Predicate
	Conditions        []Condition
	OrderBy           []OrderTerm
	GroupByTerms      []ClauseTerm
	OrderByTerms      []ClauseTerm
	JoinClauses       []JoinClause
	SelectClauses     []SelectClause
	Limits            []LimitClause
	RowLocks          []RowLockClause
	WherePresent      bool
	// InsertColumnsSpecified is true when a root INSERT has an explicit target
	// column list. InsertSourcePresent excludes INSERT DEFAULT VALUES.
	InsertColumnsSpecified  bool
	InsertSourcePresent     bool
	InsertSelectSource      bool
	InsertTargetColumnCount int
	InsertRowValueCounts    []int
	OnConflictAction        OnConflictAction
	OnConflictLocation      Location
	SetOperations           []SetOperationTerm
	NativeNodeTypes         []string
	// contains filtered or unexported fields
}

Statement is the PostgreSQL-owned semantic skeleton. It deliberately does not expose pg_query protobuf nodes or any MySQL AST type.

func Parse

func Parse(sql string) (*Statement, error)

Parse accepts exactly one PostgreSQL statement, rejects ParamRef, and converts the pg_query tree into the PostgreSQL-owned semantic skeleton.

func (*Statement) DirectColumnOrigin

func (statement *Statement) DirectColumnOrigin(ref ColumnReference) (ColumnOrigin, bool)

DirectColumnOrigin extends DirectColumnProvenance with the individual CTE references and whether resolution entered an enclosing lexical namespace.

func (*Statement) DirectColumnProvenance

func (statement *Statement) DirectColumnProvenance(ref ColumnReference) (ColumnReference, bool)

DirectColumnProvenance proves a column's physical query-block origin through direct SELECT projections. It rejects ambiguous names, expressions and materialization, cardinality or null-extension barriers; it does not prove predicate pushdown or index applicability. The returned reference is a value copy, and none of this conversion-only evidence enters Statement JSON.

func (*Statement) DirectUsingComparisons

func (statement *Statement) DirectUsingComparisons() []Predicate

DirectUsingComparisons returns independent equality operands for INNER JOIN USING with two directly named sources. It does not infer merged output columns, NATURAL joins, join aliases, or outer-join row preservation.

func (*Statement) FunctionCallSQL

func (statement *Statement) FunctionCallSQL(call FunctionCall) (string, bool)

FunctionCallSQL returns the complete source spelling of one AST-recorded function call, including its argument list. FunctionCall.Location continues to identify the function name only. PostgreSQL's lexer distinguishes quoted strings/identifiers and comments from parentheses; no SQL is executed or reparsed, and unknown or malformed source positions are rejected.

func (*Statement) HasFeature

func (statement *Statement) HasFeature(feature Feature) bool

HasFeature reports whether a feature was retained during conversion.

func (*Statement) NotInSubqueryNonNullInputs

func (statement *Statement) NotInSubqueryNonNullInputs(condition Condition) ([]ColumnReference, bool)

NotInSubqueryNonNullInputs returns the direct output columns that still need catalog non-null proof. A known empty slice proves all outputs non-null from constants or built-in COALESCE fallbacks. False means output nullability is unproven. The returned slice is caller-owned and preserves query-block scope.

func (*Statement) NotInSubqueryOutputColumns

func (statement *Statement) NotInSubqueryOutputColumns(condition Condition) ([]ColumnReference, bool)

NotInSubqueryOutputColumns returns a copy of the complete, direct-column projection of this NOT IN condition's subquery. False means output provenance or null preservation is unproven, not that the output is nullable. Correlated filters are allowed; column resolution must stay in the returned query block. This evidence is intentionally not serialized with Statement.

func (*Statement) PredicateClauses

func (statement *Statement) PredicateClauses() []PredicateClause

PredicateClauses returns caller-owned Boolean evidence collected from the original AST. It does not reparse SQL, resolve names, or infer index access.

func (*Statement) QueryBlockSQL

func (statement *Statement) QueryBlockSQL(block int) (string, bool)

QueryBlockSQL restores a complete SELECT block from its immutable native syntax, including correlation predicates. It normalizes formatting and does not claim byte-for-byte source preservation or execute/reparse the SQL.

func (*Statement) ScalarSubquerySQL

func (statement *Statement) ScalarSubquerySQL(block int, location Location) (string, bool)

ScalarSubquerySQL restores a complete scalar SELECT at its recorded location in the owning query block. Formatting is normalized; correlation and nested SQL remain intact. The native syntax is read-only and no SQL is reparsed.

type StatementKind

type StatementKind string

StatementKind identifies a supported PostgreSQL root statement.

const (
	// StatementSelect is a SELECT, including a set-operation root.
	StatementSelect StatementKind = "SELECT"
	// StatementInsert is INSERT.
	StatementInsert StatementKind = "INSERT"
	// StatementUpdate is UPDATE.
	StatementUpdate StatementKind = "UPDATE"
	// StatementDelete is DELETE.
	StatementDelete StatementKind = "DELETE"
	// StatementMerge is MERGE.
	StatementMerge StatementKind = "MERGE"
)

type StaticAuditFact

type StaticAuditFact struct {
	Kind         string
	QueryBlockID int
	Clause       string
	Column       ColumnReference
	Operator     string
	Location     Location
}

StaticAuditFact is source evidence for an advisory that needs no catalog or plan. Kind names identify syntax facts, not a database execution strategy.

type SyntaxError

type SyntaxError struct {
	Cause error
}

SyntaxError wraps a pg_query parser failure.

func (*SyntaxError) Error

func (e *SyntaxError) Error() string

Error implements error.

func (*SyntaxError) Unwrap

func (e *SyntaxError) Unwrap() error

Unwrap exposes the parser cause.

type UnsupportedStatementError

type UnsupportedStatementError struct {
	NodeType string
}

UnsupportedStatementError identifies an unsupported root parse node.

func (*UnsupportedStatementError) Error

func (e *UnsupportedStatementError) Error() string

Error implements error.

Jump to

Keyboard shortcuts

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