From 93cf899bea247125b0095772f9f59cf7902a5150 Mon Sep 17 00:00:00 2001 From: Erik Hjelm Fjeldheim Date: Wed, 25 Nov 2026 17:09:16 -0600 Subject: [PATCH 1/2] feat: #130 support accent-insensitive album and artist search via PostgreSQL unaccent --- README.md | 5 +- server/drizzle/0008_unaccent-search.sql | 43 ++ server/drizzle/meta/0008_snapshot.json | 847 ++++++++++++++++++++++ server/drizzle/meta/_journal.json | 7 + server/src/search/search.postgres.test.ts | 90 ++- server/src/search/search.test.ts | 2 +- server/src/search/search.ts | 2 +- 7 files changed, 984 insertions(+), 12 deletions(-) create mode 100644 server/drizzle/0008_unaccent-search.sql create mode 100644 server/drizzle/meta/0008_snapshot.json diff --git a/README.md b/README.md index 07457cb..7d0d0f7 100644 --- a/README.md +++ b/README.md @@ -291,9 +291,8 @@ Remaining limitations: - Only 100 of the 2,000 albums have a track list, taken from one official release of the release group. The album page says when there are no tracks. - 21 albums have no release year. They sort last and have no decade facet. -- Search is not accent-insensitive: "beyonce" does not find "Beyoncé", and - names in other scripts (for example Mulatu Astatke as ሙላቱ አስታጥቄ) only match - as written. +- Names in non-Latin scripts (for example Mulatu Astatke as ሙላቱ አስታጥቄ) only + match as written (Latin diacritics are normalized with PostgreSQL `unaccent`). - Artists are matched by name, so two different artists with the same name would share a row. None were found in the snapshot. - Classical albums credit the composer as an artist, and compilations use diff --git a/server/drizzle/0008_unaccent-search.sql b/server/drizzle/0008_unaccent-search.sql new file mode 100644 index 0000000..5fa560a --- /dev/null +++ b/server/drizzle/0008_unaccent-search.sql @@ -0,0 +1,43 @@ +CREATE EXTENSION IF NOT EXISTS unaccent; +--> statement-breakpoint +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_ts_config + WHERE cfgname = 'simple_unaccent' + AND cfgnamespace = 'public'::regnamespace + ) THEN + CREATE TEXT SEARCH CONFIGURATION public.simple_unaccent (COPY = pg_catalog.simple); + END IF; +END +$$; +--> statement-breakpoint +ALTER TEXT SEARCH CONFIGURATION public.simple_unaccent + ALTER MAPPING FOR hword, hword_part, word, numword, hword_numpart + WITH unaccent, pg_catalog.simple; +--> statement-breakpoint +CREATE OR REPLACE FUNCTION set_album_search_vector() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + NEW.search_vector := + setweight(to_tsvector('public.simple_unaccent', NEW.title), 'A') || + setweight( + to_tsvector( + 'public.simple_unaccent', + COALESCE(( + SELECT string_agg(artist.name, ' ') + FROM album_artist + JOIN artist ON artist.id = album_artist.artist_id + WHERE album_artist.album_id = NEW.id + ), '') + ), + 'B' + ); + RETURN NEW; +END; +$$; +--> statement-breakpoint +UPDATE album SET title = title; diff --git a/server/drizzle/meta/0008_snapshot.json b/server/drizzle/meta/0008_snapshot.json new file mode 100644 index 0000000..f52fdc9 --- /dev/null +++ b/server/drizzle/meta/0008_snapshot.json @@ -0,0 +1,847 @@ +{ + "id": "5805f264-82aa-45fa-b795-12d9ecee647e", + "prevId": "be61a1b0-26ab-4b78-be38-6ad2a8655ae9", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.album": { + "name": "album", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "release_year": { + "name": "release_year", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "musicbrainz_release_group_id": { + "name": "musicbrainz_release_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "search_vector": { + "name": "search_vector", + "type": "tsvector", + "primaryKey": false, + "notNull": false + }, + "average_rating": { + "name": "average_rating", + "type": "double precision", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_search_vector_idx": { + "name": "album_search_vector_idx", + "columns": [ + { + "expression": "search_vector", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "gin", + "concurrently": false + }, + "album_title_lower_id_idx": { + "name": "album_title_lower_id_idx", + "columns": [ + { + "expression": "lower(\"title\")", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "album_title_lower_desc_id_idx": { + "name": "album_title_lower_desc_id_idx", + "columns": [ + { + "expression": "lower(\"title\") DESC NULLS LAST", + "isExpression": true, + "asc": true, + "nulls": "last" + }, + { + "expression": "\"id\" DESC NULLS LAST", + "isExpression": true, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "album_release_year_asc_id_idx": { + "name": "album_release_year_asc_id_idx", + "columns": [ + { + "expression": "release_year", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "album_release_year_desc_id_idx": { + "name": "album_release_year_desc_id_idx", + "columns": [ + { + "expression": "release_year", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "album_average_rating_asc_id_idx": { + "name": "album_average_rating_asc_id_idx", + "columns": [ + { + "expression": "average_rating", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + }, + "album_average_rating_desc_id_idx": { + "name": "album_average_rating_desc_id_idx", + "columns": [ + { + "expression": "average_rating", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "album_musicbrainz_release_group_id_unique": { + "name": "album_musicbrainz_release_group_id_unique", + "columns": ["musicbrainz_release_group_id"], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_artist": { + "name": "album_artist", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artist_id": { + "name": "artist_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "album_artist_album_id_album_id_fk": { + "name": "album_artist_album_id_album_id_fk", + "tableFrom": "album_artist", + "columnsFrom": ["album_id"], + "tableTo": "album", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "album_artist_artist_id_artist_id_fk": { + "name": "album_artist_artist_id_artist_id_fk", + "tableFrom": "album_artist", + "columnsFrom": ["artist_id"], + "tableTo": "artist", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": { + "album_artist_album_id_artist_id_pk": { + "name": "album_artist_album_id_artist_id_pk", + "columns": ["album_id", "artist_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_genre": { + "name": "album_genre", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "genre_id": { + "name": "genre_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "album_genre_album_id_album_id_fk": { + "name": "album_genre_album_id_album_id_fk", + "tableFrom": "album_genre", + "columnsFrom": ["album_id"], + "tableTo": "album", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "album_genre_genre_id_genre_id_fk": { + "name": "album_genre_genre_id_genre_id_fk", + "tableFrom": "album_genre", + "columnsFrom": ["genre_id"], + "tableTo": "genre", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": { + "album_genre_album_id_genre_id_pk": { + "name": "album_genre_album_id_genre_id_pk", + "columns": ["album_id", "genre_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_user": { + "name": "app_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.artist": { + "name": "artist", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "musicbrainz_artist_id": { + "name": "musicbrainz_artist_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "country": { + "name": "country", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "artist_musicbrainz_artist_id_unique": { + "name": "artist_musicbrainz_artist_id_unique", + "columns": [ + { + "expression": "musicbrainz_artist_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "artist_country_idx": { + "name": "artist_country_idx", + "columns": [ + { + "expression": "country", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.crate_item": { + "name": "crate_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "crate_item_user_album_unique": { + "name": "crate_item_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "crate_item_user_added_at_idx": { + "name": "crate_item_user_added_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "added_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "crate_item_user_id_app_user_id_fk": { + "name": "crate_item_user_id_app_user_id_fk", + "tableFrom": "crate_item", + "columnsFrom": ["user_id"], + "tableTo": "app_user", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "crate_item_album_id_album_id_fk": { + "name": "crate_item_album_id_album_id_fk", + "tableFrom": "crate_item", + "columnsFrom": ["album_id"], + "tableTo": "album", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.genre": { + "name": "genre", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "genre_name_unique": { + "name": "genre_name_unique", + "columns": ["name"], + "nullsNotDistinct": false + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.review": { + "name": "review", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "rating": { + "name": "rating", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "review_user_album_unique": { + "name": "review_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "review_album_idx": { + "name": "review_album_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "review_user_id_app_user_id_fk": { + "name": "review_user_id_app_user_id_fk", + "tableFrom": "review", + "columnsFrom": ["user_id"], + "tableTo": "app_user", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + }, + "review_album_id_album_id_fk": { + "name": "review_album_id_album_id_fk", + "tableFrom": "review", + "columnsFrom": ["album_id"], + "tableTo": "album", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "review_rating_range": { + "name": "review_rating_range", + "value": "\"review\".\"rating\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "public.search_history": { + "name": "search_history", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_searched_at": { + "name": "last_searched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "search_history_user_recent_idx": { + "name": "search_history_user_recent_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_searched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "search_history_user_id_app_user_id_fk": { + "name": "search_history_user_id_app_user_id_fk", + "tableFrom": "search_history", + "columnsFrom": ["user_id"], + "tableTo": "app_user", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": { + "search_history_user_id_query_pk": { + "name": "search_history_user_id_query_pk", + "columns": ["user_id", "query"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "search_history_query_nonempty": { + "name": "search_history_query_nonempty", + "value": "length(btrim(\"search_history\".\"query\")) > 0" + } + }, + "isRLSEnabled": false + }, + "public.track": { + "name": "track", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "track_number": { + "name": "track_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_seconds": { + "name": "duration_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "track_album_track_number_unique": { + "name": "track_album_track_number_unique", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "with": {}, + "method": "btree", + "concurrently": false + }, + "track_album_track_number_idx": { + "name": "track_album_track_number_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "with": {}, + "method": "btree", + "concurrently": false + } + }, + "foreignKeys": { + "track_album_id_album_id_fk": { + "name": "track_album_id_album_id_fk", + "tableFrom": "track", + "columnsFrom": ["album_id"], + "tableTo": "album", + "columnsTo": ["id"], + "onUpdate": "no action", + "onDelete": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "views": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index 8e2eeaf..d0de76c 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -57,6 +57,13 @@ "when": 1794671787291, "tag": "0007_album_sort_cursor_indexes", "breakpoints": true + }, + { + "idx": 8, + "version": "7", + "when": 1795553702444, + "tag": "0008_unaccent-search", + "breakpoints": true } ] } diff --git a/server/src/search/search.postgres.test.ts b/server/src/search/search.postgres.test.ts index 29edbf0..55321b8 100644 --- a/server/src/search/search.postgres.test.ts +++ b/server/src/search/search.postgres.test.ts @@ -1,10 +1,10 @@ import { PgDialect } from 'drizzle-orm/pg-core'; import { Pool } from 'pg'; -import { afterAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { searchFilter, sortKey } from './search.js'; // Set TEST_DATABASE_URL to run these tests. VALUES supplies temporary test rows; -// the queries do not read or change stored albums. +// the real-table suite inserts tagged fixtures and removes them in afterAll. describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL prefix search', () => { const pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL }); const dialect = new PgDialect(); @@ -22,17 +22,27 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL prefix search', () = [String.raw`"' \\ ); DROP TABLE album; --`, []], ['radio OR dark', []], ['björ', ['Björk']], + ['bjork', ['Björk']], + ['bjor', ['Björk']], + ['cafe', ['Café del Mar']], + ['café', ['Café del Mar']], + ['beyonce', ['Beyoncé']], + ['jose merce', ['José Mercé']], + ['jose mer', ['José Mercé']], ])('matches safely for %j', async (query, expected) => { const input = { query, sort: 'RELEVANCE' as const }; const filter = dialect.sqlToQuery(searchFilter(input)); const rank = dialect.sqlToQuery(sortKey(input).expr); const fixture = `FROM ( - SELECT title, to_tsvector('simple', title) AS search_vector + SELECT title, to_tsvector('public.simple_unaccent', title) AS search_vector FROM (VALUES ('Radiohead'), ('Dark Side of the Moon'), ('Dark'), - ('Björk') + ('Björk'), + ('Café del Mar'), + ('Beyoncé'), + ('José Mercé') ) AS titles(title) ) AS album`; @@ -62,13 +72,13 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL prefix search', () = }); it('keeps weighted title matches ahead of artist matches', async () => { - const key = dialect.sqlToQuery(sortKey({ query: 'radio', sort: 'RELEVANCE' }).expr); + const key = dialect.sqlToQuery(sortKey({ query: 'bjork', sort: 'RELEVANCE' }).expr); const result = await pool.query<{ id: number; rank: number }>( `SELECT id, ${key.sql} AS rank FROM (VALUES - (1, setweight(to_tsvector('simple', 'Radiohead'), 'B')), - (2, setweight(to_tsvector('simple', 'Radiohead'), 'A')) + (1, setweight(to_tsvector('public.simple_unaccent', 'Björk'), 'B')), + (2, setweight(to_tsvector('public.simple_unaccent', 'Björk'), 'A')) ) AS album(id, search_vector) ORDER BY rank DESC, id ASC`, key.params, @@ -76,4 +86,70 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL prefix search', () = expect(result.rows.map((row) => row.id)).toEqual([2, 1]); }); + + describe('album and artist trigger accent-insensitive search', () => { + const tag = `unaccent${Math.random() + .toString(36) + .replace(/[^a-z]/g, '')}`; + const albumIds: number[] = []; + const artistIds: number[] = []; + + beforeAll(async () => { + const fixtures = [ + { title: `Café del Mar ${tag}`, artist: `Röyksopp ${tag}` }, + { title: `Homogenic ${tag}`, artist: `Björk ${tag}` }, + { title: `Lemonade ${tag}`, artist: `Beyoncé ${tag}` }, + { title: `Aire ${tag}`, artist: `José Mercé ${tag}` }, + ]; + + for (const item of fixtures) { + const albumRes = await pool.query<{ id: number }>( + 'INSERT INTO album (title, release_year) VALUES ($1, 2000) RETURNING id', + [item.title], + ); + const artistRes = await pool.query<{ id: number }>( + 'INSERT INTO artist (name) VALUES ($1) RETURNING id', + [item.artist], + ); + const albumId = albumRes.rows[0]!.id; + const artistId = artistRes.rows[0]!.id; + albumIds.push(albumId); + artistIds.push(artistId); + await pool.query( + 'INSERT INTO album_artist (album_id, artist_id, position) VALUES ($1, $2, 0)', + [albumId, artistId], + ); + } + }); + + afterAll(async () => { + if (albumIds.length > 0) { + await pool.query('DELETE FROM album WHERE id = ANY($1)', [albumIds]); + } + if (artistIds.length > 0) { + await pool.query('DELETE FROM artist WHERE id = ANY($1)', [artistIds]); + } + }); + + it.each([ + [`cafe ${tag}`, `Café del Mar ${tag}`], + [`café ${tag}`, `Café del Mar ${tag}`], + [`royksopp ${tag}`, `Café del Mar ${tag}`], + [`bjork ${tag}`, `Homogenic ${tag}`], + [`bjor ${tag}`, `Homogenic ${tag}`], + [`beyonce ${tag}`, `Lemonade ${tag}`], + [`jose merce ${tag}`, `Aire ${tag}`], + [`jose mer ${tag}`, `Aire ${tag}`], + ])( + 'matches accented titles and artists for query %j via search_vector trigger', + async (query, expectedTitle) => { + const filter = dialect.sqlToQuery(searchFilter({ query, sort: 'RELEVANCE' })); + const result = await pool.query<{ title: string }>( + `SELECT title FROM album WHERE ${filter.sql} ORDER BY id`, + filter.params, + ); + expect(result.rows.map((row) => row.title)).toEqual([expectedTitle]); + }, + ); + }); }); diff --git a/server/src/search/search.test.ts b/server/src/search/search.test.ts index 5ae59aa..290ce3c 100644 --- a/server/src/search/search.test.ts +++ b/server/src/search/search.test.ts @@ -189,7 +189,7 @@ describe('searchFilter', () => { it('normalizes and quotes prefix lexemes while keeping input parameterised', () => { const { sql, params } = render(searchFilter(input({ query: ' Blue ' }))); - expect(sql).toContain("to_tsvector('simple', $1)"); + expect(sql).toContain("to_tsvector('public.simple_unaccent', $1)"); expect(sql).toContain("array_to_tsvector(ARRAY[lexeme])::text || ':*'"); expect(params).toEqual(['Blue']); }); diff --git a/server/src/search/search.ts b/server/src/search/search.ts index 0eeb4a8..8d0ba91 100644 --- a/server/src/search/search.ts +++ b/server/src/search/search.ts @@ -78,7 +78,7 @@ function tsQuery(query: string): SQL { string_agg(array_to_tsvector(ARRAY[lexeme])::text || ':*', ' & '), '' )::tsquery - FROM unnest(tsvector_to_array(to_tsvector('simple', ${query}))) AS tokens(lexeme) + FROM unnest(tsvector_to_array(to_tsvector('public.simple_unaccent', ${query}))) AS tokens(lexeme) )`; } From d235ecf2b32bdb39de7e208c2cfb576102d5e792 Mon Sep 17 00:00:00 2001 From: Erik Hjelm Fjeldheim Date: Thu, 26 Nov 2026 13:27:37 -0600 Subject: [PATCH 2/2] fix: #130 handle numhword accents and test artist rename trigger --- server/drizzle/0008_unaccent-search.sql | 2 +- server/src/search/search.postgres.test.ts | 79 +++++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/server/drizzle/0008_unaccent-search.sql b/server/drizzle/0008_unaccent-search.sql index 5fa560a..6b277fa 100644 --- a/server/drizzle/0008_unaccent-search.sql +++ b/server/drizzle/0008_unaccent-search.sql @@ -14,7 +14,7 @@ END $$; --> statement-breakpoint ALTER TEXT SEARCH CONFIGURATION public.simple_unaccent - ALTER MAPPING FOR hword, hword_part, word, numword, hword_numpart + ALTER MAPPING FOR hword, hword_part, word, numword, numhword, hword_numpart WITH unaccent, pg_catalog.simple; --> statement-breakpoint CREATE OR REPLACE FUNCTION set_album_search_vector() diff --git a/server/src/search/search.postgres.test.ts b/server/src/search/search.postgres.test.ts index 55321b8..701e2fd 100644 --- a/server/src/search/search.postgres.test.ts +++ b/server/src/search/search.postgres.test.ts @@ -87,16 +87,46 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL prefix search', () = expect(result.rows.map((row) => row.id)).toEqual([2, 1]); }); + it('matches hyphenated letter+digit accented tokens (numhword)', async () => { + const fixture = `FROM ( + SELECT title, to_tsvector('public.simple_unaccent', title) AS search_vector + FROM (VALUES ('Café-80s')) AS titles(title) + ) AS album`; + + for (const query of ['cafe-80s', 'café-80s', 'cafe 80s']) { + const input = { query, sort: 'RELEVANCE' as const }; + const filter = dialect.sqlToQuery(searchFilter(input)); + const rank = dialect.sqlToQuery(sortKey(input).expr); + + const result = await pool.query<{ title: string }>( + `SELECT title ${fixture} WHERE ${filter.sql}`, + filter.params, + ); + expect(result.rows.map((row) => row.title)).toEqual(['Café-80s']); + + const ranked = await pool.query<{ title: string; rank: number }>( + `SELECT title, ${rank.sql} AS rank ${fixture} WHERE ${filter.sql}`, + rank.params, + ); + expect(ranked.rows).toHaveLength(1); + expect(ranked.rows[0]!.rank).toBeGreaterThan(0); + } + }); + describe('album and artist trigger accent-insensitive search', () => { const tag = `unaccent${Math.random() .toString(36) .replace(/[^a-z]/g, '')}`; + const numhwordTag = `numhword${Math.random() + .toString(36) + .replace(/[^a-z]/g, '')}`; const albumIds: number[] = []; const artistIds: number[] = []; beforeAll(async () => { const fixtures = [ { title: `Café del Mar ${tag}`, artist: `Röyksopp ${tag}` }, + { title: `Café-80s ${numhwordTag}`, artist: `Daft Punk ${numhwordTag}` }, { title: `Homogenic ${tag}`, artist: `Björk ${tag}` }, { title: `Lemonade ${tag}`, artist: `Beyoncé ${tag}` }, { title: `Aire ${tag}`, artist: `José Mercé ${tag}` }, @@ -134,6 +164,8 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL prefix search', () = it.each([ [`cafe ${tag}`, `Café del Mar ${tag}`], [`café ${tag}`, `Café del Mar ${tag}`], + [`cafe-80s ${numhwordTag}`, `Café-80s ${numhwordTag}`], + [`café-80s ${numhwordTag}`, `Café-80s ${numhwordTag}`], [`royksopp ${tag}`, `Café del Mar ${tag}`], [`bjork ${tag}`, `Homogenic ${tag}`], [`bjor ${tag}`, `Homogenic ${tag}`], @@ -151,5 +183,52 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL prefix search', () = expect(result.rows.map((row) => row.title)).toEqual([expectedTitle]); }, ); + + it('refreshes search_vector when an artist is renamed to an accented name', async () => { + const renameTag = `rename${Math.random() + .toString(36) + .replace(/[^a-z]/g, '')}`; + const albumTitle = `Ágætis byrjun ${renameTag}`; + const albumRes = await pool.query<{ id: number }>( + 'INSERT INTO album (title, release_year) VALUES ($1, 1999) RETURNING id', + [albumTitle], + ); + const artistRes = await pool.query<{ id: number }>( + 'INSERT INTO artist (name) VALUES ($1) RETURNING id', + [`Original Artist ${renameTag}`], + ); + const albumId = albumRes.rows[0]!.id; + const artistId = artistRes.rows[0]!.id; + albumIds.push(albumId); + artistIds.push(artistId); + + await pool.query( + 'INSERT INTO album_artist (album_id, artist_id, position) VALUES ($1, $2, 0)', + [albumId, artistId], + ); + + await pool.query('UPDATE artist SET name = $1 WHERE id = $2', [ + `Sigur Rós ${renameTag}`, + artistId, + ]); + + const renamedFilter = dialect.sqlToQuery( + searchFilter({ query: `sigur ros ${renameTag}`, sort: 'RELEVANCE' }), + ); + const renamedResult = await pool.query<{ title: string }>( + `SELECT title FROM album WHERE ${renamedFilter.sql} ORDER BY id`, + renamedFilter.params, + ); + expect(renamedResult.rows.map((row) => row.title)).toEqual([albumTitle]); + + const oldNameFilter = dialect.sqlToQuery( + searchFilter({ query: `original artist ${renameTag}`, sort: 'RELEVANCE' }), + ); + const oldNameResult = await pool.query<{ title: string }>( + `SELECT title FROM album WHERE ${oldNameFilter.sql} ORDER BY id`, + oldNameFilter.params, + ); + expect(oldNameResult.rows).toEqual([]); + }); }); });