Class: Woods::Db::SchemaVersion

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

Overview

Tracks which schema migrations have been applied.

Uses a simple ‘woods_schema_migrations` table with a single `version` column. Works with any database connection that supports `execute` and returns arrays (SQLite3, pg, mysql2).

Examples:

db = SQLite3::Database.new('woods.db')
sv = SchemaVersion.new(connection: db)
sv.ensure_table!
sv.current_version  # => 0
sv.record_version(1)
sv.current_version  # => 1

Constant Summary collapse

TABLE_NAME =
'woods_schema_migrations'

Instance Method Summary collapse

Constructor Details

#initialize(connection:) ⇒ SchemaVersion

Returns a new instance of SchemaVersion.

Parameters:

  • connection (Object)

    Database connection supporting #execute



23
24
25
# File 'lib/woods/db/schema_version.rb', line 23

def initialize(connection:)
  @connection = connection
end

Instance Method Details

#applied?(version) ⇒ Boolean

Check whether a version has been applied.

Parameters:

  • version (Integer)

Returns:

  • (Boolean)


61
62
63
# File 'lib/woods/db/schema_version.rb', line 61

def applied?(version)
  applied_versions.include?(version)
end

#applied_versionsArray<Integer>

List all applied migration version numbers, sorted ascending.

Returns:

  • (Array<Integer>)


42
43
44
45
# File 'lib/woods/db/schema_version.rb', line 42

def applied_versions
  rows = @connection.execute("SELECT version FROM #{TABLE_NAME} ORDER BY version ASC")
  rows.map { |row| row.is_a?(Array) ? row[0] : row['version'] }
end

#current_versionInteger

The highest applied version, or 0 if none.

Returns:

  • (Integer)


68
69
70
# File 'lib/woods/db/schema_version.rb', line 68

def current_version
  applied_versions.last || 0
end

#ensure_table!void

This method returns an undefined value.

Create the schema migrations table if it does not exist.



30
31
32
33
34
35
36
37
# File 'lib/woods/db/schema_version.rb', line 30

def ensure_table!
  @connection.execute(<<~SQL)
    CREATE TABLE IF NOT EXISTS #{TABLE_NAME} (
      version INTEGER PRIMARY KEY NOT NULL,
      applied_at TEXT NOT NULL DEFAULT (datetime('now'))
    )
  SQL
end

#record_version(version) ⇒ void

This method returns an undefined value.

Record a migration version as applied.

Parameters:

  • version (Integer)

    The migration version number



51
52
53
54
55
# File 'lib/woods/db/schema_version.rb', line 51

def record_version(version)
  @connection.execute(
    "INSERT OR IGNORE INTO #{TABLE_NAME} (version) VALUES (?)", [version]
  )
end