Class: Hummingbird::Database
- Inherits:
-
Object
- Object
- Hummingbird::Database
- Defined in:
- lib/hummingbird/database.rb
Overview
Class to handle retrieving recorded migrations, as well as running new migrations and recording that they have been run.
Instance Method Summary collapse
-
#already_run_migrations ⇒ Array<Hash{Symbol => String, Number}>
If the database has yet to be initialized with the migrations table, or if the migrations table has no recorded migrations, this will return an empty array.
-
#initialize(connection_string, migrations_table) ⇒ Database
constructor
A new instance of Database.
-
#initialized? ⇒ true, false
Whether or not the migrations table is present in the database.
-
#run_migration(name, sql) ⇒ Object
Run the provided SQL in a transaction (provided the DB in question supports transactions).
Constructor Details
#initialize(connection_string, migrations_table) ⇒ Database
Returns a new instance of Database.
12 13 14 15 16 |
# File 'lib/hummingbird/database.rb', line 12 def initialize(connection_string, migrations_table) @sequel_db = Sequel.connect(connection_string) @migrations_table_name = migrations_table @prepared_run_migration_insert = nil end |
Instance Method Details
#already_run_migrations ⇒ Array<Hash{Symbol => String, Number}>
If the database has yet to be initialized with the migrations table, or if the migrations table has no recorded migrations, this will return an empty array.
If there are recorded migrations, this will return an array of hashes. Where the hashes have the following format:
{
:migration_name => 'name/of/migration.sql',
:run_on => 1350683387
}
‘:migration_name` is the path of the migration file relative to the migrations directory. `:run_on` is the time the migration was run, as a unix epoch.
43 44 45 |
# File 'lib/hummingbird/database.rb', line 43 def already_run_migrations initialized? ? @sequel_db[@migrations_table_name].order(:run_on).to_a : [] end |
#initialized? ⇒ true, false
Returns Whether or not the migrations table is present in the database.
20 21 22 |
# File 'lib/hummingbird/database.rb', line 20 def initialized? @sequel_db.tables.include?(@migrations_table_name) end |
#run_migration(name, sql) ⇒ Object
Run the provided SQL in a transaction (provided the DB in question supports transactions). If the SQL successfully runs, then also record the migration in the migration table. The time recorded for the ‘run_on` of the migration is when the migration finished, not when it started.
57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/hummingbird/database.rb', line 57 def run_migration(name,sql) @prepared_run_migration_insert ||= @sequel_db[@migrations_table_name].prepare(:insert, :record_migration, migration_name: :$name, run_on: :$date) @sequel_db.transaction do @sequel_db.execute(sql) @prepared_run_migration_insert.call(name: name, date: DateTime.now.strftime('%s')) end true end |