mirror of
https://github.com/navidrome/navidrome.git
synced 2026-11-19 15:23:36 +00:00
perf(scanner): use the title index for the cross-library move lookup (#6463)
This commit is contained in:
parent
2ce7ef53ca
commit
7bea40a25f
@ -545,7 +545,18 @@ func (r *mediaFileRepository) FindRecentFilesByMBZTrackID(ctx context.Context, m
|
||||
// FindRecentFilesByProperties finds recently added files by intrinsic properties in other libraries
|
||||
// It uses a lightweight query without annotation/bookmark joins since those are not needed for matching
|
||||
func (r *mediaFileRepository) FindRecentFilesByProperties(ctx context.Context, missing model.MediaFile, since time.Time) (model.MediaFiles, error) {
|
||||
sel := r.newSelect(ctx).Columns("media_file.*", "library.path as library_path", "library.name as library_name").
|
||||
var res dbMediaFiles
|
||||
err := r.queryAll(ctx, recentFilesByPropertiesQuery(missing, since), &res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res.toModels(), nil
|
||||
}
|
||||
|
||||
func recentFilesByPropertiesQuery(missing model.MediaFile, since time.Time) SelectBuilder {
|
||||
// Many files share mbz_release_track_id = '', so the planner's pick of that index scans them all
|
||||
return Select("media_file.*", "library.path as library_path", "library.name as library_name").
|
||||
From("media_file INDEXED BY media_file_title").
|
||||
LeftJoin("library on media_file.library_id = library.id").
|
||||
Where(And{
|
||||
NotEq{"media_file.library_id": missing.LibraryID},
|
||||
@ -559,13 +570,6 @@ func (r *mediaFileRepository) FindRecentFilesByProperties(ctx context.Context, m
|
||||
Gt{"media_file.created_at": since},
|
||||
Eq{"media_file.missing": false},
|
||||
}).OrderBy("media_file.created_at DESC")
|
||||
|
||||
var res dbMediaFiles
|
||||
err := r.queryAll(ctx, sel, &res)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res.toModels(), nil
|
||||
}
|
||||
|
||||
var mediaFileSearchConfig = searchConfig{
|
||||
|
||||
@ -1203,6 +1203,73 @@ var _ = Describe("MediaRepository", func() {
|
||||
})
|
||||
})
|
||||
|
||||
Describe("FindRecentFilesByProperties", func() {
|
||||
var adminCtx context.Context
|
||||
var otherLib model.Library
|
||||
var missing model.MediaFile
|
||||
var since time.Time
|
||||
|
||||
BeforeEach(func() {
|
||||
adminCtx, otherLib, _ = restrictedFixture("moved")
|
||||
since = time.Now().Add(-time.Hour)
|
||||
missing = model.MediaFile{
|
||||
LibraryID: 1, Title: "Moved Song", Album: "Moved Album", Size: 1234,
|
||||
Suffix: "flac", DiscNumber: 1, TrackNumber: 3,
|
||||
}
|
||||
})
|
||||
|
||||
candidate := func(id string, change func(*model.MediaFile)) {
|
||||
mf := missing
|
||||
mf.ID, mf.LibraryID, mf.Path, mf.CreatedAt = id, otherLib.ID, id+".flac", since.Add(time.Minute)
|
||||
if change != nil {
|
||||
change(&mf)
|
||||
}
|
||||
Expect(mr.Put(adminCtx, &mf)).To(Succeed())
|
||||
DeferCleanup(func() { _ = mr.Delete(adminCtx, mf.ID) })
|
||||
}
|
||||
|
||||
It("returns only recent, present, untagged copies from other libraries", func() {
|
||||
candidate("moved-match", nil)
|
||||
candidate("moved-same-lib", func(mf *model.MediaFile) { mf.LibraryID = 1 })
|
||||
candidate("moved-tagged", func(mf *model.MediaFile) { mf.MbzReleaseTrackID = "some-mbid" })
|
||||
candidate("moved-older", func(mf *model.MediaFile) { mf.CreatedAt = since.Add(-time.Minute) })
|
||||
candidate("moved-missing", func(mf *model.MediaFile) { mf.Missing = true })
|
||||
candidate("moved-other-title", func(mf *model.MediaFile) { mf.Title = "Another Song" })
|
||||
|
||||
results, err := mr.FindRecentFilesByProperties(adminCtx, missing, since)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(slice.Map(results, func(mf model.MediaFile) string { return mf.ID })).To(ConsistOf("moved-match"))
|
||||
Expect(results[0].LibraryPath).To(Equal(otherLib.Path))
|
||||
})
|
||||
|
||||
It("searches by title even when stats make the MBZ track ID index look more selective", func() {
|
||||
conn := GetDBXBuilder().DB()
|
||||
tx, err := conn.BeginTx(adminCtx, nil)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
// The schema, and so the loaded stats, are shared by every connection to the in-memory DB
|
||||
DeferCleanup(func() {
|
||||
Expect(tx.Rollback()).To(Succeed())
|
||||
_, err := conn.Exec("ANALYZE sqlite_schema")
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
})
|
||||
for _, stmt := range []string{
|
||||
"ANALYZE media_file_title",
|
||||
"DELETE FROM sqlite_stat1 WHERE tbl = 'media_file'",
|
||||
"INSERT INTO sqlite_stat1 VALUES ('media_file', 'media_file_title', '40000 2'), ('media_file', 'media_file_mbz_release_track_id', '40000 1'), ('media_file', 'media_file_created_at', '40000 1')",
|
||||
"ANALYZE sqlite_schema",
|
||||
} {
|
||||
_, err := tx.Exec(stmt)
|
||||
Expect(err).ToNot(HaveOccurred(), stmt)
|
||||
}
|
||||
|
||||
query, args, err := recentFilesByPropertiesQuery(missing, since).ToSql()
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
plan, err := queryPlan(tx, query, args...)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(plan).To(ContainElement(ContainSubstring("USING INDEX media_file_title")))
|
||||
})
|
||||
})
|
||||
|
||||
Describe("dbMediaFile.String", func() {
|
||||
It("does not dereference a nil MediaFile", func() {
|
||||
Expect(fmt.Sprint(dbMediaFile{})).To(Equal("<nil>"))
|
||||
|
||||
@ -140,24 +140,30 @@ var _ = Describe("Sort index coverage", func() {
|
||||
// "USE TEMP B-TREE FOR LAST TERM OF ORDER BY" (or "LAST N TERMS") and are allowed.
|
||||
var fullTempBTreeSort = regexp.MustCompile(`USE TEMP B-TREE FOR ORDER BY`)
|
||||
|
||||
func checkSortUsesIndex(conn *sql.DB, table, orderBy string) error {
|
||||
rows, err := conn.Query(fmt.Sprintf("explain query plan select * from %s order by %s limit 15", table, orderBy))
|
||||
func queryPlan(conn interface {
|
||||
Query(string, ...any) (*sql.Rows, error)
|
||||
}, query string, args ...any) ([]string, error) {
|
||||
rows, err := conn.Query("explain query plan "+query, args...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("explain query plan failed for order by %q: %w", orderBy, err)
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var details []string
|
||||
for rows.Next() {
|
||||
var id, parent, notUsed int
|
||||
var detail string
|
||||
if err := rows.Scan(&id, &parent, ¬Used, &detail); err != nil {
|
||||
return err
|
||||
if err := rows.Scan(new(int), new(int), new(int), &detail); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
details = append(details, detail)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
return details, rows.Err()
|
||||
}
|
||||
|
||||
func checkSortUsesIndex(conn *sql.DB, table, orderBy string) error {
|
||||
details, err := queryPlan(conn, fmt.Sprintf("select * from %s order by %s limit 15", table, orderBy))
|
||||
if err != nil {
|
||||
return fmt.Errorf("explain query plan failed for order by %q: %w", orderBy, err)
|
||||
}
|
||||
if slices.ContainsFunc(details, fullTempBTreeSort.MatchString) {
|
||||
return fmt.Errorf("no index satisfies ORDER BY %s - plan: %v", orderBy, details)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user