engine

package
v1.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 15 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package engine is the dialect-neutral schema planner and executor. A Dialect supplies inspection, diffing and lowering; the engine adds scope policy, forced rebuilds of dependent objects, global ordering, unit grouping, the reviewed artifact and its executor once, for every dialect.

Index

Constants

View Source
const ArtifactVersion = 2

ArtifactVersion is the version of the reviewed artifact format.

Variables

This section is empty.

Functions

func Acknowledgements

func Acknowledgements(a Artifact) []string

Acknowledgements lists the selected destructive change IDs an artifact plans. A forced rebuild is acknowledged through its cause.

func Check

func Check(ctx context.Context, q Querier, a Artifact) (map[string]UnitState, error)

Check classifies every unit of a validated artifact against the database as applied or pending. A unit that is in neither state is a *DriftError or a *PartialError.

func Register

func Register(d Dialect)

Register adds a dialect by name. It panics on an empty or duplicate name.

func SameDefinition

func SameDefinition(a, b Dependent) (bool, error)

SameDefinition compares what two dependents re-create by canonical JSON; On and Refusal describe why one was found, not what it is. Dialects delegate to it from SameDependent when they have no looser rule.

func Validate

func Validate(a Artifact) error

Validate checks the version and hash, then re-plans from the artifact's own inputs and requires the same hash, so edited SQL, units or changes are refused.

func ValidateAcknowledgements

func ValidateAcknowledgements(a Artifact, acknowledgements []string) error

ValidateAcknowledgements requires every destructive change to be acknowledged exactly once and nothing else.

func ValidateRequest

func ValidateRequest(req ApplyRequest) error

ValidateRequest checks the reviewed inputs without touching a database.

Types

type ApplyRequest

type ApplyRequest struct {
	Artifact         Artifact
	Hash             string
	Acknowledgements []string
	LockTimeout      time.Duration
}

type Artifact

type Artifact struct {
	Version      int            `json:"version"`
	Dialect      string         `json:"dialect"`
	Capabilities Capabilities   `json:"capabilities"`
	Scope        Scope          `json:"scope"`
	Baseline     migrate.Schema `json:"baseline"`
	Desired      migrate.Schema `json:"desired"`
	// Context lists objects read only because a dependent sits on them; they
	// are never planned or preserved.
	Context   []migrate.Name `json:"context,omitempty"`
	Selection []string       `json:"selection,omitempty"`
	// SelectNone says the plan was limited to no change at all.
	SelectNone bool `json:"selectNone,omitempty"`
	// Dependents are the dependents the plan rebuilds, with the definitions to re-create and verify.
	Dependents []Dependent `json:"dependents,omitempty"`
	// Refusals are the inspection refusals no planned change touches.
	Refusals []Refusal `json:"refusals,omitempty"`
	// Warnings name the definitions the dialect compares as written.
	Warnings []string `json:"warnings,omitempty"`
	// Changes are the planned changes, forced rebuilds included.
	Changes []migrate.Change `json:"changes"`
	// Preserved are the drops left unplanned because the table is declared
	// partial (or, for a whole object, because the scope is declared).
	Preserved []migrate.Change `json:"preserved,omitempty"`
	Units     []Unit           `json:"units"`
	Atomic    bool             `json:"atomic,omitempty"`
	Hash      string           `json:"hash"`
}

Artifact binds reviewed, ordered, grouped SQL to the snapshots it was planned from.

func Plan

func Plan(req PlanRequest) (Artifact, error)

Plan diffs Current against Desired and plans the selected changes, the rebuilds they force, their global order, preconditions and units. It reads no database: live dependents and refusals arrive in the request.

func PlanLive

func PlanLive(ctx context.Context, q Querier, req PlanLiveRequest) (Artifact, error)

PlanLive reads capabilities, the current schema and the live dependents of the columns the selected changes force, then plans. Dependents that sit on objects outside the scope are inspected again and carried as context, so the baseline holds everything a unit will touch. Inspection refusals go to Plan, which fails only when a planned change or rebuild touches one.

type Capabilities

type Capabilities struct {
	Fingerprint      string          `json:"fingerprint"`
	TransactionalDDL bool            `json:"transactionalDdl"`
	Features         map[string]bool `json:"features,omitempty"`
}

type ColumnRef

type ColumnRef struct {
	Table  migrate.Name `json:"table"`
	Column string       `json:"column"`
	// Dropped is set when the forcing change removes this column, or its whole table (an empty Column names the table itself), so a dependent on it cannot be re-created.
	Dropped DroppedKind `json:"dropped,omitempty"`
}

type Dependent

type Dependent struct {
	Kind       DependentKind       `json:"kind"`
	Table      migrate.Name        `json:"table"`
	Name       string              `json:"name"`
	On         []ColumnRef         `json:"on,omitempty"` // the forcing columns it depends on
	Index      *migrate.Index      `json:"index,omitempty"`
	ForeignKey *migrate.ForeignKey `json:"foreignKey,omitempty"`
	Check      *migrate.Check      `json:"check,omitempty"`
	// Definition is the live definition for kinds with no model type (statistic, view).
	Definition string `json:"definition,omitempty"`
	// Refusal, when set, says why the dependent cannot be reproduced faithfully.
	Refusal string `json:"refusal,omitempty"`
}

Dependent is an object that depends on columns and must be dropped and re-created when they change. For the view and table kinds the dependent is the object itself: Table names it and its rebuild change has no member.

type DependentKind

type DependentKind string
const (
	DependentIndex            DependentKind = "index"
	DependentPrimaryKey       DependentKind = "primary-key"
	DependentUniqueConstraint DependentKind = "unique-constraint"
	DependentForeignKey       DependentKind = "foreign-key"
	DependentCheck            DependentKind = "check"
	DependentDefault          DependentKind = "default"
	DependentStatistic        DependentKind = "statistic"
	DependentTrigger          DependentKind = "trigger"
	DependentView             DependentKind = "view"
	DependentTable            DependentKind = "table"
)

type Dialect

type Dialect interface {
	Name() string
	// Capabilities reads what the database can do and fingerprints it. q == nil
	// means offline (the same convention as Dependents): return the dialect's
	// static capabilities, which hold for every server of the dialect: whether
	// its DDL is transactional, an EMPTY Fingerprint (an offline artifact is not
	// bound to one server, and Apply skips the fingerprint check for it) and only
	// the features no version or compatibility level can lack.
	Capabilities(ctx context.Context, q Querier) (Capabilities, error)
	Inspect(ctx context.Context, q Querier, scope Scope) (Inspection, error)
	// Dependents lists what depends on columns. q == nil means offline: derive
	// from current only.
	Dependents(ctx context.Context, q Querier, current migrate.Schema, columns []ColumnRef) ([]Dependent, error)
	Diff(current, desired migrate.Schema) (Diff, error)
	Preconditions(change migrate.Change, current, desired migrate.Schema, caps Capabilities) ([]Precondition, error)
	// Open starts a unit on its dedicated connection: it sets pragmas, the
	// lock, the lock timeout and session options, and begins a transaction
	// when opts.Transactional. The engine calls the returned Finish exactly
	// once: commit=true only after the postcondition passed.
	Open(ctx context.Context, conn *sql.Conn, opts SessionOptions) (UnitSession, error)
	// Reconcile returns desired rewritten so that unset attributes inherit the
	// live value and values the database considers equal to the live ones are
	// spelled like them (Postgres default expressions, SQL Server collation).
	Reconcile(ctx context.Context, q Querier, current, desired migrate.Schema) (migrate.Schema, error)
	// SameDependent reports whether a dependent that was rebuilt is back as it
	// was: before is the one recorded at plan time, after the one read now. A
	// dialect may accept a changed definition (a Postgres view's stored text
	// changes after a retype); SameDefinition is the strict comparison.
	SameDependent(before, after Dependent) (bool, error)
	// Exec runs one statement of a plan. Any wrapping the dialect needs (SQL
	// Server's nested batch that sets session options) happens here, never in
	// the reviewed SQL.
	Exec(ctx context.Context, q Querier, s Statement) error
}

Dialect supplies everything database-specific. The engine narrows the schemas it hands to Diff to the objects of one unit when it classifies that unit, so:

  • Diff must accept a schema whose foreign keys reference a table that is not in the schema (the reference is compared by name and columns).
  • Inspect in declared mode returns exactly the scope's Objects that exist.
  • Schema.Native is passed through un-narrowed (the engine treats it as opaque), so a dialect that reads it must filter it to the objects left in the projection itself.

func Lookup

func Lookup(name string) (Dialect, error)

Lookup returns the registered dialect, or an error naming the known ones.

type Diff

type Diff interface {
	// Changes lists every change with Destructive and Requires set.
	Changes() []migrate.Change
	// Forcing lists the changes that force dependents to be rebuilt.
	Forcing() []Forcing
	// Lower returns the primitive ops for the selected changes and rebuilds.
	Lower(selection []string, rebuilds []Rebuild) ([]Op, error)
	// Warnings lists the definitions the dialect compares as written because it
	// does not understand their bodies.
	Warnings() []string
}

Diff is one comparison of two schemas, held by the dialect so that Lower can reach the dialect's own representation of each change.

type DriftError

type DriftError struct {
	Unit    string
	Changes []migrate.Change
}

DriftError reports a unit whose objects are neither at the artifact's baseline nor at its desired state.

func (*DriftError) Error

func (e *DriftError) Error() string

type DroppedKind

type DroppedKind string

DroppedKind says what a forcing change removes.

const (
	DroppedColumn DroppedKind = "column"
	DroppedTable  DroppedKind = "table"
)

type Forcing

type Forcing struct {
	Change  string      `json:"change"`
	Columns []ColumnRef `json:"columns"`
	// Retype means foreign-key partner columns must change with it.
	Retype bool `json:"retype,omitempty"`
}

Forcing is a change that forces dependents on its columns to be rebuilt.

type Inspection

type Inspection struct {
	Schema   migrate.Schema `json:"schema"`
	Refusals []Refusal      `json:"refusals,omitempty"`
}

type Op

type Op struct {
	ID         string       `json:"id"`
	Change     string       `json:"change"`
	Phase      Phase        `json:"phase"`
	Object     migrate.Name `json:"object"`
	Statements []Statement  `json:"statements"`
	Requires   []string     `json:"requires,omitempty"`
}

Op is the unit of ordering: the statements one change contributes in one phase.

type Outcome

type Outcome string
const (
	Applied        Outcome = "applied"
	AlreadyApplied Outcome = "already-applied"
	Failed         Outcome = "failed"
	CommitUnknown  Outcome = "commit-unknown"
)

type PartialError

type PartialError struct {
	Unit    string
	Missing []Dependent
}

PartialError reports a unit whose own changes are in place but a dependent it dropped to make them is missing or differs: it is neither applied nor pending, and re-running it would not bring the dependent back.

func (*PartialError) Error

func (e *PartialError) Error() string

type Phase

type Phase string
const (
	PhaseDrop   Phase = "drop"
	PhaseAlter  Phase = "alter"
	PhaseCreate Phase = "create"
)

type PlanLiveRequest

type PlanLiveRequest struct {
	Dialect   string
	Scope     Scope
	Desired   migrate.Schema
	Selection []string
	// SelectNone plans no change at all (see PlanRequest.SelectNone).
	SelectNone bool
	Atomic     bool
}

type PlanRequest

type PlanRequest struct {
	Dialect string
	// Using plans with this dialect instead of the one registered as Dialect,
	// so a pure planner can plan offline in a program that links no database
	// dialect of that name. Its Name must be Dialect.
	Using Dialect
	Scope Scope
	// Context lists objects present in Current only because a dependent sits on
	// them. They are not managed: no diff change on them is planned or preserved.
	Context []migrate.Name
	Current migrate.Schema
	Desired migrate.Schema
	// Selection limits the plan to those change IDs; empty plans every change.
	Selection []string
	// SelectNone plans no change at all (an artifact that records what it left
	// out and runs nothing). It excludes Selection.
	SelectNone   bool
	Dependents   []Dependent
	Refusals     []Refusal
	Capabilities Capabilities
	Atomic       bool
}

type Precondition

type Precondition struct {
	ID      string `json:"id"`
	Change  string `json:"change"`
	SQL     string `json:"sql"`
	Message string `json:"message"`
}

Precondition passes when its SQL returns no rows.

type PreconditionError

type PreconditionError struct {
	Unit    string
	ID      string
	Message string
}

PreconditionError reports a precondition query that returned a row.

func (*PreconditionError) Error

func (e *PreconditionError) Error() string

type Querier

type Querier interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

Querier is satisfied by *sql.DB, *sql.Conn and *sql.Tx.

type Rebuild

type Rebuild struct {
	Change    migrate.Change `json:"change"`
	Dependent Dependent      `json:"dependent"`
}

Rebuild is a forced drop and re-create of a dependent. Change.Action is "rebuild" and Change.Cause names the forcing change.

type Refusal

type Refusal struct {
	Object migrate.Name `json:"object"`
	Member string       `json:"member,omitempty"`
	Reason string       `json:"reason"`
}

Refusal is an object or member the inspector could not read faithfully.

type Result

type Result struct {
	Hash    string       `json:"hash"`
	Outcome Outcome      `json:"outcome"`
	Units   []UnitResult `json:"units,omitempty"`
}

func Apply

func Apply(ctx context.Context, db *sql.DB, req ApplyRequest) (Result, error)

Apply runs the artifact's units in order, each in its own transaction (or on a dedicated connection when it holds a non-transactional statement). A unit already at its desired state is skipped. The first error stops the run; earlier units stay committed and are reported, so a re-run resumes.

type Scope

type Scope struct {
	Mode    ScopeMode      `json:"mode"`
	Schemas []string       `json:"schemas,omitempty"`
	Objects []migrate.Name `json:"objects,omitempty"` // the managed objects in declared mode
}

type ScopeMode

type ScopeMode string
const (
	// ScopeDeclared manages only the named objects: an undeclared table or other
	// object is never dropped. A declared table is complete unless it is marked
	// partial, so its undeclared members are dropped.
	ScopeDeclared ScopeMode = "declared"
	// ScopeComplete manages every object of the schemas; drops are planned,
	// except for the members of a partial table.
	ScopeComplete ScopeMode = "complete"
)

type SessionOptions

type SessionOptions struct {
	LockTimeout time.Duration
	Unit        string
	// Transactional is the unit's flag: its statements may share one transaction.
	Transactional bool
}

type Statement

type Statement struct {
	SQL              string `json:"sql"`
	NonTransactional bool   `json:"nonTransactional,omitempty"`
	SizeOfData       bool   `json:"sizeOfData,omitempty"`
}

type Unit

type Unit struct {
	ID            string         `json:"id"`
	Changes       []string       `json:"changes"`
	Objects       []migrate.Name `json:"objects"`
	Ops           []Op           `json:"ops"`
	Preconditions []Precondition `json:"preconditions,omitempty"`
	Transactional bool           `json:"transactional"`
}

Unit is a connected component of the op graph, executed in one transaction where the dialect allows it.

type UnitResult

type UnitResult struct {
	ID         string  `json:"id"`
	Outcome    Outcome `json:"outcome"`
	Statements int     `json:"statements"`
}

type UnitSession

type UnitSession struct {
	// Q runs the unit's inspection, preconditions and statements.
	Q Querier
	// Finish commits or rolls back, releases locks and restores the
	// connection's settings. The engine calls it exactly once.
	Finish func(ctx context.Context, commit bool) error
}

UnitSession is how a dialect runs one unit on its dedicated connection.

func TxSession

func TxSession(ctx context.Context, conn *sql.Conn, setup func(ctx context.Context, q Querier) error) (UnitSession, error)

TxSession is the session of a dialect whose unit is one transaction: it begins one on conn, runs setup inside it (lock, lock timeout, session options), and commits or rolls back in Finish. A failing setup rolls back and returns the setup error.

type UnitState

type UnitState string
const (
	UnitApplied UnitState = "applied"
	UnitPending UnitState = "pending"
)

Jump to

Keyboard shortcuts

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