mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-09 02:47:29 +02:00
* feat(db): add repair command to rebuild a corrupted FTS5 search index A corrupted media_file_fts index made every scan fail with 'database disk image is malformed', and sqlite3's built-in 'rebuild' command cannot repair contentless FTS5 tables, leaving users to hand-drop tables and triggers. Add 'navidrome db repair': it runs PRAGMA integrity_check, and when the reported corruption is confined to the FTS5 search tables, drops and recreates the three tables and their nine triggers and repopulates them from the base tables (which hold all the data, so nothing is lost). The result is verified with the FTS5-native 'integrity-check' command, which reads only the rebuilt indexes instead of re-scanning the whole database (on a 761MB production copy: ~9s full check, ~1s rebuild, sub-second verify). A --rebuild flag forces the rebuild even when the check passes, for silently desynced indexes. The rebuild refuses to run while migrations are pending, and a schema-comparison test guards the duplicated DDL against drifting from the migration. The DbPath existence check and the YES confirmation prompt, previously copy-pasted across the backup commands, are extracted into shared cmd helpers used by both backup and repair. Part of #6067 * fix(db): type the FTS migration version as int64 for 32-bit builds The untyped constant defaults to int, which overflows on arm/v7 and 386. * feat(db): split repair into 'db doctor' and 'search rebuild' commands A single 'db repair' command promised more than it delivered: the only thing it could actually repair was the search index, and its diagnosis and its fix were welded together, so a forced rebuild paid the full integrity check twice. Split it: 'navidrome db doctor' is strictly read-only, runs both PRAGMA integrity_check and PRAGMA foreign_key_check, and routes the user (to 'search rebuild' when corruption is FTS-only, to backup/.recover otherwise). 'navidrome search rebuild' just rebuilds and verifies the FTS index, which takes ~2s on a prod-size library instead of ~19s. * refactor(cmd): extract a testable doctor function and bound foreign key output Extract the doctor routing (check, classify, advise) into a function that takes an io.Writer, so the advice paths are unit-tested and the process exit happens in the cobra wrapper after the DB is closed (os.Exit was skipping the deferred close, leaving WAL/SHM files behind on the unhealthy paths). Aggregate foreign_key_check by (table, parent): the raw pragma emits one row per orphan, which is unbounded output on a large corrupted library. Also make confirmYES take an io.Reader, drop the unused return from the renamed requireExistingDB, share the FTS table list with the tests, and stop the schema-guard specs from paying for a seeded database they never use. * docs(cmd): promise 'never alters your data' instead of 'never modifies the database' Closing the doctor's connection can checkpoint a stale WAL into the main file (as any SQLite tool does), so the byte-level claim was too strong. The checks themselves are read-only and no logical content ever changes. * fix(cmd): make 'db doctor' advice honest when checks are inconclusive PRAGMA integrity_check stops at 100 errors and emits no marker row, so a saturated result was being read as the whole picture. IntegrityCheck now sets the limit itself and reports saturation as a truncated list, and doctor no longer claims corruption is limited to the search index in that case. Foreign key violations now print a next step instead of only flipping the exit code: migrations run with foreign_keys off, so orphan rows are a realistic leftover on a database that is not corrupt. Also corrects the 'search rebuild' help, which promised that 'db doctor' detects when a rebuild is needed -- integrity_check cannot see an index that is merely out of sync; gives the never-migrated case its intended message instead of a raw 'no such table: goose_db_version'; and extracts rebuildSearchIndex so the database is closed before log.Fatal exits. * refactor(cmd): promote 'db doctor' to a top-level 'doctor' command The 'db' group held a single subcommand, and the checks planned for it reach past the database: config, music folder permissions, external tools. None of those belong under 'db'. Promoting it also evens out the shape of the pair. The command that finds the problem is now top-level alongside 'search rebuild', the command that fixes it, matching the 'brew doctor' convention users already expect. 'db doctor' has never been released, so no alias or deprecation is needed. * refactor(db): tighten the doctor and search rebuild internals Follow-up cleanup with no behaviour change except where noted. integrity_check now asks the pragma for one row beyond the reported limit and treats that extra row as the proof it truncated, instead of inferring truncation from a saturated count. That distinguishes a list of exactly 100 issues from one that was cut short -- the old test could not, and 100 was SQLite's own default, so passing it was a no-op. ForeignKeyCheck returns []FKViolation instead of pre-formatted English, moving the prose to the layer that already owns the CLI vocabulary. The goose table probe shared with isSchemaEmpty becomes hasGooseTable, so 'has this database ever been migrated' has one spelling. Also folds ftsMigrationApplied into requireFTSMigration, lifts printFindings out of a closure that captured nothing, names the FTS trigger suffixes once, and corrects the ftsSchemaDDL comment: the drift test compares against the full migration chain, not the single frozen migration it claimed. * fix(db): verify the rebuilt search index before committing it RebuildFTS committed its transaction and only then ran the FTS5 integrity check, from the caller. A rebuild that produced a bad index was therefore already persisted by the time anyone noticed, leaving the user worse off than before they ran the command. The check now runs inside the transaction, so a rebuild that does not verify rolls back and leaves the original index in place. VerifyFTS keeps its *sql.DB signature for callers outside a transaction; the shared body takes the small execer interface that both *sql.DB and *sql.Tx satisfy. Adds a spec for the rollback: it removes a column the repopulating SELECT reads, so the transaction fails after the drops, and asserts the old index still answers queries. * refactor(cmd): drop the unused io.Reader parameter from confirmYES The reader was added as a test seam that no test ever used: all three callers pass os.Stdin. Back to fmt.Scanln, which drops the parameter and the now-unused os import from backup.go and search.go. * fix(cmd): stop promising a scan clears every foreign key violation doctor told the user to run 'navidrome scan -f' for any foreign key violation. SQLStore.GC only purges albums, artists, folders, annotations, bookmarks, tags and playlist tracks, so orphans elsewhere survive it and the next doctor run still reports them. player.user_id references user(id) and no scan phase touches that table at all. The advice now says a scan clears some of them and the rest have to be removed by hand, which keeps the next step the earlier round asked for without claiming a cleanup that does not happen. * docs(db): trim over-long comments on the doctor and rebuild paths Six comments ran past two lines or repeated something already stated nearby. The RebuildFTS doc claimed the rebuild rolls back on a column mismatch, which the new 'verifies before committing' sentence already implies, and a spec comment restated that same rationale a second time. * docs: drop em dashes from the comments added in this branch
309 lines
10 KiB
Go
309 lines
10 KiB
Go
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())
|
|
})
|
|
})
|
|
})
|