Skip to content

Commit

Permalink
Translate foreign key violations to ActiveRecord::InvalidForeignKey e…
Browse files Browse the repository at this point in the history
…xceptions.

Signed-off-by: Michael Koziarski <michael@koziarski.com>
  • Loading branch information
mschuerig authored and NZKoz committed Jun 26, 2009
1 parent 53a3eaa commit 00a5fd3
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions activerecord/lib/active_record/base.rb
Expand Up @@ -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.
#
Expand Down
Expand Up @@ -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
Expand Down
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/cases/adapter_test.rb
Expand Up @@ -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.