diff --git a/CHANGELOG.md b/CHANGELOG.md index 1607d59..8730a46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## 2.1.1 (unreleased) + +- Fixed constraint name for long table and column names with `change_column_null` + ## 2.1.0 (2024-11-08) - Added `skip_database` method diff --git a/lib/strong_migrations/checks.rb b/lib/strong_migrations/checks.rb index 7aab849..bd01d68 100644 --- a/lib/strong_migrations/checks.rb +++ b/lib/strong_migrations/checks.rb @@ -232,10 +232,21 @@ def check_change_column_null(*args) safe = constraints.any? { |c| c.options[:validate] && (c.expression == "#{column} IS NOT NULL" || c.expression == "#{connection.quote_column_name(column)} IS NOT NULL") } unless safe + expression = "#{quote_column_if_needed(column)} IS NOT NULL" + # match https://github.com/nullobject/rein constraint_name = "#{table}_#{column}_null" + # 63 characters is max length for Postgres, 64 characters for MySQL and MariaDB + if constraint_name.bytesize > 63 + constraint_name = connection.check_constraint_options(table, expression, {})[:name] + + # avoid collision with Active Record naming for safe_by_default + if StrongMigrations.safe_by_default + constraint_name = constraint_name.sub("rails", "strong") + end + end - add_args = [table, "#{quote_column_if_needed(column)} IS NOT NULL", {name: constraint_name, validate: false}] + add_args = [table, expression, {name: constraint_name, validate: false}] validate_args = [table, {name: constraint_name}] change_args = [table, column, null] remove_args = [table, {name: constraint_name}] diff --git a/test/migrations/change_column_null.rb b/test/migrations/change_column_null.rb index d572063..f63ac67 100644 --- a/test/migrations/change_column_null.rb +++ b/test/migrations/change_column_null.rb @@ -83,3 +83,11 @@ def down change_column_null :users, :interval, true end end + +class ChangeColumnNullLongName < TestMigration + def change + column = "a"*60 + add_column :users, column, :string + change_column_null :users, column, false + end +end diff --git a/test/safe_by_default_test.rb b/test/safe_by_default_test.rb index f83a93d..66812ad 100644 --- a/test/safe_by_default_test.rb +++ b/test/safe_by_default_test.rb @@ -235,4 +235,10 @@ def test_change_column_null_invalid ensure User.delete_all end + + def test_change_column_null_long_name + skip unless postgresql? + + assert_safe ChangeColumnNullLongName + end end