You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

707 lines
20KB

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