Class: Woods::Db::Migrator

Inherits:
Object
  • Object
show all
Defined in:
lib/woods/db/migrator.rb

Overview

Runs schema migrations against a database connection.

Tracks applied migrations via SchemaVersion and only runs pending ones. Migrations are defined as modules in ‘db/migrations/` with a VERSION constant and a `.up(connection)` class method.

Examples:

db = SQLite3::Database.new('woods.db')
migrator = Migrator.new(connection: db)
migrator.migrate!  # => [1, 2, 3]

Constant Summary collapse

MIGRATIONS =
[
  Migrations::CreateUnits,
  Migrations::CreateEdges,
  Migrations::CreateEmbeddings,
  Migrations::CreateSnapshots,
  Migrations::CreateSnapshotUnits,
  Migrations::RenameTables
].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection:) ⇒ Migrator

Returns a new instance of Migrator.

Parameters:

  • connection (Object)

    Database connection supporting #execute



37
38
39
40
41
# File 'lib/woods/db/migrator.rb', line 37

def initialize(connection:)
  @connection = connection
  @schema_version = SchemaVersion.new(connection: connection)
  @schema_version.ensure_table!
end

Instance Attribute Details

#schema_versionObject (readonly)

Returns the value of attribute schema_version.



34
35
36
# File 'lib/woods/db/migrator.rb', line 34

def schema_version
  @schema_version
end

Instance Method Details

#migrate!Array<Integer>

Run all pending migrations.

Returns:

  • (Array<Integer>)

    Version numbers of newly applied migrations



46
47
48
49
50
51
52
53
54
# File 'lib/woods/db/migrator.rb', line 46

def migrate!
  applied = []
  pending_migrations.each do |migration|
    migration.up(@connection)
    @schema_version.record_version(migration::VERSION)
    applied << migration::VERSION
  end
  applied
end

#pending_versionsArray<Integer>

List version numbers of pending (unapplied) migrations.

Returns:

  • (Array<Integer>)


59
60
61
62
# File 'lib/woods/db/migrator.rb', line 59

def pending_versions
  applied = @schema_version.applied_versions
  MIGRATIONS.map { |m| m::VERSION }.reject { |v| applied.include?(v) }
end