base.py 55 KB

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