Skip to content

Commit

Permalink
Ticket CV2-5653 [WIP]: Adding migration related to last commit
Browse files Browse the repository at this point in the history
  • Loading branch information
caiosba committed Nov 23, 2024
1 parent f6f551c commit ad8108c
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions db/migrate/20241123135242_add_trigger_to_relationships_table.rb
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

0 comments on commit ad8108c

Please sign in to comment.