Last active
December 19, 2015 13:09
-
-
Save edwinv/5960407 to your computer and use it in GitHub Desktop.
PostgreSQL exception library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_record/connection_adapters/postgresql_adapter' | |
module ActiveRecord | |
class NotNullViolation < ActiveRecord::WrappedDatabaseException | |
end | |
class CheckViolation < ActiveRecord::WrappedDatabaseException | |
end | |
module ConnectionAdapters | |
class PostgreSQLAdapter < AbstractAdapter | |
def translate_exception(exception, message) | |
raise exception unless exception.respond_to?(:result) | |
case exception.result.try(:error_field, PGresult::PG_DIAG_SQLSTATE) | |
when UNIQUE_VIOLATION | |
RecordNotUnique.new(message, exception) | |
when FOREIGN_KEY_VIOLATION | |
InvalidForeignKey.new(message, exception) | |
# Custom error codes based on PostgreSQL documentation: | |
# http://www.postgresql.org/docs/9.2/static/errcodes-appendix.html | |
when '23502' | |
NotNullViolation.new(message, exception) | |
when '23514' | |
CheckViolation.new(message, exception) | |
else | |
super | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment