selectable.py 228 KB

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