errors
– Package exceptions#
This module exposes objects to represent and examine database errors.
DB-API exceptions#
In compliance with the DB-API, all the exceptions raised by Psycopg derive from the following classes:
Exception
|__Warning
|__Error
|__InterfaceError
|__DatabaseError
|__DataError
|__OperationalError
|__IntegrityError
|__InternalError
|__ProgrammingError
|__NotSupportedError
These classes are exposed both by this module and the root psycopg
module.
- exception psycopg.Error(*args, info=None, encoding='utf-8')#
Base exception for all the errors psycopg will raise.
Exception that is the base class of all other error exceptions. You can use this to catch all errors with one single
except
statement.This exception is guaranteed to be picklable.
- diag#
A
Diagnostic
object to inspect details of the errors from the database.
-
sqlstate:
Optional
[str
] = None# The code of the error, if received from the server.
This attribute is also available as class attribute on the SQLSTATE exceptions classes.
- exception psycopg.Warning#
Exception raised for important warnings.
Defined for DBAPI compatibility, but never raised by
psycopg
.
- exception psycopg.InterfaceError(*args, info=None, encoding='utf-8')#
An error related to the database interface rather than the database itself.
- exception psycopg.DatabaseError(*args, info=None, encoding='utf-8')#
Exception raised for errors that are related to the database.
- exception psycopg.DataError(*args, info=None, encoding='utf-8')#
An error caused by problems with the processed data.
Examples may be division by zero, numeric value out of range, etc.
- exception psycopg.OperationalError(*args, info=None, encoding='utf-8')#
An error related to the database’s operation.
These errors are not necessarily under the control of the programmer, e.g. an unexpected disconnect occurs, the data source name is not found, a transaction could not be processed, a memory allocation error occurred during processing, etc.
- exception psycopg.IntegrityError(*args, info=None, encoding='utf-8')#
An error caused when the relational integrity of the database is affected.
An example may be a foreign key check failed.
- exception psycopg.InternalError(*args, info=None, encoding='utf-8')#
An error generated when the database encounters an internal error,
Examples could be the cursor is not valid anymore, the transaction is out of sync, etc.
- exception psycopg.ProgrammingError(*args, info=None, encoding='utf-8')#
Exception raised for programming errors
Examples may be table not found or already exists, syntax error in the SQL statement, wrong number of parameters specified, etc.
- exception psycopg.NotSupportedError(*args, info=None, encoding='utf-8')#
A method or database API was used which is not supported by the database,
Error diagnostics#
- class psycopg.errors.Diagnostic(info, encoding='utf-8')#
Details from a database error report.
The object is available as the ~psycopg.Error.~psycopg.Error.diag attribute and is passed to the callback functions registered with ~psycopg.Connection.add_notice_handler().
All the information available from the
PQresultErrorField()
function are exposed as attributes by the object. For instance the !severity attribute returns the !PG_DIAG_SEVERITY code. Please refer to the PostgreSQL documentation for the meaning of all the attributes.The attributes available are:
- column_name#
- constraint_name#
- context#
- datatype_name#
- internal_position#
- internal_query#
- message_detail#
- message_hint#
- message_primary#
- schema_name#
- severity#
- severity_nonlocalized#
- source_file#
- source_function#
- source_line#
- sqlstate#
- statement_position#
- table_name#
A string with the error field if available; !None if not available. The attribute value is available only for errors sent by the server: not all the fields are available for all the errors and for all the server versions.
SQLSTATE exceptions#
Errors coming from a database server (as opposite as ones generated client-side, such as connection failed) usually have a 5-letters error code called SQLSTATE (available in the ~Diagnostic.sqlstate attribute of the error’s ~psycopg.Error.diag attribute).
Psycopg exposes a different class for each SQLSTATE value, allowing to write idiomatic error handling code according to specific conditions happening in the database:
try:
cur.execute("LOCK TABLE mytable IN ACCESS EXCLUSIVE MODE NOWAIT")
except psycopg.errors.LockNotAvailable:
locked = True
The exception names are generated from the PostgreSQL source code and includes
classes for every error defined by PostgreSQL in versions between 9.6 and 14.
Every class in the module is named after what referred as “condition name” in
the documentation, converted to CamelCase: e.g. the error 22012,
division_by_zero
is exposed by this module as the class !DivisionByZero.
There is a handful of… exceptions to this rule, required for disambiguate
name clashes: please refer to the table below for all
the classes defined.
Every exception class is a subclass of one of the standard DB-API exception, thus exposing the ~psycopg.Error interface.
- psycopg.errors.lookup(sqlstate)#
Lookup an error code or constant name and return its exception class.
Raise !KeyError if the code is not found. :rtype:
Type
[Error
]Example: if you have code using constant names or sql codes you can use them to look up the exception class.
try: cur.execute("LOCK TABLE mytable IN ACCESS EXCLUSIVE MODE NOWAIT") except psycopg.errors.lookup("UNDEFINED_TABLE"): missing = True except psycopg.errors.lookup("55P03"): locked = True
List of known exceptions#
The following are all the SQLSTATE-related error classed defined by this module, together with the base DBAPI exception they derive from.
SQLSTATE |
Exception |
Base exception |
---|---|---|
Class 02 - No Data (this is also a warning class per the SQL standard) |
||
|
!NoData |
!DatabaseError |
|
!NoAdditionalDynamicResultSetsReturned |
!DatabaseError |
Class 03 - SQL Statement Not Yet Complete |
||
|
!SqlStatementNotYetComplete |
!DatabaseError |
Class 08 - Connection Exception |
||
|
!ConnectionException |
!OperationalError |
|
!SqlclientUnableToEstablishSqlconnection |
!OperationalError |
|
!ConnectionDoesNotExist |
!OperationalError |
|
!SqlserverRejectedEstablishmentOfSqlconnection |
!OperationalError |
|
!ConnectionFailure |
!OperationalError |
|
!TransactionResolutionUnknown |
!OperationalError |
|
!ProtocolViolation |
!OperationalError |
Class 09 - Triggered Action Exception |
||
|
!TriggeredActionException |
!DatabaseError |
Class 0A - Feature Not Supported |
||
|
!FeatureNotSupported |
!NotSupportedError |
Class 0B - Invalid Transaction Initiation |
||
|
!InvalidTransactionInitiation |
!DatabaseError |
Class 0F - Locator Exception |
||
|
!LocatorException |
!DatabaseError |
|
!InvalidLocatorSpecification |
!DatabaseError |
Class 0L - Invalid Grantor |
||
|
!InvalidGrantor |
!DatabaseError |
|
!InvalidGrantOperation |
!DatabaseError |
Class 0P - Invalid Role Specification |
||
|
!InvalidRoleSpecification |
!DatabaseError |
Class 0Z - Diagnostics Exception |
||
|
!DiagnosticsException |
!DatabaseError |
|
!StackedDiagnosticsAccessedWithoutActiveHandler |
!DatabaseError |
Class 20 - Case Not Found |
||
|
!CaseNotFound |
!ProgrammingError |
Class 21 - Cardinality Violation |
||
|
!CardinalityViolation |
!ProgrammingError |
Class 22 - Data Exception |
||
|
!DataException |
!DataError |
|
!StringDataRightTruncation |
!DataError |
|
!NullValueNoIndicatorParameter |
!DataError |
|
!NumericValueOutOfRange |
!DataError |
|
!NullValueNotAllowed |
!DataError |
|
!ErrorInAssignment |
!DataError |
|
!InvalidDatetimeFormat |
!DataError |
|
!DatetimeFieldOverflow |
!DataError |
|
!InvalidTimeZoneDisplacementValue |
!DataError |
|
!EscapeCharacterConflict |
!DataError |
|
!InvalidUseOfEscapeCharacter |
!DataError |
|
!InvalidEscapeOctet |
!DataError |
|
!ZeroLengthCharacterString |
!DataError |
|
!MostSpecificTypeMismatch |
!DataError |
|
!SequenceGeneratorLimitExceeded |
!DataError |
|
!NotAnXmlDocument |
!DataError |
|
!InvalidXmlDocument |
!DataError |
|
!InvalidXmlContent |
!DataError |
|
!InvalidXmlComment |
!DataError |
|
!InvalidXmlProcessingInstruction |
!DataError |
|
!InvalidIndicatorParameterValue |
!DataError |
|
!SubstringError |
!DataError |
|
!DivisionByZero |
!DataError |
|
!InvalidPrecedingOrFollowingSize |
!DataError |
|
!InvalidArgumentForNtileFunction |
!DataError |
|
!IntervalFieldOverflow |
!DataError |
|
!InvalidArgumentForNthValueFunction |
!DataError |
|
!InvalidCharacterValueForCast |
!DataError |
|
!InvalidEscapeCharacter |
!DataError |
|
!InvalidRegularExpression |
!DataError |
|
!InvalidArgumentForLogarithm |
!DataError |
|
!InvalidArgumentForPowerFunction |
!DataError |
|
!InvalidArgumentForWidthBucketFunction |
!DataError |
|
!InvalidRowCountInLimitClause |
!DataError |
|
!InvalidRowCountInResultOffsetClause |
!DataError |
|
!CharacterNotInRepertoire |
!DataError |
|
!IndicatorOverflow |
!DataError |
|
!InvalidParameterValue |
!DataError |
|
!UnterminatedCString |
!DataError |
|
!InvalidEscapeSequence |
!DataError |
|
!StringDataLengthMismatch |
!DataError |
|
!TrimError |
!DataError |
|
!ArraySubscriptError |
!DataError |
|
!InvalidTablesampleRepeat |
!DataError |
|
!InvalidTablesampleArgument |
!DataError |
|
!DuplicateJsonObjectKeyValue |
!DataError |
|
!InvalidArgumentForSqlJsonDatetimeFunction |
!DataError |
|
!InvalidJsonText |
!DataError |
|
!InvalidSqlJsonSubscript |
!DataError |
|
!MoreThanOneSqlJsonItem |
!DataError |
|
!NoSqlJsonItem |
!DataError |
|
!NonNumericSqlJsonItem |
!DataError |
|
!NonUniqueKeysInAJsonObject |
!DataError |
|
!SingletonSqlJsonItemRequired |
!DataError |
|
!SqlJsonArrayNotFound |
!DataError |
|
!SqlJsonMemberNotFound |
!DataError |
|
!SqlJsonNumberNotFound |
!DataError |
|
!SqlJsonObjectNotFound |
!DataError |
|
!TooManyJsonArrayElements |
!DataError |
|
!TooManyJsonObjectMembers |
!DataError |
|
!SqlJsonScalarRequired |
!DataError |
|
!FloatingPointException |
!DataError |
|
!InvalidTextRepresentation |
!DataError |
|
!InvalidBinaryRepresentation |
!DataError |
|
!BadCopyFileFormat |
!DataError |
|
!UntranslatableCharacter |
!DataError |
|
!NonstandardUseOfEscapeCharacter |
!DataError |
Class 23 - Integrity Constraint Violation |
||
|
!IntegrityConstraintViolation |
!IntegrityError |
|
!RestrictViolation |
!IntegrityError |
|
!NotNullViolation |
!IntegrityError |
|
!ForeignKeyViolation |
!IntegrityError |
|
!UniqueViolation |
!IntegrityError |
|
!CheckViolation |
!IntegrityError |
|
!ExclusionViolation |
!IntegrityError |
Class 24 - Invalid Cursor State |
||
|
!InvalidCursorState |
!InternalError |
Class 25 - Invalid Transaction State |
||
|
!InvalidTransactionState |
!InternalError |
|
!ActiveSqlTransaction |
!InternalError |
|
!BranchTransactionAlreadyActive |
!InternalError |
|
!InappropriateAccessModeForBranchTransaction |
!InternalError |
|
!InappropriateIsolationLevelForBranchTransaction |
!InternalError |
|
!NoActiveSqlTransactionForBranchTransaction |
!InternalError |
|
!ReadOnlySqlTransaction |
!InternalError |
|
!SchemaAndDataStatementMixingNotSupported |
!InternalError |
|
!HeldCursorRequiresSameIsolationLevel |
!InternalError |
|
!NoActiveSqlTransaction |
!InternalError |
|
!InFailedSqlTransaction |
!InternalError |
|
!IdleInTransactionSessionTimeout |
!InternalError |
Class 26 - Invalid SQL Statement Name |
||
|
!InvalidSqlStatementName |
!ProgrammingError |
Class 27 - Triggered Data Change Violation |
||
|
!TriggeredDataChangeViolation |
!OperationalError |
Class 28 - Invalid Authorization Specification |
||
|
!InvalidAuthorizationSpecification |
!OperationalError |
|
!InvalidPassword |
!OperationalError |
Class 2B - Dependent Privilege Descriptors Still Exist |
||
|
!DependentPrivilegeDescriptorsStillExist |
!InternalError |
|
!DependentObjectsStillExist |
!InternalError |
Class 2D - Invalid Transaction Termination |
||
|
!InvalidTransactionTermination |
!InternalError |
Class 2F - SQL Routine Exception |
||
|
!SqlRoutineException |
!OperationalError |
|
!ModifyingSqlDataNotPermitted |
!OperationalError |
|
!ProhibitedSqlStatementAttempted |
!OperationalError |
|
!ReadingSqlDataNotPermitted |
!OperationalError |
|
!FunctionExecutedNoReturnStatement |
!OperationalError |
Class 34 - Invalid Cursor Name |
||
|
!InvalidCursorName |
!ProgrammingError |
Class 38 - External Routine Exception |
||
|
!ExternalRoutineException |
!OperationalError |
|
!ContainingSqlNotPermitted |
!OperationalError |
|
!ModifyingSqlDataNotPermittedExt |
!OperationalError |
|
!ProhibitedSqlStatementAttemptedExt |
!OperationalError |
|
!ReadingSqlDataNotPermittedExt |
!OperationalError |
Class 39 - External Routine Invocation Exception |
||
|
!ExternalRoutineInvocationException |
!OperationalError |
|
!InvalidSqlstateReturned |
!OperationalError |
|
!NullValueNotAllowedExt |
!OperationalError |
|
!TriggerProtocolViolated |
!OperationalError |
|
!SrfProtocolViolated |
!OperationalError |
|
!EventTriggerProtocolViolated |
!OperationalError |
Class 3B - Savepoint Exception |
||
|
!SavepointException |
!OperationalError |
|
!InvalidSavepointSpecification |
!OperationalError |
Class 3D - Invalid Catalog Name |
||
|
!InvalidCatalogName |
!ProgrammingError |
Class 3F - Invalid Schema Name |
||
|
!InvalidSchemaName |
!ProgrammingError |
Class 40 - Transaction Rollback |
||
|
!TransactionRollback |
!OperationalError |
|
!SerializationFailure |
!OperationalError |
|
!TransactionIntegrityConstraintViolation |
!OperationalError |
|
!StatementCompletionUnknown |
!OperationalError |
|
!DeadlockDetected |
!OperationalError |
Class 42 - Syntax Error or Access Rule Violation |
||
|
!SyntaxErrorOrAccessRuleViolation |
!ProgrammingError |
|
!InsufficientPrivilege |
!ProgrammingError |
|
!SyntaxError |
!ProgrammingError |
|
!InvalidName |
!ProgrammingError |
|
!InvalidColumnDefinition |
!ProgrammingError |
|
!NameTooLong |
!ProgrammingError |
|
!DuplicateColumn |
!ProgrammingError |
|
!AmbiguousColumn |
!ProgrammingError |
|
!UndefinedColumn |
!ProgrammingError |
|
!UndefinedObject |
!ProgrammingError |
|
!DuplicateObject |
!ProgrammingError |
|
!DuplicateAlias |
!ProgrammingError |
|
!DuplicateFunction |
!ProgrammingError |
|
!AmbiguousFunction |
!ProgrammingError |
|
!GroupingError |
!ProgrammingError |
|
!DatatypeMismatch |
!ProgrammingError |
|
!WrongObjectType |
!ProgrammingError |
|
!InvalidForeignKey |
!ProgrammingError |
|
!CannotCoerce |
!ProgrammingError |
|
!UndefinedFunction |
!ProgrammingError |
|
!GeneratedAlways |
!ProgrammingError |
|
!ReservedName |
!ProgrammingError |
|
!UndefinedTable |
!ProgrammingError |
|
!UndefinedParameter |
!ProgrammingError |
|
!DuplicateCursor |
!ProgrammingError |
|
!DuplicateDatabase |
!ProgrammingError |
|
!DuplicatePreparedStatement |
!ProgrammingError |
|
!DuplicateSchema |
!ProgrammingError |
|
!DuplicateTable |
!ProgrammingError |
|
!AmbiguousParameter |
!ProgrammingError |
|
!AmbiguousAlias |
!ProgrammingError |
|
!InvalidColumnReference |
!ProgrammingError |
|
!InvalidCursorDefinition |
!ProgrammingError |
|
!InvalidDatabaseDefinition |
!ProgrammingError |
|
!InvalidFunctionDefinition |
!ProgrammingError |
|
!InvalidPreparedStatementDefinition |
!ProgrammingError |
|
!InvalidSchemaDefinition |
!ProgrammingError |
|
!InvalidTableDefinition |
!ProgrammingError |
|
!InvalidObjectDefinition |
!ProgrammingError |
|
!IndeterminateDatatype |
!ProgrammingError |
|
!InvalidRecursion |
!ProgrammingError |
|
!WindowingError |
!ProgrammingError |
|
!CollationMismatch |
!ProgrammingError |
|
!IndeterminateCollation |
!ProgrammingError |
Class 44 - WITH CHECK OPTION Violation |
||
|
!WithCheckOptionViolation |
!ProgrammingError |
Class 53 - Insufficient Resources |
||
|
!InsufficientResources |
!OperationalError |
|
!DiskFull |
!OperationalError |
|
!OutOfMemory |
!OperationalError |
|
!TooManyConnections |
!OperationalError |
|
!ConfigurationLimitExceeded |
!OperationalError |
Class 54 - Program Limit Exceeded |
||
|
!ProgramLimitExceeded |
!OperationalError |
|
!StatementTooComplex |
!OperationalError |
|
!TooManyColumns |
!OperationalError |
|
!TooManyArguments |
!OperationalError |
Class 55 - Object Not In Prerequisite State |
||
|
!ObjectNotInPrerequisiteState |
!OperationalError |
|
!ObjectInUse |
!OperationalError |
|
!CantChangeRuntimeParam |
!OperationalError |
|
!LockNotAvailable |
!OperationalError |
|
!UnsafeNewEnumValueUsage |
!OperationalError |
Class 57 - Operator Intervention |
||
|
!OperatorIntervention |
!OperationalError |
|
!QueryCanceled |
!OperationalError |
|
!AdminShutdown |
!OperationalError |
|
!CrashShutdown |
!OperationalError |
|
!CannotConnectNow |
!OperationalError |
|
!DatabaseDropped |
!OperationalError |
|
!IdleSessionTimeout |
!OperationalError |
Class 58 - System Error (errors external to PostgreSQL itself) |
||
|
!SystemError |
!OperationalError |
|
!IoError |
!OperationalError |
|
!UndefinedFile |
!OperationalError |
|
!DuplicateFile |
!OperationalError |
Class 72 - Snapshot Failure |
||
|
!SnapshotTooOld |
!DatabaseError |
Class F0 - Configuration File Error |
||
|
!ConfigFileError |
!OperationalError |
|
!LockFileExists |
!OperationalError |
Class HV - Foreign Data Wrapper Error (SQL/MED) |
||
|
!FdwError |
!OperationalError |
|
!FdwOutOfMemory |
!OperationalError |
|
!FdwDynamicParameterValueNeeded |
!OperationalError |
|
!FdwInvalidDataType |
!OperationalError |
|
!FdwColumnNameNotFound |
!OperationalError |
|
!FdwInvalidDataTypeDescriptors |
!OperationalError |
|
!FdwInvalidColumnName |
!OperationalError |
|
!FdwInvalidColumnNumber |
!OperationalError |
|
!FdwInvalidUseOfNullPointer |
!OperationalError |
|
!FdwInvalidStringFormat |
!OperationalError |
|
!FdwInvalidHandle |
!OperationalError |
|
!FdwInvalidOptionIndex |
!OperationalError |
|
!FdwInvalidOptionName |
!OperationalError |
|
!FdwOptionNameNotFound |
!OperationalError |
|
!FdwReplyHandle |
!OperationalError |
|
!FdwUnableToCreateExecution |
!OperationalError |
|
!FdwUnableToCreateReply |
!OperationalError |
|
!FdwUnableToEstablishConnection |
!OperationalError |
|
!FdwNoSchemas |
!OperationalError |
|
!FdwSchemaNotFound |
!OperationalError |
|
!FdwTableNotFound |
!OperationalError |
|
!FdwFunctionSequenceError |
!OperationalError |
|
!FdwTooManyHandles |
!OperationalError |
|
!FdwInconsistentDescriptorInformation |
!OperationalError |
|
!FdwInvalidAttributeValue |
!OperationalError |
|
!FdwInvalidStringLengthOrBufferLength |
!OperationalError |
|
!FdwInvalidDescriptorFieldIdentifier |
!OperationalError |
Class P0 - PL/pgSQL Error |
||
|
!PlpgsqlError |
!ProgrammingError |
|
!RaiseException |
!ProgrammingError |
|
!NoDataFound |
!ProgrammingError |
|
!TooManyRows |
!ProgrammingError |
|
!AssertFailure |
!ProgrammingError |
Class XX - Internal Error |
||
|
!InternalError_ |
!InternalError |
|
!DataCorrupted |
!InternalError |
|
!IndexCorrupted |
!InternalError |