You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

649 lines
20KB

  1. # sqlalchemy/ext/baked.py
  2. # Copyright (C) 2005-2021 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: http://www.opensource.org/licenses/mit-license.php
  7. """Baked query extension.
  8. Provides a creational pattern for the :class:`.query.Query` object which
  9. allows the fully constructed object, Core select statement, and string
  10. compiled result to be fully cached.
  11. """
  12. import logging
  13. from .. import exc as sa_exc
  14. from .. import util
  15. from ..orm import exc as orm_exc
  16. from ..orm import strategy_options
  17. from ..orm.query import Query
  18. from ..orm.session import Session
  19. from ..sql import func
  20. from ..sql import literal_column
  21. from ..sql import util as sql_util
  22. from ..util import collections_abc
  23. log = logging.getLogger(__name__)
  24. class Bakery(object):
  25. """Callable which returns a :class:`.BakedQuery`.
  26. This object is returned by the class method
  27. :meth:`.BakedQuery.bakery`. It exists as an object
  28. so that the "cache" can be easily inspected.
  29. .. versionadded:: 1.2
  30. """
  31. __slots__ = "cls", "cache"
  32. def __init__(self, cls_, cache):
  33. self.cls = cls_
  34. self.cache = cache
  35. def __call__(self, initial_fn, *args):
  36. return self.cls(self.cache, initial_fn, args)
  37. class BakedQuery(object):
  38. """A builder object for :class:`.query.Query` objects."""
  39. __slots__ = "steps", "_bakery", "_cache_key", "_spoiled"
  40. def __init__(self, bakery, initial_fn, args=()):
  41. self._cache_key = ()
  42. self._update_cache_key(initial_fn, args)
  43. self.steps = [initial_fn]
  44. self._spoiled = False
  45. self._bakery = bakery
  46. @classmethod
  47. def bakery(cls, size=200, _size_alert=None):
  48. """Construct a new bakery.
  49. :return: an instance of :class:`.Bakery`
  50. """
  51. return Bakery(cls, util.LRUCache(size, size_alert=_size_alert))
  52. def _clone(self):
  53. b1 = BakedQuery.__new__(BakedQuery)
  54. b1._cache_key = self._cache_key
  55. b1.steps = list(self.steps)
  56. b1._bakery = self._bakery
  57. b1._spoiled = self._spoiled
  58. return b1
  59. def _update_cache_key(self, fn, args=()):
  60. self._cache_key += (fn.__code__,) + args
  61. def __iadd__(self, other):
  62. if isinstance(other, tuple):
  63. self.add_criteria(*other)
  64. else:
  65. self.add_criteria(other)
  66. return self
  67. def __add__(self, other):
  68. if isinstance(other, tuple):
  69. return self.with_criteria(*other)
  70. else:
  71. return self.with_criteria(other)
  72. def add_criteria(self, fn, *args):
  73. """Add a criteria function to this :class:`.BakedQuery`.
  74. This is equivalent to using the ``+=`` operator to
  75. modify a :class:`.BakedQuery` in-place.
  76. """
  77. self._update_cache_key(fn, args)
  78. self.steps.append(fn)
  79. return self
  80. def with_criteria(self, fn, *args):
  81. """Add a criteria function to a :class:`.BakedQuery` cloned from this
  82. one.
  83. This is equivalent to using the ``+`` operator to
  84. produce a new :class:`.BakedQuery` with modifications.
  85. """
  86. return self._clone().add_criteria(fn, *args)
  87. def for_session(self, session):
  88. """Return a :class:`_baked.Result` object for this
  89. :class:`.BakedQuery`.
  90. This is equivalent to calling the :class:`.BakedQuery` as a
  91. Python callable, e.g. ``result = my_baked_query(session)``.
  92. """
  93. return Result(self, session)
  94. def __call__(self, session):
  95. return self.for_session(session)
  96. def spoil(self, full=False):
  97. """Cancel any query caching that will occur on this BakedQuery object.
  98. The BakedQuery can continue to be used normally, however additional
  99. creational functions will not be cached; they will be called
  100. on every invocation.
  101. This is to support the case where a particular step in constructing
  102. a baked query disqualifies the query from being cacheable, such
  103. as a variant that relies upon some uncacheable value.
  104. :param full: if False, only functions added to this
  105. :class:`.BakedQuery` object subsequent to the spoil step will be
  106. non-cached; the state of the :class:`.BakedQuery` up until
  107. this point will be pulled from the cache. If True, then the
  108. entire :class:`_query.Query` object is built from scratch each
  109. time, with all creational functions being called on each
  110. invocation.
  111. """
  112. if not full and not self._spoiled:
  113. _spoil_point = self._clone()
  114. _spoil_point._cache_key += ("_query_only",)
  115. self.steps = [_spoil_point._retrieve_baked_query]
  116. self._spoiled = True
  117. return self
  118. def _effective_key(self, session):
  119. """Return the key that actually goes into the cache dictionary for
  120. this :class:`.BakedQuery`, taking into account the given
  121. :class:`.Session`.
  122. This basically means we also will include the session's query_class,
  123. as the actual :class:`_query.Query` object is part of what's cached
  124. and needs to match the type of :class:`_query.Query` that a later
  125. session will want to use.
  126. """
  127. return self._cache_key + (session._query_cls,)
  128. def _with_lazyload_options(self, options, effective_path, cache_path=None):
  129. """Cloning version of _add_lazyload_options."""
  130. q = self._clone()
  131. q._add_lazyload_options(options, effective_path, cache_path=cache_path)
  132. return q
  133. def _add_lazyload_options(self, options, effective_path, cache_path=None):
  134. """Used by per-state lazy loaders to add options to the
  135. "lazy load" query from a parent query.
  136. Creates a cache key based on given load path and query options;
  137. if a repeatable cache key cannot be generated, the query is
  138. "spoiled" so that it won't use caching.
  139. """
  140. key = ()
  141. if not cache_path:
  142. cache_path = effective_path
  143. for opt in options:
  144. if opt._is_legacy_option or opt._is_compile_state:
  145. ck = opt._generate_cache_key()
  146. if ck is None:
  147. self.spoil(full=True)
  148. else:
  149. assert not ck[1], (
  150. "loader options with variable bound parameters "
  151. "not supported with baked queries. Please "
  152. "use new-style select() statements for cached "
  153. "ORM queries."
  154. )
  155. key += ck[0]
  156. self.add_criteria(
  157. lambda q: q._with_current_path(effective_path).options(*options),
  158. cache_path.path,
  159. key,
  160. )
  161. def _retrieve_baked_query(self, session):
  162. query = self._bakery.get(self._effective_key(session), None)
  163. if query is None:
  164. query = self._as_query(session)
  165. self._bakery[self._effective_key(session)] = query.with_session(
  166. None
  167. )
  168. return query.with_session(session)
  169. def _bake(self, session):
  170. query = self._as_query(session)
  171. query.session = None
  172. # in 1.4, this is where before_compile() event is
  173. # invoked
  174. statement = query._statement_20()
  175. # if the query is not safe to cache, we still do everything as though
  176. # we did cache it, since the receiver of _bake() assumes subqueryload
  177. # context was set up, etc.
  178. #
  179. # note also we want to cache the statement itself because this
  180. # allows the statement itself to hold onto its cache key that is
  181. # used by the Connection, which in itself is more expensive to
  182. # generate than what BakedQuery was able to provide in 1.3 and prior
  183. if statement._compile_options._bake_ok:
  184. self._bakery[self._effective_key(session)] = (
  185. query,
  186. statement,
  187. )
  188. return query, statement
  189. def to_query(self, query_or_session):
  190. """Return the :class:`_query.Query` object for use as a subquery.
  191. This method should be used within the lambda callable being used
  192. to generate a step of an enclosing :class:`.BakedQuery`. The
  193. parameter should normally be the :class:`_query.Query` object that
  194. is passed to the lambda::
  195. sub_bq = self.bakery(lambda s: s.query(User.name))
  196. sub_bq += lambda q: q.filter(
  197. User.id == Address.user_id).correlate(Address)
  198. main_bq = self.bakery(lambda s: s.query(Address))
  199. main_bq += lambda q: q.filter(
  200. sub_bq.to_query(q).exists())
  201. In the case where the subquery is used in the first callable against
  202. a :class:`.Session`, the :class:`.Session` is also accepted::
  203. sub_bq = self.bakery(lambda s: s.query(User.name))
  204. sub_bq += lambda q: q.filter(
  205. User.id == Address.user_id).correlate(Address)
  206. main_bq = self.bakery(
  207. lambda s: s.query(
  208. Address.id, sub_bq.to_query(q).scalar_subquery())
  209. )
  210. :param query_or_session: a :class:`_query.Query` object or a class
  211. :class:`.Session` object, that is assumed to be within the context
  212. of an enclosing :class:`.BakedQuery` callable.
  213. .. versionadded:: 1.3
  214. """
  215. if isinstance(query_or_session, Session):
  216. session = query_or_session
  217. elif isinstance(query_or_session, Query):
  218. session = query_or_session.session
  219. if session is None:
  220. raise sa_exc.ArgumentError(
  221. "Given Query needs to be associated with a Session"
  222. )
  223. else:
  224. raise TypeError(
  225. "Query or Session object expected, got %r."
  226. % type(query_or_session)
  227. )
  228. return self._as_query(session)
  229. def _as_query(self, session):
  230. query = self.steps[0](session)
  231. for step in self.steps[1:]:
  232. query = step(query)
  233. return query
  234. class Result(object):
  235. """Invokes a :class:`.BakedQuery` against a :class:`.Session`.
  236. The :class:`_baked.Result` object is where the actual :class:`.query.Query`
  237. object gets created, or retrieved from the cache,
  238. against a target :class:`.Session`, and is then invoked for results.
  239. """
  240. __slots__ = "bq", "session", "_params", "_post_criteria"
  241. def __init__(self, bq, session):
  242. self.bq = bq
  243. self.session = session
  244. self._params = {}
  245. self._post_criteria = []
  246. def params(self, *args, **kw):
  247. """Specify parameters to be replaced into the string SQL statement."""
  248. if len(args) == 1:
  249. kw.update(args[0])
  250. elif len(args) > 0:
  251. raise sa_exc.ArgumentError(
  252. "params() takes zero or one positional argument, "
  253. "which is a dictionary."
  254. )
  255. self._params.update(kw)
  256. return self
  257. def _using_post_criteria(self, fns):
  258. if fns:
  259. self._post_criteria.extend(fns)
  260. return self
  261. def with_post_criteria(self, fn):
  262. """Add a criteria function that will be applied post-cache.
  263. This adds a function that will be run against the
  264. :class:`_query.Query` object after it is retrieved from the
  265. cache. This currently includes **only** the
  266. :meth:`_query.Query.params` and :meth:`_query.Query.execution_options`
  267. methods.
  268. .. warning:: :meth:`_baked.Result.with_post_criteria`
  269. functions are applied
  270. to the :class:`_query.Query`
  271. object **after** the query's SQL statement
  272. object has been retrieved from the cache. Only
  273. :meth:`_query.Query.params` and
  274. :meth:`_query.Query.execution_options`
  275. methods should be used.
  276. .. versionadded:: 1.2
  277. """
  278. return self._using_post_criteria([fn])
  279. def _as_query(self):
  280. q = self.bq._as_query(self.session).params(self._params)
  281. for fn in self._post_criteria:
  282. q = fn(q)
  283. return q
  284. def __str__(self):
  285. return str(self._as_query())
  286. def __iter__(self):
  287. return self._iter().__iter__()
  288. def _iter(self):
  289. bq = self.bq
  290. if not self.session.enable_baked_queries or bq._spoiled:
  291. return self._as_query()._iter()
  292. query, statement = bq._bakery.get(
  293. bq._effective_key(self.session), (None, None)
  294. )
  295. if query is None:
  296. query, statement = bq._bake(self.session)
  297. if self._params:
  298. q = query.params(self._params)
  299. else:
  300. q = query
  301. for fn in self._post_criteria:
  302. q = fn(q)
  303. params = q._params
  304. execution_options = dict(q._execution_options)
  305. execution_options.update(
  306. {
  307. "_sa_orm_load_options": q.load_options,
  308. "compiled_cache": bq._bakery,
  309. }
  310. )
  311. result = self.session.execute(
  312. statement, params, execution_options=execution_options
  313. )
  314. if result._attributes.get("is_single_entity", False):
  315. result = result.scalars()
  316. if result._attributes.get("filtered", False):
  317. result = result.unique()
  318. return result
  319. def count(self):
  320. """return the 'count'.
  321. Equivalent to :meth:`_query.Query.count`.
  322. Note this uses a subquery to ensure an accurate count regardless
  323. of the structure of the original statement.
  324. .. versionadded:: 1.1.6
  325. """
  326. col = func.count(literal_column("*"))
  327. bq = self.bq.with_criteria(lambda q: q._from_self(col))
  328. return bq.for_session(self.session).params(self._params).scalar()
  329. def scalar(self):
  330. """Return the first element of the first result or None
  331. if no rows present. If multiple rows are returned,
  332. raises MultipleResultsFound.
  333. Equivalent to :meth:`_query.Query.scalar`.
  334. .. versionadded:: 1.1.6
  335. """
  336. try:
  337. ret = self.one()
  338. if not isinstance(ret, collections_abc.Sequence):
  339. return ret
  340. return ret[0]
  341. except orm_exc.NoResultFound:
  342. return None
  343. def first(self):
  344. """Return the first row.
  345. Equivalent to :meth:`_query.Query.first`.
  346. """
  347. bq = self.bq.with_criteria(lambda q: q.slice(0, 1))
  348. return (
  349. bq.for_session(self.session)
  350. .params(self._params)
  351. ._using_post_criteria(self._post_criteria)
  352. ._iter()
  353. .first()
  354. )
  355. def one(self):
  356. """Return exactly one result or raise an exception.
  357. Equivalent to :meth:`_query.Query.one`.
  358. """
  359. return self._iter().one()
  360. def one_or_none(self):
  361. """Return one or zero results, or raise an exception for multiple
  362. rows.
  363. Equivalent to :meth:`_query.Query.one_or_none`.
  364. .. versionadded:: 1.0.9
  365. """
  366. return self._iter().one_or_none()
  367. def all(self):
  368. """Return all rows.
  369. Equivalent to :meth:`_query.Query.all`.
  370. """
  371. return self._iter().all()
  372. def get(self, ident):
  373. """Retrieve an object based on identity.
  374. Equivalent to :meth:`_query.Query.get`.
  375. """
  376. query = self.bq.steps[0](self.session)
  377. return query._get_impl(ident, self._load_on_pk_identity)
  378. def _load_on_pk_identity(self, session, query, primary_key_identity, **kw):
  379. """Load the given primary key identity from the database."""
  380. mapper = query._raw_columns[0]._annotations["parententity"]
  381. _get_clause, _get_params = mapper._get_clause
  382. def setup(query):
  383. _lcl_get_clause = _get_clause
  384. q = query._clone()
  385. q._get_condition()
  386. q._order_by = None
  387. # None present in ident - turn those comparisons
  388. # into "IS NULL"
  389. if None in primary_key_identity:
  390. nones = set(
  391. [
  392. _get_params[col].key
  393. for col, value in zip(
  394. mapper.primary_key, primary_key_identity
  395. )
  396. if value is None
  397. ]
  398. )
  399. _lcl_get_clause = sql_util.adapt_criterion_to_null(
  400. _lcl_get_clause, nones
  401. )
  402. # TODO: can mapper._get_clause be pre-adapted?
  403. q._where_criteria = (
  404. sql_util._deep_annotate(_lcl_get_clause, {"_orm_adapt": True}),
  405. )
  406. for fn in self._post_criteria:
  407. q = fn(q)
  408. return q
  409. # cache the query against a key that includes
  410. # which positions in the primary key are NULL
  411. # (remember, we can map to an OUTER JOIN)
  412. bq = self.bq
  413. # add the clause we got from mapper._get_clause to the cache
  414. # key so that if a race causes multiple calls to _get_clause,
  415. # we've cached on ours
  416. bq = bq._clone()
  417. bq._cache_key += (_get_clause,)
  418. bq = bq.with_criteria(
  419. setup, tuple(elem is None for elem in primary_key_identity)
  420. )
  421. params = dict(
  422. [
  423. (_get_params[primary_key].key, id_val)
  424. for id_val, primary_key in zip(
  425. primary_key_identity, mapper.primary_key
  426. )
  427. ]
  428. )
  429. result = list(bq.for_session(self.session).params(**params))
  430. l = len(result)
  431. if l > 1:
  432. raise orm_exc.MultipleResultsFound()
  433. elif l:
  434. return result[0]
  435. else:
  436. return None
  437. @util.deprecated(
  438. "1.2", "Baked lazy loading is now the default implementation."
  439. )
  440. def bake_lazy_loaders():
  441. """Enable the use of baked queries for all lazyloaders systemwide.
  442. The "baked" implementation of lazy loading is now the sole implementation
  443. for the base lazy loader; this method has no effect except for a warning.
  444. """
  445. pass
  446. @util.deprecated(
  447. "1.2", "Baked lazy loading is now the default implementation."
  448. )
  449. def unbake_lazy_loaders():
  450. """Disable the use of baked queries for all lazyloaders systemwide.
  451. This method now raises NotImplementedError() as the "baked" implementation
  452. is the only lazy load implementation. The
  453. :paramref:`_orm.relationship.bake_queries` flag may be used to disable
  454. the caching of queries on a per-relationship basis.
  455. """
  456. raise NotImplementedError(
  457. "Baked lazy loading is now the default implementation"
  458. )
  459. @strategy_options.loader_option()
  460. def baked_lazyload(loadopt, attr):
  461. """Indicate that the given attribute should be loaded using "lazy"
  462. loading with a "baked" query used in the load.
  463. """
  464. return loadopt.set_relationship_strategy(attr, {"lazy": "baked_select"})
  465. @baked_lazyload._add_unbound_fn
  466. @util.deprecated(
  467. "1.2",
  468. "Baked lazy loading is now the default "
  469. "implementation for lazy loading.",
  470. )
  471. def baked_lazyload(*keys):
  472. return strategy_options._UnboundLoad._from_keys(
  473. strategy_options._UnboundLoad.baked_lazyload, keys, False, {}
  474. )
  475. @baked_lazyload._add_unbound_all_fn
  476. @util.deprecated(
  477. "1.2",
  478. "Baked lazy loading is now the default "
  479. "implementation for lazy loading.",
  480. )
  481. def baked_lazyload_all(*keys):
  482. return strategy_options._UnboundLoad._from_keys(
  483. strategy_options._UnboundLoad.baked_lazyload, keys, True, {}
  484. )
  485. baked_lazyload = baked_lazyload._unbound_fn
  486. baked_lazyload_all = baked_lazyload_all._unbound_all_fn
  487. bakery = BakedQuery.bakery