Class: Cassandro::Migrator

Inherits:
Object
  • Object
show all
Defined in:
lib/cassandro/ext/migrator.rb

Defined Under Namespace

Classes: CassandroMigration

Instance Method Summary collapse

Constructor Details

#initialize(path, logger = ::Logger.new(STDOUT)) ⇒ Migrator

Returns a new instance of Migrator.

[View source]

6
7
8
9
10
11
12
13
14
15
16
# File 'lib/cassandro/ext/migrator.rb', line 6

def initialize(path, logger = ::Logger.new(STDOUT))
  Dir["#{path}/**/*.rb"].each { |file| require file }
  @migrations = Cassandro::Migration.migrations
  @logger = logger

  Cassandro.client.execute CassandroMigration.schema

  version = CassandroMigration[name: 'version'] || CassandroMigration.create(name: 'version', value: "0")

  @current_version = version
end

Instance Method Details

#migrate!(direction, to = '.') ⇒ Object

[View source]

18
19
20
21
22
23
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
# File 'lib/cassandro/ext/migrator.rb', line 18

def migrate!(direction, to = '.')
  from = @current_version.value.to_i

  case direction
  when :up
    to   = (to == '.' ? @migrations.size - 1 : to).to_i
    return @logger.error "Can't migrate up to a prev version (#{from} to #{to})" if to < from
    return @logger.info  "Database is up to date" if to == from

    @logger.info "Upgrading database from version #{from} to #{to}"
    begin
      @migrations[from+1..to].each do |migration|
        Object.const_get(migration).apply(:up)
      end
      @current_version.update_attributes(value: to.to_s)
      @logger.info "OK"
    rescue => e
      @logger.error "#{e.message}\n#{e.backtrace}"
    end
  when :down
    to   = (to == '.' ? 0 : to).to_i
    return @logger.error "Can't migrate down to a higher version (#{from} to #{to})" if to > from
    return @logger.info  "Database is up to date" if to == from

    @logger.info "Drowngrading database from version #{from} to #{to}"
    begin
      @migrations[to+1..from].reverse_each do |migration|
        Object.const_get(migration).apply(:down)
      end
      @current_version.update_attributes(value: to.to_s)
      @logger.info "OK"
    rescue => e
      @logger.error "#{e.message}\n#{e.backtrace}"
    end
  end
end