Class: ActiveRecord::Migrator

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record_shards/migration.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.shard_status(versions) ⇒ Object

public list of pending and missing versions per shard

=> [1234567], => [2345678]


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/active_record_shards/migration.rb', line 58

def self.shard_status(versions)
  pending = {}
  missing = {}

  collect = lambda do |shard|
    migrated = shards_migration_context.get_all_versions

    p = versions - migrated
    pending[shard] = p if p.any?

    m = migrated - versions
    missing[shard] = m if m.any?
  end

  ActiveRecord::Base.on_shard(nil) { collect.call(nil) }
  ActiveRecord::Base.on_all_shards { |shard| collect.call(shard) }

  [pending, missing]
end

.shards_migration_contextObject



4
5
6
7
8
9
10
# File 'lib/active_record_shards/migration.rb', line 4

def self.shards_migration_context
  if ActiveRecord::VERSION::STRING >= '5.2.0'
    ActiveRecord::MigrationContext.new(['db/migrate'])
  else
    self
  end
end

Instance Method Details

#initialize_with_sharding(*args) ⇒ Object Also known as: initialize



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/active_record_shards/migration.rb', line 12

def initialize_with_sharding(*args)
  initialize_without_sharding(*args)

  # Rails creates the internal tables on the unsharded DB. We make them
  # manually on the sharded DBs.
  ActiveRecord::Base.on_all_shards do
    ActiveRecord::SchemaMigration.create_table
    if ActiveRecord::VERSION::MAJOR >= 5
      ActiveRecord::InternalMetadata.create_table
    end
  end
end

#migrate_with_shardingObject Also known as: migrate



34
35
36
37
# File 'lib/active_record_shards/migration.rb', line 34

def migrate_with_sharding
  ActiveRecord::Base.on_shard(nil) { migrate_without_sharding }
  ActiveRecord::Base.on_all_shards { migrate_without_sharding }
end

#migratedObject



43
44
45
# File 'lib/active_record_shards/migration.rb', line 43

def migrated
  self.class.shards_migration_context.get_all_versions
end

#pending_migrationsObject



49
50
51
52
53
# File 'lib/active_record_shards/migration.rb', line 49

def pending_migrations
  pending, _missing = self.class.shard_status(migrations.map(&:version))
  pending = pending.values.flatten
  migrations.select { |m| pending.include?(m.version) }
end

#run_with_shardingObject Also known as: run



27
28
29
30
# File 'lib/active_record_shards/migration.rb', line 27

def run_with_sharding
  ActiveRecord::Base.on_shard(nil) { run_without_sharding }
  ActiveRecord::Base.on_all_shards { run_without_sharding }
end