base.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  1. # sql/base.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. """Foundational utilities common to many sql modules.
  9. """
  10. from __future__ import annotations
  11. import collections
  12. from enum import Enum
  13. import itertools
  14. from itertools import zip_longest
  15. import operator
  16. import re
  17. from typing import Any
  18. from typing import Callable
  19. from typing import cast
  20. from typing import Dict
  21. from typing import FrozenSet
  22. from typing import Generic
  23. from typing import Iterable
  24. from typing import Iterator
  25. from typing import List
  26. from typing import Mapping
  27. from typing import MutableMapping
  28. from typing import NamedTuple
  29. from typing import NoReturn
  30. from typing import Optional
  31. from typing import overload
  32. from typing import Sequence
  33. from typing import Set
  34. from typing import Tuple
  35. from typing import Type
  36. from typing import TYPE_CHECKING
  37. from typing import TypeVar
  38. from typing import Union
  39. from . import roles
  40. from . import visitors
  41. from .cache_key import HasCacheKey # noqa
  42. from .cache_key import MemoizedHasCacheKey # noqa
  43. from .traversals import HasCopyInternals # noqa
  44. from .visitors import ClauseVisitor
  45. from .visitors import ExtendedInternalTraversal
  46. from .visitors import ExternallyTraversible
  47. from .visitors import InternalTraversal
  48. from .. import event
  49. from .. import exc
  50. from .. import util
  51. from ..util import HasMemoized as HasMemoized
  52. from ..util import hybridmethod
  53. from ..util import typing as compat_typing
  54. from ..util.typing import Protocol
  55. from ..util.typing import Self
  56. from ..util.typing import TypeGuard
  57. if TYPE_CHECKING:
  58. from . import coercions
  59. from . import elements
  60. from . import type_api
  61. from ._orm_types import DMLStrategyArgument
  62. from ._orm_types import SynchronizeSessionArgument
  63. from ._typing import _CLE
  64. from .elements import BindParameter
  65. from .elements import ClauseList
  66. from .elements import ColumnClause # noqa
  67. from .elements import ColumnElement
  68. from .elements import KeyedColumnElement
  69. from .elements import NamedColumn
  70. from .elements import SQLCoreOperations
  71. from .elements import TextClause
  72. from .schema import Column
  73. from .schema import DefaultGenerator
  74. from .selectable import _JoinTargetElement
  75. from .selectable import _SelectIterable
  76. from .selectable import FromClause
  77. from ..engine import Connection
  78. from ..engine import CursorResult
  79. from ..engine.interfaces import _CoreMultiExecuteParams
  80. from ..engine.interfaces import _ExecuteOptions
  81. from ..engine.interfaces import _ImmutableExecuteOptions
  82. from ..engine.interfaces import CacheStats
  83. from ..engine.interfaces import Compiled
  84. from ..engine.interfaces import CompiledCacheType
  85. from ..engine.interfaces import CoreExecuteOptionsParameter
  86. from ..engine.interfaces import Dialect
  87. from ..engine.interfaces import IsolationLevel
  88. from ..engine.interfaces import SchemaTranslateMapType
  89. from ..event import dispatcher
  90. if not TYPE_CHECKING:
  91. coercions = None # noqa
  92. elements = None # noqa
  93. type_api = None # noqa
  94. class _NoArg(Enum):
  95. NO_ARG = 0
  96. def __repr__(self):
  97. return f"_NoArg.{self.name}"
  98. NO_ARG = _NoArg.NO_ARG
  99. class _NoneName(Enum):
  100. NONE_NAME = 0
  101. """indicate a 'deferred' name that was ultimately the value None."""
  102. _NONE_NAME = _NoneName.NONE_NAME
  103. _T = TypeVar("_T", bound=Any)
  104. _Fn = TypeVar("_Fn", bound=Callable[..., Any])
  105. _AmbiguousTableNameMap = MutableMapping[str, str]
  106. class _DefaultDescriptionTuple(NamedTuple):
  107. arg: Any
  108. is_scalar: Optional[bool]
  109. is_callable: Optional[bool]
  110. is_sentinel: Optional[bool]
  111. @classmethod
  112. def _from_column_default(
  113. cls, default: Optional[DefaultGenerator]
  114. ) -> _DefaultDescriptionTuple:
  115. return (
  116. _DefaultDescriptionTuple(
  117. default.arg, # type: ignore
  118. default.is_scalar,
  119. default.is_callable,
  120. default.is_sentinel,
  121. )
  122. if default
  123. and (
  124. default.has_arg
  125. or (not default.for_update and default.is_sentinel)
  126. )
  127. else _DefaultDescriptionTuple(None, None, None, None)
  128. )
  129. _never_select_column = operator.attrgetter("_omit_from_statements")
  130. class _EntityNamespace(Protocol):
  131. def __getattr__(self, key: str) -> SQLCoreOperations[Any]:
  132. ...
  133. class _HasEntityNamespace(Protocol):
  134. @util.ro_non_memoized_property
  135. def entity_namespace(self) -> _EntityNamespace:
  136. ...
  137. def _is_has_entity_namespace(element: Any) -> TypeGuard[_HasEntityNamespace]:
  138. return hasattr(element, "entity_namespace")
  139. # Remove when https://github.com/python/mypy/issues/14640 will be fixed
  140. _Self = TypeVar("_Self", bound=Any)
  141. class Immutable:
  142. """mark a ClauseElement as 'immutable' when expressions are cloned.
  143. "immutable" objects refers to the "mutability" of an object in the
  144. context of SQL DQL and DML generation. Such as, in DQL, one can
  145. compose a SELECT or subquery of varied forms, but one cannot modify
  146. the structure of a specific table or column within DQL.
  147. :class:`.Immutable` is mostly intended to follow this concept, and as
  148. such the primary "immutable" objects are :class:`.ColumnClause`,
  149. :class:`.Column`, :class:`.TableClause`, :class:`.Table`.
  150. """
  151. __slots__ = ()
  152. _is_immutable = True
  153. def unique_params(self, *optionaldict, **kwargs):
  154. raise NotImplementedError("Immutable objects do not support copying")
  155. def params(self, *optionaldict, **kwargs):
  156. raise NotImplementedError("Immutable objects do not support copying")
  157. def _clone(self: _Self, **kw: Any) -> _Self:
  158. return self
  159. def _copy_internals(
  160. self, *, omit_attrs: Iterable[str] = (), **kw: Any
  161. ) -> None:
  162. pass
  163. class SingletonConstant(Immutable):
  164. """Represent SQL constants like NULL, TRUE, FALSE"""
  165. _is_singleton_constant = True
  166. _singleton: SingletonConstant
  167. def __new__(cls: _T, *arg: Any, **kw: Any) -> _T:
  168. return cast(_T, cls._singleton)
  169. @util.non_memoized_property
  170. def proxy_set(self) -> FrozenSet[ColumnElement[Any]]:
  171. raise NotImplementedError()
  172. @classmethod
  173. def _create_singleton(cls):
  174. obj = object.__new__(cls)
  175. obj.__init__() # type: ignore
  176. # for a long time this was an empty frozenset, meaning
  177. # a SingletonConstant would never be a "corresponding column" in
  178. # a statement. This referred to #6259. However, in #7154 we see
  179. # that we do in fact need "correspondence" to work when matching cols
  180. # in result sets, so the non-correspondence was moved to a more
  181. # specific level when we are actually adapting expressions for SQL
  182. # render only.
  183. obj.proxy_set = frozenset([obj])
  184. cls._singleton = obj
  185. def _from_objects(
  186. *elements: Union[
  187. ColumnElement[Any], FromClause, TextClause, _JoinTargetElement
  188. ]
  189. ) -> Iterator[FromClause]:
  190. return itertools.chain.from_iterable(
  191. [element._from_objects for element in elements]
  192. )
  193. def _select_iterables(
  194. elements: Iterable[roles.ColumnsClauseRole],
  195. ) -> _SelectIterable:
  196. """expand tables into individual columns in the
  197. given list of column expressions.
  198. """
  199. return itertools.chain.from_iterable(
  200. [c._select_iterable for c in elements]
  201. )
  202. _SelfGenerativeType = TypeVar("_SelfGenerativeType", bound="_GenerativeType")
  203. class _GenerativeType(compat_typing.Protocol):
  204. def _generate(self) -> Self:
  205. ...
  206. def _generative(fn: _Fn) -> _Fn:
  207. """non-caching _generative() decorator.
  208. This is basically the legacy decorator that copies the object and
  209. runs a method on the new copy.
  210. """
  211. @util.decorator
  212. def _generative(
  213. fn: _Fn, self: _SelfGenerativeType, *args: Any, **kw: Any
  214. ) -> _SelfGenerativeType:
  215. """Mark a method as generative."""
  216. self = self._generate()
  217. x = fn(self, *args, **kw)
  218. assert x is self, "generative methods must return self"
  219. return self
  220. decorated = _generative(fn)
  221. decorated.non_generative = fn # type: ignore
  222. return decorated
  223. def _exclusive_against(*names: str, **kw: Any) -> Callable[[_Fn], _Fn]:
  224. msgs = kw.pop("msgs", {})
  225. defaults = kw.pop("defaults", {})
  226. getters = [
  227. (name, operator.attrgetter(name), defaults.get(name, None))
  228. for name in names
  229. ]
  230. @util.decorator
  231. def check(fn, *args, **kw):
  232. # make pylance happy by not including "self" in the argument
  233. # list
  234. self = args[0]
  235. args = args[1:]
  236. for name, getter, default_ in getters:
  237. if getter(self) is not default_:
  238. msg = msgs.get(
  239. name,
  240. "Method %s() has already been invoked on this %s construct"
  241. % (fn.__name__, self.__class__),
  242. )
  243. raise exc.InvalidRequestError(msg)
  244. return fn(self, *args, **kw)
  245. return check
  246. def _clone(element, **kw):
  247. return element._clone(**kw)
  248. def _expand_cloned(
  249. elements: Iterable[_CLE],
  250. ) -> Iterable[_CLE]:
  251. """expand the given set of ClauseElements to be the set of all 'cloned'
  252. predecessors.
  253. """
  254. # TODO: cython candidate
  255. return itertools.chain(*[x._cloned_set for x in elements])
  256. def _de_clone(
  257. elements: Iterable[_CLE],
  258. ) -> Iterable[_CLE]:
  259. for x in elements:
  260. while x._is_clone_of is not None:
  261. x = x._is_clone_of
  262. yield x
  263. def _cloned_intersection(a: Iterable[_CLE], b: Iterable[_CLE]) -> Set[_CLE]:
  264. """return the intersection of sets a and b, counting
  265. any overlap between 'cloned' predecessors.
  266. The returned set is in terms of the entities present within 'a'.
  267. """
  268. all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
  269. return {elem for elem in a if all_overlap.intersection(elem._cloned_set)}
  270. def _cloned_difference(a: Iterable[_CLE], b: Iterable[_CLE]) -> Set[_CLE]:
  271. all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))
  272. return {
  273. elem for elem in a if not all_overlap.intersection(elem._cloned_set)
  274. }
  275. class _DialectArgView(MutableMapping[str, Any]):
  276. """A dictionary view of dialect-level arguments in the form
  277. <dialectname>_<argument_name>.
  278. """
  279. def __init__(self, obj):
  280. self.obj = obj
  281. def _key(self, key):
  282. try:
  283. dialect, value_key = key.split("_", 1)
  284. except ValueError as err:
  285. raise KeyError(key) from err
  286. else:
  287. return dialect, value_key
  288. def __getitem__(self, key):
  289. dialect, value_key = self._key(key)
  290. try:
  291. opt = self.obj.dialect_options[dialect]
  292. except exc.NoSuchModuleError as err:
  293. raise KeyError(key) from err
  294. else:
  295. return opt[value_key]
  296. def __setitem__(self, key, value):
  297. try:
  298. dialect, value_key = self._key(key)
  299. except KeyError as err:
  300. raise exc.ArgumentError(
  301. "Keys must be of the form <dialectname>_<argname>"
  302. ) from err
  303. else:
  304. self.obj.dialect_options[dialect][value_key] = value
  305. def __delitem__(self, key):
  306. dialect, value_key = self._key(key)
  307. del self.obj.dialect_options[dialect][value_key]
  308. def __len__(self):
  309. return sum(
  310. len(args._non_defaults)
  311. for args in self.obj.dialect_options.values()
  312. )
  313. def __iter__(self):
  314. return (
  315. "%s_%s" % (dialect_name, value_name)
  316. for dialect_name in self.obj.dialect_options
  317. for value_name in self.obj.dialect_options[
  318. dialect_name
  319. ]._non_defaults
  320. )
  321. class _DialectArgDict(MutableMapping[str, Any]):
  322. """A dictionary view of dialect-level arguments for a specific
  323. dialect.
  324. Maintains a separate collection of user-specified arguments
  325. and dialect-specified default arguments.
  326. """
  327. def __init__(self):
  328. self._non_defaults = {}
  329. self._defaults = {}
  330. def __len__(self):
  331. return len(set(self._non_defaults).union(self._defaults))
  332. def __iter__(self):
  333. return iter(set(self._non_defaults).union(self._defaults))
  334. def __getitem__(self, key):
  335. if key in self._non_defaults:
  336. return self._non_defaults[key]
  337. else:
  338. return self._defaults[key]
  339. def __setitem__(self, key, value):
  340. self._non_defaults[key] = value
  341. def __delitem__(self, key):
  342. del self._non_defaults[key]
  343. @util.preload_module("sqlalchemy.dialects")
  344. def _kw_reg_for_dialect(dialect_name):
  345. dialect_cls = util.preloaded.dialects.registry.load(dialect_name)
  346. if dialect_cls.construct_arguments is None:
  347. return None
  348. return dict(dialect_cls.construct_arguments)
  349. class DialectKWArgs:
  350. """Establish the ability for a class to have dialect-specific arguments
  351. with defaults and constructor validation.
  352. The :class:`.DialectKWArgs` interacts with the
  353. :attr:`.DefaultDialect.construct_arguments` present on a dialect.
  354. .. seealso::
  355. :attr:`.DefaultDialect.construct_arguments`
  356. """
  357. __slots__ = ()
  358. _dialect_kwargs_traverse_internals = [
  359. ("dialect_options", InternalTraversal.dp_dialect_options)
  360. ]
  361. @classmethod
  362. def argument_for(cls, dialect_name, argument_name, default):
  363. """Add a new kind of dialect-specific keyword argument for this class.
  364. E.g.::
  365. Index.argument_for("mydialect", "length", None)
  366. some_index = Index('a', 'b', mydialect_length=5)
  367. The :meth:`.DialectKWArgs.argument_for` method is a per-argument
  368. way adding extra arguments to the
  369. :attr:`.DefaultDialect.construct_arguments` dictionary. This
  370. dictionary provides a list of argument names accepted by various
  371. schema-level constructs on behalf of a dialect.
  372. New dialects should typically specify this dictionary all at once as a
  373. data member of the dialect class. The use case for ad-hoc addition of
  374. argument names is typically for end-user code that is also using
  375. a custom compilation scheme which consumes the additional arguments.
  376. :param dialect_name: name of a dialect. The dialect must be
  377. locatable, else a :class:`.NoSuchModuleError` is raised. The
  378. dialect must also include an existing
  379. :attr:`.DefaultDialect.construct_arguments` collection, indicating
  380. that it participates in the keyword-argument validation and default
  381. system, else :class:`.ArgumentError` is raised. If the dialect does
  382. not include this collection, then any keyword argument can be
  383. specified on behalf of this dialect already. All dialects packaged
  384. within SQLAlchemy include this collection, however for third party
  385. dialects, support may vary.
  386. :param argument_name: name of the parameter.
  387. :param default: default value of the parameter.
  388. """
  389. construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
  390. if construct_arg_dictionary is None:
  391. raise exc.ArgumentError(
  392. "Dialect '%s' does have keyword-argument "
  393. "validation and defaults enabled configured" % dialect_name
  394. )
  395. if cls not in construct_arg_dictionary:
  396. construct_arg_dictionary[cls] = {}
  397. construct_arg_dictionary[cls][argument_name] = default
  398. @util.memoized_property
  399. def dialect_kwargs(self):
  400. """A collection of keyword arguments specified as dialect-specific
  401. options to this construct.
  402. The arguments are present here in their original ``<dialect>_<kwarg>``
  403. format. Only arguments that were actually passed are included;
  404. unlike the :attr:`.DialectKWArgs.dialect_options` collection, which
  405. contains all options known by this dialect including defaults.
  406. The collection is also writable; keys are accepted of the
  407. form ``<dialect>_<kwarg>`` where the value will be assembled
  408. into the list of options.
  409. .. seealso::
  410. :attr:`.DialectKWArgs.dialect_options` - nested dictionary form
  411. """
  412. return _DialectArgView(self)
  413. @property
  414. def kwargs(self):
  415. """A synonym for :attr:`.DialectKWArgs.dialect_kwargs`."""
  416. return self.dialect_kwargs
  417. _kw_registry = util.PopulateDict(_kw_reg_for_dialect)
  418. def _kw_reg_for_dialect_cls(self, dialect_name):
  419. construct_arg_dictionary = DialectKWArgs._kw_registry[dialect_name]
  420. d = _DialectArgDict()
  421. if construct_arg_dictionary is None:
  422. d._defaults.update({"*": None})
  423. else:
  424. for cls in reversed(self.__class__.__mro__):
  425. if cls in construct_arg_dictionary:
  426. d._defaults.update(construct_arg_dictionary[cls])
  427. return d
  428. @util.memoized_property
  429. def dialect_options(self):
  430. """A collection of keyword arguments specified as dialect-specific
  431. options to this construct.
  432. This is a two-level nested registry, keyed to ``<dialect_name>``
  433. and ``<argument_name>``. For example, the ``postgresql_where``
  434. argument would be locatable as::
  435. arg = my_object.dialect_options['postgresql']['where']
  436. .. versionadded:: 0.9.2
  437. .. seealso::
  438. :attr:`.DialectKWArgs.dialect_kwargs` - flat dictionary form
  439. """
  440. return util.PopulateDict(
  441. util.portable_instancemethod(self._kw_reg_for_dialect_cls)
  442. )
  443. def _validate_dialect_kwargs(self, kwargs: Dict[str, Any]) -> None:
  444. # validate remaining kwargs that they all specify DB prefixes
  445. if not kwargs:
  446. return
  447. for k in kwargs:
  448. m = re.match("^(.+?)_(.+)$", k)
  449. if not m:
  450. raise TypeError(
  451. "Additional arguments should be "
  452. "named <dialectname>_<argument>, got '%s'" % k
  453. )
  454. dialect_name, arg_name = m.group(1, 2)
  455. try:
  456. construct_arg_dictionary = self.dialect_options[dialect_name]
  457. except exc.NoSuchModuleError:
  458. util.warn(
  459. "Can't validate argument %r; can't "
  460. "locate any SQLAlchemy dialect named %r"
  461. % (k, dialect_name)
  462. )
  463. self.dialect_options[dialect_name] = d = _DialectArgDict()
  464. d._defaults.update({"*": None})
  465. d._non_defaults[arg_name] = kwargs[k]
  466. else:
  467. if (
  468. "*" not in construct_arg_dictionary
  469. and arg_name not in construct_arg_dictionary
  470. ):
  471. raise exc.ArgumentError(
  472. "Argument %r is not accepted by "
  473. "dialect %r on behalf of %r"
  474. % (k, dialect_name, self.__class__)
  475. )
  476. else:
  477. construct_arg_dictionary[arg_name] = kwargs[k]
  478. class CompileState:
  479. """Produces additional object state necessary for a statement to be
  480. compiled.
  481. the :class:`.CompileState` class is at the base of classes that assemble
  482. state for a particular statement object that is then used by the
  483. compiler. This process is essentially an extension of the process that
  484. the SQLCompiler.visit_XYZ() method takes, however there is an emphasis
  485. on converting raw user intent into more organized structures rather than
  486. producing string output. The top-level :class:`.CompileState` for the
  487. statement being executed is also accessible when the execution context
  488. works with invoking the statement and collecting results.
  489. The production of :class:`.CompileState` is specific to the compiler, such
  490. as within the :meth:`.SQLCompiler.visit_insert`,
  491. :meth:`.SQLCompiler.visit_select` etc. methods. These methods are also
  492. responsible for associating the :class:`.CompileState` with the
  493. :class:`.SQLCompiler` itself, if the statement is the "toplevel" statement,
  494. i.e. the outermost SQL statement that's actually being executed.
  495. There can be other :class:`.CompileState` objects that are not the
  496. toplevel, such as when a SELECT subquery or CTE-nested
  497. INSERT/UPDATE/DELETE is generated.
  498. .. versionadded:: 1.4
  499. """
  500. __slots__ = ("statement", "_ambiguous_table_name_map")
  501. plugins: Dict[Tuple[str, str], Type[CompileState]] = {}
  502. _ambiguous_table_name_map: Optional[_AmbiguousTableNameMap]
  503. @classmethod
  504. def create_for_statement(cls, statement, compiler, **kw):
  505. # factory construction.
  506. if statement._propagate_attrs:
  507. plugin_name = statement._propagate_attrs.get(
  508. "compile_state_plugin", "default"
  509. )
  510. klass = cls.plugins.get(
  511. (plugin_name, statement._effective_plugin_target), None
  512. )
  513. if klass is None:
  514. klass = cls.plugins[
  515. ("default", statement._effective_plugin_target)
  516. ]
  517. else:
  518. klass = cls.plugins[
  519. ("default", statement._effective_plugin_target)
  520. ]
  521. if klass is cls:
  522. return cls(statement, compiler, **kw)
  523. else:
  524. return klass.create_for_statement(statement, compiler, **kw)
  525. def __init__(self, statement, compiler, **kw):
  526. self.statement = statement
  527. @classmethod
  528. def get_plugin_class(
  529. cls, statement: Executable
  530. ) -> Optional[Type[CompileState]]:
  531. plugin_name = statement._propagate_attrs.get(
  532. "compile_state_plugin", None
  533. )
  534. if plugin_name:
  535. key = (plugin_name, statement._effective_plugin_target)
  536. if key in cls.plugins:
  537. return cls.plugins[key]
  538. # there's no case where we call upon get_plugin_class() and want
  539. # to get None back, there should always be a default. return that
  540. # if there was no plugin-specific class (e.g. Insert with "orm"
  541. # plugin)
  542. try:
  543. return cls.plugins[("default", statement._effective_plugin_target)]
  544. except KeyError:
  545. return None
  546. @classmethod
  547. def _get_plugin_class_for_plugin(
  548. cls, statement: Executable, plugin_name: str
  549. ) -> Optional[Type[CompileState]]:
  550. try:
  551. return cls.plugins[
  552. (plugin_name, statement._effective_plugin_target)
  553. ]
  554. except KeyError:
  555. return None
  556. @classmethod
  557. def plugin_for(
  558. cls, plugin_name: str, visit_name: str
  559. ) -> Callable[[_Fn], _Fn]:
  560. def decorate(cls_to_decorate):
  561. cls.plugins[(plugin_name, visit_name)] = cls_to_decorate
  562. return cls_to_decorate
  563. return decorate
  564. class Generative(HasMemoized):
  565. """Provide a method-chaining pattern in conjunction with the
  566. @_generative decorator."""
  567. def _generate(self) -> Self:
  568. skip = self._memoized_keys
  569. cls = self.__class__
  570. s = cls.__new__(cls)
  571. if skip:
  572. # ensure this iteration remains atomic
  573. s.__dict__ = {
  574. k: v for k, v in self.__dict__.copy().items() if k not in skip
  575. }
  576. else:
  577. s.__dict__ = self.__dict__.copy()
  578. return s
  579. class InPlaceGenerative(HasMemoized):
  580. """Provide a method-chaining pattern in conjunction with the
  581. @_generative decorator that mutates in place."""
  582. __slots__ = ()
  583. def _generate(self):
  584. skip = self._memoized_keys
  585. # note __dict__ needs to be in __slots__ if this is used
  586. for k in skip:
  587. self.__dict__.pop(k, None)
  588. return self
  589. class HasCompileState(Generative):
  590. """A class that has a :class:`.CompileState` associated with it."""
  591. _compile_state_plugin: Optional[Type[CompileState]] = None
  592. _attributes: util.immutabledict[str, Any] = util.EMPTY_DICT
  593. _compile_state_factory = CompileState.create_for_statement
  594. class _MetaOptions(type):
  595. """metaclass for the Options class.
  596. This metaclass is actually necessary despite the availability of the
  597. ``__init_subclass__()`` hook as this type also provides custom class-level
  598. behavior for the ``__add__()`` method.
  599. """
  600. _cache_attrs: Tuple[str, ...]
  601. def __add__(self, other):
  602. o1 = self()
  603. if set(other).difference(self._cache_attrs):
  604. raise TypeError(
  605. "dictionary contains attributes not covered by "
  606. "Options class %s: %r"
  607. % (self, set(other).difference(self._cache_attrs))
  608. )
  609. o1.__dict__.update(other)
  610. return o1
  611. if TYPE_CHECKING:
  612. def __getattr__(self, key: str) -> Any:
  613. ...
  614. def __setattr__(self, key: str, value: Any) -> None:
  615. ...
  616. def __delattr__(self, key: str) -> None:
  617. ...
  618. class Options(metaclass=_MetaOptions):
  619. """A cacheable option dictionary with defaults."""
  620. __slots__ = ()
  621. _cache_attrs: Tuple[str, ...]
  622. def __init_subclass__(cls) -> None:
  623. dict_ = cls.__dict__
  624. cls._cache_attrs = tuple(
  625. sorted(
  626. d
  627. for d in dict_
  628. if not d.startswith("__")
  629. and d not in ("_cache_key_traversal",)
  630. )
  631. )
  632. super().__init_subclass__()
  633. def __init__(self, **kw):
  634. self.__dict__.update(kw)
  635. def __add__(self, other):
  636. o1 = self.__class__.__new__(self.__class__)
  637. o1.__dict__.update(self.__dict__)
  638. if set(other).difference(self._cache_attrs):
  639. raise TypeError(
  640. "dictionary contains attributes not covered by "
  641. "Options class %s: %r"
  642. % (self, set(other).difference(self._cache_attrs))
  643. )
  644. o1.__dict__.update(other)
  645. return o1
  646. def __eq__(self, other):
  647. # TODO: very inefficient. This is used only in test suites
  648. # right now.
  649. for a, b in zip_longest(self._cache_attrs, other._cache_attrs):
  650. if getattr(self, a) != getattr(other, b):
  651. return False
  652. return True
  653. def __repr__(self):
  654. # TODO: fairly inefficient, used only in debugging right now.
  655. return "%s(%s)" % (
  656. self.__class__.__name__,
  657. ", ".join(
  658. "%s=%r" % (k, self.__dict__[k])
  659. for k in self._cache_attrs
  660. if k in self.__dict__
  661. ),
  662. )
  663. @classmethod
  664. def isinstance(cls, klass: Type[Any]) -> bool:
  665. return issubclass(cls, klass)
  666. @hybridmethod
  667. def add_to_element(self, name, value):
  668. return self + {name: getattr(self, name) + value}
  669. @hybridmethod
  670. def _state_dict_inst(self) -> Mapping[str, Any]:
  671. return self.__dict__
  672. _state_dict_const: util.immutabledict[str, Any] = util.EMPTY_DICT
  673. @_state_dict_inst.classlevel
  674. def _state_dict(cls) -> Mapping[str, Any]:
  675. return cls._state_dict_const
  676. @classmethod
  677. def safe_merge(cls, other):
  678. d = other._state_dict()
  679. # only support a merge with another object of our class
  680. # and which does not have attrs that we don't. otherwise
  681. # we risk having state that might not be part of our cache
  682. # key strategy
  683. if (
  684. cls is not other.__class__
  685. and other._cache_attrs
  686. and set(other._cache_attrs).difference(cls._cache_attrs)
  687. ):
  688. raise TypeError(
  689. "other element %r is not empty, is not of type %s, "
  690. "and contains attributes not covered here %r"
  691. % (
  692. other,
  693. cls,
  694. set(other._cache_attrs).difference(cls._cache_attrs),
  695. )
  696. )
  697. return cls + d
  698. @classmethod
  699. def from_execution_options(
  700. cls, key, attrs, exec_options, statement_exec_options
  701. ):
  702. """process Options argument in terms of execution options.
  703. e.g.::
  704. (
  705. load_options,
  706. execution_options,
  707. ) = QueryContext.default_load_options.from_execution_options(
  708. "_sa_orm_load_options",
  709. {
  710. "populate_existing",
  711. "autoflush",
  712. "yield_per"
  713. },
  714. execution_options,
  715. statement._execution_options,
  716. )
  717. get back the Options and refresh "_sa_orm_load_options" in the
  718. exec options dict w/ the Options as well
  719. """
  720. # common case is that no options we are looking for are
  721. # in either dictionary, so cancel for that first
  722. check_argnames = attrs.intersection(
  723. set(exec_options).union(statement_exec_options)
  724. )
  725. existing_options = exec_options.get(key, cls)
  726. if check_argnames:
  727. result = {}
  728. for argname in check_argnames:
  729. local = "_" + argname
  730. if argname in exec_options:
  731. result[local] = exec_options[argname]
  732. elif argname in statement_exec_options:
  733. result[local] = statement_exec_options[argname]
  734. new_options = existing_options + result
  735. exec_options = util.immutabledict().merge_with(
  736. exec_options, {key: new_options}
  737. )
  738. return new_options, exec_options
  739. else:
  740. return existing_options, exec_options
  741. if TYPE_CHECKING:
  742. def __getattr__(self, key: str) -> Any:
  743. ...
  744. def __setattr__(self, key: str, value: Any) -> None:
  745. ...
  746. def __delattr__(self, key: str) -> None:
  747. ...
  748. class CacheableOptions(Options, HasCacheKey):
  749. __slots__ = ()
  750. @hybridmethod
  751. def _gen_cache_key_inst(self, anon_map, bindparams):
  752. return HasCacheKey._gen_cache_key(self, anon_map, bindparams)
  753. @_gen_cache_key_inst.classlevel
  754. def _gen_cache_key(cls, anon_map, bindparams):
  755. return (cls, ())
  756. @hybridmethod
  757. def _generate_cache_key(self):
  758. return HasCacheKey._generate_cache_key_for_object(self)
  759. class ExecutableOption(HasCopyInternals):
  760. __slots__ = ()
  761. _annotations = util.EMPTY_DICT
  762. __visit_name__ = "executable_option"
  763. _is_has_cache_key = False
  764. _is_core = True
  765. def _clone(self, **kw):
  766. """Create a shallow copy of this ExecutableOption."""
  767. c = self.__class__.__new__(self.__class__)
  768. c.__dict__ = dict(self.__dict__) # type: ignore
  769. return c
  770. class Executable(roles.StatementRole):
  771. """Mark a :class:`_expression.ClauseElement` as supporting execution.
  772. :class:`.Executable` is a superclass for all "statement" types
  773. of objects, including :func:`select`, :func:`delete`, :func:`update`,
  774. :func:`insert`, :func:`text`.
  775. """
  776. supports_execution: bool = True
  777. _execution_options: _ImmutableExecuteOptions = util.EMPTY_DICT
  778. _is_default_generator = False
  779. _with_options: Tuple[ExecutableOption, ...] = ()
  780. _with_context_options: Tuple[
  781. Tuple[Callable[[CompileState], None], Any], ...
  782. ] = ()
  783. _compile_options: Optional[Union[Type[CacheableOptions], CacheableOptions]]
  784. _executable_traverse_internals = [
  785. ("_with_options", InternalTraversal.dp_executable_options),
  786. (
  787. "_with_context_options",
  788. ExtendedInternalTraversal.dp_with_context_options,
  789. ),
  790. ("_propagate_attrs", ExtendedInternalTraversal.dp_propagate_attrs),
  791. ]
  792. is_select = False
  793. is_update = False
  794. is_insert = False
  795. is_text = False
  796. is_delete = False
  797. is_dml = False
  798. if TYPE_CHECKING:
  799. __visit_name__: str
  800. def _compile_w_cache(
  801. self,
  802. dialect: Dialect,
  803. *,
  804. compiled_cache: Optional[CompiledCacheType],
  805. column_keys: List[str],
  806. for_executemany: bool = False,
  807. schema_translate_map: Optional[SchemaTranslateMapType] = None,
  808. **kw: Any,
  809. ) -> Tuple[
  810. Compiled, Optional[Sequence[BindParameter[Any]]], CacheStats
  811. ]:
  812. ...
  813. def _execute_on_connection(
  814. self,
  815. connection: Connection,
  816. distilled_params: _CoreMultiExecuteParams,
  817. execution_options: CoreExecuteOptionsParameter,
  818. ) -> CursorResult[Any]:
  819. ...
  820. def _execute_on_scalar(
  821. self,
  822. connection: Connection,
  823. distilled_params: _CoreMultiExecuteParams,
  824. execution_options: CoreExecuteOptionsParameter,
  825. ) -> Any:
  826. ...
  827. @util.ro_non_memoized_property
  828. def _all_selected_columns(self):
  829. raise NotImplementedError()
  830. @property
  831. def _effective_plugin_target(self) -> str:
  832. return self.__visit_name__
  833. @_generative
  834. def options(self, *options: ExecutableOption) -> Self:
  835. """Apply options to this statement.
  836. In the general sense, options are any kind of Python object
  837. that can be interpreted by the SQL compiler for the statement.
  838. These options can be consumed by specific dialects or specific kinds
  839. of compilers.
  840. The most commonly known kind of option are the ORM level options
  841. that apply "eager load" and other loading behaviors to an ORM
  842. query. However, options can theoretically be used for many other
  843. purposes.
  844. For background on specific kinds of options for specific kinds of
  845. statements, refer to the documentation for those option objects.
  846. .. versionchanged:: 1.4 - added :meth:`.Executable.options` to
  847. Core statement objects towards the goal of allowing unified
  848. Core / ORM querying capabilities.
  849. .. seealso::
  850. :ref:`loading_columns` - refers to options specific to the usage
  851. of ORM queries
  852. :ref:`relationship_loader_options` - refers to options specific
  853. to the usage of ORM queries
  854. """
  855. self._with_options += tuple(
  856. coercions.expect(roles.ExecutableOptionRole, opt)
  857. for opt in options
  858. )
  859. return self
  860. @_generative
  861. def _set_compile_options(self, compile_options: CacheableOptions) -> Self:
  862. """Assign the compile options to a new value.
  863. :param compile_options: appropriate CacheableOptions structure
  864. """
  865. self._compile_options = compile_options
  866. return self
  867. @_generative
  868. def _update_compile_options(self, options: CacheableOptions) -> Self:
  869. """update the _compile_options with new keys."""
  870. assert self._compile_options is not None
  871. self._compile_options += options
  872. return self
  873. @_generative
  874. def _add_context_option(
  875. self,
  876. callable_: Callable[[CompileState], None],
  877. cache_args: Any,
  878. ) -> Self:
  879. """Add a context option to this statement.
  880. These are callable functions that will
  881. be given the CompileState object upon compilation.
  882. A second argument cache_args is required, which will be combined with
  883. the ``__code__`` identity of the function itself in order to produce a
  884. cache key.
  885. """
  886. self._with_context_options += ((callable_, cache_args),)
  887. return self
  888. @overload
  889. def execution_options(
  890. self,
  891. *,
  892. compiled_cache: Optional[CompiledCacheType] = ...,
  893. logging_token: str = ...,
  894. isolation_level: IsolationLevel = ...,
  895. no_parameters: bool = False,
  896. stream_results: bool = False,
  897. max_row_buffer: int = ...,
  898. yield_per: int = ...,
  899. insertmanyvalues_page_size: int = ...,
  900. schema_translate_map: Optional[SchemaTranslateMapType] = ...,
  901. populate_existing: bool = False,
  902. autoflush: bool = False,
  903. synchronize_session: SynchronizeSessionArgument = ...,
  904. dml_strategy: DMLStrategyArgument = ...,
  905. render_nulls: bool = ...,
  906. is_delete_using: bool = ...,
  907. is_update_from: bool = ...,
  908. **opt: Any,
  909. ) -> Self:
  910. ...
  911. @overload
  912. def execution_options(self, **opt: Any) -> Self:
  913. ...
  914. @_generative
  915. def execution_options(self, **kw: Any) -> Self:
  916. """Set non-SQL options for the statement which take effect during
  917. execution.
  918. Execution options can be set at many scopes, including per-statement,
  919. per-connection, or per execution, using methods such as
  920. :meth:`_engine.Connection.execution_options` and parameters which
  921. accept a dictionary of options such as
  922. :paramref:`_engine.Connection.execute.execution_options` and
  923. :paramref:`_orm.Session.execute.execution_options`.
  924. The primary characteristic of an execution option, as opposed to
  925. other kinds of options such as ORM loader options, is that
  926. **execution options never affect the compiled SQL of a query, only
  927. things that affect how the SQL statement itself is invoked or how
  928. results are fetched**. That is, execution options are not part of
  929. what's accommodated by SQL compilation nor are they considered part of
  930. the cached state of a statement.
  931. The :meth:`_sql.Executable.execution_options` method is
  932. :term:`generative`, as
  933. is the case for the method as applied to the :class:`_engine.Engine`
  934. and :class:`_orm.Query` objects, which means when the method is called,
  935. a copy of the object is returned, which applies the given parameters to
  936. that new copy, but leaves the original unchanged::
  937. statement = select(table.c.x, table.c.y)
  938. new_statement = statement.execution_options(my_option=True)
  939. An exception to this behavior is the :class:`_engine.Connection`
  940. object, where the :meth:`_engine.Connection.execution_options` method
  941. is explicitly **not** generative.
  942. The kinds of options that may be passed to
  943. :meth:`_sql.Executable.execution_options` and other related methods and
  944. parameter dictionaries include parameters that are explicitly consumed
  945. by SQLAlchemy Core or ORM, as well as arbitrary keyword arguments not
  946. defined by SQLAlchemy, which means the methods and/or parameter
  947. dictionaries may be used for user-defined parameters that interact with
  948. custom code, which may access the parameters using methods such as
  949. :meth:`_sql.Executable.get_execution_options` and
  950. :meth:`_engine.Connection.get_execution_options`, or within selected
  951. event hooks using a dedicated ``execution_options`` event parameter
  952. such as
  953. :paramref:`_events.ConnectionEvents.before_execute.execution_options`
  954. or :attr:`_orm.ORMExecuteState.execution_options`, e.g.::
  955. from sqlalchemy import event
  956. @event.listens_for(some_engine, "before_execute")
  957. def _process_opt(conn, statement, multiparams, params, execution_options):
  958. "run a SQL function before invoking a statement"
  959. if execution_options.get("do_special_thing", False):
  960. conn.exec_driver_sql("run_special_function()")
  961. Within the scope of options that are explicitly recognized by
  962. SQLAlchemy, most apply to specific classes of objects and not others.
  963. The most common execution options include:
  964. * :paramref:`_engine.Connection.execution_options.isolation_level` -
  965. sets the isolation level for a connection or a class of connections
  966. via an :class:`_engine.Engine`. This option is accepted only
  967. by :class:`_engine.Connection` or :class:`_engine.Engine`.
  968. * :paramref:`_engine.Connection.execution_options.stream_results` -
  969. indicates results should be fetched using a server side cursor;
  970. this option is accepted by :class:`_engine.Connection`, by the
  971. :paramref:`_engine.Connection.execute.execution_options` parameter
  972. on :meth:`_engine.Connection.execute`, and additionally by
  973. :meth:`_sql.Executable.execution_options` on a SQL statement object,
  974. as well as by ORM constructs like :meth:`_orm.Session.execute`.
  975. * :paramref:`_engine.Connection.execution_options.compiled_cache` -
  976. indicates a dictionary that will serve as the
  977. :ref:`SQL compilation cache <sql_caching>`
  978. for a :class:`_engine.Connection` or :class:`_engine.Engine`, as
  979. well as for ORM methods like :meth:`_orm.Session.execute`.
  980. Can be passed as ``None`` to disable caching for statements.
  981. This option is not accepted by
  982. :meth:`_sql.Executable.execution_options` as it is inadvisable to
  983. carry along a compilation cache within a statement object.
  984. * :paramref:`_engine.Connection.execution_options.schema_translate_map`
  985. - a mapping of schema names used by the
  986. :ref:`Schema Translate Map <schema_translating>` feature, accepted
  987. by :class:`_engine.Connection`, :class:`_engine.Engine`,
  988. :class:`_sql.Executable`, as well as by ORM constructs
  989. like :meth:`_orm.Session.execute`.
  990. .. seealso::
  991. :meth:`_engine.Connection.execution_options`
  992. :paramref:`_engine.Connection.execute.execution_options`
  993. :paramref:`_orm.Session.execute.execution_options`
  994. :ref:`orm_queryguide_execution_options` - documentation on all
  995. ORM-specific execution options
  996. """ # noqa: E501
  997. if "isolation_level" in kw:
  998. raise exc.ArgumentError(
  999. "'isolation_level' execution option may only be specified "
  1000. "on Connection.execution_options(), or "
  1001. "per-engine using the isolation_level "
  1002. "argument to create_engine()."
  1003. )
  1004. if "compiled_cache" in kw:
  1005. raise exc.ArgumentError(
  1006. "'compiled_cache' execution option may only be specified "
  1007. "on Connection.execution_options(), not per statement."
  1008. )
  1009. self._execution_options = self._execution_options.union(kw)
  1010. return self
  1011. def get_execution_options(self) -> _ExecuteOptions:
  1012. """Get the non-SQL options which will take effect during execution.
  1013. .. versionadded:: 1.3
  1014. .. seealso::
  1015. :meth:`.Executable.execution_options`
  1016. """
  1017. return self._execution_options
  1018. class SchemaEventTarget(event.EventTarget):
  1019. """Base class for elements that are the targets of :class:`.DDLEvents`
  1020. events.
  1021. This includes :class:`.SchemaItem` as well as :class:`.SchemaType`.
  1022. """
  1023. dispatch: dispatcher[SchemaEventTarget]
  1024. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  1025. """Associate with this SchemaEvent's parent object."""
  1026. def _set_parent_with_dispatch(
  1027. self, parent: SchemaEventTarget, **kw: Any
  1028. ) -> None:
  1029. self.dispatch.before_parent_attach(self, parent)
  1030. self._set_parent(parent, **kw)
  1031. self.dispatch.after_parent_attach(self, parent)
  1032. class SchemaVisitor(ClauseVisitor):
  1033. """Define the visiting for ``SchemaItem`` objects."""
  1034. __traverse_options__ = {"schema_visitor": True}
  1035. class _SentinelDefaultCharacterization(Enum):
  1036. NONE = "none"
  1037. UNKNOWN = "unknown"
  1038. CLIENTSIDE = "clientside"
  1039. SENTINEL_DEFAULT = "sentinel_default"
  1040. SERVERSIDE = "serverside"
  1041. IDENTITY = "identity"
  1042. SEQUENCE = "sequence"
  1043. class _SentinelColumnCharacterization(NamedTuple):
  1044. columns: Optional[Sequence[Column[Any]]] = None
  1045. is_explicit: bool = False
  1046. is_autoinc: bool = False
  1047. default_characterization: _SentinelDefaultCharacterization = (
  1048. _SentinelDefaultCharacterization.NONE
  1049. )
  1050. _COLKEY = TypeVar("_COLKEY", Union[None, str], str)
  1051. _COL_co = TypeVar("_COL_co", bound="ColumnElement[Any]", covariant=True)
  1052. _COL = TypeVar("_COL", bound="KeyedColumnElement[Any]")
  1053. class _ColumnMetrics(Generic[_COL_co]):
  1054. __slots__ = ("column",)
  1055. column: _COL_co
  1056. def __init__(
  1057. self, collection: ColumnCollection[Any, _COL_co], col: _COL_co
  1058. ):
  1059. self.column = col
  1060. # proxy_index being non-empty means it was initialized.
  1061. # so we need to update it
  1062. pi = collection._proxy_index
  1063. if pi:
  1064. for eps_col in col._expanded_proxy_set:
  1065. pi[eps_col].add(self)
  1066. def get_expanded_proxy_set(self):
  1067. return self.column._expanded_proxy_set
  1068. def dispose(self, collection):
  1069. pi = collection._proxy_index
  1070. if not pi:
  1071. return
  1072. for col in self.column._expanded_proxy_set:
  1073. colset = pi.get(col, None)
  1074. if colset:
  1075. colset.discard(self)
  1076. if colset is not None and not colset:
  1077. del pi[col]
  1078. def embedded(
  1079. self,
  1080. target_set: Union[
  1081. Set[ColumnElement[Any]], FrozenSet[ColumnElement[Any]]
  1082. ],
  1083. ) -> bool:
  1084. expanded_proxy_set = self.column._expanded_proxy_set
  1085. for t in target_set.difference(expanded_proxy_set):
  1086. if not expanded_proxy_set.intersection(_expand_cloned([t])):
  1087. return False
  1088. return True
  1089. class ColumnCollection(Generic[_COLKEY, _COL_co]):
  1090. """Collection of :class:`_expression.ColumnElement` instances,
  1091. typically for
  1092. :class:`_sql.FromClause` objects.
  1093. The :class:`_sql.ColumnCollection` object is most commonly available
  1094. as the :attr:`_schema.Table.c` or :attr:`_schema.Table.columns` collection
  1095. on the :class:`_schema.Table` object, introduced at
  1096. :ref:`metadata_tables_and_columns`.
  1097. The :class:`_expression.ColumnCollection` has both mapping- and sequence-
  1098. like behaviors. A :class:`_expression.ColumnCollection` usually stores
  1099. :class:`_schema.Column` objects, which are then accessible both via mapping
  1100. style access as well as attribute access style.
  1101. To access :class:`_schema.Column` objects using ordinary attribute-style
  1102. access, specify the name like any other object attribute, such as below
  1103. a column named ``employee_name`` is accessed::
  1104. >>> employee_table.c.employee_name
  1105. To access columns that have names with special characters or spaces,
  1106. index-style access is used, such as below which illustrates a column named
  1107. ``employee ' payment`` is accessed::
  1108. >>> employee_table.c["employee ' payment"]
  1109. As the :class:`_sql.ColumnCollection` object provides a Python dictionary
  1110. interface, common dictionary method names like
  1111. :meth:`_sql.ColumnCollection.keys`, :meth:`_sql.ColumnCollection.values`,
  1112. and :meth:`_sql.ColumnCollection.items` are available, which means that
  1113. database columns that are keyed under these names also need to use indexed
  1114. access::
  1115. >>> employee_table.c["values"]
  1116. The name for which a :class:`_schema.Column` would be present is normally
  1117. that of the :paramref:`_schema.Column.key` parameter. In some contexts,
  1118. such as a :class:`_sql.Select` object that uses a label style set
  1119. using the :meth:`_sql.Select.set_label_style` method, a column of a certain
  1120. key may instead be represented under a particular label name such
  1121. as ``tablename_columnname``::
  1122. >>> from sqlalchemy import select, column, table
  1123. >>> from sqlalchemy import LABEL_STYLE_TABLENAME_PLUS_COL
  1124. >>> t = table("t", column("c"))
  1125. >>> stmt = select(t).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  1126. >>> subq = stmt.subquery()
  1127. >>> subq.c.t_c
  1128. <sqlalchemy.sql.elements.ColumnClause at 0x7f59dcf04fa0; t_c>
  1129. :class:`.ColumnCollection` also indexes the columns in order and allows
  1130. them to be accessible by their integer position::
  1131. >>> cc[0]
  1132. Column('x', Integer(), table=None)
  1133. >>> cc[1]
  1134. Column('y', Integer(), table=None)
  1135. .. versionadded:: 1.4 :class:`_expression.ColumnCollection`
  1136. allows integer-based
  1137. index access to the collection.
  1138. Iterating the collection yields the column expressions in order::
  1139. >>> list(cc)
  1140. [Column('x', Integer(), table=None),
  1141. Column('y', Integer(), table=None)]
  1142. The base :class:`_expression.ColumnCollection` object can store
  1143. duplicates, which can
  1144. mean either two columns with the same key, in which case the column
  1145. returned by key access is **arbitrary**::
  1146. >>> x1, x2 = Column('x', Integer), Column('x', Integer)
  1147. >>> cc = ColumnCollection(columns=[(x1.name, x1), (x2.name, x2)])
  1148. >>> list(cc)
  1149. [Column('x', Integer(), table=None),
  1150. Column('x', Integer(), table=None)]
  1151. >>> cc['x'] is x1
  1152. False
  1153. >>> cc['x'] is x2
  1154. True
  1155. Or it can also mean the same column multiple times. These cases are
  1156. supported as :class:`_expression.ColumnCollection`
  1157. is used to represent the columns in
  1158. a SELECT statement which may include duplicates.
  1159. A special subclass :class:`.DedupeColumnCollection` exists which instead
  1160. maintains SQLAlchemy's older behavior of not allowing duplicates; this
  1161. collection is used for schema level objects like :class:`_schema.Table`
  1162. and
  1163. :class:`.PrimaryKeyConstraint` where this deduping is helpful. The
  1164. :class:`.DedupeColumnCollection` class also has additional mutation methods
  1165. as the schema constructs have more use cases that require removal and
  1166. replacement of columns.
  1167. .. versionchanged:: 1.4 :class:`_expression.ColumnCollection`
  1168. now stores duplicate
  1169. column keys as well as the same column in multiple positions. The
  1170. :class:`.DedupeColumnCollection` class is added to maintain the
  1171. former behavior in those cases where deduplication as well as
  1172. additional replace/remove operations are needed.
  1173. """
  1174. __slots__ = "_collection", "_index", "_colset", "_proxy_index"
  1175. _collection: List[Tuple[_COLKEY, _COL_co, _ColumnMetrics[_COL_co]]]
  1176. _index: Dict[Union[None, str, int], Tuple[_COLKEY, _COL_co]]
  1177. _proxy_index: Dict[ColumnElement[Any], Set[_ColumnMetrics[_COL_co]]]
  1178. _colset: Set[_COL_co]
  1179. def __init__(
  1180. self, columns: Optional[Iterable[Tuple[_COLKEY, _COL_co]]] = None
  1181. ):
  1182. object.__setattr__(self, "_colset", set())
  1183. object.__setattr__(self, "_index", {})
  1184. object.__setattr__(
  1185. self, "_proxy_index", collections.defaultdict(util.OrderedSet)
  1186. )
  1187. object.__setattr__(self, "_collection", [])
  1188. if columns:
  1189. self._initial_populate(columns)
  1190. @util.preload_module("sqlalchemy.sql.elements")
  1191. def __clause_element__(self) -> ClauseList:
  1192. elements = util.preloaded.sql_elements
  1193. return elements.ClauseList(
  1194. _literal_as_text_role=roles.ColumnsClauseRole,
  1195. group=False,
  1196. *self._all_columns,
  1197. )
  1198. def _initial_populate(
  1199. self, iter_: Iterable[Tuple[_COLKEY, _COL_co]]
  1200. ) -> None:
  1201. self._populate_separate_keys(iter_)
  1202. @property
  1203. def _all_columns(self) -> List[_COL_co]:
  1204. return [col for (_, col, _) in self._collection]
  1205. def keys(self) -> List[_COLKEY]:
  1206. """Return a sequence of string key names for all columns in this
  1207. collection."""
  1208. return [k for (k, _, _) in self._collection]
  1209. def values(self) -> List[_COL_co]:
  1210. """Return a sequence of :class:`_sql.ColumnClause` or
  1211. :class:`_schema.Column` objects for all columns in this
  1212. collection."""
  1213. return [col for (_, col, _) in self._collection]
  1214. def items(self) -> List[Tuple[_COLKEY, _COL_co]]:
  1215. """Return a sequence of (key, column) tuples for all columns in this
  1216. collection each consisting of a string key name and a
  1217. :class:`_sql.ColumnClause` or
  1218. :class:`_schema.Column` object.
  1219. """
  1220. return [(k, col) for (k, col, _) in self._collection]
  1221. def __bool__(self) -> bool:
  1222. return bool(self._collection)
  1223. def __len__(self) -> int:
  1224. return len(self._collection)
  1225. def __iter__(self) -> Iterator[_COL_co]:
  1226. # turn to a list first to maintain over a course of changes
  1227. return iter([col for _, col, _ in self._collection])
  1228. @overload
  1229. def __getitem__(self, key: Union[str, int]) -> _COL_co:
  1230. ...
  1231. @overload
  1232. def __getitem__(
  1233. self, key: Tuple[Union[str, int], ...]
  1234. ) -> ReadOnlyColumnCollection[_COLKEY, _COL_co]:
  1235. ...
  1236. @overload
  1237. def __getitem__(
  1238. self, key: slice
  1239. ) -> ReadOnlyColumnCollection[_COLKEY, _COL_co]:
  1240. ...
  1241. def __getitem__(
  1242. self, key: Union[str, int, slice, Tuple[Union[str, int], ...]]
  1243. ) -> Union[ReadOnlyColumnCollection[_COLKEY, _COL_co], _COL_co]:
  1244. try:
  1245. if isinstance(key, (tuple, slice)):
  1246. if isinstance(key, slice):
  1247. cols = (
  1248. (sub_key, col)
  1249. for (sub_key, col, _) in self._collection[key]
  1250. )
  1251. else:
  1252. cols = (self._index[sub_key] for sub_key in key)
  1253. return ColumnCollection(cols).as_readonly()
  1254. else:
  1255. return self._index[key][1]
  1256. except KeyError as err:
  1257. if isinstance(err.args[0], int):
  1258. raise IndexError(err.args[0]) from err
  1259. else:
  1260. raise
  1261. def __getattr__(self, key: str) -> _COL_co:
  1262. try:
  1263. return self._index[key][1]
  1264. except KeyError as err:
  1265. raise AttributeError(key) from err
  1266. def __contains__(self, key: str) -> bool:
  1267. if key not in self._index:
  1268. if not isinstance(key, str):
  1269. raise exc.ArgumentError(
  1270. "__contains__ requires a string argument"
  1271. )
  1272. return False
  1273. else:
  1274. return True
  1275. def compare(self, other: ColumnCollection[Any, Any]) -> bool:
  1276. """Compare this :class:`_expression.ColumnCollection` to another
  1277. based on the names of the keys"""
  1278. for l, r in zip_longest(self, other):
  1279. if l is not r:
  1280. return False
  1281. else:
  1282. return True
  1283. def __eq__(self, other: Any) -> bool:
  1284. return self.compare(other)
  1285. def get(
  1286. self, key: str, default: Optional[_COL_co] = None
  1287. ) -> Optional[_COL_co]:
  1288. """Get a :class:`_sql.ColumnClause` or :class:`_schema.Column` object
  1289. based on a string key name from this
  1290. :class:`_expression.ColumnCollection`."""
  1291. if key in self._index:
  1292. return self._index[key][1]
  1293. else:
  1294. return default
  1295. def __str__(self) -> str:
  1296. return "%s(%s)" % (
  1297. self.__class__.__name__,
  1298. ", ".join(str(c) for c in self),
  1299. )
  1300. def __setitem__(self, key: str, value: Any) -> NoReturn:
  1301. raise NotImplementedError()
  1302. def __delitem__(self, key: str) -> NoReturn:
  1303. raise NotImplementedError()
  1304. def __setattr__(self, key: str, obj: Any) -> NoReturn:
  1305. raise NotImplementedError()
  1306. def clear(self) -> NoReturn:
  1307. """Dictionary clear() is not implemented for
  1308. :class:`_sql.ColumnCollection`."""
  1309. raise NotImplementedError()
  1310. def remove(self, column: Any) -> None:
  1311. raise NotImplementedError()
  1312. def update(self, iter_: Any) -> NoReturn:
  1313. """Dictionary update() is not implemented for
  1314. :class:`_sql.ColumnCollection`."""
  1315. raise NotImplementedError()
  1316. # https://github.com/python/mypy/issues/4266
  1317. __hash__ = None # type: ignore
  1318. def _populate_separate_keys(
  1319. self, iter_: Iterable[Tuple[_COLKEY, _COL_co]]
  1320. ) -> None:
  1321. """populate from an iterator of (key, column)"""
  1322. self._collection[:] = collection = [
  1323. (k, c, _ColumnMetrics(self, c)) for k, c in iter_
  1324. ]
  1325. self._colset.update(c._deannotate() for _, c, _ in collection)
  1326. self._index.update(
  1327. {idx: (k, c) for idx, (k, c, _) in enumerate(collection)}
  1328. )
  1329. self._index.update({k: (k, col) for k, col, _ in reversed(collection)})
  1330. def add(
  1331. self, column: ColumnElement[Any], key: Optional[_COLKEY] = None
  1332. ) -> None:
  1333. """Add a column to this :class:`_sql.ColumnCollection`.
  1334. .. note::
  1335. This method is **not normally used by user-facing code**, as the
  1336. :class:`_sql.ColumnCollection` is usually part of an existing
  1337. object such as a :class:`_schema.Table`. To add a
  1338. :class:`_schema.Column` to an existing :class:`_schema.Table`
  1339. object, use the :meth:`_schema.Table.append_column` method.
  1340. """
  1341. colkey: _COLKEY
  1342. if key is None:
  1343. colkey = column.key # type: ignore
  1344. else:
  1345. colkey = key
  1346. l = len(self._collection)
  1347. # don't really know how this part is supposed to work w/ the
  1348. # covariant thing
  1349. _column = cast(_COL_co, column)
  1350. self._collection.append(
  1351. (colkey, _column, _ColumnMetrics(self, _column))
  1352. )
  1353. self._colset.add(_column._deannotate())
  1354. self._index[l] = (colkey, _column)
  1355. if colkey not in self._index:
  1356. self._index[colkey] = (colkey, _column)
  1357. def __getstate__(self) -> Dict[str, Any]:
  1358. return {
  1359. "_collection": [(k, c) for k, c, _ in self._collection],
  1360. "_index": self._index,
  1361. }
  1362. def __setstate__(self, state: Dict[str, Any]) -> None:
  1363. object.__setattr__(self, "_index", state["_index"])
  1364. object.__setattr__(
  1365. self, "_proxy_index", collections.defaultdict(util.OrderedSet)
  1366. )
  1367. object.__setattr__(
  1368. self,
  1369. "_collection",
  1370. [
  1371. (k, c, _ColumnMetrics(self, c))
  1372. for (k, c) in state["_collection"]
  1373. ],
  1374. )
  1375. object.__setattr__(
  1376. self, "_colset", {col for k, col, _ in self._collection}
  1377. )
  1378. def contains_column(self, col: ColumnElement[Any]) -> bool:
  1379. """Checks if a column object exists in this collection"""
  1380. if col not in self._colset:
  1381. if isinstance(col, str):
  1382. raise exc.ArgumentError(
  1383. "contains_column cannot be used with string arguments. "
  1384. "Use ``col_name in table.c`` instead."
  1385. )
  1386. return False
  1387. else:
  1388. return True
  1389. def as_readonly(self) -> ReadOnlyColumnCollection[_COLKEY, _COL_co]:
  1390. """Return a "read only" form of this
  1391. :class:`_sql.ColumnCollection`."""
  1392. return ReadOnlyColumnCollection(self)
  1393. def _init_proxy_index(self):
  1394. """populate the "proxy index", if empty.
  1395. proxy index is added in 2.0 to provide more efficient operation
  1396. for the corresponding_column() method.
  1397. For reasons of both time to construct new .c collections as well as
  1398. memory conservation for large numbers of large .c collections, the
  1399. proxy_index is only filled if corresponding_column() is called. once
  1400. filled it stays that way, and new _ColumnMetrics objects created after
  1401. that point will populate it with new data. Note this case would be
  1402. unusual, if not nonexistent, as it means a .c collection is being
  1403. mutated after corresponding_column() were used, however it is tested in
  1404. test/base/test_utils.py.
  1405. """
  1406. pi = self._proxy_index
  1407. if pi:
  1408. return
  1409. for _, _, metrics in self._collection:
  1410. eps = metrics.column._expanded_proxy_set
  1411. for eps_col in eps:
  1412. pi[eps_col].add(metrics)
  1413. def corresponding_column(
  1414. self, column: _COL, require_embedded: bool = False
  1415. ) -> Optional[Union[_COL, _COL_co]]:
  1416. """Given a :class:`_expression.ColumnElement`, return the exported
  1417. :class:`_expression.ColumnElement` object from this
  1418. :class:`_expression.ColumnCollection`
  1419. which corresponds to that original :class:`_expression.ColumnElement`
  1420. via a common
  1421. ancestor column.
  1422. :param column: the target :class:`_expression.ColumnElement`
  1423. to be matched.
  1424. :param require_embedded: only return corresponding columns for
  1425. the given :class:`_expression.ColumnElement`, if the given
  1426. :class:`_expression.ColumnElement`
  1427. is actually present within a sub-element
  1428. of this :class:`_expression.Selectable`.
  1429. Normally the column will match if
  1430. it merely shares a common ancestor with one of the exported
  1431. columns of this :class:`_expression.Selectable`.
  1432. .. seealso::
  1433. :meth:`_expression.Selectable.corresponding_column`
  1434. - invokes this method
  1435. against the collection returned by
  1436. :attr:`_expression.Selectable.exported_columns`.
  1437. .. versionchanged:: 1.4 the implementation for ``corresponding_column``
  1438. was moved onto the :class:`_expression.ColumnCollection` itself.
  1439. """
  1440. # TODO: cython candidate
  1441. # don't dig around if the column is locally present
  1442. if column in self._colset:
  1443. return column
  1444. selected_intersection, selected_metrics = None, None
  1445. target_set = column.proxy_set
  1446. pi = self._proxy_index
  1447. if not pi:
  1448. self._init_proxy_index()
  1449. for current_metrics in (
  1450. mm for ts in target_set if ts in pi for mm in pi[ts]
  1451. ):
  1452. if not require_embedded or current_metrics.embedded(target_set):
  1453. if selected_metrics is None:
  1454. # no corresponding column yet, pick this one.
  1455. selected_metrics = current_metrics
  1456. continue
  1457. current_intersection = target_set.intersection(
  1458. current_metrics.column._expanded_proxy_set
  1459. )
  1460. if selected_intersection is None:
  1461. selected_intersection = target_set.intersection(
  1462. selected_metrics.column._expanded_proxy_set
  1463. )
  1464. if len(current_intersection) > len(selected_intersection):
  1465. # 'current' has a larger field of correspondence than
  1466. # 'selected'. i.e. selectable.c.a1_x->a1.c.x->table.c.x
  1467. # matches a1.c.x->table.c.x better than
  1468. # selectable.c.x->table.c.x does.
  1469. selected_metrics = current_metrics
  1470. selected_intersection = current_intersection
  1471. elif current_intersection == selected_intersection:
  1472. # they have the same field of correspondence. see
  1473. # which proxy_set has fewer columns in it, which
  1474. # indicates a closer relationship with the root
  1475. # column. Also take into account the "weight"
  1476. # attribute which CompoundSelect() uses to give
  1477. # higher precedence to columns based on vertical
  1478. # position in the compound statement, and discard
  1479. # columns that have no reference to the target
  1480. # column (also occurs with CompoundSelect)
  1481. selected_col_distance = sum(
  1482. [
  1483. sc._annotations.get("weight", 1)
  1484. for sc in (
  1485. selected_metrics.column._uncached_proxy_list()
  1486. )
  1487. if sc.shares_lineage(column)
  1488. ],
  1489. )
  1490. current_col_distance = sum(
  1491. [
  1492. sc._annotations.get("weight", 1)
  1493. for sc in (
  1494. current_metrics.column._uncached_proxy_list()
  1495. )
  1496. if sc.shares_lineage(column)
  1497. ],
  1498. )
  1499. if current_col_distance < selected_col_distance:
  1500. selected_metrics = current_metrics
  1501. selected_intersection = current_intersection
  1502. return selected_metrics.column if selected_metrics else None
  1503. _NAMEDCOL = TypeVar("_NAMEDCOL", bound="NamedColumn[Any]")
  1504. class DedupeColumnCollection(ColumnCollection[str, _NAMEDCOL]):
  1505. """A :class:`_expression.ColumnCollection`
  1506. that maintains deduplicating behavior.
  1507. This is useful by schema level objects such as :class:`_schema.Table` and
  1508. :class:`.PrimaryKeyConstraint`. The collection includes more
  1509. sophisticated mutator methods as well to suit schema objects which
  1510. require mutable column collections.
  1511. .. versionadded:: 1.4
  1512. """
  1513. def add(
  1514. self, column: ColumnElement[Any], key: Optional[str] = None
  1515. ) -> None:
  1516. named_column = cast(_NAMEDCOL, column)
  1517. if key is not None and named_column.key != key:
  1518. raise exc.ArgumentError(
  1519. "DedupeColumnCollection requires columns be under "
  1520. "the same key as their .key"
  1521. )
  1522. key = named_column.key
  1523. if key is None:
  1524. raise exc.ArgumentError(
  1525. "Can't add unnamed column to column collection"
  1526. )
  1527. if key in self._index:
  1528. existing = self._index[key][1]
  1529. if existing is named_column:
  1530. return
  1531. self.replace(named_column)
  1532. # pop out memoized proxy_set as this
  1533. # operation may very well be occurring
  1534. # in a _make_proxy operation
  1535. util.memoized_property.reset(named_column, "proxy_set")
  1536. else:
  1537. self._append_new_column(key, named_column)
  1538. def _append_new_column(self, key: str, named_column: _NAMEDCOL) -> None:
  1539. l = len(self._collection)
  1540. self._collection.append(
  1541. (key, named_column, _ColumnMetrics(self, named_column))
  1542. )
  1543. self._colset.add(named_column._deannotate())
  1544. self._index[l] = (key, named_column)
  1545. self._index[key] = (key, named_column)
  1546. def _populate_separate_keys(
  1547. self, iter_: Iterable[Tuple[str, _NAMEDCOL]]
  1548. ) -> None:
  1549. """populate from an iterator of (key, column)"""
  1550. cols = list(iter_)
  1551. replace_col = []
  1552. for k, col in cols:
  1553. if col.key != k:
  1554. raise exc.ArgumentError(
  1555. "DedupeColumnCollection requires columns be under "
  1556. "the same key as their .key"
  1557. )
  1558. if col.name in self._index and col.key != col.name:
  1559. replace_col.append(col)
  1560. elif col.key in self._index:
  1561. replace_col.append(col)
  1562. else:
  1563. self._index[k] = (k, col)
  1564. self._collection.append((k, col, _ColumnMetrics(self, col)))
  1565. self._colset.update(c._deannotate() for (k, c, _) in self._collection)
  1566. self._index.update(
  1567. (idx, (k, c)) for idx, (k, c, _) in enumerate(self._collection)
  1568. )
  1569. for col in replace_col:
  1570. self.replace(col)
  1571. def extend(self, iter_: Iterable[_NAMEDCOL]) -> None:
  1572. self._populate_separate_keys((col.key, col) for col in iter_)
  1573. def remove(self, column: _NAMEDCOL) -> None:
  1574. if column not in self._colset:
  1575. raise ValueError(
  1576. "Can't remove column %r; column is not in this collection"
  1577. % column
  1578. )
  1579. del self._index[column.key]
  1580. self._colset.remove(column)
  1581. self._collection[:] = [
  1582. (k, c, metrics)
  1583. for (k, c, metrics) in self._collection
  1584. if c is not column
  1585. ]
  1586. for metrics in self._proxy_index.get(column, ()):
  1587. metrics.dispose(self)
  1588. self._index.update(
  1589. {idx: (k, col) for idx, (k, col, _) in enumerate(self._collection)}
  1590. )
  1591. # delete higher index
  1592. del self._index[len(self._collection)]
  1593. def replace(
  1594. self,
  1595. column: _NAMEDCOL,
  1596. extra_remove: Optional[Iterable[_NAMEDCOL]] = None,
  1597. ) -> None:
  1598. """add the given column to this collection, removing unaliased
  1599. versions of this column as well as existing columns with the
  1600. same key.
  1601. e.g.::
  1602. t = Table('sometable', metadata, Column('col1', Integer))
  1603. t.columns.replace(Column('col1', Integer, key='columnone'))
  1604. will remove the original 'col1' from the collection, and add
  1605. the new column under the name 'columnname'.
  1606. Used by schema.Column to override columns during table reflection.
  1607. """
  1608. if extra_remove:
  1609. remove_col = set(extra_remove)
  1610. else:
  1611. remove_col = set()
  1612. # remove up to two columns based on matches of name as well as key
  1613. if column.name in self._index and column.key != column.name:
  1614. other = self._index[column.name][1]
  1615. if other.name == other.key:
  1616. remove_col.add(other)
  1617. if column.key in self._index:
  1618. remove_col.add(self._index[column.key][1])
  1619. if not remove_col:
  1620. self._append_new_column(column.key, column)
  1621. return
  1622. new_cols: List[Tuple[str, _NAMEDCOL, _ColumnMetrics[_NAMEDCOL]]] = []
  1623. replaced = False
  1624. for k, col, metrics in self._collection:
  1625. if col in remove_col:
  1626. if not replaced:
  1627. replaced = True
  1628. new_cols.append(
  1629. (column.key, column, _ColumnMetrics(self, column))
  1630. )
  1631. else:
  1632. new_cols.append((k, col, metrics))
  1633. if remove_col:
  1634. self._colset.difference_update(remove_col)
  1635. for rc in remove_col:
  1636. for metrics in self._proxy_index.get(rc, ()):
  1637. metrics.dispose(self)
  1638. if not replaced:
  1639. new_cols.append((column.key, column, _ColumnMetrics(self, column)))
  1640. self._colset.add(column._deannotate())
  1641. self._collection[:] = new_cols
  1642. self._index.clear()
  1643. self._index.update(
  1644. {idx: (k, col) for idx, (k, col, _) in enumerate(self._collection)}
  1645. )
  1646. self._index.update({k: (k, col) for (k, col, _) in self._collection})
  1647. class ReadOnlyColumnCollection(
  1648. util.ReadOnlyContainer, ColumnCollection[_COLKEY, _COL_co]
  1649. ):
  1650. __slots__ = ("_parent",)
  1651. def __init__(self, collection):
  1652. object.__setattr__(self, "_parent", collection)
  1653. object.__setattr__(self, "_colset", collection._colset)
  1654. object.__setattr__(self, "_index", collection._index)
  1655. object.__setattr__(self, "_collection", collection._collection)
  1656. object.__setattr__(self, "_proxy_index", collection._proxy_index)
  1657. def __getstate__(self):
  1658. return {"_parent": self._parent}
  1659. def __setstate__(self, state):
  1660. parent = state["_parent"]
  1661. self.__init__(parent) # type: ignore
  1662. def add(self, column: Any, key: Any = ...) -> Any:
  1663. self._readonly()
  1664. def extend(self, elements: Any) -> NoReturn:
  1665. self._readonly()
  1666. def remove(self, item: Any) -> NoReturn:
  1667. self._readonly()
  1668. class ColumnSet(util.OrderedSet["ColumnClause[Any]"]):
  1669. def contains_column(self, col):
  1670. return col in self
  1671. def extend(self, cols):
  1672. for col in cols:
  1673. self.add(col)
  1674. def __eq__(self, other):
  1675. l = []
  1676. for c in other:
  1677. for local in self:
  1678. if c.shares_lineage(local):
  1679. l.append(c == local)
  1680. return elements.and_(*l)
  1681. def __hash__(self):
  1682. return hash(tuple(x for x in self))
  1683. def _entity_namespace(
  1684. entity: Union[_HasEntityNamespace, ExternallyTraversible]
  1685. ) -> _EntityNamespace:
  1686. """Return the nearest .entity_namespace for the given entity.
  1687. If not immediately available, does an iterate to find a sub-element
  1688. that has one, if any.
  1689. """
  1690. try:
  1691. return cast(_HasEntityNamespace, entity).entity_namespace
  1692. except AttributeError:
  1693. for elem in visitors.iterate(cast(ExternallyTraversible, entity)):
  1694. if _is_has_entity_namespace(elem):
  1695. return elem.entity_namespace
  1696. else:
  1697. raise
  1698. def _entity_namespace_key(
  1699. entity: Union[_HasEntityNamespace, ExternallyTraversible],
  1700. key: str,
  1701. default: Union[SQLCoreOperations[Any], _NoArg] = NO_ARG,
  1702. ) -> SQLCoreOperations[Any]:
  1703. """Return an entry from an entity_namespace.
  1704. Raises :class:`_exc.InvalidRequestError` rather than attribute error
  1705. on not found.
  1706. """
  1707. try:
  1708. ns = _entity_namespace(entity)
  1709. if default is not NO_ARG:
  1710. return getattr(ns, key, default)
  1711. else:
  1712. return getattr(ns, key) # type: ignore
  1713. except AttributeError as err:
  1714. raise exc.InvalidRequestError(
  1715. 'Entity namespace for "%s" has no property "%s"' % (entity, key)
  1716. ) from err