migrate

package
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 43 Imported by: 2 modules, 1 package

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

HCL migrations

This package owns the HCL and script migration engine extracted from commons-db. See standalone database documentation for the unified CLI, read-only bundle preview and reviewed PostgreSQL/SQLite schema artifacts. commons-db retains compatible API shims.

migrate.Apply is the single filesystem-backed migration seam for PostgreSQL, SQLite and SQL Server. The connection string selects the target, while callers pass the same embedded Atlas HCL bundle and options. SQL Server bundles are SQL Server-shaped rather than portable; see SQL Server.

err := migrate.Apply(ctx, dsn, schemaFS,
    migrate.WithDir("migrations"),
    migrate.WithName("runtime"),
)

Target selection

PostgreSQL accepts postgres://, postgresql://, and keyword connection strings such as host=localhost dbname=runtime sslmode=disable.

SQLite accepts sqlite:// URLs and plain file paths ending in .db:

err := migrate.Apply(ctx, "sqlite://state/runtime.sqlite", schemaFS, migrate.WithDir("migrations"))
err := migrate.Apply(ctx, "/var/lib/example/runtime.db", schemaFS, migrate.WithDir("migrations"))

SQL Server accepts sqlserver:// URLs in the go-mssqldb form, e.g. sqlserver://user:password@host:1433?database=app. mssql:// is rejected so that one spelling reaches the migrator. ADO connection strings (;-separated pairs that name the server with server, data source, address, addr or network address, e.g. server=db;user id=app;password=secret;database=acme) and odbc: connection strings are SQL Server too, and are passed to go-mssqldb unchanged.

Existing connections

WithDB runs a SQL Server or SQLite migration on a *sql.DB the caller already holds, with the connection string left empty. The dialect comes from the handle's driver. Apply neither closes the handle nor changes its pool settings:

err := migrate.Apply(ctx, "", bundle,
	migrate.WithDB(writeDB),
	migrate.WithRoutines("routines"),
	migrate.WithName("acme/routines"))

Passing both a connection string and WithDB is an error. A PostgreSQL (lib/pq) handle is accepted for the default schema: each schema unit sets and restores its own lock_timeout on a dedicated connection. A handle whose search_path resolves unqualified names to another schema (current_schema() is not public, e.g. search_path=tenant,public) is refused, naming both schemas, because its scripts and metadata tables would land there while the schema units write public. WithSchema with another schema needs a connection string, because the script phases and metadata tables resolve unqualified names through search_path, which only a connection the migration opens can scope.

Relative SQLite paths are resolved from the process working directory. SQLite is always file-backed; :memory: and mode=memory are rejected. The normalized connection enables foreign keys, a 5-second busy timeout, and WAL while preserving caller-supplied query parameters and unmanaged pragmas.

Unknown URI schemes written as scheme://... fail instead of being passed to PostgreSQL accidentally. Scheme-like strings without :// are treated as PostgreSQL DSNs unless they are SQL Server ADO/ODBC strings or their path ends in .db; use one of the explicit forms above rather than relying on that ambiguity. A PostgreSQL keyword DSN remains PostgreSQL even when its dbname ends in .db.

db.NewGorm uses the same DSN resolver, so migration and application connections cannot disagree about the target.

Portable canonical HCL

A cross-database bundle declares PostgreSQL-shaped Atlas HCL. PostgreSQL evaluates the declaration directly. SQLite evaluates the same declaration with the PostgreSQL evaluator, validates the resulting realm against the compatibility contract below, and then projects it to SQLite. Acceptance by the HCL parser alone does not mean an object is SQLite-compatible.

All .hcl files below WithDir are loaded recursively in lexical path order and evaluated as one realm. Every file may start with the same schema "public" {} block, as a tool that evaluates one file alone requires: identical schema blocks repeated across files are one schema, for PostgreSQL, SQLite and SQL Server alike. Two blocks of one name that differ are an error naming both files, and a bundle that declares two different schemas keeps the error of its dialect. variable blocks are supported on both targets when callers provide values through WithVariables; the resulting schema must still fit the portable set.

Supported cross-database blocks
HCL block Supported portable form SQLite behavior
variable Atlas variable declarations referenced by schema expressions Evaluated before projection using WithVariables values
schema Exactly one schema "public" {} Projected to SQLite's main schema
table One or more tables assigned to schema.public, optionally with partial = true Created with their declared portable columns and constraints; a partial table keeps every member it does not name and cannot be created
column type, null, and a literal or sql(...) default Type is mapped as documented below; default SQL is preserved verbatim
primary_key Column references only Preserved when the table is first created or safely rebuilt
unique Named constraint over column references Projected to a named unique index
index Column references, optional unique, and optional where; default or explicit B-tree method only Projected to a SQLite index; where is preserved verbatim
foreign_key Local and referenced columns plus on_update and on_delete actions Preserved when the table is first created or safely rebuilt
check Named check with expr and no dialect attributes Preserved verbatim when the table is first created or safely rebuilt

Index expressions, per-column index attributes such as sort direction or operator classes, foreign-key attributes, and table or check attributes outside the forms above are not in the portable set.

Supported portable column types

The following table lists the PostgreSQL type families accepted after HCL evaluation, not every type accepted by Atlas's PostgreSQL parser. Underscored names such as character_varying and double_precision are direct HCL aliases. Space-containing SQL spellings and the less common aliases noted below are accepted through sql("...") and normalize to the same family.

PostgreSQL HCL type SQLite declaration Compatibility notes
uuid text No SQLite UUID-format constraint is added
text, char, character, varchar, character_varying, bpchar, name; SQL spelling character varying text Length modifiers and PostgreSQL's internal name limit are not preserved
json, jsonb text plus json_valid(column) The generated check is named <table>_<column>_json
date, time, timetz, timestamp, timestamptz; SQL spellings time with time zone, time without time zone, timestamp with time zone, timestamp without time zone datetime Precision and timezone enforcement are not preserved by SQLite
int2, int4, int8, int, integer, smallint, bigint, xid, xid8 integer PostgreSQL width and transaction-ID distinctions collapse to SQLite integer affinity
bool, boolean bool SQLite gives the declared bool type NUMERIC affinity; it has no native boolean type
bytea blob Binary values remain binary
numeric, decimal numeric Precision and scale modifiers are not preserved
real, float, float4, float8, double_precision real Precision modifiers and PostgreSQL width distinctions are not preserved

Use only type modifiers whose loss is acceptable to the application, or enforce the invariant with a portable named check. Evaluated type families outside this table fail projection; they are not coerced to text.

Portable example
schema "public" {}

table "projects" {
  schema = schema.public

  column "id" {
    type = uuid
    null = false
  }
  column "payload" {
    type    = jsonb
    null    = false
    default = sql("'{}'")
  }
  column "created_at" {
    type    = timestamptz
    null    = false
    default = sql("CURRENT_TIMESTAMP")
  }

  primary_key {
    columns = [column.id]
  }
}

table "events" {
  schema = schema.public

  column "id" {
    type = uuid
    null = false
  }
  column "project_id" {
    type = uuid
    null = false
  }
  column "event_key" {
    type = text
    null = false
  }
  column "active" {
    type    = bool
    null    = false
    default = false
  }

  primary_key {
    columns = [column.id]
  }
  foreign_key "events_project_id_fkey" {
    columns     = [column.project_id]
    ref_columns = [table.projects.column.id]
    on_update   = NO_ACTION
    on_delete   = CASCADE
  }
  index "events_active_key" {
    unique  = true
    columns = [column.project_id, column.event_key]
    where   = "active"
  }
  check "events_event_key_nonempty" {
    expr = "length(event_key) > 0"
  }
}

Defaults, checks, and partial-index predicates are SQL strings, not a portable expression language. commons-db does not translate them. Every expression in a cross-database bundle must be accepted with the intended meaning by both PostgreSQL and SQLite. CURRENT_TIMESTAMP and sql("'{}'") are portable examples; PostgreSQL-only casts such as ::jsonb, functions such as now(), operators, and JSON expressions must not be assumed portable.

SQLite rejection list

SQLite rejects the following before schema mutation:

Incompatible declaration or option Reason
No table declarations The SQLite reconciler requires at least one declared table
More than one schema, or a schema other than public A portable bundle maps exactly one canonical schema to SQLite main
Realm or schema attributes and objects, including enums, domains, extensions, sequences, views, functions, and procedures There is no defined lossless projection
Table triggers Trigger SQL is dialect-specific
Column types outside the supported type table The projector never guesses an affinity
Column attributes such as generated or identity behavior PostgreSQL attributes cannot be preserved by the current projection
Table attributes other than plain named checks and partial Storage parameters, partitioning, and other PostgreSQL metadata are not portable
Check attributes Only the check name and expression are portable
Non-B-tree index methods SQLite cannot preserve PostgreSQL access-method behavior
Expression indexes or index-part attributes Only direct column references are portable
Foreign-key attributes beyond columns, references, and actions PostgreSQL-only metadata would be lost
A user check named <table>_<json-column>_json with a different expression That name is reserved for the generated json_valid check
Any .sql migration file SQL phases are PostgreSQL-only; SQLite does not skip them silently
role or permission blocks Managed security is PostgreSQL-only
WithExclude(...) naming a member of a table (table.column) A rebuild cannot keep a column, index or key the plan cannot see; whole tables may be excluded
WithSchema(...) with a value other than public SQLite has no PostgreSQL schema namespace

These declarations are parser-valid PostgreSQL HCL but are not SQLite-compatible: bit strings, network and MAC types, spatial types, intervals, serial and identity types, XML, money, arrays, ranges and multiranges, full-text search types, enums, domains, and other user-defined types.

Accepted declarations with different SQLite semantics

Some declarations are accepted because their storage representation is useful on both targets, but SQLite cannot enforce every PostgreSQL semantic:

  • UUIDs are stored as text without a canonical-format check.
  • String length, numeric precision and scale, floating-point width, and time precision are normalized to SQLite affinities.
  • json and jsonb both become validated JSON text; PostgreSQL JSONB indexing and operators are not provided.
  • Date and time families become datetime; SQLite does not enforce PostgreSQL timezone or temporal-type distinctions.
  • Integer widths collapse to SQLite integer affinity.
  • Boolean declarations have NUMERIC affinity and do not restrict stored values to 0 or 1; add a portable check when that invariant matters.
  • Defaults, checks, foreign-key actions, and partial-index predicates are carried as written. Syntax or semantics that differ between engines fail at apply time or behave according to the target engine.
SQLite migration-time limits

PostgreSQL and SQLite bundles are planned by the shared planner (migrate/engine): the HCL is evaluated with its variables, projected to the dialect, diffed against the live database and applied one unit (a table with its dependents) per transaction. A table rebuilt to change a column keeps its rows. Undeclared tables and types are never dropped by default, on either dialect.

Apply records, per bundle scope, the hash of the desired schema it brought the database to in a schema_migration_schema table (beside the script metadata on PostgreSQL; never planned or dropped, even under WithDrops()). The hash covers the evaluated HCL (variables, exclusions and partial tables applied), the dialect, the migrated schema, the drop scope, the exclusions and the path and content hash of every SQL script. When the next Apply computes the same hash, it skips inspecting and planning the schema; scripts still run by their own hashes, and a pre script that is not runs: always makes the schema plan again. The reviewed workflow (workflow.Apply of a PostgreSQL or SQLite schema artifact) empties the ledger of every schema the artifact covers before its first unit runs and again after it finishes, so the next Apply of any bundle there, including one recorded before the deploy, plans against the database and repairs what the deploy moved; ForgetRecordedSchemas does the same for any other writer. A change made by hand outside the bundle and the workflow is not repaired, and an undeclared column is not reported again, until the bundle changes or the ledger is forgotten. SQL Server bundles keep no ledger, and PreviewBundle never reads it.

A table declaration is complete unless its table block says partial = true (default false, a boolean; any other value, or the same table declared in two files, fails naming the file and table). A partial table never loses a member: the columns, indexes, keys, foreign keys and checks it does not name stay, even under WithDrops(), and a rebuild keeps them in the rebuilt table, so valid changes in the same migration still apply. A partial table the database does not have is an error, because a partial declaration cannot create a table. The attribute is a sqlglot extension: Atlas ignores it, so it is read from the parsed HCL and kept on migrate.Table.Partial, never in the canonical Atlas HCL.

The reviewed plan (workflow.Plan, PreviewBundle with WithReviewedPlan()) holds the drops of every undeclared member of a complete table as destructive changes to acknowledge. The unreviewed Apply, PreviewBundle without that option and PendingSQLServer have nobody to acknowledge them, so they run every planned change except the drop of a column, which holds data. Dropping an undeclared index, key, foreign key, check or default is executed. Each column left in place is reported every time the schema is planned, as a log warning from Apply and in Preview.Warnings and SQLServerPending.Warnings, naming the table and column and how to settle it: declare the column, mark the table partial = true, or apply with WithDrops() (SQL Server bundles do not support WithDrops, so only the first two are offered). If leaving a column drop out makes another change unappliable, the apply fails with the engine's message instead of running a partial plan. Preview.Artifact then holds only what would run, and no change when nothing is left.

WithDrops() makes the bundle the complete description of its schema: drops are planned for every undeclared table, type and column of a complete table, and the unreviewed Apply acknowledges them all, including column drops. On SQLite it inspects all user tables, so user tables omitted from the bundle are removed. The bundle's own schema_migration_* tables are never dropped. A rename represented by Atlas as a column removal and addition is a drop and an add of a column, so the old column is dropped in a complete table; this API does not infer rename mappings.

WithExclude(...) hides objects from the plan on both sides (live and declared), so they are neither created, altered nor dropped, even under WithDrops().

Each unit disables foreign-key enforcement while applying changes, verifies that no new foreign-key violations appear before commit, and restores enforcement afterward. An incompatible value or constraint rolls the unit back. A rebuild that would discard an unmanaged trigger is refused. SQLite's native column-addition rules still apply, and the migrator does not backfill values. Views remain outside the table bundle; callers must assess views that depend on changed columns.

PostgreSQL schema-scoped bundles

WithSchema applies one bundle inside a normalized PostgreSQL schema and leaves the default behavior on public unchanged:

err := migrate.Apply(ctx, dsn, schemaFS,
    migrate.WithName("runtime"),
    migrate.WithSchema("agent_tenant_context"),
)

The schema name must be a lowercase PostgreSQL identifier no longer than 63 bytes. The migration creates the schema and scopes Atlas inspection, HCL objects, SQL migration metadata, dependent-view handling, and managed security to it. A reusable HCL bundle still declares only schema "public" {}; migration remaps that declaration to the selected schema.

SQL files run with the selected schema as search_path. Keep objects owned by the bundle unqualified so the same bundle can target different schemas. Explicitly qualified SQL remains explicit and is not rewritten.

PostgreSQL SQL phases and security

SQL files default to the post-Atlas phase. Directives are read from the leading comment header:

-- phase: pre
-- dependsOn: 001_extensions.sql
-- runs: always
-- transaction: false
  • phase is pre or post; omitted means post.
  • dependsOn uses paths relative to the migration root. Dependencies are topologically ordered and changes rerun all transitive dependents.
  • Scripts are transactional by default; the SQL and its SHA-256 migration log commit atomically.
  • runs: always re-runs a script on every apply. It is an escape hatch for reconciliation that truly must occur at every boot, not a replacement for dependency tracking.

Views that read a column the schema step retypes are dropped and re-created automatically around the change, from their live definitions, with their owner, options, comment and grants, whether a script owns them or not. A script's recorded hash is left alone, so it does not re-run only because a column changed; edit the script when the view itself should change. Prefer small hash-gated files, such as one file per view or shared dependency, so steady-state startup remains DDL-free.

Atlas-style PostgreSQL role and permission blocks may live in the same HCL files as tables. The OSS migration layer supports roles and memberships plus schema, table, column, and sequence permissions. Managed grants are reconciled exactly within the bundle's metadata scope; unrelated roles and grants remain untouched. Different scopes must not manage the same role or grantee/object pair.

Reusable PostgreSQL test templates

migrate.NewProvisioner adapts an HCL and SQL bundle to dbtest.Options.Provisioner:

handle := dbtest.ForT(t, dbtest.Options{
    Name:    "query_sessions",
    LogName: "query-sessions-test",
    Provisioner: migrate.NewProvisioner(
        querySchema,
        migrate.WithDir("migrations"),
        migrate.WithName("query"),
    ),
})

The provisioner fingerprints the migration name, directory, Atlas options, variables, and every HCL and SQL file. dbtest prepares one sealed PostgreSQL template for that fingerprint, clones an isolated database for each call, and keeps the template for later tests. Normal hash-gated SQL is already present in the clone; runs: always scripts and security reconciliation still run for every instance.

This option requires database creation. dbtest fails before invoking the provisioner when COMMONS_DB_CREATE=false because that mode targets the configured database directly.

Programmatic SQLite declarations

The migrate/sqlite subpackage remains the lower-level seam for callers that already own a *sql.DB or *sql.Tx and construct Atlas *schema.Table declarations in Go. Its ReconcileTables function uses the same additive-only policy but does not load or project HCL.

declared, err := sqlitetable.Table{Name: "events", Columns: columns, StoredAs: stored, PrimaryKey: []string{"id"}}.Declare()
if err != nil {
    return err
}
if err := sqlitemigrate.ReconcileTables(ctx, tx, sqlitemigrate.ReconcileOptions{}, declared); err != nil {
    return err
}

The record store uses this lower-level API to add newly declared columns to tables that may already contain rows. New filesystem-backed migrations should call the target-aware parent migrate.Apply instead.

SQL Server

Reviewed CSV data

Plan against a saved SQL Server connection. Review the counts and selected files in review.json, then apply the plan file with the same source root and filters. This example assumes the review lists zero deletes.

sqlglot migrate plan --csv-root ./data --dsn connection://example \
  --layer 'country=none,BW' --layer 'env=!dev' --out ./review.json
sqlglot migrate apply --csv-root ./data --dsn connection://example \
  --layer 'country=none,BW' --layer 'env=!dev' ./review.json

For a plan with deletes, review the count for each table and pass each exact acknowledgement reported by the preview using repeatable --ack flags. The artifact contains source digests, selected files, filters, and operation counts. Source CSVs stay in the import root. The HTTP workflow accepts uploaded files with source.kind: csv and a layerFilters map. Apply takes both the artifact and the uploaded files.

Select files and layers

Place this AS.csv.yaml at the import root to map an example AsCode.csv and its country and environment overlays.

version: 1
defaults:
  schema: dbo
  tablePattern: '^(.*/)?(?P<table>AsCode)(_[A-Z]{2})?\.csv$'
  delimiter: "~"
layers:
  country:
    values: [BW, KE]
    match: ["**/*_${value}.csv"]
    valuePattern: "[A-Z]{2}"
  env:
    values: [dev, qa, prod]
    match: ["overrides/${value}/**/*.csv"]
tables:
  dbo.AsCode:
    key: [CODENAME, CODEVALUE]

Use tables.<schema.table>.sources for exact paths or globs with different names. Use a sidecar such as lookup.csv.yaml with version: 1 and table: dbo.Lookup to route a single file. Settings inherit in order from defaults, the table, and the sidecar. --csv-phase selects the tables with the matching YAML phase, which defaults to pre-rules. By default apply processes pre-rules first and post-rules second, committing each separately. Plan and apply each phase separately to schedule rule deployment between them.

Layer filters are independent. none selects untagged files, * selects every value, and !value excludes a value. Within a layer, a comma-separated filter includes the union of positive terms and subtracts exclusions. Files pass every layer. Use --layer name=filter for additional layers. An overlay row supersedes a less specific row when its tags include every tag of that row. Incomparable records for the same key require a more specific record or a narrower filter.

Unquoted \N defaults to SQL NULL. Quoting preserves it as text. An unquoted blank follows values.blank (empty-string, sql-null, or error). A quoted empty field always means an empty string. Configure alternatives through values.nullTokens, values.nullTokenCase, and per-column settings under values.columns.

The optional $delete column deletes the exact key on true. Missing, blank, and false mean upsert. Under the default delete: explicit, unmatched database rows remain. A table using delete: snapshot must list every untagged source in snapshotFiles and retain a nonempty effective dataset after filtering.

Bulk staging and replay

Plan and apply use SQL Server bulk copy to stream input into transaction-local staging tables. SQL Server converts the staged values to the destination column types before comparing rows. Apply revalidates the reviewed inputs and target state under its migration lock. If the source or target state changed, generate and review a fresh plan. After a successful apply, a fresh plan shows zero writes when the data matches.

In a three-table SQL Server clone with 17,900 selected CSV rows, median native apply time across three runs fell from 6.07 to 1.97 seconds when rows already matched, and from 12.73 to 2.62 seconds for 487 inserts and 475 updates. The final row hashes matched across both staging implementations. These timings cover apply with an existing reviewed artifact.

Schema bundles

sqlserver:// targets reconcile through the Atlas SQL Server driver in atlas/sqlserver, which commons-db ships because Atlas OSS has none. A bundle declares tables in SQL Server-shaped HCL and stored procedures and functions as plain .sql files:

The driver delegates its differ, SQL Server types and migration planner to github.com/flanksource/sqlglot-go/migrate/atlas/sqlserver. Commons-db owns catalog inspection, HCL loading, connections, locks, transactions and applying the resulting SQL. Consumers that need a database-independent typed plan can register sqlglot's pure migrate/sqlserver dialect and call engine.Plan; this does not expand the HCL or inspection support described below.

//go:embed db
var bundle embed.FS

err := migrate.Apply(ctx, "sqlserver://app:secret@db:1433?database=acme", bundle,
    migrate.WithDir("db"),
    migrate.WithRoutines("db/routines"),
    migrate.WithName("acme/orders"),
)
Routines come from .sql files

WithRoutines(dir) declares one routine per .sql file under dir. Each file holds exactly one CREATE [OR ALTER] PROCEDURE|FUNCTION batch, optionally followed by GO, and is named after the routine it creates (acme_count_orders.sql creates acme_count_orders). The file is the routine's only source: there are no procedure or function HCL blocks. It runs as written in SSMS or sqlcmd, and migrate runs the same text, with CREATE rewritten to CREATE OR ALTER and every other byte kept, as its own batch.

A routine is compared with the live sys.sql_modules definition through sqlglot's canonical T-SQL: comments, whitespace, keyword case, [brackets] and OR ALTER do not count as changes, while a literal or any other token does and produces one CREATE OR ALTER. A definition, declared or live, that sqlglot cannot parse is an error naming the routine, never a guessed change. Routine files are never hash-gated SQL scripts.

A routine that is removed from the bundle is left in the database; migrate never drops procedures or functions.

Tables from HCL

.hcl files under WithDir are optional when the bundle has routines. They declare exactly schema "dbo" {} and its tables:

Block Supported form
table partial = true (a boolean, default false) declares only some members: the others are never dropped, and the table must already exist
column type, null, default (a number, a string, or sql("getdate()")), default_name = "DF_x" (the default constraint's name, instead of DF_<table>_<column>), collate = "...", and an identity { seed, increment } block
primary_key columns, optional name, clustered = false for a nonclustered key (clustered by default)
index columns (with desc parts), unique, constraint = true (a UNIQUE constraint rather than a unique index; no where or include), clustered = true (nonclustered by default), include = [column.x], where = "..."
foreign_key columns, ref_columns, on_delete, on_update
check expr

Types: bit, tinyint, smallint, int, bigint, decimal(p,s), numeric(p,s), money, smallmoney, float(n) (stored as real up to 24 bits), real, char(n), varchar(n), nchar(n), nvarchar(n), text, ntext, binary(n), varbinary(n), image, date, time(p), datetime, datetime2(p), smalldatetime, datetimeoffset(p), uniqueidentifier, xml, sql_variant and rowversion (timestamp). A (max) size is written with sql(): type = sql("nvarchar(max)"). Defaults are named DF_<table>_<column>; changing one drops the live default constraint, whatever its name, and adds the new one. String defaults on nchar/nvarchar/ntext columns are written as N'...'.

sqlglot schema inspect --hcl writes the HCL of tables a database already has, and ExportHCL in migrate/sqlserver (read from a database by dialect/sqlserver.ExportHCL) does the same from a migrate.Schema. It refuses, naming the table, the member and the attribute, what this HCL cannot declare (ROWGUIDCOL, index fill factor and the other index options, NOT FOR REPLICATION, a foreign key to a table outside the export), unless OmitUnsupported leaves it out with one comment line each.

Scoped inspection

An OIPA-sized database holds thousands of objects, so migrate inspects only the tables and routines the bundle names. Undeclared objects are never read, and so never changed. Inside a declared table that does not say partial = true, columns, indexes, keys, foreign keys and checks are reconciled to the declaration: an undeclared index, key, foreign key or check is dropped, and an undeclared column is left in place and reported on every run (PendingSQLServer.Warnings), because the unreviewed apply never drops a column and SQL Server bundles do not support WithDrops. A table marked partial = true keeps everything it does not name, so tuning indexes added by a DBA survive. sqlglot schema inspect --hcl --columns writes the attribute for the tables it declares in part. An apply that finds nothing to change runs no DDL. Every apply holds a session sp_getapplock named after WithName (one-minute wait), so concurrent applies of one bundle serialize.

The schema step is a reviewed artifact

The tables and routines of a bundle are planned together, in one declared-scope batch, by the shared schema engine (migrate/engine, dialect sqlserver): PlanSchema(ctx, db, fsys, opts...) returns that engine.Artifact without changing anything, and Apply and PendingSQLServer embed it as bundle.schema of the plan file (version 3). Dependents of a changed column are dropped and re-created around it, and the artifact lists each forced rebuild with its cause, the data guards (a varchar(36) column becoming uniqueidentifier is refused while a value is not a GUID) and, under preserved, the drops it left out because their table is partial or nothing declares the object. The reviewed plan (PlanSchema) carries the drops of a complete table's undeclared members for acknowledgement; the unreviewed apply runs the plan without the column drops and reports them. The schema step runs between the pre and post scripts, one transaction per unit, with a 15 second lock timeout (WithSchemaLockTimeout on scripts/sqlserver.Apply changes it). Pre scripts that ran before a failing unit stay committed and recorded. A database that moved since the plan, or whose capabilities changed, makes the plan file stale (*StalePlanError); a unit that already committed is skipped when the plan file is applied again. A version 2 plan file without a schema step still applies; one with schema statements is refused and must be planned again.

Scripts are sqlcmd files

Every other .sql file under WithDir (outside the routine directory) is a hash-gated script with the same -- phase:, -- dependsOn:, -- runs: always and -- transaction: headers as on PostgreSQL. It is plain T-SQL that runs unchanged with sqlcmd -i or in SSMS: migrate splits it at GO on its own line (never inside a string or comment) and sends each batch in turn. sqlcmd commands (:setvar, :r, :on error, !!) and $(var) scripting variables, which sqlcmd substitutes even inside strings, are refused, so a file never means something different here than in sqlcmd. pre scripts run before the table and routine reconcile, post scripts after, all under the bundle's sp_getapplock. A transactional script runs every batch and records its SHA-256 in dbo.sqlglot_migrations (created on first use) in one transaction, the record appended to its last batch unless that batch defines a module or may end early, under SET LOCK_TIMEOUT 15000; deadlocks (1205) and lock timeouts (1222) are retried. Apply plans the bundle into a sqlserver.PlanFile and runs exactly that file, refusing it as stale when the target moved during the apply. PendingSQLServer reports what an Apply would do without executing anything: the reconcile statements, each script it would run with why (new, changed, dependency or always), and the plan file itself (Plan).

Merging ledger scopes

The script ledger in dbo.sqlglot_migrations is kept per scope (the bundle's WithName, or scripts/sqlserver.Options.Scope), so two bundles on one database never see each other's runs. A caller that wants several scopes to count as one, for example a database that received the same scripts from different repositories under one scope each, sets Options.AbsorbScopes to accept those scopes. Plan then reads the newest row of each path across Scope and the accepted scopes (by updated_at, then hash), so a script whose body differs from what ran last on the database is re-run whichever scope recorded that run. The plan file lists the scopes in absorbed, and its stale check covers their rows. Apply, under the scope's migration lock and in one transaction, keeps the newest row of each path, re-keys it and the scopes' attempts to Scope, and drops the absorbed scopes' observation snapshots. Later plans find nothing left to absorb.

Compatibility level 100

Generated DDL and the catalog queries avoid syntax newer than compatibility level 100 (no STRING_AGG, OPENJSON or DROP ... IF EXISTS). CREATE OR ALTER depends on the engine version (2016 SP1+), not the database's compatibility level.

Refused on SQL Server

These fail with an error instead of being ignored:

  • sqlcmd commands in scripts (see above);
  • WithSchema other than dbo and WithDrops;
  • role and permission blocks;
  • view, trigger, sequence, function and procedure HCL blocks, computed columns, user-defined and alias types (including sysname), and any unknown column, index or table attribute;
  • declared tables that the database has partitioned or carries triggers on, and IDENTITY changes on an existing column.

Documentation

Overview

Package migrate applies declarative Atlas HCL schemas to PostgreSQL, SQLite and SQL Server databases, and on SQL Server also the stored procedures and functions declared as .sql files (WithRoutines).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apply

func Apply(ctx context.Context, connection string, schemaFS fs.FS, opts ...Option) (returnErr error)

Apply resolves the database target from connection, or from the WithDB handle, and reconciles HCL schemas.

Apply is the unreviewed path: it plans the schema against the live database with the shared planner (engine.PlanLive) and applies the plan in the same call, acknowledging every destructive change of its own plan (engine.Acknowledgements). A table declaration is complete unless it says `partial = true`, so the members it omits are dropped: its indexes, keys and checks run, but the drop of a column does not, unless WithDrops. Each such column is reported as a warning every time, naming the three ways to settle it (declare it, mark the table partial, or WithDrops). The scope bounds the rest: declared by default, where an undeclared table or type is never dropped, and complete with WithDrops. Use the reviewed workflow when a person must approve the changes first.

On PostgreSQL and SQLite, Apply records the hash of the desired schema it brought the database to in schema_migration_schema, per bundle scope; the hash covers the evaluated HCL, dialect, schema, drop scope, exclusions and the bundle's script contents. The next Apply of an unchanged bundle skips inspecting and planning the schema (scripts still follow their own hashes, and a pre script that runs makes it plan), so a change made to the database by hand outside the bundle is not repaired, and an undeclared column is not reported again, until the bundle changes. The reviewed workflow forgets the ledger of the schemas it applies to (ForgetRecordedSchemas), so the next Apply after a reviewed deploy plans again.

PostgreSQL supports the complete HCL, SQL, security, and destructive-change lifecycle; the views that depend on a retyped column are dropped and re-created around the change from their live definitions. SQLite projects portable PostgreSQL-shaped HCL to tables, columns, and indexes, rebuilding tables when needed; undeclared tables are kept and undeclared columns are reported, not dropped, unless WithDrops is enabled. SQL Server (sqlserver:// URLs, ADO and odbc: strings) reconciles SQL Server HCL tables and the stored procedures and functions declared with WithRoutines, inspecting only the objects the bundle names; it refuses SQL scripts, security blocks, drops, rebuilds and schemas other than dbo.

func BookkeepingTables added in v1.7.1

func BookkeepingTables(dialect, schema string) ([]native.Name, error)

BookkeepingTables names the tables a bundle keeps for itself in schema: the script and security ledgers and the schema ledger. A plan of a desired schema given outside a bundle (pasted HCL or a snapshot) never declares them, so it must leave them alone.

func ConnectionForSchema

func ConnectionForSchema(connection, schemaName string) (string, error)

ConnectionForSchema returns a PostgreSQL URL whose connections select schemaName.

func ForgetRecordedSchemas added in v1.7.0

func ForgetRecordedSchemas(ctx context.Context, db *sql.DB, dialect string, schemas []string) error

ForgetRecordedSchemas deletes the schema ledger of every bundle scope in the given schemas, so the next Apply of any bundle there plans against the database again instead of skipping. Every path that changes a PostgreSQL or SQLite schema without Apply (the reviewed workflow) calls it, before and after applying. SQL Server bundles keep no schema ledger.

func PlanSchema added in v1.3.8

func PlanSchema(ctx context.Context, db *sql.DB, schemaFS fs.FS, opts ...Option) (engine.Artifact, error)

PlanSchema is the reviewed schema plan of a SQL Server bundle on db: its HCL tables and WithRoutines routines against the live dbo schema, as the engine artifact Apply embeds in its plan file. It reads only the declared objects and what depends on the columns a change forces, never drops an object the bundle does not declare, and changes nothing. A table the bundle declares without `partial = true` is complete, so the plan holds the drops of its undeclared columns, indexes, keys and checks as destructive changes for a reviewer to acknowledge. The bundle's scripts are not loaded. The caller owns db.

func ValidateSchemaName

func ValidateSchemaName(name string) error

ValidateSchemaName validates an application-normalized PostgreSQL schema identifier.

Types

type Option

type Option func(*options)

Option configures an HCL migration.

func WithDB

func WithDB(db *sql.DB) Option

WithDB runs the migration on an already open SQL Server, SQLite or PostgreSQL handle, with Apply's connection string left empty; the dialect comes from the handle's driver. Apply never closes db and never changes its pool settings. Every schema unit runs on a dedicated connection that sets and restores its own lock timeout, so a PostgreSQL handle needs no scoping; what it cannot do is move the script phases and metadata tables to another schema, so a PostgreSQL handle is accepted for the default schema only, and only when its current_schema() is that schema (WithSchema needs a connection string, which scopes search_path).

func WithDir

func WithDir(dir string) Option

WithDir selects the root containing colocated HCL and SQL migrations.

func WithDrops

func WithDrops() Option

WithDrops makes the bundle the complete description of its schema: the plan is planned in the engine's complete scope, so anything the HCL does not declare (tables, types, columns, indexes, keys, checks) is dropped, and every drop it plans runs. Without it the scope is declared: only what the HCL names is managed, so an undeclared table or type is never dropped, and the columns a declared table lacks stay (they are reported, each time, as a warning). A table declared `partial = true` keeps every member it does not name, with or without WithDrops. The bundle's own metadata tables are never dropped.

func WithExclude

func WithExclude(patterns ...string) Option

WithExclude hides database objects from the plan: they are removed from the live schema and from the declared one before they are compared, so they are neither created, altered nor dropped. Values use Atlas's schema inspection patterns (for example "table" or "table.column"); SQLite accepts whole tables only, because it rebuilds a table from what the plan can see.

func WithName

func WithName(name string) Option

WithName sets the metadata scope used for SQL hashes and managed security. It should be stable and unique for each migration bundle sharing a database.

func WithReviewedPlan added in v1.3.8

func WithReviewedPlan() Option

WithReviewedPlan plans every change the scope allows, column drops included, for a reviewer to select and acknowledge. Without it a plan is what an unreviewed Apply runs, which leaves out the drop of a column of a declared table (unless WithDrops).

func WithRoutines

func WithRoutines(dir string) Option

WithRoutines declares stored procedures and functions from the .sql files under dir (relative to the schema filesystem root). Each file holds exactly one CREATE [OR ALTER] PROCEDURE|FUNCTION batch, optionally followed by GO, and is named after the routine it creates (mc_ClonePlan.sql creates mc_ClonePlan). The files are the routines' single source: they run as written, so the same file works in SSMS or sqlcmd, and they are never treated as hash-gated SQL scripts. Only SQL Server supports routines.

func WithSchema

func WithSchema(name string) Option

WithSchema selects the PostgreSQL schema used for the complete migration lifecycle. SQLite accepts only the default public schema declared by portable HCL bundles, and SQL Server only dbo.

func WithScriptPolicy added in v1.2.0

func WithScriptPolicy(policy ScriptPolicy) Option

WithScriptPolicy enables SQL Server dependency tracking for named script paths.

func WithScriptSources added in v1.3.3

func WithScriptSources(sources map[string]sharedscripts.Source) Option

WithScriptSources sets the metadata for scripts keyed by bundle-relative SQL path.

func WithVariables

func WithVariables(input map[string]cty.Value) Option

WithVariables supplies values for HCL variable blocks and security expressions.

type PendingScript added in v1.1.2

type PendingScript struct {
	Path    string   `json:"path"`
	Phase   string   `json:"phase"`
	Reason  string   `json:"reason"` // new | changed | dependency | always
	Reasons []string `json:"reasons,omitempty"`
	Blocked []string `json:"blocked,omitempty"`
	Hash    string   `json:"hash,omitempty"`
}

PendingScript is one script Apply would run, and why: new or changed since it last ran, dependency (a script it depends on changed), or always (a `runs: always` script, which runs on every Apply and so is never a change by itself).

type Preview

type Preview struct {
	Artifact   *engine.Artifact       `json:"artifact,omitempty"`
	Advisory   []string               `json:"advisory,omitempty"`
	Scripts    []ScriptAnalysis       `json:"scripts,omitempty"`
	ScriptPlan *scriptserver.PlanFile `json:"scriptPlan,omitempty"`
	Warnings   []string               `json:"warnings,omitempty"`
	Error      string                 `json:"error,omitempty"`
}

Preview is what PreviewBundle plans. For PostgreSQL and SQLite, Artifact is the engine's reviewed artifact: its changes (forced rebuilds carry their cause), preserved drops, refusals, warnings and units with their ordered statements and preconditions. Without WithReviewedPlan it is what an unreviewed Apply would run: the drops of undeclared columns are not in it (Warnings names each one), so it holds no change when nothing else is left to run. A non-empty Advisory marks a bundle whose scripts or security blocks the artifact does not carry, so it must not be applied as the whole migration.

func PreviewBundle

func PreviewBundle(ctx context.Context, db *sql.DB, dialect string, files fs.FS, opts ...Option) (result Preview, returnErr error)

PreviewBundle inspects and plans without executing scripts or creating metadata. Script and security bundles yield advisory schema plans until phased artifacts are supported.

type SQLServerPending added in v1.1.2

type SQLServerPending struct {
	Statements []string        `json:"statements,omitempty"`
	Scripts    []PendingScript `json:"scripts,omitempty"`
	// Warnings name each column of a declared table that is in the database but
	// not declared: Apply does not drop it and reports it every time.
	Warnings []string          `json:"warnings,omitempty"`
	Plan     *backend.PlanFile `json:"plan"`
}

SQLServerPending is what Apply would do to a SQL Server database: the statements that reconcile the declared tables and routines (every unit's statements in order, derived from the plan file's schema artifact), the scripts it would run, and the plan file holding both. It inspects only the objects the bundle names.

func PendingSQLServer added in v1.1.2

func PendingSQLServer(ctx context.Context, db *sql.DB, schemaFS fs.FS, opts ...Option) (SQLServerPending, error)

PendingSQLServer plans Apply on db without executing or recording anything.

func (SQLServerPending) Changed added in v1.1.2

func (p SQLServerPending) Changed() bool

Changed reports whether Apply would change anything beyond running its `runs: always` scripts.

type SchemaProvisioner

type SchemaProvisioner struct {
	// contains filtered or unexported fields
}

SchemaProvisioner prepares reusable dbtest templates and reconciles each cloned database using the same migration behavior as Apply.

func NewProvisioner

func NewProvisioner(schemaFS fs.FS, opts ...Option) *SchemaProvisioner

NewProvisioner adapts an HCL migration bundle to dbtest.Provisioner without coupling the migrate package to dbtest. Options are frozen at construction.

func (*SchemaProvisioner) Fingerprint

func (p *SchemaProvisioner) Fingerprint(ctx context.Context) (string, error)

Fingerprint returns a deterministic identity for all inputs that affect the database produced by this provisioner.

func (*SchemaProvisioner) PrepareInstance

func (p *SchemaProvisioner) PrepareInstance(ctx context.Context, connection string) error

PrepareInstance reconciles instance-specific and always-run migrations after cloning a prepared template.

func (*SchemaProvisioner) PrepareTemplate

func (p *SchemaProvisioner) PrepareTemplate(ctx context.Context, connection string) error

PrepareTemplate applies the full migration bundle to a new template.

type ScriptAnalysis

type ScriptAnalysis struct {
	Path        string                    `json:"path,omitempty"`
	Phase       string                    `json:"phase,omitempty"`
	Kind        string                    `json:"kind"`
	Complete    bool                      `json:"complete"`
	Diagnostics []sqlglot.ParseDiagnostic `json:"diagnostics,omitempty"`
	Error       string                    `json:"error,omitempty"`
}

func AnalyzeScript

func AnalyzeScript(text, dialect string) ScriptAnalysis

type ScriptPolicy added in v1.2.0

type ScriptPolicy struct {
	Functions            []backend.Function
	Dependencies         map[string][]scripts.Dependency
	ExplicitDependencies []string
}

Directories

Path Synopsis
Package dialect is what the reviewed workflows need from the registered engine dialects besides planning: the desired schema a dialect reads from HCL, a schema snapshot, and the script a plan's statements make.
Package dialect is what the reviewed workflows need from the registered engine dialects besides planning: the desired schema a dialect reads from HCL, a schema snapshot, and the script a plan's statements make.
atlasdriver
Package atlasdriver is the shared engine.Dialect implementation for the dialects that plan with an upstream Atlas driver (Postgres and SQLite).
Package atlasdriver is the shared engine.Dialect implementation for the dialects that plan with an upstream Atlas driver (Postgres and SQLite).
postgres
Package postgres registers the "postgres" engine dialect, planned with the upstream Atlas PostgreSQL driver.
Package postgres registers the "postgres" engine dialect, planned with the upstream Atlas PostgreSQL driver.
sqlite
Package sqlite registers the "sqlite" engine dialect, planned with the upstream Atlas SQLite driver.
Package sqlite registers the "sqlite" engine dialect, planned with the upstream Atlas SQLite driver.
sqlserver
Package sqlserver is the database half of the SQL Server dialect of the schema engine: it reads capabilities, schemas and the live dependents of columns, and runs a unit on one connection.
Package sqlserver is the database half of the SQL Server dialect of the schema engine: it reads capabilities, schemas and the live dependents of columns, and runs a unit on one connection.
Package scripts owns migration source identity, dependencies and consumed fingerprints.
Package scripts owns migration source identity, dependencies and consumed fingerprints.
sqlserver
Package sqlserver plans and applies dependency-aware scripts on SQL Server through a self-contained plan file: Plan observes the target once and writes what apply will do, and Apply runs exactly that plan, refusing it as stale when the target moved since.
Package sqlserver plans and applies dependency-aware scripts on SQL Server through a self-contained plan file: Plan observes the target once and writes what apply will do, and Apply runs exactly that plan, refusing it as stale when the target moved since.
Package sqlite reconciles SQLite tables with programmatic Atlas declarations.
Package sqlite reconciles SQLite tables with programmatic Atlas declarations.

Jump to

Keyboard shortcuts

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