dbmigrate

package
v0.0.0-...-4452e01 Latest Latest
Warning

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

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

Documentation

Overview

Package dbmigrate renders registered Go models into a target schema and migrates a database towards it.

SchemaDumper produces the target schema from the models themselves, so it always matches the DDL the runtime applies. Migrate then diffs that schema against the live database through sqldef and applies the difference, or only plans it in dry-run mode. A plan that would drop and re-create an identical definition comes back with advisory text offering the metadata-only rename instead; executing it stays a human decision.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apply

func Apply(plan Plan, dbtyp config.DBType, cfg *DatabaseConfig) error

Apply runs the statements of a plan as they stand, against the same kind of target Migrate planned them for. Nothing is planned again: what runs is what the plan carries, including the destructive statements a reviewer approved. A plan with nothing to run does nothing.

Types

type DatabaseConfig

type DatabaseConfig struct {
	// Database is the schema name on MySQL and PostgreSQL, and the file path
	// on SQLite.
	Database string
	Username string
	Password string
	Host     string
	Port     int
	// SSLMode is the PostgreSQL sslmode parameter; the other dialects ignore it.
	SSLMode string
}

DatabaseConfig is the connection the migration runs against.

func SQLiteTarget

func SQLiteTarget(cfg config.Sqlite) (*DatabaseConfig, bool)

SQLiteTarget returns the migration target of a sqlite configuration: the database file the application opens, the one the path names. It reports false for a configuration selecting the in-memory database, with is_memory set, with no path, or with a path naming memory: the application creates that database's tables from the models every time it starts, and a migration, running in a process of its own, cannot reach it. For {Path: "./data.db"} it returns {Database: "./data.db"} and true; for {IsMemory: true, Path: "./data.db"} it returns nil and false.

type MigrateOption

type MigrateOption struct {
	// DryRun plans the migration and reports what would change without
	// touching the database.
	DryRun bool
	// EnableDrop lets the plan contain destructive statements. Without it
	// sqldef keeps every table, column and index the models no longer declare.
	EnableDrop bool
}

MigrateOption tunes a single migration run.

type Plan

type Plan struct {
	// Statements are the DDL statements of the plan, in execution order.
	Statements []string
	// Advisory is the rename advisory, empty when the plan suggests none.
	Advisory string
	// CreatesDatabase reports that the plan starts from a sqlite database file
	// that does not exist yet: applying its statements creates the file.
	// MySQL and PostgreSQL databases must exist, so it is always false there.
	CreatesDatabase bool
}

Plan is what a migration would do to the database: the statements it would run, in order, and the rename advisory that belongs beside them.

It exists so that what a reviewer approved is what runs. A plan is computed against the schema the database has at that moment; computing it a second time to execute it would plan against whatever the database has by then, which is not what was shown — a table created in between turns a CREATE into an ALTER, and one dropped in between turns nothing into a CREATE. Apply runs the statements of the plan as they stand.

func Migrate

func Migrate(schemas []string, dbtyp config.DBType, cfg *DatabaseConfig, opt *MigrateOption) (plan Plan, err error)

Migrate plans the schema changes towards the models' schema, and applies them unless the option asks for a dry run. It returns the plan either way, so a caller that plans first can execute exactly what it showed through Apply.

A dry run creates nothing. A sqlite database file that does not exist yet is planned against as the empty database it would be, and the plan reports CreatesDatabase; the file comes into being when the plan is applied. A file whose directory does not exist either fails the migration: the driver creates the file but not the directory.

Index renames must run through this migration path BEFORE deploying code that carries the new index name: once the rename is applied, startup table preparation matches the new name and does nothing. With database.auto_migrate enabled (local development, tests), deploying first instead fails the start: table preparation finds the same definition under the old name and refuses with the rename statement, dropping nothing. With auto_migrate disabled (the production default) the start passes, but the model and the database keep drifting until the migration runs.

When a plan drops and re-creates an identical definition — an index on the same table, or a whole table under a new name — the suspected renames are returned as advisory text with ready-to-run rename statements in that server's syntax. For tables the advisory doubles as a data-loss guard, because the planned DROP TABLE would discard every row that the metadata-only rename keeps. SQLite renames tables but no index, so its advisory covers table renames alone and drops the renamed table's indexes for the next run to create under their new names. The caller owns when and how to present it; executing the rename stays a human decision.

A SQLite database whose columns no longer match the models' definitions — type, nullability, default or check — fails the migration instead of planning nothing: SQLite's ALTER TABLE cannot change a column, and sqldef plans no statement for it. The error names the table and the columns and points to the rebuild SQLite documents for such changes.

func (Plan) Changed

func (p Plan) Changed() bool

Changed reports whether the plan has anything to run: a database already matching the models plans nothing.

type SchemaDumper

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

SchemaDumper renders models into the target schema DDL that Migrate diffs against the live database. It runs gorm's migrator in dry-run mode over a mock connection, so the statements are the ones the runtime itself would apply and no database is contacted.

func NewSchemaDumper

func NewSchemaDumper() (*SchemaDumper, error)

NewSchemaDumper opens a dumper on a mock connection of its own. The caller owns it and closes it through Close.

func (*SchemaDumper) Close

func (s *SchemaDumper) Close() (err error)

Close releases the mock connection the dumper renders through. A dumper already closed reports no error.

func (*SchemaDumper) Dump

func (s *SchemaDumper) Dump(driver config.DBType, dst ...any) (string, error)

Dump renders dst as the target schema for driver: one CREATE TABLE per model, each followed by the CREATE INDEX statements of the indexes it declares through its optional Indexes method, and each annotated with the model it came from. Models are sorted by type name, so the same input always renders the same schema.

Jump to

Keyboard shortcuts

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