Module: Apartment::Migrator

Defined in:
lib/apartment/migrator.rb

Class Method Summary collapse

Class Method Details

.migrate(database) ⇒ Object

Migrate to latest



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/apartment/migrator.rb', line 10

def migrate(database)
  # Pin a connection for the entire migration to ensure Tenant.switch
  # sets search_path on the same connection used by migration_context.
  # Without this, connection pool may return different connections
  # for the switch vs the actual migration operations.
  ActiveRecord::Base.connection_pool.with_connection do
    Tenant.switch(database) do
      version = ENV['VERSION']&.to_i

      migration_scope_block = ->(migration) { ENV['SCOPE'].blank? || (ENV['SCOPE'] == migration.scope) }

      if ActiveRecord.version >= Gem::Version.new('7.2.0')
        ActiveRecord::Base.connection_pool.migration_context.migrate(version, &migration_scope_block)
      else
        ActiveRecord::Base.connection.migration_context.migrate(version, &migration_scope_block)
      end
    end
  end
end

.rollback(database, step = 1) ⇒ Object

rollback latest migration ‘step` number of times



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/apartment/migrator.rb', line 44

def rollback(database, step = 1)
  ActiveRecord::Base.connection_pool.with_connection do
    Tenant.switch(database) do
      if ActiveRecord.version >= Gem::Version.new('7.2.0')
        ActiveRecord::Base.connection_pool.migration_context.rollback(step)
      else
        ActiveRecord::Base.connection.migration_context.rollback(step)
      end
    end
  end
end

.run(direction, database, version) ⇒ Object

Migrate up/down to a specific version



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/apartment/migrator.rb', line 31

def run(direction, database, version)
  ActiveRecord::Base.connection_pool.with_connection do
    Tenant.switch(database) do
      if ActiveRecord.version >= Gem::Version.new('7.2.0')
        ActiveRecord::Base.connection_pool.migration_context.run(direction, version)
      else
        ActiveRecord::Base.connection.migration_context.run(direction, version)
      end
    end
  end
end