selectable.py 237 KB

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