base.py 74 KB

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