selectable.py 236 KB

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