trellis-pg 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,16 +34,15 @@ module Trellis
34
34
  # the definitions in `structure.sql` (Trellis::SchemaDump). The database
35
35
  # they dump into is config.trellis.dump_database, "primary" by default.
36
36
  #
37
- # `config.trellis.off_in` names the environments Trellis is off in. The
38
- # default is `%w[test]`: a test suite's transactions never commit, so it
39
- # can't see a target change. `off_in = []` turns Trellis on in tests. It
40
- # is read from any environment, so a `db:prepare` or `db:test:prepare` run
41
- # from development leaves Trellis out of the test database too. There,
42
- # nothing connects at boot, Railtie.connect and `trellis:migrate` do
43
- # nothing, the schema load and dump hooks leave the target tables as plain
44
- # ones, and the migration helpers refuse (or skip, migrating that database
45
- # from an environment Trellis is on in).
46
- # Trellis.enabled? is the predicate; "Testing" in the README has the rest.
37
+ # `config.trellis.off_in` names the environments Trellis's runtime is off
38
+ # in. The default is `%w[test]`: a test suite's transactions never commit,
39
+ # so it can't see a target change. `off_in = []` turns Trellis on in tests.
40
+ # There, nothing connects at boot and Railtie.connect does nothing. The
41
+ # migration helpers, `trellis:migrate` and the schema load and dump hooks
42
+ # run as they do where it's on, against the database Rails is migrating,
43
+ # loading or dumping (with_handle), so that database gets every
44
+ # definition, unbuilt. Trellis.enabled? is the predicate; "Testing" in the
45
+ # README has the rest.
47
46
  #
48
47
  # When either is set, the app's handles connect in an after_initialize hook,
49
48
  # except in these cases:
@@ -61,6 +60,11 @@ module Trellis
61
60
  # - config.trellis.connect_on_boot = false, for a server that forks with
62
61
  # no hook to shut the handle down first (see below).
63
62
  #
63
+ # The Rails database tasks (`db:migrate`, `db:prepare`, `db:rollback`,
64
+ # `db:schema:load`, `db:test:prepare`, ...) run Trellis's `migrate` after
65
+ # their own work (Trellis::TaskHooks), unless `config.trellis.task_hooks =
66
+ # false`.
67
+ #
64
68
  # The engine's log lines go to Rails.logger (Trellis::LogBridge), at
65
69
  # Rails.logger's level or config.trellis.log_level (:debug, :info, :warn,
66
70
  # :error), unless config.trellis.log_bridge = false or Trellis is off in
@@ -88,19 +92,34 @@ module Trellis
88
92
  config.trellis.off_in = %w[test]
89
93
  config.trellis.log_bridge = true
90
94
  config.trellis.log_level = nil
95
+ config.trellis.task_hooks = true
91
96
 
92
97
  rake_tasks do
98
+ if ::Rails.application.config.trellis.task_hooks != false
99
+ require "trellis/task_hooks"
100
+ Trellis::TaskHooks.install
101
+ end
102
+
93
103
  namespace :trellis do
94
104
  desc "Create or upgrade Trellis's own tables, for config.trellis.connect and config.trellis.instances"
95
105
  task migrate: :environment do
96
106
  Trellis::Railtie.migrate_all
97
107
  end
98
108
 
99
- # No :environment: the check reads git and files, so it runs in a CI
100
- # job with no database and none of the app's initializers.
101
- desc "Fail if this release changes trellis-pg's version and adds a Trellis migration (BASE=<git ref>)"
102
- task :release_check do
103
- Trellis::Railtie.release_check(ENV.fetch("BASE", nil))
109
+ desc "Leave this trellis-pg release for an earlier one (destructive; TO=release, CONFIRM=yes)"
110
+ task rollback: :environment do
111
+ require "trellis/leave_task"
112
+ Trellis::LeaveTask.run(:rollback, to: ENV["TO"], confirm: ENV["CONFIRM"])
113
+ rescue Trellis::LeaveTask::NotConfirmed => e
114
+ abort e.message
115
+ end
116
+
117
+ desc "Remove everything Trellis has in the database, targets included (destructive; CONFIRM=yes)"
118
+ task uninstall: :environment do
119
+ require "trellis/leave_task"
120
+ Trellis::LeaveTask.run(:uninstall, confirm: ENV["CONFIRM"])
121
+ rescue Trellis::LeaveTask::NotConfirmed => e
122
+ abort e.message
104
123
  end
105
124
  end
106
125
  end
@@ -122,6 +141,9 @@ module Trellis
122
141
 
123
142
  config.after_initialize { Trellis::Railtie.instance.send(:boot) }
124
143
 
144
+ # The thread-local Railtie.working_on records its db_config in.
145
+ WORKING_ON = :trellis_migrating_database
146
+
125
147
  # The instances Railtie.connect opened for config.trellis.instances,
126
148
  # by name.
127
149
  @instances = {}
@@ -199,16 +221,33 @@ module Trellis
199
221
  # warning, so it doesn't hide the block's error; after a block that
200
222
  # returned, the shutdown's error is raised. Raises ValidationError if
201
223
  # the instance isn't connected and its options aren't configured.
224
+ #
225
+ # In a migration, schema load or dump of another environment's
226
+ # database (`db:prepare` in development migrates the test databases
227
+ # too), or of a database of an environment Trellis is off in, it never
228
+ # uses this process's handle: it connects one of its own to that
229
+ # environment's counterpart of the database the instance's url points
230
+ # at, or to that database itself when the url points at none
231
+ # (SchemaDump.migration_url), with the instance's other options.
202
232
  def with_handle(name = nil)
233
+ other = elsewhere_database
203
234
  instance = name ? @instances[name.to_sym] : (Trellis.default_instance if Trellis.connected?)
204
- if instance&.connected?
235
+ if instance&.connected? && !other
205
236
  instance.migrate
206
237
  return yield(instance)
207
238
  end
208
239
 
209
240
  options = name ? named_options(name) : required_connect_options
210
241
  options = options.merge(staging: false, drain_threads: 0)
211
- instance = name ? Trellis::Instance.connect(**options) : connect_default(options)
242
+ if other
243
+ require "trellis/schema_dump"
244
+ what = name ? "config.trellis.instances[#{name.inspect}]" : "config.trellis.connect"
245
+ options = options.merge(url: SchemaDump.migration_url(other, options[:url], what))
246
+ end
247
+ # The default instance's own handle is Trellis's default, unless
248
+ # that may already be this process's handle.
249
+ default = !name && !other
250
+ instance = default ? connect_default(options) : Trellis::Instance.connect(**options)
212
251
  primary = nil
213
252
  begin
214
253
  instance.migrate
@@ -217,17 +256,18 @@ module Trellis
217
256
  primary = e
218
257
  raise
219
258
  ensure
220
- shutdown_after(name, instance, primary)
259
+ shutdown_after(default, instance, primary)
221
260
  end
222
261
  end
223
262
 
224
263
  # Runs Trellis.migrate on the default instance (when
225
264
  # config.trellis.connect is set) and on each of
226
- # config.trellis.instances, each as with_handle does. Raises
227
- # ValidationError if neither is set.
265
+ # config.trellis.instances, each as with_handle does, whether or not
266
+ # Trellis is off in this environment. Where it's off, and no Rails task
267
+ # is working on a database, that is this environment's
268
+ # config.trellis.dump_database. Raises ValidationError if neither is
269
+ # set.
228
270
  def migrate_all
229
- return skipped("trellis:migrate migrates nothing") unless enabled?
230
-
231
271
  default = connect_options
232
272
  named = instance_options
233
273
  if default.nil? && named.empty?
@@ -235,35 +275,23 @@ module Trellis
235
275
  "config.trellis.connect is not set: give it Trellis.connect's options"
236
276
  end
237
277
 
238
- with_handle { nil } if default
239
- named.each_key { |name| with_handle(name) { nil } }
278
+ run = lambda do
279
+ with_handle { nil } if default
280
+ named.each_key { |name| with_handle(name) { nil } }
281
+ end
282
+ database = off_environment_database
283
+ database ? working_on(database, &run) : run.call
240
284
  nil
241
285
  end
242
286
 
243
- # Runs Trellis::ReleaseCheck for this app against the git ref `base`,
244
- # over every migrations path the app has (db/migrate, and each
245
- # database's migrations_paths): prints its verdict, and exits 1 when
246
- # the release both changes trellis-pg's version and adds a Trellis
247
- # migration, or when the check can't run. What `rails
248
- # trellis:release_check BASE=<ref>` runs.
249
- def release_check(base)
250
- require "trellis/release_check"
251
- result = ReleaseCheck.call(root: ::Rails.root, base: base,
252
- migrations_paths: migrations_paths, lockfile: lockfile)
253
- abort result.message unless result.ok?
254
- puts result.message
255
- rescue ReleaseCheck::Error => e
256
- abort "trellis:release_check: #{e.message}"
257
- end
258
-
259
287
  # Whether Trellis is off in `environment`, however it is spelled.
260
288
  def off_in?(environment)
261
289
  off_in.include?(environment.to_s)
262
290
  end
263
291
 
264
- # Whether Trellis is on in `environment` (this process's, by default):
265
- # false when config.trellis.off_in names it. Trellis.enabled? is the
266
- # shortcut for code that doesn't need the Railtie.
292
+ # Whether Trellis's runtime is on in `environment` (this process's, by
293
+ # default): false when config.trellis.off_in names it. Trellis.enabled?
294
+ # is the shortcut for code that doesn't need the Railtie.
267
295
  def enabled?(environment = ::Rails.env)
268
296
  !off_in?(environment)
269
297
  end
@@ -301,42 +329,46 @@ module Trellis
301
329
  end
302
330
  end
303
331
 
332
+ # Runs the block with db_config recorded as the database Rails is
333
+ # working on (a migration, schema load or dump of it), for with_handle,
334
+ # and returns the block's value.
335
+ def working_on(db_config)
336
+ previous = Thread.current[WORKING_ON]
337
+ Thread.current[WORKING_ON] = db_config
338
+ yield
339
+ ensure
340
+ Thread.current[WORKING_ON] = previous
341
+ end
342
+
304
343
  private
305
344
 
306
- # The environments config.trellis.off_in names, as strings; empty when
307
- # it isn't set (or there's no Rails app).
308
- def off_in
309
- app = ::Rails.respond_to?(:application) && ::Rails.application or return []
345
+ # This environment's config.trellis.dump_database config, when Trellis
346
+ # is off here and no Rails task is working on a database, or nil.
347
+ def off_environment_database
348
+ return nil if Thread.current[WORKING_ON] || enabled? || !defined?(::ActiveRecord::Base)
310
349
 
311
- Array(app.config.trellis.off_in).map(&:to_s)
350
+ require "trellis/schema_dump"
351
+ ::ActiveRecord::Base.configurations.configs_for(env_name: ::Rails.env.to_s, name: SchemaDump.dump_database)
312
352
  end
313
353
 
314
- # Where the app keeps migrations: db/migrate, and the migrations_paths
315
- # of every database in config/database.yml, read without connecting.
316
- # An app whose database config can't be read here (no database.yml, a
317
- # missing environment variable) is checked on db/migrate alone.
318
- def migrations_paths
319
- app = ::Rails.application
320
- collect = lambda do |node|
321
- next [] unless node.is_a?(Hash)
354
+ # The db_config working_on recorded, when it belongs to another
355
+ # environment than the one running the task, or to one Trellis is off
356
+ # in: with_handle connects to it rather than to the configured url.
357
+ # nil otherwise.
358
+ def elsewhere_database
359
+ db_config = Thread.current[WORKING_ON] or return nil
360
+ return db_config if off_in?(db_config.env_name)
361
+ return nil if db_config.env_name.to_s == ::ActiveRecord::Tasks::DatabaseTasks.env.to_s
322
362
 
323
- node.flat_map { |key, value| key.to_s == "migrations_paths" ? Array(value) : collect.call(value) }
324
- end
325
- configured = begin
326
- collect.call(app.config.database_configuration)
327
- rescue StandardError
328
- []
329
- end
330
- (app.paths["db/migrate"].to_a + configured).map(&:to_s).uniq
363
+ db_config
331
364
  end
332
365
 
333
- # The lockfile Bundler resolved the app with (it follows BUNDLE_GEMFILE,
334
- # and a gems.rb has a gems.locked), or Gemfile.lock in an app that
335
- # isn't running under Bundler.
336
- def lockfile
337
- defined?(::Bundler) ? ::Bundler.default_lockfile : "Gemfile.lock"
338
- rescue StandardError
339
- "Gemfile.lock"
366
+ # The environments config.trellis.off_in names, as strings; empty when
367
+ # it isn't set (or there's no Rails app).
368
+ def off_in
369
+ app = ::Rails.respond_to?(:application) && ::Rails.application or return []
370
+
371
+ Array(app.config.trellis.off_in).map(&:to_s)
340
372
  end
341
373
 
342
374
  def keyword_options(what, options)
@@ -378,8 +410,8 @@ module Trellis
378
410
  # Shuts with_handle's own instance down. With a primary error on its
379
411
  # way out, a failed shutdown is only a warning: raising would replace
380
412
  # it.
381
- def shutdown_after(name, instance, primary)
382
- name ? instance.shutdown : Trellis.shutdown
413
+ def shutdown_after(default, instance, primary)
414
+ default ? Trellis.shutdown : instance.shutdown
383
415
  rescue StandardError => e
384
416
  raise unless primary
385
417
 
@@ -4,6 +4,7 @@ require "active_record"
4
4
  require "etc"
5
5
  require "fileutils"
6
6
  require "trellis/pg"
7
+ require "trellis/task_hooks"
7
8
 
8
9
  module Trellis
9
10
  # Makes `structure.sql` carry Trellis's definitions, the way Rails makes it
@@ -47,12 +48,12 @@ module Trellis
47
48
  # that database: the instances' options with the database's host, port,
48
49
  # name, user and password from its config.
49
50
  #
50
- # None of this applies to a database of an environment named in
51
- # config.trellis.off_in (`%w[test]`): its load creates the target tables as
52
- # plain tables and restores nothing, and its dump is Rails' own. A dump of
53
- # such a database run from an environment Trellis is on in (`db:prepare` in
54
- # development also dumps the test database) is skipped, since the file is
55
- # that environment's.
51
+ # A database of an environment named in config.trellis.off_in (`%w[test]`)
52
+ # loads and dumps the same way, connecting to that database itself
53
+ # (Railtie.with_handle): its load restores every definition, unbuilt. A
54
+ # dump of such a database run from an environment Trellis is on in
55
+ # (`db:prepare` in development also dumps the test database) is skipped,
56
+ # since the file is that environment's.
56
57
  #
57
58
  # A load that doesn't go through Rails (`psql -f structure.sql`) is followed
58
59
  # by `rails trellis:migrate`.
@@ -95,17 +96,16 @@ module Trellis
95
96
  end
96
97
 
97
98
  # Whether Trellis's definitions belong in the dump of db_config: Trellis
98
- # is configured and on in db_config's environment, and db_config is
99
- # the database config.trellis.dump_database names.
99
+ # is configured, and db_config is the database
100
+ # config.trellis.dump_database names.
100
101
  def applies?(db_config)
101
- configured_for?(db_config) && !Railtie.off_in?(db_config.env_name)
102
+ configured_for?(db_config)
102
103
  end
103
104
 
104
105
  # Whether a dump of db_config is left undone: db_config belongs to an
105
106
  # environment Trellis is off in, and the environment running the task is
106
- # one it is on in. The dump file is the running environment's, and
107
- # a dump of the off database would overwrite it with one that has no
108
- # definitions.
107
+ # one it is on in. The dump file is the running environment's, which
108
+ # the off database, migrated alongside it, would only overwrite.
109
109
  def skip_dump?(db_config)
110
110
  configured_for?(db_config) && Railtie.off_in?(db_config.env_name) &&
111
111
  !Railtie.off_in?(::ActiveRecord::Tasks::DatabaseTasks.env)
@@ -139,6 +139,10 @@ module Trellis
139
139
  # development's: a db_config of another environment is compared as the
140
140
  # current environment's config of the same name.
141
141
  def verify_same_database!(db_config)
142
+ # Trellis connects to a database of an off environment itself
143
+ # (Railtie.with_handle), whatever the urls say.
144
+ return if Railtie.off_in?(db_config.env_name)
145
+
142
146
  require "pg"
143
147
  target = rails_database(current_environment_config(db_config).configuration_hash)
144
148
  configured = {}
@@ -172,7 +176,7 @@ module Trellis
172
176
  def schema_flags(db_config, configuration_hash, parts = nil)
173
177
  return [] unless applies?(db_config)
174
178
 
175
- parts ||= Thread.current[PARTS_KEY] || self.parts
179
+ parts ||= Thread.current[PARTS_KEY] || Railtie.working_on(db_config) { self.parts }
176
180
  flags = []
177
181
  if restricts_schemas?(configuration_hash)
178
182
  flags.concat(configured_options.map { |options| "--schema=#{exact_pattern(options.fetch(:target_schema, "public"))}" })
@@ -220,27 +224,33 @@ module Trellis
220
224
  end
221
225
 
222
226
  # Restores the definitions a load of db_config's dump queued: `migrate`
223
- # on each configured instance, in the database db_config names.
227
+ # on each configured instance, in the database db_config names, through
228
+ # the claim the Rake task hooks use (TaskHooks.claim).
224
229
  def restore(db_config)
225
230
  verify_same_database!(db_config)
226
- if db_config.env_name.to_s == ::ActiveRecord::Tasks::DatabaseTasks.env.to_s
227
- Railtie.migrate_all
228
- return
229
- end
231
+ TaskHooks.claim(db_config, force: true)
232
+ end
230
233
 
231
- configured = []
232
- configured << [nil, Railtie.connect_options] if Railtie.connect_options
233
- Railtie.instance_options.each { |name, options| configured << [name, options] }
234
- configured.each do |name, options|
235
- what = name ? "config.trellis.instances[#{name.inspect}]" : "config.trellis.connect"
236
- url = environment_url(db_config, options[:url], what)
237
- instance = Trellis::Instance.connect(**options, url:, staging: false, drain_threads: 0)
238
- begin
239
- instance.migrate
240
- ensure
241
- instance.shutdown
242
- end
234
+ # The url an instance configured with configured_url (`what` names it
235
+ # in an error) connects to in a migration running on db_config, a
236
+ # database of another environment than the one running the task
237
+ # (`db:prepare` in development migrates the test databases too), or of
238
+ # one Trellis is off in: db_config's environment's config of the same
239
+ # name as the config configured_url points at (the running
240
+ # environment's, else any environment's), compared as
241
+ # verify_same_database! compares, or db_config itself when it points
242
+ # at none of them. Either is read as environment_url reads it.
243
+ def migration_url(db_config, configured_url, what)
244
+ require "pg"
245
+ configurations = ::ActiveRecord::Base.configurations
246
+ found = trellis_database(configured_url, what)
247
+ named = lambda do |configs|
248
+ configs.find { |config| same_database?(found, rails_database(config.configuration_hash)) }
243
249
  end
250
+ pointed = named.call(configurations.configs_for(env_name: ::ActiveRecord::Tasks::DatabaseTasks.env.to_s)) ||
251
+ named.call(configurations.configs_for)
252
+ counterpart = pointed && configurations.configs_for(env_name: db_config.env_name, name: pointed.name)
253
+ environment_url(counterpart || db_config, configured_url, what)
244
254
  end
245
255
 
246
256
  private
@@ -389,35 +399,37 @@ module Trellis
389
399
  filename = schema_dump_path(db_config, format)
390
400
  return super unless filename
391
401
 
392
- SchemaDump.verify_same_database!(db_config)
393
-
394
- previous = File.exist?(filename) ? File.binread(filename) : nil
395
- finished = false
396
- begin
397
- SchemaDump::ATTEMPTS.times do
398
- before = SchemaDump.parts
399
- begin
400
- Thread.current[SchemaDump::PARTS_KEY] = before
401
- super(db_config, format)
402
- ensure
403
- Thread.current[SchemaDump::PARTS_KEY] = nil
404
- end
405
- if SchemaDump.parts == before
406
- SchemaDump.finish(filename, before)
407
- finished = true
408
- return nil
402
+ Railtie.working_on(db_config) do
403
+ SchemaDump.verify_same_database!(db_config)
404
+
405
+ previous = File.exist?(filename) ? File.binread(filename) : nil
406
+ finished = false
407
+ begin
408
+ SchemaDump::ATTEMPTS.times do
409
+ before = SchemaDump.parts
410
+ begin
411
+ Thread.current[SchemaDump::PARTS_KEY] = before
412
+ super(db_config, format)
413
+ ensure
414
+ Thread.current[SchemaDump::PARTS_KEY] = nil
415
+ end
416
+ if SchemaDump.parts == before
417
+ SchemaDump.finish(filename, before)
418
+ finished = true
419
+ return nil
420
+ end
409
421
  end
422
+ raise Trellis::ConflictError,
423
+ "Trellis's definitions changed during each of #{SchemaDump::ATTEMPTS} dumps of " \
424
+ "#{db_config.name}: run the dump when no define or drop is running"
425
+ ensure
426
+ # Whatever Rails wrote is raw `pg_dump` output with the capture
427
+ # triggers in and no definitions: left in place, a later
428
+ # `db:schema:load` would load it without a word. A file no
429
+ # `pg_dump` wrote to (a failure before the first, or a `pg_dump`
430
+ # that failed before opening it) is the previous dump: left alone.
431
+ SchemaDump.discard_unfinished(filename, previous) unless finished
410
432
  end
411
- raise Trellis::ConflictError,
412
- "Trellis's definitions changed during each of #{SchemaDump::ATTEMPTS} dumps of " \
413
- "#{db_config.name}: run the dump when no define or drop is running"
414
- ensure
415
- # Whatever Rails wrote is raw `pg_dump` output with the capture
416
- # triggers in and no definitions: left in place, a later
417
- # `db:schema:load` would load it without a word. A file no
418
- # `pg_dump` wrote to (a failure before the first, or a `pg_dump`
419
- # that failed before opening it) is the previous dump: left alone.
420
- SchemaDump.discard_unfinished(filename, previous) unless finished
421
433
  end
422
434
  end
423
435
 
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module Trellis
6
+ # Runs Trellis's `migrate` after the Rails database tasks that move a
7
+ # database between schema versions, whether or not a migration was pending.
8
+ # The instance belongs to the version that last ran `migrate`, so a gem-only
9
+ # bump (nothing pending) has to claim it too, and `db:prepare`, which Kamal
10
+ # and the generated Dockerfile run at every boot, never invokes the
11
+ # `db:migrate` task.
12
+ #
13
+ # Installed by the Railtie unless `config.trellis.task_hooks = false`.
14
+ # The hook runs after a task's own actions and only if they succeeded, and
15
+ # a failing `migrate` fails the task. It acts on the
16
+ # `config.trellis.dump_database` of each environment the task touches
17
+ # (`db:prepare` in development touches test too), through
18
+ # Railtie.migrate_all, which is how the schema load hook reaches another
19
+ # environment's database. A task on a database Trellis doesn't use does
20
+ # nothing. It runs in `off_in` environments too, like the migration
21
+ # helpers.
22
+ #
23
+ # Once per database per process: the schema load hook (SchemaDump.restore)
24
+ # claims through the same path, so a load followed by the task's own hook
25
+ # migrates once.
26
+ #
27
+ # Rake-level only: a caller that skips Rake (DatabaseTasks.prepare_all from
28
+ # `rails runner`) isn't covered.
29
+ module TaskHooks
30
+ # Each task the hooks cover. A database-named variant captures the name.
31
+ TASKS = [
32
+ /\Adb:migrate(?::(?:up|down|redo))?\z/,
33
+ /\Adb:migrate:(?:(?:up|down|redo):)?(?!(?:up|down|redo|status|reset)\z)(\w+)\z/,
34
+ /\Adb:rollback\z/,
35
+ /\Adb:rollback:(\w+)\z/,
36
+ /\Adb:prepare\z/,
37
+ /\Adb:schema:load\z/,
38
+ /\Adb:schema:load:(\w+)\z/,
39
+ /\Adb:test:(?:prepare|load_schema)\z/,
40
+ /\Adb:test:load_schema:(\w+)\z/
41
+ ].freeze
42
+
43
+ # Prepended to Rake::Task. Not `enhance`: that installs nothing for a
44
+ # task that isn't defined yet, and the Railtie's rake_tasks block runs
45
+ # before ActiveRecord's when the app requires trellis/pg ahead of
46
+ # active_record/railtie.
47
+ module AfterExecute
48
+ def execute(args = nil)
49
+ result = super
50
+ TaskHooks.run(name) unless ::Rake.application.options.dryrun
51
+ result
52
+ end
53
+ end
54
+
55
+ @done = Set.new
56
+ @mutex = Mutex.new
57
+
58
+ class << self
59
+ # Idempotent. True once Rake::Task runs the hooks.
60
+ def install
61
+ return false unless defined?(::Rake::Task)
62
+
63
+ ::Rake::Task.prepend(AfterExecute) unless ::Rake::Task < AfterExecute
64
+ true
65
+ end
66
+
67
+ # Migrates every configured instance of each database `task_name` left
68
+ # behind, unless the task isn't one of the hooked ones, Trellis isn't
69
+ # configured, or the app turned the hooks off.
70
+ def run(task_name)
71
+ return unless hooked?(task_name) && enabled?
72
+
73
+ databases(task_name).each { |db_config| claim(db_config) }
74
+ end
75
+
76
+ def hooked?(task_name)
77
+ TASKS.any? { |pattern| pattern.match?(task_name) }
78
+ end
79
+
80
+ # Migrates every configured instance in db_config's database, and
81
+ # records that this process has: the one claim path, for the task hooks
82
+ # and the schema load (which passes `force`: a load queues definitions
83
+ # to restore however often the process migrated before). Without
84
+ # `force`, a database this process already claimed is skipped.
85
+ def claim(db_config, force: false)
86
+ claimed = @mutex.synchronize { @done.add?(key(db_config)) }
87
+ return unless claimed || force
88
+
89
+ Railtie.working_on(db_config) { Railtie.migrate_all }
90
+ end
91
+
92
+ def enabled?
93
+ app = ::Rails.application or return false
94
+ return false if app.config.trellis.task_hooks == false
95
+
96
+ !Railtie.connect_options.nil? || !Railtie.instance_options.empty?
97
+ end
98
+
99
+ # The config.trellis.dump_database configs `task_name` touches: one per
100
+ # environment it walks, limited to the database the task names
101
+ # (`db:migrate:<name>`). `configurations` and `env` are Rails' own.
102
+ def databases(task_name, configurations: ::ActiveRecord::Base.configurations,
103
+ env: ::ActiveRecord::Tasks::DatabaseTasks.env)
104
+ require "trellis/schema_dump"
105
+ wanted = SchemaDump.dump_database
106
+ named = TASKS.filter_map { |pattern| pattern.match(task_name)&.captures&.first }.first
107
+ return [] if named && named != wanted
108
+
109
+ environments(task_name, env.to_s).filter_map do |environment|
110
+ configurations.configs_for(env_name: environment, name: wanted)
111
+ end
112
+ end
113
+
114
+ private
115
+
116
+ def key(db_config)
117
+ [db_config.env_name.to_s, db_config.name.to_s]
118
+ end
119
+
120
+ # The environments a task walks: Rails' each_current_environment, which
121
+ # only the schema load and prepare tasks use, adds test to development.
122
+ def environments(task_name, env)
123
+ return ["test"] if task_name.start_with?("db:test:")
124
+
125
+ walks = task_name.match?(/\Adb:(prepare|schema:load)/)
126
+ walks && env == "development" && !ENV["SKIP_TEST_DATABASE"] && !ENV["DATABASE_URL"] ? [env, "test"] : [env]
127
+ end
128
+ end
129
+ end
130
+ end
@@ -130,16 +130,16 @@ module Trellis
130
130
  # the definition names without a schema resolves on the connection's
131
131
  # search_path. Returns the number of rows written.
132
132
  #
133
- # The definition is the one the schema load left in the restore queue
134
- # (`trellis.restore_queue`, or the schema config.trellis.connect or
135
- # config.trellis.instances names). A definition that reads another
136
- # transform's target refreshes that target first.
133
+ # The definition is the one Trellis's catalog records (in `trellis`, or
134
+ # the schema config.trellis.connect or config.trellis.instances names),
135
+ # or one a schema load not followed by a restore left in the restore
136
+ # queue. A definition that reads another transform's target refreshes
137
+ # that target first.
137
138
  #
138
139
  # Raises Trellis::NotFoundError when the target has no definition, and
139
140
  # Trellis::ValidationError when Trellis is on in this environment
140
141
  # (Trellis.enabled?), where the engine maintains the target and would
141
- # overwrite what this writes. `trellis_on: true` writes anyway, reading
142
- # the definition from the instance's catalog when there is no queue.
142
+ # overwrite what this writes. `trellis_on: true` writes anyway.
143
143
  def refresh_trellis_target(target, connection: nil, trellis_on: false)
144
144
  if Trellis.enabled? && !trellis_on
145
145
  raise ValidationError,
@@ -244,8 +244,8 @@ module Trellis
244
244
  when 1 then matches.first
245
245
  when 0
246
246
  raise NotFoundError,
247
- "no Trellis definition is recorded for the target #{name}: refresh_trellis_target reads " \
248
- "the definitions the schema load left in #{trellis_schemas.map { |s| "#{s}.restore_queue" }.join(', ')}"
247
+ "no Trellis definition is recorded for the target #{name} in the schemas " \
248
+ "#{trellis_schemas.join(', ')}"
249
249
  else
250
250
  raise ValidationError,
251
251
  "#{name} names more than one target (#{matches.map { |d| d.fetch(:target) }.join(', ')}): " \