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.

1678 lines
54KB

  1. # sql/base.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. """Foundational utilities common to many sql modules.
  8. """
  9. import itertools
  10. import operator
  11. import re
  12. from . import roles
  13. from . import visitors
  14. from .traversals import HasCacheKey # noqa
  15. from .traversals import HasCopyInternals # noqa
  16. from .traversals import MemoizedHasCacheKey # noqa
  17. from .visitors import ClauseVisitor
  18. from .visitors import ExtendedInternalTraversal
  19. from .visitors import InternalTraversal
  20. from .. import exc
  21. from .. import util
  22. from ..util import HasMemoized
  23. from ..util import hybridmethod
  24. coercions = None
  25. elements = None
  26. type_api = None
  27. PARSE_AUTOCOMMIT = util.symbol("PARSE_AUTOCOMMIT")
  28. NO_ARG = util.symbol("NO_ARG")
  29. class Immutable(object):
  30. """mark a ClauseElement as 'immutable' when expressions are cloned."""
  31. def unique_params(self, *optionaldict, **kwargs):
  32. raise NotImplementedError("Immutable objects do not support copying")
  33. def params(self, *optionaldict, **kwargs):
  34. raise NotImplementedError("Immutable objects do not support copying")
  35. def _clone(self, **kw):
  36. return self
  37. def _copy_internals(self, **kw):
  38. pass
  39. class SingletonConstant(Immutable):
  40. """Represent SQL constants like NULL, TRUE, FALSE"""
  41. def __new__(cls, *arg, **kw):
  42. return cls._singleton
  43. @classmethod
  44. def _create_singleton(cls):
  45. obj = object.__new__(cls)
  46. obj.__init__()
  47. cls._singleton = obj
  48. # don't proxy singletons. this means that a SingletonConstant
  49. # will never be a "corresponding column" in a statement; the constant
  50. # can be named directly and as it is often/usually compared against using
  51. # "IS", it can't be adapted to a subquery column in any case.
  52. # see :ticket:`6259`.
  53. proxy_set = frozenset()
  54. def _from_objects(*elements):
  55. return itertools.chain.from_iterable(
  56. [element._from_objects for element in elements]
  57. )
  58. def _select_iterables(elements):
  59. """expand tables into individual columns in the
  60. given list of column expressions.
  61. """
  62. return itertools.chain.from_iterable(
  63. [c._select_iterable for c in elements]
  64. )
  65. def _generative(fn):
  66. """non-caching _generative() decorator.
  67. This is basically the legacy decorator that copies the object and
  68. runs a method on the new copy.
  69. """
  70. @util.decorator
  71. def _generative(fn, self, *args, **kw):
  72. """Mark a method as generative."""
  73. self = self._generate()
  74. x = fn(self, *args, **kw)
  75. assert x is None, "generative methods must have no return value"
  76. return self
  77. decorated = _generative(fn)
  78. decorated.non_generative = fn
  79. return decorated
  80. def _exclusive_against(*names, **kw):
  81. msgs = kw.pop("msgs", {})
  82. defaults = kw.pop("defaults", {})
  83. getters = [
  84. (name, operator.attrgetter(name), defaults.get(name, None))
  85. for name in names
  86. ]
  87. @util.decorator
  88. def check(fn, self, *args, **kw):
  89. for name, getter, default_ in getters:
  90. if getter(self) is not default_:
  91. msg = msgs.get(
  92. name,
  93. "Method %s() has already been invoked on this %s construct"
  94. % (fn.__name__, self.__class__),
  95. )
  96. raise exc.InvalidRequestError(msg)
  97. return fn(self, *args, **kw)
  98. return check
  99. def _clone(element, **kw):
  100. return element._clone(**kw)
  101. def _expand_cloned(elements):
  102. """expand the given set of ClauseElements to be the set of all 'cloned'
  103. predecessors.
  104. """
  105. return itertools.chain(*[x._cloned_set for x in elements])
  106. def _cloned_intersection(a, b):
  107. """return the intersection of sets a and b, counting
  108. any overlap between 'cloned' predecessors.
  109. The returned set is in terms of the entities present within 'a'.
  110. """
  111. all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
  112. return set(
  113. elem for elem in a if all_overlap.intersection(elem._cloned_set)
  114. )
  115. def _cloned_difference(a, b):
  116. all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
  117. return set(
  118. elem for elem in a if not all_overlap.intersection(elem._cloned_set)
  119. )
  120. class _DialectArgView(util.collections_abc.MutableMapping):
  121. """A dictionary view of dialect-level arguments in the form
  122. <dialectname>_<argument_name>.
  123. """
  124. def __init__(self, obj):
  125. self.obj = obj
  126. def _key(self, key):
  127. try:
  128. dialect, value_key = key.split("_", 1)
  129. except ValueError as err:
  130. util.raise_(KeyError(key), replace_context=err)
  131. else:
  132. return dialect, value_key
  133. def __getitem__(self, key):
  134. dialect, value_key = self._key(key)
  135. try:
  136. opt = self.obj.dialect_options[dialect]
  137. except exc.NoSuchModuleError as err:
  138. util.raise_(KeyError(key), replace_context=err)
  139. else:
  140. return opt[value_key]
  141. def __setitem__(self, key, value):
  142. try:
  143. dialect, value_key = self._key(key)
  144. except KeyError as err:
  145. util.raise_(
  146. exc.ArgumentError(
  147. "Keys must be of the form <dialectname>_<argname>"
  148. ),
  149. replace_context=err,
  150. )
  151. else:
  152. self.obj.dialect_options[dialect][value_key] = value
  153. def __delitem__(self, key):
  154. dialect, value_key = self._key(key)
  155. del self.obj.dialect_options[dialect][value_key]
  156. def __len__(self):
  157. return sum(
  158. len(args._non_defaults)
  159. for args in self.obj.dialect_options.values()
  160. )
  161. def __iter__(self):
  162. return (
  163. "%s_%s" % (dialect_name, value_name)
  164. for dialect_name in self.obj.dialect_options
  165. for value_name in self.obj.dialect_options[
  166. dialect_name
  167. ]._non_defaults
  168. )
  169. class _DialectArgDict(util.collections_abc.MutableMapping):
  170. """A dictionary view of dialect-level arguments for a specific
  171. dialect.
  172. Maintains a separate collection of user-specified arguments
  173. and dialect-specified default arguments.
  174. """
  175. def __init__(self):
  176. self._non_defaults = {}
  177. self._defaults = {}
  178. def __len__(self):
  179. return len(set(self._non_defaults).union(self._defaults))
  180. def __iter__(self):
  181. return iter(set(self._non_defaults).union(self._defaults))
  182. def __getitem__(self, key):
  183. if key in self._non_defaults:
  184. return self._non_defaults[key]
  185. else:
  186. return self._defaults[key]
  187. def __setitem__(self, key, value):
  188. self._non_defaults[key] = value
  189. def __delitem__(self, key):
  190. del self._non_defaults[key]
  191. @util.preload_module("sqlalchemy.dialects")
  192. def _kw_reg_for_dialect(dialect_name):
  193. dialect_cls = util.preloaded.dialects.registry.load(dialect_name)
  194. if dialect_cls.construct_arguments is None:
  195. return None
  196. return dict(dialect_cls.construct_arguments)
  197. class DialectKWArgs(object):
  198. """Establish the ability for a class to have dialect-specific arguments
  199. with defaults and constructor validation.
  200. The :class:`.DialectKWArgs` interacts with the
  201. :attr:`.DefaultDialect.construct_arguments` present on a dialect.
  202. .. seealso::
  203. :attr:`.DefaultDialect.construct_arguments`
  204. """
  205. _dialect_kwargs_traverse_internals = [
  206. ("dialect_options", InternalTraversal.dp_dialect_options)
  207. ]
  208. @classmethod
  209. def argument_for(cls, dialect_name, argument_name, default):
  210. """Add a new kind of dialect-specific keyword argument for this class.
  211. E.g.::
  212. Index.argument_for("mydialect", "length", None)
  213. some_index = Index('a', 'b', mydialect_length=5)
  214. The :meth:`.DialectKWArgs.argument_for` method is a per-argument
  215. way adding extra arguments to the
  216. :attr:`.DefaultDialect.construct_arguments` dictionary. This
  217. dictionary provides a list of argument names accepted by various
  218. schema-level constructs on behalf of a dialect.
  219. New dialects should typically specify this dictionary all at once as a
  220. data member of the dialect class. The use case for ad-hoc addition of
  221. argument names is typically for end-user code that is also using
  222. a custom compilation scheme which consumes the additional arguments.
  223. :param dialect_name: name of a dialect. The dialect must be
  224. locatable, else a :class:`.NoSuchModuleError` is raised. The
  225. dialect must also include an existing
  226. :attr:`.DefaultDialect.construct_arguments` collection, indicating
  227. that it participates in the keyword-argument validation and default
  228. system, else :class:`.ArgumentError` is raised. If the dialect does
  229. not include this collection, then any keyword argument can be
  230. specified on behalf of this dialect already. All dialects packaged
  231. within SQLAlchemy include this collection, however for third party
  232. dialects, support may vary.
  233. :param argument_name: name of the parameter.
  234. :param default: default value of the parameter.
  235. .. versionadded:: 0.9.4
  236. """
  237. construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
  238. if construct_arg_dictionary is None:
  239. raise exc.ArgumentError(
  240. "Dialect '%s' does have keyword-argument "
  241. "validation and defaults enabled configured" % dialect_name
  242. )
  243. if cls not in construct_arg_dictionary:
  244. construct_arg_dictionary[cls] = {}
  245. construct_arg_dictionary[cls][argument_name] = default
  246. @util.memoized_property
  247. def dialect_kwargs(self):
  248. """A collection of keyword arguments specified as dialect-specific
  249. options to this construct.
  250. The arguments are present here in their original ``<dialect>_<kwarg>``
  251. format. Only arguments that were actually passed are included;
  252. unlike the :attr:`.DialectKWArgs.dialect_options` collection, which
  253. contains all options known by this dialect including defaults.
  254. The collection is also writable; keys are accepted of the
  255. form ``<dialect>_<kwarg>`` where the value will be assembled
  256. into the list of options.
  257. .. versionadded:: 0.9.2
  258. .. versionchanged:: 0.9.4 The :attr:`.DialectKWArgs.dialect_kwargs`
  259. collection is now writable.
  260. .. seealso::
  261. :attr:`.DialectKWArgs.dialect_options` - nested dictionary form
  262. """
  263. return _DialectArgView(self)
  264. @property
  265. def kwargs(self):
  266. """A synonym for :attr:`.DialectKWArgs.dialect_kwargs`."""
  267. return self.dialect_kwargs
  268. _kw_registry = util.PopulateDict(_kw_reg_for_dialect)
  269. def _kw_reg_for_dialect_cls(self, dialect_name):
  270. construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
  271. d = _DialectArgDict()
  272. if construct_arg_dictionary is None:
  273. d._defaults.update({"*": None})
  274. else:
  275. for cls in reversed(self.__class__.__mro__):
  276. if cls in construct_arg_dictionary:
  277. d._defaults.update(construct_arg_dictionary[cls])
  278. return d
  279. @util.memoized_property
  280. def dialect_options(self):
  281. """A collection of keyword arguments specified as dialect-specific
  282. options to this construct.
  283. This is a two-level nested registry, keyed to ``<dialect_name>``
  284. and ``<argument_name>``. For example, the ``postgresql_where``
  285. argument would be locatable as::
  286. arg = my_object.dialect_options['postgresql']['where']
  287. .. versionadded:: 0.9.2
  288. .. seealso::
  289. :attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form
  290. """
  291. return util.PopulateDict(
  292. util.portable_instancemethod(self._kw_reg_for_dialect_cls)
  293. )
  294. def _validate_dialect_kwargs(self, kwargs):
  295. # validate remaining kwargs that they all specify DB prefixes
  296. if not kwargs:
  297. return
  298. for k in kwargs:
  299. m = re.match("^(.+?)_(.+)$", k)
  300. if not m:
  301. raise TypeError(
  302. "Additional arguments should be "
  303. "named <dialectname>_<argument>, got '%s'" % k
  304. )
  305. dialect_name, arg_name = m.group(1, 2)
  306. try:
  307. construct_arg_dictionary = self.dialect_options[dialect_name]
  308. except exc.NoSuchModuleError:
  309. util.warn(
  310. "Can't validate argument %r; can't "
  311. "locate any SQLAlchemy dialect named %r"
  312. % (k, dialect_name)
  313. )
  314. self.dialect_options[dialect_name] = d = _DialectArgDict()
  315. d._defaults.update({"*": None})
  316. d._non_defaults[arg_name] = kwargs[k]
  317. else:
  318. if (
  319. "*" not in construct_arg_dictionary
  320. and arg_name not in construct_arg_dictionary
  321. ):
  322. raise exc.ArgumentError(
  323. "Argument %r is not accepted by "
  324. "dialect %r on behalf of %r"
  325. % (k, dialect_name, self.__class__)
  326. )
  327. else:
  328. construct_arg_dictionary[arg_name] = kwargs[k]
  329. class CompileState(object):
  330. """Produces additional object state necessary for a statement to be
  331. compiled.
  332. the :class:`.CompileState` class is at the base of classes that assemble
  333. state for a particular statement object that is then used by the
  334. compiler. This process is essentially an extension of the process that
  335. the SQLCompiler.visit_XYZ() method takes, however there is an emphasis
  336. on converting raw user intent into more organized structures rather than
  337. producing string output. The top-level :class:`.CompileState` for the
  338. statement being executed is also accessible when the execution context
  339. works with invoking the statement and collecting results.
  340. The production of :class:`.CompileState` is specific to the compiler, such
  341. as within the :meth:`.SQLCompiler.visit_insert`,
  342. :meth:`.SQLCompiler.visit_select` etc. methods. These methods are also
  343. responsible for associating the :class:`.CompileState` with the
  344. :class:`.SQLCompiler` itself, if the statement is the "toplevel" statement,
  345. i.e. the outermost SQL statement that's actually being executed.
  346. There can be other :class:`.CompileState` objects that are not the
  347. toplevel, such as when a SELECT subquery or CTE-nested
  348. INSERT/UPDATE/DELETE is generated.
  349. .. versionadded:: 1.4
  350. """
  351. __slots__ = ("statement",)
  352. plugins = {}
  353. @classmethod
  354. def create_for_statement(cls, statement, compiler, **kw):
  355. # factory construction.
  356. if statement._propagate_attrs:
  357. plugin_name = statement._propagate_attrs.get(
  358. "compile_state_plugin", "default"
  359. )
  360. klass = cls.plugins.get(
  361. (plugin_name, statement._effective_plugin_target), None
  362. )
  363. if klass is None:
  364. klass = cls.plugins[
  365. ("default", statement._effective_plugin_target)
  366. ]
  367. else:
  368. klass = cls.plugins[
  369. ("default", statement._effective_plugin_target)
  370. ]
  371. if klass is cls:
  372. return cls(statement, compiler, **kw)
  373. else:
  374. return klass.create_for_statement(statement, compiler, **kw)
  375. def __init__(self, statement, compiler, **kw):
  376. self.statement = statement
  377. @classmethod
  378. def get_plugin_class(cls, statement):
  379. plugin_name = statement._propagate_attrs.get(
  380. "compile_state_plugin", "default"
  381. )
  382. try:
  383. return cls.plugins[
  384. (plugin_name, statement._effective_plugin_target)
  385. ]
  386. except KeyError:
  387. return None
  388. @classmethod
  389. def _get_plugin_class_for_plugin(cls, statement, plugin_name):
  390. try:
  391. return cls.plugins[
  392. (plugin_name, statement._effective_plugin_target)
  393. ]
  394. except KeyError:
  395. return None
  396. @classmethod
  397. def plugin_for(cls, plugin_name, visit_name):
  398. def decorate(cls_to_decorate):
  399. cls.plugins[(plugin_name, visit_name)] = cls_to_decorate
  400. return cls_to_decorate
  401. return decorate
  402. class Generative(HasMemoized):
  403. """Provide a method-chaining pattern in conjunction with the
  404. @_generative decorator."""
  405. def _generate(self):
  406. skip = self._memoized_keys
  407. cls = self.__class__
  408. s = cls.__new__(cls)
  409. if skip:
  410. s.__dict__ = {
  411. k: v for k, v in self.__dict__.items() if k not in skip
  412. }
  413. else:
  414. s.__dict__ = self.__dict__.copy()
  415. return s
  416. class InPlaceGenerative(HasMemoized):
  417. """Provide a method-chaining pattern in conjunction with the
  418. @_generative decorator that mutates in place."""
  419. def _generate(self):
  420. skip = self._memoized_keys
  421. for k in skip:
  422. self.__dict__.pop(k, None)
  423. return self
  424. class HasCompileState(Generative):
  425. """A class that has a :class:`.CompileState` associated with it."""
  426. _compile_state_plugin = None
  427. _attributes = util.immutabledict()
  428. _compile_state_factory = CompileState.create_for_statement
  429. class _MetaOptions(type):
  430. """metaclass for the Options class."""
  431. def __init__(cls, classname, bases, dict_):
  432. cls._cache_attrs = tuple(
  433. sorted(
  434. d
  435. for d in dict_
  436. if not d.startswith("__")
  437. and d not in ("_cache_key_traversal",)
  438. )
  439. )
  440. type.__init__(cls, classname, bases, dict_)
  441. def __add__(self, other):
  442. o1 = self()
  443. if set(other).difference(self._cache_attrs):
  444. raise TypeError(
  445. "dictionary contains attributes not covered by "
  446. "Options class %s: %r"
  447. % (self, set(other).difference(self._cache_attrs))
  448. )
  449. o1.__dict__.update(other)
  450. return o1
  451. class Options(util.with_metaclass(_MetaOptions)):
  452. """A cacheable option dictionary with defaults."""
  453. def __init__(self, **kw):
  454. self.__dict__.update(kw)
  455. def __add__(self, other):
  456. o1 = self.__class__.__new__(self.__class__)
  457. o1.__dict__.update(self.__dict__)
  458. if set(other).difference(self._cache_attrs):
  459. raise TypeError(
  460. "dictionary contains attributes not covered by "
  461. "Options class %s: %r"
  462. % (self, set(other).difference(self._cache_attrs))
  463. )
  464. o1.__dict__.update(other)
  465. return o1
  466. def __eq__(self, other):
  467. # TODO: very inefficient. This is used only in test suites
  468. # right now.
  469. for a, b in util.zip_longest(self._cache_attrs, other._cache_attrs):
  470. if getattr(self, a) != getattr(other, b):
  471. return False
  472. return True
  473. def __repr__(self):
  474. # TODO: fairly inefficient, used only in debugging right now.
  475. return "%s(%s)" % (
  476. self.__class__.__name__,
  477. ", ".join(
  478. "%s=%r" % (k, self.__dict__[k])
  479. for k in self._cache_attrs
  480. if k in self.__dict__
  481. ),
  482. )
  483. @classmethod
  484. def isinstance(cls, klass):
  485. return issubclass(cls, klass)
  486. @hybridmethod
  487. def add_to_element(self, name, value):
  488. return self + {name: getattr(self, name) + value}
  489. @hybridmethod
  490. def _state_dict(self):
  491. return self.__dict__
  492. _state_dict_const = util.immutabledict()
  493. @_state_dict.classlevel
  494. def _state_dict(cls):
  495. return cls._state_dict_const
  496. @classmethod
  497. def safe_merge(cls, other):
  498. d = other._state_dict()
  499. # only support a merge with another object of our class
  500. # and which does not have attrs that we don't. otherwise
  501. # we risk having state that might not be part of our cache
  502. # key strategy
  503. if (
  504. cls is not other.__class__
  505. and other._cache_attrs
  506. and set(other._cache_attrs).difference(cls._cache_attrs)
  507. ):
  508. raise TypeError(
  509. "other element %r is not empty, is not of type %s, "
  510. "and contains attributes not covered here %r"
  511. % (
  512. other,
  513. cls,
  514. set(other._cache_attrs).difference(cls._cache_attrs),
  515. )
  516. )
  517. return cls + d
  518. @classmethod
  519. def from_execution_options(
  520. cls, key, attrs, exec_options, statement_exec_options
  521. ):
  522. """process Options argument in terms of execution options.
  523. e.g.::
  524. (
  525. load_options,
  526. execution_options,
  527. ) = QueryContext.default_load_options.from_execution_options(
  528. "_sa_orm_load_options",
  529. {
  530. "populate_existing",
  531. "autoflush",
  532. "yield_per"
  533. },
  534. execution_options,
  535. statement._execution_options,
  536. )
  537. get back the Options and refresh "_sa_orm_load_options" in the
  538. exec options dict w/ the Options as well
  539. """
  540. # common case is that no options we are looking for are
  541. # in either dictionary, so cancel for that first
  542. check_argnames = attrs.intersection(
  543. set(exec_options).union(statement_exec_options)
  544. )
  545. existing_options = exec_options.get(key, cls)
  546. if check_argnames:
  547. result = {}
  548. for argname in check_argnames:
  549. local = "_" + argname
  550. if argname in exec_options:
  551. result[local] = exec_options[argname]
  552. elif argname in statement_exec_options:
  553. result[local] = statement_exec_options[argname]
  554. new_options = existing_options + result
  555. exec_options = util.immutabledict().merge_with(
  556. exec_options, {key: new_options}
  557. )
  558. return new_options, exec_options
  559. else:
  560. return existing_options, exec_options
  561. class CacheableOptions(Options, HasCacheKey):
  562. @hybridmethod
  563. def _gen_cache_key(self, anon_map, bindparams):
  564. return HasCacheKey._gen_cache_key(self, anon_map, bindparams)
  565. @_gen_cache_key.classlevel
  566. def _gen_cache_key(cls, anon_map, bindparams):
  567. return (cls, ())
  568. @hybridmethod
  569. def _generate_cache_key(self):
  570. return HasCacheKey._generate_cache_key_for_object(self)
  571. class ExecutableOption(HasCopyInternals, HasCacheKey):
  572. _annotations = util.EMPTY_DICT
  573. __visit_name__ = "executable_option"
  574. def _clone(self, **kw):
  575. """Create a shallow copy of this ExecutableOption."""
  576. c = self.__class__.__new__(self.__class__)
  577. c.__dict__ = dict(self.__dict__)
  578. return c
  579. class Executable(roles.StatementRole, Generative):
  580. """Mark a :class:`_expression.ClauseElement` as supporting execution.
  581. :class:`.Executable` is a superclass for all "statement" types
  582. of objects, including :func:`select`, :func:`delete`, :func:`update`,
  583. :func:`insert`, :func:`text`.
  584. """
  585. supports_execution = True
  586. _execution_options = util.immutabledict()
  587. _bind = None
  588. _with_options = ()
  589. _with_context_options = ()
  590. _executable_traverse_internals = [
  591. ("_with_options", InternalTraversal.dp_executable_options),
  592. (
  593. "_with_context_options",
  594. ExtendedInternalTraversal.dp_with_context_options,
  595. ),
  596. ("_propagate_attrs", ExtendedInternalTraversal.dp_propagate_attrs),
  597. ]
  598. is_select = False
  599. is_update = False
  600. is_insert = False
  601. is_text = False
  602. is_delete = False
  603. is_dml = False
  604. @property
  605. def _effective_plugin_target(self):
  606. return self.__visit_name__
  607. @_generative
  608. def options(self, *options):
  609. """Apply options to this statement.
  610. In the general sense, options are any kind of Python object
  611. that can be interpreted by the SQL compiler for the statement.
  612. These options can be consumed by specific dialects or specific kinds
  613. of compilers.
  614. The most commonly known kind of option are the ORM level options
  615. that apply "eager load" and other loading behaviors to an ORM
  616. query. However, options can theoretically be used for many other
  617. purposes.
  618. For background on specific kinds of options for specific kinds of
  619. statements, refer to the documentation for those option objects.
  620. .. versionchanged:: 1.4 - added :meth:`.Generative.options` to
  621. Core statement objects towards the goal of allowing unified
  622. Core / ORM querying capabilities.
  623. .. seealso::
  624. :ref:`deferred_options` - refers to options specific to the usage
  625. of ORM queries
  626. :ref:`relationship_loader_options` - refers to options specific
  627. to the usage of ORM queries
  628. """
  629. self._with_options += tuple(
  630. coercions.expect(roles.HasCacheKeyRole, opt) for opt in options
  631. )
  632. @_generative
  633. def _set_compile_options(self, compile_options):
  634. """Assign the compile options to a new value.
  635. :param compile_options: appropriate CacheableOptions structure
  636. """
  637. self._compile_options = compile_options
  638. @_generative
  639. def _update_compile_options(self, options):
  640. """update the _compile_options with new keys."""
  641. self._compile_options += options
  642. @_generative
  643. def _add_context_option(self, callable_, cache_args):
  644. """Add a context option to this statement.
  645. These are callable functions that will
  646. be given the CompileState object upon compilation.
  647. A second argument cache_args is required, which will be combined with
  648. the ``__code__`` identity of the function itself in order to produce a
  649. cache key.
  650. """
  651. self._with_context_options += ((callable_, cache_args),)
  652. @_generative
  653. def execution_options(self, **kw):
  654. """Set non-SQL options for the statement which take effect during
  655. execution.
  656. Execution options can be set on a per-statement or
  657. per :class:`_engine.Connection` basis. Additionally, the
  658. :class:`_engine.Engine` and ORM :class:`~.orm.query.Query`
  659. objects provide
  660. access to execution options which they in turn configure upon
  661. connections.
  662. The :meth:`execution_options` method is generative. A new
  663. instance of this statement is returned that contains the options::
  664. statement = select(table.c.x, table.c.y)
  665. statement = statement.execution_options(autocommit=True)
  666. Note that only a subset of possible execution options can be applied
  667. to a statement - these include "autocommit" and "stream_results",
  668. but not "isolation_level" or "compiled_cache".
  669. See :meth:`_engine.Connection.execution_options` for a full list of
  670. possible options.
  671. .. seealso::
  672. :meth:`_engine.Connection.execution_options`
  673. :meth:`_query.Query.execution_options`
  674. :meth:`.Executable.get_execution_options`
  675. """
  676. if "isolation_level" in kw:
  677. raise exc.ArgumentError(
  678. "'isolation_level' execution option may only be specified "
  679. "on Connection.execution_options(), or "
  680. "per-engine using the isolation_level "
  681. "argument to create_engine()."
  682. )
  683. if "compiled_cache" in kw:
  684. raise exc.ArgumentError(
  685. "'compiled_cache' execution option may only be specified "
  686. "on Connection.execution_options(), not per statement."
  687. )
  688. self._execution_options = self._execution_options.union(kw)
  689. def get_execution_options(self):
  690. """Get the non-SQL options which will take effect during execution.
  691. .. versionadded:: 1.3
  692. .. seealso::
  693. :meth:`.Executable.execution_options`
  694. """
  695. return self._execution_options
  696. @util.deprecated_20(
  697. ":meth:`.Executable.execute`",
  698. alternative="All statement execution in SQLAlchemy 2.0 is performed "
  699. "by the :meth:`_engine.Connection.execute` method of "
  700. ":class:`_engine.Connection`, "
  701. "or in the ORM by the :meth:`.Session.execute` method of "
  702. ":class:`.Session`.",
  703. )
  704. def execute(self, *multiparams, **params):
  705. """Compile and execute this :class:`.Executable`."""
  706. e = self.bind
  707. if e is None:
  708. label = (
  709. getattr(self, "description", None) or self.__class__.__name__
  710. )
  711. msg = (
  712. "This %s is not directly bound to a Connection or Engine. "
  713. "Use the .execute() method of a Connection or Engine "
  714. "to execute this construct." % label
  715. )
  716. raise exc.UnboundExecutionError(msg)
  717. return e._execute_clauseelement(
  718. self, multiparams, params, util.immutabledict()
  719. )
  720. @util.deprecated_20(
  721. ":meth:`.Executable.scalar`",
  722. alternative="Scalar execution in SQLAlchemy 2.0 is performed "
  723. "by the :meth:`_engine.Connection.scalar` method of "
  724. ":class:`_engine.Connection`, "
  725. "or in the ORM by the :meth:`.Session.scalar` method of "
  726. ":class:`.Session`.",
  727. )
  728. def scalar(self, *multiparams, **params):
  729. """Compile and execute this :class:`.Executable`, returning the
  730. result's scalar representation.
  731. """
  732. return self.execute(*multiparams, **params).scalar()
  733. @property
  734. @util.deprecated_20(
  735. ":attr:`.Executable.bind`",
  736. alternative="Bound metadata is being removed as of SQLAlchemy 2.0.",
  737. enable_warnings=False,
  738. )
  739. def bind(self):
  740. """Returns the :class:`_engine.Engine` or :class:`_engine.Connection`
  741. to
  742. which this :class:`.Executable` is bound, or None if none found.
  743. This is a traversal which checks locally, then
  744. checks among the "from" clauses of associated objects
  745. until a bound engine or connection is found.
  746. """
  747. if self._bind is not None:
  748. return self._bind
  749. for f in _from_objects(self):
  750. if f is self:
  751. continue
  752. engine = f.bind
  753. if engine is not None:
  754. return engine
  755. else:
  756. return None
  757. class prefix_anon_map(dict):
  758. """A map that creates new keys for missing key access.
  759. Considers keys of the form "<ident> <name>" to produce
  760. new symbols "<name>_<index>", where "index" is an incrementing integer
  761. corresponding to <name>.
  762. Inlines the approach taken by :class:`sqlalchemy.util.PopulateDict` which
  763. is otherwise usually used for this type of operation.
  764. """
  765. def __missing__(self, key):
  766. (ident, derived) = key.split(" ", 1)
  767. anonymous_counter = self.get(derived, 1)
  768. self[derived] = anonymous_counter + 1
  769. value = derived + "_" + str(anonymous_counter)
  770. self[key] = value
  771. return value
  772. class SchemaEventTarget(object):
  773. """Base class for elements that are the targets of :class:`.DDLEvents`
  774. events.
  775. This includes :class:`.SchemaItem` as well as :class:`.SchemaType`.
  776. """
  777. def _set_parent(self, parent, **kw):
  778. """Associate with this SchemaEvent's parent object."""
  779. def _set_parent_with_dispatch(self, parent, **kw):
  780. self.dispatch.before_parent_attach(self, parent)
  781. self._set_parent(parent, **kw)
  782. self.dispatch.after_parent_attach(self, parent)
  783. class SchemaVisitor(ClauseVisitor):
  784. """Define the visiting for ``SchemaItem`` objects."""
  785. __traverse_options__ = {"schema_visitor": True}
  786. class ColumnCollection(object):
  787. """Collection of :class:`_expression.ColumnElement` instances,
  788. typically for
  789. :class:`_sql.FromClause` objects.
  790. The :class:`_sql.ColumnCollection` object is most commonly available
  791. as the :attr:`_schema.Table.c` or :attr:`_schema.Table.columns` collection
  792. on the :class:`_schema.Table` object, introduced at
  793. :ref:`metadata_tables_and_columns`.
  794. The :class:`_expression.ColumnCollection` has both mapping- and sequence-
  795. like behaviors. A :class:`_expression.ColumnCollection` usually stores
  796. :class:`_schema.Column` objects, which are then accessible both via mapping
  797. style access as well as attribute access style.
  798. To access :class:`_schema.Column` objects using ordinary attribute-style
  799. access, specify the name like any other object attribute, such as below
  800. a column named ``employee_name`` is accessed::
  801. >>> employee_table.c.employee_name
  802. To access columns that have names with special characters or spaces,
  803. index-style access is used, such as below which illustrates a column named
  804. ``employee ' payment`` is accessed::
  805. >>> employee_table.c["employee ' payment"]
  806. As the :class:`_sql.ColumnCollection` object provides a Python dictionary
  807. interface, common dictionary method names like
  808. :meth:`_sql.ColumnCollection.keys`, :meth:`_sql.ColumnCollection.values`,
  809. and :meth:`_sql.ColumnCollection.items` are available, which means that
  810. database columns that are keyed under these names also need to use indexed
  811. access::
  812. >>> employee_table.c["values"]
  813. The name for which a :class:`_schema.Column` would be present is normally
  814. that of the :paramref:`_schema.Column.key` parameter. In some contexts,
  815. such as a :class:`_sql.Select` object that uses a label style set
  816. using the :meth:`_sql.Select.set_label_style` method, a column of a certain
  817. key may instead be represented under a particular label name such
  818. as ``tablename_columnname``::
  819. >>> from sqlalchemy import select, column, table
  820. >>> from sqlalchemy import LABEL_STYLE_TABLENAME_PLUS_COL
  821. >>> t = table("t", column("c"))
  822. >>> stmt = select(t).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  823. >>> subq = stmt.subquery()
  824. >>> subq.c.t_c
  825. <sqlalchemy.sql.elements.ColumnClause at 0x7f59dcf04fa0; t_c>
  826. :class:`.ColumnCollection` also indexes the columns in order and allows
  827. them to be accessible by their integer position::
  828. >>> cc[0]
  829. Column('x', Integer(), table=None)
  830. >>> cc[1]
  831. Column('y', Integer(), table=None)
  832. .. versionadded:: 1.4 :class:`_expression.ColumnCollection`
  833. allows integer-based
  834. index access to the collection.
  835. Iterating the collection yields the column expressions in order::
  836. >>> list(cc)
  837. [Column('x', Integer(), table=None),
  838. Column('y', Integer(), table=None)]
  839. The base :class:`_expression.ColumnCollection` object can store
  840. duplicates, which can
  841. mean either two columns with the same key, in which case the column
  842. returned by key access is **arbitrary**::
  843. >>> x1, x2 = Column('x', Integer), Column('x', Integer)
  844. >>> cc = ColumnCollection(columns=[(x1.name, x1), (x2.name, x2)])
  845. >>> list(cc)
  846. [Column('x', Integer(), table=None),
  847. Column('x', Integer(), table=None)]
  848. >>> cc['x'] is x1
  849. False
  850. >>> cc['x'] is x2
  851. True
  852. Or it can also mean the same column multiple times. These cases are
  853. supported as :class:`_expression.ColumnCollection`
  854. is used to represent the columns in
  855. a SELECT statement which may include duplicates.
  856. A special subclass :class:`.DedupeColumnCollection` exists which instead
  857. maintains SQLAlchemy's older behavior of not allowing duplicates; this
  858. collection is used for schema level objects like :class:`_schema.Table`
  859. and
  860. :class:`.PrimaryKeyConstraint` where this deduping is helpful. The
  861. :class:`.DedupeColumnCollection` class also has additional mutation methods
  862. as the schema constructs have more use cases that require removal and
  863. replacement of columns.
  864. .. versionchanged:: 1.4 :class:`_expression.ColumnCollection`
  865. now stores duplicate
  866. column keys as well as the same column in multiple positions. The
  867. :class:`.DedupeColumnCollection` class is added to maintain the
  868. former behavior in those cases where deduplication as well as
  869. additional replace/remove operations are needed.
  870. """
  871. __slots__ = "_collection", "_index", "_colset"
  872. def __init__(self, columns=None):
  873. object.__setattr__(self, "_colset", set())
  874. object.__setattr__(self, "_index", {})
  875. object.__setattr__(self, "_collection", [])
  876. if columns:
  877. self._initial_populate(columns)
  878. def _initial_populate(self, iter_):
  879. self._populate_separate_keys(iter_)
  880. @property
  881. def _all_columns(self):
  882. return [col for (k, col) in self._collection]
  883. def keys(self):
  884. """Return a sequence of string key names for all columns in this
  885. collection."""
  886. return [k for (k, col) in self._collection]
  887. def values(self):
  888. """Return a sequence of :class:`_sql.ColumnClause` or
  889. :class:`_schema.Column` objects for all columns in this
  890. collection."""
  891. return [col for (k, col) in self._collection]
  892. def items(self):
  893. """Return a sequence of (key, column) tuples for all columns in this
  894. collection each consisting of a string key name and a
  895. :class:`_sql.ColumnClause` or
  896. :class:`_schema.Column` object.
  897. """
  898. return list(self._collection)
  899. def __bool__(self):
  900. return bool(self._collection)
  901. def __len__(self):
  902. return len(self._collection)
  903. def __iter__(self):
  904. # turn to a list first to maintain over a course of changes
  905. return iter([col for k, col in self._collection])
  906. def __getitem__(self, key):
  907. try:
  908. return self._index[key]
  909. except KeyError as err:
  910. if isinstance(key, util.int_types):
  911. util.raise_(IndexError(key), replace_context=err)
  912. else:
  913. raise
  914. def __getattr__(self, key):
  915. try:
  916. return self._index[key]
  917. except KeyError as err:
  918. util.raise_(AttributeError(key), replace_context=err)
  919. def __contains__(self, key):
  920. if key not in self._index:
  921. if not isinstance(key, util.string_types):
  922. raise exc.ArgumentError(
  923. "__contains__ requires a string argument"
  924. )
  925. return False
  926. else:
  927. return True
  928. def compare(self, other):
  929. """Compare this :class:`_expression.ColumnCollection` to another
  930. based on the names of the keys"""
  931. for l, r in util.zip_longest(self, other):
  932. if l is not r:
  933. return False
  934. else:
  935. return True
  936. def __eq__(self, other):
  937. return self.compare(other)
  938. def get(self, key, default=None):
  939. """Get a :class:`_sql.ColumnClause` or :class:`_schema.Column` object
  940. based on a string key name from this
  941. :class:`_expression.ColumnCollection`."""
  942. if key in self._index:
  943. return self._index[key]
  944. else:
  945. return default
  946. def __str__(self):
  947. return "%s(%s)" % (
  948. self.__class__.__name__,
  949. ", ".join(str(c) for c in self),
  950. )
  951. def __setitem__(self, key, value):
  952. raise NotImplementedError()
  953. def __delitem__(self, key):
  954. raise NotImplementedError()
  955. def __setattr__(self, key, obj):
  956. raise NotImplementedError()
  957. def clear(self):
  958. """Dictionary clear() is not implemented for
  959. :class:`_sql.ColumnCollection`."""
  960. raise NotImplementedError()
  961. def remove(self, column):
  962. """Dictionary remove() is not implemented for
  963. :class:`_sql.ColumnCollection`."""
  964. raise NotImplementedError()
  965. def update(self, iter_):
  966. """Dictionary update() is not implemented for
  967. :class:`_sql.ColumnCollection`."""
  968. raise NotImplementedError()
  969. __hash__ = None
  970. def _populate_separate_keys(self, iter_):
  971. """populate from an iterator of (key, column)"""
  972. cols = list(iter_)
  973. self._collection[:] = cols
  974. self._colset.update(c for k, c in self._collection)
  975. self._index.update(
  976. (idx, c) for idx, (k, c) in enumerate(self._collection)
  977. )
  978. self._index.update({k: col for k, col in reversed(self._collection)})
  979. def add(self, column, key=None):
  980. """Add a column to this :class:`_sql.ColumnCollection`.
  981. .. note::
  982. This method is **not normally used by user-facing code**, as the
  983. :class:`_sql.ColumnCollection` is usually part of an existing
  984. object such as a :class:`_schema.Table`. To add a
  985. :class:`_schema.Column` to an existing :class:`_schema.Table`
  986. object, use the :meth:`_schema.Table.append_column` method.
  987. """
  988. if key is None:
  989. key = column.key
  990. l = len(self._collection)
  991. self._collection.append((key, column))
  992. self._colset.add(column)
  993. self._index[l] = column
  994. if key not in self._index:
  995. self._index[key] = column
  996. def __getstate__(self):
  997. return {"_collection": self._collection, "_index": self._index}
  998. def __setstate__(self, state):
  999. object.__setattr__(self, "_index", state["_index"])
  1000. object.__setattr__(self, "_collection", state["_collection"])
  1001. object.__setattr__(
  1002. self, "_colset", {col for k, col in self._collection}
  1003. )
  1004. def contains_column(self, col):
  1005. """Checks if a column object exists in this collection"""
  1006. if col not in self._colset:
  1007. if isinstance(col, util.string_types):
  1008. raise exc.ArgumentError(
  1009. "contains_column cannot be used with string arguments. "
  1010. "Use ``col_name in table.c`` instead."
  1011. )
  1012. return False
  1013. else:
  1014. return True
  1015. def as_immutable(self):
  1016. """Return an "immutable" form of this
  1017. :class:`_sql.ColumnCollection`."""
  1018. return ImmutableColumnCollection(self)
  1019. def corresponding_column(self, column, require_embedded=False):
  1020. """Given a :class:`_expression.ColumnElement`, return the exported
  1021. :class:`_expression.ColumnElement` object from this
  1022. :class:`_expression.ColumnCollection`
  1023. which corresponds to that original :class:`_expression.ColumnElement`
  1024. via a common
  1025. ancestor column.
  1026. :param column: the target :class:`_expression.ColumnElement`
  1027. to be matched.
  1028. :param require_embedded: only return corresponding columns for
  1029. the given :class:`_expression.ColumnElement`, if the given
  1030. :class:`_expression.ColumnElement`
  1031. is actually present within a sub-element
  1032. of this :class:`_expression.Selectable`.
  1033. Normally the column will match if
  1034. it merely shares a common ancestor with one of the exported
  1035. columns of this :class:`_expression.Selectable`.
  1036. .. seealso::
  1037. :meth:`_expression.Selectable.corresponding_column`
  1038. - invokes this method
  1039. against the collection returned by
  1040. :attr:`_expression.Selectable.exported_columns`.
  1041. .. versionchanged:: 1.4 the implementation for ``corresponding_column``
  1042. was moved onto the :class:`_expression.ColumnCollection` itself.
  1043. """
  1044. def embedded(expanded_proxy_set, target_set):
  1045. for t in target_set.difference(expanded_proxy_set):
  1046. if not set(_expand_cloned([t])).intersection(
  1047. expanded_proxy_set
  1048. ):
  1049. return False
  1050. return True
  1051. # don't dig around if the column is locally present
  1052. if column in self._colset:
  1053. return column
  1054. col, intersect = None, None
  1055. target_set = column.proxy_set
  1056. cols = [c for (k, c) in self._collection]
  1057. for c in cols:
  1058. expanded_proxy_set = set(_expand_cloned(c.proxy_set))
  1059. i = target_set.intersection(expanded_proxy_set)
  1060. if i and (
  1061. not require_embedded
  1062. or embedded(expanded_proxy_set, target_set)
  1063. ):
  1064. if col is None:
  1065. # no corresponding column yet, pick this one.
  1066. col, intersect = c, i
  1067. elif len(i) > len(intersect):
  1068. # 'c' has a larger field of correspondence than
  1069. # 'col'. i.e. selectable.c.a1_x->a1.c.x->table.c.x
  1070. # matches a1.c.x->table.c.x better than
  1071. # selectable.c.x->table.c.x does.
  1072. col, intersect = c, i
  1073. elif i == intersect:
  1074. # they have the same field of correspondence. see
  1075. # which proxy_set has fewer columns in it, which
  1076. # indicates a closer relationship with the root
  1077. # column. Also take into account the "weight"
  1078. # attribute which CompoundSelect() uses to give
  1079. # higher precedence to columns based on vertical
  1080. # position in the compound statement, and discard
  1081. # columns that have no reference to the target
  1082. # column (also occurs with CompoundSelect)
  1083. col_distance = util.reduce(
  1084. operator.add,
  1085. [
  1086. sc._annotations.get("weight", 1)
  1087. for sc in col._uncached_proxy_set()
  1088. if sc.shares_lineage(column)
  1089. ],
  1090. )
  1091. c_distance = util.reduce(
  1092. operator.add,
  1093. [
  1094. sc._annotations.get("weight", 1)
  1095. for sc in c._uncached_proxy_set()
  1096. if sc.shares_lineage(column)
  1097. ],
  1098. )
  1099. if c_distance < col_distance:
  1100. col, intersect = c, i
  1101. return col
  1102. class DedupeColumnCollection(ColumnCollection):
  1103. """A :class:`_expression.ColumnCollection`
  1104. that maintains deduplicating behavior.
  1105. This is useful by schema level objects such as :class:`_schema.Table` and
  1106. :class:`.PrimaryKeyConstraint`. The collection includes more
  1107. sophisticated mutator methods as well to suit schema objects which
  1108. require mutable column collections.
  1109. .. versionadded:: 1.4
  1110. """
  1111. def add(self, column, key=None):
  1112. if key is not None and column.key != key:
  1113. raise exc.ArgumentError(
  1114. "DedupeColumnCollection requires columns be under "
  1115. "the same key as their .key"
  1116. )
  1117. key = column.key
  1118. if key is None:
  1119. raise exc.ArgumentError(
  1120. "Can't add unnamed column to column collection"
  1121. )
  1122. if key in self._index:
  1123. existing = self._index[key]
  1124. if existing is column:
  1125. return
  1126. self.replace(column)
  1127. # pop out memoized proxy_set as this
  1128. # operation may very well be occurring
  1129. # in a _make_proxy operation
  1130. util.memoized_property.reset(column, "proxy_set")
  1131. else:
  1132. l = len(self._collection)
  1133. self._collection.append((key, column))
  1134. self._colset.add(column)
  1135. self._index[l] = column
  1136. self._index[key] = column
  1137. def _populate_separate_keys(self, iter_):
  1138. """populate from an iterator of (key, column)"""
  1139. cols = list(iter_)
  1140. replace_col = []
  1141. for k, col in cols:
  1142. if col.key != k:
  1143. raise exc.ArgumentError(
  1144. "DedupeColumnCollection requires columns be under "
  1145. "the same key as their .key"
  1146. )
  1147. if col.name in self._index and col.key != col.name:
  1148. replace_col.append(col)
  1149. elif col.key in self._index:
  1150. replace_col.append(col)
  1151. else:
  1152. self._index[k] = col
  1153. self._collection.append((k, col))
  1154. self._colset.update(c for (k, c) in self._collection)
  1155. self._index.update(
  1156. (idx, c) for idx, (k, c) in enumerate(self._collection)
  1157. )
  1158. for col in replace_col:
  1159. self.replace(col)
  1160. def extend(self, iter_):
  1161. self._populate_separate_keys((col.key, col) for col in iter_)
  1162. def remove(self, column):
  1163. if column not in self._colset:
  1164. raise ValueError(
  1165. "Can't remove column %r; column is not in this collection"
  1166. % column
  1167. )
  1168. del self._index[column.key]
  1169. self._colset.remove(column)
  1170. self._collection[:] = [
  1171. (k, c) for (k, c) in self._collection if c is not column
  1172. ]
  1173. self._index.update(
  1174. {idx: col for idx, (k, col) in enumerate(self._collection)}
  1175. )
  1176. # delete higher index
  1177. del self._index[len(self._collection)]
  1178. def replace(self, column):
  1179. """add the given column to this collection, removing unaliased
  1180. versions of this column as well as existing columns with the
  1181. same key.
  1182. e.g.::
  1183. t = Table('sometable', metadata, Column('col1', Integer))
  1184. t.columns.replace(Column('col1', Integer, key='columnone'))
  1185. will remove the original 'col1' from the collection, and add
  1186. the new column under the name 'columnname'.
  1187. Used by schema.Column to override columns during table reflection.
  1188. """
  1189. remove_col = set()
  1190. # remove up to two columns based on matches of name as well as key
  1191. if column.name in self._index and column.key != column.name:
  1192. other = self._index[column.name]
  1193. if other.name == other.key:
  1194. remove_col.add(other)
  1195. if column.key in self._index:
  1196. remove_col.add(self._index[column.key])
  1197. new_cols = []
  1198. replaced = False
  1199. for k, col in self._collection:
  1200. if col in remove_col:
  1201. if not replaced:
  1202. replaced = True
  1203. new_cols.append((column.key, column))
  1204. else:
  1205. new_cols.append((k, col))
  1206. if remove_col:
  1207. self._colset.difference_update(remove_col)
  1208. if not replaced:
  1209. new_cols.append((column.key, column))
  1210. self._colset.add(column)
  1211. self._collection[:] = new_cols
  1212. self._index.clear()
  1213. self._index.update(
  1214. {idx: col for idx, (k, col) in enumerate(self._collection)}
  1215. )
  1216. self._index.update(self._collection)
  1217. class ImmutableColumnCollection(util.ImmutableContainer, ColumnCollection):
  1218. __slots__ = ("_parent",)
  1219. def __init__(self, collection):
  1220. object.__setattr__(self, "_parent", collection)
  1221. object.__setattr__(self, "_colset", collection._colset)
  1222. object.__setattr__(self, "_index", collection._index)
  1223. object.__setattr__(self, "_collection", collection._collection)
  1224. def __getstate__(self):
  1225. return {"_parent": self._parent}
  1226. def __setstate__(self, state):
  1227. parent = state["_parent"]
  1228. self.__init__(parent)
  1229. add = extend = remove = util.ImmutableContainer._immutable
  1230. class ColumnSet(util.ordered_column_set):
  1231. def contains_column(self, col):
  1232. return col in self
  1233. def extend(self, cols):
  1234. for col in cols:
  1235. self.add(col)
  1236. def __add__(self, other):
  1237. return list(self) + list(other)
  1238. def __eq__(self, other):
  1239. l = []
  1240. for c in other:
  1241. for local in self:
  1242. if c.shares_lineage(local):
  1243. l.append(c == local)
  1244. return elements.and_(*l)
  1245. def __hash__(self):
  1246. return hash(tuple(x for x in self))
  1247. def _bind_or_error(schemaitem, msg=None):
  1248. util.warn_deprecated_20(
  1249. "The ``bind`` argument for schema methods that invoke SQL "
  1250. "against an engine or connection will be required in SQLAlchemy 2.0."
  1251. )
  1252. bind = schemaitem.bind
  1253. if not bind:
  1254. name = schemaitem.__class__.__name__
  1255. label = getattr(
  1256. schemaitem, "fullname", getattr(schemaitem, "name", None)
  1257. )
  1258. if label:
  1259. item = "%s object %r" % (name, label)
  1260. else:
  1261. item = "%s object" % name
  1262. if msg is None:
  1263. msg = (
  1264. "%s is not bound to an Engine or Connection. "
  1265. "Execution can not proceed without a database to execute "
  1266. "against." % item
  1267. )
  1268. raise exc.UnboundExecutionError(msg)
  1269. return bind
  1270. def _entity_namespace(entity):
  1271. """Return the nearest .entity_namespace for the given entity.
  1272. If not immediately available, does an iterate to find a sub-element
  1273. that has one, if any.
  1274. """
  1275. try:
  1276. return entity.entity_namespace
  1277. except AttributeError:
  1278. for elem in visitors.iterate(entity):
  1279. if hasattr(elem, "entity_namespace"):
  1280. return elem.entity_namespace
  1281. else:
  1282. raise
  1283. def _entity_namespace_key(entity, key):
  1284. """Return an entry from an entity_namespace.
  1285. Raises :class:`_exc.InvalidRequestError` rather than attribute error
  1286. on not found.
  1287. """
  1288. try:
  1289. ns = _entity_namespace(entity)
  1290. return getattr(ns, key)
  1291. except AttributeError as err:
  1292. util.raise_(
  1293. exc.InvalidRequestError(
  1294. 'Entity namespace for "%s" has no property "%s"'
  1295. % (entity, key)
  1296. ),
  1297. replace_context=err,
  1298. )