Browse files

Translate foreign key violations to ActiveRecord::InvalidForeignKey e…

…xceptions.

Signed-off-by: Michael Koziarski <michael@koziarski.com>
  • Loading branch information...
1 parent 53a3eaa commit 00a5fd3d18ac908af688c5944922cf69c56e850b @mschuerig mschuerig committed with NZKoz Apr 4, 2009
View
4 activerecord/lib/active_record/base.rb
@@ -71,6 +71,10 @@ class StatementInvalid < ActiveRecordError
class RecordNotUnique < StatementInvalid
end
+ # Raised when a record cannot be inserted or updated because it references a non-existent record.
+ class InvalidForeignKey < StatementInvalid
+ end
+
# Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
# does not match number of expected variables.
#
View
2 activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -569,6 +569,8 @@ def translate_exception(exception, message)
case exception.errno
when 1062
RecordNotUnique.new(message)
+ when 1452
+ InvalidForeignKey.new(message)
else
super
end
View
2 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -945,6 +945,8 @@ def translate_exception(exception, message)
case exception.message
when /duplicate key value violates unique constraint/
RecordNotUnique.new(message)
+ when /violates foreign key constraint/
+ InvalidForeignKey.new(message)
else
super
end
View
8 activerecord/test/cases/adapter_test.rb
@@ -137,4 +137,12 @@ def test_uniqueness_violations_are_translated_to_specific_exception
@connection.execute "INSERT INTO subscribers(nick) VALUES('me')"
end
end
+
+ def test_foreign_key_violations_are_translated_to_specific_exception
+ unless @connection.adapter_name == 'SQLite'
+ assert_raises(ActiveRecord::InvalidForeignKey) do
+ @connection.execute "INSERT INTO fk_test_has_fk (fk_id) VALUES (0)"
+ end
+ end
+ end
end

0 comments on commit 00a5fd3

Please sign in to comment.