Translate foreign key violations to ActiveRecord::InvalidForeignKey exceptions.

Signed-off-by: Michael Koziarski <michael@koziarski.com>
This commit is contained in:
Michael Schuerig
2009-04-05 01:42:21 +02:00
committed by Michael Koziarski
parent 53a3eaa860
commit 00a5fd3d18
4 changed files with 16 additions and 0 deletions

View File

@@ -71,6 +71,10 @@ module ActiveRecord #:nodoc:
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 File

@@ -569,6 +569,8 @@ module ActiveRecord
case exception.errno
when 1062
RecordNotUnique.new(message)
when 1452
InvalidForeignKey.new(message)
else
super
end

View File

@@ -945,6 +945,8 @@ module ActiveRecord
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 File

@@ -137,4 +137,12 @@ class AdapterTest < ActiveRecord::TestCase
@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