diff --git a/internal/api/admin_fingerprint_settings.go b/internal/api/admin_fingerprint_settings.go index cf27c54e..69e6351d 100644 --- a/internal/api/admin_fingerprint_settings.go +++ b/internal/api/admin_fingerprint_settings.go @@ -67,7 +67,7 @@ func (h *handlers) handleUpdateFingerprintSettings(w http.ResponseWriter, r *htt AutoResolve: autoResolve, }) if err != nil { - // Validation mirrors migration 0061's CHECKs and names the field. + // Validation mirrors fingerprint_settings's CHECKs and names the field. if errors.Is(err, library.ErrFingerprintSettingOutOfRange) { writeErr(w, apierror.BadRequest("invalid_setting", err.Error())) return diff --git a/internal/api/diagnostics.go b/internal/api/diagnostics.go index dffc6feb..e1425457 100644 --- a/internal/api/diagnostics.go +++ b/internal/api/diagnostics.go @@ -15,7 +15,7 @@ import ( ) // validDiagnosticKinds is the COARSE category whitelist. Mirrors the -// CHECK constraint in migration 0036 — keep both in sync (per the +// CHECK constraint on diagnostic_events.kind — keep both in sync (per the // enum-CHECK-whitelist rule). The finer event discriminator + all // event-specific fields live inside each event's payload, so new event // variants do NOT require a new category here. diff --git a/internal/api/me_recommendation_metrics.go b/internal/api/me_recommendation_metrics.go index 3d2c5fc5..f77d21c4 100644 --- a/internal/api/me_recommendation_metrics.go +++ b/internal/api/me_recommendation_metrics.go @@ -213,7 +213,7 @@ func (h *handlers) handleGetRecommendationMetrics(w http.ResponseWriter, r *http } // pickKindLabels is the display vocabulary for play_events.pick_kind -// values (mirrors the CHECK in migration 0041). Every system mix that +// values (mirrors the CHECK on play_events.pick_kind). Every system mix that // stamps provenance gets its breakdown from this one map — adding a // stamping mix needs no metrics change. var pickKindLabels = map[string]string{ diff --git a/internal/api/me_subsonic_password.go b/internal/api/me_subsonic_password.go index 9f3e1778..bb60b804 100644 --- a/internal/api/me_subsonic_password.go +++ b/internal/api/me_subsonic_password.go @@ -13,7 +13,7 @@ import ( // The Subsonic password is for clients that sign in with Subsonic's t/s // scheme (md5 of the password plus a salt). Checking that needs the password -// itself, so it is stored readable (migration 0003). That is why Minstrel +// itself, so it is stored readable (users.subsonic_password). That is why Minstrel // generates it rather than letting the user choose one: a generated value // can never be a login password reused from somewhere else, so a leaked // users table gives up access to this server's /rest API and nothing more. diff --git a/internal/api/playback_errors.go b/internal/api/playback_errors.go index d736d69a..8eccdcc8 100644 --- a/internal/api/playback_errors.go +++ b/internal/api/playback_errors.go @@ -14,7 +14,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" ) -// Valid `kind` values. Mirrors the CHECK constraint in migration 0032 +// Valid `kind` values. Mirrors playback_errors_kind_check // — keep both lists in sync if you add a kind here, otherwise inserts // pass the handler whitelist and trip the DB constraint instead. var validPlaybackErrorKinds = map[string]struct{}{ diff --git a/internal/db/dbq/acoustid.sql.go b/internal/db/dbq/acoustid.sql.go index 6315d96e..558a1088 100644 --- a/internal/db/dbq/acoustid.sql.go +++ b/internal/db/dbq/acoustid.sql.go @@ -120,8 +120,8 @@ type ListTracksNeedingAcoustIDLookupRow struct { DurationMs int32 } -// AcoustID recording-id lookup. Migration 0069 says what each -// lookup state means. +// AcoustID recording-id lookup. The CHECK on track_acoustid_lookups.state +// lists the lookup states. // The lookup worker's queue: present tracks with no tag MBID and no lookup // since their file last changed. A looked-up id is included once its row is // gone (the file changed), so the new bytes are checked rather than trusted. diff --git a/internal/db/dbq/fingerprint_settings.sql.go b/internal/db/dbq/fingerprint_settings.sql.go index 62086971..4697384a 100644 --- a/internal/db/dbq/fingerprint_settings.sql.go +++ b/internal/db/dbq/fingerprint_settings.sql.go @@ -51,7 +51,7 @@ type UpdateFingerprintSettingsParams struct { AutoResolve bool } -// Whole-row write from the admin card; migration 0061's CHECKs are the backstop +// Whole-row write from the admin card; fingerprint_settings's CHECKs are the backstop // behind the service's own validation. func (q *Queries) UpdateFingerprintSettings(ctx context.Context, arg UpdateFingerprintSettingsParams) (FingerprintSetting, error) { row := q.db.QueryRow(ctx, updateFingerprintSettings, diff --git a/internal/db/dbq/missing_pairs.sql.go b/internal/db/dbq/missing_pairs.sql.go index 408f1e43..c33ab3b3 100644 --- a/internal/db/dbq/missing_pairs.sql.go +++ b/internal/db/dbq/missing_pairs.sql.go @@ -89,7 +89,7 @@ type ListMissingTrackPairsRow struct { // they are different recordings. The caller folds a pair only when each side has // exactly one candidate; anything else is ambiguous and left alone. // -// A slot the duplicate resolver emptied (emptied_at, migration 0095) pairs by +// A slot the duplicate resolver emptied (emptied_at) pairs by // title only with a track added since: the album held no copy of the song as // long as it is, so one already there under the title is another song. func (q *Queries) ListMissingTrackPairs(ctx context.Context) ([]ListMissingTrackPairsRow, error) { diff --git a/internal/db/dbq/normalization_prefs.sql.go b/internal/db/dbq/normalization_prefs.sql.go index 332edb96..2726d2b5 100644 --- a/internal/db/dbq/normalization_prefs.sql.go +++ b/internal/db/dbq/normalization_prefs.sql.go @@ -61,7 +61,7 @@ type UpsertNormalizationPrefsRow struct { UpdatedAt pgtype.Timestamptz } -// Whole-row write from either client; the CHECKs in migration 0067 back the +// Whole-row write from either client; the CHECKs on user_normalization_prefs back the // handler's own validation. func (q *Queries) UpsertNormalizationPrefs(ctx context.Context, arg UpsertNormalizationPrefsParams) (UpsertNormalizationPrefsRow, error) { row := q.db.QueryRow(ctx, upsertNormalizationPrefs, diff --git a/internal/db/dbq/notifications.sql.go b/internal/db/dbq/notifications.sql.go index 4a693e7a..56e350a0 100644 --- a/internal/db/dbq/notifications.sql.go +++ b/internal/db/dbq/notifications.sql.go @@ -463,7 +463,7 @@ type UpdateNotificationEmailSettingsParams struct { BatchWindowMinutes int32 } -// Migration 0074's CHECKs are the backstop behind the service's validation. +// notification_email_settings's CHECKs are the backstop behind the service's validation. func (q *Queries) UpdateNotificationEmailSettings(ctx context.Context, arg UpdateNotificationEmailSettingsParams) (NotificationEmailSetting, error) { row := q.db.QueryRow(ctx, updateNotificationEmailSettings, arg.SummaryHour, arg.BatchWindowMinutes) var i NotificationEmailSetting diff --git a/internal/db/dbq/songs.sql.go b/internal/db/dbq/songs.sql.go index a441f9c6..dba271bb 100644 --- a/internal/db/dbq/songs.sql.go +++ b/internal/db/dbq/songs.sql.go @@ -34,7 +34,7 @@ type LinkTracksAsSongRow struct { } // Song links: copies of one song on different releases share a -// song_key (migration 0076). +// song_key. // Links the tracks into one song, joining any songs they already belong to. // The song keeps the lowest key among them, so linking the same set again // changes nothing. Returns that key and how many tracks moved to it. diff --git a/internal/db/dbq/tracks.sql.go b/internal/db/dbq/tracks.sql.go index 9310f8ed..0407fdc5 100644 --- a/internal/db/dbq/tracks.sql.go +++ b/internal/db/dbq/tracks.sql.go @@ -1021,7 +1021,7 @@ UPDATE tracks ` // Stamps rows the duplicate resolver emptied, whose song the album holds no -// other copy of, with the time they went missing (migration 0095): missing-pair +// other copy of, with the time they went missing (emptied_at): missing-pair // folding then waits for a copy fetched again. func (q *Queries) MarkTracksEmptied(ctx context.Context, ids []pgtype.UUID) error { _, err := q.db.Exec(ctx, markTracksEmptied, ids) diff --git a/internal/db/dbq/users.sql.go b/internal/db/dbq/users.sql.go index d14a016d..5815913f 100644 --- a/internal/db/dbq/users.sql.go +++ b/internal/db/dbq/users.sql.go @@ -572,7 +572,7 @@ type SetSubsonicPasswordParams struct { } // Stores (or clears with NULL) the per-user Subsonic legacy credential used -// for t/s and p auth on /rest/*. Must be plaintext; see migration 0003. Only +// for t/s and p auth on /rest/*. Must be plaintext: t/s auth hashes it with a salt. Only // ever a server-generated value, never the login password. func (q *Queries) SetSubsonicPassword(ctx context.Context, arg SetSubsonicPasswordParams) error { _, err := q.db.Exec(ctx, setSubsonicPassword, arg.ID, arg.SubsonicPassword) diff --git a/internal/db/migrations/0001_init.down.sql b/internal/db/migrations/0001_init.down.sql deleted file mode 100644 index f1ce7100..00000000 --- a/internal/db/migrations/0001_init.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Placeholder down migration — nothing to reverse. -SELECT 1; diff --git a/internal/db/migrations/0001_init.up.sql b/internal/db/migrations/0001_init.up.sql deleted file mode 100644 index 25f4c2ce..00000000 --- a/internal/db/migrations/0001_init.up.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Placeholder to establish the migration runner. Real schema lands in 0002. -SELECT 1; diff --git a/internal/db/migrations/0002_core_library.down.sql b/internal/db/migrations/0002_core_library.down.sql deleted file mode 100644 index e6b4bf3e..00000000 --- a/internal/db/migrations/0002_core_library.down.sql +++ /dev/null @@ -1,5 +0,0 @@ -DROP TABLE IF EXISTS users; -DROP TABLE IF EXISTS tracks; -DROP TABLE IF EXISTS albums; -DROP TABLE IF EXISTS artists; --- pgcrypto left installed; other extensions may depend on it. diff --git a/internal/db/migrations/0002_core_library.up.sql b/internal/db/migrations/0002_core_library.up.sql deleted file mode 100644 index 80cc3fe0..00000000 --- a/internal/db/migrations/0002_core_library.up.sql +++ /dev/null @@ -1,60 +0,0 @@ --- Core library schema: artists, albums, tracks and users. Likes, sessions, --- scrobbling and similarity get tables of their own in later migrations. - -CREATE EXTENSION IF NOT EXISTS "pgcrypto"; - -CREATE TABLE artists ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - name text NOT NULL, - sort_name text NOT NULL, - mbid text, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); -CREATE UNIQUE INDEX artists_mbid_unique ON artists (mbid) WHERE mbid IS NOT NULL; -CREATE INDEX artists_sort_name ON artists (sort_name); - -CREATE TABLE albums ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - title text NOT NULL, - sort_title text NOT NULL, - artist_id uuid NOT NULL REFERENCES artists (id) ON DELETE CASCADE, - release_date date, - mbid text, - cover_art_path text, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); -CREATE UNIQUE INDEX albums_mbid_unique ON albums (mbid) WHERE mbid IS NOT NULL; -CREATE INDEX albums_artist ON albums (artist_id); -CREATE INDEX albums_sort_title ON albums (sort_title); - -CREATE TABLE tracks ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - title text NOT NULL, - album_id uuid NOT NULL REFERENCES albums (id) ON DELETE CASCADE, - artist_id uuid NOT NULL REFERENCES artists (id) ON DELETE CASCADE, - track_number integer, - disc_number integer, - duration_ms integer NOT NULL, - file_path text NOT NULL UNIQUE, - file_size bigint NOT NULL, - file_format text NOT NULL, - bitrate integer, - mbid text, - genre text, - added_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); -CREATE UNIQUE INDEX tracks_mbid_unique ON tracks (mbid) WHERE mbid IS NOT NULL; -CREATE INDEX tracks_album ON tracks (album_id, disc_number, track_number); -CREATE INDEX tracks_artist ON tracks (artist_id); - -CREATE TABLE users ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - username text NOT NULL UNIQUE, - password_hash text NOT NULL, - api_token text NOT NULL UNIQUE, - is_admin boolean NOT NULL DEFAULT false, - created_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0003_subsonic_password.down.sql b/internal/db/migrations/0003_subsonic_password.down.sql deleted file mode 100644 index c46bad35..00000000 --- a/internal/db/migrations/0003_subsonic_password.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users DROP COLUMN IF EXISTS subsonic_password; diff --git a/internal/db/migrations/0003_subsonic_password.up.sql b/internal/db/migrations/0003_subsonic_password.up.sql deleted file mode 100644 index 304e0192..00000000 --- a/internal/db/migrations/0003_subsonic_password.up.sql +++ /dev/null @@ -1,7 +0,0 @@ --- Subsonic's token auth (t = md5(password + salt)) requires the server to --- compute md5 over the user's plaintext password. bcrypt (password_hash) is --- not reversible, so we store a *separate*, opt-in, plaintext credential used --- exclusively for the /rest/* legacy auth path. NULL means the user has not --- opted into Subsonic t/s auth and must use apiKey (OpenSubsonic) instead. - -ALTER TABLE users ADD COLUMN subsonic_password text; diff --git a/internal/db/migrations/0004_sessions.down.sql b/internal/db/migrations/0004_sessions.down.sql deleted file mode 100644 index 0d6115ac..00000000 --- a/internal/db/migrations/0004_sessions.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS sessions_user_id_idx; -DROP TABLE IF EXISTS sessions; diff --git a/internal/db/migrations/0004_sessions.up.sql b/internal/db/migrations/0004_sessions.up.sql deleted file mode 100644 index cac6544a..00000000 --- a/internal/db/migrations/0004_sessions.up.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Session tokens authenticate /api/* requests. We store sha256(token) so a --- read-only DB leak doesn't grant active sessions; the raw token lives only --- in the client's cookie (web) or bearer header (native clients). --- --- last_seen_at and user_agent (captured at issue time) are for an "active --- sessions" list. - -CREATE TABLE sessions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - token_hash bytea NOT NULL UNIQUE, - user_agent text NOT NULL DEFAULT '', - created_at timestamptz NOT NULL DEFAULT now(), - last_seen_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX sessions_user_id_idx ON sessions (user_id); diff --git a/internal/db/migrations/0005_events.down.sql b/internal/db/migrations/0005_events.down.sql deleted file mode 100644 index 96175523..00000000 --- a/internal/db/migrations/0005_events.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE IF EXISTS skip_events; -DROP TABLE IF EXISTS play_events; -DROP TABLE IF EXISTS play_sessions; diff --git a/internal/db/migrations/0005_events.up.sql b/internal/db/migrations/0005_events.up.sql deleted file mode 100644 index bcfc20b0..00000000 --- a/internal/db/migrations/0005_events.up.sql +++ /dev/null @@ -1,45 +0,0 @@ --- Listening telemetry: play_sessions, play_events, skip_events. --- The table is named play_sessions (not sessions — that table already --- exists from migration 0004 and holds HTTP auth sessions). Listening --- sessions are an entirely separate concept. --- --- session_vector_at_play is nullable: plays are recorded before the --- recommendation engine fills it. - -CREATE TABLE play_sessions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - started_at timestamptz NOT NULL, - ended_at timestamptz, - last_event_at timestamptz NOT NULL, - track_count integer NOT NULL DEFAULT 0, - client_id text -); -CREATE INDEX play_sessions_user_last_event_idx ON play_sessions (user_id, last_event_at DESC); - -CREATE TABLE play_events ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - session_id uuid NOT NULL REFERENCES play_sessions(id) ON DELETE CASCADE, - started_at timestamptz NOT NULL, - ended_at timestamptz, - duration_played_ms integer, - completion_ratio double precision, - was_skipped boolean NOT NULL DEFAULT false, - client_id text, - session_vector_at_play jsonb, - scrobbled_at timestamptz -); -CREATE INDEX play_events_user_started_idx ON play_events (user_id, started_at DESC); -CREATE INDEX play_events_user_track_idx ON play_events (user_id, track_id); - -CREATE TABLE skip_events ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - session_id uuid NOT NULL REFERENCES play_sessions(id) ON DELETE CASCADE, - skipped_at timestamptz NOT NULL, - position_ms integer NOT NULL -); -CREATE INDEX skip_events_user_skipped_idx ON skip_events (user_id, skipped_at DESC); diff --git a/internal/db/migrations/0006_likes.down.sql b/internal/db/migrations/0006_likes.down.sql deleted file mode 100644 index b3ca0692..00000000 --- a/internal/db/migrations/0006_likes.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE IF EXISTS general_likes_artists; -DROP TABLE IF EXISTS general_likes_albums; -DROP TABLE IF EXISTS general_likes; diff --git a/internal/db/migrations/0006_likes.up.sql b/internal/db/migrations/0006_likes.up.sql deleted file mode 100644 index 9f34df31..00000000 --- a/internal/db/migrations/0006_likes.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Likes: three tables, one per entity type. general_likes was track-only; --- albums and artists get the same shape for Subsonic star/unstar. - -CREATE TABLE general_likes ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - liked_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, track_id) -); -CREATE INDEX general_likes_user_liked_at_idx ON general_likes (user_id, liked_at DESC); - -CREATE TABLE general_likes_albums ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - album_id uuid NOT NULL REFERENCES albums(id) ON DELETE CASCADE, - liked_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, album_id) -); -CREATE INDEX general_likes_albums_user_liked_at_idx ON general_likes_albums (user_id, liked_at DESC); - -CREATE TABLE general_likes_artists ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - artist_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - liked_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, artist_id) -); -CREATE INDEX general_likes_artists_user_liked_at_idx ON general_likes_artists (user_id, liked_at DESC); diff --git a/internal/db/migrations/0007_contextual_likes.down.sql b/internal/db/migrations/0007_contextual_likes.down.sql deleted file mode 100644 index 942b4de2..00000000 --- a/internal/db/migrations/0007_contextual_likes.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS contextual_likes; diff --git a/internal/db/migrations/0007_contextual_likes.up.sql b/internal/db/migrations/0007_contextual_likes.up.sql deleted file mode 100644 index 69f14ae9..00000000 --- a/internal/db/migrations/0007_contextual_likes.up.sql +++ /dev/null @@ -1,28 +0,0 @@ --- contextual_likes captures a per-session-context snapshot at the time of each --- like. The recommendation engine uses these rows to compute --- contextual_match_score per (current session, candidate track). --- --- Multiple rows per (user, track) are allowed and expected — each row --- represents a like in a specific session context. Soft-deleted rows --- remain in the table (deleted_at populated) but are filtered out of the --- engine's queries via the partial index. Re-liking a previously-unliked --- track adds a NEW row (does not undelete the old one). - -CREATE TABLE contextual_likes ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - liked_at timestamptz NOT NULL DEFAULT now(), - deleted_at timestamptz, - session_vector jsonb, - session_id uuid REFERENCES play_sessions(id) ON DELETE SET NULL -); - --- Hot path for both the engine's lookups and the soft-delete UPDATE. -CREATE INDEX contextual_likes_active_idx - ON contextual_likes (user_id, track_id) - WHERE deleted_at IS NULL; - --- For the engine's vector similarity queries. -CREATE INDEX contextual_likes_vector_idx - ON contextual_likes USING gin (session_vector); diff --git a/internal/db/migrations/0008_scrobble.down.sql b/internal/db/migrations/0008_scrobble.down.sql deleted file mode 100644 index c5721872..00000000 --- a/internal/db/migrations/0008_scrobble.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE IF EXISTS scrobble_queue; -ALTER TABLE users DROP COLUMN IF EXISTS listenbrainz_enabled; -ALTER TABLE users DROP COLUMN IF EXISTS listenbrainz_token; diff --git a/internal/db/migrations/0008_scrobble.up.sql b/internal/db/migrations/0008_scrobble.up.sql deleted file mode 100644 index 32f3e15a..00000000 --- a/internal/db/migrations/0008_scrobble.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Outbound ListenBrainz scrobble worker. --- Per-user LB config (plaintext token; users rotate via /settings if leaked). --- scrobble_queue is a work list, not a log: successfully-sent rows are --- DELETEd by the worker (the canonical record stays in --- play_events.scrobbled_at). Only `pending` and `failed` states exist. - -ALTER TABLE users - ADD COLUMN listenbrainz_token TEXT NULL, - ADD COLUMN listenbrainz_enabled BOOLEAN NOT NULL DEFAULT FALSE; - -CREATE TABLE scrobble_queue ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - play_event_id uuid NOT NULL REFERENCES play_events(id) ON DELETE CASCADE, - status TEXT NOT NULL CHECK (status IN ('pending', 'failed')), - attempts INTEGER NOT NULL DEFAULT 0, - next_attempt_at timestamptz NOT NULL DEFAULT now(), - last_error TEXT NULL, - enqueued_at timestamptz NOT NULL DEFAULT now(), - UNIQUE (play_event_id) -); - --- Hot path for the worker's per-tick query. -CREATE INDEX scrobble_queue_pending_idx - ON scrobble_queue (next_attempt_at) - WHERE status = 'pending'; diff --git a/internal/db/migrations/0009_similarity.down.sql b/internal/db/migrations/0009_similarity.down.sql deleted file mode 100644 index b6718a77..00000000 --- a/internal/db/migrations/0009_similarity.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS artist_similarity; -DROP TABLE IF EXISTS track_similarity; diff --git a/internal/db/migrations/0009_similarity.up.sql b/internal/db/migrations/0009_similarity.up.sql deleted file mode 100644 index 382631c2..00000000 --- a/internal/db/migrations/0009_similarity.up.sql +++ /dev/null @@ -1,33 +0,0 @@ --- ListenBrainz similarity ingest. Two symmetric tables — tracks and --- artists — both keyed by (a_id, b_id, source) so the schema reserves room --- for additional similarity sources (musicbrainz_tag, user_cooccurrence) --- alongside listenbrainz. M4b only writes 'listenbrainz' rows. --- --- The (a_id, score DESC) index satisfies M4c's hot path: "for seed S, give --- me top-N similar tracks/artists descending by score." - -CREATE TABLE track_similarity ( - track_a_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - track_b_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - score DOUBLE PRECISION NOT NULL, - source TEXT NOT NULL CHECK (source IN ('listenbrainz', 'musicbrainz_tag', 'user_cooccurrence')), - fetched_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (track_a_id, track_b_id, source), - CHECK (track_a_id <> track_b_id) -); - -CREATE INDEX track_similarity_a_score_idx - ON track_similarity (track_a_id, score DESC); - -CREATE TABLE artist_similarity ( - artist_a_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - artist_b_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - score DOUBLE PRECISION NOT NULL, - source TEXT NOT NULL CHECK (source IN ('listenbrainz', 'musicbrainz_tag', 'user_cooccurrence')), - fetched_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (artist_a_id, artist_b_id, source), - CHECK (artist_a_id <> artist_b_id) -); - -CREATE INDEX artist_similarity_a_score_idx - ON artist_similarity (artist_a_id, score DESC); diff --git a/internal/db/migrations/0010_lidarr.down.sql b/internal/db/migrations/0010_lidarr.down.sql deleted file mode 100644 index a6aabe02..00000000 --- a/internal/db/migrations/0010_lidarr.down.sql +++ /dev/null @@ -1,8 +0,0 @@ -DROP INDEX IF EXISTS lidarr_requests_album_mbid_idx; -DROP INDEX IF EXISTS lidarr_requests_artist_mbid_idx; -DROP INDEX IF EXISTS lidarr_requests_status_idx; -DROP INDEX IF EXISTS lidarr_requests_user_id_idx; -DROP TABLE IF EXISTS lidarr_requests; -DROP TYPE IF EXISTS lidarr_request_kind; -DROP TYPE IF EXISTS lidarr_request_status; -DROP TABLE IF EXISTS lidarr_config; diff --git a/internal/db/migrations/0010_lidarr.up.sql b/internal/db/migrations/0010_lidarr.up.sql deleted file mode 100644 index b2586ed1..00000000 --- a/internal/db/migrations/0010_lidarr.up.sql +++ /dev/null @@ -1,63 +0,0 @@ --- Lidarr integration. Two tables: --- --- lidarr_config — singleton (CHECK id=1) holding the Lidarr --- connection. enabled=false is the unconfigured state. --- --- lidarr_requests — per-request lifecycle row created by users at --- /discover, transitioned by admin at /admin/requests, and matched --- back to library tracks by the reconciler worker. Three matched_*_id --- FKs (one per kind) instead of polymorphic — clean SQL, ON DELETE --- SET NULL preserves audit even if the matched track is later removed. - -CREATE TABLE lidarr_config ( - id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), - enabled boolean NOT NULL DEFAULT false, - base_url text, - api_key text, - default_quality_profile_id int, - default_root_folder_path text, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -INSERT INTO lidarr_config (id, enabled) VALUES (1, false); - -CREATE TYPE lidarr_request_status AS ENUM ( - 'pending', 'approved', 'rejected', 'completed', 'failed' -); -CREATE TYPE lidarr_request_kind AS ENUM ('artist', 'album', 'track'); - -CREATE TABLE lidarr_requests ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - status lidarr_request_status NOT NULL DEFAULT 'pending', - kind lidarr_request_kind NOT NULL, - - lidarr_artist_mbid text NOT NULL, - lidarr_album_mbid text, - lidarr_track_mbid text, - artist_name text NOT NULL, - album_title text, - track_title text, - - quality_profile_id int, - root_folder_path text, - - decided_at timestamptz, - decided_by uuid REFERENCES users(id) ON DELETE SET NULL, - notes text, - - completed_at timestamptz, - matched_track_id uuid REFERENCES tracks(id) ON DELETE SET NULL, - matched_album_id uuid REFERENCES albums(id) ON DELETE SET NULL, - matched_artist_id uuid REFERENCES artists(id) ON DELETE SET NULL, - - requested_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX lidarr_requests_user_id_idx ON lidarr_requests (user_id); -CREATE INDEX lidarr_requests_status_idx ON lidarr_requests (status); -CREATE INDEX lidarr_requests_artist_mbid_idx ON lidarr_requests (lidarr_artist_mbid); -CREATE INDEX lidarr_requests_album_mbid_idx ON lidarr_requests (lidarr_album_mbid) - WHERE lidarr_album_mbid IS NOT NULL; diff --git a/internal/db/migrations/0011_lidarr_quarantine.down.sql b/internal/db/migrations/0011_lidarr_quarantine.down.sql deleted file mode 100644 index bd086c54..00000000 --- a/internal/db/migrations/0011_lidarr_quarantine.down.sql +++ /dev/null @@ -1,7 +0,0 @@ -DROP INDEX IF EXISTS lidarr_quarantine_actions_created_idx; -DROP INDEX IF EXISTS lidarr_quarantine_actions_track_idx; -DROP TABLE IF EXISTS lidarr_quarantine_actions; -DROP TYPE IF EXISTS lidarr_quarantine_action_kind; -DROP INDEX IF EXISTS lidarr_quarantine_track_idx; -DROP TABLE IF EXISTS lidarr_quarantine; -DROP TYPE IF EXISTS lidarr_quarantine_reason; diff --git a/internal/db/migrations/0011_lidarr_quarantine.up.sql b/internal/db/migrations/0011_lidarr_quarantine.up.sql deleted file mode 100644 index 1d2443c9..00000000 --- a/internal/db/migrations/0011_lidarr_quarantine.up.sql +++ /dev/null @@ -1,48 +0,0 @@ --- Per-user track quarantines + admin action audit log. --- --- lidarr_quarantine — one row per (user, track) complaint. PK matches --- the general_likes pattern. Re-flagging the same track upserts. Deleted --- on user resolution (un-hide), admin Resolve, or any of the deletes. --- --- lidarr_quarantine_actions — audit log of admin destructive actions. --- Snapshot text columns let the log stay readable after the underlying --- track/album rows are gone. - -CREATE TYPE lidarr_quarantine_reason AS ENUM ( - 'bad_rip', 'wrong_file', 'wrong_tags', 'duplicate', 'other' -); - -CREATE TABLE lidarr_quarantine ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - reason lidarr_quarantine_reason NOT NULL, - notes text, - created_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, track_id) -); - --- Only the track_id index is non-redundant: the composite PK --- (user_id, track_id) already serves WHERE user_id = $1 lookups, so a --- separate (user_id, created_at DESC) index would just amplify writes --- without paying for itself at household-scale row counts. -CREATE INDEX lidarr_quarantine_track_idx ON lidarr_quarantine (track_id); - -CREATE TYPE lidarr_quarantine_action_kind AS ENUM ( - 'resolved', 'deleted_file', 'deleted_via_lidarr' -); - -CREATE TABLE lidarr_quarantine_actions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - track_id uuid NOT NULL, - track_title text NOT NULL, - artist_name text NOT NULL, - album_title text, - action lidarr_quarantine_action_kind NOT NULL, - admin_id uuid REFERENCES users(id) ON DELETE SET NULL, - lidarr_album_mbid text, - affected_users int NOT NULL, - created_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX lidarr_quarantine_actions_track_idx ON lidarr_quarantine_actions (track_id); -CREATE INDEX lidarr_quarantine_actions_created_idx ON lidarr_quarantine_actions (created_at DESC); diff --git a/internal/db/migrations/0012_artist_similarity_unmatched.down.sql b/internal/db/migrations/0012_artist_similarity_unmatched.down.sql deleted file mode 100644 index 29d52c9e..00000000 --- a/internal/db/migrations/0012_artist_similarity_unmatched.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS artist_similarity_unmatched_seed_score_idx; -DROP TABLE IF EXISTS artist_similarity_unmatched; diff --git a/internal/db/migrations/0012_artist_similarity_unmatched.up.sql b/internal/db/migrations/0012_artist_similarity_unmatched.up.sql deleted file mode 100644 index b89b7bb1..00000000 --- a/internal/db/migrations/0012_artist_similarity_unmatched.up.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Persist unmatched-similar-artist MBIDs that the M4b worker would --- otherwise discard. Mirrors artist_similarity shape: same composite PK --- with source, same (seed_id, score DESC) index, same source enum check. --- The candidate side is text + name (no FK) — that's the whole point. - -CREATE TABLE artist_similarity_unmatched ( - seed_artist_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - candidate_mbid text NOT NULL, - candidate_name text NOT NULL, - score DOUBLE PRECISION NOT NULL, - source text NOT NULL CHECK (source IN ('listenbrainz', 'musicbrainz_tag', 'user_cooccurrence')), - fetched_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (seed_artist_id, candidate_mbid, source) -); - -CREATE INDEX artist_similarity_unmatched_seed_score_idx - ON artist_similarity_unmatched (seed_artist_id, score DESC); diff --git a/internal/db/migrations/0013_lidarr_metadata_profile.down.sql b/internal/db/migrations/0013_lidarr_metadata_profile.down.sql deleted file mode 100644 index 4f97bdba..00000000 --- a/internal/db/migrations/0013_lidarr_metadata_profile.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE lidarr_config - DROP COLUMN default_metadata_profile_id; diff --git a/internal/db/migrations/0013_lidarr_metadata_profile.up.sql b/internal/db/migrations/0013_lidarr_metadata_profile.up.sql deleted file mode 100644 index 627d46f9..00000000 --- a/internal/db/migrations/0013_lidarr_metadata_profile.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- Persist the chosen Lidarr metadata profile alongside quality profile + --- root folder. Lidarr POST /api/v1/artist requires metadataProfileId; --- without storing it every Approve would refetch and pick the first. --- Nullable: existing rows get NULL and the service falls back to "fetch --- list and pick first" until an admin saves. - -ALTER TABLE lidarr_config - ADD COLUMN default_metadata_profile_id integer; diff --git a/internal/db/migrations/0014_playlists.down.sql b/internal/db/migrations/0014_playlists.down.sql deleted file mode 100644 index 0e7e724d..00000000 --- a/internal/db/migrations/0014_playlists.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS playlist_tracks; -DROP TABLE IF EXISTS playlists; diff --git a/internal/db/migrations/0014_playlists.up.sql b/internal/db/migrations/0014_playlists.up.sql deleted file mode 100644 index 6cf9d825..00000000 --- a/internal/db/migrations/0014_playlists.up.sql +++ /dev/null @@ -1,38 +0,0 @@ --- User playlists. - -CREATE TABLE playlists ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - name text NOT NULL, - description text NOT NULL DEFAULT '', - is_public boolean NOT NULL DEFAULT false, - cover_path text, - track_count integer NOT NULL DEFAULT 0, - duration_sec integer NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX playlists_user_idx ON playlists (user_id, updated_at DESC); -CREATE INDEX playlists_public_idx ON playlists (is_public, updated_at DESC) WHERE is_public; - --- track_id is nullable + ON DELETE SET NULL so deleting a track from --- the library doesn't silently drop entries from operators' playlists. --- Denormalized title/artist/album/duration carry a snapshot so the row --- is still legible after the upstream track row is gone. -CREATE TABLE playlist_tracks ( - playlist_id uuid NOT NULL REFERENCES playlists(id) ON DELETE CASCADE, - position integer NOT NULL, - track_id uuid REFERENCES tracks(id) ON DELETE SET NULL, - title text NOT NULL, - artist_name text NOT NULL, - album_title text NOT NULL, - duration_sec integer NOT NULL, - added_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (playlist_id, position) -); - --- Partial index supports the FK lookup that fires when a track is --- deleted (ON DELETE SET NULL) — without it, deleting a track triggers --- a full scan of playlist_tracks. -CREATE INDEX playlist_tracks_track_idx ON playlist_tracks (track_id) WHERE track_id IS NOT NULL; diff --git a/internal/db/migrations/0015_system_playlists.down.sql b/internal/db/migrations/0015_system_playlists.down.sql deleted file mode 100644 index 9e7ef182..00000000 --- a/internal/db/migrations/0015_system_playlists.down.sql +++ /dev/null @@ -1,10 +0,0 @@ -DROP TABLE IF EXISTS system_playlist_runs; -DROP INDEX IF EXISTS playlists_user_kind_idx; -ALTER TABLE playlists - DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - DROP COLUMN IF EXISTS seed_artist_id, - DROP COLUMN IF EXISTS system_variant, - DROP COLUMN IF EXISTS kind; diff --git a/internal/db/migrations/0015_system_playlists.up.sql b/internal/db/migrations/0015_system_playlists.up.sql deleted file mode 100644 index 7e138ec5..00000000 --- a/internal/db/migrations/0015_system_playlists.up.sql +++ /dev/null @@ -1,46 +0,0 @@ --- System-generated playlists. --- Adds kind/system_variant/seed_artist_id columns to playlists and a --- per-user run-tracking table. Backfills existing playlists to --- kind='user'. - --- Discriminator on existing playlists table. -ALTER TABLE playlists - ADD COLUMN kind text NOT NULL DEFAULT 'user', - ADD COLUMN system_variant text, - ADD COLUMN seed_artist_id uuid REFERENCES artists(id) ON DELETE SET NULL; - --- Belt-and-braces backfill in case the DEFAULT didn't apply on some --- runtime branches; a no-op when the column metadata already filled. -UPDATE playlists SET kind = 'user' WHERE kind IS NULL OR kind = ''; - --- Constraint: kind/system_variant pair is consistent. -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent - CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ('for_you', 'songs_like_artist')) - ); - --- Constraint: 'songs_like_artist' has a seed artist; nothing else does. -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent - CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); - --- Filter index for kind=user vs kind=system queries on the user's row. -CREATE INDEX playlists_user_kind_idx ON playlists (user_id, kind); - --- Per-user run tracking — one row per user. -CREATE TABLE system_playlist_runs ( - user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - last_run_at timestamptz, - last_run_date date, - in_flight boolean NOT NULL DEFAULT false, - last_error text -); diff --git a/internal/db/migrations/0016_album_cover_source.down.sql b/internal/db/migrations/0016_album_cover_source.down.sql deleted file mode 100644 index 86c33bed..00000000 --- a/internal/db/migrations/0016_album_cover_source.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS albums_cover_art_source_idx; -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums DROP COLUMN IF EXISTS cover_art_source; diff --git a/internal/db/migrations/0016_album_cover_source.up.sql b/internal/db/migrations/0016_album_cover_source.up.sql deleted file mode 100644 index b198c989..00000000 --- a/internal/db/migrations/0016_album_cover_source.up.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Album cover origin attribution. --- 'embedded' — extracted from audio file (reserved). --- 'sidecar' — found in the album directory (cover.jpg/folder.jpg/etc). --- 'mbcaa' — fetched from MusicBrainz Cover Art Archive. --- 'none' — tried, no cover available. Skip auto-retry; only manual. -ALTER TABLE albums ADD COLUMN cover_art_source text; - -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded', 'sidecar', 'mbcaa', 'none')); - --- Backfill existing rows with cover_art_path set (defensive: scanner has --- never populated cover_art_path in current dev, but keeps re-runs idempotent). -UPDATE albums SET cover_art_source = 'sidecar' - WHERE cover_art_path IS NOT NULL AND cover_art_source IS NULL; - --- Index supports "find missing covers" queries. -CREATE INDEX albums_cover_art_source_idx ON albums (cover_art_source); diff --git a/internal/db/migrations/0017_scan_runs.down.sql b/internal/db/migrations/0017_scan_runs.down.sql deleted file mode 100644 index a498146a..00000000 --- a/internal/db/migrations/0017_scan_runs.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS scan_runs_started_at_idx; -DROP TABLE IF EXISTS scan_runs; diff --git a/internal/db/migrations/0017_scan_runs.up.sql b/internal/db/migrations/0017_scan_runs.up.sql deleted file mode 100644 index ed3a528b..00000000 --- a/internal/db/migrations/0017_scan_runs.up.sql +++ /dev/null @@ -1,20 +0,0 @@ --- Track library-scan / MBID-backfill / cover-enrich runs so the --- admin overview can show last-run results + manual trigger state. -CREATE TABLE scan_runs ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - started_at timestamptz NOT NULL DEFAULT now(), - finished_at timestamptz, - -- Per-stage tallies are jsonb so the schema doesn't need to grow when - -- a stage gains/loses a counter. Each stage's value matches the Go - -- struct emitted by that worker (e.g. library.Stats). - library jsonb, - mbid_backfill jsonb, - cover_enrich jsonb, - -- Non-empty when the run as a whole errored (a stage panic, or the - -- worker hit a fatal error before writing stage tallies). - error_message text -); - --- The status endpoint always reads the latest row; the in-flight guard --- needs to find rows where finished_at IS NULL. Both hit started_at DESC. -CREATE INDEX scan_runs_started_at_idx ON scan_runs (started_at DESC); diff --git a/internal/db/migrations/0018_artist_art_and_provider_settings.down.sql b/internal/db/migrations/0018_artist_art_and_provider_settings.down.sql deleted file mode 100644 index fae6f46c..00000000 --- a/internal/db/migrations/0018_artist_art_and_provider_settings.down.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Reverse of 0018. - -ALTER TABLE scan_runs DROP COLUMN IF EXISTS artist_art_enrich; - -DROP TABLE IF EXISTS cover_art_sources_meta; -DROP TABLE IF EXISTS cover_art_provider_settings; - -ALTER TABLE artists DROP COLUMN IF EXISTS artist_art_sources_version; -ALTER TABLE albums DROP COLUMN IF EXISTS cover_art_sources_version; - -DROP INDEX IF EXISTS artists_artist_art_source_idx; -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists DROP COLUMN IF EXISTS artist_art_source; -ALTER TABLE artists DROP COLUMN IF EXISTS artist_fanart_path; -ALTER TABLE artists DROP COLUMN IF EXISTS artist_thumb_path; - --- Restore the original albums.cover_art_source CHECK from migration 0016. -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','none')); --- Note: rows with cover_art_source='theaudiodb' will be rejected by this --- restored constraint. If down-migrating from a populated DB, run: --- UPDATE albums SET cover_art_source = NULL WHERE cover_art_source = 'theaudiodb'; --- before applying this migration. diff --git a/internal/db/migrations/0018_artist_art_and_provider_settings.up.sql b/internal/db/migrations/0018_artist_art_and_provider_settings.up.sql deleted file mode 100644 index b1ba95ba..00000000 --- a/internal/db/migrations/0018_artist_art_and_provider_settings.up.sql +++ /dev/null @@ -1,61 +0,0 @@ --- Schema for additional cover-art providers (TheAudioDB first), artist art --- (thumb + fanart), and the recheck-on-source-change trigger. - --- (0) Extend the existing albums.cover_art_source CHECK to accept the --- new 'theaudiodb' value. The constraint was created in migration 0016 --- with the IN list ('embedded','sidecar','mbcaa','none'); without this --- extension, the enricher's UPDATE setting cover_art_source='theaudiodb' --- would fail with a CHECK violation. -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','theaudiodb','none')); - --- (1) Artist art columns parallel albums.cover_art_*. -ALTER TABLE artists - ADD COLUMN artist_thumb_path text, - ADD COLUMN artist_fanart_path text, - ADD COLUMN artist_art_source text; - -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL - OR artist_art_source IN ('theaudiodb','none')); - -CREATE INDEX artists_artist_art_source_idx ON artists (artist_art_source); - --- (2) Recheck-trigger version stamps. Default 0; current_version starts --- at 1, so every existing row is "stale" relative to current — first --- scan after migrate retries every settled row through the new chain. -ALTER TABLE albums - ADD COLUMN cover_art_sources_version int NOT NULL DEFAULT 0; -ALTER TABLE artists - ADD COLUMN artist_art_sources_version int NOT NULL DEFAULT 0; - --- (3) Per-provider settings + singleton meta row. -CREATE TABLE cover_art_provider_settings ( - provider_id text PRIMARY KEY, - enabled boolean NOT NULL DEFAULT true, - api_key text, - display_order int NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE TABLE cover_art_sources_meta ( - id boolean PRIMARY KEY DEFAULT true, - current_version int NOT NULL DEFAULT 1, - CONSTRAINT cover_art_sources_meta_singleton CHECK (id = true) -); -INSERT INTO cover_art_sources_meta (id, current_version) VALUES (true, 1); - --- Seed both v1 providers as enabled. TheAudioDB's api_key stays NULL; --- the application supplies the test key '2' when the column is NULL, --- per the no-coercive-settings principle. -INSERT INTO cover_art_provider_settings (provider_id, enabled, display_order) VALUES - ('mbcaa', true, 0), - ('theaudiodb', true, 1); - --- (4) Scan-runs gains a stage tally column for artist art enrichment. -ALTER TABLE scan_runs ADD COLUMN artist_art_enrich jsonb; diff --git a/internal/db/migrations/0019_scan_schedule.down.sql b/internal/db/migrations/0019_scan_schedule.down.sql deleted file mode 100644 index b785659c..00000000 --- a/internal/db/migrations/0019_scan_schedule.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS scan_schedule; diff --git a/internal/db/migrations/0019_scan_schedule.up.sql b/internal/db/migrations/0019_scan_schedule.up.sql deleted file mode 100644 index 0d872edb..00000000 --- a/internal/db/migrations/0019_scan_schedule.up.sql +++ /dev/null @@ -1,23 +0,0 @@ --- Recurring scans: singleton table holding the scan schedule --- config. mode is the discriminator: 'off' / 'interval' / 'daily' / 'weekly'. --- Per-mode fields are populated only when their mode is selected; others --- stay NULL. weekly_day uses ISO 8601: 1=Monday … 7=Sunday. -CREATE TABLE scan_schedule ( - id boolean PRIMARY KEY DEFAULT true, - mode text NOT NULL DEFAULT 'off', - interval_hours int, - time_of_day text, - weekly_day int, - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT scan_schedule_singleton CHECK (id = true), - CONSTRAINT scan_schedule_mode_check - CHECK (mode IN ('off', 'interval', 'daily', 'weekly')), - CONSTRAINT scan_schedule_interval_check - CHECK (mode != 'interval' OR (interval_hours IS NOT NULL AND interval_hours > 0)), - CONSTRAINT scan_schedule_daily_check - CHECK (mode != 'daily' OR time_of_day IS NOT NULL), - CONSTRAINT scan_schedule_weekly_check - CHECK (mode != 'weekly' OR (time_of_day IS NOT NULL AND weekly_day IS NOT NULL AND weekly_day BETWEEN 1 AND 7)) -); - -INSERT INTO scan_schedule (id) VALUES (true); diff --git a/internal/db/migrations/0020_relax_art_source_checks.down.sql b/internal/db/migrations/0020_relax_art_source_checks.down.sql deleted file mode 100644 index 59166599..00000000 --- a/internal/db/migrations/0020_relax_art_source_checks.down.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Restore the prior tighter CHECK constraints (pre-Deezer/Last.fm). --- This will fail if any rows currently have artist_art_source = --- 'deezer' or 'lastfm' (likewise album); operator must clear those --- rows manually before rolling back. - -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL - OR artist_art_source IN ('theaudiodb','none')); - -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','theaudiodb','none')); - -ALTER TABLE cover_art_sources_meta DROP COLUMN IF EXISTS last_registered_providers_hash; diff --git a/internal/db/migrations/0020_relax_art_source_checks.up.sql b/internal/db/migrations/0020_relax_art_source_checks.up.sql deleted file mode 100644 index b663e06e..00000000 --- a/internal/db/migrations/0020_relax_art_source_checks.up.sql +++ /dev/null @@ -1,22 +0,0 @@ --- Relax cover-art and artist-art source CHECK constraints so the new --- Deezer and Last.fm providers can persist their IDs as --- accepted source values. Also add the --- last_registered_providers_hash column to cover_art_sources_meta for --- boot-time auto-bump detection (when the registered-provider set --- changes, we bump current_version once so 'none' rows get --- re-eligibled). - -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL - OR artist_art_source IN ('theaudiodb','deezer','lastfm','none')); - -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','theaudiodb','deezer','lastfm','none')); - -ALTER TABLE cover_art_sources_meta - ADD COLUMN IF NOT EXISTS last_registered_providers_hash text NOT NULL DEFAULT ''; diff --git a/internal/db/migrations/0021_discover_variant.down.sql b/internal/db/migrations/0021_discover_variant.down.sql deleted file mode 100644 index d93aa89b..00000000 --- a/internal/db/migrations/0021_discover_variant.down.sql +++ /dev/null @@ -1,21 +0,0 @@ --- Restore the prior tighter CHECK constraints (pre-discover). --- This will fail if any rows currently have system_variant = 'discover'; --- operator must clear those rows manually before rolling back. - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ('for_you', 'songs_like_artist')) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0021_discover_variant.up.sql b/internal/db/migrations/0021_discover_variant.up.sql deleted file mode 100644 index 79af4416..00000000 --- a/internal/db/migrations/0021_discover_variant.up.sql +++ /dev/null @@ -1,27 +0,0 @@ --- Adds 'discover' as an accepted system_variant alongside 'for_you' --- and 'songs_like_artist'. Discover has no seed_artist_id (like --- for_you), so the variant->seed coherence check is extended to --- accept (system_variant = 'discover' AND seed_artist_id IS NULL). --- --- Drops + re-adds both CHECK constraints; PostgreSQL doesn't have --- ALTER CONSTRAINT for CHECK so this is the standard pattern. - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ('for_you', 'songs_like_artist', 'discover')) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'discover' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0022_user_management.down.sql b/internal/db/migrations/0022_user_management.down.sql deleted file mode 100644 index 53632f82..00000000 --- a/internal/db/migrations/0022_user_management.down.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Reverses migration 0022. Drop tables in reverse dependency order. --- This will fail if any rows in audit_log or user_invites reference --- users that were deleted with ON DELETE SET NULL semantics; those --- references will already be NULL so the drops should succeed cleanly. - -DROP TABLE IF EXISTS audit_log; -DROP TABLE IF EXISTS user_invites; -DROP TABLE IF EXISTS registration_settings; -ALTER TABLE users DROP COLUMN IF EXISTS display_name; diff --git a/internal/db/migrations/0022_user_management.up.sql b/internal/db/migrations/0022_user_management.up.sql deleted file mode 100644 index 434a951d..00000000 --- a/internal/db/migrations/0022_user_management.up.sql +++ /dev/null @@ -1,48 +0,0 @@ --- User management: --- --- - users.display_name: optional human-readable name distinct from username. --- - user_invites: admin-generated tokens; user redeems during signup. --- - registration_settings (singleton): controls whether registration is --- 'invite_only' (default after first admin) or 'open' (admin can --- re-enable). The registration handler also has a special-case for the --- "no users yet" state where it ignores invites and lets the first --- register as admin. --- - audit_log: append-only record of admin-driven user mutations. --- No retention policy. - -ALTER TABLE users ADD COLUMN IF NOT EXISTS display_name text; - -CREATE TABLE user_invites ( - token text PRIMARY KEY, - invited_by uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - note text, - created_at timestamptz NOT NULL DEFAULT now(), - expires_at timestamptz NOT NULL, - redeemed_at timestamptz, - redeemed_by uuid REFERENCES users(id) ON DELETE SET NULL -); -CREATE INDEX user_invites_active_idx - ON user_invites (expires_at) - WHERE redeemed_at IS NULL; - -CREATE TABLE registration_settings ( - id boolean PRIMARY KEY DEFAULT true, - mode text NOT NULL DEFAULT 'invite_only', - CONSTRAINT registration_settings_singleton CHECK (id = true), - CONSTRAINT registration_settings_mode_check - CHECK (mode IN ('invite_only', 'open')) -); -INSERT INTO registration_settings (id) VALUES (true) - ON CONFLICT (id) DO NOTHING; - -CREATE TABLE audit_log ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - actor_id uuid REFERENCES users(id) ON DELETE SET NULL, - target_id uuid REFERENCES users(id) ON DELETE SET NULL, - action text NOT NULL, - metadata jsonb, - created_at timestamptz NOT NULL DEFAULT now() -); -CREATE INDEX audit_log_created_at_idx ON audit_log (created_at DESC); -CREATE INDEX audit_log_actor_id_idx ON audit_log (actor_id); -CREATE INDEX audit_log_target_id_idx ON audit_log (target_id); diff --git a/internal/db/migrations/0023_user_auto_approve.down.sql b/internal/db/migrations/0023_user_auto_approve.down.sql deleted file mode 100644 index 65295c6c..00000000 --- a/internal/db/migrations/0023_user_auto_approve.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE users DROP COLUMN IF EXISTS auto_approve_requests; diff --git a/internal/db/migrations/0023_user_auto_approve.up.sql b/internal/db/migrations/0023_user_auto_approve.up.sql deleted file mode 100644 index 76f0b333..00000000 --- a/internal/db/migrations/0023_user_auto_approve.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- Adds users.auto_approve_requests for the per-user auto-approve toggle: --- the request submission flow approves that user's requests at once. --- --- Default false: existing users keep manual approval, opt-in via the --- admin user-management UI. - -ALTER TABLE users - ADD COLUMN IF NOT EXISTS auto_approve_requests boolean NOT NULL DEFAULT false; diff --git a/internal/db/migrations/0024_user_management_u3.down.sql b/internal/db/migrations/0024_user_management_u3.down.sql deleted file mode 100644 index fc39e95e..00000000 --- a/internal/db/migrations/0024_user_management_u3.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DROP TABLE IF EXISTS password_resets; -DROP TABLE IF EXISTS smtp_config; -DROP INDEX IF EXISTS users_email_unique; -ALTER TABLE users DROP COLUMN IF EXISTS email; diff --git a/internal/db/migrations/0024_user_management_u3.up.sql b/internal/db/migrations/0024_user_management_u3.up.sql deleted file mode 100644 index 072daa05..00000000 --- a/internal/db/migrations/0024_user_management_u3.up.sql +++ /dev/null @@ -1,44 +0,0 @@ --- User management U3: self-service profile + email + email-based --- password reset infrastructure. --- --- - users.email: optional; required for the forgot-password flow. --- Lowercase-unique via a partial index to allow many NULL emails --- while preventing case-insensitive duplicates. --- - smtp_config singleton: SMTP server settings + from-address + --- enabled flag. The actual mailer reads this row at send time so --- config edits take effect without a server restart. --- - password_resets: short-lived single-use tokens for the --- forgot-password flow. 24h TTL enforced at issue time. - -ALTER TABLE users ADD COLUMN IF NOT EXISTS email text; -CREATE UNIQUE INDEX IF NOT EXISTS users_email_unique - ON users (lower(email)) - WHERE email IS NOT NULL; - -CREATE TABLE smtp_config ( - id boolean PRIMARY KEY DEFAULT true, - enabled boolean NOT NULL DEFAULT false, - host text NOT NULL DEFAULT '', - port int NOT NULL DEFAULT 587, - username text NOT NULL DEFAULT '', - password text NOT NULL DEFAULT '', - from_address text NOT NULL DEFAULT '', - from_name text NOT NULL DEFAULT 'Minstrel', - use_tls boolean NOT NULL DEFAULT true, - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT smtp_config_singleton CHECK (id = true) -); -INSERT INTO smtp_config (id) VALUES (true) - ON CONFLICT (id) DO NOTHING; - -CREATE TABLE password_resets ( - token text PRIMARY KEY, - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - created_at timestamptz NOT NULL DEFAULT now(), - expires_at timestamptz NOT NULL, - used_at timestamptz -); -CREATE INDEX password_resets_user_id_idx ON password_resets (user_id); -CREATE INDEX password_resets_active_idx - ON password_resets (expires_at) - WHERE used_at IS NULL; diff --git a/internal/db/migrations/0025_library_changes.down.sql b/internal/db/migrations/0025_library_changes.down.sql deleted file mode 100644 index fed8a61a..00000000 --- a/internal/db/migrations/0025_library_changes.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS library_changes; diff --git a/internal/db/migrations/0025_library_changes.up.sql b/internal/db/migrations/0025_library_changes.up.sql deleted file mode 100644 index f4252cc4..00000000 --- a/internal/db/migrations/0025_library_changes.up.sql +++ /dev/null @@ -1,20 +0,0 @@ --- Append-only change log for library entities. Every mutation on --- artists/albums/tracks/likes/playlists/playlist_tracks writes a row --- in the same transaction as the mutation itself. Powers the delta-sync --- endpoint — clients pass back the last-seen `id` as a cursor. --- --- Retention: not capped here. A cursor older than what the table keeps gets --- the reset path (410). - -CREATE TABLE library_changes ( - id BIGSERIAL PRIMARY KEY, - entity_type TEXT NOT NULL CHECK (entity_type IN ( - 'artist', 'album', 'track', 'like_track', 'like_album', 'like_artist', - 'playlist', 'playlist_track' - )), - entity_id TEXT NOT NULL, - op TEXT NOT NULL CHECK (op IN ('upsert', 'delete')), - changed_at TIMESTAMPTZ NOT NULL DEFAULT now() -); - -CREATE INDEX idx_library_changes_id ON library_changes(id); diff --git a/internal/db/migrations/0026_users_timezone.down.sql b/internal/db/migrations/0026_users_timezone.down.sql deleted file mode 100644 index 6752f9d1..00000000 --- a/internal/db/migrations/0026_users_timezone.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE users - DROP COLUMN timezone, - DROP COLUMN timezone_updated_at; diff --git a/internal/db/migrations/0026_users_timezone.up.sql b/internal/db/migrations/0026_users_timezone.up.sql deleted file mode 100644 index ec14c39f..00000000 --- a/internal/db/migrations/0026_users_timezone.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- 0026_users_timezone.up.sql — per-user timezone for the system-playlist --- scheduler. Default 'UTC' so existing rows + brand-new --- users have a safe value before their first client check-in via --- PUT /api/me/timezone. The scheduler reads this column to decide --- which IANA zone to anchor each user's daily 03:00 build to. -ALTER TABLE users - ADD COLUMN timezone text NOT NULL DEFAULT 'UTC', - ADD COLUMN timezone_updated_at timestamptz; diff --git a/internal/db/migrations/0027_system_playlist_rotation.down.sql b/internal/db/migrations/0027_system_playlist_rotation.down.sql deleted file mode 100644 index c52a8f5f..00000000 --- a/internal/db/migrations/0027_system_playlist_rotation.down.sql +++ /dev/null @@ -1,5 +0,0 @@ --- 0027_system_playlist_rotation.down.sql -DROP TABLE IF EXISTS system_playlist_rotation_state; - -ALTER TABLE play_events - DROP COLUMN IF EXISTS source; diff --git a/internal/db/migrations/0027_system_playlist_rotation.up.sql b/internal/db/migrations/0027_system_playlist_rotation.up.sql deleted file mode 100644 index 5c604801..00000000 --- a/internal/db/migrations/0027_system_playlist_rotation.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- 0027_system_playlist_rotation.up.sql — sample-history dedup for --- system playlists. Two parts: --- --- 1. play_events.source: which system playlist a play originated --- from ('for_you' | 'discover' | future kinds), or NULL for any --- play not launched from a system-playlist surface (library, --- user playlist, radio, Subsonic). Lets the ingest path know a --- play should count against that playlist's rotation. --- --- 2. system_playlist_rotation_state: per (user, playlist_kind) set --- of track ids already played in the current rotation window. --- Shuffle-on-play prefers the unplayed tail; when the snapshot --- is exhausted the set resets and rotation_started_at advances. --- Centralized server-side so phone / web / watch share one --- rotation, mirroring how radio dedup already lives server-side. -ALTER TABLE play_events - ADD COLUMN source text; - -CREATE TABLE system_playlist_rotation_state ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - playlist_kind text NOT NULL, - played_track_ids uuid[] NOT NULL DEFAULT '{}', - rotation_started_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, playlist_kind) -); diff --git a/internal/db/migrations/0028_discovery_mix_variants.down.sql b/internal/db/migrations/0028_discovery_mix_variants.down.sql deleted file mode 100644 index e16f7ecf..00000000 --- a/internal/db/migrations/0028_discovery_mix_variants.down.sql +++ /dev/null @@ -1,24 +0,0 @@ --- Reverts to the 0021 constraint set (for_you, songs_like_artist, --- discover only). Fails if any playlists row still has one of the --- five new system_variant values — delete/rebuild system playlists --- first if rolling back. - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ('for_you', 'songs_like_artist', 'discover')) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'discover' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0028_discovery_mix_variants.up.sql b/internal/db/migrations/0028_discovery_mix_variants.up.sql deleted file mode 100644 index e2eee325..00000000 --- a/internal/db/migrations/0028_discovery_mix_variants.up.sql +++ /dev/null @@ -1,45 +0,0 @@ --- Before: the five discovery mixes (deep_cuts, rediscover, new_for_you, --- on_this_day, first_listens) had producers and registry entries but no --- system_variant values in the two playlists CHECK constraints, so inserting --- any of them failed playlists_kind_variant_consistent (SQLSTATE 23514) — --- and because BuildSystemPlaylists is one all-or-nothing transaction, that --- aborts the WHOLE build. After: the constraints accept them. --- --- All five are seedless (like for_you/discover): seed_artist_id IS --- NULL. Drop + re-add both constraints with the expanded set, same --- pattern as 0021_discover_variant (Postgres has no ALTER CONSTRAINT --- for CHECK). - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ( - 'for_you', 'songs_like_artist', 'discover', - 'deep_cuts', 'rediscover', 'new_for_you', - 'on_this_day', 'first_listens' - )) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'discover' AND seed_artist_id IS NULL) - OR - (system_variant = 'deep_cuts' AND seed_artist_id IS NULL) - OR - (system_variant = 'rediscover' AND seed_artist_id IS NULL) - OR - (system_variant = 'new_for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'on_this_day' AND seed_artist_id IS NULL) - OR - (system_variant = 'first_listens' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0029_tracks_mbid_nonunique.down.sql b/internal/db/migrations/0029_tracks_mbid_nonunique.down.sql deleted file mode 100644 index b40e0408..00000000 --- a/internal/db/migrations/0029_tracks_mbid_nonunique.down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Reverts to the unique partial index. This FAILS if any recording --- MBID is shared across releases in the library (the exact case 0029 --- exists to allow) — dedupe tracks.mbid before rolling back. - -DROP INDEX IF EXISTS tracks_mbid_idx; -CREATE UNIQUE INDEX tracks_mbid_unique ON tracks (mbid) WHERE mbid IS NOT NULL; diff --git a/internal/db/migrations/0029_tracks_mbid_nonunique.up.sql b/internal/db/migrations/0029_tracks_mbid_nonunique.up.sql deleted file mode 100644 index 714789cb..00000000 --- a/internal/db/migrations/0029_tracks_mbid_nonunique.up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- tracks.mbid holds the MusicBrainz *recording* MBID — the id the --- ListenBrainz similarity pipeline (ListPlayedTracksNeedingSimilarity, --- GetTracksByMBIDs) matches on. A single recording legitimately appears --- on multiple releases (album + compilation + single), so multiple --- tracks rows share one recording MBID. --- --- tracks_mbid_unique (added in 0002, when this column was always NULL --- and never populated) wrongly assumes one MBID == one track. Now that --- the scanner extracts the recording MBID, that uniqueness throws --- 23505 for any recording present on >1 release. Replace it with a --- non-unique partial index serving the same lookups. Zero-risk: the --- column is 100% NULL at migration time. - -DROP INDEX IF EXISTS tracks_mbid_unique; -CREATE INDEX IF NOT EXISTS tracks_mbid_idx ON tracks (mbid) WHERE mbid IS NOT NULL; diff --git a/internal/db/migrations/0030_relax_art_source_check_to_nonempty.down.sql b/internal/db/migrations/0030_relax_art_source_check_to_nonempty.down.sql deleted file mode 100644 index 68fe224e..00000000 --- a/internal/db/migrations/0030_relax_art_source_check_to_nonempty.down.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Restore the 0020 fixed-allowlist CHECKs. FAILS if any row holds a --- source value outside the allowlist (the exact case 0030 enables) — --- normalise such rows before rolling back. - -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL - OR cover_art_source IN ('embedded','sidecar','mbcaa','theaudiodb','deezer','lastfm','none')); - -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL - OR artist_art_source IN ('theaudiodb','deezer','lastfm','none')); diff --git a/internal/db/migrations/0030_relax_art_source_check_to_nonempty.up.sql b/internal/db/migrations/0030_relax_art_source_check_to_nonempty.up.sql deleted file mode 100644 index 7b6dd3fd..00000000 --- a/internal/db/migrations/0030_relax_art_source_check_to_nonempty.up.sql +++ /dev/null @@ -1,18 +0,0 @@ --- The cover/artist art `*_source` column stores the recording --- provider's registry ID. coverart.Register makes the provider set --- extensible, so a fixed IN-list CHECK (0016 → 0018 → 0020) required a --- schema migration for every new provider and rejected any --- out-of-list value (e.g. test stub providers): a fixed-value CHECK --- fighting an extensible value set. Relax to "NULL or any --- non-empty string" — the registry, not the schema, is the source of --- truth for valid provider IDs. - -ALTER TABLE albums DROP CONSTRAINT IF EXISTS albums_cover_art_source_check; -ALTER TABLE albums - ADD CONSTRAINT albums_cover_art_source_check - CHECK (cover_art_source IS NULL OR cover_art_source <> ''); - -ALTER TABLE artists DROP CONSTRAINT IF EXISTS artists_artist_art_source_check; -ALTER TABLE artists - ADD CONSTRAINT artists_artist_art_source_check - CHECK (artist_art_source IS NULL OR artist_art_source <> ''); diff --git a/internal/db/migrations/0031_lidarr_add_confirmed_at.down.sql b/internal/db/migrations/0031_lidarr_add_confirmed_at.down.sql deleted file mode 100644 index 40964d14..00000000 --- a/internal/db/migrations/0031_lidarr_add_confirmed_at.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE lidarr_requests - DROP COLUMN lidarr_add_confirmed_at; diff --git a/internal/db/migrations/0031_lidarr_add_confirmed_at.up.sql b/internal/db/migrations/0031_lidarr_add_confirmed_at.up.sql deleted file mode 100644 index b5468d98..00000000 --- a/internal/db/migrations/0031_lidarr_add_confirmed_at.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- Additive: records when Lidarr accepted the add (POST artist/album) --- for an approved request. NULL = not yet sent/confirmed; the --- reconciler idempotently (re)sends the add until this is set, then --- watches for the import. Decouples the durable admin approval from the --- best-effort Lidarr call, so a transient Lidarr outage does not force a --- manual re-approve. -ALTER TABLE lidarr_requests - ADD COLUMN lidarr_add_confirmed_at timestamptz; diff --git a/internal/db/migrations/0032_playback_errors.down.sql b/internal/db/migrations/0032_playback_errors.down.sql deleted file mode 100644 index 43ae6b48..00000000 --- a/internal/db/migrations/0032_playback_errors.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS playback_errors; diff --git a/internal/db/migrations/0032_playback_errors.up.sql b/internal/db/migrations/0032_playback_errors.up.sql deleted file mode 100644 index 12de900c..00000000 --- a/internal/db/migrations/0032_playback_errors.up.sql +++ /dev/null @@ -1,41 +0,0 @@ --- Client-reported playback errors. Populated by clients when a track --- fails to play (zero duration, decode error, etc.); surfaced in the --- admin /admin/playback-errors inbox so an admin can hide / delete --- / re-request the offending track. --- --- resolved_at + resolved_by + resolution are NULL until an admin acts --- on the row. Auto-resolved by the client when the admin clicks Hide / --- Delete / Re-request from the inbox row, with the resolution string --- recording which path was taken. The partial index keeps the --- unresolved-queue lookup fast even as resolved history accumulates. --- --- CHECK constraints on kind/resolution gate the enum values so client --- typos can't pollute the data; a new value means swapping the constraint --- in the same migration as the code that writes it. - -CREATE TABLE playback_errors ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - client_id text NOT NULL, - kind text NOT NULL, - detail text, - occurred_at timestamptz NOT NULL DEFAULT now(), - resolved_at timestamptz, - resolved_by uuid REFERENCES users(id), - resolution text, - CONSTRAINT playback_errors_kind_check - CHECK (kind IN ('zero_duration', 'load_failed', 'stalled')), - CONSTRAINT playback_errors_resolution_check - CHECK (resolution IS NULL OR resolution IN - ('hidden', 'deleted', 'requested', 'fixed', 'ignored')), - CONSTRAINT playback_errors_resolved_consistency - CHECK ((resolved_at IS NULL) = (resolution IS NULL)) -); - -CREATE INDEX idx_playback_errors_unresolved - ON playback_errors (occurred_at DESC) - WHERE resolved_at IS NULL; - -CREATE INDEX idx_playback_errors_track - ON playback_errors (track_id); diff --git a/internal/db/migrations/0033_drop_scan_schedule.down.sql b/internal/db/migrations/0033_drop_scan_schedule.down.sql deleted file mode 100644 index 59b72012..00000000 --- a/internal/db/migrations/0033_drop_scan_schedule.down.sql +++ /dev/null @@ -1,21 +0,0 @@ --- Recreate the scan_schedule singleton (mirror of 0019) so the drop is --- reversible. The application no longer reads or writes this table. -CREATE TABLE scan_schedule ( - id boolean PRIMARY KEY DEFAULT true, - mode text NOT NULL DEFAULT 'off', - interval_hours int, - time_of_day text, - weekly_day int, - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT scan_schedule_singleton CHECK (id = true), - CONSTRAINT scan_schedule_mode_check - CHECK (mode IN ('off', 'interval', 'daily', 'weekly')), - CONSTRAINT scan_schedule_interval_check - CHECK (mode != 'interval' OR (interval_hours IS NOT NULL AND interval_hours > 0)), - CONSTRAINT scan_schedule_daily_check - CHECK (mode != 'daily' OR time_of_day IS NOT NULL), - CONSTRAINT scan_schedule_weekly_check - CHECK (mode != 'weekly' OR (time_of_day IS NOT NULL AND weekly_day IS NOT NULL AND weekly_day BETWEEN 1 AND 7)) -); - -INSERT INTO scan_schedule (id) VALUES (true); diff --git a/internal/db/migrations/0033_drop_scan_schedule.up.sql b/internal/db/migrations/0033_drop_scan_schedule.up.sql deleted file mode 100644 index 346ed9ca..00000000 --- a/internal/db/migrations/0033_drop_scan_schedule.up.sql +++ /dev/null @@ -1,4 +0,0 @@ --- Retire the configurable scan scheduler. New-file pickup is now handled by --- the fsnotify watcher + a hardcoded safety-net delta walk (cmd/minstrel), --- so the configurable schedule (and its admin UI) is gone. -DROP TABLE IF EXISTS scan_schedule; diff --git a/internal/db/migrations/0034_you_might_like.down.sql b/internal/db/migrations/0034_you_might_like.down.sql deleted file mode 100644 index e31679d6..00000000 --- a/internal/db/migrations/0034_you_might_like.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Reverse 0034_you_might_like.up.sql. -DROP TABLE IF EXISTS you_might_like_artists; -DROP TABLE IF EXISTS you_might_like_albums; diff --git a/internal/db/migrations/0034_you_might_like.up.sql b/internal/db/migrations/0034_you_might_like.up.sql deleted file mode 100644 index 6be652a2..00000000 --- a/internal/db/migrations/0034_you_might_like.up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- 0034_you_might_like.up.sql — "You might like" Home rows. --- --- Per-user ranked lists of IN-LIBRARY albums/artists the listener --- doesn't actively spin but is predicted to enjoy, derived from the --- same similarity + like-weighted candidate engine that powers For-You --- (rolled up from track scores to album/artist). Built in the daily --- 3am BuildSystemPlaylists pass and atomic-replaced, exactly like the --- system playlists; read back by /api/home. --- --- Two thin tables (id + rank) rather than denormalized snapshots: the --- Home read path hydrates album/artist refs through the existing --- albums/artists joins, so a later metadata edit is reflected without --- a rebuild. CASCADE on user/album/artist deletes keeps them clean. - -CREATE TABLE you_might_like_albums ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - album_id uuid NOT NULL REFERENCES albums(id) ON DELETE CASCADE, - rank integer NOT NULL, - built_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, album_id) -); - --- Read path orders by rank within a user; the index serves it directly. -CREATE INDEX you_might_like_albums_user_rank_idx - ON you_might_like_albums (user_id, rank); - -CREATE TABLE you_might_like_artists ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - artist_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - rank integer NOT NULL, - built_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, artist_id) -); - -CREATE INDEX you_might_like_artists_user_rank_idx - ON you_might_like_artists (user_id, rank); diff --git a/internal/db/migrations/0035_taste_profile.down.sql b/internal/db/migrations/0035_taste_profile.down.sql deleted file mode 100644 index 4af083e7..00000000 --- a/internal/db/migrations/0035_taste_profile.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Reverse 0035_taste_profile.up.sql. -DROP TABLE IF EXISTS taste_profile_tags; -DROP TABLE IF EXISTS taste_profile_artists; diff --git a/internal/db/migrations/0035_taste_profile.up.sql b/internal/db/migrations/0035_taste_profile.up.sql deleted file mode 100644 index 47084fa5..00000000 --- a/internal/db/migrations/0035_taste_profile.up.sql +++ /dev/null @@ -1,33 +0,0 @@ --- 0035_taste_profile.up.sql — per-user taste profile. --- --- A persistent, decaying model of each user's taste, rebuilt daily from --- graded play engagement (completion + skip position) plus explicit --- likes. Two facet tables: weighted artists and weighted genre tags. --- Weight is a signed float — positive = drawn to, negative = (passively) --- avoided; magnitude reflects decayed engagement. Candidate sourcing and --- scoring read them. --- --- CASCADE on user/artist deletes keeps them clean. Indexed by --- (user_id, weight DESC) to serve "top taste artists/tags" reads cheaply. - -CREATE TABLE taste_profile_artists ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - artist_id uuid NOT NULL REFERENCES artists(id) ON DELETE CASCADE, - weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, artist_id) -); - -CREATE INDEX taste_profile_artists_user_weight_idx - ON taste_profile_artists (user_id, weight DESC); - -CREATE TABLE taste_profile_tags ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - tag text NOT NULL, - weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, tag) -); - -CREATE INDEX taste_profile_tags_user_weight_idx - ON taste_profile_tags (user_id, weight DESC); diff --git a/internal/db/migrations/0036_diagnostics.down.sql b/internal/db/migrations/0036_diagnostics.down.sql deleted file mode 100644 index b53c33ba..00000000 --- a/internal/db/migrations/0036_diagnostics.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE users DROP COLUMN IF EXISTS debug_mode_enabled; -DROP TABLE IF EXISTS diagnostic_events; diff --git a/internal/db/migrations/0036_diagnostics.up.sql b/internal/db/migrations/0036_diagnostics.up.sql deleted file mode 100644 index afcab288..00000000 --- a/internal/db/migrations/0036_diagnostics.up.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Device diagnostics / debug-reporting subsystem. --- --- When an account has users.debug_mode_enabled = true, that account's --- client(s) stream a timeseries of device state here: connectivity + --- server-health transitions (roaming / poor-data recovery), UPnP/Sonos --- sync events (locked-phone desync), and power/lifecycle state (Doze / --- battery-optimization, the prime suspect for the desync). The admin --- /admin/diagnostics view filters by account + device + time window and --- exports the slice as JSON for offline analysis. --- --- `kind` is a COARSE category gated by a CHECK whitelist; the finer event --- discriminator + all event-specific fields live in the `payload` jsonb. This --- keeps the enum small and stable so new event variants don't require a --- migration (only a new *category* would: a new CHECK value means swapping the --- constraint in the same migration). If you add a category here, mirror it in --- the handler whitelist in internal/api/diagnostics.go. --- --- Two timestamps on purpose: occurred_at is the client device clock --- (when the event happened on the phone — may be skewed/wrong, e.g. in --- a dead zone), received_at is the server clock at ingest. Retention --- pruning is keyed on received_at so a bad client clock can't keep rows --- alive forever. - -CREATE TABLE diagnostic_events ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - client_id text NOT NULL, - app_version text, - os_version text, - kind text NOT NULL, - payload jsonb NOT NULL DEFAULT '{}'::jsonb, - occurred_at timestamptz NOT NULL, - received_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT diagnostic_events_kind_check - CHECK (kind IN ( - 'connectivity', 'upnp_sync', 'power', 'lifecycle', - 'heartbeat', 'http' - )) -); - --- Admin reads filter by account then device, ordered newest-first. -CREATE INDEX idx_diagnostic_events_user - ON diagnostic_events (user_id, occurred_at DESC); -CREATE INDEX idx_diagnostic_events_client - ON diagnostic_events (client_id, occurred_at DESC); --- Retention pruner deletes by server-clock age. -CREATE INDEX idx_diagnostic_events_received - ON diagnostic_events (received_at); - --- Per-account opt-in for diagnostics reporting. Admin-set primarily --- (flip remotely while a bug is live); the client also exposes a local --- OFF switch. Default false: no account reports until explicitly enabled. -ALTER TABLE users - ADD COLUMN IF NOT EXISTS debug_mode_enabled boolean NOT NULL DEFAULT false; diff --git a/internal/db/migrations/0037_diagnostics_playback_kind.down.sql b/internal/db/migrations/0037_diagnostics_playback_kind.down.sql deleted file mode 100644 index 10875ec9..00000000 --- a/internal/db/migrations/0037_diagnostics_playback_kind.down.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Drop rows using the new value first so they don't violate the restored --- (narrower) constraint, then revert the whitelist. -DELETE FROM diagnostic_events WHERE kind = 'playback'; -ALTER TABLE diagnostic_events DROP CONSTRAINT diagnostic_events_kind_check; -ALTER TABLE diagnostic_events ADD CONSTRAINT diagnostic_events_kind_check - CHECK (kind IN ( - 'connectivity', 'upnp_sync', 'power', 'lifecycle', - 'heartbeat', 'http' - )); diff --git a/internal/db/migrations/0037_diagnostics_playback_kind.up.sql b/internal/db/migrations/0037_diagnostics_playback_kind.up.sql deleted file mode 100644 index 290ee688..00000000 --- a/internal/db/migrations/0037_diagnostics_playback_kind.up.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Add 'playback' to the diagnostic_events kind whitelist. --- --- `route` and `player_state` events fire for EVERY output route (phone --- speaker, Bluetooth, UPnP/Sonos), so bucketing them under 'upnp_sync' --- was misleading — a listener on Bluetooth earbuds produced "upnp_sync" --- rows. 'upnp_sync' now means genuinely UPnP/Sonos-specific signal --- (drops, and future resync/desync); general playback + route telemetry --- moves to the new 'playback' kind. --- --- The new value lands by dropping and re-adding the constraint in the same --- migration. Existing rows tagged --- 'upnp_sync' stay as-is (debug telemetry on a 30-day retention). - -ALTER TABLE diagnostic_events DROP CONSTRAINT diagnostic_events_kind_check; -ALTER TABLE diagnostic_events ADD CONSTRAINT diagnostic_events_kind_check - CHECK (kind IN ( - 'connectivity', 'upnp_sync', 'power', 'lifecycle', - 'heartbeat', 'http', 'playback' - )); diff --git a/internal/db/migrations/0038_for_you_pick_kind.down.sql b/internal/db/migrations/0038_for_you_pick_kind.down.sql deleted file mode 100644 index 7158bd2f..00000000 --- a/internal/db/migrations/0038_for_you_pick_kind.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE play_events DROP COLUMN pick_kind; -ALTER TABLE playlist_tracks DROP COLUMN pick_kind; diff --git a/internal/db/migrations/0038_for_you_pick_kind.up.sql b/internal/db/migrations/0038_for_you_pick_kind.up.sql deleted file mode 100644 index 29b582f6..00000000 --- a/internal/db/migrations/0038_for_you_pick_kind.up.sql +++ /dev/null @@ -1,34 +0,0 @@ --- For You exploration attribution. --- --- For You is deliberately composed of two populations: a head of --- top-scored similarity matches ("taste" picks) and a tail sampled from --- deeper in the candidate ranking ("fresh" picks — the freshness --- injection). Before this the metrics could only judge For You as one --- blob, so a high skip rate couldn't be read as "the taste engine is --- missing" vs "the freshness tax is too high". --- --- Two denormalized columns, both nullable: --- --- 1. playlist_tracks.pick_kind — stamped by the system-playlist builder --- at snapshot build time. NULL for manual playlists and for system --- variants that don't split (Discover, Songs like X, discovery --- mixes). System snapshots are atomically replaced daily, so the --- column never goes stale within a snapshot. --- --- 2. play_events.pick_kind — stamped at play-ingestion time by looking --- the track up in the user's CURRENT For You snapshot. Attribution --- must be frozen at play time: For You rebuilds daily, so a 30-day --- metrics window spans ~30 snapshots and a join-at-read against the --- live snapshot would misattribute nearly everything. Plays that --- predate this feature (or whose track already rotated out, e.g. a --- late offline replay) stay NULL → reported as unattributed. - -ALTER TABLE playlist_tracks - ADD COLUMN pick_kind text - CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ('taste', 'fresh')); - -ALTER TABLE play_events - ADD COLUMN pick_kind text - CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ('taste', 'fresh')); diff --git a/internal/db/migrations/0039_pick_kind_vocabulary.down.sql b/internal/db/migrations/0039_pick_kind_vocabulary.down.sql deleted file mode 100644 index eb447d38..00000000 --- a/internal/db/migrations/0039_pick_kind_vocabulary.down.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Rows stamped with the widened vocabulary must be cleared before the --- narrow CHECK can be re-added; NULL reads as "unattributed", which is --- the honest downgrade. -UPDATE play_events SET pick_kind = NULL - WHERE pick_kind NOT IN ('taste', 'fresh'); -UPDATE playlist_tracks SET pick_kind = NULL - WHERE pick_kind NOT IN ('taste', 'fresh'); - -ALTER TABLE play_events - DROP CONSTRAINT play_events_pick_kind_check; -ALTER TABLE play_events - ADD CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ('taste', 'fresh')); - -ALTER TABLE playlist_tracks - DROP CONSTRAINT playlist_tracks_pick_kind_check; -ALTER TABLE playlist_tracks - ADD CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ('taste', 'fresh')); diff --git a/internal/db/migrations/0039_pick_kind_vocabulary.up.sql b/internal/db/migrations/0039_pick_kind_vocabulary.up.sql deleted file mode 100644 index c1502d73..00000000 --- a/internal/db/migrations/0039_pick_kind_vocabulary.up.sql +++ /dev/null @@ -1,41 +0,0 @@ --- Provenance as standard. --- --- 0038 introduced pick_kind as a For You one-off ('taste'/'fresh'). --- The mechanism — stamp WHY a track is in the snapshot at build time, --- freeze it onto the play at ingestion, break it down in metrics — is --- now the standard for every system mix, so the CHECK vocabulary --- widens to cover: --- --- taste / fresh For You head vs freshness-injection tail --- dormant / cross_user / random --- Discover's three candidate buckets — makes --- the 40/30/30 allocation measurable instead --- of a guess --- tier1 / tier2 / tier3 the tiered-eligibility ladder: tier 1 pins the --- mix's exact desire, each higher tier steps --- back a little. Tier --- provenance is how we measure what the --- step-back trades away. --- --- Postgres CHECK whitelists can't be altered in place: DROP + re-ADD --- with the expanded list, in the same migration. - -ALTER TABLE playlist_tracks - DROP CONSTRAINT playlist_tracks_pick_kind_check; -ALTER TABLE playlist_tracks - ADD CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', - 'tier1', 'tier2', 'tier3' - )); - -ALTER TABLE play_events - DROP CONSTRAINT play_events_pick_kind_check; -ALTER TABLE play_events - ADD CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', - 'tier1', 'tier2', 'tier3' - )); diff --git a/internal/db/migrations/0040_recommendation_tuning.down.sql b/internal/db/migrations/0040_recommendation_tuning.down.sql deleted file mode 100644 index 9575d0eb..00000000 --- a/internal/db/migrations/0040_recommendation_tuning.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE recommendation_tuning_audit; -DROP TABLE taste_tuning; -DROP TABLE recommendation_weight_profiles; diff --git a/internal/db/migrations/0040_recommendation_tuning.up.sql b/internal/db/migrations/0040_recommendation_tuning.up.sql deleted file mode 100644 index 3d3705d0..00000000 --- a/internal/db/migrations/0040_recommendation_tuning.up.sql +++ /dev/null @@ -1,56 +0,0 @@ --- Recommendation tuning lab. --- --- The scoring weights move out of YAML (radio profile) and out of the --- systemMixWeights hard-code (daily_mix profile) into DB-backed --- settings with live effect — a lab for FINDING good values, which then --- get baked into shipped defaults; nobody should need this card to get --- good recommendations. --- --- Rows are seeded by the recsettings service's boot reconcile (the --- coverart SettingsService pattern), not by this migration, so shipped --- defaults live in exactly one place (Go). - -CREATE TABLE recommendation_weight_profiles ( - profile text PRIMARY KEY - CONSTRAINT recommendation_weight_profiles_profile_check - CHECK (profile IN ('radio', 'daily_mix')), - base_weight double precision NOT NULL, - like_boost double precision NOT NULL, - recency_weight double precision NOT NULL, - skip_penalty double precision NOT NULL, - jitter_magnitude double precision NOT NULL, - context_weight double precision NOT NULL, - similarity_weight double precision NOT NULL, - taste_weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now() -); - --- Taste-profile build knobs: engagement half-life + the completion→ --- engagement curve points (taste.Config's tunable subset). -CREATE TABLE taste_tuning ( - singleton boolean PRIMARY KEY DEFAULT true - CONSTRAINT taste_tuning_singleton_check CHECK (singleton), - half_life_days double precision NOT NULL, - engagement_hard_skip double precision NOT NULL, - engagement_neutral double precision NOT NULL, - engagement_full double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now() -); - --- Every knob turn writes one audit row; the metrics trend view --- annotates these on its timeline so cause→effect is visible --- after a change. changes is a jsonb array of {field, old, new}. -CREATE TABLE recommendation_tuning_audit ( - id bigserial PRIMARY KEY, - changed_at timestamptz NOT NULL DEFAULT now(), - scope text NOT NULL - CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste')), - action text NOT NULL - CONSTRAINT recommendation_tuning_audit_action_check - CHECK (action IN ('update', 'reset')), - changes jsonb NOT NULL -); - -CREATE INDEX recommendation_tuning_audit_changed_at_idx - ON recommendation_tuning_audit (changed_at DESC); diff --git a/internal/db/migrations/0041_discover_taste_unheard.down.sql b/internal/db/migrations/0041_discover_taste_unheard.down.sql deleted file mode 100644 index 2bc620a2..00000000 --- a/internal/db/migrations/0041_discover_taste_unheard.down.sql +++ /dev/null @@ -1,27 +0,0 @@ --- Reverse 0041_discover_taste_unheard.up.sql. --- --- Null out any rows stamped with the new value before shrinking the --- CHECK back to the 0039 vocabulary, or the ADD CONSTRAINT would fail --- on existing 'taste_unheard' rows (mirrors 0039's down). -UPDATE play_events SET pick_kind = NULL WHERE pick_kind = 'taste_unheard'; -UPDATE playlist_tracks SET pick_kind = NULL WHERE pick_kind = 'taste_unheard'; - -ALTER TABLE playlist_tracks - DROP CONSTRAINT playlist_tracks_pick_kind_check; -ALTER TABLE playlist_tracks - ADD CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', - 'tier1', 'tier2', 'tier3' - )); - -ALTER TABLE play_events - DROP CONSTRAINT play_events_pick_kind_check; -ALTER TABLE play_events - ADD CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', - 'tier1', 'tier2', 'tier3' - )); diff --git a/internal/db/migrations/0041_discover_taste_unheard.up.sql b/internal/db/migrations/0041_discover_taste_unheard.up.sql deleted file mode 100644 index 4f8934d1..00000000 --- a/internal/db/migrations/0041_discover_taste_unheard.up.sql +++ /dev/null @@ -1,29 +0,0 @@ --- Discover taste-targeted novelty bucket. --- --- Without it, Discover on a single-user server is effectively dormant + --- crude-random, and the per-user taste profile's tags go unused. This adds a --- fourth Discover candidate bucket that ranks unheard tracks by the --- user's taste-profile tag weights ("novelty that fits your vibe"), so --- its picks need a new pick_kind provenance value. --- --- Postgres CHECK whitelists can't be altered in place: DROP + re-ADD with --- the expanded list, in the same migration. -ALTER TABLE playlist_tracks - DROP CONSTRAINT playlist_tracks_pick_kind_check; -ALTER TABLE playlist_tracks - ADD CONSTRAINT playlist_tracks_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', 'taste_unheard', - 'tier1', 'tier2', 'tier3' - )); - -ALTER TABLE play_events - DROP CONSTRAINT play_events_pick_kind_check; -ALTER TABLE play_events - ADD CONSTRAINT play_events_pick_kind_check - CHECK (pick_kind IN ( - 'taste', 'fresh', - 'dormant', 'cross_user', 'random', 'taste_unheard', - 'tier1', 'tier2', 'tier3' - )); diff --git a/internal/db/migrations/0042_track_tags.down.sql b/internal/db/migrations/0042_track_tags.down.sql deleted file mode 100644 index e60b8a3d..00000000 --- a/internal/db/migrations/0042_track_tags.down.sql +++ /dev/null @@ -1,5 +0,0 @@ --- Reverse 0042_track_tags.up.sql. -DROP INDEX IF EXISTS tracks_tag_source_idx; -ALTER TABLE tracks DROP COLUMN IF EXISTS tag_sources_version; -ALTER TABLE tracks DROP COLUMN IF EXISTS tag_source; -DROP TABLE IF EXISTS track_tags; diff --git a/internal/db/migrations/0042_track_tags.up.sql b/internal/db/migrations/0042_track_tags.up.sql deleted file mode 100644 index 8c49156d..00000000 --- a/internal/db/migrations/0042_track_tags.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Track-level folksonomy tags for taste enrichment. --- --- A global (not per-user) cache of style/mood tags fetched from --- MusicBrainz (keyless) + Last.fm (when a key is configured), keyed by --- track. Feeds the taste recompute's tag facet alongside raw ID3 genre, --- lifting resolution from coarse "Rock" to "post-punk / shoegaze / --- melancholic". The enricher caps to the top-K tags per track at write --- time so a heavily-tagged track can't dominate the profile. weight is a --- normalized folksonomy strength in [0,1]. Mirrors the coverart --- enricher's versioned source-tracking pattern. -CREATE TABLE track_tags ( - track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - tag text NOT NULL, - weight double precision NOT NULL DEFAULT 1, - PRIMARY KEY (track_id, tag) -); -CREATE INDEX track_tags_track_idx ON track_tags (track_id); - --- Enrichment bookkeeping (mirror artists.artist_art_source): --- tag_source NULL → not yet processed (eligible) --- tag_source 'lastfm' / 'musicbrainz' / 'mixed' → found, cached --- tag_source 'none' → providers returned nothing --- tag_sources_version → bump to re-process none/stale -ALTER TABLE tracks ADD COLUMN tag_source text; -ALTER TABLE tracks ADD COLUMN tag_sources_version integer NOT NULL DEFAULT 0; -CREATE INDEX tracks_tag_source_idx ON tracks (tag_source, tag_sources_version); diff --git a/internal/db/migrations/0043_tag_provider_settings.down.sql b/internal/db/migrations/0043_tag_provider_settings.down.sql deleted file mode 100644 index 6c82f9d0..00000000 --- a/internal/db/migrations/0043_tag_provider_settings.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- Reverse 0043_tag_provider_settings.up.sql. -DROP TABLE IF EXISTS tag_sources_meta; -DROP TABLE IF EXISTS tag_provider_settings; diff --git a/internal/db/migrations/0043_tag_provider_settings.up.sql b/internal/db/migrations/0043_tag_provider_settings.up.sql deleted file mode 100644 index f7a87cd8..00000000 --- a/internal/db/migrations/0043_tag_provider_settings.up.sql +++ /dev/null @@ -1,38 +0,0 @@ --- Tag-enrichment provider settings. --- --- Mirrors the cover-art provider-settings substrate (migration 0018) so --- adding a new tag source later is "register a provider + it auto-upserts --- a row here" — never a schema change. The tag enricher reads the enabled --- set + api keys from tag_provider_settings and stamps the current version --- from tag_sources_meta onto tracks.tag_sources_version (added in 0042). --- --- current_version starts at 1 while tracks.tag_sources_version defaults to --- 0 (migration 0042), so every existing track is "stale" relative to --- current and gets enriched on the first pass after this migrates. - -CREATE TABLE tag_provider_settings ( - provider_id text PRIMARY KEY, - enabled boolean NOT NULL DEFAULT true, - api_key text, - display_order int NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE TABLE tag_sources_meta ( - id boolean PRIMARY KEY DEFAULT true, - current_version int NOT NULL DEFAULT 1, - last_registered_providers_hash text NOT NULL DEFAULT '', - CONSTRAINT tag_sources_meta_singleton CHECK (id = true) -); -INSERT INTO tag_sources_meta (id, current_version) VALUES (true, 1); - --- Seed the v1 providers. MusicBrainz is the keyless always-on default; --- Last.fm ships disabled and is opt-in once an admin supplies a key in --- Settings: a feature that needs a third-party account is never on by --- default. The --- SettingsService also upserts these at boot, so the seed is belt-and- --- suspenders / documents the intended defaults. -INSERT INTO tag_provider_settings (provider_id, enabled, display_order) VALUES - ('musicbrainz', true, 0), - ('lastfm', false, 1); diff --git a/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.down.sql b/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.down.sql deleted file mode 100644 index 4ad01726..00000000 --- a/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Reverse 0044_taste_tuning_enriched_tag_scale.up.sql. -ALTER TABLE taste_tuning DROP COLUMN IF EXISTS enriched_tag_scale; diff --git a/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.up.sql b/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.up.sql deleted file mode 100644 index c02818b4..00000000 --- a/internal/db/migrations/0044_taste_tuning_enriched_tag_scale.up.sql +++ /dev/null @@ -1,6 +0,0 @@ --- Expose EnrichedTagScale in the tuning lab. Adds the enriched-tag --- weight knob to the taste_tuning singleton so an admin can dial how much --- folksonomy tags count vs raw ID3 genre. DEFAULT 0.5 backfills the --- existing row and matches taste.DefaultConfig().EnrichedTagScale. -ALTER TABLE taste_tuning - ADD COLUMN enriched_tag_scale double precision NOT NULL DEFAULT 0.5; diff --git a/internal/db/migrations/0045_taste_profile_eras.down.sql b/internal/db/migrations/0045_taste_profile_eras.down.sql deleted file mode 100644 index bbd08459..00000000 --- a/internal/db/migrations/0045_taste_profile_eras.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE taste_tuning DROP COLUMN IF EXISTS era_scale; -DROP TABLE IF EXISTS taste_profile_eras; diff --git a/internal/db/migrations/0045_taste_profile_eras.up.sql b/internal/db/migrations/0045_taste_profile_eras.up.sql deleted file mode 100644 index b4cdbfe1..00000000 --- a/internal/db/migrations/0045_taste_profile_eras.up.sql +++ /dev/null @@ -1,26 +0,0 @@ --- 0045_taste_profile_eras.up.sql — era/decade taste facet. A third taste --- facet alongside artists + tags: --- signed weights over decade buckets ("1990s") derived from --- albums.release_date, rebuilt daily by internal/taste next to the --- artist/tag facets. Weight is a signed float — positive = drawn to --- that era, negative = passively avoided; magnitude reflects decayed --- engagement. Consumed by the recommendation scorer's taste match. --- Mirrors taste_profile_tags: CASCADE on user delete, indexed by --- (user_id, weight DESC) so "top eras" reads stay cheap. -CREATE TABLE taste_profile_eras ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - era text NOT NULL, - weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, era) -); - -CREATE INDEX taste_profile_eras_user_weight_idx - ON taste_profile_eras (user_id, weight DESC); - --- Era-facet build knob, tunable in the lab (mirrors enriched_tag_scale): --- scales how strongly a decade-play imprints on the profile. --- DEFAULT 0.5 backfills the existing singleton and matches --- taste.DefaultConfig().EraScale; 0 disables the era facet entirely. -ALTER TABLE taste_tuning - ADD COLUMN era_scale double precision NOT NULL DEFAULT 0.5; diff --git a/internal/db/migrations/0046_context_time_weight.down.sql b/internal/db/migrations/0046_context_time_weight.down.sql deleted file mode 100644 index d2be5249..00000000 --- a/internal/db/migrations/0046_context_time_weight.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE recommendation_weight_profiles DROP COLUMN IF EXISTS context_time_weight; diff --git a/internal/db/migrations/0046_context_time_weight.up.sql b/internal/db/migrations/0046_context_time_weight.up.sql deleted file mode 100644 index f592279a..00000000 --- a/internal/db/migrations/0046_context_time_weight.up.sql +++ /dev/null @@ -1,12 +0,0 @@ --- 0046_context_time_weight.up.sql — time-of-day/weekday context conditioning. --- Adds a per-profile scoring weight for the new --- context-affinity term: how strongly a candidate is boosted when its artist's --- play history concentrates in the current daypart × weekday-type cell (in the --- user's local timezone). Mirrors the other ScoringWeights columns. --- --- DEFAULT 1.0 backfills both existing profile rows to a modest on-value; the --- Go ShippedRadioWeights/ShippedDailyMixWeights carry the same 1.0 so fresh --- installs seed identically. Reconcile only seeds MISSING rows (ON CONFLICT DO --- NOTHING), so existing rows rely on this DEFAULT until an admin resets. -ALTER TABLE recommendation_weight_profiles - ADD COLUMN context_time_weight double precision NOT NULL DEFAULT 1.0; diff --git a/internal/db/migrations/0047_taste_profile_moods.down.sql b/internal/db/migrations/0047_taste_profile_moods.down.sql deleted file mode 100644 index ae61a7dd..00000000 --- a/internal/db/migrations/0047_taste_profile_moods.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE taste_tuning DROP COLUMN IF EXISTS mood_scale; -DROP TABLE IF EXISTS taste_profile_moods; diff --git a/internal/db/migrations/0047_taste_profile_moods.up.sql b/internal/db/migrations/0047_taste_profile_moods.up.sql deleted file mode 100644 index 5fd5ffbb..00000000 --- a/internal/db/migrations/0047_taste_profile_moods.up.sql +++ /dev/null @@ -1,25 +0,0 @@ --- 0047_taste_profile_moods.up.sql — mood taste facet. A fourth taste facet --- alongside artists + tags + eras: signed weights over canonical mood buckets --- (melancholic / energetic / chill / …) derived from a track's enriched --- folksonomy tags via the internal/mood vocabulary, rebuilt daily. Weight is a --- signed float — positive = drawn to that mood, negative = passively avoided. --- Coverage is partial (grows with tag enrichment), so it's a supplement, not a --- foundation. Mirrors taste_profile_tags: CASCADE on user delete, indexed by --- (user_id, weight DESC). -CREATE TABLE taste_profile_moods ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - mood text NOT NULL, - weight double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, mood) -); - -CREATE INDEX taste_profile_moods_user_weight_idx - ON taste_profile_moods (user_id, weight DESC); - --- Mood-facet build knob, tunable in the lab (mirrors era_scale / enriched_tag_ --- scale): scales how strongly a mood-tagged play imprints on the profile. --- DEFAULT 0.5 backfills the existing singleton and matches --- taste.DefaultConfig().MoodScale; 0 disables the mood facet entirely. -ALTER TABLE taste_tuning - ADD COLUMN mood_scale double precision NOT NULL DEFAULT 0.5; diff --git a/internal/db/migrations/0048_play_events_device_class.down.sql b/internal/db/migrations/0048_play_events_device_class.down.sql deleted file mode 100644 index 4742e15a..00000000 --- a/internal/db/migrations/0048_play_events_device_class.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE play_events DROP COLUMN IF EXISTS device_class; diff --git a/internal/db/migrations/0048_play_events_device_class.up.sql b/internal/db/migrations/0048_play_events_device_class.up.sql deleted file mode 100644 index 6177f1a7..00000000 --- a/internal/db/migrations/0048_play_events_device_class.up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- 0048_play_events_device_class.up.sql — device-class context conditioning. --- Records which class of device a play came from (mobile / web / …), sent by --- the client on play-start and normalized server-side. Extends the --- time-of-day/weekday affinity cell (0046) to (daypart × weekday × device) for --- the radio path. Nullable + no CHECK: values are normalized in Go, so a new --- client class needs no migration, and historical rows stay NULL → excluded --- from the device dimension (a graceful cold-start; the facet ramps as new --- plays land). -ALTER TABLE play_events ADD COLUMN device_class text; diff --git a/internal/db/migrations/0049_suggestion_snoozes.down.sql b/internal/db/migrations/0049_suggestion_snoozes.down.sql deleted file mode 100644 index 05f6770d..00000000 --- a/internal/db/migrations/0049_suggestion_snoozes.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS suggestion_snoozes_expiry_idx; -DROP TABLE IF EXISTS suggestion_snoozes; diff --git a/internal/db/migrations/0049_suggestion_snoozes.up.sql b/internal/db/migrations/0049_suggestion_snoozes.up.sql deleted file mode 100644 index 9b55ef27..00000000 --- a/internal/db/migrations/0049_suggestion_snoozes.up.sql +++ /dev/null @@ -1,34 +0,0 @@ --- 0049_suggestion_snoozes.up.sql — time-boxed "not right now" on a Discover --- artist suggestion. --- --- This is NOT a dislike. Minstrel has no "Not for me" / thumbs-down / --- exclusion control — taste is learned from listening — and a snooze --- deliberately isn't one: it records no verdict on --- the music, expires on its own, and MUST NEVER feed the taste profile. It is --- acquisition triage — "I don't want to request this right now" — so the same --- candidate is free to return once snoozed_until passes. Anything that reads --- this table as negative preference signal is a bug. --- --- Per-user, never global: one household member parking a --- suggestion must not remove it from anyone else's deck. --- --- candidate_mbid is text with NO foreign key, on purpose. Suggestions come --- from artist_similarity_unmatched and are out-of-library BY DEFINITION, so --- there is no artists row to reference — the MBID is the only stable identity --- available. candidate_name is denormalized for the same reason: the manage / --- un-snooze list has nowhere else to resolve a display name from. - -CREATE TABLE suggestion_snoozes ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - candidate_mbid text NOT NULL, - candidate_name text NOT NULL, - snoozed_until timestamptz NOT NULL, - created_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, candidate_mbid) -); - --- Supports the gc sweep's unqualified `WHERE snoozed_until < now()` scan. The --- composite PK already covers every per-user read, so this is the only extra --- index worth its write cost at household-scale row counts (same reasoning as --- lidarr_quarantine in 0011). -CREATE INDEX suggestion_snoozes_expiry_idx ON suggestion_snoozes (snoozed_until); diff --git a/internal/db/migrations/0050_candidate_artist_tags.down.sql b/internal/db/migrations/0050_candidate_artist_tags.down.sql deleted file mode 100644 index cd7cd862..00000000 --- a/internal/db/migrations/0050_candidate_artist_tags.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS candidate_artist_tag_state_source_idx; -DROP TABLE IF EXISTS candidate_artist_tag_state; -DROP TABLE IF EXISTS candidate_artist_tags; diff --git a/internal/db/migrations/0050_candidate_artist_tags.up.sql b/internal/db/migrations/0050_candidate_artist_tags.up.sql deleted file mode 100644 index 72896af5..00000000 --- a/internal/db/migrations/0050_candidate_artist_tags.up.sql +++ /dev/null @@ -1,53 +0,0 @@ --- 0050_candidate_artist_tags.up.sql — folksonomy tags for OUT-OF-LIBRARY --- artists. --- --- track_tags (0042) cannot hold these: it is FK'd to tracks(id), and a --- Discover candidate has no local row by definition. So this is a parallel --- cache keyed by the candidate's MusicBrainz MBID — the only stable identity --- available for an artist we don't have. --- --- Purpose: rank Discover suggestions by overlap between these tags and the --- user's taste_profile_tags, turning "neighbour of an artist you play" into --- "matches the sound you like". --- --- GLOBAL, not per-user: a candidate's tags are a property of the artist, not --- of anyone's taste. The per-user part lives entirely in the ranking. --- --- weight is a normalized folksonomy strength in [0,1], same scale as --- track_tags, so the two can be compared without a conversion step. -CREATE TABLE candidate_artist_tags ( - candidate_mbid text NOT NULL, - tag text NOT NULL, - weight double precision NOT NULL DEFAULT 1, - PRIMARY KEY (candidate_mbid, tag) -); - --- Enrichment bookkeeping. This is a SEPARATE table rather than columns on the --- tags table, because the "providers had nothing" outcome must be recordable --- for a candidate with zero tag rows — otherwise every empty candidate stays --- eligible forever and the worker re-fetches it on every tick. --- --- tracks solved the same problem with columns on `tracks` (0042), but there is --- no per-candidate row anywhere to hang them off: artist_similarity_unmatched --- is keyed (seed_artist_id, candidate_mbid, source) and holds MANY rows per --- candidate. --- --- Absence of a row here means "never processed", so unlike tracks.tag_source --- this column can be NOT NULL — there is no null-means-pending state to model. --- 'musicbrainz' | 'lastfm' | 'mixed' → found, cached --- 'none' → providers confirmed nothing --- tag_sources_version → bump to re-process settled 'none' --- --- A transient failure writes NO row at all (rather than a row it would then --- have to distinguish), which leaves the candidate eligible for the next pass. -CREATE TABLE candidate_artist_tag_state ( - candidate_mbid text PRIMARY KEY, - tag_source text NOT NULL, - tag_sources_version integer NOT NULL DEFAULT 0, - updated_at timestamptz NOT NULL DEFAULT now() -); - --- Serves the eligibility scan's "settled 'none' under an older version" --- branch. The PK already covers the per-candidate lookups. -CREATE INDEX candidate_artist_tag_state_source_idx - ON candidate_artist_tag_state (tag_source, tag_sources_version); diff --git a/internal/db/migrations/0051_discover_tuning.down.sql b/internal/db/migrations/0051_discover_tuning.down.sql deleted file mode 100644 index 1da70de4..00000000 --- a/internal/db/migrations/0051_discover_tuning.down.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Drop any audit rows under the scope the constraint is about to forbid, --- otherwise re-adding the narrower CHECK fails against existing data. -DELETE FROM recommendation_tuning_audit WHERE scope = 'discover'; -ALTER TABLE recommendation_tuning_audit - DROP CONSTRAINT recommendation_tuning_audit_scope_check; -ALTER TABLE recommendation_tuning_audit - ADD CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste')); - -DROP TABLE IF EXISTS discover_tuning; diff --git a/internal/db/migrations/0051_discover_tuning.up.sql b/internal/db/migrations/0051_discover_tuning.up.sql deleted file mode 100644 index e0cdacfe..00000000 --- a/internal/db/migrations/0051_discover_tuning.up.sql +++ /dev/null @@ -1,38 +0,0 @@ --- 0051_discover_tuning.up.sql — tunable knobs for the Discover request --- surface. --- --- A FOURTH tuning scope alongside radio / daily_mix / taste. Its own scope --- rather than extra columns on taste_tuning, for a reason that matters: --- snooze_days lives here, and a snooze must never be read as taste signal --- (0049). Filing it under 'taste' would put it one careless join away from --- exactly that leak. --- --- These are DB-backed and editable in the admin UI with no restart — the --- shipped values below are defaults, not settings. -CREATE TABLE discover_tuning ( - singleton boolean PRIMARY KEY DEFAULT true - CONSTRAINT discover_tuning_singleton_check CHECK (singleton), - -- How strongly taste-tag overlap boosts a candidate's similarity score. - -- The blend is MULTIPLICATIVE: score * (1 + w * overlap), overlap in - -- [0,1]. So 0 disables the feature outright and leaves pure similarity - -- ranking, 1.0 lets a perfectly-matching candidate double its score, and - -- a candidate with no cached tags is unchanged rather than penalised - -- (tag coverage is permanently partial, so a missing tag is no signal). - tag_overlap_weight double precision NOT NULL, - -- Default snooze duration in days. Before this a Go constant in - -- internal/api/suggestions.go; now an admin setting. - snooze_days double precision NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now() -); - -INSERT INTO discover_tuning (singleton, tag_overlap_weight, snooze_days) -VALUES (true, 1.0, 90); - --- Rule #36: a new value for a CHECK-gated column needs the constraint --- rewritten in the SAME change, or the first audit row written under the new --- scope fails at runtime rather than at migrate time. -ALTER TABLE recommendation_tuning_audit - DROP CONSTRAINT recommendation_tuning_audit_scope_check; -ALTER TABLE recommendation_tuning_audit - ADD CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste', 'discover')); diff --git a/internal/db/migrations/0052_session_ips.down.sql b/internal/db/migrations/0052_session_ips.down.sql deleted file mode 100644 index e1e631d6..00000000 --- a/internal/db/migrations/0052_session_ips.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE sessions - DROP COLUMN created_ip, - DROP COLUMN last_ip; diff --git a/internal/db/migrations/0052_session_ips.up.sql b/internal/db/migrations/0052_session_ips.up.sql deleted file mode 100644 index b461d925..00000000 --- a/internal/db/migrations/0052_session_ips.up.sql +++ /dev/null @@ -1,19 +0,0 @@ --- Session provenance for the active-sessions surface. --- --- TWO addresses, not one, and the pair is the point: a session created at --- home and now being used from somewhere else is the shape of a stolen --- token. A single "current IP" column can't express that, and a single --- "origin IP" column goes stale the moment the token moves. --- --- text rather than inet, matching user_agent directly above: these are --- stored to be displayed, never queried by subnet, and inet round-trips --- through pgx/sqlc as a netip.Prefix that renders as "1.2.3.4/32" and would --- need unwrapping at every display site. --- --- DEFAULT '' rather than NULL so existing rows — and any future insert that --- genuinely can't determine an address — stay renderable without a null --- check at every call site. The UI reads empty as "unknown" rather than --- inventing a value. -ALTER TABLE sessions - ADD COLUMN created_ip text NOT NULL DEFAULT '', - ADD COLUMN last_ip text NOT NULL DEFAULT ''; diff --git a/internal/db/migrations/0053_network_settings.down.sql b/internal/db/migrations/0053_network_settings.down.sql deleted file mode 100644 index 88c2e842..00000000 --- a/internal/db/migrations/0053_network_settings.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE network_settings; diff --git a/internal/db/migrations/0053_network_settings.up.sql b/internal/db/migrations/0053_network_settings.up.sql deleted file mode 100644 index a995af37..00000000 --- a/internal/db/migrations/0053_network_settings.up.sql +++ /dev/null @@ -1,34 +0,0 @@ --- Trusted reverse-proxy depth for client-IP extraction. --- --- X-Forwarded-For grows left-to-right: each proxy APPENDS the peer it --- received the request from. For client -> CDN -> own-proxy -> Minstrel the --- app sees XFF = [client, CDN] with RemoteAddr = own-proxy. So the real --- client sits at XFF[len - hops], where hops counts the proxies you trust: --- --- 0 no proxy in front — use the socket peer, ignore XFF entirely --- 1 one reverse proxy (nginx / Caddy / Traefik terminating TLS) --- 2 a CDN in front of your own proxy (Cloudflare -> nginx -> Minstrel) --- --- Default 1: a publicly reachable Minstrel needs a TLS terminator in front of --- it, and recording that terminator's own address for every session makes the --- active-sessions surface useless — created_ip and last_ip would both --- be the proxy, so the "address changed" signal could never fire. --- --- The cost, stated on the admin card rather than buried: hops >= 1 DECLARES --- that a proxy exists. If one doesn't, a client can forge X-Forwarded-For and --- choose what its own session row shows, which defeats exactly the compromise --- detection the active-sessions surface exists for. That is inherent to the --- trusted-hop model, which is why 0 is a first-class setting and not a hidden --- escape hatch. --- --- Upper bound 10 guards a typo turning into "trust the whole header"; no real --- deployment chains ten proxies. -CREATE TABLE network_settings ( - id boolean PRIMARY KEY DEFAULT true, - trusted_proxy_hops int NOT NULL DEFAULT 1, - CONSTRAINT network_settings_singleton CHECK (id = true), - CONSTRAINT network_settings_hops_range - CHECK (trusted_proxy_hops >= 0 AND trusted_proxy_hops <= 10) -); - -INSERT INTO network_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0054_track_tag_read_version.down.sql b/internal/db/migrations/0054_track_tag_read_version.down.sql deleted file mode 100644 index b948246e..00000000 --- a/internal/db/migrations/0054_track_tag_read_version.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE tracks - DROP COLUMN tag_read_version; diff --git a/internal/db/migrations/0054_track_tag_read_version.up.sql b/internal/db/migrations/0054_track_tag_read_version.up.sql deleted file mode 100644 index e9b0f3a8..00000000 --- a/internal/db/migrations/0054_track_tag_read_version.up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- Records which version of the scanner's tag-extraction logic last wrote a --- track's tag-derived columns. --- --- DEFAULT 0 is the point of this migration: every existing row lands below the --- scanner's current library.tagReadVersion, so the next scan re-reads its tags --- instead of short-circuiting on the mtime check. That repairs genre values the --- old reader welded together ("Alternative Rock" + "Rock" -> "Alternative --- RockRock") without anyone wiping and rebuilding the library. --- --- Bump library.tagReadVersion in Go — not this default — whenever a tag --- extraction fix needs to reach already-indexed files. That makes tag repairs a --- self-healing scan rather than a manual full rebuild, which is why this is a --- version number and not a boolean "needs_reread" flag. -ALTER TABLE tracks - ADD COLUMN tag_read_version smallint NOT NULL DEFAULT 0; diff --git a/internal/db/migrations/0055_track_missing_since.down.sql b/internal/db/migrations/0055_track_missing_since.down.sql deleted file mode 100644 index d9bc5bc1..00000000 --- a/internal/db/migrations/0055_track_missing_since.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DROP INDEX IF EXISTS tracks_missing_since_idx; - -ALTER TABLE tracks - DROP COLUMN missing_since; diff --git a/internal/db/migrations/0055_track_missing_since.up.sql b/internal/db/migrations/0055_track_missing_since.up.sql deleted file mode 100644 index 64cdea80..00000000 --- a/internal/db/migrations/0055_track_missing_since.up.sql +++ /dev/null @@ -1,25 +0,0 @@ --- Marks a track whose file the scanner could no longer find. --- --- NULL means present. A timestamp means the file was absent as of that scan, --- and is the point from which "how long has this been gone" is measured — which --- is what a later cleanup pass needs in order to require a grace period rather --- than deleting on a single missed stat. --- --- Deliberately a nullable timestamp rather than a boolean: "missing" is not a --- state we want to act on immediately, and the age is the only thing that makes --- an automated deletion safe to reason about. --- --- No default and no backfill. Existing rows start NULL (present) and the next --- full scan sets the mark where it belongs — a migration cannot check the --- filesystem, and guessing here would mark the whole library on a server whose --- media volume happens to be detached at upgrade time. -ALTER TABLE tracks - ADD COLUMN missing_since timestamptz; - --- Partial index: the only query that filters on this column positively is the --- admin "what's missing" list, which is a small set. Playback and browse --- queries filter `missing_since IS NULL`, which matches nearly every row and is --- better served by a sequential scan than an index lookup. -CREATE INDEX tracks_missing_since_idx - ON tracks (missing_since) - WHERE missing_since IS NOT NULL; diff --git a/internal/db/migrations/0056_missing_reacquisition.down.sql b/internal/db/migrations/0056_missing_reacquisition.down.sql deleted file mode 100644 index 5acbc0ba..00000000 --- a/internal/db/migrations/0056_missing_reacquisition.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS reacquisition_settings; -DROP TABLE IF EXISTS missing_reacquisitions; diff --git a/internal/db/migrations/0056_missing_reacquisition.up.sql b/internal/db/migrations/0056_missing_reacquisition.up.sql deleted file mode 100644 index 175b576f..00000000 --- a/internal/db/migrations/0056_missing_reacquisition.up.sql +++ /dev/null @@ -1,97 +0,0 @@ --- Auto re-acquisition of missing files via Lidarr. Before this a missing --- file was a dead end: reconcile marks it, every selection path skips it, --- the admin surface lists it, and there it sits. --- --- The unit here is the ALBUM, not the track, and that is the design decision --- carrying most of the safety. Lidarr acquires releases; there is no --- meaningful "fetch me one track" operation, and a track-kind request needs a --- recording MBID plenty of files simply don't have. Grouping by album means --- a reorganised album with dozens of missing files becomes one request. - -CREATE TABLE missing_reacquisitions ( - album_id uuid PRIMARY KEY REFERENCES albums (id) ON DELETE CASCADE, - attempts int NOT NULL DEFAULT 0, - last_attempt_at timestamptz, - -- The request this album's most recent attempt produced. SET NULL rather - -- than CASCADE: a purged request row must not erase the attempt history - -- that stops us asking again in a loop. - last_request_id uuid REFERENCES lidarr_requests (id) ON DELETE SET NULL, - -- Set when the attempt budget is spent. Distinct from "attempts = max" - -- so the reason survives a later change to the configured maximum, and so - -- the admin surface can say "gave up on the 3rd of August" rather than - -- inferring it. - gave_up_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT missing_reacquisitions_attempts_nonneg CHECK (attempts >= 0) -); - --- The sweeper's own read: albums due another attempt, oldest attempt first. --- Partial on the not-given-up rows because a spent album is never selected --- again and would otherwise grow the index forever. -CREATE INDEX missing_reacquisitions_due_idx - ON missing_reacquisitions (last_attempt_at NULLS FIRST) - WHERE gave_up_at IS NULL; - --- Settings, singleton in the style of network_settings (0053). Every value an --- admin might want to tune lives here rather than in YAML, changed without a --- restart. -CREATE TABLE reacquisition_settings ( - id boolean PRIMARY KEY DEFAULT true, - - -- Master switch. Default true: this is meant to happen by itself, and a - -- feature that ships switched off is a feature nobody finds. - enabled boolean NOT NULL DEFAULT true, - - -- How long a file must have been missing before the FIRST attempt. This - -- is what separates "automatic" from "trigger-happy": a filesystem lies - -- transiently -- an unmounted volume, a container that started before its - -- media mount attached, a NAS mid-reboot -- and every one of those - -- resolves itself well inside a day at no cost. tracks.missing_since is - -- never re-stamped, so it is a true "gone since" clock to measure - -- against. - grace_hours int NOT NULL DEFAULT 24, - - -- Exponential spacing between attempts: base * 2^(attempts-1), clamped to - -- backoff_max_hours. 6h -> 12h -> 24h -> 48h by default. An album Lidarr - -- genuinely cannot find must get quieter, not keep pace. - backoff_base_hours int NOT NULL DEFAULT 6, - backoff_max_hours int NOT NULL DEFAULT 168, -- one week - - -- Attempts before giving up. Three real tries spread over days is enough - -- to ride out a transient Lidarr/indexer outage; past that the answer is - -- "this release is not obtainable" and asking again is noise. - max_attempts int NOT NULL DEFAULT 3, - - -- Ceiling on requests created per sweep. Album grouping already collapses - -- the common case, but a genuinely large loss (a whole drive slipping - -- under reconcile's 25% mark cap) should still trickle rather than dump - -- hundreds of requests into the queue at once. - max_per_pass int NOT NULL DEFAULT 20, - - -- Whether the sweeper approves what it creates. Requests are created - -- pending and nothing reaches Lidarr until approval, so with this off the - -- feature is a notification rather than an attempt -- which is why the - -- default is on. Off is the review-first posture: rows appear in the - -- admin Requests queue for a human to release. - auto_approve boolean NOT NULL DEFAULT true, - - CONSTRAINT reacquisition_settings_singleton CHECK (id = true), - -- Ranges exist to stop a typo becoming a behaviour change: a 0-hour grace - -- would fire on every transient unmount, and a 10000-per-pass cap would - -- defeat the point of having one. - CONSTRAINT reacquisition_settings_grace_range - CHECK (grace_hours >= 1 AND grace_hours <= 720), - CONSTRAINT reacquisition_settings_backoff_base_range - CHECK (backoff_base_hours >= 1 AND backoff_base_hours <= 168), - CONSTRAINT reacquisition_settings_backoff_max_range - CHECK (backoff_max_hours >= 1 AND backoff_max_hours <= 720), - CONSTRAINT reacquisition_settings_backoff_ordered - CHECK (backoff_max_hours >= backoff_base_hours), - CONSTRAINT reacquisition_settings_attempts_range - CHECK (max_attempts >= 1 AND max_attempts <= 10), - CONSTRAINT reacquisition_settings_per_pass_range - CHECK (max_per_pass >= 1 AND max_per_pass <= 200) -); - -INSERT INTO reacquisition_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0057_songs_like_tuning.down.sql b/internal/db/migrations/0057_songs_like_tuning.down.sql deleted file mode 100644 index 96070ff5..00000000 --- a/internal/db/migrations/0057_songs_like_tuning.down.sql +++ /dev/null @@ -1,16 +0,0 @@ --- Drop the rows the narrower constraints are about to forbid, or re-adding --- them fails against existing data (the 0051 down-migration pattern). -DELETE FROM recommendation_weight_profiles WHERE profile = 'songs_like'; -DELETE FROM recommendation_tuning_audit WHERE scope = 'songs_like'; - -ALTER TABLE recommendation_tuning_audit - DROP CONSTRAINT recommendation_tuning_audit_scope_check; -ALTER TABLE recommendation_tuning_audit - ADD CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste', 'discover')); - -ALTER TABLE recommendation_weight_profiles - DROP CONSTRAINT recommendation_weight_profiles_profile_check; -ALTER TABLE recommendation_weight_profiles - ADD CONSTRAINT recommendation_weight_profiles_profile_check - CHECK (profile IN ('radio', 'daily_mix')); diff --git a/internal/db/migrations/0057_songs_like_tuning.up.sql b/internal/db/migrations/0057_songs_like_tuning.up.sql deleted file mode 100644 index c8071e66..00000000 --- a/internal/db/migrations/0057_songs_like_tuning.up.sql +++ /dev/null @@ -1,33 +0,0 @@ --- 0057_songs_like_tuning.up.sql — a THIRD weight profile, for Songs-like. --- --- Before: Songs-like shared the `daily_mix` profile with For-You. The two --- surfaces want opposite things: For-You is a broad "what will they enjoy --- today", Songs-like answers "what sounds like THIS" and should stay in one --- neighbourhood of sound, and under one set of weights the broad answer wins. --- --- Under the shared daily_mix weights, an UNRELATED track the user had liked --- and not played recently scored 1.0 + 2.0 + 1.0 = 4.0 before taste, while a --- PERFECT similarity match they had not liked scored 1.0 + 1.5 = 2.5. Liking --- something outranked sounding like the seed. Splitting the profile is what --- lets similarity dominate here without making For-You narrow. --- --- Rows are seeded by the recsettings boot reconcile, not here, so shipped --- defaults live in exactly one place (Go) — same as 0040. - --- Rule #36: a new value for a CHECK-gated column needs the constraint --- rewritten in the SAME change, or the first row written under the new --- profile fails at runtime rather than at migrate time. -ALTER TABLE recommendation_weight_profiles - DROP CONSTRAINT recommendation_weight_profiles_profile_check; -ALTER TABLE recommendation_weight_profiles - ADD CONSTRAINT recommendation_weight_profiles_profile_check - CHECK (profile IN ('radio', 'daily_mix', 'songs_like')); - --- The audit table gates the same name on a separate constraint. Missing this --- one would let the profile be seeded and then fail on the first knob turn — --- green at boot, 500 on first use. -ALTER TABLE recommendation_tuning_audit - DROP CONSTRAINT recommendation_tuning_audit_scope_check; -ALTER TABLE recommendation_tuning_audit - ADD CONSTRAINT recommendation_tuning_audit_scope_check - CHECK (scope IN ('radio', 'daily_mix', 'taste', 'discover', 'songs_like')); diff --git a/internal/db/migrations/0058_track_fingerprints.down.sql b/internal/db/migrations/0058_track_fingerprints.down.sql deleted file mode 100644 index c04a359c..00000000 --- a/internal/db/migrations/0058_track_fingerprints.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE track_fingerprints; diff --git a/internal/db/migrations/0058_track_fingerprints.up.sql b/internal/db/migrations/0058_track_fingerprints.up.sql deleted file mode 100644 index a42e6151..00000000 --- a/internal/db/migrations/0058_track_fingerprints.up.sql +++ /dev/null @@ -1,37 +0,0 @@ --- 0058_track_fingerprints.up.sql — an acoustic identity per track. --- --- A table of its own rather than columns on tracks, for the hot path's sake: --- tracks is read with SELECT * by eight queries, among them ListTracksByAlbum, --- SearchTracks and GetTracksByIDs — album pages, search, the Subsonic surface. --- A ~4 KB chromaprint column on tracks would be de-TOASTed on every one of --- those reads to carry a value only the duplicate sweep ever looks at. --- --- What a row means, which the backfill depends on: --- no row never fingerprinted --- fingerprint_version < current derived by an older method; re-derive it --- fingerprint_version = current attempted; a NULL value means that tool --- failed on this file, and it is not retried --- until the file changes --- A failure that says nothing about the file — a timeout, a cancelled scan, a --- missing binary — writes no row at all, so the backfill tries again. -CREATE TABLE track_fingerprints ( - -- CASCADE is right here, unlike for the likes and play history the - -- duplicate merge has to carry across: a fingerprint describes one file's - -- bytes and means nothing once that file's row is gone. - track_id uuid PRIMARY KEY REFERENCES tracks (id) ON DELETE CASCADE, - -- SHA-256 of the ENCODED audio packets (ffmpeg -c:a copy -f hash), not of - -- decoded samples. internal/library/fingerprint.go says why. - audio_stream_sha256 bytea - CHECK (audio_stream_sha256 IS NULL OR octet_length(audio_stream_sha256) = 32), - -- fpcalc -raw -signed: the same 32 bits per item, stored signed because - -- integer is. - chromaprint integer[], - fingerprint_version smallint NOT NULL, - computed_at timestamptz NOT NULL DEFAULT now() -); - --- The exact duplicate tier is an equality match on this column. Partial --- because a NULL is never looked up — it only means the hash was not taken. -CREATE INDEX track_fingerprints_audio_stream_sha256 - ON track_fingerprints (audio_stream_sha256) - WHERE audio_stream_sha256 IS NOT NULL; diff --git a/internal/db/migrations/0059_duplicate_groups.down.sql b/internal/db/migrations/0059_duplicate_groups.down.sql deleted file mode 100644 index 1d37bf4c..00000000 --- a/internal/db/migrations/0059_duplicate_groups.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DROP INDEX IF EXISTS tracks_duration_id_idx; -DROP TABLE duplicate_group_members; -DROP TABLE duplicate_groups; -DROP TABLE duplicate_sweeps; diff --git a/internal/db/migrations/0059_duplicate_groups.up.sql b/internal/db/migrations/0059_duplicate_groups.up.sql deleted file mode 100644 index 67073cd6..00000000 --- a/internal/db/migrations/0059_duplicate_groups.up.sql +++ /dev/null @@ -1,54 +0,0 @@ --- 0059_duplicate_groups.up.sql — proposed duplicates and the sweeps that find --- them. --- --- The sweep compares fingerprints (track_fingerprints, 0058) and proposes --- groups of tracks that hold one recording. Nothing here merges anything: a --- group is a proposal an admin reviews, and the merge is a separate act. - --- One row per sweep. Lets the report tell "the sweep has never run" apart from --- "it ran and found nothing", and gives the in-flight guard something to check, --- the same way scan_runs does for the library scan. -CREATE TABLE duplicate_sweeps ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - started_at timestamptz NOT NULL DEFAULT now(), - finished_at timestamptz, - candidates integer, - groups_found integer, - oversize_clusters integer, - error_message text -); -CREATE INDEX duplicate_sweeps_started_at_idx ON duplicate_sweeps (started_at DESC); - -CREATE TABLE duplicate_groups ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - -- The group's identity: its member track ids, sorted and joined. A sweep - -- that finds the same tracks again updates this row rather than proposing - -- them twice, and a dismissal stays attached to the set it was made about. - member_key text NOT NULL UNIQUE, - -- Rule 36: a new value for either CHECK swaps the constraint in the same - -- migration. - tier text NOT NULL CHECK (tier IN ('exact', 'acoustic')), - -- Largest disagreement between any two members; NULL for exact groups, - -- which have no score. - worst_bit_error_rate real, - status text NOT NULL DEFAULT 'pending' - CHECK (status IN ('pending', 'dismissed', 'merged')), - detected_at timestamptz NOT NULL DEFAULT now(), - last_seen_sweep_id uuid REFERENCES duplicate_sweeps (id) ON DELETE SET NULL, - resolved_at timestamptz -); -CREATE INDEX duplicate_groups_status_idx ON duplicate_groups (status); - -CREATE TABLE duplicate_group_members ( - group_id uuid NOT NULL REFERENCES duplicate_groups (id) ON DELETE CASCADE, - -- CASCADE is right here: a track that genuinely leaves the library has no - -- place in a proposal about its duplicates. - track_id uuid NOT NULL REFERENCES tracks (id) ON DELETE CASCADE, - PRIMARY KEY (group_id, track_id) -); -CREATE INDEX duplicate_group_members_track_idx ON duplicate_group_members (track_id); - --- The sweep streams candidates in (duration_ms, id) order, keyset-paged, so it --- only ever holds a few seconds' worth of durations in memory. Without this --- each page would sort the whole library again. -CREATE INDEX tracks_duration_id_idx ON tracks (duration_ms, id); diff --git a/internal/db/migrations/0060_play_events_track_index.down.sql b/internal/db/migrations/0060_play_events_track_index.down.sql deleted file mode 100644 index af749a3f..00000000 --- a/internal/db/migrations/0060_play_events_track_index.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP INDEX IF EXISTS play_events_track_idx; diff --git a/internal/db/migrations/0060_play_events_track_index.up.sql b/internal/db/migrations/0060_play_events_track_index.up.sql deleted file mode 100644 index 2c19bd36..00000000 --- a/internal/db/migrations/0060_play_events_track_index.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- 0060_play_events_track_index.up.sql — play_events by track. --- --- play_events is indexed by (user_id, started_at) and (user_id, track_id), both --- led by user. Nothing reached it by track alone until the duplicates report, --- which shows each copy's play count — a scan of the whole table per copy — and --- the duplicate merge, which repoints a duplicate's play history onto the copy --- being kept. Both ask "every play of this track", whoever played it. -CREATE INDEX play_events_track_idx ON play_events (track_id); diff --git a/internal/db/migrations/0061_fingerprint_settings.down.sql b/internal/db/migrations/0061_fingerprint_settings.down.sql deleted file mode 100644 index 31d6d9cc..00000000 --- a/internal/db/migrations/0061_fingerprint_settings.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE track_fingerprints DROP COLUMN chromaprint_length_sec; -DROP TABLE fingerprint_settings; diff --git a/internal/db/migrations/0061_fingerprint_settings.up.sql b/internal/db/migrations/0061_fingerprint_settings.up.sql deleted file mode 100644 index 89911d69..00000000 --- a/internal/db/migrations/0061_fingerprint_settings.up.sql +++ /dev/null @@ -1,48 +0,0 @@ --- 0061_fingerprint_settings.up.sql — fingerprinting's knobs, in admin --- Settings: anything an admin might tune is a database row, changed without a --- restart. Singleton in the style of reacquisition_settings (0056). -CREATE TABLE fingerprint_settings ( - id boolean PRIMARY KEY DEFAULT true, - - -- Fingerprinting new files, the backfill, and the duplicate sweep. Off - -- stops the decode work entirely — the reason to turn it off is a slow NAS. - -- On by default: without it the library cannot tell its duplicates apart. - enabled boolean NOT NULL DEFAULT true, - - -- Seconds of audio fpcalc fingerprints. Chromaprints taken at different - -- lengths cannot be compared, which is why track_fingerprints records the - -- length each row was taken at (below): change this and every chromaprint - -- is re-derived, and until then only rows at the new length are compared. - chromaprint_length_sec integer NOT NULL DEFAULT 120, - - -- The most disagreement two aligned fingerprints may show and still be - -- proposed as one recording. Unrelated audio sits near 0.5, so the ceiling - -- stays well clear of it. - acoustic_max_bit_error_rate double precision NOT NULL DEFAULT 0.15, - - -- Files the backfill decodes at once. Decoding competes with playback - -- transcoding for CPU and with streaming for the mount. - backfill_concurrency integer NOT NULL DEFAULT 2, - - -- The least time between duplicate sweeps. A sweep still runs only when - -- fingerprints have changed since the last one. - sweep_interval_hours integer NOT NULL DEFAULT 1, - - -- When the settings were last saved. A new threshold or length can change - -- what a sweep finds, so a save makes a sweep due. - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT fingerprint_settings_singleton CHECK (id = true), - CONSTRAINT fingerprint_settings_length_range - CHECK (chromaprint_length_sec >= 30 AND chromaprint_length_sec <= 600), - CONSTRAINT fingerprint_settings_threshold_range - CHECK (acoustic_max_bit_error_rate >= 0.01 AND acoustic_max_bit_error_rate <= 0.35), - CONSTRAINT fingerprint_settings_concurrency_range - CHECK (backfill_concurrency >= 1 AND backfill_concurrency <= 8), - CONSTRAINT fingerprint_settings_sweep_interval_range - CHECK (sweep_interval_hours >= 1 AND sweep_interval_hours <= 168) -); -INSERT INTO fingerprint_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; - --- Every row written so far was taken at fpcalc's default length. -ALTER TABLE track_fingerprints ADD COLUMN chromaprint_length_sec integer NOT NULL DEFAULT 120; diff --git a/internal/db/migrations/0062_network_public_url.down.sql b/internal/db/migrations/0062_network_public_url.down.sql deleted file mode 100644 index 418a7cd6..00000000 --- a/internal/db/migrations/0062_network_public_url.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE network_settings DROP COLUMN IF EXISTS public_url; diff --git a/internal/db/migrations/0062_network_public_url.up.sql b/internal/db/migrations/0062_network_public_url.up.sql deleted file mode 100644 index 4eb7dee8..00000000 --- a/internal/db/migrations/0062_network_public_url.up.sql +++ /dev/null @@ -1,8 +0,0 @@ --- The address users reach Minstrel at, e.g. https://music.example.com. --- --- Before: password-reset links were built from the request's Host header, --- which the requester controls, so a forgot-password call with a forged Host --- would email the victim a real reset token on a link to the attacker's --- server. After: links are built only from this admin-set value, and none --- are sent while it is empty. -ALTER TABLE network_settings ADD COLUMN public_url text NOT NULL DEFAULT ''; diff --git a/internal/db/migrations/0063_api_token_hash.down.sql b/internal/db/migrations/0063_api_token_hash.down.sql deleted file mode 100644 index 8b80a9f4..00000000 --- a/internal/db/migrations/0063_api_token_hash.down.sql +++ /dev/null @@ -1,7 +0,0 @@ --- The keys cannot be recovered from their hashes. Rolling back gives every --- user a new random key; Subsonic clients using apiKey need the new one. -ALTER TABLE users ADD COLUMN api_token text; -UPDATE users SET api_token = md5(random()::text || id::text || clock_timestamp()::text); -ALTER TABLE users ALTER COLUMN api_token SET NOT NULL; -ALTER TABLE users ADD CONSTRAINT users_api_token_key UNIQUE (api_token); -ALTER TABLE users DROP COLUMN api_token_hash; diff --git a/internal/db/migrations/0063_api_token_hash.up.sql b/internal/db/migrations/0063_api_token_hash.up.sql deleted file mode 100644 index 646d6b18..00000000 --- a/internal/db/migrations/0063_api_token_hash.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- API keys (the OpenSubsonic apiKey) are stored as their sha256, hex, the --- same way session tokens are. A leaked database row or backup no longer --- hands out working keys. Existing keys are hashed in place, so every --- Subsonic client keeps working; the key itself can no longer be shown --- again, only replaced. -ALTER TABLE users ADD COLUMN api_token_hash text; -UPDATE users SET api_token_hash = encode(sha256(convert_to(api_token, 'UTF8')), 'hex'); -ALTER TABLE users ALTER COLUMN api_token_hash SET NOT NULL; -ALTER TABLE users ADD CONSTRAINT users_api_token_hash_key UNIQUE (api_token_hash); -ALTER TABLE users DROP COLUMN api_token; diff --git a/internal/db/migrations/0064_clear_subsonic_password.down.sql b/internal/db/migrations/0064_clear_subsonic_password.down.sql deleted file mode 100644 index 98a094aa..00000000 --- a/internal/db/migrations/0064_clear_subsonic_password.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- The cleared values are gone and were never meant to be kept; nothing to undo. -SELECT 1; diff --git a/internal/db/migrations/0064_clear_subsonic_password.up.sql b/internal/db/migrations/0064_clear_subsonic_password.up.sql deleted file mode 100644 index bcb885bc..00000000 --- a/internal/db/migrations/0064_clear_subsonic_password.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Before: `minstrel admin reset-password` copied the new login password into --- subsonic_password, so every account recovered through the CLI had its login --- password stored in plain text, and a later password change in Settings left --- that copy behind. After: the CLI does not write this column; a Subsonic --- password is generated separately in Settings and is never the login --- password. Clearing every value here removes the copies already made. --- --- Accounts whose Subsonic client signs in with t/s stop working until the user --- generates a Subsonic password (or switches the client to an API key). -UPDATE users SET subsonic_password = NULL WHERE subsonic_password IS NOT NULL; diff --git a/internal/db/migrations/0065_track_loudness.down.sql b/internal/db/migrations/0065_track_loudness.down.sql deleted file mode 100644 index 0bb9eced..00000000 --- a/internal/db/migrations/0065_track_loudness.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS loudness_settings; -DROP TABLE IF EXISTS track_loudness; diff --git a/internal/db/migrations/0065_track_loudness.up.sql b/internal/db/migrations/0065_track_loudness.up.sql deleted file mode 100644 index 17b46ace..00000000 --- a/internal/db/migrations/0065_track_loudness.up.sql +++ /dev/null @@ -1,65 +0,0 @@ --- 0065_track_loudness.up.sql — measured loudness per track, for loudness --- normalization. --- --- Measured with ffmpeg's EBU R128 filter rather than read from ReplayGain tags: --- tags in the wild are written against four different reference levels, and --- most files have none. internal/library/loudness.go says how it is measured. --- --- A table of its own rather than columns on tracks, for the reason --- track_fingerprints is (0058): tracks is read with SELECT * on the hot path, --- and the block histogram is a few hundred integers only album loudness reads. --- --- What a row means, which the backfill depends on: --- no row never analyzed, or the file changed since --- analysis_version < current measured by an older method; measure again --- analysis_version = current settled until the file changes: --- integrated_lufs NOT NULL measured --- integrated_lufs NULL, unreadable false --- read fine, but no 400 ms block was above --- the -70 LUFS gate: silence, or too short --- unreadable true ffmpeg could not decode the file --- A failure that says nothing about the file (a timeout, a cancelled pass, a --- missing ffmpeg) writes no row, so the backfill tries again. -CREATE TABLE track_loudness ( - track_id uuid PRIMARY KEY REFERENCES tracks (id) ON DELETE CASCADE, - -- Gated integrated loudness (ITU-R BS.1770), mono measured as dual mono. - integrated_lufs real, - -- Highest inter-sample peak, from 4x oversampling, in dB relative to full - -- scale. NULL for digital silence, whose peak is -inf. - true_peak_dbtp real, - -- Loudness range (EBU Tech 3342): how much the loudness moves within the - -- track. Not used for gain; kept because it costs nothing here. - loudness_range_lu real, - -- How many 400 ms gating blocks fell in each 0.1 LU bin. Bin i holds blocks - -- measuring -70.0 + (block_hist_start + i) / 10 LUFS; the array is trimmed - -- to the first and last non-empty bins. Album loudness is the gated - -- loudness of every block on the album, so it is computed from these - -- exactly, with no second decode. - block_hist_start smallint, - block_hist integer[], - unreadable boolean NOT NULL DEFAULT false, - analysis_version smallint NOT NULL, - analyzed_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT track_loudness_hist_pair - CHECK ((block_hist IS NULL) = (block_hist_start IS NULL)) -); - --- Loudness analysis's knobs, in admin Settings. Rule 25: an operator setting is --- a database row, changed without a restart. Singleton in the style of --- fingerprint_settings (0061). -CREATE TABLE loudness_settings ( - id boolean PRIMARY KEY DEFAULT true, - -- Off stops the background analysis. Tracks already measured keep their - -- values, so normalization keeps working for them. - enabled boolean NOT NULL DEFAULT true, - -- Files analyzed at once. Each is a full decode, competing with playback - -- transcoding for CPU and with streaming for the mount. - backfill_concurrency integer NOT NULL DEFAULT 2, - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT loudness_settings_singleton CHECK (id = true), - CONSTRAINT loudness_settings_concurrency_range - CHECK (backfill_concurrency >= 1 AND backfill_concurrency <= 8) -); -INSERT INTO loudness_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0066_album_loudness.down.sql b/internal/db/migrations/0066_album_loudness.down.sql deleted file mode 100644 index 7e0a1306..00000000 --- a/internal/db/migrations/0066_album_loudness.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS album_loudness; diff --git a/internal/db/migrations/0066_album_loudness.up.sql b/internal/db/migrations/0066_album_loudness.up.sql deleted file mode 100644 index 0e04820f..00000000 --- a/internal/db/migrations/0066_album_loudness.up.sql +++ /dev/null @@ -1,30 +0,0 @@ --- 0066_album_loudness.up.sql — album loudness for album-mode normalization. --- --- An album's loudness is the gated loudness of every 400 ms block on the album, --- not an average of its tracks' values: a quiet interlude and a loud single --- should keep their difference when the album plays in order. It is computed --- from the per-track block histograms in track_loudness (0065), summed, so no --- audio is decoded again. --- --- A derived value, recomputed by the loudness worker whenever its inputs --- change. inputs_digest is an md5 over the album's present tracks and the --- measurement each holds; the worker recomputes every album whose stored digest --- no longer matches. That one comparison covers every way membership changes --- (a scan moving a track between albums, a duplicate merge, a delete, a file --- going missing or coming back) without hooking each of them. -CREATE TABLE album_loudness ( - album_id uuid PRIMARY KEY REFERENCES albums (id) ON DELETE CASCADE, - -- NULL until every present track has a settled measurement: an album - -- leveled from half its tracks would jump when the rest arrived. Also NULL - -- for an album with no block above the gate. Clients fall back to track - -- gain while it is NULL. - integrated_lufs real, - -- The loudest true peak of any track on the album, so album gain is held - -- to the headroom of its loudest track. - true_peak_dbtp real, - tracks_total integer NOT NULL, - -- Tracks with a settled measurement (measured, silent or unreadable). - tracks_settled integer NOT NULL, - inputs_digest text NOT NULL, - computed_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0067_user_normalization_prefs.down.sql b/internal/db/migrations/0067_user_normalization_prefs.down.sql deleted file mode 100644 index 650e65d7..00000000 --- a/internal/db/migrations/0067_user_normalization_prefs.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS user_normalization_prefs; diff --git a/internal/db/migrations/0067_user_normalization_prefs.up.sql b/internal/db/migrations/0067_user_normalization_prefs.up.sql deleted file mode 100644 index 4f767df7..00000000 --- a/internal/db/migrations/0067_user_normalization_prefs.up.sql +++ /dev/null @@ -1,22 +0,0 @@ --- Each user's loudness-normalization preference. It is kept on --- the server, not per device, so the web player, the Android app and the --- leveled stream for UPnP/Sonos all apply the same one. --- --- mode: off, auto (album gain while an album plays in order, otherwise --- track gain), track or album. --- target: the loudness tracks are leveled to, in LUFS. --- boost: headroom raises quiet tracks only as far as their true peak --- allows; limiter raises them all the way and limits the peaks. --- --- No row means the defaults, which are the column defaults here and --- library.DefaultNormalizationPrefs in Go (a test holds them equal). -CREATE TABLE user_normalization_prefs ( - user_id uuid PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, - mode text NOT NULL DEFAULT 'auto' - CHECK (mode IN ('off', 'auto', 'track', 'album')), - target_lufs smallint NOT NULL DEFAULT -18 - CHECK (target_lufs IN (-18, -16, -14)), - boost text NOT NULL DEFAULT 'headroom' - CHECK (boost IN ('headroom', 'limiter')), - updated_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0068_leveled_stream_cache.down.sql b/internal/db/migrations/0068_leveled_stream_cache.down.sql deleted file mode 100644 index 59ab4d17..00000000 --- a/internal/db/migrations/0068_leveled_stream_cache.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE loudness_settings - DROP CONSTRAINT loudness_settings_leveled_cache_range, - DROP COLUMN leveled_cache_mb; diff --git a/internal/db/migrations/0068_leveled_stream_cache.up.sql b/internal/db/migrations/0068_leveled_stream_cache.up.sql deleted file mode 100644 index 84293517..00000000 --- a/internal/db/migrations/0068_leveled_stream_cache.up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- 0068_leveled_stream_cache.up.sql — the size cap of the leveled-stream render --- cache. --- --- Sonos and other UPnP renderers fetch a track's URL themselves, so the phone --- cannot level what they play. The server renders a gain-applied FLAC for them --- instead and keeps it on disk, oldest-used first out once the cache is over --- this size. An admin setting, on the loudness settings row it belongs with. -ALTER TABLE loudness_settings - ADD COLUMN leveled_cache_mb integer NOT NULL DEFAULT 2048, - ADD CONSTRAINT loudness_settings_leveled_cache_range - CHECK (leveled_cache_mb >= 256 AND leveled_cache_mb <= 65536); diff --git a/internal/db/migrations/0069_acoustid_lookup.down.sql b/internal/db/migrations/0069_acoustid_lookup.down.sql deleted file mode 100644 index 3dae17cb..00000000 --- a/internal/db/migrations/0069_acoustid_lookup.down.sql +++ /dev/null @@ -1,7 +0,0 @@ -DROP TABLE IF EXISTS acoustid_settings; -DROP TABLE IF EXISTS track_acoustid_lookups; --- Looked-up ids go with the lookups; a tag id stays. -UPDATE tracks SET mbid = NULL WHERE mbid_source = 'acoustid'; -ALTER TABLE tracks DROP CONSTRAINT IF EXISTS tracks_mbid_source_pair; -ALTER TABLE tracks DROP CONSTRAINT IF EXISTS tracks_mbid_source_check; -ALTER TABLE tracks DROP COLUMN IF EXISTS mbid_source; diff --git a/internal/db/migrations/0069_acoustid_lookup.up.sql b/internal/db/migrations/0069_acoustid_lookup.up.sql deleted file mode 100644 index ecd56c99..00000000 --- a/internal/db/migrations/0069_acoustid_lookup.up.sql +++ /dev/null @@ -1,69 +0,0 @@ --- 0069_acoustid_lookup.up.sql — recording MBIDs looked up through AcoustID --- for tracks whose tags carry none. --- --- A track with no recording MBID is invisible to the ListenBrainz similarity --- arm in both directions, so this fills the ids the tags leave empty. - --- Where tracks.mbid came from. The file's own tag always outranks a lookup: --- the scan's upsert keeps a looked-up id while the tag carries --- none, and replaces it the moment the tag carries one. -ALTER TABLE tracks ADD COLUMN mbid_source text; --- Every id stored so far was read from a tag (the scan or the tag backfill), --- or inherited from a merged duplicate's tag. -UPDATE tracks SET mbid_source = 'tag' WHERE mbid IS NOT NULL; -ALTER TABLE tracks - ADD CONSTRAINT tracks_mbid_source_check CHECK (mbid_source IN ('tag', 'acoustid')), - ADD CONSTRAINT tracks_mbid_source_pair CHECK ((mbid IS NULL) = (mbid_source IS NULL)); - --- What happened the last time a track was looked up. A table of its own, as --- track_loudness is (0065): tracks is read with SELECT * on the hot path. --- --- What a row means, which the lookup worker depends on: --- no row never looked up, or the file changed since (the scan deletes --- the row): look it up --- matched one recording cleared the score threshold, or one was left --- after disambiguating by title and length; recording_mbid is it --- ambiguous several recordings cleared it and nothing told them apart. --- Nothing is written: a wrong MBID would feed similarity the --- wrong neighbours, which is worse than none --- no_match AcoustID linked nothing at or above the threshold --- failed fpcalc rejected the file, or AcoustID rejected its print --- Every state is settled until the file changes. A failure that says nothing --- about the file (AcoustID unreachable, a timeout, a cancelled pass) writes no --- row, so the worker tries again. -CREATE TABLE track_acoustid_lookups ( - track_id uuid PRIMARY KEY REFERENCES tracks (id) ON DELETE CASCADE, - state text NOT NULL, - -- The best score any linked recording had; NULL when none was linked. - best_score real, - -- How many distinct recordings were linked, at any score. - candidates integer NOT NULL DEFAULT 0, - recording_mbid text, - -- Why a lookup failed, for the admin list. - detail text, - looked_up_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT track_acoustid_lookups_state_check - CHECK (state IN ('matched', 'ambiguous', 'no_match', 'failed')), - CONSTRAINT track_acoustid_lookups_matched_has_mbid - CHECK ((state = 'matched') = (recording_mbid IS NOT NULL)) -); -CREATE INDEX track_acoustid_lookups_state ON track_acoustid_lookups (state); - --- AcoustID's knobs, in admin Settings. Singleton in the style of --- loudness_settings (0065). -CREATE TABLE acoustid_settings ( - id boolean PRIMARY KEY DEFAULT true, - -- Off by default: AcoustID needs a key an admin registers, and the lookup - -- sends fingerprints to a third party. - enabled boolean NOT NULL DEFAULT false, - api_key text, - -- The score a recording needs before it is considered at all. AcoustID - -- scores a true match close to 1; 0.85 leaves room for a lossy encode. - min_score real NOT NULL DEFAULT 0.85, - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT acoustid_settings_singleton CHECK (id = true), - CONSTRAINT acoustid_settings_min_score_range CHECK (min_score >= 0.5 AND min_score <= 1) -); -INSERT INTO acoustid_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0070_album_release_group_mbid.down.sql b/internal/db/migrations/0070_album_release_group_mbid.down.sql deleted file mode 100644 index 1deb2957..00000000 --- a/internal/db/migrations/0070_album_release_group_mbid.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP INDEX IF EXISTS albums_release_group_mbid_idx; -ALTER TABLE albums DROP COLUMN IF EXISTS release_group_mbid; diff --git a/internal/db/migrations/0070_album_release_group_mbid.up.sql b/internal/db/migrations/0070_album_release_group_mbid.up.sql deleted file mode 100644 index e6068030..00000000 --- a/internal/db/migrations/0070_album_release_group_mbid.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- MusicBrainz release-group id for an album. albums.mbid holds the --- *release* id (Picard's musicbrainz_albumid: one edition), but Lidarr names --- albums by release group, so re-acquisition and request completion need --- this one. Not unique: several releases of one group can each be an album --- row. Filled by the scanner from musicbrainz_releasegroupid, or by the --- re-acquisition sweeper resolving the release through MusicBrainz. -ALTER TABLE albums ADD COLUMN release_group_mbid text; - -CREATE INDEX albums_release_group_mbid_idx ON albums (release_group_mbid) - WHERE release_group_mbid IS NOT NULL; diff --git a/internal/db/migrations/0071_reopen_false_reacquisition_completions.down.sql b/internal/db/migrations/0071_reopen_false_reacquisition_completions.down.sql deleted file mode 100644 index 03bb6852..00000000 --- a/internal/db/migrations/0071_reopen_false_reacquisition_completions.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- The reopened requests were never complete; the reconciler completes them --- again once their albums come back. Nothing to undo. -SELECT 1; diff --git a/internal/db/migrations/0071_reopen_false_reacquisition_completions.up.sql b/internal/db/migrations/0071_reopen_false_reacquisition_completions.up.sql deleted file mode 100644 index e7e18c49..00000000 --- a/internal/db/migrations/0071_reopen_false_reacquisition_completions.up.sql +++ /dev/null @@ -1,30 +0,0 @@ --- Before: the reconciler completed album and track requests as soon as the --- album had any track on disk. Re-acquisition targets albums with only SOME --- tracks missing, so those requests completed the moment Lidarr accepted the --- add, with nothing downloaded. --- --- Reopen every completed album/track request whose matched album does not meet --- the corrected test: a track --- that arrived after the request, or no track that was already missing at the --- request still missing. The reconciler then judges them again; the Lidarr add --- stays confirmed, so nothing is re-sent. Requests that genuinely completed --- meet the test and are left alone. -UPDATE lidarr_requests lr - SET status = 'approved', - completed_at = NULL, - matched_album_id = NULL, - matched_track_id = NULL, - updated_at = now() - WHERE lr.status = 'completed' - AND lr.kind IN ('album', 'track') - AND lr.matched_album_id IS NOT NULL - AND NOT EXISTS ( - SELECT 1 FROM tracks t - WHERE t.album_id = lr.matched_album_id - AND t.missing_since IS NULL - AND t.added_at > lr.requested_at) - AND EXISTS ( - SELECT 1 FROM tracks t - WHERE t.album_id = lr.matched_album_id - AND t.missing_since IS NOT NULL - AND t.missing_since < lr.requested_at); diff --git a/internal/db/migrations/0072_similarity_cache.down.sql b/internal/db/migrations/0072_similarity_cache.down.sql deleted file mode 100644 index fb3b01a0..00000000 --- a/internal/db/migrations/0072_similarity_cache.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP TABLE IF EXISTS artist_similarity_fetches; -DROP TABLE IF EXISTS track_similarity_fetches; -DROP TABLE IF EXISTS listenbrainz_similar_recordings; diff --git a/internal/db/migrations/0072_similarity_cache.up.sql b/internal/db/migrations/0072_similarity_cache.up.sql deleted file mode 100644 index f11866f0..00000000 --- a/internal/db/migrations/0072_similarity_cache.up.sql +++ /dev/null @@ -1,43 +0,0 @@ --- Keep ListenBrainz's whole similar-recordings answer, and record every --- fetch, so the library match is made locally and can be made again. --- --- Before: the worker kept only the recordings already in the library (at most --- 20 of LB's 50) and threw the rest away. Two things followed: --- --- * A recording that reached the library later — a Lidarr import, or an MBID --- filled in by the AcoustID lookup — was not linked until its seed was --- fetched again. --- * A seed with no in-library match wrote nothing at all, and freshness was --- read from track_similarity, so that seed was never fresh. With the queue --- ordered by id, such seeds held its head and were re-asked every hour --- while the rest waited. --- --- The listenbrainz rows in track_similarity are now derived from this cache by --- ResolveListenBrainzTrackEdges. - -CREATE TABLE listenbrainz_similar_recordings ( - seed_track_id uuid NOT NULL REFERENCES tracks(id) ON DELETE CASCADE, - recording_mbid text NOT NULL, - score DOUBLE PRECISION NOT NULL, - PRIMARY KEY (seed_track_id, recording_mbid) -); - --- The resolve joins the cache to tracks by recording MBID. -CREATE INDEX listenbrainz_similar_recordings_mbid_idx - ON listenbrainz_similar_recordings (recording_mbid); - --- One row per seed that ListenBrainz has answered for, an empty answer --- included. The worker's queue reads this, not the edges. -CREATE TABLE track_similarity_fetches ( - track_id uuid PRIMARY KEY REFERENCES tracks(id) ON DELETE CASCADE, - fetched_at timestamptz NOT NULL DEFAULT now(), - returned integer NOT NULL -); - --- The same for artists. Their answer is already kept, in artist_similarity and --- artist_similarity_unmatched; this only stops an empty answer being re-asked. -CREATE TABLE artist_similarity_fetches ( - artist_id uuid PRIMARY KEY REFERENCES artists(id) ON DELETE CASCADE, - fetched_at timestamptz NOT NULL DEFAULT now(), - returned integer NOT NULL -); diff --git a/internal/db/migrations/0073_user_notifications.down.sql b/internal/db/migrations/0073_user_notifications.down.sql deleted file mode 100644 index df94a29d..00000000 --- a/internal/db/migrations/0073_user_notifications.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS user_notification_prefs; -DROP TABLE IF EXISTS user_notifications; diff --git a/internal/db/migrations/0073_user_notifications.up.sql b/internal/db/migrations/0073_user_notifications.up.sql deleted file mode 100644 index ea6fdf9e..00000000 --- a/internal/db/migrations/0073_user_notifications.up.sql +++ /dev/null @@ -1,74 +0,0 @@ --- A persistent, per-user notifications inbox. --- --- The event bus is fire-and-forget: a client that is not connected when a --- request completes, or when the scanner marks tracks missing, never hears of --- it. A row here is the durable record; the bus only nudges open clients to --- come and read it. --- --- `kind` is CHECK-gated. A new kind adds its value here, in the --- same migration as the code that produces it. The list is mirrored in --- internal/notifications/kinds.go, and both CHECKs below must agree with it. - -CREATE TABLE user_notifications ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - kind text NOT NULL CHECK (kind IN ( - 'request_approved', - 'request_rejected', - 'request_completed', - 'request_pending', - 'quarantine_flagged', - 'scan_failed', - 'tracks_missing', - 'duplicates_found', - 'playback_errors' - )), - payload jsonb NOT NULL DEFAULT '{}'::jsonb, - created_at timestamptz NOT NULL DEFAULT now(), - read_at timestamptz, - -- Burst-prone kinds share one key per user. While a row with that key is - -- unread, a new event updates it in place rather than adding another, so - -- fourteen missing tracks are one notification with a count. - coalesce_key text, - -- Stamped once the row has gone out in an email (or been judged not to - -- need one), so the digest never sends the same item twice. - emailed_at timestamptz -); - --- The inbox list, newest first. -CREATE INDEX user_notifications_user_created_idx - ON user_notifications (user_id, created_at DESC); - --- The unread badge, and the digest's selection of unread rows. -CREATE INDEX user_notifications_unread_idx - ON user_notifications (user_id, created_at DESC) - WHERE read_at IS NULL; - --- At most one unread row per coalesce key per user. The upsert in --- notifications.sql targets this index. -CREATE UNIQUE INDEX user_notifications_coalesce_idx - ON user_notifications (user_id, coalesce_key) - WHERE read_at IS NULL AND coalesce_key IS NOT NULL; - --- Per user, per kind: which channels a kind reaches. A missing row means the --- kind's defaults (internal/notifications/kinds.go), so nothing is seeded and --- a new kind needs no backfill. -CREATE TABLE user_notification_prefs ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - kind text NOT NULL CHECK (kind IN ( - 'request_approved', - 'request_rejected', - 'request_completed', - 'request_pending', - 'quarantine_flagged', - 'scan_failed', - 'tracks_missing', - 'duplicates_found', - 'playback_errors' - )), - inbox boolean NOT NULL, - phone boolean NOT NULL, - email boolean NOT NULL, - updated_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (user_id, kind) -); diff --git a/internal/db/migrations/0074_notification_email.down.sql b/internal/db/migrations/0074_notification_email.down.sql deleted file mode 100644 index e8c2d908..00000000 --- a/internal/db/migrations/0074_notification_email.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS user_notifications_email_pending_idx; -DROP TABLE IF EXISTS user_notification_email_state; -DROP TABLE IF EXISTS notification_email_settings; diff --git a/internal/db/migrations/0074_notification_email.up.sql b/internal/db/migrations/0074_notification_email.up.sql deleted file mode 100644 index 917fd02a..00000000 --- a/internal/db/migrations/0074_notification_email.up.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Notifications by email, grouped. Nothing is emailed per event. --- --- New music (request_completed) goes out as at most one summary a day, at a set --- hour in each user's own timezone. Everything else is batched: a batch opens --- at the first un-emailed item and one email goes out a window later, holding --- whatever accumulated. internal/notifications/digest.go is the one sender. - --- The two knobs, in admin Settings. Singleton in the style of --- fingerprint_settings (0061). -CREATE TABLE notification_email_settings ( - id boolean PRIMARY KEY DEFAULT true, - -- The local hour (0-23, in each user's timezone) the daily new-music - -- summary goes out. - summary_hour integer NOT NULL DEFAULT 9, - -- How long a batch stays open after its first item before it is sent. - batch_window_minutes integer NOT NULL DEFAULT 60, - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT notification_email_settings_singleton CHECK (id = true), - CONSTRAINT notification_email_settings_hour_range - CHECK (summary_hour >= 0 AND summary_hour <= 23), - CONSTRAINT notification_email_settings_window_range - CHECK (batch_window_minutes >= 15 AND batch_window_minutes <= 1440) -); -INSERT INTO notification_email_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; - --- Per user, per email group: where the digest stands. A missing row is a user --- who has never had a batch open or a summary sent. -CREATE TABLE user_notification_email_state ( - user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, - email_group text NOT NULL CHECK (email_group IN ('batch', 'summary')), - -- When the open batch started. Held here rather than read off the items, - -- because a coalesced item moves its created_at forward on every update - -- and would otherwise keep a batch from ever coming due. - batch_opened_at timestamptz, - -- The last email of this group the mailer accepted. A summary is due once - -- per local day, after the summary hour, if this is before it. - last_sent_at timestamptz, - -- A failed send backs off: nothing is tried for this group before - -- retry_after, and the gap doubles with each failure in a row. - failures integer NOT NULL DEFAULT 0, - retry_after timestamptz, - PRIMARY KEY (user_id, email_group) -); - --- The digest's selection: unread rows not yet emailed. -CREATE INDEX user_notifications_email_pending_idx - ON user_notifications (user_id, created_at) - WHERE read_at IS NULL AND emailed_at IS NULL; - --- Rows written before this migration were never judged for email. Treat them --- as already handled, so the first digest after the upgrade doesn't send a --- backlog nobody asked for. -UPDATE user_notifications SET emailed_at = now() WHERE emailed_at IS NULL; diff --git a/internal/db/migrations/0075_duplicate_resolve.down.sql b/internal/db/migrations/0075_duplicate_resolve.down.sql deleted file mode 100644 index 60372195..00000000 --- a/internal/db/migrations/0075_duplicate_resolve.down.sql +++ /dev/null @@ -1,17 +0,0 @@ -DELETE FROM user_notifications WHERE kind = 'duplicates_resolved'; -DELETE FROM user_notification_prefs WHERE kind = 'duplicates_resolved'; -ALTER TABLE user_notification_prefs DROP CONSTRAINT user_notification_prefs_kind_check; -ALTER TABLE user_notification_prefs ADD CONSTRAINT user_notification_prefs_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'playback_errors')); -ALTER TABLE user_notifications DROP CONSTRAINT user_notifications_kind_check; -ALTER TABLE user_notifications ADD CONSTRAINT user_notifications_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'playback_errors')); -ALTER TABLE fingerprint_settings DROP COLUMN IF EXISTS auto_resolve; -ALTER TABLE duplicate_group_members DROP COLUMN IF EXISTS lidarr_state; -ALTER TABLE duplicate_groups DROP COLUMN IF EXISTS resolved_automatically; -ALTER TABLE duplicate_groups DROP COLUMN IF EXISTS resolve_note; -ALTER TABLE duplicate_groups DROP COLUMN IF EXISTS class; diff --git a/internal/db/migrations/0075_duplicate_resolve.up.sql b/internal/db/migrations/0075_duplicate_resolve.up.sql deleted file mode 100644 index 95b958da..00000000 --- a/internal/db/migrations/0075_duplicate_resolve.up.sql +++ /dev/null @@ -1,56 +0,0 @@ --- 0075_duplicate_resolve.up.sql — duplicates resolve themselves. --- --- Before: the sweep (0059) proposed groups and every proposal waited for an --- admin. After: the resolver classifies each pending group and acts on the --- classes that are safe. What makes deletion safe is Lidarr's view of the file: --- Lidarr maps one file to each track of the release it monitors, so deleting a --- mapped file opens a hole it fills by downloading again. Only a copy Lidarr --- does not map may go. - --- What kind of duplicate a group is. NULL until the resolver has classified it. --- same_release every copy is on one album --- cross_release the same song on different releases (a single and its album) --- mismatch identical audio under different titles on different albums: --- a file imported as the wrong song --- review anything else: an admin decides --- A new value swaps this constraint in the same migration. -ALTER TABLE duplicate_groups ADD COLUMN class text; -ALTER TABLE duplicate_groups ADD CONSTRAINT duplicate_groups_class_check - CHECK (class IN ('same_release', 'cross_release', 'mismatch', 'review')); - --- Why the resolver left a group for an admin, in words the report shows --- ("Lidarr tracks every copy as its own track"). NULL when it had nothing to --- say. -ALTER TABLE duplicate_groups ADD COLUMN resolve_note text; - --- True when the resolver merged the group itself, so the report can tell its --- merges from an admin's. -ALTER TABLE duplicate_groups ADD COLUMN resolved_automatically boolean NOT NULL DEFAULT false; - --- Lidarr's view of each copy, as of the resolver's last pass: --- tracked Lidarr holds the file and it is not among its unmapped files --- unmapped Lidarr holds the file but maps it to no track: removing it opens --- no hole --- NULL when Lidarr was not consulted (disabled, or unreachable that pass). -ALTER TABLE duplicate_group_members ADD COLUMN lidarr_state text; -ALTER TABLE duplicate_group_members ADD CONSTRAINT duplicate_group_members_lidarr_state_check - CHECK (lidarr_state IN ('tracked', 'unmapped')); - --- An admin can turn the resolver off. On by default: duplicates are meant to --- resolve themselves. -ALTER TABLE fingerprint_settings ADD COLUMN auto_resolve boolean NOT NULL DEFAULT true; - --- The resolver tells admins what it did (the kind CHECKs of 0073 are swapped --- to carry the new value). Postgres named both from their columns. -ALTER TABLE user_notifications DROP CONSTRAINT user_notifications_kind_check; -ALTER TABLE user_notifications ADD CONSTRAINT user_notifications_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'duplicates_resolved', - 'playback_errors')); -ALTER TABLE user_notification_prefs DROP CONSTRAINT user_notification_prefs_kind_check; -ALTER TABLE user_notification_prefs ADD CONSTRAINT user_notification_prefs_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'duplicates_resolved', - 'playback_errors')); diff --git a/internal/db/migrations/0076_track_song_link.down.sql b/internal/db/migrations/0076_track_song_link.down.sql deleted file mode 100644 index f81c06f2..00000000 --- a/internal/db/migrations/0076_track_song_link.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS tracks_song_key_idx; -ALTER TABLE tracks DROP COLUMN IF EXISTS song_key; -ALTER TABLE tracks DROP COLUMN IF EXISTS song_id; diff --git a/internal/db/migrations/0076_track_song_link.up.sql b/internal/db/migrations/0076_track_song_link.up.sql deleted file mode 100644 index 94789e09..00000000 --- a/internal/db/migrations/0076_track_song_link.up.sql +++ /dev/null @@ -1,15 +0,0 @@ --- 0076_track_song_link.up.sql — the same song on several releases counts as --- one song. --- --- A single and the album it came from each hold the song, and Lidarr keeps --- both: each fulfils its own release. Minstrel keeps both files and links --- them, so a like on one is a like on the song, and a mix or radio picks the --- song once rather than once per release. --- --- song_id is set only on a linked track, to the song_key the link chose. --- song_key is what everything reads: the track's own id until it is linked. --- No foreign key: the track whose id names a song may itself be merged away --- later, and the key still groups the copies left. -ALTER TABLE tracks ADD COLUMN song_id uuid; -ALTER TABLE tracks ADD COLUMN song_key uuid GENERATED ALWAYS AS (COALESCE(song_id, id)) STORED; -CREATE INDEX tracks_song_key_idx ON tracks (song_key); diff --git a/internal/db/migrations/0077_track_source_verdict.down.sql b/internal/db/migrations/0077_track_source_verdict.down.sql deleted file mode 100644 index 17b626c6..00000000 --- a/internal/db/migrations/0077_track_source_verdict.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -DROP INDEX IF EXISTS tracks_source_suspect_idx; -ALTER TABLE tracks DROP COLUMN IF EXISTS source_verdict_at; -ALTER TABLE tracks DROP COLUMN IF EXISTS source_verdict; diff --git a/internal/db/migrations/0077_track_source_verdict.up.sql b/internal/db/migrations/0077_track_source_verdict.up.sql deleted file mode 100644 index 529b5d3e..00000000 --- a/internal/db/migrations/0077_track_source_verdict.up.sql +++ /dev/null @@ -1,14 +0,0 @@ --- 0077_track_source_verdict.up.sql — video rips are held back from mixes and --- radio until an admin says otherwise. --- --- A file whose name carries a video-rip marker ("(Official Video)", "[HD]") --- holds the audio of an upload, which can carry intros, skits or a --- different take. The duplicate resolver sets 'suspect' on such a present --- track each pass, and clears it when the name no longer matches. 'suspect' --- keeps the track out of radio and the system mixes; it still plays when --- chosen. 'fine' is an admin's "this one is fine" and is never --- overwritten by the resolver. -ALTER TABLE tracks ADD COLUMN source_verdict text - CONSTRAINT tracks_source_verdict_check CHECK (source_verdict IN ('suspect', 'fine')); -ALTER TABLE tracks ADD COLUMN source_verdict_at timestamptz; -CREATE INDEX tracks_source_suspect_idx ON tracks (id) WHERE source_verdict = 'suspect'; diff --git a/internal/db/migrations/0078_drop_duplicate_lidarr_state.down.sql b/internal/db/migrations/0078_drop_duplicate_lidarr_state.down.sql deleted file mode 100644 index b325605d..00000000 --- a/internal/db/migrations/0078_drop_duplicate_lidarr_state.down.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE duplicate_group_members ADD COLUMN lidarr_state text; -ALTER TABLE duplicate_group_members ADD CONSTRAINT duplicate_group_members_lidarr_state_check - CHECK (lidarr_state IN ('tracked', 'unmapped')); diff --git a/internal/db/migrations/0078_drop_duplicate_lidarr_state.up.sql b/internal/db/migrations/0078_drop_duplicate_lidarr_state.up.sql deleted file mode 100644 index 943423a1..00000000 --- a/internal/db/migrations/0078_drop_duplicate_lidarr_state.up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- 0078_drop_duplicate_lidarr_state.up.sql — the duplicate resolver works --- without Lidarr. --- --- 0075 recorded Lidarr's view of each duplicate copy (tracked or unmapped) --- because a copy Lidarr mapped could not be removed without Lidarr downloading --- it again. Lidarr is gone: Minstrel is the only program writing the library, --- so no copy is anyone else's to keep, and the column has nothing to say. -ALTER TABLE duplicate_group_members DROP CONSTRAINT IF EXISTS duplicate_group_members_lidarr_state_check; -ALTER TABLE duplicate_group_members DROP COLUMN IF EXISTS lidarr_state; diff --git a/internal/db/migrations/0079_acquisition_services.down.sql b/internal/db/migrations/0079_acquisition_services.down.sql deleted file mode 100644 index 49d5d65c..00000000 --- a/internal/db/migrations/0079_acquisition_services.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS acquisition_services; diff --git a/internal/db/migrations/0079_acquisition_services.up.sql b/internal/db/migrations/0079_acquisition_services.up.sql deleted file mode 100644 index b4487dac..00000000 --- a/internal/db/migrations/0079_acquisition_services.up.sql +++ /dev/null @@ -1,61 +0,0 @@ --- 0079_acquisition_services.up.sql — the indexers and download clients the --- admin adds in Admin → Integrations. --- --- Minstrel replaces Lidarr, so it searches and downloads itself. Nothing is --- seeded and nothing is copied from Lidarr: a connection is a row an admin --- adds, from a list of what Minstrel can speak: --- --- kind which list the row appears in: search (Indexers) or download --- (Download clients). --- protocol which client is built: prowlarr (its native /api/v1/search, --- because Prowlarr has no aggregate Torznab feed), torznab (any --- single feed), qbittorrent (the WebUI v2), exchange. --- --- FabledExchange is ONE row under Download clients with a switch per job: --- downloading, searching its DHT index, and describing a torrent's files and --- swarm before a grab. The serves_* switches mean something on an exchange --- row only; every other row does the one job its kind names. --- --- Secrets (api_key, password) are write-only: no query the API answers with --- returns them, only whether one is set. -CREATE TABLE acquisition_services ( - -- code is the stable identity: the protocol for the first of its kind, - -- then protocol-2, protocol-3. Legible in a log, never typed. - code text PRIMARY KEY, - kind text NOT NULL - CONSTRAINT acquisition_services_kind_check CHECK (kind IN ('search', 'download')), - protocol text NOT NULL - CONSTRAINT acquisition_services_protocol_check - CHECK (protocol IN ('prowlarr', 'torznab', 'qbittorrent', 'exchange')), - label text NOT NULL, - -- A new row is off: it has no address yet. - enabled boolean NOT NULL DEFAULT false, - -- The address as an admin's browser opens it. For a Torznab feed it - -- is the whole feed URL up to and including /api. - base_url text NOT NULL DEFAULT '', - api_key text NOT NULL DEFAULT '', - -- qBittorrent only. Both may be empty: a WebUI with auth bypassed for - -- local addresses takes neither. - username text NOT NULL DEFAULT '', - password text NOT NULL DEFAULT '', - -- Download clients: everything Minstrel adds is filed under it. - category text NOT NULL DEFAULT '', - timeout_ms integer NOT NULL DEFAULT 30000 - CONSTRAINT acquisition_services_timeout_check CHECK (timeout_ms BETWEEN 1000 AND 300000), - serves_search boolean NOT NULL DEFAULT true, - serves_downloads boolean NOT NULL DEFAULT true, - serves_enrichment boolean NOT NULL DEFAULT true, - -- One downloads folder, two names: where Minstrel has it mounted, and - -- where the client sees it (empty = the same path, nothing translated). - local_path text NOT NULL DEFAULT '/downloads' - CONSTRAINT acquisition_services_local_path_check CHECK (local_path LIKE '/%'), - remote_path text NOT NULL DEFAULT '' - CONSTRAINT acquisition_services_remote_path_check CHECK (remote_path = '' OR remote_path LIKE '/%'), - -- The most searches the schedule sends this source an hour; 0 = unpaced. - -- Prowlarr's indexers answer 429 when asked too often; an Exchange - -- searches its own database and starts unpaced. - searches_per_hour integer NOT NULL DEFAULT 120 - CONSTRAINT acquisition_services_searches_per_hour_check CHECK (searches_per_hour BETWEEN 0 AND 3600), - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0080_release_catalogue.down.sql b/internal/db/migrations/0080_release_catalogue.down.sql deleted file mode 100644 index bb9e6ac3..00000000 --- a/internal/db/migrations/0080_release_catalogue.down.sql +++ /dev/null @@ -1,5 +0,0 @@ -DROP TABLE IF EXISTS mb_release_tracks; -DROP TABLE IF EXISTS mb_releases; -DROP TABLE IF EXISTS mb_artist_release_groups; -DROP TABLE IF EXISTS mb_release_groups; -DROP TABLE IF EXISTS mb_artists; diff --git a/internal/db/migrations/0080_release_catalogue.up.sql b/internal/db/migrations/0080_release_catalogue.up.sql deleted file mode 100644 index 88e3086c..00000000 --- a/internal/db/migrations/0080_release_catalogue.up.sql +++ /dev/null @@ -1,86 +0,0 @@ --- 0080_release_catalogue.up.sql — Minstrel's own copy of what artists have --- released, read from MusicBrainz. --- --- With Lidarr gone, the wanted list, search and import need to know an --- artist's discography and each release's track list. MusicBrainz allows one --- request a second, so what has been read is kept here and refreshed on a --- schedule rather than asked again for every page. --- --- mb_artists artists the catalogue has been asked about. --- mb_release_groups what a person calls an album (Lidarr's albums --- were release groups too), with MusicBrainz's --- primary and secondary types. --- mb_artist_release_groups who is credited on each group: a collaboration --- belongs to every credited artist's discography. --- mb_releases the editions of a group, read when something --- needs a track list. --- mb_release_tracks each release's track list. --- --- Dates stay as MusicBrainz's partial-date text ("1997", "1997-05", --- "1997-05-21"): most early releases have only a year. - -CREATE TABLE mb_artists ( - mbid text PRIMARY KEY, - name text NOT NULL, - sort_name text NOT NULL DEFAULT '', - disambiguation text NOT NULL DEFAULT '', - artist_type text NOT NULL DEFAULT '', - country text NOT NULL DEFAULT '', - -- When the discography was last read in full; NULL means never. - discography_refreshed_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX mb_artists_refresh_idx ON mb_artists (discography_refreshed_at NULLS FIRST); - -CREATE TABLE mb_release_groups ( - mbid text PRIMARY KEY, - title text NOT NULL, - primary_type text NOT NULL DEFAULT '', - secondary_types text[] NOT NULL DEFAULT '{}', - first_release_date text NOT NULL DEFAULT '', - artist_credit text NOT NULL DEFAULT '', - -- When the releases and their track lists were last read; NULL means never. - releases_refreshed_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE TABLE mb_artist_release_groups ( - artist_mbid text NOT NULL REFERENCES mb_artists (mbid) ON DELETE CASCADE, - release_group_mbid text NOT NULL REFERENCES mb_release_groups (mbid) ON DELETE CASCADE, - PRIMARY KEY (artist_mbid, release_group_mbid) -); - -CREATE INDEX mb_artist_release_groups_group_idx ON mb_artist_release_groups (release_group_mbid); - -CREATE TABLE mb_releases ( - mbid text PRIMARY KEY, - release_group_mbid text NOT NULL REFERENCES mb_release_groups (mbid) ON DELETE CASCADE, - title text NOT NULL, - status text NOT NULL DEFAULT '', - release_date text NOT NULL DEFAULT '', - country text NOT NULL DEFAULT '', - disambiguation text NOT NULL DEFAULT '', - formats text NOT NULL DEFAULT '', - track_count integer NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX mb_releases_group_idx ON mb_releases (release_group_mbid); - -CREATE TABLE mb_release_tracks ( - release_mbid text NOT NULL REFERENCES mb_releases (mbid) ON DELETE CASCADE, - medium_position integer NOT NULL, - position integer NOT NULL, - medium_format text NOT NULL DEFAULT '', - number text NOT NULL DEFAULT '', - title text NOT NULL, - length_ms integer NOT NULL DEFAULT 0, - recording_mbid text NOT NULL DEFAULT '', - PRIMARY KEY (release_mbid, medium_position, position) -); - -CREATE INDEX mb_release_tracks_recording_idx ON mb_release_tracks (recording_mbid) - WHERE recording_mbid <> ''; diff --git a/internal/db/migrations/0081_wanted.down.sql b/internal/db/migrations/0081_wanted.down.sql deleted file mode 100644 index 4087ae4d..00000000 --- a/internal/db/migrations/0081_wanted.down.sql +++ /dev/null @@ -1,38 +0,0 @@ -ALTER TABLE reacquisition_settings - ADD COLUMN backoff_base_hours int NOT NULL DEFAULT 6, - ADD COLUMN backoff_max_hours int NOT NULL DEFAULT 168, - ADD COLUMN max_attempts int NOT NULL DEFAULT 3, - ADD COLUMN auto_approve boolean NOT NULL DEFAULT true; - -ALTER INDEX requests_user_id_idx RENAME TO lidarr_requests_user_id_idx; -ALTER INDEX requests_status_idx RENAME TO lidarr_requests_status_idx; -ALTER INDEX requests_artist_mbid_idx RENAME TO lidarr_requests_artist_mbid_idx; -ALTER INDEX requests_album_mbid_idx RENAME TO lidarr_requests_album_mbid_idx; -ALTER TABLE requests ADD COLUMN lidarr_add_confirmed_at timestamptz; -ALTER TABLE requests ADD COLUMN root_folder_path text; -ALTER TABLE requests ADD COLUMN quality_profile_id int; -ALTER TABLE requests RENAME COLUMN track_mbid TO lidarr_track_mbid; -ALTER TABLE requests RENAME COLUMN album_mbid TO lidarr_album_mbid; -ALTER TABLE requests RENAME COLUMN artist_mbid TO lidarr_artist_mbid; -ALTER TYPE request_kind RENAME TO lidarr_request_kind; -ALTER TYPE request_status RENAME TO lidarr_request_status; -ALTER TABLE requests RENAME TO lidarr_requests; - -CREATE TABLE missing_reacquisitions ( - album_id uuid PRIMARY KEY REFERENCES albums (id) ON DELETE CASCADE, - attempts int NOT NULL DEFAULT 0, - last_attempt_at timestamptz, - last_request_id uuid REFERENCES lidarr_requests (id) ON DELETE SET NULL, - gave_up_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT missing_reacquisitions_attempts_nonneg CHECK (attempts >= 0) -); -CREATE INDEX missing_reacquisitions_due_idx - ON missing_reacquisitions (last_attempt_at NULLS FIRST) - WHERE gave_up_at IS NULL; - -DROP TABLE wants; -DROP TABLE follow_seen_groups; -DROP TABLE follows; -DROP TABLE release_type_profiles; diff --git a/internal/db/migrations/0081_wanted.up.sql b/internal/db/migrations/0081_wanted.up.sql deleted file mode 100644 index d358ab3d..00000000 --- a/internal/db/migrations/0081_wanted.up.sql +++ /dev/null @@ -1,165 +0,0 @@ --- 0081_wanted.up.sql — the wanted list. --- --- With Lidarr gone, Minstrel keeps its own record of what it is looking for: --- --- release_type_profiles which kinds of release a follow wants: primary --- types (Album, EP, Single…) and the secondary types --- allowed (Live, Compilation, Remix…). An empty --- secondary list means studio releases only, which --- is how live recordings are left out. --- follows artists whose new releases are wanted, each on a --- profile. --- follow_seen_groups release groups a follow has already judged, so --- each is judged once. --- wants release groups wanted: a request, a followed --- artist's new release, or an album whose files went --- missing. A want is held once the library has a --- full copy (internal/wanted). --- --- lidarr_requests becomes requests with no Lidarr columns: approving a request --- now records a want or a follow instead of sending an add to Lidarr. The --- missing-file sweeper's attempt bookkeeping goes too; retrying belongs to the --- search schedule, which works per want. - -CREATE TABLE release_type_profiles ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - name text NOT NULL UNIQUE, - primary_types text[] NOT NULL, - secondary_types text[] NOT NULL DEFAULT '{}', - is_default boolean NOT NULL DEFAULT false, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now(), - CONSTRAINT release_type_profiles_primary_nonempty CHECK (cardinality(primary_types) > 0) -); - --- At most one default; the service keeps exactly one by moving it. -CREATE UNIQUE INDEX release_type_profiles_one_default - ON release_type_profiles (is_default) WHERE is_default; - --- Lidarr's "Standard" metadata profile, which followed artists used: albums, --- EPs and singles, studio releases only. -INSERT INTO release_type_profiles (name, primary_types, secondary_types, is_default) -VALUES ('Standard', ARRAY['Album', 'EP', 'Single'], '{}', true); - -CREATE TABLE follows ( - artist_mbid text PRIMARY KEY, - artist_name text NOT NULL, - -- RESTRICT: a profile in use cannot be deleted out from under a follow. - profile_id uuid NOT NULL REFERENCES release_type_profiles (id) ON DELETE RESTRICT, - followed_by uuid REFERENCES users (id) ON DELETE SET NULL, - followed_at timestamptz NOT NULL DEFAULT now(), - -- When the first discography read marked everything then listed as seen. - -- NULL until then: a follow wants only what appears after it. - baseline_at timestamptz, - -- Whether the baseline also wants what the artist had already released - -- that the profile passes and the library lacks: an approved artist - -- request, or an admin ticking "also want…". Cleared once applied. - want_existing boolean NOT NULL DEFAULT false, - -- The discography read this follow last applied. - checked_at timestamptz, - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX follows_profile_idx ON follows (profile_id); - -CREATE TABLE follow_seen_groups ( - artist_mbid text NOT NULL REFERENCES follows (artist_mbid) ON DELETE CASCADE, - release_group_mbid text NOT NULL, - seen_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (artist_mbid, release_group_mbid) -); - -CREATE TABLE wants ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - release_group_mbid text NOT NULL UNIQUE, - artist_mbid text NOT NULL, - artist_name text NOT NULL, - title text NOT NULL, - primary_type text NOT NULL DEFAULT '', - first_release_date text NOT NULL DEFAULT '', - reason text NOT NULL - CONSTRAINT wants_reason_check CHECK (reason IN ('request', 'follow', 'missing')), - -- The library album this want is about (a missing want), or the one that - -- answered it. - album_id uuid REFERENCES albums (id) ON DELETE SET NULL, - created_by uuid REFERENCES users (id) ON DELETE SET NULL, - -- When it was last wanted: set again when a held want is reopened, so - -- "arrived since it was wanted" measures from the reopening. - wanted_at timestamptz NOT NULL DEFAULT now(), - fulfilled_at timestamptz, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX wants_open_idx ON wants (wanted_at) WHERE fulfilled_at IS NULL; -CREATE INDEX wants_artist_idx ON wants (artist_mbid); - --- Requests lose Lidarr. -DROP TABLE missing_reacquisitions; - -ALTER TABLE lidarr_requests RENAME TO requests; -ALTER TYPE lidarr_request_status RENAME TO request_status; -ALTER TYPE lidarr_request_kind RENAME TO request_kind; -ALTER TABLE requests RENAME COLUMN lidarr_artist_mbid TO artist_mbid; -ALTER TABLE requests RENAME COLUMN lidarr_album_mbid TO album_mbid; -ALTER TABLE requests RENAME COLUMN lidarr_track_mbid TO track_mbid; -ALTER TABLE requests DROP COLUMN quality_profile_id; -ALTER TABLE requests DROP COLUMN root_folder_path; -ALTER TABLE requests DROP COLUMN lidarr_add_confirmed_at; -ALTER INDEX lidarr_requests_user_id_idx RENAME TO requests_user_id_idx; -ALTER INDEX lidarr_requests_status_idx RENAME TO requests_status_idx; -ALTER INDEX lidarr_requests_artist_mbid_idx RENAME TO requests_artist_mbid_idx; -ALTER INDEX lidarr_requests_album_mbid_idx RENAME TO requests_album_mbid_idx; - --- Older requests may name albums by release id. A want is keyed by --- release group, so repoint every request the library can translate. -UPDATE requests r - SET album_mbid = a.release_group_mbid, - updated_at = now() - FROM albums a - WHERE a.mbid = r.album_mbid - AND a.release_group_mbid IS NOT NULL - AND a.release_group_mbid <> r.album_mbid; - --- Approved album and track requests still waiting become wants, judged by --- the same test as any other (internal/wanted). -INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, created_by, wanted_at) -SELECT DISTINCT ON (r.album_mbid) - r.album_mbid, r.artist_mbid, r.artist_name, COALESCE(r.album_title, ''), 'request', r.user_id, r.requested_at - FROM requests r - WHERE r.status = 'approved' - AND r.kind IN ('album', 'track') - AND r.album_mbid IS NOT NULL - ORDER BY r.album_mbid, r.requested_at -ON CONFLICT (release_group_mbid) DO NOTHING; - --- The library's album artists start out followed on the default profile: the --- artists already in the library are the wanted artists. Various Artists and --- MusicBrainz's bracketed placeholders ([unknown], [anonymous]…) are not --- artists anyone follows. -INSERT INTO follows (artist_mbid, artist_name, profile_id) -SELECT ar.mbid, ar.name, p.id - FROM artists ar - CROSS JOIN (SELECT id FROM release_type_profiles WHERE is_default) p - WHERE ar.mbid IS NOT NULL AND ar.mbid <> '' - AND ar.mbid <> '89ad4ac3-39f7-470e-963a-56509c546377' - AND ar.name NOT LIKE '[%]' - AND EXISTS (SELECT 1 FROM albums al WHERE al.artist_id = ar.id) -ON CONFLICT (artist_mbid) DO NOTHING; - --- An approved artist request was an artist added to Lidarr: it is followed. -INSERT INTO follows (artist_mbid, artist_name, profile_id, followed_by) -SELECT DISTINCT ON (r.artist_mbid) r.artist_mbid, r.artist_name, p.id, r.decided_by - FROM requests r - CROSS JOIN (SELECT id FROM release_type_profiles WHERE is_default) p - WHERE r.status = 'approved' AND r.kind = 'artist' - ORDER BY r.artist_mbid, r.requested_at -ON CONFLICT (artist_mbid) DO NOTHING; - --- The sweeper now only records a want; how often to look again is the --- search schedule's business. -ALTER TABLE reacquisition_settings - DROP COLUMN backoff_base_hours, - DROP COLUMN backoff_max_hours, - DROP COLUMN max_attempts, - DROP COLUMN auto_approve; diff --git a/internal/db/migrations/0082_search_and_grab.down.sql b/internal/db/migrations/0082_search_and_grab.down.sql deleted file mode 100644 index 630d58e6..00000000 --- a/internal/db/migrations/0082_search_and_grab.down.sql +++ /dev/null @@ -1,12 +0,0 @@ -DROP TABLE release_blocks; -DROP TABLE grabs; -DROP TABLE want_candidates; -DROP INDEX wants_search_due_idx; -ALTER TABLE wants - DROP COLUMN searched_at, - DROP COLUMN search_outcome, - DROP COLUMN search_considered, - DROP COLUMN best_release, - DROP COLUMN best_verdict, - DROP COLUMN search_error; -DROP TABLE acquisition_settings; diff --git a/internal/db/migrations/0082_search_and_grab.up.sql b/internal/db/migrations/0082_search_and_grab.up.sql deleted file mode 100644 index 962586a1..00000000 --- a/internal/db/migrations/0082_search_and_grab.up.sql +++ /dev/null @@ -1,101 +0,0 @@ --- 0082_search_and_grab.up.sql — searching for wants and grabbing releases. --- --- acquisition_settings one row: whether the schedule takes the best release --- by itself, how often a want is searched again, which --- quality tiers are taken, and the last pass's report. --- wants (columns) when each want was last searched and what came of it. --- want_candidates every release the last search found for a want, with --- its verdict and the reasons behind it. --- grabs downloads started for wants; at most one live per want. --- release_blocks releases never to take again, by infohash. - -CREATE TABLE acquisition_settings ( - id boolean PRIMARY KEY DEFAULT true CONSTRAINT acquisition_settings_one_row CHECK (id), - auto_grab boolean NOT NULL DEFAULT true, - -- 0 switches the schedule off. - search_interval_hours integer NOT NULL DEFAULT 24 - CONSTRAINT acquisition_settings_interval_check CHECK (search_interval_hours BETWEEN 0 AND 720), - -- As Lidarr's "Any" profile: trash lossy to lossless; unknown off. - allowed_qualities text[] NOT NULL DEFAULT ARRAY['lossless_hires', 'lossless', 'lossy_high', - 'lossy_standard', 'lossy_low', 'lossy_poor', 'lossy_trash'], - last_pass_at timestamptz, - last_pass jsonb NOT NULL DEFAULT '{}', - updated_at timestamptz NOT NULL DEFAULT now() -); - -INSERT INTO acquisition_settings DEFAULT VALUES; - -ALTER TABLE wants - ADD COLUMN searched_at timestamptz, - ADD COLUMN search_outcome text NOT NULL DEFAULT '' - CONSTRAINT wants_search_outcome_check CHECK (search_outcome IN ('', 'grabbed', 'waiting', 'nothing', 'error')), - ADD COLUMN search_considered integer NOT NULL DEFAULT 0, - ADD COLUMN best_release text NOT NULL DEFAULT '', - ADD COLUMN best_verdict text NOT NULL DEFAULT '', - ADD COLUMN search_error text NOT NULL DEFAULT ''; - -CREATE INDEX wants_search_due_idx ON wants (searched_at NULLS FIRST) WHERE fulfilled_at IS NULL; - -CREATE TABLE want_candidates ( - want_id uuid NOT NULL REFERENCES wants (id) ON DELETE CASCADE, - -- The infohash, or the name when the source gave none. - key text NOT NULL, - name text NOT NULL, - info_hash text NOT NULL DEFAULT '', - indexer text NOT NULL DEFAULT '', - source text NOT NULL DEFAULT '', - size_bytes bigint NOT NULL DEFAULT 0, - seeders integer NOT NULL DEFAULT 0, - files_count integer NOT NULL DEFAULT 0, - format text NOT NULL DEFAULT '', - quality text NOT NULL DEFAULT '', - year integer NOT NULL DEFAULT 0, - verdict text NOT NULL - CONSTRAINT want_candidates_verdict_check CHECK (verdict IN ('grab', 'review', 'refused', 'rejected', 'blocked')), - reason text NOT NULL DEFAULT '', - reasons jsonb NOT NULL DEFAULT '[]', - folded_from text[] NOT NULL DEFAULT '{}', - -- Position in the search's order, best first. - rank integer NOT NULL DEFAULT 0, - searched_at timestamptz NOT NULL DEFAULT now(), - PRIMARY KEY (want_id, key) -); - -CREATE INDEX want_candidates_info_hash_idx ON want_candidates (info_hash) WHERE info_hash <> ''; - -CREATE TABLE grabs ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - want_id uuid REFERENCES wants (id) ON DELETE SET NULL, - info_hash text NOT NULL DEFAULT '', - name text NOT NULL, - key text NOT NULL, - indexer text NOT NULL DEFAULT '', - source text NOT NULL DEFAULT '', - -- The acquisition_services row of the download client it went to. - client text NOT NULL, - save_path text NOT NULL, - quality text NOT NULL DEFAULT '', - origin text NOT NULL CONSTRAINT grabs_origin_check CHECK (origin IN ('schedule', 'operator')), - forced boolean NOT NULL DEFAULT false, - grabbed_by uuid REFERENCES users (id) ON DELETE SET NULL, - grabbed_at timestamptz NOT NULL DEFAULT now(), - ended_at timestamptz, - end_reason text NOT NULL DEFAULT '' - CONSTRAINT grabs_end_reason_check CHECK (end_reason IN ('', 'superseded')), - end_detail text NOT NULL DEFAULT '' -); - --- One live grab per want; the service decides which, this is the backstop. -CREATE UNIQUE INDEX grabs_one_live_per_want ON grabs (want_id) WHERE ended_at IS NULL AND want_id IS NOT NULL; -CREATE INDEX grabs_info_hash_idx ON grabs (info_hash) WHERE info_hash <> ''; - -CREATE TABLE release_blocks ( - info_hash text PRIMARY KEY, - name text NOT NULL DEFAULT '', - -- operator: "never this one"; files: its .torrent held the wrong thing. - reason text NOT NULL CONSTRAINT release_blocks_reason_check CHECK (reason IN ('operator', 'files')), - detail text NOT NULL DEFAULT '', - want_id uuid REFERENCES wants (id) ON DELETE SET NULL, - blocked_by uuid REFERENCES users (id) ON DELETE SET NULL, - blocked_at timestamptz NOT NULL DEFAULT now() -); diff --git a/internal/db/migrations/0083_import.down.sql b/internal/db/migrations/0083_import.down.sql deleted file mode 100644 index a7677dcb..00000000 --- a/internal/db/migrations/0083_import.down.sql +++ /dev/null @@ -1,24 +0,0 @@ -ALTER TABLE acquisition_settings DROP COLUMN import_root; - -DELETE FROM release_blocks WHERE reason = 'import'; -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files')); - -DROP INDEX grabs_live_idx; - -UPDATE grabs SET end_reason = 'superseded' WHERE end_reason IN ('imported', 'refused', 'held'); -ALTER TABLE grabs DROP CONSTRAINT grabs_end_reason_check; -ALTER TABLE grabs ADD CONSTRAINT grabs_end_reason_check CHECK (end_reason IN ('', 'superseded')); - -ALTER TABLE grabs - DROP COLUMN progress, - DROP COLUMN import_state, - DROP COLUMN import_reason, - DROP COLUMN import_detail, - DROP COLUMN import_forced, - DROP COLUMN import_attempts, - DROP COLUMN import_updated_at, - DROP COLUMN imported_at, - DROP COLUMN imported_files, - DROP COLUMN destination; diff --git a/internal/db/migrations/0083_import.up.sql b/internal/db/migrations/0083_import.up.sql deleted file mode 100644 index 0cf4d5bb..00000000 --- a/internal/db/migrations/0083_import.up.sql +++ /dev/null @@ -1,37 +0,0 @@ --- Import with verification: a finished download is checked --- against the album it was grabbed for before anything reaches the library. --- --- grabs (columns) how far the download has got, and what the import --- made of it: the verdict, its reason and evidence, --- where the files went. --- grabs.end_reason a grab also ends by being imported, refused, or --- found to be an album already held. --- release_blocks.reason import: the files were not the album. --- acquisition_settings which library folder new music is filed into --- ('' = the first scan path). -ALTER TABLE grabs - ADD COLUMN progress real NOT NULL DEFAULT 0, - ADD COLUMN import_state text NOT NULL DEFAULT '' - CONSTRAINT grabs_import_state_check CHECK (import_state IN - ('', 'downloading', 'waiting', 'importing', 'imported', 'refused', 'review', 'held', 'failed')), - ADD COLUMN import_reason text NOT NULL DEFAULT '', - ADD COLUMN import_detail jsonb NOT NULL DEFAULT '{}', - -- A person said "import anyway" to a download the check held for them. - ADD COLUMN import_forced boolean NOT NULL DEFAULT false, - ADD COLUMN import_attempts integer NOT NULL DEFAULT 0, - ADD COLUMN import_updated_at timestamptz, - ADD COLUMN imported_at timestamptz, - ADD COLUMN imported_files integer NOT NULL DEFAULT 0, - ADD COLUMN destination text NOT NULL DEFAULT ''; - -ALTER TABLE grabs DROP CONSTRAINT grabs_end_reason_check; -ALTER TABLE grabs ADD CONSTRAINT grabs_end_reason_check - CHECK (end_reason IN ('', 'superseded', 'imported', 'refused', 'held')); - -CREATE INDEX grabs_live_idx ON grabs (grabbed_at) WHERE ended_at IS NULL; - -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import')); - -ALTER TABLE acquisition_settings ADD COLUMN import_root text NOT NULL DEFAULT ''; diff --git a/internal/db/migrations/0084_download_lifecycle.down.sql b/internal/db/migrations/0084_download_lifecycle.down.sql deleted file mode 100644 index 9e00a4d5..00000000 --- a/internal/db/migrations/0084_download_lifecycle.down.sql +++ /dev/null @@ -1,23 +0,0 @@ -ALTER TABLE acquisition_settings - DROP COLUMN seed_ratio, - DROP COLUMN seed_days, - DROP COLUMN stall_hours; - -ALTER TABLE release_blocks DROP COLUMN expires_at; -DELETE FROM release_blocks WHERE reason = 'stalled'; -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import')); - -DROP INDEX grabs_seeding_idx; -ALTER TABLE grabs - DROP COLUMN seeding, - DROP COLUMN ratio, - DROP COLUMN seed_released_at; - -UPDATE grabs SET end_reason = 'superseded' WHERE end_reason IN ('stalled', 'failed', 'abandoned', 'gone'); -ALTER TABLE grabs DROP CONSTRAINT grabs_end_reason_check; -ALTER TABLE grabs ADD CONSTRAINT grabs_end_reason_check - CHECK (end_reason IN ('', 'superseded', 'imported', 'refused', 'held')); - -DROP TABLE download_interventions; diff --git a/internal/db/migrations/0084_download_lifecycle.up.sql b/internal/db/migrations/0084_download_lifecycle.up.sql deleted file mode 100644 index eedda40a..00000000 --- a/internal/db/migrations/0084_download_lifecycle.up.sql +++ /dev/null @@ -1,89 +0,0 @@ --- Download lifecycle: a download that stalls or fails is given up and its album --- searched again; an imported download seeds, then is removed. --- --- download_interventions what was seen wrong with a download or a client, --- what Minstrel did about it, and whether it --- cleared. One open row per (client, download, --- condition), updated in place. --- grabs (columns) a grab also ends by being given up (stalled, --- failed), set aside by a person, or leaving the --- client; an imported one records its seeding. --- release_blocks a release given up on is held back for a while, --- not for ever: expires_at. --- acquisition_settings how long to seed, and how long a download may sit --- with nobody sharing it. -CREATE TABLE download_interventions ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - -- The acquisition_services code of the download client. - client text NOT NULL, - -- The torrent, or '' for a condition of the client itself. - info_hash text NOT NULL DEFAULT '', - grab_id uuid REFERENCES grabs (id) ON DELETE SET NULL, - name text NOT NULL DEFAULT '', - -- no_peers nobody is sharing an unfinished download. - -- no_metadata still fetching the torrent's file list. - -- client_error the client gave up on it, in its own words. - -- client_unreachable the client does not answer, or its engine is down. - -- gone the client no longer lists a running download. - -- not_removed given up on, and the client would not remove it. - trigger text NOT NULL CONSTRAINT download_interventions_trigger_check CHECK (trigger IN ( - 'no_peers', 'no_metadata', 'client_error', 'client_unreachable', 'gone', 'not_removed')), - -- escalated seen and shown; nothing done yet. - -- retried asked the trackers again and re-read the files. - -- given_up the download was removed and its album searched again. - -- removed a download left behind was removed. - action text NOT NULL DEFAULT 'escalated' - CONSTRAINT download_interventions_action_check CHECK (action IN ('escalated', 'retried', 'given_up', 'removed')), - outcome text NOT NULL DEFAULT 'open' - CONSTRAINT download_interventions_outcome_check CHECK (outcome IN ('open', 'resolved')), - detail text NOT NULL DEFAULT '', - -- How many passes have seen it, and how many times Minstrel acted on it. - -- The second is the retry ladder's rung, kept here so a restart does not - -- hand a stuck download fresh retries. - observations integer NOT NULL DEFAULT 1, - remediations integer NOT NULL DEFAULT 0, - first_seen timestamptz NOT NULL DEFAULT now(), - last_seen timestamptz NOT NULL DEFAULT now(), - settled_at timestamptz, - CONSTRAINT download_interventions_settled_together CHECK ((outcome = 'open') = (settled_at IS NULL)) -); - --- One open row per condition: a pass that sees it again lands on the same row. -CREATE UNIQUE INDEX download_interventions_one_open - ON download_interventions (client, info_hash, trigger) WHERE outcome = 'open'; -CREATE INDEX download_interventions_grab_idx ON download_interventions (grab_id) WHERE grab_id IS NOT NULL; - -ALTER TABLE grabs DROP CONSTRAINT grabs_end_reason_check; -ALTER TABLE grabs ADD CONSTRAINT grabs_end_reason_check - CHECK (end_reason IN ('', 'superseded', 'imported', 'refused', 'held', 'stalled', 'failed', 'abandoned', 'gone')); - --- An imported download goes on sharing (the files were copied) until its --- ratio reaches the setting or its time is up; seed_released_at is when it --- was removed, or found gone. -ALTER TABLE grabs - ADD COLUMN seeding boolean NOT NULL DEFAULT false, - ADD COLUMN ratio real NOT NULL DEFAULT 0, - ADD COLUMN seed_released_at timestamptz; - -CREATE INDEX grabs_seeding_idx ON grabs (imported_at) WHERE seeding AND seed_released_at IS NULL; - --- stalled: given up on because it would not finish; held back until --- expires_at. NULL is for good. -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import', 'stalled')); -ALTER TABLE release_blocks ADD COLUMN expires_at timestamptz; - --- FL's rulings: seed to ratio 2.0 or for 14 days at most; a download nobody --- has shared for 6 hours is retried, then given up. --- seed_ratio 0 the download is removed once imported. --- seed_days 0 no time limit: only the ratio ends it. --- stall_hours 0 never give up on a download for want of peers (a failed --- one is still given up). -ALTER TABLE acquisition_settings - ADD COLUMN seed_ratio real NOT NULL DEFAULT 2.0 - CONSTRAINT acquisition_settings_seed_ratio_check CHECK (seed_ratio BETWEEN 0 AND 100), - ADD COLUMN seed_days integer NOT NULL DEFAULT 14 - CONSTRAINT acquisition_settings_seed_days_check CHECK (seed_days BETWEEN 0 AND 365), - ADD COLUMN stall_hours integer NOT NULL DEFAULT 6 - CONSTRAINT acquisition_settings_stall_hours_check CHECK (stall_hours BETWEEN 0 AND 720); diff --git a/internal/db/migrations/0085_library_wants.down.sql b/internal/db/migrations/0085_library_wants.down.sql deleted file mode 100644 index 3fe34736..00000000 --- a/internal/db/migrations/0085_library_wants.down.sql +++ /dev/null @@ -1,8 +0,0 @@ -ALTER TABLE acquisition_settings - DROP COLUMN library_listing_started_at, - DROP COLUMN library_listed_at, - DROP COLUMN library_unlisted; - -DELETE FROM wants WHERE reason = 'library'; -ALTER TABLE wants DROP CONSTRAINT wants_reason_check; -ALTER TABLE wants ADD CONSTRAINT wants_reason_check CHECK (reason IN ('request', 'follow', 'missing')); diff --git a/internal/db/migrations/0085_library_wants.up.sql b/internal/db/migrations/0085_library_wants.up.sql deleted file mode 100644 index 9f7b87ce..00000000 --- a/internal/db/migrations/0085_library_wants.up.sql +++ /dev/null @@ -1,23 +0,0 @@ --- The library's albums go on the wanted list as held, once. After that the list --- is the truth: an album taken off it stays off, and one dropped into the --- library folder by hand is not added. Re-acquisition fetches back only albums --- on the list. --- --- wants.reason library: on the list because the library --- held it when the list began. --- acquisition_settings when the one-time listing began (its cutoff: --- albums added later are not listed), when it --- finished, and how many albums it could not --- list because nothing names them to --- MusicBrainz. --- --- The listing itself runs in the wanted worker after boot, not here: it may --- have to ask MusicBrainz for each album's release group. -ALTER TABLE wants DROP CONSTRAINT wants_reason_check; -ALTER TABLE wants ADD CONSTRAINT wants_reason_check - CHECK (reason IN ('request', 'follow', 'missing', 'library')); - -ALTER TABLE acquisition_settings - ADD COLUMN library_listing_started_at timestamptz, - ADD COLUMN library_listed_at timestamptz, - ADD COLUMN library_unlisted integer NOT NULL DEFAULT 0; diff --git a/internal/db/migrations/0086_library_album_matches.down.sql b/internal/db/migrations/0086_library_album_matches.down.sql deleted file mode 100644 index b61ff4fa..00000000 --- a/internal/db/migrations/0086_library_album_matches.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE library_album_matches; diff --git a/internal/db/migrations/0086_library_album_matches.up.sql b/internal/db/migrations/0086_library_album_matches.up.sql deleted file mode 100644 index fd7986da..00000000 --- a/internal/db/migrations/0086_library_album_matches.up.sql +++ /dev/null @@ -1,45 +0,0 @@ --- Every library album is matched to MusicBrainz before it goes on the list, so --- its metadata comes from MusicBrainz. The listing in 0085 took only albums --- whose tags already named their release group and artist; the rest are now --- matched by the release their tags name, the artist's discography, or a --- search, and checked against their own tracks. --- --- library_album_matches one row per album the listing has decided: --- listed (with how it was matched) or unmatched --- (with why). It is the record that the listing --- saw the album, so an album taken off the list --- is never listed again. -CREATE TABLE library_album_matches ( - album_id uuid PRIMARY KEY REFERENCES albums (id) ON DELETE CASCADE, - outcome text NOT NULL - CONSTRAINT library_album_matches_outcome_check CHECK (outcome IN ('listed', 'unmatched')), - -- tags its tags named the release group. - -- release its tags named a release; MusicBrainz named the group. - -- discography its title is one of the artist's release groups. - -- search MusicBrainz's search found it by artist and title. - method text NOT NULL DEFAULT '' - CONSTRAINT library_album_matches_method_check CHECK (method IN ('', 'tags', 'release', 'discography', 'search')), - release_group_mbid text NOT NULL DEFAULT '', - detail text NOT NULL DEFAULT '', - decided_at timestamptz NOT NULL DEFAULT now() -); - -CREATE INDEX library_album_matches_unmatched_idx ON library_album_matches (decided_at) WHERE outcome = 'unmatched'; - --- The albums 0085's listing already took, by its own test, are decided: --- one taken off the list since stays off. -INSERT INTO library_album_matches (album_id, outcome, method, release_group_mbid) -SELECT a.id, 'listed', 'tags', a.release_group_mbid - FROM albums a - JOIN artists ar ON ar.id = a.artist_id - JOIN acquisition_settings s ON s.id = true - WHERE s.library_listing_started_at IS NOT NULL - AND a.created_at <= s.library_listing_started_at - AND a.release_group_mbid IS NOT NULL AND a.release_group_mbid <> '' - AND ar.mbid IS NOT NULL AND ar.mbid <> '' - AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id); - --- The rest are matched by the wanted worker after boot: the listing resumes. -UPDATE acquisition_settings - SET library_listed_at = NULL, library_unlisted = 0 - WHERE library_listing_started_at IS NOT NULL; diff --git a/internal/db/migrations/0087_library_rematch.down.sql b/internal/db/migrations/0087_library_rematch.down.sql deleted file mode 100644 index 66b5e525..00000000 --- a/internal/db/migrations/0087_library_rematch.down.sql +++ /dev/null @@ -1,2 +0,0 @@ --- Nothing to undo: the refused albums are matched again either way. -SELECT 1; diff --git a/internal/db/migrations/0087_library_rematch.up.sql b/internal/db/migrations/0087_library_rematch.up.sql deleted file mode 100644 index cc278ed9..00000000 --- a/internal/db/migrations/0087_library_rematch.up.sql +++ /dev/null @@ -1,9 +0,0 @@ --- The first matching (0086) required every track's length to fit as well --- as its title, and refused singles and near-complete albums the library --- plainly holds. Matching now takes the titles alone under the album's own --- name: the albums it refused are matched again. -DELETE FROM library_album_matches WHERE outcome = 'unmatched'; - -UPDATE acquisition_settings - SET library_listed_at = NULL, library_unlisted = 0 - WHERE library_listing_started_at IS NOT NULL; diff --git a/internal/db/migrations/0088_library_matcher_version.down.sql b/internal/db/migrations/0088_library_matcher_version.down.sql deleted file mode 100644 index 1e22094a..00000000 --- a/internal/db/migrations/0088_library_matcher_version.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE library_album_matches DROP COLUMN matcher; diff --git a/internal/db/migrations/0088_library_matcher_version.up.sql b/internal/db/migrations/0088_library_matcher_version.up.sql deleted file mode 100644 index 568921f5..00000000 --- a/internal/db/migrations/0088_library_matcher_version.up.sql +++ /dev/null @@ -1,4 +0,0 @@ --- Which version of the matching decided an album. A refusal by an --- older matcher is tried again by a newer one, so improving the matching --- reaches the albums it refused without a migration each time. -ALTER TABLE library_album_matches ADD COLUMN matcher integer NOT NULL DEFAULT 0; diff --git a/internal/db/migrations/0089_library_match_by_hand.down.sql b/internal/db/migrations/0089_library_match_by_hand.down.sql deleted file mode 100644 index 678f4eab..00000000 --- a/internal/db/migrations/0089_library_match_by_hand.down.sql +++ /dev/null @@ -1,8 +0,0 @@ -UPDATE library_album_matches SET outcome = 'unmatched' WHERE outcome = 'dismissed'; -UPDATE library_album_matches SET method = 'search' WHERE method = 'manual'; -ALTER TABLE library_album_matches DROP CONSTRAINT library_album_matches_outcome_check; -ALTER TABLE library_album_matches ADD CONSTRAINT library_album_matches_outcome_check - CHECK (outcome IN ('listed', 'unmatched')); -ALTER TABLE library_album_matches DROP CONSTRAINT library_album_matches_method_check; -ALTER TABLE library_album_matches ADD CONSTRAINT library_album_matches_method_check - CHECK (method IN ('', 'tags', 'release', 'discography', 'search')); diff --git a/internal/db/migrations/0089_library_match_by_hand.up.sql b/internal/db/migrations/0089_library_match_by_hand.up.sql deleted file mode 100644 index 8d8e47ca..00000000 --- a/internal/db/migrations/0089_library_match_by_hand.up.sql +++ /dev/null @@ -1,10 +0,0 @@ --- The Collection's Unmatched section: a person matches an album the --- listing could not, by a MusicBrainz link or a search (method 'manual'), --- or leaves it off the list for good (outcome 'dismissed': a local band's --- album MusicBrainz will never have, a mix that is no album). -ALTER TABLE library_album_matches DROP CONSTRAINT library_album_matches_outcome_check; -ALTER TABLE library_album_matches ADD CONSTRAINT library_album_matches_outcome_check - CHECK (outcome IN ('listed', 'unmatched', 'dismissed')); -ALTER TABLE library_album_matches DROP CONSTRAINT library_album_matches_method_check; -ALTER TABLE library_album_matches ADD CONSTRAINT library_album_matches_method_check - CHECK (method IN ('', 'tags', 'release', 'discography', 'search', 'manual')); diff --git a/internal/db/migrations/0090_upgrades.down.sql b/internal/db/migrations/0090_upgrades.down.sql deleted file mode 100644 index 8986bbc1..00000000 --- a/internal/db/migrations/0090_upgrades.down.sql +++ /dev/null @@ -1,7 +0,0 @@ -DROP INDEX IF EXISTS wants_upgrade_idx; -ALTER TABLE wants - DROP COLUMN upgrade_checked_at, - DROP COLUMN held_quality, - DROP COLUMN held_tier, - DROP COLUMN upgrade; -ALTER TABLE acquisition_settings DROP COLUMN upgrade_until; diff --git a/internal/db/migrations/0090_upgrades.up.sql b/internal/db/migrations/0090_upgrades.up.sql deleted file mode 100644 index c64734d4..00000000 --- a/internal/db/migrations/0090_upgrades.up.sql +++ /dev/null @@ -1,29 +0,0 @@ --- Upgrades: a held album whose copy is below the quality an admin settles --- for, or that holds a video rip, stays wanted for a better --- copy. The import replaces the old tracks with the new ones. --- --- acquisition_settings.upgrade_until the tier a held album is upgraded to; --- '' switches quality upgrades off. --- Lidarr's "Any" profile upgraded up to --- High Quality Lossy. --- wants.upgrade why a held album is wanted again: --- quality (below upgrade_until) or rip --- (a track is a video rip); '' not. --- wants.held_tier, held_quality the library copy's tier, estimated --- from format and size per second, and --- the same in words. --- wants.upgrade_checked_at when the wanted worker last judged it. --- want_candidates.verdict unchanged: a release no better than --- the copy held is "refused". -ALTER TABLE acquisition_settings - ADD COLUMN upgrade_until text NOT NULL DEFAULT 'lossy_high'; - -ALTER TABLE wants - ADD COLUMN upgrade text NOT NULL DEFAULT '' - CONSTRAINT wants_upgrade_check CHECK (upgrade IN ('', 'quality', 'rip')), - ADD COLUMN held_tier text NOT NULL DEFAULT '', - ADD COLUMN held_quality text NOT NULL DEFAULT '', - ADD COLUMN upgrade_checked_at timestamptz; - -CREATE INDEX wants_upgrade_idx ON wants (searched_at NULLS FIRST) - WHERE fulfilled_at IS NOT NULL AND upgrade <> ''; diff --git a/internal/db/migrations/0091_remove_lidarr.down.sql b/internal/db/migrations/0091_remove_lidarr.down.sql deleted file mode 100644 index dceb707f..00000000 --- a/internal/db/migrations/0091_remove_lidarr.down.sql +++ /dev/null @@ -1,29 +0,0 @@ -ALTER TABLE quarantine_actions RENAME CONSTRAINT quarantine_actions_admin_id_fkey TO lidarr_quarantine_actions_admin_id_fkey; -ALTER TABLE quarantine RENAME CONSTRAINT quarantine_track_id_fkey TO lidarr_quarantine_track_id_fkey; -ALTER TABLE quarantine RENAME CONSTRAINT quarantine_user_id_fkey TO lidarr_quarantine_user_id_fkey; - -ALTER INDEX quarantine_actions_created_idx RENAME TO lidarr_quarantine_actions_created_idx; -ALTER INDEX quarantine_actions_track_idx RENAME TO lidarr_quarantine_actions_track_idx; -ALTER INDEX quarantine_actions_pkey RENAME TO lidarr_quarantine_actions_pkey; -ALTER TABLE quarantine_actions RENAME COLUMN album_mbid TO lidarr_album_mbid; -ALTER TYPE quarantine_action_kind RENAME VALUE 'deleted_album' TO 'deleted_via_lidarr'; -ALTER TYPE quarantine_action_kind RENAME TO lidarr_quarantine_action_kind; -ALTER TABLE quarantine_actions RENAME TO lidarr_quarantine_actions; - -ALTER INDEX quarantine_pkey RENAME TO lidarr_quarantine_pkey; -ALTER INDEX quarantine_track_idx RENAME TO lidarr_quarantine_track_idx; -ALTER TYPE quarantine_reason RENAME TO lidarr_quarantine_reason; -ALTER TABLE quarantine RENAME TO lidarr_quarantine; - -CREATE TABLE lidarr_config ( - id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), - enabled boolean NOT NULL DEFAULT false, - base_url text, - api_key text, - default_quality_profile_id int, - default_root_folder_path text, - default_metadata_profile_id integer, - created_at timestamptz NOT NULL DEFAULT now(), - updated_at timestamptz NOT NULL DEFAULT now() -); -INSERT INTO lidarr_config (id, enabled) VALUES (1, false); diff --git a/internal/db/migrations/0091_remove_lidarr.up.sql b/internal/db/migrations/0091_remove_lidarr.up.sql deleted file mode 100644 index b8e64723..00000000 --- a/internal/db/migrations/0091_remove_lidarr.up.sql +++ /dev/null @@ -1,29 +0,0 @@ --- Minstrel does not talk to Lidarr: it finds, downloads, --- checks and files music itself. --- --- lidarr_config the connection's settings: dropped. --- lidarr_quarantine(_actions) the per-user track reports and the admin --- actions on them, which never needed Lidarr: --- renamed to quarantine(_actions), with their --- types and indexes. --- 'deleted_via_lidarr' the history of an album removed through --- Lidarr reads as what it did: 'deleted_album'. --- lidarr_album_mbid the album id that removal recorded: album_mbid. -DROP TABLE lidarr_config; - -ALTER TABLE lidarr_quarantine RENAME TO quarantine; -ALTER TYPE lidarr_quarantine_reason RENAME TO quarantine_reason; -ALTER INDEX lidarr_quarantine_track_idx RENAME TO quarantine_track_idx; -ALTER INDEX lidarr_quarantine_pkey RENAME TO quarantine_pkey; - -ALTER TABLE lidarr_quarantine_actions RENAME TO quarantine_actions; -ALTER TYPE lidarr_quarantine_action_kind RENAME TO quarantine_action_kind; -ALTER TYPE quarantine_action_kind RENAME VALUE 'deleted_via_lidarr' TO 'deleted_album'; -ALTER TABLE quarantine_actions RENAME COLUMN lidarr_album_mbid TO album_mbid; -ALTER INDEX lidarr_quarantine_actions_pkey RENAME TO quarantine_actions_pkey; -ALTER INDEX lidarr_quarantine_actions_track_idx RENAME TO quarantine_actions_track_idx; -ALTER INDEX lidarr_quarantine_actions_created_idx RENAME TO quarantine_actions_created_idx; - -ALTER TABLE quarantine RENAME CONSTRAINT lidarr_quarantine_user_id_fkey TO quarantine_user_id_fkey; -ALTER TABLE quarantine RENAME CONSTRAINT lidarr_quarantine_track_id_fkey TO quarantine_track_id_fkey; -ALTER TABLE quarantine_actions RENAME CONSTRAINT lidarr_quarantine_actions_admin_id_fkey TO quarantine_actions_admin_id_fkey; diff --git a/internal/db/migrations/0092_play_events_started_idx.down.sql b/internal/db/migrations/0092_play_events_started_idx.down.sql deleted file mode 100644 index 62eafa51..00000000 --- a/internal/db/migrations/0092_play_events_started_idx.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP INDEX IF EXISTS play_events_started_idx; diff --git a/internal/db/migrations/0092_play_events_started_idx.up.sql b/internal/db/migrations/0092_play_events_started_idx.up.sql deleted file mode 100644 index d5404011..00000000 --- a/internal/db/migrations/0092_play_events_started_idx.up.sql +++ /dev/null @@ -1,4 +0,0 @@ --- The admin Overview reads plays across every user by time: the ones --- in progress and the last day's count. The only index on play_events leads --- with user_id, so without this every Overview load scanned the table. -CREATE INDEX play_events_started_idx ON play_events (started_at); diff --git a/internal/db/migrations/0093_library_settings.down.sql b/internal/db/migrations/0093_library_settings.down.sql deleted file mode 100644 index 793e3ffb..00000000 --- a/internal/db/migrations/0093_library_settings.down.sql +++ /dev/null @@ -1 +0,0 @@ -DROP TABLE IF EXISTS library_settings; diff --git a/internal/db/migrations/0093_library_settings.up.sql b/internal/db/migrations/0093_library_settings.up.sql deleted file mode 100644 index 4bf3473d..00000000 --- a/internal/db/migrations/0093_library_settings.up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- The library's folders, set in Settings. Until someone saves them --- there, scan_paths is NULL and MINSTREL_LIBRARY_SCAN_PATHS names the folders, --- as it always has; from the first save the row is what the server reads. -CREATE TABLE library_settings ( - id boolean PRIMARY KEY DEFAULT true, - scan_paths text[], - updated_at timestamptz NOT NULL DEFAULT now(), - - CONSTRAINT library_settings_singleton CHECK (id = true) -); -INSERT INTO library_settings (id) VALUES (true) ON CONFLICT (id) DO NOTHING; diff --git a/internal/db/migrations/0094_duplicate_distinct.down.sql b/internal/db/migrations/0094_duplicate_distinct.down.sql deleted file mode 100644 index e5e44233..00000000 --- a/internal/db/migrations/0094_duplicate_distinct.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -UPDATE duplicate_groups SET class = 'review' WHERE class = 'distinct'; -ALTER TABLE duplicate_groups DROP CONSTRAINT duplicate_groups_class_check; -ALTER TABLE duplicate_groups ADD CONSTRAINT duplicate_groups_class_check - CHECK (class IN ('same_release', 'cross_release', 'mismatch', 'review')); diff --git a/internal/db/migrations/0094_duplicate_distinct.up.sql b/internal/db/migrations/0094_duplicate_distinct.up.sql deleted file mode 100644 index 856757e5..00000000 --- a/internal/db/migrations/0094_duplicate_distinct.up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- 0094_duplicate_distinct.up.sql — duplicates settle themselves, without --- waiting on an admin. --- --- distinct: one album holds two versions of a song that sound alike ("Lovesick" --- and "Lovesick (Instrumental)"). They are not duplicates, and the resolver --- dismisses them itself. mismatch now also covers one album holding the same --- audio in several track slots, the resolver's wrong-file case. --- The new value swaps the constraint in the same migration. -ALTER TABLE duplicate_groups DROP CONSTRAINT duplicate_groups_class_check; -ALTER TABLE duplicate_groups ADD CONSTRAINT duplicate_groups_class_check - CHECK (class IN ('same_release', 'cross_release', 'mismatch', 'distinct', 'review')); diff --git a/internal/db/migrations/0095_tracks_emptied_at.down.sql b/internal/db/migrations/0095_tracks_emptied_at.down.sql deleted file mode 100644 index f3feee97..00000000 --- a/internal/db/migrations/0095_tracks_emptied_at.down.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE tracks DROP COLUMN emptied_at; diff --git a/internal/db/migrations/0095_tracks_emptied_at.up.sql b/internal/db/migrations/0095_tracks_emptied_at.up.sql deleted file mode 100644 index 3ab7883a..00000000 --- a/internal/db/migrations/0095_tracks_emptied_at.up.sql +++ /dev/null @@ -1,13 +0,0 @@ --- 0095_tracks_emptied_at.up.sql — a slot the duplicate resolver emptied --- waits for a copy fetched again. --- --- When the resolver removes a file filed under another song's title and the --- album holds no copy of that song as long as the song is, the row is marked --- missing and stamped here with the same time. Missing-pair folding then pairs --- it by title only with a track added after that time, a copy fetched again, --- and not with one already on the album, which under that title holds --- another song. --- --- The stamp counts only while it equals missing_since: a row whose file came --- back and later went missing again is an ordinary missing row. -ALTER TABLE tracks ADD COLUMN emptied_at timestamptz; diff --git a/internal/db/migrations/0096_similarity_relative_scores.down.sql b/internal/db/migrations/0096_similarity_relative_scores.down.sql deleted file mode 100644 index 7c4e468f..00000000 --- a/internal/db/migrations/0096_similarity_relative_scores.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- The raw scores are not kept for artists; the worker rewrites every seed with --- relative scores on its next fetch either way. Nothing to undo. -SELECT 1; diff --git a/internal/db/migrations/0096_similarity_relative_scores.up.sql b/internal/db/migrations/0096_similarity_relative_scores.up.sql deleted file mode 100644 index 111e110e..00000000 --- a/internal/db/migrations/0096_similarity_relative_scores.up.sql +++ /dev/null @@ -1,51 +0,0 @@ --- Before: ListenBrainz similarity scores were stored raw. They are counts, into --- the thousands, and every reader treats similarity as 0 to 1. After: the --- stored rows are rescaled relative to each seed's best score, as the worker --- now writes them. --- --- A seed's best is taken over everything stored for it: the cached LB answer --- and its edges for tracks, matched and unmatched rows for artists. A seed --- whose best is already at most 1 is left alone, so a second run changes --- nothing. - -WITH best AS ( - SELECT seed_id, max(score) AS score - FROM ( - SELECT track_a_id AS seed_id, score FROM track_similarity WHERE source = 'listenbrainz' - UNION ALL - SELECT seed_track_id, score FROM listenbrainz_similar_recordings - ) s - GROUP BY seed_id -) -UPDATE track_similarity ts - SET score = ts.score / b.score - FROM best b - WHERE ts.source = 'listenbrainz' - AND ts.track_a_id = b.seed_id - AND b.score > 1; - --- One statement, so both updates divide by the best as it stood before either. -WITH best AS ( - SELECT seed_id, max(score) AS score - FROM ( - SELECT artist_a_id AS seed_id, score FROM artist_similarity WHERE source = 'listenbrainz' - UNION ALL - SELECT seed_artist_id, score FROM artist_similarity_unmatched WHERE source = 'listenbrainz' - ) s - GROUP BY seed_id -), -matched AS ( - UPDATE artist_similarity a - SET score = a.score / b.score - FROM best b - WHERE a.source = 'listenbrainz' - AND a.artist_a_id = b.seed_id - AND b.score > 1 - RETURNING 1 -) -UPDATE artist_similarity_unmatched u - SET score = u.score / b.score - FROM best b - WHERE u.source = 'listenbrainz' - AND u.seed_artist_id = b.seed_id - AND b.score > 1; diff --git a/internal/db/migrations/0097_requeue_short_track_prints.down.sql b/internal/db/migrations/0097_requeue_short_track_prints.down.sql deleted file mode 100644 index f1513b02..00000000 --- a/internal/db/migrations/0097_requeue_short_track_prints.down.sql +++ /dev/null @@ -1,3 +0,0 @@ --- The cleared rows were failures; the workers write them again, or better. --- Nothing to undo. -SELECT 1; diff --git a/internal/db/migrations/0097_requeue_short_track_prints.up.sql b/internal/db/migrations/0097_requeue_short_track_prints.up.sql deleted file mode 100644 index 47288f43..00000000 --- a/internal/db/migrations/0097_requeue_short_track_prints.up.sql +++ /dev/null @@ -1,20 +0,0 @@ --- The image's fpcalc exits 3 ("Error decoding audio frame (End of file)") on --- every file shorter than the span it is asked for, so every track under two --- minutes failed both prints. Before: the failure was stored as a verdict, and --- a verdict is not retried until the file changes. After: fpcalcReadToEnd keeps --- those prints; clear the failures so the workers take them again. - --- The AcoustID lookup's queue takes a track with no lookup row. -DELETE FROM track_acoustid_lookups - WHERE state = 'failed' - AND detail LIKE '%Error decoding audio frame (End of file)%'; - --- The fingerprint backfill's queue takes a track with no fingerprint row. A --- NULL chromaprint is always a verdict (an inconclusive attempt stores --- nothing), and on a track no longer than the span it was taken at it is this --- failure. A track that is damaged fails again and is stamped again. -DELETE FROM track_fingerprints f - USING tracks t - WHERE f.track_id = t.id - AND f.chromaprint IS NULL - AND t.duration_ms <= f.chromaprint_length_sec * 1000; diff --git a/internal/db/migrations/0098_release_blocks_gone.down.sql b/internal/db/migrations/0098_release_blocks_gone.down.sql deleted file mode 100644 index 97d45aea..00000000 --- a/internal/db/migrations/0098_release_blocks_gone.down.sql +++ /dev/null @@ -1,4 +0,0 @@ -DELETE FROM release_blocks WHERE reason = 'gone'; -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import', 'stalled')); diff --git a/internal/db/migrations/0098_release_blocks_gone.up.sql b/internal/db/migrations/0098_release_blocks_gone.up.sql deleted file mode 100644 index 1b2a2cfe..00000000 --- a/internal/db/migrations/0098_release_blocks_gone.up.sql +++ /dev/null @@ -1,6 +0,0 @@ --- gone: a release its download client would not let Minstrel follow: --- held outside Minstrel's category, or leaving the client twice. Held back --- until expires_at, as stalled is. -ALTER TABLE release_blocks DROP CONSTRAINT release_blocks_reason_check; -ALTER TABLE release_blocks ADD CONSTRAINT release_blocks_reason_check - CHECK (reason IN ('operator', 'files', 'import', 'stalled', 'gone')); diff --git a/internal/db/migrations/0099_backups.down.sql b/internal/db/migrations/0099_backups.down.sql deleted file mode 100644 index 65035b94..00000000 --- a/internal/db/migrations/0099_backups.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS backup_runs; -DROP TABLE IF EXISTS backup_settings; diff --git a/internal/db/migrations/0099_backups.up.sql b/internal/db/migrations/0099_backups.up.sql deleted file mode 100644 index 856ee28c..00000000 --- a/internal/db/migrations/0099_backups.up.sql +++ /dev/null @@ -1,44 +0,0 @@ --- 0099_backups.up.sql — Minstrel backing itself up. --- --- backup_settings one row: whether the nightly backup is on, where it goes --- (a folder, or an S3 bucket such as a Fabled Archives --- target), and the hour it runs, in UTC. Off until an --- admin switches it on. --- backup_runs one row per attempt: when, what started it, how it ended, --- where the file went, its size, and the error in words. -CREATE TABLE backup_settings ( - id boolean PRIMARY KEY DEFAULT true CONSTRAINT backup_settings_one_row CHECK (id), - enabled boolean NOT NULL DEFAULT false, - destination text NOT NULL DEFAULT 's3' - CONSTRAINT backup_settings_destination_check CHECK (destination IN ('folder', 's3')), - folder text NOT NULL DEFAULT '', - endpoint text NOT NULL DEFAULT '', - bucket text NOT NULL DEFAULT '', - access_key text NOT NULL DEFAULT '', - -- Sealed under the stream secret, as every stored credential is. - secret_key text NOT NULL DEFAULT '', - run_hour smallint NOT NULL DEFAULT 3 - CONSTRAINT backup_settings_run_hour_check CHECK (run_hour BETWEEN 0 AND 23), - -- The most an upload to the bucket may send, in KiB a second; 0 is no limit. - upload_limit_kib integer NOT NULL DEFAULT 4096 - CONSTRAINT backup_settings_upload_limit_check CHECK (upload_limit_kib >= 0), - updated_at timestamptz NOT NULL DEFAULT now() -); - -INSERT INTO backup_settings DEFAULT VALUES; - -CREATE TABLE backup_runs ( - id uuid PRIMARY KEY DEFAULT gen_random_uuid(), - trigger text NOT NULL - CONSTRAINT backup_runs_trigger_check CHECK (trigger IN ('schedule', 'manual')), - status text NOT NULL DEFAULT 'running' - CONSTRAINT backup_runs_status_check CHECK (status IN ('running', 'succeeded', 'failed')), - started_at timestamptz NOT NULL DEFAULT now(), - finished_at timestamptz, - -- Where the file went: the object key, or the file's path in the folder. - location text NOT NULL DEFAULT '', - bytes bigint NOT NULL DEFAULT 0, - error text NOT NULL DEFAULT '' -); - -CREATE INDEX backup_runs_started_at_idx ON backup_runs (started_at DESC); diff --git a/internal/db/migrations/0100_backup_music.down.sql b/internal/db/migrations/0100_backup_music.down.sql deleted file mode 100644 index 4dccd1f6..00000000 --- a/internal/db/migrations/0100_backup_music.down.sql +++ /dev/null @@ -1,6 +0,0 @@ -DROP TABLE IF EXISTS backup_music_files; -ALTER TABLE backup_runs - DROP COLUMN IF EXISTS music_note, - DROP COLUMN IF EXISTS music_bytes, - DROP COLUMN IF EXISTS music_files; -ALTER TABLE backup_settings DROP COLUMN IF EXISTS include_music; diff --git a/internal/db/migrations/0100_backup_music.up.sql b/internal/db/migrations/0100_backup_music.up.sql deleted file mode 100644 index cc0c894b..00000000 --- a/internal/db/migrations/0100_backup_music.up.sql +++ /dev/null @@ -1,36 +0,0 @@ --- 0100_backup_music.up.sql — the music files in Minstrel's own backup. --- --- Until now a backup held the database only. With include_music on, each --- library file is also sent once to music/ in the same destination, --- and sent again only when it changes. --- --- backup_settings.include_music off until an admin switches it on. --- backup_music_files one row per track sent (or refused): the --- file's size and mtime when it was sent, so --- a later night sends only what is new or --- changed. A track the scan has touched since --- checked_at is looked at again; it goes up --- again only if the file itself changed, so a --- full rescan doesn't resend the library. A --- refusal is kept with its reason and tried --- again once the file changes. --- backup_runs.music_* how much a run sent, and why it stopped. -ALTER TABLE backup_settings ADD COLUMN include_music boolean NOT NULL DEFAULT false; - -ALTER TABLE backup_runs - ADD COLUMN music_files integer NOT NULL DEFAULT 0, - ADD COLUMN music_bytes bigint NOT NULL DEFAULT 0, - ADD COLUMN music_note text NOT NULL DEFAULT ''; - -CREATE TABLE backup_music_files ( - track_id uuid PRIMARY KEY REFERENCES tracks (id) ON DELETE CASCADE, - -- The file as it was sent. - size bigint NOT NULL, - mtime timestamptz NOT NULL, - -- Where it went: the object key, or the file's path in the folder. - location text NOT NULL, - -- When the file was last sent or found unchanged. - checked_at timestamptz NOT NULL DEFAULT now(), - -- Empty when it was sent; otherwise why the destination refused it. - error text NOT NULL DEFAULT '' -); diff --git a/internal/db/migrations/0101_library_changes_keep_latest.down.sql b/internal/db/migrations/0101_library_changes_keep_latest.down.sql deleted file mode 100644 index ffee2bf1..00000000 --- a/internal/db/migrations/0101_library_changes_keep_latest.down.sql +++ /dev/null @@ -1,2 +0,0 @@ -DROP TABLE IF EXISTS library_changes_trimmed; -DROP INDEX IF EXISTS idx_library_changes_entity; diff --git a/internal/db/migrations/0101_library_changes_keep_latest.up.sql b/internal/db/migrations/0101_library_changes_keep_latest.up.sql deleted file mode 100644 index 4d9933cd..00000000 --- a/internal/db/migrations/0101_library_changes_keep_latest.up.sql +++ /dev/null @@ -1,56 +0,0 @@ --- 0101_library_changes_keep_latest.up.sql — the change feed keeps every --- entity's latest change, so an app syncing from nothing gets the whole --- library. --- --- Until now the compactor dropped every row older than 30 days. An app --- syncing from cursor 0 (a fresh install, cleared data, or a reset after a --- 410) builds its library from the feed, so it got only what had changed in --- the last 30 days. From here the compactor drops a row only once a newer row --- for the same entity exists, and drops a delete only once it is 30 days old. --- --- idx_library_changes_entity finds an entity's rows, newest first, for --- the compactor and the fill below. --- library_changes_trimmed one row: the highest id of a delete the --- compactor has dropped. An app whose cursor --- is below it may have missed that delete, so --- it is told to start over (410). It starts --- where the old compactor left off: everything --- below the oldest remaining row is gone. --- --- Then every artist, album and track whose latest row is not an upsert, or --- which has no row at all (the old compactor dropped it), gets one, artists --- first so an album never arrives before its artist. Likes and playlists are --- left as they are: the apps fetch those from their own endpoints. -CREATE INDEX idx_library_changes_entity ON library_changes (entity_type, entity_id, id DESC); - -CREATE TABLE library_changes_trimmed ( - id boolean PRIMARY KEY DEFAULT true CONSTRAINT library_changes_trimmed_one_row CHECK (id), - through bigint NOT NULL DEFAULT 0 -); - -INSERT INTO library_changes_trimmed (through) -SELECT COALESCE(min(id), 1) - 1 FROM library_changes; - -INSERT INTO library_changes (entity_type, entity_id, op) -SELECT 'artist', a.id::text, 'upsert' - FROM artists a - WHERE COALESCE((SELECT c.op FROM library_changes c - WHERE c.entity_type = 'artist' AND c.entity_id = a.id::text - ORDER BY c.id DESC LIMIT 1), 'delete') <> 'upsert' - ORDER BY a.id; - -INSERT INTO library_changes (entity_type, entity_id, op) -SELECT 'album', al.id::text, 'upsert' - FROM albums al - WHERE COALESCE((SELECT c.op FROM library_changes c - WHERE c.entity_type = 'album' AND c.entity_id = al.id::text - ORDER BY c.id DESC LIMIT 1), 'delete') <> 'upsert' - ORDER BY al.id; - -INSERT INTO library_changes (entity_type, entity_id, op) -SELECT 'track', t.id::text, 'upsert' - FROM tracks t - WHERE COALESCE((SELECT c.op FROM library_changes c - WHERE c.entity_type = 'track' AND c.entity_id = t.id::text - ORDER BY c.id DESC LIMIT 1), 'delete') <> 'upsert' - ORDER BY t.id; diff --git a/internal/db/migrations/0102_genre_mix_variant.down.sql b/internal/db/migrations/0102_genre_mix_variant.down.sql deleted file mode 100644 index b039f04c..00000000 --- a/internal/db/migrations/0102_genre_mix_variant.down.sql +++ /dev/null @@ -1,37 +0,0 @@ --- Restores the 0028 constraint set. Genre-mix rows would violate it, so they --- go first. -DELETE FROM playlists WHERE system_variant = 'genre_mix'; - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ( - 'for_you', 'songs_like_artist', 'discover', - 'deep_cuts', 'rediscover', 'new_for_you', - 'on_this_day', 'first_listens' - )) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'discover' AND seed_artist_id IS NULL) - OR - (system_variant = 'deep_cuts' AND seed_artist_id IS NULL) - OR - (system_variant = 'rediscover' AND seed_artist_id IS NULL) - OR - (system_variant = 'new_for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'on_this_day' AND seed_artist_id IS NULL) - OR - (system_variant = 'first_listens' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0102_genre_mix_variant.up.sql b/internal/db/migrations/0102_genre_mix_variant.up.sql deleted file mode 100644 index 706ccd69..00000000 --- a/internal/db/migrations/0102_genre_mix_variant.up.sql +++ /dev/null @@ -1,43 +0,0 @@ --- Genre mixes: one daily system playlist per genre the user listens to --- ("Post-Punk mix", "Jazz mix", ...). Several per user, like --- songs_like_artist, but seedless: the genre lives in the playlist name and --- seed_artist_id is NULL. --- --- Postgres has no ALTER CONSTRAINT for CHECK, so both constraints are --- dropped and re-added with 'genre_mix' in the accepted set. - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_kind_variant_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_kind_variant_consistent CHECK ( - (kind = 'user' AND system_variant IS NULL) - OR - (kind = 'system' AND system_variant IN ( - 'for_you', 'songs_like_artist', 'discover', - 'deep_cuts', 'rediscover', 'new_for_you', - 'on_this_day', 'first_listens', 'genre_mix' - )) - ); - -ALTER TABLE playlists DROP CONSTRAINT IF EXISTS playlists_seed_consistent; -ALTER TABLE playlists - ADD CONSTRAINT playlists_seed_consistent CHECK ( - (system_variant IS NULL AND seed_artist_id IS NULL) - OR - (system_variant = 'for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'discover' AND seed_artist_id IS NULL) - OR - (system_variant = 'deep_cuts' AND seed_artist_id IS NULL) - OR - (system_variant = 'rediscover' AND seed_artist_id IS NULL) - OR - (system_variant = 'new_for_you' AND seed_artist_id IS NULL) - OR - (system_variant = 'on_this_day' AND seed_artist_id IS NULL) - OR - (system_variant = 'first_listens' AND seed_artist_id IS NULL) - OR - (system_variant = 'genre_mix' AND seed_artist_id IS NULL) - OR - (system_variant = 'songs_like_artist' AND seed_artist_id IS NOT NULL) - ); diff --git a/internal/db/migrations/0103_new_music.down.sql b/internal/db/migrations/0103_new_music.down.sql deleted file mode 100644 index 731ad5f6..00000000 --- a/internal/db/migrations/0103_new_music.down.sql +++ /dev/null @@ -1,17 +0,0 @@ -ALTER TABLE albums DROP COLUMN IF EXISTS announced_at; - -DELETE FROM user_notifications WHERE kind = 'new_music'; -DELETE FROM user_notification_prefs WHERE kind = 'new_music'; - -ALTER TABLE user_notifications DROP CONSTRAINT user_notifications_kind_check; -ALTER TABLE user_notifications ADD CONSTRAINT user_notifications_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'duplicates_resolved', - 'playback_errors')); -ALTER TABLE user_notification_prefs DROP CONSTRAINT user_notification_prefs_kind_check; -ALTER TABLE user_notification_prefs ADD CONSTRAINT user_notification_prefs_kind_check - CHECK (kind IN ('request_approved', 'request_rejected', 'request_completed', - 'request_pending', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'duplicates_resolved', - 'playback_errors')); diff --git a/internal/db/migrations/0103_new_music.up.sql b/internal/db/migrations/0103_new_music.up.sql deleted file mode 100644 index b1f86606..00000000 --- a/internal/db/migrations/0103_new_music.up.sql +++ /dev/null @@ -1,29 +0,0 @@ --- New-music notices come from the library itself instead of from requests. --- --- The request_* kinds announced the stages of a request: asked, approved, --- declined, arrived. Minstrel no longer takes requests, so their rows and --- per-user preferences are deleted, and the kind CHECKs swap them for --- new_music, which announces albums a scan brought into the library. --- --- albums.announced_at marks an album as already told about. A scan claims --- every album without one and tells users about those that are new. Every --- album held now counts as announced, so the first scan after this migration --- announces nothing old. -DELETE FROM user_notifications - WHERE kind IN ('request_approved', 'request_rejected', 'request_completed', 'request_pending'); -DELETE FROM user_notification_prefs - WHERE kind IN ('request_approved', 'request_rejected', 'request_completed', 'request_pending'); - -ALTER TABLE user_notifications DROP CONSTRAINT user_notifications_kind_check; -ALTER TABLE user_notifications ADD CONSTRAINT user_notifications_kind_check - CHECK (kind IN ('new_music', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'duplicates_resolved', - 'playback_errors')); -ALTER TABLE user_notification_prefs DROP CONSTRAINT user_notification_prefs_kind_check; -ALTER TABLE user_notification_prefs ADD CONSTRAINT user_notification_prefs_kind_check - CHECK (kind IN ('new_music', 'quarantine_flagged', 'scan_failed', - 'tracks_missing', 'duplicates_found', 'duplicates_resolved', - 'playback_errors')); - -ALTER TABLE albums ADD COLUMN announced_at timestamptz; -UPDATE albums SET announced_at = created_at; diff --git a/internal/db/migrations/0104_removed_tracks.down.sql b/internal/db/migrations/0104_removed_tracks.down.sql deleted file mode 100644 index 07c453ec..00000000 --- a/internal/db/migrations/0104_removed_tracks.down.sql +++ /dev/null @@ -1,9 +0,0 @@ --- Postgres cannot drop an enum value, so removed_file stays in --- quarantine_action_kind; its history rows read as deleted_file again. -UPDATE quarantine_actions SET action = 'deleted_file' WHERE action = 'removed_file'; - -ALTER TABLE tracks - DROP CONSTRAINT IF EXISTS tracks_removed_only_missing, - DROP CONSTRAINT IF EXISTS tracks_removed_reason_check, - DROP COLUMN IF EXISTS removed_by, - DROP COLUMN IF EXISTS removed_reason; diff --git a/internal/db/migrations/0104_removed_tracks.up.sql b/internal/db/migrations/0104_removed_tracks.up.sql deleted file mode 100644 index 88b29b7b..00000000 --- a/internal/db/migrations/0104_removed_tracks.up.sql +++ /dev/null @@ -1,22 +0,0 @@ --- 0104_removed_tracks.up.sql — a track whose file an admin removed waits for a --- good copy, and says why. --- --- Removing a bad file from Reports, Duplicates or Suspect sources keeps the --- track: it is marked missing with its likes, plays and playlist places, and --- a good copy that lands in the library later is adopted or folded into it. --- removed_reason says which queue it was removed from and removed_by who did --- it (NULL when the duplicate resolver did it on its own). Both describe the --- current missing spell only, so they are cleared with the missing mark, and --- the CHECK keeps them off a present track. --- --- removed_file is the Reports history's name for that removal, beside --- deleted_file, which removes the track as well. -ALTER TABLE tracks - ADD COLUMN removed_reason text, - ADD COLUMN removed_by uuid REFERENCES users(id) ON DELETE SET NULL, - ADD CONSTRAINT tracks_removed_reason_check - CHECK (removed_reason IN ('report', 'duplicate', 'suspect')), - ADD CONSTRAINT tracks_removed_only_missing - CHECK (missing_since IS NOT NULL OR (removed_reason IS NULL AND removed_by IS NULL)); - -ALTER TYPE quarantine_action_kind ADD VALUE IF NOT EXISTS 'removed_file'; diff --git a/internal/db/migrations/0105_drop_acquisition.down.sql b/internal/db/migrations/0105_drop_acquisition.down.sql deleted file mode 100644 index be46e1ba..00000000 --- a/internal/db/migrations/0105_drop_acquisition.down.sql +++ /dev/null @@ -1,5 +0,0 @@ --- The dropped tables held data this migration deleted, so there is nothing --- to restore them from. Restore a backup taken before it instead. -DO $$ BEGIN - RAISE EXCEPTION 'migration 105 dropped data and cannot be undone; restore a backup taken before it'; -END $$; diff --git a/internal/db/migrations/0105_drop_acquisition.up.sql b/internal/db/migrations/0105_drop_acquisition.up.sql deleted file mode 100644 index 87de6af8..00000000 --- a/internal/db/migrations/0105_drop_acquisition.up.sql +++ /dev/null @@ -1,44 +0,0 @@ --- Minstrel plays and keeps the library it is given; it no longer finds --- music. This drops the tables that served finding it (follows, wants, --- searches, downloads, requests and their settings), the Discover tables, --- the MusicBrainz artist catalogue only those used, and the per-user --- auto-approve switch. --- --- An album matched to a release group only through its wanted-listing --- match keeps that release group: it is copied onto the album first, where --- the duplicate resolver reads it. -UPDATE albums al - SET release_group_mbid = lam.release_group_mbid - FROM library_album_matches lam - WHERE lam.album_id = al.id - AND lam.outcome = 'listed' - AND COALESCE(lam.release_group_mbid, '') <> '' - AND COALESCE(al.release_group_mbid, '') = ''; - --- Each table goes after the tables that reference it, without CASCADE, so --- a reference from a table that stays stops the migration instead of being --- dropped quietly. -DROP TABLE download_interventions; -DROP TABLE want_candidates; -DROP TABLE release_blocks; -DROP TABLE grabs; -DROP TABLE wants; -DROP TABLE follow_seen_groups; -DROP TABLE follows; -DROP TABLE release_type_profiles; -DROP TABLE requests; -DROP TABLE acquisition_services; -DROP TABLE acquisition_settings; -DROP TABLE reacquisition_settings; -DROP TABLE library_album_matches; - -DROP TABLE suggestion_snoozes; -DROP TABLE discover_tuning; -DROP TABLE candidate_artist_tag_state; -DROP TABLE candidate_artist_tags; -DROP TABLE artist_similarity_unmatched; - -DROP TABLE mb_artist_release_groups; -DROP TABLE mb_artists; - -ALTER TABLE users DROP COLUMN auto_approve_requests; diff --git a/internal/db/migrations/0106_baseline.down.sql b/internal/db/migrations/0106_baseline.down.sql new file mode 100644 index 00000000..98893644 --- /dev/null +++ b/internal/db/migrations/0106_baseline.down.sql @@ -0,0 +1 @@ +DO $$ BEGIN RAISE EXCEPTION 'the baseline is the whole schema and cannot be undone; restore a backup instead'; END $$; diff --git a/internal/db/migrations/0106_baseline.up.sql b/internal/db/migrations/0106_baseline.up.sql new file mode 100644 index 00000000..7f3de9ff --- /dev/null +++ b/internal/db/migrations/0106_baseline.up.sql @@ -0,0 +1,1433 @@ +-- The whole schema at version 106, and the settings rows it starts with. +-- Earlier versions were folded into this one; a database already at 106 +-- skips it, and an older one restores from a backup instead. + +CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public; + +CREATE TYPE public.quarantine_action_kind AS ENUM ( + 'resolved', + 'deleted_file', + 'deleted_album', + 'removed_file' +); + +CREATE TYPE public.quarantine_reason AS ENUM ( + 'bad_rip', + 'wrong_file', + 'wrong_tags', + 'duplicate', + 'other' +); + +CREATE TABLE public.acoustid_settings ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT false NOT NULL, + api_key text, + min_score real DEFAULT 0.85 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT acoustid_settings_min_score_range CHECK (((min_score >= (0.5)::double precision) AND (min_score <= (1)::double precision))), + CONSTRAINT acoustid_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.album_loudness ( + album_id uuid NOT NULL, + integrated_lufs real, + true_peak_dbtp real, + tracks_total integer NOT NULL, + tracks_settled integer NOT NULL, + inputs_digest text NOT NULL, + computed_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.albums ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + title text NOT NULL, + sort_title text NOT NULL, + artist_id uuid NOT NULL, + release_date date, + mbid text, + cover_art_path text, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + cover_art_source text, + cover_art_sources_version integer DEFAULT 0 NOT NULL, + release_group_mbid text, + announced_at timestamp with time zone, + CONSTRAINT albums_cover_art_source_check CHECK (((cover_art_source IS NULL) OR (cover_art_source <> ''::text))) +); + +CREATE TABLE public.artist_similarity ( + artist_a_id uuid NOT NULL, + artist_b_id uuid NOT NULL, + score double precision NOT NULL, + source text NOT NULL, + fetched_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT artist_similarity_check CHECK ((artist_a_id <> artist_b_id)), + CONSTRAINT artist_similarity_source_check CHECK ((source = ANY (ARRAY['listenbrainz'::text, 'musicbrainz_tag'::text, 'user_cooccurrence'::text]))) +); + +CREATE TABLE public.artist_similarity_fetches ( + artist_id uuid NOT NULL, + fetched_at timestamp with time zone DEFAULT now() NOT NULL, + returned integer NOT NULL +); + +CREATE TABLE public.artists ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + name text NOT NULL, + sort_name text NOT NULL, + mbid text, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + artist_thumb_path text, + artist_fanart_path text, + artist_art_source text, + artist_art_sources_version integer DEFAULT 0 NOT NULL, + CONSTRAINT artists_artist_art_source_check CHECK (((artist_art_source IS NULL) OR (artist_art_source <> ''::text))) +); + +CREATE TABLE public.audit_log ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + actor_id uuid, + target_id uuid, + action text NOT NULL, + metadata jsonb, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.backup_music_files ( + track_id uuid NOT NULL, + size bigint NOT NULL, + mtime timestamp with time zone NOT NULL, + location text NOT NULL, + checked_at timestamp with time zone DEFAULT now() NOT NULL, + error text DEFAULT ''::text NOT NULL +); + +CREATE TABLE public.backup_runs ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + trigger text NOT NULL, + status text DEFAULT 'running'::text NOT NULL, + started_at timestamp with time zone DEFAULT now() NOT NULL, + finished_at timestamp with time zone, + location text DEFAULT ''::text NOT NULL, + bytes bigint DEFAULT 0 NOT NULL, + error text DEFAULT ''::text NOT NULL, + music_files integer DEFAULT 0 NOT NULL, + music_bytes bigint DEFAULT 0 NOT NULL, + music_note text DEFAULT ''::text NOT NULL, + CONSTRAINT backup_runs_status_check CHECK ((status = ANY (ARRAY['running'::text, 'succeeded'::text, 'failed'::text]))), + CONSTRAINT backup_runs_trigger_check CHECK ((trigger = ANY (ARRAY['schedule'::text, 'manual'::text]))) +); + +CREATE TABLE public.backup_settings ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT false NOT NULL, + destination text DEFAULT 's3'::text NOT NULL, + folder text DEFAULT ''::text NOT NULL, + endpoint text DEFAULT ''::text NOT NULL, + bucket text DEFAULT ''::text NOT NULL, + access_key text DEFAULT ''::text NOT NULL, + secret_key text DEFAULT ''::text NOT NULL, + run_hour smallint DEFAULT 3 NOT NULL, + upload_limit_kib integer DEFAULT 4096 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + include_music boolean DEFAULT false NOT NULL, + CONSTRAINT backup_settings_destination_check CHECK ((destination = ANY (ARRAY['folder'::text, 's3'::text]))), + CONSTRAINT backup_settings_one_row CHECK (id), + CONSTRAINT backup_settings_run_hour_check CHECK (((run_hour >= 0) AND (run_hour <= 23))), + CONSTRAINT backup_settings_upload_limit_check CHECK ((upload_limit_kib >= 0)) +); + +CREATE TABLE public.contextual_likes ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + track_id uuid NOT NULL, + liked_at timestamp with time zone DEFAULT now() NOT NULL, + deleted_at timestamp with time zone, + session_vector jsonb, + session_id uuid +); + +CREATE TABLE public.cover_art_provider_settings ( + provider_id text NOT NULL, + enabled boolean DEFAULT true NOT NULL, + api_key text, + display_order integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.cover_art_sources_meta ( + id boolean DEFAULT true NOT NULL, + current_version integer DEFAULT 1 NOT NULL, + last_registered_providers_hash text DEFAULT ''::text NOT NULL, + CONSTRAINT cover_art_sources_meta_singleton CHECK ((id = true)) +); + +CREATE TABLE public.diagnostic_events ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + client_id text NOT NULL, + app_version text, + os_version text, + kind text NOT NULL, + payload jsonb DEFAULT '{}'::jsonb NOT NULL, + occurred_at timestamp with time zone NOT NULL, + received_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT diagnostic_events_kind_check CHECK ((kind = ANY (ARRAY['connectivity'::text, 'upnp_sync'::text, 'power'::text, 'lifecycle'::text, 'heartbeat'::text, 'http'::text, 'playback'::text]))) +); + +CREATE TABLE public.duplicate_group_members ( + group_id uuid NOT NULL, + track_id uuid NOT NULL +); + +CREATE TABLE public.duplicate_groups ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + member_key text NOT NULL, + tier text NOT NULL, + worst_bit_error_rate real, + status text DEFAULT 'pending'::text NOT NULL, + detected_at timestamp with time zone DEFAULT now() NOT NULL, + last_seen_sweep_id uuid, + resolved_at timestamp with time zone, + class text, + resolve_note text, + resolved_automatically boolean DEFAULT false NOT NULL, + CONSTRAINT duplicate_groups_class_check CHECK ((class = ANY (ARRAY['same_release'::text, 'cross_release'::text, 'mismatch'::text, 'distinct'::text, 'review'::text]))), + CONSTRAINT duplicate_groups_status_check CHECK ((status = ANY (ARRAY['pending'::text, 'dismissed'::text, 'merged'::text]))), + CONSTRAINT duplicate_groups_tier_check CHECK ((tier = ANY (ARRAY['exact'::text, 'acoustic'::text]))) +); + +CREATE TABLE public.duplicate_sweeps ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + started_at timestamp with time zone DEFAULT now() NOT NULL, + finished_at timestamp with time zone, + candidates integer, + groups_found integer, + oversize_clusters integer, + error_message text +); + +CREATE TABLE public.fingerprint_settings ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT true NOT NULL, + chromaprint_length_sec integer DEFAULT 120 NOT NULL, + acoustic_max_bit_error_rate double precision DEFAULT 0.15 NOT NULL, + backfill_concurrency integer DEFAULT 2 NOT NULL, + sweep_interval_hours integer DEFAULT 1 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + auto_resolve boolean DEFAULT true NOT NULL, + CONSTRAINT fingerprint_settings_concurrency_range CHECK (((backfill_concurrency >= 1) AND (backfill_concurrency <= 8))), + CONSTRAINT fingerprint_settings_length_range CHECK (((chromaprint_length_sec >= 30) AND (chromaprint_length_sec <= 600))), + CONSTRAINT fingerprint_settings_singleton CHECK ((id = true)), + CONSTRAINT fingerprint_settings_sweep_interval_range CHECK (((sweep_interval_hours >= 1) AND (sweep_interval_hours <= 168))), + CONSTRAINT fingerprint_settings_threshold_range CHECK (((acoustic_max_bit_error_rate >= (0.01)::double precision) AND (acoustic_max_bit_error_rate <= (0.35)::double precision))) +); + +CREATE TABLE public.general_likes ( + user_id uuid NOT NULL, + track_id uuid NOT NULL, + liked_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.general_likes_albums ( + user_id uuid NOT NULL, + album_id uuid NOT NULL, + liked_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.general_likes_artists ( + user_id uuid NOT NULL, + artist_id uuid NOT NULL, + liked_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.library_changes ( + id bigint NOT NULL, + entity_type text NOT NULL, + entity_id text NOT NULL, + op text NOT NULL, + changed_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT library_changes_entity_type_check CHECK ((entity_type = ANY (ARRAY['artist'::text, 'album'::text, 'track'::text, 'like_track'::text, 'like_album'::text, 'like_artist'::text, 'playlist'::text, 'playlist_track'::text]))), + CONSTRAINT library_changes_op_check CHECK ((op = ANY (ARRAY['upsert'::text, 'delete'::text]))) +); + +CREATE SEQUENCE public.library_changes_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + +ALTER SEQUENCE public.library_changes_id_seq OWNED BY public.library_changes.id; + +CREATE TABLE public.library_changes_trimmed ( + id boolean DEFAULT true NOT NULL, + through bigint DEFAULT 0 NOT NULL, + CONSTRAINT library_changes_trimmed_one_row CHECK (id) +); + +CREATE TABLE public.library_settings ( + id boolean DEFAULT true NOT NULL, + scan_paths text[], + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT library_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.listenbrainz_similar_recordings ( + seed_track_id uuid NOT NULL, + recording_mbid text NOT NULL, + score double precision NOT NULL +); + +CREATE TABLE public.loudness_settings ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT true NOT NULL, + backfill_concurrency integer DEFAULT 2 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + leveled_cache_mb integer DEFAULT 2048 NOT NULL, + CONSTRAINT loudness_settings_concurrency_range CHECK (((backfill_concurrency >= 1) AND (backfill_concurrency <= 8))), + CONSTRAINT loudness_settings_leveled_cache_range CHECK (((leveled_cache_mb >= 256) AND (leveled_cache_mb <= 65536))), + CONSTRAINT loudness_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.mb_release_groups ( + mbid text NOT NULL, + title text NOT NULL, + primary_type text DEFAULT ''::text NOT NULL, + secondary_types text[] DEFAULT '{}'::text[] NOT NULL, + first_release_date text DEFAULT ''::text NOT NULL, + artist_credit text DEFAULT ''::text NOT NULL, + releases_refreshed_at timestamp with time zone, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.mb_release_tracks ( + release_mbid text NOT NULL, + medium_position integer NOT NULL, + "position" integer NOT NULL, + medium_format text DEFAULT ''::text NOT NULL, + number text DEFAULT ''::text NOT NULL, + title text NOT NULL, + length_ms integer DEFAULT 0 NOT NULL, + recording_mbid text DEFAULT ''::text NOT NULL +); + +CREATE TABLE public.mb_releases ( + mbid text NOT NULL, + release_group_mbid text NOT NULL, + title text NOT NULL, + status text DEFAULT ''::text NOT NULL, + release_date text DEFAULT ''::text NOT NULL, + country text DEFAULT ''::text NOT NULL, + disambiguation text DEFAULT ''::text NOT NULL, + formats text DEFAULT ''::text NOT NULL, + track_count integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.network_settings ( + id boolean DEFAULT true NOT NULL, + trusted_proxy_hops integer DEFAULT 1 NOT NULL, + public_url text DEFAULT ''::text NOT NULL, + CONSTRAINT network_settings_hops_range CHECK (((trusted_proxy_hops >= 0) AND (trusted_proxy_hops <= 10))), + CONSTRAINT network_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.notification_email_settings ( + id boolean DEFAULT true NOT NULL, + summary_hour integer DEFAULT 9 NOT NULL, + batch_window_minutes integer DEFAULT 60 NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT notification_email_settings_hour_range CHECK (((summary_hour >= 0) AND (summary_hour <= 23))), + CONSTRAINT notification_email_settings_singleton CHECK ((id = true)), + CONSTRAINT notification_email_settings_window_range CHECK (((batch_window_minutes >= 15) AND (batch_window_minutes <= 1440))) +); + +CREATE TABLE public.password_resets ( + token text NOT NULL, + user_id uuid NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + expires_at timestamp with time zone NOT NULL, + used_at timestamp with time zone +); + +CREATE TABLE public.play_events ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + track_id uuid NOT NULL, + session_id uuid NOT NULL, + started_at timestamp with time zone NOT NULL, + ended_at timestamp with time zone, + duration_played_ms integer, + completion_ratio double precision, + was_skipped boolean DEFAULT false NOT NULL, + client_id text, + session_vector_at_play jsonb, + scrobbled_at timestamp with time zone, + source text, + pick_kind text, + device_class text, + CONSTRAINT play_events_pick_kind_check CHECK ((pick_kind = ANY (ARRAY['taste'::text, 'fresh'::text, 'dormant'::text, 'cross_user'::text, 'random'::text, 'taste_unheard'::text, 'tier1'::text, 'tier2'::text, 'tier3'::text]))) +); + +CREATE TABLE public.play_sessions ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + started_at timestamp with time zone NOT NULL, + ended_at timestamp with time zone, + last_event_at timestamp with time zone NOT NULL, + track_count integer DEFAULT 0 NOT NULL, + client_id text +); + +CREATE TABLE public.playback_errors ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + track_id uuid NOT NULL, + user_id uuid NOT NULL, + client_id text NOT NULL, + kind text NOT NULL, + detail text, + occurred_at timestamp with time zone DEFAULT now() NOT NULL, + resolved_at timestamp with time zone, + resolved_by uuid, + resolution text, + CONSTRAINT playback_errors_kind_check CHECK ((kind = ANY (ARRAY['zero_duration'::text, 'load_failed'::text, 'stalled'::text]))), + CONSTRAINT playback_errors_resolution_check CHECK (((resolution IS NULL) OR (resolution = ANY (ARRAY['hidden'::text, 'deleted'::text, 'fixed'::text, 'ignored'::text])))), + CONSTRAINT playback_errors_resolved_consistency CHECK (((resolved_at IS NULL) = (resolution IS NULL))) +); + +CREATE TABLE public.playlist_tracks ( + playlist_id uuid NOT NULL, + "position" integer NOT NULL, + track_id uuid, + title text NOT NULL, + artist_name text NOT NULL, + album_title text NOT NULL, + duration_sec integer NOT NULL, + added_at timestamp with time zone DEFAULT now() NOT NULL, + pick_kind text, + CONSTRAINT playlist_tracks_pick_kind_check CHECK ((pick_kind = ANY (ARRAY['taste'::text, 'fresh'::text, 'dormant'::text, 'cross_user'::text, 'random'::text, 'taste_unheard'::text, 'tier1'::text, 'tier2'::text, 'tier3'::text]))) +); + +CREATE TABLE public.playlists ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + name text NOT NULL, + description text DEFAULT ''::text NOT NULL, + is_public boolean DEFAULT false NOT NULL, + cover_path text, + track_count integer DEFAULT 0 NOT NULL, + duration_sec integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + kind text DEFAULT 'user'::text NOT NULL, + system_variant text, + seed_artist_id uuid, + CONSTRAINT playlists_kind_variant_consistent CHECK ((((kind = 'user'::text) AND (system_variant IS NULL)) OR ((kind = 'system'::text) AND (system_variant = ANY (ARRAY['for_you'::text, 'songs_like_artist'::text, 'discover'::text, 'deep_cuts'::text, 'rediscover'::text, 'new_for_you'::text, 'on_this_day'::text, 'first_listens'::text, 'genre_mix'::text]))))), + CONSTRAINT playlists_seed_consistent CHECK ((((system_variant IS NULL) AND (seed_artist_id IS NULL)) OR ((system_variant = 'for_you'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'discover'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'deep_cuts'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'rediscover'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'new_for_you'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'on_this_day'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'first_listens'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'genre_mix'::text) AND (seed_artist_id IS NULL)) OR ((system_variant = 'songs_like_artist'::text) AND (seed_artist_id IS NOT NULL)))) +); + +CREATE TABLE public.quarantine ( + user_id uuid NOT NULL, + track_id uuid NOT NULL, + reason public.quarantine_reason NOT NULL, + notes text, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.quarantine_actions ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + track_id uuid NOT NULL, + track_title text NOT NULL, + artist_name text NOT NULL, + album_title text, + action public.quarantine_action_kind NOT NULL, + admin_id uuid, + album_mbid text, + affected_users integer NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.recommendation_tuning_audit ( + id bigint NOT NULL, + changed_at timestamp with time zone DEFAULT now() NOT NULL, + scope text NOT NULL, + action text NOT NULL, + changes jsonb NOT NULL, + CONSTRAINT recommendation_tuning_audit_action_check CHECK ((action = ANY (ARRAY['update'::text, 'reset'::text]))), + CONSTRAINT recommendation_tuning_audit_scope_check CHECK ((scope = ANY (ARRAY['radio'::text, 'daily_mix'::text, 'taste'::text, 'discover'::text, 'songs_like'::text]))) +); + +CREATE SEQUENCE public.recommendation_tuning_audit_id_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + +ALTER SEQUENCE public.recommendation_tuning_audit_id_seq OWNED BY public.recommendation_tuning_audit.id; + +CREATE TABLE public.recommendation_weight_profiles ( + profile text NOT NULL, + base_weight double precision NOT NULL, + like_boost double precision NOT NULL, + recency_weight double precision NOT NULL, + skip_penalty double precision NOT NULL, + jitter_magnitude double precision NOT NULL, + context_weight double precision NOT NULL, + similarity_weight double precision NOT NULL, + taste_weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + context_time_weight double precision DEFAULT 1.0 NOT NULL, + CONSTRAINT recommendation_weight_profiles_profile_check CHECK ((profile = ANY (ARRAY['radio'::text, 'daily_mix'::text, 'songs_like'::text]))) +); + +CREATE TABLE public.registration_settings ( + id boolean DEFAULT true NOT NULL, + mode text DEFAULT 'invite_only'::text NOT NULL, + CONSTRAINT registration_settings_mode_check CHECK ((mode = ANY (ARRAY['invite_only'::text, 'open'::text]))), + CONSTRAINT registration_settings_singleton CHECK ((id = true)) +); + +CREATE TABLE public.scan_runs ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + started_at timestamp with time zone DEFAULT now() NOT NULL, + finished_at timestamp with time zone, + library jsonb, + mbid_backfill jsonb, + cover_enrich jsonb, + error_message text, + artist_art_enrich jsonb +); + +CREATE TABLE public.scrobble_queue ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + play_event_id uuid NOT NULL, + status text NOT NULL, + attempts integer DEFAULT 0 NOT NULL, + next_attempt_at timestamp with time zone DEFAULT now() NOT NULL, + last_error text, + enqueued_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT scrobble_queue_status_check CHECK ((status = ANY (ARRAY['pending'::text, 'failed'::text]))) +); + +CREATE TABLE public.sessions ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + token_hash bytea NOT NULL, + user_agent text DEFAULT ''::text NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + last_seen_at timestamp with time zone DEFAULT now() NOT NULL, + created_ip text DEFAULT ''::text NOT NULL, + last_ip text DEFAULT ''::text NOT NULL +); + +CREATE TABLE public.skip_events ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + track_id uuid NOT NULL, + session_id uuid NOT NULL, + skipped_at timestamp with time zone NOT NULL, + position_ms integer NOT NULL +); + +CREATE TABLE public.smtp_config ( + id boolean DEFAULT true NOT NULL, + enabled boolean DEFAULT false NOT NULL, + host text DEFAULT ''::text NOT NULL, + port integer DEFAULT 587 NOT NULL, + username text DEFAULT ''::text NOT NULL, + password text DEFAULT ''::text NOT NULL, + from_address text DEFAULT ''::text NOT NULL, + from_name text DEFAULT 'Minstrel'::text NOT NULL, + use_tls boolean DEFAULT true NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT smtp_config_singleton CHECK ((id = true)) +); + +CREATE TABLE public.system_playlist_rotation_state ( + user_id uuid NOT NULL, + playlist_kind text NOT NULL, + played_track_ids uuid[] DEFAULT '{}'::uuid[] NOT NULL, + rotation_started_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.system_playlist_runs ( + user_id uuid NOT NULL, + last_run_at timestamp with time zone, + last_run_date date, + in_flight boolean DEFAULT false NOT NULL, + last_error text +); + +CREATE TABLE public.tag_provider_settings ( + provider_id text NOT NULL, + enabled boolean DEFAULT true NOT NULL, + api_key text, + display_order integer DEFAULT 0 NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.tag_sources_meta ( + id boolean DEFAULT true NOT NULL, + current_version integer DEFAULT 1 NOT NULL, + last_registered_providers_hash text DEFAULT ''::text NOT NULL, + CONSTRAINT tag_sources_meta_singleton CHECK ((id = true)) +); + +CREATE TABLE public.taste_profile_artists ( + user_id uuid NOT NULL, + artist_id uuid NOT NULL, + weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.taste_profile_eras ( + user_id uuid NOT NULL, + era text NOT NULL, + weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.taste_profile_moods ( + user_id uuid NOT NULL, + mood text NOT NULL, + weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.taste_profile_tags ( + user_id uuid NOT NULL, + tag text NOT NULL, + weight double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.taste_tuning ( + singleton boolean DEFAULT true NOT NULL, + half_life_days double precision NOT NULL, + engagement_hard_skip double precision NOT NULL, + engagement_neutral double precision NOT NULL, + engagement_full double precision NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + enriched_tag_scale double precision DEFAULT 0.5 NOT NULL, + era_scale double precision DEFAULT 0.5 NOT NULL, + mood_scale double precision DEFAULT 0.5 NOT NULL, + CONSTRAINT taste_tuning_singleton_check CHECK (singleton) +); + +CREATE TABLE public.track_acoustid_lookups ( + track_id uuid NOT NULL, + state text NOT NULL, + best_score real, + candidates integer DEFAULT 0 NOT NULL, + recording_mbid text, + detail text, + looked_up_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT track_acoustid_lookups_matched_has_mbid CHECK (((state = 'matched'::text) = (recording_mbid IS NOT NULL))), + CONSTRAINT track_acoustid_lookups_state_check CHECK ((state = ANY (ARRAY['matched'::text, 'ambiguous'::text, 'no_match'::text, 'failed'::text]))) +); + +CREATE TABLE public.track_fingerprints ( + track_id uuid NOT NULL, + audio_stream_sha256 bytea, + chromaprint integer[], + fingerprint_version smallint NOT NULL, + computed_at timestamp with time zone DEFAULT now() NOT NULL, + chromaprint_length_sec integer DEFAULT 120 NOT NULL, + CONSTRAINT track_fingerprints_audio_stream_sha256_check CHECK (((audio_stream_sha256 IS NULL) OR (octet_length(audio_stream_sha256) = 32))) +); + +CREATE TABLE public.track_loudness ( + track_id uuid NOT NULL, + integrated_lufs real, + true_peak_dbtp real, + loudness_range_lu real, + block_hist_start smallint, + block_hist integer[], + unreadable boolean DEFAULT false NOT NULL, + analysis_version smallint NOT NULL, + analyzed_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT track_loudness_hist_pair CHECK (((block_hist IS NULL) = (block_hist_start IS NULL))) +); + +CREATE TABLE public.track_similarity ( + track_a_id uuid NOT NULL, + track_b_id uuid NOT NULL, + score double precision NOT NULL, + source text NOT NULL, + fetched_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT track_similarity_check CHECK ((track_a_id <> track_b_id)), + CONSTRAINT track_similarity_source_check CHECK ((source = ANY (ARRAY['listenbrainz'::text, 'musicbrainz_tag'::text, 'user_cooccurrence'::text]))) +); + +CREATE TABLE public.track_similarity_fetches ( + track_id uuid NOT NULL, + fetched_at timestamp with time zone DEFAULT now() NOT NULL, + returned integer NOT NULL +); + +CREATE TABLE public.track_tags ( + track_id uuid NOT NULL, + tag text NOT NULL, + weight double precision DEFAULT 1 NOT NULL +); + +CREATE TABLE public.tracks ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + title text NOT NULL, + album_id uuid NOT NULL, + artist_id uuid NOT NULL, + track_number integer, + disc_number integer, + duration_ms integer NOT NULL, + file_path text NOT NULL, + file_size bigint NOT NULL, + file_format text NOT NULL, + bitrate integer, + mbid text, + genre text, + added_at timestamp with time zone DEFAULT now() NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + tag_source text, + tag_sources_version integer DEFAULT 0 NOT NULL, + tag_read_version smallint DEFAULT 0 NOT NULL, + missing_since timestamp with time zone, + mbid_source text, + song_id uuid, + song_key uuid GENERATED ALWAYS AS (COALESCE(song_id, id)) STORED, + source_verdict text, + source_verdict_at timestamp with time zone, + emptied_at timestamp with time zone, + removed_reason text, + removed_by uuid, + CONSTRAINT tracks_mbid_source_check CHECK ((mbid_source = ANY (ARRAY['tag'::text, 'acoustid'::text]))), + CONSTRAINT tracks_mbid_source_pair CHECK (((mbid IS NULL) = (mbid_source IS NULL))), + CONSTRAINT tracks_removed_only_missing CHECK (((missing_since IS NOT NULL) OR ((removed_reason IS NULL) AND (removed_by IS NULL)))), + CONSTRAINT tracks_removed_reason_check CHECK ((removed_reason = ANY (ARRAY['report'::text, 'duplicate'::text, 'suspect'::text]))), + CONSTRAINT tracks_source_verdict_check CHECK ((source_verdict = ANY (ARRAY['suspect'::text, 'fine'::text]))) +); + +CREATE TABLE public.user_invites ( + token text NOT NULL, + invited_by uuid NOT NULL, + note text, + created_at timestamp with time zone DEFAULT now() NOT NULL, + expires_at timestamp with time zone NOT NULL, + redeemed_at timestamp with time zone, + redeemed_by uuid +); + +CREATE TABLE public.user_normalization_prefs ( + user_id uuid NOT NULL, + mode text DEFAULT 'auto'::text NOT NULL, + target_lufs smallint DEFAULT '-18'::integer NOT NULL, + boost text DEFAULT 'headroom'::text NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT user_normalization_prefs_boost_check CHECK ((boost = ANY (ARRAY['headroom'::text, 'limiter'::text]))), + CONSTRAINT user_normalization_prefs_mode_check CHECK ((mode = ANY (ARRAY['off'::text, 'auto'::text, 'track'::text, 'album'::text]))), + CONSTRAINT user_normalization_prefs_target_lufs_check CHECK ((target_lufs = ANY (ARRAY['-18'::integer, '-16'::integer, '-14'::integer]))) +); + +CREATE TABLE public.user_notification_email_state ( + user_id uuid NOT NULL, + email_group text NOT NULL, + batch_opened_at timestamp with time zone, + last_sent_at timestamp with time zone, + failures integer DEFAULT 0 NOT NULL, + retry_after timestamp with time zone, + CONSTRAINT user_notification_email_state_email_group_check CHECK ((email_group = ANY (ARRAY['batch'::text, 'summary'::text]))) +); + +CREATE TABLE public.user_notification_prefs ( + user_id uuid NOT NULL, + kind text NOT NULL, + inbox boolean NOT NULL, + phone boolean NOT NULL, + email boolean NOT NULL, + updated_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT user_notification_prefs_kind_check CHECK ((kind = ANY (ARRAY['new_music'::text, 'quarantine_flagged'::text, 'scan_failed'::text, 'tracks_missing'::text, 'duplicates_found'::text, 'duplicates_resolved'::text, 'playback_errors'::text]))) +); + +CREATE TABLE public.user_notifications ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + kind text NOT NULL, + payload jsonb DEFAULT '{}'::jsonb NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + read_at timestamp with time zone, + coalesce_key text, + emailed_at timestamp with time zone, + CONSTRAINT user_notifications_kind_check CHECK ((kind = ANY (ARRAY['new_music'::text, 'quarantine_flagged'::text, 'scan_failed'::text, 'tracks_missing'::text, 'duplicates_found'::text, 'duplicates_resolved'::text, 'playback_errors'::text]))) +); + +CREATE TABLE public.users ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + username text NOT NULL, + password_hash text NOT NULL, + is_admin boolean DEFAULT false NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + subsonic_password text, + listenbrainz_token text, + listenbrainz_enabled boolean DEFAULT false NOT NULL, + display_name text, + email text, + timezone text DEFAULT 'UTC'::text NOT NULL, + timezone_updated_at timestamp with time zone, + debug_mode_enabled boolean DEFAULT false NOT NULL, + api_token_hash text NOT NULL +); + +CREATE TABLE public.you_might_like_albums ( + user_id uuid NOT NULL, + album_id uuid NOT NULL, + rank integer NOT NULL, + built_at timestamp with time zone DEFAULT now() NOT NULL +); + +CREATE TABLE public.you_might_like_artists ( + user_id uuid NOT NULL, + artist_id uuid NOT NULL, + rank integer NOT NULL, + built_at timestamp with time zone DEFAULT now() NOT NULL +); + +ALTER TABLE ONLY public.library_changes ALTER COLUMN id SET DEFAULT nextval('public.library_changes_id_seq'::regclass); + +ALTER TABLE ONLY public.recommendation_tuning_audit ALTER COLUMN id SET DEFAULT nextval('public.recommendation_tuning_audit_id_seq'::regclass); + +INSERT INTO public.acoustid_settings (id, enabled, api_key, min_score, updated_at) VALUES (true, false, NULL, 0.85, now()); + +INSERT INTO public.backup_settings (id, enabled, destination, folder, endpoint, bucket, access_key, secret_key, run_hour, upload_limit_kib, updated_at, include_music) VALUES (true, false, 's3', '', '', '', '', '', 3, 4096, now(), false); + +INSERT INTO public.cover_art_provider_settings (provider_id, enabled, api_key, display_order, created_at, updated_at) VALUES ('mbcaa', true, NULL, 0, now(), now()); +INSERT INTO public.cover_art_provider_settings (provider_id, enabled, api_key, display_order, created_at, updated_at) VALUES ('theaudiodb', true, NULL, 1, now(), now()); + +INSERT INTO public.cover_art_sources_meta (id, current_version, last_registered_providers_hash) VALUES (true, 1, ''); + +INSERT INTO public.fingerprint_settings (id, enabled, chromaprint_length_sec, acoustic_max_bit_error_rate, backfill_concurrency, sweep_interval_hours, updated_at, auto_resolve) VALUES (true, true, 120, 0.15, 2, 1, now(), true); + +INSERT INTO public.library_changes_trimmed (id, through) VALUES (true, 0); + +INSERT INTO public.library_settings (id, scan_paths, updated_at) VALUES (true, NULL, now()); + +INSERT INTO public.loudness_settings (id, enabled, backfill_concurrency, updated_at, leveled_cache_mb) VALUES (true, true, 2, now(), 2048); + +INSERT INTO public.network_settings (id, trusted_proxy_hops, public_url) VALUES (true, 1, ''); + +INSERT INTO public.notification_email_settings (id, summary_hour, batch_window_minutes, updated_at) VALUES (true, 9, 60, now()); + +INSERT INTO public.registration_settings (id, mode) VALUES (true, 'invite_only'); + +INSERT INTO public.smtp_config (id, enabled, host, port, username, password, from_address, from_name, use_tls, updated_at) VALUES (true, false, '', 587, '', '', '', 'Minstrel', true, now()); + +INSERT INTO public.tag_provider_settings (provider_id, enabled, api_key, display_order, created_at, updated_at) VALUES ('musicbrainz', true, NULL, 0, now(), now()); +INSERT INTO public.tag_provider_settings (provider_id, enabled, api_key, display_order, created_at, updated_at) VALUES ('lastfm', false, NULL, 1, now(), now()); + +INSERT INTO public.tag_sources_meta (id, current_version, last_registered_providers_hash) VALUES (true, 1, ''); + +SELECT pg_catalog.setval('public.library_changes_id_seq', 1, false); + +SELECT pg_catalog.setval('public.recommendation_tuning_audit_id_seq', 1, false); + +ALTER TABLE ONLY public.acoustid_settings + ADD CONSTRAINT acoustid_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.album_loudness + ADD CONSTRAINT album_loudness_pkey PRIMARY KEY (album_id); + +ALTER TABLE ONLY public.albums + ADD CONSTRAINT albums_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.artist_similarity_fetches + ADD CONSTRAINT artist_similarity_fetches_pkey PRIMARY KEY (artist_id); + +ALTER TABLE ONLY public.artist_similarity + ADD CONSTRAINT artist_similarity_pkey PRIMARY KEY (artist_a_id, artist_b_id, source); + +ALTER TABLE ONLY public.artists + ADD CONSTRAINT artists_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.audit_log + ADD CONSTRAINT audit_log_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.backup_music_files + ADD CONSTRAINT backup_music_files_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.backup_runs + ADD CONSTRAINT backup_runs_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.backup_settings + ADD CONSTRAINT backup_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.contextual_likes + ADD CONSTRAINT contextual_likes_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.cover_art_provider_settings + ADD CONSTRAINT cover_art_provider_settings_pkey PRIMARY KEY (provider_id); + +ALTER TABLE ONLY public.cover_art_sources_meta + ADD CONSTRAINT cover_art_sources_meta_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.diagnostic_events + ADD CONSTRAINT diagnostic_events_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.duplicate_group_members + ADD CONSTRAINT duplicate_group_members_pkey PRIMARY KEY (group_id, track_id); + +ALTER TABLE ONLY public.duplicate_groups + ADD CONSTRAINT duplicate_groups_member_key_key UNIQUE (member_key); + +ALTER TABLE ONLY public.duplicate_groups + ADD CONSTRAINT duplicate_groups_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.duplicate_sweeps + ADD CONSTRAINT duplicate_sweeps_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.fingerprint_settings + ADD CONSTRAINT fingerprint_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.general_likes_albums + ADD CONSTRAINT general_likes_albums_pkey PRIMARY KEY (user_id, album_id); + +ALTER TABLE ONLY public.general_likes_artists + ADD CONSTRAINT general_likes_artists_pkey PRIMARY KEY (user_id, artist_id); + +ALTER TABLE ONLY public.general_likes + ADD CONSTRAINT general_likes_pkey PRIMARY KEY (user_id, track_id); + +ALTER TABLE ONLY public.library_changes + ADD CONSTRAINT library_changes_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.library_changes_trimmed + ADD CONSTRAINT library_changes_trimmed_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.library_settings + ADD CONSTRAINT library_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.listenbrainz_similar_recordings + ADD CONSTRAINT listenbrainz_similar_recordings_pkey PRIMARY KEY (seed_track_id, recording_mbid); + +ALTER TABLE ONLY public.loudness_settings + ADD CONSTRAINT loudness_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.mb_release_groups + ADD CONSTRAINT mb_release_groups_pkey PRIMARY KEY (mbid); + +ALTER TABLE ONLY public.mb_release_tracks + ADD CONSTRAINT mb_release_tracks_pkey PRIMARY KEY (release_mbid, medium_position, "position"); + +ALTER TABLE ONLY public.mb_releases + ADD CONSTRAINT mb_releases_pkey PRIMARY KEY (mbid); + +ALTER TABLE ONLY public.network_settings + ADD CONSTRAINT network_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.notification_email_settings + ADD CONSTRAINT notification_email_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.password_resets + ADD CONSTRAINT password_resets_pkey PRIMARY KEY (token); + +ALTER TABLE ONLY public.play_events + ADD CONSTRAINT play_events_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.play_sessions + ADD CONSTRAINT play_sessions_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.playback_errors + ADD CONSTRAINT playback_errors_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.playlist_tracks + ADD CONSTRAINT playlist_tracks_pkey PRIMARY KEY (playlist_id, "position"); + +ALTER TABLE ONLY public.playlists + ADD CONSTRAINT playlists_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.quarantine_actions + ADD CONSTRAINT quarantine_actions_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.quarantine + ADD CONSTRAINT quarantine_pkey PRIMARY KEY (user_id, track_id); + +ALTER TABLE ONLY public.recommendation_tuning_audit + ADD CONSTRAINT recommendation_tuning_audit_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.recommendation_weight_profiles + ADD CONSTRAINT recommendation_weight_profiles_pkey PRIMARY KEY (profile); + +ALTER TABLE ONLY public.registration_settings + ADD CONSTRAINT registration_settings_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.scan_runs + ADD CONSTRAINT scan_runs_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.scrobble_queue + ADD CONSTRAINT scrobble_queue_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.scrobble_queue + ADD CONSTRAINT scrobble_queue_play_event_id_key UNIQUE (play_event_id); + +ALTER TABLE ONLY public.sessions + ADD CONSTRAINT sessions_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.sessions + ADD CONSTRAINT sessions_token_hash_key UNIQUE (token_hash); + +ALTER TABLE ONLY public.skip_events + ADD CONSTRAINT skip_events_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.smtp_config + ADD CONSTRAINT smtp_config_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.system_playlist_rotation_state + ADD CONSTRAINT system_playlist_rotation_state_pkey PRIMARY KEY (user_id, playlist_kind); + +ALTER TABLE ONLY public.system_playlist_runs + ADD CONSTRAINT system_playlist_runs_pkey PRIMARY KEY (user_id); + +ALTER TABLE ONLY public.tag_provider_settings + ADD CONSTRAINT tag_provider_settings_pkey PRIMARY KEY (provider_id); + +ALTER TABLE ONLY public.tag_sources_meta + ADD CONSTRAINT tag_sources_meta_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.taste_profile_artists + ADD CONSTRAINT taste_profile_artists_pkey PRIMARY KEY (user_id, artist_id); + +ALTER TABLE ONLY public.taste_profile_eras + ADD CONSTRAINT taste_profile_eras_pkey PRIMARY KEY (user_id, era); + +ALTER TABLE ONLY public.taste_profile_moods + ADD CONSTRAINT taste_profile_moods_pkey PRIMARY KEY (user_id, mood); + +ALTER TABLE ONLY public.taste_profile_tags + ADD CONSTRAINT taste_profile_tags_pkey PRIMARY KEY (user_id, tag); + +ALTER TABLE ONLY public.taste_tuning + ADD CONSTRAINT taste_tuning_pkey PRIMARY KEY (singleton); + +ALTER TABLE ONLY public.track_acoustid_lookups + ADD CONSTRAINT track_acoustid_lookups_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.track_fingerprints + ADD CONSTRAINT track_fingerprints_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.track_loudness + ADD CONSTRAINT track_loudness_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.track_similarity_fetches + ADD CONSTRAINT track_similarity_fetches_pkey PRIMARY KEY (track_id); + +ALTER TABLE ONLY public.track_similarity + ADD CONSTRAINT track_similarity_pkey PRIMARY KEY (track_a_id, track_b_id, source); + +ALTER TABLE ONLY public.track_tags + ADD CONSTRAINT track_tags_pkey PRIMARY KEY (track_id, tag); + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_file_path_key UNIQUE (file_path); + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.user_invites + ADD CONSTRAINT user_invites_pkey PRIMARY KEY (token); + +ALTER TABLE ONLY public.user_normalization_prefs + ADD CONSTRAINT user_normalization_prefs_pkey PRIMARY KEY (user_id); + +ALTER TABLE ONLY public.user_notification_email_state + ADD CONSTRAINT user_notification_email_state_pkey PRIMARY KEY (user_id, email_group); + +ALTER TABLE ONLY public.user_notification_prefs + ADD CONSTRAINT user_notification_prefs_pkey PRIMARY KEY (user_id, kind); + +ALTER TABLE ONLY public.user_notifications + ADD CONSTRAINT user_notifications_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_api_token_hash_key UNIQUE (api_token_hash); + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY public.users + ADD CONSTRAINT users_username_key UNIQUE (username); + +ALTER TABLE ONLY public.you_might_like_albums + ADD CONSTRAINT you_might_like_albums_pkey PRIMARY KEY (user_id, album_id); + +ALTER TABLE ONLY public.you_might_like_artists + ADD CONSTRAINT you_might_like_artists_pkey PRIMARY KEY (user_id, artist_id); + +CREATE INDEX albums_artist ON public.albums USING btree (artist_id); + +CREATE INDEX albums_cover_art_source_idx ON public.albums USING btree (cover_art_source); + +CREATE UNIQUE INDEX albums_mbid_unique ON public.albums USING btree (mbid) WHERE (mbid IS NOT NULL); + +CREATE INDEX albums_release_group_mbid_idx ON public.albums USING btree (release_group_mbid) WHERE (release_group_mbid IS NOT NULL); + +CREATE INDEX albums_sort_title ON public.albums USING btree (sort_title); + +CREATE INDEX artist_similarity_a_score_idx ON public.artist_similarity USING btree (artist_a_id, score DESC); + +CREATE INDEX artists_artist_art_source_idx ON public.artists USING btree (artist_art_source); + +CREATE UNIQUE INDEX artists_mbid_unique ON public.artists USING btree (mbid) WHERE (mbid IS NOT NULL); + +CREATE INDEX artists_sort_name ON public.artists USING btree (sort_name); + +CREATE INDEX audit_log_actor_id_idx ON public.audit_log USING btree (actor_id); + +CREATE INDEX audit_log_created_at_idx ON public.audit_log USING btree (created_at DESC); + +CREATE INDEX audit_log_target_id_idx ON public.audit_log USING btree (target_id); + +CREATE INDEX backup_runs_started_at_idx ON public.backup_runs USING btree (started_at DESC); + +CREATE INDEX contextual_likes_active_idx ON public.contextual_likes USING btree (user_id, track_id) WHERE (deleted_at IS NULL); + +CREATE INDEX contextual_likes_vector_idx ON public.contextual_likes USING gin (session_vector); + +CREATE INDEX duplicate_group_members_track_idx ON public.duplicate_group_members USING btree (track_id); + +CREATE INDEX duplicate_groups_status_idx ON public.duplicate_groups USING btree (status); + +CREATE INDEX duplicate_sweeps_started_at_idx ON public.duplicate_sweeps USING btree (started_at DESC); + +CREATE INDEX general_likes_albums_user_liked_at_idx ON public.general_likes_albums USING btree (user_id, liked_at DESC); + +CREATE INDEX general_likes_artists_user_liked_at_idx ON public.general_likes_artists USING btree (user_id, liked_at DESC); + +CREATE INDEX general_likes_user_liked_at_idx ON public.general_likes USING btree (user_id, liked_at DESC); + +CREATE INDEX idx_diagnostic_events_client ON public.diagnostic_events USING btree (client_id, occurred_at DESC); + +CREATE INDEX idx_diagnostic_events_received ON public.diagnostic_events USING btree (received_at); + +CREATE INDEX idx_diagnostic_events_user ON public.diagnostic_events USING btree (user_id, occurred_at DESC); + +CREATE INDEX idx_library_changes_entity ON public.library_changes USING btree (entity_type, entity_id, id DESC); + +CREATE INDEX idx_library_changes_id ON public.library_changes USING btree (id); + +CREATE INDEX idx_playback_errors_track ON public.playback_errors USING btree (track_id); + +CREATE INDEX idx_playback_errors_unresolved ON public.playback_errors USING btree (occurred_at DESC) WHERE (resolved_at IS NULL); + +CREATE INDEX listenbrainz_similar_recordings_mbid_idx ON public.listenbrainz_similar_recordings USING btree (recording_mbid); + +CREATE INDEX mb_release_tracks_recording_idx ON public.mb_release_tracks USING btree (recording_mbid) WHERE (recording_mbid <> ''::text); + +CREATE INDEX mb_releases_group_idx ON public.mb_releases USING btree (release_group_mbid); + +CREATE INDEX password_resets_active_idx ON public.password_resets USING btree (expires_at) WHERE (used_at IS NULL); + +CREATE INDEX password_resets_user_id_idx ON public.password_resets USING btree (user_id); + +CREATE INDEX play_events_started_idx ON public.play_events USING btree (started_at); + +CREATE INDEX play_events_track_idx ON public.play_events USING btree (track_id); + +CREATE INDEX play_events_user_started_idx ON public.play_events USING btree (user_id, started_at DESC); + +CREATE INDEX play_events_user_track_idx ON public.play_events USING btree (user_id, track_id); + +CREATE INDEX play_sessions_user_last_event_idx ON public.play_sessions USING btree (user_id, last_event_at DESC); + +CREATE INDEX playlist_tracks_track_idx ON public.playlist_tracks USING btree (track_id) WHERE (track_id IS NOT NULL); + +CREATE INDEX playlists_public_idx ON public.playlists USING btree (is_public, updated_at DESC) WHERE is_public; + +CREATE INDEX playlists_user_idx ON public.playlists USING btree (user_id, updated_at DESC); + +CREATE INDEX playlists_user_kind_idx ON public.playlists USING btree (user_id, kind); + +CREATE INDEX quarantine_actions_created_idx ON public.quarantine_actions USING btree (created_at DESC); + +CREATE INDEX quarantine_actions_track_idx ON public.quarantine_actions USING btree (track_id); + +CREATE INDEX quarantine_track_idx ON public.quarantine USING btree (track_id); + +CREATE INDEX recommendation_tuning_audit_changed_at_idx ON public.recommendation_tuning_audit USING btree (changed_at DESC); + +CREATE INDEX scan_runs_started_at_idx ON public.scan_runs USING btree (started_at DESC); + +CREATE INDEX scrobble_queue_pending_idx ON public.scrobble_queue USING btree (next_attempt_at) WHERE (status = 'pending'::text); + +CREATE INDEX sessions_user_id_idx ON public.sessions USING btree (user_id); + +CREATE INDEX skip_events_user_skipped_idx ON public.skip_events USING btree (user_id, skipped_at DESC); + +CREATE INDEX taste_profile_artists_user_weight_idx ON public.taste_profile_artists USING btree (user_id, weight DESC); + +CREATE INDEX taste_profile_eras_user_weight_idx ON public.taste_profile_eras USING btree (user_id, weight DESC); + +CREATE INDEX taste_profile_moods_user_weight_idx ON public.taste_profile_moods USING btree (user_id, weight DESC); + +CREATE INDEX taste_profile_tags_user_weight_idx ON public.taste_profile_tags USING btree (user_id, weight DESC); + +CREATE INDEX track_acoustid_lookups_state ON public.track_acoustid_lookups USING btree (state); + +CREATE INDEX track_fingerprints_audio_stream_sha256 ON public.track_fingerprints USING btree (audio_stream_sha256) WHERE (audio_stream_sha256 IS NOT NULL); + +CREATE INDEX track_similarity_a_score_idx ON public.track_similarity USING btree (track_a_id, score DESC); + +CREATE INDEX track_tags_track_idx ON public.track_tags USING btree (track_id); + +CREATE INDEX tracks_album ON public.tracks USING btree (album_id, disc_number, track_number); + +CREATE INDEX tracks_artist ON public.tracks USING btree (artist_id); + +CREATE INDEX tracks_duration_id_idx ON public.tracks USING btree (duration_ms, id); + +CREATE INDEX tracks_mbid_idx ON public.tracks USING btree (mbid) WHERE (mbid IS NOT NULL); + +CREATE INDEX tracks_missing_since_idx ON public.tracks USING btree (missing_since) WHERE (missing_since IS NOT NULL); + +CREATE INDEX tracks_song_key_idx ON public.tracks USING btree (song_key); + +CREATE INDEX tracks_source_suspect_idx ON public.tracks USING btree (id) WHERE (source_verdict = 'suspect'::text); + +CREATE INDEX tracks_tag_source_idx ON public.tracks USING btree (tag_source, tag_sources_version); + +CREATE INDEX user_invites_active_idx ON public.user_invites USING btree (expires_at) WHERE (redeemed_at IS NULL); + +CREATE UNIQUE INDEX user_notifications_coalesce_idx ON public.user_notifications USING btree (user_id, coalesce_key) WHERE ((read_at IS NULL) AND (coalesce_key IS NOT NULL)); + +CREATE INDEX user_notifications_email_pending_idx ON public.user_notifications USING btree (user_id, created_at) WHERE ((read_at IS NULL) AND (emailed_at IS NULL)); + +CREATE INDEX user_notifications_unread_idx ON public.user_notifications USING btree (user_id, created_at DESC) WHERE (read_at IS NULL); + +CREATE INDEX user_notifications_user_created_idx ON public.user_notifications USING btree (user_id, created_at DESC); + +CREATE UNIQUE INDEX users_email_unique ON public.users USING btree (lower(email)) WHERE (email IS NOT NULL); + +CREATE INDEX you_might_like_albums_user_rank_idx ON public.you_might_like_albums USING btree (user_id, rank); + +CREATE INDEX you_might_like_artists_user_rank_idx ON public.you_might_like_artists USING btree (user_id, rank); + +ALTER TABLE ONLY public.album_loudness + ADD CONSTRAINT album_loudness_album_id_fkey FOREIGN KEY (album_id) REFERENCES public.albums(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.albums + ADD CONSTRAINT albums_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.artist_similarity + ADD CONSTRAINT artist_similarity_artist_a_id_fkey FOREIGN KEY (artist_a_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.artist_similarity + ADD CONSTRAINT artist_similarity_artist_b_id_fkey FOREIGN KEY (artist_b_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.artist_similarity_fetches + ADD CONSTRAINT artist_similarity_fetches_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.audit_log + ADD CONSTRAINT audit_log_actor_id_fkey FOREIGN KEY (actor_id) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.audit_log + ADD CONSTRAINT audit_log_target_id_fkey FOREIGN KEY (target_id) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.backup_music_files + ADD CONSTRAINT backup_music_files_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.contextual_likes + ADD CONSTRAINT contextual_likes_session_id_fkey FOREIGN KEY (session_id) REFERENCES public.play_sessions(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.contextual_likes + ADD CONSTRAINT contextual_likes_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.contextual_likes + ADD CONSTRAINT contextual_likes_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.diagnostic_events + ADD CONSTRAINT diagnostic_events_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.duplicate_group_members + ADD CONSTRAINT duplicate_group_members_group_id_fkey FOREIGN KEY (group_id) REFERENCES public.duplicate_groups(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.duplicate_group_members + ADD CONSTRAINT duplicate_group_members_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.duplicate_groups + ADD CONSTRAINT duplicate_groups_last_seen_sweep_id_fkey FOREIGN KEY (last_seen_sweep_id) REFERENCES public.duplicate_sweeps(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.general_likes_albums + ADD CONSTRAINT general_likes_albums_album_id_fkey FOREIGN KEY (album_id) REFERENCES public.albums(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes_albums + ADD CONSTRAINT general_likes_albums_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes_artists + ADD CONSTRAINT general_likes_artists_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes_artists + ADD CONSTRAINT general_likes_artists_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes + ADD CONSTRAINT general_likes_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.general_likes + ADD CONSTRAINT general_likes_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.listenbrainz_similar_recordings + ADD CONSTRAINT listenbrainz_similar_recordings_seed_track_id_fkey FOREIGN KEY (seed_track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.mb_release_tracks + ADD CONSTRAINT mb_release_tracks_release_mbid_fkey FOREIGN KEY (release_mbid) REFERENCES public.mb_releases(mbid) ON DELETE CASCADE; + +ALTER TABLE ONLY public.mb_releases + ADD CONSTRAINT mb_releases_release_group_mbid_fkey FOREIGN KEY (release_group_mbid) REFERENCES public.mb_release_groups(mbid) ON DELETE CASCADE; + +ALTER TABLE ONLY public.password_resets + ADD CONSTRAINT password_resets_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.play_events + ADD CONSTRAINT play_events_session_id_fkey FOREIGN KEY (session_id) REFERENCES public.play_sessions(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.play_events + ADD CONSTRAINT play_events_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.play_events + ADD CONSTRAINT play_events_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.play_sessions + ADD CONSTRAINT play_sessions_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.playback_errors + ADD CONSTRAINT playback_errors_resolved_by_fkey FOREIGN KEY (resolved_by) REFERENCES public.users(id); + +ALTER TABLE ONLY public.playback_errors + ADD CONSTRAINT playback_errors_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.playback_errors + ADD CONSTRAINT playback_errors_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.playlist_tracks + ADD CONSTRAINT playlist_tracks_playlist_id_fkey FOREIGN KEY (playlist_id) REFERENCES public.playlists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.playlist_tracks + ADD CONSTRAINT playlist_tracks_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.playlists + ADD CONSTRAINT playlists_seed_artist_id_fkey FOREIGN KEY (seed_artist_id) REFERENCES public.artists(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.playlists + ADD CONSTRAINT playlists_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.quarantine_actions + ADD CONSTRAINT quarantine_actions_admin_id_fkey FOREIGN KEY (admin_id) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.quarantine + ADD CONSTRAINT quarantine_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.quarantine + ADD CONSTRAINT quarantine_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.scrobble_queue + ADD CONSTRAINT scrobble_queue_play_event_id_fkey FOREIGN KEY (play_event_id) REFERENCES public.play_events(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.scrobble_queue + ADD CONSTRAINT scrobble_queue_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.sessions + ADD CONSTRAINT sessions_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.skip_events + ADD CONSTRAINT skip_events_session_id_fkey FOREIGN KEY (session_id) REFERENCES public.play_sessions(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.skip_events + ADD CONSTRAINT skip_events_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.skip_events + ADD CONSTRAINT skip_events_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.system_playlist_rotation_state + ADD CONSTRAINT system_playlist_rotation_state_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.system_playlist_runs + ADD CONSTRAINT system_playlist_runs_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_artists + ADD CONSTRAINT taste_profile_artists_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_artists + ADD CONSTRAINT taste_profile_artists_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_eras + ADD CONSTRAINT taste_profile_eras_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_moods + ADD CONSTRAINT taste_profile_moods_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.taste_profile_tags + ADD CONSTRAINT taste_profile_tags_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_acoustid_lookups + ADD CONSTRAINT track_acoustid_lookups_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_fingerprints + ADD CONSTRAINT track_fingerprints_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_loudness + ADD CONSTRAINT track_loudness_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_similarity_fetches + ADD CONSTRAINT track_similarity_fetches_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_similarity + ADD CONSTRAINT track_similarity_track_a_id_fkey FOREIGN KEY (track_a_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_similarity + ADD CONSTRAINT track_similarity_track_b_id_fkey FOREIGN KEY (track_b_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.track_tags + ADD CONSTRAINT track_tags_track_id_fkey FOREIGN KEY (track_id) REFERENCES public.tracks(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_album_id_fkey FOREIGN KEY (album_id) REFERENCES public.albums(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.tracks + ADD CONSTRAINT tracks_removed_by_fkey FOREIGN KEY (removed_by) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.user_invites + ADD CONSTRAINT user_invites_invited_by_fkey FOREIGN KEY (invited_by) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.user_invites + ADD CONSTRAINT user_invites_redeemed_by_fkey FOREIGN KEY (redeemed_by) REFERENCES public.users(id) ON DELETE SET NULL; + +ALTER TABLE ONLY public.user_normalization_prefs + ADD CONSTRAINT user_normalization_prefs_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.user_notification_email_state + ADD CONSTRAINT user_notification_email_state_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.user_notification_prefs + ADD CONSTRAINT user_notification_prefs_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.user_notifications + ADD CONSTRAINT user_notifications_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.you_might_like_albums + ADD CONSTRAINT you_might_like_albums_album_id_fkey FOREIGN KEY (album_id) REFERENCES public.albums(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.you_might_like_albums + ADD CONSTRAINT you_might_like_albums_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.you_might_like_artists + ADD CONSTRAINT you_might_like_artists_artist_id_fkey FOREIGN KEY (artist_id) REFERENCES public.artists(id) ON DELETE CASCADE; + +ALTER TABLE ONLY public.you_might_like_artists + ADD CONSTRAINT you_might_like_artists_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.users(id) ON DELETE CASCADE; diff --git a/internal/db/migrations/0106_playback_error_resolutions.down.sql b/internal/db/migrations/0106_playback_error_resolutions.down.sql deleted file mode 100644 index fc82c544..00000000 --- a/internal/db/migrations/0106_playback_error_resolutions.down.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TYPE request_kind AS ENUM ('artist', 'album', 'track'); -CREATE TYPE request_status AS ENUM ('pending', 'approved', 'rejected', 'completed', 'failed'); - -ALTER TABLE playback_errors - DROP CONSTRAINT playback_errors_resolution_check, - ADD CONSTRAINT playback_errors_resolution_check - CHECK (resolution IS NULL OR resolution IN ('hidden', 'deleted', 'requested', 'fixed', 'ignored')); diff --git a/internal/db/migrations/0106_playback_error_resolutions.up.sql b/internal/db/migrations/0106_playback_error_resolutions.up.sql deleted file mode 100644 index 68a024b3..00000000 --- a/internal/db/migrations/0106_playback_error_resolutions.up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- A playback error is resolved by hiding or deleting the track, or by marking --- it fixed or ignored. Nothing re-requests a track any more, so 'requested' --- is no longer a resolution. -ALTER TABLE playback_errors - DROP CONSTRAINT playback_errors_resolution_check, - ADD CONSTRAINT playback_errors_resolution_check - CHECK (resolution IS NULL OR resolution IN ('hidden', 'deleted', 'fixed', 'ignored')); - --- The enums the requests table used, left behind when it went. -DROP TYPE request_kind; -DROP TYPE request_status; diff --git a/internal/db/queries/acoustid.sql b/internal/db/queries/acoustid.sql index cb677a6c..22a4eca0 100644 --- a/internal/db/queries/acoustid.sql +++ b/internal/db/queries/acoustid.sql @@ -1,5 +1,5 @@ --- AcoustID recording-id lookup. Migration 0069 says what each --- lookup state means. +-- AcoustID recording-id lookup. The CHECK on track_acoustid_lookups.state +-- lists the lookup states. -- name: ListTracksNeedingAcoustIDLookup :many -- The lookup worker's queue: present tracks with no tag MBID and no lookup diff --git a/internal/db/queries/fingerprint_settings.sql b/internal/db/queries/fingerprint_settings.sql index 010f5ff6..cfa698aa 100644 --- a/internal/db/queries/fingerprint_settings.sql +++ b/internal/db/queries/fingerprint_settings.sql @@ -2,7 +2,7 @@ SELECT * FROM fingerprint_settings WHERE id = true; -- name: UpdateFingerprintSettings :one --- Whole-row write from the admin card; migration 0061's CHECKs are the backstop +-- Whole-row write from the admin card; fingerprint_settings's CHECKs are the backstop -- behind the service's own validation. UPDATE fingerprint_settings SET enabled = sqlc.arg(enabled), diff --git a/internal/db/queries/missing_pairs.sql b/internal/db/queries/missing_pairs.sql index f7eec982..c91bc781 100644 --- a/internal/db/queries/missing_pairs.sql +++ b/internal/db/queries/missing_pairs.sql @@ -26,7 +26,7 @@ -- they are different recordings. The caller folds a pair only when each side has -- exactly one candidate; anything else is ambiguous and left alone. -- --- A slot the duplicate resolver emptied (emptied_at, migration 0095) pairs by +-- A slot the duplicate resolver emptied (emptied_at) pairs by -- title only with a track added since: the album held no copy of the song as -- long as it is, so one already there under the title is another song. WITH grp AS ( diff --git a/internal/db/queries/normalization_prefs.sql b/internal/db/queries/normalization_prefs.sql index ebe3eb30..599f9d28 100644 --- a/internal/db/queries/normalization_prefs.sql +++ b/internal/db/queries/normalization_prefs.sql @@ -4,7 +4,7 @@ SELECT mode, target_lufs, boost, updated_at WHERE user_id = $1; -- name: UpsertNormalizationPrefs :one --- Whole-row write from either client; the CHECKs in migration 0067 back the +-- Whole-row write from either client; the CHECKs on user_normalization_prefs back the -- handler's own validation. INSERT INTO user_normalization_prefs (user_id, mode, target_lufs, boost) VALUES (sqlc.arg(user_id), sqlc.arg(mode), sqlc.arg(target_lufs), sqlc.arg(boost)) diff --git a/internal/db/queries/notifications.sql b/internal/db/queries/notifications.sql index cfac0ea7..a79a949a 100644 --- a/internal/db/queries/notifications.sql +++ b/internal/db/queries/notifications.sql @@ -154,7 +154,7 @@ ON CONFLICT (user_id, email_group) DO UPDATE SET SELECT * FROM notification_email_settings WHERE id = true; -- name: UpdateNotificationEmailSettings :one --- Migration 0074's CHECKs are the backstop behind the service's validation. +-- notification_email_settings's CHECKs are the backstop behind the service's validation. UPDATE notification_email_settings SET summary_hour = sqlc.arg(summary_hour), batch_window_minutes = sqlc.arg(batch_window_minutes), diff --git a/internal/db/queries/songs.sql b/internal/db/queries/songs.sql index 5095c918..103f0f9e 100644 --- a/internal/db/queries/songs.sql +++ b/internal/db/queries/songs.sql @@ -1,5 +1,5 @@ -- Song links: copies of one song on different releases share a --- song_key (migration 0076). +-- song_key. -- name: LinkTracksAsSong :one -- Links the tracks into one song, joining any songs they already belong to. diff --git a/internal/db/queries/tracks.sql b/internal/db/queries/tracks.sql index ac3d1813..2c585858 100644 --- a/internal/db/queries/tracks.sql +++ b/internal/db/queries/tracks.sql @@ -243,7 +243,7 @@ UPDATE tracks -- name: MarkTracksEmptied :exec -- Stamps rows the duplicate resolver emptied, whose song the album holds no --- other copy of, with the time they went missing (migration 0095): missing-pair +-- other copy of, with the time they went missing (emptied_at): missing-pair -- folding then waits for a copy fetched again. UPDATE tracks SET emptied_at = missing_since diff --git a/internal/db/queries/users.sql b/internal/db/queries/users.sql index 4e956f37..1c1bb2b6 100644 --- a/internal/db/queries/users.sql +++ b/internal/db/queries/users.sql @@ -36,7 +36,7 @@ SELECT count(*) FROM users; -- name: SetSubsonicPassword :exec -- Stores (or clears with NULL) the per-user Subsonic legacy credential used --- for t/s and p auth on /rest/*. Must be plaintext; see migration 0003. Only +-- for t/s and p auth on /rest/*. Must be plaintext: t/s auth hashes it with a salt. Only -- ever a server-generated value, never the login password. UPDATE users SET subsonic_password = $2 WHERE id = $1; diff --git a/internal/dbtest/reset.go b/internal/dbtest/reset.go index 02e2ada6..abef12db 100644 --- a/internal/dbtest/reset.go +++ b/internal/dbtest/reset.go @@ -69,7 +69,7 @@ var dataTables = []string{ // for every registered provider at boot, so truncating this is the // correct per-test reset (clears test-modified enabled/api_key rows). // cover_art_sources_meta is NOT truncated — boot only READS it - // (never recreates the singleton, seeded once by 0018); ResetDB + // (never recreates the singleton, seeded once by the schema); ResetDB // resets its counter via UPDATE below instead. "cover_art_provider_settings", // Same reasoning for the tag-enrichment settings: truncate the diff --git a/internal/library/acoustid_lookup.go b/internal/library/acoustid_lookup.go index ce881a0f..2f896ff0 100644 --- a/internal/library/acoustid_lookup.go +++ b/internal/library/acoustid_lookup.go @@ -49,7 +49,7 @@ const acoustIDLookupConcurrency = 2 // silence; a radio edit or a live take differs by far more. const acoustIDDurationToleranceSec = 3 -// Lookup states, as migration 0069's CHECK has them. +// Lookup states, as the CHECK on track_acoustid_lookups.state has them. const ( lookupMatched = "matched" lookupAmbiguous = "ambiguous" diff --git a/internal/library/acoustid_settings.go b/internal/library/acoustid_settings.go index 27e8d963..e9cf2128 100644 --- a/internal/library/acoustid_settings.go +++ b/internal/library/acoustid_settings.go @@ -31,10 +31,10 @@ type AcoustIDSettings struct { // Ready reports whether the worker may call AcoustID at all. func (s AcoustIDSettings) Ready() bool { return s.Enabled && s.APIKey != "" } -// DefaultAcoustIDSettings mirrors migration 0069's defaults: off, no key. +// DefaultAcoustIDSettings mirrors acoustid_settings's defaults: off, no key. var DefaultAcoustIDSettings = AcoustIDSettings{MinScore: 0.85} -// The score threshold's bounds, as migration 0069's CHECK has them. Below 0.5 +// The score threshold's bounds, as acoustid_settings's CHECK has them. Below 0.5 // AcoustID's own docs call a match doubtful; the floor keeps a typo in the // field from filling the library with guesses. const ( diff --git a/internal/library/fingerprint_settings.go b/internal/library/fingerprint_settings.go index ff13c24b..9bb3a08c 100644 --- a/internal/library/fingerprint_settings.go +++ b/internal/library/fingerprint_settings.go @@ -20,13 +20,13 @@ import ( // // The length is the dangerous knob: chromaprints taken at two lengths cannot be // compared. Rather than bumping fingerprintVersion when it changes, every row -// records the length it was taken at (migration 0061) and every reader filters -// on the current one. A row at another length is stale to the backfill, pending +// records the length it was taken at (track_fingerprints.chromaprint_length_sec) +// and every reader filters on the current one. A row at another length is stale to the backfill, pending // to the gauge and invisible to the sweep, which is the effect a version bump // would have, with one difference worth having: setting the length back makes // rows not yet re-derived current again, instead of redoing the library twice. -// Bounds for each setting, mirrored by migration 0061's CHECKs. +// Bounds for each setting, mirrored by fingerprint_settings's CHECKs. const ( // Below 30s a print has too few items to align at the matcher's larger // offsets and still overlap by minOverlapItems. Above 600s each print @@ -65,7 +65,7 @@ type FingerprintSettings struct { UpdatedAt time.Time } -// DefaultFingerprintSettings mirrors migration 0061's column defaults, so a +// DefaultFingerprintSettings mirrors fingerprint_settings's column defaults, so a // database that cannot be read still fingerprints the way a fresh install does. var DefaultFingerprintSettings = FingerprintSettings{ Enabled: true, diff --git a/internal/library/fingerprint_settings_test.go b/internal/library/fingerprint_settings_test.go index d77b9b59..4a517641 100644 --- a/internal/library/fingerprint_settings_test.go +++ b/internal/library/fingerprint_settings_test.go @@ -84,7 +84,7 @@ func TestFingerprintSettingsService_Integration(t *testing.T) { t.Fatalf("load: %v", err) } // ResetDB puts every column back to its migration default, so this pins the - // Go defaults to migration 0061's. Were they to drift, a database that + // Go defaults to fingerprint_settings's. Were they to drift, a database that // could not be read would fingerprint differently from one that could. loaded := svc.Get() if loaded.UpdatedAt.IsZero() { diff --git a/internal/library/loudness_settings.go b/internal/library/loudness_settings.go index 21fe1bad..f14c29cc 100644 --- a/internal/library/loudness_settings.go +++ b/internal/library/loudness_settings.go @@ -29,7 +29,7 @@ type LoudnessSettings struct { UpdatedAt time.Time } -// DefaultLoudnessSettings mirrors migrations 0065 and 0068's column defaults, +// DefaultLoudnessSettings mirrors loudness_settings's column defaults, // so a database that cannot be read still analyzes the way a fresh install // does. var DefaultLoudnessSettings = LoudnessSettings{ @@ -38,14 +38,14 @@ var DefaultLoudnessSettings = LoudnessSettings{ LeveledCacheMB: 2048, } -// The leveled-stream cache's bounds, as migration 0068's CHECK has them. +// The leveled-stream cache's bounds, as loudness_settings's CHECK has them. const ( minLeveledCacheMB = 256 maxLeveledCacheMB = 65536 ) -// ErrLoudnessSettingOutOfRange is returned by Set for a value migration 0065's -// CHECK would reject, so the API answers 400 naming the field. +// ErrLoudnessSettingOutOfRange is returned by Set for a value loudness_settings's +// CHECKs would reject, so the API answers 400 naming the field. var ErrLoudnessSettingOutOfRange = errors.New("loudness setting out of range") // LoudnessSettingsService caches the settings and owns their persistence. diff --git a/internal/library/normalization_prefs.go b/internal/library/normalization_prefs.go index 2a1b1585..1686e94b 100644 --- a/internal/library/normalization_prefs.go +++ b/internal/library/normalization_prefs.go @@ -26,7 +26,7 @@ type NormalizationPrefs struct { Boost string `json:"boost"` } -// The accepted values. Migration 0067's CHECKs hold the same lists. +// The accepted values. user_normalization_prefs's CHECKs hold the same lists. var ( NormalizationModes = []string{"off", "auto", "track", "album"} NormalizationTargets = []int16{-18, -16, -14} @@ -34,7 +34,7 @@ var ( ) // DefaultNormalizationPrefs applies to a user who has never chosen. It must -// equal migration 0067's column defaults; a test holds them together. +// equal user_normalization_prefs's column defaults; a test holds them together. var DefaultNormalizationPrefs = NormalizationPrefs{Mode: "auto", TargetLUFS: -18, Boost: "headroom"} // ErrNormalizationPrefsInvalid is returned for a value outside the lists. diff --git a/internal/library/scanner.go b/internal/library/scanner.go index 10ac9dd7..3cee17d5 100644 --- a/internal/library/scanner.go +++ b/internal/library/scanner.go @@ -42,7 +42,7 @@ var audioExtensions = map[string]bool{ // tagReadVersion is the version of this package's tag-extraction logic. Rows // whose tracks.tag_read_version is lower get their tags re-read on the next // scan even when the file itself hasn't changed, so a fix reaches an existing -// library without anyone rebuilding it (migration 0054). +// library without anyone rebuilding it. // // Bump this whenever a change to tag extraction should reach already-indexed // files, and say why below. diff --git a/internal/netsettings/service.go b/internal/netsettings/service.go index 8fe4d31a..abae69f9 100644 --- a/internal/netsettings/service.go +++ b/internal/netsettings/service.go @@ -22,11 +22,11 @@ import ( ) const ( - // DefaultTrustedProxyHops mirrors migration 0053's column default. One + // DefaultTrustedProxyHops mirrors network_settings's column default. One // proxy, because anything publicly reachable needs a TLS terminator in // front of it. DefaultTrustedProxyHops = 1 - // MaxTrustedProxyHops mirrors the CHECK in migration 0053. + // MaxTrustedProxyHops mirrors network_settings's CHECK. MaxTrustedProxyHops = 10 ) diff --git a/internal/notifications/email_settings.go b/internal/notifications/email_settings.go index 52cafe00..9d95587a 100644 --- a/internal/notifications/email_settings.go +++ b/internal/notifications/email_settings.go @@ -23,10 +23,10 @@ const ( maxBatchWindowMinutes = 1440 ) -// DefaultEmailSettings mirrors migration 0074's column defaults. +// DefaultEmailSettings mirrors notification_email_settings's column defaults. var DefaultEmailSettings = EmailSettings{SummaryHour: 9, BatchWindowMinutes: 60} -// ErrEmailSettingOutOfRange is a value migration 0074's CHECKs would reject, +// ErrEmailSettingOutOfRange is a value notification_email_settings's CHECKs would reject, // so the API answers 400 naming the field rather than a constraint violation. var ErrEmailSettingOutOfRange = errors.New("notification email setting out of range") diff --git a/internal/playlists/system.go b/internal/playlists/system.go index 38879166..98373d9b 100644 --- a/internal/playlists/system.go +++ b/internal/playlists/system.go @@ -132,7 +132,7 @@ type rankedCandidate struct { // Pick kinds, persisted on playlist_tracks.pick_kind so plays can // attribute skips to the population that sourced the track — For You's // "taste engine missing" vs "freshness tax", Discover's three buckets -// Values mirror the CHECK in migration 0041; taste_unheard is Discover's +// Values mirror the CHECK on playlist_tracks.pick_kind; taste_unheard is Discover's // taste-targeted-novelty arm. const ( pickKindTaste = "taste" diff --git a/internal/sync/types.go b/internal/sync/types.go index 1865caa4..4f507768 100644 --- a/internal/sync/types.go +++ b/internal/sync/types.go @@ -9,7 +9,7 @@ package sync // EntityType enumerates the entity kinds whose mutations are tracked // by the library_changes log. Values must stay in sync with the CHECK -// constraint on library_changes.entity_type (migration 0025). +// constraint on library_changes.entity_type. type EntityType string const ( @@ -23,7 +23,7 @@ const ( EntityPlaylistTrack EntityType = "playlist_track" ) -// Op is upsert or delete. Matches the CHECK constraint in migration 0025. +// Op is upsert or delete. Matches the CHECK constraint on library_changes.op. type Op string const (