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]


62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/active_record_shards/migration.rb', line 62

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
24
25
26
27
# 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
    if ActiveRecord::VERSION::MAJOR >= 4
      ActiveRecord::SchemaMigration.create_table
    else
      ActiveRecord::Base.connection.initialize_schema_migrations_table
    end
    if ActiveRecord::VERSION::MAJOR >= 5
      ActiveRecord::InternalMetadata.create_table
    end
  end
end

#migrate_with_shardingObject Also known as: migrate



38
39
40
41
# File 'lib/active_record_shards/migration.rb', line 38

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

#migratedObject



47
48
49
# File 'lib/active_record_shards/migration.rb', line 47

def migrated
  self.class.shards_migration_context.get_all_versions
end

#pending_migrationsObject



53
54
55
56
57
# File 'lib/active_record_shards/migration.rb', line 53

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



31
32
33
34
# File 'lib/active_record_shards/migration.rb', line 31

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