Class: Diary::Migrator

Inherits:
Object
  • Object
show all
Defined in:
lib/diary-ruby/database/migrator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db) ⇒ Migrator

Returns a new instance of Migrator.



48
49
50
# File 'lib/diary-ruby/database/migrator.rb', line 48

def initialize(db)
  @db = db.database
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



46
47
48
# File 'lib/diary-ruby/database/migrator.rb', line 46

def db
  @db
end

Instance Method Details

#migrate!Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/diary-ruby/database/migrator.rb', line 52

def migrate!
  exists = false
  db.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name='versions';" ) do |row|
    if row
      exists = true
    end
  end

  if !exists
    db.execute(INITIALIZE)
  end

  MIGRATION_VERSIONS.each do |version|
    exists = false
    on_date = nil
    db.execute( "select rowid, migrated_at from versions WHERE version = '#{version}'" ) do |row|
      if row
        exists = true
        on_date = row[1]
      end
    end

    if !exists
      Diary.debug("UPDATING DATABASE TO VERSION #{ version }")
      if MIGRATIONS[version].is_a?(Array)
        MIGRATIONS[version].each do |statement|
          db.execute(statement)
        end
      else
        db.execute(MIGRATIONS[version])
      end
      db.execute("INSERT INTO versions VALUES ('#{version}', strftime('%Y-%m-%dT%H:%M:%S+0000'));")
    else
      Diary.debug("AT #{ version } SINCE #{ on_date }")
    end
  end
end