Skip to content

Commit

Permalink
Fixed constraint name for long table and column names with change_col…
Browse files Browse the repository at this point in the history
…umn_null - fixes #291
  • Loading branch information
ankane committed Jan 29, 2025
1 parent aef4e80 commit 241631e
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
13 changes: 12 additions & 1 deletion lib/strong_migrations/checks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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}]
Expand Down
8 changes: 8 additions & 0 deletions test/migrations/change_column_null.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions test/safe_by_default_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 241631e

Please sign in to comment.