From c1fdea952b5f2b98339113c4f06e4364fc834251 Mon Sep 17 00:00:00 2001 From: Stanislav Kiselev <“staskis@yandex-team.ru”> Date: Wed, 17 Jan 2024 17:49:20 +0300 Subject: [PATCH] Added migration script for search on favorites aliases --- ...117092824_add_sort_columns_to_favorites.ts | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/db/migrations/20240117092824_add_sort_columns_to_favorites.ts diff --git a/src/db/migrations/20240117092824_add_sort_columns_to_favorites.ts b/src/db/migrations/20240117092824_add_sort_columns_to_favorites.ts new file mode 100644 index 00000000..3a4e7036 --- /dev/null +++ b/src/db/migrations/20240117092824_add_sort_columns_to_favorites.ts @@ -0,0 +1,38 @@ +import type {Knex} from 'knex'; + +export async function up(knex: Knex): Promise { + return knex.raw(` + ALTER TABLE favorites ADD COLUMN display_alias TEXT; + ALTER TABLE favorites ADD COLUMN sort_alias bytea; + + UPDATE favorites SET display_alias = alias; + CREATE INDEX favorites_alias_idx ON favorites(alias); + + UPDATE favorites SET sort_alias = naturalsort(alias); + CREATE INDEX sort_favorites_alias_idx ON favorites(sort_alias); + + CREATE FUNCTION update_favorites() RETURNS trigger AS $$ + BEGIN + NEW.sort_alias := naturalsort(NEW.alias); + RETURN NEW; + END + $$ LANGUAGE plpgsql; + + CREATE TRIGGER before_favorites_insert_or_update + BEFORE INSERT OR UPDATE ON favorites + FOR EACH ROW EXECUTE PROCEDURE update_favorites(); + `); +} + +export async function down(knex: Knex): Promise { + return knex.raw(` + DROP TRIGGER before_favorites_insert_or_update on favorites; + DROP FUNCTION update_favorites(); + + DROP INDEX sort_favorites_alias_idx; + DROP INDEX favorites_alias_idx; + + ALTER TABLE favorites DROP COLUMN sort_alias; + ALTER TABLE favorites DROP COLUMN display_alias; + `); +}