context.py 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234
  1. # orm/context.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. # mypy: ignore-errors
  8. from __future__ import annotations
  9. import itertools
  10. from typing import Any
  11. from typing import cast
  12. from typing import Dict
  13. from typing import Iterable
  14. from typing import List
  15. from typing import Optional
  16. from typing import Set
  17. from typing import Tuple
  18. from typing import Type
  19. from typing import TYPE_CHECKING
  20. from typing import TypeVar
  21. from typing import Union
  22. from . import attributes
  23. from . import interfaces
  24. from . import loading
  25. from .base import _is_aliased_class
  26. from .interfaces import ORMColumnDescription
  27. from .interfaces import ORMColumnsClauseRole
  28. from .path_registry import PathRegistry
  29. from .util import _entity_corresponds_to
  30. from .util import _ORMJoin
  31. from .util import _TraceAdaptRole
  32. from .util import AliasedClass
  33. from .util import Bundle
  34. from .util import ORMAdapter
  35. from .util import ORMStatementAdapter
  36. from .. import exc as sa_exc
  37. from .. import future
  38. from .. import inspect
  39. from .. import sql
  40. from .. import util
  41. from ..sql import coercions
  42. from ..sql import expression
  43. from ..sql import roles
  44. from ..sql import util as sql_util
  45. from ..sql import visitors
  46. from ..sql._typing import _TP
  47. from ..sql._typing import is_dml
  48. from ..sql._typing import is_insert_update
  49. from ..sql._typing import is_select_base
  50. from ..sql.base import _select_iterables
  51. from ..sql.base import CacheableOptions
  52. from ..sql.base import CompileState
  53. from ..sql.base import Executable
  54. from ..sql.base import Generative
  55. from ..sql.base import Options
  56. from ..sql.dml import UpdateBase
  57. from ..sql.elements import GroupedElement
  58. from ..sql.elements import TextClause
  59. from ..sql.selectable import CompoundSelectState
  60. from ..sql.selectable import LABEL_STYLE_DISAMBIGUATE_ONLY
  61. from ..sql.selectable import LABEL_STYLE_NONE
  62. from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
  63. from ..sql.selectable import Select
  64. from ..sql.selectable import SelectLabelStyle
  65. from ..sql.selectable import SelectState
  66. from ..sql.selectable import TypedReturnsRows
  67. from ..sql.visitors import InternalTraversal
  68. if TYPE_CHECKING:
  69. from ._typing import _InternalEntityType
  70. from ._typing import OrmExecuteOptionsParameter
  71. from .loading import PostLoad
  72. from .mapper import Mapper
  73. from .query import Query
  74. from .session import _BindArguments
  75. from .session import Session
  76. from ..engine import Result
  77. from ..engine.interfaces import _CoreSingleExecuteParams
  78. from ..sql._typing import _ColumnsClauseArgument
  79. from ..sql.compiler import SQLCompiler
  80. from ..sql.dml import _DMLTableElement
  81. from ..sql.elements import ColumnElement
  82. from ..sql.selectable import _JoinTargetElement
  83. from ..sql.selectable import _LabelConventionCallable
  84. from ..sql.selectable import _SetupJoinsElement
  85. from ..sql.selectable import ExecutableReturnsRows
  86. from ..sql.selectable import SelectBase
  87. from ..sql.type_api import TypeEngine
  88. _T = TypeVar("_T", bound=Any)
  89. _path_registry = PathRegistry.root
  90. _EMPTY_DICT = util.immutabledict()
  91. LABEL_STYLE_LEGACY_ORM = SelectLabelStyle.LABEL_STYLE_LEGACY_ORM
  92. class QueryContext:
  93. __slots__ = (
  94. "top_level_context",
  95. "compile_state",
  96. "query",
  97. "params",
  98. "load_options",
  99. "bind_arguments",
  100. "execution_options",
  101. "session",
  102. "autoflush",
  103. "populate_existing",
  104. "invoke_all_eagers",
  105. "version_check",
  106. "refresh_state",
  107. "create_eager_joins",
  108. "propagated_loader_options",
  109. "attributes",
  110. "runid",
  111. "partials",
  112. "post_load_paths",
  113. "identity_token",
  114. "yield_per",
  115. "loaders_require_buffering",
  116. "loaders_require_uniquing",
  117. )
  118. runid: int
  119. post_load_paths: Dict[PathRegistry, PostLoad]
  120. compile_state: ORMCompileState
  121. class default_load_options(Options):
  122. _only_return_tuples = False
  123. _populate_existing = False
  124. _version_check = False
  125. _invoke_all_eagers = True
  126. _autoflush = True
  127. _identity_token = None
  128. _yield_per = None
  129. _refresh_state = None
  130. _lazy_loaded_from = None
  131. _legacy_uniquing = False
  132. _sa_top_level_orm_context = None
  133. _is_user_refresh = False
  134. def __init__(
  135. self,
  136. compile_state: CompileState,
  137. statement: Union[Select[Any], FromStatement[Any]],
  138. params: _CoreSingleExecuteParams,
  139. session: Session,
  140. load_options: Union[
  141. Type[QueryContext.default_load_options],
  142. QueryContext.default_load_options,
  143. ],
  144. execution_options: Optional[OrmExecuteOptionsParameter] = None,
  145. bind_arguments: Optional[_BindArguments] = None,
  146. ):
  147. self.load_options = load_options
  148. self.execution_options = execution_options or _EMPTY_DICT
  149. self.bind_arguments = bind_arguments or _EMPTY_DICT
  150. self.compile_state = compile_state
  151. self.query = statement
  152. self.session = session
  153. self.loaders_require_buffering = False
  154. self.loaders_require_uniquing = False
  155. self.params = params
  156. self.top_level_context = load_options._sa_top_level_orm_context
  157. cached_options = compile_state.select_statement._with_options
  158. uncached_options = statement._with_options
  159. # see issue #7447 , #8399 for some background
  160. # propagated loader options will be present on loaded InstanceState
  161. # objects under state.load_options and are typically used by
  162. # LazyLoader to apply options to the SELECT statement it emits.
  163. # For compile state options (i.e. loader strategy options), these
  164. # need to line up with the ".load_path" attribute which in
  165. # loader.py is pulled from context.compile_state.current_path.
  166. # so, this means these options have to be the ones from the
  167. # *cached* statement that's travelling with compile_state, not the
  168. # *current* statement which won't match up for an ad-hoc
  169. # AliasedClass
  170. self.propagated_loader_options = tuple(
  171. opt._adapt_cached_option_to_uncached_option(self, uncached_opt)
  172. for opt, uncached_opt in zip(cached_options, uncached_options)
  173. if opt.propagate_to_loaders
  174. )
  175. self.attributes = dict(compile_state.attributes)
  176. self.autoflush = load_options._autoflush
  177. self.populate_existing = load_options._populate_existing
  178. self.invoke_all_eagers = load_options._invoke_all_eagers
  179. self.version_check = load_options._version_check
  180. self.refresh_state = load_options._refresh_state
  181. self.yield_per = load_options._yield_per
  182. self.identity_token = load_options._identity_token
  183. def _get_top_level_context(self) -> QueryContext:
  184. return self.top_level_context or self
  185. _orm_load_exec_options = util.immutabledict(
  186. {"_result_disable_adapt_to_context": True}
  187. )
  188. class AbstractORMCompileState(CompileState):
  189. is_dml_returning = False
  190. def _init_global_attributes(
  191. self, statement, compiler, *, toplevel, process_criteria_for_toplevel
  192. ):
  193. self.attributes = {}
  194. if compiler is None:
  195. # this is the legacy / testing only ORM _compile_state() use case.
  196. # there is no need to apply criteria options for this.
  197. self.global_attributes = ga = {}
  198. assert toplevel
  199. return
  200. else:
  201. self.global_attributes = ga = compiler._global_attributes
  202. if toplevel:
  203. ga["toplevel_orm"] = True
  204. if process_criteria_for_toplevel:
  205. for opt in statement._with_options:
  206. if opt._is_criteria_option:
  207. opt.process_compile_state(self)
  208. return
  209. elif ga.get("toplevel_orm", False):
  210. return
  211. stack_0 = compiler.stack[0]
  212. try:
  213. toplevel_stmt = stack_0["selectable"]
  214. except KeyError:
  215. pass
  216. else:
  217. for opt in toplevel_stmt._with_options:
  218. if opt._is_compile_state and opt._is_criteria_option:
  219. opt.process_compile_state(self)
  220. ga["toplevel_orm"] = True
  221. @classmethod
  222. def create_for_statement(
  223. cls,
  224. statement: Union[Select, FromStatement],
  225. compiler: Optional[SQLCompiler],
  226. **kw: Any,
  227. ) -> AbstractORMCompileState:
  228. """Create a context for a statement given a :class:`.Compiler`.
  229. This method is always invoked in the context of SQLCompiler.process().
  230. For a Select object, this would be invoked from
  231. SQLCompiler.visit_select(). For the special FromStatement object used
  232. by Query to indicate "Query.from_statement()", this is called by
  233. FromStatement._compiler_dispatch() that would be called by
  234. SQLCompiler.process().
  235. """
  236. return super().create_for_statement(statement, compiler, **kw)
  237. @classmethod
  238. def orm_pre_session_exec(
  239. cls,
  240. session,
  241. statement,
  242. params,
  243. execution_options,
  244. bind_arguments,
  245. is_pre_event,
  246. ):
  247. raise NotImplementedError()
  248. @classmethod
  249. def orm_execute_statement(
  250. cls,
  251. session,
  252. statement,
  253. params,
  254. execution_options,
  255. bind_arguments,
  256. conn,
  257. ) -> Result:
  258. result = conn.execute(
  259. statement, params or {}, execution_options=execution_options
  260. )
  261. return cls.orm_setup_cursor_result(
  262. session,
  263. statement,
  264. params,
  265. execution_options,
  266. bind_arguments,
  267. result,
  268. )
  269. @classmethod
  270. def orm_setup_cursor_result(
  271. cls,
  272. session,
  273. statement,
  274. params,
  275. execution_options,
  276. bind_arguments,
  277. result,
  278. ):
  279. raise NotImplementedError()
  280. class AutoflushOnlyORMCompileState(AbstractORMCompileState):
  281. """ORM compile state that is a passthrough, except for autoflush."""
  282. @classmethod
  283. def orm_pre_session_exec(
  284. cls,
  285. session,
  286. statement,
  287. params,
  288. execution_options,
  289. bind_arguments,
  290. is_pre_event,
  291. ):
  292. # consume result-level load_options. These may have been set up
  293. # in an ORMExecuteState hook
  294. (
  295. load_options,
  296. execution_options,
  297. ) = QueryContext.default_load_options.from_execution_options(
  298. "_sa_orm_load_options",
  299. {
  300. "autoflush",
  301. },
  302. execution_options,
  303. statement._execution_options,
  304. )
  305. if not is_pre_event and load_options._autoflush:
  306. session._autoflush()
  307. return statement, execution_options
  308. @classmethod
  309. def orm_setup_cursor_result(
  310. cls,
  311. session,
  312. statement,
  313. params,
  314. execution_options,
  315. bind_arguments,
  316. result,
  317. ):
  318. return result
  319. class ORMCompileState(AbstractORMCompileState):
  320. class default_compile_options(CacheableOptions):
  321. _cache_key_traversal = [
  322. ("_use_legacy_query_style", InternalTraversal.dp_boolean),
  323. ("_for_statement", InternalTraversal.dp_boolean),
  324. ("_bake_ok", InternalTraversal.dp_boolean),
  325. ("_current_path", InternalTraversal.dp_has_cache_key),
  326. ("_enable_single_crit", InternalTraversal.dp_boolean),
  327. ("_enable_eagerloads", InternalTraversal.dp_boolean),
  328. ("_only_load_props", InternalTraversal.dp_plain_obj),
  329. ("_set_base_alias", InternalTraversal.dp_boolean),
  330. ("_for_refresh_state", InternalTraversal.dp_boolean),
  331. ("_render_for_subquery", InternalTraversal.dp_boolean),
  332. ("_is_star", InternalTraversal.dp_boolean),
  333. ]
  334. # set to True by default from Query._statement_20(), to indicate
  335. # the rendered query should look like a legacy ORM query. right
  336. # now this basically indicates we should use tablename_columnname
  337. # style labels. Generally indicates the statement originated
  338. # from a Query object.
  339. _use_legacy_query_style = False
  340. # set *only* when we are coming from the Query.statement
  341. # accessor, or a Query-level equivalent such as
  342. # query.subquery(). this supersedes "toplevel".
  343. _for_statement = False
  344. _bake_ok = True
  345. _current_path = _path_registry
  346. _enable_single_crit = True
  347. _enable_eagerloads = True
  348. _only_load_props = None
  349. _set_base_alias = False
  350. _for_refresh_state = False
  351. _render_for_subquery = False
  352. _is_star = False
  353. attributes: Dict[Any, Any]
  354. global_attributes: Dict[Any, Any]
  355. statement: Union[Select[Any], FromStatement[Any]]
  356. select_statement: Union[Select[Any], FromStatement[Any]]
  357. _entities: List[_QueryEntity]
  358. _polymorphic_adapters: Dict[_InternalEntityType, ORMAdapter]
  359. compile_options: Union[
  360. Type[default_compile_options], default_compile_options
  361. ]
  362. _primary_entity: Optional[_QueryEntity]
  363. use_legacy_query_style: bool
  364. _label_convention: _LabelConventionCallable
  365. primary_columns: List[ColumnElement[Any]]
  366. secondary_columns: List[ColumnElement[Any]]
  367. dedupe_columns: Set[ColumnElement[Any]]
  368. create_eager_joins: List[
  369. # TODO: this structure is set up by JoinedLoader
  370. Tuple[Any, ...]
  371. ]
  372. current_path: PathRegistry = _path_registry
  373. _has_mapper_entities = False
  374. def __init__(self, *arg, **kw):
  375. raise NotImplementedError()
  376. if TYPE_CHECKING:
  377. @classmethod
  378. def create_for_statement(
  379. cls,
  380. statement: Union[Select, FromStatement],
  381. compiler: Optional[SQLCompiler],
  382. **kw: Any,
  383. ) -> ORMCompileState:
  384. ...
  385. def _append_dedupe_col_collection(self, obj, col_collection):
  386. dedupe = self.dedupe_columns
  387. if obj not in dedupe:
  388. dedupe.add(obj)
  389. col_collection.append(obj)
  390. @classmethod
  391. def _column_naming_convention(
  392. cls, label_style: SelectLabelStyle, legacy: bool
  393. ) -> _LabelConventionCallable:
  394. if legacy:
  395. def name(col, col_name=None):
  396. if col_name:
  397. return col_name
  398. else:
  399. return getattr(col, "key")
  400. return name
  401. else:
  402. return SelectState._column_naming_convention(label_style)
  403. @classmethod
  404. def get_column_descriptions(cls, statement):
  405. return _column_descriptions(statement)
  406. @classmethod
  407. def orm_pre_session_exec(
  408. cls,
  409. session,
  410. statement,
  411. params,
  412. execution_options,
  413. bind_arguments,
  414. is_pre_event,
  415. ):
  416. # consume result-level load_options. These may have been set up
  417. # in an ORMExecuteState hook
  418. (
  419. load_options,
  420. execution_options,
  421. ) = QueryContext.default_load_options.from_execution_options(
  422. "_sa_orm_load_options",
  423. {
  424. "populate_existing",
  425. "autoflush",
  426. "yield_per",
  427. "identity_token",
  428. "sa_top_level_orm_context",
  429. },
  430. execution_options,
  431. statement._execution_options,
  432. )
  433. # default execution options for ORM results:
  434. # 1. _result_disable_adapt_to_context=True
  435. # this will disable the ResultSetMetadata._adapt_to_context()
  436. # step which we don't need, as we have result processors cached
  437. # against the original SELECT statement before caching.
  438. if "sa_top_level_orm_context" in execution_options:
  439. ctx = execution_options["sa_top_level_orm_context"]
  440. execution_options = ctx.query._execution_options.merge_with(
  441. ctx.execution_options, execution_options
  442. )
  443. if not execution_options:
  444. execution_options = _orm_load_exec_options
  445. else:
  446. execution_options = execution_options.union(_orm_load_exec_options)
  447. # would have been placed here by legacy Query only
  448. if load_options._yield_per:
  449. execution_options = execution_options.union(
  450. {"yield_per": load_options._yield_per}
  451. )
  452. if (
  453. getattr(statement._compile_options, "_current_path", None)
  454. and len(statement._compile_options._current_path) > 10
  455. and execution_options.get("compiled_cache", True) is not None
  456. ):
  457. util.warn(
  458. "Loader depth for query is excessively deep; caching will "
  459. "be disabled for additional loaders. For recursive eager "
  460. "loaders consider using the recursion_depth feature. "
  461. "Use the compiled_cache=None execution option to "
  462. "skip this warning."
  463. )
  464. execution_options = execution_options.union(
  465. {"compiled_cache": None}
  466. )
  467. bind_arguments["clause"] = statement
  468. # new in 1.4 - the coercions system is leveraged to allow the
  469. # "subject" mapper of a statement be propagated to the top
  470. # as the statement is built. "subject" mapper is the generally
  471. # standard object used as an identifier for multi-database schemes.
  472. # we are here based on the fact that _propagate_attrs contains
  473. # "compile_state_plugin": "orm". The "plugin_subject"
  474. # needs to be present as well.
  475. try:
  476. plugin_subject = statement._propagate_attrs["plugin_subject"]
  477. except KeyError:
  478. assert False, "statement had 'orm' plugin but no plugin_subject"
  479. else:
  480. if plugin_subject:
  481. bind_arguments["mapper"] = plugin_subject.mapper
  482. if not is_pre_event and load_options._autoflush:
  483. session._autoflush()
  484. return statement, execution_options
  485. @classmethod
  486. def orm_setup_cursor_result(
  487. cls,
  488. session,
  489. statement,
  490. params,
  491. execution_options,
  492. bind_arguments,
  493. result,
  494. ):
  495. execution_context = result.context
  496. compile_state = execution_context.compiled.compile_state
  497. # cover edge case where ORM entities used in legacy select
  498. # were passed to session.execute:
  499. # session.execute(legacy_select([User.id, User.name]))
  500. # see test_query->test_legacy_tuple_old_select
  501. load_options = execution_options.get(
  502. "_sa_orm_load_options", QueryContext.default_load_options
  503. )
  504. if compile_state.compile_options._is_star:
  505. return result
  506. querycontext = QueryContext(
  507. compile_state,
  508. statement,
  509. params,
  510. session,
  511. load_options,
  512. execution_options,
  513. bind_arguments,
  514. )
  515. return loading.instances(result, querycontext)
  516. @property
  517. def _lead_mapper_entities(self):
  518. """return all _MapperEntity objects in the lead entities collection.
  519. Does **not** include entities that have been replaced by
  520. with_entities(), with_only_columns()
  521. """
  522. return [
  523. ent for ent in self._entities if isinstance(ent, _MapperEntity)
  524. ]
  525. def _create_with_polymorphic_adapter(self, ext_info, selectable):
  526. """given MapperEntity or ORMColumnEntity, setup polymorphic loading
  527. if called for by the Mapper.
  528. As of #8168 in 2.0.0rc1, polymorphic adapters, which greatly increase
  529. the complexity of the query creation process, are not used at all
  530. except in the quasi-legacy cases of with_polymorphic referring to an
  531. alias and/or subquery. This would apply to concrete polymorphic
  532. loading, and joined inheritance where a subquery is
  533. passed to with_polymorphic (which is completely unnecessary in modern
  534. use).
  535. """
  536. if (
  537. not ext_info.is_aliased_class
  538. and ext_info.mapper.persist_selectable
  539. not in self._polymorphic_adapters
  540. ):
  541. for mp in ext_info.mapper.iterate_to_root():
  542. self._mapper_loads_polymorphically_with(
  543. mp,
  544. ORMAdapter(
  545. _TraceAdaptRole.WITH_POLYMORPHIC_ADAPTER,
  546. mp,
  547. equivalents=mp._equivalent_columns,
  548. selectable=selectable,
  549. ),
  550. )
  551. def _mapper_loads_polymorphically_with(self, mapper, adapter):
  552. for m2 in mapper._with_polymorphic_mappers or [mapper]:
  553. self._polymorphic_adapters[m2] = adapter
  554. for m in m2.iterate_to_root():
  555. self._polymorphic_adapters[m.local_table] = adapter
  556. @classmethod
  557. def _create_entities_collection(cls, query, legacy):
  558. raise NotImplementedError(
  559. "this method only works for ORMSelectCompileState"
  560. )
  561. class DMLReturningColFilter:
  562. """an adapter used for the DML RETURNING case.
  563. Has a subset of the interface used by
  564. :class:`.ORMAdapter` and is used for :class:`._QueryEntity`
  565. instances to set up their columns as used in RETURNING for a
  566. DML statement.
  567. """
  568. __slots__ = ("mapper", "columns", "__weakref__")
  569. def __init__(self, target_mapper, immediate_dml_mapper):
  570. if (
  571. immediate_dml_mapper is not None
  572. and target_mapper.local_table
  573. is not immediate_dml_mapper.local_table
  574. ):
  575. # joined inh, or in theory other kinds of multi-table mappings
  576. self.mapper = immediate_dml_mapper
  577. else:
  578. # single inh, normal mappings, etc.
  579. self.mapper = target_mapper
  580. self.columns = self.columns = util.WeakPopulateDict(
  581. self.adapt_check_present # type: ignore
  582. )
  583. def __call__(self, col, as_filter):
  584. for cc in sql_util._find_columns(col):
  585. c2 = self.adapt_check_present(cc)
  586. if c2 is not None:
  587. return col
  588. else:
  589. return None
  590. def adapt_check_present(self, col):
  591. mapper = self.mapper
  592. prop = mapper._columntoproperty.get(col, None)
  593. if prop is None:
  594. return None
  595. return mapper.local_table.c.corresponding_column(col)
  596. @sql.base.CompileState.plugin_for("orm", "orm_from_statement")
  597. class ORMFromStatementCompileState(ORMCompileState):
  598. _from_obj_alias = None
  599. _has_mapper_entities = False
  600. statement_container: FromStatement
  601. requested_statement: Union[SelectBase, TextClause, UpdateBase]
  602. dml_table: Optional[_DMLTableElement] = None
  603. _has_orm_entities = False
  604. multi_row_eager_loaders = False
  605. eager_adding_joins = False
  606. compound_eager_adapter = None
  607. extra_criteria_entities = _EMPTY_DICT
  608. eager_joins = _EMPTY_DICT
  609. @classmethod
  610. def create_for_statement(
  611. cls,
  612. statement_container: Union[Select, FromStatement],
  613. compiler: Optional[SQLCompiler],
  614. **kw: Any,
  615. ) -> ORMFromStatementCompileState:
  616. assert isinstance(statement_container, FromStatement)
  617. if compiler is not None and compiler.stack:
  618. raise sa_exc.CompileError(
  619. "The ORM FromStatement construct only supports being "
  620. "invoked as the topmost statement, as it is only intended to "
  621. "define how result rows should be returned."
  622. )
  623. self = cls.__new__(cls)
  624. self._primary_entity = None
  625. self.use_legacy_query_style = (
  626. statement_container._compile_options._use_legacy_query_style
  627. )
  628. self.statement_container = self.select_statement = statement_container
  629. self.requested_statement = statement = statement_container.element
  630. if statement.is_dml:
  631. self.dml_table = statement.table
  632. self.is_dml_returning = True
  633. self._entities = []
  634. self._polymorphic_adapters = {}
  635. self.compile_options = statement_container._compile_options
  636. if (
  637. self.use_legacy_query_style
  638. and isinstance(statement, expression.SelectBase)
  639. and not statement._is_textual
  640. and not statement.is_dml
  641. and statement._label_style is LABEL_STYLE_NONE
  642. ):
  643. self.statement = statement.set_label_style(
  644. LABEL_STYLE_TABLENAME_PLUS_COL
  645. )
  646. else:
  647. self.statement = statement
  648. self._label_convention = self._column_naming_convention(
  649. statement._label_style
  650. if not statement._is_textual and not statement.is_dml
  651. else LABEL_STYLE_NONE,
  652. self.use_legacy_query_style,
  653. )
  654. _QueryEntity.to_compile_state(
  655. self,
  656. statement_container._raw_columns,
  657. self._entities,
  658. is_current_entities=True,
  659. )
  660. self.current_path = statement_container._compile_options._current_path
  661. self._init_global_attributes(
  662. statement_container,
  663. compiler,
  664. process_criteria_for_toplevel=False,
  665. toplevel=True,
  666. )
  667. if statement_container._with_options:
  668. for opt in statement_container._with_options:
  669. if opt._is_compile_state:
  670. opt.process_compile_state(self)
  671. if statement_container._with_context_options:
  672. for fn, key in statement_container._with_context_options:
  673. fn(self)
  674. self.primary_columns = []
  675. self.secondary_columns = []
  676. self.dedupe_columns = set()
  677. self.create_eager_joins = []
  678. self._fallback_from_clauses = []
  679. self.order_by = None
  680. if isinstance(self.statement, expression.TextClause):
  681. # TextClause has no "column" objects at all. for this case,
  682. # we generate columns from our _QueryEntity objects, then
  683. # flip on all the "please match no matter what" parameters.
  684. self.extra_criteria_entities = {}
  685. for entity in self._entities:
  686. entity.setup_compile_state(self)
  687. compiler._ordered_columns = (
  688. compiler._textual_ordered_columns
  689. ) = False
  690. # enable looser result column matching. this is shown to be
  691. # needed by test_query.py::TextTest
  692. compiler._loose_column_name_matching = True
  693. for c in self.primary_columns:
  694. compiler.process(
  695. c,
  696. within_columns_clause=True,
  697. add_to_result_map=compiler._add_to_result_map,
  698. )
  699. else:
  700. # for everyone else, Select, Insert, Update, TextualSelect, they
  701. # have column objects already. After much
  702. # experimentation here, the best approach seems to be, use
  703. # those columns completely, don't interfere with the compiler
  704. # at all; just in ORM land, use an adapter to convert from
  705. # our ORM columns to whatever columns are in the statement,
  706. # before we look in the result row. Adapt on names
  707. # to accept cases such as issue #9217, however also allow
  708. # this to be overridden for cases such as #9273.
  709. self._from_obj_alias = ORMStatementAdapter(
  710. _TraceAdaptRole.ADAPT_FROM_STATEMENT,
  711. self.statement,
  712. adapt_on_names=statement_container._adapt_on_names,
  713. )
  714. return self
  715. def _adapt_col_list(self, cols, current_adapter):
  716. return cols
  717. def _get_current_adapter(self):
  718. return None
  719. def setup_dml_returning_compile_state(self, dml_mapper):
  720. """used by BulkORMInsert (and Update / Delete?) to set up a handler
  721. for RETURNING to return ORM objects and expressions
  722. """
  723. target_mapper = self.statement._propagate_attrs.get(
  724. "plugin_subject", None
  725. )
  726. adapter = DMLReturningColFilter(target_mapper, dml_mapper)
  727. if self.compile_options._is_star and (len(self._entities) != 1):
  728. raise sa_exc.CompileError(
  729. "Can't generate ORM query that includes multiple expressions "
  730. "at the same time as '*'; query for '*' alone if present"
  731. )
  732. for entity in self._entities:
  733. entity.setup_dml_returning_compile_state(self, adapter)
  734. class FromStatement(GroupedElement, Generative, TypedReturnsRows[_TP]):
  735. """Core construct that represents a load of ORM objects from various
  736. :class:`.ReturnsRows` and other classes including:
  737. :class:`.Select`, :class:`.TextClause`, :class:`.TextualSelect`,
  738. :class:`.CompoundSelect`, :class`.Insert`, :class:`.Update`,
  739. and in theory, :class:`.Delete`.
  740. """
  741. __visit_name__ = "orm_from_statement"
  742. _compile_options = ORMFromStatementCompileState.default_compile_options
  743. _compile_state_factory = ORMFromStatementCompileState.create_for_statement
  744. _for_update_arg = None
  745. element: Union[ExecutableReturnsRows, TextClause]
  746. _adapt_on_names: bool
  747. _traverse_internals = [
  748. ("_raw_columns", InternalTraversal.dp_clauseelement_list),
  749. ("element", InternalTraversal.dp_clauseelement),
  750. ] + Executable._executable_traverse_internals
  751. _cache_key_traversal = _traverse_internals + [
  752. ("_compile_options", InternalTraversal.dp_has_cache_key)
  753. ]
  754. def __init__(
  755. self,
  756. entities: Iterable[_ColumnsClauseArgument[Any]],
  757. element: Union[ExecutableReturnsRows, TextClause],
  758. _adapt_on_names: bool = True,
  759. ):
  760. self._raw_columns = [
  761. coercions.expect(
  762. roles.ColumnsClauseRole,
  763. ent,
  764. apply_propagate_attrs=self,
  765. post_inspect=True,
  766. )
  767. for ent in util.to_list(entities)
  768. ]
  769. self.element = element
  770. self.is_dml = element.is_dml
  771. self._label_style = (
  772. element._label_style if is_select_base(element) else None
  773. )
  774. self._adapt_on_names = _adapt_on_names
  775. def _compiler_dispatch(self, compiler, **kw):
  776. """provide a fixed _compiler_dispatch method.
  777. This is roughly similar to using the sqlalchemy.ext.compiler
  778. ``@compiles`` extension.
  779. """
  780. compile_state = self._compile_state_factory(self, compiler, **kw)
  781. toplevel = not compiler.stack
  782. if toplevel:
  783. compiler.compile_state = compile_state
  784. return compiler.process(compile_state.statement, **kw)
  785. @property
  786. def column_descriptions(self):
  787. """Return a :term:`plugin-enabled` 'column descriptions' structure
  788. referring to the columns which are SELECTed by this statement.
  789. See the section :ref:`queryguide_inspection` for an overview
  790. of this feature.
  791. .. seealso::
  792. :ref:`queryguide_inspection` - ORM background
  793. """
  794. meth = cast(
  795. ORMSelectCompileState, SelectState.get_plugin_class(self)
  796. ).get_column_descriptions
  797. return meth(self)
  798. def _ensure_disambiguated_names(self):
  799. return self
  800. def get_children(self, **kw):
  801. yield from itertools.chain.from_iterable(
  802. element._from_objects for element in self._raw_columns
  803. )
  804. yield from super().get_children(**kw)
  805. @property
  806. def _all_selected_columns(self):
  807. return self.element._all_selected_columns
  808. @property
  809. def _return_defaults(self):
  810. return self.element._return_defaults if is_dml(self.element) else None
  811. @property
  812. def _returning(self):
  813. return self.element._returning if is_dml(self.element) else None
  814. @property
  815. def _inline(self):
  816. return self.element._inline if is_insert_update(self.element) else None
  817. @sql.base.CompileState.plugin_for("orm", "compound_select")
  818. class CompoundSelectCompileState(
  819. AutoflushOnlyORMCompileState, CompoundSelectState
  820. ):
  821. pass
  822. @sql.base.CompileState.plugin_for("orm", "select")
  823. class ORMSelectCompileState(ORMCompileState, SelectState):
  824. _already_joined_edges = ()
  825. _memoized_entities = _EMPTY_DICT
  826. _from_obj_alias = None
  827. _has_mapper_entities = False
  828. _has_orm_entities = False
  829. multi_row_eager_loaders = False
  830. eager_adding_joins = False
  831. compound_eager_adapter = None
  832. correlate = None
  833. correlate_except = None
  834. _where_criteria = ()
  835. _having_criteria = ()
  836. @classmethod
  837. def create_for_statement(
  838. cls,
  839. statement: Union[Select, FromStatement],
  840. compiler: Optional[SQLCompiler],
  841. **kw: Any,
  842. ) -> ORMSelectCompileState:
  843. """compiler hook, we arrive here from compiler.visit_select() only."""
  844. self = cls.__new__(cls)
  845. if compiler is not None:
  846. toplevel = not compiler.stack
  847. else:
  848. toplevel = True
  849. select_statement = statement
  850. # if we are a select() that was never a legacy Query, we won't
  851. # have ORM level compile options.
  852. statement._compile_options = cls.default_compile_options.safe_merge(
  853. statement._compile_options
  854. )
  855. if select_statement._execution_options:
  856. # execution options should not impact the compilation of a
  857. # query, and at the moment subqueryloader is putting some things
  858. # in here that we explicitly don't want stuck in a cache.
  859. self.select_statement = select_statement._clone()
  860. self.select_statement._execution_options = util.immutabledict()
  861. else:
  862. self.select_statement = select_statement
  863. # indicates this select() came from Query.statement
  864. self.for_statement = select_statement._compile_options._for_statement
  865. # generally if we are from Query or directly from a select()
  866. self.use_legacy_query_style = (
  867. select_statement._compile_options._use_legacy_query_style
  868. )
  869. self._entities = []
  870. self._primary_entity = None
  871. self._polymorphic_adapters = {}
  872. self.compile_options = select_statement._compile_options
  873. if not toplevel:
  874. # for subqueries, turn off eagerloads and set
  875. # "render_for_subquery".
  876. self.compile_options += {
  877. "_enable_eagerloads": False,
  878. "_render_for_subquery": True,
  879. }
  880. # determine label style. we can make different decisions here.
  881. # at the moment, trying to see if we can always use DISAMBIGUATE_ONLY
  882. # rather than LABEL_STYLE_NONE, and if we can use disambiguate style
  883. # for new style ORM selects too.
  884. if (
  885. self.use_legacy_query_style
  886. and self.select_statement._label_style is LABEL_STYLE_LEGACY_ORM
  887. ):
  888. if not self.for_statement:
  889. self.label_style = LABEL_STYLE_TABLENAME_PLUS_COL
  890. else:
  891. self.label_style = LABEL_STYLE_DISAMBIGUATE_ONLY
  892. else:
  893. self.label_style = self.select_statement._label_style
  894. if select_statement._memoized_select_entities:
  895. self._memoized_entities = {
  896. memoized_entities: _QueryEntity.to_compile_state(
  897. self,
  898. memoized_entities._raw_columns,
  899. [],
  900. is_current_entities=False,
  901. )
  902. for memoized_entities in (
  903. select_statement._memoized_select_entities
  904. )
  905. }
  906. # label_convention is stateful and will yield deduping keys if it
  907. # sees the same key twice. therefore it's important that it is not
  908. # invoked for the above "memoized" entities that aren't actually
  909. # in the columns clause
  910. self._label_convention = self._column_naming_convention(
  911. statement._label_style, self.use_legacy_query_style
  912. )
  913. _QueryEntity.to_compile_state(
  914. self,
  915. select_statement._raw_columns,
  916. self._entities,
  917. is_current_entities=True,
  918. )
  919. self.current_path = select_statement._compile_options._current_path
  920. self.eager_order_by = ()
  921. self._init_global_attributes(
  922. select_statement,
  923. compiler,
  924. toplevel=toplevel,
  925. process_criteria_for_toplevel=False,
  926. )
  927. if toplevel and (
  928. select_statement._with_options
  929. or select_statement._memoized_select_entities
  930. ):
  931. for (
  932. memoized_entities
  933. ) in select_statement._memoized_select_entities:
  934. for opt in memoized_entities._with_options:
  935. if opt._is_compile_state:
  936. opt.process_compile_state_replaced_entities(
  937. self,
  938. [
  939. ent
  940. for ent in self._memoized_entities[
  941. memoized_entities
  942. ]
  943. if isinstance(ent, _MapperEntity)
  944. ],
  945. )
  946. for opt in self.select_statement._with_options:
  947. if opt._is_compile_state:
  948. opt.process_compile_state(self)
  949. # uncomment to print out the context.attributes structure
  950. # after it's been set up above
  951. # self._dump_option_struct()
  952. if select_statement._with_context_options:
  953. for fn, key in select_statement._with_context_options:
  954. fn(self)
  955. self.primary_columns = []
  956. self.secondary_columns = []
  957. self.dedupe_columns = set()
  958. self.eager_joins = {}
  959. self.extra_criteria_entities = {}
  960. self.create_eager_joins = []
  961. self._fallback_from_clauses = []
  962. # normalize the FROM clauses early by themselves, as this makes
  963. # it an easier job when we need to assemble a JOIN onto these,
  964. # for select.join() as well as joinedload(). As of 1.4 there are now
  965. # potentially more complex sets of FROM objects here as the use
  966. # of lambda statements for lazyload, load_on_pk etc. uses more
  967. # cloning of the select() construct. See #6495
  968. self.from_clauses = self._normalize_froms(
  969. info.selectable for info in select_statement._from_obj
  970. )
  971. # this is a fairly arbitrary break into a second method,
  972. # so it might be nicer to break up create_for_statement()
  973. # and _setup_for_generate into three or four logical sections
  974. self._setup_for_generate()
  975. SelectState.__init__(self, self.statement, compiler, **kw)
  976. return self
  977. def _dump_option_struct(self):
  978. print("\n---------------------------------------------------\n")
  979. print(f"current path: {self.current_path}")
  980. for key in self.attributes:
  981. if isinstance(key, tuple) and key[0] == "loader":
  982. print(f"\nLoader: {PathRegistry.coerce(key[1])}")
  983. print(f" {self.attributes[key]}")
  984. print(f" {self.attributes[key].__dict__}")
  985. elif isinstance(key, tuple) and key[0] == "path_with_polymorphic":
  986. print(f"\nWith Polymorphic: {PathRegistry.coerce(key[1])}")
  987. print(f" {self.attributes[key]}")
  988. def _setup_for_generate(self):
  989. query = self.select_statement
  990. self.statement = None
  991. self._join_entities = ()
  992. if self.compile_options._set_base_alias:
  993. # legacy Query only
  994. self._set_select_from_alias()
  995. for memoized_entities in query._memoized_select_entities:
  996. if memoized_entities._setup_joins:
  997. self._join(
  998. memoized_entities._setup_joins,
  999. self._memoized_entities[memoized_entities],
  1000. )
  1001. if query._setup_joins:
  1002. self._join(query._setup_joins, self._entities)
  1003. current_adapter = self._get_current_adapter()
  1004. if query._where_criteria:
  1005. self._where_criteria = query._where_criteria
  1006. if current_adapter:
  1007. self._where_criteria = tuple(
  1008. current_adapter(crit, True)
  1009. for crit in self._where_criteria
  1010. )
  1011. # TODO: some complexity with order_by here was due to mapper.order_by.
  1012. # now that this is removed we can hopefully make order_by /
  1013. # group_by act identically to how they are in Core select.
  1014. self.order_by = (
  1015. self._adapt_col_list(query._order_by_clauses, current_adapter)
  1016. if current_adapter and query._order_by_clauses not in (None, False)
  1017. else query._order_by_clauses
  1018. )
  1019. if query._having_criteria:
  1020. self._having_criteria = tuple(
  1021. current_adapter(crit, True) if current_adapter else crit
  1022. for crit in query._having_criteria
  1023. )
  1024. self.group_by = (
  1025. self._adapt_col_list(
  1026. util.flatten_iterator(query._group_by_clauses), current_adapter
  1027. )
  1028. if current_adapter and query._group_by_clauses not in (None, False)
  1029. else query._group_by_clauses or None
  1030. )
  1031. if self.eager_order_by:
  1032. adapter = self.from_clauses[0]._target_adapter
  1033. self.eager_order_by = adapter.copy_and_process(self.eager_order_by)
  1034. if query._distinct_on:
  1035. self.distinct_on = self._adapt_col_list(
  1036. query._distinct_on, current_adapter
  1037. )
  1038. else:
  1039. self.distinct_on = ()
  1040. self.distinct = query._distinct
  1041. if query._correlate:
  1042. # ORM mapped entities that are mapped to joins can be passed
  1043. # to .correlate, so here they are broken into their component
  1044. # tables.
  1045. self.correlate = tuple(
  1046. util.flatten_iterator(
  1047. sql_util.surface_selectables(s) if s is not None else None
  1048. for s in query._correlate
  1049. )
  1050. )
  1051. elif query._correlate_except is not None:
  1052. self.correlate_except = tuple(
  1053. util.flatten_iterator(
  1054. sql_util.surface_selectables(s) if s is not None else None
  1055. for s in query._correlate_except
  1056. )
  1057. )
  1058. elif not query._auto_correlate:
  1059. self.correlate = (None,)
  1060. # PART II
  1061. self._for_update_arg = query._for_update_arg
  1062. if self.compile_options._is_star and (len(self._entities) != 1):
  1063. raise sa_exc.CompileError(
  1064. "Can't generate ORM query that includes multiple expressions "
  1065. "at the same time as '*'; query for '*' alone if present"
  1066. )
  1067. for entity in self._entities:
  1068. entity.setup_compile_state(self)
  1069. for rec in self.create_eager_joins:
  1070. strategy = rec[0]
  1071. strategy(self, *rec[1:])
  1072. # else "load from discrete FROMs" mode,
  1073. # i.e. when each _MappedEntity has its own FROM
  1074. if self.compile_options._enable_single_crit:
  1075. self._adjust_for_extra_criteria()
  1076. if not self.primary_columns:
  1077. if self.compile_options._only_load_props:
  1078. assert False, "no columns were included in _only_load_props"
  1079. raise sa_exc.InvalidRequestError(
  1080. "Query contains no columns with which to SELECT from."
  1081. )
  1082. if not self.from_clauses:
  1083. self.from_clauses = list(self._fallback_from_clauses)
  1084. if self.order_by is False:
  1085. self.order_by = None
  1086. if (
  1087. self.multi_row_eager_loaders
  1088. and self.eager_adding_joins
  1089. and self._should_nest_selectable
  1090. ):
  1091. self.statement = self._compound_eager_statement()
  1092. else:
  1093. self.statement = self._simple_statement()
  1094. if self.for_statement:
  1095. ezero = self._mapper_zero()
  1096. if ezero is not None:
  1097. # TODO: this goes away once we get rid of the deep entity
  1098. # thing
  1099. self.statement = self.statement._annotate(
  1100. {"deepentity": ezero}
  1101. )
  1102. @classmethod
  1103. def _create_entities_collection(cls, query, legacy):
  1104. """Creates a partial ORMSelectCompileState that includes
  1105. the full collection of _MapperEntity and other _QueryEntity objects.
  1106. Supports a few remaining use cases that are pre-compilation
  1107. but still need to gather some of the column / adaption information.
  1108. """
  1109. self = cls.__new__(cls)
  1110. self._entities = []
  1111. self._primary_entity = None
  1112. self._polymorphic_adapters = {}
  1113. self._label_convention = self._column_naming_convention(
  1114. query._label_style, legacy
  1115. )
  1116. # entities will also set up polymorphic adapters for mappers
  1117. # that have with_polymorphic configured
  1118. _QueryEntity.to_compile_state(
  1119. self, query._raw_columns, self._entities, is_current_entities=True
  1120. )
  1121. return self
  1122. @classmethod
  1123. def determine_last_joined_entity(cls, statement):
  1124. setup_joins = statement._setup_joins
  1125. return _determine_last_joined_entity(setup_joins, None)
  1126. @classmethod
  1127. def all_selected_columns(cls, statement):
  1128. for element in statement._raw_columns:
  1129. if (
  1130. element.is_selectable
  1131. and "entity_namespace" in element._annotations
  1132. ):
  1133. ens = element._annotations["entity_namespace"]
  1134. if not ens.is_mapper and not ens.is_aliased_class:
  1135. yield from _select_iterables([element])
  1136. else:
  1137. yield from _select_iterables(ens._all_column_expressions)
  1138. else:
  1139. yield from _select_iterables([element])
  1140. @classmethod
  1141. def get_columns_clause_froms(cls, statement):
  1142. return cls._normalize_froms(
  1143. itertools.chain.from_iterable(
  1144. element._from_objects
  1145. if "parententity" not in element._annotations
  1146. else [
  1147. element._annotations["parententity"].__clause_element__()
  1148. ]
  1149. for element in statement._raw_columns
  1150. )
  1151. )
  1152. @classmethod
  1153. def from_statement(cls, statement, from_statement):
  1154. from_statement = coercions.expect(
  1155. roles.ReturnsRowsRole,
  1156. from_statement,
  1157. apply_propagate_attrs=statement,
  1158. )
  1159. stmt = FromStatement(statement._raw_columns, from_statement)
  1160. stmt.__dict__.update(
  1161. _with_options=statement._with_options,
  1162. _with_context_options=statement._with_context_options,
  1163. _execution_options=statement._execution_options,
  1164. _propagate_attrs=statement._propagate_attrs,
  1165. )
  1166. return stmt
  1167. def _set_select_from_alias(self):
  1168. """used only for legacy Query cases"""
  1169. query = self.select_statement # query
  1170. assert self.compile_options._set_base_alias
  1171. assert len(query._from_obj) == 1
  1172. adapter = self._get_select_from_alias_from_obj(query._from_obj[0])
  1173. if adapter:
  1174. self.compile_options += {"_enable_single_crit": False}
  1175. self._from_obj_alias = adapter
  1176. def _get_select_from_alias_from_obj(self, from_obj):
  1177. """used only for legacy Query cases"""
  1178. info = from_obj
  1179. if "parententity" in info._annotations:
  1180. info = info._annotations["parententity"]
  1181. if hasattr(info, "mapper"):
  1182. if not info.is_aliased_class:
  1183. raise sa_exc.ArgumentError(
  1184. "A selectable (FromClause) instance is "
  1185. "expected when the base alias is being set."
  1186. )
  1187. else:
  1188. return info._adapter
  1189. elif isinstance(info.selectable, sql.selectable.AliasedReturnsRows):
  1190. equivs = self._all_equivs()
  1191. assert info is info.selectable
  1192. return ORMStatementAdapter(
  1193. _TraceAdaptRole.LEGACY_SELECT_FROM_ALIAS,
  1194. info.selectable,
  1195. equivalents=equivs,
  1196. )
  1197. else:
  1198. return None
  1199. def _mapper_zero(self):
  1200. """return the Mapper associated with the first QueryEntity."""
  1201. return self._entities[0].mapper
  1202. def _entity_zero(self):
  1203. """Return the 'entity' (mapper or AliasedClass) associated
  1204. with the first QueryEntity, or alternatively the 'select from'
  1205. entity if specified."""
  1206. for ent in self.from_clauses:
  1207. if "parententity" in ent._annotations:
  1208. return ent._annotations["parententity"]
  1209. for qent in self._entities:
  1210. if qent.entity_zero:
  1211. return qent.entity_zero
  1212. return None
  1213. def _only_full_mapper_zero(self, methname):
  1214. if self._entities != [self._primary_entity]:
  1215. raise sa_exc.InvalidRequestError(
  1216. "%s() can only be used against "
  1217. "a single mapped class." % methname
  1218. )
  1219. return self._primary_entity.entity_zero
  1220. def _only_entity_zero(self, rationale=None):
  1221. if len(self._entities) > 1:
  1222. raise sa_exc.InvalidRequestError(
  1223. rationale
  1224. or "This operation requires a Query "
  1225. "against a single mapper."
  1226. )
  1227. return self._entity_zero()
  1228. def _all_equivs(self):
  1229. equivs = {}
  1230. for memoized_entities in self._memoized_entities.values():
  1231. for ent in [
  1232. ent
  1233. for ent in memoized_entities
  1234. if isinstance(ent, _MapperEntity)
  1235. ]:
  1236. equivs.update(ent.mapper._equivalent_columns)
  1237. for ent in [
  1238. ent for ent in self._entities if isinstance(ent, _MapperEntity)
  1239. ]:
  1240. equivs.update(ent.mapper._equivalent_columns)
  1241. return equivs
  1242. def _compound_eager_statement(self):
  1243. # for eager joins present and LIMIT/OFFSET/DISTINCT,
  1244. # wrap the query inside a select,
  1245. # then append eager joins onto that
  1246. if self.order_by:
  1247. # the default coercion for ORDER BY is now the OrderByRole,
  1248. # which adds an additional post coercion to ByOfRole in that
  1249. # elements are converted into label references. For the
  1250. # eager load / subquery wrapping case, we need to un-coerce
  1251. # the original expressions outside of the label references
  1252. # in order to have them render.
  1253. unwrapped_order_by = [
  1254. elem.element
  1255. if isinstance(elem, sql.elements._label_reference)
  1256. else elem
  1257. for elem in self.order_by
  1258. ]
  1259. order_by_col_expr = sql_util.expand_column_list_from_order_by(
  1260. self.primary_columns, unwrapped_order_by
  1261. )
  1262. else:
  1263. order_by_col_expr = []
  1264. unwrapped_order_by = None
  1265. # put FOR UPDATE on the inner query, where MySQL will honor it,
  1266. # as well as if it has an OF so PostgreSQL can use it.
  1267. inner = self._select_statement(
  1268. self.primary_columns
  1269. + [c for c in order_by_col_expr if c not in self.dedupe_columns],
  1270. self.from_clauses,
  1271. self._where_criteria,
  1272. self._having_criteria,
  1273. self.label_style,
  1274. self.order_by,
  1275. for_update=self._for_update_arg,
  1276. hints=self.select_statement._hints,
  1277. statement_hints=self.select_statement._statement_hints,
  1278. correlate=self.correlate,
  1279. correlate_except=self.correlate_except,
  1280. **self._select_args,
  1281. )
  1282. inner = inner.alias()
  1283. equivs = self._all_equivs()
  1284. self.compound_eager_adapter = ORMStatementAdapter(
  1285. _TraceAdaptRole.COMPOUND_EAGER_STATEMENT, inner, equivalents=equivs
  1286. )
  1287. statement = future.select(
  1288. *([inner] + self.secondary_columns) # use_labels=self.labels
  1289. )
  1290. statement._label_style = self.label_style
  1291. # Oracle however does not allow FOR UPDATE on the subquery,
  1292. # and the Oracle dialect ignores it, plus for PostgreSQL, MySQL
  1293. # we expect that all elements of the row are locked, so also put it
  1294. # on the outside (except in the case of PG when OF is used)
  1295. if (
  1296. self._for_update_arg is not None
  1297. and self._for_update_arg.of is None
  1298. ):
  1299. statement._for_update_arg = self._for_update_arg
  1300. from_clause = inner
  1301. for eager_join in self.eager_joins.values():
  1302. # EagerLoader places a 'stop_on' attribute on the join,
  1303. # giving us a marker as to where the "splice point" of
  1304. # the join should be
  1305. from_clause = sql_util.splice_joins(
  1306. from_clause, eager_join, eager_join.stop_on
  1307. )
  1308. statement.select_from.non_generative(statement, from_clause)
  1309. if unwrapped_order_by:
  1310. statement.order_by.non_generative(
  1311. statement,
  1312. *self.compound_eager_adapter.copy_and_process(
  1313. unwrapped_order_by
  1314. ),
  1315. )
  1316. statement.order_by.non_generative(statement, *self.eager_order_by)
  1317. return statement
  1318. def _simple_statement(self):
  1319. statement = self._select_statement(
  1320. self.primary_columns + self.secondary_columns,
  1321. tuple(self.from_clauses) + tuple(self.eager_joins.values()),
  1322. self._where_criteria,
  1323. self._having_criteria,
  1324. self.label_style,
  1325. self.order_by,
  1326. for_update=self._for_update_arg,
  1327. hints=self.select_statement._hints,
  1328. statement_hints=self.select_statement._statement_hints,
  1329. correlate=self.correlate,
  1330. correlate_except=self.correlate_except,
  1331. **self._select_args,
  1332. )
  1333. if self.eager_order_by:
  1334. statement.order_by.non_generative(statement, *self.eager_order_by)
  1335. return statement
  1336. def _select_statement(
  1337. self,
  1338. raw_columns,
  1339. from_obj,
  1340. where_criteria,
  1341. having_criteria,
  1342. label_style,
  1343. order_by,
  1344. for_update,
  1345. hints,
  1346. statement_hints,
  1347. correlate,
  1348. correlate_except,
  1349. limit_clause,
  1350. offset_clause,
  1351. fetch_clause,
  1352. fetch_clause_options,
  1353. distinct,
  1354. distinct_on,
  1355. prefixes,
  1356. suffixes,
  1357. group_by,
  1358. independent_ctes,
  1359. independent_ctes_opts,
  1360. ):
  1361. statement = Select._create_raw_select(
  1362. _raw_columns=raw_columns,
  1363. _from_obj=from_obj,
  1364. _label_style=label_style,
  1365. )
  1366. if where_criteria:
  1367. statement._where_criteria = where_criteria
  1368. if having_criteria:
  1369. statement._having_criteria = having_criteria
  1370. if order_by:
  1371. statement._order_by_clauses += tuple(order_by)
  1372. if distinct_on:
  1373. statement.distinct.non_generative(statement, *distinct_on)
  1374. elif distinct:
  1375. statement.distinct.non_generative(statement)
  1376. if group_by:
  1377. statement._group_by_clauses += tuple(group_by)
  1378. statement._limit_clause = limit_clause
  1379. statement._offset_clause = offset_clause
  1380. statement._fetch_clause = fetch_clause
  1381. statement._fetch_clause_options = fetch_clause_options
  1382. statement._independent_ctes = independent_ctes
  1383. statement._independent_ctes_opts = independent_ctes_opts
  1384. if prefixes:
  1385. statement._prefixes = prefixes
  1386. if suffixes:
  1387. statement._suffixes = suffixes
  1388. statement._for_update_arg = for_update
  1389. if hints:
  1390. statement._hints = hints
  1391. if statement_hints:
  1392. statement._statement_hints = statement_hints
  1393. if correlate:
  1394. statement.correlate.non_generative(statement, *correlate)
  1395. if correlate_except is not None:
  1396. statement.correlate_except.non_generative(
  1397. statement, *correlate_except
  1398. )
  1399. return statement
  1400. def _adapt_polymorphic_element(self, element):
  1401. if "parententity" in element._annotations:
  1402. search = element._annotations["parententity"]
  1403. alias = self._polymorphic_adapters.get(search, None)
  1404. if alias:
  1405. return alias.adapt_clause(element)
  1406. if isinstance(element, expression.FromClause):
  1407. search = element
  1408. elif hasattr(element, "table"):
  1409. search = element.table
  1410. else:
  1411. return None
  1412. alias = self._polymorphic_adapters.get(search, None)
  1413. if alias:
  1414. return alias.adapt_clause(element)
  1415. def _adapt_col_list(self, cols, current_adapter):
  1416. if current_adapter:
  1417. return [current_adapter(o, True) for o in cols]
  1418. else:
  1419. return cols
  1420. def _get_current_adapter(self):
  1421. adapters = []
  1422. if self._from_obj_alias:
  1423. # used for legacy going forward for query set_ops, e.g.
  1424. # union(), union_all(), etc.
  1425. # 1.4 and previously, also used for from_self(),
  1426. # select_entity_from()
  1427. #
  1428. # for the "from obj" alias, apply extra rule to the
  1429. # 'ORM only' check, if this query were generated from a
  1430. # subquery of itself, i.e. _from_selectable(), apply adaption
  1431. # to all SQL constructs.
  1432. adapters.append(
  1433. (
  1434. True,
  1435. self._from_obj_alias.replace,
  1436. )
  1437. )
  1438. # this was *hopefully* the only adapter we were going to need
  1439. # going forward...however, we unfortunately need _from_obj_alias
  1440. # for query.union(), which we can't drop
  1441. if self._polymorphic_adapters:
  1442. adapters.append((False, self._adapt_polymorphic_element))
  1443. if not adapters:
  1444. return None
  1445. def _adapt_clause(clause, as_filter):
  1446. # do we adapt all expression elements or only those
  1447. # tagged as 'ORM' constructs ?
  1448. def replace(elem):
  1449. is_orm_adapt = (
  1450. "_orm_adapt" in elem._annotations
  1451. or "parententity" in elem._annotations
  1452. )
  1453. for always_adapt, adapter in adapters:
  1454. if is_orm_adapt or always_adapt:
  1455. e = adapter(elem)
  1456. if e is not None:
  1457. return e
  1458. return visitors.replacement_traverse(clause, {}, replace)
  1459. return _adapt_clause
  1460. def _join(self, args, entities_collection):
  1461. for right, onclause, from_, flags in args:
  1462. isouter = flags["isouter"]
  1463. full = flags["full"]
  1464. right = inspect(right)
  1465. if onclause is not None:
  1466. onclause = inspect(onclause)
  1467. if isinstance(right, interfaces.PropComparator):
  1468. if onclause is not None:
  1469. raise sa_exc.InvalidRequestError(
  1470. "No 'on clause' argument may be passed when joining "
  1471. "to a relationship path as a target"
  1472. )
  1473. onclause = right
  1474. right = None
  1475. elif "parententity" in right._annotations:
  1476. right = right._annotations["parententity"]
  1477. if onclause is None:
  1478. if not right.is_selectable and not hasattr(right, "mapper"):
  1479. raise sa_exc.ArgumentError(
  1480. "Expected mapped entity or "
  1481. "selectable/table as join target"
  1482. )
  1483. of_type = None
  1484. if isinstance(onclause, interfaces.PropComparator):
  1485. # descriptor/property given (or determined); this tells us
  1486. # explicitly what the expected "left" side of the join is.
  1487. of_type = getattr(onclause, "_of_type", None)
  1488. if right is None:
  1489. if of_type:
  1490. right = of_type
  1491. else:
  1492. right = onclause.property
  1493. try:
  1494. right = right.entity
  1495. except AttributeError as err:
  1496. raise sa_exc.ArgumentError(
  1497. "Join target %s does not refer to a "
  1498. "mapped entity" % right
  1499. ) from err
  1500. left = onclause._parententity
  1501. prop = onclause.property
  1502. if not isinstance(onclause, attributes.QueryableAttribute):
  1503. onclause = prop
  1504. # check for this path already present. don't render in that
  1505. # case.
  1506. if (left, right, prop.key) in self._already_joined_edges:
  1507. continue
  1508. if from_ is not None:
  1509. if (
  1510. from_ is not left
  1511. and from_._annotations.get("parententity", None)
  1512. is not left
  1513. ):
  1514. raise sa_exc.InvalidRequestError(
  1515. "explicit from clause %s does not match left side "
  1516. "of relationship attribute %s"
  1517. % (
  1518. from_._annotations.get("parententity", from_),
  1519. onclause,
  1520. )
  1521. )
  1522. elif from_ is not None:
  1523. prop = None
  1524. left = from_
  1525. else:
  1526. # no descriptor/property given; we will need to figure out
  1527. # what the effective "left" side is
  1528. prop = left = None
  1529. # figure out the final "left" and "right" sides and create an
  1530. # ORMJoin to add to our _from_obj tuple
  1531. self._join_left_to_right(
  1532. entities_collection,
  1533. left,
  1534. right,
  1535. onclause,
  1536. prop,
  1537. isouter,
  1538. full,
  1539. )
  1540. def _join_left_to_right(
  1541. self,
  1542. entities_collection,
  1543. left,
  1544. right,
  1545. onclause,
  1546. prop,
  1547. outerjoin,
  1548. full,
  1549. ):
  1550. """given raw "left", "right", "onclause" parameters consumed from
  1551. a particular key within _join(), add a real ORMJoin object to
  1552. our _from_obj list (or augment an existing one)
  1553. """
  1554. if left is None:
  1555. # left not given (e.g. no relationship object/name specified)
  1556. # figure out the best "left" side based on our existing froms /
  1557. # entities
  1558. assert prop is None
  1559. (
  1560. left,
  1561. replace_from_obj_index,
  1562. use_entity_index,
  1563. ) = self._join_determine_implicit_left_side(
  1564. entities_collection, left, right, onclause
  1565. )
  1566. else:
  1567. # left is given via a relationship/name, or as explicit left side.
  1568. # Determine where in our
  1569. # "froms" list it should be spliced/appended as well as what
  1570. # existing entity it corresponds to.
  1571. (
  1572. replace_from_obj_index,
  1573. use_entity_index,
  1574. ) = self._join_place_explicit_left_side(entities_collection, left)
  1575. if left is right:
  1576. raise sa_exc.InvalidRequestError(
  1577. "Can't construct a join from %s to %s, they "
  1578. "are the same entity" % (left, right)
  1579. )
  1580. # the right side as given often needs to be adapted. additionally
  1581. # a lot of things can be wrong with it. handle all that and
  1582. # get back the new effective "right" side
  1583. r_info, right, onclause = self._join_check_and_adapt_right_side(
  1584. left, right, onclause, prop
  1585. )
  1586. if not r_info.is_selectable:
  1587. extra_criteria = self._get_extra_criteria(r_info)
  1588. else:
  1589. extra_criteria = ()
  1590. if replace_from_obj_index is not None:
  1591. # splice into an existing element in the
  1592. # self._from_obj list
  1593. left_clause = self.from_clauses[replace_from_obj_index]
  1594. self.from_clauses = (
  1595. self.from_clauses[:replace_from_obj_index]
  1596. + [
  1597. _ORMJoin(
  1598. left_clause,
  1599. right,
  1600. onclause,
  1601. isouter=outerjoin,
  1602. full=full,
  1603. _extra_criteria=extra_criteria,
  1604. )
  1605. ]
  1606. + self.from_clauses[replace_from_obj_index + 1 :]
  1607. )
  1608. else:
  1609. # add a new element to the self._from_obj list
  1610. if use_entity_index is not None:
  1611. # make use of _MapperEntity selectable, which is usually
  1612. # entity_zero.selectable, but if with_polymorphic() were used
  1613. # might be distinct
  1614. assert isinstance(
  1615. entities_collection[use_entity_index], _MapperEntity
  1616. )
  1617. left_clause = entities_collection[use_entity_index].selectable
  1618. else:
  1619. left_clause = left
  1620. self.from_clauses = self.from_clauses + [
  1621. _ORMJoin(
  1622. left_clause,
  1623. r_info,
  1624. onclause,
  1625. isouter=outerjoin,
  1626. full=full,
  1627. _extra_criteria=extra_criteria,
  1628. )
  1629. ]
  1630. def _join_determine_implicit_left_side(
  1631. self, entities_collection, left, right, onclause
  1632. ):
  1633. """When join conditions don't express the left side explicitly,
  1634. determine if an existing FROM or entity in this query
  1635. can serve as the left hand side.
  1636. """
  1637. # when we are here, it means join() was called without an ORM-
  1638. # specific way of telling us what the "left" side is, e.g.:
  1639. #
  1640. # join(RightEntity)
  1641. #
  1642. # or
  1643. #
  1644. # join(RightEntity, RightEntity.foo == LeftEntity.bar)
  1645. #
  1646. r_info = inspect(right)
  1647. replace_from_obj_index = use_entity_index = None
  1648. if self.from_clauses:
  1649. # we have a list of FROMs already. So by definition this
  1650. # join has to connect to one of those FROMs.
  1651. indexes = sql_util.find_left_clause_to_join_from(
  1652. self.from_clauses, r_info.selectable, onclause
  1653. )
  1654. if len(indexes) == 1:
  1655. replace_from_obj_index = indexes[0]
  1656. left = self.from_clauses[replace_from_obj_index]
  1657. elif len(indexes) > 1:
  1658. raise sa_exc.InvalidRequestError(
  1659. "Can't determine which FROM clause to join "
  1660. "from, there are multiple FROMS which can "
  1661. "join to this entity. Please use the .select_from() "
  1662. "method to establish an explicit left side, as well as "
  1663. "providing an explicit ON clause if not present already "
  1664. "to help resolve the ambiguity."
  1665. )
  1666. else:
  1667. raise sa_exc.InvalidRequestError(
  1668. "Don't know how to join to %r. "
  1669. "Please use the .select_from() "
  1670. "method to establish an explicit left side, as well as "
  1671. "providing an explicit ON clause if not present already "
  1672. "to help resolve the ambiguity." % (right,)
  1673. )
  1674. elif entities_collection:
  1675. # we have no explicit FROMs, so the implicit left has to
  1676. # come from our list of entities.
  1677. potential = {}
  1678. for entity_index, ent in enumerate(entities_collection):
  1679. entity = ent.entity_zero_or_selectable
  1680. if entity is None:
  1681. continue
  1682. ent_info = inspect(entity)
  1683. if ent_info is r_info: # left and right are the same, skip
  1684. continue
  1685. # by using a dictionary with the selectables as keys this
  1686. # de-duplicates those selectables as occurs when the query is
  1687. # against a series of columns from the same selectable
  1688. if isinstance(ent, _MapperEntity):
  1689. potential[ent.selectable] = (entity_index, entity)
  1690. else:
  1691. potential[ent_info.selectable] = (None, entity)
  1692. all_clauses = list(potential.keys())
  1693. indexes = sql_util.find_left_clause_to_join_from(
  1694. all_clauses, r_info.selectable, onclause
  1695. )
  1696. if len(indexes) == 1:
  1697. use_entity_index, left = potential[all_clauses[indexes[0]]]
  1698. elif len(indexes) > 1:
  1699. raise sa_exc.InvalidRequestError(
  1700. "Can't determine which FROM clause to join "
  1701. "from, there are multiple FROMS which can "
  1702. "join to this entity. Please use the .select_from() "
  1703. "method to establish an explicit left side, as well as "
  1704. "providing an explicit ON clause if not present already "
  1705. "to help resolve the ambiguity."
  1706. )
  1707. else:
  1708. raise sa_exc.InvalidRequestError(
  1709. "Don't know how to join to %r. "
  1710. "Please use the .select_from() "
  1711. "method to establish an explicit left side, as well as "
  1712. "providing an explicit ON clause if not present already "
  1713. "to help resolve the ambiguity." % (right,)
  1714. )
  1715. else:
  1716. raise sa_exc.InvalidRequestError(
  1717. "No entities to join from; please use "
  1718. "select_from() to establish the left "
  1719. "entity/selectable of this join"
  1720. )
  1721. return left, replace_from_obj_index, use_entity_index
  1722. def _join_place_explicit_left_side(self, entities_collection, left):
  1723. """When join conditions express a left side explicitly, determine
  1724. where in our existing list of FROM clauses we should join towards,
  1725. or if we need to make a new join, and if so is it from one of our
  1726. existing entities.
  1727. """
  1728. # when we are here, it means join() was called with an indicator
  1729. # as to an exact left side, which means a path to a
  1730. # Relationship was given, e.g.:
  1731. #
  1732. # join(RightEntity, LeftEntity.right)
  1733. #
  1734. # or
  1735. #
  1736. # join(LeftEntity.right)
  1737. #
  1738. # as well as string forms:
  1739. #
  1740. # join(RightEntity, "right")
  1741. #
  1742. # etc.
  1743. #
  1744. replace_from_obj_index = use_entity_index = None
  1745. l_info = inspect(left)
  1746. if self.from_clauses:
  1747. indexes = sql_util.find_left_clause_that_matches_given(
  1748. self.from_clauses, l_info.selectable
  1749. )
  1750. if len(indexes) > 1:
  1751. raise sa_exc.InvalidRequestError(
  1752. "Can't identify which entity in which to assign the "
  1753. "left side of this join. Please use a more specific "
  1754. "ON clause."
  1755. )
  1756. # have an index, means the left side is already present in
  1757. # an existing FROM in the self._from_obj tuple
  1758. if indexes:
  1759. replace_from_obj_index = indexes[0]
  1760. # no index, means we need to add a new element to the
  1761. # self._from_obj tuple
  1762. # no from element present, so we will have to add to the
  1763. # self._from_obj tuple. Determine if this left side matches up
  1764. # with existing mapper entities, in which case we want to apply the
  1765. # aliasing / adaptation rules present on that entity if any
  1766. if (
  1767. replace_from_obj_index is None
  1768. and entities_collection
  1769. and hasattr(l_info, "mapper")
  1770. ):
  1771. for idx, ent in enumerate(entities_collection):
  1772. # TODO: should we be checking for multiple mapper entities
  1773. # matching?
  1774. if isinstance(ent, _MapperEntity) and ent.corresponds_to(left):
  1775. use_entity_index = idx
  1776. break
  1777. return replace_from_obj_index, use_entity_index
  1778. def _join_check_and_adapt_right_side(self, left, right, onclause, prop):
  1779. """transform the "right" side of the join as well as the onclause
  1780. according to polymorphic mapping translations, aliasing on the query
  1781. or on the join, special cases where the right and left side have
  1782. overlapping tables.
  1783. """
  1784. l_info = inspect(left)
  1785. r_info = inspect(right)
  1786. overlap = False
  1787. right_mapper = getattr(r_info, "mapper", None)
  1788. # if the target is a joined inheritance mapping,
  1789. # be more liberal about auto-aliasing.
  1790. if right_mapper and (
  1791. right_mapper.with_polymorphic
  1792. or isinstance(right_mapper.persist_selectable, expression.Join)
  1793. ):
  1794. for from_obj in self.from_clauses or [l_info.selectable]:
  1795. if sql_util.selectables_overlap(
  1796. l_info.selectable, from_obj
  1797. ) and sql_util.selectables_overlap(
  1798. from_obj, r_info.selectable
  1799. ):
  1800. overlap = True
  1801. break
  1802. if overlap and l_info.selectable is r_info.selectable:
  1803. raise sa_exc.InvalidRequestError(
  1804. "Can't join table/selectable '%s' to itself"
  1805. % l_info.selectable
  1806. )
  1807. right_mapper, right_selectable, right_is_aliased = (
  1808. getattr(r_info, "mapper", None),
  1809. r_info.selectable,
  1810. getattr(r_info, "is_aliased_class", False),
  1811. )
  1812. if (
  1813. right_mapper
  1814. and prop
  1815. and not right_mapper.common_parent(prop.mapper)
  1816. ):
  1817. raise sa_exc.InvalidRequestError(
  1818. "Join target %s does not correspond to "
  1819. "the right side of join condition %s" % (right, onclause)
  1820. )
  1821. # _join_entities is used as a hint for single-table inheritance
  1822. # purposes at the moment
  1823. if hasattr(r_info, "mapper"):
  1824. self._join_entities += (r_info,)
  1825. need_adapter = False
  1826. # test for joining to an unmapped selectable as the target
  1827. if r_info.is_clause_element:
  1828. if prop:
  1829. right_mapper = prop.mapper
  1830. if right_selectable._is_lateral:
  1831. # orm_only is disabled to suit the case where we have to
  1832. # adapt an explicit correlate(Entity) - the select() loses
  1833. # the ORM-ness in this case right now, ideally it would not
  1834. current_adapter = self._get_current_adapter()
  1835. if current_adapter is not None:
  1836. # TODO: we had orm_only=False here before, removing
  1837. # it didn't break things. if we identify the rationale,
  1838. # may need to apply "_orm_only" annotation here.
  1839. right = current_adapter(right, True)
  1840. elif prop:
  1841. # joining to selectable with a mapper property given
  1842. # as the ON clause
  1843. if not right_selectable.is_derived_from(
  1844. right_mapper.persist_selectable
  1845. ):
  1846. raise sa_exc.InvalidRequestError(
  1847. "Selectable '%s' is not derived from '%s'"
  1848. % (
  1849. right_selectable.description,
  1850. right_mapper.persist_selectable.description,
  1851. )
  1852. )
  1853. # if the destination selectable is a plain select(),
  1854. # turn it into an alias().
  1855. if isinstance(right_selectable, expression.SelectBase):
  1856. right_selectable = coercions.expect(
  1857. roles.FromClauseRole, right_selectable
  1858. )
  1859. need_adapter = True
  1860. # make the right hand side target into an ORM entity
  1861. right = AliasedClass(right_mapper, right_selectable)
  1862. util.warn_deprecated(
  1863. "An alias is being generated automatically against "
  1864. "joined entity %s for raw clauseelement, which is "
  1865. "deprecated and will be removed in a later release. "
  1866. "Use the aliased() "
  1867. "construct explicitly, see the linked example."
  1868. % right_mapper,
  1869. "1.4",
  1870. code="xaj1",
  1871. )
  1872. # test for overlap:
  1873. # orm/inheritance/relationships.py
  1874. # SelfReferentialM2MTest
  1875. aliased_entity = right_mapper and not right_is_aliased and overlap
  1876. if not need_adapter and aliased_entity:
  1877. # there are a few places in the ORM that automatic aliasing
  1878. # is still desirable, and can't be automatic with a Core
  1879. # only approach. For illustrations of "overlaps" see
  1880. # test/orm/inheritance/test_relationships.py. There are also
  1881. # general overlap cases with many-to-many tables where automatic
  1882. # aliasing is desirable.
  1883. right = AliasedClass(right, flat=True)
  1884. need_adapter = True
  1885. util.warn(
  1886. "An alias is being generated automatically against "
  1887. "joined entity %s due to overlapping tables. This is a "
  1888. "legacy pattern which may be "
  1889. "deprecated in a later release. Use the "
  1890. "aliased(<entity>, flat=True) "
  1891. "construct explicitly, see the linked example." % right_mapper,
  1892. code="xaj2",
  1893. )
  1894. if need_adapter:
  1895. # if need_adapter is True, we are in a deprecated case and
  1896. # a warning has been emitted.
  1897. assert right_mapper
  1898. adapter = ORMAdapter(
  1899. _TraceAdaptRole.DEPRECATED_JOIN_ADAPT_RIGHT_SIDE,
  1900. inspect(right),
  1901. equivalents=right_mapper._equivalent_columns,
  1902. )
  1903. # if an alias() on the right side was generated,
  1904. # which is intended to wrap a the right side in a subquery,
  1905. # ensure that columns retrieved from this target in the result
  1906. # set are also adapted.
  1907. self._mapper_loads_polymorphically_with(right_mapper, adapter)
  1908. elif (
  1909. not r_info.is_clause_element
  1910. and not right_is_aliased
  1911. and right_mapper._has_aliased_polymorphic_fromclause
  1912. ):
  1913. # for the case where the target mapper has a with_polymorphic
  1914. # set up, ensure an adapter is set up for criteria that works
  1915. # against this mapper. Previously, this logic used to
  1916. # use the "create_aliases or aliased_entity" case to generate
  1917. # an aliased() object, but this creates an alias that isn't
  1918. # strictly necessary.
  1919. # see test/orm/test_core_compilation.py
  1920. # ::RelNaturalAliasedJoinsTest::test_straight
  1921. # and similar
  1922. self._mapper_loads_polymorphically_with(
  1923. right_mapper,
  1924. ORMAdapter(
  1925. _TraceAdaptRole.WITH_POLYMORPHIC_ADAPTER_RIGHT_JOIN,
  1926. right_mapper,
  1927. selectable=right_mapper.selectable,
  1928. equivalents=right_mapper._equivalent_columns,
  1929. ),
  1930. )
  1931. # if the onclause is a ClauseElement, adapt it with any
  1932. # adapters that are in place right now
  1933. if isinstance(onclause, expression.ClauseElement):
  1934. current_adapter = self._get_current_adapter()
  1935. if current_adapter:
  1936. onclause = current_adapter(onclause, True)
  1937. # if joining on a MapperProperty path,
  1938. # track the path to prevent redundant joins
  1939. if prop:
  1940. self._already_joined_edges += ((left, right, prop.key),)
  1941. return inspect(right), right, onclause
  1942. @property
  1943. def _select_args(self):
  1944. return {
  1945. "limit_clause": self.select_statement._limit_clause,
  1946. "offset_clause": self.select_statement._offset_clause,
  1947. "distinct": self.distinct,
  1948. "distinct_on": self.distinct_on,
  1949. "prefixes": self.select_statement._prefixes,
  1950. "suffixes": self.select_statement._suffixes,
  1951. "group_by": self.group_by or None,
  1952. "fetch_clause": self.select_statement._fetch_clause,
  1953. "fetch_clause_options": (
  1954. self.select_statement._fetch_clause_options
  1955. ),
  1956. "independent_ctes": self.select_statement._independent_ctes,
  1957. "independent_ctes_opts": (
  1958. self.select_statement._independent_ctes_opts
  1959. ),
  1960. }
  1961. @property
  1962. def _should_nest_selectable(self):
  1963. kwargs = self._select_args
  1964. return (
  1965. kwargs.get("limit_clause") is not None
  1966. or kwargs.get("offset_clause") is not None
  1967. or kwargs.get("distinct", False)
  1968. or kwargs.get("distinct_on", ())
  1969. or kwargs.get("group_by", False)
  1970. )
  1971. def _get_extra_criteria(self, ext_info):
  1972. if (
  1973. "additional_entity_criteria",
  1974. ext_info.mapper,
  1975. ) in self.global_attributes:
  1976. return tuple(
  1977. ae._resolve_where_criteria(ext_info)
  1978. for ae in self.global_attributes[
  1979. ("additional_entity_criteria", ext_info.mapper)
  1980. ]
  1981. if (ae.include_aliases or ae.entity is ext_info)
  1982. and ae._should_include(self)
  1983. )
  1984. else:
  1985. return ()
  1986. def _adjust_for_extra_criteria(self):
  1987. """Apply extra criteria filtering.
  1988. For all distinct single-table-inheritance mappers represented in
  1989. the columns clause of this query, as well as the "select from entity",
  1990. add criterion to the WHERE
  1991. clause of the given QueryContext such that only the appropriate
  1992. subtypes are selected from the total results.
  1993. Additionally, add WHERE criteria originating from LoaderCriteriaOptions
  1994. associated with the global context.
  1995. """
  1996. for fromclause in self.from_clauses:
  1997. ext_info = fromclause._annotations.get("parententity", None)
  1998. if (
  1999. ext_info
  2000. and (
  2001. ext_info.mapper._single_table_criterion is not None
  2002. or ("additional_entity_criteria", ext_info.mapper)
  2003. in self.global_attributes
  2004. )
  2005. and ext_info not in self.extra_criteria_entities
  2006. ):
  2007. self.extra_criteria_entities[ext_info] = (
  2008. ext_info,
  2009. ext_info._adapter if ext_info.is_aliased_class else None,
  2010. )
  2011. search = set(self.extra_criteria_entities.values())
  2012. for ext_info, adapter in search:
  2013. if ext_info in self._join_entities:
  2014. continue
  2015. single_crit = ext_info.mapper._single_table_criterion
  2016. if self.compile_options._for_refresh_state:
  2017. additional_entity_criteria = []
  2018. else:
  2019. additional_entity_criteria = self._get_extra_criteria(ext_info)
  2020. if single_crit is not None:
  2021. additional_entity_criteria += (single_crit,)
  2022. current_adapter = self._get_current_adapter()
  2023. for crit in additional_entity_criteria:
  2024. if adapter:
  2025. crit = adapter.traverse(crit)
  2026. if current_adapter:
  2027. crit = sql_util._deep_annotate(crit, {"_orm_adapt": True})
  2028. crit = current_adapter(crit, False)
  2029. self._where_criteria += (crit,)
  2030. def _column_descriptions(
  2031. query_or_select_stmt: Union[Query, Select, FromStatement],
  2032. compile_state: Optional[ORMSelectCompileState] = None,
  2033. legacy: bool = False,
  2034. ) -> List[ORMColumnDescription]:
  2035. if compile_state is None:
  2036. compile_state = ORMSelectCompileState._create_entities_collection(
  2037. query_or_select_stmt, legacy=legacy
  2038. )
  2039. ctx = compile_state
  2040. d = [
  2041. {
  2042. "name": ent._label_name,
  2043. "type": ent.type,
  2044. "aliased": getattr(insp_ent, "is_aliased_class", False),
  2045. "expr": ent.expr,
  2046. "entity": getattr(insp_ent, "entity", None)
  2047. if ent.entity_zero is not None and not insp_ent.is_clause_element
  2048. else None,
  2049. }
  2050. for ent, insp_ent in [
  2051. (_ent, _ent.entity_zero) for _ent in ctx._entities
  2052. ]
  2053. ]
  2054. return d
  2055. def _legacy_filter_by_entity_zero(
  2056. query_or_augmented_select: Union[Query[Any], Select[Any]]
  2057. ) -> Optional[_InternalEntityType[Any]]:
  2058. self = query_or_augmented_select
  2059. if self._setup_joins:
  2060. _last_joined_entity = self._last_joined_entity
  2061. if _last_joined_entity is not None:
  2062. return _last_joined_entity
  2063. if self._from_obj and "parententity" in self._from_obj[0]._annotations:
  2064. return self._from_obj[0]._annotations["parententity"]
  2065. return _entity_from_pre_ent_zero(self)
  2066. def _entity_from_pre_ent_zero(
  2067. query_or_augmented_select: Union[Query[Any], Select[Any]]
  2068. ) -> Optional[_InternalEntityType[Any]]:
  2069. self = query_or_augmented_select
  2070. if not self._raw_columns:
  2071. return None
  2072. ent = self._raw_columns[0]
  2073. if "parententity" in ent._annotations:
  2074. return ent._annotations["parententity"]
  2075. elif isinstance(ent, ORMColumnsClauseRole):
  2076. return ent.entity
  2077. elif "bundle" in ent._annotations:
  2078. return ent._annotations["bundle"]
  2079. else:
  2080. return ent
  2081. def _determine_last_joined_entity(
  2082. setup_joins: Tuple[_SetupJoinsElement, ...],
  2083. entity_zero: Optional[_InternalEntityType[Any]] = None,
  2084. ) -> Optional[Union[_InternalEntityType[Any], _JoinTargetElement]]:
  2085. if not setup_joins:
  2086. return None
  2087. (target, onclause, from_, flags) = setup_joins[-1]
  2088. if isinstance(
  2089. target,
  2090. attributes.QueryableAttribute,
  2091. ):
  2092. return target.entity
  2093. else:
  2094. return target
  2095. class _QueryEntity:
  2096. """represent an entity column returned within a Query result."""
  2097. __slots__ = ()
  2098. supports_single_entity: bool
  2099. _non_hashable_value = False
  2100. _null_column_type = False
  2101. use_id_for_hash = False
  2102. _label_name: Optional[str]
  2103. type: Union[Type[Any], TypeEngine[Any]]
  2104. expr: Union[_InternalEntityType, ColumnElement[Any]]
  2105. entity_zero: Optional[_InternalEntityType]
  2106. def setup_compile_state(self, compile_state: ORMCompileState) -> None:
  2107. raise NotImplementedError()
  2108. def setup_dml_returning_compile_state(
  2109. self,
  2110. compile_state: ORMCompileState,
  2111. adapter: DMLReturningColFilter,
  2112. ) -> None:
  2113. raise NotImplementedError()
  2114. def row_processor(self, context, result):
  2115. raise NotImplementedError()
  2116. @classmethod
  2117. def to_compile_state(
  2118. cls, compile_state, entities, entities_collection, is_current_entities
  2119. ):
  2120. for idx, entity in enumerate(entities):
  2121. if entity._is_lambda_element:
  2122. if entity._is_sequence:
  2123. cls.to_compile_state(
  2124. compile_state,
  2125. entity._resolved,
  2126. entities_collection,
  2127. is_current_entities,
  2128. )
  2129. continue
  2130. else:
  2131. entity = entity._resolved
  2132. if entity.is_clause_element:
  2133. if entity.is_selectable:
  2134. if "parententity" in entity._annotations:
  2135. _MapperEntity(
  2136. compile_state,
  2137. entity,
  2138. entities_collection,
  2139. is_current_entities,
  2140. )
  2141. else:
  2142. _ColumnEntity._for_columns(
  2143. compile_state,
  2144. entity._select_iterable,
  2145. entities_collection,
  2146. idx,
  2147. is_current_entities,
  2148. )
  2149. else:
  2150. if entity._annotations.get("bundle", False):
  2151. _BundleEntity(
  2152. compile_state,
  2153. entity,
  2154. entities_collection,
  2155. is_current_entities,
  2156. )
  2157. elif entity._is_clause_list:
  2158. # this is legacy only - test_composites.py
  2159. # test_query_cols_legacy
  2160. _ColumnEntity._for_columns(
  2161. compile_state,
  2162. entity._select_iterable,
  2163. entities_collection,
  2164. idx,
  2165. is_current_entities,
  2166. )
  2167. else:
  2168. _ColumnEntity._for_columns(
  2169. compile_state,
  2170. [entity],
  2171. entities_collection,
  2172. idx,
  2173. is_current_entities,
  2174. )
  2175. elif entity.is_bundle:
  2176. _BundleEntity(compile_state, entity, entities_collection)
  2177. return entities_collection
  2178. class _MapperEntity(_QueryEntity):
  2179. """mapper/class/AliasedClass entity"""
  2180. __slots__ = (
  2181. "expr",
  2182. "mapper",
  2183. "entity_zero",
  2184. "is_aliased_class",
  2185. "path",
  2186. "_extra_entities",
  2187. "_label_name",
  2188. "_with_polymorphic_mappers",
  2189. "selectable",
  2190. "_polymorphic_discriminator",
  2191. )
  2192. expr: _InternalEntityType
  2193. mapper: Mapper[Any]
  2194. entity_zero: _InternalEntityType
  2195. is_aliased_class: bool
  2196. path: PathRegistry
  2197. _label_name: str
  2198. def __init__(
  2199. self, compile_state, entity, entities_collection, is_current_entities
  2200. ):
  2201. entities_collection.append(self)
  2202. if is_current_entities:
  2203. if compile_state._primary_entity is None:
  2204. compile_state._primary_entity = self
  2205. compile_state._has_mapper_entities = True
  2206. compile_state._has_orm_entities = True
  2207. entity = entity._annotations["parententity"]
  2208. entity._post_inspect
  2209. ext_info = self.entity_zero = entity
  2210. entity = ext_info.entity
  2211. self.expr = entity
  2212. self.mapper = mapper = ext_info.mapper
  2213. self._extra_entities = (self.expr,)
  2214. if ext_info.is_aliased_class:
  2215. self._label_name = ext_info.name
  2216. else:
  2217. self._label_name = mapper.class_.__name__
  2218. self.is_aliased_class = ext_info.is_aliased_class
  2219. self.path = ext_info._path_registry
  2220. self.selectable = ext_info.selectable
  2221. self._with_polymorphic_mappers = ext_info.with_polymorphic_mappers
  2222. self._polymorphic_discriminator = ext_info.polymorphic_on
  2223. if mapper._should_select_with_poly_adapter:
  2224. compile_state._create_with_polymorphic_adapter(
  2225. ext_info, self.selectable
  2226. )
  2227. supports_single_entity = True
  2228. _non_hashable_value = True
  2229. use_id_for_hash = True
  2230. @property
  2231. def type(self):
  2232. return self.mapper.class_
  2233. @property
  2234. def entity_zero_or_selectable(self):
  2235. return self.entity_zero
  2236. def corresponds_to(self, entity):
  2237. return _entity_corresponds_to(self.entity_zero, entity)
  2238. def _get_entity_clauses(self, compile_state):
  2239. adapter = None
  2240. if not self.is_aliased_class:
  2241. if compile_state._polymorphic_adapters:
  2242. adapter = compile_state._polymorphic_adapters.get(
  2243. self.mapper, None
  2244. )
  2245. else:
  2246. adapter = self.entity_zero._adapter
  2247. if adapter:
  2248. if compile_state._from_obj_alias:
  2249. ret = adapter.wrap(compile_state._from_obj_alias)
  2250. else:
  2251. ret = adapter
  2252. else:
  2253. ret = compile_state._from_obj_alias
  2254. return ret
  2255. def row_processor(self, context, result):
  2256. compile_state = context.compile_state
  2257. adapter = self._get_entity_clauses(compile_state)
  2258. if compile_state.compound_eager_adapter and adapter:
  2259. adapter = adapter.wrap(compile_state.compound_eager_adapter)
  2260. elif not adapter:
  2261. adapter = compile_state.compound_eager_adapter
  2262. if compile_state._primary_entity is self:
  2263. only_load_props = compile_state.compile_options._only_load_props
  2264. refresh_state = context.refresh_state
  2265. else:
  2266. only_load_props = refresh_state = None
  2267. _instance = loading._instance_processor(
  2268. self,
  2269. self.mapper,
  2270. context,
  2271. result,
  2272. self.path,
  2273. adapter,
  2274. only_load_props=only_load_props,
  2275. refresh_state=refresh_state,
  2276. polymorphic_discriminator=self._polymorphic_discriminator,
  2277. )
  2278. return _instance, self._label_name, self._extra_entities
  2279. def setup_dml_returning_compile_state(
  2280. self,
  2281. compile_state: ORMCompileState,
  2282. adapter: DMLReturningColFilter,
  2283. ) -> None:
  2284. loading._setup_entity_query(
  2285. compile_state,
  2286. self.mapper,
  2287. self,
  2288. self.path,
  2289. adapter,
  2290. compile_state.primary_columns,
  2291. with_polymorphic=self._with_polymorphic_mappers,
  2292. only_load_props=compile_state.compile_options._only_load_props,
  2293. polymorphic_discriminator=self._polymorphic_discriminator,
  2294. )
  2295. def setup_compile_state(self, compile_state):
  2296. adapter = self._get_entity_clauses(compile_state)
  2297. single_table_crit = self.mapper._single_table_criterion
  2298. if (
  2299. single_table_crit is not None
  2300. or ("additional_entity_criteria", self.mapper)
  2301. in compile_state.global_attributes
  2302. ):
  2303. ext_info = self.entity_zero
  2304. compile_state.extra_criteria_entities[ext_info] = (
  2305. ext_info,
  2306. ext_info._adapter if ext_info.is_aliased_class else None,
  2307. )
  2308. loading._setup_entity_query(
  2309. compile_state,
  2310. self.mapper,
  2311. self,
  2312. self.path,
  2313. adapter,
  2314. compile_state.primary_columns,
  2315. with_polymorphic=self._with_polymorphic_mappers,
  2316. only_load_props=compile_state.compile_options._only_load_props,
  2317. polymorphic_discriminator=self._polymorphic_discriminator,
  2318. )
  2319. compile_state._fallback_from_clauses.append(self.selectable)
  2320. class _BundleEntity(_QueryEntity):
  2321. _extra_entities = ()
  2322. __slots__ = (
  2323. "bundle",
  2324. "expr",
  2325. "type",
  2326. "_label_name",
  2327. "_entities",
  2328. "supports_single_entity",
  2329. )
  2330. _entities: List[_QueryEntity]
  2331. bundle: Bundle
  2332. type: Type[Any]
  2333. _label_name: str
  2334. supports_single_entity: bool
  2335. expr: Bundle
  2336. def __init__(
  2337. self,
  2338. compile_state,
  2339. expr,
  2340. entities_collection,
  2341. is_current_entities,
  2342. setup_entities=True,
  2343. parent_bundle=None,
  2344. ):
  2345. compile_state._has_orm_entities = True
  2346. expr = expr._annotations["bundle"]
  2347. if parent_bundle:
  2348. parent_bundle._entities.append(self)
  2349. else:
  2350. entities_collection.append(self)
  2351. if isinstance(
  2352. expr, (attributes.QueryableAttribute, interfaces.PropComparator)
  2353. ):
  2354. bundle = expr.__clause_element__()
  2355. else:
  2356. bundle = expr
  2357. self.bundle = self.expr = bundle
  2358. self.type = type(bundle)
  2359. self._label_name = bundle.name
  2360. self._entities = []
  2361. if setup_entities:
  2362. for expr in bundle.exprs:
  2363. if "bundle" in expr._annotations:
  2364. _BundleEntity(
  2365. compile_state,
  2366. expr,
  2367. entities_collection,
  2368. is_current_entities,
  2369. parent_bundle=self,
  2370. )
  2371. elif isinstance(expr, Bundle):
  2372. _BundleEntity(
  2373. compile_state,
  2374. expr,
  2375. entities_collection,
  2376. is_current_entities,
  2377. parent_bundle=self,
  2378. )
  2379. else:
  2380. _ORMColumnEntity._for_columns(
  2381. compile_state,
  2382. [expr],
  2383. entities_collection,
  2384. None,
  2385. is_current_entities,
  2386. parent_bundle=self,
  2387. )
  2388. self.supports_single_entity = self.bundle.single_entity
  2389. @property
  2390. def mapper(self):
  2391. ezero = self.entity_zero
  2392. if ezero is not None:
  2393. return ezero.mapper
  2394. else:
  2395. return None
  2396. @property
  2397. def entity_zero(self):
  2398. for ent in self._entities:
  2399. ezero = ent.entity_zero
  2400. if ezero is not None:
  2401. return ezero
  2402. else:
  2403. return None
  2404. def corresponds_to(self, entity):
  2405. # TODO: we might be able to implement this but for now
  2406. # we are working around it
  2407. return False
  2408. @property
  2409. def entity_zero_or_selectable(self):
  2410. for ent in self._entities:
  2411. ezero = ent.entity_zero_or_selectable
  2412. if ezero is not None:
  2413. return ezero
  2414. else:
  2415. return None
  2416. def setup_compile_state(self, compile_state):
  2417. for ent in self._entities:
  2418. ent.setup_compile_state(compile_state)
  2419. def setup_dml_returning_compile_state(
  2420. self,
  2421. compile_state: ORMCompileState,
  2422. adapter: DMLReturningColFilter,
  2423. ) -> None:
  2424. return self.setup_compile_state(compile_state)
  2425. def row_processor(self, context, result):
  2426. procs, labels, extra = zip(
  2427. *[ent.row_processor(context, result) for ent in self._entities]
  2428. )
  2429. proc = self.bundle.create_row_processor(context.query, procs, labels)
  2430. return proc, self._label_name, self._extra_entities
  2431. class _ColumnEntity(_QueryEntity):
  2432. __slots__ = (
  2433. "_fetch_column",
  2434. "_row_processor",
  2435. "raw_column_index",
  2436. "translate_raw_column",
  2437. )
  2438. @classmethod
  2439. def _for_columns(
  2440. cls,
  2441. compile_state,
  2442. columns,
  2443. entities_collection,
  2444. raw_column_index,
  2445. is_current_entities,
  2446. parent_bundle=None,
  2447. ):
  2448. for column in columns:
  2449. annotations = column._annotations
  2450. if "parententity" in annotations:
  2451. _entity = annotations["parententity"]
  2452. else:
  2453. _entity = sql_util.extract_first_column_annotation(
  2454. column, "parententity"
  2455. )
  2456. if _entity:
  2457. if "identity_token" in column._annotations:
  2458. _IdentityTokenEntity(
  2459. compile_state,
  2460. column,
  2461. entities_collection,
  2462. _entity,
  2463. raw_column_index,
  2464. is_current_entities,
  2465. parent_bundle=parent_bundle,
  2466. )
  2467. else:
  2468. _ORMColumnEntity(
  2469. compile_state,
  2470. column,
  2471. entities_collection,
  2472. _entity,
  2473. raw_column_index,
  2474. is_current_entities,
  2475. parent_bundle=parent_bundle,
  2476. )
  2477. else:
  2478. _RawColumnEntity(
  2479. compile_state,
  2480. column,
  2481. entities_collection,
  2482. raw_column_index,
  2483. is_current_entities,
  2484. parent_bundle=parent_bundle,
  2485. )
  2486. @property
  2487. def type(self):
  2488. return self.column.type
  2489. @property
  2490. def _non_hashable_value(self):
  2491. return not self.column.type.hashable
  2492. @property
  2493. def _null_column_type(self):
  2494. return self.column.type._isnull
  2495. def row_processor(self, context, result):
  2496. compile_state = context.compile_state
  2497. # the resulting callable is entirely cacheable so just return
  2498. # it if we already made one
  2499. if self._row_processor is not None:
  2500. getter, label_name, extra_entities = self._row_processor
  2501. if self.translate_raw_column:
  2502. extra_entities += (
  2503. context.query._raw_columns[self.raw_column_index],
  2504. )
  2505. return getter, label_name, extra_entities
  2506. # retrieve the column that would have been set up in
  2507. # setup_compile_state, to avoid doing redundant work
  2508. if self._fetch_column is not None:
  2509. column = self._fetch_column
  2510. else:
  2511. # fetch_column will be None when we are doing a from_statement
  2512. # and setup_compile_state may not have been called.
  2513. column = self.column
  2514. # previously, the RawColumnEntity didn't look for from_obj_alias
  2515. # however I can't think of a case where we would be here and
  2516. # we'd want to ignore it if this is the from_statement use case.
  2517. # it's not really a use case to have raw columns + from_statement
  2518. if compile_state._from_obj_alias:
  2519. column = compile_state._from_obj_alias.columns[column]
  2520. if column._annotations:
  2521. # annotated columns perform more slowly in compiler and
  2522. # result due to the __eq__() method, so use deannotated
  2523. column = column._deannotate()
  2524. if compile_state.compound_eager_adapter:
  2525. column = compile_state.compound_eager_adapter.columns[column]
  2526. getter = result._getter(column)
  2527. ret = getter, self._label_name, self._extra_entities
  2528. self._row_processor = ret
  2529. if self.translate_raw_column:
  2530. extra_entities = self._extra_entities + (
  2531. context.query._raw_columns[self.raw_column_index],
  2532. )
  2533. return getter, self._label_name, extra_entities
  2534. else:
  2535. return ret
  2536. class _RawColumnEntity(_ColumnEntity):
  2537. entity_zero = None
  2538. mapper = None
  2539. supports_single_entity = False
  2540. __slots__ = (
  2541. "expr",
  2542. "column",
  2543. "_label_name",
  2544. "entity_zero_or_selectable",
  2545. "_extra_entities",
  2546. )
  2547. def __init__(
  2548. self,
  2549. compile_state,
  2550. column,
  2551. entities_collection,
  2552. raw_column_index,
  2553. is_current_entities,
  2554. parent_bundle=None,
  2555. ):
  2556. self.expr = column
  2557. self.raw_column_index = raw_column_index
  2558. self.translate_raw_column = raw_column_index is not None
  2559. if column._is_star:
  2560. compile_state.compile_options += {"_is_star": True}
  2561. if not is_current_entities or column._is_text_clause:
  2562. self._label_name = None
  2563. else:
  2564. self._label_name = compile_state._label_convention(column)
  2565. if parent_bundle:
  2566. parent_bundle._entities.append(self)
  2567. else:
  2568. entities_collection.append(self)
  2569. self.column = column
  2570. self.entity_zero_or_selectable = (
  2571. self.column._from_objects[0] if self.column._from_objects else None
  2572. )
  2573. self._extra_entities = (self.expr, self.column)
  2574. self._fetch_column = self._row_processor = None
  2575. def corresponds_to(self, entity):
  2576. return False
  2577. def setup_dml_returning_compile_state(
  2578. self,
  2579. compile_state: ORMCompileState,
  2580. adapter: DMLReturningColFilter,
  2581. ) -> None:
  2582. return self.setup_compile_state(compile_state)
  2583. def setup_compile_state(self, compile_state):
  2584. current_adapter = compile_state._get_current_adapter()
  2585. if current_adapter:
  2586. column = current_adapter(self.column, False)
  2587. if column is None:
  2588. return
  2589. else:
  2590. column = self.column
  2591. if column._annotations:
  2592. # annotated columns perform more slowly in compiler and
  2593. # result due to the __eq__() method, so use deannotated
  2594. column = column._deannotate()
  2595. compile_state.dedupe_columns.add(column)
  2596. compile_state.primary_columns.append(column)
  2597. self._fetch_column = column
  2598. class _ORMColumnEntity(_ColumnEntity):
  2599. """Column/expression based entity."""
  2600. supports_single_entity = False
  2601. __slots__ = (
  2602. "expr",
  2603. "mapper",
  2604. "column",
  2605. "_label_name",
  2606. "entity_zero_or_selectable",
  2607. "entity_zero",
  2608. "_extra_entities",
  2609. )
  2610. def __init__(
  2611. self,
  2612. compile_state,
  2613. column,
  2614. entities_collection,
  2615. parententity,
  2616. raw_column_index,
  2617. is_current_entities,
  2618. parent_bundle=None,
  2619. ):
  2620. annotations = column._annotations
  2621. _entity = parententity
  2622. # an AliasedClass won't have proxy_key in the annotations for
  2623. # a column if it was acquired using the class' adapter directly,
  2624. # such as using AliasedInsp._adapt_element(). this occurs
  2625. # within internal loaders.
  2626. orm_key = annotations.get("proxy_key", None)
  2627. proxy_owner = annotations.get("proxy_owner", _entity)
  2628. if orm_key:
  2629. self.expr = getattr(proxy_owner.entity, orm_key)
  2630. self.translate_raw_column = False
  2631. else:
  2632. # if orm_key is not present, that means this is an ad-hoc
  2633. # SQL ColumnElement, like a CASE() or other expression.
  2634. # include this column position from the invoked statement
  2635. # in the ORM-level ResultSetMetaData on each execute, so that
  2636. # it can be targeted by identity after caching
  2637. self.expr = column
  2638. self.translate_raw_column = raw_column_index is not None
  2639. self.raw_column_index = raw_column_index
  2640. if is_current_entities:
  2641. self._label_name = compile_state._label_convention(
  2642. column, col_name=orm_key
  2643. )
  2644. else:
  2645. self._label_name = None
  2646. _entity._post_inspect
  2647. self.entity_zero = self.entity_zero_or_selectable = ezero = _entity
  2648. self.mapper = mapper = _entity.mapper
  2649. if parent_bundle:
  2650. parent_bundle._entities.append(self)
  2651. else:
  2652. entities_collection.append(self)
  2653. compile_state._has_orm_entities = True
  2654. self.column = column
  2655. self._fetch_column = self._row_processor = None
  2656. self._extra_entities = (self.expr, self.column)
  2657. if mapper._should_select_with_poly_adapter:
  2658. compile_state._create_with_polymorphic_adapter(
  2659. ezero, ezero.selectable
  2660. )
  2661. def corresponds_to(self, entity):
  2662. if _is_aliased_class(entity):
  2663. # TODO: polymorphic subclasses ?
  2664. return entity is self.entity_zero
  2665. else:
  2666. return not _is_aliased_class(
  2667. self.entity_zero
  2668. ) and entity.common_parent(self.entity_zero)
  2669. def setup_dml_returning_compile_state(
  2670. self,
  2671. compile_state: ORMCompileState,
  2672. adapter: DMLReturningColFilter,
  2673. ) -> None:
  2674. self._fetch_column = self.column
  2675. column = adapter(self.column, False)
  2676. if column is not None:
  2677. compile_state.dedupe_columns.add(column)
  2678. compile_state.primary_columns.append(column)
  2679. def setup_compile_state(self, compile_state):
  2680. current_adapter = compile_state._get_current_adapter()
  2681. if current_adapter:
  2682. column = current_adapter(self.column, False)
  2683. if column is None:
  2684. assert compile_state.is_dml_returning
  2685. self._fetch_column = self.column
  2686. return
  2687. else:
  2688. column = self.column
  2689. ezero = self.entity_zero
  2690. single_table_crit = self.mapper._single_table_criterion
  2691. if (
  2692. single_table_crit is not None
  2693. or ("additional_entity_criteria", self.mapper)
  2694. in compile_state.global_attributes
  2695. ):
  2696. compile_state.extra_criteria_entities[ezero] = (
  2697. ezero,
  2698. ezero._adapter if ezero.is_aliased_class else None,
  2699. )
  2700. if column._annotations and not column._expression_label:
  2701. # annotated columns perform more slowly in compiler and
  2702. # result due to the __eq__() method, so use deannotated
  2703. column = column._deannotate()
  2704. # use entity_zero as the from if we have it. this is necessary
  2705. # for polymorphic scenarios where our FROM is based on ORM entity,
  2706. # not the FROM of the column. but also, don't use it if our column
  2707. # doesn't actually have any FROMs that line up, such as when its
  2708. # a scalar subquery.
  2709. if set(self.column._from_objects).intersection(
  2710. ezero.selectable._from_objects
  2711. ):
  2712. compile_state._fallback_from_clauses.append(ezero.selectable)
  2713. compile_state.dedupe_columns.add(column)
  2714. compile_state.primary_columns.append(column)
  2715. self._fetch_column = column
  2716. class _IdentityTokenEntity(_ORMColumnEntity):
  2717. translate_raw_column = False
  2718. def setup_compile_state(self, compile_state):
  2719. pass
  2720. def row_processor(self, context, result):
  2721. def getter(row):
  2722. return context.load_options._identity_token
  2723. return getter, self._label_name, self._extra_entities