Skip to content

Commit

Permalink
Merge pull request #47948 from fatkodima/rails-5-2-create_table-dupli…
Browse files Browse the repository at this point in the history
…cate-columns

Restore ability to redefine column in `create_table` for Rails 5.2
  • Loading branch information
byroot committed Apr 16, 2023
2 parents b4f4797 + 11aaa3d commit 325dd7b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
Expand Up @@ -485,14 +485,7 @@ def column(name, type, index: nil, **options)
name = name.to_s
type = type.to_sym if type

if @columns_hash[name]
if @columns_hash[name].primary_key?
raise ArgumentError, "you can't redefine the primary key column '#{name}' on '#{@name}'. To define a custom primary key, pass { id: false } to create_table."
else
raise ArgumentError, "you can't define an already defined column '#{name}' on '#{@name}'."
end
end

raise_on_duplicate_column(name)
@columns_hash[name] = new_column_definition(name, type, **options)

if index
Expand Down Expand Up @@ -608,6 +601,16 @@ def integer_like_primary_key?(type, options)
def integer_like_primary_key_type(type, options)
type
end

def raise_on_duplicate_column(name)
if @columns_hash[name]
if @columns_hash[name].primary_key?
raise ArgumentError, "you can't redefine the primary key column '#{name}' on '#{@name}'. To define a custom primary key, pass { id: false } to create_table."
else
raise ArgumentError, "you can't define an already defined column '#{name}' on '#{@name}'."
end
end
end
end

class AlterTable # :nodoc:
Expand Down
3 changes: 3 additions & 0 deletions activerecord/lib/active_record/migration/compatibility.rb
Expand Up @@ -294,6 +294,9 @@ def column(name, type, index: nil, **options)
private
def raise_on_if_exist_options(options)
end

def raise_on_duplicate_column(name)
end
end

module CommandRecorder
Expand Down
18 changes: 18 additions & 0 deletions activerecord/test/cases/migration/compatibility_test.rb
Expand Up @@ -282,6 +282,24 @@ def migrate(x)
connection.drop_table :tests, if_exists: true
end

def test_create_table_allows_duplicate_column_names
migration = Class.new(ActiveRecord::Migration[5.2]) {
def migrate(x)
create_table :tests do |t|
t.integer :some_id
t.string :some_id
end
end
}.new

ActiveRecord::Migrator.new(:up, [migration], @schema_migration, @internal_metadata).migrate

column = connection.columns(:tests).find { |column| column.name == "some_id" }
assert_equal :string, column.type
ensure
connection.drop_table :tests, if_exists: true
end

if current_adapter?(:PostgreSQLAdapter)
class Testing < ActiveRecord::Base
end
Expand Down

0 comments on commit 325dd7b

Please sign in to comment.