aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authoryui-knk <spiketeika@gmail.com>2016-01-30 16:47:51 +0900
committeryui-knk <spiketeika@gmail.com>2016-01-30 16:47:51 +0900
commit444c4d05fea817fcad991e79fa128b640e2e4ff1 (patch)
tree442c6ef8de128d9828637249d613e1ada0203868
parent6162c49e40582bf058a6bb82ccc0cfb8f92332b6 (diff)
downloadrails-444c4d05fea817fcad991e79fa128b640e2e4ff1.tar.gz
rails-444c4d05fea817fcad991e79fa128b640e2e4ff1.tar.bz2
rails-444c4d05fea817fcad991e79fa128b640e2e4ff1.zip
Warn if `AR.primary_key` is called for a table who has composite primary key
If `AR.primary_key` is called for a table who has composite primary key, the method returns `nil`. This behavior sometimes generates invalid SQL. The first time developers notice to invalid SQL is when they execute SQL. This commit enables developers to know they are doing something dangerous as soon as possible.
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb6
-rw-r--r--activerecord/test/cases/primary_keys_test.rb7
2 files changed, 13 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index c7aff63228..3b4ceb915e 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -122,6 +122,12 @@ module ActiveRecord
# Returns just a table's primary key
def primary_key(table_name)
pks = primary_keys(table_name)
+ warn <<-WARNING.strip_heredoc if pks.count > 1
+ WARNING: Rails does not support composite primary key.
+
+ #{table_name} has composite primary key. Composite primary key is ignored.
+ WARNING
+
pks.first if pks.one?
end
diff --git a/activerecord/test/cases/primary_keys_test.rb b/activerecord/test/cases/primary_keys_test.rb
index 7e18313c00..360efd0b2b 100644
--- a/activerecord/test/cases/primary_keys_test.rb
+++ b/activerecord/test/cases/primary_keys_test.rb
@@ -262,6 +262,13 @@ class CompositePrimaryKeyTest < ActiveRecord::TestCase
assert_equal ["region", "code"], @connection.primary_keys("barcodes")
end
+ def test_primary_key_issues_warning
+ warning = capture(:stderr) do
+ @connection.primary_key("barcodes")
+ end
+ assert_match(/WARNING: Rails does not support composite primary key\./, warning)
+ end
+
def test_collectly_dump_composite_primary_key
schema = dump_table_schema "barcodes"
assert_match %r{create_table "barcodes", primary_key: \["region", "code"\]}, schema