Class: Kredis::Migration

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

Instance Method Summary collapse

Constructor Details

#initialize(config = :shared) ⇒ Migration

Returns a new instance of Migration.



8
9
10
11
12
# File 'lib/kredis/migration.rb', line 8

def initialize(config = :shared)
  @redis = Kredis.configured_for config
  # TODO: Replace script loading with `copy` command once Redis 6.2+ is the minimum supported version.
  @copy_sha = @redis.script "load", "redis.call('SETNX', KEYS[2], redis.call('GET', KEYS[1])); return 1;"
end

Instance Method Details

#delete_all(*key_patterns) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/kredis/migration.rb', line 35

def delete_all(*key_patterns)
  log_migration "DELETE ALL #{key_patterns.inspect}" do
    if key_patterns.length > 1
      @redis.del(*key_patterns)
    else
      each_key_batch_matching(key_patterns.first) do |keys, pipeline|
        pipeline.del(*keys)
      end
    end
  end
end

#migrate(from:, to:, pipeline: nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/kredis/migration.rb', line 23

def migrate(from:, to:, pipeline: nil)
  namespaced_to = Kredis.namespaced_key(to)

  if to.present? && from != namespaced_to
    log_migration "Migrating key #{from} to #{namespaced_to}" do
      (pipeline || @redis).evalsha @copy_sha, keys: [ from, namespaced_to ]
    end
  else
    log_migration "Skipping blank/unaltered migration key #{from}#{to}"
  end
end

#migrate_all(key_pattern) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/kredis/migration.rb', line 14

def migrate_all(key_pattern)
  each_key_batch_matching(key_pattern) do |keys, pipeline|
    keys.each do |key|
      ids = key.scan(/\d+/).map(&:to_i)
      migrate from: key, to: yield(key, *ids), pipeline: pipeline
    end
  end
end