Files
pages/internal/db/migration_runner_test.go
T
Anya Tokugawa d5d21b7841
Build and publish container images / images (push) Successful in 9m34s
Release container images / release (push) Successful in 36s
Refactor architecture into eight components and consolidate reliability work
Extract Grammaratur, Dregarnuhr, Geduldh, Mestionora, Ordoschnellic, Schutzaria, Kunstzeal and Seheweit behind compatible application contracts.

Include accumulated editor resilience, navigation and theme UX, remote CLI, storage/schema and DR groundwork, tests and design/operations documentation.

Verified: uncached full Go suite; go vet ./...; race tests for all eight components; 11 targeted Chromium tests; Node suites; 19 Python CLI tests; reproducible editor build. No push, release tag or deployment in this checkpoint.
2026-11-01 15:23:31 +09:00

151 lines
5.8 KiB
Go

package db
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"path/filepath"
"strings"
"sync"
"testing"
)
func TestSQLMigrationLedgerConcurrencyAndChecksum(t *testing.T) {
database, err := Open(filepath.Join(t.TempDir(), "migration.db"))
if err != nil {
t.Fatal(err)
}
defer database.Close()
steps := []SQLMigration{{Version: 1, Name: "initial", Statements: []string{`CREATE TABLE sample (id INTEGER PRIMARY KEY)`, `INSERT INTO sample VALUES (1)`}}}
var wg sync.WaitGroup
errors := make(chan error, 6)
for i := 0; i < 6; i++ {
wg.Add(1)
go func() {
defer wg.Done()
errors <- ApplySQLiteMigrations(context.Background(), database, "test", steps)
}()
}
wg.Wait()
close(errors)
for err := range errors {
if err != nil {
t.Fatal(err)
}
}
var count int
if err := database.QueryRow(`SELECT count(*) FROM sample`).Scan(&count); err != nil || count != 1 {
t.Fatalf("count=%d err=%v", count, err)
}
changed := []SQLMigration{{Version: 1, Name: "initial", Statements: []string{`CREATE TABLE sample (id TEXT)`}}}
if err := ApplySQLiteMigrations(context.Background(), database, "test", changed); err == nil || !strings.Contains(err.Error(), "history mismatch") {
t.Fatalf("changed migration accepted: %v", err)
}
if err := ApplySQLiteMigrations(context.Background(), database, "test", nil); err == nil {
t.Fatal("downgrade accepted")
}
if err := ApplySQLiteMigrations(context.Background(), database, "other", []SQLMigration{{Version: 2, Name: "gap", Statements: []string{`SELECT 1`}}}); err == nil {
t.Fatal("version gap accepted")
}
}
func TestSQLMigrationFailureRollsBackDDLAndLedger(t *testing.T) {
database, err := Open(filepath.Join(t.TempDir(), "migration.db"))
if err != nil {
t.Fatal(err)
}
defer database.Close()
steps := []SQLMigration{{Version: 1, Name: "broken", Statements: []string{`CREATE TABLE partial (id INTEGER)`, `NOT VALID SQL`}}}
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err == nil {
t.Fatal("DDL failure ignored")
}
var count int
if err := database.QueryRow(`SELECT count(*) FROM sqlite_master WHERE name IN ('partial','schema_migration_steps')`).Scan(&count); err != nil || count != 0 {
t.Fatalf("partial migration remains count=%d err=%v", count, err)
}
steps[0].Statements = steps[0].Statements[:1]
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err != nil {
t.Fatal("retry after rollback", err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if err := ApplySQLiteMigrations(ctx, database, "test", steps); err == nil {
t.Fatal("cancel ignored")
}
}
func TestLegacyRevisionHashMigrationSpansBoundedBatches(t *testing.T) {
database, err := Open(filepath.Join(t.TempDir(), "legacy.db"))
if err != nil {
t.Fatal(err)
}
defer database.Close()
if _, err := database.Exec(`CREATE TABLE revisions (uuid TEXT PRIMARY KEY,object_uuid TEXT,body TEXT,message TEXT)`); err != nil {
t.Fatal(err)
}
for i := 0; i < 260; i++ {
if _, err := database.Exec(`INSERT INTO revisions(uuid,body) VALUES(?,?)`, fmt.Sprintf("revision-%04d", i), "body"); err != nil {
t.Fatal(err)
}
}
if err := Migrate(database); err != nil {
t.Fatal(err)
}
var count int
if err := database.QueryRow(`SELECT count(*) FROM revisions WHERE length(document_hash)=64 AND lang='und' AND created_at_ms=0`).Scan(&count); err != nil || count != 260 {
t.Fatalf("migrated=%d err=%v", count, err)
}
if err := ensureSQLiteColumn(database, "does_not_exist", "created_at", "INTEGER"); err == nil {
t.Fatal("ALTER failure swallowed")
}
}
func TestMigrationChecksumPreservesLegacyFormat(t *testing.T) {
step := SQLMigration{Version: 1, Name: "legacy", Statements: []string{"SELECT 1"}}
sum := sha256.Sum256([]byte(`{"Version":1,"Name":"legacy","Statements":["SELECT 1"]}`))
if got := migrationChecksum(step); got != hex.EncodeToString(sum[:]) {
t.Fatalf("legacy checksum changed: %s", got)
}
}
func TestMigrationConditionalColumnsAndAssertionsAreAtomic(t *testing.T) {
database, err := Open(filepath.Join(t.TempDir(), "schema.db"))
if err != nil {
t.Fatal(err)
}
defer database.Close()
if _, err := database.Exec(`CREATE TABLE sample(id INTEGER PRIMARY KEY); INSERT INTO sample VALUES(1)`); err != nil {
t.Fatal(err)
}
steps := []SQLMigration{{Version: 1, Name: "adopt", AddColumns: []SQLiteColumn{{Table: "sample", Name: "value", Declaration: "TEXT NOT NULL DEFAULT ''"}}, Assertions: []string{`SELECT missing FROM sample LIMIT 0`}}}
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err == nil {
t.Fatal("invalid schema accepted")
}
var count int
if err := database.QueryRow(`SELECT count(*) FROM pragma_table_info('sample') WHERE name='value'`).Scan(&count); err != nil || count != 0 {
t.Fatalf("ALTER was not rolled back: %d %v", count, err)
}
steps[0].Assertions = []string{`SELECT id,value FROM sample LIMIT 0`}
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err != nil {
t.Fatal(err)
}
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err != nil {
t.Fatal("repeated apply", err)
}
var value string
if err := database.QueryRow(`SELECT value FROM sample WHERE id=1`).Scan(&value); err != nil || value != "" {
t.Fatalf("legacy row lost: %q %v", value, err)
}
steps = append(steps, SQLMigration{Version: 2, Name: "remove_value", Statements: []string{`ALTER TABLE sample DROP COLUMN value`}, Assertions: []string{`SELECT id FROM sample LIMIT 0`}})
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err != nil {
t.Fatal("new contract must supersede old contract", err)
}
if _, err := database.Exec(`DROP TABLE sample`); err != nil {
t.Fatal(err)
}
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err == nil {
t.Fatal("recorded history masked missing table")
}
}