base.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701
  1. # sql/base.py
  2. # Copyright (C) 2005-2022 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. s.__dict__ = {
  425. k: v for k, v in self.__dict__.items() if k not in skip
  426. }
  427. else:
  428. s.__dict__ = self.__dict__.copy()
  429. return s
  430. class InPlaceGenerative(HasMemoized):
  431. """Provide a method-chaining pattern in conjunction with the
  432. @_generative decorator that mutates in place."""
  433. def _generate(self):
  434. skip = self._memoized_keys
  435. for k in skip:
  436. self.__dict__.pop(k, None)
  437. return self
  438. class HasCompileState(Generative):
  439. """A class that has a :class:`.CompileState` associated with it."""
  440. _compile_state_plugin = None
  441. _attributes = util.immutabledict()
  442. _compile_state_factory = CompileState.create_for_statement
  443. class _MetaOptions(type):
  444. """metaclass for the Options class."""
  445. def __init__(cls, classname, bases, dict_):
  446. cls._cache_attrs = tuple(
  447. sorted(
  448. d
  449. for d in dict_
  450. if not d.startswith("__")
  451. and d not in ("_cache_key_traversal",)
  452. )
  453. )
  454. type.__init__(cls, classname, bases, dict_)
  455. def __add__(self, other):
  456. o1 = self()
  457. if set(other).difference(self._cache_attrs):
  458. raise TypeError(
  459. "dictionary contains attributes not covered by "
  460. "Options class %s: %r"
  461. % (self, set(other).difference(self._cache_attrs))
  462. )
  463. o1.__dict__.update(other)
  464. return o1
  465. class Options(util.with_metaclass(_MetaOptions)):
  466. """A cacheable option dictionary with defaults."""
  467. def __init__(self, **kw):
  468. self.__dict__.update(kw)
  469. def __add__(self, other):
  470. o1 = self.__class__.__new__(self.__class__)
  471. o1.__dict__.update(self.__dict__)
  472. if set(other).difference(self._cache_attrs):
  473. raise TypeError(
  474. "dictionary contains attributes not covered by "
  475. "Options class %s: %r"
  476. % (self, set(other).difference(self._cache_attrs))
  477. )
  478. o1.__dict__.update(other)
  479. return o1
  480. def __eq__(self, other):
  481. # TODO: very inefficient. This is used only in test suites
  482. # right now.
  483. for a, b in util.zip_longest(self._cache_attrs, other._cache_attrs):
  484. if getattr(self, a) != getattr(other, b):
  485. return False
  486. return True
  487. def __repr__(self):
  488. # TODO: fairly inefficient, used only in debugging right now.
  489. return "%s(%s)" % (
  490. self.__class__.__name__,
  491. ", ".join(
  492. "%s=%r" % (k, self.__dict__[k])
  493. for k in self._cache_attrs
  494. if k in self.__dict__
  495. ),
  496. )
  497. @classmethod
  498. def isinstance(cls, klass):
  499. return issubclass(cls, klass)
  500. @hybridmethod
  501. def add_to_element(self, name, value):
  502. return self + {name: getattr(self, name) + value}
  503. @hybridmethod
  504. def _state_dict(self):
  505. return self.__dict__
  506. _state_dict_const = util.immutabledict()
  507. @_state_dict.classlevel
  508. def _state_dict(cls):
  509. return cls._state_dict_const
  510. @classmethod
  511. def safe_merge(cls, other):
  512. d = other._state_dict()
  513. # only support a merge with another object of our class
  514. # and which does not have attrs that we don't. otherwise
  515. # we risk having state that might not be part of our cache
  516. # key strategy
  517. if (
  518. cls is not other.__class__
  519. and other._cache_attrs
  520. and set(other._cache_attrs).difference(cls._cache_attrs)
  521. ):
  522. raise TypeError(
  523. "other element %r is not empty, is not of type %s, "
  524. "and contains attributes not covered here %r"
  525. % (
  526. other,
  527. cls,
  528. set(other._cache_attrs).difference(cls._cache_attrs),
  529. )
  530. )
  531. return cls + d
  532. @classmethod
  533. def from_execution_options(
  534. cls, key, attrs, exec_options, statement_exec_options
  535. ):
  536. """process Options argument in terms of execution options.
  537. e.g.::
  538. (
  539. load_options,
  540. execution_options,
  541. ) = QueryContext.default_load_options.from_execution_options(
  542. "_sa_orm_load_options",
  543. {
  544. "populate_existing",
  545. "autoflush",
  546. "yield_per"
  547. },
  548. execution_options,
  549. statement._execution_options,
  550. )
  551. get back the Options and refresh "_sa_orm_load_options" in the
  552. exec options dict w/ the Options as well
  553. """
  554. # common case is that no options we are looking for are
  555. # in either dictionary, so cancel for that first
  556. check_argnames = attrs.intersection(
  557. set(exec_options).union(statement_exec_options)
  558. )
  559. existing_options = exec_options.get(key, cls)
  560. if check_argnames:
  561. result = {}
  562. for argname in check_argnames:
  563. local = "_" + argname
  564. if argname in exec_options:
  565. result[local] = exec_options[argname]
  566. elif argname in statement_exec_options:
  567. result[local] = statement_exec_options[argname]
  568. new_options = existing_options + result
  569. exec_options = util.immutabledict().merge_with(
  570. exec_options, {key: new_options}
  571. )
  572. return new_options, exec_options
  573. else:
  574. return existing_options, exec_options
  575. class CacheableOptions(Options, HasCacheKey):
  576. @hybridmethod
  577. def _gen_cache_key(self, anon_map, bindparams):
  578. return HasCacheKey._gen_cache_key(self, anon_map, bindparams)
  579. @_gen_cache_key.classlevel
  580. def _gen_cache_key(cls, anon_map, bindparams):
  581. return (cls, ())
  582. @hybridmethod
  583. def _generate_cache_key(self):
  584. return HasCacheKey._generate_cache_key_for_object(self)
  585. class ExecutableOption(HasCopyInternals):
  586. _annotations = util.EMPTY_DICT
  587. __visit_name__ = "executable_option"
  588. _is_has_cache_key = False
  589. def _clone(self, **kw):
  590. """Create a shallow copy of this ExecutableOption."""
  591. c = self.__class__.__new__(self.__class__)
  592. c.__dict__ = dict(self.__dict__)
  593. return c
  594. class Executable(roles.StatementRole, Generative):
  595. """Mark a :class:`_expression.ClauseElement` as supporting execution.
  596. :class:`.Executable` is a superclass for all "statement" types
  597. of objects, including :func:`select`, :func:`delete`, :func:`update`,
  598. :func:`insert`, :func:`text`.
  599. """
  600. supports_execution = True
  601. _execution_options = util.immutabledict()
  602. _bind = None
  603. _with_options = ()
  604. _with_context_options = ()
  605. _executable_traverse_internals = [
  606. ("_with_options", InternalTraversal.dp_executable_options),
  607. (
  608. "_with_context_options",
  609. ExtendedInternalTraversal.dp_with_context_options,
  610. ),
  611. ("_propagate_attrs", ExtendedInternalTraversal.dp_propagate_attrs),
  612. ]
  613. is_select = False
  614. is_update = False
  615. is_insert = False
  616. is_text = False
  617. is_delete = False
  618. is_dml = False
  619. @property
  620. def _effective_plugin_target(self):
  621. return self.__visit_name__
  622. @_generative
  623. def options(self, *options):
  624. """Apply options to this statement.
  625. In the general sense, options are any kind of Python object
  626. that can be interpreted by the SQL compiler for the statement.
  627. These options can be consumed by specific dialects or specific kinds
  628. of compilers.
  629. The most commonly known kind of option are the ORM level options
  630. that apply "eager load" and other loading behaviors to an ORM
  631. query. However, options can theoretically be used for many other
  632. purposes.
  633. For background on specific kinds of options for specific kinds of
  634. statements, refer to the documentation for those option objects.
  635. .. versionchanged:: 1.4 - added :meth:`.Generative.options` to
  636. Core statement objects towards the goal of allowing unified
  637. Core / ORM querying capabilities.
  638. .. seealso::
  639. :ref:`deferred_options` - refers to options specific to the usage
  640. of ORM queries
  641. :ref:`relationship_loader_options` - refers to options specific
  642. to the usage of ORM queries
  643. """
  644. self._with_options += tuple(
  645. coercions.expect(roles.ExecutableOptionRole, opt)
  646. for opt in options
  647. )
  648. @_generative
  649. def _set_compile_options(self, compile_options):
  650. """Assign the compile options to a new value.
  651. :param compile_options: appropriate CacheableOptions structure
  652. """
  653. self._compile_options = compile_options
  654. @_generative
  655. def _update_compile_options(self, options):
  656. """update the _compile_options with new keys."""
  657. self._compile_options += options
  658. @_generative
  659. def _add_context_option(self, callable_, cache_args):
  660. """Add a context option to this statement.
  661. These are callable functions that will
  662. be given the CompileState object upon compilation.
  663. A second argument cache_args is required, which will be combined with
  664. the ``__code__`` identity of the function itself in order to produce a
  665. cache key.
  666. """
  667. self._with_context_options += ((callable_, cache_args),)
  668. @_generative
  669. def execution_options(self, **kw):
  670. """Set non-SQL options for the statement which take effect during
  671. execution.
  672. Execution options can be set on a per-statement or
  673. per :class:`_engine.Connection` basis. Additionally, the
  674. :class:`_engine.Engine` and ORM :class:`~.orm.query.Query`
  675. objects provide
  676. access to execution options which they in turn configure upon
  677. connections.
  678. The :meth:`execution_options` method is generative. A new
  679. instance of this statement is returned that contains the options::
  680. statement = select(table.c.x, table.c.y)
  681. statement = statement.execution_options(autocommit=True)
  682. Note that only a subset of possible execution options can be applied
  683. to a statement - these include "autocommit" and "stream_results",
  684. but not "isolation_level" or "compiled_cache".
  685. See :meth:`_engine.Connection.execution_options` for a full list of
  686. possible options.
  687. .. seealso::
  688. :meth:`_engine.Connection.execution_options`
  689. :meth:`_query.Query.execution_options`
  690. :meth:`.Executable.get_execution_options`
  691. """
  692. if "isolation_level" in kw:
  693. raise exc.ArgumentError(
  694. "'isolation_level' execution option may only be specified "
  695. "on Connection.execution_options(), or "
  696. "per-engine using the isolation_level "
  697. "argument to create_engine()."
  698. )
  699. if "compiled_cache" in kw:
  700. raise exc.ArgumentError(
  701. "'compiled_cache' execution option may only be specified "
  702. "on Connection.execution_options(), not per statement."
  703. )
  704. self._execution_options = self._execution_options.union(kw)
  705. def get_execution_options(self):
  706. """Get the non-SQL options which will take effect during execution.
  707. .. versionadded:: 1.3
  708. .. seealso::
  709. :meth:`.Executable.execution_options`
  710. """
  711. return self._execution_options
  712. @util.deprecated_20(
  713. ":meth:`.Executable.execute`",
  714. alternative="All statement execution in SQLAlchemy 2.0 is performed "
  715. "by the :meth:`_engine.Connection.execute` method of "
  716. ":class:`_engine.Connection`, "
  717. "or in the ORM by the :meth:`.Session.execute` method of "
  718. ":class:`.Session`.",
  719. )
  720. def execute(self, *multiparams, **params):
  721. """Compile and execute this :class:`.Executable`."""
  722. e = self.bind
  723. if e is None:
  724. label = (
  725. getattr(self, "description", None) or self.__class__.__name__
  726. )
  727. msg = (
  728. "This %s is not directly bound to a Connection or Engine. "
  729. "Use the .execute() method of a Connection or Engine "
  730. "to execute this construct." % label
  731. )
  732. raise exc.UnboundExecutionError(msg)
  733. return e._execute_clauseelement(
  734. self, multiparams, params, util.immutabledict()
  735. )
  736. @util.deprecated_20(
  737. ":meth:`.Executable.scalar`",
  738. alternative="Scalar execution in SQLAlchemy 2.0 is performed "
  739. "by the :meth:`_engine.Connection.scalar` method of "
  740. ":class:`_engine.Connection`, "
  741. "or in the ORM by the :meth:`.Session.scalar` method of "
  742. ":class:`.Session`.",
  743. )
  744. def scalar(self, *multiparams, **params):
  745. """Compile and execute this :class:`.Executable`, returning the
  746. result's scalar representation.
  747. """
  748. return self.execute(*multiparams, **params).scalar()
  749. @property
  750. @util.deprecated_20(
  751. ":attr:`.Executable.bind`",
  752. alternative="Bound metadata is being removed as of SQLAlchemy 2.0.",
  753. enable_warnings=False,
  754. )
  755. def bind(self):
  756. """Returns the :class:`_engine.Engine` or :class:`_engine.Connection`
  757. to
  758. which this :class:`.Executable` is bound, or None if none found.
  759. This is a traversal which checks locally, then
  760. checks among the "from" clauses of associated objects
  761. until a bound engine or connection is found.
  762. """
  763. if self._bind is not None:
  764. return self._bind
  765. for f in _from_objects(self):
  766. if f is self:
  767. continue
  768. engine = f.bind
  769. if engine is not None:
  770. return engine
  771. else:
  772. return None
  773. class prefix_anon_map(dict):
  774. """A map that creates new keys for missing key access.
  775. Considers keys of the form "<ident> <name>" to produce
  776. new symbols "<name>_<index>", where "index" is an incrementing integer
  777. corresponding to <name>.
  778. Inlines the approach taken by :class:`sqlalchemy.util.PopulateDict` which
  779. is otherwise usually used for this type of operation.
  780. """
  781. def __missing__(self, key):
  782. (ident, derived) = key.split(" ", 1)
  783. anonymous_counter = self.get(derived, 1)
  784. self[derived] = anonymous_counter + 1
  785. value = derived + "_" + str(anonymous_counter)
  786. self[key] = value
  787. return value
  788. class SchemaEventTarget(object):
  789. """Base class for elements that are the targets of :class:`.DDLEvents`
  790. events.
  791. This includes :class:`.SchemaItem` as well as :class:`.SchemaType`.
  792. """
  793. def _set_parent(self, parent, **kw):
  794. """Associate with this SchemaEvent's parent object."""
  795. def _set_parent_with_dispatch(self, parent, **kw):
  796. self.dispatch.before_parent_attach(self, parent)
  797. self._set_parent(parent, **kw)
  798. self.dispatch.after_parent_attach(self, parent)
  799. class SchemaVisitor(ClauseVisitor):
  800. """Define the visiting for ``SchemaItem`` objects."""
  801. __traverse_options__ = {"schema_visitor": True}
  802. class ColumnCollection(object):
  803. """Collection of :class:`_expression.ColumnElement` instances,
  804. typically for
  805. :class:`_sql.FromClause` objects.
  806. The :class:`_sql.ColumnCollection` object is most commonly available
  807. as the :attr:`_schema.Table.c` or :attr:`_schema.Table.columns` collection
  808. on the :class:`_schema.Table` object, introduced at
  809. :ref:`metadata_tables_and_columns`.
  810. The :class:`_expression.ColumnCollection` has both mapping- and sequence-
  811. like behaviors. A :class:`_expression.ColumnCollection` usually stores
  812. :class:`_schema.Column` objects, which are then accessible both via mapping
  813. style access as well as attribute access style.
  814. To access :class:`_schema.Column` objects using ordinary attribute-style
  815. access, specify the name like any other object attribute, such as below
  816. a column named ``employee_name`` is accessed::
  817. >>> employee_table.c.employee_name
  818. To access columns that have names with special characters or spaces,
  819. index-style access is used, such as below which illustrates a column named
  820. ``employee ' payment`` is accessed::
  821. >>> employee_table.c["employee ' payment"]
  822. As the :class:`_sql.ColumnCollection` object provides a Python dictionary
  823. interface, common dictionary method names like
  824. :meth:`_sql.ColumnCollection.keys`, :meth:`_sql.ColumnCollection.values`,
  825. and :meth:`_sql.ColumnCollection.items` are available, which means that
  826. database columns that are keyed under these names also need to use indexed
  827. access::
  828. >>> employee_table.c["values"]
  829. The name for which a :class:`_schema.Column` would be present is normally
  830. that of the :paramref:`_schema.Column.key` parameter. In some contexts,
  831. such as a :class:`_sql.Select` object that uses a label style set
  832. using the :meth:`_sql.Select.set_label_style` method, a column of a certain
  833. key may instead be represented under a particular label name such
  834. as ``tablename_columnname``::
  835. >>> from sqlalchemy import select, column, table
  836. >>> from sqlalchemy import LABEL_STYLE_TABLENAME_PLUS_COL
  837. >>> t = table("t", column("c"))
  838. >>> stmt = select(t).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  839. >>> subq = stmt.subquery()
  840. >>> subq.c.t_c
  841. <sqlalchemy.sql.elements.ColumnClause at 0x7f59dcf04fa0; t_c>
  842. :class:`.ColumnCollection` also indexes the columns in order and allows
  843. them to be accessible by their integer position::
  844. >>> cc[0]
  845. Column('x', Integer(), table=None)
  846. >>> cc[1]
  847. Column('y', Integer(), table=None)
  848. .. versionadded:: 1.4 :class:`_expression.ColumnCollection`
  849. allows integer-based
  850. index access to the collection.
  851. Iterating the collection yields the column expressions in order::
  852. >>> list(cc)
  853. [Column('x', Integer(), table=None),
  854. Column('y', Integer(), table=None)]
  855. The base :class:`_expression.ColumnCollection` object can store
  856. duplicates, which can
  857. mean either two columns with the same key, in which case the column
  858. returned by key access is **arbitrary**::
  859. >>> x1, x2 = Column('x', Integer), Column('x', Integer)
  860. >>> cc = ColumnCollection(columns=[(x1.name, x1), (x2.name, x2)])
  861. >>> list(cc)
  862. [Column('x', Integer(), table=None),
  863. Column('x', Integer(), table=None)]
  864. >>> cc['x'] is x1
  865. False
  866. >>> cc['x'] is x2
  867. True
  868. Or it can also mean the same column multiple times. These cases are
  869. supported as :class:`_expression.ColumnCollection`
  870. is used to represent the columns in
  871. a SELECT statement which may include duplicates.
  872. A special subclass :class:`.DedupeColumnCollection` exists which instead
  873. maintains SQLAlchemy's older behavior of not allowing duplicates; this
  874. collection is used for schema level objects like :class:`_schema.Table`
  875. and
  876. :class:`.PrimaryKeyConstraint` where this deduping is helpful. The
  877. :class:`.DedupeColumnCollection` class also has additional mutation methods
  878. as the schema constructs have more use cases that require removal and
  879. replacement of columns.
  880. .. versionchanged:: 1.4 :class:`_expression.ColumnCollection`
  881. now stores duplicate
  882. column keys as well as the same column in multiple positions. The
  883. :class:`.DedupeColumnCollection` class is added to maintain the
  884. former behavior in those cases where deduplication as well as
  885. additional replace/remove operations are needed.
  886. """
  887. __slots__ = "_collection", "_index", "_colset"
  888. def __init__(self, columns=None):
  889. object.__setattr__(self, "_colset", set())
  890. object.__setattr__(self, "_index", {})
  891. object.__setattr__(self, "_collection", [])
  892. if columns:
  893. self._initial_populate(columns)
  894. def _initial_populate(self, iter_):
  895. self._populate_separate_keys(iter_)
  896. @property
  897. def _all_columns(self):
  898. return [col for (k, col) in self._collection]
  899. def keys(self):
  900. """Return a sequence of string key names for all columns in this
  901. collection."""
  902. return [k for (k, col) in self._collection]
  903. def values(self):
  904. """Return a sequence of :class:`_sql.ColumnClause` or
  905. :class:`_schema.Column` objects for all columns in this
  906. collection."""
  907. return [col for (k, col) in self._collection]
  908. def items(self):
  909. """Return a sequence of (key, column) tuples for all columns in this
  910. collection each consisting of a string key name and a
  911. :class:`_sql.ColumnClause` or
  912. :class:`_schema.Column` object.
  913. """
  914. return list(self._collection)
  915. def __bool__(self):
  916. return bool(self._collection)
  917. def __len__(self):
  918. return len(self._collection)
  919. def __iter__(self):
  920. # turn to a list first to maintain over a course of changes
  921. return iter([col for k, col in self._collection])
  922. def __getitem__(self, key):
  923. try:
  924. return self._index[key]
  925. except KeyError as err:
  926. if isinstance(key, util.int_types):
  927. util.raise_(IndexError(key), replace_context=err)
  928. else:
  929. raise
  930. def __getattr__(self, key):
  931. try:
  932. return self._index[key]
  933. except KeyError as err:
  934. util.raise_(AttributeError(key), replace_context=err)
  935. def __contains__(self, key):
  936. if key not in self._index:
  937. if not isinstance(key, util.string_types):
  938. raise exc.ArgumentError(
  939. "__contains__ requires a string argument"
  940. )
  941. return False
  942. else:
  943. return True
  944. def compare(self, other):
  945. """Compare this :class:`_expression.ColumnCollection` to another
  946. based on the names of the keys"""
  947. for l, r in util.zip_longest(self, other):
  948. if l is not r:
  949. return False
  950. else:
  951. return True
  952. def __eq__(self, other):
  953. return self.compare(other)
  954. def get(self, key, default=None):
  955. """Get a :class:`_sql.ColumnClause` or :class:`_schema.Column` object
  956. based on a string key name from this
  957. :class:`_expression.ColumnCollection`."""
  958. if key in self._index:
  959. return self._index[key]
  960. else:
  961. return default
  962. def __str__(self):
  963. return "%s(%s)" % (
  964. self.__class__.__name__,
  965. ", ".join(str(c) for c in self),
  966. )
  967. def __setitem__(self, key, value):
  968. raise NotImplementedError()
  969. def __delitem__(self, key):
  970. raise NotImplementedError()
  971. def __setattr__(self, key, obj):
  972. raise NotImplementedError()
  973. def clear(self):
  974. """Dictionary clear() is not implemented for
  975. :class:`_sql.ColumnCollection`."""
  976. raise NotImplementedError()
  977. def remove(self, column):
  978. """Dictionary remove() is not implemented for
  979. :class:`_sql.ColumnCollection`."""
  980. raise NotImplementedError()
  981. def update(self, iter_):
  982. """Dictionary update() is not implemented for
  983. :class:`_sql.ColumnCollection`."""
  984. raise NotImplementedError()
  985. __hash__ = None
  986. def _populate_separate_keys(self, iter_):
  987. """populate from an iterator of (key, column)"""
  988. cols = list(iter_)
  989. self._collection[:] = cols
  990. self._colset.update(c for k, c in self._collection)
  991. self._index.update(
  992. (idx, c) for idx, (k, c) in enumerate(self._collection)
  993. )
  994. self._index.update({k: col for k, col in reversed(self._collection)})
  995. def add(self, column, key=None):
  996. """Add a column to this :class:`_sql.ColumnCollection`.
  997. .. note::
  998. This method is **not normally used by user-facing code**, as the
  999. :class:`_sql.ColumnCollection` is usually part of an existing
  1000. object such as a :class:`_schema.Table`. To add a
  1001. :class:`_schema.Column` to an existing :class:`_schema.Table`
  1002. object, use the :meth:`_schema.Table.append_column` method.
  1003. """
  1004. if key is None:
  1005. key = column.key
  1006. l = len(self._collection)
  1007. self._collection.append((key, column))
  1008. self._colset.add(column)
  1009. self._index[l] = column
  1010. if key not in self._index:
  1011. self._index[key] = column
  1012. def __getstate__(self):
  1013. return {"_collection": self._collection, "_index": self._index}
  1014. def __setstate__(self, state):
  1015. object.__setattr__(self, "_index", state["_index"])
  1016. object.__setattr__(self, "_collection", state["_collection"])
  1017. object.__setattr__(
  1018. self, "_colset", {col for k, col in self._collection}
  1019. )
  1020. def contains_column(self, col):
  1021. """Checks if a column object exists in this collection"""
  1022. if col not in self._colset:
  1023. if isinstance(col, util.string_types):
  1024. raise exc.ArgumentError(
  1025. "contains_column cannot be used with string arguments. "
  1026. "Use ``col_name in table.c`` instead."
  1027. )
  1028. return False
  1029. else:
  1030. return True
  1031. def as_immutable(self):
  1032. """Return an "immutable" form of this
  1033. :class:`_sql.ColumnCollection`."""
  1034. return ImmutableColumnCollection(self)
  1035. def corresponding_column(self, column, require_embedded=False):
  1036. """Given a :class:`_expression.ColumnElement`, return the exported
  1037. :class:`_expression.ColumnElement` object from this
  1038. :class:`_expression.ColumnCollection`
  1039. which corresponds to that original :class:`_expression.ColumnElement`
  1040. via a common
  1041. ancestor column.
  1042. :param column: the target :class:`_expression.ColumnElement`
  1043. to be matched.
  1044. :param require_embedded: only return corresponding columns for
  1045. the given :class:`_expression.ColumnElement`, if the given
  1046. :class:`_expression.ColumnElement`
  1047. is actually present within a sub-element
  1048. of this :class:`_expression.Selectable`.
  1049. Normally the column will match if
  1050. it merely shares a common ancestor with one of the exported
  1051. columns of this :class:`_expression.Selectable`.
  1052. .. seealso::
  1053. :meth:`_expression.Selectable.corresponding_column`
  1054. - invokes this method
  1055. against the collection returned by
  1056. :attr:`_expression.Selectable.exported_columns`.
  1057. .. versionchanged:: 1.4 the implementation for ``corresponding_column``
  1058. was moved onto the :class:`_expression.ColumnCollection` itself.
  1059. """
  1060. def embedded(expanded_proxy_set, target_set):
  1061. for t in target_set.difference(expanded_proxy_set):
  1062. if not set(_expand_cloned([t])).intersection(
  1063. expanded_proxy_set
  1064. ):
  1065. return False
  1066. return True
  1067. # don't dig around if the column is locally present
  1068. if column in self._colset:
  1069. return column
  1070. col, intersect = None, None
  1071. target_set = column.proxy_set
  1072. cols = [c for (k, c) in self._collection]
  1073. for c in cols:
  1074. expanded_proxy_set = set(_expand_cloned(c.proxy_set))
  1075. i = target_set.intersection(expanded_proxy_set)
  1076. if i and (
  1077. not require_embedded
  1078. or embedded(expanded_proxy_set, target_set)
  1079. ):
  1080. if col is None:
  1081. # no corresponding column yet, pick this one.
  1082. col, intersect = c, i
  1083. elif len(i) > len(intersect):
  1084. # 'c' has a larger field of correspondence than
  1085. # 'col'. i.e. selectable.c.a1_x->a1.c.x->table.c.x
  1086. # matches a1.c.x->table.c.x better than
  1087. # selectable.c.x->table.c.x does.
  1088. col, intersect = c, i
  1089. elif i == intersect:
  1090. # they have the same field of correspondence. see
  1091. # which proxy_set has fewer columns in it, which
  1092. # indicates a closer relationship with the root
  1093. # column. Also take into account the "weight"
  1094. # attribute which CompoundSelect() uses to give
  1095. # higher precedence to columns based on vertical
  1096. # position in the compound statement, and discard
  1097. # columns that have no reference to the target
  1098. # column (also occurs with CompoundSelect)
  1099. col_distance = util.reduce(
  1100. operator.add,
  1101. [
  1102. sc._annotations.get("weight", 1)
  1103. for sc in col._uncached_proxy_set()
  1104. if sc.shares_lineage(column)
  1105. ],
  1106. )
  1107. c_distance = util.reduce(
  1108. operator.add,
  1109. [
  1110. sc._annotations.get("weight", 1)
  1111. for sc in c._uncached_proxy_set()
  1112. if sc.shares_lineage(column)
  1113. ],
  1114. )
  1115. if c_distance < col_distance:
  1116. col, intersect = c, i
  1117. return col
  1118. class DedupeColumnCollection(ColumnCollection):
  1119. """A :class:`_expression.ColumnCollection`
  1120. that maintains deduplicating behavior.
  1121. This is useful by schema level objects such as :class:`_schema.Table` and
  1122. :class:`.PrimaryKeyConstraint`. The collection includes more
  1123. sophisticated mutator methods as well to suit schema objects which
  1124. require mutable column collections.
  1125. .. versionadded:: 1.4
  1126. """
  1127. def add(self, column, key=None):
  1128. if key is not None and column.key != key:
  1129. raise exc.ArgumentError(
  1130. "DedupeColumnCollection requires columns be under "
  1131. "the same key as their .key"
  1132. )
  1133. key = column.key
  1134. if key is None:
  1135. raise exc.ArgumentError(
  1136. "Can't add unnamed column to column collection"
  1137. )
  1138. if key in self._index:
  1139. existing = self._index[key]
  1140. if existing is column:
  1141. return
  1142. self.replace(column)
  1143. # pop out memoized proxy_set as this
  1144. # operation may very well be occurring
  1145. # in a _make_proxy operation
  1146. util.memoized_property.reset(column, "proxy_set")
  1147. else:
  1148. l = len(self._collection)
  1149. self._collection.append((key, column))
  1150. self._colset.add(column)
  1151. self._index[l] = column
  1152. self._index[key] = column
  1153. def _populate_separate_keys(self, iter_):
  1154. """populate from an iterator of (key, column)"""
  1155. cols = list(iter_)
  1156. replace_col = []
  1157. for k, col in cols:
  1158. if col.key != k:
  1159. raise exc.ArgumentError(
  1160. "DedupeColumnCollection requires columns be under "
  1161. "the same key as their .key"
  1162. )
  1163. if col.name in self._index and col.key != col.name:
  1164. replace_col.append(col)
  1165. elif col.key in self._index:
  1166. replace_col.append(col)
  1167. else:
  1168. self._index[k] = col
  1169. self._collection.append((k, col))
  1170. self._colset.update(c for (k, c) in self._collection)
  1171. self._index.update(
  1172. (idx, c) for idx, (k, c) in enumerate(self._collection)
  1173. )
  1174. for col in replace_col:
  1175. self.replace(col)
  1176. def extend(self, iter_):
  1177. self._populate_separate_keys((col.key, col) for col in iter_)
  1178. def remove(self, column):
  1179. if column not in self._colset:
  1180. raise ValueError(
  1181. "Can't remove column %r; column is not in this collection"
  1182. % column
  1183. )
  1184. del self._index[column.key]
  1185. self._colset.remove(column)
  1186. self._collection[:] = [
  1187. (k, c) for (k, c) in self._collection if c is not column
  1188. ]
  1189. self._index.update(
  1190. {idx: col for idx, (k, col) in enumerate(self._collection)}
  1191. )
  1192. # delete higher index
  1193. del self._index[len(self._collection)]
  1194. def replace(self, column):
  1195. """add the given column to this collection, removing unaliased
  1196. versions of this column as well as existing columns with the
  1197. same key.
  1198. e.g.::
  1199. t = Table('sometable', metadata, Column('col1', Integer))
  1200. t.columns.replace(Column('col1', Integer, key='columnone'))
  1201. will remove the original 'col1' from the collection, and add
  1202. the new column under the name 'columnname'.
  1203. Used by schema.Column to override columns during table reflection.
  1204. """
  1205. remove_col = set()
  1206. # remove up to two columns based on matches of name as well as key
  1207. if column.name in self._index and column.key != column.name:
  1208. other = self._index[column.name]
  1209. if other.name == other.key:
  1210. remove_col.add(other)
  1211. if column.key in self._index:
  1212. remove_col.add(self._index[column.key])
  1213. new_cols = []
  1214. replaced = False
  1215. for k, col in self._collection:
  1216. if col in remove_col:
  1217. if not replaced:
  1218. replaced = True
  1219. new_cols.append((column.key, column))
  1220. else:
  1221. new_cols.append((k, col))
  1222. if remove_col:
  1223. self._colset.difference_update(remove_col)
  1224. if not replaced:
  1225. new_cols.append((column.key, column))
  1226. self._colset.add(column)
  1227. self._collection[:] = new_cols
  1228. self._index.clear()
  1229. self._index.update(
  1230. {idx: col for idx, (k, col) in enumerate(self._collection)}
  1231. )
  1232. self._index.update(self._collection)
  1233. class ImmutableColumnCollection(util.ImmutableContainer, ColumnCollection):
  1234. __slots__ = ("_parent",)
  1235. def __init__(self, collection):
  1236. object.__setattr__(self, "_parent", collection)
  1237. object.__setattr__(self, "_colset", collection._colset)
  1238. object.__setattr__(self, "_index", collection._index)
  1239. object.__setattr__(self, "_collection", collection._collection)
  1240. def __getstate__(self):
  1241. return {"_parent": self._parent}
  1242. def __setstate__(self, state):
  1243. parent = state["_parent"]
  1244. self.__init__(parent)
  1245. add = extend = remove = util.ImmutableContainer._immutable
  1246. class ColumnSet(util.ordered_column_set):
  1247. def contains_column(self, col):
  1248. return col in self
  1249. def extend(self, cols):
  1250. for col in cols:
  1251. self.add(col)
  1252. def __add__(self, other):
  1253. return list(self) + list(other)
  1254. def __eq__(self, other):
  1255. l = []
  1256. for c in other:
  1257. for local in self:
  1258. if c.shares_lineage(local):
  1259. l.append(c == local)
  1260. return elements.and_(*l)
  1261. def __hash__(self):
  1262. return hash(tuple(x for x in self))
  1263. def _bind_or_error(schemaitem, msg=None):
  1264. util.warn_deprecated_20(
  1265. "The ``bind`` argument for schema methods that invoke SQL "
  1266. "against an engine or connection will be required in SQLAlchemy 2.0."
  1267. )
  1268. bind = schemaitem.bind
  1269. if not bind:
  1270. name = schemaitem.__class__.__name__
  1271. label = getattr(
  1272. schemaitem, "fullname", getattr(schemaitem, "name", None)
  1273. )
  1274. if label:
  1275. item = "%s object %r" % (name, label)
  1276. else:
  1277. item = "%s object" % name
  1278. if msg is None:
  1279. msg = (
  1280. "%s is not bound to an Engine or Connection. "
  1281. "Execution can not proceed without a database to execute "
  1282. "against." % item
  1283. )
  1284. raise exc.UnboundExecutionError(msg)
  1285. return bind
  1286. def _entity_namespace(entity):
  1287. """Return the nearest .entity_namespace for the given entity.
  1288. If not immediately available, does an iterate to find a sub-element
  1289. that has one, if any.
  1290. """
  1291. try:
  1292. return entity.entity_namespace
  1293. except AttributeError:
  1294. for elem in visitors.iterate(entity):
  1295. if hasattr(elem, "entity_namespace"):
  1296. return elem.entity_namespace
  1297. else:
  1298. raise
  1299. def _entity_namespace_key(entity, key, default=NO_ARG):
  1300. """Return an entry from an entity_namespace.
  1301. Raises :class:`_exc.InvalidRequestError` rather than attribute error
  1302. on not found.
  1303. """
  1304. try:
  1305. ns = _entity_namespace(entity)
  1306. if default is not NO_ARG:
  1307. return getattr(ns, key, default)
  1308. else:
  1309. return getattr(ns, key)
  1310. except AttributeError as err:
  1311. util.raise_(
  1312. exc.InvalidRequestError(
  1313. 'Entity namespace for "%s" has no property "%s"'
  1314. % (entity, key)
  1315. ),
  1316. replace_context=err,
  1317. )