-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Ticket CV2-5653 [WIP]: Adding migration related to last commit
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
db/migrate/20241123135242_add_trigger_to_relationships_table.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
class AddTriggerToRelationshipsTable < ActiveRecord::Migration[6.1] | ||
def up | ||
# Create the trigger function | ||
execute <<~SQL | ||
CREATE OR REPLACE FUNCTION validate_relationships() | ||
RETURNS TRIGGER AS $$ | ||
BEGIN | ||
-- Check if source_id exists as a target_id | ||
IF EXISTS (SELECT 1 FROM relationships WHERE target_id = NEW.source_id) THEN | ||
RAISE EXCEPTION 'source_id % already exists as a target_id', NEW.source_id; | ||
END IF; | ||
-- Check if target_id exists as a source_id | ||
IF EXISTS (SELECT 1 FROM relationships WHERE source_id = NEW.target_id) THEN | ||
RAISE EXCEPTION 'target_id % already exists as a source_id', NEW.target_id; | ||
END IF; | ||
RETURN NEW; | ||
END; | ||
$$ LANGUAGE plpgsql; | ||
SQL | ||
|
||
# Attach the trigger to the table | ||
execute <<~SQL | ||
CREATE TRIGGER enforce_relationships | ||
BEFORE INSERT OR UPDATE ON relationships | ||
FOR EACH ROW | ||
EXECUTE FUNCTION validate_relationships(); | ||
SQL | ||
end | ||
|
||
def down | ||
# Remove the trigger and function if rolling back | ||
execute "DROP TRIGGER IF EXISTS enforce_relationships ON relationships;" | ||
execute "DROP FUNCTION IF EXISTS validate_relationships();" | ||
end | ||
end |