Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

safe-pg-migrations

> 后端框架
Open source

Make your PostgreSQL migrations safe

523 stars0 likes3 views
WebsiteGitHub

About

Make your PostgreSQL migrations safe

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 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubycriticality-tier0dododowntimegithub-actions

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

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