context.py 108 KB

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