selectable.py 236 KB

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