migrate

package
v1.3.8 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 0 Imported by: 2 modules, 2 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.

README

Schema migrations

migrate/engine plans and applies schema migrations for every dialect. A dialect (database/migrate/dialect/sqlserver, postgres or sqlite, registered by importing it) supplies inspection, diffing and lowering; the engine adds the scope policy, forced rebuilds of dependent objects, global ordering, units, preconditions and the reviewed artifact once. migrate/sqlserver is the pure SQL Server half: it diffs two schemas and lowers the changes to ordered T-SQL without opening a database, and migrate/atlas/sqlserver exposes the same differ and planner to Atlas consumers. Credentials, application locks, transactions, execution and deployment records belong to the dialect's session and the caller.

import (
    _ "github.com/flanksource/sqlglot-go/database/migrate/dialect/sqlserver"
    "github.com/flanksource/sqlglot-go/migrate"
    "github.com/flanksource/sqlglot-go/migrate/engine"
)

artifact, err := engine.Plan(engine.PlanRequest{
    Dialect: "sqlserver",
    Scope:   engine.Scope{Mode: engine.ScopeComplete, Schemas: []string{"dbo"}},
    Desired: migrate.Schema{Tables: []migrate.Table{{
        Name:    migrate.Name{Schema: "dbo", Name: "orders"},
        Columns: []migrate.Column{{Name: "id", Type: "int"}},
    }}},
})

Run the complete example with go run ./examples/sqlserver-migration from the module root. It prints generated SQL and never connects to a database. engine.PlanLive is the same plan against a database: it reads the capabilities, the current schema and the live dependents first. See ARTIFACTS.md for the artifact, its scopes, forced rebuilds, preconditions and units, and how an artifact is applied, checked and rendered as a script.

PlanRequest.Current is the target baseline and PlanRequest.Desired the desired state. In complete scope an omitted current object or member is dropped, and each drop is a destructive change that must be acknowledged. In declared scope only the named objects are managed: an undeclared object is never dropped, and an omitted member of a declared table is dropped like in complete scope. A table declaration is complete unless it sets Table.Partial (partial = true in HCL): the drop of any member of a partial table (column, index, key, foreign key, check, default) is preserved in both scopes, so a partial declaration names only what it wants to manage. A partial table the target does not have is an error, because a partial declaration cannot create a table. A dependent that cannot be re-created over a dropped column, or an inbound foreign key from another table on it, fails the plan by name unless the same plan drops or declares it away. A partially selected schema must not be passed as the desired state in complete scope: it would drop the unselected members. Selection is a list of change IDs on the plan, not an edit of the schema.

Every object requires an explicit schema and catalog name. Schemas must already exist. Columns retain SQL Server types, nullability, identity seed/increment, named defaults and collation. Indexes retain ordered key columns, descending flags, included columns, filters, clustering, fill factor and primary-key and UNIQUE-constraint identity; an index read from a live database also keeps its padding, lock flags, compression and filegroup so a rebuild re-creates it faithfully. Foreign keys retain ordered referenced columns and referential actions. Checks retain their names and expressions. A foreign key may reference a table the schema does not hold, because the engine plans schemas narrowed to the objects a plan touches; the diff never reports the missing table. Duplicate objects, missing referenced columns of a table the schema does hold, invalid types and unsupported changes fail planning.

Definition carries a full qualified CREATE, CREATE OR ALTER or ALTER procedure, function, view or DML-trigger definition in SQL. Kind is PROCEDURE, FUNCTION, VIEW or TRIGGER. Triggers also require Parent and preserve Disabled. Dependencies names the catalog objects required by the definition; a dependency the schema does not hold is left unbound and neither created nor dropped by the diff. Capture must supply complete dependency metadata. The planner orders creates and drops by dependencies, detaches cyclic foreign keys and rejects remaining dependency cycles. Module definitions run in separate batches, with only their leading verb rewritten to CREATE OR ALTER; their remaining source bytes are preserved.

For native T-SQL module analysis, use sqlglot.ParseScript and inspect its diagnostics, or use CanonicalSQL for semantic comparison. These entrypoints support structured SQL Server triggers. ParseOne retains the upstream reference's single-statement tree contract, including opaque trigger commands. ParseScript.Complete describes scan completion; a successful analysis additionally requires no diagnostics and a non-nil tree.

Artifact.Changes contains stable IDs and destructive classifications. Each unit lists its ops and statements in execution order and the change responsible for each. Several statements can implement one change, such as replacing a named default or setting a trigger's disabled state. Drops and potentially lossy column type, collation or nullability changes are marked destructive. Callers must enforce selection, review and acknowledgments before execution; engine.Apply requires them.

The native model describes supported logical schema features. Inspection refuses, per object, what it cannot reproduce faithfully: encrypted definitions and unsupported physical features such as partitioning, computed columns and temporal tables. A refusal blocks a plan only when a change or a forced rebuild touches that object. There are no guessed renames, physical column reordering, data backfills or execution fallbacks.

Commons-db's SQL Server driver consumes migrate/atlas/sqlserver for diffing, type conversion and planning. Sqlglot imports neither commons-db nor UIR. To release a consumer of the extracted packages, publish sqlglot first, then update the consumer's pinned module version and verify with GOWORK=off; a workspace-only import is insufficient for release.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Change

type Change struct {
	ID          string `json:"id"`
	Action      string `json:"action"`
	Kind        string `json:"kind"`
	Object      Name   `json:"object"`
	Member      string `json:"member,omitempty"`
	Destructive bool   `json:"destructive"`
	Reason      string `json:"reason,omitempty"`
	// RuntimeDependencies flags a module whose references bind only at runtime.
	RuntimeDependencies []RuntimeDependency `json:"runtimeDependencies,omitempty"`
	// Requires lists the change IDs that must be selected with this one.
	Requires []string `json:"requires,omitempty"`
	// Cause is the ID of the change that forced this rebuild.
	Cause string `json:"cause,omitempty"`
}

type Check

type Check struct {
	Name       string `json:"name"`
	Expression string `json:"expression"`
	// NotForReplication is read from a live check so a rebuild keeps it; the diff does not compare it.
	NotForReplication bool `json:"notForReplication,omitempty"`
}

type Column

type Column struct {
	Name      string    `json:"name"`
	Type      string    `json:"type"`
	Nullable  bool      `json:"nullable"`
	Identity  *Identity `json:"identity,omitempty"`
	Default   *Default  `json:"default,omitempty"`
	Collation string    `json:"collation,omitempty"`
	RowGUID   bool      `json:"rowGuid,omitempty"`
}

type Default

type Default struct {
	Name       string `json:"name"`
	Expression string `json:"expression"`
	// SystemNamed marks a constraint SQL Server named itself (DF__table__col__hex).
	// Its name differs in every database, so it is never compared, and a new
	// one is created unnamed; Name is still what a drop of the live one uses.
	SystemNamed bool `json:"systemNamed,omitempty"`
}

type Definition

type Definition struct {
	Name     Name   `json:"name"`
	Kind     string `json:"kind"`
	SQL      string `json:"sql"`
	Parent   *Name  `json:"parent,omitempty"`
	Disabled bool   `json:"disabled,omitempty"`
	// QuotedIdentifierOff records a module created under SET QUOTED_IDENTIFIER
	// OFF, where double quotes delimit strings rather than identifiers.
	QuotedIdentifierOff bool   `json:"quotedIdentifierOff,omitempty"`
	Dependencies        []Name `json:"dependencies,omitempty"`
	// RuntimeDependencies are references the catalog could not bind to a local
	// object: missing objects, cross-database or linked-server names, built-ins
	// and method calls. They resolve when the module runs, so they never order DDL.
	RuntimeDependencies []RuntimeDependency `json:"runtimeDependencies,omitempty"`
}

type ForeignKey

type ForeignKey struct {
	Name              string   `json:"name"`
	Columns           []string `json:"columns"`
	References        Name     `json:"references"`
	ReferencedColumns []string `json:"referencedColumns"`
	OnDelete          string   `json:"onDelete,omitempty"`
	OnUpdate          string   `json:"onUpdate,omitempty"`
	// NotForReplication is read from a live key so a rebuild keeps it; the diff does not compare it.
	NotForReplication bool `json:"notForReplication,omitempty"`
}

type Identity

type Identity struct {
	Seed      int64 `json:"seed"`
	Increment int64 `json:"increment"`
}

type Index

type Index struct {
	Name       string        `json:"name"`
	Columns    []IndexColumn `json:"columns"`
	Included   []string      `json:"included,omitempty"`
	Unique     bool          `json:"unique,omitempty"`
	Primary    bool          `json:"primary,omitempty"`
	Clustered  bool          `json:"clustered,omitempty"`
	Constraint bool          `json:"constraint,omitempty"`
	Filter     string        `json:"filter,omitempty"`
	// FillFactor is 1-99; 0 is the server default, which FILLFACTOR = 100 equals.
	FillFactor int `json:"fillFactor,omitempty"`
	// The options below are read from a live index so a rebuild re-creates it
	// faithfully; the diff does not compare them.
	PadIndex     bool `json:"padIndex,omitempty"`
	IgnoreDupKey bool `json:"ignoreDupKey,omitempty"`
	NoRowLocks   bool `json:"noRowLocks,omitempty"`
	NoPageLocks  bool `json:"noPageLocks,omitempty"`
	NoRecompute  bool `json:"noRecompute,omitempty"`
	// Compression is ROW or PAGE; empty is none.
	Compression string `json:"compression,omitempty"`
	// Filegroup is set only when the index is not on the default filegroup.
	Filegroup string `json:"filegroup,omitempty"`
}

type IndexColumn

type IndexColumn struct {
	Name       string `json:"name"`
	Descending bool   `json:"descending,omitempty"`
}

type Name

type Name struct {
	Schema string `json:"schema"`
	Name   string `json:"name"`
}

type RuntimeDependency added in v1.1.0

type RuntimeDependency struct {
	Server   string `json:"server,omitempty"`
	Database string `json:"database,omitempty"`
	Schema   string `json:"schema,omitempty"`
	Name     string `json:"name"`
}

type Schema

type Schema struct {
	Tables      []Table      `json:"tables"`
	Definitions []Definition `json:"definitions"`
	Sequences   []Sequence   `json:"sequences,omitempty"`
	TableTypes  []TableType  `json:"tableTypes,omitempty"`
	// Native is a dialect's own lossless description of the schema (Atlas HCL) when the fields above cannot hold it; the fields are then a projection of the same objects.
	Native string `json:"native,omitempty"`
}

type Sequence added in v1.1.0

type Sequence struct {
	Name      Name   `json:"name"`
	Type      string `json:"type"`
	Start     string `json:"start"`
	Increment string `json:"increment"`
	Minimum   string `json:"minimum"`
	Maximum   string `json:"maximum"`
	Cycle     bool   `json:"cycle,omitempty"`
	NoCache   bool   `json:"noCache,omitempty"`
	CacheSize int64  `json:"cacheSize,omitempty"`
}

Sequence is a CREATE SEQUENCE object. Numeric bounds are exact decimal strings so every integer and decimal sequence type round-trips. CacheSize 0 with NoCache false is the server's default cache.

type Table

type Table struct {
	Name        Name         `json:"name"`
	Partial     bool         `json:"partial,omitempty"`
	Columns     []Column     `json:"columns"`
	Indexes     []Index      `json:"indexes,omitempty"`
	ForeignKeys []ForeignKey `json:"foreignKeys,omitempty"`
	Checks      []Check      `json:"checks,omitempty"`
}

Table is a table declaration. A declaration is complete: the columns, indexes, keys and checks it omits are dropped from a table that has them. Partial says it names only some of the table's members, so the plan leaves every other member of the live table alone and never creates the table. It is read from the desired declaration; an inspected table never sets it, and the diff does not compare it.

type TableType added in v1.1.0

type TableType struct {
	Name    Name     `json:"name"`
	Columns []Column `json:"columns"`
	Keys    []Index  `json:"keys,omitempty"`
	Checks  []string `json:"checks,omitempty"`
}

TableType is a CREATE TYPE ... AS TABLE user-defined table type. SQL Server names a table type's constraints itself, so its defaults, keys and checks carry no names: Default.Name, Index.Name and Check.Name stay empty. Keys are the PRIMARY KEY and UNIQUE constraints; a table type cannot be altered.

Directories

Path Synopsis
atlas
Package changeset names atlas schema changes as selectable, typed migration changes and filters a diff down to a reviewed selection before planning.
Package changeset names atlas schema changes as selectable, typed migration changes and filters a diff down to a reviewed selection before planning.
Package engine is the dialect-neutral schema planner and executor.
Package engine is the dialect-neutral schema planner and executor.
internal
Package sqlserver is the pure half of the SQL Server dialect: it compares two schemas, lowers the changes to statements and renders reviewed artifacts as scripts, all without a database connection.
Package sqlserver is the pure half of the SQL Server dialect: it compares two schemas, lowers the changes to statements and renders reviewed artifacts as scripts, all without a database connection.

Jump to

Keyboard shortcuts

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