百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
S

safe-pg-migrations

> 后端框架
开源

让您的 PostgreSQL 迁移变得安全

523 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

让您的 PostgreSQL 迁移变得安全

safe-pg-migrations

ActiveRecord migrations for Postgres made safe.

Requirements

  • Ruby 3.0+
  • Rails 6.1+
  • PostgreSQL 11.7+

Usage

Just drop this line in your Gemfile:

rb
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.

Example

Consider the following migration:

…

ruby add_column :users, :created_at, default: 'clock_timestamp()'

…

ruby

✅ SAFE - non-volatile default with automatic backfill

safety_assured do add_column :users, :status, :string, default: 'active', default_value_backfill: :update_in_batches end

❌ NOT ALLOWED - volatile default with automatic backfill (will raise an error)

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: false
  1. BACKFILL the column using a job (chunk over the primary key)

    ruby
    # Your own script to backfill in batches
    User.in_batches.update_all("created_at = NOW()")
  2. VALIDATE CONSTRAINT (check whole table, only if you added the constraint)

    ruby
    validate_check_constraint :users, name: "check_users_created_at_not_null"
  3. ALTER COLUMN SET NOT NULL (only if you need NOT NULL)

    ruby
    change_column_null :users, :created_at, false
  4. DROP CONSTRAINT (only if you added the constraint)

    ruby
    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:

ruby
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

Configuration

Safe PG Migrations can be customized, here is an example of a Rails initializer (the values are the default ones):

ruby
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 migration

Authors

  • Matthieu Prat
  • Romain Choquet
  • Thomas Hareau
  • Paul-Etienne Coisne

License

MIT © Doctolib

Additional resources

Alternatives:

  • https://github.com/gocardless/activerecord-safer_migrations
  • https://github.com/ankane/strong_migrations
  • https://github.com/LendingHome/zero_downtime_migrations

Interesting reads:

  • When Postgres blocks: 7 tips for dealing with locks
  • Migrations and Long Transactions in Postgres
  • PostgreSQL Alter Table and Long Transactions
  • Adding a NOT NULL CONSTRAINT on PG Faster with Minimal Locking
  • Adding columns with default values to really large tables in Postgres + Rails
  • Rails migrations with no downtime
  • Safe Operations For High Volume PostgreSQL
  • Rails Migrations with Zero Downtime
  • Stop worrying about PostgreSQL locks in your Rails migrations
  • PostgreSQL at Scale: Database Schema Changes Without Downtime

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubycriticality-tier0dododowntimegithub-actions

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架