mirror of
https://github.com/navidrome/navidrome.git
synced 2026-10-08 18:37:09 +02:00
* refactor(persistence): adopt generic deluan/rest repository API Pin deluan/rest to the refactor branch. REST-facing repository methods take a context and return typed values. Drop DataStore.Resource and ResourceRepository; the native API names typed repositories directly through a per-request adapter that later commits remove. * refactor(persistence): base repository helpers take a context * refactor(persistence): LibraryRepository takes a context per call * refactor(persistence): PropertyRepository takes a context per call * refactor(persistence): UserPropsRepository takes a context per call * refactor(persistence): TranscodingRepository takes a context per call * refactor(persistence): ShareRepository takes a context per call * refactor(persistence): PlayerRepository takes a context per call * refactor(persistence): RadioRepository takes a context per call * refactor(persistence): PlayQueueRepository takes a context per call * refactor(persistence): Tag and Genre repositories take a context per call * refactor(persistence): PluginRepository takes a context per call * refactor(persistence): Scrobble repositories take a context per call * refactor(persistence): FolderRepository takes a context per call * refactor(persistence): Artwork repositories take a context per call * refactor(persistence): UserRepository takes a context per call * refactor(persistence): ArtistRepository takes a context per call ReadAll no longer rewrites the shared sort mappings for the role filter; it works on a per-call copy. * test(persistence): assert artist role sort sanitization in ReadAll * refactor(persistence): AlbumRepository takes a context per call * test(persistence): pass the test context to album repository helpers * refactor(persistence): MediaFileRepository takes a context per call * refactor(persistence): Playlist repositories take a context per call * refactor(persistence): build all repositories once per store * refactor(core): REST repository wrappers are built once * refactor(persistence): repositories are stateless Remove the context field from the base repository and the per-request REST adapter. Enable the containedctx linter so no repository can hold a request context again. * chore(lint): skip containedctx in test files * refactor: share simplifications from the stateless repositories sweep Add deleteOwnedAll on sqlRepository and use it in player/share Delete to remove the duplicated bulk-delete loop; have Share.Repository() return model.ShareRepository so subsonic sharing.go drops its repeated type assertions. * chore(core): assert REST wrappers implement Persistable * chore: reformat imports * perf(persistence): build repositories on first use Each transaction store used to construct all 21 repositories up front, paying for filter and sort mapping setup the block never touched. Fields are now sync.OnceValue thunks, so a store only builds what it uses. * fix(persistence): clean plugin references per deleted user A bulk user delete that fails on a later id had already removed the earlier rows but skipped their plugin cleanup. Cleanup now runs right after each successful delete. * fix(core): unload disabled plugins even when a user delete fails A bulk delete can fail on a later id after earlier users were removed and their plugins auto-disabled. The wrapper returned before unloading, leaving those plugins running until the next successful delete or a restart. * chore(deps): pin deluan/rest to v1.0.1 Replaces the pseudo-version of the refactor branch with the tagged release. REST error messages now name the bare type (Artist, not model.Artist). * test: use the spec context instead of context.Background() Replace the context.Background()/context.TODO() calls this branch added to tests with the spec's ctx, GinkgoT().Context(), or t/b.Context(), so repository calls are bound to the running spec's lifetime. * test: declare the spec context once per Describe Set ctx from GinkgoT().Context() first in each top-level BeforeEach and reuse it, building user contexts on top of it instead of repeating inline calls.
142 lines
5.5 KiB
Go
142 lines
5.5 KiB
Go
package persistence
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
. "github.com/Masterminds/squirrel"
|
|
"github.com/google/uuid"
|
|
"github.com/navidrome/navidrome/conf"
|
|
"github.com/navidrome/navidrome/model"
|
|
"github.com/navidrome/navidrome/utils/str"
|
|
)
|
|
|
|
func formatFullText(text ...string) string {
|
|
fullText := str.SanitizeStrings(text...)
|
|
return " " + fullText
|
|
}
|
|
|
|
// searchConfig holds per-repository constants for doSearch.
|
|
type searchConfig struct {
|
|
NaturalOrder string // ORDER BY for empty-query results (e.g. "album.rowid")
|
|
OrderBy []string // ORDER BY for text search results (e.g. ["name"])
|
|
MBIDFields []string // columns to match when query is a UUID
|
|
// LibraryFilter overrides the default applyLibraryFilter for the rowid Phase 1, for entities whose
|
|
// library access goes through a junction table (e.g. artist → library_artist). It MUST be join-free
|
|
// (Phase 1 has no DISTINCT, so a fan-out JOIN would corrupt offset pagination). See [artistLibraryFilter].
|
|
LibraryFilter func(sq SelectBuilder) SelectBuilder
|
|
}
|
|
|
|
// searchStrategy defines how to execute a text search against a repository table.
|
|
// options carries filters and pagination that must reach all query phases,
|
|
// including FTS Phase 1 which builds its own query outside sq.
|
|
type searchStrategy interface {
|
|
Sqlizer
|
|
execute(ctx context.Context, r sqlRepository, sq SelectBuilder, dest any, cfg searchConfig, options model.QueryOptions) error
|
|
}
|
|
|
|
// getSearchStrategy returns the appropriate search strategy based on config and query content.
|
|
// Returns nil when the query produces no searchable tokens.
|
|
func getSearchStrategy(tableName, query string) searchStrategy {
|
|
if conf.Server.Search.Backend == "legacy" || conf.Server.Search.FullString {
|
|
return newLegacySearch(tableName, query)
|
|
}
|
|
if containsCJK(query) {
|
|
return newLikeSearch(tableName, query)
|
|
}
|
|
return newFTSSearch(tableName, query)
|
|
}
|
|
|
|
// doSearch dispatches a search query: empty → natural order, UUID → MBID match,
|
|
// otherwise delegates to getSearchStrategy. sq must already have LIMIT/OFFSET set
|
|
// via newSelect(options...). options is forwarded so FTS Phase 1 can apply the same
|
|
// filters and pagination independently.
|
|
func (r sqlRepository) doSearch(ctx context.Context, sq SelectBuilder, q string, results any, cfg searchConfig, options model.QueryOptions) error {
|
|
q = strings.TrimSpace(q)
|
|
q = strings.TrimSuffix(q, "*")
|
|
|
|
sq = sq.Where(Eq{r.tableName + ".missing": false})
|
|
|
|
// Empty query (OpenSubsonic `search3?query=""`) — return all in natural order.
|
|
if q == "" || q == `""` {
|
|
rowidCore := Select(r.tableName + ".rowid").From(r.tableName).OrderBy(cfg.NaturalOrder)
|
|
return r.executeTwoPhase(ctx, sq, results, rowidCore, cfg, options)
|
|
}
|
|
|
|
// MBID search: if query is a valid UUID, search by MBID fields instead
|
|
if uuid.Validate(q) == nil && len(cfg.MBIDFields) > 0 {
|
|
sq = sq.Where(mbidExpr(r.tableName, q, cfg.MBIDFields...))
|
|
return r.queryAll(ctx, sq, results)
|
|
}
|
|
|
|
// Min-length guard: single-character queries are too broad for search3.
|
|
// This check lives here (not in the strategies) so that fullTextFilter
|
|
// (REST filter path) can still use single-character queries.
|
|
if len(q) < 2 {
|
|
return nil
|
|
}
|
|
|
|
strategy := getSearchStrategy(r.tableName, q)
|
|
if strategy == nil {
|
|
return nil
|
|
}
|
|
|
|
return strategy.execute(ctx, r, sq, results, cfg, options)
|
|
}
|
|
|
|
// executeTwoPhase runs a search in two phases:
|
|
// - Phase 1: rowidCore (strategy-specific FROM/JOINs and ORDER BY) plus the shared search
|
|
// contract applied here — non-missing rows only, library access, options.Filters, and
|
|
// pagination. Keeping Phase 1 free of the full SELECT's JOINs lets SQLite paginate via a
|
|
// covering index; with those JOINs, large offsets degrade to O(offset) join probes —
|
|
// multi-second responses on 100k+ libraries.
|
|
// - Phase 2: full SELECT with all JOINs, scoped to Phase 1's rowid page.
|
|
func (r sqlRepository) executeTwoPhase(ctx context.Context, sq SelectBuilder, results any, rowidCore SelectBuilder, cfg searchConfig, options model.QueryOptions) error {
|
|
rowidQuery := rowidCore.
|
|
Where(Eq{r.tableName + ".missing": false})
|
|
if options.Max > 0 {
|
|
rowidQuery = rowidQuery.Limit(uint64(options.Max))
|
|
}
|
|
if options.Offset > 0 {
|
|
rowidQuery = rowidQuery.Offset(uint64(options.Offset))
|
|
}
|
|
if cfg.LibraryFilter != nil {
|
|
rowidQuery = cfg.LibraryFilter(rowidQuery)
|
|
} else {
|
|
rowidQuery = r.applyLibraryFilter(ctx, rowidQuery)
|
|
}
|
|
if options.Filters != nil {
|
|
rowidQuery = rowidQuery.Where(options.Filters)
|
|
}
|
|
return r.hydrateRowidPage(ctx, sq, rowidQuery, results)
|
|
}
|
|
|
|
// hydrateRowidPage joins sq to the ordered rowid set produced by rowidQuery, preserving its
|
|
// ordering. rowidQuery must handle pagination itself; sq's LIMIT/OFFSET are stripped.
|
|
func (r sqlRepository) hydrateRowidPage(ctx context.Context, sq SelectBuilder, rowidQuery SelectBuilder, results any) error {
|
|
rowidSQL, rowidArgs, err := rowidQuery.ToSql()
|
|
if err != nil {
|
|
return fmt.Errorf("building rowid query: %w", err)
|
|
}
|
|
sq = sq.RemoveLimit().RemoveOffset()
|
|
rankedSubquery := fmt.Sprintf(
|
|
"(SELECT rowid as _rid, row_number() OVER () AS _rn FROM (%s)) AS _ranked",
|
|
rowidSQL,
|
|
)
|
|
sq = sq.Join(rankedSubquery+" ON "+r.tableName+".rowid = _ranked._rid", rowidArgs...)
|
|
sq = sq.OrderBy("_ranked._rn")
|
|
return r.queryAll(ctx, sq, results)
|
|
}
|
|
|
|
func mbidExpr(tableName, mbid string, mbidFields ...string) Sqlizer {
|
|
if uuid.Validate(mbid) != nil || len(mbidFields) == 0 {
|
|
return nil
|
|
}
|
|
mbid = strings.ToLower(mbid)
|
|
var cond []Sqlizer
|
|
for _, mbidField := range mbidFields {
|
|
cond = append(cond, Eq{tableName + "." + mbidField: mbid})
|
|
}
|
|
return Or(cond)
|
|
}
|