2024-11-06 22:16:17 +00:00
|
|
|
package litemigrate_test
|
2024-09-27 23:04:07 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"github.com/stretchr/testify/assert"
|
2024-11-06 22:16:17 +00:00
|
|
|
"lmika.dev/pkg/litemigrate"
|
2024-09-27 23:04:07 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"testing"
|
|
|
|
"testing/fstest"
|
|
|
|
|
|
|
|
_ "modernc.org/sqlite"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestMigrator_MigrateUp(t *testing.T) {
|
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
db, closeFn := newDB(t)
|
|
|
|
defer closeFn()
|
|
|
|
|
|
|
|
fileMigrated := make([]string, 0)
|
2024-11-06 22:16:17 +00:00
|
|
|
migrator := litemigrate.New(testMigration, db, litemigrate.WithPreStepHook(func(filename string) {
|
2024-09-27 23:04:07 +00:00
|
|
|
fileMigrated = append(fileMigrated, filename)
|
|
|
|
}))
|
|
|
|
|
|
|
|
// Check initial version
|
|
|
|
ver, err := migrator.Version(ctx)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, 0, ver)
|
|
|
|
|
|
|
|
// Run migration
|
|
|
|
err = migrator.MigrateUp(ctx)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, []string{"01_base_schema.up.sql", "02_insert_things.up.sql"}, fileMigrated)
|
|
|
|
|
|
|
|
// Check new version
|
|
|
|
ver, err = migrator.Version(ctx)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, 2, ver)
|
|
|
|
|
|
|
|
// Verify that migration worked
|
|
|
|
var some string
|
|
|
|
row := db.QueryRow(`SELECT some FROM thing LIMIT 1`)
|
|
|
|
err = row.Scan(&some)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, "bla", some)
|
|
|
|
|
|
|
|
fileMigrated = make([]string, 0)
|
|
|
|
|
|
|
|
// Check that running migration nops
|
|
|
|
err = migrator.MigrateUp(ctx)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, []string{}, fileMigrated)
|
|
|
|
|
|
|
|
ver, err = migrator.Version(ctx)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.Equal(t, 2, ver)
|
|
|
|
}
|
|
|
|
|
|
|
|
func newDB(t *testing.T) (*sql.DB, func()) {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
tmpDir, err := os.MkdirTemp("", "")
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("cannot create mkdir: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
drvr, err := sql.Open("sqlite", filepath.Join(tmpDir, "test.db"))
|
|
|
|
if err != nil {
|
|
|
|
t.Errorf("cannot open driver: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return drvr, func() {
|
|
|
|
drvr.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var testMigration = fstest.MapFS{
|
|
|
|
"01_base_schema.up.sql": {
|
|
|
|
Data: []byte(`
|
|
|
|
CREATE TABLE thing (some text);
|
|
|
|
`),
|
|
|
|
},
|
|
|
|
"02_insert_things.up.sql": {
|
|
|
|
Data: []byte(`
|
|
|
|
INSERT INTO thing (some) VALUES ("bla");
|
|
|
|
`),
|
|
|
|
},
|
|
|
|
}
|