Skip to content

Commit

Permalink
fix reversibility of create function migration and support bigint pkey
Browse files Browse the repository at this point in the history
  • Loading branch information
matthew fong committed Jun 19, 2020
1 parent c6cdec6 commit afe20ff
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
12 changes: 11 additions & 1 deletion lib/active_record/log_deleted/configuration.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
module ActiveRecord
module LogDeleted
class Configuration
attr_reader :deleted_rows_table_name, :log_deleted_row_function_name, :log_deleted_row_trigger_name
attr_reader(
:deleted_rows_table_name,
:log_deleted_row_function_name,
:log_deleted_row_trigger_name,
:support_uuids
)

def initialize
@deleted_rows_table_name = :deleted_rows
@log_deleted_row_function_name = :log_deleted_row
@log_deleted_row_trigger_name = :log_deleted_row_trigger
@support_uuids = true
end

def deleted_rows_table_name=(name)
Expand All @@ -21,6 +27,10 @@ def log_deleted_row_trigger_name=(name)
@log_deleted_row_trigger_name = sanitize(name)
end

def support_uuids=(value)
@support_uuids = value
end

private

def sanitize(value)
Expand Down
15 changes: 12 additions & 3 deletions lib/active_record/log_deleted/postgresql_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ module ActiveRecord
module LogDeleted
module PostgreSQLAdapter
def create_deleted_rows_table
old_primary_key_type = configuration.support_uuids ? :string : :bigint
create_table deleted_rows_table_name do |t|
t.datetime :created_at, comment: 'The datetime at which the record was created.'
t.text :old_row_json, comment: 'JSON with the entire row that was hard deleted.'
t.string :primary_key, comment: 'The primary key of the row which was hard deleted.'
t.send old_primary_key_type, :primary_key, comment: 'The primary key of the row which was hard deleted.'
t.string :table_name, limit: 255, comment: 'The table name from which the row was hard deleted.'
end
end
Expand All @@ -22,15 +23,17 @@ def create_log_deleted_row_function
BEGIN
INSERT INTO
deleted_rows(table_name, primary_key, old_row_json, created_at)
VALUES (TG_TABLE_NAME, OLD.id::varchar, ROW_TO_JSON(OLD), now());
VALUES (TG_TABLE_NAME, #{old_primary_key('OLD')}, ROW_TO_JSON(OLD), now());
RETURN OLD;
END;
$$ LANGUAGE plpgsql;
SQL
end

def drop_log_deleted_row_function
execute "DROP FUNCTION #{log_deleted_row_function_name};"
execute <<~SQL
DROP FUNCTION IF EXISTS #{log_deleted_row_function_name}();
SQL
end

def create_deleted_row_trigger(table_name)
Expand All @@ -47,6 +50,12 @@ def drop_deleted_row_trigger(table_name)

private

def old_primary_key(table)
value = "#{table}.id"
value += '::varchar' if configuration.support_uuids
value
end

def log_deleted_row_trigger_name
configuration.log_deleted_row_trigger_name
end
Expand Down

0 comments on commit afe20ff

Please sign in to comment.