SQLAlchemy 2.0 Documentation
SQLAlchemy Core
- SQL Statements and Expressions API
- Schema Definition Language
- SQL Datatype Objects
- Engine and Connection Use
- Core API Basics
- Events
- Runtime Inspection API
- Core Exceptions¶
AmbiguousForeignKeysErrorArgumentErrorAwaitRequiredBase20DeprecationWarningCircularDependencyErrorCompileErrorConstraintColumnNotFoundErrorDBAPIErrorDataErrorDatabaseErrorDisconnectionErrorDontWrapMixinDuplicateColumnErrorHasDescriptionCodeIdentifierErrorIllegalStateChangeErrorIntegrityErrorInterfaceErrorInternalErrorInvalidRequestErrorInvalidatePoolErrorLegacyAPIWarningMissingGreenletMovedIn20WarningMultipleResultsFoundNoForeignKeysErrorNoInspectionAvailableNoReferenceErrorNoReferencedColumnErrorNoReferencedTableErrorNoResultFoundNoSuchColumnErrorNoSuchModuleErrorNoSuchTableErrorNotSupportedErrorObjectNotExecutableErrorOperationalErrorPendingRollbackErrorProgrammingErrorResourceClosedErrorSADeprecationWarningSAPendingDeprecationWarningSATestSuiteWarningSAWarningSQLAlchemyErrorStatementErrorTimeoutErrorUnboundExecutionErrorUnreflectableTableErrorUnsupportedCompilationError
- Core Internals
Project Versions
- Previous: Runtime Inspection API
- Next: Core Internals
- Up: Home
- On this page:
- Core Exceptions
AmbiguousForeignKeysErrorArgumentErrorAwaitRequiredBase20DeprecationWarningCircularDependencyErrorCompileErrorConstraintColumnNotFoundErrorDBAPIErrorDataErrorDatabaseErrorDisconnectionErrorDontWrapMixinDuplicateColumnErrorHasDescriptionCodeIdentifierErrorIllegalStateChangeErrorIntegrityErrorInterfaceErrorInternalErrorInvalidRequestErrorInvalidatePoolErrorLegacyAPIWarningMissingGreenletMovedIn20WarningMultipleResultsFoundNoForeignKeysErrorNoInspectionAvailableNoReferenceErrorNoReferencedColumnErrorNoReferencedTableErrorNoResultFoundNoSuchColumnErrorNoSuchModuleErrorNoSuchTableErrorNotSupportedErrorObjectNotExecutableErrorOperationalErrorPendingRollbackErrorProgrammingErrorResourceClosedErrorSADeprecationWarningSAPendingDeprecationWarningSATestSuiteWarningSAWarningSQLAlchemyErrorStatementErrorTimeoutErrorUnboundExecutionErrorUnreflectableTableErrorUnsupportedCompilationError
Core Exceptions¶
Exceptions used with SQLAlchemy.
The base exception class is SQLAlchemyError. Exceptions which are raised as a result of DBAPI exceptions are all subclasses of DBAPIError.
- exception sqlalchemy.exc.AmbiguousForeignKeysError¶
inherits from
sqlalchemy.exc.ArgumentErrorRaised when more than one foreign key matching can be located between two selectables during a join.
- exception sqlalchemy.exc.ArgumentError¶
inherits from
sqlalchemy.exc.SQLAlchemyErrorRaised when an invalid or conflicting function argument is supplied.
This error generally corresponds to construction time state errors.
- exception sqlalchemy.exc.AwaitRequired¶
inherits from
sqlalchemy.exc.InvalidRequestErrorError raised by the async greenlet spawn if no async operation was awaited when it required one.
- exception sqlalchemy.exc.Base20DeprecationWarning¶
inherits from
sqlalchemy.exc.SADeprecationWarningIssued for usage of APIs specifically deprecated or legacy in SQLAlchemy 2.0.
- attribute
sqlalchemy.exc.Base20DeprecationWarning.deprecated_since: str | None = '1.4'¶ Indicates the version that started raising this deprecation warning
- attribute
- exception sqlalchemy.exc.CircularDependencyError¶
inherits from
sqlalchemy.exc.SQLAlchemyErrorRaised by topological sorts when a circular dependency is detected.
There are two scenarios where this error occurs:
In a Session flush operation, if two objects are mutually dependent on each other, they can not be inserted or deleted via INSERT or DELETE statements alone; an UPDATE will be needed to post-associate or pre-deassociate one of the foreign key constrained values. The
post_updateflag described at Rows that point to themselves / Mutually Dependent Rows can resolve this cycle.In a
MetaData.sorted_tablesoperation, twoForeignKeyorForeignKeyConstraintobjects mutually refer to each other. Apply theuse_alter=Trueflag to one or both, see Creating/Dropping Foreign Key Constraints via ALTER.
- method
sqlalchemy.exc.CircularDependencyError.__init__(message: str, cycles: Any, edges: Any, msg: str | None = None, code: str | None = None)¶
- exception sqlalchemy.exc.CompileError¶
inherits from
sqlalchemy.exc.SQLAlchemyErrorRaised when an error occurs during SQL compilation
- exception sqlalchemy.exc.ConstraintColumnNotFoundError¶
inherits from
sqlalchemy.exc.ArgumentErrorraised when a constraint refers to a string column name that is not present in the table being constrained.
Added in version 2.0.
- exception sqlalchemy.exc.DBAPIError¶
inherits from
sqlalchemy.exc.StatementErrorRaised when the execution of a database operation fails.
Wraps exceptions raised by the DB-API underlying the database operation. Driver-specific implementations of the standard DB-API exception types are wrapped by matching sub-types of SQLAlchemy’s
DBAPIErrorwhen possible. DB-API’sErrortype maps toDBAPIErrorin SQLAlchemy, otherwise the names are identical. Note that there is no guarantee that different DB-API implementations will raise the same exception type for any given error condition.DBAPIErrorfeaturesStatementError.statementandStatementError.paramsattributes which supply context regarding the specifics of the statement which had an issue, for the typical case when the error was raised within the context of emitting a SQL statement.The wrapped exception object is available in the
StatementError.origattribute. Its type and properties are DB-API implementation specific.- method
sqlalchemy.exc.DBAPIError.__init__(statement: str | None, params: _AnyExecuteParams | None, orig: BaseException, hide_parameters: bool = False, connection_invalidated: bool = False, code: str | None = None, ismulti: bool | None = None)¶
- method
- exception sqlalchemy.exc.DataError¶
inherits from
sqlalchemy.exc.DatabaseErrorWraps a DB-API DataError.
- exception sqlalchemy.exc.DatabaseError¶
inherits from
sqlalchemy.exc.DBAPIErrorWraps a DB-API DatabaseError.
- exception sqlalchemy.exc.DisconnectionError¶
inherits from
sqlalchemy.exc.SQLAlchemyErrorA disconnect is detected on a raw DB-API connection.
This error is raised and consumed internally by a connection pool. It can be raised by the
PoolEvents.checkout()event so that the host pool forces a retry; the exception will be caught three times in a row before the pool gives up and raisesInvalidRequestErrorregarding the connection attempt.
| Object Name | Description |
|---|---|
A mixin class which, when applied to a user-defined Exception class, will not be wrapped inside of | |
helper which adds ‘code’ as an attribute and ‘_code_str’ as a method |
- class sqlalchemy.exc.DontWrapMixin¶
A mixin class which, when applied to a user-defined Exception class, will not be wrapped inside of
StatementErrorif the error is emitted within the process of executing a statement.E.g.:
from sqlalchemy.exc import DontWrapMixin class MyCustomException(Exception, DontWrapMixin): pass class MySpecialType(TypeDecorator): impl = String def process_bind_param(self, value, dialect): if value == "invalid": raise MyCustomException("invalid!")
- exception sqlalchemy.exc.DuplicateColumnError¶
inherits from
sqlalchemy.exc.ArgumentErrora Column is being added to a Table that would replace another Column, without appropriate parameters to allow this in place.
Added in version 2.0.0b4.
- class sqlalchemy.exc.HasDescriptionCode¶
helper which adds ‘code’ as an attribute and ‘_code_str’ as a method
- exception sqlalchemy.exc.IdentifierError¶
inherits from
sqlalchemy.exc.SQLAlchemyErrorRaised when a schema name is beyond the max character limit
- exception sqlalchemy.exc.IllegalStateChangeError¶
inherits from
sqlalchemy.exc.InvalidRequestErrorAn object that tracks state encountered an illegal state change of some kind.
Added in version 2.0.
- exception sqlalchemy.exc.IntegrityError¶
inherits from
sqlalchemy.exc.DatabaseErrorWraps a DB-API IntegrityError.
- exception sqlalchemy.exc.InterfaceError¶
inherits from
sqlalchemy.exc.DBAPIErrorWraps a DB-API InterfaceError.
- exception sqlalchemy.exc.InternalError¶
inherits from
sqlalchemy.exc.DatabaseErrorWraps a DB-API InternalError.
- exception sqlalchemy.exc.InvalidRequestError¶
inherits from
sqlalchemy.exc.SQLAlchemyErrorSQLAlchemy was asked to do something it can’t do.
This error generally corresponds to runtime state errors.
- exception sqlalchemy.exc.InvalidatePoolError¶
inherits from
sqlalchemy.exc.DisconnectionErrorRaised when the connection pool should invalidate all stale connections.
A subclass of
DisconnectionErrorthat indicates that the disconnect situation encountered on the connection probably means the entire pool should be invalidated, as the database has been restarted.This exception will be handled otherwise the same way as
DisconnectionError, allowing three attempts to reconnect before giving up.Added in version 1.2.
- exception sqlalchemy.exc.LegacyAPIWarning¶
inherits from
sqlalchemy.exc.Base20DeprecationWarningindicates an API that is in ‘legacy’ status, a long term deprecation.
- exception sqlalchemy.exc.MissingGreenlet¶
inherits from
sqlalchemy.exc.InvalidRequestErrorError raised by the async greenlet await_ if called while not inside the greenlet spawn context.
- exception sqlalchemy.exc.MovedIn20Warning¶
inherits from
sqlalchemy.exc.Base20DeprecationWarningSubtype of RemovedIn20Warning to indicate an API that moved only.
- exception sqlalchemy.exc.MultipleResultsFound¶
inherits from
sqlalchemy.exc.InvalidRequestErrorA single database result was required but more than one were found.
Changed in version 1.4: This exception is now part of the
sqlalchemy.excmodule in Core, moved from the ORM. The symbol remains importable fromsqlalchemy.orm.exc.
- exception sqlalchemy.exc.NoForeignKeysError¶
inherits from
sqlalchemy.exc.ArgumentErrorRaised when no foreign keys can be located between two selectables during a join.
- exception sqlalchemy.exc.NoInspectionAvailable¶
inherits from
sqlalchemy.exc.InvalidRequestErrorA subject passed to
sqlalchemy.inspection.inspect()produced no context for inspection.
- exception sqlalchemy.exc.NoReferenceError¶
inherits from
sqlalchemy.exc.InvalidRequestErrorRaised by
ForeignKeyto indicate a reference cannot be resolved.
- exception sqlalchemy.exc.NoReferencedColumnError¶
inherits from
sqlalchemy.exc.NoReferenceErrorRaised by
ForeignKeywhen the referredColumncannot be located.- method
sqlalchemy.exc.NoReferencedColumnError.__init__(message: str, tname: str, cname: str)¶
- method
- exception sqlalchemy.exc.NoReferencedTableError¶
inherits from
sqlalchemy.exc.NoReferenceErrorRaised by
ForeignKeywhen the referredTablecannot be located.- method
sqlalchemy.exc.NoReferencedTableError.__init__(message: str, tname: str)¶
- method
- exception sqlalchemy.exc.NoResultFound¶
inherits from
sqlalchemy.exc.InvalidRequestErrorA database result was required but none was found.
Changed in version 1.4: This exception is now part of the
sqlalchemy.excmodule in Core, moved from the ORM. The symbol remains importable fromsqlalchemy.orm.exc.
- exception sqlalchemy.exc.NoSuchColumnError¶
inherits from
sqlalchemy.exc.InvalidRequestError,builtins.KeyErrorA nonexistent column is requested from a
Row.
- exception sqlalchemy.exc.NoSuchModuleError¶
inherits from
sqlalchemy.exc.ArgumentErrorRaised when a dynamically-loaded module (usually a database dialect) of a particular name cannot be located.
- exception sqlalchemy.exc.NoSuchTableError¶
inherits from
sqlalchemy.exc.InvalidRequestErrorTable does not exist or is not visible to a connection.
- exception sqlalchemy.exc.NotSupportedError¶
inherits from
sqlalchemy.exc.DatabaseErrorWraps a DB-API NotSupportedError.
- exception sqlalchemy.exc.ObjectNotExecutableError¶
inherits from
sqlalchemy.exc.ArgumentErrorRaised when an object is passed to .execute() that can’t be executed as SQL.
- method
sqlalchemy.exc.ObjectNotExecutableError.__init__(target: Any)¶
- method
- exception sqlalchemy.exc.OperationalError¶
inherits from
sqlalchemy.exc.DatabaseErrorWraps a DB-API OperationalError.
- exception sqlalchemy.exc.PendingRollbackError¶
inherits from
sqlalchemy.exc.InvalidRequestErrorA transaction has failed and needs to be rolled back before continuing.
Added in version 1.4.
- exception sqlalchemy.exc.ProgrammingError¶
inherits from
sqlalchemy.exc.DatabaseErrorWraps a DB-API ProgrammingError.
- exception sqlalchemy.exc.ResourceClosedError¶
inherits from
sqlalchemy.exc.InvalidRequestErrorAn operation was requested from a connection, cursor, or other object that’s in a closed state.
- exception sqlalchemy.exc.SADeprecationWarning¶
inherits from
sqlalchemy.exc.HasDescriptionCode,builtins.DeprecationWarningIssued for usage of deprecated APIs.
- attribute
sqlalchemy.exc.SADeprecationWarning.deprecated_since: str | None = None¶ Indicates the version that started raising this deprecation warning
- attribute
- exception sqlalchemy.exc.SAPendingDeprecationWarning¶
inherits from
builtins.PendingDeprecationWarningA similar warning as
SADeprecationWarning, this warning is not used in modern versions of SQLAlchemy.- attribute
sqlalchemy.exc.SAPendingDeprecationWarning.deprecated_since: str | None = None¶ Indicates the version that started raising this deprecation warning
- attribute
- exception sqlalchemy.exc.SATestSuiteWarning¶
inherits from
builtins.Warningwarning for a condition detected during tests that is non-fatal
Currently outside of SAWarning so that we can work around tools like Alembic doing the wrong thing with warnings.
- exception sqlalchemy.exc.SAWarning¶
inherits from
sqlalchemy.exc.HasDescriptionCode,builtins.RuntimeWarningIssued at runtime.
- exception sqlalchemy.exc.SQLAlchemyError¶
inherits from
sqlalchemy.exc.HasDescriptionCode,builtins.ExceptionGeneric error class.
- exception sqlalchemy.exc.StatementError¶
inherits from
sqlalchemy.exc.SQLAlchemyErrorAn error occurred during execution of a SQL statement.
StatementErrorwraps the exception raised during execution, and featuresstatementandparamsattributes which supply context regarding the specifics of the statement which had an issue.The wrapped exception object is available in the
origattribute.- method
sqlalchemy.exc.StatementError.__init__(message: str, statement: str | None, params: _AnyExecuteParams | None, orig: BaseException | None, hide_parameters: bool = False, code: str | None = None, ismulti: bool | None = None)¶
- attribute
sqlalchemy.exc.StatementError.ismulti: bool | None = None¶ multi parameter passed to repr_params(). None is meaningful.
- attribute
sqlalchemy.exc.StatementError.orig: BaseException | None = None¶ The original exception that was thrown.
- attribute
sqlalchemy.exc.StatementError.params: _AnyExecuteParams | None = None¶ The parameter list being used when this exception occurred.
- attribute
sqlalchemy.exc.StatementError.statement: str | None = None¶ The string SQL statement being invoked when this exception occurred.
- method
- exception sqlalchemy.exc.TimeoutError¶
inherits from
sqlalchemy.exc.SQLAlchemyErrorRaised when a connection pool times out on getting a connection.
- exception sqlalchemy.exc.UnboundExecutionError¶
inherits from
sqlalchemy.exc.InvalidRequestErrorSQL was attempted without a database connection to execute it on.
- exception sqlalchemy.exc.UnreflectableTableError¶
inherits from
sqlalchemy.exc.InvalidRequestErrorTable exists but can’t be reflected for some reason.
Added in version 1.2.
- exception sqlalchemy.exc.UnsupportedCompilationError¶
inherits from
sqlalchemy.exc.CompileErrorRaised when an operation is not supported by the given compiler.
See also
How do I render SQL expressions as strings, possibly with bound parameters inlined?
Compiler StrSQLCompiler can’t render element of type <element type>
- method
sqlalchemy.exc.UnsupportedCompilationError.__init__(compiler: Compiled | TypeCompiler, element_type: Type[ClauseElement], message: str | None = None)¶
- method
flambé! the dragon and The Alchemist image designs created and generously donated by Rotem Yaari.
Created using Sphinx 8.2.3. Documentation last generated: Tue 21 Oct 2025 06:01:18 PM EDT