banger hasn't shipped a public release — every "legacy", "pre-opt-in",
"previously", "migration note", "no longer" reference in the tree is
pinning against a state no real user's install has ever been in.
That scaffolding has weight: it's a coordinate system future readers
have to decode, and it keeps dead code alive.
Removed (code):
- internal/daemon/ssh_client_config.go
- vmSSHConfigIncludeBegin / vmSSHConfigIncludeEnd constants and
every `removeManagedBlock(existing, vm...)` call they enabled
(legacy inline `Host *.vm` block scrub)
- cleanupLegacySSHConfigDir (+ its caller in syncVMSSHClientConfig)
— wiped a pre-opt-in sibling file under $ConfigDir/ssh
- sameDirOrParent + resolvePathForComparison — only ever used
by cleanupLegacySSHConfigDir
- the "also check legacy marker" fallback in
UserSSHIncludeInstalled / UninstallUserSSHInclude
- internal/store/migrations.go
- migrateDropDeadImageColumns (migration 2) + its slice entry
- dropColumnIfExists (orphaned after the above)
- addColumnIfMissing + the whole "columns added across the pre-
versioning lifetime" block at the end of migrateBaseline —
subsumed into the baseline CREATE TABLE
- `packages_path TEXT` column on the images table (the
throwaway migration 2 dropped it, but there was never any
reader)
- internal/daemon/vm.go
- vmDNSRecordName local wrapper — was justified as "avoid
pulling vmdns into every file"; three of four callers already
imported vmdns directly, so inline the one stray call
- internal/cli/cli_test.go
- TestLegacyRemovedCommandIsRejected (`tui` subcommand never
shipped)
Removed / simplified (tests):
- ssh_client_config_test.go: dropped TestSameDirOrParentHandlesSymlinks,
TestSyncVMSSHClientConfigPreservesUserKeyInLegacyDir,
TestSyncVMSSHClientConfigNarrowsCleanupToLegacyFile,
TestSyncVMSSHClientConfigLeavesUnexpectedLegacyContents,
TestInstallUserSSHIncludeMigratesLegacyInlineBlock, plus the
"legacy posture" regression strings in the remaining happy-path
test; TestUninstallUserSSHIncludeRemovesBothMarkerBlocks collapsed
to a single-block test
- migrations_test.go: dropped TestMigrateDropDeadImageColumns_AcrossInstallPaths,
TestDropColumnIfExistsIsIdempotent; TestOpenReadOnlyDoesNotRunMigrations
simplified to test against the baseline marker
Removed (docs):
- README.md "**Migration note.**" blockquote about the SSH-key path move
- docs/advanced.md parenthetical "(the old behaviour)"
Reworded (comments):
- Dropped "Previously this file also contained LogLevel DEBUG3..."
history from vm_disk.go's sshdGuestConfig doc
- Dropped "Call sites that previously read vm.Runtime.{PID,...}"
from vm_handles.go; now documents the current contract
- Dropped "Pre-v0.1 the defaults are" scaffolding in doctor_test.go
- Dropped "no longer does its own git inspection" phrasing in vm_run.go
- Dropped the "(also cleans up legacy inline block from pre-opt-in
builds)" aside on the `ssh-config` CLI docstring
- Renamed test var `legacyKey` → `existingKey` in vm_test.go; its
purpose was "pre-existing authorized_keys line," not banger-legacy
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
259 lines
8 KiB
Go
259 lines
8 KiB
Go
package store
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
// openRawDB opens a SQLite DB at a fresh tempfile without running any
|
|
// migrations, so tests can observe migration-runner behaviour directly.
|
|
func openRawDB(t *testing.T) *sql.DB {
|
|
t.Helper()
|
|
path := filepath.Join(t.TempDir(), "state.db")
|
|
dsn, err := sqliteDSN(path)
|
|
if err != nil {
|
|
t.Fatalf("sqliteDSN: %v", err)
|
|
}
|
|
db, err := sql.Open("sqlite", dsn)
|
|
if err != nil {
|
|
t.Fatalf("sql.Open: %v", err)
|
|
}
|
|
t.Cleanup(func() { _ = db.Close() })
|
|
return db
|
|
}
|
|
|
|
func TestRunMigrationsAppliesBaselineOnFreshDB(t *testing.T) {
|
|
db := openRawDB(t)
|
|
if err := runMigrations(db); err != nil {
|
|
t.Fatalf("runMigrations: %v", err)
|
|
}
|
|
// All declared migrations must be recorded.
|
|
for _, m := range migrations {
|
|
var got string
|
|
if err := db.QueryRow("SELECT name FROM schema_migrations WHERE id = ?", m.id).Scan(&got); err != nil {
|
|
t.Fatalf("migration %d not recorded: %v", m.id, err)
|
|
}
|
|
if got != m.name {
|
|
t.Errorf("migration %d name = %q, want %q", m.id, got, m.name)
|
|
}
|
|
}
|
|
// Baseline must have created the real tables.
|
|
for _, table := range []string{"images", "vms"} {
|
|
var name string
|
|
if err := db.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name=?", table).Scan(&name); err != nil {
|
|
t.Fatalf("table %s missing: %v", table, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRunMigrationsIsIdempotent(t *testing.T) {
|
|
db := openRawDB(t)
|
|
if err := runMigrations(db); err != nil {
|
|
t.Fatalf("runMigrations first pass: %v", err)
|
|
}
|
|
if err := runMigrations(db); err != nil {
|
|
t.Fatalf("runMigrations second pass: %v", err)
|
|
}
|
|
// One row per migration, no duplicates.
|
|
var count int
|
|
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations").Scan(&count); err != nil {
|
|
t.Fatalf("count: %v", err)
|
|
}
|
|
if count != len(migrations) {
|
|
t.Errorf("schema_migrations rows = %d, want %d", count, len(migrations))
|
|
}
|
|
}
|
|
|
|
func TestRunMigrationsSkipsAlreadyApplied(t *testing.T) {
|
|
db := openRawDB(t)
|
|
|
|
// Swap in a test-only migration whose body would error if invoked,
|
|
// pre-insert its id into schema_migrations, and confirm the runner
|
|
// recognises the marker and skips the body entirely.
|
|
orig := migrations
|
|
t.Cleanup(func() { migrations = orig })
|
|
migrations = []migration{
|
|
{id: 1, name: "baseline", up: migrateBaseline},
|
|
{id: 99, name: "explodes-if-run", up: func(*sql.Tx) error {
|
|
return errors.New("must not execute")
|
|
}},
|
|
}
|
|
|
|
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
id INTEGER PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
applied_at TEXT NOT NULL
|
|
)`); err != nil {
|
|
t.Fatalf("seed schema_migrations table: %v", err)
|
|
}
|
|
if _, err := db.Exec(
|
|
"INSERT INTO schema_migrations (id, name, applied_at) VALUES (?, ?, ?)",
|
|
99, "explodes-if-run", "2026-04-20T00:00:00Z",
|
|
); err != nil {
|
|
t.Fatalf("seed applied row: %v", err)
|
|
}
|
|
|
|
if err := runMigrations(db); err != nil {
|
|
t.Fatalf("runMigrations: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestApplyMigrationRollsBackOnBodyError(t *testing.T) {
|
|
db := openRawDB(t)
|
|
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
id INTEGER PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
applied_at TEXT NOT NULL
|
|
)`); err != nil {
|
|
t.Fatalf("seed schema_migrations: %v", err)
|
|
}
|
|
|
|
err := applyMigration(db, migration{
|
|
id: 7,
|
|
name: "creates-then-fails",
|
|
up: func(tx *sql.Tx) error {
|
|
if _, err := tx.Exec("CREATE TABLE transient (x INTEGER)"); err != nil {
|
|
return err
|
|
}
|
|
return errors.New("synthetic failure")
|
|
},
|
|
})
|
|
if err == nil {
|
|
t.Fatal("expected applyMigration to surface body error")
|
|
}
|
|
|
|
// The transient table must NOT survive the failed migration.
|
|
var name string
|
|
if err := db.QueryRow("SELECT name FROM sqlite_master WHERE type='table' AND name='transient'").Scan(&name); err == nil {
|
|
t.Fatal("transient table survived rollback")
|
|
}
|
|
// And no schema_migrations row for id=7.
|
|
var count int
|
|
if err := db.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE id=7").Scan(&count); err != nil {
|
|
t.Fatalf("count: %v", err)
|
|
}
|
|
if count != 0 {
|
|
t.Fatalf("schema_migrations recorded failed migration: count=%d", count)
|
|
}
|
|
}
|
|
|
|
// TestOpenReadOnlyDoesNotRunMigrations pins the doctor contract:
|
|
// OpenReadOnly must not mutate the DB. Seed a DB whose baseline
|
|
// migration row has been forcibly removed (simulating a "behind"
|
|
// state), open it read-only, and confirm nothing was re-applied.
|
|
func TestOpenReadOnlyDoesNotRunMigrations(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "state.db")
|
|
full, err := Open(path)
|
|
if err != nil {
|
|
t.Fatalf("Open: %v", err)
|
|
}
|
|
if _, err := full.db.Exec("DELETE FROM schema_migrations WHERE id = 1"); err != nil {
|
|
t.Fatalf("remove baseline marker: %v", err)
|
|
}
|
|
_ = full.Close()
|
|
|
|
ro, err := OpenReadOnly(path)
|
|
if err != nil {
|
|
t.Fatalf("OpenReadOnly: %v", err)
|
|
}
|
|
defer ro.Close()
|
|
|
|
var migCount int
|
|
if err := ro.db.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE id = 1").Scan(&migCount); err != nil {
|
|
t.Fatalf("query schema_migrations: %v", err)
|
|
}
|
|
if migCount != 0 {
|
|
t.Fatal("OpenReadOnly re-recorded a migration row — the open path mutated the DB")
|
|
}
|
|
}
|
|
|
|
// TestOpenReadOnlyRefusesWrites confirms SQLite's mode=ro is in effect
|
|
// — no matter what a caller tries, writes are rejected at the driver
|
|
// level. Belt-and-braces guard against a future refactor that might
|
|
// plumb a write method through.
|
|
func TestOpenReadOnlyRefusesWrites(t *testing.T) {
|
|
path := filepath.Join(t.TempDir(), "state.db")
|
|
if s, err := Open(path); err != nil {
|
|
t.Fatalf("seed Open: %v", err)
|
|
} else {
|
|
_ = s.Close()
|
|
}
|
|
ro, err := OpenReadOnly(path)
|
|
if err != nil {
|
|
t.Fatalf("OpenReadOnly: %v", err)
|
|
}
|
|
defer ro.Close()
|
|
if _, err := ro.db.Exec("INSERT INTO schema_migrations (id, name, applied_at) VALUES (999, 'x', 'x')"); err == nil {
|
|
t.Fatal("write succeeded against a read-only store")
|
|
}
|
|
}
|
|
|
|
// TestRunMigrationsIgnoresUnknownAppliedIDs simulates an older banger
|
|
// opening a DB that was written by a newer version: schema_migrations
|
|
// carries rows with ids the current binary's migrations slice doesn't
|
|
// know about. The runner must leave those rows alone and still apply
|
|
// any of its own known migrations that haven't been recorded yet.
|
|
//
|
|
// Without this behaviour, upgrading forward then downgrading back
|
|
// (or running two daemon versions against the same state dir) would
|
|
// either fail outright or start destructively reinterpreting rows.
|
|
func TestRunMigrationsIgnoresUnknownAppliedIDs(t *testing.T) {
|
|
db := openRawDB(t)
|
|
|
|
// Bootstrap schema_migrations and pre-seed a row for a migration
|
|
// id the current binary doesn't know. Use a high id so it's
|
|
// clearly outside our slice.
|
|
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
id INTEGER PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
applied_at TEXT NOT NULL
|
|
)`); err != nil {
|
|
t.Fatalf("seed schema_migrations: %v", err)
|
|
}
|
|
if _, err := db.Exec(
|
|
"INSERT INTO schema_migrations (id, name, applied_at) VALUES (?, ?, ?)",
|
|
9001, "from-the-future", "2099-01-01T00:00:00Z",
|
|
); err != nil {
|
|
t.Fatalf("seed future migration row: %v", err)
|
|
}
|
|
|
|
if err := runMigrations(db); err != nil {
|
|
t.Fatalf("runMigrations: %v", err)
|
|
}
|
|
|
|
// The alien row is untouched.
|
|
var name string
|
|
if err := db.QueryRow("SELECT name FROM schema_migrations WHERE id = 9001").Scan(&name); err != nil {
|
|
t.Fatalf("alien migration row disappeared: %v", err)
|
|
}
|
|
if name != "from-the-future" {
|
|
t.Fatalf("alien row name = %q, want 'from-the-future'", name)
|
|
}
|
|
|
|
// Every known migration in our slice was applied — their rows
|
|
// should exist too.
|
|
for _, m := range migrations {
|
|
var got string
|
|
if err := db.QueryRow("SELECT name FROM schema_migrations WHERE id = ?", m.id).Scan(&got); err != nil {
|
|
t.Fatalf("migration %d not recorded despite unknown alien row: %v", m.id, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestRunMigrationsRejectsDuplicateID(t *testing.T) {
|
|
db := openRawDB(t)
|
|
orig := migrations
|
|
t.Cleanup(func() { migrations = orig })
|
|
migrations = []migration{
|
|
{id: 1, name: "first", up: func(*sql.Tx) error { return nil }},
|
|
{id: 1, name: "dupe", up: func(*sql.Tx) error { return nil }},
|
|
}
|
|
err := runMigrations(db)
|
|
if err == nil {
|
|
t.Fatal("expected error for duplicate migration id")
|
|
}
|
|
}
|