From 9dc72537e5c4c6ced04899be5e68c7759b6a1048 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Thu, 8 Mar 2018 15:05:21 +0800 Subject: [PATCH] FIX: `TableMigrationHelper` didn't clean up after itself. --- lib/table_migration_helper.rb | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/lib/table_migration_helper.rb b/lib/table_migration_helper.rb index 605555d49f8..72870ce0d02 100644 --- a/lib/table_migration_helper.rb +++ b/lib/table_migration_helper.rb @@ -1,7 +1,7 @@ class TableMigrationHelper def self.read_only_table(table_name) ActiveRecord::Base.exec_sql <<-SQL - CREATE OR REPLACE FUNCTION raise_read_only() RETURNS trigger AS $rro$ + CREATE OR REPLACE FUNCTION #{readonly_function_name(table_name)} RETURNS trigger AS $rro$ BEGIN RAISE EXCEPTION 'Discourse: Table is read only'; RETURN null; @@ -10,22 +10,21 @@ class TableMigrationHelper SQL ActiveRecord::Base.exec_sql <<-SQL - CREATE TRIGGER #{table_name}_read_only + CREATE TRIGGER #{readonly_trigger_name(table_name)} BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON #{table_name} FOR EACH STATEMENT - EXECUTE PROCEDURE raise_read_only(); + EXECUTE PROCEDURE #{readonly_function_name(table_name)}; SQL end def self.delayed_drop(old_name:, new_name:, after_migration:, delay: nil, on_drop: nil) - delay ||= Rails.env.production? ? 300 : 0 + delay ||= Rails.env.production? ? 3600 : 0 - sql = < 0 - on_drop&.call - ActiveRecord::Base.exec_sql("DROP TABLE #{old_name}") + on_drop&.call + ActiveRecord::Base.exec_sql("DROP TABLE IF EXISTS #{old_name}") + + ActiveRecord::Base.exec_sql <<~SQL + DROP TRIGGER IF EXISTS #{readonly_trigger_name(old_name)} ON #{old_name}; + DROP FUNCTION IF EXISTS #{readonly_function_name(old_name)} CASCADE; + SQL end end + + private + + def self.readonly_function_name(table_name) + "public.raise_#{table_name}_read_only()" + end + + def self.readonly_trigger_name(table_name) + "#{table_name}_read_only" + end end