Class: CassandraSchema::Migrator

Inherits:
Object
  • Object
show all
Defined in:
lib/cassandra-schema/migrator.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  lock:          true,
  lock_timeout:  30,
  lock_retry:    [],
  query_timeout: 30,
  query_delay:   0,
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection:, migrations:, logger: Logger.new(STDOUT), options: {}) ⇒ Migrator

Returns a new instance of Migrator.



15
16
17
18
19
20
21
22
# File 'lib/cassandra-schema/migrator.rb', line 15

def initialize(connection:, migrations:, logger: Logger.new(STDOUT), options: {})
  @connection = connection
  @logger     = logger
  @migrations = migrations
  @options    = DEFAULT_OPTIONS.merge(options)

  generate_migrator_schema!
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



5
6
7
# File 'lib/cassandra-schema/migrator.rb', line 5

def connection
  @connection
end

#current_versionObject (readonly)

Returns the value of attribute current_version.



5
6
7
# File 'lib/cassandra-schema/migrator.rb', line 5

def current_version
  @current_version
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/cassandra-schema/migrator.rb', line 5

def options
  @options
end

Instance Method Details

#migrate(target = nil) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/cassandra-schema/migrator.rb', line 24

def migrate(target = nil)
  lock_retry = @options.fetch(:lock_retry).dup

  begin
    raise if @options.fetch(:lock) && !lock_schema
  rescue
    if wait = lock_retry.shift
      @logger.info "Schema is locked; retrying in #{wait} seconds"
      sleep wait
      retry
    end

    @logger.info "Can't run migrations. Schema is locked."
    return
  end

  @current_version = get_current_version

  target ||= @migrations.keys.max || 0

  @logger.info "Running migrations..."

  if target == current_version || @migrations.empty?
    @logger.info "Nothing to migrate."
    return
  end

  begin
    if target > current_version
      # excludes current version's up
      (current_version + 1).upto(target) do |next_version|
        migrate_to(next_version, :up)
        renew_lock if @options.fetch(:lock)
      end
    else
      # includes current version's :down
      # excludes target version's :down
      current_version.downto(target + 1) do |version|
        migrate_to(version, :down)
        renew_lock if @options.fetch(:lock)
      end
    end

    @logger.info "Current version: #{current_version}"
    @logger.info "Done!"
  rescue => ex
    @logger.error ex.message if ex.message && !ex.message.empty?
    @logger.info "Failed migrating all files. Current schema version: #{@current_version}"
  ensure
    unlock_schema if @options.fetch(:lock)
  end
end