Plans 013 and 014, the album page that prompted them, and the smaller fixes they turned up. Changelog, largest first. ## The local library is shaped like files, not like MusicBrainz `audio_files` carries its own tags and points at `albums` and `artists`; `file_genres` is the one real many-to-many. `recordings`, `release_group_recordings`, `artist_credit`, `artist_credit_artist`, `recording_genres`, `release_groups` and `release_to_rg` are gone from the local side, and with them a six-way join in every read, a `MIN(release_group_id)` subquery in eleven queries and a first-credited-artist subquery in nine. Measured on a real 25,966-file library, every many-to-many that model expressed was 1:1 in the data. - Ownership is a file. `GetFilePathsByRecordingMBIDs`, `LibraryMBIDIndex.CheckMBIDs`, `collectLibraryEntities` and `pruneStaleLocalCrossReferences` all join `audio_files`, so the 812 orphaned recordings, 216 release groups and 260 artists that library carried are now structurally impossible. - One projection: every track query selects from the `track_metadata` view, one row type, one mapper. Nine hand-rolled copies had drifted far enough to report different years on different screens. - `library_id = 0` means every library, so each list query exists once instead of scoped and unscoped with a branch at every call site. - No migration chain. `sql/schemas/` is the one description of the shape; `sql/migrations/`, `applyMigrations` and `schema_migrations` are squashed away, along with the drift between them that had sqlc generating against a stale schema. - `database.InsertTestTrack` is the one test seeder; twenty test files had been assembling the old FK chain each in its own order. ## The catalog stores its ids as bytes `explore_index`'s three 36-char MBID columns and its entity-type text are 16 raw bytes and a small integer. The table and its six indexes go 780 MB to 405 MB on a real 2,052,200-row catalog, which is why a fresh install is ~0.6 GB rather than ~1.0 GB. - `backend/explore/mbid.go` is the only place the encoding is known; everything above it speaks dashed strings. - `CHECK(length(mbid) = 16)` makes a stringly write fail at the insert rather than silently returning no rows, since SQLite does not coerce between TEXT and BLOB. - The importer asks the artifact what encoding it carries and converts on the way in, so the artifact already published keeps working and no format bump is needed. - `indexRowColumns`/`scanIndexRow` replace four copies of a 22-column list, and `TestStoredEncodingRoundTrips` sweeps every read path. ## An album page that says how much of the album is yours - One question, asked once: is there a file. `filePaths` is filled by a single batched lookup when the tracklist settles, and the badge, the Play count, the dimmed rows and every menu item read it — replacing four claims of decreasing confidence that could show a green tick on an album whose every action did nothing. - Play, Play 7 of 12, or no play button at all. - `total_tracks` on `explore_index` (~2 bytes over 400,677 release groups) and on `audio_files` from tags that have always carried it: a complete MBID-matched album now makes no catalog call at all, where it used to spend the most expensive request the app makes. - A merged cluster shows the running order the most releases agree on, and the version list marks the release you own rather than standing a synthetic entry in for it. - `AlbumReleasesFailed`: a slow fetch is no longer reported as a failed one by a 12-second timer. - Rows not in the library are dimmed in place (with `aria-disabled`) instead of the owned ones wearing a green tick and a legend. ## Caches and cover art get ceilings - Only the three tiers of a cover are stored; the full-resolution copy nothing rendered was 1,134 MB of a 1.4 GB covers directory. - One artist portrait is downloaded and the rest are remembered as URLs — 4.1 GB of a 5.3 GB cache was candidates no code path reads. - `browsedArtBudget` and `httpCacheBudget` bound what an age cannot: the same install held art for 5,770 artists in a 1,301-artist library. - `OrphanedArtistImagesJob` joined a bare MBID onto a sharded directory, so it deleted the rows that were the only record of the files it left behind. `explore.ArtistImageDir` is that layout's one definition now. ## The autotag queue asks whether there is work `tagging_items` was a row per album folder, not a queue, and no query read the `tag_status` column that held the answer. The four queue queries ask the files, which matters most where it is least visible: `startPrefetch` was scoring every album in a tagged library against MusicBrainz. ## Phantom playlist tracks resolve in place An M3U8 imported before its files leaves phantom rows; they now match by path and fall back to position, keep their place in the playlist when resolved, and pair best-first so two phantoms cannot claim the same file. ## Playing a track plays the list it is in Double-click, and Play on a single row's menu, queue the list as displayed with `startIndex` on that row — the album page and the track list used to queue one track and discard the album around it. A multi-row selection still plays exactly itself. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AfVYUVExXsx1nSWrXN8mAh
275 lines
6.9 KiB
Go
275 lines
6.9 KiB
Go
package database
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"log/slog"
|
|
"path/filepath"
|
|
"sync/atomic"
|
|
"testing"
|
|
|
|
_ "modernc.org/sqlite" // Register sqlite driver.
|
|
|
|
"yellowjacket/backend/database/sql/sqlcgen"
|
|
)
|
|
|
|
// NewTestDB returns an in-memory SQLite database shaped like the real
|
|
// one: a single-writer handle and a separate query-only read pool over
|
|
// the same database, built by the same applySchema production uses.
|
|
//
|
|
// The two handles matter. The test DB used to be one shared connection
|
|
// with readDB nil, so `reader()` returned the *writer* — which is how a
|
|
// query-shaped write (`INSERT ... RETURNING` through QueryContext)
|
|
// passed every test and then failed for a user with "attempt to write a
|
|
// readonly database". `TestNoWritesOnTheReadPool` had to walk the source
|
|
// tree to catch what a test could not.
|
|
//
|
|
// A shared-cache in-memory database is what lets two handles see one
|
|
// database; the connections are capped the way production caps them.
|
|
// It is closed when the test completes via t.Cleanup.
|
|
func NewTestDB(t *testing.T) *DB {
|
|
t.Helper()
|
|
|
|
// A per-test name, so parallel tests do not share a database.
|
|
dsn := fmt.Sprintf(
|
|
"file:testdb%d?mode=memory&cache=shared&_pragma=busy_timeout(5000)",
|
|
testDBSeq.Add(1),
|
|
)
|
|
|
|
db, err := sql.Open("sqlite", dsn)
|
|
if err != nil {
|
|
t.Fatalf("could not open test database: %v", err)
|
|
}
|
|
|
|
db.SetMaxOpenConns(1)
|
|
|
|
ctx := t.Context()
|
|
|
|
if err := applyPRAGMAs(ctx, db); err != nil {
|
|
t.Fatalf("could not apply PRAGMAs: %v", err)
|
|
}
|
|
|
|
// The same call production uses, so a test database and a real one
|
|
// cannot diverge.
|
|
if err := applySchema(ctx, db); err != nil {
|
|
t.Fatalf("could not apply schema: %v", err)
|
|
}
|
|
|
|
// Insert a sentinel library row at id=0 so audio_files inserts
|
|
// using the DEFAULT library_id=0 satisfy the FK constraint.
|
|
if _, err := db.ExecContext(
|
|
ctx,
|
|
"INSERT INTO libraries (id, name, path) VALUES (0, 'Test', '/test')",
|
|
); err != nil {
|
|
t.Fatalf("could not insert test library: %v", err)
|
|
}
|
|
|
|
readDB, err := sql.Open("sqlite", dsn+"&_pragma=query_only(true)")
|
|
if err != nil {
|
|
t.Fatalf("could not open test read pool: %v", err)
|
|
}
|
|
|
|
readDB.SetMaxOpenConns(readPoolConns)
|
|
|
|
t.Cleanup(func() {
|
|
_ = readDB.Close()
|
|
_ = db.Close()
|
|
})
|
|
|
|
return &DB{
|
|
db: db,
|
|
readDB: readDB,
|
|
Ctx: ctx,
|
|
Queries: sqlcgen.New(db),
|
|
ReadQueries: sqlcgen.New(readDB),
|
|
logger: slog.Default(),
|
|
}
|
|
}
|
|
|
|
// testDBSeq names each test database uniquely, so parallel tests do not
|
|
// share one through the shared cache.
|
|
var testDBSeq atomic.Int64
|
|
|
|
// NewTestDBWithLibrary returns a test DB with a library row
|
|
// pre-inserted. Returns the DB and the library ID.
|
|
func NewTestDBWithLibrary(
|
|
t *testing.T,
|
|
name, libPath string,
|
|
) (*DB, int64) {
|
|
t.Helper()
|
|
|
|
db := NewTestDB(t)
|
|
|
|
lib, err := db.Queries.CreateLibrary(
|
|
db.Ctx,
|
|
sqlcgen.CreateLibraryParams{
|
|
Name: name,
|
|
Path: libPath,
|
|
},
|
|
)
|
|
if err != nil {
|
|
t.Fatalf("could not create test library: %v", err)
|
|
}
|
|
|
|
return db, lib.ID
|
|
}
|
|
|
|
// TestTrack describes one file to seed into a test database. Zero
|
|
// values are fine: only FilePath is required.
|
|
type TestTrack struct {
|
|
FilePath string
|
|
Title string
|
|
Artist string
|
|
ArtistMBID string
|
|
Album string
|
|
AlbumArtist string
|
|
AlbumMBID string
|
|
RecordingMBID string
|
|
Genres []string
|
|
TrackNumber int64
|
|
DiscNumber int64
|
|
TotalTracks int64
|
|
Year int64
|
|
LengthMs int64
|
|
LibraryID int64
|
|
PlayCount int64
|
|
TagStatus string
|
|
GroupKey string
|
|
// SkipSearchIndex leaves the file out of the FTS index, for the
|
|
// tests that assert on a rebuild putting it there.
|
|
SkipSearchIndex bool
|
|
}
|
|
|
|
// InsertTestTrack seeds one file, with the artist and album its tags
|
|
// name, and returns the audio_files id.
|
|
//
|
|
// There is one of these because there is one shape. Twenty test files
|
|
// used to carry their own seeder, each inserting a recording, an artist
|
|
// credit, a credit-artist link and a release-group link in the right
|
|
// order - which is exactly the ceremony the schema change removed, and
|
|
// exactly why every one of those seeders was subtly different.
|
|
func InsertTestTrack(t *testing.T, db *DB, tr TestTrack) int64 {
|
|
t.Helper()
|
|
|
|
if tr.Title == "" {
|
|
tr.Title = "Test Track"
|
|
}
|
|
|
|
if tr.Artist == "" {
|
|
tr.Artist = "Test Artist"
|
|
}
|
|
|
|
if tr.TagStatus == "" {
|
|
tr.TagStatus = "untagged"
|
|
}
|
|
|
|
artist, err := db.Queries.UpsertArtist(db.Ctx, sqlcgen.UpsertArtistParams{
|
|
Name: tr.Artist,
|
|
Mbid: nullString(tr.ArtistMBID),
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("seed artist: %v", err)
|
|
}
|
|
|
|
artistID := sql.NullInt64{Int64: artist.ID, Valid: true}
|
|
albumID := sql.NullInt64{}
|
|
|
|
if tr.Album != "" {
|
|
credit := tr.AlbumArtist
|
|
if credit == "" {
|
|
credit = tr.Artist
|
|
}
|
|
|
|
album, albErr := db.Queries.UpsertAlbum(db.Ctx, sqlcgen.UpsertAlbumParams{
|
|
Name: tr.Album,
|
|
ArtistCredit: credit,
|
|
ArtistID: artistID,
|
|
Year: nullInt64(tr.Year),
|
|
})
|
|
if albErr != nil {
|
|
t.Fatalf("seed album: %v", albErr)
|
|
}
|
|
|
|
if tr.AlbumMBID != "" {
|
|
if err := db.Queries.SetAlbumMBID(db.Ctx, sqlcgen.SetAlbumMBIDParams{
|
|
Mbid: nullString(tr.AlbumMBID),
|
|
ID: album.ID,
|
|
}); err != nil {
|
|
t.Fatalf("seed album mbid: %v", err)
|
|
}
|
|
}
|
|
|
|
albumID = sql.NullInt64{Int64: album.ID, Valid: true}
|
|
}
|
|
|
|
af, err := db.Queries.CreateAudioFile(db.Ctx, sqlcgen.CreateAudioFileParams{
|
|
FilePath: tr.FilePath,
|
|
LibraryID: tr.LibraryID,
|
|
LengthMilliseconds: tr.LengthMs,
|
|
Title: tr.Title,
|
|
ArtistCredit: tr.Artist,
|
|
ArtistID: artistID,
|
|
AlbumID: albumID,
|
|
TrackNumber: nullInt64(tr.TrackNumber),
|
|
DiscNumber: nullInt64(tr.DiscNumber),
|
|
TotalTracks: nullInt64(tr.TotalTracks),
|
|
Year: nullInt64(tr.Year),
|
|
RecordingMbid: nullString(tr.RecordingMBID),
|
|
Basename: filepath.Base(tr.FilePath),
|
|
GroupKey: tr.GroupKey,
|
|
TagStatus: tr.TagStatus,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("seed audio file %q: %v", tr.FilePath, err)
|
|
}
|
|
|
|
for _, name := range tr.Genres {
|
|
g, gErr := db.Queries.UpsertGenre(db.Ctx, name)
|
|
if gErr != nil {
|
|
t.Fatalf("seed genre %q: %v", name, gErr)
|
|
}
|
|
|
|
if err := db.Queries.LinkFileGenre(db.Ctx, sqlcgen.LinkFileGenreParams{
|
|
AudioFileID: af.ID,
|
|
GenreID: g.ID,
|
|
}); err != nil {
|
|
t.Fatalf("seed file genre: %v", err)
|
|
}
|
|
}
|
|
|
|
if tr.PlayCount > 0 {
|
|
if _, err := db.db.ExecContext(db.Ctx,
|
|
"UPDATE audio_files SET play_count = ? WHERE id = ?",
|
|
tr.PlayCount, af.ID,
|
|
); err != nil {
|
|
t.Fatalf("seed play count: %v", err)
|
|
}
|
|
}
|
|
|
|
if !tr.SkipSearchIndex {
|
|
if err := db.InsertSearchIndex(
|
|
af.ID, tr.FilePath, tr.Title, tr.Artist, tr.Album,
|
|
); err != nil {
|
|
t.Fatalf("seed search index: %v", err)
|
|
}
|
|
}
|
|
|
|
return af.ID
|
|
}
|
|
|
|
func nullString(v string) sql.NullString {
|
|
if v == "" {
|
|
return sql.NullString{}
|
|
}
|
|
|
|
return sql.NullString{String: v, Valid: true}
|
|
}
|
|
|
|
func nullInt64(v int64) sql.NullInt64 {
|
|
if v == 0 {
|
|
return sql.NullInt64{}
|
|
}
|
|
|
|
return sql.NullInt64{Int64: v, Valid: true}
|
|
}
|