context.py 109 KB

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