Class: SequelData::Migrate::Migrator

Inherits:
Object
  • Object
show all
Defined in:
lib/sequel_data/migrate/migrator.rb

Constant Summary collapse

DATE_TIME_PATTERN =

YYYYMMDDHHMMSS

"[0-9]" * 14
FILE_NAME_PATTERN =
"#{DATE_TIME_PATTERN}_*.rb"
MUTEX =
Mutex.new

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Migrator

Returns a new instance of Migrator.



13
14
15
# File 'lib/sequel_data/migrate/migrator.rb', line 13

def initialize(config)
  @config = config
end

Instance Method Details

#migrateObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sequel_data/migrate/migrator.rb', line 17

def migrate
  connect_database do |db|
    dataset = ensure_table_exists(db)

    already_migrated = dataset.select_map(column).to_set
    migration_files = fetch_migration_files.reject { |file| already_migrated.include?(File.basename(file)) }.sort
    migrations = fetch_migrations(migration_files)

    migrations.zip(migration_files).each do |migration, file|
      db.log_info("Begin applying migration file #{file}")
      migration.new.up
      set_migration_version(db, file)
      db.log_info("Finished applying migration version #{file}")
    end
  end
end

#rollback(step = 1) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/sequel_data/migrate/migrator.rb', line 34

def rollback(step = 1)
  connect_database do |db|
    dataset = ensure_table_exists(db)

    already_migrated = dataset.select_map(column).to_set
    migration_files = fetch_migration_files.select do |file|
      already_migrated.include?(File.basename(file))
    end.sort.reverse!
    migrations = fetch_migrations(migration_files)

    migrations.zip(migration_files).each do |migration, file|
      step -= 1
      break if step.negative?

      db.log_info("Begin rolling back migration file #{file}")
      migration.new.down
      remove_migration_version(db, file)
      db.log_info("Finished rolling back migration version #{file}")
    end
  end
end