safe-pg-migrations 0.0.3 → 1.2.2
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/README.md +128 -23
- data/lib/safe-pg-migrations/base.rb +17 -7
- data/lib/safe-pg-migrations/configuration.rb +13 -4
- data/lib/safe-pg-migrations/plugins/blocking_activity_logger.rb +18 -6
- data/lib/safe-pg-migrations/plugins/idem_potent_statements.rb +32 -0
- data/lib/safe-pg-migrations/plugins/statement_insurer.rb +48 -11
- data/lib/safe-pg-migrations/plugins/statement_retrier.rb +1 -2
- data/lib/safe-pg-migrations/plugins/useless_statements_logger.rb +33 -0
- data/lib/safe-pg-migrations/plugins/verbose_sql_logger.rb +43 -0
- data/lib/safe-pg-migrations/railtie.rb +1 -1
- data/lib/safe-pg-migrations/version.rb +1 -1
- metadata +10 -8
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
|
-
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: d981ad3d9694961fa982676398e257817a2f20fb5ef28111c664da67d8caef19
|
4
|
+
data.tar.gz: 7792a0f882fe9c594a1a0309bba12f03c2d0d18d5a0ef68fe49e1681da486ba6
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: a3d03df54c2a401ea4d7d178d66c8fc49c605cebc1e15f87a69e262df2bfc6433ef7ab86ae21e3ce88b52224a0c9fd14c3cf5f923e109ef06da2d55072fc7d3e
|
7
|
+
data.tar.gz: b28101c7aedcdfb6fc3680ce9c5b14b459ed90fecf21aaf598942f6c91ebd757f1ed608f71c00e622ec9b24cf1f719a6450ae3ef28abd4f07476fd02f7c54242
|
data/README.md
CHANGED
@@ -1,10 +1,10 @@
|
|
1
|
-
# safe-pg-migrations
|
1
|
+
# safe-pg-migrations
|
2
2
|
|
3
3
|
ActiveRecord migrations for Postgres made safe.
|
4
4
|
|
5
5
|
## Requirements
|
6
6
|
|
7
|
-
- Ruby 2.
|
7
|
+
- Ruby 2.5+
|
8
8
|
- Rails 5.2+
|
9
9
|
- PostgreSQL 9.3+
|
10
10
|
|
@@ -16,6 +16,8 @@ Just drop this line in your Gemfile:
|
|
16
16
|
gem 'safe-pg-migrations'
|
17
17
|
```
|
18
18
|
|
19
|
+
**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.**
|
20
|
+
|
19
21
|
## Example
|
20
22
|
|
21
23
|
Consider the following migration:
|
@@ -28,7 +30,7 @@ class AddAdminToUsers < ActiveRecord::Migration[5.2]
|
|
28
30
|
end
|
29
31
|
```
|
30
32
|
|
31
|
-
If the `users` table is large, running this migration on a live Postgres database will likely cause downtime. **Safe PG Migrations** hooks into Active Record so that the following gets executed instead:
|
33
|
+
If the `users` table is large, running this migration on a live Postgres 9 database will likely cause downtime. **Safe PG Migrations** hooks into Active Record so that the following gets executed instead:
|
32
34
|
|
33
35
|
```rb
|
34
36
|
class AddAdminToUsers < ActiveRecord::Migration[5.2]
|
@@ -61,27 +63,29 @@ Under the hood, **Safe PG Migrations** patches `ActiveRecord::Migration` and ext
|
|
61
63
|
|
62
64
|
## Motivation
|
63
65
|
|
64
|
-
Writing a safe migration can be daunting. Numerous articles have been written on the topic and a few gems are trying to address the problem. Even for someone who has a pretty good command of Postgres, remembering all the subtleties of explicit locking is not a piece of cake.
|
66
|
+
Writing a safe migration can be daunting. Numerous articles, [including ours](https://medium.com/doctolib/stop-worrying-about-postgresql-locks-in-your-rails-migrations-3426027e9cc9), have been written on the topic and a few gems are trying to address the problem. Even for someone who has a pretty good command of Postgres, remembering all the subtleties of explicit locking is not a piece of cake.
|
65
67
|
|
66
68
|
Active Record means developers don't have to be proficient in SQL to interact with a database. In the same way, **Safe PG Migrations** was created so that developers don't have to understand the ins and outs of Postgres to write a safe migration.
|
67
69
|
|
68
70
|
## Feature set
|
69
71
|
|
70
|
-
|
72
|
+
<details><summary>Lock timeout</summary>
|
71
73
|
|
72
|
-
Most DDL operations (e.g. adding a column, removing a column or adding a default value to a column) take an `ACCESS EXCLUSIVE` lock on the table they are altering. While these operations wait to acquire their lock, other statements are blocked. Before running a migration, **Safe PG Migrations** sets a short lock timeout so that statements are not blocked for too long.
|
74
|
+
Most DDL operations (e.g. adding a column, removing a column or adding a default value to a column) take an `ACCESS EXCLUSIVE` lock on the table they are altering. While these operations wait to acquire their lock, other statements are blocked. Before running a migration, **Safe PG Migrations** sets a short lock timeout (default to 5 seconds) so that statements are not blocked for too long.
|
73
75
|
|
74
76
|
See [PostgreSQL Alter Table and Long Transactions](http://www.joshuakehn.com/2017/9/9/postgresql-alter-table-and-long-transactions.html) and [Migrations and Long Transactions](https://www.fin.com/post/2018/1/migrations-and-long-transactions) for detailed explanations of the matter.
|
77
|
+
</details>
|
75
78
|
|
76
|
-
|
79
|
+
<details><summary>Statement timeout</summary>
|
77
80
|
|
78
|
-
Adding a foreign key or a not-null constraint can take a lot of time on a large table. The problem is that those operations take `ACCESS EXCLUSIVE` locks. We clearly don't want them to hold these locks for too long. Thus, **Safe PG Migrations** runs them with a short statement timeout.
|
81
|
+
Adding a foreign key or a not-null constraint can take a lot of time on a large table. The problem is that those operations take `ACCESS EXCLUSIVE` locks. We clearly don't want them to hold these locks for too long. Thus, **Safe PG Migrations** runs them with a short statement timeout (default to 5 seconds).
|
79
82
|
|
80
83
|
See [Zero-downtime Postgres migrations - the hard parts](https://gocardless.com/blog/zero-downtime-postgres-migrations-the-hard-parts/) for a detailed explanation on the subject.
|
84
|
+
</details>
|
81
85
|
|
82
|
-
|
86
|
+
<details><summary>Prevent wrapping migrations in transaction</summary>
|
83
87
|
|
84
|
-
When **Safe PG Migrations** is
|
88
|
+
When **Safe PG Migrations** is used, migrations are not wrapped in a transaction. This is for several reasons:
|
85
89
|
|
86
90
|
- We want to release locks as soon as possible.
|
87
91
|
- In order to be able to retry statements that have failed because of a lock timeout, we have to be outside a transaction.
|
@@ -89,8 +93,22 @@ When **Safe PG Migrations** is enabled (which is the case by default if `Rails.e
|
|
89
93
|
|
90
94
|
Note that if a migration fails, it won't be rollbacked. This can result in migrations being partially applied. In that case, they need to be manually reverted.
|
91
95
|
|
92
|
-
|
96
|
+
</details>
|
97
|
+
|
98
|
+
<details>
|
99
|
+
<summary>Safe <code>add_column</code></summary>
|
100
|
+
|
101
|
+
**Safe PG Migrations** gracefully handle the upgrade to PG11 by **not** backfilling default value for existing rows, as the [database engine is now natively handling it](https://www.postgresql.org/docs/11/ddl-alter.html#DDL-ALTER-ADDING-A-COLUMN).
|
102
|
+
|
103
|
+
Beware though, when adding a volatile default value:
|
104
|
+
```ruby
|
105
|
+
add_column :users, :created_at, default: 'clock_timestamp()'
|
106
|
+
```
|
107
|
+
PG will still needs to update every row of the table, and will most likely statement timeout for big table. In this case, your best bet is to add the column without default, set the default, and backfill existing rows.
|
93
108
|
|
109
|
+
<blockquote>
|
110
|
+
|
111
|
+
**Note: Pre-postgre 11**
|
94
112
|
Adding a column with a default value and a not-null constraint is [dangerous](https://wework.github.io/data/2015/11/05/add-columns-with-default-values-to-large-tables-in-rails-postgres/).
|
95
113
|
|
96
114
|
**Safe PG Migrations** makes it safe by:
|
@@ -102,17 +120,102 @@ Adding a column with a default value and a not-null constraint is [dangerous](ht
|
|
102
120
|
|
103
121
|
Note: the addition of the not null constraint may timeout. In that case, you may want to add the not-null constraint as initially not valid and validate it in a separate statement. See [Adding a not-null constraint on Postgres with minimal locking](https://medium.com/doctolib-engineering/adding-a-not-null-constraint-on-pg-faster-with-minimal-locking-38b2c00c4d1c).
|
104
122
|
|
105
|
-
|
123
|
+
</blockquote>
|
124
|
+
|
125
|
+
</details>
|
126
|
+
|
127
|
+
<details><summary id="safe_add_remove_index">Safe <code>add_index</code> and <code>remove_index</code></summary>
|
106
128
|
|
107
129
|
Creating an index requires a `SHARE` lock on the target table which blocks all write on the table while the index is created (which can take some time on a large table). This is usually not practical in a live environment. Thus, **Safe PG Migrations** ensures indexes are created concurrently.
|
108
130
|
|
109
|
-
|
131
|
+
As `CREATE INDEX CONCURRENTLY` and `DROP INDEX CONCURRENTLY` are non-blocking operations (ie: read/write operations on the table are still possible), **Safe PG Migrations** sets a lock timeout to 30 seconds for those 2 specific statements.
|
132
|
+
|
133
|
+
If you still get lock timeout while adding / removing indexes, it might be for one of those reasons:
|
110
134
|
|
111
|
-
|
135
|
+
- Long-running queries are active on the table. To create / remove an index, PG needs to wait for the queries that are actually running to finish before starting the index creation / removal. The blocking activity logger might help you to pinpoint the culprit queries.
|
136
|
+
- A vacuum / autovacuum is running on the table, holding a ShareUpdateExclusiveLock, you are most likely out of luck for the current migration, but you may try to [optimize your autovacuums settings](https://www.percona.com/blog/2018/08/10/tuning-autovacuum-in-postgresql-and-autovacuum-internals/).
|
112
137
|
|
113
|
-
|
138
|
+
</details>
|
139
|
+
|
140
|
+
<details><summary id="safe_add_foreign_key">safe <code>add_foreign_key</code> (and <code>add_reference</code>)</summary>
|
141
|
+
|
142
|
+
Adding a foreign key requires a `SHARE ROW EXCLUSIVE` lock, which **prevent writing in the tables** while the migration is running.
|
143
|
+
|
144
|
+
Adding the constraint itself is rather fast, the major part of the time is spent on validating this constraint. Thus safe-pg-migrations ensures that adding a foreign key holds blocking locks for the least amount of time by splitting the foreign key creation in two steps:
|
145
|
+
|
146
|
+
1. adding the constraint *without validation*, will not validate existing rows;
|
147
|
+
2. validating the constraint, will validate existing rows in the table, without blocking read or write on the table
|
148
|
+
|
149
|
+
</details>
|
150
|
+
|
151
|
+
<details><summary>Retry after lock timeout</summary>
|
152
|
+
|
153
|
+
When a statement fails with a lock timeout, **Safe PG Migrations** retries it (5 times max) [list of retryable statments](https://github.com/doctolib/safe-pg-migrations/blob/66933256252b6bbf12e404b829a361dbba30e684/lib/safe-pg-migrations/plugins/statement_retrier.rb#L5)
|
154
|
+
</details>
|
155
|
+
|
156
|
+
<details><summary>Blocking activity logging</summary>
|
114
157
|
|
115
158
|
If a statement fails with a lock timeout, **Safe PG Migrations** will try to tell you what was the blocking statement.
|
159
|
+
</details>
|
160
|
+
|
161
|
+
<details><summary>Verbose SQL logging</summary>
|
162
|
+
|
163
|
+
For any operation, **Safe PG Migrations** can output the performed SQL queries. This feature is enabled by default in a production Rails environment. If you want to explicit enable it, for example in your development environment you can use:
|
164
|
+
```bash
|
165
|
+
export SAFE_PG_MIGRATIONS_VERBOSE=1
|
166
|
+
```
|
167
|
+
|
168
|
+
Instead of the traditional output:
|
169
|
+
```ruby
|
170
|
+
add_index :users, :age
|
171
|
+
|
172
|
+
== 20191215132355 SampleIndex: migrating ======================================
|
173
|
+
-- add_index(:users, :age)
|
174
|
+
-> add_index("users", :age, {:algorithm=>:concurrently})
|
175
|
+
-> 0.0175s
|
176
|
+
== 20191215132355 SampleIndex: migrated (0.0200s) =============================
|
177
|
+
```
|
178
|
+
**Safe PG Migrations** will output the following logs:
|
179
|
+
```ruby
|
180
|
+
add_index :users, :age
|
181
|
+
|
182
|
+
== 20191215132355 SampleIndex: migrating ======================================
|
183
|
+
(0.3ms) SHOW lock_timeout
|
184
|
+
(0.3ms) SET lock_timeout TO '5s'
|
185
|
+
-- add_index(:users, :age)
|
186
|
+
-> add_index("users", :age, {:algorithm=>:concurrently})
|
187
|
+
(0.3ms) SHOW statement_timeout
|
188
|
+
(0.3ms) SET statement_timeout TO 0
|
189
|
+
(0.3ms) SHOW lock_timeout
|
190
|
+
(0.3ms) SET lock_timeout TO '30s'
|
191
|
+
(3.5ms) CREATE INDEX CONCURRENTLY "index_users_on_age" ON "users" ("age")
|
192
|
+
(0.3ms) SET lock_timeout TO '5s'
|
193
|
+
(0.2ms) SET statement_timeout TO '1min'
|
194
|
+
-> 0.0093s
|
195
|
+
(0.2ms) SET lock_timeout TO '0'
|
196
|
+
== 20191215132355 SampleIndex: migrated (0.0114s) =============================
|
197
|
+
```
|
198
|
+
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.
|
199
|
+
|
200
|
+
*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*
|
201
|
+
|
202
|
+
</details>
|
203
|
+
|
204
|
+
## Configuration
|
205
|
+
|
206
|
+
**Safe PG Migrations** can be customized, here is an example of a Rails initializer (the values are the default ones):
|
207
|
+
|
208
|
+
```ruby
|
209
|
+
SafePgMigrations.config.safe_timeout = 5.seconds # Lock and statement timeout used for all DDL operations except from CREATE / DROP INDEX
|
210
|
+
|
211
|
+
SafePgMigrations.config.blocking_activity_logger_margin = 1.second # Delay to output blocking queries before timeout. Must be shorter than safe_timeout
|
212
|
+
|
213
|
+
SafePgMigrations.config.batch_size = 1000 # Size of the batches used for backfilling when adding a column with a default value pre-PG11
|
214
|
+
|
215
|
+
SafePgMigrations.config.retry_delay = 1.minute # Delay between retries for retryable statements
|
216
|
+
|
217
|
+
SafePgMigrations.config.max_tries = 5 # Number of retries before abortion of the migration
|
218
|
+
```
|
116
219
|
|
117
220
|
## Runnings tests
|
118
221
|
|
@@ -142,11 +245,13 @@ Alternatives:
|
|
142
245
|
|
143
246
|
Interesting reads:
|
144
247
|
|
145
|
-
- https://www.citusdata.com/blog/2018/02/22/seven-tips-for-dealing-with-postgres-locks/
|
146
|
-
-
|
147
|
-
|
148
|
-
-
|
149
|
-
- https://
|
150
|
-
- https://
|
151
|
-
- https://
|
152
|
-
- https://
|
248
|
+
- [When Postgres blocks: 7 tips for dealing with locks](https://www.citusdata.com/blog/2018/02/22/seven-tips-for-dealing-with-postgres-locks/)
|
249
|
+
- [Migrations and Long Transactions in Postgres
|
250
|
+
](https://www.fin.com/post/2018/1/migrations-and-long-transactions)
|
251
|
+
- [PostgreSQL Alter Table and Long Transactions](http://www.joshuakehn.com/2017/9/9/postgresql-alter-table-and-long-transactions.html)
|
252
|
+
- [Adding a NOT NULL CONSTRAINT on PG Faster with Minimal Locking](https://medium.com/doctolib-engineering/adding-a-not-null-constraint-on-pg-faster-with-minimal-locking-38b2c00c4d1c)
|
253
|
+
- [Adding columns with default values to really large tables in Postgres + Rails](https://wework.github.io/data/2015/11/05/add-columns-with-default-values-to-large-tables-in-rails-postgres/)
|
254
|
+
- [Rails migrations with no downtime](https://pedro.herokuapp.com/past/2011/7/13/rails_migrations_with_no_downtime/)
|
255
|
+
- [Safe Operations For High Volume PostgreSQL](https://www.braintreepayments.com/blog/safe-operations-for-high-volume-postgresql/)
|
256
|
+
- [Rails Migrations with Zero Downtime](https://blog.codeship.com/rails-migrations-zero-downtime/)
|
257
|
+
- [Stop worrying about PostgreSQL locks in your Rails migrations](https://medium.com/doctolib/stop-worrying-about-postgresql-locks-in-your-rails-migrations-3426027e9cc9)
|
@@ -1,10 +1,12 @@
|
|
1
1
|
# frozen_string_literal: true
|
2
2
|
|
3
3
|
require 'safe-pg-migrations/configuration'
|
4
|
+
require 'safe-pg-migrations/plugins/verbose_sql_logger'
|
4
5
|
require 'safe-pg-migrations/plugins/blocking_activity_logger'
|
5
6
|
require 'safe-pg-migrations/plugins/statement_insurer'
|
6
7
|
require 'safe-pg-migrations/plugins/statement_retrier'
|
7
8
|
require 'safe-pg-migrations/plugins/idem_potent_statements'
|
9
|
+
require 'safe-pg-migrations/plugins/useless_statements_logger'
|
8
10
|
|
9
11
|
module SafePgMigrations
|
10
12
|
# Order matters: the bottom-most plugin will have precedence
|
@@ -13,20 +15,28 @@ module SafePgMigrations
|
|
13
15
|
IdemPotentStatements,
|
14
16
|
StatementRetrier,
|
15
17
|
StatementInsurer,
|
18
|
+
UselessStatementsLogger,
|
16
19
|
].freeze
|
17
20
|
|
18
21
|
class << self
|
19
|
-
attr_reader :current_migration
|
20
|
-
attr_accessor :enabled
|
22
|
+
attr_reader :current_migration, :pg_version_num
|
21
23
|
|
22
24
|
def setup_and_teardown(migration, connection)
|
25
|
+
@pg_version_num = get_pg_version_num(connection)
|
23
26
|
@alternate_connection = nil
|
24
27
|
@current_migration = migration
|
28
|
+
stdout_sql_logger = VerboseSqlLogger.new.setup if verbose?
|
25
29
|
PLUGINS.each { |plugin| connection.extend(plugin) }
|
26
|
-
|
30
|
+
|
31
|
+
connection.with_setting(:lock_timeout, SafePgMigrations.config.pg_safe_timeout) { yield }
|
27
32
|
ensure
|
28
33
|
close_alternate_connection
|
29
34
|
@current_migration = nil
|
35
|
+
stdout_sql_logger&.teardown
|
36
|
+
end
|
37
|
+
|
38
|
+
def get_pg_version_num(connection)
|
39
|
+
connection.query_value('SHOW server_version_num').to_i
|
30
40
|
end
|
31
41
|
|
32
42
|
def alternate_connection
|
@@ -50,9 +60,8 @@ module SafePgMigrations
|
|
50
60
|
say "#{method}(#{args.map(&:inspect) * ', '})", true
|
51
61
|
end
|
52
62
|
|
53
|
-
def
|
54
|
-
return ENV['
|
55
|
-
return enabled unless enabled.nil?
|
63
|
+
def verbose?
|
64
|
+
return ENV['SAFE_PG_MIGRATIONS_VERBOSE'] == '1' if ENV['SAFE_PG_MIGRATIONS_VERBOSE']
|
56
65
|
return Rails.env.production? if defined?(Rails)
|
57
66
|
|
58
67
|
false
|
@@ -71,7 +80,8 @@ module SafePgMigrations
|
|
71
80
|
end
|
72
81
|
|
73
82
|
def disable_ddl_transaction
|
74
|
-
|
83
|
+
UselessStatementsLogger.warn_useless '`disable_ddl_transaction`' if super
|
84
|
+
true
|
75
85
|
end
|
76
86
|
|
77
87
|
SAFE_METHODS = %i[execute add_column add_index add_reference add_belongs_to change_column_null].freeze
|
@@ -5,17 +5,26 @@ require 'active_support/core_ext/numeric/time'
|
|
5
5
|
module SafePgMigrations
|
6
6
|
class Configuration
|
7
7
|
attr_accessor :safe_timeout
|
8
|
-
attr_accessor :
|
8
|
+
attr_accessor :blocking_activity_logger_margin
|
9
9
|
attr_accessor :batch_size
|
10
10
|
attr_accessor :retry_delay
|
11
11
|
attr_accessor :max_tries
|
12
12
|
|
13
13
|
def initialize
|
14
|
-
self.safe_timeout =
|
15
|
-
self.
|
14
|
+
self.safe_timeout = 5.seconds
|
15
|
+
self.blocking_activity_logger_margin = 1.second
|
16
16
|
self.batch_size = 1000
|
17
|
-
self.retry_delay =
|
17
|
+
self.retry_delay = 1.minute
|
18
18
|
self.max_tries = 5
|
19
19
|
end
|
20
|
+
|
21
|
+
def pg_safe_timeout
|
22
|
+
pg_duration(safe_timeout)
|
23
|
+
end
|
24
|
+
|
25
|
+
def pg_duration(duration)
|
26
|
+
value, unit = duration.integer? ? [duration, 's'] : [(duration * 1000).to_i, 'ms']
|
27
|
+
"#{value}#{unit}"
|
28
|
+
end
|
20
29
|
end
|
21
30
|
end
|
@@ -3,7 +3,7 @@
|
|
3
3
|
module SafePgMigrations
|
4
4
|
module BlockingActivityLogger
|
5
5
|
SELECT_BLOCKING_QUERIES_SQL = <<~SQL.squish
|
6
|
-
SELECT blocking_activity.query
|
6
|
+
SELECT blocking_activity.query, blocked_activity.xact_start as start
|
7
7
|
FROM pg_catalog.pg_locks blocked_locks
|
8
8
|
JOIN pg_catalog.pg_stat_activity blocked_activity
|
9
9
|
ON blocked_activity.pid = blocked_locks.pid
|
@@ -25,8 +25,7 @@ module SafePgMigrations
|
|
25
25
|
SQL
|
26
26
|
|
27
27
|
%i[
|
28
|
-
add_column remove_column add_foreign_key remove_foreign_key change_column_default
|
29
|
-
change_column_null create_table add_index remove_index
|
28
|
+
add_column remove_column add_foreign_key remove_foreign_key change_column_default change_column_null create_table
|
30
29
|
].each do |method|
|
31
30
|
define_method method do |*args, &block|
|
32
31
|
log_blocking_queries { super(*args, &block) }
|
@@ -36,10 +35,13 @@ module SafePgMigrations
|
|
36
35
|
private
|
37
36
|
|
38
37
|
def log_blocking_queries
|
38
|
+
delay_before_logging =
|
39
|
+
SafePgMigrations.config.safe_timeout - SafePgMigrations.config.blocking_activity_logger_margin
|
40
|
+
|
39
41
|
blocking_queries_retriever_thread =
|
40
42
|
Thread.new do
|
41
|
-
sleep
|
42
|
-
SafePgMigrations.alternate_connection.
|
43
|
+
sleep delay_before_logging
|
44
|
+
SafePgMigrations.alternate_connection.query(SELECT_BLOCKING_QUERIES_SQL % raw_connection.backend_pid)
|
43
45
|
end
|
44
46
|
|
45
47
|
yield
|
@@ -64,11 +66,21 @@ module SafePgMigrations
|
|
64
66
|
"Statement was being blocked by the following #{'query'.pluralize(queries.size)}:", true
|
65
67
|
)
|
66
68
|
SafePgMigrations.say '', true
|
67
|
-
queries.each { |query| SafePgMigrations.say " #{query}", true }
|
69
|
+
queries.each { |query, start_time| SafePgMigrations.say "#{format_start_time start_time}: #{query}", true }
|
70
|
+
SafePgMigrations.say(
|
71
|
+
'Beware, some of those queries might run in a transaction. In this case the locking query might be '\
|
72
|
+
'located elsewhere in the transaction',
|
73
|
+
true
|
74
|
+
)
|
68
75
|
SafePgMigrations.say '', true
|
69
76
|
end
|
70
77
|
|
71
78
|
raise
|
72
79
|
end
|
80
|
+
|
81
|
+
def format_start_time(start_time, reference_time = Time.now)
|
82
|
+
duration = (reference_time - start_time).round
|
83
|
+
"transaction started #{duration} #{'second'.pluralize(duration)} ago"
|
84
|
+
end
|
73
85
|
end
|
74
86
|
end
|
@@ -12,6 +12,12 @@ module SafePgMigrations
|
|
12
12
|
super
|
13
13
|
end
|
14
14
|
|
15
|
+
def add_column(table_name, column_name, type, options = {})
|
16
|
+
return super unless column_exists?(table_name, column_name)
|
17
|
+
|
18
|
+
SafePgMigrations.say("/!\\ Column '#{column_name}' already exists in '#{table_name}'. Skipping statement.", true)
|
19
|
+
end
|
20
|
+
|
15
21
|
def remove_column(table_name, column_name, type = nil, options = {})
|
16
22
|
return super if column_exists?(table_name, column_name)
|
17
23
|
|
@@ -26,6 +32,32 @@ module SafePgMigrations
|
|
26
32
|
SafePgMigrations.say("/!\\ Index '#{index_name}' not found on table '#{table_name}'. Skipping statement.", true)
|
27
33
|
end
|
28
34
|
|
35
|
+
def add_foreign_key(from_table, to_table, **options)
|
36
|
+
options_or_to_table = options.slice(:name, :column).presence || to_table
|
37
|
+
return super unless foreign_key_exists?(from_table, options_or_to_table)
|
38
|
+
|
39
|
+
SafePgMigrations.say(
|
40
|
+
"/!\\ Foreign key '#{from_table}' -> '#{to_table}' already exists. Skipping statement.",
|
41
|
+
true
|
42
|
+
)
|
43
|
+
end
|
44
|
+
|
45
|
+
def create_table(table_name, comment: nil, **options)
|
46
|
+
return super if options[:force] || !table_exists?(table_name)
|
47
|
+
|
48
|
+
SafePgMigrations.say "/!\\ Table '#{table_name}' already exists.", true
|
49
|
+
|
50
|
+
td = create_table_definition(table_name, **options)
|
51
|
+
|
52
|
+
yield td if block_given?
|
53
|
+
|
54
|
+
SafePgMigrations.say(td.indexes.empty? ? '-- Skipping statement' : '-- Creating indexes', true)
|
55
|
+
|
56
|
+
td.indexes.each do |column_name, index_options|
|
57
|
+
add_index(table_name, column_name, index_options)
|
58
|
+
end
|
59
|
+
end
|
60
|
+
|
29
61
|
private
|
30
62
|
|
31
63
|
def index_valid?(index_name)
|
@@ -2,18 +2,22 @@
|
|
2
2
|
|
3
3
|
module SafePgMigrations
|
4
4
|
module StatementInsurer
|
5
|
-
|
5
|
+
PG_11_VERSION_NUM = 110_000
|
6
|
+
|
7
|
+
%i[change_column_null change_column].each do |method|
|
6
8
|
define_method method do |*args, &block|
|
7
|
-
with_setting(:statement_timeout, SafePgMigrations.config.
|
9
|
+
with_setting(:statement_timeout, SafePgMigrations.config.pg_safe_timeout) { super(*args, &block) }
|
8
10
|
end
|
9
11
|
end
|
10
12
|
|
11
13
|
def add_column(table_name, column_name, type, **options)
|
14
|
+
return super if SafePgMigrations.pg_version_num >= PG_11_VERSION_NUM
|
15
|
+
|
12
16
|
default = options.delete(:default)
|
13
17
|
null = options.delete(:null)
|
14
18
|
|
15
19
|
if !default.nil? || null == false
|
16
|
-
SafePgMigrations.say_method_call(:add_column, table_name, column_name, type,
|
20
|
+
SafePgMigrations.say_method_call(:add_column, table_name, column_name, type, options)
|
17
21
|
end
|
18
22
|
|
19
23
|
super
|
@@ -32,21 +36,46 @@ module SafePgMigrations
|
|
32
36
|
end
|
33
37
|
end
|
34
38
|
|
39
|
+
def add_foreign_key(from_table, to_table, **options)
|
40
|
+
validate_present = options.key? :validate
|
41
|
+
options[:validate] = false unless validate_present
|
42
|
+
|
43
|
+
with_setting(:statement_timeout, SafePgMigrations.config.pg_safe_timeout) { super }
|
44
|
+
|
45
|
+
options_or_to_table = options.slice(:name, :column).presence || to_table
|
46
|
+
without_statement_timeout { validate_foreign_key from_table, options_or_to_table } unless validate_present
|
47
|
+
end
|
48
|
+
|
49
|
+
def create_table(*)
|
50
|
+
with_setting(:statement_timeout, SafePgMigrations.config.pg_safe_timeout) do
|
51
|
+
super do |td|
|
52
|
+
yield td if block_given?
|
53
|
+
td.indexes.map! do |key, index_options|
|
54
|
+
index_options[:algorithm] ||= :default
|
55
|
+
[key, index_options]
|
56
|
+
end
|
57
|
+
end
|
58
|
+
end
|
59
|
+
end
|
60
|
+
|
35
61
|
def add_index(table_name, column_name, **options)
|
36
|
-
if
|
62
|
+
if options[:algorithm] == :default
|
63
|
+
options.delete :algorithm
|
64
|
+
else
|
37
65
|
options[:algorithm] = :concurrently
|
38
|
-
SafePgMigrations.say_method_call(:add_index, table_name, column_name, **options)
|
39
66
|
end
|
40
|
-
|
67
|
+
|
68
|
+
SafePgMigrations.say_method_call(:add_index, table_name, column_name, options)
|
69
|
+
|
70
|
+
without_timeout { super }
|
41
71
|
end
|
42
72
|
|
43
73
|
def remove_index(table_name, options = {})
|
44
74
|
options = { column: options } unless options.is_a?(Hash)
|
45
|
-
|
46
|
-
|
47
|
-
|
48
|
-
|
49
|
-
without_statement_timeout { super }
|
75
|
+
options[:algorithm] = :concurrently
|
76
|
+
SafePgMigrations.say_method_call(:remove_index, table_name, options)
|
77
|
+
|
78
|
+
without_timeout { super }
|
50
79
|
end
|
51
80
|
|
52
81
|
def backfill_column_default(table_name, column_name)
|
@@ -86,5 +115,13 @@ module SafePgMigrations
|
|
86
115
|
def without_statement_timeout
|
87
116
|
with_setting(:statement_timeout, 0) { yield }
|
88
117
|
end
|
118
|
+
|
119
|
+
def without_lock_timeout
|
120
|
+
with_setting(:lock_timeout, 0) { yield }
|
121
|
+
end
|
122
|
+
|
123
|
+
def without_timeout
|
124
|
+
without_statement_timeout { without_lock_timeout { yield } }
|
125
|
+
end
|
89
126
|
end
|
90
127
|
end
|
@@ -3,8 +3,7 @@
|
|
3
3
|
module SafePgMigrations
|
4
4
|
module StatementRetrier
|
5
5
|
RETRIABLE_SCHEMA_STATEMENTS = %i[
|
6
|
-
add_column add_foreign_key remove_foreign_key change_column_default
|
7
|
-
change_column_null add_index remove_index remove_column
|
6
|
+
add_column add_foreign_key remove_foreign_key change_column_default change_column_null remove_column
|
8
7
|
].freeze
|
9
8
|
|
10
9
|
RETRIABLE_SCHEMA_STATEMENTS.each do |method|
|
@@ -0,0 +1,33 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module SafePgMigrations
|
4
|
+
module UselessStatementsLogger
|
5
|
+
def self.warn_useless(action, link = nil, *args)
|
6
|
+
SafePgMigrations.say "/!\\ No need to explicitly use #{action}, safe-pg-migrations does it for you", *args
|
7
|
+
SafePgMigrations.say "\t see #{link} for more details", *args if link
|
8
|
+
end
|
9
|
+
|
10
|
+
def add_index(*, **options)
|
11
|
+
warn_for_index(**options)
|
12
|
+
super
|
13
|
+
end
|
14
|
+
|
15
|
+
def remove_index(table_name, options = {})
|
16
|
+
warn_for_index(options) if options.is_a? Hash
|
17
|
+
super
|
18
|
+
end
|
19
|
+
|
20
|
+
def add_foreign_key(*, **options)
|
21
|
+
if options[:validate] == false
|
22
|
+
UselessStatementsLogger.warn_useless '`validate: :false`', 'https://github.com/doctolib/safe-pg-migrations#safe_add_foreign_key'
|
23
|
+
end
|
24
|
+
super
|
25
|
+
end
|
26
|
+
|
27
|
+
def warn_for_index(**options)
|
28
|
+
return unless options[:algorithm] == :concurrently
|
29
|
+
|
30
|
+
UselessStatementsLogger.warn_useless '`algorithm: :concurrently`', 'https://github.com/doctolib/safe-pg-migrations#safe_add_remove_index'
|
31
|
+
end
|
32
|
+
end
|
33
|
+
end
|
@@ -0,0 +1,43 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module SafePgMigrations
|
4
|
+
class VerboseSqlLogger
|
5
|
+
def setup
|
6
|
+
@activerecord_logger_was = ActiveRecord::Base.logger
|
7
|
+
@verbose_query_logs_was = ActiveRecord::Base.verbose_query_logs
|
8
|
+
@colorize_logging_was = ActiveRecord::LogSubscriber.colorize_logging
|
9
|
+
|
10
|
+
disable_marginalia if defined?(Marginalia)
|
11
|
+
|
12
|
+
stdout_logger = Logger.new($stdout, formatter: ->(_severity, _time, _progname, query) { "#{query}\n" })
|
13
|
+
ActiveRecord::Base.logger = stdout_logger
|
14
|
+
ActiveRecord::LogSubscriber.colorize_logging = colorize_logging?
|
15
|
+
# Do not output caller method, we know it is coming from the migration
|
16
|
+
ActiveRecord::Base.verbose_query_logs = false
|
17
|
+
self
|
18
|
+
end
|
19
|
+
|
20
|
+
def teardown
|
21
|
+
ActiveRecord::Base.verbose_query_logs = @verbose_query_logs_was
|
22
|
+
ActiveRecord::LogSubscriber.colorize_logging = @colorize_logging_was
|
23
|
+
ActiveRecord::Base.logger = @activerecord_logger_was
|
24
|
+
enable_marginalia if defined?(Marginalia)
|
25
|
+
end
|
26
|
+
|
27
|
+
private
|
28
|
+
|
29
|
+
def colorize_logging?
|
30
|
+
defined?(Rails) && Rails.env.development?
|
31
|
+
end
|
32
|
+
|
33
|
+
# Marginalia annotations will most likely pollute the output
|
34
|
+
def disable_marginalia
|
35
|
+
@marginalia_components_were = Marginalia::Comment.components
|
36
|
+
Marginalia::Comment.components = []
|
37
|
+
end
|
38
|
+
|
39
|
+
def enable_marginalia
|
40
|
+
Marginalia::Comment.components = @marginalia_components_were
|
41
|
+
end
|
42
|
+
end
|
43
|
+
end
|
@@ -4,7 +4,7 @@ require 'safe-pg-migrations/base'
|
|
4
4
|
|
5
5
|
module SafePgMigrations
|
6
6
|
class Railtie < Rails::Railtie
|
7
|
-
initializer '
|
7
|
+
initializer 'safe_pg_migrations.insert_into_active_record' do
|
8
8
|
ActiveSupport.on_load :active_record do
|
9
9
|
ActiveRecord::Migration.prepend(SafePgMigrations::Migration)
|
10
10
|
end
|
metadata
CHANGED
@@ -1,15 +1,15 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: safe-pg-migrations
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version:
|
4
|
+
version: 1.2.2
|
5
5
|
platform: ruby
|
6
6
|
authors:
|
7
7
|
- Matthieu Prat
|
8
8
|
- Romain Choquet
|
9
|
-
autorequire:
|
9
|
+
autorequire:
|
10
10
|
bindir: bin
|
11
11
|
cert_chain: []
|
12
|
-
date:
|
12
|
+
date: 2021-04-13 00:00:00.000000000 Z
|
13
13
|
dependencies:
|
14
14
|
- !ruby/object:Gem::Dependency
|
15
15
|
name: activerecord
|
@@ -166,13 +166,15 @@ files:
|
|
166
166
|
- lib/safe-pg-migrations/plugins/idem_potent_statements.rb
|
167
167
|
- lib/safe-pg-migrations/plugins/statement_insurer.rb
|
168
168
|
- lib/safe-pg-migrations/plugins/statement_retrier.rb
|
169
|
+
- lib/safe-pg-migrations/plugins/useless_statements_logger.rb
|
170
|
+
- lib/safe-pg-migrations/plugins/verbose_sql_logger.rb
|
169
171
|
- lib/safe-pg-migrations/railtie.rb
|
170
172
|
- lib/safe-pg-migrations/version.rb
|
171
173
|
homepage: https://github.com/doctolib/safe-pg-migrations
|
172
174
|
licenses:
|
173
175
|
- MIT
|
174
176
|
metadata: {}
|
175
|
-
post_install_message:
|
177
|
+
post_install_message:
|
176
178
|
rdoc_options: []
|
177
179
|
require_paths:
|
178
180
|
- lib
|
@@ -180,16 +182,16 @@ required_ruby_version: !ruby/object:Gem::Requirement
|
|
180
182
|
requirements:
|
181
183
|
- - ">="
|
182
184
|
- !ruby/object:Gem::Version
|
183
|
-
version: '2.
|
185
|
+
version: '2.5'
|
184
186
|
required_rubygems_version: !ruby/object:Gem::Requirement
|
185
187
|
requirements:
|
186
188
|
- - ">="
|
187
189
|
- !ruby/object:Gem::Version
|
188
190
|
version: '0'
|
189
191
|
requirements: []
|
190
|
-
rubyforge_project:
|
191
|
-
rubygems_version: 2.
|
192
|
-
signing_key:
|
192
|
+
rubyforge_project:
|
193
|
+
rubygems_version: 2.7.3
|
194
|
+
signing_key:
|
193
195
|
specification_version: 4
|
194
196
|
summary: Make your PG migrations safe.
|
195
197
|
test_files: []
|