diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 67b84b061..23dbd10e7 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "fmt" "os" "os/exec" @@ -28,6 +29,7 @@ import ( "github.com/steveyegge/beads/internal/molecules" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" + "github.com/steveyegge/beads/internal/storage/schema" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/telemetry" "github.com/steveyegge/beads/internal/utils" @@ -74,6 +76,7 @@ var ( proxiedServerMode bool readonlyMode bool // Read-only mode: block write operations (for worker sandboxes) storeIsReadOnly bool // Track if store was opened read-only (for staleness checks) + ignoreSchemaSkew bool // Proceed despite forward schema drift lockTimeout = 30 * time.Second // Dolt open timeout (fixed default) profileEnabled bool profileFile *os.File @@ -515,6 +518,7 @@ func init() { rootCmd.PersistentFlags().BoolVar(&profileEnabled, "profile", false, "Generate CPU profile for performance analysis") rootCmd.PersistentFlags().BoolVarP(&verboseFlag, "verbose", "v", false, "Enable verbose/debug output") rootCmd.PersistentFlags().BoolVarP(&quietFlag, "quiet", "q", false, "Suppress non-essential output (errors only)") + rootCmd.PersistentFlags().BoolVar(&ignoreSchemaSkew, "ignore-schema-skew", false, "Proceed despite forward schema drift (some queries may fail)") // Add --version flag to root command (same behavior as version subcommand) rootCmd.Flags().BoolP("version", "V", false, "Print version information") @@ -706,6 +710,12 @@ var rootCmd = &cobra.Command{ }{doltAutoCommit, true} } + // --ignore-schema-skew sets BD_IGNORE_SCHEMA_SKEW so the env-var escape + // hatch works uniformly for all store open paths (dolt, embedded). + if ignoreSchemaSkew { + _ = os.Setenv("BD_IGNORE_SCHEMA_SKEW", "1") + } + // Check for and log configuration overrides (only in verbose mode) if verboseFlag { overrides := config.CheckOverrides(flagOverrides) @@ -1038,6 +1048,16 @@ var rootCmd = &cobra.Command{ if handleFreshCloneError(err) { os.Exit(1) } + // Schema skew gets dedicated UX with actionable rebuild instructions. + var skewErr *schema.SchemaSkewError + if errors.As(err, &skewErr) { + if jsonOutput { + handleSchemaSkewJSON(skewErr) + } else { + fmt.Fprint(os.Stderr, skewErr.UserMessage()) + } + os.Exit(1) + } FatalError("failed to open database: %v", err) } diff --git a/cmd/bd/schema_skew.go b/cmd/bd/schema_skew.go new file mode 100644 index 000000000..92cde3165 --- /dev/null +++ b/cmd/bd/schema_skew.go @@ -0,0 +1,22 @@ +package main + +import ( + "encoding/json" + "os" + + "github.com/steveyegge/beads/internal/storage/schema" +) + +func handleSchemaSkewJSON(e *schema.SchemaSkewError) { + outer := buildJSONError(e.Error(), e.EscapeHint()) + if m, ok := outer.(map[string]interface{}); ok { + m["schema_skew"] = map[string]interface{}{ + "current_version": e.DBVersion, + "required_version": e.BinaryVersion, + "delta": e.DBVersion - e.BinaryVersion, + } + } + encoder := json.NewEncoder(os.Stderr) + encoder.SetIndent("", " ") + _ = encoder.Encode(outer) +} diff --git a/cmd/bd/schema_skew_test.go b/cmd/bd/schema_skew_test.go new file mode 100644 index 000000000..8d876e6ba --- /dev/null +++ b/cmd/bd/schema_skew_test.go @@ -0,0 +1,85 @@ +package main + +import ( + "bytes" + "encoding/json" + "io" + "os" + "testing" + + "github.com/steveyegge/beads/internal/storage/schema" +) + +// TestHandleSchemaSkewJSON_Shape verifies the JSON written to stderr by +// handleSchemaSkewJSON has the expected shape: error (terse one-liner), +// hint (escape-hatch string), schema_skew subobject, and schema_version. +func TestHandleSchemaSkewJSON_Shape(t *testing.T) { + skew := &schema.SchemaSkewError{DBVersion: 45, BinaryVersion: 42} + + origStderr := os.Stderr + r, w, pipeErr := os.Pipe() + if pipeErr != nil { + t.Fatal(pipeErr) + } + os.Stderr = w + + handleSchemaSkewJSON(skew) + + _ = w.Close() + os.Stderr = origStderr + + var buf bytes.Buffer + if _, err := io.Copy(&buf, r); err != nil { + t.Fatal(err) + } + _ = r.Close() + + var parsed map[string]interface{} + if err := json.Unmarshal(buf.Bytes(), &parsed); err != nil { + t.Fatalf("json.Unmarshal stderr: %v\nstderr was: %s", err, buf.String()) + } + + // "error" key must contain the terse Error() string. + wantError := skew.Error() + if got, ok := parsed["error"].(string); !ok || got != wantError { + t.Errorf("error = %v, want %q", parsed["error"], wantError) + } + + // "hint" key must contain EscapeHint(). + wantHint := skew.EscapeHint() + if got, ok := parsed["hint"].(string); !ok || got != wantHint { + t.Errorf("hint = %v, want %q", parsed["hint"], wantHint) + } + + // "schema_version" key must be JSONSchemaVersion. + if got, ok := parsed["schema_version"].(float64); !ok || int(got) != JSONSchemaVersion { + t.Errorf("schema_version = %v, want %d", parsed["schema_version"], JSONSchemaVersion) + } + + // "schema_skew" subobject must be present with current_version, required_version, delta. + skewObj, ok := parsed["schema_skew"].(map[string]interface{}) + if !ok { + t.Fatalf("schema_skew key missing or wrong type: %T", parsed["schema_skew"]) + } + if got, ok := skewObj["current_version"].(float64); !ok || int(got) != 45 { + t.Errorf("schema_skew.current_version = %v, want 45", skewObj["current_version"]) + } + if got, ok := skewObj["required_version"].(float64); !ok || int(got) != 42 { + t.Errorf("schema_skew.required_version = %v, want 42", skewObj["required_version"]) + } + if got, ok := skewObj["delta"].(float64); !ok || int(got) != 3 { + t.Errorf("schema_skew.delta = %v, want 3", skewObj["delta"]) + } +} + +// TestIgnoreSchemaSkewFlagRegistered verifies that --ignore-schema-skew is +// registered as a persistent flag on the root command. +func TestIgnoreSchemaSkewFlagRegistered(t *testing.T) { + f := rootCmd.PersistentFlags().Lookup("ignore-schema-skew") + if f == nil { + t.Fatal("--ignore-schema-skew persistent flag is not registered") + } + if f.Value.Type() != "bool" { + t.Errorf("--ignore-schema-skew flag type = %q, want bool", f.Value.Type()) + } +} diff --git a/internal/storage/dolt/schema_skew_test.go b/internal/storage/dolt/schema_skew_test.go new file mode 100644 index 000000000..9da15cce4 --- /dev/null +++ b/internal/storage/dolt/schema_skew_test.go @@ -0,0 +1,224 @@ +package dolt + +import ( + "context" + "errors" + "fmt" + "os" + "testing" + + "github.com/steveyegge/beads/internal/storage/schema" +) + +// TestCheckForwardDrift_ForwardDrift_ReturnsSchemaSkewError verifies that +// CheckForwardDrift returns a *schema.SchemaSkewError when the DB is one +// migration ahead of the binary. +func TestCheckForwardDrift_ForwardDrift_ReturnsSchemaSkewError(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + + ctx, cancel := testContext(t) + defer cancel() + + if _, err := store.db.ExecContext(ctx, + "INSERT INTO schema_migrations (version) VALUES (?)", + schema.LatestVersion()+1, + ); err != nil { + t.Fatalf("insert future migration: %v", err) + } + + err := schema.CheckForwardDrift(ctx, store.db) + if err == nil { + t.Fatal("CheckForwardDrift = nil, want error when DB is ahead of binary") + } + var skewErr *schema.SchemaSkewError + if !errors.As(err, &skewErr) { + t.Fatalf("error = %T (%v), want *schema.SchemaSkewError", err, err) + } + if skewErr.DBVersion != schema.LatestVersion()+1 { + t.Errorf("DBVersion = %d, want %d", skewErr.DBVersion, schema.LatestVersion()+1) + } + if skewErr.BinaryVersion != schema.LatestVersion() { + t.Errorf("BinaryVersion = %d, want %d", skewErr.BinaryVersion, schema.LatestVersion()) + } +} + +// TestCheckForwardDrift_CurrentVersion_NoError verifies that CheckForwardDrift +// returns nil when the DB schema matches the binary. +func TestCheckForwardDrift_CurrentVersion_NoError(t *testing.T) { + if os.Getenv("BD_IGNORE_SCHEMA_SKEW") != "" { + t.Skip("BD_IGNORE_SCHEMA_SKEW is set — skipping to keep the non-escape-hatch path clean") + } + + store, cleanup := setupTestStore(t) + defer cleanup() + + ctx, cancel := testContext(t) + defer cancel() + + if err := schema.CheckForwardDrift(ctx, store.db); err != nil { + t.Fatalf("CheckForwardDrift = %v, want nil when schema is current", err) + } +} + +// TestCheckForwardDrift_EscapeHatch_ReturnsNil verifies that +// BD_IGNORE_SCHEMA_SKEW=1 suppresses the forward-drift error. +func TestCheckForwardDrift_EscapeHatch_ReturnsNil(t *testing.T) { + t.Setenv("BD_IGNORE_SCHEMA_SKEW", "1") + + store, cleanup := setupTestStore(t) + defer cleanup() + + ctx, cancel := testContext(t) + defer cancel() + + if _, err := store.db.ExecContext(ctx, + "INSERT INTO schema_migrations (version) VALUES (?)", + schema.LatestVersion()+1, + ); err != nil { + t.Fatalf("insert future migration: %v", err) + } + + if err := schema.CheckForwardDrift(ctx, store.db); err != nil { + t.Fatalf("CheckForwardDrift = %v, want nil when BD_IGNORE_SCHEMA_SKEW=1", err) + } +} + +// TestDoltNew_ReadOnly_ForwardDrift_ReturnsSchemaSkewError is a full-chain +// integration test: opening a read-only store against a DB that is one +// migration ahead of the binary must fail with a *schema.SchemaSkewError. +func TestDoltNew_ReadOnly_ForwardDrift_ReturnsSchemaSkewError(t *testing.T) { + skipIfNoDolt(t) + + ctx, cancel := testContext(t) + defer cancel() + + tmpDir := t.TempDir() + dbName := uniqueTestDBName(t) + + // Open a writable store to create the database and initialize the schema. + store, err := New(ctx, &Config{ + Path: tmpDir, + CommitterName: "test", + CommitterEmail: "test@example.com", + Database: dbName, + CreateIfMissing: true, + }) + if err != nil { + t.Fatalf("New (create): %v", err) + } + // Keep store open for cleanup; DROP must happen before Close. + defer func() { + dropCtx, dropCancel := context.WithTimeout(context.Background(), 5*testTimeout) + defer dropCancel() + _, _ = store.db.ExecContext(dropCtx, fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", dbName)) + store.Close() + }() + + // Advance schema_migrations by one to simulate a DB from a newer binary. + if _, err := store.db.ExecContext(ctx, + "INSERT INTO schema_migrations (version) VALUES (?)", + schema.LatestVersion()+1, + ); err != nil { + t.Fatalf("insert future migration: %v", err) + } + + // Opening in read-only mode must detect the drift and return a SchemaSkewError. + roStore, roErr := New(ctx, &Config{ + Path: tmpDir, + Database: dbName, + ReadOnly: true, + }) + if roErr == nil { + roStore.Close() + t.Fatal("New (read-only) = nil, want error for forward schema drift") + } + if !schema.IsSchemaSkewError(roErr) { + t.Fatalf("error = %T (%v), want error wrapping *schema.SchemaSkewError", roErr, roErr) + } +} + +// TestDoltNew_ReadOnly_ForwardDrift_EscapeHatch_Succeeds verifies that +// BD_IGNORE_SCHEMA_SKEW=1 allows a read-only store to open despite forward drift. +func TestDoltNew_ReadOnly_ForwardDrift_EscapeHatch_Succeeds(t *testing.T) { + skipIfNoDolt(t) + t.Setenv("BD_IGNORE_SCHEMA_SKEW", "1") + + ctx, cancel := testContext(t) + defer cancel() + + tmpDir := t.TempDir() + dbName := uniqueTestDBName(t) + + store, err := New(ctx, &Config{ + Path: tmpDir, + CommitterName: "test", + CommitterEmail: "test@example.com", + Database: dbName, + CreateIfMissing: true, + }) + if err != nil { + t.Fatalf("New (create): %v", err) + } + defer func() { + dropCtx, dropCancel := context.WithTimeout(context.Background(), 5*testTimeout) + defer dropCancel() + _, _ = store.db.ExecContext(dropCtx, fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", dbName)) + store.Close() + }() + + if _, err := store.db.ExecContext(ctx, + "INSERT INTO schema_migrations (version) VALUES (?)", + schema.LatestVersion()+1, + ); err != nil { + t.Fatalf("insert future migration: %v", err) + } + + roStore, roErr := New(ctx, &Config{ + Path: tmpDir, + Database: dbName, + ReadOnly: true, + }) + if roErr != nil { + t.Fatalf("New (read-only with escape hatch) = %v, want nil", roErr) + } + defer roStore.Close() +} + +// TestDoltNew_CreateIfMissing_NoSchemaSkewError is the bd-init no-op guard: +// creating a brand-new database must not trip the schema skew guard. +// A fresh DB has schema_migrations version=0, which checkSchemaSkew treats as no-op. +func TestDoltNew_CreateIfMissing_NoSchemaSkewError(t *testing.T) { + skipIfNoDolt(t) + + ctx, cancel := testContext(t) + defer cancel() + + tmpDir := t.TempDir() + dbName := uniqueTestDBName(t) + + store, err := New(ctx, &Config{ + Path: tmpDir, + CommitterName: "test", + CommitterEmail: "test@example.com", + Database: dbName, + CreateIfMissing: true, + }) + if err != nil { + if schema.IsSchemaSkewError(err) { + t.Fatalf("New (CreateIfMissing) tripped schema skew guard — guard must be no-op for fresh DB: %v", err) + } + t.Fatalf("New (CreateIfMissing) = %v, want nil", err) + } + defer func() { + dropCtx, dropCancel := context.WithTimeout(context.Background(), 5*testTimeout) + defer dropCancel() + _, _ = store.db.ExecContext(dropCtx, fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", dbName)) + store.Close() + }() + + // A fully-migrated fresh DB should also pass CheckForwardDrift (version == binary). + if err := schema.CheckForwardDrift(ctx, store.db); err != nil { + t.Fatalf("CheckForwardDrift on fresh DB = %v, want nil", err) + } +} diff --git a/internal/storage/dolt/store.go b/internal/storage/dolt/store.go index 8aeaf6fe1..020ec1fb2 100644 --- a/internal/storage/dolt/store.go +++ b/internal/storage/dolt/store.go @@ -1095,7 +1095,12 @@ func newServerMode(ctx context.Context, cfg *Config) (*DoltStore, error) { autoStartedServerDir: autoStartedDir, } - if !cfg.ReadOnly { + if cfg.ReadOnly { + if err := schema.CheckForwardDrift(ctx, db); err != nil { + _ = db.Close() + return nil, err + } + } else { if err := store.initSchema(ctx); err != nil { return nil, fmt.Errorf("failed to initialize schema: %w", err) } diff --git a/internal/storage/schema/schema.go b/internal/storage/schema/schema.go index 4b0868343..a6ff859e4 100644 --- a/internal/storage/schema/schema.go +++ b/internal/storage/schema/schema.go @@ -6,9 +6,11 @@ import ( "database/sql" "embed" "encoding/hex" + "errors" "fmt" "io/fs" "log" + "os" "regexp" "sort" "strconv" @@ -24,6 +26,82 @@ type DBConn interface { QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row } +// SchemaSkewError is returned when the DB schema version is ahead of the +// binary's known version (forward drift). Stale binary queries may fail with +// cryptic SQL errors like "column X could not be found in any table in scope". +type SchemaSkewError struct { + DBVersion int + BinaryVersion int +} + +func (e *SchemaSkewError) Error() string { + delta := e.DBVersion - e.BinaryVersion + unit := "migrations" + if delta == 1 { + unit = "migration" + } + return fmt.Sprintf("schema version mismatch: database is at v%d, binary knows up to v%d (%d %s ahead)", + e.DBVersion, e.BinaryVersion, delta, unit) +} + +// UserMessage returns the full multi-line error block for terminal output. +func (e *SchemaSkewError) UserMessage() string { + return e.Error() + "\n" + + "\n" + + " Your bd binary is stale. Queries for dropped or renamed columns will fail\n" + + " with cryptic SQL errors (e.g. \"column X could not be found in any table in scope\").\n" + + "\n" + + " Rebuild from main:\n" + + " CGO_ENABLED=0 go build -tags gms_pure_go ./cmd/bd\n" + + "\n" + + " Or install the latest release:\n" + + " go install github.com/steveyegge/beads/cmd/bd@latest\n" + + "\n" + + " To proceed despite the risk (some read commands may still work):\n" + + " BD_IGNORE_SCHEMA_SKEW=1 bd \n" + + " bd --ignore-schema-skew \n" +} + +// EscapeHint returns the escape-hatch string for JSON error output. +func (e *SchemaSkewError) EscapeHint() string { + return "BD_IGNORE_SCHEMA_SKEW=1 bd or bd --ignore-schema-skew " +} + +// IsSchemaSkewError reports whether err (or any error it wraps) is a +// *SchemaSkewError. +func IsSchemaSkewError(err error) bool { + var e *SchemaSkewError + return errors.As(err, &e) +} + +// checkSchemaSkew queries the DB's current schema version and returns a +// *SchemaSkewError if the DB is ahead of the binary. Returns nil for a fresh +// DB (version=0) or when BD_IGNORE_SCHEMA_SKEW=1 (prints a warning instead). +func checkSchemaSkew(ctx context.Context, db DBConn) error { + var currentVersion int + if err := db.QueryRowContext(ctx, + "SELECT COALESCE(MAX(version), 0) FROM schema_migrations", + ).Scan(¤tVersion); err != nil { + return fmt.Errorf("schema skew check: %w", err) + } + if currentVersion == 0 || currentVersion <= LatestVersion() { + return nil + } + if os.Getenv("BD_IGNORE_SCHEMA_SKEW") == "1" { + fmt.Fprintf(os.Stderr, + "Warning: schema skew ignored — database (v%d) is ahead of binary (v%d); some queries may fail\n", + currentVersion, LatestVersion()) + return nil + } + return &SchemaSkewError{DBVersion: currentVersion, BinaryVersion: LatestVersion()} +} + +// CheckForwardDrift checks for forward schema drift on an existing *sql.DB +// connection. Used by the read-only store path where MigrateUp is skipped. +func CheckForwardDrift(ctx context.Context, db *sql.DB) error { + return checkSchemaSkew(ctx, db) +} + type dirtyTableState struct { staged bool } diff --git a/internal/storage/schema/schema_skew_test.go b/internal/storage/schema/schema_skew_test.go new file mode 100644 index 000000000..3b38c1687 --- /dev/null +++ b/internal/storage/schema/schema_skew_test.go @@ -0,0 +1,232 @@ +package schema + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "strings" + "testing" + + sqlmock "github.com/DATA-DOG/go-sqlmock" +) + +// -- checkSchemaSkew unit tests (mock DB) -- + +func TestCheckSchemaSkew_FreshDB_NoError(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + mock.ExpectQuery(`SELECT COALESCE\(MAX\(version\), 0\) FROM schema_migrations`). + WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow(0)) + + if err := checkSchemaSkew(context.Background(), db); err != nil { + t.Fatalf("checkSchemaSkew = %v, want nil for fresh DB (version=0)", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet sql expectations: %v", err) + } +} + +func TestCheckSchemaSkew_EqualVersion_NoError(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + mock.ExpectQuery(`SELECT COALESCE\(MAX\(version\), 0\) FROM schema_migrations`). + WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow(LatestVersion())) + + if err := checkSchemaSkew(context.Background(), db); err != nil { + t.Fatalf("checkSchemaSkew = %v, want nil when DB at binary version", err) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet sql expectations: %v", err) + } +} + +func TestCheckSchemaSkew_OneAhead_ReturnsSchemaSkewError(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + dbVersion := LatestVersion() + 1 + mock.ExpectQuery(`SELECT COALESCE\(MAX\(version\), 0\) FROM schema_migrations`). + WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow(dbVersion)) + + got := checkSchemaSkew(context.Background(), db) + if got == nil { + t.Fatal("checkSchemaSkew = nil, want error when DB one migration ahead") + } + var skewErr *SchemaSkewError + if !errors.As(got, &skewErr) { + t.Fatalf("error type = %T (%v), want *SchemaSkewError", got, got) + } + if skewErr.DBVersion != dbVersion { + t.Errorf("DBVersion = %d, want %d", skewErr.DBVersion, dbVersion) + } + if skewErr.BinaryVersion != LatestVersion() { + t.Errorf("BinaryVersion = %d, want %d", skewErr.BinaryVersion, LatestVersion()) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet sql expectations: %v", err) + } +} + +func TestCheckSchemaSkew_ThreeAhead_ReturnsSchemaSkewError(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + dbVersion := LatestVersion() + 3 + mock.ExpectQuery(`SELECT COALESCE\(MAX\(version\), 0\) FROM schema_migrations`). + WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow(dbVersion)) + + got := checkSchemaSkew(context.Background(), db) + if got == nil { + t.Fatal("checkSchemaSkew = nil, want error when DB three migrations ahead") + } + var skewErr *SchemaSkewError + if !errors.As(got, &skewErr) { + t.Fatalf("error type = %T (%v), want *SchemaSkewError", got, got) + } + if skewErr.DBVersion != dbVersion { + t.Errorf("DBVersion = %d, want %d", skewErr.DBVersion, dbVersion) + } + if skewErr.BinaryVersion != LatestVersion() { + t.Errorf("BinaryVersion = %d, want %d", skewErr.BinaryVersion, LatestVersion()) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet sql expectations: %v", err) + } +} + +func TestCheckSchemaSkew_EscapeHatch_ReturnsNilAndWarns(t *testing.T) { + t.Setenv("BD_IGNORE_SCHEMA_SKEW", "1") + + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("sqlmock.New: %v", err) + } + defer db.Close() + + dbVersion := LatestVersion() + 3 + mock.ExpectQuery(`SELECT COALESCE\(MAX\(version\), 0\) FROM schema_migrations`). + WillReturnRows(sqlmock.NewRows([]string{"version"}).AddRow(dbVersion)) + + // Capture stderr to verify warning is emitted. + origStderr := os.Stderr + r, w, pipeErr := os.Pipe() + if pipeErr != nil { + t.Fatal(pipeErr) + } + os.Stderr = w + + gotErr := checkSchemaSkew(context.Background(), db) + + _ = w.Close() + os.Stderr = origStderr + + var buf bytes.Buffer + if _, copyErr := io.Copy(&buf, r); copyErr != nil { + t.Fatal(copyErr) + } + _ = r.Close() + + if gotErr != nil { + t.Fatalf("checkSchemaSkew = %v, want nil when BD_IGNORE_SCHEMA_SKEW=1", gotErr) + } + + wantWarning := fmt.Sprintf( + "Warning: schema skew ignored — database (v%d) is ahead of binary (v%d); some queries may fail", + dbVersion, LatestVersion(), + ) + if !strings.Contains(buf.String(), wantWarning) { + t.Errorf("stderr = %q\nwant to contain warning:\n %q", buf.String(), wantWarning) + } + if err := mock.ExpectationsWereMet(); err != nil { + t.Fatalf("unmet sql expectations: %v", err) + } +} + +// -- SchemaSkewError message copy tests -- + +func TestSchemaSkewError_Error_Singular(t *testing.T) { + e := &SchemaSkewError{DBVersion: 43, BinaryVersion: 42} + want := "schema version mismatch: database is at v43, binary knows up to v42 (1 migration ahead)" + if got := e.Error(); got != want { + t.Errorf("Error() = %q\nwant: %q", got, want) + } +} + +func TestSchemaSkewError_Error_Plural(t *testing.T) { + e := &SchemaSkewError{DBVersion: 45, BinaryVersion: 42} + want := "schema version mismatch: database is at v45, binary knows up to v42 (3 migrations ahead)" + if got := e.Error(); got != want { + t.Errorf("Error() = %q\nwant: %q", got, want) + } +} + +func TestSchemaSkewError_UserMessage_ExactCopy(t *testing.T) { + e := &SchemaSkewError{DBVersion: 45, BinaryVersion: 42} + want := "schema version mismatch: database is at v45, binary knows up to v42 (3 migrations ahead)\n" + + "\n" + + " Your bd binary is stale. Queries for dropped or renamed columns will fail\n" + + " with cryptic SQL errors (e.g. \"column X could not be found in any table in scope\").\n" + + "\n" + + " Rebuild from main:\n" + + " CGO_ENABLED=0 go build -tags gms_pure_go ./cmd/bd\n" + + "\n" + + " Or install the latest release:\n" + + " go install github.com/steveyegge/beads/cmd/bd@latest\n" + + "\n" + + " To proceed despite the risk (some read commands may still work):\n" + + " BD_IGNORE_SCHEMA_SKEW=1 bd \n" + + " bd --ignore-schema-skew \n" + if got := e.UserMessage(); got != want { + t.Errorf("UserMessage() mismatch.\ngot:\n%s\nwant:\n%s", got, want) + } +} + +func TestSchemaSkewError_EscapeHint_ExactCopy(t *testing.T) { + e := &SchemaSkewError{DBVersion: 45, BinaryVersion: 42} + want := "BD_IGNORE_SCHEMA_SKEW=1 bd or bd --ignore-schema-skew " + if got := e.EscapeHint(); got != want { + t.Errorf("EscapeHint() = %q\nwant: %q", got, want) + } +} + +// -- IsSchemaSkewError tests -- + +func TestIsSchemaSkewError_DirectError(t *testing.T) { + err := &SchemaSkewError{DBVersion: 45, BinaryVersion: 42} + if !IsSchemaSkewError(err) { + t.Error("IsSchemaSkewError(*SchemaSkewError) = false, want true") + } +} + +func TestIsSchemaSkewError_WrappedError(t *testing.T) { + skew := &SchemaSkewError{DBVersion: 45, BinaryVersion: 42} + wrapped := fmt.Errorf("schema version check: %w", skew) + doubleWrapped := fmt.Errorf("failed to open database: %w", wrapped) + if !IsSchemaSkewError(doubleWrapped) { + t.Error("IsSchemaSkewError(wrapped *SchemaSkewError) = false, want true") + } +} + +func TestIsSchemaSkewError_OtherError(t *testing.T) { + err := errors.New("some unrelated error") + if IsSchemaSkewError(err) { + t.Error("IsSchemaSkewError(non-SchemaSkewError) = true, want false") + } +}