selectable.py 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713
  1. # sql/selectable.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """The :class:`.FromClause` class of SQL expression elements, representing
  8. SQL tables and derived rowsets.
  9. """
  10. from .elements import ClauseElement, TextClause, ClauseList, \
  11. and_, Grouping, UnaryExpression, literal_column, BindParameter
  12. from .elements import _clone, \
  13. _literal_as_text, _interpret_as_column_or_from, _expand_cloned,\
  14. _select_iterables, _anonymous_label, _clause_element_as_expr,\
  15. _cloned_intersection, _cloned_difference, True_, \
  16. _literal_as_label_reference, _literal_and_labels_as_label_reference
  17. from .base import Immutable, Executable, _generative, \
  18. ColumnCollection, ColumnSet, _from_objects, Generative
  19. from . import type_api
  20. from .. import inspection
  21. from .. import util
  22. from .. import exc
  23. from operator import attrgetter
  24. from . import operators
  25. import operator
  26. import collections
  27. from .annotation import Annotated
  28. import itertools
  29. from sqlalchemy.sql.visitors import Visitable
  30. def _interpret_as_from(element):
  31. insp = inspection.inspect(element, raiseerr=False)
  32. if insp is None:
  33. if isinstance(element, util.string_types):
  34. util.warn_limited(
  35. "Textual SQL FROM expression %(expr)r should be "
  36. "explicitly declared as text(%(expr)r), "
  37. "or use table(%(expr)r) for more specificity",
  38. {"expr": util.ellipses_string(element)})
  39. return TextClause(util.text_type(element))
  40. try:
  41. return insp.selectable
  42. except AttributeError:
  43. raise exc.ArgumentError("FROM expression expected")
  44. def _interpret_as_select(element):
  45. element = _interpret_as_from(element)
  46. if isinstance(element, Alias):
  47. element = element.original
  48. if not isinstance(element, SelectBase):
  49. element = element.select()
  50. return element
  51. class _OffsetLimitParam(BindParameter):
  52. @property
  53. def _limit_offset_value(self):
  54. return self.effective_value
  55. def _offset_or_limit_clause(element, name=None, type_=None):
  56. """Convert the given value to an "offset or limit" clause.
  57. This handles incoming integers and converts to an expression; if
  58. an expression is already given, it is passed through.
  59. """
  60. if element is None:
  61. return None
  62. elif hasattr(element, '__clause_element__'):
  63. return element.__clause_element__()
  64. elif isinstance(element, Visitable):
  65. return element
  66. else:
  67. value = util.asint(element)
  68. return _OffsetLimitParam(name, value, type_=type_, unique=True)
  69. def _offset_or_limit_clause_asint(clause, attrname):
  70. """Convert the "offset or limit" clause of a select construct to an
  71. integer.
  72. This is only possible if the value is stored as a simple bound parameter.
  73. Otherwise, a compilation error is raised.
  74. """
  75. if clause is None:
  76. return None
  77. try:
  78. value = clause._limit_offset_value
  79. except AttributeError:
  80. raise exc.CompileError(
  81. "This SELECT structure does not use a simple "
  82. "integer value for %s" % attrname)
  83. else:
  84. return util.asint(value)
  85. def subquery(alias, *args, **kwargs):
  86. r"""Return an :class:`.Alias` object derived
  87. from a :class:`.Select`.
  88. name
  89. alias name
  90. \*args, \**kwargs
  91. all other arguments are delivered to the
  92. :func:`select` function.
  93. """
  94. return Select(*args, **kwargs).alias(alias)
  95. def alias(selectable, name=None, flat=False):
  96. """Return an :class:`.Alias` object.
  97. An :class:`.Alias` represents any :class:`.FromClause`
  98. with an alternate name assigned within SQL, typically using the ``AS``
  99. clause when generated, e.g. ``SELECT * FROM table AS aliasname``.
  100. Similar functionality is available via the
  101. :meth:`~.FromClause.alias` method
  102. available on all :class:`.FromClause` subclasses.
  103. When an :class:`.Alias` is created from a :class:`.Table` object,
  104. this has the effect of the table being rendered
  105. as ``tablename AS aliasname`` in a SELECT statement.
  106. For :func:`.select` objects, the effect is that of creating a named
  107. subquery, i.e. ``(select ...) AS aliasname``.
  108. The ``name`` parameter is optional, and provides the name
  109. to use in the rendered SQL. If blank, an "anonymous" name
  110. will be deterministically generated at compile time.
  111. Deterministic means the name is guaranteed to be unique against
  112. other constructs used in the same statement, and will also be the
  113. same name for each successive compilation of the same statement
  114. object.
  115. :param selectable: any :class:`.FromClause` subclass,
  116. such as a table, select statement, etc.
  117. :param name: string name to be assigned as the alias.
  118. If ``None``, a name will be deterministically generated
  119. at compile time.
  120. :param flat: Will be passed through to if the given selectable
  121. is an instance of :class:`.Join` - see :meth:`.Join.alias`
  122. for details.
  123. .. versionadded:: 0.9.0
  124. """
  125. return _interpret_as_from(selectable).alias(name=name, flat=flat)
  126. def lateral(selectable, name=None):
  127. """Return a :class:`.Lateral` object.
  128. :class:`.Lateral` is an :class:`.Alias` subclass that represents
  129. a subquery with the LATERAL keyword applied to it.
  130. The special behavior of a LATERAL subquery is that it appears in the
  131. FROM clause of an enclosing SELECT, but may correlate to other
  132. FROM clauses of that SELECT. It is a special case of subquery
  133. only supported by a small number of backends, currently more recent
  134. PostgreSQL versions.
  135. .. versionadded:: 1.1
  136. .. seealso::
  137. :ref:`lateral_selects` - overview of usage.
  138. """
  139. return _interpret_as_from(selectable).lateral(name=name)
  140. def tablesample(selectable, sampling, name=None, seed=None):
  141. """Return a :class:`.TableSample` object.
  142. :class:`.TableSample` is an :class:`.Alias` subclass that represents
  143. a table with the TABLESAMPLE clause applied to it.
  144. :func:`~.expression.tablesample`
  145. is also available from the :class:`.FromClause` class via the
  146. :meth:`.FromClause.tablesample` method.
  147. The TABLESAMPLE clause allows selecting a randomly selected approximate
  148. percentage of rows from a table. It supports multiple sampling methods,
  149. most commonly BERNOULLI and SYSTEM.
  150. e.g.::
  151. from sqlalchemy import func
  152. selectable = people.tablesample(
  153. func.bernoulli(1),
  154. name='alias',
  155. seed=func.random())
  156. stmt = select([selectable.c.people_id])
  157. Assuming ``people`` with a column ``people_id``, the above
  158. statement would render as::
  159. SELECT alias.people_id FROM
  160. people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
  161. REPEATABLE (random())
  162. .. versionadded:: 1.1
  163. :param sampling: a ``float`` percentage between 0 and 100 or
  164. :class:`.functions.Function`.
  165. :param name: optional alias name
  166. :param seed: any real-valued SQL expression. When specified, the
  167. REPEATABLE sub-clause is also rendered.
  168. """
  169. return _interpret_as_from(selectable).tablesample(
  170. sampling, name=name, seed=seed)
  171. class Selectable(ClauseElement):
  172. """mark a class as being selectable"""
  173. __visit_name__ = 'selectable'
  174. is_selectable = True
  175. @property
  176. def selectable(self):
  177. return self
  178. class HasPrefixes(object):
  179. _prefixes = ()
  180. @_generative
  181. def prefix_with(self, *expr, **kw):
  182. r"""Add one or more expressions following the statement keyword, i.e.
  183. SELECT, INSERT, UPDATE, or DELETE. Generative.
  184. This is used to support backend-specific prefix keywords such as those
  185. provided by MySQL.
  186. E.g.::
  187. stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
  188. Multiple prefixes can be specified by multiple calls
  189. to :meth:`.prefix_with`.
  190. :param \*expr: textual or :class:`.ClauseElement` construct which
  191. will be rendered following the INSERT, UPDATE, or DELETE
  192. keyword.
  193. :param \**kw: A single keyword 'dialect' is accepted. This is an
  194. optional string dialect name which will
  195. limit rendering of this prefix to only that dialect.
  196. """
  197. dialect = kw.pop('dialect', None)
  198. if kw:
  199. raise exc.ArgumentError("Unsupported argument(s): %s" %
  200. ",".join(kw))
  201. self._setup_prefixes(expr, dialect)
  202. def _setup_prefixes(self, prefixes, dialect=None):
  203. self._prefixes = self._prefixes + tuple(
  204. [(_literal_as_text(p, warn=False), dialect) for p in prefixes])
  205. class HasSuffixes(object):
  206. _suffixes = ()
  207. @_generative
  208. def suffix_with(self, *expr, **kw):
  209. r"""Add one or more expressions following the statement as a whole.
  210. This is used to support backend-specific suffix keywords on
  211. certain constructs.
  212. E.g.::
  213. stmt = select([col1, col2]).cte().suffix_with(
  214. "cycle empno set y_cycle to 1 default 0", dialect="oracle")
  215. Multiple suffixes can be specified by multiple calls
  216. to :meth:`.suffix_with`.
  217. :param \*expr: textual or :class:`.ClauseElement` construct which
  218. will be rendered following the target clause.
  219. :param \**kw: A single keyword 'dialect' is accepted. This is an
  220. optional string dialect name which will
  221. limit rendering of this suffix to only that dialect.
  222. """
  223. dialect = kw.pop('dialect', None)
  224. if kw:
  225. raise exc.ArgumentError("Unsupported argument(s): %s" %
  226. ",".join(kw))
  227. self._setup_suffixes(expr, dialect)
  228. def _setup_suffixes(self, suffixes, dialect=None):
  229. self._suffixes = self._suffixes + tuple(
  230. [(_literal_as_text(p, warn=False), dialect) for p in suffixes])
  231. class FromClause(Selectable):
  232. """Represent an element that can be used within the ``FROM``
  233. clause of a ``SELECT`` statement.
  234. The most common forms of :class:`.FromClause` are the
  235. :class:`.Table` and the :func:`.select` constructs. Key
  236. features common to all :class:`.FromClause` objects include:
  237. * a :attr:`.c` collection, which provides per-name access to a collection
  238. of :class:`.ColumnElement` objects.
  239. * a :attr:`.primary_key` attribute, which is a collection of all those
  240. :class:`.ColumnElement` objects that indicate the ``primary_key`` flag.
  241. * Methods to generate various derivations of a "from" clause, including
  242. :meth:`.FromClause.alias`, :meth:`.FromClause.join`,
  243. :meth:`.FromClause.select`.
  244. """
  245. __visit_name__ = 'fromclause'
  246. named_with_column = False
  247. _hide_froms = []
  248. _is_join = False
  249. _is_select = False
  250. _is_from_container = False
  251. _textual = False
  252. """a marker that allows us to easily distinguish a :class:`.TextAsFrom`
  253. or similar object from other kinds of :class:`.FromClause` objects."""
  254. schema = None
  255. """Define the 'schema' attribute for this :class:`.FromClause`.
  256. This is typically ``None`` for most objects except that of
  257. :class:`.Table`, where it is taken as the value of the
  258. :paramref:`.Table.schema` argument.
  259. """
  260. def _translate_schema(self, effective_schema, map_):
  261. return effective_schema
  262. _memoized_property = util.group_expirable_memoized_property(["_columns"])
  263. @util.deprecated(
  264. '1.1',
  265. message="``FromClause.count()`` is deprecated. Counting "
  266. "rows requires that the correct column expression and "
  267. "accommodations for joins, DISTINCT, etc. must be made, "
  268. "otherwise results may not be what's expected. "
  269. "Please use an appropriate ``func.count()`` expression "
  270. "directly.")
  271. @util.dependencies("sqlalchemy.sql.functions")
  272. def count(self, functions, whereclause=None, **params):
  273. """return a SELECT COUNT generated against this
  274. :class:`.FromClause`.
  275. The function generates COUNT against the
  276. first column in the primary key of the table, or against
  277. the first column in the table overall. Explicit use of
  278. ``func.count()`` should be preferred::
  279. row_count = conn.scalar(
  280. select([func.count('*')]).select_from(table)
  281. )
  282. .. seealso::
  283. :data:`.func`
  284. """
  285. if self.primary_key:
  286. col = list(self.primary_key)[0]
  287. else:
  288. col = list(self.columns)[0]
  289. return Select(
  290. [functions.func.count(col).label('tbl_row_count')],
  291. whereclause,
  292. from_obj=[self],
  293. **params)
  294. def select(self, whereclause=None, **params):
  295. """return a SELECT of this :class:`.FromClause`.
  296. .. seealso::
  297. :func:`~.sql.expression.select` - general purpose
  298. method which allows for arbitrary column lists.
  299. """
  300. return Select([self], whereclause, **params)
  301. def join(self, right, onclause=None, isouter=False, full=False):
  302. """Return a :class:`.Join` from this :class:`.FromClause`
  303. to another :class:`FromClause`.
  304. E.g.::
  305. from sqlalchemy import join
  306. j = user_table.join(address_table,
  307. user_table.c.id == address_table.c.user_id)
  308. stmt = select([user_table]).select_from(j)
  309. would emit SQL along the lines of::
  310. SELECT user.id, user.name FROM user
  311. JOIN address ON user.id = address.user_id
  312. :param right: the right side of the join; this is any
  313. :class:`.FromClause` object such as a :class:`.Table` object, and
  314. may also be a selectable-compatible object such as an ORM-mapped
  315. class.
  316. :param onclause: a SQL expression representing the ON clause of the
  317. join. If left at ``None``, :meth:`.FromClause.join` will attempt to
  318. join the two tables based on a foreign key relationship.
  319. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.
  320. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER
  321. JOIN. Implies :paramref:`.FromClause.join.isouter`.
  322. .. versionadded:: 1.1
  323. .. seealso::
  324. :func:`.join` - standalone function
  325. :class:`.Join` - the type of object produced
  326. """
  327. return Join(self, right, onclause, isouter, full)
  328. def outerjoin(self, right, onclause=None, full=False):
  329. """Return a :class:`.Join` from this :class:`.FromClause`
  330. to another :class:`FromClause`, with the "isouter" flag set to
  331. True.
  332. E.g.::
  333. from sqlalchemy import outerjoin
  334. j = user_table.outerjoin(address_table,
  335. user_table.c.id == address_table.c.user_id)
  336. The above is equivalent to::
  337. j = user_table.join(
  338. address_table,
  339. user_table.c.id == address_table.c.user_id,
  340. isouter=True)
  341. :param right: the right side of the join; this is any
  342. :class:`.FromClause` object such as a :class:`.Table` object, and
  343. may also be a selectable-compatible object such as an ORM-mapped
  344. class.
  345. :param onclause: a SQL expression representing the ON clause of the
  346. join. If left at ``None``, :meth:`.FromClause.join` will attempt to
  347. join the two tables based on a foreign key relationship.
  348. :param full: if True, render a FULL OUTER JOIN, instead of
  349. LEFT OUTER JOIN.
  350. .. versionadded:: 1.1
  351. .. seealso::
  352. :meth:`.FromClause.join`
  353. :class:`.Join`
  354. """
  355. return Join(self, right, onclause, True, full)
  356. def alias(self, name=None, flat=False):
  357. """return an alias of this :class:`.FromClause`.
  358. This is shorthand for calling::
  359. from sqlalchemy import alias
  360. a = alias(self, name=name)
  361. See :func:`~.expression.alias` for details.
  362. """
  363. return Alias(self, name)
  364. def lateral(self, name=None):
  365. """Return a LATERAL alias of this :class:`.FromClause`.
  366. The return value is the :class:`.Lateral` construct also
  367. provided by the top-level :func:`~.expression.lateral` function.
  368. .. versionadded:: 1.1
  369. .. seealso::
  370. :ref:`lateral_selects` - overview of usage.
  371. """
  372. return Lateral(self, name)
  373. def tablesample(self, sampling, name=None, seed=None):
  374. """Return a TABLESAMPLE alias of this :class:`.FromClause`.
  375. The return value is the :class:`.TableSample` construct also
  376. provided by the top-level :func:`~.expression.tablesample` function.
  377. .. versionadded:: 1.1
  378. .. seealso::
  379. :func:`~.expression.tablesample` - usage guidelines and parameters
  380. """
  381. return TableSample(self, sampling, name, seed)
  382. def is_derived_from(self, fromclause):
  383. """Return True if this FromClause is 'derived' from the given
  384. FromClause.
  385. An example would be an Alias of a Table is derived from that Table.
  386. """
  387. # this is essentially an "identity" check in the base class.
  388. # Other constructs override this to traverse through
  389. # contained elements.
  390. return fromclause in self._cloned_set
  391. def _is_lexical_equivalent(self, other):
  392. """Return True if this FromClause and the other represent
  393. the same lexical identity.
  394. This tests if either one is a copy of the other, or
  395. if they are the same via annotation identity.
  396. """
  397. return self._cloned_set.intersection(other._cloned_set)
  398. @util.dependencies("sqlalchemy.sql.util")
  399. def replace_selectable(self, sqlutil, old, alias):
  400. """replace all occurrences of FromClause 'old' with the given Alias
  401. object, returning a copy of this :class:`.FromClause`.
  402. """
  403. return sqlutil.ClauseAdapter(alias).traverse(self)
  404. def correspond_on_equivalents(self, column, equivalents):
  405. """Return corresponding_column for the given column, or if None
  406. search for a match in the given dictionary.
  407. """
  408. col = self.corresponding_column(column, require_embedded=True)
  409. if col is None and col in equivalents:
  410. for equiv in equivalents[col]:
  411. nc = self.corresponding_column(equiv, require_embedded=True)
  412. if nc:
  413. return nc
  414. return col
  415. def corresponding_column(self, column, require_embedded=False):
  416. """Given a :class:`.ColumnElement`, return the exported
  417. :class:`.ColumnElement` object from this :class:`.Selectable`
  418. which corresponds to that original
  419. :class:`~sqlalchemy.schema.Column` via a common ancestor
  420. column.
  421. :param column: the target :class:`.ColumnElement` to be matched
  422. :param require_embedded: only return corresponding columns for
  423. the given :class:`.ColumnElement`, if the given
  424. :class:`.ColumnElement` is actually present within a sub-element
  425. of this :class:`.FromClause`. Normally the column will match if
  426. it merely shares a common ancestor with one of the exported
  427. columns of this :class:`.FromClause`.
  428. """
  429. def embedded(expanded_proxy_set, target_set):
  430. for t in target_set.difference(expanded_proxy_set):
  431. if not set(_expand_cloned([t])
  432. ).intersection(expanded_proxy_set):
  433. return False
  434. return True
  435. # don't dig around if the column is locally present
  436. if self.c.contains_column(column):
  437. return column
  438. col, intersect = None, None
  439. target_set = column.proxy_set
  440. cols = self.c._all_columns
  441. for c in cols:
  442. expanded_proxy_set = set(_expand_cloned(c.proxy_set))
  443. i = target_set.intersection(expanded_proxy_set)
  444. if i and (not require_embedded
  445. or embedded(expanded_proxy_set, target_set)):
  446. if col is None:
  447. # no corresponding column yet, pick this one.
  448. col, intersect = c, i
  449. elif len(i) > len(intersect):
  450. # 'c' has a larger field of correspondence than
  451. # 'col'. i.e. selectable.c.a1_x->a1.c.x->table.c.x
  452. # matches a1.c.x->table.c.x better than
  453. # selectable.c.x->table.c.x does.
  454. col, intersect = c, i
  455. elif i == intersect:
  456. # they have the same field of correspondence. see
  457. # which proxy_set has fewer columns in it, which
  458. # indicates a closer relationship with the root
  459. # column. Also take into account the "weight"
  460. # attribute which CompoundSelect() uses to give
  461. # higher precedence to columns based on vertical
  462. # position in the compound statement, and discard
  463. # columns that have no reference to the target
  464. # column (also occurs with CompoundSelect)
  465. col_distance = util.reduce(
  466. operator.add,
  467. [sc._annotations.get('weight', 1) for sc in
  468. col.proxy_set if sc.shares_lineage(column)])
  469. c_distance = util.reduce(
  470. operator.add,
  471. [sc._annotations.get('weight', 1) for sc in
  472. c.proxy_set if sc.shares_lineage(column)])
  473. if c_distance < col_distance:
  474. col, intersect = c, i
  475. return col
  476. @property
  477. def description(self):
  478. """a brief description of this FromClause.
  479. Used primarily for error message formatting.
  480. """
  481. return getattr(self, 'name', self.__class__.__name__ + " object")
  482. def _reset_exported(self):
  483. """delete memoized collections when a FromClause is cloned."""
  484. self._memoized_property.expire_instance(self)
  485. @_memoized_property
  486. def columns(self):
  487. """A named-based collection of :class:`.ColumnElement` objects
  488. maintained by this :class:`.FromClause`.
  489. The :attr:`.columns`, or :attr:`.c` collection, is the gateway
  490. to the construction of SQL expressions using table-bound or
  491. other selectable-bound columns::
  492. select([mytable]).where(mytable.c.somecolumn == 5)
  493. """
  494. if '_columns' not in self.__dict__:
  495. self._init_collections()
  496. self._populate_column_collection()
  497. return self._columns.as_immutable()
  498. @_memoized_property
  499. def primary_key(self):
  500. """Return the collection of Column objects which comprise the
  501. primary key of this FromClause."""
  502. self._init_collections()
  503. self._populate_column_collection()
  504. return self.primary_key
  505. @_memoized_property
  506. def foreign_keys(self):
  507. """Return the collection of ForeignKey objects which this
  508. FromClause references."""
  509. self._init_collections()
  510. self._populate_column_collection()
  511. return self.foreign_keys
  512. c = property(attrgetter('columns'),
  513. doc="An alias for the :attr:`.columns` attribute.")
  514. _select_iterable = property(attrgetter('columns'))
  515. def _init_collections(self):
  516. assert '_columns' not in self.__dict__
  517. assert 'primary_key' not in self.__dict__
  518. assert 'foreign_keys' not in self.__dict__
  519. self._columns = ColumnCollection()
  520. self.primary_key = ColumnSet()
  521. self.foreign_keys = set()
  522. @property
  523. def _cols_populated(self):
  524. return '_columns' in self.__dict__
  525. def _populate_column_collection(self):
  526. """Called on subclasses to establish the .c collection.
  527. Each implementation has a different way of establishing
  528. this collection.
  529. """
  530. def _refresh_for_new_column(self, column):
  531. """Given a column added to the .c collection of an underlying
  532. selectable, produce the local version of that column, assuming this
  533. selectable ultimately should proxy this column.
  534. this is used to "ping" a derived selectable to add a new column
  535. to its .c. collection when a Column has been added to one of the
  536. Table objects it ultimtely derives from.
  537. If the given selectable hasn't populated its .c. collection yet,
  538. it should at least pass on the message to the contained selectables,
  539. but it will return None.
  540. This method is currently used by Declarative to allow Table
  541. columns to be added to a partially constructed inheritance
  542. mapping that may have already produced joins. The method
  543. isn't public right now, as the full span of implications
  544. and/or caveats aren't yet clear.
  545. It's also possible that this functionality could be invoked by
  546. default via an event, which would require that
  547. selectables maintain a weak referencing collection of all
  548. derivations.
  549. """
  550. if not self._cols_populated:
  551. return None
  552. elif (column.key in self.columns and
  553. self.columns[column.key] is column):
  554. return column
  555. else:
  556. return None
  557. class Join(FromClause):
  558. """represent a ``JOIN`` construct between two :class:`.FromClause`
  559. elements.
  560. The public constructor function for :class:`.Join` is the module-level
  561. :func:`.join()` function, as well as the :meth:`.FromClause.join` method
  562. of any :class:`.FromClause` (e.g. such as :class:`.Table`).
  563. .. seealso::
  564. :func:`.join`
  565. :meth:`.FromClause.join`
  566. """
  567. __visit_name__ = 'join'
  568. _is_join = True
  569. def __init__(self, left, right, onclause=None, isouter=False, full=False):
  570. """Construct a new :class:`.Join`.
  571. The usual entrypoint here is the :func:`~.expression.join`
  572. function or the :meth:`.FromClause.join` method of any
  573. :class:`.FromClause` object.
  574. """
  575. self.left = _interpret_as_from(left)
  576. self.right = _interpret_as_from(right).self_group()
  577. if onclause is None:
  578. self.onclause = self._match_primaries(self.left, self.right)
  579. else:
  580. self.onclause = onclause
  581. self.isouter = isouter
  582. self.full = full
  583. @classmethod
  584. def _create_outerjoin(cls, left, right, onclause=None, full=False):
  585. """Return an ``OUTER JOIN`` clause element.
  586. The returned object is an instance of :class:`.Join`.
  587. Similar functionality is also available via the
  588. :meth:`~.FromClause.outerjoin()` method on any
  589. :class:`.FromClause`.
  590. :param left: The left side of the join.
  591. :param right: The right side of the join.
  592. :param onclause: Optional criterion for the ``ON`` clause, is
  593. derived from foreign key relationships established between
  594. left and right otherwise.
  595. To chain joins together, use the :meth:`.FromClause.join` or
  596. :meth:`.FromClause.outerjoin` methods on the resulting
  597. :class:`.Join` object.
  598. """
  599. return cls(left, right, onclause, isouter=True, full=full)
  600. @classmethod
  601. def _create_join(cls, left, right, onclause=None, isouter=False,
  602. full=False):
  603. """Produce a :class:`.Join` object, given two :class:`.FromClause`
  604. expressions.
  605. E.g.::
  606. j = join(user_table, address_table,
  607. user_table.c.id == address_table.c.user_id)
  608. stmt = select([user_table]).select_from(j)
  609. would emit SQL along the lines of::
  610. SELECT user.id, user.name FROM user
  611. JOIN address ON user.id = address.user_id
  612. Similar functionality is available given any
  613. :class:`.FromClause` object (e.g. such as a :class:`.Table`) using
  614. the :meth:`.FromClause.join` method.
  615. :param left: The left side of the join.
  616. :param right: the right side of the join; this is any
  617. :class:`.FromClause` object such as a :class:`.Table` object, and
  618. may also be a selectable-compatible object such as an ORM-mapped
  619. class.
  620. :param onclause: a SQL expression representing the ON clause of the
  621. join. If left at ``None``, :meth:`.FromClause.join` will attempt to
  622. join the two tables based on a foreign key relationship.
  623. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.
  624. :param full: if True, render a FULL OUTER JOIN, instead of JOIN.
  625. .. versionadded:: 1.1
  626. .. seealso::
  627. :meth:`.FromClause.join` - method form, based on a given left side
  628. :class:`.Join` - the type of object produced
  629. """
  630. return cls(left, right, onclause, isouter, full)
  631. @property
  632. def description(self):
  633. return "Join object on %s(%d) and %s(%d)" % (
  634. self.left.description,
  635. id(self.left),
  636. self.right.description,
  637. id(self.right))
  638. def is_derived_from(self, fromclause):
  639. return fromclause is self or \
  640. self.left.is_derived_from(fromclause) or \
  641. self.right.is_derived_from(fromclause)
  642. def self_group(self, against=None):
  643. return FromGrouping(self)
  644. @util.dependencies("sqlalchemy.sql.util")
  645. def _populate_column_collection(self, sqlutil):
  646. columns = [c for c in self.left.columns] + \
  647. [c for c in self.right.columns]
  648. self.primary_key.extend(sqlutil.reduce_columns(
  649. (c for c in columns if c.primary_key), self.onclause))
  650. self._columns.update((col._label, col) for col in columns)
  651. self.foreign_keys.update(itertools.chain(
  652. *[col.foreign_keys for col in columns]))
  653. def _refresh_for_new_column(self, column):
  654. col = self.left._refresh_for_new_column(column)
  655. if col is None:
  656. col = self.right._refresh_for_new_column(column)
  657. if col is not None:
  658. if self._cols_populated:
  659. self._columns[col._label] = col
  660. self.foreign_keys.update(col.foreign_keys)
  661. if col.primary_key:
  662. self.primary_key.add(col)
  663. return col
  664. return None
  665. def _copy_internals(self, clone=_clone, **kw):
  666. self._reset_exported()
  667. self.left = clone(self.left, **kw)
  668. self.right = clone(self.right, **kw)
  669. self.onclause = clone(self.onclause, **kw)
  670. def get_children(self, **kwargs):
  671. return self.left, self.right, self.onclause
  672. def _match_primaries(self, left, right):
  673. if isinstance(left, Join):
  674. left_right = left.right
  675. else:
  676. left_right = None
  677. return self._join_condition(left, right, a_subset=left_right)
  678. @classmethod
  679. def _join_condition(cls, a, b, ignore_nonexistent_tables=False,
  680. a_subset=None,
  681. consider_as_foreign_keys=None):
  682. """create a join condition between two tables or selectables.
  683. e.g.::
  684. join_condition(tablea, tableb)
  685. would produce an expression along the lines of::
  686. tablea.c.id==tableb.c.tablea_id
  687. The join is determined based on the foreign key relationships
  688. between the two selectables. If there are multiple ways
  689. to join, or no way to join, an error is raised.
  690. :param ignore_nonexistent_tables: Deprecated - this
  691. flag is no longer used. Only resolution errors regarding
  692. the two given tables are propagated.
  693. :param a_subset: An optional expression that is a sub-component
  694. of ``a``. An attempt will be made to join to just this sub-component
  695. first before looking at the full ``a`` construct, and if found
  696. will be successful even if there are other ways to join to ``a``.
  697. This allows the "right side" of a join to be passed thereby
  698. providing a "natural join".
  699. """
  700. constraints = cls._joincond_scan_left_right(
  701. a, a_subset, b, consider_as_foreign_keys)
  702. if len(constraints) > 1:
  703. cls._joincond_trim_constraints(
  704. a, b, constraints, consider_as_foreign_keys)
  705. if len(constraints) == 0:
  706. if isinstance(b, FromGrouping):
  707. hint = " Perhaps you meant to convert the right side to a "\
  708. "subquery using alias()?"
  709. else:
  710. hint = ""
  711. raise exc.NoForeignKeysError(
  712. "Can't find any foreign key relationships "
  713. "between '%s' and '%s'.%s" %
  714. (a.description, b.description, hint))
  715. crit = [(x == y) for x, y in list(constraints.values())[0]]
  716. if len(crit) == 1:
  717. return (crit[0])
  718. else:
  719. return and_(*crit)
  720. @classmethod
  721. def _joincond_scan_left_right(
  722. cls, a, a_subset, b, consider_as_foreign_keys):
  723. constraints = collections.defaultdict(list)
  724. for left in (a_subset, a):
  725. if left is None:
  726. continue
  727. for fk in sorted(
  728. b.foreign_keys,
  729. key=lambda fk: fk.parent._creation_order):
  730. if consider_as_foreign_keys is not None and \
  731. fk.parent not in consider_as_foreign_keys:
  732. continue
  733. try:
  734. col = fk.get_referent(left)
  735. except exc.NoReferenceError as nrte:
  736. if nrte.table_name == left.name:
  737. raise
  738. else:
  739. continue
  740. if col is not None:
  741. constraints[fk.constraint].append((col, fk.parent))
  742. if left is not b:
  743. for fk in sorted(
  744. left.foreign_keys,
  745. key=lambda fk: fk.parent._creation_order):
  746. if consider_as_foreign_keys is not None and \
  747. fk.parent not in consider_as_foreign_keys:
  748. continue
  749. try:
  750. col = fk.get_referent(b)
  751. except exc.NoReferenceError as nrte:
  752. if nrte.table_name == b.name:
  753. raise
  754. else:
  755. continue
  756. if col is not None:
  757. constraints[fk.constraint].append((col, fk.parent))
  758. if constraints:
  759. break
  760. return constraints
  761. @classmethod
  762. def _joincond_trim_constraints(
  763. cls, a, b, constraints, consider_as_foreign_keys):
  764. # more than one constraint matched. narrow down the list
  765. # to include just those FKCs that match exactly to
  766. # "consider_as_foreign_keys".
  767. if consider_as_foreign_keys:
  768. for const in list(constraints):
  769. if set(f.parent for f in const.elements) != set(
  770. consider_as_foreign_keys):
  771. del constraints[const]
  772. # if still multiple constraints, but
  773. # they all refer to the exact same end result, use it.
  774. if len(constraints) > 1:
  775. dedupe = set(tuple(crit) for crit in constraints.values())
  776. if len(dedupe) == 1:
  777. key = list(constraints)[0]
  778. constraints = {key: constraints[key]}
  779. if len(constraints) != 1:
  780. raise exc.AmbiguousForeignKeysError(
  781. "Can't determine join between '%s' and '%s'; "
  782. "tables have more than one foreign key "
  783. "constraint relationship between them. "
  784. "Please specify the 'onclause' of this "
  785. "join explicitly." % (a.description, b.description))
  786. def select(self, whereclause=None, **kwargs):
  787. r"""Create a :class:`.Select` from this :class:`.Join`.
  788. The equivalent long-hand form, given a :class:`.Join` object
  789. ``j``, is::
  790. from sqlalchemy import select
  791. j = select([j.left, j.right], **kw).\
  792. where(whereclause).\
  793. select_from(j)
  794. :param whereclause: the WHERE criterion that will be sent to
  795. the :func:`select()` function
  796. :param \**kwargs: all other kwargs are sent to the
  797. underlying :func:`select()` function.
  798. """
  799. collist = [self.left, self.right]
  800. return Select(collist, whereclause, from_obj=[self], **kwargs)
  801. @property
  802. def bind(self):
  803. return self.left.bind or self.right.bind
  804. @util.dependencies("sqlalchemy.sql.util")
  805. def alias(self, sqlutil, name=None, flat=False):
  806. r"""return an alias of this :class:`.Join`.
  807. The default behavior here is to first produce a SELECT
  808. construct from this :class:`.Join`, then to produce an
  809. :class:`.Alias` from that. So given a join of the form::
  810. j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
  811. The JOIN by itself would look like::
  812. table_a JOIN table_b ON table_a.id = table_b.a_id
  813. Whereas the alias of the above, ``j.alias()``, would in a
  814. SELECT context look like::
  815. (SELECT table_a.id AS table_a_id, table_b.id AS table_b_id,
  816. table_b.a_id AS table_b_a_id
  817. FROM table_a
  818. JOIN table_b ON table_a.id = table_b.a_id) AS anon_1
  819. The equivalent long-hand form, given a :class:`.Join` object
  820. ``j``, is::
  821. from sqlalchemy import select, alias
  822. j = alias(
  823. select([j.left, j.right]).\
  824. select_from(j).\
  825. with_labels(True).\
  826. correlate(False),
  827. name=name
  828. )
  829. The selectable produced by :meth:`.Join.alias` features the same
  830. columns as that of the two individual selectables presented under
  831. a single name - the individual columns are "auto-labeled", meaning
  832. the ``.c.`` collection of the resulting :class:`.Alias` represents
  833. the names of the individual columns using a
  834. ``<tablename>_<columname>`` scheme::
  835. j.c.table_a_id
  836. j.c.table_b_a_id
  837. :meth:`.Join.alias` also features an alternate
  838. option for aliasing joins which produces no enclosing SELECT and
  839. does not normally apply labels to the column names. The
  840. ``flat=True`` option will call :meth:`.FromClause.alias`
  841. against the left and right sides individually.
  842. Using this option, no new ``SELECT`` is produced;
  843. we instead, from a construct as below::
  844. j = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
  845. j = j.alias(flat=True)
  846. we get a result like this::
  847. table_a AS table_a_1 JOIN table_b AS table_b_1 ON
  848. table_a_1.id = table_b_1.a_id
  849. The ``flat=True`` argument is also propagated to the contained
  850. selectables, so that a composite join such as::
  851. j = table_a.join(
  852. table_b.join(table_c,
  853. table_b.c.id == table_c.c.b_id),
  854. table_b.c.a_id == table_a.c.id
  855. ).alias(flat=True)
  856. Will produce an expression like::
  857. table_a AS table_a_1 JOIN (
  858. table_b AS table_b_1 JOIN table_c AS table_c_1
  859. ON table_b_1.id = table_c_1.b_id
  860. ) ON table_a_1.id = table_b_1.a_id
  861. The standalone :func:`~.expression.alias` function as well as the
  862. base :meth:`.FromClause.alias` method also support the ``flat=True``
  863. argument as a no-op, so that the argument can be passed to the
  864. ``alias()`` method of any selectable.
  865. .. versionadded:: 0.9.0 Added the ``flat=True`` option to create
  866. "aliases" of joins without enclosing inside of a SELECT
  867. subquery.
  868. :param name: name given to the alias.
  869. :param flat: if True, produce an alias of the left and right
  870. sides of this :class:`.Join` and return the join of those
  871. two selectables. This produces join expression that does not
  872. include an enclosing SELECT.
  873. .. versionadded:: 0.9.0
  874. .. seealso::
  875. :func:`~.expression.alias`
  876. """
  877. if flat:
  878. assert name is None, "Can't send name argument with flat"
  879. left_a, right_a = self.left.alias(flat=True), \
  880. self.right.alias(flat=True)
  881. adapter = sqlutil.ClauseAdapter(left_a).\
  882. chain(sqlutil.ClauseAdapter(right_a))
  883. return left_a.join(right_a, adapter.traverse(self.onclause),
  884. isouter=self.isouter, full=self.full)
  885. else:
  886. return self.select(use_labels=True, correlate=False).alias(name)
  887. @property
  888. def _hide_froms(self):
  889. return itertools.chain(*[_from_objects(x.left, x.right)
  890. for x in self._cloned_set])
  891. @property
  892. def _from_objects(self):
  893. return [self] + \
  894. self.onclause._from_objects + \
  895. self.left._from_objects + \
  896. self.right._from_objects
  897. class Alias(FromClause):
  898. """Represents an table or selectable alias (AS).
  899. Represents an alias, as typically applied to any table or
  900. sub-select within a SQL statement using the ``AS`` keyword (or
  901. without the keyword on certain databases such as Oracle).
  902. This object is constructed from the :func:`~.expression.alias` module
  903. level function as well as the :meth:`.FromClause.alias` method available
  904. on all :class:`.FromClause` subclasses.
  905. """
  906. __visit_name__ = 'alias'
  907. named_with_column = True
  908. _is_from_container = True
  909. def __init__(self, selectable, name=None):
  910. baseselectable = selectable
  911. while isinstance(baseselectable, Alias):
  912. baseselectable = baseselectable.element
  913. self.original = baseselectable
  914. self.supports_execution = baseselectable.supports_execution
  915. if self.supports_execution:
  916. self._execution_options = baseselectable._execution_options
  917. self.element = selectable
  918. if name is None:
  919. if self.original.named_with_column:
  920. name = getattr(self.original, 'name', None)
  921. name = _anonymous_label('%%(%d %s)s' % (id(self), name
  922. or 'anon'))
  923. self.name = name
  924. def self_group(self, target=None):
  925. if isinstance(target, CompoundSelect) and \
  926. isinstance(self.original, Select) and \
  927. self.original._needs_parens_for_grouping():
  928. return FromGrouping(self)
  929. return super(Alias, self).self_group(target)
  930. @property
  931. def description(self):
  932. if util.py3k:
  933. return self.name
  934. else:
  935. return self.name.encode('ascii', 'backslashreplace')
  936. def as_scalar(self):
  937. try:
  938. return self.element.as_scalar()
  939. except AttributeError:
  940. raise AttributeError("Element %s does not support "
  941. "'as_scalar()'" % self.element)
  942. def is_derived_from(self, fromclause):
  943. if fromclause in self._cloned_set:
  944. return True
  945. return self.element.is_derived_from(fromclause)
  946. def _populate_column_collection(self):
  947. for col in self.element.columns._all_columns:
  948. col._make_proxy(self)
  949. def _refresh_for_new_column(self, column):
  950. col = self.element._refresh_for_new_column(column)
  951. if col is not None:
  952. if not self._cols_populated:
  953. return None
  954. else:
  955. return col._make_proxy(self)
  956. else:
  957. return None
  958. def _copy_internals(self, clone=_clone, **kw):
  959. # don't apply anything to an aliased Table
  960. # for now. May want to drive this from
  961. # the given **kw.
  962. if isinstance(self.element, TableClause):
  963. return
  964. self._reset_exported()
  965. self.element = clone(self.element, **kw)
  966. baseselectable = self.element
  967. while isinstance(baseselectable, Alias):
  968. baseselectable = baseselectable.element
  969. self.original = baseselectable
  970. def get_children(self, column_collections=True, **kw):
  971. if column_collections:
  972. for c in self.c:
  973. yield c
  974. yield self.element
  975. @property
  976. def _from_objects(self):
  977. return [self]
  978. @property
  979. def bind(self):
  980. return self.element.bind
  981. class Lateral(Alias):
  982. """Represent a LATERAL subquery.
  983. This object is constructed from the :func:`~.expression.lateral` module
  984. level function as well as the :meth:`.FromClause.lateral` method available
  985. on all :class:`.FromClause` subclasses.
  986. While LATERAL is part of the SQL standard, curently only more recent
  987. PostgreSQL versions provide support for this keyword.
  988. .. versionadded:: 1.1
  989. .. seealso::
  990. :ref:`lateral_selects` - overview of usage.
  991. """
  992. __visit_name__ = 'lateral'
  993. class TableSample(Alias):
  994. """Represent a TABLESAMPLE clause.
  995. This object is constructed from the :func:`~.expression.tablesample` module
  996. level function as well as the :meth:`.FromClause.tablesample` method available
  997. on all :class:`.FromClause` subclasses.
  998. .. versionadded:: 1.1
  999. .. seealso::
  1000. :func:`~.expression.tablesample`
  1001. """
  1002. __visit_name__ = 'tablesample'
  1003. def __init__(self, selectable, sampling,
  1004. name=None,
  1005. seed=None):
  1006. self.sampling = sampling
  1007. self.seed = seed
  1008. super(TableSample, self).__init__(selectable, name=name)
  1009. @util.dependencies("sqlalchemy.sql.functions")
  1010. def _get_method(self, functions):
  1011. if isinstance(self.sampling, functions.Function):
  1012. return self.sampling
  1013. else:
  1014. return functions.func.system(self.sampling)
  1015. class CTE(Generative, HasSuffixes, Alias):
  1016. """Represent a Common Table Expression.
  1017. The :class:`.CTE` object is obtained using the
  1018. :meth:`.SelectBase.cte` method from any selectable.
  1019. See that method for complete examples.
  1020. .. versionadded:: 0.7.6
  1021. """
  1022. __visit_name__ = 'cte'
  1023. def __init__(self, selectable,
  1024. name=None,
  1025. recursive=False,
  1026. _cte_alias=None,
  1027. _restates=frozenset(),
  1028. _suffixes=None):
  1029. self.recursive = recursive
  1030. self._cte_alias = _cte_alias
  1031. self._restates = _restates
  1032. if _suffixes:
  1033. self._suffixes = _suffixes
  1034. super(CTE, self).__init__(selectable, name=name)
  1035. def _copy_internals(self, clone=_clone, **kw):
  1036. super(CTE, self)._copy_internals(clone, **kw)
  1037. if self._cte_alias is not None:
  1038. self._cte_alias = self
  1039. self._restates = frozenset([
  1040. clone(elem, **kw) for elem in self._restates
  1041. ])
  1042. @util.dependencies("sqlalchemy.sql.dml")
  1043. def _populate_column_collection(self, dml):
  1044. if isinstance(self.element, dml.UpdateBase):
  1045. for col in self.element._returning:
  1046. col._make_proxy(self)
  1047. else:
  1048. for col in self.element.columns._all_columns:
  1049. col._make_proxy(self)
  1050. def alias(self, name=None, flat=False):
  1051. return CTE(
  1052. self.original,
  1053. name=name,
  1054. recursive=self.recursive,
  1055. _cte_alias=self,
  1056. _suffixes=self._suffixes
  1057. )
  1058. def union(self, other):
  1059. return CTE(
  1060. self.original.union(other),
  1061. name=self.name,
  1062. recursive=self.recursive,
  1063. _restates=self._restates.union([self]),
  1064. _suffixes=self._suffixes
  1065. )
  1066. def union_all(self, other):
  1067. return CTE(
  1068. self.original.union_all(other),
  1069. name=self.name,
  1070. recursive=self.recursive,
  1071. _restates=self._restates.union([self]),
  1072. _suffixes=self._suffixes
  1073. )
  1074. class HasCTE(object):
  1075. """Mixin that declares a class to include CTE support.
  1076. .. versionadded:: 1.1
  1077. """
  1078. def cte(self, name=None, recursive=False):
  1079. r"""Return a new :class:`.CTE`, or Common Table Expression instance.
  1080. Common table expressions are a SQL standard whereby SELECT
  1081. statements can draw upon secondary statements specified along
  1082. with the primary statement, using a clause called "WITH".
  1083. Special semantics regarding UNION can also be employed to
  1084. allow "recursive" queries, where a SELECT statement can draw
  1085. upon the set of rows that have previously been selected.
  1086. CTEs can also be applied to DML constructs UPDATE, INSERT
  1087. and DELETE on some databases, both as a source of CTE rows
  1088. when combined with RETURNING, as well as a consumer of
  1089. CTE rows.
  1090. SQLAlchemy detects :class:`.CTE` objects, which are treated
  1091. similarly to :class:`.Alias` objects, as special elements
  1092. to be delivered to the FROM clause of the statement as well
  1093. as to a WITH clause at the top of the statement.
  1094. .. versionchanged:: 1.1 Added support for UPDATE/INSERT/DELETE as
  1095. CTE, CTEs added to UPDATE/INSERT/DELETE.
  1096. :param name: name given to the common table expression. Like
  1097. :meth:`._FromClause.alias`, the name can be left as ``None``
  1098. in which case an anonymous symbol will be used at query
  1099. compile time.
  1100. :param recursive: if ``True``, will render ``WITH RECURSIVE``.
  1101. A recursive common table expression is intended to be used in
  1102. conjunction with UNION ALL in order to derive rows
  1103. from those already selected.
  1104. The following examples include two from PostgreSQL's documentation at
  1105. http://www.postgresql.org/docs/current/static/queries-with.html,
  1106. as well as additional examples.
  1107. Example 1, non recursive::
  1108. from sqlalchemy import (Table, Column, String, Integer,
  1109. MetaData, select, func)
  1110. metadata = MetaData()
  1111. orders = Table('orders', metadata,
  1112. Column('region', String),
  1113. Column('amount', Integer),
  1114. Column('product', String),
  1115. Column('quantity', Integer)
  1116. )
  1117. regional_sales = select([
  1118. orders.c.region,
  1119. func.sum(orders.c.amount).label('total_sales')
  1120. ]).group_by(orders.c.region).cte("regional_sales")
  1121. top_regions = select([regional_sales.c.region]).\
  1122. where(
  1123. regional_sales.c.total_sales >
  1124. select([
  1125. func.sum(regional_sales.c.total_sales)/10
  1126. ])
  1127. ).cte("top_regions")
  1128. statement = select([
  1129. orders.c.region,
  1130. orders.c.product,
  1131. func.sum(orders.c.quantity).label("product_units"),
  1132. func.sum(orders.c.amount).label("product_sales")
  1133. ]).where(orders.c.region.in_(
  1134. select([top_regions.c.region])
  1135. )).group_by(orders.c.region, orders.c.product)
  1136. result = conn.execute(statement).fetchall()
  1137. Example 2, WITH RECURSIVE::
  1138. from sqlalchemy import (Table, Column, String, Integer,
  1139. MetaData, select, func)
  1140. metadata = MetaData()
  1141. parts = Table('parts', metadata,
  1142. Column('part', String),
  1143. Column('sub_part', String),
  1144. Column('quantity', Integer),
  1145. )
  1146. included_parts = select([
  1147. parts.c.sub_part,
  1148. parts.c.part,
  1149. parts.c.quantity]).\
  1150. where(parts.c.part=='our part').\
  1151. cte(recursive=True)
  1152. incl_alias = included_parts.alias()
  1153. parts_alias = parts.alias()
  1154. included_parts = included_parts.union_all(
  1155. select([
  1156. parts_alias.c.sub_part,
  1157. parts_alias.c.part,
  1158. parts_alias.c.quantity
  1159. ]).
  1160. where(parts_alias.c.part==incl_alias.c.sub_part)
  1161. )
  1162. statement = select([
  1163. included_parts.c.sub_part,
  1164. func.sum(included_parts.c.quantity).
  1165. label('total_quantity')
  1166. ]).\
  1167. group_by(included_parts.c.sub_part)
  1168. result = conn.execute(statement).fetchall()
  1169. Example 3, an upsert using UPDATE and INSERT with CTEs::
  1170. from datetime import date
  1171. from sqlalchemy import (MetaData, Table, Column, Integer,
  1172. Date, select, literal, and_, exists)
  1173. metadata = MetaData()
  1174. visitors = Table('visitors', metadata,
  1175. Column('product_id', Integer, primary_key=True),
  1176. Column('date', Date, primary_key=True),
  1177. Column('count', Integer),
  1178. )
  1179. # add 5 visitors for the product_id == 1
  1180. product_id = 1
  1181. day = date.today()
  1182. count = 5
  1183. update_cte = (
  1184. visitors.update()
  1185. .where(and_(visitors.c.product_id == product_id,
  1186. visitors.c.date == day))
  1187. .values(count=visitors.c.count + count)
  1188. .returning(literal(1))
  1189. .cte('update_cte')
  1190. )
  1191. upsert = visitors.insert().from_select(
  1192. [visitors.c.product_id, visitors.c.date, visitors.c.count],
  1193. select([literal(product_id), literal(day), literal(count)])
  1194. .where(~exists(update_cte.select()))
  1195. )
  1196. connection.execute(upsert)
  1197. .. seealso::
  1198. :meth:`.orm.query.Query.cte` - ORM version of
  1199. :meth:`.HasCTE.cte`.
  1200. """
  1201. return CTE(self, name=name, recursive=recursive)
  1202. class FromGrouping(FromClause):
  1203. """Represent a grouping of a FROM clause"""
  1204. __visit_name__ = 'grouping'
  1205. def __init__(self, element):
  1206. self.element = element
  1207. def _init_collections(self):
  1208. pass
  1209. @property
  1210. def columns(self):
  1211. return self.element.columns
  1212. @property
  1213. def primary_key(self):
  1214. return self.element.primary_key
  1215. @property
  1216. def foreign_keys(self):
  1217. return self.element.foreign_keys
  1218. def is_derived_from(self, element):
  1219. return self.element.is_derived_from(element)
  1220. def alias(self, **kw):
  1221. return FromGrouping(self.element.alias(**kw))
  1222. @property
  1223. def _hide_froms(self):
  1224. return self.element._hide_froms
  1225. def get_children(self, **kwargs):
  1226. return self.element,
  1227. def _copy_internals(self, clone=_clone, **kw):
  1228. self.element = clone(self.element, **kw)
  1229. @property
  1230. def _from_objects(self):
  1231. return self.element._from_objects
  1232. def __getattr__(self, attr):
  1233. return getattr(self.element, attr)
  1234. def __getstate__(self):
  1235. return {'element': self.element}
  1236. def __setstate__(self, state):
  1237. self.element = state['element']
  1238. class TableClause(Immutable, FromClause):
  1239. """Represents a minimal "table" construct.
  1240. This is a lightweight table object that has only a name and a
  1241. collection of columns, which are typically produced
  1242. by the :func:`.expression.column` function::
  1243. from sqlalchemy import table, column
  1244. user = table("user",
  1245. column("id"),
  1246. column("name"),
  1247. column("description"),
  1248. )
  1249. The :class:`.TableClause` construct serves as the base for
  1250. the more commonly used :class:`~.schema.Table` object, providing
  1251. the usual set of :class:`~.expression.FromClause` services including
  1252. the ``.c.`` collection and statement generation methods.
  1253. It does **not** provide all the additional schema-level services
  1254. of :class:`~.schema.Table`, including constraints, references to other
  1255. tables, or support for :class:`.MetaData`-level services. It's useful
  1256. on its own as an ad-hoc construct used to generate quick SQL
  1257. statements when a more fully fledged :class:`~.schema.Table`
  1258. is not on hand.
  1259. """
  1260. __visit_name__ = 'table'
  1261. named_with_column = True
  1262. implicit_returning = False
  1263. """:class:`.TableClause` doesn't support having a primary key or column
  1264. -level defaults, so implicit returning doesn't apply."""
  1265. _autoincrement_column = None
  1266. """No PK or default support so no autoincrement column."""
  1267. def __init__(self, name, *columns):
  1268. """Produce a new :class:`.TableClause`.
  1269. The object returned is an instance of :class:`.TableClause`, which
  1270. represents the "syntactical" portion of the schema-level
  1271. :class:`~.schema.Table` object.
  1272. It may be used to construct lightweight table constructs.
  1273. .. versionchanged:: 1.0.0 :func:`.expression.table` can now
  1274. be imported from the plain ``sqlalchemy`` namespace like any
  1275. other SQL element.
  1276. :param name: Name of the table.
  1277. :param columns: A collection of :func:`.expression.column` constructs.
  1278. """
  1279. super(TableClause, self).__init__()
  1280. self.name = self.fullname = name
  1281. self._columns = ColumnCollection()
  1282. self.primary_key = ColumnSet()
  1283. self.foreign_keys = set()
  1284. for c in columns:
  1285. self.append_column(c)
  1286. def _init_collections(self):
  1287. pass
  1288. @util.memoized_property
  1289. def description(self):
  1290. if util.py3k:
  1291. return self.name
  1292. else:
  1293. return self.name.encode('ascii', 'backslashreplace')
  1294. def append_column(self, c):
  1295. self._columns[c.key] = c
  1296. c.table = self
  1297. def get_children(self, column_collections=True, **kwargs):
  1298. if column_collections:
  1299. return [c for c in self.c]
  1300. else:
  1301. return []
  1302. @util.dependencies("sqlalchemy.sql.dml")
  1303. def insert(self, dml, values=None, inline=False, **kwargs):
  1304. """Generate an :func:`.insert` construct against this
  1305. :class:`.TableClause`.
  1306. E.g.::
  1307. table.insert().values(name='foo')
  1308. See :func:`.insert` for argument and usage information.
  1309. """
  1310. return dml.Insert(self, values=values, inline=inline, **kwargs)
  1311. @util.dependencies("sqlalchemy.sql.dml")
  1312. def update(
  1313. self, dml, whereclause=None, values=None, inline=False, **kwargs):
  1314. """Generate an :func:`.update` construct against this
  1315. :class:`.TableClause`.
  1316. E.g.::
  1317. table.update().where(table.c.id==7).values(name='foo')
  1318. See :func:`.update` for argument and usage information.
  1319. """
  1320. return dml.Update(self, whereclause=whereclause,
  1321. values=values, inline=inline, **kwargs)
  1322. @util.dependencies("sqlalchemy.sql.dml")
  1323. def delete(self, dml, whereclause=None, **kwargs):
  1324. """Generate a :func:`.delete` construct against this
  1325. :class:`.TableClause`.
  1326. E.g.::
  1327. table.delete().where(table.c.id==7)
  1328. See :func:`.delete` for argument and usage information.
  1329. """
  1330. return dml.Delete(self, whereclause, **kwargs)
  1331. @property
  1332. def _from_objects(self):
  1333. return [self]
  1334. class ForUpdateArg(ClauseElement):
  1335. @classmethod
  1336. def parse_legacy_select(self, arg):
  1337. """Parse the for_update argument of :func:`.select`.
  1338. :param mode: Defines the lockmode to use.
  1339. ``None`` - translates to no lockmode
  1340. ``'update'`` - translates to ``FOR UPDATE``
  1341. (standard SQL, supported by most dialects)
  1342. ``'nowait'`` - translates to ``FOR UPDATE NOWAIT``
  1343. (supported by Oracle, PostgreSQL 8.1 upwards)
  1344. ``'read'`` - translates to ``LOCK IN SHARE MODE`` (for MySQL),
  1345. and ``FOR SHARE`` (for PostgreSQL)
  1346. ``'read_nowait'`` - translates to ``FOR SHARE NOWAIT``
  1347. (supported by PostgreSQL). ``FOR SHARE`` and
  1348. ``FOR SHARE NOWAIT`` (PostgreSQL).
  1349. """
  1350. if arg in (None, False):
  1351. return None
  1352. nowait = read = False
  1353. if arg == 'nowait':
  1354. nowait = True
  1355. elif arg == 'read':
  1356. read = True
  1357. elif arg == 'read_nowait':
  1358. read = nowait = True
  1359. elif arg is not True:
  1360. raise exc.ArgumentError("Unknown for_update argument: %r" % arg)
  1361. return ForUpdateArg(read=read, nowait=nowait)
  1362. @property
  1363. def legacy_for_update_value(self):
  1364. if self.read and not self.nowait:
  1365. return "read"
  1366. elif self.read and self.nowait:
  1367. return "read_nowait"
  1368. elif self.nowait:
  1369. return "nowait"
  1370. else:
  1371. return True
  1372. def _copy_internals(self, clone=_clone, **kw):
  1373. if self.of is not None:
  1374. self.of = [clone(col, **kw) for col in self.of]
  1375. def __init__(
  1376. self, nowait=False, read=False, of=None,
  1377. skip_locked=False, key_share=False):
  1378. """Represents arguments specified to :meth:`.Select.for_update`.
  1379. .. versionadded:: 0.9.0
  1380. """
  1381. self.nowait = nowait
  1382. self.read = read
  1383. self.skip_locked = skip_locked
  1384. self.key_share = key_share
  1385. if of is not None:
  1386. self.of = [_interpret_as_column_or_from(elem)
  1387. for elem in util.to_list(of)]
  1388. else:
  1389. self.of = None
  1390. class SelectBase(HasCTE, Executable, FromClause):
  1391. """Base class for SELECT statements.
  1392. This includes :class:`.Select`, :class:`.CompoundSelect` and
  1393. :class:`.TextAsFrom`.
  1394. """
  1395. def as_scalar(self):
  1396. """return a 'scalar' representation of this selectable, which can be
  1397. used as a column expression.
  1398. Typically, a select statement which has only one column in its columns
  1399. clause is eligible to be used as a scalar expression.
  1400. The returned object is an instance of
  1401. :class:`ScalarSelect`.
  1402. """
  1403. return ScalarSelect(self)
  1404. def label(self, name):
  1405. """return a 'scalar' representation of this selectable, embedded as a
  1406. subquery with a label.
  1407. .. seealso::
  1408. :meth:`~.SelectBase.as_scalar`.
  1409. """
  1410. return self.as_scalar().label(name)
  1411. @_generative
  1412. @util.deprecated('0.6',
  1413. message="``autocommit()`` is deprecated. Use "
  1414. ":meth:`.Executable.execution_options` with the "
  1415. "'autocommit' flag.")
  1416. def autocommit(self):
  1417. """return a new selectable with the 'autocommit' flag set to
  1418. True.
  1419. """
  1420. self._execution_options = \
  1421. self._execution_options.union({'autocommit': True})
  1422. def _generate(self):
  1423. """Override the default _generate() method to also clear out
  1424. exported collections."""
  1425. s = self.__class__.__new__(self.__class__)
  1426. s.__dict__ = self.__dict__.copy()
  1427. s._reset_exported()
  1428. return s
  1429. @property
  1430. def _from_objects(self):
  1431. return [self]
  1432. class GenerativeSelect(SelectBase):
  1433. """Base class for SELECT statements where additional elements can be
  1434. added.
  1435. This serves as the base for :class:`.Select` and :class:`.CompoundSelect`
  1436. where elements such as ORDER BY, GROUP BY can be added and column
  1437. rendering can be controlled. Compare to :class:`.TextAsFrom`, which,
  1438. while it subclasses :class:`.SelectBase` and is also a SELECT construct,
  1439. represents a fixed textual string which cannot be altered at this level,
  1440. only wrapped as a subquery.
  1441. .. versionadded:: 0.9.0 :class:`.GenerativeSelect` was added to
  1442. provide functionality specific to :class:`.Select` and
  1443. :class:`.CompoundSelect` while allowing :class:`.SelectBase` to be
  1444. used for other SELECT-like objects, e.g. :class:`.TextAsFrom`.
  1445. """
  1446. _order_by_clause = ClauseList()
  1447. _group_by_clause = ClauseList()
  1448. _limit_clause = None
  1449. _offset_clause = None
  1450. _for_update_arg = None
  1451. def __init__(self,
  1452. use_labels=False,
  1453. for_update=False,
  1454. limit=None,
  1455. offset=None,
  1456. order_by=None,
  1457. group_by=None,
  1458. bind=None,
  1459. autocommit=None):
  1460. self.use_labels = use_labels
  1461. if for_update is not False:
  1462. self._for_update_arg = (ForUpdateArg.
  1463. parse_legacy_select(for_update))
  1464. if autocommit is not None:
  1465. util.warn_deprecated('autocommit on select() is '
  1466. 'deprecated. Use .execution_options(a'
  1467. 'utocommit=True)')
  1468. self._execution_options = \
  1469. self._execution_options.union(
  1470. {'autocommit': autocommit})
  1471. if limit is not None:
  1472. self._limit_clause = _offset_or_limit_clause(limit)
  1473. if offset is not None:
  1474. self._offset_clause = _offset_or_limit_clause(offset)
  1475. self._bind = bind
  1476. if order_by is not None:
  1477. self._order_by_clause = ClauseList(
  1478. *util.to_list(order_by),
  1479. _literal_as_text=_literal_and_labels_as_label_reference)
  1480. if group_by is not None:
  1481. self._group_by_clause = ClauseList(
  1482. *util.to_list(group_by),
  1483. _literal_as_text=_literal_as_label_reference)
  1484. @property
  1485. def for_update(self):
  1486. """Provide legacy dialect support for the ``for_update`` attribute.
  1487. """
  1488. if self._for_update_arg is not None:
  1489. return self._for_update_arg.legacy_for_update_value
  1490. else:
  1491. return None
  1492. @for_update.setter
  1493. def for_update(self, value):
  1494. self._for_update_arg = ForUpdateArg.parse_legacy_select(value)
  1495. @_generative
  1496. def with_for_update(self, nowait=False, read=False, of=None,
  1497. skip_locked=False, key_share=False):
  1498. """Specify a ``FOR UPDATE`` clause for this :class:`.GenerativeSelect`.
  1499. E.g.::
  1500. stmt = select([table]).with_for_update(nowait=True)
  1501. On a database like PostgreSQL or Oracle, the above would render a
  1502. statement like::
  1503. SELECT table.a, table.b FROM table FOR UPDATE NOWAIT
  1504. on other backends, the ``nowait`` option is ignored and instead
  1505. would produce::
  1506. SELECT table.a, table.b FROM table FOR UPDATE
  1507. When called with no arguments, the statement will render with
  1508. the suffix ``FOR UPDATE``. Additional arguments can then be
  1509. provided which allow for common database-specific
  1510. variants.
  1511. :param nowait: boolean; will render ``FOR UPDATE NOWAIT`` on Oracle
  1512. and PostgreSQL dialects.
  1513. :param read: boolean; will render ``LOCK IN SHARE MODE`` on MySQL,
  1514. ``FOR SHARE`` on PostgreSQL. On PostgreSQL, when combined with
  1515. ``nowait``, will render ``FOR SHARE NOWAIT``.
  1516. :param of: SQL expression or list of SQL expression elements
  1517. (typically :class:`.Column` objects or a compatible expression) which
  1518. will render into a ``FOR UPDATE OF`` clause; supported by PostgreSQL
  1519. and Oracle. May render as a table or as a column depending on
  1520. backend.
  1521. :param skip_locked: boolean, will render ``FOR UPDATE SKIP LOCKED``
  1522. on Oracle and PostgreSQL dialects or ``FOR SHARE SKIP LOCKED`` if
  1523. ``read=True`` is also specified.
  1524. .. versionadded:: 1.1.0
  1525. :param key_share: boolean, will render ``FOR NO KEY UPDATE``,
  1526. or if combined with ``read=True`` will render ``FOR KEY SHARE``,
  1527. on the PostgreSQL dialect.
  1528. .. versionadded:: 1.1.0
  1529. """
  1530. self._for_update_arg = ForUpdateArg(nowait=nowait, read=read, of=of,
  1531. skip_locked=skip_locked,
  1532. key_share=key_share)
  1533. @_generative
  1534. def apply_labels(self):
  1535. """return a new selectable with the 'use_labels' flag set to True.
  1536. This will result in column expressions being generated using labels
  1537. against their table name, such as "SELECT somecolumn AS
  1538. tablename_somecolumn". This allows selectables which contain multiple
  1539. FROM clauses to produce a unique set of column names regardless of
  1540. name conflicts among the individual FROM clauses.
  1541. """
  1542. self.use_labels = True
  1543. @property
  1544. def _limit(self):
  1545. """Get an integer value for the limit. This should only be used
  1546. by code that cannot support a limit as a BindParameter or
  1547. other custom clause as it will throw an exception if the limit
  1548. isn't currently set to an integer.
  1549. """
  1550. return _offset_or_limit_clause_asint(self._limit_clause, "limit")
  1551. @property
  1552. def _simple_int_limit(self):
  1553. """True if the LIMIT clause is a simple integer, False
  1554. if it is not present or is a SQL expression.
  1555. """
  1556. return isinstance(self._limit_clause, _OffsetLimitParam)
  1557. @property
  1558. def _simple_int_offset(self):
  1559. """True if the OFFSET clause is a simple integer, False
  1560. if it is not present or is a SQL expression.
  1561. """
  1562. return isinstance(self._offset_clause, _OffsetLimitParam)
  1563. @property
  1564. def _offset(self):
  1565. """Get an integer value for the offset. This should only be used
  1566. by code that cannot support an offset as a BindParameter or
  1567. other custom clause as it will throw an exception if the
  1568. offset isn't currently set to an integer.
  1569. """
  1570. return _offset_or_limit_clause_asint(self._offset_clause, "offset")
  1571. @_generative
  1572. def limit(self, limit):
  1573. """return a new selectable with the given LIMIT criterion
  1574. applied.
  1575. This is a numerical value which usually renders as a ``LIMIT``
  1576. expression in the resulting select. Backends that don't
  1577. support ``LIMIT`` will attempt to provide similar
  1578. functionality.
  1579. .. versionchanged:: 1.0.0 - :meth:`.Select.limit` can now
  1580. accept arbitrary SQL expressions as well as integer values.
  1581. :param limit: an integer LIMIT parameter, or a SQL expression
  1582. that provides an integer result.
  1583. """
  1584. self._limit_clause = _offset_or_limit_clause(limit)
  1585. @_generative
  1586. def offset(self, offset):
  1587. """return a new selectable with the given OFFSET criterion
  1588. applied.
  1589. This is a numeric value which usually renders as an ``OFFSET``
  1590. expression in the resulting select. Backends that don't
  1591. support ``OFFSET`` will attempt to provide similar
  1592. functionality.
  1593. .. versionchanged:: 1.0.0 - :meth:`.Select.offset` can now
  1594. accept arbitrary SQL expressions as well as integer values.
  1595. :param offset: an integer OFFSET parameter, or a SQL expression
  1596. that provides an integer result.
  1597. """
  1598. self._offset_clause = _offset_or_limit_clause(offset)
  1599. @_generative
  1600. def order_by(self, *clauses):
  1601. """return a new selectable with the given list of ORDER BY
  1602. criterion applied.
  1603. The criterion will be appended to any pre-existing ORDER BY
  1604. criterion.
  1605. """
  1606. self.append_order_by(*clauses)
  1607. @_generative
  1608. def group_by(self, *clauses):
  1609. """return a new selectable with the given list of GROUP BY
  1610. criterion applied.
  1611. The criterion will be appended to any pre-existing GROUP BY
  1612. criterion.
  1613. """
  1614. self.append_group_by(*clauses)
  1615. def append_order_by(self, *clauses):
  1616. """Append the given ORDER BY criterion applied to this selectable.
  1617. The criterion will be appended to any pre-existing ORDER BY criterion.
  1618. This is an **in-place** mutation method; the
  1619. :meth:`~.GenerativeSelect.order_by` method is preferred, as it
  1620. provides standard :term:`method chaining`.
  1621. """
  1622. if len(clauses) == 1 and clauses[0] is None:
  1623. self._order_by_clause = ClauseList()
  1624. else:
  1625. if getattr(self, '_order_by_clause', None) is not None:
  1626. clauses = list(self._order_by_clause) + list(clauses)
  1627. self._order_by_clause = ClauseList(
  1628. *clauses,
  1629. _literal_as_text=_literal_and_labels_as_label_reference)
  1630. def append_group_by(self, *clauses):
  1631. """Append the given GROUP BY criterion applied to this selectable.
  1632. The criterion will be appended to any pre-existing GROUP BY criterion.
  1633. This is an **in-place** mutation method; the
  1634. :meth:`~.GenerativeSelect.group_by` method is preferred, as it
  1635. provides standard :term:`method chaining`.
  1636. """
  1637. if len(clauses) == 1 and clauses[0] is None:
  1638. self._group_by_clause = ClauseList()
  1639. else:
  1640. if getattr(self, '_group_by_clause', None) is not None:
  1641. clauses = list(self._group_by_clause) + list(clauses)
  1642. self._group_by_clause = ClauseList(
  1643. *clauses, _literal_as_text=_literal_as_label_reference)
  1644. @property
  1645. def _label_resolve_dict(self):
  1646. raise NotImplementedError()
  1647. def _copy_internals(self, clone=_clone, **kw):
  1648. if self._limit_clause is not None:
  1649. self._limit_clause = clone(self._limit_clause, **kw)
  1650. if self._offset_clause is not None:
  1651. self._offset_clause = clone(self._offset_clause, **kw)
  1652. class CompoundSelect(GenerativeSelect):
  1653. """Forms the basis of ``UNION``, ``UNION ALL``, and other
  1654. SELECT-based set operations.
  1655. .. seealso::
  1656. :func:`.union`
  1657. :func:`.union_all`
  1658. :func:`.intersect`
  1659. :func:`.intersect_all`
  1660. :func:`.except`
  1661. :func:`.except_all`
  1662. """
  1663. __visit_name__ = 'compound_select'
  1664. UNION = util.symbol('UNION')
  1665. UNION_ALL = util.symbol('UNION ALL')
  1666. EXCEPT = util.symbol('EXCEPT')
  1667. EXCEPT_ALL = util.symbol('EXCEPT ALL')
  1668. INTERSECT = util.symbol('INTERSECT')
  1669. INTERSECT_ALL = util.symbol('INTERSECT ALL')
  1670. _is_from_container = True
  1671. def __init__(self, keyword, *selects, **kwargs):
  1672. self._auto_correlate = kwargs.pop('correlate', False)
  1673. self.keyword = keyword
  1674. self.selects = []
  1675. numcols = None
  1676. # some DBs do not like ORDER BY in the inner queries of a UNION, etc.
  1677. for n, s in enumerate(selects):
  1678. s = _clause_element_as_expr(s)
  1679. if not numcols:
  1680. numcols = len(s.c._all_columns)
  1681. elif len(s.c._all_columns) != numcols:
  1682. raise exc.ArgumentError(
  1683. 'All selectables passed to '
  1684. 'CompoundSelect must have identical numbers of '
  1685. 'columns; select #%d has %d columns, select '
  1686. '#%d has %d' %
  1687. (1, len(self.selects[0].c._all_columns),
  1688. n + 1, len(s.c._all_columns))
  1689. )
  1690. self.selects.append(s.self_group(self))
  1691. GenerativeSelect.__init__(self, **kwargs)
  1692. @property
  1693. def _label_resolve_dict(self):
  1694. d = dict(
  1695. (c.key, c) for c in self.c
  1696. )
  1697. return d, d, d
  1698. @classmethod
  1699. def _create_union(cls, *selects, **kwargs):
  1700. r"""Return a ``UNION`` of multiple selectables.
  1701. The returned object is an instance of
  1702. :class:`.CompoundSelect`.
  1703. A similar :func:`union()` method is available on all
  1704. :class:`.FromClause` subclasses.
  1705. \*selects
  1706. a list of :class:`.Select` instances.
  1707. \**kwargs
  1708. available keyword arguments are the same as those of
  1709. :func:`select`.
  1710. """
  1711. return CompoundSelect(CompoundSelect.UNION, *selects, **kwargs)
  1712. @classmethod
  1713. def _create_union_all(cls, *selects, **kwargs):
  1714. r"""Return a ``UNION ALL`` of multiple selectables.
  1715. The returned object is an instance of
  1716. :class:`.CompoundSelect`.
  1717. A similar :func:`union_all()` method is available on all
  1718. :class:`.FromClause` subclasses.
  1719. \*selects
  1720. a list of :class:`.Select` instances.
  1721. \**kwargs
  1722. available keyword arguments are the same as those of
  1723. :func:`select`.
  1724. """
  1725. return CompoundSelect(CompoundSelect.UNION_ALL, *selects, **kwargs)
  1726. @classmethod
  1727. def _create_except(cls, *selects, **kwargs):
  1728. r"""Return an ``EXCEPT`` of multiple selectables.
  1729. The returned object is an instance of
  1730. :class:`.CompoundSelect`.
  1731. \*selects
  1732. a list of :class:`.Select` instances.
  1733. \**kwargs
  1734. available keyword arguments are the same as those of
  1735. :func:`select`.
  1736. """
  1737. return CompoundSelect(CompoundSelect.EXCEPT, *selects, **kwargs)
  1738. @classmethod
  1739. def _create_except_all(cls, *selects, **kwargs):
  1740. r"""Return an ``EXCEPT ALL`` of multiple selectables.
  1741. The returned object is an instance of
  1742. :class:`.CompoundSelect`.
  1743. \*selects
  1744. a list of :class:`.Select` instances.
  1745. \**kwargs
  1746. available keyword arguments are the same as those of
  1747. :func:`select`.
  1748. """
  1749. return CompoundSelect(CompoundSelect.EXCEPT_ALL, *selects, **kwargs)
  1750. @classmethod
  1751. def _create_intersect(cls, *selects, **kwargs):
  1752. r"""Return an ``INTERSECT`` of multiple selectables.
  1753. The returned object is an instance of
  1754. :class:`.CompoundSelect`.
  1755. \*selects
  1756. a list of :class:`.Select` instances.
  1757. \**kwargs
  1758. available keyword arguments are the same as those of
  1759. :func:`select`.
  1760. """
  1761. return CompoundSelect(CompoundSelect.INTERSECT, *selects, **kwargs)
  1762. @classmethod
  1763. def _create_intersect_all(cls, *selects, **kwargs):
  1764. r"""Return an ``INTERSECT ALL`` of multiple selectables.
  1765. The returned object is an instance of
  1766. :class:`.CompoundSelect`.
  1767. \*selects
  1768. a list of :class:`.Select` instances.
  1769. \**kwargs
  1770. available keyword arguments are the same as those of
  1771. :func:`select`.
  1772. """
  1773. return CompoundSelect(
  1774. CompoundSelect.INTERSECT_ALL, *selects, **kwargs)
  1775. def _scalar_type(self):
  1776. return self.selects[0]._scalar_type()
  1777. def self_group(self, against=None):
  1778. return FromGrouping(self)
  1779. def is_derived_from(self, fromclause):
  1780. for s in self.selects:
  1781. if s.is_derived_from(fromclause):
  1782. return True
  1783. return False
  1784. def _populate_column_collection(self):
  1785. for cols in zip(*[s.c._all_columns for s in self.selects]):
  1786. # this is a slightly hacky thing - the union exports a
  1787. # column that resembles just that of the *first* selectable.
  1788. # to get at a "composite" column, particularly foreign keys,
  1789. # you have to dig through the proxies collection which we
  1790. # generate below. We may want to improve upon this, such as
  1791. # perhaps _make_proxy can accept a list of other columns
  1792. # that are "shared" - schema.column can then copy all the
  1793. # ForeignKeys in. this would allow the union() to have all
  1794. # those fks too.
  1795. proxy = cols[0]._make_proxy(
  1796. self, name=cols[0]._label if self.use_labels else None,
  1797. key=cols[0]._key_label if self.use_labels else None)
  1798. # hand-construct the "_proxies" collection to include all
  1799. # derived columns place a 'weight' annotation corresponding
  1800. # to how low in the list of select()s the column occurs, so
  1801. # that the corresponding_column() operation can resolve
  1802. # conflicts
  1803. proxy._proxies = [
  1804. c._annotate({'weight': i + 1}) for (i, c) in enumerate(cols)]
  1805. def _refresh_for_new_column(self, column):
  1806. for s in self.selects:
  1807. s._refresh_for_new_column(column)
  1808. if not self._cols_populated:
  1809. return None
  1810. raise NotImplementedError("CompoundSelect constructs don't support "
  1811. "addition of columns to underlying "
  1812. "selectables")
  1813. def _copy_internals(self, clone=_clone, **kw):
  1814. super(CompoundSelect, self)._copy_internals(clone, **kw)
  1815. self._reset_exported()
  1816. self.selects = [clone(s, **kw) for s in self.selects]
  1817. if hasattr(self, '_col_map'):
  1818. del self._col_map
  1819. for attr in (
  1820. '_order_by_clause', '_group_by_clause', '_for_update_arg'):
  1821. if getattr(self, attr) is not None:
  1822. setattr(self, attr, clone(getattr(self, attr), **kw))
  1823. def get_children(self, column_collections=True, **kwargs):
  1824. return (column_collections and list(self.c) or []) \
  1825. + [self._order_by_clause, self._group_by_clause] \
  1826. + list(self.selects)
  1827. def bind(self):
  1828. if self._bind:
  1829. return self._bind
  1830. for s in self.selects:
  1831. e = s.bind
  1832. if e:
  1833. return e
  1834. else:
  1835. return None
  1836. def _set_bind(self, bind):
  1837. self._bind = bind
  1838. bind = property(bind, _set_bind)
  1839. class Select(HasPrefixes, HasSuffixes, GenerativeSelect):
  1840. """Represents a ``SELECT`` statement.
  1841. """
  1842. __visit_name__ = 'select'
  1843. _prefixes = ()
  1844. _suffixes = ()
  1845. _hints = util.immutabledict()
  1846. _statement_hints = ()
  1847. _distinct = False
  1848. _from_cloned = None
  1849. _correlate = ()
  1850. _correlate_except = None
  1851. _memoized_property = SelectBase._memoized_property
  1852. _is_select = True
  1853. def __init__(self,
  1854. columns=None,
  1855. whereclause=None,
  1856. from_obj=None,
  1857. distinct=False,
  1858. having=None,
  1859. correlate=True,
  1860. prefixes=None,
  1861. suffixes=None,
  1862. **kwargs):
  1863. """Construct a new :class:`.Select`.
  1864. Similar functionality is also available via the
  1865. :meth:`.FromClause.select` method on any :class:`.FromClause`.
  1866. All arguments which accept :class:`.ClauseElement` arguments also
  1867. accept string arguments, which will be converted as appropriate into
  1868. either :func:`text()` or :func:`literal_column()` constructs.
  1869. .. seealso::
  1870. :ref:`coretutorial_selecting` - Core Tutorial description of
  1871. :func:`.select`.
  1872. :param columns:
  1873. A list of :class:`.ColumnElement` or :class:`.FromClause`
  1874. objects which will form the columns clause of the resulting
  1875. statement. For those objects that are instances of
  1876. :class:`.FromClause` (typically :class:`.Table` or :class:`.Alias`
  1877. objects), the :attr:`.FromClause.c` collection is extracted
  1878. to form a collection of :class:`.ColumnElement` objects.
  1879. This parameter will also accept :class:`.Text` constructs as
  1880. given, as well as ORM-mapped classes.
  1881. .. note::
  1882. The :paramref:`.select.columns` parameter is not available
  1883. in the method form of :func:`.select`, e.g.
  1884. :meth:`.FromClause.select`.
  1885. .. seealso::
  1886. :meth:`.Select.column`
  1887. :meth:`.Select.with_only_columns`
  1888. :param whereclause:
  1889. A :class:`.ClauseElement` expression which will be used to form the
  1890. ``WHERE`` clause. It is typically preferable to add WHERE
  1891. criterion to an existing :class:`.Select` using method chaining
  1892. with :meth:`.Select.where`.
  1893. .. seealso::
  1894. :meth:`.Select.where`
  1895. :param from_obj:
  1896. A list of :class:`.ClauseElement` objects which will be added to the
  1897. ``FROM`` clause of the resulting statement. This is equivalent
  1898. to calling :meth:`.Select.select_from` using method chaining on
  1899. an existing :class:`.Select` object.
  1900. .. seealso::
  1901. :meth:`.Select.select_from` - full description of explicit
  1902. FROM clause specification.
  1903. :param autocommit:
  1904. Deprecated. Use ``.execution_options(autocommit=<True|False>)``
  1905. to set the autocommit option.
  1906. .. seealso::
  1907. :meth:`.Executable.execution_options`
  1908. :param bind=None:
  1909. an :class:`~.Engine` or :class:`~.Connection` instance
  1910. to which the
  1911. resulting :class:`.Select` object will be bound. The
  1912. :class:`.Select` object will otherwise automatically bind to
  1913. whatever :class:`~.base.Connectable` instances can be located within
  1914. its contained :class:`.ClauseElement` members.
  1915. :param correlate=True:
  1916. indicates that this :class:`.Select` object should have its
  1917. contained :class:`.FromClause` elements "correlated" to an enclosing
  1918. :class:`.Select` object. It is typically preferable to specify
  1919. correlations on an existing :class:`.Select` construct using
  1920. :meth:`.Select.correlate`.
  1921. .. seealso::
  1922. :meth:`.Select.correlate` - full description of correlation.
  1923. :param distinct=False:
  1924. when ``True``, applies a ``DISTINCT`` qualifier to the columns
  1925. clause of the resulting statement.
  1926. The boolean argument may also be a column expression or list
  1927. of column expressions - this is a special calling form which
  1928. is understood by the PostgreSQL dialect to render the
  1929. ``DISTINCT ON (<columns>)`` syntax.
  1930. ``distinct`` is also available on an existing :class:`.Select`
  1931. object via the :meth:`~.Select.distinct` method.
  1932. .. seealso::
  1933. :meth:`.Select.distinct`
  1934. :param for_update=False:
  1935. when ``True``, applies ``FOR UPDATE`` to the end of the
  1936. resulting statement.
  1937. .. deprecated:: 0.9.0 - use
  1938. :meth:`.Select.with_for_update` to specify the
  1939. structure of the ``FOR UPDATE`` clause.
  1940. ``for_update`` accepts various string values interpreted by
  1941. specific backends, including:
  1942. * ``"read"`` - on MySQL, translates to ``LOCK IN SHARE MODE``;
  1943. on PostgreSQL, translates to ``FOR SHARE``.
  1944. * ``"nowait"`` - on PostgreSQL and Oracle, translates to
  1945. ``FOR UPDATE NOWAIT``.
  1946. * ``"read_nowait"`` - on PostgreSQL, translates to
  1947. ``FOR SHARE NOWAIT``.
  1948. .. seealso::
  1949. :meth:`.Select.with_for_update` - improved API for
  1950. specifying the ``FOR UPDATE`` clause.
  1951. :param group_by:
  1952. a list of :class:`.ClauseElement` objects which will comprise the
  1953. ``GROUP BY`` clause of the resulting select. This parameter
  1954. is typically specified more naturally using the
  1955. :meth:`.Select.group_by` method on an existing :class:`.Select`.
  1956. .. seealso::
  1957. :meth:`.Select.group_by`
  1958. :param having:
  1959. a :class:`.ClauseElement` that will comprise the ``HAVING`` clause
  1960. of the resulting select when ``GROUP BY`` is used. This parameter
  1961. is typically specified more naturally using the
  1962. :meth:`.Select.having` method on an existing :class:`.Select`.
  1963. .. seealso::
  1964. :meth:`.Select.having`
  1965. :param limit=None:
  1966. a numerical value which usually renders as a ``LIMIT``
  1967. expression in the resulting select. Backends that don't
  1968. support ``LIMIT`` will attempt to provide similar
  1969. functionality. This parameter is typically specified more naturally
  1970. using the :meth:`.Select.limit` method on an existing
  1971. :class:`.Select`.
  1972. .. seealso::
  1973. :meth:`.Select.limit`
  1974. :param offset=None:
  1975. a numeric value which usually renders as an ``OFFSET``
  1976. expression in the resulting select. Backends that don't
  1977. support ``OFFSET`` will attempt to provide similar
  1978. functionality. This parameter is typically specified more naturally
  1979. using the :meth:`.Select.offset` method on an existing
  1980. :class:`.Select`.
  1981. .. seealso::
  1982. :meth:`.Select.offset`
  1983. :param order_by:
  1984. a scalar or list of :class:`.ClauseElement` objects which will
  1985. comprise the ``ORDER BY`` clause of the resulting select.
  1986. This parameter is typically specified more naturally using the
  1987. :meth:`.Select.order_by` method on an existing :class:`.Select`.
  1988. .. seealso::
  1989. :meth:`.Select.order_by`
  1990. :param use_labels=False:
  1991. when ``True``, the statement will be generated using labels
  1992. for each column in the columns clause, which qualify each
  1993. column with its parent table's (or aliases) name so that name
  1994. conflicts between columns in different tables don't occur.
  1995. The format of the label is <tablename>_<column>. The "c"
  1996. collection of the resulting :class:`.Select` object will use these
  1997. names as well for targeting column members.
  1998. This parameter can also be specified on an existing
  1999. :class:`.Select` object using the :meth:`.Select.apply_labels`
  2000. method.
  2001. .. seealso::
  2002. :meth:`.Select.apply_labels`
  2003. """
  2004. self._auto_correlate = correlate
  2005. if distinct is not False:
  2006. if distinct is True:
  2007. self._distinct = True
  2008. else:
  2009. self._distinct = [
  2010. _literal_as_text(e)
  2011. for e in util.to_list(distinct)
  2012. ]
  2013. if from_obj is not None:
  2014. self._from_obj = util.OrderedSet(
  2015. _interpret_as_from(f)
  2016. for f in util.to_list(from_obj))
  2017. else:
  2018. self._from_obj = util.OrderedSet()
  2019. try:
  2020. cols_present = bool(columns)
  2021. except TypeError:
  2022. raise exc.ArgumentError("columns argument to select() must "
  2023. "be a Python list or other iterable")
  2024. if cols_present:
  2025. self._raw_columns = []
  2026. for c in columns:
  2027. c = _interpret_as_column_or_from(c)
  2028. if isinstance(c, ScalarSelect):
  2029. c = c.self_group(against=operators.comma_op)
  2030. self._raw_columns.append(c)
  2031. else:
  2032. self._raw_columns = []
  2033. if whereclause is not None:
  2034. self._whereclause = _literal_as_text(
  2035. whereclause).self_group(against=operators._asbool)
  2036. else:
  2037. self._whereclause = None
  2038. if having is not None:
  2039. self._having = _literal_as_text(
  2040. having).self_group(against=operators._asbool)
  2041. else:
  2042. self._having = None
  2043. if prefixes:
  2044. self._setup_prefixes(prefixes)
  2045. if suffixes:
  2046. self._setup_suffixes(suffixes)
  2047. GenerativeSelect.__init__(self, **kwargs)
  2048. @property
  2049. def _froms(self):
  2050. # would love to cache this,
  2051. # but there's just enough edge cases, particularly now that
  2052. # declarative encourages construction of SQL expressions
  2053. # without tables present, to just regen this each time.
  2054. froms = []
  2055. seen = set()
  2056. translate = self._from_cloned
  2057. for item in itertools.chain(
  2058. _from_objects(*self._raw_columns),
  2059. _from_objects(self._whereclause)
  2060. if self._whereclause is not None else (),
  2061. self._from_obj
  2062. ):
  2063. if item is self:
  2064. raise exc.InvalidRequestError(
  2065. "select() construct refers to itself as a FROM")
  2066. if translate and item in translate:
  2067. item = translate[item]
  2068. if not seen.intersection(item._cloned_set):
  2069. froms.append(item)
  2070. seen.update(item._cloned_set)
  2071. return froms
  2072. def _get_display_froms(self, explicit_correlate_froms=None,
  2073. implicit_correlate_froms=None):
  2074. """Return the full list of 'from' clauses to be displayed.
  2075. Takes into account a set of existing froms which may be
  2076. rendered in the FROM clause of enclosing selects; this Select
  2077. may want to leave those absent if it is automatically
  2078. correlating.
  2079. """
  2080. froms = self._froms
  2081. toremove = set(itertools.chain(*[
  2082. _expand_cloned(f._hide_froms)
  2083. for f in froms]))
  2084. if toremove:
  2085. # if we're maintaining clones of froms,
  2086. # add the copies out to the toremove list. only include
  2087. # clones that are lexical equivalents.
  2088. if self._from_cloned:
  2089. toremove.update(
  2090. self._from_cloned[f] for f in
  2091. toremove.intersection(self._from_cloned)
  2092. if self._from_cloned[f]._is_lexical_equivalent(f)
  2093. )
  2094. # filter out to FROM clauses not in the list,
  2095. # using a list to maintain ordering
  2096. froms = [f for f in froms if f not in toremove]
  2097. if self._correlate:
  2098. to_correlate = self._correlate
  2099. if to_correlate:
  2100. froms = [
  2101. f for f in froms if f not in
  2102. _cloned_intersection(
  2103. _cloned_intersection(
  2104. froms, explicit_correlate_froms or ()),
  2105. to_correlate
  2106. )
  2107. ]
  2108. if self._correlate_except is not None:
  2109. froms = [
  2110. f for f in froms if f not in
  2111. _cloned_difference(
  2112. _cloned_intersection(
  2113. froms, explicit_correlate_froms or ()),
  2114. self._correlate_except
  2115. )
  2116. ]
  2117. if self._auto_correlate and \
  2118. implicit_correlate_froms and \
  2119. len(froms) > 1:
  2120. froms = [
  2121. f for f in froms if f not in
  2122. _cloned_intersection(froms, implicit_correlate_froms)
  2123. ]
  2124. if not len(froms):
  2125. raise exc.InvalidRequestError("Select statement '%s"
  2126. "' returned no FROM clauses "
  2127. "due to auto-correlation; "
  2128. "specify correlate(<tables>) "
  2129. "to control correlation "
  2130. "manually." % self)
  2131. return froms
  2132. def _scalar_type(self):
  2133. elem = self._raw_columns[0]
  2134. cols = list(elem._select_iterable)
  2135. return cols[0].type
  2136. @property
  2137. def froms(self):
  2138. """Return the displayed list of FromClause elements."""
  2139. return self._get_display_froms()
  2140. def with_statement_hint(self, text, dialect_name='*'):
  2141. """add a statement hint to this :class:`.Select`.
  2142. This method is similar to :meth:`.Select.with_hint` except that
  2143. it does not require an individual table, and instead applies to the
  2144. statement as a whole.
  2145. Hints here are specific to the backend database and may include
  2146. directives such as isolation levels, file directives, fetch directives,
  2147. etc.
  2148. .. versionadded:: 1.0.0
  2149. .. seealso::
  2150. :meth:`.Select.with_hint`
  2151. """
  2152. return self.with_hint(None, text, dialect_name)
  2153. @_generative
  2154. def with_hint(self, selectable, text, dialect_name='*'):
  2155. r"""Add an indexing or other executional context hint for the given
  2156. selectable to this :class:`.Select`.
  2157. The text of the hint is rendered in the appropriate
  2158. location for the database backend in use, relative
  2159. to the given :class:`.Table` or :class:`.Alias` passed as the
  2160. ``selectable`` argument. The dialect implementation
  2161. typically uses Python string substitution syntax
  2162. with the token ``%(name)s`` to render the name of
  2163. the table or alias. E.g. when using Oracle, the
  2164. following::
  2165. select([mytable]).\
  2166. with_hint(mytable, "index(%(name)s ix_mytable)")
  2167. Would render SQL as::
  2168. select /*+ index(mytable ix_mytable) */ ... from mytable
  2169. The ``dialect_name`` option will limit the rendering of a particular
  2170. hint to a particular backend. Such as, to add hints for both Oracle
  2171. and Sybase simultaneously::
  2172. select([mytable]).\
  2173. with_hint(mytable, "index(%(name)s ix_mytable)", 'oracle').\
  2174. with_hint(mytable, "WITH INDEX ix_mytable", 'sybase')
  2175. .. seealso::
  2176. :meth:`.Select.with_statement_hint`
  2177. """
  2178. if selectable is None:
  2179. self._statement_hints += ((dialect_name, text), )
  2180. else:
  2181. self._hints = self._hints.union(
  2182. {(selectable, dialect_name): text})
  2183. @property
  2184. def type(self):
  2185. raise exc.InvalidRequestError("Select objects don't have a type. "
  2186. "Call as_scalar() on this Select "
  2187. "object to return a 'scalar' version "
  2188. "of this Select.")
  2189. @_memoized_property.method
  2190. def locate_all_froms(self):
  2191. """return a Set of all FromClause elements referenced by this Select.
  2192. This set is a superset of that returned by the ``froms`` property,
  2193. which is specifically for those FromClause elements that would
  2194. actually be rendered.
  2195. """
  2196. froms = self._froms
  2197. return froms + list(_from_objects(*froms))
  2198. @property
  2199. def inner_columns(self):
  2200. """an iterator of all ColumnElement expressions which would
  2201. be rendered into the columns clause of the resulting SELECT statement.
  2202. """
  2203. return _select_iterables(self._raw_columns)
  2204. @_memoized_property
  2205. def _label_resolve_dict(self):
  2206. with_cols = dict(
  2207. (c._resolve_label or c._label or c.key, c)
  2208. for c in _select_iterables(self._raw_columns)
  2209. if c._allow_label_resolve)
  2210. only_froms = dict(
  2211. (c.key, c) for c in
  2212. _select_iterables(self.froms) if c._allow_label_resolve)
  2213. only_cols = with_cols.copy()
  2214. for key, value in only_froms.items():
  2215. with_cols.setdefault(key, value)
  2216. return with_cols, only_froms, only_cols
  2217. def is_derived_from(self, fromclause):
  2218. if self in fromclause._cloned_set:
  2219. return True
  2220. for f in self.locate_all_froms():
  2221. if f.is_derived_from(fromclause):
  2222. return True
  2223. return False
  2224. def _copy_internals(self, clone=_clone, **kw):
  2225. super(Select, self)._copy_internals(clone, **kw)
  2226. # Select() object has been cloned and probably adapted by the
  2227. # given clone function. Apply the cloning function to internal
  2228. # objects
  2229. # 1. keep a dictionary of the froms we've cloned, and what
  2230. # they've become. This is consulted later when we derive
  2231. # additional froms from "whereclause" and the columns clause,
  2232. # which may still reference the uncloned parent table.
  2233. # as of 0.7.4 we also put the current version of _froms, which
  2234. # gets cleared on each generation. previously we were "baking"
  2235. # _froms into self._from_obj.
  2236. self._from_cloned = from_cloned = dict(
  2237. (f, clone(f, **kw)) for f in self._from_obj.union(self._froms))
  2238. # 3. update persistent _from_obj with the cloned versions.
  2239. self._from_obj = util.OrderedSet(from_cloned[f] for f in
  2240. self._from_obj)
  2241. # the _correlate collection is done separately, what can happen
  2242. # here is the same item is _correlate as in _from_obj but the
  2243. # _correlate version has an annotation on it - (specifically
  2244. # RelationshipProperty.Comparator._criterion_exists() does
  2245. # this). Also keep _correlate liberally open with its previous
  2246. # contents, as this set is used for matching, not rendering.
  2247. self._correlate = set(clone(f) for f in
  2248. self._correlate).union(self._correlate)
  2249. # 4. clone other things. The difficulty here is that Column
  2250. # objects are not actually cloned, and refer to their original
  2251. # .table, resulting in the wrong "from" parent after a clone
  2252. # operation. Hence _from_cloned and _from_obj supersede what is
  2253. # present here.
  2254. self._raw_columns = [clone(c, **kw) for c in self._raw_columns]
  2255. for attr in '_whereclause', '_having', '_order_by_clause', \
  2256. '_group_by_clause', '_for_update_arg':
  2257. if getattr(self, attr) is not None:
  2258. setattr(self, attr, clone(getattr(self, attr), **kw))
  2259. # erase exported column list, _froms collection,
  2260. # etc.
  2261. self._reset_exported()
  2262. def get_children(self, column_collections=True, **kwargs):
  2263. """return child elements as per the ClauseElement specification."""
  2264. return (column_collections and list(self.columns) or []) + \
  2265. self._raw_columns + list(self._froms) + \
  2266. [x for x in
  2267. (self._whereclause, self._having,
  2268. self._order_by_clause, self._group_by_clause)
  2269. if x is not None]
  2270. @_generative
  2271. def column(self, column):
  2272. """return a new select() construct with the given column expression
  2273. added to its columns clause.
  2274. E.g.::
  2275. my_select = my_select.column(table.c.new_column)
  2276. See the documentation for :meth:`.Select.with_only_columns`
  2277. for guidelines on adding /replacing the columns of a
  2278. :class:`.Select` object.
  2279. """
  2280. self.append_column(column)
  2281. @util.dependencies("sqlalchemy.sql.util")
  2282. def reduce_columns(self, sqlutil, only_synonyms=True):
  2283. """Return a new :func`.select` construct with redundantly
  2284. named, equivalently-valued columns removed from the columns clause.
  2285. "Redundant" here means two columns where one refers to the
  2286. other either based on foreign key, or via a simple equality
  2287. comparison in the WHERE clause of the statement. The primary purpose
  2288. of this method is to automatically construct a select statement
  2289. with all uniquely-named columns, without the need to use
  2290. table-qualified labels as :meth:`.apply_labels` does.
  2291. When columns are omitted based on foreign key, the referred-to
  2292. column is the one that's kept. When columns are omitted based on
  2293. WHERE eqivalence, the first column in the columns clause is the
  2294. one that's kept.
  2295. :param only_synonyms: when True, limit the removal of columns
  2296. to those which have the same name as the equivalent. Otherwise,
  2297. all columns that are equivalent to another are removed.
  2298. .. versionadded:: 0.8
  2299. """
  2300. return self.with_only_columns(
  2301. sqlutil.reduce_columns(
  2302. self.inner_columns,
  2303. only_synonyms=only_synonyms,
  2304. *(self._whereclause, ) + tuple(self._from_obj)
  2305. )
  2306. )
  2307. @_generative
  2308. def with_only_columns(self, columns):
  2309. r"""Return a new :func:`.select` construct with its columns
  2310. clause replaced with the given columns.
  2311. This method is exactly equivalent to as if the original
  2312. :func:`.select` had been called with the given columns
  2313. clause. I.e. a statement::
  2314. s = select([table1.c.a, table1.c.b])
  2315. s = s.with_only_columns([table1.c.b])
  2316. should be exactly equivalent to::
  2317. s = select([table1.c.b])
  2318. This means that FROM clauses which are only derived
  2319. from the column list will be discarded if the new column
  2320. list no longer contains that FROM::
  2321. >>> table1 = table('t1', column('a'), column('b'))
  2322. >>> table2 = table('t2', column('a'), column('b'))
  2323. >>> s1 = select([table1.c.a, table2.c.b])
  2324. >>> print s1
  2325. SELECT t1.a, t2.b FROM t1, t2
  2326. >>> s2 = s1.with_only_columns([table2.c.b])
  2327. >>> print s2
  2328. SELECT t2.b FROM t1
  2329. The preferred way to maintain a specific FROM clause
  2330. in the construct, assuming it won't be represented anywhere
  2331. else (i.e. not in the WHERE clause, etc.) is to set it using
  2332. :meth:`.Select.select_from`::
  2333. >>> s1 = select([table1.c.a, table2.c.b]).\
  2334. ... select_from(table1.join(table2,
  2335. ... table1.c.a==table2.c.a))
  2336. >>> s2 = s1.with_only_columns([table2.c.b])
  2337. >>> print s2
  2338. SELECT t2.b FROM t1 JOIN t2 ON t1.a=t2.a
  2339. Care should also be taken to use the correct
  2340. set of column objects passed to :meth:`.Select.with_only_columns`.
  2341. Since the method is essentially equivalent to calling the
  2342. :func:`.select` construct in the first place with the given
  2343. columns, the columns passed to :meth:`.Select.with_only_columns`
  2344. should usually be a subset of those which were passed
  2345. to the :func:`.select` construct, not those which are available
  2346. from the ``.c`` collection of that :func:`.select`. That
  2347. is::
  2348. s = select([table1.c.a, table1.c.b]).select_from(table1)
  2349. s = s.with_only_columns([table1.c.b])
  2350. and **not**::
  2351. # usually incorrect
  2352. s = s.with_only_columns([s.c.b])
  2353. The latter would produce the SQL::
  2354. SELECT b
  2355. FROM (SELECT t1.a AS a, t1.b AS b
  2356. FROM t1), t1
  2357. Since the :func:`.select` construct is essentially being
  2358. asked to select both from ``table1`` as well as itself.
  2359. """
  2360. self._reset_exported()
  2361. rc = []
  2362. for c in columns:
  2363. c = _interpret_as_column_or_from(c)
  2364. if isinstance(c, ScalarSelect):
  2365. c = c.self_group(against=operators.comma_op)
  2366. rc.append(c)
  2367. self._raw_columns = rc
  2368. @_generative
  2369. def where(self, whereclause):
  2370. """return a new select() construct with the given expression added to
  2371. its WHERE clause, joined to the existing clause via AND, if any.
  2372. """
  2373. self.append_whereclause(whereclause)
  2374. @_generative
  2375. def having(self, having):
  2376. """return a new select() construct with the given expression added to
  2377. its HAVING clause, joined to the existing clause via AND, if any.
  2378. """
  2379. self.append_having(having)
  2380. @_generative
  2381. def distinct(self, *expr):
  2382. r"""Return a new select() construct which will apply DISTINCT to its
  2383. columns clause.
  2384. :param \*expr: optional column expressions. When present,
  2385. the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>>)``
  2386. construct.
  2387. """
  2388. if expr:
  2389. expr = [_literal_as_label_reference(e) for e in expr]
  2390. if isinstance(self._distinct, list):
  2391. self._distinct = self._distinct + expr
  2392. else:
  2393. self._distinct = expr
  2394. else:
  2395. self._distinct = True
  2396. @_generative
  2397. def select_from(self, fromclause):
  2398. r"""return a new :func:`.select` construct with the
  2399. given FROM expression
  2400. merged into its list of FROM objects.
  2401. E.g.::
  2402. table1 = table('t1', column('a'))
  2403. table2 = table('t2', column('b'))
  2404. s = select([table1.c.a]).\
  2405. select_from(
  2406. table1.join(table2, table1.c.a==table2.c.b)
  2407. )
  2408. The "from" list is a unique set on the identity of each element,
  2409. so adding an already present :class:`.Table` or other selectable
  2410. will have no effect. Passing a :class:`.Join` that refers
  2411. to an already present :class:`.Table` or other selectable will have
  2412. the effect of concealing the presence of that selectable as
  2413. an individual element in the rendered FROM list, instead
  2414. rendering it into a JOIN clause.
  2415. While the typical purpose of :meth:`.Select.select_from` is to
  2416. replace the default, derived FROM clause with a join, it can
  2417. also be called with individual table elements, multiple times
  2418. if desired, in the case that the FROM clause cannot be fully
  2419. derived from the columns clause::
  2420. select([func.count('*')]).select_from(table1)
  2421. """
  2422. self.append_from(fromclause)
  2423. @_generative
  2424. def correlate(self, *fromclauses):
  2425. r"""return a new :class:`.Select` which will correlate the given FROM
  2426. clauses to that of an enclosing :class:`.Select`.
  2427. Calling this method turns off the :class:`.Select` object's
  2428. default behavior of "auto-correlation". Normally, FROM elements
  2429. which appear in a :class:`.Select` that encloses this one via
  2430. its :term:`WHERE clause`, ORDER BY, HAVING or
  2431. :term:`columns clause` will be omitted from this :class:`.Select`
  2432. object's :term:`FROM clause`.
  2433. Setting an explicit correlation collection using the
  2434. :meth:`.Select.correlate` method provides a fixed list of FROM objects
  2435. that can potentially take place in this process.
  2436. When :meth:`.Select.correlate` is used to apply specific FROM clauses
  2437. for correlation, the FROM elements become candidates for
  2438. correlation regardless of how deeply nested this :class:`.Select`
  2439. object is, relative to an enclosing :class:`.Select` which refers to
  2440. the same FROM object. This is in contrast to the behavior of
  2441. "auto-correlation" which only correlates to an immediate enclosing
  2442. :class:`.Select`. Multi-level correlation ensures that the link
  2443. between enclosed and enclosing :class:`.Select` is always via
  2444. at least one WHERE/ORDER BY/HAVING/columns clause in order for
  2445. correlation to take place.
  2446. If ``None`` is passed, the :class:`.Select` object will correlate
  2447. none of its FROM entries, and all will render unconditionally
  2448. in the local FROM clause.
  2449. :param \*fromclauses: a list of one or more :class:`.FromClause`
  2450. constructs, or other compatible constructs (i.e. ORM-mapped
  2451. classes) to become part of the correlate collection.
  2452. .. versionchanged:: 0.8.0 ORM-mapped classes are accepted by
  2453. :meth:`.Select.correlate`.
  2454. .. versionchanged:: 0.8.0 The :meth:`.Select.correlate` method no
  2455. longer unconditionally removes entries from the FROM clause;
  2456. instead, the candidate FROM entries must also be matched by a FROM
  2457. entry located in an enclosing :class:`.Select`, which ultimately
  2458. encloses this one as present in the WHERE clause, ORDER BY clause,
  2459. HAVING clause, or columns clause of an enclosing :meth:`.Select`.
  2460. .. versionchanged:: 0.8.2 explicit correlation takes place
  2461. via any level of nesting of :class:`.Select` objects; in previous
  2462. 0.8 versions, correlation would only occur relative to the
  2463. immediate enclosing :class:`.Select` construct.
  2464. .. seealso::
  2465. :meth:`.Select.correlate_except`
  2466. :ref:`correlated_subqueries`
  2467. """
  2468. self._auto_correlate = False
  2469. if fromclauses and fromclauses[0] is None:
  2470. self._correlate = ()
  2471. else:
  2472. self._correlate = set(self._correlate).union(
  2473. _interpret_as_from(f) for f in fromclauses)
  2474. @_generative
  2475. def correlate_except(self, *fromclauses):
  2476. r"""return a new :class:`.Select` which will omit the given FROM
  2477. clauses from the auto-correlation process.
  2478. Calling :meth:`.Select.correlate_except` turns off the
  2479. :class:`.Select` object's default behavior of
  2480. "auto-correlation" for the given FROM elements. An element
  2481. specified here will unconditionally appear in the FROM list, while
  2482. all other FROM elements remain subject to normal auto-correlation
  2483. behaviors.
  2484. .. versionchanged:: 0.8.2 The :meth:`.Select.correlate_except`
  2485. method was improved to fully prevent FROM clauses specified here
  2486. from being omitted from the immediate FROM clause of this
  2487. :class:`.Select`.
  2488. If ``None`` is passed, the :class:`.Select` object will correlate
  2489. all of its FROM entries.
  2490. .. versionchanged:: 0.8.2 calling ``correlate_except(None)`` will
  2491. correctly auto-correlate all FROM clauses.
  2492. :param \*fromclauses: a list of one or more :class:`.FromClause`
  2493. constructs, or other compatible constructs (i.e. ORM-mapped
  2494. classes) to become part of the correlate-exception collection.
  2495. .. seealso::
  2496. :meth:`.Select.correlate`
  2497. :ref:`correlated_subqueries`
  2498. """
  2499. self._auto_correlate = False
  2500. if fromclauses and fromclauses[0] is None:
  2501. self._correlate_except = ()
  2502. else:
  2503. self._correlate_except = set(self._correlate_except or ()).union(
  2504. _interpret_as_from(f) for f in fromclauses)
  2505. def append_correlation(self, fromclause):
  2506. """append the given correlation expression to this select()
  2507. construct.
  2508. This is an **in-place** mutation method; the
  2509. :meth:`~.Select.correlate` method is preferred, as it provides
  2510. standard :term:`method chaining`.
  2511. """
  2512. self._auto_correlate = False
  2513. self._correlate = set(self._correlate).union(
  2514. _interpret_as_from(f) for f in fromclause)
  2515. def append_column(self, column):
  2516. """append the given column expression to the columns clause of this
  2517. select() construct.
  2518. E.g.::
  2519. my_select.append_column(some_table.c.new_column)
  2520. This is an **in-place** mutation method; the
  2521. :meth:`~.Select.column` method is preferred, as it provides standard
  2522. :term:`method chaining`.
  2523. See the documentation for :meth:`.Select.with_only_columns`
  2524. for guidelines on adding /replacing the columns of a
  2525. :class:`.Select` object.
  2526. """
  2527. self._reset_exported()
  2528. column = _interpret_as_column_or_from(column)
  2529. if isinstance(column, ScalarSelect):
  2530. column = column.self_group(against=operators.comma_op)
  2531. self._raw_columns = self._raw_columns + [column]
  2532. def append_prefix(self, clause):
  2533. """append the given columns clause prefix expression to this select()
  2534. construct.
  2535. This is an **in-place** mutation method; the
  2536. :meth:`~.Select.prefix_with` method is preferred, as it provides
  2537. standard :term:`method chaining`.
  2538. """
  2539. clause = _literal_as_text(clause)
  2540. self._prefixes = self._prefixes + (clause,)
  2541. def append_whereclause(self, whereclause):
  2542. """append the given expression to this select() construct's WHERE
  2543. criterion.
  2544. The expression will be joined to existing WHERE criterion via AND.
  2545. This is an **in-place** mutation method; the
  2546. :meth:`~.Select.where` method is preferred, as it provides standard
  2547. :term:`method chaining`.
  2548. """
  2549. self._reset_exported()
  2550. self._whereclause = and_(
  2551. True_._ifnone(self._whereclause), whereclause)
  2552. def append_having(self, having):
  2553. """append the given expression to this select() construct's HAVING
  2554. criterion.
  2555. The expression will be joined to existing HAVING criterion via AND.
  2556. This is an **in-place** mutation method; the
  2557. :meth:`~.Select.having` method is preferred, as it provides standard
  2558. :term:`method chaining`.
  2559. """
  2560. self._reset_exported()
  2561. self._having = and_(True_._ifnone(self._having), having)
  2562. def append_from(self, fromclause):
  2563. """append the given FromClause expression to this select() construct's
  2564. FROM clause.
  2565. This is an **in-place** mutation method; the
  2566. :meth:`~.Select.select_from` method is preferred, as it provides
  2567. standard :term:`method chaining`.
  2568. """
  2569. self._reset_exported()
  2570. fromclause = _interpret_as_from(fromclause)
  2571. self._from_obj = self._from_obj.union([fromclause])
  2572. @_memoized_property
  2573. def _columns_plus_names(self):
  2574. if self.use_labels:
  2575. names = set()
  2576. def name_for_col(c):
  2577. if c._label is None or not c._render_label_in_columns_clause:
  2578. return (None, c)
  2579. name = c._label
  2580. if name in names:
  2581. name = c.anon_label
  2582. else:
  2583. names.add(name)
  2584. return name, c
  2585. return [
  2586. name_for_col(c)
  2587. for c in util.unique_list(
  2588. _select_iterables(self._raw_columns))
  2589. ]
  2590. else:
  2591. return [
  2592. (None, c)
  2593. for c in util.unique_list(
  2594. _select_iterables(self._raw_columns))
  2595. ]
  2596. def _populate_column_collection(self):
  2597. for name, c in self._columns_plus_names:
  2598. if not hasattr(c, '_make_proxy'):
  2599. continue
  2600. if name is None:
  2601. key = None
  2602. elif self.use_labels:
  2603. key = c._key_label
  2604. if key is not None and key in self.c:
  2605. key = c.anon_label
  2606. else:
  2607. key = None
  2608. c._make_proxy(self, key=key,
  2609. name=name,
  2610. name_is_truncatable=True)
  2611. def _refresh_for_new_column(self, column):
  2612. for fromclause in self._froms:
  2613. col = fromclause._refresh_for_new_column(column)
  2614. if col is not None:
  2615. if col in self.inner_columns and self._cols_populated:
  2616. our_label = col._key_label if self.use_labels else col.key
  2617. if our_label not in self.c:
  2618. return col._make_proxy(
  2619. self,
  2620. name=col._label if self.use_labels else None,
  2621. key=col._key_label if self.use_labels else None,
  2622. name_is_truncatable=True)
  2623. return None
  2624. return None
  2625. def _needs_parens_for_grouping(self):
  2626. return (
  2627. self._limit_clause is not None or
  2628. self._offset_clause is not None or
  2629. bool(self._order_by_clause.clauses)
  2630. )
  2631. def self_group(self, against=None):
  2632. """return a 'grouping' construct as per the ClauseElement
  2633. specification.
  2634. This produces an element that can be embedded in an expression. Note
  2635. that this method is called automatically as needed when constructing
  2636. expressions and should not require explicit use.
  2637. """
  2638. if isinstance(against, CompoundSelect) and \
  2639. not self._needs_parens_for_grouping():
  2640. return self
  2641. return FromGrouping(self)
  2642. def union(self, other, **kwargs):
  2643. """return a SQL UNION of this select() construct against the given
  2644. selectable."""
  2645. return CompoundSelect._create_union(self, other, **kwargs)
  2646. def union_all(self, other, **kwargs):
  2647. """return a SQL UNION ALL of this select() construct against the given
  2648. selectable.
  2649. """
  2650. return CompoundSelect._create_union_all(self, other, **kwargs)
  2651. def except_(self, other, **kwargs):
  2652. """return a SQL EXCEPT of this select() construct against the given
  2653. selectable."""
  2654. return CompoundSelect._create_except(self, other, **kwargs)
  2655. def except_all(self, other, **kwargs):
  2656. """return a SQL EXCEPT ALL of this select() construct against the
  2657. given selectable.
  2658. """
  2659. return CompoundSelect._create_except_all(self, other, **kwargs)
  2660. def intersect(self, other, **kwargs):
  2661. """return a SQL INTERSECT of this select() construct against the given
  2662. selectable.
  2663. """
  2664. return CompoundSelect._create_intersect(self, other, **kwargs)
  2665. def intersect_all(self, other, **kwargs):
  2666. """return a SQL INTERSECT ALL of this select() construct against the
  2667. given selectable.
  2668. """
  2669. return CompoundSelect._create_intersect_all(self, other, **kwargs)
  2670. def bind(self):
  2671. if self._bind:
  2672. return self._bind
  2673. froms = self._froms
  2674. if not froms:
  2675. for c in self._raw_columns:
  2676. e = c.bind
  2677. if e:
  2678. self._bind = e
  2679. return e
  2680. else:
  2681. e = list(froms)[0].bind
  2682. if e:
  2683. self._bind = e
  2684. return e
  2685. return None
  2686. def _set_bind(self, bind):
  2687. self._bind = bind
  2688. bind = property(bind, _set_bind)
  2689. class ScalarSelect(Generative, Grouping):
  2690. _from_objects = []
  2691. _is_from_container = True
  2692. def __init__(self, element):
  2693. self.element = element
  2694. self.type = element._scalar_type()
  2695. @property
  2696. def columns(self):
  2697. raise exc.InvalidRequestError('Scalar Select expression has no '
  2698. 'columns; use this object directly '
  2699. 'within a column-level expression.')
  2700. c = columns
  2701. @_generative
  2702. def where(self, crit):
  2703. """Apply a WHERE clause to the SELECT statement referred to
  2704. by this :class:`.ScalarSelect`.
  2705. """
  2706. self.element = self.element.where(crit)
  2707. def self_group(self, **kwargs):
  2708. return self
  2709. class Exists(UnaryExpression):
  2710. """Represent an ``EXISTS`` clause.
  2711. """
  2712. __visit_name__ = UnaryExpression.__visit_name__
  2713. _from_objects = []
  2714. def __init__(self, *args, **kwargs):
  2715. """Construct a new :class:`.Exists` against an existing
  2716. :class:`.Select` object.
  2717. Calling styles are of the following forms::
  2718. # use on an existing select()
  2719. s = select([table.c.col1]).where(table.c.col2==5)
  2720. s = exists(s)
  2721. # construct a select() at once
  2722. exists(['*'], **select_arguments).where(criterion)
  2723. # columns argument is optional, generates "EXISTS (SELECT *)"
  2724. # by default.
  2725. exists().where(table.c.col2==5)
  2726. """
  2727. if args and isinstance(args[0], (SelectBase, ScalarSelect)):
  2728. s = args[0]
  2729. else:
  2730. if not args:
  2731. args = ([literal_column('*')],)
  2732. s = Select(*args, **kwargs).as_scalar().self_group()
  2733. UnaryExpression.__init__(self, s, operator=operators.exists,
  2734. type_=type_api.BOOLEANTYPE,
  2735. wraps_column_expression=True)
  2736. def select(self, whereclause=None, **params):
  2737. return Select([self], whereclause, **params)
  2738. def correlate(self, *fromclause):
  2739. e = self._clone()
  2740. e.element = self.element.correlate(*fromclause).self_group()
  2741. return e
  2742. def correlate_except(self, *fromclause):
  2743. e = self._clone()
  2744. e.element = self.element.correlate_except(*fromclause).self_group()
  2745. return e
  2746. def select_from(self, clause):
  2747. """return a new :class:`.Exists` construct, applying the given
  2748. expression to the :meth:`.Select.select_from` method of the select
  2749. statement contained.
  2750. """
  2751. e = self._clone()
  2752. e.element = self.element.select_from(clause).self_group()
  2753. return e
  2754. def where(self, clause):
  2755. """return a new exists() construct with the given expression added to
  2756. its WHERE clause, joined to the existing clause via AND, if any.
  2757. """
  2758. e = self._clone()
  2759. e.element = self.element.where(clause).self_group()
  2760. return e
  2761. class TextAsFrom(SelectBase):
  2762. """Wrap a :class:`.TextClause` construct within a :class:`.SelectBase`
  2763. interface.
  2764. This allows the :class:`.TextClause` object to gain a ``.c`` collection
  2765. and other FROM-like capabilities such as :meth:`.FromClause.alias`,
  2766. :meth:`.SelectBase.cte`, etc.
  2767. The :class:`.TextAsFrom` construct is produced via the
  2768. :meth:`.TextClause.columns` method - see that method for details.
  2769. .. versionadded:: 0.9.0
  2770. .. seealso::
  2771. :func:`.text`
  2772. :meth:`.TextClause.columns`
  2773. """
  2774. __visit_name__ = "text_as_from"
  2775. _textual = True
  2776. def __init__(self, text, columns, positional=False):
  2777. self.element = text
  2778. self.column_args = columns
  2779. self.positional = positional
  2780. @property
  2781. def _bind(self):
  2782. return self.element._bind
  2783. @_generative
  2784. def bindparams(self, *binds, **bind_as_values):
  2785. self.element = self.element.bindparams(*binds, **bind_as_values)
  2786. def _populate_column_collection(self):
  2787. for c in self.column_args:
  2788. c._make_proxy(self)
  2789. def _copy_internals(self, clone=_clone, **kw):
  2790. self._reset_exported()
  2791. self.element = clone(self.element, **kw)
  2792. def _scalar_type(self):
  2793. return self.column_args[0].type
  2794. class AnnotatedFromClause(Annotated):
  2795. def __init__(self, element, values):
  2796. # force FromClause to generate their internal
  2797. # collections into __dict__
  2798. element.c
  2799. Annotated.__init__(self, element, values)