summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/sqlalchemy/dialects/mssql/base.py24
-rw-r--r--lib/sqlalchemy/dialects/mysql/base.py19
-rw-r--r--lib/sqlalchemy/dialects/sqlite/aiosqlite.py7
-rw-r--r--lib/sqlalchemy/dialects/sqlite/base.py9
-rw-r--r--lib/sqlalchemy/engine/_py_processors.py13
-rw-r--r--lib/sqlalchemy/engine/base.py45
-rw-r--r--lib/sqlalchemy/engine/cursor.py40
-rw-r--r--lib/sqlalchemy/engine/result.py2
-rw-r--r--lib/sqlalchemy/event/base.py11
-rw-r--r--lib/sqlalchemy/ext/associationproxy.py22
-rw-r--r--lib/sqlalchemy/ext/compiler.py31
-rw-r--r--lib/sqlalchemy/ext/indexable.py5
-rw-r--r--lib/sqlalchemy/orm/attributes.py94
-rw-r--r--lib/sqlalchemy/orm/base.py9
-rw-r--r--lib/sqlalchemy/orm/clsregistry.py17
-rw-r--r--lib/sqlalchemy/orm/context.py22
-rw-r--r--lib/sqlalchemy/orm/mapper.py88
-rw-r--r--lib/sqlalchemy/orm/persistence.py24
-rw-r--r--lib/sqlalchemy/orm/relationships.py92
-rw-r--r--lib/sqlalchemy/orm/session.py84
-rw-r--r--lib/sqlalchemy/orm/strategy_options.py9
-rw-r--r--lib/sqlalchemy/orm/sync.py37
-rw-r--r--lib/sqlalchemy/sql/base.py27
-rw-r--r--lib/sqlalchemy/sql/coercions.py23
-rw-r--r--lib/sqlalchemy/sql/compiler.py42
-rw-r--r--lib/sqlalchemy/sql/ddl.py33
-rw-r--r--lib/sqlalchemy/sql/elements.py70
-rw-r--r--lib/sqlalchemy/sql/lambdas.py33
-rw-r--r--lib/sqlalchemy/sql/schema.py41
-rw-r--r--lib/sqlalchemy/sql/selectable.py26
-rw-r--r--lib/sqlalchemy/sql/sqltypes.py42
-rw-r--r--lib/sqlalchemy/testing/exclusions.py2
-rw-r--r--lib/sqlalchemy/util/__init__.py3
-rw-r--r--lib/sqlalchemy/util/compat.py52
-rw-r--r--lib/sqlalchemy/util/langhelpers.py7
-rw-r--r--lib/sqlalchemy/util/queue.py21
-rw-r--r--test/aaa_profiling/test_memusage.py14
-rw-r--r--test/base/test_utils.py60
38 files changed, 405 insertions, 795 deletions
diff --git a/lib/sqlalchemy/dialects/mssql/base.py b/lib/sqlalchemy/dialects/mssql/base.py
index 5b38c4bb5..84f8e72f0 100644
--- a/lib/sqlalchemy/dialects/mssql/base.py
+++ b/lib/sqlalchemy/dialects/mssql/base.py
@@ -3101,22 +3101,16 @@ class MSDialect(default.DefaultDialect):
{"p1": self._temp_table_name_like_pattern(tablename)},
).one()
except exc.MultipleResultsFound as me:
- util.raise_(
- exc.UnreflectableTableError(
- "Found more than one temporary table named '%s' in tempdb "
- "at this time. Cannot reliably resolve that name to its "
- "internal table name." % tablename
- ),
- replace_context=me,
- )
+ raise exc.UnreflectableTableError(
+ "Found more than one temporary table named '%s' in tempdb "
+ "at this time. Cannot reliably resolve that name to its "
+ "internal table name." % tablename
+ ) from me
except exc.NoResultFound as ne:
- util.raise_(
- exc.NoSuchTableError(
- "Unable to find a temporary table named '%s' in tempdb."
- % tablename
- ),
- replace_context=ne,
- )
+ raise exc.NoSuchTableError(
+ "Unable to find a temporary table named '%s' in tempdb."
+ % tablename
+ ) from ne
@reflection.cache
@_db_plus_owner
diff --git a/lib/sqlalchemy/dialects/mysql/base.py b/lib/sqlalchemy/dialects/mysql/base.py
index 50bae40b8..5be057495 100644
--- a/lib/sqlalchemy/dialects/mysql/base.py
+++ b/lib/sqlalchemy/dialects/mysql/base.py
@@ -3159,7 +3159,7 @@ class MySQLDialect(default.DefaultDialect):
).exec_driver_sql(st)
except exc.DBAPIError as e:
if self._extract_error_code(e.orig) == 1146:
- util.raise_(exc.NoSuchTableError(full_name), replace_context=e)
+ raise exc.NoSuchTableError(full_name) from e
else:
raise
row = self._compat_first(rp, charset=charset)
@@ -3183,17 +3183,14 @@ class MySQLDialect(default.DefaultDialect):
except exc.DBAPIError as e:
code = self._extract_error_code(e.orig)
if code == 1146:
- util.raise_(
- exc.NoSuchTableError(full_name), replace_context=e
- )
+ raise exc.NoSuchTableError(full_name) from e
+
elif code == 1356:
- util.raise_(
- exc.UnreflectableTableError(
- "Table or view named %s could not be "
- "reflected: %s" % (full_name, e)
- ),
- replace_context=e,
- )
+ raise exc.UnreflectableTableError(
+ "Table or view named %s could not be "
+ "reflected: %s" % (full_name, e)
+ ) from e
+
else:
raise
rows = self._compat_fetchall(rp, charset=charset)
diff --git a/lib/sqlalchemy/dialects/sqlite/aiosqlite.py b/lib/sqlalchemy/dialects/sqlite/aiosqlite.py
index 4319e2661..0bc8d5cf1 100644
--- a/lib/sqlalchemy/dialects/sqlite/aiosqlite.py
+++ b/lib/sqlalchemy/dialects/sqlite/aiosqlite.py
@@ -221,10 +221,9 @@ class AsyncAdapt_aiosqlite_connection(AdaptedConnection):
isinstance(error, ValueError)
and error.args[0] == "no active connection"
):
- util.raise_(
- self.dbapi.sqlite.OperationalError("no active connection"),
- from_=error,
- )
+ raise self.dbapi.sqlite.OperationalError(
+ "no active connection"
+ ) from error
else:
raise error
diff --git a/lib/sqlalchemy/dialects/sqlite/base.py b/lib/sqlalchemy/dialects/sqlite/base.py
index d238de1ab..dd43dbc79 100644
--- a/lib/sqlalchemy/dialects/sqlite/base.py
+++ b/lib/sqlalchemy/dialects/sqlite/base.py
@@ -1250,12 +1250,9 @@ class SQLiteCompiler(compiler.SQLCompiler):
self.process(extract.expr, **kw),
)
except KeyError as err:
- util.raise_(
- exc.CompileError(
- "%s is not a valid extract argument." % extract.field
- ),
- replace_context=err,
- )
+ raise exc.CompileError(
+ "%s is not a valid extract argument." % extract.field
+ ) from err
def limit_clause(self, select, **kw):
text = ""
diff --git a/lib/sqlalchemy/engine/_py_processors.py b/lib/sqlalchemy/engine/_py_processors.py
index db722a978..ea48bb493 100644
--- a/lib/sqlalchemy/engine/_py_processors.py
+++ b/lib/sqlalchemy/engine/_py_processors.py
@@ -16,8 +16,6 @@ They all share one common characteristic: None is passed through unchanged.
import datetime
import re
-from .. import util
-
def str_to_datetime_processor_factory(regexp, type_):
rmatch = regexp.match
@@ -32,13 +30,10 @@ def str_to_datetime_processor_factory(regexp, type_):
try:
m = rmatch(value)
except TypeError as err:
- util.raise_(
- ValueError(
- "Couldn't parse %s string '%r' "
- "- value is not a string." % (type_.__name__, value)
- ),
- from_=err,
- )
+ raise ValueError(
+ "Couldn't parse %s string '%r' "
+ "- value is not a string." % (type_.__name__, value)
+ ) from err
if m is None:
raise ValueError(
"Couldn't parse %s string: "
diff --git a/lib/sqlalchemy/engine/base.py b/lib/sqlalchemy/engine/base.py
index b11ffd871..4f8535447 100644
--- a/lib/sqlalchemy/engine/base.py
+++ b/lib/sqlalchemy/engine/base.py
@@ -1115,9 +1115,7 @@ class Connection(ConnectionEventsTarget):
try:
meth = statement._execute_on_connection
except AttributeError as err:
- util.raise_(
- exc.ObjectNotExecutableError(statement), replace_context=err
- )
+ raise exc.ObjectNotExecutableError(statement) from err
else:
return meth(
self,
@@ -1670,21 +1668,15 @@ class Connection(ConnectionEventsTarget):
invalidate_pool_on_disconnect = not is_exit_exception
if self._reentrant_error:
- util.raise_(
- exc.DBAPIError.instance(
- statement,
- parameters,
- e,
- self.dialect.dbapi.Error,
- hide_parameters=self.engine.hide_parameters,
- dialect=self.dialect,
- ismulti=context.executemany
- if context is not None
- else None,
- ),
- with_traceback=exc_info[2],
- from_=e,
- )
+ raise exc.DBAPIError.instance(
+ statement,
+ parameters,
+ e,
+ self.dialect.dbapi.Error,
+ hide_parameters=self.engine.hide_parameters,
+ dialect=self.dialect,
+ ismulti=context.executemany if context is not None else None,
+ ).with_traceback(exc_info[2]) from e
self._reentrant_error = True
try:
# non-DBAPI error - if we already got a context,
@@ -1773,14 +1765,11 @@ class Connection(ConnectionEventsTarget):
self._rollback_impl()
if newraise:
- util.raise_(newraise, with_traceback=exc_info[2], from_=e)
+ raise newraise.with_traceback(exc_info[2]) from e
elif should_wrap:
- util.raise_(
- sqlalchemy_exception, with_traceback=exc_info[2], from_=e
- )
+ raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
else:
- util.raise_(exc_info[1], with_traceback=exc_info[2])
-
+ raise exc_info[1].with_traceback(exc_info[2])
finally:
del self._reentrant_error
if self._is_disconnect:
@@ -1844,13 +1833,11 @@ class Connection(ConnectionEventsTarget):
) = ctx.is_disconnect
if newraise:
- util.raise_(newraise, with_traceback=exc_info[2], from_=e)
+ raise newraise.with_traceback(exc_info[2]) from e
elif should_wrap:
- util.raise_(
- sqlalchemy_exception, with_traceback=exc_info[2], from_=e
- )
+ raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
else:
- util.raise_(exc_info[1], with_traceback=exc_info[2])
+ raise exc_info[1].with_traceback(exc_info[2])
def _run_ddl_visitor(self, visitorcallable, element, **kwargs):
"""run a DDL visitor.
diff --git a/lib/sqlalchemy/engine/cursor.py b/lib/sqlalchemy/engine/cursor.py
index 8247987fa..bd2c092a7 100644
--- a/lib/sqlalchemy/engine/cursor.py
+++ b/lib/sqlalchemy/engine/cursor.py
@@ -587,21 +587,15 @@ class CursorResultMetaData(ResultMetaData):
if raiseerr:
if self._unpickled and isinstance(key, elements.ColumnElement):
- util.raise_(
- exc.NoSuchColumnError(
- "Row was unpickled; lookup by ColumnElement "
- "is unsupported"
- ),
- replace_context=err,
- )
+ raise exc.NoSuchColumnError(
+ "Row was unpickled; lookup by ColumnElement "
+ "is unsupported"
+ ) from err
else:
- util.raise_(
- exc.NoSuchColumnError(
- "Could not locate column in row for column '%s'"
- % util.string_or_unprintable(key)
- ),
- replace_context=err,
- )
+ raise exc.NoSuchColumnError(
+ "Could not locate column in row for column '%s'"
+ % util.string_or_unprintable(key)
+ ) from err
else:
return None
@@ -763,10 +757,9 @@ class NoCursorDQLFetchStrategy(NoCursorFetchStrategy):
def _non_result(self, result, default, err=None):
if result.closed:
- util.raise_(
- exc.ResourceClosedError("This result object is closed."),
- replace_context=err,
- )
+ raise exc.ResourceClosedError(
+ "This result object is closed."
+ ) from err
else:
return default
@@ -1058,13 +1051,10 @@ class _NoResultMetaData(ResultMetaData):
returns_rows = False
def _we_dont_return_rows(self, err=None):
- util.raise_(
- exc.ResourceClosedError(
- "This result object does not return rows. "
- "It has been closed automatically."
- ),
- replace_context=err,
- )
+ raise exc.ResourceClosedError(
+ "This result object does not return rows. "
+ "It has been closed automatically."
+ ) from err
def _index_for_key(self, keys, raiseerr):
self._we_dont_return_rows()
diff --git a/lib/sqlalchemy/engine/result.py b/lib/sqlalchemy/engine/result.py
index ff292c7d7..7d496838a 100644
--- a/lib/sqlalchemy/engine/result.py
+++ b/lib/sqlalchemy/engine/result.py
@@ -47,7 +47,7 @@ class ResultMetaData:
def _key_fallback(self, key, err, raiseerr=True):
assert raiseerr
- util.raise_(KeyError(key), replace_context=err)
+ raise KeyError(key) from err
def _raise_for_nonint(self, key):
raise TypeError(
diff --git a/lib/sqlalchemy/event/base.py b/lib/sqlalchemy/event/base.py
index 1041647c8..8509a1b44 100644
--- a/lib/sqlalchemy/event/base.py
+++ b/lib/sqlalchemy/event/base.py
@@ -320,13 +320,10 @@ class dispatcher:
try:
obj.__dict__["dispatch"] = disp
except AttributeError as ae:
- util.raise_(
- TypeError(
- "target %r doesn't have __dict__, should it be "
- "defining _slots_dispatch?" % (obj,)
- ),
- replace_context=ae,
- )
+ raise TypeError(
+ "target %r doesn't have __dict__, should it be "
+ "defining _slots_dispatch?" % (obj,)
+ ) from ae
return disp
diff --git a/lib/sqlalchemy/ext/associationproxy.py b/lib/sqlalchemy/ext/associationproxy.py
index 9e8f84f46..4dfcae6d3 100644
--- a/lib/sqlalchemy/ext/associationproxy.py
+++ b/lib/sqlalchemy/ext/associationproxy.py
@@ -362,13 +362,10 @@ class AssociationProxyInstance:
# this was never asserted before but this should be made clear.
if not isinstance(prop, orm.RelationshipProperty):
- util.raise_(
- NotImplementedError(
- "association proxy to a non-relationship "
- "intermediary is not supported"
- ),
- replace_context=None,
- )
+ raise NotImplementedError(
+ "association proxy to a non-relationship "
+ "intermediary is not supported"
+ ) from None
target_class = prop.mapper.class_
@@ -1327,13 +1324,10 @@ class _AssociationDict(_AssociationCollection):
for k, v in seq_or_map:
self[k] = v
except ValueError as err:
- util.raise_(
- ValueError(
- "dictionary update sequence "
- "requires 2-element tuples"
- ),
- replace_context=err,
- )
+ raise ValueError(
+ "dictionary update sequence "
+ "requires 2-element tuples"
+ ) from err
for key, value in kw:
self[key] = value
diff --git a/lib/sqlalchemy/ext/compiler.py b/lib/sqlalchemy/ext/compiler.py
index 2b3e4cd7c..d87e1f663 100644
--- a/lib/sqlalchemy/ext/compiler.py
+++ b/lib/sqlalchemy/ext/compiler.py
@@ -444,7 +444,6 @@ Example usage::
"""
from .. import exc
-from .. import util
from ..sql import sqltypes
@@ -469,15 +468,12 @@ def compiles(class_, *specs):
try:
return existing_dispatch(element, compiler, **kw)
except exc.UnsupportedCompilationError as uce:
- util.raise_(
- exc.UnsupportedCompilationError(
- compiler,
- type(element),
- message="%s construct has no default "
- "compilation handler." % type(element),
- ),
- from_=uce,
- )
+ raise exc.UnsupportedCompilationError(
+ compiler,
+ type(element),
+ message="%s construct has no default "
+ "compilation handler." % type(element),
+ ) from uce
existing.specs["default"] = _wrap_existing_dispatch
@@ -522,15 +518,12 @@ class _dispatcher:
try:
fn = self.specs["default"]
except KeyError as ke:
- util.raise_(
- exc.UnsupportedCompilationError(
- compiler,
- type(element),
- message="%s construct has no default "
- "compilation handler." % type(element),
- ),
- replace_context=ke,
- )
+ raise exc.UnsupportedCompilationError(
+ compiler,
+ type(element),
+ message="%s construct has no default "
+ "compilation handler." % type(element),
+ ) from ke
# if compilation includes add_to_result_map, collect add_to_result_map
# arguments from the user-defined callable, which are probably none
diff --git a/lib/sqlalchemy/ext/indexable.py b/lib/sqlalchemy/ext/indexable.py
index 70673ac26..a86af3d16 100644
--- a/lib/sqlalchemy/ext/indexable.py
+++ b/lib/sqlalchemy/ext/indexable.py
@@ -222,7 +222,6 @@ The above query will render::
""" # noqa
from .. import inspect
-from .. import util
from ..ext.hybrid import hybrid_property
from ..orm.attributes import flag_modified
@@ -302,7 +301,7 @@ class index_property(hybrid_property): # noqa
def _fget_default(self, err=None):
if self.default == self._NO_DEFAULT_ARGUMENT:
- util.raise_(AttributeError(self.attr_name), replace_context=err)
+ raise AttributeError(self.attr_name) from err
else:
return self.default
@@ -337,7 +336,7 @@ class index_property(hybrid_property): # noqa
try:
del column_value[self.index]
except KeyError as err:
- util.raise_(AttributeError(self.attr_name), replace_context=err)
+ raise AttributeError(self.attr_name) from err
else:
setattr(instance, attr_name, column_value)
flag_modified(instance, attr_name)
diff --git a/lib/sqlalchemy/orm/attributes.py b/lib/sqlalchemy/orm/attributes.py
index bf8d69b4e..dce008a67 100644
--- a/lib/sqlalchemy/orm/attributes.py
+++ b/lib/sqlalchemy/orm/attributes.py
@@ -238,14 +238,11 @@ class QueryableAttribute(
try:
anno = ce._annotate
except AttributeError as ae:
- util.raise_(
- exc.InvalidRequestError(
- 'When interpreting attribute "%s" as a SQL expression, '
- "expected __clause_element__() to return "
- "a ClauseElement object, got: %r" % (self, ce)
- ),
- from_=ae,
- )
+ raise exc.InvalidRequestError(
+ 'When interpreting attribute "%s" as a SQL expression, '
+ "expected __clause_element__() to return "
+ "a ClauseElement object, got: %r" % (self, ce)
+ ) from ae
else:
return anno(annotations)
@@ -328,19 +325,16 @@ class QueryableAttribute(
try:
return getattr(self.comparator, key)
except AttributeError as err:
- util.raise_(
- AttributeError(
- "Neither %r object nor %r object associated with %s "
- "has an attribute %r"
- % (
- type(self).__name__,
- type(self.comparator).__name__,
- self,
- key,
- )
- ),
- replace_context=err,
- )
+ raise AttributeError(
+ "Neither %r object nor %r object associated with %s "
+ "has an attribute %r"
+ % (
+ type(self).__name__,
+ type(self.comparator).__name__,
+ self,
+ key,
+ )
+ ) from err
def __str__(self):
return "%s.%s" % (self.class_.__name__, self.key)
@@ -471,10 +465,7 @@ class InstrumentedAttribute(Mapped):
try:
state = instance_state(instance)
except AttributeError as err:
- util.raise_(
- orm_exc.UnmappedInstanceError(instance),
- replace_context=err,
- )
+ raise orm_exc.UnmappedInstanceError(instance) from err
return self.impl.get(state, dict_)
@@ -601,38 +592,30 @@ def create_proxied_attribute(descriptor):
return getattr(descriptor, attribute)
except AttributeError as err:
if attribute == "comparator":
- util.raise_(
- AttributeError("comparator"), replace_context=err
- )
+ raise AttributeError("comparator") from err
try:
# comparator itself might be unreachable
comparator = self.comparator
except AttributeError as err2:
- util.raise_(
- AttributeError(
- "Neither %r object nor unconfigured comparator "
- "object associated with %s has an attribute %r"
- % (type(descriptor).__name__, self, attribute)
- ),
- replace_context=err2,
- )
+ raise AttributeError(
+ "Neither %r object nor unconfigured comparator "
+ "object associated with %s has an attribute %r"
+ % (type(descriptor).__name__, self, attribute)
+ ) from err2
else:
try:
return getattr(comparator, attribute)
except AttributeError as err3:
- util.raise_(
- AttributeError(
- "Neither %r object nor %r object "
- "associated with %s has an attribute %r"
- % (
- type(descriptor).__name__,
- type(comparator).__name__,
- self,
- attribute,
- )
- ),
- replace_context=err3,
- )
+ raise AttributeError(
+ "Neither %r object nor %r object "
+ "associated with %s has an attribute %r"
+ % (
+ type(descriptor).__name__,
+ type(comparator).__name__,
+ self,
+ attribute,
+ )
+ ) from err3
Proxy.__name__ = type(descriptor).__name__ + "Proxy"
@@ -944,14 +927,11 @@ class AttributeImpl:
return dict_[key]
except KeyError as err:
# TODO: no test coverage here.
- util.raise_(
- KeyError(
- "Deferred loader for attribute "
- "%r failed to populate "
- "correctly" % key
- ),
- replace_context=err,
- )
+ raise KeyError(
+ "Deferred loader for attribute "
+ "%r failed to populate "
+ "correctly" % key
+ ) from err
elif value is not ATTR_EMPTY:
return self.set_committed_value(state, dict_, value)
diff --git a/lib/sqlalchemy/orm/base.py b/lib/sqlalchemy/orm/base.py
index 2cd4134d6..c79592625 100644
--- a/lib/sqlalchemy/orm/base.py
+++ b/lib/sqlalchemy/orm/base.py
@@ -396,12 +396,9 @@ def _entity_descriptor(entity, key):
try:
return getattr(entity, key)
except AttributeError as err:
- util.raise_(
- sa_exc.InvalidRequestError(
- "Entity '%s' has no property '%s'" % (description, key)
- ),
- replace_context=err,
- )
+ raise sa_exc.InvalidRequestError(
+ "Entity '%s' has no property '%s'" % (description, key)
+ ) from err
_state_mapper = util.dottedgetter("manager.mapper")
diff --git a/lib/sqlalchemy/orm/clsregistry.py b/lib/sqlalchemy/orm/clsregistry.py
index 0d45fb40d..bd02aea4f 100644
--- a/lib/sqlalchemy/orm/clsregistry.py
+++ b/lib/sqlalchemy/orm/clsregistry.py
@@ -372,16 +372,13 @@ class _class_resolver:
return self.fallback[key]
def _raise_for_name(self, name, err):
- util.raise_(
- exc.InvalidRequestError(
- "When initializing mapper %s, expression %r failed to "
- "locate a name (%r). If this is a class name, consider "
- "adding this relationship() to the %r class after "
- "both dependent classes have been defined."
- % (self.prop.parent, self.arg, name, self.cls)
- ),
- from_=err,
- )
+ raise exc.InvalidRequestError(
+ "When initializing mapper %s, expression %r failed to "
+ "locate a name (%r). If this is a class name, consider "
+ "adding this relationship() to the %r class after "
+ "both dependent classes have been defined."
+ % (self.prop.parent, self.arg, name, self.cls)
+ ) from err
def _resolve_name(self):
name = self.arg
diff --git a/lib/sqlalchemy/orm/context.py b/lib/sqlalchemy/orm/context.py
index f438b0b3a..e59bc4871 100644
--- a/lib/sqlalchemy/orm/context.py
+++ b/lib/sqlalchemy/orm/context.py
@@ -1403,13 +1403,10 @@ class ORMSelectCompileState(ORMCompileState, SelectState):
try:
right = right.entity
except AttributeError as err:
- util.raise_(
- sa_exc.ArgumentError(
- "Join target %s does not refer to a "
- "mapped entity" % right
- ),
- replace_context=err,
- )
+ raise sa_exc.ArgumentError(
+ "Join target %s does not refer to a "
+ "mapped entity" % right
+ ) from err
left = onclause._parententity
@@ -1558,13 +1555,10 @@ class ORMSelectCompileState(ORMCompileState, SelectState):
try:
right = right.entity
except AttributeError as err:
- util.raise_(
- sa_exc.ArgumentError(
- "Join target %s does not refer to a "
- "mapped entity" % right
- ),
- replace_context=err,
- )
+ raise sa_exc.ArgumentError(
+ "Join target %s does not refer to a "
+ "mapped entity" % right
+ ) from err
left = onclause._parententity
diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py
index a94c6bfa7..272329c30 100644
--- a/lib/sqlalchemy/orm/mapper.py
+++ b/lib/sqlalchemy/orm/mapper.py
@@ -1018,45 +1018,39 @@ class Mapper(
except sa_exc.NoForeignKeysError as nfe:
assert self.inherits.local_table is not None
assert self.local_table is not None
- util.raise_(
- sa_exc.NoForeignKeysError(
- "Can't determine the inherit condition "
- "between inherited table '%s' and "
- "inheriting "
- "table '%s'; tables have no "
- "foreign key relationships established. "
- "Please ensure the inheriting table has "
- "a foreign key relationship to the "
- "inherited "
- "table, or provide an "
- "'on clause' using "
- "the 'inherit_condition' mapper argument."
- % (
- self.inherits.local_table.description,
- self.local_table.description,
- )
- ),
- replace_context=nfe,
- )
+ raise sa_exc.NoForeignKeysError(
+ "Can't determine the inherit condition "
+ "between inherited table '%s' and "
+ "inheriting "
+ "table '%s'; tables have no "
+ "foreign key relationships established. "
+ "Please ensure the inheriting table has "
+ "a foreign key relationship to the "
+ "inherited "
+ "table, or provide an "
+ "'on clause' using "
+ "the 'inherit_condition' mapper argument."
+ % (
+ self.inherits.local_table.description,
+ self.local_table.description,
+ )
+ ) from nfe
except sa_exc.AmbiguousForeignKeysError as afe:
assert self.inherits.local_table is not None
assert self.local_table is not None
- util.raise_(
- sa_exc.AmbiguousForeignKeysError(
- "Can't determine the inherit condition "
- "between inherited table '%s' and "
- "inheriting "
- "table '%s'; tables have more than one "
- "foreign key relationship established. "
- "Please specify the 'on clause' using "
- "the 'inherit_condition' mapper argument."
- % (
- self.inherits.local_table.description,
- self.local_table.description,
- )
- ),
- replace_context=afe,
- )
+ raise sa_exc.AmbiguousForeignKeysError(
+ "Can't determine the inherit condition "
+ "between inherited table '%s' and "
+ "inheriting "
+ "table '%s'; tables have more than one "
+ "foreign key relationship established. "
+ "Please specify the 'on clause' using "
+ "the 'inherit_condition' mapper argument."
+ % (
+ self.inherits.local_table.description,
+ self.local_table.description,
+ )
+ ) from afe
self.persist_selectable = sql.join(
self.inherits.persist_selectable,
self.local_table,
@@ -1504,14 +1498,11 @@ class Mapper(
try:
self.polymorphic_on = self._props[self.polymorphic_on]
except KeyError as err:
- util.raise_(
- sa_exc.ArgumentError(
- "Can't determine polymorphic_on "
- "value '%s' - no attribute is "
- "mapped to this name." % self.polymorphic_on
- ),
- replace_context=err,
- )
+ raise sa_exc.ArgumentError(
+ "Can't determine polymorphic_on "
+ "value '%s' - no attribute is "
+ "mapped to this name." % self.polymorphic_on
+ ) from err
if self.polymorphic_on in self._columntoproperty:
# polymorphic_on is a column that is already mapped
@@ -2025,12 +2016,9 @@ class Mapper(
try:
return self._props[key]
except KeyError as err:
- util.raise_(
- sa_exc.InvalidRequestError(
- "Mapper '%s' has no property '%s'" % (self, key)
- ),
- replace_context=err,
- )
+ raise sa_exc.InvalidRequestError(
+ "Mapper '%s' has no property '%s'" % (self, key)
+ ) from err
def get_property_by_column(self, column):
"""Given a :class:`_schema.Column` object, return the
diff --git a/lib/sqlalchemy/orm/persistence.py b/lib/sqlalchemy/orm/persistence.py
index 6dd827b43..eebef31f7 100644
--- a/lib/sqlalchemy/orm/persistence.py
+++ b/lib/sqlalchemy/orm/persistence.py
@@ -1730,13 +1730,10 @@ def _sort_states(mapper, states):
persistent, key=mapper._persistent_sortkey_fn
)
except TypeError as err:
- util.raise_(
- sa_exc.InvalidRequestError(
- "Could not sort objects by primary key; primary key "
- "values must be sortable in Python (was: %s)" % err
- ),
- replace_context=err,
- )
+ raise sa_exc.InvalidRequestError(
+ "Could not sort objects by primary key; primary key "
+ "values must be sortable in Python (was: %s)" % err
+ ) from err
return (
sorted(pending, key=operator.attrgetter("insert_order"))
+ persistent_sorted
@@ -1942,14 +1939,11 @@ class BulkUDCompileState(CompileState):
return True
except evaluator.UnevaluatableError as err:
- util.raise_(
- sa_exc.InvalidRequestError(
- 'Could not evaluate current criteria in Python: "%s". '
- "Specify 'fetch' or False for the "
- "synchronize_session execution option." % err
- ),
- from_=err,
- )
+ raise sa_exc.InvalidRequestError(
+ 'Could not evaluate current criteria in Python: "%s". '
+ "Specify 'fetch' or False for the "
+ "synchronize_session execution option." % err
+ ) from err
if statement.__visit_name__ == "lambda_element":
# ._resolved is called on every LambdaElement in order to
diff --git a/lib/sqlalchemy/orm/relationships.py b/lib/sqlalchemy/orm/relationships.py
index 4293cf656..a597d9c4f 100644
--- a/lib/sqlalchemy/orm/relationships.py
+++ b/lib/sqlalchemy/orm/relationships.py
@@ -2758,63 +2758,49 @@ class JoinCondition:
)
except sa_exc.NoForeignKeysError as nfe:
if self.secondary is not None:
- util.raise_(
- sa_exc.NoForeignKeysError(
- "Could not determine join "
- "condition between parent/child tables on "
- "relationship %s - there are no foreign keys "
- "linking these tables via secondary table '%s'. "
- "Ensure that referencing columns are associated "
- "with a ForeignKey or ForeignKeyConstraint, or "
- "specify 'primaryjoin' and 'secondaryjoin' "
- "expressions." % (self.prop, self.secondary)
- ),
- from_=nfe,
- )
+ raise sa_exc.NoForeignKeysError(
+ "Could not determine join "
+ "condition between parent/child tables on "
+ "relationship %s - there are no foreign keys "
+ "linking these tables via secondary table '%s'. "
+ "Ensure that referencing columns are associated "
+ "with a ForeignKey or ForeignKeyConstraint, or "
+ "specify 'primaryjoin' and 'secondaryjoin' "
+ "expressions." % (self.prop, self.secondary)
+ ) from nfe
else:
- util.raise_(
- sa_exc.NoForeignKeysError(
- "Could not determine join "
- "condition between parent/child tables on "
- "relationship %s - there are no foreign keys "
- "linking these tables. "
- "Ensure that referencing columns are associated "
- "with a ForeignKey or ForeignKeyConstraint, or "
- "specify a 'primaryjoin' expression." % self.prop
- ),
- from_=nfe,
- )
+ raise sa_exc.NoForeignKeysError(
+ "Could not determine join "
+ "condition between parent/child tables on "
+ "relationship %s - there are no foreign keys "
+ "linking these tables. "
+ "Ensure that referencing columns are associated "
+ "with a ForeignKey or ForeignKeyConstraint, or "
+ "specify a 'primaryjoin' expression." % self.prop
+ ) from nfe
except sa_exc.AmbiguousForeignKeysError as afe:
if self.secondary is not None:
- util.raise_(
- sa_exc.AmbiguousForeignKeysError(
- "Could not determine join "
- "condition between parent/child tables on "
- "relationship %s - there are multiple foreign key "
- "paths linking the tables via secondary table '%s'. "
- "Specify the 'foreign_keys' "
- "argument, providing a list of those columns which "
- "should be counted as containing a foreign key "
- "reference from the secondary table to each of the "
- "parent and child tables."
- % (self.prop, self.secondary)
- ),
- from_=afe,
- )
+ raise sa_exc.AmbiguousForeignKeysError(
+ "Could not determine join "
+ "condition between parent/child tables on "
+ "relationship %s - there are multiple foreign key "
+ "paths linking the tables via secondary table '%s'. "
+ "Specify the 'foreign_keys' "
+ "argument, providing a list of those columns which "
+ "should be counted as containing a foreign key "
+ "reference from the secondary table to each of the "
+ "parent and child tables." % (self.prop, self.secondary)
+ ) from afe
else:
- util.raise_(
- sa_exc.AmbiguousForeignKeysError(
- "Could not determine join "
- "condition between parent/child tables on "
- "relationship %s - there are multiple foreign key "
- "paths linking the tables. Specify the "
- "'foreign_keys' argument, providing a list of those "
- "columns which should be counted as containing a "
- "foreign key reference to the parent table."
- % self.prop
- ),
- from_=afe,
- )
+ raise sa_exc.AmbiguousForeignKeysError(
+ "Could not determine join "
+ "condition between parent/child tables on "
+ "relationship %s - there are multiple foreign key "
+ "paths linking the tables. Specify the "
+ "'foreign_keys' argument, providing a list of those "
+ "columns which should be counted as containing a "
+ "foreign key reference to the parent table." % self.prop
+ ) from afe
@property
def primaryjoin_minus_local(self):
diff --git a/lib/sqlalchemy/orm/session.py b/lib/sqlalchemy/orm/session.py
index e921bb8f0..161dd432d 100644
--- a/lib/sqlalchemy/orm/session.py
+++ b/lib/sqlalchemy/orm/session.py
@@ -898,7 +898,7 @@ class SessionTransaction(TransactionalContext):
self._parent._rollback_exception = sys.exc_info()[1]
if rollback_err:
- util.raise_(rollback_err[1], with_traceback=rollback_err[2])
+ raise rollback_err[1].with_traceback(rollback_err[2])
sess.dispatch.after_soft_rollback(sess, self)
@@ -1762,12 +1762,9 @@ class Session(_SessionClassMethods):
insp = inspect(key)
except sa_exc.NoInspectionAvailable as err:
if not isinstance(key, type):
- util.raise_(
- sa_exc.ArgumentError(
- "Not an acceptable bind target: %s" % key
- ),
- replace_context=err,
- )
+ raise sa_exc.ArgumentError(
+ "Not an acceptable bind target: %s" % key
+ ) from err
else:
self.__binds[key] = bind
else:
@@ -1949,10 +1946,7 @@ class Session(_SessionClassMethods):
mapper = inspect(mapper)
except sa_exc.NoInspectionAvailable as err:
if isinstance(mapper, type):
- util.raise_(
- exc.UnmappedClassError(mapper),
- replace_context=err,
- )
+ raise exc.UnmappedClassError(mapper) from err
else:
raise
@@ -2113,7 +2107,7 @@ class Session(_SessionClassMethods):
"consider using a session.no_autoflush block if this "
"flush is occurring prematurely"
)
- util.raise_(e, with_traceback=sys.exc_info()[2])
+ raise e.with_traceback(sys.exc_info()[2])
def refresh(self, instance, attribute_names=None, with_for_update=None):
"""Expire and refresh attributes on the given instance.
@@ -2176,10 +2170,7 @@ class Session(_SessionClassMethods):
try:
state = attributes.instance_state(instance)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(instance),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(instance) from err
self._expire_state(state, attribute_names)
@@ -2283,10 +2274,7 @@ class Session(_SessionClassMethods):
try:
state = attributes.instance_state(instance)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(instance),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(instance) from err
self._expire_state(state, attribute_names)
def _expire_state(self, state, attribute_names):
@@ -2322,10 +2310,7 @@ class Session(_SessionClassMethods):
try:
state = attributes.instance_state(instance)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(instance),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(instance) from err
if state.session_id is not self.hash_key:
raise sa_exc.InvalidRequestError(
"Instance %s is not present in this Session" % state_str(state)
@@ -2477,10 +2462,7 @@ class Session(_SessionClassMethods):
try:
state = attributes.instance_state(instance)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(instance),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(instance) from err
self._save_or_update_state(state)
@@ -2515,10 +2497,7 @@ class Session(_SessionClassMethods):
try:
state = attributes.instance_state(instance)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(instance),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(instance) from err
self._delete_impl(state, instance, head=True)
@@ -2716,18 +2695,15 @@ class Session(_SessionClassMethods):
)
except KeyError as err:
- util.raise_(
- sa_exc.InvalidRequestError(
- "Incorrect names of values in identifier to formulate "
- "primary key for session.get(); primary key attribute "
- "names are %s"
- % ",".join(
- "'%s'" % prop.key
- for prop in mapper._identity_key_props
- )
- ),
- replace_context=err,
- )
+ raise sa_exc.InvalidRequestError(
+ "Incorrect names of values in identifier to formulate "
+ "primary key for session.get(); primary key attribute "
+ "names are %s"
+ % ",".join(
+ "'%s'" % prop.key
+ for prop in mapper._identity_key_props
+ )
+ ) from err
if (
not populate_existing
@@ -3139,10 +3115,7 @@ class Session(_SessionClassMethods):
try:
state = attributes.instance_state(obj)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(obj),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(obj) from err
to_attach = self._before_attach(state, obj)
state._load_pending = True
@@ -3187,10 +3160,7 @@ class Session(_SessionClassMethods):
try:
state = attributes.instance_state(instance)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(instance),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(instance) from err
return self._contains_state(state)
def __iter__(self):
@@ -3283,10 +3253,7 @@ class Session(_SessionClassMethods):
state = attributes.instance_state(o)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(o),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(o) from err
objset.add(state)
else:
objset = None
@@ -4211,10 +4178,7 @@ def object_session(instance):
try:
state = attributes.instance_state(instance)
except exc.NO_STATE as err:
- util.raise_(
- exc.UnmappedInstanceError(instance),
- replace_context=err,
- )
+ raise exc.UnmappedInstanceError(instance) from err
else:
return _state_session(state)
diff --git a/lib/sqlalchemy/orm/strategy_options.py b/lib/sqlalchemy/orm/strategy_options.py
index 02068adce..27c12658c 100644
--- a/lib/sqlalchemy/orm/strategy_options.py
+++ b/lib/sqlalchemy/orm/strategy_options.py
@@ -2056,12 +2056,9 @@ def _parse_attr_argument(attr):
try:
insp = inspect(attr)
except sa_exc.NoInspectionAvailable as err:
- util.raise_(
- sa_exc.ArgumentError(
- "expected ORM mapped attribute for loader strategy argument"
- ),
- from_=err,
- )
+ raise sa_exc.ArgumentError(
+ "expected ORM mapped attribute for loader strategy argument"
+ ) from err
if insp.is_property:
lead_entity = insp.parent
diff --git a/lib/sqlalchemy/orm/sync.py b/lib/sqlalchemy/orm/sync.py
index 9d684a2a8..7e67e9cb0 100644
--- a/lib/sqlalchemy/orm/sync.py
+++ b/lib/sqlalchemy/orm/sync.py
@@ -13,7 +13,6 @@ between instances based on join conditions.
from . import attributes
from . import exc
from . import util as orm_util
-from .. import util
def populate(
@@ -143,25 +142,19 @@ def _raise_col_to_prop(
isdest, source_mapper, source_column, dest_mapper, dest_column, err
):
if isdest:
- util.raise_(
- exc.UnmappedColumnError(
- "Can't execute sync rule for "
- "destination column '%s'; mapper '%s' does not map "
- "this column. Try using an explicit `foreign_keys` "
- "collection which does not include this column (or use "
- "a viewonly=True relation)." % (dest_column, dest_mapper)
- ),
- replace_context=err,
- )
+ raise exc.UnmappedColumnError(
+ "Can't execute sync rule for "
+ "destination column '%s'; mapper '%s' does not map "
+ "this column. Try using an explicit `foreign_keys` "
+ "collection which does not include this column (or use "
+ "a viewonly=True relation)." % (dest_column, dest_mapper)
+ ) from err
else:
- util.raise_(
- exc.UnmappedColumnError(
- "Can't execute sync rule for "
- "source column '%s'; mapper '%s' does not map this "
- "column. Try using an explicit `foreign_keys` "
- "collection which does not include destination column "
- "'%s' (or use a viewonly=True relation)."
- % (source_column, source_mapper, dest_column)
- ),
- replace_context=err,
- )
+ raise exc.UnmappedColumnError(
+ "Can't execute sync rule for "
+ "source column '%s'; mapper '%s' does not map this "
+ "column. Try using an explicit `foreign_keys` "
+ "collection which does not include destination column "
+ "'%s' (or use a viewonly=True relation)."
+ % (source_column, source_mapper, dest_column)
+ ) from err
diff --git a/lib/sqlalchemy/sql/base.py b/lib/sqlalchemy/sql/base.py
index 7ac253dd4..187651435 100644
--- a/lib/sqlalchemy/sql/base.py
+++ b/lib/sqlalchemy/sql/base.py
@@ -199,7 +199,7 @@ class _DialectArgView(collections_abc.MutableMapping):
try:
dialect, value_key = key.split("_", 1)
except ValueError as err:
- util.raise_(KeyError(key), replace_context=err)
+ raise KeyError(key) from err
else:
return dialect, value_key
@@ -209,7 +209,7 @@ class _DialectArgView(collections_abc.MutableMapping):
try:
opt = self.obj.dialect_options[dialect]
except exc.NoSuchModuleError as err:
- util.raise_(KeyError(key), replace_context=err)
+ raise KeyError(key) from err
else:
return opt[value_key]
@@ -217,12 +217,9 @@ class _DialectArgView(collections_abc.MutableMapping):
try:
dialect, value_key = self._key(key)
except KeyError as err:
- util.raise_(
- exc.ArgumentError(
- "Keys must be of the form <dialectname>_<argname>"
- ),
- replace_context=err,
- )
+ raise exc.ArgumentError(
+ "Keys must be of the form <dialectname>_<argname>"
+ ) from err
else:
self.obj.dialect_options[dialect][value_key] = value
@@ -1203,7 +1200,7 @@ class ColumnCollection:
return self._index[key]
except KeyError as err:
if isinstance(key, int):
- util.raise_(IndexError(key), replace_context=err)
+ raise IndexError(key) from err
else:
raise
@@ -1211,7 +1208,7 @@ class ColumnCollection:
try:
return self._index[key]
except KeyError as err:
- util.raise_(AttributeError(key), replace_context=err)
+ raise AttributeError(key) from err
def __contains__(self, key):
if key not in self._index:
@@ -1656,10 +1653,6 @@ def _entity_namespace_key(entity, key, default=NO_ARG):
else:
return getattr(ns, key)
except AttributeError as err:
- util.raise_(
- exc.InvalidRequestError(
- 'Entity namespace for "%s" has no property "%s"'
- % (entity, key)
- ),
- replace_context=err,
- )
+ raise exc.InvalidRequestError(
+ 'Entity namespace for "%s" has no property "%s"' % (entity, key)
+ ) from err
diff --git a/lib/sqlalchemy/sql/coercions.py b/lib/sqlalchemy/sql/coercions.py
index 38eed4d2a..9b8b4540c 100644
--- a/lib/sqlalchemy/sql/coercions.py
+++ b/lib/sqlalchemy/sql/coercions.py
@@ -280,7 +280,7 @@ class RoleImpl:
if advice:
msg += " " + advice
- util.raise_(exc.ArgumentError(msg, code=code), replace_context=err)
+ raise exc.ArgumentError(msg, code=code) from err
class _Deannotate:
@@ -345,18 +345,15 @@ class _ColumnCoercions:
def _no_text_coercion(
element, argname=None, exc_cls=exc.ArgumentError, extra=None, err=None
):
- util.raise_(
- exc_cls(
- "%(extra)sTextual SQL expression %(expr)r %(argname)sshould be "
- "explicitly declared as text(%(expr)r)"
- % {
- "expr": util.ellipses_string(element),
- "argname": "for argument %s" % (argname,) if argname else "",
- "extra": "%s " % extra if extra else "",
- }
- ),
- replace_context=err,
- )
+ raise exc_cls(
+ "%(extra)sTextual SQL expression %(expr)r %(argname)sshould be "
+ "explicitly declared as text(%(expr)r)"
+ % {
+ "expr": util.ellipses_string(element),
+ "argname": "for argument %s" % (argname,) if argname else "",
+ "extra": "%s " % extra if extra else "",
+ }
+ ) from err
class _NoTextCoercion:
diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py
index 5f6ee5f41..a9dd6a23a 100644
--- a/lib/sqlalchemy/sql/compiler.py
+++ b/lib/sqlalchemy/sql/compiler.py
@@ -467,10 +467,7 @@ class Compiled:
raise exc.ObjectNotExecutableError(self.statement)
def visit_unsupported_compilation(self, element, err):
- util.raise_(
- exc.UnsupportedCompilationError(self, type(element)),
- replace_context=err,
- )
+ raise exc.UnsupportedCompilationError(self, type(element)) from err
@property
def sql_compiler(self):
@@ -518,10 +515,7 @@ class TypeCompiler(metaclass=util.EnsureKWArgType):
return type_._compiler_dispatch(self, **kw)
def visit_unsupported_compilation(self, element, err, **kw):
- util.raise_(
- exc.UnsupportedCompilationError(self, element),
- replace_context=err,
- )
+ raise exc.UnsupportedCompilationError(self, element) from err
# this was a Visitable, but to allow accurate detection of
@@ -830,10 +824,7 @@ class SQLCompiler(Compiled):
try:
return self.stack[-1]["selectable"]
except IndexError as ie:
- util.raise_(
- IndexError("Compiler does not have a stack entry"),
- replace_context=ie,
- )
+ raise IndexError("Compiler does not have a stack entry") from ie
@property
def prefetch(self):
@@ -943,13 +934,10 @@ class SQLCompiler(Compiled):
try:
orig_extracted = self.cache_key[1]
except TypeError as err:
- util.raise_(
- exc.CompileError(
- "This compiled object has no original cache key; "
- "can't pass extracted_parameters to construct_params"
- ),
- replace_context=err,
- )
+ raise exc.CompileError(
+ "This compiled object has no original cache key; "
+ "can't pass extracted_parameters to construct_params"
+ ) from err
ckbm = self._cache_key_bind_match
resolved_extracted = {
@@ -2176,10 +2164,7 @@ class SQLCompiler(Compiled):
try:
opstring = OPERATORS[operator_]
except KeyError as err:
- util.raise_(
- exc.UnsupportedCompilationError(self, operator_),
- replace_context=err,
- )
+ raise exc.UnsupportedCompilationError(self, operator_) from err
else:
return self._generate_generic_binary(
binary,
@@ -4393,13 +4378,10 @@ class DDLCompiler(Compiled):
if column.primary_key:
first_pk = True
except exc.CompileError as ce:
- util.raise_(
- exc.CompileError(
- "(in table '%s', column '%s'): %s"
- % (table.description, column.name, ce.args[0])
- ),
- from_=ce,
- )
+ raise exc.CompileError(
+ "(in table '%s', column '%s'): %s"
+ % (table.description, column.name, ce.args[0])
+ ) from ce
const = self.create_table_constraints(
table,
diff --git a/lib/sqlalchemy/sql/ddl.py b/lib/sqlalchemy/sql/ddl.py
index ef0906328..f415aeaff 100644
--- a/lib/sqlalchemy/sql/ddl.py
+++ b/lib/sqlalchemy/sql/ddl.py
@@ -855,26 +855,19 @@ class SchemaDropper(DDLBase):
)
collection = [(t, ()) for t in unsorted_tables]
else:
- util.raise_(
- exc.CircularDependencyError(
- err2.args[0],
- err2.cycles,
- err2.edges,
- msg="Can't sort tables for DROP; an "
- "unresolvable foreign key "
- "dependency exists between tables: %s. Please ensure "
- "that the ForeignKey and ForeignKeyConstraint objects "
- "involved in the cycle have "
- "names so that they can be dropped using "
- "DROP CONSTRAINT."
- % (
- ", ".join(
- sorted([t.fullname for t in err2.cycles])
- )
- ),
- ),
- from_=err2,
- )
+ raise exc.CircularDependencyError(
+ err2.args[0],
+ err2.cycles,
+ err2.edges,
+ msg="Can't sort tables for DROP; an "
+ "unresolvable foreign key "
+ "dependency exists between tables: %s. Please ensure "
+ "that the ForeignKey and ForeignKeyConstraint objects "
+ "involved in the cycle have "
+ "names so that they can be dropped using "
+ "DROP CONSTRAINT."
+ % (", ".join(sorted([t.fullname for t in err2.cycles]))),
+ ) from err2
seq_coll = [
s
diff --git a/lib/sqlalchemy/sql/elements.py b/lib/sqlalchemy/sql/elements.py
index 028743706..37425345b 100644
--- a/lib/sqlalchemy/sql/elements.py
+++ b/lib/sqlalchemy/sql/elements.py
@@ -848,13 +848,10 @@ class ColumnElement(
try:
comparator_factory = self.type.comparator_factory
except AttributeError as err:
- util.raise_(
- TypeError(
- "Object %r associated with '.type' attribute "
- "is not a TypeEngine class or object" % self.type
- ),
- replace_context=err,
- )
+ raise TypeError(
+ "Object %r associated with '.type' attribute "
+ "is not a TypeEngine class or object" % self.type
+ ) from err
else:
return comparator_factory(self)
@@ -862,17 +859,14 @@ class ColumnElement(
try:
return getattr(self.comparator, key)
except AttributeError as err:
- util.raise_(
- AttributeError(
- "Neither %r object nor %r object has an attribute %r"
- % (
- type(self).__name__,
- type(self.comparator).__name__,
- key,
- )
- ),
- replace_context=err,
- )
+ raise AttributeError(
+ "Neither %r object nor %r object has an attribute %r"
+ % (
+ type(self).__name__,
+ type(self.comparator).__name__,
+ key,
+ )
+ ) from err
def operate(self, op, *other, **kwargs):
return op(self.comparator, *other, **kwargs)
@@ -1989,13 +1983,10 @@ class TextClause(
# so that a text() construct can support unique parameters
existing = new_params[bind._orig_key]
except KeyError as err:
- util.raise_(
- exc.ArgumentError(
- "This text() construct doesn't define a "
- "bound parameter named %r" % bind._orig_key
- ),
- replace_context=err,
- )
+ raise exc.ArgumentError(
+ "This text() construct doesn't define a "
+ "bound parameter named %r" % bind._orig_key
+ ) from err
else:
new_params[existing._orig_key] = bind
@@ -2003,13 +1994,10 @@ class TextClause(
try:
existing = new_params[key]
except KeyError as err:
- util.raise_(
- exc.ArgumentError(
- "This text() construct doesn't define a "
- "bound parameter named %r" % key
- ),
- replace_context=err,
- )
+ raise exc.ArgumentError(
+ "This text() construct doesn't define a "
+ "bound parameter named %r" % key
+ ) from err
else:
new_params[key] = existing._with_value(value, required=False)
@@ -4175,12 +4163,9 @@ class Over(ColumnElement):
try:
lower = int(range_[0])
except ValueError as err:
- util.raise_(
- exc.ArgumentError(
- "Integer or None expected for range value"
- ),
- replace_context=err,
- )
+ raise exc.ArgumentError(
+ "Integer or None expected for range value"
+ ) from err
else:
if lower == 0:
lower = RANGE_CURRENT
@@ -4191,12 +4176,9 @@ class Over(ColumnElement):
try:
upper = int(range_[1])
except ValueError as err:
- util.raise_(
- exc.ArgumentError(
- "Integer or None expected for range value"
- ),
- replace_context=err,
- )
+ raise exc.ArgumentError(
+ "Integer or None expected for range value"
+ ) from err
else:
if upper == 0:
upper = RANGE_CURRENT
diff --git a/lib/sqlalchemy/sql/lambdas.py b/lib/sqlalchemy/sql/lambdas.py
index 2256fb5a9..da1dbedbb 100644
--- a/lib/sqlalchemy/sql/lambdas.py
+++ b/lib/sqlalchemy/sql/lambdas.py
@@ -901,24 +901,21 @@ class AnalyzedCode:
def _raise_for_uncacheable_closure_variable(
self, variable_name, fn, from_=None
):
- util.raise_(
- exc.InvalidRequestError(
- "Closure variable named '%s' inside of lambda callable %s "
- "does not refer to a cacheable SQL element, and also does not "
- "appear to be serving as a SQL literal bound value based on "
- "the default "
- "SQL expression returned by the function. This variable "
- "needs to remain outside the scope of a SQL-generating lambda "
- "so that a proper cache key may be generated from the "
- "lambda's state. Evaluate this variable outside of the "
- "lambda, set track_on=[<elements>] to explicitly select "
- "closure elements to track, or set "
- "track_closure_variables=False to exclude "
- "closure variables from being part of the cache key."
- % (variable_name, fn.__code__),
- ),
- from_=from_,
- )
+ raise exc.InvalidRequestError(
+ "Closure variable named '%s' inside of lambda callable %s "
+ "does not refer to a cacheable SQL element, and also does not "
+ "appear to be serving as a SQL literal bound value based on "
+ "the default "
+ "SQL expression returned by the function. This variable "
+ "needs to remain outside the scope of a SQL-generating lambda "
+ "so that a proper cache key may be generated from the "
+ "lambda's state. Evaluate this variable outside of the "
+ "lambda, set track_on=[<elements>] to explicitly select "
+ "closure elements to track, or set "
+ "track_closure_variables=False to exclude "
+ "closure variables from being part of the cache key."
+ % (variable_name, fn.__code__),
+ ) from from_
def _cache_key_getter_tracked_literal(self, fn, pytracker):
"""Return a getter that will extend a cache key with new entries
diff --git a/lib/sqlalchemy/sql/schema.py b/lib/sqlalchemy/sql/schema.py
index cdd17f2c0..9b5005b5d 100644
--- a/lib/sqlalchemy/sql/schema.py
+++ b/lib/sqlalchemy/sql/schema.py
@@ -120,13 +120,10 @@ class SchemaItem(SchemaEventTarget, visitors.Visitable):
try:
spwd = item._set_parent_with_dispatch
except AttributeError as err:
- util.raise_(
- exc.ArgumentError(
- "'SchemaItem' object, such as a 'Column' or a "
- "'Constraint' expected, got %r" % item
- ),
- replace_context=err,
- )
+ raise exc.ArgumentError(
+ "'SchemaItem' object, such as a 'Column' or a "
+ "'Constraint' expected, got %r" % item
+ ) from err
else:
spwd(self, **kw)
@@ -1932,16 +1929,13 @@ class Column(DialectKWArgs, SchemaItem, ColumnClause):
*fk
)
except TypeError as err:
- util.raise_(
- TypeError(
- "Could not create a copy of this %r object. "
- "Ensure the class includes a _constructor() "
- "attribute or method which accepts the "
- "standard Column constructor arguments, or "
- "references the Column class itself." % self.__class__
- ),
- from_=err,
- )
+ raise TypeError(
+ "Could not create a copy of this %r object. "
+ "Ensure the class includes a _constructor() "
+ "attribute or method which accepts the "
+ "standard Column constructor arguments, or "
+ "references the Column class itself." % self.__class__
+ ) from err
c.table = selectable
c._propagate_attrs = selectable._propagate_attrs
@@ -3647,14 +3641,11 @@ class ForeignKeyConstraint(ColumnCollectionConstraint):
try:
ColumnCollectionConstraint._set_parent(self, table)
except KeyError as ke:
- util.raise_(
- exc.ArgumentError(
- "Can't create ForeignKeyConstraint "
- "on table '%s': no column "
- "named '%s' is present." % (table.description, ke.args[0])
- ),
- from_=ke,
- )
+ raise exc.ArgumentError(
+ "Can't create ForeignKeyConstraint "
+ "on table '%s': no column "
+ "named '%s' is present." % (table.description, ke.args[0])
+ ) from ke
for col, fk in zip(self.columns, self.elements):
if not hasattr(fk, "parent") or fk.parent is not col:
diff --git a/lib/sqlalchemy/sql/selectable.py b/lib/sqlalchemy/sql/selectable.py
index a96ed479d..2f157c27e 100644
--- a/lib/sqlalchemy/sql/selectable.py
+++ b/lib/sqlalchemy/sql/selectable.py
@@ -3606,13 +3606,10 @@ class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase):
try:
value = clause._limit_offset_value
except AttributeError as err:
- util.raise_(
- exc.CompileError(
- "This SELECT structure does not use a simple "
- "integer value for %s" % attrname
- ),
- replace_context=err,
- )
+ raise exc.CompileError(
+ "This SELECT structure does not use a simple "
+ "integer value for %s" % attrname
+ ) from err
else:
return util.asint(value)
@@ -5053,15 +5050,12 @@ class Select(
try:
cols_present = bool(columns)
except TypeError as err:
- util.raise_(
- exc.ArgumentError(
- "select() construct created in legacy mode, i.e. with "
- "keyword arguments, must provide the columns argument as "
- "a Python list or other iterable.",
- code="c9ae",
- ),
- from_=err,
- )
+ raise exc.ArgumentError(
+ "select() construct created in legacy mode, i.e. with "
+ "keyword arguments, must provide the columns argument as "
+ "a Python list or other iterable.",
+ code="c9ae",
+ ) from err
if cols_present:
self._raw_columns = [
diff --git a/lib/sqlalchemy/sql/sqltypes.py b/lib/sqlalchemy/sql/sqltypes.py
index f035284f4..574692fed 100644
--- a/lib/sqlalchemy/sql/sqltypes.py
+++ b/lib/sqlalchemy/sql/sqltypes.py
@@ -1325,18 +1325,15 @@ class Enum(Emulated, String, SchemaType):
if not self.validate_strings and isinstance(elem, str):
return elem
else:
- util.raise_(
- LookupError(
- "'%s' is not among the defined enum values. "
- "Enum name: %s. Possible values: %s"
- % (
- elem,
- self.name,
- langhelpers.repr_tuple_names(self.enums),
- )
- ),
- replace_context=err,
- )
+ raise LookupError(
+ "'%s' is not among the defined enum values. "
+ "Enum name: %s. Possible values: %s"
+ % (
+ elem,
+ self.name,
+ langhelpers.repr_tuple_names(self.enums),
+ )
+ ) from err
class Comparator(String.Comparator):
def _adapt_expression(self, op, other_comparator):
@@ -1353,18 +1350,15 @@ class Enum(Emulated, String, SchemaType):
try:
return self._object_lookup[elem]
except KeyError as err:
- util.raise_(
- LookupError(
- "'%s' is not among the defined enum values. "
- "Enum name: %s. Possible values: %s"
- % (
- elem,
- self.name,
- langhelpers.repr_tuple_names(self.enums),
- )
- ),
- replace_context=err,
- )
+ raise LookupError(
+ "'%s' is not among the defined enum values. "
+ "Enum name: %s. Possible values: %s"
+ % (
+ elem,
+ self.name,
+ langhelpers.repr_tuple_names(self.enums),
+ )
+ ) from err
def __repr__(self):
return util.generic_repr(
diff --git a/lib/sqlalchemy/testing/exclusions.py b/lib/sqlalchemy/testing/exclusions.py
index c20cd920c..90e5d5ff9 100644
--- a/lib/sqlalchemy/testing/exclusions.py
+++ b/lib/sqlalchemy/testing/exclusions.py
@@ -147,7 +147,7 @@ class compound:
)
break
else:
- util.raise_(ex, with_traceback=sys.exc_info()[2])
+ raise ex.with_traceback(sys.exc_info()[2])
def _expect_success(self, config, name="block"):
if not self.fails:
diff --git a/lib/sqlalchemy/util/__init__.py b/lib/sqlalchemy/util/__init__.py
index a82e040df..b452a1fda 100644
--- a/lib/sqlalchemy/util/__init__.py
+++ b/lib/sqlalchemy/util/__init__.py
@@ -63,9 +63,6 @@ from .compat import osx
from .compat import py38
from .compat import py39
from .compat import pypy
-from .compat import raise_
-from .compat import raise_from_cause
-from .compat import reraise
from .compat import threading
from .compat import win32
from .concurrency import asyncio
diff --git a/lib/sqlalchemy/util/compat.py b/lib/sqlalchemy/util/compat.py
index 37f157698..59846c5c2 100644
--- a/lib/sqlalchemy/util/compat.py
+++ b/lib/sqlalchemy/util/compat.py
@@ -122,42 +122,6 @@ def cmp(a, b):
return (a > b) - (a < b)
-def raise_(exception, with_traceback=None, replace_context=None, from_=False):
- r"""implement "raise" with cause support.
-
- :param exception: exception to raise
- :param with_traceback: will call exception.with_traceback()
- :param replace_context: an as-yet-unsupported feature. This is
- an exception object which we are "replacing", e.g., it's our
- "cause" but we don't want it printed. Basically just what
- ``__suppress_context__`` does but we don't want to suppress
- the enclosing context, if any. So for now we make it the
- cause.
- :param from\_: the cause. this actually sets the cause and doesn't
- hope to hide it someday.
-
- """
- if with_traceback is not None:
- exception = exception.with_traceback(with_traceback)
-
- if from_ is not False:
- exception.__cause__ = from_
- elif replace_context is not None:
- # no good solution here, we would like to have the exception
- # have only the context of replace_context.__context__ so that the
- # intermediary exception does not change, but we can't figure
- # that out.
- exception.__cause__ = replace_context
-
- try:
- raise exception
- finally:
- # credit to
- # https://cosmicpercolator.com/2016/01/13/exception-leaks-in-python-2-and-3/
- # as the __traceback__ object creates a cycle
- del exception, replace_context, from_, with_traceback
-
-
def _formatannotation(annotation, base_module=None):
"""vendored from python 3.7"""
@@ -260,19 +224,3 @@ def local_dataclass_fields(cls):
return [f for f in dataclasses.fields(cls) if f not in super_fields]
else:
return []
-
-
-def raise_from_cause(exception, exc_info=None):
- r"""legacy. use raise\_()"""
-
- if exc_info is None:
- exc_info = sys.exc_info()
- exc_type, exc_value, exc_tb = exc_info
- cause = exc_value if exc_value is not exception else None
- reraise(type(exception), exception, tb=exc_tb, cause=cause)
-
-
-def reraise(tp, value, tb=None, cause=None):
- r"""legacy. use raise\_()"""
-
- raise_(value, with_traceback=tb, from_=cause)
diff --git a/lib/sqlalchemy/util/langhelpers.py b/lib/sqlalchemy/util/langhelpers.py
index 52182a4f7..ca64296c1 100644
--- a/lib/sqlalchemy/util/langhelpers.py
+++ b/lib/sqlalchemy/util/langhelpers.py
@@ -76,13 +76,10 @@ class safe_reraise:
exc_type, exc_value, exc_tb = self._exc_info
self._exc_info = None # remove potential circular references
if not self.warn_only:
- compat.raise_(
- exc_value,
- with_traceback=exc_tb,
- )
+ raise exc_value.with_traceback(exc_tb)
else:
self._exc_info = None # remove potential circular references
- compat.raise_(value, with_traceback=traceback)
+ raise value.with_traceback(traceback)
def walk_subclasses(cls):
diff --git a/lib/sqlalchemy/util/queue.py b/lib/sqlalchemy/util/queue.py
index 12b372202..4769d5886 100644
--- a/lib/sqlalchemy/util/queue.py
+++ b/lib/sqlalchemy/util/queue.py
@@ -21,7 +21,6 @@ condition.
from collections import deque
from time import time as _time
-from . import compat
from .compat import threading
from .concurrency import asyncio
from .concurrency import await_fallback
@@ -238,10 +237,7 @@ class AsyncAdaptedQueue:
try:
return self._queue.put_nowait(item)
except asyncio.QueueFull as err:
- compat.raise_(
- Full(),
- replace_context=err,
- )
+ raise Full() from err
def put(self, item, block=True, timeout=None):
if not block:
@@ -255,19 +251,13 @@ class AsyncAdaptedQueue:
else:
return self.await_(self._queue.put(item))
except (asyncio.QueueFull, asyncio.TimeoutError) as err:
- compat.raise_(
- Full(),
- replace_context=err,
- )
+ raise Full() from err
def get_nowait(self):
try:
return self._queue.get_nowait()
except asyncio.QueueEmpty as err:
- compat.raise_(
- Empty(),
- replace_context=err,
- )
+ raise Empty() from err
def get(self, block=True, timeout=None):
if not block:
@@ -281,10 +271,7 @@ class AsyncAdaptedQueue:
else:
return self.await_(self._queue.get())
except (asyncio.QueueEmpty, asyncio.TimeoutError) as err:
- compat.raise_(
- Empty(),
- replace_context=err,
- )
+ raise Empty() from err
class FallbackAsyncAdaptedQueue(AsyncAdaptedQueue):
diff --git a/test/aaa_profiling/test_memusage.py b/test/aaa_profiling/test_memusage.py
index 8d6e4f500..42f882366 100644
--- a/test/aaa_profiling/test_memusage.py
+++ b/test/aaa_profiling/test_memusage.py
@@ -1220,20 +1220,6 @@ class CycleTest(_fixtures.FixtureTest):
go()
- def test_raise_from(self):
- @assert_cycles()
- def go():
- try:
- try:
- raise KeyError("foo")
- except KeyError as ke:
-
- util.raise_(Exception("oops"), from_=ke)
- except Exception as err: # noqa
- pass
-
- go()
-
def test_query_alias(self):
User, Address = self.classes("User", "Address")
configure_mappers()
diff --git a/test/base/test_utils.py b/test/base/test_utils.py
index 9278bd268..2a912f349 100644
--- a/test/base/test_utils.py
+++ b/test/base/test_utils.py
@@ -2988,66 +2988,6 @@ class TestClassHierarchy(fixtures.TestBase):
eq_(set(util.class_hierarchy(B)), set((A, B, C, object)))
-class ReraiseTest(fixtures.TestBase):
- def test_raise_from_cause_same_cause(self):
- class MyException(Exception):
- pass
-
- def go():
- try:
- raise MyException("exc one")
- except Exception as err:
- util.raise_from_cause(err)
-
- try:
- go()
- assert False
- except MyException as err:
- is_(err.__cause__, None)
-
- def test_raise_from_cause_legacy(self):
- class MyException(Exception):
- pass
-
- class MyOtherException(Exception):
- pass
-
- me = MyException("exc on")
-
- def go():
- try:
- raise me
- except Exception:
- util.raise_from_cause(MyOtherException("exc two"))
-
- try:
- go()
- assert False
- except MyOtherException as moe:
- is_(moe.__cause__, me)
-
- def test_raise_from(self):
- class MyException(Exception):
- pass
-
- class MyOtherException(Exception):
- pass
-
- me = MyException("exc on")
-
- def go():
- try:
- raise me
- except Exception as err:
- util.raise_(MyOtherException("exc two"), from_=err)
-
- try:
- go()
- assert False
- except MyOtherException as moe:
- is_(moe.__cause__, me)
-
-
class TestClassProperty(fixtures.TestBase):
def test_simple(self):
class A: