strong_migrations: Support custom checks against the TableDefinition object in the `create_table` block

Hi! There’s currently a check against adding foreign key constraints unsafely. This problem is that this doesn’t include adding foreign keys using the create_table method, e.g.:

create_table(:menus) do |t|
  t.references :restaurant, null: false, foreign_key: true, type: :uuid
end

This circumvents the check, which can cause locking and downtime. Some options in the solution space here:

  1. Have the foreign key check include looking at the TableDefinition object passed into create_table for foreign key additions
  2. More generally, allow strong_migrations users to configure custom checks against the TableDefinition

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 18 (9 by maintainers)

Most upvoted comments

Adding a foreign key is safe on an empty table

I don’t know the exact differences but our teams understanding is the same as @bullfight’s. That Postgres can lock the referenced tables so it’s not safe.

Here’s an example migration that brought our db to a halt.

# 1
create_table :x do |t|
  t.references :busy_table_one, null: false, index: true,
    foreign_key: {on_delete: :cascade}
  t.references :from_busy_table_two, null: false, index: true,
    foreign_key: {to_table: :busy_table_two, on_delete: :cascade}
  t.references :to_busy_table_two, null: false, index: true
    foreign_key: {to_table: :busy_table_two, on_delete: :cascade}
  t.timestamps
end

Adding / validating the foreign keys across separately did not.

# 1
create_table :x do |t|
  t.references :busy_table_one, null: false, index: true
  t.references :from_busy_table_two, null: false, index: true
  t.references :to_busy_table_two, null: false, index: true
  t.timestamps
end

# 2
add_foreign_key :x, :busy_table_one, column: :busy_table_one_id,
  validate: false, on_delete: :cascade

# 3
add_foreign_key :x, :busy_table_two, column: :from_busy_table_two_id,
  validate: false, on_delete: :cascade

# 4
add_foreign_key :x, :busy_table_two, column: :to_busy_table_two_id,
  validate: false, on_delete: :cascade

# 5
validate_foreign_key :x, column: :busy_table_one_id
validate_foreign_key :x, column: :from_busy_table_two_id
validate_foreign_key :x, column: :to_busy_table_two_id

Just one example, so not conclusive. But we’re now enforcing adding foreign keys separately because we’ve been bitten more than once by this. Keen to hear if you know what else could be the issue with the first migration.