selectable.py 239 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265
  1. # sql/selectable.py
  2. # Copyright (C) 2005-2026 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. """The :class:`_expression.FromClause` class of SQL expression elements,
  8. representing
  9. SQL tables and derived rowsets.
  10. """
  11. from __future__ import annotations
  12. import collections
  13. from enum import Enum
  14. import itertools
  15. from typing import AbstractSet
  16. from typing import Any as TODO_Any
  17. from typing import Any
  18. from typing import Callable
  19. from typing import cast
  20. from typing import Dict
  21. from typing import Generic
  22. from typing import Iterable
  23. from typing import Iterator
  24. from typing import List
  25. from typing import NamedTuple
  26. from typing import NoReturn
  27. from typing import Optional
  28. from typing import overload
  29. from typing import Sequence
  30. from typing import Set
  31. from typing import Tuple
  32. from typing import Type
  33. from typing import TYPE_CHECKING
  34. from typing import TypeVar
  35. from typing import Union
  36. from . import cache_key
  37. from . import coercions
  38. from . import operators
  39. from . import roles
  40. from . import traversals
  41. from . import type_api
  42. from . import visitors
  43. from ._typing import _ColumnsClauseArgument
  44. from ._typing import _no_kw
  45. from ._typing import _T
  46. from ._typing import _TP
  47. from ._typing import is_column_element
  48. from ._typing import is_select_statement
  49. from ._typing import is_subquery
  50. from ._typing import is_table
  51. from ._typing import is_text_clause
  52. from .annotation import Annotated
  53. from .annotation import SupportsCloneAnnotations
  54. from .base import _clone
  55. from .base import _cloned_difference
  56. from .base import _cloned_intersection
  57. from .base import _entity_namespace_key
  58. from .base import _EntityNamespace
  59. from .base import _expand_cloned
  60. from .base import _from_objects
  61. from .base import _generative
  62. from .base import _never_select_column
  63. from .base import _NoArg
  64. from .base import _select_iterables
  65. from .base import CacheableOptions
  66. from .base import ColumnCollection
  67. from .base import ColumnSet
  68. from .base import CompileState
  69. from .base import DedupeColumnCollection
  70. from .base import DialectKWArgs
  71. from .base import Executable
  72. from .base import Generative
  73. from .base import HasCompileState
  74. from .base import HasMemoized
  75. from .base import Immutable
  76. from .coercions import _document_text_coercion
  77. from .elements import _anonymous_label
  78. from .elements import BindParameter
  79. from .elements import BooleanClauseList
  80. from .elements import ClauseElement
  81. from .elements import ClauseList
  82. from .elements import ColumnClause
  83. from .elements import ColumnElement
  84. from .elements import DQLDMLClauseElement
  85. from .elements import GroupedElement
  86. from .elements import literal_column
  87. from .elements import TableValuedColumn
  88. from .elements import UnaryExpression
  89. from .operators import OperatorType
  90. from .sqltypes import NULLTYPE
  91. from .visitors import _TraverseInternalsType
  92. from .visitors import InternalTraversal
  93. from .visitors import prefix_anon_map
  94. from .. import exc
  95. from .. import util
  96. from ..util import HasMemoized_ro_memoized_attribute
  97. from ..util.typing import Literal
  98. from ..util.typing import Protocol
  99. from ..util.typing import Self
  100. and_ = BooleanClauseList.and_
  101. if TYPE_CHECKING:
  102. from ._typing import _ColumnExpressionArgument
  103. from ._typing import _ColumnExpressionOrStrLabelArgument
  104. from ._typing import _FromClauseArgument
  105. from ._typing import _JoinTargetArgument
  106. from ._typing import _LimitOffsetType
  107. from ._typing import _MAYBE_ENTITY
  108. from ._typing import _NOT_ENTITY
  109. from ._typing import _OnClauseArgument
  110. from ._typing import _OnlyColumnArgument
  111. from ._typing import _SelectStatementForCompoundArgument
  112. from ._typing import _T0
  113. from ._typing import _T1
  114. from ._typing import _T2
  115. from ._typing import _T3
  116. from ._typing import _T4
  117. from ._typing import _T5
  118. from ._typing import _T6
  119. from ._typing import _T7
  120. from ._typing import _TextCoercedExpressionArgument
  121. from ._typing import _TypedColumnClauseArgument as _TCCA
  122. from ._typing import _TypeEngineArgument
  123. from .base import _AmbiguousTableNameMap
  124. from .base import ExecutableOption
  125. from .base import ReadOnlyColumnCollection
  126. from .cache_key import _CacheKeyTraversalType
  127. from .compiler import SQLCompiler
  128. from .dml import Delete
  129. from .dml import Update
  130. from .elements import BinaryExpression
  131. from .elements import KeyedColumnElement
  132. from .elements import Label
  133. from .elements import NamedColumn
  134. from .elements import TextClause
  135. from .functions import Function
  136. from .schema import ForeignKey
  137. from .schema import ForeignKeyConstraint
  138. from .sqltypes import TableValueType
  139. from .type_api import TypeEngine
  140. from .visitors import _CloneCallableType
  141. _ColumnsClauseElement = Union["FromClause", ColumnElement[Any], "TextClause"]
  142. _LabelConventionCallable = Callable[
  143. [Union["ColumnElement[Any]", "TextClause"]], Optional[str]
  144. ]
  145. class _JoinTargetProtocol(Protocol):
  146. @util.ro_non_memoized_property
  147. def _from_objects(self) -> List[FromClause]: ...
  148. @util.ro_non_memoized_property
  149. def entity_namespace(self) -> _EntityNamespace: ...
  150. _JoinTargetElement = Union["FromClause", _JoinTargetProtocol]
  151. _OnClauseElement = Union["ColumnElement[bool]", _JoinTargetProtocol]
  152. _ForUpdateOfArgument = Union[
  153. # single column, Table, ORM entity
  154. Union[
  155. "_ColumnExpressionArgument[Any]",
  156. "_FromClauseArgument",
  157. ],
  158. # or sequence of column, Table, ORM entity
  159. Sequence[
  160. Union[
  161. "_ColumnExpressionArgument[Any]",
  162. "_FromClauseArgument",
  163. ]
  164. ],
  165. ]
  166. _SetupJoinsElement = Tuple[
  167. _JoinTargetElement,
  168. Optional[_OnClauseElement],
  169. Optional["FromClause"],
  170. Dict[str, Any],
  171. ]
  172. _SelectIterable = Iterable[Union["ColumnElement[Any]", "TextClause"]]
  173. class _OffsetLimitParam(BindParameter[int]):
  174. inherit_cache = True
  175. @property
  176. def _limit_offset_value(self) -> Optional[int]:
  177. return self.effective_value
  178. class ReturnsRows(roles.ReturnsRowsRole, DQLDMLClauseElement):
  179. """The base-most class for Core constructs that have some concept of
  180. columns that can represent rows.
  181. While the SELECT statement and TABLE are the primary things we think
  182. of in this category, DML like INSERT, UPDATE and DELETE can also specify
  183. RETURNING which means they can be used in CTEs and other forms, and
  184. PostgreSQL has functions that return rows also.
  185. .. versionadded:: 1.4
  186. """
  187. _is_returns_rows = True
  188. # sub-elements of returns_rows
  189. _is_from_clause = False
  190. _is_select_base = False
  191. _is_select_statement = False
  192. _is_lateral = False
  193. @property
  194. def selectable(self) -> ReturnsRows:
  195. return self
  196. @util.ro_non_memoized_property
  197. def _all_selected_columns(self) -> _SelectIterable:
  198. """A sequence of column expression objects that represents the
  199. "selected" columns of this :class:`_expression.ReturnsRows`.
  200. This is typically equivalent to .exported_columns except it is
  201. delivered in the form of a straight sequence and not keyed
  202. :class:`_expression.ColumnCollection`.
  203. """
  204. raise NotImplementedError()
  205. def is_derived_from(self, fromclause: Optional[FromClause]) -> bool:
  206. """Return ``True`` if this :class:`.ReturnsRows` is
  207. 'derived' from the given :class:`.FromClause`.
  208. An example would be an Alias of a Table is derived from that Table.
  209. """
  210. raise NotImplementedError()
  211. def _generate_fromclause_column_proxies(
  212. self,
  213. fromclause: FromClause,
  214. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  215. primary_key: ColumnSet,
  216. foreign_keys: Set[KeyedColumnElement[Any]],
  217. ) -> None:
  218. """Populate columns into an :class:`.AliasedReturnsRows` object."""
  219. raise NotImplementedError()
  220. def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
  221. """reset internal collections for an incoming column being added."""
  222. raise NotImplementedError()
  223. @property
  224. def exported_columns(self) -> ReadOnlyColumnCollection[Any, Any]:
  225. """A :class:`_expression.ColumnCollection`
  226. that represents the "exported"
  227. columns of this :class:`_expression.ReturnsRows`.
  228. The "exported" columns represent the collection of
  229. :class:`_expression.ColumnElement`
  230. expressions that are rendered by this SQL
  231. construct. There are primary varieties which are the
  232. "FROM clause columns" of a FROM clause, such as a table, join,
  233. or subquery, the "SELECTed columns", which are the columns in
  234. the "columns clause" of a SELECT statement, and the RETURNING
  235. columns in a DML statement..
  236. .. versionadded:: 1.4
  237. .. seealso::
  238. :attr:`_expression.FromClause.exported_columns`
  239. :attr:`_expression.SelectBase.exported_columns`
  240. """
  241. raise NotImplementedError()
  242. class ExecutableReturnsRows(Executable, ReturnsRows):
  243. """base for executable statements that return rows."""
  244. class TypedReturnsRows(ExecutableReturnsRows, Generic[_TP]):
  245. """base for a typed executable statements that return rows."""
  246. class Selectable(ReturnsRows):
  247. """Mark a class as being selectable."""
  248. __visit_name__ = "selectable"
  249. is_selectable = True
  250. def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
  251. raise NotImplementedError()
  252. def lateral(self, name: Optional[str] = None) -> LateralFromClause:
  253. """Return a LATERAL alias of this :class:`_expression.Selectable`.
  254. The return value is the :class:`_expression.Lateral` construct also
  255. provided by the top-level :func:`_expression.lateral` function.
  256. .. seealso::
  257. :ref:`tutorial_lateral_correlation` - overview of usage.
  258. """
  259. return Lateral._construct(self, name=name)
  260. @util.deprecated(
  261. "1.4",
  262. message="The :meth:`.Selectable.replace_selectable` method is "
  263. "deprecated, and will be removed in a future release. Similar "
  264. "functionality is available via the sqlalchemy.sql.visitors module.",
  265. )
  266. @util.preload_module("sqlalchemy.sql.util")
  267. def replace_selectable(self, old: FromClause, alias: Alias) -> Self:
  268. """Replace all occurrences of :class:`_expression.FromClause`
  269. 'old' with the given :class:`_expression.Alias`
  270. object, returning a copy of this :class:`_expression.FromClause`.
  271. """
  272. return util.preloaded.sql_util.ClauseAdapter(alias).traverse(self)
  273. def corresponding_column(
  274. self, column: KeyedColumnElement[Any], require_embedded: bool = False
  275. ) -> Optional[KeyedColumnElement[Any]]:
  276. """Given a :class:`_expression.ColumnElement`, return the exported
  277. :class:`_expression.ColumnElement` object from the
  278. :attr:`_expression.Selectable.exported_columns`
  279. collection of this :class:`_expression.Selectable`
  280. which corresponds to that
  281. original :class:`_expression.ColumnElement` via a common ancestor
  282. column.
  283. :param column: the target :class:`_expression.ColumnElement`
  284. to be matched.
  285. :param require_embedded: only return corresponding columns for
  286. the given :class:`_expression.ColumnElement`, if the given
  287. :class:`_expression.ColumnElement`
  288. is actually present within a sub-element
  289. of this :class:`_expression.Selectable`.
  290. Normally the column will match if
  291. it merely shares a common ancestor with one of the exported
  292. columns of this :class:`_expression.Selectable`.
  293. .. seealso::
  294. :attr:`_expression.Selectable.exported_columns` - the
  295. :class:`_expression.ColumnCollection`
  296. that is used for the operation.
  297. :meth:`_expression.ColumnCollection.corresponding_column`
  298. - implementation
  299. method.
  300. """
  301. return self.exported_columns.corresponding_column(
  302. column, require_embedded
  303. )
  304. class HasPrefixes:
  305. _prefixes: Tuple[Tuple[DQLDMLClauseElement, str], ...] = ()
  306. _has_prefixes_traverse_internals: _TraverseInternalsType = [
  307. ("_prefixes", InternalTraversal.dp_prefix_sequence)
  308. ]
  309. @_generative
  310. @_document_text_coercion(
  311. "prefixes",
  312. ":meth:`_expression.HasPrefixes.prefix_with`",
  313. ":paramref:`.HasPrefixes.prefix_with.*prefixes`",
  314. )
  315. def prefix_with(
  316. self,
  317. *prefixes: _TextCoercedExpressionArgument[Any],
  318. dialect: str = "*",
  319. ) -> Self:
  320. r"""Add one or more expressions following the statement keyword, i.e.
  321. SELECT, INSERT, UPDATE, or DELETE. Generative.
  322. This is used to support backend-specific prefix keywords such as those
  323. provided by MySQL.
  324. E.g.::
  325. stmt = table.insert().prefix_with("LOW_PRIORITY", dialect="mysql")
  326. # MySQL 5.7 optimizer hints
  327. stmt = select(table).prefix_with("/*+ BKA(t1) */", dialect="mysql")
  328. Multiple prefixes can be specified by multiple calls
  329. to :meth:`_expression.HasPrefixes.prefix_with`.
  330. :param \*prefixes: textual or :class:`_expression.ClauseElement`
  331. construct which
  332. will be rendered following the INSERT, UPDATE, or DELETE
  333. keyword.
  334. :param dialect: optional string dialect name which will
  335. limit rendering of this prefix to only that dialect.
  336. """
  337. self._prefixes = self._prefixes + tuple(
  338. [
  339. (coercions.expect(roles.StatementOptionRole, p), dialect)
  340. for p in prefixes
  341. ]
  342. )
  343. return self
  344. class HasSuffixes:
  345. _suffixes: Tuple[Tuple[DQLDMLClauseElement, str], ...] = ()
  346. _has_suffixes_traverse_internals: _TraverseInternalsType = [
  347. ("_suffixes", InternalTraversal.dp_prefix_sequence)
  348. ]
  349. @_generative
  350. @_document_text_coercion(
  351. "suffixes",
  352. ":meth:`_expression.HasSuffixes.suffix_with`",
  353. ":paramref:`.HasSuffixes.suffix_with.*suffixes`",
  354. )
  355. def suffix_with(
  356. self,
  357. *suffixes: _TextCoercedExpressionArgument[Any],
  358. dialect: str = "*",
  359. ) -> Self:
  360. r"""Add one or more expressions following the statement as a whole.
  361. This is used to support backend-specific suffix keywords on
  362. certain constructs.
  363. E.g.::
  364. stmt = (
  365. select(col1, col2)
  366. .cte()
  367. .suffix_with(
  368. "cycle empno set y_cycle to 1 default 0", dialect="oracle"
  369. )
  370. )
  371. Multiple suffixes can be specified by multiple calls
  372. to :meth:`_expression.HasSuffixes.suffix_with`.
  373. :param \*suffixes: textual or :class:`_expression.ClauseElement`
  374. construct which
  375. will be rendered following the target clause.
  376. :param dialect: Optional string dialect name which will
  377. limit rendering of this suffix to only that dialect.
  378. """
  379. self._suffixes = self._suffixes + tuple(
  380. [
  381. (coercions.expect(roles.StatementOptionRole, p), dialect)
  382. for p in suffixes
  383. ]
  384. )
  385. return self
  386. class HasHints:
  387. _hints: util.immutabledict[Tuple[FromClause, str], str] = (
  388. util.immutabledict()
  389. )
  390. _statement_hints: Tuple[Tuple[str, str], ...] = ()
  391. _has_hints_traverse_internals: _TraverseInternalsType = [
  392. ("_statement_hints", InternalTraversal.dp_statement_hint_list),
  393. ("_hints", InternalTraversal.dp_table_hint_list),
  394. ]
  395. @_generative
  396. def with_statement_hint(self, text: str, dialect_name: str = "*") -> Self:
  397. """Add a statement hint to this :class:`_expression.Select` or
  398. other selectable object.
  399. .. tip::
  400. :meth:`_expression.Select.with_statement_hint` generally adds hints
  401. **at the trailing end** of a SELECT statement. To place
  402. dialect-specific hints such as optimizer hints at the **front** of
  403. the SELECT statement after the SELECT keyword, use the
  404. :meth:`_expression.Select.prefix_with` method for an open-ended
  405. space, or for table-specific hints the
  406. :meth:`_expression.Select.with_hint` may be used, which places
  407. hints in a dialect-specific location.
  408. This method is similar to :meth:`_expression.Select.with_hint` except
  409. that it does not require an individual table, and instead applies to
  410. the statement as a whole.
  411. Hints here are specific to the backend database and may include
  412. directives such as isolation levels, file directives, fetch directives,
  413. etc.
  414. .. seealso::
  415. :meth:`_expression.Select.with_hint`
  416. :meth:`_expression.Select.prefix_with` - generic SELECT prefixing
  417. which also can suit some database-specific HINT syntaxes such as
  418. MySQL or Oracle Database optimizer hints
  419. """
  420. return self._with_hint(None, text, dialect_name)
  421. @_generative
  422. def with_hint(
  423. self,
  424. selectable: _FromClauseArgument,
  425. text: str,
  426. dialect_name: str = "*",
  427. ) -> Self:
  428. r"""Add an indexing or other executional context hint for the given
  429. selectable to this :class:`_expression.Select` or other selectable
  430. object.
  431. .. tip::
  432. The :meth:`_expression.Select.with_hint` method adds hints that are
  433. **specific to a single table** to a statement, in a location that
  434. is **dialect-specific**. To add generic optimizer hints to the
  435. **beginning** of a statement ahead of the SELECT keyword such as
  436. for MySQL or Oracle Database, use the
  437. :meth:`_expression.Select.prefix_with` method. To add optimizer
  438. hints to the **end** of a statement such as for PostgreSQL, use the
  439. :meth:`_expression.Select.with_statement_hint` method.
  440. The text of the hint is rendered in the appropriate
  441. location for the database backend in use, relative
  442. to the given :class:`_schema.Table` or :class:`_expression.Alias`
  443. passed as the
  444. ``selectable`` argument. The dialect implementation
  445. typically uses Python string substitution syntax
  446. with the token ``%(name)s`` to render the name of
  447. the table or alias. E.g. when using Oracle Database, the
  448. following::
  449. select(mytable).with_hint(mytable, "index(%(name)s ix_mytable)")
  450. Would render SQL as:
  451. .. sourcecode:: sql
  452. select /*+ index(mytable ix_mytable) */ ... from mytable
  453. The ``dialect_name`` option will limit the rendering of a particular
  454. hint to a particular backend. Such as, to add hints for both Oracle
  455. Database and MSSql simultaneously::
  456. select(mytable).with_hint(
  457. mytable, "index(%(name)s ix_mytable)", "oracle"
  458. ).with_hint(mytable, "WITH INDEX ix_mytable", "mssql")
  459. .. seealso::
  460. :meth:`_expression.Select.with_statement_hint`
  461. :meth:`_expression.Select.prefix_with` - generic SELECT prefixing
  462. which also can suit some database-specific HINT syntaxes such as
  463. MySQL or Oracle Database optimizer hints
  464. """
  465. return self._with_hint(selectable, text, dialect_name)
  466. def _with_hint(
  467. self,
  468. selectable: Optional[_FromClauseArgument],
  469. text: str,
  470. dialect_name: str,
  471. ) -> Self:
  472. if selectable is None:
  473. self._statement_hints += ((dialect_name, text),)
  474. else:
  475. self._hints = self._hints.union(
  476. {
  477. (
  478. coercions.expect(roles.FromClauseRole, selectable),
  479. dialect_name,
  480. ): text
  481. }
  482. )
  483. return self
  484. class FromClause(roles.AnonymizedFromClauseRole, Selectable):
  485. """Represent an element that can be used within the ``FROM``
  486. clause of a ``SELECT`` statement.
  487. The most common forms of :class:`_expression.FromClause` are the
  488. :class:`_schema.Table` and the :func:`_expression.select` constructs. Key
  489. features common to all :class:`_expression.FromClause` objects include:
  490. * a :attr:`.c` collection, which provides per-name access to a collection
  491. of :class:`_expression.ColumnElement` objects.
  492. * a :attr:`.primary_key` attribute, which is a collection of all those
  493. :class:`_expression.ColumnElement`
  494. objects that indicate the ``primary_key`` flag.
  495. * Methods to generate various derivations of a "from" clause, including
  496. :meth:`_expression.FromClause.alias`,
  497. :meth:`_expression.FromClause.join`,
  498. :meth:`_expression.FromClause.select`.
  499. """
  500. __visit_name__ = "fromclause"
  501. named_with_column = False
  502. @util.ro_non_memoized_property
  503. def _hide_froms(self) -> Iterable[FromClause]:
  504. return ()
  505. _is_clone_of: Optional[FromClause]
  506. _columns: ColumnCollection[Any, Any]
  507. schema: Optional[str] = None
  508. """Define the 'schema' attribute for this :class:`_expression.FromClause`.
  509. This is typically ``None`` for most objects except that of
  510. :class:`_schema.Table`, where it is taken as the value of the
  511. :paramref:`_schema.Table.schema` argument.
  512. """
  513. is_selectable = True
  514. _is_from_clause = True
  515. _is_join = False
  516. _use_schema_map = False
  517. def select(self) -> Select[Any]:
  518. r"""Return a SELECT of this :class:`_expression.FromClause`.
  519. e.g.::
  520. stmt = some_table.select().where(some_table.c.id == 5)
  521. .. seealso::
  522. :func:`_expression.select` - general purpose
  523. method which allows for arbitrary column lists.
  524. """
  525. return Select(self)
  526. def join(
  527. self,
  528. right: _FromClauseArgument,
  529. onclause: Optional[_ColumnExpressionArgument[bool]] = None,
  530. isouter: bool = False,
  531. full: bool = False,
  532. ) -> Join:
  533. """Return a :class:`_expression.Join` from this
  534. :class:`_expression.FromClause`
  535. to another :class:`FromClause`.
  536. E.g.::
  537. from sqlalchemy import join
  538. j = user_table.join(
  539. address_table, user_table.c.id == address_table.c.user_id
  540. )
  541. stmt = select(user_table).select_from(j)
  542. would emit SQL along the lines of:
  543. .. sourcecode:: sql
  544. SELECT user.id, user.name FROM user
  545. JOIN address ON user.id = address.user_id
  546. :param right: the right side of the join; this is any
  547. :class:`_expression.FromClause` object such as a
  548. :class:`_schema.Table` object, and
  549. may also be a selectable-compatible object such as an ORM-mapped
  550. class.
  551. :param onclause: a SQL expression representing the ON clause of the
  552. join. If left at ``None``, :meth:`_expression.FromClause.join`
  553. will attempt to
  554. join the two tables based on a foreign key relationship.
  555. :param isouter: if True, render a LEFT OUTER JOIN, instead of JOIN.
  556. :param full: if True, render a FULL OUTER JOIN, instead of LEFT OUTER
  557. JOIN. Implies :paramref:`.FromClause.join.isouter`.
  558. .. seealso::
  559. :func:`_expression.join` - standalone function
  560. :class:`_expression.Join` - the type of object produced
  561. """
  562. return Join(self, right, onclause, isouter, full)
  563. def outerjoin(
  564. self,
  565. right: _FromClauseArgument,
  566. onclause: Optional[_ColumnExpressionArgument[bool]] = None,
  567. full: bool = False,
  568. ) -> Join:
  569. """Return a :class:`_expression.Join` from this
  570. :class:`_expression.FromClause`
  571. to another :class:`FromClause`, with the "isouter" flag set to
  572. True.
  573. E.g.::
  574. from sqlalchemy import outerjoin
  575. j = user_table.outerjoin(
  576. address_table, user_table.c.id == address_table.c.user_id
  577. )
  578. The above is equivalent to::
  579. j = user_table.join(
  580. address_table, user_table.c.id == address_table.c.user_id, isouter=True
  581. )
  582. :param right: the right side of the join; this is any
  583. :class:`_expression.FromClause` object such as a
  584. :class:`_schema.Table` object, and
  585. may also be a selectable-compatible object such as an ORM-mapped
  586. class.
  587. :param onclause: a SQL expression representing the ON clause of the
  588. join. If left at ``None``, :meth:`_expression.FromClause.join`
  589. will attempt to
  590. join the two tables based on a foreign key relationship.
  591. :param full: if True, render a FULL OUTER JOIN, instead of
  592. LEFT OUTER JOIN.
  593. .. seealso::
  594. :meth:`_expression.FromClause.join`
  595. :class:`_expression.Join`
  596. """ # noqa: E501
  597. return Join(self, right, onclause, True, full)
  598. def alias(
  599. self, name: Optional[str] = None, flat: bool = False
  600. ) -> NamedFromClause:
  601. """Return an alias of this :class:`_expression.FromClause`.
  602. E.g.::
  603. a2 = some_table.alias("a2")
  604. The above code creates an :class:`_expression.Alias`
  605. object which can be used
  606. as a FROM clause in any SELECT statement.
  607. .. seealso::
  608. :ref:`tutorial_using_aliases`
  609. :func:`_expression.alias`
  610. """
  611. return Alias._construct(self, name=name)
  612. def tablesample(
  613. self,
  614. sampling: Union[float, Function[Any]],
  615. name: Optional[str] = None,
  616. seed: Optional[roles.ExpressionElementRole[Any]] = None,
  617. ) -> TableSample:
  618. """Return a TABLESAMPLE alias of this :class:`_expression.FromClause`.
  619. The return value is the :class:`_expression.TableSample`
  620. construct also
  621. provided by the top-level :func:`_expression.tablesample` function.
  622. .. seealso::
  623. :func:`_expression.tablesample` - usage guidelines and parameters
  624. """
  625. return TableSample._construct(
  626. self, sampling=sampling, name=name, seed=seed
  627. )
  628. def is_derived_from(self, fromclause: Optional[FromClause]) -> bool:
  629. """Return ``True`` if this :class:`_expression.FromClause` is
  630. 'derived' from the given ``FromClause``.
  631. An example would be an Alias of a Table is derived from that Table.
  632. """
  633. # this is essentially an "identity" check in the base class.
  634. # Other constructs override this to traverse through
  635. # contained elements.
  636. return fromclause in self._cloned_set
  637. def _is_lexical_equivalent(self, other: FromClause) -> bool:
  638. """Return ``True`` if this :class:`_expression.FromClause` and
  639. the other represent the same lexical identity.
  640. This tests if either one is a copy of the other, or
  641. if they are the same via annotation identity.
  642. """
  643. return bool(self._cloned_set.intersection(other._cloned_set))
  644. @util.ro_non_memoized_property
  645. def description(self) -> str:
  646. """A brief description of this :class:`_expression.FromClause`.
  647. Used primarily for error message formatting.
  648. """
  649. return getattr(self, "name", self.__class__.__name__ + " object")
  650. def _generate_fromclause_column_proxies(
  651. self,
  652. fromclause: FromClause,
  653. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  654. primary_key: ColumnSet,
  655. foreign_keys: Set[KeyedColumnElement[Any]],
  656. ) -> None:
  657. columns._populate_separate_keys(
  658. col._make_proxy(
  659. fromclause, primary_key=primary_key, foreign_keys=foreign_keys
  660. )
  661. for col in self.c
  662. )
  663. @util.ro_non_memoized_property
  664. def exported_columns(
  665. self,
  666. ) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
  667. """A :class:`_expression.ColumnCollection`
  668. that represents the "exported"
  669. columns of this :class:`_expression.Selectable`.
  670. The "exported" columns for a :class:`_expression.FromClause`
  671. object are synonymous
  672. with the :attr:`_expression.FromClause.columns` collection.
  673. .. versionadded:: 1.4
  674. .. seealso::
  675. :attr:`_expression.Selectable.exported_columns`
  676. :attr:`_expression.SelectBase.exported_columns`
  677. """
  678. return self.c
  679. @util.ro_non_memoized_property
  680. def columns(
  681. self,
  682. ) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
  683. """A named-based collection of :class:`_expression.ColumnElement`
  684. objects maintained by this :class:`_expression.FromClause`.
  685. The :attr:`.columns`, or :attr:`.c` collection, is the gateway
  686. to the construction of SQL expressions using table-bound or
  687. other selectable-bound columns::
  688. select(mytable).where(mytable.c.somecolumn == 5)
  689. :return: a :class:`.ColumnCollection` object.
  690. """
  691. return self.c
  692. @util.ro_memoized_property
  693. def c(self) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
  694. """
  695. A synonym for :attr:`.FromClause.columns`
  696. :return: a :class:`.ColumnCollection`
  697. """
  698. if "_columns" not in self.__dict__:
  699. self._setup_collections()
  700. return self._columns.as_readonly()
  701. def _setup_collections(self) -> None:
  702. with util.mini_gil:
  703. # detect another thread that raced ahead
  704. if "_columns" in self.__dict__:
  705. assert "primary_key" in self.__dict__
  706. assert "foreign_keys" in self.__dict__
  707. return
  708. _columns: ColumnCollection[Any, Any] = ColumnCollection()
  709. primary_key = ColumnSet()
  710. foreign_keys: Set[KeyedColumnElement[Any]] = set()
  711. self._populate_column_collection(
  712. columns=_columns,
  713. primary_key=primary_key,
  714. foreign_keys=foreign_keys,
  715. )
  716. # assigning these three collections separately is not itself
  717. # atomic, but greatly reduces the surface for problems
  718. self._columns = _columns
  719. self.primary_key = primary_key # type: ignore
  720. self.foreign_keys = foreign_keys # type: ignore
  721. @util.ro_non_memoized_property
  722. def entity_namespace(self) -> _EntityNamespace:
  723. """Return a namespace used for name-based access in SQL expressions.
  724. This is the namespace that is used to resolve "filter_by()" type
  725. expressions, such as::
  726. stmt.filter_by(address="some address")
  727. It defaults to the ``.c`` collection, however internally it can
  728. be overridden using the "entity_namespace" annotation to deliver
  729. alternative results.
  730. """
  731. return self.c
  732. @util.ro_memoized_property
  733. def primary_key(self) -> Iterable[NamedColumn[Any]]:
  734. """Return the iterable collection of :class:`_schema.Column` objects
  735. which comprise the primary key of this :class:`_selectable.FromClause`.
  736. For a :class:`_schema.Table` object, this collection is represented
  737. by the :class:`_schema.PrimaryKeyConstraint` which itself is an
  738. iterable collection of :class:`_schema.Column` objects.
  739. """
  740. self._setup_collections()
  741. return self.primary_key
  742. @util.ro_memoized_property
  743. def foreign_keys(self) -> Iterable[ForeignKey]:
  744. """Return the collection of :class:`_schema.ForeignKey` marker objects
  745. which this FromClause references.
  746. Each :class:`_schema.ForeignKey` is a member of a
  747. :class:`_schema.Table`-wide
  748. :class:`_schema.ForeignKeyConstraint`.
  749. .. seealso::
  750. :attr:`_schema.Table.foreign_key_constraints`
  751. """
  752. self._setup_collections()
  753. return self.foreign_keys
  754. def _reset_column_collection(self) -> None:
  755. """Reset the attributes linked to the ``FromClause.c`` attribute.
  756. This collection is separate from all the other memoized things
  757. as it has shown to be sensitive to being cleared out in situations
  758. where enclosing code, typically in a replacement traversal scenario,
  759. has already established strong relationships
  760. with the exported columns.
  761. The collection is cleared for the case where a table is having a
  762. column added to it as well as within a Join during copy internals.
  763. """
  764. for key in ["_columns", "columns", "c", "primary_key", "foreign_keys"]:
  765. self.__dict__.pop(key, None)
  766. @util.ro_non_memoized_property
  767. def _select_iterable(self) -> _SelectIterable:
  768. return (c for c in self.c if not _never_select_column(c))
  769. @property
  770. def _cols_populated(self) -> bool:
  771. return "_columns" in self.__dict__
  772. def _populate_column_collection(
  773. self,
  774. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  775. primary_key: ColumnSet,
  776. foreign_keys: Set[KeyedColumnElement[Any]],
  777. ) -> None:
  778. """Called on subclasses to establish the .c collection.
  779. Each implementation has a different way of establishing
  780. this collection.
  781. """
  782. def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
  783. """Given a column added to the .c collection of an underlying
  784. selectable, produce the local version of that column, assuming this
  785. selectable ultimately should proxy this column.
  786. this is used to "ping" a derived selectable to add a new column
  787. to its .c. collection when a Column has been added to one of the
  788. Table objects it ultimately derives from.
  789. If the given selectable hasn't populated its .c. collection yet,
  790. it should at least pass on the message to the contained selectables,
  791. but it will return None.
  792. This method is currently used by Declarative to allow Table
  793. columns to be added to a partially constructed inheritance
  794. mapping that may have already produced joins. The method
  795. isn't public right now, as the full span of implications
  796. and/or caveats aren't yet clear.
  797. It's also possible that this functionality could be invoked by
  798. default via an event, which would require that
  799. selectables maintain a weak referencing collection of all
  800. derivations.
  801. """
  802. self._reset_column_collection()
  803. def _anonymous_fromclause(
  804. self, *, name: Optional[str] = None, flat: bool = False
  805. ) -> FromClause:
  806. return self.alias(name=name)
  807. if TYPE_CHECKING:
  808. def self_group(
  809. self, against: Optional[OperatorType] = None
  810. ) -> Union[FromGrouping, Self]: ...
  811. class NamedFromClause(FromClause):
  812. """A :class:`.FromClause` that has a name.
  813. Examples include tables, subqueries, CTEs, aliased tables.
  814. .. versionadded:: 2.0
  815. """
  816. named_with_column = True
  817. name: str
  818. @util.preload_module("sqlalchemy.sql.sqltypes")
  819. def table_valued(self) -> TableValuedColumn[Any]:
  820. """Return a :class:`_sql.TableValuedColumn` object for this
  821. :class:`_expression.FromClause`.
  822. A :class:`_sql.TableValuedColumn` is a :class:`_sql.ColumnElement` that
  823. represents a complete row in a table. Support for this construct is
  824. backend dependent, and is supported in various forms by backends
  825. such as PostgreSQL, Oracle Database and SQL Server.
  826. E.g.:
  827. .. sourcecode:: pycon+sql
  828. >>> from sqlalchemy import select, column, func, table
  829. >>> a = table("a", column("id"), column("x"), column("y"))
  830. >>> stmt = select(func.row_to_json(a.table_valued()))
  831. >>> print(stmt)
  832. {printsql}SELECT row_to_json(a) AS row_to_json_1
  833. FROM a
  834. .. versionadded:: 1.4.0b2
  835. .. seealso::
  836. :ref:`tutorial_functions` - in the :ref:`unified_tutorial`
  837. """
  838. return TableValuedColumn(self, type_api.TABLEVALUE)
  839. class SelectLabelStyle(Enum):
  840. """Label style constants that may be passed to
  841. :meth:`_sql.Select.set_label_style`."""
  842. LABEL_STYLE_NONE = 0
  843. """Label style indicating no automatic labeling should be applied to the
  844. columns clause of a SELECT statement.
  845. Below, the columns named ``columna`` are both rendered as is, meaning that
  846. the name ``columna`` can only refer to the first occurrence of this name
  847. within a result set, as well as if the statement were used as a subquery:
  848. .. sourcecode:: pycon+sql
  849. >>> from sqlalchemy import table, column, select, true, LABEL_STYLE_NONE
  850. >>> table1 = table("table1", column("columna"), column("columnb"))
  851. >>> table2 = table("table2", column("columna"), column("columnc"))
  852. >>> print(
  853. ... select(table1, table2)
  854. ... .join(table2, true())
  855. ... .set_label_style(LABEL_STYLE_NONE)
  856. ... )
  857. {printsql}SELECT table1.columna, table1.columnb, table2.columna, table2.columnc
  858. FROM table1 JOIN table2 ON true
  859. Used with the :meth:`_sql.Select.set_label_style` method.
  860. .. versionadded:: 1.4
  861. """ # noqa: E501
  862. LABEL_STYLE_TABLENAME_PLUS_COL = 1
  863. """Label style indicating all columns should be labeled as
  864. ``<tablename>_<columnname>`` when generating the columns clause of a SELECT
  865. statement, to disambiguate same-named columns referenced from different
  866. tables, aliases, or subqueries.
  867. Below, all column names are given a label so that the two same-named
  868. columns ``columna`` are disambiguated as ``table1_columna`` and
  869. ``table2_columna``:
  870. .. sourcecode:: pycon+sql
  871. >>> from sqlalchemy import (
  872. ... table,
  873. ... column,
  874. ... select,
  875. ... true,
  876. ... LABEL_STYLE_TABLENAME_PLUS_COL,
  877. ... )
  878. >>> table1 = table("table1", column("columna"), column("columnb"))
  879. >>> table2 = table("table2", column("columna"), column("columnc"))
  880. >>> print(
  881. ... select(table1, table2)
  882. ... .join(table2, true())
  883. ... .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  884. ... )
  885. {printsql}SELECT table1.columna AS table1_columna, table1.columnb AS table1_columnb, table2.columna AS table2_columna, table2.columnc AS table2_columnc
  886. FROM table1 JOIN table2 ON true
  887. Used with the :meth:`_sql.GenerativeSelect.set_label_style` method.
  888. Equivalent to the legacy method ``Select.apply_labels()``;
  889. :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL` is SQLAlchemy's legacy
  890. auto-labeling style. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` provides a
  891. less intrusive approach to disambiguation of same-named column expressions.
  892. .. versionadded:: 1.4
  893. """ # noqa: E501
  894. LABEL_STYLE_DISAMBIGUATE_ONLY = 2
  895. """Label style indicating that columns with a name that conflicts with
  896. an existing name should be labeled with a semi-anonymizing label
  897. when generating the columns clause of a SELECT statement.
  898. Below, most column names are left unaffected, except for the second
  899. occurrence of the name ``columna``, which is labeled using the
  900. label ``columna_1`` to disambiguate it from that of ``tablea.columna``:
  901. .. sourcecode:: pycon+sql
  902. >>> from sqlalchemy import (
  903. ... table,
  904. ... column,
  905. ... select,
  906. ... true,
  907. ... LABEL_STYLE_DISAMBIGUATE_ONLY,
  908. ... )
  909. >>> table1 = table("table1", column("columna"), column("columnb"))
  910. >>> table2 = table("table2", column("columna"), column("columnc"))
  911. >>> print(
  912. ... select(table1, table2)
  913. ... .join(table2, true())
  914. ... .set_label_style(LABEL_STYLE_DISAMBIGUATE_ONLY)
  915. ... )
  916. {printsql}SELECT table1.columna, table1.columnb, table2.columna AS columna_1, table2.columnc
  917. FROM table1 JOIN table2 ON true
  918. Used with the :meth:`_sql.GenerativeSelect.set_label_style` method,
  919. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` is the default labeling style
  920. for all SELECT statements outside of :term:`1.x style` ORM queries.
  921. .. versionadded:: 1.4
  922. """ # noqa: E501
  923. LABEL_STYLE_DEFAULT = LABEL_STYLE_DISAMBIGUATE_ONLY
  924. """The default label style, refers to
  925. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`.
  926. .. versionadded:: 1.4
  927. """
  928. LABEL_STYLE_LEGACY_ORM = 3
  929. (
  930. LABEL_STYLE_NONE,
  931. LABEL_STYLE_TABLENAME_PLUS_COL,
  932. LABEL_STYLE_DISAMBIGUATE_ONLY,
  933. _,
  934. ) = list(SelectLabelStyle)
  935. LABEL_STYLE_DEFAULT = LABEL_STYLE_DISAMBIGUATE_ONLY
  936. class Join(roles.DMLTableRole, FromClause):
  937. """Represent a ``JOIN`` construct between two
  938. :class:`_expression.FromClause`
  939. elements.
  940. The public constructor function for :class:`_expression.Join`
  941. is the module-level
  942. :func:`_expression.join()` function, as well as the
  943. :meth:`_expression.FromClause.join` method
  944. of any :class:`_expression.FromClause` (e.g. such as
  945. :class:`_schema.Table`).
  946. .. seealso::
  947. :func:`_expression.join`
  948. :meth:`_expression.FromClause.join`
  949. """
  950. __visit_name__ = "join"
  951. _traverse_internals: _TraverseInternalsType = [
  952. ("left", InternalTraversal.dp_clauseelement),
  953. ("right", InternalTraversal.dp_clauseelement),
  954. ("onclause", InternalTraversal.dp_clauseelement),
  955. ("isouter", InternalTraversal.dp_boolean),
  956. ("full", InternalTraversal.dp_boolean),
  957. ]
  958. _is_join = True
  959. left: FromClause
  960. right: FromClause
  961. onclause: Optional[ColumnElement[bool]]
  962. isouter: bool
  963. full: bool
  964. def __init__(
  965. self,
  966. left: _FromClauseArgument,
  967. right: _FromClauseArgument,
  968. onclause: Optional[_OnClauseArgument] = None,
  969. isouter: bool = False,
  970. full: bool = False,
  971. ):
  972. """Construct a new :class:`_expression.Join`.
  973. The usual entrypoint here is the :func:`_expression.join`
  974. function or the :meth:`_expression.FromClause.join` method of any
  975. :class:`_expression.FromClause` object.
  976. """
  977. # when deannotate was removed here, callcounts went up for ORM
  978. # compilation of eager joins, since there were more comparisons of
  979. # annotated objects. test_orm.py -> test_fetch_results
  980. # was therefore changed to show a more real-world use case, where the
  981. # compilation is cached; there's no change in post-cache callcounts.
  982. # callcounts for a single compilation in that particular test
  983. # that includes about eight joins about 1100 extra fn calls, from
  984. # 29200 -> 30373
  985. self.left = coercions.expect(
  986. roles.FromClauseRole,
  987. left,
  988. )
  989. self.right = coercions.expect(
  990. roles.FromClauseRole,
  991. right,
  992. ).self_group()
  993. if onclause is None:
  994. self.onclause = self._match_primaries(self.left, self.right)
  995. else:
  996. # note: taken from If91f61527236fd4d7ae3cad1f24c38be921c90ba
  997. # not merged yet
  998. self.onclause = coercions.expect(
  999. roles.OnClauseRole, onclause
  1000. ).self_group(against=operators._asbool)
  1001. self.isouter = isouter
  1002. self.full = full
  1003. @util.ro_non_memoized_property
  1004. def description(self) -> str:
  1005. return "Join object on %s(%d) and %s(%d)" % (
  1006. self.left.description,
  1007. id(self.left),
  1008. self.right.description,
  1009. id(self.right),
  1010. )
  1011. def is_derived_from(self, fromclause: Optional[FromClause]) -> bool:
  1012. return (
  1013. # use hash() to ensure direct comparison to annotated works
  1014. # as well
  1015. hash(fromclause) == hash(self)
  1016. or self.left.is_derived_from(fromclause)
  1017. or self.right.is_derived_from(fromclause)
  1018. )
  1019. def self_group(
  1020. self, against: Optional[OperatorType] = None
  1021. ) -> FromGrouping:
  1022. return FromGrouping(self)
  1023. @util.preload_module("sqlalchemy.sql.util")
  1024. def _populate_column_collection(
  1025. self,
  1026. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  1027. primary_key: ColumnSet,
  1028. foreign_keys: Set[KeyedColumnElement[Any]],
  1029. ) -> None:
  1030. sqlutil = util.preloaded.sql_util
  1031. _columns: List[KeyedColumnElement[Any]] = [c for c in self.left.c] + [
  1032. c for c in self.right.c
  1033. ]
  1034. primary_key.extend(
  1035. sqlutil.reduce_columns(
  1036. (c for c in _columns if c.primary_key), self.onclause
  1037. )
  1038. )
  1039. columns._populate_separate_keys(
  1040. (col._tq_key_label, col) for col in _columns # type: ignore
  1041. )
  1042. foreign_keys.update(
  1043. itertools.chain(*[col.foreign_keys for col in _columns]) # type: ignore # noqa: E501
  1044. )
  1045. def _copy_internals(
  1046. self, clone: _CloneCallableType = _clone, **kw: Any
  1047. ) -> None:
  1048. # see Select._copy_internals() for similar concept
  1049. # here we pre-clone "left" and "right" so that we can
  1050. # determine the new FROM clauses
  1051. all_the_froms = set(
  1052. itertools.chain(
  1053. _from_objects(self.left),
  1054. _from_objects(self.right),
  1055. )
  1056. )
  1057. # run the clone on those. these will be placed in the
  1058. # cache used by the clone function
  1059. new_froms = {f: clone(f, **kw) for f in all_the_froms}
  1060. # set up a special replace function that will replace for
  1061. # ColumnClause with parent table referring to those
  1062. # replaced FromClause objects
  1063. def replace(
  1064. obj: Union[BinaryExpression[Any], ColumnClause[Any]],
  1065. **kw: Any,
  1066. ) -> Optional[KeyedColumnElement[Any]]:
  1067. if isinstance(obj, ColumnClause) and obj.table in new_froms:
  1068. newelem = new_froms[obj.table].corresponding_column(obj)
  1069. return newelem
  1070. return None
  1071. kw["replace"] = replace
  1072. # run normal _copy_internals. the clones for
  1073. # left and right will come from the clone function's
  1074. # cache
  1075. super()._copy_internals(clone=clone, **kw)
  1076. self._reset_memoizations()
  1077. def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
  1078. super()._refresh_for_new_column(column)
  1079. self.left._refresh_for_new_column(column)
  1080. self.right._refresh_for_new_column(column)
  1081. def _match_primaries(
  1082. self,
  1083. left: FromClause,
  1084. right: FromClause,
  1085. ) -> ColumnElement[bool]:
  1086. if isinstance(left, Join):
  1087. left_right = left.right
  1088. else:
  1089. left_right = None
  1090. return self._join_condition(left, right, a_subset=left_right)
  1091. @classmethod
  1092. def _join_condition(
  1093. cls,
  1094. a: FromClause,
  1095. b: FromClause,
  1096. *,
  1097. a_subset: Optional[FromClause] = None,
  1098. consider_as_foreign_keys: Optional[
  1099. AbstractSet[ColumnClause[Any]]
  1100. ] = None,
  1101. ) -> ColumnElement[bool]:
  1102. """Create a join condition between two tables or selectables.
  1103. See sqlalchemy.sql.util.join_condition() for full docs.
  1104. """
  1105. constraints = cls._joincond_scan_left_right(
  1106. a, a_subset, b, consider_as_foreign_keys
  1107. )
  1108. if len(constraints) > 1:
  1109. cls._joincond_trim_constraints(
  1110. a, b, constraints, consider_as_foreign_keys
  1111. )
  1112. if len(constraints) == 0:
  1113. if isinstance(b, FromGrouping):
  1114. hint = (
  1115. " Perhaps you meant to convert the right side to a "
  1116. "subquery using alias()?"
  1117. )
  1118. else:
  1119. hint = ""
  1120. raise exc.NoForeignKeysError(
  1121. "Can't find any foreign key relationships "
  1122. "between '%s' and '%s'.%s"
  1123. % (a.description, b.description, hint)
  1124. )
  1125. crit = [(x == y) for x, y in list(constraints.values())[0]]
  1126. if len(crit) == 1:
  1127. return crit[0]
  1128. else:
  1129. return and_(*crit)
  1130. @classmethod
  1131. def _can_join(
  1132. cls,
  1133. left: FromClause,
  1134. right: FromClause,
  1135. *,
  1136. consider_as_foreign_keys: Optional[
  1137. AbstractSet[ColumnClause[Any]]
  1138. ] = None,
  1139. ) -> bool:
  1140. if isinstance(left, Join):
  1141. left_right = left.right
  1142. else:
  1143. left_right = None
  1144. constraints = cls._joincond_scan_left_right(
  1145. a=left,
  1146. b=right,
  1147. a_subset=left_right,
  1148. consider_as_foreign_keys=consider_as_foreign_keys,
  1149. )
  1150. return bool(constraints)
  1151. @classmethod
  1152. @util.preload_module("sqlalchemy.sql.util")
  1153. def _joincond_scan_left_right(
  1154. cls,
  1155. a: FromClause,
  1156. a_subset: Optional[FromClause],
  1157. b: FromClause,
  1158. consider_as_foreign_keys: Optional[AbstractSet[ColumnClause[Any]]],
  1159. ) -> collections.defaultdict[
  1160. Optional[ForeignKeyConstraint],
  1161. List[Tuple[ColumnClause[Any], ColumnClause[Any]]],
  1162. ]:
  1163. sql_util = util.preloaded.sql_util
  1164. a = coercions.expect(roles.FromClauseRole, a)
  1165. b = coercions.expect(roles.FromClauseRole, b)
  1166. constraints: collections.defaultdict[
  1167. Optional[ForeignKeyConstraint],
  1168. List[Tuple[ColumnClause[Any], ColumnClause[Any]]],
  1169. ] = collections.defaultdict(list)
  1170. for left in (a_subset, a):
  1171. if left is None:
  1172. continue
  1173. for fk in sorted(
  1174. b.foreign_keys,
  1175. key=lambda fk: fk.parent._creation_order,
  1176. ):
  1177. if (
  1178. consider_as_foreign_keys is not None
  1179. and fk.parent not in consider_as_foreign_keys
  1180. ):
  1181. continue
  1182. try:
  1183. col = fk.get_referent(left)
  1184. except exc.NoReferenceError as nrte:
  1185. table_names = {t.name for t in sql_util.find_tables(left)}
  1186. if nrte.table_name in table_names:
  1187. raise
  1188. else:
  1189. continue
  1190. if col is not None:
  1191. constraints[fk.constraint].append((col, fk.parent))
  1192. if left is not b:
  1193. for fk in sorted(
  1194. left.foreign_keys,
  1195. key=lambda fk: fk.parent._creation_order,
  1196. ):
  1197. if (
  1198. consider_as_foreign_keys is not None
  1199. and fk.parent not in consider_as_foreign_keys
  1200. ):
  1201. continue
  1202. try:
  1203. col = fk.get_referent(b)
  1204. except exc.NoReferenceError as nrte:
  1205. table_names = {t.name for t in sql_util.find_tables(b)}
  1206. if nrte.table_name in table_names:
  1207. raise
  1208. else:
  1209. continue
  1210. if col is not None:
  1211. constraints[fk.constraint].append((col, fk.parent))
  1212. if constraints:
  1213. break
  1214. return constraints
  1215. @classmethod
  1216. def _joincond_trim_constraints(
  1217. cls,
  1218. a: FromClause,
  1219. b: FromClause,
  1220. constraints: Dict[Any, Any],
  1221. consider_as_foreign_keys: Optional[Any],
  1222. ) -> None:
  1223. # more than one constraint matched. narrow down the list
  1224. # to include just those FKCs that match exactly to
  1225. # "consider_as_foreign_keys".
  1226. if consider_as_foreign_keys:
  1227. for const in list(constraints):
  1228. if {f.parent for f in const.elements} != set(
  1229. consider_as_foreign_keys
  1230. ):
  1231. del constraints[const]
  1232. # if still multiple constraints, but
  1233. # they all refer to the exact same end result, use it.
  1234. if len(constraints) > 1:
  1235. dedupe = {tuple(crit) for crit in constraints.values()}
  1236. if len(dedupe) == 1:
  1237. key = list(constraints)[0]
  1238. constraints = {key: constraints[key]}
  1239. if len(constraints) != 1:
  1240. raise exc.AmbiguousForeignKeysError(
  1241. "Can't determine join between '%s' and '%s'; "
  1242. "tables have more than one foreign key "
  1243. "constraint relationship between them. "
  1244. "Please specify the 'onclause' of this "
  1245. "join explicitly." % (a.description, b.description)
  1246. )
  1247. def select(self) -> Select[Any]:
  1248. r"""Create a :class:`_expression.Select` from this
  1249. :class:`_expression.Join`.
  1250. E.g.::
  1251. stmt = table_a.join(table_b, table_a.c.id == table_b.c.a_id)
  1252. stmt = stmt.select()
  1253. The above will produce a SQL string resembling:
  1254. .. sourcecode:: sql
  1255. SELECT table_a.id, table_a.col, table_b.id, table_b.a_id
  1256. FROM table_a JOIN table_b ON table_a.id = table_b.a_id
  1257. """
  1258. return Select(self.left, self.right).select_from(self)
  1259. @util.preload_module("sqlalchemy.sql.util")
  1260. def _anonymous_fromclause(
  1261. self, name: Optional[str] = None, flat: bool = False
  1262. ) -> TODO_Any:
  1263. sqlutil = util.preloaded.sql_util
  1264. if flat:
  1265. if isinstance(self.left, (FromGrouping, Join)):
  1266. left_name = name # will recurse
  1267. else:
  1268. if name and isinstance(self.left, NamedFromClause):
  1269. left_name = f"{name}_{self.left.name}"
  1270. else:
  1271. left_name = name
  1272. if isinstance(self.right, (FromGrouping, Join)):
  1273. right_name = name # will recurse
  1274. else:
  1275. if name and isinstance(self.right, NamedFromClause):
  1276. right_name = f"{name}_{self.right.name}"
  1277. else:
  1278. right_name = name
  1279. left_a, right_a = (
  1280. self.left._anonymous_fromclause(name=left_name, flat=flat),
  1281. self.right._anonymous_fromclause(name=right_name, flat=flat),
  1282. )
  1283. adapter = sqlutil.ClauseAdapter(left_a).chain(
  1284. sqlutil.ClauseAdapter(right_a)
  1285. )
  1286. return left_a.join(
  1287. right_a,
  1288. adapter.traverse(self.onclause),
  1289. isouter=self.isouter,
  1290. full=self.full,
  1291. )
  1292. else:
  1293. return (
  1294. self.select()
  1295. .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  1296. .correlate(None)
  1297. .alias(name)
  1298. )
  1299. @util.ro_non_memoized_property
  1300. def _hide_froms(self) -> Iterable[FromClause]:
  1301. return itertools.chain(
  1302. *[_from_objects(x.left, x.right) for x in self._cloned_set]
  1303. )
  1304. @util.ro_non_memoized_property
  1305. def _from_objects(self) -> List[FromClause]:
  1306. self_list: List[FromClause] = [self]
  1307. return self_list + self.left._from_objects + self.right._from_objects
  1308. class NoInit:
  1309. def __init__(self, *arg: Any, **kw: Any):
  1310. raise NotImplementedError(
  1311. "The %s class is not intended to be constructed "
  1312. "directly. Please use the %s() standalone "
  1313. "function or the %s() method available from appropriate "
  1314. "selectable objects."
  1315. % (
  1316. self.__class__.__name__,
  1317. self.__class__.__name__.lower(),
  1318. self.__class__.__name__.lower(),
  1319. )
  1320. )
  1321. class LateralFromClause(NamedFromClause):
  1322. """mark a FROM clause as being able to render directly as LATERAL"""
  1323. # FromClause ->
  1324. # AliasedReturnsRows
  1325. # -> Alias only for FromClause
  1326. # -> Subquery only for SelectBase
  1327. # -> CTE only for HasCTE -> SelectBase, DML
  1328. # -> Lateral -> FromClause, but we accept SelectBase
  1329. # w/ non-deprecated coercion
  1330. # -> TableSample -> only for FromClause
  1331. class AliasedReturnsRows(NoInit, NamedFromClause):
  1332. """Base class of aliases against tables, subqueries, and other
  1333. selectables."""
  1334. _is_from_container = True
  1335. _supports_derived_columns = False
  1336. element: ReturnsRows
  1337. _traverse_internals: _TraverseInternalsType = [
  1338. ("element", InternalTraversal.dp_clauseelement),
  1339. ("name", InternalTraversal.dp_anon_name),
  1340. ]
  1341. @classmethod
  1342. def _construct(
  1343. cls,
  1344. selectable: Any,
  1345. *,
  1346. name: Optional[str] = None,
  1347. **kw: Any,
  1348. ) -> Self:
  1349. obj = cls.__new__(cls)
  1350. obj._init(selectable, name=name, **kw)
  1351. return obj
  1352. def _init(self, selectable: Any, *, name: Optional[str] = None) -> None:
  1353. self.element = coercions.expect(
  1354. roles.ReturnsRowsRole, selectable, apply_propagate_attrs=self
  1355. )
  1356. self.element = selectable
  1357. self._orig_name = name
  1358. if name is None:
  1359. if (
  1360. isinstance(selectable, FromClause)
  1361. and selectable.named_with_column
  1362. ):
  1363. name = getattr(selectable, "name", None)
  1364. if isinstance(name, _anonymous_label):
  1365. name = None
  1366. name = _anonymous_label.safe_construct(id(self), name or "anon")
  1367. self.name = name
  1368. def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
  1369. super()._refresh_for_new_column(column)
  1370. self.element._refresh_for_new_column(column)
  1371. def _populate_column_collection(
  1372. self,
  1373. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  1374. primary_key: ColumnSet,
  1375. foreign_keys: Set[KeyedColumnElement[Any]],
  1376. ) -> None:
  1377. self.element._generate_fromclause_column_proxies(
  1378. self, columns, primary_key=primary_key, foreign_keys=foreign_keys
  1379. )
  1380. @util.ro_non_memoized_property
  1381. def description(self) -> str:
  1382. name = self.name
  1383. if isinstance(name, _anonymous_label):
  1384. return "anon_1"
  1385. return name
  1386. @util.ro_non_memoized_property
  1387. def implicit_returning(self) -> bool:
  1388. return self.element.implicit_returning # type: ignore
  1389. @property
  1390. def original(self) -> ReturnsRows:
  1391. """Legacy for dialects that are referring to Alias.original."""
  1392. return self.element
  1393. def is_derived_from(self, fromclause: Optional[FromClause]) -> bool:
  1394. if fromclause in self._cloned_set:
  1395. return True
  1396. return self.element.is_derived_from(fromclause)
  1397. def _copy_internals(
  1398. self, clone: _CloneCallableType = _clone, **kw: Any
  1399. ) -> None:
  1400. existing_element = self.element
  1401. super()._copy_internals(clone=clone, **kw)
  1402. # the element clone is usually against a Table that returns the
  1403. # same object. don't reset exported .c. collections and other
  1404. # memoized details if it was not changed. this saves a lot on
  1405. # performance.
  1406. if existing_element is not self.element:
  1407. self._reset_column_collection()
  1408. @property
  1409. def _from_objects(self) -> List[FromClause]:
  1410. return [self]
  1411. class FromClauseAlias(AliasedReturnsRows):
  1412. element: FromClause
  1413. @util.ro_non_memoized_property
  1414. def description(self) -> str:
  1415. name = self.name
  1416. if isinstance(name, _anonymous_label):
  1417. return f"Anonymous alias of {self.element.description}"
  1418. return name
  1419. class Alias(roles.DMLTableRole, FromClauseAlias):
  1420. """Represents an table or selectable alias (AS).
  1421. Represents an alias, as typically applied to any table or
  1422. sub-select within a SQL statement using the ``AS`` keyword (or
  1423. without the keyword on certain databases such as Oracle Database).
  1424. This object is constructed from the :func:`_expression.alias` module
  1425. level function as well as the :meth:`_expression.FromClause.alias`
  1426. method available
  1427. on all :class:`_expression.FromClause` subclasses.
  1428. .. seealso::
  1429. :meth:`_expression.FromClause.alias`
  1430. """
  1431. __visit_name__ = "alias"
  1432. inherit_cache = True
  1433. element: FromClause
  1434. @classmethod
  1435. def _factory(
  1436. cls,
  1437. selectable: FromClause,
  1438. name: Optional[str] = None,
  1439. flat: bool = False,
  1440. ) -> NamedFromClause:
  1441. return coercions.expect(
  1442. roles.FromClauseRole, selectable, allow_select=True
  1443. ).alias(name=name, flat=flat)
  1444. class TableValuedAlias(LateralFromClause, Alias):
  1445. """An alias against a "table valued" SQL function.
  1446. This construct provides for a SQL function that returns columns
  1447. to be used in the FROM clause of a SELECT statement. The
  1448. object is generated using the :meth:`_functions.FunctionElement.table_valued`
  1449. method, e.g.:
  1450. .. sourcecode:: pycon+sql
  1451. >>> from sqlalchemy import select, func
  1452. >>> fn = func.json_array_elements_text('["one", "two", "three"]').table_valued(
  1453. ... "value"
  1454. ... )
  1455. >>> print(select(fn.c.value))
  1456. {printsql}SELECT anon_1.value
  1457. FROM json_array_elements_text(:json_array_elements_text_1) AS anon_1
  1458. .. versionadded:: 1.4.0b2
  1459. .. seealso::
  1460. :ref:`tutorial_functions_table_valued` - in the :ref:`unified_tutorial`
  1461. """ # noqa: E501
  1462. __visit_name__ = "table_valued_alias"
  1463. _supports_derived_columns = True
  1464. _render_derived = False
  1465. _render_derived_w_types = False
  1466. joins_implicitly = False
  1467. _traverse_internals: _TraverseInternalsType = [
  1468. ("element", InternalTraversal.dp_clauseelement),
  1469. ("name", InternalTraversal.dp_anon_name),
  1470. ("_tableval_type", InternalTraversal.dp_type),
  1471. ("_render_derived", InternalTraversal.dp_boolean),
  1472. ("_render_derived_w_types", InternalTraversal.dp_boolean),
  1473. ]
  1474. def _init(
  1475. self,
  1476. selectable: Any,
  1477. *,
  1478. name: Optional[str] = None,
  1479. table_value_type: Optional[TableValueType] = None,
  1480. joins_implicitly: bool = False,
  1481. ) -> None:
  1482. super()._init(selectable, name=name)
  1483. self.joins_implicitly = joins_implicitly
  1484. self._tableval_type = (
  1485. type_api.TABLEVALUE
  1486. if table_value_type is None
  1487. else table_value_type
  1488. )
  1489. @HasMemoized.memoized_attribute
  1490. def column(self) -> TableValuedColumn[Any]:
  1491. """Return a column expression representing this
  1492. :class:`_sql.TableValuedAlias`.
  1493. This accessor is used to implement the
  1494. :meth:`_functions.FunctionElement.column_valued` method. See that
  1495. method for further details.
  1496. E.g.:
  1497. .. sourcecode:: pycon+sql
  1498. >>> print(select(func.some_func().table_valued("value").column))
  1499. {printsql}SELECT anon_1 FROM some_func() AS anon_1
  1500. .. seealso::
  1501. :meth:`_functions.FunctionElement.column_valued`
  1502. """
  1503. return TableValuedColumn(self, self._tableval_type)
  1504. def alias(
  1505. self, name: Optional[str] = None, flat: bool = False
  1506. ) -> TableValuedAlias:
  1507. """Return a new alias of this :class:`_sql.TableValuedAlias`.
  1508. This creates a distinct FROM object that will be distinguished
  1509. from the original one when used in a SQL statement.
  1510. """
  1511. tva: TableValuedAlias = TableValuedAlias._construct(
  1512. self,
  1513. name=name,
  1514. table_value_type=self._tableval_type,
  1515. joins_implicitly=self.joins_implicitly,
  1516. )
  1517. if self._render_derived:
  1518. tva._render_derived = True
  1519. tva._render_derived_w_types = self._render_derived_w_types
  1520. return tva
  1521. def lateral(self, name: Optional[str] = None) -> LateralFromClause:
  1522. """Return a new :class:`_sql.TableValuedAlias` with the lateral flag
  1523. set, so that it renders as LATERAL.
  1524. .. seealso::
  1525. :func:`_expression.lateral`
  1526. """
  1527. tva = self.alias(name=name)
  1528. tva._is_lateral = True
  1529. return tva
  1530. def render_derived(
  1531. self,
  1532. name: Optional[str] = None,
  1533. with_types: bool = False,
  1534. ) -> TableValuedAlias:
  1535. """Apply "render derived" to this :class:`_sql.TableValuedAlias`.
  1536. This has the effect of the individual column names listed out
  1537. after the alias name in the "AS" sequence, e.g.:
  1538. .. sourcecode:: pycon+sql
  1539. >>> print(
  1540. ... select(
  1541. ... func.unnest(array(["one", "two", "three"]))
  1542. ... .table_valued("x", with_ordinality="o")
  1543. ... .render_derived()
  1544. ... )
  1545. ... )
  1546. {printsql}SELECT anon_1.x, anon_1.o
  1547. FROM unnest(ARRAY[%(param_1)s, %(param_2)s, %(param_3)s]) WITH ORDINALITY AS anon_1(x, o)
  1548. The ``with_types`` keyword will render column types inline within
  1549. the alias expression (this syntax currently applies to the
  1550. PostgreSQL database):
  1551. .. sourcecode:: pycon+sql
  1552. >>> print(
  1553. ... select(
  1554. ... func.json_to_recordset('[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]')
  1555. ... .table_valued(column("a", Integer), column("b", String))
  1556. ... .render_derived(with_types=True)
  1557. ... )
  1558. ... )
  1559. {printsql}SELECT anon_1.a, anon_1.b FROM json_to_recordset(:json_to_recordset_1)
  1560. AS anon_1(a INTEGER, b VARCHAR)
  1561. :param name: optional string name that will be applied to the alias
  1562. generated. If left as None, a unique anonymizing name will be used.
  1563. :param with_types: if True, the derived columns will include the
  1564. datatype specification with each column. This is a special syntax
  1565. currently known to be required by PostgreSQL for some SQL functions.
  1566. """ # noqa: E501
  1567. # note: don't use the @_generative system here, keep a reference
  1568. # to the original object. otherwise you can have reuse of the
  1569. # python id() of the original which can cause name conflicts if
  1570. # a new anon-name grabs the same identifier as the local anon-name
  1571. # (just saw it happen on CI)
  1572. # construct against original to prevent memory growth
  1573. # for repeated generations
  1574. new_alias: TableValuedAlias = TableValuedAlias._construct(
  1575. self.element,
  1576. name=name,
  1577. table_value_type=self._tableval_type,
  1578. joins_implicitly=self.joins_implicitly,
  1579. )
  1580. new_alias._render_derived = True
  1581. new_alias._render_derived_w_types = with_types
  1582. return new_alias
  1583. class Lateral(FromClauseAlias, LateralFromClause):
  1584. """Represent a LATERAL subquery.
  1585. This object is constructed from the :func:`_expression.lateral` module
  1586. level function as well as the :meth:`_expression.FromClause.lateral`
  1587. method available
  1588. on all :class:`_expression.FromClause` subclasses.
  1589. While LATERAL is part of the SQL standard, currently only more recent
  1590. PostgreSQL versions provide support for this keyword.
  1591. .. seealso::
  1592. :ref:`tutorial_lateral_correlation` - overview of usage.
  1593. """
  1594. __visit_name__ = "lateral"
  1595. _is_lateral = True
  1596. inherit_cache = True
  1597. @classmethod
  1598. def _factory(
  1599. cls,
  1600. selectable: Union[SelectBase, _FromClauseArgument],
  1601. name: Optional[str] = None,
  1602. ) -> LateralFromClause:
  1603. return coercions.expect(
  1604. roles.FromClauseRole, selectable, explicit_subquery=True
  1605. ).lateral(name=name)
  1606. class TableSample(FromClauseAlias):
  1607. """Represent a TABLESAMPLE clause.
  1608. This object is constructed from the :func:`_expression.tablesample` module
  1609. level function as well as the :meth:`_expression.FromClause.tablesample`
  1610. method
  1611. available on all :class:`_expression.FromClause` subclasses.
  1612. .. seealso::
  1613. :func:`_expression.tablesample`
  1614. """
  1615. __visit_name__ = "tablesample"
  1616. _traverse_internals: _TraverseInternalsType = (
  1617. AliasedReturnsRows._traverse_internals
  1618. + [
  1619. ("sampling", InternalTraversal.dp_clauseelement),
  1620. ("seed", InternalTraversal.dp_clauseelement),
  1621. ]
  1622. )
  1623. @classmethod
  1624. def _factory(
  1625. cls,
  1626. selectable: _FromClauseArgument,
  1627. sampling: Union[float, Function[Any]],
  1628. name: Optional[str] = None,
  1629. seed: Optional[roles.ExpressionElementRole[Any]] = None,
  1630. ) -> TableSample:
  1631. return coercions.expect(roles.FromClauseRole, selectable).tablesample(
  1632. sampling, name=name, seed=seed
  1633. )
  1634. @util.preload_module("sqlalchemy.sql.functions")
  1635. def _init( # type: ignore[override]
  1636. self,
  1637. selectable: Any,
  1638. *,
  1639. name: Optional[str] = None,
  1640. sampling: Union[float, Function[Any]],
  1641. seed: Optional[roles.ExpressionElementRole[Any]] = None,
  1642. ) -> None:
  1643. assert sampling is not None
  1644. functions = util.preloaded.sql_functions
  1645. if not isinstance(sampling, functions.Function):
  1646. sampling = functions.func.system(sampling)
  1647. self.sampling: Function[Any] = sampling
  1648. self.seed = seed
  1649. super()._init(selectable, name=name)
  1650. def _get_method(self) -> Function[Any]:
  1651. return self.sampling
  1652. class CTE(
  1653. roles.DMLTableRole,
  1654. roles.IsCTERole,
  1655. Generative,
  1656. HasPrefixes,
  1657. HasSuffixes,
  1658. AliasedReturnsRows,
  1659. ):
  1660. """Represent a Common Table Expression.
  1661. The :class:`_expression.CTE` object is obtained using the
  1662. :meth:`_sql.SelectBase.cte` method from any SELECT statement. A less often
  1663. available syntax also allows use of the :meth:`_sql.HasCTE.cte` method
  1664. present on :term:`DML` constructs such as :class:`_sql.Insert`,
  1665. :class:`_sql.Update` and
  1666. :class:`_sql.Delete`. See the :meth:`_sql.HasCTE.cte` method for
  1667. usage details on CTEs.
  1668. .. seealso::
  1669. :ref:`tutorial_subqueries_ctes` - in the 2.0 tutorial
  1670. :meth:`_sql.HasCTE.cte` - examples of calling styles
  1671. """
  1672. __visit_name__ = "cte"
  1673. _traverse_internals: _TraverseInternalsType = (
  1674. AliasedReturnsRows._traverse_internals
  1675. + [
  1676. ("_cte_alias", InternalTraversal.dp_clauseelement),
  1677. ("_restates", InternalTraversal.dp_clauseelement),
  1678. ("recursive", InternalTraversal.dp_boolean),
  1679. ("nesting", InternalTraversal.dp_boolean),
  1680. ]
  1681. + HasPrefixes._has_prefixes_traverse_internals
  1682. + HasSuffixes._has_suffixes_traverse_internals
  1683. )
  1684. element: HasCTE
  1685. @classmethod
  1686. def _factory(
  1687. cls,
  1688. selectable: HasCTE,
  1689. name: Optional[str] = None,
  1690. recursive: bool = False,
  1691. ) -> CTE:
  1692. r"""Return a new :class:`_expression.CTE`,
  1693. or Common Table Expression instance.
  1694. Please see :meth:`_expression.HasCTE.cte` for detail on CTE usage.
  1695. """
  1696. return coercions.expect(roles.HasCTERole, selectable).cte(
  1697. name=name, recursive=recursive
  1698. )
  1699. def _init(
  1700. self,
  1701. selectable: Select[Any],
  1702. *,
  1703. name: Optional[str] = None,
  1704. recursive: bool = False,
  1705. nesting: bool = False,
  1706. _cte_alias: Optional[CTE] = None,
  1707. _restates: Optional[CTE] = None,
  1708. _prefixes: Optional[Tuple[()]] = None,
  1709. _suffixes: Optional[Tuple[()]] = None,
  1710. ) -> None:
  1711. self.recursive = recursive
  1712. self.nesting = nesting
  1713. self._cte_alias = _cte_alias
  1714. # Keep recursivity reference with union/union_all
  1715. self._restates = _restates
  1716. if _prefixes:
  1717. self._prefixes = _prefixes
  1718. if _suffixes:
  1719. self._suffixes = _suffixes
  1720. super()._init(selectable, name=name)
  1721. def _populate_column_collection(
  1722. self,
  1723. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  1724. primary_key: ColumnSet,
  1725. foreign_keys: Set[KeyedColumnElement[Any]],
  1726. ) -> None:
  1727. if self._cte_alias is not None:
  1728. self._cte_alias._generate_fromclause_column_proxies(
  1729. self,
  1730. columns,
  1731. primary_key=primary_key,
  1732. foreign_keys=foreign_keys,
  1733. )
  1734. else:
  1735. self.element._generate_fromclause_column_proxies(
  1736. self,
  1737. columns,
  1738. primary_key=primary_key,
  1739. foreign_keys=foreign_keys,
  1740. )
  1741. def alias(self, name: Optional[str] = None, flat: bool = False) -> CTE:
  1742. """Return an :class:`_expression.Alias` of this
  1743. :class:`_expression.CTE`.
  1744. This method is a CTE-specific specialization of the
  1745. :meth:`_expression.FromClause.alias` method.
  1746. .. seealso::
  1747. :ref:`tutorial_using_aliases`
  1748. :func:`_expression.alias`
  1749. """
  1750. return CTE._construct(
  1751. self.element,
  1752. name=name,
  1753. recursive=self.recursive,
  1754. nesting=self.nesting,
  1755. _cte_alias=self,
  1756. _prefixes=self._prefixes,
  1757. _suffixes=self._suffixes,
  1758. )
  1759. def union(self, *other: _SelectStatementForCompoundArgument[Any]) -> CTE:
  1760. r"""Return a new :class:`_expression.CTE` with a SQL ``UNION``
  1761. of the original CTE against the given selectables provided
  1762. as positional arguments.
  1763. :param \*other: one or more elements with which to create a
  1764. UNION.
  1765. .. versionchanged:: 1.4.28 multiple elements are now accepted.
  1766. .. seealso::
  1767. :meth:`_sql.HasCTE.cte` - examples of calling styles
  1768. """
  1769. assert is_select_statement(
  1770. self.element
  1771. ), f"CTE element f{self.element} does not support union()"
  1772. return CTE._construct(
  1773. self.element.union(*other),
  1774. name=self.name,
  1775. recursive=self.recursive,
  1776. nesting=self.nesting,
  1777. _restates=self,
  1778. _prefixes=self._prefixes,
  1779. _suffixes=self._suffixes,
  1780. )
  1781. def union_all(
  1782. self, *other: _SelectStatementForCompoundArgument[Any]
  1783. ) -> CTE:
  1784. r"""Return a new :class:`_expression.CTE` with a SQL ``UNION ALL``
  1785. of the original CTE against the given selectables provided
  1786. as positional arguments.
  1787. :param \*other: one or more elements with which to create a
  1788. UNION.
  1789. .. versionchanged:: 1.4.28 multiple elements are now accepted.
  1790. .. seealso::
  1791. :meth:`_sql.HasCTE.cte` - examples of calling styles
  1792. """
  1793. assert is_select_statement(
  1794. self.element
  1795. ), f"CTE element f{self.element} does not support union_all()"
  1796. return CTE._construct(
  1797. self.element.union_all(*other),
  1798. name=self.name,
  1799. recursive=self.recursive,
  1800. nesting=self.nesting,
  1801. _restates=self,
  1802. _prefixes=self._prefixes,
  1803. _suffixes=self._suffixes,
  1804. )
  1805. def _get_reference_cte(self) -> CTE:
  1806. """
  1807. A recursive CTE is updated to attach the recursive part.
  1808. Updated CTEs should still refer to the original CTE.
  1809. This function returns this reference identifier.
  1810. """
  1811. return self._restates if self._restates is not None else self
  1812. class _CTEOpts(NamedTuple):
  1813. nesting: bool
  1814. class _ColumnsPlusNames(NamedTuple):
  1815. required_label_name: Optional[str]
  1816. """
  1817. string label name, if non-None, must be rendered as a
  1818. label, i.e. "AS <name>"
  1819. """
  1820. proxy_key: Optional[str]
  1821. """
  1822. proxy_key that is to be part of the result map for this
  1823. col. this is also the key in a fromclause.c or
  1824. select.selected_columns collection
  1825. """
  1826. fallback_label_name: Optional[str]
  1827. """
  1828. name that can be used to render an "AS <name>" when
  1829. we have to render a label even though
  1830. required_label_name was not given
  1831. """
  1832. column: Union[ColumnElement[Any], TextClause]
  1833. """
  1834. the ColumnElement itself
  1835. """
  1836. repeated: bool
  1837. """
  1838. True if this is a duplicate of a previous column
  1839. in the list of columns
  1840. """
  1841. class SelectsRows(ReturnsRows):
  1842. """Sub-base of ReturnsRows for elements that deliver rows
  1843. directly, namely SELECT and INSERT/UPDATE/DELETE..RETURNING"""
  1844. _label_style: SelectLabelStyle = LABEL_STYLE_NONE
  1845. def _generate_columns_plus_names(
  1846. self,
  1847. anon_for_dupe_key: bool,
  1848. cols: Optional[_SelectIterable] = None,
  1849. ) -> List[_ColumnsPlusNames]:
  1850. """Generate column names as rendered in a SELECT statement by
  1851. the compiler, as well as tokens used to populate the .c. collection
  1852. on a :class:`.FromClause`.
  1853. This is distinct from the _column_naming_convention generator that's
  1854. intended for population of the Select.selected_columns collection,
  1855. different rules. the collection returned here calls upon the
  1856. _column_naming_convention as well.
  1857. """
  1858. if cols is None:
  1859. cols = self._all_selected_columns
  1860. key_naming_convention = SelectState._column_naming_convention(
  1861. self._label_style
  1862. )
  1863. names = {}
  1864. result: List[_ColumnsPlusNames] = []
  1865. result_append = result.append
  1866. table_qualified = self._label_style is LABEL_STYLE_TABLENAME_PLUS_COL
  1867. label_style_none = self._label_style is LABEL_STYLE_NONE
  1868. # a counter used for "dedupe" labels, which have double underscores
  1869. # in them and are never referred by name; they only act
  1870. # as positional placeholders. they need only be unique within
  1871. # the single columns clause they're rendered within (required by
  1872. # some dbs such as mysql). So their anon identity is tracked against
  1873. # a fixed counter rather than hash() identity.
  1874. dedupe_hash = 1
  1875. for c in cols:
  1876. repeated = False
  1877. if not c._render_label_in_columns_clause:
  1878. effective_name = required_label_name = fallback_label_name = (
  1879. None
  1880. )
  1881. elif label_style_none:
  1882. if TYPE_CHECKING:
  1883. assert is_column_element(c)
  1884. effective_name = required_label_name = None
  1885. fallback_label_name = c._non_anon_label or c._anon_name_label
  1886. else:
  1887. if TYPE_CHECKING:
  1888. assert is_column_element(c)
  1889. if table_qualified:
  1890. required_label_name = effective_name = (
  1891. fallback_label_name
  1892. ) = c._tq_label
  1893. else:
  1894. effective_name = fallback_label_name = c._non_anon_label
  1895. required_label_name = None
  1896. if effective_name is None:
  1897. # it seems like this could be _proxy_key and we would
  1898. # not need _expression_label but it isn't
  1899. # giving us a clue when to use anon_label instead
  1900. expr_label = c._expression_label
  1901. if expr_label is None:
  1902. repeated = c._anon_name_label in names
  1903. names[c._anon_name_label] = c
  1904. effective_name = required_label_name = None
  1905. if repeated:
  1906. # here, "required_label_name" is sent as
  1907. # "None" and "fallback_label_name" is sent.
  1908. if table_qualified:
  1909. fallback_label_name = (
  1910. c._dedupe_anon_tq_label_idx(dedupe_hash)
  1911. )
  1912. dedupe_hash += 1
  1913. else:
  1914. fallback_label_name = c._dedupe_anon_label_idx(
  1915. dedupe_hash
  1916. )
  1917. dedupe_hash += 1
  1918. else:
  1919. fallback_label_name = c._anon_name_label
  1920. else:
  1921. required_label_name = effective_name = (
  1922. fallback_label_name
  1923. ) = expr_label
  1924. if effective_name is not None:
  1925. if TYPE_CHECKING:
  1926. assert is_column_element(c)
  1927. if effective_name in names:
  1928. # when looking to see if names[name] is the same column as
  1929. # c, use hash(), so that an annotated version of the column
  1930. # is seen as the same as the non-annotated
  1931. if hash(names[effective_name]) != hash(c):
  1932. # different column under the same name. apply
  1933. # disambiguating label
  1934. if table_qualified:
  1935. required_label_name = fallback_label_name = (
  1936. c._anon_tq_label
  1937. )
  1938. else:
  1939. required_label_name = fallback_label_name = (
  1940. c._anon_name_label
  1941. )
  1942. if anon_for_dupe_key and required_label_name in names:
  1943. # here, c._anon_tq_label is definitely unique to
  1944. # that column identity (or annotated version), so
  1945. # this should always be true.
  1946. # this is also an infrequent codepath because
  1947. # you need two levels of duplication to be here
  1948. assert hash(names[required_label_name]) == hash(c)
  1949. # the column under the disambiguating label is
  1950. # already present. apply the "dedupe" label to
  1951. # subsequent occurrences of the column so that the
  1952. # original stays non-ambiguous
  1953. if table_qualified:
  1954. required_label_name = fallback_label_name = (
  1955. c._dedupe_anon_tq_label_idx(dedupe_hash)
  1956. )
  1957. dedupe_hash += 1
  1958. else:
  1959. required_label_name = fallback_label_name = (
  1960. c._dedupe_anon_label_idx(dedupe_hash)
  1961. )
  1962. dedupe_hash += 1
  1963. repeated = True
  1964. else:
  1965. names[required_label_name] = c
  1966. elif anon_for_dupe_key:
  1967. # same column under the same name. apply the "dedupe"
  1968. # label so that the original stays non-ambiguous
  1969. if table_qualified:
  1970. required_label_name = fallback_label_name = (
  1971. c._dedupe_anon_tq_label_idx(dedupe_hash)
  1972. )
  1973. dedupe_hash += 1
  1974. else:
  1975. required_label_name = fallback_label_name = (
  1976. c._dedupe_anon_label_idx(dedupe_hash)
  1977. )
  1978. dedupe_hash += 1
  1979. repeated = True
  1980. else:
  1981. names[effective_name] = c
  1982. result_append(
  1983. _ColumnsPlusNames(
  1984. required_label_name,
  1985. key_naming_convention(c),
  1986. fallback_label_name,
  1987. c,
  1988. repeated,
  1989. )
  1990. )
  1991. return result
  1992. class HasCTE(roles.HasCTERole, SelectsRows):
  1993. """Mixin that declares a class to include CTE support."""
  1994. _has_ctes_traverse_internals: _TraverseInternalsType = [
  1995. ("_independent_ctes", InternalTraversal.dp_clauseelement_list),
  1996. ("_independent_ctes_opts", InternalTraversal.dp_plain_obj),
  1997. ]
  1998. _independent_ctes: Tuple[CTE, ...] = ()
  1999. _independent_ctes_opts: Tuple[_CTEOpts, ...] = ()
  2000. name_cte_columns: bool = False
  2001. """indicates if this HasCTE as contained within a CTE should compel the CTE
  2002. to render the column names of this object in the WITH clause.
  2003. .. versionadded:: 2.0.42
  2004. """
  2005. @_generative
  2006. def add_cte(self, *ctes: CTE, nest_here: bool = False) -> Self:
  2007. r"""Add one or more :class:`_sql.CTE` constructs to this statement.
  2008. This method will associate the given :class:`_sql.CTE` constructs with
  2009. the parent statement such that they will each be unconditionally
  2010. rendered in the WITH clause of the final statement, even if not
  2011. referenced elsewhere within the statement or any sub-selects.
  2012. The optional :paramref:`.HasCTE.add_cte.nest_here` parameter when set
  2013. to True will have the effect that each given :class:`_sql.CTE` will
  2014. render in a WITH clause rendered directly along with this statement,
  2015. rather than being moved to the top of the ultimate rendered statement,
  2016. even if this statement is rendered as a subquery within a larger
  2017. statement.
  2018. This method has two general uses. One is to embed CTE statements that
  2019. serve some purpose without being referenced explicitly, such as the use
  2020. case of embedding a DML statement such as an INSERT or UPDATE as a CTE
  2021. inline with a primary statement that may draw from its results
  2022. indirectly. The other is to provide control over the exact placement
  2023. of a particular series of CTE constructs that should remain rendered
  2024. directly in terms of a particular statement that may be nested in a
  2025. larger statement.
  2026. E.g.::
  2027. from sqlalchemy import table, column, select
  2028. t = table("t", column("c1"), column("c2"))
  2029. ins = t.insert().values({"c1": "x", "c2": "y"}).cte()
  2030. stmt = select(t).add_cte(ins)
  2031. Would render:
  2032. .. sourcecode:: sql
  2033. WITH anon_1 AS (
  2034. INSERT INTO t (c1, c2) VALUES (:param_1, :param_2)
  2035. )
  2036. SELECT t.c1, t.c2
  2037. FROM t
  2038. Above, the "anon_1" CTE is not referenced in the SELECT
  2039. statement, however still accomplishes the task of running an INSERT
  2040. statement.
  2041. Similarly in a DML-related context, using the PostgreSQL
  2042. :class:`_postgresql.Insert` construct to generate an "upsert"::
  2043. from sqlalchemy import table, column
  2044. from sqlalchemy.dialects.postgresql import insert
  2045. t = table("t", column("c1"), column("c2"))
  2046. delete_statement_cte = t.delete().where(t.c.c1 < 1).cte("deletions")
  2047. insert_stmt = insert(t).values({"c1": 1, "c2": 2})
  2048. update_statement = insert_stmt.on_conflict_do_update(
  2049. index_elements=[t.c.c1],
  2050. set_={
  2051. "c1": insert_stmt.excluded.c1,
  2052. "c2": insert_stmt.excluded.c2,
  2053. },
  2054. ).add_cte(delete_statement_cte)
  2055. print(update_statement)
  2056. The above statement renders as:
  2057. .. sourcecode:: sql
  2058. WITH deletions AS (
  2059. DELETE FROM t WHERE t.c1 < %(c1_1)s
  2060. )
  2061. INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s)
  2062. ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2
  2063. .. versionadded:: 1.4.21
  2064. :param \*ctes: zero or more :class:`.CTE` constructs.
  2065. .. versionchanged:: 2.0 Multiple CTE instances are accepted
  2066. :param nest_here: if True, the given CTE or CTEs will be rendered
  2067. as though they specified the :paramref:`.HasCTE.cte.nesting` flag
  2068. to ``True`` when they were added to this :class:`.HasCTE`.
  2069. Assuming the given CTEs are not referenced in an outer-enclosing
  2070. statement as well, the CTEs given should render at the level of
  2071. this statement when this flag is given.
  2072. .. versionadded:: 2.0
  2073. .. seealso::
  2074. :paramref:`.HasCTE.cte.nesting`
  2075. """ # noqa: E501
  2076. opt = _CTEOpts(nest_here)
  2077. for cte in ctes:
  2078. cte = coercions.expect(roles.IsCTERole, cte)
  2079. self._independent_ctes += (cte,)
  2080. self._independent_ctes_opts += (opt,)
  2081. return self
  2082. def cte(
  2083. self,
  2084. name: Optional[str] = None,
  2085. recursive: bool = False,
  2086. nesting: bool = False,
  2087. ) -> CTE:
  2088. r"""Return a new :class:`_expression.CTE`,
  2089. or Common Table Expression instance.
  2090. Common table expressions are a SQL standard whereby SELECT
  2091. statements can draw upon secondary statements specified along
  2092. with the primary statement, using a clause called "WITH".
  2093. Special semantics regarding UNION can also be employed to
  2094. allow "recursive" queries, where a SELECT statement can draw
  2095. upon the set of rows that have previously been selected.
  2096. CTEs can also be applied to DML constructs UPDATE, INSERT
  2097. and DELETE on some databases, both as a source of CTE rows
  2098. when combined with RETURNING, as well as a consumer of
  2099. CTE rows.
  2100. SQLAlchemy detects :class:`_expression.CTE` objects, which are treated
  2101. similarly to :class:`_expression.Alias` objects, as special elements
  2102. to be delivered to the FROM clause of the statement as well
  2103. as to a WITH clause at the top of the statement.
  2104. For special prefixes such as PostgreSQL "MATERIALIZED" and
  2105. "NOT MATERIALIZED", the :meth:`_expression.CTE.prefix_with`
  2106. method may be
  2107. used to establish these.
  2108. .. versionchanged:: 1.3.13 Added support for prefixes.
  2109. In particular - MATERIALIZED and NOT MATERIALIZED.
  2110. :param name: name given to the common table expression. Like
  2111. :meth:`_expression.FromClause.alias`, the name can be left as
  2112. ``None`` in which case an anonymous symbol will be used at query
  2113. compile time.
  2114. :param recursive: if ``True``, will render ``WITH RECURSIVE``.
  2115. A recursive common table expression is intended to be used in
  2116. conjunction with UNION ALL in order to derive rows
  2117. from those already selected.
  2118. :param nesting: if ``True``, will render the CTE locally to the
  2119. statement in which it is referenced. For more complex scenarios,
  2120. the :meth:`.HasCTE.add_cte` method using the
  2121. :paramref:`.HasCTE.add_cte.nest_here`
  2122. parameter may also be used to more carefully
  2123. control the exact placement of a particular CTE.
  2124. .. versionadded:: 1.4.24
  2125. .. seealso::
  2126. :meth:`.HasCTE.add_cte`
  2127. The following examples include two from PostgreSQL's documentation at
  2128. https://www.postgresql.org/docs/current/static/queries-with.html,
  2129. as well as additional examples.
  2130. Example 1, non recursive::
  2131. from sqlalchemy import (
  2132. Table,
  2133. Column,
  2134. String,
  2135. Integer,
  2136. MetaData,
  2137. select,
  2138. func,
  2139. )
  2140. metadata = MetaData()
  2141. orders = Table(
  2142. "orders",
  2143. metadata,
  2144. Column("region", String),
  2145. Column("amount", Integer),
  2146. Column("product", String),
  2147. Column("quantity", Integer),
  2148. )
  2149. regional_sales = (
  2150. select(orders.c.region, func.sum(orders.c.amount).label("total_sales"))
  2151. .group_by(orders.c.region)
  2152. .cte("regional_sales")
  2153. )
  2154. top_regions = (
  2155. select(regional_sales.c.region)
  2156. .where(
  2157. regional_sales.c.total_sales
  2158. > select(func.sum(regional_sales.c.total_sales) / 10)
  2159. )
  2160. .cte("top_regions")
  2161. )
  2162. statement = (
  2163. select(
  2164. orders.c.region,
  2165. orders.c.product,
  2166. func.sum(orders.c.quantity).label("product_units"),
  2167. func.sum(orders.c.amount).label("product_sales"),
  2168. )
  2169. .where(orders.c.region.in_(select(top_regions.c.region)))
  2170. .group_by(orders.c.region, orders.c.product)
  2171. )
  2172. result = conn.execute(statement).fetchall()
  2173. Example 2, WITH RECURSIVE::
  2174. from sqlalchemy import (
  2175. Table,
  2176. Column,
  2177. String,
  2178. Integer,
  2179. MetaData,
  2180. select,
  2181. func,
  2182. )
  2183. metadata = MetaData()
  2184. parts = Table(
  2185. "parts",
  2186. metadata,
  2187. Column("part", String),
  2188. Column("sub_part", String),
  2189. Column("quantity", Integer),
  2190. )
  2191. included_parts = (
  2192. select(parts.c.sub_part, parts.c.part, parts.c.quantity)
  2193. .where(parts.c.part == "our part")
  2194. .cte(recursive=True)
  2195. )
  2196. incl_alias = included_parts.alias()
  2197. parts_alias = parts.alias()
  2198. included_parts = included_parts.union_all(
  2199. select(
  2200. parts_alias.c.sub_part, parts_alias.c.part, parts_alias.c.quantity
  2201. ).where(parts_alias.c.part == incl_alias.c.sub_part)
  2202. )
  2203. statement = select(
  2204. included_parts.c.sub_part,
  2205. func.sum(included_parts.c.quantity).label("total_quantity"),
  2206. ).group_by(included_parts.c.sub_part)
  2207. result = conn.execute(statement).fetchall()
  2208. Example 3, an upsert using UPDATE and INSERT with CTEs::
  2209. from datetime import date
  2210. from sqlalchemy import (
  2211. MetaData,
  2212. Table,
  2213. Column,
  2214. Integer,
  2215. Date,
  2216. select,
  2217. literal,
  2218. and_,
  2219. exists,
  2220. )
  2221. metadata = MetaData()
  2222. visitors = Table(
  2223. "visitors",
  2224. metadata,
  2225. Column("product_id", Integer, primary_key=True),
  2226. Column("date", Date, primary_key=True),
  2227. Column("count", Integer),
  2228. )
  2229. # add 5 visitors for the product_id == 1
  2230. product_id = 1
  2231. day = date.today()
  2232. count = 5
  2233. update_cte = (
  2234. visitors.update()
  2235. .where(
  2236. and_(visitors.c.product_id == product_id, visitors.c.date == day)
  2237. )
  2238. .values(count=visitors.c.count + count)
  2239. .returning(literal(1))
  2240. .cte("update_cte")
  2241. )
  2242. upsert = visitors.insert().from_select(
  2243. [visitors.c.product_id, visitors.c.date, visitors.c.count],
  2244. select(literal(product_id), literal(day), literal(count)).where(
  2245. ~exists(update_cte.select())
  2246. ),
  2247. )
  2248. connection.execute(upsert)
  2249. Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above)::
  2250. value_a = select(literal("root").label("n")).cte("value_a")
  2251. # A nested CTE with the same name as the root one
  2252. value_a_nested = select(literal("nesting").label("n")).cte(
  2253. "value_a", nesting=True
  2254. )
  2255. # Nesting CTEs takes ascendency locally
  2256. # over the CTEs at a higher level
  2257. value_b = select(value_a_nested.c.n).cte("value_b")
  2258. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
  2259. The above query will render the second CTE nested inside the first,
  2260. shown with inline parameters below as:
  2261. .. sourcecode:: sql
  2262. WITH
  2263. value_a AS
  2264. (SELECT 'root' AS n),
  2265. value_b AS
  2266. (WITH value_a AS
  2267. (SELECT 'nesting' AS n)
  2268. SELECT value_a.n AS n FROM value_a)
  2269. SELECT value_a.n AS a, value_b.n AS b
  2270. FROM value_a, value_b
  2271. The same CTE can be set up using the :meth:`.HasCTE.add_cte` method
  2272. as follows (SQLAlchemy 2.0 and above)::
  2273. value_a = select(literal("root").label("n")).cte("value_a")
  2274. # A nested CTE with the same name as the root one
  2275. value_a_nested = select(literal("nesting").label("n")).cte("value_a")
  2276. # Nesting CTEs takes ascendency locally
  2277. # over the CTEs at a higher level
  2278. value_b = (
  2279. select(value_a_nested.c.n)
  2280. .add_cte(value_a_nested, nest_here=True)
  2281. .cte("value_b")
  2282. )
  2283. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
  2284. Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above)::
  2285. edge = Table(
  2286. "edge",
  2287. metadata,
  2288. Column("id", Integer, primary_key=True),
  2289. Column("left", Integer),
  2290. Column("right", Integer),
  2291. )
  2292. root_node = select(literal(1).label("node")).cte("nodes", recursive=True)
  2293. left_edge = select(edge.c.left).join(
  2294. root_node, edge.c.right == root_node.c.node
  2295. )
  2296. right_edge = select(edge.c.right).join(
  2297. root_node, edge.c.left == root_node.c.node
  2298. )
  2299. subgraph_cte = root_node.union(left_edge, right_edge)
  2300. subgraph = select(subgraph_cte)
  2301. The above query will render 2 UNIONs inside the recursive CTE:
  2302. .. sourcecode:: sql
  2303. WITH RECURSIVE nodes(node) AS (
  2304. SELECT 1 AS node
  2305. UNION
  2306. SELECT edge."left" AS "left"
  2307. FROM edge JOIN nodes ON edge."right" = nodes.node
  2308. UNION
  2309. SELECT edge."right" AS "right"
  2310. FROM edge JOIN nodes ON edge."left" = nodes.node
  2311. )
  2312. SELECT nodes.node FROM nodes
  2313. .. seealso::
  2314. :meth:`_orm.Query.cte` - ORM version of
  2315. :meth:`_expression.HasCTE.cte`.
  2316. """ # noqa: E501
  2317. return CTE._construct(
  2318. self, name=name, recursive=recursive, nesting=nesting
  2319. )
  2320. class Subquery(AliasedReturnsRows):
  2321. """Represent a subquery of a SELECT.
  2322. A :class:`.Subquery` is created by invoking the
  2323. :meth:`_expression.SelectBase.subquery` method, or for convenience the
  2324. :meth:`_expression.SelectBase.alias` method, on any
  2325. :class:`_expression.SelectBase` subclass
  2326. which includes :class:`_expression.Select`,
  2327. :class:`_expression.CompoundSelect`, and
  2328. :class:`_expression.TextualSelect`. As rendered in a FROM clause,
  2329. it represents the
  2330. body of the SELECT statement inside of parenthesis, followed by the usual
  2331. "AS <somename>" that defines all "alias" objects.
  2332. The :class:`.Subquery` object is very similar to the
  2333. :class:`_expression.Alias`
  2334. object and can be used in an equivalent way. The difference between
  2335. :class:`_expression.Alias` and :class:`.Subquery` is that
  2336. :class:`_expression.Alias` always
  2337. contains a :class:`_expression.FromClause` object whereas
  2338. :class:`.Subquery`
  2339. always contains a :class:`_expression.SelectBase` object.
  2340. .. versionadded:: 1.4 The :class:`.Subquery` class was added which now
  2341. serves the purpose of providing an aliased version of a SELECT
  2342. statement.
  2343. """
  2344. __visit_name__ = "subquery"
  2345. _is_subquery = True
  2346. inherit_cache = True
  2347. element: SelectBase
  2348. @classmethod
  2349. def _factory(
  2350. cls, selectable: SelectBase, name: Optional[str] = None
  2351. ) -> Subquery:
  2352. """Return a :class:`.Subquery` object."""
  2353. return coercions.expect(
  2354. roles.SelectStatementRole, selectable
  2355. ).subquery(name=name)
  2356. @util.deprecated(
  2357. "1.4",
  2358. "The :meth:`.Subquery.as_scalar` method, which was previously "
  2359. "``Alias.as_scalar()`` prior to version 1.4, is deprecated and "
  2360. "will be removed in a future release; Please use the "
  2361. ":meth:`_expression.Select.scalar_subquery` method of the "
  2362. ":func:`_expression.select` "
  2363. "construct before constructing a subquery object, or with the ORM "
  2364. "use the :meth:`_query.Query.scalar_subquery` method.",
  2365. )
  2366. def as_scalar(self) -> ScalarSelect[Any]:
  2367. return self.element.set_label_style(LABEL_STYLE_NONE).scalar_subquery()
  2368. class FromGrouping(GroupedElement, FromClause):
  2369. """Represent a grouping of a FROM clause"""
  2370. _traverse_internals: _TraverseInternalsType = [
  2371. ("element", InternalTraversal.dp_clauseelement)
  2372. ]
  2373. element: FromClause
  2374. def __init__(self, element: FromClause):
  2375. self.element = coercions.expect(roles.FromClauseRole, element)
  2376. @util.ro_non_memoized_property
  2377. def columns(
  2378. self,
  2379. ) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
  2380. return self.element.columns
  2381. @util.ro_non_memoized_property
  2382. def c(self) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
  2383. return self.element.columns
  2384. @property
  2385. def primary_key(self) -> Iterable[NamedColumn[Any]]:
  2386. return self.element.primary_key
  2387. @property
  2388. def foreign_keys(self) -> Iterable[ForeignKey]:
  2389. return self.element.foreign_keys
  2390. def is_derived_from(self, fromclause: Optional[FromClause]) -> bool:
  2391. return self.element.is_derived_from(fromclause)
  2392. def alias(
  2393. self, name: Optional[str] = None, flat: bool = False
  2394. ) -> NamedFromGrouping:
  2395. return NamedFromGrouping(self.element.alias(name=name, flat=flat))
  2396. def _anonymous_fromclause(self, **kw: Any) -> FromGrouping:
  2397. return FromGrouping(self.element._anonymous_fromclause(**kw))
  2398. @util.ro_non_memoized_property
  2399. def _hide_froms(self) -> Iterable[FromClause]:
  2400. return self.element._hide_froms
  2401. @util.ro_non_memoized_property
  2402. def _from_objects(self) -> List[FromClause]:
  2403. return self.element._from_objects
  2404. def __getstate__(self) -> Dict[str, FromClause]:
  2405. return {"element": self.element}
  2406. def __setstate__(self, state: Dict[str, FromClause]) -> None:
  2407. self.element = state["element"]
  2408. if TYPE_CHECKING:
  2409. def self_group(
  2410. self, against: Optional[OperatorType] = None
  2411. ) -> Self: ...
  2412. class NamedFromGrouping(FromGrouping, NamedFromClause):
  2413. """represent a grouping of a named FROM clause
  2414. .. versionadded:: 2.0
  2415. """
  2416. inherit_cache = True
  2417. if TYPE_CHECKING:
  2418. def self_group(
  2419. self, against: Optional[OperatorType] = None
  2420. ) -> Self: ...
  2421. class TableClause(roles.DMLTableRole, Immutable, NamedFromClause):
  2422. """Represents a minimal "table" construct.
  2423. This is a lightweight table object that has only a name, a
  2424. collection of columns, which are typically produced
  2425. by the :func:`_expression.column` function, and a schema::
  2426. from sqlalchemy import table, column
  2427. user = table(
  2428. "user",
  2429. column("id"),
  2430. column("name"),
  2431. column("description"),
  2432. )
  2433. The :class:`_expression.TableClause` construct serves as the base for
  2434. the more commonly used :class:`_schema.Table` object, providing
  2435. the usual set of :class:`_expression.FromClause` services including
  2436. the ``.c.`` collection and statement generation methods.
  2437. It does **not** provide all the additional schema-level services
  2438. of :class:`_schema.Table`, including constraints, references to other
  2439. tables, or support for :class:`_schema.MetaData`-level services.
  2440. It's useful
  2441. on its own as an ad-hoc construct used to generate quick SQL
  2442. statements when a more fully fledged :class:`_schema.Table`
  2443. is not on hand.
  2444. """
  2445. __visit_name__ = "table"
  2446. _traverse_internals: _TraverseInternalsType = [
  2447. (
  2448. "columns",
  2449. InternalTraversal.dp_fromclause_canonical_column_collection,
  2450. ),
  2451. ("name", InternalTraversal.dp_string),
  2452. ("schema", InternalTraversal.dp_string),
  2453. ]
  2454. _is_table = True
  2455. fullname: str
  2456. implicit_returning = False
  2457. """:class:`_expression.TableClause`
  2458. doesn't support having a primary key or column
  2459. -level defaults, so implicit returning doesn't apply."""
  2460. @util.ro_memoized_property
  2461. def _autoincrement_column(self) -> Optional[ColumnClause[Any]]:
  2462. """No PK or default support so no autoincrement column."""
  2463. return None
  2464. def __init__(self, name: str, *columns: ColumnClause[Any], **kw: Any):
  2465. super().__init__()
  2466. self.name = name
  2467. self._columns = DedupeColumnCollection()
  2468. self.primary_key = ColumnSet() # type: ignore
  2469. self.foreign_keys = set() # type: ignore
  2470. for c in columns:
  2471. self.append_column(c)
  2472. schema = kw.pop("schema", None)
  2473. if schema is not None:
  2474. self.schema = schema
  2475. if self.schema is not None:
  2476. self.fullname = "%s.%s" % (self.schema, self.name)
  2477. else:
  2478. self.fullname = self.name
  2479. if kw:
  2480. raise exc.ArgumentError("Unsupported argument(s): %s" % list(kw))
  2481. if TYPE_CHECKING:
  2482. @util.ro_non_memoized_property
  2483. def columns(
  2484. self,
  2485. ) -> ReadOnlyColumnCollection[str, ColumnClause[Any]]: ...
  2486. @util.ro_non_memoized_property
  2487. def c(self) -> ReadOnlyColumnCollection[str, ColumnClause[Any]]: ...
  2488. def __str__(self) -> str:
  2489. if self.schema is not None:
  2490. return self.schema + "." + self.name
  2491. else:
  2492. return self.name
  2493. def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
  2494. pass
  2495. @util.ro_memoized_property
  2496. def description(self) -> str:
  2497. return self.name
  2498. def append_column(self, c: ColumnClause[Any]) -> None:
  2499. existing = c.table
  2500. if existing is not None and existing is not self:
  2501. raise exc.ArgumentError(
  2502. "column object '%s' already assigned to table '%s'"
  2503. % (c.key, existing)
  2504. )
  2505. self._columns.add(c)
  2506. c.table = self
  2507. @util.preload_module("sqlalchemy.sql.dml")
  2508. def insert(self) -> util.preloaded.sql_dml.Insert:
  2509. """Generate an :class:`_sql.Insert` construct against this
  2510. :class:`_expression.TableClause`.
  2511. E.g.::
  2512. table.insert().values(name="foo")
  2513. See :func:`_expression.insert` for argument and usage information.
  2514. """
  2515. return util.preloaded.sql_dml.Insert(self)
  2516. @util.preload_module("sqlalchemy.sql.dml")
  2517. def update(self) -> Update:
  2518. """Generate an :func:`_expression.update` construct against this
  2519. :class:`_expression.TableClause`.
  2520. E.g.::
  2521. table.update().where(table.c.id == 7).values(name="foo")
  2522. See :func:`_expression.update` for argument and usage information.
  2523. """
  2524. return util.preloaded.sql_dml.Update(
  2525. self,
  2526. )
  2527. @util.preload_module("sqlalchemy.sql.dml")
  2528. def delete(self) -> Delete:
  2529. """Generate a :func:`_expression.delete` construct against this
  2530. :class:`_expression.TableClause`.
  2531. E.g.::
  2532. table.delete().where(table.c.id == 7)
  2533. See :func:`_expression.delete` for argument and usage information.
  2534. """
  2535. return util.preloaded.sql_dml.Delete(self)
  2536. @util.ro_non_memoized_property
  2537. def _from_objects(self) -> List[FromClause]:
  2538. return [self]
  2539. ForUpdateParameter = Union["ForUpdateArg", None, bool, Dict[str, Any]]
  2540. class ForUpdateArg(ClauseElement):
  2541. _traverse_internals: _TraverseInternalsType = [
  2542. ("of", InternalTraversal.dp_clauseelement_list),
  2543. ("nowait", InternalTraversal.dp_boolean),
  2544. ("read", InternalTraversal.dp_boolean),
  2545. ("skip_locked", InternalTraversal.dp_boolean),
  2546. ("key_share", InternalTraversal.dp_boolean),
  2547. ]
  2548. of: Optional[Sequence[ClauseElement]]
  2549. nowait: bool
  2550. read: bool
  2551. skip_locked: bool
  2552. @classmethod
  2553. def _from_argument(
  2554. cls, with_for_update: ForUpdateParameter
  2555. ) -> Optional[ForUpdateArg]:
  2556. if isinstance(with_for_update, ForUpdateArg):
  2557. return with_for_update
  2558. elif with_for_update in (None, False):
  2559. return None
  2560. elif with_for_update is True:
  2561. return ForUpdateArg()
  2562. else:
  2563. return ForUpdateArg(**cast("Dict[str, Any]", with_for_update))
  2564. def __eq__(self, other: Any) -> bool:
  2565. return (
  2566. isinstance(other, ForUpdateArg)
  2567. and other.nowait == self.nowait
  2568. and other.read == self.read
  2569. and other.skip_locked == self.skip_locked
  2570. and other.key_share == self.key_share
  2571. and other.of is self.of
  2572. )
  2573. def __ne__(self, other: Any) -> bool:
  2574. return not self.__eq__(other)
  2575. def __hash__(self) -> int:
  2576. return id(self)
  2577. def __init__(
  2578. self,
  2579. *,
  2580. nowait: bool = False,
  2581. read: bool = False,
  2582. of: Optional[_ForUpdateOfArgument] = None,
  2583. skip_locked: bool = False,
  2584. key_share: bool = False,
  2585. ):
  2586. """Represents arguments specified to
  2587. :meth:`_expression.Select.for_update`.
  2588. """
  2589. self.nowait = nowait
  2590. self.read = read
  2591. self.skip_locked = skip_locked
  2592. self.key_share = key_share
  2593. if of is not None:
  2594. self.of = [
  2595. coercions.expect(roles.ColumnsClauseRole, elem)
  2596. for elem in util.to_list(of)
  2597. ]
  2598. else:
  2599. self.of = None
  2600. class Values(roles.InElementRole, HasCTE, Generative, LateralFromClause):
  2601. """Represent a ``VALUES`` construct that can be used as a FROM element
  2602. in a statement.
  2603. The :class:`_expression.Values` object is created from the
  2604. :func:`_expression.values` function.
  2605. .. versionadded:: 1.4
  2606. """
  2607. __visit_name__ = "values"
  2608. _data: Tuple[Sequence[Tuple[Any, ...]], ...] = ()
  2609. _column_args: Tuple[NamedColumn[Any], ...]
  2610. _unnamed: bool
  2611. _traverse_internals: _TraverseInternalsType = [
  2612. ("_column_args", InternalTraversal.dp_clauseelement_list),
  2613. ("_data", InternalTraversal.dp_dml_multi_values),
  2614. ("name", InternalTraversal.dp_string),
  2615. ("literal_binds", InternalTraversal.dp_boolean),
  2616. ] + HasCTE._has_ctes_traverse_internals
  2617. name_cte_columns = True
  2618. def __init__(
  2619. self,
  2620. *columns: _OnlyColumnArgument[Any],
  2621. name: Optional[str] = None,
  2622. literal_binds: bool = False,
  2623. ):
  2624. super().__init__()
  2625. self._column_args = tuple(
  2626. coercions.expect(roles.LabeledColumnExprRole, col)
  2627. for col in columns
  2628. )
  2629. if name is None:
  2630. self._unnamed = True
  2631. self.name = _anonymous_label.safe_construct(id(self), "anon")
  2632. else:
  2633. self._unnamed = False
  2634. self.name = name
  2635. self.literal_binds = literal_binds
  2636. self.named_with_column = not self._unnamed
  2637. @property
  2638. def _column_types(self) -> List[TypeEngine[Any]]:
  2639. return [col.type for col in self._column_args]
  2640. @util.ro_non_memoized_property
  2641. def _all_selected_columns(self) -> _SelectIterable:
  2642. return self._column_args
  2643. @_generative
  2644. def alias(self, name: Optional[str] = None, flat: bool = False) -> Self:
  2645. """Return a new :class:`_expression.Values`
  2646. construct that is a copy of this
  2647. one with the given name.
  2648. This method is a VALUES-specific specialization of the
  2649. :meth:`_expression.FromClause.alias` method.
  2650. .. seealso::
  2651. :ref:`tutorial_using_aliases`
  2652. :func:`_expression.alias`
  2653. """
  2654. non_none_name: str
  2655. if name is None:
  2656. non_none_name = _anonymous_label.safe_construct(id(self), "anon")
  2657. else:
  2658. non_none_name = name
  2659. self.name = non_none_name
  2660. self.named_with_column = True
  2661. self._unnamed = False
  2662. return self
  2663. @_generative
  2664. def lateral(self, name: Optional[str] = None) -> Self:
  2665. """Return a new :class:`_expression.Values` with the lateral flag set,
  2666. so that
  2667. it renders as LATERAL.
  2668. .. seealso::
  2669. :func:`_expression.lateral`
  2670. """
  2671. non_none_name: str
  2672. if name is None:
  2673. non_none_name = self.name
  2674. else:
  2675. non_none_name = name
  2676. self._is_lateral = True
  2677. self.name = non_none_name
  2678. self._unnamed = False
  2679. return self
  2680. @_generative
  2681. def data(self, values: Sequence[Tuple[Any, ...]]) -> Self:
  2682. """Return a new :class:`_expression.Values` construct,
  2683. adding the given data to the data list.
  2684. E.g.::
  2685. my_values = my_values.data([(1, "value 1"), (2, "value2")])
  2686. :param values: a sequence (i.e. list) of tuples that map to the
  2687. column expressions given in the :class:`_expression.Values`
  2688. constructor.
  2689. """
  2690. self._data += (values,)
  2691. return self
  2692. def scalar_values(self) -> ScalarValues:
  2693. """Returns a scalar ``VALUES`` construct that can be used as a
  2694. COLUMN element in a statement.
  2695. .. versionadded:: 2.0.0b4
  2696. """
  2697. return ScalarValues(self._column_args, self._data, self.literal_binds)
  2698. def _populate_column_collection(
  2699. self,
  2700. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  2701. primary_key: ColumnSet,
  2702. foreign_keys: Set[KeyedColumnElement[Any]],
  2703. ) -> None:
  2704. for c in self._column_args:
  2705. if c.table is not None and c.table is not self:
  2706. _, c = c._make_proxy(
  2707. self, primary_key=primary_key, foreign_keys=foreign_keys
  2708. )
  2709. else:
  2710. # if the column was used in other contexts, ensure
  2711. # no memoizations of other FROM clauses.
  2712. # see test_values.py -> test_auto_proxy_select_direct_col
  2713. c._reset_memoizations()
  2714. columns.add(c)
  2715. c.table = self
  2716. @util.ro_non_memoized_property
  2717. def _from_objects(self) -> List[FromClause]:
  2718. return [self]
  2719. class ScalarValues(roles.InElementRole, GroupedElement, ColumnElement[Any]):
  2720. """Represent a scalar ``VALUES`` construct that can be used as a
  2721. COLUMN element in a statement.
  2722. The :class:`_expression.ScalarValues` object is created from the
  2723. :meth:`_expression.Values.scalar_values` method. It's also
  2724. automatically generated when a :class:`_expression.Values` is used in
  2725. an ``IN`` or ``NOT IN`` condition.
  2726. .. versionadded:: 2.0.0b4
  2727. """
  2728. __visit_name__ = "scalar_values"
  2729. _traverse_internals: _TraverseInternalsType = [
  2730. ("_column_args", InternalTraversal.dp_clauseelement_list),
  2731. ("_data", InternalTraversal.dp_dml_multi_values),
  2732. ("literal_binds", InternalTraversal.dp_boolean),
  2733. ]
  2734. def __init__(
  2735. self,
  2736. columns: Sequence[NamedColumn[Any]],
  2737. data: Tuple[Sequence[Tuple[Any, ...]], ...],
  2738. literal_binds: bool,
  2739. ):
  2740. super().__init__()
  2741. self._column_args = columns
  2742. self._data = data
  2743. self.literal_binds = literal_binds
  2744. @property
  2745. def _column_types(self) -> List[TypeEngine[Any]]:
  2746. return [col.type for col in self._column_args]
  2747. def __clause_element__(self) -> ScalarValues:
  2748. return self
  2749. if TYPE_CHECKING:
  2750. def self_group(
  2751. self, against: Optional[OperatorType] = None
  2752. ) -> Self: ...
  2753. def _ungroup(self) -> ColumnElement[Any]: ...
  2754. class SelectBase(
  2755. roles.SelectStatementRole,
  2756. roles.DMLSelectRole,
  2757. roles.CompoundElementRole,
  2758. roles.InElementRole,
  2759. HasCTE,
  2760. SupportsCloneAnnotations,
  2761. Selectable,
  2762. ):
  2763. """Base class for SELECT statements.
  2764. This includes :class:`_expression.Select`,
  2765. :class:`_expression.CompoundSelect` and
  2766. :class:`_expression.TextualSelect`.
  2767. """
  2768. _is_select_base = True
  2769. is_select = True
  2770. _label_style: SelectLabelStyle = LABEL_STYLE_NONE
  2771. def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
  2772. self._reset_memoizations()
  2773. @util.ro_non_memoized_property
  2774. def selected_columns(
  2775. self,
  2776. ) -> ColumnCollection[str, ColumnElement[Any]]:
  2777. """A :class:`_expression.ColumnCollection`
  2778. representing the columns that
  2779. this SELECT statement or similar construct returns in its result set.
  2780. This collection differs from the :attr:`_expression.FromClause.columns`
  2781. collection of a :class:`_expression.FromClause` in that the columns
  2782. within this collection cannot be directly nested inside another SELECT
  2783. statement; a subquery must be applied first which provides for the
  2784. necessary parenthesization required by SQL.
  2785. .. note::
  2786. The :attr:`_sql.SelectBase.selected_columns` collection does not
  2787. include expressions established in the columns clause using the
  2788. :func:`_sql.text` construct; these are silently omitted from the
  2789. collection. To use plain textual column expressions inside of a
  2790. :class:`_sql.Select` construct, use the :func:`_sql.literal_column`
  2791. construct.
  2792. .. seealso::
  2793. :attr:`_sql.Select.selected_columns`
  2794. .. versionadded:: 1.4
  2795. """
  2796. raise NotImplementedError()
  2797. def _generate_fromclause_column_proxies(
  2798. self,
  2799. subquery: FromClause,
  2800. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  2801. primary_key: ColumnSet,
  2802. foreign_keys: Set[KeyedColumnElement[Any]],
  2803. *,
  2804. proxy_compound_columns: Optional[
  2805. Iterable[Sequence[ColumnElement[Any]]]
  2806. ] = None,
  2807. ) -> None:
  2808. raise NotImplementedError()
  2809. @util.ro_non_memoized_property
  2810. def _all_selected_columns(self) -> _SelectIterable:
  2811. """A sequence of expressions that correspond to what is rendered
  2812. in the columns clause, including :class:`_sql.TextClause`
  2813. constructs.
  2814. .. versionadded:: 1.4.12
  2815. .. seealso::
  2816. :attr:`_sql.SelectBase.exported_columns`
  2817. """
  2818. raise NotImplementedError()
  2819. @property
  2820. def exported_columns(
  2821. self,
  2822. ) -> ReadOnlyColumnCollection[str, ColumnElement[Any]]:
  2823. """A :class:`_expression.ColumnCollection`
  2824. that represents the "exported"
  2825. columns of this :class:`_expression.Selectable`, not including
  2826. :class:`_sql.TextClause` constructs.
  2827. The "exported" columns for a :class:`_expression.SelectBase`
  2828. object are synonymous
  2829. with the :attr:`_expression.SelectBase.selected_columns` collection.
  2830. .. versionadded:: 1.4
  2831. .. seealso::
  2832. :attr:`_expression.Select.exported_columns`
  2833. :attr:`_expression.Selectable.exported_columns`
  2834. :attr:`_expression.FromClause.exported_columns`
  2835. """
  2836. return self.selected_columns.as_readonly()
  2837. @property
  2838. @util.deprecated(
  2839. "1.4",
  2840. "The :attr:`_expression.SelectBase.c` and "
  2841. ":attr:`_expression.SelectBase.columns` attributes "
  2842. "are deprecated and will be removed in a future release; these "
  2843. "attributes implicitly create a subquery that should be explicit. "
  2844. "Please call :meth:`_expression.SelectBase.subquery` "
  2845. "first in order to create "
  2846. "a subquery, which then contains this attribute. To access the "
  2847. "columns that this SELECT object SELECTs "
  2848. "from, use the :attr:`_expression.SelectBase.selected_columns` "
  2849. "attribute.",
  2850. )
  2851. def c(self) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
  2852. return self._implicit_subquery.columns
  2853. @property
  2854. def columns(
  2855. self,
  2856. ) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
  2857. return self.c
  2858. def get_label_style(self) -> SelectLabelStyle:
  2859. """
  2860. Retrieve the current label style.
  2861. Implemented by subclasses.
  2862. """
  2863. raise NotImplementedError()
  2864. def set_label_style(self, style: SelectLabelStyle) -> Self:
  2865. """Return a new selectable with the specified label style.
  2866. Implemented by subclasses.
  2867. """
  2868. raise NotImplementedError()
  2869. @util.deprecated(
  2870. "1.4",
  2871. "The :meth:`_expression.SelectBase.select` method is deprecated "
  2872. "and will be removed in a future release; this method implicitly "
  2873. "creates a subquery that should be explicit. "
  2874. "Please call :meth:`_expression.SelectBase.subquery` "
  2875. "first in order to create "
  2876. "a subquery, which then can be selected.",
  2877. )
  2878. def select(self, *arg: Any, **kw: Any) -> Select[Any]:
  2879. return self._implicit_subquery.select(*arg, **kw)
  2880. @HasMemoized.memoized_attribute
  2881. def _implicit_subquery(self) -> Subquery:
  2882. return self.subquery()
  2883. def _scalar_type(self) -> TypeEngine[Any]:
  2884. raise NotImplementedError()
  2885. @util.deprecated(
  2886. "1.4",
  2887. "The :meth:`_expression.SelectBase.as_scalar` "
  2888. "method is deprecated and will be "
  2889. "removed in a future release. Please refer to "
  2890. ":meth:`_expression.SelectBase.scalar_subquery`.",
  2891. )
  2892. def as_scalar(self) -> ScalarSelect[Any]:
  2893. return self.scalar_subquery()
  2894. def exists(self) -> Exists:
  2895. """Return an :class:`_sql.Exists` representation of this selectable,
  2896. which can be used as a column expression.
  2897. The returned object is an instance of :class:`_sql.Exists`.
  2898. .. seealso::
  2899. :func:`_sql.exists`
  2900. :ref:`tutorial_exists` - in the :term:`2.0 style` tutorial.
  2901. .. versionadded:: 1.4
  2902. """
  2903. return Exists(self)
  2904. def scalar_subquery(self) -> ScalarSelect[Any]:
  2905. """Return a 'scalar' representation of this selectable, which can be
  2906. used as a column expression.
  2907. The returned object is an instance of :class:`_sql.ScalarSelect`.
  2908. Typically, a select statement which has only one column in its columns
  2909. clause is eligible to be used as a scalar expression. The scalar
  2910. subquery can then be used in the WHERE clause or columns clause of
  2911. an enclosing SELECT.
  2912. Note that the scalar subquery differentiates from the FROM-level
  2913. subquery that can be produced using the
  2914. :meth:`_expression.SelectBase.subquery`
  2915. method.
  2916. .. versionchanged: 1.4 - the ``.as_scalar()`` method was renamed to
  2917. :meth:`_expression.SelectBase.scalar_subquery`.
  2918. .. seealso::
  2919. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  2920. """
  2921. if self._label_style is not LABEL_STYLE_NONE:
  2922. self = self.set_label_style(LABEL_STYLE_NONE)
  2923. return ScalarSelect(self)
  2924. def label(self, name: Optional[str]) -> Label[Any]:
  2925. """Return a 'scalar' representation of this selectable, embedded as a
  2926. subquery with a label.
  2927. .. seealso::
  2928. :meth:`_expression.SelectBase.scalar_subquery`.
  2929. """
  2930. return self.scalar_subquery().label(name)
  2931. def lateral(self, name: Optional[str] = None) -> LateralFromClause:
  2932. """Return a LATERAL alias of this :class:`_expression.Selectable`.
  2933. The return value is the :class:`_expression.Lateral` construct also
  2934. provided by the top-level :func:`_expression.lateral` function.
  2935. .. seealso::
  2936. :ref:`tutorial_lateral_correlation` - overview of usage.
  2937. """
  2938. return Lateral._factory(self, name)
  2939. def subquery(self, name: Optional[str] = None) -> Subquery:
  2940. """Return a subquery of this :class:`_expression.SelectBase`.
  2941. A subquery is from a SQL perspective a parenthesized, named
  2942. construct that can be placed in the FROM clause of another
  2943. SELECT statement.
  2944. Given a SELECT statement such as::
  2945. stmt = select(table.c.id, table.c.name)
  2946. The above statement might look like:
  2947. .. sourcecode:: sql
  2948. SELECT table.id, table.name FROM table
  2949. The subquery form by itself renders the same way, however when
  2950. embedded into the FROM clause of another SELECT statement, it becomes
  2951. a named sub-element::
  2952. subq = stmt.subquery()
  2953. new_stmt = select(subq)
  2954. The above renders as:
  2955. .. sourcecode:: sql
  2956. SELECT anon_1.id, anon_1.name
  2957. FROM (SELECT table.id, table.name FROM table) AS anon_1
  2958. Historically, :meth:`_expression.SelectBase.subquery`
  2959. is equivalent to calling
  2960. the :meth:`_expression.FromClause.alias`
  2961. method on a FROM object; however,
  2962. as a :class:`_expression.SelectBase`
  2963. object is not directly FROM object,
  2964. the :meth:`_expression.SelectBase.subquery`
  2965. method provides clearer semantics.
  2966. .. versionadded:: 1.4
  2967. """
  2968. return Subquery._construct(
  2969. self._ensure_disambiguated_names(), name=name
  2970. )
  2971. def _ensure_disambiguated_names(self) -> Self:
  2972. """Ensure that the names generated by this selectbase will be
  2973. disambiguated in some way, if possible.
  2974. """
  2975. raise NotImplementedError()
  2976. def alias(
  2977. self, name: Optional[str] = None, flat: bool = False
  2978. ) -> Subquery:
  2979. """Return a named subquery against this
  2980. :class:`_expression.SelectBase`.
  2981. For a :class:`_expression.SelectBase` (as opposed to a
  2982. :class:`_expression.FromClause`),
  2983. this returns a :class:`.Subquery` object which behaves mostly the
  2984. same as the :class:`_expression.Alias` object that is used with a
  2985. :class:`_expression.FromClause`.
  2986. .. versionchanged:: 1.4 The :meth:`_expression.SelectBase.alias`
  2987. method is now
  2988. a synonym for the :meth:`_expression.SelectBase.subquery` method.
  2989. """
  2990. return self.subquery(name=name)
  2991. _SB = TypeVar("_SB", bound=SelectBase)
  2992. class SelectStatementGrouping(GroupedElement, SelectBase, Generic[_SB]):
  2993. """Represent a grouping of a :class:`_expression.SelectBase`.
  2994. This differs from :class:`.Subquery` in that we are still
  2995. an "inner" SELECT statement, this is strictly for grouping inside of
  2996. compound selects.
  2997. """
  2998. __visit_name__ = "select_statement_grouping"
  2999. _traverse_internals: _TraverseInternalsType = [
  3000. ("element", InternalTraversal.dp_clauseelement)
  3001. ] + SupportsCloneAnnotations._clone_annotations_traverse_internals
  3002. _is_select_container = True
  3003. element: _SB
  3004. def __init__(self, element: _SB) -> None:
  3005. self.element = cast(
  3006. _SB, coercions.expect(roles.SelectStatementRole, element)
  3007. )
  3008. def _ensure_disambiguated_names(self) -> SelectStatementGrouping[_SB]:
  3009. new_element = self.element._ensure_disambiguated_names()
  3010. if new_element is not self.element:
  3011. return SelectStatementGrouping(new_element)
  3012. else:
  3013. return self
  3014. def get_label_style(self) -> SelectLabelStyle:
  3015. return self.element.get_label_style()
  3016. def set_label_style(
  3017. self, label_style: SelectLabelStyle
  3018. ) -> SelectStatementGrouping[_SB]:
  3019. return SelectStatementGrouping(
  3020. self.element.set_label_style(label_style)
  3021. )
  3022. @property
  3023. def select_statement(self) -> _SB:
  3024. return self.element
  3025. def self_group(self, against: Optional[OperatorType] = None) -> Self:
  3026. return self
  3027. if TYPE_CHECKING:
  3028. def _ungroup(self) -> _SB: ...
  3029. # def _generate_columns_plus_names(
  3030. # self, anon_for_dupe_key: bool
  3031. # ) -> List[Tuple[str, str, str, ColumnElement[Any], bool]]:
  3032. # return self.element._generate_columns_plus_names(anon_for_dupe_key)
  3033. def _generate_fromclause_column_proxies(
  3034. self,
  3035. subquery: FromClause,
  3036. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  3037. primary_key: ColumnSet,
  3038. foreign_keys: Set[KeyedColumnElement[Any]],
  3039. *,
  3040. proxy_compound_columns: Optional[
  3041. Iterable[Sequence[ColumnElement[Any]]]
  3042. ] = None,
  3043. ) -> None:
  3044. self.element._generate_fromclause_column_proxies(
  3045. subquery,
  3046. columns,
  3047. proxy_compound_columns=proxy_compound_columns,
  3048. primary_key=primary_key,
  3049. foreign_keys=foreign_keys,
  3050. )
  3051. @util.ro_non_memoized_property
  3052. def _all_selected_columns(self) -> _SelectIterable:
  3053. return self.element._all_selected_columns
  3054. @util.ro_non_memoized_property
  3055. def selected_columns(self) -> ColumnCollection[str, ColumnElement[Any]]:
  3056. """A :class:`_expression.ColumnCollection`
  3057. representing the columns that
  3058. the embedded SELECT statement returns in its result set, not including
  3059. :class:`_sql.TextClause` constructs.
  3060. .. versionadded:: 1.4
  3061. .. seealso::
  3062. :attr:`_sql.Select.selected_columns`
  3063. """
  3064. return self.element.selected_columns
  3065. @util.ro_non_memoized_property
  3066. def _from_objects(self) -> List[FromClause]:
  3067. return self.element._from_objects
  3068. def _scalar_type(self) -> TypeEngine[Any]:
  3069. return self.element._scalar_type()
  3070. def add_cte(self, *ctes: CTE, nest_here: bool = False) -> Self:
  3071. # SelectStatementGrouping not generative: has no attribute '_generate'
  3072. raise NotImplementedError
  3073. class GenerativeSelect(DialectKWArgs, SelectBase, Generative):
  3074. """Base class for SELECT statements where additional elements can be
  3075. added.
  3076. This serves as the base for :class:`_expression.Select` and
  3077. :class:`_expression.CompoundSelect`
  3078. where elements such as ORDER BY, GROUP BY can be added and column
  3079. rendering can be controlled. Compare to
  3080. :class:`_expression.TextualSelect`, which,
  3081. while it subclasses :class:`_expression.SelectBase`
  3082. and is also a SELECT construct,
  3083. represents a fixed textual string which cannot be altered at this level,
  3084. only wrapped as a subquery.
  3085. """
  3086. _order_by_clauses: Tuple[ColumnElement[Any], ...] = ()
  3087. _group_by_clauses: Tuple[ColumnElement[Any], ...] = ()
  3088. _limit_clause: Optional[ColumnElement[Any]] = None
  3089. _offset_clause: Optional[ColumnElement[Any]] = None
  3090. _fetch_clause: Optional[ColumnElement[Any]] = None
  3091. _fetch_clause_options: Optional[Dict[str, bool]] = None
  3092. _for_update_arg: Optional[ForUpdateArg] = None
  3093. def __init__(self, _label_style: SelectLabelStyle = LABEL_STYLE_DEFAULT):
  3094. self._label_style = _label_style
  3095. @_generative
  3096. def with_for_update(
  3097. self,
  3098. *,
  3099. nowait: bool = False,
  3100. read: bool = False,
  3101. of: Optional[_ForUpdateOfArgument] = None,
  3102. skip_locked: bool = False,
  3103. key_share: bool = False,
  3104. ) -> Self:
  3105. """Specify a ``FOR UPDATE`` clause for this
  3106. :class:`_expression.GenerativeSelect`.
  3107. E.g.::
  3108. stmt = select(table).with_for_update(nowait=True)
  3109. On a database like PostgreSQL or Oracle Database, the above would
  3110. render a statement like:
  3111. .. sourcecode:: sql
  3112. SELECT table.a, table.b FROM table FOR UPDATE NOWAIT
  3113. on other backends, the ``nowait`` option is ignored and instead
  3114. would produce:
  3115. .. sourcecode:: sql
  3116. SELECT table.a, table.b FROM table FOR UPDATE
  3117. When called with no arguments, the statement will render with
  3118. the suffix ``FOR UPDATE``. Additional arguments can then be
  3119. provided which allow for common database-specific
  3120. variants.
  3121. :param nowait: boolean; will render ``FOR UPDATE NOWAIT`` on Oracle
  3122. Database and PostgreSQL dialects.
  3123. :param read: boolean; will render ``LOCK IN SHARE MODE`` on MySQL,
  3124. ``FOR SHARE`` on PostgreSQL. On PostgreSQL, when combined with
  3125. ``nowait``, will render ``FOR SHARE NOWAIT``.
  3126. :param of: SQL expression or list of SQL expression elements,
  3127. (typically :class:`_schema.Column` objects or a compatible expression,
  3128. for some backends may also be a table expression) which will render
  3129. into a ``FOR UPDATE OF`` clause; supported by PostgreSQL, Oracle
  3130. Database, some MySQL versions and possibly others. May render as a
  3131. table or as a column depending on backend.
  3132. :param skip_locked: boolean, will render ``FOR UPDATE SKIP LOCKED`` on
  3133. Oracle Database and PostgreSQL dialects or ``FOR SHARE SKIP LOCKED``
  3134. if ``read=True`` is also specified.
  3135. :param key_share: boolean, will render ``FOR NO KEY UPDATE``,
  3136. or if combined with ``read=True`` will render ``FOR KEY SHARE``,
  3137. on the PostgreSQL dialect.
  3138. """
  3139. self._for_update_arg = ForUpdateArg(
  3140. nowait=nowait,
  3141. read=read,
  3142. of=of,
  3143. skip_locked=skip_locked,
  3144. key_share=key_share,
  3145. )
  3146. return self
  3147. def get_label_style(self) -> SelectLabelStyle:
  3148. """
  3149. Retrieve the current label style.
  3150. .. versionadded:: 1.4
  3151. """
  3152. return self._label_style
  3153. def set_label_style(self, style: SelectLabelStyle) -> Self:
  3154. """Return a new selectable with the specified label style.
  3155. There are three "label styles" available,
  3156. :attr:`_sql.SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY`,
  3157. :attr:`_sql.SelectLabelStyle.LABEL_STYLE_TABLENAME_PLUS_COL`, and
  3158. :attr:`_sql.SelectLabelStyle.LABEL_STYLE_NONE`. The default style is
  3159. :attr:`_sql.SelectLabelStyle.LABEL_STYLE_DISAMBIGUATE_ONLY`.
  3160. In modern SQLAlchemy, there is not generally a need to change the
  3161. labeling style, as per-expression labels are more effectively used by
  3162. making use of the :meth:`_sql.ColumnElement.label` method. In past
  3163. versions, :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL` was used to
  3164. disambiguate same-named columns from different tables, aliases, or
  3165. subqueries; the newer :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` now
  3166. applies labels only to names that conflict with an existing name so
  3167. that the impact of this labeling is minimal.
  3168. The rationale for disambiguation is mostly so that all column
  3169. expressions are available from a given :attr:`_sql.FromClause.c`
  3170. collection when a subquery is created.
  3171. .. versionadded:: 1.4 - the
  3172. :meth:`_sql.GenerativeSelect.set_label_style` method replaces the
  3173. previous combination of ``.apply_labels()``, ``.with_labels()`` and
  3174. ``use_labels=True`` methods and/or parameters.
  3175. .. seealso::
  3176. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`
  3177. :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`
  3178. :data:`_sql.LABEL_STYLE_NONE`
  3179. :data:`_sql.LABEL_STYLE_DEFAULT`
  3180. """
  3181. if self._label_style is not style:
  3182. self = self._generate()
  3183. self._label_style = style
  3184. return self
  3185. @property
  3186. def _group_by_clause(self) -> ClauseList:
  3187. """ClauseList access to group_by_clauses for legacy dialects"""
  3188. return ClauseList._construct_raw(
  3189. operators.comma_op, self._group_by_clauses
  3190. )
  3191. @property
  3192. def _order_by_clause(self) -> ClauseList:
  3193. """ClauseList access to order_by_clauses for legacy dialects"""
  3194. return ClauseList._construct_raw(
  3195. operators.comma_op, self._order_by_clauses
  3196. )
  3197. def _offset_or_limit_clause(
  3198. self,
  3199. element: _LimitOffsetType,
  3200. name: Optional[str] = None,
  3201. type_: Optional[_TypeEngineArgument[int]] = None,
  3202. ) -> ColumnElement[Any]:
  3203. """Convert the given value to an "offset or limit" clause.
  3204. This handles incoming integers and converts to an expression; if
  3205. an expression is already given, it is passed through.
  3206. """
  3207. return coercions.expect(
  3208. roles.LimitOffsetRole, element, name=name, type_=type_
  3209. )
  3210. @overload
  3211. def _offset_or_limit_clause_asint(
  3212. self, clause: ColumnElement[Any], attrname: str
  3213. ) -> NoReturn: ...
  3214. @overload
  3215. def _offset_or_limit_clause_asint(
  3216. self, clause: Optional[_OffsetLimitParam], attrname: str
  3217. ) -> Optional[int]: ...
  3218. def _offset_or_limit_clause_asint(
  3219. self, clause: Optional[ColumnElement[Any]], attrname: str
  3220. ) -> Union[NoReturn, Optional[int]]:
  3221. """Convert the "offset or limit" clause of a select construct to an
  3222. integer.
  3223. This is only possible if the value is stored as a simple bound
  3224. parameter. Otherwise, a compilation error is raised.
  3225. """
  3226. if clause is None:
  3227. return None
  3228. try:
  3229. value = clause._limit_offset_value
  3230. except AttributeError as err:
  3231. raise exc.CompileError(
  3232. "This SELECT structure does not use a simple "
  3233. "integer value for %s" % attrname
  3234. ) from err
  3235. else:
  3236. return util.asint(value)
  3237. @property
  3238. def _limit(self) -> Optional[int]:
  3239. """Get an integer value for the limit. This should only be used
  3240. by code that cannot support a limit as a BindParameter or
  3241. other custom clause as it will throw an exception if the limit
  3242. isn't currently set to an integer.
  3243. """
  3244. return self._offset_or_limit_clause_asint(self._limit_clause, "limit")
  3245. def _simple_int_clause(self, clause: ClauseElement) -> bool:
  3246. """True if the clause is a simple integer, False
  3247. if it is not present or is a SQL expression.
  3248. """
  3249. return isinstance(clause, _OffsetLimitParam)
  3250. @property
  3251. def _offset(self) -> Optional[int]:
  3252. """Get an integer value for the offset. This should only be used
  3253. by code that cannot support an offset as a BindParameter or
  3254. other custom clause as it will throw an exception if the
  3255. offset isn't currently set to an integer.
  3256. """
  3257. return self._offset_or_limit_clause_asint(
  3258. self._offset_clause, "offset"
  3259. )
  3260. @property
  3261. def _has_row_limiting_clause(self) -> bool:
  3262. return (
  3263. self._limit_clause is not None
  3264. or self._offset_clause is not None
  3265. or self._fetch_clause is not None
  3266. )
  3267. @_generative
  3268. def limit(self, limit: _LimitOffsetType) -> Self:
  3269. """Return a new selectable with the given LIMIT criterion
  3270. applied.
  3271. This is a numerical value which usually renders as a ``LIMIT``
  3272. expression in the resulting select. Backends that don't
  3273. support ``LIMIT`` will attempt to provide similar
  3274. functionality.
  3275. .. note::
  3276. The :meth:`_sql.GenerativeSelect.limit` method will replace
  3277. any clause applied with :meth:`_sql.GenerativeSelect.fetch`.
  3278. :param limit: an integer LIMIT parameter, or a SQL expression
  3279. that provides an integer result. Pass ``None`` to reset it.
  3280. .. seealso::
  3281. :meth:`_sql.GenerativeSelect.fetch`
  3282. :meth:`_sql.GenerativeSelect.offset`
  3283. """
  3284. self._fetch_clause = self._fetch_clause_options = None
  3285. self._limit_clause = self._offset_or_limit_clause(limit)
  3286. return self
  3287. @_generative
  3288. def fetch(
  3289. self,
  3290. count: _LimitOffsetType,
  3291. with_ties: bool = False,
  3292. percent: bool = False,
  3293. **dialect_kw: Any,
  3294. ) -> Self:
  3295. r"""Return a new selectable with the given FETCH FIRST criterion
  3296. applied.
  3297. This is a numeric value which usually renders as ``FETCH {FIRST | NEXT}
  3298. [ count ] {ROW | ROWS} {ONLY | WITH TIES}`` expression in the resulting
  3299. select. This functionality is is currently implemented for Oracle
  3300. Database, PostgreSQL, MSSQL.
  3301. Use :meth:`_sql.GenerativeSelect.offset` to specify the offset.
  3302. .. note::
  3303. The :meth:`_sql.GenerativeSelect.fetch` method will replace
  3304. any clause applied with :meth:`_sql.GenerativeSelect.limit`.
  3305. .. versionadded:: 1.4
  3306. :param count: an integer COUNT parameter, or a SQL expression
  3307. that provides an integer result. When ``percent=True`` this will
  3308. represent the percentage of rows to return, not the absolute value.
  3309. Pass ``None`` to reset it.
  3310. :param with_ties: When ``True``, the WITH TIES option is used
  3311. to return any additional rows that tie for the last place in the
  3312. result set according to the ``ORDER BY`` clause. The
  3313. ``ORDER BY`` may be mandatory in this case. Defaults to ``False``
  3314. :param percent: When ``True``, ``count`` represents the percentage
  3315. of the total number of selected rows to return. Defaults to ``False``
  3316. :param \**dialect_kw: Additional dialect-specific keyword arguments
  3317. may be accepted by dialects.
  3318. .. versionadded:: 2.0.41
  3319. .. seealso::
  3320. :meth:`_sql.GenerativeSelect.limit`
  3321. :meth:`_sql.GenerativeSelect.offset`
  3322. """
  3323. self._validate_dialect_kwargs(dialect_kw)
  3324. self._limit_clause = None
  3325. if count is None:
  3326. self._fetch_clause = self._fetch_clause_options = None
  3327. else:
  3328. self._fetch_clause = self._offset_or_limit_clause(count)
  3329. self._fetch_clause_options = {
  3330. "with_ties": with_ties,
  3331. "percent": percent,
  3332. }
  3333. return self
  3334. @_generative
  3335. def offset(self, offset: _LimitOffsetType) -> Self:
  3336. """Return a new selectable with the given OFFSET criterion
  3337. applied.
  3338. This is a numeric value which usually renders as an ``OFFSET``
  3339. expression in the resulting select. Backends that don't
  3340. support ``OFFSET`` will attempt to provide similar
  3341. functionality.
  3342. :param offset: an integer OFFSET parameter, or a SQL expression
  3343. that provides an integer result. Pass ``None`` to reset it.
  3344. .. seealso::
  3345. :meth:`_sql.GenerativeSelect.limit`
  3346. :meth:`_sql.GenerativeSelect.fetch`
  3347. """
  3348. self._offset_clause = self._offset_or_limit_clause(offset)
  3349. return self
  3350. @_generative
  3351. @util.preload_module("sqlalchemy.sql.util")
  3352. def slice(
  3353. self,
  3354. start: int,
  3355. stop: int,
  3356. ) -> Self:
  3357. """Apply LIMIT / OFFSET to this statement based on a slice.
  3358. The start and stop indices behave like the argument to Python's
  3359. built-in :func:`range` function. This method provides an
  3360. alternative to using ``LIMIT``/``OFFSET`` to get a slice of the
  3361. query.
  3362. For example, ::
  3363. stmt = select(User).order_by(User.id).slice(1, 3)
  3364. renders as
  3365. .. sourcecode:: sql
  3366. SELECT users.id AS users_id,
  3367. users.name AS users_name
  3368. FROM users ORDER BY users.id
  3369. LIMIT ? OFFSET ?
  3370. (2, 1)
  3371. .. note::
  3372. The :meth:`_sql.GenerativeSelect.slice` method will replace
  3373. any clause applied with :meth:`_sql.GenerativeSelect.fetch`.
  3374. .. versionadded:: 1.4 Added the :meth:`_sql.GenerativeSelect.slice`
  3375. method generalized from the ORM.
  3376. .. seealso::
  3377. :meth:`_sql.GenerativeSelect.limit`
  3378. :meth:`_sql.GenerativeSelect.offset`
  3379. :meth:`_sql.GenerativeSelect.fetch`
  3380. """
  3381. sql_util = util.preloaded.sql_util
  3382. self._fetch_clause = self._fetch_clause_options = None
  3383. self._limit_clause, self._offset_clause = sql_util._make_slice(
  3384. self._limit_clause, self._offset_clause, start, stop
  3385. )
  3386. return self
  3387. @_generative
  3388. def order_by(
  3389. self,
  3390. __first: Union[
  3391. Literal[None, _NoArg.NO_ARG],
  3392. _ColumnExpressionOrStrLabelArgument[Any],
  3393. ] = _NoArg.NO_ARG,
  3394. *clauses: _ColumnExpressionOrStrLabelArgument[Any],
  3395. ) -> Self:
  3396. r"""Return a new selectable with the given list of ORDER BY
  3397. criteria applied.
  3398. e.g.::
  3399. stmt = select(table).order_by(table.c.id, table.c.name)
  3400. Calling this method multiple times is equivalent to calling it once
  3401. with all the clauses concatenated. All existing ORDER BY criteria may
  3402. be cancelled by passing ``None`` by itself. New ORDER BY criteria may
  3403. then be added by invoking :meth:`_orm.Query.order_by` again, e.g.::
  3404. # will erase all ORDER BY and ORDER BY new_col alone
  3405. stmt = stmt.order_by(None).order_by(new_col)
  3406. :param \*clauses: a series of :class:`_expression.ColumnElement`
  3407. constructs which will be used to generate an ORDER BY clause.
  3408. Alternatively, an individual entry may also be the string name of a
  3409. label located elsewhere in the columns clause of the statement which
  3410. will be matched and rendered in a backend-specific way based on
  3411. context; see :ref:`tutorial_order_by_label` for background on string
  3412. label matching in ORDER BY and GROUP BY expressions.
  3413. .. seealso::
  3414. :ref:`tutorial_order_by` - in the :ref:`unified_tutorial`
  3415. :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
  3416. """
  3417. if not clauses and __first is None:
  3418. self._order_by_clauses = ()
  3419. elif __first is not _NoArg.NO_ARG:
  3420. self._order_by_clauses += tuple(
  3421. coercions.expect(
  3422. roles.OrderByRole, clause, apply_propagate_attrs=self
  3423. )
  3424. for clause in (__first,) + clauses
  3425. )
  3426. return self
  3427. @_generative
  3428. def group_by(
  3429. self,
  3430. __first: Union[
  3431. Literal[None, _NoArg.NO_ARG],
  3432. _ColumnExpressionOrStrLabelArgument[Any],
  3433. ] = _NoArg.NO_ARG,
  3434. *clauses: _ColumnExpressionOrStrLabelArgument[Any],
  3435. ) -> Self:
  3436. r"""Return a new selectable with the given list of GROUP BY
  3437. criterion applied.
  3438. All existing GROUP BY settings can be suppressed by passing ``None``.
  3439. e.g.::
  3440. stmt = select(table.c.name, func.max(table.c.stat)).group_by(table.c.name)
  3441. :param \*clauses: a series of :class:`_expression.ColumnElement`
  3442. constructs which will be used to generate an GROUP BY clause.
  3443. Alternatively, an individual entry may also be the string name of a
  3444. label located elsewhere in the columns clause of the statement which
  3445. will be matched and rendered in a backend-specific way based on
  3446. context; see :ref:`tutorial_order_by_label` for background on string
  3447. label matching in ORDER BY and GROUP BY expressions.
  3448. .. seealso::
  3449. :ref:`tutorial_group_by_w_aggregates` - in the
  3450. :ref:`unified_tutorial`
  3451. :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
  3452. """ # noqa: E501
  3453. if not clauses and __first is None:
  3454. self._group_by_clauses = ()
  3455. elif __first is not _NoArg.NO_ARG:
  3456. self._group_by_clauses += tuple(
  3457. coercions.expect(
  3458. roles.GroupByRole, clause, apply_propagate_attrs=self
  3459. )
  3460. for clause in (__first,) + clauses
  3461. )
  3462. return self
  3463. @CompileState.plugin_for("default", "compound_select")
  3464. class CompoundSelectState(CompileState):
  3465. @util.memoized_property
  3466. def _label_resolve_dict(
  3467. self,
  3468. ) -> Tuple[
  3469. Dict[str, ColumnElement[Any]],
  3470. Dict[str, ColumnElement[Any]],
  3471. Dict[str, ColumnElement[Any]],
  3472. ]:
  3473. # TODO: this is hacky and slow
  3474. hacky_subquery = self.statement.subquery()
  3475. hacky_subquery.named_with_column = False
  3476. d = {c.key: c for c in hacky_subquery.c}
  3477. return d, d, d
  3478. class _CompoundSelectKeyword(Enum):
  3479. UNION = "UNION"
  3480. UNION_ALL = "UNION ALL"
  3481. EXCEPT = "EXCEPT"
  3482. EXCEPT_ALL = "EXCEPT ALL"
  3483. INTERSECT = "INTERSECT"
  3484. INTERSECT_ALL = "INTERSECT ALL"
  3485. class CompoundSelect(HasCompileState, GenerativeSelect, TypedReturnsRows[_TP]):
  3486. """Forms the basis of ``UNION``, ``UNION ALL``, and other
  3487. SELECT-based set operations.
  3488. .. seealso::
  3489. :func:`_expression.union`
  3490. :func:`_expression.union_all`
  3491. :func:`_expression.intersect`
  3492. :func:`_expression.intersect_all`
  3493. :func:`_expression.except`
  3494. :func:`_expression.except_all`
  3495. """
  3496. __visit_name__ = "compound_select"
  3497. _traverse_internals: _TraverseInternalsType = (
  3498. [
  3499. ("selects", InternalTraversal.dp_clauseelement_list),
  3500. ("_limit_clause", InternalTraversal.dp_clauseelement),
  3501. ("_offset_clause", InternalTraversal.dp_clauseelement),
  3502. ("_fetch_clause", InternalTraversal.dp_clauseelement),
  3503. ("_fetch_clause_options", InternalTraversal.dp_plain_dict),
  3504. ("_order_by_clauses", InternalTraversal.dp_clauseelement_list),
  3505. ("_group_by_clauses", InternalTraversal.dp_clauseelement_list),
  3506. ("_for_update_arg", InternalTraversal.dp_clauseelement),
  3507. ("keyword", InternalTraversal.dp_string),
  3508. ]
  3509. + SupportsCloneAnnotations._clone_annotations_traverse_internals
  3510. + HasCTE._has_ctes_traverse_internals
  3511. + DialectKWArgs._dialect_kwargs_traverse_internals
  3512. + Executable._executable_traverse_internals
  3513. )
  3514. selects: List[SelectBase]
  3515. _is_from_container = True
  3516. _auto_correlate = False
  3517. def __init__(
  3518. self,
  3519. keyword: _CompoundSelectKeyword,
  3520. *selects: _SelectStatementForCompoundArgument[_TP],
  3521. ):
  3522. self.keyword = keyword
  3523. self.selects = [
  3524. coercions.expect(
  3525. roles.CompoundElementRole, s, apply_propagate_attrs=self
  3526. ).self_group(against=self)
  3527. for s in selects
  3528. ]
  3529. GenerativeSelect.__init__(self)
  3530. @classmethod
  3531. def _create_union(
  3532. cls, *selects: _SelectStatementForCompoundArgument[_TP]
  3533. ) -> CompoundSelect[_TP]:
  3534. return CompoundSelect(_CompoundSelectKeyword.UNION, *selects)
  3535. @classmethod
  3536. def _create_union_all(
  3537. cls, *selects: _SelectStatementForCompoundArgument[_TP]
  3538. ) -> CompoundSelect[_TP]:
  3539. return CompoundSelect(_CompoundSelectKeyword.UNION_ALL, *selects)
  3540. @classmethod
  3541. def _create_except(
  3542. cls, *selects: _SelectStatementForCompoundArgument[_TP]
  3543. ) -> CompoundSelect[_TP]:
  3544. return CompoundSelect(_CompoundSelectKeyword.EXCEPT, *selects)
  3545. @classmethod
  3546. def _create_except_all(
  3547. cls, *selects: _SelectStatementForCompoundArgument[_TP]
  3548. ) -> CompoundSelect[_TP]:
  3549. return CompoundSelect(_CompoundSelectKeyword.EXCEPT_ALL, *selects)
  3550. @classmethod
  3551. def _create_intersect(
  3552. cls, *selects: _SelectStatementForCompoundArgument[_TP]
  3553. ) -> CompoundSelect[_TP]:
  3554. return CompoundSelect(_CompoundSelectKeyword.INTERSECT, *selects)
  3555. @classmethod
  3556. def _create_intersect_all(
  3557. cls, *selects: _SelectStatementForCompoundArgument[_TP]
  3558. ) -> CompoundSelect[_TP]:
  3559. return CompoundSelect(_CompoundSelectKeyword.INTERSECT_ALL, *selects)
  3560. def _scalar_type(self) -> TypeEngine[Any]:
  3561. return self.selects[0]._scalar_type()
  3562. def self_group(
  3563. self, against: Optional[OperatorType] = None
  3564. ) -> GroupedElement:
  3565. return SelectStatementGrouping(self)
  3566. def is_derived_from(self, fromclause: Optional[FromClause]) -> bool:
  3567. for s in self.selects:
  3568. if s.is_derived_from(fromclause):
  3569. return True
  3570. return False
  3571. def set_label_style(self, style: SelectLabelStyle) -> Self:
  3572. if self._label_style is not style:
  3573. self = self._generate()
  3574. select_0 = self.selects[0].set_label_style(style)
  3575. self.selects = [select_0] + self.selects[1:]
  3576. return self
  3577. def _ensure_disambiguated_names(self) -> Self:
  3578. new_select = self.selects[0]._ensure_disambiguated_names()
  3579. if new_select is not self.selects[0]:
  3580. self = self._generate()
  3581. self.selects = [new_select] + self.selects[1:]
  3582. return self
  3583. def _generate_fromclause_column_proxies(
  3584. self,
  3585. subquery: FromClause,
  3586. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  3587. primary_key: ColumnSet,
  3588. foreign_keys: Set[KeyedColumnElement[Any]],
  3589. *,
  3590. proxy_compound_columns: Optional[
  3591. Iterable[Sequence[ColumnElement[Any]]]
  3592. ] = None,
  3593. ) -> None:
  3594. # this is a slightly hacky thing - the union exports a
  3595. # column that resembles just that of the *first* selectable.
  3596. # to get at a "composite" column, particularly foreign keys,
  3597. # you have to dig through the proxies collection which we
  3598. # generate below.
  3599. select_0 = self.selects[0]
  3600. if self._label_style is not LABEL_STYLE_DEFAULT:
  3601. select_0 = select_0.set_label_style(self._label_style)
  3602. # hand-construct the "_proxies" collection to include all
  3603. # derived columns place a 'weight' annotation corresponding
  3604. # to how low in the list of select()s the column occurs, so
  3605. # that the corresponding_column() operation can resolve
  3606. # conflicts
  3607. extra_col_iterator = zip(
  3608. *[
  3609. [
  3610. c._annotate(dd)
  3611. for c in stmt._all_selected_columns
  3612. if is_column_element(c)
  3613. ]
  3614. for dd, stmt in [
  3615. ({"weight": i + 1}, stmt)
  3616. for i, stmt in enumerate(self.selects)
  3617. ]
  3618. ]
  3619. )
  3620. # the incoming proxy_compound_columns can be present also if this is
  3621. # a compound embedded in a compound. it's probably more appropriate
  3622. # that we generate new weights local to this nested compound, though
  3623. # i haven't tried to think what it means for compound nested in
  3624. # compound
  3625. select_0._generate_fromclause_column_proxies(
  3626. subquery,
  3627. columns,
  3628. proxy_compound_columns=extra_col_iterator,
  3629. primary_key=primary_key,
  3630. foreign_keys=foreign_keys,
  3631. )
  3632. def _refresh_for_new_column(self, column: ColumnElement[Any]) -> None:
  3633. super()._refresh_for_new_column(column)
  3634. for select in self.selects:
  3635. select._refresh_for_new_column(column)
  3636. @util.ro_non_memoized_property
  3637. def _all_selected_columns(self) -> _SelectIterable:
  3638. return self.selects[0]._all_selected_columns
  3639. @util.ro_non_memoized_property
  3640. def selected_columns(
  3641. self,
  3642. ) -> ColumnCollection[str, ColumnElement[Any]]:
  3643. """A :class:`_expression.ColumnCollection`
  3644. representing the columns that
  3645. this SELECT statement or similar construct returns in its result set,
  3646. not including :class:`_sql.TextClause` constructs.
  3647. For a :class:`_expression.CompoundSelect`, the
  3648. :attr:`_expression.CompoundSelect.selected_columns`
  3649. attribute returns the selected
  3650. columns of the first SELECT statement contained within the series of
  3651. statements within the set operation.
  3652. .. seealso::
  3653. :attr:`_sql.Select.selected_columns`
  3654. .. versionadded:: 1.4
  3655. """
  3656. return self.selects[0].selected_columns
  3657. # backwards compat
  3658. for elem in _CompoundSelectKeyword:
  3659. setattr(CompoundSelect, elem.name, elem)
  3660. @CompileState.plugin_for("default", "select")
  3661. class SelectState(util.MemoizedSlots, CompileState):
  3662. __slots__ = (
  3663. "from_clauses",
  3664. "froms",
  3665. "columns_plus_names",
  3666. "_label_resolve_dict",
  3667. )
  3668. if TYPE_CHECKING:
  3669. default_select_compile_options: CacheableOptions
  3670. else:
  3671. class default_select_compile_options(CacheableOptions):
  3672. _cache_key_traversal = []
  3673. if TYPE_CHECKING:
  3674. @classmethod
  3675. def get_plugin_class(
  3676. cls, statement: Executable
  3677. ) -> Type[SelectState]: ...
  3678. def __init__(
  3679. self,
  3680. statement: Select[Any],
  3681. compiler: SQLCompiler,
  3682. **kw: Any,
  3683. ):
  3684. self.statement = statement
  3685. self.from_clauses = statement._from_obj
  3686. for memoized_entities in statement._memoized_select_entities:
  3687. self._setup_joins(
  3688. memoized_entities._setup_joins, memoized_entities._raw_columns
  3689. )
  3690. if statement._setup_joins:
  3691. self._setup_joins(statement._setup_joins, statement._raw_columns)
  3692. self.froms = self._get_froms(statement)
  3693. self.columns_plus_names = statement._generate_columns_plus_names(True)
  3694. @classmethod
  3695. def _plugin_not_implemented(cls) -> NoReturn:
  3696. raise NotImplementedError(
  3697. "The default SELECT construct without plugins does not "
  3698. "implement this method."
  3699. )
  3700. @classmethod
  3701. def get_column_descriptions(
  3702. cls, statement: Select[Any]
  3703. ) -> List[Dict[str, Any]]:
  3704. return [
  3705. {
  3706. "name": name,
  3707. "type": element.type,
  3708. "expr": element,
  3709. }
  3710. for _, name, _, element, _ in (
  3711. statement._generate_columns_plus_names(False)
  3712. )
  3713. ]
  3714. @classmethod
  3715. def from_statement(
  3716. cls, statement: Select[Any], from_statement: roles.ReturnsRowsRole
  3717. ) -> ExecutableReturnsRows:
  3718. cls._plugin_not_implemented()
  3719. @classmethod
  3720. def get_columns_clause_froms(
  3721. cls, statement: Select[Any]
  3722. ) -> List[FromClause]:
  3723. return cls._normalize_froms(
  3724. itertools.chain.from_iterable(
  3725. element._from_objects for element in statement._raw_columns
  3726. )
  3727. )
  3728. @classmethod
  3729. def _column_naming_convention(
  3730. cls, label_style: SelectLabelStyle
  3731. ) -> _LabelConventionCallable:
  3732. table_qualified = label_style is LABEL_STYLE_TABLENAME_PLUS_COL
  3733. dedupe = label_style is not LABEL_STYLE_NONE
  3734. pa = prefix_anon_map()
  3735. names = set()
  3736. def go(
  3737. c: Union[ColumnElement[Any], TextClause],
  3738. col_name: Optional[str] = None,
  3739. ) -> Optional[str]:
  3740. if is_text_clause(c):
  3741. return None
  3742. elif TYPE_CHECKING:
  3743. assert is_column_element(c)
  3744. if not dedupe:
  3745. name = c._proxy_key
  3746. if name is None:
  3747. name = "_no_label"
  3748. return name
  3749. name = c._tq_key_label if table_qualified else c._proxy_key
  3750. if name is None:
  3751. name = "_no_label"
  3752. if name in names:
  3753. return c._anon_label(name) % pa
  3754. else:
  3755. names.add(name)
  3756. return name
  3757. elif name in names:
  3758. return (
  3759. c._anon_tq_key_label % pa
  3760. if table_qualified
  3761. else c._anon_key_label % pa
  3762. )
  3763. else:
  3764. names.add(name)
  3765. return name
  3766. return go
  3767. def _get_froms(self, statement: Select[Any]) -> List[FromClause]:
  3768. ambiguous_table_name_map: _AmbiguousTableNameMap
  3769. self._ambiguous_table_name_map = ambiguous_table_name_map = {}
  3770. return self._normalize_froms(
  3771. itertools.chain(
  3772. self.from_clauses,
  3773. itertools.chain.from_iterable(
  3774. [
  3775. element._from_objects
  3776. for element in statement._raw_columns
  3777. ]
  3778. ),
  3779. itertools.chain.from_iterable(
  3780. [
  3781. element._from_objects
  3782. for element in statement._where_criteria
  3783. ]
  3784. ),
  3785. ),
  3786. check_statement=statement,
  3787. ambiguous_table_name_map=ambiguous_table_name_map,
  3788. )
  3789. @classmethod
  3790. def _normalize_froms(
  3791. cls,
  3792. iterable_of_froms: Iterable[FromClause],
  3793. check_statement: Optional[Select[Any]] = None,
  3794. ambiguous_table_name_map: Optional[_AmbiguousTableNameMap] = None,
  3795. ) -> List[FromClause]:
  3796. """given an iterable of things to select FROM, reduce them to what
  3797. would actually render in the FROM clause of a SELECT.
  3798. This does the job of checking for JOINs, tables, etc. that are in fact
  3799. overlapping due to cloning, adaption, present in overlapping joins,
  3800. etc.
  3801. """
  3802. seen: Set[FromClause] = set()
  3803. froms: List[FromClause] = []
  3804. for item in iterable_of_froms:
  3805. if is_subquery(item) and item.element is check_statement:
  3806. raise exc.InvalidRequestError(
  3807. "select() construct refers to itself as a FROM"
  3808. )
  3809. if not seen.intersection(item._cloned_set):
  3810. froms.append(item)
  3811. seen.update(item._cloned_set)
  3812. if froms:
  3813. toremove = set(
  3814. itertools.chain.from_iterable(
  3815. [_expand_cloned(f._hide_froms) for f in froms]
  3816. )
  3817. )
  3818. if toremove:
  3819. # filter out to FROM clauses not in the list,
  3820. # using a list to maintain ordering
  3821. froms = [f for f in froms if f not in toremove]
  3822. if ambiguous_table_name_map is not None:
  3823. ambiguous_table_name_map.update(
  3824. (
  3825. fr.name,
  3826. _anonymous_label.safe_construct(
  3827. hash(fr.name), fr.name
  3828. ),
  3829. )
  3830. for item in froms
  3831. for fr in item._from_objects
  3832. if is_table(fr)
  3833. and fr.schema
  3834. and fr.name not in ambiguous_table_name_map
  3835. )
  3836. return froms
  3837. def _get_display_froms(
  3838. self,
  3839. explicit_correlate_froms: Optional[Sequence[FromClause]] = None,
  3840. implicit_correlate_froms: Optional[Sequence[FromClause]] = None,
  3841. ) -> List[FromClause]:
  3842. """Return the full list of 'from' clauses to be displayed.
  3843. Takes into account a set of existing froms which may be
  3844. rendered in the FROM clause of enclosing selects; this Select
  3845. may want to leave those absent if it is automatically
  3846. correlating.
  3847. """
  3848. froms = self.froms
  3849. if self.statement._correlate:
  3850. to_correlate = self.statement._correlate
  3851. if to_correlate:
  3852. froms = [
  3853. f
  3854. for f in froms
  3855. if f
  3856. not in _cloned_intersection(
  3857. _cloned_intersection(
  3858. froms, explicit_correlate_froms or ()
  3859. ),
  3860. to_correlate,
  3861. )
  3862. ]
  3863. if self.statement._correlate_except is not None:
  3864. froms = [
  3865. f
  3866. for f in froms
  3867. if f
  3868. not in _cloned_difference(
  3869. _cloned_intersection(
  3870. froms, explicit_correlate_froms or ()
  3871. ),
  3872. self.statement._correlate_except,
  3873. )
  3874. ]
  3875. if (
  3876. self.statement._auto_correlate
  3877. and implicit_correlate_froms
  3878. and len(froms) > 1
  3879. ):
  3880. froms = [
  3881. f
  3882. for f in froms
  3883. if f
  3884. not in _cloned_intersection(froms, implicit_correlate_froms)
  3885. ]
  3886. if not len(froms):
  3887. raise exc.InvalidRequestError(
  3888. "Select statement '%r"
  3889. "' returned no FROM clauses "
  3890. "due to auto-correlation; "
  3891. "specify correlate(<tables>) "
  3892. "to control correlation "
  3893. "manually." % self.statement
  3894. )
  3895. return froms
  3896. def _memoized_attr__label_resolve_dict(
  3897. self,
  3898. ) -> Tuple[
  3899. Dict[str, ColumnElement[Any]],
  3900. Dict[str, ColumnElement[Any]],
  3901. Dict[str, ColumnElement[Any]],
  3902. ]:
  3903. with_cols: Dict[str, ColumnElement[Any]] = {
  3904. c._tq_label or c.key: c
  3905. for c in self.statement._all_selected_columns
  3906. if c._allow_label_resolve
  3907. }
  3908. only_froms: Dict[str, ColumnElement[Any]] = {
  3909. c.key: c # type: ignore
  3910. for c in _select_iterables(self.froms)
  3911. if c._allow_label_resolve
  3912. }
  3913. only_cols: Dict[str, ColumnElement[Any]] = with_cols.copy()
  3914. for key, value in only_froms.items():
  3915. with_cols.setdefault(key, value)
  3916. return with_cols, only_froms, only_cols
  3917. @classmethod
  3918. def determine_last_joined_entity(
  3919. cls, stmt: Select[Any]
  3920. ) -> Optional[_JoinTargetElement]:
  3921. if stmt._setup_joins:
  3922. return stmt._setup_joins[-1][0]
  3923. else:
  3924. return None
  3925. @classmethod
  3926. def all_selected_columns(cls, statement: Select[Any]) -> _SelectIterable:
  3927. return [c for c in _select_iterables(statement._raw_columns)]
  3928. def _setup_joins(
  3929. self,
  3930. args: Tuple[_SetupJoinsElement, ...],
  3931. raw_columns: List[_ColumnsClauseElement],
  3932. ) -> None:
  3933. for right, onclause, left, flags in args:
  3934. if TYPE_CHECKING:
  3935. if onclause is not None:
  3936. assert isinstance(onclause, ColumnElement)
  3937. isouter = flags["isouter"]
  3938. full = flags["full"]
  3939. if left is None:
  3940. (
  3941. left,
  3942. replace_from_obj_index,
  3943. ) = self._join_determine_implicit_left_side(
  3944. raw_columns, left, right, onclause
  3945. )
  3946. else:
  3947. (replace_from_obj_index) = self._join_place_explicit_left_side(
  3948. left
  3949. )
  3950. # these assertions can be made here, as if the right/onclause
  3951. # contained ORM elements, the select() statement would have been
  3952. # upgraded to an ORM select, and this method would not be called;
  3953. # orm.context.ORMSelectCompileState._join() would be
  3954. # used instead.
  3955. if TYPE_CHECKING:
  3956. assert isinstance(right, FromClause)
  3957. if onclause is not None:
  3958. assert isinstance(onclause, ColumnElement)
  3959. if replace_from_obj_index is not None:
  3960. # splice into an existing element in the
  3961. # self._from_obj list
  3962. left_clause = self.from_clauses[replace_from_obj_index]
  3963. self.from_clauses = (
  3964. self.from_clauses[:replace_from_obj_index]
  3965. + (
  3966. Join(
  3967. left_clause,
  3968. right,
  3969. onclause,
  3970. isouter=isouter,
  3971. full=full,
  3972. ),
  3973. )
  3974. + self.from_clauses[replace_from_obj_index + 1 :]
  3975. )
  3976. else:
  3977. assert left is not None
  3978. self.from_clauses = self.from_clauses + (
  3979. Join(left, right, onclause, isouter=isouter, full=full),
  3980. )
  3981. @util.preload_module("sqlalchemy.sql.util")
  3982. def _join_determine_implicit_left_side(
  3983. self,
  3984. raw_columns: List[_ColumnsClauseElement],
  3985. left: Optional[FromClause],
  3986. right: _JoinTargetElement,
  3987. onclause: Optional[ColumnElement[Any]],
  3988. ) -> Tuple[Optional[FromClause], Optional[int]]:
  3989. """When join conditions don't express the left side explicitly,
  3990. determine if an existing FROM or entity in this query
  3991. can serve as the left hand side.
  3992. """
  3993. sql_util = util.preloaded.sql_util
  3994. replace_from_obj_index: Optional[int] = None
  3995. from_clauses = self.from_clauses
  3996. if from_clauses:
  3997. indexes: List[int] = sql_util.find_left_clause_to_join_from(
  3998. from_clauses, right, onclause
  3999. )
  4000. if len(indexes) == 1:
  4001. replace_from_obj_index = indexes[0]
  4002. left = from_clauses[replace_from_obj_index]
  4003. else:
  4004. potential = {}
  4005. statement = self.statement
  4006. for from_clause in itertools.chain(
  4007. itertools.chain.from_iterable(
  4008. [element._from_objects for element in raw_columns]
  4009. ),
  4010. itertools.chain.from_iterable(
  4011. [
  4012. element._from_objects
  4013. for element in statement._where_criteria
  4014. ]
  4015. ),
  4016. ):
  4017. potential[from_clause] = ()
  4018. all_clauses = list(potential.keys())
  4019. indexes = sql_util.find_left_clause_to_join_from(
  4020. all_clauses, right, onclause
  4021. )
  4022. if len(indexes) == 1:
  4023. left = all_clauses[indexes[0]]
  4024. if len(indexes) > 1:
  4025. raise exc.InvalidRequestError(
  4026. "Can't determine which FROM clause to join "
  4027. "from, there are multiple FROMS which can "
  4028. "join to this entity. Please use the .select_from() "
  4029. "method to establish an explicit left side, as well as "
  4030. "providing an explicit ON clause if not present already to "
  4031. "help resolve the ambiguity."
  4032. )
  4033. elif not indexes:
  4034. raise exc.InvalidRequestError(
  4035. "Don't know how to join to %r. "
  4036. "Please use the .select_from() "
  4037. "method to establish an explicit left side, as well as "
  4038. "providing an explicit ON clause if not present already to "
  4039. "help resolve the ambiguity." % (right,)
  4040. )
  4041. return left, replace_from_obj_index
  4042. @util.preload_module("sqlalchemy.sql.util")
  4043. def _join_place_explicit_left_side(
  4044. self, left: FromClause
  4045. ) -> Optional[int]:
  4046. replace_from_obj_index: Optional[int] = None
  4047. sql_util = util.preloaded.sql_util
  4048. from_clauses = list(self.statement._iterate_from_elements())
  4049. if from_clauses:
  4050. indexes: List[int] = sql_util.find_left_clause_that_matches_given(
  4051. self.from_clauses, left
  4052. )
  4053. else:
  4054. indexes = []
  4055. if len(indexes) > 1:
  4056. raise exc.InvalidRequestError(
  4057. "Can't identify which entity in which to assign the "
  4058. "left side of this join. Please use a more specific "
  4059. "ON clause."
  4060. )
  4061. # have an index, means the left side is already present in
  4062. # an existing FROM in the self._from_obj tuple
  4063. if indexes:
  4064. replace_from_obj_index = indexes[0]
  4065. # no index, means we need to add a new element to the
  4066. # self._from_obj tuple
  4067. return replace_from_obj_index
  4068. class _SelectFromElements:
  4069. __slots__ = ()
  4070. _raw_columns: List[_ColumnsClauseElement]
  4071. _where_criteria: Tuple[ColumnElement[Any], ...]
  4072. _from_obj: Tuple[FromClause, ...]
  4073. def _iterate_from_elements(self) -> Iterator[FromClause]:
  4074. # note this does not include elements
  4075. # in _setup_joins
  4076. seen = set()
  4077. for element in self._raw_columns:
  4078. for fr in element._from_objects:
  4079. if fr in seen:
  4080. continue
  4081. seen.add(fr)
  4082. yield fr
  4083. for element in self._where_criteria:
  4084. for fr in element._from_objects:
  4085. if fr in seen:
  4086. continue
  4087. seen.add(fr)
  4088. yield fr
  4089. for element in self._from_obj:
  4090. if element in seen:
  4091. continue
  4092. seen.add(element)
  4093. yield element
  4094. class _MemoizedSelectEntities(
  4095. cache_key.HasCacheKey, traversals.HasCopyInternals, visitors.Traversible
  4096. ):
  4097. """represents partial state from a Select object, for the case
  4098. where Select.columns() has redefined the set of columns/entities the
  4099. statement will be SELECTing from. This object represents
  4100. the entities from the SELECT before that transformation was applied,
  4101. so that transformations that were made in terms of the SELECT at that
  4102. time, such as join() as well as options(), can access the correct context.
  4103. In previous SQLAlchemy versions, this wasn't needed because these
  4104. constructs calculated everything up front, like when you called join()
  4105. or options(), it did everything to figure out how that would translate
  4106. into specific SQL constructs that would be ready to send directly to the
  4107. SQL compiler when needed. But as of
  4108. 1.4, all of that stuff is done in the compilation phase, during the
  4109. "compile state" portion of the process, so that the work can all be
  4110. cached. So it needs to be able to resolve joins/options2 based on what
  4111. the list of entities was when those methods were called.
  4112. """
  4113. __visit_name__ = "memoized_select_entities"
  4114. _traverse_internals: _TraverseInternalsType = [
  4115. ("_raw_columns", InternalTraversal.dp_clauseelement_list),
  4116. ("_setup_joins", InternalTraversal.dp_setup_join_tuple),
  4117. ("_with_options", InternalTraversal.dp_executable_options),
  4118. ]
  4119. _is_clone_of: Optional[ClauseElement]
  4120. _raw_columns: List[_ColumnsClauseElement]
  4121. _setup_joins: Tuple[_SetupJoinsElement, ...]
  4122. _with_options: Tuple[ExecutableOption, ...]
  4123. _annotations = util.EMPTY_DICT
  4124. def _clone(self, **kw: Any) -> Self:
  4125. c = self.__class__.__new__(self.__class__)
  4126. c.__dict__ = {k: v for k, v in self.__dict__.items()}
  4127. c._is_clone_of = self.__dict__.get("_is_clone_of", self)
  4128. return c
  4129. @classmethod
  4130. def _generate_for_statement(cls, select_stmt: Select[Any]) -> None:
  4131. if select_stmt._setup_joins or select_stmt._with_options:
  4132. self = _MemoizedSelectEntities()
  4133. self._raw_columns = select_stmt._raw_columns
  4134. self._setup_joins = select_stmt._setup_joins
  4135. self._with_options = select_stmt._with_options
  4136. select_stmt._memoized_select_entities += (self,)
  4137. select_stmt._raw_columns = []
  4138. select_stmt._setup_joins = select_stmt._with_options = ()
  4139. class Select(
  4140. HasPrefixes,
  4141. HasSuffixes,
  4142. HasHints,
  4143. HasCompileState,
  4144. _SelectFromElements,
  4145. GenerativeSelect,
  4146. TypedReturnsRows[_TP],
  4147. ):
  4148. """Represents a ``SELECT`` statement.
  4149. The :class:`_sql.Select` object is normally constructed using the
  4150. :func:`_sql.select` function. See that function for details.
  4151. .. seealso::
  4152. :func:`_sql.select`
  4153. :ref:`tutorial_selecting_data` - in the 2.0 tutorial
  4154. """
  4155. __visit_name__ = "select"
  4156. _setup_joins: Tuple[_SetupJoinsElement, ...] = ()
  4157. _memoized_select_entities: Tuple[TODO_Any, ...] = ()
  4158. _raw_columns: List[_ColumnsClauseElement]
  4159. _distinct: bool = False
  4160. _distinct_on: Tuple[ColumnElement[Any], ...] = ()
  4161. _correlate: Tuple[FromClause, ...] = ()
  4162. _correlate_except: Optional[Tuple[FromClause, ...]] = None
  4163. _where_criteria: Tuple[ColumnElement[Any], ...] = ()
  4164. _having_criteria: Tuple[ColumnElement[Any], ...] = ()
  4165. _from_obj: Tuple[FromClause, ...] = ()
  4166. _auto_correlate = True
  4167. _is_select_statement = True
  4168. _compile_options: CacheableOptions = (
  4169. SelectState.default_select_compile_options
  4170. )
  4171. _traverse_internals: _TraverseInternalsType = (
  4172. [
  4173. ("_raw_columns", InternalTraversal.dp_clauseelement_list),
  4174. (
  4175. "_memoized_select_entities",
  4176. InternalTraversal.dp_memoized_select_entities,
  4177. ),
  4178. ("_from_obj", InternalTraversal.dp_clauseelement_list),
  4179. ("_where_criteria", InternalTraversal.dp_clauseelement_tuple),
  4180. ("_having_criteria", InternalTraversal.dp_clauseelement_tuple),
  4181. ("_order_by_clauses", InternalTraversal.dp_clauseelement_tuple),
  4182. ("_group_by_clauses", InternalTraversal.dp_clauseelement_tuple),
  4183. ("_setup_joins", InternalTraversal.dp_setup_join_tuple),
  4184. ("_correlate", InternalTraversal.dp_clauseelement_tuple),
  4185. ("_correlate_except", InternalTraversal.dp_clauseelement_tuple),
  4186. ("_limit_clause", InternalTraversal.dp_clauseelement),
  4187. ("_offset_clause", InternalTraversal.dp_clauseelement),
  4188. ("_fetch_clause", InternalTraversal.dp_clauseelement),
  4189. ("_fetch_clause_options", InternalTraversal.dp_plain_dict),
  4190. ("_for_update_arg", InternalTraversal.dp_clauseelement),
  4191. ("_distinct", InternalTraversal.dp_boolean),
  4192. ("_distinct_on", InternalTraversal.dp_clauseelement_tuple),
  4193. ("_label_style", InternalTraversal.dp_plain_obj),
  4194. ]
  4195. + HasCTE._has_ctes_traverse_internals
  4196. + HasPrefixes._has_prefixes_traverse_internals
  4197. + HasSuffixes._has_suffixes_traverse_internals
  4198. + HasHints._has_hints_traverse_internals
  4199. + SupportsCloneAnnotations._clone_annotations_traverse_internals
  4200. + Executable._executable_traverse_internals
  4201. + DialectKWArgs._dialect_kwargs_traverse_internals
  4202. )
  4203. _cache_key_traversal: _CacheKeyTraversalType = _traverse_internals + [
  4204. ("_compile_options", InternalTraversal.dp_has_cache_key)
  4205. ]
  4206. _compile_state_factory: Type[SelectState]
  4207. @classmethod
  4208. def _create_raw_select(cls, **kw: Any) -> Select[Any]:
  4209. """Create a :class:`.Select` using raw ``__new__`` with no coercions.
  4210. Used internally to build up :class:`.Select` constructs with
  4211. pre-established state.
  4212. """
  4213. stmt = Select.__new__(Select)
  4214. stmt.__dict__.update(kw)
  4215. return stmt
  4216. def __init__(
  4217. self, *entities: _ColumnsClauseArgument[Any], **dialect_kw: Any
  4218. ):
  4219. r"""Construct a new :class:`_expression.Select`.
  4220. The public constructor for :class:`_expression.Select` is the
  4221. :func:`_sql.select` function.
  4222. """
  4223. self._raw_columns = [
  4224. coercions.expect(
  4225. roles.ColumnsClauseRole, ent, apply_propagate_attrs=self
  4226. )
  4227. for ent in entities
  4228. ]
  4229. GenerativeSelect.__init__(self)
  4230. def _scalar_type(self) -> TypeEngine[Any]:
  4231. if not self._raw_columns:
  4232. return NULLTYPE
  4233. elem = self._raw_columns[0]
  4234. cols = list(elem._select_iterable)
  4235. return cols[0].type
  4236. def filter(self, *criteria: _ColumnExpressionArgument[bool]) -> Self:
  4237. """A synonym for the :meth:`_sql.Select.where` method."""
  4238. return self.where(*criteria)
  4239. def _filter_by_zero(
  4240. self,
  4241. ) -> Union[
  4242. FromClause, _JoinTargetProtocol, ColumnElement[Any], TextClause
  4243. ]:
  4244. if self._setup_joins:
  4245. meth = SelectState.get_plugin_class(
  4246. self
  4247. ).determine_last_joined_entity
  4248. _last_joined_entity = meth(self)
  4249. if _last_joined_entity is not None:
  4250. return _last_joined_entity
  4251. if self._from_obj:
  4252. return self._from_obj[0]
  4253. return self._raw_columns[0]
  4254. if TYPE_CHECKING:
  4255. @overload
  4256. def scalar_subquery(
  4257. self: Select[Tuple[_MAYBE_ENTITY]],
  4258. ) -> ScalarSelect[Any]: ...
  4259. @overload
  4260. def scalar_subquery(
  4261. self: Select[Tuple[_NOT_ENTITY]],
  4262. ) -> ScalarSelect[_NOT_ENTITY]: ...
  4263. @overload
  4264. def scalar_subquery(self) -> ScalarSelect[Any]: ...
  4265. def scalar_subquery(self) -> ScalarSelect[Any]: ...
  4266. def filter_by(self, **kwargs: Any) -> Self:
  4267. r"""apply the given filtering criterion as a WHERE clause
  4268. to this select.
  4269. """
  4270. from_entity = self._filter_by_zero()
  4271. clauses = [
  4272. _entity_namespace_key(from_entity, key) == value
  4273. for key, value in kwargs.items()
  4274. ]
  4275. return self.filter(*clauses)
  4276. @property
  4277. def column_descriptions(self) -> Any:
  4278. """Return a :term:`plugin-enabled` 'column descriptions' structure
  4279. referring to the columns which are SELECTed by this statement.
  4280. This attribute is generally useful when using the ORM, as an
  4281. extended structure which includes information about mapped
  4282. entities is returned. The section :ref:`queryguide_inspection`
  4283. contains more background.
  4284. For a Core-only statement, the structure returned by this accessor
  4285. is derived from the same objects that are returned by the
  4286. :attr:`.Select.selected_columns` accessor, formatted as a list of
  4287. dictionaries which contain the keys ``name``, ``type`` and ``expr``,
  4288. which indicate the column expressions to be selected::
  4289. >>> stmt = select(user_table)
  4290. >>> stmt.column_descriptions
  4291. [
  4292. {
  4293. 'name': 'id',
  4294. 'type': Integer(),
  4295. 'expr': Column('id', Integer(), ...)},
  4296. {
  4297. 'name': 'name',
  4298. 'type': String(length=30),
  4299. 'expr': Column('name', String(length=30), ...)}
  4300. ]
  4301. .. versionchanged:: 1.4.33 The :attr:`.Select.column_descriptions`
  4302. attribute returns a structure for a Core-only set of entities,
  4303. not just ORM-only entities.
  4304. .. seealso::
  4305. :attr:`.UpdateBase.entity_description` - entity information for
  4306. an :func:`.insert`, :func:`.update`, or :func:`.delete`
  4307. :ref:`queryguide_inspection` - ORM background
  4308. """
  4309. meth = SelectState.get_plugin_class(self).get_column_descriptions
  4310. return meth(self)
  4311. def from_statement(
  4312. self, statement: roles.ReturnsRowsRole
  4313. ) -> ExecutableReturnsRows:
  4314. """Apply the columns which this :class:`.Select` would select
  4315. onto another statement.
  4316. This operation is :term:`plugin-specific` and will raise a not
  4317. supported exception if this :class:`_sql.Select` does not select from
  4318. plugin-enabled entities.
  4319. The statement is typically either a :func:`_expression.text` or
  4320. :func:`_expression.select` construct, and should return the set of
  4321. columns appropriate to the entities represented by this
  4322. :class:`.Select`.
  4323. .. seealso::
  4324. :ref:`orm_queryguide_selecting_text` - usage examples in the
  4325. ORM Querying Guide
  4326. """
  4327. meth = SelectState.get_plugin_class(self).from_statement
  4328. return meth(self, statement)
  4329. @_generative
  4330. def join(
  4331. self,
  4332. target: _JoinTargetArgument,
  4333. onclause: Optional[_OnClauseArgument] = None,
  4334. *,
  4335. isouter: bool = False,
  4336. full: bool = False,
  4337. ) -> Self:
  4338. r"""Create a SQL JOIN against this :class:`_expression.Select`
  4339. object's criterion
  4340. and apply generatively, returning the newly resulting
  4341. :class:`_expression.Select`.
  4342. E.g.::
  4343. stmt = select(user_table).join(
  4344. address_table, user_table.c.id == address_table.c.user_id
  4345. )
  4346. The above statement generates SQL similar to:
  4347. .. sourcecode:: sql
  4348. SELECT user.id, user.name
  4349. FROM user
  4350. JOIN address ON user.id = address.user_id
  4351. .. versionchanged:: 1.4 :meth:`_expression.Select.join` now creates
  4352. a :class:`_sql.Join` object between a :class:`_sql.FromClause`
  4353. source that is within the FROM clause of the existing SELECT,
  4354. and a given target :class:`_sql.FromClause`, and then adds
  4355. this :class:`_sql.Join` to the FROM clause of the newly generated
  4356. SELECT statement. This is completely reworked from the behavior
  4357. in 1.3, which would instead create a subquery of the entire
  4358. :class:`_expression.Select` and then join that subquery to the
  4359. target.
  4360. This is a **backwards incompatible change** as the previous behavior
  4361. was mostly useless, producing an unnamed subquery rejected by
  4362. most databases in any case. The new behavior is modeled after
  4363. that of the very successful :meth:`_orm.Query.join` method in the
  4364. ORM, in order to support the functionality of :class:`_orm.Query`
  4365. being available by using a :class:`_sql.Select` object with an
  4366. :class:`_orm.Session`.
  4367. See the notes for this change at :ref:`change_select_join`.
  4368. :param target: target table to join towards
  4369. :param onclause: ON clause of the join. If omitted, an ON clause
  4370. is generated automatically based on the :class:`_schema.ForeignKey`
  4371. linkages between the two tables, if one can be unambiguously
  4372. determined, otherwise an error is raised.
  4373. :param isouter: if True, generate LEFT OUTER join. Same as
  4374. :meth:`_expression.Select.outerjoin`.
  4375. :param full: if True, generate FULL OUTER join.
  4376. .. seealso::
  4377. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  4378. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  4379. :meth:`_expression.Select.join_from`
  4380. :meth:`_expression.Select.outerjoin`
  4381. """ # noqa: E501
  4382. join_target = coercions.expect(
  4383. roles.JoinTargetRole, target, apply_propagate_attrs=self
  4384. )
  4385. if onclause is not None:
  4386. onclause_element = coercions.expect(roles.OnClauseRole, onclause)
  4387. else:
  4388. onclause_element = None
  4389. self._setup_joins += (
  4390. (
  4391. join_target,
  4392. onclause_element,
  4393. None,
  4394. {"isouter": isouter, "full": full},
  4395. ),
  4396. )
  4397. return self
  4398. def outerjoin_from(
  4399. self,
  4400. from_: _FromClauseArgument,
  4401. target: _JoinTargetArgument,
  4402. onclause: Optional[_OnClauseArgument] = None,
  4403. *,
  4404. full: bool = False,
  4405. ) -> Self:
  4406. r"""Create a SQL LEFT OUTER JOIN against this
  4407. :class:`_expression.Select` object's criterion and apply generatively,
  4408. returning the newly resulting :class:`_expression.Select`.
  4409. Usage is the same as that of :meth:`_selectable.Select.join_from`.
  4410. """
  4411. return self.join_from(
  4412. from_, target, onclause=onclause, isouter=True, full=full
  4413. )
  4414. @_generative
  4415. def join_from(
  4416. self,
  4417. from_: _FromClauseArgument,
  4418. target: _JoinTargetArgument,
  4419. onclause: Optional[_OnClauseArgument] = None,
  4420. *,
  4421. isouter: bool = False,
  4422. full: bool = False,
  4423. ) -> Self:
  4424. r"""Create a SQL JOIN against this :class:`_expression.Select`
  4425. object's criterion
  4426. and apply generatively, returning the newly resulting
  4427. :class:`_expression.Select`.
  4428. E.g.::
  4429. stmt = select(user_table, address_table).join_from(
  4430. user_table, address_table, user_table.c.id == address_table.c.user_id
  4431. )
  4432. The above statement generates SQL similar to:
  4433. .. sourcecode:: sql
  4434. SELECT user.id, user.name, address.id, address.email, address.user_id
  4435. FROM user JOIN address ON user.id = address.user_id
  4436. .. versionadded:: 1.4
  4437. :param from\_: the left side of the join, will be rendered in the
  4438. FROM clause and is roughly equivalent to using the
  4439. :meth:`.Select.select_from` method.
  4440. :param target: target table to join towards
  4441. :param onclause: ON clause of the join.
  4442. :param isouter: if True, generate LEFT OUTER join. Same as
  4443. :meth:`_expression.Select.outerjoin`.
  4444. :param full: if True, generate FULL OUTER join.
  4445. .. seealso::
  4446. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  4447. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  4448. :meth:`_expression.Select.join`
  4449. """ # noqa: E501
  4450. # note the order of parsing from vs. target is important here, as we
  4451. # are also deriving the source of the plugin (i.e. the subject mapper
  4452. # in an ORM query) which should favor the "from_" over the "target"
  4453. from_ = coercions.expect(
  4454. roles.FromClauseRole, from_, apply_propagate_attrs=self
  4455. )
  4456. join_target = coercions.expect(
  4457. roles.JoinTargetRole, target, apply_propagate_attrs=self
  4458. )
  4459. if onclause is not None:
  4460. onclause_element = coercions.expect(roles.OnClauseRole, onclause)
  4461. else:
  4462. onclause_element = None
  4463. self._setup_joins += (
  4464. (
  4465. join_target,
  4466. onclause_element,
  4467. from_,
  4468. {"isouter": isouter, "full": full},
  4469. ),
  4470. )
  4471. return self
  4472. def outerjoin(
  4473. self,
  4474. target: _JoinTargetArgument,
  4475. onclause: Optional[_OnClauseArgument] = None,
  4476. *,
  4477. full: bool = False,
  4478. ) -> Self:
  4479. """Create a left outer join.
  4480. Parameters are the same as that of :meth:`_expression.Select.join`.
  4481. .. versionchanged:: 1.4 :meth:`_expression.Select.outerjoin` now
  4482. creates a :class:`_sql.Join` object between a
  4483. :class:`_sql.FromClause` source that is within the FROM clause of
  4484. the existing SELECT, and a given target :class:`_sql.FromClause`,
  4485. and then adds this :class:`_sql.Join` to the FROM clause of the
  4486. newly generated SELECT statement. This is completely reworked
  4487. from the behavior in 1.3, which would instead create a subquery of
  4488. the entire
  4489. :class:`_expression.Select` and then join that subquery to the
  4490. target.
  4491. This is a **backwards incompatible change** as the previous behavior
  4492. was mostly useless, producing an unnamed subquery rejected by
  4493. most databases in any case. The new behavior is modeled after
  4494. that of the very successful :meth:`_orm.Query.join` method in the
  4495. ORM, in order to support the functionality of :class:`_orm.Query`
  4496. being available by using a :class:`_sql.Select` object with an
  4497. :class:`_orm.Session`.
  4498. See the notes for this change at :ref:`change_select_join`.
  4499. .. seealso::
  4500. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  4501. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  4502. :meth:`_expression.Select.join`
  4503. """
  4504. return self.join(target, onclause=onclause, isouter=True, full=full)
  4505. def get_final_froms(self) -> Sequence[FromClause]:
  4506. """Compute the final displayed list of :class:`_expression.FromClause`
  4507. elements.
  4508. This method will run through the full computation required to
  4509. determine what FROM elements will be displayed in the resulting
  4510. SELECT statement, including shadowing individual tables with
  4511. JOIN objects, as well as full computation for ORM use cases including
  4512. eager loading clauses.
  4513. For ORM use, this accessor returns the **post compilation**
  4514. list of FROM objects; this collection will include elements such as
  4515. eagerly loaded tables and joins. The objects will **not** be
  4516. ORM enabled and not work as a replacement for the
  4517. :meth:`_sql.Select.select_froms` collection; additionally, the
  4518. method is not well performing for an ORM enabled statement as it
  4519. will incur the full ORM construction process.
  4520. To retrieve the FROM list that's implied by the "columns" collection
  4521. passed to the :class:`_sql.Select` originally, use the
  4522. :attr:`_sql.Select.columns_clause_froms` accessor.
  4523. To select from an alternative set of columns while maintaining the
  4524. FROM list, use the :meth:`_sql.Select.with_only_columns` method and
  4525. pass the
  4526. :paramref:`_sql.Select.with_only_columns.maintain_column_froms`
  4527. parameter.
  4528. .. versionadded:: 1.4.23 - the :meth:`_sql.Select.get_final_froms`
  4529. method replaces the previous :attr:`_sql.Select.froms` accessor,
  4530. which is deprecated.
  4531. .. seealso::
  4532. :attr:`_sql.Select.columns_clause_froms`
  4533. """
  4534. compiler = self._default_compiler()
  4535. return self._compile_state_factory(self, compiler)._get_display_froms()
  4536. @property
  4537. @util.deprecated(
  4538. "1.4.23",
  4539. "The :attr:`_expression.Select.froms` attribute is moved to "
  4540. "the :meth:`_expression.Select.get_final_froms` method.",
  4541. )
  4542. def froms(self) -> Sequence[FromClause]:
  4543. """Return the displayed list of :class:`_expression.FromClause`
  4544. elements.
  4545. """
  4546. return self.get_final_froms()
  4547. @property
  4548. def columns_clause_froms(self) -> List[FromClause]:
  4549. """Return the set of :class:`_expression.FromClause` objects implied
  4550. by the columns clause of this SELECT statement.
  4551. .. versionadded:: 1.4.23
  4552. .. seealso::
  4553. :attr:`_sql.Select.froms` - "final" FROM list taking the full
  4554. statement into account
  4555. :meth:`_sql.Select.with_only_columns` - makes use of this
  4556. collection to set up a new FROM list
  4557. """
  4558. return SelectState.get_plugin_class(self).get_columns_clause_froms(
  4559. self
  4560. )
  4561. @property
  4562. def inner_columns(self) -> _SelectIterable:
  4563. """An iterator of all :class:`_expression.ColumnElement`
  4564. expressions which would
  4565. be rendered into the columns clause of the resulting SELECT statement.
  4566. This method is legacy as of 1.4 and is superseded by the
  4567. :attr:`_expression.Select.exported_columns` collection.
  4568. """
  4569. return iter(self._all_selected_columns)
  4570. def is_derived_from(self, fromclause: Optional[FromClause]) -> bool:
  4571. if fromclause is not None and self in fromclause._cloned_set:
  4572. return True
  4573. for f in self._iterate_from_elements():
  4574. if f.is_derived_from(fromclause):
  4575. return True
  4576. return False
  4577. def _copy_internals(
  4578. self, clone: _CloneCallableType = _clone, **kw: Any
  4579. ) -> None:
  4580. # Select() object has been cloned and probably adapted by the
  4581. # given clone function. Apply the cloning function to internal
  4582. # objects
  4583. # 1. keep a dictionary of the froms we've cloned, and what
  4584. # they've become. This allows us to ensure the same cloned from
  4585. # is used when other items such as columns are "cloned"
  4586. all_the_froms = set(
  4587. itertools.chain(
  4588. _from_objects(*self._raw_columns),
  4589. _from_objects(*self._where_criteria),
  4590. _from_objects(*[elem[0] for elem in self._setup_joins]),
  4591. )
  4592. )
  4593. # do a clone for the froms we've gathered. what is important here
  4594. # is if any of the things we are selecting from, like tables,
  4595. # were converted into Join objects. if so, these need to be
  4596. # added to _from_obj explicitly, because otherwise they won't be
  4597. # part of the new state, as they don't associate themselves with
  4598. # their columns.
  4599. new_froms = {f: clone(f, **kw) for f in all_the_froms}
  4600. # 2. copy FROM collections, adding in joins that we've created.
  4601. existing_from_obj = [clone(f, **kw) for f in self._from_obj]
  4602. add_froms = (
  4603. {f for f in new_froms.values() if isinstance(f, Join)}
  4604. .difference(all_the_froms)
  4605. .difference(existing_from_obj)
  4606. )
  4607. self._from_obj = tuple(existing_from_obj) + tuple(add_froms)
  4608. # 3. clone everything else, making sure we use columns
  4609. # corresponding to the froms we just made.
  4610. def replace(
  4611. obj: Union[BinaryExpression[Any], ColumnClause[Any]],
  4612. **kw: Any,
  4613. ) -> Optional[KeyedColumnElement[Any]]:
  4614. if isinstance(obj, ColumnClause) and obj.table in new_froms:
  4615. newelem = new_froms[obj.table].corresponding_column(obj)
  4616. return newelem
  4617. return None
  4618. kw["replace"] = replace
  4619. # copy everything else. for table-ish things like correlate,
  4620. # correlate_except, setup_joins, these clone normally. For
  4621. # column-expression oriented things like raw_columns, where_criteria,
  4622. # order by, we get this from the new froms.
  4623. super()._copy_internals(clone=clone, omit_attrs=("_from_obj",), **kw)
  4624. self._reset_memoizations()
  4625. def get_children(self, **kw: Any) -> Iterable[ClauseElement]:
  4626. return itertools.chain(
  4627. super().get_children(
  4628. omit_attrs=("_from_obj", "_correlate", "_correlate_except"),
  4629. **kw,
  4630. ),
  4631. self._iterate_from_elements(),
  4632. )
  4633. @_generative
  4634. def add_columns(
  4635. self, *entities: _ColumnsClauseArgument[Any]
  4636. ) -> Select[Any]:
  4637. r"""Return a new :func:`_expression.select` construct with
  4638. the given entities appended to its columns clause.
  4639. E.g.::
  4640. my_select = my_select.add_columns(table.c.new_column)
  4641. The original expressions in the columns clause remain in place.
  4642. To replace the original expressions with new ones, see the method
  4643. :meth:`_expression.Select.with_only_columns`.
  4644. :param \*entities: column, table, or other entity expressions to be
  4645. added to the columns clause
  4646. .. seealso::
  4647. :meth:`_expression.Select.with_only_columns` - replaces existing
  4648. expressions rather than appending.
  4649. :ref:`orm_queryguide_select_multiple_entities` - ORM-centric
  4650. example
  4651. """
  4652. self._reset_memoizations()
  4653. self._raw_columns = self._raw_columns + [
  4654. coercions.expect(
  4655. roles.ColumnsClauseRole, column, apply_propagate_attrs=self
  4656. )
  4657. for column in entities
  4658. ]
  4659. return self
  4660. def _set_entities(
  4661. self, entities: Iterable[_ColumnsClauseArgument[Any]]
  4662. ) -> None:
  4663. self._raw_columns = [
  4664. coercions.expect(
  4665. roles.ColumnsClauseRole, ent, apply_propagate_attrs=self
  4666. )
  4667. for ent in util.to_list(entities)
  4668. ]
  4669. @util.deprecated(
  4670. "1.4",
  4671. "The :meth:`_expression.Select.column` method is deprecated and will "
  4672. "be removed in a future release. Please use "
  4673. ":meth:`_expression.Select.add_columns`",
  4674. )
  4675. def column(self, column: _ColumnsClauseArgument[Any]) -> Select[Any]:
  4676. """Return a new :func:`_expression.select` construct with
  4677. the given column expression added to its columns clause.
  4678. E.g.::
  4679. my_select = my_select.column(table.c.new_column)
  4680. See the documentation for
  4681. :meth:`_expression.Select.with_only_columns`
  4682. for guidelines on adding /replacing the columns of a
  4683. :class:`_expression.Select` object.
  4684. """
  4685. return self.add_columns(column)
  4686. @util.preload_module("sqlalchemy.sql.util")
  4687. def reduce_columns(self, only_synonyms: bool = True) -> Select[Any]:
  4688. """Return a new :func:`_expression.select` construct with redundantly
  4689. named, equivalently-valued columns removed from the columns clause.
  4690. "Redundant" here means two columns where one refers to the
  4691. other either based on foreign key, or via a simple equality
  4692. comparison in the WHERE clause of the statement. The primary purpose
  4693. of this method is to automatically construct a select statement
  4694. with all uniquely-named columns, without the need to use
  4695. table-qualified labels as
  4696. :meth:`_expression.Select.set_label_style`
  4697. does.
  4698. When columns are omitted based on foreign key, the referred-to
  4699. column is the one that's kept. When columns are omitted based on
  4700. WHERE equivalence, the first column in the columns clause is the
  4701. one that's kept.
  4702. :param only_synonyms: when True, limit the removal of columns
  4703. to those which have the same name as the equivalent. Otherwise,
  4704. all columns that are equivalent to another are removed.
  4705. """
  4706. woc: Select[Any]
  4707. woc = self.with_only_columns(
  4708. *util.preloaded.sql_util.reduce_columns(
  4709. self._all_selected_columns,
  4710. only_synonyms=only_synonyms,
  4711. *(self._where_criteria + self._from_obj),
  4712. )
  4713. )
  4714. return woc
  4715. # START OVERLOADED FUNCTIONS self.with_only_columns Select 1-8 ", *, maintain_column_froms: bool =..." # noqa: E501
  4716. # code within this block is **programmatically,
  4717. # statically generated** by tools/generate_tuple_map_overloads.py
  4718. @overload
  4719. def with_only_columns(
  4720. self, __ent0: _TCCA[_T0], *, maintain_column_froms: bool = ...
  4721. ) -> Select[Tuple[_T0]]: ...
  4722. @overload
  4723. def with_only_columns(
  4724. self,
  4725. __ent0: _TCCA[_T0],
  4726. __ent1: _TCCA[_T1],
  4727. *,
  4728. maintain_column_froms: bool = ...,
  4729. ) -> Select[Tuple[_T0, _T1]]: ...
  4730. @overload
  4731. def with_only_columns(
  4732. self,
  4733. __ent0: _TCCA[_T0],
  4734. __ent1: _TCCA[_T1],
  4735. __ent2: _TCCA[_T2],
  4736. *,
  4737. maintain_column_froms: bool = ...,
  4738. ) -> Select[Tuple[_T0, _T1, _T2]]: ...
  4739. @overload
  4740. def with_only_columns(
  4741. self,
  4742. __ent0: _TCCA[_T0],
  4743. __ent1: _TCCA[_T1],
  4744. __ent2: _TCCA[_T2],
  4745. __ent3: _TCCA[_T3],
  4746. *,
  4747. maintain_column_froms: bool = ...,
  4748. ) -> Select[Tuple[_T0, _T1, _T2, _T3]]: ...
  4749. @overload
  4750. def with_only_columns(
  4751. self,
  4752. __ent0: _TCCA[_T0],
  4753. __ent1: _TCCA[_T1],
  4754. __ent2: _TCCA[_T2],
  4755. __ent3: _TCCA[_T3],
  4756. __ent4: _TCCA[_T4],
  4757. *,
  4758. maintain_column_froms: bool = ...,
  4759. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4]]: ...
  4760. @overload
  4761. def with_only_columns(
  4762. self,
  4763. __ent0: _TCCA[_T0],
  4764. __ent1: _TCCA[_T1],
  4765. __ent2: _TCCA[_T2],
  4766. __ent3: _TCCA[_T3],
  4767. __ent4: _TCCA[_T4],
  4768. __ent5: _TCCA[_T5],
  4769. *,
  4770. maintain_column_froms: bool = ...,
  4771. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]: ...
  4772. @overload
  4773. def with_only_columns(
  4774. self,
  4775. __ent0: _TCCA[_T0],
  4776. __ent1: _TCCA[_T1],
  4777. __ent2: _TCCA[_T2],
  4778. __ent3: _TCCA[_T3],
  4779. __ent4: _TCCA[_T4],
  4780. __ent5: _TCCA[_T5],
  4781. __ent6: _TCCA[_T6],
  4782. *,
  4783. maintain_column_froms: bool = ...,
  4784. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]]: ...
  4785. @overload
  4786. def with_only_columns(
  4787. self,
  4788. __ent0: _TCCA[_T0],
  4789. __ent1: _TCCA[_T1],
  4790. __ent2: _TCCA[_T2],
  4791. __ent3: _TCCA[_T3],
  4792. __ent4: _TCCA[_T4],
  4793. __ent5: _TCCA[_T5],
  4794. __ent6: _TCCA[_T6],
  4795. __ent7: _TCCA[_T7],
  4796. *,
  4797. maintain_column_froms: bool = ...,
  4798. ) -> Select[Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ...
  4799. # END OVERLOADED FUNCTIONS self.with_only_columns
  4800. @overload
  4801. def with_only_columns(
  4802. self,
  4803. *entities: _ColumnsClauseArgument[Any],
  4804. maintain_column_froms: bool = False,
  4805. **__kw: Any,
  4806. ) -> Select[Any]: ...
  4807. @_generative
  4808. def with_only_columns(
  4809. self,
  4810. *entities: _ColumnsClauseArgument[Any],
  4811. maintain_column_froms: bool = False,
  4812. **__kw: Any,
  4813. ) -> Select[Any]:
  4814. r"""Return a new :func:`_expression.select` construct with its columns
  4815. clause replaced with the given entities.
  4816. By default, this method is exactly equivalent to as if the original
  4817. :func:`_expression.select` had been called with the given entities.
  4818. E.g. a statement::
  4819. s = select(table1.c.a, table1.c.b)
  4820. s = s.with_only_columns(table1.c.b)
  4821. should be exactly equivalent to::
  4822. s = select(table1.c.b)
  4823. In this mode of operation, :meth:`_sql.Select.with_only_columns`
  4824. will also dynamically alter the FROM clause of the
  4825. statement if it is not explicitly stated.
  4826. To maintain the existing set of FROMs including those implied by the
  4827. current columns clause, add the
  4828. :paramref:`_sql.Select.with_only_columns.maintain_column_froms`
  4829. parameter::
  4830. s = select(table1.c.a, table2.c.b)
  4831. s = s.with_only_columns(table1.c.a, maintain_column_froms=True)
  4832. The above parameter performs a transfer of the effective FROMs
  4833. in the columns collection to the :meth:`_sql.Select.select_from`
  4834. method, as though the following were invoked::
  4835. s = select(table1.c.a, table2.c.b)
  4836. s = s.select_from(table1, table2).with_only_columns(table1.c.a)
  4837. The :paramref:`_sql.Select.with_only_columns.maintain_column_froms`
  4838. parameter makes use of the :attr:`_sql.Select.columns_clause_froms`
  4839. collection and performs an operation equivalent to the following::
  4840. s = select(table1.c.a, table2.c.b)
  4841. s = s.select_from(*s.columns_clause_froms).with_only_columns(table1.c.a)
  4842. :param \*entities: column expressions to be used.
  4843. :param maintain_column_froms: boolean parameter that will ensure the
  4844. FROM list implied from the current columns clause will be transferred
  4845. to the :meth:`_sql.Select.select_from` method first.
  4846. .. versionadded:: 1.4.23
  4847. """ # noqa: E501
  4848. if __kw:
  4849. raise _no_kw()
  4850. # memoizations should be cleared here as of
  4851. # I95c560ffcbfa30b26644999412fb6a385125f663 , asserting this
  4852. # is the case for now.
  4853. self._assert_no_memoizations()
  4854. if maintain_column_froms:
  4855. self.select_from.non_generative( # type: ignore
  4856. self, *self.columns_clause_froms
  4857. )
  4858. # then memoize the FROMs etc.
  4859. _MemoizedSelectEntities._generate_for_statement(self)
  4860. self._raw_columns = [
  4861. coercions.expect(roles.ColumnsClauseRole, c)
  4862. for c in coercions._expression_collection_was_a_list(
  4863. "entities", "Select.with_only_columns", entities
  4864. )
  4865. ]
  4866. return self
  4867. @property
  4868. def whereclause(self) -> Optional[ColumnElement[Any]]:
  4869. """Return the completed WHERE clause for this
  4870. :class:`_expression.Select` statement.
  4871. This assembles the current collection of WHERE criteria
  4872. into a single :class:`_expression.BooleanClauseList` construct.
  4873. .. versionadded:: 1.4
  4874. """
  4875. return BooleanClauseList._construct_for_whereclause(
  4876. self._where_criteria
  4877. )
  4878. _whereclause = whereclause
  4879. @_generative
  4880. def where(self, *whereclause: _ColumnExpressionArgument[bool]) -> Self:
  4881. """Return a new :func:`_expression.select` construct with
  4882. the given expression added to
  4883. its WHERE clause, joined to the existing clause via AND, if any.
  4884. """
  4885. assert isinstance(self._where_criteria, tuple)
  4886. for criterion in whereclause:
  4887. where_criteria: ColumnElement[Any] = coercions.expect(
  4888. roles.WhereHavingRole, criterion, apply_propagate_attrs=self
  4889. )
  4890. self._where_criteria += (where_criteria,)
  4891. return self
  4892. @_generative
  4893. def having(self, *having: _ColumnExpressionArgument[bool]) -> Self:
  4894. """Return a new :func:`_expression.select` construct with
  4895. the given expression added to
  4896. its HAVING clause, joined to the existing clause via AND, if any.
  4897. """
  4898. for criterion in having:
  4899. having_criteria = coercions.expect(
  4900. roles.WhereHavingRole, criterion, apply_propagate_attrs=self
  4901. )
  4902. self._having_criteria += (having_criteria,)
  4903. return self
  4904. @_generative
  4905. def distinct(self, *expr: _ColumnExpressionArgument[Any]) -> Self:
  4906. r"""Return a new :func:`_expression.select` construct which
  4907. will apply DISTINCT to the SELECT statement overall.
  4908. E.g.::
  4909. from sqlalchemy import select
  4910. stmt = select(users_table.c.id, users_table.c.name).distinct()
  4911. The above would produce an statement resembling:
  4912. .. sourcecode:: sql
  4913. SELECT DISTINCT user.id, user.name FROM user
  4914. The method also accepts an ``*expr`` parameter which produces the
  4915. PostgreSQL dialect-specific ``DISTINCT ON`` expression. Using this
  4916. parameter on other backends which don't support this syntax will
  4917. raise an error.
  4918. :param \*expr: optional column expressions. When present,
  4919. the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>)``
  4920. construct. A deprecation warning and/or :class:`_exc.CompileError`
  4921. will be raised on other backends.
  4922. .. deprecated:: 1.4 Using \*expr in other dialects is deprecated
  4923. and will raise :class:`_exc.CompileError` in a future version.
  4924. """
  4925. if expr:
  4926. self._distinct = True
  4927. self._distinct_on = self._distinct_on + tuple(
  4928. coercions.expect(roles.ByOfRole, e, apply_propagate_attrs=self)
  4929. for e in expr
  4930. )
  4931. else:
  4932. self._distinct = True
  4933. return self
  4934. @_generative
  4935. def select_from(self, *froms: _FromClauseArgument) -> Self:
  4936. r"""Return a new :func:`_expression.select` construct with the
  4937. given FROM expression(s)
  4938. merged into its list of FROM objects.
  4939. E.g.::
  4940. table1 = table("t1", column("a"))
  4941. table2 = table("t2", column("b"))
  4942. s = select(table1.c.a).select_from(
  4943. table1.join(table2, table1.c.a == table2.c.b)
  4944. )
  4945. The "from" list is a unique set on the identity of each element,
  4946. so adding an already present :class:`_schema.Table`
  4947. or other selectable
  4948. will have no effect. Passing a :class:`_expression.Join` that refers
  4949. to an already present :class:`_schema.Table`
  4950. or other selectable will have
  4951. the effect of concealing the presence of that selectable as
  4952. an individual element in the rendered FROM list, instead
  4953. rendering it into a JOIN clause.
  4954. While the typical purpose of :meth:`_expression.Select.select_from`
  4955. is to
  4956. replace the default, derived FROM clause with a join, it can
  4957. also be called with individual table elements, multiple times
  4958. if desired, in the case that the FROM clause cannot be fully
  4959. derived from the columns clause::
  4960. select(func.count("*")).select_from(table1)
  4961. """
  4962. self._from_obj += tuple(
  4963. coercions.expect(
  4964. roles.FromClauseRole, fromclause, apply_propagate_attrs=self
  4965. )
  4966. for fromclause in froms
  4967. )
  4968. return self
  4969. @_generative
  4970. def correlate(
  4971. self,
  4972. *fromclauses: Union[Literal[None, False], _FromClauseArgument],
  4973. ) -> Self:
  4974. r"""Return a new :class:`_expression.Select`
  4975. which will correlate the given FROM
  4976. clauses to that of an enclosing :class:`_expression.Select`.
  4977. Calling this method turns off the :class:`_expression.Select` object's
  4978. default behavior of "auto-correlation". Normally, FROM elements
  4979. which appear in a :class:`_expression.Select`
  4980. that encloses this one via
  4981. its :term:`WHERE clause`, ORDER BY, HAVING or
  4982. :term:`columns clause` will be omitted from this
  4983. :class:`_expression.Select`
  4984. object's :term:`FROM clause`.
  4985. Setting an explicit correlation collection using the
  4986. :meth:`_expression.Select.correlate`
  4987. method provides a fixed list of FROM objects
  4988. that can potentially take place in this process.
  4989. When :meth:`_expression.Select.correlate`
  4990. is used to apply specific FROM clauses
  4991. for correlation, the FROM elements become candidates for
  4992. correlation regardless of how deeply nested this
  4993. :class:`_expression.Select`
  4994. object is, relative to an enclosing :class:`_expression.Select`
  4995. which refers to
  4996. the same FROM object. This is in contrast to the behavior of
  4997. "auto-correlation" which only correlates to an immediate enclosing
  4998. :class:`_expression.Select`.
  4999. Multi-level correlation ensures that the link
  5000. between enclosed and enclosing :class:`_expression.Select`
  5001. is always via
  5002. at least one WHERE/ORDER BY/HAVING/columns clause in order for
  5003. correlation to take place.
  5004. If ``None`` is passed, the :class:`_expression.Select`
  5005. object will correlate
  5006. none of its FROM entries, and all will render unconditionally
  5007. in the local FROM clause.
  5008. :param \*fromclauses: one or more :class:`.FromClause` or other
  5009. FROM-compatible construct such as an ORM mapped entity to become part
  5010. of the correlate collection; alternatively pass a single value
  5011. ``None`` to remove all existing correlations.
  5012. .. seealso::
  5013. :meth:`_expression.Select.correlate_except`
  5014. :ref:`tutorial_scalar_subquery`
  5015. """
  5016. # tests failing when we try to change how these
  5017. # arguments are passed
  5018. self._auto_correlate = False
  5019. if not fromclauses or fromclauses[0] in {None, False}:
  5020. if len(fromclauses) > 1:
  5021. raise exc.ArgumentError(
  5022. "additional FROM objects not accepted when "
  5023. "passing None/False to correlate()"
  5024. )
  5025. self._correlate = ()
  5026. else:
  5027. self._correlate = self._correlate + tuple(
  5028. coercions.expect(roles.FromClauseRole, f) for f in fromclauses
  5029. )
  5030. return self
  5031. @_generative
  5032. def correlate_except(
  5033. self,
  5034. *fromclauses: Union[Literal[None, False], _FromClauseArgument],
  5035. ) -> Self:
  5036. r"""Return a new :class:`_expression.Select`
  5037. which will omit the given FROM
  5038. clauses from the auto-correlation process.
  5039. Calling :meth:`_expression.Select.correlate_except` turns off the
  5040. :class:`_expression.Select` object's default behavior of
  5041. "auto-correlation" for the given FROM elements. An element
  5042. specified here will unconditionally appear in the FROM list, while
  5043. all other FROM elements remain subject to normal auto-correlation
  5044. behaviors.
  5045. If ``None`` is passed, or no arguments are passed,
  5046. the :class:`_expression.Select` object will correlate all of its
  5047. FROM entries.
  5048. :param \*fromclauses: a list of one or more
  5049. :class:`_expression.FromClause`
  5050. constructs, or other compatible constructs (i.e. ORM-mapped
  5051. classes) to become part of the correlate-exception collection.
  5052. .. seealso::
  5053. :meth:`_expression.Select.correlate`
  5054. :ref:`tutorial_scalar_subquery`
  5055. """
  5056. self._auto_correlate = False
  5057. if not fromclauses or fromclauses[0] in {None, False}:
  5058. if len(fromclauses) > 1:
  5059. raise exc.ArgumentError(
  5060. "additional FROM objects not accepted when "
  5061. "passing None/False to correlate_except()"
  5062. )
  5063. self._correlate_except = ()
  5064. else:
  5065. self._correlate_except = (self._correlate_except or ()) + tuple(
  5066. coercions.expect(roles.FromClauseRole, f) for f in fromclauses
  5067. )
  5068. return self
  5069. @HasMemoized_ro_memoized_attribute
  5070. def selected_columns(
  5071. self,
  5072. ) -> ColumnCollection[str, ColumnElement[Any]]:
  5073. """A :class:`_expression.ColumnCollection`
  5074. representing the columns that
  5075. this SELECT statement or similar construct returns in its result set,
  5076. not including :class:`_sql.TextClause` constructs.
  5077. This collection differs from the :attr:`_expression.FromClause.columns`
  5078. collection of a :class:`_expression.FromClause` in that the columns
  5079. within this collection cannot be directly nested inside another SELECT
  5080. statement; a subquery must be applied first which provides for the
  5081. necessary parenthesization required by SQL.
  5082. For a :func:`_expression.select` construct, the collection here is
  5083. exactly what would be rendered inside the "SELECT" statement, and the
  5084. :class:`_expression.ColumnElement` objects are directly present as they
  5085. were given, e.g.::
  5086. col1 = column("q", Integer)
  5087. col2 = column("p", Integer)
  5088. stmt = select(col1, col2)
  5089. Above, ``stmt.selected_columns`` would be a collection that contains
  5090. the ``col1`` and ``col2`` objects directly. For a statement that is
  5091. against a :class:`_schema.Table` or other
  5092. :class:`_expression.FromClause`, the collection will use the
  5093. :class:`_expression.ColumnElement` objects that are in the
  5094. :attr:`_expression.FromClause.c` collection of the from element.
  5095. A use case for the :attr:`_sql.Select.selected_columns` collection is
  5096. to allow the existing columns to be referenced when adding additional
  5097. criteria, e.g.::
  5098. def filter_on_id(my_select, id):
  5099. return my_select.where(my_select.selected_columns["id"] == id)
  5100. stmt = select(MyModel)
  5101. # adds "WHERE id=:param" to the statement
  5102. stmt = filter_on_id(stmt, 42)
  5103. .. note::
  5104. The :attr:`_sql.Select.selected_columns` collection does not
  5105. include expressions established in the columns clause using the
  5106. :func:`_sql.text` construct; these are silently omitted from the
  5107. collection. To use plain textual column expressions inside of a
  5108. :class:`_sql.Select` construct, use the :func:`_sql.literal_column`
  5109. construct.
  5110. .. versionadded:: 1.4
  5111. """
  5112. # compare to SelectState._generate_columns_plus_names, which
  5113. # generates the actual names used in the SELECT string. that
  5114. # method is more complex because it also renders columns that are
  5115. # fully ambiguous, e.g. same column more than once.
  5116. conv = cast(
  5117. "Callable[[Any], str]",
  5118. SelectState._column_naming_convention(self._label_style),
  5119. )
  5120. cc: ColumnCollection[str, ColumnElement[Any]] = ColumnCollection(
  5121. [
  5122. (conv(c), c)
  5123. for c in self._all_selected_columns
  5124. if is_column_element(c)
  5125. ]
  5126. )
  5127. return cc.as_readonly()
  5128. @HasMemoized_ro_memoized_attribute
  5129. def _all_selected_columns(self) -> _SelectIterable:
  5130. meth = SelectState.get_plugin_class(self).all_selected_columns
  5131. return list(meth(self))
  5132. def _ensure_disambiguated_names(self) -> Select[Any]:
  5133. if self._label_style is LABEL_STYLE_NONE:
  5134. self = self.set_label_style(LABEL_STYLE_DISAMBIGUATE_ONLY)
  5135. return self
  5136. def _generate_fromclause_column_proxies(
  5137. self,
  5138. subquery: FromClause,
  5139. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  5140. primary_key: ColumnSet,
  5141. foreign_keys: Set[KeyedColumnElement[Any]],
  5142. *,
  5143. proxy_compound_columns: Optional[
  5144. Iterable[Sequence[ColumnElement[Any]]]
  5145. ] = None,
  5146. ) -> None:
  5147. """Generate column proxies to place in the exported ``.c``
  5148. collection of a subquery."""
  5149. if proxy_compound_columns:
  5150. extra_col_iterator = proxy_compound_columns
  5151. prox = [
  5152. c._make_proxy(
  5153. subquery,
  5154. key=proxy_key,
  5155. name=required_label_name,
  5156. name_is_truncatable=True,
  5157. compound_select_cols=extra_cols,
  5158. primary_key=primary_key,
  5159. foreign_keys=foreign_keys,
  5160. )
  5161. for (
  5162. (
  5163. required_label_name,
  5164. proxy_key,
  5165. fallback_label_name,
  5166. c,
  5167. repeated,
  5168. ),
  5169. extra_cols,
  5170. ) in (
  5171. zip(
  5172. self._generate_columns_plus_names(False),
  5173. extra_col_iterator,
  5174. )
  5175. )
  5176. if is_column_element(c)
  5177. ]
  5178. else:
  5179. prox = [
  5180. c._make_proxy(
  5181. subquery,
  5182. key=proxy_key,
  5183. name=required_label_name,
  5184. name_is_truncatable=True,
  5185. primary_key=primary_key,
  5186. foreign_keys=foreign_keys,
  5187. )
  5188. for (
  5189. required_label_name,
  5190. proxy_key,
  5191. fallback_label_name,
  5192. c,
  5193. repeated,
  5194. ) in (self._generate_columns_plus_names(False))
  5195. if is_column_element(c)
  5196. ]
  5197. columns._populate_separate_keys(prox)
  5198. def _needs_parens_for_grouping(self) -> bool:
  5199. return self._has_row_limiting_clause or bool(
  5200. self._order_by_clause.clauses
  5201. )
  5202. def self_group(
  5203. self, against: Optional[OperatorType] = None
  5204. ) -> Union[SelectStatementGrouping[Self], Self]:
  5205. """Return a 'grouping' construct as per the
  5206. :class:`_expression.ClauseElement` specification.
  5207. This produces an element that can be embedded in an expression. Note
  5208. that this method is called automatically as needed when constructing
  5209. expressions and should not require explicit use.
  5210. """
  5211. if (
  5212. isinstance(against, CompoundSelect)
  5213. and not self._needs_parens_for_grouping()
  5214. ):
  5215. return self
  5216. else:
  5217. return SelectStatementGrouping(self)
  5218. def union(
  5219. self, *other: _SelectStatementForCompoundArgument[_TP]
  5220. ) -> CompoundSelect[_TP]:
  5221. r"""Return a SQL ``UNION`` of this select() construct against
  5222. the given selectables provided as positional arguments.
  5223. :param \*other: one or more elements with which to create a
  5224. UNION.
  5225. .. versionchanged:: 1.4.28
  5226. multiple elements are now accepted.
  5227. :param \**kwargs: keyword arguments are forwarded to the constructor
  5228. for the newly created :class:`_sql.CompoundSelect` object.
  5229. """
  5230. return CompoundSelect._create_union(self, *other)
  5231. def union_all(
  5232. self, *other: _SelectStatementForCompoundArgument[_TP]
  5233. ) -> CompoundSelect[_TP]:
  5234. r"""Return a SQL ``UNION ALL`` of this select() construct against
  5235. the given selectables provided as positional arguments.
  5236. :param \*other: one or more elements with which to create a
  5237. UNION.
  5238. .. versionchanged:: 1.4.28
  5239. multiple elements are now accepted.
  5240. :param \**kwargs: keyword arguments are forwarded to the constructor
  5241. for the newly created :class:`_sql.CompoundSelect` object.
  5242. """
  5243. return CompoundSelect._create_union_all(self, *other)
  5244. def except_(
  5245. self, *other: _SelectStatementForCompoundArgument[_TP]
  5246. ) -> CompoundSelect[_TP]:
  5247. r"""Return a SQL ``EXCEPT`` of this select() construct against
  5248. the given selectable provided as positional arguments.
  5249. :param \*other: one or more elements with which to create a
  5250. UNION.
  5251. .. versionchanged:: 1.4.28
  5252. multiple elements are now accepted.
  5253. """
  5254. return CompoundSelect._create_except(self, *other)
  5255. def except_all(
  5256. self, *other: _SelectStatementForCompoundArgument[_TP]
  5257. ) -> CompoundSelect[_TP]:
  5258. r"""Return a SQL ``EXCEPT ALL`` of this select() construct against
  5259. the given selectables provided as positional arguments.
  5260. :param \*other: one or more elements with which to create a
  5261. UNION.
  5262. .. versionchanged:: 1.4.28
  5263. multiple elements are now accepted.
  5264. """
  5265. return CompoundSelect._create_except_all(self, *other)
  5266. def intersect(
  5267. self, *other: _SelectStatementForCompoundArgument[_TP]
  5268. ) -> CompoundSelect[_TP]:
  5269. r"""Return a SQL ``INTERSECT`` of this select() construct against
  5270. the given selectables provided as positional arguments.
  5271. :param \*other: one or more elements with which to create a
  5272. UNION.
  5273. .. versionchanged:: 1.4.28
  5274. multiple elements are now accepted.
  5275. :param \**kwargs: keyword arguments are forwarded to the constructor
  5276. for the newly created :class:`_sql.CompoundSelect` object.
  5277. """
  5278. return CompoundSelect._create_intersect(self, *other)
  5279. def intersect_all(
  5280. self, *other: _SelectStatementForCompoundArgument[_TP]
  5281. ) -> CompoundSelect[_TP]:
  5282. r"""Return a SQL ``INTERSECT ALL`` of this select() construct
  5283. against the given selectables provided as positional arguments.
  5284. :param \*other: one or more elements with which to create a
  5285. UNION.
  5286. .. versionchanged:: 1.4.28
  5287. multiple elements are now accepted.
  5288. :param \**kwargs: keyword arguments are forwarded to the constructor
  5289. for the newly created :class:`_sql.CompoundSelect` object.
  5290. """
  5291. return CompoundSelect._create_intersect_all(self, *other)
  5292. class ScalarSelect(
  5293. roles.InElementRole, Generative, GroupedElement, ColumnElement[_T]
  5294. ):
  5295. """Represent a scalar subquery.
  5296. A :class:`_sql.ScalarSelect` is created by invoking the
  5297. :meth:`_sql.SelectBase.scalar_subquery` method. The object
  5298. then participates in other SQL expressions as a SQL column expression
  5299. within the :class:`_sql.ColumnElement` hierarchy.
  5300. .. seealso::
  5301. :meth:`_sql.SelectBase.scalar_subquery`
  5302. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  5303. """
  5304. _traverse_internals: _TraverseInternalsType = [
  5305. ("element", InternalTraversal.dp_clauseelement),
  5306. ("type", InternalTraversal.dp_type),
  5307. ]
  5308. _from_objects: List[FromClause] = []
  5309. _is_from_container = True
  5310. if not TYPE_CHECKING:
  5311. _is_implicitly_boolean = False
  5312. inherit_cache = True
  5313. element: SelectBase
  5314. def __init__(self, element: SelectBase) -> None:
  5315. self.element = element
  5316. self.type = element._scalar_type()
  5317. self._propagate_attrs = element._propagate_attrs
  5318. def __getattr__(self, attr: str) -> Any:
  5319. return getattr(self.element, attr)
  5320. def __getstate__(self) -> Dict[str, Any]:
  5321. return {"element": self.element, "type": self.type}
  5322. def __setstate__(self, state: Dict[str, Any]) -> None:
  5323. self.element = state["element"]
  5324. self.type = state["type"]
  5325. @property
  5326. def columns(self) -> NoReturn:
  5327. raise exc.InvalidRequestError(
  5328. "Scalar Select expression has no "
  5329. "columns; use this object directly "
  5330. "within a column-level expression."
  5331. )
  5332. c = columns
  5333. @_generative
  5334. def where(self, crit: _ColumnExpressionArgument[bool]) -> Self:
  5335. """Apply a WHERE clause to the SELECT statement referred to
  5336. by this :class:`_expression.ScalarSelect`.
  5337. """
  5338. self.element = cast("Select[Any]", self.element).where(crit)
  5339. return self
  5340. def self_group(self, against: Optional[OperatorType] = None) -> Self:
  5341. return self
  5342. def _ungroup(self) -> Self:
  5343. return self
  5344. @_generative
  5345. def correlate(
  5346. self,
  5347. *fromclauses: Union[Literal[None, False], _FromClauseArgument],
  5348. ) -> Self:
  5349. r"""Return a new :class:`_expression.ScalarSelect`
  5350. which will correlate the given FROM
  5351. clauses to that of an enclosing :class:`_expression.Select`.
  5352. This method is mirrored from the :meth:`_sql.Select.correlate` method
  5353. of the underlying :class:`_sql.Select`. The method applies the
  5354. :meth:_sql.Select.correlate` method, then returns a new
  5355. :class:`_sql.ScalarSelect` against that statement.
  5356. .. versionadded:: 1.4 Previously, the
  5357. :meth:`_sql.ScalarSelect.correlate`
  5358. method was only available from :class:`_sql.Select`.
  5359. :param \*fromclauses: a list of one or more
  5360. :class:`_expression.FromClause`
  5361. constructs, or other compatible constructs (i.e. ORM-mapped
  5362. classes) to become part of the correlate collection.
  5363. .. seealso::
  5364. :meth:`_expression.ScalarSelect.correlate_except`
  5365. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  5366. """
  5367. self.element = cast("Select[Any]", self.element).correlate(
  5368. *fromclauses
  5369. )
  5370. return self
  5371. @_generative
  5372. def correlate_except(
  5373. self,
  5374. *fromclauses: Union[Literal[None, False], _FromClauseArgument],
  5375. ) -> Self:
  5376. r"""Return a new :class:`_expression.ScalarSelect`
  5377. which will omit the given FROM
  5378. clauses from the auto-correlation process.
  5379. This method is mirrored from the
  5380. :meth:`_sql.Select.correlate_except` method of the underlying
  5381. :class:`_sql.Select`. The method applies the
  5382. :meth:_sql.Select.correlate_except` method, then returns a new
  5383. :class:`_sql.ScalarSelect` against that statement.
  5384. .. versionadded:: 1.4 Previously, the
  5385. :meth:`_sql.ScalarSelect.correlate_except`
  5386. method was only available from :class:`_sql.Select`.
  5387. :param \*fromclauses: a list of one or more
  5388. :class:`_expression.FromClause`
  5389. constructs, or other compatible constructs (i.e. ORM-mapped
  5390. classes) to become part of the correlate-exception collection.
  5391. .. seealso::
  5392. :meth:`_expression.ScalarSelect.correlate`
  5393. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  5394. """
  5395. self.element = cast("Select[Any]", self.element).correlate_except(
  5396. *fromclauses
  5397. )
  5398. return self
  5399. class Exists(UnaryExpression[bool]):
  5400. """Represent an ``EXISTS`` clause.
  5401. See :func:`_sql.exists` for a description of usage.
  5402. An ``EXISTS`` clause can also be constructed from a :func:`_sql.select`
  5403. instance by calling :meth:`_sql.SelectBase.exists`.
  5404. """
  5405. inherit_cache = True
  5406. def __init__(
  5407. self,
  5408. __argument: Optional[
  5409. Union[_ColumnsClauseArgument[Any], SelectBase, ScalarSelect[Any]]
  5410. ] = None,
  5411. ):
  5412. s: ScalarSelect[Any]
  5413. # TODO: this seems like we should be using coercions for this
  5414. if __argument is None:
  5415. s = Select(literal_column("*")).scalar_subquery()
  5416. elif isinstance(__argument, SelectBase):
  5417. s = __argument.scalar_subquery()
  5418. s._propagate_attrs = __argument._propagate_attrs
  5419. elif isinstance(__argument, ScalarSelect):
  5420. s = __argument
  5421. else:
  5422. s = Select(__argument).scalar_subquery()
  5423. UnaryExpression.__init__(
  5424. self,
  5425. s,
  5426. operator=operators.exists,
  5427. type_=type_api.BOOLEANTYPE,
  5428. )
  5429. @util.ro_non_memoized_property
  5430. def _from_objects(self) -> List[FromClause]:
  5431. return []
  5432. def _regroup(
  5433. self,
  5434. fn: Callable[[Select[Any]], Select[Any]],
  5435. ) -> ScalarSelect[Any]:
  5436. assert isinstance(self.element, ScalarSelect)
  5437. element = self.element.element
  5438. if not isinstance(element, Select):
  5439. raise exc.InvalidRequestError(
  5440. "Can only apply this operation to a plain SELECT construct"
  5441. )
  5442. new_element = fn(element)
  5443. return_value = new_element.scalar_subquery()
  5444. return return_value
  5445. def select(self) -> Select[Tuple[bool]]:
  5446. r"""Return a SELECT of this :class:`_expression.Exists`.
  5447. e.g.::
  5448. stmt = exists(some_table.c.id).where(some_table.c.id == 5).select()
  5449. This will produce a statement resembling:
  5450. .. sourcecode:: sql
  5451. SELECT EXISTS (SELECT id FROM some_table WHERE some_table = :param) AS anon_1
  5452. .. seealso::
  5453. :func:`_expression.select` - general purpose
  5454. method which allows for arbitrary column lists.
  5455. """ # noqa
  5456. return Select(self)
  5457. def correlate(
  5458. self,
  5459. *fromclauses: Union[Literal[None, False], _FromClauseArgument],
  5460. ) -> Self:
  5461. """Apply correlation to the subquery noted by this
  5462. :class:`_sql.Exists`.
  5463. .. seealso::
  5464. :meth:`_sql.ScalarSelect.correlate`
  5465. """
  5466. e = self._clone()
  5467. e.element = self._regroup(
  5468. lambda element: element.correlate(*fromclauses)
  5469. )
  5470. return e
  5471. def correlate_except(
  5472. self,
  5473. *fromclauses: Union[Literal[None, False], _FromClauseArgument],
  5474. ) -> Self:
  5475. """Apply correlation to the subquery noted by this
  5476. :class:`_sql.Exists`.
  5477. .. seealso::
  5478. :meth:`_sql.ScalarSelect.correlate_except`
  5479. """
  5480. e = self._clone()
  5481. e.element = self._regroup(
  5482. lambda element: element.correlate_except(*fromclauses)
  5483. )
  5484. return e
  5485. def select_from(self, *froms: _FromClauseArgument) -> Self:
  5486. """Return a new :class:`_expression.Exists` construct,
  5487. applying the given
  5488. expression to the :meth:`_expression.Select.select_from`
  5489. method of the select
  5490. statement contained.
  5491. .. note:: it is typically preferable to build a :class:`_sql.Select`
  5492. statement first, including the desired WHERE clause, then use the
  5493. :meth:`_sql.SelectBase.exists` method to produce an
  5494. :class:`_sql.Exists` object at once.
  5495. """
  5496. e = self._clone()
  5497. e.element = self._regroup(lambda element: element.select_from(*froms))
  5498. return e
  5499. def where(self, *clause: _ColumnExpressionArgument[bool]) -> Self:
  5500. """Return a new :func:`_expression.exists` construct with the
  5501. given expression added to
  5502. its WHERE clause, joined to the existing clause via AND, if any.
  5503. .. note:: it is typically preferable to build a :class:`_sql.Select`
  5504. statement first, including the desired WHERE clause, then use the
  5505. :meth:`_sql.SelectBase.exists` method to produce an
  5506. :class:`_sql.Exists` object at once.
  5507. """
  5508. e = self._clone()
  5509. e.element = self._regroup(lambda element: element.where(*clause))
  5510. return e
  5511. class TextualSelect(SelectBase, ExecutableReturnsRows, Generative):
  5512. """Wrap a :class:`_expression.TextClause` construct within a
  5513. :class:`_expression.SelectBase`
  5514. interface.
  5515. This allows the :class:`_expression.TextClause` object to gain a
  5516. ``.c`` collection
  5517. and other FROM-like capabilities such as
  5518. :meth:`_expression.FromClause.alias`,
  5519. :meth:`_expression.SelectBase.cte`, etc.
  5520. The :class:`_expression.TextualSelect` construct is produced via the
  5521. :meth:`_expression.TextClause.columns`
  5522. method - see that method for details.
  5523. .. versionchanged:: 1.4 the :class:`_expression.TextualSelect`
  5524. class was renamed
  5525. from ``TextAsFrom``, to more correctly suit its role as a
  5526. SELECT-oriented object and not a FROM clause.
  5527. .. seealso::
  5528. :func:`_expression.text`
  5529. :meth:`_expression.TextClause.columns` - primary creation interface.
  5530. """
  5531. __visit_name__ = "textual_select"
  5532. _label_style = LABEL_STYLE_NONE
  5533. _traverse_internals: _TraverseInternalsType = (
  5534. [
  5535. ("element", InternalTraversal.dp_clauseelement),
  5536. ("column_args", InternalTraversal.dp_clauseelement_list),
  5537. ]
  5538. + SupportsCloneAnnotations._clone_annotations_traverse_internals
  5539. + HasCTE._has_ctes_traverse_internals
  5540. + Executable._executable_traverse_internals
  5541. )
  5542. _is_textual = True
  5543. is_text = True
  5544. is_select = True
  5545. def __init__(
  5546. self,
  5547. text: TextClause,
  5548. columns: List[_ColumnExpressionArgument[Any]],
  5549. positional: bool = False,
  5550. ) -> None:
  5551. self._init(
  5552. text,
  5553. # convert for ORM attributes->columns, etc
  5554. [
  5555. coercions.expect(roles.LabeledColumnExprRole, c)
  5556. for c in columns
  5557. ],
  5558. positional,
  5559. )
  5560. def _init(
  5561. self,
  5562. text: TextClause,
  5563. columns: List[NamedColumn[Any]],
  5564. positional: bool = False,
  5565. ) -> None:
  5566. self.element = text
  5567. self.column_args = columns
  5568. self.positional = positional
  5569. @HasMemoized_ro_memoized_attribute
  5570. def selected_columns(
  5571. self,
  5572. ) -> ColumnCollection[str, KeyedColumnElement[Any]]:
  5573. """A :class:`_expression.ColumnCollection`
  5574. representing the columns that
  5575. this SELECT statement or similar construct returns in its result set,
  5576. not including :class:`_sql.TextClause` constructs.
  5577. This collection differs from the :attr:`_expression.FromClause.columns`
  5578. collection of a :class:`_expression.FromClause` in that the columns
  5579. within this collection cannot be directly nested inside another SELECT
  5580. statement; a subquery must be applied first which provides for the
  5581. necessary parenthesization required by SQL.
  5582. For a :class:`_expression.TextualSelect` construct, the collection
  5583. contains the :class:`_expression.ColumnElement` objects that were
  5584. passed to the constructor, typically via the
  5585. :meth:`_expression.TextClause.columns` method.
  5586. .. versionadded:: 1.4
  5587. """
  5588. return ColumnCollection(
  5589. (c.key, c) for c in self.column_args
  5590. ).as_readonly()
  5591. @util.ro_non_memoized_property
  5592. def _all_selected_columns(self) -> _SelectIterable:
  5593. return self.column_args
  5594. def set_label_style(self, style: SelectLabelStyle) -> TextualSelect:
  5595. return self
  5596. def _ensure_disambiguated_names(self) -> TextualSelect:
  5597. return self
  5598. @_generative
  5599. def bindparams(
  5600. self,
  5601. *binds: BindParameter[Any],
  5602. **bind_as_values: Any,
  5603. ) -> Self:
  5604. self.element = self.element.bindparams(*binds, **bind_as_values)
  5605. return self
  5606. def _generate_fromclause_column_proxies(
  5607. self,
  5608. fromclause: FromClause,
  5609. columns: ColumnCollection[str, KeyedColumnElement[Any]],
  5610. primary_key: ColumnSet,
  5611. foreign_keys: Set[KeyedColumnElement[Any]],
  5612. *,
  5613. proxy_compound_columns: Optional[
  5614. Iterable[Sequence[ColumnElement[Any]]]
  5615. ] = None,
  5616. ) -> None:
  5617. if TYPE_CHECKING:
  5618. assert isinstance(fromclause, Subquery)
  5619. if proxy_compound_columns:
  5620. columns._populate_separate_keys(
  5621. c._make_proxy(
  5622. fromclause,
  5623. compound_select_cols=extra_cols,
  5624. primary_key=primary_key,
  5625. foreign_keys=foreign_keys,
  5626. )
  5627. for c, extra_cols in zip(
  5628. self.column_args, proxy_compound_columns
  5629. )
  5630. )
  5631. else:
  5632. columns._populate_separate_keys(
  5633. c._make_proxy(
  5634. fromclause,
  5635. primary_key=primary_key,
  5636. foreign_keys=foreign_keys,
  5637. )
  5638. for c in self.column_args
  5639. )
  5640. def _scalar_type(self) -> Union[TypeEngine[Any], Any]:
  5641. return self.column_args[0].type
  5642. TextAsFrom = TextualSelect
  5643. """Backwards compatibility with the previous name"""
  5644. class AnnotatedFromClause(Annotated):
  5645. def _copy_internals(
  5646. self,
  5647. _annotations_traversal: bool = False,
  5648. ind_cols_on_fromclause: bool = False,
  5649. **kw: Any,
  5650. ) -> None:
  5651. super()._copy_internals(**kw)
  5652. # passed from annotations._shallow_annotate(), _deep_annotate(), etc.
  5653. # the traversals used by annotations for these cases are not currently
  5654. # designed around expecting that inner elements inside of
  5655. # AnnotatedFromClause's element are also deep copied, so skip for these
  5656. # cases. in other cases such as plain visitors.cloned_traverse(), we
  5657. # expect this to happen. see issue #12915
  5658. if not _annotations_traversal:
  5659. ee = self._Annotated__element # type: ignore
  5660. ee._copy_internals(**kw)
  5661. if ind_cols_on_fromclause:
  5662. # passed from annotations._deep_annotate(). See that function
  5663. # for notes
  5664. ee = self._Annotated__element # type: ignore
  5665. self.c = ee.__class__.c.fget(self) # type: ignore
  5666. @util.ro_memoized_property
  5667. def c(self) -> ReadOnlyColumnCollection[str, KeyedColumnElement[Any]]:
  5668. """proxy the .c collection of the underlying FromClause.
  5669. Originally implemented in 2008 as a simple load of the .c collection
  5670. when the annotated construct was created (see d3621ae961a), in modern
  5671. SQLAlchemy versions this can be expensive for statements constructed
  5672. with ORM aliases. So for #8796 SQLAlchemy 2.0 we instead proxy
  5673. it, which works just as well.
  5674. Two different use cases seem to require the collection either copied
  5675. from the underlying one, or unique to this AnnotatedFromClause.
  5676. See test_selectable->test_annotated_corresponding_column
  5677. """
  5678. ee = self._Annotated__element # type: ignore
  5679. return ee.c # type: ignore