Files
QuoteForge/internal/models/sql_migrations_test.go
T

57 lines
1.7 KiB
Go

package models
import (
"path/filepath"
"testing"
"testing/fstest"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
)
func TestSQLMigrationStatusAndListing(t *testing.T) {
migrations := fstest.MapFS{
"002_b.sql": {Data: []byte("ALTER TABLE x ADD COLUMN b INT;")},
"001_a.sql": {Data: []byte("ALTER TABLE x ADD COLUMN a INT;")},
"006_local_only_versions.sql": {Data: []byte("-- sqlite only")},
"README.md": {Data: []byte("not a migration")},
}
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "m.db")), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
// No history table yet: everything pending, nothing created.
states, err := SQLMigrationStatus(db, migrations)
if err != nil {
t.Fatal(err)
}
if len(states) != 2 || states[0].Filename != "001_a.sql" || states[1].Filename != "002_b.sql" {
t.Fatalf("unexpected listing %+v", states)
}
if states[0].AppliedAt != nil || db.Migrator().HasTable(&SQLSchemaMigration{}) {
t.Fatal("status must be read-only and report pending")
}
if err := db.AutoMigrate(&SQLSchemaMigration{}); err != nil {
t.Fatal(err)
}
if err := db.Create(&SQLSchemaMigration{Filename: "001_a.sql"}).Error; err != nil {
t.Fatal(err)
}
states, _ = SQLMigrationStatus(db, migrations)
if states[0].AppliedAt == nil || states[1].AppliedAt != nil {
t.Fatalf("want 001 applied, 002 pending: %+v", states)
}
}
func TestSplitSQLStatementsSkipsComments(t *testing.T) {
got, err := splitSQLStatements("-- header; with semicolon\nALTER TABLE a ADD COLUMN x INT;\n\nALTER TABLE b\n ADD COLUMN y INT;\n")
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[1] != "ALTER TABLE b\n ADD COLUMN y INT" {
t.Fatalf("unexpected statements %q", got)
}
}