Use ->> instead of json_extract in queries

Improves readability of queries.
This commit is contained in:
Claudio Ortolina
2025-06-06 21:05:44 +01:00
parent b83e23918c
commit a63f2de60b
4 changed files with 7 additions and 6 deletions
+2 -1
View File
@@ -126,7 +126,7 @@ A view that extracts artist information from the embedded JSON in the records ta
```sql ```sql
CREATE VIEW artist_records AS 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, records.id AS record_id,
json_each.value as artist json_each.value as artist
FROM records, FROM records,
@@ -134,6 +134,7 @@ CREATE VIEW artist_records AS
``` ```
This view is crucial for querying artist information as it: This view is crucial for querying artist information as it:
- Extracts individual artists from the embedded JSON array in the records table - Extracts individual artists from the embedded JSON array in the records table
- Provides a normalized view of the artist-record relationships - Provides a normalized view of the artist-record relationships
- Makes it easier to query records by artist - Makes it easier to query records by artist
+3 -3
View File
@@ -78,11 +78,11 @@ defmodule MusicLibrary.Collection do
q = q =
from r in fragment("records, json_each(records.artists)"), from r in fragment("records, json_each(records.artists)"),
where: fragment("records.purchased_at IS NOT NULL"), 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)")], order_by: [desc: fragment("count(1)")],
select: %{ select: %{
id: fragment("json_extract(?, '$.musicbrainz_id')", r.value), id: fragment("? ->> '$.musicbrainz_id'", r.value),
name: fragment("json_extract(?, '$.name')", r.value), name: fragment("? ->> '$.name'", r.value),
count: fragment("count(1)") count: fragment("count(1)")
}, },
limit: ^limit limit: ^limit
+1 -1
View File
@@ -50,7 +50,7 @@ defmodule MusicLibrary.Records do
defmacro order_alphabetically do defmacro order_alphabetically do
quote do quote do
fragment( 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
end end
@@ -4,7 +4,7 @@ defmodule MusicLibrary.Repo.Migrations.CreateArtistRecordsView do
def up do def up do
execute """ execute """
CREATE VIEW artist_records AS 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, records.id AS record_id,
json_each.value as artist json_each.value as artist
FROM records, FROM records,