From c12bfc284c796b691787b82acaf5d8643bcbfa91 Mon Sep 17 00:00:00 2001 From: Antoine Moreaux Date: Mon, 23 Dec 2024 12:06:06 +0100 Subject: [PATCH] feat(database): Add trigger to set impersonation on first user Introduced a trigger to automatically set `canImpersonate` to true for the first user inserted into the `core.user` table. The trigger is removed after the first user is added to ensure this behavior only applies to the initial user. Includes both the creation and rollback logic for the migration. --- ...to-update-can-impersonate-on-first-user.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 packages/twenty-server/src/database/typeorm/core/migrations/common/1734950137596-add-trigger-to-update-can-impersonate-on-first-user.ts diff --git a/packages/twenty-server/src/database/typeorm/core/migrations/common/1734950137596-add-trigger-to-update-can-impersonate-on-first-user.ts b/packages/twenty-server/src/database/typeorm/core/migrations/common/1734950137596-add-trigger-to-update-can-impersonate-on-first-user.ts new file mode 100644 index 000000000000..6bb19ab9f529 --- /dev/null +++ b/packages/twenty-server/src/database/typeorm/core/migrations/common/1734950137596-add-trigger-to-update-can-impersonate-on-first-user.ts @@ -0,0 +1,44 @@ +import { MigrationInterface, QueryRunner } from 'typeorm'; + +export class AddTriggerToUpdateCanImpersonateOnFirstUser1734950137596 + implements MigrationInterface +{ + name = 'AddTriggerToUpdateCanImpersonateOnFirstUser1734950137596'; + + public async up(queryRunner: QueryRunner): Promise { + queryRunner.query(` +CREATE OR REPLACE FUNCTION set_can_impersonate_to_true_on_first_user() + RETURNS TRIGGER AS $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM core."user") THEN + NEW."canImpersonate" := true; + PERFORM delete_first_user_trigger(); + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +`); + queryRunner.query(` +CREATE TRIGGER insert_user_trigger + BEFORE INSERT ON core."user" + FOR EACH ROW +EXECUTE FUNCTION set_can_impersonate_to_true_on_first_user(); +`); + queryRunner.query(` +CREATE OR REPLACE FUNCTION delete_first_user_trigger() + RETURNS void AS $$ +BEGIN + EXECUTE 'DROP TRIGGER IF EXISTS insert_user_trigger ON core.user'; +END; +$$ LANGUAGE plpgsql; +`); + } + + public async down(queryRunner: QueryRunner): Promise { + queryRunner.query(` +DROP TRIGGER IF EXISTS insert_user_trigger ON core."user"; +DROP FUNCTION IF EXISTS set_can_impersonate_to_true_on_first_user(); +DROP FUNCTION IF EXISTS delete_first_user_trigger(); +`); + } +}