From 3acffec33379d0a774aea3f3eaa76c0917f59a7e Mon Sep 17 00:00:00 2001 From: stankis <151746694+stankis@users.noreply.github.com> Date: Thu, 18 Jan 2024 10:09:59 +0300 Subject: [PATCH] Added migration script for search on favorites aliases (#56) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added migration script for search on favorites aliases * Update src/db/migrations/20240117092824_add_sort_columns_to_favorites.ts Co-authored-by: Evgenij Shangin * Update src/db/migrations/20240117092824_add_sort_columns_to_favorites.ts Co-authored-by: Evgenij Shangin --------- Co-authored-by: Stanislav Kiselev <“staskis@yandex-team.ru”> Co-authored-by: Evgenij Shangin --- ...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..59b50f87 --- /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 favorites_sort_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 favorites_sort_alias_idx; + DROP INDEX favorites_alias_idx; + + ALTER TABLE favorites DROP COLUMN sort_alias; + ALTER TABLE favorites DROP COLUMN display_alias; + `); +}