selectable.py 232 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955
  1. # sql/selectable.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """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:`tutorial_lateral_correlation` - 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:`tutorial_using_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. joins_implicitly = False
  1344. _traverse_internals = [
  1345. ("element", InternalTraversal.dp_clauseelement),
  1346. ("name", InternalTraversal.dp_anon_name),
  1347. ("_tableval_type", InternalTraversal.dp_type),
  1348. ("_render_derived", InternalTraversal.dp_boolean),
  1349. ("_render_derived_w_types", InternalTraversal.dp_boolean),
  1350. ]
  1351. def _init(
  1352. self,
  1353. selectable,
  1354. name=None,
  1355. table_value_type=None,
  1356. joins_implicitly=False,
  1357. ):
  1358. super(TableValuedAlias, self)._init(selectable, name=name)
  1359. self.joins_implicitly = joins_implicitly
  1360. self._tableval_type = (
  1361. type_api.TABLEVALUE
  1362. if table_value_type is None
  1363. else table_value_type
  1364. )
  1365. @HasMemoized.memoized_attribute
  1366. def column(self):
  1367. """Return a column expression representing this
  1368. :class:`_sql.TableValuedAlias`.
  1369. This accessor is used to implement the
  1370. :meth:`_functions.FunctionElement.column_valued` method. See that
  1371. method for further details.
  1372. E.g.::
  1373. >>> print(select(func.some_func().table_valued("value").column))
  1374. SELECT anon_1 FROM some_func() AS anon_1
  1375. .. seealso::
  1376. :meth:`_functions.FunctionElement.column_valued`
  1377. """
  1378. return TableValuedColumn(self, self._tableval_type)
  1379. def alias(self, name=None):
  1380. """Return a new alias of this :class:`_sql.TableValuedAlias`.
  1381. This creates a distinct FROM object that will be distinguished
  1382. from the original one when used in a SQL statement.
  1383. """
  1384. tva = TableValuedAlias._construct(
  1385. self,
  1386. name=name,
  1387. table_value_type=self._tableval_type,
  1388. joins_implicitly=self.joins_implicitly,
  1389. )
  1390. if self._render_derived:
  1391. tva._render_derived = True
  1392. tva._render_derived_w_types = self._render_derived_w_types
  1393. return tva
  1394. def lateral(self, name=None):
  1395. """Return a new :class:`_sql.TableValuedAlias` with the lateral flag
  1396. set, so that it renders as LATERAL.
  1397. .. seealso::
  1398. :func:`_expression.lateral`
  1399. """
  1400. tva = self.alias(name=name)
  1401. tva._is_lateral = True
  1402. return tva
  1403. def render_derived(self, name=None, with_types=False):
  1404. """Apply "render derived" to this :class:`_sql.TableValuedAlias`.
  1405. This has the effect of the individual column names listed out
  1406. after the alias name in the "AS" sequence, e.g.::
  1407. >>> print(
  1408. ... select(
  1409. ... func.unnest(array(["one", "two", "three"])).
  1410. table_valued("x", with_ordinality="o").render_derived()
  1411. ... )
  1412. ... )
  1413. SELECT anon_1.x, anon_1.o
  1414. FROM unnest(ARRAY[%(param_1)s, %(param_2)s, %(param_3)s]) WITH ORDINALITY AS anon_1(x, o)
  1415. The ``with_types`` keyword will render column types inline within
  1416. the alias expression (this syntax currently applies to the
  1417. PostgreSQL database)::
  1418. >>> print(
  1419. ... select(
  1420. ... func.json_to_recordset(
  1421. ... '[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]'
  1422. ... )
  1423. ... .table_valued(column("a", Integer), column("b", String))
  1424. ... .render_derived(with_types=True)
  1425. ... )
  1426. ... )
  1427. SELECT anon_1.a, anon_1.b FROM json_to_recordset(:json_to_recordset_1)
  1428. AS anon_1(a INTEGER, b VARCHAR)
  1429. :param name: optional string name that will be applied to the alias
  1430. generated. If left as None, a unique anonymizing name will be used.
  1431. :param with_types: if True, the derived columns will include the
  1432. datatype specification with each column. This is a special syntax
  1433. currently known to be required by PostgreSQL for some SQL functions.
  1434. """ # noqa: E501
  1435. # note: don't use the @_generative system here, keep a reference
  1436. # to the original object. otherwise you can have re-use of the
  1437. # python id() of the original which can cause name conflicts if
  1438. # a new anon-name grabs the same identifier as the local anon-name
  1439. # (just saw it happen on CI)
  1440. # construct against original to prevent memory growth
  1441. # for repeated generations
  1442. new_alias = TableValuedAlias._construct(
  1443. self.element,
  1444. name=name,
  1445. table_value_type=self._tableval_type,
  1446. joins_implicitly=self.joins_implicitly,
  1447. )
  1448. new_alias._render_derived = True
  1449. new_alias._render_derived_w_types = with_types
  1450. return new_alias
  1451. class Lateral(AliasedReturnsRows):
  1452. """Represent a LATERAL subquery.
  1453. This object is constructed from the :func:`_expression.lateral` module
  1454. level function as well as the :meth:`_expression.FromClause.lateral`
  1455. method available
  1456. on all :class:`_expression.FromClause` subclasses.
  1457. While LATERAL is part of the SQL standard, currently only more recent
  1458. PostgreSQL versions provide support for this keyword.
  1459. .. versionadded:: 1.1
  1460. .. seealso::
  1461. :ref:`tutorial_lateral_correlation` - overview of usage.
  1462. """
  1463. __visit_name__ = "lateral"
  1464. _is_lateral = True
  1465. inherit_cache = True
  1466. @classmethod
  1467. def _factory(cls, selectable, name=None):
  1468. """Return a :class:`_expression.Lateral` object.
  1469. :class:`_expression.Lateral` is an :class:`_expression.Alias`
  1470. subclass that represents
  1471. a subquery with the LATERAL keyword applied to it.
  1472. The special behavior of a LATERAL subquery is that it appears in the
  1473. FROM clause of an enclosing SELECT, but may correlate to other
  1474. FROM clauses of that SELECT. It is a special case of subquery
  1475. only supported by a small number of backends, currently more recent
  1476. PostgreSQL versions.
  1477. .. versionadded:: 1.1
  1478. .. seealso::
  1479. :ref:`tutorial_lateral_correlation` - overview of usage.
  1480. """
  1481. return coercions.expect(
  1482. roles.FromClauseRole, selectable, explicit_subquery=True
  1483. ).lateral(name=name)
  1484. class TableSample(AliasedReturnsRows):
  1485. """Represent a TABLESAMPLE clause.
  1486. This object is constructed from the :func:`_expression.tablesample` module
  1487. level function as well as the :meth:`_expression.FromClause.tablesample`
  1488. method
  1489. available on all :class:`_expression.FromClause` subclasses.
  1490. .. versionadded:: 1.1
  1491. .. seealso::
  1492. :func:`_expression.tablesample`
  1493. """
  1494. __visit_name__ = "tablesample"
  1495. _traverse_internals = AliasedReturnsRows._traverse_internals + [
  1496. ("sampling", InternalTraversal.dp_clauseelement),
  1497. ("seed", InternalTraversal.dp_clauseelement),
  1498. ]
  1499. @classmethod
  1500. def _factory(cls, selectable, sampling, name=None, seed=None):
  1501. """Return a :class:`_expression.TableSample` object.
  1502. :class:`_expression.TableSample` is an :class:`_expression.Alias`
  1503. subclass that represents
  1504. a table with the TABLESAMPLE clause applied to it.
  1505. :func:`_expression.tablesample`
  1506. is also available from the :class:`_expression.FromClause`
  1507. class via the
  1508. :meth:`_expression.FromClause.tablesample` method.
  1509. The TABLESAMPLE clause allows selecting a randomly selected approximate
  1510. percentage of rows from a table. It supports multiple sampling methods,
  1511. most commonly BERNOULLI and SYSTEM.
  1512. e.g.::
  1513. from sqlalchemy import func
  1514. selectable = people.tablesample(
  1515. func.bernoulli(1),
  1516. name='alias',
  1517. seed=func.random())
  1518. stmt = select(selectable.c.people_id)
  1519. Assuming ``people`` with a column ``people_id``, the above
  1520. statement would render as::
  1521. SELECT alias.people_id FROM
  1522. people AS alias TABLESAMPLE bernoulli(:bernoulli_1)
  1523. REPEATABLE (random())
  1524. .. versionadded:: 1.1
  1525. :param sampling: a ``float`` percentage between 0 and 100 or
  1526. :class:`_functions.Function`.
  1527. :param name: optional alias name
  1528. :param seed: any real-valued SQL expression. When specified, the
  1529. REPEATABLE sub-clause is also rendered.
  1530. """
  1531. return coercions.expect(roles.FromClauseRole, selectable).tablesample(
  1532. sampling, name=name, seed=seed
  1533. )
  1534. @util.preload_module("sqlalchemy.sql.functions")
  1535. def _init(self, selectable, sampling, name=None, seed=None):
  1536. functions = util.preloaded.sql_functions
  1537. if not isinstance(sampling, functions.Function):
  1538. sampling = functions.func.system(sampling)
  1539. self.sampling = sampling
  1540. self.seed = seed
  1541. super(TableSample, self)._init(selectable, name=name)
  1542. def _get_method(self):
  1543. return self.sampling
  1544. class CTE(
  1545. roles.DMLTableRole,
  1546. roles.IsCTERole,
  1547. Generative,
  1548. HasPrefixes,
  1549. HasSuffixes,
  1550. AliasedReturnsRows,
  1551. ):
  1552. """Represent a Common Table Expression.
  1553. The :class:`_expression.CTE` object is obtained using the
  1554. :meth:`_sql.SelectBase.cte` method from any SELECT statement. A less often
  1555. available syntax also allows use of the :meth:`_sql.HasCTE.cte` method
  1556. present on :term:`DML` constructs such as :class:`_sql.Insert`,
  1557. :class:`_sql.Update` and
  1558. :class:`_sql.Delete`. See the :meth:`_sql.HasCTE.cte` method for
  1559. usage details on CTEs.
  1560. .. seealso::
  1561. :ref:`tutorial_subqueries_ctes` - in the 2.0 tutorial
  1562. :meth:`_sql.HasCTE.cte` - examples of calling styles
  1563. """
  1564. __visit_name__ = "cte"
  1565. _traverse_internals = (
  1566. AliasedReturnsRows._traverse_internals
  1567. + [
  1568. ("_cte_alias", InternalTraversal.dp_clauseelement),
  1569. ("_restates", InternalTraversal.dp_clauseelement),
  1570. ("recursive", InternalTraversal.dp_boolean),
  1571. ("nesting", InternalTraversal.dp_boolean),
  1572. ]
  1573. + HasPrefixes._has_prefixes_traverse_internals
  1574. + HasSuffixes._has_suffixes_traverse_internals
  1575. )
  1576. @classmethod
  1577. def _factory(cls, selectable, name=None, recursive=False):
  1578. r"""Return a new :class:`_expression.CTE`,
  1579. or Common Table Expression instance.
  1580. Please see :meth:`_expression.HasCTE.cte` for detail on CTE usage.
  1581. """
  1582. return coercions.expect(roles.HasCTERole, selectable).cte(
  1583. name=name, recursive=recursive
  1584. )
  1585. def _init(
  1586. self,
  1587. selectable,
  1588. name=None,
  1589. recursive=False,
  1590. nesting=False,
  1591. _cte_alias=None,
  1592. _restates=None,
  1593. _prefixes=None,
  1594. _suffixes=None,
  1595. ):
  1596. self.recursive = recursive
  1597. self.nesting = nesting
  1598. self._cte_alias = _cte_alias
  1599. # Keep recursivity reference with union/union_all
  1600. self._restates = _restates
  1601. if _prefixes:
  1602. self._prefixes = _prefixes
  1603. if _suffixes:
  1604. self._suffixes = _suffixes
  1605. super(CTE, self)._init(selectable, name=name)
  1606. def _populate_column_collection(self):
  1607. if self._cte_alias is not None:
  1608. self._cte_alias._generate_fromclause_column_proxies(self)
  1609. else:
  1610. self.element._generate_fromclause_column_proxies(self)
  1611. def alias(self, name=None, flat=False):
  1612. """Return an :class:`_expression.Alias` of this
  1613. :class:`_expression.CTE`.
  1614. This method is a CTE-specific specialization of the
  1615. :meth:`_expression.FromClause.alias` method.
  1616. .. seealso::
  1617. :ref:`tutorial_using_aliases`
  1618. :func:`_expression.alias`
  1619. """
  1620. return CTE._construct(
  1621. self.element,
  1622. name=name,
  1623. recursive=self.recursive,
  1624. nesting=self.nesting,
  1625. _cte_alias=self,
  1626. _prefixes=self._prefixes,
  1627. _suffixes=self._suffixes,
  1628. )
  1629. def union(self, *other):
  1630. r"""Return a new :class:`_expression.CTE` with a SQL ``UNION``
  1631. of the original CTE against the given selectables provided
  1632. as positional arguments.
  1633. :param \*other: one or more elements with which to create a
  1634. UNION.
  1635. .. versionchanged:: 1.4.28 multiple elements are now accepted.
  1636. .. seealso::
  1637. :meth:`_sql.HasCTE.cte` - examples of calling styles
  1638. """
  1639. return CTE._construct(
  1640. self.element.union(*other),
  1641. name=self.name,
  1642. recursive=self.recursive,
  1643. nesting=self.nesting,
  1644. _restates=self,
  1645. _prefixes=self._prefixes,
  1646. _suffixes=self._suffixes,
  1647. )
  1648. def union_all(self, *other):
  1649. r"""Return a new :class:`_expression.CTE` with a SQL ``UNION ALL``
  1650. of the original CTE against the given selectables provided
  1651. as positional arguments.
  1652. :param \*other: one or more elements with which to create a
  1653. UNION.
  1654. .. versionchanged:: 1.4.28 multiple elements are now accepted.
  1655. .. seealso::
  1656. :meth:`_sql.HasCTE.cte` - examples of calling styles
  1657. """
  1658. return CTE._construct(
  1659. self.element.union_all(*other),
  1660. name=self.name,
  1661. recursive=self.recursive,
  1662. nesting=self.nesting,
  1663. _restates=self,
  1664. _prefixes=self._prefixes,
  1665. _suffixes=self._suffixes,
  1666. )
  1667. def _get_reference_cte(self):
  1668. """
  1669. A recursive CTE is updated to attach the recursive part.
  1670. Updated CTEs should still refer to the original CTE.
  1671. This function returns this reference identifier.
  1672. """
  1673. return self._restates if self._restates is not None else self
  1674. class HasCTE(roles.HasCTERole):
  1675. """Mixin that declares a class to include CTE support.
  1676. .. versionadded:: 1.1
  1677. """
  1678. _has_ctes_traverse_internals = [
  1679. ("_independent_ctes", InternalTraversal.dp_clauseelement_list),
  1680. ]
  1681. _independent_ctes = ()
  1682. @_generative
  1683. def add_cte(self, cte):
  1684. """Add a :class:`_sql.CTE` to this statement object that will be
  1685. independently rendered even if not referenced in the statement
  1686. otherwise.
  1687. This feature is useful for the use case of embedding a DML statement
  1688. such as an INSERT or UPDATE as a CTE inline with a primary statement
  1689. that may draw from its results indirectly; while PostgreSQL is known
  1690. to support this usage, it may not be supported by other backends.
  1691. E.g.::
  1692. from sqlalchemy import table, column, select
  1693. t = table('t', column('c1'), column('c2'))
  1694. ins = t.insert().values({"c1": "x", "c2": "y"}).cte()
  1695. stmt = select(t).add_cte(ins)
  1696. Would render::
  1697. WITH anon_1 AS
  1698. (INSERT INTO t (c1, c2) VALUES (:param_1, :param_2))
  1699. SELECT t.c1, t.c2
  1700. FROM t
  1701. Above, the "anon_1" CTE is not referred towards in the SELECT
  1702. statement, however still accomplishes the task of running an INSERT
  1703. statement.
  1704. Similarly in a DML-related context, using the PostgreSQL
  1705. :class:`_postgresql.Insert` construct to generate an "upsert"::
  1706. from sqlalchemy import table, column
  1707. from sqlalchemy.dialects.postgresql import insert
  1708. t = table("t", column("c1"), column("c2"))
  1709. delete_statement_cte = (
  1710. t.delete().where(t.c.c1 < 1).cte("deletions")
  1711. )
  1712. insert_stmt = insert(t).values({"c1": 1, "c2": 2})
  1713. update_statement = insert_stmt.on_conflict_do_update(
  1714. index_elements=[t.c.c1],
  1715. set_={
  1716. "c1": insert_stmt.excluded.c1,
  1717. "c2": insert_stmt.excluded.c2,
  1718. },
  1719. ).add_cte(delete_statement_cte)
  1720. print(update_statement)
  1721. The above statement renders as::
  1722. WITH deletions AS
  1723. (DELETE FROM t WHERE t.c1 < %(c1_1)s)
  1724. INSERT INTO t (c1, c2) VALUES (%(c1)s, %(c2)s)
  1725. ON CONFLICT (c1) DO UPDATE SET c1 = excluded.c1, c2 = excluded.c2
  1726. .. versionadded:: 1.4.21
  1727. """
  1728. cte = coercions.expect(roles.IsCTERole, cte)
  1729. self._independent_ctes += (cte,)
  1730. def cte(self, name=None, recursive=False, nesting=False):
  1731. r"""Return a new :class:`_expression.CTE`,
  1732. or Common Table Expression instance.
  1733. Common table expressions are a SQL standard whereby SELECT
  1734. statements can draw upon secondary statements specified along
  1735. with the primary statement, using a clause called "WITH".
  1736. Special semantics regarding UNION can also be employed to
  1737. allow "recursive" queries, where a SELECT statement can draw
  1738. upon the set of rows that have previously been selected.
  1739. CTEs can also be applied to DML constructs UPDATE, INSERT
  1740. and DELETE on some databases, both as a source of CTE rows
  1741. when combined with RETURNING, as well as a consumer of
  1742. CTE rows.
  1743. .. versionchanged:: 1.1 Added support for UPDATE/INSERT/DELETE as
  1744. CTE, CTEs added to UPDATE/INSERT/DELETE.
  1745. SQLAlchemy detects :class:`_expression.CTE` objects, which are treated
  1746. similarly to :class:`_expression.Alias` objects, as special elements
  1747. to be delivered to the FROM clause of the statement as well
  1748. as to a WITH clause at the top of the statement.
  1749. For special prefixes such as PostgreSQL "MATERIALIZED" and
  1750. "NOT MATERIALIZED", the :meth:`_expression.CTE.prefix_with`
  1751. method may be
  1752. used to establish these.
  1753. .. versionchanged:: 1.3.13 Added support for prefixes.
  1754. In particular - MATERIALIZED and NOT MATERIALIZED.
  1755. :param name: name given to the common table expression. Like
  1756. :meth:`_expression.FromClause.alias`, the name can be left as
  1757. ``None`` in which case an anonymous symbol will be used at query
  1758. compile time.
  1759. :param recursive: if ``True``, will render ``WITH RECURSIVE``.
  1760. A recursive common table expression is intended to be used in
  1761. conjunction with UNION ALL in order to derive rows
  1762. from those already selected.
  1763. :param nesting: if ``True``, will render the CTE locally to the
  1764. actual statement.
  1765. .. versionadded:: 1.4.24
  1766. The following examples include two from PostgreSQL's documentation at
  1767. https://www.postgresql.org/docs/current/static/queries-with.html,
  1768. as well as additional examples.
  1769. Example 1, non recursive::
  1770. from sqlalchemy import (Table, Column, String, Integer,
  1771. MetaData, select, func)
  1772. metadata = MetaData()
  1773. orders = Table('orders', metadata,
  1774. Column('region', String),
  1775. Column('amount', Integer),
  1776. Column('product', String),
  1777. Column('quantity', Integer)
  1778. )
  1779. regional_sales = select(
  1780. orders.c.region,
  1781. func.sum(orders.c.amount).label('total_sales')
  1782. ).group_by(orders.c.region).cte("regional_sales")
  1783. top_regions = select(regional_sales.c.region).\
  1784. where(
  1785. regional_sales.c.total_sales >
  1786. select(
  1787. func.sum(regional_sales.c.total_sales) / 10
  1788. )
  1789. ).cte("top_regions")
  1790. statement = select(
  1791. orders.c.region,
  1792. orders.c.product,
  1793. func.sum(orders.c.quantity).label("product_units"),
  1794. func.sum(orders.c.amount).label("product_sales")
  1795. ).where(orders.c.region.in_(
  1796. select(top_regions.c.region)
  1797. )).group_by(orders.c.region, orders.c.product)
  1798. result = conn.execute(statement).fetchall()
  1799. Example 2, WITH RECURSIVE::
  1800. from sqlalchemy import (Table, Column, String, Integer,
  1801. MetaData, select, func)
  1802. metadata = MetaData()
  1803. parts = Table('parts', metadata,
  1804. Column('part', String),
  1805. Column('sub_part', String),
  1806. Column('quantity', Integer),
  1807. )
  1808. included_parts = select(\
  1809. parts.c.sub_part, parts.c.part, parts.c.quantity\
  1810. ).\
  1811. where(parts.c.part=='our part').\
  1812. cte(recursive=True)
  1813. incl_alias = included_parts.alias()
  1814. parts_alias = parts.alias()
  1815. included_parts = included_parts.union_all(
  1816. select(
  1817. parts_alias.c.sub_part,
  1818. parts_alias.c.part,
  1819. parts_alias.c.quantity
  1820. ).\
  1821. where(parts_alias.c.part==incl_alias.c.sub_part)
  1822. )
  1823. statement = select(
  1824. included_parts.c.sub_part,
  1825. func.sum(included_parts.c.quantity).
  1826. label('total_quantity')
  1827. ).\
  1828. group_by(included_parts.c.sub_part)
  1829. result = conn.execute(statement).fetchall()
  1830. Example 3, an upsert using UPDATE and INSERT with CTEs::
  1831. from datetime import date
  1832. from sqlalchemy import (MetaData, Table, Column, Integer,
  1833. Date, select, literal, and_, exists)
  1834. metadata = MetaData()
  1835. visitors = Table('visitors', metadata,
  1836. Column('product_id', Integer, primary_key=True),
  1837. Column('date', Date, primary_key=True),
  1838. Column('count', Integer),
  1839. )
  1840. # add 5 visitors for the product_id == 1
  1841. product_id = 1
  1842. day = date.today()
  1843. count = 5
  1844. update_cte = (
  1845. visitors.update()
  1846. .where(and_(visitors.c.product_id == product_id,
  1847. visitors.c.date == day))
  1848. .values(count=visitors.c.count + count)
  1849. .returning(literal(1))
  1850. .cte('update_cte')
  1851. )
  1852. upsert = visitors.insert().from_select(
  1853. [visitors.c.product_id, visitors.c.date, visitors.c.count],
  1854. select(literal(product_id), literal(day), literal(count))
  1855. .where(~exists(update_cte.select()))
  1856. )
  1857. connection.execute(upsert)
  1858. Example 4, Nesting CTE (SQLAlchemy 1.4.24 and above)::
  1859. value_a = select(
  1860. literal("root").label("n")
  1861. ).cte("value_a")
  1862. # A nested CTE with the same name as the root one
  1863. value_a_nested = select(
  1864. literal("nesting").label("n")
  1865. ).cte("value_a", nesting=True)
  1866. # Nesting CTEs takes ascendency locally
  1867. # over the CTEs at a higher level
  1868. value_b = select(value_a_nested.c.n).cte("value_b")
  1869. value_ab = select(value_a.c.n.label("a"), value_b.c.n.label("b"))
  1870. The above query will render the second CTE nested inside the first,
  1871. shown with inline parameters below as::
  1872. WITH
  1873. value_a AS
  1874. (SELECT 'root' AS n),
  1875. value_b AS
  1876. (WITH value_a AS
  1877. (SELECT 'nesting' AS n)
  1878. SELECT value_a.n AS n FROM value_a)
  1879. SELECT value_a.n AS a, value_b.n AS b
  1880. FROM value_a, value_b
  1881. Example 5, Non-Linear CTE (SQLAlchemy 1.4.28 and above)::
  1882. edge = Table(
  1883. "edge",
  1884. metadata,
  1885. Column("id", Integer, primary_key=True),
  1886. Column("left", Integer),
  1887. Column("right", Integer),
  1888. )
  1889. root_node = select(literal(1).label("node")).cte(
  1890. "nodes", recursive=True
  1891. )
  1892. left_edge = select(edge.c.left).join(
  1893. root_node, edge.c.right == root_node.c.node
  1894. )
  1895. right_edge = select(edge.c.right).join(
  1896. root_node, edge.c.left == root_node.c.node
  1897. )
  1898. subgraph_cte = root_node.union(left_edge, right_edge)
  1899. subgraph = select(subgraph_cte)
  1900. The above query will render 2 UNIONs inside the recursive CTE::
  1901. WITH RECURSIVE nodes(node) AS (
  1902. SELECT 1 AS node
  1903. UNION
  1904. SELECT edge."left" AS "left"
  1905. FROM edge JOIN nodes ON edge."right" = nodes.node
  1906. UNION
  1907. SELECT edge."right" AS "right"
  1908. FROM edge JOIN nodes ON edge."left" = nodes.node
  1909. )
  1910. SELECT nodes.node FROM nodes
  1911. .. seealso::
  1912. :meth:`_orm.Query.cte` - ORM version of
  1913. :meth:`_expression.HasCTE.cte`.
  1914. """
  1915. return CTE._construct(
  1916. self, name=name, recursive=recursive, nesting=nesting
  1917. )
  1918. class Subquery(AliasedReturnsRows):
  1919. """Represent a subquery of a SELECT.
  1920. A :class:`.Subquery` is created by invoking the
  1921. :meth:`_expression.SelectBase.subquery` method, or for convenience the
  1922. :meth:`_expression.SelectBase.alias` method, on any
  1923. :class:`_expression.SelectBase` subclass
  1924. which includes :class:`_expression.Select`,
  1925. :class:`_expression.CompoundSelect`, and
  1926. :class:`_expression.TextualSelect`. As rendered in a FROM clause,
  1927. it represents the
  1928. body of the SELECT statement inside of parenthesis, followed by the usual
  1929. "AS <somename>" that defines all "alias" objects.
  1930. The :class:`.Subquery` object is very similar to the
  1931. :class:`_expression.Alias`
  1932. object and can be used in an equivalent way. The difference between
  1933. :class:`_expression.Alias` and :class:`.Subquery` is that
  1934. :class:`_expression.Alias` always
  1935. contains a :class:`_expression.FromClause` object whereas
  1936. :class:`.Subquery`
  1937. always contains a :class:`_expression.SelectBase` object.
  1938. .. versionadded:: 1.4 The :class:`.Subquery` class was added which now
  1939. serves the purpose of providing an aliased version of a SELECT
  1940. statement.
  1941. """
  1942. __visit_name__ = "subquery"
  1943. _is_subquery = True
  1944. inherit_cache = True
  1945. @classmethod
  1946. def _factory(cls, selectable, name=None):
  1947. """Return a :class:`.Subquery` object."""
  1948. return coercions.expect(
  1949. roles.SelectStatementRole, selectable
  1950. ).subquery(name=name)
  1951. @util.deprecated(
  1952. "1.4",
  1953. "The :meth:`.Subquery.as_scalar` method, which was previously "
  1954. "``Alias.as_scalar()`` prior to version 1.4, is deprecated and "
  1955. "will be removed in a future release; Please use the "
  1956. ":meth:`_expression.Select.scalar_subquery` method of the "
  1957. ":func:`_expression.select` "
  1958. "construct before constructing a subquery object, or with the ORM "
  1959. "use the :meth:`_query.Query.scalar_subquery` method.",
  1960. )
  1961. def as_scalar(self):
  1962. return self.element.set_label_style(LABEL_STYLE_NONE).scalar_subquery()
  1963. def _execute_on_connection(
  1964. self,
  1965. connection,
  1966. multiparams,
  1967. params,
  1968. execution_options,
  1969. ):
  1970. util.warn_deprecated(
  1971. "Executing a subquery object is deprecated and will raise "
  1972. "ObjectNotExecutableError in an upcoming release. Please "
  1973. "execute the underlying select() statement directly.",
  1974. "1.4",
  1975. )
  1976. return self.element._execute_on_connection(
  1977. connection, multiparams, params, execution_options, _force=True
  1978. )
  1979. class FromGrouping(GroupedElement, FromClause):
  1980. """Represent a grouping of a FROM clause"""
  1981. _traverse_internals = [("element", InternalTraversal.dp_clauseelement)]
  1982. def __init__(self, element):
  1983. self.element = coercions.expect(roles.FromClauseRole, element)
  1984. def _init_collections(self):
  1985. pass
  1986. @property
  1987. def columns(self):
  1988. return self.element.columns
  1989. @property
  1990. def primary_key(self):
  1991. return self.element.primary_key
  1992. @property
  1993. def foreign_keys(self):
  1994. return self.element.foreign_keys
  1995. def is_derived_from(self, element):
  1996. return self.element.is_derived_from(element)
  1997. def alias(self, **kw):
  1998. return FromGrouping(self.element.alias(**kw))
  1999. def _anonymous_fromclause(self, **kw):
  2000. return FromGrouping(self.element._anonymous_fromclause(**kw))
  2001. @property
  2002. def _hide_froms(self):
  2003. return self.element._hide_froms
  2004. @property
  2005. def _from_objects(self):
  2006. return self.element._from_objects
  2007. def __getstate__(self):
  2008. return {"element": self.element}
  2009. def __setstate__(self, state):
  2010. self.element = state["element"]
  2011. class TableClause(roles.DMLTableRole, Immutable, FromClause):
  2012. """Represents a minimal "table" construct.
  2013. This is a lightweight table object that has only a name, a
  2014. collection of columns, which are typically produced
  2015. by the :func:`_expression.column` function, and a schema::
  2016. from sqlalchemy import table, column
  2017. user = table("user",
  2018. column("id"),
  2019. column("name"),
  2020. column("description"),
  2021. )
  2022. The :class:`_expression.TableClause` construct serves as the base for
  2023. the more commonly used :class:`_schema.Table` object, providing
  2024. the usual set of :class:`_expression.FromClause` services including
  2025. the ``.c.`` collection and statement generation methods.
  2026. It does **not** provide all the additional schema-level services
  2027. of :class:`_schema.Table`, including constraints, references to other
  2028. tables, or support for :class:`_schema.MetaData`-level services.
  2029. It's useful
  2030. on its own as an ad-hoc construct used to generate quick SQL
  2031. statements when a more fully fledged :class:`_schema.Table`
  2032. is not on hand.
  2033. """
  2034. __visit_name__ = "table"
  2035. _traverse_internals = [
  2036. (
  2037. "columns",
  2038. InternalTraversal.dp_fromclause_canonical_column_collection,
  2039. ),
  2040. ("name", InternalTraversal.dp_string),
  2041. ("schema", InternalTraversal.dp_string),
  2042. ]
  2043. named_with_column = True
  2044. implicit_returning = False
  2045. """:class:`_expression.TableClause`
  2046. doesn't support having a primary key or column
  2047. -level defaults, so implicit returning doesn't apply."""
  2048. _autoincrement_column = None
  2049. """No PK or default support so no autoincrement column."""
  2050. def __init__(self, name, *columns, **kw):
  2051. """Produce a new :class:`_expression.TableClause`.
  2052. The object returned is an instance of
  2053. :class:`_expression.TableClause`, which
  2054. represents the "syntactical" portion of the schema-level
  2055. :class:`_schema.Table` object.
  2056. It may be used to construct lightweight table constructs.
  2057. .. versionchanged:: 1.0.0 :func:`_expression.table` can now
  2058. be imported from the plain ``sqlalchemy`` namespace like any
  2059. other SQL element.
  2060. :param name: Name of the table.
  2061. :param columns: A collection of :func:`_expression.column` constructs.
  2062. :param schema: The schema name for this table.
  2063. .. versionadded:: 1.3.18 :func:`_expression.table` can now
  2064. accept a ``schema`` argument.
  2065. """
  2066. super(TableClause, self).__init__()
  2067. self.name = name
  2068. self._columns = DedupeColumnCollection()
  2069. self.primary_key = ColumnSet()
  2070. self.foreign_keys = set()
  2071. for c in columns:
  2072. self.append_column(c)
  2073. schema = kw.pop("schema", None)
  2074. if schema is not None:
  2075. self.schema = schema
  2076. if self.schema is not None:
  2077. self.fullname = "%s.%s" % (self.schema, self.name)
  2078. else:
  2079. self.fullname = self.name
  2080. if kw:
  2081. raise exc.ArgumentError("Unsupported argument(s): %s" % list(kw))
  2082. def __str__(self):
  2083. if self.schema is not None:
  2084. return self.schema + "." + self.name
  2085. else:
  2086. return self.name
  2087. def _refresh_for_new_column(self, column):
  2088. pass
  2089. def _init_collections(self):
  2090. pass
  2091. @util.memoized_property
  2092. def description(self):
  2093. if util.py3k:
  2094. return self.name
  2095. else:
  2096. return self.name.encode("ascii", "backslashreplace")
  2097. def append_column(self, c, **kw):
  2098. existing = c.table
  2099. if existing is not None and existing is not self:
  2100. raise exc.ArgumentError(
  2101. "column object '%s' already assigned to table '%s'"
  2102. % (c.key, existing)
  2103. )
  2104. self._columns.add(c)
  2105. c.table = self
  2106. @util.preload_module("sqlalchemy.sql.dml")
  2107. def insert(self, values=None, inline=False, **kwargs):
  2108. """Generate an :func:`_expression.insert` construct against this
  2109. :class:`_expression.TableClause`.
  2110. E.g.::
  2111. table.insert().values(name='foo')
  2112. See :func:`_expression.insert` for argument and usage information.
  2113. """
  2114. return util.preloaded.sql_dml.Insert(
  2115. self, values=values, inline=inline, **kwargs
  2116. )
  2117. @util.preload_module("sqlalchemy.sql.dml")
  2118. def update(self, whereclause=None, values=None, inline=False, **kwargs):
  2119. """Generate an :func:`_expression.update` construct against this
  2120. :class:`_expression.TableClause`.
  2121. E.g.::
  2122. table.update().where(table.c.id==7).values(name='foo')
  2123. See :func:`_expression.update` for argument and usage information.
  2124. """
  2125. return util.preloaded.sql_dml.Update(
  2126. self,
  2127. whereclause=whereclause,
  2128. values=values,
  2129. inline=inline,
  2130. **kwargs
  2131. )
  2132. @util.preload_module("sqlalchemy.sql.dml")
  2133. def delete(self, whereclause=None, **kwargs):
  2134. """Generate a :func:`_expression.delete` construct against this
  2135. :class:`_expression.TableClause`.
  2136. E.g.::
  2137. table.delete().where(table.c.id==7)
  2138. See :func:`_expression.delete` for argument and usage information.
  2139. """
  2140. return util.preloaded.sql_dml.Delete(self, whereclause, **kwargs)
  2141. @property
  2142. def _from_objects(self):
  2143. return [self]
  2144. class ForUpdateArg(ClauseElement):
  2145. _traverse_internals = [
  2146. ("of", InternalTraversal.dp_clauseelement_list),
  2147. ("nowait", InternalTraversal.dp_boolean),
  2148. ("read", InternalTraversal.dp_boolean),
  2149. ("skip_locked", InternalTraversal.dp_boolean),
  2150. ("key_share", InternalTraversal.dp_boolean),
  2151. ]
  2152. @classmethod
  2153. def _from_argument(cls, with_for_update):
  2154. if isinstance(with_for_update, ForUpdateArg):
  2155. return with_for_update
  2156. elif with_for_update in (None, False):
  2157. return None
  2158. elif with_for_update is True:
  2159. return ForUpdateArg()
  2160. else:
  2161. return ForUpdateArg(**with_for_update)
  2162. def __eq__(self, other):
  2163. return (
  2164. isinstance(other, ForUpdateArg)
  2165. and other.nowait == self.nowait
  2166. and other.read == self.read
  2167. and other.skip_locked == self.skip_locked
  2168. and other.key_share == self.key_share
  2169. and other.of is self.of
  2170. )
  2171. def __ne__(self, other):
  2172. return not self.__eq__(other)
  2173. def __hash__(self):
  2174. return id(self)
  2175. def __init__(
  2176. self,
  2177. nowait=False,
  2178. read=False,
  2179. of=None,
  2180. skip_locked=False,
  2181. key_share=False,
  2182. ):
  2183. """Represents arguments specified to
  2184. :meth:`_expression.Select.for_update`.
  2185. """
  2186. self.nowait = nowait
  2187. self.read = read
  2188. self.skip_locked = skip_locked
  2189. self.key_share = key_share
  2190. if of is not None:
  2191. self.of = [
  2192. coercions.expect(roles.ColumnsClauseRole, elem)
  2193. for elem in util.to_list(of)
  2194. ]
  2195. else:
  2196. self.of = None
  2197. class Values(Generative, FromClause):
  2198. """Represent a ``VALUES`` construct that can be used as a FROM element
  2199. in a statement.
  2200. The :class:`_expression.Values` object is created from the
  2201. :func:`_expression.values` function.
  2202. .. versionadded:: 1.4
  2203. """
  2204. named_with_column = True
  2205. __visit_name__ = "values"
  2206. _data = ()
  2207. _traverse_internals = [
  2208. ("_column_args", InternalTraversal.dp_clauseelement_list),
  2209. ("_data", InternalTraversal.dp_dml_multi_values),
  2210. ("name", InternalTraversal.dp_string),
  2211. ("literal_binds", InternalTraversal.dp_boolean),
  2212. ]
  2213. def __init__(self, *columns, **kw):
  2214. r"""Construct a :class:`_expression.Values` construct.
  2215. The column expressions and the actual data for
  2216. :class:`_expression.Values` are given in two separate steps. The
  2217. constructor receives the column expressions typically as
  2218. :func:`_expression.column` constructs,
  2219. and the data is then passed via the
  2220. :meth:`_expression.Values.data` method as a list,
  2221. which can be called multiple
  2222. times to add more data, e.g.::
  2223. from sqlalchemy import column
  2224. from sqlalchemy import values
  2225. value_expr = values(
  2226. column('id', Integer),
  2227. column('name', String),
  2228. name="my_values"
  2229. ).data(
  2230. [(1, 'name1'), (2, 'name2'), (3, 'name3')]
  2231. )
  2232. :param \*columns: column expressions, typically composed using
  2233. :func:`_expression.column` objects.
  2234. :param name: the name for this VALUES construct. If omitted, the
  2235. VALUES construct will be unnamed in a SQL expression. Different
  2236. backends may have different requirements here.
  2237. :param literal_binds: Defaults to False. Whether or not to render
  2238. the data values inline in the SQL output, rather than using bound
  2239. parameters.
  2240. """
  2241. super(Values, self).__init__()
  2242. self._column_args = columns
  2243. self.name = kw.pop("name", None)
  2244. self.literal_binds = kw.pop("literal_binds", False)
  2245. self.named_with_column = self.name is not None
  2246. @property
  2247. def _column_types(self):
  2248. return [col.type for col in self._column_args]
  2249. @_generative
  2250. def alias(self, name, **kw):
  2251. """Return a new :class:`_expression.Values`
  2252. construct that is a copy of this
  2253. one with the given name.
  2254. This method is a VALUES-specific specialization of the
  2255. :meth:`_expression.FromClause.alias` method.
  2256. .. seealso::
  2257. :ref:`tutorial_using_aliases`
  2258. :func:`_expression.alias`
  2259. """
  2260. self.name = name
  2261. self.named_with_column = self.name is not None
  2262. @_generative
  2263. def lateral(self, name=None):
  2264. """Return a new :class:`_expression.Values` with the lateral flag set,
  2265. so that
  2266. it renders as LATERAL.
  2267. .. seealso::
  2268. :func:`_expression.lateral`
  2269. """
  2270. self._is_lateral = True
  2271. if name is not None:
  2272. self.name = name
  2273. @_generative
  2274. def data(self, values):
  2275. """Return a new :class:`_expression.Values` construct,
  2276. adding the given data
  2277. to the data list.
  2278. E.g.::
  2279. my_values = my_values.data([(1, 'value 1'), (2, 'value2')])
  2280. :param values: a sequence (i.e. list) of tuples that map to the
  2281. column expressions given in the :class:`_expression.Values`
  2282. constructor.
  2283. """
  2284. self._data += (values,)
  2285. def _populate_column_collection(self):
  2286. for c in self._column_args:
  2287. self._columns.add(c)
  2288. c.table = self
  2289. @property
  2290. def _from_objects(self):
  2291. return [self]
  2292. class SelectBase(
  2293. roles.SelectStatementRole,
  2294. roles.DMLSelectRole,
  2295. roles.CompoundElementRole,
  2296. roles.InElementRole,
  2297. HasCTE,
  2298. Executable,
  2299. SupportsCloneAnnotations,
  2300. Selectable,
  2301. ):
  2302. """Base class for SELECT statements.
  2303. This includes :class:`_expression.Select`,
  2304. :class:`_expression.CompoundSelect` and
  2305. :class:`_expression.TextualSelect`.
  2306. """
  2307. _is_select_statement = True
  2308. is_select = True
  2309. def _generate_fromclause_column_proxies(self, fromclause):
  2310. raise NotImplementedError()
  2311. def _refresh_for_new_column(self, column):
  2312. self._reset_memoizations()
  2313. @property
  2314. def selected_columns(self):
  2315. """A :class:`_expression.ColumnCollection`
  2316. representing the columns that
  2317. this SELECT statement or similar construct returns in its result set.
  2318. This collection differs from the :attr:`_expression.FromClause.columns`
  2319. collection of a :class:`_expression.FromClause` in that the columns
  2320. within this collection cannot be directly nested inside another SELECT
  2321. statement; a subquery must be applied first which provides for the
  2322. necessary parenthesization required by SQL.
  2323. .. note::
  2324. The :attr:`_sql.SelectBase.selected_columns` collection does not
  2325. include expressions established in the columns clause using the
  2326. :func:`_sql.text` construct; these are silently omitted from the
  2327. collection. To use plain textual column expressions inside of a
  2328. :class:`_sql.Select` construct, use the :func:`_sql.literal_column`
  2329. construct.
  2330. .. seealso::
  2331. :attr:`_sql.Select.selected_columns`
  2332. .. versionadded:: 1.4
  2333. """
  2334. raise NotImplementedError()
  2335. @property
  2336. def _all_selected_columns(self):
  2337. """A sequence of expressions that correspond to what is rendered
  2338. in the columns clause, including :class:`_sql.TextClause`
  2339. constructs.
  2340. .. versionadded:: 1.4.12
  2341. .. seealso::
  2342. :attr:`_sql.SelectBase.exported_columns`
  2343. """
  2344. raise NotImplementedError()
  2345. @property
  2346. def exported_columns(self):
  2347. """A :class:`_expression.ColumnCollection`
  2348. that represents the "exported"
  2349. columns of this :class:`_expression.Selectable`, not including
  2350. :class:`_sql.TextClause` constructs.
  2351. The "exported" columns for a :class:`_expression.SelectBase`
  2352. object are synonymous
  2353. with the :attr:`_expression.SelectBase.selected_columns` collection.
  2354. .. versionadded:: 1.4
  2355. .. seealso::
  2356. :attr:`_expression.Select.exported_columns`
  2357. :attr:`_expression.Selectable.exported_columns`
  2358. :attr:`_expression.FromClause.exported_columns`
  2359. """
  2360. return self.selected_columns
  2361. @property
  2362. @util.deprecated(
  2363. "1.4",
  2364. "The :attr:`_expression.SelectBase.c` and "
  2365. ":attr:`_expression.SelectBase.columns` attributes "
  2366. "are deprecated and will be removed in a future release; these "
  2367. "attributes implicitly create a subquery that should be explicit. "
  2368. "Please call :meth:`_expression.SelectBase.subquery` "
  2369. "first in order to create "
  2370. "a subquery, which then contains this attribute. To access the "
  2371. "columns that this SELECT object SELECTs "
  2372. "from, use the :attr:`_expression.SelectBase.selected_columns` "
  2373. "attribute.",
  2374. )
  2375. def c(self):
  2376. return self._implicit_subquery.columns
  2377. @property
  2378. def columns(self):
  2379. return self.c
  2380. @util.deprecated(
  2381. "1.4",
  2382. "The :meth:`_expression.SelectBase.select` method is deprecated "
  2383. "and will be removed in a future release; this method implicitly "
  2384. "creates a subquery that should be explicit. "
  2385. "Please call :meth:`_expression.SelectBase.subquery` "
  2386. "first in order to create "
  2387. "a subquery, which then can be selected.",
  2388. )
  2389. def select(self, *arg, **kw):
  2390. return self._implicit_subquery.select(*arg, **kw)
  2391. @HasMemoized.memoized_attribute
  2392. def _implicit_subquery(self):
  2393. return self.subquery()
  2394. @util.deprecated(
  2395. "1.4",
  2396. "The :meth:`_expression.SelectBase.as_scalar` "
  2397. "method is deprecated and will be "
  2398. "removed in a future release. Please refer to "
  2399. ":meth:`_expression.SelectBase.scalar_subquery`.",
  2400. )
  2401. def as_scalar(self):
  2402. return self.scalar_subquery()
  2403. def exists(self):
  2404. """Return an :class:`_sql.Exists` representation of this selectable,
  2405. which can be used as a column expression.
  2406. The returned object is an instance of :class:`_sql.Exists`.
  2407. .. seealso::
  2408. :func:`_sql.exists`
  2409. :ref:`tutorial_exists` - in the :term:`2.0 style` tutorial.
  2410. .. versionadded:: 1.4
  2411. """
  2412. return Exists(self)
  2413. def scalar_subquery(self):
  2414. """Return a 'scalar' representation of this selectable, which can be
  2415. used as a column expression.
  2416. The returned object is an instance of :class:`_sql.ScalarSelect`.
  2417. Typically, a select statement which has only one column in its columns
  2418. clause is eligible to be used as a scalar expression. The scalar
  2419. subquery can then be used in the WHERE clause or columns clause of
  2420. an enclosing SELECT.
  2421. Note that the scalar subquery differentiates from the FROM-level
  2422. subquery that can be produced using the
  2423. :meth:`_expression.SelectBase.subquery`
  2424. method.
  2425. .. versionchanged: 1.4 - the ``.as_scalar()`` method was renamed to
  2426. :meth:`_expression.SelectBase.scalar_subquery`.
  2427. .. seealso::
  2428. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  2429. """
  2430. if self._label_style is not LABEL_STYLE_NONE:
  2431. self = self.set_label_style(LABEL_STYLE_NONE)
  2432. return ScalarSelect(self)
  2433. def label(self, name):
  2434. """Return a 'scalar' representation of this selectable, embedded as a
  2435. subquery with a label.
  2436. .. seealso::
  2437. :meth:`_expression.SelectBase.as_scalar`.
  2438. """
  2439. return self.scalar_subquery().label(name)
  2440. def lateral(self, name=None):
  2441. """Return a LATERAL alias of this :class:`_expression.Selectable`.
  2442. The return value is the :class:`_expression.Lateral` construct also
  2443. provided by the top-level :func:`_expression.lateral` function.
  2444. .. versionadded:: 1.1
  2445. .. seealso::
  2446. :ref:`tutorial_lateral_correlation` - overview of usage.
  2447. """
  2448. return Lateral._factory(self, name)
  2449. @property
  2450. def _from_objects(self):
  2451. return [self]
  2452. def subquery(self, name=None):
  2453. """Return a subquery of this :class:`_expression.SelectBase`.
  2454. A subquery is from a SQL perspective a parenthesized, named
  2455. construct that can be placed in the FROM clause of another
  2456. SELECT statement.
  2457. Given a SELECT statement such as::
  2458. stmt = select(table.c.id, table.c.name)
  2459. The above statement might look like::
  2460. SELECT table.id, table.name FROM table
  2461. The subquery form by itself renders the same way, however when
  2462. embedded into the FROM clause of another SELECT statement, it becomes
  2463. a named sub-element::
  2464. subq = stmt.subquery()
  2465. new_stmt = select(subq)
  2466. The above renders as::
  2467. SELECT anon_1.id, anon_1.name
  2468. FROM (SELECT table.id, table.name FROM table) AS anon_1
  2469. Historically, :meth:`_expression.SelectBase.subquery`
  2470. is equivalent to calling
  2471. the :meth:`_expression.FromClause.alias`
  2472. method on a FROM object; however,
  2473. as a :class:`_expression.SelectBase`
  2474. object is not directly FROM object,
  2475. the :meth:`_expression.SelectBase.subquery`
  2476. method provides clearer semantics.
  2477. .. versionadded:: 1.4
  2478. """
  2479. return Subquery._construct(self._ensure_disambiguated_names(), name)
  2480. def _ensure_disambiguated_names(self):
  2481. """Ensure that the names generated by this selectbase will be
  2482. disambiguated in some way, if possible.
  2483. """
  2484. raise NotImplementedError()
  2485. def alias(self, name=None, flat=False):
  2486. """Return a named subquery against this
  2487. :class:`_expression.SelectBase`.
  2488. For a :class:`_expression.SelectBase` (as opposed to a
  2489. :class:`_expression.FromClause`),
  2490. this returns a :class:`.Subquery` object which behaves mostly the
  2491. same as the :class:`_expression.Alias` object that is used with a
  2492. :class:`_expression.FromClause`.
  2493. .. versionchanged:: 1.4 The :meth:`_expression.SelectBase.alias`
  2494. method is now
  2495. a synonym for the :meth:`_expression.SelectBase.subquery` method.
  2496. """
  2497. return self.subquery(name=name)
  2498. class SelectStatementGrouping(GroupedElement, SelectBase):
  2499. """Represent a grouping of a :class:`_expression.SelectBase`.
  2500. This differs from :class:`.Subquery` in that we are still
  2501. an "inner" SELECT statement, this is strictly for grouping inside of
  2502. compound selects.
  2503. """
  2504. __visit_name__ = "select_statement_grouping"
  2505. _traverse_internals = [("element", InternalTraversal.dp_clauseelement)]
  2506. _is_select_container = True
  2507. def __init__(self, element):
  2508. self.element = coercions.expect(roles.SelectStatementRole, element)
  2509. def _ensure_disambiguated_names(self):
  2510. new_element = self.element._ensure_disambiguated_names()
  2511. if new_element is not self.element:
  2512. return SelectStatementGrouping(new_element)
  2513. else:
  2514. return self
  2515. def get_label_style(self):
  2516. return self._label_style
  2517. def set_label_style(self, label_style):
  2518. return SelectStatementGrouping(
  2519. self.element.set_label_style(label_style)
  2520. )
  2521. @property
  2522. def _label_style(self):
  2523. return self.element._label_style
  2524. @property
  2525. def select_statement(self):
  2526. return self.element
  2527. def self_group(self, against=None):
  2528. return self
  2529. def _generate_columns_plus_names(self, anon_for_dupe_key):
  2530. return self.element._generate_columns_plus_names(anon_for_dupe_key)
  2531. def _generate_fromclause_column_proxies(self, subquery):
  2532. self.element._generate_fromclause_column_proxies(subquery)
  2533. def _generate_proxy_for_new_column(self, column, subquery):
  2534. return self.element._generate_proxy_for_new_column(subquery)
  2535. @property
  2536. def _all_selected_columns(self):
  2537. return self.element._all_selected_columns
  2538. @property
  2539. def selected_columns(self):
  2540. """A :class:`_expression.ColumnCollection`
  2541. representing the columns that
  2542. the embedded SELECT statement returns in its result set, not including
  2543. :class:`_sql.TextClause` constructs.
  2544. .. versionadded:: 1.4
  2545. .. seealso::
  2546. :attr:`_sql.Select.selected_columns`
  2547. """
  2548. return self.element.selected_columns
  2549. @property
  2550. def _from_objects(self):
  2551. return self.element._from_objects
  2552. class DeprecatedSelectBaseGenerations(object):
  2553. """A collection of methods available on :class:`_sql.Select` and
  2554. :class:`_sql.CompoundSelect`, these are all **deprecated** methods as they
  2555. modify the object in-place.
  2556. """
  2557. @util.deprecated(
  2558. "1.4",
  2559. "The :meth:`_expression.GenerativeSelect.append_order_by` "
  2560. "method is deprecated "
  2561. "and will be removed in a future release. Use the generative method "
  2562. ":meth:`_expression.GenerativeSelect.order_by`.",
  2563. )
  2564. def append_order_by(self, *clauses):
  2565. """Append the given ORDER BY criterion applied to this selectable.
  2566. The criterion will be appended to any pre-existing ORDER BY criterion.
  2567. This is an **in-place** mutation method; the
  2568. :meth:`_expression.GenerativeSelect.order_by` method is preferred,
  2569. as it
  2570. provides standard :term:`method chaining`.
  2571. .. seealso::
  2572. :meth:`_expression.GenerativeSelect.order_by`
  2573. """
  2574. self.order_by.non_generative(self, *clauses)
  2575. @util.deprecated(
  2576. "1.4",
  2577. "The :meth:`_expression.GenerativeSelect.append_group_by` "
  2578. "method is deprecated "
  2579. "and will be removed in a future release. Use the generative method "
  2580. ":meth:`_expression.GenerativeSelect.group_by`.",
  2581. )
  2582. def append_group_by(self, *clauses):
  2583. """Append the given GROUP BY criterion applied to this selectable.
  2584. The criterion will be appended to any pre-existing GROUP BY criterion.
  2585. This is an **in-place** mutation method; the
  2586. :meth:`_expression.GenerativeSelect.group_by` method is preferred,
  2587. as it
  2588. provides standard :term:`method chaining`.
  2589. """
  2590. self.group_by.non_generative(self, *clauses)
  2591. class GenerativeSelect(DeprecatedSelectBaseGenerations, SelectBase):
  2592. """Base class for SELECT statements where additional elements can be
  2593. added.
  2594. This serves as the base for :class:`_expression.Select` and
  2595. :class:`_expression.CompoundSelect`
  2596. where elements such as ORDER BY, GROUP BY can be added and column
  2597. rendering can be controlled. Compare to
  2598. :class:`_expression.TextualSelect`, which,
  2599. while it subclasses :class:`_expression.SelectBase`
  2600. and is also a SELECT construct,
  2601. represents a fixed textual string which cannot be altered at this level,
  2602. only wrapped as a subquery.
  2603. """
  2604. _order_by_clauses = ()
  2605. _group_by_clauses = ()
  2606. _limit_clause = None
  2607. _offset_clause = None
  2608. _fetch_clause = None
  2609. _fetch_clause_options = None
  2610. _for_update_arg = None
  2611. @util.deprecated_params(
  2612. bind=(
  2613. "2.0",
  2614. "The :paramref:`_sql.select.bind` argument is deprecated and "
  2615. "will be removed in SQLAlchemy 2.0.",
  2616. ),
  2617. )
  2618. def __init__(
  2619. self,
  2620. _label_style=LABEL_STYLE_DEFAULT,
  2621. use_labels=False,
  2622. limit=None,
  2623. offset=None,
  2624. order_by=None,
  2625. group_by=None,
  2626. bind=None,
  2627. ):
  2628. if use_labels:
  2629. if util.SQLALCHEMY_WARN_20:
  2630. util.warn_deprecated_20(
  2631. "The use_labels=True keyword argument to GenerativeSelect "
  2632. "is deprecated and will be removed in version 2.0. Please "
  2633. "use "
  2634. "select.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) "
  2635. "if you need to replicate this legacy behavior.",
  2636. stacklevel=4,
  2637. )
  2638. _label_style = LABEL_STYLE_TABLENAME_PLUS_COL
  2639. self._label_style = _label_style
  2640. if limit is not None:
  2641. self.limit.non_generative(self, limit)
  2642. if offset is not None:
  2643. self.offset.non_generative(self, offset)
  2644. if order_by is not None:
  2645. self.order_by.non_generative(self, *util.to_list(order_by))
  2646. if group_by is not None:
  2647. self.group_by.non_generative(self, *util.to_list(group_by))
  2648. self._bind = bind
  2649. @_generative
  2650. def with_for_update(
  2651. self,
  2652. nowait=False,
  2653. read=False,
  2654. of=None,
  2655. skip_locked=False,
  2656. key_share=False,
  2657. ):
  2658. """Specify a ``FOR UPDATE`` clause for this
  2659. :class:`_expression.GenerativeSelect`.
  2660. E.g.::
  2661. stmt = select(table).with_for_update(nowait=True)
  2662. On a database like PostgreSQL or Oracle, the above would render a
  2663. statement like::
  2664. SELECT table.a, table.b FROM table FOR UPDATE NOWAIT
  2665. on other backends, the ``nowait`` option is ignored and instead
  2666. would produce::
  2667. SELECT table.a, table.b FROM table FOR UPDATE
  2668. When called with no arguments, the statement will render with
  2669. the suffix ``FOR UPDATE``. Additional arguments can then be
  2670. provided which allow for common database-specific
  2671. variants.
  2672. :param nowait: boolean; will render ``FOR UPDATE NOWAIT`` on Oracle
  2673. and PostgreSQL dialects.
  2674. :param read: boolean; will render ``LOCK IN SHARE MODE`` on MySQL,
  2675. ``FOR SHARE`` on PostgreSQL. On PostgreSQL, when combined with
  2676. ``nowait``, will render ``FOR SHARE NOWAIT``.
  2677. :param of: SQL expression or list of SQL expression elements
  2678. (typically :class:`_schema.Column`
  2679. objects or a compatible expression) which
  2680. will render into a ``FOR UPDATE OF`` clause; supported by PostgreSQL
  2681. and Oracle. May render as a table or as a column depending on
  2682. backend.
  2683. :param skip_locked: boolean, will render ``FOR UPDATE SKIP LOCKED``
  2684. on Oracle and PostgreSQL dialects or ``FOR SHARE SKIP LOCKED`` if
  2685. ``read=True`` is also specified.
  2686. :param key_share: boolean, will render ``FOR NO KEY UPDATE``,
  2687. or if combined with ``read=True`` will render ``FOR KEY SHARE``,
  2688. on the PostgreSQL dialect.
  2689. """
  2690. self._for_update_arg = ForUpdateArg(
  2691. nowait=nowait,
  2692. read=read,
  2693. of=of,
  2694. skip_locked=skip_locked,
  2695. key_share=key_share,
  2696. )
  2697. def get_label_style(self):
  2698. """
  2699. Retrieve the current label style.
  2700. .. versionadded:: 1.4
  2701. """
  2702. return self._label_style
  2703. def set_label_style(self, style):
  2704. """Return a new selectable with the specified label style.
  2705. There are three "label styles" available,
  2706. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`,
  2707. :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`, and
  2708. :data:`_sql.LABEL_STYLE_NONE`. The default style is
  2709. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`.
  2710. In modern SQLAlchemy, there is not generally a need to change the
  2711. labeling style, as per-expression labels are more effectively used by
  2712. making use of the :meth:`_sql.ColumnElement.label` method. In past
  2713. versions, :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL` was used to
  2714. disambiguate same-named columns from different tables, aliases, or
  2715. subqueries; the newer :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY` now
  2716. applies labels only to names that conflict with an existing name so
  2717. that the impact of this labeling is minimal.
  2718. The rationale for disambiguation is mostly so that all column
  2719. expressions are available from a given :attr:`_sql.FromClause.c`
  2720. collection when a subquery is created.
  2721. .. versionadded:: 1.4 - the
  2722. :meth:`_sql.GenerativeSelect.set_label_style` method replaces the
  2723. previous combination of ``.apply_labels()``, ``.with_labels()`` and
  2724. ``use_labels=True`` methods and/or parameters.
  2725. .. seealso::
  2726. :data:`_sql.LABEL_STYLE_DISAMBIGUATE_ONLY`
  2727. :data:`_sql.LABEL_STYLE_TABLENAME_PLUS_COL`
  2728. :data:`_sql.LABEL_STYLE_NONE`
  2729. :data:`_sql.LABEL_STYLE_DEFAULT`
  2730. """
  2731. if self._label_style is not style:
  2732. self = self._generate()
  2733. self._label_style = style
  2734. return self
  2735. @util.deprecated_20(
  2736. ":meth:`_sql.GenerativeSelect.apply_labels`",
  2737. alternative="Use set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) "
  2738. "instead.",
  2739. )
  2740. def apply_labels(self):
  2741. return self.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
  2742. @property
  2743. def _group_by_clause(self):
  2744. """ClauseList access to group_by_clauses for legacy dialects"""
  2745. return ClauseList._construct_raw(
  2746. operators.comma_op, self._group_by_clauses
  2747. )
  2748. @property
  2749. def _order_by_clause(self):
  2750. """ClauseList access to order_by_clauses for legacy dialects"""
  2751. return ClauseList._construct_raw(
  2752. operators.comma_op, self._order_by_clauses
  2753. )
  2754. def _offset_or_limit_clause(self, element, name=None, type_=None):
  2755. """Convert the given value to an "offset or limit" clause.
  2756. This handles incoming integers and converts to an expression; if
  2757. an expression is already given, it is passed through.
  2758. """
  2759. return coercions.expect(
  2760. roles.LimitOffsetRole, element, name=name, type_=type_
  2761. )
  2762. def _offset_or_limit_clause_asint(self, clause, attrname):
  2763. """Convert the "offset or limit" clause of a select construct to an
  2764. integer.
  2765. This is only possible if the value is stored as a simple bound
  2766. parameter. Otherwise, a compilation error is raised.
  2767. """
  2768. if clause is None:
  2769. return None
  2770. try:
  2771. value = clause._limit_offset_value
  2772. except AttributeError as err:
  2773. util.raise_(
  2774. exc.CompileError(
  2775. "This SELECT structure does not use a simple "
  2776. "integer value for %s" % attrname
  2777. ),
  2778. replace_context=err,
  2779. )
  2780. else:
  2781. return util.asint(value)
  2782. @property
  2783. def _limit(self):
  2784. """Get an integer value for the limit. This should only be used
  2785. by code that cannot support a limit as a BindParameter or
  2786. other custom clause as it will throw an exception if the limit
  2787. isn't currently set to an integer.
  2788. """
  2789. return self._offset_or_limit_clause_asint(self._limit_clause, "limit")
  2790. def _simple_int_clause(self, clause):
  2791. """True if the clause is a simple integer, False
  2792. if it is not present or is a SQL expression.
  2793. """
  2794. return isinstance(clause, _OffsetLimitParam)
  2795. @property
  2796. def _offset(self):
  2797. """Get an integer value for the offset. This should only be used
  2798. by code that cannot support an offset as a BindParameter or
  2799. other custom clause as it will throw an exception if the
  2800. offset isn't currently set to an integer.
  2801. """
  2802. return self._offset_or_limit_clause_asint(
  2803. self._offset_clause, "offset"
  2804. )
  2805. @property
  2806. def _has_row_limiting_clause(self):
  2807. return (
  2808. self._limit_clause is not None
  2809. or self._offset_clause is not None
  2810. or self._fetch_clause is not None
  2811. )
  2812. @_generative
  2813. def limit(self, limit):
  2814. """Return a new selectable with the given LIMIT criterion
  2815. applied.
  2816. This is a numerical value which usually renders as a ``LIMIT``
  2817. expression in the resulting select. Backends that don't
  2818. support ``LIMIT`` will attempt to provide similar
  2819. functionality.
  2820. .. note::
  2821. The :meth:`_sql.GenerativeSelect.limit` method will replace
  2822. any clause applied with :meth:`_sql.GenerativeSelect.fetch`.
  2823. .. versionchanged:: 1.0.0 - :meth:`_expression.Select.limit` can now
  2824. accept arbitrary SQL expressions as well as integer values.
  2825. :param limit: an integer LIMIT parameter, or a SQL expression
  2826. that provides an integer result. Pass ``None`` to reset it.
  2827. .. seealso::
  2828. :meth:`_sql.GenerativeSelect.fetch`
  2829. :meth:`_sql.GenerativeSelect.offset`
  2830. """
  2831. self._fetch_clause = self._fetch_clause_options = None
  2832. self._limit_clause = self._offset_or_limit_clause(limit)
  2833. @_generative
  2834. def fetch(self, count, with_ties=False, percent=False):
  2835. """Return a new selectable with the given FETCH FIRST criterion
  2836. applied.
  2837. This is a numeric value which usually renders as
  2838. ``FETCH {FIRST | NEXT} [ count ] {ROW | ROWS} {ONLY | WITH TIES}``
  2839. expression in the resulting select. This functionality is
  2840. is currently implemented for Oracle, PostgreSQL, MSSQL.
  2841. Use :meth:`_sql.GenerativeSelect.offset` to specify the offset.
  2842. .. note::
  2843. The :meth:`_sql.GenerativeSelect.fetch` method will replace
  2844. any clause applied with :meth:`_sql.GenerativeSelect.limit`.
  2845. .. versionadded:: 1.4
  2846. :param count: an integer COUNT parameter, or a SQL expression
  2847. that provides an integer result. When ``percent=True`` this will
  2848. represent the percentage of rows to return, not the absolute value.
  2849. Pass ``None`` to reset it.
  2850. :param with_ties: When ``True``, the WITH TIES option is used
  2851. to return any additional rows that tie for the last place in the
  2852. result set according to the ``ORDER BY`` clause. The
  2853. ``ORDER BY`` may be mandatory in this case. Defaults to ``False``
  2854. :param percent: When ``True``, ``count`` represents the percentage
  2855. of the total number of selected rows to return. Defaults to ``False``
  2856. .. seealso::
  2857. :meth:`_sql.GenerativeSelect.limit`
  2858. :meth:`_sql.GenerativeSelect.offset`
  2859. """
  2860. self._limit_clause = None
  2861. if count is None:
  2862. self._fetch_clause = self._fetch_clause_options = None
  2863. else:
  2864. self._fetch_clause = self._offset_or_limit_clause(count)
  2865. self._fetch_clause_options = {
  2866. "with_ties": with_ties,
  2867. "percent": percent,
  2868. }
  2869. @_generative
  2870. def offset(self, offset):
  2871. """Return a new selectable with the given OFFSET criterion
  2872. applied.
  2873. This is a numeric value which usually renders as an ``OFFSET``
  2874. expression in the resulting select. Backends that don't
  2875. support ``OFFSET`` will attempt to provide similar
  2876. functionality.
  2877. .. versionchanged:: 1.0.0 - :meth:`_expression.Select.offset` can now
  2878. accept arbitrary SQL expressions as well as integer values.
  2879. :param offset: an integer OFFSET parameter, or a SQL expression
  2880. that provides an integer result. Pass ``None`` to reset it.
  2881. .. seealso::
  2882. :meth:`_sql.GenerativeSelect.limit`
  2883. :meth:`_sql.GenerativeSelect.fetch`
  2884. """
  2885. self._offset_clause = self._offset_or_limit_clause(offset)
  2886. @_generative
  2887. @util.preload_module("sqlalchemy.sql.util")
  2888. def slice(self, start, stop):
  2889. """Apply LIMIT / OFFSET to this statement based on a slice.
  2890. The start and stop indices behave like the argument to Python's
  2891. built-in :func:`range` function. This method provides an
  2892. alternative to using ``LIMIT``/``OFFSET`` to get a slice of the
  2893. query.
  2894. For example, ::
  2895. stmt = select(User).order_by(User.id).slice(1, 3)
  2896. renders as
  2897. .. sourcecode:: sql
  2898. SELECT users.id AS users_id,
  2899. users.name AS users_name
  2900. FROM users ORDER BY users.id
  2901. LIMIT ? OFFSET ?
  2902. (2, 1)
  2903. .. note::
  2904. The :meth:`_sql.GenerativeSelect.slice` method will replace
  2905. any clause applied with :meth:`_sql.GenerativeSelect.fetch`.
  2906. .. versionadded:: 1.4 Added the :meth:`_sql.GenerativeSelect.slice`
  2907. method generalized from the ORM.
  2908. .. seealso::
  2909. :meth:`_sql.GenerativeSelect.limit`
  2910. :meth:`_sql.GenerativeSelect.offset`
  2911. :meth:`_sql.GenerativeSelect.fetch`
  2912. """
  2913. sql_util = util.preloaded.sql_util
  2914. self._fetch_clause = self._fetch_clause_options = None
  2915. self._limit_clause, self._offset_clause = sql_util._make_slice(
  2916. self._limit_clause, self._offset_clause, start, stop
  2917. )
  2918. @_generative
  2919. def order_by(self, *clauses):
  2920. r"""Return a new selectable with the given list of ORDER BY
  2921. criteria applied.
  2922. e.g.::
  2923. stmt = select(table).order_by(table.c.id, table.c.name)
  2924. Calling this method multiple times is equivalent to calling it once
  2925. with all the clauses concatenated. All existing ORDER BY criteria may
  2926. be cancelled by passing ``None`` by itself. New ORDER BY criteria may
  2927. then be added by invoking :meth:`_orm.Query.order_by` again, e.g.::
  2928. # will erase all ORDER BY and ORDER BY new_col alone
  2929. stmt = stmt.order_by(None).order_by(new_col)
  2930. :param \*clauses: a series of :class:`_expression.ColumnElement`
  2931. constructs
  2932. which will be used to generate an ORDER BY clause.
  2933. .. seealso::
  2934. :ref:`tutorial_order_by` - in the :ref:`unified_tutorial`
  2935. :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
  2936. """
  2937. if len(clauses) == 1 and clauses[0] is None:
  2938. self._order_by_clauses = ()
  2939. else:
  2940. self._order_by_clauses += tuple(
  2941. coercions.expect(roles.OrderByRole, clause)
  2942. for clause in clauses
  2943. )
  2944. @_generative
  2945. def group_by(self, *clauses):
  2946. r"""Return a new selectable with the given list of GROUP BY
  2947. criterion applied.
  2948. All existing GROUP BY settings can be suppressed by passing ``None``.
  2949. e.g.::
  2950. stmt = select(table.c.name, func.max(table.c.stat)).\
  2951. group_by(table.c.name)
  2952. :param \*clauses: a series of :class:`_expression.ColumnElement`
  2953. constructs
  2954. which will be used to generate an GROUP BY clause.
  2955. .. seealso::
  2956. :ref:`tutorial_group_by_w_aggregates` - in the
  2957. :ref:`unified_tutorial`
  2958. :ref:`tutorial_order_by_label` - in the :ref:`unified_tutorial`
  2959. """
  2960. if len(clauses) == 1 and clauses[0] is None:
  2961. self._group_by_clauses = ()
  2962. else:
  2963. self._group_by_clauses += tuple(
  2964. coercions.expect(roles.GroupByRole, clause)
  2965. for clause in clauses
  2966. )
  2967. @CompileState.plugin_for("default", "compound_select")
  2968. class CompoundSelectState(CompileState):
  2969. @util.memoized_property
  2970. def _label_resolve_dict(self):
  2971. # TODO: this is hacky and slow
  2972. hacky_subquery = self.statement.subquery()
  2973. hacky_subquery.named_with_column = False
  2974. d = dict((c.key, c) for c in hacky_subquery.c)
  2975. return d, d, d
  2976. class CompoundSelect(HasCompileState, GenerativeSelect):
  2977. """Forms the basis of ``UNION``, ``UNION ALL``, and other
  2978. SELECT-based set operations.
  2979. .. seealso::
  2980. :func:`_expression.union`
  2981. :func:`_expression.union_all`
  2982. :func:`_expression.intersect`
  2983. :func:`_expression.intersect_all`
  2984. :func:`_expression.except`
  2985. :func:`_expression.except_all`
  2986. """
  2987. __visit_name__ = "compound_select"
  2988. _traverse_internals = [
  2989. ("selects", InternalTraversal.dp_clauseelement_list),
  2990. ("_limit_clause", InternalTraversal.dp_clauseelement),
  2991. ("_offset_clause", InternalTraversal.dp_clauseelement),
  2992. ("_fetch_clause", InternalTraversal.dp_clauseelement),
  2993. ("_fetch_clause_options", InternalTraversal.dp_plain_dict),
  2994. ("_order_by_clauses", InternalTraversal.dp_clauseelement_list),
  2995. ("_group_by_clauses", InternalTraversal.dp_clauseelement_list),
  2996. ("_for_update_arg", InternalTraversal.dp_clauseelement),
  2997. ("keyword", InternalTraversal.dp_string),
  2998. ] + SupportsCloneAnnotations._clone_annotations_traverse_internals
  2999. UNION = util.symbol("UNION")
  3000. UNION_ALL = util.symbol("UNION ALL")
  3001. EXCEPT = util.symbol("EXCEPT")
  3002. EXCEPT_ALL = util.symbol("EXCEPT ALL")
  3003. INTERSECT = util.symbol("INTERSECT")
  3004. INTERSECT_ALL = util.symbol("INTERSECT ALL")
  3005. _is_from_container = True
  3006. def __init__(self, keyword, *selects, **kwargs):
  3007. self._auto_correlate = kwargs.pop("correlate", False)
  3008. self.keyword = keyword
  3009. self.selects = [
  3010. coercions.expect(roles.CompoundElementRole, s).self_group(
  3011. against=self
  3012. )
  3013. for s in selects
  3014. ]
  3015. if kwargs and util.SQLALCHEMY_WARN_20:
  3016. util.warn_deprecated_20(
  3017. "Set functions such as union(), union_all(), extract(), etc. "
  3018. "in SQLAlchemy 2.0 will accept a "
  3019. "series of SELECT statements only. "
  3020. "Please use generative methods such as order_by() for "
  3021. "additional modifications to this CompoundSelect.",
  3022. stacklevel=4,
  3023. )
  3024. GenerativeSelect.__init__(self, **kwargs)
  3025. @classmethod
  3026. def _create_union(cls, *selects, **kwargs):
  3027. r"""Return a ``UNION`` of multiple selectables.
  3028. The returned object is an instance of
  3029. :class:`_expression.CompoundSelect`.
  3030. A similar :func:`union()` method is available on all
  3031. :class:`_expression.FromClause` subclasses.
  3032. :param \*selects:
  3033. a list of :class:`_expression.Select` instances.
  3034. :param \**kwargs:
  3035. available keyword arguments are the same as those of
  3036. :func:`select`.
  3037. """
  3038. return CompoundSelect(CompoundSelect.UNION, *selects, **kwargs)
  3039. @classmethod
  3040. def _create_union_all(cls, *selects, **kwargs):
  3041. r"""Return a ``UNION ALL`` of multiple selectables.
  3042. The returned object is an instance of
  3043. :class:`_expression.CompoundSelect`.
  3044. A similar :func:`union_all()` method is available on all
  3045. :class:`_expression.FromClause` subclasses.
  3046. :param \*selects:
  3047. a list of :class:`_expression.Select` instances.
  3048. :param \**kwargs:
  3049. available keyword arguments are the same as those of
  3050. :func:`select`.
  3051. """
  3052. return CompoundSelect(CompoundSelect.UNION_ALL, *selects, **kwargs)
  3053. @classmethod
  3054. def _create_except(cls, *selects, **kwargs):
  3055. r"""Return an ``EXCEPT`` of multiple selectables.
  3056. The returned object is an instance of
  3057. :class:`_expression.CompoundSelect`.
  3058. :param \*selects:
  3059. a list of :class:`_expression.Select` instances.
  3060. :param \**kwargs:
  3061. available keyword arguments are the same as those of
  3062. :func:`select`.
  3063. """
  3064. return CompoundSelect(CompoundSelect.EXCEPT, *selects, **kwargs)
  3065. @classmethod
  3066. def _create_except_all(cls, *selects, **kwargs):
  3067. r"""Return an ``EXCEPT ALL`` of multiple selectables.
  3068. The returned object is an instance of
  3069. :class:`_expression.CompoundSelect`.
  3070. :param \*selects:
  3071. a list of :class:`_expression.Select` instances.
  3072. :param \**kwargs:
  3073. available keyword arguments are the same as those of
  3074. :func:`select`.
  3075. """
  3076. return CompoundSelect(CompoundSelect.EXCEPT_ALL, *selects, **kwargs)
  3077. @classmethod
  3078. def _create_intersect(cls, *selects, **kwargs):
  3079. r"""Return an ``INTERSECT`` of multiple selectables.
  3080. The returned object is an instance of
  3081. :class:`_expression.CompoundSelect`.
  3082. :param \*selects:
  3083. a list of :class:`_expression.Select` instances.
  3084. :param \**kwargs:
  3085. available keyword arguments are the same as those of
  3086. :func:`select`.
  3087. """
  3088. return CompoundSelect(CompoundSelect.INTERSECT, *selects, **kwargs)
  3089. @classmethod
  3090. def _create_intersect_all(cls, *selects, **kwargs):
  3091. r"""Return an ``INTERSECT ALL`` of multiple selectables.
  3092. The returned object is an instance of
  3093. :class:`_expression.CompoundSelect`.
  3094. :param \*selects:
  3095. a list of :class:`_expression.Select` instances.
  3096. :param \**kwargs:
  3097. available keyword arguments are the same as those of
  3098. :func:`select`.
  3099. """
  3100. return CompoundSelect(CompoundSelect.INTERSECT_ALL, *selects, **kwargs)
  3101. def _scalar_type(self):
  3102. return self.selects[0]._scalar_type()
  3103. def self_group(self, against=None):
  3104. return SelectStatementGrouping(self)
  3105. def is_derived_from(self, fromclause):
  3106. for s in self.selects:
  3107. if s.is_derived_from(fromclause):
  3108. return True
  3109. return False
  3110. def _set_label_style(self, style):
  3111. if self._label_style is not style:
  3112. self = self._generate()
  3113. select_0 = self.selects[0]._set_label_style(style)
  3114. self.selects = [select_0] + self.selects[1:]
  3115. return self
  3116. def _ensure_disambiguated_names(self):
  3117. new_select = self.selects[0]._ensure_disambiguated_names()
  3118. if new_select is not self.selects[0]:
  3119. self = self._generate()
  3120. self.selects = [new_select] + self.selects[1:]
  3121. return self
  3122. def _generate_fromclause_column_proxies(self, subquery):
  3123. # this is a slightly hacky thing - the union exports a
  3124. # column that resembles just that of the *first* selectable.
  3125. # to get at a "composite" column, particularly foreign keys,
  3126. # you have to dig through the proxies collection which we
  3127. # generate below. We may want to improve upon this, such as
  3128. # perhaps _make_proxy can accept a list of other columns
  3129. # that are "shared" - schema.column can then copy all the
  3130. # ForeignKeys in. this would allow the union() to have all
  3131. # those fks too.
  3132. select_0 = self.selects[0]
  3133. if self._label_style is not LABEL_STYLE_DEFAULT:
  3134. select_0 = select_0.set_label_style(self._label_style)
  3135. select_0._generate_fromclause_column_proxies(subquery)
  3136. # hand-construct the "_proxies" collection to include all
  3137. # derived columns place a 'weight' annotation corresponding
  3138. # to how low in the list of select()s the column occurs, so
  3139. # that the corresponding_column() operation can resolve
  3140. # conflicts
  3141. for subq_col, select_cols in zip(
  3142. subquery.c._all_columns,
  3143. zip(*[s.selected_columns for s in self.selects]),
  3144. ):
  3145. subq_col._proxies = [
  3146. c._annotate({"weight": i + 1})
  3147. for (i, c) in enumerate(select_cols)
  3148. ]
  3149. def _refresh_for_new_column(self, column):
  3150. super(CompoundSelect, self)._refresh_for_new_column(column)
  3151. for select in self.selects:
  3152. select._refresh_for_new_column(column)
  3153. @property
  3154. def _all_selected_columns(self):
  3155. return self.selects[0]._all_selected_columns
  3156. @property
  3157. def selected_columns(self):
  3158. """A :class:`_expression.ColumnCollection`
  3159. representing the columns that
  3160. this SELECT statement or similar construct returns in its result set,
  3161. not including :class:`_sql.TextClause` constructs.
  3162. For a :class:`_expression.CompoundSelect`, the
  3163. :attr:`_expression.CompoundSelect.selected_columns`
  3164. attribute returns the selected
  3165. columns of the first SELECT statement contained within the series of
  3166. statements within the set operation.
  3167. .. seealso::
  3168. :attr:`_sql.Select.selected_columns`
  3169. .. versionadded:: 1.4
  3170. """
  3171. return self.selects[0].selected_columns
  3172. @property
  3173. @util.deprecated_20(
  3174. ":attr:`.Executable.bind`",
  3175. alternative="Bound metadata is being removed as of SQLAlchemy 2.0.",
  3176. enable_warnings=False,
  3177. )
  3178. def bind(self):
  3179. """Returns the :class:`_engine.Engine` or :class:`_engine.Connection`
  3180. to which this :class:`.Executable` is bound, or None if none found.
  3181. """
  3182. if self._bind:
  3183. return self._bind
  3184. for s in self.selects:
  3185. e = s.bind
  3186. if e:
  3187. return e
  3188. else:
  3189. return None
  3190. @bind.setter
  3191. def bind(self, bind):
  3192. self._bind = bind
  3193. class DeprecatedSelectGenerations(object):
  3194. """A collection of methods available on :class:`_sql.Select`, these
  3195. are all **deprecated** methods as they modify the :class:`_sql.Select`
  3196. object in -place.
  3197. """
  3198. @util.deprecated(
  3199. "1.4",
  3200. "The :meth:`_expression.Select.append_correlation` "
  3201. "method is deprecated "
  3202. "and will be removed in a future release. Use the generative "
  3203. "method :meth:`_expression.Select.correlate`.",
  3204. )
  3205. def append_correlation(self, fromclause):
  3206. """Append the given correlation expression to this select()
  3207. construct.
  3208. This is an **in-place** mutation method; the
  3209. :meth:`_expression.Select.correlate` method is preferred,
  3210. as it provides
  3211. standard :term:`method chaining`.
  3212. """
  3213. self.correlate.non_generative(self, fromclause)
  3214. @util.deprecated(
  3215. "1.4",
  3216. "The :meth:`_expression.Select.append_column` method is deprecated "
  3217. "and will be removed in a future release. Use the generative "
  3218. "method :meth:`_expression.Select.add_columns`.",
  3219. )
  3220. def append_column(self, column):
  3221. """Append the given column expression to the columns clause of this
  3222. select() construct.
  3223. E.g.::
  3224. my_select.append_column(some_table.c.new_column)
  3225. This is an **in-place** mutation method; the
  3226. :meth:`_expression.Select.add_columns` method is preferred,
  3227. as it provides standard
  3228. :term:`method chaining`.
  3229. """
  3230. self.add_columns.non_generative(self, column)
  3231. @util.deprecated(
  3232. "1.4",
  3233. "The :meth:`_expression.Select.append_prefix` method is deprecated "
  3234. "and will be removed in a future release. Use the generative "
  3235. "method :meth:`_expression.Select.prefix_with`.",
  3236. )
  3237. def append_prefix(self, clause):
  3238. """Append the given columns clause prefix expression to this select()
  3239. construct.
  3240. This is an **in-place** mutation method; the
  3241. :meth:`_expression.Select.prefix_with` method is preferred,
  3242. as it provides
  3243. standard :term:`method chaining`.
  3244. """
  3245. self.prefix_with.non_generative(self, clause)
  3246. @util.deprecated(
  3247. "1.4",
  3248. "The :meth:`_expression.Select.append_whereclause` "
  3249. "method is deprecated "
  3250. "and will be removed in a future release. Use the generative "
  3251. "method :meth:`_expression.Select.where`.",
  3252. )
  3253. def append_whereclause(self, whereclause):
  3254. """Append the given expression to this select() construct's WHERE
  3255. criterion.
  3256. The expression will be joined to existing WHERE criterion via AND.
  3257. This is an **in-place** mutation method; the
  3258. :meth:`_expression.Select.where` method is preferred,
  3259. as it provides standard
  3260. :term:`method chaining`.
  3261. """
  3262. self.where.non_generative(self, whereclause)
  3263. @util.deprecated(
  3264. "1.4",
  3265. "The :meth:`_expression.Select.append_having` method is deprecated "
  3266. "and will be removed in a future release. Use the generative "
  3267. "method :meth:`_expression.Select.having`.",
  3268. )
  3269. def append_having(self, having):
  3270. """Append the given expression to this select() construct's HAVING
  3271. criterion.
  3272. The expression will be joined to existing HAVING criterion via AND.
  3273. This is an **in-place** mutation method; the
  3274. :meth:`_expression.Select.having` method is preferred,
  3275. as it provides standard
  3276. :term:`method chaining`.
  3277. """
  3278. self.having.non_generative(self, having)
  3279. @util.deprecated(
  3280. "1.4",
  3281. "The :meth:`_expression.Select.append_from` method is deprecated "
  3282. "and will be removed in a future release. Use the generative "
  3283. "method :meth:`_expression.Select.select_from`.",
  3284. )
  3285. def append_from(self, fromclause):
  3286. """Append the given :class:`_expression.FromClause` expression
  3287. to this select() construct's FROM clause.
  3288. This is an **in-place** mutation method; the
  3289. :meth:`_expression.Select.select_from` method is preferred,
  3290. as it provides
  3291. standard :term:`method chaining`.
  3292. """
  3293. self.select_from.non_generative(self, fromclause)
  3294. @CompileState.plugin_for("default", "select")
  3295. class SelectState(util.MemoizedSlots, CompileState):
  3296. __slots__ = (
  3297. "from_clauses",
  3298. "froms",
  3299. "columns_plus_names",
  3300. "_label_resolve_dict",
  3301. )
  3302. class default_select_compile_options(CacheableOptions):
  3303. _cache_key_traversal = []
  3304. def __init__(self, statement, compiler, **kw):
  3305. self.statement = statement
  3306. self.from_clauses = statement._from_obj
  3307. for memoized_entities in statement._memoized_select_entities:
  3308. self._setup_joins(
  3309. memoized_entities._setup_joins, memoized_entities._raw_columns
  3310. )
  3311. if statement._setup_joins:
  3312. self._setup_joins(statement._setup_joins, statement._raw_columns)
  3313. self.froms = self._get_froms(statement)
  3314. self.columns_plus_names = statement._generate_columns_plus_names(True)
  3315. @classmethod
  3316. def _plugin_not_implemented(cls):
  3317. raise NotImplementedError(
  3318. "The default SELECT construct without plugins does not "
  3319. "implement this method."
  3320. )
  3321. @classmethod
  3322. def get_column_descriptions(cls, statement):
  3323. return [
  3324. {
  3325. "name": name,
  3326. "type": element.type,
  3327. "expr": element,
  3328. }
  3329. for _, name, _, element, _ in (
  3330. statement._generate_columns_plus_names(False)
  3331. )
  3332. ]
  3333. @classmethod
  3334. def from_statement(cls, statement, from_statement):
  3335. cls._plugin_not_implemented()
  3336. @classmethod
  3337. def get_columns_clause_froms(cls, statement):
  3338. return cls._normalize_froms(
  3339. itertools.chain.from_iterable(
  3340. element._from_objects for element in statement._raw_columns
  3341. )
  3342. )
  3343. @classmethod
  3344. def _column_naming_convention(cls, label_style):
  3345. table_qualified = label_style is LABEL_STYLE_TABLENAME_PLUS_COL
  3346. dedupe = label_style is not LABEL_STYLE_NONE
  3347. pa = prefix_anon_map()
  3348. names = set()
  3349. def go(c, col_name=None):
  3350. if c._is_text_clause:
  3351. return None
  3352. elif not dedupe:
  3353. name = c._proxy_key
  3354. if name is None:
  3355. name = "_no_label"
  3356. return name
  3357. name = c._tq_key_label if table_qualified else c._proxy_key
  3358. if name is None:
  3359. name = "_no_label"
  3360. if name in names:
  3361. return c._anon_label(name) % pa
  3362. else:
  3363. names.add(name)
  3364. return name
  3365. elif name in names:
  3366. return (
  3367. c._anon_tq_key_label % pa
  3368. if table_qualified
  3369. else c._anon_key_label % pa
  3370. )
  3371. else:
  3372. names.add(name)
  3373. return name
  3374. return go
  3375. def _get_froms(self, statement):
  3376. return self._normalize_froms(
  3377. itertools.chain(
  3378. itertools.chain.from_iterable(
  3379. [
  3380. element._from_objects
  3381. for element in statement._raw_columns
  3382. ]
  3383. ),
  3384. itertools.chain.from_iterable(
  3385. [
  3386. element._from_objects
  3387. for element in statement._where_criteria
  3388. ]
  3389. ),
  3390. self.from_clauses,
  3391. ),
  3392. check_statement=statement,
  3393. )
  3394. @classmethod
  3395. def _normalize_froms(cls, iterable_of_froms, check_statement=None):
  3396. """given an iterable of things to select FROM, reduce them to what
  3397. would actually render in the FROM clause of a SELECT.
  3398. This does the job of checking for JOINs, tables, etc. that are in fact
  3399. overlapping due to cloning, adaption, present in overlapping joins,
  3400. etc.
  3401. """
  3402. seen = set()
  3403. froms = []
  3404. for item in iterable_of_froms:
  3405. if item._is_subquery and item.element is check_statement:
  3406. raise exc.InvalidRequestError(
  3407. "select() construct refers to itself as a FROM"
  3408. )
  3409. if not seen.intersection(item._cloned_set):
  3410. froms.append(item)
  3411. seen.update(item._cloned_set)
  3412. if froms:
  3413. toremove = set(
  3414. itertools.chain.from_iterable(
  3415. [_expand_cloned(f._hide_froms) for f in froms]
  3416. )
  3417. )
  3418. if toremove:
  3419. # filter out to FROM clauses not in the list,
  3420. # using a list to maintain ordering
  3421. froms = [f for f in froms if f not in toremove]
  3422. return froms
  3423. def _get_display_froms(
  3424. self, explicit_correlate_froms=None, implicit_correlate_froms=None
  3425. ):
  3426. """Return the full list of 'from' clauses to be displayed.
  3427. Takes into account a set of existing froms which may be
  3428. rendered in the FROM clause of enclosing selects; this Select
  3429. may want to leave those absent if it is automatically
  3430. correlating.
  3431. """
  3432. froms = self.froms
  3433. if self.statement._correlate:
  3434. to_correlate = self.statement._correlate
  3435. if to_correlate:
  3436. froms = [
  3437. f
  3438. for f in froms
  3439. if f
  3440. not in _cloned_intersection(
  3441. _cloned_intersection(
  3442. froms, explicit_correlate_froms or ()
  3443. ),
  3444. to_correlate,
  3445. )
  3446. ]
  3447. if self.statement._correlate_except is not None:
  3448. froms = [
  3449. f
  3450. for f in froms
  3451. if f
  3452. not in _cloned_difference(
  3453. _cloned_intersection(
  3454. froms, explicit_correlate_froms or ()
  3455. ),
  3456. self.statement._correlate_except,
  3457. )
  3458. ]
  3459. if (
  3460. self.statement._auto_correlate
  3461. and implicit_correlate_froms
  3462. and len(froms) > 1
  3463. ):
  3464. froms = [
  3465. f
  3466. for f in froms
  3467. if f
  3468. not in _cloned_intersection(froms, implicit_correlate_froms)
  3469. ]
  3470. if not len(froms):
  3471. raise exc.InvalidRequestError(
  3472. "Select statement '%r"
  3473. "' returned no FROM clauses "
  3474. "due to auto-correlation; "
  3475. "specify correlate(<tables>) "
  3476. "to control correlation "
  3477. "manually." % self.statement
  3478. )
  3479. return froms
  3480. def _memoized_attr__label_resolve_dict(self):
  3481. with_cols = dict(
  3482. (c._tq_label or c.key, c)
  3483. for c in self.statement._all_selected_columns
  3484. if c._allow_label_resolve
  3485. )
  3486. only_froms = dict(
  3487. (c.key, c)
  3488. for c in _select_iterables(self.froms)
  3489. if c._allow_label_resolve
  3490. )
  3491. only_cols = with_cols.copy()
  3492. for key, value in only_froms.items():
  3493. with_cols.setdefault(key, value)
  3494. return with_cols, only_froms, only_cols
  3495. @classmethod
  3496. def determine_last_joined_entity(cls, stmt):
  3497. if stmt._setup_joins:
  3498. return stmt._setup_joins[-1][0]
  3499. else:
  3500. return None
  3501. @classmethod
  3502. def all_selected_columns(cls, statement):
  3503. return [c for c in _select_iterables(statement._raw_columns)]
  3504. def _setup_joins(self, args, raw_columns):
  3505. for (right, onclause, left, flags) in args:
  3506. isouter = flags["isouter"]
  3507. full = flags["full"]
  3508. if left is None:
  3509. (
  3510. left,
  3511. replace_from_obj_index,
  3512. ) = self._join_determine_implicit_left_side(
  3513. raw_columns, left, right, onclause
  3514. )
  3515. else:
  3516. (replace_from_obj_index) = self._join_place_explicit_left_side(
  3517. left
  3518. )
  3519. if replace_from_obj_index is not None:
  3520. # splice into an existing element in the
  3521. # self._from_obj list
  3522. left_clause = self.from_clauses[replace_from_obj_index]
  3523. self.from_clauses = (
  3524. self.from_clauses[:replace_from_obj_index]
  3525. + (
  3526. Join(
  3527. left_clause,
  3528. right,
  3529. onclause,
  3530. isouter=isouter,
  3531. full=full,
  3532. ),
  3533. )
  3534. + self.from_clauses[replace_from_obj_index + 1 :]
  3535. )
  3536. else:
  3537. self.from_clauses = self.from_clauses + (
  3538. Join(left, right, onclause, isouter=isouter, full=full),
  3539. )
  3540. @util.preload_module("sqlalchemy.sql.util")
  3541. def _join_determine_implicit_left_side(
  3542. self, raw_columns, left, right, onclause
  3543. ):
  3544. """When join conditions don't express the left side explicitly,
  3545. determine if an existing FROM or entity in this query
  3546. can serve as the left hand side.
  3547. """
  3548. sql_util = util.preloaded.sql_util
  3549. replace_from_obj_index = None
  3550. from_clauses = self.from_clauses
  3551. if from_clauses:
  3552. indexes = sql_util.find_left_clause_to_join_from(
  3553. from_clauses, right, onclause
  3554. )
  3555. if len(indexes) == 1:
  3556. replace_from_obj_index = indexes[0]
  3557. left = from_clauses[replace_from_obj_index]
  3558. else:
  3559. potential = {}
  3560. statement = self.statement
  3561. for from_clause in itertools.chain(
  3562. itertools.chain.from_iterable(
  3563. [element._from_objects for element in raw_columns]
  3564. ),
  3565. itertools.chain.from_iterable(
  3566. [
  3567. element._from_objects
  3568. for element in statement._where_criteria
  3569. ]
  3570. ),
  3571. ):
  3572. potential[from_clause] = ()
  3573. all_clauses = list(potential.keys())
  3574. indexes = sql_util.find_left_clause_to_join_from(
  3575. all_clauses, right, onclause
  3576. )
  3577. if len(indexes) == 1:
  3578. left = all_clauses[indexes[0]]
  3579. if len(indexes) > 1:
  3580. raise exc.InvalidRequestError(
  3581. "Can't determine which FROM clause to join "
  3582. "from, there are multiple FROMS which can "
  3583. "join to this entity. Please use the .select_from() "
  3584. "method to establish an explicit left side, as well as "
  3585. "providing an explicit ON clause if not present already to "
  3586. "help resolve the ambiguity."
  3587. )
  3588. elif not indexes:
  3589. raise exc.InvalidRequestError(
  3590. "Don't know how to join to %r. "
  3591. "Please use the .select_from() "
  3592. "method to establish an explicit left side, as well as "
  3593. "providing an explicit ON clause if not present already to "
  3594. "help resolve the ambiguity." % (right,)
  3595. )
  3596. return left, replace_from_obj_index
  3597. @util.preload_module("sqlalchemy.sql.util")
  3598. def _join_place_explicit_left_side(self, left):
  3599. replace_from_obj_index = None
  3600. sql_util = util.preloaded.sql_util
  3601. from_clauses = list(self.statement._iterate_from_elements())
  3602. if from_clauses:
  3603. indexes = sql_util.find_left_clause_that_matches_given(
  3604. self.from_clauses, left
  3605. )
  3606. else:
  3607. indexes = []
  3608. if len(indexes) > 1:
  3609. raise exc.InvalidRequestError(
  3610. "Can't identify which entity in which to assign the "
  3611. "left side of this join. Please use a more specific "
  3612. "ON clause."
  3613. )
  3614. # have an index, means the left side is already present in
  3615. # an existing FROM in the self._from_obj tuple
  3616. if indexes:
  3617. replace_from_obj_index = indexes[0]
  3618. # no index, means we need to add a new element to the
  3619. # self._from_obj tuple
  3620. return replace_from_obj_index
  3621. class _SelectFromElements(object):
  3622. def _iterate_from_elements(self):
  3623. # note this does not include elements
  3624. # in _setup_joins or _legacy_setup_joins
  3625. seen = set()
  3626. for element in self._raw_columns:
  3627. for fr in element._from_objects:
  3628. if fr in seen:
  3629. continue
  3630. seen.add(fr)
  3631. yield fr
  3632. for element in self._where_criteria:
  3633. for fr in element._from_objects:
  3634. if fr in seen:
  3635. continue
  3636. seen.add(fr)
  3637. yield fr
  3638. for element in self._from_obj:
  3639. if element in seen:
  3640. continue
  3641. seen.add(element)
  3642. yield element
  3643. class _MemoizedSelectEntities(
  3644. traversals.HasCacheKey, traversals.HasCopyInternals, visitors.Traversible
  3645. ):
  3646. __visit_name__ = "memoized_select_entities"
  3647. _traverse_internals = [
  3648. ("_raw_columns", InternalTraversal.dp_clauseelement_list),
  3649. ("_setup_joins", InternalTraversal.dp_setup_join_tuple),
  3650. ("_legacy_setup_joins", InternalTraversal.dp_setup_join_tuple),
  3651. ("_with_options", InternalTraversal.dp_executable_options),
  3652. ]
  3653. _annotations = util.EMPTY_DICT
  3654. def _clone(self, **kw):
  3655. c = self.__class__.__new__(self.__class__)
  3656. c.__dict__ = {k: v for k, v in self.__dict__.items()}
  3657. c._is_clone_of = self.__dict__.get("_is_clone_of", self)
  3658. return c
  3659. @classmethod
  3660. def _generate_for_statement(cls, select_stmt):
  3661. if (
  3662. select_stmt._setup_joins
  3663. or select_stmt._legacy_setup_joins
  3664. or select_stmt._with_options
  3665. ):
  3666. self = _MemoizedSelectEntities()
  3667. self._raw_columns = select_stmt._raw_columns
  3668. self._setup_joins = select_stmt._setup_joins
  3669. self._legacy_setup_joins = select_stmt._legacy_setup_joins
  3670. self._with_options = select_stmt._with_options
  3671. select_stmt._memoized_select_entities += (self,)
  3672. select_stmt._raw_columns = (
  3673. select_stmt._setup_joins
  3674. ) = (
  3675. select_stmt._legacy_setup_joins
  3676. ) = select_stmt._with_options = ()
  3677. class Select(
  3678. HasPrefixes,
  3679. HasSuffixes,
  3680. HasHints,
  3681. HasCompileState,
  3682. DeprecatedSelectGenerations,
  3683. _SelectFromElements,
  3684. GenerativeSelect,
  3685. ):
  3686. """Represents a ``SELECT`` statement.
  3687. The :class:`_sql.Select` object is normally constructed using the
  3688. :func:`_sql.select` function. See that function for details.
  3689. .. seealso::
  3690. :func:`_sql.select`
  3691. :ref:`tutorial_selecting_data` - in the 2.0 tutorial
  3692. """
  3693. __visit_name__ = "select"
  3694. _setup_joins = ()
  3695. _legacy_setup_joins = ()
  3696. _memoized_select_entities = ()
  3697. _distinct = False
  3698. _distinct_on = ()
  3699. _correlate = ()
  3700. _correlate_except = None
  3701. _where_criteria = ()
  3702. _having_criteria = ()
  3703. _from_obj = ()
  3704. _auto_correlate = True
  3705. _compile_options = SelectState.default_select_compile_options
  3706. _traverse_internals = (
  3707. [
  3708. ("_raw_columns", InternalTraversal.dp_clauseelement_list),
  3709. (
  3710. "_memoized_select_entities",
  3711. InternalTraversal.dp_memoized_select_entities,
  3712. ),
  3713. ("_from_obj", InternalTraversal.dp_clauseelement_list),
  3714. ("_where_criteria", InternalTraversal.dp_clauseelement_tuple),
  3715. ("_having_criteria", InternalTraversal.dp_clauseelement_tuple),
  3716. ("_order_by_clauses", InternalTraversal.dp_clauseelement_tuple),
  3717. ("_group_by_clauses", InternalTraversal.dp_clauseelement_tuple),
  3718. ("_setup_joins", InternalTraversal.dp_setup_join_tuple),
  3719. ("_legacy_setup_joins", InternalTraversal.dp_setup_join_tuple),
  3720. ("_correlate", InternalTraversal.dp_clauseelement_tuple),
  3721. ("_correlate_except", InternalTraversal.dp_clauseelement_tuple),
  3722. ("_limit_clause", InternalTraversal.dp_clauseelement),
  3723. ("_offset_clause", InternalTraversal.dp_clauseelement),
  3724. ("_fetch_clause", InternalTraversal.dp_clauseelement),
  3725. ("_fetch_clause_options", InternalTraversal.dp_plain_dict),
  3726. ("_for_update_arg", InternalTraversal.dp_clauseelement),
  3727. ("_distinct", InternalTraversal.dp_boolean),
  3728. ("_distinct_on", InternalTraversal.dp_clauseelement_tuple),
  3729. ("_label_style", InternalTraversal.dp_plain_obj),
  3730. ]
  3731. + HasCTE._has_ctes_traverse_internals
  3732. + HasPrefixes._has_prefixes_traverse_internals
  3733. + HasSuffixes._has_suffixes_traverse_internals
  3734. + HasHints._has_hints_traverse_internals
  3735. + SupportsCloneAnnotations._clone_annotations_traverse_internals
  3736. + Executable._executable_traverse_internals
  3737. )
  3738. _cache_key_traversal = _traverse_internals + [
  3739. ("_compile_options", InternalTraversal.dp_has_cache_key)
  3740. ]
  3741. @classmethod
  3742. def _create_select_from_fromclause(cls, target, entities, *arg, **kw):
  3743. if arg or kw:
  3744. return Select.create_legacy_select(entities, *arg, **kw)
  3745. else:
  3746. return Select._create_select(*entities)
  3747. @classmethod
  3748. @util.deprecated(
  3749. "2.0",
  3750. "The legacy calling style of :func:`_sql.select` is deprecated and "
  3751. "will be removed in SQLAlchemy 2.0. Please use the new calling "
  3752. "style described at :func:`_sql.select`.",
  3753. )
  3754. def create_legacy_select(
  3755. cls,
  3756. columns=None,
  3757. whereclause=None,
  3758. from_obj=None,
  3759. distinct=False,
  3760. having=None,
  3761. correlate=True,
  3762. prefixes=None,
  3763. suffixes=None,
  3764. **kwargs
  3765. ):
  3766. """Construct a new :class:`_expression.Select` using the 1.x style API.
  3767. This method is called implicitly when the :func:`_expression.select`
  3768. construct is used and the first argument is a Python list or other
  3769. plain sequence object, which is taken to refer to the columns
  3770. collection.
  3771. .. versionchanged:: 1.4 Added the :meth:`.Select.create_legacy_select`
  3772. constructor which documents the calling style in use when the
  3773. :func:`.select` construct is invoked using 1.x-style arguments.
  3774. Similar functionality is also available via the
  3775. :meth:`_expression.FromClause.select` method on any
  3776. :class:`_expression.FromClause`.
  3777. All arguments which accept :class:`_expression.ClauseElement` arguments
  3778. also accept string arguments, which will be converted as appropriate
  3779. into either :func:`_expression.text()` or
  3780. :func:`_expression.literal_column()` constructs.
  3781. .. seealso::
  3782. :ref:`tutorial_selecting_data` - in the :ref:`unified_tutorial`
  3783. :param columns:
  3784. A list of :class:`_expression.ColumnElement` or
  3785. :class:`_expression.FromClause`
  3786. objects which will form the columns clause of the resulting
  3787. statement. For those objects that are instances of
  3788. :class:`_expression.FromClause` (typically :class:`_schema.Table`
  3789. or :class:`_expression.Alias`
  3790. objects), the :attr:`_expression.FromClause.c`
  3791. collection is extracted
  3792. to form a collection of :class:`_expression.ColumnElement` objects.
  3793. This parameter will also accept :class:`_expression.TextClause`
  3794. constructs as
  3795. given, as well as ORM-mapped classes.
  3796. .. note::
  3797. The :paramref:`_expression.select.columns`
  3798. parameter is not available
  3799. in the method form of :func:`_expression.select`, e.g.
  3800. :meth:`_expression.FromClause.select`.
  3801. .. seealso::
  3802. :meth:`_expression.Select.column`
  3803. :meth:`_expression.Select.with_only_columns`
  3804. :param whereclause:
  3805. A :class:`_expression.ClauseElement`
  3806. expression which will be used to form the
  3807. ``WHERE`` clause. It is typically preferable to add WHERE
  3808. criterion to an existing :class:`_expression.Select`
  3809. using method chaining
  3810. with :meth:`_expression.Select.where`.
  3811. .. seealso::
  3812. :meth:`_expression.Select.where`
  3813. :param from_obj:
  3814. A list of :class:`_expression.ClauseElement`
  3815. objects which will be added to the
  3816. ``FROM`` clause of the resulting statement. This is equivalent
  3817. to calling :meth:`_expression.Select.select_from`
  3818. using method chaining on
  3819. an existing :class:`_expression.Select` object.
  3820. .. seealso::
  3821. :meth:`_expression.Select.select_from`
  3822. - full description of explicit
  3823. FROM clause specification.
  3824. :param bind=None:
  3825. an :class:`_engine.Engine` or :class:`_engine.Connection` instance
  3826. to which the
  3827. resulting :class:`_expression.Select` object will be bound. The
  3828. :class:`_expression.Select`
  3829. object will otherwise automatically bind to
  3830. whatever :class:`~.base.Connectable` instances can be located within
  3831. its contained :class:`_expression.ClauseElement` members.
  3832. :param correlate=True:
  3833. indicates that this :class:`_expression.Select`
  3834. object should have its
  3835. contained :class:`_expression.FromClause`
  3836. elements "correlated" to an enclosing
  3837. :class:`_expression.Select` object.
  3838. It is typically preferable to specify
  3839. correlations on an existing :class:`_expression.Select`
  3840. construct using
  3841. :meth:`_expression.Select.correlate`.
  3842. .. seealso::
  3843. :meth:`_expression.Select.correlate`
  3844. - full description of correlation.
  3845. :param distinct=False:
  3846. when ``True``, applies a ``DISTINCT`` qualifier to the columns
  3847. clause of the resulting statement.
  3848. The boolean argument may also be a column expression or list
  3849. of column expressions - this is a special calling form which
  3850. is understood by the PostgreSQL dialect to render the
  3851. ``DISTINCT ON (<columns>)`` syntax.
  3852. ``distinct`` is also available on an existing
  3853. :class:`_expression.Select`
  3854. object via the :meth:`_expression.Select.distinct` method.
  3855. .. seealso::
  3856. :meth:`_expression.Select.distinct`
  3857. :param group_by:
  3858. a list of :class:`_expression.ClauseElement`
  3859. objects which will comprise the
  3860. ``GROUP BY`` clause of the resulting select. This parameter
  3861. is typically specified more naturally using the
  3862. :meth:`_expression.Select.group_by` method on an existing
  3863. :class:`_expression.Select`.
  3864. .. seealso::
  3865. :meth:`_expression.Select.group_by`
  3866. :param having:
  3867. a :class:`_expression.ClauseElement`
  3868. that will comprise the ``HAVING`` clause
  3869. of the resulting select when ``GROUP BY`` is used. This parameter
  3870. is typically specified more naturally using the
  3871. :meth:`_expression.Select.having` method on an existing
  3872. :class:`_expression.Select`.
  3873. .. seealso::
  3874. :meth:`_expression.Select.having`
  3875. :param limit=None:
  3876. a numerical value which usually renders as a ``LIMIT``
  3877. expression in the resulting select. Backends that don't
  3878. support ``LIMIT`` will attempt to provide similar
  3879. functionality. This parameter is typically specified more
  3880. naturally using the :meth:`_expression.Select.limit`
  3881. method on an existing
  3882. :class:`_expression.Select`.
  3883. .. seealso::
  3884. :meth:`_expression.Select.limit`
  3885. :param offset=None:
  3886. a numeric value which usually renders as an ``OFFSET``
  3887. expression in the resulting select. Backends that don't
  3888. support ``OFFSET`` will attempt to provide similar
  3889. functionality. This parameter is typically specified more naturally
  3890. using the :meth:`_expression.Select.offset` method on an existing
  3891. :class:`_expression.Select`.
  3892. .. seealso::
  3893. :meth:`_expression.Select.offset`
  3894. :param order_by:
  3895. a scalar or list of :class:`_expression.ClauseElement`
  3896. objects which will
  3897. comprise the ``ORDER BY`` clause of the resulting select.
  3898. This parameter is typically specified more naturally using the
  3899. :meth:`_expression.Select.order_by` method on an existing
  3900. :class:`_expression.Select`.
  3901. .. seealso::
  3902. :meth:`_expression.Select.order_by`
  3903. :param use_labels=False:
  3904. when ``True``, the statement will be generated using labels
  3905. for each column in the columns clause, which qualify each
  3906. column with its parent table's (or aliases) name so that name
  3907. conflicts between columns in different tables don't occur.
  3908. The format of the label is ``<tablename>_<column>``. The "c"
  3909. collection of a :class:`_expression.Subquery` created
  3910. against this :class:`_expression.Select`
  3911. object, as well as the :attr:`_expression.Select.selected_columns`
  3912. collection of the :class:`_expression.Select` itself, will use these
  3913. names for targeting column members.
  3914. This parameter can also be specified on an existing
  3915. :class:`_expression.Select` object using the
  3916. :meth:`_expression.Select.set_label_style`
  3917. method.
  3918. .. seealso::
  3919. :meth:`_expression.Select.set_label_style`
  3920. """
  3921. self = cls.__new__(cls)
  3922. self._auto_correlate = correlate
  3923. if distinct is not False:
  3924. if distinct is True:
  3925. self.distinct.non_generative(self)
  3926. else:
  3927. self.distinct.non_generative(self, *util.to_list(distinct))
  3928. if from_obj is not None:
  3929. self.select_from.non_generative(self, *util.to_list(from_obj))
  3930. try:
  3931. cols_present = bool(columns)
  3932. except TypeError as err:
  3933. util.raise_(
  3934. exc.ArgumentError(
  3935. "select() construct created in legacy mode, i.e. with "
  3936. "keyword arguments, must provide the columns argument as "
  3937. "a Python list or other iterable.",
  3938. code="c9ae",
  3939. ),
  3940. from_=err,
  3941. )
  3942. if cols_present:
  3943. self._raw_columns = [
  3944. coercions.expect(
  3945. roles.ColumnsClauseRole, c, apply_propagate_attrs=self
  3946. )
  3947. for c in columns
  3948. ]
  3949. else:
  3950. self._raw_columns = []
  3951. if whereclause is not None:
  3952. self.where.non_generative(self, whereclause)
  3953. if having is not None:
  3954. self.having.non_generative(self, having)
  3955. if prefixes:
  3956. self._setup_prefixes(prefixes)
  3957. if suffixes:
  3958. self._setup_suffixes(suffixes)
  3959. GenerativeSelect.__init__(self, **kwargs)
  3960. return self
  3961. @classmethod
  3962. def _create_future_select(cls, *entities):
  3963. r"""Construct a new :class:`_expression.Select` using the 2.
  3964. x style API.
  3965. .. versionadded:: 1.4 - The :func:`_sql.select` function now accepts
  3966. column arguments positionally. The top-level :func:`_sql.select`
  3967. function will automatically use the 1.x or 2.x style API based on
  3968. the incoming arguments; using :func:`_future.select` from the
  3969. ``sqlalchemy.future`` module will enforce that only the 2.x style
  3970. constructor is used.
  3971. Similar functionality is also available via the
  3972. :meth:`_expression.FromClause.select` method on any
  3973. :class:`_expression.FromClause`.
  3974. .. seealso::
  3975. :ref:`coretutorial_selecting` - Core Tutorial description of
  3976. :func:`_expression.select`.
  3977. :param \*entities:
  3978. Entities to SELECT from. For Core usage, this is typically a series
  3979. of :class:`_expression.ColumnElement` and / or
  3980. :class:`_expression.FromClause`
  3981. objects which will form the columns clause of the resulting
  3982. statement. For those objects that are instances of
  3983. :class:`_expression.FromClause` (typically :class:`_schema.Table`
  3984. or :class:`_expression.Alias`
  3985. objects), the :attr:`_expression.FromClause.c`
  3986. collection is extracted
  3987. to form a collection of :class:`_expression.ColumnElement` objects.
  3988. This parameter will also accept :class:`_expression.TextClause`
  3989. constructs as
  3990. given, as well as ORM-mapped classes.
  3991. """
  3992. self = cls.__new__(cls)
  3993. self._raw_columns = [
  3994. coercions.expect(
  3995. roles.ColumnsClauseRole, ent, apply_propagate_attrs=self
  3996. )
  3997. for ent in entities
  3998. ]
  3999. GenerativeSelect.__init__(self)
  4000. return self
  4001. _create_select = _create_future_select
  4002. @classmethod
  4003. def _create_raw_select(cls, **kw):
  4004. """Create a :class:`.Select` using raw ``__new__`` with no coercions.
  4005. Used internally to build up :class:`.Select` constructs with
  4006. pre-established state.
  4007. """
  4008. stmt = Select.__new__(Select)
  4009. stmt.__dict__.update(kw)
  4010. return stmt
  4011. @classmethod
  4012. def _create(cls, *args, **kw):
  4013. r"""Create a :class:`.Select` using either the 1.x or 2.0 constructor
  4014. style.
  4015. For the legacy calling style, see :meth:`.Select.create_legacy_select`.
  4016. If the first argument passed is a Python sequence or if keyword
  4017. arguments are present, this style is used.
  4018. .. versionadded:: 2.0 - the :func:`_future.select` construct is
  4019. the same construct as the one returned by
  4020. :func:`_expression.select`, except that the function only
  4021. accepts the "columns clause" entities up front; the rest of the
  4022. state of the SELECT should be built up using generative methods.
  4023. Similar functionality is also available via the
  4024. :meth:`_expression.FromClause.select` method on any
  4025. :class:`_expression.FromClause`.
  4026. .. seealso::
  4027. :ref:`coretutorial_selecting` - Core Tutorial description of
  4028. :func:`_expression.select`.
  4029. :param \*entities:
  4030. Entities to SELECT from. For Core usage, this is typically a series
  4031. of :class:`_expression.ColumnElement` and / or
  4032. :class:`_expression.FromClause`
  4033. objects which will form the columns clause of the resulting
  4034. statement. For those objects that are instances of
  4035. :class:`_expression.FromClause` (typically :class:`_schema.Table`
  4036. or :class:`_expression.Alias`
  4037. objects), the :attr:`_expression.FromClause.c`
  4038. collection is extracted
  4039. to form a collection of :class:`_expression.ColumnElement` objects.
  4040. This parameter will also accept :class:`_expression.TextClause`
  4041. constructs as given, as well as ORM-mapped classes.
  4042. """
  4043. if (
  4044. args
  4045. and (
  4046. isinstance(args[0], list)
  4047. or (
  4048. hasattr(args[0], "__iter__")
  4049. and not isinstance(
  4050. args[0], util.string_types + (ClauseElement,)
  4051. )
  4052. and inspect(args[0], raiseerr=False) is None
  4053. and not hasattr(args[0], "__clause_element__")
  4054. )
  4055. )
  4056. ) or kw:
  4057. return cls.create_legacy_select(*args, **kw)
  4058. else:
  4059. return cls._create_future_select(*args)
  4060. def __init__(self):
  4061. raise NotImplementedError()
  4062. def _scalar_type(self):
  4063. elem = self._raw_columns[0]
  4064. cols = list(elem._select_iterable)
  4065. return cols[0].type
  4066. def filter(self, *criteria):
  4067. """A synonym for the :meth:`_future.Select.where` method."""
  4068. return self.where(*criteria)
  4069. def _filter_by_zero(self):
  4070. if self._setup_joins:
  4071. meth = SelectState.get_plugin_class(
  4072. self
  4073. ).determine_last_joined_entity
  4074. _last_joined_entity = meth(self)
  4075. if _last_joined_entity is not None:
  4076. return _last_joined_entity
  4077. if self._from_obj:
  4078. return self._from_obj[0]
  4079. return self._raw_columns[0]
  4080. def filter_by(self, **kwargs):
  4081. r"""apply the given filtering criterion as a WHERE clause
  4082. to this select.
  4083. """
  4084. from_entity = self._filter_by_zero()
  4085. clauses = [
  4086. _entity_namespace_key(from_entity, key) == value
  4087. for key, value in kwargs.items()
  4088. ]
  4089. return self.filter(*clauses)
  4090. @property
  4091. def column_descriptions(self):
  4092. """Return a :term:`plugin-enabled` 'column descriptions' structure
  4093. referring to the columns which are SELECTed by this statement.
  4094. This attribute is generally useful when using the ORM, as an
  4095. extended structure which includes information about mapped
  4096. entities is returned. The section :ref:`queryguide_inspection`
  4097. contains more background.
  4098. For a Core-only statement, the structure returned by this accessor
  4099. is derived from the same objects that are returned by the
  4100. :attr:`.Select.selected_columns` accessor, formatted as a list of
  4101. dictionaries which contain the keys ``name``, ``type`` and ``expr``,
  4102. which indicate the column expressions to be selected::
  4103. >>> stmt = select(user_table)
  4104. >>> stmt.column_descriptions
  4105. [
  4106. {
  4107. 'name': 'id',
  4108. 'type': Integer(),
  4109. 'expr': Column('id', Integer(), ...)},
  4110. {
  4111. 'name': 'name',
  4112. 'type': String(length=30),
  4113. 'expr': Column('name', String(length=30), ...)}
  4114. ]
  4115. .. versionchanged:: 1.4.33 The :attr:`.Select.column_descriptions`
  4116. attribute returns a structure for a Core-only set of entities,
  4117. not just ORM-only entities.
  4118. .. seealso::
  4119. :attr:`.UpdateBase.entity_description` - entity information for
  4120. an :func:`.insert`, :func:`.update`, or :func:`.delete`
  4121. :ref:`queryguide_inspection` - ORM background
  4122. """
  4123. meth = SelectState.get_plugin_class(self).get_column_descriptions
  4124. return meth(self)
  4125. def from_statement(self, statement):
  4126. """Apply the columns which this :class:`.Select` would select
  4127. onto another statement.
  4128. This operation is :term:`plugin-specific` and will raise a not
  4129. supported exception if this :class:`_sql.Select` does not select from
  4130. plugin-enabled entities.
  4131. The statement is typically either a :func:`_expression.text` or
  4132. :func:`_expression.select` construct, and should return the set of
  4133. columns appropriate to the entities represented by this
  4134. :class:`.Select`.
  4135. .. seealso::
  4136. :ref:`orm_queryguide_selecting_text` - usage examples in the
  4137. ORM Querying Guide
  4138. """
  4139. meth = SelectState.get_plugin_class(self).from_statement
  4140. return meth(self, statement)
  4141. @_generative
  4142. def join(self, target, onclause=None, isouter=False, full=False):
  4143. r"""Create a SQL JOIN against this :class:`_expression.Select`
  4144. object's criterion
  4145. and apply generatively, returning the newly resulting
  4146. :class:`_expression.Select`.
  4147. E.g.::
  4148. stmt = select(user_table).join(address_table, user_table.c.id == address_table.c.user_id)
  4149. The above statement generates SQL similar to::
  4150. SELECT user.id, user.name FROM user JOIN address ON user.id = address.user_id
  4151. .. versionchanged:: 1.4 :meth:`_expression.Select.join` now creates
  4152. a :class:`_sql.Join` object between a :class:`_sql.FromClause`
  4153. source that is within the FROM clause of the existing SELECT,
  4154. and a given target :class:`_sql.FromClause`, and then adds
  4155. this :class:`_sql.Join` to the FROM clause of the newly generated
  4156. SELECT statement. This is completely reworked from the behavior
  4157. in 1.3, which would instead create a subquery of the entire
  4158. :class:`_expression.Select` and then join that subquery to the
  4159. target.
  4160. This is a **backwards incompatible change** as the previous behavior
  4161. was mostly useless, producing an unnamed subquery rejected by
  4162. most databases in any case. The new behavior is modeled after
  4163. that of the very successful :meth:`_orm.Query.join` method in the
  4164. ORM, in order to support the functionality of :class:`_orm.Query`
  4165. being available by using a :class:`_sql.Select` object with an
  4166. :class:`_orm.Session`.
  4167. See the notes for this change at :ref:`change_select_join`.
  4168. :param target: target table to join towards
  4169. :param onclause: ON clause of the join. If omitted, an ON clause
  4170. is generated automatically based on the :class:`_schema.ForeignKey`
  4171. linkages between the two tables, if one can be unambiguously
  4172. determined, otherwise an error is raised.
  4173. :param isouter: if True, generate LEFT OUTER join. Same as
  4174. :meth:`_expression.Select.outerjoin`.
  4175. :param full: if True, generate FULL OUTER join.
  4176. .. seealso::
  4177. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  4178. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  4179. :meth:`_expression.Select.join_from`
  4180. :meth:`_expression.Select.outerjoin`
  4181. """ # noqa: E501
  4182. target = coercions.expect(
  4183. roles.JoinTargetRole, target, apply_propagate_attrs=self
  4184. )
  4185. if onclause is not None:
  4186. onclause = coercions.expect(roles.OnClauseRole, onclause)
  4187. self._setup_joins += (
  4188. (target, onclause, None, {"isouter": isouter, "full": full}),
  4189. )
  4190. def outerjoin_from(self, from_, target, onclause=None, full=False):
  4191. r"""Create a SQL LEFT OUTER JOIN against this
  4192. :class:`_expression.Select` object's criterion and apply generatively,
  4193. returning the newly resulting :class:`_expression.Select`.
  4194. Usage is the same as that of :meth:`_selectable.Select.join_from`.
  4195. """
  4196. return self.join_from(
  4197. from_, target, onclause=onclause, isouter=True, full=full
  4198. )
  4199. @_generative
  4200. def join_from(
  4201. self, from_, target, onclause=None, isouter=False, full=False
  4202. ):
  4203. r"""Create a SQL JOIN against this :class:`_expression.Select`
  4204. object's criterion
  4205. and apply generatively, returning the newly resulting
  4206. :class:`_expression.Select`.
  4207. E.g.::
  4208. stmt = select(user_table, address_table).join_from(
  4209. user_table, address_table, user_table.c.id == address_table.c.user_id
  4210. )
  4211. The above statement generates SQL similar to::
  4212. SELECT user.id, user.name, address.id, address.email, address.user_id
  4213. FROM user JOIN address ON user.id = address.user_id
  4214. .. versionadded:: 1.4
  4215. :param from\_: the left side of the join, will be rendered in the
  4216. FROM clause and is roughly equivalent to using the
  4217. :meth:`.Select.select_from` method.
  4218. :param target: target table to join towards
  4219. :param onclause: ON clause of the join.
  4220. :param isouter: if True, generate LEFT OUTER join. Same as
  4221. :meth:`_expression.Select.outerjoin`.
  4222. :param full: if True, generate FULL OUTER join.
  4223. .. seealso::
  4224. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  4225. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  4226. :meth:`_expression.Select.join`
  4227. """ # noqa: E501
  4228. # note the order of parsing from vs. target is important here, as we
  4229. # are also deriving the source of the plugin (i.e. the subject mapper
  4230. # in an ORM query) which should favor the "from_" over the "target"
  4231. from_ = coercions.expect(
  4232. roles.FromClauseRole, from_, apply_propagate_attrs=self
  4233. )
  4234. target = coercions.expect(
  4235. roles.JoinTargetRole, target, apply_propagate_attrs=self
  4236. )
  4237. if onclause is not None:
  4238. onclause = coercions.expect(roles.OnClauseRole, onclause)
  4239. self._setup_joins += (
  4240. (target, onclause, from_, {"isouter": isouter, "full": full}),
  4241. )
  4242. def outerjoin(self, target, onclause=None, full=False):
  4243. """Create a left outer join.
  4244. Parameters are the same as that of :meth:`_expression.Select.join`.
  4245. .. versionchanged:: 1.4 :meth:`_expression.Select.outerjoin` now
  4246. creates a :class:`_sql.Join` object between a
  4247. :class:`_sql.FromClause` source that is within the FROM clause of
  4248. the existing SELECT, and a given target :class:`_sql.FromClause`,
  4249. and then adds this :class:`_sql.Join` to the FROM clause of the
  4250. newly generated SELECT statement. This is completely reworked
  4251. from the behavior in 1.3, which would instead create a subquery of
  4252. the entire
  4253. :class:`_expression.Select` and then join that subquery to the
  4254. target.
  4255. This is a **backwards incompatible change** as the previous behavior
  4256. was mostly useless, producing an unnamed subquery rejected by
  4257. most databases in any case. The new behavior is modeled after
  4258. that of the very successful :meth:`_orm.Query.join` method in the
  4259. ORM, in order to support the functionality of :class:`_orm.Query`
  4260. being available by using a :class:`_sql.Select` object with an
  4261. :class:`_orm.Session`.
  4262. See the notes for this change at :ref:`change_select_join`.
  4263. .. seealso::
  4264. :ref:`tutorial_select_join` - in the :doc:`/tutorial/index`
  4265. :ref:`orm_queryguide_joins` - in the :ref:`queryguide_toplevel`
  4266. :meth:`_expression.Select.join`
  4267. """
  4268. return self.join(target, onclause=onclause, isouter=True, full=full)
  4269. def get_final_froms(self):
  4270. """Compute the final displayed list of :class:`_expression.FromClause`
  4271. elements.
  4272. This method will run through the full computation required to
  4273. determine what FROM elements will be displayed in the resulting
  4274. SELECT statement, including shadowing individual tables with
  4275. JOIN objects, as well as full computation for ORM use cases including
  4276. eager loading clauses.
  4277. For ORM use, this accessor returns the **post compilation**
  4278. list of FROM objects; this collection will include elements such as
  4279. eagerly loaded tables and joins. The objects will **not** be
  4280. ORM enabled and not work as a replacement for the
  4281. :meth:`_sql.Select.select_froms` collection; additionally, the
  4282. method is not well performing for an ORM enabled statement as it
  4283. will incur the full ORM construction process.
  4284. To retrieve the FROM list that's implied by the "columns" collection
  4285. passed to the :class:`_sql.Select` originally, use the
  4286. :attr:`_sql.Select.columns_clause_froms` accessor.
  4287. To select from an alternative set of columns while maintaining the
  4288. FROM list, use the :meth:`_sql.Select.with_only_columns` method and
  4289. pass the
  4290. :paramref:`_sql.Select.with_only_columns.maintain_column_froms`
  4291. parameter.
  4292. .. versionadded:: 1.4.23 - the :meth:`_sql.Select.get_final_froms`
  4293. method replaces the previous :attr:`_sql.Select.froms` accessor,
  4294. which is deprecated.
  4295. .. seealso::
  4296. :attr:`_sql.Select.columns_clause_froms`
  4297. """
  4298. return self._compile_state_factory(self, None)._get_display_froms()
  4299. @property
  4300. @util.deprecated(
  4301. "1.4.23",
  4302. "The :attr:`_expression.Select.froms` attribute is moved to "
  4303. "the :meth:`_expression.Select.get_final_froms` method.",
  4304. )
  4305. def froms(self):
  4306. """Return the displayed list of :class:`_expression.FromClause`
  4307. elements.
  4308. """
  4309. return self.get_final_froms()
  4310. @property
  4311. def columns_clause_froms(self):
  4312. """Return the set of :class:`_expression.FromClause` objects implied
  4313. by the columns clause of this SELECT statement.
  4314. .. versionadded:: 1.4.23
  4315. .. seealso::
  4316. :attr:`_sql.Select.froms` - "final" FROM list taking the full
  4317. statement into account
  4318. :meth:`_sql.Select.with_only_columns` - makes use of this
  4319. collection to set up a new FROM list
  4320. """
  4321. return SelectState.get_plugin_class(self).get_columns_clause_froms(
  4322. self
  4323. )
  4324. @property
  4325. def inner_columns(self):
  4326. """An iterator of all :class:`_expression.ColumnElement`
  4327. expressions which would
  4328. be rendered into the columns clause of the resulting SELECT statement.
  4329. This method is legacy as of 1.4 and is superseded by the
  4330. :attr:`_expression.Select.exported_columns` collection.
  4331. """
  4332. return iter(self._all_selected_columns)
  4333. def is_derived_from(self, fromclause):
  4334. if self in fromclause._cloned_set:
  4335. return True
  4336. for f in self._iterate_from_elements():
  4337. if f.is_derived_from(fromclause):
  4338. return True
  4339. return False
  4340. def _copy_internals(self, clone=_clone, **kw):
  4341. # Select() object has been cloned and probably adapted by the
  4342. # given clone function. Apply the cloning function to internal
  4343. # objects
  4344. # 1. keep a dictionary of the froms we've cloned, and what
  4345. # they've become. This allows us to ensure the same cloned from
  4346. # is used when other items such as columns are "cloned"
  4347. all_the_froms = set(
  4348. itertools.chain(
  4349. _from_objects(*self._raw_columns),
  4350. _from_objects(*self._where_criteria),
  4351. _from_objects(*[elem[0] for elem in self._setup_joins]),
  4352. )
  4353. )
  4354. # do a clone for the froms we've gathered. what is important here
  4355. # is if any of the things we are selecting from, like tables,
  4356. # were converted into Join objects. if so, these need to be
  4357. # added to _from_obj explicitly, because otherwise they won't be
  4358. # part of the new state, as they don't associate themselves with
  4359. # their columns.
  4360. new_froms = {f: clone(f, **kw) for f in all_the_froms}
  4361. # 2. copy FROM collections, adding in joins that we've created.
  4362. existing_from_obj = [clone(f, **kw) for f in self._from_obj]
  4363. add_froms = (
  4364. set(f for f in new_froms.values() if isinstance(f, Join))
  4365. .difference(all_the_froms)
  4366. .difference(existing_from_obj)
  4367. )
  4368. self._from_obj = tuple(existing_from_obj) + tuple(add_froms)
  4369. # 3. clone everything else, making sure we use columns
  4370. # corresponding to the froms we just made.
  4371. def replace(obj, **kw):
  4372. if isinstance(obj, ColumnClause) and obj.table in new_froms:
  4373. newelem = new_froms[obj.table].corresponding_column(obj)
  4374. return newelem
  4375. kw["replace"] = replace
  4376. # copy everything else. for table-ish things like correlate,
  4377. # correlate_except, setup_joins, these clone normally. For
  4378. # column-expression oriented things like raw_columns, where_criteria,
  4379. # order by, we get this from the new froms.
  4380. super(Select, self)._copy_internals(
  4381. clone=clone, omit_attrs=("_from_obj",), **kw
  4382. )
  4383. self._reset_memoizations()
  4384. def get_children(self, **kwargs):
  4385. return itertools.chain(
  4386. super(Select, self).get_children(
  4387. omit_attrs=["_from_obj", "_correlate", "_correlate_except"]
  4388. ),
  4389. self._iterate_from_elements(),
  4390. )
  4391. @_generative
  4392. def add_columns(self, *columns):
  4393. """Return a new :func:`_expression.select` construct with
  4394. the given column expressions added to its columns clause.
  4395. E.g.::
  4396. my_select = my_select.add_columns(table.c.new_column)
  4397. See the documentation for
  4398. :meth:`_expression.Select.with_only_columns`
  4399. for guidelines on adding /replacing the columns of a
  4400. :class:`_expression.Select` object.
  4401. """
  4402. self._reset_memoizations()
  4403. self._raw_columns = self._raw_columns + [
  4404. coercions.expect(
  4405. roles.ColumnsClauseRole, column, apply_propagate_attrs=self
  4406. )
  4407. for column in columns
  4408. ]
  4409. def _set_entities(self, entities):
  4410. self._raw_columns = [
  4411. coercions.expect(
  4412. roles.ColumnsClauseRole, ent, apply_propagate_attrs=self
  4413. )
  4414. for ent in util.to_list(entities)
  4415. ]
  4416. @util.deprecated(
  4417. "1.4",
  4418. "The :meth:`_expression.Select.column` method is deprecated and will "
  4419. "be removed in a future release. Please use "
  4420. ":meth:`_expression.Select.add_columns`",
  4421. )
  4422. def column(self, column):
  4423. """Return a new :func:`_expression.select` construct with
  4424. the given column expression added to its columns clause.
  4425. E.g.::
  4426. my_select = my_select.column(table.c.new_column)
  4427. See the documentation for
  4428. :meth:`_expression.Select.with_only_columns`
  4429. for guidelines on adding /replacing the columns of a
  4430. :class:`_expression.Select` object.
  4431. """
  4432. return self.add_columns(column)
  4433. @util.preload_module("sqlalchemy.sql.util")
  4434. def reduce_columns(self, only_synonyms=True):
  4435. """Return a new :func:`_expression.select` construct with redundantly
  4436. named, equivalently-valued columns removed from the columns clause.
  4437. "Redundant" here means two columns where one refers to the
  4438. other either based on foreign key, or via a simple equality
  4439. comparison in the WHERE clause of the statement. The primary purpose
  4440. of this method is to automatically construct a select statement
  4441. with all uniquely-named columns, without the need to use
  4442. table-qualified labels as
  4443. :meth:`_expression.Select.set_label_style`
  4444. does.
  4445. When columns are omitted based on foreign key, the referred-to
  4446. column is the one that's kept. When columns are omitted based on
  4447. WHERE equivalence, the first column in the columns clause is the
  4448. one that's kept.
  4449. :param only_synonyms: when True, limit the removal of columns
  4450. to those which have the same name as the equivalent. Otherwise,
  4451. all columns that are equivalent to another are removed.
  4452. """
  4453. return self.with_only_columns(
  4454. *util.preloaded.sql_util.reduce_columns(
  4455. self._all_selected_columns,
  4456. only_synonyms=only_synonyms,
  4457. *(self._where_criteria + self._from_obj)
  4458. )
  4459. )
  4460. @_generative
  4461. def with_only_columns(self, *columns, **kw):
  4462. r"""Return a new :func:`_expression.select` construct with its columns
  4463. clause replaced with the given columns.
  4464. By default, this method is exactly equivalent to as if the original
  4465. :func:`_expression.select` had been called with the given columns
  4466. clause. E.g. a statement::
  4467. s = select(table1.c.a, table1.c.b)
  4468. s = s.with_only_columns(table1.c.b)
  4469. should be exactly equivalent to::
  4470. s = select(table1.c.b)
  4471. In this mode of operation, :meth:`_sql.Select.with_only_columns`
  4472. will also dynamically alter the FROM clause of the
  4473. statement if it is not explicitly stated.
  4474. To maintain the existing set of FROMs including those implied by the
  4475. current columns clause, add the
  4476. :paramref:`_sql.Select.with_only_columns.maintain_column_froms`
  4477. parameter::
  4478. s = select(table1.c.a, table2.c.b)
  4479. s = s.with_only_columns(table1.c.a, maintain_column_froms=True)
  4480. The above parameter performs a transfer of the effective FROMs
  4481. in the columns collection to the :meth:`_sql.Select.select_from`
  4482. method, as though the following were invoked::
  4483. s = select(table1.c.a, table2.c.b)
  4484. s = s.select_from(table1, table2).with_only_columns(table1.c.a)
  4485. The :paramref:`_sql.Select.with_only_columns.maintain_column_froms`
  4486. parameter makes use of the :attr:`_sql.Select.columns_clause_froms`
  4487. collection and performs an operation equivalent to the following::
  4488. s = select(table1.c.a, table2.c.b)
  4489. s = s.select_from(*s.columns_clause_froms).with_only_columns(table1.c.a)
  4490. :param \*columns: column expressions to be used.
  4491. .. versionchanged:: 1.4 the :meth:`_sql.Select.with_only_columns`
  4492. method accepts the list of column expressions positionally;
  4493. passing the expressions as a list is deprecated.
  4494. :param maintain_column_froms: boolean parameter that will ensure the
  4495. FROM list implied from the current columns clause will be transferred
  4496. to the :meth:`_sql.Select.select_from` method first.
  4497. .. versionadded:: 1.4.23
  4498. """ # noqa: E501
  4499. # memoizations should be cleared here as of
  4500. # I95c560ffcbfa30b26644999412fb6a385125f663 , asserting this
  4501. # is the case for now.
  4502. self._assert_no_memoizations()
  4503. maintain_column_froms = kw.pop("maintain_column_froms", False)
  4504. if kw:
  4505. raise TypeError("unknown parameters: %s" % (", ".join(kw),))
  4506. if maintain_column_froms:
  4507. self.select_from.non_generative(self, *self.columns_clause_froms)
  4508. # then memoize the FROMs etc.
  4509. _MemoizedSelectEntities._generate_for_statement(self)
  4510. self._raw_columns = [
  4511. coercions.expect(roles.ColumnsClauseRole, c)
  4512. for c in coercions._expression_collection_was_a_list(
  4513. "columns", "Select.with_only_columns", columns
  4514. )
  4515. ]
  4516. @property
  4517. def whereclause(self):
  4518. """Return the completed WHERE clause for this
  4519. :class:`_expression.Select` statement.
  4520. This assembles the current collection of WHERE criteria
  4521. into a single :class:`_expression.BooleanClauseList` construct.
  4522. .. versionadded:: 1.4
  4523. """
  4524. return BooleanClauseList._construct_for_whereclause(
  4525. self._where_criteria
  4526. )
  4527. _whereclause = whereclause
  4528. @_generative
  4529. def where(self, *whereclause):
  4530. """Return a new :func:`_expression.select` construct with
  4531. the given expression added to
  4532. its WHERE clause, joined to the existing clause via AND, if any.
  4533. """
  4534. assert isinstance(self._where_criteria, tuple)
  4535. for criterion in whereclause:
  4536. where_criteria = coercions.expect(roles.WhereHavingRole, criterion)
  4537. self._where_criteria += (where_criteria,)
  4538. @_generative
  4539. def having(self, having):
  4540. """Return a new :func:`_expression.select` construct with
  4541. the given expression added to
  4542. its HAVING clause, joined to the existing clause via AND, if any.
  4543. """
  4544. self._having_criteria += (
  4545. coercions.expect(roles.WhereHavingRole, having),
  4546. )
  4547. @_generative
  4548. def distinct(self, *expr):
  4549. r"""Return a new :func:`_expression.select` construct which
  4550. will apply DISTINCT to its columns clause.
  4551. :param \*expr: optional column expressions. When present,
  4552. the PostgreSQL dialect will render a ``DISTINCT ON (<expressions>>)``
  4553. construct.
  4554. .. deprecated:: 1.4 Using \*expr in other dialects is deprecated
  4555. and will raise :class:`_exc.CompileError` in a future version.
  4556. """
  4557. if expr:
  4558. self._distinct = True
  4559. self._distinct_on = self._distinct_on + tuple(
  4560. coercions.expect(roles.ByOfRole, e) for e in expr
  4561. )
  4562. else:
  4563. self._distinct = True
  4564. @_generative
  4565. def select_from(self, *froms):
  4566. r"""Return a new :func:`_expression.select` construct with the
  4567. given FROM expression(s)
  4568. merged into its list of FROM objects.
  4569. E.g.::
  4570. table1 = table('t1', column('a'))
  4571. table2 = table('t2', column('b'))
  4572. s = select(table1.c.a).\
  4573. select_from(
  4574. table1.join(table2, table1.c.a==table2.c.b)
  4575. )
  4576. The "from" list is a unique set on the identity of each element,
  4577. so adding an already present :class:`_schema.Table`
  4578. or other selectable
  4579. will have no effect. Passing a :class:`_expression.Join` that refers
  4580. to an already present :class:`_schema.Table`
  4581. or other selectable will have
  4582. the effect of concealing the presence of that selectable as
  4583. an individual element in the rendered FROM list, instead
  4584. rendering it into a JOIN clause.
  4585. While the typical purpose of :meth:`_expression.Select.select_from`
  4586. is to
  4587. replace the default, derived FROM clause with a join, it can
  4588. also be called with individual table elements, multiple times
  4589. if desired, in the case that the FROM clause cannot be fully
  4590. derived from the columns clause::
  4591. select(func.count('*')).select_from(table1)
  4592. """
  4593. self._from_obj += tuple(
  4594. coercions.expect(
  4595. roles.FromClauseRole, fromclause, apply_propagate_attrs=self
  4596. )
  4597. for fromclause in froms
  4598. )
  4599. @_generative
  4600. def correlate(self, *fromclauses):
  4601. r"""Return a new :class:`_expression.Select`
  4602. which will correlate the given FROM
  4603. clauses to that of an enclosing :class:`_expression.Select`.
  4604. Calling this method turns off the :class:`_expression.Select` object's
  4605. default behavior of "auto-correlation". Normally, FROM elements
  4606. which appear in a :class:`_expression.Select`
  4607. that encloses this one via
  4608. its :term:`WHERE clause`, ORDER BY, HAVING or
  4609. :term:`columns clause` will be omitted from this
  4610. :class:`_expression.Select`
  4611. object's :term:`FROM clause`.
  4612. Setting an explicit correlation collection using the
  4613. :meth:`_expression.Select.correlate`
  4614. method provides a fixed list of FROM objects
  4615. that can potentially take place in this process.
  4616. When :meth:`_expression.Select.correlate`
  4617. is used to apply specific FROM clauses
  4618. for correlation, the FROM elements become candidates for
  4619. correlation regardless of how deeply nested this
  4620. :class:`_expression.Select`
  4621. object is, relative to an enclosing :class:`_expression.Select`
  4622. which refers to
  4623. the same FROM object. This is in contrast to the behavior of
  4624. "auto-correlation" which only correlates to an immediate enclosing
  4625. :class:`_expression.Select`.
  4626. Multi-level correlation ensures that the link
  4627. between enclosed and enclosing :class:`_expression.Select`
  4628. is always via
  4629. at least one WHERE/ORDER BY/HAVING/columns clause in order for
  4630. correlation to take place.
  4631. If ``None`` is passed, the :class:`_expression.Select`
  4632. object will correlate
  4633. none of its FROM entries, and all will render unconditionally
  4634. in the local FROM clause.
  4635. :param \*fromclauses: a list of one or more
  4636. :class:`_expression.FromClause`
  4637. constructs, or other compatible constructs (i.e. ORM-mapped
  4638. classes) to become part of the correlate collection.
  4639. .. seealso::
  4640. :meth:`_expression.Select.correlate_except`
  4641. :ref:`tutorial_scalar_subquery`
  4642. """
  4643. self._auto_correlate = False
  4644. if fromclauses and fromclauses[0] in {None, False}:
  4645. self._correlate = ()
  4646. else:
  4647. self._correlate = self._correlate + tuple(
  4648. coercions.expect(roles.FromClauseRole, f) for f in fromclauses
  4649. )
  4650. @_generative
  4651. def correlate_except(self, *fromclauses):
  4652. r"""Return a new :class:`_expression.Select`
  4653. which will omit the given FROM
  4654. clauses from the auto-correlation process.
  4655. Calling :meth:`_expression.Select.correlate_except` turns off the
  4656. :class:`_expression.Select` object's default behavior of
  4657. "auto-correlation" for the given FROM elements. An element
  4658. specified here will unconditionally appear in the FROM list, while
  4659. all other FROM elements remain subject to normal auto-correlation
  4660. behaviors.
  4661. If ``None`` is passed, the :class:`_expression.Select`
  4662. object will correlate
  4663. all of its FROM entries.
  4664. :param \*fromclauses: a list of one or more
  4665. :class:`_expression.FromClause`
  4666. constructs, or other compatible constructs (i.e. ORM-mapped
  4667. classes) to become part of the correlate-exception collection.
  4668. .. seealso::
  4669. :meth:`_expression.Select.correlate`
  4670. :ref:`tutorial_scalar_subquery`
  4671. """
  4672. self._auto_correlate = False
  4673. if fromclauses and fromclauses[0] in {None, False}:
  4674. self._correlate_except = ()
  4675. else:
  4676. self._correlate_except = (self._correlate_except or ()) + tuple(
  4677. coercions.expect(roles.FromClauseRole, f) for f in fromclauses
  4678. )
  4679. @HasMemoized.memoized_attribute
  4680. def selected_columns(self):
  4681. """A :class:`_expression.ColumnCollection`
  4682. representing the columns that
  4683. this SELECT statement or similar construct returns in its result set,
  4684. not including :class:`_sql.TextClause` constructs.
  4685. This collection differs from the :attr:`_expression.FromClause.columns`
  4686. collection of a :class:`_expression.FromClause` in that the columns
  4687. within this collection cannot be directly nested inside another SELECT
  4688. statement; a subquery must be applied first which provides for the
  4689. necessary parenthesization required by SQL.
  4690. For a :func:`_expression.select` construct, the collection here is
  4691. exactly what would be rendered inside the "SELECT" statement, and the
  4692. :class:`_expression.ColumnElement` objects are directly present as they
  4693. were given, e.g.::
  4694. col1 = column('q', Integer)
  4695. col2 = column('p', Integer)
  4696. stmt = select(col1, col2)
  4697. Above, ``stmt.selected_columns`` would be a collection that contains
  4698. the ``col1`` and ``col2`` objects directly. For a statement that is
  4699. against a :class:`_schema.Table` or other
  4700. :class:`_expression.FromClause`, the collection will use the
  4701. :class:`_expression.ColumnElement` objects that are in the
  4702. :attr:`_expression.FromClause.c` collection of the from element.
  4703. .. note::
  4704. The :attr:`_sql.Select.selected_columns` collection does not
  4705. include expressions established in the columns clause using the
  4706. :func:`_sql.text` construct; these are silently omitted from the
  4707. collection. To use plain textual column expressions inside of a
  4708. :class:`_sql.Select` construct, use the :func:`_sql.literal_column`
  4709. construct.
  4710. .. versionadded:: 1.4
  4711. """
  4712. # compare to SelectState._generate_columns_plus_names, which
  4713. # generates the actual names used in the SELECT string. that
  4714. # method is more complex because it also renders columns that are
  4715. # fully ambiguous, e.g. same column more than once.
  4716. conv = SelectState._column_naming_convention(self._label_style)
  4717. return ColumnCollection(
  4718. [
  4719. (conv(c), c)
  4720. for c in self._all_selected_columns
  4721. if not c._is_text_clause
  4722. ]
  4723. ).as_immutable()
  4724. @HasMemoized.memoized_attribute
  4725. def _all_selected_columns(self):
  4726. meth = SelectState.get_plugin_class(self).all_selected_columns
  4727. return list(meth(self))
  4728. def _ensure_disambiguated_names(self):
  4729. if self._label_style is LABEL_STYLE_NONE:
  4730. self = self.set_label_style(LABEL_STYLE_DISAMBIGUATE_ONLY)
  4731. return self
  4732. def _generate_columns_plus_names(self, anon_for_dupe_key, cols=None):
  4733. """Generate column names as rendered in a SELECT statement by
  4734. the compiler.
  4735. This is distinct from the _column_naming_convention generator that's
  4736. intended for population of .c collections and similar, which has
  4737. different rules. the collection returned here calls upon the
  4738. _column_naming_convention as well.
  4739. """
  4740. if cols is None:
  4741. cols = self._all_selected_columns
  4742. key_naming_convention = SelectState._column_naming_convention(
  4743. self._label_style
  4744. )
  4745. names = {}
  4746. result = []
  4747. result_append = result.append
  4748. table_qualified = self._label_style is LABEL_STYLE_TABLENAME_PLUS_COL
  4749. label_style_none = self._label_style is LABEL_STYLE_NONE
  4750. # a counter used for "dedupe" labels, which have double underscores
  4751. # in them and are never referred by name; they only act
  4752. # as positional placeholders. they need only be unique within
  4753. # the single columns clause they're rendered within (required by
  4754. # some dbs such as mysql). So their anon identity is tracked against
  4755. # a fixed counter rather than hash() identity.
  4756. dedupe_hash = 1
  4757. for c in cols:
  4758. repeated = False
  4759. if not c._render_label_in_columns_clause:
  4760. effective_name = (
  4761. required_label_name
  4762. ) = fallback_label_name = None
  4763. elif label_style_none:
  4764. effective_name = required_label_name = None
  4765. fallback_label_name = c._non_anon_label or c._anon_name_label
  4766. else:
  4767. if table_qualified:
  4768. required_label_name = (
  4769. effective_name
  4770. ) = fallback_label_name = c._tq_label
  4771. else:
  4772. effective_name = fallback_label_name = c._non_anon_label
  4773. required_label_name = None
  4774. if effective_name is None:
  4775. # it seems like this could be _proxy_key and we would
  4776. # not need _expression_label but it isn't
  4777. # giving us a clue when to use anon_label instead
  4778. expr_label = c._expression_label
  4779. if expr_label is None:
  4780. repeated = c._anon_name_label in names
  4781. names[c._anon_name_label] = c
  4782. effective_name = required_label_name = None
  4783. if repeated:
  4784. # here, "required_label_name" is sent as
  4785. # "None" and "fallback_label_name" is sent.
  4786. if table_qualified:
  4787. fallback_label_name = (
  4788. c._dedupe_anon_tq_label_idx(dedupe_hash)
  4789. )
  4790. dedupe_hash += 1
  4791. else:
  4792. fallback_label_name = c._dedupe_anon_label_idx(
  4793. dedupe_hash
  4794. )
  4795. dedupe_hash += 1
  4796. else:
  4797. fallback_label_name = c._anon_name_label
  4798. else:
  4799. required_label_name = (
  4800. effective_name
  4801. ) = fallback_label_name = expr_label
  4802. if effective_name is not None:
  4803. if effective_name in names:
  4804. # when looking to see if names[name] is the same column as
  4805. # c, use hash(), so that an annotated version of the column
  4806. # is seen as the same as the non-annotated
  4807. if hash(names[effective_name]) != hash(c):
  4808. # different column under the same name. apply
  4809. # disambiguating label
  4810. if table_qualified:
  4811. required_label_name = (
  4812. fallback_label_name
  4813. ) = c._anon_tq_label
  4814. else:
  4815. required_label_name = (
  4816. fallback_label_name
  4817. ) = c._anon_name_label
  4818. if anon_for_dupe_key and required_label_name in names:
  4819. # here, c._anon_tq_label is definitely unique to
  4820. # that column identity (or annotated version), so
  4821. # this should always be true.
  4822. # this is also an infrequent codepath because
  4823. # you need two levels of duplication to be here
  4824. assert hash(names[required_label_name]) == hash(c)
  4825. # the column under the disambiguating label is
  4826. # already present. apply the "dedupe" label to
  4827. # subsequent occurrences of the column so that the
  4828. # original stays non-ambiguous
  4829. if table_qualified:
  4830. required_label_name = (
  4831. fallback_label_name
  4832. ) = c._dedupe_anon_tq_label_idx(dedupe_hash)
  4833. dedupe_hash += 1
  4834. else:
  4835. required_label_name = (
  4836. fallback_label_name
  4837. ) = c._dedupe_anon_label_idx(dedupe_hash)
  4838. dedupe_hash += 1
  4839. repeated = True
  4840. else:
  4841. names[required_label_name] = c
  4842. elif anon_for_dupe_key:
  4843. # same column under the same name. apply the "dedupe"
  4844. # label so that the original stays non-ambiguous
  4845. if table_qualified:
  4846. required_label_name = (
  4847. fallback_label_name
  4848. ) = c._dedupe_anon_tq_label_idx(dedupe_hash)
  4849. dedupe_hash += 1
  4850. else:
  4851. required_label_name = (
  4852. fallback_label_name
  4853. ) = c._dedupe_anon_label_idx(dedupe_hash)
  4854. dedupe_hash += 1
  4855. repeated = True
  4856. else:
  4857. names[effective_name] = c
  4858. result_append(
  4859. (
  4860. # string label name, if non-None, must be rendered as a
  4861. # label, i.e. "AS <name>"
  4862. required_label_name,
  4863. # proxy_key that is to be part of the result map for this
  4864. # col. this is also the key in a fromclause.c or
  4865. # select.selected_columns collection
  4866. key_naming_convention(c),
  4867. # name that can be used to render an "AS <name>" when
  4868. # we have to render a label even though
  4869. # required_label_name was not given
  4870. fallback_label_name,
  4871. # the ColumnElement itself
  4872. c,
  4873. # True if this is a duplicate of a previous column
  4874. # in the list of columns
  4875. repeated,
  4876. )
  4877. )
  4878. return result
  4879. def _generate_fromclause_column_proxies(self, subquery):
  4880. """Generate column proxies to place in the exported ``.c``
  4881. collection of a subquery."""
  4882. prox = [
  4883. c._make_proxy(
  4884. subquery,
  4885. key=proxy_key,
  4886. name=required_label_name,
  4887. name_is_truncatable=True,
  4888. )
  4889. for (
  4890. required_label_name,
  4891. proxy_key,
  4892. fallback_label_name,
  4893. c,
  4894. repeated,
  4895. ) in (self._generate_columns_plus_names(False))
  4896. if not c._is_text_clause
  4897. ]
  4898. subquery._columns._populate_separate_keys(prox)
  4899. def _needs_parens_for_grouping(self):
  4900. return self._has_row_limiting_clause or bool(
  4901. self._order_by_clause.clauses
  4902. )
  4903. def self_group(self, against=None):
  4904. """Return a 'grouping' construct as per the
  4905. :class:`_expression.ClauseElement` specification.
  4906. This produces an element that can be embedded in an expression. Note
  4907. that this method is called automatically as needed when constructing
  4908. expressions and should not require explicit use.
  4909. """
  4910. if (
  4911. isinstance(against, CompoundSelect)
  4912. and not self._needs_parens_for_grouping()
  4913. ):
  4914. return self
  4915. else:
  4916. return SelectStatementGrouping(self)
  4917. def union(self, *other, **kwargs):
  4918. r"""Return a SQL ``UNION`` of this select() construct against
  4919. the given selectables provided as positional arguments.
  4920. :param \*other: one or more elements with which to create a
  4921. UNION.
  4922. .. versionchanged:: 1.4.28
  4923. multiple elements are now accepted.
  4924. :param \**kwargs: keyword arguments are forwarded to the constructor
  4925. for the newly created :class:`_sql.CompoundSelect` object.
  4926. """
  4927. return CompoundSelect._create_union(self, *other, **kwargs)
  4928. def union_all(self, *other, **kwargs):
  4929. r"""Return a SQL ``UNION ALL`` of this select() construct against
  4930. the given selectables provided as positional arguments.
  4931. :param \*other: one or more elements with which to create a
  4932. UNION.
  4933. .. versionchanged:: 1.4.28
  4934. multiple elements are now accepted.
  4935. :param \**kwargs: keyword arguments are forwarded to the constructor
  4936. for the newly created :class:`_sql.CompoundSelect` object.
  4937. """
  4938. return CompoundSelect._create_union_all(self, *other, **kwargs)
  4939. def except_(self, *other, **kwargs):
  4940. r"""Return a SQL ``EXCEPT`` of this select() construct against
  4941. the given selectable provided as positional arguments.
  4942. :param \*other: one or more elements with which to create a
  4943. UNION.
  4944. .. versionchanged:: 1.4.28
  4945. multiple elements are now accepted.
  4946. :param \**kwargs: keyword arguments are forwarded to the constructor
  4947. for the newly created :class:`_sql.CompoundSelect` object.
  4948. """
  4949. return CompoundSelect._create_except(self, *other, **kwargs)
  4950. def except_all(self, *other, **kwargs):
  4951. r"""Return a SQL ``EXCEPT ALL`` of this select() construct against
  4952. the given selectables provided as positional arguments.
  4953. :param \*other: one or more elements with which to create a
  4954. UNION.
  4955. .. versionchanged:: 1.4.28
  4956. multiple elements are now accepted.
  4957. :param \**kwargs: keyword arguments are forwarded to the constructor
  4958. for the newly created :class:`_sql.CompoundSelect` object.
  4959. """
  4960. return CompoundSelect._create_except_all(self, *other, **kwargs)
  4961. def intersect(self, *other, **kwargs):
  4962. r"""Return a SQL ``INTERSECT`` of this select() construct against
  4963. the given selectables provided as positional arguments.
  4964. :param \*other: one or more elements with which to create a
  4965. UNION.
  4966. .. versionchanged:: 1.4.28
  4967. multiple elements are now accepted.
  4968. :param \**kwargs: keyword arguments are forwarded to the constructor
  4969. for the newly created :class:`_sql.CompoundSelect` object.
  4970. """
  4971. return CompoundSelect._create_intersect(self, *other, **kwargs)
  4972. def intersect_all(self, *other, **kwargs):
  4973. r"""Return a SQL ``INTERSECT ALL`` of this select() construct
  4974. against the given selectables provided as positional arguments.
  4975. :param \*other: one or more elements with which to create a
  4976. UNION.
  4977. .. versionchanged:: 1.4.28
  4978. multiple elements are now accepted.
  4979. :param \**kwargs: keyword arguments are forwarded to the constructor
  4980. for the newly created :class:`_sql.CompoundSelect` object.
  4981. """
  4982. return CompoundSelect._create_intersect_all(self, *other, **kwargs)
  4983. @property
  4984. @util.deprecated_20(
  4985. ":attr:`.Executable.bind`",
  4986. alternative="Bound metadata is being removed as of SQLAlchemy 2.0.",
  4987. enable_warnings=False,
  4988. )
  4989. def bind(self):
  4990. """Returns the :class:`_engine.Engine` or :class:`_engine.Connection`
  4991. to which this :class:`.Executable` is bound, or None if none found.
  4992. """
  4993. if self._bind:
  4994. return self._bind
  4995. for item in self._iterate_from_elements():
  4996. if item._is_subquery and item.element is self:
  4997. raise exc.InvalidRequestError(
  4998. "select() construct refers to itself as a FROM"
  4999. )
  5000. e = item.bind
  5001. if e:
  5002. self._bind = e
  5003. return e
  5004. else:
  5005. break
  5006. for c in self._raw_columns:
  5007. e = c.bind
  5008. if e:
  5009. self._bind = e
  5010. return e
  5011. @bind.setter
  5012. def bind(self, bind):
  5013. self._bind = bind
  5014. class ScalarSelect(roles.InElementRole, Generative, Grouping):
  5015. """Represent a scalar subquery.
  5016. A :class:`_sql.ScalarSelect` is created by invoking the
  5017. :meth:`_sql.SelectBase.scalar_subquery` method. The object
  5018. then participates in other SQL expressions as a SQL column expression
  5019. within the :class:`_sql.ColumnElement` hierarchy.
  5020. .. seealso::
  5021. :meth:`_sql.SelectBase.scalar_subquery`
  5022. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  5023. """
  5024. _from_objects = []
  5025. _is_from_container = True
  5026. _is_implicitly_boolean = False
  5027. inherit_cache = True
  5028. def __init__(self, element):
  5029. self.element = element
  5030. self.type = element._scalar_type()
  5031. @property
  5032. def columns(self):
  5033. raise exc.InvalidRequestError(
  5034. "Scalar Select expression has no "
  5035. "columns; use this object directly "
  5036. "within a column-level expression."
  5037. )
  5038. c = columns
  5039. @_generative
  5040. def where(self, crit):
  5041. """Apply a WHERE clause to the SELECT statement referred to
  5042. by this :class:`_expression.ScalarSelect`.
  5043. """
  5044. self.element = self.element.where(crit)
  5045. def self_group(self, **kwargs):
  5046. return self
  5047. @_generative
  5048. def correlate(self, *fromclauses):
  5049. r"""Return a new :class:`_expression.ScalarSelect`
  5050. which will correlate the given FROM
  5051. clauses to that of an enclosing :class:`_expression.Select`.
  5052. This method is mirrored from the :meth:`_sql.Select.correlate` method
  5053. of the underlying :class:`_sql.Select`. The method applies the
  5054. :meth:_sql.Select.correlate` method, then returns a new
  5055. :class:`_sql.ScalarSelect` against that statement.
  5056. .. versionadded:: 1.4 Previously, the
  5057. :meth:`_sql.ScalarSelect.correlate`
  5058. method was only available from :class:`_sql.Select`.
  5059. :param \*fromclauses: a list of one or more
  5060. :class:`_expression.FromClause`
  5061. constructs, or other compatible constructs (i.e. ORM-mapped
  5062. classes) to become part of the correlate collection.
  5063. .. seealso::
  5064. :meth:`_expression.ScalarSelect.correlate_except`
  5065. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  5066. """
  5067. self.element = self.element.correlate(*fromclauses)
  5068. @_generative
  5069. def correlate_except(self, *fromclauses):
  5070. r"""Return a new :class:`_expression.ScalarSelect`
  5071. which will omit the given FROM
  5072. clauses from the auto-correlation process.
  5073. This method is mirrored from the
  5074. :meth:`_sql.Select.correlate_except` method of the underlying
  5075. :class:`_sql.Select`. The method applies the
  5076. :meth:_sql.Select.correlate_except` method, then returns a new
  5077. :class:`_sql.ScalarSelect` against that statement.
  5078. .. versionadded:: 1.4 Previously, the
  5079. :meth:`_sql.ScalarSelect.correlate_except`
  5080. method was only available from :class:`_sql.Select`.
  5081. :param \*fromclauses: a list of one or more
  5082. :class:`_expression.FromClause`
  5083. constructs, or other compatible constructs (i.e. ORM-mapped
  5084. classes) to become part of the correlate-exception collection.
  5085. .. seealso::
  5086. :meth:`_expression.ScalarSelect.correlate`
  5087. :ref:`tutorial_scalar_subquery` - in the 2.0 tutorial
  5088. """
  5089. self.element = self.element.correlate_except(*fromclauses)
  5090. class Exists(UnaryExpression):
  5091. """Represent an ``EXISTS`` clause.
  5092. See :func:`_sql.exists` for a description of usage.
  5093. An ``EXISTS`` clause can also be constructed from a :func:`_sql.select`
  5094. instance by calling :meth:`_sql.SelectBase.exists`.
  5095. """
  5096. _from_objects = []
  5097. inherit_cache = True
  5098. def __init__(self, *args, **kwargs):
  5099. """Construct a new :class:`_expression.Exists` construct.
  5100. The :func:`_sql.exists` can be invoked by itself to produce an
  5101. :class:`_sql.Exists` construct, which will accept simple WHERE
  5102. criteria::
  5103. exists_criteria = exists().where(table1.c.col1 == table2.c.col2)
  5104. However, for greater flexibility in constructing the SELECT, an
  5105. existing :class:`_sql.Select` construct may be converted to an
  5106. :class:`_sql.Exists`, most conveniently by making use of the
  5107. :meth:`_sql.SelectBase.exists` method::
  5108. exists_criteria = (
  5109. select(table2.c.col2).
  5110. where(table1.c.col1 == table2.c.col2).
  5111. exists()
  5112. )
  5113. The EXISTS criteria is then used inside of an enclosing SELECT::
  5114. stmt = select(table1.c.col1).where(exists_criteria)
  5115. The above statement will then be of the form::
  5116. SELECT col1 FROM table1 WHERE EXISTS
  5117. (SELECT table2.col2 FROM table2 WHERE table2.col2 = table1.col1)
  5118. .. seealso::
  5119. :ref:`tutorial_exists` - in the :term:`2.0 style` tutorial.
  5120. :meth:`_sql.SelectBase.exists` - method to transform a ``SELECT`` to an
  5121. ``EXISTS`` clause.
  5122. """ # noqa: E501
  5123. if args and isinstance(args[0], (SelectBase, ScalarSelect)):
  5124. s = args[0]
  5125. else:
  5126. if not args:
  5127. args = (literal_column("*"),)
  5128. s = Select._create(*args, **kwargs).scalar_subquery()
  5129. UnaryExpression.__init__(
  5130. self,
  5131. s,
  5132. operator=operators.exists,
  5133. type_=type_api.BOOLEANTYPE,
  5134. wraps_column_expression=True,
  5135. )
  5136. def _regroup(self, fn):
  5137. element = self.element._ungroup()
  5138. element = fn(element)
  5139. return element.self_group(against=operators.exists)
  5140. @util.deprecated_params(
  5141. whereclause=(
  5142. "2.0",
  5143. "The :paramref:`_sql.Exists.select().whereclause` parameter "
  5144. "is deprecated and will be removed in version 2.0. "
  5145. "Please make use "
  5146. "of the :meth:`.Select.where` "
  5147. "method to add WHERE criteria to the SELECT statement.",
  5148. ),
  5149. kwargs=(
  5150. "2.0",
  5151. "The :meth:`_sql.Exists.select` method will no longer accept "
  5152. "keyword arguments in version 2.0. "
  5153. "Please use generative methods from the "
  5154. ":class:`_sql.Select` construct in order to apply additional "
  5155. "modifications.",
  5156. ),
  5157. )
  5158. def select(self, whereclause=None, **kwargs):
  5159. r"""Return a SELECT of this :class:`_expression.Exists`.
  5160. e.g.::
  5161. stmt = exists(some_table.c.id).where(some_table.c.id == 5).select()
  5162. This will produce a statement resembling::
  5163. SELECT EXISTS (SELECT id FROM some_table WHERE some_table = :param) AS anon_1
  5164. :param whereclause: a WHERE clause, equivalent to calling the
  5165. :meth:`_sql.Select.where` method.
  5166. :param **kwargs: additional keyword arguments are passed to the
  5167. legacy constructor for :class:`_sql.Select` described at
  5168. :meth:`_sql.Select.create_legacy_select`.
  5169. .. seealso::
  5170. :func:`_expression.select` - general purpose
  5171. method which allows for arbitrary column lists.
  5172. """ # noqa
  5173. if whereclause is not None:
  5174. kwargs["whereclause"] = whereclause
  5175. return Select._create_select_from_fromclause(self, [self], **kwargs)
  5176. def correlate(self, *fromclause):
  5177. """Apply correlation to the subquery noted by this
  5178. :class:`_sql.Exists`.
  5179. .. seealso::
  5180. :meth:`_sql.ScalarSelect.correlate`
  5181. """
  5182. e = self._clone()
  5183. e.element = self._regroup(
  5184. lambda element: element.correlate(*fromclause)
  5185. )
  5186. return e
  5187. def correlate_except(self, *fromclause):
  5188. """Apply correlation to the subquery noted by this
  5189. :class:`_sql.Exists`.
  5190. .. seealso::
  5191. :meth:`_sql.ScalarSelect.correlate_except`
  5192. """
  5193. e = self._clone()
  5194. e.element = self._regroup(
  5195. lambda element: element.correlate_except(*fromclause)
  5196. )
  5197. return e
  5198. def select_from(self, *froms):
  5199. """Return a new :class:`_expression.Exists` construct,
  5200. applying the given
  5201. expression to the :meth:`_expression.Select.select_from`
  5202. method of the select
  5203. statement contained.
  5204. .. note:: it is typically preferable to build a :class:`_sql.Select`
  5205. statement first, including the desired WHERE clause, then use the
  5206. :meth:`_sql.SelectBase.exists` method to produce an
  5207. :class:`_sql.Exists` object at once.
  5208. """
  5209. e = self._clone()
  5210. e.element = self._regroup(lambda element: element.select_from(*froms))
  5211. return e
  5212. def where(self, *clause):
  5213. """Return a new :func:`_expression.exists` construct with the
  5214. given expression added to
  5215. its WHERE clause, joined to the existing clause via AND, if any.
  5216. .. note:: it is typically preferable to build a :class:`_sql.Select`
  5217. statement first, including the desired WHERE clause, then use the
  5218. :meth:`_sql.SelectBase.exists` method to produce an
  5219. :class:`_sql.Exists` object at once.
  5220. """
  5221. e = self._clone()
  5222. e.element = self._regroup(lambda element: element.where(*clause))
  5223. return e
  5224. class TextualSelect(SelectBase):
  5225. """Wrap a :class:`_expression.TextClause` construct within a
  5226. :class:`_expression.SelectBase`
  5227. interface.
  5228. This allows the :class:`_expression.TextClause` object to gain a
  5229. ``.c`` collection
  5230. and other FROM-like capabilities such as
  5231. :meth:`_expression.FromClause.alias`,
  5232. :meth:`_expression.SelectBase.cte`, etc.
  5233. The :class:`_expression.TextualSelect` construct is produced via the
  5234. :meth:`_expression.TextClause.columns`
  5235. method - see that method for details.
  5236. .. versionchanged:: 1.4 the :class:`_expression.TextualSelect`
  5237. class was renamed
  5238. from ``TextAsFrom``, to more correctly suit its role as a
  5239. SELECT-oriented object and not a FROM clause.
  5240. .. seealso::
  5241. :func:`_expression.text`
  5242. :meth:`_expression.TextClause.columns` - primary creation interface.
  5243. """
  5244. __visit_name__ = "textual_select"
  5245. _label_style = LABEL_STYLE_NONE
  5246. _traverse_internals = (
  5247. [
  5248. ("element", InternalTraversal.dp_clauseelement),
  5249. ("column_args", InternalTraversal.dp_clauseelement_list),
  5250. ]
  5251. + SupportsCloneAnnotations._clone_annotations_traverse_internals
  5252. + HasCTE._has_ctes_traverse_internals
  5253. )
  5254. _is_textual = True
  5255. is_text = True
  5256. is_select = True
  5257. def __init__(self, text, columns, positional=False):
  5258. self.element = text
  5259. # convert for ORM attributes->columns, etc
  5260. self.column_args = [
  5261. coercions.expect(roles.ColumnsClauseRole, c) for c in columns
  5262. ]
  5263. self.positional = positional
  5264. @HasMemoized.memoized_attribute
  5265. def selected_columns(self):
  5266. """A :class:`_expression.ColumnCollection`
  5267. representing the columns that
  5268. this SELECT statement or similar construct returns in its result set,
  5269. not including :class:`_sql.TextClause` constructs.
  5270. This collection differs from the :attr:`_expression.FromClause.columns`
  5271. collection of a :class:`_expression.FromClause` in that the columns
  5272. within this collection cannot be directly nested inside another SELECT
  5273. statement; a subquery must be applied first which provides for the
  5274. necessary parenthesization required by SQL.
  5275. For a :class:`_expression.TextualSelect` construct, the collection
  5276. contains the :class:`_expression.ColumnElement` objects that were
  5277. passed to the constructor, typically via the
  5278. :meth:`_expression.TextClause.columns` method.
  5279. .. versionadded:: 1.4
  5280. """
  5281. return ColumnCollection(
  5282. (c.key, c) for c in self.column_args
  5283. ).as_immutable()
  5284. @property
  5285. def _all_selected_columns(self):
  5286. return self.column_args
  5287. def _set_label_style(self, style):
  5288. return self
  5289. def _ensure_disambiguated_names(self):
  5290. return self
  5291. @property
  5292. def _bind(self):
  5293. return self.element._bind
  5294. @_generative
  5295. def bindparams(self, *binds, **bind_as_values):
  5296. self.element = self.element.bindparams(*binds, **bind_as_values)
  5297. def _generate_fromclause_column_proxies(self, fromclause):
  5298. fromclause._columns._populate_separate_keys(
  5299. c._make_proxy(fromclause) for c in self.column_args
  5300. )
  5301. def _scalar_type(self):
  5302. return self.column_args[0].type
  5303. TextAsFrom = TextualSelect
  5304. """Backwards compatibility with the previous name"""
  5305. class AnnotatedFromClause(Annotated):
  5306. def __init__(self, element, values):
  5307. # force FromClause to generate their internal
  5308. # collections into __dict__
  5309. element.c
  5310. Annotated.__init__(self, element, values)