Skip to content

Commit

Permalink
Fix collided sequence name detection
Browse files Browse the repository at this point in the history
If collided named sequence already exists, newly created serial column
will generate alternative sequence name. Fix sequence name detection to
allow the alternative names.
  • Loading branch information
kamipo committed Oct 15, 2017
1 parent 8b6e694 commit 976f9c3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
Expand Up @@ -8,8 +8,15 @@ class PostgreSQLColumn < Column #:nodoc:
def serial?
return unless default_function

%r{\Anextval\('"?#{table_name}_#{name}_seq"?'::regclass\)\z} === default_function
if %r{\Anextval\('"?(?<sequence_name>.+_(?<suffix>seq\d*))"?'::regclass\)\z} =~ default_function
sequence_name_from_parts(table_name, name, suffix) == sequence_name
end
end

private
def sequence_name_from_parts(table_name, column_name, suffix)
"#{table_name}_#{column_name}_#{suffix}"
end
end
end
end
36 changes: 36 additions & 0 deletions activerecord/test/cases/adapters/postgresql/serial_test.rb
Expand Up @@ -84,3 +84,39 @@ def test_schema_dump_with_not_bigserial
assert_match %r{t\.bigint\s+"serials_id",\s+default: -> \{ "nextval\('postgresql_big_serials_id_seq'::regclass\)" \}$}, output
end
end

module SequenceNameDetectionTestCases
class CollidedSequenceNameTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper

def setup
@connection = ActiveRecord::Base.connection
@connection.create_table :foo_bar, force: true do |t|
t.serial :baz_id
end
@connection.create_table :foo, force: true do |t|
t.serial :bar_id
t.bigserial :bar_baz_id
end
end

def teardown
@connection.drop_table :foo_bar, if_exists: true
@connection.drop_table :foo, if_exists: true
end

def test_serial_columns
columns = @connection.columns(:foo)
columns.each do |column|
assert_equal :integer, column.type
assert column.serial?
end
end

def test_schema_dump_with_collided_sequence_name
output = dump_table_schema "foo"
assert_match %r{t\.serial\s+"bar_id",\s+null: false$}, output
assert_match %r{t\.bigserial\s+"bar_baz_id",\s+null: false$}, output
end
end
end

0 comments on commit 976f9c3

Please sign in to comment.