exc.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. # sqlalchemy/exc.py
  2. # Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """Exceptions used with SQLAlchemy.
  8. The base exception class is :exc:`.SQLAlchemyError`. Exceptions which are
  9. raised as a result of DBAPI exceptions are all subclasses of
  10. :exc:`.DBAPIError`.
  11. """
  12. from .util import _preloaded
  13. from .util import compat
  14. _version_token = None
  15. class HasDescriptionCode(object):
  16. """helper which adds 'code' as an attribute and '_code_str' as a method"""
  17. code = None
  18. def __init__(self, *arg, **kw):
  19. code = kw.pop("code", None)
  20. if code is not None:
  21. self.code = code
  22. super(HasDescriptionCode, self).__init__(*arg, **kw)
  23. def _code_str(self):
  24. if not self.code:
  25. return ""
  26. else:
  27. return (
  28. "(Background on this error at: "
  29. "https://sqlalche.me/e/%s/%s)"
  30. % (
  31. _version_token,
  32. self.code,
  33. )
  34. )
  35. def __str__(self):
  36. message = super(HasDescriptionCode, self).__str__()
  37. if self.code:
  38. message = "%s %s" % (message, self._code_str())
  39. return message
  40. class SQLAlchemyError(HasDescriptionCode, Exception):
  41. """Generic error class."""
  42. def _message(self, as_unicode=compat.py3k):
  43. # rules:
  44. #
  45. # 1. under py2k, for __str__ return single string arg as it was
  46. # given without converting to unicode. for __unicode__
  47. # do a conversion but check that it's not unicode already just in
  48. # case
  49. #
  50. # 2. under py3k, single arg string will usually be a unicode
  51. # object, but since __str__() must return unicode, check for
  52. # bytestring just in case
  53. #
  54. # 3. for multiple self.args, this is not a case in current
  55. # SQLAlchemy though this is happening in at least one known external
  56. # library, call str() which does a repr().
  57. #
  58. if len(self.args) == 1:
  59. text = self.args[0]
  60. if as_unicode and isinstance(text, compat.binary_types):
  61. text = compat.decode_backslashreplace(text, "utf-8")
  62. # This is for when the argument is not a string of any sort.
  63. # Otherwise, converting this exception to string would fail for
  64. # non-string arguments.
  65. elif compat.py3k or not as_unicode:
  66. text = str(text)
  67. else:
  68. text = compat.text_type(text)
  69. return text
  70. else:
  71. # this is not a normal case within SQLAlchemy but is here for
  72. # compatibility with Exception.args - the str() comes out as
  73. # a repr() of the tuple
  74. return str(self.args)
  75. def _sql_message(self, as_unicode):
  76. message = self._message(as_unicode)
  77. if self.code:
  78. message = "%s %s" % (message, self._code_str())
  79. return message
  80. def __str__(self):
  81. return self._sql_message(compat.py3k)
  82. def __unicode__(self):
  83. return self._sql_message(as_unicode=True)
  84. class ArgumentError(SQLAlchemyError):
  85. """Raised when an invalid or conflicting function argument is supplied.
  86. This error generally corresponds to construction time state errors.
  87. """
  88. class ObjectNotExecutableError(ArgumentError):
  89. """Raised when an object is passed to .execute() that can't be
  90. executed as SQL.
  91. .. versionadded:: 1.1
  92. """
  93. def __init__(self, target):
  94. super(ObjectNotExecutableError, self).__init__(
  95. "Not an executable object: %r" % target
  96. )
  97. self.target = target
  98. def __reduce__(self):
  99. return self.__class__, (self.target,)
  100. class NoSuchModuleError(ArgumentError):
  101. """Raised when a dynamically-loaded module (usually a database dialect)
  102. of a particular name cannot be located."""
  103. class NoForeignKeysError(ArgumentError):
  104. """Raised when no foreign keys can be located between two selectables
  105. during a join."""
  106. class AmbiguousForeignKeysError(ArgumentError):
  107. """Raised when more than one foreign key matching can be located
  108. between two selectables during a join."""
  109. class CircularDependencyError(SQLAlchemyError):
  110. """Raised by topological sorts when a circular dependency is detected.
  111. There are two scenarios where this error occurs:
  112. * In a Session flush operation, if two objects are mutually dependent
  113. on each other, they can not be inserted or deleted via INSERT or
  114. DELETE statements alone; an UPDATE will be needed to post-associate
  115. or pre-deassociate one of the foreign key constrained values.
  116. The ``post_update`` flag described at :ref:`post_update` can resolve
  117. this cycle.
  118. * In a :attr:`_schema.MetaData.sorted_tables` operation, two
  119. :class:`_schema.ForeignKey`
  120. or :class:`_schema.ForeignKeyConstraint` objects mutually refer to each
  121. other. Apply the ``use_alter=True`` flag to one or both,
  122. see :ref:`use_alter`.
  123. """
  124. def __init__(self, message, cycles, edges, msg=None, code=None):
  125. if msg is None:
  126. message += " (%s)" % ", ".join(repr(s) for s in cycles)
  127. else:
  128. message = msg
  129. SQLAlchemyError.__init__(self, message, code=code)
  130. self.cycles = cycles
  131. self.edges = edges
  132. def __reduce__(self):
  133. return (
  134. self.__class__,
  135. (None, self.cycles, self.edges, self.args[0]),
  136. {"code": self.code} if self.code is not None else {},
  137. )
  138. class CompileError(SQLAlchemyError):
  139. """Raised when an error occurs during SQL compilation"""
  140. class UnsupportedCompilationError(CompileError):
  141. """Raised when an operation is not supported by the given compiler.
  142. .. seealso::
  143. :ref:`faq_sql_expression_string`
  144. :ref:`error_l7de`
  145. """
  146. code = "l7de"
  147. def __init__(self, compiler, element_type, message=None):
  148. super(UnsupportedCompilationError, self).__init__(
  149. "Compiler %r can't render element of type %s%s"
  150. % (compiler, element_type, ": %s" % message if message else "")
  151. )
  152. self.compiler = compiler
  153. self.element_type = element_type
  154. self.message = message
  155. def __reduce__(self):
  156. return self.__class__, (self.compiler, self.element_type, self.message)
  157. class IdentifierError(SQLAlchemyError):
  158. """Raised when a schema name is beyond the max character limit"""
  159. class DisconnectionError(SQLAlchemyError):
  160. """A disconnect is detected on a raw DB-API connection.
  161. This error is raised and consumed internally by a connection pool. It can
  162. be raised by the :meth:`_events.PoolEvents.checkout`
  163. event so that the host pool
  164. forces a retry; the exception will be caught three times in a row before
  165. the pool gives up and raises :class:`~sqlalchemy.exc.InvalidRequestError`
  166. regarding the connection attempt.
  167. """
  168. invalidate_pool = False
  169. class InvalidatePoolError(DisconnectionError):
  170. """Raised when the connection pool should invalidate all stale connections.
  171. A subclass of :class:`_exc.DisconnectionError` that indicates that the
  172. disconnect situation encountered on the connection probably means the
  173. entire pool should be invalidated, as the database has been restarted.
  174. This exception will be handled otherwise the same way as
  175. :class:`_exc.DisconnectionError`, allowing three attempts to reconnect
  176. before giving up.
  177. .. versionadded:: 1.2
  178. """
  179. invalidate_pool = True
  180. class TimeoutError(SQLAlchemyError): # noqa
  181. """Raised when a connection pool times out on getting a connection."""
  182. class InvalidRequestError(SQLAlchemyError):
  183. """SQLAlchemy was asked to do something it can't do.
  184. This error generally corresponds to runtime state errors.
  185. """
  186. class NoInspectionAvailable(InvalidRequestError):
  187. """A subject passed to :func:`sqlalchemy.inspection.inspect` produced
  188. no context for inspection."""
  189. class PendingRollbackError(InvalidRequestError):
  190. """A transaction has failed and needs to be rolled back before
  191. continuing.
  192. .. versionadded:: 1.4
  193. """
  194. class ResourceClosedError(InvalidRequestError):
  195. """An operation was requested from a connection, cursor, or other
  196. object that's in a closed state."""
  197. class NoSuchColumnError(InvalidRequestError, KeyError):
  198. """A nonexistent column is requested from a ``Row``."""
  199. class NoResultFound(InvalidRequestError):
  200. """A database result was required but none was found.
  201. .. versionchanged:: 1.4 This exception is now part of the
  202. ``sqlalchemy.exc`` module in Core, moved from the ORM. The symbol
  203. remains importable from ``sqlalchemy.orm.exc``.
  204. """
  205. class MultipleResultsFound(InvalidRequestError):
  206. """A single database result was required but more than one were found.
  207. .. versionchanged:: 1.4 This exception is now part of the
  208. ``sqlalchemy.exc`` module in Core, moved from the ORM. The symbol
  209. remains importable from ``sqlalchemy.orm.exc``.
  210. """
  211. class NoReferenceError(InvalidRequestError):
  212. """Raised by ``ForeignKey`` to indicate a reference cannot be resolved."""
  213. class AwaitRequired(InvalidRequestError):
  214. """Error raised by the async greenlet spawn if no async operation
  215. was awaited when it required one.
  216. """
  217. code = "xd1r"
  218. class MissingGreenlet(InvalidRequestError):
  219. r"""Error raised by the async greenlet await\_ if called while not inside
  220. the greenlet spawn context.
  221. """
  222. code = "xd2s"
  223. class NoReferencedTableError(NoReferenceError):
  224. """Raised by ``ForeignKey`` when the referred ``Table`` cannot be
  225. located.
  226. """
  227. def __init__(self, message, tname):
  228. NoReferenceError.__init__(self, message)
  229. self.table_name = tname
  230. def __reduce__(self):
  231. return self.__class__, (self.args[0], self.table_name)
  232. class NoReferencedColumnError(NoReferenceError):
  233. """Raised by ``ForeignKey`` when the referred ``Column`` cannot be
  234. located.
  235. """
  236. def __init__(self, message, tname, cname):
  237. NoReferenceError.__init__(self, message)
  238. self.table_name = tname
  239. self.column_name = cname
  240. def __reduce__(self):
  241. return (
  242. self.__class__,
  243. (self.args[0], self.table_name, self.column_name),
  244. )
  245. class NoSuchTableError(InvalidRequestError):
  246. """Table does not exist or is not visible to a connection."""
  247. class UnreflectableTableError(InvalidRequestError):
  248. """Table exists but can't be reflected for some reason.
  249. .. versionadded:: 1.2
  250. """
  251. class UnboundExecutionError(InvalidRequestError):
  252. """SQL was attempted without a database connection to execute it on."""
  253. class DontWrapMixin(object):
  254. """A mixin class which, when applied to a user-defined Exception class,
  255. will not be wrapped inside of :exc:`.StatementError` if the error is
  256. emitted within the process of executing a statement.
  257. E.g.::
  258. from sqlalchemy.exc import DontWrapMixin
  259. class MyCustomException(Exception, DontWrapMixin):
  260. pass
  261. class MySpecialType(TypeDecorator):
  262. impl = String
  263. def process_bind_param(self, value, dialect):
  264. if value == 'invalid':
  265. raise MyCustomException("invalid!")
  266. """
  267. class StatementError(SQLAlchemyError):
  268. """An error occurred during execution of a SQL statement.
  269. :class:`StatementError` wraps the exception raised
  270. during execution, and features :attr:`.statement`
  271. and :attr:`.params` attributes which supply context regarding
  272. the specifics of the statement which had an issue.
  273. The wrapped exception object is available in
  274. the :attr:`.orig` attribute.
  275. """
  276. statement = None
  277. """The string SQL statement being invoked when this exception occurred."""
  278. params = None
  279. """The parameter list being used when this exception occurred."""
  280. orig = None
  281. """The DBAPI exception object."""
  282. ismulti = None
  283. def __init__(
  284. self,
  285. message,
  286. statement,
  287. params,
  288. orig,
  289. hide_parameters=False,
  290. code=None,
  291. ismulti=None,
  292. ):
  293. SQLAlchemyError.__init__(self, message, code=code)
  294. self.statement = statement
  295. self.params = params
  296. self.orig = orig
  297. self.ismulti = ismulti
  298. self.hide_parameters = hide_parameters
  299. self.detail = []
  300. def add_detail(self, msg):
  301. self.detail.append(msg)
  302. def __reduce__(self):
  303. return (
  304. self.__class__,
  305. (
  306. self.args[0],
  307. self.statement,
  308. self.params,
  309. self.orig,
  310. self.hide_parameters,
  311. self.__dict__.get("code"),
  312. self.ismulti,
  313. ),
  314. {"detail": self.detail},
  315. )
  316. @_preloaded.preload_module("sqlalchemy.sql.util")
  317. def _sql_message(self, as_unicode):
  318. util = _preloaded.preloaded.sql_util
  319. details = [self._message(as_unicode=as_unicode)]
  320. if self.statement:
  321. if not as_unicode and not compat.py3k:
  322. stmt_detail = "[SQL: %s]" % compat.safe_bytestring(
  323. self.statement
  324. )
  325. else:
  326. stmt_detail = "[SQL: %s]" % self.statement
  327. details.append(stmt_detail)
  328. if self.params:
  329. if self.hide_parameters:
  330. details.append(
  331. "[SQL parameters hidden due to hide_parameters=True]"
  332. )
  333. else:
  334. params_repr = util._repr_params(
  335. self.params, 10, ismulti=self.ismulti
  336. )
  337. details.append("[parameters: %r]" % params_repr)
  338. code_str = self._code_str()
  339. if code_str:
  340. details.append(code_str)
  341. return "\n".join(["(%s)" % det for det in self.detail] + details)
  342. class DBAPIError(StatementError):
  343. """Raised when the execution of a database operation fails.
  344. Wraps exceptions raised by the DB-API underlying the
  345. database operation. Driver-specific implementations of the standard
  346. DB-API exception types are wrapped by matching sub-types of SQLAlchemy's
  347. :class:`DBAPIError` when possible. DB-API's ``Error`` type maps to
  348. :class:`DBAPIError` in SQLAlchemy, otherwise the names are identical. Note
  349. that there is no guarantee that different DB-API implementations will
  350. raise the same exception type for any given error condition.
  351. :class:`DBAPIError` features :attr:`~.StatementError.statement`
  352. and :attr:`~.StatementError.params` attributes which supply context
  353. regarding the specifics of the statement which had an issue, for the
  354. typical case when the error was raised within the context of
  355. emitting a SQL statement.
  356. The wrapped exception object is available in the
  357. :attr:`~.StatementError.orig` attribute. Its type and properties are
  358. DB-API implementation specific.
  359. """
  360. code = "dbapi"
  361. @classmethod
  362. def instance(
  363. cls,
  364. statement,
  365. params,
  366. orig,
  367. dbapi_base_err,
  368. hide_parameters=False,
  369. connection_invalidated=False,
  370. dialect=None,
  371. ismulti=None,
  372. ):
  373. # Don't ever wrap these, just return them directly as if
  374. # DBAPIError didn't exist.
  375. if (
  376. isinstance(orig, BaseException) and not isinstance(orig, Exception)
  377. ) or isinstance(orig, DontWrapMixin):
  378. return orig
  379. if orig is not None:
  380. # not a DBAPI error, statement is present.
  381. # raise a StatementError
  382. if isinstance(orig, SQLAlchemyError) and statement:
  383. return StatementError(
  384. "(%s.%s) %s"
  385. % (
  386. orig.__class__.__module__,
  387. orig.__class__.__name__,
  388. orig.args[0],
  389. ),
  390. statement,
  391. params,
  392. orig,
  393. hide_parameters=hide_parameters,
  394. code=orig.code,
  395. ismulti=ismulti,
  396. )
  397. elif not isinstance(orig, dbapi_base_err) and statement:
  398. return StatementError(
  399. "(%s.%s) %s"
  400. % (
  401. orig.__class__.__module__,
  402. orig.__class__.__name__,
  403. orig,
  404. ),
  405. statement,
  406. params,
  407. orig,
  408. hide_parameters=hide_parameters,
  409. ismulti=ismulti,
  410. )
  411. glob = globals()
  412. for super_ in orig.__class__.__mro__:
  413. name = super_.__name__
  414. if dialect:
  415. name = dialect.dbapi_exception_translation_map.get(
  416. name, name
  417. )
  418. if name in glob and issubclass(glob[name], DBAPIError):
  419. cls = glob[name]
  420. break
  421. return cls(
  422. statement,
  423. params,
  424. orig,
  425. connection_invalidated=connection_invalidated,
  426. hide_parameters=hide_parameters,
  427. code=cls.code,
  428. ismulti=ismulti,
  429. )
  430. def __reduce__(self):
  431. return (
  432. self.__class__,
  433. (
  434. self.statement,
  435. self.params,
  436. self.orig,
  437. self.hide_parameters,
  438. self.connection_invalidated,
  439. self.__dict__.get("code"),
  440. self.ismulti,
  441. ),
  442. {"detail": self.detail},
  443. )
  444. def __init__(
  445. self,
  446. statement,
  447. params,
  448. orig,
  449. hide_parameters=False,
  450. connection_invalidated=False,
  451. code=None,
  452. ismulti=None,
  453. ):
  454. try:
  455. text = str(orig)
  456. except Exception as e:
  457. text = "Error in str() of DB-API-generated exception: " + str(e)
  458. StatementError.__init__(
  459. self,
  460. "(%s.%s) %s"
  461. % (orig.__class__.__module__, orig.__class__.__name__, text),
  462. statement,
  463. params,
  464. orig,
  465. hide_parameters,
  466. code=code,
  467. ismulti=ismulti,
  468. )
  469. self.connection_invalidated = connection_invalidated
  470. class InterfaceError(DBAPIError):
  471. """Wraps a DB-API InterfaceError."""
  472. code = "rvf5"
  473. class DatabaseError(DBAPIError):
  474. """Wraps a DB-API DatabaseError."""
  475. code = "4xp6"
  476. class DataError(DatabaseError):
  477. """Wraps a DB-API DataError."""
  478. code = "9h9h"
  479. class OperationalError(DatabaseError):
  480. """Wraps a DB-API OperationalError."""
  481. code = "e3q8"
  482. class IntegrityError(DatabaseError):
  483. """Wraps a DB-API IntegrityError."""
  484. code = "gkpj"
  485. class InternalError(DatabaseError):
  486. """Wraps a DB-API InternalError."""
  487. code = "2j85"
  488. class ProgrammingError(DatabaseError):
  489. """Wraps a DB-API ProgrammingError."""
  490. code = "f405"
  491. class NotSupportedError(DatabaseError):
  492. """Wraps a DB-API NotSupportedError."""
  493. code = "tw8g"
  494. # Warnings
  495. class SADeprecationWarning(HasDescriptionCode, DeprecationWarning):
  496. """Issued for usage of deprecated APIs."""
  497. deprecated_since = None
  498. "Indicates the version that started raising this deprecation warning"
  499. class Base20DeprecationWarning(SADeprecationWarning):
  500. """Issued for usage of APIs specifically deprecated or legacy in
  501. SQLAlchemy 2.0.
  502. .. seealso::
  503. :ref:`error_b8d9`.
  504. :ref:`deprecation_20_mode`
  505. """
  506. deprecated_since = "1.4"
  507. "Indicates the version that started raising this deprecation warning"
  508. def __str__(self):
  509. return (
  510. super(Base20DeprecationWarning, self).__str__()
  511. + " (Background on SQLAlchemy 2.0 at: https://sqlalche.me/e/b8d9)"
  512. )
  513. class LegacyAPIWarning(Base20DeprecationWarning):
  514. """indicates an API that is in 'legacy' status, a long term deprecation."""
  515. class RemovedIn20Warning(Base20DeprecationWarning):
  516. """indicates an API that will be fully removed in SQLAlchemy 2.0."""
  517. class MovedIn20Warning(RemovedIn20Warning):
  518. """Subtype of RemovedIn20Warning to indicate an API that moved only."""
  519. class SAPendingDeprecationWarning(PendingDeprecationWarning):
  520. """A similar warning as :class:`_exc.SADeprecationWarning`, this warning
  521. is not used in modern versions of SQLAlchemy.
  522. """
  523. deprecated_since = None
  524. "Indicates the version that started raising this deprecation warning"
  525. class SAWarning(HasDescriptionCode, RuntimeWarning):
  526. """Issued at runtime."""