Skip to content

Commit

Permalink
Support setting custom table name (#16)
Browse files Browse the repository at this point in the history
Fixes #11.
  • Loading branch information
markuswustenberg authored Jul 5, 2021
1 parent 711f2e2 commit 275bddd
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 16 deletions.
47 changes: 32 additions & 15 deletions migrate.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Package migrate provides a simple Migrator that can migrate databases.
// Up and Down are one-liner convenience functions.
// Package migrate provides simple migration functions Up, Down, and To, as well as a Migrator.
// Up, Down, and To are one-liner convenience functions that use default Options.
// If you need custom Options, use New.
package migrate

import (
Expand All @@ -12,8 +13,9 @@ import (
)

var (
upMatcher = regexp.MustCompile(`^([\w-]+).up.sql$`)
downMatcher = regexp.MustCompile(`^([\w-]+).down.sql`)
upMatcher = regexp.MustCompile(`^([\w-]+).up.sql$`)
downMatcher = regexp.MustCompile(`^([\w-]+).down.sql`)
tableMatcher = regexp.MustCompile(`^[\w]+$`)
)

// Up from the current version.
Expand All @@ -35,20 +37,35 @@ func To(ctx context.Context, db *sql.DB, fsys fs.FS, version string) error {
}

type Migrator struct {
db *sql.DB
fs fs.FS
db *sql.DB
fs fs.FS
table string
}

// Options for New. DB and FS are always required.
type Options struct {
DB *sql.DB
FS fs.FS
DB *sql.DB
FS fs.FS
Table string
}

// New Migrator with Options.
// If Options.Table is not set, defaults to "migrations". The table name must match ^[\w]+$ .
// New panics on illegal options.
func New(opts Options) *Migrator {
if opts.DB == nil || opts.FS == nil {
panic("DB and FS must be set")
}
if opts.Table == "" {
opts.Table = "migrations"
}
if !tableMatcher.MatchString(opts.Table) {
panic("illegal table name " + opts.Table + ", must match " + tableMatcher.String())
}
return &Migrator{
db: opts.DB,
fs: opts.FS,
db: opts.DB,
fs: opts.FS,
table: opts.Table,
}
}

Expand Down Expand Up @@ -203,7 +220,7 @@ func (m *Migrator) apply(ctx context.Context, name, version string) error {
return m.inTransaction(ctx, func(tx *sql.Tx) error {
// Normally we wouldn't just string interpolate the version like this,
// but because we know the version has been matched against the regexes, we know it's safe.
if _, err := tx.ExecContext(ctx, `update migrations set version = '`+version+`'`); err != nil {
if _, err := tx.ExecContext(ctx, `update `+m.table+` set version = '`+version+`'`); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, string(content)); err != nil {
Expand Down Expand Up @@ -233,17 +250,17 @@ func (m *Migrator) getFilenames(matcher *regexp.Regexp) ([]string, error) {
// createMigrationsTable if it does not exist already, and insert the empty version if it's empty.
func (m *Migrator) createMigrationsTable(ctx context.Context) error {
return m.inTransaction(ctx, func(tx *sql.Tx) error {
if _, err := tx.ExecContext(ctx, `create table if not exists migrations (version text not null)`); err != nil {
if _, err := tx.ExecContext(ctx, `create table if not exists `+m.table+` (version text not null)`); err != nil {
return err
}

var exists bool
if err := tx.QueryRowContext(ctx, `select exists (select * from migrations)`).Scan(&exists); err != nil {
if err := tx.QueryRowContext(ctx, `select exists (select * from `+m.table+`)`).Scan(&exists); err != nil {
return err
}

if !exists {
if _, err := tx.ExecContext(ctx, `insert into migrations values ('')`); err != nil {
if _, err := tx.ExecContext(ctx, `insert into `+m.table+` values ('')`); err != nil {
return err
}
}
Expand All @@ -254,7 +271,7 @@ func (m *Migrator) createMigrationsTable(ctx context.Context) error {
// getCurrentVersion from the migrations table.
func (m *Migrator) getCurrentVersion(ctx context.Context) (string, error) {
var version string
if err := m.db.QueryRowContext(ctx, `select version from migrations`).Scan(&version); err != nil {
if err := m.db.QueryRowContext(ctx, `select version from `+m.table+``).Scan(&version); err != nil {
return "", err
}
return version, nil
Expand Down
56 changes: 55 additions & 1 deletion migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,60 @@ func TestMigrator(t *testing.T) {
is.True(err != nil)
is.Equal("error finding version doesnotexist", err.Error())
})

t.Run("supports custom table name", func(t *testing.T) {
db, cleanup := test.createDatabase(t)
defer cleanup()
is := is.New(t)

m := migrate.New(migrate.Options{DB: db, FS: mustSub(t, testdata, "good"), Table: "migrations2"})
err := m.MigrateUp(context.Background())
is.NoErr(err)

var version string
err = db.QueryRow(`select version from migrations2`).Scan(&version)
is.NoErr(err)
is.Equal("3", version)
})
})
}
}

func TestNew(t *testing.T) {
t.Run("panics on bad table name", func(t *testing.T) {
is := is.New(t)

defer func() {
err := recover()
is.True(err != nil)
is.Equal(`illegal table name +, must match ^[\w]+$`, err)
}()
migrate.New(migrate.Options{DB: &sql.DB{}, FS: fstest.MapFS{}, Table: "+"})
})

t.Run("panics on no db given", func(t *testing.T) {
is := is.New(t)

defer func() {
err := recover()
is.True(err != nil)
is.Equal(`DB and FS must be set`, err)
}()
migrate.New(migrate.Options{FS: fstest.MapFS{}})
})

t.Run("panics on no fs given", func(t *testing.T) {
is := is.New(t)

defer func() {
err := recover()
is.True(err != nil)
is.Equal(`DB and FS must be set`, err)
}()
migrate.New(migrate.Options{DB: &sql.DB{}})
})
}

var migrations = os.DirFS("testdata/example")

func Example() {
Expand Down Expand Up @@ -287,7 +337,7 @@ func createPostgresDatabase(t *testing.T) (*sql.DB, func()) {
t.FailNow()
}
return db, func() {
if _, err := db.Exec(`drop table if exists migrations; drop table if exists test`); err != nil {
if _, err := db.Exec(`drop table if exists migrations; drop table if exists migrations2; drop table if exists test`); err != nil {
t.Log(err)
t.FailNow()
}
Expand Down Expand Up @@ -324,6 +374,10 @@ func createMariaDatabase(t *testing.T) (*sql.DB, func()) {
t.Log(err)
t.FailNow()
}
if _, err := db.Exec(`drop table if exists migrations2`); err != nil {
t.Log(err)
t.FailNow()
}
if _, err := db.Exec(`drop table if exists test`); err != nil {
t.Log(err)
t.FailNow()
Expand Down

0 comments on commit 275bddd

Please sign in to comment.