Class: Cybertrain::Migration::Base

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/migration.rb

Overview

The superclass of every migration in db/migrate/. A file is named <version>_<name>.rb (20260925174942_create_articles.rb) and holds the class <Name> (CreateArticles); the version is the file’s prefix. cybertrain generate scaffold writes one, and cybertrain db migrate applies the pending ones (db rollback [N] reverts), each in a transaction, then rewrites db/schema.rb from the database. Never edit db/schema.rb by hand.

Write change when every operation is reversible (create_table, add_column, add_index, rename_column); otherwise write up and down. A data step goes through #execute, which runs in order with the schema operations, in the same transaction. SQLite cannot add a foreign key to an existing table, so declare references in create_table or with #add_reference. #change_column, #change_column_default, #change_column_null, #remove_reference and #remove_foreign_key rebuild the table (SQLite has no ALTER COLUMN), with foreign key enforcement off for the version and checked before its commit. The rebuilt table is declared from the schema, so a rebuild refuses (DB::Error “rebuilding <table> would drop

: rewrite the migration with execute", before it touches the table, and the version rolls back) a table whose CREATE TABLE has what the schema does not model: a CHECK or inline UNIQUE constraint (a unique index is fine), COLLATE, a generated column, ON UPDATE, ON DELETE SET DEFAULT, DEFERRABLE, a foreign key to a column other than id, a column with no type, a primary key other than id, WITHOUT ROWID or STRICT. Write such a change as #execute statements. Not available: `create_join_table`, `change_table`, `rename_index`, `add_timestamps`, an expression index in #add_index (write it with #execute; the schema dump keeps it).

Examples:

class CreateComments < Cybertrain::Migration::Base
  def change
    create_table "comments" do |t|
      t.string "commenter"
      t.text "body"
      t.references :article
      t.timestamps
    end
  end
end

up and down

class RemoveSubtitleFromArticles < Cybertrain::Migration::Base
  def up
    remove_column "articles", "subtitle"
  end

  def down
    add_column "articles", "subtitle", :string
  end
end

Instance Method Summary collapse

Instance Method Details

#add_column(table, name, type, null: true, default: nil, limit: 0, precision: 0, scale: -1)) ⇒ nil

Adds a column. Reversible. SQLite adds a NOT NULL column to an existing table only with a non-NULL default:.

Examples:

add_column "articles", "published", :boolean, null: false, default: "false"

Parameters:

  • table (String, Symbol)
  • name (String, Symbol)
  • type (Symbol) —

    :string, :text, :integer, :float, :decimal, :boolean, :datetime, :date, :binary (BLOB) or :json

  • null (Boolean) (defaults to: true)
  • default (String, nil) (defaults to: nil) —

    SQL literal text

  • limit (Integer) (defaults to: 0) —

    VARCHAR(n) for a string when positive; 8 makes an integer a BIGINT

  • precision (Integer) (defaults to: 0) —

    a decimal’s total digits; 0 for none

  • scale (Integer) (defaults to: -1)) —

    a decimal’s digits after the point; -1 for none (a scale needs a precision: ArgumentError otherwise)

Returns:

  • (nil)


406
407
408
409
410
# File 'cybertrain/migration.rb', line 406

def add_column(table, name, type, null: true, default: nil, limit: 0, precision: 0, scale: -1)
  Cybertrain::Schema::Column.check_decimal(precision, scale)
  @operations << Operation.for_add_column(table.to_s, name.to_s, type, null, default, limit, precision, scale)
  nil
end

#add_index(table, columns, unique: false, name: "", where: "") ⇒ nil

Adds an index, named index_<table>_on_<col>_and_<col> unless name: is given. Reversible.

Examples:

add_index "articles", ["slug"], unique: true

Parameters:

  • table (String, Symbol)
  • columns (Array<String, Symbol>)
  • unique (Boolean) (defaults to: false)
  • name (String) (defaults to: "")
  • where (String) (defaults to: "") —

    a partial index’s predicate ("deleted_at IS NULL"); “” for none

Returns:

  • (nil)


446
447
448
449
450
# File 'cybertrain/migration.rb', line 446

def add_index(table, columns, unique: false, name: "", where: "")
  cols = columns.map { |c| c.to_s }
  @operations << Operation.for_add_index(table.to_s, cols, unique, name.to_s, where.to_s)
  nil
end

#add_reference(table, name, null: false, foreign_key: true, on_delete: :no_action) ⇒ nil

Adds <name>_id (an integer, NOT NULL by default), an index on it and, unless foreign_key: false, a foreign key to the plural table. Not reversible. SQLite adds a NOT NULL column to an existing table only with a default, so pass null: true here; in a new table use Schema::TableDef#references instead.

Parameters:

  • table (String, Symbol)
  • name (Symbol, String) —

    the singular (:author)

  • null (Boolean) (defaults to: false)
  • foreign_key (Boolean) (defaults to: true)
  • on_delete (Symbol) (defaults to: :no_action) —

    :no_action, :cascade, :nullify (needs null: true) or :restrict, as Schema::TableDef#references

Returns:

  • (nil)


476
477
478
479
480
481
482
483
484
485
486
# File 'cybertrain/migration.rb', line 476

def add_reference(table, name, null: false, foreign_key: true, on_delete: :no_action)
  Cybertrain::Schema::ForeignKey.check_on_delete(on_delete)
  Cybertrain::Schema::ForeignKey.check_nullify(on_delete, null)
  column_name = "#{name}_id"
  @operations << Operation.for_add_reference(table.to_s, column_name, null, on_delete)
  if foreign_key
    to_table = Cybertrain::Inflector.pluralize(name.to_s)
    @operations << Operation.for_add_foreign_key(table.to_s, to_table, column_name, on_delete)
  end
  nil
end

#change

This method returns an undefined value.

Override with the migration’s operations; cybertrain db migrate runs them, and db rollback runs their inverses in reverse order.

Subclasses override change (recorded both ways via inverse) or up/down directly when a migration is not mechanically reversible.



323
324
# File 'cybertrain/migration.rb', line 323

def change
end

#change_column(table, column, type, null: true, default: nil, limit: 0, precision: 0, scale: -1)) ⇒ nil

Redefines a column: the table is rebuilt with the column declared as given (everything not given is reset, as in Rails), its rows copied over. Not reversible inside change: write up and down.

Examples:

change_column :posts, :views, :bigint
change_column :posts, :price, :decimal, precision: 10, scale: 2, null: false, default: "0"

Parameters:

  • table (String, Symbol)
  • column (String, Symbol)
  • type (Symbol) —

    a type #add_column takes, or :bigint

  • null (Boolean) (defaults to: true)
  • default (String, nil) (defaults to: nil) —

    SQL literal text

  • limit (Integer) (defaults to: 0) —
  • precision (Integer) (defaults to: 0) —
  • scale (Integer) (defaults to: -1)) —

Returns:

  • (nil)

Raises:

  • (Cybertrain::DB::Error) —

    when migrating, if the table has something a rebuild would drop (see the class notes); the version rolls back



555
556
557
558
559
560
561
562
563
564
565
# File 'cybertrain/migration.rb', line 555

def change_column(table, column, type, null: true, default: nil, limit: 0, precision: 0, scale: -1)
  Cybertrain::Schema::Column.check_decimal(precision, scale)
  kind = type
  size = limit
  if type == :bigint
    kind = :integer
    size = 8
  end
  @operations << Operation.for_change_column(table.to_s, column.to_s, kind, null, default, size, precision, scale)
  nil
end

#change_column_default(table, column, from: UNKNOWN_DEFAULT, to:) ⇒ nil

Changes a column’s default (by rebuilding the table). Reversible when from: names the previous default (from: nil when there was none); without it a rollback raises IrreversibleMigration.

Examples:

change_column_default :posts, :state, from: nil, to: "'draft'"

Parameters:

  • table (String, Symbol)
  • column (String, Symbol)
  • from (String, nil) (defaults to: UNKNOWN_DEFAULT) —

    the previous default, SQL literal text

  • to (String, nil) —

    the new default, SQL literal text; nil drops it

Returns:

  • (nil)

Raises:

  • (Cybertrain::DB::Error) —

    when migrating, if the table has something a rebuild would drop (see the class notes); the version rolls back



580
581
582
583
584
585
# File 'cybertrain/migration.rb', line 580

def change_column_default(table, column, from: UNKNOWN_DEFAULT, to:)
  given = from != UNKNOWN_DEFAULT
  previous = given ? from : Operation.no_default
  @operations << Operation.for_change_column_default(table.to_s, column.to_s, given, previous, to)
  nil
end

#change_column_null(table, column, null, default = nil) ⇒ nil

Adds or drops a column’s NOT NULL (by rebuilding the table). With null false, default is first written into the cells that are NULL (UPDATE ... WHERE column IS NULL); it does not become the column’s DEFAULT. Reversible, except that rolling back a null true needs default for the cells that became NULL since.

Examples:

change_column_null :posts, :title, false, "untitled"

Parameters:

  • table (String, Symbol)
  • column (String, Symbol)
  • null (Boolean)
  • default (String, Integer, Float, Boolean, Time, nil) (defaults to: nil) —

    a value (not SQL text) for the NULL cells

Returns:

  • (nil)

Raises:

  • (Cybertrain::DB::Error) —

    when migrating, if the table has something a rebuild would drop (see the class notes); the version rolls back



603
604
605
606
607
608
# File 'cybertrain/migration.rb', line 603

def change_column_null(table, column, null, default = nil)
  values = Operation.no_binds
  values << Cybertrain::Cast.to_sql(default) unless default.nil?
  @operations << Operation.for_change_column_null(table.to_s, column.to_s, null, values)
  nil
end

#create_table(name) {|t| ... }

This method returns an undefined value.

Creates a table with an id primary key and the columns the block declares. Reversible.

Parameters:

  • name (String, Symbol) —

    the plural ("articles")

Yield Parameters:



365
366
367
368
369
370
# File 'cybertrain/migration.rb', line 365

def create_table(name)
  table = Cybertrain::Schema::Table.new(name)
  yield Cybertrain::Schema::TableDef.new(table)
  @operations << Operation.for_create_table(table)
  table
end

#down

This method returns an undefined value.

What db rollback runs: the inverse of change, unless you override it (together with #up).

The default down runs change to record the forward operations, then replaces them with their inverses in reverse order – it must NOT simply re-run change and keep the forward operations, or a rollback would re-apply the migration instead of undoing it. Raises IrreversibleMigration (via inverse) when change recorded an operation with no automatic inverse.



352
353
354
355
356
357
# File 'cybertrain/migration.rb', line 352

def down
  @operations = empty_operations
  change
  @operations = @operations.reverse.map { |op| inverse(op) }
  nil
end

#drop_table(name) ⇒ nil

Drops a table. Not reversible.

Parameters:

  • name (String, Symbol)

Returns:

  • (nil)


383
384
385
386
# File 'cybertrain/migration.rb', line 383

def drop_table(name)
  @operations << Operation.for_drop_table(name.to_s)
  nil
end

#execute(sql, binds = []) ⇒ nil

Runs a data statement (an UPDATE, an INSERT, a DELETE) at this point of the migration, on the migrator’s own connection and inside the same transaction as the version’s schema operations: operations recorded before it have run when it runs, and those after it run after it. Nothing runs while the migration is only being recorded, so the migrator can call up to learn a version’s operations (it does, when rolling back) without repeating the statement.

Without binds sql may hold several statements separated by ;; with binds it must be exactly one statement with ? placeholders.

Not reversible: rolling back a change that executes SQL raises IrreversibleMigration before anything is reverted, unless the migration defines #down. db/schema.rb is dumped from the database, so a data statement never appears in it.

Examples:

keep existing rows when a new column’s default would change them

class AddRetentionDaysToBackups < Cybertrain::Migration::Base
  def change
    add_column "backups", "retention_days", :integer, null: false, default: "90"
    execute "UPDATE backups SET retention_days = ?", [0]
  end

  def down
    remove_column "backups", "retention_days"
  end
end

Parameters:

  • sql (String)
  • binds (Array<String, Integer, Float, Boolean, Time, nil>) (defaults to: []) —

    values for the ? placeholders, in order

Returns:

  • (nil)


519
520
521
522
523
524
# File 'cybertrain/migration.rb', line 519

def execute(sql, binds = [])
  values = Operation.no_binds
  binds.each { |v| values << Cybertrain::Cast.to_sql(v) }
  @operations << Operation.for_execute(sql.to_s, values)
  nil
end

#remove_column(table, name) ⇒ nil

Drops a column (ALTER TABLE ... DROP COLUMN). Not reversible. Drop its indexes first.

Parameters:

  • table (String, Symbol)
  • name (String, Symbol)

Returns:

  • (nil)


418
419
420
421
# File 'cybertrain/migration.rb', line 418

def remove_column(table, name)
  @operations << Operation.for_remove_column(table.to_s, name.to_s)
  nil
end

#remove_foreign_key(from_table, to_table, column: "") ⇒ nil

Drops the foreign key from from_table to to_table (by rebuilding the table); the column and its index stay. Not reversible inside change.

Parameters:

  • from_table (String, Symbol)
  • to_table (String, Symbol)
  • column (String) (defaults to: "") —

    the referencing column; “” means singularize(to_table) + “_id”

Returns:

  • (nil)

Raises:

  • (Cybertrain::DB::Error) —

    when migrating, if the table has something a rebuild would drop (see the class notes); the version rolls back



634
635
636
637
638
639
# File 'cybertrain/migration.rb', line 634

def remove_foreign_key(from_table, to_table, column: "")
  col = column.to_s
  col = Cybertrain::Schema::ForeignKey.default_column(to_table) if col == ""
  @operations << Operation.for_remove_foreign_key(from_table.to_s, to_table.to_s, col)
  nil
end

#remove_index(table, columns) ⇒ nil

Drops the index on these columns. Not reversible.

Parameters:

  • table (String, Symbol)
  • columns (Array<String, Symbol>)

Returns:

  • (nil)


457
458
459
460
461
# File 'cybertrain/migration.rb', line 457

def remove_index(table, columns)
  cols = columns.map { |c| c.to_s }
  @operations << Operation.for_remove_index(table.to_s, cols)
  nil
end

#remove_reference(table, name) ⇒ nil

Drops <name>_id, its indexes and its foreign key (by rebuilding the table). Not reversible inside change.

Parameters:

  • table (String, Symbol)
  • name (Symbol, String) —

    the singular (:author)

Returns:

  • (nil)

Raises:

  • (Cybertrain::DB::Error) —

    when migrating, if the table has something a rebuild would drop (see the class notes); the version rolls back



618
619
620
621
# File 'cybertrain/migration.rb', line 618

def remove_reference(table, name)
  @operations << Operation.for_remove_reference(table.to_s, "#{name}_id")
  nil
end

#rename_column(table, from, to) ⇒ nil

Renames a column. Reversible.

Parameters:

  • table (String, Symbol)
  • from (String, Symbol)
  • to (String, Symbol)

Returns:

  • (nil)


429
430
431
432
# File 'cybertrain/migration.rb', line 429

def rename_column(table, from, to)
  @operations << Operation.for_rename_column(table.to_s, from.to_s, to.to_s)
  nil
end

#rename_table(old_name, new_name) ⇒ nil

Renames a table (ALTER TABLE ... RENAME TO ...); the foreign keys that point at it follow. Its indexes keep their names. Reversible.

Parameters:

  • old_name (String, Symbol)
  • new_name (String, Symbol)

Returns:

  • (nil)


532
533
534
535
# File 'cybertrain/migration.rb', line 532

def rename_table(old_name, new_name)
  @operations << Operation.for_rename_table(old_name.to_s, new_name.to_s)
  nil
end

#reversible {|dir| ... } ⇒ nil

A data step written both ways inside change: dir.up’s #execute statements run on migrate, dir.down’s on rollback. Only #execute goes inside the blocks.

Examples:

reversible do |dir|
  dir.up { execute "UPDATE posts SET slug = lower(title)" }
  dir.down { execute "UPDATE posts SET slug = NULL" }
end

Yield Parameters:

Returns:

  • (nil)


652
653
654
655
# File 'cybertrain/migration.rb', line 652

def reversible
  yield Direction.new(self)
  nil
end

#up

This method returns an undefined value.

What db migrate runs: change, unless you override it (together with #down) because change cannot be reversed automatically.

Both up and down reset @operations before running change so calling either one twice (or calling both on the same instance) never duplicates or mixes forward/backward operations.



334
335
336
337
338
# File 'cybertrain/migration.rb', line 334

def up
  @operations = empty_operations
  change
  nil
end