Skip to content

🎧 Your Personal Streaming Service

feat(cli): add 'doctor' and 'search rebuild' commands to recover from FTS5 corruption (#6069)

Deluan Quintãod0d5403708c1
diff --git a/cmd/backup.go b/cmd/backup.go
index eca78a272..932a833f2 100644
--- a/cmd/backup.go
+++ b/cmd/backup.go
@@ -2,10 +2,7 @@ package cmd
import (
"context"
- "fmt"
- "os"
"path/filepath"
- "strings"
"time"
"github.com/navidrome/navidrome/conf"
@@ -79,19 +76,7 @@ func runBackup(ctx context.Context) {
conf.Server.Backup.Path = conf.NewDir(backupDir)
}
- idx := strings.LastIndex(conf.Server.DbPath, "?")
- var path string
-
- if idx == -1 {
- path = conf.Server.DbPath
- } else {
- path = conf.Server.DbPath[:idx]
- }
-
- if _, err := os.Stat(path); os.IsNotExist(err) {
- log.Fatal("No existing database", "path", path)
- return
- }
+ requireExistingDB()
start := time.Now()
path, err := db.Backup(ctx)
@@ -112,32 +97,13 @@ func runPrune(ctx context.Context) {
conf.Server.Backup.Count = backupCount
}
- if conf.Server.Backup.Count == 0 && !force {
- fmt.Println("Warning: pruning ALL backups")
- fmt.Printf("Please enter YES (all caps) to continue: ")
- var input string
- _, err := fmt.Scanln(&input)
-
- if input != "YES" || err != nil {
- log.Warn("Prune cancelled")
- return
- }
- }
-
- idx := strings.LastIndex(conf.Server.DbPath, "?")
- var path string
-
- if idx == -1 {
- path = conf.Server.DbPath
- } else {
- path = conf.Server.DbPath[:idx]
- }
-
- if _, err := os.Stat(path); os.IsNotExist(err) {
- log.Fatal("No existing database", "path", path)
+ if conf.Server.Backup.Count == 0 && !force && !confirmYES("Warning: pruning ALL backups") {
+ log.Warn("Prune cancelled")
return
}
+ requireExistingDB()
+
start := time.Now()
count, err := db.Prune(ctx)
if err != nil {
@@ -150,19 +116,7 @@ func runPrune(ctx context.Context) {
}
func runRestore(ctx context.Context) {
- idx := strings.LastIndex(conf.Server.DbPath, "?")
- var path string
-
- if idx == -1 {
- path = conf.Server.DbPath
- } else {
- path = conf.Server.DbPath[:idx]
- }
-
- if _, err := os.Stat(path); os.IsNotExist(err) {
- log.Fatal("No existing database", "path", path)
- return
- }
+ requireExistingDB()
// A relative --backup-file is resolved against Backup.Path, the same folder
// `backup create` writes to. Without this, the value was treated as relative
@@ -176,16 +130,9 @@ func runRestore(ctx context.Context) {
restorePath = filepath.Join(backupPath, restorePath)
}
- if !force {
- fmt.Println("Warning: restoring the Navidrome database should only be done offline, especially if your backup is very old.")
- fmt.Printf("Please enter YES (all caps) to continue: ")
- var input string
- _, err := fmt.Scanln(&input)
-
- if input != "YES" || err != nil {
- log.Warn("Restore cancelled")
- return
- }
+ if !force && !confirmYES("Warning: restoring the Navidrome database should only be done offline, especially if your backup is very old.") {
+ log.Warn("Restore cancelled")
+ return
}
start := time.Now()
diff --git a/cmd/doctor.go b/cmd/doctor.go
new file mode 100644
index 000000000..fd0eb1cd7
--- /dev/null
+++ b/cmd/doctor.go
@@ -0,0 +1,99 @@
+package cmd
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "io"
+ "os"
+
+ "github.com/navidrome/navidrome/db"
+ "github.com/spf13/cobra"
+)
+
+func init() {
+ rootCmd.AddCommand(doctorCmd)
+}
+
+var doctorCmd = &cobra.Command{
+ Use: "doctor",
+ Short: "Check your Navidrome installation for problems",
+ Long: "Run read-only health checks and report what was found. Checks the database for " +
+ "corruption and foreign key violations, and reports whether 'navidrome search rebuild' " +
+ "can fix what it finds. This command never alters your data",
+ Run: func(cmd *cobra.Command, _ []string) {
+ runDoctor(cmd.Context())
+ },
+}
+
+func runDoctor(ctx context.Context) {
+ requireExistingDB()
+
+ healthy := doctor(ctx, db.Db(), os.Stdout)
+ db.Close(ctx)
+ if !healthy {
+ os.Exit(1)
+ }
+}
+
+const recoveryAdvice = "Restore a backup (navidrome backup restore), or try SQLite's '.recover' command."
+
+func printFindings(out io.Writer, check, noun string, items []string) {
+ fmt.Fprintf(out, "%s reported %d %s:\n", check, len(items), noun)
+ for _, item := range items {
+ fmt.Fprintln(out, " "+item)
+ }
+}
+
+func doctor(ctx context.Context, database *sql.DB, out io.Writer) bool {
+ healthy := true
+
+ fmt.Fprintln(out, "Checking database integrity...")
+ issues, truncated, err := db.IntegrityCheck(ctx, database)
+ switch {
+ case err != nil:
+ fmt.Fprintln(out, "The integrity check could not complete: "+err.Error())
+ fmt.Fprintln(out, recoveryAdvice)
+ return false
+ case len(issues) == 0:
+ fmt.Fprintln(out, "Integrity check passed.")
+ default:
+ healthy = false
+ printFindings(out, "Integrity check", "issue(s)", issues)
+ switch {
+ case truncated:
+ fmt.Fprintln(out, "The integrity check stopped at its limit, so the damage may reach further than listed.")
+ fmt.Fprintln(out, recoveryAdvice)
+ case db.IsFTSCorruptionOnly(issues):
+ fmt.Fprintln(out, "Corruption is limited to the search index. Run 'navidrome search rebuild' to fix it.")
+ default:
+ fmt.Fprintln(out, "Corruption is not limited to the search index, and cannot be repaired automatically.")
+ fmt.Fprintln(out, recoveryAdvice)
+ }
+ }
+
+ fmt.Fprintln(out, "Checking foreign keys...")
+ violations, err := db.ForeignKeyCheck(ctx, database)
+ switch {
+ case err != nil:
+ healthy = false
+ fmt.Fprintln(out, "The foreign key check could not complete: "+err.Error())
+ case len(violations) == 0:
+ fmt.Fprintln(out, "Foreign key check passed.")
+ default:
+ healthy = false
+ lines := make([]string, 0, len(violations))
+ for _, v := range violations {
+ lines = append(lines,
+ fmt.Sprintf("%s: %d row(s) reference missing rows in %s", v.Table, v.Count, v.Parent))
+ }
+ printFindings(out, "Foreign key check", "violation(s)", lines)
+ fmt.Fprintln(out, "These are orphaned rows, not corruption. 'navidrome scan -f' clears some of them "+
+ "in library data; the rest have to be removed by hand.")
+ }
+
+ if healthy {
+ fmt.Fprintln(out, "Database is healthy.")
+ }
+ return healthy
+}
diff --git a/cmd/doctor_test.go b/cmd/doctor_test.go
new file mode 100644
index 000000000..7f8cd9728
--- /dev/null
+++ b/cmd/doctor_test.go
@@ -0,0 +1,124 @@
+package cmd
+
+import (
+ "context"
+ "database/sql"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/navidrome/navidrome/db"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("doctor", func() {
+ var (
+ ctx context.Context
+ dbPath string
+ database *sql.DB
+ out *strings.Builder
+ reopen func()
+ )
+
+ // A file-backed DB so specs can corrupt raw pages; a table named like a real FTS
+ // search table so IsFTSCorruptionOnly matches, plus a parent/child pair for FK checks.
+ BeforeEach(func() {
+ ctx = context.Background()
+ dbPath = filepath.Join(GinkgoT().TempDir(), "doctor.db")
+ reopen = func() {
+ var err error
+ database, err = sql.Open(db.Dialect, dbPath)
+ Expect(err).ToNot(HaveOccurred())
+ database.SetMaxOpenConns(1)
+ }
+ reopen()
+ DeferCleanup(func() { _ = database.Close() })
+
+ for _, stmt := range []string{
+ `create virtual table media_file_fts using fts5(title, content='', content_rowid='rowid')`,
+ `insert into media_file_fts(rowid, title) values (1, 'teenage lobotomy'), (2, 'rockaway beach')`,
+ `create table library(id integer primary key)`,
+ `create table media_file(id integer primary key, library_id integer references library(id))`,
+ } {
+ _, err := database.ExecContext(ctx, stmt)
+ Expect(err).ToNot(HaveOccurred())
+ }
+ out = &strings.Builder{}
+ })
+
+ It("reports a healthy database", func() {
+ Expect(doctor(ctx, database, out)).To(BeTrue())
+ Expect(out.String()).To(ContainSubstring("Database is healthy."))
+ })
+
+ It("points to 'search rebuild' when corruption is limited to the search index", func() {
+ _, err := database.ExecContext(ctx,
+ `update media_file_fts_data set block = x'deadbeefdeadbeef' where id > 1`)
+ Expect(err).ToNot(HaveOccurred())
+
+ Expect(doctor(ctx, database, out)).To(BeFalse())
+ Expect(out.String()).To(ContainSubstring("navidrome search rebuild"))
+ })
+
+ It("points to a backup restore when corruption is not limited to the search index", func() {
+ _, err := database.ExecContext(ctx,
+ `insert into library(id)
+ with recursive s(x) as (select 1 union all select x+1 from s where x < 200)
+ select x from s`)
+ Expect(err).ToNot(HaveOccurred())
+ var rootPage, pageSize int64
+ Expect(database.QueryRowContext(ctx,
+ `select rootpage from sqlite_master where name = 'library'`).Scan(&rootPage)).To(Succeed())
+ Expect(database.QueryRowContext(ctx, `pragma page_size`).Scan(&pageSize)).To(Succeed())
+ Expect(database.Close()).To(Succeed())
+ f, err := os.OpenFile(dbPath, os.O_WRONLY, 0600)
+ Expect(err).ToNot(HaveOccurred())
+ _, err = f.WriteAt([]byte{0xde, 0xad, 0xbe, 0xef, 0xde, 0xad, 0xbe, 0xef}, (rootPage-1)*pageSize+40)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(f.Close()).To(Succeed())
+ reopen()
+
+ Expect(doctor(ctx, database, out)).To(BeFalse())
+ Expect(out.String()).To(ContainSubstring("backup restore"))
+ Expect(out.String()).ToNot(ContainSubstring("search rebuild"))
+ })
+
+ It("reports foreign key violations", func() {
+ _, err := database.ExecContext(ctx, `pragma foreign_keys = off`)
+ Expect(err).ToNot(HaveOccurred())
+ _, err = database.ExecContext(ctx, `insert into media_file(id, library_id) values (1, 999)`)
+ Expect(err).ToNot(HaveOccurred())
+
+ Expect(doctor(ctx, database, out)).To(BeFalse())
+ Expect(out.String()).To(ContainSubstring("Foreign key check reported"))
+ Expect(out.String()).To(ContainSubstring("media_file"))
+ Expect(out.String()).To(ContainSubstring("navidrome scan -f"))
+ // GC never touches player, share or playqueue, so don't promise a full cleanup.
+ Expect(out.String()).To(ContainSubstring("removed by hand"))
+ })
+
+ // Every issue names an FTS-like index, so IsFTSCorruptionOnly alone would send the
+ // user to 'search rebuild', but the pragma stopped at its limit without saying so.
+ It("does not blame the search index when the issue list is truncated", func() {
+ for _, stmt := range []string{
+ `create table t(a, b)`,
+ `with recursive s(x) as (select 1 union all select x+1 from s where x < 300)
+ insert into t select x, x + 10000 from s`,
+ `create index media_file_fts_probe on t(a)`,
+ `pragma writable_schema=on`,
+ `update sqlite_master set sql = 'CREATE INDEX media_file_fts_probe ON t(b)'
+ where name = 'media_file_fts_probe'`,
+ } {
+ _, err := database.ExecContext(ctx, stmt)
+ Expect(err).ToNot(HaveOccurred())
+ }
+ Expect(database.Close()).To(Succeed())
+ reopen()
+
+ Expect(doctor(ctx, database, out)).To(BeFalse())
+ Expect(out.String()).ToNot(ContainSubstring("search rebuild"))
+ Expect(out.String()).To(ContainSubstring("backup restore"))
+ })
+})
diff --git a/cmd/search.go b/cmd/search.go
new file mode 100644
index 000000000..46b7eebd5
--- /dev/null
+++ b/cmd/search.go
@@ -0,0 +1,55 @@
+package cmd
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/navidrome/navidrome/db"
+ "github.com/navidrome/navidrome/log"
+ "github.com/spf13/cobra"
+)
+
+var searchRebuildForce bool
+
+func init() {
+ rootCmd.AddCommand(searchRoot)
+
+ searchRebuildCmd.Flags().BoolVarP(&searchRebuildForce, "force", "f", false, "bypass rebuild confirmation")
+ searchRoot.AddCommand(searchRebuildCmd)
+}
+
+var (
+ searchRoot = &cobra.Command{
+ Use: "search",
+ Short: "Search index maintenance",
+ }
+
+ searchRebuildCmd = &cobra.Command{
+ Use: "rebuild",
+ Short: "Rebuild the full-text search index",
+ Long: "Drop and rebuild the full-text search index from the library data. Fixes a corrupted " +
+ "or desynced search index without any data loss. Note that 'navidrome doctor' detects a " +
+ "corrupted index, but cannot tell when the index has merely drifted out of sync with the " +
+ "library. This must be done offline",
+ Run: func(cmd *cobra.Command, _ []string) {
+ runSearchRebuild(cmd.Context())
+ },
+ }
+)
+
+func runSearchRebuild(ctx context.Context) {
+ requireExistingDB()
+
+ if !searchRebuildForce && !confirmYES("This will rebuild the search index. Make sure Navidrome is not running.") {
+ log.Warn("Rebuild cancelled")
+ return
+ }
+
+ fmt.Println("Rebuilding the search index...")
+ err := db.RebuildFTS(ctx, db.Db())
+ db.Close(ctx)
+ if err != nil {
+ log.Fatal("Error rebuilding the search index", err)
+ }
+ fmt.Println("Search index rebuilt successfully.")
+}
diff --git a/cmd/utils.go b/cmd/utils.go
index 74da51828..a67f720ac 100644
--- a/cmd/utils.go
+++ b/cmd/utils.go
@@ -5,8 +5,11 @@ import (
"errors"
"fmt"
"io"
+ "os"
+ "strings"
"text/tabwriter"
+ "github.com/navidrome/navidrome/conf"
"github.com/navidrome/navidrome/core/auth"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log"
@@ -15,6 +18,23 @@ import (
"github.com/navidrome/navidrome/persistence"
)
+// requireExistingDB aborts the command when the database file (DbPath minus DSN
+// params) does not exist.
+func requireExistingDB() {
+ path, _, _ := strings.Cut(conf.Server.DbPath, "?")
+ if _, err := os.Stat(path); os.IsNotExist(err) {
+ log.Fatal("No existing database", "path", path)
+ }
+}
+
+func confirmYES(warning string) bool {
+ fmt.Println(warning)
+ fmt.Printf("Please enter YES (all caps) to continue: ")
+ var input string
+ _, err := fmt.Scanln(&input)
+ return input == "YES" && err == nil
+}
+
// newTabWriter keeps every CLI table on the same column settings.
func newTabWriter(out io.Writer) *tabwriter.Writer {
return tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
diff --git a/db/db.go b/db/db.go
index c53aa364a..685886edb 100644
--- a/db/db.go
+++ b/db/db.go
@@ -157,13 +157,24 @@ func hasPendingMigrations(ctx context.Context, db *sql.DB, folder string) bool {
return l.numPending > 0
}
+// hasGooseTable reports whether goose's bookkeeping table exists, i.e. whether the
+// database has ever been migrated.
+func hasGooseTable(ctx context.Context, db *sql.DB) (bool, error) {
+ var name string
+ err := db.QueryRowContext(ctx,
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='goose_db_version'").Scan(&name)
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return err == nil, err
+}
+
func isSchemaEmpty(ctx context.Context, db *sql.DB) bool {
- rows, err := db.QueryContext(ctx, "SELECT name FROM sqlite_master WHERE type='table' AND name='goose_db_version';") // nolint:rowserrcheck
+ found, err := hasGooseTable(ctx, db)
if err != nil {
log.Fatal(ctx, "Database could not be opened!", err)
}
- defer rows.Close()
- return !rows.Next()
+ return !found
}
type logAdapter struct {
diff --git a/db/export_test.go b/db/export_test.go
index 02b88cd66..d2034bcdb 100644
--- a/db/export_test.go
+++ b/db/export_test.go
@@ -2,6 +2,10 @@ package db
// Definitions for testing private methods
var (
+ EmbedMigrations = embedMigrations
+ FTSTables = ftsTables
+ FTSTriggerSuffixes = ftsTriggerSuffixes
+ FTSSearchMigration = ftsSearchMigration
IsSchemaEmpty = isSchemaEmpty
BackupPath = backupPath
OptimizeDBAt = optimizeAt
diff --git a/db/repair.go b/db/repair.go
new file mode 100644
index 000000000..7f8b8d044
--- /dev/null
+++ b/db/repair.go
@@ -0,0 +1,367 @@
+package db
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "slices"
+ "strings"
+)
+
+var ftsTables = []string{"media_file_fts", "album_fts", "artist_fts"}
+
+var ftsTriggerSuffixes = []string{"_ai", "_ad", "_au"}
+
+// integrityCheckMaxIssues bounds the problems reported; IntegrityCheck asks the
+// pragma for one extra row, because it truncates without emitting any marker.
+const integrityCheckMaxIssues = 100
+
+// IntegrityCheck runs PRAGMA integrity_check and returns the problems it reports, or
+// an empty slice when healthy. The second value marks a list that was cut short.
+func IntegrityCheck(ctx context.Context, database *sql.DB) ([]string, bool, error) {
+ rows, err := database.QueryContext(ctx,
+ fmt.Sprintf("PRAGMA integrity_check(%d)", integrityCheckMaxIssues+1))
+ if err != nil {
+ return nil, false, fmt.Errorf("running integrity_check: %w", err)
+ }
+ defer rows.Close()
+
+ var issues []string
+ for rows.Next() {
+ var line string
+ if err := rows.Scan(&line); err != nil {
+ return nil, false, fmt.Errorf("reading integrity_check results: %w", err)
+ }
+ issues = append(issues, line)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, false, fmt.Errorf("reading integrity_check results: %w", err)
+ }
+ if len(issues) == 1 && issues[0] == "ok" {
+ return nil, false, nil
+ }
+ if len(issues) > integrityCheckMaxIssues {
+ return issues[:integrityCheckMaxIssues], true, nil
+ }
+ return issues, false, nil
+}
+
+// FKViolation counts the rows in Table that reference missing rows in Parent.
+type FKViolation struct {
+ Table string
+ Parent string
+ Count int64
+}
+
+// ForeignKeyCheck runs PRAGMA foreign_key_check, aggregated per (table, parent) pair
+// because the raw pragma emits one row per orphan, unbounded on a large library.
+func ForeignKeyCheck(ctx context.Context, database *sql.DB) ([]FKViolation, error) {
+ rows, err := database.QueryContext(ctx,
+ `SELECT "table", "parent", count(*) FROM pragma_foreign_key_check GROUP BY "table", "parent"`)
+ if err != nil {
+ return nil, fmt.Errorf("running foreign_key_check: %w", err)
+ }
+ defer rows.Close()
+
+ var violations []FKViolation
+ for rows.Next() {
+ var v FKViolation
+ if err := rows.Scan(&v.Table, &v.Parent, &v.Count); err != nil {
+ return nil, fmt.Errorf("reading foreign_key_check results: %w", err)
+ }
+ violations = append(violations, v)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("reading foreign_key_check results: %w", err)
+ }
+ return violations, nil
+}
+
+// IsFTSCorruptionOnly reports whether every integrity issue refers to one of the
+// FTS5 search tables, meaning RebuildFTS can fully repair the database.
+func IsFTSCorruptionOnly(issues []string) bool {
+ if len(issues) == 0 {
+ return false
+ }
+ for _, line := range issues {
+ if !slices.ContainsFunc(ftsTables, func(table string) bool { return strings.Contains(line, table) }) {
+ return false
+ }
+ }
+ return true
+}
+
+// execer is the subset of *sql.DB and *sql.Tx that verifyFTS needs.
+type execer interface {
+ ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
+}
+
+// VerifyFTS runs the FTS5 'integrity-check' command on each search table. Unlike a
+// full PRAGMA integrity_check, it reads only the FTS indexes, not the whole database.
+func VerifyFTS(ctx context.Context, database *sql.DB) error {
+ return verifyFTS(ctx, database)
+}
+
+func verifyFTS(ctx context.Context, database execer) error {
+ for _, table := range ftsTables {
+ stmt := fmt.Sprintf("INSERT INTO %[1]s(%[1]s) VALUES('integrity-check')", table) //nolint:gosec // fixed table list
+ if _, err := database.ExecContext(ctx, stmt); err != nil {
+ return fmt.Errorf("verifying %s: %w", table, err)
+ }
+ }
+ return nil
+}
+
+const ftsSearchMigration int64 = 20260220173400
+
+var errNotMigrated = errors.New("the FTS search migration has not been applied yet; start Navidrome once to migrate the database first")
+
+// requireFTSMigration fails unless the FTS search migration has run. The goose table
+// is probed separately because a query against a missing table fails at prepare time.
+func requireFTSMigration(ctx context.Context, database *sql.DB) error {
+ migrated, err := hasGooseTable(ctx, database)
+ if err != nil {
+ return fmt.Errorf("checking FTS migration status: %w", err)
+ }
+ if !migrated {
+ return errNotMigrated
+ }
+ var applied int
+ if err := database.QueryRowContext(ctx,
+ "SELECT count(*) FROM goose_db_version WHERE version_id = ?", ftsSearchMigration).Scan(&applied); err != nil {
+ return fmt.Errorf("checking FTS migration status: %w", err)
+ }
+ if applied == 0 {
+ return errNotMigrated
+ }
+ return nil
+}
+
+// RebuildFTS drops the FTS5 search tables and their triggers, recreates them from the
+// base tables, and verifies the result before committing. The tables are contentless,
+// so no user data is lost. It needs only the FTS migration, not a fully migrated
+// schema, because a corrupted DB often cannot run pending migrations.
+func RebuildFTS(ctx context.Context, database *sql.DB) error {
+ if err := requireFTSMigration(ctx, database); err != nil {
+ return err
+ }
+
+ tx, err := database.BeginTx(ctx, nil)
+ if err != nil {
+ return fmt.Errorf("starting FTS rebuild transaction: %w", err)
+ }
+ defer func() { _ = tx.Rollback() }()
+
+ var stmts []string
+ for _, table := range ftsTables {
+ for _, suffix := range ftsTriggerSuffixes {
+ stmts = append(stmts, "DROP TRIGGER IF EXISTS "+table+suffix)
+ }
+ stmts = append(stmts, "DROP TABLE IF EXISTS "+table)
+ }
+ stmts = append(stmts, ftsSchemaDDL...)
+ for _, stmt := range stmts {
+ if _, err := tx.ExecContext(ctx, stmt); err != nil {
+ return fmt.Errorf("rebuilding FTS schema: %w", err)
+ }
+ }
+ if err := verifyFTS(ctx, tx); err != nil {
+ return fmt.Errorf("the rebuilt search index did not verify: %w", err)
+ }
+ if err := tx.Commit(); err != nil {
+ return fmt.Errorf("committing FTS rebuild: %w", err)
+ }
+ return nil
+}
+
+// ftsSchemaDDL must reproduce what the full migration chain produces, not what any
+// single migration does; the schema comparison in repair_test.go guards the drift.
+var ftsSchemaDDL = []string{
+ `
+ CREATE VIRTUAL TABLE IF NOT EXISTS media_file_fts USING fts5(
+ title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized,
+ content='', content_rowid='rowid',
+ tokenize='unicode61 remove_diacritics 2'
+ )
+ `,
+ `
+ CREATE VIRTUAL TABLE IF NOT EXISTS album_fts USING fts5(
+ name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized,
+ content='', content_rowid='rowid',
+ tokenize='unicode61 remove_diacritics 2'
+ )
+ `,
+ `
+ CREATE VIRTUAL TABLE IF NOT EXISTS artist_fts USING fts5(
+ name, sort_artist_name, search_normalized,
+ content='', content_rowid='rowid',
+ tokenize='unicode61 remove_diacritics 2'
+ )
+ `,
+ `
+ INSERT INTO media_file_fts(rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ SELECT rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ COALESCE(disc_subtitle, ''), COALESCE(search_participants, ''),
+ COALESCE(search_normalized, '')
+ FROM media_file
+ `,
+ `
+ INSERT INTO album_fts(rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ SELECT rowid, name, COALESCE(sort_album_name, ''), COALESCE(album_artist, ''),
+ COALESCE(search_participants, ''), COALESCE(discs, ''),
+ COALESCE(catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(album.tags, '$.albumversion') AS je), ''),
+ COALESCE(search_normalized, '')
+ FROM album
+ `,
+ `
+ INSERT INTO artist_fts(rowid, name, sort_artist_name, search_normalized)
+ SELECT rowid, name, COALESCE(sort_artist_name, ''), COALESCE(search_normalized, '')
+ FROM artist
+ `,
+ `
+ CREATE TRIGGER media_file_fts_ai AFTER INSERT ON media_file BEGIN
+ INSERT INTO media_file_fts(rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ VALUES (NEW.rowid, NEW.title, NEW.album, NEW.artist, NEW.album_artist,
+ NEW.sort_title, NEW.sort_album_name, NEW.sort_artist_name, NEW.sort_album_artist_name,
+ COALESCE(NEW.disc_subtitle, ''), COALESCE(NEW.search_participants, ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `,
+ `
+ CREATE TRIGGER media_file_fts_ad AFTER DELETE ON media_file BEGIN
+ INSERT INTO media_file_fts(media_file_fts, rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.title, OLD.album, OLD.artist, OLD.album_artist,
+ OLD.sort_title, OLD.sort_album_name, OLD.sort_artist_name, OLD.sort_album_artist_name,
+ COALESCE(OLD.disc_subtitle, ''), COALESCE(OLD.search_participants, ''),
+ COALESCE(OLD.search_normalized, ''));
+ END
+ `,
+ `
+ CREATE TRIGGER media_file_fts_au AFTER UPDATE ON media_file
+ WHEN
+ OLD.title IS NOT NEW.title OR
+ OLD.album IS NOT NEW.album OR
+ OLD.artist IS NOT NEW.artist OR
+ OLD.album_artist IS NOT NEW.album_artist OR
+ OLD.sort_title IS NOT NEW.sort_title OR
+ OLD.sort_album_name IS NOT NEW.sort_album_name OR
+ OLD.sort_artist_name IS NOT NEW.sort_artist_name OR
+ OLD.sort_album_artist_name IS NOT NEW.sort_album_artist_name OR
+ OLD.disc_subtitle IS NOT NEW.disc_subtitle OR
+ OLD.search_participants IS NOT NEW.search_participants OR
+ OLD.search_normalized IS NOT NEW.search_normalized
+ BEGIN
+ INSERT INTO media_file_fts(media_file_fts, rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.title, OLD.album, OLD.artist, OLD.album_artist,
+ OLD.sort_title, OLD.sort_album_name, OLD.sort_artist_name, OLD.sort_album_artist_name,
+ COALESCE(OLD.disc_subtitle, ''), COALESCE(OLD.search_participants, ''),
+ COALESCE(OLD.search_normalized, ''));
+ INSERT INTO media_file_fts(rowid, title, album, artist, album_artist,
+ sort_title, sort_album_name, sort_artist_name, sort_album_artist_name,
+ disc_subtitle, search_participants, search_normalized)
+ VALUES (NEW.rowid, NEW.title, NEW.album, NEW.artist, NEW.album_artist,
+ NEW.sort_title, NEW.sort_album_name, NEW.sort_artist_name, NEW.sort_album_artist_name,
+ COALESCE(NEW.disc_subtitle, ''), COALESCE(NEW.search_participants, ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `,
+ `
+ CREATE TRIGGER album_fts_ai AFTER INSERT ON album BEGIN
+ INSERT INTO album_fts(rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ VALUES (NEW.rowid, NEW.name, COALESCE(NEW.sort_album_name, ''), COALESCE(NEW.album_artist, ''),
+ COALESCE(NEW.search_participants, ''), COALESCE(NEW.discs, ''),
+ COALESCE(NEW.catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(NEW.tags, '$.albumversion') AS je), ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `,
+ `
+ CREATE TRIGGER album_fts_ad AFTER DELETE ON album BEGIN
+ INSERT INTO album_fts(album_fts, rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.name, COALESCE(OLD.sort_album_name, ''), COALESCE(OLD.album_artist, ''),
+ COALESCE(OLD.search_participants, ''), COALESCE(OLD.discs, ''),
+ COALESCE(OLD.catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(OLD.tags, '$.albumversion') AS je), ''),
+ COALESCE(OLD.search_normalized, ''));
+ END
+ `,
+ `
+ CREATE TRIGGER album_fts_au AFTER UPDATE ON album
+ WHEN
+ OLD.name IS NOT NEW.name OR
+ OLD.sort_album_name IS NOT NEW.sort_album_name OR
+ OLD.album_artist IS NOT NEW.album_artist OR
+ OLD.search_participants IS NOT NEW.search_participants OR
+ OLD.discs IS NOT NEW.discs OR
+ OLD.catalog_num IS NOT NEW.catalog_num OR
+ OLD.tags IS NOT NEW.tags OR
+ OLD.search_normalized IS NOT NEW.search_normalized
+ BEGIN
+ INSERT INTO album_fts(album_fts, rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.name, COALESCE(OLD.sort_album_name, ''), COALESCE(OLD.album_artist, ''),
+ COALESCE(OLD.search_participants, ''), COALESCE(OLD.discs, ''),
+ COALESCE(OLD.catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(OLD.tags, '$.albumversion') AS je), ''),
+ COALESCE(OLD.search_normalized, ''));
+ INSERT INTO album_fts(rowid, name, sort_album_name, album_artist,
+ search_participants, discs, catalog_num, album_version, search_normalized)
+ VALUES (NEW.rowid, NEW.name, COALESCE(NEW.sort_album_name, ''), COALESCE(NEW.album_artist, ''),
+ COALESCE(NEW.search_participants, ''), COALESCE(NEW.discs, ''),
+ COALESCE(NEW.catalog_num, ''),
+ COALESCE((SELECT group_concat(json_extract(je.value, '$.value'), ' ')
+ FROM json_each(NEW.tags, '$.albumversion') AS je), ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `,
+ `
+ CREATE TRIGGER artist_fts_ai AFTER INSERT ON artist BEGIN
+ INSERT INTO artist_fts(rowid, name, sort_artist_name, search_normalized)
+ VALUES (NEW.rowid, NEW.name, COALESCE(NEW.sort_artist_name, ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `,
+ `
+ CREATE TRIGGER artist_fts_ad AFTER DELETE ON artist BEGIN
+ INSERT INTO artist_fts(artist_fts, rowid, name, sort_artist_name, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.name, COALESCE(OLD.sort_artist_name, ''),
+ COALESCE(OLD.search_normalized, ''));
+ END
+ `,
+ `
+ CREATE TRIGGER artist_fts_au AFTER UPDATE ON artist
+ WHEN
+ OLD.name IS NOT NEW.name OR
+ OLD.sort_artist_name IS NOT NEW.sort_artist_name OR
+ OLD.search_normalized IS NOT NEW.search_normalized
+ BEGIN
+ INSERT INTO artist_fts(artist_fts, rowid, name, sort_artist_name, search_normalized)
+ VALUES ('delete', OLD.rowid, OLD.name, COALESCE(OLD.sort_artist_name, ''),
+ COALESCE(OLD.search_normalized, ''));
+ INSERT INTO artist_fts(rowid, name, sort_artist_name, search_normalized)
+ VALUES (NEW.rowid, NEW.name, COALESCE(NEW.sort_artist_name, ''),
+ COALESCE(NEW.search_normalized, ''));
+ END
+ `,
+}
diff --git a/db/repair_test.go b/db/repair_test.go
new file mode 100644
index 000000000..eb7321939
--- /dev/null
+++ b/db/repair_test.go
@@ -0,0 +1,309 @@
+package db_test
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "path/filepath"
+ "regexp"
+ "strings"
+
+ "github.com/navidrome/navidrome/db"
+ "github.com/pressly/goose/v3"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+// newDB returns an in-memory database migrated up to the given goose version
+// (0 = fully migrated).
+func newDB(ctx context.Context, upTo int64) *sql.DB {
+ GinkgoHelper()
+ d, err := sql.Open(db.Dialect, "file::memory:")
+ Expect(err).ToNot(HaveOccurred())
+ d.SetMaxOpenConns(1) // non-shared :memory:, a second conn would be an empty DB
+ DeferCleanup(func() { _ = d.Close() })
+
+ _, err = d.ExecContext(ctx, "PRAGMA foreign_keys=off")
+ Expect(err).ToNot(HaveOccurred())
+ goose.SetBaseFS(db.EmbedMigrations)
+ goose.SetLogger(goose.NopLogger())
+ DeferCleanup(func() { goose.SetBaseFS(nil) })
+ Expect(goose.SetDialect(db.Dialect)).To(Succeed())
+ if upTo == 0 {
+ Expect(goose.UpContext(ctx, d, "migrations")).To(Succeed())
+ } else {
+ Expect(goose.UpToContext(ctx, d, "migrations", upTo)).To(Succeed())
+ }
+ return d
+}
+
+// openMismatchedIndexDB builds a database whose index is declared over a different
+// column than the one it was populated from, so integrity_check reports one issue per row.
+func openMismatchedIndexDB(ctx context.Context, rows int) *sql.DB {
+ GinkgoHelper()
+ path := filepath.Join(GinkgoT().TempDir(), "mismatched.db")
+ open := func() *sql.DB {
+ d, err := sql.Open(db.Dialect, path)
+ Expect(err).ToNot(HaveOccurred())
+ d.SetMaxOpenConns(1)
+ return d
+ }
+ d := open()
+ for _, stmt := range []string{
+ `create table t(a, b)`,
+ fmt.Sprintf(`with recursive s(x) as (select 1 union all select x+1 from s where x < %d)
+ insert into t select x, x + 10000 from s`, rows),
+ `create index i on t(a)`,
+ `pragma writable_schema=on`,
+ `update sqlite_master set sql = 'CREATE INDEX i ON t(b)' where name = 'i'`,
+ } {
+ _, err := d.ExecContext(ctx, stmt)
+ Expect(err).ToNot(HaveOccurred())
+ }
+ Expect(d.Close()).To(Succeed()) // reopen so SQLite reparses the doctored schema
+
+ d = open()
+ DeferCleanup(func() { _ = d.Close() })
+ return d
+}
+
+var _ = Describe("IsFTSCorruptionOnly", func() {
+ It("is true when every issue mentions an FTS search table", func() {
+ Expect(db.IsFTSCorruptionOnly([]string{
+ `fts5: corruption found reading blob 42 from table "media_file_fts"`,
+ `malformed inverted index for FTS5 table main.album_fts`,
+ `fts5: corruption in "artist_fts"`,
+ })).To(BeTrue())
+ })
+
+ It("is false when any issue is outside the FTS search tables", func() {
+ Expect(db.IsFTSCorruptionOnly([]string{
+ `fts5: corruption found reading blob 42 from table "media_file_fts"`,
+ `*** in database main ***`,
+ })).To(BeFalse())
+ })
+
+ It("is false when there are no issues", func() {
+ Expect(db.IsFTSCorruptionOnly(nil)).To(BeFalse())
+ })
+})
+
+var _ = Describe("RebuildFTS schema guard", func() {
+ var ctx context.Context
+
+ BeforeEach(func() {
+ ctx = context.Background()
+ })
+
+ It("refuses to run on a schema older than the FTS migration", func() {
+ old := newDB(ctx, db.FTSSearchMigration-1)
+
+ err := db.RebuildFTS(ctx, old)
+ Expect(err).To(MatchError(ContainSubstring("migration")))
+ })
+
+ It("refuses to run on a database that was never migrated", func() {
+ empty, err := sql.Open(db.Dialect, "file::memory:")
+ Expect(err).ToNot(HaveOccurred())
+ empty.SetMaxOpenConns(1)
+ DeferCleanup(func() { _ = empty.Close() })
+
+ Expect(db.RebuildFTS(ctx, empty)).To(MatchError(ContainSubstring("start Navidrome once")))
+ })
+
+ It("runs on a post-FTS schema even when newer migrations are pending", func() {
+ behind := newDB(ctx, 20260702152457)
+
+ Expect(db.RebuildFTS(ctx, behind)).To(Succeed())
+ })
+})
+
+var _ = Describe("Repair", func() {
+ var (
+ ctx context.Context
+ database *sql.DB
+ )
+
+ BeforeEach(func() {
+ ctx = context.Background()
+ database = newDB(ctx, 0)
+
+ for _, stmt := range []string{
+ `insert into artist(id, name, search_normalized) values ('ar-1', 'Ramones', 'ramones')`,
+ `insert into album(id, name, search_normalized) values ('al-1', 'Rocket to Russia', 'rocket to russia')`,
+ `insert into media_file(id, title, search_normalized) values ('mf-1', 'Teenage Lobotomy', 'teenage lobotomy')`,
+ `insert into media_file(id, title, search_normalized) values ('mf-2', 'Rockaway Beach', 'rockaway beach')`,
+ } {
+ _, err := database.ExecContext(ctx, stmt)
+ Expect(err).ToNot(HaveOccurred())
+ }
+ })
+
+ corruptFTS := func(table string) {
+ // 8+ bytes of garbage: a 4-byte blob still parses as a valid empty structure record
+ _, err := database.ExecContext(ctx, `update `+table+`_data set block = x'deadbeefdeadbeef' where id > 1`) //nolint:gosec
+ Expect(err).ToNot(HaveOccurred())
+ }
+
+ searchFTS := func(table, term string) int {
+ var count int
+ err := database.QueryRowContext(ctx, `select count(*) from `+table+` where `+table+` match ?`, term).Scan(&count)
+ Expect(err).ToNot(HaveOccurred())
+ return count
+ }
+
+ // ftsSchema returns name -> whitespace-normalized DDL for the FTS tables,
+ // their shadow tables, and their triggers.
+ ftsSchema := func() map[string]string {
+ rows, err := database.QueryContext(ctx,
+ `select name, sql from sqlite_master where name like '%_fts%' and sql is not null`)
+ Expect(err).ToNot(HaveOccurred())
+ defer rows.Close()
+ ws := regexp.MustCompile(`\s+`)
+ schema := map[string]string{}
+ for rows.Next() {
+ var name, ddl string
+ Expect(rows.Scan(&name, &ddl)).To(Succeed())
+ schema[name] = ws.ReplaceAllString(ddl, " ")
+ }
+ Expect(rows.Err()).ToNot(HaveOccurred())
+ return schema
+ }
+
+ Describe("IntegrityCheck", func() {
+ It("returns no issues for a healthy database", func() {
+ issues, truncated, err := db.IntegrityCheck(ctx, database)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(issues).To(BeEmpty())
+ Expect(truncated).To(BeFalse())
+ })
+
+ It("reports corruption in an FTS index", func() {
+ corruptFTS("media_file_fts")
+ issues, truncated, err := db.IntegrityCheck(ctx, database)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(issues).ToNot(BeEmpty())
+ Expect(strings.Join(issues, "\n")).To(ContainSubstring("media_file_fts"))
+ Expect(truncated).To(BeFalse())
+ })
+
+ It("flags the issue list as truncated when there are more issues than the limit", func() {
+ broken := openMismatchedIndexDB(ctx, 300)
+
+ issues, truncated, err := db.IntegrityCheck(ctx, broken)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(issues).To(HaveLen(100))
+ Expect(truncated).To(BeTrue())
+ })
+
+ It("does not flag truncation when the issues exactly fill the limit", func() {
+ broken := openMismatchedIndexDB(ctx, 100)
+
+ issues, truncated, err := db.IntegrityCheck(ctx, broken)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(issues).To(HaveLen(100))
+ Expect(truncated).To(BeFalse())
+ })
+ })
+
+ Describe("ForeignKeyCheck", func() {
+ It("returns no violations for a healthy database", func() {
+ violations, err := db.ForeignKeyCheck(ctx, database)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(violations).To(BeEmpty())
+ })
+
+ It("reports rows referencing missing parents", func() {
+ _, err := database.ExecContext(ctx,
+ `insert into media_file(id, title, library_id) values ('mf-bad', 'Orphan', 999)`)
+ Expect(err).ToNot(HaveOccurred())
+
+ violations, err := db.ForeignKeyCheck(ctx, database)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(violations).To(HaveLen(1))
+ Expect(violations[0].Table).To(Equal("media_file"))
+ Expect(violations[0].Parent).To(Equal("library"))
+ Expect(violations[0].Count).To(BeNumerically("==", 1))
+ })
+ })
+
+ Describe("VerifyFTS", func() {
+ It("passes on a healthy index", func() {
+ Expect(db.VerifyFTS(ctx, database)).To(Succeed())
+ })
+
+ It("fails on a corrupted index, naming the table", func() {
+ corruptFTS("album_fts")
+ Expect(db.VerifyFTS(ctx, database)).To(MatchError(ContainSubstring("album_fts")))
+ })
+ })
+
+ Describe("RebuildFTS", func() {
+ It("repairs a corrupted FTS index", func() {
+ corruptFTS("media_file_fts")
+
+ Expect(db.RebuildFTS(ctx, database)).To(Succeed())
+
+ issues, _, err := db.IntegrityCheck(ctx, database)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(issues).To(BeEmpty())
+ Expect(db.VerifyFTS(ctx, database)).To(Succeed())
+ Expect(searchFTS("media_file_fts", "lobotomy")).To(Equal(1))
+ Expect(searchFTS("album_fts", "russia")).To(Equal(1))
+ Expect(searchFTS("artist_fts", "ramones")).To(Equal(1))
+ })
+
+ It("recreates tables and triggers dropped by hand", func() {
+ for _, table := range db.FTSTables {
+ for _, suffix := range db.FTSTriggerSuffixes {
+ _, err := database.ExecContext(ctx, "drop trigger "+table+suffix)
+ Expect(err).ToNot(HaveOccurred())
+ }
+ _, err := database.ExecContext(ctx, "drop table "+table)
+ Expect(err).ToNot(HaveOccurred())
+ }
+
+ Expect(db.RebuildFTS(ctx, database)).To(Succeed())
+
+ Expect(searchFTS("media_file_fts", "rockaway")).To(Equal(1))
+ })
+
+ It("rolls back and keeps the old index when the rebuild fails", func() {
+ // Triggers go first: SQLite refuses to drop a column they reference.
+ for _, suffix := range db.FTSTriggerSuffixes {
+ _, err := database.ExecContext(ctx, "drop trigger media_file_fts"+suffix)
+ Expect(err).ToNot(HaveOccurred())
+ }
+ _, err := database.ExecContext(ctx, `alter table media_file drop column disc_subtitle`)
+ Expect(err).ToNot(HaveOccurred())
+
+ Expect(db.RebuildFTS(ctx, database)).ToNot(Succeed())
+
+ Expect(searchFTS("media_file_fts", "lobotomy")).To(Equal(1))
+ Expect(searchFTS("album_fts", "russia")).To(Equal(1))
+ })
+
+ It("produces the same schema as the migration", func() {
+ migrated := ftsSchema()
+ Expect(migrated).ToNot(BeEmpty())
+
+ Expect(db.RebuildFTS(ctx, database)).To(Succeed())
+
+ Expect(ftsSchema()).To(Equal(migrated))
+ })
+
+ It("leaves working triggers behind", func() {
+ Expect(db.RebuildFTS(ctx, database)).To(Succeed())
+
+ _, err := database.ExecContext(ctx,
+ `insert into artist(id, name, search_normalized) values ('ar-2', 'Blondie', 'blondie')`)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(searchFTS("artist_fts", "blondie")).To(Equal(1))
+
+ _, err = database.ExecContext(ctx, `delete from artist where id = 'ar-2'`)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(searchFTS("artist_fts", "blondie")).To(BeZero())
+ })
+ })
+})