compiler.py 274 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946
  1. # sql/compiler.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: allow-untyped-defs, allow-untyped-calls
  8. """Base SQL and DDL compiler implementations.
  9. Classes provided include:
  10. :class:`.compiler.SQLCompiler` - renders SQL
  11. strings
  12. :class:`.compiler.DDLCompiler` - renders DDL
  13. (data definition language) strings
  14. :class:`.compiler.GenericTypeCompiler` - renders
  15. type specification strings.
  16. To generate user-defined SQL strings, see
  17. :doc:`/ext/compiler`.
  18. """
  19. from __future__ import annotations
  20. import collections
  21. import collections.abc as collections_abc
  22. import contextlib
  23. from enum import IntEnum
  24. import functools
  25. import itertools
  26. import operator
  27. import re
  28. from time import perf_counter
  29. import typing
  30. from typing import Any
  31. from typing import Callable
  32. from typing import cast
  33. from typing import ClassVar
  34. from typing import Dict
  35. from typing import FrozenSet
  36. from typing import Iterable
  37. from typing import Iterator
  38. from typing import List
  39. from typing import Mapping
  40. from typing import MutableMapping
  41. from typing import NamedTuple
  42. from typing import NoReturn
  43. from typing import Optional
  44. from typing import Pattern
  45. from typing import Sequence
  46. from typing import Set
  47. from typing import Tuple
  48. from typing import Type
  49. from typing import TYPE_CHECKING
  50. from typing import Union
  51. from . import base
  52. from . import coercions
  53. from . import crud
  54. from . import elements
  55. from . import functions
  56. from . import operators
  57. from . import roles
  58. from . import schema
  59. from . import selectable
  60. from . import sqltypes
  61. from . import util as sql_util
  62. from ._typing import is_column_element
  63. from ._typing import is_dml
  64. from .base import _de_clone
  65. from .base import _from_objects
  66. from .base import _NONE_NAME
  67. from .base import _SentinelDefaultCharacterization
  68. from .base import NO_ARG
  69. from .elements import quoted_name
  70. from .sqltypes import TupleType
  71. from .visitors import prefix_anon_map
  72. from .. import exc
  73. from .. import util
  74. from ..util import FastIntFlag
  75. from ..util.typing import Literal
  76. from ..util.typing import Protocol
  77. from ..util.typing import Self
  78. from ..util.typing import TypedDict
  79. if typing.TYPE_CHECKING:
  80. from .annotation import _AnnotationDict
  81. from .base import _AmbiguousTableNameMap
  82. from .base import CompileState
  83. from .base import Executable
  84. from .cache_key import CacheKey
  85. from .ddl import ExecutableDDLElement
  86. from .dml import Insert
  87. from .dml import Update
  88. from .dml import UpdateBase
  89. from .dml import UpdateDMLState
  90. from .dml import ValuesBase
  91. from .elements import _truncated_label
  92. from .elements import BinaryExpression
  93. from .elements import BindParameter
  94. from .elements import ClauseElement
  95. from .elements import ColumnClause
  96. from .elements import ColumnElement
  97. from .elements import False_
  98. from .elements import Label
  99. from .elements import Null
  100. from .elements import True_
  101. from .functions import Function
  102. from .schema import Column
  103. from .schema import Constraint
  104. from .schema import ForeignKeyConstraint
  105. from .schema import Index
  106. from .schema import PrimaryKeyConstraint
  107. from .schema import Table
  108. from .schema import UniqueConstraint
  109. from .selectable import _ColumnsClauseElement
  110. from .selectable import AliasedReturnsRows
  111. from .selectable import CompoundSelectState
  112. from .selectable import CTE
  113. from .selectable import FromClause
  114. from .selectable import NamedFromClause
  115. from .selectable import ReturnsRows
  116. from .selectable import Select
  117. from .selectable import SelectState
  118. from .type_api import _BindProcessorType
  119. from .type_api import TypeDecorator
  120. from .type_api import TypeEngine
  121. from .type_api import UserDefinedType
  122. from .visitors import Visitable
  123. from ..engine.cursor import CursorResultMetaData
  124. from ..engine.interfaces import _CoreSingleExecuteParams
  125. from ..engine.interfaces import _DBAPIAnyExecuteParams
  126. from ..engine.interfaces import _DBAPIMultiExecuteParams
  127. from ..engine.interfaces import _DBAPISingleExecuteParams
  128. from ..engine.interfaces import _ExecuteOptions
  129. from ..engine.interfaces import _GenericSetInputSizesType
  130. from ..engine.interfaces import _MutableCoreSingleExecuteParams
  131. from ..engine.interfaces import Dialect
  132. from ..engine.interfaces import SchemaTranslateMapType
  133. _FromHintsType = Dict["FromClause", str]
  134. RESERVED_WORDS = {
  135. "all",
  136. "analyse",
  137. "analyze",
  138. "and",
  139. "any",
  140. "array",
  141. "as",
  142. "asc",
  143. "asymmetric",
  144. "authorization",
  145. "between",
  146. "binary",
  147. "both",
  148. "case",
  149. "cast",
  150. "check",
  151. "collate",
  152. "column",
  153. "constraint",
  154. "create",
  155. "cross",
  156. "current_date",
  157. "current_role",
  158. "current_time",
  159. "current_timestamp",
  160. "current_user",
  161. "default",
  162. "deferrable",
  163. "desc",
  164. "distinct",
  165. "do",
  166. "else",
  167. "end",
  168. "except",
  169. "false",
  170. "for",
  171. "foreign",
  172. "freeze",
  173. "from",
  174. "full",
  175. "grant",
  176. "group",
  177. "having",
  178. "ilike",
  179. "in",
  180. "initially",
  181. "inner",
  182. "intersect",
  183. "into",
  184. "is",
  185. "isnull",
  186. "join",
  187. "leading",
  188. "left",
  189. "like",
  190. "limit",
  191. "localtime",
  192. "localtimestamp",
  193. "natural",
  194. "new",
  195. "not",
  196. "notnull",
  197. "null",
  198. "off",
  199. "offset",
  200. "old",
  201. "on",
  202. "only",
  203. "or",
  204. "order",
  205. "outer",
  206. "overlaps",
  207. "placing",
  208. "primary",
  209. "references",
  210. "right",
  211. "select",
  212. "session_user",
  213. "set",
  214. "similar",
  215. "some",
  216. "symmetric",
  217. "table",
  218. "then",
  219. "to",
  220. "trailing",
  221. "true",
  222. "union",
  223. "unique",
  224. "user",
  225. "using",
  226. "verbose",
  227. "when",
  228. "where",
  229. }
  230. LEGAL_CHARACTERS = re.compile(r"^[A-Z0-9_$]+$", re.I)
  231. LEGAL_CHARACTERS_PLUS_SPACE = re.compile(r"^[A-Z0-9_ $]+$", re.I)
  232. ILLEGAL_INITIAL_CHARACTERS = {str(x) for x in range(0, 10)}.union(["$"])
  233. FK_ON_DELETE = re.compile(
  234. r"^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$", re.I
  235. )
  236. FK_ON_UPDATE = re.compile(
  237. r"^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$", re.I
  238. )
  239. FK_INITIALLY = re.compile(r"^(?:DEFERRED|IMMEDIATE)$", re.I)
  240. BIND_PARAMS = re.compile(r"(?<![:\w\$\x5c]):([\w\$]+)(?![:\w\$])", re.UNICODE)
  241. BIND_PARAMS_ESC = re.compile(r"\x5c(:[\w\$]*)(?![:\w\$])", re.UNICODE)
  242. _pyformat_template = "%%(%(name)s)s"
  243. BIND_TEMPLATES = {
  244. "pyformat": _pyformat_template,
  245. "qmark": "?",
  246. "format": "%%s",
  247. "numeric": ":[_POSITION]",
  248. "numeric_dollar": "$[_POSITION]",
  249. "named": ":%(name)s",
  250. }
  251. OPERATORS = {
  252. # binary
  253. operators.and_: " AND ",
  254. operators.or_: " OR ",
  255. operators.add: " + ",
  256. operators.mul: " * ",
  257. operators.sub: " - ",
  258. operators.mod: " % ",
  259. operators.neg: "-",
  260. operators.lt: " < ",
  261. operators.le: " <= ",
  262. operators.ne: " != ",
  263. operators.gt: " > ",
  264. operators.ge: " >= ",
  265. operators.eq: " = ",
  266. operators.is_distinct_from: " IS DISTINCT FROM ",
  267. operators.is_not_distinct_from: " IS NOT DISTINCT FROM ",
  268. operators.concat_op: " || ",
  269. operators.match_op: " MATCH ",
  270. operators.not_match_op: " NOT MATCH ",
  271. operators.in_op: " IN ",
  272. operators.not_in_op: " NOT IN ",
  273. operators.comma_op: ", ",
  274. operators.from_: " FROM ",
  275. operators.as_: " AS ",
  276. operators.is_: " IS ",
  277. operators.is_not: " IS NOT ",
  278. operators.collate: " COLLATE ",
  279. # unary
  280. operators.exists: "EXISTS ",
  281. operators.distinct_op: "DISTINCT ",
  282. operators.inv: "NOT ",
  283. operators.any_op: "ANY ",
  284. operators.all_op: "ALL ",
  285. # modifiers
  286. operators.desc_op: " DESC",
  287. operators.asc_op: " ASC",
  288. operators.nulls_first_op: " NULLS FIRST",
  289. operators.nulls_last_op: " NULLS LAST",
  290. # bitwise
  291. operators.bitwise_xor_op: " ^ ",
  292. operators.bitwise_or_op: " | ",
  293. operators.bitwise_and_op: " & ",
  294. operators.bitwise_not_op: "~",
  295. operators.bitwise_lshift_op: " << ",
  296. operators.bitwise_rshift_op: " >> ",
  297. }
  298. FUNCTIONS: Dict[Type[Function[Any]], str] = {
  299. functions.coalesce: "coalesce",
  300. functions.current_date: "CURRENT_DATE",
  301. functions.current_time: "CURRENT_TIME",
  302. functions.current_timestamp: "CURRENT_TIMESTAMP",
  303. functions.current_user: "CURRENT_USER",
  304. functions.localtime: "LOCALTIME",
  305. functions.localtimestamp: "LOCALTIMESTAMP",
  306. functions.random: "random",
  307. functions.sysdate: "sysdate",
  308. functions.session_user: "SESSION_USER",
  309. functions.user: "USER",
  310. functions.cube: "CUBE",
  311. functions.rollup: "ROLLUP",
  312. functions.grouping_sets: "GROUPING SETS",
  313. }
  314. EXTRACT_MAP = {
  315. "month": "month",
  316. "day": "day",
  317. "year": "year",
  318. "second": "second",
  319. "hour": "hour",
  320. "doy": "doy",
  321. "minute": "minute",
  322. "quarter": "quarter",
  323. "dow": "dow",
  324. "week": "week",
  325. "epoch": "epoch",
  326. "milliseconds": "milliseconds",
  327. "microseconds": "microseconds",
  328. "timezone_hour": "timezone_hour",
  329. "timezone_minute": "timezone_minute",
  330. }
  331. COMPOUND_KEYWORDS = {
  332. selectable._CompoundSelectKeyword.UNION: "UNION",
  333. selectable._CompoundSelectKeyword.UNION_ALL: "UNION ALL",
  334. selectable._CompoundSelectKeyword.EXCEPT: "EXCEPT",
  335. selectable._CompoundSelectKeyword.EXCEPT_ALL: "EXCEPT ALL",
  336. selectable._CompoundSelectKeyword.INTERSECT: "INTERSECT",
  337. selectable._CompoundSelectKeyword.INTERSECT_ALL: "INTERSECT ALL",
  338. }
  339. class ResultColumnsEntry(NamedTuple):
  340. """Tracks a column expression that is expected to be represented
  341. in the result rows for this statement.
  342. This normally refers to the columns clause of a SELECT statement
  343. but may also refer to a RETURNING clause, as well as for dialect-specific
  344. emulations.
  345. """
  346. keyname: str
  347. """string name that's expected in cursor.description"""
  348. name: str
  349. """column name, may be labeled"""
  350. objects: Tuple[Any, ...]
  351. """sequence of objects that should be able to locate this column
  352. in a RowMapping. This is typically string names and aliases
  353. as well as Column objects.
  354. """
  355. type: TypeEngine[Any]
  356. """Datatype to be associated with this column. This is where
  357. the "result processing" logic directly links the compiled statement
  358. to the rows that come back from the cursor.
  359. """
  360. class _ResultMapAppender(Protocol):
  361. def __call__(
  362. self,
  363. keyname: str,
  364. name: str,
  365. objects: Sequence[Any],
  366. type_: TypeEngine[Any],
  367. ) -> None: ...
  368. # integer indexes into ResultColumnsEntry used by cursor.py.
  369. # some profiling showed integer access faster than named tuple
  370. RM_RENDERED_NAME: Literal[0] = 0
  371. RM_NAME: Literal[1] = 1
  372. RM_OBJECTS: Literal[2] = 2
  373. RM_TYPE: Literal[3] = 3
  374. class _BaseCompilerStackEntry(TypedDict):
  375. asfrom_froms: Set[FromClause]
  376. correlate_froms: Set[FromClause]
  377. selectable: ReturnsRows
  378. class _CompilerStackEntry(_BaseCompilerStackEntry, total=False):
  379. compile_state: CompileState
  380. need_result_map_for_nested: bool
  381. need_result_map_for_compound: bool
  382. select_0: ReturnsRows
  383. insert_from_select: Select[Any]
  384. class ExpandedState(NamedTuple):
  385. """represents state to use when producing "expanded" and
  386. "post compile" bound parameters for a statement.
  387. "expanded" parameters are parameters that are generated at
  388. statement execution time to suit a number of parameters passed, the most
  389. prominent example being the individual elements inside of an IN expression.
  390. "post compile" parameters are parameters where the SQL literal value
  391. will be rendered into the SQL statement at execution time, rather than
  392. being passed as separate parameters to the driver.
  393. To create an :class:`.ExpandedState` instance, use the
  394. :meth:`.SQLCompiler.construct_expanded_state` method on any
  395. :class:`.SQLCompiler` instance.
  396. """
  397. statement: str
  398. """String SQL statement with parameters fully expanded"""
  399. parameters: _CoreSingleExecuteParams
  400. """Parameter dictionary with parameters fully expanded.
  401. For a statement that uses named parameters, this dictionary will map
  402. exactly to the names in the statement. For a statement that uses
  403. positional parameters, the :attr:`.ExpandedState.positional_parameters`
  404. will yield a tuple with the positional parameter set.
  405. """
  406. processors: Mapping[str, _BindProcessorType[Any]]
  407. """mapping of bound value processors"""
  408. positiontup: Optional[Sequence[str]]
  409. """Sequence of string names indicating the order of positional
  410. parameters"""
  411. parameter_expansion: Mapping[str, List[str]]
  412. """Mapping representing the intermediary link from original parameter
  413. name to list of "expanded" parameter names, for those parameters that
  414. were expanded."""
  415. @property
  416. def positional_parameters(self) -> Tuple[Any, ...]:
  417. """Tuple of positional parameters, for statements that were compiled
  418. using a positional paramstyle.
  419. """
  420. if self.positiontup is None:
  421. raise exc.InvalidRequestError(
  422. "statement does not use a positional paramstyle"
  423. )
  424. return tuple(self.parameters[key] for key in self.positiontup)
  425. @property
  426. def additional_parameters(self) -> _CoreSingleExecuteParams:
  427. """synonym for :attr:`.ExpandedState.parameters`."""
  428. return self.parameters
  429. class _InsertManyValues(NamedTuple):
  430. """represents state to use for executing an "insertmanyvalues" statement.
  431. The primary consumers of this object are the
  432. :meth:`.SQLCompiler._deliver_insertmanyvalues_batches` and
  433. :meth:`.DefaultDialect._deliver_insertmanyvalues_batches` methods.
  434. .. versionadded:: 2.0
  435. """
  436. is_default_expr: bool
  437. """if True, the statement is of the form
  438. ``INSERT INTO TABLE DEFAULT VALUES``, and can't be rewritten as a "batch"
  439. """
  440. single_values_expr: str
  441. """The rendered "values" clause of the INSERT statement.
  442. This is typically the parenthesized section e.g. "(?, ?, ?)" or similar.
  443. The insertmanyvalues logic uses this string as a search and replace
  444. target.
  445. """
  446. insert_crud_params: List[crud._CrudParamElementStr]
  447. """List of Column / bind names etc. used while rewriting the statement"""
  448. num_positional_params_counted: int
  449. """the number of bound parameters in a single-row statement.
  450. This count may be larger or smaller than the actual number of columns
  451. targeted in the INSERT, as it accommodates for SQL expressions
  452. in the values list that may have zero or more parameters embedded
  453. within them.
  454. This count is part of what's used to organize rewritten parameter lists
  455. when batching.
  456. """
  457. sort_by_parameter_order: bool = False
  458. """if the deterministic_returnined_order parameter were used on the
  459. insert.
  460. All of the attributes following this will only be used if this is True.
  461. """
  462. includes_upsert_behaviors: bool = False
  463. """if True, we have to accommodate for upsert behaviors.
  464. This will in some cases downgrade "insertmanyvalues" that requests
  465. deterministic ordering.
  466. """
  467. sentinel_columns: Optional[Sequence[Column[Any]]] = None
  468. """List of sentinel columns that were located.
  469. This list is only here if the INSERT asked for
  470. sort_by_parameter_order=True,
  471. and dialect-appropriate sentinel columns were located.
  472. .. versionadded:: 2.0.10
  473. """
  474. num_sentinel_columns: int = 0
  475. """how many sentinel columns are in the above list, if any.
  476. This is the same as
  477. ``len(sentinel_columns) if sentinel_columns is not None else 0``
  478. """
  479. sentinel_param_keys: Optional[Sequence[str]] = None
  480. """parameter str keys in each param dictionary / tuple
  481. that would link to the client side "sentinel" values for that row, which
  482. we can use to match up parameter sets to result rows.
  483. This is only present if sentinel_columns is present and the INSERT
  484. statement actually refers to client side values for these sentinel
  485. columns.
  486. .. versionadded:: 2.0.10
  487. .. versionchanged:: 2.0.29 - the sequence is now string dictionary keys
  488. only, used against the "compiled parameteters" collection before
  489. the parameters were converted by bound parameter processors
  490. """
  491. implicit_sentinel: bool = False
  492. """if True, we have exactly one sentinel column and it uses a server side
  493. value, currently has to generate an incrementing integer value.
  494. The dialect in question would have asserted that it supports receiving
  495. these values back and sorting on that value as a means of guaranteeing
  496. correlation with the incoming parameter list.
  497. .. versionadded:: 2.0.10
  498. """
  499. embed_values_counter: bool = False
  500. """Whether to embed an incrementing integer counter in each parameter
  501. set within the VALUES clause as parameters are batched over.
  502. This is only used for a specific INSERT..SELECT..VALUES..RETURNING syntax
  503. where a subquery is used to produce value tuples. Current support
  504. includes PostgreSQL, Microsoft SQL Server.
  505. .. versionadded:: 2.0.10
  506. """
  507. class _InsertManyValuesBatch(NamedTuple):
  508. """represents an individual batch SQL statement for insertmanyvalues.
  509. This is passed through the
  510. :meth:`.SQLCompiler._deliver_insertmanyvalues_batches` and
  511. :meth:`.DefaultDialect._deliver_insertmanyvalues_batches` methods out
  512. to the :class:`.Connection` within the
  513. :meth:`.Connection._exec_insertmany_context` method.
  514. .. versionadded:: 2.0.10
  515. """
  516. replaced_statement: str
  517. replaced_parameters: _DBAPIAnyExecuteParams
  518. processed_setinputsizes: Optional[_GenericSetInputSizesType]
  519. batch: Sequence[_DBAPISingleExecuteParams]
  520. sentinel_values: Sequence[Tuple[Any, ...]]
  521. current_batch_size: int
  522. batchnum: int
  523. total_batches: int
  524. rows_sorted: bool
  525. is_downgraded: bool
  526. class InsertmanyvaluesSentinelOpts(FastIntFlag):
  527. """bitflag enum indicating styles of PK defaults
  528. which can work as implicit sentinel columns
  529. """
  530. NOT_SUPPORTED = 1
  531. AUTOINCREMENT = 2
  532. IDENTITY = 4
  533. SEQUENCE = 8
  534. ANY_AUTOINCREMENT = AUTOINCREMENT | IDENTITY | SEQUENCE
  535. _SUPPORTED_OR_NOT = NOT_SUPPORTED | ANY_AUTOINCREMENT
  536. USE_INSERT_FROM_SELECT = 16
  537. RENDER_SELECT_COL_CASTS = 64
  538. class CompilerState(IntEnum):
  539. COMPILING = 0
  540. """statement is present, compilation phase in progress"""
  541. STRING_APPLIED = 1
  542. """statement is present, string form of the statement has been applied.
  543. Additional processors by subclasses may still be pending.
  544. """
  545. NO_STATEMENT = 2
  546. """compiler does not have a statement to compile, is used
  547. for method access"""
  548. class Linting(IntEnum):
  549. """represent preferences for the 'SQL linting' feature.
  550. this feature currently includes support for flagging cartesian products
  551. in SQL statements.
  552. """
  553. NO_LINTING = 0
  554. "Disable all linting."
  555. COLLECT_CARTESIAN_PRODUCTS = 1
  556. """Collect data on FROMs and cartesian products and gather into
  557. 'self.from_linter'"""
  558. WARN_LINTING = 2
  559. "Emit warnings for linters that find problems"
  560. FROM_LINTING = COLLECT_CARTESIAN_PRODUCTS | WARN_LINTING
  561. """Warn for cartesian products; combines COLLECT_CARTESIAN_PRODUCTS
  562. and WARN_LINTING"""
  563. NO_LINTING, COLLECT_CARTESIAN_PRODUCTS, WARN_LINTING, FROM_LINTING = tuple(
  564. Linting
  565. )
  566. class FromLinter(collections.namedtuple("FromLinter", ["froms", "edges"])):
  567. """represents current state for the "cartesian product" detection
  568. feature."""
  569. def lint(self, start=None):
  570. froms = self.froms
  571. if not froms:
  572. return None, None
  573. edges = set(self.edges)
  574. the_rest = set(froms)
  575. if start is not None:
  576. start_with = start
  577. the_rest.remove(start_with)
  578. else:
  579. start_with = the_rest.pop()
  580. stack = collections.deque([start_with])
  581. while stack and the_rest:
  582. node = stack.popleft()
  583. the_rest.discard(node)
  584. # comparison of nodes in edges here is based on hash equality, as
  585. # there are "annotated" elements that match the non-annotated ones.
  586. # to remove the need for in-python hash() calls, use native
  587. # containment routines (e.g. "node in edge", "edge.index(node)")
  588. to_remove = {edge for edge in edges if node in edge}
  589. # appendleft the node in each edge that is not
  590. # the one that matched.
  591. stack.extendleft(edge[not edge.index(node)] for edge in to_remove)
  592. edges.difference_update(to_remove)
  593. # FROMS left over? boom
  594. if the_rest:
  595. return the_rest, start_with
  596. else:
  597. return None, None
  598. def warn(self, stmt_type="SELECT"):
  599. the_rest, start_with = self.lint()
  600. # FROMS left over? boom
  601. if the_rest:
  602. froms = the_rest
  603. if froms:
  604. template = (
  605. "{stmt_type} statement has a cartesian product between "
  606. "FROM element(s) {froms} and "
  607. 'FROM element "{start}". Apply join condition(s) '
  608. "between each element to resolve."
  609. )
  610. froms_str = ", ".join(
  611. f'"{self.froms[from_]}"' for from_ in froms
  612. )
  613. message = template.format(
  614. stmt_type=stmt_type,
  615. froms=froms_str,
  616. start=self.froms[start_with],
  617. )
  618. util.warn(message)
  619. class Compiled:
  620. """Represent a compiled SQL or DDL expression.
  621. The ``__str__`` method of the ``Compiled`` object should produce
  622. the actual text of the statement. ``Compiled`` objects are
  623. specific to their underlying database dialect, and also may
  624. or may not be specific to the columns referenced within a
  625. particular set of bind parameters. In no case should the
  626. ``Compiled`` object be dependent on the actual values of those
  627. bind parameters, even though it may reference those values as
  628. defaults.
  629. """
  630. statement: Optional[ClauseElement] = None
  631. "The statement to compile."
  632. string: str = ""
  633. "The string representation of the ``statement``"
  634. state: CompilerState
  635. """description of the compiler's state"""
  636. is_sql = False
  637. is_ddl = False
  638. _cached_metadata: Optional[CursorResultMetaData] = None
  639. _result_columns: Optional[List[ResultColumnsEntry]] = None
  640. schema_translate_map: Optional[SchemaTranslateMapType] = None
  641. execution_options: _ExecuteOptions = util.EMPTY_DICT
  642. """
  643. Execution options propagated from the statement. In some cases,
  644. sub-elements of the statement can modify these.
  645. """
  646. preparer: IdentifierPreparer
  647. _annotations: _AnnotationDict = util.EMPTY_DICT
  648. compile_state: Optional[CompileState] = None
  649. """Optional :class:`.CompileState` object that maintains additional
  650. state used by the compiler.
  651. Major executable objects such as :class:`_expression.Insert`,
  652. :class:`_expression.Update`, :class:`_expression.Delete`,
  653. :class:`_expression.Select` will generate this
  654. state when compiled in order to calculate additional information about the
  655. object. For the top level object that is to be executed, the state can be
  656. stored here where it can also have applicability towards result set
  657. processing.
  658. .. versionadded:: 1.4
  659. """
  660. dml_compile_state: Optional[CompileState] = None
  661. """Optional :class:`.CompileState` assigned at the same point that
  662. .isinsert, .isupdate, or .isdelete is assigned.
  663. This will normally be the same object as .compile_state, with the
  664. exception of cases like the :class:`.ORMFromStatementCompileState`
  665. object.
  666. .. versionadded:: 1.4.40
  667. """
  668. cache_key: Optional[CacheKey] = None
  669. """The :class:`.CacheKey` that was generated ahead of creating this
  670. :class:`.Compiled` object.
  671. This is used for routines that need access to the original
  672. :class:`.CacheKey` instance generated when the :class:`.Compiled`
  673. instance was first cached, typically in order to reconcile
  674. the original list of :class:`.BindParameter` objects with a
  675. per-statement list that's generated on each call.
  676. """
  677. _gen_time: float
  678. """Generation time of this :class:`.Compiled`, used for reporting
  679. cache stats."""
  680. def __init__(
  681. self,
  682. dialect: Dialect,
  683. statement: Optional[ClauseElement],
  684. schema_translate_map: Optional[SchemaTranslateMapType] = None,
  685. render_schema_translate: bool = False,
  686. compile_kwargs: Mapping[str, Any] = util.immutabledict(),
  687. ):
  688. """Construct a new :class:`.Compiled` object.
  689. :param dialect: :class:`.Dialect` to compile against.
  690. :param statement: :class:`_expression.ClauseElement` to be compiled.
  691. :param schema_translate_map: dictionary of schema names to be
  692. translated when forming the resultant SQL
  693. .. seealso::
  694. :ref:`schema_translating`
  695. :param compile_kwargs: additional kwargs that will be
  696. passed to the initial call to :meth:`.Compiled.process`.
  697. """
  698. self.dialect = dialect
  699. self.preparer = self.dialect.identifier_preparer
  700. if schema_translate_map:
  701. self.schema_translate_map = schema_translate_map
  702. self.preparer = self.preparer._with_schema_translate(
  703. schema_translate_map
  704. )
  705. if statement is not None:
  706. self.state = CompilerState.COMPILING
  707. self.statement = statement
  708. self.can_execute = statement.supports_execution
  709. self._annotations = statement._annotations
  710. if self.can_execute:
  711. if TYPE_CHECKING:
  712. assert isinstance(statement, Executable)
  713. self.execution_options = statement._execution_options
  714. self.string = self.process(self.statement, **compile_kwargs)
  715. if render_schema_translate:
  716. assert schema_translate_map is not None
  717. self.string = self.preparer._render_schema_translates(
  718. self.string, schema_translate_map
  719. )
  720. self.state = CompilerState.STRING_APPLIED
  721. else:
  722. self.state = CompilerState.NO_STATEMENT
  723. self._gen_time = perf_counter()
  724. def __init_subclass__(cls) -> None:
  725. cls._init_compiler_cls()
  726. return super().__init_subclass__()
  727. @classmethod
  728. def _init_compiler_cls(cls):
  729. pass
  730. def _execute_on_connection(
  731. self, connection, distilled_params, execution_options
  732. ):
  733. if self.can_execute:
  734. return connection._execute_compiled(
  735. self, distilled_params, execution_options
  736. )
  737. else:
  738. raise exc.ObjectNotExecutableError(self.statement)
  739. def visit_unsupported_compilation(self, element, err, **kw):
  740. raise exc.UnsupportedCompilationError(self, type(element)) from err
  741. @property
  742. def sql_compiler(self) -> SQLCompiler:
  743. """Return a Compiled that is capable of processing SQL expressions.
  744. If this compiler is one, it would likely just return 'self'.
  745. """
  746. raise NotImplementedError()
  747. def process(self, obj: Visitable, **kwargs: Any) -> str:
  748. return obj._compiler_dispatch(self, **kwargs)
  749. def __str__(self) -> str:
  750. """Return the string text of the generated SQL or DDL."""
  751. if self.state is CompilerState.STRING_APPLIED:
  752. return self.string
  753. else:
  754. return ""
  755. def construct_params(
  756. self,
  757. params: Optional[_CoreSingleExecuteParams] = None,
  758. extracted_parameters: Optional[Sequence[BindParameter[Any]]] = None,
  759. escape_names: bool = True,
  760. ) -> Optional[_MutableCoreSingleExecuteParams]:
  761. """Return the bind params for this compiled object.
  762. :param params: a dict of string/object pairs whose values will
  763. override bind values compiled in to the
  764. statement.
  765. """
  766. raise NotImplementedError()
  767. @property
  768. def params(self):
  769. """Return the bind params for this compiled object."""
  770. return self.construct_params()
  771. class TypeCompiler(util.EnsureKWArg):
  772. """Produces DDL specification for TypeEngine objects."""
  773. ensure_kwarg = r"visit_\w+"
  774. def __init__(self, dialect: Dialect):
  775. self.dialect = dialect
  776. def process(self, type_: TypeEngine[Any], **kw: Any) -> str:
  777. if (
  778. type_._variant_mapping
  779. and self.dialect.name in type_._variant_mapping
  780. ):
  781. type_ = type_._variant_mapping[self.dialect.name]
  782. return type_._compiler_dispatch(self, **kw)
  783. def visit_unsupported_compilation(
  784. self, element: Any, err: Exception, **kw: Any
  785. ) -> NoReturn:
  786. raise exc.UnsupportedCompilationError(self, element) from err
  787. # this was a Visitable, but to allow accurate detection of
  788. # column elements this is actually a column element
  789. class _CompileLabel(
  790. roles.BinaryElementRole[Any], elements.CompilerColumnElement
  791. ):
  792. """lightweight label object which acts as an expression.Label."""
  793. __visit_name__ = "label"
  794. __slots__ = "element", "name", "_alt_names"
  795. def __init__(self, col, name, alt_names=()):
  796. self.element = col
  797. self.name = name
  798. self._alt_names = (col,) + alt_names
  799. @property
  800. def proxy_set(self):
  801. return self.element.proxy_set
  802. @property
  803. def type(self):
  804. return self.element.type
  805. def self_group(self, **kw):
  806. return self
  807. class ilike_case_insensitive(
  808. roles.BinaryElementRole[Any], elements.CompilerColumnElement
  809. ):
  810. """produce a wrapping element for a case-insensitive portion of
  811. an ILIKE construct.
  812. The construct usually renders the ``lower()`` function, but on
  813. PostgreSQL will pass silently with the assumption that "ILIKE"
  814. is being used.
  815. .. versionadded:: 2.0
  816. """
  817. __visit_name__ = "ilike_case_insensitive_operand"
  818. __slots__ = "element", "comparator"
  819. def __init__(self, element):
  820. self.element = element
  821. self.comparator = element.comparator
  822. @property
  823. def proxy_set(self):
  824. return self.element.proxy_set
  825. @property
  826. def type(self):
  827. return self.element.type
  828. def self_group(self, **kw):
  829. return self
  830. def _with_binary_element_type(self, type_):
  831. return ilike_case_insensitive(
  832. self.element._with_binary_element_type(type_)
  833. )
  834. class SQLCompiler(Compiled):
  835. """Default implementation of :class:`.Compiled`.
  836. Compiles :class:`_expression.ClauseElement` objects into SQL strings.
  837. """
  838. extract_map = EXTRACT_MAP
  839. bindname_escape_characters: ClassVar[Mapping[str, str]] = (
  840. util.immutabledict(
  841. {
  842. "%": "P",
  843. "(": "A",
  844. ")": "Z",
  845. ":": "C",
  846. ".": "_",
  847. "[": "_",
  848. "]": "_",
  849. " ": "_",
  850. }
  851. )
  852. )
  853. """A mapping (e.g. dict or similar) containing a lookup of
  854. characters keyed to replacement characters which will be applied to all
  855. 'bind names' used in SQL statements as a form of 'escaping'; the given
  856. characters are replaced entirely with the 'replacement' character when
  857. rendered in the SQL statement, and a similar translation is performed
  858. on the incoming names used in parameter dictionaries passed to methods
  859. like :meth:`_engine.Connection.execute`.
  860. This allows bound parameter names used in :func:`_sql.bindparam` and
  861. other constructs to have any arbitrary characters present without any
  862. concern for characters that aren't allowed at all on the target database.
  863. Third party dialects can establish their own dictionary here to replace the
  864. default mapping, which will ensure that the particular characters in the
  865. mapping will never appear in a bound parameter name.
  866. The dictionary is evaluated at **class creation time**, so cannot be
  867. modified at runtime; it must be present on the class when the class
  868. is first declared.
  869. Note that for dialects that have additional bound parameter rules such
  870. as additional restrictions on leading characters, the
  871. :meth:`_sql.SQLCompiler.bindparam_string` method may need to be augmented.
  872. See the cx_Oracle compiler for an example of this.
  873. .. versionadded:: 2.0.0rc1
  874. """
  875. _bind_translate_re: ClassVar[Pattern[str]]
  876. _bind_translate_chars: ClassVar[Mapping[str, str]]
  877. is_sql = True
  878. compound_keywords = COMPOUND_KEYWORDS
  879. isdelete: bool = False
  880. isinsert: bool = False
  881. isupdate: bool = False
  882. """class-level defaults which can be set at the instance
  883. level to define if this Compiled instance represents
  884. INSERT/UPDATE/DELETE
  885. """
  886. postfetch: Optional[List[Column[Any]]]
  887. """list of columns that can be post-fetched after INSERT or UPDATE to
  888. receive server-updated values"""
  889. insert_prefetch: Sequence[Column[Any]] = ()
  890. """list of columns for which default values should be evaluated before
  891. an INSERT takes place"""
  892. update_prefetch: Sequence[Column[Any]] = ()
  893. """list of columns for which onupdate default values should be evaluated
  894. before an UPDATE takes place"""
  895. implicit_returning: Optional[Sequence[ColumnElement[Any]]] = None
  896. """list of "implicit" returning columns for a toplevel INSERT or UPDATE
  897. statement, used to receive newly generated values of columns.
  898. .. versionadded:: 2.0 ``implicit_returning`` replaces the previous
  899. ``returning`` collection, which was not a generalized RETURNING
  900. collection and instead was in fact specific to the "implicit returning"
  901. feature.
  902. """
  903. isplaintext: bool = False
  904. binds: Dict[str, BindParameter[Any]]
  905. """a dictionary of bind parameter keys to BindParameter instances."""
  906. bind_names: Dict[BindParameter[Any], str]
  907. """a dictionary of BindParameter instances to "compiled" names
  908. that are actually present in the generated SQL"""
  909. stack: List[_CompilerStackEntry]
  910. """major statements such as SELECT, INSERT, UPDATE, DELETE are
  911. tracked in this stack using an entry format."""
  912. returning_precedes_values: bool = False
  913. """set to True classwide to generate RETURNING
  914. clauses before the VALUES or WHERE clause (i.e. MSSQL)
  915. """
  916. render_table_with_column_in_update_from: bool = False
  917. """set to True classwide to indicate the SET clause
  918. in a multi-table UPDATE statement should qualify
  919. columns with the table name (i.e. MySQL only)
  920. """
  921. ansi_bind_rules: bool = False
  922. """SQL 92 doesn't allow bind parameters to be used
  923. in the columns clause of a SELECT, nor does it allow
  924. ambiguous expressions like "? = ?". A compiler
  925. subclass can set this flag to False if the target
  926. driver/DB enforces this
  927. """
  928. bindtemplate: str
  929. """template to render bound parameters based on paramstyle."""
  930. compilation_bindtemplate: str
  931. """template used by compiler to render parameters before positional
  932. paramstyle application"""
  933. _numeric_binds_identifier_char: str
  934. """Character that's used to as the identifier of a numerical bind param.
  935. For example if this char is set to ``$``, numerical binds will be rendered
  936. in the form ``$1, $2, $3``.
  937. """
  938. _result_columns: List[ResultColumnsEntry]
  939. """relates label names in the final SQL to a tuple of local
  940. column/label name, ColumnElement object (if any) and
  941. TypeEngine. CursorResult uses this for type processing and
  942. column targeting"""
  943. _textual_ordered_columns: bool = False
  944. """tell the result object that the column names as rendered are important,
  945. but they are also "ordered" vs. what is in the compiled object here.
  946. As of 1.4.42 this condition is only present when the statement is a
  947. TextualSelect, e.g. text("....").columns(...), where it is required
  948. that the columns are considered positionally and not by name.
  949. """
  950. _ad_hoc_textual: bool = False
  951. """tell the result that we encountered text() or '*' constructs in the
  952. middle of the result columns, but we also have compiled columns, so
  953. if the number of columns in cursor.description does not match how many
  954. expressions we have, that means we can't rely on positional at all and
  955. should match on name.
  956. """
  957. _ordered_columns: bool = True
  958. """
  959. if False, means we can't be sure the list of entries
  960. in _result_columns is actually the rendered order. Usually
  961. True unless using an unordered TextualSelect.
  962. """
  963. _loose_column_name_matching: bool = False
  964. """tell the result object that the SQL statement is textual, wants to match
  965. up to Column objects, and may be using the ._tq_label in the SELECT rather
  966. than the base name.
  967. """
  968. _numeric_binds: bool = False
  969. """
  970. True if paramstyle is "numeric". This paramstyle is trickier than
  971. all the others.
  972. """
  973. _render_postcompile: bool = False
  974. """
  975. whether to render out POSTCOMPILE params during the compile phase.
  976. This attribute is used only for end-user invocation of stmt.compile();
  977. it's never used for actual statement execution, where instead the
  978. dialect internals access and render the internal postcompile structure
  979. directly.
  980. """
  981. _post_compile_expanded_state: Optional[ExpandedState] = None
  982. """When render_postcompile is used, the ``ExpandedState`` used to create
  983. the "expanded" SQL is assigned here, and then used by the ``.params``
  984. accessor and ``.construct_params()`` methods for their return values.
  985. .. versionadded:: 2.0.0rc1
  986. """
  987. _pre_expanded_string: Optional[str] = None
  988. """Stores the original string SQL before 'post_compile' is applied,
  989. for cases where 'post_compile' were used.
  990. """
  991. _pre_expanded_positiontup: Optional[List[str]] = None
  992. _insertmanyvalues: Optional[_InsertManyValues] = None
  993. _insert_crud_params: Optional[crud._CrudParamSequence] = None
  994. literal_execute_params: FrozenSet[BindParameter[Any]] = frozenset()
  995. """bindparameter objects that are rendered as literal values at statement
  996. execution time.
  997. """
  998. post_compile_params: FrozenSet[BindParameter[Any]] = frozenset()
  999. """bindparameter objects that are rendered as bound parameter placeholders
  1000. at statement execution time.
  1001. """
  1002. escaped_bind_names: util.immutabledict[str, str] = util.EMPTY_DICT
  1003. """Late escaping of bound parameter names that has to be converted
  1004. to the original name when looking in the parameter dictionary.
  1005. """
  1006. has_out_parameters = False
  1007. """if True, there are bindparam() objects that have the isoutparam
  1008. flag set."""
  1009. postfetch_lastrowid = False
  1010. """if True, and this in insert, use cursor.lastrowid to populate
  1011. result.inserted_primary_key. """
  1012. _cache_key_bind_match: Optional[
  1013. Tuple[
  1014. Dict[
  1015. BindParameter[Any],
  1016. List[BindParameter[Any]],
  1017. ],
  1018. Dict[
  1019. str,
  1020. BindParameter[Any],
  1021. ],
  1022. ]
  1023. ] = None
  1024. """a mapping that will relate the BindParameter object we compile
  1025. to those that are part of the extracted collection of parameters
  1026. in the cache key, if we were given a cache key.
  1027. """
  1028. positiontup: Optional[List[str]] = None
  1029. """for a compiled construct that uses a positional paramstyle, will be
  1030. a sequence of strings, indicating the names of bound parameters in order.
  1031. This is used in order to render bound parameters in their correct order,
  1032. and is combined with the :attr:`_sql.Compiled.params` dictionary to
  1033. render parameters.
  1034. This sequence always contains the unescaped name of the parameters.
  1035. .. seealso::
  1036. :ref:`faq_sql_expression_string` - includes a usage example for
  1037. debugging use cases.
  1038. """
  1039. _values_bindparam: Optional[List[str]] = None
  1040. _visited_bindparam: Optional[List[str]] = None
  1041. inline: bool = False
  1042. ctes: Optional[MutableMapping[CTE, str]]
  1043. # Detect same CTE references - Dict[(level, name), cte]
  1044. # Level is required for supporting nesting
  1045. ctes_by_level_name: Dict[Tuple[int, str], CTE]
  1046. # To retrieve key/level in ctes_by_level_name -
  1047. # Dict[cte_reference, (level, cte_name, cte_opts)]
  1048. level_name_by_cte: Dict[CTE, Tuple[int, str, selectable._CTEOpts]]
  1049. ctes_recursive: bool
  1050. _post_compile_pattern = re.compile(r"__\[POSTCOMPILE_(\S+?)(~~.+?~~)?\]")
  1051. _pyformat_pattern = re.compile(r"%\(([^)]+?)\)s")
  1052. _positional_pattern = re.compile(
  1053. f"{_pyformat_pattern.pattern}|{_post_compile_pattern.pattern}"
  1054. )
  1055. @classmethod
  1056. def _init_compiler_cls(cls):
  1057. cls._init_bind_translate()
  1058. @classmethod
  1059. def _init_bind_translate(cls):
  1060. reg = re.escape("".join(cls.bindname_escape_characters))
  1061. cls._bind_translate_re = re.compile(f"[{reg}]")
  1062. cls._bind_translate_chars = cls.bindname_escape_characters
  1063. def __init__(
  1064. self,
  1065. dialect: Dialect,
  1066. statement: Optional[ClauseElement],
  1067. cache_key: Optional[CacheKey] = None,
  1068. column_keys: Optional[Sequence[str]] = None,
  1069. for_executemany: bool = False,
  1070. linting: Linting = NO_LINTING,
  1071. _supporting_against: Optional[SQLCompiler] = None,
  1072. **kwargs: Any,
  1073. ):
  1074. """Construct a new :class:`.SQLCompiler` object.
  1075. :param dialect: :class:`.Dialect` to be used
  1076. :param statement: :class:`_expression.ClauseElement` to be compiled
  1077. :param column_keys: a list of column names to be compiled into an
  1078. INSERT or UPDATE statement.
  1079. :param for_executemany: whether INSERT / UPDATE statements should
  1080. expect that they are to be invoked in an "executemany" style,
  1081. which may impact how the statement will be expected to return the
  1082. values of defaults and autoincrement / sequences and similar.
  1083. Depending on the backend and driver in use, support for retrieving
  1084. these values may be disabled which means SQL expressions may
  1085. be rendered inline, RETURNING may not be rendered, etc.
  1086. :param kwargs: additional keyword arguments to be consumed by the
  1087. superclass.
  1088. """
  1089. self.column_keys = column_keys
  1090. self.cache_key = cache_key
  1091. if cache_key:
  1092. cksm = {b.key: b for b in cache_key[1]}
  1093. ckbm = {b: [b] for b in cache_key[1]}
  1094. self._cache_key_bind_match = (ckbm, cksm)
  1095. # compile INSERT/UPDATE defaults/sequences to expect executemany
  1096. # style execution, which may mean no pre-execute of defaults,
  1097. # or no RETURNING
  1098. self.for_executemany = for_executemany
  1099. self.linting = linting
  1100. # a dictionary of bind parameter keys to BindParameter
  1101. # instances.
  1102. self.binds = {}
  1103. # a dictionary of BindParameter instances to "compiled" names
  1104. # that are actually present in the generated SQL
  1105. self.bind_names = util.column_dict()
  1106. # stack which keeps track of nested SELECT statements
  1107. self.stack = []
  1108. self._result_columns = []
  1109. # true if the paramstyle is positional
  1110. self.positional = dialect.positional
  1111. if self.positional:
  1112. self._numeric_binds = nb = dialect.paramstyle.startswith("numeric")
  1113. if nb:
  1114. self._numeric_binds_identifier_char = (
  1115. "$" if dialect.paramstyle == "numeric_dollar" else ":"
  1116. )
  1117. self.compilation_bindtemplate = _pyformat_template
  1118. else:
  1119. self.compilation_bindtemplate = BIND_TEMPLATES[dialect.paramstyle]
  1120. self.ctes = None
  1121. self.label_length = (
  1122. dialect.label_length or dialect.max_identifier_length
  1123. )
  1124. # a map which tracks "anonymous" identifiers that are created on
  1125. # the fly here
  1126. self.anon_map = prefix_anon_map()
  1127. # a map which tracks "truncated" names based on
  1128. # dialect.label_length or dialect.max_identifier_length
  1129. self.truncated_names: Dict[Tuple[str, str], str] = {}
  1130. self._truncated_counters: Dict[str, int] = {}
  1131. Compiled.__init__(self, dialect, statement, **kwargs)
  1132. if self.isinsert or self.isupdate or self.isdelete:
  1133. if TYPE_CHECKING:
  1134. assert isinstance(statement, UpdateBase)
  1135. if self.isinsert or self.isupdate:
  1136. if TYPE_CHECKING:
  1137. assert isinstance(statement, ValuesBase)
  1138. if statement._inline:
  1139. self.inline = True
  1140. elif self.for_executemany and (
  1141. not self.isinsert
  1142. or (
  1143. self.dialect.insert_executemany_returning
  1144. and statement._return_defaults
  1145. )
  1146. ):
  1147. self.inline = True
  1148. self.bindtemplate = BIND_TEMPLATES[dialect.paramstyle]
  1149. if _supporting_against:
  1150. self.__dict__.update(
  1151. {
  1152. k: v
  1153. for k, v in _supporting_against.__dict__.items()
  1154. if k
  1155. not in {
  1156. "state",
  1157. "dialect",
  1158. "preparer",
  1159. "positional",
  1160. "_numeric_binds",
  1161. "compilation_bindtemplate",
  1162. "bindtemplate",
  1163. }
  1164. }
  1165. )
  1166. if self.state is CompilerState.STRING_APPLIED:
  1167. if self.positional:
  1168. if self._numeric_binds:
  1169. self._process_numeric()
  1170. else:
  1171. self._process_positional()
  1172. if self._render_postcompile:
  1173. parameters = self.construct_params(
  1174. escape_names=False,
  1175. _no_postcompile=True,
  1176. )
  1177. self._process_parameters_for_postcompile(
  1178. parameters, _populate_self=True
  1179. )
  1180. @property
  1181. def insert_single_values_expr(self) -> Optional[str]:
  1182. """When an INSERT is compiled with a single set of parameters inside
  1183. a VALUES expression, the string is assigned here, where it can be
  1184. used for insert batching schemes to rewrite the VALUES expression.
  1185. .. versionadded:: 1.3.8
  1186. .. versionchanged:: 2.0 This collection is no longer used by
  1187. SQLAlchemy's built-in dialects, in favor of the currently
  1188. internal ``_insertmanyvalues`` collection that is used only by
  1189. :class:`.SQLCompiler`.
  1190. """
  1191. if self._insertmanyvalues is None:
  1192. return None
  1193. else:
  1194. return self._insertmanyvalues.single_values_expr
  1195. @util.ro_memoized_property
  1196. def effective_returning(self) -> Optional[Sequence[ColumnElement[Any]]]:
  1197. """The effective "returning" columns for INSERT, UPDATE or DELETE.
  1198. This is either the so-called "implicit returning" columns which are
  1199. calculated by the compiler on the fly, or those present based on what's
  1200. present in ``self.statement._returning`` (expanded into individual
  1201. columns using the ``._all_selected_columns`` attribute) i.e. those set
  1202. explicitly using the :meth:`.UpdateBase.returning` method.
  1203. .. versionadded:: 2.0
  1204. """
  1205. if self.implicit_returning:
  1206. return self.implicit_returning
  1207. elif self.statement is not None and is_dml(self.statement):
  1208. return [
  1209. c
  1210. for c in self.statement._all_selected_columns
  1211. if is_column_element(c)
  1212. ]
  1213. else:
  1214. return None
  1215. @property
  1216. def returning(self):
  1217. """backwards compatibility; returns the
  1218. effective_returning collection.
  1219. """
  1220. return self.effective_returning
  1221. @property
  1222. def current_executable(self):
  1223. """Return the current 'executable' that is being compiled.
  1224. This is currently the :class:`_sql.Select`, :class:`_sql.Insert`,
  1225. :class:`_sql.Update`, :class:`_sql.Delete`,
  1226. :class:`_sql.CompoundSelect` object that is being compiled.
  1227. Specifically it's assigned to the ``self.stack`` list of elements.
  1228. When a statement like the above is being compiled, it normally
  1229. is also assigned to the ``.statement`` attribute of the
  1230. :class:`_sql.Compiler` object. However, all SQL constructs are
  1231. ultimately nestable, and this attribute should never be consulted
  1232. by a ``visit_`` method, as it is not guaranteed to be assigned
  1233. nor guaranteed to correspond to the current statement being compiled.
  1234. .. versionadded:: 1.3.21
  1235. For compatibility with previous versions, use the following
  1236. recipe::
  1237. statement = getattr(self, "current_executable", False)
  1238. if statement is False:
  1239. statement = self.stack[-1]["selectable"]
  1240. For versions 1.4 and above, ensure only .current_executable
  1241. is used; the format of "self.stack" may change.
  1242. """
  1243. try:
  1244. return self.stack[-1]["selectable"]
  1245. except IndexError as ie:
  1246. raise IndexError("Compiler does not have a stack entry") from ie
  1247. @property
  1248. def prefetch(self):
  1249. return list(self.insert_prefetch) + list(self.update_prefetch)
  1250. @util.memoized_property
  1251. def _global_attributes(self) -> Dict[Any, Any]:
  1252. return {}
  1253. @util.memoized_instancemethod
  1254. def _init_cte_state(self) -> MutableMapping[CTE, str]:
  1255. """Initialize collections related to CTEs only if
  1256. a CTE is located, to save on the overhead of
  1257. these collections otherwise.
  1258. """
  1259. # collect CTEs to tack on top of a SELECT
  1260. # To store the query to print - Dict[cte, text_query]
  1261. ctes: MutableMapping[CTE, str] = util.OrderedDict()
  1262. self.ctes = ctes
  1263. # Detect same CTE references - Dict[(level, name), cte]
  1264. # Level is required for supporting nesting
  1265. self.ctes_by_level_name = {}
  1266. # To retrieve key/level in ctes_by_level_name -
  1267. # Dict[cte_reference, (level, cte_name, cte_opts)]
  1268. self.level_name_by_cte = {}
  1269. self.ctes_recursive = False
  1270. return ctes
  1271. @contextlib.contextmanager
  1272. def _nested_result(self):
  1273. """special API to support the use case of 'nested result sets'"""
  1274. result_columns, ordered_columns = (
  1275. self._result_columns,
  1276. self._ordered_columns,
  1277. )
  1278. self._result_columns, self._ordered_columns = [], False
  1279. try:
  1280. if self.stack:
  1281. entry = self.stack[-1]
  1282. entry["need_result_map_for_nested"] = True
  1283. else:
  1284. entry = None
  1285. yield self._result_columns, self._ordered_columns
  1286. finally:
  1287. if entry:
  1288. entry.pop("need_result_map_for_nested")
  1289. self._result_columns, self._ordered_columns = (
  1290. result_columns,
  1291. ordered_columns,
  1292. )
  1293. def _process_positional(self):
  1294. assert not self.positiontup
  1295. assert self.state is CompilerState.STRING_APPLIED
  1296. assert not self._numeric_binds
  1297. if self.dialect.paramstyle == "format":
  1298. placeholder = "%s"
  1299. else:
  1300. assert self.dialect.paramstyle == "qmark"
  1301. placeholder = "?"
  1302. positions = []
  1303. def find_position(m: re.Match[str]) -> str:
  1304. normal_bind = m.group(1)
  1305. if normal_bind:
  1306. positions.append(normal_bind)
  1307. return placeholder
  1308. else:
  1309. # this a post-compile bind
  1310. positions.append(m.group(2))
  1311. return m.group(0)
  1312. self.string = re.sub(
  1313. self._positional_pattern, find_position, self.string
  1314. )
  1315. if self.escaped_bind_names:
  1316. reverse_escape = {v: k for k, v in self.escaped_bind_names.items()}
  1317. assert len(self.escaped_bind_names) == len(reverse_escape)
  1318. self.positiontup = [
  1319. reverse_escape.get(name, name) for name in positions
  1320. ]
  1321. else:
  1322. self.positiontup = positions
  1323. if self._insertmanyvalues:
  1324. positions = []
  1325. single_values_expr = re.sub(
  1326. self._positional_pattern,
  1327. find_position,
  1328. self._insertmanyvalues.single_values_expr,
  1329. )
  1330. insert_crud_params = [
  1331. (
  1332. v[0],
  1333. v[1],
  1334. re.sub(self._positional_pattern, find_position, v[2]),
  1335. v[3],
  1336. )
  1337. for v in self._insertmanyvalues.insert_crud_params
  1338. ]
  1339. self._insertmanyvalues = self._insertmanyvalues._replace(
  1340. single_values_expr=single_values_expr,
  1341. insert_crud_params=insert_crud_params,
  1342. )
  1343. def _process_numeric(self):
  1344. assert self._numeric_binds
  1345. assert self.state is CompilerState.STRING_APPLIED
  1346. num = 1
  1347. param_pos: Dict[str, str] = {}
  1348. order: Iterable[str]
  1349. if self._insertmanyvalues and self._values_bindparam is not None:
  1350. # bindparams that are not in values are always placed first.
  1351. # this avoids the need of changing them when using executemany
  1352. # values () ()
  1353. order = itertools.chain(
  1354. (
  1355. name
  1356. for name in self.bind_names.values()
  1357. if name not in self._values_bindparam
  1358. ),
  1359. self.bind_names.values(),
  1360. )
  1361. else:
  1362. order = self.bind_names.values()
  1363. for bind_name in order:
  1364. if bind_name in param_pos:
  1365. continue
  1366. bind = self.binds[bind_name]
  1367. if (
  1368. bind in self.post_compile_params
  1369. or bind in self.literal_execute_params
  1370. ):
  1371. # set to None to just mark the in positiontup, it will not
  1372. # be replaced below.
  1373. param_pos[bind_name] = None # type: ignore
  1374. else:
  1375. ph = f"{self._numeric_binds_identifier_char}{num}"
  1376. num += 1
  1377. param_pos[bind_name] = ph
  1378. self.next_numeric_pos = num
  1379. self.positiontup = list(param_pos)
  1380. if self.escaped_bind_names:
  1381. len_before = len(param_pos)
  1382. param_pos = {
  1383. self.escaped_bind_names.get(name, name): pos
  1384. for name, pos in param_pos.items()
  1385. }
  1386. assert len(param_pos) == len_before
  1387. # Can't use format here since % chars are not escaped.
  1388. self.string = self._pyformat_pattern.sub(
  1389. lambda m: param_pos[m.group(1)], self.string
  1390. )
  1391. if self._insertmanyvalues:
  1392. single_values_expr = (
  1393. # format is ok here since single_values_expr includes only
  1394. # place-holders
  1395. self._insertmanyvalues.single_values_expr
  1396. % param_pos
  1397. )
  1398. insert_crud_params = [
  1399. (v[0], v[1], "%s", v[3])
  1400. for v in self._insertmanyvalues.insert_crud_params
  1401. ]
  1402. self._insertmanyvalues = self._insertmanyvalues._replace(
  1403. # This has the numbers (:1, :2)
  1404. single_values_expr=single_values_expr,
  1405. # The single binds are instead %s so they can be formatted
  1406. insert_crud_params=insert_crud_params,
  1407. )
  1408. @util.memoized_property
  1409. def _bind_processors(
  1410. self,
  1411. ) -> MutableMapping[
  1412. str, Union[_BindProcessorType[Any], Sequence[_BindProcessorType[Any]]]
  1413. ]:
  1414. # mypy is not able to see the two value types as the above Union,
  1415. # it just sees "object". don't know how to resolve
  1416. return {
  1417. key: value # type: ignore
  1418. for key, value in (
  1419. (
  1420. self.bind_names[bindparam],
  1421. (
  1422. bindparam.type._cached_bind_processor(self.dialect)
  1423. if not bindparam.type._is_tuple_type
  1424. else tuple(
  1425. elem_type._cached_bind_processor(self.dialect)
  1426. for elem_type in cast(
  1427. TupleType, bindparam.type
  1428. ).types
  1429. )
  1430. ),
  1431. )
  1432. for bindparam in self.bind_names
  1433. )
  1434. if value is not None
  1435. }
  1436. def is_subquery(self):
  1437. return len(self.stack) > 1
  1438. @property
  1439. def sql_compiler(self) -> Self:
  1440. return self
  1441. def construct_expanded_state(
  1442. self,
  1443. params: Optional[_CoreSingleExecuteParams] = None,
  1444. escape_names: bool = True,
  1445. ) -> ExpandedState:
  1446. """Return a new :class:`.ExpandedState` for a given parameter set.
  1447. For queries that use "expanding" or other late-rendered parameters,
  1448. this method will provide for both the finalized SQL string as well
  1449. as the parameters that would be used for a particular parameter set.
  1450. .. versionadded:: 2.0.0rc1
  1451. """
  1452. parameters = self.construct_params(
  1453. params,
  1454. escape_names=escape_names,
  1455. _no_postcompile=True,
  1456. )
  1457. return self._process_parameters_for_postcompile(
  1458. parameters,
  1459. )
  1460. def construct_params(
  1461. self,
  1462. params: Optional[_CoreSingleExecuteParams] = None,
  1463. extracted_parameters: Optional[Sequence[BindParameter[Any]]] = None,
  1464. escape_names: bool = True,
  1465. _group_number: Optional[int] = None,
  1466. _check: bool = True,
  1467. _no_postcompile: bool = False,
  1468. ) -> _MutableCoreSingleExecuteParams:
  1469. """return a dictionary of bind parameter keys and values"""
  1470. if self._render_postcompile and not _no_postcompile:
  1471. assert self._post_compile_expanded_state is not None
  1472. if not params:
  1473. return dict(self._post_compile_expanded_state.parameters)
  1474. else:
  1475. raise exc.InvalidRequestError(
  1476. "can't construct new parameters when render_postcompile "
  1477. "is used; the statement is hard-linked to the original "
  1478. "parameters. Use construct_expanded_state to generate a "
  1479. "new statement and parameters."
  1480. )
  1481. has_escaped_names = escape_names and bool(self.escaped_bind_names)
  1482. if extracted_parameters:
  1483. # related the bound parameters collected in the original cache key
  1484. # to those collected in the incoming cache key. They will not have
  1485. # matching names but they will line up positionally in the same
  1486. # way. The parameters present in self.bind_names may be clones of
  1487. # these original cache key params in the case of DML but the .key
  1488. # will be guaranteed to match.
  1489. if self.cache_key is None:
  1490. raise exc.CompileError(
  1491. "This compiled object has no original cache key; "
  1492. "can't pass extracted_parameters to construct_params"
  1493. )
  1494. else:
  1495. orig_extracted = self.cache_key[1]
  1496. ckbm_tuple = self._cache_key_bind_match
  1497. assert ckbm_tuple is not None
  1498. ckbm, _ = ckbm_tuple
  1499. resolved_extracted = {
  1500. bind: extracted
  1501. for b, extracted in zip(orig_extracted, extracted_parameters)
  1502. for bind in ckbm[b]
  1503. }
  1504. else:
  1505. resolved_extracted = None
  1506. if params:
  1507. pd = {}
  1508. for bindparam, name in self.bind_names.items():
  1509. escaped_name = (
  1510. self.escaped_bind_names.get(name, name)
  1511. if has_escaped_names
  1512. else name
  1513. )
  1514. if bindparam.key in params:
  1515. pd[escaped_name] = params[bindparam.key]
  1516. elif name in params:
  1517. pd[escaped_name] = params[name]
  1518. elif _check and bindparam.required:
  1519. if _group_number:
  1520. raise exc.InvalidRequestError(
  1521. "A value is required for bind parameter %r, "
  1522. "in parameter group %d"
  1523. % (bindparam.key, _group_number),
  1524. code="cd3x",
  1525. )
  1526. else:
  1527. raise exc.InvalidRequestError(
  1528. "A value is required for bind parameter %r"
  1529. % bindparam.key,
  1530. code="cd3x",
  1531. )
  1532. else:
  1533. if resolved_extracted:
  1534. value_param = resolved_extracted.get(
  1535. bindparam, bindparam
  1536. )
  1537. else:
  1538. value_param = bindparam
  1539. if bindparam.callable:
  1540. pd[escaped_name] = value_param.effective_value
  1541. else:
  1542. pd[escaped_name] = value_param.value
  1543. return pd
  1544. else:
  1545. pd = {}
  1546. for bindparam, name in self.bind_names.items():
  1547. escaped_name = (
  1548. self.escaped_bind_names.get(name, name)
  1549. if has_escaped_names
  1550. else name
  1551. )
  1552. if _check and bindparam.required:
  1553. if _group_number:
  1554. raise exc.InvalidRequestError(
  1555. "A value is required for bind parameter %r, "
  1556. "in parameter group %d"
  1557. % (bindparam.key, _group_number),
  1558. code="cd3x",
  1559. )
  1560. else:
  1561. raise exc.InvalidRequestError(
  1562. "A value is required for bind parameter %r"
  1563. % bindparam.key,
  1564. code="cd3x",
  1565. )
  1566. if resolved_extracted:
  1567. value_param = resolved_extracted.get(bindparam, bindparam)
  1568. else:
  1569. value_param = bindparam
  1570. if bindparam.callable:
  1571. pd[escaped_name] = value_param.effective_value
  1572. else:
  1573. pd[escaped_name] = value_param.value
  1574. return pd
  1575. @util.memoized_instancemethod
  1576. def _get_set_input_sizes_lookup(self):
  1577. dialect = self.dialect
  1578. include_types = dialect.include_set_input_sizes
  1579. exclude_types = dialect.exclude_set_input_sizes
  1580. dbapi = dialect.dbapi
  1581. def lookup_type(typ):
  1582. dbtype = typ._unwrapped_dialect_impl(dialect).get_dbapi_type(dbapi)
  1583. if (
  1584. dbtype is not None
  1585. and (exclude_types is None or dbtype not in exclude_types)
  1586. and (include_types is None or dbtype in include_types)
  1587. ):
  1588. return dbtype
  1589. else:
  1590. return None
  1591. inputsizes = {}
  1592. literal_execute_params = self.literal_execute_params
  1593. for bindparam in self.bind_names:
  1594. if bindparam in literal_execute_params:
  1595. continue
  1596. if bindparam.type._is_tuple_type:
  1597. inputsizes[bindparam] = [
  1598. lookup_type(typ)
  1599. for typ in cast(TupleType, bindparam.type).types
  1600. ]
  1601. else:
  1602. inputsizes[bindparam] = lookup_type(bindparam.type)
  1603. return inputsizes
  1604. @property
  1605. def params(self):
  1606. """Return the bind param dictionary embedded into this
  1607. compiled object, for those values that are present.
  1608. .. seealso::
  1609. :ref:`faq_sql_expression_string` - includes a usage example for
  1610. debugging use cases.
  1611. """
  1612. return self.construct_params(_check=False)
  1613. def _process_parameters_for_postcompile(
  1614. self,
  1615. parameters: _MutableCoreSingleExecuteParams,
  1616. _populate_self: bool = False,
  1617. ) -> ExpandedState:
  1618. """handle special post compile parameters.
  1619. These include:
  1620. * "expanding" parameters -typically IN tuples that are rendered
  1621. on a per-parameter basis for an otherwise fixed SQL statement string.
  1622. * literal_binds compiled with the literal_execute flag. Used for
  1623. things like SQL Server "TOP N" where the driver does not accommodate
  1624. N as a bound parameter.
  1625. """
  1626. expanded_parameters = {}
  1627. new_positiontup: Optional[List[str]]
  1628. pre_expanded_string = self._pre_expanded_string
  1629. if pre_expanded_string is None:
  1630. pre_expanded_string = self.string
  1631. if self.positional:
  1632. new_positiontup = []
  1633. pre_expanded_positiontup = self._pre_expanded_positiontup
  1634. if pre_expanded_positiontup is None:
  1635. pre_expanded_positiontup = self.positiontup
  1636. else:
  1637. new_positiontup = pre_expanded_positiontup = None
  1638. processors = self._bind_processors
  1639. single_processors = cast(
  1640. "Mapping[str, _BindProcessorType[Any]]", processors
  1641. )
  1642. tuple_processors = cast(
  1643. "Mapping[str, Sequence[_BindProcessorType[Any]]]", processors
  1644. )
  1645. new_processors: Dict[str, _BindProcessorType[Any]] = {}
  1646. replacement_expressions: Dict[str, Any] = {}
  1647. to_update_sets: Dict[str, Any] = {}
  1648. # notes:
  1649. # *unescaped* parameter names in:
  1650. # self.bind_names, self.binds, self._bind_processors, self.positiontup
  1651. #
  1652. # *escaped* parameter names in:
  1653. # construct_params(), replacement_expressions
  1654. numeric_positiontup: Optional[List[str]] = None
  1655. if self.positional and pre_expanded_positiontup is not None:
  1656. names: Iterable[str] = pre_expanded_positiontup
  1657. if self._numeric_binds:
  1658. numeric_positiontup = []
  1659. else:
  1660. names = self.bind_names.values()
  1661. ebn = self.escaped_bind_names
  1662. for name in names:
  1663. escaped_name = ebn.get(name, name) if ebn else name
  1664. parameter = self.binds[name]
  1665. if parameter in self.literal_execute_params:
  1666. if escaped_name not in replacement_expressions:
  1667. replacement_expressions[escaped_name] = (
  1668. self.render_literal_bindparam(
  1669. parameter,
  1670. render_literal_value=parameters.pop(escaped_name),
  1671. )
  1672. )
  1673. continue
  1674. if parameter in self.post_compile_params:
  1675. if escaped_name in replacement_expressions:
  1676. to_update = to_update_sets[escaped_name]
  1677. values = None
  1678. else:
  1679. # we are removing the parameter from parameters
  1680. # because it is a list value, which is not expected by
  1681. # TypeEngine objects that would otherwise be asked to
  1682. # process it. the single name is being replaced with
  1683. # individual numbered parameters for each value in the
  1684. # param.
  1685. #
  1686. # note we are also inserting *escaped* parameter names
  1687. # into the given dictionary. default dialect will
  1688. # use these param names directly as they will not be
  1689. # in the escaped_bind_names dictionary.
  1690. values = parameters.pop(name)
  1691. leep_res = self._literal_execute_expanding_parameter(
  1692. escaped_name, parameter, values
  1693. )
  1694. (to_update, replacement_expr) = leep_res
  1695. to_update_sets[escaped_name] = to_update
  1696. replacement_expressions[escaped_name] = replacement_expr
  1697. if not parameter.literal_execute:
  1698. parameters.update(to_update)
  1699. if parameter.type._is_tuple_type:
  1700. assert values is not None
  1701. new_processors.update(
  1702. (
  1703. "%s_%s_%s" % (name, i, j),
  1704. tuple_processors[name][j - 1],
  1705. )
  1706. for i, tuple_element in enumerate(values, 1)
  1707. for j, _ in enumerate(tuple_element, 1)
  1708. if name in tuple_processors
  1709. and tuple_processors[name][j - 1] is not None
  1710. )
  1711. else:
  1712. new_processors.update(
  1713. (key, single_processors[name])
  1714. for key, _ in to_update
  1715. if name in single_processors
  1716. )
  1717. if numeric_positiontup is not None:
  1718. numeric_positiontup.extend(
  1719. name for name, _ in to_update
  1720. )
  1721. elif new_positiontup is not None:
  1722. # to_update has escaped names, but that's ok since
  1723. # these are new names, that aren't in the
  1724. # escaped_bind_names dict.
  1725. new_positiontup.extend(name for name, _ in to_update)
  1726. expanded_parameters[name] = [
  1727. expand_key for expand_key, _ in to_update
  1728. ]
  1729. elif new_positiontup is not None:
  1730. new_positiontup.append(name)
  1731. def process_expanding(m):
  1732. key = m.group(1)
  1733. expr = replacement_expressions[key]
  1734. # if POSTCOMPILE included a bind_expression, render that
  1735. # around each element
  1736. if m.group(2):
  1737. tok = m.group(2).split("~~")
  1738. be_left, be_right = tok[1], tok[3]
  1739. expr = ", ".join(
  1740. "%s%s%s" % (be_left, exp, be_right)
  1741. for exp in expr.split(", ")
  1742. )
  1743. return expr
  1744. statement = re.sub(
  1745. self._post_compile_pattern, process_expanding, pre_expanded_string
  1746. )
  1747. if numeric_positiontup is not None:
  1748. assert new_positiontup is not None
  1749. param_pos = {
  1750. key: f"{self._numeric_binds_identifier_char}{num}"
  1751. for num, key in enumerate(
  1752. numeric_positiontup, self.next_numeric_pos
  1753. )
  1754. }
  1755. # Can't use format here since % chars are not escaped.
  1756. statement = self._pyformat_pattern.sub(
  1757. lambda m: param_pos[m.group(1)], statement
  1758. )
  1759. new_positiontup.extend(numeric_positiontup)
  1760. expanded_state = ExpandedState(
  1761. statement,
  1762. parameters,
  1763. new_processors,
  1764. new_positiontup,
  1765. expanded_parameters,
  1766. )
  1767. if _populate_self:
  1768. # this is for the "render_postcompile" flag, which is not
  1769. # otherwise used internally and is for end-user debugging and
  1770. # special use cases.
  1771. self._pre_expanded_string = pre_expanded_string
  1772. self._pre_expanded_positiontup = pre_expanded_positiontup
  1773. self.string = expanded_state.statement
  1774. self.positiontup = (
  1775. list(expanded_state.positiontup or ())
  1776. if self.positional
  1777. else None
  1778. )
  1779. self._post_compile_expanded_state = expanded_state
  1780. return expanded_state
  1781. @util.preload_module("sqlalchemy.engine.cursor")
  1782. def _create_result_map(self):
  1783. """utility method used for unit tests only."""
  1784. cursor = util.preloaded.engine_cursor
  1785. return cursor.CursorResultMetaData._create_description_match_map(
  1786. self._result_columns
  1787. )
  1788. # assigned by crud.py for insert/update statements
  1789. _get_bind_name_for_col: _BindNameForColProtocol
  1790. @util.memoized_property
  1791. def _within_exec_param_key_getter(self) -> Callable[[Any], str]:
  1792. getter = self._get_bind_name_for_col
  1793. return getter
  1794. @util.memoized_property
  1795. @util.preload_module("sqlalchemy.engine.result")
  1796. def _inserted_primary_key_from_lastrowid_getter(self):
  1797. result = util.preloaded.engine_result
  1798. param_key_getter = self._within_exec_param_key_getter
  1799. assert self.compile_state is not None
  1800. statement = self.compile_state.statement
  1801. if TYPE_CHECKING:
  1802. assert isinstance(statement, Insert)
  1803. table = statement.table
  1804. getters = [
  1805. (operator.methodcaller("get", param_key_getter(col), None), col)
  1806. for col in table.primary_key
  1807. ]
  1808. autoinc_getter = None
  1809. autoinc_col = table._autoincrement_column
  1810. if autoinc_col is not None:
  1811. # apply type post processors to the lastrowid
  1812. lastrowid_processor = autoinc_col.type._cached_result_processor(
  1813. self.dialect, None
  1814. )
  1815. autoinc_key = param_key_getter(autoinc_col)
  1816. # if a bind value is present for the autoincrement column
  1817. # in the parameters, we need to do the logic dictated by
  1818. # #7998; honor a non-None user-passed parameter over lastrowid.
  1819. # previously in the 1.4 series we weren't fetching lastrowid
  1820. # at all if the key were present in the parameters
  1821. if autoinc_key in self.binds:
  1822. def _autoinc_getter(lastrowid, parameters):
  1823. param_value = parameters.get(autoinc_key, lastrowid)
  1824. if param_value is not None:
  1825. # they supplied non-None parameter, use that.
  1826. # SQLite at least is observed to return the wrong
  1827. # cursor.lastrowid for INSERT..ON CONFLICT so it
  1828. # can't be used in all cases
  1829. return param_value
  1830. else:
  1831. # use lastrowid
  1832. return lastrowid
  1833. # work around mypy https://github.com/python/mypy/issues/14027
  1834. autoinc_getter = _autoinc_getter
  1835. else:
  1836. lastrowid_processor = None
  1837. row_fn = result.result_tuple([col.key for col in table.primary_key])
  1838. def get(lastrowid, parameters):
  1839. """given cursor.lastrowid value and the parameters used for INSERT,
  1840. return a "row" that represents the primary key, either by
  1841. using the "lastrowid" or by extracting values from the parameters
  1842. that were sent along with the INSERT.
  1843. """
  1844. if lastrowid_processor is not None:
  1845. lastrowid = lastrowid_processor(lastrowid)
  1846. if lastrowid is None:
  1847. return row_fn(getter(parameters) for getter, col in getters)
  1848. else:
  1849. return row_fn(
  1850. (
  1851. (
  1852. autoinc_getter(lastrowid, parameters)
  1853. if autoinc_getter is not None
  1854. else lastrowid
  1855. )
  1856. if col is autoinc_col
  1857. else getter(parameters)
  1858. )
  1859. for getter, col in getters
  1860. )
  1861. return get
  1862. @util.memoized_property
  1863. @util.preload_module("sqlalchemy.engine.result")
  1864. def _inserted_primary_key_from_returning_getter(self):
  1865. if typing.TYPE_CHECKING:
  1866. from ..engine import result
  1867. else:
  1868. result = util.preloaded.engine_result
  1869. assert self.compile_state is not None
  1870. statement = self.compile_state.statement
  1871. if TYPE_CHECKING:
  1872. assert isinstance(statement, Insert)
  1873. param_key_getter = self._within_exec_param_key_getter
  1874. table = statement.table
  1875. returning = self.implicit_returning
  1876. assert returning is not None
  1877. ret = {col: idx for idx, col in enumerate(returning)}
  1878. getters = cast(
  1879. "List[Tuple[Callable[[Any], Any], bool]]",
  1880. [
  1881. (
  1882. (operator.itemgetter(ret[col]), True)
  1883. if col in ret
  1884. else (
  1885. operator.methodcaller(
  1886. "get", param_key_getter(col), None
  1887. ),
  1888. False,
  1889. )
  1890. )
  1891. for col in table.primary_key
  1892. ],
  1893. )
  1894. row_fn = result.result_tuple([col.key for col in table.primary_key])
  1895. def get(row, parameters):
  1896. return row_fn(
  1897. getter(row) if use_row else getter(parameters)
  1898. for getter, use_row in getters
  1899. )
  1900. return get
  1901. def default_from(self) -> str:
  1902. """Called when a SELECT statement has no froms, and no FROM clause is
  1903. to be appended.
  1904. Gives Oracle Database a chance to tack on a ``FROM DUAL`` to the string
  1905. output.
  1906. """
  1907. return ""
  1908. def visit_override_binds(self, override_binds, **kw):
  1909. """SQL compile the nested element of an _OverrideBinds with
  1910. bindparams swapped out.
  1911. The _OverrideBinds is not normally expected to be compiled; it
  1912. is meant to be used when an already cached statement is to be used,
  1913. the compilation was already performed, and only the bound params should
  1914. be swapped in at execution time.
  1915. However, there are test cases that exericise this object, and
  1916. additionally the ORM subquery loader is known to feed in expressions
  1917. which include this construct into new queries (discovered in #11173),
  1918. so it has to do the right thing at compile time as well.
  1919. """
  1920. # get SQL text first
  1921. sqltext = override_binds.element._compiler_dispatch(self, **kw)
  1922. # for a test compile that is not for caching, change binds after the
  1923. # fact. note that we don't try to
  1924. # swap the bindparam as we compile, because our element may be
  1925. # elsewhere in the statement already (e.g. a subquery or perhaps a
  1926. # CTE) and was already visited / compiled. See
  1927. # test_relationship_criteria.py ->
  1928. # test_selectinload_local_criteria_subquery
  1929. for k in override_binds.translate:
  1930. if k not in self.binds:
  1931. continue
  1932. bp = self.binds[k]
  1933. # so this would work, just change the value of bp in place.
  1934. # but we dont want to mutate things outside.
  1935. # bp.value = override_binds.translate[bp.key]
  1936. # continue
  1937. # instead, need to replace bp with new_bp or otherwise accommodate
  1938. # in all internal collections
  1939. new_bp = bp._with_value(
  1940. override_binds.translate[bp.key],
  1941. maintain_key=True,
  1942. required=False,
  1943. )
  1944. name = self.bind_names[bp]
  1945. self.binds[k] = self.binds[name] = new_bp
  1946. self.bind_names[new_bp] = name
  1947. self.bind_names.pop(bp, None)
  1948. if bp in self.post_compile_params:
  1949. self.post_compile_params |= {new_bp}
  1950. if bp in self.literal_execute_params:
  1951. self.literal_execute_params |= {new_bp}
  1952. ckbm_tuple = self._cache_key_bind_match
  1953. if ckbm_tuple:
  1954. ckbm, cksm = ckbm_tuple
  1955. for bp in bp._cloned_set:
  1956. if bp.key in cksm:
  1957. cb = cksm[bp.key]
  1958. ckbm[cb].append(new_bp)
  1959. return sqltext
  1960. def visit_grouping(self, grouping, asfrom=False, **kwargs):
  1961. return "(" + grouping.element._compiler_dispatch(self, **kwargs) + ")"
  1962. def visit_select_statement_grouping(self, grouping, **kwargs):
  1963. return "(" + grouping.element._compiler_dispatch(self, **kwargs) + ")"
  1964. def visit_label_reference(
  1965. self, element, within_columns_clause=False, **kwargs
  1966. ):
  1967. if self.stack and self.dialect.supports_simple_order_by_label:
  1968. try:
  1969. compile_state = cast(
  1970. "Union[SelectState, CompoundSelectState]",
  1971. self.stack[-1]["compile_state"],
  1972. )
  1973. except KeyError as ke:
  1974. raise exc.CompileError(
  1975. "Can't resolve label reference for ORDER BY / "
  1976. "GROUP BY / DISTINCT etc."
  1977. ) from ke
  1978. (
  1979. with_cols,
  1980. only_froms,
  1981. only_cols,
  1982. ) = compile_state._label_resolve_dict
  1983. if within_columns_clause:
  1984. resolve_dict = only_froms
  1985. else:
  1986. resolve_dict = only_cols
  1987. # this can be None in the case that a _label_reference()
  1988. # were subject to a replacement operation, in which case
  1989. # the replacement of the Label element may have changed
  1990. # to something else like a ColumnClause expression.
  1991. order_by_elem = element.element._order_by_label_element
  1992. if (
  1993. order_by_elem is not None
  1994. and order_by_elem.name in resolve_dict
  1995. and order_by_elem.shares_lineage(
  1996. resolve_dict[order_by_elem.name]
  1997. )
  1998. ):
  1999. kwargs["render_label_as_label"] = (
  2000. element.element._order_by_label_element
  2001. )
  2002. return self.process(
  2003. element.element,
  2004. within_columns_clause=within_columns_clause,
  2005. **kwargs,
  2006. )
  2007. def visit_textual_label_reference(
  2008. self, element, within_columns_clause=False, **kwargs
  2009. ):
  2010. if not self.stack:
  2011. # compiling the element outside of the context of a SELECT
  2012. return self.process(element._text_clause)
  2013. try:
  2014. compile_state = cast(
  2015. "Union[SelectState, CompoundSelectState]",
  2016. self.stack[-1]["compile_state"],
  2017. )
  2018. except KeyError as ke:
  2019. coercions._no_text_coercion(
  2020. element.element,
  2021. extra=(
  2022. "Can't resolve label reference for ORDER BY / "
  2023. "GROUP BY / DISTINCT etc."
  2024. ),
  2025. exc_cls=exc.CompileError,
  2026. err=ke,
  2027. )
  2028. with_cols, only_froms, only_cols = compile_state._label_resolve_dict
  2029. try:
  2030. if within_columns_clause:
  2031. col = only_froms[element.element]
  2032. else:
  2033. col = with_cols[element.element]
  2034. except KeyError as err:
  2035. coercions._no_text_coercion(
  2036. element.element,
  2037. extra=(
  2038. "Can't resolve label reference for ORDER BY / "
  2039. "GROUP BY / DISTINCT etc."
  2040. ),
  2041. exc_cls=exc.CompileError,
  2042. err=err,
  2043. )
  2044. else:
  2045. kwargs["render_label_as_label"] = col
  2046. return self.process(
  2047. col, within_columns_clause=within_columns_clause, **kwargs
  2048. )
  2049. def visit_label(
  2050. self,
  2051. label,
  2052. add_to_result_map=None,
  2053. within_label_clause=False,
  2054. within_columns_clause=False,
  2055. render_label_as_label=None,
  2056. result_map_targets=(),
  2057. **kw,
  2058. ):
  2059. # only render labels within the columns clause
  2060. # or ORDER BY clause of a select. dialect-specific compilers
  2061. # can modify this behavior.
  2062. render_label_with_as = (
  2063. within_columns_clause and not within_label_clause
  2064. )
  2065. render_label_only = render_label_as_label is label
  2066. if render_label_only or render_label_with_as:
  2067. if isinstance(label.name, elements._truncated_label):
  2068. labelname = self._truncated_identifier("colident", label.name)
  2069. else:
  2070. labelname = label.name
  2071. if render_label_with_as:
  2072. if add_to_result_map is not None:
  2073. add_to_result_map(
  2074. labelname,
  2075. label.name,
  2076. (label, labelname) + label._alt_names + result_map_targets,
  2077. label.type,
  2078. )
  2079. return (
  2080. label.element._compiler_dispatch(
  2081. self,
  2082. within_columns_clause=True,
  2083. within_label_clause=True,
  2084. **kw,
  2085. )
  2086. + OPERATORS[operators.as_]
  2087. + self.preparer.format_label(label, labelname)
  2088. )
  2089. elif render_label_only:
  2090. return self.preparer.format_label(label, labelname)
  2091. else:
  2092. return label.element._compiler_dispatch(
  2093. self, within_columns_clause=False, **kw
  2094. )
  2095. def _fallback_column_name(self, column):
  2096. raise exc.CompileError(
  2097. "Cannot compile Column object until its 'name' is assigned."
  2098. )
  2099. def visit_lambda_element(self, element, **kw):
  2100. sql_element = element._resolved
  2101. return self.process(sql_element, **kw)
  2102. def visit_column(
  2103. self,
  2104. column: ColumnClause[Any],
  2105. add_to_result_map: Optional[_ResultMapAppender] = None,
  2106. include_table: bool = True,
  2107. result_map_targets: Tuple[Any, ...] = (),
  2108. ambiguous_table_name_map: Optional[_AmbiguousTableNameMap] = None,
  2109. **kwargs: Any,
  2110. ) -> str:
  2111. name = orig_name = column.name
  2112. if name is None:
  2113. name = self._fallback_column_name(column)
  2114. is_literal = column.is_literal
  2115. if not is_literal and isinstance(name, elements._truncated_label):
  2116. name = self._truncated_identifier("colident", name)
  2117. if add_to_result_map is not None:
  2118. targets = (column, name, column.key) + result_map_targets
  2119. if column._tq_label:
  2120. targets += (column._tq_label,)
  2121. add_to_result_map(name, orig_name, targets, column.type)
  2122. if is_literal:
  2123. # note we are not currently accommodating for
  2124. # literal_column(quoted_name('ident', True)) here
  2125. name = self.escape_literal_column(name)
  2126. else:
  2127. name = self.preparer.quote(name)
  2128. table = column.table
  2129. if table is None or not include_table or not table.named_with_column:
  2130. return name
  2131. else:
  2132. effective_schema = self.preparer.schema_for_object(table)
  2133. if effective_schema:
  2134. schema_prefix = (
  2135. self.preparer.quote_schema(effective_schema) + "."
  2136. )
  2137. else:
  2138. schema_prefix = ""
  2139. if TYPE_CHECKING:
  2140. assert isinstance(table, NamedFromClause)
  2141. tablename = table.name
  2142. if (
  2143. not effective_schema
  2144. and ambiguous_table_name_map
  2145. and tablename in ambiguous_table_name_map
  2146. ):
  2147. tablename = ambiguous_table_name_map[tablename]
  2148. if isinstance(tablename, elements._truncated_label):
  2149. tablename = self._truncated_identifier("alias", tablename)
  2150. return schema_prefix + self.preparer.quote(tablename) + "." + name
  2151. def visit_collation(self, element, **kw):
  2152. return self.preparer.format_collation(element.collation)
  2153. def visit_fromclause(self, fromclause, **kwargs):
  2154. return fromclause.name
  2155. def visit_index(self, index, **kwargs):
  2156. return index.name
  2157. def visit_typeclause(self, typeclause, **kw):
  2158. kw["type_expression"] = typeclause
  2159. kw["identifier_preparer"] = self.preparer
  2160. return self.dialect.type_compiler_instance.process(
  2161. typeclause.type, **kw
  2162. )
  2163. def post_process_text(self, text):
  2164. if self.preparer._double_percents:
  2165. text = text.replace("%", "%%")
  2166. return text
  2167. def escape_literal_column(self, text):
  2168. if self.preparer._double_percents:
  2169. text = text.replace("%", "%%")
  2170. return text
  2171. def visit_textclause(self, textclause, add_to_result_map=None, **kw):
  2172. def do_bindparam(m):
  2173. name = m.group(1)
  2174. if name in textclause._bindparams:
  2175. return self.process(textclause._bindparams[name], **kw)
  2176. else:
  2177. return self.bindparam_string(name, **kw)
  2178. if not self.stack:
  2179. self.isplaintext = True
  2180. if add_to_result_map:
  2181. # text() object is present in the columns clause of a
  2182. # select(). Add a no-name entry to the result map so that
  2183. # row[text()] produces a result
  2184. add_to_result_map(None, None, (textclause,), sqltypes.NULLTYPE)
  2185. # un-escape any \:params
  2186. return BIND_PARAMS_ESC.sub(
  2187. lambda m: m.group(1),
  2188. BIND_PARAMS.sub(
  2189. do_bindparam, self.post_process_text(textclause.text)
  2190. ),
  2191. )
  2192. def visit_textual_select(
  2193. self, taf, compound_index=None, asfrom=False, **kw
  2194. ):
  2195. toplevel = not self.stack
  2196. entry = self._default_stack_entry if toplevel else self.stack[-1]
  2197. new_entry: _CompilerStackEntry = {
  2198. "correlate_froms": set(),
  2199. "asfrom_froms": set(),
  2200. "selectable": taf,
  2201. }
  2202. self.stack.append(new_entry)
  2203. if taf._independent_ctes:
  2204. self._dispatch_independent_ctes(taf, kw)
  2205. populate_result_map = (
  2206. toplevel
  2207. or (
  2208. compound_index == 0
  2209. and entry.get("need_result_map_for_compound", False)
  2210. )
  2211. or entry.get("need_result_map_for_nested", False)
  2212. )
  2213. if populate_result_map:
  2214. self._ordered_columns = self._textual_ordered_columns = (
  2215. taf.positional
  2216. )
  2217. # enable looser result column matching when the SQL text links to
  2218. # Column objects by name only
  2219. self._loose_column_name_matching = not taf.positional and bool(
  2220. taf.column_args
  2221. )
  2222. for c in taf.column_args:
  2223. self.process(
  2224. c,
  2225. within_columns_clause=True,
  2226. add_to_result_map=self._add_to_result_map,
  2227. )
  2228. text = self.process(taf.element, **kw)
  2229. if self.ctes:
  2230. nesting_level = len(self.stack) if not toplevel else None
  2231. text = self._render_cte_clause(nesting_level=nesting_level) + text
  2232. self.stack.pop(-1)
  2233. return text
  2234. def visit_null(self, expr: Null, **kw: Any) -> str:
  2235. return "NULL"
  2236. def visit_true(self, expr: True_, **kw: Any) -> str:
  2237. if self.dialect.supports_native_boolean:
  2238. return "true"
  2239. else:
  2240. return "1"
  2241. def visit_false(self, expr: False_, **kw: Any) -> str:
  2242. if self.dialect.supports_native_boolean:
  2243. return "false"
  2244. else:
  2245. return "0"
  2246. def _generate_delimited_list(self, elements, separator, **kw):
  2247. return separator.join(
  2248. s
  2249. for s in (c._compiler_dispatch(self, **kw) for c in elements)
  2250. if s
  2251. )
  2252. def _generate_delimited_and_list(self, clauses, **kw):
  2253. lcc, clauses = elements.BooleanClauseList._process_clauses_for_boolean(
  2254. operators.and_,
  2255. elements.True_._singleton,
  2256. elements.False_._singleton,
  2257. clauses,
  2258. )
  2259. if lcc == 1:
  2260. return clauses[0]._compiler_dispatch(self, **kw)
  2261. else:
  2262. separator = OPERATORS[operators.and_]
  2263. return separator.join(
  2264. s
  2265. for s in (c._compiler_dispatch(self, **kw) for c in clauses)
  2266. if s
  2267. )
  2268. def visit_tuple(self, clauselist, **kw):
  2269. return "(%s)" % self.visit_clauselist(clauselist, **kw)
  2270. def visit_clauselist(self, clauselist, **kw):
  2271. sep = clauselist.operator
  2272. if sep is None:
  2273. sep = " "
  2274. else:
  2275. sep = OPERATORS[clauselist.operator]
  2276. return self._generate_delimited_list(clauselist.clauses, sep, **kw)
  2277. def visit_expression_clauselist(self, clauselist, **kw):
  2278. operator_ = clauselist.operator
  2279. disp = self._get_operator_dispatch(
  2280. operator_, "expression_clauselist", None
  2281. )
  2282. if disp:
  2283. return disp(clauselist, operator_, **kw)
  2284. try:
  2285. opstring = OPERATORS[operator_]
  2286. except KeyError as err:
  2287. raise exc.UnsupportedCompilationError(self, operator_) from err
  2288. else:
  2289. kw["_in_operator_expression"] = True
  2290. return self._generate_delimited_list(
  2291. clauselist.clauses, opstring, **kw
  2292. )
  2293. def visit_case(self, clause, **kwargs):
  2294. x = "CASE "
  2295. if clause.value is not None:
  2296. x += clause.value._compiler_dispatch(self, **kwargs) + " "
  2297. for cond, result in clause.whens:
  2298. x += (
  2299. "WHEN "
  2300. + cond._compiler_dispatch(self, **kwargs)
  2301. + " THEN "
  2302. + result._compiler_dispatch(self, **kwargs)
  2303. + " "
  2304. )
  2305. if clause.else_ is not None:
  2306. x += (
  2307. "ELSE " + clause.else_._compiler_dispatch(self, **kwargs) + " "
  2308. )
  2309. x += "END"
  2310. return x
  2311. def visit_type_coerce(self, type_coerce, **kw):
  2312. return type_coerce.typed_expression._compiler_dispatch(self, **kw)
  2313. def visit_cast(self, cast, **kwargs):
  2314. type_clause = cast.typeclause._compiler_dispatch(self, **kwargs)
  2315. match = re.match("(.*)( COLLATE .*)", type_clause)
  2316. return "CAST(%s AS %s)%s" % (
  2317. cast.clause._compiler_dispatch(self, **kwargs),
  2318. match.group(1) if match else type_clause,
  2319. match.group(2) if match else "",
  2320. )
  2321. def _format_frame_clause(self, range_, **kw):
  2322. return "%s AND %s" % (
  2323. (
  2324. "UNBOUNDED PRECEDING"
  2325. if range_[0] is elements.RANGE_UNBOUNDED
  2326. else (
  2327. "CURRENT ROW"
  2328. if range_[0] is elements.RANGE_CURRENT
  2329. else (
  2330. "%s PRECEDING"
  2331. % (
  2332. self.process(
  2333. elements.literal(abs(range_[0])), **kw
  2334. ),
  2335. )
  2336. if range_[0] < 0
  2337. else "%s FOLLOWING"
  2338. % (self.process(elements.literal(range_[0]), **kw),)
  2339. )
  2340. )
  2341. ),
  2342. (
  2343. "UNBOUNDED FOLLOWING"
  2344. if range_[1] is elements.RANGE_UNBOUNDED
  2345. else (
  2346. "CURRENT ROW"
  2347. if range_[1] is elements.RANGE_CURRENT
  2348. else (
  2349. "%s PRECEDING"
  2350. % (
  2351. self.process(
  2352. elements.literal(abs(range_[1])), **kw
  2353. ),
  2354. )
  2355. if range_[1] < 0
  2356. else "%s FOLLOWING"
  2357. % (self.process(elements.literal(range_[1]), **kw),)
  2358. )
  2359. )
  2360. ),
  2361. )
  2362. def visit_over(self, over, **kwargs):
  2363. text = over.element._compiler_dispatch(self, **kwargs)
  2364. if over.range_ is not None:
  2365. range_ = "RANGE BETWEEN %s" % self._format_frame_clause(
  2366. over.range_, **kwargs
  2367. )
  2368. elif over.rows is not None:
  2369. range_ = "ROWS BETWEEN %s" % self._format_frame_clause(
  2370. over.rows, **kwargs
  2371. )
  2372. elif over.groups is not None:
  2373. range_ = "GROUPS BETWEEN %s" % self._format_frame_clause(
  2374. over.groups, **kwargs
  2375. )
  2376. else:
  2377. range_ = None
  2378. return "%s OVER (%s)" % (
  2379. text,
  2380. " ".join(
  2381. [
  2382. "%s BY %s"
  2383. % (word, clause._compiler_dispatch(self, **kwargs))
  2384. for word, clause in (
  2385. ("PARTITION", over.partition_by),
  2386. ("ORDER", over.order_by),
  2387. )
  2388. if clause is not None and len(clause)
  2389. ]
  2390. + ([range_] if range_ else [])
  2391. ),
  2392. )
  2393. def visit_withingroup(self, withingroup, **kwargs):
  2394. return "%s WITHIN GROUP (ORDER BY %s)" % (
  2395. withingroup.element._compiler_dispatch(self, **kwargs),
  2396. withingroup.order_by._compiler_dispatch(self, **kwargs),
  2397. )
  2398. def visit_funcfilter(self, funcfilter, **kwargs):
  2399. return "%s FILTER (WHERE %s)" % (
  2400. funcfilter.func._compiler_dispatch(self, **kwargs),
  2401. funcfilter.criterion._compiler_dispatch(self, **kwargs),
  2402. )
  2403. def visit_extract(self, extract, **kwargs):
  2404. field = self.extract_map.get(extract.field, extract.field)
  2405. return "EXTRACT(%s FROM %s)" % (
  2406. field,
  2407. extract.expr._compiler_dispatch(self, **kwargs),
  2408. )
  2409. def visit_scalar_function_column(self, element, **kw):
  2410. compiled_fn = self.visit_function(element.fn, **kw)
  2411. compiled_col = self.visit_column(element, **kw)
  2412. return "(%s).%s" % (compiled_fn, compiled_col)
  2413. def visit_function(
  2414. self,
  2415. func: Function[Any],
  2416. add_to_result_map: Optional[_ResultMapAppender] = None,
  2417. **kwargs: Any,
  2418. ) -> str:
  2419. if add_to_result_map is not None:
  2420. add_to_result_map(func.name, func.name, (func.name,), func.type)
  2421. disp = getattr(self, "visit_%s_func" % func.name.lower(), None)
  2422. text: str
  2423. if disp:
  2424. text = disp(func, **kwargs)
  2425. else:
  2426. name = FUNCTIONS.get(func._deannotate().__class__, None)
  2427. if name:
  2428. if func._has_args:
  2429. name += "%(expr)s"
  2430. else:
  2431. name = func.name
  2432. name = (
  2433. self.preparer.quote(name)
  2434. if self.preparer._requires_quotes_illegal_chars(name)
  2435. or isinstance(name, elements.quoted_name)
  2436. else name
  2437. )
  2438. name = name + "%(expr)s"
  2439. text = ".".join(
  2440. [
  2441. (
  2442. self.preparer.quote(tok)
  2443. if self.preparer._requires_quotes_illegal_chars(tok)
  2444. or isinstance(name, elements.quoted_name)
  2445. else tok
  2446. )
  2447. for tok in func.packagenames
  2448. ]
  2449. + [name]
  2450. ) % {"expr": self.function_argspec(func, **kwargs)}
  2451. if func._with_ordinality:
  2452. text += " WITH ORDINALITY"
  2453. return text
  2454. def visit_next_value_func(self, next_value, **kw):
  2455. return self.visit_sequence(next_value.sequence)
  2456. def visit_sequence(self, sequence, **kw):
  2457. raise NotImplementedError(
  2458. "Dialect '%s' does not support sequence increments."
  2459. % self.dialect.name
  2460. )
  2461. def function_argspec(self, func: Function[Any], **kwargs: Any) -> str:
  2462. return func.clause_expr._compiler_dispatch(self, **kwargs)
  2463. def visit_compound_select(
  2464. self, cs, asfrom=False, compound_index=None, **kwargs
  2465. ):
  2466. toplevel = not self.stack
  2467. compile_state = cs._compile_state_factory(cs, self, **kwargs)
  2468. if toplevel and not self.compile_state:
  2469. self.compile_state = compile_state
  2470. compound_stmt = compile_state.statement
  2471. entry = self._default_stack_entry if toplevel else self.stack[-1]
  2472. need_result_map = toplevel or (
  2473. not compound_index
  2474. and entry.get("need_result_map_for_compound", False)
  2475. )
  2476. # indicates there is already a CompoundSelect in play
  2477. if compound_index == 0:
  2478. entry["select_0"] = cs
  2479. self.stack.append(
  2480. {
  2481. "correlate_froms": entry["correlate_froms"],
  2482. "asfrom_froms": entry["asfrom_froms"],
  2483. "selectable": cs,
  2484. "compile_state": compile_state,
  2485. "need_result_map_for_compound": need_result_map,
  2486. }
  2487. )
  2488. if compound_stmt._independent_ctes:
  2489. self._dispatch_independent_ctes(compound_stmt, kwargs)
  2490. keyword = self.compound_keywords[cs.keyword]
  2491. text = (" " + keyword + " ").join(
  2492. (
  2493. c._compiler_dispatch(
  2494. self, asfrom=asfrom, compound_index=i, **kwargs
  2495. )
  2496. for i, c in enumerate(cs.selects)
  2497. )
  2498. )
  2499. kwargs["include_table"] = False
  2500. text += self.group_by_clause(cs, **dict(asfrom=asfrom, **kwargs))
  2501. text += self.order_by_clause(cs, **kwargs)
  2502. if cs._has_row_limiting_clause:
  2503. text += self._row_limit_clause(cs, **kwargs)
  2504. if self.ctes:
  2505. nesting_level = len(self.stack) if not toplevel else None
  2506. text = (
  2507. self._render_cte_clause(
  2508. nesting_level=nesting_level,
  2509. include_following_stack=True,
  2510. )
  2511. + text
  2512. )
  2513. self.stack.pop(-1)
  2514. return text
  2515. def _row_limit_clause(self, cs, **kwargs):
  2516. if cs._fetch_clause is not None:
  2517. return self.fetch_clause(cs, **kwargs)
  2518. else:
  2519. return self.limit_clause(cs, **kwargs)
  2520. def _get_operator_dispatch(self, operator_, qualifier1, qualifier2):
  2521. attrname = "visit_%s_%s%s" % (
  2522. operator_.__name__,
  2523. qualifier1,
  2524. "_" + qualifier2 if qualifier2 else "",
  2525. )
  2526. return getattr(self, attrname, None)
  2527. def visit_unary(
  2528. self, unary, add_to_result_map=None, result_map_targets=(), **kw
  2529. ):
  2530. if add_to_result_map is not None:
  2531. result_map_targets += (unary,)
  2532. kw["add_to_result_map"] = add_to_result_map
  2533. kw["result_map_targets"] = result_map_targets
  2534. if unary.operator:
  2535. if unary.modifier:
  2536. raise exc.CompileError(
  2537. "Unary expression does not support operator "
  2538. "and modifier simultaneously"
  2539. )
  2540. disp = self._get_operator_dispatch(
  2541. unary.operator, "unary", "operator"
  2542. )
  2543. if disp:
  2544. return disp(unary, unary.operator, **kw)
  2545. else:
  2546. return self._generate_generic_unary_operator(
  2547. unary, OPERATORS[unary.operator], **kw
  2548. )
  2549. elif unary.modifier:
  2550. disp = self._get_operator_dispatch(
  2551. unary.modifier, "unary", "modifier"
  2552. )
  2553. if disp:
  2554. return disp(unary, unary.modifier, **kw)
  2555. else:
  2556. return self._generate_generic_unary_modifier(
  2557. unary, OPERATORS[unary.modifier], **kw
  2558. )
  2559. else:
  2560. raise exc.CompileError(
  2561. "Unary expression has no operator or modifier"
  2562. )
  2563. def visit_truediv_binary(self, binary, operator, **kw):
  2564. if self.dialect.div_is_floordiv:
  2565. return (
  2566. self.process(binary.left, **kw)
  2567. + " / "
  2568. # TODO: would need a fast cast again here,
  2569. # unless we want to use an implicit cast like "+ 0.0"
  2570. + self.process(
  2571. elements.Cast(
  2572. binary.right,
  2573. (
  2574. binary.right.type
  2575. if binary.right.type._type_affinity
  2576. is sqltypes.Numeric
  2577. else sqltypes.Numeric()
  2578. ),
  2579. ),
  2580. **kw,
  2581. )
  2582. )
  2583. else:
  2584. return (
  2585. self.process(binary.left, **kw)
  2586. + " / "
  2587. + self.process(binary.right, **kw)
  2588. )
  2589. def visit_floordiv_binary(self, binary, operator, **kw):
  2590. if (
  2591. self.dialect.div_is_floordiv
  2592. and binary.right.type._type_affinity is sqltypes.Integer
  2593. ):
  2594. return (
  2595. self.process(binary.left, **kw)
  2596. + " / "
  2597. + self.process(binary.right, **kw)
  2598. )
  2599. else:
  2600. return "FLOOR(%s)" % (
  2601. self.process(binary.left, **kw)
  2602. + " / "
  2603. + self.process(binary.right, **kw)
  2604. )
  2605. def visit_is_true_unary_operator(self, element, operator, **kw):
  2606. if (
  2607. element._is_implicitly_boolean
  2608. or self.dialect.supports_native_boolean
  2609. ):
  2610. return self.process(element.element, **kw)
  2611. else:
  2612. return "%s = 1" % self.process(element.element, **kw)
  2613. def visit_is_false_unary_operator(self, element, operator, **kw):
  2614. if (
  2615. element._is_implicitly_boolean
  2616. or self.dialect.supports_native_boolean
  2617. ):
  2618. return "NOT %s" % self.process(element.element, **kw)
  2619. else:
  2620. return "%s = 0" % self.process(element.element, **kw)
  2621. def visit_not_match_op_binary(self, binary, operator, **kw):
  2622. return "NOT %s" % self.visit_binary(
  2623. binary, override_operator=operators.match_op
  2624. )
  2625. def visit_not_in_op_binary(self, binary, operator, **kw):
  2626. # The brackets are required in the NOT IN operation because the empty
  2627. # case is handled using the form "(col NOT IN (null) OR 1 = 1)".
  2628. # The presence of the OR makes the brackets required.
  2629. return "(%s)" % self._generate_generic_binary(
  2630. binary, OPERATORS[operator], **kw
  2631. )
  2632. def visit_empty_set_op_expr(self, type_, expand_op, **kw):
  2633. if expand_op is operators.not_in_op:
  2634. if len(type_) > 1:
  2635. return "(%s)) OR (1 = 1" % (
  2636. ", ".join("NULL" for element in type_)
  2637. )
  2638. else:
  2639. return "NULL) OR (1 = 1"
  2640. elif expand_op is operators.in_op:
  2641. if len(type_) > 1:
  2642. return "(%s)) AND (1 != 1" % (
  2643. ", ".join("NULL" for element in type_)
  2644. )
  2645. else:
  2646. return "NULL) AND (1 != 1"
  2647. else:
  2648. return self.visit_empty_set_expr(type_)
  2649. def visit_empty_set_expr(self, element_types, **kw):
  2650. raise NotImplementedError(
  2651. "Dialect '%s' does not support empty set expression."
  2652. % self.dialect.name
  2653. )
  2654. def _literal_execute_expanding_parameter_literal_binds(
  2655. self, parameter, values, bind_expression_template=None
  2656. ):
  2657. typ_dialect_impl = parameter.type._unwrapped_dialect_impl(self.dialect)
  2658. if not values:
  2659. # empty IN expression. note we don't need to use
  2660. # bind_expression_template here because there are no
  2661. # expressions to render.
  2662. if typ_dialect_impl._is_tuple_type:
  2663. replacement_expression = (
  2664. "VALUES " if self.dialect.tuple_in_values else ""
  2665. ) + self.visit_empty_set_op_expr(
  2666. parameter.type.types, parameter.expand_op
  2667. )
  2668. else:
  2669. replacement_expression = self.visit_empty_set_op_expr(
  2670. [parameter.type], parameter.expand_op
  2671. )
  2672. elif typ_dialect_impl._is_tuple_type or (
  2673. typ_dialect_impl._isnull
  2674. and isinstance(values[0], collections_abc.Sequence)
  2675. and not isinstance(values[0], (str, bytes))
  2676. ):
  2677. if typ_dialect_impl._has_bind_expression:
  2678. raise NotImplementedError(
  2679. "bind_expression() on TupleType not supported with "
  2680. "literal_binds"
  2681. )
  2682. replacement_expression = (
  2683. "VALUES " if self.dialect.tuple_in_values else ""
  2684. ) + ", ".join(
  2685. "(%s)"
  2686. % (
  2687. ", ".join(
  2688. self.render_literal_value(value, param_type)
  2689. for value, param_type in zip(
  2690. tuple_element, parameter.type.types
  2691. )
  2692. )
  2693. )
  2694. for i, tuple_element in enumerate(values)
  2695. )
  2696. else:
  2697. if bind_expression_template:
  2698. post_compile_pattern = self._post_compile_pattern
  2699. m = post_compile_pattern.search(bind_expression_template)
  2700. assert m and m.group(
  2701. 2
  2702. ), "unexpected format for expanding parameter"
  2703. tok = m.group(2).split("~~")
  2704. be_left, be_right = tok[1], tok[3]
  2705. replacement_expression = ", ".join(
  2706. "%s%s%s"
  2707. % (
  2708. be_left,
  2709. self.render_literal_value(value, parameter.type),
  2710. be_right,
  2711. )
  2712. for value in values
  2713. )
  2714. else:
  2715. replacement_expression = ", ".join(
  2716. self.render_literal_value(value, parameter.type)
  2717. for value in values
  2718. )
  2719. return (), replacement_expression
  2720. def _literal_execute_expanding_parameter(self, name, parameter, values):
  2721. if parameter.literal_execute:
  2722. return self._literal_execute_expanding_parameter_literal_binds(
  2723. parameter, values
  2724. )
  2725. dialect = self.dialect
  2726. typ_dialect_impl = parameter.type._unwrapped_dialect_impl(dialect)
  2727. if self._numeric_binds:
  2728. bind_template = self.compilation_bindtemplate
  2729. else:
  2730. bind_template = self.bindtemplate
  2731. if (
  2732. self.dialect._bind_typing_render_casts
  2733. and typ_dialect_impl.render_bind_cast
  2734. ):
  2735. def _render_bindtemplate(name):
  2736. return self.render_bind_cast(
  2737. parameter.type,
  2738. typ_dialect_impl,
  2739. bind_template % {"name": name},
  2740. )
  2741. else:
  2742. def _render_bindtemplate(name):
  2743. return bind_template % {"name": name}
  2744. if not values:
  2745. to_update = []
  2746. if typ_dialect_impl._is_tuple_type:
  2747. replacement_expression = self.visit_empty_set_op_expr(
  2748. parameter.type.types, parameter.expand_op
  2749. )
  2750. else:
  2751. replacement_expression = self.visit_empty_set_op_expr(
  2752. [parameter.type], parameter.expand_op
  2753. )
  2754. elif typ_dialect_impl._is_tuple_type or (
  2755. typ_dialect_impl._isnull
  2756. and isinstance(values[0], collections_abc.Sequence)
  2757. and not isinstance(values[0], (str, bytes))
  2758. ):
  2759. assert not typ_dialect_impl._is_array
  2760. to_update = [
  2761. ("%s_%s_%s" % (name, i, j), value)
  2762. for i, tuple_element in enumerate(values, 1)
  2763. for j, value in enumerate(tuple_element, 1)
  2764. ]
  2765. replacement_expression = (
  2766. "VALUES " if dialect.tuple_in_values else ""
  2767. ) + ", ".join(
  2768. "(%s)"
  2769. % (
  2770. ", ".join(
  2771. _render_bindtemplate(
  2772. to_update[i * len(tuple_element) + j][0]
  2773. )
  2774. for j, value in enumerate(tuple_element)
  2775. )
  2776. )
  2777. for i, tuple_element in enumerate(values)
  2778. )
  2779. else:
  2780. to_update = [
  2781. ("%s_%s" % (name, i), value)
  2782. for i, value in enumerate(values, 1)
  2783. ]
  2784. replacement_expression = ", ".join(
  2785. _render_bindtemplate(key) for key, value in to_update
  2786. )
  2787. return to_update, replacement_expression
  2788. def visit_binary(
  2789. self,
  2790. binary,
  2791. override_operator=None,
  2792. eager_grouping=False,
  2793. from_linter=None,
  2794. lateral_from_linter=None,
  2795. **kw,
  2796. ):
  2797. if from_linter and operators.is_comparison(binary.operator):
  2798. if lateral_from_linter is not None:
  2799. enclosing_lateral = kw["enclosing_lateral"]
  2800. lateral_from_linter.edges.update(
  2801. itertools.product(
  2802. _de_clone(
  2803. binary.left._from_objects + [enclosing_lateral]
  2804. ),
  2805. _de_clone(
  2806. binary.right._from_objects + [enclosing_lateral]
  2807. ),
  2808. )
  2809. )
  2810. else:
  2811. from_linter.edges.update(
  2812. itertools.product(
  2813. _de_clone(binary.left._from_objects),
  2814. _de_clone(binary.right._from_objects),
  2815. )
  2816. )
  2817. # don't allow "? = ?" to render
  2818. if (
  2819. self.ansi_bind_rules
  2820. and isinstance(binary.left, elements.BindParameter)
  2821. and isinstance(binary.right, elements.BindParameter)
  2822. ):
  2823. kw["literal_execute"] = True
  2824. operator_ = override_operator or binary.operator
  2825. disp = self._get_operator_dispatch(operator_, "binary", None)
  2826. if disp:
  2827. return disp(binary, operator_, **kw)
  2828. else:
  2829. try:
  2830. opstring = OPERATORS[operator_]
  2831. except KeyError as err:
  2832. raise exc.UnsupportedCompilationError(self, operator_) from err
  2833. else:
  2834. return self._generate_generic_binary(
  2835. binary,
  2836. opstring,
  2837. from_linter=from_linter,
  2838. lateral_from_linter=lateral_from_linter,
  2839. **kw,
  2840. )
  2841. def visit_function_as_comparison_op_binary(self, element, operator, **kw):
  2842. return self.process(element.sql_function, **kw)
  2843. def visit_mod_binary(self, binary, operator, **kw):
  2844. if self.preparer._double_percents:
  2845. return (
  2846. self.process(binary.left, **kw)
  2847. + " %% "
  2848. + self.process(binary.right, **kw)
  2849. )
  2850. else:
  2851. return (
  2852. self.process(binary.left, **kw)
  2853. + " % "
  2854. + self.process(binary.right, **kw)
  2855. )
  2856. def visit_custom_op_binary(self, element, operator, **kw):
  2857. kw["eager_grouping"] = operator.eager_grouping
  2858. return self._generate_generic_binary(
  2859. element,
  2860. " " + self.escape_literal_column(operator.opstring) + " ",
  2861. **kw,
  2862. )
  2863. def visit_custom_op_unary_operator(self, element, operator, **kw):
  2864. return self._generate_generic_unary_operator(
  2865. element, self.escape_literal_column(operator.opstring) + " ", **kw
  2866. )
  2867. def visit_custom_op_unary_modifier(self, element, operator, **kw):
  2868. return self._generate_generic_unary_modifier(
  2869. element, " " + self.escape_literal_column(operator.opstring), **kw
  2870. )
  2871. def _generate_generic_binary(
  2872. self,
  2873. binary: BinaryExpression[Any],
  2874. opstring: str,
  2875. eager_grouping: bool = False,
  2876. **kw: Any,
  2877. ) -> str:
  2878. _in_operator_expression = kw.get("_in_operator_expression", False)
  2879. kw["_in_operator_expression"] = True
  2880. kw["_binary_op"] = binary.operator
  2881. text = (
  2882. binary.left._compiler_dispatch(
  2883. self, eager_grouping=eager_grouping, **kw
  2884. )
  2885. + opstring
  2886. + binary.right._compiler_dispatch(
  2887. self, eager_grouping=eager_grouping, **kw
  2888. )
  2889. )
  2890. if _in_operator_expression and eager_grouping:
  2891. text = "(%s)" % text
  2892. return text
  2893. def _generate_generic_unary_operator(self, unary, opstring, **kw):
  2894. return opstring + unary.element._compiler_dispatch(self, **kw)
  2895. def _generate_generic_unary_modifier(self, unary, opstring, **kw):
  2896. return unary.element._compiler_dispatch(self, **kw) + opstring
  2897. @util.memoized_property
  2898. def _like_percent_literal(self):
  2899. return elements.literal_column("'%'", type_=sqltypes.STRINGTYPE)
  2900. def visit_ilike_case_insensitive_operand(self, element, **kw):
  2901. return f"lower({element.element._compiler_dispatch(self, **kw)})"
  2902. def visit_contains_op_binary(self, binary, operator, **kw):
  2903. binary = binary._clone()
  2904. percent = self._like_percent_literal
  2905. binary.right = percent.concat(binary.right).concat(percent)
  2906. return self.visit_like_op_binary(binary, operator, **kw)
  2907. def visit_not_contains_op_binary(self, binary, operator, **kw):
  2908. binary = binary._clone()
  2909. percent = self._like_percent_literal
  2910. binary.right = percent.concat(binary.right).concat(percent)
  2911. return self.visit_not_like_op_binary(binary, operator, **kw)
  2912. def visit_icontains_op_binary(self, binary, operator, **kw):
  2913. binary = binary._clone()
  2914. percent = self._like_percent_literal
  2915. binary.left = ilike_case_insensitive(binary.left)
  2916. binary.right = percent.concat(
  2917. ilike_case_insensitive(binary.right)
  2918. ).concat(percent)
  2919. return self.visit_ilike_op_binary(binary, operator, **kw)
  2920. def visit_not_icontains_op_binary(self, binary, operator, **kw):
  2921. binary = binary._clone()
  2922. percent = self._like_percent_literal
  2923. binary.left = ilike_case_insensitive(binary.left)
  2924. binary.right = percent.concat(
  2925. ilike_case_insensitive(binary.right)
  2926. ).concat(percent)
  2927. return self.visit_not_ilike_op_binary(binary, operator, **kw)
  2928. def visit_startswith_op_binary(self, binary, operator, **kw):
  2929. binary = binary._clone()
  2930. percent = self._like_percent_literal
  2931. binary.right = percent._rconcat(binary.right)
  2932. return self.visit_like_op_binary(binary, operator, **kw)
  2933. def visit_not_startswith_op_binary(self, binary, operator, **kw):
  2934. binary = binary._clone()
  2935. percent = self._like_percent_literal
  2936. binary.right = percent._rconcat(binary.right)
  2937. return self.visit_not_like_op_binary(binary, operator, **kw)
  2938. def visit_istartswith_op_binary(self, binary, operator, **kw):
  2939. binary = binary._clone()
  2940. percent = self._like_percent_literal
  2941. binary.left = ilike_case_insensitive(binary.left)
  2942. binary.right = percent._rconcat(ilike_case_insensitive(binary.right))
  2943. return self.visit_ilike_op_binary(binary, operator, **kw)
  2944. def visit_not_istartswith_op_binary(self, binary, operator, **kw):
  2945. binary = binary._clone()
  2946. percent = self._like_percent_literal
  2947. binary.left = ilike_case_insensitive(binary.left)
  2948. binary.right = percent._rconcat(ilike_case_insensitive(binary.right))
  2949. return self.visit_not_ilike_op_binary(binary, operator, **kw)
  2950. def visit_endswith_op_binary(self, binary, operator, **kw):
  2951. binary = binary._clone()
  2952. percent = self._like_percent_literal
  2953. binary.right = percent.concat(binary.right)
  2954. return self.visit_like_op_binary(binary, operator, **kw)
  2955. def visit_not_endswith_op_binary(self, binary, operator, **kw):
  2956. binary = binary._clone()
  2957. percent = self._like_percent_literal
  2958. binary.right = percent.concat(binary.right)
  2959. return self.visit_not_like_op_binary(binary, operator, **kw)
  2960. def visit_iendswith_op_binary(self, binary, operator, **kw):
  2961. binary = binary._clone()
  2962. percent = self._like_percent_literal
  2963. binary.left = ilike_case_insensitive(binary.left)
  2964. binary.right = percent.concat(ilike_case_insensitive(binary.right))
  2965. return self.visit_ilike_op_binary(binary, operator, **kw)
  2966. def visit_not_iendswith_op_binary(self, binary, operator, **kw):
  2967. binary = binary._clone()
  2968. percent = self._like_percent_literal
  2969. binary.left = ilike_case_insensitive(binary.left)
  2970. binary.right = percent.concat(ilike_case_insensitive(binary.right))
  2971. return self.visit_not_ilike_op_binary(binary, operator, **kw)
  2972. def visit_like_op_binary(self, binary, operator, **kw):
  2973. escape = binary.modifiers.get("escape", None)
  2974. return "%s LIKE %s" % (
  2975. binary.left._compiler_dispatch(self, **kw),
  2976. binary.right._compiler_dispatch(self, **kw),
  2977. ) + (
  2978. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  2979. if escape is not None
  2980. else ""
  2981. )
  2982. def visit_not_like_op_binary(self, binary, operator, **kw):
  2983. escape = binary.modifiers.get("escape", None)
  2984. return "%s NOT LIKE %s" % (
  2985. binary.left._compiler_dispatch(self, **kw),
  2986. binary.right._compiler_dispatch(self, **kw),
  2987. ) + (
  2988. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  2989. if escape is not None
  2990. else ""
  2991. )
  2992. def visit_ilike_op_binary(self, binary, operator, **kw):
  2993. if operator is operators.ilike_op:
  2994. binary = binary._clone()
  2995. binary.left = ilike_case_insensitive(binary.left)
  2996. binary.right = ilike_case_insensitive(binary.right)
  2997. # else we assume ilower() has been applied
  2998. return self.visit_like_op_binary(binary, operator, **kw)
  2999. def visit_not_ilike_op_binary(self, binary, operator, **kw):
  3000. if operator is operators.not_ilike_op:
  3001. binary = binary._clone()
  3002. binary.left = ilike_case_insensitive(binary.left)
  3003. binary.right = ilike_case_insensitive(binary.right)
  3004. # else we assume ilower() has been applied
  3005. return self.visit_not_like_op_binary(binary, operator, **kw)
  3006. def visit_between_op_binary(self, binary, operator, **kw):
  3007. symmetric = binary.modifiers.get("symmetric", False)
  3008. return self._generate_generic_binary(
  3009. binary, " BETWEEN SYMMETRIC " if symmetric else " BETWEEN ", **kw
  3010. )
  3011. def visit_not_between_op_binary(self, binary, operator, **kw):
  3012. symmetric = binary.modifiers.get("symmetric", False)
  3013. return self._generate_generic_binary(
  3014. binary,
  3015. " NOT BETWEEN SYMMETRIC " if symmetric else " NOT BETWEEN ",
  3016. **kw,
  3017. )
  3018. def visit_regexp_match_op_binary(
  3019. self, binary: BinaryExpression[Any], operator: Any, **kw: Any
  3020. ) -> str:
  3021. raise exc.CompileError(
  3022. "%s dialect does not support regular expressions"
  3023. % self.dialect.name
  3024. )
  3025. def visit_not_regexp_match_op_binary(
  3026. self, binary: BinaryExpression[Any], operator: Any, **kw: Any
  3027. ) -> str:
  3028. raise exc.CompileError(
  3029. "%s dialect does not support regular expressions"
  3030. % self.dialect.name
  3031. )
  3032. def visit_regexp_replace_op_binary(
  3033. self, binary: BinaryExpression[Any], operator: Any, **kw: Any
  3034. ) -> str:
  3035. raise exc.CompileError(
  3036. "%s dialect does not support regular expression replacements"
  3037. % self.dialect.name
  3038. )
  3039. def visit_bindparam(
  3040. self,
  3041. bindparam,
  3042. within_columns_clause=False,
  3043. literal_binds=False,
  3044. skip_bind_expression=False,
  3045. literal_execute=False,
  3046. render_postcompile=False,
  3047. **kwargs,
  3048. ):
  3049. if not skip_bind_expression:
  3050. impl = bindparam.type.dialect_impl(self.dialect)
  3051. if impl._has_bind_expression:
  3052. bind_expression = impl.bind_expression(bindparam)
  3053. wrapped = self.process(
  3054. bind_expression,
  3055. skip_bind_expression=True,
  3056. within_columns_clause=within_columns_clause,
  3057. literal_binds=literal_binds and not bindparam.expanding,
  3058. literal_execute=literal_execute,
  3059. render_postcompile=render_postcompile,
  3060. **kwargs,
  3061. )
  3062. if bindparam.expanding:
  3063. # for postcompile w/ expanding, move the "wrapped" part
  3064. # of this into the inside
  3065. m = re.match(
  3066. r"^(.*)\(__\[POSTCOMPILE_(\S+?)\]\)(.*)$", wrapped
  3067. )
  3068. assert m, "unexpected format for expanding parameter"
  3069. wrapped = "(__[POSTCOMPILE_%s~~%s~~REPL~~%s~~])" % (
  3070. m.group(2),
  3071. m.group(1),
  3072. m.group(3),
  3073. )
  3074. if literal_binds:
  3075. ret = self.render_literal_bindparam(
  3076. bindparam,
  3077. within_columns_clause=True,
  3078. bind_expression_template=wrapped,
  3079. **kwargs,
  3080. )
  3081. return "(%s)" % ret
  3082. return wrapped
  3083. if not literal_binds:
  3084. literal_execute = (
  3085. literal_execute
  3086. or bindparam.literal_execute
  3087. or (within_columns_clause and self.ansi_bind_rules)
  3088. )
  3089. post_compile = literal_execute or bindparam.expanding
  3090. else:
  3091. post_compile = False
  3092. if literal_binds:
  3093. ret = self.render_literal_bindparam(
  3094. bindparam, within_columns_clause=True, **kwargs
  3095. )
  3096. if bindparam.expanding:
  3097. ret = "(%s)" % ret
  3098. return ret
  3099. name = self._truncate_bindparam(bindparam)
  3100. if name in self.binds:
  3101. existing = self.binds[name]
  3102. if existing is not bindparam:
  3103. if (
  3104. (existing.unique or bindparam.unique)
  3105. and not existing.proxy_set.intersection(
  3106. bindparam.proxy_set
  3107. )
  3108. and not existing._cloned_set.intersection(
  3109. bindparam._cloned_set
  3110. )
  3111. ):
  3112. raise exc.CompileError(
  3113. "Bind parameter '%s' conflicts with "
  3114. "unique bind parameter of the same name" % name
  3115. )
  3116. elif existing.expanding != bindparam.expanding:
  3117. raise exc.CompileError(
  3118. "Can't reuse bound parameter name '%s' in both "
  3119. "'expanding' (e.g. within an IN expression) and "
  3120. "non-expanding contexts. If this parameter is to "
  3121. "receive a list/array value, set 'expanding=True' on "
  3122. "it for expressions that aren't IN, otherwise use "
  3123. "a different parameter name." % (name,)
  3124. )
  3125. elif existing._is_crud or bindparam._is_crud:
  3126. if existing._is_crud and bindparam._is_crud:
  3127. # TODO: this condition is not well understood.
  3128. # see tests in test/sql/test_update.py
  3129. raise exc.CompileError(
  3130. "Encountered unsupported case when compiling an "
  3131. "INSERT or UPDATE statement. If this is a "
  3132. "multi-table "
  3133. "UPDATE statement, please provide string-named "
  3134. "arguments to the "
  3135. "values() method with distinct names; support for "
  3136. "multi-table UPDATE statements that "
  3137. "target multiple tables for UPDATE is very "
  3138. "limited",
  3139. )
  3140. else:
  3141. raise exc.CompileError(
  3142. f"bindparam() name '{bindparam.key}' is reserved "
  3143. "for automatic usage in the VALUES or SET "
  3144. "clause of this "
  3145. "insert/update statement. Please use a "
  3146. "name other than column name when using "
  3147. "bindparam() "
  3148. "with insert() or update() (for example, "
  3149. f"'b_{bindparam.key}')."
  3150. )
  3151. self.binds[bindparam.key] = self.binds[name] = bindparam
  3152. # if we are given a cache key that we're going to match against,
  3153. # relate the bindparam here to one that is most likely present
  3154. # in the "extracted params" portion of the cache key. this is used
  3155. # to set up a positional mapping that is used to determine the
  3156. # correct parameters for a subsequent use of this compiled with
  3157. # a different set of parameter values. here, we accommodate for
  3158. # parameters that may have been cloned both before and after the cache
  3159. # key was been generated.
  3160. ckbm_tuple = self._cache_key_bind_match
  3161. if ckbm_tuple:
  3162. ckbm, cksm = ckbm_tuple
  3163. for bp in bindparam._cloned_set:
  3164. if bp.key in cksm:
  3165. cb = cksm[bp.key]
  3166. ckbm[cb].append(bindparam)
  3167. if bindparam.isoutparam:
  3168. self.has_out_parameters = True
  3169. if post_compile:
  3170. if render_postcompile:
  3171. self._render_postcompile = True
  3172. if literal_execute:
  3173. self.literal_execute_params |= {bindparam}
  3174. else:
  3175. self.post_compile_params |= {bindparam}
  3176. ret = self.bindparam_string(
  3177. name,
  3178. post_compile=post_compile,
  3179. expanding=bindparam.expanding,
  3180. bindparam_type=bindparam.type,
  3181. **kwargs,
  3182. )
  3183. if bindparam.expanding:
  3184. ret = "(%s)" % ret
  3185. return ret
  3186. def render_bind_cast(self, type_, dbapi_type, sqltext):
  3187. raise NotImplementedError()
  3188. def render_literal_bindparam(
  3189. self,
  3190. bindparam,
  3191. render_literal_value=NO_ARG,
  3192. bind_expression_template=None,
  3193. **kw,
  3194. ):
  3195. if render_literal_value is not NO_ARG:
  3196. value = render_literal_value
  3197. else:
  3198. if bindparam.value is None and bindparam.callable is None:
  3199. op = kw.get("_binary_op", None)
  3200. if op and op not in (operators.is_, operators.is_not):
  3201. util.warn_limited(
  3202. "Bound parameter '%s' rendering literal NULL in a SQL "
  3203. "expression; comparisons to NULL should not use "
  3204. "operators outside of 'is' or 'is not'",
  3205. (bindparam.key,),
  3206. )
  3207. return self.process(sqltypes.NULLTYPE, **kw)
  3208. value = bindparam.effective_value
  3209. if bindparam.expanding:
  3210. leep = self._literal_execute_expanding_parameter_literal_binds
  3211. to_update, replacement_expr = leep(
  3212. bindparam,
  3213. value,
  3214. bind_expression_template=bind_expression_template,
  3215. )
  3216. return replacement_expr
  3217. else:
  3218. return self.render_literal_value(value, bindparam.type)
  3219. def render_literal_value(
  3220. self, value: Any, type_: sqltypes.TypeEngine[Any]
  3221. ) -> str:
  3222. """Render the value of a bind parameter as a quoted literal.
  3223. This is used for statement sections that do not accept bind parameters
  3224. on the target driver/database.
  3225. This should be implemented by subclasses using the quoting services
  3226. of the DBAPI.
  3227. """
  3228. if value is None and not type_.should_evaluate_none:
  3229. # issue #10535 - handle NULL in the compiler without placing
  3230. # this onto each type, except for "evaluate None" types
  3231. # (e.g. JSON)
  3232. return self.process(elements.Null._instance())
  3233. processor = type_._cached_literal_processor(self.dialect)
  3234. if processor:
  3235. try:
  3236. return processor(value)
  3237. except Exception as e:
  3238. raise exc.CompileError(
  3239. f"Could not render literal value "
  3240. f'"{sql_util._repr_single_value(value)}" '
  3241. f"with datatype "
  3242. f"{type_}; see parent stack trace for "
  3243. "more detail."
  3244. ) from e
  3245. else:
  3246. raise exc.CompileError(
  3247. f"No literal value renderer is available for literal value "
  3248. f'"{sql_util._repr_single_value(value)}" '
  3249. f"with datatype {type_}"
  3250. )
  3251. def _truncate_bindparam(self, bindparam):
  3252. if bindparam in self.bind_names:
  3253. return self.bind_names[bindparam]
  3254. bind_name = bindparam.key
  3255. if isinstance(bind_name, elements._truncated_label):
  3256. bind_name = self._truncated_identifier("bindparam", bind_name)
  3257. # add to bind_names for translation
  3258. self.bind_names[bindparam] = bind_name
  3259. return bind_name
  3260. def _truncated_identifier(
  3261. self, ident_class: str, name: _truncated_label
  3262. ) -> str:
  3263. if (ident_class, name) in self.truncated_names:
  3264. return self.truncated_names[(ident_class, name)]
  3265. anonname = name.apply_map(self.anon_map)
  3266. if len(anonname) > self.label_length - 6:
  3267. counter = self._truncated_counters.get(ident_class, 1)
  3268. truncname = (
  3269. anonname[0 : max(self.label_length - 6, 0)]
  3270. + "_"
  3271. + hex(counter)[2:]
  3272. )
  3273. self._truncated_counters[ident_class] = counter + 1
  3274. else:
  3275. truncname = anonname
  3276. self.truncated_names[(ident_class, name)] = truncname
  3277. return truncname
  3278. def _anonymize(self, name: str) -> str:
  3279. return name % self.anon_map
  3280. def bindparam_string(
  3281. self,
  3282. name: str,
  3283. post_compile: bool = False,
  3284. expanding: bool = False,
  3285. escaped_from: Optional[str] = None,
  3286. bindparam_type: Optional[TypeEngine[Any]] = None,
  3287. accumulate_bind_names: Optional[Set[str]] = None,
  3288. visited_bindparam: Optional[List[str]] = None,
  3289. **kw: Any,
  3290. ) -> str:
  3291. # TODO: accumulate_bind_names is passed by crud.py to gather
  3292. # names on a per-value basis, visited_bindparam is passed by
  3293. # visit_insert() to collect all parameters in the statement.
  3294. # see if this gathering can be simplified somehow
  3295. if accumulate_bind_names is not None:
  3296. accumulate_bind_names.add(name)
  3297. if visited_bindparam is not None:
  3298. visited_bindparam.append(name)
  3299. if not escaped_from:
  3300. if self._bind_translate_re.search(name):
  3301. # not quite the translate use case as we want to
  3302. # also get a quick boolean if we even found
  3303. # unusual characters in the name
  3304. new_name = self._bind_translate_re.sub(
  3305. lambda m: self._bind_translate_chars[m.group(0)],
  3306. name,
  3307. )
  3308. escaped_from = name
  3309. name = new_name
  3310. if escaped_from:
  3311. self.escaped_bind_names = self.escaped_bind_names.union(
  3312. {escaped_from: name}
  3313. )
  3314. if post_compile:
  3315. ret = "__[POSTCOMPILE_%s]" % name
  3316. if expanding:
  3317. # for expanding, bound parameters or literal values will be
  3318. # rendered per item
  3319. return ret
  3320. # otherwise, for non-expanding "literal execute", apply
  3321. # bind casts as determined by the datatype
  3322. if bindparam_type is not None:
  3323. type_impl = bindparam_type._unwrapped_dialect_impl(
  3324. self.dialect
  3325. )
  3326. if type_impl.render_literal_cast:
  3327. ret = self.render_bind_cast(bindparam_type, type_impl, ret)
  3328. return ret
  3329. elif self.state is CompilerState.COMPILING:
  3330. ret = self.compilation_bindtemplate % {"name": name}
  3331. else:
  3332. ret = self.bindtemplate % {"name": name}
  3333. if (
  3334. bindparam_type is not None
  3335. and self.dialect._bind_typing_render_casts
  3336. ):
  3337. type_impl = bindparam_type._unwrapped_dialect_impl(self.dialect)
  3338. if type_impl.render_bind_cast:
  3339. ret = self.render_bind_cast(bindparam_type, type_impl, ret)
  3340. return ret
  3341. def _dispatch_independent_ctes(self, stmt, kw):
  3342. local_kw = kw.copy()
  3343. local_kw.pop("cte_opts", None)
  3344. for cte, opt in zip(
  3345. stmt._independent_ctes, stmt._independent_ctes_opts
  3346. ):
  3347. cte._compiler_dispatch(self, cte_opts=opt, **local_kw)
  3348. def visit_cte(
  3349. self,
  3350. cte: CTE,
  3351. asfrom: bool = False,
  3352. ashint: bool = False,
  3353. fromhints: Optional[_FromHintsType] = None,
  3354. visiting_cte: Optional[CTE] = None,
  3355. from_linter: Optional[FromLinter] = None,
  3356. cte_opts: selectable._CTEOpts = selectable._CTEOpts(False),
  3357. **kwargs: Any,
  3358. ) -> Optional[str]:
  3359. self_ctes = self._init_cte_state()
  3360. assert self_ctes is self.ctes
  3361. kwargs["visiting_cte"] = cte
  3362. cte_name = cte.name
  3363. if isinstance(cte_name, elements._truncated_label):
  3364. cte_name = self._truncated_identifier("alias", cte_name)
  3365. is_new_cte = True
  3366. embedded_in_current_named_cte = False
  3367. _reference_cte = cte._get_reference_cte()
  3368. nesting = cte.nesting or cte_opts.nesting
  3369. # check for CTE already encountered
  3370. if _reference_cte in self.level_name_by_cte:
  3371. cte_level, _, existing_cte_opts = self.level_name_by_cte[
  3372. _reference_cte
  3373. ]
  3374. assert _ == cte_name
  3375. cte_level_name = (cte_level, cte_name)
  3376. existing_cte = self.ctes_by_level_name[cte_level_name]
  3377. # check if we are receiving it here with a specific
  3378. # "nest_here" location; if so, move it to this location
  3379. if cte_opts.nesting:
  3380. if existing_cte_opts.nesting:
  3381. raise exc.CompileError(
  3382. "CTE is stated as 'nest_here' in "
  3383. "more than one location"
  3384. )
  3385. old_level_name = (cte_level, cte_name)
  3386. cte_level = len(self.stack) if nesting else 1
  3387. cte_level_name = new_level_name = (cte_level, cte_name)
  3388. del self.ctes_by_level_name[old_level_name]
  3389. self.ctes_by_level_name[new_level_name] = existing_cte
  3390. self.level_name_by_cte[_reference_cte] = new_level_name + (
  3391. cte_opts,
  3392. )
  3393. else:
  3394. cte_level = len(self.stack) if nesting else 1
  3395. cte_level_name = (cte_level, cte_name)
  3396. if cte_level_name in self.ctes_by_level_name:
  3397. existing_cte = self.ctes_by_level_name[cte_level_name]
  3398. else:
  3399. existing_cte = None
  3400. if existing_cte is not None:
  3401. embedded_in_current_named_cte = visiting_cte is existing_cte
  3402. # we've generated a same-named CTE that we are enclosed in,
  3403. # or this is the same CTE. just return the name.
  3404. if cte is existing_cte._restates or cte is existing_cte:
  3405. is_new_cte = False
  3406. elif existing_cte is cte._restates:
  3407. # we've generated a same-named CTE that is
  3408. # enclosed in us - we take precedence, so
  3409. # discard the text for the "inner".
  3410. del self_ctes[existing_cte]
  3411. existing_cte_reference_cte = existing_cte._get_reference_cte()
  3412. assert existing_cte_reference_cte is _reference_cte
  3413. assert existing_cte_reference_cte is existing_cte
  3414. del self.level_name_by_cte[existing_cte_reference_cte]
  3415. else:
  3416. if (
  3417. # if the two CTEs have the same hash, which we expect
  3418. # here means that one/both is an annotated of the other
  3419. (hash(cte) == hash(existing_cte))
  3420. # or...
  3421. or (
  3422. (
  3423. # if they are clones, i.e. they came from the ORM
  3424. # or some other visit method
  3425. cte._is_clone_of is not None
  3426. or existing_cte._is_clone_of is not None
  3427. )
  3428. # and are deep-copy identical
  3429. and cte.compare(existing_cte)
  3430. )
  3431. ):
  3432. # then consider these two CTEs the same
  3433. is_new_cte = False
  3434. else:
  3435. # otherwise these are two CTEs that either will render
  3436. # differently, or were indicated separately by the user,
  3437. # with the same name
  3438. raise exc.CompileError(
  3439. "Multiple, unrelated CTEs found with "
  3440. "the same name: %r" % cte_name
  3441. )
  3442. if not asfrom and not is_new_cte:
  3443. return None
  3444. if cte._cte_alias is not None:
  3445. pre_alias_cte = cte._cte_alias
  3446. cte_pre_alias_name = cte._cte_alias.name
  3447. if isinstance(cte_pre_alias_name, elements._truncated_label):
  3448. cte_pre_alias_name = self._truncated_identifier(
  3449. "alias", cte_pre_alias_name
  3450. )
  3451. else:
  3452. pre_alias_cte = cte
  3453. cte_pre_alias_name = None
  3454. if is_new_cte:
  3455. self.ctes_by_level_name[cte_level_name] = cte
  3456. self.level_name_by_cte[_reference_cte] = cte_level_name + (
  3457. cte_opts,
  3458. )
  3459. if pre_alias_cte not in self.ctes:
  3460. self.visit_cte(pre_alias_cte, **kwargs)
  3461. if not cte_pre_alias_name and cte not in self_ctes:
  3462. if cte.recursive:
  3463. self.ctes_recursive = True
  3464. text = self.preparer.format_alias(cte, cte_name)
  3465. if cte.recursive:
  3466. col_source = cte.element
  3467. # TODO: can we get at the .columns_plus_names collection
  3468. # that is already (or will be?) generated for the SELECT
  3469. # rather than calling twice?
  3470. recur_cols = [
  3471. # TODO: proxy_name is not technically safe,
  3472. # see test_cte->
  3473. # test_with_recursive_no_name_currently_buggy. not
  3474. # clear what should be done with such a case
  3475. fallback_label_name or proxy_name
  3476. for (
  3477. _,
  3478. proxy_name,
  3479. fallback_label_name,
  3480. c,
  3481. repeated,
  3482. ) in (col_source._generate_columns_plus_names(True))
  3483. if not repeated
  3484. ]
  3485. text += "(%s)" % (
  3486. ", ".join(
  3487. self.preparer.format_label_name(
  3488. ident, anon_map=self.anon_map
  3489. )
  3490. for ident in recur_cols
  3491. )
  3492. )
  3493. assert kwargs.get("subquery", False) is False
  3494. if not self.stack:
  3495. # toplevel, this is a stringify of the
  3496. # cte directly. just compile the inner
  3497. # the way alias() does.
  3498. return cte.element._compiler_dispatch(
  3499. self, asfrom=asfrom, **kwargs
  3500. )
  3501. else:
  3502. prefixes = self._generate_prefixes(
  3503. cte, cte._prefixes, **kwargs
  3504. )
  3505. inner = cte.element._compiler_dispatch(
  3506. self, asfrom=True, **kwargs
  3507. )
  3508. text += " AS %s\n(%s)" % (prefixes, inner)
  3509. if cte._suffixes:
  3510. text += " " + self._generate_prefixes(
  3511. cte, cte._suffixes, **kwargs
  3512. )
  3513. self_ctes[cte] = text
  3514. if asfrom:
  3515. if from_linter:
  3516. from_linter.froms[cte._de_clone()] = cte_name
  3517. if not is_new_cte and embedded_in_current_named_cte:
  3518. return self.preparer.format_alias(cte, cte_name)
  3519. if cte_pre_alias_name:
  3520. text = self.preparer.format_alias(cte, cte_pre_alias_name)
  3521. if self.preparer._requires_quotes(cte_name):
  3522. cte_name = self.preparer.quote(cte_name)
  3523. text += self.get_render_as_alias_suffix(cte_name)
  3524. return text
  3525. else:
  3526. return self.preparer.format_alias(cte, cte_name)
  3527. return None
  3528. def visit_table_valued_alias(self, element, **kw):
  3529. if element.joins_implicitly:
  3530. kw["from_linter"] = None
  3531. if element._is_lateral:
  3532. return self.visit_lateral(element, **kw)
  3533. else:
  3534. return self.visit_alias(element, **kw)
  3535. def visit_table_valued_column(self, element, **kw):
  3536. return self.visit_column(element, **kw)
  3537. def visit_alias(
  3538. self,
  3539. alias,
  3540. asfrom=False,
  3541. ashint=False,
  3542. iscrud=False,
  3543. fromhints=None,
  3544. subquery=False,
  3545. lateral=False,
  3546. enclosing_alias=None,
  3547. from_linter=None,
  3548. **kwargs,
  3549. ):
  3550. if lateral:
  3551. if "enclosing_lateral" not in kwargs:
  3552. # if lateral is set and enclosing_lateral is not
  3553. # present, we assume we are being called directly
  3554. # from visit_lateral() and we need to set enclosing_lateral.
  3555. assert alias._is_lateral
  3556. kwargs["enclosing_lateral"] = alias
  3557. # for lateral objects, we track a second from_linter that is...
  3558. # lateral! to the level above us.
  3559. if (
  3560. from_linter
  3561. and "lateral_from_linter" not in kwargs
  3562. and "enclosing_lateral" in kwargs
  3563. ):
  3564. kwargs["lateral_from_linter"] = from_linter
  3565. if enclosing_alias is not None and enclosing_alias.element is alias:
  3566. inner = alias.element._compiler_dispatch(
  3567. self,
  3568. asfrom=asfrom,
  3569. ashint=ashint,
  3570. iscrud=iscrud,
  3571. fromhints=fromhints,
  3572. lateral=lateral,
  3573. enclosing_alias=alias,
  3574. **kwargs,
  3575. )
  3576. if subquery and (asfrom or lateral):
  3577. inner = "(%s)" % (inner,)
  3578. return inner
  3579. else:
  3580. kwargs["enclosing_alias"] = alias
  3581. if asfrom or ashint:
  3582. if isinstance(alias.name, elements._truncated_label):
  3583. alias_name = self._truncated_identifier("alias", alias.name)
  3584. else:
  3585. alias_name = alias.name
  3586. if ashint:
  3587. return self.preparer.format_alias(alias, alias_name)
  3588. elif asfrom:
  3589. if from_linter:
  3590. from_linter.froms[alias._de_clone()] = alias_name
  3591. inner = alias.element._compiler_dispatch(
  3592. self, asfrom=True, lateral=lateral, **kwargs
  3593. )
  3594. if subquery:
  3595. inner = "(%s)" % (inner,)
  3596. ret = inner + self.get_render_as_alias_suffix(
  3597. self.preparer.format_alias(alias, alias_name)
  3598. )
  3599. if alias._supports_derived_columns and alias._render_derived:
  3600. ret += "(%s)" % (
  3601. ", ".join(
  3602. "%s%s"
  3603. % (
  3604. self.preparer.quote(col.name),
  3605. (
  3606. " %s"
  3607. % self.dialect.type_compiler_instance.process(
  3608. col.type, **kwargs
  3609. )
  3610. if alias._render_derived_w_types
  3611. else ""
  3612. ),
  3613. )
  3614. for col in alias.c
  3615. )
  3616. )
  3617. if fromhints and alias in fromhints:
  3618. ret = self.format_from_hint_text(
  3619. ret, alias, fromhints[alias], iscrud
  3620. )
  3621. return ret
  3622. else:
  3623. # note we cancel the "subquery" flag here as well
  3624. return alias.element._compiler_dispatch(
  3625. self, lateral=lateral, **kwargs
  3626. )
  3627. def visit_subquery(self, subquery, **kw):
  3628. kw["subquery"] = True
  3629. return self.visit_alias(subquery, **kw)
  3630. def visit_lateral(self, lateral_, **kw):
  3631. kw["lateral"] = True
  3632. return "LATERAL %s" % self.visit_alias(lateral_, **kw)
  3633. def visit_tablesample(self, tablesample, asfrom=False, **kw):
  3634. text = "%s TABLESAMPLE %s" % (
  3635. self.visit_alias(tablesample, asfrom=True, **kw),
  3636. tablesample._get_method()._compiler_dispatch(self, **kw),
  3637. )
  3638. if tablesample.seed is not None:
  3639. text += " REPEATABLE (%s)" % (
  3640. tablesample.seed._compiler_dispatch(self, **kw)
  3641. )
  3642. return text
  3643. def _render_values(self, element, **kw):
  3644. kw.setdefault("literal_binds", element.literal_binds)
  3645. tuples = ", ".join(
  3646. self.process(
  3647. elements.Tuple(
  3648. types=element._column_types, *elem
  3649. ).self_group(),
  3650. **kw,
  3651. )
  3652. for chunk in element._data
  3653. for elem in chunk
  3654. )
  3655. return f"VALUES {tuples}"
  3656. def visit_values(self, element, asfrom=False, from_linter=None, **kw):
  3657. v = self._render_values(element, **kw)
  3658. if element._unnamed:
  3659. name = None
  3660. elif isinstance(element.name, elements._truncated_label):
  3661. name = self._truncated_identifier("values", element.name)
  3662. else:
  3663. name = element.name
  3664. if element._is_lateral:
  3665. lateral = "LATERAL "
  3666. else:
  3667. lateral = ""
  3668. if asfrom:
  3669. if from_linter:
  3670. from_linter.froms[element._de_clone()] = (
  3671. name if name is not None else "(unnamed VALUES element)"
  3672. )
  3673. if name:
  3674. kw["include_table"] = False
  3675. v = "%s(%s)%s (%s)" % (
  3676. lateral,
  3677. v,
  3678. self.get_render_as_alias_suffix(self.preparer.quote(name)),
  3679. (
  3680. ", ".join(
  3681. c._compiler_dispatch(self, **kw)
  3682. for c in element.columns
  3683. )
  3684. ),
  3685. )
  3686. else:
  3687. v = "%s(%s)" % (lateral, v)
  3688. return v
  3689. def visit_scalar_values(self, element, **kw):
  3690. return f"({self._render_values(element, **kw)})"
  3691. def get_render_as_alias_suffix(self, alias_name_text):
  3692. return " AS " + alias_name_text
  3693. def _add_to_result_map(
  3694. self,
  3695. keyname: str,
  3696. name: str,
  3697. objects: Tuple[Any, ...],
  3698. type_: TypeEngine[Any],
  3699. ) -> None:
  3700. # note objects must be non-empty for cursor.py to handle the
  3701. # collection properly
  3702. assert objects
  3703. if keyname is None or keyname == "*":
  3704. self._ordered_columns = False
  3705. self._ad_hoc_textual = True
  3706. if type_._is_tuple_type:
  3707. raise exc.CompileError(
  3708. "Most backends don't support SELECTing "
  3709. "from a tuple() object. If this is an ORM query, "
  3710. "consider using the Bundle object."
  3711. )
  3712. self._result_columns.append(
  3713. ResultColumnsEntry(keyname, name, objects, type_)
  3714. )
  3715. def _label_returning_column(
  3716. self, stmt, column, populate_result_map, column_clause_args=None, **kw
  3717. ):
  3718. """Render a column with necessary labels inside of a RETURNING clause.
  3719. This method is provided for individual dialects in place of calling
  3720. the _label_select_column method directly, so that the two use cases
  3721. of RETURNING vs. SELECT can be disambiguated going forward.
  3722. .. versionadded:: 1.4.21
  3723. """
  3724. return self._label_select_column(
  3725. None,
  3726. column,
  3727. populate_result_map,
  3728. False,
  3729. {} if column_clause_args is None else column_clause_args,
  3730. **kw,
  3731. )
  3732. def _label_select_column(
  3733. self,
  3734. select,
  3735. column,
  3736. populate_result_map,
  3737. asfrom,
  3738. column_clause_args,
  3739. name=None,
  3740. proxy_name=None,
  3741. fallback_label_name=None,
  3742. within_columns_clause=True,
  3743. column_is_repeated=False,
  3744. need_column_expressions=False,
  3745. include_table=True,
  3746. ):
  3747. """produce labeled columns present in a select()."""
  3748. impl = column.type.dialect_impl(self.dialect)
  3749. if impl._has_column_expression and (
  3750. need_column_expressions or populate_result_map
  3751. ):
  3752. col_expr = impl.column_expression(column)
  3753. else:
  3754. col_expr = column
  3755. if populate_result_map:
  3756. # pass an "add_to_result_map" callable into the compilation
  3757. # of embedded columns. this collects information about the
  3758. # column as it will be fetched in the result and is coordinated
  3759. # with cursor.description when the query is executed.
  3760. add_to_result_map = self._add_to_result_map
  3761. # if the SELECT statement told us this column is a repeat,
  3762. # wrap the callable with one that prevents the addition of the
  3763. # targets
  3764. if column_is_repeated:
  3765. _add_to_result_map = add_to_result_map
  3766. def add_to_result_map(keyname, name, objects, type_):
  3767. _add_to_result_map(keyname, name, (keyname,), type_)
  3768. # if we redefined col_expr for type expressions, wrap the
  3769. # callable with one that adds the original column to the targets
  3770. elif col_expr is not column:
  3771. _add_to_result_map = add_to_result_map
  3772. def add_to_result_map(keyname, name, objects, type_):
  3773. _add_to_result_map(
  3774. keyname, name, (column,) + objects, type_
  3775. )
  3776. else:
  3777. add_to_result_map = None
  3778. # this method is used by some of the dialects for RETURNING,
  3779. # which has different inputs. _label_returning_column was added
  3780. # as the better target for this now however for 1.4 we will keep
  3781. # _label_select_column directly compatible with this use case.
  3782. # these assertions right now set up the current expected inputs
  3783. assert within_columns_clause, (
  3784. "_label_select_column is only relevant within "
  3785. "the columns clause of a SELECT or RETURNING"
  3786. )
  3787. if isinstance(column, elements.Label):
  3788. if col_expr is not column:
  3789. result_expr = _CompileLabel(
  3790. col_expr, column.name, alt_names=(column.element,)
  3791. )
  3792. else:
  3793. result_expr = col_expr
  3794. elif name:
  3795. # here, _columns_plus_names has determined there's an explicit
  3796. # label name we need to use. this is the default for
  3797. # tablenames_plus_columnnames as well as when columns are being
  3798. # deduplicated on name
  3799. assert (
  3800. proxy_name is not None
  3801. ), "proxy_name is required if 'name' is passed"
  3802. result_expr = _CompileLabel(
  3803. col_expr,
  3804. name,
  3805. alt_names=(
  3806. proxy_name,
  3807. # this is a hack to allow legacy result column lookups
  3808. # to work as they did before; this goes away in 2.0.
  3809. # TODO: this only seems to be tested indirectly
  3810. # via test/orm/test_deprecations.py. should be a
  3811. # resultset test for this
  3812. column._tq_label,
  3813. ),
  3814. )
  3815. else:
  3816. # determine here whether this column should be rendered in
  3817. # a labelled context or not, as we were given no required label
  3818. # name from the caller. Here we apply heuristics based on the kind
  3819. # of SQL expression involved.
  3820. if col_expr is not column:
  3821. # type-specific expression wrapping the given column,
  3822. # so we render a label
  3823. render_with_label = True
  3824. elif isinstance(column, elements.ColumnClause):
  3825. # table-bound column, we render its name as a label if we are
  3826. # inside of a subquery only
  3827. render_with_label = (
  3828. asfrom
  3829. and not column.is_literal
  3830. and column.table is not None
  3831. )
  3832. elif isinstance(column, elements.TextClause):
  3833. render_with_label = False
  3834. elif isinstance(column, elements.UnaryExpression):
  3835. render_with_label = column.wraps_column_expression or asfrom
  3836. elif (
  3837. # general class of expressions that don't have a SQL-column
  3838. # addressible name. includes scalar selects, bind parameters,
  3839. # SQL functions, others
  3840. not isinstance(column, elements.NamedColumn)
  3841. # deeper check that indicates there's no natural "name" to
  3842. # this element, which accommodates for custom SQL constructs
  3843. # that might have a ".name" attribute (but aren't SQL
  3844. # functions) but are not implementing this more recently added
  3845. # base class. in theory the "NamedColumn" check should be
  3846. # enough, however here we seek to maintain legacy behaviors
  3847. # as well.
  3848. and column._non_anon_label is None
  3849. ):
  3850. render_with_label = True
  3851. else:
  3852. render_with_label = False
  3853. if render_with_label:
  3854. if not fallback_label_name:
  3855. # used by the RETURNING case right now. we generate it
  3856. # here as 3rd party dialects may be referring to
  3857. # _label_select_column method directly instead of the
  3858. # just-added _label_returning_column method
  3859. assert not column_is_repeated
  3860. fallback_label_name = column._anon_name_label
  3861. fallback_label_name = (
  3862. elements._truncated_label(fallback_label_name)
  3863. if not isinstance(
  3864. fallback_label_name, elements._truncated_label
  3865. )
  3866. else fallback_label_name
  3867. )
  3868. result_expr = _CompileLabel(
  3869. col_expr, fallback_label_name, alt_names=(proxy_name,)
  3870. )
  3871. else:
  3872. result_expr = col_expr
  3873. column_clause_args.update(
  3874. within_columns_clause=within_columns_clause,
  3875. add_to_result_map=add_to_result_map,
  3876. include_table=include_table,
  3877. )
  3878. return result_expr._compiler_dispatch(self, **column_clause_args)
  3879. def format_from_hint_text(self, sqltext, table, hint, iscrud):
  3880. hinttext = self.get_from_hint_text(table, hint)
  3881. if hinttext:
  3882. sqltext += " " + hinttext
  3883. return sqltext
  3884. def get_select_hint_text(self, byfroms):
  3885. return None
  3886. def get_from_hint_text(
  3887. self, table: FromClause, text: Optional[str]
  3888. ) -> Optional[str]:
  3889. return None
  3890. def get_crud_hint_text(self, table, text):
  3891. return None
  3892. def get_statement_hint_text(self, hint_texts):
  3893. return " ".join(hint_texts)
  3894. _default_stack_entry: _CompilerStackEntry
  3895. if not typing.TYPE_CHECKING:
  3896. _default_stack_entry = util.immutabledict(
  3897. [("correlate_froms", frozenset()), ("asfrom_froms", frozenset())]
  3898. )
  3899. def _display_froms_for_select(
  3900. self, select_stmt, asfrom, lateral=False, **kw
  3901. ):
  3902. # utility method to help external dialects
  3903. # get the correct from list for a select.
  3904. # specifically the oracle dialect needs this feature
  3905. # right now.
  3906. toplevel = not self.stack
  3907. entry = self._default_stack_entry if toplevel else self.stack[-1]
  3908. compile_state = select_stmt._compile_state_factory(select_stmt, self)
  3909. correlate_froms = entry["correlate_froms"]
  3910. asfrom_froms = entry["asfrom_froms"]
  3911. if asfrom and not lateral:
  3912. froms = compile_state._get_display_froms(
  3913. explicit_correlate_froms=correlate_froms.difference(
  3914. asfrom_froms
  3915. ),
  3916. implicit_correlate_froms=(),
  3917. )
  3918. else:
  3919. froms = compile_state._get_display_froms(
  3920. explicit_correlate_froms=correlate_froms,
  3921. implicit_correlate_froms=asfrom_froms,
  3922. )
  3923. return froms
  3924. translate_select_structure: Any = None
  3925. """if not ``None``, should be a callable which accepts ``(select_stmt,
  3926. **kw)`` and returns a select object. this is used for structural changes
  3927. mostly to accommodate for LIMIT/OFFSET schemes
  3928. """
  3929. def visit_select(
  3930. self,
  3931. select_stmt,
  3932. asfrom=False,
  3933. insert_into=False,
  3934. fromhints=None,
  3935. compound_index=None,
  3936. select_wraps_for=None,
  3937. lateral=False,
  3938. from_linter=None,
  3939. **kwargs,
  3940. ):
  3941. assert select_wraps_for is None, (
  3942. "SQLAlchemy 1.4 requires use of "
  3943. "the translate_select_structure hook for structural "
  3944. "translations of SELECT objects"
  3945. )
  3946. # initial setup of SELECT. the compile_state_factory may now
  3947. # be creating a totally different SELECT from the one that was
  3948. # passed in. for ORM use this will convert from an ORM-state
  3949. # SELECT to a regular "Core" SELECT. other composed operations
  3950. # such as computation of joins will be performed.
  3951. kwargs["within_columns_clause"] = False
  3952. compile_state = select_stmt._compile_state_factory(
  3953. select_stmt, self, **kwargs
  3954. )
  3955. kwargs["ambiguous_table_name_map"] = (
  3956. compile_state._ambiguous_table_name_map
  3957. )
  3958. select_stmt = compile_state.statement
  3959. toplevel = not self.stack
  3960. if toplevel and not self.compile_state:
  3961. self.compile_state = compile_state
  3962. is_embedded_select = compound_index is not None or insert_into
  3963. # translate step for Oracle, SQL Server which often need to
  3964. # restructure the SELECT to allow for LIMIT/OFFSET and possibly
  3965. # other conditions
  3966. if self.translate_select_structure:
  3967. new_select_stmt = self.translate_select_structure(
  3968. select_stmt, asfrom=asfrom, **kwargs
  3969. )
  3970. # if SELECT was restructured, maintain a link to the originals
  3971. # and assemble a new compile state
  3972. if new_select_stmt is not select_stmt:
  3973. compile_state_wraps_for = compile_state
  3974. select_wraps_for = select_stmt
  3975. select_stmt = new_select_stmt
  3976. compile_state = select_stmt._compile_state_factory(
  3977. select_stmt, self, **kwargs
  3978. )
  3979. select_stmt = compile_state.statement
  3980. entry = self._default_stack_entry if toplevel else self.stack[-1]
  3981. populate_result_map = need_column_expressions = (
  3982. toplevel
  3983. or entry.get("need_result_map_for_compound", False)
  3984. or entry.get("need_result_map_for_nested", False)
  3985. )
  3986. # indicates there is a CompoundSelect in play and we are not the
  3987. # first select
  3988. if compound_index:
  3989. populate_result_map = False
  3990. # this was first proposed as part of #3372; however, it is not
  3991. # reached in current tests and could possibly be an assertion
  3992. # instead.
  3993. if not populate_result_map and "add_to_result_map" in kwargs:
  3994. del kwargs["add_to_result_map"]
  3995. froms = self._setup_select_stack(
  3996. select_stmt, compile_state, entry, asfrom, lateral, compound_index
  3997. )
  3998. column_clause_args = kwargs.copy()
  3999. column_clause_args.update(
  4000. {"within_label_clause": False, "within_columns_clause": False}
  4001. )
  4002. text = "SELECT " # we're off to a good start !
  4003. if select_stmt._hints:
  4004. hint_text, byfrom = self._setup_select_hints(select_stmt)
  4005. if hint_text:
  4006. text += hint_text + " "
  4007. else:
  4008. byfrom = None
  4009. if select_stmt._independent_ctes:
  4010. self._dispatch_independent_ctes(select_stmt, kwargs)
  4011. if select_stmt._prefixes:
  4012. text += self._generate_prefixes(
  4013. select_stmt, select_stmt._prefixes, **kwargs
  4014. )
  4015. text += self.get_select_precolumns(select_stmt, **kwargs)
  4016. # the actual list of columns to print in the SELECT column list.
  4017. inner_columns = [
  4018. c
  4019. for c in [
  4020. self._label_select_column(
  4021. select_stmt,
  4022. column,
  4023. populate_result_map,
  4024. asfrom,
  4025. column_clause_args,
  4026. name=name,
  4027. proxy_name=proxy_name,
  4028. fallback_label_name=fallback_label_name,
  4029. column_is_repeated=repeated,
  4030. need_column_expressions=need_column_expressions,
  4031. )
  4032. for (
  4033. name,
  4034. proxy_name,
  4035. fallback_label_name,
  4036. column,
  4037. repeated,
  4038. ) in compile_state.columns_plus_names
  4039. ]
  4040. if c is not None
  4041. ]
  4042. if populate_result_map and select_wraps_for is not None:
  4043. # if this select was generated from translate_select,
  4044. # rewrite the targeted columns in the result map
  4045. translate = dict(
  4046. zip(
  4047. [
  4048. name
  4049. for (
  4050. key,
  4051. proxy_name,
  4052. fallback_label_name,
  4053. name,
  4054. repeated,
  4055. ) in compile_state.columns_plus_names
  4056. ],
  4057. [
  4058. name
  4059. for (
  4060. key,
  4061. proxy_name,
  4062. fallback_label_name,
  4063. name,
  4064. repeated,
  4065. ) in compile_state_wraps_for.columns_plus_names
  4066. ],
  4067. )
  4068. )
  4069. self._result_columns = [
  4070. ResultColumnsEntry(
  4071. key, name, tuple(translate.get(o, o) for o in obj), type_
  4072. )
  4073. for key, name, obj, type_ in self._result_columns
  4074. ]
  4075. text = self._compose_select_body(
  4076. text,
  4077. select_stmt,
  4078. compile_state,
  4079. inner_columns,
  4080. froms,
  4081. byfrom,
  4082. toplevel,
  4083. kwargs,
  4084. )
  4085. if select_stmt._statement_hints:
  4086. per_dialect = [
  4087. ht
  4088. for (dialect_name, ht) in select_stmt._statement_hints
  4089. if dialect_name in ("*", self.dialect.name)
  4090. ]
  4091. if per_dialect:
  4092. text += " " + self.get_statement_hint_text(per_dialect)
  4093. # In compound query, CTEs are shared at the compound level
  4094. if self.ctes and (not is_embedded_select or toplevel):
  4095. nesting_level = len(self.stack) if not toplevel else None
  4096. text = self._render_cte_clause(nesting_level=nesting_level) + text
  4097. if select_stmt._suffixes:
  4098. text += " " + self._generate_prefixes(
  4099. select_stmt, select_stmt._suffixes, **kwargs
  4100. )
  4101. self.stack.pop(-1)
  4102. return text
  4103. def _setup_select_hints(
  4104. self, select: Select[Any]
  4105. ) -> Tuple[str, _FromHintsType]:
  4106. byfrom = {
  4107. from_: hinttext
  4108. % {"name": from_._compiler_dispatch(self, ashint=True)}
  4109. for (from_, dialect), hinttext in select._hints.items()
  4110. if dialect in ("*", self.dialect.name)
  4111. }
  4112. hint_text = self.get_select_hint_text(byfrom)
  4113. return hint_text, byfrom
  4114. def _setup_select_stack(
  4115. self, select, compile_state, entry, asfrom, lateral, compound_index
  4116. ):
  4117. correlate_froms = entry["correlate_froms"]
  4118. asfrom_froms = entry["asfrom_froms"]
  4119. if compound_index == 0:
  4120. entry["select_0"] = select
  4121. elif compound_index:
  4122. select_0 = entry["select_0"]
  4123. numcols = len(select_0._all_selected_columns)
  4124. if len(compile_state.columns_plus_names) != numcols:
  4125. raise exc.CompileError(
  4126. "All selectables passed to "
  4127. "CompoundSelect must have identical numbers of "
  4128. "columns; select #%d has %d columns, select "
  4129. "#%d has %d"
  4130. % (
  4131. 1,
  4132. numcols,
  4133. compound_index + 1,
  4134. len(select._all_selected_columns),
  4135. )
  4136. )
  4137. if asfrom and not lateral:
  4138. froms = compile_state._get_display_froms(
  4139. explicit_correlate_froms=correlate_froms.difference(
  4140. asfrom_froms
  4141. ),
  4142. implicit_correlate_froms=(),
  4143. )
  4144. else:
  4145. froms = compile_state._get_display_froms(
  4146. explicit_correlate_froms=correlate_froms,
  4147. implicit_correlate_froms=asfrom_froms,
  4148. )
  4149. new_correlate_froms = set(_from_objects(*froms))
  4150. all_correlate_froms = new_correlate_froms.union(correlate_froms)
  4151. new_entry: _CompilerStackEntry = {
  4152. "asfrom_froms": new_correlate_froms,
  4153. "correlate_froms": all_correlate_froms,
  4154. "selectable": select,
  4155. "compile_state": compile_state,
  4156. }
  4157. self.stack.append(new_entry)
  4158. return froms
  4159. def _compose_select_body(
  4160. self,
  4161. text,
  4162. select,
  4163. compile_state,
  4164. inner_columns,
  4165. froms,
  4166. byfrom,
  4167. toplevel,
  4168. kwargs,
  4169. ):
  4170. text += ", ".join(inner_columns)
  4171. if self.linting & COLLECT_CARTESIAN_PRODUCTS:
  4172. from_linter = FromLinter({}, set())
  4173. warn_linting = self.linting & WARN_LINTING
  4174. if toplevel:
  4175. self.from_linter = from_linter
  4176. else:
  4177. from_linter = None
  4178. warn_linting = False
  4179. # adjust the whitespace for no inner columns, part of #9440,
  4180. # so that a no-col SELECT comes out as "SELECT WHERE..." or
  4181. # "SELECT FROM ...".
  4182. # while it would be better to have built the SELECT starting string
  4183. # without trailing whitespace first, then add whitespace only if inner
  4184. # cols were present, this breaks compatibility with various custom
  4185. # compilation schemes that are currently being tested.
  4186. if not inner_columns:
  4187. text = text.rstrip()
  4188. if froms:
  4189. text += " \nFROM "
  4190. if select._hints:
  4191. text += ", ".join(
  4192. [
  4193. f._compiler_dispatch(
  4194. self,
  4195. asfrom=True,
  4196. fromhints=byfrom,
  4197. from_linter=from_linter,
  4198. **kwargs,
  4199. )
  4200. for f in froms
  4201. ]
  4202. )
  4203. else:
  4204. text += ", ".join(
  4205. [
  4206. f._compiler_dispatch(
  4207. self,
  4208. asfrom=True,
  4209. from_linter=from_linter,
  4210. **kwargs,
  4211. )
  4212. for f in froms
  4213. ]
  4214. )
  4215. else:
  4216. text += self.default_from()
  4217. if select._where_criteria:
  4218. t = self._generate_delimited_and_list(
  4219. select._where_criteria, from_linter=from_linter, **kwargs
  4220. )
  4221. if t:
  4222. text += " \nWHERE " + t
  4223. if warn_linting:
  4224. assert from_linter is not None
  4225. from_linter.warn()
  4226. if select._group_by_clauses:
  4227. text += self.group_by_clause(select, **kwargs)
  4228. if select._having_criteria:
  4229. t = self._generate_delimited_and_list(
  4230. select._having_criteria, **kwargs
  4231. )
  4232. if t:
  4233. text += " \nHAVING " + t
  4234. if select._order_by_clauses:
  4235. text += self.order_by_clause(select, **kwargs)
  4236. if select._has_row_limiting_clause:
  4237. text += self._row_limit_clause(select, **kwargs)
  4238. if select._for_update_arg is not None:
  4239. text += self.for_update_clause(select, **kwargs)
  4240. return text
  4241. def _generate_prefixes(self, stmt, prefixes, **kw):
  4242. clause = " ".join(
  4243. prefix._compiler_dispatch(self, **kw)
  4244. for prefix, dialect_name in prefixes
  4245. if dialect_name in (None, "*") or dialect_name == self.dialect.name
  4246. )
  4247. if clause:
  4248. clause += " "
  4249. return clause
  4250. def _render_cte_clause(
  4251. self,
  4252. nesting_level=None,
  4253. include_following_stack=False,
  4254. ):
  4255. """
  4256. include_following_stack
  4257. Also render the nesting CTEs on the next stack. Useful for
  4258. SQL structures like UNION or INSERT that can wrap SELECT
  4259. statements containing nesting CTEs.
  4260. """
  4261. if not self.ctes:
  4262. return ""
  4263. ctes: MutableMapping[CTE, str]
  4264. if nesting_level and nesting_level > 1:
  4265. ctes = util.OrderedDict()
  4266. for cte in list(self.ctes.keys()):
  4267. cte_level, cte_name, cte_opts = self.level_name_by_cte[
  4268. cte._get_reference_cte()
  4269. ]
  4270. nesting = cte.nesting or cte_opts.nesting
  4271. is_rendered_level = cte_level == nesting_level or (
  4272. include_following_stack and cte_level == nesting_level + 1
  4273. )
  4274. if not (nesting and is_rendered_level):
  4275. continue
  4276. ctes[cte] = self.ctes[cte]
  4277. else:
  4278. ctes = self.ctes
  4279. if not ctes:
  4280. return ""
  4281. ctes_recursive = any([cte.recursive for cte in ctes])
  4282. cte_text = self.get_cte_preamble(ctes_recursive) + " "
  4283. cte_text += ", \n".join([txt for txt in ctes.values()])
  4284. cte_text += "\n "
  4285. if nesting_level and nesting_level > 1:
  4286. for cte in list(ctes.keys()):
  4287. cte_level, cte_name, cte_opts = self.level_name_by_cte[
  4288. cte._get_reference_cte()
  4289. ]
  4290. del self.ctes[cte]
  4291. del self.ctes_by_level_name[(cte_level, cte_name)]
  4292. del self.level_name_by_cte[cte._get_reference_cte()]
  4293. return cte_text
  4294. def get_cte_preamble(self, recursive):
  4295. if recursive:
  4296. return "WITH RECURSIVE"
  4297. else:
  4298. return "WITH"
  4299. def get_select_precolumns(self, select: Select[Any], **kw: Any) -> str:
  4300. """Called when building a ``SELECT`` statement, position is just
  4301. before column list.
  4302. """
  4303. if select._distinct_on:
  4304. util.warn_deprecated(
  4305. "DISTINCT ON is currently supported only by the PostgreSQL "
  4306. "dialect. Use of DISTINCT ON for other backends is currently "
  4307. "silently ignored, however this usage is deprecated, and will "
  4308. "raise CompileError in a future release for all backends "
  4309. "that do not support this syntax.",
  4310. version="1.4",
  4311. )
  4312. return "DISTINCT " if select._distinct else ""
  4313. def group_by_clause(self, select, **kw):
  4314. """allow dialects to customize how GROUP BY is rendered."""
  4315. group_by = self._generate_delimited_list(
  4316. select._group_by_clauses, OPERATORS[operators.comma_op], **kw
  4317. )
  4318. if group_by:
  4319. return " GROUP BY " + group_by
  4320. else:
  4321. return ""
  4322. def order_by_clause(self, select, **kw):
  4323. """allow dialects to customize how ORDER BY is rendered."""
  4324. order_by = self._generate_delimited_list(
  4325. select._order_by_clauses, OPERATORS[operators.comma_op], **kw
  4326. )
  4327. if order_by:
  4328. return " ORDER BY " + order_by
  4329. else:
  4330. return ""
  4331. def for_update_clause(self, select, **kw):
  4332. return " FOR UPDATE"
  4333. def returning_clause(
  4334. self,
  4335. stmt: UpdateBase,
  4336. returning_cols: Sequence[_ColumnsClauseElement],
  4337. *,
  4338. populate_result_map: bool,
  4339. **kw: Any,
  4340. ) -> str:
  4341. columns = [
  4342. self._label_returning_column(
  4343. stmt,
  4344. column,
  4345. populate_result_map,
  4346. fallback_label_name=fallback_label_name,
  4347. column_is_repeated=repeated,
  4348. name=name,
  4349. proxy_name=proxy_name,
  4350. **kw,
  4351. )
  4352. for (
  4353. name,
  4354. proxy_name,
  4355. fallback_label_name,
  4356. column,
  4357. repeated,
  4358. ) in stmt._generate_columns_plus_names(
  4359. True, cols=base._select_iterables(returning_cols)
  4360. )
  4361. ]
  4362. return "RETURNING " + ", ".join(columns)
  4363. def limit_clause(self, select, **kw):
  4364. text = ""
  4365. if select._limit_clause is not None:
  4366. text += "\n LIMIT " + self.process(select._limit_clause, **kw)
  4367. if select._offset_clause is not None:
  4368. if select._limit_clause is None:
  4369. text += "\n LIMIT -1"
  4370. text += " OFFSET " + self.process(select._offset_clause, **kw)
  4371. return text
  4372. def fetch_clause(
  4373. self,
  4374. select,
  4375. fetch_clause=None,
  4376. require_offset=False,
  4377. use_literal_execute_for_simple_int=False,
  4378. **kw,
  4379. ):
  4380. if fetch_clause is None:
  4381. fetch_clause = select._fetch_clause
  4382. fetch_clause_options = select._fetch_clause_options
  4383. else:
  4384. fetch_clause_options = {"percent": False, "with_ties": False}
  4385. text = ""
  4386. if select._offset_clause is not None:
  4387. offset_clause = select._offset_clause
  4388. if (
  4389. use_literal_execute_for_simple_int
  4390. and select._simple_int_clause(offset_clause)
  4391. ):
  4392. offset_clause = offset_clause.render_literal_execute()
  4393. offset_str = self.process(offset_clause, **kw)
  4394. text += "\n OFFSET %s ROWS" % offset_str
  4395. elif require_offset:
  4396. text += "\n OFFSET 0 ROWS"
  4397. if fetch_clause is not None:
  4398. if (
  4399. use_literal_execute_for_simple_int
  4400. and select._simple_int_clause(fetch_clause)
  4401. ):
  4402. fetch_clause = fetch_clause.render_literal_execute()
  4403. text += "\n FETCH FIRST %s%s ROWS %s" % (
  4404. self.process(fetch_clause, **kw),
  4405. " PERCENT" if fetch_clause_options["percent"] else "",
  4406. "WITH TIES" if fetch_clause_options["with_ties"] else "ONLY",
  4407. )
  4408. return text
  4409. def visit_table(
  4410. self,
  4411. table,
  4412. asfrom=False,
  4413. iscrud=False,
  4414. ashint=False,
  4415. fromhints=None,
  4416. use_schema=True,
  4417. from_linter=None,
  4418. ambiguous_table_name_map=None,
  4419. enclosing_alias=None,
  4420. **kwargs,
  4421. ):
  4422. if from_linter:
  4423. from_linter.froms[table] = table.fullname
  4424. if asfrom or ashint:
  4425. effective_schema = self.preparer.schema_for_object(table)
  4426. if use_schema and effective_schema:
  4427. ret = (
  4428. self.preparer.quote_schema(effective_schema)
  4429. + "."
  4430. + self.preparer.quote(table.name)
  4431. )
  4432. else:
  4433. ret = self.preparer.quote(table.name)
  4434. if (
  4435. (
  4436. enclosing_alias is None
  4437. or enclosing_alias.element is not table
  4438. )
  4439. and not effective_schema
  4440. and ambiguous_table_name_map
  4441. and table.name in ambiguous_table_name_map
  4442. ):
  4443. anon_name = self._truncated_identifier(
  4444. "alias", ambiguous_table_name_map[table.name]
  4445. )
  4446. ret = ret + self.get_render_as_alias_suffix(
  4447. self.preparer.format_alias(None, anon_name)
  4448. )
  4449. if fromhints and table in fromhints:
  4450. ret = self.format_from_hint_text(
  4451. ret, table, fromhints[table], iscrud
  4452. )
  4453. return ret
  4454. else:
  4455. return ""
  4456. def visit_join(self, join, asfrom=False, from_linter=None, **kwargs):
  4457. if from_linter:
  4458. from_linter.edges.update(
  4459. itertools.product(
  4460. _de_clone(join.left._from_objects),
  4461. _de_clone(join.right._from_objects),
  4462. )
  4463. )
  4464. if join.full:
  4465. join_type = " FULL OUTER JOIN "
  4466. elif join.isouter:
  4467. join_type = " LEFT OUTER JOIN "
  4468. else:
  4469. join_type = " JOIN "
  4470. return (
  4471. join.left._compiler_dispatch(
  4472. self, asfrom=True, from_linter=from_linter, **kwargs
  4473. )
  4474. + join_type
  4475. + join.right._compiler_dispatch(
  4476. self, asfrom=True, from_linter=from_linter, **kwargs
  4477. )
  4478. + " ON "
  4479. # TODO: likely need asfrom=True here?
  4480. + join.onclause._compiler_dispatch(
  4481. self, from_linter=from_linter, **kwargs
  4482. )
  4483. )
  4484. def _setup_crud_hints(self, stmt, table_text):
  4485. dialect_hints = {
  4486. table: hint_text
  4487. for (table, dialect), hint_text in stmt._hints.items()
  4488. if dialect in ("*", self.dialect.name)
  4489. }
  4490. if stmt.table in dialect_hints:
  4491. table_text = self.format_from_hint_text(
  4492. table_text, stmt.table, dialect_hints[stmt.table], True
  4493. )
  4494. return dialect_hints, table_text
  4495. # within the realm of "insertmanyvalues sentinel columns",
  4496. # these lookups match different kinds of Column() configurations
  4497. # to specific backend capabilities. they are broken into two
  4498. # lookups, one for autoincrement columns and the other for non
  4499. # autoincrement columns
  4500. _sentinel_col_non_autoinc_lookup = util.immutabledict(
  4501. {
  4502. _SentinelDefaultCharacterization.CLIENTSIDE: (
  4503. InsertmanyvaluesSentinelOpts._SUPPORTED_OR_NOT
  4504. ),
  4505. _SentinelDefaultCharacterization.SENTINEL_DEFAULT: (
  4506. InsertmanyvaluesSentinelOpts._SUPPORTED_OR_NOT
  4507. ),
  4508. _SentinelDefaultCharacterization.NONE: (
  4509. InsertmanyvaluesSentinelOpts._SUPPORTED_OR_NOT
  4510. ),
  4511. _SentinelDefaultCharacterization.IDENTITY: (
  4512. InsertmanyvaluesSentinelOpts.IDENTITY
  4513. ),
  4514. _SentinelDefaultCharacterization.SEQUENCE: (
  4515. InsertmanyvaluesSentinelOpts.SEQUENCE
  4516. ),
  4517. }
  4518. )
  4519. _sentinel_col_autoinc_lookup = _sentinel_col_non_autoinc_lookup.union(
  4520. {
  4521. _SentinelDefaultCharacterization.NONE: (
  4522. InsertmanyvaluesSentinelOpts.AUTOINCREMENT
  4523. ),
  4524. }
  4525. )
  4526. def _get_sentinel_column_for_table(
  4527. self, table: Table
  4528. ) -> Optional[Sequence[Column[Any]]]:
  4529. """given a :class:`.Table`, return a usable sentinel column or
  4530. columns for this dialect if any.
  4531. Return None if no sentinel columns could be identified, or raise an
  4532. error if a column was marked as a sentinel explicitly but isn't
  4533. compatible with this dialect.
  4534. """
  4535. sentinel_opts = self.dialect.insertmanyvalues_implicit_sentinel
  4536. sentinel_characteristics = table._sentinel_column_characteristics
  4537. sent_cols = sentinel_characteristics.columns
  4538. if sent_cols is None:
  4539. return None
  4540. if sentinel_characteristics.is_autoinc:
  4541. bitmask = self._sentinel_col_autoinc_lookup.get(
  4542. sentinel_characteristics.default_characterization, 0
  4543. )
  4544. else:
  4545. bitmask = self._sentinel_col_non_autoinc_lookup.get(
  4546. sentinel_characteristics.default_characterization, 0
  4547. )
  4548. if sentinel_opts & bitmask:
  4549. return sent_cols
  4550. if sentinel_characteristics.is_explicit:
  4551. # a column was explicitly marked as insert_sentinel=True,
  4552. # however it is not compatible with this dialect. they should
  4553. # not indicate this column as a sentinel if they need to include
  4554. # this dialect.
  4555. # TODO: do we want non-primary key explicit sentinel cols
  4556. # that can gracefully degrade for some backends?
  4557. # insert_sentinel="degrade" perhaps. not for the initial release.
  4558. # I am hoping people are generally not dealing with this sentinel
  4559. # business at all.
  4560. # if is_explicit is True, there will be only one sentinel column.
  4561. raise exc.InvalidRequestError(
  4562. f"Column {sent_cols[0]} can't be explicitly "
  4563. "marked as a sentinel column when using the "
  4564. f"{self.dialect.name} dialect, as the "
  4565. "particular type of default generation on this column is "
  4566. "not currently compatible with this dialect's specific "
  4567. f"INSERT..RETURNING syntax which can receive the "
  4568. "server-generated value in "
  4569. "a deterministic way. To remove this error, remove "
  4570. "insert_sentinel=True from primary key autoincrement "
  4571. "columns; these columns are automatically used as "
  4572. "sentinels for supported dialects in any case."
  4573. )
  4574. return None
  4575. def _deliver_insertmanyvalues_batches(
  4576. self,
  4577. statement: str,
  4578. parameters: _DBAPIMultiExecuteParams,
  4579. compiled_parameters: List[_MutableCoreSingleExecuteParams],
  4580. generic_setinputsizes: Optional[_GenericSetInputSizesType],
  4581. batch_size: int,
  4582. sort_by_parameter_order: bool,
  4583. schema_translate_map: Optional[SchemaTranslateMapType],
  4584. ) -> Iterator[_InsertManyValuesBatch]:
  4585. imv = self._insertmanyvalues
  4586. assert imv is not None
  4587. if not imv.sentinel_param_keys:
  4588. _sentinel_from_params = None
  4589. else:
  4590. _sentinel_from_params = operator.itemgetter(
  4591. *imv.sentinel_param_keys
  4592. )
  4593. lenparams = len(parameters)
  4594. if imv.is_default_expr and not self.dialect.supports_default_metavalue:
  4595. # backend doesn't support
  4596. # INSERT INTO table (pk_col) VALUES (DEFAULT), (DEFAULT), ...
  4597. # at the moment this is basically SQL Server due to
  4598. # not being able to use DEFAULT for identity column
  4599. # just yield out that many single statements! still
  4600. # faster than a whole connection.execute() call ;)
  4601. #
  4602. # note we still are taking advantage of the fact that we know
  4603. # we are using RETURNING. The generalized approach of fetching
  4604. # cursor.lastrowid etc. still goes through the more heavyweight
  4605. # "ExecutionContext per statement" system as it isn't usable
  4606. # as a generic "RETURNING" approach
  4607. use_row_at_a_time = True
  4608. downgraded = False
  4609. elif not self.dialect.supports_multivalues_insert or (
  4610. sort_by_parameter_order
  4611. and self._result_columns
  4612. and (imv.sentinel_columns is None or imv.includes_upsert_behaviors)
  4613. ):
  4614. # deterministic order was requested and the compiler could
  4615. # not organize sentinel columns for this dialect/statement.
  4616. # use row at a time
  4617. use_row_at_a_time = True
  4618. downgraded = True
  4619. else:
  4620. use_row_at_a_time = False
  4621. downgraded = False
  4622. if use_row_at_a_time:
  4623. for batchnum, (param, compiled_param) in enumerate(
  4624. cast(
  4625. "Sequence[Tuple[_DBAPISingleExecuteParams, _MutableCoreSingleExecuteParams]]", # noqa: E501
  4626. zip(parameters, compiled_parameters),
  4627. ),
  4628. 1,
  4629. ):
  4630. yield _InsertManyValuesBatch(
  4631. statement,
  4632. param,
  4633. generic_setinputsizes,
  4634. [param],
  4635. (
  4636. [_sentinel_from_params(compiled_param)]
  4637. if _sentinel_from_params
  4638. else []
  4639. ),
  4640. 1,
  4641. batchnum,
  4642. lenparams,
  4643. sort_by_parameter_order,
  4644. downgraded,
  4645. )
  4646. return
  4647. if schema_translate_map:
  4648. rst = functools.partial(
  4649. self.preparer._render_schema_translates,
  4650. schema_translate_map=schema_translate_map,
  4651. )
  4652. else:
  4653. rst = None
  4654. imv_single_values_expr = imv.single_values_expr
  4655. if rst:
  4656. imv_single_values_expr = rst(imv_single_values_expr)
  4657. executemany_values = f"({imv_single_values_expr})"
  4658. statement = statement.replace(executemany_values, "__EXECMANY_TOKEN__")
  4659. # Use optional insertmanyvalues_max_parameters
  4660. # to further shrink the batch size so that there are no more than
  4661. # insertmanyvalues_max_parameters params.
  4662. # Currently used by SQL Server, which limits statements to 2100 bound
  4663. # parameters (actually 2099).
  4664. max_params = self.dialect.insertmanyvalues_max_parameters
  4665. if max_params:
  4666. total_num_of_params = len(self.bind_names)
  4667. num_params_per_batch = len(imv.insert_crud_params)
  4668. num_params_outside_of_batch = (
  4669. total_num_of_params - num_params_per_batch
  4670. )
  4671. batch_size = min(
  4672. batch_size,
  4673. (
  4674. (max_params - num_params_outside_of_batch)
  4675. // num_params_per_batch
  4676. ),
  4677. )
  4678. batches = cast("List[Sequence[Any]]", list(parameters))
  4679. compiled_batches = cast(
  4680. "List[Sequence[Any]]", list(compiled_parameters)
  4681. )
  4682. processed_setinputsizes: Optional[_GenericSetInputSizesType] = None
  4683. batchnum = 1
  4684. total_batches = lenparams // batch_size + (
  4685. 1 if lenparams % batch_size else 0
  4686. )
  4687. insert_crud_params = imv.insert_crud_params
  4688. assert insert_crud_params is not None
  4689. if rst:
  4690. insert_crud_params = [
  4691. (col, key, rst(expr), st)
  4692. for col, key, expr, st in insert_crud_params
  4693. ]
  4694. escaped_bind_names: Mapping[str, str]
  4695. expand_pos_lower_index = expand_pos_upper_index = 0
  4696. if not self.positional:
  4697. if self.escaped_bind_names:
  4698. escaped_bind_names = self.escaped_bind_names
  4699. else:
  4700. escaped_bind_names = {}
  4701. all_keys = set(parameters[0])
  4702. def apply_placeholders(keys, formatted):
  4703. for key in keys:
  4704. key = escaped_bind_names.get(key, key)
  4705. formatted = formatted.replace(
  4706. self.bindtemplate % {"name": key},
  4707. self.bindtemplate
  4708. % {"name": f"{key}__EXECMANY_INDEX__"},
  4709. )
  4710. return formatted
  4711. if imv.embed_values_counter:
  4712. imv_values_counter = ", _IMV_VALUES_COUNTER"
  4713. else:
  4714. imv_values_counter = ""
  4715. formatted_values_clause = f"""({', '.join(
  4716. apply_placeholders(bind_keys, formatted)
  4717. for _, _, formatted, bind_keys in insert_crud_params
  4718. )}{imv_values_counter})"""
  4719. keys_to_replace = all_keys.intersection(
  4720. escaped_bind_names.get(key, key)
  4721. for _, _, _, bind_keys in insert_crud_params
  4722. for key in bind_keys
  4723. )
  4724. base_parameters = {
  4725. key: parameters[0][key]
  4726. for key in all_keys.difference(keys_to_replace)
  4727. }
  4728. executemany_values_w_comma = ""
  4729. else:
  4730. formatted_values_clause = ""
  4731. keys_to_replace = set()
  4732. base_parameters = {}
  4733. if imv.embed_values_counter:
  4734. executemany_values_w_comma = (
  4735. f"({imv_single_values_expr}, _IMV_VALUES_COUNTER), "
  4736. )
  4737. else:
  4738. executemany_values_w_comma = f"({imv_single_values_expr}), "
  4739. all_names_we_will_expand: Set[str] = set()
  4740. for elem in imv.insert_crud_params:
  4741. all_names_we_will_expand.update(elem[3])
  4742. # get the start and end position in a particular list
  4743. # of parameters where we will be doing the "expanding".
  4744. # statements can have params on either side or both sides,
  4745. # given RETURNING and CTEs
  4746. if all_names_we_will_expand:
  4747. positiontup = self.positiontup
  4748. assert positiontup is not None
  4749. all_expand_positions = {
  4750. idx
  4751. for idx, name in enumerate(positiontup)
  4752. if name in all_names_we_will_expand
  4753. }
  4754. expand_pos_lower_index = min(all_expand_positions)
  4755. expand_pos_upper_index = max(all_expand_positions) + 1
  4756. assert (
  4757. len(all_expand_positions)
  4758. == expand_pos_upper_index - expand_pos_lower_index
  4759. )
  4760. if self._numeric_binds:
  4761. escaped = re.escape(self._numeric_binds_identifier_char)
  4762. executemany_values_w_comma = re.sub(
  4763. rf"{escaped}\d+", "%s", executemany_values_w_comma
  4764. )
  4765. while batches:
  4766. batch = batches[0:batch_size]
  4767. compiled_batch = compiled_batches[0:batch_size]
  4768. batches[0:batch_size] = []
  4769. compiled_batches[0:batch_size] = []
  4770. if batches:
  4771. current_batch_size = batch_size
  4772. else:
  4773. current_batch_size = len(batch)
  4774. if generic_setinputsizes:
  4775. # if setinputsizes is present, expand this collection to
  4776. # suit the batch length as well
  4777. # currently this will be mssql+pyodbc for internal dialects
  4778. processed_setinputsizes = [
  4779. (new_key, len_, typ)
  4780. for new_key, len_, typ in (
  4781. (f"{key}_{index}", len_, typ)
  4782. for index in range(current_batch_size)
  4783. for key, len_, typ in generic_setinputsizes
  4784. )
  4785. ]
  4786. replaced_parameters: Any
  4787. if self.positional:
  4788. num_ins_params = imv.num_positional_params_counted
  4789. batch_iterator: Iterable[Sequence[Any]]
  4790. extra_params_left: Sequence[Any]
  4791. extra_params_right: Sequence[Any]
  4792. if num_ins_params == len(batch[0]):
  4793. extra_params_left = extra_params_right = ()
  4794. batch_iterator = batch
  4795. else:
  4796. extra_params_left = batch[0][:expand_pos_lower_index]
  4797. extra_params_right = batch[0][expand_pos_upper_index:]
  4798. batch_iterator = (
  4799. b[expand_pos_lower_index:expand_pos_upper_index]
  4800. for b in batch
  4801. )
  4802. if imv.embed_values_counter:
  4803. expanded_values_string = (
  4804. "".join(
  4805. executemany_values_w_comma.replace(
  4806. "_IMV_VALUES_COUNTER", str(i)
  4807. )
  4808. for i, _ in enumerate(batch)
  4809. )
  4810. )[:-2]
  4811. else:
  4812. expanded_values_string = (
  4813. (executemany_values_w_comma * current_batch_size)
  4814. )[:-2]
  4815. if self._numeric_binds and num_ins_params > 0:
  4816. # numeric will always number the parameters inside of
  4817. # VALUES (and thus order self.positiontup) to be higher
  4818. # than non-VALUES parameters, no matter where in the
  4819. # statement those non-VALUES parameters appear (this is
  4820. # ensured in _process_numeric by numbering first all
  4821. # params that are not in _values_bindparam)
  4822. # therefore all extra params are always
  4823. # on the left side and numbered lower than the VALUES
  4824. # parameters
  4825. assert not extra_params_right
  4826. start = expand_pos_lower_index + 1
  4827. end = num_ins_params * (current_batch_size) + start
  4828. # need to format here, since statement may contain
  4829. # unescaped %, while values_string contains just (%s, %s)
  4830. positions = tuple(
  4831. f"{self._numeric_binds_identifier_char}{i}"
  4832. for i in range(start, end)
  4833. )
  4834. expanded_values_string = expanded_values_string % positions
  4835. replaced_statement = statement.replace(
  4836. "__EXECMANY_TOKEN__", expanded_values_string
  4837. )
  4838. replaced_parameters = tuple(
  4839. itertools.chain.from_iterable(batch_iterator)
  4840. )
  4841. replaced_parameters = (
  4842. extra_params_left
  4843. + replaced_parameters
  4844. + extra_params_right
  4845. )
  4846. else:
  4847. replaced_values_clauses = []
  4848. replaced_parameters = base_parameters.copy()
  4849. for i, param in enumerate(batch):
  4850. fmv = formatted_values_clause.replace(
  4851. "EXECMANY_INDEX__", str(i)
  4852. )
  4853. if imv.embed_values_counter:
  4854. fmv = fmv.replace("_IMV_VALUES_COUNTER", str(i))
  4855. replaced_values_clauses.append(fmv)
  4856. replaced_parameters.update(
  4857. {f"{key}__{i}": param[key] for key in keys_to_replace}
  4858. )
  4859. replaced_statement = statement.replace(
  4860. "__EXECMANY_TOKEN__",
  4861. ", ".join(replaced_values_clauses),
  4862. )
  4863. yield _InsertManyValuesBatch(
  4864. replaced_statement,
  4865. replaced_parameters,
  4866. processed_setinputsizes,
  4867. batch,
  4868. (
  4869. [_sentinel_from_params(cb) for cb in compiled_batch]
  4870. if _sentinel_from_params
  4871. else []
  4872. ),
  4873. current_batch_size,
  4874. batchnum,
  4875. total_batches,
  4876. sort_by_parameter_order,
  4877. False,
  4878. )
  4879. batchnum += 1
  4880. def visit_insert(
  4881. self, insert_stmt, visited_bindparam=None, visiting_cte=None, **kw
  4882. ):
  4883. compile_state = insert_stmt._compile_state_factory(
  4884. insert_stmt, self, **kw
  4885. )
  4886. insert_stmt = compile_state.statement
  4887. if visiting_cte is not None:
  4888. kw["visiting_cte"] = visiting_cte
  4889. toplevel = False
  4890. else:
  4891. toplevel = not self.stack
  4892. if toplevel:
  4893. self.isinsert = True
  4894. if not self.dml_compile_state:
  4895. self.dml_compile_state = compile_state
  4896. if not self.compile_state:
  4897. self.compile_state = compile_state
  4898. self.stack.append(
  4899. {
  4900. "correlate_froms": set(),
  4901. "asfrom_froms": set(),
  4902. "selectable": insert_stmt,
  4903. }
  4904. )
  4905. counted_bindparam = 0
  4906. # reset any incoming "visited_bindparam" collection
  4907. visited_bindparam = None
  4908. # for positional, insertmanyvalues needs to know how many
  4909. # bound parameters are in the VALUES sequence; there's no simple
  4910. # rule because default expressions etc. can have zero or more
  4911. # params inside them. After multiple attempts to figure this out,
  4912. # this very simplistic "count after" works and is
  4913. # likely the least amount of callcounts, though looks clumsy
  4914. if self.positional and visiting_cte is None:
  4915. # if we are inside a CTE, don't count parameters
  4916. # here since they wont be for insertmanyvalues. keep
  4917. # visited_bindparam at None so no counting happens.
  4918. # see #9173
  4919. visited_bindparam = []
  4920. crud_params_struct = crud._get_crud_params(
  4921. self,
  4922. insert_stmt,
  4923. compile_state,
  4924. toplevel,
  4925. visited_bindparam=visited_bindparam,
  4926. **kw,
  4927. )
  4928. if self.positional and visited_bindparam is not None:
  4929. counted_bindparam = len(visited_bindparam)
  4930. if self._numeric_binds:
  4931. if self._values_bindparam is not None:
  4932. self._values_bindparam += visited_bindparam
  4933. else:
  4934. self._values_bindparam = visited_bindparam
  4935. crud_params_single = crud_params_struct.single_params
  4936. if (
  4937. not crud_params_single
  4938. and not self.dialect.supports_default_values
  4939. and not self.dialect.supports_default_metavalue
  4940. and not self.dialect.supports_empty_insert
  4941. ):
  4942. raise exc.CompileError(
  4943. "The '%s' dialect with current database "
  4944. "version settings does not support empty "
  4945. "inserts." % self.dialect.name
  4946. )
  4947. if compile_state._has_multi_parameters:
  4948. if not self.dialect.supports_multivalues_insert:
  4949. raise exc.CompileError(
  4950. "The '%s' dialect with current database "
  4951. "version settings does not support "
  4952. "in-place multirow inserts." % self.dialect.name
  4953. )
  4954. elif (
  4955. self.implicit_returning or insert_stmt._returning
  4956. ) and insert_stmt._sort_by_parameter_order:
  4957. raise exc.CompileError(
  4958. "RETURNING cannot be determinstically sorted when "
  4959. "using an INSERT which includes multi-row values()."
  4960. )
  4961. crud_params_single = crud_params_struct.single_params
  4962. else:
  4963. crud_params_single = crud_params_struct.single_params
  4964. preparer = self.preparer
  4965. supports_default_values = self.dialect.supports_default_values
  4966. text = "INSERT "
  4967. if insert_stmt._prefixes:
  4968. text += self._generate_prefixes(
  4969. insert_stmt, insert_stmt._prefixes, **kw
  4970. )
  4971. text += "INTO "
  4972. table_text = preparer.format_table(insert_stmt.table)
  4973. if insert_stmt._hints:
  4974. _, table_text = self._setup_crud_hints(insert_stmt, table_text)
  4975. if insert_stmt._independent_ctes:
  4976. self._dispatch_independent_ctes(insert_stmt, kw)
  4977. text += table_text
  4978. if crud_params_single or not supports_default_values:
  4979. text += " (%s)" % ", ".join(
  4980. [expr for _, expr, _, _ in crud_params_single]
  4981. )
  4982. # look for insertmanyvalues attributes that would have been configured
  4983. # by crud.py as it scanned through the columns to be part of the
  4984. # INSERT
  4985. use_insertmanyvalues = crud_params_struct.use_insertmanyvalues
  4986. named_sentinel_params: Optional[Sequence[str]] = None
  4987. add_sentinel_cols = None
  4988. implicit_sentinel = False
  4989. returning_cols = self.implicit_returning or insert_stmt._returning
  4990. if returning_cols:
  4991. add_sentinel_cols = crud_params_struct.use_sentinel_columns
  4992. if add_sentinel_cols is not None:
  4993. assert use_insertmanyvalues
  4994. # search for the sentinel column explicitly present
  4995. # in the INSERT columns list, and additionally check that
  4996. # this column has a bound parameter name set up that's in the
  4997. # parameter list. If both of these cases are present, it means
  4998. # we will have a client side value for the sentinel in each
  4999. # parameter set.
  5000. _params_by_col = {
  5001. col: param_names
  5002. for col, _, _, param_names in crud_params_single
  5003. }
  5004. named_sentinel_params = []
  5005. for _add_sentinel_col in add_sentinel_cols:
  5006. if _add_sentinel_col not in _params_by_col:
  5007. named_sentinel_params = None
  5008. break
  5009. param_name = self._within_exec_param_key_getter(
  5010. _add_sentinel_col
  5011. )
  5012. if param_name not in _params_by_col[_add_sentinel_col]:
  5013. named_sentinel_params = None
  5014. break
  5015. named_sentinel_params.append(param_name)
  5016. if named_sentinel_params is None:
  5017. # if we are not going to have a client side value for
  5018. # the sentinel in the parameter set, that means it's
  5019. # an autoincrement, an IDENTITY, or a server-side SQL
  5020. # expression like nextval('seqname'). So this is
  5021. # an "implicit" sentinel; we will look for it in
  5022. # RETURNING
  5023. # only, and then sort on it. For this case on PG,
  5024. # SQL Server we have to use a special INSERT form
  5025. # that guarantees the server side function lines up with
  5026. # the entries in the VALUES.
  5027. if (
  5028. self.dialect.insertmanyvalues_implicit_sentinel
  5029. & InsertmanyvaluesSentinelOpts.ANY_AUTOINCREMENT
  5030. ):
  5031. implicit_sentinel = True
  5032. else:
  5033. # here, we are not using a sentinel at all
  5034. # and we are likely the SQLite dialect.
  5035. # The first add_sentinel_col that we have should not
  5036. # be marked as "insert_sentinel=True". if it was,
  5037. # an error should have been raised in
  5038. # _get_sentinel_column_for_table.
  5039. assert not add_sentinel_cols[0]._insert_sentinel, (
  5040. "sentinel selection rules should have prevented "
  5041. "us from getting here for this dialect"
  5042. )
  5043. # always put the sentinel columns last. even if they are
  5044. # in the returning list already, they will be there twice
  5045. # then.
  5046. returning_cols = list(returning_cols) + list(add_sentinel_cols)
  5047. returning_clause = self.returning_clause(
  5048. insert_stmt,
  5049. returning_cols,
  5050. populate_result_map=toplevel,
  5051. )
  5052. if self.returning_precedes_values:
  5053. text += " " + returning_clause
  5054. else:
  5055. returning_clause = None
  5056. if insert_stmt.select is not None:
  5057. # placed here by crud.py
  5058. select_text = self.process(
  5059. self.stack[-1]["insert_from_select"], insert_into=True, **kw
  5060. )
  5061. if self.ctes and self.dialect.cte_follows_insert:
  5062. nesting_level = len(self.stack) if not toplevel else None
  5063. text += " %s%s" % (
  5064. self._render_cte_clause(
  5065. nesting_level=nesting_level,
  5066. include_following_stack=True,
  5067. ),
  5068. select_text,
  5069. )
  5070. else:
  5071. text += " %s" % select_text
  5072. elif not crud_params_single and supports_default_values:
  5073. text += " DEFAULT VALUES"
  5074. if use_insertmanyvalues:
  5075. self._insertmanyvalues = _InsertManyValues(
  5076. True,
  5077. self.dialect.default_metavalue_token,
  5078. cast(
  5079. "List[crud._CrudParamElementStr]", crud_params_single
  5080. ),
  5081. counted_bindparam,
  5082. sort_by_parameter_order=(
  5083. insert_stmt._sort_by_parameter_order
  5084. ),
  5085. includes_upsert_behaviors=(
  5086. insert_stmt._post_values_clause is not None
  5087. ),
  5088. sentinel_columns=add_sentinel_cols,
  5089. num_sentinel_columns=(
  5090. len(add_sentinel_cols) if add_sentinel_cols else 0
  5091. ),
  5092. implicit_sentinel=implicit_sentinel,
  5093. )
  5094. elif compile_state._has_multi_parameters:
  5095. text += " VALUES %s" % (
  5096. ", ".join(
  5097. "(%s)"
  5098. % (", ".join(value for _, _, value, _ in crud_param_set))
  5099. for crud_param_set in crud_params_struct.all_multi_params
  5100. ),
  5101. )
  5102. else:
  5103. insert_single_values_expr = ", ".join(
  5104. [
  5105. value
  5106. for _, _, value, _ in cast(
  5107. "List[crud._CrudParamElementStr]",
  5108. crud_params_single,
  5109. )
  5110. ]
  5111. )
  5112. if use_insertmanyvalues:
  5113. if (
  5114. implicit_sentinel
  5115. and (
  5116. self.dialect.insertmanyvalues_implicit_sentinel
  5117. & InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT
  5118. )
  5119. # this is checking if we have
  5120. # INSERT INTO table (id) VALUES (DEFAULT).
  5121. and not (crud_params_struct.is_default_metavalue_only)
  5122. ):
  5123. # if we have a sentinel column that is server generated,
  5124. # then for selected backends render the VALUES list as a
  5125. # subquery. This is the orderable form supported by
  5126. # PostgreSQL and SQL Server.
  5127. embed_sentinel_value = True
  5128. render_bind_casts = (
  5129. self.dialect.insertmanyvalues_implicit_sentinel
  5130. & InsertmanyvaluesSentinelOpts.RENDER_SELECT_COL_CASTS
  5131. )
  5132. colnames = ", ".join(
  5133. f"p{i}" for i, _ in enumerate(crud_params_single)
  5134. )
  5135. if render_bind_casts:
  5136. # render casts for the SELECT list. For PG, we are
  5137. # already rendering bind casts in the parameter list,
  5138. # selectively for the more "tricky" types like ARRAY.
  5139. # however, even for the "easy" types, if the parameter
  5140. # is NULL for every entry, PG gives up and says
  5141. # "it must be TEXT", which fails for other easy types
  5142. # like ints. So we cast on this side too.
  5143. colnames_w_cast = ", ".join(
  5144. self.render_bind_cast(
  5145. col.type,
  5146. col.type._unwrapped_dialect_impl(self.dialect),
  5147. f"p{i}",
  5148. )
  5149. for i, (col, *_) in enumerate(crud_params_single)
  5150. )
  5151. else:
  5152. colnames_w_cast = colnames
  5153. text += (
  5154. f" SELECT {colnames_w_cast} FROM "
  5155. f"(VALUES ({insert_single_values_expr})) "
  5156. f"AS imp_sen({colnames}, sen_counter) "
  5157. "ORDER BY sen_counter"
  5158. )
  5159. else:
  5160. # otherwise, if no sentinel or backend doesn't support
  5161. # orderable subquery form, use a plain VALUES list
  5162. embed_sentinel_value = False
  5163. text += f" VALUES ({insert_single_values_expr})"
  5164. self._insertmanyvalues = _InsertManyValues(
  5165. is_default_expr=False,
  5166. single_values_expr=insert_single_values_expr,
  5167. insert_crud_params=cast(
  5168. "List[crud._CrudParamElementStr]",
  5169. crud_params_single,
  5170. ),
  5171. num_positional_params_counted=counted_bindparam,
  5172. sort_by_parameter_order=(
  5173. insert_stmt._sort_by_parameter_order
  5174. ),
  5175. includes_upsert_behaviors=(
  5176. insert_stmt._post_values_clause is not None
  5177. ),
  5178. sentinel_columns=add_sentinel_cols,
  5179. num_sentinel_columns=(
  5180. len(add_sentinel_cols) if add_sentinel_cols else 0
  5181. ),
  5182. sentinel_param_keys=named_sentinel_params,
  5183. implicit_sentinel=implicit_sentinel,
  5184. embed_values_counter=embed_sentinel_value,
  5185. )
  5186. else:
  5187. text += f" VALUES ({insert_single_values_expr})"
  5188. if insert_stmt._post_values_clause is not None:
  5189. post_values_clause = self.process(
  5190. insert_stmt._post_values_clause, **kw
  5191. )
  5192. if post_values_clause:
  5193. text += " " + post_values_clause
  5194. if returning_clause and not self.returning_precedes_values:
  5195. text += " " + returning_clause
  5196. if self.ctes and not self.dialect.cte_follows_insert:
  5197. nesting_level = len(self.stack) if not toplevel else None
  5198. text = (
  5199. self._render_cte_clause(
  5200. nesting_level=nesting_level,
  5201. include_following_stack=True,
  5202. )
  5203. + text
  5204. )
  5205. self.stack.pop(-1)
  5206. return text
  5207. def update_limit_clause(self, update_stmt):
  5208. """Provide a hook for MySQL to add LIMIT to the UPDATE"""
  5209. return None
  5210. def delete_limit_clause(self, delete_stmt):
  5211. """Provide a hook for MySQL to add LIMIT to the DELETE"""
  5212. return None
  5213. def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw):
  5214. """Provide a hook to override the initial table clause
  5215. in an UPDATE statement.
  5216. MySQL overrides this.
  5217. """
  5218. kw["asfrom"] = True
  5219. return from_table._compiler_dispatch(self, iscrud=True, **kw)
  5220. def update_from_clause(
  5221. self, update_stmt, from_table, extra_froms, from_hints, **kw
  5222. ):
  5223. """Provide a hook to override the generation of an
  5224. UPDATE..FROM clause.
  5225. MySQL and MSSQL override this.
  5226. """
  5227. raise NotImplementedError(
  5228. "This backend does not support multiple-table "
  5229. "criteria within UPDATE"
  5230. )
  5231. def visit_update(
  5232. self,
  5233. update_stmt: Update,
  5234. visiting_cte: Optional[CTE] = None,
  5235. **kw: Any,
  5236. ) -> str:
  5237. compile_state = update_stmt._compile_state_factory( # type: ignore[call-arg] # noqa: E501
  5238. update_stmt, self, **kw # type: ignore[arg-type]
  5239. )
  5240. if TYPE_CHECKING:
  5241. assert isinstance(compile_state, UpdateDMLState)
  5242. update_stmt = compile_state.statement # type: ignore[assignment]
  5243. if visiting_cte is not None:
  5244. kw["visiting_cte"] = visiting_cte
  5245. toplevel = False
  5246. else:
  5247. toplevel = not self.stack
  5248. if toplevel:
  5249. self.isupdate = True
  5250. if not self.dml_compile_state:
  5251. self.dml_compile_state = compile_state
  5252. if not self.compile_state:
  5253. self.compile_state = compile_state
  5254. if self.linting & COLLECT_CARTESIAN_PRODUCTS:
  5255. from_linter = FromLinter({}, set())
  5256. warn_linting = self.linting & WARN_LINTING
  5257. if toplevel:
  5258. self.from_linter = from_linter
  5259. else:
  5260. from_linter = None
  5261. warn_linting = False
  5262. extra_froms = compile_state._extra_froms
  5263. is_multitable = bool(extra_froms)
  5264. if is_multitable:
  5265. # main table might be a JOIN
  5266. main_froms = set(_from_objects(update_stmt.table))
  5267. render_extra_froms = [
  5268. f for f in extra_froms if f not in main_froms
  5269. ]
  5270. correlate_froms = main_froms.union(extra_froms)
  5271. else:
  5272. render_extra_froms = []
  5273. correlate_froms = {update_stmt.table}
  5274. self.stack.append(
  5275. {
  5276. "correlate_froms": correlate_froms,
  5277. "asfrom_froms": correlate_froms,
  5278. "selectable": update_stmt,
  5279. }
  5280. )
  5281. text = "UPDATE "
  5282. if update_stmt._prefixes:
  5283. text += self._generate_prefixes(
  5284. update_stmt, update_stmt._prefixes, **kw
  5285. )
  5286. table_text = self.update_tables_clause(
  5287. update_stmt,
  5288. update_stmt.table,
  5289. render_extra_froms,
  5290. from_linter=from_linter,
  5291. **kw,
  5292. )
  5293. crud_params_struct = crud._get_crud_params(
  5294. self, update_stmt, compile_state, toplevel, **kw
  5295. )
  5296. crud_params = crud_params_struct.single_params
  5297. if update_stmt._hints:
  5298. dialect_hints, table_text = self._setup_crud_hints(
  5299. update_stmt, table_text
  5300. )
  5301. else:
  5302. dialect_hints = None
  5303. if update_stmt._independent_ctes:
  5304. self._dispatch_independent_ctes(update_stmt, kw)
  5305. text += table_text
  5306. text += " SET "
  5307. text += ", ".join(
  5308. expr + "=" + value
  5309. for _, expr, value, _ in cast(
  5310. "List[Tuple[Any, str, str, Any]]", crud_params
  5311. )
  5312. )
  5313. if self.implicit_returning or update_stmt._returning:
  5314. if self.returning_precedes_values:
  5315. text += " " + self.returning_clause(
  5316. update_stmt,
  5317. self.implicit_returning or update_stmt._returning,
  5318. populate_result_map=toplevel,
  5319. )
  5320. if extra_froms:
  5321. extra_from_text = self.update_from_clause(
  5322. update_stmt,
  5323. update_stmt.table,
  5324. render_extra_froms,
  5325. dialect_hints,
  5326. from_linter=from_linter,
  5327. **kw,
  5328. )
  5329. if extra_from_text:
  5330. text += " " + extra_from_text
  5331. if update_stmt._where_criteria:
  5332. t = self._generate_delimited_and_list(
  5333. update_stmt._where_criteria, from_linter=from_linter, **kw
  5334. )
  5335. if t:
  5336. text += " WHERE " + t
  5337. limit_clause = self.update_limit_clause(update_stmt)
  5338. if limit_clause:
  5339. text += " " + limit_clause
  5340. if (
  5341. self.implicit_returning or update_stmt._returning
  5342. ) and not self.returning_precedes_values:
  5343. text += " " + self.returning_clause(
  5344. update_stmt,
  5345. self.implicit_returning or update_stmt._returning,
  5346. populate_result_map=toplevel,
  5347. )
  5348. if self.ctes:
  5349. nesting_level = len(self.stack) if not toplevel else None
  5350. text = self._render_cte_clause(nesting_level=nesting_level) + text
  5351. if warn_linting:
  5352. assert from_linter is not None
  5353. from_linter.warn(stmt_type="UPDATE")
  5354. self.stack.pop(-1)
  5355. return text
  5356. def delete_extra_from_clause(
  5357. self, delete_stmt, from_table, extra_froms, from_hints, **kw
  5358. ):
  5359. """Provide a hook to override the generation of an
  5360. DELETE..FROM clause.
  5361. This can be used to implement DELETE..USING for example.
  5362. MySQL and MSSQL override this.
  5363. """
  5364. raise NotImplementedError(
  5365. "This backend does not support multiple-table "
  5366. "criteria within DELETE"
  5367. )
  5368. def delete_table_clause(self, delete_stmt, from_table, extra_froms, **kw):
  5369. return from_table._compiler_dispatch(
  5370. self, asfrom=True, iscrud=True, **kw
  5371. )
  5372. def visit_delete(self, delete_stmt, visiting_cte=None, **kw):
  5373. compile_state = delete_stmt._compile_state_factory(
  5374. delete_stmt, self, **kw
  5375. )
  5376. delete_stmt = compile_state.statement
  5377. if visiting_cte is not None:
  5378. kw["visiting_cte"] = visiting_cte
  5379. toplevel = False
  5380. else:
  5381. toplevel = not self.stack
  5382. if toplevel:
  5383. self.isdelete = True
  5384. if not self.dml_compile_state:
  5385. self.dml_compile_state = compile_state
  5386. if not self.compile_state:
  5387. self.compile_state = compile_state
  5388. if self.linting & COLLECT_CARTESIAN_PRODUCTS:
  5389. from_linter = FromLinter({}, set())
  5390. warn_linting = self.linting & WARN_LINTING
  5391. if toplevel:
  5392. self.from_linter = from_linter
  5393. else:
  5394. from_linter = None
  5395. warn_linting = False
  5396. extra_froms = compile_state._extra_froms
  5397. correlate_froms = {delete_stmt.table}.union(extra_froms)
  5398. self.stack.append(
  5399. {
  5400. "correlate_froms": correlate_froms,
  5401. "asfrom_froms": correlate_froms,
  5402. "selectable": delete_stmt,
  5403. }
  5404. )
  5405. text = "DELETE "
  5406. if delete_stmt._prefixes:
  5407. text += self._generate_prefixes(
  5408. delete_stmt, delete_stmt._prefixes, **kw
  5409. )
  5410. text += "FROM "
  5411. try:
  5412. table_text = self.delete_table_clause(
  5413. delete_stmt,
  5414. delete_stmt.table,
  5415. extra_froms,
  5416. from_linter=from_linter,
  5417. )
  5418. except TypeError:
  5419. # anticipate 3rd party dialects that don't include **kw
  5420. # TODO: remove in 2.1
  5421. table_text = self.delete_table_clause(
  5422. delete_stmt, delete_stmt.table, extra_froms
  5423. )
  5424. if from_linter:
  5425. _ = self.process(delete_stmt.table, from_linter=from_linter)
  5426. crud._get_crud_params(self, delete_stmt, compile_state, toplevel, **kw)
  5427. if delete_stmt._hints:
  5428. dialect_hints, table_text = self._setup_crud_hints(
  5429. delete_stmt, table_text
  5430. )
  5431. else:
  5432. dialect_hints = None
  5433. if delete_stmt._independent_ctes:
  5434. self._dispatch_independent_ctes(delete_stmt, kw)
  5435. text += table_text
  5436. if (
  5437. self.implicit_returning or delete_stmt._returning
  5438. ) and self.returning_precedes_values:
  5439. text += " " + self.returning_clause(
  5440. delete_stmt,
  5441. self.implicit_returning or delete_stmt._returning,
  5442. populate_result_map=toplevel,
  5443. )
  5444. if extra_froms:
  5445. extra_from_text = self.delete_extra_from_clause(
  5446. delete_stmt,
  5447. delete_stmt.table,
  5448. extra_froms,
  5449. dialect_hints,
  5450. from_linter=from_linter,
  5451. **kw,
  5452. )
  5453. if extra_from_text:
  5454. text += " " + extra_from_text
  5455. if delete_stmt._where_criteria:
  5456. t = self._generate_delimited_and_list(
  5457. delete_stmt._where_criteria, from_linter=from_linter, **kw
  5458. )
  5459. if t:
  5460. text += " WHERE " + t
  5461. limit_clause = self.delete_limit_clause(delete_stmt)
  5462. if limit_clause:
  5463. text += " " + limit_clause
  5464. if (
  5465. self.implicit_returning or delete_stmt._returning
  5466. ) and not self.returning_precedes_values:
  5467. text += " " + self.returning_clause(
  5468. delete_stmt,
  5469. self.implicit_returning or delete_stmt._returning,
  5470. populate_result_map=toplevel,
  5471. )
  5472. if self.ctes:
  5473. nesting_level = len(self.stack) if not toplevel else None
  5474. text = self._render_cte_clause(nesting_level=nesting_level) + text
  5475. if warn_linting:
  5476. assert from_linter is not None
  5477. from_linter.warn(stmt_type="DELETE")
  5478. self.stack.pop(-1)
  5479. return text
  5480. def visit_savepoint(self, savepoint_stmt, **kw):
  5481. return "SAVEPOINT %s" % self.preparer.format_savepoint(savepoint_stmt)
  5482. def visit_rollback_to_savepoint(self, savepoint_stmt, **kw):
  5483. return "ROLLBACK TO SAVEPOINT %s" % self.preparer.format_savepoint(
  5484. savepoint_stmt
  5485. )
  5486. def visit_release_savepoint(self, savepoint_stmt, **kw):
  5487. return "RELEASE SAVEPOINT %s" % self.preparer.format_savepoint(
  5488. savepoint_stmt
  5489. )
  5490. class StrSQLCompiler(SQLCompiler):
  5491. """A :class:`.SQLCompiler` subclass which allows a small selection
  5492. of non-standard SQL features to render into a string value.
  5493. The :class:`.StrSQLCompiler` is invoked whenever a Core expression
  5494. element is directly stringified without calling upon the
  5495. :meth:`_expression.ClauseElement.compile` method.
  5496. It can render a limited set
  5497. of non-standard SQL constructs to assist in basic stringification,
  5498. however for more substantial custom or dialect-specific SQL constructs,
  5499. it will be necessary to make use of
  5500. :meth:`_expression.ClauseElement.compile`
  5501. directly.
  5502. .. seealso::
  5503. :ref:`faq_sql_expression_string`
  5504. """
  5505. def _fallback_column_name(self, column):
  5506. return "<name unknown>"
  5507. @util.preload_module("sqlalchemy.engine.url")
  5508. def visit_unsupported_compilation(self, element, err, **kw):
  5509. if element.stringify_dialect != "default":
  5510. url = util.preloaded.engine_url
  5511. dialect = url.URL.create(element.stringify_dialect).get_dialect()()
  5512. compiler = dialect.statement_compiler(
  5513. dialect, None, _supporting_against=self
  5514. )
  5515. if not isinstance(compiler, StrSQLCompiler):
  5516. return compiler.process(element, **kw)
  5517. return super().visit_unsupported_compilation(element, err)
  5518. def visit_getitem_binary(self, binary, operator, **kw):
  5519. return "%s[%s]" % (
  5520. self.process(binary.left, **kw),
  5521. self.process(binary.right, **kw),
  5522. )
  5523. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  5524. return self.visit_getitem_binary(binary, operator, **kw)
  5525. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  5526. return self.visit_getitem_binary(binary, operator, **kw)
  5527. def visit_sequence(self, sequence, **kw):
  5528. return (
  5529. f"<next sequence value: {self.preparer.format_sequence(sequence)}>"
  5530. )
  5531. def returning_clause(
  5532. self,
  5533. stmt: UpdateBase,
  5534. returning_cols: Sequence[_ColumnsClauseElement],
  5535. *,
  5536. populate_result_map: bool,
  5537. **kw: Any,
  5538. ) -> str:
  5539. columns = [
  5540. self._label_select_column(None, c, True, False, {})
  5541. for c in base._select_iterables(returning_cols)
  5542. ]
  5543. return "RETURNING " + ", ".join(columns)
  5544. def update_from_clause(
  5545. self, update_stmt, from_table, extra_froms, from_hints, **kw
  5546. ):
  5547. kw["asfrom"] = True
  5548. return "FROM " + ", ".join(
  5549. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  5550. for t in extra_froms
  5551. )
  5552. def delete_extra_from_clause(
  5553. self, delete_stmt, from_table, extra_froms, from_hints, **kw
  5554. ):
  5555. kw["asfrom"] = True
  5556. return ", " + ", ".join(
  5557. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  5558. for t in extra_froms
  5559. )
  5560. def visit_empty_set_expr(self, element_types, **kw):
  5561. return "SELECT 1 WHERE 1!=1"
  5562. def get_from_hint_text(self, table, text):
  5563. return "[%s]" % text
  5564. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  5565. return self._generate_generic_binary(binary, " <regexp> ", **kw)
  5566. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  5567. return self._generate_generic_binary(binary, " <not regexp> ", **kw)
  5568. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  5569. return "<regexp replace>(%s, %s)" % (
  5570. binary.left._compiler_dispatch(self, **kw),
  5571. binary.right._compiler_dispatch(self, **kw),
  5572. )
  5573. def visit_try_cast(self, cast, **kwargs):
  5574. return "TRY_CAST(%s AS %s)" % (
  5575. cast.clause._compiler_dispatch(self, **kwargs),
  5576. cast.typeclause._compiler_dispatch(self, **kwargs),
  5577. )
  5578. class DDLCompiler(Compiled):
  5579. is_ddl = True
  5580. if TYPE_CHECKING:
  5581. def __init__(
  5582. self,
  5583. dialect: Dialect,
  5584. statement: ExecutableDDLElement,
  5585. schema_translate_map: Optional[SchemaTranslateMapType] = ...,
  5586. render_schema_translate: bool = ...,
  5587. compile_kwargs: Mapping[str, Any] = ...,
  5588. ): ...
  5589. @util.ro_memoized_property
  5590. def sql_compiler(self) -> SQLCompiler:
  5591. return self.dialect.statement_compiler(
  5592. self.dialect, None, schema_translate_map=self.schema_translate_map
  5593. )
  5594. @util.memoized_property
  5595. def type_compiler(self):
  5596. return self.dialect.type_compiler_instance
  5597. def construct_params(
  5598. self,
  5599. params: Optional[_CoreSingleExecuteParams] = None,
  5600. extracted_parameters: Optional[Sequence[BindParameter[Any]]] = None,
  5601. escape_names: bool = True,
  5602. ) -> Optional[_MutableCoreSingleExecuteParams]:
  5603. return None
  5604. def visit_ddl(self, ddl, **kwargs):
  5605. # table events can substitute table and schema name
  5606. context = ddl.context
  5607. if isinstance(ddl.target, schema.Table):
  5608. context = context.copy()
  5609. preparer = self.preparer
  5610. path = preparer.format_table_seq(ddl.target)
  5611. if len(path) == 1:
  5612. table, sch = path[0], ""
  5613. else:
  5614. table, sch = path[-1], path[0]
  5615. context.setdefault("table", table)
  5616. context.setdefault("schema", sch)
  5617. context.setdefault("fullname", preparer.format_table(ddl.target))
  5618. return self.sql_compiler.post_process_text(ddl.statement % context)
  5619. def visit_create_schema(self, create, **kw):
  5620. text = "CREATE SCHEMA "
  5621. if create.if_not_exists:
  5622. text += "IF NOT EXISTS "
  5623. return text + self.preparer.format_schema(create.element)
  5624. def visit_drop_schema(self, drop, **kw):
  5625. text = "DROP SCHEMA "
  5626. if drop.if_exists:
  5627. text += "IF EXISTS "
  5628. text += self.preparer.format_schema(drop.element)
  5629. if drop.cascade:
  5630. text += " CASCADE"
  5631. return text
  5632. def visit_create_table(self, create, **kw):
  5633. table = create.element
  5634. preparer = self.preparer
  5635. text = "\nCREATE "
  5636. if table._prefixes:
  5637. text += " ".join(table._prefixes) + " "
  5638. text += "TABLE "
  5639. if create.if_not_exists:
  5640. text += "IF NOT EXISTS "
  5641. text += preparer.format_table(table) + " "
  5642. create_table_suffix = self.create_table_suffix(table)
  5643. if create_table_suffix:
  5644. text += create_table_suffix + " "
  5645. text += "("
  5646. separator = "\n"
  5647. # if only one primary key, specify it along with the column
  5648. first_pk = False
  5649. for create_column in create.columns:
  5650. column = create_column.element
  5651. try:
  5652. processed = self.process(
  5653. create_column, first_pk=column.primary_key and not first_pk
  5654. )
  5655. if processed is not None:
  5656. text += separator
  5657. separator = ", \n"
  5658. text += "\t" + processed
  5659. if column.primary_key:
  5660. first_pk = True
  5661. except exc.CompileError as ce:
  5662. raise exc.CompileError(
  5663. "(in table '%s', column '%s'): %s"
  5664. % (table.description, column.name, ce.args[0])
  5665. ) from ce
  5666. const = self.create_table_constraints(
  5667. table,
  5668. _include_foreign_key_constraints=create.include_foreign_key_constraints, # noqa
  5669. )
  5670. if const:
  5671. text += separator + "\t" + const
  5672. text += "\n)%s\n\n" % self.post_create_table(table)
  5673. return text
  5674. def visit_create_column(self, create, first_pk=False, **kw):
  5675. column = create.element
  5676. if column.system:
  5677. return None
  5678. text = self.get_column_specification(column, first_pk=first_pk)
  5679. const = " ".join(
  5680. self.process(constraint) for constraint in column.constraints
  5681. )
  5682. if const:
  5683. text += " " + const
  5684. return text
  5685. def create_table_constraints(
  5686. self, table, _include_foreign_key_constraints=None, **kw
  5687. ):
  5688. # On some DB order is significant: visit PK first, then the
  5689. # other constraints (engine.ReflectionTest.testbasic failed on FB2)
  5690. constraints = []
  5691. if table.primary_key:
  5692. constraints.append(table.primary_key)
  5693. all_fkcs = table.foreign_key_constraints
  5694. if _include_foreign_key_constraints is not None:
  5695. omit_fkcs = all_fkcs.difference(_include_foreign_key_constraints)
  5696. else:
  5697. omit_fkcs = set()
  5698. constraints.extend(
  5699. [
  5700. c
  5701. for c in table._sorted_constraints
  5702. if c is not table.primary_key and c not in omit_fkcs
  5703. ]
  5704. )
  5705. return ", \n\t".join(
  5706. p
  5707. for p in (
  5708. self.process(constraint)
  5709. for constraint in constraints
  5710. if (constraint._should_create_for_compiler(self))
  5711. and (
  5712. not self.dialect.supports_alter
  5713. or not getattr(constraint, "use_alter", False)
  5714. )
  5715. )
  5716. if p is not None
  5717. )
  5718. def visit_drop_table(self, drop, **kw):
  5719. text = "\nDROP TABLE "
  5720. if drop.if_exists:
  5721. text += "IF EXISTS "
  5722. return text + self.preparer.format_table(drop.element)
  5723. def visit_drop_view(self, drop, **kw):
  5724. return "\nDROP VIEW " + self.preparer.format_table(drop.element)
  5725. def _verify_index_table(self, index: Index) -> None:
  5726. if index.table is None:
  5727. raise exc.CompileError(
  5728. "Index '%s' is not associated with any table." % index.name
  5729. )
  5730. def visit_create_index(
  5731. self, create, include_schema=False, include_table_schema=True, **kw
  5732. ):
  5733. index = create.element
  5734. self._verify_index_table(index)
  5735. preparer = self.preparer
  5736. text = "CREATE "
  5737. if index.unique:
  5738. text += "UNIQUE "
  5739. if index.name is None:
  5740. raise exc.CompileError(
  5741. "CREATE INDEX requires that the index have a name"
  5742. )
  5743. text += "INDEX "
  5744. if create.if_not_exists:
  5745. text += "IF NOT EXISTS "
  5746. text += "%s ON %s (%s)" % (
  5747. self._prepared_index_name(index, include_schema=include_schema),
  5748. preparer.format_table(
  5749. index.table, use_schema=include_table_schema
  5750. ),
  5751. ", ".join(
  5752. self.sql_compiler.process(
  5753. expr, include_table=False, literal_binds=True
  5754. )
  5755. for expr in index.expressions
  5756. ),
  5757. )
  5758. return text
  5759. def visit_drop_index(self, drop, **kw):
  5760. index = drop.element
  5761. if index.name is None:
  5762. raise exc.CompileError(
  5763. "DROP INDEX requires that the index have a name"
  5764. )
  5765. text = "\nDROP INDEX "
  5766. if drop.if_exists:
  5767. text += "IF EXISTS "
  5768. return text + self._prepared_index_name(index, include_schema=True)
  5769. def _prepared_index_name(
  5770. self, index: Index, include_schema: bool = False
  5771. ) -> str:
  5772. if index.table is not None:
  5773. effective_schema = self.preparer.schema_for_object(index.table)
  5774. else:
  5775. effective_schema = None
  5776. if include_schema and effective_schema:
  5777. schema_name = self.preparer.quote_schema(effective_schema)
  5778. else:
  5779. schema_name = None
  5780. index_name = self.preparer.format_index(index)
  5781. if schema_name:
  5782. index_name = schema_name + "." + index_name
  5783. return index_name
  5784. def visit_add_constraint(self, create, **kw):
  5785. return "ALTER TABLE %s ADD %s" % (
  5786. self.preparer.format_table(create.element.table),
  5787. self.process(create.element),
  5788. )
  5789. def visit_set_table_comment(self, create, **kw):
  5790. return "COMMENT ON TABLE %s IS %s" % (
  5791. self.preparer.format_table(create.element),
  5792. self.sql_compiler.render_literal_value(
  5793. create.element.comment, sqltypes.String()
  5794. ),
  5795. )
  5796. def visit_drop_table_comment(self, drop, **kw):
  5797. return "COMMENT ON TABLE %s IS NULL" % self.preparer.format_table(
  5798. drop.element
  5799. )
  5800. def visit_set_column_comment(self, create, **kw):
  5801. return "COMMENT ON COLUMN %s IS %s" % (
  5802. self.preparer.format_column(
  5803. create.element, use_table=True, use_schema=True
  5804. ),
  5805. self.sql_compiler.render_literal_value(
  5806. create.element.comment, sqltypes.String()
  5807. ),
  5808. )
  5809. def visit_drop_column_comment(self, drop, **kw):
  5810. return "COMMENT ON COLUMN %s IS NULL" % self.preparer.format_column(
  5811. drop.element, use_table=True
  5812. )
  5813. def visit_set_constraint_comment(self, create, **kw):
  5814. raise exc.UnsupportedCompilationError(self, type(create))
  5815. def visit_drop_constraint_comment(self, drop, **kw):
  5816. raise exc.UnsupportedCompilationError(self, type(drop))
  5817. def get_identity_options(self, identity_options):
  5818. text = []
  5819. if identity_options.increment is not None:
  5820. text.append("INCREMENT BY %d" % identity_options.increment)
  5821. if identity_options.start is not None:
  5822. text.append("START WITH %d" % identity_options.start)
  5823. if identity_options.minvalue is not None:
  5824. text.append("MINVALUE %d" % identity_options.minvalue)
  5825. if identity_options.maxvalue is not None:
  5826. text.append("MAXVALUE %d" % identity_options.maxvalue)
  5827. if identity_options.nominvalue is not None:
  5828. text.append("NO MINVALUE")
  5829. if identity_options.nomaxvalue is not None:
  5830. text.append("NO MAXVALUE")
  5831. if identity_options.cache is not None:
  5832. text.append("CACHE %d" % identity_options.cache)
  5833. if identity_options.cycle is not None:
  5834. text.append("CYCLE" if identity_options.cycle else "NO CYCLE")
  5835. return " ".join(text)
  5836. def visit_create_sequence(self, create, prefix=None, **kw):
  5837. text = "CREATE SEQUENCE "
  5838. if create.if_not_exists:
  5839. text += "IF NOT EXISTS "
  5840. text += self.preparer.format_sequence(create.element)
  5841. if prefix:
  5842. text += prefix
  5843. options = self.get_identity_options(create.element)
  5844. if options:
  5845. text += " " + options
  5846. return text
  5847. def visit_drop_sequence(self, drop, **kw):
  5848. text = "DROP SEQUENCE "
  5849. if drop.if_exists:
  5850. text += "IF EXISTS "
  5851. return text + self.preparer.format_sequence(drop.element)
  5852. def visit_drop_constraint(self, drop, **kw):
  5853. constraint = drop.element
  5854. if constraint.name is not None:
  5855. formatted_name = self.preparer.format_constraint(constraint)
  5856. else:
  5857. formatted_name = None
  5858. if formatted_name is None:
  5859. raise exc.CompileError(
  5860. "Can't emit DROP CONSTRAINT for constraint %r; "
  5861. "it has no name" % drop.element
  5862. )
  5863. return "ALTER TABLE %s DROP CONSTRAINT %s%s%s" % (
  5864. self.preparer.format_table(drop.element.table),
  5865. "IF EXISTS " if drop.if_exists else "",
  5866. formatted_name,
  5867. " CASCADE" if drop.cascade else "",
  5868. )
  5869. def get_column_specification(self, column, **kwargs):
  5870. colspec = (
  5871. self.preparer.format_column(column)
  5872. + " "
  5873. + self.dialect.type_compiler_instance.process(
  5874. column.type, type_expression=column
  5875. )
  5876. )
  5877. default = self.get_column_default_string(column)
  5878. if default is not None:
  5879. colspec += " DEFAULT " + default
  5880. if column.computed is not None:
  5881. colspec += " " + self.process(column.computed)
  5882. if (
  5883. column.identity is not None
  5884. and self.dialect.supports_identity_columns
  5885. ):
  5886. colspec += " " + self.process(column.identity)
  5887. if not column.nullable and (
  5888. not column.identity or not self.dialect.supports_identity_columns
  5889. ):
  5890. colspec += " NOT NULL"
  5891. return colspec
  5892. def create_table_suffix(self, table):
  5893. return ""
  5894. def post_create_table(self, table):
  5895. return ""
  5896. def get_column_default_string(self, column: Column[Any]) -> Optional[str]:
  5897. if isinstance(column.server_default, schema.DefaultClause):
  5898. return self.render_default_string(column.server_default.arg)
  5899. else:
  5900. return None
  5901. def render_default_string(self, default: Union[Visitable, str]) -> str:
  5902. if isinstance(default, str):
  5903. return self.sql_compiler.render_literal_value(
  5904. default, sqltypes.STRINGTYPE
  5905. )
  5906. else:
  5907. return self.sql_compiler.process(default, literal_binds=True)
  5908. def visit_table_or_column_check_constraint(self, constraint, **kw):
  5909. if constraint.is_column_level:
  5910. return self.visit_column_check_constraint(constraint)
  5911. else:
  5912. return self.visit_check_constraint(constraint)
  5913. def visit_check_constraint(self, constraint, **kw):
  5914. text = ""
  5915. if constraint.name is not None:
  5916. formatted_name = self.preparer.format_constraint(constraint)
  5917. if formatted_name is not None:
  5918. text += "CONSTRAINT %s " % formatted_name
  5919. text += "CHECK (%s)" % self.sql_compiler.process(
  5920. constraint.sqltext, include_table=False, literal_binds=True
  5921. )
  5922. text += self.define_constraint_deferrability(constraint)
  5923. return text
  5924. def visit_column_check_constraint(self, constraint, **kw):
  5925. text = ""
  5926. if constraint.name is not None:
  5927. formatted_name = self.preparer.format_constraint(constraint)
  5928. if formatted_name is not None:
  5929. text += "CONSTRAINT %s " % formatted_name
  5930. text += "CHECK (%s)" % self.sql_compiler.process(
  5931. constraint.sqltext, include_table=False, literal_binds=True
  5932. )
  5933. text += self.define_constraint_deferrability(constraint)
  5934. return text
  5935. def visit_primary_key_constraint(
  5936. self, constraint: PrimaryKeyConstraint, **kw: Any
  5937. ) -> str:
  5938. if len(constraint) == 0:
  5939. return ""
  5940. text = ""
  5941. if constraint.name is not None:
  5942. formatted_name = self.preparer.format_constraint(constraint)
  5943. if formatted_name is not None:
  5944. text += "CONSTRAINT %s " % formatted_name
  5945. text += "PRIMARY KEY "
  5946. text += "(%s)" % ", ".join(
  5947. self.preparer.quote(c.name)
  5948. for c in (
  5949. constraint.columns_autoinc_first
  5950. if constraint._implicit_generated
  5951. else constraint.columns
  5952. )
  5953. )
  5954. text += self.define_constraint_deferrability(constraint)
  5955. return text
  5956. def visit_foreign_key_constraint(self, constraint, **kw):
  5957. preparer = self.preparer
  5958. text = ""
  5959. if constraint.name is not None:
  5960. formatted_name = self.preparer.format_constraint(constraint)
  5961. if formatted_name is not None:
  5962. text += "CONSTRAINT %s " % formatted_name
  5963. remote_table = list(constraint.elements)[0].column.table
  5964. text += "FOREIGN KEY(%s) REFERENCES %s (%s)" % (
  5965. ", ".join(
  5966. preparer.quote(f.parent.name) for f in constraint.elements
  5967. ),
  5968. self.define_constraint_remote_table(
  5969. constraint, remote_table, preparer
  5970. ),
  5971. ", ".join(
  5972. preparer.quote(f.column.name) for f in constraint.elements
  5973. ),
  5974. )
  5975. text += self.define_constraint_match(constraint)
  5976. text += self.define_constraint_cascades(constraint)
  5977. text += self.define_constraint_deferrability(constraint)
  5978. return text
  5979. def define_constraint_remote_table(self, constraint, table, preparer):
  5980. """Format the remote table clause of a CREATE CONSTRAINT clause."""
  5981. return preparer.format_table(table)
  5982. def visit_unique_constraint(
  5983. self, constraint: UniqueConstraint, **kw: Any
  5984. ) -> str:
  5985. if len(constraint) == 0:
  5986. return ""
  5987. text = ""
  5988. if constraint.name is not None:
  5989. formatted_name = self.preparer.format_constraint(constraint)
  5990. if formatted_name is not None:
  5991. text += "CONSTRAINT %s " % formatted_name
  5992. text += "UNIQUE %s(%s)" % (
  5993. self.define_unique_constraint_distinct(constraint, **kw),
  5994. ", ".join(self.preparer.quote(c.name) for c in constraint),
  5995. )
  5996. text += self.define_constraint_deferrability(constraint)
  5997. return text
  5998. def define_unique_constraint_distinct(
  5999. self, constraint: UniqueConstraint, **kw: Any
  6000. ) -> str:
  6001. return ""
  6002. def define_constraint_cascades(
  6003. self, constraint: ForeignKeyConstraint
  6004. ) -> str:
  6005. text = ""
  6006. if constraint.ondelete is not None:
  6007. text += self.define_constraint_ondelete_cascade(constraint)
  6008. if constraint.onupdate is not None:
  6009. text += self.define_constraint_onupdate_cascade(constraint)
  6010. return text
  6011. def define_constraint_ondelete_cascade(
  6012. self, constraint: ForeignKeyConstraint
  6013. ) -> str:
  6014. return " ON DELETE %s" % self.preparer.validate_sql_phrase(
  6015. constraint.ondelete, FK_ON_DELETE
  6016. )
  6017. def define_constraint_onupdate_cascade(
  6018. self, constraint: ForeignKeyConstraint
  6019. ) -> str:
  6020. return " ON UPDATE %s" % self.preparer.validate_sql_phrase(
  6021. constraint.onupdate, FK_ON_UPDATE
  6022. )
  6023. def define_constraint_deferrability(self, constraint: Constraint) -> str:
  6024. text = ""
  6025. if constraint.deferrable is not None:
  6026. if constraint.deferrable:
  6027. text += " DEFERRABLE"
  6028. else:
  6029. text += " NOT DEFERRABLE"
  6030. if constraint.initially is not None:
  6031. text += " INITIALLY %s" % self.preparer.validate_sql_phrase(
  6032. constraint.initially, FK_INITIALLY
  6033. )
  6034. return text
  6035. def define_constraint_match(self, constraint):
  6036. text = ""
  6037. if constraint.match is not None:
  6038. text += " MATCH %s" % constraint.match
  6039. return text
  6040. def visit_computed_column(self, generated, **kw):
  6041. text = "GENERATED ALWAYS AS (%s)" % self.sql_compiler.process(
  6042. generated.sqltext, include_table=False, literal_binds=True
  6043. )
  6044. if generated.persisted is True:
  6045. text += " STORED"
  6046. elif generated.persisted is False:
  6047. text += " VIRTUAL"
  6048. return text
  6049. def visit_identity_column(self, identity, **kw):
  6050. text = "GENERATED %s AS IDENTITY" % (
  6051. "ALWAYS" if identity.always else "BY DEFAULT",
  6052. )
  6053. options = self.get_identity_options(identity)
  6054. if options:
  6055. text += " (%s)" % options
  6056. return text
  6057. class GenericTypeCompiler(TypeCompiler):
  6058. def visit_FLOAT(self, type_: sqltypes.Float[Any], **kw: Any) -> str:
  6059. return "FLOAT"
  6060. def visit_DOUBLE(self, type_: sqltypes.Double[Any], **kw: Any) -> str:
  6061. return "DOUBLE"
  6062. def visit_DOUBLE_PRECISION(
  6063. self, type_: sqltypes.DOUBLE_PRECISION[Any], **kw: Any
  6064. ) -> str:
  6065. return "DOUBLE PRECISION"
  6066. def visit_REAL(self, type_: sqltypes.REAL[Any], **kw: Any) -> str:
  6067. return "REAL"
  6068. def visit_NUMERIC(self, type_: sqltypes.Numeric[Any], **kw: Any) -> str:
  6069. if type_.precision is None:
  6070. return "NUMERIC"
  6071. elif type_.scale is None:
  6072. return "NUMERIC(%(precision)s)" % {"precision": type_.precision}
  6073. else:
  6074. return "NUMERIC(%(precision)s, %(scale)s)" % {
  6075. "precision": type_.precision,
  6076. "scale": type_.scale,
  6077. }
  6078. def visit_DECIMAL(self, type_: sqltypes.DECIMAL[Any], **kw: Any) -> str:
  6079. if type_.precision is None:
  6080. return "DECIMAL"
  6081. elif type_.scale is None:
  6082. return "DECIMAL(%(precision)s)" % {"precision": type_.precision}
  6083. else:
  6084. return "DECIMAL(%(precision)s, %(scale)s)" % {
  6085. "precision": type_.precision,
  6086. "scale": type_.scale,
  6087. }
  6088. def visit_INTEGER(self, type_: sqltypes.Integer, **kw: Any) -> str:
  6089. return "INTEGER"
  6090. def visit_SMALLINT(self, type_: sqltypes.SmallInteger, **kw: Any) -> str:
  6091. return "SMALLINT"
  6092. def visit_BIGINT(self, type_: sqltypes.BigInteger, **kw: Any) -> str:
  6093. return "BIGINT"
  6094. def visit_TIMESTAMP(self, type_: sqltypes.TIMESTAMP, **kw: Any) -> str:
  6095. return "TIMESTAMP"
  6096. def visit_DATETIME(self, type_: sqltypes.DateTime, **kw: Any) -> str:
  6097. return "DATETIME"
  6098. def visit_DATE(self, type_: sqltypes.Date, **kw: Any) -> str:
  6099. return "DATE"
  6100. def visit_TIME(self, type_: sqltypes.Time, **kw: Any) -> str:
  6101. return "TIME"
  6102. def visit_CLOB(self, type_: sqltypes.CLOB, **kw: Any) -> str:
  6103. return "CLOB"
  6104. def visit_NCLOB(self, type_: sqltypes.Text, **kw: Any) -> str:
  6105. return "NCLOB"
  6106. def _render_string_type(
  6107. self, name: str, length: Optional[int], collation: Optional[str]
  6108. ) -> str:
  6109. text = name
  6110. if length:
  6111. text += f"({length})"
  6112. if collation:
  6113. text += f' COLLATE "{collation}"'
  6114. return text
  6115. def visit_CHAR(self, type_: sqltypes.CHAR, **kw: Any) -> str:
  6116. return self._render_string_type("CHAR", type_.length, type_.collation)
  6117. def visit_NCHAR(self, type_: sqltypes.NCHAR, **kw: Any) -> str:
  6118. return self._render_string_type("NCHAR", type_.length, type_.collation)
  6119. def visit_VARCHAR(self, type_: sqltypes.String, **kw: Any) -> str:
  6120. return self._render_string_type(
  6121. "VARCHAR", type_.length, type_.collation
  6122. )
  6123. def visit_NVARCHAR(self, type_: sqltypes.NVARCHAR, **kw: Any) -> str:
  6124. return self._render_string_type(
  6125. "NVARCHAR", type_.length, type_.collation
  6126. )
  6127. def visit_TEXT(self, type_: sqltypes.Text, **kw: Any) -> str:
  6128. return self._render_string_type("TEXT", type_.length, type_.collation)
  6129. def visit_UUID(self, type_: sqltypes.Uuid[Any], **kw: Any) -> str:
  6130. return "UUID"
  6131. def visit_BLOB(self, type_: sqltypes.LargeBinary, **kw: Any) -> str:
  6132. return "BLOB"
  6133. def visit_BINARY(self, type_: sqltypes.BINARY, **kw: Any) -> str:
  6134. return "BINARY" + (type_.length and "(%d)" % type_.length or "")
  6135. def visit_VARBINARY(self, type_: sqltypes.VARBINARY, **kw: Any) -> str:
  6136. return "VARBINARY" + (type_.length and "(%d)" % type_.length or "")
  6137. def visit_BOOLEAN(self, type_: sqltypes.Boolean, **kw: Any) -> str:
  6138. return "BOOLEAN"
  6139. def visit_uuid(self, type_: sqltypes.Uuid[Any], **kw: Any) -> str:
  6140. if not type_.native_uuid or not self.dialect.supports_native_uuid:
  6141. return self._render_string_type("CHAR", length=32, collation=None)
  6142. else:
  6143. return self.visit_UUID(type_, **kw)
  6144. def visit_large_binary(
  6145. self, type_: sqltypes.LargeBinary, **kw: Any
  6146. ) -> str:
  6147. return self.visit_BLOB(type_, **kw)
  6148. def visit_boolean(self, type_: sqltypes.Boolean, **kw: Any) -> str:
  6149. return self.visit_BOOLEAN(type_, **kw)
  6150. def visit_time(self, type_: sqltypes.Time, **kw: Any) -> str:
  6151. return self.visit_TIME(type_, **kw)
  6152. def visit_datetime(self, type_: sqltypes.DateTime, **kw: Any) -> str:
  6153. return self.visit_DATETIME(type_, **kw)
  6154. def visit_date(self, type_: sqltypes.Date, **kw: Any) -> str:
  6155. return self.visit_DATE(type_, **kw)
  6156. def visit_big_integer(self, type_: sqltypes.BigInteger, **kw: Any) -> str:
  6157. return self.visit_BIGINT(type_, **kw)
  6158. def visit_small_integer(
  6159. self, type_: sqltypes.SmallInteger, **kw: Any
  6160. ) -> str:
  6161. return self.visit_SMALLINT(type_, **kw)
  6162. def visit_integer(self, type_: sqltypes.Integer, **kw: Any) -> str:
  6163. return self.visit_INTEGER(type_, **kw)
  6164. def visit_real(self, type_: sqltypes.REAL[Any], **kw: Any) -> str:
  6165. return self.visit_REAL(type_, **kw)
  6166. def visit_float(self, type_: sqltypes.Float[Any], **kw: Any) -> str:
  6167. return self.visit_FLOAT(type_, **kw)
  6168. def visit_double(self, type_: sqltypes.Double[Any], **kw: Any) -> str:
  6169. return self.visit_DOUBLE(type_, **kw)
  6170. def visit_numeric(self, type_: sqltypes.Numeric[Any], **kw: Any) -> str:
  6171. return self.visit_NUMERIC(type_, **kw)
  6172. def visit_string(self, type_: sqltypes.String, **kw: Any) -> str:
  6173. return self.visit_VARCHAR(type_, **kw)
  6174. def visit_unicode(self, type_: sqltypes.Unicode, **kw: Any) -> str:
  6175. return self.visit_VARCHAR(type_, **kw)
  6176. def visit_text(self, type_: sqltypes.Text, **kw: Any) -> str:
  6177. return self.visit_TEXT(type_, **kw)
  6178. def visit_unicode_text(
  6179. self, type_: sqltypes.UnicodeText, **kw: Any
  6180. ) -> str:
  6181. return self.visit_TEXT(type_, **kw)
  6182. def visit_enum(self, type_: sqltypes.Enum, **kw: Any) -> str:
  6183. return self.visit_VARCHAR(type_, **kw)
  6184. def visit_null(self, type_, **kw):
  6185. raise exc.CompileError(
  6186. "Can't generate DDL for %r; "
  6187. "did you forget to specify a "
  6188. "type on this Column?" % type_
  6189. )
  6190. def visit_type_decorator(
  6191. self, type_: TypeDecorator[Any], **kw: Any
  6192. ) -> str:
  6193. return self.process(type_.type_engine(self.dialect), **kw)
  6194. def visit_user_defined(
  6195. self, type_: UserDefinedType[Any], **kw: Any
  6196. ) -> str:
  6197. return type_.get_col_spec(**kw)
  6198. class StrSQLTypeCompiler(GenericTypeCompiler):
  6199. def process(self, type_, **kw):
  6200. try:
  6201. _compiler_dispatch = type_._compiler_dispatch
  6202. except AttributeError:
  6203. return self._visit_unknown(type_, **kw)
  6204. else:
  6205. return _compiler_dispatch(self, **kw)
  6206. def __getattr__(self, key):
  6207. if key.startswith("visit_"):
  6208. return self._visit_unknown
  6209. else:
  6210. raise AttributeError(key)
  6211. def _visit_unknown(self, type_, **kw):
  6212. if type_.__class__.__name__ == type_.__class__.__name__.upper():
  6213. return type_.__class__.__name__
  6214. else:
  6215. return repr(type_)
  6216. def visit_null(self, type_, **kw):
  6217. return "NULL"
  6218. def visit_user_defined(self, type_, **kw):
  6219. try:
  6220. get_col_spec = type_.get_col_spec
  6221. except AttributeError:
  6222. return repr(type_)
  6223. else:
  6224. return get_col_spec(**kw)
  6225. class _SchemaForObjectCallable(Protocol):
  6226. def __call__(self, __obj: Any) -> str: ...
  6227. class _BindNameForColProtocol(Protocol):
  6228. def __call__(self, col: ColumnClause[Any]) -> str: ...
  6229. class IdentifierPreparer:
  6230. """Handle quoting and case-folding of identifiers based on options."""
  6231. reserved_words = RESERVED_WORDS
  6232. legal_characters = LEGAL_CHARACTERS
  6233. illegal_initial_characters = ILLEGAL_INITIAL_CHARACTERS
  6234. initial_quote: str
  6235. final_quote: str
  6236. _strings: MutableMapping[str, str]
  6237. schema_for_object: _SchemaForObjectCallable = operator.attrgetter("schema")
  6238. """Return the .schema attribute for an object.
  6239. For the default IdentifierPreparer, the schema for an object is always
  6240. the value of the ".schema" attribute. if the preparer is replaced
  6241. with one that has a non-empty schema_translate_map, the value of the
  6242. ".schema" attribute is rendered a symbol that will be converted to a
  6243. real schema name from the mapping post-compile.
  6244. """
  6245. _includes_none_schema_translate: bool = False
  6246. def __init__(
  6247. self,
  6248. dialect: Dialect,
  6249. initial_quote: str = '"',
  6250. final_quote: Optional[str] = None,
  6251. escape_quote: str = '"',
  6252. quote_case_sensitive_collations: bool = True,
  6253. omit_schema: bool = False,
  6254. ):
  6255. """Construct a new ``IdentifierPreparer`` object.
  6256. initial_quote
  6257. Character that begins a delimited identifier.
  6258. final_quote
  6259. Character that ends a delimited identifier. Defaults to
  6260. `initial_quote`.
  6261. omit_schema
  6262. Prevent prepending schema name. Useful for databases that do
  6263. not support schemae.
  6264. """
  6265. self.dialect = dialect
  6266. self.initial_quote = initial_quote
  6267. self.final_quote = final_quote or self.initial_quote
  6268. self.escape_quote = escape_quote
  6269. self.escape_to_quote = self.escape_quote * 2
  6270. self.omit_schema = omit_schema
  6271. self.quote_case_sensitive_collations = quote_case_sensitive_collations
  6272. self._strings = {}
  6273. self._double_percents = self.dialect.paramstyle in (
  6274. "format",
  6275. "pyformat",
  6276. )
  6277. def _with_schema_translate(self, schema_translate_map):
  6278. prep = self.__class__.__new__(self.__class__)
  6279. prep.__dict__.update(self.__dict__)
  6280. includes_none = None in schema_translate_map
  6281. def symbol_getter(obj):
  6282. name = obj.schema
  6283. if obj._use_schema_map and (name is not None or includes_none):
  6284. if name is not None and ("[" in name or "]" in name):
  6285. raise exc.CompileError(
  6286. "Square bracket characters ([]) not supported "
  6287. "in schema translate name '%s'" % name
  6288. )
  6289. return quoted_name(
  6290. "__[SCHEMA_%s]" % (name or "_none"), quote=False
  6291. )
  6292. else:
  6293. return obj.schema
  6294. prep.schema_for_object = symbol_getter
  6295. prep._includes_none_schema_translate = includes_none
  6296. return prep
  6297. def _render_schema_translates(
  6298. self, statement: str, schema_translate_map: SchemaTranslateMapType
  6299. ) -> str:
  6300. d = schema_translate_map
  6301. if None in d:
  6302. if not self._includes_none_schema_translate:
  6303. raise exc.InvalidRequestError(
  6304. "schema translate map which previously did not have "
  6305. "`None` present as a key now has `None` present; compiled "
  6306. "statement may lack adequate placeholders. Please use "
  6307. "consistent keys in successive "
  6308. "schema_translate_map dictionaries."
  6309. )
  6310. d["_none"] = d[None] # type: ignore[index]
  6311. def replace(m):
  6312. name = m.group(2)
  6313. if name in d:
  6314. effective_schema = d[name]
  6315. else:
  6316. if name in (None, "_none"):
  6317. raise exc.InvalidRequestError(
  6318. "schema translate map which previously had `None` "
  6319. "present as a key now no longer has it present; don't "
  6320. "know how to apply schema for compiled statement. "
  6321. "Please use consistent keys in successive "
  6322. "schema_translate_map dictionaries."
  6323. )
  6324. effective_schema = name
  6325. if not effective_schema:
  6326. effective_schema = self.dialect.default_schema_name
  6327. if not effective_schema:
  6328. # TODO: no coverage here
  6329. raise exc.CompileError(
  6330. "Dialect has no default schema name; can't "
  6331. "use None as dynamic schema target."
  6332. )
  6333. return self.quote_schema(effective_schema)
  6334. return re.sub(r"(__\[SCHEMA_([^\]]+)\])", replace, statement)
  6335. def _escape_identifier(self, value: str) -> str:
  6336. """Escape an identifier.
  6337. Subclasses should override this to provide database-dependent
  6338. escaping behavior.
  6339. """
  6340. value = value.replace(self.escape_quote, self.escape_to_quote)
  6341. if self._double_percents:
  6342. value = value.replace("%", "%%")
  6343. return value
  6344. def _unescape_identifier(self, value: str) -> str:
  6345. """Canonicalize an escaped identifier.
  6346. Subclasses should override this to provide database-dependent
  6347. unescaping behavior that reverses _escape_identifier.
  6348. """
  6349. return value.replace(self.escape_to_quote, self.escape_quote)
  6350. def validate_sql_phrase(self, element, reg):
  6351. """keyword sequence filter.
  6352. a filter for elements that are intended to represent keyword sequences,
  6353. such as "INITIALLY", "INITIALLY DEFERRED", etc. no special characters
  6354. should be present.
  6355. .. versionadded:: 1.3
  6356. """
  6357. if element is not None and not reg.match(element):
  6358. raise exc.CompileError(
  6359. "Unexpected SQL phrase: %r (matching against %r)"
  6360. % (element, reg.pattern)
  6361. )
  6362. return element
  6363. def quote_identifier(self, value: str) -> str:
  6364. """Quote an identifier.
  6365. Subclasses should override this to provide database-dependent
  6366. quoting behavior.
  6367. """
  6368. return (
  6369. self.initial_quote
  6370. + self._escape_identifier(value)
  6371. + self.final_quote
  6372. )
  6373. def _requires_quotes(self, value: str) -> bool:
  6374. """Return True if the given identifier requires quoting."""
  6375. lc_value = value.lower()
  6376. return (
  6377. lc_value in self.reserved_words
  6378. or value[0] in self.illegal_initial_characters
  6379. or not self.legal_characters.match(str(value))
  6380. or (lc_value != value)
  6381. )
  6382. def _requires_quotes_illegal_chars(self, value):
  6383. """Return True if the given identifier requires quoting, but
  6384. not taking case convention into account."""
  6385. return not self.legal_characters.match(str(value))
  6386. def quote_schema(self, schema: str, force: Any = None) -> str:
  6387. """Conditionally quote a schema name.
  6388. The name is quoted if it is a reserved word, contains quote-necessary
  6389. characters, or is an instance of :class:`.quoted_name` which includes
  6390. ``quote`` set to ``True``.
  6391. Subclasses can override this to provide database-dependent
  6392. quoting behavior for schema names.
  6393. :param schema: string schema name
  6394. :param force: unused
  6395. .. deprecated:: 0.9
  6396. The :paramref:`.IdentifierPreparer.quote_schema.force`
  6397. parameter is deprecated and will be removed in a future
  6398. release. This flag has no effect on the behavior of the
  6399. :meth:`.IdentifierPreparer.quote` method; please refer to
  6400. :class:`.quoted_name`.
  6401. """
  6402. if force is not None:
  6403. # not using the util.deprecated_params() decorator in this
  6404. # case because of the additional function call overhead on this
  6405. # very performance-critical spot.
  6406. util.warn_deprecated(
  6407. "The IdentifierPreparer.quote_schema.force parameter is "
  6408. "deprecated and will be removed in a future release. This "
  6409. "flag has no effect on the behavior of the "
  6410. "IdentifierPreparer.quote method; please refer to "
  6411. "quoted_name().",
  6412. # deprecated 0.9. warning from 1.3
  6413. version="0.9",
  6414. )
  6415. return self.quote(schema)
  6416. def quote(self, ident: str, force: Any = None) -> str:
  6417. """Conditionally quote an identifier.
  6418. The identifier is quoted if it is a reserved word, contains
  6419. quote-necessary characters, or is an instance of
  6420. :class:`.quoted_name` which includes ``quote`` set to ``True``.
  6421. Subclasses can override this to provide database-dependent
  6422. quoting behavior for identifier names.
  6423. :param ident: string identifier
  6424. :param force: unused
  6425. .. deprecated:: 0.9
  6426. The :paramref:`.IdentifierPreparer.quote.force`
  6427. parameter is deprecated and will be removed in a future
  6428. release. This flag has no effect on the behavior of the
  6429. :meth:`.IdentifierPreparer.quote` method; please refer to
  6430. :class:`.quoted_name`.
  6431. """
  6432. if force is not None:
  6433. # not using the util.deprecated_params() decorator in this
  6434. # case because of the additional function call overhead on this
  6435. # very performance-critical spot.
  6436. util.warn_deprecated(
  6437. "The IdentifierPreparer.quote.force parameter is "
  6438. "deprecated and will be removed in a future release. This "
  6439. "flag has no effect on the behavior of the "
  6440. "IdentifierPreparer.quote method; please refer to "
  6441. "quoted_name().",
  6442. # deprecated 0.9. warning from 1.3
  6443. version="0.9",
  6444. )
  6445. force = getattr(ident, "quote", None)
  6446. if force is None:
  6447. if ident in self._strings:
  6448. return self._strings[ident]
  6449. else:
  6450. if self._requires_quotes(ident):
  6451. self._strings[ident] = self.quote_identifier(ident)
  6452. else:
  6453. self._strings[ident] = ident
  6454. return self._strings[ident]
  6455. elif force:
  6456. return self.quote_identifier(ident)
  6457. else:
  6458. return ident
  6459. def format_collation(self, collation_name):
  6460. if self.quote_case_sensitive_collations:
  6461. return self.quote(collation_name)
  6462. else:
  6463. return collation_name
  6464. def format_sequence(
  6465. self, sequence: schema.Sequence, use_schema: bool = True
  6466. ) -> str:
  6467. name = self.quote(sequence.name)
  6468. effective_schema = self.schema_for_object(sequence)
  6469. if (
  6470. not self.omit_schema
  6471. and use_schema
  6472. and effective_schema is not None
  6473. ):
  6474. name = self.quote_schema(effective_schema) + "." + name
  6475. return name
  6476. def format_label(
  6477. self, label: Label[Any], name: Optional[str] = None
  6478. ) -> str:
  6479. return self.quote(name or label.name)
  6480. def format_alias(
  6481. self, alias: Optional[AliasedReturnsRows], name: Optional[str] = None
  6482. ) -> str:
  6483. if name is None:
  6484. assert alias is not None
  6485. return self.quote(alias.name)
  6486. else:
  6487. return self.quote(name)
  6488. def format_savepoint(self, savepoint, name=None):
  6489. # Running the savepoint name through quoting is unnecessary
  6490. # for all known dialects. This is here to support potential
  6491. # third party use cases
  6492. ident = name or savepoint.ident
  6493. if self._requires_quotes(ident):
  6494. ident = self.quote_identifier(ident)
  6495. return ident
  6496. @util.preload_module("sqlalchemy.sql.naming")
  6497. def format_constraint(
  6498. self, constraint: Union[Constraint, Index], _alembic_quote: bool = True
  6499. ) -> Optional[str]:
  6500. naming = util.preloaded.sql_naming
  6501. if constraint.name is _NONE_NAME:
  6502. name = naming._constraint_name_for_table(
  6503. constraint, constraint.table
  6504. )
  6505. if name is None:
  6506. return None
  6507. else:
  6508. name = constraint.name
  6509. assert name is not None
  6510. if constraint.__visit_name__ == "index":
  6511. return self.truncate_and_render_index_name(
  6512. name, _alembic_quote=_alembic_quote
  6513. )
  6514. else:
  6515. return self.truncate_and_render_constraint_name(
  6516. name, _alembic_quote=_alembic_quote
  6517. )
  6518. def truncate_and_render_index_name(
  6519. self, name: str, _alembic_quote: bool = True
  6520. ) -> str:
  6521. # calculate these at format time so that ad-hoc changes
  6522. # to dialect.max_identifier_length etc. can be reflected
  6523. # as IdentifierPreparer is long lived
  6524. max_ = (
  6525. self.dialect.max_index_name_length
  6526. or self.dialect.max_identifier_length
  6527. )
  6528. return self._truncate_and_render_maxlen_name(
  6529. name, max_, _alembic_quote
  6530. )
  6531. def truncate_and_render_constraint_name(
  6532. self, name: str, _alembic_quote: bool = True
  6533. ) -> str:
  6534. # calculate these at format time so that ad-hoc changes
  6535. # to dialect.max_identifier_length etc. can be reflected
  6536. # as IdentifierPreparer is long lived
  6537. max_ = (
  6538. self.dialect.max_constraint_name_length
  6539. or self.dialect.max_identifier_length
  6540. )
  6541. return self._truncate_and_render_maxlen_name(
  6542. name, max_, _alembic_quote
  6543. )
  6544. def _truncate_and_render_maxlen_name(
  6545. self, name: str, max_: int, _alembic_quote: bool
  6546. ) -> str:
  6547. if isinstance(name, elements._truncated_label):
  6548. if len(name) > max_:
  6549. name = name[0 : max_ - 8] + "_" + util.md5_hex(name)[-4:]
  6550. else:
  6551. self.dialect.validate_identifier(name)
  6552. if not _alembic_quote:
  6553. return name
  6554. else:
  6555. return self.quote(name)
  6556. def format_index(self, index: Index) -> str:
  6557. name = self.format_constraint(index)
  6558. assert name is not None
  6559. return name
  6560. def format_table(
  6561. self,
  6562. table: FromClause,
  6563. use_schema: bool = True,
  6564. name: Optional[str] = None,
  6565. ) -> str:
  6566. """Prepare a quoted table and schema name."""
  6567. if name is None:
  6568. if TYPE_CHECKING:
  6569. assert isinstance(table, NamedFromClause)
  6570. name = table.name
  6571. result = self.quote(name)
  6572. effective_schema = self.schema_for_object(table)
  6573. if not self.omit_schema and use_schema and effective_schema:
  6574. result = self.quote_schema(effective_schema) + "." + result
  6575. return result
  6576. def format_schema(self, name):
  6577. """Prepare a quoted schema name."""
  6578. return self.quote(name)
  6579. def format_label_name(
  6580. self,
  6581. name,
  6582. anon_map=None,
  6583. ):
  6584. """Prepare a quoted column name."""
  6585. if anon_map is not None and isinstance(
  6586. name, elements._truncated_label
  6587. ):
  6588. name = name.apply_map(anon_map)
  6589. return self.quote(name)
  6590. def format_column(
  6591. self,
  6592. column: ColumnElement[Any],
  6593. use_table: bool = False,
  6594. name: Optional[str] = None,
  6595. table_name: Optional[str] = None,
  6596. use_schema: bool = False,
  6597. anon_map: Optional[Mapping[str, Any]] = None,
  6598. ) -> str:
  6599. """Prepare a quoted column name."""
  6600. if name is None:
  6601. name = column.name
  6602. assert name is not None
  6603. if anon_map is not None and isinstance(
  6604. name, elements._truncated_label
  6605. ):
  6606. name = name.apply_map(anon_map)
  6607. if not getattr(column, "is_literal", False):
  6608. if use_table:
  6609. return (
  6610. self.format_table(
  6611. column.table, use_schema=use_schema, name=table_name
  6612. )
  6613. + "."
  6614. + self.quote(name)
  6615. )
  6616. else:
  6617. return self.quote(name)
  6618. else:
  6619. # literal textual elements get stuck into ColumnClause a lot,
  6620. # which shouldn't get quoted
  6621. if use_table:
  6622. return (
  6623. self.format_table(
  6624. column.table, use_schema=use_schema, name=table_name
  6625. )
  6626. + "."
  6627. + name
  6628. )
  6629. else:
  6630. return name
  6631. def format_table_seq(self, table, use_schema=True):
  6632. """Format table name and schema as a tuple."""
  6633. # Dialects with more levels in their fully qualified references
  6634. # ('database', 'owner', etc.) could override this and return
  6635. # a longer sequence.
  6636. effective_schema = self.schema_for_object(table)
  6637. if not self.omit_schema and use_schema and effective_schema:
  6638. return (
  6639. self.quote_schema(effective_schema),
  6640. self.format_table(table, use_schema=False),
  6641. )
  6642. else:
  6643. return (self.format_table(table, use_schema=False),)
  6644. @util.memoized_property
  6645. def _r_identifiers(self):
  6646. initial, final, escaped_final = (
  6647. re.escape(s)
  6648. for s in (
  6649. self.initial_quote,
  6650. self.final_quote,
  6651. self._escape_identifier(self.final_quote),
  6652. )
  6653. )
  6654. r = re.compile(
  6655. r"(?:"
  6656. r"(?:%(initial)s((?:%(escaped)s|[^%(final)s])+)%(final)s"
  6657. r"|([^\.]+))(?=\.|$))+"
  6658. % {"initial": initial, "final": final, "escaped": escaped_final}
  6659. )
  6660. return r
  6661. def unformat_identifiers(self, identifiers: str) -> Sequence[str]:
  6662. """Unpack 'schema.table.column'-like strings into components."""
  6663. r = self._r_identifiers
  6664. return [
  6665. self._unescape_identifier(i)
  6666. for i in [a or b for a, b in r.findall(identifiers)]
  6667. ]