elements.py 174 KB

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