提交 bc8ebefe 编写于 作者: A Aaron Patterson

add uuid primary key support

上级 d25e4076
......@@ -64,8 +64,9 @@ def columns; @columns_hash.values; end
# Appends a primary key definition to the table definition.
# Can be called multiple times, but this is probably not a good idea.
def primary_key(name)
column(name, :primary_key, primary_key: true)
def primary_key(name, type = :primary_key, options = {})
options[:primary_key] = true
column(name, type, options)
end
# Returns a ColumnDefinition for the column with name +name+.
......
......@@ -178,7 +178,7 @@ def create_table(table_name, options = {})
Base.get_primary_key table_name.to_s.singularize
}
td.primary_key pk
td.primary_key pk, options.fetch(:id, :primary_key), options
end
yield td if block_given?
......
......@@ -10,6 +10,15 @@ def visit_AddColumn(o)
add_column_options!(sql, column_options(o))
end
def visit_ColumnDefinition(o)
sql = super
if o.primary_key? && o.type == :uuid
sql << " PRIMARY KEY "
add_column_options!(sql, column_options(o))
end
sql
end
def add_column_options!(sql, options)
if options[:array] || options[:column].try(:array)
sql << '[]'
......
......@@ -330,6 +330,13 @@ def json(name, options = {})
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
include ColumnMethods
def primary_key(name, type = :primary_key, options = {})
return super unless type == :uuid
options[:default] ||= 'uuid_generate_v4()'
options[:primary_key] = true
column name, type, options
end
def column(name, type = nil, options = {})
super
column = self[name]
......
......@@ -35,6 +35,16 @@ def teardown
@connection.execute 'drop table if exists pg_uuids'
end
def test_id_is_uuid
assert_equal :uuid, UUID.columns_hash['id'].type
assert UUID.primary_key
end
def test_id_has_a_default
u = UUID.create
assert_not_nil u.id
end
def test_auto_create_uuid
u = UUID.create
u.reload
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册