Can fetch records by a specific artist

This commit is contained in:
Claudio Ortolina
2024-12-02 10:20:47 +00:00
parent 963b3c826f
commit b63b3a633a
4 changed files with 79 additions and 1 deletions
+22 -1
View File
@@ -6,7 +6,7 @@ defmodule MusicLibrary.Records do
import Ecto.Query, warn: false
alias MusicLibrary.Repo
alias MusicLibrary.Records.{Cover, Record, SearchParser}
alias MusicLibrary.Records.{ArtistRecord, Cover, Record, SearchParser}
def essential_fields do
[
@@ -17,6 +17,7 @@ defmodule MusicLibrary.Records do
:artists,
:genres,
:musicbrainz_id,
:purchased_at,
:release_ids,
:included_release_group_ids,
:cover_hash,
@@ -89,6 +90,26 @@ defmodule MusicLibrary.Records do
def get_record!(id), do: Repo.get!(Record, id)
def get_artist(musicbrainz_id) do
q =
from ar in ArtistRecord,
where: ar.musicbrainz_id == ^musicbrainz_id,
limit: 1,
select: ar.artist
Repo.one(q)
end
def get_artist_records(musicbrainz_id) do
q =
from r in Record,
join: ar in ArtistRecord,
on: r.id == ar.record_id and ar.musicbrainz_id == ^musicbrainz_id,
select: ^essential_fields()
Repo.all(q)
end
def get_cover(id) do
q =
from r in Record,
@@ -0,0 +1,16 @@
defmodule MusicLibrary.Records.ArtistRecord do
@moduledoc """
This is a lookup table that maps from an artist musicbrainz_id to a record id.
"""
use Ecto.Schema
alias MusicLibrary.Records.Artist
@primary_key false
schema "artist_records" do
field :musicbrainz_id, Ecto.UUID
field :record_id, Ecto.UUID
embeds_one :artist, Artist
end
end
@@ -0,0 +1,18 @@
defmodule MusicLibrary.Repo.Migrations.CreateArtistRecordsView do
use Ecto.Migration
def up do
execute """
CREATE VIEW artist_records AS
SELECT json_extract(json_each.value, '$.musicbrainz_id') AS musicbrainz_id,
records.id AS record_id,
json_each.value as artist
FROM records,
json_each(records.artists)
"""
end
def down do
execute "DROP VIEW artist_records"
end
end
+23
View File
@@ -156,6 +156,29 @@ defmodule MusicLibrary.RecordsTest do
end
end
describe "get_artists_records/1" do
test "it returns records with essential data" do
expected = record_fixture()
artist_musicbrainz_id = expected.artists |> hd() |> Map.get(:musicbrainz_id)
[artist_record] = Records.get_artist_records(artist_musicbrainz_id)
assert expected.id == artist_record.id
end
end
describe "get_artist/1" do
test "it returns records with essential data" do
record = record_fixture()
expected = record.artists |> hd()
artist = Records.get_artist(expected.musicbrainz_id)
assert expected == artist
end
end
describe "get_cover/1" do
test "it returns the record cover by id" do
# while this test may seem redundant, it implicitely checks that ALL record fields are returned,