feat: Minstrel stops acquiring music and drops Discover
release / go (push) Successful in 1m54s
release / web (push) Failing after 5s
release / integration (push) Failing after 3m44s
release / govulncheck (push) Successful in 20s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 19s
release / android (push) Canceled after 2m37s

Minstrel is now a viewer of the library it is pointed at. Finding,
downloading and filing music moves out of it.

Removed from the server:
- the request flow (requests, approval, auto-approve) and the wanted list,
  follows, release profiles and release blocks;
- searching indexers, the download clients, the importer, the album
  lifecycle and missing-file re-acquisition;
- the catalogue's discography, search and art (the MusicBrainz release and
  track-list cache stays, for the duplicate resolver);
- Discover: its suggestions of artists not in the library, snoozes, the
  candidate-artist tag enrichment and its tuning scope;
- writes to acquisition tables from moving the library folder and from
  merging duplicates, the want-list join on Suspect sources, the sealing of
  acquisition credentials, and the release-group lookup only
  re-acquisition used.

Settling a wrong-slot duplicate no longer sets the release aside: the
copies go and their slots show as missing until a good copy is in the
library.

Removed from the web: Admin > Acquisition and Requests, /requests,
/discover, Follow on the artist page, the auto-approve toggle, and the
Collection's wanted-list tabs. The Collection is now the library's health:
an overview, Reports, Duplicates, Suspect sources and Missing files. The
README and docs no longer describe getting music.

The tables stay for now; a later migration drops them. The request
notification kinds and the Android screens are still to go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 20:51:14 -05:00
co-authored by Claude Opus 5.5
parent dabe1e052d
commit 55c7497ca7
277 changed files with 521 additions and 40021 deletions
-362
View File
@@ -1,362 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: acquisition.sql
package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const createAcquisitionService = `-- name: CreateAcquisitionService :one
INSERT INTO acquisition_services
(code, kind, protocol, label, category, timeout_ms, searches_per_hour)
VALUES
($1, $2, $3, $4,
$5, $6, $7)
ON CONFLICT (code) DO NOTHING
RETURNING code, kind, protocol, label, enabled, base_url, api_key, username, password, category, timeout_ms, serves_search, serves_downloads, serves_enrichment, local_path, remote_path, searches_per_hour, created_at, updated_at
`
type CreateAcquisitionServiceParams struct {
Code string
Kind string
Protocol string
Label string
Category string
TimeoutMs int32
SearchesPerHour int32
}
// ON CONFLICT so the caller can try the next code when this one is taken.
func (q *Queries) CreateAcquisitionService(ctx context.Context, arg CreateAcquisitionServiceParams) (AcquisitionService, error) {
row := q.db.QueryRow(ctx, createAcquisitionService,
arg.Code,
arg.Kind,
arg.Protocol,
arg.Label,
arg.Category,
arg.TimeoutMs,
arg.SearchesPerHour,
)
var i AcquisitionService
err := row.Scan(
&i.Code,
&i.Kind,
&i.Protocol,
&i.Label,
&i.Enabled,
&i.BaseUrl,
&i.ApiKey,
&i.Username,
&i.Password,
&i.Category,
&i.TimeoutMs,
&i.ServesSearch,
&i.ServesDownloads,
&i.ServesEnrichment,
&i.LocalPath,
&i.RemotePath,
&i.SearchesPerHour,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteAcquisitionService = `-- name: DeleteAcquisitionService :execrows
DELETE FROM acquisition_services WHERE code = $1
`
func (q *Queries) DeleteAcquisitionService(ctx context.Context, code string) (int64, error) {
result, err := q.db.Exec(ctx, deleteAcquisitionService, code)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getAcquisitionService = `-- name: GetAcquisitionService :one
SELECT code, kind, protocol, label, enabled, base_url, api_key, username, password, category, timeout_ms, serves_search, serves_downloads, serves_enrichment, local_path, remote_path, searches_per_hour, created_at, updated_at FROM acquisition_services WHERE code = $1
`
// The full row, credentials included. For building a client, never for a
// response.
func (q *Queries) GetAcquisitionService(ctx context.Context, code string) (AcquisitionService, error) {
row := q.db.QueryRow(ctx, getAcquisitionService, code)
var i AcquisitionService
err := row.Scan(
&i.Code,
&i.Kind,
&i.Protocol,
&i.Label,
&i.Enabled,
&i.BaseUrl,
&i.ApiKey,
&i.Username,
&i.Password,
&i.Category,
&i.TimeoutMs,
&i.ServesSearch,
&i.ServesDownloads,
&i.ServesEnrichment,
&i.LocalPath,
&i.RemotePath,
&i.SearchesPerHour,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const listAcquisitionServices = `-- name: ListAcquisitionServices :many
SELECT code, kind, protocol, label, enabled, base_url,
(api_key <> '')::boolean AS has_api_key,
(password <> '')::boolean AS has_password,
username, category, timeout_ms,
serves_search, serves_downloads, serves_enrichment,
local_path, remote_path, searches_per_hour,
created_at, updated_at
FROM acquisition_services
ORDER BY kind, label, code
`
type ListAcquisitionServicesRow struct {
Code string
Kind string
Protocol string
Label string
Enabled bool
BaseUrl string
HasApiKey bool
HasPassword bool
Username string
Category string
TimeoutMs int32
ServesSearch bool
ServesDownloads bool
ServesEnrichment bool
LocalPath string
RemotePath string
SearchesPerHour int32
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Indexers and download clients.
// Returns no secret, only whether one is set: this feeds the settings page.
func (q *Queries) ListAcquisitionServices(ctx context.Context) ([]ListAcquisitionServicesRow, error) {
rows, err := q.db.Query(ctx, listAcquisitionServices)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAcquisitionServicesRow
for rows.Next() {
var i ListAcquisitionServicesRow
if err := rows.Scan(
&i.Code,
&i.Kind,
&i.Protocol,
&i.Label,
&i.Enabled,
&i.BaseUrl,
&i.HasApiKey,
&i.HasPassword,
&i.Username,
&i.Category,
&i.TimeoutMs,
&i.ServesSearch,
&i.ServesDownloads,
&i.ServesEnrichment,
&i.LocalPath,
&i.RemotePath,
&i.SearchesPerHour,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listUsableAcquisitionServices = `-- name: ListUsableAcquisitionServices :many
SELECT code, kind, protocol, label, enabled, base_url, api_key, username, password, category, timeout_ms, serves_search, serves_downloads, serves_enrichment, local_path, remote_path, searches_per_hour, created_at, updated_at FROM acquisition_services
WHERE enabled AND base_url <> ''
AND CASE WHEN protocol = 'exchange' THEN
CASE $1::text
WHEN 'search' THEN serves_search
WHEN 'download' THEN serves_downloads
WHEN 'enrichment' THEN serves_enrichment
ELSE false
END
ELSE kind = $1::text
END
ORDER BY code
`
// Every enabled, addressed service doing one job. An exchange row does a job
// when its switch for it is on; any other row does the job its kind names.
// Ordered by code so a fan-out is deterministic.
func (q *Queries) ListUsableAcquisitionServices(ctx context.Context, job string) ([]AcquisitionService, error) {
rows, err := q.db.Query(ctx, listUsableAcquisitionServices, job)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AcquisitionService
for rows.Next() {
var i AcquisitionService
if err := rows.Scan(
&i.Code,
&i.Kind,
&i.Protocol,
&i.Label,
&i.Enabled,
&i.BaseUrl,
&i.ApiKey,
&i.Username,
&i.Password,
&i.Category,
&i.TimeoutMs,
&i.ServesSearch,
&i.ServesDownloads,
&i.ServesEnrichment,
&i.LocalPath,
&i.RemotePath,
&i.SearchesPerHour,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setAcquisitionServiceAPIKey = `-- name: SetAcquisitionServiceAPIKey :execrows
UPDATE acquisition_services SET api_key = $1, updated_at = now()
WHERE code = $2
`
type SetAcquisitionServiceAPIKeyParams struct {
ApiKey string
Code string
}
func (q *Queries) SetAcquisitionServiceAPIKey(ctx context.Context, arg SetAcquisitionServiceAPIKeyParams) (int64, error) {
result, err := q.db.Exec(ctx, setAcquisitionServiceAPIKey, arg.ApiKey, arg.Code)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const setAcquisitionServicePassword = `-- name: SetAcquisitionServicePassword :execrows
UPDATE acquisition_services SET password = $1, updated_at = now()
WHERE code = $2
`
type SetAcquisitionServicePasswordParams struct {
Password string
Code string
}
func (q *Queries) SetAcquisitionServicePassword(ctx context.Context, arg SetAcquisitionServicePasswordParams) (int64, error) {
result, err := q.db.Exec(ctx, setAcquisitionServicePassword, arg.Password, arg.Code)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateAcquisitionService = `-- name: UpdateAcquisitionService :one
UPDATE acquisition_services SET
label = $1,
enabled = $2,
base_url = $3,
username = $4,
category = $5,
timeout_ms = $6,
serves_search = $7,
serves_downloads = $8,
serves_enrichment = $9,
local_path = $10,
remote_path = $11,
searches_per_hour = $12,
updated_at = now()
WHERE code = $13
RETURNING code, kind, protocol, label, enabled, base_url, api_key, username, password, category, timeout_ms, serves_search, serves_downloads, serves_enrichment, local_path, remote_path, searches_per_hour, created_at, updated_at
`
type UpdateAcquisitionServiceParams struct {
Label string
Enabled bool
BaseUrl string
Username string
Category string
TimeoutMs int32
ServesSearch bool
ServesDownloads bool
ServesEnrichment bool
LocalPath string
RemotePath string
SearchesPerHour int32
Code string
}
// Everything on the settings form except the credentials, which have their
// own write-only calls.
func (q *Queries) UpdateAcquisitionService(ctx context.Context, arg UpdateAcquisitionServiceParams) (AcquisitionService, error) {
row := q.db.QueryRow(ctx, updateAcquisitionService,
arg.Label,
arg.Enabled,
arg.BaseUrl,
arg.Username,
arg.Category,
arg.TimeoutMs,
arg.ServesSearch,
arg.ServesDownloads,
arg.ServesEnrichment,
arg.LocalPath,
arg.RemotePath,
arg.SearchesPerHour,
arg.Code,
)
var i AcquisitionService
err := row.Scan(
&i.Code,
&i.Kind,
&i.Protocol,
&i.Label,
&i.Enabled,
&i.BaseUrl,
&i.ApiKey,
&i.Username,
&i.Password,
&i.Category,
&i.TimeoutMs,
&i.ServesSearch,
&i.ServesDownloads,
&i.ServesEnrichment,
&i.LocalPath,
&i.RemotePath,
&i.SearchesPerHour,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
+2 -38
View File
@@ -11,42 +11,6 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const downloadsStatus = `-- name: DownloadsStatus :one
SELECT COUNT(*) FILTER (WHERE ended_at IS NULL AND import_state IN ('', 'downloading', 'waiting', 'importing'))::bigint AS running,
COUNT(*) FILTER (WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::bigint AS needs_you,
MIN(COALESCE(import_updated_at, grabbed_at)) FILTER (WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::timestamptz AS needs_you_since,
COUNT(*) FILTER (WHERE imported_at > now() - INTERVAL '24 hours')::bigint AS imported_day,
COUNT(*) FILTER (WHERE ended_at > now() - INTERVAL '24 hours'
AND end_reason IN ('stalled', 'failed', 'gone', 'abandoned'))::bigint AS given_up_day
FROM grabs
WHERE ended_at IS NULL
OR ended_at > now() - INTERVAL '24 hours'
OR imported_at > now() - INTERVAL '24 hours'
`
type DownloadsStatusRow struct {
Running int64
NeedsYou int64
NeedsYouSince pgtype.Timestamptz
ImportedDay int64
GivenUpDay int64
}
// Downloads at a glance: running, waiting on a person (and since when), and
// the last day's imports and give-ups.
func (q *Queries) DownloadsStatus(ctx context.Context) (DownloadsStatusRow, error) {
row := q.db.QueryRow(ctx, downloadsStatus)
var i DownloadsStatusRow
err := row.Scan(
&i.Running,
&i.NeedsYou,
&i.NeedsYouSince,
&i.ImportedDay,
&i.GivenUpDay,
)
return i, err
}
const libraryStatus = `-- name: LibraryStatus :one
SELECT COUNT(*)::bigint AS tracks,
COUNT(DISTINCT album_id)::bigint AS albums,
@@ -109,8 +73,8 @@ type ListListeningNowRow struct {
AlbumTitle string
}
// The admin Overview's status sections: who is listening, what is
// downloading, what the library holds. Each is one cheap read.
// The admin Overview's status sections: who is listening and what the
// library holds. Each is one cheap read.
// Plays in progress: open play events still inside their track's length,
// with a few minutes' grace for a pause. A client that never says a play
// ended would otherwise read as listening until the 24-hour sweep closes it.
-6
View File
@@ -13,8 +13,6 @@ import (
const adminSummary = `-- name: AdminSummary :one
SELECT
(SELECT count(*) FROM requests WHERE status = 'pending')::bigint AS requests,
(SELECT min(requested_at) FROM requests WHERE status = 'pending')::timestamptz AS requests_since,
-- A broken track is one report however it was found: a listener flagged
-- it, or it failed to play. Counted by track, as the Reports
-- page lists them.
@@ -41,8 +39,6 @@ SELECT
`
type AdminSummaryRow struct {
Requests int64
RequestsSince pgtype.Timestamptz
Reports int64
ReportsSince pgtype.Timestamptz
Duplicates int64
@@ -62,8 +58,6 @@ func (q *Queries) AdminSummary(ctx context.Context) (AdminSummaryRow, error) {
row := q.db.QueryRow(ctx, adminSummary)
var i AdminSummaryRow
err := row.Scan(
&i.Requests,
&i.RequestsSince,
&i.Reports,
&i.ReportsSince,
&i.Duplicates,
-35
View File
@@ -267,22 +267,6 @@ func (q *Queries) GetAlbumsByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([
return items, nil
}
const getReleaseGroupForReleaseMbid = `-- name: GetReleaseGroupForReleaseMbid :one
SELECT release_group_mbid::text
FROM albums
WHERE mbid = $1 AND release_group_mbid IS NOT NULL
LIMIT 1
`
// The release group the library already knows for a release id, so a
// request carrying a release id can be repaired without asking MusicBrainz.
func (q *Queries) GetReleaseGroupForReleaseMbid(ctx context.Context, mbid *string) (string, error) {
row := q.db.QueryRow(ctx, getReleaseGroupForReleaseMbid, mbid)
var release_group_mbid string
err := row.Scan(&release_group_mbid)
return release_group_mbid, err
}
const listAlbumsAlphaByArtist = `-- name: ListAlbumsAlphaByArtist :many
SELECT albums.id, albums.title, albums.sort_title, albums.artist_id, albums.release_date, albums.mbid, albums.cover_art_path, albums.created_at, albums.updated_at, albums.cover_art_source, albums.cover_art_sources_version, albums.release_group_mbid, artists.sort_name AS artist_sort_name
FROM albums
@@ -1015,25 +999,6 @@ func (q *Queries) SetAlbumReleaseGroupMbidIfNull(ctx context.Context, arg SetAlb
return err
}
const setReleaseGroupForReleaseMbidIfNull = `-- name: SetReleaseGroupForReleaseMbidIfNull :exec
UPDATE albums
SET release_group_mbid = $1::text,
updated_at = now()
WHERE mbid = $2::text AND release_group_mbid IS NULL
`
type SetReleaseGroupForReleaseMbidIfNullParams struct {
ReleaseGroupMbid string
ReleaseMbid string
}
// Cache a MusicBrainz-resolved release group onto the album row that
// holds the release, filling only a NULL.
func (q *Queries) SetReleaseGroupForReleaseMbidIfNull(ctx context.Context, arg SetReleaseGroupForReleaseMbidIfNullParams) error {
_, err := q.db.Exec(ctx, setReleaseGroupForReleaseMbidIfNull, arg.ReleaseGroupMbid, arg.ReleaseMbid)
return err
}
const upsertAlbum = `-- name: UpsertAlbum :one
INSERT INTO albums (title, sort_title, artist_id, release_date, mbid, cover_art_path, release_group_mbid)
VALUES ($1, $2, $3, $4, $5, $6, $7)
@@ -1,228 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: candidate_artist_tags.sql
package dbq
import (
"context"
)
const countCandidateArtistTagCoverage = `-- name: CountCandidateArtistTagCoverage :one
SELECT count(*)::bigint AS processed,
count(*) FILTER (WHERE tag_source <> 'none')::bigint AS with_tags
FROM candidate_artist_tag_state
`
type CountCandidateArtistTagCoverageRow struct {
Processed int64
WithTags int64
}
// Operator-facing coverage: how many distinct candidates have been processed,
// and how many of those actually yielded tags. The gap is the honest ceiling
// from the task — obscure artists with no MBID presence or no upstream tags
// stay thin no matter how long the worker runs, and that is worth being able
// to see rather than inferring from a silent surface.
func (q *Queries) CountCandidateArtistTagCoverage(ctx context.Context) (CountCandidateArtistTagCoverageRow, error) {
row := q.db.QueryRow(ctx, countCandidateArtistTagCoverage)
var i CountCandidateArtistTagCoverageRow
err := row.Scan(&i.Processed, &i.WithTags)
return i, err
}
const deleteCandidateArtistTags = `-- name: DeleteCandidateArtistTags :exec
DELETE FROM candidate_artist_tags WHERE candidate_mbid = $1
`
// Clear a candidate's cached tags before rewriting (atomic replace by the
// caller, same shape as DeleteTrackTags).
func (q *Queries) DeleteCandidateArtistTags(ctx context.Context, candidateMbid string) error {
_, err := q.db.Exec(ctx, deleteCandidateArtistTags, candidateMbid)
return err
}
const gcDeleteOrphanedCandidateArtistTagState = `-- name: GcDeleteOrphanedCandidateArtistTagState :execrows
DELETE FROM candidate_artist_tag_state s
WHERE NOT EXISTS (
SELECT 1 FROM artist_similarity_unmatched u
WHERE u.candidate_mbid = s.candidate_mbid
)
OR EXISTS (SELECT 1 FROM artists a WHERE a.mbid = s.candidate_mbid)
`
// Same sweep for the bookkeeping rows. Kept as a separate statement rather
// than a cascade: the two tables are independent by design (a 'none' outcome
// has state but no tags), so neither can be the parent of the other.
func (q *Queries) GcDeleteOrphanedCandidateArtistTagState(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, gcDeleteOrphanedCandidateArtistTagState)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const gcDeleteOrphanedCandidateArtistTags = `-- name: GcDeleteOrphanedCandidateArtistTags :execrows
DELETE FROM candidate_artist_tags t
WHERE NOT EXISTS (
SELECT 1 FROM artist_similarity_unmatched u
WHERE u.candidate_mbid = t.candidate_mbid
)
OR EXISTS (SELECT 1 FROM artists a WHERE a.mbid = t.candidate_mbid)
`
// Drops cached tags for candidates that no longer appear in the similarity
// feed, or that have since been added to the library (their tags now live in
// track_tags). The feed is refetched periodically and churns, so without this
// the cache only ever grows.
func (q *Queries) GcDeleteOrphanedCandidateArtistTags(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, gcDeleteOrphanedCandidateArtistTags)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const insertCandidateArtistTag = `-- name: InsertCandidateArtistTag :exec
INSERT INTO candidate_artist_tags (candidate_mbid, tag, weight)
VALUES ($1, $2, $3)
ON CONFLICT (candidate_mbid, tag)
DO UPDATE SET weight = GREATEST(candidate_artist_tags.weight, EXCLUDED.weight)
`
type InsertCandidateArtistTagParams struct {
CandidateMbid string
Tag string
Weight float64
}
// Upsert one (candidate, tag); keep the stronger weight when two providers
// agree on a tag with different folksonomy strengths.
func (q *Queries) InsertCandidateArtistTag(ctx context.Context, arg InsertCandidateArtistTagParams) error {
_, err := q.db.Exec(ctx, insertCandidateArtistTag, arg.CandidateMbid, arg.Tag, arg.Weight)
return err
}
const listCandidateArtistTagsForMbids = `-- name: ListCandidateArtistTagsForMbids :many
SELECT candidate_mbid, tag, weight
FROM candidate_artist_tags
WHERE candidate_mbid = ANY($1::text[])
`
// Cached tags for a set of candidates, for the taste-overlap ranking.
// One row per (candidate, tag).
func (q *Queries) ListCandidateArtistTagsForMbids(ctx context.Context, dollar_1 []string) ([]CandidateArtistTag, error) {
rows, err := q.db.Query(ctx, listCandidateArtistTagsForMbids, dollar_1)
if err != nil {
return nil, err
}
defer rows.Close()
var items []CandidateArtistTag
for rows.Next() {
var i CandidateArtistTag
if err := rows.Scan(&i.CandidateMbid, &i.Tag, &i.Weight); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listCandidateArtistsMissingTags = `-- name: ListCandidateArtistsMissingTags :many
SELECT u.candidate_mbid,
coalesce(max(u.candidate_name), '')::text AS candidate_name,
sum(u.score)::float8 AS total_score
FROM artist_similarity_unmatched u
LEFT JOIN candidate_artist_tag_state s ON s.candidate_mbid = u.candidate_mbid
WHERE NOT EXISTS (SELECT 1 FROM artists a WHERE a.mbid = u.candidate_mbid)
AND (
s.candidate_mbid IS NULL
OR (s.tag_source = 'none' AND s.tag_sources_version < $1)
)
GROUP BY u.candidate_mbid
ORDER BY total_score DESC, u.candidate_mbid
LIMIT $2
`
type ListCandidateArtistsMissingTagsParams struct {
TagSourcesVersion int32
Limit int32
}
type ListCandidateArtistsMissingTagsRow struct {
CandidateMbid string
CandidateName string
TotalScore float64
}
// Folksonomy tags for out-of-library Discover candidates. Parallel to
// track_tags.sql, but keyed by MBID because the artist has no local row. See
// 0050_candidate_artist_tags.up.sql for why the bookkeeping is its own table.
// Candidates eligible for tag enrichment: never processed (no state row) or
// settled 'none' under an older provider version.
//
// artist_similarity_unmatched holds one row per (seed, candidate, source), so
// this GROUPs to one row per candidate — enriching the same MBID once per seed
// that pointed at it would multiply the API calls for no gain.
//
// ORDER BY summed similarity DESC is the load-bearing part. The candidate pool
// is O(library artists x neighbours per artist) — thousands — and MusicBrainz
// allows ~1 req/s, so it can NEVER be fully enriched in one pass. Draining in
// strength order means the candidates most likely to actually reach a user's
// deck get tags first, and the long tail fills in over subsequent ticks
// instead of starving behind it.
//
// Already-in-library candidates are skipped: they have an artists row, so
// their tags belong in track_tags, and the suggestion query filters them out
// anyway. $1 = current tag_sources_version, $2 = limit.
// candidate_name is coalesced to the empty string so it lands non-nullable in
// Go: the name is only a Last.fm lookup key, and empty simply means "MBID-keyed
// providers only", which the provider chain already handles. max() is an
// arbitrary-but-deterministic pick when several seeds spell one MBID
// differently.
func (q *Queries) ListCandidateArtistsMissingTags(ctx context.Context, arg ListCandidateArtistsMissingTagsParams) ([]ListCandidateArtistsMissingTagsRow, error) {
rows, err := q.db.Query(ctx, listCandidateArtistsMissingTags, arg.TagSourcesVersion, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListCandidateArtistsMissingTagsRow
for rows.Next() {
var i ListCandidateArtistsMissingTagsRow
if err := rows.Scan(&i.CandidateMbid, &i.CandidateName, &i.TotalScore); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setCandidateArtistTagState = `-- name: SetCandidateArtistTagState :exec
INSERT INTO candidate_artist_tag_state (candidate_mbid, tag_source, tag_sources_version)
VALUES ($1, $2, $3)
ON CONFLICT (candidate_mbid) DO UPDATE
SET tag_source = EXCLUDED.tag_source,
tag_sources_version = EXCLUDED.tag_sources_version,
updated_at = now()
`
type SetCandidateArtistTagStateParams struct {
CandidateMbid string
TagSource string
TagSourcesVersion int32
}
// Stamp the enrichment outcome so the drainer skips settled candidates.
// $2 = 'musicbrainz' | 'lastfm' | 'mixed' | 'none', $3 = current version.
func (q *Queries) SetCandidateArtistTagState(ctx context.Context, arg SetCandidateArtistTagStateParams) error {
_, err := q.db.Exec(ctx, setCandidateArtistTagState, arg.CandidateMbid, arg.TagSource, arg.TagSourcesVersion)
return err
}
+4 -205
View File
@@ -7,35 +7,8 @@ package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const addMBArtistReleaseGroup = `-- name: AddMBArtistReleaseGroup :exec
INSERT INTO mb_artist_release_groups (artist_mbid, release_group_mbid)
VALUES ($1, $2)
ON CONFLICT DO NOTHING
`
type AddMBArtistReleaseGroupParams struct {
ArtistMbid string
ReleaseGroupMbid string
}
func (q *Queries) AddMBArtistReleaseGroup(ctx context.Context, arg AddMBArtistReleaseGroupParams) error {
_, err := q.db.Exec(ctx, addMBArtistReleaseGroup, arg.ArtistMbid, arg.ReleaseGroupMbid)
return err
}
const deleteMBArtistReleaseGroups = `-- name: DeleteMBArtistReleaseGroups :exec
DELETE FROM mb_artist_release_groups WHERE artist_mbid = $1
`
func (q *Queries) DeleteMBArtistReleaseGroups(ctx context.Context, artistMbid string) error {
_, err := q.db.Exec(ctx, deleteMBArtistReleaseGroups, artistMbid)
return err
}
const deleteMBReleasesForGroup = `-- name: DeleteMBReleasesForGroup :exec
DELETE FROM mb_releases WHERE release_group_mbid = $1
`
@@ -46,27 +19,6 @@ func (q *Queries) DeleteMBReleasesForGroup(ctx context.Context, releaseGroupMbid
return err
}
const getMBArtist = `-- name: GetMBArtist :one
SELECT mbid, name, sort_name, disambiguation, artist_type, country, discography_refreshed_at, created_at, updated_at FROM mb_artists WHERE mbid = $1
`
func (q *Queries) GetMBArtist(ctx context.Context, mbid string) (MbArtist, error) {
row := q.db.QueryRow(ctx, getMBArtist, mbid)
var i MbArtist
err := row.Scan(
&i.Mbid,
&i.Name,
&i.SortName,
&i.Disambiguation,
&i.ArtistType,
&i.Country,
&i.DiscographyRefreshedAt,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getMBReleaseGroup = `-- name: GetMBReleaseGroup :one
SELECT mbid, title, primary_type, secondary_types, first_release_date, artist_credit, releases_refreshed_at, created_at, updated_at FROM mb_release_groups WHERE mbid = $1
`
@@ -165,78 +117,6 @@ func (q *Queries) InsertMBReleaseTrack(ctx context.Context, arg InsertMBReleaseT
return err
}
const listMBArtistReleaseGroups = `-- name: ListMBArtistReleaseGroups :many
SELECT g.mbid, g.title, g.primary_type, g.secondary_types, g.first_release_date, g.artist_credit, g.releases_refreshed_at, g.created_at, g.updated_at FROM mb_release_groups g
JOIN mb_artist_release_groups ag ON ag.release_group_mbid = g.mbid
WHERE ag.artist_mbid = $1
ORDER BY g.first_release_date = '', g.first_release_date, g.title, g.mbid
`
// An artist's discography, oldest first; undated groups last.
func (q *Queries) ListMBArtistReleaseGroups(ctx context.Context, artistMbid string) ([]MbReleaseGroup, error) {
rows, err := q.db.Query(ctx, listMBArtistReleaseGroups, artistMbid)
if err != nil {
return nil, err
}
defer rows.Close()
var items []MbReleaseGroup
for rows.Next() {
var i MbReleaseGroup
if err := rows.Scan(
&i.Mbid,
&i.Title,
&i.PrimaryType,
&i.SecondaryTypes,
&i.FirstReleaseDate,
&i.ArtistCredit,
&i.ReleasesRefreshedAt,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMBArtistsDueForRefresh = `-- name: ListMBArtistsDueForRefresh :many
SELECT mbid FROM mb_artists
WHERE discography_refreshed_at IS NULL OR discography_refreshed_at < $1
ORDER BY discography_refreshed_at NULLS FIRST, mbid
LIMIT $2
`
type ListMBArtistsDueForRefreshParams struct {
Before pgtype.Timestamptz
MaxRows int32
}
// Artists whose discography has never been read, or was read before the
// cutoff: never-read first, then oldest first.
func (q *Queries) ListMBArtistsDueForRefresh(ctx context.Context, arg ListMBArtistsDueForRefreshParams) ([]string, error) {
rows, err := q.db.Query(ctx, listMBArtistsDueForRefresh, arg.Before, arg.MaxRows)
if err != nil {
return nil, err
}
defer rows.Close()
var items []string
for rows.Next() {
var mbid string
if err := rows.Scan(&mbid); err != nil {
return nil, err
}
items = append(items, mbid)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMBReleaseTracksForGroup = `-- name: ListMBReleaseTracksForGroup :many
SELECT t.release_mbid, t.medium_position, t.position, t.medium_format, t.number, t.title, t.length_ms, t.recording_mbid FROM mb_release_tracks t
JOIN mb_releases r ON r.mbid = t.release_mbid
@@ -273,53 +153,6 @@ func (q *Queries) ListMBReleaseTracksForGroup(ctx context.Context, releaseGroupM
return items, nil
}
const listMBReleasesForGroup = `-- name: ListMBReleasesForGroup :many
SELECT mbid, release_group_mbid, title, status, release_date, country, disambiguation, formats, track_count, created_at FROM mb_releases
WHERE release_group_mbid = $1
ORDER BY status <> 'Official', release_date = '', release_date, title, mbid
`
// Official editions first, then by date; undated last.
func (q *Queries) ListMBReleasesForGroup(ctx context.Context, releaseGroupMbid string) ([]MbRelease, error) {
rows, err := q.db.Query(ctx, listMBReleasesForGroup, releaseGroupMbid)
if err != nil {
return nil, err
}
defer rows.Close()
var items []MbRelease
for rows.Next() {
var i MbRelease
if err := rows.Scan(
&i.Mbid,
&i.ReleaseGroupMbid,
&i.Title,
&i.Status,
&i.ReleaseDate,
&i.Country,
&i.Disambiguation,
&i.Formats,
&i.TrackCount,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const markMBArtistDiscographyRefreshed = `-- name: MarkMBArtistDiscographyRefreshed :exec
UPDATE mb_artists SET discography_refreshed_at = now() WHERE mbid = $1
`
func (q *Queries) MarkMBArtistDiscographyRefreshed(ctx context.Context, mbid string) error {
_, err := q.db.Exec(ctx, markMBArtistDiscographyRefreshed, mbid)
return err
}
const markMBReleaseGroupReleasesRefreshed = `-- name: MarkMBReleaseGroupReleasesRefreshed :exec
UPDATE mb_release_groups SET releases_refreshed_at = now() WHERE mbid = $1
`
@@ -329,43 +162,8 @@ func (q *Queries) MarkMBReleaseGroupReleasesRefreshed(ctx context.Context, mbid
return err
}
const upsertMBArtist = `-- name: UpsertMBArtist :exec
INSERT INTO mb_artists (mbid, name, sort_name, disambiguation, artist_type, country)
VALUES ($1, $2, $3, $4,
$5, $6)
ON CONFLICT (mbid) DO UPDATE SET
name = EXCLUDED.name,
sort_name = EXCLUDED.sort_name,
disambiguation = EXCLUDED.disambiguation,
artist_type = EXCLUDED.artist_type,
country = EXCLUDED.country,
updated_at = now()
`
type UpsertMBArtistParams struct {
Mbid string
Name string
SortName string
Disambiguation string
ArtistType string
Country string
}
// The release catalogue read from MusicBrainz.
func (q *Queries) UpsertMBArtist(ctx context.Context, arg UpsertMBArtistParams) error {
_, err := q.db.Exec(ctx, upsertMBArtist,
arg.Mbid,
arg.Name,
arg.SortName,
arg.Disambiguation,
arg.ArtistType,
arg.Country,
)
return err
}
const upsertMBReleaseGroup = `-- name: UpsertMBReleaseGroup :exec
INSERT INTO mb_release_groups (mbid, title, primary_type, secondary_types, first_release_date, artist_credit)
VALUES ($1, $2, $3, $4::text[],
$5, $6)
@@ -387,8 +185,9 @@ type UpsertMBReleaseGroupParams struct {
ArtistCredit string
}
// Leaves releases_refreshed_at alone: re-reading a discography says nothing
// about whether the group's track lists are current.
// The release catalogue read from MusicBrainz.
// Leaves releases_refreshed_at alone: only a full read of the group's
// releases and track lists marks it.
func (q *Queries) UpsertMBReleaseGroup(ctx context.Context, arg UpsertMBReleaseGroupParams) error {
_, err := q.db.Exec(ctx, upsertMBReleaseGroup,
arg.Mbid,
-902
View File
@@ -1,902 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: imports.sql
package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const claimGrabImport = `-- name: ClaimGrabImport :one
UPDATE grabs
SET import_state = 'importing', import_attempts = import_attempts + 1,
import_updated_at = now(), progress = 1
WHERE id = $1 AND ended_at IS NULL AND import_state IN ('', 'downloading', 'waiting')
RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at
`
// Takes a finished download for import. The update is the lock: a second
// pass finds nothing to claim.
func (q *Queries) ClaimGrabImport(ctx context.Context, id pgtype.UUID) (Grab, error) {
row := q.db.QueryRow(ctx, claimGrabImport, id)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const clearTrackSourceVerdict = `-- name: ClearTrackSourceVerdict :exec
UPDATE tracks SET source_verdict = NULL, source_verdict_at = NULL
WHERE id = $1 AND source_verdict = 'suspect'
`
// A track whose file was replaced in place is no longer the rip it was.
func (q *Queries) ClearTrackSourceVerdict(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, clearTrackSourceVerdict, id)
return err
}
const finishUpgrade = `-- name: FinishUpgrade :exec
UPDATE wants
SET album_id = COALESCE($1, album_id),
upgrade = '',
upgrade_checked_at = NULL,
updated_at = now()
WHERE id = $2
`
type FinishUpgradeParams struct {
AlbumID pgtype.UUID
ID pgtype.UUID
}
// An upgrade was imported: the want holds the album the new tracks are in,
// and is judged again by the next upgrade check.
func (q *Queries) FinishUpgrade(ctx context.Context, arg FinishUpgradeParams) error {
_, err := q.db.Exec(ctx, finishUpgrade, arg.AlbumID, arg.ID)
return err
}
const forceGrabImport = `-- name: ForceGrabImport :one
UPDATE grabs
SET import_state = '', import_forced = true, import_reason = '', import_updated_at = now()
WHERE id = $1 AND ended_at IS NULL AND import_state IN ('review', 'failed')
RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at
`
// "Import anyway": the next pass imports the download whatever the check said.
func (q *Queries) ForceGrabImport(ctx context.Context, id pgtype.UUID) (Grab, error) {
row := q.db.QueryRow(ctx, forceGrabImport, id)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const getGrab = `-- name: GetGrab :one
SELECT id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at FROM grabs WHERE id = $1
`
func (q *Queries) GetGrab(ctx context.Context, id pgtype.UUID) (Grab, error) {
row := q.db.QueryRow(ctx, getGrab, id)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const heldPositions = `-- name: HeldPositions :many
SELECT DISTINCT COALESCE(t.disc_number, 1)::int AS disc, t.track_number::int AS track
FROM tracks t
JOIN albums a ON a.id = t.album_id
WHERE a.release_group_mbid = $1
AND t.missing_since IS NULL AND t.track_number IS NOT NULL
`
type HeldPositionsRow struct {
Disc int32
Track int32
}
// The disc and track positions the library holds for an album of this group.
func (q *Queries) HeldPositions(ctx context.Context, releaseGroupMbid *string) ([]HeldPositionsRow, error) {
rows, err := q.db.Query(ctx, heldPositions, releaseGroupMbid)
if err != nil {
return nil, err
}
defer rows.Close()
var items []HeldPositionsRow
for rows.Next() {
var i HeldPositionsRow
if err := rows.Scan(&i.Disc, &i.Track); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const heldRecordings = `-- name: HeldRecordings :many
SELECT DISTINCT mbid::text AS mbid FROM tracks
WHERE mbid = ANY($1::text[]) AND missing_since IS NULL
`
// Which of these recordings the library holds a file for.
func (q *Queries) HeldRecordings(ctx context.Context, recordings []string) ([]string, error) {
rows, err := q.db.Query(ctx, heldRecordings, recordings)
if err != nil {
return nil, err
}
defer rows.Close()
var items []string
for rows.Next() {
var mbid string
if err := rows.Scan(&mbid); err != nil {
return nil, err
}
items = append(items, mbid)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listGrabs = `-- name: ListGrabs :many
SELECT g.id, g.want_id, g.name, g.indexer, g.client, g.quality, g.origin, g.forced,
g.grabbed_at, g.ended_at, g.end_reason, g.end_detail, g.progress, g.import_state,
g.import_reason, g.import_detail, g.import_updated_at, g.imported_at, g.imported_files,
g.destination, g.seeding, g.ratio, g.seed_released_at,
w.title AS want_title, w.artist_name AS want_artist,
di.trigger AS condition, di.detail AS condition_detail, di.remediations AS condition_retries,
di.first_seen AS condition_since
FROM grabs g
LEFT JOIN wants w ON w.id = g.want_id
LEFT JOIN download_interventions di
ON di.id = (SELECT x.id FROM download_interventions x
WHERE x.grab_id = g.id AND x.outcome = 'open'
ORDER BY x.last_seen DESC LIMIT 1)
ORDER BY (g.ended_at IS NULL AND g.import_state IN ('review', 'failed')) DESC,
g.ended_at IS NULL DESC, g.grabbed_at DESC, g.id
LIMIT $2 OFFSET $1
`
type ListGrabsParams struct {
Skip int32
MaxRows int32
}
type ListGrabsRow struct {
ID pgtype.UUID
WantID pgtype.UUID
Name string
Indexer string
Client string
Quality string
Origin string
Forced bool
GrabbedAt pgtype.Timestamptz
EndedAt pgtype.Timestamptz
EndReason string
EndDetail string
Progress float32
ImportState string
ImportReason string
ImportDetail []byte
ImportUpdatedAt pgtype.Timestamptz
ImportedAt pgtype.Timestamptz
ImportedFiles int32
Destination string
Seeding bool
Ratio float32
SeedReleasedAt pgtype.Timestamptz
WantTitle *string
WantArtist *string
Condition *string
ConditionDetail *string
ConditionRetries *int32
ConditionSince pgtype.Timestamptz
}
// The Wanted view's Activity tab: downloads waiting on a person first, then
// the rest still running, then the ended ones newest first. Each carries
// what is wrong with it now, if anything.
func (q *Queries) ListGrabs(ctx context.Context, arg ListGrabsParams) ([]ListGrabsRow, error) {
rows, err := q.db.Query(ctx, listGrabs, arg.Skip, arg.MaxRows)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListGrabsRow
for rows.Next() {
var i ListGrabsRow
if err := rows.Scan(
&i.ID,
&i.WantID,
&i.Name,
&i.Indexer,
&i.Client,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
&i.WantTitle,
&i.WantArtist,
&i.Condition,
&i.ConditionDetail,
&i.ConditionRetries,
&i.ConditionSince,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listImportedGrabsHolding = `-- name: ListImportedGrabsHolding :many
SELECT id, info_hash, name, want_id
FROM grabs
WHERE import_state = 'imported'
AND info_hash <> ''
AND destination <> ''
AND starts_with($1::text, rtrim(destination, '/') || '/')
`
type ListImportedGrabsHoldingRow struct {
ID pgtype.UUID
InfoHash string
Name string
WantID pgtype.UUID
}
// The downloads Minstrel imported into the folder holding path: the releases a
// file there came from, to block when the files proved not to be the album
// . A file imported before Minstrel downloaded anything has none.
func (q *Queries) ListImportedGrabsHolding(ctx context.Context, path string) ([]ListImportedGrabsHoldingRow, error) {
rows, err := q.db.Query(ctx, listImportedGrabsHolding, path)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListImportedGrabsHoldingRow
for rows.Next() {
var i ListImportedGrabsHoldingRow
if err := rows.Scan(
&i.ID,
&i.InfoHash,
&i.Name,
&i.WantID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listLiveGrabs = `-- name: ListLiveGrabs :many
SELECT g.id, g.want_id, g.info_hash, g.name, g.key, g.indexer, g.source, g.client, g.save_path, g.quality, g.origin, g.forced, g.grabbed_by, g.grabbed_at, g.ended_at, g.end_reason, g.end_detail, g.progress, g.import_state, g.import_reason, g.import_detail, g.import_forced, g.import_attempts, g.import_updated_at, g.imported_at, g.imported_files, g.destination, g.seeding, g.ratio, g.seed_released_at, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title AS want_title,
w.reason AS want_reason, w.album_id AS want_album_id
FROM grabs g
LEFT JOIN wants w ON w.id = g.want_id
WHERE g.ended_at IS NULL
ORDER BY g.grabbed_at, g.id
`
type ListLiveGrabsRow struct {
ID pgtype.UUID
WantID pgtype.UUID
InfoHash string
Name string
Key string
Indexer string
Source string
Client string
SavePath string
Quality string
Origin string
Forced bool
GrabbedBy pgtype.UUID
GrabbedAt pgtype.Timestamptz
EndedAt pgtype.Timestamptz
EndReason string
EndDetail string
Progress float32
ImportState string
ImportReason string
ImportDetail []byte
ImportForced bool
ImportAttempts int32
ImportUpdatedAt pgtype.Timestamptz
ImportedAt pgtype.Timestamptz
ImportedFiles int32
Destination string
Seeding bool
Ratio float32
SeedReleasedAt pgtype.Timestamptz
ReleaseGroupMbid *string
ArtistMbid *string
ArtistName *string
WantTitle *string
WantReason *string
WantAlbumID pgtype.UUID
}
// Import with verification.
// Every download still running or waiting on its import, oldest first.
func (q *Queries) ListLiveGrabs(ctx context.Context) ([]ListLiveGrabsRow, error) {
rows, err := q.db.Query(ctx, listLiveGrabs)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListLiveGrabsRow
for rows.Next() {
var i ListLiveGrabsRow
if err := rows.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
&i.ReleaseGroupMbid,
&i.ArtistMbid,
&i.ArtistName,
&i.WantTitle,
&i.WantReason,
&i.WantAlbumID,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listReleaseBlocksPage = `-- name: ListReleaseBlocksPage :many
SELECT b.info_hash, b.name, b.reason, b.detail, b.blocked_at, b.expires_at, w.title AS want_title,
w.artist_name AS want_artist
FROM release_blocks b
LEFT JOIN wants w ON w.id = b.want_id
WHERE b.expires_at IS NULL OR b.expires_at > now()
ORDER BY b.blocked_at DESC, b.info_hash
LIMIT $2 OFFSET $1
`
type ListReleaseBlocksPageParams struct {
Skip int32
MaxRows int32
}
type ListReleaseBlocksPageRow struct {
InfoHash string
Name string
Reason string
Detail string
BlockedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
WantTitle *string
WantArtist *string
}
func (q *Queries) ListReleaseBlocksPage(ctx context.Context, arg ListReleaseBlocksPageParams) ([]ListReleaseBlocksPageRow, error) {
rows, err := q.db.Query(ctx, listReleaseBlocksPage, arg.Skip, arg.MaxRows)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListReleaseBlocksPageRow
for rows.Next() {
var i ListReleaseBlocksPageRow
if err := rows.Scan(
&i.InfoHash,
&i.Name,
&i.Reason,
&i.Detail,
&i.BlockedAt,
&i.ExpiresAt,
&i.WantTitle,
&i.WantArtist,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listUpgradeTracks = `-- name: ListUpgradeTracks :many
SELECT id, file_path, mbid, COALESCE(disc_number, 1)::int AS disc, track_number,
file_format, file_size, duration_ms, source_verdict
FROM tracks
WHERE album_id = $1 AND missing_since IS NULL
`
type ListUpgradeTracksRow struct {
ID pgtype.UUID
FilePath string
Mbid *string
Disc int32
TrackNumber *int32
FileFormat string
FileSize int64
DurationMs int32
SourceVerdict *string
}
// The tracks an upgrade may replace: the present tracks of the album
// the want holds.
func (q *Queries) ListUpgradeTracks(ctx context.Context, albumID pgtype.UUID) ([]ListUpgradeTracksRow, error) {
rows, err := q.db.Query(ctx, listUpgradeTracks, albumID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListUpgradeTracksRow
for rows.Next() {
var i ListUpgradeTracksRow
if err := rows.Scan(
&i.ID,
&i.FilePath,
&i.Mbid,
&i.Disc,
&i.TrackNumber,
&i.FileFormat,
&i.FileSize,
&i.DurationMs,
&i.SourceVerdict,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const markWantSearched = `-- name: MarkWantSearched :exec
UPDATE wants SET searched_at = now() WHERE id = $1
`
// Imported: nothing to search for until the wanted pass settles the want.
func (q *Queries) MarkWantSearched(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, markWantSearched, id)
return err
}
const openWantsForGroups = `-- name: OpenWantsForGroups :many
SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.primary_type, w.first_release_date, w.reason, w.album_id, w.created_by, w.wanted_at, w.fulfilled_at, w.created_at, w.updated_at, w.searched_at, w.search_outcome, w.search_considered, w.best_release, w.best_verdict, w.search_error, w.upgrade, w.held_tier, w.held_quality, w.upgrade_checked_at FROM wants w
WHERE w.fulfilled_at IS NULL AND w.release_group_mbid = ANY($1::text[])
AND NOT EXISTS (SELECT 1 FROM grabs g WHERE g.want_id = w.id AND g.ended_at IS NULL)
`
// Open wants for these release groups with no download running.
func (q *Queries) OpenWantsForGroups(ctx context.Context, groups []string) ([]Want, error) {
rows, err := q.db.Query(ctx, openWantsForGroups, groups)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Want
for rows.Next() {
var i Want
if err := rows.Scan(
&i.ID,
&i.ReleaseGroupMbid,
&i.ArtistMbid,
&i.ArtistName,
&i.Title,
&i.PrimaryType,
&i.FirstReleaseDate,
&i.Reason,
&i.AlbumID,
&i.CreatedBy,
&i.WantedAt,
&i.FulfilledAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.SearchedAt,
&i.SearchOutcome,
&i.SearchConsidered,
&i.BestRelease,
&i.BestVerdict,
&i.SearchError,
&i.Upgrade,
&i.HeldTier,
&i.HeldQuality,
&i.UpgradeCheckedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const reclaimStaleImports = `-- name: ReclaimStaleImports :execrows
UPDATE grabs
SET import_state = 'waiting',
import_reason = 'The last import was cut short, so it is being tried again.'
WHERE ended_at IS NULL AND import_state = 'importing'
AND import_updated_at < now() - make_interval(mins => $1::int)
`
// An import cut short (a restart mid-copy) is tried again.
func (q *Queries) ReclaimStaleImports(ctx context.Context, minutes int32) (int64, error) {
result, err := q.db.Exec(ctx, reclaimStaleImports, minutes)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const recordImport = `-- name: RecordImport :one
UPDATE grabs
SET import_state = $1,
import_reason = $2,
import_detail = $3,
import_updated_at = now(),
import_forced = false,
imported_at = CASE WHEN $1::text = 'imported' THEN now() ELSE imported_at END,
-- The files were copied, so an imported download goes on sharing
-- until the lifecycle removes it.
seeding = $1::text = 'imported',
imported_files = $4,
destination = $5,
ended_at = CASE WHEN $6::text <> '' THEN now() ELSE ended_at END,
end_reason = $6,
end_detail = CASE WHEN $6::text <> '' THEN $2::text ELSE end_detail END
WHERE id = $7
RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at
`
type RecordImportParams struct {
ImportState string
ImportReason string
ImportDetail []byte
ImportedFiles int32
Destination string
EndReason string
ID pgtype.UUID
}
// The import's outcome. An end reason ends the grab: imported, refused or
// held. Without one the grab stays live: review and failed wait for a person.
func (q *Queries) RecordImport(ctx context.Context, arg RecordImportParams) (Grab, error) {
row := q.db.QueryRow(ctx, recordImport,
arg.ImportState,
arg.ImportReason,
arg.ImportDetail,
arg.ImportedFiles,
arg.Destination,
arg.EndReason,
arg.ID,
)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const rehomeGrab = `-- name: RehomeGrab :one
UPDATE grabs g
SET want_id = $1
WHERE g.id = $2 AND g.ended_at IS NULL
AND NOT EXISTS (SELECT 1 FROM grabs o WHERE o.want_id = $1 AND o.ended_at IS NULL)
RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at
`
type RehomeGrabParams struct {
WantID pgtype.UUID
ID pgtype.UUID
}
// A download that turned out to be another wanted album is that want's grab,
// when the want has none running.
func (q *Queries) RehomeGrab(ctx context.Context, arg RehomeGrabParams) (Grab, error) {
row := q.db.QueryRow(ctx, rehomeGrab, arg.WantID, arg.ID)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const retryGrabImport = `-- name: RetryGrabImport :one
UPDATE grabs
SET import_state = '', import_reason = '', import_updated_at = now()
WHERE id = $1 AND ended_at IS NULL AND import_state = 'failed'
RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at
`
func (q *Queries) RetryGrabImport(ctx context.Context, id pgtype.UUID) (Grab, error) {
row := q.db.QueryRow(ctx, retryGrabImport, id)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const searchWantAgain = `-- name: SearchWantAgain :exec
UPDATE wants SET searched_at = NULL, search_outcome = '' WHERE id = $1
`
// Refused: search again on the next pass.
func (q *Queries) SearchWantAgain(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, searchWantAgain, id)
return err
}
const setGrabProgress = `-- name: SetGrabProgress :exec
UPDATE grabs
SET progress = $1,
import_state = $2,
import_reason = $3,
import_updated_at = now()
WHERE id = $4 AND ended_at IS NULL
AND import_state IN ('', 'downloading', 'waiting')
`
type SetGrabProgressParams struct {
Progress float32
ImportState string
ImportReason string
ID pgtype.UUID
}
// What the download client says of a download not yet finished, or finished
// and waiting for what the import needs. Leaves a claimed, decided or failed
// import alone.
func (q *Queries) SetGrabProgress(ctx context.Context, arg SetGrabProgressParams) error {
_, err := q.db.Exec(ctx, setGrabProgress,
arg.Progress,
arg.ImportState,
arg.ImportReason,
arg.ID,
)
return err
}
-39
View File
@@ -50,45 +50,6 @@ func (q *Queries) RerootAlbumCoverPaths(ctx context.Context, arg RerootAlbumCove
return result.RowsAffected(), nil
}
const rerootGrabDestinations = `-- name: RerootGrabDestinations :execrows
UPDATE grabs
SET destination = $1::text || substr(destination, length($2::text) + 1)
WHERE destination = $2::text
OR starts_with(destination, $2::text || '/')
`
type RerootGrabDestinationsParams struct {
NewRoot string
OldRoot string
}
func (q *Queries) RerootGrabDestinations(ctx context.Context, arg RerootGrabDestinationsParams) (int64, error) {
result, err := q.db.Exec(ctx, rerootGrabDestinations, arg.NewRoot, arg.OldRoot)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const rerootImportRoot = `-- name: RerootImportRoot :execrows
UPDATE acquisition_settings
SET import_root = $1::text
WHERE import_root = $2::text
`
type RerootImportRootParams struct {
NewRoot string
OldRoot string
}
func (q *Queries) RerootImportRoot(ctx context.Context, arg RerootImportRootParams) (int64, error) {
result, err := q.db.Exec(ctx, rerootImportRoot, arg.NewRoot, arg.OldRoot)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const rerootTrackPaths = `-- name: RerootTrackPaths :execrows
UPDATE tracks
-408
View File
@@ -1,408 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: lifecycle.sql
package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countGoneGrabs = `-- name: CountGoneGrabs :one
SELECT count(*) FROM grabs
WHERE info_hash = $1 AND end_reason = 'gone' AND ended_at > $2
`
type CountGoneGrabsParams struct {
InfoHash string
Since pgtype.Timestamptz
}
// How many of a release's grabs ended gone since a time: a release that keeps
// leaving its client is held back rather than taken on every pass.
func (q *Queries) CountGoneGrabs(ctx context.Context, arg CountGoneGrabsParams) (int64, error) {
row := q.db.QueryRow(ctx, countGoneGrabs, arg.InfoHash, arg.Since)
var count int64
err := row.Scan(&count)
return count, err
}
const countRemediation = `-- name: CountRemediation :one
UPDATE download_interventions
SET remediations = remediations + 1,
action = $1,
last_seen = now(),
outcome = CASE WHEN $1::text IN ('given_up', 'removed') THEN 'resolved' ELSE outcome END,
settled_at = CASE WHEN $1::text IN ('given_up', 'removed') THEN now() ELSE settled_at END
WHERE client = $2 AND info_hash = $3
AND trigger = $4 AND outcome = 'open'
RETURNING remediations
`
type CountRemediationParams struct {
Action string
Client string
InfoHash string
Trigger string
}
// Minstrel acted on an open condition. A retry climbs the ladder; giving up
// or removing ends the condition, since what it was about is gone. Written
// before the act, so a retry that happened is never uncounted.
func (q *Queries) CountRemediation(ctx context.Context, arg CountRemediationParams) (int32, error) {
row := q.db.QueryRow(ctx, countRemediation,
arg.Action,
arg.Client,
arg.InfoHash,
arg.Trigger,
)
var remediations int32
err := row.Scan(&remediations)
return remediations, err
}
const deleteExpiredBlocks = `-- name: DeleteExpiredBlocks :execrows
DELETE FROM release_blocks WHERE expires_at IS NOT NULL AND expires_at <= now()
`
// A release given up on is held back for a while; after that the search may
// take it again.
func (q *Queries) DeleteExpiredBlocks(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, deleteExpiredBlocks)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const giveUpGrab = `-- name: GiveUpGrab :one
UPDATE grabs
SET ended_at = now(), end_reason = $1, end_detail = $2,
import_updated_at = now()
WHERE id = $3 AND ended_at IS NULL AND import_state = ANY($4::text[])
RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at
`
type GiveUpGrabParams struct {
EndReason string
EndDetail string
ID pgtype.UUID
States []string
}
// Ends a running grab, given up on. Only from the states named: the update
// is the lock against an import that claimed the download meanwhile.
func (q *Queries) GiveUpGrab(ctx context.Context, arg GiveUpGrabParams) (Grab, error) {
row := q.db.QueryRow(ctx, giveUpGrab,
arg.EndReason,
arg.EndDetail,
arg.ID,
arg.States,
)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const listClientsDown = `-- name: ListClientsDown :many
SELECT client, detail, first_seen FROM download_interventions
WHERE trigger = 'client_unreachable' AND outcome = 'open'
ORDER BY client
`
type ListClientsDownRow struct {
Client string
Detail string
FirstSeen pgtype.Timestamptz
}
// Download clients not answering now, for the Activity tab.
func (q *Queries) ListClientsDown(ctx context.Context) ([]ListClientsDownRow, error) {
rows, err := q.db.Query(ctx, listClientsDown)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListClientsDownRow
for rows.Next() {
var i ListClientsDownRow
if err := rows.Scan(&i.Client, &i.Detail, &i.FirstSeen); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listLeftovers = `-- name: ListLeftovers :many
SELECT id, client, info_hash, grab_id, name, trigger, action, outcome, detail, observations, remediations, first_seen, last_seen, settled_at FROM download_interventions
WHERE trigger = 'not_removed' AND outcome = 'open' AND info_hash <> ''
ORDER BY first_seen
`
// Downloads given up on that the client would not remove; each pass asks
// again.
func (q *Queries) ListLeftovers(ctx context.Context) ([]DownloadIntervention, error) {
rows, err := q.db.Query(ctx, listLeftovers)
if err != nil {
return nil, err
}
defer rows.Close()
var items []DownloadIntervention
for rows.Next() {
var i DownloadIntervention
if err := rows.Scan(
&i.ID,
&i.Client,
&i.InfoHash,
&i.GrabID,
&i.Name,
&i.Trigger,
&i.Action,
&i.Outcome,
&i.Detail,
&i.Observations,
&i.Remediations,
&i.FirstSeen,
&i.LastSeen,
&i.SettledAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listSeedingGrabs = `-- name: ListSeedingGrabs :many
SELECT id, client, info_hash, name, imported_at FROM grabs
WHERE seeding AND seed_released_at IS NULL
ORDER BY imported_at, id
`
type ListSeedingGrabsRow struct {
ID pgtype.UUID
Client string
InfoHash string
Name string
ImportedAt pgtype.Timestamptz
}
// Imported downloads still sharing, oldest import first.
func (q *Queries) ListSeedingGrabs(ctx context.Context) ([]ListSeedingGrabsRow, error) {
rows, err := q.db.Query(ctx, listSeedingGrabs)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListSeedingGrabsRow
for rows.Next() {
var i ListSeedingGrabsRow
if err := rows.Scan(
&i.ID,
&i.Client,
&i.InfoHash,
&i.Name,
&i.ImportedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const liveGrabOnHash = `-- name: LiveGrabOnHash :one
SELECT EXISTS (SELECT 1 FROM grabs WHERE info_hash = $1 AND ended_at IS NULL)::bool
`
func (q *Queries) LiveGrabOnHash(ctx context.Context, infoHash string) (bool, error) {
row := q.db.QueryRow(ctx, liveGrabOnHash, infoHash)
var column_1 bool
err := row.Scan(&column_1)
return column_1, err
}
const raiseIntervention = `-- name: RaiseIntervention :one
INSERT INTO download_interventions (client, info_hash, grab_id, name, trigger, detail)
VALUES ($1, $2, $3, $4,
$5, $6)
ON CONFLICT (client, info_hash, trigger) WHERE outcome = 'open' DO UPDATE SET
observations = download_interventions.observations + 1,
last_seen = now(),
detail = EXCLUDED.detail,
grab_id = COALESCE(EXCLUDED.grab_id, download_interventions.grab_id),
name = CASE WHEN EXCLUDED.name <> '' THEN EXCLUDED.name ELSE download_interventions.name END
RETURNING id, client, info_hash, grab_id, name, trigger, action, outcome, detail, observations, remediations, first_seen, last_seen, settled_at
`
type RaiseInterventionParams struct {
Client string
InfoHash string
GrabID pgtype.UUID
Name string
Trigger string
Detail string
}
// The download lifecycle: the intervention ledger, giving a
// download up, and seeding after import.
// A condition seen, or seen again: a second pass lands on the open row, so
// a download stuck for a week is one row that says how long. The name only
// improves, and the detail is the latest word.
func (q *Queries) RaiseIntervention(ctx context.Context, arg RaiseInterventionParams) (DownloadIntervention, error) {
row := q.db.QueryRow(ctx, raiseIntervention,
arg.Client,
arg.InfoHash,
arg.GrabID,
arg.Name,
arg.Trigger,
arg.Detail,
)
var i DownloadIntervention
err := row.Scan(
&i.ID,
&i.Client,
&i.InfoHash,
&i.GrabID,
&i.Name,
&i.Trigger,
&i.Action,
&i.Outcome,
&i.Detail,
&i.Observations,
&i.Remediations,
&i.FirstSeen,
&i.LastSeen,
&i.SettledAt,
)
return i, err
}
const releaseSeed = `-- name: ReleaseSeed :exec
UPDATE grabs SET seed_released_at = now() WHERE id = $1 AND seed_released_at IS NULL
`
// The seeding download was removed, or found gone.
func (q *Queries) ReleaseSeed(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, releaseSeed, id)
return err
}
const setGrabRatio = `-- name: SetGrabRatio :exec
UPDATE grabs SET ratio = $1 WHERE id = $2
`
type SetGrabRatioParams struct {
Ratio float32
ID pgtype.UUID
}
func (q *Queries) SetGrabRatio(ctx context.Context, arg SetGrabRatioParams) error {
_, err := q.db.Exec(ctx, setGrabRatio, arg.Ratio, arg.ID)
return err
}
const settleEndedGrabs = `-- name: SettleEndedGrabs :execrows
UPDATE download_interventions di
SET outcome = 'resolved', settled_at = now(), last_seen = now()
FROM grabs g
WHERE g.id = di.grab_id AND g.ended_at IS NOT NULL
AND di.outcome = 'open' AND di.trigger <> 'not_removed'
`
// What was wrong with a download whose grab has ended (imported, refused,
// given up) is over, except a download left in the client to remove.
func (q *Queries) SettleEndedGrabs(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, settleEndedGrabs)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const settleIntervention = `-- name: SettleIntervention :execrows
UPDATE download_interventions
SET outcome = 'resolved', settled_at = now(), last_seen = now()
WHERE client = $1 AND info_hash = $2
AND trigger = $3 AND outcome = 'open'
`
type SettleInterventionParams struct {
Client string
InfoHash string
Trigger string
}
// The condition cleared.
func (q *Queries) SettleIntervention(ctx context.Context, arg SettleInterventionParams) (int64, error) {
result, err := q.db.Exec(ctx, settleIntervention, arg.Client, arg.InfoHash, arg.Trigger)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const settleInterventionsFor = `-- name: SettleInterventionsFor :execrows
UPDATE download_interventions
SET outcome = 'resolved', settled_at = now(), last_seen = now()
WHERE client = $1 AND info_hash = $2 AND outcome = 'open'
`
type SettleInterventionsForParams struct {
Client string
InfoHash string
}
// Everything open about one download is over: it is gone from the client.
func (q *Queries) SettleInterventionsFor(ctx context.Context, arg SettleInterventionsForParams) (int64, error) {
result, err := q.db.Exec(ctx, settleInterventionsFor, arg.Client, arg.InfoHash)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
-18
View File
@@ -297,24 +297,6 @@ func (q *Queries) MergeRepointPlaylistTracks(ctx context.Context, arg MergeRepoi
return items, nil
}
const mergeRepointRequests = `-- name: MergeRepointRequests :execrows
UPDATE requests SET matched_track_id = $1::uuid
WHERE matched_track_id = $2::uuid
`
type MergeRepointRequestsParams struct {
SurvivorID pgtype.UUID
LoserID pgtype.UUID
}
func (q *Queries) MergeRepointRequests(ctx context.Context, arg MergeRepointRequestsParams) (int64, error) {
result, err := q.db.Exec(ctx, mergeRepointRequests, arg.SurvivorID, arg.LoserID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const mergeRepointSkipEvents = `-- name: MergeRepointSkipEvents :execrows
UPDATE skip_events SET track_id = $1::uuid WHERE track_id = $2::uuid
`
-272
View File
@@ -1,272 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: reacquisition.sql
package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const countAlbumsMissingWithoutMbid = `-- name: CountAlbumsMissingWithoutMbid :one
SELECT COUNT(DISTINCT albums.id)::bigint
FROM albums
JOIN artists ON artists.id = albums.artist_id
JOIN tracks ON tracks.album_id = albums.id
WHERE tracks.missing_since IS NOT NULL
AND ((albums.mbid IS NULL AND albums.release_group_mbid IS NULL) OR artists.mbid IS NULL)
`
// Albums with missing files that can never be wanted automatically because
// nothing identifies them to MusicBrainz. Surfaced on the admin card so the
// gap is visible: silently doing nothing for these would read as broken.
func (q *Queries) CountAlbumsMissingWithoutMbid(ctx context.Context) (int64, error) {
row := q.db.QueryRow(ctx, countAlbumsMissingWithoutMbid)
var column_1 int64
err := row.Scan(&column_1)
return column_1, err
}
const getReacquisitionSettings = `-- name: GetReacquisitionSettings :one
SELECT id, enabled, grace_hours, max_per_pass FROM reacquisition_settings WHERE id = true
`
// Re-acquisition of missing files.
// The unit is the album: an album whose files went missing becomes a want for
// its release group, and the search schedule looks for it.
func (q *Queries) GetReacquisitionSettings(ctx context.Context) (ReacquisitionSetting, error) {
row := q.db.QueryRow(ctx, getReacquisitionSettings)
var i ReacquisitionSetting
err := row.Scan(
&i.ID,
&i.Enabled,
&i.GraceHours,
&i.MaxPerPass,
)
return i, err
}
const getWantsForAlbums = `-- name: GetWantsForAlbums :many
SELECT a.id AS album_id, w.id AS want_id, w.wanted_at, w.fulfilled_at
FROM albums a
JOIN wants w ON w.album_id = a.id OR w.release_group_mbid = a.release_group_mbid
WHERE a.id = ANY($1::uuid[])
ORDER BY w.wanted_at DESC
`
type GetWantsForAlbumsRow struct {
AlbumID pgtype.UUID
WantID pgtype.UUID
WantedAt pgtype.Timestamptz
FulfilledAt pgtype.Timestamptz
}
// What the wanted list says about each album on the missing-files page.
func (q *Queries) GetWantsForAlbums(ctx context.Context, albumIds []pgtype.UUID) ([]GetWantsForAlbumsRow, error) {
rows, err := q.db.Query(ctx, getWantsForAlbums, albumIds)
if err != nil {
return nil, err
}
defer rows.Close()
var items []GetWantsForAlbumsRow
for rows.Next() {
var i GetWantsForAlbumsRow
if err := rows.Scan(
&i.AlbumID,
&i.WantID,
&i.WantedAt,
&i.FulfilledAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAlbumsDueReacquisition = `-- name: ListAlbumsDueReacquisition :many
SELECT albums.id AS album_id,
albums.title AS album_title,
albums.mbid AS album_mbid,
albums.release_group_mbid AS album_release_group_mbid,
artists.name AS artist_name,
artists.mbid AS artist_mbid,
COUNT(tracks.id)::bigint AS missing_track_count,
MAX(tracks.missing_since)::timestamptz AS last_missing_since
FROM albums
JOIN artists ON artists.id = albums.artist_id
JOIN tracks ON tracks.album_id = albums.id
WHERE tracks.missing_since IS NOT NULL
AND tracks.missing_since <= now() - make_interval(hours => $1::int)
AND (albums.mbid IS NOT NULL OR albums.release_group_mbid IS NOT NULL)
AND artists.mbid IS NOT NULL
GROUP BY albums.id, albums.title, albums.mbid, albums.release_group_mbid,
artists.name, artists.mbid
HAVING EXISTS (
SELECT 1 FROM wants w
WHERE w.album_id = albums.id OR w.release_group_mbid = albums.release_group_mbid)
AND NOT EXISTS (
SELECT 1 FROM wants w
WHERE (w.album_id = albums.id OR w.release_group_mbid = albums.release_group_mbid)
AND (w.fulfilled_at IS NULL OR w.fulfilled_at > MAX(tracks.missing_since)))
ORDER BY MIN(tracks.missing_since), albums.sort_title
LIMIT $2
`
type ListAlbumsDueReacquisitionParams struct {
GraceHours int32
PageLimit int32
}
type ListAlbumsDueReacquisitionRow struct {
AlbumID pgtype.UUID
AlbumTitle string
AlbumMbid *string
AlbumReleaseGroupMbid *string
ArtistName string
ArtistMbid *string
MissingTrackCount int64
LastMissingSince pgtype.Timestamptz
}
// The sweeper's selection. An album qualifies when:
//
// - it still has at least one track whose file has been missing longer than
// the grace window. Measured on missing_since, which reconcile never
// re-stamps, so it is a genuine "gone since" clock;
// - MusicBrainz can name it: the artist has an MBID, and the album a
// release MBID or a release group. The release MBID is only ever used to
// find the group, and an album matched to a group may carry no release
// id. Albums failing this are counted separately
// (CountAlbumsMissingWithoutMbid);
// - it is on the wanted list: an album taken off the list, or
// dropped into the library by hand, is not fetched back;
// - no want already covers it: none open, and none held since its files
// went missing. A want held after the loss means the library has a full
// copy despite the missing rows, so asking again would loop.
func (q *Queries) ListAlbumsDueReacquisition(ctx context.Context, arg ListAlbumsDueReacquisitionParams) ([]ListAlbumsDueReacquisitionRow, error) {
rows, err := q.db.Query(ctx, listAlbumsDueReacquisition, arg.GraceHours, arg.PageLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAlbumsDueReacquisitionRow
for rows.Next() {
var i ListAlbumsDueReacquisitionRow
if err := rows.Scan(
&i.AlbumID,
&i.AlbumTitle,
&i.AlbumMbid,
&i.AlbumReleaseGroupMbid,
&i.ArtistName,
&i.ArtistMbid,
&i.MissingTrackCount,
&i.LastMissingSince,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updateReacquisitionSettings = `-- name: UpdateReacquisitionSettings :one
UPDATE reacquisition_settings
SET enabled = $1,
grace_hours = $2,
max_per_pass = $3
WHERE id = true
RETURNING id, enabled, grace_hours, max_per_pass
`
type UpdateReacquisitionSettingsParams struct {
Enabled bool
GraceHours int32
MaxPerPass int32
}
// Whole-row write from the admin card; the CHECKs in migration 0056 are the
// validation, so a bad value fails loudly rather than being clamped silently.
func (q *Queries) UpdateReacquisitionSettings(ctx context.Context, arg UpdateReacquisitionSettingsParams) (ReacquisitionSetting, error) {
row := q.db.QueryRow(ctx, updateReacquisitionSettings, arg.Enabled, arg.GraceHours, arg.MaxPerPass)
var i ReacquisitionSetting
err := row.Scan(
&i.ID,
&i.Enabled,
&i.GraceHours,
&i.MaxPerPass,
)
return i, err
}
const wantMissingAlbum = `-- name: WantMissingAlbum :one
INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id)
VALUES ($1, $2, $3,
$4, 'missing', $5)
ON CONFLICT (release_group_mbid) DO UPDATE
SET reason = 'missing',
album_id = EXCLUDED.album_id,
wanted_at = now(),
fulfilled_at = NULL,
updated_at = now()
WHERE wants.fulfilled_at IS NOT NULL
RETURNING id, release_group_mbid, artist_mbid, artist_name, title, primary_type, first_release_date, reason, album_id, created_by, wanted_at, fulfilled_at, created_at, updated_at, searched_at, search_outcome, search_considered, best_release, best_verdict, search_error, upgrade, held_tier, held_quality, upgrade_checked_at
`
type WantMissingAlbumParams struct {
ReleaseGroupMbid string
ArtistMbid string
ArtistName string
Title string
AlbumID pgtype.UUID
}
// Records an album with missing files as wanted. A held want for the same
// group is reopened; an open one is left as it is, and no row comes back.
func (q *Queries) WantMissingAlbum(ctx context.Context, arg WantMissingAlbumParams) (Want, error) {
row := q.db.QueryRow(ctx, wantMissingAlbum,
arg.ReleaseGroupMbid,
arg.ArtistMbid,
arg.ArtistName,
arg.Title,
arg.AlbumID,
)
var i Want
err := row.Scan(
&i.ID,
&i.ReleaseGroupMbid,
&i.ArtistMbid,
&i.ArtistName,
&i.Title,
&i.PrimaryType,
&i.FirstReleaseDate,
&i.Reason,
&i.AlbumID,
&i.CreatedBy,
&i.WantedAt,
&i.FulfilledAt,
&i.CreatedAt,
&i.UpdatedAt,
&i.SearchedAt,
&i.SearchOutcome,
&i.SearchConsidered,
&i.BestRelease,
&i.BestVerdict,
&i.SearchError,
&i.Upgrade,
&i.HeldTier,
&i.HeldQuality,
&i.UpgradeCheckedAt,
)
return i, err
}
-149
View File
@@ -1112,152 +1112,3 @@ func (q *Queries) LoadRadioCandidatesV2(ctx context.Context, arg LoadRadioCandid
}
return items, nil
}
const suggestArtistsForUser = `-- name: SuggestArtistsForUser :many
WITH artist_plays AS (
-- Completed plays only: counting every play_event would make skipping an
-- artist repeatedly INCREASE its signal and push more of its neighbours
-- at the user.
SELECT t.artist_id, count(*)::bigint AS play_count
FROM play_events pe
JOIN tracks t ON t.id = pe.track_id
WHERE pe.user_id = $1 AND pe.was_skipped = false
GROUP BY t.artist_id
),
profile_seeds AS (
SELECT tpa.artist_id, tpa.weight AS raw_signal
FROM taste_profile_artists tpa
WHERE tpa.user_id = $1 AND tpa.weight > 0
),
fallback_seeds AS (
SELECT a.id AS artist_id,
5.0 * (CASE WHEN gla.artist_id IS NOT NULL THEN 1 ELSE 0 END)
+ COALESCE(SUM(EXP(- EXTRACT(epoch FROM now() - pe.started_at) / ($2::float8 * 86400.0))), 0)
AS raw_signal
FROM artists a
LEFT JOIN general_likes_artists gla ON gla.artist_id = a.id AND gla.user_id = $1
LEFT JOIN tracks t ON t.artist_id = a.id
LEFT JOIN play_events pe
ON pe.track_id = t.id AND pe.user_id = $1 AND pe.was_skipped = false
WHERE (gla.artist_id IS NOT NULL OR pe.id IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM profile_seeds)
GROUP BY a.id, gla.artist_id
),
seeds AS (
SELECT s.artist_id,
ln(1.0 + s.raw_signal) AS signal,
(gla.artist_id IS NOT NULL) AS is_liked,
COALESCE(ap.play_count, 0)::bigint AS play_count
FROM (
SELECT artist_id, raw_signal FROM profile_seeds
UNION ALL
SELECT artist_id, raw_signal FROM fallback_seeds
) s
LEFT JOIN general_likes_artists gla
ON gla.artist_id = s.artist_id AND gla.user_id = $1
LEFT JOIN artist_plays ap ON ap.artist_id = s.artist_id
WHERE s.raw_signal > 0
),
contributions AS (
SELECT u.candidate_mbid,
u.candidate_name,
seeds.artist_id AS seed_id,
seeds.is_liked,
seeds.play_count,
seeds.signal * u.score AS contribution
FROM artist_similarity_unmatched u
JOIN seeds ON seeds.artist_id = u.seed_artist_id
WHERE NOT EXISTS (SELECT 1 FROM artists WHERE mbid = u.candidate_mbid)
AND NOT EXISTS (
SELECT 1 FROM requests r
WHERE r.user_id = $1
AND r.artist_mbid = u.candidate_mbid
AND r.status NOT IN ('rejected', 'failed')
)
-- Snoozed by this user and not yet expired. Time-boxed and
-- per-user: the candidate returns on its own once snoozed_until
-- passes, and stays visible to everyone else meanwhile. Deliberately
-- filtered at the candidate stage, NOT folded into the score — a
-- snooze carries no opinion about the music, so it must not become a
-- ranking signal.
AND NOT EXISTS (
SELECT 1 FROM suggestion_snoozes s
WHERE s.user_id = $1
AND s.candidate_mbid = u.candidate_mbid
AND s.snoozed_until > now()
)
)
SELECT candidate_mbid,
candidate_name,
SUM(contribution)::float8 AS total_score,
((array_agg(seed_id ORDER BY contribution DESC))[1:3])::uuid[] AS top_seed_ids,
((array_agg(contribution ORDER BY contribution DESC))[1:3])::float8[] AS top_contributions,
((array_agg(is_liked ORDER BY contribution DESC))[1:3])::boolean[] AS top_is_liked,
((array_agg(play_count ORDER BY contribution DESC))[1:3])::bigint[] AS top_play_counts
FROM contributions
GROUP BY candidate_mbid, candidate_name
ORDER BY total_score DESC
LIMIT $3
`
type SuggestArtistsForUserParams struct {
UserID pgtype.UUID
Column2 float64
Limit int32
}
type SuggestArtistsForUserRow struct {
CandidateMbid string
CandidateName string
TotalScore float64
TopSeedIds []pgtype.UUID
TopContributions []float64
TopIsLiked []bool
TopPlayCounts []int64
}
// Per-user artist suggestions ranked by taste signal x similarity, projected
// through artist_similarity_unmatched (out-of-library candidates only).
//
// Seeds are TIERED so the surface never empties:
//
// tier 1 - taste_profile_artists.weight: engagement-graded, time-decayed and
// SIGNED by internal/taste, so an artist the user has drifted away
// from stops contributing instead of accumulating forever.
// tier 2 - likes + completed plays, used ONLY when the profile has no rows
// (new account, or before the first daily recompute).
//
// The signal is log-damped: contribution is signal x similarity, and an
// undamped sum would let one heavily-played artist's neighbours take every
// slot -- entrenching harder the MORE the user listened.
//
// Candidates already in the library, already requested and not terminal, or
// snoozed by this user, are excluded. $1=user_id, $2=half_life_days (tier 2
// decay), $3=limit.
func (q *Queries) SuggestArtistsForUser(ctx context.Context, arg SuggestArtistsForUserParams) ([]SuggestArtistsForUserRow, error) {
rows, err := q.db.Query(ctx, suggestArtistsForUser, arg.UserID, arg.Column2, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []SuggestArtistsForUserRow
for rows.Next() {
var i SuggestArtistsForUserRow
if err := rows.Scan(
&i.CandidateMbid,
&i.CandidateName,
&i.TotalScore,
&i.TopSeedIds,
&i.TopContributions,
&i.TopIsLiked,
&i.TopPlayCounts,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
@@ -9,22 +9,6 @@ import (
"context"
)
const getDiscoverTuning = `-- name: GetDiscoverTuning :one
SELECT singleton, tag_overlap_weight, snooze_days, updated_at FROM discover_tuning WHERE singleton = true
`
func (q *Queries) GetDiscoverTuning(ctx context.Context) (DiscoverTuning, error) {
row := q.db.QueryRow(ctx, getDiscoverTuning)
var i DiscoverTuning
err := row.Scan(
&i.Singleton,
&i.TagOverlapWeight,
&i.SnoozeDays,
&i.UpdatedAt,
)
return i, err
}
const getTasteTuning = `-- name: GetTasteTuning :one
SELECT singleton, half_life_days, engagement_hard_skip, engagement_neutral, engagement_full, updated_at, enriched_tag_scale, era_scale, mood_scale FROM taste_tuning WHERE singleton = true
`
@@ -134,32 +118,6 @@ func (q *Queries) ListWeightProfiles(ctx context.Context) ([]RecommendationWeigh
return items, nil
}
const updateDiscoverTuning = `-- name: UpdateDiscoverTuning :one
UPDATE discover_tuning
SET tag_overlap_weight = $1,
snooze_days = $2,
updated_at = now()
WHERE singleton = true
RETURNING singleton, tag_overlap_weight, snooze_days, updated_at
`
type UpdateDiscoverTuningParams struct {
TagOverlapWeight float64
SnoozeDays float64
}
func (q *Queries) UpdateDiscoverTuning(ctx context.Context, arg UpdateDiscoverTuningParams) (DiscoverTuning, error) {
row := q.db.QueryRow(ctx, updateDiscoverTuning, arg.TagOverlapWeight, arg.SnoozeDays)
var i DiscoverTuning
err := row.Scan(
&i.Singleton,
&i.TagOverlapWeight,
&i.SnoozeDays,
&i.UpdatedAt,
)
return i, err
}
const updateTasteTuning = `-- name: UpdateTasteTuning :one
UPDATE taste_tuning
SET half_life_days = $1,
@@ -268,24 +226,6 @@ func (q *Queries) UpdateWeightProfile(ctx context.Context, arg UpdateWeightProfi
return i, err
}
const upsertDiscoverTuningDefaults = `-- name: UpsertDiscoverTuningDefaults :exec
INSERT INTO discover_tuning (singleton, tag_overlap_weight, snooze_days)
VALUES (true, $1, $2)
ON CONFLICT (singleton) DO NOTHING
`
type UpsertDiscoverTuningDefaultsParams struct {
TagOverlapWeight float64
SnoozeDays float64
}
// Boot reconcile for the Discover scope. Never overwrites
// admin-tuned values, same contract as the other two.
func (q *Queries) UpsertDiscoverTuningDefaults(ctx context.Context, arg UpsertDiscoverTuningDefaultsParams) error {
_, err := q.db.Exec(ctx, upsertDiscoverTuningDefaults, arg.TagOverlapWeight, arg.SnoozeDays)
return err
}
const upsertTasteTuningDefaults = `-- name: UpsertTasteTuningDefaults :exec
INSERT INTO taste_tuning (
singleton, half_life_days, engagement_hard_skip,
-528
View File
@@ -1,528 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: requests.sql
package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const approveRequest = `-- name: ApproveRequest :one
UPDATE requests
SET status = 'approved',
decided_at = now(),
decided_by = $2,
updated_at = now()
WHERE id = $1 AND status = 'pending'
RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at
`
type ApproveRequestParams struct {
ID pgtype.UUID
DecidedBy pgtype.UUID
}
func (q *Queries) ApproveRequest(ctx context.Context, arg ApproveRequestParams) (Request, error) {
row := q.db.QueryRow(ctx, approveRequest, arg.ID, arg.DecidedBy)
var i Request
err := row.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
)
return i, err
}
const cancelRequest = `-- name: CancelRequest :one
UPDATE requests
SET status = 'rejected',
notes = 'cancelled by user',
decided_at = now(),
decided_by = $2,
updated_at = now()
WHERE id = $1 AND user_id = $2 AND status = 'pending'
RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at
`
type CancelRequestParams struct {
ID pgtype.UUID
DecidedBy pgtype.UUID
}
// $2 serves as both the ownership guard (user_id = $2) and the
// decided_by audit field. The generated parameter struct names it
// DecidedBy — callers must pass the cancelling user's UUID, and
// a wrong UUID will silently no-op (zero rows updated) rather than
// erroring at the SQL layer.
func (q *Queries) CancelRequest(ctx context.Context, arg CancelRequestParams) (Request, error) {
row := q.db.QueryRow(ctx, cancelRequest, arg.ID, arg.DecidedBy)
var i Request
err := row.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
)
return i, err
}
const completeRequest = `-- name: CompleteRequest :one
UPDATE requests
SET status = 'completed',
matched_track_id = $2,
matched_album_id = $3,
matched_artist_id = $4,
completed_at = now(),
updated_at = now()
WHERE id = $1 AND status = 'approved'
RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at
`
type CompleteRequestParams struct {
ID pgtype.UUID
MatchedTrackID pgtype.UUID
MatchedAlbumID pgtype.UUID
MatchedArtistID pgtype.UUID
}
// Reconciler transitions an approved request to completed when its
// target track/album/artist has appeared in the library. Callers
// should set ONLY the matched_*_id corresponding to the request's
// kind and pass pgtype.UUID{} (Valid: false) for the others —
// per-kind one-of-three is the contract, NULL for the others
// preserves auditability if the matched row is later evicted.
func (q *Queries) CompleteRequest(ctx context.Context, arg CompleteRequestParams) (Request, error) {
row := q.db.QueryRow(ctx, completeRequest,
arg.ID,
arg.MatchedTrackID,
arg.MatchedAlbumID,
arg.MatchedArtistID,
)
var i Request
err := row.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
)
return i, err
}
const createRequest = `-- name: CreateRequest :one
INSERT INTO requests (
user_id, kind,
artist_mbid, album_mbid, track_mbid,
artist_name, album_title, track_title
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at
`
type CreateRequestParams struct {
UserID pgtype.UUID
Kind RequestKind
ArtistMbid string
AlbumMbid *string
TrackMbid *string
ArtistName string
AlbumTitle *string
TrackTitle *string
}
func (q *Queries) CreateRequest(ctx context.Context, arg CreateRequestParams) (Request, error) {
row := q.db.QueryRow(ctx, createRequest,
arg.UserID,
arg.Kind,
arg.ArtistMbid,
arg.AlbumMbid,
arg.TrackMbid,
arg.ArtistName,
arg.AlbumTitle,
arg.TrackTitle,
)
var i Request
err := row.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
)
return i, err
}
const getNonTerminalRequestForMBID = `-- name: GetNonTerminalRequestForMBID :one
SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests
WHERE status IN ('pending', 'approved', 'completed')
AND ((kind = 'artist' AND artist_mbid = $1)
OR (kind = 'album' AND album_mbid = $1)
OR (kind = 'track' AND track_mbid = $1))
ORDER BY requested_at ASC
LIMIT 1
`
// Returns the oldest non-terminal (pending/approved/completed) request
// whose own-kind MBID matches @mbid, or pgx.ErrNoRows when none. Create()
// uses this to dedupe: a re-request for something already in flight
// returns the existing row instead of inserting a duplicate.
func (q *Queries) GetNonTerminalRequestForMBID(ctx context.Context, mbid string) (Request, error) {
row := q.db.QueryRow(ctx, getNonTerminalRequestForMBID, mbid)
var i Request
err := row.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
)
return i, err
}
const getRequestByID = `-- name: GetRequestByID :one
SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests WHERE id = $1
`
func (q *Queries) GetRequestByID(ctx context.Context, id pgtype.UUID) (Request, error) {
row := q.db.QueryRow(ctx, getRequestByID, id)
var i Request
err := row.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
)
return i, err
}
const hasNonTerminalRequestForMBID = `-- name: HasNonTerminalRequestForMBID :one
SELECT (EXISTS (
SELECT 1 FROM requests r
WHERE r.status IN ('pending', 'approved', 'completed')
AND ((r.kind = 'artist' AND r.artist_mbid = $1)
OR (r.kind = 'album' AND r.album_mbid = $1)
OR (r.kind = 'track' AND r.track_mbid = $1))
) OR EXISTS (
SELECT 1 FROM wants w WHERE w.release_group_mbid = $1 AND w.fulfilled_at IS NULL
) OR EXISTS (
SELECT 1 FROM follows f WHERE f.artist_mbid = $1
))::bool AS requested
`
// Whether something is already on its way: a pending, approved or completed
// request at the given level, an open want for the release group, or a
// follow of the artist. Sets the `requested` flag on catalogue search.
// Terminal-status (rejected, failed) requests do not count. MBIDs are unique
// per entity type, so checking one id against every column cannot
// false-match.
func (q *Queries) HasNonTerminalRequestForMBID(ctx context.Context, mbid string) (bool, error) {
row := q.db.QueryRow(ctx, hasNonTerminalRequestForMBID, mbid)
var requested bool
err := row.Scan(&requested)
return requested, err
}
const listApprovedRequestsForReconcile = `-- name: ListApprovedRequestsForReconcile :many
SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests
WHERE status = 'approved'
ORDER BY decided_at ASC
LIMIT $1
`
func (q *Queries) ListApprovedRequestsForReconcile(ctx context.Context, limit int32) ([]Request, error) {
rows, err := q.db.Query(ctx, listApprovedRequestsForReconcile, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Request
for rows.Next() {
var i Request
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listRequestsByStatus = `-- name: ListRequestsByStatus :many
SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests
WHERE status = $1
ORDER BY requested_at DESC
LIMIT $2
`
type ListRequestsByStatusParams struct {
Status RequestStatus
Limit int32
}
func (q *Queries) ListRequestsByStatus(ctx context.Context, arg ListRequestsByStatusParams) ([]Request, error) {
rows, err := q.db.Query(ctx, listRequestsByStatus, arg.Status, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Request
for rows.Next() {
var i Request
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listRequestsForUser = `-- name: ListRequestsForUser :many
SELECT id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at FROM requests
WHERE user_id = $1
ORDER BY requested_at DESC
LIMIT $2
`
type ListRequestsForUserParams struct {
UserID pgtype.UUID
Limit int32
}
func (q *Queries) ListRequestsForUser(ctx context.Context, arg ListRequestsForUserParams) ([]Request, error) {
rows, err := q.db.Query(ctx, listRequestsForUser, arg.UserID, arg.Limit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Request
for rows.Next() {
var i Request
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const rejectRequest = `-- name: RejectRequest :one
UPDATE requests
SET status = 'rejected',
notes = $2,
decided_at = now(),
decided_by = $3,
updated_at = now()
WHERE id = $1 AND status = 'pending'
RETURNING id, user_id, status, kind, artist_mbid, album_mbid, track_mbid, artist_name, album_title, track_title, decided_at, decided_by, notes, completed_at, matched_track_id, matched_album_id, matched_artist_id, requested_at, updated_at
`
type RejectRequestParams struct {
ID pgtype.UUID
Notes *string
DecidedBy pgtype.UUID
}
func (q *Queries) RejectRequest(ctx context.Context, arg RejectRequestParams) (Request, error) {
row := q.db.QueryRow(ctx, rejectRequest, arg.ID, arg.Notes, arg.DecidedBy)
var i Request
err := row.Scan(
&i.ID,
&i.UserID,
&i.Status,
&i.Kind,
&i.ArtistMbid,
&i.AlbumMbid,
&i.TrackMbid,
&i.ArtistName,
&i.AlbumTitle,
&i.TrackTitle,
&i.DecidedAt,
&i.DecidedBy,
&i.Notes,
&i.CompletedAt,
&i.MatchedTrackID,
&i.MatchedAlbumID,
&i.MatchedArtistID,
&i.RequestedAt,
&i.UpdatedAt,
)
return i, err
}
const repointRequestsAlbumMbid = `-- name: RepointRequestsAlbumMbid :exec
UPDATE requests
SET album_mbid = $1,
updated_at = now()
WHERE album_mbid = $2
`
type RepointRequestsAlbumMbidParams struct {
NewMbid *string
OldMbid *string
}
// A want moved from a release id to its group takes the requests
// that name it along, so the reconciler finds it.
func (q *Queries) RepointRequestsAlbumMbid(ctx context.Context, arg RepointRequestsAlbumMbidParams) error {
_, err := q.db.Exec(ctx, repointRequestsAlbumMbid, arg.NewMbid, arg.OldMbid)
return err
}
-680
View File
@@ -1,680 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: search.sql
package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const blockRelease = `-- name: BlockRelease :exec
INSERT INTO release_blocks (info_hash, name, reason, detail, want_id, blocked_by, expires_at)
VALUES ($1, $2, $3, $4,
$5, $6, $7)
ON CONFLICT (info_hash) DO UPDATE
SET reason = EXCLUDED.reason, detail = EXCLUDED.detail, blocked_at = now(),
expires_at = EXCLUDED.expires_at, blocked_by = EXCLUDED.blocked_by
WHERE release_blocks.expires_at IS NOT NULL OR EXCLUDED.expires_at IS NULL
`
type BlockReleaseParams struct {
InfoHash string
Name string
Reason string
Detail string
WantID pgtype.UUID
BlockedBy pgtype.UUID
ExpiresAt pgtype.Timestamptz
}
// A release set aside. expires_at NULL is for good. A block for good is never
// shortened by a timed one: only a timed block, or another for good, is
// replaced.
func (q *Queries) BlockRelease(ctx context.Context, arg BlockReleaseParams) error {
_, err := q.db.Exec(ctx, blockRelease,
arg.InfoHash,
arg.Name,
arg.Reason,
arg.Detail,
arg.WantID,
arg.BlockedBy,
arg.ExpiresAt,
)
return err
}
const deleteWantCandidates = `-- name: DeleteWantCandidates :exec
DELETE FROM want_candidates WHERE want_id = $1
`
func (q *Queries) DeleteWantCandidates(ctx context.Context, wantID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteWantCandidates, wantID)
return err
}
const editionTrackSpan = `-- name: EditionTrackSpan :one
SELECT COALESCE(MIN(track_count) FILTER (WHERE status = 'Official'), MIN(track_count), 0)::int AS min_tracks,
COALESCE(MAX(track_count), 0)::int AS max_tracks
FROM mb_releases
WHERE release_group_mbid = $1 AND track_count > 0
`
type EditionTrackSpanRow struct {
MinTracks int32
MaxTracks int32
}
// The fewest tracks an official edition of the group has (any edition when
// none is official), and the most any has. Zero when none is catalogued.
func (q *Queries) EditionTrackSpan(ctx context.Context, releaseGroupMbid string) (EditionTrackSpanRow, error) {
row := q.db.QueryRow(ctx, editionTrackSpan, releaseGroupMbid)
var i EditionTrackSpanRow
err := row.Scan(&i.MinTracks, &i.MaxTracks)
return i, err
}
const endGrab = `-- name: EndGrab :exec
UPDATE grabs
SET ended_at = now(), end_reason = $1, end_detail = $2
WHERE id = $3 AND ended_at IS NULL
`
type EndGrabParams struct {
EndReason string
EndDetail string
ID pgtype.UUID
}
func (q *Queries) EndGrab(ctx context.Context, arg EndGrabParams) error {
_, err := q.db.Exec(ctx, endGrab, arg.EndReason, arg.EndDetail, arg.ID)
return err
}
const getAcquisitionSettings = `-- name: GetAcquisitionSettings :one
SELECT id, auto_grab, search_interval_hours, allowed_qualities, last_pass_at, last_pass, updated_at, import_root, seed_ratio, seed_days, stall_hours, library_listing_started_at, library_listed_at, library_unlisted, upgrade_until FROM acquisition_settings WHERE id = true
`
// Searching for wants and grabbing releases.
func (q *Queries) GetAcquisitionSettings(ctx context.Context) (AcquisitionSetting, error) {
row := q.db.QueryRow(ctx, getAcquisitionSettings)
var i AcquisitionSetting
err := row.Scan(
&i.ID,
&i.AutoGrab,
&i.SearchIntervalHours,
&i.AllowedQualities,
&i.LastPassAt,
&i.LastPass,
&i.UpdatedAt,
&i.ImportRoot,
&i.SeedRatio,
&i.SeedDays,
&i.StallHours,
&i.LibraryListingStartedAt,
&i.LibraryListedAt,
&i.LibraryUnlisted,
&i.UpgradeUntil,
)
return i, err
}
const getLiveGrab = `-- name: GetLiveGrab :one
SELECT id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at FROM grabs WHERE want_id = $1 AND ended_at IS NULL
`
func (q *Queries) GetLiveGrab(ctx context.Context, wantID pgtype.UUID) (Grab, error) {
row := q.db.QueryRow(ctx, getLiveGrab, wantID)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const getWantCandidate = `-- name: GetWantCandidate :one
SELECT want_id, key, name, info_hash, indexer, source, size_bytes, seeders, files_count, format, quality, year, verdict, reason, reasons, folded_from, rank, searched_at FROM want_candidates WHERE want_id = $1 AND key = $2
`
type GetWantCandidateParams struct {
WantID pgtype.UUID
Key string
}
func (q *Queries) GetWantCandidate(ctx context.Context, arg GetWantCandidateParams) (WantCandidate, error) {
row := q.db.QueryRow(ctx, getWantCandidate, arg.WantID, arg.Key)
var i WantCandidate
err := row.Scan(
&i.WantID,
&i.Key,
&i.Name,
&i.InfoHash,
&i.Indexer,
&i.Source,
&i.SizeBytes,
&i.Seeders,
&i.FilesCount,
&i.Format,
&i.Quality,
&i.Year,
&i.Verdict,
&i.Reason,
&i.Reasons,
&i.FoldedFrom,
&i.Rank,
&i.SearchedAt,
)
return i, err
}
const getWantForSearch = `-- name: GetWantForSearch :one
SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.reason, w.fulfilled_at,
w.upgrade, w.held_tier, w.held_quality, w.album_id,
COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type,
COALESCE(g.secondary_types, '{}')::text[] AS secondary_types,
COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date
FROM wants w
LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid
WHERE w.id = $1
`
type GetWantForSearchRow struct {
ID pgtype.UUID
ReleaseGroupMbid string
ArtistMbid string
ArtistName string
Title string
Reason string
FulfilledAt pgtype.Timestamptz
Upgrade string
HeldTier string
HeldQuality string
AlbumID pgtype.UUID
PrimaryType string
SecondaryTypes []string
FirstReleaseDate string
}
func (q *Queries) GetWantForSearch(ctx context.Context, id pgtype.UUID) (GetWantForSearchRow, error) {
row := q.db.QueryRow(ctx, getWantForSearch, id)
var i GetWantForSearchRow
err := row.Scan(
&i.ID,
&i.ReleaseGroupMbid,
&i.ArtistMbid,
&i.ArtistName,
&i.Title,
&i.Reason,
&i.FulfilledAt,
&i.Upgrade,
&i.HeldTier,
&i.HeldQuality,
&i.AlbumID,
&i.PrimaryType,
&i.SecondaryTypes,
&i.FirstReleaseDate,
)
return i, err
}
const insertGrab = `-- name: InsertGrab :one
INSERT INTO grabs (want_id, info_hash, name, key, indexer, source, client, save_path, quality,
origin, forced, grabbed_by)
VALUES ($1, $2, $3, $4, $5,
$6, $7, $8, $9,
$10, $11, $12)
RETURNING id, want_id, info_hash, name, key, indexer, source, client, save_path, quality, origin, forced, grabbed_by, grabbed_at, ended_at, end_reason, end_detail, progress, import_state, import_reason, import_detail, import_forced, import_attempts, import_updated_at, imported_at, imported_files, destination, seeding, ratio, seed_released_at
`
type InsertGrabParams struct {
WantID pgtype.UUID
InfoHash string
Name string
Key string
Indexer string
Source string
Client string
SavePath string
Quality string
Origin string
Forced bool
GrabbedBy pgtype.UUID
}
func (q *Queries) InsertGrab(ctx context.Context, arg InsertGrabParams) (Grab, error) {
row := q.db.QueryRow(ctx, insertGrab,
arg.WantID,
arg.InfoHash,
arg.Name,
arg.Key,
arg.Indexer,
arg.Source,
arg.Client,
arg.SavePath,
arg.Quality,
arg.Origin,
arg.Forced,
arg.GrabbedBy,
)
var i Grab
err := row.Scan(
&i.ID,
&i.WantID,
&i.InfoHash,
&i.Name,
&i.Key,
&i.Indexer,
&i.Source,
&i.Client,
&i.SavePath,
&i.Quality,
&i.Origin,
&i.Forced,
&i.GrabbedBy,
&i.GrabbedAt,
&i.EndedAt,
&i.EndReason,
&i.EndDetail,
&i.Progress,
&i.ImportState,
&i.ImportReason,
&i.ImportDetail,
&i.ImportForced,
&i.ImportAttempts,
&i.ImportUpdatedAt,
&i.ImportedAt,
&i.ImportedFiles,
&i.Destination,
&i.Seeding,
&i.Ratio,
&i.SeedReleasedAt,
)
return i, err
}
const insertWantCandidate = `-- name: InsertWantCandidate :exec
INSERT INTO want_candidates (want_id, key, name, info_hash, indexer, source, size_bytes, seeders,
files_count, format, quality, year, verdict, reason, reasons, folded_from, rank)
VALUES ($1, $2, $3, $4, $5,
$6, $7, $8, $9, $10,
$11, $12, $13, $14, $15,
$16, $17)
ON CONFLICT (want_id, key) DO NOTHING
`
type InsertWantCandidateParams struct {
WantID pgtype.UUID
Key string
Name string
InfoHash string
Indexer string
Source string
SizeBytes int64
Seeders int32
FilesCount int32
Format string
Quality string
Year int32
Verdict string
Reason string
Reasons []byte
FoldedFrom []string
Rank int32
}
func (q *Queries) InsertWantCandidate(ctx context.Context, arg InsertWantCandidateParams) error {
_, err := q.db.Exec(ctx, insertWantCandidate,
arg.WantID,
arg.Key,
arg.Name,
arg.InfoHash,
arg.Indexer,
arg.Source,
arg.SizeBytes,
arg.Seeders,
arg.FilesCount,
arg.Format,
arg.Quality,
arg.Year,
arg.Verdict,
arg.Reason,
arg.Reasons,
arg.FoldedFrom,
arg.Rank,
)
return err
}
const listReleaseBlocks = `-- name: ListReleaseBlocks :many
SELECT info_hash, name, reason, detail, want_id, blocked_by, blocked_at, expires_at FROM release_blocks
WHERE expires_at IS NULL OR expires_at > now()
ORDER BY blocked_at DESC
`
// Every release set aside and still held back: a stalled one lifts by itself
// at expires_at.
func (q *Queries) ListReleaseBlocks(ctx context.Context) ([]ReleaseBlock, error) {
rows, err := q.db.Query(ctx, listReleaseBlocks)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ReleaseBlock
for rows.Next() {
var i ReleaseBlock
if err := rows.Scan(
&i.InfoHash,
&i.Name,
&i.Reason,
&i.Detail,
&i.WantID,
&i.BlockedBy,
&i.BlockedAt,
&i.ExpiresAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listWantCandidates = `-- name: ListWantCandidates :many
SELECT want_id, key, name, info_hash, indexer, source, size_bytes, seeders, files_count, format, quality, year, verdict, reason, reasons, folded_from, rank, searched_at FROM want_candidates WHERE want_id = $1 ORDER BY rank, key
`
func (q *Queries) ListWantCandidates(ctx context.Context, wantID pgtype.UUID) ([]WantCandidate, error) {
rows, err := q.db.Query(ctx, listWantCandidates, wantID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []WantCandidate
for rows.Next() {
var i WantCandidate
if err := rows.Scan(
&i.WantID,
&i.Key,
&i.Name,
&i.InfoHash,
&i.Indexer,
&i.Source,
&i.SizeBytes,
&i.Seeders,
&i.FilesCount,
&i.Format,
&i.Quality,
&i.Year,
&i.Verdict,
&i.Reason,
&i.Reasons,
&i.FoldedFrom,
&i.Rank,
&i.SearchedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listWantsDueForSearch = `-- name: ListWantsDueForSearch :many
SELECT w.id, w.release_group_mbid, w.artist_name, w.title, w.reason, w.upgrade, w.held_tier, w.held_quality,
COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type,
COALESCE(g.secondary_types, '{}')::text[] AS secondary_types,
COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date
FROM wants w
LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid
WHERE (w.fulfilled_at IS NULL OR w.upgrade <> '')
AND NOT EXISTS (SELECT 1 FROM grabs gr WHERE gr.want_id = w.id AND gr.ended_at IS NULL)
AND (w.searched_at IS NULL
OR w.searched_at < now() - make_interval(hours => CASE WHEN w.fulfilled_at IS NULL
THEN $1::int
ELSE GREATEST($1::int, 168) END))
ORDER BY w.fulfilled_at IS NOT NULL,
w.searched_at IS NOT NULL,
CASE w.reason WHEN 'request' THEN 0 WHEN 'missing' THEN 1 ELSE 2 END,
w.searched_at NULLS FIRST, w.wanted_at, w.id
LIMIT $2
`
type ListWantsDueForSearchParams struct {
Hours int32
MaxRows int32
}
type ListWantsDueForSearchRow struct {
ID pgtype.UUID
ReleaseGroupMbid string
ArtistName string
Title string
Reason string
Upgrade string
HeldTier string
HeldQuality string
PrimaryType string
SecondaryTypes []string
FirstReleaseDate string
}
// Wants with no download running that were never searched or not since
// @hours ago: open wants first (never-searched, then requests, then missing
// files, then followed artists' releases), then held albums wanted for an
// upgrade, which are searched at most weekly.
func (q *Queries) ListWantsDueForSearch(ctx context.Context, arg ListWantsDueForSearchParams) ([]ListWantsDueForSearchRow, error) {
rows, err := q.db.Query(ctx, listWantsDueForSearch, arg.Hours, arg.MaxRows)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListWantsDueForSearchRow
for rows.Next() {
var i ListWantsDueForSearchRow
if err := rows.Scan(
&i.ID,
&i.ReleaseGroupMbid,
&i.ArtistName,
&i.Title,
&i.Reason,
&i.Upgrade,
&i.HeldTier,
&i.HeldQuality,
&i.PrimaryType,
&i.SecondaryTypes,
&i.FirstReleaseDate,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const markCandidatesBlocked = `-- name: MarkCandidatesBlocked :exec
UPDATE want_candidates
SET verdict = 'blocked', reason = $1,
reasons = jsonb_build_array(jsonb_build_object('kind', 'hard', 'code', 'blocked', 'text', $1::text))
WHERE info_hash = $2
`
type MarkCandidatesBlockedParams struct {
Reason string
InfoHash string
}
func (q *Queries) MarkCandidatesBlocked(ctx context.Context, arg MarkCandidatesBlockedParams) error {
_, err := q.db.Exec(ctx, markCandidatesBlocked, arg.Reason, arg.InfoHash)
return err
}
const markCandidatesUnblocked = `-- name: MarkCandidatesUnblocked :exec
UPDATE want_candidates
SET verdict = 'review', reason = $1,
reasons = jsonb_build_array(jsonb_build_object('kind', 'soft', 'code', 'unblocked', 'text', $1::text))
WHERE info_hash = $2 AND verdict = 'blocked'
`
type MarkCandidatesUnblockedParams struct {
Reason string
InfoHash string
}
func (q *Queries) MarkCandidatesUnblocked(ctx context.Context, arg MarkCandidatesUnblockedParams) error {
_, err := q.db.Exec(ctx, markCandidatesUnblocked, arg.Reason, arg.InfoHash)
return err
}
const recordSearchPass = `-- name: RecordSearchPass :exec
UPDATE acquisition_settings SET last_pass_at = now(), last_pass = $1 WHERE id = true
`
func (q *Queries) RecordSearchPass(ctx context.Context, report []byte) error {
_, err := q.db.Exec(ctx, recordSearchPass, report)
return err
}
const recordWantSearch = `-- name: RecordWantSearch :exec
UPDATE wants
SET searched_at = now(),
search_outcome = $1,
search_considered = $2,
best_release = $3,
best_verdict = $4,
search_error = $5,
updated_at = now()
WHERE id = $6
`
type RecordWantSearchParams struct {
Outcome string
Considered int32
BestRelease string
BestVerdict string
SearchError string
ID pgtype.UUID
}
func (q *Queries) RecordWantSearch(ctx context.Context, arg RecordWantSearchParams) error {
_, err := q.db.Exec(ctx, recordWantSearch,
arg.Outcome,
arg.Considered,
arg.BestRelease,
arg.BestVerdict,
arg.SearchError,
arg.ID,
)
return err
}
const unblockRelease = `-- name: UnblockRelease :execrows
DELETE FROM release_blocks WHERE info_hash = $1
`
func (q *Queries) UnblockRelease(ctx context.Context, infoHash string) (int64, error) {
result, err := q.db.Exec(ctx, unblockRelease, infoHash)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateAcquisitionSettings = `-- name: UpdateAcquisitionSettings :one
UPDATE acquisition_settings
SET auto_grab = $1,
search_interval_hours = $2,
allowed_qualities = $3,
import_root = $4,
seed_ratio = $5,
seed_days = $6,
stall_hours = $7,
upgrade_until = $8,
updated_at = now()
WHERE id = true
RETURNING id, auto_grab, search_interval_hours, allowed_qualities, last_pass_at, last_pass, updated_at, import_root, seed_ratio, seed_days, stall_hours, library_listing_started_at, library_listed_at, library_unlisted, upgrade_until
`
type UpdateAcquisitionSettingsParams struct {
AutoGrab bool
SearchIntervalHours int32
AllowedQualities []string
ImportRoot string
SeedRatio float32
SeedDays int32
StallHours int32
UpgradeUntil string
}
func (q *Queries) UpdateAcquisitionSettings(ctx context.Context, arg UpdateAcquisitionSettingsParams) (AcquisitionSetting, error) {
row := q.db.QueryRow(ctx, updateAcquisitionSettings,
arg.AutoGrab,
arg.SearchIntervalHours,
arg.AllowedQualities,
arg.ImportRoot,
arg.SeedRatio,
arg.SeedDays,
arg.StallHours,
arg.UpgradeUntil,
)
var i AcquisitionSetting
err := row.Scan(
&i.ID,
&i.AutoGrab,
&i.SearchIntervalHours,
&i.AllowedQualities,
&i.LastPassAt,
&i.LastPass,
&i.UpdatedAt,
&i.ImportRoot,
&i.SeedRatio,
&i.SeedDays,
&i.StallHours,
&i.LibraryListingStartedAt,
&i.LibraryListedAt,
&i.LibraryUnlisted,
&i.UpgradeUntil,
)
return i, err
}
-32
View File
@@ -340,35 +340,3 @@ func (q *Queries) UpsertArtistSimilarity(ctx context.Context, arg UpsertArtistSi
_, err := q.db.Exec(ctx, upsertArtistSimilarity, arg.ArtistAID, arg.ArtistBID, arg.Score)
return err
}
const upsertArtistSimilarityUnmatched = `-- name: UpsertArtistSimilarityUnmatched :exec
INSERT INTO artist_similarity_unmatched (
seed_artist_id, candidate_mbid, candidate_name, score, source
) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (seed_artist_id, candidate_mbid, source) DO UPDATE SET
candidate_name = EXCLUDED.candidate_name,
score = EXCLUDED.score,
fetched_at = now()
`
type UpsertArtistSimilarityUnmatchedParams struct {
SeedArtistID pgtype.UUID
CandidateMbid string
CandidateName string
Score float64
Source string
}
// Persists an out-of-library similar-artist MBID. Idempotent on
// (seed_artist_id, candidate_mbid, source) — re-fetches refresh the
// name/score and bump fetched_at.
func (q *Queries) UpsertArtistSimilarityUnmatched(ctx context.Context, arg UpsertArtistSimilarityUnmatchedParams) error {
_, err := q.db.Exec(ctx, upsertArtistSimilarityUnmatched,
arg.SeedArtistID,
arg.CandidateMbid,
arg.CandidateName,
arg.Score,
arg.Source,
)
return err
}
-126
View File
@@ -1,126 +0,0 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: suggestion_snoozes.sql
package dbq
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const gcDeleteExpiredSuggestionSnoozes = `-- name: GcDeleteExpiredSuggestionSnoozes :execrows
DELETE FROM suggestion_snoozes WHERE snoozed_until < now()
`
// Keeps the table from growing without bound. Every read already filters on
// snoozed_until > now(), so deleting an expired row changes no behaviour —
// this is purely reclamation.
func (q *Queries) GcDeleteExpiredSuggestionSnoozes(ctx context.Context) (int64, error) {
result, err := q.db.Exec(ctx, gcDeleteExpiredSuggestionSnoozes)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const listActiveSuggestionSnoozes = `-- name: ListActiveSuggestionSnoozes :many
SELECT candidate_mbid, candidate_name, snoozed_until, created_at
FROM suggestion_snoozes
WHERE user_id = $1 AND snoozed_until > now()
ORDER BY snoozed_until, candidate_mbid
`
type ListActiveSuggestionSnoozesRow struct {
CandidateMbid string
CandidateName string
SnoozedUntil pgtype.Timestamptz
CreatedAt pgtype.Timestamptz
}
// Backs the manage / un-snooze surface. Expired rows are filtered HERE
// rather than left to the sweeper: gc runs on an hourly tick, so a row can
// outlive its expiry by up to a tick and must not read as still-snoozed in
// the meantime.
func (q *Queries) ListActiveSuggestionSnoozes(ctx context.Context, userID pgtype.UUID) ([]ListActiveSuggestionSnoozesRow, error) {
rows, err := q.db.Query(ctx, listActiveSuggestionSnoozes, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListActiveSuggestionSnoozesRow
for rows.Next() {
var i ListActiveSuggestionSnoozesRow
if err := rows.Scan(
&i.CandidateMbid,
&i.CandidateName,
&i.SnoozedUntil,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const snoozeSuggestion = `-- name: SnoozeSuggestion :exec
INSERT INTO suggestion_snoozes (user_id, candidate_mbid, candidate_name, snoozed_until)
VALUES ($1, $2, $3, now() + ($4::float8 * INTERVAL '1 day'))
ON CONFLICT (user_id, candidate_mbid) DO UPDATE
SET snoozed_until = EXCLUDED.snoozed_until,
candidate_name = EXCLUDED.candidate_name
`
type SnoozeSuggestionParams struct {
UserID pgtype.UUID
CandidateMbid string
CandidateName string
Column4 float64
}
// Time-boxed "not right now" on a Discover artist suggestion.
//
// See 0049_suggestion_snoozes.up.sql for why this is a snooze and not a
// dismissal: it records no verdict on the music, expires on its own, and
// must never reach the taste profile. Nothing in internal/taste may read
// this table.
// Upsert, so re-snoozing an already-snoozed candidate EXTENDS it instead of
// erroring on the PK. The name is refreshed too — a later suggestion may
// carry a corrected spelling from the similarity feed.
// $1=user_id, $2=candidate_mbid, $3=candidate_name, $4=duration in days.
func (q *Queries) SnoozeSuggestion(ctx context.Context, arg SnoozeSuggestionParams) error {
_, err := q.db.Exec(ctx, snoozeSuggestion,
arg.UserID,
arg.CandidateMbid,
arg.CandidateName,
arg.Column4,
)
return err
}
const unsnoozeSuggestion = `-- name: UnsnoozeSuggestion :execrows
DELETE FROM suggestion_snoozes
WHERE user_id = $1 AND candidate_mbid = $2
`
type UnsnoozeSuggestionParams struct {
UserID pgtype.UUID
CandidateMbid string
}
// Row count is returned so the handler can 404 an MBID that was never
// snoozed rather than reporting success for a no-op.
func (q *Queries) UnsnoozeSuggestion(ctx context.Context, arg UnsnoozeSuggestionParams) (int64, error) {
result, err := q.db.Exec(ctx, unsnoozeSuggestion, arg.UserID, arg.CandidateMbid)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
+1 -13
View File
@@ -716,18 +716,10 @@ SELECT t.id,
artists.id AS artist_id,
artists.name AS artist_name,
t.source_verdict,
t.source_verdict_at,
-- The album's place on the wanted list: wanted for a clean copy, and
-- when that was last searched for.
COALESCE(w.upgrade, '')::text AS want_upgrade,
w.searched_at AS searched_at
t.source_verdict_at
FROM tracks t
JOIN albums ON albums.id = t.album_id
JOIN artists ON artists.id = t.artist_id
LEFT JOIN LATERAL (
SELECT x.upgrade, x.searched_at FROM wants x
WHERE x.album_id = albums.id AND x.fulfilled_at IS NOT NULL LIMIT 1
) w ON true
WHERE t.missing_since IS NULL
AND regexp_replace(t.file_path, '^.*/', '') ~* $1::text
ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title
@@ -754,8 +746,6 @@ type ListSuspectSourceTracksRow struct {
ArtistName string
SourceVerdict *string
SourceVerdictAt pgtype.Timestamptz
WantUpgrade string
SearchedAt pgtype.Timestamptz
}
// The admin report of present tracks whose filename looks like a video rip
@@ -791,8 +781,6 @@ func (q *Queries) ListSuspectSourceTracks(ctx context.Context, arg ListSuspectSo
&i.ArtistName,
&i.SourceVerdict,
&i.SourceVerdictAt,
&i.WantUpgrade,
&i.SearchedAt,
); err != nil {
return nil, err
}
+1 -38
View File
@@ -397,8 +397,7 @@ type ListUsernamesByIDsRow struct {
Username string
}
// Names a list's people in one round trip, e.g. who made each request on
// /admin/requests.
// Names a list's people in one round trip.
func (q *Queries) ListUsernamesByIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([]ListUsernamesByIDsRow, error) {
rows, err := q.db.Query(ctx, listUsernamesByIDs, dollar_1)
if err != nil {
@@ -627,42 +626,6 @@ func (q *Queries) UpdateUserAdmin(ctx context.Context, arg UpdateUserAdminParams
return i, err
}
const updateUserAutoApprove = `-- name: UpdateUserAutoApprove :one
UPDATE users
SET auto_approve_requests = $2
WHERE id = $1
RETURNING id, username, password_hash, is_admin, created_at, subsonic_password, listenbrainz_token, listenbrainz_enabled, display_name, auto_approve_requests, email, timezone, timezone_updated_at, debug_mode_enabled, api_token_hash
`
type UpdateUserAutoApproveParams struct {
ID pgtype.UUID
AutoApproveRequests bool
}
// Toggle the per-user auto_approve_requests flag.
func (q *Queries) UpdateUserAutoApprove(ctx context.Context, arg UpdateUserAutoApproveParams) (User, error) {
row := q.db.QueryRow(ctx, updateUserAutoApprove, arg.ID, arg.AutoApproveRequests)
var i User
err := row.Scan(
&i.ID,
&i.Username,
&i.PasswordHash,
&i.IsAdmin,
&i.CreatedAt,
&i.SubsonicPassword,
&i.ListenbrainzToken,
&i.ListenbrainzEnabled,
&i.DisplayName,
&i.AutoApproveRequests,
&i.Email,
&i.Timezone,
&i.TimezoneUpdatedAt,
&i.DebugModeEnabled,
&i.ApiTokenHash,
)
return i, err
}
const updateUserProfile = `-- name: UpdateUserProfile :one
UPDATE users
SET display_name = $2,
File diff suppressed because it is too large Load Diff
-76
View File
@@ -1,76 +0,0 @@
-- Indexers and download clients.
-- name: ListAcquisitionServices :many
-- Returns no secret, only whether one is set: this feeds the settings page.
SELECT code, kind, protocol, label, enabled, base_url,
(api_key <> '')::boolean AS has_api_key,
(password <> '')::boolean AS has_password,
username, category, timeout_ms,
serves_search, serves_downloads, serves_enrichment,
local_path, remote_path, searches_per_hour,
created_at, updated_at
FROM acquisition_services
ORDER BY kind, label, code;
-- name: GetAcquisitionService :one
-- The full row, credentials included. For building a client, never for a
-- response.
SELECT * FROM acquisition_services WHERE code = sqlc.arg(code);
-- name: ListUsableAcquisitionServices :many
-- Every enabled, addressed service doing one job. An exchange row does a job
-- when its switch for it is on; any other row does the job its kind names.
-- Ordered by code so a fan-out is deterministic.
SELECT * FROM acquisition_services
WHERE enabled AND base_url <> ''
AND CASE WHEN protocol = 'exchange' THEN
CASE sqlc.arg(job)::text
WHEN 'search' THEN serves_search
WHEN 'download' THEN serves_downloads
WHEN 'enrichment' THEN serves_enrichment
ELSE false
END
ELSE kind = sqlc.arg(job)::text
END
ORDER BY code;
-- name: CreateAcquisitionService :one
-- ON CONFLICT so the caller can try the next code when this one is taken.
INSERT INTO acquisition_services
(code, kind, protocol, label, category, timeout_ms, searches_per_hour)
VALUES
(sqlc.arg(code), sqlc.arg(kind), sqlc.arg(protocol), sqlc.arg(label),
sqlc.arg(category), sqlc.arg(timeout_ms), sqlc.arg(searches_per_hour))
ON CONFLICT (code) DO NOTHING
RETURNING *;
-- name: UpdateAcquisitionService :one
-- Everything on the settings form except the credentials, which have their
-- own write-only calls.
UPDATE acquisition_services SET
label = sqlc.arg(label),
enabled = sqlc.arg(enabled),
base_url = sqlc.arg(base_url),
username = sqlc.arg(username),
category = sqlc.arg(category),
timeout_ms = sqlc.arg(timeout_ms),
serves_search = sqlc.arg(serves_search),
serves_downloads = sqlc.arg(serves_downloads),
serves_enrichment = sqlc.arg(serves_enrichment),
local_path = sqlc.arg(local_path),
remote_path = sqlc.arg(remote_path),
searches_per_hour = sqlc.arg(searches_per_hour),
updated_at = now()
WHERE code = sqlc.arg(code)
RETURNING *;
-- name: DeleteAcquisitionService :execrows
DELETE FROM acquisition_services WHERE code = sqlc.arg(code);
-- name: SetAcquisitionServiceAPIKey :execrows
UPDATE acquisition_services SET api_key = sqlc.arg(api_key), updated_at = now()
WHERE code = sqlc.arg(code);
-- name: SetAcquisitionServicePassword :execrows
UPDATE acquisition_services SET password = sqlc.arg(password), updated_at = now()
WHERE code = sqlc.arg(code);
+2 -16
View File
@@ -1,5 +1,5 @@
-- The admin Overview's status sections: who is listening, what is
-- downloading, what the library holds. Each is one cheap read.
-- The admin Overview's status sections: who is listening and what the
-- library holds. Each is one cheap read.
-- name: ListListeningNow :many
-- Plays in progress: open play events still inside their track's length,
@@ -29,20 +29,6 @@ SELECT COUNT(*)::bigint AS plays,
FROM play_events
WHERE started_at > now() - INTERVAL '24 hours';
-- name: DownloadsStatus :one
-- Downloads at a glance: running, waiting on a person (and since when), and
-- the last day's imports and give-ups.
SELECT COUNT(*) FILTER (WHERE ended_at IS NULL AND import_state IN ('', 'downloading', 'waiting', 'importing'))::bigint AS running,
COUNT(*) FILTER (WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::bigint AS needs_you,
MIN(COALESCE(import_updated_at, grabbed_at)) FILTER (WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::timestamptz AS needs_you_since,
COUNT(*) FILTER (WHERE imported_at > now() - INTERVAL '24 hours')::bigint AS imported_day,
COUNT(*) FILTER (WHERE ended_at > now() - INTERVAL '24 hours'
AND end_reason IN ('stalled', 'failed', 'gone', 'abandoned'))::bigint AS given_up_day
FROM grabs
WHERE ended_at IS NULL
OR ended_at > now() - INTERVAL '24 hours'
OR imported_at > now() - INTERVAL '24 hours';
-- name: LibraryStatus :one
-- What the library holds on disk: tracks whose files are present, the
-- albums and artists they make, and their size.
-2
View File
@@ -5,8 +5,6 @@
-- oldest item still waiting: how long the queue has been left, which is what
-- tells an admin a count of 2 is fine today and wrong after a month.
SELECT
(SELECT count(*) FROM requests WHERE status = 'pending')::bigint AS requests,
(SELECT min(requested_at) FROM requests WHERE status = 'pending')::timestamptz AS requests_since,
-- A broken track is one report however it was found: a listener flagged
-- it, or it failed to play. Counted by track, as the Reports
-- page lists them.
-16
View File
@@ -215,22 +215,6 @@ UPDATE albums
updated_at = now()
WHERE id = $1 AND release_group_mbid IS NULL;
-- name: GetReleaseGroupForReleaseMbid :one
-- The release group the library already knows for a release id, so a
-- request carrying a release id can be repaired without asking MusicBrainz.
SELECT release_group_mbid::text
FROM albums
WHERE mbid = $1 AND release_group_mbid IS NOT NULL
LIMIT 1;
-- name: SetReleaseGroupForReleaseMbidIfNull :exec
-- Cache a MusicBrainz-resolved release group onto the album row that
-- holds the release, filling only a NULL.
UPDATE albums
SET release_group_mbid = sqlc.arg(release_group_mbid)::text,
updated_at = now()
WHERE mbid = sqlc.arg(release_mbid)::text AND release_group_mbid IS NULL;
-- name: ListAlbumsMissingMbidWithTrack :many
-- One-shot MBID backfill: returns each album where mbid IS NULL alongside
-- one of its tracks' file_path so the worker can re-read tags. LIMIT
@@ -1,103 +0,0 @@
-- Folksonomy tags for out-of-library Discover candidates. Parallel to
-- track_tags.sql, but keyed by MBID because the artist has no local row. See
-- 0050_candidate_artist_tags.up.sql for why the bookkeeping is its own table.
-- name: ListCandidateArtistsMissingTags :many
-- Candidates eligible for tag enrichment: never processed (no state row) or
-- settled 'none' under an older provider version.
--
-- artist_similarity_unmatched holds one row per (seed, candidate, source), so
-- this GROUPs to one row per candidate — enriching the same MBID once per seed
-- that pointed at it would multiply the API calls for no gain.
--
-- ORDER BY summed similarity DESC is the load-bearing part. The candidate pool
-- is O(library artists x neighbours per artist) — thousands — and MusicBrainz
-- allows ~1 req/s, so it can NEVER be fully enriched in one pass. Draining in
-- strength order means the candidates most likely to actually reach a user's
-- deck get tags first, and the long tail fills in over subsequent ticks
-- instead of starving behind it.
--
-- Already-in-library candidates are skipped: they have an artists row, so
-- their tags belong in track_tags, and the suggestion query filters them out
-- anyway. $1 = current tag_sources_version, $2 = limit.
-- candidate_name is coalesced to the empty string so it lands non-nullable in
-- Go: the name is only a Last.fm lookup key, and empty simply means "MBID-keyed
-- providers only", which the provider chain already handles. max() is an
-- arbitrary-but-deterministic pick when several seeds spell one MBID
-- differently.
SELECT u.candidate_mbid,
coalesce(max(u.candidate_name), '')::text AS candidate_name,
sum(u.score)::float8 AS total_score
FROM artist_similarity_unmatched u
LEFT JOIN candidate_artist_tag_state s ON s.candidate_mbid = u.candidate_mbid
WHERE NOT EXISTS (SELECT 1 FROM artists a WHERE a.mbid = u.candidate_mbid)
AND (
s.candidate_mbid IS NULL
OR (s.tag_source = 'none' AND s.tag_sources_version < $1)
)
GROUP BY u.candidate_mbid
ORDER BY total_score DESC, u.candidate_mbid
LIMIT $2;
-- name: DeleteCandidateArtistTags :exec
-- Clear a candidate's cached tags before rewriting (atomic replace by the
-- caller, same shape as DeleteTrackTags).
DELETE FROM candidate_artist_tags WHERE candidate_mbid = $1;
-- name: InsertCandidateArtistTag :exec
-- Upsert one (candidate, tag); keep the stronger weight when two providers
-- agree on a tag with different folksonomy strengths.
INSERT INTO candidate_artist_tags (candidate_mbid, tag, weight)
VALUES ($1, $2, $3)
ON CONFLICT (candidate_mbid, tag)
DO UPDATE SET weight = GREATEST(candidate_artist_tags.weight, EXCLUDED.weight);
-- name: SetCandidateArtistTagState :exec
-- Stamp the enrichment outcome so the drainer skips settled candidates.
-- $2 = 'musicbrainz' | 'lastfm' | 'mixed' | 'none', $3 = current version.
INSERT INTO candidate_artist_tag_state (candidate_mbid, tag_source, tag_sources_version)
VALUES ($1, $2, $3)
ON CONFLICT (candidate_mbid) DO UPDATE
SET tag_source = EXCLUDED.tag_source,
tag_sources_version = EXCLUDED.tag_sources_version,
updated_at = now();
-- name: ListCandidateArtistTagsForMbids :many
-- Cached tags for a set of candidates, for the taste-overlap ranking.
-- One row per (candidate, tag).
SELECT candidate_mbid, tag, weight
FROM candidate_artist_tags
WHERE candidate_mbid = ANY($1::text[]);
-- name: CountCandidateArtistTagCoverage :one
-- Operator-facing coverage: how many distinct candidates have been processed,
-- and how many of those actually yielded tags. The gap is the honest ceiling
-- from the task — obscure artists with no MBID presence or no upstream tags
-- stay thin no matter how long the worker runs, and that is worth being able
-- to see rather than inferring from a silent surface.
SELECT count(*)::bigint AS processed,
count(*) FILTER (WHERE tag_source <> 'none')::bigint AS with_tags
FROM candidate_artist_tag_state;
-- name: GcDeleteOrphanedCandidateArtistTags :execrows
-- Drops cached tags for candidates that no longer appear in the similarity
-- feed, or that have since been added to the library (their tags now live in
-- track_tags). The feed is refetched periodically and churns, so without this
-- the cache only ever grows.
DELETE FROM candidate_artist_tags t
WHERE NOT EXISTS (
SELECT 1 FROM artist_similarity_unmatched u
WHERE u.candidate_mbid = t.candidate_mbid
)
OR EXISTS (SELECT 1 FROM artists a WHERE a.mbid = t.candidate_mbid);
-- name: GcDeleteOrphanedCandidateArtistTagState :execrows
-- Same sweep for the bookkeeping rows. Kept as a separate statement rather
-- than a cascade: the two tables are independent by design (a 'none' outcome
-- has state but no tags), so neither can be the parent of the other.
DELETE FROM candidate_artist_tag_state s
WHERE NOT EXISTS (
SELECT 1 FROM artist_similarity_unmatched u
WHERE u.candidate_mbid = s.candidate_mbid
)
OR EXISTS (SELECT 1 FROM artists a WHERE a.mbid = s.candidate_mbid);
+2 -49
View File
@@ -1,34 +1,8 @@
-- The release catalogue read from MusicBrainz.
-- name: UpsertMBArtist :exec
INSERT INTO mb_artists (mbid, name, sort_name, disambiguation, artist_type, country)
VALUES (sqlc.arg(mbid), sqlc.arg(name), sqlc.arg(sort_name), sqlc.arg(disambiguation),
sqlc.arg(artist_type), sqlc.arg(country))
ON CONFLICT (mbid) DO UPDATE SET
name = EXCLUDED.name,
sort_name = EXCLUDED.sort_name,
disambiguation = EXCLUDED.disambiguation,
artist_type = EXCLUDED.artist_type,
country = EXCLUDED.country,
updated_at = now();
-- name: GetMBArtist :one
SELECT * FROM mb_artists WHERE mbid = sqlc.arg(mbid);
-- name: MarkMBArtistDiscographyRefreshed :exec
UPDATE mb_artists SET discography_refreshed_at = now() WHERE mbid = sqlc.arg(mbid);
-- name: ListMBArtistsDueForRefresh :many
-- Artists whose discography has never been read, or was read before the
-- cutoff: never-read first, then oldest first.
SELECT mbid FROM mb_artists
WHERE discography_refreshed_at IS NULL OR discography_refreshed_at < sqlc.arg(before)
ORDER BY discography_refreshed_at NULLS FIRST, mbid
LIMIT sqlc.arg(max_rows);
-- name: UpsertMBReleaseGroup :exec
-- Leaves releases_refreshed_at alone: re-reading a discography says nothing
-- about whether the group's track lists are current.
-- Leaves releases_refreshed_at alone: only a full read of the group's
-- releases and track lists marks it.
INSERT INTO mb_release_groups (mbid, title, primary_type, secondary_types, first_release_date, artist_credit)
VALUES (sqlc.arg(mbid), sqlc.arg(title), sqlc.arg(primary_type), sqlc.arg(secondary_types)::text[],
sqlc.arg(first_release_date), sqlc.arg(artist_credit))
@@ -43,21 +17,6 @@ ON CONFLICT (mbid) DO UPDATE SET
-- name: GetMBReleaseGroup :one
SELECT * FROM mb_release_groups WHERE mbid = sqlc.arg(mbid);
-- name: DeleteMBArtistReleaseGroups :exec
DELETE FROM mb_artist_release_groups WHERE artist_mbid = sqlc.arg(artist_mbid);
-- name: AddMBArtistReleaseGroup :exec
INSERT INTO mb_artist_release_groups (artist_mbid, release_group_mbid)
VALUES (sqlc.arg(artist_mbid), sqlc.arg(release_group_mbid))
ON CONFLICT DO NOTHING;
-- name: ListMBArtistReleaseGroups :many
-- An artist's discography, oldest first; undated groups last.
SELECT g.* FROM mb_release_groups g
JOIN mb_artist_release_groups ag ON ag.release_group_mbid = g.mbid
WHERE ag.artist_mbid = sqlc.arg(artist_mbid)
ORDER BY g.first_release_date = '', g.first_release_date, g.title, g.mbid;
-- name: MarkMBReleaseGroupReleasesRefreshed :exec
UPDATE mb_release_groups SET releases_refreshed_at = now() WHERE mbid = sqlc.arg(mbid);
@@ -88,12 +47,6 @@ VALUES (sqlc.arg(release_mbid), sqlc.arg(medium_position), sqlc.arg(position),
sqlc.arg(medium_format), sqlc.arg(number), sqlc.arg(title), sqlc.arg(length_ms),
sqlc.arg(recording_mbid));
-- name: ListMBReleasesForGroup :many
-- Official editions first, then by date; undated last.
SELECT * FROM mb_releases
WHERE release_group_mbid = sqlc.arg(release_group_mbid)
ORDER BY status <> 'Official', release_date = '', release_date, title, mbid;
-- name: ListMBReleaseTracksForGroup :many
SELECT t.* FROM mb_release_tracks t
JOIN mb_releases r ON r.mbid = t.release_mbid
-176
View File
@@ -1,176 +0,0 @@
-- Import with verification.
-- name: ListLiveGrabs :many
-- Every download still running or waiting on its import, oldest first.
SELECT g.*, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title AS want_title,
w.reason AS want_reason, w.album_id AS want_album_id
FROM grabs g
LEFT JOIN wants w ON w.id = g.want_id
WHERE g.ended_at IS NULL
ORDER BY g.grabbed_at, g.id;
-- name: GetGrab :one
SELECT * FROM grabs WHERE id = $1;
-- name: SetGrabProgress :exec
-- What the download client says of a download not yet finished, or finished
-- and waiting for what the import needs. Leaves a claimed, decided or failed
-- import alone.
UPDATE grabs
SET progress = sqlc.arg(progress),
import_state = sqlc.arg(import_state),
import_reason = sqlc.arg(import_reason),
import_updated_at = now()
WHERE id = sqlc.arg(id) AND ended_at IS NULL
AND import_state IN ('', 'downloading', 'waiting');
-- name: ClaimGrabImport :one
-- Takes a finished download for import. The update is the lock: a second
-- pass finds nothing to claim.
UPDATE grabs
SET import_state = 'importing', import_attempts = import_attempts + 1,
import_updated_at = now(), progress = 1
WHERE id = $1 AND ended_at IS NULL AND import_state IN ('', 'downloading', 'waiting')
RETURNING *;
-- name: ReclaimStaleImports :execrows
-- An import cut short (a restart mid-copy) is tried again.
UPDATE grabs
SET import_state = 'waiting',
import_reason = 'The last import was cut short, so it is being tried again.'
WHERE ended_at IS NULL AND import_state = 'importing'
AND import_updated_at < now() - make_interval(mins => sqlc.arg(minutes)::int);
-- name: RecordImport :one
-- The import's outcome. An end reason ends the grab: imported, refused or
-- held. Without one the grab stays live: review and failed wait for a person.
UPDATE grabs
SET import_state = sqlc.arg(import_state),
import_reason = sqlc.arg(import_reason),
import_detail = sqlc.arg(import_detail),
import_updated_at = now(),
import_forced = false,
imported_at = CASE WHEN sqlc.arg(import_state)::text = 'imported' THEN now() ELSE imported_at END,
-- The files were copied, so an imported download goes on sharing
-- until the lifecycle removes it.
seeding = sqlc.arg(import_state)::text = 'imported',
imported_files = sqlc.arg(imported_files),
destination = sqlc.arg(destination),
ended_at = CASE WHEN sqlc.arg(end_reason)::text <> '' THEN now() ELSE ended_at END,
end_reason = sqlc.arg(end_reason),
end_detail = CASE WHEN sqlc.arg(end_reason)::text <> '' THEN sqlc.arg(import_reason)::text ELSE end_detail END
WHERE id = sqlc.arg(id)
RETURNING *;
-- name: ForceGrabImport :one
-- "Import anyway": the next pass imports the download whatever the check said.
UPDATE grabs
SET import_state = '', import_forced = true, import_reason = '', import_updated_at = now()
WHERE id = $1 AND ended_at IS NULL AND import_state IN ('review', 'failed')
RETURNING *;
-- name: RetryGrabImport :one
UPDATE grabs
SET import_state = '', import_reason = '', import_updated_at = now()
WHERE id = $1 AND ended_at IS NULL AND import_state = 'failed'
RETURNING *;
-- name: RehomeGrab :one
-- A download that turned out to be another wanted album is that want's grab,
-- when the want has none running.
UPDATE grabs g
SET want_id = sqlc.arg(want_id)
WHERE g.id = sqlc.arg(id) AND g.ended_at IS NULL
AND NOT EXISTS (SELECT 1 FROM grabs o WHERE o.want_id = sqlc.arg(want_id) AND o.ended_at IS NULL)
RETURNING *;
-- name: OpenWantsForGroups :many
-- Open wants for these release groups with no download running.
SELECT w.* FROM wants w
WHERE w.fulfilled_at IS NULL AND w.release_group_mbid = ANY(sqlc.arg(groups)::text[])
AND NOT EXISTS (SELECT 1 FROM grabs g WHERE g.want_id = w.id AND g.ended_at IS NULL);
-- name: MarkWantSearched :exec
-- Imported: nothing to search for until the wanted pass settles the want.
UPDATE wants SET searched_at = now() WHERE id = $1;
-- name: SearchWantAgain :exec
-- Refused: search again on the next pass.
UPDATE wants SET searched_at = NULL, search_outcome = '' WHERE id = $1;
-- name: HeldRecordings :many
-- Which of these recordings the library holds a file for.
SELECT DISTINCT mbid::text AS mbid FROM tracks
WHERE mbid = ANY(sqlc.arg(recordings)::text[]) AND missing_since IS NULL;
-- name: HeldPositions :many
-- The disc and track positions the library holds for an album of this group.
SELECT DISTINCT COALESCE(t.disc_number, 1)::int AS disc, t.track_number::int AS track
FROM tracks t
JOIN albums a ON a.id = t.album_id
WHERE a.release_group_mbid = sqlc.arg(release_group_mbid)
AND t.missing_since IS NULL AND t.track_number IS NOT NULL;
-- name: ListGrabs :many
-- The Wanted view's Activity tab: downloads waiting on a person first, then
-- the rest still running, then the ended ones newest first. Each carries
-- what is wrong with it now, if anything.
SELECT g.id, g.want_id, g.name, g.indexer, g.client, g.quality, g.origin, g.forced,
g.grabbed_at, g.ended_at, g.end_reason, g.end_detail, g.progress, g.import_state,
g.import_reason, g.import_detail, g.import_updated_at, g.imported_at, g.imported_files,
g.destination, g.seeding, g.ratio, g.seed_released_at,
w.title AS want_title, w.artist_name AS want_artist,
di.trigger AS condition, di.detail AS condition_detail, di.remediations AS condition_retries,
di.first_seen AS condition_since
FROM grabs g
LEFT JOIN wants w ON w.id = g.want_id
LEFT JOIN download_interventions di
ON di.id = (SELECT x.id FROM download_interventions x
WHERE x.grab_id = g.id AND x.outcome = 'open'
ORDER BY x.last_seen DESC LIMIT 1)
ORDER BY (g.ended_at IS NULL AND g.import_state IN ('review', 'failed')) DESC,
g.ended_at IS NULL DESC, g.grabbed_at DESC, g.id
LIMIT sqlc.arg(max_rows) OFFSET sqlc.arg(skip);
-- name: ListReleaseBlocksPage :many
SELECT b.info_hash, b.name, b.reason, b.detail, b.blocked_at, b.expires_at, w.title AS want_title,
w.artist_name AS want_artist
FROM release_blocks b
LEFT JOIN wants w ON w.id = b.want_id
WHERE b.expires_at IS NULL OR b.expires_at > now()
ORDER BY b.blocked_at DESC, b.info_hash
LIMIT sqlc.arg(max_rows) OFFSET sqlc.arg(skip);
-- name: ListUpgradeTracks :many
-- The tracks an upgrade may replace: the present tracks of the album
-- the want holds.
SELECT id, file_path, mbid, COALESCE(disc_number, 1)::int AS disc, track_number,
file_format, file_size, duration_ms, source_verdict
FROM tracks
WHERE album_id = $1 AND missing_since IS NULL;
-- name: FinishUpgrade :exec
-- An upgrade was imported: the want holds the album the new tracks are in,
-- and is judged again by the next upgrade check.
UPDATE wants
SET album_id = COALESCE(sqlc.narg(album_id), album_id),
upgrade = '',
upgrade_checked_at = NULL,
updated_at = now()
WHERE id = sqlc.arg(id);
-- name: ClearTrackSourceVerdict :exec
-- A track whose file was replaced in place is no longer the rip it was.
UPDATE tracks SET source_verdict = NULL, source_verdict_at = NULL
WHERE id = $1 AND source_verdict = 'suspect';
-- name: ListImportedGrabsHolding :many
-- The downloads Minstrel imported into the folder holding path: the releases a
-- file there came from, to block when the files proved not to be the album
--. A file imported before Minstrel downloaded anything has none.
SELECT id, info_hash, name, want_id
FROM grabs
WHERE import_state = 'imported'
AND info_hash <> ''
AND destination <> ''
AND starts_with(sqlc.arg(path)::text, rtrim(destination, '/') || '/');
-11
View File
@@ -23,17 +23,6 @@ UPDATE albums
SET cover_art_path = sqlc.arg(new_root)::text || substr(cover_art_path, length(sqlc.arg(old_root)::text) + 1)
WHERE starts_with(cover_art_path, sqlc.arg(old_root)::text || '/');
-- name: RerootGrabDestinations :execrows
UPDATE grabs
SET destination = sqlc.arg(new_root)::text || substr(destination, length(sqlc.arg(old_root)::text) + 1)
WHERE destination = sqlc.arg(old_root)::text
OR starts_with(destination, sqlc.arg(old_root)::text || '/');
-- name: RerootImportRoot :execrows
UPDATE acquisition_settings
SET import_root = sqlc.arg(new_root)::text
WHERE import_root = sqlc.arg(old_root)::text;
-- name: SampleTrackPathsUnder :many
-- A few present tracks under a folder, to check a move before rewriting it.
SELECT file_path FROM tracks
-102
View File
@@ -1,102 +0,0 @@
-- The download lifecycle: the intervention ledger, giving a
-- download up, and seeding after import.
-- name: RaiseIntervention :one
-- A condition seen, or seen again: a second pass lands on the open row, so
-- a download stuck for a week is one row that says how long. The name only
-- improves, and the detail is the latest word.
INSERT INTO download_interventions (client, info_hash, grab_id, name, trigger, detail)
VALUES (sqlc.arg(client), sqlc.arg(info_hash), sqlc.narg(grab_id), sqlc.arg(name),
sqlc.arg(trigger), sqlc.arg(detail))
ON CONFLICT (client, info_hash, trigger) WHERE outcome = 'open' DO UPDATE SET
observations = download_interventions.observations + 1,
last_seen = now(),
detail = EXCLUDED.detail,
grab_id = COALESCE(EXCLUDED.grab_id, download_interventions.grab_id),
name = CASE WHEN EXCLUDED.name <> '' THEN EXCLUDED.name ELSE download_interventions.name END
RETURNING *;
-- name: SettleIntervention :execrows
-- The condition cleared.
UPDATE download_interventions
SET outcome = 'resolved', settled_at = now(), last_seen = now()
WHERE client = sqlc.arg(client) AND info_hash = sqlc.arg(info_hash)
AND trigger = sqlc.arg(trigger) AND outcome = 'open';
-- name: SettleInterventionsFor :execrows
-- Everything open about one download is over: it is gone from the client.
UPDATE download_interventions
SET outcome = 'resolved', settled_at = now(), last_seen = now()
WHERE client = sqlc.arg(client) AND info_hash = sqlc.arg(info_hash) AND outcome = 'open';
-- name: SettleEndedGrabs :execrows
-- What was wrong with a download whose grab has ended (imported, refused,
-- given up) is over, except a download left in the client to remove.
UPDATE download_interventions di
SET outcome = 'resolved', settled_at = now(), last_seen = now()
FROM grabs g
WHERE g.id = di.grab_id AND g.ended_at IS NOT NULL
AND di.outcome = 'open' AND di.trigger <> 'not_removed';
-- name: CountRemediation :one
-- Minstrel acted on an open condition. A retry climbs the ladder; giving up
-- or removing ends the condition, since what it was about is gone. Written
-- before the act, so a retry that happened is never uncounted.
UPDATE download_interventions
SET remediations = remediations + 1,
action = sqlc.arg(action),
last_seen = now(),
outcome = CASE WHEN sqlc.arg(action)::text IN ('given_up', 'removed') THEN 'resolved' ELSE outcome END,
settled_at = CASE WHEN sqlc.arg(action)::text IN ('given_up', 'removed') THEN now() ELSE settled_at END
WHERE client = sqlc.arg(client) AND info_hash = sqlc.arg(info_hash)
AND trigger = sqlc.arg(trigger) AND outcome = 'open'
RETURNING remediations;
-- name: ListLeftovers :many
-- Downloads given up on that the client would not remove; each pass asks
-- again.
SELECT * FROM download_interventions
WHERE trigger = 'not_removed' AND outcome = 'open' AND info_hash <> ''
ORDER BY first_seen;
-- name: ListClientsDown :many
-- Download clients not answering now, for the Activity tab.
SELECT client, detail, first_seen FROM download_interventions
WHERE trigger = 'client_unreachable' AND outcome = 'open'
ORDER BY client;
-- name: LiveGrabOnHash :one
SELECT EXISTS (SELECT 1 FROM grabs WHERE info_hash = sqlc.arg(info_hash) AND ended_at IS NULL)::bool;
-- name: GiveUpGrab :one
-- Ends a running grab, given up on. Only from the states named: the update
-- is the lock against an import that claimed the download meanwhile.
UPDATE grabs
SET ended_at = now(), end_reason = sqlc.arg(end_reason), end_detail = sqlc.arg(end_detail),
import_updated_at = now()
WHERE id = sqlc.arg(id) AND ended_at IS NULL AND import_state = ANY(sqlc.arg(states)::text[])
RETURNING *;
-- name: CountGoneGrabs :one
-- How many of a release's grabs ended gone since a time: a release that keeps
-- leaving its client is held back rather than taken on every pass.
SELECT count(*) FROM grabs
WHERE info_hash = sqlc.arg(info_hash) AND end_reason = 'gone' AND ended_at > sqlc.arg(since);
-- name: ListSeedingGrabs :many
-- Imported downloads still sharing, oldest import first.
SELECT id, client, info_hash, name, imported_at FROM grabs
WHERE seeding AND seed_released_at IS NULL
ORDER BY imported_at, id;
-- name: SetGrabRatio :exec
UPDATE grabs SET ratio = sqlc.arg(ratio) WHERE id = sqlc.arg(id);
-- name: ReleaseSeed :exec
-- The seeding download was removed, or found gone.
UPDATE grabs SET seed_released_at = now() WHERE id = $1 AND seed_released_at IS NULL;
-- name: DeleteExpiredBlocks :execrows
-- A release given up on is held back for a while; after that the search may
-- take it again.
DELETE FROM release_blocks WHERE expires_at IS NOT NULL AND expires_at <= now();
-4
View File
@@ -33,10 +33,6 @@ UPDATE contextual_likes SET track_id = sqlc.arg(survivor_id)::uuid WHERE track_i
-- name: MergeRepointPlaybackErrors :execrows
UPDATE playback_errors SET track_id = sqlc.arg(survivor_id)::uuid WHERE track_id = sqlc.arg(loser_id)::uuid;
-- name: MergeRepointRequests :execrows
UPDATE requests SET matched_track_id = sqlc.arg(survivor_id)::uuid
WHERE matched_track_id = sqlc.arg(loser_id)::uuid;
-- name: MergeRepointPlaylistTracks :many
-- playlist_tracks is keyed by (playlist_id, position), so repointing keeps every
-- entry exactly where it was. A playlist that held both copies simply holds the
-93
View File
@@ -1,93 +0,0 @@
-- Re-acquisition of missing files.
-- The unit is the album: an album whose files went missing becomes a want for
-- its release group, and the search schedule looks for it.
-- name: GetReacquisitionSettings :one
SELECT * FROM reacquisition_settings WHERE id = true;
-- name: UpdateReacquisitionSettings :one
-- Whole-row write from the admin card; the CHECKs in migration 0056 are the
-- validation, so a bad value fails loudly rather than being clamped silently.
UPDATE reacquisition_settings
SET enabled = sqlc.arg(enabled),
grace_hours = sqlc.arg(grace_hours),
max_per_pass = sqlc.arg(max_per_pass)
WHERE id = true
RETURNING *;
-- name: ListAlbumsDueReacquisition :many
-- The sweeper's selection. An album qualifies when:
--
-- * it still has at least one track whose file has been missing longer than
-- the grace window. Measured on missing_since, which reconcile never
-- re-stamps, so it is a genuine "gone since" clock;
-- * MusicBrainz can name it: the artist has an MBID, and the album a
-- release MBID or a release group. The release MBID is only ever used to
-- find the group, and an album matched to a group may carry no release
-- id. Albums failing this are counted separately
-- (CountAlbumsMissingWithoutMbid);
-- * it is on the wanted list: an album taken off the list, or
-- dropped into the library by hand, is not fetched back;
-- * no want already covers it: none open, and none held since its files
-- went missing. A want held after the loss means the library has a full
-- copy despite the missing rows, so asking again would loop.
SELECT albums.id AS album_id,
albums.title AS album_title,
albums.mbid AS album_mbid,
albums.release_group_mbid AS album_release_group_mbid,
artists.name AS artist_name,
artists.mbid AS artist_mbid,
COUNT(tracks.id)::bigint AS missing_track_count,
MAX(tracks.missing_since)::timestamptz AS last_missing_since
FROM albums
JOIN artists ON artists.id = albums.artist_id
JOIN tracks ON tracks.album_id = albums.id
WHERE tracks.missing_since IS NOT NULL
AND tracks.missing_since <= now() - make_interval(hours => sqlc.arg(grace_hours)::int)
AND (albums.mbid IS NOT NULL OR albums.release_group_mbid IS NOT NULL)
AND artists.mbid IS NOT NULL
GROUP BY albums.id, albums.title, albums.mbid, albums.release_group_mbid,
artists.name, artists.mbid
HAVING EXISTS (
SELECT 1 FROM wants w
WHERE w.album_id = albums.id OR w.release_group_mbid = albums.release_group_mbid)
AND NOT EXISTS (
SELECT 1 FROM wants w
WHERE (w.album_id = albums.id OR w.release_group_mbid = albums.release_group_mbid)
AND (w.fulfilled_at IS NULL OR w.fulfilled_at > MAX(tracks.missing_since)))
ORDER BY MIN(tracks.missing_since), albums.sort_title
LIMIT sqlc.arg(page_limit);
-- name: CountAlbumsMissingWithoutMbid :one
-- Albums with missing files that can never be wanted automatically because
-- nothing identifies them to MusicBrainz. Surfaced on the admin card so the
-- gap is visible: silently doing nothing for these would read as broken.
SELECT COUNT(DISTINCT albums.id)::bigint
FROM albums
JOIN artists ON artists.id = albums.artist_id
JOIN tracks ON tracks.album_id = albums.id
WHERE tracks.missing_since IS NOT NULL
AND ((albums.mbid IS NULL AND albums.release_group_mbid IS NULL) OR artists.mbid IS NULL);
-- name: WantMissingAlbum :one
-- Records an album with missing files as wanted. A held want for the same
-- group is reopened; an open one is left as it is, and no row comes back.
INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id)
VALUES (sqlc.arg(release_group_mbid), sqlc.arg(artist_mbid), sqlc.arg(artist_name),
sqlc.arg(title), 'missing', sqlc.arg(album_id))
ON CONFLICT (release_group_mbid) DO UPDATE
SET reason = 'missing',
album_id = EXCLUDED.album_id,
wanted_at = now(),
fulfilled_at = NULL,
updated_at = now()
WHERE wants.fulfilled_at IS NOT NULL
RETURNING *;
-- name: GetWantsForAlbums :many
-- What the wanted list says about each album on the missing-files page.
SELECT a.id AS album_id, w.id AS want_id, w.wanted_at, w.fulfilled_at
FROM albums a
JOIN wants w ON w.album_id = a.id OR w.release_group_mbid = a.release_group_mbid
WHERE a.id = ANY(sqlc.arg(album_ids)::uuid[])
ORDER BY w.wanted_at DESC;
-103
View File
@@ -310,109 +310,6 @@ WHERE user_id = $1
ORDER BY started_at DESC
LIMIT 1;
-- name: SuggestArtistsForUser :many
-- Per-user artist suggestions ranked by taste signal x similarity, projected
-- through artist_similarity_unmatched (out-of-library candidates only).
--
-- Seeds are TIERED so the surface never empties:
-- tier 1 - taste_profile_artists.weight: engagement-graded, time-decayed and
-- SIGNED by internal/taste, so an artist the user has drifted away
-- from stops contributing instead of accumulating forever.
-- tier 2 - likes + completed plays, used ONLY when the profile has no rows
-- (new account, or before the first daily recompute).
--
-- The signal is log-damped: contribution is signal x similarity, and an
-- undamped sum would let one heavily-played artist's neighbours take every
-- slot -- entrenching harder the MORE the user listened.
--
-- Candidates already in the library, already requested and not terminal, or
-- snoozed by this user, are excluded. $1=user_id, $2=half_life_days (tier 2
-- decay), $3=limit.
WITH artist_plays AS (
-- Completed plays only: counting every play_event would make skipping an
-- artist repeatedly INCREASE its signal and push more of its neighbours
-- at the user.
SELECT t.artist_id, count(*)::bigint AS play_count
FROM play_events pe
JOIN tracks t ON t.id = pe.track_id
WHERE pe.user_id = $1 AND pe.was_skipped = false
GROUP BY t.artist_id
),
profile_seeds AS (
SELECT tpa.artist_id, tpa.weight AS raw_signal
FROM taste_profile_artists tpa
WHERE tpa.user_id = $1 AND tpa.weight > 0
),
fallback_seeds AS (
SELECT a.id AS artist_id,
5.0 * (CASE WHEN gla.artist_id IS NOT NULL THEN 1 ELSE 0 END)
+ COALESCE(SUM(EXP(- EXTRACT(epoch FROM now() - pe.started_at) / ($2::float8 * 86400.0))), 0)
AS raw_signal
FROM artists a
LEFT JOIN general_likes_artists gla ON gla.artist_id = a.id AND gla.user_id = $1
LEFT JOIN tracks t ON t.artist_id = a.id
LEFT JOIN play_events pe
ON pe.track_id = t.id AND pe.user_id = $1 AND pe.was_skipped = false
WHERE (gla.artist_id IS NOT NULL OR pe.id IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM profile_seeds)
GROUP BY a.id, gla.artist_id
),
seeds AS (
SELECT s.artist_id,
ln(1.0 + s.raw_signal) AS signal,
(gla.artist_id IS NOT NULL) AS is_liked,
COALESCE(ap.play_count, 0)::bigint AS play_count
FROM (
SELECT artist_id, raw_signal FROM profile_seeds
UNION ALL
SELECT artist_id, raw_signal FROM fallback_seeds
) s
LEFT JOIN general_likes_artists gla
ON gla.artist_id = s.artist_id AND gla.user_id = $1
LEFT JOIN artist_plays ap ON ap.artist_id = s.artist_id
WHERE s.raw_signal > 0
),
contributions AS (
SELECT u.candidate_mbid,
u.candidate_name,
seeds.artist_id AS seed_id,
seeds.is_liked,
seeds.play_count,
seeds.signal * u.score AS contribution
FROM artist_similarity_unmatched u
JOIN seeds ON seeds.artist_id = u.seed_artist_id
WHERE NOT EXISTS (SELECT 1 FROM artists WHERE mbid = u.candidate_mbid)
AND NOT EXISTS (
SELECT 1 FROM requests r
WHERE r.user_id = $1
AND r.artist_mbid = u.candidate_mbid
AND r.status NOT IN ('rejected', 'failed')
)
-- Snoozed by this user and not yet expired. Time-boxed and
-- per-user: the candidate returns on its own once snoozed_until
-- passes, and stays visible to everyone else meanwhile. Deliberately
-- filtered at the candidate stage, NOT folded into the score — a
-- snooze carries no opinion about the music, so it must not become a
-- ranking signal.
AND NOT EXISTS (
SELECT 1 FROM suggestion_snoozes s
WHERE s.user_id = $1
AND s.candidate_mbid = u.candidate_mbid
AND s.snoozed_until > now()
)
)
SELECT candidate_mbid,
candidate_name,
SUM(contribution)::float8 AS total_score,
((array_agg(seed_id ORDER BY contribution DESC))[1:3])::uuid[] AS top_seed_ids,
((array_agg(contribution ORDER BY contribution DESC))[1:3])::float8[] AS top_contributions,
((array_agg(is_liked ORDER BY contribution DESC))[1:3])::boolean[] AS top_is_liked,
((array_agg(play_count ORDER BY contribution DESC))[1:3])::bigint[] AS top_play_counts
FROM contributions
GROUP BY candidate_mbid, candidate_name
ORDER BY total_score DESC
LIMIT $3;
-- name: ListMostPlayedTracksForUser :many
-- Top-N tracks by completed-play count for the user. was_skipped
-- excludes skips so a user spamming next doesn't fabricate a top track.
@@ -53,24 +53,6 @@ UPDATE taste_tuning
WHERE singleton = true
RETURNING *;
-- name: UpsertDiscoverTuningDefaults :exec
-- Boot reconcile for the Discover scope. Never overwrites
-- admin-tuned values, same contract as the other two.
INSERT INTO discover_tuning (singleton, tag_overlap_weight, snooze_days)
VALUES (true, $1, $2)
ON CONFLICT (singleton) DO NOTHING;
-- name: GetDiscoverTuning :one
SELECT * FROM discover_tuning WHERE singleton = true;
-- name: UpdateDiscoverTuning :one
UPDATE discover_tuning
SET tag_overlap_weight = $1,
snooze_days = $2,
updated_at = now()
WHERE singleton = true
RETURNING *;
-- name: InsertTuningAudit :exec
-- changes is a jsonb array of {field, old, new} objects.
INSERT INTO recommendation_tuning_audit (scope, action, changes)
-119
View File
@@ -1,119 +0,0 @@
-- name: CreateRequest :one
INSERT INTO requests (
user_id, kind,
artist_mbid, album_mbid, track_mbid,
artist_name, album_title, track_title
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *;
-- name: GetRequestByID :one
SELECT * FROM requests WHERE id = $1;
-- name: ListRequestsForUser :many
SELECT * FROM requests
WHERE user_id = $1
ORDER BY requested_at DESC
LIMIT $2;
-- name: ListRequestsByStatus :many
SELECT * FROM requests
WHERE status = $1
ORDER BY requested_at DESC
LIMIT $2;
-- name: ListApprovedRequestsForReconcile :many
SELECT * FROM requests
WHERE status = 'approved'
ORDER BY decided_at ASC
LIMIT $1;
-- name: ApproveRequest :one
UPDATE requests
SET status = 'approved',
decided_at = now(),
decided_by = $2,
updated_at = now()
WHERE id = $1 AND status = 'pending'
RETURNING *;
-- name: RejectRequest :one
UPDATE requests
SET status = 'rejected',
notes = $2,
decided_at = now(),
decided_by = $3,
updated_at = now()
WHERE id = $1 AND status = 'pending'
RETURNING *;
-- name: CancelRequest :one
-- $2 serves as both the ownership guard (user_id = $2) and the
-- decided_by audit field. The generated parameter struct names it
-- DecidedBy — callers must pass the cancelling user's UUID, and
-- a wrong UUID will silently no-op (zero rows updated) rather than
-- erroring at the SQL layer.
UPDATE requests
SET status = 'rejected',
notes = 'cancelled by user',
decided_at = now(),
decided_by = $2,
updated_at = now()
WHERE id = $1 AND user_id = $2 AND status = 'pending'
RETURNING *;
-- name: CompleteRequest :one
-- Reconciler transitions an approved request to completed when its
-- target track/album/artist has appeared in the library. Callers
-- should set ONLY the matched_*_id corresponding to the request's
-- kind and pass pgtype.UUID{} (Valid: false) for the others —
-- per-kind one-of-three is the contract, NULL for the others
-- preserves auditability if the matched row is later evicted.
UPDATE requests
SET status = 'completed',
matched_track_id = $2,
matched_album_id = $3,
matched_artist_id = $4,
completed_at = now(),
updated_at = now()
WHERE id = $1 AND status = 'approved'
RETURNING *;
-- name: HasNonTerminalRequestForMBID :one
-- Whether something is already on its way: a pending, approved or completed
-- request at the given level, an open want for the release group, or a
-- follow of the artist. Sets the `requested` flag on catalogue search.
-- Terminal-status (rejected, failed) requests do not count. MBIDs are unique
-- per entity type, so checking one id against every column cannot
-- false-match.
SELECT (EXISTS (
SELECT 1 FROM requests r
WHERE r.status IN ('pending', 'approved', 'completed')
AND ((r.kind = 'artist' AND r.artist_mbid = @mbid)
OR (r.kind = 'album' AND r.album_mbid = @mbid)
OR (r.kind = 'track' AND r.track_mbid = @mbid))
) OR EXISTS (
SELECT 1 FROM wants w WHERE w.release_group_mbid = @mbid AND w.fulfilled_at IS NULL
) OR EXISTS (
SELECT 1 FROM follows f WHERE f.artist_mbid = @mbid
))::bool AS requested;
-- name: GetNonTerminalRequestForMBID :one
-- Returns the oldest non-terminal (pending/approved/completed) request
-- whose own-kind MBID matches @mbid, or pgx.ErrNoRows when none. Create()
-- uses this to dedupe: a re-request for something already in flight
-- returns the existing row instead of inserting a duplicate.
SELECT * FROM requests
WHERE status IN ('pending', 'approved', 'completed')
AND ((kind = 'artist' AND artist_mbid = @mbid)
OR (kind = 'album' AND album_mbid = @mbid)
OR (kind = 'track' AND track_mbid = @mbid))
ORDER BY requested_at ASC
LIMIT 1;
-- name: RepointRequestsAlbumMbid :exec
-- A want moved from a release id to its group takes the requests
-- that name it along, so the reconciler finds it.
UPDATE requests
SET album_mbid = sqlc.arg(new_mbid),
updated_at = now()
WHERE album_mbid = sqlc.arg(old_mbid);
-141
View File
@@ -1,141 +0,0 @@
-- Searching for wants and grabbing releases.
-- name: GetAcquisitionSettings :one
SELECT * FROM acquisition_settings WHERE id = true;
-- name: UpdateAcquisitionSettings :one
UPDATE acquisition_settings
SET auto_grab = sqlc.arg(auto_grab),
search_interval_hours = sqlc.arg(search_interval_hours),
allowed_qualities = sqlc.arg(allowed_qualities),
import_root = sqlc.arg(import_root),
seed_ratio = sqlc.arg(seed_ratio),
seed_days = sqlc.arg(seed_days),
stall_hours = sqlc.arg(stall_hours),
upgrade_until = sqlc.arg(upgrade_until),
updated_at = now()
WHERE id = true
RETURNING *;
-- name: RecordSearchPass :exec
UPDATE acquisition_settings SET last_pass_at = now(), last_pass = sqlc.arg(report) WHERE id = true;
-- name: ListWantsDueForSearch :many
-- Wants with no download running that were never searched or not since
-- @hours ago: open wants first (never-searched, then requests, then missing
-- files, then followed artists' releases), then held albums wanted for an
-- upgrade, which are searched at most weekly.
SELECT w.id, w.release_group_mbid, w.artist_name, w.title, w.reason, w.upgrade, w.held_tier, w.held_quality,
COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type,
COALESCE(g.secondary_types, '{}')::text[] AS secondary_types,
COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date
FROM wants w
LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid
WHERE (w.fulfilled_at IS NULL OR w.upgrade <> '')
AND NOT EXISTS (SELECT 1 FROM grabs gr WHERE gr.want_id = w.id AND gr.ended_at IS NULL)
AND (w.searched_at IS NULL
OR w.searched_at < now() - make_interval(hours => CASE WHEN w.fulfilled_at IS NULL
THEN sqlc.arg(hours)::int
ELSE GREATEST(sqlc.arg(hours)::int, 168) END))
ORDER BY w.fulfilled_at IS NOT NULL,
w.searched_at IS NOT NULL,
CASE w.reason WHEN 'request' THEN 0 WHEN 'missing' THEN 1 ELSE 2 END,
w.searched_at NULLS FIRST, w.wanted_at, w.id
LIMIT sqlc.arg(max_rows);
-- name: GetWantForSearch :one
SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.reason, w.fulfilled_at,
w.upgrade, w.held_tier, w.held_quality, w.album_id,
COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type,
COALESCE(g.secondary_types, '{}')::text[] AS secondary_types,
COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date
FROM wants w
LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid
WHERE w.id = $1;
-- name: EditionTrackSpan :one
-- The fewest tracks an official edition of the group has (any edition when
-- none is official), and the most any has. Zero when none is catalogued.
SELECT COALESCE(MIN(track_count) FILTER (WHERE status = 'Official'), MIN(track_count), 0)::int AS min_tracks,
COALESCE(MAX(track_count), 0)::int AS max_tracks
FROM mb_releases
WHERE release_group_mbid = $1 AND track_count > 0;
-- name: RecordWantSearch :exec
UPDATE wants
SET searched_at = now(),
search_outcome = sqlc.arg(outcome),
search_considered = sqlc.arg(considered),
best_release = sqlc.arg(best_release),
best_verdict = sqlc.arg(best_verdict),
search_error = sqlc.arg(search_error),
updated_at = now()
WHERE id = sqlc.arg(id);
-- name: DeleteWantCandidates :exec
DELETE FROM want_candidates WHERE want_id = $1;
-- name: InsertWantCandidate :exec
INSERT INTO want_candidates (want_id, key, name, info_hash, indexer, source, size_bytes, seeders,
files_count, format, quality, year, verdict, reason, reasons, folded_from, rank)
VALUES (sqlc.arg(want_id), sqlc.arg(key), sqlc.arg(name), sqlc.arg(info_hash), sqlc.arg(indexer),
sqlc.arg(source), sqlc.arg(size_bytes), sqlc.arg(seeders), sqlc.arg(files_count), sqlc.arg(format),
sqlc.arg(quality), sqlc.arg(year), sqlc.arg(verdict), sqlc.arg(reason), sqlc.arg(reasons),
sqlc.arg(folded_from), sqlc.arg(rank))
ON CONFLICT (want_id, key) DO NOTHING;
-- name: ListWantCandidates :many
SELECT * FROM want_candidates WHERE want_id = $1 ORDER BY rank, key;
-- name: GetWantCandidate :one
SELECT * FROM want_candidates WHERE want_id = $1 AND key = $2;
-- name: MarkCandidatesBlocked :exec
UPDATE want_candidates
SET verdict = 'blocked', reason = sqlc.arg(reason),
reasons = jsonb_build_array(jsonb_build_object('kind', 'hard', 'code', 'blocked', 'text', sqlc.arg(reason)::text))
WHERE info_hash = sqlc.arg(info_hash);
-- name: MarkCandidatesUnblocked :exec
UPDATE want_candidates
SET verdict = 'review', reason = sqlc.arg(reason),
reasons = jsonb_build_array(jsonb_build_object('kind', 'soft', 'code', 'unblocked', 'text', sqlc.arg(reason)::text))
WHERE info_hash = sqlc.arg(info_hash) AND verdict = 'blocked';
-- name: GetLiveGrab :one
SELECT * FROM grabs WHERE want_id = $1 AND ended_at IS NULL;
-- name: InsertGrab :one
INSERT INTO grabs (want_id, info_hash, name, key, indexer, source, client, save_path, quality,
origin, forced, grabbed_by)
VALUES (sqlc.narg(want_id), sqlc.arg(info_hash), sqlc.arg(name), sqlc.arg(key), sqlc.arg(indexer),
sqlc.arg(source), sqlc.arg(client), sqlc.arg(save_path), sqlc.arg(quality),
sqlc.arg(origin), sqlc.arg(forced), sqlc.narg(grabbed_by))
RETURNING *;
-- name: EndGrab :exec
UPDATE grabs
SET ended_at = now(), end_reason = sqlc.arg(end_reason), end_detail = sqlc.arg(end_detail)
WHERE id = sqlc.arg(id) AND ended_at IS NULL;
-- name: ListReleaseBlocks :many
-- Every release set aside and still held back: a stalled one lifts by itself
-- at expires_at.
SELECT * FROM release_blocks
WHERE expires_at IS NULL OR expires_at > now()
ORDER BY blocked_at DESC;
-- name: BlockRelease :exec
-- A release set aside. expires_at NULL is for good. A block for good is never
-- shortened by a timed one: only a timed block, or another for good, is
-- replaced.
INSERT INTO release_blocks (info_hash, name, reason, detail, want_id, blocked_by, expires_at)
VALUES (sqlc.arg(info_hash), sqlc.arg(name), sqlc.arg(reason), sqlc.arg(detail),
sqlc.narg(want_id), sqlc.narg(blocked_by), sqlc.narg(expires_at))
ON CONFLICT (info_hash) DO UPDATE
SET reason = EXCLUDED.reason, detail = EXCLUDED.detail, blocked_at = now(),
expires_at = EXCLUDED.expires_at, blocked_by = EXCLUDED.blocked_by
WHERE release_blocks.expires_at IS NOT NULL OR EXCLUDED.expires_at IS NULL;
-- name: UnblockRelease :execrows
DELETE FROM release_blocks WHERE info_hash = $1;
-12
View File
@@ -121,18 +121,6 @@ VALUES ($1, $2, $3, 'listenbrainz', now())
ON CONFLICT (artist_a_id, artist_b_id, source)
DO UPDATE SET score = EXCLUDED.score, fetched_at = EXCLUDED.fetched_at;
-- name: UpsertArtistSimilarityUnmatched :exec
-- Persists an out-of-library similar-artist MBID. Idempotent on
-- (seed_artist_id, candidate_mbid, source) — re-fetches refresh the
-- name/score and bump fetched_at.
INSERT INTO artist_similarity_unmatched (
seed_artist_id, candidate_mbid, candidate_name, score, source
) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (seed_artist_id, candidate_mbid, source) DO UPDATE SET
candidate_name = EXCLUDED.candidate_name,
score = EXCLUDED.score,
fetched_at = now();
-- name: ListSimilarArtistsForArtist :many
-- In-library artists similar to a seed artist, ranked by best similarity
-- score across sources (deduped per candidate). cover_album_id + album_count
@@ -1,39 +0,0 @@
-- Time-boxed "not right now" on a Discover artist suggestion.
--
-- See 0049_suggestion_snoozes.up.sql for why this is a snooze and not a
-- dismissal: it records no verdict on the music, expires on its own, and
-- must never reach the taste profile. Nothing in internal/taste may read
-- this table.
-- name: SnoozeSuggestion :exec
-- Upsert, so re-snoozing an already-snoozed candidate EXTENDS it instead of
-- erroring on the PK. The name is refreshed too — a later suggestion may
-- carry a corrected spelling from the similarity feed.
-- $1=user_id, $2=candidate_mbid, $3=candidate_name, $4=duration in days.
INSERT INTO suggestion_snoozes (user_id, candidate_mbid, candidate_name, snoozed_until)
VALUES ($1, $2, $3, now() + ($4::float8 * INTERVAL '1 day'))
ON CONFLICT (user_id, candidate_mbid) DO UPDATE
SET snoozed_until = EXCLUDED.snoozed_until,
candidate_name = EXCLUDED.candidate_name;
-- name: UnsnoozeSuggestion :execrows
-- Row count is returned so the handler can 404 an MBID that was never
-- snoozed rather than reporting success for a no-op.
DELETE FROM suggestion_snoozes
WHERE user_id = $1 AND candidate_mbid = $2;
-- name: ListActiveSuggestionSnoozes :many
-- Backs the manage / un-snooze surface. Expired rows are filtered HERE
-- rather than left to the sweeper: gc runs on an hourly tick, so a row can
-- outlive its expiry by up to a tick and must not read as still-snoozed in
-- the meantime.
SELECT candidate_mbid, candidate_name, snoozed_until, created_at
FROM suggestion_snoozes
WHERE user_id = $1 AND snoozed_until > now()
ORDER BY snoozed_until, candidate_mbid;
-- name: GcDeleteExpiredSuggestionSnoozes :execrows
-- Keeps the table from growing without bound. Every read already filters on
-- snoozed_until > now(), so deleting an expired row changes no behaviour —
-- this is purely reclamation.
DELETE FROM suggestion_snoozes WHERE snoozed_until < now();
+1 -9
View File
@@ -305,18 +305,10 @@ SELECT t.id,
artists.id AS artist_id,
artists.name AS artist_name,
t.source_verdict,
t.source_verdict_at,
-- The album's place on the wanted list: wanted for a clean copy, and
-- when that was last searched for.
COALESCE(w.upgrade, '')::text AS want_upgrade,
w.searched_at AS searched_at
t.source_verdict_at
FROM tracks t
JOIN albums ON albums.id = t.album_id
JOIN artists ON artists.id = t.artist_id
LEFT JOIN LATERAL (
SELECT x.upgrade, x.searched_at FROM wants x
WHERE x.album_id = albums.id AND x.fulfilled_at IS NOT NULL LIMIT 1
) w ON true
WHERE t.missing_since IS NULL
AND regexp_replace(t.file_path, '^.*/', '') ~* sqlc.arg(pattern)::text
ORDER BY directory, t.disc_number NULLS FIRST, t.track_number NULLS FIRST, t.title
+1 -9
View File
@@ -44,8 +44,7 @@ UPDATE users SET subsonic_password = $2 WHERE id = $1;
SELECT * FROM users WHERE id = $1;
-- name: ListUsernamesByIDs :many
-- Names a list's people in one round trip, e.g. who made each request on
-- /admin/requests.
-- Names a list's people in one round trip.
SELECT id, username FROM users WHERE id = ANY($1::uuid[]);
-- name: SetListenBrainzToken :exec
@@ -115,13 +114,6 @@ UPDATE users
SET password_hash = $2
WHERE id = $1;
-- name: UpdateUserAutoApprove :one
-- Toggle the per-user auto_approve_requests flag.
UPDATE users
SET auto_approve_requests = $2
WHERE id = $1
RETURNING *;
-- name: SetDebugMode :one
-- Toggle the per-account diagnostics/debug-reporting opt-in. Admin-driven
-- from /admin (flip remotely while a bug is live) or self-driven OFF from
-501
View File
@@ -1,501 +0,0 @@
-- The wanted list: release-type profiles, follows and wants.
-- name: ListReleaseTypeProfiles :many
SELECT p.*,
(SELECT COUNT(*) FROM follows f WHERE f.profile_id = p.id)::bigint AS follow_count
FROM release_type_profiles p
ORDER BY p.is_default DESC, p.name;
-- name: GetReleaseTypeProfile :one
SELECT * FROM release_type_profiles WHERE id = $1;
-- name: GetDefaultReleaseTypeProfile :one
SELECT * FROM release_type_profiles WHERE is_default;
-- name: CreateReleaseTypeProfile :one
INSERT INTO release_type_profiles (name, primary_types, secondary_types)
VALUES ($1, $2, $3)
RETURNING *;
-- name: UpdateReleaseTypeProfile :one
UPDATE release_type_profiles
SET name = $2,
primary_types = $3,
secondary_types = $4,
updated_at = now()
WHERE id = $1
RETURNING *;
-- name: ClearDefaultReleaseTypeProfile :exec
UPDATE release_type_profiles SET is_default = false, updated_at = now() WHERE is_default;
-- name: SetDefaultReleaseTypeProfile :execrows
UPDATE release_type_profiles SET is_default = true, updated_at = now() WHERE id = $1;
-- name: DeleteReleaseTypeProfile :execrows
-- The default stays; one in use is refused by the follows foreign key.
DELETE FROM release_type_profiles WHERE id = $1 AND NOT is_default;
-- name: UpsertFollow :one
-- Following an artist already followed changes its profile. want_existing
-- only ever turns on here; the worker turns it off once applied, and turning
-- it on again re-reads the baseline so the existing releases are judged.
INSERT INTO follows (artist_mbid, artist_name, profile_id, followed_by, want_existing)
VALUES (sqlc.arg(artist_mbid), sqlc.arg(artist_name), sqlc.arg(profile_id),
sqlc.narg(followed_by), sqlc.arg(want_existing))
ON CONFLICT (artist_mbid) DO UPDATE
SET artist_name = EXCLUDED.artist_name,
profile_id = EXCLUDED.profile_id,
want_existing = follows.want_existing OR EXCLUDED.want_existing,
baseline_at = CASE WHEN EXCLUDED.want_existing THEN NULL ELSE follows.baseline_at END,
updated_at = now()
RETURNING *;
-- name: GetFollow :one
SELECT f.*, p.name AS profile_name
FROM follows f
JOIN release_type_profiles p ON p.id = f.profile_id
WHERE f.artist_mbid = $1;
-- name: DeleteFollow :execrows
DELETE FROM follows WHERE artist_mbid = $1;
-- name: ListFollows :many
SELECT f.artist_mbid, f.artist_name, f.profile_id, f.followed_at, f.baseline_at, f.checked_at,
p.name AS profile_name,
(SELECT a.id FROM artists a WHERE a.mbid = f.artist_mbid) AS artist_id,
(SELECT COUNT(*) FROM wants w
WHERE w.artist_mbid = f.artist_mbid AND w.fulfilled_at IS NULL)::bigint AS open_wants
FROM follows f
JOIN release_type_profiles p ON p.id = f.profile_id
ORDER BY lower(f.artist_name), f.artist_mbid;
-- name: ListFollowsDue :many
-- Follows whose discography has not been applied since @before, never-read
-- first, so a new follow's baseline is not stuck behind daily re-checks.
SELECT f.*
FROM follows f
WHERE f.baseline_at IS NULL OR f.checked_at IS NULL OR f.checked_at < sqlc.arg(before)
ORDER BY f.baseline_at NULLS FIRST, f.checked_at NULLS FIRST, f.artist_mbid
LIMIT sqlc.arg(max_rows);
-- name: MarkFollowChecked :exec
UPDATE follows
SET checked_at = now(),
baseline_at = COALESCE(baseline_at, now()),
want_existing = false,
updated_at = now()
WHERE artist_mbid = $1;
-- name: ListFollowGroups :many
-- An artist's release groups from the catalogue, each with whether the
-- follow has judged it before.
SELECT g.mbid, g.title, g.primary_type, g.secondary_types, g.first_release_date,
EXISTS (SELECT 1 FROM follow_seen_groups s
WHERE s.artist_mbid = sqlc.arg(artist_mbid) AND s.release_group_mbid = g.mbid) AS seen
FROM mb_artist_release_groups ag
JOIN mb_release_groups g ON g.mbid = ag.release_group_mbid
WHERE ag.artist_mbid = sqlc.arg(artist_mbid)
ORDER BY g.first_release_date, g.title;
-- name: MarkGroupSeen :exec
INSERT INTO follow_seen_groups (artist_mbid, release_group_mbid)
VALUES ($1, $2)
ON CONFLICT DO NOTHING;
-- name: LibraryHoldsReleaseGroup :one
-- Whether the library already has the group: an album tagged with it or
-- with one of its releases, or failing that an album of the artist's with
-- the same title. Only albums with a track on disk count.
SELECT EXISTS (
SELECT 1 FROM albums a
WHERE (a.release_group_mbid = sqlc.arg(group_mbid)::text
OR a.mbid = sqlc.arg(group_mbid)
OR a.mbid IN (SELECT r.mbid FROM mb_releases r WHERE r.release_group_mbid = sqlc.arg(group_mbid))
OR (lower(a.title) = lower(sqlc.arg(title)::text)
AND a.artist_id IN (SELECT ar.id FROM artists ar WHERE ar.mbid = sqlc.arg(artist_mbid)::text)))
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL)
);
-- name: WantReleaseGroup :one
-- Wants a release group, or returns the want already recorded for it. A
-- held want is not reopened here: the library has it.
INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, primary_type,
first_release_date, reason, created_by)
VALUES (sqlc.arg(release_group_mbid), sqlc.arg(artist_mbid), sqlc.arg(artist_name), sqlc.arg(title),
sqlc.arg(primary_type), sqlc.arg(first_release_date), sqlc.arg(reason), sqlc.narg(created_by))
ON CONFLICT (release_group_mbid) DO UPDATE SET updated_at = wants.updated_at
RETURNING *;
-- name: GetWantByReleaseGroup :one
SELECT * FROM wants WHERE release_group_mbid = $1;
-- name: ListOpenWants :many
SELECT * FROM wants
WHERE fulfilled_at IS NULL
ORDER BY wanted_at, id
LIMIT $1;
-- name: WantHoldings :many
-- Each library album that may answer a want, with what it has on disk:
-- tracks present, whether one arrived since the want, and whether a track
-- missing before the want is still missing.
SELECT a.id AS album_id,
COUNT(*) FILTER (WHERE t.missing_since IS NULL)::int AS present,
COALESCE(bool_or(t.missing_since IS NULL AND t.added_at > sqlc.arg(since)::timestamptz), false)::bool AS arrived_since,
COALESCE(bool_or(t.missing_since IS NOT NULL AND t.missing_since < sqlc.arg(since)::timestamptz), false)::bool AS missing_before,
-- Missing tracks no track on disk stands in for, by position or
-- title. A missing row whose song is back at a new path is
-- covered; a lost bonus track is not. A track with no disc number is
-- on disc 1, so a missing track 6 with no disc beside a present 1/6
-- does not keep the album wanted.
COUNT(*) FILTER (WHERE t.missing_since IS NOT NULL AND NOT EXISTS (
SELECT 1 FROM tracks p
WHERE p.album_id = a.id AND p.missing_since IS NULL
AND ((p.track_number = t.track_number AND COALESCE(p.disc_number, 1) = COALESCE(t.disc_number, 1))
OR lower(p.title) = lower(t.title))))::int AS uncovered_missing
FROM albums a
JOIN tracks t ON t.album_id = a.id
WHERE a.release_group_mbid = sqlc.arg(group_mbid)::text
OR a.mbid = sqlc.arg(group_mbid)
OR a.id = sqlc.narg(album_id)
OR a.mbid IN (SELECT r.mbid FROM mb_releases r WHERE r.release_group_mbid = sqlc.arg(group_mbid))
GROUP BY a.id
ORDER BY present DESC, a.id;
-- name: FulfillWant :exec
UPDATE wants
SET fulfilled_at = now(),
album_id = sqlc.arg(album_id),
updated_at = now()
WHERE id = sqlc.arg(id) AND fulfilled_at IS NULL;
-- name: RepointWant :exec
-- A want recorded under a release id is moved to its group.
UPDATE wants SET release_group_mbid = $2, updated_at = now() WHERE id = $1;
-- name: DeleteWant :execrows
DELETE FROM wants WHERE id = $1;
-- name: ListWants :many
-- The Wanted page: open wants (all but missing ones, or only missing ones),
-- the held ones, or all of them; artist_mbid narrows to one artist's page,
-- want_ids to given wants. Ordered like the library: artists A–Z by the
-- library's sort name when it holds the artist, each artist's albums by
-- release date, so the page groups them as they arrive. q narrows to an
-- artist or album title; total counts every match, past the page.
SELECT w.id, w.release_group_mbid, w.artist_mbid, w.artist_name, w.title, w.reason,
w.album_id, w.wanted_at, w.fulfilled_at,
-- Why a held album is wanted again, and the copy it has.
w.upgrade, w.held_quality,
-- A request names an album before the catalogue has read it: the
-- catalogue's type and date fill in once it has.
COALESCE(NULLIF(w.primary_type, ''), g.primary_type, '')::text AS primary_type,
COALESCE(g.secondary_types, '{}')::text[] AS secondary_types,
COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, '')::text AS first_release_date,
u.username AS requested_by,
la.id AS library_artist_id,
COUNT(*) OVER () AS total,
-- The search schedule's last look, and the download running.
w.searched_at, w.search_outcome, w.search_considered, w.best_release, w.best_verdict, w.search_error,
-- Its latest download, running or ended, and what the import made of
-- it.
gr.id AS grab_id, gr.name AS grab_name, gr.grabbed_at, gr.origin AS grab_origin,
gr.quality AS grab_quality, gr.ended_at AS grab_ended_at, gr.end_reason AS grab_end_reason,
gr.progress AS grab_progress, gr.import_state AS grab_import_state,
gr.import_reason AS grab_import_reason, gr.end_detail AS grab_end_detail, gr.imported_at AS grab_imported_at,
gr.imported_files AS grab_imported_files
FROM wants w
LEFT JOIN users u ON u.id = w.created_by
LEFT JOIN mb_release_groups g ON g.mbid = w.release_group_mbid
LEFT JOIN LATERAL (SELECT ar.id, ar.sort_name FROM artists ar WHERE ar.mbid = w.artist_mbid LIMIT 1) la ON true
LEFT JOIN grabs gr ON gr.id = (SELECT x.id FROM grabs x WHERE x.want_id = w.id
ORDER BY x.ended_at IS NULL DESC, x.grabbed_at DESC LIMIT 1)
WHERE CASE sqlc.arg(state)::text
WHEN 'all' THEN true
WHEN 'held' THEN w.fulfilled_at IS NOT NULL
WHEN 'upgrade' THEN w.fulfilled_at IS NOT NULL AND w.upgrade <> ''
WHEN 'missing' THEN w.fulfilled_at IS NULL AND w.reason = 'missing'
ELSE w.fulfilled_at IS NULL AND w.reason <> 'missing'
END
AND (sqlc.arg(artist_mbid)::text = '' OR w.artist_mbid = sqlc.arg(artist_mbid)::text)
-- want_ids narrows to given wants: the Missing page's folders.
AND (COALESCE(cardinality(sqlc.arg(want_ids)::uuid[]), 0) = 0 OR w.id = ANY(sqlc.arg(want_ids)::uuid[]))
AND (sqlc.arg(q)::text = ''
OR strpos(lower(w.artist_name), lower(sqlc.arg(q)::text)) > 0
OR strpos(lower(w.title), lower(sqlc.arg(q)::text)) > 0)
ORDER BY lower(COALESCE(NULLIF(la.sort_name, ''), w.artist_name)), w.artist_mbid,
NULLIF(COALESCE(NULLIF(w.first_release_date, ''), g.first_release_date, ''), '') NULLS LAST,
lower(w.title), w.id
LIMIT sqlc.arg(max_rows) OFFSET sqlc.arg(skip);
-- name: ListWantArtists :many
-- The Wanted view's main page: every artist on the list, A–Z like
-- the library, with how many of their albums are held of how many are on
-- the list. q matches the artist's name or any of their albums' titles;
-- artist_mbid narrows to one artist, for their page's header.
WITH a AS (
SELECT w.artist_mbid,
(array_agg(w.artist_name ORDER BY w.wanted_at DESC))[1] AS artist_name,
COUNT(*) FILTER (WHERE w.fulfilled_at IS NOT NULL)::int AS held,
COUNT(*) FILTER (WHERE w.fulfilled_at IS NULL AND w.reason <> 'missing')::int AS wanted,
COUNT(*) FILTER (WHERE w.fulfilled_at IS NULL AND w.reason = 'missing')::int AS missing,
COUNT(*)::int AS albums,
bool_or(sqlc.arg(q)::text <> '' AND strpos(lower(w.title), lower(sqlc.arg(q)::text)) > 0) AS title_match
FROM wants w
WHERE sqlc.arg(artist_mbid)::text = '' OR w.artist_mbid = sqlc.arg(artist_mbid)::text
GROUP BY w.artist_mbid
)
SELECT a.artist_mbid, a.artist_name::text AS artist_name, a.held, a.wanted, a.missing, a.albums,
COALESCE(NULLIF(la.sort_name, ''), a.artist_name)::text AS sort_name,
la.id AS library_artist_id,
(f.artist_mbid IS NOT NULL)::bool AS following,
(SELECT COUNT(*) FROM grabs g JOIN wants x ON x.id = g.want_id
WHERE x.artist_mbid = a.artist_mbid AND g.ended_at IS NULL)::int AS downloading,
COUNT(*) OVER () AS total
FROM a
LEFT JOIN LATERAL (SELECT ar.id, ar.sort_name FROM artists ar WHERE ar.mbid = a.artist_mbid LIMIT 1) la ON true
LEFT JOIN follows f ON f.artist_mbid = a.artist_mbid
WHERE sqlc.arg(q)::text = ''
OR strpos(lower(a.artist_name), lower(sqlc.arg(q)::text)) > 0
OR a.title_match
ORDER BY lower(COALESCE(NULLIF(la.sort_name, ''), a.artist_name)), a.artist_mbid
LIMIT sqlc.arg(max_rows) OFFSET sqlc.arg(skip);
-- name: GetWantAlbum :one
-- What the Wanted view's track list needs of a want.
SELECT id, release_group_mbid, album_id FROM wants WHERE id = $1;
-- name: ListLibraryAlbumTracks :many
-- A held or missing album's own tracks, for the Wanted view's track list;
-- missing says its file is gone.
SELECT title, disc_number, track_number, duration_ms, (missing_since IS NOT NULL)::bool AS missing
FROM tracks
WHERE album_id = $1
ORDER BY disc_number NULLS FIRST, track_number NULLS LAST, title;
-- name: CountWants :one
SELECT COUNT(*) FILTER (WHERE fulfilled_at IS NULL AND reason <> 'missing')::bigint AS wanted,
COUNT(*) FILTER (WHERE fulfilled_at IS NULL AND reason = 'missing')::bigint AS missing,
COUNT(*) FILTER (WHERE fulfilled_at IS NOT NULL)::bigint AS held,
-- Held albums wanted for a better copy.
COUNT(*) FILTER (WHERE fulfilled_at IS NOT NULL AND upgrade <> '')::bigint AS upgrades,
COUNT(DISTINCT artist_mbid)::bigint AS artists,
-- Library albums waiting to be matched by hand.
(SELECT COUNT(*) FROM library_album_matches m
WHERE m.outcome = 'unmatched'
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id))::bigint AS unmatched,
(SELECT COUNT(*) FROM follows)::bigint AS following,
-- The Wanted view's other tabs: downloads running, those
-- waiting on a person, and releases set aside.
(SELECT COUNT(*) FROM grabs WHERE ended_at IS NULL)::bigint AS activity,
(SELECT COUNT(*) FROM grabs
WHERE ended_at IS NULL AND import_state IN ('review', 'failed'))::bigint AS attention,
(SELECT COUNT(*) FROM release_blocks b
WHERE b.expires_at IS NULL OR b.expires_at > now())::bigint AS blocked
FROM wants;
-- The one-time listing of the library. ---------------------------
-- name: GetLibraryListing :one
SELECT library_listing_started_at, library_listed_at, library_unlisted
FROM acquisition_settings WHERE id = true;
-- name: StartLibraryListing :one
-- Marks the listing begun, once; its time is the cutoff for which albums
-- count as the library's.
UPDATE acquisition_settings
SET library_listing_started_at = COALESCE(library_listing_started_at, now())
WHERE id = true
RETURNING library_listing_started_at;
-- name: ListLibraryAlbums :execrows
-- Puts library albums on the list as held: each release group once, by the
-- album holding the most tracks. Only albums the library had at the cutoff,
-- and with album_id given only that album. A group already on the list is
-- left as it is. An album with tracks already missing is held from just
-- before the first loss, so re-acquisition still fetches it back.
INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, reason, album_id, wanted_at, fulfilled_at)
SELECT DISTINCT ON (a.release_group_mbid)
a.release_group_mbid, ar.mbid, ar.name, a.title, 'library', a.id, now(),
COALESCE((SELECT MIN(t.missing_since) FROM tracks t WHERE t.album_id = a.id) - interval '1 second', now())
FROM albums a
JOIN artists ar ON ar.id = a.artist_id
WHERE a.release_group_mbid IS NOT NULL AND a.release_group_mbid <> ''
AND ar.mbid IS NOT NULL AND ar.mbid <> ''
AND a.created_at <= sqlc.arg(cutoff)::timestamptz
AND (sqlc.narg(album_id)::uuid IS NULL OR a.id = sqlc.narg(album_id)::uuid)
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)
ORDER BY a.release_group_mbid,
(SELECT COUNT(*) FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL) DESC, a.id
ON CONFLICT (release_group_mbid) DO NOTHING;
-- name: RecordListedAlbums :exec
-- The albums ListLibraryAlbums takes are decided as listed by their tags,
-- so the matching that follows leaves them alone.
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
WHERE a.release_group_mbid IS NOT NULL AND a.release_group_mbid <> ''
AND ar.mbid IS NOT NULL AND ar.mbid <> ''
AND a.created_at <= sqlc.arg(cutoff)::timestamptz
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)
ON CONFLICT (album_id) DO NOTHING;
-- name: ListAlbumsToMatch :many
-- Library albums the listing has not decided, or that an older matcher
-- refused, or whose tracks changed since they were refused: each is matched
-- to MusicBrainz. A library album is one from before the cutoff, or
-- one whose tracks were: a re-tag files a track under a new album row but
-- keeps the track. An album row with no tracks is not an album in
-- the library; one a person left off stays off.
SELECT a.id, a.title, a.mbid, a.release_group_mbid, ar.name AS artist_name, ar.mbid AS artist_mbid
FROM albums a
JOIN artists ar ON ar.id = a.artist_id
WHERE (a.created_at <= sqlc.arg(cutoff)::timestamptz
OR EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.added_at <= sqlc.arg(cutoff)::timestamptz))
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)
AND NOT EXISTS (SELECT 1 FROM library_album_matches m
WHERE m.album_id = a.id
AND (m.outcome IN ('listed', 'dismissed')
OR (m.matcher >= sqlc.arg(matcher)::int
AND NOT EXISTS (SELECT 1 FROM tracks t
WHERE t.album_id = a.id AND t.updated_at > m.decided_at))))
ORDER BY a.created_at, a.id
LIMIT sqlc.arg(max_rows);
-- name: CountAlbumsToMatch :one
-- Whether a finished listing has albums to go back to: those
-- ListAlbumsToMatch would hand it.
SELECT COUNT(*)
FROM albums a
WHERE (a.created_at <= sqlc.arg(cutoff)::timestamptz
OR EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id AND t.added_at <= sqlc.arg(cutoff)::timestamptz))
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = a.id)
AND NOT EXISTS (SELECT 1 FROM library_album_matches m
WHERE m.album_id = a.id
AND (m.outcome IN ('listed', 'dismissed')
OR (m.matcher >= sqlc.arg(matcher)::int
AND NOT EXISTS (SELECT 1 FROM tracks t
WHERE t.album_id = a.id AND t.updated_at > m.decided_at))));
-- name: ListAlbumTracksToMatch :many
-- What an album's tracks say about themselves, to check a match against.
SELECT title, disc_number, track_number, duration_ms, mbid
FROM tracks
WHERE album_id = $1
ORDER BY disc_number NULLS FIRST, track_number NULLS LAST, title;
-- name: SetAlbumReleaseGroup :exec
-- Names a matched album's release group, filling only what nothing named.
UPDATE albums SET release_group_mbid = sqlc.arg(release_group_mbid), updated_at = now()
WHERE id = sqlc.arg(id) AND (release_group_mbid IS NULL OR release_group_mbid = '');
-- name: InsertLibraryWant :execrows
-- Puts one matched album on the list as held, from just before its first
-- lost track if it has one. A group already on the list is left as it is.
INSERT INTO wants (release_group_mbid, artist_mbid, artist_name, title, primary_type, first_release_date,
reason, album_id, wanted_at, fulfilled_at)
VALUES (sqlc.arg(release_group_mbid), sqlc.arg(artist_mbid), sqlc.arg(artist_name), sqlc.arg(title),
sqlc.arg(primary_type), sqlc.arg(first_release_date), 'library', sqlc.arg(album_id)::uuid, now(),
COALESCE((SELECT MIN(t.missing_since) FROM tracks t WHERE t.album_id = sqlc.arg(album_id)::uuid)
- interval '1 second', now()))
ON CONFLICT (release_group_mbid) DO NOTHING;
-- name: RecordAlbumMatch :exec
INSERT INTO library_album_matches (album_id, outcome, method, release_group_mbid, detail, matcher)
VALUES (sqlc.arg(album_id), sqlc.arg(outcome), sqlc.arg(method), sqlc.arg(release_group_mbid), sqlc.arg(detail),
sqlc.arg(matcher))
ON CONFLICT (album_id) DO UPDATE
SET outcome = EXCLUDED.outcome, method = EXCLUDED.method, release_group_mbid = EXCLUDED.release_group_mbid,
detail = EXCLUDED.detail, matcher = EXCLUDED.matcher, decided_at = now();
-- name: FinishLibraryListing :one
-- The listing is done, or done again after a newer matcher's retries:
-- count the albums no match was found for. The first finish is kept.
UPDATE acquisition_settings
SET library_listed_at = COALESCE(library_listed_at, now()),
library_unlisted = (SELECT COUNT(*) FROM library_album_matches m
WHERE m.outcome = 'unmatched'
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id))
WHERE id = true
RETURNING library_listed_at, library_unlisted;
-- name: ListUnmatchedLibraryAlbums :many
-- The Collection's Unmatched section: the albums the listing could
-- not match, and below them the ones a person left off. An album whose
-- tracks have all moved to another row is gone, not unmatched.
SELECT m.album_id, a.title, ar.name AS artist_name, m.detail, m.outcome, m.decided_at,
(SELECT COUNT(*) FROM tracks t WHERE t.album_id = a.id AND t.missing_since IS NULL)::int AS tracks
FROM library_album_matches m
JOIN albums a ON a.id = m.album_id
JOIN artists ar ON ar.id = a.artist_id
WHERE m.outcome IN ('unmatched', 'dismissed')
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id)
ORDER BY m.outcome DESC, lower(ar.name), lower(a.title)
LIMIT sqlc.arg(max_rows);
-- name: RecountLibraryUnlisted :exec
-- After a person matches or leaves off an album, the count the catalogue
-- shows.
UPDATE acquisition_settings
SET library_unlisted = (SELECT COUNT(*) FROM library_album_matches m
WHERE m.outcome = 'unmatched'
AND EXISTS (SELECT 1 FROM tracks t WHERE t.album_id = m.album_id))
WHERE id = true;
-- name: GetAlbumToMatch :one
-- One album a person is matching by hand, as the matcher reads albums.
SELECT a.id, a.title, a.mbid, a.release_group_mbid, ar.name AS artist_name, ar.mbid AS artist_mbid
FROM albums a
JOIN artists ar ON ar.id = a.artist_id
JOIN library_album_matches m ON m.album_id = a.id AND m.outcome IN ('unmatched', 'dismissed')
WHERE a.id = $1;
-- name: SetAlbumMatchOutcome :execrows
-- Leave an unmatched album off the list, or put a left-off one back.
UPDATE library_album_matches SET outcome = sqlc.arg(outcome), decided_at = now()
WHERE album_id = sqlc.arg(album_id) AND outcome = sqlc.arg(was);
-- Upgrades. -------------------------------------------------------
-- name: ListHeldWantFormats :many
-- What each held album's copy is made of, for judging whether it is worth
-- upgrading: its present tracks grouped by format, with their bytes and
-- length summed, and how many are held back as video rips. A held want whose
-- album has no track with a length yet has no rows.
SELECT w.id AS want_id, w.upgrade, w.held_tier, w.held_quality,
lower(t.file_format)::text AS file_format,
SUM(t.file_size)::bigint AS bytes,
SUM(t.duration_ms)::bigint AS duration_ms,
COUNT(*)::int AS tracks,
COUNT(*) FILTER (WHERE t.source_verdict = 'suspect')::int AS rips
FROM wants w
JOIN tracks t ON t.album_id = w.album_id
WHERE w.fulfilled_at IS NOT NULL
AND t.missing_since IS NULL AND t.duration_ms > 0
GROUP BY w.id, lower(t.file_format)
ORDER BY w.id;
-- name: SetWantUpgrades :exec
-- Writes the upgrade check's verdicts, one row per want.
UPDATE wants w
SET upgrade = v.upgrade,
held_tier = v.held_tier,
held_quality = v.held_quality,
upgrade_checked_at = now(),
updated_at = CASE WHEN w.upgrade <> v.upgrade THEN now() ELSE w.updated_at END
FROM (SELECT unnest(sqlc.arg(ids)::uuid[]) AS id,
unnest(sqlc.arg(upgrades)::text[]) AS upgrade,
unnest(sqlc.arg(held_tiers)::text[]) AS held_tier,
unnest(sqlc.arg(held_qualities)::text[]) AS held_quality) v
WHERE w.id = v.id;
-- name: ClearHeldUpgrades :execrows
-- A held want whose album has no track left to judge is not wanted again.
UPDATE wants SET upgrade = '', held_tier = '', held_quality = '', upgrade_checked_at = now()
WHERE fulfilled_at IS NOT NULL AND upgrade <> ''
AND NOT EXISTS (SELECT 1 FROM tracks t
WHERE t.album_id = wants.album_id AND t.missing_since IS NULL AND t.duration_ms > 0);