Permalink
Browse files

add uuid primary key support

  • Loading branch information...
1 parent d25e407 commit bc8ebefe9825dbff2cffa29ff015a1e7a31f9812 @tenderlove tenderlove committed Mar 23, 2013
@@ -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
@nertzy

nertzy May 11, 2013

Contributor

This modifies the options hash! See #10572

+ 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

2 comments on commit bc8ebef

Bravo @tenderlove. Bravo!

Excellent. Thanks @tenderlove!

Please sign in to comment.