query.py 115 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414
  1. # orm/query.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """The Query class and support.
  8. Defines the :class:`_query.Query` class, the central
  9. construct used by the ORM to construct database queries.
  10. The :class:`_query.Query` class should not be confused with the
  11. :class:`_expression.Select` class, which defines database
  12. SELECT operations at the SQL (non-ORM) level. ``Query`` differs from
  13. ``Select`` in that it returns ORM-mapped objects and interacts with an
  14. ORM session, whereas the ``Select`` construct interacts directly with the
  15. database to return iterable result sets.
  16. """
  17. from __future__ import annotations
  18. import collections.abc as collections_abc
  19. import operator
  20. from typing import Any
  21. from typing import Callable
  22. from typing import cast
  23. from typing import Dict
  24. from typing import Generic
  25. from typing import Iterable
  26. from typing import Iterator
  27. from typing import List
  28. from typing import Mapping
  29. from typing import Optional
  30. from typing import overload
  31. from typing import Sequence
  32. from typing import Tuple
  33. from typing import Type
  34. from typing import TYPE_CHECKING
  35. from typing import TypeVar
  36. from typing import Union
  37. from . import attributes
  38. from . import interfaces
  39. from . import loading
  40. from . import util as orm_util
  41. from ._typing import _O
  42. from .base import _assertions
  43. from .context import _column_descriptions
  44. from .context import _determine_last_joined_entity
  45. from .context import _legacy_filter_by_entity_zero
  46. from .context import FromStatement
  47. from .context import ORMCompileState
  48. from .context import QueryContext
  49. from .interfaces import ORMColumnDescription
  50. from .interfaces import ORMColumnsClauseRole
  51. from .util import AliasedClass
  52. from .util import object_mapper
  53. from .util import with_parent
  54. from .. import exc as sa_exc
  55. from .. import inspect
  56. from .. import inspection
  57. from .. import log
  58. from .. import sql
  59. from .. import util
  60. from ..engine import Result
  61. from ..engine import Row
  62. from ..event import dispatcher
  63. from ..event import EventTarget
  64. from ..sql import coercions
  65. from ..sql import expression
  66. from ..sql import roles
  67. from ..sql import Select
  68. from ..sql import util as sql_util
  69. from ..sql import visitors
  70. from ..sql._typing import _FromClauseArgument
  71. from ..sql._typing import _TP
  72. from ..sql.annotation import SupportsCloneAnnotations
  73. from ..sql.base import _entity_namespace_key
  74. from ..sql.base import _generative
  75. from ..sql.base import _NoArg
  76. from ..sql.base import Executable
  77. from ..sql.base import Generative
  78. from ..sql.elements import BooleanClauseList
  79. from ..sql.expression import Exists
  80. from ..sql.selectable import _MemoizedSelectEntities
  81. from ..sql.selectable import _SelectFromElements
  82. from ..sql.selectable import ForUpdateArg
  83. from ..sql.selectable import HasHints
  84. from ..sql.selectable import HasPrefixes
  85. from ..sql.selectable import HasSuffixes
  86. from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
  87. from ..sql.selectable import SelectLabelStyle
  88. from ..util.typing import Literal
  89. from ..util.typing import Self
  90. if TYPE_CHECKING:
  91. from ._typing import _EntityType
  92. from ._typing import _ExternalEntityType
  93. from ._typing import _InternalEntityType
  94. from ._typing import SynchronizeSessionArgument
  95. from .mapper import Mapper
  96. from .path_registry import PathRegistry
  97. from .session import _PKIdentityArgument
  98. from .session import Session
  99. from .state import InstanceState
  100. from ..engine.cursor import CursorResult
  101. from ..engine.interfaces import _ImmutableExecuteOptions
  102. from ..engine.interfaces import CompiledCacheType
  103. from ..engine.interfaces import IsolationLevel
  104. from ..engine.interfaces import SchemaTranslateMapType
  105. from ..engine.result import FrozenResult
  106. from ..engine.result import ScalarResult
  107. from ..sql._typing import _ColumnExpressionArgument
  108. from ..sql._typing import _ColumnExpressionOrStrLabelArgument
  109. from ..sql._typing import _ColumnsClauseArgument
  110. from ..sql._typing import _DMLColumnArgument
  111. from ..sql._typing import _JoinTargetArgument
  112. from ..sql._typing import _LimitOffsetType
  113. from ..sql._typing import _MAYBE_ENTITY
  114. from ..sql._typing import _no_kw
  115. from ..sql._typing import _NOT_ENTITY
  116. from ..sql._typing import _OnClauseArgument
  117. from ..sql._typing import _PropagateAttrsType
  118. from ..sql._typing import _T0
  119. from ..sql._typing import _T1
  120. from ..sql._typing import _T2
  121. from ..sql._typing import _T3
  122. from ..sql._typing import _T4
  123. from ..sql._typing import _T5
  124. from ..sql._typing import _T6
  125. from ..sql._typing import _T7
  126. from ..sql._typing import _TypedColumnClauseArgument as _TCCA
  127. from ..sql.base import CacheableOptions
  128. from ..sql.base import ExecutableOption
  129. from ..sql.elements import ColumnElement
  130. from ..sql.elements import Label
  131. from ..sql.selectable import _ForUpdateOfArgument
  132. from ..sql.selectable import _JoinTargetElement
  133. from ..sql.selectable import _SetupJoinsElement
  134. from ..sql.selectable import Alias
  135. from ..sql.selectable import CTE
  136. from ..sql.selectable import ExecutableReturnsRows
  137. from ..sql.selectable import FromClause
  138. from ..sql.selectable import ScalarSelect
  139. from ..sql.selectable import Subquery
  140. __all__ = ["Query", "QueryContext"]
  141. _T = TypeVar("_T", bound=Any)
  142. @inspection._self_inspects
  143. @log.class_logger
  144. class Query(
  145. _SelectFromElements,
  146. SupportsCloneAnnotations,
  147. HasPrefixes,
  148. HasSuffixes,
  149. HasHints,
  150. EventTarget,
  151. log.Identified,
  152. Generative,
  153. Executable,
  154. Generic[_T],
  155. ):
  156. """ORM-level SQL construction object.
  157. .. legacy:: The ORM :class:`.Query` object is a legacy construct
  158. as of SQLAlchemy 2.0. See the notes at the top of
  159. :ref:`query_api_toplevel` for an overview, including links to migration
  160. documentation.
  161. :class:`_query.Query` objects are normally initially generated using the
  162. :meth:`~.Session.query` method of :class:`.Session`, and in
  163. less common cases by instantiating the :class:`_query.Query` directly and
  164. associating with a :class:`.Session` using the
  165. :meth:`_query.Query.with_session`
  166. method.
  167. """
  168. # elements that are in Core and can be cached in the same way
  169. _where_criteria: Tuple[ColumnElement[Any], ...] = ()
  170. _having_criteria: Tuple[ColumnElement[Any], ...] = ()
  171. _order_by_clauses: Tuple[ColumnElement[Any], ...] = ()
  172. _group_by_clauses: Tuple[ColumnElement[Any], ...] = ()
  173. _limit_clause: Optional[ColumnElement[Any]] = None
  174. _offset_clause: Optional[ColumnElement[Any]] = None
  175. _distinct: bool = False
  176. _distinct_on: Tuple[ColumnElement[Any], ...] = ()
  177. _for_update_arg: Optional[ForUpdateArg] = None
  178. _correlate: Tuple[FromClause, ...] = ()
  179. _auto_correlate: bool = True
  180. _from_obj: Tuple[FromClause, ...] = ()
  181. _setup_joins: Tuple[_SetupJoinsElement, ...] = ()
  182. _label_style: SelectLabelStyle = SelectLabelStyle.LABEL_STYLE_LEGACY_ORM
  183. _memoized_select_entities = ()
  184. _compile_options: Union[
  185. Type[CacheableOptions], CacheableOptions
  186. ] = ORMCompileState.default_compile_options
  187. _with_options: Tuple[ExecutableOption, ...]
  188. load_options = QueryContext.default_load_options + {
  189. "_legacy_uniquing": True
  190. }
  191. _params: util.immutabledict[str, Any] = util.EMPTY_DICT
  192. # local Query builder state, not needed for
  193. # compilation or execution
  194. _enable_assertions = True
  195. _statement: Optional[ExecutableReturnsRows] = None
  196. session: Session
  197. dispatch: dispatcher[Query[_T]]
  198. # mirrors that of ClauseElement, used to propagate the "orm"
  199. # plugin as well as the "subject" of the plugin, e.g. the mapper
  200. # we are querying against.
  201. @util.memoized_property
  202. def _propagate_attrs(self) -> _PropagateAttrsType:
  203. return util.EMPTY_DICT
  204. def __init__(
  205. self,
  206. entities: Union[
  207. _ColumnsClauseArgument[Any], Sequence[_ColumnsClauseArgument[Any]]
  208. ],
  209. session: Optional[Session] = None,
  210. ):
  211. """Construct a :class:`_query.Query` directly.
  212. E.g.::
  213. q = Query([User, Address], session=some_session)
  214. The above is equivalent to::
  215. q = some_session.query(User, Address)
  216. :param entities: a sequence of entities and/or SQL expressions.
  217. :param session: a :class:`.Session` with which the
  218. :class:`_query.Query`
  219. will be associated. Optional; a :class:`_query.Query`
  220. can be associated
  221. with a :class:`.Session` generatively via the
  222. :meth:`_query.Query.with_session` method as well.
  223. .. seealso::
  224. :meth:`.Session.query`
  225. :meth:`_query.Query.with_session`
  226. """
  227. # session is usually present. There's one case in subqueryloader
  228. # where it stores a Query without a Session and also there are tests
  229. # for the query(Entity).with_session(session) API which is likely in
  230. # some old recipes, however these are legacy as select() can now be
  231. # used.
  232. self.session = session # type: ignore
  233. self._set_entities(entities)
  234. def _set_propagate_attrs(self, values: Mapping[str, Any]) -> Self:
  235. self._propagate_attrs = util.immutabledict(values)
  236. return self
  237. def _set_entities(
  238. self,
  239. entities: Union[
  240. _ColumnsClauseArgument[Any], Iterable[_ColumnsClauseArgument[Any]]
  241. ],
  242. ) -> None:
  243. self._raw_columns = [
  244. coercions.expect(
  245. roles.ColumnsClauseRole,
  246. ent,
  247. apply_propagate_attrs=self,
  248. post_inspect=True,
  249. )
  250. for ent in util.to_list(entities)
  251. ]
  252. def tuples(self: Query[_O]) -> Query[Tuple[_O]]:
  253. """return a tuple-typed form of this :class:`.Query`.
  254. This method invokes the :meth:`.Query.only_return_tuples`
  255. method with a value of ``True``, which by itself ensures that this
  256. :class:`.Query` will always return :class:`.Row` objects, even
  257. if the query is made against a single entity. It then also
  258. at the typing level will return a "typed" query, if possible,
  259. that will type result rows as ``Tuple`` objects with typed
  260. elements.
  261. This method can be compared to the :meth:`.Result.tuples` method,
  262. which returns "self", but from a typing perspective returns an object
  263. that will yield typed ``Tuple`` objects for results. Typing
  264. takes effect only if this :class:`.Query` object is a typed
  265. query object already.
  266. .. versionadded:: 2.0
  267. .. seealso::
  268. :meth:`.Result.tuples` - v2 equivalent method.
  269. """
  270. return self.only_return_tuples(True) # type: ignore
  271. def _entity_from_pre_ent_zero(self) -> Optional[_InternalEntityType[Any]]:
  272. if not self._raw_columns:
  273. return None
  274. ent = self._raw_columns[0]
  275. if "parententity" in ent._annotations:
  276. return ent._annotations["parententity"] # type: ignore
  277. elif "bundle" in ent._annotations:
  278. return ent._annotations["bundle"] # type: ignore
  279. else:
  280. # label, other SQL expression
  281. for element in visitors.iterate(ent):
  282. if "parententity" in element._annotations:
  283. return element._annotations["parententity"] # type: ignore # noqa: E501
  284. else:
  285. return None
  286. def _only_full_mapper_zero(self, methname: str) -> Mapper[Any]:
  287. if (
  288. len(self._raw_columns) != 1
  289. or "parententity" not in self._raw_columns[0]._annotations
  290. or not self._raw_columns[0].is_selectable
  291. ):
  292. raise sa_exc.InvalidRequestError(
  293. "%s() can only be used against "
  294. "a single mapped class." % methname
  295. )
  296. return self._raw_columns[0]._annotations["parententity"] # type: ignore # noqa: E501
  297. def _set_select_from(
  298. self, obj: Iterable[_FromClauseArgument], set_base_alias: bool
  299. ) -> None:
  300. fa = [
  301. coercions.expect(
  302. roles.StrictFromClauseRole,
  303. elem,
  304. allow_select=True,
  305. apply_propagate_attrs=self,
  306. )
  307. for elem in obj
  308. ]
  309. self._compile_options += {"_set_base_alias": set_base_alias}
  310. self._from_obj = tuple(fa)
  311. @_generative
  312. def _set_lazyload_from(self, state: InstanceState[Any]) -> Self:
  313. self.load_options += {"_lazy_loaded_from": state}
  314. return self
  315. def _get_condition(self) -> None:
  316. """used by legacy BakedQuery"""
  317. self._no_criterion_condition("get", order_by=False, distinct=False)
  318. def _get_existing_condition(self) -> None:
  319. self._no_criterion_assertion("get", order_by=False, distinct=False)
  320. def _no_criterion_assertion(
  321. self, meth: str, order_by: bool = True, distinct: bool = True
  322. ) -> None:
  323. if not self._enable_assertions:
  324. return
  325. if (
  326. self._where_criteria
  327. or self._statement is not None
  328. or self._from_obj
  329. or self._setup_joins
  330. or self._limit_clause is not None
  331. or self._offset_clause is not None
  332. or self._group_by_clauses
  333. or (order_by and self._order_by_clauses)
  334. or (distinct and self._distinct)
  335. ):
  336. raise sa_exc.InvalidRequestError(
  337. "Query.%s() being called on a "
  338. "Query with existing criterion. " % meth
  339. )
  340. def _no_criterion_condition(
  341. self, meth: str, order_by: bool = True, distinct: bool = True
  342. ) -> None:
  343. self._no_criterion_assertion(meth, order_by, distinct)
  344. self._from_obj = self._setup_joins = ()
  345. if self._statement is not None:
  346. self._compile_options += {"_statement": None}
  347. self._where_criteria = ()
  348. self._distinct = False
  349. self._order_by_clauses = self._group_by_clauses = ()
  350. def _no_clauseelement_condition(self, meth: str) -> None:
  351. if not self._enable_assertions:
  352. return
  353. if self._order_by_clauses:
  354. raise sa_exc.InvalidRequestError(
  355. "Query.%s() being called on a "
  356. "Query with existing criterion. " % meth
  357. )
  358. self._no_criterion_condition(meth)
  359. def _no_statement_condition(self, meth: str) -> None:
  360. if not self._enable_assertions:
  361. return
  362. if self._statement is not None:
  363. raise sa_exc.InvalidRequestError(
  364. (
  365. "Query.%s() being called on a Query with an existing full "
  366. "statement - can't apply criterion."
  367. )
  368. % meth
  369. )
  370. def _no_limit_offset(self, meth: str) -> None:
  371. if not self._enable_assertions:
  372. return
  373. if self._limit_clause is not None or self._offset_clause is not None:
  374. raise sa_exc.InvalidRequestError(
  375. "Query.%s() being called on a Query which already has LIMIT "
  376. "or OFFSET applied. Call %s() before limit() or offset() "
  377. "are applied." % (meth, meth)
  378. )
  379. @property
  380. def _has_row_limiting_clause(self) -> bool:
  381. return (
  382. self._limit_clause is not None or self._offset_clause is not None
  383. )
  384. def _get_options(
  385. self,
  386. populate_existing: Optional[bool] = None,
  387. version_check: Optional[bool] = None,
  388. only_load_props: Optional[Sequence[str]] = None,
  389. refresh_state: Optional[InstanceState[Any]] = None,
  390. identity_token: Optional[Any] = None,
  391. ) -> Self:
  392. load_options: Dict[str, Any] = {}
  393. compile_options: Dict[str, Any] = {}
  394. if version_check:
  395. load_options["_version_check"] = version_check
  396. if populate_existing:
  397. load_options["_populate_existing"] = populate_existing
  398. if refresh_state:
  399. load_options["_refresh_state"] = refresh_state
  400. compile_options["_for_refresh_state"] = True
  401. if only_load_props:
  402. compile_options["_only_load_props"] = frozenset(only_load_props)
  403. if identity_token:
  404. load_options["_identity_token"] = identity_token
  405. if load_options:
  406. self.load_options += load_options
  407. if compile_options:
  408. self._compile_options += compile_options
  409. return self
  410. def _clone(self, **kw: Any) -> Self:
  411. return self._generate()
  412. def _get_select_statement_only(self) -> Select[_T]:
  413. if self._statement is not None:
  414. raise sa_exc.InvalidRequestError(
  415. "Can't call this method on a Query that uses from_statement()"
  416. )
  417. return cast("Select[_T]", self.statement)
  418. @property
  419. def statement(self) -> Union[Select[_T], FromStatement[_T]]:
  420. """The full SELECT statement represented by this Query.
  421. The statement by default will not have disambiguating labels
  422. applied to the construct unless with_labels(True) is called
  423. first.
  424. """
  425. # .statement can return the direct future.Select() construct here, as
  426. # long as we are not using subsequent adaption features that
  427. # are made against raw entities, e.g. from_self(), with_polymorphic(),
  428. # select_entity_from(). If these features are being used, then
  429. # the Select() we return will not have the correct .selected_columns
  430. # collection and will not embed in subsequent queries correctly.
  431. # We could find a way to make this collection "correct", however
  432. # this would not be too different from doing the full compile as
  433. # we are doing in any case, the Select() would still not have the
  434. # proper state for other attributes like whereclause, order_by,
  435. # and these features are all deprecated in any case.
  436. #
  437. # for these reasons, Query is not a Select, it remains an ORM
  438. # object for which __clause_element__() must be called in order for
  439. # it to provide a real expression object.
  440. #
  441. # from there, it starts to look much like Query itself won't be
  442. # passed into the execute process and won't generate its own cache
  443. # key; this will all occur in terms of the ORM-enabled Select.
  444. if not self._compile_options._set_base_alias:
  445. # if we don't have legacy top level aliasing features in use
  446. # then convert to a future select() directly
  447. stmt = self._statement_20(for_statement=True)
  448. else:
  449. stmt = self._compile_state(for_statement=True).statement
  450. if self._params:
  451. stmt = stmt.params(self._params)
  452. return stmt
  453. def _final_statement(self, legacy_query_style: bool = True) -> Select[Any]:
  454. """Return the 'final' SELECT statement for this :class:`.Query`.
  455. This is used by the testing suite only and is fairly inefficient.
  456. This is the Core-only select() that will be rendered by a complete
  457. compilation of this query, and is what .statement used to return
  458. in 1.3.
  459. """
  460. q = self._clone()
  461. return q._compile_state(
  462. use_legacy_query_style=legacy_query_style
  463. ).statement # type: ignore
  464. def _statement_20(
  465. self, for_statement: bool = False, use_legacy_query_style: bool = True
  466. ) -> Union[Select[_T], FromStatement[_T]]:
  467. # TODO: this event needs to be deprecated, as it currently applies
  468. # only to ORM query and occurs at this spot that is now more
  469. # or less an artificial spot
  470. if self.dispatch.before_compile:
  471. for fn in self.dispatch.before_compile:
  472. new_query = fn(self)
  473. if new_query is not None and new_query is not self:
  474. self = new_query
  475. if not fn._bake_ok: # type: ignore
  476. self._compile_options += {"_bake_ok": False}
  477. compile_options = self._compile_options
  478. compile_options += {
  479. "_for_statement": for_statement,
  480. "_use_legacy_query_style": use_legacy_query_style,
  481. }
  482. stmt: Union[Select[_T], FromStatement[_T]]
  483. if self._statement is not None:
  484. stmt = FromStatement(self._raw_columns, self._statement)
  485. stmt.__dict__.update(
  486. _with_options=self._with_options,
  487. _with_context_options=self._with_context_options,
  488. _compile_options=compile_options,
  489. _execution_options=self._execution_options,
  490. _propagate_attrs=self._propagate_attrs,
  491. )
  492. else:
  493. # Query / select() internal attributes are 99% cross-compatible
  494. stmt = Select._create_raw_select(**self.__dict__)
  495. stmt.__dict__.update(
  496. _label_style=self._label_style,
  497. _compile_options=compile_options,
  498. _propagate_attrs=self._propagate_attrs,
  499. )
  500. stmt.__dict__.pop("session", None)
  501. # ensure the ORM context is used to compile the statement, even
  502. # if it has no ORM entities. This is so ORM-only things like
  503. # _legacy_joins are picked up that wouldn't be picked up by the
  504. # Core statement context
  505. if "compile_state_plugin" not in stmt._propagate_attrs:
  506. stmt._propagate_attrs = stmt._propagate_attrs.union(
  507. {"compile_state_plugin": "orm", "plugin_subject": None}
  508. )
  509. return stmt
  510. def subquery(
  511. self,
  512. name: Optional[str] = None,
  513. with_labels: bool = False,
  514. reduce_columns: bool = False,
  515. ) -> Subquery:
  516. """Return the full SELECT statement represented by
  517. this :class:`_query.Query`, embedded within an
  518. :class:`_expression.Alias`.
  519. Eager JOIN generation within the query is disabled.
  520. .. seealso::
  521. :meth:`_sql.Select.subquery` - v2 comparable method.
  522. :param name: string name to be assigned as the alias;
  523. this is passed through to :meth:`_expression.FromClause.alias`.
  524. If ``None``, a name will be deterministically generated
  525. at compile time.
  526. :param with_labels: if True, :meth:`.with_labels` will be called
  527. on the :class:`_query.Query` first to apply table-qualified labels
  528. to all columns.
  529. :param reduce_columns: if True,
  530. :meth:`_expression.Select.reduce_columns` will
  531. be called on the resulting :func:`_expression.select` construct,
  532. to remove same-named columns where one also refers to the other
  533. via foreign key or WHERE clause equivalence.
  534. """
  535. q = self.enable_eagerloads(False)
  536. if with_labels:
  537. q = q.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  538. stmt = q._get_select_statement_only()
  539. if TYPE_CHECKING:
  540. assert isinstance(stmt, Select)
  541. if reduce_columns:
  542. stmt = stmt.reduce_columns()
  543. return stmt.subquery(name=name)
  544. def cte(
  545. self,
  546. name: Optional[str] = None,
  547. recursive: bool = False,
  548. nesting: bool = False,
  549. ) -> CTE:
  550. r"""Return the full SELECT statement represented by this
  551. :class:`_query.Query` represented as a common table expression (CTE).
  552. Parameters and usage are the same as those of the
  553. :meth:`_expression.SelectBase.cte` method; see that method for
  554. further details.
  555. Here is the `PostgreSQL WITH
  556. RECURSIVE example
  557. <https://www.postgresql.org/docs/current/static/queries-with.html>`_.
  558. Note that, in this example, the ``included_parts`` cte and the
  559. ``incl_alias`` alias of it are Core selectables, which
  560. means the columns are accessed via the ``.c.`` attribute. The
  561. ``parts_alias`` object is an :func:`_orm.aliased` instance of the
  562. ``Part`` entity, so column-mapped attributes are available
  563. directly::
  564. from sqlalchemy.orm import aliased
  565. class Part(Base):
  566. __tablename__ = 'part'
  567. part = Column(String, primary_key=True)
  568. sub_part = Column(String, primary_key=True)
  569. quantity = Column(Integer)
  570. included_parts = session.query(
  571. Part.sub_part,
  572. Part.part,
  573. Part.quantity).\
  574. filter(Part.part=="our part").\
  575. cte(name="included_parts", recursive=True)
  576. incl_alias = aliased(included_parts, name="pr")
  577. parts_alias = aliased(Part, name="p")
  578. included_parts = included_parts.union_all(
  579. session.query(
  580. parts_alias.sub_part,
  581. parts_alias.part,
  582. parts_alias.quantity).\
  583. filter(parts_alias.part==incl_alias.c.sub_part)
  584. )
  585. q = session.query(
  586. included_parts.c.sub_part,
  587. func.sum(included_parts.c.quantity).
  588. label('total_quantity')
  589. ).\
  590. group_by(included_parts.c.sub_part)
  591. .. seealso::
  592. :meth:`_sql.Select.cte` - v2 equivalent method.
  593. """
  594. return (
  595. self.enable_eagerloads(False)
  596. ._get_select_statement_only()
  597. .cte(name=name, recursive=recursive, nesting=nesting)
  598. )
  599. def label(self, name: Optional[str]) -> Label[Any]:
  600. """Return the full SELECT statement represented by this
  601. :class:`_query.Query`, converted
  602. to a scalar subquery with a label of the given name.
  603. .. seealso::
  604. :meth:`_sql.Select.label` - v2 comparable method.
  605. """
  606. return (
  607. self.enable_eagerloads(False)
  608. ._get_select_statement_only()
  609. .label(name)
  610. )
  611. @overload
  612. def as_scalar(
  613. self: Query[Tuple[_MAYBE_ENTITY]],
  614. ) -> ScalarSelect[_MAYBE_ENTITY]:
  615. ...
  616. @overload
  617. def as_scalar(
  618. self: Query[Tuple[_NOT_ENTITY]],
  619. ) -> ScalarSelect[_NOT_ENTITY]:
  620. ...
  621. @overload
  622. def as_scalar(self) -> ScalarSelect[Any]:
  623. ...
  624. @util.deprecated(
  625. "1.4",
  626. "The :meth:`_query.Query.as_scalar` method is deprecated and will be "
  627. "removed in a future release. Please refer to "
  628. ":meth:`_query.Query.scalar_subquery`.",
  629. )
  630. def as_scalar(self) -> ScalarSelect[Any]:
  631. """Return the full SELECT statement represented by this
  632. :class:`_query.Query`, converted to a scalar subquery.
  633. """
  634. return self.scalar_subquery()
  635. @overload
  636. def scalar_subquery(
  637. self: Query[Tuple[_MAYBE_ENTITY]],
  638. ) -> ScalarSelect[Any]:
  639. ...
  640. @overload
  641. def scalar_subquery(
  642. self: Query[Tuple[_NOT_ENTITY]],
  643. ) -> ScalarSelect[_NOT_ENTITY]:
  644. ...
  645. @overload
  646. def scalar_subquery(self) -> ScalarSelect[Any]:
  647. ...
  648. def scalar_subquery(self) -> ScalarSelect[Any]:
  649. """Return the full SELECT statement represented by this
  650. :class:`_query.Query`, converted to a scalar subquery.
  651. Analogous to
  652. :meth:`sqlalchemy.sql.expression.SelectBase.scalar_subquery`.
  653. .. versionchanged:: 1.4 The :meth:`_query.Query.scalar_subquery`
  654. method replaces the :meth:`_query.Query.as_scalar` method.
  655. .. seealso::
  656. :meth:`_sql.Select.scalar_subquery` - v2 comparable method.
  657. """
  658. return (
  659. self.enable_eagerloads(False)
  660. ._get_select_statement_only()
  661. .scalar_subquery()
  662. )
  663. @property
  664. def selectable(self) -> Union[Select[_T], FromStatement[_T]]:
  665. """Return the :class:`_expression.Select` object emitted by this
  666. :class:`_query.Query`.
  667. Used for :func:`_sa.inspect` compatibility, this is equivalent to::
  668. query.enable_eagerloads(False).with_labels().statement
  669. """
  670. return self.__clause_element__()
  671. def __clause_element__(self) -> Union[Select[_T], FromStatement[_T]]:
  672. return (
  673. self._with_compile_options(
  674. _enable_eagerloads=False, _render_for_subquery=True
  675. )
  676. .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  677. .statement
  678. )
  679. @overload
  680. def only_return_tuples(
  681. self: Query[_O], value: Literal[True]
  682. ) -> RowReturningQuery[Tuple[_O]]:
  683. ...
  684. @overload
  685. def only_return_tuples(
  686. self: Query[_O], value: Literal[False]
  687. ) -> Query[_O]:
  688. ...
  689. @_generative
  690. def only_return_tuples(self, value: bool) -> Query[Any]:
  691. """When set to True, the query results will always be a
  692. :class:`.Row` object.
  693. This can change a query that normally returns a single entity
  694. as a scalar to return a :class:`.Row` result in all cases.
  695. .. seealso::
  696. :meth:`.Query.tuples` - returns tuples, but also at the typing
  697. level will type results as ``Tuple``.
  698. :meth:`_query.Query.is_single_entity`
  699. :meth:`_engine.Result.tuples` - v2 comparable method.
  700. """
  701. self.load_options += dict(_only_return_tuples=value)
  702. return self
  703. @property
  704. def is_single_entity(self) -> bool:
  705. """Indicates if this :class:`_query.Query`
  706. returns tuples or single entities.
  707. Returns True if this query returns a single entity for each instance
  708. in its result list, and False if this query returns a tuple of entities
  709. for each result.
  710. .. versionadded:: 1.3.11
  711. .. seealso::
  712. :meth:`_query.Query.only_return_tuples`
  713. """
  714. return (
  715. not self.load_options._only_return_tuples
  716. and len(self._raw_columns) == 1
  717. and "parententity" in self._raw_columns[0]._annotations
  718. and isinstance(
  719. self._raw_columns[0]._annotations["parententity"],
  720. ORMColumnsClauseRole,
  721. )
  722. )
  723. @_generative
  724. def enable_eagerloads(self, value: bool) -> Self:
  725. """Control whether or not eager joins and subqueries are
  726. rendered.
  727. When set to False, the returned Query will not render
  728. eager joins regardless of :func:`~sqlalchemy.orm.joinedload`,
  729. :func:`~sqlalchemy.orm.subqueryload` options
  730. or mapper-level ``lazy='joined'``/``lazy='subquery'``
  731. configurations.
  732. This is used primarily when nesting the Query's
  733. statement into a subquery or other
  734. selectable, or when using :meth:`_query.Query.yield_per`.
  735. """
  736. self._compile_options += {"_enable_eagerloads": value}
  737. return self
  738. @_generative
  739. def _with_compile_options(self, **opt: Any) -> Self:
  740. self._compile_options += opt
  741. return self
  742. @util.became_legacy_20(
  743. ":meth:`_orm.Query.with_labels` and :meth:`_orm.Query.apply_labels`",
  744. alternative="Use set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) "
  745. "instead.",
  746. )
  747. def with_labels(self) -> Self:
  748. return self.set_label_style(
  749. SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL
  750. )
  751. apply_labels = with_labels
  752. @property
  753. def get_label_style(self) -> SelectLabelStyle:
  754. """
  755. Retrieve the current label style.
  756. .. versionadded:: 1.4
  757. .. seealso::
  758. :meth:`_sql.Select.get_label_style` - v2 equivalent method.
  759. """
  760. return self._label_style
  761. def set_label_style(self, style: SelectLabelStyle) -> Self:
  762. """Apply column labels to the return value of Query.statement.
  763. Indicates that this Query's `statement` accessor should return
  764. a SELECT statement that applies labels to all columns in the
  765. form <tablename>_<columnname>; this is commonly used to
  766. disambiguate columns from multiple tables which have the same
  767. name.
  768. When the `Query` actually issues SQL to load rows, it always
  769. uses column labeling.
  770. .. note:: The :meth:`_query.Query.set_label_style` method *only* applies
  771. the output of :attr:`_query.Query.statement`, and *not* to any of
  772. the result-row invoking systems of :class:`_query.Query` itself,
  773. e.g.
  774. :meth:`_query.Query.first`, :meth:`_query.Query.all`, etc.
  775. To execute
  776. a query using :meth:`_query.Query.set_label_style`, invoke the
  777. :attr:`_query.Query.statement` using :meth:`.Session.execute`::
  778. result = session.execute(
  779. query
  780. .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  781. .statement
  782. )
  783. .. versionadded:: 1.4
  784. .. seealso::
  785. :meth:`_sql.Select.set_label_style` - v2 equivalent method.
  786. """ # noqa
  787. if self._label_style is not style:
  788. self = self._generate()
  789. self._label_style = style
  790. return self
  791. @_generative
  792. def enable_assertions(self, value: bool) -> Self:
  793. """Control whether assertions are generated.
  794. When set to False, the returned Query will
  795. not assert its state before certain operations,
  796. including that LIMIT/OFFSET has not been applied
  797. when filter() is called, no criterion exists
  798. when get() is called, and no "from_statement()"
  799. exists when filter()/order_by()/group_by() etc.
  800. is called. This more permissive mode is used by
  801. custom Query subclasses to specify criterion or
  802. other modifiers outside of the usual usage patterns.
  803. Care should be taken to ensure that the usage
  804. pattern is even possible. A statement applied
  805. by from_statement() will override any criterion
  806. set by filter() or order_by(), for example.
  807. """
  808. self._enable_assertions = value
  809. return self
  810. @property
  811. def whereclause(self) -> Optional[ColumnElement[bool]]:
  812. """A readonly attribute which returns the current WHERE criterion for
  813. this Query.
  814. This returned value is a SQL expression construct, or ``None`` if no
  815. criterion has been established.
  816. .. seealso::
  817. :attr:`_sql.Select.whereclause` - v2 equivalent property.
  818. """
  819. return BooleanClauseList._construct_for_whereclause(
  820. self._where_criteria
  821. )
  822. @_generative
  823. def _with_current_path(self, path: PathRegistry) -> Self:
  824. """indicate that this query applies to objects loaded
  825. within a certain path.
  826. Used by deferred loaders (see strategies.py) which transfer
  827. query options from an originating query to a newly generated
  828. query intended for the deferred load.
  829. """
  830. self._compile_options += {"_current_path": path}
  831. return self
  832. @_generative
  833. def yield_per(self, count: int) -> Self:
  834. r"""Yield only ``count`` rows at a time.
  835. The purpose of this method is when fetching very large result sets
  836. (> 10K rows), to batch results in sub-collections and yield them
  837. out partially, so that the Python interpreter doesn't need to declare
  838. very large areas of memory which is both time consuming and leads
  839. to excessive memory use. The performance from fetching hundreds of
  840. thousands of rows can often double when a suitable yield-per setting
  841. (e.g. approximately 1000) is used, even with DBAPIs that buffer
  842. rows (which are most).
  843. As of SQLAlchemy 1.4, the :meth:`_orm.Query.yield_per` method is
  844. equivalent to using the ``yield_per`` execution option at the ORM
  845. level. See the section :ref:`orm_queryguide_yield_per` for further
  846. background on this option.
  847. .. seealso::
  848. :ref:`orm_queryguide_yield_per`
  849. """
  850. self.load_options += {"_yield_per": count}
  851. return self
  852. @util.became_legacy_20(
  853. ":meth:`_orm.Query.get`",
  854. alternative="The method is now available as :meth:`_orm.Session.get`",
  855. )
  856. def get(self, ident: _PKIdentityArgument) -> Optional[Any]:
  857. """Return an instance based on the given primary key identifier,
  858. or ``None`` if not found.
  859. E.g.::
  860. my_user = session.query(User).get(5)
  861. some_object = session.query(VersionedFoo).get((5, 10))
  862. some_object = session.query(VersionedFoo).get(
  863. {"id": 5, "version_id": 10})
  864. :meth:`_query.Query.get` is special in that it provides direct
  865. access to the identity map of the owning :class:`.Session`.
  866. If the given primary key identifier is present
  867. in the local identity map, the object is returned
  868. directly from this collection and no SQL is emitted,
  869. unless the object has been marked fully expired.
  870. If not present,
  871. a SELECT is performed in order to locate the object.
  872. :meth:`_query.Query.get` also will perform a check if
  873. the object is present in the identity map and
  874. marked as expired - a SELECT
  875. is emitted to refresh the object as well as to
  876. ensure that the row is still present.
  877. If not, :class:`~sqlalchemy.orm.exc.ObjectDeletedError` is raised.
  878. :meth:`_query.Query.get` is only used to return a single
  879. mapped instance, not multiple instances or
  880. individual column constructs, and strictly
  881. on a single primary key value. The originating
  882. :class:`_query.Query` must be constructed in this way,
  883. i.e. against a single mapped entity,
  884. with no additional filtering criterion. Loading
  885. options via :meth:`_query.Query.options` may be applied
  886. however, and will be used if the object is not
  887. yet locally present.
  888. :param ident: A scalar, tuple, or dictionary representing the
  889. primary key. For a composite (e.g. multiple column) primary key,
  890. a tuple or dictionary should be passed.
  891. For a single-column primary key, the scalar calling form is typically
  892. the most expedient. If the primary key of a row is the value "5",
  893. the call looks like::
  894. my_object = query.get(5)
  895. The tuple form contains primary key values typically in
  896. the order in which they correspond to the mapped
  897. :class:`_schema.Table`
  898. object's primary key columns, or if the
  899. :paramref:`_orm.Mapper.primary_key` configuration parameter were
  900. used, in
  901. the order used for that parameter. For example, if the primary key
  902. of a row is represented by the integer
  903. digits "5, 10" the call would look like::
  904. my_object = query.get((5, 10))
  905. The dictionary form should include as keys the mapped attribute names
  906. corresponding to each element of the primary key. If the mapped class
  907. has the attributes ``id``, ``version_id`` as the attributes which
  908. store the object's primary key value, the call would look like::
  909. my_object = query.get({"id": 5, "version_id": 10})
  910. .. versionadded:: 1.3 the :meth:`_query.Query.get`
  911. method now optionally
  912. accepts a dictionary of attribute names to values in order to
  913. indicate a primary key identifier.
  914. :return: The object instance, or ``None``.
  915. """
  916. self._no_criterion_assertion("get", order_by=False, distinct=False)
  917. # we still implement _get_impl() so that baked query can override
  918. # it
  919. return self._get_impl(ident, loading.load_on_pk_identity)
  920. def _get_impl(
  921. self,
  922. primary_key_identity: _PKIdentityArgument,
  923. db_load_fn: Callable[..., Any],
  924. identity_token: Optional[Any] = None,
  925. ) -> Optional[Any]:
  926. mapper = self._only_full_mapper_zero("get")
  927. return self.session._get_impl(
  928. mapper,
  929. primary_key_identity,
  930. db_load_fn,
  931. populate_existing=self.load_options._populate_existing,
  932. with_for_update=self._for_update_arg,
  933. options=self._with_options,
  934. identity_token=identity_token,
  935. execution_options=self._execution_options,
  936. )
  937. @property
  938. def lazy_loaded_from(self) -> Optional[InstanceState[Any]]:
  939. """An :class:`.InstanceState` that is using this :class:`_query.Query`
  940. for a lazy load operation.
  941. .. deprecated:: 1.4 This attribute should be viewed via the
  942. :attr:`.ORMExecuteState.lazy_loaded_from` attribute, within
  943. the context of the :meth:`.SessionEvents.do_orm_execute`
  944. event.
  945. .. seealso::
  946. :attr:`.ORMExecuteState.lazy_loaded_from`
  947. """
  948. return self.load_options._lazy_loaded_from # type: ignore
  949. @property
  950. def _current_path(self) -> PathRegistry:
  951. return self._compile_options._current_path # type: ignore
  952. @_generative
  953. def correlate(
  954. self,
  955. *fromclauses: Union[Literal[None, False], _FromClauseArgument],
  956. ) -> Self:
  957. """Return a :class:`.Query` construct which will correlate the given
  958. FROM clauses to that of an enclosing :class:`.Query` or
  959. :func:`~.expression.select`.
  960. The method here accepts mapped classes, :func:`.aliased` constructs,
  961. and :class:`_orm.Mapper` constructs as arguments, which are resolved
  962. into expression constructs, in addition to appropriate expression
  963. constructs.
  964. The correlation arguments are ultimately passed to
  965. :meth:`_expression.Select.correlate`
  966. after coercion to expression constructs.
  967. The correlation arguments take effect in such cases
  968. as when :meth:`_query.Query.from_self` is used, or when
  969. a subquery as returned by :meth:`_query.Query.subquery` is
  970. embedded in another :func:`_expression.select` construct.
  971. .. seealso::
  972. :meth:`_sql.Select.correlate` - v2 equivalent method.
  973. """
  974. self._auto_correlate = False
  975. if fromclauses and fromclauses[0] in {None, False}:
  976. self._correlate = ()
  977. else:
  978. self._correlate = self._correlate + tuple(
  979. coercions.expect(roles.FromClauseRole, f) for f in fromclauses
  980. )
  981. return self
  982. @_generative
  983. def autoflush(self, setting: bool) -> Self:
  984. """Return a Query with a specific 'autoflush' setting.
  985. As of SQLAlchemy 1.4, the :meth:`_orm.Query.autoflush` method
  986. is equivalent to using the ``autoflush`` execution option at the
  987. ORM level. See the section :ref:`orm_queryguide_autoflush` for
  988. further background on this option.
  989. """
  990. self.load_options += {"_autoflush": setting}
  991. return self
  992. @_generative
  993. def populate_existing(self) -> Self:
  994. """Return a :class:`_query.Query`
  995. that will expire and refresh all instances
  996. as they are loaded, or reused from the current :class:`.Session`.
  997. As of SQLAlchemy 1.4, the :meth:`_orm.Query.populate_existing` method
  998. is equivalent to using the ``populate_existing`` execution option at
  999. the ORM level. See the section :ref:`orm_queryguide_populate_existing`
  1000. for further background on this option.
  1001. """
  1002. self.load_options += {"_populate_existing": True}
  1003. return self
  1004. @_generative
  1005. def _with_invoke_all_eagers(self, value: bool) -> Self:
  1006. """Set the 'invoke all eagers' flag which causes joined- and
  1007. subquery loaders to traverse into already-loaded related objects
  1008. and collections.
  1009. Default is that of :attr:`_query.Query._invoke_all_eagers`.
  1010. """
  1011. self.load_options += {"_invoke_all_eagers": value}
  1012. return self
  1013. @util.became_legacy_20(
  1014. ":meth:`_orm.Query.with_parent`",
  1015. alternative="Use the :func:`_orm.with_parent` standalone construct.",
  1016. )
  1017. @util.preload_module("sqlalchemy.orm.relationships")
  1018. def with_parent(
  1019. self,
  1020. instance: object,
  1021. property: Optional[ # noqa: A002
  1022. attributes.QueryableAttribute[Any]
  1023. ] = None,
  1024. from_entity: Optional[_ExternalEntityType[Any]] = None,
  1025. ) -> Self:
  1026. """Add filtering criterion that relates the given instance
  1027. to a child object or collection, using its attribute state
  1028. as well as an established :func:`_orm.relationship()`
  1029. configuration.
  1030. The method uses the :func:`.with_parent` function to generate
  1031. the clause, the result of which is passed to
  1032. :meth:`_query.Query.filter`.
  1033. Parameters are the same as :func:`.with_parent`, with the exception
  1034. that the given property can be None, in which case a search is
  1035. performed against this :class:`_query.Query` object's target mapper.
  1036. :param instance:
  1037. An instance which has some :func:`_orm.relationship`.
  1038. :param property:
  1039. Class bound attribute which indicates
  1040. what relationship from the instance should be used to reconcile the
  1041. parent/child relationship.
  1042. :param from_entity:
  1043. Entity in which to consider as the left side. This defaults to the
  1044. "zero" entity of the :class:`_query.Query` itself.
  1045. """
  1046. relationships = util.preloaded.orm_relationships
  1047. if from_entity:
  1048. entity_zero = inspect(from_entity)
  1049. else:
  1050. entity_zero = _legacy_filter_by_entity_zero(self)
  1051. if property is None:
  1052. # TODO: deprecate, property has to be supplied
  1053. mapper = object_mapper(instance)
  1054. for prop in mapper.iterate_properties:
  1055. if (
  1056. isinstance(prop, relationships.RelationshipProperty)
  1057. and prop.mapper is entity_zero.mapper # type: ignore
  1058. ):
  1059. property = prop # type: ignore # noqa: A001
  1060. break
  1061. else:
  1062. raise sa_exc.InvalidRequestError(
  1063. "Could not locate a property which relates instances "
  1064. "of class '%s' to instances of class '%s'"
  1065. % (
  1066. entity_zero.mapper.class_.__name__, # type: ignore
  1067. instance.__class__.__name__,
  1068. )
  1069. )
  1070. return self.filter(
  1071. with_parent(
  1072. instance,
  1073. property, # type: ignore
  1074. entity_zero.entity, # type: ignore
  1075. )
  1076. )
  1077. @_generative
  1078. def add_entity(
  1079. self,
  1080. entity: _EntityType[Any],
  1081. alias: Optional[Union[Alias, Subquery]] = None,
  1082. ) -> Query[Any]:
  1083. """add a mapped entity to the list of result columns
  1084. to be returned.
  1085. .. seealso::
  1086. :meth:`_sql.Select.add_columns` - v2 comparable method.
  1087. """
  1088. if alias is not None:
  1089. # TODO: deprecate
  1090. entity = AliasedClass(entity, alias)
  1091. self._raw_columns = list(self._raw_columns)
  1092. self._raw_columns.append(
  1093. coercions.expect(
  1094. roles.ColumnsClauseRole, entity, apply_propagate_attrs=self
  1095. )
  1096. )
  1097. return self
  1098. @_generative
  1099. def with_session(self, session: Session) -> Self:
  1100. """Return a :class:`_query.Query` that will use the given
  1101. :class:`.Session`.
  1102. While the :class:`_query.Query`
  1103. object is normally instantiated using the
  1104. :meth:`.Session.query` method, it is legal to build the
  1105. :class:`_query.Query`
  1106. directly without necessarily using a :class:`.Session`. Such a
  1107. :class:`_query.Query` object, or any :class:`_query.Query`
  1108. already associated
  1109. with a different :class:`.Session`, can produce a new
  1110. :class:`_query.Query`
  1111. object associated with a target session using this method::
  1112. from sqlalchemy.orm import Query
  1113. query = Query([MyClass]).filter(MyClass.id == 5)
  1114. result = query.with_session(my_session).one()
  1115. """
  1116. self.session = session
  1117. return self
  1118. def _legacy_from_self(
  1119. self, *entities: _ColumnsClauseArgument[Any]
  1120. ) -> Self:
  1121. # used for query.count() as well as for the same
  1122. # function in BakedQuery, as well as some old tests in test_baked.py.
  1123. fromclause = (
  1124. self.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  1125. .correlate(None)
  1126. .subquery()
  1127. ._anonymous_fromclause()
  1128. )
  1129. q = self._from_selectable(fromclause)
  1130. if entities:
  1131. q._set_entities(entities)
  1132. return q
  1133. @_generative
  1134. def _set_enable_single_crit(self, val: bool) -> Self:
  1135. self._compile_options += {"_enable_single_crit": val}
  1136. return self
  1137. @_generative
  1138. def _from_selectable(
  1139. self, fromclause: FromClause, set_entity_from: bool = True
  1140. ) -> Self:
  1141. for attr in (
  1142. "_where_criteria",
  1143. "_order_by_clauses",
  1144. "_group_by_clauses",
  1145. "_limit_clause",
  1146. "_offset_clause",
  1147. "_last_joined_entity",
  1148. "_setup_joins",
  1149. "_memoized_select_entities",
  1150. "_distinct",
  1151. "_distinct_on",
  1152. "_having_criteria",
  1153. "_prefixes",
  1154. "_suffixes",
  1155. ):
  1156. self.__dict__.pop(attr, None)
  1157. self._set_select_from([fromclause], set_entity_from)
  1158. self._compile_options += {
  1159. "_enable_single_crit": False,
  1160. }
  1161. return self
  1162. @util.deprecated(
  1163. "1.4",
  1164. ":meth:`_query.Query.values` "
  1165. "is deprecated and will be removed in a "
  1166. "future release. Please use :meth:`_query.Query.with_entities`",
  1167. )
  1168. def values(self, *columns: _ColumnsClauseArgument[Any]) -> Iterable[Any]:
  1169. """Return an iterator yielding result tuples corresponding
  1170. to the given list of columns
  1171. """
  1172. return self._values_no_warn(*columns)
  1173. _values = values
  1174. def _values_no_warn(
  1175. self, *columns: _ColumnsClauseArgument[Any]
  1176. ) -> Iterable[Any]:
  1177. if not columns:
  1178. return iter(())
  1179. q = self._clone().enable_eagerloads(False)
  1180. q._set_entities(columns)
  1181. if not q.load_options._yield_per:
  1182. q.load_options += {"_yield_per": 10}
  1183. return iter(q)
  1184. @util.deprecated(
  1185. "1.4",
  1186. ":meth:`_query.Query.value` "
  1187. "is deprecated and will be removed in a "
  1188. "future release. Please use :meth:`_query.Query.with_entities` "
  1189. "in combination with :meth:`_query.Query.scalar`",
  1190. )
  1191. def value(self, column: _ColumnExpressionArgument[Any]) -> Any:
  1192. """Return a scalar result corresponding to the given
  1193. column expression.
  1194. """
  1195. try:
  1196. return next(self._values_no_warn(column))[0] # type: ignore
  1197. except StopIteration:
  1198. return None
  1199. @overload
  1200. def with_entities(self, _entity: _EntityType[_O]) -> Query[_O]:
  1201. ...
  1202. @overload
  1203. def with_entities(
  1204. self,
  1205. _colexpr: roles.TypedColumnsClauseRole[_T],
  1206. ) -> RowReturningQuery[Tuple[_T]]:
  1207. ...
  1208. # START OVERLOADED FUNCTIONS self.with_entities RowReturningQuery 2-8
  1209. # code within this block is **programmatically,
  1210. # statically generated** by tools/generate_tuple_map_overloads.py
  1211. @overload
  1212. def with_entities(
  1213. self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1]
  1214. ) -> RowReturningQuery[Tuple[_T0, _T1]]:
  1215. ...
  1216. @overload
  1217. def with_entities(
  1218. self, __ent0: _TCCA[_T0], __ent1: _TCCA[_T1], __ent2: _TCCA[_T2]
  1219. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2]]:
  1220. ...
  1221. @overload
  1222. def with_entities(
  1223. self,
  1224. __ent0: _TCCA[_T0],
  1225. __ent1: _TCCA[_T1],
  1226. __ent2: _TCCA[_T2],
  1227. __ent3: _TCCA[_T3],
  1228. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3]]:
  1229. ...
  1230. @overload
  1231. def with_entities(
  1232. self,
  1233. __ent0: _TCCA[_T0],
  1234. __ent1: _TCCA[_T1],
  1235. __ent2: _TCCA[_T2],
  1236. __ent3: _TCCA[_T3],
  1237. __ent4: _TCCA[_T4],
  1238. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4]]:
  1239. ...
  1240. @overload
  1241. def with_entities(
  1242. self,
  1243. __ent0: _TCCA[_T0],
  1244. __ent1: _TCCA[_T1],
  1245. __ent2: _TCCA[_T2],
  1246. __ent3: _TCCA[_T3],
  1247. __ent4: _TCCA[_T4],
  1248. __ent5: _TCCA[_T5],
  1249. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]:
  1250. ...
  1251. @overload
  1252. def with_entities(
  1253. self,
  1254. __ent0: _TCCA[_T0],
  1255. __ent1: _TCCA[_T1],
  1256. __ent2: _TCCA[_T2],
  1257. __ent3: _TCCA[_T3],
  1258. __ent4: _TCCA[_T4],
  1259. __ent5: _TCCA[_T5],
  1260. __ent6: _TCCA[_T6],
  1261. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]:
  1262. ...
  1263. @overload
  1264. def with_entities(
  1265. self,
  1266. __ent0: _TCCA[_T0],
  1267. __ent1: _TCCA[_T1],
  1268. __ent2: _TCCA[_T2],
  1269. __ent3: _TCCA[_T3],
  1270. __ent4: _TCCA[_T4],
  1271. __ent5: _TCCA[_T5],
  1272. __ent6: _TCCA[_T6],
  1273. __ent7: _TCCA[_T7],
  1274. ) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]:
  1275. ...
  1276. # END OVERLOADED FUNCTIONS self.with_entities
  1277. @overload
  1278. def with_entities(
  1279. self, *entities: _ColumnsClauseArgument[Any]
  1280. ) -> Query[Any]:
  1281. ...
  1282. @_generative
  1283. def with_entities(
  1284. self, *entities: _ColumnsClauseArgument[Any], **__kw: Any
  1285. ) -> Query[Any]:
  1286. r"""Return a new :class:`_query.Query`
  1287. replacing the SELECT list with the
  1288. given entities.
  1289. e.g.::
  1290. # Users, filtered on some arbitrary criterion
  1291. # and then ordered by related email address
  1292. q = session.query(User).\
  1293. join(User.address).\
  1294. filter(User.name.like('%ed%')).\
  1295. order_by(Address.email)
  1296. # given *only* User.id==5, Address.email, and 'q', what
  1297. # would the *next* User in the result be ?
  1298. subq = q.with_entities(Address.email).\
  1299. order_by(None).\
  1300. filter(User.id==5).\
  1301. subquery()
  1302. q = q.join((subq, subq.c.email < Address.email)).\
  1303. limit(1)
  1304. .. seealso::
  1305. :meth:`_sql.Select.with_only_columns` - v2 comparable method.
  1306. """
  1307. if __kw:
  1308. raise _no_kw()
  1309. # Query has all the same fields as Select for this operation
  1310. # this could in theory be based on a protocol but not sure if it's
  1311. # worth it
  1312. _MemoizedSelectEntities._generate_for_statement(self) # type: ignore
  1313. self._set_entities(entities)
  1314. return self
  1315. @_generative
  1316. def add_columns(
  1317. self, *column: _ColumnExpressionArgument[Any]
  1318. ) -> Query[Any]:
  1319. """Add one or more column expressions to the list
  1320. of result columns to be returned.
  1321. .. seealso::
  1322. :meth:`_sql.Select.add_columns` - v2 comparable method.
  1323. """
  1324. self._raw_columns = list(self._raw_columns)
  1325. self._raw_columns.extend(
  1326. coercions.expect(
  1327. roles.ColumnsClauseRole,
  1328. c,
  1329. apply_propagate_attrs=self,
  1330. post_inspect=True,
  1331. )
  1332. for c in column
  1333. )
  1334. return self
  1335. @util.deprecated(
  1336. "1.4",
  1337. ":meth:`_query.Query.add_column` "
  1338. "is deprecated and will be removed in a "
  1339. "future release. Please use :meth:`_query.Query.add_columns`",
  1340. )
  1341. def add_column(self, column: _ColumnExpressionArgument[Any]) -> Query[Any]:
  1342. """Add a column expression to the list of result columns to be
  1343. returned.
  1344. """
  1345. return self.add_columns(column)
  1346. @_generative
  1347. def options(self, *args: ExecutableOption) -> Self:
  1348. """Return a new :class:`_query.Query` object,
  1349. applying the given list of
  1350. mapper options.
  1351. Most supplied options regard changing how column- and
  1352. relationship-mapped attributes are loaded.
  1353. .. seealso::
  1354. :ref:`loading_columns`
  1355. :ref:`relationship_loader_options`
  1356. """
  1357. opts = tuple(util.flatten_iterator(args))
  1358. if self._compile_options._current_path:
  1359. # opting for lower method overhead for the checks
  1360. for opt in opts:
  1361. if not opt._is_core and opt._is_legacy_option: # type: ignore
  1362. opt.process_query_conditionally(self) # type: ignore
  1363. else:
  1364. for opt in opts:
  1365. if not opt._is_core and opt._is_legacy_option: # type: ignore
  1366. opt.process_query(self) # type: ignore
  1367. self._with_options += opts
  1368. return self
  1369. def with_transformation(
  1370. self, fn: Callable[[Query[Any]], Query[Any]]
  1371. ) -> Query[Any]:
  1372. """Return a new :class:`_query.Query` object transformed by
  1373. the given function.
  1374. E.g.::
  1375. def filter_something(criterion):
  1376. def transform(q):
  1377. return q.filter(criterion)
  1378. return transform
  1379. q = q.with_transformation(filter_something(x==5))
  1380. This allows ad-hoc recipes to be created for :class:`_query.Query`
  1381. objects.
  1382. """
  1383. return fn(self)
  1384. def get_execution_options(self) -> _ImmutableExecuteOptions:
  1385. """Get the non-SQL options which will take effect during execution.
  1386. .. versionadded:: 1.3
  1387. .. seealso::
  1388. :meth:`_query.Query.execution_options`
  1389. :meth:`_sql.Select.get_execution_options` - v2 comparable method.
  1390. """
  1391. return self._execution_options
  1392. @overload
  1393. def execution_options(
  1394. self,
  1395. *,
  1396. compiled_cache: Optional[CompiledCacheType] = ...,
  1397. logging_token: str = ...,
  1398. isolation_level: IsolationLevel = ...,
  1399. no_parameters: bool = False,
  1400. stream_results: bool = False,
  1401. max_row_buffer: int = ...,
  1402. yield_per: int = ...,
  1403. insertmanyvalues_page_size: int = ...,
  1404. schema_translate_map: Optional[SchemaTranslateMapType] = ...,
  1405. populate_existing: bool = False,
  1406. autoflush: bool = False,
  1407. **opt: Any,
  1408. ) -> Self:
  1409. ...
  1410. @overload
  1411. def execution_options(self, **opt: Any) -> Self:
  1412. ...
  1413. @_generative
  1414. def execution_options(self, **kwargs: Any) -> Self:
  1415. """Set non-SQL options which take effect during execution.
  1416. Options allowed here include all of those accepted by
  1417. :meth:`_engine.Connection.execution_options`, as well as a series
  1418. of ORM specific options:
  1419. ``populate_existing=True`` - equivalent to using
  1420. :meth:`_orm.Query.populate_existing`
  1421. ``autoflush=True|False`` - equivalent to using
  1422. :meth:`_orm.Query.autoflush`
  1423. ``yield_per=<value>`` - equivalent to using
  1424. :meth:`_orm.Query.yield_per`
  1425. Note that the ``stream_results`` execution option is enabled
  1426. automatically if the :meth:`~sqlalchemy.orm.query.Query.yield_per()`
  1427. method or execution option is used.
  1428. .. versionadded:: 1.4 - added ORM options to
  1429. :meth:`_orm.Query.execution_options`
  1430. The execution options may also be specified on a per execution basis
  1431. when using :term:`2.0 style` queries via the
  1432. :paramref:`_orm.Session.execution_options` parameter.
  1433. .. warning:: The
  1434. :paramref:`_engine.Connection.execution_options.stream_results`
  1435. parameter should not be used at the level of individual ORM
  1436. statement executions, as the :class:`_orm.Session` will not track
  1437. objects from different schema translate maps within a single
  1438. session. For multiple schema translate maps within the scope of a
  1439. single :class:`_orm.Session`, see :ref:`examples_sharding`.
  1440. .. seealso::
  1441. :ref:`engine_stream_results`
  1442. :meth:`_query.Query.get_execution_options`
  1443. :meth:`_sql.Select.execution_options` - v2 equivalent method.
  1444. """
  1445. self._execution_options = self._execution_options.union(kwargs)
  1446. return self
  1447. @_generative
  1448. def with_for_update(
  1449. self,
  1450. *,
  1451. nowait: bool = False,
  1452. read: bool = False,
  1453. of: Optional[_ForUpdateOfArgument] = None,
  1454. skip_locked: bool = False,
  1455. key_share: bool = False,
  1456. ) -> Self:
  1457. """return a new :class:`_query.Query`
  1458. with the specified options for the
  1459. ``FOR UPDATE`` clause.
  1460. The behavior of this method is identical to that of
  1461. :meth:`_expression.GenerativeSelect.with_for_update`.
  1462. When called with no arguments,
  1463. the resulting ``SELECT`` statement will have a ``FOR UPDATE`` clause
  1464. appended. When additional arguments are specified, backend-specific
  1465. options such as ``FOR UPDATE NOWAIT`` or ``LOCK IN SHARE MODE``
  1466. can take effect.
  1467. E.g.::
  1468. q = sess.query(User).populate_existing().with_for_update(nowait=True, of=User)
  1469. The above query on a PostgreSQL backend will render like::
  1470. SELECT users.id AS users_id FROM users FOR UPDATE OF users NOWAIT
  1471. .. warning::
  1472. Using ``with_for_update`` in the context of eager loading
  1473. relationships is not officially supported or recommended by
  1474. SQLAlchemy and may not work with certain queries on various
  1475. database backends. When ``with_for_update`` is successfully used
  1476. with a query that involves :func:`_orm.joinedload`, SQLAlchemy will
  1477. attempt to emit SQL that locks all involved tables.
  1478. .. note:: It is generally a good idea to combine the use of the
  1479. :meth:`_orm.Query.populate_existing` method when using the
  1480. :meth:`_orm.Query.with_for_update` method. The purpose of
  1481. :meth:`_orm.Query.populate_existing` is to force all the data read
  1482. from the SELECT to be populated into the ORM objects returned,
  1483. even if these objects are already in the :term:`identity map`.
  1484. .. seealso::
  1485. :meth:`_expression.GenerativeSelect.with_for_update`
  1486. - Core level method with
  1487. full argument and behavioral description.
  1488. :meth:`_orm.Query.populate_existing` - overwrites attributes of
  1489. objects already loaded in the identity map.
  1490. """ # noqa: E501
  1491. self._for_update_arg = ForUpdateArg(
  1492. read=read,
  1493. nowait=nowait,
  1494. of=of,
  1495. skip_locked=skip_locked,
  1496. key_share=key_share,
  1497. )
  1498. return self
  1499. @_generative
  1500. def params(
  1501. self, __params: Optional[Dict[str, Any]] = None, **kw: Any
  1502. ) -> Self:
  1503. r"""Add values for bind parameters which may have been
  1504. specified in filter().
  1505. Parameters may be specified using \**kwargs, or optionally a single
  1506. dictionary as the first positional argument. The reason for both is
  1507. that \**kwargs is convenient, however some parameter dictionaries
  1508. contain unicode keys in which case \**kwargs cannot be used.
  1509. """
  1510. if __params:
  1511. kw.update(__params)
  1512. self._params = self._params.union(kw)
  1513. return self
  1514. def where(self, *criterion: _ColumnExpressionArgument[bool]) -> Self:
  1515. """A synonym for :meth:`.Query.filter`.
  1516. .. versionadded:: 1.4
  1517. .. seealso::
  1518. :meth:`_sql.Select.where` - v2 equivalent method.
  1519. """
  1520. return self.filter(*criterion)
  1521. @_generative
  1522. @_assertions(_no_statement_condition, _no_limit_offset)
  1523. def filter(self, *criterion: _ColumnExpressionArgument[bool]) -> Self:
  1524. r"""Apply the given filtering criterion to a copy
  1525. of this :class:`_query.Query`, using SQL expressions.
  1526. e.g.::
  1527. session.query(MyClass).filter(MyClass.name == 'some name')
  1528. Multiple criteria may be specified as comma separated; the effect
  1529. is that they will be joined together using the :func:`.and_`
  1530. function::
  1531. session.query(MyClass).\
  1532. filter(MyClass.name == 'some name', MyClass.id > 5)
  1533. The criterion is any SQL expression object applicable to the
  1534. WHERE clause of a select. String expressions are coerced
  1535. into SQL expression constructs via the :func:`_expression.text`
  1536. construct.
  1537. .. seealso::
  1538. :meth:`_query.Query.filter_by` - filter on keyword expressions.
  1539. :meth:`_sql.Select.where` - v2 equivalent method.
  1540. """
  1541. for crit in list(criterion):
  1542. crit = coercions.expect(
  1543. roles.WhereHavingRole, crit, apply_propagate_attrs=self
  1544. )
  1545. self._where_criteria += (crit,)
  1546. return self
  1547. @util.memoized_property
  1548. def _last_joined_entity(
  1549. self,
  1550. ) -> Optional[Union[_InternalEntityType[Any], _JoinTargetElement]]:
  1551. if self._setup_joins:
  1552. return _determine_last_joined_entity(
  1553. self._setup_joins,
  1554. )
  1555. else:
  1556. return None
  1557. def _filter_by_zero(self) -> Any:
  1558. """for the filter_by() method, return the target entity for which
  1559. we will attempt to derive an expression from based on string name.
  1560. """
  1561. if self._setup_joins:
  1562. _last_joined_entity = self._last_joined_entity
  1563. if _last_joined_entity is not None:
  1564. return _last_joined_entity
  1565. # discussion related to #7239
  1566. # special check determines if we should try to derive attributes
  1567. # for filter_by() from the "from object", i.e., if the user
  1568. # called query.select_from(some selectable).filter_by(some_attr=value).
  1569. # We don't want to do that in the case that methods like
  1570. # from_self(), select_entity_from(), or a set op like union() were
  1571. # called; while these methods also place a
  1572. # selectable in the _from_obj collection, they also set up
  1573. # the _set_base_alias boolean which turns on the whole "adapt the
  1574. # entity to this selectable" thing, meaning the query still continues
  1575. # to construct itself in terms of the lead entity that was passed
  1576. # to query(), e.g. query(User).from_self() is still in terms of User,
  1577. # and not the subquery that from_self() created. This feature of
  1578. # "implicitly adapt all occurrences of entity X to some arbitrary
  1579. # subquery" is the main thing I am trying to do away with in 2.0 as
  1580. # users should now used aliased() for that, but I can't entirely get
  1581. # rid of it due to query.union() and other set ops relying upon it.
  1582. #
  1583. # compare this to the base Select()._filter_by_zero() which can
  1584. # just return self._from_obj[0] if present, because there is no
  1585. # "_set_base_alias" feature.
  1586. #
  1587. # IOW, this conditional essentially detects if
  1588. # "select_from(some_selectable)" has been called, as opposed to
  1589. # "select_entity_from()", "from_self()"
  1590. # or "union() / some_set_op()".
  1591. if self._from_obj and not self._compile_options._set_base_alias:
  1592. return self._from_obj[0]
  1593. return self._raw_columns[0]
  1594. def filter_by(self, **kwargs: Any) -> Self:
  1595. r"""Apply the given filtering criterion to a copy
  1596. of this :class:`_query.Query`, using keyword expressions.
  1597. e.g.::
  1598. session.query(MyClass).filter_by(name = 'some name')
  1599. Multiple criteria may be specified as comma separated; the effect
  1600. is that they will be joined together using the :func:`.and_`
  1601. function::
  1602. session.query(MyClass).\
  1603. filter_by(name = 'some name', id = 5)
  1604. The keyword expressions are extracted from the primary
  1605. entity of the query, or the last entity that was the
  1606. target of a call to :meth:`_query.Query.join`.
  1607. .. seealso::
  1608. :meth:`_query.Query.filter` - filter on SQL expressions.
  1609. :meth:`_sql.Select.filter_by` - v2 comparable method.
  1610. """
  1611. from_entity = self._filter_by_zero()
  1612. clauses = [
  1613. _entity_namespace_key(from_entity, key) == value
  1614. for key, value in kwargs.items()
  1615. ]
  1616. return self.filter(*clauses)
  1617. @_generative
  1618. def order_by(
  1619. self,
  1620. __first: Union[
  1621. Literal[None, False, _NoArg.NO_ARG],
  1622. _ColumnExpressionOrStrLabelArgument[Any],
  1623. ] = _NoArg.NO_ARG,
  1624. *clauses: _ColumnExpressionOrStrLabelArgument[Any],
  1625. ) -> Self:
  1626. """Apply one or more ORDER BY criteria to the query and return
  1627. the newly resulting :class:`_query.Query`.
  1628. e.g.::
  1629. q = session.query(Entity).order_by(Entity.id, Entity.name)
  1630. Calling this method multiple times is equivalent to calling it once
  1631. with all the clauses concatenated. All existing ORDER BY criteria may
  1632. be cancelled by passing ``None`` by itself. New ORDER BY criteria may
  1633. then be added by invoking :meth:`_orm.Query.order_by` again, e.g.::
  1634. # will erase all ORDER BY and ORDER BY new_col alone
  1635. q = q.order_by(None).order_by(new_col)
  1636. .. seealso::
  1637. These sections describe ORDER BY in terms of :term:`2.0 style`
  1638. invocation but apply to :class:`_orm.Query` as well:
  1639. :ref:`tutorial_order_by` - in the :ref:`unified_tutorial`
  1640. :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
  1641. :meth:`_sql.Select.order_by` - v2 equivalent method.
  1642. """
  1643. for assertion in (self._no_statement_condition, self._no_limit_offset):
  1644. assertion("order_by")
  1645. if not clauses and (__first is None or __first is False):
  1646. self._order_by_clauses = ()
  1647. elif __first is not _NoArg.NO_ARG:
  1648. criterion = tuple(
  1649. coercions.expect(roles.OrderByRole, clause)
  1650. for clause in (__first,) + clauses
  1651. )
  1652. self._order_by_clauses += criterion
  1653. return self
  1654. @_generative
  1655. def group_by(
  1656. self,
  1657. __first: Union[
  1658. Literal[None, False, _NoArg.NO_ARG],
  1659. _ColumnExpressionOrStrLabelArgument[Any],
  1660. ] = _NoArg.NO_ARG,
  1661. *clauses: _ColumnExpressionOrStrLabelArgument[Any],
  1662. ) -> Self:
  1663. """Apply one or more GROUP BY criterion to the query and return
  1664. the newly resulting :class:`_query.Query`.
  1665. All existing GROUP BY settings can be suppressed by
  1666. passing ``None`` - this will suppress any GROUP BY configured
  1667. on mappers as well.
  1668. .. seealso::
  1669. These sections describe GROUP BY in terms of :term:`2.0 style`
  1670. invocation but apply to :class:`_orm.Query` as well:
  1671. :ref:`tutorial_group_by_w_aggregates` - in the
  1672. :ref:`unified_tutorial`
  1673. :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
  1674. :meth:`_sql.Select.group_by` - v2 equivalent method.
  1675. """
  1676. for assertion in (self._no_statement_condition, self._no_limit_offset):
  1677. assertion("group_by")
  1678. if not clauses and (__first is None or __first is False):
  1679. self._group_by_clauses = ()
  1680. elif __first is not _NoArg.NO_ARG:
  1681. criterion = tuple(
  1682. coercions.expect(roles.GroupByRole, clause)
  1683. for clause in (__first,) + clauses
  1684. )
  1685. self._group_by_clauses += criterion
  1686. return self
  1687. @_generative
  1688. @_assertions(_no_statement_condition, _no_limit_offset)
  1689. def having(self, *having: _ColumnExpressionArgument[bool]) -> Self:
  1690. r"""Apply a HAVING criterion to the query and return the
  1691. newly resulting :class:`_query.Query`.
  1692. :meth:`_query.Query.having` is used in conjunction with
  1693. :meth:`_query.Query.group_by`.
  1694. HAVING criterion makes it possible to use filters on aggregate
  1695. functions like COUNT, SUM, AVG, MAX, and MIN, eg.::
  1696. q = session.query(User.id).\
  1697. join(User.addresses).\
  1698. group_by(User.id).\
  1699. having(func.count(Address.id) > 2)
  1700. .. seealso::
  1701. :meth:`_sql.Select.having` - v2 equivalent method.
  1702. """
  1703. for criterion in having:
  1704. having_criteria = coercions.expect(
  1705. roles.WhereHavingRole, criterion
  1706. )
  1707. self._having_criteria += (having_criteria,)
  1708. return self
  1709. def _set_op(self, expr_fn: Any, *q: Query[Any]) -> Self:
  1710. list_of_queries = (self,) + q
  1711. return self._from_selectable(expr_fn(*(list_of_queries)).subquery())
  1712. def union(self, *q: Query[Any]) -> Self:
  1713. """Produce a UNION of this Query against one or more queries.
  1714. e.g.::
  1715. q1 = sess.query(SomeClass).filter(SomeClass.foo=='bar')
  1716. q2 = sess.query(SomeClass).filter(SomeClass.bar=='foo')
  1717. q3 = q1.union(q2)
  1718. The method accepts multiple Query objects so as to control
  1719. the level of nesting. A series of ``union()`` calls such as::
  1720. x.union(y).union(z).all()
  1721. will nest on each ``union()``, and produces::
  1722. SELECT * FROM (SELECT * FROM (SELECT * FROM X UNION
  1723. SELECT * FROM y) UNION SELECT * FROM Z)
  1724. Whereas::
  1725. x.union(y, z).all()
  1726. produces::
  1727. SELECT * FROM (SELECT * FROM X UNION SELECT * FROM y UNION
  1728. SELECT * FROM Z)
  1729. Note that many database backends do not allow ORDER BY to
  1730. be rendered on a query called within UNION, EXCEPT, etc.
  1731. To disable all ORDER BY clauses including those configured
  1732. on mappers, issue ``query.order_by(None)`` - the resulting
  1733. :class:`_query.Query` object will not render ORDER BY within
  1734. its SELECT statement.
  1735. .. seealso::
  1736. :meth:`_sql.Select.union` - v2 equivalent method.
  1737. """
  1738. return self._set_op(expression.union, *q)
  1739. def union_all(self, *q: Query[Any]) -> Self:
  1740. """Produce a UNION ALL of this Query against one or more queries.
  1741. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
  1742. that method for usage examples.
  1743. .. seealso::
  1744. :meth:`_sql.Select.union_all` - v2 equivalent method.
  1745. """
  1746. return self._set_op(expression.union_all, *q)
  1747. def intersect(self, *q: Query[Any]) -> Self:
  1748. """Produce an INTERSECT of this Query against one or more queries.
  1749. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
  1750. that method for usage examples.
  1751. .. seealso::
  1752. :meth:`_sql.Select.intersect` - v2 equivalent method.
  1753. """
  1754. return self._set_op(expression.intersect, *q)
  1755. def intersect_all(self, *q: Query[Any]) -> Self:
  1756. """Produce an INTERSECT ALL of this Query against one or more queries.
  1757. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
  1758. that method for usage examples.
  1759. .. seealso::
  1760. :meth:`_sql.Select.intersect_all` - v2 equivalent method.
  1761. """
  1762. return self._set_op(expression.intersect_all, *q)
  1763. def except_(self, *q: Query[Any]) -> Self:
  1764. """Produce an EXCEPT of this Query against one or more queries.
  1765. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
  1766. that method for usage examples.
  1767. .. seealso::
  1768. :meth:`_sql.Select.except_` - v2 equivalent method.
  1769. """
  1770. return self._set_op(expression.except_, *q)
  1771. def except_all(self, *q: Query[Any]) -> Self:
  1772. """Produce an EXCEPT ALL of this Query against one or more queries.
  1773. Works the same way as :meth:`~sqlalchemy.orm.query.Query.union`. See
  1774. that method for usage examples.
  1775. .. seealso::
  1776. :meth:`_sql.Select.except_all` - v2 equivalent method.
  1777. """
  1778. return self._set_op(expression.except_all, *q)
  1779. @_generative
  1780. @_assertions(_no_statement_condition, _no_limit_offset)
  1781. def join(
  1782. self,
  1783. target: _JoinTargetArgument,
  1784. onclause: Optional[_OnClauseArgument] = None,
  1785. *,
  1786. isouter: bool = False,
  1787. full: bool = False,
  1788. ) -> Self:
  1789. r"""Create a SQL JOIN against this :class:`_query.Query`
  1790. object's criterion
  1791. and apply generatively, returning the newly resulting
  1792. :class:`_query.Query`.
  1793. **Simple Relationship Joins**
  1794. Consider a mapping between two classes ``User`` and ``Address``,
  1795. with a relationship ``User.addresses`` representing a collection
  1796. of ``Address`` objects associated with each ``User``. The most
  1797. common usage of :meth:`_query.Query.join`
  1798. is to create a JOIN along this
  1799. relationship, using the ``User.addresses`` attribute as an indicator
  1800. for how this should occur::
  1801. q = session.query(User).join(User.addresses)
  1802. Where above, the call to :meth:`_query.Query.join` along
  1803. ``User.addresses`` will result in SQL approximately equivalent to::
  1804. SELECT user.id, user.name
  1805. FROM user JOIN address ON user.id = address.user_id
  1806. In the above example we refer to ``User.addresses`` as passed to
  1807. :meth:`_query.Query.join` as the "on clause", that is, it indicates
  1808. how the "ON" portion of the JOIN should be constructed.
  1809. To construct a chain of joins, multiple :meth:`_query.Query.join`
  1810. calls may be used. The relationship-bound attribute implies both
  1811. the left and right side of the join at once::
  1812. q = session.query(User).\
  1813. join(User.orders).\
  1814. join(Order.items).\
  1815. join(Item.keywords)
  1816. .. note:: as seen in the above example, **the order in which each
  1817. call to the join() method occurs is important**. Query would not,
  1818. for example, know how to join correctly if we were to specify
  1819. ``User``, then ``Item``, then ``Order``, in our chain of joins; in
  1820. such a case, depending on the arguments passed, it may raise an
  1821. error that it doesn't know how to join, or it may produce invalid
  1822. SQL in which case the database will raise an error. In correct
  1823. practice, the
  1824. :meth:`_query.Query.join` method is invoked in such a way that lines
  1825. up with how we would want the JOIN clauses in SQL to be
  1826. rendered, and each call should represent a clear link from what
  1827. precedes it.
  1828. **Joins to a Target Entity or Selectable**
  1829. A second form of :meth:`_query.Query.join` allows any mapped entity or
  1830. core selectable construct as a target. In this usage,
  1831. :meth:`_query.Query.join` will attempt to create a JOIN along the
  1832. natural foreign key relationship between two entities::
  1833. q = session.query(User).join(Address)
  1834. In the above calling form, :meth:`_query.Query.join` is called upon to
  1835. create the "on clause" automatically for us. This calling form will
  1836. ultimately raise an error if either there are no foreign keys between
  1837. the two entities, or if there are multiple foreign key linkages between
  1838. the target entity and the entity or entities already present on the
  1839. left side such that creating a join requires more information. Note
  1840. that when indicating a join to a target without any ON clause, ORM
  1841. configured relationships are not taken into account.
  1842. **Joins to a Target with an ON Clause**
  1843. The third calling form allows both the target entity as well
  1844. as the ON clause to be passed explicitly. A example that includes
  1845. a SQL expression as the ON clause is as follows::
  1846. q = session.query(User).join(Address, User.id==Address.user_id)
  1847. The above form may also use a relationship-bound attribute as the
  1848. ON clause as well::
  1849. q = session.query(User).join(Address, User.addresses)
  1850. The above syntax can be useful for the case where we wish
  1851. to join to an alias of a particular target entity. If we wanted
  1852. to join to ``Address`` twice, it could be achieved using two
  1853. aliases set up using the :func:`~sqlalchemy.orm.aliased` function::
  1854. a1 = aliased(Address)
  1855. a2 = aliased(Address)
  1856. q = session.query(User).\
  1857. join(a1, User.addresses).\
  1858. join(a2, User.addresses).\
  1859. filter(a1.email_address=='ed@foo.com').\
  1860. filter(a2.email_address=='ed@bar.com')
  1861. The relationship-bound calling form can also specify a target entity
  1862. using the :meth:`_orm.PropComparator.of_type` method; a query
  1863. equivalent to the one above would be::
  1864. a1 = aliased(Address)
  1865. a2 = aliased(Address)
  1866. q = session.query(User).\
  1867. join(User.addresses.of_type(a1)).\
  1868. join(User.addresses.of_type(a2)).\
  1869. filter(a1.email_address == 'ed@foo.com').\
  1870. filter(a2.email_address == 'ed@bar.com')
  1871. **Augmenting Built-in ON Clauses**
  1872. As a substitute for providing a full custom ON condition for an
  1873. existing relationship, the :meth:`_orm.PropComparator.and_` function
  1874. may be applied to a relationship attribute to augment additional
  1875. criteria into the ON clause; the additional criteria will be combined
  1876. with the default criteria using AND::
  1877. q = session.query(User).join(
  1878. User.addresses.and_(Address.email_address != 'foo@bar.com')
  1879. )
  1880. .. versionadded:: 1.4
  1881. **Joining to Tables and Subqueries**
  1882. The target of a join may also be any table or SELECT statement,
  1883. which may be related to a target entity or not. Use the
  1884. appropriate ``.subquery()`` method in order to make a subquery
  1885. out of a query::
  1886. subq = session.query(Address).\
  1887. filter(Address.email_address == 'ed@foo.com').\
  1888. subquery()
  1889. q = session.query(User).join(
  1890. subq, User.id == subq.c.user_id
  1891. )
  1892. Joining to a subquery in terms of a specific relationship and/or
  1893. target entity may be achieved by linking the subquery to the
  1894. entity using :func:`_orm.aliased`::
  1895. subq = session.query(Address).\
  1896. filter(Address.email_address == 'ed@foo.com').\
  1897. subquery()
  1898. address_subq = aliased(Address, subq)
  1899. q = session.query(User).join(
  1900. User.addresses.of_type(address_subq)
  1901. )
  1902. **Controlling what to Join From**
  1903. In cases where the left side of the current state of
  1904. :class:`_query.Query` is not in line with what we want to join from,
  1905. the :meth:`_query.Query.select_from` method may be used::
  1906. q = session.query(Address).select_from(User).\
  1907. join(User.addresses).\
  1908. filter(User.name == 'ed')
  1909. Which will produce SQL similar to::
  1910. SELECT address.* FROM user
  1911. JOIN address ON user.id=address.user_id
  1912. WHERE user.name = :name_1
  1913. .. seealso::
  1914. :meth:`_sql.Select.join` - v2 equivalent method.
  1915. :param \*props: Incoming arguments for :meth:`_query.Query.join`,
  1916. the props collection in modern use should be considered to be a one
  1917. or two argument form, either as a single "target" entity or ORM
  1918. attribute-bound relationship, or as a target entity plus an "on
  1919. clause" which may be a SQL expression or ORM attribute-bound
  1920. relationship.
  1921. :param isouter=False: If True, the join used will be a left outer join,
  1922. just as if the :meth:`_query.Query.outerjoin` method were called.
  1923. :param full=False: render FULL OUTER JOIN; implies ``isouter``.
  1924. """
  1925. join_target = coercions.expect(
  1926. roles.JoinTargetRole,
  1927. target,
  1928. apply_propagate_attrs=self,
  1929. legacy=True,
  1930. )
  1931. if onclause is not None:
  1932. onclause_element = coercions.expect(
  1933. roles.OnClauseRole, onclause, legacy=True
  1934. )
  1935. else:
  1936. onclause_element = None
  1937. self._setup_joins += (
  1938. (
  1939. join_target,
  1940. onclause_element,
  1941. None,
  1942. {
  1943. "isouter": isouter,
  1944. "full": full,
  1945. },
  1946. ),
  1947. )
  1948. self.__dict__.pop("_last_joined_entity", None)
  1949. return self
  1950. def outerjoin(
  1951. self,
  1952. target: _JoinTargetArgument,
  1953. onclause: Optional[_OnClauseArgument] = None,
  1954. *,
  1955. full: bool = False,
  1956. ) -> Self:
  1957. """Create a left outer join against this ``Query`` object's criterion
  1958. and apply generatively, returning the newly resulting ``Query``.
  1959. Usage is the same as the ``join()`` method.
  1960. .. seealso::
  1961. :meth:`_sql.Select.outerjoin` - v2 equivalent method.
  1962. """
  1963. return self.join(target, onclause=onclause, isouter=True, full=full)
  1964. @_generative
  1965. @_assertions(_no_statement_condition)
  1966. def reset_joinpoint(self) -> Self:
  1967. """Return a new :class:`.Query`, where the "join point" has
  1968. been reset back to the base FROM entities of the query.
  1969. This method is usually used in conjunction with the
  1970. ``aliased=True`` feature of the :meth:`~.Query.join`
  1971. method. See the example in :meth:`~.Query.join` for how
  1972. this is used.
  1973. """
  1974. self._last_joined_entity = None
  1975. return self
  1976. @_generative
  1977. @_assertions(_no_clauseelement_condition)
  1978. def select_from(self, *from_obj: _FromClauseArgument) -> Self:
  1979. r"""Set the FROM clause of this :class:`.Query` explicitly.
  1980. :meth:`.Query.select_from` is often used in conjunction with
  1981. :meth:`.Query.join` in order to control which entity is selected
  1982. from on the "left" side of the join.
  1983. The entity or selectable object here effectively replaces the
  1984. "left edge" of any calls to :meth:`~.Query.join`, when no
  1985. joinpoint is otherwise established - usually, the default "join
  1986. point" is the leftmost entity in the :class:`~.Query` object's
  1987. list of entities to be selected.
  1988. A typical example::
  1989. q = session.query(Address).select_from(User).\
  1990. join(User.addresses).\
  1991. filter(User.name == 'ed')
  1992. Which produces SQL equivalent to::
  1993. SELECT address.* FROM user
  1994. JOIN address ON user.id=address.user_id
  1995. WHERE user.name = :name_1
  1996. :param \*from_obj: collection of one or more entities to apply
  1997. to the FROM clause. Entities can be mapped classes,
  1998. :class:`.AliasedClass` objects, :class:`.Mapper` objects
  1999. as well as core :class:`.FromClause` elements like subqueries.
  2000. .. seealso::
  2001. :meth:`~.Query.join`
  2002. :meth:`.Query.select_entity_from`
  2003. :meth:`_sql.Select.select_from` - v2 equivalent method.
  2004. """
  2005. self._set_select_from(from_obj, False)
  2006. return self
  2007. def __getitem__(self, item: Any) -> Any:
  2008. return orm_util._getitem(
  2009. self,
  2010. item,
  2011. )
  2012. @_generative
  2013. @_assertions(_no_statement_condition)
  2014. def slice(
  2015. self,
  2016. start: int,
  2017. stop: int,
  2018. ) -> Self:
  2019. """Computes the "slice" of the :class:`_query.Query` represented by
  2020. the given indices and returns the resulting :class:`_query.Query`.
  2021. The start and stop indices behave like the argument to Python's
  2022. built-in :func:`range` function. This method provides an
  2023. alternative to using ``LIMIT``/``OFFSET`` to get a slice of the
  2024. query.
  2025. For example, ::
  2026. session.query(User).order_by(User.id).slice(1, 3)
  2027. renders as
  2028. .. sourcecode:: sql
  2029. SELECT users.id AS users_id,
  2030. users.name AS users_name
  2031. FROM users ORDER BY users.id
  2032. LIMIT ? OFFSET ?
  2033. (2, 1)
  2034. .. seealso::
  2035. :meth:`_query.Query.limit`
  2036. :meth:`_query.Query.offset`
  2037. :meth:`_sql.Select.slice` - v2 equivalent method.
  2038. """
  2039. self._limit_clause, self._offset_clause = sql_util._make_slice(
  2040. self._limit_clause, self._offset_clause, start, stop
  2041. )
  2042. return self
  2043. @_generative
  2044. @_assertions(_no_statement_condition)
  2045. def limit(self, limit: _LimitOffsetType) -> Self:
  2046. """Apply a ``LIMIT`` to the query and return the newly resulting
  2047. ``Query``.
  2048. .. seealso::
  2049. :meth:`_sql.Select.limit` - v2 equivalent method.
  2050. """
  2051. self._limit_clause = sql_util._offset_or_limit_clause(limit)
  2052. return self
  2053. @_generative
  2054. @_assertions(_no_statement_condition)
  2055. def offset(self, offset: _LimitOffsetType) -> Self:
  2056. """Apply an ``OFFSET`` to the query and return the newly resulting
  2057. ``Query``.
  2058. .. seealso::
  2059. :meth:`_sql.Select.offset` - v2 equivalent method.
  2060. """
  2061. self._offset_clause = sql_util._offset_or_limit_clause(offset)
  2062. return self
  2063. @_generative
  2064. @_assertions(_no_statement_condition)
  2065. def distinct(self, *expr: _ColumnExpressionArgument[Any]) -> Self:
  2066. r"""Apply a ``DISTINCT`` to the query and return the newly resulting
  2067. ``Query``.
  2068. .. note::
  2069. The ORM-level :meth:`.distinct` call includes logic that will
  2070. automatically add columns from the ORDER BY of the query to the
  2071. columns clause of the SELECT statement, to satisfy the common need
  2072. of the database backend that ORDER BY columns be part of the SELECT
  2073. list when DISTINCT is used. These columns *are not* added to the
  2074. list of columns actually fetched by the :class:`_query.Query`,
  2075. however,
  2076. so would not affect results. The columns are passed through when
  2077. using the :attr:`_query.Query.statement` accessor, however.
  2078. .. deprecated:: 2.0 This logic is deprecated and will be removed
  2079. in SQLAlchemy 2.0. See :ref:`migration_20_query_distinct`
  2080. for a description of this use case in 2.0.
  2081. .. seealso::
  2082. :meth:`_sql.Select.distinct` - v2 equivalent method.
  2083. :param \*expr: optional column expressions. When present,
  2084. the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>)``
  2085. construct.
  2086. .. deprecated:: 1.4 Using \*expr in other dialects is deprecated
  2087. and will raise :class:`_exc.CompileError` in a future version.
  2088. """
  2089. if expr:
  2090. self._distinct = True
  2091. self._distinct_on = self._distinct_on + tuple(
  2092. coercions.expect(roles.ByOfRole, e) for e in expr
  2093. )
  2094. else:
  2095. self._distinct = True
  2096. return self
  2097. def all(self) -> List[_T]:
  2098. """Return the results represented by this :class:`_query.Query`
  2099. as a list.
  2100. This results in an execution of the underlying SQL statement.
  2101. .. warning:: The :class:`_query.Query` object,
  2102. when asked to return either
  2103. a sequence or iterator that consists of full ORM-mapped entities,
  2104. will **deduplicate entries based on primary key**. See the FAQ for
  2105. more details.
  2106. .. seealso::
  2107. :ref:`faq_query_deduplicating`
  2108. .. seealso::
  2109. :meth:`_engine.Result.all` - v2 comparable method.
  2110. :meth:`_engine.Result.scalars` - v2 comparable method.
  2111. """
  2112. return self._iter().all() # type: ignore
  2113. @_generative
  2114. @_assertions(_no_clauseelement_condition)
  2115. def from_statement(self, statement: ExecutableReturnsRows) -> Self:
  2116. """Execute the given SELECT statement and return results.
  2117. This method bypasses all internal statement compilation, and the
  2118. statement is executed without modification.
  2119. The statement is typically either a :func:`_expression.text`
  2120. or :func:`_expression.select` construct, and should return the set
  2121. of columns
  2122. appropriate to the entity class represented by this
  2123. :class:`_query.Query`.
  2124. .. seealso::
  2125. :meth:`_sql.Select.from_statement` - v2 comparable method.
  2126. """
  2127. statement = coercions.expect(
  2128. roles.SelectStatementRole, statement, apply_propagate_attrs=self
  2129. )
  2130. self._statement = statement
  2131. return self
  2132. def first(self) -> Optional[_T]:
  2133. """Return the first result of this ``Query`` or
  2134. None if the result doesn't contain any row.
  2135. first() applies a limit of one within the generated SQL, so that
  2136. only one primary entity row is generated on the server side
  2137. (note this may consist of multiple result rows if join-loaded
  2138. collections are present).
  2139. Calling :meth:`_query.Query.first`
  2140. results in an execution of the underlying
  2141. query.
  2142. .. seealso::
  2143. :meth:`_query.Query.one`
  2144. :meth:`_query.Query.one_or_none`
  2145. :meth:`_engine.Result.first` - v2 comparable method.
  2146. :meth:`_engine.Result.scalars` - v2 comparable method.
  2147. """
  2148. # replicates limit(1) behavior
  2149. if self._statement is not None:
  2150. return self._iter().first() # type: ignore
  2151. else:
  2152. return self.limit(1)._iter().first() # type: ignore
  2153. def one_or_none(self) -> Optional[_T]:
  2154. """Return at most one result or raise an exception.
  2155. Returns ``None`` if the query selects
  2156. no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
  2157. if multiple object identities are returned, or if multiple
  2158. rows are returned for a query that returns only scalar values
  2159. as opposed to full identity-mapped entities.
  2160. Calling :meth:`_query.Query.one_or_none`
  2161. results in an execution of the
  2162. underlying query.
  2163. .. seealso::
  2164. :meth:`_query.Query.first`
  2165. :meth:`_query.Query.one`
  2166. :meth:`_engine.Result.one_or_none` - v2 comparable method.
  2167. :meth:`_engine.Result.scalar_one_or_none` - v2 comparable method.
  2168. """
  2169. return self._iter().one_or_none() # type: ignore
  2170. def one(self) -> _T:
  2171. """Return exactly one result or raise an exception.
  2172. Raises ``sqlalchemy.orm.exc.NoResultFound`` if the query selects
  2173. no rows. Raises ``sqlalchemy.orm.exc.MultipleResultsFound``
  2174. if multiple object identities are returned, or if multiple
  2175. rows are returned for a query that returns only scalar values
  2176. as opposed to full identity-mapped entities.
  2177. Calling :meth:`.one` results in an execution of the underlying query.
  2178. .. seealso::
  2179. :meth:`_query.Query.first`
  2180. :meth:`_query.Query.one_or_none`
  2181. :meth:`_engine.Result.one` - v2 comparable method.
  2182. :meth:`_engine.Result.scalar_one` - v2 comparable method.
  2183. """
  2184. return self._iter().one() # type: ignore
  2185. def scalar(self) -> Any:
  2186. """Return the first element of the first result or None
  2187. if no rows present. If multiple rows are returned,
  2188. raises MultipleResultsFound.
  2189. >>> session.query(Item).scalar()
  2190. <Item>
  2191. >>> session.query(Item.id).scalar()
  2192. 1
  2193. >>> session.query(Item.id).filter(Item.id < 0).scalar()
  2194. None
  2195. >>> session.query(Item.id, Item.name).scalar()
  2196. 1
  2197. >>> session.query(func.count(Parent.id)).scalar()
  2198. 20
  2199. This results in an execution of the underlying query.
  2200. .. seealso::
  2201. :meth:`_engine.Result.scalar` - v2 comparable method.
  2202. """
  2203. # TODO: not sure why we can't use result.scalar() here
  2204. try:
  2205. ret = self.one()
  2206. if not isinstance(ret, collections_abc.Sequence):
  2207. return ret
  2208. return ret[0]
  2209. except sa_exc.NoResultFound:
  2210. return None
  2211. def __iter__(self) -> Iterator[_T]:
  2212. result = self._iter()
  2213. try:
  2214. yield from result # type: ignore
  2215. except GeneratorExit:
  2216. # issue #8710 - direct iteration is not re-usable after
  2217. # an iterable block is broken, so close the result
  2218. result._soft_close()
  2219. raise
  2220. def _iter(self) -> Union[ScalarResult[_T], Result[_T]]:
  2221. # new style execution.
  2222. params = self._params
  2223. statement = self._statement_20()
  2224. result: Union[ScalarResult[_T], Result[_T]] = self.session.execute(
  2225. statement,
  2226. params,
  2227. execution_options={"_sa_orm_load_options": self.load_options},
  2228. )
  2229. # legacy: automatically set scalars, unique
  2230. if result._attributes.get("is_single_entity", False):
  2231. result = cast("Result[_T]", result).scalars()
  2232. if (
  2233. result._attributes.get("filtered", False)
  2234. and not self.load_options._yield_per
  2235. ):
  2236. result = result.unique()
  2237. return result
  2238. def __str__(self) -> str:
  2239. statement = self._statement_20()
  2240. try:
  2241. bind = (
  2242. self._get_bind_args(statement, self.session.get_bind)
  2243. if self.session
  2244. else None
  2245. )
  2246. except sa_exc.UnboundExecutionError:
  2247. bind = None
  2248. return str(statement.compile(bind))
  2249. def _get_bind_args(self, statement: Any, fn: Any, **kw: Any) -> Any:
  2250. return fn(clause=statement, **kw)
  2251. @property
  2252. def column_descriptions(self) -> List[ORMColumnDescription]:
  2253. """Return metadata about the columns which would be
  2254. returned by this :class:`_query.Query`.
  2255. Format is a list of dictionaries::
  2256. user_alias = aliased(User, name='user2')
  2257. q = sess.query(User, User.id, user_alias)
  2258. # this expression:
  2259. q.column_descriptions
  2260. # would return:
  2261. [
  2262. {
  2263. 'name':'User',
  2264. 'type':User,
  2265. 'aliased':False,
  2266. 'expr':User,
  2267. 'entity': User
  2268. },
  2269. {
  2270. 'name':'id',
  2271. 'type':Integer(),
  2272. 'aliased':False,
  2273. 'expr':User.id,
  2274. 'entity': User
  2275. },
  2276. {
  2277. 'name':'user2',
  2278. 'type':User,
  2279. 'aliased':True,
  2280. 'expr':user_alias,
  2281. 'entity': user_alias
  2282. }
  2283. ]
  2284. .. seealso::
  2285. This API is available using :term:`2.0 style` queries as well,
  2286. documented at:
  2287. * :ref:`queryguide_inspection`
  2288. * :attr:`.Select.column_descriptions`
  2289. """
  2290. return _column_descriptions(self, legacy=True)
  2291. @util.deprecated(
  2292. "2.0",
  2293. "The :meth:`_orm.Query.instances` method is deprecated and will "
  2294. "be removed in a future release. "
  2295. "Use the Select.from_statement() method or aliased() construct in "
  2296. "conjunction with Session.execute() instead.",
  2297. )
  2298. def instances(
  2299. self,
  2300. result_proxy: CursorResult[Any],
  2301. context: Optional[QueryContext] = None,
  2302. ) -> Any:
  2303. """Return an ORM result given a :class:`_engine.CursorResult` and
  2304. :class:`.QueryContext`.
  2305. """
  2306. if context is None:
  2307. util.warn_deprecated(
  2308. "Using the Query.instances() method without a context "
  2309. "is deprecated and will be disallowed in a future release. "
  2310. "Please make use of :meth:`_query.Query.from_statement` "
  2311. "for linking ORM results to arbitrary select constructs.",
  2312. version="1.4",
  2313. )
  2314. compile_state = self._compile_state(for_statement=False)
  2315. context = QueryContext(
  2316. compile_state,
  2317. compile_state.statement,
  2318. self._params,
  2319. self.session,
  2320. self.load_options,
  2321. )
  2322. result = loading.instances(result_proxy, context)
  2323. # legacy: automatically set scalars, unique
  2324. if result._attributes.get("is_single_entity", False):
  2325. result = result.scalars() # type: ignore
  2326. if result._attributes.get("filtered", False):
  2327. result = result.unique()
  2328. # TODO: isn't this supposed to be a list?
  2329. return result
  2330. @util.became_legacy_20(
  2331. ":meth:`_orm.Query.merge_result`",
  2332. alternative="The method is superseded by the "
  2333. ":func:`_orm.merge_frozen_result` function.",
  2334. enable_warnings=False, # warnings occur via loading.merge_result
  2335. )
  2336. def merge_result(
  2337. self,
  2338. iterator: Union[
  2339. FrozenResult[Any], Iterable[Sequence[Any]], Iterable[object]
  2340. ],
  2341. load: bool = True,
  2342. ) -> Union[FrozenResult[Any], Iterable[Any]]:
  2343. """Merge a result into this :class:`_query.Query` object's Session.
  2344. Given an iterator returned by a :class:`_query.Query`
  2345. of the same structure
  2346. as this one, return an identical iterator of results, with all mapped
  2347. instances merged into the session using :meth:`.Session.merge`. This
  2348. is an optimized method which will merge all mapped instances,
  2349. preserving the structure of the result rows and unmapped columns with
  2350. less method overhead than that of calling :meth:`.Session.merge`
  2351. explicitly for each value.
  2352. The structure of the results is determined based on the column list of
  2353. this :class:`_query.Query` - if these do not correspond,
  2354. unchecked errors
  2355. will occur.
  2356. The 'load' argument is the same as that of :meth:`.Session.merge`.
  2357. For an example of how :meth:`_query.Query.merge_result` is used, see
  2358. the source code for the example :ref:`examples_caching`, where
  2359. :meth:`_query.Query.merge_result` is used to efficiently restore state
  2360. from a cache back into a target :class:`.Session`.
  2361. """
  2362. return loading.merge_result(self, iterator, load)
  2363. def exists(self) -> Exists:
  2364. """A convenience method that turns a query into an EXISTS subquery
  2365. of the form EXISTS (SELECT 1 FROM ... WHERE ...).
  2366. e.g.::
  2367. q = session.query(User).filter(User.name == 'fred')
  2368. session.query(q.exists())
  2369. Producing SQL similar to::
  2370. SELECT EXISTS (
  2371. SELECT 1 FROM users WHERE users.name = :name_1
  2372. ) AS anon_1
  2373. The EXISTS construct is usually used in the WHERE clause::
  2374. session.query(User.id).filter(q.exists()).scalar()
  2375. Note that some databases such as SQL Server don't allow an
  2376. EXISTS expression to be present in the columns clause of a
  2377. SELECT. To select a simple boolean value based on the exists
  2378. as a WHERE, use :func:`.literal`::
  2379. from sqlalchemy import literal
  2380. session.query(literal(True)).filter(q.exists()).scalar()
  2381. .. seealso::
  2382. :meth:`_sql.Select.exists` - v2 comparable method.
  2383. """
  2384. # .add_columns() for the case that we are a query().select_from(X),
  2385. # so that ".statement" can be produced (#2995) but also without
  2386. # omitting the FROM clause from a query(X) (#2818);
  2387. # .with_only_columns() after we have a core select() so that
  2388. # we get just "SELECT 1" without any entities.
  2389. inner = (
  2390. self.enable_eagerloads(False)
  2391. .add_columns(sql.literal_column("1"))
  2392. .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  2393. ._get_select_statement_only()
  2394. .with_only_columns(1)
  2395. )
  2396. ezero = self._entity_from_pre_ent_zero()
  2397. if ezero is not None:
  2398. inner = inner.select_from(ezero)
  2399. return sql.exists(inner)
  2400. def count(self) -> int:
  2401. r"""Return a count of rows this the SQL formed by this :class:`Query`
  2402. would return.
  2403. This generates the SQL for this Query as follows::
  2404. SELECT count(1) AS count_1 FROM (
  2405. SELECT <rest of query follows...>
  2406. ) AS anon_1
  2407. The above SQL returns a single row, which is the aggregate value
  2408. of the count function; the :meth:`_query.Query.count`
  2409. method then returns
  2410. that single integer value.
  2411. .. warning::
  2412. It is important to note that the value returned by
  2413. count() is **not the same as the number of ORM objects that this
  2414. Query would return from a method such as the .all() method**.
  2415. The :class:`_query.Query` object,
  2416. when asked to return full entities,
  2417. will **deduplicate entries based on primary key**, meaning if the
  2418. same primary key value would appear in the results more than once,
  2419. only one object of that primary key would be present. This does
  2420. not apply to a query that is against individual columns.
  2421. .. seealso::
  2422. :ref:`faq_query_deduplicating`
  2423. For fine grained control over specific columns to count, to skip the
  2424. usage of a subquery or otherwise control of the FROM clause, or to use
  2425. other aggregate functions, use :attr:`~sqlalchemy.sql.expression.func`
  2426. expressions in conjunction with :meth:`~.Session.query`, i.e.::
  2427. from sqlalchemy import func
  2428. # count User records, without
  2429. # using a subquery.
  2430. session.query(func.count(User.id))
  2431. # return count of user "id" grouped
  2432. # by "name"
  2433. session.query(func.count(User.id)).\
  2434. group_by(User.name)
  2435. from sqlalchemy import distinct
  2436. # count distinct "name" values
  2437. session.query(func.count(distinct(User.name)))
  2438. .. seealso::
  2439. :ref:`migration_20_query_usage`
  2440. """
  2441. col = sql.func.count(sql.literal_column("*"))
  2442. return ( # type: ignore
  2443. self._legacy_from_self(col).enable_eagerloads(False).scalar()
  2444. )
  2445. def delete(
  2446. self, synchronize_session: SynchronizeSessionArgument = "auto"
  2447. ) -> int:
  2448. r"""Perform a DELETE with an arbitrary WHERE clause.
  2449. Deletes rows matched by this query from the database.
  2450. E.g.::
  2451. sess.query(User).filter(User.age == 25).\
  2452. delete(synchronize_session=False)
  2453. sess.query(User).filter(User.age == 25).\
  2454. delete(synchronize_session='evaluate')
  2455. .. warning::
  2456. See the section :ref:`orm_expression_update_delete` for important
  2457. caveats and warnings, including limitations when using bulk UPDATE
  2458. and DELETE with mapper inheritance configurations.
  2459. :param synchronize_session: chooses the strategy to update the
  2460. attributes on objects in the session. See the section
  2461. :ref:`orm_expression_update_delete` for a discussion of these
  2462. strategies.
  2463. :return: the count of rows matched as returned by the database's
  2464. "row count" feature.
  2465. .. seealso::
  2466. :ref:`orm_expression_update_delete`
  2467. """
  2468. bulk_del = BulkDelete(self)
  2469. if self.dispatch.before_compile_delete:
  2470. for fn in self.dispatch.before_compile_delete:
  2471. new_query = fn(bulk_del.query, bulk_del)
  2472. if new_query is not None:
  2473. bulk_del.query = new_query
  2474. self = bulk_del.query
  2475. delete_ = sql.delete(*self._raw_columns) # type: ignore
  2476. delete_._where_criteria = self._where_criteria
  2477. result: CursorResult[Any] = self.session.execute(
  2478. delete_,
  2479. self._params,
  2480. execution_options=self._execution_options.union(
  2481. {"synchronize_session": synchronize_session}
  2482. ),
  2483. )
  2484. bulk_del.result = result # type: ignore
  2485. self.session.dispatch.after_bulk_delete(bulk_del)
  2486. result.close()
  2487. return result.rowcount
  2488. def update(
  2489. self,
  2490. values: Dict[_DMLColumnArgument, Any],
  2491. synchronize_session: SynchronizeSessionArgument = "auto",
  2492. update_args: Optional[Dict[Any, Any]] = None,
  2493. ) -> int:
  2494. r"""Perform an UPDATE with an arbitrary WHERE clause.
  2495. Updates rows matched by this query in the database.
  2496. E.g.::
  2497. sess.query(User).filter(User.age == 25).\
  2498. update({User.age: User.age - 10}, synchronize_session=False)
  2499. sess.query(User).filter(User.age == 25).\
  2500. update({"age": User.age - 10}, synchronize_session='evaluate')
  2501. .. warning::
  2502. See the section :ref:`orm_expression_update_delete` for important
  2503. caveats and warnings, including limitations when using arbitrary
  2504. UPDATE and DELETE with mapper inheritance configurations.
  2505. :param values: a dictionary with attributes names, or alternatively
  2506. mapped attributes or SQL expressions, as keys, and literal
  2507. values or sql expressions as values. If :ref:`parameter-ordered
  2508. mode <tutorial_parameter_ordered_updates>` is desired, the values can
  2509. be passed as a list of 2-tuples; this requires that the
  2510. :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`
  2511. flag is passed to the :paramref:`.Query.update.update_args` dictionary
  2512. as well.
  2513. :param synchronize_session: chooses the strategy to update the
  2514. attributes on objects in the session. See the section
  2515. :ref:`orm_expression_update_delete` for a discussion of these
  2516. strategies.
  2517. :param update_args: Optional dictionary, if present will be passed
  2518. to the underlying :func:`_expression.update`
  2519. construct as the ``**kw`` for
  2520. the object. May be used to pass dialect-specific arguments such
  2521. as ``mysql_limit``, as well as other special arguments such as
  2522. :paramref:`~sqlalchemy.sql.expression.update.preserve_parameter_order`.
  2523. :return: the count of rows matched as returned by the database's
  2524. "row count" feature.
  2525. .. seealso::
  2526. :ref:`orm_expression_update_delete`
  2527. """
  2528. update_args = update_args or {}
  2529. bulk_ud = BulkUpdate(self, values, update_args)
  2530. if self.dispatch.before_compile_update:
  2531. for fn in self.dispatch.before_compile_update:
  2532. new_query = fn(bulk_ud.query, bulk_ud)
  2533. if new_query is not None:
  2534. bulk_ud.query = new_query
  2535. self = bulk_ud.query
  2536. upd = sql.update(*self._raw_columns) # type: ignore
  2537. ppo = update_args.pop("preserve_parameter_order", False)
  2538. if ppo:
  2539. upd = upd.ordered_values(*values) # type: ignore
  2540. else:
  2541. upd = upd.values(values)
  2542. if update_args:
  2543. upd = upd.with_dialect_options(**update_args)
  2544. upd._where_criteria = self._where_criteria
  2545. result: CursorResult[Any] = self.session.execute(
  2546. upd,
  2547. self._params,
  2548. execution_options=self._execution_options.union(
  2549. {"synchronize_session": synchronize_session}
  2550. ),
  2551. )
  2552. bulk_ud.result = result # type: ignore
  2553. self.session.dispatch.after_bulk_update(bulk_ud)
  2554. result.close()
  2555. return result.rowcount
  2556. def _compile_state(
  2557. self, for_statement: bool = False, **kw: Any
  2558. ) -> ORMCompileState:
  2559. """Create an out-of-compiler ORMCompileState object.
  2560. The ORMCompileState object is normally created directly as a result
  2561. of the SQLCompiler.process() method being handed a Select()
  2562. or FromStatement() object that uses the "orm" plugin. This method
  2563. provides a means of creating this ORMCompileState object directly
  2564. without using the compiler.
  2565. This method is used only for deprecated cases, which include
  2566. the .from_self() method for a Query that has multiple levels
  2567. of .from_self() in use, as well as the instances() method. It is
  2568. also used within the test suite to generate ORMCompileState objects
  2569. for test purposes.
  2570. """
  2571. stmt = self._statement_20(for_statement=for_statement, **kw)
  2572. assert for_statement == stmt._compile_options._for_statement
  2573. # this chooses between ORMFromStatementCompileState and
  2574. # ORMSelectCompileState. We could also base this on
  2575. # query._statement is not None as we have the ORM Query here
  2576. # however this is the more general path.
  2577. compile_state_cls = cast(
  2578. ORMCompileState,
  2579. ORMCompileState._get_plugin_class_for_plugin(stmt, "orm"),
  2580. )
  2581. return compile_state_cls.create_for_statement(stmt, None)
  2582. def _compile_context(self, for_statement: bool = False) -> QueryContext:
  2583. compile_state = self._compile_state(for_statement=for_statement)
  2584. context = QueryContext(
  2585. compile_state,
  2586. compile_state.statement,
  2587. self._params,
  2588. self.session,
  2589. self.load_options,
  2590. )
  2591. return context
  2592. class AliasOption(interfaces.LoaderOption):
  2593. inherit_cache = False
  2594. @util.deprecated(
  2595. "1.4",
  2596. "The :class:`.AliasOption` object is not necessary "
  2597. "for entities to be matched up to a query that is established "
  2598. "via :meth:`.Query.from_statement` and now does nothing.",
  2599. )
  2600. def __init__(self, alias: Union[Alias, Subquery]):
  2601. r"""Return a :class:`.MapperOption` that will indicate to the
  2602. :class:`_query.Query`
  2603. that the main table has been aliased.
  2604. """
  2605. def process_compile_state(self, compile_state: ORMCompileState) -> None:
  2606. pass
  2607. class BulkUD:
  2608. """State used for the orm.Query version of update() / delete().
  2609. This object is now specific to Query only.
  2610. """
  2611. def __init__(self, query: Query[Any]):
  2612. self.query = query.enable_eagerloads(False)
  2613. self._validate_query_state()
  2614. self.mapper = self.query._entity_from_pre_ent_zero()
  2615. def _validate_query_state(self) -> None:
  2616. for attr, methname, notset, op in (
  2617. ("_limit_clause", "limit()", None, operator.is_),
  2618. ("_offset_clause", "offset()", None, operator.is_),
  2619. ("_order_by_clauses", "order_by()", (), operator.eq),
  2620. ("_group_by_clauses", "group_by()", (), operator.eq),
  2621. ("_distinct", "distinct()", False, operator.is_),
  2622. (
  2623. "_from_obj",
  2624. "join(), outerjoin(), select_from(), or from_self()",
  2625. (),
  2626. operator.eq,
  2627. ),
  2628. (
  2629. "_setup_joins",
  2630. "join(), outerjoin(), select_from(), or from_self()",
  2631. (),
  2632. operator.eq,
  2633. ),
  2634. ):
  2635. if not op(getattr(self.query, attr), notset):
  2636. raise sa_exc.InvalidRequestError(
  2637. "Can't call Query.update() or Query.delete() "
  2638. "when %s has been called" % (methname,)
  2639. )
  2640. @property
  2641. def session(self) -> Session:
  2642. return self.query.session
  2643. class BulkUpdate(BulkUD):
  2644. """BulkUD which handles UPDATEs."""
  2645. def __init__(
  2646. self,
  2647. query: Query[Any],
  2648. values: Dict[_DMLColumnArgument, Any],
  2649. update_kwargs: Optional[Dict[Any, Any]],
  2650. ):
  2651. super().__init__(query)
  2652. self.values = values
  2653. self.update_kwargs = update_kwargs
  2654. class BulkDelete(BulkUD):
  2655. """BulkUD which handles DELETEs."""
  2656. class RowReturningQuery(Query[Row[_TP]]):
  2657. if TYPE_CHECKING:
  2658. def tuples(self) -> Query[_TP]: # type: ignore
  2659. ...