discourse/lib/migration/base_dropper.rb
Guo Xiang Tan 40fa96777d
FEATURE: Post deployment migrations. (#6406)
This moves us away from the delayed drops pattern which
was problematic on two counts. First, it uses a hardcoded "delay for"
duration which may be too short for certain deployment strategies.
Second, delayed drop doesn't ensure that it only runs after
the latest application code has been deployed. If the migration runs
and the application code fails to deploy, running the migration after
"delay for" has been met will cause the application to blow up.

The new strategy allows post deployment migrations to be skipped if the
env `SKIP_POST_DEPLOYMENT_MIGRATIONS` is provided.

```
SKIP_POST_DEPLOYMENT_MIGRATIONS=1 rake db:migrate
-> deploy app servers
SKIP_POST_DEPLOYMENT_MIGRATIONS=0 rake db:migrate
```

To aid with the generation of a post deployment migration, a generator
has been added. Simply run `rails generate post_migration`.
2018-10-08 15:47:38 +08:00

54 lines
1.5 KiB
Ruby

module Migration
class BaseDropper
FUNCTION_SCHEMA_NAME = "discourse_functions".freeze
def self.create_readonly_function(table_name, column_name = nil)
DB.exec <<~SQL
CREATE SCHEMA IF NOT EXISTS #{FUNCTION_SCHEMA_NAME};
SQL
message = column_name ?
"Discourse: #{column_name} in #{table_name} is readonly" :
"Discourse: #{table_name} is read only"
DB.exec <<~SQL
CREATE OR REPLACE FUNCTION #{readonly_function_name(table_name, column_name)} RETURNS trigger AS $rcr$
BEGIN
RAISE EXCEPTION '#{message}';
END
$rcr$ LANGUAGE plpgsql;
SQL
end
def self.readonly_function_name(table_name, column_name = nil)
function_name = [
"raise",
table_name,
column_name,
"readonly()"
].compact.join("_")
if DB.exec(<<~SQL).to_s == '1'
SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = '#{FUNCTION_SCHEMA_NAME}'
SQL
"#{FUNCTION_SCHEMA_NAME}.#{function_name}"
else
function_name
end
end
def self.old_readonly_function_name(table_name, column_name = nil)
readonly_function_name(table_name, column_name).sub(
"#{FUNCTION_SCHEMA_NAME}.", ''
)
end
def self.readonly_trigger_name(table_name, column_name = nil)
[table_name, column_name, "readonly"].compact.join("_")
end
end
end