lambdas.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. # sql/lambdas.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. import inspect
  8. import itertools
  9. import operator
  10. import sys
  11. import types
  12. import weakref
  13. from . import coercions
  14. from . import elements
  15. from . import roles
  16. from . import schema
  17. from . import traversals
  18. from . import type_api
  19. from . import visitors
  20. from .base import _clone
  21. from .base import Options
  22. from .operators import ColumnOperators
  23. from .. import exc
  24. from .. import inspection
  25. from .. import util
  26. from ..util import collections_abc
  27. from ..util import compat
  28. _closure_per_cache_key = util.LRUCache(1000)
  29. class LambdaOptions(Options):
  30. enable_tracking = True
  31. track_closure_variables = True
  32. track_on = None
  33. global_track_bound_values = True
  34. track_bound_values = True
  35. lambda_cache = None
  36. def lambda_stmt(
  37. lmb,
  38. enable_tracking=True,
  39. track_closure_variables=True,
  40. track_on=None,
  41. global_track_bound_values=True,
  42. track_bound_values=True,
  43. lambda_cache=None,
  44. ):
  45. """Produce a SQL statement that is cached as a lambda.
  46. The Python code object within the lambda is scanned for both Python
  47. literals that will become bound parameters as well as closure variables
  48. that refer to Core or ORM constructs that may vary. The lambda itself
  49. will be invoked only once per particular set of constructs detected.
  50. E.g.::
  51. from sqlalchemy import lambda_stmt
  52. stmt = lambda_stmt(lambda: table.select())
  53. stmt += lambda s: s.where(table.c.id == 5)
  54. result = connection.execute(stmt)
  55. The object returned is an instance of :class:`_sql.StatementLambdaElement`.
  56. .. versionadded:: 1.4
  57. :param lmb: a Python function, typically a lambda, which takes no arguments
  58. and returns a SQL expression construct
  59. :param enable_tracking: when False, all scanning of the given lambda for
  60. changes in closure variables or bound parameters is disabled. Use for
  61. a lambda that produces the identical results in all cases with no
  62. parameterization.
  63. :param track_closure_variables: when False, changes in closure variables
  64. within the lambda will not be scanned. Use for a lambda where the
  65. state of its closure variables will never change the SQL structure
  66. returned by the lambda.
  67. :param track_bound_values: when False, bound parameter tracking will
  68. be disabled for the given lambda. Use for a lambda that either does
  69. not produce any bound values, or where the initial bound values never
  70. change.
  71. :param global_track_bound_values: when False, bound parameter tracking
  72. will be disabled for the entire statement including additional links
  73. added via the :meth:`_sql.StatementLambdaElement.add_criteria` method.
  74. :param lambda_cache: a dictionary or other mapping-like object where
  75. information about the lambda's Python code as well as the tracked closure
  76. variables in the lambda itself will be stored. Defaults
  77. to a global LRU cache. This cache is independent of the "compiled_cache"
  78. used by the :class:`_engine.Connection` object.
  79. .. seealso::
  80. :ref:`engine_lambda_caching`
  81. """
  82. return StatementLambdaElement(
  83. lmb,
  84. roles.StatementRole,
  85. LambdaOptions(
  86. enable_tracking=enable_tracking,
  87. track_on=track_on,
  88. track_closure_variables=track_closure_variables,
  89. global_track_bound_values=global_track_bound_values,
  90. track_bound_values=track_bound_values,
  91. lambda_cache=lambda_cache,
  92. ),
  93. )
  94. class LambdaElement(elements.ClauseElement):
  95. """A SQL construct where the state is stored as an un-invoked lambda.
  96. The :class:`_sql.LambdaElement` is produced transparently whenever
  97. passing lambda expressions into SQL constructs, such as::
  98. stmt = select(table).where(lambda: table.c.col == parameter)
  99. The :class:`_sql.LambdaElement` is the base of the
  100. :class:`_sql.StatementLambdaElement` which represents a full statement
  101. within a lambda.
  102. .. versionadded:: 1.4
  103. .. seealso::
  104. :ref:`engine_lambda_caching`
  105. """
  106. __visit_name__ = "lambda_element"
  107. _is_lambda_element = True
  108. _traverse_internals = [
  109. ("_resolved", visitors.InternalTraversal.dp_clauseelement)
  110. ]
  111. _transforms = ()
  112. parent_lambda = None
  113. def __repr__(self):
  114. return "%s(%r)" % (self.__class__.__name__, self.fn.__code__)
  115. def __init__(
  116. self, fn, role, opts=LambdaOptions, apply_propagate_attrs=None
  117. ):
  118. self.fn = fn
  119. self.role = role
  120. self.tracker_key = (fn.__code__,)
  121. self.opts = opts
  122. if apply_propagate_attrs is None and (role is roles.StatementRole):
  123. apply_propagate_attrs = self
  124. rec = self._retrieve_tracker_rec(fn, apply_propagate_attrs, opts)
  125. if apply_propagate_attrs is not None:
  126. propagate_attrs = rec.propagate_attrs
  127. if propagate_attrs:
  128. apply_propagate_attrs._propagate_attrs = propagate_attrs
  129. def _retrieve_tracker_rec(self, fn, apply_propagate_attrs, opts):
  130. lambda_cache = opts.lambda_cache
  131. if lambda_cache is None:
  132. lambda_cache = _closure_per_cache_key
  133. tracker_key = self.tracker_key
  134. fn = self.fn
  135. closure = fn.__closure__
  136. tracker = AnalyzedCode.get(
  137. fn,
  138. self,
  139. opts,
  140. )
  141. self._resolved_bindparams = bindparams = []
  142. if self.parent_lambda is not None:
  143. parent_closure_cache_key = self.parent_lambda.closure_cache_key
  144. else:
  145. parent_closure_cache_key = ()
  146. if parent_closure_cache_key is not traversals.NO_CACHE:
  147. anon_map = traversals.anon_map()
  148. cache_key = tuple(
  149. [
  150. getter(closure, opts, anon_map, bindparams)
  151. for getter in tracker.closure_trackers
  152. ]
  153. )
  154. if traversals.NO_CACHE not in anon_map:
  155. cache_key = parent_closure_cache_key + cache_key
  156. self.closure_cache_key = cache_key
  157. try:
  158. rec = lambda_cache[tracker_key + cache_key]
  159. except KeyError:
  160. rec = None
  161. else:
  162. cache_key = traversals.NO_CACHE
  163. rec = None
  164. else:
  165. cache_key = traversals.NO_CACHE
  166. rec = None
  167. self.closure_cache_key = cache_key
  168. if rec is None:
  169. if cache_key is not traversals.NO_CACHE:
  170. rec = AnalyzedFunction(
  171. tracker, self, apply_propagate_attrs, fn
  172. )
  173. rec.closure_bindparams = bindparams
  174. lambda_cache[tracker_key + cache_key] = rec
  175. else:
  176. rec = NonAnalyzedFunction(self._invoke_user_fn(fn))
  177. else:
  178. bindparams[:] = [
  179. orig_bind._with_value(new_bind.value, maintain_key=True)
  180. for orig_bind, new_bind in zip(
  181. rec.closure_bindparams, bindparams
  182. )
  183. ]
  184. self._rec = rec
  185. if cache_key is not traversals.NO_CACHE:
  186. if self.parent_lambda is not None:
  187. bindparams[:0] = self.parent_lambda._resolved_bindparams
  188. lambda_element = self
  189. while lambda_element is not None:
  190. rec = lambda_element._rec
  191. if rec.bindparam_trackers:
  192. tracker_instrumented_fn = rec.tracker_instrumented_fn
  193. for tracker in rec.bindparam_trackers:
  194. tracker(
  195. lambda_element.fn,
  196. tracker_instrumented_fn,
  197. bindparams,
  198. )
  199. lambda_element = lambda_element.parent_lambda
  200. return rec
  201. def __getattr__(self, key):
  202. return getattr(self._rec.expected_expr, key)
  203. @property
  204. def _is_sequence(self):
  205. return self._rec.is_sequence
  206. @property
  207. def _select_iterable(self):
  208. if self._is_sequence:
  209. return itertools.chain.from_iterable(
  210. [element._select_iterable for element in self._resolved]
  211. )
  212. else:
  213. return self._resolved._select_iterable
  214. @property
  215. def _from_objects(self):
  216. if self._is_sequence:
  217. return itertools.chain.from_iterable(
  218. [element._from_objects for element in self._resolved]
  219. )
  220. else:
  221. return self._resolved._from_objects
  222. def _param_dict(self):
  223. return {b.key: b.value for b in self._resolved_bindparams}
  224. def _setup_binds_for_tracked_expr(self, expr):
  225. bindparam_lookup = {b.key: b for b in self._resolved_bindparams}
  226. def replace(thing):
  227. if isinstance(thing, elements.BindParameter):
  228. if thing.key in bindparam_lookup:
  229. bind = bindparam_lookup[thing.key]
  230. if thing.expanding:
  231. bind.expanding = True
  232. bind.expand_op = thing.expand_op
  233. bind.type = thing.type
  234. return bind
  235. if self._rec.is_sequence:
  236. expr = [
  237. visitors.replacement_traverse(sub_expr, {}, replace)
  238. for sub_expr in expr
  239. ]
  240. elif getattr(expr, "is_clause_element", False):
  241. expr = visitors.replacement_traverse(expr, {}, replace)
  242. return expr
  243. def _copy_internals(
  244. self, clone=_clone, deferred_copy_internals=None, **kw
  245. ):
  246. # TODO: this needs A LOT of tests
  247. self._resolved = clone(
  248. self._resolved,
  249. deferred_copy_internals=deferred_copy_internals,
  250. **kw
  251. )
  252. @util.memoized_property
  253. def _resolved(self):
  254. expr = self._rec.expected_expr
  255. if self._resolved_bindparams:
  256. expr = self._setup_binds_for_tracked_expr(expr)
  257. return expr
  258. def _gen_cache_key(self, anon_map, bindparams):
  259. if self.closure_cache_key is traversals.NO_CACHE:
  260. anon_map[traversals.NO_CACHE] = True
  261. return None
  262. cache_key = (
  263. self.fn.__code__,
  264. self.__class__,
  265. ) + self.closure_cache_key
  266. parent = self.parent_lambda
  267. while parent is not None:
  268. cache_key = (
  269. (parent.fn.__code__,) + parent.closure_cache_key + cache_key
  270. )
  271. parent = parent.parent_lambda
  272. if self._resolved_bindparams:
  273. bindparams.extend(self._resolved_bindparams)
  274. return cache_key
  275. def _invoke_user_fn(self, fn, *arg):
  276. return fn()
  277. class DeferredLambdaElement(LambdaElement):
  278. """A LambdaElement where the lambda accepts arguments and is
  279. invoked within the compile phase with special context.
  280. This lambda doesn't normally produce its real SQL expression outside of the
  281. compile phase. It is passed a fixed set of initial arguments
  282. so that it can generate a sample expression.
  283. """
  284. def __init__(self, fn, role, opts=LambdaOptions, lambda_args=()):
  285. self.lambda_args = lambda_args
  286. super(DeferredLambdaElement, self).__init__(fn, role, opts)
  287. def _invoke_user_fn(self, fn, *arg):
  288. return fn(*self.lambda_args)
  289. def _resolve_with_args(self, *lambda_args):
  290. tracker_fn = self._rec.tracker_instrumented_fn
  291. expr = tracker_fn(*lambda_args)
  292. expr = coercions.expect(self.role, expr)
  293. expr = self._setup_binds_for_tracked_expr(expr)
  294. # this validation is getting very close, but not quite, to achieving
  295. # #5767. The problem is if the base lambda uses an unnamed column
  296. # as is very common with mixins, the parameter name is different
  297. # and it produces a false positive; that is, for the documented case
  298. # that is exactly what people will be doing, it doesn't work, so
  299. # I'm not really sure how to handle this right now.
  300. # expected_binds = [
  301. # b._orig_key
  302. # for b in self._rec.expr._generate_cache_key()[1]
  303. # if b.required
  304. # ]
  305. # got_binds = [
  306. # b._orig_key for b in expr._generate_cache_key()[1] if b.required
  307. # ]
  308. # if expected_binds != got_binds:
  309. # raise exc.InvalidRequestError(
  310. # "Lambda callable at %s produced a different set of bound "
  311. # "parameters than its original run: %s"
  312. # % (self.fn.__code__, ", ".join(got_binds))
  313. # )
  314. # TODO: TEST TEST TEST, this is very out there
  315. for deferred_copy_internals in self._transforms:
  316. expr = deferred_copy_internals(expr)
  317. return expr
  318. def _copy_internals(
  319. self, clone=_clone, deferred_copy_internals=None, **kw
  320. ):
  321. super(DeferredLambdaElement, self)._copy_internals(
  322. clone=clone,
  323. deferred_copy_internals=deferred_copy_internals, # **kw
  324. opts=kw,
  325. )
  326. # TODO: A LOT A LOT of tests. for _resolve_with_args, we don't know
  327. # our expression yet. so hold onto the replacement
  328. if deferred_copy_internals:
  329. self._transforms += (deferred_copy_internals,)
  330. class StatementLambdaElement(roles.AllowsLambdaRole, LambdaElement):
  331. """Represent a composable SQL statement as a :class:`_sql.LambdaElement`.
  332. The :class:`_sql.StatementLambdaElement` is constructed using the
  333. :func:`_sql.lambda_stmt` function::
  334. from sqlalchemy import lambda_stmt
  335. stmt = lambda_stmt(lambda: select(table))
  336. Once constructed, additional criteria can be built onto the statement
  337. by adding subsequent lambdas, which accept the existing statement
  338. object as a single parameter::
  339. stmt += lambda s: s.where(table.c.col == parameter)
  340. .. versionadded:: 1.4
  341. .. seealso::
  342. :ref:`engine_lambda_caching`
  343. """
  344. def __add__(self, other):
  345. return self.add_criteria(other)
  346. def add_criteria(
  347. self,
  348. other,
  349. enable_tracking=True,
  350. track_on=None,
  351. track_closure_variables=True,
  352. track_bound_values=True,
  353. ):
  354. """Add new criteria to this :class:`_sql.StatementLambdaElement`.
  355. E.g.::
  356. >>> def my_stmt(parameter):
  357. ... stmt = lambda_stmt(
  358. ... lambda: select(table.c.x, table.c.y),
  359. ... )
  360. ... stmt = stmt.add_criteria(
  361. ... lambda: table.c.x > parameter
  362. ... )
  363. ... return stmt
  364. The :meth:`_sql.StatementLambdaElement.add_criteria` method is
  365. equivalent to using the Python addition operator to add a new
  366. lambda, except that additional arguments may be added including
  367. ``track_closure_values`` and ``track_on``::
  368. >>> def my_stmt(self, foo):
  369. ... stmt = lambda_stmt(
  370. ... lambda: select(func.max(foo.x, foo.y)),
  371. ... track_closure_variables=False
  372. ... )
  373. ... stmt = stmt.add_criteria(
  374. ... lambda: self.where_criteria,
  375. ... track_on=[self]
  376. ... )
  377. ... return stmt
  378. See :func:`_sql.lambda_stmt` for a description of the parameters
  379. accepted.
  380. """
  381. opts = self.opts + dict(
  382. enable_tracking=enable_tracking,
  383. track_closure_variables=track_closure_variables,
  384. global_track_bound_values=self.opts.global_track_bound_values,
  385. track_on=track_on,
  386. track_bound_values=track_bound_values,
  387. )
  388. return LinkedLambdaElement(other, parent_lambda=self, opts=opts)
  389. def _execute_on_connection(
  390. self, connection, multiparams, params, execution_options
  391. ):
  392. if self._rec.expected_expr.supports_execution:
  393. return connection._execute_clauseelement(
  394. self, multiparams, params, execution_options
  395. )
  396. else:
  397. raise exc.ObjectNotExecutableError(self)
  398. @property
  399. def _with_options(self):
  400. return self._rec.expected_expr._with_options
  401. @property
  402. def _effective_plugin_target(self):
  403. return self._rec.expected_expr._effective_plugin_target
  404. @property
  405. def _execution_options(self):
  406. return self._rec.expected_expr._execution_options
  407. def spoil(self):
  408. """Return a new :class:`.StatementLambdaElement` that will run
  409. all lambdas unconditionally each time.
  410. """
  411. return NullLambdaStatement(self.fn())
  412. class NullLambdaStatement(roles.AllowsLambdaRole, elements.ClauseElement):
  413. """Provides the :class:`.StatementLambdaElement` API but does not
  414. cache or analyze lambdas.
  415. the lambdas are instead invoked immediately.
  416. The intended use is to isolate issues that may arise when using
  417. lambda statements.
  418. """
  419. __visit_name__ = "lambda_element"
  420. _is_lambda_element = True
  421. _traverse_internals = [
  422. ("_resolved", visitors.InternalTraversal.dp_clauseelement)
  423. ]
  424. def __init__(self, statement):
  425. self._resolved = statement
  426. self._propagate_attrs = statement._propagate_attrs
  427. def __getattr__(self, key):
  428. return getattr(self._resolved, key)
  429. def __add__(self, other):
  430. statement = other(self._resolved)
  431. return NullLambdaStatement(statement)
  432. def add_criteria(self, other, **kw):
  433. statement = other(self._resolved)
  434. return NullLambdaStatement(statement)
  435. def _execute_on_connection(
  436. self, connection, multiparams, params, execution_options
  437. ):
  438. if self._resolved.supports_execution:
  439. return connection._execute_clauseelement(
  440. self, multiparams, params, execution_options
  441. )
  442. else:
  443. raise exc.ObjectNotExecutableError(self)
  444. class LinkedLambdaElement(StatementLambdaElement):
  445. """Represent subsequent links of a :class:`.StatementLambdaElement`."""
  446. role = None
  447. def __init__(self, fn, parent_lambda, opts):
  448. self.opts = opts
  449. self.fn = fn
  450. self.parent_lambda = parent_lambda
  451. self.tracker_key = parent_lambda.tracker_key + (fn.__code__,)
  452. self._retrieve_tracker_rec(fn, self, opts)
  453. self._propagate_attrs = parent_lambda._propagate_attrs
  454. def _invoke_user_fn(self, fn, *arg):
  455. return fn(self.parent_lambda._resolved)
  456. class AnalyzedCode(object):
  457. __slots__ = (
  458. "track_closure_variables",
  459. "track_bound_values",
  460. "bindparam_trackers",
  461. "closure_trackers",
  462. "build_py_wrappers",
  463. )
  464. _fns = weakref.WeakKeyDictionary()
  465. @classmethod
  466. def get(cls, fn, lambda_element, lambda_kw, **kw):
  467. try:
  468. # TODO: validate kw haven't changed?
  469. return cls._fns[fn.__code__]
  470. except KeyError:
  471. pass
  472. cls._fns[fn.__code__] = analyzed = AnalyzedCode(
  473. fn, lambda_element, lambda_kw, **kw
  474. )
  475. return analyzed
  476. def __init__(self, fn, lambda_element, opts):
  477. if inspect.ismethod(fn):
  478. raise exc.ArgumentError(
  479. "Method %s may not be passed as a SQL expression" % fn
  480. )
  481. closure = fn.__closure__
  482. self.track_bound_values = (
  483. opts.track_bound_values and opts.global_track_bound_values
  484. )
  485. enable_tracking = opts.enable_tracking
  486. track_on = opts.track_on
  487. track_closure_variables = opts.track_closure_variables
  488. self.track_closure_variables = track_closure_variables and not track_on
  489. # a list of callables generated from _bound_parameter_getter_*
  490. # functions. Each of these uses a PyWrapper object to retrieve
  491. # a parameter value
  492. self.bindparam_trackers = []
  493. # a list of callables generated from _cache_key_getter_* functions
  494. # these callables work to generate a cache key for the lambda
  495. # based on what's inside its closure variables.
  496. self.closure_trackers = []
  497. self.build_py_wrappers = []
  498. if enable_tracking:
  499. if track_on:
  500. self._init_track_on(track_on)
  501. self._init_globals(fn)
  502. if closure:
  503. self._init_closure(fn)
  504. self._setup_additional_closure_trackers(fn, lambda_element, opts)
  505. def _init_track_on(self, track_on):
  506. self.closure_trackers.extend(
  507. self._cache_key_getter_track_on(idx, elem)
  508. for idx, elem in enumerate(track_on)
  509. )
  510. def _init_globals(self, fn):
  511. build_py_wrappers = self.build_py_wrappers
  512. bindparam_trackers = self.bindparam_trackers
  513. track_bound_values = self.track_bound_values
  514. for name in fn.__code__.co_names:
  515. if name not in fn.__globals__:
  516. continue
  517. _bound_value = self._roll_down_to_literal(fn.__globals__[name])
  518. if coercions._deep_is_literal(_bound_value):
  519. build_py_wrappers.append((name, None))
  520. if track_bound_values:
  521. bindparam_trackers.append(
  522. self._bound_parameter_getter_func_globals(name)
  523. )
  524. def _init_closure(self, fn):
  525. build_py_wrappers = self.build_py_wrappers
  526. closure = fn.__closure__
  527. track_bound_values = self.track_bound_values
  528. track_closure_variables = self.track_closure_variables
  529. bindparam_trackers = self.bindparam_trackers
  530. closure_trackers = self.closure_trackers
  531. for closure_index, (fv, cell) in enumerate(
  532. zip(fn.__code__.co_freevars, closure)
  533. ):
  534. _bound_value = self._roll_down_to_literal(cell.cell_contents)
  535. if coercions._deep_is_literal(_bound_value):
  536. build_py_wrappers.append((fv, closure_index))
  537. if track_bound_values:
  538. bindparam_trackers.append(
  539. self._bound_parameter_getter_func_closure(
  540. fv, closure_index
  541. )
  542. )
  543. else:
  544. # for normal cell contents, add them to a list that
  545. # we can compare later when we get new lambdas. if
  546. # any identities have changed, then we will
  547. # recalculate the whole lambda and run it again.
  548. if track_closure_variables:
  549. closure_trackers.append(
  550. self._cache_key_getter_closure_variable(
  551. fn, fv, closure_index, cell.cell_contents
  552. )
  553. )
  554. def _setup_additional_closure_trackers(self, fn, lambda_element, opts):
  555. # an additional step is to actually run the function, then
  556. # go through the PyWrapper objects that were set up to catch a bound
  557. # parameter. then if they *didn't* make a param, oh they're another
  558. # object in the closure we have to track for our cache key. so
  559. # create trackers to catch those.
  560. analyzed_function = AnalyzedFunction(
  561. self,
  562. lambda_element,
  563. None,
  564. fn,
  565. )
  566. closure_trackers = self.closure_trackers
  567. for pywrapper in analyzed_function.closure_pywrappers:
  568. if not pywrapper._sa__has_param:
  569. closure_trackers.append(
  570. self._cache_key_getter_tracked_literal(fn, pywrapper)
  571. )
  572. @classmethod
  573. def _roll_down_to_literal(cls, element):
  574. is_clause_element = hasattr(element, "__clause_element__")
  575. if is_clause_element:
  576. while not isinstance(
  577. element, (elements.ClauseElement, schema.SchemaItem, type)
  578. ):
  579. try:
  580. element = element.__clause_element__()
  581. except AttributeError:
  582. break
  583. if not is_clause_element:
  584. insp = inspection.inspect(element, raiseerr=False)
  585. if insp is not None:
  586. try:
  587. return insp.__clause_element__()
  588. except AttributeError:
  589. return insp
  590. # TODO: should we coerce consts None/True/False here?
  591. return element
  592. else:
  593. return element
  594. def _bound_parameter_getter_func_globals(self, name):
  595. """Return a getter that will extend a list of bound parameters
  596. with new entries from the ``__globals__`` collection of a particular
  597. lambda.
  598. """
  599. def extract_parameter_value(
  600. current_fn, tracker_instrumented_fn, result
  601. ):
  602. wrapper = tracker_instrumented_fn.__globals__[name]
  603. object.__getattribute__(wrapper, "_extract_bound_parameters")(
  604. current_fn.__globals__[name], result
  605. )
  606. return extract_parameter_value
  607. def _bound_parameter_getter_func_closure(self, name, closure_index):
  608. """Return a getter that will extend a list of bound parameters
  609. with new entries from the ``__closure__`` collection of a particular
  610. lambda.
  611. """
  612. def extract_parameter_value(
  613. current_fn, tracker_instrumented_fn, result
  614. ):
  615. wrapper = tracker_instrumented_fn.__closure__[
  616. closure_index
  617. ].cell_contents
  618. object.__getattribute__(wrapper, "_extract_bound_parameters")(
  619. current_fn.__closure__[closure_index].cell_contents, result
  620. )
  621. return extract_parameter_value
  622. def _cache_key_getter_track_on(self, idx, elem):
  623. """Return a getter that will extend a cache key with new entries
  624. from the "track_on" parameter passed to a :class:`.LambdaElement`.
  625. """
  626. if isinstance(elem, tuple):
  627. # tuple must contain hascachekey elements
  628. def get(closure, opts, anon_map, bindparams):
  629. return tuple(
  630. tup_elem._gen_cache_key(anon_map, bindparams)
  631. for tup_elem in opts.track_on[idx]
  632. )
  633. elif isinstance(elem, traversals.HasCacheKey):
  634. def get(closure, opts, anon_map, bindparams):
  635. return opts.track_on[idx]._gen_cache_key(anon_map, bindparams)
  636. else:
  637. def get(closure, opts, anon_map, bindparams):
  638. return opts.track_on[idx]
  639. return get
  640. def _cache_key_getter_closure_variable(
  641. self,
  642. fn,
  643. variable_name,
  644. idx,
  645. cell_contents,
  646. use_clause_element=False,
  647. use_inspect=False,
  648. ):
  649. """Return a getter that will extend a cache key with new entries
  650. from the ``__closure__`` collection of a particular lambda.
  651. """
  652. if isinstance(cell_contents, traversals.HasCacheKey):
  653. def get(closure, opts, anon_map, bindparams):
  654. obj = closure[idx].cell_contents
  655. if use_inspect:
  656. obj = inspection.inspect(obj)
  657. elif use_clause_element:
  658. while hasattr(obj, "__clause_element__"):
  659. if not getattr(obj, "is_clause_element", False):
  660. obj = obj.__clause_element__()
  661. return obj._gen_cache_key(anon_map, bindparams)
  662. elif isinstance(cell_contents, types.FunctionType):
  663. def get(closure, opts, anon_map, bindparams):
  664. return closure[idx].cell_contents.__code__
  665. elif isinstance(cell_contents, collections_abc.Sequence):
  666. def get(closure, opts, anon_map, bindparams):
  667. contents = closure[idx].cell_contents
  668. try:
  669. return tuple(
  670. elem._gen_cache_key(anon_map, bindparams)
  671. for elem in contents
  672. )
  673. except AttributeError as ae:
  674. self._raise_for_uncacheable_closure_variable(
  675. variable_name, fn, from_=ae
  676. )
  677. else:
  678. # if the object is a mapped class or aliased class, or some
  679. # other object in the ORM realm of things like that, imitate
  680. # the logic used in coercions.expect() to roll it down to the
  681. # SQL element
  682. element = cell_contents
  683. is_clause_element = False
  684. while hasattr(element, "__clause_element__"):
  685. is_clause_element = True
  686. if not getattr(element, "is_clause_element", False):
  687. element = element.__clause_element__()
  688. else:
  689. break
  690. if not is_clause_element:
  691. insp = inspection.inspect(element, raiseerr=False)
  692. if insp is not None:
  693. return self._cache_key_getter_closure_variable(
  694. fn, variable_name, idx, insp, use_inspect=True
  695. )
  696. else:
  697. return self._cache_key_getter_closure_variable(
  698. fn, variable_name, idx, element, use_clause_element=True
  699. )
  700. self._raise_for_uncacheable_closure_variable(variable_name, fn)
  701. return get
  702. def _raise_for_uncacheable_closure_variable(
  703. self, variable_name, fn, from_=None
  704. ):
  705. util.raise_(
  706. exc.InvalidRequestError(
  707. "Closure variable named '%s' inside of lambda callable %s "
  708. "does not refer to a cacheable SQL element, and also does not "
  709. "appear to be serving as a SQL literal bound value based on "
  710. "the default "
  711. "SQL expression returned by the function. This variable "
  712. "needs to remain outside the scope of a SQL-generating lambda "
  713. "so that a proper cache key may be generated from the "
  714. "lambda's state. Evaluate this variable outside of the "
  715. "lambda, set track_on=[<elements>] to explicitly select "
  716. "closure elements to track, or set "
  717. "track_closure_variables=False to exclude "
  718. "closure variables from being part of the cache key."
  719. % (variable_name, fn.__code__),
  720. ),
  721. from_=from_,
  722. )
  723. def _cache_key_getter_tracked_literal(self, fn, pytracker):
  724. """Return a getter that will extend a cache key with new entries
  725. from the ``__closure__`` collection of a particular lambda.
  726. this getter differs from _cache_key_getter_closure_variable
  727. in that these are detected after the function is run, and PyWrapper
  728. objects have recorded that a particular literal value is in fact
  729. not being interpreted as a bound parameter.
  730. """
  731. elem = pytracker._sa__to_evaluate
  732. closure_index = pytracker._sa__closure_index
  733. variable_name = pytracker._sa__name
  734. return self._cache_key_getter_closure_variable(
  735. fn, variable_name, closure_index, elem
  736. )
  737. class NonAnalyzedFunction(object):
  738. __slots__ = ("expr",)
  739. closure_bindparams = None
  740. bindparam_trackers = None
  741. def __init__(self, expr):
  742. self.expr = expr
  743. @property
  744. def expected_expr(self):
  745. return self.expr
  746. class AnalyzedFunction(object):
  747. __slots__ = (
  748. "analyzed_code",
  749. "fn",
  750. "closure_pywrappers",
  751. "tracker_instrumented_fn",
  752. "expr",
  753. "bindparam_trackers",
  754. "expected_expr",
  755. "is_sequence",
  756. "propagate_attrs",
  757. "closure_bindparams",
  758. )
  759. def __init__(
  760. self,
  761. analyzed_code,
  762. lambda_element,
  763. apply_propagate_attrs,
  764. fn,
  765. ):
  766. self.analyzed_code = analyzed_code
  767. self.fn = fn
  768. self.bindparam_trackers = analyzed_code.bindparam_trackers
  769. self._instrument_and_run_function(lambda_element)
  770. self._coerce_expression(lambda_element, apply_propagate_attrs)
  771. def _instrument_and_run_function(self, lambda_element):
  772. analyzed_code = self.analyzed_code
  773. fn = self.fn
  774. self.closure_pywrappers = closure_pywrappers = []
  775. build_py_wrappers = analyzed_code.build_py_wrappers
  776. if not build_py_wrappers:
  777. self.tracker_instrumented_fn = tracker_instrumented_fn = fn
  778. self.expr = lambda_element._invoke_user_fn(tracker_instrumented_fn)
  779. else:
  780. track_closure_variables = analyzed_code.track_closure_variables
  781. closure = fn.__closure__
  782. # will form the __closure__ of the function when we rebuild it
  783. if closure:
  784. new_closure = {
  785. fv: cell.cell_contents
  786. for fv, cell in zip(fn.__code__.co_freevars, closure)
  787. }
  788. else:
  789. new_closure = {}
  790. # will form the __globals__ of the function when we rebuild it
  791. new_globals = fn.__globals__.copy()
  792. for name, closure_index in build_py_wrappers:
  793. if closure_index is not None:
  794. value = closure[closure_index].cell_contents
  795. new_closure[name] = bind = PyWrapper(
  796. fn,
  797. name,
  798. value,
  799. closure_index=closure_index,
  800. track_bound_values=(
  801. self.analyzed_code.track_bound_values
  802. ),
  803. )
  804. if track_closure_variables:
  805. closure_pywrappers.append(bind)
  806. else:
  807. value = fn.__globals__[name]
  808. new_globals[name] = bind = PyWrapper(fn, name, value)
  809. # rewrite the original fn. things that look like they will
  810. # become bound parameters are wrapped in a PyWrapper.
  811. self.tracker_instrumented_fn = (
  812. tracker_instrumented_fn
  813. ) = self._rewrite_code_obj(
  814. fn,
  815. [new_closure[name] for name in fn.__code__.co_freevars],
  816. new_globals,
  817. )
  818. # now invoke the function. This will give us a new SQL
  819. # expression, but all the places that there would be a bound
  820. # parameter, the PyWrapper in its place will give us a bind
  821. # with a predictable name we can match up later.
  822. # additionally, each PyWrapper will log that it did in fact
  823. # create a parameter, otherwise, it's some kind of Python
  824. # object in the closure and we want to track that, to make
  825. # sure it doesn't change to something else, or if it does,
  826. # that we create a different tracked function with that
  827. # variable.
  828. self.expr = lambda_element._invoke_user_fn(tracker_instrumented_fn)
  829. def _coerce_expression(self, lambda_element, apply_propagate_attrs):
  830. """Run the tracker-generated expression through coercion rules.
  831. After the user-defined lambda has been invoked to produce a statement
  832. for re-use, run it through coercion rules to both check that it's the
  833. correct type of object and also to coerce it to its useful form.
  834. """
  835. parent_lambda = lambda_element.parent_lambda
  836. expr = self.expr
  837. if parent_lambda is None:
  838. if isinstance(expr, collections_abc.Sequence):
  839. self.expected_expr = [
  840. coercions.expect(
  841. lambda_element.role,
  842. sub_expr,
  843. apply_propagate_attrs=apply_propagate_attrs,
  844. )
  845. for sub_expr in expr
  846. ]
  847. self.is_sequence = True
  848. else:
  849. self.expected_expr = coercions.expect(
  850. lambda_element.role,
  851. expr,
  852. apply_propagate_attrs=apply_propagate_attrs,
  853. )
  854. self.is_sequence = False
  855. else:
  856. self.expected_expr = expr
  857. self.is_sequence = False
  858. if apply_propagate_attrs is not None:
  859. self.propagate_attrs = apply_propagate_attrs._propagate_attrs
  860. else:
  861. self.propagate_attrs = util.EMPTY_DICT
  862. def _rewrite_code_obj(self, f, cell_values, globals_):
  863. """Return a copy of f, with a new closure and new globals
  864. yes it works in pypy :P
  865. """
  866. argrange = range(len(cell_values))
  867. code = "def make_cells():\n"
  868. if cell_values:
  869. code += " (%s) = (%s)\n" % (
  870. ", ".join("i%d" % i for i in argrange),
  871. ", ".join("o%d" % i for i in argrange),
  872. )
  873. code += " def closure():\n"
  874. code += " return %s\n" % ", ".join("i%d" % i for i in argrange)
  875. code += " return closure.__closure__"
  876. vars_ = {"o%d" % i: cell_values[i] for i in argrange}
  877. compat.exec_(code, vars_, vars_)
  878. closure = vars_["make_cells"]()
  879. func = type(f)(
  880. f.__code__, globals_, f.__name__, f.__defaults__, closure
  881. )
  882. if sys.version_info >= (3,):
  883. func.__annotations__ = f.__annotations__
  884. func.__kwdefaults__ = f.__kwdefaults__
  885. func.__doc__ = f.__doc__
  886. func.__module__ = f.__module__
  887. return func
  888. class PyWrapper(ColumnOperators):
  889. """A wrapper object that is injected into the ``__globals__`` and
  890. ``__closure__`` of a Python function.
  891. When the function is instrumented with :class:`.PyWrapper` objects, it is
  892. then invoked just once in order to set up the wrappers. We look through
  893. all the :class:`.PyWrapper` objects we made to find the ones that generated
  894. a :class:`.BindParameter` object, e.g. the expression system interpreted
  895. something as a literal. Those positions in the globals/closure are then
  896. ones that we will look at, each time a new lambda comes in that refers to
  897. the same ``__code__`` object. In this way, we keep a single version of
  898. the SQL expression that this lambda produced, without calling upon the
  899. Python function that created it more than once, unless its other closure
  900. variables have changed. The expression is then transformed to have the
  901. new bound values embedded into it.
  902. """
  903. def __init__(
  904. self,
  905. fn,
  906. name,
  907. to_evaluate,
  908. closure_index=None,
  909. getter=None,
  910. track_bound_values=True,
  911. ):
  912. self.fn = fn
  913. self._name = name
  914. self._to_evaluate = to_evaluate
  915. self._param = None
  916. self._has_param = False
  917. self._bind_paths = {}
  918. self._getter = getter
  919. self._closure_index = closure_index
  920. self.track_bound_values = track_bound_values
  921. def __call__(self, *arg, **kw):
  922. elem = object.__getattribute__(self, "_to_evaluate")
  923. value = elem(*arg, **kw)
  924. if (
  925. self._sa_track_bound_values
  926. and coercions._deep_is_literal(value)
  927. and not isinstance(
  928. # TODO: coverage where an ORM option or similar is here
  929. value,
  930. traversals.HasCacheKey,
  931. )
  932. ):
  933. name = object.__getattribute__(self, "_name")
  934. raise exc.InvalidRequestError(
  935. "Can't invoke Python callable %s() inside of lambda "
  936. "expression argument at %s; lambda SQL constructs should "
  937. "not invoke functions from closure variables to produce "
  938. "literal values since the "
  939. "lambda SQL system normally extracts bound values without "
  940. "actually "
  941. "invoking the lambda or any functions within it. Call the "
  942. "function outside of the "
  943. "lambda and assign to a local variable that is used in the "
  944. "lambda as a closure variable, or set "
  945. "track_bound_values=False if the return value of this "
  946. "function is used in some other way other than a SQL bound "
  947. "value." % (name, self._sa_fn.__code__)
  948. )
  949. else:
  950. return value
  951. def operate(self, op, *other, **kwargs):
  952. elem = object.__getattribute__(self, "__clause_element__")()
  953. return op(elem, *other, **kwargs)
  954. def reverse_operate(self, op, other, **kwargs):
  955. elem = object.__getattribute__(self, "__clause_element__")()
  956. return op(other, elem, **kwargs)
  957. def _extract_bound_parameters(self, starting_point, result_list):
  958. param = object.__getattribute__(self, "_param")
  959. if param is not None:
  960. param = param._with_value(starting_point, maintain_key=True)
  961. result_list.append(param)
  962. for pywrapper in object.__getattribute__(self, "_bind_paths").values():
  963. getter = object.__getattribute__(pywrapper, "_getter")
  964. element = getter(starting_point)
  965. pywrapper._sa__extract_bound_parameters(element, result_list)
  966. def __clause_element__(self):
  967. param = object.__getattribute__(self, "_param")
  968. to_evaluate = object.__getattribute__(self, "_to_evaluate")
  969. if param is None:
  970. name = object.__getattribute__(self, "_name")
  971. self._param = param = elements.BindParameter(
  972. name, required=False, unique=True
  973. )
  974. self._has_param = True
  975. param.type = type_api._resolve_value_to_type(to_evaluate)
  976. return param._with_value(to_evaluate, maintain_key=True)
  977. def __bool__(self):
  978. to_evaluate = object.__getattribute__(self, "_to_evaluate")
  979. return bool(to_evaluate)
  980. def __nonzero__(self):
  981. to_evaluate = object.__getattribute__(self, "_to_evaluate")
  982. return bool(to_evaluate)
  983. def __getattribute__(self, key):
  984. if key.startswith("_sa_"):
  985. return object.__getattribute__(self, key[4:])
  986. elif key in (
  987. "__clause_element__",
  988. "operate",
  989. "reverse_operate",
  990. "__class__",
  991. "__dict__",
  992. ):
  993. return object.__getattribute__(self, key)
  994. if key.startswith("__"):
  995. elem = object.__getattribute__(self, "_to_evaluate")
  996. return getattr(elem, key)
  997. else:
  998. return self._sa__add_getter(key, operator.attrgetter)
  999. def __iter__(self):
  1000. elem = object.__getattribute__(self, "_to_evaluate")
  1001. return iter(elem)
  1002. def __getitem__(self, key):
  1003. elem = object.__getattribute__(self, "_to_evaluate")
  1004. if not hasattr(elem, "__getitem__"):
  1005. raise AttributeError("__getitem__")
  1006. if isinstance(key, PyWrapper):
  1007. # TODO: coverage
  1008. raise exc.InvalidRequestError(
  1009. "Dictionary keys / list indexes inside of a cached "
  1010. "lambda must be Python literals only"
  1011. )
  1012. return self._sa__add_getter(key, operator.itemgetter)
  1013. def _add_getter(self, key, getter_fn):
  1014. bind_paths = object.__getattribute__(self, "_bind_paths")
  1015. bind_path_key = (key, getter_fn)
  1016. if bind_path_key in bind_paths:
  1017. return bind_paths[bind_path_key]
  1018. getter = getter_fn(key)
  1019. elem = object.__getattribute__(self, "_to_evaluate")
  1020. value = getter(elem)
  1021. rolled_down_value = AnalyzedCode._roll_down_to_literal(value)
  1022. if coercions._deep_is_literal(rolled_down_value):
  1023. wrapper = PyWrapper(self._sa_fn, key, value, getter=getter)
  1024. bind_paths[bind_path_key] = wrapper
  1025. return wrapper
  1026. else:
  1027. return value
  1028. @inspection._inspects(LambdaElement)
  1029. def insp(lmb):
  1030. return inspection.inspect(lmb._resolved)