migrate/migrate.go

100 lines
2.2 KiB
Go

// Package migrate allows you to update your database from your application
package migrate
import (
"database/sql"
"errors"
"fmt"
"strconv"
)
// Options contains all settings
type Options struct {
TableName string // Name used for version info table; defaults to DefaultTableName if not set
Schema string // Schema used for version info table; For PostgreSQL, ignored if not set
AssetPrefix string
}
// DefaultTableName is the name used when no TableName is specified in Options
const DefaultTableName = `version`
// ErrUpdatesMissing indicates an update is missing, making it impossible to execute the migration
var ErrUpdatesMissing = errors.New(`Missing migration files`)
const fileFormat = `%04d.sql`
// AssetFunc is a function that returns the data for the given name
type AssetFunc func(string) ([]byte, error)
// Migrate executes migrations to get to the desired version
// Downgrading is not supported as it could result in data loss
func Migrate(db *sql.DB, version int, o Options, asset AssetFunc) error {
if o.TableName == `` {
o.TableName = DefaultTableName
}
var err error
searchPath := `public`
_ = db.QueryRow(`SHOW search_path`).Scan(&searchPath)
if o.Schema != `` {
_, _ = db.Exec(`CREATE SCHEMA IF NOT EXISTS ` + o.Schema)
_, err = db.Exec(`SET search_path TO ` + o.Schema)
if err != nil {
return err
}
}
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.Exec(`CREATE TABLE IF NOT EXISTS ` + o.TableName + ` (Version integer NOT NULL PRIMARY KEY)`)
if err != nil {
return err
}
row := tx.QueryRow(`SELECT Version FROM ` + o.TableName + ` ORDER BY Version DESC`)
var v int
err = row.Scan(&v)
if err != sql.ErrNoRows && err != nil {
return err
}
for i := v + 1; i <= version; i++ {
script, err := asset(fmt.Sprintf(o.AssetPrefix+fileFormat, i))
if err != nil {
return ErrUpdatesMissing
}
_, err = tx.Exec(string(script))
if err != nil {
return err
}
_, err = tx.Exec(`INSERT INTO ` + o.TableName + ` VALUES (` + strconv.Itoa(i) + `)`)
if err != nil {
return err
}
}
if o.Schema != `` {
_, err = tx.Exec(`SET search_path TO ` + searchPath)
if err != nil {
return err
}
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}