goose

package module
v3.6.5 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2023 License: MIT Imports: 22 Imported by: 0

README

goose Goose CI Go Reference

Goose is a database migration tool. Manage your database schema by creating incremental SQL changes or Go functions.

Starting with v3.0.0 this project adds Go module support, but maintains backwards compatibility with older v2.x.y tags.

Goose supports embedding SQL migrations, which means you'll need go1.16 and up. If using go1.15 or lower, then pin v3.0.1.

Goals of this fork

github.com/gdey/goose is a Hard fork of bitbucket.org/liamstask/goose with the following changes:

  • No config files
  • Default goose binary can migrate SQL files only
  • Go migrations:
    • We don't go build Go migrations functions on-the-fly from within the goose binary
    • Instead, we let you create your own custom goose binary, register your Go migration functions explicitly and run complex migrations with your own *sql.DB connection
    • Go migration functions let you run your code within an SQL transaction, if you use the *sql.Tx argument
  • The goose pkg is decoupled from the binary:
    • goose pkg doesn't register any SQL drivers anymore, thus no driver panic() conflict within your codebase!
    • goose pkg doesn't have any vendor dependencies anymore
  • We use timestamped migrations by default but recommend a hybrid approach of using timestamps in the development process and sequential versions in production.
  • Supports missing (out-of-order) migrations with the -allow-missing flag, or if using as a library supply the functional option goose.WithAllowMissing() to Up, UpTo or UpByOne.
  • Supports applying ad-hoc migrations without tracking them in the schema table. Useful for seeding a database after migrations have been applied. Use -no-versioning flag or the functional option goose.WithNoVersioning().

Install

$ go install github.com/gdey/goose/v3/cmd/goose@latest

This will install the goose binary to your $GOPATH/bin directory.

For a lite version of the binary without DB connection dependent commands, use the exclusive build tags:

$ go build -tags='no_postgres no_mysql no_sqlite3' -o goose ./cmd/goose

For macOS users goose is available as a Homebrew Formulae:

$ brew install goose

See the docs for more installation instructions.

Usage

Usage: goose [OPTIONS] DRIVER DBSTRING COMMAND

Drivers:
    postgres
    mysql
    sqlite3
    mssql
    redshift
    tidb
    clickhouse

Examples:
    goose sqlite3 ./foo.db status
    goose sqlite3 ./foo.db create init sql
    goose sqlite3 ./foo.db create add_some_column sql
    goose sqlite3 ./foo.db create fetch_user_data go
    goose sqlite3 ./foo.db up

    goose postgres "user=postgres password=postgres dbname=postgres sslmode=disable" status
    goose mysql "user:password@/dbname?parseTime=true" status
    goose redshift "postgres://user:password@qwerty.us-east-1.redshift.amazonaws.com:5439/db" status
    goose tidb "user:password@/dbname?parseTime=true" status
    goose mssql "sqlserver://user:password@dbname:1433?database=master" status

Options:

  -allow-missing
    	applies missing (out-of-order) migrations
  -certfile string
    	file path to root CA's certificates in pem format (only support on mysql)
  -dir string
    	directory with migration files (default ".")
  -h	print help
  -no-versioning
    	apply migration commands with no versioning, in file order, from directory pointed to
  -s	use sequential numbering for new migrations
  -ssl-cert string
    	file path to SSL certificates in pem format (only support on mysql)
  -ssl-key string
    	file path to SSL key in pem format (only support on mysql)
  -table string
    	migrations table name (default "goose_db_version")
  -v	enable verbose mode
  -version
    	print version

Commands:
    up                   Migrate the DB to the most recent version available
    up-by-one            Migrate the DB up by 1
    up-to VERSION        Migrate the DB to a specific VERSION
    down                 Roll back the version by 1
    down-to VERSION      Roll back to a specific VERSION
    redo                 Re-run the latest migration
    reset                Roll back all migrations
    status               Dump the migration status for the current DB
    version              Print the current version of the database
    create NAME [sql|go] Creates new migration file with the current timestamp
    fix                  Apply sequential ordering to migrations

create

Create a new SQL migration.

$ goose create add_some_column sql
$ Created new file: 20170506082420_add_some_column.sql

Edit the newly created file to define the behavior of your migration.

You can also create a Go migration, if you then invoke it with your own goose binary:

$ goose create fetch_user_data go
$ Created new file: 20170506082421_fetch_user_data.go

up

Apply all available migrations.

$ goose up
$ OK    001_basics.sql
$ OK    002_next.sql
$ OK    003_and_again.go

up-to

Migrate up to a specific version.

$ goose up-to 20170506082420
$ OK    20170506082420_create_table.sql

up-by-one

Migrate up a single migration from the current version

$ goose up-by-one
$ OK    20170614145246_change_type.sql

down

Roll back a single migration from the current version.

$ goose down
$ OK    003_and_again.go

down-to

Roll back migrations to a specific version.

$ goose down-to 20170506082527
$ OK    20170506082527_alter_column.sql

redo

Roll back the most recently applied migration, then run it again.

$ goose redo
$ OK    003_and_again.go
$ OK    003_and_again.go

status

Print the status of all migrations:

$ goose status
$   Applied At                  Migration
$   =======================================
$   Sun Jan  6 11:25:03 2013 -- 001_basics.sql
$   Sun Jan  6 11:25:03 2013 -- 002_next.sql
$   Pending                  -- 003_and_again.go

Note: for MySQL parseTime flag must be enabled.

Note: for MySQL multiStatements must be enabled. This is required when writing multiple queries separated by ';' characters in a single sql file.

verify

version

Print the current version of the database:

$ goose version
$ goose: version 002

Migrations

goose supports migrations written in SQL or in Go.

SQL Migrations

A sample SQL migration looks like:

-- +goose Up
CREATE TABLE post (
    id int NOT NULL,
    title text,
    body text,
    PRIMARY KEY(id)
);

-- +goose Down
DROP TABLE post;

Notice the annotations in the comments. Any statements following -- +goose Up will be executed as part of a forward migration, and any statements following -- +goose Down will be executed as part of a rollback.

By default, all migrations are run within a transaction. Some statements like CREATE DATABASE, however, cannot be run within a transaction. You may optionally add -- +goose NO TRANSACTION to the top of your migration file in order to skip transactions within that specific migration file. Both Up and Down migrations within this file will be run without transactions.

By default, SQL statements are delimited by semicolons - in fact, query statements must end with a semicolon to be properly recognized by goose.

More complex statements (PL/pgSQL) that have semicolons within them must be annotated with -- +goose StatementBegin and -- +goose StatementEnd to be properly recognized. For example:

-- +goose Up
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION histories_partition_creation( DATE, DATE )
returns void AS $$
DECLARE
  create_query text;
BEGIN
  FOR create_query IN SELECT
      'CREATE TABLE IF NOT EXISTS histories_'
      || TO_CHAR( d, 'YYYY_MM' )
      || ' ( CHECK( created_at >= timestamp '''
      || TO_CHAR( d, 'YYYY-MM-DD 00:00:00' )
      || ''' AND created_at < timestamp '''
      || TO_CHAR( d + INTERVAL '1 month', 'YYYY-MM-DD 00:00:00' )
      || ''' ) ) inherits ( histories );'
    FROM generate_series( $1, $2, '1 month' ) AS d
  LOOP
    EXECUTE create_query;
  END LOOP;  -- LOOP END
END;         -- FUNCTION END
$$
language plpgsql;
-- +goose StatementEnd

Embedded sql migrations

Go 1.16 introduced new feature: compile-time embedding files into binary and corresponding filesystem abstraction.

This feature can be used only for applying existing migrations. Modifying operations such as fix and create will continue to operate on OS filesystem even if using embedded files. This is expected behaviour because io/fs interfaces allows read-only access.

Make sure to configure the correct SQL dialect, see dialect.go for supported SQL dialects.

Example usage, assuming that SQL migrations are placed in the migrations directory:

package main

import (
    "database/sql"
    "embed"

    "github.com/gdey/goose/v3"
)

//go:embed migrations/*.sql
var embedMigrations embed.FS

func main() {
    var db *sql.DB
    // setup database

    goose.SetBaseFS(embedMigrations)

    if err := goose.SetDialect("postgres"); err != nil {
        panic(err)
    }

    if err := goose.Up(db, "migrations"); err != nil {
        panic(err)
    }

    // run app
}

Note that we pass "migrations" as directory argument in Up because embedding saves directory structure.

Go Migrations

  1. Create your own goose binary, see example
  2. Import github.com/gdey/goose
  3. Register your migration functions
  4. Run goose command, ie. goose.Up(db *sql.DB, dir string)

A sample Go migration 00002_users_add_email.go file looks like:

package migrations

import (
	"database/sql"

	"github.com/gdey/goose/v3"
)

func init() {
	goose.AddMigration(Up, Down)
}

func Up(tx *sql.Tx) error {
	_, err := tx.Exec("UPDATE users SET username='admin' WHERE username='root';")
	if err != nil {
		return err
	}
	return nil
}

func Down(tx *sql.Tx) error {
	_, err := tx.Exec("UPDATE users SET username='root' WHERE username='admin';")
	if err != nil {
		return err
	}
	return nil
}

Development

This can be used to build local goose binaries without having the latest Go version installed locally.

DOCKER_BUILDKIT=1  docker build -f Dockerfile.local --output bin .

Hybrid Versioning

Please, read the versioning problem first.

By default, if you attempt to apply missing (out-of-order) migrations goose will raise an error. However, If you want to apply these missing migrations pass goose the -allow-missing flag, or if using as a library supply the functional option goose.WithAllowMissing() to Up, UpTo or UpByOne.

However, we strongly recommend adopting a hybrid versioning approach, using both timestamps and sequential numbers. Migrations created during the development process are timestamped and sequential versions are ran on production. We believe this method will prevent the problem of conflicting versions when writing software in a team environment.

To help you adopt this approach, create will use the current timestamp as the migration version. When you're ready to deploy your migrations in a production environment, we also provide a helpful fix command to convert your migrations into sequential order, while preserving the timestamp ordering. We recommend running fix in the CI pipeline, and only when the migrations are ready for production.

License

Licensed under MIT License

Documentation

Index

Constants

View Source
const (
	DialectPostgres   = "postgres"
	DialectSQLite3    = "sqlite3"
	DialectMySQL      = "mysql"
	DialectMSSQL      = "mssql"
	DialectRedShit    = "redshift"
	DialectTiDB       = "tidb"
	DialectClickHouse = "clickhouse"
)
View Source
const (
	// VerifyStatusErr indicates an error occurred of some sort. If this is the only bit set,
	// then it was a generic error dealing with accessing the migrations. The Error field of
	// VerifyStatus will have the error or errors
	VerifyStatusErr = 1 << iota
	// VerifyStatusTsMigrations indicates that there are timestamp-based migrations
	VerifyStatusTsMigrations
	// VerifyStatusTplSql indicates that there was an error loading, parsing, or executing sql templates.
	// the Error field will contain an error list with the error for each template that errored out.
	VerifyStatusTplSql = VerifyStatusErr | (1 << iota)
)
View Source
const VERSION = "v3.2.0"

Deprecated: VERSION will no longer be supported in v4.

View Source
const (
	// VerifyStatusOK indicates that no issue were found, this includes not having any timestamp-based migrations.
	VerifyStatusOK = 0
)

Variables

View Source
var (
	// ErrNoCurrentVersion when a current migration version is not found.
	ErrNoCurrentVersion = errors.New("no current version found")
	// ErrNoNextVersion when the next migration version is not found.
	ErrNoNextVersion = errors.New("no next version found")
	// MaxVersion is the maximum allowed version.
	MaxVersion int64 = 9223372036854775807 // max(int64)
)

Functions

func AddMigration

func AddMigration(up func(*sql.Tx) error, down func(*sql.Tx) error)

AddMigration adds a migration.

func AddNamedMigration

func AddNamedMigration(filename string, up func(*sql.Tx) error, down func(*sql.Tx) error)

AddNamedMigration : Add a named migration.

func AreEventsEqual added in v3.6.3

func AreEventsEqual(e1, e2 Eventer) bool

func BaseDir

func BaseDir(dir string) func(p *Provider)

BaseDir will set the base directory, if an empty string is passed the directory of the package that called BaseDir is used instead this is only useful for Create* and Fix functions

func Create

func Create(db *sql.DB, dir, name, migrationType string) error

Create writes a new blank migration file.

func CreateWithTemplate

func CreateWithTemplate(db *sql.DB, dir string, tmpl *template.Template, name, migrationType string) error

CreateWithTemplate writes a new blank migration file.

func Dialect

func Dialect(dialect string) func(p *Provider)

func DialectObject

func DialectObject(dialect SQLDialect) func(p *Provider)

func Down

func Down(db *sql.DB, dir string, opts ...OptionsFunc) error

Down rolls back a single migration from the current version.

func DownTo

func DownTo(db *sql.DB, dir string, version int64, opts ...OptionsFunc) error

DownTo rolls back migrations to a specific version.

func EnsureDBVersion

func EnsureDBVersion(db *sql.DB) (int64, error)

EnsureDBVersion retrieves the current version for this DB. Create and initialize the DB version table if it doesn't exist.

func Filesystem

func Filesystem(baseFS fs.FS) func(p *Provider)

func Fix

func Fix(dir string) error

func GetDBVersion

func GetDBVersion(db *sql.DB) (int64, error)

GetDBVersion is an alias for EnsureDBVersion, but returns -1 in error.

func Log

func Log(log Logger) func(p *Provider)

func NumericComponent

func NumericComponent(name string) (int64, error)

NumericComponent looks for migration scripts with names in the form: XXX_descriptive_name.ext where XXX specifies the version number and ext specifies the type of migration

func OpenDBWithDriver

func OpenDBWithDriver(driver string, dbstring string) (*sql.DB, error)

OpenDBWithDriver creates a connection to a database, and modifies goose internals to be compatible with the supplied driver by calling SetDialect.

func ProviderPackage

func ProviderPackage(packageName, providerVar string) func(p *Provider)

ProviderPackage sets the packageName and providerVar used in templates

func Redo

func Redo(db *sql.DB, dir string, opts ...OptionsFunc) error

Redo rolls back the most recently applied migration, then runs it again.

func Reset

func Reset(db *sql.DB, dir string, opts ...OptionsFunc) error

Reset rolls back all migrations

func Run

func Run(command string, db *sql.DB, dir string, args ...string) error

Run runs a goose command.

func RunWithOptions

func RunWithOptions(command string, db *sql.DB, dir string, args []string, options ...OptionsFunc) error

RunWithOptions runs a goose command with options.

func SequentialVersion

func SequentialVersion(versionTemplate string) func(p *Provider)

SequentialVersion make the provider use sequential versioning

func SetBaseFS

func SetBaseFS(fsys fs.FS)

SetBaseFS sets a base FS to discover migrations. It can be used with 'embed' package. Calling with 'nil' argument leads to default behaviour: discovering migrations from os filesystem. Note that modifying operations like Create will use os filesystem anyway.

func SetDialect

func SetDialect(d string) error

SetDialect sets the SQLDialect

func SetLogger

func SetLogger(l Logger)

SetLogger sets the logger for package output

func SetSequential

func SetSequential(s bool)

SetSequential set whether to use sequential versioning instead of timestamp based versioning

func SetTableName

func SetTableName(n string)

SetTableName set goose db version table name

func SetVerbose

func SetVerbose(v bool)

SetVerbose set the goose verbosity mode

func Status

func Status(db *sql.DB, dir string, opts ...OptionsFunc) error

Status prints the status of all migrations.

func TableName

func TableName() string

TableName returns goose db version table name

func Tablename

func Tablename(tablename string) func(p *Provider)

func TimeFunction

func TimeFunction(fn func() time.Time) func(p *Provider)

TimeFunction sets the time function used to get the time for timestamp numbers defaults to time.Now

func TimestampFormat

func TimestampFormat(format string) func(p *Provider)

TimestampFormat sets the timestamp format for the provider

func TimestampVersion

func TimestampVersion(p *Provider)

TimestampVersion make the provider use sequential versioning

func Up

func Up(db *sql.DB, dir string, opts ...OptionsFunc) error

Up applies all available migrations.

func UpByOne

func UpByOne(db *sql.DB, dir string, opts ...OptionsFunc) error

UpByOne migrates up by a single version.

func UpTo

func UpTo(db *sql.DB, dir string, version int64, opts ...OptionsFunc) error

UpTo migrates up to a specific version.

func Verbose

func Verbose(b bool) func(p *Provider)

Verbose sets the verbose on the provider

func Version

func Version(db *sql.DB, dir string, opts ...OptionsFunc) error

Version prints the current version of the database.

Types

type BaseDialect

type BaseDialect struct {
	TableName string
}

BaseDialect struct.

func (*BaseDialect) SetTableName

func (bd *BaseDialect) SetTableName(name string)

type ClickHouseDialect

type ClickHouseDialect struct{ BaseDialect }

ClickHouseDialect struct.

type ErrMigrationSQLParse added in v3.6.4

type ErrMigrationSQLParse struct {
	Filename string
	Up       bool

	ErrUnwrap
}

func (ErrMigrationSQLParse) Error added in v3.6.4

func (err ErrMigrationSQLParse) Error() string

type ErrUnknownExtension added in v3.6.4

type ErrUnknownExtension struct {
	Extension string
}

func (ErrUnknownExtension) Error added in v3.6.4

func (err ErrUnknownExtension) Error() string

type ErrUnwrap added in v3.6.4

type ErrUnwrap struct {
	Err error
}

func (ErrUnwrap) Unwrap added in v3.6.4

func (err ErrUnwrap) Unwrap() error

type Event added in v3.6.2

type Event struct{}

type Eventer added in v3.6.2

type Eventer interface {
	IsEqual(e Eventer) bool
	// contains filtered or unexported methods
}

type Logger

type Logger interface {
	Fatal(v ...interface{})
	Fatalf(format string, v ...interface{})
	Print(v ...interface{})
	Println(v ...interface{})
	Printf(format string, v ...interface{})
}

Logger is standard logger interface

type Migration

type Migration struct {
	Version    int64
	Next       int64  // next version, or -1 if none
	Previous   int64  // previous version, -1 if none
	Source     string // path to .sql script or go file
	Registered bool
	UpFn       func(*sql.Tx) error // Up go migration function
	DownFn     func(*sql.Tx) error // Down go migration function
	// contains filtered or unexported fields
}

Migration struct.

func (*Migration) Down

func (m *Migration) Down(db *sql.DB) error

Down runs a down migration. Deprecated: please use DownWithProvider

func (*Migration) DownWithProvider

func (m *Migration) DownWithProvider(p *Provider, db *sql.DB) error

func (*Migration) String

func (m *Migration) String() string

func (*Migration) Up

func (m *Migration) Up(db *sql.DB) error

Up runs an up migration. Deprecated: please use UpWithProvider

func (*Migration) UpWithProvider

func (m *Migration) UpWithProvider(p *Provider, db *sql.DB) error

type MigrationRecord

type MigrationRecord struct {
	VersionID int64
	TStamp    time.Time
	IsApplied bool // was this a result of up() or down()
}

MigrationRecord struct.

type Migrations

type Migrations []*Migration

Migrations slice.

func CollectMigrations

func CollectMigrations(dirPath string, current, target int64) (Migrations, error)

CollectMigrations returns all the valid looking migration scripts in the migrations folder and go func registry, and key them by version.

func (Migrations) Current

func (ms Migrations) Current(current int64) (*Migration, error)

Current gets the current migration.

func (Migrations) Last

func (ms Migrations) Last() (*Migration, error)

Last gets the last migration.

func (Migrations) Len

func (ms Migrations) Len() int

helpers so we can use pkg sort

func (Migrations) Less

func (ms Migrations) Less(i, j int) bool

func (Migrations) Next

func (ms Migrations) Next(current int64) (*Migration, error)

Next gets the next migration.

func (Migrations) NumberOfMigrations added in v3.6.2

func (ms Migrations) NumberOfMigrations(current int64, down bool) int

NumberOfMigrations returns the number of migrations that could be applied from the provided version number if the current version number is not found then a -1 is returned if -1 is passed in for the current version then the number of migrations in the set is returned down indicates the direction of migration. If down is true, the current is used to report the number of migrations to get to back to the start of the migration sequence. Otherwise, it's the number of migrations to get to the end of the migration sequence.

func (Migrations) NumberOfMigrationsTo added in v3.6.2

func (ms Migrations) NumberOfMigrationsTo(from int64, to int64) int

NumberOfMigrationsTo returns the number of migrations that could be applied from the starting migration to the given to migration. If the `to` migration does not exist it will be the migration that would be the next on in line of the migrations depending on if the trend is going up or down, e.g. if `to - from > 0` then it's going up if `to - from < 0` then it's going down. If `to - from == 0`, zero is returned. if from migration is not found this function will panic

func (Migrations) Previous

func (ms Migrations) Previous(current int64) (*Migration, error)

Previous : Get the previous migration.

func (Migrations) String

func (ms Migrations) String() string

func (Migrations) Swap

func (ms Migrations) Swap(i, j int)

type MissingMigrations added in v3.6.2

type MissingMigrations struct {
	Version int64
	Source  string
}

type MissingMigrationsErr added in v3.6.2

type MissingMigrationsErr struct {
	MissingMigrations []MissingMigrations
}

func MissingMigrationsErrFromMigrations added in v3.6.2

func MissingMigrationsErrFromMigrations(migrations Migrations) (err MissingMigrationsErr)

func (MissingMigrationsErr) Error added in v3.6.2

func (err MissingMigrationsErr) Error() string

type MySQLDialect

type MySQLDialect struct{ BaseDialect }

MySQLDialect struct.

type OptionsFunc

type OptionsFunc func(o *options)

func WithAllowMissing

func WithAllowMissing() OptionsFunc

func WithEvents added in v3.6.2

func WithEvents(events chan<- Eventer, DontCloseChannelOnComplete bool) OptionsFunc

WithEvents will publish events to the given channel, and close the channel upon the completion of the function.

func WithNoOutput added in v3.6.2

func WithNoOutput() OptionsFunc

WithNoOutput will suppress the output of the function

func WithNoVersioning

func WithNoVersioning() OptionsFunc

type PostgresDialect

type PostgresDialect struct{ BaseDialect }

PostgresDialect struct.

type Provider

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

func NewProvider

func NewProvider(options ...providerOptions) *Provider

func (*Provider) AddMigration

func (p *Provider) AddMigration(up func(*sql.Tx) error, down func(*sql.Tx) error)

func (*Provider) AddNamedMigration

func (p *Provider) AddNamedMigration(filename string, up func(*sql.Tx) error, down func(*sql.Tx) error)

AddNamedMigration : Add a named migration.

func (*Provider) BaseDir added in v3.6.5

func (p *Provider) BaseDir(dir string) string

func (*Provider) CollectMigrations

func (p *Provider) CollectMigrations(dirPath string, current, target int64) (Migrations, error)

func (*Provider) Create

func (p *Provider) Create(db *sql.DB, dir, name, migrationType string) error

Create writes a new blank migration file.

func (*Provider) CreateWithTemplate

func (p *Provider) CreateWithTemplate(_ *sql.DB, dir string, tmpl *template.Template, name, migrationType string) error

CreateWithTemplate writes a new blank migration file.

func (*Provider) Dialect

func (p *Provider) Dialect() SQLDialect

Dialect returns the SQLDialect of the provider

func (*Provider) Down

func (p *Provider) Down(db *sql.DB, dir string, opts ...OptionsFunc) error

Down rolls back a single migration from the current version.

func (*Provider) DownTo

func (p *Provider) DownTo(db *sql.DB, dir string, version int64, opts ...OptionsFunc) error

DownTo rolls back migrations to a specific version.

func (*Provider) EnsureDBVersion

func (p *Provider) EnsureDBVersion(db *sql.DB) (int64, error)

EnsureDBVersion retrieves the current version for this DB. Create and initialize the DB version table if it doesn't exist.

func (*Provider) Fix

func (p *Provider) Fix(dir string) error

func (*Provider) GetDBVersion

func (p *Provider) GetDBVersion(db *sql.DB) (int64, error)

GetDBVersion is an alias for EnsureDBVersion, but returns -1 in error.

func (*Provider) GetVersions added in v3.6.2

func (p *Provider) GetVersions(db *sql.DB, dir string, opts ...OptionsFunc) (migrationVersion int64, dbVersion int64, err error)

GetVersion will return the current version of the migration, and database version, or -1, -1 if not found or if there is an error If db is nil, or the option.noVersioning is specificed, then the dbVersion will be -1.

func (*Provider) OpenDBWithDriver

func (p *Provider) OpenDBWithDriver(driver string, dbstring string) (*sql.DB, error)

OpenDBWithDriver creates a connection to a database, and modifies goose internals to be compatible with the supplied driver by calling SetDialect.

func (*Provider) Redo

func (p *Provider) Redo(db *sql.DB, dir string, opts ...OptionsFunc) error

Redo rolls back the most recently applied migration, then runs it again.

func (*Provider) Reset

func (p *Provider) Reset(db *sql.DB, dir string, opts ...OptionsFunc) error

Reset rolls back all migrations

func (*Provider) SetBaseFS

func (p *Provider) SetBaseFS(fsys fs.FS)

SetBaseFS sets a base FS to discover migrations. It can be used with the `embed` package. Calling with `nil` argument leads to the default behavior: discovering migrations from the os filesystem.

Note: that modifying operations like Create will use os filesystem anyway.

func (*Provider) SetDialect

func (p *Provider) SetDialect(d string) error

SetDialect sets the SQLDialect

func (*Provider) SetLogger

func (p *Provider) SetLogger(l Logger)

SetLogger sets the logger for package output

func (*Provider) SetSequential

func (p *Provider) SetSequential(s bool)

SetSequential set's whether to use sequential versioning instead of timestamp based versioning

func (*Provider) SetTableName

func (p *Provider) SetTableName(n string)

SetTableName set goose db version table name

func (*Provider) SetVerbose

func (p *Provider) SetVerbose(v bool)

SetVerbose set the goose verbosity mode

func (*Provider) Status

func (p *Provider) Status(db *sql.DB, dir string, opts ...OptionsFunc) (err error)

func (*Provider) TableName

func (p *Provider) TableName() string

TableName returns goose db version table name

func (*Provider) Up

func (p *Provider) Up(db *sql.DB, dir string, opts ...OptionsFunc) error

Up applies all available migrations.

func (*Provider) UpByOne

func (p *Provider) UpByOne(db *sql.DB, dir string, opts ...OptionsFunc) error

UpByOne migrates up by a single version.

func (*Provider) UpTo

func (p *Provider) UpTo(db *sql.DB, dir string, version int64, opts ...OptionsFunc) (err error)

func (*Provider) Verify added in v3.6.4

func (p *Provider) Verify(dir string) VerifyStatus

Verify will check the migration directory to see if there are any errors, or other issues. It will return a VerifyStatus with any errors it found

func (*Provider) Version

func (p *Provider) Version(db *sql.DB, dir string, opts ...OptionsFunc) error

Version prints the current version of the database.

type RedshiftDialect

type RedshiftDialect struct{ BaseDialect }

RedshiftDialect struct.

type SQLDialect

type SQLDialect interface {
	SetTableName(name string) // set table name to use for SQL generation
	// contains filtered or unexported methods
}

SQLDialect abstracts the details of specific SQL dialects for goose's few SQL specific statements

func GetDialect

func GetDialect() SQLDialect

GetDialect gets the SQLDialect

func SelectDialect

func SelectDialect(tableName, d string) (SQLDialect, error)

type SqlServerDialect

type SqlServerDialect struct{ BaseDialect }

SqlServerDialect struct.

type Sqlite3Dialect

type Sqlite3Dialect struct{ BaseDialect }

Sqlite3Dialect struct.

type StatusEvent added in v3.6.2

type StatusEvent struct {
	*Event

	// Source is the full path of the source file, use `Script` to get the name
	Source string
	// Version is the version number, it should be -1 if not set
	Version   int64
	Versioned bool
	// If not zero then the time the migration was applied at
	AppliedAt time.Time
}

StatusEvent is a version number, and source of a migration, and whether it has been applied

func (StatusEvent) AppliedString added in v3.6.2

func (se StatusEvent) AppliedString() string

func (StatusEvent) IsEqual added in v3.6.3

func (se StatusEvent) IsEqual(e Eventer) bool

func (StatusEvent) Script added in v3.6.2

func (se StatusEvent) Script() string

func (StatusEvent) String added in v3.6.2

func (se StatusEvent) String() string

func (StatusEvent) VersionedString added in v3.6.3

func (se StatusEvent) VersionedString() string

type TiDBDialect

type TiDBDialect struct{ BaseDialect }

TiDBDialect struct.

type VerifyStatus added in v3.6.4

type VerifyStatus struct {
	Status int
	Error  error
}

func Verify added in v3.6.4

func Verify(dir string) VerifyStatus

Verify will check the migration directory to see if there are any errors, or other issues. It will return a VerifyStatus with any errors it found

func (VerifyStatus) HasTsMigrations added in v3.6.4

func (vs VerifyStatus) HasTsMigrations() bool

func (VerifyStatus) Ok added in v3.6.4

func (vs VerifyStatus) Ok() bool

type VersionApplyEvent added in v3.6.2

type VersionApplyEvent struct {
	*Event
	From       int64
	FromSource string
	To         int64
	ToSource   string
	ApplyAT    time.Time
	Missing    bool
	Applied    bool
	Versioned  bool
	Down       bool
}

VersionApplyEvent usually comes in pairs unless there is an error, the first event (with applied set to false) will be emmited before the version is applied to the database, and the applied version after the new version has been applied.

func (VersionApplyEvent) IsEqual added in v3.6.3

func (e VersionApplyEvent) IsEqual(o Eventer) bool

type VersionCountEvent added in v3.6.2

type VersionCountEvent struct {
	*Event
	Version           int64
	VersionSource     string
	TotalVersionsLeft int
}

func (VersionCountEvent) IsEqual added in v3.6.3

func (e VersionCountEvent) IsEqual(o Eventer) bool

Directories

Path Synopsis
cmd
examples
internal

Jump to

Keyboard shortcuts

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