让您的 PostgreSQL 迁移变得安全
ActiveRecord migrations for Postgres made safe.
Just drop this line in your Gemfile:
gem 'safe-pg-migrations'Note: Do not run migrations via PgBouncer connection if it is configured to use transactional or statement pooling modes. You must run migrations via a direct Postgres connection, or configure PgBouncer to use session pooling mode.
Consider the following migration:
…ruby add_column :users, :created_at, default: 'clock_timestamp()'
…ruby
safety_assured do add_column :users, :status, :string, default: 'active', default_value_backfill: :update_in_batches end
safety_assured do add_column :users, :created_at, :datetime, default: -> { 'clock_timestamp()' }, default_value_backfill: :update_in_batches end
…ruby change_column_default :users, :created_at, -> { 'NOW()' }
2. **ADD CONSTRAINT CHECK NOT NULL NOT VALID** (for new and updated rows, only if you need NOT NULL)
```ruby
add_check_constraint :users, "created_at IS NOT NULL",
name: "check_users_created_at_not_null",
validate: falseBACKFILL the column using a job (chunk over the primary key)
# Your own script to backfill in batches
User.in_batches.update_all("created_at = NOW()")VALIDATE CONSTRAINT (check whole table, only if you added the constraint)
validate_check_constraint :users, name: "check_users_created_at_not_null"ALTER COLUMN SET NOT NULL (only if you need NOT NULL)
change_column_null :users, :created_at, falseDROP CONSTRAINT (only if you added the constraint)
remove_check_constraint :users, name: "check_users_created_at_not_null"…bash export SAFE_PG_MIGRATIONS_VERBOSE=1
Instead of the traditional output:
```ruby
add_index :users, :age
== 20191215132355 SampleIndex: migrating ======================================
-- add_index(:users, :age)
-> add_index("users", :age, {:algorithm=>:concurrently})
-> 0.0175s
== 20191215132355 SampleIndex: migrated (0.0200s) =============================Safe PG Migrations will output the following logs:
add_index :users, :age
== 20191215132355 SampleIndex: migrating ======================================
(0.3ms) SHOW lock_timeout
(0.3ms) SET lock_timeout TO '5s'
-- add_index(:users, :age)
-> add_index("users", :age, {:algorithm=>:concurrently})
(0.3ms) SHOW statement_timeout
(0.3ms) SET statement_timeout TO 0
(0.3ms) SHOW lock_timeout
(0.3ms) SET lock_timeout TO '30s'
(3.5ms) CREATE INDEX CONCURRENTLY "index_users_on_age" ON "users" ("age")
(0.3ms) SET lock_timeout TO '5s'
(0.2ms) SET statement_timeout TO '1min'
-> 0.0093s
(0.2ms) SET lock_timeout TO '0'
== 20191215132355 SampleIndex: migrated (0.0114s) =============================So you can actually check that the CREATE INDEX statement will be performed concurrently, without any statement timeout and with a lock timeout of 30 seconds.
Nb: The SHOW statements are used by Safe PG Migrations to query settings for their original values in order to restore them after the work is done
Safe PG Migrations can be customized, here is an example of a Rails initializer (the values are the default ones):
SafePgMigrations.config.safe_timeout = 5.seconds # Statement timeout used for all DDL operations except from CREATE / DROP INDEX
SafePgMigrations.config.lock_timeout = nil # Lock timeout used for all DDL operations except from CREATE / DROP INDEX. If not set, safe_timeout will be used with a deduction of 1% to ensure that the lock timeout is raised in priority
SafePgMigrations.config.increase_lock_timeout_on_retry # Activate the lock timeout increase feature on retry if set to true. See max_lock_timeout_for_retry for more information.
SafePgMigrations.config.max_lock_timeout_for_retry = 1.second # Max lock timeout for the retries for all DDL operations except from CREATE / DROP INDEX. Each retry will increase the lock_timeout (if increase_lock_timeout_on_retry option is set to true) by (max_lock_timeout_for_retry - lock_timeout) / max_tries
SafePgMigrations.config.blocking_activity_logger_verbose = true # Outputs the raw blocking queries on timeout. When false, outputs information about the lock instead
SafePgMigrations.config.sensitive_logger = nil # When given, sensitive data will be sent to this logger instead of the standard output. Must implement method `info`.
SafePgMigrations.config.blocking_activity_logger_margin = 1.second # Delay to output blocking queries before timeout. Must be shorter than safe_timeout
SafePgMigrations.config.backfill_batch_size = 100_000 # Size of the batches used for backfilling when adding a column with a default value
SafePgMigrations.config.backfill_pause = 0.5.second # Delay between each batch during a backfill. This ensure replication can happen safely.
SafePgMigrations.config.default_value_backfill_threshold = nil # When set, batch backfill will only be available if the table is under the given threshold. If the number of rows is higher (according to stats), the migration will fail.
SafePgMigrations.config.retry_delay = 1.minute # Delay between retries for retryable statements
SafePgMigrations.config.max_tries = 5 # Number of retries before abortion of the migrationAlternatives:
Interesting reads:
暂无开放 Issues,或尚未同步最近议题。