1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activerecord/test/cases/primary_keys_test.rb

366 lines
11 KiB
Ruby
Raw Normal View History

require "cases/helper"
require 'support/schema_dumping_helper'
require 'models/topic'
require 'models/reply'
require 'models/subscriber'
require 'models/movie'
require 'models/keyboard'
require 'models/mixed_case_monkey'
require 'models/dashboard'
class PrimaryKeysTest < ActiveRecord::TestCase
fixtures :topics, :subscribers, :movies, :mixed_case_monkeys
AMo #key is now #to_key and CI is probably happy Obviously #key is a too common name to be included in the AMo interface, #to_key fits better and also relates nicely to #to_param. Thx wycats, koz and josevalim for the suggestion. AR's #to_key implementation now takes customized primary keys into account and there's a testcase for that too. The #to_param AMo lint makes no assumptions on how the method behaves in the presence of composite primary keys. It leaves the decision wether to provide a default, or to raise and thus signal to the user that implementing this method will need his special attention, up to the implementers. All AMo cares about is that #to_param is implemented and returns nil in case of a new_record?. The default CompliantObject used in lint_test provides a naive default implementation that just joins all key attributes with '-'. The #to_key default implementation in lint_test's CompliantObject now returns [id] instead of [1]. This was previously causing the (wrong) tests I added for AR's #to_key implementation to pass. The #to_key tests added with this patch should be better. The CI failure was caused by my lack of knowledge about the test:isolated task. The tests for the record_identifier code in action_controller are using fake non AR models and I forgot to stub the #to_key method over there. This issue didn't come up when running the test task, only test:isolated revealed it. This patch fixes that. All tests pass isolated or not, well, apart from one previously unpended test in action_controller that is unrelated to my patch.
2010-02-20 21:05:28 -05:00
def test_to_key_with_default_primary_key
Adds #key and #to_param to the AMo interface This commit introduces two new methods that every AMo compliant object must implement. Below are the default implementations along with the implied interface contract. # Returns an Enumerable of all (primary) key # attributes or nil if new_record? is true def key new_record? ? nil : [1] end # Returns a string representing the object's key # suitable for use in URLs, or nil if new_record? # is true def to_param key ? key.first.to_s : nil end 1) The #key method Previously rails' record_identifier code, which is used in the #dom_id helper, relied on calling #id on the record to provide a reasonable DOM id. Now with rails3 being all ORM agnostic, it's not safe anymore to assume that every record ever will have an #id as its primary key attribute. Having a #key method available on every AMo object means that #dom_id can be implemented using record.to_model.key # instead of record.id Using this we're able to take composite primary keys into account (e.g. available in datamapper) by implementing #dom_id using a newly added record_key_for_dom_id(record) method. The user can overwrite this method to provide customized versions of the object's key used in #dom_id. Also, dealing with more complex keys that can contain arbitrary strings, means that we need to make sure that we only provide DOM ids that are valid according to the spec. For this reason, this patch sends the key provided through a newly added sanitize_dom_id(candidate_id) method, that makes sure we only produce valid HTML The reason to not just add #dom_id to the AMo interface was that it feels like providing a DOM id should not be a model concern. Adding #dom_id to the AMo interface would force these concern on the model, while it's better left to be implemented in a helper. Now one could say the same is true for #to_param, and actually I think that it doesn't really fit into the model either, but it's used in AR and it's a main part of integrating into the rails router. This is different from #dom_id which is only used in view helpers and can be implemented on top of a semantically more meaningful method like #key. 2) The #to_param method Since the rails router relies on #to_param to be present, AR::Base implements it and returns the id by default, allowing the user to overwrite the method if desired. Now with different ORMs integrating into rails, every ORM railtie needs to implement it's own #to_param implementation while already providing code to be AMo compliant. Since the whole point of AMo compliance seems to be to integrate any ORM seamlessly into rails, it seems fair that all we really need to do as another ORM, is to be AMo compliant. By including #to_param into the official interface, we can make sure that this code can be centralized in the various AMo compliance layers, and not be added separately by every ORM railtie. 3) All specs pass
2010-02-20 02:24:10 -05:00
topic = Topic.new
assert_nil topic.to_key
Adds #key and #to_param to the AMo interface This commit introduces two new methods that every AMo compliant object must implement. Below are the default implementations along with the implied interface contract. # Returns an Enumerable of all (primary) key # attributes or nil if new_record? is true def key new_record? ? nil : [1] end # Returns a string representing the object's key # suitable for use in URLs, or nil if new_record? # is true def to_param key ? key.first.to_s : nil end 1) The #key method Previously rails' record_identifier code, which is used in the #dom_id helper, relied on calling #id on the record to provide a reasonable DOM id. Now with rails3 being all ORM agnostic, it's not safe anymore to assume that every record ever will have an #id as its primary key attribute. Having a #key method available on every AMo object means that #dom_id can be implemented using record.to_model.key # instead of record.id Using this we're able to take composite primary keys into account (e.g. available in datamapper) by implementing #dom_id using a newly added record_key_for_dom_id(record) method. The user can overwrite this method to provide customized versions of the object's key used in #dom_id. Also, dealing with more complex keys that can contain arbitrary strings, means that we need to make sure that we only provide DOM ids that are valid according to the spec. For this reason, this patch sends the key provided through a newly added sanitize_dom_id(candidate_id) method, that makes sure we only produce valid HTML The reason to not just add #dom_id to the AMo interface was that it feels like providing a DOM id should not be a model concern. Adding #dom_id to the AMo interface would force these concern on the model, while it's better left to be implemented in a helper. Now one could say the same is true for #to_param, and actually I think that it doesn't really fit into the model either, but it's used in AR and it's a main part of integrating into the rails router. This is different from #dom_id which is only used in view helpers and can be implemented on top of a semantically more meaningful method like #key. 2) The #to_param method Since the rails router relies on #to_param to be present, AR::Base implements it and returns the id by default, allowing the user to overwrite the method if desired. Now with different ORMs integrating into rails, every ORM railtie needs to implement it's own #to_param implementation while already providing code to be AMo compliant. Since the whole point of AMo compliance seems to be to integrate any ORM seamlessly into rails, it seems fair that all we really need to do as another ORM, is to be AMo compliant. By including #to_param into the official interface, we can make sure that this code can be centralized in the various AMo compliance layers, and not be added separately by every ORM railtie. 3) All specs pass
2010-02-20 02:24:10 -05:00
topic = Topic.find(1)
assert_equal [1], topic.to_key
AMo #key is now #to_key and CI is probably happy Obviously #key is a too common name to be included in the AMo interface, #to_key fits better and also relates nicely to #to_param. Thx wycats, koz and josevalim for the suggestion. AR's #to_key implementation now takes customized primary keys into account and there's a testcase for that too. The #to_param AMo lint makes no assumptions on how the method behaves in the presence of composite primary keys. It leaves the decision wether to provide a default, or to raise and thus signal to the user that implementing this method will need his special attention, up to the implementers. All AMo cares about is that #to_param is implemented and returns nil in case of a new_record?. The default CompliantObject used in lint_test provides a naive default implementation that just joins all key attributes with '-'. The #to_key default implementation in lint_test's CompliantObject now returns [id] instead of [1]. This was previously causing the (wrong) tests I added for AR's #to_key implementation to pass. The #to_key tests added with this patch should be better. The CI failure was caused by my lack of knowledge about the test:isolated task. The tests for the record_identifier code in action_controller are using fake non AR models and I forgot to stub the #to_key method over there. This issue didn't come up when running the test task, only test:isolated revealed it. This patch fixes that. All tests pass isolated or not, well, apart from one previously unpended test in action_controller that is unrelated to my patch.
2010-02-20 21:05:28 -05:00
end
def test_to_key_with_customized_primary_key
keyboard = Keyboard.new
assert_nil keyboard.to_key
AMo #key is now #to_key and CI is probably happy Obviously #key is a too common name to be included in the AMo interface, #to_key fits better and also relates nicely to #to_param. Thx wycats, koz and josevalim for the suggestion. AR's #to_key implementation now takes customized primary keys into account and there's a testcase for that too. The #to_param AMo lint makes no assumptions on how the method behaves in the presence of composite primary keys. It leaves the decision wether to provide a default, or to raise and thus signal to the user that implementing this method will need his special attention, up to the implementers. All AMo cares about is that #to_param is implemented and returns nil in case of a new_record?. The default CompliantObject used in lint_test provides a naive default implementation that just joins all key attributes with '-'. The #to_key default implementation in lint_test's CompliantObject now returns [id] instead of [1]. This was previously causing the (wrong) tests I added for AR's #to_key implementation to pass. The #to_key tests added with this patch should be better. The CI failure was caused by my lack of knowledge about the test:isolated task. The tests for the record_identifier code in action_controller are using fake non AR models and I forgot to stub the #to_key method over there. This issue didn't come up when running the test task, only test:isolated revealed it. This patch fixes that. All tests pass isolated or not, well, apart from one previously unpended test in action_controller that is unrelated to my patch.
2010-02-20 21:05:28 -05:00
keyboard.save
assert_equal keyboard.to_key, [keyboard.id]
Adds #key and #to_param to the AMo interface This commit introduces two new methods that every AMo compliant object must implement. Below are the default implementations along with the implied interface contract. # Returns an Enumerable of all (primary) key # attributes or nil if new_record? is true def key new_record? ? nil : [1] end # Returns a string representing the object's key # suitable for use in URLs, or nil if new_record? # is true def to_param key ? key.first.to_s : nil end 1) The #key method Previously rails' record_identifier code, which is used in the #dom_id helper, relied on calling #id on the record to provide a reasonable DOM id. Now with rails3 being all ORM agnostic, it's not safe anymore to assume that every record ever will have an #id as its primary key attribute. Having a #key method available on every AMo object means that #dom_id can be implemented using record.to_model.key # instead of record.id Using this we're able to take composite primary keys into account (e.g. available in datamapper) by implementing #dom_id using a newly added record_key_for_dom_id(record) method. The user can overwrite this method to provide customized versions of the object's key used in #dom_id. Also, dealing with more complex keys that can contain arbitrary strings, means that we need to make sure that we only provide DOM ids that are valid according to the spec. For this reason, this patch sends the key provided through a newly added sanitize_dom_id(candidate_id) method, that makes sure we only produce valid HTML The reason to not just add #dom_id to the AMo interface was that it feels like providing a DOM id should not be a model concern. Adding #dom_id to the AMo interface would force these concern on the model, while it's better left to be implemented in a helper. Now one could say the same is true for #to_param, and actually I think that it doesn't really fit into the model either, but it's used in AR and it's a main part of integrating into the rails router. This is different from #dom_id which is only used in view helpers and can be implemented on top of a semantically more meaningful method like #key. 2) The #to_param method Since the rails router relies on #to_param to be present, AR::Base implements it and returns the id by default, allowing the user to overwrite the method if desired. Now with different ORMs integrating into rails, every ORM railtie needs to implement it's own #to_param implementation while already providing code to be AMo compliant. Since the whole point of AMo compliance seems to be to integrate any ORM seamlessly into rails, it seems fair that all we really need to do as another ORM, is to be AMo compliant. By including #to_param into the official interface, we can make sure that this code can be centralized in the various AMo compliance layers, and not be added separately by every ORM railtie. 3) All specs pass
2010-02-20 02:24:10 -05:00
end
def test_read_attribute_with_custom_primary_key
keyboard = Keyboard.create!
assert_equal keyboard.key_number, keyboard.read_attribute(:id)
end
def test_to_key_with_primary_key_after_destroy
topic = Topic.find(1)
topic.destroy
assert_equal [1], topic.to_key
end
def test_integer_key
topic = Topic.find(1)
assert_equal(topics(:first).author_name, topic.author_name)
topic = Topic.find(2)
assert_equal(topics(:second).author_name, topic.author_name)
topic = Topic.new
topic.title = "New Topic"
assert_nil topic.id
assert_nothing_raised { topic.save! }
id = topic.id
topicReloaded = Topic.find(id)
assert_equal("New Topic", topicReloaded.title)
end
def test_customized_primary_key_auto_assigns_on_save
Keyboard.delete_all
keyboard = Keyboard.new(:name => 'HHKB')
assert_nothing_raised { keyboard.save! }
assert_equal keyboard.id, Keyboard.find_by_name('HHKB').id
end
def test_customized_primary_key_can_be_get_before_saving
keyboard = Keyboard.new
assert_nil keyboard.id
assert_nothing_raised { assert_nil keyboard.key_number }
end
def test_customized_string_primary_key_settable_before_save
subscriber = Subscriber.new
assert_nothing_raised { subscriber.id = 'webster123' }
assert_equal 'webster123', subscriber.id
assert_equal 'webster123', subscriber.nick
end
def test_string_key
subscriber = Subscriber.find(subscribers(:first).nick)
assert_equal(subscribers(:first).name, subscriber.name)
subscriber = Subscriber.find(subscribers(:second).nick)
assert_equal(subscribers(:second).name, subscriber.name)
subscriber = Subscriber.new
subscriber.id = "jdoe"
assert_equal("jdoe", subscriber.id)
subscriber.name = "John Doe"
assert_nothing_raised { subscriber.save! }
assert_equal("jdoe", subscriber.id)
subscriberReloaded = Subscriber.find("jdoe")
assert_equal("John Doe", subscriberReloaded.name)
end
def test_find_with_more_than_one_string_key
assert_equal 2, Subscriber.find(subscribers(:first).nick, subscribers(:second).nick).length
end
def test_primary_key_prefix
old_primary_key_prefix_type = ActiveRecord::Base.primary_key_prefix_type
ActiveRecord::Base.primary_key_prefix_type = :table_name
Topic.reset_primary_key
assert_equal "topicid", Topic.primary_key
ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore
Topic.reset_primary_key
assert_equal "topic_id", Topic.primary_key
ActiveRecord::Base.primary_key_prefix_type = nil
Topic.reset_primary_key
assert_equal "id", Topic.primary_key
ensure
ActiveRecord::Base.primary_key_prefix_type = old_primary_key_prefix_type
end
def test_delete_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.delete(1) }
end
def test_update_counters_should_quote_pkey_and_quote_counter_columns
assert_nothing_raised { MixedCaseMonkey.update_counters(1, :fleaCount => 99) }
end
def test_find_with_one_id_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.find(1) }
end
def test_find_with_multiple_ids_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.find([1,2]) }
end
def test_instance_update_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.find(1).save }
end
def test_instance_destroy_should_quote_pkey
assert_nothing_raised { MixedCaseMonkey.find(1).destroy }
end
def test_supports_primary_key
assert_nothing_raised NoMethodError do
ActiveRecord::Base.connection.supports_primary_key?
end
end
def test_primary_key_returns_value_if_it_exists
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'developers'
end
if ActiveRecord::Base.connection.supports_primary_key?
assert_equal 'id', klass.primary_key
end
end
def test_primary_key_returns_nil_if_it_does_not_exist
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'developers_projects'
end
if ActiveRecord::Base.connection.supports_primary_key?
assert_nil klass.primary_key
end
end
def test_quoted_primary_key_after_set_primary_key
k = Class.new( ActiveRecord::Base )
assert_equal k.connection.quote_column_name("id"), k.quoted_primary_key
k.primary_key = "foo"
assert_equal k.connection.quote_column_name("foo"), k.quoted_primary_key
end
2011-12-15 08:23:18 -05:00
def test_auto_detect_primary_key_from_schema
MixedCaseMonkey.reset_primary_key
assert_equal "monkeyID", MixedCaseMonkey.primary_key
end
def test_primary_key_update_with_custom_key_name
dashboard = Dashboard.create!(dashboard_id: '1')
dashboard.id = '2'
dashboard.save!
dashboard = Dashboard.first
assert_equal '2', dashboard.id
end
if current_adapter?(:PostgreSQLAdapter)
def test_serial_with_quoted_sequence_name
column = MixedCaseMonkey.columns_hash[MixedCaseMonkey.primary_key]
assert_equal "nextval('\"mixed_case_monkeys_monkeyID_seq\"'::regclass)", column.default_function
assert column.serial?
end
def test_serial_with_unquoted_sequence_name
column = Topic.columns_hash[Topic.primary_key]
assert_equal "nextval('topics_id_seq'::regclass)", column.default_function
assert column.serial?
end
end
end
class PrimaryKeyWithNoConnectionTest < ActiveRecord::TestCase
self.use_transactional_tests = false
unless in_memory_db?
def test_set_primary_key_with_no_connection
connection = ActiveRecord::Base.remove_connection
model = Class.new(ActiveRecord::Base)
model.primary_key = 'foo'
assert_equal 'foo', model.primary_key
ActiveRecord::Base.establish_connection(connection)
assert_equal 'foo', model.primary_key
end
end
end
2014-11-15 13:08:46 -05:00
class PrimaryKeyAnyTypeTest < ActiveRecord::TestCase
include SchemaDumpingHelper
self.use_transactional_tests = false
2014-11-15 13:08:46 -05:00
class Barcode < ActiveRecord::Base
end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table(:barcodes, primary_key: "code", id: :string, limit: 42, force: true)
end
teardown do
@connection.drop_table(:barcodes, if_exists: true)
2014-11-15 13:08:46 -05:00
end
def test_any_type_primary_key
assert_equal "code", Barcode.primary_key
column_type = Barcode.type_for_attribute(Barcode.primary_key)
assert_equal :string, column_type.type
assert_equal 42, column_type.limit
end
test "schema dump primary key includes type and options" do
schema = dump_table_schema "barcodes"
assert_match %r{create_table "barcodes", primary_key: "code", id: :string, limit: 42}, schema
end
2014-11-15 13:08:46 -05:00
end
class CompositePrimaryKeyTest < ActiveRecord::TestCase
include SchemaDumpingHelper
self.use_transactional_tests = false
def setup
@connection = ActiveRecord::Base.connection
@connection.create_table(:barcodes, primary_key: ["region", "code"], force: true) do |t|
t.string :region
t.integer :code
end
end
def teardown
@connection.drop_table(:barcodes, if_exists: true)
end
def test_composite_primary_key
assert_equal ["region", "code"], @connection.primary_keys("barcodes")
end
def test_collectly_dump_composite_primary_key
schema = dump_table_schema "barcodes"
assert_match %r{create_table "barcodes", primary_key: \["region", "code"\]}, schema
end
end
2015-12-15 17:01:30 -05:00
if current_adapter?(:Mysql2Adapter)
class PrimaryKeyWithAnsiQuotesTest < ActiveRecord::TestCase
self.use_transactional_tests = false
2013-05-12 05:33:14 -04:00
def test_primary_key_method_with_ansi_quotes
con = ActiveRecord::Base.connection
con.execute("SET SESSION sql_mode='ANSI_QUOTES'")
assert_equal "id", con.primary_key("topics")
ensure
con.reconnect!
end
end
class PrimaryKeyBigintNilDefaultTest < ActiveRecord::TestCase
include SchemaDumpingHelper
self.use_transactional_tests = false
def setup
@connection = ActiveRecord::Base.connection
@connection.create_table(:bigint_defaults, id: :bigint, default: nil, force: true)
end
def teardown
@connection.drop_table :bigint_defaults, if_exists: true
end
test "primary key with bigint allows default override via nil" do
column = @connection.columns(:bigint_defaults).find { |c| c.name == 'id' }
assert column.bigint?
assert_not column.auto_increment?
end
test "schema dump primary key with bigint default nil" do
schema = dump_table_schema "bigint_defaults"
assert_match %r{create_table "bigint_defaults", id: :bigint, default: nil}, schema
end
end
end
2015-12-15 17:01:30 -05:00
if current_adapter?(:PostgreSQLAdapter, :Mysql2Adapter)
class PrimaryKeyBigSerialTest < ActiveRecord::TestCase
include SchemaDumpingHelper
self.use_transactional_tests = false
class Widget < ActiveRecord::Base
end
setup do
@connection = ActiveRecord::Base.connection
if current_adapter?(:PostgreSQLAdapter)
@connection.create_table(:widgets, id: :bigserial, force: true)
else
@connection.create_table(:widgets, id: :bigint, force: true)
end
end
teardown do
use Model.reset_column_information to clear table cache connection wide. `widgets` table is being created in `primary_keys_test.rb` for PostgreSQLAdapter, MysqlAdapter, Mysql2Adapter and it makes test to fail earlier. Before: `bundle exec rake mysql2:test` ``` Finished in 127.287669s, 35.5258 runs/s, 97.8885 assertions/s. 1) Error: PersistenceTest::SaveTest#test_save_touch_false: ActiveModel::UnknownAttributeError: unknown attribute 'name' for #<Class:0x0000000a7d6ef0>. /home/kd/projects/kd-rails/activerecord/lib/active_record/attribute_assignment.rb:36:in `rescue in _assign_attribute' /home/kd/projects/kd-rails/activerecord/lib/active_record/attribute_assignment.rb:34:in `_assign_attribute' /home/kd/projects/kd-rails/activemodel/lib/active_model/attribute_assignment.rb:40:in `block in _assign_attributes' /home/kd/projects/kd-rails/activemodel/lib/active_model/attribute_assignment.rb:39:in `each' /home/kd/projects/kd-rails/activemodel/lib/active_model/attribute_assignment.rb:39:in `_assign_attributes' /home/kd/projects/kd-rails/activerecord/lib/active_record/attribute_assignment.rb:26:in `_assign_attributes' /home/kd/projects/kd-rails/activemodel/lib/active_model/attribute_assignment.rb:33:in `assign_attributes' /home/kd/projects/kd-rails/activerecord/lib/active_record/core.rb:293:in `initialize' /home/kd/projects/kd-rails/activerecord/lib/active_record/inheritance.rb:61:in `new' /home/kd/projects/kd-rails/activerecord/lib/active_record/inheritance.rb:61:in `new' /home/kd/projects/kd-rails/activerecord/lib/active_record/persistence.rb:50:in `create!' /home/kd/projects/kd-rails/activerecord/test/cases/persistence_test.rb:913:in `test_save_touch_false' 4522 runs, 12460 assertions, 0 failures, 1 errors, 4 skips ``` After: `bundle exec rake mysql2:test` ``` Finished in 135.785086s, 33.3026 runs/s, 91.7774 assertions/s. 4522 runs, 12462 assertions, 0 failures, 0 errors, 4 skips ```
2015-03-31 02:44:03 -04:00
@connection.drop_table :widgets, if_exists: true
Widget.reset_column_information
end
test "primary key column type with bigserial" do
column_type = Widget.type_for_attribute(Widget.primary_key)
assert_equal :integer, column_type.type
assert_equal 8, column_type.limit
end
test "primary key with bigserial are automatically numbered" do
widget = Widget.create!
assert_not_nil widget.id
end
test "schema dump primary key with bigserial" do
schema = dump_table_schema "widgets"
if current_adapter?(:PostgreSQLAdapter)
assert_match %r{create_table "widgets", id: :bigserial}, schema
else
assert_match %r{create_table "widgets", id: :bigint}, schema
end
end
2015-12-15 17:01:30 -05:00
if current_adapter?(:Mysql2Adapter)
test "primary key column type with options" do
@connection.create_table(:widgets, id: :primary_key, limit: 8, unsigned: true, force: true)
column = @connection.columns(:widgets).find { |c| c.name == 'id' }
assert column.auto_increment?
assert_equal :integer, column.type
assert_equal 8, column.limit
assert column.unsigned?
end
end
end
end