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 DetachedPartition(sql string) (schema, name string, ok bool, err error)
- func FormatDesired(sql string) (string, error)
- func HasRowSecurityDeclaration(sql string) (bool, error)
- func ImplicitRelationNames(sql string) ([]string, error)
- func IndexKeyColumns(sql string) ([]string, error)
- func IndexOnWholeTable(sql string) (string, error)
- func OnlyIndex(sql string) (string, error)
- func PartitionIndex(parentIndexDef, schema, table, name string, form PartitionIndexForm) (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 DeclaredIndexConstraints
- type DefaultKind
- type DesiredEnumType
- type DesiredFile
- type DesiredSchema
- func (ds DesiredSchema) ExtensionSchemas() []string
- func (ds DesiredSchema) HasForeignKeys() bool
- func (ds DesiredSchema) ReferencedTables() []string
- func (ds DesiredSchema) Statements() []Statement
- func (ds DesiredSchema) Table() string
- func (ds DesiredSchema) WithExtensionSchemas(schemas ...string) (DesiredSchema, error)
- type DesiredWithRowSecurity
- func (d DesiredWithRowSecurity) ExtensionSchemas() []string
- func (d DesiredWithRowSecurity) PolicyReads() []QualifiedName
- func (d DesiredWithRowSecurity) Statements() []Statement
- func (d DesiredWithRowSecurity) Table() string
- func (d DesiredWithRowSecurity) TableDefinition() DesiredSchema
- func (d DesiredWithRowSecurity) WithExtensionSchemas(schemas ...string) (DesiredWithRowSecurity, error)
- type DisallowedStatementError
- type EnumTypeFileError
- type IndexRelation
- type IndexRelationKind
- type IndexTarget
- type Kind
- type Op
- type OpKind
- type PartitionIndexForm
- type QualifiedName
- type RowSecurityChange
- type SecondTableError
- type SourceStatement
- type StatedConstraintNames
- type Statement
- func (s Statement) AddedEnumValue() string
- func (s Statement) BuildsIndex() bool
- func (s Statement) Cascades() bool
- func (s Statement) Concurrent() bool
- func (s Statement) EnumType() TypeName
- func (s Statement) EnumValueNeighbor() string
- func (s Statement) FinalizesDetach() 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 TableName
- type Transaction
- type TransactionControl
- type TypeName
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. The parser returns it inside a // [*SecondTableError], which names the refused CREATE TABLE. ErrMultipleCreateTables = errors.New("desired schema must contain exactly one CREATE TABLE") // ErrDesiredPartitions is returned alongside ErrMultipleCreateTables // (both inside a [*SecondTableError]) for a file whose CREATE TABLEs // declare partitions of a table: a partition is a table of its own, and // the declarative model does not plan partitions. ErrDesiredPartitions = errors.New("desired schema declares partitions of a table, which the declarative model does not plan") // 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. // The parser returns it inside a [*DisallowedStatementError], which // names the statement and its kind. 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") // ErrExtensionSchema is returned by [DesiredSchema.WithExtensionSchemas] // for a name that cannot hold extension objects the file resolves: an // empty name, a duplicate, or a system schema PostgreSQL searches on its // own terms. ErrExtensionSchema = errors.New("invalid extension schema") )
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 ( // ErrEnumTypeAlone is returned for a statement in a desired enum type // file other than its one CREATE TYPE ... AS ENUM: the file declares one // type, and a table or a second type belongs in a file of its own. The // parser returns it inside an [*EnumTypeFileError], which names the // refused statement. ErrEnumTypeAlone = errors.New("a desired enum type file holds exactly one CREATE TYPE ... AS ENUM and nothing else") // ErrEnumLabel is returned when a desired enum type lists a label twice, // lists the empty label, or lists one longer than PostgreSQL stores: a // plan places each new label next to a neighbor it names, so every label // must be one the plan can name and the server can add. ErrEnumLabel = errors.New("a desired enum type's labels must be distinct, non-empty, and at most 63 bytes") )
Typed refusals for a desired enum type file. The caller branches with errors.Is, never on text.
var ( // ErrNotCreateIndex is returned when the statement is not a single // CREATE INDEX. ErrNotCreateIndex = errors.New("statement is not CREATE INDEX") // ErrIndexIfNotExists is returned for CREATE INDEX IF NOT EXISTS: the // clause makes the statement a no-op while any relation owns the name, // so an edit of it would not say what the edited statement did. ErrIndexIfNotExists = errors.New("CREATE INDEX IF NOT EXISTS cannot be edited") // ErrIndexUnnamed is returned for a CREATE INDEX with no name: a derived // index needs a name a rerun can find. ErrIndexUnnamed = errors.New("CREATE INDEX must name its index") // ErrUnknownPartitionIndexForm is returned for a PartitionIndexForm the // package does not define. ErrUnknownPartitionIndexForm = errors.New("unknown partition index form") )
Typed refusals for the partitioned index edits. Both edits parse one CREATE INDEX, change a few named fields, and deparse.
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 ErrPolicyLocksRows = errors.New("a policy cannot lock the rows it reads, such as with FOR SHARE or FOR UPDATE")
ErrPolicyLocksRows refuses a policy expression whose query locks the rows it reads (FOR UPDATE, FOR SHARE, and their weaker forms). PostgreSQL takes ROW SHARE on such a table while it builds the policy, which waits behind a session holding EXCLUSIVE, where a plain read takes only ACCESS SHARE.
var ErrPolicyReadsCatalog = errors.New("a policy cannot read a pg_catalog table")
ErrPolicyReadsCatalog refuses a policy expression that reads a pg_catalog table. pg_catalog is always searched, so introspection prints such a table unqualified, and the file pull would export from the live policy could not be admitted again.
var ErrPolicyReadsOwnTable = errors.New("a policy cannot read the table it is defined on")
ErrPolicyReadsOwnTable refuses a policy expression that reads a relation with its own table's name. The scratch build would bind the name to the live table rather than to the desired one, and PostgreSQL reports infinite recursion for a policy that reads the table it protects. The file does not say which schema the table lives in, so the name is refused in every schema.
var ErrPolicyRelationDependency = errors.New("a policy must name every table it reads schema-qualified, such as public.team_members")
ErrPolicyRelationDependency refuses a policy expression that reads a table it does not name schema-qualified. Policy expressions resolve against nothing but the scratch schema and PostgreSQL's built-ins, so an unqualified name either fails to resolve or binds an object nobody meant. A CTE name is refused the same way, because the grammar cannot tell it from a table name.
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, including a file with no table definition, which arrives as ErrRowSecurityTableDefinitionRequired and matches this error too. Match both with errors.Is; their text is for people and may change.
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 error = rowSecurityTableDefinitionError{}
ErrRowSecurityTableDefinitionRequired identifies a missing table definition in an RLS file. It also matches ErrRowSecurityDeclaration, whose sentence it does not print: the file may well hold its ENABLE. It is one value, not a chain of two, so match it with errors.Is rather than errors.Unwrap; its text is for people and may change.
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, or refuses it for leaving an existing row NULL: its type and collation, its DEFAULT, NOT NULL, and identity. An inline PRIMARY KEY becomes the NOT NULL it implies. The probe drops the inline CHECK, UNIQUE, REFERENCES, and EXCLUDE constraints and the rest of a PRIMARY KEY, 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 DetachedPartition ¶ added in v0.5.6
DetachedPartition returns the partition a single-command ALTER TABLE ... DETACH PARTITION names, as the grammar spelled it: its schema (empty when the name is unqualified) and its name. ok is false for every other statement, a DETACH PARTITION ... FINALIZE included.
func FormatDesired ¶ added in v0.5.4
FormatDesired returns the canonical text of a desired-state schema file: sql is admitted by ParseDesiredFile and every admitted statement is printed in the deparser's canonical form followed by ";\n", in the order DesiredFile.Statements reports them, which can differ from the input's (indexes after the table, policy comments last).
The file is the one ParseDesiredFile admits: exactly one CREATE TABLE (ErrMultipleCreateTables for a second), unqualified names (ErrQualifiedName), the table's indexes, and its row-security statements, any other statement kind being ErrDisallowedStatement; or exactly one CREATE TYPE ... AS ENUM and nothing else (ErrEnumTypeAlone). Input that is not valid SQL, an unterminated quote or comment included, is ErrParseDesired.
A lexical comment (-- or /* */) is refused with ErrCommentLoss before any admission rule runs: the parser drops comments, and formatting must never silently discard content. An admitted statement such as COMMENT ON POLICY is content, not a comment, and is printed. On any refusal the text is empty.
The text is stable across calls and formats to itself, but it is the canonical form of the PostgreSQL parser this version of pg-sprite builds with: it can change when that parser is upgraded, though what the statements mean does not.
Example ¶
ExampleFormatDesired formats a desired-state schema file the way the fmt command does. A file is printed in canonical form; a commented one is refused, since the parser would drop the comment; a syntax error is told from a refusal by ErrParseDesired. On any error the text is empty.
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); -- keep me",
"CREATE TABLE documents (title text DEFAULT 'oops);",
"CREATE TABLE documents (id bigint);\nALTER TABLE documents ADD COLUMN title text;",
} {
formatted, err := statement.FormatDesired(sql)
switch {
case errors.Is(err, statement.ErrCommentLoss):
fmt.Println("refused: commented input")
case errors.Is(err, statement.ErrParseDesired):
fmt.Println("not valid SQL")
case errors.Is(err, statement.ErrDisallowedStatement):
fmt.Println("refused:", statement.ErrDisallowedStatement)
case err != nil:
fmt.Println("refused:", err)
default:
fmt.Print(formatted)
}
}
}
Output: CREATE TABLE documents (id bigint PRIMARY KEY); CREATE INDEX documents_id_idx ON documents USING btree (id); refused: commented input not valid SQL refused: statement kind not allowed in a desired schema
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 IndexKeyColumns ¶ added in v0.5.5
IndexKeyColumns returns the key columns of sql, a single named CREATE INDEX, in key order: the columns its key names as plain columns. An expression key and an INCLUDE column are not key columns, so neither is listed.
func IndexOnWholeTable ¶ added in v0.5.5
IndexOnWholeTable returns a CREATE INDEX definition with ONLY removed from its ON clause, reprinted through the PostgreSQL deparser. pg_get_indexdef prints every index on a partitioned parent as CREATE INDEX ... ON ONLY, whether or not its partitions carry the index; a desired file declares the parent's index for the whole table, which is what PostgreSQL builds for ON without ONLY. On a table with no partitions — the scratch schema a desired file is built in, and a table the file creates — the two forms build the same index, so a file rendered with this form introspects back to the definition it was rendered from. Only the target RangeVar's inheritance flag changes.
func OnlyIndex ¶ added in v0.5.5
OnlyIndex returns sql, a single named CREATE INDEX, as CREATE INDEX ... ON ONLY without CONCURRENTLY: the statement that creates a partitioned table's index, marked invalid, without building anything. The server rejects CONCURRENTLY on a partitioned table, so the flag is cleared. Nothing else changes. This and PartitionIndex are the second executable-SQL AST edit pg-sprite permits, after Qualify.
func PartitionIndex ¶ added in v0.5.5
func PartitionIndex(parentIndexDef, schema, table, name string, form PartitionIndexForm) (string, error)
PartitionIndex returns parentIndexDef, a partitioned index's definition as pg_get_indexdef prints it, as a statement that creates the matching index named name on the partition schema.table, in the given form. It sets the name, the target relation, and the ONLY and CONCURRENTLY flags; the key, predicate, uniqueness, and options stay as the server printed them, which is what makes the result attachable to the parent's index.
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. A CREATE TABLE's unqualified foreign-key references are qualified by schema too, because a desired file's referenced tables live in the target schema: left unqualified, a reference would resolve through the session's search_path and could bind a same-named table in another schema. Stripping is the inverse: it also strips a reference qualified by the target's own schema, so a planned CREATE TABLE round-trips back to its desired form, and leaves a reference to any other schema as written. 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" // AddColumnInPlaceScans means the column is added without rewriting the // table, but PostgreSQL still reads every row to check the column's NOT // NULL: no default fills the rows the table already has, so the server // must prove none of them exists. AddColumnInPlaceScans AddColumnProof = "in-place-scans" // AddColumnInPlaceRunsUserCode means the column is added without // rewriting the table, but adding it evaluates something defined // outside PostgreSQL's built-in catalog: a domain's default or checks, // or a function, cast, or operator its default resolves to. That code // runs once under the table's lock and can read any table, so the // cost of adding the column is not proven independent of the table. AddColumnInPlaceRunsUserCode AddColumnProof = "in-place-runs-user-code" // 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 DeclaredIndexConstraints ¶ added in v0.5.1
type DeclaredIndexConstraints struct {
// Names holds one entry per constraint, table-level and column-inline,
// in definition order: the name the statement states, or "" when the
// server chooses one.
Names []string
// IndexesCopiedFrom names, in definition order, the table each LIKE
// clause that includes indexes copies from. The server creates the
// copies after the table, so they are kept beside the declared
// constraints rather than merged with them, and the table built holds
// the declared constraints plus every PRIMARY KEY, UNIQUE, and EXCLUDE
// constraint these tables hold. A LIKE clause that excludes indexes
// copies none and is not listed.
IndexesCopiedFrom []QualifiedName
}
DeclaredIndexConstraints are the PRIMARY KEY, UNIQUE, and EXCLUDE constraints a CREATE TABLE declares.
func IndexConstraints ¶ added in v0.5.1
func IndexConstraints(sql string) (DeclaredIndexConstraints, error)
IndexConstraints returns the PRIMARY KEY, UNIQUE, and EXCLUDE constraints a CREATE TABLE declares.
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 DesiredEnumType ¶ added in v0.5.5
type DesiredEnumType struct {
// contains filtered or unexported fields
}
DesiredEnumType proves a desired-state schema file declares exactly one enum type: a single unqualified CREATE TYPE ... AS ENUM whose labels are distinct, non-empty, and at most 63 bytes. Only ParseDesiredFile produces a non-zero value.
The labels are the type's desired values in their declared order, which is the order PostgreSQL sorts them in. A plan converges a live type onto them by adding the labels it lacks, each in its declared position; it never removes, renames, or reorders a label.
func (DesiredEnumType) Labels ¶ added in v0.5.5
func (d DesiredEnumType) Labels() []string
Labels returns the desired labels in their declared order. The slice is a copy.
func (DesiredEnumType) Name ¶ added in v0.5.5
func (d DesiredEnumType) Name() string
Name returns the unqualified name of the enum type.
func (DesiredEnumType) Statements ¶ added in v0.5.5
func (d DesiredEnumType) Statements() []Statement
Statements returns the file's one CREATE TYPE ... AS ENUM in the deparser's canonical form. The slice is a copy.
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 three declarative front doors: ParseDesired for a table with its indexes, ParseDesiredWithRowSecurity for a table that also declares row security, or the enum type door for a file that declares one enum type (DesiredEnumType). 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, RowSecurity, and EnumType reports ok.
DesiredFile is a router over those proof types, not a proof type itself: no planner or executor accepts it. Hand the value Schema, RowSecurity, or EnumType 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 an enum type (CREATE TYPE ... AS ENUM) must hold that one statement and nothing else (ErrEnumTypeAlone, ErrEnumLabel, ErrQualifiedName). 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) EnumType ¶ added in v0.5.5
func (f DesiredFile) EnumType() (DesiredEnumType, bool)
EnumType returns the enum type planner input when the file declares an enum type.
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 a table and no row security. The zero DesiredFile admitted nothing, so it reports none of the three.
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. For a row-security file that is the table and its indexes, then the settings and policies in the order the file wrote them, then the policy comments. For an enum type file it is the one CREATE TYPE. 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. An enum type file declares no table, so its Table is empty; DesiredEnumType.Name names its type.
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) ExtensionSchemas ¶ added in v0.5.1
func (ds DesiredSchema) ExtensionSchemas() []string
ExtensionSchemas returns the schemas, in search order, that the file's unqualified type, function, and operator names also resolve against after the target schema and public. It is empty unless DesiredSchema.WithExtensionSchemas set it. The slice is a copy.
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.
func (DesiredSchema) WithExtensionSchemas ¶ added in v0.5.1
func (ds DesiredSchema) WithExtensionSchemas(schemas ...string) (DesiredSchema, error)
WithExtensionSchemas returns a copy of ds whose unqualified type, function, and operator names also resolve against schemas, in order, after the target schema and public: `email citext` then finds the type an extension installed in a schema such as extensions. The schemas only widen what the file's names resolve to when pg-sprite builds and creates the table; introspection still prints each such name qualified, so a plan states exactly which object it means. Unqualified names are a choice the caller makes explicitly, because with more schemas searched an unqualified function call can resolve to a different overload.
A name must be non-empty, listed once, and not a system schema (pg_catalog, information_schema, or any pg_ name): pg_catalog is searched first regardless, and the others never hold an extension the file should name. An empty schemas clears the list.
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 a table unqualified or reading their own table are refused.
func (DesiredWithRowSecurity) ExtensionSchemas ¶ added in v0.5.1
func (d DesiredWithRowSecurity) ExtensionSchemas() []string
ExtensionSchemas returns the schemas the table definition's unqualified names also resolve against, as DesiredSchema.ExtensionSchemas does. It is empty unless DesiredWithRowSecurity.WithExtensionSchemas set it. The slice is a copy.
func (DesiredWithRowSecurity) PolicyReads ¶ added in v0.5.1
func (d DesiredWithRowSecurity) PolicyReads() []QualifiedName
PolicyReads returns the tables the policies' expressions read, each schema-qualified as the file names it, sorted and without duplicates. The slice is a copy.
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.
func (DesiredWithRowSecurity) TableDefinition ¶ added in v0.5.1
func (d DesiredWithRowSecurity) TableDefinition() DesiredSchema
TableDefinition returns the CREATE TABLE and its indexes without the row security that follows them. Running it on its own creates a table without its row security, so only the executor that creates the table and its row security in one transaction consumes it.
func (DesiredWithRowSecurity) WithExtensionSchemas ¶ added in v0.5.1
func (d DesiredWithRowSecurity) WithExtensionSchemas(schemas ...string) (DesiredWithRowSecurity, error)
WithExtensionSchemas returns a copy of d whose table definition resolves unqualified type, function, and operator names against schemas as well, under DesiredSchema.WithExtensionSchemas's rules. Only the CREATE TABLE and its indexes widen. Policy expressions still resolve nothing but the table and PostgreSQL's built-ins, so every helper and table a policy names stays qualified, and an extension schema can never change which function a policy calls.
type DisallowedStatementError ¶ added in v0.5.5
type DisallowedStatementError struct {
// SQL is the refused statement in the deparser's canonical form, or its
// source text when the canonical form would classify as a different
// kind: the parse tree drops some distinctions [ParseOne] reads from the
// statement's keywords, such as an empty enum label.
SQL string
// Kind is the kind [ParseOne] gives the statement's source text.
Kind Kind
}
DisallowedStatementError is ErrDisallowedStatement for one statement of a desired file. It carries the statement's SQL and the kind ParseOne gives the statement's source text, so a caller can classify the refusal the way the imperative front door classifies the same statement.
func (*DisallowedStatementError) Error ¶ added in v0.5.5
func (e *DisallowedStatementError) Error() string
func (*DisallowedStatementError) Unwrap ¶ added in v0.5.5
func (e *DisallowedStatementError) Unwrap() error
Unwrap returns ErrDisallowedStatement.
type EnumTypeFileError ¶ added in v0.5.5
type EnumTypeFileError struct {
// SQL is the refused statement as [DisallowedStatementError.SQL]
// names it: the canonical form, or the source text when the canonical
// form would classify as a different kind.
SQL string
}
EnumTypeFileError is ErrEnumTypeAlone for one statement of a desired enum type file.
func (*EnumTypeFileError) Error ¶ added in v0.5.5
func (e *EnumTypeFileError) Error() string
func (*EnumTypeFileError) Unwrap ¶ added in v0.5.5
func (e *EnumTypeFileError) Unwrap() error
Unwrap returns ErrEnumTypeAlone.
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 // KindAddEnumValue is ALTER TYPE ... ADD VALUE. It names an enum type, // not a table, so it carries the type as its EnumType and no table // target. KindAddEnumValue )
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
// Tablespace is the TABLESPACE clause of a CREATE INDEX: where the
// index is built. Empty when the statement carries none.
Tablespace 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
// ColumnStorage is true for the OpSetColumnOptions that is ALTER
// COLUMN ... SET STORAGE, which takes ACCESS EXCLUSIVE where SET
// STATISTICS and the column's SET / RESET options take SHARE UPDATE
// EXCLUSIVE.
ColumnStorage bool
// RelOptions are the storage parameters an OpSetRelOptions sets or
// resets, in statement order, each named as written, with its
// namespace prefix ("toast.autovacuum_enabled") where it has one.
RelOptions []string
// 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.
func (Op) Describe ¶
Describe returns a short operator-facing label for the operation, e.g. "ADD COLUMN age" — for plan rendering, never for branching.
func (Op) TakesShareUpdateExclusiveOnly ¶ added in v0.5.0
TakesShareUpdateExclusiveOnly reports an ALTER TABLE operation whose lock on the table is SHARE UPDATE EXCLUSIVE, which blocks neither reads nor writes: VALIDATE CONSTRAINT, SET STATISTICS and a column's SET / RESET options, and SET / RESET of the storage parameters PostgreSQL changes under that lock. SET STORAGE, user_catalog_table, and a parameter not listed here count as blocking.
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 OpAddEnumValue )
The operation shapes ParseOps reports. OpUnrecognized is everything the engine does not recognize; the classifier refuses it.
type PartitionIndexForm ¶ added in v0.5.5
type PartitionIndexForm int
PartitionIndexForm is the statement shape PartitionIndex produces.
const ( // PartitionIndexConcurrently is CREATE INDEX CONCURRENTLY on a plain // table: the form for a leaf partition. PartitionIndexConcurrently PartitionIndexForm = iota + 1 // PartitionIndexOnly is CREATE INDEX ... ON ONLY, not concurrent: the // form for a partition that is itself partitioned. It builds nothing. PartitionIndexOnly )
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 SecondTableError ¶ added in v0.5.5
type SecondTableError struct {
// SQL is the refused CREATE TABLE in the deparser's canonical form.
SQL string
// Partition reports whether the file declares a partition.
Partition bool
}
SecondTableError is ErrMultipleCreateTables for the second CREATE TABLE of a desired file. It also matches ErrDesiredPartitions when either CREATE TABLE is a partition.
func (*SecondTableError) Error ¶ added in v0.5.5
func (e *SecondTableError) Error() string
func (*SecondTableError) Unwrap ¶ added in v0.5.5
func (e *SecondTableError) Unwrap() []error
Unwrap returns ErrMultipleCreateTables, and ErrDesiredPartitions when the file declares a partition.
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 StatedConstraintNames ¶ added in v0.5.5
type StatedConstraintNames struct {
// Names holds every name the statement states for a constraint it
// declares, table-level and column-inline, of every constraint type,
// in definition order. A constraint the statement declares without a
// name takes one the server chooses and is not listed.
Names []string
// Complete is false when the statement can bring in constraints under
// names it does not state: a CREATE TABLE whose LIKE clause copies
// another table's constraints. A constraint the statement builds is
// then not known to be unnamed merely because Names leaves it out.
Complete bool
}
StatedConstraintNames are the constraint names one statement states.
func ConstraintNames ¶ added in v0.5.5
func ConstraintNames(sql string) (StatedConstraintNames, error)
ConstraintNames returns the constraint names a CREATE TABLE or an ALTER TABLE states, whether declared as a table constraint or inline on a column: for ALTER TABLE, those of every ADD CONSTRAINT and ADD COLUMN command it carries. Any other statement declares no constraint and returns an empty, complete result.
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) AddedEnumValue ¶ added in v0.5.1
AddedEnumValue returns the label an ALTER TYPE ... ADD VALUE adds, as the grammar spelled it; empty for every other statement.
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) EnumType ¶ added in v0.5.1
EnumType returns the enum type an ALTER TYPE ... ADD VALUE adds a value to; the zero value for every other statement.
func (Statement) EnumValueNeighbor ¶ added in v0.5.5
EnumValueNeighbor returns the label an ALTER TYPE ... ADD VALUE places its value BEFORE or AFTER; empty when the statement names no position, and for every other statement. A position next to the empty label is not an enum value add, so a set position is never the empty label.
func (Statement) FinalizesDetach ¶ added in v0.5.6
FinalizesDetach reports whether the statement is an ALTER TABLE with a DETACH PARTITION ... FINALIZE subcommand, the statement that finishes a concurrent detach that was interrupted. The deparser does not reprint it faithfully: it drops the space before FINALIZE, which turns the keyword into part of the partition's name, so a front door has to refuse it before it reprints the statement.
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 TableName ¶ added in v0.5.0
TableName is a table as a statement spells it: its schema qualification, empty when the statement leaves it unqualified, and its name.
func TablesLockedAgainstWrites ¶ added in v0.5.0
TablesLockedAgainstWrites returns the tables a LOCK TABLE or TRUNCATE statement locks in a mode that blocks writes, each as the statement spells it, and none for any other statement. LOCK TABLE without a mode takes ACCESS EXCLUSIVE, SHARE and every stronger mode block writes, and the weaker modes block neither reads nor writes. TRUNCATE takes ACCESS EXCLUSIVE.
type Transaction ¶ added in v0.5.0
type Transaction struct {
Control TransactionControl
// Savepoint is the savepoint a TransactionSavepoint,
// TransactionRelease, or TransactionRollbackTo names.
Savepoint string
}
Transaction is what one statement does to an explicit transaction block, with the savepoint it names, if any.
func TransactionControlOf ¶ added in v0.4.0
func TransactionControlOf(sql string) (Transaction, error)
TransactionControlOf reports what sql, exactly one statement, does to an explicit transaction block.
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, // and sets no savepoint. 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 // TransactionChain: COMMIT or ROLLBACK AND CHAIN closes one block and // opens the next at once. The script stays inside a block, but the // locks the closed block held are released. TransactionChain // TransactionSavepoint: SAVEPOINT marks a point inside the block. TransactionSavepoint // TransactionRelease: RELEASE SAVEPOINT forgets a savepoint and every // later one; the locks taken since stay held. TransactionRelease // TransactionRollbackTo: ROLLBACK TO SAVEPOINT undoes the work since // a savepoint and releases the locks taken since it; the savepoint // stays, and every later one is forgotten. TransactionRollbackTo )
The effects a statement can have on an explicit transaction block.
Source Files
¶
- add_column_probe.go
- comments.go
- constraint_names.go
- conversion.go
- conversion_names.go
- desired.go
- desired_enum.go
- desired_file.go
- desired_rls.go
- detach_partition.go
- enum.go
- foreign_key.go
- implicit.go
- index_only.go
- locks.go
- ops.go
- partition_index.go
- retarget.go
- rewrite.go
- row_security_change.go
- split.go
- statement.go
- transaction.go