Help us shape the future of Go! Take the 2026 Go Developer Survey

migrate

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

README

SQL Server migrations

migrate/sqlserver.Plan compares typed current and desired schemas and generates ordered SQL without opening a database. migrate/atlas/sqlserver exposes the same differ and planner to Atlas consumers. Sqlglot also compiles and checks immutable migration artifacts. Inspection, credentials, application locks, transactions, execution and deployment records belong to the caller.

import (
    "github.com/flanksource/sqlglot-go/migrate"
    "github.com/flanksource/sqlglot-go/migrate/sqlserver"
)

plan, err := sqlserver.Plan(migrate.Request{
    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.

Request.Current is the target baseline. Request.Desired is the complete desired state, including target members the caller intends to preserve. An omitted current object or member is dropped. Selection overlays belong above the planner; passing a partially selected schema as the desired state would drop unselected members.

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, primary-key and UNIQUE-constraint identity. Foreign keys retain ordered referenced columns and referential actions. Checks retain their names and expressions. Duplicate objects, missing referenced tables or columns, 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; these must be present in the snapshot. 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.

Plan.Changes contains stable IDs and destructive classifications. Plan.Steps contains SQL in execution order and the change responsible for each statement. 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.

The native model describes supported logical schema features. Snapshot capture must reject incomplete visibility, encrypted definitions and unsupported physical features such as partitioning, computed columns and temporal tables before constructing a request. There are no guessed renames, table rebuilds, physical column reordering, data backfills or execution fallbacks. The returned SQL is a plan; a deployment artifact must add its own baseline checks, locking, transaction, idempotence and postconditions before applying it.

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 Artifact added in v1.0.5

type Artifact struct {
	Version int      `json:"version"`
	Schemas []string `json:"schemas"`
	Request Request  `json:"request"`
	Plan    Plan     `json:"plan"`
	Hash    string   `json:"hash"`
}

Artifact binds reviewed SQL to complete baseline and desired snapshots.

type ArtifactRequest added in v1.0.5

type ArtifactRequest struct {
	Schemas []string
	Request Request
}

type ArtifactState added in v1.0.5

type ArtifactState string
const (
	ArtifactPending ArtifactState = "pending"
	ArtifactApplied ArtifactState = "applied"
)

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"`
}

type Check

type Check struct {
	Name       string `json:"name"`
	Expression string `json:"expression"`
}

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"`
}

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"`
}

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 Plan

type Plan struct {
	Steps   []Step   `json:"steps"`
	Changes []Change `json:"changes"`
}

type Request

type Request struct {
	Current Schema `json:"current"`
	Desired Schema `json:"desired"`
	// Selection limits the plan to these change IDs; empty plans every change.
	Selection []string `json:"selection,omitempty"`
}

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"`
}

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 Step

type Step struct {
	Change Change `json:"change"`
	SQL    string `json:"sql"`
}

type Table

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

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.
internal
Package sqlserver plans SQL Server schema migrations without a database connection.
Package sqlserver plans SQL Server schema migrations without a database connection.

Jump to

Keyboard shortcuts

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