elements.py 169 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447
  1. # sql/elements.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. """Core SQL expression elements, including :class:`_expression.ClauseElement`,
  9. :class:`_expression.ColumnElement`, and derived classes.
  10. """
  11. from __future__ import annotations
  12. from decimal import Decimal
  13. from enum import IntEnum
  14. import itertools
  15. import operator
  16. import re
  17. import typing
  18. from typing import AbstractSet
  19. from typing import Any
  20. from typing import Callable
  21. from typing import cast
  22. from typing import Dict
  23. from typing import FrozenSet
  24. from typing import Generic
  25. from typing import Iterable
  26. from typing import Iterator
  27. from typing import List
  28. from typing import Mapping
  29. from typing import Optional
  30. from typing import overload
  31. from typing import Sequence
  32. from typing import Set
  33. from typing import Tuple as typing_Tuple
  34. from typing import Type
  35. from typing import TYPE_CHECKING
  36. from typing import TypeVar
  37. from typing import Union
  38. from . import coercions
  39. from . import operators
  40. from . import roles
  41. from . import traversals
  42. from . import type_api
  43. from ._typing import has_schema_attr
  44. from ._typing import is_named_from_clause
  45. from ._typing import is_quoted_name
  46. from ._typing import is_tuple_type
  47. from .annotation import Annotated
  48. from .annotation import SupportsWrappingAnnotations
  49. from .base import _clone
  50. from .base import _expand_cloned
  51. from .base import _generative
  52. from .base import _NoArg
  53. from .base import Executable
  54. from .base import Generative
  55. from .base import HasMemoized
  56. from .base import Immutable
  57. from .base import NO_ARG
  58. from .base import SingletonConstant
  59. from .cache_key import MemoizedHasCacheKey
  60. from .cache_key import NO_CACHE
  61. from .coercions import _document_text_coercion # noqa
  62. from .operators import ColumnOperators
  63. from .traversals import HasCopyInternals
  64. from .visitors import cloned_traverse
  65. from .visitors import ExternallyTraversible
  66. from .visitors import InternalTraversal
  67. from .visitors import traverse
  68. from .visitors import Visitable
  69. from .. import exc
  70. from .. import inspection
  71. from .. import util
  72. from ..util import HasMemoized_ro_memoized_attribute
  73. from ..util import TypingOnly
  74. from ..util.typing import Literal
  75. from ..util.typing import Self
  76. if typing.TYPE_CHECKING:
  77. from ._typing import _ByArgument
  78. from ._typing import _ColumnExpressionArgument
  79. from ._typing import _ColumnExpressionOrStrLabelArgument
  80. from ._typing import _InfoType
  81. from ._typing import _PropagateAttrsType
  82. from ._typing import _TypeEngineArgument
  83. from .cache_key import _CacheKeyTraversalType
  84. from .cache_key import CacheKey
  85. from .compiler import Compiled
  86. from .compiler import SQLCompiler
  87. from .functions import FunctionElement
  88. from .operators import OperatorType
  89. from .schema import Column
  90. from .schema import DefaultGenerator
  91. from .schema import FetchedValue
  92. from .schema import ForeignKey
  93. from .selectable import _SelectIterable
  94. from .selectable import FromClause
  95. from .selectable import NamedFromClause
  96. from .selectable import TextualSelect
  97. from .sqltypes import TupleType
  98. from .type_api import TypeEngine
  99. from .visitors import _CloneCallableType
  100. from .visitors import _TraverseInternalsType
  101. from ..engine import Connection
  102. from ..engine import Dialect
  103. from ..engine import Engine
  104. from ..engine.interfaces import _CoreMultiExecuteParams
  105. from ..engine.interfaces import CacheStats
  106. from ..engine.interfaces import CompiledCacheType
  107. from ..engine.interfaces import CoreExecuteOptionsParameter
  108. from ..engine.interfaces import SchemaTranslateMapType
  109. from ..engine.result import Result
  110. _NUMERIC = Union[float, Decimal]
  111. _NUMBER = Union[float, int, Decimal]
  112. _T = TypeVar("_T", bound="Any")
  113. _T_co = TypeVar("_T_co", bound=Any, covariant=True)
  114. _OPT = TypeVar("_OPT", bound="Any")
  115. _NT = TypeVar("_NT", bound="_NUMERIC")
  116. _NMT = TypeVar("_NMT", bound="_NUMBER")
  117. @overload
  118. def literal(
  119. value: Any,
  120. type_: _TypeEngineArgument[_T],
  121. literal_execute: bool = False,
  122. ) -> BindParameter[_T]:
  123. ...
  124. @overload
  125. def literal(
  126. value: _T,
  127. type_: None = None,
  128. literal_execute: bool = False,
  129. ) -> BindParameter[_T]:
  130. ...
  131. @overload
  132. def literal(
  133. value: Any,
  134. type_: Optional[_TypeEngineArgument[Any]] = None,
  135. literal_execute: bool = False,
  136. ) -> BindParameter[Any]:
  137. ...
  138. def literal(
  139. value: Any,
  140. type_: Optional[_TypeEngineArgument[Any]] = None,
  141. literal_execute: bool = False,
  142. ) -> BindParameter[Any]:
  143. r"""Return a literal clause, bound to a bind parameter.
  144. Literal clauses are created automatically when non-
  145. :class:`_expression.ClauseElement` objects (such as strings, ints, dates,
  146. etc.) are
  147. used in a comparison operation with a :class:`_expression.ColumnElement`
  148. subclass,
  149. such as a :class:`~sqlalchemy.schema.Column` object. Use this function
  150. to force the generation of a literal clause, which will be created as a
  151. :class:`BindParameter` with a bound value.
  152. :param value: the value to be bound. Can be any Python object supported by
  153. the underlying DB-API, or is translatable via the given type argument.
  154. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which will
  155. provide bind-parameter translation for this literal.
  156. :param literal_execute: optional bool, when True, the SQL engine will
  157. attempt to render the bound value directly in the SQL statement at
  158. execution time rather than providing as a parameter value.
  159. .. versionadded:: 2.0
  160. """
  161. return coercions.expect(
  162. roles.LiteralValueRole,
  163. value,
  164. type_=type_,
  165. literal_execute=literal_execute,
  166. )
  167. def literal_column(
  168. text: str, type_: Optional[_TypeEngineArgument[_T]] = None
  169. ) -> ColumnClause[_T]:
  170. r"""Produce a :class:`.ColumnClause` object that has the
  171. :paramref:`_expression.column.is_literal` flag set to True.
  172. :func:`_expression.literal_column` is similar to
  173. :func:`_expression.column`, except that
  174. it is more often used as a "standalone" column expression that renders
  175. exactly as stated; while :func:`_expression.column`
  176. stores a string name that
  177. will be assumed to be part of a table and may be quoted as such,
  178. :func:`_expression.literal_column` can be that,
  179. or any other arbitrary column-oriented
  180. expression.
  181. :param text: the text of the expression; can be any SQL expression.
  182. Quoting rules will not be applied. To specify a column-name expression
  183. which should be subject to quoting rules, use the :func:`column`
  184. function.
  185. :param type\_: an optional :class:`~sqlalchemy.types.TypeEngine`
  186. object which will
  187. provide result-set translation and additional expression semantics for
  188. this column. If left as ``None`` the type will be :class:`.NullType`.
  189. .. seealso::
  190. :func:`_expression.column`
  191. :func:`_expression.text`
  192. :ref:`tutorial_select_arbitrary_text`
  193. """
  194. return ColumnClause(text, type_=type_, is_literal=True)
  195. class CompilerElement(Visitable):
  196. """base class for SQL elements that can be compiled to produce a
  197. SQL string.
  198. .. versionadded:: 2.0
  199. """
  200. __slots__ = ()
  201. __visit_name__ = "compiler_element"
  202. supports_execution = False
  203. stringify_dialect = "default"
  204. @util.preload_module("sqlalchemy.engine.default")
  205. @util.preload_module("sqlalchemy.engine.url")
  206. def compile(
  207. self,
  208. bind: Optional[Union[Engine, Connection]] = None,
  209. dialect: Optional[Dialect] = None,
  210. **kw: Any,
  211. ) -> Compiled:
  212. """Compile this SQL expression.
  213. The return value is a :class:`~.Compiled` object.
  214. Calling ``str()`` or ``unicode()`` on the returned value will yield a
  215. string representation of the result. The
  216. :class:`~.Compiled` object also can return a
  217. dictionary of bind parameter names and values
  218. using the ``params`` accessor.
  219. :param bind: An :class:`.Connection` or :class:`.Engine` which
  220. can provide a :class:`.Dialect` in order to generate a
  221. :class:`.Compiled` object. If the ``bind`` and
  222. ``dialect`` parameters are both omitted, a default SQL compiler
  223. is used.
  224. :param column_keys: Used for INSERT and UPDATE statements, a list of
  225. column names which should be present in the VALUES clause of the
  226. compiled statement. If ``None``, all columns from the target table
  227. object are rendered.
  228. :param dialect: A :class:`.Dialect` instance which can generate
  229. a :class:`.Compiled` object. This argument takes precedence over
  230. the ``bind`` argument.
  231. :param compile_kwargs: optional dictionary of additional parameters
  232. that will be passed through to the compiler within all "visit"
  233. methods. This allows any custom flag to be passed through to
  234. a custom compilation construct, for example. It is also used
  235. for the case of passing the ``literal_binds`` flag through::
  236. from sqlalchemy.sql import table, column, select
  237. t = table('t', column('x'))
  238. s = select(t).where(t.c.x == 5)
  239. print(s.compile(compile_kwargs={"literal_binds": True}))
  240. .. seealso::
  241. :ref:`faq_sql_expression_string`
  242. """
  243. if dialect is None:
  244. if bind:
  245. dialect = bind.dialect
  246. elif self.stringify_dialect == "default":
  247. default = util.preloaded.engine_default
  248. dialect = default.StrCompileDialect()
  249. else:
  250. url = util.preloaded.engine_url
  251. dialect = url.URL.create(
  252. self.stringify_dialect
  253. ).get_dialect()()
  254. return self._compiler(dialect, **kw)
  255. def _compiler(self, dialect: Dialect, **kw: Any) -> Compiled:
  256. """Return a compiler appropriate for this ClauseElement, given a
  257. Dialect."""
  258. if TYPE_CHECKING:
  259. assert isinstance(self, ClauseElement)
  260. return dialect.statement_compiler(dialect, self, **kw)
  261. def __str__(self) -> str:
  262. return str(self.compile())
  263. @inspection._self_inspects
  264. class ClauseElement(
  265. SupportsWrappingAnnotations,
  266. MemoizedHasCacheKey,
  267. HasCopyInternals,
  268. ExternallyTraversible,
  269. CompilerElement,
  270. ):
  271. """Base class for elements of a programmatically constructed SQL
  272. expression.
  273. """
  274. __visit_name__ = "clause"
  275. if TYPE_CHECKING:
  276. @util.memoized_property
  277. def _propagate_attrs(self) -> _PropagateAttrsType:
  278. """like annotations, however these propagate outwards liberally
  279. as SQL constructs are built, and are set up at construction time.
  280. """
  281. ...
  282. else:
  283. _propagate_attrs = util.EMPTY_DICT
  284. @util.ro_memoized_property
  285. def description(self) -> Optional[str]:
  286. return None
  287. _is_clone_of: Optional[Self] = None
  288. is_clause_element = True
  289. is_selectable = False
  290. is_dml = False
  291. _is_column_element = False
  292. _is_keyed_column_element = False
  293. _is_table = False
  294. _gen_static_annotations_cache_key = False
  295. _is_textual = False
  296. _is_from_clause = False
  297. _is_returns_rows = False
  298. _is_text_clause = False
  299. _is_from_container = False
  300. _is_select_container = False
  301. _is_select_base = False
  302. _is_select_statement = False
  303. _is_bind_parameter = False
  304. _is_clause_list = False
  305. _is_lambda_element = False
  306. _is_singleton_constant = False
  307. _is_immutable = False
  308. _is_star = False
  309. @property
  310. def _order_by_label_element(self) -> Optional[Label[Any]]:
  311. return None
  312. _cache_key_traversal: _CacheKeyTraversalType = None
  313. negation_clause: ColumnElement[bool]
  314. if typing.TYPE_CHECKING:
  315. def get_children(
  316. self, *, omit_attrs: typing_Tuple[str, ...] = ..., **kw: Any
  317. ) -> Iterable[ClauseElement]:
  318. ...
  319. @util.ro_non_memoized_property
  320. def _from_objects(self) -> List[FromClause]:
  321. return []
  322. def _set_propagate_attrs(self, values: Mapping[str, Any]) -> Self:
  323. # usually, self._propagate_attrs is empty here. one case where it's
  324. # not is a subquery against ORM select, that is then pulled as a
  325. # property of an aliased class. should all be good
  326. # assert not self._propagate_attrs
  327. self._propagate_attrs = util.immutabledict(values)
  328. return self
  329. def _clone(self, **kw: Any) -> Self:
  330. """Create a shallow copy of this ClauseElement.
  331. This method may be used by a generative API. Its also used as
  332. part of the "deep" copy afforded by a traversal that combines
  333. the _copy_internals() method.
  334. """
  335. skip = self._memoized_keys
  336. c = self.__class__.__new__(self.__class__)
  337. if skip:
  338. # ensure this iteration remains atomic
  339. c.__dict__ = {
  340. k: v for k, v in self.__dict__.copy().items() if k not in skip
  341. }
  342. else:
  343. c.__dict__ = self.__dict__.copy()
  344. # this is a marker that helps to "equate" clauses to each other
  345. # when a Select returns its list of FROM clauses. the cloning
  346. # process leaves around a lot of remnants of the previous clause
  347. # typically in the form of column expressions still attached to the
  348. # old table.
  349. cc = self._is_clone_of
  350. c._is_clone_of = cc if cc is not None else self
  351. return c
  352. def _negate_in_binary(self, negated_op, original_op):
  353. """a hook to allow the right side of a binary expression to respond
  354. to a negation of the binary expression.
  355. Used for the special case of expanding bind parameter with IN.
  356. """
  357. return self
  358. def _with_binary_element_type(self, type_):
  359. """in the context of binary expression, convert the type of this
  360. object to the one given.
  361. applies only to :class:`_expression.ColumnElement` classes.
  362. """
  363. return self
  364. @property
  365. def _constructor(self):
  366. """return the 'constructor' for this ClauseElement.
  367. This is for the purposes for creating a new object of
  368. this type. Usually, its just the element's __class__.
  369. However, the "Annotated" version of the object overrides
  370. to return the class of its proxied element.
  371. """
  372. return self.__class__
  373. @HasMemoized.memoized_attribute
  374. def _cloned_set(self):
  375. """Return the set consisting all cloned ancestors of this
  376. ClauseElement.
  377. Includes this ClauseElement. This accessor tends to be used for
  378. FromClause objects to identify 'equivalent' FROM clauses, regardless
  379. of transformative operations.
  380. """
  381. s = util.column_set()
  382. f: Optional[ClauseElement] = self
  383. # note this creates a cycle, asserted in test_memusage. however,
  384. # turning this into a plain @property adds tends of thousands of method
  385. # calls to Core / ORM performance tests, so the small overhead
  386. # introduced by the relatively small amount of short term cycles
  387. # produced here is preferable
  388. while f is not None:
  389. s.add(f)
  390. f = f._is_clone_of
  391. return s
  392. def _de_clone(self):
  393. while self._is_clone_of is not None:
  394. self = self._is_clone_of
  395. return self
  396. @property
  397. def entity_namespace(self):
  398. raise AttributeError(
  399. "This SQL expression has no entity namespace "
  400. "with which to filter from."
  401. )
  402. def __getstate__(self):
  403. d = self.__dict__.copy()
  404. d.pop("_is_clone_of", None)
  405. d.pop("_generate_cache_key", None)
  406. return d
  407. def _execute_on_connection(
  408. self,
  409. connection: Connection,
  410. distilled_params: _CoreMultiExecuteParams,
  411. execution_options: CoreExecuteOptionsParameter,
  412. ) -> Result[Any]:
  413. if self.supports_execution:
  414. if TYPE_CHECKING:
  415. assert isinstance(self, Executable)
  416. return connection._execute_clauseelement(
  417. self, distilled_params, execution_options
  418. )
  419. else:
  420. raise exc.ObjectNotExecutableError(self)
  421. def _execute_on_scalar(
  422. self,
  423. connection: Connection,
  424. distilled_params: _CoreMultiExecuteParams,
  425. execution_options: CoreExecuteOptionsParameter,
  426. ) -> Any:
  427. """an additional hook for subclasses to provide a different
  428. implementation for connection.scalar() vs. connection.execute().
  429. .. versionadded:: 2.0
  430. """
  431. return self._execute_on_connection(
  432. connection, distilled_params, execution_options
  433. ).scalar()
  434. def _get_embedded_bindparams(self) -> Sequence[BindParameter[Any]]:
  435. """Return the list of :class:`.BindParameter` objects embedded in the
  436. object.
  437. This accomplishes the same purpose as ``visitors.traverse()`` or
  438. similar would provide, however by making use of the cache key
  439. it takes advantage of memoization of the key to result in fewer
  440. net method calls, assuming the statement is also going to be
  441. executed.
  442. """
  443. key = self._generate_cache_key()
  444. if key is None:
  445. bindparams: List[BindParameter[Any]] = []
  446. traverse(self, {}, {"bindparam": bindparams.append})
  447. return bindparams
  448. else:
  449. return key.bindparams
  450. def unique_params(
  451. self,
  452. __optionaldict: Optional[Dict[str, Any]] = None,
  453. **kwargs: Any,
  454. ) -> Self:
  455. """Return a copy with :func:`_expression.bindparam` elements
  456. replaced.
  457. Same functionality as :meth:`_expression.ClauseElement.params`,
  458. except adds `unique=True`
  459. to affected bind parameters so that multiple statements can be
  460. used.
  461. """
  462. return self._replace_params(True, __optionaldict, kwargs)
  463. def params(
  464. self,
  465. __optionaldict: Optional[Mapping[str, Any]] = None,
  466. **kwargs: Any,
  467. ) -> Self:
  468. """Return a copy with :func:`_expression.bindparam` elements
  469. replaced.
  470. Returns a copy of this ClauseElement with
  471. :func:`_expression.bindparam`
  472. elements replaced with values taken from the given dictionary::
  473. >>> clause = column('x') + bindparam('foo')
  474. >>> print(clause.compile().params)
  475. {'foo':None}
  476. >>> print(clause.params({'foo':7}).compile().params)
  477. {'foo':7}
  478. """
  479. return self._replace_params(False, __optionaldict, kwargs)
  480. def _replace_params(
  481. self,
  482. unique: bool,
  483. optionaldict: Optional[Mapping[str, Any]],
  484. kwargs: Dict[str, Any],
  485. ) -> Self:
  486. if optionaldict:
  487. kwargs.update(optionaldict)
  488. def visit_bindparam(bind: BindParameter[Any]) -> None:
  489. if bind.key in kwargs:
  490. bind.value = kwargs[bind.key]
  491. bind.required = False
  492. if unique:
  493. bind._convert_to_unique()
  494. return cloned_traverse(
  495. self,
  496. {"maintain_key": True, "detect_subquery_cols": True},
  497. {"bindparam": visit_bindparam},
  498. )
  499. def compare(self, other: ClauseElement, **kw: Any) -> bool:
  500. r"""Compare this :class:`_expression.ClauseElement` to
  501. the given :class:`_expression.ClauseElement`.
  502. Subclasses should override the default behavior, which is a
  503. straight identity comparison.
  504. \**kw are arguments consumed by subclass ``compare()`` methods and
  505. may be used to modify the criteria for comparison
  506. (see :class:`_expression.ColumnElement`).
  507. """
  508. return traversals.compare(self, other, **kw)
  509. def self_group(
  510. self, against: Optional[OperatorType] = None
  511. ) -> ClauseElement:
  512. """Apply a 'grouping' to this :class:`_expression.ClauseElement`.
  513. This method is overridden by subclasses to return a "grouping"
  514. construct, i.e. parenthesis. In particular it's used by "binary"
  515. expressions to provide a grouping around themselves when placed into a
  516. larger expression, as well as by :func:`_expression.select`
  517. constructs when placed into the FROM clause of another
  518. :func:`_expression.select`. (Note that subqueries should be
  519. normally created using the :meth:`_expression.Select.alias` method,
  520. as many
  521. platforms require nested SELECT statements to be named).
  522. As expressions are composed together, the application of
  523. :meth:`self_group` is automatic - end-user code should never
  524. need to use this method directly. Note that SQLAlchemy's
  525. clause constructs take operator precedence into account -
  526. so parenthesis might not be needed, for example, in
  527. an expression like ``x OR (y AND z)`` - AND takes precedence
  528. over OR.
  529. The base :meth:`self_group` method of
  530. :class:`_expression.ClauseElement`
  531. just returns self.
  532. """
  533. return self
  534. def _ungroup(self) -> ClauseElement:
  535. """Return this :class:`_expression.ClauseElement`
  536. without any groupings.
  537. """
  538. return self
  539. def _compile_w_cache(
  540. self,
  541. dialect: Dialect,
  542. *,
  543. compiled_cache: Optional[CompiledCacheType],
  544. column_keys: List[str],
  545. for_executemany: bool = False,
  546. schema_translate_map: Optional[SchemaTranslateMapType] = None,
  547. **kw: Any,
  548. ) -> typing_Tuple[
  549. Compiled, Optional[Sequence[BindParameter[Any]]], CacheStats
  550. ]:
  551. elem_cache_key: Optional[CacheKey]
  552. if compiled_cache is not None and dialect._supports_statement_cache:
  553. elem_cache_key = self._generate_cache_key()
  554. else:
  555. elem_cache_key = None
  556. if elem_cache_key is not None:
  557. if TYPE_CHECKING:
  558. assert compiled_cache is not None
  559. cache_key, extracted_params = elem_cache_key
  560. key = (
  561. dialect,
  562. cache_key,
  563. tuple(column_keys),
  564. bool(schema_translate_map),
  565. for_executemany,
  566. )
  567. compiled_sql = compiled_cache.get(key)
  568. if compiled_sql is None:
  569. cache_hit = dialect.CACHE_MISS
  570. compiled_sql = self._compiler(
  571. dialect,
  572. cache_key=elem_cache_key,
  573. column_keys=column_keys,
  574. for_executemany=for_executemany,
  575. schema_translate_map=schema_translate_map,
  576. **kw,
  577. )
  578. compiled_cache[key] = compiled_sql
  579. else:
  580. cache_hit = dialect.CACHE_HIT
  581. else:
  582. extracted_params = None
  583. compiled_sql = self._compiler(
  584. dialect,
  585. cache_key=elem_cache_key,
  586. column_keys=column_keys,
  587. for_executemany=for_executemany,
  588. schema_translate_map=schema_translate_map,
  589. **kw,
  590. )
  591. if not dialect._supports_statement_cache:
  592. cache_hit = dialect.NO_DIALECT_SUPPORT
  593. elif compiled_cache is None:
  594. cache_hit = dialect.CACHING_DISABLED
  595. else:
  596. cache_hit = dialect.NO_CACHE_KEY
  597. return compiled_sql, extracted_params, cache_hit
  598. def __invert__(self):
  599. # undocumented element currently used by the ORM for
  600. # relationship.contains()
  601. if hasattr(self, "negation_clause"):
  602. return self.negation_clause
  603. else:
  604. return self._negate()
  605. def _negate(self) -> ClauseElement:
  606. grouped = self.self_group(against=operators.inv)
  607. assert isinstance(grouped, ColumnElement)
  608. return UnaryExpression(grouped, operator=operators.inv)
  609. def __bool__(self):
  610. raise TypeError("Boolean value of this clause is not defined")
  611. def __repr__(self):
  612. friendly = self.description
  613. if friendly is None:
  614. return object.__repr__(self)
  615. else:
  616. return "<%s.%s at 0x%x; %s>" % (
  617. self.__module__,
  618. self.__class__.__name__,
  619. id(self),
  620. friendly,
  621. )
  622. class DQLDMLClauseElement(ClauseElement):
  623. """represents a :class:`.ClauseElement` that compiles to a DQL or DML
  624. expression, not DDL.
  625. .. versionadded:: 2.0
  626. """
  627. if typing.TYPE_CHECKING:
  628. def _compiler(self, dialect: Dialect, **kw: Any) -> SQLCompiler:
  629. """Return a compiler appropriate for this ClauseElement, given a
  630. Dialect."""
  631. ...
  632. def compile( # noqa: A001
  633. self,
  634. bind: Optional[Union[Engine, Connection]] = None,
  635. dialect: Optional[Dialect] = None,
  636. **kw: Any,
  637. ) -> SQLCompiler:
  638. ...
  639. class CompilerColumnElement(
  640. roles.DMLColumnRole,
  641. roles.DDLConstraintColumnRole,
  642. roles.ColumnsClauseRole,
  643. CompilerElement,
  644. ):
  645. """A compiler-only column element used for ad-hoc string compilations.
  646. .. versionadded:: 2.0
  647. """
  648. __slots__ = ()
  649. _propagate_attrs = util.EMPTY_DICT
  650. _is_collection_aggregate = False
  651. # SQLCoreOperations should be suiting the ExpressionElementRole
  652. # and ColumnsClauseRole. however the MRO issues become too elaborate
  653. # at the moment.
  654. class SQLCoreOperations(Generic[_T_co], ColumnOperators, TypingOnly):
  655. __slots__ = ()
  656. # annotations for comparison methods
  657. # these are from operators->Operators / ColumnOperators,
  658. # redefined with the specific types returned by ColumnElement hierarchies
  659. if typing.TYPE_CHECKING:
  660. @util.non_memoized_property
  661. def _propagate_attrs(self) -> _PropagateAttrsType:
  662. ...
  663. def operate(
  664. self, op: OperatorType, *other: Any, **kwargs: Any
  665. ) -> ColumnElement[Any]:
  666. ...
  667. def reverse_operate(
  668. self, op: OperatorType, other: Any, **kwargs: Any
  669. ) -> ColumnElement[Any]:
  670. ...
  671. @overload
  672. def op(
  673. self,
  674. opstring: str,
  675. precedence: int = ...,
  676. is_comparison: bool = ...,
  677. *,
  678. return_type: _TypeEngineArgument[_OPT],
  679. python_impl: Optional[Callable[..., Any]] = None,
  680. ) -> Callable[[Any], BinaryExpression[_OPT]]:
  681. ...
  682. @overload
  683. def op(
  684. self,
  685. opstring: str,
  686. precedence: int = ...,
  687. is_comparison: bool = ...,
  688. return_type: Optional[_TypeEngineArgument[Any]] = ...,
  689. python_impl: Optional[Callable[..., Any]] = ...,
  690. ) -> Callable[[Any], BinaryExpression[Any]]:
  691. ...
  692. def op(
  693. self,
  694. opstring: str,
  695. precedence: int = 0,
  696. is_comparison: bool = False,
  697. return_type: Optional[_TypeEngineArgument[Any]] = None,
  698. python_impl: Optional[Callable[..., Any]] = None,
  699. ) -> Callable[[Any], BinaryExpression[Any]]:
  700. ...
  701. def bool_op(
  702. self,
  703. opstring: str,
  704. precedence: int = 0,
  705. python_impl: Optional[Callable[..., Any]] = None,
  706. ) -> Callable[[Any], BinaryExpression[bool]]:
  707. ...
  708. def __and__(self, other: Any) -> BooleanClauseList:
  709. ...
  710. def __or__(self, other: Any) -> BooleanClauseList:
  711. ...
  712. def __invert__(self) -> ColumnElement[_T_co]:
  713. ...
  714. def __lt__(self, other: Any) -> ColumnElement[bool]:
  715. ...
  716. def __le__(self, other: Any) -> ColumnElement[bool]:
  717. ...
  718. # declare also that this class has an hash method otherwise
  719. # it may be assumed to be None by type checkers since the
  720. # object defines __eq__ and python sets it to None in that case:
  721. # https://docs.python.org/3/reference/datamodel.html#object.__hash__
  722. def __hash__(self) -> int:
  723. ...
  724. def __eq__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
  725. ...
  726. def __ne__(self, other: Any) -> ColumnElement[bool]: # type: ignore[override] # noqa: E501
  727. ...
  728. def is_distinct_from(self, other: Any) -> ColumnElement[bool]:
  729. ...
  730. def is_not_distinct_from(self, other: Any) -> ColumnElement[bool]:
  731. ...
  732. def __gt__(self, other: Any) -> ColumnElement[bool]:
  733. ...
  734. def __ge__(self, other: Any) -> ColumnElement[bool]:
  735. ...
  736. def __neg__(self) -> UnaryExpression[_T_co]:
  737. ...
  738. def __contains__(self, other: Any) -> ColumnElement[bool]:
  739. ...
  740. def __getitem__(self, index: Any) -> ColumnElement[Any]:
  741. ...
  742. @overload
  743. def __lshift__(self: _SQO[int], other: Any) -> ColumnElement[int]:
  744. ...
  745. @overload
  746. def __lshift__(self, other: Any) -> ColumnElement[Any]:
  747. ...
  748. def __lshift__(self, other: Any) -> ColumnElement[Any]:
  749. ...
  750. @overload
  751. def __rshift__(self: _SQO[int], other: Any) -> ColumnElement[int]:
  752. ...
  753. @overload
  754. def __rshift__(self, other: Any) -> ColumnElement[Any]:
  755. ...
  756. def __rshift__(self, other: Any) -> ColumnElement[Any]:
  757. ...
  758. @overload
  759. def concat(self: _SQO[str], other: Any) -> ColumnElement[str]:
  760. ...
  761. @overload
  762. def concat(self, other: Any) -> ColumnElement[Any]:
  763. ...
  764. def concat(self, other: Any) -> ColumnElement[Any]:
  765. ...
  766. def like(
  767. self, other: Any, escape: Optional[str] = None
  768. ) -> BinaryExpression[bool]:
  769. ...
  770. def ilike(
  771. self, other: Any, escape: Optional[str] = None
  772. ) -> BinaryExpression[bool]:
  773. ...
  774. def bitwise_xor(self, other: Any) -> BinaryExpression[Any]:
  775. ...
  776. def bitwise_or(self, other: Any) -> BinaryExpression[Any]:
  777. ...
  778. def bitwise_and(self, other: Any) -> BinaryExpression[Any]:
  779. ...
  780. def bitwise_not(self) -> UnaryExpression[_T_co]:
  781. ...
  782. def bitwise_lshift(self, other: Any) -> BinaryExpression[Any]:
  783. ...
  784. def bitwise_rshift(self, other: Any) -> BinaryExpression[Any]:
  785. ...
  786. def in_(
  787. self,
  788. other: Union[
  789. Iterable[Any], BindParameter[Any], roles.InElementRole
  790. ],
  791. ) -> BinaryExpression[bool]:
  792. ...
  793. def not_in(
  794. self,
  795. other: Union[
  796. Iterable[Any], BindParameter[Any], roles.InElementRole
  797. ],
  798. ) -> BinaryExpression[bool]:
  799. ...
  800. def notin_(
  801. self,
  802. other: Union[
  803. Iterable[Any], BindParameter[Any], roles.InElementRole
  804. ],
  805. ) -> BinaryExpression[bool]:
  806. ...
  807. def not_like(
  808. self, other: Any, escape: Optional[str] = None
  809. ) -> BinaryExpression[bool]:
  810. ...
  811. def notlike(
  812. self, other: Any, escape: Optional[str] = None
  813. ) -> BinaryExpression[bool]:
  814. ...
  815. def not_ilike(
  816. self, other: Any, escape: Optional[str] = None
  817. ) -> BinaryExpression[bool]:
  818. ...
  819. def notilike(
  820. self, other: Any, escape: Optional[str] = None
  821. ) -> BinaryExpression[bool]:
  822. ...
  823. def is_(self, other: Any) -> BinaryExpression[bool]:
  824. ...
  825. def is_not(self, other: Any) -> BinaryExpression[bool]:
  826. ...
  827. def isnot(self, other: Any) -> BinaryExpression[bool]:
  828. ...
  829. def startswith(
  830. self,
  831. other: Any,
  832. escape: Optional[str] = None,
  833. autoescape: bool = False,
  834. ) -> ColumnElement[bool]:
  835. ...
  836. def istartswith(
  837. self,
  838. other: Any,
  839. escape: Optional[str] = None,
  840. autoescape: bool = False,
  841. ) -> ColumnElement[bool]:
  842. ...
  843. def endswith(
  844. self,
  845. other: Any,
  846. escape: Optional[str] = None,
  847. autoescape: bool = False,
  848. ) -> ColumnElement[bool]:
  849. ...
  850. def iendswith(
  851. self,
  852. other: Any,
  853. escape: Optional[str] = None,
  854. autoescape: bool = False,
  855. ) -> ColumnElement[bool]:
  856. ...
  857. def contains(self, other: Any, **kw: Any) -> ColumnElement[bool]:
  858. ...
  859. def icontains(self, other: Any, **kw: Any) -> ColumnElement[bool]:
  860. ...
  861. def match(self, other: Any, **kwargs: Any) -> ColumnElement[bool]:
  862. ...
  863. def regexp_match(
  864. self, pattern: Any, flags: Optional[str] = None
  865. ) -> ColumnElement[bool]:
  866. ...
  867. def regexp_replace(
  868. self, pattern: Any, replacement: Any, flags: Optional[str] = None
  869. ) -> ColumnElement[str]:
  870. ...
  871. def desc(self) -> UnaryExpression[_T_co]:
  872. ...
  873. def asc(self) -> UnaryExpression[_T_co]:
  874. ...
  875. def nulls_first(self) -> UnaryExpression[_T_co]:
  876. ...
  877. def nullsfirst(self) -> UnaryExpression[_T_co]:
  878. ...
  879. def nulls_last(self) -> UnaryExpression[_T_co]:
  880. ...
  881. def nullslast(self) -> UnaryExpression[_T_co]:
  882. ...
  883. def collate(self, collation: str) -> CollationClause:
  884. ...
  885. def between(
  886. self, cleft: Any, cright: Any, symmetric: bool = False
  887. ) -> BinaryExpression[bool]:
  888. ...
  889. def distinct(self: _SQO[_T_co]) -> UnaryExpression[_T_co]:
  890. ...
  891. def any_(self) -> CollectionAggregate[Any]:
  892. ...
  893. def all_(self) -> CollectionAggregate[Any]:
  894. ...
  895. # numeric overloads. These need more tweaking
  896. # in particular they all need to have a variant for Optiona[_T]
  897. # because Optional only applies to the data side, not the expression
  898. # side
  899. @overload
  900. def __add__(
  901. self: _SQO[_NMT],
  902. other: Any,
  903. ) -> ColumnElement[_NMT]:
  904. ...
  905. @overload
  906. def __add__(
  907. self: _SQO[str],
  908. other: Any,
  909. ) -> ColumnElement[str]:
  910. ...
  911. def __add__(self, other: Any) -> ColumnElement[Any]:
  912. ...
  913. @overload
  914. def __radd__(self: _SQO[_NMT], other: Any) -> ColumnElement[_NMT]:
  915. ...
  916. @overload
  917. def __radd__(self: _SQO[str], other: Any) -> ColumnElement[str]:
  918. ...
  919. def __radd__(self, other: Any) -> ColumnElement[Any]:
  920. ...
  921. @overload
  922. def __sub__(
  923. self: _SQO[_NMT],
  924. other: Any,
  925. ) -> ColumnElement[_NMT]:
  926. ...
  927. @overload
  928. def __sub__(self, other: Any) -> ColumnElement[Any]:
  929. ...
  930. def __sub__(self, other: Any) -> ColumnElement[Any]:
  931. ...
  932. @overload
  933. def __rsub__(
  934. self: _SQO[_NMT],
  935. other: Any,
  936. ) -> ColumnElement[_NMT]:
  937. ...
  938. @overload
  939. def __rsub__(self, other: Any) -> ColumnElement[Any]:
  940. ...
  941. def __rsub__(self, other: Any) -> ColumnElement[Any]:
  942. ...
  943. @overload
  944. def __mul__(
  945. self: _SQO[_NMT],
  946. other: Any,
  947. ) -> ColumnElement[_NMT]:
  948. ...
  949. @overload
  950. def __mul__(self, other: Any) -> ColumnElement[Any]:
  951. ...
  952. def __mul__(self, other: Any) -> ColumnElement[Any]:
  953. ...
  954. @overload
  955. def __rmul__(
  956. self: _SQO[_NMT],
  957. other: Any,
  958. ) -> ColumnElement[_NMT]:
  959. ...
  960. @overload
  961. def __rmul__(self, other: Any) -> ColumnElement[Any]:
  962. ...
  963. def __rmul__(self, other: Any) -> ColumnElement[Any]:
  964. ...
  965. @overload
  966. def __mod__(self: _SQO[_NMT], other: Any) -> ColumnElement[_NMT]:
  967. ...
  968. @overload
  969. def __mod__(self, other: Any) -> ColumnElement[Any]:
  970. ...
  971. def __mod__(self, other: Any) -> ColumnElement[Any]:
  972. ...
  973. @overload
  974. def __rmod__(self: _SQO[_NMT], other: Any) -> ColumnElement[_NMT]:
  975. ...
  976. @overload
  977. def __rmod__(self, other: Any) -> ColumnElement[Any]:
  978. ...
  979. def __rmod__(self, other: Any) -> ColumnElement[Any]:
  980. ...
  981. @overload
  982. def __truediv__(
  983. self: _SQO[int], other: Any
  984. ) -> ColumnElement[_NUMERIC]:
  985. ...
  986. @overload
  987. def __truediv__(self: _SQO[_NT], other: Any) -> ColumnElement[_NT]:
  988. ...
  989. @overload
  990. def __truediv__(self, other: Any) -> ColumnElement[Any]:
  991. ...
  992. def __truediv__(self, other: Any) -> ColumnElement[Any]:
  993. ...
  994. @overload
  995. def __rtruediv__(
  996. self: _SQO[_NMT], other: Any
  997. ) -> ColumnElement[_NUMERIC]:
  998. ...
  999. @overload
  1000. def __rtruediv__(self, other: Any) -> ColumnElement[Any]:
  1001. ...
  1002. def __rtruediv__(self, other: Any) -> ColumnElement[Any]:
  1003. ...
  1004. @overload
  1005. def __floordiv__(self: _SQO[_NMT], other: Any) -> ColumnElement[_NMT]:
  1006. ...
  1007. @overload
  1008. def __floordiv__(self, other: Any) -> ColumnElement[Any]:
  1009. ...
  1010. def __floordiv__(self, other: Any) -> ColumnElement[Any]:
  1011. ...
  1012. @overload
  1013. def __rfloordiv__(self: _SQO[_NMT], other: Any) -> ColumnElement[_NMT]:
  1014. ...
  1015. @overload
  1016. def __rfloordiv__(self, other: Any) -> ColumnElement[Any]:
  1017. ...
  1018. def __rfloordiv__(self, other: Any) -> ColumnElement[Any]:
  1019. ...
  1020. class SQLColumnExpression(
  1021. SQLCoreOperations[_T_co], roles.ExpressionElementRole[_T_co], TypingOnly
  1022. ):
  1023. """A type that may be used to indicate any SQL column element or object
  1024. that acts in place of one.
  1025. :class:`.SQLColumnExpression` is a base of
  1026. :class:`.ColumnElement`, as well as within the bases of ORM elements
  1027. such as :class:`.InstrumentedAttribute`, and may be used in :pep:`484`
  1028. typing to indicate arguments or return values that should behave
  1029. as column expressions.
  1030. .. versionadded:: 2.0.0b4
  1031. """
  1032. __slots__ = ()
  1033. _SQO = SQLCoreOperations
  1034. class ColumnElement(
  1035. roles.ColumnArgumentOrKeyRole,
  1036. roles.StatementOptionRole,
  1037. roles.WhereHavingRole,
  1038. roles.BinaryElementRole[_T],
  1039. roles.OrderByRole,
  1040. roles.ColumnsClauseRole,
  1041. roles.LimitOffsetRole,
  1042. roles.DMLColumnRole,
  1043. roles.DDLConstraintColumnRole,
  1044. roles.DDLExpressionRole,
  1045. SQLColumnExpression[_T],
  1046. DQLDMLClauseElement,
  1047. ):
  1048. """Represent a column-oriented SQL expression suitable for usage in the
  1049. "columns" clause, WHERE clause etc. of a statement.
  1050. While the most familiar kind of :class:`_expression.ColumnElement` is the
  1051. :class:`_schema.Column` object, :class:`_expression.ColumnElement`
  1052. serves as the basis
  1053. for any unit that may be present in a SQL expression, including
  1054. the expressions themselves, SQL functions, bound parameters,
  1055. literal expressions, keywords such as ``NULL``, etc.
  1056. :class:`_expression.ColumnElement`
  1057. is the ultimate base class for all such elements.
  1058. A wide variety of SQLAlchemy Core functions work at the SQL expression
  1059. level, and are intended to accept instances of
  1060. :class:`_expression.ColumnElement` as
  1061. arguments. These functions will typically document that they accept a
  1062. "SQL expression" as an argument. What this means in terms of SQLAlchemy
  1063. usually refers to an input which is either already in the form of a
  1064. :class:`_expression.ColumnElement` object,
  1065. or a value which can be **coerced** into
  1066. one. The coercion rules followed by most, but not all, SQLAlchemy Core
  1067. functions with regards to SQL expressions are as follows:
  1068. * a literal Python value, such as a string, integer or floating
  1069. point value, boolean, datetime, ``Decimal`` object, or virtually
  1070. any other Python object, will be coerced into a "literal bound
  1071. value". This generally means that a :func:`.bindparam` will be
  1072. produced featuring the given value embedded into the construct; the
  1073. resulting :class:`.BindParameter` object is an instance of
  1074. :class:`_expression.ColumnElement`.
  1075. The Python value will ultimately be sent
  1076. to the DBAPI at execution time as a parameterized argument to the
  1077. ``execute()`` or ``executemany()`` methods, after SQLAlchemy
  1078. type-specific converters (e.g. those provided by any associated
  1079. :class:`.TypeEngine` objects) are applied to the value.
  1080. * any special object value, typically ORM-level constructs, which
  1081. feature an accessor called ``__clause_element__()``. The Core
  1082. expression system looks for this method when an object of otherwise
  1083. unknown type is passed to a function that is looking to coerce the
  1084. argument into a :class:`_expression.ColumnElement` and sometimes a
  1085. :class:`_expression.SelectBase` expression.
  1086. It is used within the ORM to
  1087. convert from ORM-specific objects like mapped classes and
  1088. mapped attributes into Core expression objects.
  1089. * The Python ``None`` value is typically interpreted as ``NULL``,
  1090. which in SQLAlchemy Core produces an instance of :func:`.null`.
  1091. A :class:`_expression.ColumnElement` provides the ability to generate new
  1092. :class:`_expression.ColumnElement`
  1093. objects using Python expressions. This means that Python operators
  1094. such as ``==``, ``!=`` and ``<`` are overloaded to mimic SQL operations,
  1095. and allow the instantiation of further :class:`_expression.ColumnElement`
  1096. instances
  1097. which are composed from other, more fundamental
  1098. :class:`_expression.ColumnElement`
  1099. objects. For example, two :class:`.ColumnClause` objects can be added
  1100. together with the addition operator ``+`` to produce
  1101. a :class:`.BinaryExpression`.
  1102. Both :class:`.ColumnClause` and :class:`.BinaryExpression` are subclasses
  1103. of :class:`_expression.ColumnElement`:
  1104. .. sourcecode:: pycon+sql
  1105. >>> from sqlalchemy.sql import column
  1106. >>> column('a') + column('b')
  1107. <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
  1108. >>> print(column('a') + column('b'))
  1109. {printsql}a + b
  1110. .. seealso::
  1111. :class:`_schema.Column`
  1112. :func:`_expression.column`
  1113. """
  1114. __visit_name__ = "column_element"
  1115. primary_key: bool = False
  1116. _is_clone_of: Optional[ColumnElement[_T]]
  1117. _is_column_element = True
  1118. _insert_sentinel: bool = False
  1119. _omit_from_statements = False
  1120. _is_collection_aggregate = False
  1121. foreign_keys: AbstractSet[ForeignKey] = frozenset()
  1122. @util.memoized_property
  1123. def _proxies(self) -> List[ColumnElement[Any]]:
  1124. return []
  1125. @util.non_memoized_property
  1126. def _tq_label(self) -> Optional[str]:
  1127. """The named label that can be used to target
  1128. this column in a result set in a "table qualified" context.
  1129. This label is almost always the label used when
  1130. rendering <expr> AS <label> in a SELECT statement when using
  1131. the LABEL_STYLE_TABLENAME_PLUS_COL label style, which is what the
  1132. legacy ORM ``Query`` object uses as well.
  1133. For a regular Column bound to a Table, this is typically the label
  1134. <tablename>_<columnname>. For other constructs, different rules
  1135. may apply, such as anonymized labels and others.
  1136. .. versionchanged:: 1.4.21 renamed from ``._label``
  1137. """
  1138. return None
  1139. key: Optional[str] = None
  1140. """The 'key' that in some circumstances refers to this object in a
  1141. Python namespace.
  1142. This typically refers to the "key" of the column as present in the
  1143. ``.c`` collection of a selectable, e.g. ``sometable.c["somekey"]`` would
  1144. return a :class:`_schema.Column` with a ``.key`` of "somekey".
  1145. """
  1146. @HasMemoized.memoized_attribute
  1147. def _tq_key_label(self) -> Optional[str]:
  1148. """A label-based version of 'key' that in some circumstances refers
  1149. to this object in a Python namespace.
  1150. _tq_key_label comes into play when a select() statement is constructed
  1151. with apply_labels(); in this case, all Column objects in the ``.c``
  1152. collection are rendered as <tablename>_<columnname> in SQL; this is
  1153. essentially the value of ._label. But to locate those columns in the
  1154. ``.c`` collection, the name is along the lines of <tablename>_<key>;
  1155. that's the typical value of .key_label.
  1156. .. versionchanged:: 1.4.21 renamed from ``._key_label``
  1157. """
  1158. return self._proxy_key
  1159. @property
  1160. def _key_label(self) -> Optional[str]:
  1161. """legacy; renamed to _tq_key_label"""
  1162. return self._tq_key_label
  1163. @property
  1164. def _label(self) -> Optional[str]:
  1165. """legacy; renamed to _tq_label"""
  1166. return self._tq_label
  1167. @property
  1168. def _non_anon_label(self) -> Optional[str]:
  1169. """the 'name' that naturally applies this element when rendered in
  1170. SQL.
  1171. Concretely, this is the "name" of a column or a label in a
  1172. SELECT statement; ``<columnname>`` and ``<labelname>`` below::
  1173. SELECT <columnmame> FROM table
  1174. SELECT column AS <labelname> FROM table
  1175. Above, the two names noted will be what's present in the DBAPI
  1176. ``cursor.description`` as the names.
  1177. If this attribute returns ``None``, it means that the SQL element as
  1178. written does not have a 100% fully predictable "name" that would appear
  1179. in the ``cursor.description``. Examples include SQL functions, CAST
  1180. functions, etc. While such things do return names in
  1181. ``cursor.description``, they are only predictable on a
  1182. database-specific basis; e.g. an expression like ``MAX(table.col)`` may
  1183. appear as the string ``max`` on one database (like PostgreSQL) or may
  1184. appear as the whole expression ``max(table.col)`` on SQLite.
  1185. The default implementation looks for a ``.name`` attribute on the
  1186. object, as has been the precedent established in SQLAlchemy for many
  1187. years. An exception is made on the ``FunctionElement`` subclass
  1188. so that the return value is always ``None``.
  1189. .. versionadded:: 1.4.21
  1190. """
  1191. return getattr(self, "name", None)
  1192. _render_label_in_columns_clause = True
  1193. """A flag used by select._columns_plus_names that helps to determine
  1194. we are actually going to render in terms of "SELECT <col> AS <label>".
  1195. This flag can be returned as False for some Column objects that want
  1196. to be rendered as simple "SELECT <col>"; typically columns that don't have
  1197. any parent table and are named the same as what the label would be
  1198. in any case.
  1199. """
  1200. _allow_label_resolve = True
  1201. """A flag that can be flipped to prevent a column from being resolvable
  1202. by string label name.
  1203. The joined eager loader strategy in the ORM uses this, for example.
  1204. """
  1205. _is_implicitly_boolean = False
  1206. _alt_names: Sequence[str] = ()
  1207. @overload
  1208. def self_group(
  1209. self: ColumnElement[_T], against: Optional[OperatorType] = None
  1210. ) -> ColumnElement[_T]:
  1211. ...
  1212. @overload
  1213. def self_group(
  1214. self: ColumnElement[Any], against: Optional[OperatorType] = None
  1215. ) -> ColumnElement[Any]:
  1216. ...
  1217. def self_group(
  1218. self, against: Optional[OperatorType] = None
  1219. ) -> ColumnElement[Any]:
  1220. if (
  1221. against in (operators.and_, operators.or_, operators._asbool)
  1222. and self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity
  1223. ):
  1224. return AsBoolean(self, operators.is_true, operators.is_false)
  1225. elif against in (operators.any_op, operators.all_op):
  1226. return Grouping(self)
  1227. else:
  1228. return self
  1229. @overload
  1230. def _negate(self: ColumnElement[bool]) -> ColumnElement[bool]:
  1231. ...
  1232. @overload
  1233. def _negate(self: ColumnElement[_T]) -> ColumnElement[_T]:
  1234. ...
  1235. def _negate(self) -> ColumnElement[Any]:
  1236. if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
  1237. return AsBoolean(self, operators.is_false, operators.is_true)
  1238. else:
  1239. grouped = self.self_group(against=operators.inv)
  1240. assert isinstance(grouped, ColumnElement)
  1241. return UnaryExpression(
  1242. grouped, operator=operators.inv, wraps_column_expression=True
  1243. )
  1244. type: TypeEngine[_T]
  1245. if not TYPE_CHECKING:
  1246. @util.memoized_property
  1247. def type(self) -> TypeEngine[_T]: # noqa: A001
  1248. # used for delayed setup of
  1249. # type_api
  1250. return type_api.NULLTYPE
  1251. @HasMemoized.memoized_attribute
  1252. def comparator(self) -> TypeEngine.Comparator[_T]:
  1253. try:
  1254. comparator_factory = self.type.comparator_factory
  1255. except AttributeError as err:
  1256. raise TypeError(
  1257. "Object %r associated with '.type' attribute "
  1258. "is not a TypeEngine class or object" % self.type
  1259. ) from err
  1260. else:
  1261. return comparator_factory(self)
  1262. def __setstate__(self, state):
  1263. self.__dict__.update(state)
  1264. def __getattr__(self, key: str) -> Any:
  1265. try:
  1266. return getattr(self.comparator, key)
  1267. except AttributeError as err:
  1268. raise AttributeError(
  1269. "Neither %r object nor %r object has an attribute %r"
  1270. % (
  1271. type(self).__name__,
  1272. type(self.comparator).__name__,
  1273. key,
  1274. )
  1275. ) from err
  1276. def operate(
  1277. self,
  1278. op: operators.OperatorType,
  1279. *other: Any,
  1280. **kwargs: Any,
  1281. ) -> ColumnElement[Any]:
  1282. return op(self.comparator, *other, **kwargs) # type: ignore[no-any-return] # noqa: E501
  1283. def reverse_operate(
  1284. self, op: operators.OperatorType, other: Any, **kwargs: Any
  1285. ) -> ColumnElement[Any]:
  1286. return op(other, self.comparator, **kwargs) # type: ignore[no-any-return] # noqa: E501
  1287. def _bind_param(
  1288. self,
  1289. operator: operators.OperatorType,
  1290. obj: Any,
  1291. type_: Optional[TypeEngine[_T]] = None,
  1292. expanding: bool = False,
  1293. ) -> BindParameter[_T]:
  1294. return BindParameter(
  1295. None,
  1296. obj,
  1297. _compared_to_operator=operator,
  1298. type_=type_,
  1299. _compared_to_type=self.type,
  1300. unique=True,
  1301. expanding=expanding,
  1302. )
  1303. @property
  1304. def expression(self) -> ColumnElement[Any]:
  1305. """Return a column expression.
  1306. Part of the inspection interface; returns self.
  1307. """
  1308. return self
  1309. @property
  1310. def _select_iterable(self) -> _SelectIterable:
  1311. return (self,)
  1312. @util.memoized_property
  1313. def base_columns(self) -> FrozenSet[ColumnElement[Any]]:
  1314. return frozenset(c for c in self.proxy_set if not c._proxies)
  1315. @util.memoized_property
  1316. def proxy_set(self) -> FrozenSet[ColumnElement[Any]]:
  1317. """set of all columns we are proxying
  1318. as of 2.0 this is explicitly deannotated columns. previously it was
  1319. effectively deannotated columns but wasn't enforced. annotated
  1320. columns should basically not go into sets if at all possible because
  1321. their hashing behavior is very non-performant.
  1322. """
  1323. return frozenset([self._deannotate()]).union(
  1324. itertools.chain(*[c.proxy_set for c in self._proxies])
  1325. )
  1326. @util.memoized_property
  1327. def _expanded_proxy_set(self) -> FrozenSet[ColumnElement[Any]]:
  1328. return frozenset(_expand_cloned(self.proxy_set))
  1329. def _uncached_proxy_list(self) -> List[ColumnElement[Any]]:
  1330. """An 'uncached' version of proxy set.
  1331. This list includes annotated columns which perform very poorly in
  1332. set operations.
  1333. """
  1334. return [self] + list(
  1335. itertools.chain(*[c._uncached_proxy_list() for c in self._proxies])
  1336. )
  1337. def shares_lineage(self, othercolumn: ColumnElement[Any]) -> bool:
  1338. """Return True if the given :class:`_expression.ColumnElement`
  1339. has a common ancestor to this :class:`_expression.ColumnElement`."""
  1340. return bool(self.proxy_set.intersection(othercolumn.proxy_set))
  1341. def _compare_name_for_result(self, other: ColumnElement[Any]) -> bool:
  1342. """Return True if the given column element compares to this one
  1343. when targeting within a result row."""
  1344. return (
  1345. hasattr(other, "name")
  1346. and hasattr(self, "name")
  1347. and other.name == self.name
  1348. )
  1349. @HasMemoized.memoized_attribute
  1350. def _proxy_key(self) -> Optional[str]:
  1351. if self._annotations and "proxy_key" in self._annotations:
  1352. return cast(str, self._annotations["proxy_key"])
  1353. name = self.key
  1354. if not name:
  1355. # there's a bit of a seeming contradiction which is that the
  1356. # "_non_anon_label" of a column can in fact be an
  1357. # "_anonymous_label"; this is when it's on a column that is
  1358. # proxying for an anonymous expression in a subquery.
  1359. name = self._non_anon_label
  1360. if isinstance(name, _anonymous_label):
  1361. return None
  1362. else:
  1363. return name
  1364. @HasMemoized.memoized_attribute
  1365. def _expression_label(self) -> Optional[str]:
  1366. """a suggested label to use in the case that the column has no name,
  1367. which should be used if possible as the explicit 'AS <label>'
  1368. where this expression would normally have an anon label.
  1369. this is essentially mostly what _proxy_key does except it returns
  1370. None if the column has a normal name that can be used.
  1371. """
  1372. if getattr(self, "name", None) is not None:
  1373. return None
  1374. elif self._annotations and "proxy_key" in self._annotations:
  1375. return cast(str, self._annotations["proxy_key"])
  1376. else:
  1377. return None
  1378. def _make_proxy(
  1379. self,
  1380. selectable: FromClause,
  1381. *,
  1382. name: Optional[str] = None,
  1383. key: Optional[str] = None,
  1384. name_is_truncatable: bool = False,
  1385. compound_select_cols: Optional[Sequence[ColumnElement[Any]]] = None,
  1386. **kw: Any,
  1387. ) -> typing_Tuple[str, ColumnClause[_T]]:
  1388. """Create a new :class:`_expression.ColumnElement` representing this
  1389. :class:`_expression.ColumnElement` as it appears in the select list of
  1390. a descending selectable.
  1391. """
  1392. if name is None:
  1393. name = self._anon_name_label
  1394. if key is None:
  1395. key = self._proxy_key
  1396. else:
  1397. key = name
  1398. assert key is not None
  1399. co: ColumnClause[_T] = ColumnClause(
  1400. coercions.expect(roles.TruncatedLabelRole, name)
  1401. if name_is_truncatable
  1402. else name,
  1403. type_=getattr(self, "type", None),
  1404. _selectable=selectable,
  1405. )
  1406. co._propagate_attrs = selectable._propagate_attrs
  1407. if compound_select_cols:
  1408. co._proxies = list(compound_select_cols)
  1409. else:
  1410. co._proxies = [self]
  1411. if selectable._is_clone_of is not None:
  1412. co._is_clone_of = selectable._is_clone_of.columns.get(key)
  1413. return key, co
  1414. def cast(self, type_: _TypeEngineArgument[_OPT]) -> Cast[_OPT]:
  1415. """Produce a type cast, i.e. ``CAST(<expression> AS <type>)``.
  1416. This is a shortcut to the :func:`_expression.cast` function.
  1417. .. seealso::
  1418. :ref:`tutorial_casts`
  1419. :func:`_expression.cast`
  1420. :func:`_expression.type_coerce`
  1421. """
  1422. return Cast(self, type_)
  1423. def label(self, name: Optional[str]) -> Label[_T]:
  1424. """Produce a column label, i.e. ``<columnname> AS <name>``.
  1425. This is a shortcut to the :func:`_expression.label` function.
  1426. If 'name' is ``None``, an anonymous label name will be generated.
  1427. """
  1428. return Label(name, self, self.type)
  1429. def _anon_label(
  1430. self, seed: Optional[str], add_hash: Optional[int] = None
  1431. ) -> _anonymous_label:
  1432. while self._is_clone_of is not None:
  1433. self = self._is_clone_of
  1434. # as of 1.4 anonymous label for ColumnElement uses hash(), not id(),
  1435. # as the identifier, because a column and its annotated version are
  1436. # the same thing in a SQL statement
  1437. hash_value = hash(self)
  1438. if add_hash:
  1439. # this path is used for disambiguating anon labels that would
  1440. # otherwise be the same name for the same element repeated.
  1441. # an additional numeric value is factored in for each label.
  1442. # shift hash(self) (which is id(self), typically 8 byte integer)
  1443. # 16 bits leftward. fill extra add_hash on right
  1444. assert add_hash < (2 << 15)
  1445. assert seed
  1446. hash_value = (hash_value << 16) | add_hash
  1447. # extra underscore is added for labels with extra hash
  1448. # values, to isolate the "deduped anon" namespace from the
  1449. # regular namespace. eliminates chance of these
  1450. # manufactured hash values overlapping with regular ones for some
  1451. # undefined python interpreter
  1452. seed = seed + "_"
  1453. if isinstance(seed, _anonymous_label):
  1454. return _anonymous_label.safe_construct(
  1455. hash_value, "", enclosing_label=seed
  1456. )
  1457. return _anonymous_label.safe_construct(hash_value, seed or "anon")
  1458. @util.memoized_property
  1459. def _anon_name_label(self) -> str:
  1460. """Provides a constant 'anonymous label' for this ColumnElement.
  1461. This is a label() expression which will be named at compile time.
  1462. The same label() is returned each time ``anon_label`` is called so
  1463. that expressions can reference ``anon_label`` multiple times,
  1464. producing the same label name at compile time.
  1465. The compiler uses this function automatically at compile time
  1466. for expressions that are known to be 'unnamed' like binary
  1467. expressions and function calls.
  1468. .. versionchanged:: 1.4.9 - this attribute was not intended to be
  1469. public and is renamed to _anon_name_label. anon_name exists
  1470. for backwards compat
  1471. """
  1472. name = getattr(self, "name", None)
  1473. return self._anon_label(name)
  1474. @util.memoized_property
  1475. def _anon_key_label(self) -> _anonymous_label:
  1476. """Provides a constant 'anonymous key label' for this ColumnElement.
  1477. Compare to ``anon_label``, except that the "key" of the column,
  1478. if available, is used to generate the label.
  1479. This is used when a deduplicating key is placed into the columns
  1480. collection of a selectable.
  1481. .. versionchanged:: 1.4.9 - this attribute was not intended to be
  1482. public and is renamed to _anon_key_label. anon_key_label exists
  1483. for backwards compat
  1484. """
  1485. return self._anon_label(self._proxy_key)
  1486. @property
  1487. @util.deprecated(
  1488. "1.4",
  1489. "The :attr:`_expression.ColumnElement.anon_label` attribute is now "
  1490. "private, and the public accessor is deprecated.",
  1491. )
  1492. def anon_label(self) -> str:
  1493. return self._anon_name_label
  1494. @property
  1495. @util.deprecated(
  1496. "1.4",
  1497. "The :attr:`_expression.ColumnElement.anon_key_label` attribute is "
  1498. "now private, and the public accessor is deprecated.",
  1499. )
  1500. def anon_key_label(self) -> str:
  1501. return self._anon_key_label
  1502. def _dedupe_anon_label_idx(self, idx: int) -> str:
  1503. """label to apply to a column that is anon labeled, but repeated
  1504. in the SELECT, so that we have to make an "extra anon" label that
  1505. disambiguates it from the previous appearance.
  1506. these labels come out like "foo_bar_id__1" and have double underscores
  1507. in them.
  1508. """
  1509. label = getattr(self, "name", None)
  1510. # current convention is that if the element doesn't have a
  1511. # ".name" (usually because it is not NamedColumn), we try to
  1512. # use a "table qualified" form for the "dedupe anon" label,
  1513. # based on the notion that a label like
  1514. # "CAST(casttest.v1 AS DECIMAL) AS casttest_v1__1" looks better than
  1515. # "CAST(casttest.v1 AS DECIMAL) AS anon__1"
  1516. if label is None:
  1517. return self._dedupe_anon_tq_label_idx(idx)
  1518. else:
  1519. return self._anon_label(label, add_hash=idx)
  1520. @util.memoized_property
  1521. def _anon_tq_label(self) -> _anonymous_label:
  1522. return self._anon_label(getattr(self, "_tq_label", None))
  1523. @util.memoized_property
  1524. def _anon_tq_key_label(self) -> _anonymous_label:
  1525. return self._anon_label(getattr(self, "_tq_key_label", None))
  1526. def _dedupe_anon_tq_label_idx(self, idx: int) -> _anonymous_label:
  1527. label = getattr(self, "_tq_label", None) or "anon"
  1528. return self._anon_label(label, add_hash=idx)
  1529. class KeyedColumnElement(ColumnElement[_T]):
  1530. """ColumnElement where ``.key`` is non-None."""
  1531. _is_keyed_column_element = True
  1532. key: str
  1533. class WrapsColumnExpression(ColumnElement[_T]):
  1534. """Mixin that defines a :class:`_expression.ColumnElement`
  1535. as a wrapper with special
  1536. labeling behavior for an expression that already has a name.
  1537. .. versionadded:: 1.4
  1538. .. seealso::
  1539. :ref:`change_4449`
  1540. """
  1541. @property
  1542. def wrapped_column_expression(self) -> ColumnElement[_T]:
  1543. raise NotImplementedError()
  1544. @util.non_memoized_property
  1545. def _tq_label(self) -> Optional[str]:
  1546. wce = self.wrapped_column_expression
  1547. if hasattr(wce, "_tq_label"):
  1548. return wce._tq_label
  1549. else:
  1550. return None
  1551. @property
  1552. def _label(self) -> Optional[str]:
  1553. return self._tq_label
  1554. @property
  1555. def _non_anon_label(self) -> Optional[str]:
  1556. return None
  1557. @util.non_memoized_property
  1558. def _anon_name_label(self) -> str:
  1559. wce = self.wrapped_column_expression
  1560. # this logic tries to get the WrappedColumnExpression to render
  1561. # with "<expr> AS <name>", where "<name>" is the natural name
  1562. # within the expression itself. e.g. "CAST(table.foo) AS foo".
  1563. if not wce._is_text_clause:
  1564. nal = wce._non_anon_label
  1565. if nal:
  1566. return nal
  1567. elif hasattr(wce, "_anon_name_label"):
  1568. return wce._anon_name_label
  1569. return super()._anon_name_label
  1570. def _dedupe_anon_label_idx(self, idx: int) -> str:
  1571. wce = self.wrapped_column_expression
  1572. nal = wce._non_anon_label
  1573. if nal:
  1574. return self._anon_label(nal + "_")
  1575. else:
  1576. return self._dedupe_anon_tq_label_idx(idx)
  1577. @property
  1578. def _proxy_key(self):
  1579. wce = self.wrapped_column_expression
  1580. if not wce._is_text_clause:
  1581. return wce._proxy_key
  1582. return super()._proxy_key
  1583. class BindParameter(roles.InElementRole, KeyedColumnElement[_T]):
  1584. r"""Represent a "bound expression".
  1585. :class:`.BindParameter` is invoked explicitly using the
  1586. :func:`.bindparam` function, as in::
  1587. from sqlalchemy import bindparam
  1588. stmt = select(users_table).\
  1589. where(users_table.c.name == bindparam('username'))
  1590. Detailed discussion of how :class:`.BindParameter` is used is
  1591. at :func:`.bindparam`.
  1592. .. seealso::
  1593. :func:`.bindparam`
  1594. """
  1595. __visit_name__ = "bindparam"
  1596. _traverse_internals: _TraverseInternalsType = [
  1597. ("key", InternalTraversal.dp_anon_name),
  1598. ("type", InternalTraversal.dp_type),
  1599. ("callable", InternalTraversal.dp_plain_dict),
  1600. ("value", InternalTraversal.dp_plain_obj),
  1601. ("literal_execute", InternalTraversal.dp_boolean),
  1602. ]
  1603. key: str
  1604. type: TypeEngine[_T]
  1605. value: Optional[_T]
  1606. _is_crud = False
  1607. _is_bind_parameter = True
  1608. _key_is_anon = False
  1609. # bindparam implements its own _gen_cache_key() method however
  1610. # we check subclasses for this flag, else no cache key is generated
  1611. inherit_cache = True
  1612. def __init__(
  1613. self,
  1614. key: Optional[str],
  1615. value: Any = _NoArg.NO_ARG,
  1616. type_: Optional[_TypeEngineArgument[_T]] = None,
  1617. unique: bool = False,
  1618. required: Union[bool, Literal[_NoArg.NO_ARG]] = _NoArg.NO_ARG,
  1619. quote: Optional[bool] = None,
  1620. callable_: Optional[Callable[[], Any]] = None,
  1621. expanding: bool = False,
  1622. isoutparam: bool = False,
  1623. literal_execute: bool = False,
  1624. _compared_to_operator: Optional[OperatorType] = None,
  1625. _compared_to_type: Optional[TypeEngine[Any]] = None,
  1626. _is_crud: bool = False,
  1627. ):
  1628. if required is _NoArg.NO_ARG:
  1629. required = value is _NoArg.NO_ARG and callable_ is None
  1630. if value is _NoArg.NO_ARG:
  1631. value = None
  1632. if quote is not None:
  1633. key = quoted_name.construct(key, quote)
  1634. if unique:
  1635. self.key = _anonymous_label.safe_construct(
  1636. id(self),
  1637. key
  1638. if key is not None and not isinstance(key, _anonymous_label)
  1639. else "param",
  1640. sanitize_key=True,
  1641. )
  1642. self._key_is_anon = True
  1643. elif key:
  1644. self.key = key
  1645. else:
  1646. self.key = _anonymous_label.safe_construct(id(self), "param")
  1647. self._key_is_anon = True
  1648. # identifying key that won't change across
  1649. # clones, used to identify the bind's logical
  1650. # identity
  1651. self._identifying_key = self.key
  1652. # key that was passed in the first place, used to
  1653. # generate new keys
  1654. self._orig_key = key or "param"
  1655. self.unique = unique
  1656. self.value = value
  1657. self.callable = callable_
  1658. self.isoutparam = isoutparam
  1659. self.required = required
  1660. # indicate an "expanding" parameter; the compiler sets this
  1661. # automatically in the compiler _render_in_expr_w_bindparam method
  1662. # for an IN expression
  1663. self.expanding = expanding
  1664. # this is another hint to help w/ expanding and is typically
  1665. # set in the compiler _render_in_expr_w_bindparam method for an
  1666. # IN expression
  1667. self.expand_op = None
  1668. self.literal_execute = literal_execute
  1669. if _is_crud:
  1670. self._is_crud = True
  1671. if type_ is None:
  1672. if expanding:
  1673. if value:
  1674. check_value = value[0]
  1675. else:
  1676. check_value = type_api._NO_VALUE_IN_LIST
  1677. else:
  1678. check_value = value
  1679. if _compared_to_type is not None:
  1680. self.type = _compared_to_type.coerce_compared_value(
  1681. _compared_to_operator, check_value
  1682. )
  1683. else:
  1684. self.type = type_api._resolve_value_to_type(check_value)
  1685. elif isinstance(type_, type):
  1686. self.type = type_()
  1687. elif is_tuple_type(type_):
  1688. if value:
  1689. if expanding:
  1690. check_value = value[0]
  1691. else:
  1692. check_value = value
  1693. cast(
  1694. "BindParameter[typing_Tuple[Any, ...]]", self
  1695. ).type = type_._resolve_values_to_types(check_value)
  1696. else:
  1697. cast(
  1698. "BindParameter[typing_Tuple[Any, ...]]", self
  1699. ).type = type_
  1700. else:
  1701. self.type = type_
  1702. def _with_value(self, value, maintain_key=False, required=NO_ARG):
  1703. """Return a copy of this :class:`.BindParameter` with the given value
  1704. set.
  1705. """
  1706. cloned = self._clone(maintain_key=maintain_key)
  1707. cloned.value = value
  1708. cloned.callable = None
  1709. cloned.required = required if required is not NO_ARG else self.required
  1710. if cloned.type is type_api.NULLTYPE:
  1711. cloned.type = type_api._resolve_value_to_type(value)
  1712. return cloned
  1713. @property
  1714. def effective_value(self) -> Optional[_T]:
  1715. """Return the value of this bound parameter,
  1716. taking into account if the ``callable`` parameter
  1717. was set.
  1718. The ``callable`` value will be evaluated
  1719. and returned if present, else ``value``.
  1720. """
  1721. if self.callable:
  1722. # TODO: set up protocol for bind parameter callable
  1723. return self.callable() # type: ignore
  1724. else:
  1725. return self.value
  1726. def render_literal_execute(self) -> BindParameter[_T]:
  1727. """Produce a copy of this bound parameter that will enable the
  1728. :paramref:`_sql.BindParameter.literal_execute` flag.
  1729. The :paramref:`_sql.BindParameter.literal_execute` flag will
  1730. have the effect of the parameter rendered in the compiled SQL
  1731. string using ``[POSTCOMPILE]`` form, which is a special form that
  1732. is converted to be a rendering of the literal value of the parameter
  1733. at SQL execution time. The rationale is to support caching
  1734. of SQL statement strings that can embed per-statement literal values,
  1735. such as LIMIT and OFFSET parameters, in the final SQL string that
  1736. is passed to the DBAPI. Dialects in particular may want to use
  1737. this method within custom compilation schemes.
  1738. .. versionadded:: 1.4.5
  1739. .. seealso::
  1740. :ref:`engine_thirdparty_caching`
  1741. """
  1742. c = ClauseElement._clone(self)
  1743. c.literal_execute = True
  1744. return c
  1745. def _negate_in_binary(self, negated_op, original_op):
  1746. if self.expand_op is original_op:
  1747. bind = self._clone()
  1748. bind.expand_op = negated_op
  1749. return bind
  1750. else:
  1751. return self
  1752. def _with_binary_element_type(self, type_):
  1753. c = ClauseElement._clone(self)
  1754. c.type = type_
  1755. return c
  1756. def _clone(self, maintain_key: bool = False, **kw: Any) -> Self:
  1757. c = ClauseElement._clone(self, **kw)
  1758. # ensure all the BindParameter objects stay in cloned set.
  1759. # in #7823, we changed "clone" so that a clone only keeps a reference
  1760. # to the "original" element, since for column correspondence, that's
  1761. # all we need. However, for BindParam, _cloned_set is used by
  1762. # the "cache key bind match" lookup, which means if any of those
  1763. # interim BindParameter objects became part of a cache key in the
  1764. # cache, we need it. So here, make sure all clones keep carrying
  1765. # forward.
  1766. c._cloned_set.update(self._cloned_set)
  1767. if not maintain_key and self.unique:
  1768. c.key = _anonymous_label.safe_construct(
  1769. id(c), c._orig_key or "param", sanitize_key=True
  1770. )
  1771. return c
  1772. def _gen_cache_key(self, anon_map, bindparams):
  1773. _gen_cache_ok = self.__class__.__dict__.get("inherit_cache", False)
  1774. if not _gen_cache_ok:
  1775. if anon_map is not None:
  1776. anon_map[NO_CACHE] = True
  1777. return None
  1778. id_, found = anon_map.get_anon(self)
  1779. if found:
  1780. return (id_, self.__class__)
  1781. if bindparams is not None:
  1782. bindparams.append(self)
  1783. return (
  1784. id_,
  1785. self.__class__,
  1786. self.type._static_cache_key,
  1787. self.key % anon_map if self._key_is_anon else self.key,
  1788. self.literal_execute,
  1789. )
  1790. def _convert_to_unique(self):
  1791. if not self.unique:
  1792. self.unique = True
  1793. self.key = _anonymous_label.safe_construct(
  1794. id(self), self._orig_key or "param", sanitize_key=True
  1795. )
  1796. def __getstate__(self):
  1797. """execute a deferred value for serialization purposes."""
  1798. d = self.__dict__.copy()
  1799. v = self.value
  1800. if self.callable:
  1801. v = self.callable()
  1802. d["callable"] = None
  1803. d["value"] = v
  1804. return d
  1805. def __setstate__(self, state):
  1806. if state.get("unique", False):
  1807. state["key"] = _anonymous_label.safe_construct(
  1808. id(self), state.get("_orig_key", "param"), sanitize_key=True
  1809. )
  1810. self.__dict__.update(state)
  1811. def __repr__(self):
  1812. return "%s(%r, %r, type_=%r)" % (
  1813. self.__class__.__name__,
  1814. self.key,
  1815. self.value,
  1816. self.type,
  1817. )
  1818. class TypeClause(DQLDMLClauseElement):
  1819. """Handle a type keyword in a SQL statement.
  1820. Used by the ``Case`` statement.
  1821. """
  1822. __visit_name__ = "typeclause"
  1823. _traverse_internals: _TraverseInternalsType = [
  1824. ("type", InternalTraversal.dp_type)
  1825. ]
  1826. def __init__(self, type_):
  1827. self.type = type_
  1828. class TextClause(
  1829. roles.DDLConstraintColumnRole,
  1830. roles.DDLExpressionRole,
  1831. roles.StatementOptionRole,
  1832. roles.WhereHavingRole,
  1833. roles.OrderByRole,
  1834. roles.FromClauseRole,
  1835. roles.SelectStatementRole,
  1836. roles.InElementRole,
  1837. Generative,
  1838. Executable,
  1839. DQLDMLClauseElement,
  1840. roles.BinaryElementRole[Any],
  1841. inspection.Inspectable["TextClause"],
  1842. ):
  1843. """Represent a literal SQL text fragment.
  1844. E.g.::
  1845. from sqlalchemy import text
  1846. t = text("SELECT * FROM users")
  1847. result = connection.execute(t)
  1848. The :class:`_expression.TextClause` construct is produced using the
  1849. :func:`_expression.text`
  1850. function; see that function for full documentation.
  1851. .. seealso::
  1852. :func:`_expression.text`
  1853. """
  1854. __visit_name__ = "textclause"
  1855. _traverse_internals: _TraverseInternalsType = [
  1856. ("_bindparams", InternalTraversal.dp_string_clauseelement_dict),
  1857. ("text", InternalTraversal.dp_string),
  1858. ]
  1859. _is_text_clause = True
  1860. _is_textual = True
  1861. _bind_params_regex = re.compile(r"(?<![:\w\x5c]):(\w+)(?!:)", re.UNICODE)
  1862. _is_implicitly_boolean = False
  1863. _render_label_in_columns_clause = False
  1864. _omit_from_statements = False
  1865. _is_collection_aggregate = False
  1866. @property
  1867. def _hide_froms(self) -> Iterable[FromClause]:
  1868. return ()
  1869. def __and__(self, other):
  1870. # support use in select.where(), query.filter()
  1871. return and_(self, other)
  1872. @property
  1873. def _select_iterable(self) -> _SelectIterable:
  1874. return (self,)
  1875. # help in those cases where text() is
  1876. # interpreted in a column expression situation
  1877. key: Optional[str] = None
  1878. _label: Optional[str] = None
  1879. _allow_label_resolve = False
  1880. @property
  1881. def _is_star(self):
  1882. return self.text == "*"
  1883. def __init__(self, text: str):
  1884. self._bindparams: Dict[str, BindParameter[Any]] = {}
  1885. def repl(m):
  1886. self._bindparams[m.group(1)] = BindParameter(m.group(1))
  1887. return ":%s" % m.group(1)
  1888. # scan the string and search for bind parameter names, add them
  1889. # to the list of bindparams
  1890. self.text = self._bind_params_regex.sub(repl, text)
  1891. @_generative
  1892. def bindparams(
  1893. self,
  1894. *binds: BindParameter[Any],
  1895. **names_to_values: Any,
  1896. ) -> Self:
  1897. """Establish the values and/or types of bound parameters within
  1898. this :class:`_expression.TextClause` construct.
  1899. Given a text construct such as::
  1900. from sqlalchemy import text
  1901. stmt = text("SELECT id, name FROM user WHERE name=:name "
  1902. "AND timestamp=:timestamp")
  1903. the :meth:`_expression.TextClause.bindparams`
  1904. method can be used to establish
  1905. the initial value of ``:name`` and ``:timestamp``,
  1906. using simple keyword arguments::
  1907. stmt = stmt.bindparams(name='jack',
  1908. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
  1909. Where above, new :class:`.BindParameter` objects
  1910. will be generated with the names ``name`` and ``timestamp``, and
  1911. values of ``jack`` and ``datetime.datetime(2012, 10, 8, 15, 12, 5)``,
  1912. respectively. The types will be
  1913. inferred from the values given, in this case :class:`.String` and
  1914. :class:`.DateTime`.
  1915. When specific typing behavior is needed, the positional ``*binds``
  1916. argument can be used in which to specify :func:`.bindparam` constructs
  1917. directly. These constructs must include at least the ``key``
  1918. argument, then an optional value and type::
  1919. from sqlalchemy import bindparam
  1920. stmt = stmt.bindparams(
  1921. bindparam('name', value='jack', type_=String),
  1922. bindparam('timestamp', type_=DateTime)
  1923. )
  1924. Above, we specified the type of :class:`.DateTime` for the
  1925. ``timestamp`` bind, and the type of :class:`.String` for the ``name``
  1926. bind. In the case of ``name`` we also set the default value of
  1927. ``"jack"``.
  1928. Additional bound parameters can be supplied at statement execution
  1929. time, e.g.::
  1930. result = connection.execute(stmt,
  1931. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5))
  1932. The :meth:`_expression.TextClause.bindparams`
  1933. method can be called repeatedly,
  1934. where it will re-use existing :class:`.BindParameter` objects to add
  1935. new information. For example, we can call
  1936. :meth:`_expression.TextClause.bindparams`
  1937. first with typing information, and a
  1938. second time with value information, and it will be combined::
  1939. stmt = text("SELECT id, name FROM user WHERE name=:name "
  1940. "AND timestamp=:timestamp")
  1941. stmt = stmt.bindparams(
  1942. bindparam('name', type_=String),
  1943. bindparam('timestamp', type_=DateTime)
  1944. )
  1945. stmt = stmt.bindparams(
  1946. name='jack',
  1947. timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
  1948. )
  1949. The :meth:`_expression.TextClause.bindparams`
  1950. method also supports the concept of
  1951. **unique** bound parameters. These are parameters that are
  1952. "uniquified" on name at statement compilation time, so that multiple
  1953. :func:`_expression.text`
  1954. constructs may be combined together without the names
  1955. conflicting. To use this feature, specify the
  1956. :paramref:`.BindParameter.unique` flag on each :func:`.bindparam`
  1957. object::
  1958. stmt1 = text("select id from table where name=:name").bindparams(
  1959. bindparam("name", value='name1', unique=True)
  1960. )
  1961. stmt2 = text("select id from table where name=:name").bindparams(
  1962. bindparam("name", value='name2', unique=True)
  1963. )
  1964. union = union_all(
  1965. stmt1.columns(column("id")),
  1966. stmt2.columns(column("id"))
  1967. )
  1968. The above statement will render as::
  1969. select id from table where name=:name_1
  1970. UNION ALL select id from table where name=:name_2
  1971. .. versionadded:: 1.3.11 Added support for the
  1972. :paramref:`.BindParameter.unique` flag to work with
  1973. :func:`_expression.text`
  1974. constructs.
  1975. """
  1976. self._bindparams = new_params = self._bindparams.copy()
  1977. for bind in binds:
  1978. try:
  1979. # the regex used for text() currently will not match
  1980. # a unique/anonymous key in any case, so use the _orig_key
  1981. # so that a text() construct can support unique parameters
  1982. existing = new_params[bind._orig_key]
  1983. except KeyError as err:
  1984. raise exc.ArgumentError(
  1985. "This text() construct doesn't define a "
  1986. "bound parameter named %r" % bind._orig_key
  1987. ) from err
  1988. else:
  1989. new_params[existing._orig_key] = bind
  1990. for key, value in names_to_values.items():
  1991. try:
  1992. existing = new_params[key]
  1993. except KeyError as err:
  1994. raise exc.ArgumentError(
  1995. "This text() construct doesn't define a "
  1996. "bound parameter named %r" % key
  1997. ) from err
  1998. else:
  1999. new_params[key] = existing._with_value(value, required=False)
  2000. return self
  2001. @util.preload_module("sqlalchemy.sql.selectable")
  2002. def columns(
  2003. self, *cols: _ColumnExpressionArgument[Any], **types: TypeEngine[Any]
  2004. ) -> TextualSelect:
  2005. r"""Turn this :class:`_expression.TextClause` object into a
  2006. :class:`_expression.TextualSelect`
  2007. object that serves the same role as a SELECT
  2008. statement.
  2009. The :class:`_expression.TextualSelect` is part of the
  2010. :class:`_expression.SelectBase`
  2011. hierarchy and can be embedded into another statement by using the
  2012. :meth:`_expression.TextualSelect.subquery` method to produce a
  2013. :class:`.Subquery`
  2014. object, which can then be SELECTed from.
  2015. This function essentially bridges the gap between an entirely
  2016. textual SELECT statement and the SQL expression language concept
  2017. of a "selectable"::
  2018. from sqlalchemy.sql import column, text
  2019. stmt = text("SELECT id, name FROM some_table")
  2020. stmt = stmt.columns(column('id'), column('name')).subquery('st')
  2021. stmt = select(mytable).\
  2022. select_from(
  2023. mytable.join(stmt, mytable.c.name == stmt.c.name)
  2024. ).where(stmt.c.id > 5)
  2025. Above, we pass a series of :func:`_expression.column` elements to the
  2026. :meth:`_expression.TextClause.columns` method positionally. These
  2027. :func:`_expression.column`
  2028. elements now become first class elements upon the
  2029. :attr:`_expression.TextualSelect.selected_columns` column collection,
  2030. which then
  2031. become part of the :attr:`.Subquery.c` collection after
  2032. :meth:`_expression.TextualSelect.subquery` is invoked.
  2033. The column expressions we pass to
  2034. :meth:`_expression.TextClause.columns` may
  2035. also be typed; when we do so, these :class:`.TypeEngine` objects become
  2036. the effective return type of the column, so that SQLAlchemy's
  2037. result-set-processing systems may be used on the return values.
  2038. This is often needed for types such as date or boolean types, as well
  2039. as for unicode processing on some dialect configurations::
  2040. stmt = text("SELECT id, name, timestamp FROM some_table")
  2041. stmt = stmt.columns(
  2042. column('id', Integer),
  2043. column('name', Unicode),
  2044. column('timestamp', DateTime)
  2045. )
  2046. for id, name, timestamp in connection.execute(stmt):
  2047. print(id, name, timestamp)
  2048. As a shortcut to the above syntax, keyword arguments referring to
  2049. types alone may be used, if only type conversion is needed::
  2050. stmt = text("SELECT id, name, timestamp FROM some_table")
  2051. stmt = stmt.columns(
  2052. id=Integer,
  2053. name=Unicode,
  2054. timestamp=DateTime
  2055. )
  2056. for id, name, timestamp in connection.execute(stmt):
  2057. print(id, name, timestamp)
  2058. The positional form of :meth:`_expression.TextClause.columns`
  2059. also provides the
  2060. unique feature of **positional column targeting**, which is
  2061. particularly useful when using the ORM with complex textual queries. If
  2062. we specify the columns from our model to
  2063. :meth:`_expression.TextClause.columns`,
  2064. the result set will match to those columns positionally, meaning the
  2065. name or origin of the column in the textual SQL doesn't matter::
  2066. stmt = text("SELECT users.id, addresses.id, users.id, "
  2067. "users.name, addresses.email_address AS email "
  2068. "FROM users JOIN addresses ON users.id=addresses.user_id "
  2069. "WHERE users.id = 1").columns(
  2070. User.id,
  2071. Address.id,
  2072. Address.user_id,
  2073. User.name,
  2074. Address.email_address
  2075. )
  2076. query = session.query(User).from_statement(stmt).options(
  2077. contains_eager(User.addresses))
  2078. The :meth:`_expression.TextClause.columns` method provides a direct
  2079. route to calling :meth:`_expression.FromClause.subquery` as well as
  2080. :meth:`_expression.SelectBase.cte`
  2081. against a textual SELECT statement::
  2082. stmt = stmt.columns(id=Integer, name=String).cte('st')
  2083. stmt = select(sometable).where(sometable.c.id == stmt.c.id)
  2084. :param \*cols: A series of :class:`_expression.ColumnElement` objects,
  2085. typically
  2086. :class:`_schema.Column` objects from a :class:`_schema.Table`
  2087. or ORM level
  2088. column-mapped attributes, representing a set of columns that this
  2089. textual string will SELECT from.
  2090. :param \**types: A mapping of string names to :class:`.TypeEngine`
  2091. type objects indicating the datatypes to use for names that are
  2092. SELECTed from the textual string. Prefer to use the ``*cols``
  2093. argument as it also indicates positional ordering.
  2094. """
  2095. selectable = util.preloaded.sql_selectable
  2096. input_cols: List[NamedColumn[Any]] = [
  2097. coercions.expect(roles.LabeledColumnExprRole, col) for col in cols
  2098. ]
  2099. positional_input_cols = [
  2100. ColumnClause(col.key, types.pop(col.key))
  2101. if col.key in types
  2102. else col
  2103. for col in input_cols
  2104. ]
  2105. keyed_input_cols: List[NamedColumn[Any]] = [
  2106. ColumnClause(key, type_) for key, type_ in types.items()
  2107. ]
  2108. elem = selectable.TextualSelect.__new__(selectable.TextualSelect)
  2109. elem._init(
  2110. self,
  2111. positional_input_cols + keyed_input_cols,
  2112. positional=bool(positional_input_cols) and not keyed_input_cols,
  2113. )
  2114. return elem
  2115. @property
  2116. def type(self) -> TypeEngine[Any]:
  2117. return type_api.NULLTYPE
  2118. @property
  2119. def comparator(self):
  2120. # TODO: this seems wrong, it seems like we might not
  2121. # be using this method.
  2122. return self.type.comparator_factory(self) # type: ignore
  2123. def self_group(self, against=None):
  2124. if against is operators.in_op:
  2125. return Grouping(self)
  2126. else:
  2127. return self
  2128. class Null(SingletonConstant, roles.ConstExprRole[None], ColumnElement[None]):
  2129. """Represent the NULL keyword in a SQL statement.
  2130. :class:`.Null` is accessed as a constant via the
  2131. :func:`.null` function.
  2132. """
  2133. __visit_name__ = "null"
  2134. _traverse_internals: _TraverseInternalsType = []
  2135. _singleton: Null
  2136. if not TYPE_CHECKING:
  2137. @util.memoized_property
  2138. def type(self) -> TypeEngine[_T]: # noqa: A001
  2139. return type_api.NULLTYPE
  2140. @classmethod
  2141. def _instance(cls) -> Null:
  2142. """Return a constant :class:`.Null` construct."""
  2143. return Null._singleton
  2144. Null._create_singleton()
  2145. class False_(
  2146. SingletonConstant, roles.ConstExprRole[bool], ColumnElement[bool]
  2147. ):
  2148. """Represent the ``false`` keyword, or equivalent, in a SQL statement.
  2149. :class:`.False_` is accessed as a constant via the
  2150. :func:`.false` function.
  2151. """
  2152. __visit_name__ = "false"
  2153. _traverse_internals: _TraverseInternalsType = []
  2154. _singleton: False_
  2155. if not TYPE_CHECKING:
  2156. @util.memoized_property
  2157. def type(self) -> TypeEngine[_T]: # noqa: A001
  2158. return type_api.BOOLEANTYPE
  2159. def _negate(self) -> True_:
  2160. return True_._singleton
  2161. @classmethod
  2162. def _instance(cls) -> False_:
  2163. return False_._singleton
  2164. False_._create_singleton()
  2165. class True_(SingletonConstant, roles.ConstExprRole[bool], ColumnElement[bool]):
  2166. """Represent the ``true`` keyword, or equivalent, in a SQL statement.
  2167. :class:`.True_` is accessed as a constant via the
  2168. :func:`.true` function.
  2169. """
  2170. __visit_name__ = "true"
  2171. _traverse_internals: _TraverseInternalsType = []
  2172. _singleton: True_
  2173. if not TYPE_CHECKING:
  2174. @util.memoized_property
  2175. def type(self) -> TypeEngine[_T]: # noqa: A001
  2176. return type_api.BOOLEANTYPE
  2177. def _negate(self) -> False_:
  2178. return False_._singleton
  2179. @classmethod
  2180. def _ifnone(
  2181. cls, other: Optional[ColumnElement[Any]]
  2182. ) -> ColumnElement[Any]:
  2183. if other is None:
  2184. return cls._instance()
  2185. else:
  2186. return other
  2187. @classmethod
  2188. def _instance(cls) -> True_:
  2189. return True_._singleton
  2190. True_._create_singleton()
  2191. class ClauseList(
  2192. roles.InElementRole,
  2193. roles.OrderByRole,
  2194. roles.ColumnsClauseRole,
  2195. roles.DMLColumnRole,
  2196. DQLDMLClauseElement,
  2197. ):
  2198. """Describe a list of clauses, separated by an operator.
  2199. By default, is comma-separated, such as a column listing.
  2200. """
  2201. __visit_name__ = "clauselist"
  2202. # this is used only by the ORM in a legacy use case for
  2203. # composite attributes
  2204. _is_clause_list = True
  2205. _traverse_internals: _TraverseInternalsType = [
  2206. ("clauses", InternalTraversal.dp_clauseelement_list),
  2207. ("operator", InternalTraversal.dp_operator),
  2208. ]
  2209. clauses: List[ColumnElement[Any]]
  2210. def __init__(
  2211. self,
  2212. *clauses: _ColumnExpressionArgument[Any],
  2213. operator: OperatorType = operators.comma_op,
  2214. group: bool = True,
  2215. group_contents: bool = True,
  2216. _literal_as_text_role: Type[roles.SQLRole] = roles.WhereHavingRole,
  2217. ):
  2218. self.operator = operator
  2219. self.group = group
  2220. self.group_contents = group_contents
  2221. clauses_iterator: Iterable[_ColumnExpressionArgument[Any]] = clauses
  2222. text_converter_role: Type[roles.SQLRole] = _literal_as_text_role
  2223. self._text_converter_role = text_converter_role
  2224. if self.group_contents:
  2225. self.clauses = [
  2226. coercions.expect(
  2227. text_converter_role, clause, apply_propagate_attrs=self
  2228. ).self_group(against=self.operator)
  2229. for clause in clauses_iterator
  2230. ]
  2231. else:
  2232. self.clauses = [
  2233. coercions.expect(
  2234. text_converter_role, clause, apply_propagate_attrs=self
  2235. )
  2236. for clause in clauses_iterator
  2237. ]
  2238. self._is_implicitly_boolean = operators.is_boolean(self.operator)
  2239. @classmethod
  2240. def _construct_raw(
  2241. cls,
  2242. operator: OperatorType,
  2243. clauses: Optional[Sequence[ColumnElement[Any]]] = None,
  2244. ) -> ClauseList:
  2245. self = cls.__new__(cls)
  2246. self.clauses = list(clauses) if clauses else []
  2247. self.group = True
  2248. self.operator = operator
  2249. self.group_contents = True
  2250. self._is_implicitly_boolean = False
  2251. return self
  2252. def __iter__(self) -> Iterator[ColumnElement[Any]]:
  2253. return iter(self.clauses)
  2254. def __len__(self) -> int:
  2255. return len(self.clauses)
  2256. @property
  2257. def _select_iterable(self) -> _SelectIterable:
  2258. return itertools.chain.from_iterable(
  2259. [elem._select_iterable for elem in self.clauses]
  2260. )
  2261. def append(self, clause):
  2262. if self.group_contents:
  2263. self.clauses.append(
  2264. coercions.expect(self._text_converter_role, clause).self_group(
  2265. against=self.operator
  2266. )
  2267. )
  2268. else:
  2269. self.clauses.append(
  2270. coercions.expect(self._text_converter_role, clause)
  2271. )
  2272. @util.ro_non_memoized_property
  2273. def _from_objects(self) -> List[FromClause]:
  2274. return list(itertools.chain(*[c._from_objects for c in self.clauses]))
  2275. def self_group(self, against=None):
  2276. if self.group and operators.is_precedent(self.operator, against):
  2277. return Grouping(self)
  2278. else:
  2279. return self
  2280. class OperatorExpression(ColumnElement[_T]):
  2281. """base for expressions that contain an operator and operands
  2282. .. versionadded:: 2.0
  2283. """
  2284. operator: OperatorType
  2285. type: TypeEngine[_T]
  2286. group: bool = True
  2287. @property
  2288. def is_comparison(self):
  2289. return operators.is_comparison(self.operator)
  2290. def self_group(self, against=None):
  2291. if (
  2292. self.group
  2293. and operators.is_precedent(self.operator, against)
  2294. or (
  2295. # a negate against a non-boolean operator
  2296. # doesn't make too much sense but we should
  2297. # group for that
  2298. against is operators.inv
  2299. and not operators.is_boolean(self.operator)
  2300. )
  2301. ):
  2302. return Grouping(self)
  2303. else:
  2304. return self
  2305. @property
  2306. def _flattened_operator_clauses(
  2307. self,
  2308. ) -> typing_Tuple[ColumnElement[Any], ...]:
  2309. raise NotImplementedError()
  2310. @classmethod
  2311. def _construct_for_op(
  2312. cls,
  2313. left: ColumnElement[Any],
  2314. right: ColumnElement[Any],
  2315. op: OperatorType,
  2316. *,
  2317. type_: TypeEngine[_T],
  2318. negate: Optional[OperatorType] = None,
  2319. modifiers: Optional[Mapping[str, Any]] = None,
  2320. ) -> OperatorExpression[_T]:
  2321. if operators.is_associative(op):
  2322. assert (
  2323. negate is None
  2324. ), f"negate not supported for associative operator {op}"
  2325. multi = False
  2326. if getattr(
  2327. left, "operator", None
  2328. ) is op and type_._compare_type_affinity(left.type):
  2329. multi = True
  2330. left_flattened = left._flattened_operator_clauses
  2331. else:
  2332. left_flattened = (left,)
  2333. if getattr(
  2334. right, "operator", None
  2335. ) is op and type_._compare_type_affinity(right.type):
  2336. multi = True
  2337. right_flattened = right._flattened_operator_clauses
  2338. else:
  2339. right_flattened = (right,)
  2340. if multi:
  2341. return ExpressionClauseList._construct_for_list(
  2342. op,
  2343. type_,
  2344. *(left_flattened + right_flattened),
  2345. )
  2346. if right._is_collection_aggregate:
  2347. negate = None
  2348. return BinaryExpression(
  2349. left, right, op, type_=type_, negate=negate, modifiers=modifiers
  2350. )
  2351. class ExpressionClauseList(OperatorExpression[_T]):
  2352. """Describe a list of clauses, separated by an operator,
  2353. in a column expression context.
  2354. :class:`.ExpressionClauseList` differs from :class:`.ClauseList` in that
  2355. it represents a column-oriented DQL expression only, not an open ended
  2356. list of anything comma separated.
  2357. .. versionadded:: 2.0
  2358. """
  2359. __visit_name__ = "expression_clauselist"
  2360. _traverse_internals: _TraverseInternalsType = [
  2361. ("clauses", InternalTraversal.dp_clauseelement_tuple),
  2362. ("operator", InternalTraversal.dp_operator),
  2363. ]
  2364. clauses: typing_Tuple[ColumnElement[Any], ...]
  2365. group: bool
  2366. def __init__(
  2367. self,
  2368. operator: OperatorType,
  2369. *clauses: _ColumnExpressionArgument[Any],
  2370. type_: Optional[_TypeEngineArgument[_T]] = None,
  2371. ):
  2372. self.operator = operator
  2373. self.clauses = tuple(
  2374. coercions.expect(
  2375. roles.ExpressionElementRole, clause, apply_propagate_attrs=self
  2376. )
  2377. for clause in clauses
  2378. )
  2379. self._is_implicitly_boolean = operators.is_boolean(self.operator)
  2380. self.type = type_api.to_instance(type_) # type: ignore
  2381. @property
  2382. def _flattened_operator_clauses(
  2383. self,
  2384. ) -> typing_Tuple[ColumnElement[Any], ...]:
  2385. return self.clauses
  2386. def __iter__(self) -> Iterator[ColumnElement[Any]]:
  2387. return iter(self.clauses)
  2388. def __len__(self) -> int:
  2389. return len(self.clauses)
  2390. @property
  2391. def _select_iterable(self) -> _SelectIterable:
  2392. return (self,)
  2393. @util.ro_non_memoized_property
  2394. def _from_objects(self) -> List[FromClause]:
  2395. return list(itertools.chain(*[c._from_objects for c in self.clauses]))
  2396. def _append_inplace(self, clause: ColumnElement[Any]) -> None:
  2397. self.clauses += (clause,)
  2398. @classmethod
  2399. def _construct_for_list(
  2400. cls,
  2401. operator: OperatorType,
  2402. type_: TypeEngine[_T],
  2403. *clauses: ColumnElement[Any],
  2404. group: bool = True,
  2405. ) -> ExpressionClauseList[_T]:
  2406. self = cls.__new__(cls)
  2407. self.group = group
  2408. if group:
  2409. self.clauses = tuple(
  2410. c.self_group(against=operator) for c in clauses
  2411. )
  2412. else:
  2413. self.clauses = clauses
  2414. self.operator = operator
  2415. self.type = type_
  2416. return self
  2417. def _negate(self) -> Any:
  2418. grouped = self.self_group(against=operators.inv)
  2419. assert isinstance(grouped, ColumnElement)
  2420. return UnaryExpression(
  2421. grouped, operator=operators.inv, wraps_column_expression=True
  2422. )
  2423. class BooleanClauseList(ExpressionClauseList[bool]):
  2424. __visit_name__ = "expression_clauselist"
  2425. inherit_cache = True
  2426. def __init__(self, *arg, **kw):
  2427. raise NotImplementedError(
  2428. "BooleanClauseList has a private constructor"
  2429. )
  2430. @classmethod
  2431. def _process_clauses_for_boolean(
  2432. cls,
  2433. operator: OperatorType,
  2434. continue_on: Any,
  2435. skip_on: Any,
  2436. clauses: Iterable[ColumnElement[Any]],
  2437. ) -> typing_Tuple[int, List[ColumnElement[Any]]]:
  2438. has_continue_on = None
  2439. convert_clauses = []
  2440. against = operators._asbool
  2441. lcc = 0
  2442. for clause in clauses:
  2443. if clause is continue_on:
  2444. # instance of continue_on, like and_(x, y, True, z), store it
  2445. # if we didn't find one already, we will use it if there
  2446. # are no other expressions here.
  2447. has_continue_on = clause
  2448. elif clause is skip_on:
  2449. # instance of skip_on, e.g. and_(x, y, False, z), cancels
  2450. # the rest out
  2451. convert_clauses = [clause]
  2452. lcc = 1
  2453. break
  2454. else:
  2455. if not lcc:
  2456. lcc = 1
  2457. else:
  2458. against = operator
  2459. # technically this would be len(convert_clauses) + 1
  2460. # however this only needs to indicate "greater than one"
  2461. lcc = 2
  2462. convert_clauses.append(clause)
  2463. if not convert_clauses and has_continue_on is not None:
  2464. convert_clauses = [has_continue_on]
  2465. lcc = 1
  2466. return lcc, [c.self_group(against=against) for c in convert_clauses]
  2467. @classmethod
  2468. def _construct(
  2469. cls,
  2470. operator: OperatorType,
  2471. continue_on: Any,
  2472. skip_on: Any,
  2473. initial_clause: Any = _NoArg.NO_ARG,
  2474. *clauses: Any,
  2475. **kw: Any,
  2476. ) -> ColumnElement[Any]:
  2477. if initial_clause is _NoArg.NO_ARG:
  2478. # no elements period. deprecated use case. return an empty
  2479. # ClauseList construct that generates nothing unless it has
  2480. # elements added to it.
  2481. name = operator.__name__
  2482. util.warn_deprecated(
  2483. f"Invoking {name}() without arguments is deprecated, and "
  2484. f"will be disallowed in a future release. For an empty "
  2485. f"""{name}() construct, use '{name}({
  2486. 'true()' if continue_on is True_._singleton else 'false()'
  2487. }, *args)' """
  2488. f"""or '{name}({
  2489. 'True' if continue_on is True_._singleton else 'False'
  2490. }, *args)'.""",
  2491. version="1.4",
  2492. )
  2493. return cls._construct_raw(operator)
  2494. lcc, convert_clauses = cls._process_clauses_for_boolean(
  2495. operator,
  2496. continue_on,
  2497. skip_on,
  2498. [
  2499. coercions.expect(roles.WhereHavingRole, clause)
  2500. for clause in util.coerce_generator_arg(
  2501. (initial_clause,) + clauses
  2502. )
  2503. ],
  2504. )
  2505. if lcc > 1:
  2506. # multiple elements. Return regular BooleanClauseList
  2507. # which will link elements against the operator.
  2508. flattened_clauses = itertools.chain.from_iterable(
  2509. (c for c in to_flat._flattened_operator_clauses)
  2510. if getattr(to_flat, "operator", None) is operator
  2511. else (to_flat,)
  2512. for to_flat in convert_clauses
  2513. )
  2514. return cls._construct_raw(operator, flattened_clauses) # type: ignore # noqa: E501
  2515. else:
  2516. assert lcc
  2517. # just one element. return it as a single boolean element,
  2518. # not a list and discard the operator.
  2519. return convert_clauses[0]
  2520. @classmethod
  2521. def _construct_for_whereclause(
  2522. cls, clauses: Iterable[ColumnElement[Any]]
  2523. ) -> Optional[ColumnElement[bool]]:
  2524. operator, continue_on, skip_on = (
  2525. operators.and_,
  2526. True_._singleton,
  2527. False_._singleton,
  2528. )
  2529. lcc, convert_clauses = cls._process_clauses_for_boolean(
  2530. operator,
  2531. continue_on,
  2532. skip_on,
  2533. clauses, # these are assumed to be coerced already
  2534. )
  2535. if lcc > 1:
  2536. # multiple elements. Return regular BooleanClauseList
  2537. # which will link elements against the operator.
  2538. return cls._construct_raw(operator, convert_clauses)
  2539. elif lcc == 1:
  2540. # just one element. return it as a single boolean element,
  2541. # not a list and discard the operator.
  2542. return convert_clauses[0]
  2543. else:
  2544. return None
  2545. @classmethod
  2546. def _construct_raw(
  2547. cls,
  2548. operator: OperatorType,
  2549. clauses: Optional[Sequence[ColumnElement[Any]]] = None,
  2550. ) -> BooleanClauseList:
  2551. self = cls.__new__(cls)
  2552. self.clauses = tuple(clauses) if clauses else ()
  2553. self.group = True
  2554. self.operator = operator
  2555. self.type = type_api.BOOLEANTYPE
  2556. self._is_implicitly_boolean = True
  2557. return self
  2558. @classmethod
  2559. def and_(
  2560. cls,
  2561. initial_clause: Union[
  2562. Literal[True], _ColumnExpressionArgument[bool], _NoArg
  2563. ] = _NoArg.NO_ARG,
  2564. *clauses: _ColumnExpressionArgument[bool],
  2565. ) -> ColumnElement[bool]:
  2566. r"""Produce a conjunction of expressions joined by ``AND``.
  2567. See :func:`_sql.and_` for full documentation.
  2568. """
  2569. return cls._construct(
  2570. operators.and_,
  2571. True_._singleton,
  2572. False_._singleton,
  2573. initial_clause,
  2574. *clauses,
  2575. )
  2576. @classmethod
  2577. def or_(
  2578. cls,
  2579. initial_clause: Union[
  2580. Literal[False], _ColumnExpressionArgument[bool], _NoArg
  2581. ] = _NoArg.NO_ARG,
  2582. *clauses: _ColumnExpressionArgument[bool],
  2583. ) -> ColumnElement[bool]:
  2584. """Produce a conjunction of expressions joined by ``OR``.
  2585. See :func:`_sql.or_` for full documentation.
  2586. """
  2587. return cls._construct(
  2588. operators.or_,
  2589. False_._singleton,
  2590. True_._singleton,
  2591. initial_clause,
  2592. *clauses,
  2593. )
  2594. @property
  2595. def _select_iterable(self) -> _SelectIterable:
  2596. return (self,)
  2597. def self_group(self, against=None):
  2598. if not self.clauses:
  2599. return self
  2600. else:
  2601. return super().self_group(against=against)
  2602. and_ = BooleanClauseList.and_
  2603. or_ = BooleanClauseList.or_
  2604. class Tuple(ClauseList, ColumnElement[typing_Tuple[Any, ...]]):
  2605. """Represent a SQL tuple."""
  2606. __visit_name__ = "tuple"
  2607. _traverse_internals: _TraverseInternalsType = (
  2608. ClauseList._traverse_internals + []
  2609. )
  2610. type: TupleType
  2611. @util.preload_module("sqlalchemy.sql.sqltypes")
  2612. def __init__(
  2613. self,
  2614. *clauses: _ColumnExpressionArgument[Any],
  2615. types: Optional[Sequence[_TypeEngineArgument[Any]]] = None,
  2616. ):
  2617. sqltypes = util.preloaded.sql_sqltypes
  2618. if types is None:
  2619. init_clauses: List[ColumnElement[Any]] = [
  2620. coercions.expect(roles.ExpressionElementRole, c)
  2621. for c in clauses
  2622. ]
  2623. else:
  2624. if len(types) != len(clauses):
  2625. raise exc.ArgumentError(
  2626. "Wrong number of elements for %d-tuple: %r "
  2627. % (len(types), clauses)
  2628. )
  2629. init_clauses = [
  2630. coercions.expect(
  2631. roles.ExpressionElementRole,
  2632. c,
  2633. type_=typ if not typ._isnull else None,
  2634. )
  2635. for typ, c in zip(types, clauses)
  2636. ]
  2637. self.type = sqltypes.TupleType(*[arg.type for arg in init_clauses])
  2638. super().__init__(*init_clauses)
  2639. @property
  2640. def _select_iterable(self) -> _SelectIterable:
  2641. return (self,)
  2642. def _bind_param(self, operator, obj, type_=None, expanding=False):
  2643. if expanding:
  2644. return BindParameter(
  2645. None,
  2646. value=obj,
  2647. _compared_to_operator=operator,
  2648. unique=True,
  2649. expanding=True,
  2650. type_=type_,
  2651. _compared_to_type=self.type,
  2652. )
  2653. else:
  2654. return Tuple(
  2655. *[
  2656. BindParameter(
  2657. None,
  2658. o,
  2659. _compared_to_operator=operator,
  2660. _compared_to_type=compared_to_type,
  2661. unique=True,
  2662. type_=type_,
  2663. )
  2664. for o, compared_to_type in zip(obj, self.type.types)
  2665. ]
  2666. )
  2667. def self_group(self, against=None):
  2668. # Tuple is parenthesized by definition.
  2669. return self
  2670. class Case(ColumnElement[_T]):
  2671. """Represent a ``CASE`` expression.
  2672. :class:`.Case` is produced using the :func:`.case` factory function,
  2673. as in::
  2674. from sqlalchemy import case
  2675. stmt = select(users_table).\
  2676. where(
  2677. case(
  2678. (users_table.c.name == 'wendy', 'W'),
  2679. (users_table.c.name == 'jack', 'J'),
  2680. else_='E'
  2681. )
  2682. )
  2683. Details on :class:`.Case` usage is at :func:`.case`.
  2684. .. seealso::
  2685. :func:`.case`
  2686. """
  2687. __visit_name__ = "case"
  2688. _traverse_internals: _TraverseInternalsType = [
  2689. ("value", InternalTraversal.dp_clauseelement),
  2690. ("whens", InternalTraversal.dp_clauseelement_tuples),
  2691. ("else_", InternalTraversal.dp_clauseelement),
  2692. ]
  2693. # for case(), the type is derived from the whens. so for the moment
  2694. # users would have to cast() the case to get a specific type
  2695. whens: List[typing_Tuple[ColumnElement[bool], ColumnElement[_T]]]
  2696. else_: Optional[ColumnElement[_T]]
  2697. value: Optional[ColumnElement[Any]]
  2698. def __init__(
  2699. self,
  2700. *whens: Union[
  2701. typing_Tuple[_ColumnExpressionArgument[bool], Any],
  2702. Mapping[Any, Any],
  2703. ],
  2704. value: Optional[Any] = None,
  2705. else_: Optional[Any] = None,
  2706. ):
  2707. new_whens: Iterable[Any] = coercions._expression_collection_was_a_list(
  2708. "whens", "case", whens
  2709. )
  2710. try:
  2711. new_whens = util.dictlike_iteritems(new_whens)
  2712. except TypeError:
  2713. pass
  2714. whenlist = [
  2715. (
  2716. coercions.expect(
  2717. roles.ExpressionElementRole,
  2718. c,
  2719. apply_propagate_attrs=self,
  2720. ).self_group(),
  2721. coercions.expect(roles.ExpressionElementRole, r),
  2722. )
  2723. for (c, r) in new_whens
  2724. ]
  2725. if whenlist:
  2726. type_ = whenlist[-1][-1].type
  2727. else:
  2728. type_ = None
  2729. if value is None:
  2730. self.value = None
  2731. else:
  2732. self.value = coercions.expect(roles.ExpressionElementRole, value)
  2733. self.type = cast(_T, type_)
  2734. self.whens = whenlist
  2735. if else_ is not None:
  2736. self.else_ = coercions.expect(roles.ExpressionElementRole, else_)
  2737. else:
  2738. self.else_ = None
  2739. @util.ro_non_memoized_property
  2740. def _from_objects(self) -> List[FromClause]:
  2741. return list(
  2742. itertools.chain(*[x._from_objects for x in self.get_children()])
  2743. )
  2744. class Cast(WrapsColumnExpression[_T]):
  2745. """Represent a ``CAST`` expression.
  2746. :class:`.Cast` is produced using the :func:`.cast` factory function,
  2747. as in::
  2748. from sqlalchemy import cast, Numeric
  2749. stmt = select(cast(product_table.c.unit_price, Numeric(10, 4)))
  2750. Details on :class:`.Cast` usage is at :func:`.cast`.
  2751. .. seealso::
  2752. :ref:`tutorial_casts`
  2753. :func:`.cast`
  2754. :func:`.try_cast`
  2755. :func:`.type_coerce` - an alternative to CAST that coerces the type
  2756. on the Python side only, which is often sufficient to generate the
  2757. correct SQL and data coercion.
  2758. """
  2759. __visit_name__ = "cast"
  2760. _traverse_internals: _TraverseInternalsType = [
  2761. ("clause", InternalTraversal.dp_clauseelement),
  2762. ("type", InternalTraversal.dp_type),
  2763. ]
  2764. clause: ColumnElement[Any]
  2765. type: TypeEngine[_T]
  2766. typeclause: TypeClause
  2767. def __init__(
  2768. self,
  2769. expression: _ColumnExpressionArgument[Any],
  2770. type_: _TypeEngineArgument[_T],
  2771. ):
  2772. self.type = type_api.to_instance(type_)
  2773. self.clause = coercions.expect(
  2774. roles.ExpressionElementRole,
  2775. expression,
  2776. type_=self.type,
  2777. apply_propagate_attrs=self,
  2778. )
  2779. self.typeclause = TypeClause(self.type)
  2780. @util.ro_non_memoized_property
  2781. def _from_objects(self) -> List[FromClause]:
  2782. return self.clause._from_objects
  2783. @property
  2784. def wrapped_column_expression(self):
  2785. return self.clause
  2786. class TryCast(Cast[_T]):
  2787. """Represent a TRY_CAST expression.
  2788. Details on :class:`.TryCast` usage is at :func:`.try_cast`.
  2789. .. seealso::
  2790. :func:`.try_cast`
  2791. :ref:`tutorial_casts`
  2792. """
  2793. __visit_name__ = "try_cast"
  2794. inherit_cache = True
  2795. class TypeCoerce(WrapsColumnExpression[_T]):
  2796. """Represent a Python-side type-coercion wrapper.
  2797. :class:`.TypeCoerce` supplies the :func:`_expression.type_coerce`
  2798. function; see that function for usage details.
  2799. .. seealso::
  2800. :func:`_expression.type_coerce`
  2801. :func:`.cast`
  2802. """
  2803. __visit_name__ = "type_coerce"
  2804. _traverse_internals: _TraverseInternalsType = [
  2805. ("clause", InternalTraversal.dp_clauseelement),
  2806. ("type", InternalTraversal.dp_type),
  2807. ]
  2808. clause: ColumnElement[Any]
  2809. type: TypeEngine[_T]
  2810. def __init__(
  2811. self,
  2812. expression: _ColumnExpressionArgument[Any],
  2813. type_: _TypeEngineArgument[_T],
  2814. ):
  2815. self.type = type_api.to_instance(type_)
  2816. self.clause = coercions.expect(
  2817. roles.ExpressionElementRole,
  2818. expression,
  2819. type_=self.type,
  2820. apply_propagate_attrs=self,
  2821. )
  2822. @util.ro_non_memoized_property
  2823. def _from_objects(self) -> List[FromClause]:
  2824. return self.clause._from_objects
  2825. @HasMemoized.memoized_attribute
  2826. def typed_expression(self):
  2827. if isinstance(self.clause, BindParameter):
  2828. bp = self.clause._clone()
  2829. bp.type = self.type
  2830. return bp
  2831. else:
  2832. return self.clause
  2833. @property
  2834. def wrapped_column_expression(self):
  2835. return self.clause
  2836. def self_group(self, against=None):
  2837. grouped = self.clause.self_group(against=against)
  2838. if grouped is not self.clause:
  2839. return TypeCoerce(grouped, self.type)
  2840. else:
  2841. return self
  2842. class Extract(ColumnElement[int]):
  2843. """Represent a SQL EXTRACT clause, ``extract(field FROM expr)``."""
  2844. __visit_name__ = "extract"
  2845. _traverse_internals: _TraverseInternalsType = [
  2846. ("expr", InternalTraversal.dp_clauseelement),
  2847. ("field", InternalTraversal.dp_string),
  2848. ]
  2849. expr: ColumnElement[Any]
  2850. field: str
  2851. def __init__(self, field: str, expr: _ColumnExpressionArgument[Any]):
  2852. self.type = type_api.INTEGERTYPE
  2853. self.field = field
  2854. self.expr = coercions.expect(roles.ExpressionElementRole, expr)
  2855. @util.ro_non_memoized_property
  2856. def _from_objects(self) -> List[FromClause]:
  2857. return self.expr._from_objects
  2858. class _label_reference(ColumnElement[_T]):
  2859. """Wrap a column expression as it appears in a 'reference' context.
  2860. This expression is any that includes an _order_by_label_element,
  2861. which is a Label, or a DESC / ASC construct wrapping a Label.
  2862. The production of _label_reference() should occur when an expression
  2863. is added to this context; this includes the ORDER BY or GROUP BY of a
  2864. SELECT statement, as well as a few other places, such as the ORDER BY
  2865. within an OVER clause.
  2866. """
  2867. __visit_name__ = "label_reference"
  2868. _traverse_internals: _TraverseInternalsType = [
  2869. ("element", InternalTraversal.dp_clauseelement)
  2870. ]
  2871. element: ColumnElement[_T]
  2872. def __init__(self, element: ColumnElement[_T]):
  2873. self.element = element
  2874. @util.ro_non_memoized_property
  2875. def _from_objects(self) -> List[FromClause]:
  2876. return []
  2877. class _textual_label_reference(ColumnElement[Any]):
  2878. __visit_name__ = "textual_label_reference"
  2879. _traverse_internals: _TraverseInternalsType = [
  2880. ("element", InternalTraversal.dp_string)
  2881. ]
  2882. def __init__(self, element: str):
  2883. self.element = element
  2884. @util.memoized_property
  2885. def _text_clause(self) -> TextClause:
  2886. return TextClause(self.element)
  2887. class UnaryExpression(ColumnElement[_T]):
  2888. """Define a 'unary' expression.
  2889. A unary expression has a single column expression
  2890. and an operator. The operator can be placed on the left
  2891. (where it is called the 'operator') or right (where it is called the
  2892. 'modifier') of the column expression.
  2893. :class:`.UnaryExpression` is the basis for several unary operators
  2894. including those used by :func:`.desc`, :func:`.asc`, :func:`.distinct`,
  2895. :func:`.nulls_first` and :func:`.nulls_last`.
  2896. """
  2897. __visit_name__ = "unary"
  2898. _traverse_internals: _TraverseInternalsType = [
  2899. ("element", InternalTraversal.dp_clauseelement),
  2900. ("operator", InternalTraversal.dp_operator),
  2901. ("modifier", InternalTraversal.dp_operator),
  2902. ]
  2903. element: ClauseElement
  2904. def __init__(
  2905. self,
  2906. element: ColumnElement[Any],
  2907. operator: Optional[OperatorType] = None,
  2908. modifier: Optional[OperatorType] = None,
  2909. type_: Optional[_TypeEngineArgument[_T]] = None,
  2910. wraps_column_expression: bool = False,
  2911. ):
  2912. self.operator = operator
  2913. self.modifier = modifier
  2914. self._propagate_attrs = element._propagate_attrs
  2915. self.element = element.self_group(
  2916. against=self.operator or self.modifier
  2917. )
  2918. # if type is None, we get NULLTYPE, which is our _T. But I don't
  2919. # know how to get the overloads to express that correctly
  2920. self.type = type_api.to_instance(type_) # type: ignore
  2921. self.wraps_column_expression = wraps_column_expression
  2922. @classmethod
  2923. def _create_nulls_first(
  2924. cls,
  2925. column: _ColumnExpressionArgument[_T],
  2926. ) -> UnaryExpression[_T]:
  2927. return UnaryExpression(
  2928. coercions.expect(roles.ByOfRole, column),
  2929. modifier=operators.nulls_first_op,
  2930. wraps_column_expression=False,
  2931. )
  2932. @classmethod
  2933. def _create_nulls_last(
  2934. cls,
  2935. column: _ColumnExpressionArgument[_T],
  2936. ) -> UnaryExpression[_T]:
  2937. return UnaryExpression(
  2938. coercions.expect(roles.ByOfRole, column),
  2939. modifier=operators.nulls_last_op,
  2940. wraps_column_expression=False,
  2941. )
  2942. @classmethod
  2943. def _create_desc(
  2944. cls, column: _ColumnExpressionOrStrLabelArgument[_T]
  2945. ) -> UnaryExpression[_T]:
  2946. return UnaryExpression(
  2947. coercions.expect(roles.ByOfRole, column),
  2948. modifier=operators.desc_op,
  2949. wraps_column_expression=False,
  2950. )
  2951. @classmethod
  2952. def _create_asc(
  2953. cls,
  2954. column: _ColumnExpressionOrStrLabelArgument[_T],
  2955. ) -> UnaryExpression[_T]:
  2956. return UnaryExpression(
  2957. coercions.expect(roles.ByOfRole, column),
  2958. modifier=operators.asc_op,
  2959. wraps_column_expression=False,
  2960. )
  2961. @classmethod
  2962. def _create_distinct(
  2963. cls,
  2964. expr: _ColumnExpressionArgument[_T],
  2965. ) -> UnaryExpression[_T]:
  2966. col_expr: ColumnElement[_T] = coercions.expect(
  2967. roles.ExpressionElementRole, expr
  2968. )
  2969. return UnaryExpression(
  2970. col_expr,
  2971. operator=operators.distinct_op,
  2972. type_=col_expr.type,
  2973. wraps_column_expression=False,
  2974. )
  2975. @classmethod
  2976. def _create_bitwise_not(
  2977. cls,
  2978. expr: _ColumnExpressionArgument[_T],
  2979. ) -> UnaryExpression[_T]:
  2980. col_expr: ColumnElement[_T] = coercions.expect(
  2981. roles.ExpressionElementRole, expr
  2982. )
  2983. return UnaryExpression(
  2984. col_expr,
  2985. operator=operators.bitwise_not_op,
  2986. type_=col_expr.type,
  2987. wraps_column_expression=False,
  2988. )
  2989. @property
  2990. def _order_by_label_element(self) -> Optional[Label[Any]]:
  2991. if self.modifier in (operators.desc_op, operators.asc_op):
  2992. return self.element._order_by_label_element
  2993. else:
  2994. return None
  2995. @util.ro_non_memoized_property
  2996. def _from_objects(self) -> List[FromClause]:
  2997. return self.element._from_objects
  2998. def _negate(self):
  2999. if self.type._type_affinity is type_api.BOOLEANTYPE._type_affinity:
  3000. return UnaryExpression(
  3001. self.self_group(against=operators.inv),
  3002. operator=operators.inv,
  3003. type_=type_api.BOOLEANTYPE,
  3004. wraps_column_expression=self.wraps_column_expression,
  3005. )
  3006. else:
  3007. return ClauseElement._negate(self)
  3008. def self_group(self, against=None):
  3009. if self.operator and operators.is_precedent(self.operator, against):
  3010. return Grouping(self)
  3011. else:
  3012. return self
  3013. class CollectionAggregate(UnaryExpression[_T]):
  3014. """Forms the basis for right-hand collection operator modifiers
  3015. ANY and ALL.
  3016. The ANY and ALL keywords are available in different ways on different
  3017. backends. On PostgreSQL, they only work for an ARRAY type. On
  3018. MySQL, they only work for subqueries.
  3019. """
  3020. inherit_cache = True
  3021. _is_collection_aggregate = True
  3022. @classmethod
  3023. def _create_any(
  3024. cls, expr: _ColumnExpressionArgument[_T]
  3025. ) -> CollectionAggregate[bool]:
  3026. col_expr: ColumnElement[_T] = coercions.expect(
  3027. roles.ExpressionElementRole,
  3028. expr,
  3029. )
  3030. col_expr = col_expr.self_group()
  3031. return CollectionAggregate(
  3032. col_expr,
  3033. operator=operators.any_op,
  3034. type_=type_api.BOOLEANTYPE,
  3035. wraps_column_expression=False,
  3036. )
  3037. @classmethod
  3038. def _create_all(
  3039. cls, expr: _ColumnExpressionArgument[_T]
  3040. ) -> CollectionAggregate[bool]:
  3041. col_expr: ColumnElement[_T] = coercions.expect(
  3042. roles.ExpressionElementRole,
  3043. expr,
  3044. )
  3045. col_expr = col_expr.self_group()
  3046. return CollectionAggregate(
  3047. col_expr,
  3048. operator=operators.all_op,
  3049. type_=type_api.BOOLEANTYPE,
  3050. wraps_column_expression=False,
  3051. )
  3052. # operate and reverse_operate are hardwired to
  3053. # dispatch onto the type comparator directly, so that we can
  3054. # ensure "reversed" behavior.
  3055. def operate(self, op, *other, **kwargs):
  3056. if not operators.is_comparison(op):
  3057. raise exc.ArgumentError(
  3058. "Only comparison operators may be used with ANY/ALL"
  3059. )
  3060. kwargs["reverse"] = True
  3061. return self.comparator.operate(operators.mirror(op), *other, **kwargs)
  3062. def reverse_operate(self, op, other, **kwargs):
  3063. # comparison operators should never call reverse_operate
  3064. assert not operators.is_comparison(op)
  3065. raise exc.ArgumentError(
  3066. "Only comparison operators may be used with ANY/ALL"
  3067. )
  3068. class AsBoolean(WrapsColumnExpression[bool], UnaryExpression[bool]):
  3069. inherit_cache = True
  3070. def __init__(self, element, operator, negate):
  3071. self.element = element
  3072. self.type = type_api.BOOLEANTYPE
  3073. self.operator = operator
  3074. self.negate = negate
  3075. self.modifier = None
  3076. self.wraps_column_expression = True
  3077. self._is_implicitly_boolean = element._is_implicitly_boolean
  3078. @property
  3079. def wrapped_column_expression(self):
  3080. return self.element
  3081. def self_group(self, against=None):
  3082. return self
  3083. def _negate(self):
  3084. if isinstance(self.element, (True_, False_)):
  3085. return self.element._negate()
  3086. else:
  3087. return AsBoolean(self.element, self.negate, self.operator)
  3088. class BinaryExpression(OperatorExpression[_T]):
  3089. """Represent an expression that is ``LEFT <operator> RIGHT``.
  3090. A :class:`.BinaryExpression` is generated automatically
  3091. whenever two column expressions are used in a Python binary expression:
  3092. .. sourcecode:: pycon+sql
  3093. >>> from sqlalchemy.sql import column
  3094. >>> column('a') + column('b')
  3095. <sqlalchemy.sql.expression.BinaryExpression object at 0x101029dd0>
  3096. >>> print(column('a') + column('b'))
  3097. {printsql}a + b
  3098. """
  3099. __visit_name__ = "binary"
  3100. _traverse_internals: _TraverseInternalsType = [
  3101. ("left", InternalTraversal.dp_clauseelement),
  3102. ("right", InternalTraversal.dp_clauseelement),
  3103. ("operator", InternalTraversal.dp_operator),
  3104. ("negate", InternalTraversal.dp_operator),
  3105. ("modifiers", InternalTraversal.dp_plain_dict),
  3106. (
  3107. "type",
  3108. InternalTraversal.dp_type,
  3109. ),
  3110. ]
  3111. _cache_key_traversal = [
  3112. ("left", InternalTraversal.dp_clauseelement),
  3113. ("right", InternalTraversal.dp_clauseelement),
  3114. ("operator", InternalTraversal.dp_operator),
  3115. ("modifiers", InternalTraversal.dp_plain_dict),
  3116. # "type" affects JSON CAST operators, so while redundant in most cases,
  3117. # is needed for that one
  3118. (
  3119. "type",
  3120. InternalTraversal.dp_type,
  3121. ),
  3122. ]
  3123. _is_implicitly_boolean = True
  3124. """Indicates that any database will know this is a boolean expression
  3125. even if the database does not have an explicit boolean datatype.
  3126. """
  3127. modifiers: Optional[Mapping[str, Any]]
  3128. left: ColumnElement[Any]
  3129. right: ColumnElement[Any]
  3130. def __init__(
  3131. self,
  3132. left: ColumnElement[Any],
  3133. right: ColumnElement[Any],
  3134. operator: OperatorType,
  3135. type_: Optional[_TypeEngineArgument[_T]] = None,
  3136. negate: Optional[OperatorType] = None,
  3137. modifiers: Optional[Mapping[str, Any]] = None,
  3138. ):
  3139. # allow compatibility with libraries that
  3140. # refer to BinaryExpression directly and pass strings
  3141. if isinstance(operator, str):
  3142. operator = operators.custom_op(operator)
  3143. self._orig = (left.__hash__(), right.__hash__())
  3144. self._propagate_attrs = left._propagate_attrs or right._propagate_attrs
  3145. self.left = left.self_group(against=operator)
  3146. self.right = right.self_group(against=operator)
  3147. self.operator = operator
  3148. # if type is None, we get NULLTYPE, which is our _T. But I don't
  3149. # know how to get the overloads to express that correctly
  3150. self.type = type_api.to_instance(type_) # type: ignore
  3151. self.negate = negate
  3152. self._is_implicitly_boolean = operators.is_boolean(operator)
  3153. if modifiers is None:
  3154. self.modifiers = {}
  3155. else:
  3156. self.modifiers = modifiers
  3157. @property
  3158. def _flattened_operator_clauses(
  3159. self,
  3160. ) -> typing_Tuple[ColumnElement[Any], ...]:
  3161. return (self.left, self.right)
  3162. def __bool__(self):
  3163. """Implement Python-side "bool" for BinaryExpression as a
  3164. simple "identity" check for the left and right attributes,
  3165. if the operator is "eq" or "ne". Otherwise the expression
  3166. continues to not support "bool" like all other column expressions.
  3167. The rationale here is so that ColumnElement objects can be hashable.
  3168. What? Well, suppose you do this::
  3169. c1, c2 = column('x'), column('y')
  3170. s1 = set([c1, c2])
  3171. We do that **a lot**, columns inside of sets is an extremely basic
  3172. thing all over the ORM for example.
  3173. So what happens if we do this? ::
  3174. c1 in s1
  3175. Hashing means it will normally use ``__hash__()`` of the object,
  3176. but in case of hash collision, it's going to also do ``c1 == c1``
  3177. and/or ``c1 == c2`` inside. Those operations need to return a
  3178. True/False value. But because we override ``==`` and ``!=``, they're
  3179. going to get a BinaryExpression. Hence we implement ``__bool__`` here
  3180. so that these comparisons behave in this particular context mostly
  3181. like regular object comparisons. Thankfully Python is OK with
  3182. that! Otherwise we'd have to use special set classes for columns
  3183. (which we used to do, decades ago).
  3184. """
  3185. if self.operator in (operators.eq, operators.ne):
  3186. # this is using the eq/ne operator given int hash values,
  3187. # rather than Operator, so that "bool" can be based on
  3188. # identity
  3189. return self.operator(*self._orig) # type: ignore
  3190. else:
  3191. raise TypeError("Boolean value of this clause is not defined")
  3192. if typing.TYPE_CHECKING:
  3193. def __invert__(
  3194. self: BinaryExpression[_T],
  3195. ) -> BinaryExpression[_T]:
  3196. ...
  3197. @util.ro_non_memoized_property
  3198. def _from_objects(self) -> List[FromClause]:
  3199. return self.left._from_objects + self.right._from_objects
  3200. def _negate(self):
  3201. if self.negate is not None:
  3202. return BinaryExpression(
  3203. self.left,
  3204. self.right._negate_in_binary(self.negate, self.operator),
  3205. self.negate,
  3206. negate=self.operator,
  3207. type_=self.type,
  3208. modifiers=self.modifiers,
  3209. )
  3210. else:
  3211. return self.self_group()._negate()
  3212. class Slice(ColumnElement[Any]):
  3213. """Represent SQL for a Python array-slice object.
  3214. This is not a specific SQL construct at this level, but
  3215. may be interpreted by specific dialects, e.g. PostgreSQL.
  3216. """
  3217. __visit_name__ = "slice"
  3218. _traverse_internals: _TraverseInternalsType = [
  3219. ("start", InternalTraversal.dp_clauseelement),
  3220. ("stop", InternalTraversal.dp_clauseelement),
  3221. ("step", InternalTraversal.dp_clauseelement),
  3222. ]
  3223. def __init__(self, start, stop, step, _name=None):
  3224. self.start = coercions.expect(
  3225. roles.ExpressionElementRole,
  3226. start,
  3227. name=_name,
  3228. type_=type_api.INTEGERTYPE,
  3229. )
  3230. self.stop = coercions.expect(
  3231. roles.ExpressionElementRole,
  3232. stop,
  3233. name=_name,
  3234. type_=type_api.INTEGERTYPE,
  3235. )
  3236. self.step = coercions.expect(
  3237. roles.ExpressionElementRole,
  3238. step,
  3239. name=_name,
  3240. type_=type_api.INTEGERTYPE,
  3241. )
  3242. self.type = type_api.NULLTYPE
  3243. def self_group(self, against=None):
  3244. assert against is operator.getitem
  3245. return self
  3246. class IndexExpression(BinaryExpression[Any]):
  3247. """Represent the class of expressions that are like an "index"
  3248. operation."""
  3249. inherit_cache = True
  3250. class GroupedElement(DQLDMLClauseElement):
  3251. """Represent any parenthesized expression"""
  3252. __visit_name__ = "grouping"
  3253. element: ClauseElement
  3254. def self_group(self, against=None):
  3255. return self
  3256. def _ungroup(self):
  3257. return self.element._ungroup()
  3258. class Grouping(GroupedElement, ColumnElement[_T]):
  3259. """Represent a grouping within a column expression"""
  3260. _traverse_internals: _TraverseInternalsType = [
  3261. ("element", InternalTraversal.dp_clauseelement),
  3262. ("type", InternalTraversal.dp_type),
  3263. ]
  3264. _cache_key_traversal = [
  3265. ("element", InternalTraversal.dp_clauseelement),
  3266. ]
  3267. element: Union[TextClause, ClauseList, ColumnElement[_T]]
  3268. def __init__(
  3269. self, element: Union[TextClause, ClauseList, ColumnElement[_T]]
  3270. ):
  3271. self.element = element
  3272. # nulltype assignment issue
  3273. self.type = getattr(element, "type", type_api.NULLTYPE) # type: ignore
  3274. self._propagate_attrs = element._propagate_attrs
  3275. def _with_binary_element_type(self, type_):
  3276. return self.__class__(self.element._with_binary_element_type(type_))
  3277. @util.memoized_property
  3278. def _is_implicitly_boolean(self):
  3279. return self.element._is_implicitly_boolean
  3280. @util.non_memoized_property
  3281. def _tq_label(self) -> Optional[str]:
  3282. return (
  3283. getattr(self.element, "_tq_label", None) or self._anon_name_label
  3284. )
  3285. @util.non_memoized_property
  3286. def _proxies(self) -> List[ColumnElement[Any]]:
  3287. if isinstance(self.element, ColumnElement):
  3288. return [self.element]
  3289. else:
  3290. return []
  3291. @util.ro_non_memoized_property
  3292. def _from_objects(self) -> List[FromClause]:
  3293. return self.element._from_objects
  3294. def __getattr__(self, attr):
  3295. return getattr(self.element, attr)
  3296. def __getstate__(self):
  3297. return {"element": self.element, "type": self.type}
  3298. def __setstate__(self, state):
  3299. self.element = state["element"]
  3300. self.type = state["type"]
  3301. class _OverRange(IntEnum):
  3302. RANGE_UNBOUNDED = 0
  3303. RANGE_CURRENT = 1
  3304. RANGE_UNBOUNDED = _OverRange.RANGE_UNBOUNDED
  3305. RANGE_CURRENT = _OverRange.RANGE_CURRENT
  3306. class Over(ColumnElement[_T]):
  3307. """Represent an OVER clause.
  3308. This is a special operator against a so-called
  3309. "window" function, as well as any aggregate function,
  3310. which produces results relative to the result set
  3311. itself. Most modern SQL backends now support window functions.
  3312. """
  3313. __visit_name__ = "over"
  3314. _traverse_internals: _TraverseInternalsType = [
  3315. ("element", InternalTraversal.dp_clauseelement),
  3316. ("order_by", InternalTraversal.dp_clauseelement),
  3317. ("partition_by", InternalTraversal.dp_clauseelement),
  3318. ("range_", InternalTraversal.dp_plain_obj),
  3319. ("rows", InternalTraversal.dp_plain_obj),
  3320. ]
  3321. order_by: Optional[ClauseList] = None
  3322. partition_by: Optional[ClauseList] = None
  3323. element: ColumnElement[_T]
  3324. """The underlying expression object to which this :class:`.Over`
  3325. object refers."""
  3326. range_: Optional[typing_Tuple[int, int]]
  3327. def __init__(
  3328. self,
  3329. element: ColumnElement[_T],
  3330. partition_by: Optional[_ByArgument] = None,
  3331. order_by: Optional[_ByArgument] = None,
  3332. range_: Optional[typing_Tuple[Optional[int], Optional[int]]] = None,
  3333. rows: Optional[typing_Tuple[Optional[int], Optional[int]]] = None,
  3334. ):
  3335. self.element = element
  3336. if order_by is not None:
  3337. self.order_by = ClauseList(
  3338. *util.to_list(order_by), _literal_as_text_role=roles.ByOfRole
  3339. )
  3340. if partition_by is not None:
  3341. self.partition_by = ClauseList(
  3342. *util.to_list(partition_by),
  3343. _literal_as_text_role=roles.ByOfRole,
  3344. )
  3345. if range_:
  3346. self.range_ = self._interpret_range(range_)
  3347. if rows:
  3348. raise exc.ArgumentError(
  3349. "'range_' and 'rows' are mutually exclusive"
  3350. )
  3351. else:
  3352. self.rows = None
  3353. elif rows:
  3354. self.rows = self._interpret_range(rows)
  3355. self.range_ = None
  3356. else:
  3357. self.rows = self.range_ = None
  3358. def __reduce__(self):
  3359. return self.__class__, (
  3360. self.element,
  3361. self.partition_by,
  3362. self.order_by,
  3363. self.range_,
  3364. self.rows,
  3365. )
  3366. def _interpret_range(
  3367. self, range_: typing_Tuple[Optional[int], Optional[int]]
  3368. ) -> typing_Tuple[int, int]:
  3369. if not isinstance(range_, tuple) or len(range_) != 2:
  3370. raise exc.ArgumentError("2-tuple expected for range/rows")
  3371. lower: int
  3372. upper: int
  3373. if range_[0] is None:
  3374. lower = RANGE_UNBOUNDED
  3375. else:
  3376. try:
  3377. lower = int(range_[0])
  3378. except ValueError as err:
  3379. raise exc.ArgumentError(
  3380. "Integer or None expected for range value"
  3381. ) from err
  3382. else:
  3383. if lower == 0:
  3384. lower = RANGE_CURRENT
  3385. if range_[1] is None:
  3386. upper = RANGE_UNBOUNDED
  3387. else:
  3388. try:
  3389. upper = int(range_[1])
  3390. except ValueError as err:
  3391. raise exc.ArgumentError(
  3392. "Integer or None expected for range value"
  3393. ) from err
  3394. else:
  3395. if upper == 0:
  3396. upper = RANGE_CURRENT
  3397. return lower, upper
  3398. if not TYPE_CHECKING:
  3399. @util.memoized_property
  3400. def type(self) -> TypeEngine[_T]: # noqa: A001
  3401. return self.element.type
  3402. @util.ro_non_memoized_property
  3403. def _from_objects(self) -> List[FromClause]:
  3404. return list(
  3405. itertools.chain(
  3406. *[
  3407. c._from_objects
  3408. for c in (self.element, self.partition_by, self.order_by)
  3409. if c is not None
  3410. ]
  3411. )
  3412. )
  3413. class WithinGroup(ColumnElement[_T]):
  3414. """Represent a WITHIN GROUP (ORDER BY) clause.
  3415. This is a special operator against so-called
  3416. "ordered set aggregate" and "hypothetical
  3417. set aggregate" functions, including ``percentile_cont()``,
  3418. ``rank()``, ``dense_rank()``, etc.
  3419. It's supported only by certain database backends, such as PostgreSQL,
  3420. Oracle and MS SQL Server.
  3421. The :class:`.WithinGroup` construct extracts its type from the
  3422. method :meth:`.FunctionElement.within_group_type`. If this returns
  3423. ``None``, the function's ``.type`` is used.
  3424. """
  3425. __visit_name__ = "withingroup"
  3426. _traverse_internals: _TraverseInternalsType = [
  3427. ("element", InternalTraversal.dp_clauseelement),
  3428. ("order_by", InternalTraversal.dp_clauseelement),
  3429. ]
  3430. order_by: Optional[ClauseList] = None
  3431. def __init__(
  3432. self,
  3433. element: FunctionElement[_T],
  3434. *order_by: _ColumnExpressionArgument[Any],
  3435. ):
  3436. self.element = element
  3437. if order_by is not None:
  3438. self.order_by = ClauseList(
  3439. *util.to_list(order_by), _literal_as_text_role=roles.ByOfRole
  3440. )
  3441. def __reduce__(self):
  3442. return self.__class__, (self.element,) + (
  3443. tuple(self.order_by) if self.order_by is not None else ()
  3444. )
  3445. def over(self, partition_by=None, order_by=None, range_=None, rows=None):
  3446. """Produce an OVER clause against this :class:`.WithinGroup`
  3447. construct.
  3448. This function has the same signature as that of
  3449. :meth:`.FunctionElement.over`.
  3450. """
  3451. return Over(
  3452. self,
  3453. partition_by=partition_by,
  3454. order_by=order_by,
  3455. range_=range_,
  3456. rows=rows,
  3457. )
  3458. if not TYPE_CHECKING:
  3459. @util.memoized_property
  3460. def type(self) -> TypeEngine[_T]: # noqa: A001
  3461. wgt = self.element.within_group_type(self)
  3462. if wgt is not None:
  3463. return wgt
  3464. else:
  3465. return self.element.type
  3466. @util.ro_non_memoized_property
  3467. def _from_objects(self) -> List[FromClause]:
  3468. return list(
  3469. itertools.chain(
  3470. *[
  3471. c._from_objects
  3472. for c in (self.element, self.order_by)
  3473. if c is not None
  3474. ]
  3475. )
  3476. )
  3477. class FunctionFilter(ColumnElement[_T]):
  3478. """Represent a function FILTER clause.
  3479. This is a special operator against aggregate and window functions,
  3480. which controls which rows are passed to it.
  3481. It's supported only by certain database backends.
  3482. Invocation of :class:`.FunctionFilter` is via
  3483. :meth:`.FunctionElement.filter`::
  3484. func.count(1).filter(True)
  3485. .. seealso::
  3486. :meth:`.FunctionElement.filter`
  3487. """
  3488. __visit_name__ = "funcfilter"
  3489. _traverse_internals: _TraverseInternalsType = [
  3490. ("func", InternalTraversal.dp_clauseelement),
  3491. ("criterion", InternalTraversal.dp_clauseelement),
  3492. ]
  3493. criterion: Optional[ColumnElement[bool]] = None
  3494. def __init__(
  3495. self,
  3496. func: FunctionElement[_T],
  3497. *criterion: _ColumnExpressionArgument[bool],
  3498. ):
  3499. self.func = func
  3500. self.filter(*criterion)
  3501. def filter(self, *criterion: _ColumnExpressionArgument[bool]) -> Self:
  3502. """Produce an additional FILTER against the function.
  3503. This method adds additional criteria to the initial criteria
  3504. set up by :meth:`.FunctionElement.filter`.
  3505. Multiple criteria are joined together at SQL render time
  3506. via ``AND``.
  3507. """
  3508. for crit in list(criterion):
  3509. crit = coercions.expect(roles.WhereHavingRole, crit)
  3510. if self.criterion is not None:
  3511. self.criterion = self.criterion & crit
  3512. else:
  3513. self.criterion = crit
  3514. return self
  3515. def over(
  3516. self,
  3517. partition_by: Optional[
  3518. Union[
  3519. Iterable[_ColumnExpressionArgument[Any]],
  3520. _ColumnExpressionArgument[Any],
  3521. ]
  3522. ] = None,
  3523. order_by: Optional[
  3524. Union[
  3525. Iterable[_ColumnExpressionArgument[Any]],
  3526. _ColumnExpressionArgument[Any],
  3527. ]
  3528. ] = None,
  3529. range_: Optional[typing_Tuple[Optional[int], Optional[int]]] = None,
  3530. rows: Optional[typing_Tuple[Optional[int], Optional[int]]] = None,
  3531. ) -> Over[_T]:
  3532. """Produce an OVER clause against this filtered function.
  3533. Used against aggregate or so-called "window" functions,
  3534. for database backends that support window functions.
  3535. The expression::
  3536. func.rank().filter(MyClass.y > 5).over(order_by='x')
  3537. is shorthand for::
  3538. from sqlalchemy import over, funcfilter
  3539. over(funcfilter(func.rank(), MyClass.y > 5), order_by='x')
  3540. See :func:`_expression.over` for a full description.
  3541. """
  3542. return Over(
  3543. self,
  3544. partition_by=partition_by,
  3545. order_by=order_by,
  3546. range_=range_,
  3547. rows=rows,
  3548. )
  3549. def self_group(
  3550. self, against: Optional[OperatorType] = None
  3551. ) -> Union[Self, Grouping[_T]]:
  3552. if operators.is_precedent(operators.filter_op, against):
  3553. return Grouping(self)
  3554. else:
  3555. return self
  3556. if not TYPE_CHECKING:
  3557. @util.memoized_property
  3558. def type(self) -> TypeEngine[_T]: # noqa: A001
  3559. return self.func.type
  3560. @util.ro_non_memoized_property
  3561. def _from_objects(self) -> List[FromClause]:
  3562. return list(
  3563. itertools.chain(
  3564. *[
  3565. c._from_objects
  3566. for c in (self.func, self.criterion)
  3567. if c is not None
  3568. ]
  3569. )
  3570. )
  3571. class NamedColumn(KeyedColumnElement[_T]):
  3572. is_literal = False
  3573. table: Optional[FromClause] = None
  3574. name: str
  3575. key: str
  3576. def _compare_name_for_result(self, other):
  3577. return (hasattr(other, "name") and self.name == other.name) or (
  3578. hasattr(other, "_label") and self._label == other._label
  3579. )
  3580. @util.ro_memoized_property
  3581. def description(self) -> str:
  3582. return self.name
  3583. @HasMemoized.memoized_attribute
  3584. def _tq_key_label(self):
  3585. """table qualified label based on column key.
  3586. for table-bound columns this is <tablename>_<column key/proxy key>;
  3587. all other expressions it resolves to key/proxy key.
  3588. """
  3589. proxy_key = self._proxy_key
  3590. if proxy_key and proxy_key != self.name:
  3591. return self._gen_tq_label(proxy_key)
  3592. else:
  3593. return self._tq_label
  3594. @HasMemoized.memoized_attribute
  3595. def _tq_label(self) -> Optional[str]:
  3596. """table qualified label based on column name.
  3597. for table-bound columns this is <tablename>_<columnname>; all other
  3598. expressions it resolves to .name.
  3599. """
  3600. return self._gen_tq_label(self.name)
  3601. @HasMemoized.memoized_attribute
  3602. def _render_label_in_columns_clause(self):
  3603. return True
  3604. @HasMemoized.memoized_attribute
  3605. def _non_anon_label(self):
  3606. return self.name
  3607. def _gen_tq_label(
  3608. self, name: str, dedupe_on_key: bool = True
  3609. ) -> Optional[str]:
  3610. return name
  3611. def _bind_param(
  3612. self,
  3613. operator: OperatorType,
  3614. obj: Any,
  3615. type_: Optional[TypeEngine[_T]] = None,
  3616. expanding: bool = False,
  3617. ) -> BindParameter[_T]:
  3618. return BindParameter(
  3619. self.key,
  3620. obj,
  3621. _compared_to_operator=operator,
  3622. _compared_to_type=self.type,
  3623. type_=type_,
  3624. unique=True,
  3625. expanding=expanding,
  3626. )
  3627. def _make_proxy(
  3628. self,
  3629. selectable: FromClause,
  3630. *,
  3631. name: Optional[str] = None,
  3632. key: Optional[str] = None,
  3633. name_is_truncatable: bool = False,
  3634. compound_select_cols: Optional[Sequence[ColumnElement[Any]]] = None,
  3635. disallow_is_literal: bool = False,
  3636. **kw: Any,
  3637. ) -> typing_Tuple[str, ColumnClause[_T]]:
  3638. c = ColumnClause(
  3639. coercions.expect(roles.TruncatedLabelRole, name or self.name)
  3640. if name_is_truncatable
  3641. else (name or self.name),
  3642. type_=self.type,
  3643. _selectable=selectable,
  3644. is_literal=False,
  3645. )
  3646. c._propagate_attrs = selectable._propagate_attrs
  3647. if name is None:
  3648. c.key = self.key
  3649. if compound_select_cols:
  3650. c._proxies = list(compound_select_cols)
  3651. else:
  3652. c._proxies = [self]
  3653. if selectable._is_clone_of is not None:
  3654. c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
  3655. return c.key, c
  3656. class Label(roles.LabeledColumnExprRole[_T], NamedColumn[_T]):
  3657. """Represents a column label (AS).
  3658. Represent a label, as typically applied to any column-level
  3659. element using the ``AS`` sql keyword.
  3660. """
  3661. __visit_name__ = "label"
  3662. _traverse_internals: _TraverseInternalsType = [
  3663. ("name", InternalTraversal.dp_anon_name),
  3664. ("type", InternalTraversal.dp_type),
  3665. ("_element", InternalTraversal.dp_clauseelement),
  3666. ]
  3667. _cache_key_traversal = [
  3668. ("name", InternalTraversal.dp_anon_name),
  3669. ("_element", InternalTraversal.dp_clauseelement),
  3670. ]
  3671. _element: ColumnElement[_T]
  3672. name: str
  3673. def __init__(
  3674. self,
  3675. name: Optional[str],
  3676. element: _ColumnExpressionArgument[_T],
  3677. type_: Optional[_TypeEngineArgument[_T]] = None,
  3678. ):
  3679. orig_element = element
  3680. element = coercions.expect(
  3681. roles.ExpressionElementRole,
  3682. element,
  3683. apply_propagate_attrs=self,
  3684. )
  3685. while isinstance(element, Label):
  3686. # TODO: this is only covered in test_text.py, but nothing
  3687. # fails if it's removed. determine rationale
  3688. element = element.element
  3689. if name:
  3690. self.name = name
  3691. else:
  3692. self.name = _anonymous_label.safe_construct(
  3693. id(self), getattr(element, "name", "anon")
  3694. )
  3695. if isinstance(orig_element, Label):
  3696. # TODO: no coverage for this block, again would be in
  3697. # test_text.py where the resolve_label concept is important
  3698. self._resolve_label = orig_element._label
  3699. self.key = self._tq_label = self._tq_key_label = self.name
  3700. self._element = element
  3701. self.type = (
  3702. type_api.to_instance(type_)
  3703. if type_ is not None
  3704. else self._element.type
  3705. )
  3706. self._proxies = [element]
  3707. def __reduce__(self):
  3708. return self.__class__, (self.name, self._element, self.type)
  3709. @HasMemoized.memoized_attribute
  3710. def _render_label_in_columns_clause(self):
  3711. return True
  3712. def _bind_param(self, operator, obj, type_=None, expanding=False):
  3713. return BindParameter(
  3714. None,
  3715. obj,
  3716. _compared_to_operator=operator,
  3717. type_=type_,
  3718. _compared_to_type=self.type,
  3719. unique=True,
  3720. expanding=expanding,
  3721. )
  3722. @util.memoized_property
  3723. def _is_implicitly_boolean(self):
  3724. return self.element._is_implicitly_boolean
  3725. @HasMemoized.memoized_attribute
  3726. def _allow_label_resolve(self):
  3727. return self.element._allow_label_resolve
  3728. @property
  3729. def _order_by_label_element(self):
  3730. return self
  3731. @HasMemoized.memoized_attribute
  3732. def element(self) -> ColumnElement[_T]:
  3733. return self._element.self_group(against=operators.as_)
  3734. def self_group(self, against=None):
  3735. return self._apply_to_inner(self._element.self_group, against=against)
  3736. def _negate(self):
  3737. return self._apply_to_inner(self._element._negate)
  3738. def _apply_to_inner(self, fn, *arg, **kw):
  3739. sub_element = fn(*arg, **kw)
  3740. if sub_element is not self._element:
  3741. return Label(self.name, sub_element, type_=self.type)
  3742. else:
  3743. return self
  3744. @property
  3745. def primary_key(self):
  3746. return self.element.primary_key
  3747. @property
  3748. def foreign_keys(self):
  3749. return self.element.foreign_keys
  3750. def _copy_internals(
  3751. self,
  3752. *,
  3753. clone: _CloneCallableType = _clone,
  3754. anonymize_labels: bool = False,
  3755. **kw: Any,
  3756. ) -> None:
  3757. self._reset_memoizations()
  3758. self._element = clone(self._element, **kw)
  3759. if anonymize_labels:
  3760. self.name = _anonymous_label.safe_construct(
  3761. id(self), getattr(self.element, "name", "anon")
  3762. )
  3763. self.key = self._tq_label = self._tq_key_label = self.name
  3764. @util.ro_non_memoized_property
  3765. def _from_objects(self) -> List[FromClause]:
  3766. return self.element._from_objects
  3767. def _make_proxy(
  3768. self,
  3769. selectable: FromClause,
  3770. *,
  3771. name: Optional[str] = None,
  3772. compound_select_cols: Optional[Sequence[ColumnElement[Any]]] = None,
  3773. **kw: Any,
  3774. ) -> typing_Tuple[str, ColumnClause[_T]]:
  3775. name = self.name if not name else name
  3776. key, e = self.element._make_proxy(
  3777. selectable,
  3778. name=name,
  3779. disallow_is_literal=True,
  3780. name_is_truncatable=isinstance(name, _truncated_label),
  3781. compound_select_cols=compound_select_cols,
  3782. )
  3783. # there was a note here to remove this assertion, which was here
  3784. # to determine if we later could support a use case where
  3785. # the key and name of a label are separate. But I don't know what
  3786. # that case was. For now, this is an unexpected case that occurs
  3787. # when a label name conflicts with other columns and select()
  3788. # is attempting to disambiguate an explicit label, which is not what
  3789. # the user would want. See issue #6090.
  3790. if key != self.name and not isinstance(self.name, _anonymous_label):
  3791. raise exc.InvalidRequestError(
  3792. "Label name %s is being renamed to an anonymous label due "
  3793. "to disambiguation "
  3794. "which is not supported right now. Please use unique names "
  3795. "for explicit labels." % (self.name)
  3796. )
  3797. e._propagate_attrs = selectable._propagate_attrs
  3798. e._proxies.append(self)
  3799. if self.type is not None:
  3800. e.type = self.type
  3801. return self.key, e
  3802. class ColumnClause(
  3803. roles.DDLReferredColumnRole,
  3804. roles.LabeledColumnExprRole[_T],
  3805. roles.StrAsPlainColumnRole,
  3806. Immutable,
  3807. NamedColumn[_T],
  3808. ):
  3809. """Represents a column expression from any textual string.
  3810. The :class:`.ColumnClause`, a lightweight analogue to the
  3811. :class:`_schema.Column` class, is typically invoked using the
  3812. :func:`_expression.column` function, as in::
  3813. from sqlalchemy import column
  3814. id, name = column("id"), column("name")
  3815. stmt = select(id, name).select_from("user")
  3816. The above statement would produce SQL like::
  3817. SELECT id, name FROM user
  3818. :class:`.ColumnClause` is the immediate superclass of the schema-specific
  3819. :class:`_schema.Column` object. While the :class:`_schema.Column`
  3820. class has all the
  3821. same capabilities as :class:`.ColumnClause`, the :class:`.ColumnClause`
  3822. class is usable by itself in those cases where behavioral requirements
  3823. are limited to simple SQL expression generation. The object has none of
  3824. the associations with schema-level metadata or with execution-time
  3825. behavior that :class:`_schema.Column` does,
  3826. so in that sense is a "lightweight"
  3827. version of :class:`_schema.Column`.
  3828. Full details on :class:`.ColumnClause` usage is at
  3829. :func:`_expression.column`.
  3830. .. seealso::
  3831. :func:`_expression.column`
  3832. :class:`_schema.Column`
  3833. """
  3834. table: Optional[FromClause]
  3835. is_literal: bool
  3836. __visit_name__ = "column"
  3837. _traverse_internals: _TraverseInternalsType = [
  3838. ("name", InternalTraversal.dp_anon_name),
  3839. ("type", InternalTraversal.dp_type),
  3840. ("table", InternalTraversal.dp_clauseelement),
  3841. ("is_literal", InternalTraversal.dp_boolean),
  3842. ]
  3843. onupdate: Optional[DefaultGenerator] = None
  3844. default: Optional[DefaultGenerator] = None
  3845. server_default: Optional[FetchedValue] = None
  3846. server_onupdate: Optional[FetchedValue] = None
  3847. _is_multiparam_column = False
  3848. @property
  3849. def _is_star(self):
  3850. return self.is_literal and self.name == "*"
  3851. def __init__(
  3852. self,
  3853. text: str,
  3854. type_: Optional[_TypeEngineArgument[_T]] = None,
  3855. is_literal: bool = False,
  3856. _selectable: Optional[FromClause] = None,
  3857. ):
  3858. self.key = self.name = text
  3859. self.table = _selectable
  3860. # if type is None, we get NULLTYPE, which is our _T. But I don't
  3861. # know how to get the overloads to express that correctly
  3862. self.type = type_api.to_instance(type_) # type: ignore
  3863. self.is_literal = is_literal
  3864. def get_children(self, *, column_tables=False, **kw):
  3865. # override base get_children() to not return the Table
  3866. # or selectable that is parent to this column. Traversals
  3867. # expect the columns of tables and subqueries to be leaf nodes.
  3868. return []
  3869. @property
  3870. def entity_namespace(self):
  3871. if self.table is not None:
  3872. return self.table.entity_namespace
  3873. else:
  3874. return super().entity_namespace
  3875. def _clone(self, detect_subquery_cols=False, **kw):
  3876. if (
  3877. detect_subquery_cols
  3878. and self.table is not None
  3879. and self.table._is_subquery
  3880. ):
  3881. clone = kw.pop("clone")
  3882. table = clone(self.table, **kw)
  3883. new = table.c.corresponding_column(self)
  3884. return new
  3885. return super()._clone(**kw)
  3886. @HasMemoized_ro_memoized_attribute
  3887. def _from_objects(self) -> List[FromClause]:
  3888. t = self.table
  3889. if t is not None:
  3890. return [t]
  3891. else:
  3892. return []
  3893. @HasMemoized.memoized_attribute
  3894. def _render_label_in_columns_clause(self):
  3895. return self.table is not None
  3896. @property
  3897. def _ddl_label(self):
  3898. return self._gen_tq_label(self.name, dedupe_on_key=False)
  3899. def _compare_name_for_result(self, other):
  3900. if (
  3901. self.is_literal
  3902. or self.table is None
  3903. or self.table._is_textual
  3904. or not hasattr(other, "proxy_set")
  3905. or (
  3906. isinstance(other, ColumnClause)
  3907. and (
  3908. other.is_literal
  3909. or other.table is None
  3910. or other.table._is_textual
  3911. )
  3912. )
  3913. ):
  3914. return (hasattr(other, "name") and self.name == other.name) or (
  3915. hasattr(other, "_tq_label")
  3916. and self._tq_label == other._tq_label
  3917. )
  3918. else:
  3919. return other.proxy_set.intersection(self.proxy_set)
  3920. def _gen_tq_label(
  3921. self, name: str, dedupe_on_key: bool = True
  3922. ) -> Optional[str]:
  3923. """generate table-qualified label
  3924. for a table-bound column this is <tablename>_<columnname>.
  3925. used primarily for LABEL_STYLE_TABLENAME_PLUS_COL
  3926. as well as the .columns collection on a Join object.
  3927. """
  3928. label: str
  3929. t = self.table
  3930. if self.is_literal:
  3931. return None
  3932. elif t is not None and is_named_from_clause(t):
  3933. if has_schema_attr(t) and t.schema:
  3934. label = t.schema.replace(".", "_") + "_" + t.name + "_" + name
  3935. else:
  3936. assert not TYPE_CHECKING or isinstance(t, NamedFromClause)
  3937. label = t.name + "_" + name
  3938. # propagate name quoting rules for labels.
  3939. if is_quoted_name(name) and name.quote is not None:
  3940. if is_quoted_name(label):
  3941. label.quote = name.quote
  3942. else:
  3943. label = quoted_name(label, name.quote)
  3944. elif is_quoted_name(t.name) and t.name.quote is not None:
  3945. # can't get this situation to occur, so let's
  3946. # assert false on it for now
  3947. assert not isinstance(label, quoted_name)
  3948. label = quoted_name(label, t.name.quote)
  3949. if dedupe_on_key:
  3950. # ensure the label name doesn't conflict with that of an
  3951. # existing column. note that this implies that any Column
  3952. # must **not** set up its _label before its parent table has
  3953. # all of its other Column objects set up. There are several
  3954. # tables in the test suite which will fail otherwise; example:
  3955. # table "owner" has columns "name" and "owner_name". Therefore
  3956. # column owner.name cannot use the label "owner_name", it has
  3957. # to be "owner_name_1".
  3958. if label in t.c:
  3959. _label = label
  3960. counter = 1
  3961. while _label in t.c:
  3962. _label = label + "_" + str(counter)
  3963. counter += 1
  3964. label = _label
  3965. return coercions.expect(roles.TruncatedLabelRole, label)
  3966. else:
  3967. return name
  3968. def _make_proxy(
  3969. self,
  3970. selectable: FromClause,
  3971. *,
  3972. name: Optional[str] = None,
  3973. key: Optional[str] = None,
  3974. name_is_truncatable: bool = False,
  3975. compound_select_cols: Optional[Sequence[ColumnElement[Any]]] = None,
  3976. disallow_is_literal: bool = False,
  3977. **kw: Any,
  3978. ) -> typing_Tuple[str, ColumnClause[_T]]:
  3979. # the "is_literal" flag normally should never be propagated; a proxied
  3980. # column is always a SQL identifier and never the actual expression
  3981. # being evaluated. however, there is a case where the "is_literal" flag
  3982. # might be used to allow the given identifier to have a fixed quoting
  3983. # pattern already, so maintain the flag for the proxy unless a
  3984. # :class:`.Label` object is creating the proxy. See [ticket:4730].
  3985. is_literal = (
  3986. not disallow_is_literal
  3987. and self.is_literal
  3988. and (
  3989. # note this does not accommodate for quoted_name differences
  3990. # right now
  3991. name is None
  3992. or name == self.name
  3993. )
  3994. )
  3995. c = self._constructor(
  3996. coercions.expect(roles.TruncatedLabelRole, name or self.name)
  3997. if name_is_truncatable
  3998. else (name or self.name),
  3999. type_=self.type,
  4000. _selectable=selectable,
  4001. is_literal=is_literal,
  4002. )
  4003. c._propagate_attrs = selectable._propagate_attrs
  4004. if name is None:
  4005. c.key = self.key
  4006. if compound_select_cols:
  4007. c._proxies = list(compound_select_cols)
  4008. else:
  4009. c._proxies = [self]
  4010. if selectable._is_clone_of is not None:
  4011. c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
  4012. return c.key, c
  4013. class TableValuedColumn(NamedColumn[_T]):
  4014. __visit_name__ = "table_valued_column"
  4015. _traverse_internals: _TraverseInternalsType = [
  4016. ("name", InternalTraversal.dp_anon_name),
  4017. ("type", InternalTraversal.dp_type),
  4018. ("scalar_alias", InternalTraversal.dp_clauseelement),
  4019. ]
  4020. def __init__(self, scalar_alias: NamedFromClause, type_: TypeEngine[_T]):
  4021. self.scalar_alias = scalar_alias
  4022. self.key = self.name = scalar_alias.name
  4023. self.type = type_
  4024. def _copy_internals(
  4025. self, clone: _CloneCallableType = _clone, **kw: Any
  4026. ) -> None:
  4027. self.scalar_alias = clone(self.scalar_alias, **kw)
  4028. self.key = self.name = self.scalar_alias.name
  4029. @util.ro_non_memoized_property
  4030. def _from_objects(self) -> List[FromClause]:
  4031. return [self.scalar_alias]
  4032. class CollationClause(ColumnElement[str]):
  4033. __visit_name__ = "collation"
  4034. _traverse_internals: _TraverseInternalsType = [
  4035. ("collation", InternalTraversal.dp_string)
  4036. ]
  4037. @classmethod
  4038. def _create_collation_expression(
  4039. cls, expression: _ColumnExpressionArgument[str], collation: str
  4040. ) -> BinaryExpression[str]:
  4041. expr = coercions.expect(roles.ExpressionElementRole[str], expression)
  4042. return BinaryExpression(
  4043. expr,
  4044. CollationClause(collation),
  4045. operators.collate,
  4046. type_=expr.type,
  4047. )
  4048. def __init__(self, collation):
  4049. self.collation = collation
  4050. class _IdentifiedClause(Executable, ClauseElement):
  4051. __visit_name__ = "identified"
  4052. def __init__(self, ident):
  4053. self.ident = ident
  4054. class SavepointClause(_IdentifiedClause):
  4055. __visit_name__ = "savepoint"
  4056. inherit_cache = False
  4057. class RollbackToSavepointClause(_IdentifiedClause):
  4058. __visit_name__ = "rollback_to_savepoint"
  4059. inherit_cache = False
  4060. class ReleaseSavepointClause(_IdentifiedClause):
  4061. __visit_name__ = "release_savepoint"
  4062. inherit_cache = False
  4063. class quoted_name(util.MemoizedSlots, str):
  4064. """Represent a SQL identifier combined with quoting preferences.
  4065. :class:`.quoted_name` is a Python unicode/str subclass which
  4066. represents a particular identifier name along with a
  4067. ``quote`` flag. This ``quote`` flag, when set to
  4068. ``True`` or ``False``, overrides automatic quoting behavior
  4069. for this identifier in order to either unconditionally quote
  4070. or to not quote the name. If left at its default of ``None``,
  4071. quoting behavior is applied to the identifier on a per-backend basis
  4072. based on an examination of the token itself.
  4073. A :class:`.quoted_name` object with ``quote=True`` is also
  4074. prevented from being modified in the case of a so-called
  4075. "name normalize" option. Certain database backends, such as
  4076. Oracle, Firebird, and DB2 "normalize" case-insensitive names
  4077. as uppercase. The SQLAlchemy dialects for these backends
  4078. convert from SQLAlchemy's lower-case-means-insensitive convention
  4079. to the upper-case-means-insensitive conventions of those backends.
  4080. The ``quote=True`` flag here will prevent this conversion from occurring
  4081. to support an identifier that's quoted as all lower case against
  4082. such a backend.
  4083. The :class:`.quoted_name` object is normally created automatically
  4084. when specifying the name for key schema constructs such as
  4085. :class:`_schema.Table`, :class:`_schema.Column`, and others.
  4086. The class can also be
  4087. passed explicitly as the name to any function that receives a name which
  4088. can be quoted. Such as to use the :meth:`_engine.Engine.has_table`
  4089. method with
  4090. an unconditionally quoted name::
  4091. from sqlalchemy import create_engine
  4092. from sqlalchemy import inspect
  4093. from sqlalchemy.sql import quoted_name
  4094. engine = create_engine("oracle+cx_oracle://some_dsn")
  4095. print(inspect(engine).has_table(quoted_name("some_table", True)))
  4096. The above logic will run the "has table" logic against the Oracle backend,
  4097. passing the name exactly as ``"some_table"`` without converting to
  4098. upper case.
  4099. .. versionchanged:: 1.2 The :class:`.quoted_name` construct is now
  4100. importable from ``sqlalchemy.sql``, in addition to the previous
  4101. location of ``sqlalchemy.sql.elements``.
  4102. """
  4103. __slots__ = "quote", "lower", "upper"
  4104. quote: Optional[bool]
  4105. @overload
  4106. @classmethod
  4107. def construct(cls, value: str, quote: Optional[bool]) -> quoted_name:
  4108. ...
  4109. @overload
  4110. @classmethod
  4111. def construct(cls, value: None, quote: Optional[bool]) -> None:
  4112. ...
  4113. @classmethod
  4114. def construct(
  4115. cls, value: Optional[str], quote: Optional[bool]
  4116. ) -> Optional[quoted_name]:
  4117. if value is None:
  4118. return None
  4119. else:
  4120. return quoted_name(value, quote)
  4121. def __new__(cls, value: str, quote: Optional[bool]) -> quoted_name:
  4122. assert (
  4123. value is not None
  4124. ), "use quoted_name.construct() for None passthrough"
  4125. if isinstance(value, cls) and (quote is None or value.quote == quote):
  4126. return value
  4127. self = super().__new__(cls, value)
  4128. self.quote = quote
  4129. return self
  4130. def __reduce__(self):
  4131. return quoted_name, (str(self), self.quote)
  4132. def _memoized_method_lower(self):
  4133. if self.quote:
  4134. return self
  4135. else:
  4136. return str(self).lower()
  4137. def _memoized_method_upper(self):
  4138. if self.quote:
  4139. return self
  4140. else:
  4141. return str(self).upper()
  4142. def _find_columns(clause: ClauseElement) -> Set[ColumnClause[Any]]:
  4143. """locate Column objects within the given expression."""
  4144. cols: Set[ColumnClause[Any]] = set()
  4145. traverse(clause, {}, {"column": cols.add})
  4146. return cols
  4147. def _type_from_args(args: Sequence[ColumnElement[_T]]) -> TypeEngine[_T]:
  4148. for a in args:
  4149. if not a.type._isnull:
  4150. return a.type
  4151. else:
  4152. return type_api.NULLTYPE # type: ignore
  4153. def _corresponding_column_or_error(fromclause, column, require_embedded=False):
  4154. c = fromclause.corresponding_column(
  4155. column, require_embedded=require_embedded
  4156. )
  4157. if c is None:
  4158. raise exc.InvalidRequestError(
  4159. "Given column '%s', attached to table '%s', "
  4160. "failed to locate a corresponding column from table '%s'"
  4161. % (column, getattr(column, "table", None), fromclause.description)
  4162. )
  4163. return c
  4164. class _memoized_property_but_not_nulltype(
  4165. util.memoized_property["TypeEngine[_T]"]
  4166. ):
  4167. """memoized property, but dont memoize NullType"""
  4168. def __get__(self, obj, cls):
  4169. if obj is None:
  4170. return self
  4171. result = self.fget(obj)
  4172. if not result._isnull:
  4173. obj.__dict__[self.__name__] = result
  4174. return result
  4175. class AnnotatedColumnElement(Annotated):
  4176. _Annotated__element: ColumnElement[Any]
  4177. def __init__(self, element, values):
  4178. Annotated.__init__(self, element, values)
  4179. for attr in (
  4180. "comparator",
  4181. "_proxy_key",
  4182. "_tq_key_label",
  4183. "_tq_label",
  4184. "_non_anon_label",
  4185. "type",
  4186. ):
  4187. self.__dict__.pop(attr, None)
  4188. for attr in ("name", "key", "table"):
  4189. if self.__dict__.get(attr, False) is None:
  4190. self.__dict__.pop(attr)
  4191. def _with_annotations(self, values):
  4192. clone = super()._with_annotations(values)
  4193. clone.__dict__.pop("comparator", None)
  4194. return clone
  4195. @util.memoized_property
  4196. def name(self):
  4197. """pull 'name' from parent, if not present"""
  4198. return self._Annotated__element.name
  4199. @_memoized_property_but_not_nulltype
  4200. def type(self):
  4201. """pull 'type' from parent and don't cache if null.
  4202. type is routinely changed on existing columns within the
  4203. mapped_column() initialization process, and "type" is also consulted
  4204. during the creation of SQL expressions. Therefore it can change after
  4205. it was already retrieved. At the same time we don't want annotated
  4206. objects having overhead when expressions are produced, so continue
  4207. to memoize, but only when we have a non-null type.
  4208. """
  4209. return self._Annotated__element.type
  4210. @util.memoized_property
  4211. def table(self):
  4212. """pull 'table' from parent, if not present"""
  4213. return self._Annotated__element.table
  4214. @util.memoized_property
  4215. def key(self):
  4216. """pull 'key' from parent, if not present"""
  4217. return self._Annotated__element.key
  4218. @util.memoized_property
  4219. def info(self) -> _InfoType:
  4220. if TYPE_CHECKING:
  4221. assert isinstance(self._Annotated__element, Column)
  4222. return self._Annotated__element.info
  4223. @util.memoized_property
  4224. def _anon_name_label(self) -> str:
  4225. return self._Annotated__element._anon_name_label
  4226. class _truncated_label(quoted_name):
  4227. """A unicode subclass used to identify symbolic "
  4228. "names that may require truncation."""
  4229. __slots__ = ()
  4230. def __new__(cls, value: str, quote: Optional[bool] = None) -> Any:
  4231. quote = getattr(value, "quote", quote)
  4232. # return super(_truncated_label, cls).__new__(cls, value, quote, True)
  4233. return super().__new__(cls, value, quote)
  4234. def __reduce__(self) -> Any:
  4235. return self.__class__, (str(self), self.quote)
  4236. def apply_map(self, map_: Mapping[str, Any]) -> str:
  4237. return self
  4238. class conv(_truncated_label):
  4239. """Mark a string indicating that a name has already been converted
  4240. by a naming convention.
  4241. This is a string subclass that indicates a name that should not be
  4242. subject to any further naming conventions.
  4243. E.g. when we create a :class:`.Constraint` using a naming convention
  4244. as follows::
  4245. m = MetaData(naming_convention={
  4246. "ck": "ck_%(table_name)s_%(constraint_name)s"
  4247. })
  4248. t = Table('t', m, Column('x', Integer),
  4249. CheckConstraint('x > 5', name='x5'))
  4250. The name of the above constraint will be rendered as ``"ck_t_x5"``.
  4251. That is, the existing name ``x5`` is used in the naming convention as the
  4252. ``constraint_name`` token.
  4253. In some situations, such as in migration scripts, we may be rendering
  4254. the above :class:`.CheckConstraint` with a name that's already been
  4255. converted. In order to make sure the name isn't double-modified, the
  4256. new name is applied using the :func:`_schema.conv` marker. We can
  4257. use this explicitly as follows::
  4258. m = MetaData(naming_convention={
  4259. "ck": "ck_%(table_name)s_%(constraint_name)s"
  4260. })
  4261. t = Table('t', m, Column('x', Integer),
  4262. CheckConstraint('x > 5', name=conv('ck_t_x5')))
  4263. Where above, the :func:`_schema.conv` marker indicates that the constraint
  4264. name here is final, and the name will render as ``"ck_t_x5"`` and not
  4265. ``"ck_t_ck_t_x5"``
  4266. .. seealso::
  4267. :ref:`constraint_naming_conventions`
  4268. """
  4269. __slots__ = ()
  4270. # for backwards compatibility in case
  4271. # someone is re-implementing the
  4272. # _truncated_identifier() sequence in a custom
  4273. # compiler
  4274. _generated_label = _truncated_label
  4275. class _anonymous_label(_truncated_label):
  4276. """A unicode subclass used to identify anonymously
  4277. generated names."""
  4278. __slots__ = ()
  4279. @classmethod
  4280. def safe_construct(
  4281. cls,
  4282. seed: int,
  4283. body: str,
  4284. enclosing_label: Optional[str] = None,
  4285. sanitize_key: bool = False,
  4286. ) -> _anonymous_label:
  4287. # need to escape chars that interfere with format
  4288. # strings in any case, issue #8724
  4289. body = re.sub(r"[%\(\) \$]+", "_", body)
  4290. if sanitize_key:
  4291. # sanitize_key is then an extra step used by BindParameter
  4292. body = body.strip("_")
  4293. label = "%%(%d %s)s" % (seed, body.replace("%", "%%"))
  4294. if enclosing_label:
  4295. label = "%s%s" % (enclosing_label, label)
  4296. return _anonymous_label(label)
  4297. def __add__(self, other):
  4298. if "%" in other and not isinstance(other, _anonymous_label):
  4299. other = str(other).replace("%", "%%")
  4300. else:
  4301. other = str(other)
  4302. return _anonymous_label(
  4303. quoted_name(
  4304. str.__add__(self, other),
  4305. self.quote,
  4306. )
  4307. )
  4308. def __radd__(self, other):
  4309. if "%" in other and not isinstance(other, _anonymous_label):
  4310. other = str(other).replace("%", "%%")
  4311. else:
  4312. other = str(other)
  4313. return _anonymous_label(
  4314. quoted_name(
  4315. str.__add__(other, self),
  4316. self.quote,
  4317. )
  4318. )
  4319. def apply_map(self, map_):
  4320. if self.quote is not None:
  4321. # preserve quoting only if necessary
  4322. return quoted_name(self % map_, self.quote)
  4323. else:
  4324. # else skip the constructor call
  4325. return self % map_