Class: Woods::Db::SchemaVersion
- Inherits:
-
Object
- Object
- Woods::Db::SchemaVersion
- 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).
Constant Summary collapse
- TABLE_NAME =
'woods_schema_migrations'
Instance Method Summary collapse
-
#applied?(version) ⇒ Boolean
Check whether a version has been applied.
-
#applied_versions ⇒ Array<Integer>
List all applied migration version numbers, sorted ascending.
-
#current_version ⇒ Integer
The highest applied version, or 0 if none.
-
#ensure_table! ⇒ void
Create the schema migrations table if it does not exist.
-
#initialize(connection:) ⇒ SchemaVersion
constructor
A new instance of SchemaVersion.
-
#record_version(version) ⇒ void
Record a migration version as applied.
Constructor Details
#initialize(connection:) ⇒ SchemaVersion
Returns a new instance of SchemaVersion.
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.
61 62 63 |
# File 'lib/woods/db/schema_version.rb', line 61 def applied?(version) applied_versions.include?(version) end |
#applied_versions ⇒ Array<Integer>
List all applied migration version numbers, sorted ascending.
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_version ⇒ Integer
The highest applied version, or 0 if none.
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.
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 |