fofm

package module
v0.0.0-...-62be2c9 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 16 Imported by: 0 modules, 0 packages

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

fofm (eff of em)

Functional migrations in Go. This library will allow you to run functions that exist on a struct as a migration.

Usage

  1. Define a struct with fofm.Migrations embedded in it. That is what marks it as a migration manager. It has nothing to set up, and the rest of the struct is whatever your migrations need to do their work.
package migrations

import "github.com/emehrkay/fofm"

type MyMigrationsManager struct {
	fofm.Migrations

	NeededResource *SomeLibrary
}

fofm.New only accepts a struct that embeds fofm.Migrations, so passing something else by mistake, like a database connection, is a compile error (does not implement fofm.MigrationManager (missing method isMigrationManager)) instead of a manager that finds no migrations and quietly does nothing. The embedded struct does not find the migrations itself, Go gives it no way to see the struct that it is in. fofm.New does that by looking at the methods of the struct you give it.

New migrations are written to the package that this struct is in, so give it a package of its own if you use CreateMigration. fofm works out where that is from the struct itself, there is nothing to implement. See Creating migrations

The methods can use value or pointer receivers. If they use pointer receivers, pass a pointer to fofm.New (&MyMigrationsManager{}). fofm.New returns an error if it finds migrations that a value does not have, rather than quietly running nothing.

  1. Add some migrations as functions that return an error. This can be done manually as long as the names adhere to the format Migration_$SOME_INTEGER_up (for every up migration there should be corresponding down migration)
func (m *MyMigrationsManager) Migration_1_up() error {
    // do something once
}

func (m *MyMigrationsManager) Migration_1_down() error {
    // undo the thing from Migration_1_up
}

A migration can also take a context.Context, which is the one that was passed to LatestContext, UpContext or DownContext

func (m *MyMigrationsManager) Migration_2_up(ctx context.Context) error {
    return m.NeededResource.DoSomethingSlow(ctx)
}

Any other signature is an error when you call fofm.New. Two migrations can't have the same integer.

You can also create migrations programatically.

db, _ := fofm.NewSQLite(":memory:")
myMig := &MyMigrationsManager{
    NeededResource: SomeLibrary.New(),
}
manager, _ := fofm.New(db, myMig)

manager.CreateMigration()

This will add a new file migration_$unix_time.go with methods Migration_$unix_time_up and Migration_$unix_time_down for you to fill in (the number can be a counter instead, see below). It will never overwrite a file that is already there, and it will not reuse the number of an existing migration. It returns the path to the file

Every migration is ordered based on the integer in the method name -- Migration_1_up, Migration_2_up, ..., Migration_X_up etc.

Numbering new migrations

By default a new migration is numbered with the current unix time (Migration_1658164360_up). That is a setting, and you can swap it by passing another one to fofm.New

// the default
manager, _ := fofm.New(db, myMig, fofm.UnixTimestamps)

// 1, 2, 3, ... padded to five digits: Migration_00001_up in migration_00001.go
manager, _ := fofm.New(db, myMig, fofm.IncrementingCounter)

The counter is one more than the highest migration that exists. Past 99999 it is simply wider. The integers are compared as numbers, so manager.Up("2") finds Migration_00002_up. Don't switch an existing project from unix times to the counter and expect it to start over at 1 -- it continues from the highest number, because migrations are ordered by their numbers.

To do something else, fofm.WithNumbering takes a fofm.Numbering, which is two functions: Next picks the number, given the numbers that are already used, and Format writes it into the name (it has to be digits). It is what UnixTimestamps and IncrementingCounter are made of.

fofm.WithNumbering(fofm.Numbering{
	Next:   func(taken []int64) int64 { return nextFromMyTicketSystem() },
	Format: func(number int64) string { return fmt.Sprintf("%07d", number) },
})
  1. Run the migrations
manager.Latest() // to run every migration that has not been run, in order, including the latest one
manager.Up("Migration_10_up") // to run every migration in order up to "Migration_10_up"
manager.Down("1") // to run every migration in reverse order down to "Migration_1_down" 
manager.Pending() // to see what Latest() would run, without running anything

Both the Up and Down methods can accept the full migration name Migration_1_up, a partial name Migration_1, or just the integer 1. A name that does not match a migration is an error and nothing is run

Creating migrations

A new migration has to be in the same package as the struct that has the migrations on it. fofm finds that package by looking at where the struct's own methods are defined, since every method of a type is in the same package and so the same directory. The package name is read from the Go files that are already there. There is nothing to implement and nothing to configure.

That can't be done in two cases, and CreateMigration returns an error that says so when it happens:

  • the struct has no methods of its own yet (the embedded fofm.Migrations doesn't count, it is not defined in your package). Add any method to it, or tell fofm where to write with fofm.WithMigrationsDir
  • the program was built with -trimpath, or it is running somewhere that the source is not. Use fofm.WithMigrationsDir

Running migrations never needs any of this, only creating them does.

// the settings that say where new migrations go. you rarely need them
fofm.WithMigrationsDir("./migrations") // a directory, relative to where the program is run
fofm.WithMigrationsFS(myWriteFS)       // any fofm.WriteFS, like one in memory for a test
fofm.WithPackageName("migrations")     // when the package can't be read from the Go files

A fofm.WriteFS is an fs.FS that can also write a file. The standard library's fs.FS can only read, so it has the one extra method, WriteFile. It must not overwrite a file. fofm.DirFS(dir) is the one for a directory on disk.

The files that are already there count: their migration_$number.go names are given to the numbering as numbers that are taken. A migration you just created is not part of the program until it is built, so without that, creating two in a row would give them both the same number.

How it decides what to run

A migration is applied when its most recent successful run was an up. A failed run changes nothing: a failed up leaves the migration unapplied and a failed down leaves it applied, so either one is tried again the next time.

  • Up(name) runs the migrations up to and including name that are not applied yet
  • Down(name) runs the downs from the newest applied migration back to and including name. Migrations that are not applied are skipped
  • Latest() runs everything after the last successful up. If the last successful run was a down, it runs everything from that migration on. If nothing has run, it runs everything

Every run is kept in the store, which is what Status() reports.

Contexts

Latest, Up and Down each have a variant that takes a context -- LatestContext, UpContext and DownContext.

The context is checked before each migration starts. If it is cancelled, the remaining migrations are not run and its error is returned (errors.Is(err, context.Canceled)). A migration that is already running is not interrupted by fofm, so a long running migration should take a context.Context and watch it. The migrations that did finish are recorded, so the next call picks up where this one stopped.

Locking

fofm holds a lock in the store while it runs, so two copies of an app starting at the same time will not both run the same migrations. The second one waits for the first to finish and then finds nothing left to run.

The SQLite store keeps the lock in a table next to the migrations. It is renewed while it is held and it expires if it is not renewed, so an app that crashes in the middle of a migration does not block the others forever (SQLite.SetLockTTL changes how long that takes, the default is fofm.DefaultLockTTL). Waiting for the lock honors the context that was passed in. If another process is writing to the database file itself, a query waits for it up to five seconds before it is tried again, and a context that ends in the middle of that wait is noticed when the wait is over. SQLite.SetBusyTimeout changes how long that is.

A store gets this by implementing the optional Locker interface. A store that does not will still work, but then you need to make sure that two copies are never migrating at once.

Failures

If a migration returns an error, or panics, it is recorded as a failure with the error and fofm stops. Nothing is rolled back. A migration is an arbitrary Go function, so there is no transaction to wrap it in. Write migrations so that running one again after a partial failure is safe -- CREATE TABLE IF NOT EXISTS, upserts, and checks before changes -- and use a transaction inside the migration if the thing that you are changing supports one.

Extending

As of now, sqlite is the only storage engine pacakged with fofm. Luckily, it adheres to the Store interface so rolling your own is pretty straight forward. Implement Locker as well to get the locking. A migration manager is just a struct that embeds fofm.Migrations.

fofm really shines when it is used as a command line tool. Simply wrap its public methods behind your defined CLI interfaces and you're good to go. Here is how I used fofm with cobra


func init() {
	migs := &myMigrationManager{}
	migrationsLocation := env.Get("MIGRATION_LOCATION", ":memory:")
	db, err := fofm.NewSQLite(migrationsLocation)
	if err != nil {
		panic(err)
	}

	manager, err := fofm.New(db, migs)
	if err != nil {
		panic(err)
	}

	var latest = &cobra.Command{
		Use: "migrate_latest",
		RunE: func(cmd *cobra.Command, args []string) error {
			return manager.LatestContext(cmd.Context())
		},
	}

	var create = &cobra.Command{
		Use: "migrate_create",
		RunE: func(cmd *cobra.Command, args []string) error {
			path, err := manager.CreateMigration()
			if err == nil {
				fmt.Println(path)
			}

			return err
		},
	}

	var pending = &cobra.Command{
		Use: "migrate_pending",
		RunE: func(cmd *cobra.Command, args []string) error {
			pending, err := manager.Pending()
			if err != nil {
				return err
			}

			for _, mig := range pending {
				fmt.Println(mig.Name)
			}

			return nil
		},
	}

	var status = &cobra.Command{
		Use: "migrate_status",
		RunE: func(cmd *cobra.Command, args []string) error {
			migStatus, err := manager.Status()
			if err != nil {
				return err
			}

			headers := []string{"ORDER", "MIGRATION", "STATUS", "RUNS"}
			writer := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', tabwriter.AlignRight)
			fmt.Fprintln(writer, strings.Join(headers, "\t"))

			for i, mig := range migStatus.Migrations {
				runs := []string{}
				status := "not run"

				for _, run := range mig.Runs {
					runs = append(runs, fmt.Sprintf(`(%s %s)`, run.Status, run.Timestamp))
					status = run.Status
				}

				if len(runs) == 0 {
					runs = append(runs, "-")
				}

				row := []string{
					fmt.Sprintf("%v", i),
					mig.Migration.Name,
					status,
					strings.Join(runs, " "),
				}

				fmt.Fprintln(writer, strings.Join(row, "\t"))
			}

			return writer.Flush()
		},
	}

	RootCmd.AddCommand(latest, create, pending, status)
}

Use Cases

Call manager.Latest() everytime your app starts up with confidence that it is up to date with any pre-defined one-time calls. It is safe to do from several copies of an app at once.

License MIT

Documentation

Index

Constants

View Source
const (
	STATUS_SUCCESS = "success"
	STATUS_FAILURE = "failure"
)
View Source
const (

	// DefaultLockTTL is how long a lock is held without being renewed before another
	// process may take it over
	DefaultLockTTL = 5 * time.Minute
)

Variables

View Source
var CounterNumbering = Numbering{
	Next: func(taken []int64) int64 {
		var highest int64
		for _, number := range taken {
			if number > highest {
				highest = number
			}
		}

		return highest + 1
	},
	Format: func(number int64) string {
		return fmt.Sprintf("%0*d", counterWidth, number)
	},
}

CounterNumbering numbers migrations 1, 2, 3, and so on, written with leading zeros so that they are five digits wide, like Migration_00001_up. The next number is one more than the highest one that exists. Past 99999 the number is simply wider

View Source
var DefaultSettings = []Setting{

	UnixTimestamps,
}
View Source
var UnixNumbering = Numbering{
	Next: func(taken []int64) int64 {
		used := make(map[int64]bool, len(taken))
		for _, number := range taken {
			used[number] = true
		}

		now := time.Now().Unix()
		for used[now] {
			now++
		}

		return now
	},
	Format: formatDecimal,
}

UnixNumbering numbers migrations with the current unix time

Functions

func IncrementingCounter

func IncrementingCounter(ins *FOFM) error

IncrementingCounter names new migrations with a counter that is padded to five digits instead of a time

func MigrationFileNameTime

func MigrationFileNameTime(name string) (timestamp time.Time, err error)

func MigrationNameParts

func MigrationNameParts(name string) (timestamp time.Time, direction string, err error)

func UnixTimestamps

func UnixTimestamps(ins *FOFM) error

UnixTimestamps is the default. New migrations are named with the current unix time

Types

type FOFM

type FOFM struct {
	DB             Store
	Migration      MigrationManager
	UpMigrations   MigrationStack
	DownMigrations MigrationStack

	// FS is where new migrations are written. Unless a Setting sets it, it is the directory
	// that the migration manager is defined in
	FS WriteFS

	// PackageName is the package that new migrations are in. Unless a Setting sets it, it
	// is read from the Go files that are beside the new migration
	PackageName string

	// Numbering is how new migrations are numbered. It is UnixTimestamps unless a Setting
	// changes it
	Numbering Numbering
	// contains filtered or unexported fields
}

func New

func New(db Store, migrationInstance MigrationManager, settings ...Setting) (*FOFM, error)

New will creae a new instance of FOFM. It will apply the DefaultSettings which can be overwritten by passing in settings.

The migration instance is a struct that has Migrations embedded in it and the migration methods on it. It can be a value or a pointer. Pass a pointer if the migration methods are defined with pointer receivers. It does not need any other methods, new migrations are written to the package that it is defined in.

func (*FOFM) ClearStore

func (m *FOFM) ClearStore() error

func (*FOFM) Down

func (m *FOFM) Down(name string) error

Down is DownContext with a context that is never cancelled

func (*FOFM) DownContext

func (m *FOFM) DownContext(ctx context.Context, name string) error

DownContext will run all migrations, in reverse order, up to and including the named one passed in. The name can be the full migration name (Migration_1_down), a partial name (Migration_1), or just the integer (1). Only migrations that are currently applied are run, so one that was never run, or has already been downed, is skipped. An error is returned if there is no down migration with that name. See LatestContext for how the context is used

func (*FOFM) Latest

func (m *FOFM) Latest() error

Latest is LatestContext with a context that is never cancelled

func (*FOFM) LatestContext

func (m *FOFM) LatestContext(ctx context.Context) error

LatestContext will run every up migration that has not been run yet. Where it picks up from depends on the last successful run:

  • nothing has been run: every up migration is run
  • an up migration was the last: everything after it is run, so nothing happens if it was the latest migration
  • a down migration was the last: it and everything after it is run again

A migration that failed is not a successful run, so it is attempted again. Pending returns the migrations that this will run.

The context is checked before each migration is started and it is passed to the migrations that accept one. If it is cancelled, the remaining migrations are not run and the context's error is returned. A migration that is already running is never interrupted by fofm, it is up to the migration to watch its context.

func (*FOFM) Pending

func (m *FOFM) Pending() (MigrationStack, error)

Pending returns the up migrations that Latest would run right now, in the order that it would run them. Nothing is run

func (*FOFM) Status

func (m *FOFM) Status() (MigrationSetStatus, error)

Status returns a list of all migrations and all of the times when they've been run since migrations can be run mulitple times

func (*FOFM) Up

func (m *FOFM) Up(name string) error

Up is UpContext with a context that is never cancelled

func (*FOFM) UpContext

func (m *FOFM) UpContext(ctx context.Context, name string) error

UpContext will run all migrations, in order, up to and inclduing the named one passed in. The name can be the full migration name (Migration_1_up), a partial name (Migration_1), or just the integer (1). Migrations that are already applied are skipped. An error is returned if there is no up migration with that name. See LatestContext for how the context is used

type Locker

type Locker interface {
	// Lock waits until it has the lock or the context is done. The returned function
	// releases the lock. A lock that is never released, because its owner crashed, must
	// eventually expire so that it does not block migrations forever
	Lock(ctx context.Context) (unlock func() error, err error)
}

Locker is an optional interface for a Store. If the store has a lock, fofm holds it while it runs migrations so that only one copy of an app is migrating at a time. The store is still usable without one, but then it is up to you to make sure that two copies of an app do not migrate at the same time

type Migration

type Migration struct {
	ID        int       `json:"id"`
	Name      string    `json:"name"`
	Direction string    `json:"direction"`
	Status    string    `json:"status"`
	Error     string    `json:"error"`
	Timestamp time.Time `json:"timestamp"`
	Created   time.Time `json:"created"`
	// contains filtered or unexported fields
}

func (Migration) BaseName

func (m Migration) BaseName() string

BaseName is the migration's name without its direction, so Migration_1_up and Migration_1_down are both Migration_1. It is what ties an up to its down

func (*Migration) CreatedFromString

func (m *Migration) CreatedFromString(timeStr string) error

func (Migration) Is

func (m Migration) Is(direction string) bool

func (Migration) MigrationTime

func (m Migration) MigrationTime() time.Time

MigrationTime is the time that is encoded in the migration's name. It is what migrations are ordered by. A migration that was read from the store has a Timestamp of when it was run, which is a different thing, so the name is preferred

func (*Migration) Scan

func (m *Migration) Scan() []any

func (*Migration) TimestampFromString

func (m *Migration) TimestampFromString(timeStr string) error

type MigrationManager

type MigrationManager interface {
	// contains filtered or unexported methods
}

MigrationManager is a struct that has fofm.Migrations embedded in it. It is what New takes. Anything else, like a database connection that was passed in by mistake, is a compile error instead of a manager that quietly has no migrations.

type MigrationSet

type MigrationSet []Migration

func (MigrationSet) ToRuns

func (m MigrationSet) ToRuns() []Run

type MigrationSetStatus

type MigrationSetStatus struct {
	Migrations []Status `json:"migration_statuses"`
	// contains filtered or unexported fields
}

type MigrationStack

type MigrationStack []Migration

func (*MigrationStack) Add

func (m *MigrationStack) Add(name, direction string, timestamp time.Time) error

func (MigrationStack) After

func (m MigrationStack) After(after *Migration) MigrationStack

After returns every migration whose time is later than the one passed in. The time is read from the name of the migration that is passed in, because that is what the stack is ordered by. A nil migration returns the whole stack

func (MigrationStack) BeforeName

func (m MigrationStack) BeforeName(name string) MigrationStack

BeforeName returns every migration from the start of the stack up to and including the named one. It returns an empty stack when there isn't a migration with that name

func (MigrationStack) Find

func (m MigrationStack) Find(name string) *Migration

Find returns the migration that the name refers to or nil if there isn't one. The name can be the full migration name, like Migration_1_up, the name without a direction, like Migration_1, or just the integer, like 1. The integer is compared as a number, so 2 finds Migration_00002_up. Direction is decided by the stack, so Migration_1_down will never find anything in a stack of up migrations

func (MigrationStack) First

func (m MigrationStack) First() *Migration

func (MigrationStack) From

func (m MigrationStack) From(from *Migration) MigrationStack

From is like After, but it also includes the migration that is passed in

func (MigrationStack) Last

func (m MigrationStack) Last() *Migration

func (MigrationStack) Names

func (m MigrationStack) Names() []string

func (MigrationStack) Order

func (m MigrationStack) Order()

func (MigrationStack) Reverse

func (m MigrationStack) Reverse()

type Migrations

type Migrations struct{}

Migrations is embedded in the struct that has the migrations on it. It is what marks the struct as a migration manager, so that New will only take a struct that was meant to be one. It has no fields and nothing to set up.

type MyMigrations struct {
	fofm.Migrations
	DB *sql.DB
}

func (m *MyMigrations) Migration_1_up() error { ... }
func (m *MyMigrations) Migration_1_down() error { ... }

An embedded struct has no way to see the struct that it is in, so it does not find the migrations. New does that by looking at the methods of the struct that it is given.

type NoResultsError

type NoResultsError struct {
	OriginalError error
	// contains filtered or unexported fields
}

NoResultsError should be used in place of a store's no results error

func (NoResultsError) Error

func (re NoResultsError) Error() string

type Numbering

type Numbering struct {
	// Next returns the number for the next migration. taken is the number of every
	// migration that already exists, from lowest to highest. The result must not be one of
	// them, because two migrations can not share a number
	Next func(taken []int64) int64

	// Format is how the number is written in the migration's name and in the name of its
	// file. It has to be digits, since that is what a migration's name is read as. If it is
	// not set, the number is written as it is
	Format func(number int64) string
}

Numbering decides the number in the name of a new migration, like the 1658164360 in Migration_1658164360_up. Migrations run in the order of their numbers.

type Run

type Run struct {
	Timestamp time.Time `json:"timestamp"`
	Status    string    `json:"status"`
	// contains filtered or unexported fields
}

type SQLite

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

func NewSQLite

func NewSQLite(filepath string) (*SQLite, error)

func NewSQLiteWithTableName

func NewSQLiteWithTableName(filepath, tablename string) (*SQLite, error)

func (*SQLite) ClearStore

func (s *SQLite) ClearStore() error

func (*SQLite) Close

func (s *SQLite) Close() error

func (*SQLite) Connect

func (s *SQLite) Connect() error

func (*SQLite) CreateStore

func (s *SQLite) CreateStore() error

func (*SQLite) GetAllByName

func (s *SQLite) GetAllByName(name string) (MigrationSet, error)

func (*SQLite) LastRun

func (s *SQLite) LastRun() (*Migration, error)

func (*SQLite) LastRunByName

func (s *SQLite) LastRunByName(name string) (*Migration, error)

func (*SQLite) LastStatusRun

func (s *SQLite) LastStatusRun(status string) (*Migration, error)

func (*SQLite) List

func (s *SQLite) List() (MigrationSet, error)

func (*SQLite) Lock

func (s *SQLite) Lock(ctx context.Context) (func() error, error)

Lock takes the migration lock. Each call has its own owner, so it also keeps two callers in the same process apart. The lock is renewed in the background while it is held and a lock that has not been renewed for the TTL is taken over, so a process that crashes while holding it does not block the others forever

func (*SQLite) Save

func (s *SQLite) Save(current Migration, err error) error

func (*SQLite) SetBusyTimeout

func (s *SQLite) SetBusyTimeout(timeout time.Duration) error

SetBusyTimeout changes how long a query waits for another process that has the database file locked before it gives up. The default is five seconds. A context that ends while a query is waiting is not noticed until the wait is over, so this is also the longest that a cancelled Lock can take to return when another process is writing to the file

func (*SQLite) SetLockTTL

func (s *SQLite) SetLockTTL(ttl time.Duration)

SetLockTTL changes how long a lock can go without being renewed before another process takes it over. A lock that is held is renewed three times per TTL. Call this before the store is passed to New

type Setting

type Setting func(ins *FOFM) error

func WithMigrationsDir

func WithMigrationsDir(dir string) Setting

WithMigrationsDir writes new migrations to a directory. This is not needed in most cases, because the directory is worked out from where the migration manager is defined. It is for when that can not be done: a manager that has no methods yet, or a program that was built with -trimpath. The directory has to be the package of the manager

func WithMigrationsFS

func WithMigrationsFS(fsys WriteFS) Setting

WithMigrationsFS writes new migrations to any WriteFS, like one in memory. The files in it are read to find the package name and the numbers that are already used

func WithNumbering

func WithNumbering(numbering Numbering) Setting

WithNumbering names new migrations with your own Numbering

func WithPackageName

func WithPackageName(name string) Setting

WithPackageName sets the package for new migrations. Without it, the package is read from the Go files that the migrations are written beside

type Status

type Status struct {
	Migration Migration `json:"migration"`
	Runs      []Run     `json:"runs"`
	// contains filtered or unexported fields
}

type Store

type Store interface {
	// Connect will connect to the store
	// it is automatcically called by FOFM
	Connect() error

	// Close will close any connections related to the store
	Close() error

	// CreateStore should do the work of creating
	// the storage for the migrations. It
	// should be a "create if doesnt exist" type
	// operation
	CreateStore() error

	// ClearStore should reset the store to an empty state
	ClearStore() error

	// LastRun will return the last run migration
	LastRun() (*Migration, error)

	// LastStatusRun will get the last run with the
	// provided status
	LastStatusRun(status string) (*Migration, error)

	// LastRunByName will get the last run with the
	// provided name
	LastRunByName(name string) (*Migration, error)

	// GetAllByName will return all migrations with the
	// provided name
	GetAllByName(name string) (MigrationSet, error)

	// List will return a list of all migrations that
	// have been saved to the store
	List() (MigrationSet, error)

	// Save should insert a new record
	Save(current Migration, err error) error
}

Jump to

Keyboard shortcuts

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