xormigrate

package module
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2023 License: MIT Imports: 7 Imported by: 5

README

Xormigrate

Go Report Card GoDoc

Supported databases

It supports any of the databases Xorm supports:

Installing

go get -u src.techknowlogick.com/xormigrate

Usage

package main

import (
	"log"

	"src.techknowlogick.com/xormigrate"

	"xorm.io/xorm"
	_ "github.com/mattn/go-sqlite3"
)

func main() {
	db, err := xorm.NewEngine("sqlite3", "mydb.sqlite3")
	if err != nil {
		log.Fatal(err)
	}

	m := xormigrate.New(db, []*xormigrate.Migration{
		// create persons table
		{
			ID: "201608301400",
			// An optional description to print out to the Xormigrate logger
			Description: "Create the Person table",
			Migrate: func(tx *xorm.Engine) error {
				// it's a good pratice to copy the struct inside the function,
				// so side effects are prevented if the original struct changes during the time
				type Person struct {
					Name string
				}
				return tx.Sync2(&Person{})
			},
			Rollback: func(tx *xorm.Engine) error {
				return tx.DropTables(&Person{})
			},
		},
		// add age column to persons
		{
			ID: "201608301415",
			Migrate: func(tx *xorm.Engine) error {
				// when table already exists, it just adds fields as columns
				type Person struct {
					Age int
				}
				return tx.Sync2(&Person{})
			},
			Rollback: func(tx *xorm.Engine) error {
				// Note: Column dropping in sqlite is not support, and you will need to do this manually
				_, err = tx.Exec("ALTER TABLE person DROP COLUMN age")
				if err != nil {
					return fmt.Errorf("Drop column failed: %v", err)
				}
				return nil
			},
		},
		// add pets table
		{
			ID: "201608301430",
			Migrate: func(tx *xorm.Engine) error {
				type Pet struct {
					Name     string
					PersonID int
				}
				return tx.Sync2(&Pet{})
			},
			Rollback: func(tx *xorm.Engine) error {
				return tx.DropTables(&Pet{})
			},
		},
	})

	if err = m.Migrate(); err != nil {
		log.Fatalf("Could not migrate: %v", err)
	}
	log.Printf("Migration did run successfully")
}

Having a separated function for initializing the schema

If you have a lot of migrations, it can be a pain to run all them, as example, when you are deploying a new instance of the app, in a clean database. To prevent this, you can set a function that will run if no migration was run before (in a new clean database). Remember to create everything here, all tables, foreign keys and what more you need in your app.

type Person struct {
	Name string
	Age int
}

type Pet struct {
	Name     string
	PersonID int
}

m := xormigrate.New(db, []*xormigrate.Migration{
    // your migrations here
})

m.InitSchema(func(tx *xorm.Engine) error {
	err := tx.sync2(
		&Person{},
		&Pet{},
		// all other tables of your app
	)
	if err != nil {
		return err
	}
	return nil
})

Adding migration descriptions to your logging

Xormigrate's logger defaults to stdout, but it can be changed to suit your needs.

m := xormigrate.New(db, []*xormigrate.Migration{
    // your migrations here
})

// Don't log anything
m.NilLogger() 

// This is the default logger
// No need to initialize this unless it was changed
// [xormigrate] message
m.DefaultLogger()

// Or, create a logger with any io.Writer you want
m.NewLogger(os.Stdout)

Credits

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRollbackImpossible is returned when trying to rollback a migration
	// that has no rollback function.
	ErrRollbackImpossible = errors.New("xormigrate: It's impossible to rollback this migration")

	// ErrNoMigrationDefined is returned when no migration is defined.
	ErrNoMigrationDefined = errors.New("xormigrate: No migration defined")

	// ErrMissingID is returned when the ID od migration is equal to ""
	ErrMissingID = errors.New("xormigrate: Missing ID in migration")

	// ErrNoRunMigration is returned when any run migration was found while
	// running RollbackLast
	ErrNoRunMigration = errors.New("xormigrate: Could not find last run migration")

	// ErrMigrationIDDoesNotExist is returned when migrating or rolling back to a migration ID that
	// does not exist in the list of migrations
	ErrMigrationIDDoesNotExist = errors.New("xormigrate: Tried to migrate to an ID that doesn't exist")
)

Functions

This section is empty.

Types

type DuplicatedIDError

type DuplicatedIDError struct {
	ID string
}

DuplicatedIDError is returned when more than one migration have the same ID

func (*DuplicatedIDError) Error

func (e *DuplicatedIDError) Error() string

type InitSchemaFunc

type InitSchemaFunc func(*xorm.Engine) error

InitSchemaFunc is the func signature for initializing the schema.

type LoggerInterface

type LoggerInterface interface {
	Debug(v ...interface{})
	Debugf(format string, v ...interface{})
	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Warn(v ...interface{})
	Warnf(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
}

type MigrateFunc

type MigrateFunc func(*xorm.Engine) error

MigrateFunc is the func signature for migrating.

type MigrateFuncSession added in v1.7.0

type MigrateFuncSession func(*xorm.Session) error

MigrateFuncSession is the func signature for migrating using xorm.Session.

type Migration

type Migration struct {
	// ID is the migration identifier. Usually a timestamp like "201601021504".
	ID string `xorm:"id"`
	// Description is the migration description, which is optionally printed out when the migration is ran.
	Description string
	// Migrate is a function that will be executed while running this migration.
	Migrate MigrateFunc `xorm:"-"`
	// Rollback will be executed on rollback. Can be nil.
	Rollback RollbackFunc `xorm:"-"`
	// MigrateSession is a function that will be executed while running this migration, using xorm.Session.
	MigrateSession MigrateFuncSession `xorm:"-"`
	// RollbackSession will be executed on rollback, using xorm.Session. Can be nil.
	RollbackSession RollbackFuncSession `xorm:"-"`
	// Long marks the migration an non-required migration that will likely take a long time. Must use Xormigrate.AllowLong() to be enabled.
	Long bool `xorm:"-"`
}

Migration represents a database migration (a modification to be made on the database).

type ReservedIDError

type ReservedIDError struct {
	ID string
}

ReservedIDError is returned when a migration is using a reserved ID

func (*ReservedIDError) Error

func (e *ReservedIDError) Error() string

type RollbackFunc

type RollbackFunc func(*xorm.Engine) error

RollbackFunc is the func signature for rollbacking.

type RollbackFuncSession added in v1.7.0

type RollbackFuncSession func(*xorm.Session) error

RollbackFuncSession is the func signature for rollbacking using xorm.Session.

type Xormigrate

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

Xormigrate represents a collection of all migrations of a database schema.

func New

func New(db *xorm.Engine, migrations []*Migration) *Xormigrate

New returns a new Xormigrate.

func (*Xormigrate) AllowLong added in v1.6.0

func (x *Xormigrate) AllowLong(allow ...bool)

AllowLong enables migrations that are marked as probably long-running.

func (*Xormigrate) DefaultLogger

func (x *Xormigrate) DefaultLogger()

DefaultLogger sets a Xormigrate logger with default settings e.g. "xormigrate message"

func (*Xormigrate) InitSchema

func (x *Xormigrate) InitSchema(initSchema InitSchemaFunc)

InitSchema sets a function that is run if no migration is found. The idea is preventing to run all migrations when a new clean database is being migratinx. In this function you should create all tables and foreign key necessary to your application.

func (*Xormigrate) Migrate

func (x *Xormigrate) Migrate() error

Migrate executes all migrations that did not run yet.

func (*Xormigrate) MigrateTo

func (x *Xormigrate) MigrateTo(migrationID string) error

MigrateTo executes all migrations that did not run yet up to the migration that matches `migrationID`.

func (*Xormigrate) NewLogger

func (x *Xormigrate) NewLogger(writer io.Writer)

NewLogger sets a Xormigrate logger with a specified io.Writer

func (*Xormigrate) NilLogger

func (x *Xormigrate) NilLogger()

NilLogger sets a Xormigrate logger that discards all messages

func (*Xormigrate) RollbackLast

func (x *Xormigrate) RollbackLast() error

RollbackLast undo the last migration

func (*Xormigrate) RollbackMigration

func (x *Xormigrate) RollbackMigration(m *Migration) error

RollbackMigration undo a migration.

func (*Xormigrate) RollbackTo

func (x *Xormigrate) RollbackTo(migrationID string) error

RollbackTo undoes migrations up to the given migration that matches the `migrationID`. Migration with the matching `migrationID` is not rolled back.

func (*Xormigrate) SetLogger

func (x *Xormigrate) SetLogger(l LoggerInterface)

SetLogger sets the Xormigrate logger

type XormigrateLogger

type XormigrateLogger struct {
	*log.Logger
}

func (*XormigrateLogger) Debug

func (l *XormigrateLogger) Debug(v ...interface{})

Debug prints a Debug message

func (*XormigrateLogger) Debugf

func (l *XormigrateLogger) Debugf(format string, v ...interface{})

Debugf prints a formatted Debug message

func (*XormigrateLogger) Error

func (l *XormigrateLogger) Error(v ...interface{})

Error prints an Error message

func (*XormigrateLogger) Errorf

func (l *XormigrateLogger) Errorf(format string, v ...interface{})

Errorf prints a formatted Error message

func (*XormigrateLogger) Info

func (l *XormigrateLogger) Info(v ...interface{})

Info prints an Info message

func (*XormigrateLogger) Infof

func (l *XormigrateLogger) Infof(format string, v ...interface{})

Infof prints a formatted Info message

func (*XormigrateLogger) Warn

func (l *XormigrateLogger) Warn(v ...interface{})

Warn prints a Warning message

func (*XormigrateLogger) Warnf

func (l *XormigrateLogger) Warnf(format string, v ...interface{})

Warnf prints a formatted Warning message

Jump to

Keyboard shortcuts

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