errors – 异常包
该模块提供了用来表示和检查数据库错误的对象。
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
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.
pgconn: Optional[pq.PGconn]
The connection object, if the error was raised from a connection attempt.
It has been closed and will be in BAD
state; however it might be useful to verify precisely what went wrong, for instance checking the needs_password
and used_password
attributes. Attempting to operate this connection will raise an OperationalError
.
New in version 3.1.
pgresult: Optional[pq.PGresult]
The result object, if the exception was raised after a failed query.
New in version 3.1.
exception psycopg.Warning
Exception raised for important warnings.
Defined for DBAPI compatibility, but never raised by psycopg
.
exception psycopg.InterfaceError
An error related to the database interface rather than the database itself.
exception psycopg.DatabaseError
Exception raised for errors that are related to the database.
exception psycopg.DataError
An error caused by problems with the processed data.
Examples may be division by zero, numeric value out of range, etc.
exception psycopg.OperationalError
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
An error caused when the relational integrity of the database is affected.
An example may be a foreign key check failed.
exception psycopg.InternalError
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
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
A method or database API was used which is not supported by the database.
In addition to the standard DB-API errors, Psycopg defines a few more specific ones.
exception psycopg.errors.ConnectionTimeout
Exception raised on timeout of the connect()
method.
The error is raised if the connect_timeout
is specified and a connection is not obtained in useful time.
Subclass of OperationalError
.
exception psycopg.errors.PipelineAborted
Raised when a operation fails because the current pipeline is in aborted state.
Subclass of OperationalError
.
class psycopg.errors.Diagnostic
Details from a database error report.
The object is available as the Error
.diag
attribute and is passed to the callback functions registered with 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.
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 sqlstate
attribute of the error’s 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 15. 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 Error
interface.
Changed in version 3.1.4: Added exceptions introduced in PostgreSQL 15.
psycopg.errors.lookup(sqlstate: str) → Type[Error]
Lookup an error code or constant name and return its exception class.
Raise KeyError
if the code is not found.
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
以下是此模块分类和定义的所有与 SQLSTATE 相关的错误,以及它们派生自的基础 DBAPI 异常。
SQLSTATE | 异常 | 基础异常 |
---|---|---|
02 类 - 无数据(根据 SQL 标准,这也是一个警告类) | ||
02000 |
NoData |
DatabaseError |
02001 |
NoAdditionalDynamicResultSetsReturned |
DatabaseError |
03 类 - SQL 语句尚未完成 | ||
03000 |
SqlStatementNotYetComplete |
DatabaseError |
08 类 - 连接异常 | ||
08000 |
ConnectionException |
OperationalError |
08001 |
SqlclientUnableToEstablishSqlconnection |
OperationalError |
08003 |
ConnectionDoesNotExist |
OperationalError |
08004 |
SqlserverRejectedEstablishmentOfSqlconnection |
OperationalError |
08006 |
ConnectionFailure |
OperationalError |
08007 |
TransactionResolutionUnknown |
OperationalError |
08P01 |
ProtocolViolation |
OperationalError |
09 类 - 触发动作异常 | ||
09000 |
TriggeredActionException |
DatabaseError |
0A 类 - 不支持的功能 | ||
0A000 |
FeatureNotSupported |
NotSupportedError |
0B 类 - 无效事务发起 | ||
0B000 |
InvalidTransactionInitiation |
DatabaseError |
0F 类 - 定位器异常 | ||
0F000 |
LocatorException |
DatabaseError |
0F001 |
InvalidLocatorSpecification |
DatabaseError |
0L 类 - 无效授权者 | ||
0L000 |
InvalidGrantor |
DatabaseError |
0LP01 |
InvalidGrantOperation |
DatabaseError |
0P 类 - 无效的角色规范 | ||
0P000 |
InvalidRoleSpecification |
DatabaseError |
0Z 类 - 诊断异常 | ||
0Z000 |
DiagnosticsException |
DatabaseError |
0Z002 |
StackedDiagnosticsAccessedWithoutActiveHandler |
DatabaseError |
20 类 - CASE 分支找不到 | ||
20000 |
CaseNotFound |
ProgrammingError |
21 类 - 违反基数 | ||
21000 |
CardinalityViolation |
ProgrammingError |
22 类 - 数据异常 | ||
22000 |
DataException |
DataError |
22001 |
StringDataRightTruncation |
DataError |
22002 |
NullValueNoIndicatorParameter |
DataError |
22003 |
NumericValueOutOfRange |
DataError |
22004 |
NullValueNotAllowed |
DataError |
22005 |
ErrorInAssignment |
DataError |
22007 |
InvalidDatetimeFormat |
DataError |
22008 |
DatetimeFieldOverflow |
DataError |
22009 |
InvalidTimeZoneDisplacementValue |
DataError |
2200B |
EscapeCharacterConflict |
DataError |
2200C |
InvalidUseOfEscapeCharacter |
DataError |
2200D |
InvalidEscapeOctet |
DataError |
2200F |
ZeroLengthCharacterString |
DataError |
2200G |
MostSpecificTypeMismatch |
DataError |
2200H |
SequenceGeneratorLimitExceeded |
DataError |
2200L |
NotAnXmlDocument |
DataError |
2200M |
InvalidXmlDocument |
DataError |
2200N |
InvalidXmlContent |
DataError |
2200S |
InvalidXmlComment |
DataError |
2200T |
InvalidXmlProcessingInstruction |
DataError |
22010 |
InvalidIndicatorParameterValue |
DataError |
22011 |
SubstringError |
DataError |
22012 |
DivisionByZero |
DataError |
22013 |
InvalidPrecedingOrFollowingSize |
DataError |
22014 |
InvalidArgumentForNtileFunction |
DataError |
22015 |
IntervalFieldOverflow |
DataError |
22016 |
InvalidArgumentForNthValueFunction |
DataError |
22018 |
InvalidCharacterValueForCast |
DataError |
22019 |
InvalidEscapeCharacter |
DataError |
2201B |
InvalidRegularExpression |
DataError |
2201E |
InvalidArgumentForLogarithm |
DataError |
2201F |
InvalidArgumentForPowerFunction |
DataError |
2201G |
InvalidArgumentForWidthBucketFunction |
DataError |
2201W |
InvalidRowCountInLimitClause |
DataError |
2201X |
InvalidRowCountInResultOffsetClause |
DataError |
22021 |
CharacterNotInRepertoire |
DataError |
22022 |
IndicatorOverflow |
DataError |
22023 |
InvalidParameterValue |
DataError |
22024 |
UnterminatedCString |
DataError |
22025 |
InvalidEscapeSequence |
DataError |
22026 |
StringDataLengthMismatch |
DataError |
22027 |
TrimError |
DataError |
2202E |
ArraySubscriptError |
DataError |
2202G |
InvalidTablesampleRepeat |
DataError |
2202H |
InvalidTablesampleArgument |
DataError |
22030 |
DuplicateJsonObjectKeyValue |
DataError |
22031 |
InvalidArgumentForSqlJsonDatetimeFunction |
DataError |
22032 |
InvalidJsonText |
DataError |
22033 |
InvalidSqlJsonSubscript |
DataError |
22034 |
MoreThanOneSqlJsonItem |
DataError |
22035 |
NoSqlJsonItem |
DataError |
22036 |
NonNumericSqlJsonItem |
DataError |
22037 |
NonUniqueKeysInAJsonObject |
DataError |
22038 |
SingletonSqlJsonItemRequired |
DataError |
22039 |
SqlJsonArrayNotFound |
DataError |
2203A |
SqlJsonMemberNotFound |
DataError |
2203B |
SqlJsonNumberNotFound |
DataError |
2203C |
SqlJsonObjectNotFound |
DataError |
2203D |
TooManyJsonArrayElements |
DataError |
2203E |
TooManyJsonObjectMembers |
DataError |
2203F |
SqlJsonScalarRequired |
DataError |
2203G |
SqlJsonItemCannotBeCastToTargetType |
DataError |
22P01 |
FloatingPointException |
DataError |
22P02 |
InvalidTextRepresentation |
DataError |
22P03 |
InvalidBinaryRepresentation |
DataError |
22P04 |
BadCopyFileFormat |
DataError |
22P05 |
UntranslatableCharacter |
DataError |
22P06 |
NonstandardUseOfEscapeCharacter |
DataError |
23 类 - 违反完整性约束 | ||
23000 |
IntegrityConstraintViolation |
IntegrityError |
23001 |
RestrictViolation |
IntegrityError |
23502 |
NotNullViolation |
IntegrityError |
23503 |
ForeignKeyViolation |
IntegrityError |
23505 |
UniqueViolation |
IntegrityError |
23514 |
CheckViolation |
IntegrityError |
23P01 |
ExclusionViolation |
IntegrityError |
24 类 - 无效的游标状态 | ||
24000 |
InvalidCursorState |
InternalError |
25 类 - 无效的事务状态 | ||
25000 |
InvalidTransactionState |
InternalError |
25001 |
ActiveSqlTransaction |
InternalError |
25002 |
BranchTransactionAlreadyActive |
InternalError |
25003 |
InappropriateAccessModeForBranchTransaction |
InternalError |
25004 |
InappropriateIsolationLevelForBranchTransaction |
InternalError |
25005 |
NoActiveSqlTransactionForBranchTransaction |
InternalError |
25006 |
ReadOnlySqlTransaction |
InternalError |
25007 |
SchemaAndDataStatementMixingNotSupported |
InternalError |
25008 |
HeldCursorRequiresSameIsolationLevel |
InternalError |
25P01 |
NoActiveSqlTransaction |
InternalError |
25P02 |
InFailedSqlTransaction |
InternalError |
25P03 |
IdleInTransactionSessionTimeout |
InternalError |
26 类 - 无效的 SQL 语句名称 | ||
26000 |
InvalidSqlStatementName |
ProgrammingError |
27 类 - 触发的数据更改违规 | ||
27000 |
TriggeredDataChangeViolation |
OperationalError |
28 类 - 无效的授权规范 | ||
28000 |
InvalidAuthorizationSpecification |
OperationalError |
28P01 |
InvalidPassword |
OperationalError |
2B 类 - 依赖的特权描述符仍然存在 | ||
2B000 |
DependentPrivilegeDescriptorsStillExist |
InternalError |
2BP01 |
DependentObjectsStillExist |
InternalError |
2D 类 - 无效事务终止 | ||
2D000 |
InvalidTransactionTermination |
InternalError |
2F 类 - SQL 例程异常 | ||
2F000 |
SqlRoutineException |
OperationalError |
2F002 |
ModifyingSqlDataNotPermitted |
OperationalError |
2F003 |
ProhibitedSqlStatementAttempted |
OperationalError |
2F004 |
ReadingSqlDataNotPermitted |
OperationalError |
2F005 |
FunctionExecutedNoReturnStatement |
OperationalError |
34 类 - 无效的游标名称 | ||
34000 |
InvalidCursorName |
ProgrammingError |
38 类 - 外部例程异常 | ||
38000 |
ExternalRoutineException |
OperationalError |
38001 |
ContainingSqlNotPermitted |
OperationalError |
38002 |
ModifyingSqlDataNotPermittedExt |
OperationalError |
38003 |
ProhibitedSqlStatementAttemptedExt |
OperationalError |
38004 |
ReadingSqlDataNotPermittedExt |
OperationalError |
39 类 - 外部例程调用异常 | ||
39000 |
ExternalRoutineInvocationException |
OperationalError |
39001 |
InvalidSqlstateReturned |
OperationalError |
39004 |
NullValueNotAllowedExt |
OperationalError |
39P01 |
TriggerProtocolViolated |
OperationalError |
39P02 |
SrfProtocolViolated |
OperationalError |
39P03 |
EventTriggerProtocolViolated |
OperationalError |
3B 类 - 保存点异常 | ||
3B000 |
SavepointException |
OperationalError |
3B001 |
InvalidSavepointSpecification |
OperationalError |
3D 类 - 无效的目录名称 | ||
3D000 |
InvalidCatalogName |
ProgrammingError |
3F 类 - 无效的模式名称 | ||
3F000 |
InvalidSchemaName |
ProgrammingError |
40 类 - 事务回滚 | ||
40000 |
TransactionRollback |
OperationalError |
40001 |
SerializationFailure |
OperationalError |
40002 |
TransactionIntegrityConstraintViolation |
OperationalError |
40003 |
StatementCompletionUnknown |
OperationalError |
40P01 |
DeadlockDetected |
OperationalError |
42 类 - 语法错误或违反访问规则 | ||
42000 |
SyntaxErrorOrAccessRuleViolation |
ProgrammingError |
42501 |
InsufficientPrivilege |
ProgrammingError |
42601 |
SyntaxError |
ProgrammingError |
42602 |
InvalidName |
ProgrammingError |
42611 |
InvalidColumnDefinition |
ProgrammingError |
42622 |
NameTooLong |
ProgrammingError |
42701 |
DuplicateColumn |
ProgrammingError |
42702 |
AmbiguousColumn |
ProgrammingError |
42703 |
UndefinedColumn |
ProgrammingError |
42704 |
UndefinedObject |
ProgrammingError |
42710 |
DuplicateObject |
ProgrammingError |
42712 |
DuplicateAlias |
ProgrammingError |
42723 |
DuplicateFunction |
ProgrammingError |
42725 |
AmbiguousFunction |
ProgrammingError |
42803 |
GroupingError |
ProgrammingError |
42804 |
DatatypeMismatch |
ProgrammingError |
42809 |
WrongObjectType |
ProgrammingError |
42830 |
InvalidForeignKey |
ProgrammingError |
42846 |
CannotCoerce |
ProgrammingError |
42883 |
UndefinedFunction |
ProgrammingError |
428C9 |
GeneratedAlways |
ProgrammingError |
42939 |
ReservedName |
ProgrammingError |
42P01 |
UndefinedTable |
ProgrammingError |
42P02 |
UndefinedParameter |
ProgrammingError |
42P03 |
DuplicateCursor |
ProgrammingError |
42P04 |
DuplicateDatabase |
ProgrammingError |
42P05 |
DuplicatePreparedStatement |
ProgrammingError |
42P06 |
DuplicateSchema |
ProgrammingError |
42P07 |
DuplicateTable |
ProgrammingError |
42P08 |
AmbiguousParameter |
ProgrammingError |
42P09 |
AmbiguousAlias |
ProgrammingError |
42P10 |
InvalidColumnReference |
ProgrammingError |
42P11 |
InvalidCursorDefinition |
ProgrammingError |
42P12 |
InvalidDatabaseDefinition |
ProgrammingError |
42P13 |
InvalidFunctionDefinition |
ProgrammingError |
42P14 |
InvalidPreparedStatementDefinition |
ProgrammingError |
42P15 |
InvalidSchemaDefinition |
ProgrammingError |
42P16 |
InvalidTableDefinition |
ProgrammingError |
42P17 |
InvalidObjectDefinition |
ProgrammingError |
42P18 |
IndeterminateDatatype |
ProgrammingError |
42P19 |
InvalidRecursion |
ProgrammingError |
42P20 |
WindowingError |
ProgrammingError |
42P21 |
CollationMismatch |
ProgrammingError |
42P22 |
IndeterminateCollation |
ProgrammingError |
44 类 - WITH CHECK OPTION 违规 | ||
44000 |
WithCheckOptionViolation |
ProgrammingError |
53 类 - 资源不足 | ||
53000 |
InsufficientResources |
OperationalError |
53100 |
DiskFull |
OperationalError |
53200 |
OutOfMemory |
OperationalError |
53300 |
TooManyConnections |
OperationalError |
53400 |
ConfigurationLimitExceeded |
OperationalError |
54 - 超出程序限制 | ||
54000 |
ProgramLimitExceeded |
OperationalError |
54001 |
StatementTooComplex |
OperationalError |
54011 |
TooManyColumns |
OperationalError |
54023 |
TooManyArguments |
OperationalError |
55 类 - 对象未在先决条件状态 | ||
55000 |
ObjectNotInPrerequisiteState |
OperationalError |
55006 |
ObjectInUse |
OperationalError |
55P02 |
CantChangeRuntimeParam |
OperationalError |
55P03 |
LockNotAvailable |
OperationalError |
55P04 |
UnsafeNewEnumValueUsage |
OperationalError |
57 类 - 操作员干预 | ||
57000 |
OperatorIntervention |
OperationalError |
57014 |
QueryCanceled |
OperationalError |
57P01 |
AdminShutdown |
OperationalError |
57P02 |
CrashShutdown |
OperationalError |
57P03 |
CannotConnectNow |
OperationalError |
57P04 |
DatabaseDropped |
OperationalError |
57P05 |
IdleSessionTimeout |
OperationalError |
58 类 - 系统错误(PostgreSQL 外部发生的错误) | ||
58000 |
SystemError |
OperationalError |
58030 |
IoError |
OperationalError |
58P01 |
UndefinedFile |
OperationalError |
58P02 |
DuplicateFile |
OperationalError |
72 类 - 快照失效 | ||
72000 |
SnapshotTooOld |
DatabaseError |
F0 类 - 配置文件错误 | ||
F0000 |
ConfigFileError |
OperationalError |
F0001 |
LockFileExists |
OperationalError |
HV 类 - 外部数据包装器错误 (SQL/MED) | ||
HV000 |
FdwError |
OperationalError |
HV001 |
FdwOutOfMemory |
OperationalError |
HV002 |
FdwDynamicParameterValueNeeded |
OperationalError |
HV004 |
FdwInvalidDataType |
OperationalError |
HV005 |
FdwColumnNameNotFound |
OperationalError |
HV006 |
FdwInvalidDataTypeDescriptors |
OperationalError |
HV007 |
FdwInvalidColumnName |
OperationalError |
HV008 |
FdwInvalidColumnNumber |
OperationalError |
HV009 |
FdwInvalidUseOfNullPointer |
OperationalError |
HV00A |
FdwInvalidStringFormat |
OperationalError |
HV00B |
FdwInvalidHandle |
OperationalError |
HV00C |
FdwInvalidOptionIndex |
OperationalError |
HV00D |
FdwInvalidOptionName |
OperationalError |
HV00J |
FdwOptionNameNotFound |
OperationalError |
HV00K |
FdwReplyHandle |
OperationalError |
HV00L |
FdwUnableToCreateExecution |
OperationalError |
HV00M |
FdwUnableToCreateReply |
OperationalError |
HV00N |
FdwUnableToEstablishConnection |
OperationalError |
HV00P |
FdwNoSchemas |
OperationalError |
HV00Q |
FdwSchemaNotFound |
OperationalError |
HV00R |
FdwTableNotFound |
OperationalError |
HV010 |
FdwFunctionSequenceError |
OperationalError |
HV014 |
FdwTooManyHandles |
OperationalError |
HV021 |
FdwInconsistentDescriptorInformation |
OperationalError |
HV024 |
FdwInvalidAttributeValue |
OperationalError |
HV090 |
FdwInvalidStringLengthOrBufferLength |
OperationalError |
HV091 |
FdwInvalidDescriptorFieldIdentifier |
OperationalError |
P0 类 - PL/pgSQL 错误 | ||
P0000 |
PlpgsqlError |
ProgrammingError |
P0001 |
RaiseException |
ProgrammingError |
P0002 |
NoDataFound |
ProgrammingError |
P0003 |
TooManyRows |
ProgrammingError |
P0004 |
AssertFailure |
ProgrammingError |
XX 类 - 内部错误 | ||
XX000 |
InternalError_ |
InternalError |
XX001 |
DataCorrupted |
InternalError |
XX002 |
IndexCorrupted |
InternalError |
3.1.4 新版功能: SqlJsonItemCannotBeCastToTargetType
异常,在 PostgreSQL 15 中引入。