Documentation
¶
Overview ¶
Package diffplan is the declarative front door as a library: a parsed desired-state schema in, the routed convergence plan out. The CLI's diff command and orchestrators embedding pg-sprite share this one pipeline, so a stored report means the same thing no matter which caller produced it.
Callers own the boundary concerns: parse the desired file through statement.ParseDesired (refusals surface at the caller) and build the connection through dbconn.NewPool. Plan never writes the live table, but it is not read-only either — desired state is realized by execute-and-introspect on a rolled-back scratch schema, so the connection requirements on Plan apply.
Before a v1 module tag the Go API carries no compatibility promise: the JSON plan.Report is the stability boundary, the Go API follows at v1 (see docs/architecture.md).
Example (Plan) ¶
Example_plan is the full library flow an orchestrator embeds: parse the desired-state schema, connect, and derive the routed convergence plan. It is compile-checked but not executed — Plan needs a live PostgreSQL database.
package main
import (
"context"
"fmt"
"log"
"github.com/block/pg-sprite/pkg/dbconn"
"github.com/block/pg-sprite/pkg/diffplan"
"github.com/block/pg-sprite/pkg/statement"
)
func main() {
ctx := context.Background()
// Parse refusals (inadmissible desired files) surface here, at the
// boundary where the embedder can render them.
ds, err := statement.ParseDesired(
"CREATE TABLE events (id bigint PRIMARY KEY, name varchar(50) NOT NULL);\n" +
"CREATE INDEX events_name_idx ON events (name);")
if err != nil {
log.Print(err)
return
}
// Plan is not read-only: the desired DDL runs in an always-rolled-back
// scratch schema, so connect read-write (not a hot standby) as a role
// with CREATE on the target database. The live table is never written.
pool, err := dbconn.NewPool(ctx, dbconn.Config{URL: "postgres://engine@localhost:5432/app"})
if err != nil {
log.Print(err)
return
}
defer pool.Close()
report, err := diffplan.Plan(ctx, pool, diffplan.Request{Schema: "public", Desired: ds})
if err != nil {
log.Print(err)
return
}
// Disposition says whether the whole plan can execute; each statement
// carries its route and the engine's canonical SQL rendering.
fmt.Println(report.Disposition)
for _, st := range report.Statements {
fmt.Println(st.Route, st.SQL)
}
}
Output:
Index ¶
- func LeftoverNotNullHelpers(ctx context.Context, pool *pgxpool.Pool, schema, table string) ([]schemadiff.DroppedObject, error)
- func Plan(ctx context.Context, pool *pgxpool.Pool, req Request) (plan.Report, error)
- func PlanEnumType(ctx context.Context, pool *pgxpool.Pool, schema string, ...) (plan.Report, error)
- func PlanWithRowSecurity(ctx context.Context, pool *pgxpool.Pool, schema string, ...) (plan.Report, error)
- type Request
- type RowSecurityReviewRequired
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func LeftoverNotNullHelpers ¶ added in v0.5.7
func LeftoverNotNullHelpers(ctx context.Context, pool *pgxpool.Pool, schema, table string) ([]schemadiff.DroppedObject, error)
LeftoverNotNullHelpers returns each helper CHECK that a stopped run of the online SET NOT NULL sequence left on schema.table, as the record a checked drop of it needs. A run leaves one when it stops after adding the helper and before dropping it: its validation failed on a NULL row, or its drop ran out of retries after SET NOT NULL, and the run was cancelled or gave up. Until it is dropped, the helper rejects every write that leaves its column NULL.
A constraint is such a helper under the same rule the planner uses to resume one: the name the sequence gives the helper of one of the table's columns, and exactly the definition the sequence gives it, NOT VALID or validated. PostgreSQL never generates that name itself, but a check a user wrote with exactly that name and definition matches too, so a caller backing out a run drops only the helpers that run added. The records are read from the live catalog, so a drop checked against one refuses a constraint replaced after the read.
func Plan ¶
Plan derives the ordered, classified, and routed convergence plan for the desired schema against the live database: introspect the live table, derive the changes (the full qualified desired schema when the table does not exist yet), classify each change with live-column facts, route the set, attach the diff's advisories (the invalid indexes it observed and declined to drop), and stamp the report with the server version and fingerprint.
Plan needs more than a read-only connection: desired state is realized by executing the desired DDL in a scratch schema inside a transaction that is always rolled back, so the pool must connect read-write (not a hot standby) as a role with CREATE privilege on the target database. The live table is introspected only — never written. Plan does not close the pool; one pool serves any number of calls.
func PlanEnumType ¶ added in v0.5.5
func PlanEnumType(ctx context.Context, pool *pgxpool.Pool, schema string, desired statement.DesiredEnumType) (plan.Report, error)
PlanEnumType derives the routed convergence plan for a desired enum type against the live type of the same name in schema: a CREATE TYPE ... AS ENUM when the schema lacks the type (schemadiff.CreateEnumType), and otherwise an ALTER TYPE ... ADD VALUE for each label the type lacks, in declared order (schemadiff.DiffEnumType), classified and routed like every planned statement. Creating a type locks nothing a session uses, and adding a label locks only the type, never a table that uses it. The report names the type in Type and has no Table; an empty plan means the type carries every label the file lists. A live label the file no longer lists stays on the type, since PostgreSQL cannot drop one, and the report's Advisories name it (schemadiff.EnumAdvisories), so an empty plan with an advisory is a type that carries more than the file lists.
A name that holds another kind of type, a file that reorders the live labels, and a file that lists a new label in place of a live one return the *schemadiff.UnsupportedChangeError for the cause, and nothing is planned. A schema that does not exist returns preflight.ErrSchemaNotFound. Unlike Plan, PlanEnumType only reads the catalog, so a read-only connection serves it. It does not close the pool.
func PlanWithRowSecurity ¶ added in v0.4.0
func PlanWithRowSecurity(ctx context.Context, pool *pgxpool.Pool, schema string, desired statement.DesiredWithRowSecurity) (plan.Report, error)
PlanWithRowSecurity plans an explicitly RLS-scoped desired definition. An unchanged existing table produces a report with no executable steps. When the live row security matches the file and only the table definition differs, the report is the plan Plan derives for the file's table definition: it changes the table and never its row security, and migrate.RunDesiredWithRowSecurity runs it; a table change that plan refuses returns its error marked with schemadiff.ErrOnlyTableDiffers. The report is empty only when one comparison of the whole file, row security included, finds it matching. A row security delta, alone or with table changes, returns RowSecurityReviewRequired, wrapping ErrUnsupportedChange. A missing table returns schemadiff.ErrTableNotFound; preview its creation with executor.PreviewDesiredCreateWithRowSecurity. The distinct parsed type cannot be passed to RunDesired or ExecuteCreate. Inspection still needs CREATE privilege for its rolled-back scratch schema, just like Plan.
Types ¶
type Request ¶
type Request struct {
// Schema is the target schema the desired table lives in.
Schema string
// Desired is the parsed desired-state schema for the table.
Desired statement.DesiredSchema
// ForeignKeySchemas names the schemas, other than Schema, that a
// desired foreign key may reference a table in (see
// schemadiff.DesiredOptions). Empty refuses every such reference with
// schemadiff.ErrForeignKeySchemaNotAllowed.
ForeignKeySchemas []string
// NewEnumTypes are the enum types the same change creates in Schema
// before this table's statements run, so a column of a type the change
// also creates plans against it; see schemadiff.DesiredOptions.NewEnumTypes.
// Plan refuses a listed name that Schema already holds, as a type or a
// table's row type, since planning against the listed type would hide
// the live one. It is for a caller that plans several files of one
// change together: pg-sprite's own diff and migrate take one file at a
// time, and an enum type file runs before the table file that uses it.
NewEnumTypes []statement.DesiredEnumType
// NewTables are the tables the same change creates in Schema, each
// parsed from its own desired file, so a foreign key to a table the
// change also creates plans against it; see
// schemadiff.DesiredOptions.NewTables. The change must create the
// tables Plan reaches from Desired before Desired's own statements run,
// in the order statement.ReferencedNewTables gives. Plan refuses a
// table it reaches that Schema already holds, since planning against
// the listed file would hide the live table, and a foreign key cycle
// among them. Like NewEnumTypes, it is for a caller that plans several
// files of one change together.
NewTables []statement.DesiredSchema
}
Request names the inputs to Plan. Zero-value fields are invalid: the schema must be set, and the desired state must come from statement.ParseDesired — the zero DesiredSchema is refused.
type RowSecurityReviewRequired ¶ added in v0.4.0
type RowSecurityReviewRequired struct {
Schema string
Table string
Review schemadiff.RowSecurityReview
// ShapeRefusal is why migrate --desired refuses to change the row
// security of the live table's shape, or nil when it can.
ShapeRefusal error
// contains filtered or unexported fields
}
RowSecurityReviewRequired carries review-only changes while preserving the unsupported-change error boundary. It never authorizes execution.
func (*RowSecurityReviewRequired) Error ¶ added in v0.4.0
func (e *RowSecurityReviewRequired) Error() string
Error explains why the comparison cannot produce an executable plan.
func (*RowSecurityReviewRequired) Unwrap ¶ added in v0.4.0
func (e *RowSecurityReviewRequired) Unwrap() error
Unwrap preserves the existing typed refusal.