Files
ubicloud/migrate/20241230_archived_record_trigger.rb
Jeremy Evans b0794935a2 Add migration to use archived_record for applied_{subject,action,object}_tag
This adds a simple trigger function to insert into the
archived_record table, and triggers on the
applied_{subject,action,object}_tag tables to use it.  This
approach is used instead of the before_destroy approach because
these tables do not have models associated with them.

We could consider this approach for other tables in the future
as a more efficient replacement for the before_destroy approach.
2024-12-31 11:34:51 -08:00

30 lines
795 B
Ruby

# frozen_string_literal: true
Sequel.migration do
up do
run <<~SQL
CREATE FUNCTION archived_record_insert() RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO archived_record (model_name, model_values) VALUES (TG_ARGV[0], to_jsonb(OLD));
RETURN NEW;
END;
$$
SQL
%w[subject action object].each do |tag_type|
run <<~SQL
CREATE TRIGGER archived_record_insert AFTER DELETE ON applied_#{tag_type}_tag
FOR EACH ROW EXECUTE FUNCTION archived_record_insert('applied_#{tag_type}_tag')
SQL
end
end
down do
%w[subject action object].each do |tag_type|
run "DROP TRIGGER archived_record_insert ON applied_#{tag_type}_tag"
end
run "DROP FUNCTION archived_record_insert()"
end
end