Documentation
¶
Overview ¶
Package statement parses SQL through the real PostgreSQL grammar (wasilibs/go-pgquery, Wasm libpg_query) and reports the facts the engine's front door needs. In Phase 1 that is a statement-type gate only: which kind of statement this is and, for ALTER TABLE, which table it targets. No schema model, no classification.
Two canonical forms coexist deliberately: this package's deparser prints grammar-canonical SQL (e.g. varchar(50)) for formatting, while pkg/schemadiff models carry server-decompiled text (character varying(50)) for comparison. The two canons never mix: models only ever compare server output against server output, and deparser output must not feed a model comparison or a schema fingerprint.
Index ¶
- Variables
- func AddColumnProbes(sql, schema, table string) (map[string]AddColumnProbe, error)
- func AddNotValid(sql string, naming ConstraintNaming) (rewritten, constraint string, err error)
- func Canonical(sql string) (string, error)
- func CheckNoComments(sql string) error
- func ColumnConversions(sql string) (map[string]string, error)
- func Concurrently(sql string) (string, error)
- func HasRowSecurityDeclaration(sql string) (bool, error)
- func ImplicitRelationNames(sql string) ([]string, error)
- func Qualify(sql, schema string) (string, error)
- func QualifyForeignKeyReferences(sql, schema string) (string, error)
- func RetargetRelation(sql, schema, table string) (string, error)
- func SameOpsExceptTarget(gated, retargeted string) error
- type AddColumnProbe
- type AddColumnProof
- type ConstraintKind
- type ConstraintNaming
- type ConversionNames
- type DefaultKind
- type DesiredFile
- type DesiredSchema
- type DesiredWithRowSecurity
- type IndexRelation
- type IndexRelationKind
- type IndexTarget
- type Kind
- type Op
- type OpKind
- type QualifiedName
- type RowSecurityChange
- type SourceStatement
- type Statement
- func (s Statement) BuildsIndex() bool
- func (s Statement) Cascades() bool
- func (s Statement) Concurrent() bool
- func (s Statement) IndexRelation() IndexRelation
- func (s Statement) IndexTarget() IndexTarget
- func (s Statement) Kind() Kind
- func (s Statement) RenamedTo() string
- func (s Statement) SQL() string
- func (s Statement) Schema() string
- func (s Statement) Table() string
- type StorageParam
- type TransactionControl
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrConversionRendering is returned when a USING expression, rendered // through the deparser, does not come back as the expression it was // rendered from: the rendering cannot be proven to be the user's // expression, so it is not handed to anything that would run it. ErrConversionRendering = errors.New("USING expression does not round-trip through the deparser") // ErrConversionRepeated is returned when one ALTER TABLE retypes the // same column with USING more than once; the copy can carry only one // expression per column, and the server itself refuses the statement. ErrConversionRepeated = errors.New("column is retyped with USING more than once") // ErrConversionForeignColumn is returned when a USING expression refers // to anything but the bare name of the column it retypes: another // column, a qualified name, or a whole-row reference. The copy runs the // expression over the source row, where every column is in reach, but // the stream's catch-up writes one column value at a time, and a value // that depends on a neighbouring column cannot be converted from the // column alone. ErrConversionForeignColumn = errors.New("USING expression refers to a column other than the one it retypes") )
var ( // ErrParseDesired is returned when the input is not valid PostgreSQL // syntax, before any admission rule runs. It separates a syntax error // from an admission refusal; the parser's own message is joined to it. ErrParseDesired = errors.New("parse desired schema") // ErrEmptyDesired is returned when the input contains no statements. ErrEmptyDesired = errors.New("desired schema contains no statements") // ErrNoCreateTable is returned when the input has no CREATE TABLE. ErrNoCreateTable = errors.New("desired schema must contain a CREATE TABLE") // ErrMultipleCreateTables is returned for more than one CREATE TABLE: // the engine is single-table scoped. ErrMultipleCreateTables = errors.New("desired schema must contain exactly one CREATE TABLE") // ErrDisallowedStatement is returned for any statement kind other than // CREATE TABLE / CREATE INDEX. The desired file is executed verbatim on // a scratch schema, so only pure schema definition is admitted. ErrDisallowedStatement = errors.New("statement kind not allowed in a desired schema") // ErrQualifiedName is returned when a statement schema-qualifies its // target. Desired files are schema-relative; the live schema comes from // the caller, and qualification could escape the scratch schema. ErrQualifiedName = errors.New("desired schema statements must use unqualified names") // ErrConcurrentIndex is returned for CREATE INDEX CONCURRENTLY, which // cannot run inside the scratch transaction. ErrConcurrentIndex = errors.New("CONCURRENTLY cannot be used in a desired schema") // ErrWrongIndexTarget is returned when an index targets a table other // than the desired CREATE TABLE. ErrWrongIndexTarget = errors.New("index must target the desired table") )
Typed refusals for desired-state schema files. Each names one rule of the declarative front door; the caller branches with errors.Is, never on text.
var ( // ErrNotAlterTable is returned when relation retargeting is requested for // anything other than a single ALTER TABLE. ErrNotAlterTable = errors.New("statement is not ALTER TABLE") // ErrRetargetMismatch is returned when the retargeted statement, re-parsed, // differs from the gated statement in anything but its target relation. ErrRetargetMismatch = errors.New("retargeted statement differs beyond its target relation") )
var ( // ErrNotRewritable is returned when the statement kind has no // CONCURRENTLY form to rewrite to. ErrNotRewritable = errors.New("statement has no concurrent form") // ErrNotValidNotApplicable is returned when the statement is not a // single ADD CHECK / ADD FOREIGN KEY that could take NOT VALID. ErrNotValidNotApplicable = errors.New("statement cannot take NOT VALID") )
Typed refusals for advisory rewrites. The rewriters flip one syntactic flag and deparse — no semantics are derived; a statement that cannot be rewritten that way is refused with one of these.
var ErrCommentLoss = errors.New("input contains comments, which formatting would discard")
ErrCommentLoss is returned when an operation that reprints SQL through the deparser would silently discard comments. The parser drops comments at parse time, so a formatter cannot carry them; refusing is the fail-closed alternative to destroying documentation in a source-of-truth file.
var ErrNotCreateTable = errors.New("statement is not a CREATE TABLE")
ErrNotCreateTable is returned when the statement handed to ImplicitRelationNames is not a single CREATE TABLE.
var ErrNotOneStatement = errors.New("input must contain exactly one SQL statement")
ErrNotOneStatement is returned by ParseOne when the input does not contain exactly one SQL statement.
var ErrPolicyRelationDependency = errors.New("policy relation dependencies are not supported in desired row security")
ErrPolicyRelationDependency refuses policy subqueries that read relations until desired-state materialization can preserve their dependency identities.
var ErrRepeatedAddColumn = errors.New("the statement adds the same column more than once")
ErrRepeatedAddColumn means an ALTER TABLE adds the same column name in more than one subcommand. Each addition can rewrite the table or not on its own terms, so one proof cannot stand for both.
var ErrRowSecurityChange = errors.New("invalid row security operation")
ErrRowSecurityChange identifies SQL outside a table-local RLS operation.
var ErrRowSecurityDeclaration = errors.New("desired row security requires one explicit ENABLE or DISABLE on the desired table")
ErrRowSecurityDeclaration reports an incomplete or contradictory RLS declaration.
var ErrRowSecurityForeignKey = errors.New("foreign keys are not supported in desired row security")
ErrRowSecurityForeignKey refuses a foreign key in a row-security desired file. The row-security scratch build creates no stand-in for a referenced table, so a foreign key there would bind to the live table and lock it.
var ErrRowSecurityTableDefinitionRequired = errors.New("desired row security requires a CREATE TABLE definition")
ErrRowSecurityTableDefinitionRequired identifies a missing table definition in an RLS file.
Functions ¶
func AddColumnProbes ¶ added in v0.4.0
func AddColumnProbes(sql, schema, table string) (map[string]AddColumnProbe, error)
AddColumnProbes returns, for each ADD COLUMN of an ALTER TABLE, a single-command ALTER TABLE that adds the same column to schema.table, keyed by column name. A probe keeps everything that decides whether the server rewrites the table to add the column: its type and collation, its DEFAULT, NOT NULL, and identity. It drops the inline CHECK, UNIQUE, PRIMARY KEY, REFERENCES, and EXCLUDE constraints, which scan the table or build an index but never rewrite it, and which a probe table cannot always carry, and an identity's SEQUENCE NAME, so the probe's sequence is created beside the probe table rather than in the named schema. A generated column gets no probe: the planner routes it by its generation alone, and its expression may name a column the same change adds, which the probe table does not have. A statement other than ALTER TABLE returns ErrNotAlterTable, and one that adds a column name twice returns ErrRepeatedAddColumn; an ALTER TABLE that adds no column, or only generated ones, returns an empty map.
func AddNotValid ¶
func AddNotValid(sql string, naming ConstraintNaming) (rewritten, constraint string, err error)
AddNotValid rewrites a single-command ALTER TABLE ... ADD CONSTRAINT (CHECK or FOREIGN KEY) to its NOT VALID form and returns the rewritten statement plus the constraint name for the follow-up VALIDATE CONSTRAINT step.
The VALIDATE step has to name the constraint, so an unnamed constraint is given the name PostgreSQL would choose (defaultConstraintName) and the rewrite states it. The server takes its first choice unless a constraint in the schema already holds it, and then tries the label with 1, 2, ... appended; naming.Taken lets the rewrite make the same moves. A name the rewrite states that the table already uses fails the NOT VALID step with a duplicate-object error, before anything is added.
func Canonical ¶
Canonical reprints one statement through the PostgreSQL deparser: grammar-canonical spelling, unnecessary quoting dropped. Commented input is refused (ErrCommentLoss): the parser drops comments, and reprinting must never silently discard content. It is the rendering the plan report carries, so both front doors describe the same change with the same string. Deparser output never feeds a model comparison or a schema fingerprint (see the package comment); the plan report's fingerprint is a plan identity, not a schema fingerprint.
func CheckNoComments ¶
CheckNoComments scans sql with the PostgreSQL lexer and returns ErrCommentLoss when it contains any SQL (--) or C-style (/* */) comment. A scan failure is surfaced to the caller, never guessed around.
func ColumnConversions ¶ added in v0.4.0
ColumnConversions returns, for each column that sql's ALTER TABLE retypes with a USING clause, the USING expression as the deparser renders it: the SQL text a SELECT list can carry in the column's place. The map is keyed by column name and is empty when no subcommand carries USING.
PostgreSQL keeps no record of a USING expression once ALTER COLUMN TYPE has run: the catalog describes the column's new type, not how the old values became it. The copy of a retyped column therefore has nowhere to take the conversion from but the statement itself, and this is the one place that reads it. The expression is extracted, not edited: the parse tree's node is rendered as the single target of a SELECT and the SELECT keyword removed, and the result is proven by parsing it back as a SELECT target and rendering it again to the same text. Nothing is derived from the expression's meaning, but one thing is read off its shape: every column reference in it must be the bare name of the column it retypes, because the catch-up that follows the copy converts one column value at a time and has no neighbouring column to hand the expression (ErrConversionForeignColumn). A statement that is not a single ALTER TABLE is ErrNotAlterTable.
func Concurrently ¶
Concurrently returns sql rewritten to its CONCURRENTLY form: CREATE INDEX, DROP INDEX, REINDEX, or ALTER TABLE ... DETACH PARTITION. The rewrite flips the grammar's concurrency flag and deparses — nothing else changes. A statement already concurrent comes back canonicalized.
func HasRowSecurityDeclaration ¶ added in v0.4.0
HasRowSecurityDeclaration reports whether sql declares row security without admitting it. Use it to ask that question alone, for example to skip input that declares no row security, or to inspect a single statement rather than a desired file. To route a desired file to its planner, use ParseDesiredFile, which makes this check and applies the matching front door in one parse. The result is not an admission: execution still needs a value from ParseDesiredWithRowSecurity or ParseDesiredFile.
func ImplicitRelationNames ¶ added in v0.3.0
ImplicitRelationNames returns the first-choice relation names PostgreSQL will use for one CREATE TABLE statement, in the table's own schema: indexes for PRIMARY KEY, UNIQUE, and EXCLUDE constraints, and sequences for serial and identity columns. A named constraint's index takes the constraint name verbatim; an unnamed one takes the server's generated name (`<table>_pkey`, `<table>_<cols>_key`, `<table>_<cols>_excl`, truncated to the identifier byte budget the way the server truncates), where `<cols>` covers every index column — the INCLUDE columns too — with a repeated column or expression name numbered the way the server numbers it. A sequence takes `<table>_<column>_seq` under the same truncation rules, or the name an identity column's SEQUENCE NAME option states; a SEQUENCE NAME qualified into another schema is born outside the table's schema and is not one of its names. Names are returned in definition order and are not de-duplicated: two constraints whose first choices coincide both appear, so a claim map sees the conflict.
func Qualify ¶
Qualify returns sql with its target relation qualified by schema; an empty schema strips an existing qualification instead. It supports exactly one CREATE TABLE, CREATE INDEX, or ALTER TABLE statement. This touches qualification only — no semantics are ever derived or transformed at the AST level (that is execute-and-introspect's job).
func QualifyForeignKeyReferences ¶ added in v0.4.0
QualifyForeignKeyReferences returns an ALTER TABLE statement with every unqualified table its added foreign keys reference qualified by schema. A planned foreign-key add names its referenced table as the desired file does, unqualified, which resolves through the search_path of whatever session runs it; the referenced table lives in the target schema, so the plan names it there and the statement binds the same table wherever it runs. An already-qualified reference is left as written. Like Qualify, this touches qualification only.
func RetargetRelation ¶ added in v0.4.0
RetargetRelation returns sql with its ALTER TABLE target relation replaced by schema.table and reprinted through the PostgreSQL deparser. It is the one AST edit the copy-and-swap route permits: the gated statement names the source table, and the shadow builder needs the same operations against the empty shadow. Only the target RangeVar changes — every other node, including a REFERENCES or expression that names the source table, is left exactly as the user wrote it.
func SameOpsExceptTarget ¶ added in v0.4.0
SameOpsExceptTarget proves that two ALTER TABLE syntax trees deparse identically after normalizing the gated target to the retargeted relation. The shadow builder runs it on the gated statement and its retargeted form before executing anything on the shadow (ST-7 with the shadow as the sole permitted target).
Types ¶
type AddColumnProbe ¶ added in v0.4.0
AddColumnProbe is the probe for one ADD COLUMN: SQL adds the same column to the probe table, and IfNotExists records that the subcommand is skipped when the column already exists.
type AddColumnProof ¶ added in v0.4.0
type AddColumnProof string
AddColumnProof is what the server proved about adding one column to a table by its probe: whether the table is rewritten, and if so what rewrites it.
const ( // AddColumnInPlace means the column is added without rewriting the table; // any default it has is stored in the catalog. AddColumnInPlace AddColumnProof = "in-place" // AddColumnDefaultRewrites means the table is rewritten to compute the // column's default for every row; the column's type alone adds in // place. AddColumnDefaultRewrites AddColumnProof = "default-rewrites" // AddColumnTypeRewrites means the column's type alone rewrites the table, // because a domain with constraints is checked against every row. AddColumnTypeRewrites AddColumnProof = "type-rewrites" // AddColumnUnproven means the proof needed a lock another session held, so // the server answered neither way. AddColumnUnproven AddColumnProof = "unproven" )
type ConstraintKind ¶
type ConstraintKind int
ConstraintKind names the constraint families the classifier routes differently.
const ( ConstraintUnrecognized ConstraintKind = iota ConstraintPrimaryKey ConstraintUnique ConstraintCheck ConstraintForeignKey ConstraintNotNull )
The constraint families ParseOps distinguishes. ConstraintUnrecognized (e.g. EXCLUDE) has no known safe pattern and is refused.
type ConstraintNaming ¶ added in v0.4.0
type ConstraintNaming struct {
// Columns are the table's live columns. A bare name in a CHECK reads
// as a column when the table has one by that name and otherwise, when
// it is the table's own name, as the table's whole row. Nil reads every
// bare name as a column.
Columns map[string]bool
// Taken are the names of the constraints already in the table's
// schema, every table's and domain's alike: the server passes over each
// of them when it picks a name.
Taken map[string]bool
}
ConstraintNaming is what the server consults when it names an unnamed constraint, read from the live table. The zero value knows nothing: a bare name reads as a column and no name counts as taken, which yields the server's first choice.
type ConversionNames ¶ added in v0.4.0
type ConversionNames struct {
Functions []QualifiedName
Operators []QualifiedName
Types []QualifiedName
Collations []QualifiedName
}
ConversionNames are the names a USING expression leaves to the catalog to resolve, by kind, each list sorted and without repeats. They are what a resolution of the expression depends on: the function names it calls, the operator names it applies, the type names it casts to, and the collations it names. The lists say which names the expression spells, not which catalog objects they resolved to; resolving them is the server's job, and what the server would resolve them to is what a fingerprint of the catalog entries under these names pins.
func ConversionNamesOf ¶ added in v0.4.0
func ConversionNamesOf(expr string) (ConversionNames, error)
ConversionNamesOf reads the names out of a USING expression as ColumnConversions rendered it: the expression is parsed as the one target of a SELECT and its tree walked for every function call, operator, type cast, and COLLATE clause. The walk reads the tree's shape, not its meaning, so it reports what the grammar wrote down and nothing the server adds while it resolves: a BETWEEN is the two comparison operators the server rewrites it to, a CASE with an operand compares with the unqualified `=`, and the grammar's own spellings — `integer` parsed as pg_catalog.int4, LIKE as the `~~` operator — appear as the grammar spells them. What the server resolves without a name the expression spelled — an implicit cast between two types, the comparison GREATEST and LEAST pick for a type — is not in the result.
func (ConversionNames) Empty ¶ added in v0.4.0
func (n ConversionNames) Empty() bool
Empty reports whether the expression spelled no name of any kind.
type DefaultKind ¶
type DefaultKind int
DefaultKind classifies the DEFAULT expression shape of an added column. The shape alone cannot settle whether PostgreSQL rewrites the table: a constant still rewrites every row when the column's type is a domain with constraints, and a non-volatile expression such as now() does not. The server answers that (preflight.AddColumnRewrites); without its answer, any expression is treated as volatile, conservatively.
const ( // DefaultNone: no DEFAULT clause. DefaultNone DefaultKind = iota // DefaultConstant: a literal (possibly type-cast), which the catalog // stores unless the column's type forces a rewrite. DefaultConstant // DefaultExpression: anything else — function calls, identity, serial. // The engine does not evaluate volatility offline; without the // server's answer it assumes the worst. DefaultExpression )
The default shapes an added column can carry.
type DesiredFile ¶ added in v0.4.0
type DesiredFile struct {
// contains filtered or unexported fields
}
DesiredFile is one desired-state schema file admitted through exactly one of the two declarative front doors: ParseDesired for a table with its indexes, or ParseDesiredWithRowSecurity for a table that also declares row security. The choice is made once, by ParseDesiredFile, so a consumer never re-derives which planner owns a file. Only ParseDesiredFile constructs a non-zero value, and exactly one of Schema and RowSecurity reports ok.
DesiredFile is a router over those two proof types, not a proof type itself: no planner or executor accepts it. Hand the value Schema or RowSecurity returns to the matching planner.
func ParseDesiredFile ¶ added in v0.4.0
func ParseDesiredFile(sql string) (DesiredFile, error)
ParseDesiredFile parses sql once and admits it through the front door its statements select. A file that declares row security (a policy, a policy comment, or ENABLE, DISABLE, FORCE or NO FORCE ROW LEVEL SECURITY) must pass ParseDesiredWithRowSecurity's rules; any other file must pass ParseDesired's. Refusals are those front doors' typed errors, unchanged; input that is not valid SQL is refused with ErrParseDesired.
Example ¶
ExampleParseDesiredFile routes a desired-state schema file to the planner that owns it. Exactly one of RowSecurity and Schema reports ok after a nil error; hand that value to diffplan.PlanWithRowSecurity or diffplan.Plan.
package main
import (
"errors"
"fmt"
"github.com/block/pg-sprite/pkg/statement"
)
func main() {
for _, sql := range []string{
"CREATE TABLE documents (id bigint PRIMARY KEY);\n" +
"CREATE INDEX documents_id_idx ON documents (id);",
"CREATE TABLE documents (id bigint PRIMARY KEY);\n" +
"ALTER TABLE documents ENABLE ROW LEVEL SECURITY;",
"CREATE TABLE documents (id bigint PRIMARY KEY);\n" +
"ALTER TABLE documents ADD COLUMN title text;",
"CREATE TABLE documents (",
} {
file, err := statement.ParseDesiredFile(sql)
switch {
case errors.Is(err, statement.ErrParseDesired):
fmt.Println("not valid SQL")
continue
case errors.Is(err, statement.ErrDisallowedStatement):
fmt.Println("refused:", statement.ErrDisallowedStatement)
continue
case err != nil:
fmt.Println("refused:", err)
continue
}
if _, ok := file.RowSecurity(); ok {
fmt.Printf("row-security planner: %s, %d statements\n", file.Table(), len(file.Statements()))
continue
}
if _, ok := file.Schema(); ok {
fmt.Printf("ordinary planner: %s, %d statements\n", file.Table(), len(file.Statements()))
}
}
}
Output: ordinary planner: documents, 2 statements row-security planner: documents, 2 statements refused: statement kind not allowed in a desired schema not valid SQL
func (DesiredFile) RowSecurity ¶ added in v0.4.0
func (f DesiredFile) RowSecurity() (DesiredWithRowSecurity, bool)
RowSecurity returns the row-security planner input when the file declares row security.
func (DesiredFile) Schema ¶ added in v0.4.0
func (f DesiredFile) Schema() (DesiredSchema, bool)
Schema returns the ordinary planner input when the file declares no row security. The zero DesiredFile admitted nothing, so it reports neither.
func (DesiredFile) Statements ¶ added in v0.4.0
func (f DesiredFile) Statements() []Statement
Statements returns the admitted statements in the order the admitted value's Statements reports them. The slice is a copy.
func (DesiredFile) Table ¶ added in v0.4.0
func (f DesiredFile) Table() string
Table returns the unqualified desired table, the same name the admitted value's Table reports.
type DesiredSchema ¶
type DesiredSchema struct {
// contains filtered or unexported fields
}
DesiredSchema proves a desired-state schema file passed the set-level admission rules: exactly one unqualified CREATE TABLE plus any number of CREATE INDEX statements on that table, none of them CONCURRENTLY, and every table a foreign key references named unqualified. Only ParseDesired produces a non-zero value.
Statement SQL is canonical (parsed and deparsed through the PostgreSQL grammar), one statement per entry, held in execution order: the CREATE TABLE first, the indexes in input order after it.
func ParseDesired ¶
func ParseDesired(sql string) (DesiredSchema, error)
ParseDesired parses a desired-state schema file and admits only what the declarative front door can execute on a scratch schema: one unqualified CREATE TABLE and unqualified, non-concurrent CREATE INDEX statements on it. Foreign keys are admitted for planning when the table they reference is unqualified; desired-state execution refuses every foreign-key change (see docs/limitations.md). Anything else is refused with a typed error.
func (DesiredSchema) HasForeignKeys ¶ added in v0.4.0
func (ds DesiredSchema) HasForeignKeys() bool
HasForeignKeys reports whether the CREATE TABLE declares a foreign key, a self-reference included.
func (DesiredSchema) ReferencedTables ¶ added in v0.4.0
func (ds DesiredSchema) ReferencedTables() []string
ReferencedTables returns the unqualified names of the other tables the CREATE TABLE's foreign keys reference, sorted and distinct; a self-reference is not listed. The slice is a copy.
func (DesiredSchema) Statements ¶
func (ds DesiredSchema) Statements() []Statement
Statements returns the admitted statements in execution order: the CREATE TABLE first, the indexes in input order after it — an index cannot be built before its table exists, and every consumer replays this order verbatim. The slice is a copy: mutating it cannot invalidate the admission proof the value carries.
func (DesiredSchema) Table ¶
func (ds DesiredSchema) Table() string
Table returns the unqualified name of the single CREATE TABLE target.
type DesiredWithRowSecurity ¶ added in v0.4.0
type DesiredWithRowSecurity struct {
// contains filtered or unexported fields
}
DesiredWithRowSecurity proves declaration syntax for scratch inspection and the dedicated atomic RLS executor. It is distinct from DesiredSchema; generic native and create executors cannot accept it. Live safety needs executor checks. The explicit parse entry point owns the complete table-local RLS definition, including an empty policy set. Only ParseDesiredWithRowSecurity constructs it.
func ParseDesiredWithRowSecurity ¶ added in v0.4.0
func ParseDesiredWithRowSecurity(sql string) (DesiredWithRowSecurity, error)
ParseDesiredWithRowSecurity admits table/index definitions followed by RLS settings, policies, and policy comments. It requires explicit ENABLE/DISABLE; FORCE/NO FORCE is optional and cannot be declared twice. Other ALTER commands, qualified targets, and policy queries reading relations are refused.
func (DesiredWithRowSecurity) Statements ¶ added in v0.4.0
func (d DesiredWithRowSecurity) Statements() []Statement
Statements returns a defensive copy in scratch execution order.
func (DesiredWithRowSecurity) Table ¶ added in v0.4.0
func (d DesiredWithRowSecurity) Table() string
Table returns the declaration's unqualified table name.
type IndexRelation ¶ added in v0.4.0
type IndexRelation struct {
Schema string
Name string
Kind IndexRelationKind
}
IndexRelation is the one relation a single-relation index-maintenance statement maintains, as the grammar spelled it. Schema is empty when the name was unqualified, so the session search_path resolves it. The acknowledgement of an accepted blocking statement resolves this name to the table whose lock the operator accepts; the parse boundary itself never consults a catalog.
type IndexRelationKind ¶ added in v0.4.0
type IndexRelationKind int
IndexRelationKind says whether a single-relation index-maintenance statement names an index or a table.
const ( // IndexRelationNone is carried by statements that name no single // maintained relation. IndexRelationNone IndexRelationKind = iota // IndexRelationIndex means the statement names an index: DROP INDEX, // REINDEX INDEX, and ALTER INDEX ... RENAME TO. IndexRelationIndex // IndexRelationTable means the statement names a table: REINDEX TABLE. IndexRelationTable )
type IndexTarget ¶ added in v0.3.3
type IndexTarget int
IndexTarget identifies whether an index-maintenance statement's scope stays within one relation. IndexTargetOther means the scope is wider than one relation, for any reason — several indexes, a schema or database scope, or a cascading drop (see Cascades()) — so it is not a count of the relations the statement names. The gate uses this parse-only fact to keep forms requiring more than one lock acknowledgement out of accepted-blocking eligibility.
const ( // IndexTargetNone is carried by statements outside index maintenance. IndexTargetNone IndexTarget = iota // IndexTargetSingleRelation covers one DROP INDEX (without CASCADE), // REINDEX INDEX or TABLE, and ALTER INDEX ... RENAME TO. IndexTargetSingleRelation // IndexTargetOther covers the DROP and REINDEX scopes that do not stay // within one relation: several indexes in one DROP INDEX, DROP INDEX with // CASCADE (which also drops dependent objects), and REINDEX SCHEMA, // DATABASE, and SYSTEM. IndexTargetOther )
func IndexTargets ¶ added in v0.3.3
func IndexTargets() []IndexTarget
IndexTargets returns the closed set of index-maintenance target shapes.
func (IndexTarget) String ¶ added in v0.3.3
func (t IndexTarget) String() string
String returns the stable name of an index target shape.
type Kind ¶
type Kind int
Kind is the statement-type bucket the Phase 1 gate branches on.
const ( KindOther Kind = iota KindAlterTable KindCreateIndex KindDropIndex KindReindex KindCreateTable KindDataChange KindProvisioning KindCatalogWork // KindRenameIndex is ALTER INDEX ... RENAME TO. It names an index, not // a table, so it carries the index as its IndexRelation and no table // target. KindRenameIndex )
The kinds the gate distinguishes. Everything the engine does not recognize as one of the named kinds is KindOther and is refused by the front door.
type Op ¶
type Op struct {
// Kind is the operation shape.
Kind OpKind
// Column is the target column for column operations.
Column string
// Name is the constraint or index name where the operation has one,
// or the new name for renames.
Name string
// Only reports that an ALTER TABLE names its table with ONLY, so the
// operation stops at the table and does not recurse into the tables
// below it.
Only bool
// Cascade reports a drop with CASCADE (DROP COLUMN, DROP CONSTRAINT,
// or DROP INDEX), which also drops the objects that depend on what it
// drops, such as a view or another table's foreign key, where the
// default RESTRICT refuses while any exist.
Cascade bool
// Indexes are the unqualified names of the indexes an OpDropIndex
// drops, in statement order, so a classifier can match each one
// without parsing Name's display form, or the one index an
// ADD CONSTRAINT ... USING INDEX takes over.
Indexes []string
// Columns are the plain key columns of an ADD PRIMARY KEY / UNIQUE;
// empty when the keys are expressions.
Columns []string
// IncludeColumns are the INCLUDE columns of an ADD PRIMARY KEY /
// UNIQUE: carried in the index, not part of the key.
IncludeColumns []string
// NullsNotDistinct is true for an ADD UNIQUE NULLS NOT DISTINCT, which
// rejects a second row whose key is NULL.
NullsNotDistinct bool
// Deferrable and InitiallyDeferred are an ADD PRIMARY KEY / UNIQUE's
// DEFERRABLE and INITIALLY DEFERRED: when the uniqueness check runs.
Deferrable bool
InitiallyDeferred bool
// IndexTablespace is the USING INDEX TABLESPACE of an ADD PRIMARY KEY
// / UNIQUE: where its index is built.
IndexTablespace string
// IndexStorageParams are the WITH (...) storage parameters of an ADD
// PRIMARY KEY / UNIQUE's index, in statement order.
IndexStorageParams []StorageParam
// IndexOptionsUnrenderable is true when an ADD PRIMARY KEY / UNIQUE's
// WITH (...) carries a parameter IndexStorageParams cannot hold
// faithfully: one whose value is not a plain word, number, or string,
// or holds a backslash.
IndexOptionsUnrenderable bool
// Constraint is the constraint family for OpAddConstraint.
Constraint ConstraintKind
// NotValid is true for ADD CONSTRAINT ... NOT VALID.
NotValid bool
// UsingIndex is true for ADD CONSTRAINT ... USING INDEX.
UsingIndex bool
// Concurrent is true when the statement carries CONCURRENTLY.
Concurrent bool
// Unique is true for CREATE UNIQUE INDEX.
Unique bool
// IfNotExists is true for CREATE TABLE IF NOT EXISTS and
// CREATE INDEX IF NOT EXISTS.
IfNotExists bool
// GeneratedStored is true for ADD COLUMN ... GENERATED ... STORED.
GeneratedStored bool
// InlineConstraints are the table-constraint families an added column
// carries inline (UNIQUE, PRIMARY KEY, REFERENCES, CHECK) — each does
// the same index build or validation scan as its ADD CONSTRAINT form.
// An inline constraint the engine does not model is reported as
// ConstraintUnrecognized so the classifier can refuse it.
InlineConstraints []ConstraintKind
// PartitionOf is true for CREATE TABLE ... PARTITION OF, which locks
// the partitioned parent, not just the new relation.
PartitionOf bool
// Inherits is true for CREATE TABLE ... INHERITS, which locks each
// named parent — an existing relation, resolved via search_path when
// unqualified. Disjoint from PartitionOf: the grammar carries the
// partitioned parent in the same clause, but only PARTITION OF sets a
// partition bound.
Inherits bool
// Like is true for a CREATE TABLE with a LIKE clause, which reads an
// existing source table — resolved via search_path when unqualified.
Like bool
// OfType is true for CREATE TABLE ... OF type, which binds the table
// to an existing composite type — resolved via search_path when
// unqualified.
OfType bool
// ForeignKey is true for a CREATE TABLE that declares a foreign key, in
// either the column or the table-constraint form; creating it locks
// each referenced table in SHARE ROW EXCLUSIVE mode.
ForeignKey bool
// Default is the DEFAULT shape for OpAddColumn.
Default DefaultKind
// NewType is the target type for OpAlterColumnType and the column type
// for OpAddColumn, as the bare grammar type name (e.g. "varchar",
// "numeric") without the pg_catalog qualification.
NewType string
// NewTypeMods are the target type's modifiers (e.g. 50 in varchar(50),
// 12 and 2 in numeric(12,2)); empty when unconstrained.
NewTypeMods []int32
// NewTypeSchema is the schema the target type is qualified with, empty
// when it is unqualified or qualified with pg_catalog. A qualified type
// is a user type that may share a built-in's name.
NewTypeSchema string
// NewTypeArray is true when the target type is an array of NewType
// (varchar(50)[], text ARRAY).
NewTypeArray bool
// NewTypeCollation is the collation the target's COLLATE clause names,
// as the statement spells it with any schema (C, pg_catalog.C); empty
// when there is no clause. A collation change rebuilds every index on
// the column, so a consumer comparing NewType to a live type must not
// read a collated target as a relabel.
NewTypeCollation string
// HasUsing is true for ALTER COLUMN TYPE ... USING <expr>, which always
// means a conversion, never a binary-coercible relabel.
HasUsing bool
}
Op is one parsed operation: the shape facts the classifier needs, nothing executable. Fields beyond Kind are populated only where meaningful for that kind; see each field's comment.
func ParseOps ¶
ParseOps parses one SQL statement and returns its typed operations. An ALTER TABLE yields one Op per subcommand; every other supported statement yields exactly one. Statements and subcommands the engine does not recognize come back as OpUnrecognized — never an error — so the classifier can refuse them with context. A parse failure is surfaced to the caller.
type OpKind ¶
type OpKind int
OpKind names one operation shape the classifier distinguishes. A single ALTER TABLE statement yields one Op per subcommand; index, rename, and schema statements yield exactly one.
const ( OpUnrecognized OpKind = iota OpCreateTable OpAddColumn OpDropColumn OpAlterColumnType OpSetDefault OpDropDefault OpSetNotNull OpDropNotNull OpSetColumnOptions OpRenameColumn OpRenameTable OpRenameIndex OpSetSchema OpSetTablespace OpSetRelOptions OpAddConstraint OpValidateConstraint OpDropConstraint OpAttachPartition OpDetachPartition OpCreateIndex OpDropIndex OpReindex )
The operation shapes ParseOps reports. OpUnrecognized is everything the engine does not recognize; the classifier refuses it.
type QualifiedName ¶ added in v0.4.0
QualifiedName is a name an expression spells, with the schema it was qualified with or the empty string when the search_path is left to resolve it. For a name of more than two parts the schema is the parts before the last, joined as written.
func (QualifiedName) String ¶ added in v0.4.0
func (n QualifiedName) String() string
String renders the name as the expression would spell it.
type RowSecurityChange ¶ added in v0.4.0
type RowSecurityChange struct {
// contains filtered or unexported fields
}
RowSecurityChange is an ordered SQL operation for comparison, not execution authority. Parsing checks statement kinds and one fully qualified target; it does not check privileges, policy dependencies, or whether access widens. It deliberately stays separate from Statement and ordinary native DDL. The PostgreSQL executor must still admit and execute the operation atomically.
func ParseRowSecurityChange ¶ added in v0.4.0
func ParseRowSecurityChange(sql string) (RowSecurityChange, error)
ParseRowSecurityChange admits the SQL shapes emitted by a complete atomic RLS replacement: policy drops/creates/comments and RLS settings on one table. The complete script must contain only these statements. Empty input is not a change. This parser does not admit statements to the native executor.
func (RowSecurityChange) CanonicalSQL ¶ added in v0.4.0
func (c RowSecurityChange) CanonicalSQL() string
CanonicalSQL preserves order and duplicates for a single operation's comparison key. It preserves physical schema qualifiers, roles, predicates, and comments; namespace mapping is a separate concern. A zero value is not a parsed operation.
func (RowSecurityChange) CanonicalSQLForNamespace ¶ added in v0.4.0
func (c RowSecurityChange) CanonicalSQLForNamespace(schema, table string) (string, error)
CanonicalSQLForNamespace omits only the operation's target schema qualifier. The expected physical schema and table must come from the caller’s target configuration, not from this operation. A mismatch refuses normalization. Use it when the comparison key already contains a canonical namespace and table. Qualified policy helpers and all expressions remain unchanged. This is a comparison representation, never executable SQL.
func (RowSecurityChange) Schema ¶ added in v0.4.0
func (c RowSecurityChange) Schema() string
Schema returns the physical schema named by every target statement.
func (RowSecurityChange) Statements ¶ added in v0.4.0
func (c RowSecurityChange) Statements() []string
Statements returns a copy of the original statements in their original order.
func (RowSecurityChange) Table ¶ added in v0.4.0
func (c RowSecurityChange) Table() string
Table returns the table named by every target statement.
type SourceStatement ¶
type SourceStatement struct {
// SQL is the statement's verbatim source text, without the trailing
// semicolon, so it can be found in the source by exact match.
SQL string
// Line is the 1-based source line of the statement's first token.
Line int
// Column is the 1-based source column of the statement's first token.
Column int
}
SourceStatement is one script statement located in its source: the verbatim text plus the position of its first token, so a consumer can point a finding back at the exact place in the file it came from.
func Split ¶
func Split(sql string) ([]SourceStatement, error)
Split parses a script with the PostgreSQL grammar and returns each statement with its verbatim text and source position, in input order. Every statement is also reprinted through the deparser as a validation gate: a statement the grammar cannot roundtrip is an error, never a guess. An empty script returns no statements; a parse failure anywhere in the script is surfaced to the caller, never guessed around.
type Statement ¶
type Statement struct {
// contains filtered or unexported fields
}
Statement proves the SQL it carries parsed as exactly one statement through the PostgreSQL grammar — the proof the executor requires before running anything (invariant ST-7). It can only be constructed by ParseOne and carries the facts the gate needs about that one statement.
func ParseOne ¶
ParseOne parses sql with the PostgreSQL grammar and requires exactly one statement. A parse failure is surfaced to the caller, never guessed around.
func (Statement) BuildsIndex ¶
BuildsIndex reports whether executing the statement creates a new index: every CREATE INDEX, and the ALTER TABLE shapes that build one as a side effect — ADD CONSTRAINT UNIQUE / PRIMARY KEY / EXCLUDE without USING INDEX, and ADD COLUMN with an inline UNIQUE or PRIMARY KEY. The server requires CREATE on the schema for these (the engine-role contract's index build tier), unlike in-place ALTERs — including USING INDEX adoption and rewrites that rebuild existing indexes, which are owner-gated only.
func (Statement) Cascades ¶ added in v0.4.0
Cascades reports whether a DROP INDEX used CASCADE, which also drops the objects that depend on the index. It is always false for other statements.
func (Statement) Concurrent ¶
Concurrent reports whether an index statement used its CONCURRENTLY form. It is always false for non-index kinds.
func (Statement) IndexRelation ¶ added in v0.4.0
func (s Statement) IndexRelation() IndexRelation
IndexRelation returns the relation an IndexTargetSingleRelation statement names; the zero value for every other statement, including an IndexTargetOther statement that names one index but whose scope is wider, such as DROP INDEX ... CASCADE (see Cascades()).
func (Statement) IndexTarget ¶ added in v0.3.3
func (s Statement) IndexTarget() IndexTarget
IndexTarget returns the typed target shape of an index-maintenance statement.
func (Statement) RenamedTo ¶ added in v0.4.0
RenamedTo returns the name an ALTER INDEX ... RENAME TO gives its index, as the grammar spelled it; empty for every other statement. The renamed index keeps its schema, so the name is never qualified.
type StorageParam ¶ added in v0.4.0
StorageParam is one WITH (...) storage parameter. The server reads every parameter's value as text, so Value holds that text whatever literal spelled it; HasValue is false for a bare name, which the server reads as true.
type TransactionControl ¶ added in v0.4.0
type TransactionControl int
TransactionControl is what a statement does to an explicit transaction block, read from the parse tree.
const ( // TransactionNone: the statement neither opens nor closes a block. A // savepoint statement, and a COMMIT or ROLLBACK AND CHAIN, which // closes one block and opens the next at once, leave a script inside // its block. TransactionNone TransactionControl = iota // TransactionBegin: BEGIN or START TRANSACTION opens a block. TransactionBegin // TransactionEnd: COMMIT, END, ROLLBACK, ABORT, or PREPARE // TRANSACTION closes the open block. TransactionEnd )
The effects a statement can have on an explicit transaction block.
func TransactionControlOf ¶ added in v0.4.0
func TransactionControlOf(sql string) (TransactionControl, error)
TransactionControlOf reports what sql, exactly one statement, does to an explicit transaction block.