traversals.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  1. from collections import deque
  2. from collections import namedtuple
  3. import itertools
  4. import operator
  5. from . import operators
  6. from .visitors import ExtendedInternalTraversal
  7. from .visitors import InternalTraversal
  8. from .. import util
  9. from ..inspection import inspect
  10. from ..util import collections_abc
  11. from ..util import HasMemoized
  12. from ..util import py37
  13. SKIP_TRAVERSE = util.symbol("skip_traverse")
  14. COMPARE_FAILED = False
  15. COMPARE_SUCCEEDED = True
  16. NO_CACHE = util.symbol("no_cache")
  17. CACHE_IN_PLACE = util.symbol("cache_in_place")
  18. CALL_GEN_CACHE_KEY = util.symbol("call_gen_cache_key")
  19. STATIC_CACHE_KEY = util.symbol("static_cache_key")
  20. PROPAGATE_ATTRS = util.symbol("propagate_attrs")
  21. ANON_NAME = util.symbol("anon_name")
  22. def compare(obj1, obj2, **kw):
  23. if kw.get("use_proxies", False):
  24. strategy = ColIdentityComparatorStrategy()
  25. else:
  26. strategy = TraversalComparatorStrategy()
  27. return strategy.compare(obj1, obj2, **kw)
  28. def _preconfigure_traversals(target_hierarchy):
  29. for cls in util.walk_subclasses(target_hierarchy):
  30. if hasattr(cls, "_traverse_internals"):
  31. cls._generate_cache_attrs()
  32. _copy_internals.generate_dispatch(
  33. cls,
  34. cls._traverse_internals,
  35. "_generated_copy_internals_traversal",
  36. )
  37. _get_children.generate_dispatch(
  38. cls,
  39. cls._traverse_internals,
  40. "_generated_get_children_traversal",
  41. )
  42. class HasCacheKey(object):
  43. """Mixin for objects which can produce a cache key.
  44. .. seealso::
  45. :class:`.CacheKey`
  46. :ref:`sql_caching`
  47. """
  48. _cache_key_traversal = NO_CACHE
  49. _is_has_cache_key = True
  50. _hierarchy_supports_caching = True
  51. """private attribute which may be set to False to prevent the
  52. inherit_cache warning from being emitted for a hierarchy of subclasses.
  53. Currently applies to the DDLElement hierarchy which does not implement
  54. caching.
  55. """
  56. inherit_cache = None
  57. """Indicate if this :class:`.HasCacheKey` instance should make use of the
  58. cache key generation scheme used by its immediate superclass.
  59. The attribute defaults to ``None``, which indicates that a construct has
  60. not yet taken into account whether or not its appropriate for it to
  61. participate in caching; this is functionally equivalent to setting the
  62. value to ``False``, except that a warning is also emitted.
  63. This flag can be set to ``True`` on a particular class, if the SQL that
  64. corresponds to the object does not change based on attributes which
  65. are local to this class, and not its superclass.
  66. .. seealso::
  67. :ref:`compilerext_caching` - General guideslines for setting the
  68. :attr:`.HasCacheKey.inherit_cache` attribute for third-party or user
  69. defined SQL constructs.
  70. """
  71. __slots__ = ()
  72. @classmethod
  73. def _generate_cache_attrs(cls):
  74. """generate cache key dispatcher for a new class.
  75. This sets the _generated_cache_key_traversal attribute once called
  76. so should only be called once per class.
  77. """
  78. inherit_cache = cls.__dict__.get("inherit_cache", None)
  79. inherit = bool(inherit_cache)
  80. if inherit:
  81. _cache_key_traversal = getattr(cls, "_cache_key_traversal", None)
  82. if _cache_key_traversal is None:
  83. try:
  84. _cache_key_traversal = cls._traverse_internals
  85. except AttributeError:
  86. cls._generated_cache_key_traversal = NO_CACHE
  87. return NO_CACHE
  88. # TODO: wouldn't we instead get this from our superclass?
  89. # also, our superclass may not have this yet, but in any case,
  90. # we'd generate for the superclass that has it. this is a little
  91. # more complicated, so for the moment this is a little less
  92. # efficient on startup but simpler.
  93. return _cache_key_traversal_visitor.generate_dispatch(
  94. cls, _cache_key_traversal, "_generated_cache_key_traversal"
  95. )
  96. else:
  97. _cache_key_traversal = cls.__dict__.get(
  98. "_cache_key_traversal", None
  99. )
  100. if _cache_key_traversal is None:
  101. _cache_key_traversal = cls.__dict__.get(
  102. "_traverse_internals", None
  103. )
  104. if _cache_key_traversal is None:
  105. cls._generated_cache_key_traversal = NO_CACHE
  106. if (
  107. inherit_cache is None
  108. and cls._hierarchy_supports_caching
  109. ):
  110. util.warn(
  111. "Class %s will not make use of SQL compilation "
  112. "caching as it does not set the 'inherit_cache' "
  113. "attribute to ``True``. This can have "
  114. "significant performance implications including "
  115. "some performance degradations in comparison to "
  116. "prior SQLAlchemy versions. Set this attribute "
  117. "to True if this object can make use of the cache "
  118. "key generated by the superclass. Alternatively, "
  119. "this attribute may be set to False which will "
  120. "disable this warning." % (cls.__name__),
  121. code="cprf",
  122. )
  123. return NO_CACHE
  124. return _cache_key_traversal_visitor.generate_dispatch(
  125. cls, _cache_key_traversal, "_generated_cache_key_traversal"
  126. )
  127. @util.preload_module("sqlalchemy.sql.elements")
  128. def _gen_cache_key(self, anon_map, bindparams):
  129. """return an optional cache key.
  130. The cache key is a tuple which can contain any series of
  131. objects that are hashable and also identifies
  132. this object uniquely within the presence of a larger SQL expression
  133. or statement, for the purposes of caching the resulting query.
  134. The cache key should be based on the SQL compiled structure that would
  135. ultimately be produced. That is, two structures that are composed in
  136. exactly the same way should produce the same cache key; any difference
  137. in the structures that would affect the SQL string or the type handlers
  138. should result in a different cache key.
  139. If a structure cannot produce a useful cache key, the NO_CACHE
  140. symbol should be added to the anon_map and the method should
  141. return None.
  142. """
  143. idself = id(self)
  144. cls = self.__class__
  145. if idself in anon_map:
  146. return (anon_map[idself], cls)
  147. else:
  148. # inline of
  149. # id_ = anon_map[idself]
  150. anon_map[idself] = id_ = str(anon_map.index)
  151. anon_map.index += 1
  152. try:
  153. dispatcher = cls.__dict__["_generated_cache_key_traversal"]
  154. except KeyError:
  155. # most of the dispatchers are generated up front
  156. # in sqlalchemy/sql/__init__.py ->
  157. # traversals.py-> _preconfigure_traversals().
  158. # this block will generate any remaining dispatchers.
  159. dispatcher = cls._generate_cache_attrs()
  160. if dispatcher is NO_CACHE:
  161. anon_map[NO_CACHE] = True
  162. return None
  163. result = (id_, cls)
  164. # inline of _cache_key_traversal_visitor.run_generated_dispatch()
  165. for attrname, obj, meth in dispatcher(
  166. self, _cache_key_traversal_visitor
  167. ):
  168. if obj is not None:
  169. # TODO: see if C code can help here as Python lacks an
  170. # efficient switch construct
  171. if meth is STATIC_CACHE_KEY:
  172. sck = obj._static_cache_key
  173. if sck is NO_CACHE:
  174. anon_map[NO_CACHE] = True
  175. return None
  176. result += (attrname, sck)
  177. elif meth is ANON_NAME:
  178. elements = util.preloaded.sql_elements
  179. if isinstance(obj, elements._anonymous_label):
  180. obj = obj.apply_map(anon_map)
  181. result += (attrname, obj)
  182. elif meth is CALL_GEN_CACHE_KEY:
  183. result += (
  184. attrname,
  185. obj._gen_cache_key(anon_map, bindparams),
  186. )
  187. # remaining cache functions are against
  188. # Python tuples, dicts, lists, etc. so we can skip
  189. # if they are empty
  190. elif obj:
  191. if meth is CACHE_IN_PLACE:
  192. result += (attrname, obj)
  193. elif meth is PROPAGATE_ATTRS:
  194. result += (
  195. attrname,
  196. obj["compile_state_plugin"],
  197. obj["plugin_subject"]._gen_cache_key(
  198. anon_map, bindparams
  199. )
  200. if obj["plugin_subject"]
  201. else None,
  202. )
  203. elif meth is InternalTraversal.dp_annotations_key:
  204. # obj is here is the _annotations dict. however, we
  205. # want to use the memoized cache key version of it. for
  206. # Columns, this should be long lived. For select()
  207. # statements, not so much, but they usually won't have
  208. # annotations.
  209. result += self._annotations_cache_key
  210. elif (
  211. meth is InternalTraversal.dp_clauseelement_list
  212. or meth is InternalTraversal.dp_clauseelement_tuple
  213. or meth
  214. is InternalTraversal.dp_memoized_select_entities
  215. ):
  216. result += (
  217. attrname,
  218. tuple(
  219. [
  220. elem._gen_cache_key(anon_map, bindparams)
  221. for elem in obj
  222. ]
  223. ),
  224. )
  225. else:
  226. result += meth(
  227. attrname, obj, self, anon_map, bindparams
  228. )
  229. return result
  230. def _generate_cache_key(self):
  231. """return a cache key.
  232. The cache key is a tuple which can contain any series of
  233. objects that are hashable and also identifies
  234. this object uniquely within the presence of a larger SQL expression
  235. or statement, for the purposes of caching the resulting query.
  236. The cache key should be based on the SQL compiled structure that would
  237. ultimately be produced. That is, two structures that are composed in
  238. exactly the same way should produce the same cache key; any difference
  239. in the structures that would affect the SQL string or the type handlers
  240. should result in a different cache key.
  241. The cache key returned by this method is an instance of
  242. :class:`.CacheKey`, which consists of a tuple representing the
  243. cache key, as well as a list of :class:`.BindParameter` objects
  244. which are extracted from the expression. While two expressions
  245. that produce identical cache key tuples will themselves generate
  246. identical SQL strings, the list of :class:`.BindParameter` objects
  247. indicates the bound values which may have different values in
  248. each one; these bound parameters must be consulted in order to
  249. execute the statement with the correct parameters.
  250. a :class:`_expression.ClauseElement` structure that does not implement
  251. a :meth:`._gen_cache_key` method and does not implement a
  252. :attr:`.traverse_internals` attribute will not be cacheable; when
  253. such an element is embedded into a larger structure, this method
  254. will return None, indicating no cache key is available.
  255. """
  256. bindparams = []
  257. _anon_map = anon_map()
  258. key = self._gen_cache_key(_anon_map, bindparams)
  259. if NO_CACHE in _anon_map:
  260. return None
  261. else:
  262. return CacheKey(key, bindparams)
  263. @classmethod
  264. def _generate_cache_key_for_object(cls, obj):
  265. bindparams = []
  266. _anon_map = anon_map()
  267. key = obj._gen_cache_key(_anon_map, bindparams)
  268. if NO_CACHE in _anon_map:
  269. return None
  270. else:
  271. return CacheKey(key, bindparams)
  272. class MemoizedHasCacheKey(HasCacheKey, HasMemoized):
  273. @HasMemoized.memoized_instancemethod
  274. def _generate_cache_key(self):
  275. return HasCacheKey._generate_cache_key(self)
  276. class CacheKey(namedtuple("CacheKey", ["key", "bindparams"])):
  277. """The key used to identify a SQL statement construct in the
  278. SQL compilation cache.
  279. .. seealso::
  280. :ref:`sql_caching`
  281. """
  282. def __hash__(self):
  283. """CacheKey itself is not hashable - hash the .key portion"""
  284. return None
  285. def to_offline_string(self, statement_cache, statement, parameters):
  286. """Generate an "offline string" form of this :class:`.CacheKey`
  287. The "offline string" is basically the string SQL for the
  288. statement plus a repr of the bound parameter values in series.
  289. Whereas the :class:`.CacheKey` object is dependent on in-memory
  290. identities in order to work as a cache key, the "offline" version
  291. is suitable for a cache that will work for other processes as well.
  292. The given ``statement_cache`` is a dictionary-like object where the
  293. string form of the statement itself will be cached. This dictionary
  294. should be in a longer lived scope in order to reduce the time spent
  295. stringifying statements.
  296. """
  297. if self.key not in statement_cache:
  298. statement_cache[self.key] = sql_str = str(statement)
  299. else:
  300. sql_str = statement_cache[self.key]
  301. if not self.bindparams:
  302. param_tuple = tuple(parameters[key] for key in sorted(parameters))
  303. else:
  304. param_tuple = tuple(
  305. parameters.get(bindparam.key, bindparam.value)
  306. for bindparam in self.bindparams
  307. )
  308. return repr((sql_str, param_tuple))
  309. def __eq__(self, other):
  310. return self.key == other.key
  311. @classmethod
  312. def _diff_tuples(cls, left, right):
  313. ck1 = CacheKey(left, [])
  314. ck2 = CacheKey(right, [])
  315. return ck1._diff(ck2)
  316. def _whats_different(self, other):
  317. k1 = self.key
  318. k2 = other.key
  319. stack = []
  320. pickup_index = 0
  321. while True:
  322. s1, s2 = k1, k2
  323. for idx in stack:
  324. s1 = s1[idx]
  325. s2 = s2[idx]
  326. for idx, (e1, e2) in enumerate(util.zip_longest(s1, s2)):
  327. if idx < pickup_index:
  328. continue
  329. if e1 != e2:
  330. if isinstance(e1, tuple) and isinstance(e2, tuple):
  331. stack.append(idx)
  332. break
  333. else:
  334. yield "key%s[%d]: %s != %s" % (
  335. "".join("[%d]" % id_ for id_ in stack),
  336. idx,
  337. e1,
  338. e2,
  339. )
  340. else:
  341. pickup_index = stack.pop(-1)
  342. break
  343. def _diff(self, other):
  344. return ", ".join(self._whats_different(other))
  345. def __str__(self):
  346. stack = [self.key]
  347. output = []
  348. sentinel = object()
  349. indent = -1
  350. while stack:
  351. elem = stack.pop(0)
  352. if elem is sentinel:
  353. output.append((" " * (indent * 2)) + "),")
  354. indent -= 1
  355. elif isinstance(elem, tuple):
  356. if not elem:
  357. output.append((" " * ((indent + 1) * 2)) + "()")
  358. else:
  359. indent += 1
  360. stack = list(elem) + [sentinel] + stack
  361. output.append((" " * (indent * 2)) + "(")
  362. else:
  363. if isinstance(elem, HasCacheKey):
  364. repr_ = "<%s object at %s>" % (
  365. type(elem).__name__,
  366. hex(id(elem)),
  367. )
  368. else:
  369. repr_ = repr(elem)
  370. output.append((" " * (indent * 2)) + " " + repr_ + ", ")
  371. return "CacheKey(key=%s)" % ("\n".join(output),)
  372. def _generate_param_dict(self):
  373. """used for testing"""
  374. from .compiler import prefix_anon_map
  375. _anon_map = prefix_anon_map()
  376. return {b.key % _anon_map: b.effective_value for b in self.bindparams}
  377. def _apply_params_to_element(self, original_cache_key, target_element):
  378. translate = {
  379. k.key: v.value
  380. for k, v in zip(original_cache_key.bindparams, self.bindparams)
  381. }
  382. return target_element.params(translate)
  383. def _clone(element, **kw):
  384. return element._clone()
  385. class _CacheKey(ExtendedInternalTraversal):
  386. # very common elements are inlined into the main _get_cache_key() method
  387. # to produce a dramatic savings in Python function call overhead
  388. visit_has_cache_key = visit_clauseelement = CALL_GEN_CACHE_KEY
  389. visit_clauseelement_list = InternalTraversal.dp_clauseelement_list
  390. visit_annotations_key = InternalTraversal.dp_annotations_key
  391. visit_clauseelement_tuple = InternalTraversal.dp_clauseelement_tuple
  392. visit_memoized_select_entities = (
  393. InternalTraversal.dp_memoized_select_entities
  394. )
  395. visit_string = (
  396. visit_boolean
  397. ) = visit_operator = visit_plain_obj = CACHE_IN_PLACE
  398. visit_statement_hint_list = CACHE_IN_PLACE
  399. visit_type = STATIC_CACHE_KEY
  400. visit_anon_name = ANON_NAME
  401. visit_propagate_attrs = PROPAGATE_ATTRS
  402. def visit_with_context_options(
  403. self, attrname, obj, parent, anon_map, bindparams
  404. ):
  405. return tuple((fn.__code__, c_key) for fn, c_key in obj)
  406. def visit_inspectable(self, attrname, obj, parent, anon_map, bindparams):
  407. return (attrname, inspect(obj)._gen_cache_key(anon_map, bindparams))
  408. def visit_string_list(self, attrname, obj, parent, anon_map, bindparams):
  409. return tuple(obj)
  410. def visit_multi(self, attrname, obj, parent, anon_map, bindparams):
  411. return (
  412. attrname,
  413. obj._gen_cache_key(anon_map, bindparams)
  414. if isinstance(obj, HasCacheKey)
  415. else obj,
  416. )
  417. def visit_multi_list(self, attrname, obj, parent, anon_map, bindparams):
  418. return (
  419. attrname,
  420. tuple(
  421. elem._gen_cache_key(anon_map, bindparams)
  422. if isinstance(elem, HasCacheKey)
  423. else elem
  424. for elem in obj
  425. ),
  426. )
  427. def visit_has_cache_key_tuples(
  428. self, attrname, obj, parent, anon_map, bindparams
  429. ):
  430. if not obj:
  431. return ()
  432. return (
  433. attrname,
  434. tuple(
  435. tuple(
  436. elem._gen_cache_key(anon_map, bindparams)
  437. for elem in tup_elem
  438. )
  439. for tup_elem in obj
  440. ),
  441. )
  442. def visit_has_cache_key_list(
  443. self, attrname, obj, parent, anon_map, bindparams
  444. ):
  445. if not obj:
  446. return ()
  447. return (
  448. attrname,
  449. tuple(elem._gen_cache_key(anon_map, bindparams) for elem in obj),
  450. )
  451. def visit_executable_options(
  452. self, attrname, obj, parent, anon_map, bindparams
  453. ):
  454. if not obj:
  455. return ()
  456. return (
  457. attrname,
  458. tuple(
  459. elem._gen_cache_key(anon_map, bindparams)
  460. for elem in obj
  461. if elem._is_has_cache_key
  462. ),
  463. )
  464. def visit_inspectable_list(
  465. self, attrname, obj, parent, anon_map, bindparams
  466. ):
  467. return self.visit_has_cache_key_list(
  468. attrname, [inspect(o) for o in obj], parent, anon_map, bindparams
  469. )
  470. def visit_clauseelement_tuples(
  471. self, attrname, obj, parent, anon_map, bindparams
  472. ):
  473. return self.visit_has_cache_key_tuples(
  474. attrname, obj, parent, anon_map, bindparams
  475. )
  476. def visit_fromclause_ordered_set(
  477. self, attrname, obj, parent, anon_map, bindparams
  478. ):
  479. if not obj:
  480. return ()
  481. return (
  482. attrname,
  483. tuple([elem._gen_cache_key(anon_map, bindparams) for elem in obj]),
  484. )
  485. def visit_clauseelement_unordered_set(
  486. self, attrname, obj, parent, anon_map, bindparams
  487. ):
  488. if not obj:
  489. return ()
  490. cache_keys = [
  491. elem._gen_cache_key(anon_map, bindparams) for elem in obj
  492. ]
  493. return (
  494. attrname,
  495. tuple(
  496. sorted(cache_keys)
  497. ), # cache keys all start with (id_, class)
  498. )
  499. def visit_named_ddl_element(
  500. self, attrname, obj, parent, anon_map, bindparams
  501. ):
  502. return (attrname, obj.name)
  503. def visit_prefix_sequence(
  504. self, attrname, obj, parent, anon_map, bindparams
  505. ):
  506. if not obj:
  507. return ()
  508. return (
  509. attrname,
  510. tuple(
  511. [
  512. (clause._gen_cache_key(anon_map, bindparams), strval)
  513. for clause, strval in obj
  514. ]
  515. ),
  516. )
  517. def visit_setup_join_tuple(
  518. self, attrname, obj, parent, anon_map, bindparams
  519. ):
  520. is_legacy = "legacy" in attrname
  521. return tuple(
  522. (
  523. target
  524. if is_legacy and isinstance(target, str)
  525. else target._gen_cache_key(anon_map, bindparams),
  526. onclause
  527. if is_legacy and isinstance(onclause, str)
  528. else onclause._gen_cache_key(anon_map, bindparams)
  529. if onclause is not None
  530. else None,
  531. from_._gen_cache_key(anon_map, bindparams)
  532. if from_ is not None
  533. else None,
  534. tuple([(key, flags[key]) for key in sorted(flags)]),
  535. )
  536. for (target, onclause, from_, flags) in obj
  537. )
  538. def visit_table_hint_list(
  539. self, attrname, obj, parent, anon_map, bindparams
  540. ):
  541. if not obj:
  542. return ()
  543. return (
  544. attrname,
  545. tuple(
  546. [
  547. (
  548. clause._gen_cache_key(anon_map, bindparams),
  549. dialect_name,
  550. text,
  551. )
  552. for (clause, dialect_name), text in obj.items()
  553. ]
  554. ),
  555. )
  556. def visit_plain_dict(self, attrname, obj, parent, anon_map, bindparams):
  557. return (attrname, tuple([(key, obj[key]) for key in sorted(obj)]))
  558. def visit_dialect_options(
  559. self, attrname, obj, parent, anon_map, bindparams
  560. ):
  561. return (
  562. attrname,
  563. tuple(
  564. (
  565. dialect_name,
  566. tuple(
  567. [
  568. (key, obj[dialect_name][key])
  569. for key in sorted(obj[dialect_name])
  570. ]
  571. ),
  572. )
  573. for dialect_name in sorted(obj)
  574. ),
  575. )
  576. def visit_string_clauseelement_dict(
  577. self, attrname, obj, parent, anon_map, bindparams
  578. ):
  579. return (
  580. attrname,
  581. tuple(
  582. (key, obj[key]._gen_cache_key(anon_map, bindparams))
  583. for key in sorted(obj)
  584. ),
  585. )
  586. def visit_string_multi_dict(
  587. self, attrname, obj, parent, anon_map, bindparams
  588. ):
  589. return (
  590. attrname,
  591. tuple(
  592. (
  593. key,
  594. value._gen_cache_key(anon_map, bindparams)
  595. if isinstance(value, HasCacheKey)
  596. else value,
  597. )
  598. for key, value in [(key, obj[key]) for key in sorted(obj)]
  599. ),
  600. )
  601. def visit_fromclause_canonical_column_collection(
  602. self, attrname, obj, parent, anon_map, bindparams
  603. ):
  604. # inlining into the internals of ColumnCollection
  605. return (
  606. attrname,
  607. tuple(
  608. col._gen_cache_key(anon_map, bindparams)
  609. for k, col in obj._collection
  610. ),
  611. )
  612. def visit_unknown_structure(
  613. self, attrname, obj, parent, anon_map, bindparams
  614. ):
  615. anon_map[NO_CACHE] = True
  616. return ()
  617. def visit_dml_ordered_values(
  618. self, attrname, obj, parent, anon_map, bindparams
  619. ):
  620. return (
  621. attrname,
  622. tuple(
  623. (
  624. key._gen_cache_key(anon_map, bindparams)
  625. if hasattr(key, "__clause_element__")
  626. else key,
  627. value._gen_cache_key(anon_map, bindparams),
  628. )
  629. for key, value in obj
  630. ),
  631. )
  632. def visit_dml_values(self, attrname, obj, parent, anon_map, bindparams):
  633. if py37:
  634. # in py37 we can assume two dictionaries created in the same
  635. # insert ordering will retain that sorting
  636. return (
  637. attrname,
  638. tuple(
  639. (
  640. k._gen_cache_key(anon_map, bindparams)
  641. if hasattr(k, "__clause_element__")
  642. else k,
  643. obj[k]._gen_cache_key(anon_map, bindparams),
  644. )
  645. for k in obj
  646. ),
  647. )
  648. else:
  649. expr_values = {k for k in obj if hasattr(k, "__clause_element__")}
  650. if expr_values:
  651. # expr values can't be sorted deterministically right now,
  652. # so no cache
  653. anon_map[NO_CACHE] = True
  654. return ()
  655. str_values = expr_values.symmetric_difference(obj)
  656. return (
  657. attrname,
  658. tuple(
  659. (k, obj[k]._gen_cache_key(anon_map, bindparams))
  660. for k in sorted(str_values)
  661. ),
  662. )
  663. def visit_dml_multi_values(
  664. self, attrname, obj, parent, anon_map, bindparams
  665. ):
  666. # multivalues are simply not cacheable right now
  667. anon_map[NO_CACHE] = True
  668. return ()
  669. _cache_key_traversal_visitor = _CacheKey()
  670. class HasCopyInternals(object):
  671. def _clone(self, **kw):
  672. raise NotImplementedError()
  673. def _copy_internals(self, omit_attrs=(), **kw):
  674. """Reassign internal elements to be clones of themselves.
  675. Called during a copy-and-traverse operation on newly
  676. shallow-copied elements to create a deep copy.
  677. The given clone function should be used, which may be applying
  678. additional transformations to the element (i.e. replacement
  679. traversal, cloned traversal, annotations).
  680. """
  681. try:
  682. traverse_internals = self._traverse_internals
  683. except AttributeError:
  684. # user-defined classes may not have a _traverse_internals
  685. return
  686. for attrname, obj, meth in _copy_internals.run_generated_dispatch(
  687. self, traverse_internals, "_generated_copy_internals_traversal"
  688. ):
  689. if attrname in omit_attrs:
  690. continue
  691. if obj is not None:
  692. result = meth(attrname, self, obj, **kw)
  693. if result is not None:
  694. setattr(self, attrname, result)
  695. class _CopyInternals(InternalTraversal):
  696. """Generate a _copy_internals internal traversal dispatch for classes
  697. with a _traverse_internals collection."""
  698. def visit_clauseelement(
  699. self, attrname, parent, element, clone=_clone, **kw
  700. ):
  701. return clone(element, **kw)
  702. def visit_clauseelement_list(
  703. self, attrname, parent, element, clone=_clone, **kw
  704. ):
  705. return [clone(clause, **kw) for clause in element]
  706. def visit_clauseelement_tuple(
  707. self, attrname, parent, element, clone=_clone, **kw
  708. ):
  709. return tuple([clone(clause, **kw) for clause in element])
  710. def visit_executable_options(
  711. self, attrname, parent, element, clone=_clone, **kw
  712. ):
  713. return tuple([clone(clause, **kw) for clause in element])
  714. def visit_clauseelement_unordered_set(
  715. self, attrname, parent, element, clone=_clone, **kw
  716. ):
  717. return {clone(clause, **kw) for clause in element}
  718. def visit_clauseelement_tuples(
  719. self, attrname, parent, element, clone=_clone, **kw
  720. ):
  721. return [
  722. tuple(clone(tup_elem, **kw) for tup_elem in elem)
  723. for elem in element
  724. ]
  725. def visit_string_clauseelement_dict(
  726. self, attrname, parent, element, clone=_clone, **kw
  727. ):
  728. return dict(
  729. (key, clone(value, **kw)) for key, value in element.items()
  730. )
  731. def visit_setup_join_tuple(
  732. self, attrname, parent, element, clone=_clone, **kw
  733. ):
  734. return tuple(
  735. (
  736. clone(target, **kw) if target is not None else None,
  737. clone(onclause, **kw) if onclause is not None else None,
  738. clone(from_, **kw) if from_ is not None else None,
  739. flags,
  740. )
  741. for (target, onclause, from_, flags) in element
  742. )
  743. def visit_memoized_select_entities(self, attrname, parent, element, **kw):
  744. return self.visit_clauseelement_tuple(attrname, parent, element, **kw)
  745. def visit_dml_ordered_values(
  746. self, attrname, parent, element, clone=_clone, **kw
  747. ):
  748. # sequence of 2-tuples
  749. return [
  750. (
  751. clone(key, **kw)
  752. if hasattr(key, "__clause_element__")
  753. else key,
  754. clone(value, **kw),
  755. )
  756. for key, value in element
  757. ]
  758. def visit_dml_values(self, attrname, parent, element, clone=_clone, **kw):
  759. return {
  760. (
  761. clone(key, **kw) if hasattr(key, "__clause_element__") else key
  762. ): clone(value, **kw)
  763. for key, value in element.items()
  764. }
  765. def visit_dml_multi_values(
  766. self, attrname, parent, element, clone=_clone, **kw
  767. ):
  768. # sequence of sequences, each sequence contains a list/dict/tuple
  769. def copy(elem):
  770. if isinstance(elem, (list, tuple)):
  771. return [
  772. clone(value, **kw)
  773. if hasattr(value, "__clause_element__")
  774. else value
  775. for value in elem
  776. ]
  777. elif isinstance(elem, dict):
  778. return {
  779. (
  780. clone(key, **kw)
  781. if hasattr(key, "__clause_element__")
  782. else key
  783. ): (
  784. clone(value, **kw)
  785. if hasattr(value, "__clause_element__")
  786. else value
  787. )
  788. for key, value in elem.items()
  789. }
  790. else:
  791. # TODO: use abc classes
  792. assert False
  793. return [
  794. [copy(sub_element) for sub_element in sequence]
  795. for sequence in element
  796. ]
  797. def visit_propagate_attrs(
  798. self, attrname, parent, element, clone=_clone, **kw
  799. ):
  800. return element
  801. _copy_internals = _CopyInternals()
  802. def _flatten_clauseelement(element):
  803. while hasattr(element, "__clause_element__") and not getattr(
  804. element, "is_clause_element", False
  805. ):
  806. element = element.__clause_element__()
  807. return element
  808. class _GetChildren(InternalTraversal):
  809. """Generate a _children_traversal internal traversal dispatch for classes
  810. with a _traverse_internals collection."""
  811. def visit_has_cache_key(self, element, **kw):
  812. # the GetChildren traversal refers explicitly to ClauseElement
  813. # structures. Within these, a plain HasCacheKey is not a
  814. # ClauseElement, so don't include these.
  815. return ()
  816. def visit_clauseelement(self, element, **kw):
  817. return (element,)
  818. def visit_clauseelement_list(self, element, **kw):
  819. return element
  820. def visit_clauseelement_tuple(self, element, **kw):
  821. return element
  822. def visit_clauseelement_tuples(self, element, **kw):
  823. return itertools.chain.from_iterable(element)
  824. def visit_fromclause_canonical_column_collection(self, element, **kw):
  825. return ()
  826. def visit_string_clauseelement_dict(self, element, **kw):
  827. return element.values()
  828. def visit_fromclause_ordered_set(self, element, **kw):
  829. return element
  830. def visit_clauseelement_unordered_set(self, element, **kw):
  831. return element
  832. def visit_setup_join_tuple(self, element, **kw):
  833. for (target, onclause, from_, flags) in element:
  834. if from_ is not None:
  835. yield from_
  836. if not isinstance(target, str):
  837. yield _flatten_clauseelement(target)
  838. if onclause is not None and not isinstance(onclause, str):
  839. yield _flatten_clauseelement(onclause)
  840. def visit_memoized_select_entities(self, element, **kw):
  841. return self.visit_clauseelement_tuple(element, **kw)
  842. def visit_dml_ordered_values(self, element, **kw):
  843. for k, v in element:
  844. if hasattr(k, "__clause_element__"):
  845. yield k
  846. yield v
  847. def visit_dml_values(self, element, **kw):
  848. expr_values = {k for k in element if hasattr(k, "__clause_element__")}
  849. str_values = expr_values.symmetric_difference(element)
  850. for k in sorted(str_values):
  851. yield element[k]
  852. for k in expr_values:
  853. yield k
  854. yield element[k]
  855. def visit_dml_multi_values(self, element, **kw):
  856. return ()
  857. def visit_propagate_attrs(self, element, **kw):
  858. return ()
  859. _get_children = _GetChildren()
  860. @util.preload_module("sqlalchemy.sql.elements")
  861. def _resolve_name_for_compare(element, name, anon_map, **kw):
  862. if isinstance(name, util.preloaded.sql_elements._anonymous_label):
  863. name = name.apply_map(anon_map)
  864. return name
  865. class anon_map(dict):
  866. """A map that creates new keys for missing key access.
  867. Produces an incrementing sequence given a series of unique keys.
  868. This is similar to the compiler prefix_anon_map class although simpler.
  869. Inlines the approach taken by :class:`sqlalchemy.util.PopulateDict` which
  870. is otherwise usually used for this type of operation.
  871. """
  872. def __init__(self):
  873. self.index = 0
  874. def __missing__(self, key):
  875. self[key] = val = str(self.index)
  876. self.index += 1
  877. return val
  878. class TraversalComparatorStrategy(InternalTraversal, util.MemoizedSlots):
  879. __slots__ = "stack", "cache", "anon_map"
  880. def __init__(self):
  881. self.stack = deque()
  882. self.cache = set()
  883. def _memoized_attr_anon_map(self):
  884. return (anon_map(), anon_map())
  885. def compare(self, obj1, obj2, **kw):
  886. stack = self.stack
  887. cache = self.cache
  888. compare_annotations = kw.get("compare_annotations", False)
  889. stack.append((obj1, obj2))
  890. while stack:
  891. left, right = stack.popleft()
  892. if left is right:
  893. continue
  894. elif left is None or right is None:
  895. # we know they are different so no match
  896. return False
  897. elif (left, right) in cache:
  898. continue
  899. cache.add((left, right))
  900. visit_name = left.__visit_name__
  901. if visit_name != right.__visit_name__:
  902. return False
  903. meth = getattr(self, "compare_%s" % visit_name, None)
  904. if meth:
  905. attributes_compared = meth(left, right, **kw)
  906. if attributes_compared is COMPARE_FAILED:
  907. return False
  908. elif attributes_compared is SKIP_TRAVERSE:
  909. continue
  910. # attributes_compared is returned as a list of attribute
  911. # names that were "handled" by the comparison method above.
  912. # remaining attribute names in the _traverse_internals
  913. # will be compared.
  914. else:
  915. attributes_compared = ()
  916. for (
  917. (left_attrname, left_visit_sym),
  918. (right_attrname, right_visit_sym),
  919. ) in util.zip_longest(
  920. left._traverse_internals,
  921. right._traverse_internals,
  922. fillvalue=(None, None),
  923. ):
  924. if not compare_annotations and (
  925. (left_attrname == "_annotations")
  926. or (right_attrname == "_annotations")
  927. ):
  928. continue
  929. if (
  930. left_attrname != right_attrname
  931. or left_visit_sym is not right_visit_sym
  932. ):
  933. return False
  934. elif left_attrname in attributes_compared:
  935. continue
  936. dispatch = self.dispatch(left_visit_sym)
  937. left_child = operator.attrgetter(left_attrname)(left)
  938. right_child = operator.attrgetter(right_attrname)(right)
  939. if left_child is None:
  940. if right_child is not None:
  941. return False
  942. else:
  943. continue
  944. comparison = dispatch(
  945. left_attrname, left, left_child, right, right_child, **kw
  946. )
  947. if comparison is COMPARE_FAILED:
  948. return False
  949. return True
  950. def compare_inner(self, obj1, obj2, **kw):
  951. comparator = self.__class__()
  952. return comparator.compare(obj1, obj2, **kw)
  953. def visit_has_cache_key(
  954. self, attrname, left_parent, left, right_parent, right, **kw
  955. ):
  956. if left._gen_cache_key(self.anon_map[0], []) != right._gen_cache_key(
  957. self.anon_map[1], []
  958. ):
  959. return COMPARE_FAILED
  960. def visit_propagate_attrs(
  961. self, attrname, left_parent, left, right_parent, right, **kw
  962. ):
  963. return self.compare_inner(
  964. left.get("plugin_subject", None), right.get("plugin_subject", None)
  965. )
  966. def visit_has_cache_key_list(
  967. self, attrname, left_parent, left, right_parent, right, **kw
  968. ):
  969. for l, r in util.zip_longest(left, right, fillvalue=None):
  970. if l._gen_cache_key(self.anon_map[0], []) != r._gen_cache_key(
  971. self.anon_map[1], []
  972. ):
  973. return COMPARE_FAILED
  974. def visit_executable_options(
  975. self, attrname, left_parent, left, right_parent, right, **kw
  976. ):
  977. for l, r in util.zip_longest(left, right, fillvalue=None):
  978. if (
  979. l._gen_cache_key(self.anon_map[0], [])
  980. if l._is_has_cache_key
  981. else l
  982. ) != (
  983. r._gen_cache_key(self.anon_map[1], [])
  984. if r._is_has_cache_key
  985. else r
  986. ):
  987. return COMPARE_FAILED
  988. def visit_clauseelement(
  989. self, attrname, left_parent, left, right_parent, right, **kw
  990. ):
  991. self.stack.append((left, right))
  992. def visit_fromclause_canonical_column_collection(
  993. self, attrname, left_parent, left, right_parent, right, **kw
  994. ):
  995. for lcol, rcol in util.zip_longest(left, right, fillvalue=None):
  996. self.stack.append((lcol, rcol))
  997. def visit_fromclause_derived_column_collection(
  998. self, attrname, left_parent, left, right_parent, right, **kw
  999. ):
  1000. pass
  1001. def visit_string_clauseelement_dict(
  1002. self, attrname, left_parent, left, right_parent, right, **kw
  1003. ):
  1004. for lstr, rstr in util.zip_longest(
  1005. sorted(left), sorted(right), fillvalue=None
  1006. ):
  1007. if lstr != rstr:
  1008. return COMPARE_FAILED
  1009. self.stack.append((left[lstr], right[rstr]))
  1010. def visit_clauseelement_tuples(
  1011. self, attrname, left_parent, left, right_parent, right, **kw
  1012. ):
  1013. for ltup, rtup in util.zip_longest(left, right, fillvalue=None):
  1014. if ltup is None or rtup is None:
  1015. return COMPARE_FAILED
  1016. for l, r in util.zip_longest(ltup, rtup, fillvalue=None):
  1017. self.stack.append((l, r))
  1018. def visit_clauseelement_list(
  1019. self, attrname, left_parent, left, right_parent, right, **kw
  1020. ):
  1021. for l, r in util.zip_longest(left, right, fillvalue=None):
  1022. self.stack.append((l, r))
  1023. def visit_clauseelement_tuple(
  1024. self, attrname, left_parent, left, right_parent, right, **kw
  1025. ):
  1026. for l, r in util.zip_longest(left, right, fillvalue=None):
  1027. self.stack.append((l, r))
  1028. def _compare_unordered_sequences(self, seq1, seq2, **kw):
  1029. if seq1 is None:
  1030. return seq2 is None
  1031. completed = set()
  1032. for clause in seq1:
  1033. for other_clause in set(seq2).difference(completed):
  1034. if self.compare_inner(clause, other_clause, **kw):
  1035. completed.add(other_clause)
  1036. break
  1037. return len(completed) == len(seq1) == len(seq2)
  1038. def visit_clauseelement_unordered_set(
  1039. self, attrname, left_parent, left, right_parent, right, **kw
  1040. ):
  1041. return self._compare_unordered_sequences(left, right, **kw)
  1042. def visit_fromclause_ordered_set(
  1043. self, attrname, left_parent, left, right_parent, right, **kw
  1044. ):
  1045. for l, r in util.zip_longest(left, right, fillvalue=None):
  1046. self.stack.append((l, r))
  1047. def visit_string(
  1048. self, attrname, left_parent, left, right_parent, right, **kw
  1049. ):
  1050. return left == right
  1051. def visit_string_list(
  1052. self, attrname, left_parent, left, right_parent, right, **kw
  1053. ):
  1054. return left == right
  1055. def visit_anon_name(
  1056. self, attrname, left_parent, left, right_parent, right, **kw
  1057. ):
  1058. return _resolve_name_for_compare(
  1059. left_parent, left, self.anon_map[0], **kw
  1060. ) == _resolve_name_for_compare(
  1061. right_parent, right, self.anon_map[1], **kw
  1062. )
  1063. def visit_boolean(
  1064. self, attrname, left_parent, left, right_parent, right, **kw
  1065. ):
  1066. return left == right
  1067. def visit_operator(
  1068. self, attrname, left_parent, left, right_parent, right, **kw
  1069. ):
  1070. return left is right
  1071. def visit_type(
  1072. self, attrname, left_parent, left, right_parent, right, **kw
  1073. ):
  1074. return left._compare_type_affinity(right)
  1075. def visit_plain_dict(
  1076. self, attrname, left_parent, left, right_parent, right, **kw
  1077. ):
  1078. return left == right
  1079. def visit_dialect_options(
  1080. self, attrname, left_parent, left, right_parent, right, **kw
  1081. ):
  1082. return left == right
  1083. def visit_annotations_key(
  1084. self, attrname, left_parent, left, right_parent, right, **kw
  1085. ):
  1086. if left and right:
  1087. return (
  1088. left_parent._annotations_cache_key
  1089. == right_parent._annotations_cache_key
  1090. )
  1091. else:
  1092. return left == right
  1093. def visit_with_context_options(
  1094. self, attrname, left_parent, left, right_parent, right, **kw
  1095. ):
  1096. return tuple((fn.__code__, c_key) for fn, c_key in left) == tuple(
  1097. (fn.__code__, c_key) for fn, c_key in right
  1098. )
  1099. def visit_plain_obj(
  1100. self, attrname, left_parent, left, right_parent, right, **kw
  1101. ):
  1102. return left == right
  1103. def visit_named_ddl_element(
  1104. self, attrname, left_parent, left, right_parent, right, **kw
  1105. ):
  1106. if left is None:
  1107. if right is not None:
  1108. return COMPARE_FAILED
  1109. return left.name == right.name
  1110. def visit_prefix_sequence(
  1111. self, attrname, left_parent, left, right_parent, right, **kw
  1112. ):
  1113. for (l_clause, l_str), (r_clause, r_str) in util.zip_longest(
  1114. left, right, fillvalue=(None, None)
  1115. ):
  1116. if l_str != r_str:
  1117. return COMPARE_FAILED
  1118. else:
  1119. self.stack.append((l_clause, r_clause))
  1120. def visit_setup_join_tuple(
  1121. self, attrname, left_parent, left, right_parent, right, **kw
  1122. ):
  1123. # TODO: look at attrname for "legacy_join" and use different structure
  1124. for (
  1125. (l_target, l_onclause, l_from, l_flags),
  1126. (r_target, r_onclause, r_from, r_flags),
  1127. ) in util.zip_longest(left, right, fillvalue=(None, None, None, None)):
  1128. if l_flags != r_flags:
  1129. return COMPARE_FAILED
  1130. self.stack.append((l_target, r_target))
  1131. self.stack.append((l_onclause, r_onclause))
  1132. self.stack.append((l_from, r_from))
  1133. def visit_memoized_select_entities(
  1134. self, attrname, left_parent, left, right_parent, right, **kw
  1135. ):
  1136. return self.visit_clauseelement_tuple(
  1137. attrname, left_parent, left, right_parent, right, **kw
  1138. )
  1139. def visit_table_hint_list(
  1140. self, attrname, left_parent, left, right_parent, right, **kw
  1141. ):
  1142. left_keys = sorted(left, key=lambda elem: (elem[0].fullname, elem[1]))
  1143. right_keys = sorted(
  1144. right, key=lambda elem: (elem[0].fullname, elem[1])
  1145. )
  1146. for (ltable, ldialect), (rtable, rdialect) in util.zip_longest(
  1147. left_keys, right_keys, fillvalue=(None, None)
  1148. ):
  1149. if ldialect != rdialect:
  1150. return COMPARE_FAILED
  1151. elif left[(ltable, ldialect)] != right[(rtable, rdialect)]:
  1152. return COMPARE_FAILED
  1153. else:
  1154. self.stack.append((ltable, rtable))
  1155. def visit_statement_hint_list(
  1156. self, attrname, left_parent, left, right_parent, right, **kw
  1157. ):
  1158. return left == right
  1159. def visit_unknown_structure(
  1160. self, attrname, left_parent, left, right_parent, right, **kw
  1161. ):
  1162. raise NotImplementedError()
  1163. def visit_dml_ordered_values(
  1164. self, attrname, left_parent, left, right_parent, right, **kw
  1165. ):
  1166. # sequence of tuple pairs
  1167. for (lk, lv), (rk, rv) in util.zip_longest(
  1168. left, right, fillvalue=(None, None)
  1169. ):
  1170. if not self._compare_dml_values_or_ce(lk, rk, **kw):
  1171. return COMPARE_FAILED
  1172. def _compare_dml_values_or_ce(self, lv, rv, **kw):
  1173. lvce = hasattr(lv, "__clause_element__")
  1174. rvce = hasattr(rv, "__clause_element__")
  1175. if lvce != rvce:
  1176. return False
  1177. elif lvce and not self.compare_inner(lv, rv, **kw):
  1178. return False
  1179. elif not lvce and lv != rv:
  1180. return False
  1181. elif not self.compare_inner(lv, rv, **kw):
  1182. return False
  1183. return True
  1184. def visit_dml_values(
  1185. self, attrname, left_parent, left, right_parent, right, **kw
  1186. ):
  1187. if left is None or right is None or len(left) != len(right):
  1188. return COMPARE_FAILED
  1189. if isinstance(left, collections_abc.Sequence):
  1190. for lv, rv in zip(left, right):
  1191. if not self._compare_dml_values_or_ce(lv, rv, **kw):
  1192. return COMPARE_FAILED
  1193. elif isinstance(right, collections_abc.Sequence):
  1194. return COMPARE_FAILED
  1195. elif py37:
  1196. # dictionaries guaranteed to support insert ordering in
  1197. # py37 so that we can compare the keys in order. without
  1198. # this, we can't compare SQL expression keys because we don't
  1199. # know which key is which
  1200. for (lk, lv), (rk, rv) in zip(left.items(), right.items()):
  1201. if not self._compare_dml_values_or_ce(lk, rk, **kw):
  1202. return COMPARE_FAILED
  1203. if not self._compare_dml_values_or_ce(lv, rv, **kw):
  1204. return COMPARE_FAILED
  1205. else:
  1206. for lk in left:
  1207. lv = left[lk]
  1208. if lk not in right:
  1209. return COMPARE_FAILED
  1210. rv = right[lk]
  1211. if not self._compare_dml_values_or_ce(lv, rv, **kw):
  1212. return COMPARE_FAILED
  1213. def visit_dml_multi_values(
  1214. self, attrname, left_parent, left, right_parent, right, **kw
  1215. ):
  1216. for lseq, rseq in util.zip_longest(left, right, fillvalue=None):
  1217. if lseq is None or rseq is None:
  1218. return COMPARE_FAILED
  1219. for ld, rd in util.zip_longest(lseq, rseq, fillvalue=None):
  1220. if (
  1221. self.visit_dml_values(
  1222. attrname, left_parent, ld, right_parent, rd, **kw
  1223. )
  1224. is COMPARE_FAILED
  1225. ):
  1226. return COMPARE_FAILED
  1227. def compare_clauselist(self, left, right, **kw):
  1228. if left.operator is right.operator:
  1229. if operators.is_associative(left.operator):
  1230. if self._compare_unordered_sequences(
  1231. left.clauses, right.clauses, **kw
  1232. ):
  1233. return ["operator", "clauses"]
  1234. else:
  1235. return COMPARE_FAILED
  1236. else:
  1237. return ["operator"]
  1238. else:
  1239. return COMPARE_FAILED
  1240. def compare_binary(self, left, right, **kw):
  1241. if left.operator == right.operator:
  1242. if operators.is_commutative(left.operator):
  1243. if (
  1244. self.compare_inner(left.left, right.left, **kw)
  1245. and self.compare_inner(left.right, right.right, **kw)
  1246. ) or (
  1247. self.compare_inner(left.left, right.right, **kw)
  1248. and self.compare_inner(left.right, right.left, **kw)
  1249. ):
  1250. return ["operator", "negate", "left", "right"]
  1251. else:
  1252. return COMPARE_FAILED
  1253. else:
  1254. return ["operator", "negate"]
  1255. else:
  1256. return COMPARE_FAILED
  1257. def compare_bindparam(self, left, right, **kw):
  1258. compare_keys = kw.pop("compare_keys", True)
  1259. compare_values = kw.pop("compare_values", True)
  1260. if compare_values:
  1261. omit = []
  1262. else:
  1263. # this means, "skip these, we already compared"
  1264. omit = ["callable", "value"]
  1265. if not compare_keys:
  1266. omit.append("key")
  1267. return omit
  1268. class ColIdentityComparatorStrategy(TraversalComparatorStrategy):
  1269. def compare_column_element(
  1270. self, left, right, use_proxies=True, equivalents=(), **kw
  1271. ):
  1272. """Compare ColumnElements using proxies and equivalent collections.
  1273. This is a comparison strategy specific to the ORM.
  1274. """
  1275. to_compare = (right,)
  1276. if equivalents and right in equivalents:
  1277. to_compare = equivalents[right].union(to_compare)
  1278. for oth in to_compare:
  1279. if use_proxies and left.shares_lineage(oth):
  1280. return SKIP_TRAVERSE
  1281. elif hash(left) == hash(right):
  1282. return SKIP_TRAVERSE
  1283. else:
  1284. return COMPARE_FAILED
  1285. def compare_column(self, left, right, **kw):
  1286. return self.compare_column_element(left, right, **kw)
  1287. def compare_label(self, left, right, **kw):
  1288. return self.compare_column_element(left, right, **kw)
  1289. def compare_table(self, left, right, **kw):
  1290. # tables compare on identity, since it's not really feasible to
  1291. # compare them column by column with the above rules
  1292. return SKIP_TRAVERSE if left is right else COMPARE_FAILED