lib

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Copyright (C) 2026 Pau Sanchez

The ascii table gofly prints for `info`, laid out like Flyway's.

Flyway-compatible checksum calculation.

Flyway computes a CRC-32 over the migration contents read line by line, which makes the result independent of the line endings and of the trailing newline. The BOM, when present, is stripped from the first line only.

See org.flywaydb.core.internal.resolver.ChecksumCalculator

Configuration, gathered from the same places Flyway looks at and with the same precedence: built in defaults, then config files, then environment variables, then the command line.

Database connectivity and the small dialect abstraction the rest of gofly builds upon. Only the differences that actually matter for migrating are abstracted: quoting, schema handling, the history table DDL and how each driver spells its bind parameters.

SQL Server dialect.

MySQL and MariaDB dialect.

MySQL calls databases schemas, so the gofly history lives in a database of its own only when one is explicitly configured. By default it sits next to the migrated tables, under its own table name.

PostgreSQL dialect.

SQLite dialect, backed by a pure Go driver so that gofly stays a single static binary with no cgo and no system libraries to install.

The commands themselves: info, validate, migrate, undo, baseline, repair and clean.

The schema history table.

gofly keeps its own table, in its own schema when the database supports it, with exactly the layout Flyway uses. On the very first run against a database that was previously migrated with Flyway, every row of flyway_schema_history is copied over so that the history, and therefore the checksum validation, carries on uninterrupted.

Pairing of the migrations found on disk with the rows of the schema history, and the state each pair ends up in.

See org.flywaydb.core.internal.info.MigrationInfoServiceImpl

Serialize mutating PostgreSQL commands before inspecting migration history.

Discovery of the migrations available on disk.

A migration owns one physical connection, including COPY protocol operations.

Placeholder replacement, compatible with Flyway's PlaceholderReplacer.

Flyway-compatible migration file name parsing.

Versioned and undo migrations are named prefixVERSIONseparatorDESCRIPTIONsuffix (V1.1__Add_users.sql), repeatable ones prefixSeparatorDESCRIPTIONsuffix (R__Refresh_views.sql).

See org.flywaydb.core.internal.resource.ResourceNameParser

Schema inspection for the safeguards around adopting unmanaged databases.

PostgreSQL session state and advisory locks, and MySQL's USE, must stay on one physical connection.

One writable history is necessary for safe handover in both directions.

PostgreSQL statement classification without matching keywords inside literals.

Splitting of a migration into the individual statements to send to the database. Every driver we support requires one statement per round trip, so the script has to be cut on the statement boundaries while respecting string literals, comments and the quoting rules of each dialect.

Plan transaction boundaries before executing any part of a migration.

Validation of the schema history against the migrations on disk.

The checks, their order and their wording follow org.flywaydb.core.internal.info.MigrationInfoImpl.validate so that a database Flyway refuses to migrate is refused by gofly too, and for the same reason.

Flyway-compatible migration version handling.

A version is a list of big integers, obtained by replacing '_' with '.' and splitting on every dot that is followed by a digit. Trailing zero parts are dropped, so 1.0 == 1 == 1.0.0, exactly like Flyway's MigrationVersion.

Index

Constants

View Source
const (
	// DefaultGoflySchema is where gofly keeps its own history table on the
	// databases that have real schemas
	DefaultGoflySchema = "gofly"

	// DefaultGoflyTable is the gofly history table name
	DefaultGoflyTable = "gofly_schema_history"

	// FlywayTable is the table gofly imports from on a first run
	FlywayTable = "flyway_schema_history"
)
View Source
const (
	// NamespaceFlyway is the deprecated flyway.* / FLYWAY_* namespace
	NamespaceFlyway = "flyway"

	// NamespaceGofly is the gofly.* / GOFLY_* namespace
	NamespaceGofly = "gofly"
)

Property namespaces a setting may be written in

View Source
const (
	DialectPostgres = "postgresql"
	DialectMysql    = "mysql"
	DialectMssql    = "sqlserver"
	DialectSqlite   = "sqlite"
)

Supported dialects

Variables

View Source
var (
	// VersionEmpty represents an empty schema (no version at all)
	VersionEmpty = &Version{kind: VersionKindEmpty, displayText: "<< Empty Schema >>"}

	// VersionLatest represents the latest available version
	VersionLatest = &Version{kind: VersionKindLatest, displayText: "<< Latest Version >>"}

	// VersionCurrent represents the version currently applied to the database
	VersionCurrent = &Version{kind: VersionKindCurrent, displayText: "<< Current Version >>"}

	// VersionNext represents the next version to be applied
	VersionNext = &Version{kind: VersionKindNext, displayText: "<< Next Version >>"}
)
View Source
var ErrUnknownProperty = errors.New("unknown configuration property")

ErrUnknownProperty is what SetFrom returns when the property name matches nothing gofly understands. A config file or the command line names a property on purpose, so there a typo stays fatal; the environment is shared with the rest of the machine and is checked against this, since plenty of variables merely start with FLYWAY_ without being settings.

Functions

func AbbreviateDescription

func AbbreviateDescription(description string) string

----------------------------------------------------------------------------- AbbreviateDescription

Descriptions are stored in a VARCHAR(200), Flyway truncates the overflow with an ellipsis and gofly has to do the same for the checksums to line up. -----------------------------------------------------------------------------

func AbbreviateScript

func AbbreviateScript(script string) string

----------------------------------------------------------------------------- AbbreviateScript -----------------------------------------------------------------------------

func ChecksumBytes

func ChecksumBytes(content []byte) int32

----------------------------------------------------------------------------- ChecksumBytes

Calculates the Flyway checksum of an in-memory migration. -----------------------------------------------------------------------------

func ChecksumCombine

func ChecksumCombine(checksums []int32) int32

----------------------------------------------------------------------------- ChecksumCombine

When a migration is made of several resources Flyway CRC-32's the big-endian representation of each individual checksum. A single resource keeps its own checksum untouched. -----------------------------------------------------------------------------

func ChecksumFile

func ChecksumFile(path string) (int32, error)

----------------------------------------------------------------------------- ChecksumFile

Calculates the Flyway checksum of a migration stored on disk. -----------------------------------------------------------------------------

func ChecksumString

func ChecksumString(content string) int32

----------------------------------------------------------------------------- ChecksumString -----------------------------------------------------------------------------

func CompiledInDialects

func CompiledInDialects() []string

----------------------------------------------------------------------------- CompiledInDialects

Names the dialects this binary can actually talk to, which is everything for a normal build and a subset for the single database ones. Derived from the drivers that registered themselves, so it cannot drift from reality. -----------------------------------------------------------------------------

func DefaultConfigFiles

func DefaultConfigFiles() []string

----------------------------------------------------------------------------- DefaultConfigFiles

Returns the config files Flyway loads implicitly: the one next to the executable, the one in the user's home and the one in the working directory. Missing files are simply not returned. -----------------------------------------------------------------------------

func DescribeLocations

func DescribeLocations(locations []string) string

----------------------------------------------------------------------------- DescribeLocations

Renders the configured locations for the banner gofly prints on start up. -----------------------------------------------------------------------------

func DetectSeparator added in v0.1.2

func DetectSeparator(fileNames []string, naming Naming) (string, int, bool)

----------------------------------------------------------------------------- DetectSeparator

Looks for a separator that parses more of the given file names than the configured one does, and returns it along with the number of names it parses.

Only a strict winner is reported: when two candidates parse the same number of names the convention in use is ambiguous, and guessing would be worse than saying nothing.

This never changes how migrations are read, it only feeds an error message. Picking a separator silently would quietly change what a name means: with "__" the file V1_2__add_users.sql is version 1.2 described "add users", while with "_" it is version 1 described "2 add users". Applying the wrong reading would write the wrong version into the schema history, so the choice stays with whoever knows the project. -----------------------------------------------------------------------------

func DumpInfoTable

func DumpInfoTable(service *MigrationInfoService) string

----------------------------------------------------------------------------- DumpInfoTable

Renders the migrations as the table the `info` command prints. Undo migrations are not listed on their own, they show up as the Undoable column of the migration they undo. -----------------------------------------------------------------------------

func DumpValidationTable added in v0.1.2

func DumpValidationTable(service *MigrationInfoService) string

----------------------------------------------------------------------------- DumpValidationTable

Renders what validation actually compared: the file found on disk, the row it was paired with in the schema history, and the checksums of both. This is what `validate --verbose` prints, so that a mismatch can be traced back to a concrete file without guessing. -----------------------------------------------------------------------------

func StripJDBCPrefix added in v0.1.1

func StripJDBCPrefix(url string) string

----------------------------------------------------------------------------- StripJDBCPrefix

Removes a leading jdbc: so that the rest of the parsing only ever deals with the native scheme. A url that does not carry it is returned untouched. -----------------------------------------------------------------------------

Types

type AppliedMigration

type AppliedMigration struct {
	InstalledRank int
	Version       *Version
	Description   string
	Type          MigrationType
	Script        string
	Checksum      *int32
	InstalledBy   string
	InstalledOn   time.Time
	ExecutionTime int
	Success       bool
}

AppliedMigration is one row of the schema history table

type Config

type Config struct {
	// connection
	URL            string
	User           string
	Password       string
	ConnectRetries int

	// where the history lives
	Schemas       []string
	DefaultSchema string
	GoflySchema   string
	Table         string

	// importing an existing Flyway history
	FlywayTable        string
	ImportFromFlyway   bool
	ReuseFlywayHistory bool

	// migration discovery
	Locations []string
	Encoding  string
	Naming

	// behaviour
	BaselineVersion         string
	BaselineDescr           string
	BaselineOnMigrate       bool
	ValidateOnMigrate       bool
	CleanDisabled           bool
	OutOfOrder              bool
	Target                  string
	Group                   bool
	Mixed                   bool
	InstalledBy             string
	IgnoreMissing           bool
	IgnoreFuture            bool
	SkipExecutingMigrations bool

	// placeholders
	PlaceholderReplacement bool
	Placeholders           map[string]string
	PlaceholderPrefix      string
	PlaceholderSuffix      string

	// output
	Quiet   bool
	Verbose bool

	// Warnings collects the deprecation notices raised while reading the
	// configuration, for the caller to print
	Warnings []string
	// contains filtered or unexported fields
}

Config holds every setting that drives a gofly run

func NewConfig

func NewConfig() *Config

----------------------------------------------------------------------------- NewConfig

Returns a configuration preloaded with Flyway's defaults. -----------------------------------------------------------------------------

func (*Config) LoadConfigFile

func (c *Config) LoadConfigFile(path string) error

----------------------------------------------------------------------------- LoadConfigFile

Reads a properties file in the Flyway syntax. Blank lines and lines starting with # or ! are skipped. Properties may use the gofly.* namespace, the deprecated flyway.* one or no namespace at all, but not a mixture. -----------------------------------------------------------------------------

func (*Config) LoadEnvironment

func (c *Config) LoadEnvironment(environment []string) error

----------------------------------------------------------------------------- LoadEnvironment

Applies FLYWAY_* and GOFLY_* environment variables. FLYWAY_SQL_MIGRATION_PREFIX maps onto sqlMigrationPrefix, and FLYWAY_PLACEHOLDERS_MY_KEY onto the placeholder my_key, exactly like the Flyway command line.

Variables that name no known property are ignored. The environment is not written for gofly alone: a machine with the Java edition installed exports FLYWAY_DIR and FLYWAY_HOME, which point at the install and are not settings at all, and refusing to run because of one is no help to anybody. -----------------------------------------------------------------------------

func (*Config) NewPlaceholderReplacer

func (c *Config) NewPlaceholderReplacer() *PlaceholderReplacer

----------------------------------------------------------------------------- NewPlaceholderReplacer -----------------------------------------------------------------------------

func (*Config) ResolveInstalledBy

func (c *Config) ResolveInstalledBy() string

----------------------------------------------------------------------------- ResolveInstalledBy

Returns the name to record in the installed_by column. -----------------------------------------------------------------------------

func (*Config) Set

func (c *Config) Set(key string, value string) error

----------------------------------------------------------------------------- Set

Applies a single `key=value` setting coming from the command line, where property names are always bare. -----------------------------------------------------------------------------

func (*Config) SetFrom

func (c *Config) SetFrom(key string, value string, origin Origin) error

----------------------------------------------------------------------------- SetFrom

Applies a single `key=value` setting, remembering where it came from so that deprecations and namespace clashes can be reported usefully.

A property may be written bare (url), in the gofly namespace (gofly.url) or in the deprecated flyway one (flyway.url). The flyway namespace still works, so an existing flyway.conf needs no editing, but it warns, and so does a configuration that uses both namespaces at once.

The namespace is recorded only once the property has turned out to be a real one, so that an unrelated FLYWAY_HOME sitting in the environment never counts as use of the flyway namespace. -----------------------------------------------------------------------------

func (*Config) TargetVersion

func (c *Config) TargetVersion() (*Version, error)

----------------------------------------------------------------------------- TargetVersion

Parses the configured target, defaulting to "latest". -----------------------------------------------------------------------------

type Connection

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

Connection bundles an open database handle with its dialect

func Connect

func Connect(url string, user string, password string, connectRetries int) (*Connection, error)

----------------------------------------------------------------------------- Connect

Opens a connection from a Flyway style JDBC url (or its native equivalent), retrying up to connectRetries times, one second apart, the way the Flyway command line does. -----------------------------------------------------------------------------

func NewConnectionFromDB

func NewConnectionFromDB(db *sql.DB, dialect Dialect) *Connection

----------------------------------------------------------------------------- NewConnectionFromDB

Wraps an already open handle, which is what the tests use. -----------------------------------------------------------------------------

func (*Connection) Close

func (c *Connection) Close() error

----------------------------------------------------------------------------- Close -----------------------------------------------------------------------------

func (*Connection) DB

func (c *Connection) DB() *sql.DB

----------------------------------------------------------------------------- DB -----------------------------------------------------------------------------

func (*Connection) Dialect

func (c *Connection) Dialect() Dialect

----------------------------------------------------------------------------- Dialect -----------------------------------------------------------------------------

func (*Connection) URL

func (c *Connection) URL() string

----------------------------------------------------------------------------- URL -----------------------------------------------------------------------------

type Database added in v0.2.0

type Database interface {
	Exec(string, ...any) (sql.Result, error)
	Query(string, ...any) (*sql.Rows, error)
	QueryRow(string, ...any) *sql.Row
	Begin() (*sql.Tx, error)
}

Database is the query surface used by dialects, pools and pinned sessions.

type Dialect

type Dialect interface {
	// Name returns the dialect identifier, one of the Dialect* constants
	Name() string

	// QuoteIdentifier quotes a possibly qualified identifier
	QuoteIdentifier(parts ...string) string

	// Placeholder renders the bind parameter for the given 1-based position
	Placeholder(index int) string

	// DefaultSchema returns the schema the connection writes to by default,
	// never returning excluding, which is the schema gofly keeps its own
	// history in
	DefaultSchema(db Database, excluding string) (string, error)

	// DefaultHistorySchema is where gofly keeps its own history table. An empty
	// string means "the default schema of the connection".
	DefaultHistorySchema() string

	// SupportsSchemas reports whether the dialect has schemas at all
	SupportsSchemas() bool

	// SchemaExists reports whether a schema is already there
	SchemaExists(db Database, schema string) (bool, error)

	// CreateSchemaSQL returns the statements creating a schema
	CreateSchemaSQL(schema string) []string

	// TableExists reports whether a table is already there
	TableExists(db Database, schema string, table string) (bool, error)

	// CreateHistoryTableSQL returns the statements creating the history table,
	// byte for byte compatible with the one Flyway creates
	CreateHistoryTableSQL(schema string, table string) []string

	// SupportsDDLTransactions reports whether DDL can be rolled back
	SupportsDDLTransactions() bool

	// BooleanLiteral renders a boolean for this dialect
	BooleanLiteral(value bool) string

	// SetSessionSchema points the session at the given schema, when possible
	SetSessionSchema(db Database, schema string) error
}

Dialect isolates everything that differs between the databases we support

func DialectByName

func DialectByName(name string) (Dialect, error)

----------------------------------------------------------------------------- DialectByName

Resolves a dialect from its short name, which is handy for tests and for the -type command line flag. -----------------------------------------------------------------------------

func ParseURL

func ParseURL(url string, user string, password string) (string, string, Dialect, error)

----------------------------------------------------------------------------- ParseURL

Turns a database url into the driver name and DSN the matching Go driver expects. The jdbc: prefix Flyway insists on is optional, so postgresql://... and jdbc:postgresql://... are read exactly the same way and the tool is usable without dragging JDBC syntax around. -----------------------------------------------------------------------------

type ErrorCode

type ErrorCode string

ErrorCode identifies a validation failure, using Flyway's own codes

const (
	ErrorFailedVersionedMigration              ErrorCode = "FAILED_VERSIONED_MIGRATION"
	ErrorFailedRepeatableMigration             ErrorCode = "FAILED_REPEATABLE_MIGRATION"
	ErrorAppliedVersionedMigrationNotResolved  ErrorCode = "APPLIED_VERSIONED_MIGRATION_NOT_RESOLVED"
	ErrorAppliedRepeatableMigrationNotResolved ErrorCode = "APPLIED_REPEATABLE_MIGRATION_NOT_RESOLVED"
	ErrorResolvedVersionedMigrationNotApplied  ErrorCode = "RESOLVED_VERSIONED_MIGRATION_NOT_APPLIED"
	ErrorResolvedRepeatableMigrationNotApplied ErrorCode = "RESOLVED_REPEATABLE_MIGRATION_NOT_APPLIED"
	ErrorOutdatedRepeatableMigration           ErrorCode = "OUTDATED_REPEATABLE_MIGRATION"
	ErrorTypeMismatch                          ErrorCode = "TYPE_MISMATCH"
	ErrorChecksumMismatch                      ErrorCode = "CHECKSUM_MISMATCH"
	ErrorDescriptionMismatch                   ErrorCode = "DESCRIPTION_MISMATCH"
)

type Gofly

type Gofly struct {
	Config     *Config
	Connection *Connection
	History    *SchemaHistory
	Output     io.Writer
	// contains filtered or unexported fields
}

Gofly ties together a configuration, a connection and its schema history

func New

func New(config *Config) (*Gofly, error)

----------------------------------------------------------------------------- New

Opens the connection and works out where the history table belongs. -----------------------------------------------------------------------------

func NewWithConnection

func NewWithConnection(config *Config, connection *Connection) (*Gofly, error)

----------------------------------------------------------------------------- NewWithConnection

Same as New for an already open connection, which is what the tests use. -----------------------------------------------------------------------------

func (*Gofly) Baseline

func (g *Gofly) Baseline() (err error)

----------------------------------------------------------------------------- Baseline -----------------------------------------------------------------------------

func (*Gofly) Clean

func (g *Gofly) Clean() error

----------------------------------------------------------------------------- Clean

Accepted for command line compatibility only. See the message below for why gofly does not wipe schemas. -----------------------------------------------------------------------------

func (*Gofly) Close

func (g *Gofly) Close() error

----------------------------------------------------------------------------- Close -----------------------------------------------------------------------------

func (*Gofly) EnsureHistory

func (g *Gofly) EnsureHistory() (err error)

----------------------------------------------------------------------------- EnsureHistory -----------------------------------------------------------------------------

func (*Gofly) Info

func (g *Gofly) Info() (*MigrationInfoService, error)

----------------------------------------------------------------------------- Info

Returns the current picture of the database. This never creates or modifies anything: on a database gofly has not taken over yet it reads the existing Flyway history instead, so that info and validate can report on it without committing to the migration. -----------------------------------------------------------------------------

func (*Gofly) InfoWithSource

func (g *Gofly) InfoWithSource() (*MigrationInfoService, HistorySource, error)

----------------------------------------------------------------------------- InfoWithSource

Same as Info, and also says which history table the answer came from. -----------------------------------------------------------------------------

func (*Gofly) Migrate

func (g *Gofly) Migrate() (result *MigrateResult, err error)

----------------------------------------------------------------------------- Migrate -----------------------------------------------------------------------------

func (*Gofly) Repair

func (g *Gofly) Repair() (result *RepairResult, err error)

----------------------------------------------------------------------------- Repair -----------------------------------------------------------------------------

func (*Gofly) Undo

func (g *Gofly) Undo() (result *UndoResult, err error)

----------------------------------------------------------------------------- Undo -----------------------------------------------------------------------------

func (*Gofly) Validate

func (g *Gofly) Validate() (*ValidateResult, error)

----------------------------------------------------------------------------- Validate

Runs the validation on its own, the way the `validate` command does. Nothing is created or migrated: on a database still managed by Flyway the files are checked against the existing flyway_schema_history. -----------------------------------------------------------------------------

type HistorySource

type HistorySource int

HistorySource says which table an info or validate run read from

const (
	// HistorySourceNone means neither gofly nor Flyway has a history here yet
	HistorySourceNone HistorySource = iota

	// HistorySourceGofly means gofly's own table was read
	HistorySourceGofly

	// HistorySourceFlyway means gofly has no table here yet and the existing
	// Flyway one was read instead, without touching it
	HistorySourceFlyway

	// HistorySourceShared means the Flyway table was read because gofly uses
	// it as its own history
	HistorySourceShared
)

type MigrateResult

type MigrateResult struct {
	InitialVersion     string
	TargetVersion      string
	MigrationsExecuted int
	Migrations         []*ResolvedMigration
}

MigrateResult reports what a migrate run did

type MigrationInfo

type MigrationInfo struct {
	Resolved   *ResolvedMigration
	Applied    *AppliedMigration
	State      MigrationState
	OutOfOrder bool
}

MigrationInfo pairs a migration on disk with its row in the history table

func (*MigrationInfo) Description

func (i *MigrationInfo) Description() string

----------------------------------------------------------------------------- Description -----------------------------------------------------------------------------

func (*MigrationInfo) IsVersioned

func (i *MigrationInfo) IsVersioned() bool

----------------------------------------------------------------------------- IsVersioned -----------------------------------------------------------------------------

func (*MigrationInfo) Script

func (i *MigrationInfo) Script() string

----------------------------------------------------------------------------- Script -----------------------------------------------------------------------------

func (*MigrationInfo) Type

func (i *MigrationInfo) Type() MigrationType

----------------------------------------------------------------------------- Type -----------------------------------------------------------------------------

func (*MigrationInfo) Version

func (i *MigrationInfo) Version() *Version

----------------------------------------------------------------------------- Version -----------------------------------------------------------------------------

type MigrationInfoService

type MigrationInfoService struct {
	Infos []*MigrationInfo

	// AppliedBaseline is the version the database was baselined at
	AppliedBaseline *Version

	// Current is the newest version successfully applied
	Current *Version

	// Target is the version migrations stop at
	Target *Version
}

MigrationInfoService is the full picture of a database at a point in time

func BuildMigrationInfo

func BuildMigrationInfo(
	config *Config,
	resolved *ResolvedMigrations,
	applied []*AppliedMigration,
) (*MigrationInfoService, error)

----------------------------------------------------------------------------- BuildMigrationInfo

Pairs the resolved migrations with the applied ones and works out the state of each of them. -----------------------------------------------------------------------------

func (*MigrationInfoService) Applied

func (s *MigrationInfoService) Applied() []*MigrationInfo

----------------------------------------------------------------------------- Applied -----------------------------------------------------------------------------

func (*MigrationInfoService) Failed

func (s *MigrationInfoService) Failed() []*MigrationInfo

----------------------------------------------------------------------------- Failed -----------------------------------------------------------------------------

func (*MigrationInfoService) Pending

func (s *MigrationInfoService) Pending() []*MigrationInfo

----------------------------------------------------------------------------- Pending

Returns the versioned and repeatable migrations that migrate would run, in the order they would run. -----------------------------------------------------------------------------

func (*MigrationInfoService) Undoable

func (s *MigrationInfoService) Undoable(resolved *ResolvedMigrations) []*MigrationInfo

----------------------------------------------------------------------------- Undoable

Returns the applied versioned migrations that have an undo script, newest first, which is the order undo runs them in. -----------------------------------------------------------------------------

func (*MigrationInfoService) Validate

func (s *MigrationInfoService) Validate(context ValidateContext) *ValidateResult

----------------------------------------------------------------------------- Validate

Checks every migration and returns all the problems found. -----------------------------------------------------------------------------

type MigrationState

type MigrationState string

MigrationState mirrors org.flywaydb.core.api.MigrationState

const (
	StatePending       MigrationState = "Pending"
	StateAboveTarget   MigrationState = "Above Target"
	StateBelowBaseline MigrationState = "Below Baseline"
	// StateBaselineIgnored is the migration sitting exactly at the baseline
	// version: the baseline row already stands for it, so it never runs
	StateBaselineIgnored MigrationState = "Ignored (Baseline)"
	StateBaseline        MigrationState = "Baseline"
	StateIgnored         MigrationState = "Ignored"
	StateMissingSuccess  MigrationState = "Missing"
	StateMissingFailed   MigrationState = "Failed (Missing)"
	StateSuccess         MigrationState = "Success"
	StateUndone          MigrationState = "Undone"
	StateAvailable       MigrationState = "Available"
	StateFailed          MigrationState = "Failed"
	StateOutOfOrder      MigrationState = "Out of Order"
	StateFutureSuccess   MigrationState = "Future"
	StateFutureFailed    MigrationState = "Failed (Future)"
	StateOutdated        MigrationState = "Outdated"
	StateSuperseded      MigrationState = "Superseded"
	StateDeleted         MigrationState = "Deleted"
)

func (MigrationState) IsApplied

func (s MigrationState) IsApplied() bool

----------------------------------------------------------------------------- IsApplied -----------------------------------------------------------------------------

func (MigrationState) IsFailed

func (s MigrationState) IsFailed() bool

----------------------------------------------------------------------------- IsFailed -----------------------------------------------------------------------------

type MigrationType

type MigrationType string

MigrationType is the value stored in the `type` column of the history table

const (
	MigrationTypeSchema   MigrationType = "SCHEMA"
	MigrationTypeBaseline MigrationType = "BASELINE"
	MigrationTypeDelete   MigrationType = "DELETE"
	MigrationTypeSQL      MigrationType = "SQL"
	MigrationTypeUndoSQL  MigrationType = "UNDO_SQL"
)

func (MigrationType) IsBaseline

func (t MigrationType) IsBaseline() bool

----------------------------------------------------------------------------- IsBaseline -----------------------------------------------------------------------------

func (MigrationType) IsSynthetic

func (t MigrationType) IsSynthetic() bool

----------------------------------------------------------------------------- IsSynthetic

Synthetic types only ever exist in the history table, they are never resolved from the file system. -----------------------------------------------------------------------------

func (MigrationType) IsUndo

func (t MigrationType) IsUndo() bool

----------------------------------------------------------------------------- IsUndo -----------------------------------------------------------------------------

type Naming

type Naming struct {
	SQLMigrationPrefix           string
	UndoSQLMigrationPrefix       string
	RepeatableSQLMigrationPrefix string
	SQLMigrationSeparator        string
	SQLMigrationSuffixes         []string
}

Naming groups every setting that drives migration file name resolution

func DefaultNaming

func DefaultNaming() Naming

----------------------------------------------------------------------------- DefaultNaming

Returns Flyway's out of the box naming conventions. -----------------------------------------------------------------------------

type Origin

type Origin struct {
	Source   string
	Location string
}

Origin says where a setting came from. Source identifies the file or channel as a whole, so a deprecation warns once for a config file rather than once per line, while Location pins down the exact spot for the error messages.

func CommandLineOrigin

func CommandLineOrigin() Origin

----------------------------------------------------------------------------- CommandLineOrigin -----------------------------------------------------------------------------

func EnvironmentOrigin

func EnvironmentOrigin(name string) Origin

----------------------------------------------------------------------------- EnvironmentOrigin -----------------------------------------------------------------------------

func FileOrigin

func FileOrigin(path string, line int) Origin

----------------------------------------------------------------------------- FileOrigin -----------------------------------------------------------------------------

type PlaceholderReplacer

type PlaceholderReplacer struct {
	Enabled      bool
	Prefix       string
	Suffix       string
	Values       map[string]string
	ErrorOnUnset bool
}

PlaceholderReplacer substitutes ${name} style placeholders in a migration

func NewPlaceholderReplacer

func NewPlaceholderReplacer(values map[string]string) *PlaceholderReplacer

----------------------------------------------------------------------------- NewPlaceholderReplacer -----------------------------------------------------------------------------

func (*PlaceholderReplacer) Replace

func (r *PlaceholderReplacer) Replace(sql string) (string, error)

----------------------------------------------------------------------------- Replace

Substitutes every known placeholder. Longer names are replaced first so that ${db} never eats the beginning of ${db_name}. -----------------------------------------------------------------------------

type RepairResult

type RepairResult struct {
	RemovedFailed    int
	AlignedChecksums int
	MarkedAsDeleted  int
}

RepairResult reports what a repair run did

type ResolvedMigration

type ResolvedMigration struct {
	Version          *Version
	Description      string
	Type             MigrationType
	Script           string
	Checksum         int32
	PhysicalLocation string
	IsUndo           bool
	IsRepeatable     bool
	// contains filtered or unexported fields
}

ResolvedMigration is a migration found on the file system

func (*ResolvedMigration) Key

func (m *ResolvedMigration) Key() string

----------------------------------------------------------------------------- Key

Returns the identity used to pair a resolved migration with an applied one. -----------------------------------------------------------------------------

func (*ResolvedMigration) LoadSQL

func (m *ResolvedMigration) LoadSQL(replacer *PlaceholderReplacer) (string, error)

----------------------------------------------------------------------------- LoadSQL

Reads a migration and applies the placeholder replacement. -----------------------------------------------------------------------------

type ResolvedMigrations

type ResolvedMigrations struct {
	Versioned  []*ResolvedMigration
	Undo       []*ResolvedMigration
	Repeatable []*ResolvedMigration
}

ResolvedMigrations groups everything found across all the locations

func ResolveMigrations

func ResolveMigrations(config *Config) (*ResolvedMigrations, error)

----------------------------------------------------------------------------- ResolveMigrations

Scans every configured location and returns the migrations found, sorted by version (and by description for the repeatable ones). Duplicated versions and unparseable names are reported as errors, the way Flyway does. -----------------------------------------------------------------------------

func (*ResolvedMigrations) UndoFor

func (r *ResolvedMigrations) UndoFor(version *Version) *ResolvedMigration

----------------------------------------------------------------------------- UndoFor

Returns the undo migration matching a version, if any. -----------------------------------------------------------------------------

type ResourceName

type ResourceName struct {
	Prefix       string
	VersionText  string
	Separator    string
	Description  string
	RawStem      string
	Suffix       string
	Type         ResourceType
	Version      *Version
	Valid        bool
	InvalidCause string
}

ResourceName holds a migration file name broken into its components

func ParseResourceName

func ParseResourceName(fileName string, naming Naming) ResourceName

----------------------------------------------------------------------------- ParseResourceName

Splits a migration file name into its parts. A name that does not follow the conventions comes back with Valid set to false and InvalidCause explaining why, mirroring how Flyway reports these problems. -----------------------------------------------------------------------------

type ResourceType

type ResourceType int

ResourceType tells which kind of file a name refers to

const (
	ResourceTypeUnknown ResourceType = iota
	ResourceTypeVersioned
	ResourceTypeUndo
	ResourceTypeRepeatable
	ResourceTypeCallback
)

func (ResourceType) IsVersioned

func (t ResourceType) IsVersioned() bool

----------------------------------------------------------------------------- IsVersioned -----------------------------------------------------------------------------

type SchemaHistory

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

SchemaHistory reads and writes the history table

func NewSchemaHistory

func NewSchemaHistory(connection *Connection, schema string, table string, installedBy string) *SchemaHistory

----------------------------------------------------------------------------- NewSchemaHistory -----------------------------------------------------------------------------

func (*SchemaHistory) All

func (h *SchemaHistory) All() ([]*AppliedMigration, error)

----------------------------------------------------------------------------- All

Returns every row, ordered by installed_rank, which is the order in which the migrations were applied. -----------------------------------------------------------------------------

func (*SchemaHistory) Create

func (h *SchemaHistory) Create() error

----------------------------------------------------------------------------- Create

Creates the schema, if needed, and then the history table itself. -----------------------------------------------------------------------------

func (*SchemaHistory) CreateAndImport added in v0.2.0

func (h *SchemaHistory) CreateAndImport(sourceSchema, sourceTable string, importHistory bool) (int, error)

----------------------------------------------------------------------------- CreateAndImport

A history table is the marker that takeover completed. On transactional DDL engines it must become visible in the same commit as the imported rows. -----------------------------------------------------------------------------

func (*SchemaHistory) Exists

func (h *SchemaHistory) Exists() (bool, error)

----------------------------------------------------------------------------- Exists -----------------------------------------------------------------------------

func (*SchemaHistory) ImportFromFlyway

func (h *SchemaHistory) ImportFromFlyway(flywaySchema string, flywayTable string) (int, error)

----------------------------------------------------------------------------- ImportFromFlyway

Copies every row of an existing Flyway history table into the gofly one. Returns how many rows were moved, or zero when there was nothing to import.

This runs only when the gofly table has just been created, so an import never overwrites a history gofly is already maintaining. -----------------------------------------------------------------------------

func (*SchemaHistory) Insert

func (h *SchemaHistory) Insert(executor sqlExecutor, migration *AppliedMigration) error

----------------------------------------------------------------------------- Insert

Records the outcome of a migration. -----------------------------------------------------------------------------

func (*SchemaHistory) MarkAsDeleted

func (h *SchemaHistory) MarkAsDeleted(installedRank int) error

----------------------------------------------------------------------------- MarkAsDeleted

Turns an applied migration into a DELETE marker, which is how `repair` records a migration that no longer exists locally. -----------------------------------------------------------------------------

func (*SchemaHistory) NextInstalledRank

func (h *SchemaHistory) NextInstalledRank() (int, error)

----------------------------------------------------------------------------- NextInstalledRank -----------------------------------------------------------------------------

func (*SchemaHistory) QualifiedName

func (h *SchemaHistory) QualifiedName() string

----------------------------------------------------------------------------- QualifiedName -----------------------------------------------------------------------------

func (*SchemaHistory) RemoveFailed

func (h *SchemaHistory) RemoveFailed() (int64, error)

----------------------------------------------------------------------------- RemoveFailed

Deletes the rows of the migrations that failed, which is the other half of what `repair` does. -----------------------------------------------------------------------------

func (*SchemaHistory) UpdateChecksum

func (h *SchemaHistory) UpdateChecksum(installedRank int, description string, migrationType MigrationType, checksum *int32) error

----------------------------------------------------------------------------- UpdateChecksum

Realigns the stored description, type and checksum with the migration on disk, which is what `repair` does. -----------------------------------------------------------------------------

type Statement

type Statement struct {
	SQL        string
	Line       int
	CopyData   *string
	ParseError string

	// Batch counts the SQL Server GO separators before the statement. Flyway
	// parses a whole batch as one statement, which matters for transactions.
	Batch int
}

Statement is a single executable statement together with the line it starts at, so that errors can be reported the way Flyway does.

func SplitStatements

func SplitStatements(sql string, dialect string) []Statement

----------------------------------------------------------------------------- SplitStatements

Cuts a migration script into statements for the given dialect. Empty statements and comment-only fragments are dropped. -----------------------------------------------------------------------------

type UndoResult

type UndoResult struct {
	MigrationsUndone int
	Migrations       []*ResolvedMigration
}

UndoResult reports what an undo run did

type ValidateContext

type ValidateContext struct {
	// IgnorePending is set while migrating, since the pending migrations are
	// about to be applied anyway
	IgnorePending bool

	// IgnoreMissing tolerates applied migrations whose file is gone
	IgnoreMissing bool

	// IgnoreFuture tolerates history rows newer than anything available here
	IgnoreFuture bool

	// IgnoreIgnored tolerates out of order migrations that will not be applied
	IgnoreIgnored bool
}

ValidateContext says which discrepancies are tolerated

type ValidateError

type ValidateError struct {
	Code        ErrorCode
	Version     string
	Description string
	FilePath    string
	Message     string
}

ValidateError is a single validation failure

func (*ValidateError) Error

func (e *ValidateError) Error() string

----------------------------------------------------------------------------- Error -----------------------------------------------------------------------------

type ValidateResult

type ValidateResult struct {
	Errors          []*ValidateError
	ValidationCount int
}

ValidateResult is the outcome of a validation run

func (*ValidateResult) Error

func (r *ValidateResult) Error() error

----------------------------------------------------------------------------- Error

Renders every failure the way the Flyway command line reports them. -----------------------------------------------------------------------------

func (*ValidateResult) Valid

func (r *ValidateResult) Valid() bool

----------------------------------------------------------------------------- Valid -----------------------------------------------------------------------------

type Version

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

Version mirrors org.flywaydb.core.api.MigrationVersion

func NewVersion

func NewVersion(version string) (*Version, error)

----------------------------------------------------------------------------- NewVersion

Parses a version string like 6, 6.0, 005, 1.2.3.4, 20100420002 or 1_2_3. Returns an error when the version contains anything but digits and separators. -----------------------------------------------------------------------------

func VersionFromString

func VersionFromString(version string) (*Version, error)

----------------------------------------------------------------------------- VersionFromString

Same as NewVersion but also understands the predefined markers Flyway accepts on the command line: current, next, latest and the empty string. -----------------------------------------------------------------------------

func (*Version) CanonicalKey

func (v *Version) CanonicalKey() string

----------------------------------------------------------------------------- CanonicalKey

Returns a key that is identical for every spelling of the same version, so that 1, 1.0 and 1_0 all collide. Version.String cannot be used for this: it keeps the text as written. -----------------------------------------------------------------------------

func (*Version) Compare

func (v *Version) Compare(other *Version) int

----------------------------------------------------------------------------- Compare

Implements the same total ordering as MigrationVersion.compareTo, including the placement of the predefined markers. -----------------------------------------------------------------------------

func (*Version) Equals

func (v *Version) Equals(other *Version) bool

----------------------------------------------------------------------------- Equals -----------------------------------------------------------------------------

func (*Version) IsAtLeast

func (v *Version) IsAtLeast(other *Version) bool

----------------------------------------------------------------------------- IsAtLeast -----------------------------------------------------------------------------

func (*Version) IsNewerThan

func (v *Version) IsNewerThan(other *Version) bool

----------------------------------------------------------------------------- IsNewerThan -----------------------------------------------------------------------------

func (*Version) IsPredefined

func (v *Version) IsPredefined() bool

----------------------------------------------------------------------------- IsPredefined -----------------------------------------------------------------------------

func (*Version) Kind

func (v *Version) Kind() VersionKind

----------------------------------------------------------------------------- Kind -----------------------------------------------------------------------------

func (*Version) RawVersion

func (v *Version) RawVersion() string

----------------------------------------------------------------------------- RawVersion

Returns the version exactly as written in the migration file name. -----------------------------------------------------------------------------

func (*Version) String

func (v *Version) String() string

----------------------------------------------------------------------------- String

Returns the printable representation of the version. -----------------------------------------------------------------------------

type VersionKind

type VersionKind int

VersionKind tells apart real versions from the predefined markers Flyway uses for `target` and friends.

const (
	VersionKindReal VersionKind = iota
	VersionKindEmpty
	VersionKindLatest
	VersionKindCurrent
	VersionKindNext
)

Jump to

Keyboard shortcuts

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