Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
add uuid primary key support
  • Loading branch information
tenderlove committed Mar 23, 2013
1 parent d25e407 commit bc8ebef
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 3 deletions.
Expand Up @@ -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

This comment has been minimized.

Copy link
@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+.
Expand Down
Expand Up @@ -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?
Expand Down
Expand Up @@ -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 << '[]'
Expand Down
Expand Up @@ -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]
Expand Down
10 changes: 10 additions & 0 deletions activerecord/test/cases/adapters/postgresql/uuid_test.rb
Expand Up @@ -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
Expand Down

2 comments on commit bc8ebef

@natebird
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bravo @tenderlove. Bravo!

@jocubeit
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Excellent. Thanks @tenderlove!

Please sign in to comment.