Use ->> instead of json_extract in queries
Improves readability of queries.
This commit is contained in:
@@ -126,7 +126,7 @@ A view that extracts artist information from the embedded JSON in the records ta
|
||||
|
||||
```sql
|
||||
CREATE VIEW artist_records AS
|
||||
SELECT json_extract(json_each.value, '$.musicbrainz_id') AS musicbrainz_id,
|
||||
SELECT json_each.value ->> '$.musicbrainz_id' AS musicbrainz_id,
|
||||
records.id AS record_id,
|
||||
json_each.value as artist
|
||||
FROM records,
|
||||
@@ -134,6 +134,7 @@ CREATE VIEW artist_records AS
|
||||
```
|
||||
|
||||
This view is crucial for querying artist information as it:
|
||||
|
||||
- Extracts individual artists from the embedded JSON array in the records table
|
||||
- Provides a normalized view of the artist-record relationships
|
||||
- Makes it easier to query records by artist
|
||||
|
||||
@@ -78,11 +78,11 @@ defmodule MusicLibrary.Collection do
|
||||
q =
|
||||
from r in fragment("records, json_each(records.artists)"),
|
||||
where: fragment("records.purchased_at IS NOT NULL"),
|
||||
group_by: fragment("json_extract(?, '$.name')", r.value),
|
||||
group_by: fragment("? ->> '$.name'", r.value),
|
||||
order_by: [desc: fragment("count(1)")],
|
||||
select: %{
|
||||
id: fragment("json_extract(?, '$.musicbrainz_id')", r.value),
|
||||
name: fragment("json_extract(?, '$.name')", r.value),
|
||||
id: fragment("? ->> '$.musicbrainz_id'", r.value),
|
||||
name: fragment("? ->> '$.name'", r.value),
|
||||
count: fragment("count(1)")
|
||||
},
|
||||
limit: ^limit
|
||||
|
||||
@@ -50,7 +50,7 @@ defmodule MusicLibrary.Records do
|
||||
defmacro order_alphabetically do
|
||||
quote do
|
||||
fragment(
|
||||
"unaccent(json_extract(artists, '$[0].sort_name')) COLLATE NOCASE ASC, unaccent(title) COLLATE NOCASE ASC"
|
||||
"unaccent(artists ->> '$[0].sort_name') COLLATE NOCASE ASC, unaccent(title) COLLATE NOCASE ASC"
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -4,7 +4,7 @@ defmodule MusicLibrary.Repo.Migrations.CreateArtistRecordsView do
|
||||
def up do
|
||||
execute """
|
||||
CREATE VIEW artist_records AS
|
||||
SELECT json_extract(json_each.value, '$.musicbrainz_id') AS musicbrainz_id,
|
||||
SELECT json_each.value ->> '$.musicbrainz_id' AS musicbrainz_id,
|
||||
records.id AS record_id,
|
||||
json_each.value as artist
|
||||
FROM records,
|
||||
|
||||
Reference in New Issue
Block a user