compiler.py 189 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678
  1. # sql/compiler.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """Base SQL and DDL compiler implementations.
  8. Classes provided include:
  9. :class:`.compiler.SQLCompiler` - renders SQL
  10. strings
  11. :class:`.compiler.DDLCompiler` - renders DDL
  12. (data definition language) strings
  13. :class:`.compiler.GenericTypeCompiler` - renders
  14. type specification strings.
  15. To generate user-defined SQL strings, see
  16. :doc:`/ext/compiler`.
  17. """
  18. import collections
  19. import contextlib
  20. import itertools
  21. import operator
  22. import re
  23. from . import base
  24. from . import coercions
  25. from . import crud
  26. from . import elements
  27. from . import functions
  28. from . import operators
  29. from . import schema
  30. from . import selectable
  31. from . import sqltypes
  32. from . import util as sql_util
  33. from .base import NO_ARG
  34. from .base import prefix_anon_map
  35. from .elements import quoted_name
  36. from .. import exc
  37. from .. import util
  38. RESERVED_WORDS = set(
  39. [
  40. "all",
  41. "analyse",
  42. "analyze",
  43. "and",
  44. "any",
  45. "array",
  46. "as",
  47. "asc",
  48. "asymmetric",
  49. "authorization",
  50. "between",
  51. "binary",
  52. "both",
  53. "case",
  54. "cast",
  55. "check",
  56. "collate",
  57. "column",
  58. "constraint",
  59. "create",
  60. "cross",
  61. "current_date",
  62. "current_role",
  63. "current_time",
  64. "current_timestamp",
  65. "current_user",
  66. "default",
  67. "deferrable",
  68. "desc",
  69. "distinct",
  70. "do",
  71. "else",
  72. "end",
  73. "except",
  74. "false",
  75. "for",
  76. "foreign",
  77. "freeze",
  78. "from",
  79. "full",
  80. "grant",
  81. "group",
  82. "having",
  83. "ilike",
  84. "in",
  85. "initially",
  86. "inner",
  87. "intersect",
  88. "into",
  89. "is",
  90. "isnull",
  91. "join",
  92. "leading",
  93. "left",
  94. "like",
  95. "limit",
  96. "localtime",
  97. "localtimestamp",
  98. "natural",
  99. "new",
  100. "not",
  101. "notnull",
  102. "null",
  103. "off",
  104. "offset",
  105. "old",
  106. "on",
  107. "only",
  108. "or",
  109. "order",
  110. "outer",
  111. "overlaps",
  112. "placing",
  113. "primary",
  114. "references",
  115. "right",
  116. "select",
  117. "session_user",
  118. "set",
  119. "similar",
  120. "some",
  121. "symmetric",
  122. "table",
  123. "then",
  124. "to",
  125. "trailing",
  126. "true",
  127. "union",
  128. "unique",
  129. "user",
  130. "using",
  131. "verbose",
  132. "when",
  133. "where",
  134. ]
  135. )
  136. LEGAL_CHARACTERS = re.compile(r"^[A-Z0-9_$]+$", re.I)
  137. LEGAL_CHARACTERS_PLUS_SPACE = re.compile(r"^[A-Z0-9_ $]+$", re.I)
  138. ILLEGAL_INITIAL_CHARACTERS = {str(x) for x in range(0, 10)}.union(["$"])
  139. FK_ON_DELETE = re.compile(
  140. r"^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$", re.I
  141. )
  142. FK_ON_UPDATE = re.compile(
  143. r"^(?:RESTRICT|CASCADE|SET NULL|NO ACTION|SET DEFAULT)$", re.I
  144. )
  145. FK_INITIALLY = re.compile(r"^(?:DEFERRED|IMMEDIATE)$", re.I)
  146. BIND_PARAMS = re.compile(r"(?<![:\w\$\x5c]):([\w\$]+)(?![:\w\$])", re.UNICODE)
  147. BIND_PARAMS_ESC = re.compile(r"\x5c(:[\w\$]*)(?![:\w\$])", re.UNICODE)
  148. BIND_TEMPLATES = {
  149. "pyformat": "%%(%(name)s)s",
  150. "qmark": "?",
  151. "format": "%%s",
  152. "numeric": ":[_POSITION]",
  153. "named": ":%(name)s",
  154. }
  155. _BIND_TRANSLATE_RE = re.compile(r"[%\(\):\[\] ]")
  156. _BIND_TRANSLATE_CHARS = dict(zip("%():[] ", "PAZC___"))
  157. OPERATORS = {
  158. # binary
  159. operators.and_: " AND ",
  160. operators.or_: " OR ",
  161. operators.add: " + ",
  162. operators.mul: " * ",
  163. operators.sub: " - ",
  164. operators.div: " / ",
  165. operators.mod: " % ",
  166. operators.truediv: " / ",
  167. operators.neg: "-",
  168. operators.lt: " < ",
  169. operators.le: " <= ",
  170. operators.ne: " != ",
  171. operators.gt: " > ",
  172. operators.ge: " >= ",
  173. operators.eq: " = ",
  174. operators.is_distinct_from: " IS DISTINCT FROM ",
  175. operators.is_not_distinct_from: " IS NOT DISTINCT FROM ",
  176. operators.concat_op: " || ",
  177. operators.match_op: " MATCH ",
  178. operators.not_match_op: " NOT MATCH ",
  179. operators.in_op: " IN ",
  180. operators.not_in_op: " NOT IN ",
  181. operators.comma_op: ", ",
  182. operators.from_: " FROM ",
  183. operators.as_: " AS ",
  184. operators.is_: " IS ",
  185. operators.is_not: " IS NOT ",
  186. operators.collate: " COLLATE ",
  187. # unary
  188. operators.exists: "EXISTS ",
  189. operators.distinct_op: "DISTINCT ",
  190. operators.inv: "NOT ",
  191. operators.any_op: "ANY ",
  192. operators.all_op: "ALL ",
  193. # modifiers
  194. operators.desc_op: " DESC",
  195. operators.asc_op: " ASC",
  196. operators.nulls_first_op: " NULLS FIRST",
  197. operators.nulls_last_op: " NULLS LAST",
  198. }
  199. FUNCTIONS = {
  200. functions.coalesce: "coalesce",
  201. functions.current_date: "CURRENT_DATE",
  202. functions.current_time: "CURRENT_TIME",
  203. functions.current_timestamp: "CURRENT_TIMESTAMP",
  204. functions.current_user: "CURRENT_USER",
  205. functions.localtime: "LOCALTIME",
  206. functions.localtimestamp: "LOCALTIMESTAMP",
  207. functions.random: "random",
  208. functions.sysdate: "sysdate",
  209. functions.session_user: "SESSION_USER",
  210. functions.user: "USER",
  211. functions.cube: "CUBE",
  212. functions.rollup: "ROLLUP",
  213. functions.grouping_sets: "GROUPING SETS",
  214. }
  215. EXTRACT_MAP = {
  216. "month": "month",
  217. "day": "day",
  218. "year": "year",
  219. "second": "second",
  220. "hour": "hour",
  221. "doy": "doy",
  222. "minute": "minute",
  223. "quarter": "quarter",
  224. "dow": "dow",
  225. "week": "week",
  226. "epoch": "epoch",
  227. "milliseconds": "milliseconds",
  228. "microseconds": "microseconds",
  229. "timezone_hour": "timezone_hour",
  230. "timezone_minute": "timezone_minute",
  231. }
  232. COMPOUND_KEYWORDS = {
  233. selectable.CompoundSelect.UNION: "UNION",
  234. selectable.CompoundSelect.UNION_ALL: "UNION ALL",
  235. selectable.CompoundSelect.EXCEPT: "EXCEPT",
  236. selectable.CompoundSelect.EXCEPT_ALL: "EXCEPT ALL",
  237. selectable.CompoundSelect.INTERSECT: "INTERSECT",
  238. selectable.CompoundSelect.INTERSECT_ALL: "INTERSECT ALL",
  239. }
  240. RM_RENDERED_NAME = 0
  241. RM_NAME = 1
  242. RM_OBJECTS = 2
  243. RM_TYPE = 3
  244. ExpandedState = collections.namedtuple(
  245. "ExpandedState",
  246. [
  247. "statement",
  248. "additional_parameters",
  249. "processors",
  250. "positiontup",
  251. "parameter_expansion",
  252. ],
  253. )
  254. NO_LINTING = util.symbol("NO_LINTING", "Disable all linting.", canonical=0)
  255. COLLECT_CARTESIAN_PRODUCTS = util.symbol(
  256. "COLLECT_CARTESIAN_PRODUCTS",
  257. "Collect data on FROMs and cartesian products and gather "
  258. "into 'self.from_linter'",
  259. canonical=1,
  260. )
  261. WARN_LINTING = util.symbol(
  262. "WARN_LINTING", "Emit warnings for linters that find problems", canonical=2
  263. )
  264. FROM_LINTING = util.symbol(
  265. "FROM_LINTING",
  266. "Warn for cartesian products; "
  267. "combines COLLECT_CARTESIAN_PRODUCTS and WARN_LINTING",
  268. canonical=COLLECT_CARTESIAN_PRODUCTS | WARN_LINTING,
  269. )
  270. class FromLinter(collections.namedtuple("FromLinter", ["froms", "edges"])):
  271. def lint(self, start=None):
  272. froms = self.froms
  273. if not froms:
  274. return None, None
  275. edges = set(self.edges)
  276. the_rest = set(froms)
  277. if start is not None:
  278. start_with = start
  279. the_rest.remove(start_with)
  280. else:
  281. start_with = the_rest.pop()
  282. stack = collections.deque([start_with])
  283. while stack and the_rest:
  284. node = stack.popleft()
  285. the_rest.discard(node)
  286. # comparison of nodes in edges here is based on hash equality, as
  287. # there are "annotated" elements that match the non-annotated ones.
  288. # to remove the need for in-python hash() calls, use native
  289. # containment routines (e.g. "node in edge", "edge.index(node)")
  290. to_remove = {edge for edge in edges if node in edge}
  291. # appendleft the node in each edge that is not
  292. # the one that matched.
  293. stack.extendleft(edge[not edge.index(node)] for edge in to_remove)
  294. edges.difference_update(to_remove)
  295. # FROMS left over? boom
  296. if the_rest:
  297. return the_rest, start_with
  298. else:
  299. return None, None
  300. def warn(self):
  301. the_rest, start_with = self.lint()
  302. # FROMS left over? boom
  303. if the_rest:
  304. froms = the_rest
  305. if froms:
  306. template = (
  307. "SELECT statement has a cartesian product between "
  308. "FROM element(s) {froms} and "
  309. 'FROM element "{start}". Apply join condition(s) '
  310. "between each element to resolve."
  311. )
  312. froms_str = ", ".join(
  313. '"{elem}"'.format(elem=self.froms[from_])
  314. for from_ in froms
  315. )
  316. message = template.format(
  317. froms=froms_str, start=self.froms[start_with]
  318. )
  319. util.warn(message)
  320. class Compiled(object):
  321. """Represent a compiled SQL or DDL expression.
  322. The ``__str__`` method of the ``Compiled`` object should produce
  323. the actual text of the statement. ``Compiled`` objects are
  324. specific to their underlying database dialect, and also may
  325. or may not be specific to the columns referenced within a
  326. particular set of bind parameters. In no case should the
  327. ``Compiled`` object be dependent on the actual values of those
  328. bind parameters, even though it may reference those values as
  329. defaults.
  330. """
  331. _cached_metadata = None
  332. _result_columns = None
  333. schema_translate_map = None
  334. execution_options = util.EMPTY_DICT
  335. """
  336. Execution options propagated from the statement. In some cases,
  337. sub-elements of the statement can modify these.
  338. """
  339. _annotations = util.EMPTY_DICT
  340. compile_state = None
  341. """Optional :class:`.CompileState` object that maintains additional
  342. state used by the compiler.
  343. Major executable objects such as :class:`_expression.Insert`,
  344. :class:`_expression.Update`, :class:`_expression.Delete`,
  345. :class:`_expression.Select` will generate this
  346. state when compiled in order to calculate additional information about the
  347. object. For the top level object that is to be executed, the state can be
  348. stored here where it can also have applicability towards result set
  349. processing.
  350. .. versionadded:: 1.4
  351. """
  352. dml_compile_state = None
  353. """Optional :class:`.CompileState` assigned at the same point that
  354. .isinsert, .isupdate, or .isdelete is assigned.
  355. This will normally be the same object as .compile_state, with the
  356. exception of cases like the :class:`.ORMFromStatementCompileState`
  357. object.
  358. .. versionadded:: 1.4.40
  359. """
  360. cache_key = None
  361. _gen_time = None
  362. def __init__(
  363. self,
  364. dialect,
  365. statement,
  366. schema_translate_map=None,
  367. render_schema_translate=False,
  368. compile_kwargs=util.immutabledict(),
  369. ):
  370. """Construct a new :class:`.Compiled` object.
  371. :param dialect: :class:`.Dialect` to compile against.
  372. :param statement: :class:`_expression.ClauseElement` to be compiled.
  373. :param schema_translate_map: dictionary of schema names to be
  374. translated when forming the resultant SQL
  375. .. versionadded:: 1.1
  376. .. seealso::
  377. :ref:`schema_translating`
  378. :param compile_kwargs: additional kwargs that will be
  379. passed to the initial call to :meth:`.Compiled.process`.
  380. """
  381. self.dialect = dialect
  382. self.preparer = self.dialect.identifier_preparer
  383. if schema_translate_map:
  384. self.schema_translate_map = schema_translate_map
  385. self.preparer = self.preparer._with_schema_translate(
  386. schema_translate_map
  387. )
  388. if statement is not None:
  389. self.statement = statement
  390. self.can_execute = statement.supports_execution
  391. self._annotations = statement._annotations
  392. if self.can_execute:
  393. self.execution_options = statement._execution_options
  394. self.string = self.process(self.statement, **compile_kwargs)
  395. if render_schema_translate:
  396. self.string = self.preparer._render_schema_translates(
  397. self.string, schema_translate_map
  398. )
  399. self._gen_time = util.perf_counter()
  400. def _execute_on_connection(
  401. self, connection, multiparams, params, execution_options
  402. ):
  403. if self.can_execute:
  404. return connection._execute_compiled(
  405. self, multiparams, params, execution_options
  406. )
  407. else:
  408. raise exc.ObjectNotExecutableError(self.statement)
  409. def visit_unsupported_compilation(self, element, err):
  410. util.raise_(
  411. exc.UnsupportedCompilationError(self, type(element)),
  412. replace_context=err,
  413. )
  414. @property
  415. def sql_compiler(self):
  416. """Return a Compiled that is capable of processing SQL expressions.
  417. If this compiler is one, it would likely just return 'self'.
  418. """
  419. raise NotImplementedError()
  420. def process(self, obj, **kwargs):
  421. return obj._compiler_dispatch(self, **kwargs)
  422. def __str__(self):
  423. """Return the string text of the generated SQL or DDL."""
  424. return self.string or ""
  425. def construct_params(
  426. self, params=None, extracted_parameters=None, escape_names=True
  427. ):
  428. """Return the bind params for this compiled object.
  429. :param params: a dict of string/object pairs whose values will
  430. override bind values compiled in to the
  431. statement.
  432. """
  433. raise NotImplementedError()
  434. @property
  435. def params(self):
  436. """Return the bind params for this compiled object."""
  437. return self.construct_params()
  438. class TypeCompiler(util.with_metaclass(util.EnsureKWArgType, object)):
  439. """Produces DDL specification for TypeEngine objects."""
  440. ensure_kwarg = r"visit_\w+"
  441. def __init__(self, dialect):
  442. self.dialect = dialect
  443. def process(self, type_, **kw):
  444. return type_._compiler_dispatch(self, **kw)
  445. def visit_unsupported_compilation(self, element, err, **kw):
  446. util.raise_(
  447. exc.UnsupportedCompilationError(self, element),
  448. replace_context=err,
  449. )
  450. # this was a Visitable, but to allow accurate detection of
  451. # column elements this is actually a column element
  452. class _CompileLabel(elements.ColumnElement):
  453. """lightweight label object which acts as an expression.Label."""
  454. __visit_name__ = "label"
  455. __slots__ = "element", "name"
  456. def __init__(self, col, name, alt_names=()):
  457. self.element = col
  458. self.name = name
  459. self._alt_names = (col,) + alt_names
  460. @property
  461. def proxy_set(self):
  462. return self.element.proxy_set
  463. @property
  464. def type(self):
  465. return self.element.type
  466. def self_group(self, **kw):
  467. return self
  468. class SQLCompiler(Compiled):
  469. """Default implementation of :class:`.Compiled`.
  470. Compiles :class:`_expression.ClauseElement` objects into SQL strings.
  471. """
  472. extract_map = EXTRACT_MAP
  473. compound_keywords = COMPOUND_KEYWORDS
  474. isdelete = isinsert = isupdate = False
  475. """class-level defaults which can be set at the instance
  476. level to define if this Compiled instance represents
  477. INSERT/UPDATE/DELETE
  478. """
  479. isplaintext = False
  480. returning = None
  481. """holds the "returning" collection of columns if
  482. the statement is CRUD and defines returning columns
  483. either implicitly or explicitly
  484. """
  485. returning_precedes_values = False
  486. """set to True classwide to generate RETURNING
  487. clauses before the VALUES or WHERE clause (i.e. MSSQL)
  488. """
  489. render_table_with_column_in_update_from = False
  490. """set to True classwide to indicate the SET clause
  491. in a multi-table UPDATE statement should qualify
  492. columns with the table name (i.e. MySQL only)
  493. """
  494. ansi_bind_rules = False
  495. """SQL 92 doesn't allow bind parameters to be used
  496. in the columns clause of a SELECT, nor does it allow
  497. ambiguous expressions like "? = ?". A compiler
  498. subclass can set this flag to False if the target
  499. driver/DB enforces this
  500. """
  501. _textual_ordered_columns = False
  502. """tell the result object that the column names as rendered are important,
  503. but they are also "ordered" vs. what is in the compiled object here.
  504. As of 1.4.42 this condition is only present when the statement is a
  505. TextualSelect, e.g. text("....").columns(...), where it is required
  506. that the columns are considered positionally and not by name.
  507. """
  508. _ad_hoc_textual = False
  509. """tell the result that we encountered text() or '*' constructs in the
  510. middle of the result columns, but we also have compiled columns, so
  511. if the number of columns in cursor.description does not match how many
  512. expressions we have, that means we can't rely on positional at all and
  513. should match on name.
  514. """
  515. _ordered_columns = True
  516. """
  517. if False, means we can't be sure the list of entries
  518. in _result_columns is actually the rendered order. Usually
  519. True unless using an unordered TextualSelect.
  520. """
  521. _loose_column_name_matching = False
  522. """tell the result object that the SQL statement is textual, wants to match
  523. up to Column objects, and may be using the ._tq_label in the SELECT rather
  524. than the base name.
  525. """
  526. _numeric_binds = False
  527. """
  528. True if paramstyle is "numeric". This paramstyle is trickier than
  529. all the others.
  530. """
  531. _render_postcompile = False
  532. """
  533. whether to render out POSTCOMPILE params during the compile phase.
  534. """
  535. insert_single_values_expr = None
  536. """When an INSERT is compiled with a single set of parameters inside
  537. a VALUES expression, the string is assigned here, where it can be
  538. used for insert batching schemes to rewrite the VALUES expression.
  539. .. versionadded:: 1.3.8
  540. """
  541. literal_execute_params = frozenset()
  542. """bindparameter objects that are rendered as literal values at statement
  543. execution time.
  544. """
  545. post_compile_params = frozenset()
  546. """bindparameter objects that are rendered as bound parameter placeholders
  547. at statement execution time.
  548. """
  549. escaped_bind_names = util.EMPTY_DICT
  550. """Late escaping of bound parameter names that has to be converted
  551. to the original name when looking in the parameter dictionary.
  552. """
  553. has_out_parameters = False
  554. """if True, there are bindparam() objects that have the isoutparam
  555. flag set."""
  556. insert_prefetch = update_prefetch = ()
  557. postfetch_lastrowid = False
  558. """if True, and this in insert, use cursor.lastrowid to populate
  559. result.inserted_primary_key. """
  560. _cache_key_bind_match = None
  561. """a mapping that will relate the BindParameter object we compile
  562. to those that are part of the extracted collection of parameters
  563. in the cache key, if we were given a cache key.
  564. """
  565. _post_compile_pattern = re.compile(r"__\[POSTCOMPILE_(\S+?)(~~.+?~~)?\]")
  566. positiontup = None
  567. """for a compiled construct that uses a positional paramstyle, will be
  568. a sequence of strings, indicating the names of bound parameters in order.
  569. This is used in order to render bound parameters in their correct order,
  570. and is combined with the :attr:`_sql.Compiled.params` dictionary to
  571. render parameters.
  572. .. seealso::
  573. :ref:`faq_sql_expression_string` - includes a usage example for
  574. debugging use cases.
  575. """
  576. positiontup_level = None
  577. inline = False
  578. def __init__(
  579. self,
  580. dialect,
  581. statement,
  582. cache_key=None,
  583. column_keys=None,
  584. for_executemany=False,
  585. linting=NO_LINTING,
  586. **kwargs
  587. ):
  588. """Construct a new :class:`.SQLCompiler` object.
  589. :param dialect: :class:`.Dialect` to be used
  590. :param statement: :class:`_expression.ClauseElement` to be compiled
  591. :param column_keys: a list of column names to be compiled into an
  592. INSERT or UPDATE statement.
  593. :param for_executemany: whether INSERT / UPDATE statements should
  594. expect that they are to be invoked in an "executemany" style,
  595. which may impact how the statement will be expected to return the
  596. values of defaults and autoincrement / sequences and similar.
  597. Depending on the backend and driver in use, support for retrieving
  598. these values may be disabled which means SQL expressions may
  599. be rendered inline, RETURNING may not be rendered, etc.
  600. :param kwargs: additional keyword arguments to be consumed by the
  601. superclass.
  602. """
  603. self.column_keys = column_keys
  604. self.cache_key = cache_key
  605. if cache_key:
  606. self._cache_key_bind_match = ckbm = {
  607. b.key: b for b in cache_key[1]
  608. }
  609. ckbm.update({b: [b] for b in cache_key[1]})
  610. # compile INSERT/UPDATE defaults/sequences to expect executemany
  611. # style execution, which may mean no pre-execute of defaults,
  612. # or no RETURNING
  613. self.for_executemany = for_executemany
  614. self.linting = linting
  615. # a dictionary of bind parameter keys to BindParameter
  616. # instances.
  617. self.binds = {}
  618. # a dictionary of BindParameter instances to "compiled" names
  619. # that are actually present in the generated SQL
  620. self.bind_names = util.column_dict()
  621. # stack which keeps track of nested SELECT statements
  622. self.stack = []
  623. # relates label names in the final SQL to a tuple of local
  624. # column/label name, ColumnElement object (if any) and
  625. # TypeEngine. CursorResult uses this for type processing and
  626. # column targeting
  627. self._result_columns = []
  628. # true if the paramstyle is positional
  629. self.positional = dialect.positional
  630. if self.positional:
  631. self.positiontup_level = {}
  632. self.positiontup = []
  633. self._numeric_binds = dialect.paramstyle == "numeric"
  634. self.bindtemplate = BIND_TEMPLATES[dialect.paramstyle]
  635. self.ctes = None
  636. self.label_length = (
  637. dialect.label_length or dialect.max_identifier_length
  638. )
  639. # a map which tracks "anonymous" identifiers that are created on
  640. # the fly here
  641. self.anon_map = prefix_anon_map()
  642. # a map which tracks "truncated" names based on
  643. # dialect.label_length or dialect.max_identifier_length
  644. self.truncated_names = {}
  645. Compiled.__init__(self, dialect, statement, **kwargs)
  646. if self.isinsert or self.isupdate or self.isdelete:
  647. if statement._returning:
  648. self.returning = statement._returning
  649. if self.isinsert or self.isupdate:
  650. if statement._inline:
  651. self.inline = True
  652. elif self.for_executemany and (
  653. not self.isinsert
  654. or (
  655. self.dialect.insert_executemany_returning
  656. and statement._return_defaults
  657. )
  658. ):
  659. self.inline = True
  660. if self.positional and self._numeric_binds:
  661. self._apply_numbered_params()
  662. if self._render_postcompile:
  663. self._process_parameters_for_postcompile(_populate_self=True)
  664. @property
  665. def current_executable(self):
  666. """Return the current 'executable' that is being compiled.
  667. This is currently the :class:`_sql.Select`, :class:`_sql.Insert`,
  668. :class:`_sql.Update`, :class:`_sql.Delete`,
  669. :class:`_sql.CompoundSelect` object that is being compiled.
  670. Specifically it's assigned to the ``self.stack`` list of elements.
  671. When a statement like the above is being compiled, it normally
  672. is also assigned to the ``.statement`` attribute of the
  673. :class:`_sql.Compiler` object. However, all SQL constructs are
  674. ultimately nestable, and this attribute should never be consulted
  675. by a ``visit_`` method, as it is not guaranteed to be assigned
  676. nor guaranteed to correspond to the current statement being compiled.
  677. .. versionadded:: 1.3.21
  678. For compatibility with previous versions, use the following
  679. recipe::
  680. statement = getattr(self, "current_executable", False)
  681. if statement is False:
  682. statement = self.stack[-1]["selectable"]
  683. For versions 1.4 and above, ensure only .current_executable
  684. is used; the format of "self.stack" may change.
  685. """
  686. try:
  687. return self.stack[-1]["selectable"]
  688. except IndexError as ie:
  689. util.raise_(
  690. IndexError("Compiler does not have a stack entry"),
  691. replace_context=ie,
  692. )
  693. @property
  694. def prefetch(self):
  695. return list(self.insert_prefetch + self.update_prefetch)
  696. @util.memoized_property
  697. def _global_attributes(self):
  698. return {}
  699. @util.memoized_instancemethod
  700. def _init_cte_state(self):
  701. """Initialize collections related to CTEs only if
  702. a CTE is located, to save on the overhead of
  703. these collections otherwise.
  704. """
  705. # collect CTEs to tack on top of a SELECT
  706. # To store the query to print - Dict[cte, text_query]
  707. self.ctes = util.OrderedDict()
  708. # Detect same CTE references - Dict[(level, name), cte]
  709. # Level is required for supporting nesting
  710. self.ctes_by_level_name = {}
  711. # To retrieve key/level in ctes_by_level_name -
  712. # Dict[cte_reference, (level, cte_name)]
  713. self.level_name_by_cte = {}
  714. self.ctes_recursive = False
  715. if self.positional:
  716. self.cte_positional = {}
  717. self.cte_level = {}
  718. self.cte_order = collections.defaultdict(list)
  719. @contextlib.contextmanager
  720. def _nested_result(self):
  721. """special API to support the use case of 'nested result sets'"""
  722. result_columns, ordered_columns = (
  723. self._result_columns,
  724. self._ordered_columns,
  725. )
  726. self._result_columns, self._ordered_columns = [], False
  727. try:
  728. if self.stack:
  729. entry = self.stack[-1]
  730. entry["need_result_map_for_nested"] = True
  731. else:
  732. entry = None
  733. yield self._result_columns, self._ordered_columns
  734. finally:
  735. if entry:
  736. entry.pop("need_result_map_for_nested")
  737. self._result_columns, self._ordered_columns = (
  738. result_columns,
  739. ordered_columns,
  740. )
  741. def _apply_numbered_params(self):
  742. poscount = itertools.count(1)
  743. self.string = re.sub(
  744. r"\[_POSITION\]", lambda m: str(util.next(poscount)), self.string
  745. )
  746. @util.memoized_property
  747. def _bind_processors(self):
  748. return dict(
  749. (
  750. key,
  751. value,
  752. )
  753. for key, value in (
  754. (
  755. self.bind_names[bindparam],
  756. bindparam.type._cached_bind_processor(self.dialect)
  757. if not bindparam.type._is_tuple_type
  758. else tuple(
  759. elem_type._cached_bind_processor(self.dialect)
  760. for elem_type in bindparam.type.types
  761. ),
  762. )
  763. for bindparam in self.bind_names
  764. )
  765. if value is not None
  766. )
  767. def is_subquery(self):
  768. return len(self.stack) > 1
  769. @property
  770. def sql_compiler(self):
  771. return self
  772. def construct_params(
  773. self,
  774. params=None,
  775. _group_number=None,
  776. _check=True,
  777. extracted_parameters=None,
  778. escape_names=True,
  779. ):
  780. """return a dictionary of bind parameter keys and values"""
  781. has_escaped_names = escape_names and bool(self.escaped_bind_names)
  782. if extracted_parameters:
  783. # related the bound parameters collected in the original cache key
  784. # to those collected in the incoming cache key. They will not have
  785. # matching names but they will line up positionally in the same
  786. # way. The parameters present in self.bind_names may be clones of
  787. # these original cache key params in the case of DML but the .key
  788. # will be guaranteed to match.
  789. try:
  790. orig_extracted = self.cache_key[1]
  791. except TypeError as err:
  792. util.raise_(
  793. exc.CompileError(
  794. "This compiled object has no original cache key; "
  795. "can't pass extracted_parameters to construct_params"
  796. ),
  797. replace_context=err,
  798. )
  799. ckbm = self._cache_key_bind_match
  800. resolved_extracted = {
  801. bind: extracted
  802. for b, extracted in zip(orig_extracted, extracted_parameters)
  803. for bind in ckbm[b]
  804. }
  805. else:
  806. resolved_extracted = None
  807. if params:
  808. pd = {}
  809. for bindparam, name in self.bind_names.items():
  810. escaped_name = (
  811. self.escaped_bind_names.get(name, name)
  812. if has_escaped_names
  813. else name
  814. )
  815. if bindparam.key in params:
  816. pd[escaped_name] = params[bindparam.key]
  817. elif name in params:
  818. pd[escaped_name] = params[name]
  819. elif _check and bindparam.required:
  820. if _group_number:
  821. raise exc.InvalidRequestError(
  822. "A value is required for bind parameter %r, "
  823. "in parameter group %d"
  824. % (bindparam.key, _group_number),
  825. code="cd3x",
  826. )
  827. else:
  828. raise exc.InvalidRequestError(
  829. "A value is required for bind parameter %r"
  830. % bindparam.key,
  831. code="cd3x",
  832. )
  833. else:
  834. if resolved_extracted:
  835. value_param = resolved_extracted.get(
  836. bindparam, bindparam
  837. )
  838. else:
  839. value_param = bindparam
  840. if bindparam.callable:
  841. pd[escaped_name] = value_param.effective_value
  842. else:
  843. pd[escaped_name] = value_param.value
  844. return pd
  845. else:
  846. pd = {}
  847. for bindparam, name in self.bind_names.items():
  848. escaped_name = (
  849. self.escaped_bind_names.get(name, name)
  850. if has_escaped_names
  851. else name
  852. )
  853. if _check and bindparam.required:
  854. if _group_number:
  855. raise exc.InvalidRequestError(
  856. "A value is required for bind parameter %r, "
  857. "in parameter group %d"
  858. % (bindparam.key, _group_number),
  859. code="cd3x",
  860. )
  861. else:
  862. raise exc.InvalidRequestError(
  863. "A value is required for bind parameter %r"
  864. % bindparam.key,
  865. code="cd3x",
  866. )
  867. if resolved_extracted:
  868. value_param = resolved_extracted.get(bindparam, bindparam)
  869. else:
  870. value_param = bindparam
  871. if bindparam.callable:
  872. pd[escaped_name] = value_param.effective_value
  873. else:
  874. pd[escaped_name] = value_param.value
  875. return pd
  876. @util.memoized_instancemethod
  877. def _get_set_input_sizes_lookup(
  878. self, include_types=None, exclude_types=None
  879. ):
  880. if not hasattr(self, "bind_names"):
  881. return None
  882. dialect = self.dialect
  883. dbapi = self.dialect.dbapi
  884. # _unwrapped_dialect_impl() is necessary so that we get the
  885. # correct dialect type for a custom TypeDecorator, or a Variant,
  886. # which is also a TypeDecorator. Special types like Interval,
  887. # that use TypeDecorator but also might be mapped directly
  888. # for a dialect impl, also subclass Emulated first which overrides
  889. # this behavior in those cases to behave like the default.
  890. if include_types is None and exclude_types is None:
  891. def _lookup_type(typ):
  892. dbtype = typ.dialect_impl(dialect).get_dbapi_type(dbapi)
  893. return dbtype
  894. else:
  895. def _lookup_type(typ):
  896. # note we get dbtype from the possibly TypeDecorator-wrapped
  897. # dialect_impl, but the dialect_impl itself that we use for
  898. # include/exclude is the unwrapped version.
  899. dialect_impl = typ._unwrapped_dialect_impl(dialect)
  900. dbtype = typ.dialect_impl(dialect).get_dbapi_type(dbapi)
  901. if (
  902. dbtype is not None
  903. and (
  904. exclude_types is None
  905. or dbtype not in exclude_types
  906. and type(dialect_impl) not in exclude_types
  907. )
  908. and (
  909. include_types is None
  910. or dbtype in include_types
  911. or type(dialect_impl) in include_types
  912. )
  913. ):
  914. return dbtype
  915. else:
  916. return None
  917. inputsizes = {}
  918. literal_execute_params = self.literal_execute_params
  919. for bindparam in self.bind_names:
  920. if bindparam in literal_execute_params:
  921. continue
  922. if bindparam.type._is_tuple_type:
  923. inputsizes[bindparam] = [
  924. _lookup_type(typ) for typ in bindparam.type.types
  925. ]
  926. else:
  927. inputsizes[bindparam] = _lookup_type(bindparam.type)
  928. return inputsizes
  929. @property
  930. def params(self):
  931. """Return the bind param dictionary embedded into this
  932. compiled object, for those values that are present.
  933. .. seealso::
  934. :ref:`faq_sql_expression_string` - includes a usage example for
  935. debugging use cases.
  936. """
  937. return self.construct_params(_check=False)
  938. def _process_parameters_for_postcompile(
  939. self, parameters=None, _populate_self=False
  940. ):
  941. """handle special post compile parameters.
  942. These include:
  943. * "expanding" parameters -typically IN tuples that are rendered
  944. on a per-parameter basis for an otherwise fixed SQL statement string.
  945. * literal_binds compiled with the literal_execute flag. Used for
  946. things like SQL Server "TOP N" where the driver does not accommodate
  947. N as a bound parameter.
  948. """
  949. if parameters is None:
  950. parameters = self.construct_params(escape_names=False)
  951. expanded_parameters = {}
  952. if self.positional:
  953. positiontup = []
  954. else:
  955. positiontup = None
  956. processors = self._bind_processors
  957. new_processors = {}
  958. if self.positional and self._numeric_binds:
  959. # I'm not familiar with any DBAPI that uses 'numeric'.
  960. # strategy would likely be to make use of numbers greater than
  961. # the highest number present; then for expanding parameters,
  962. # append them to the end of the parameter list. that way
  963. # we avoid having to renumber all the existing parameters.
  964. raise NotImplementedError(
  965. "'post-compile' bind parameters are not supported with "
  966. "the 'numeric' paramstyle at this time."
  967. )
  968. replacement_expressions = {}
  969. to_update_sets = {}
  970. # notes:
  971. # *unescaped* parameter names in:
  972. # self.bind_names, self.binds, self._bind_processors
  973. #
  974. # *escaped* parameter names in:
  975. # construct_params(), replacement_expressions
  976. for name in (
  977. self.positiontup if self.positional else self.bind_names.values()
  978. ):
  979. escaped_name = (
  980. self.escaped_bind_names.get(name, name)
  981. if self.escaped_bind_names
  982. else name
  983. )
  984. parameter = self.binds[name]
  985. if parameter in self.literal_execute_params:
  986. if escaped_name not in replacement_expressions:
  987. replacement_expressions[
  988. escaped_name
  989. ] = self.render_literal_bindparam(
  990. parameter,
  991. render_literal_value=parameters.pop(escaped_name),
  992. )
  993. continue
  994. if parameter in self.post_compile_params:
  995. if escaped_name in replacement_expressions:
  996. to_update = to_update_sets[escaped_name]
  997. else:
  998. # we are removing the parameter from parameters
  999. # because it is a list value, which is not expected by
  1000. # TypeEngine objects that would otherwise be asked to
  1001. # process it. the single name is being replaced with
  1002. # individual numbered parameters for each value in the
  1003. # param.
  1004. #
  1005. # note we are also inserting *escaped* parameter names
  1006. # into the given dictionary. default dialect will
  1007. # use these param names directly as they will not be
  1008. # in the escaped_bind_names dictionary.
  1009. values = parameters.pop(name)
  1010. leep = self._literal_execute_expanding_parameter
  1011. to_update, replacement_expr = leep(
  1012. escaped_name, parameter, values
  1013. )
  1014. to_update_sets[escaped_name] = to_update
  1015. replacement_expressions[escaped_name] = replacement_expr
  1016. if not parameter.literal_execute:
  1017. parameters.update(to_update)
  1018. if parameter.type._is_tuple_type:
  1019. new_processors.update(
  1020. (
  1021. "%s_%s_%s" % (name, i, j),
  1022. processors[name][j - 1],
  1023. )
  1024. for i, tuple_element in enumerate(values, 1)
  1025. for j, value in enumerate(tuple_element, 1)
  1026. if name in processors
  1027. and processors[name][j - 1] is not None
  1028. )
  1029. else:
  1030. new_processors.update(
  1031. (key, processors[name])
  1032. for key, value in to_update
  1033. if name in processors
  1034. )
  1035. if self.positional:
  1036. positiontup.extend(name for name, value in to_update)
  1037. expanded_parameters[name] = [
  1038. expand_key for expand_key, value in to_update
  1039. ]
  1040. elif self.positional:
  1041. positiontup.append(name)
  1042. def process_expanding(m):
  1043. key = m.group(1)
  1044. expr = replacement_expressions[key]
  1045. # if POSTCOMPILE included a bind_expression, render that
  1046. # around each element
  1047. if m.group(2):
  1048. tok = m.group(2).split("~~")
  1049. be_left, be_right = tok[1], tok[3]
  1050. expr = ", ".join(
  1051. "%s%s%s" % (be_left, exp, be_right)
  1052. for exp in expr.split(", ")
  1053. )
  1054. return expr
  1055. statement = re.sub(
  1056. self._post_compile_pattern,
  1057. process_expanding,
  1058. self.string,
  1059. )
  1060. expanded_state = ExpandedState(
  1061. statement,
  1062. parameters,
  1063. new_processors,
  1064. positiontup,
  1065. expanded_parameters,
  1066. )
  1067. if _populate_self:
  1068. # this is for the "render_postcompile" flag, which is not
  1069. # otherwise used internally and is for end-user debugging and
  1070. # special use cases.
  1071. self.string = expanded_state.statement
  1072. self._bind_processors.update(expanded_state.processors)
  1073. self.positiontup = expanded_state.positiontup
  1074. self.post_compile_params = frozenset()
  1075. for key in expanded_state.parameter_expansion:
  1076. bind = self.binds.pop(key)
  1077. self.bind_names.pop(bind)
  1078. for value, expanded_key in zip(
  1079. bind.value, expanded_state.parameter_expansion[key]
  1080. ):
  1081. self.binds[expanded_key] = new_param = bind._with_value(
  1082. value
  1083. )
  1084. self.bind_names[new_param] = expanded_key
  1085. return expanded_state
  1086. @util.preload_module("sqlalchemy.engine.cursor")
  1087. def _create_result_map(self):
  1088. """utility method used for unit tests only."""
  1089. cursor = util.preloaded.engine_cursor
  1090. return cursor.CursorResultMetaData._create_description_match_map(
  1091. self._result_columns
  1092. )
  1093. @util.memoized_property
  1094. def _within_exec_param_key_getter(self):
  1095. getter = self._key_getters_for_crud_column[2]
  1096. return getter
  1097. @util.memoized_property
  1098. @util.preload_module("sqlalchemy.engine.result")
  1099. def _inserted_primary_key_from_lastrowid_getter(self):
  1100. result = util.preloaded.engine_result
  1101. param_key_getter = self._within_exec_param_key_getter
  1102. table = self.statement.table
  1103. getters = [
  1104. (operator.methodcaller("get", param_key_getter(col), None), col)
  1105. for col in table.primary_key
  1106. ]
  1107. autoinc_col = table._autoincrement_column
  1108. if autoinc_col is not None:
  1109. # apply type post processors to the lastrowid
  1110. proc = autoinc_col.type._cached_result_processor(
  1111. self.dialect, None
  1112. )
  1113. else:
  1114. proc = None
  1115. row_fn = result.result_tuple([col.key for col in table.primary_key])
  1116. def get(lastrowid, parameters):
  1117. """given cursor.lastrowid value and the parameters used for INSERT,
  1118. return a "row" that represents the primary key, either by
  1119. using the "lastrowid" or by extracting values from the parameters
  1120. that were sent along with the INSERT.
  1121. """
  1122. if proc is not None:
  1123. lastrowid = proc(lastrowid)
  1124. if lastrowid is None:
  1125. return row_fn(getter(parameters) for getter, col in getters)
  1126. else:
  1127. return row_fn(
  1128. lastrowid if col is autoinc_col else getter(parameters)
  1129. for getter, col in getters
  1130. )
  1131. return get
  1132. @util.memoized_property
  1133. @util.preload_module("sqlalchemy.engine.result")
  1134. def _inserted_primary_key_from_returning_getter(self):
  1135. result = util.preloaded.engine_result
  1136. param_key_getter = self._within_exec_param_key_getter
  1137. table = self.statement.table
  1138. ret = {col: idx for idx, col in enumerate(self.returning)}
  1139. getters = [
  1140. (operator.itemgetter(ret[col]), True)
  1141. if col in ret
  1142. else (
  1143. operator.methodcaller("get", param_key_getter(col), None),
  1144. False,
  1145. )
  1146. for col in table.primary_key
  1147. ]
  1148. row_fn = result.result_tuple([col.key for col in table.primary_key])
  1149. def get(row, parameters):
  1150. return row_fn(
  1151. getter(row) if use_row else getter(parameters)
  1152. for getter, use_row in getters
  1153. )
  1154. return get
  1155. def default_from(self):
  1156. """Called when a SELECT statement has no froms, and no FROM clause is
  1157. to be appended.
  1158. Gives Oracle a chance to tack on a ``FROM DUAL`` to the string output.
  1159. """
  1160. return ""
  1161. def visit_grouping(self, grouping, asfrom=False, **kwargs):
  1162. return "(" + grouping.element._compiler_dispatch(self, **kwargs) + ")"
  1163. def visit_select_statement_grouping(self, grouping, **kwargs):
  1164. return "(" + grouping.element._compiler_dispatch(self, **kwargs) + ")"
  1165. def visit_label_reference(
  1166. self, element, within_columns_clause=False, **kwargs
  1167. ):
  1168. if self.stack and self.dialect.supports_simple_order_by_label:
  1169. compile_state = self.stack[-1]["compile_state"]
  1170. (
  1171. with_cols,
  1172. only_froms,
  1173. only_cols,
  1174. ) = compile_state._label_resolve_dict
  1175. if within_columns_clause:
  1176. resolve_dict = only_froms
  1177. else:
  1178. resolve_dict = only_cols
  1179. # this can be None in the case that a _label_reference()
  1180. # were subject to a replacement operation, in which case
  1181. # the replacement of the Label element may have changed
  1182. # to something else like a ColumnClause expression.
  1183. order_by_elem = element.element._order_by_label_element
  1184. if (
  1185. order_by_elem is not None
  1186. and order_by_elem.name in resolve_dict
  1187. and order_by_elem.shares_lineage(
  1188. resolve_dict[order_by_elem.name]
  1189. )
  1190. ):
  1191. kwargs[
  1192. "render_label_as_label"
  1193. ] = element.element._order_by_label_element
  1194. return self.process(
  1195. element.element,
  1196. within_columns_clause=within_columns_clause,
  1197. **kwargs
  1198. )
  1199. def visit_textual_label_reference(
  1200. self, element, within_columns_clause=False, **kwargs
  1201. ):
  1202. if not self.stack:
  1203. # compiling the element outside of the context of a SELECT
  1204. return self.process(element._text_clause)
  1205. compile_state = self.stack[-1]["compile_state"]
  1206. with_cols, only_froms, only_cols = compile_state._label_resolve_dict
  1207. try:
  1208. if within_columns_clause:
  1209. col = only_froms[element.element]
  1210. else:
  1211. col = with_cols[element.element]
  1212. except KeyError as err:
  1213. coercions._no_text_coercion(
  1214. element.element,
  1215. extra=(
  1216. "Can't resolve label reference for ORDER BY / "
  1217. "GROUP BY / DISTINCT etc."
  1218. ),
  1219. exc_cls=exc.CompileError,
  1220. err=err,
  1221. )
  1222. else:
  1223. kwargs["render_label_as_label"] = col
  1224. return self.process(
  1225. col, within_columns_clause=within_columns_clause, **kwargs
  1226. )
  1227. def visit_label(
  1228. self,
  1229. label,
  1230. add_to_result_map=None,
  1231. within_label_clause=False,
  1232. within_columns_clause=False,
  1233. render_label_as_label=None,
  1234. result_map_targets=(),
  1235. **kw
  1236. ):
  1237. # only render labels within the columns clause
  1238. # or ORDER BY clause of a select. dialect-specific compilers
  1239. # can modify this behavior.
  1240. render_label_with_as = (
  1241. within_columns_clause and not within_label_clause
  1242. )
  1243. render_label_only = render_label_as_label is label
  1244. if render_label_only or render_label_with_as:
  1245. if isinstance(label.name, elements._truncated_label):
  1246. labelname = self._truncated_identifier("colident", label.name)
  1247. else:
  1248. labelname = label.name
  1249. if render_label_with_as:
  1250. if add_to_result_map is not None:
  1251. add_to_result_map(
  1252. labelname,
  1253. label.name,
  1254. (label, labelname) + label._alt_names + result_map_targets,
  1255. label.type,
  1256. )
  1257. return (
  1258. label.element._compiler_dispatch(
  1259. self,
  1260. within_columns_clause=True,
  1261. within_label_clause=True,
  1262. **kw
  1263. )
  1264. + OPERATORS[operators.as_]
  1265. + self.preparer.format_label(label, labelname)
  1266. )
  1267. elif render_label_only:
  1268. return self.preparer.format_label(label, labelname)
  1269. else:
  1270. return label.element._compiler_dispatch(
  1271. self, within_columns_clause=False, **kw
  1272. )
  1273. def _fallback_column_name(self, column):
  1274. raise exc.CompileError(
  1275. "Cannot compile Column object until " "its 'name' is assigned."
  1276. )
  1277. def visit_lambda_element(self, element, **kw):
  1278. sql_element = element._resolved
  1279. return self.process(sql_element, **kw)
  1280. def visit_column(
  1281. self,
  1282. column,
  1283. add_to_result_map=None,
  1284. include_table=True,
  1285. result_map_targets=(),
  1286. **kwargs
  1287. ):
  1288. name = orig_name = column.name
  1289. if name is None:
  1290. name = self._fallback_column_name(column)
  1291. is_literal = column.is_literal
  1292. if not is_literal and isinstance(name, elements._truncated_label):
  1293. name = self._truncated_identifier("colident", name)
  1294. if add_to_result_map is not None:
  1295. targets = (column, name, column.key) + result_map_targets
  1296. if column._tq_label:
  1297. targets += (column._tq_label,)
  1298. add_to_result_map(name, orig_name, targets, column.type)
  1299. if is_literal:
  1300. # note we are not currently accommodating for
  1301. # literal_column(quoted_name('ident', True)) here
  1302. name = self.escape_literal_column(name)
  1303. else:
  1304. name = self.preparer.quote(name)
  1305. table = column.table
  1306. if table is None or not include_table or not table.named_with_column:
  1307. return name
  1308. else:
  1309. effective_schema = self.preparer.schema_for_object(table)
  1310. if effective_schema:
  1311. schema_prefix = (
  1312. self.preparer.quote_schema(effective_schema) + "."
  1313. )
  1314. else:
  1315. schema_prefix = ""
  1316. tablename = table.name
  1317. if isinstance(tablename, elements._truncated_label):
  1318. tablename = self._truncated_identifier("alias", tablename)
  1319. return schema_prefix + self.preparer.quote(tablename) + "." + name
  1320. def visit_collation(self, element, **kw):
  1321. return self.preparer.format_collation(element.collation)
  1322. def visit_fromclause(self, fromclause, **kwargs):
  1323. return fromclause.name
  1324. def visit_index(self, index, **kwargs):
  1325. return index.name
  1326. def visit_typeclause(self, typeclause, **kw):
  1327. kw["type_expression"] = typeclause
  1328. kw["identifier_preparer"] = self.preparer
  1329. return self.dialect.type_compiler.process(typeclause.type, **kw)
  1330. def post_process_text(self, text):
  1331. if self.preparer._double_percents:
  1332. text = text.replace("%", "%%")
  1333. return text
  1334. def escape_literal_column(self, text):
  1335. if self.preparer._double_percents:
  1336. text = text.replace("%", "%%")
  1337. return text
  1338. def visit_textclause(self, textclause, add_to_result_map=None, **kw):
  1339. def do_bindparam(m):
  1340. name = m.group(1)
  1341. if name in textclause._bindparams:
  1342. return self.process(textclause._bindparams[name], **kw)
  1343. else:
  1344. return self.bindparam_string(name, **kw)
  1345. if not self.stack:
  1346. self.isplaintext = True
  1347. if add_to_result_map:
  1348. # text() object is present in the columns clause of a
  1349. # select(). Add a no-name entry to the result map so that
  1350. # row[text()] produces a result
  1351. add_to_result_map(None, None, (textclause,), sqltypes.NULLTYPE)
  1352. # un-escape any \:params
  1353. return BIND_PARAMS_ESC.sub(
  1354. lambda m: m.group(1),
  1355. BIND_PARAMS.sub(
  1356. do_bindparam, self.post_process_text(textclause.text)
  1357. ),
  1358. )
  1359. def visit_textual_select(
  1360. self, taf, compound_index=None, asfrom=False, **kw
  1361. ):
  1362. toplevel = not self.stack
  1363. entry = self._default_stack_entry if toplevel else self.stack[-1]
  1364. new_entry = {
  1365. "correlate_froms": set(),
  1366. "asfrom_froms": set(),
  1367. "selectable": taf,
  1368. }
  1369. self.stack.append(new_entry)
  1370. if taf._independent_ctes:
  1371. for cte in taf._independent_ctes:
  1372. cte._compiler_dispatch(self, **kw)
  1373. populate_result_map = (
  1374. toplevel
  1375. or (
  1376. compound_index == 0
  1377. and entry.get("need_result_map_for_compound", False)
  1378. )
  1379. or entry.get("need_result_map_for_nested", False)
  1380. )
  1381. if populate_result_map:
  1382. self._ordered_columns = (
  1383. self._textual_ordered_columns
  1384. ) = taf.positional
  1385. # enable looser result column matching when the SQL text links to
  1386. # Column objects by name only
  1387. self._loose_column_name_matching = not taf.positional and bool(
  1388. taf.column_args
  1389. )
  1390. for c in taf.column_args:
  1391. self.process(
  1392. c,
  1393. within_columns_clause=True,
  1394. add_to_result_map=self._add_to_result_map,
  1395. )
  1396. text = self.process(taf.element, **kw)
  1397. if self.ctes:
  1398. nesting_level = len(self.stack) if not toplevel else None
  1399. text = (
  1400. self._render_cte_clause(
  1401. nesting_level=nesting_level,
  1402. visiting_cte=kw.get("visiting_cte"),
  1403. )
  1404. + text
  1405. )
  1406. self.stack.pop(-1)
  1407. return text
  1408. def visit_null(self, expr, **kw):
  1409. return "NULL"
  1410. def visit_true(self, expr, **kw):
  1411. if self.dialect.supports_native_boolean:
  1412. return "true"
  1413. else:
  1414. return "1"
  1415. def visit_false(self, expr, **kw):
  1416. if self.dialect.supports_native_boolean:
  1417. return "false"
  1418. else:
  1419. return "0"
  1420. def _generate_delimited_list(self, elements, separator, **kw):
  1421. return separator.join(
  1422. s
  1423. for s in (c._compiler_dispatch(self, **kw) for c in elements)
  1424. if s
  1425. )
  1426. def _generate_delimited_and_list(self, clauses, **kw):
  1427. lcc, clauses = elements.BooleanClauseList._process_clauses_for_boolean(
  1428. operators.and_,
  1429. elements.True_._singleton,
  1430. elements.False_._singleton,
  1431. clauses,
  1432. )
  1433. if lcc == 1:
  1434. return clauses[0]._compiler_dispatch(self, **kw)
  1435. else:
  1436. separator = OPERATORS[operators.and_]
  1437. return separator.join(
  1438. s
  1439. for s in (c._compiler_dispatch(self, **kw) for c in clauses)
  1440. if s
  1441. )
  1442. def visit_tuple(self, clauselist, **kw):
  1443. return "(%s)" % self.visit_clauselist(clauselist, **kw)
  1444. def visit_clauselist(self, clauselist, **kw):
  1445. sep = clauselist.operator
  1446. if sep is None:
  1447. sep = " "
  1448. else:
  1449. sep = OPERATORS[clauselist.operator]
  1450. return self._generate_delimited_list(clauselist.clauses, sep, **kw)
  1451. def visit_case(self, clause, **kwargs):
  1452. x = "CASE "
  1453. if clause.value is not None:
  1454. x += clause.value._compiler_dispatch(self, **kwargs) + " "
  1455. for cond, result in clause.whens:
  1456. x += (
  1457. "WHEN "
  1458. + cond._compiler_dispatch(self, **kwargs)
  1459. + " THEN "
  1460. + result._compiler_dispatch(self, **kwargs)
  1461. + " "
  1462. )
  1463. if clause.else_ is not None:
  1464. x += (
  1465. "ELSE " + clause.else_._compiler_dispatch(self, **kwargs) + " "
  1466. )
  1467. x += "END"
  1468. return x
  1469. def visit_type_coerce(self, type_coerce, **kw):
  1470. return type_coerce.typed_expression._compiler_dispatch(self, **kw)
  1471. def visit_cast(self, cast, **kwargs):
  1472. return "CAST(%s AS %s)" % (
  1473. cast.clause._compiler_dispatch(self, **kwargs),
  1474. cast.typeclause._compiler_dispatch(self, **kwargs),
  1475. )
  1476. def _format_frame_clause(self, range_, **kw):
  1477. return "%s AND %s" % (
  1478. "UNBOUNDED PRECEDING"
  1479. if range_[0] is elements.RANGE_UNBOUNDED
  1480. else "CURRENT ROW"
  1481. if range_[0] is elements.RANGE_CURRENT
  1482. else "%s PRECEDING"
  1483. % (self.process(elements.literal(abs(range_[0])), **kw),)
  1484. if range_[0] < 0
  1485. else "%s FOLLOWING"
  1486. % (self.process(elements.literal(range_[0]), **kw),),
  1487. "UNBOUNDED FOLLOWING"
  1488. if range_[1] is elements.RANGE_UNBOUNDED
  1489. else "CURRENT ROW"
  1490. if range_[1] is elements.RANGE_CURRENT
  1491. else "%s PRECEDING"
  1492. % (self.process(elements.literal(abs(range_[1])), **kw),)
  1493. if range_[1] < 0
  1494. else "%s FOLLOWING"
  1495. % (self.process(elements.literal(range_[1]), **kw),),
  1496. )
  1497. def visit_over(self, over, **kwargs):
  1498. text = over.element._compiler_dispatch(self, **kwargs)
  1499. if over.range_:
  1500. range_ = "RANGE BETWEEN %s" % self._format_frame_clause(
  1501. over.range_, **kwargs
  1502. )
  1503. elif over.rows:
  1504. range_ = "ROWS BETWEEN %s" % self._format_frame_clause(
  1505. over.rows, **kwargs
  1506. )
  1507. else:
  1508. range_ = None
  1509. return "%s OVER (%s)" % (
  1510. text,
  1511. " ".join(
  1512. [
  1513. "%s BY %s"
  1514. % (word, clause._compiler_dispatch(self, **kwargs))
  1515. for word, clause in (
  1516. ("PARTITION", over.partition_by),
  1517. ("ORDER", over.order_by),
  1518. )
  1519. if clause is not None and len(clause)
  1520. ]
  1521. + ([range_] if range_ else [])
  1522. ),
  1523. )
  1524. def visit_withingroup(self, withingroup, **kwargs):
  1525. return "%s WITHIN GROUP (ORDER BY %s)" % (
  1526. withingroup.element._compiler_dispatch(self, **kwargs),
  1527. withingroup.order_by._compiler_dispatch(self, **kwargs),
  1528. )
  1529. def visit_funcfilter(self, funcfilter, **kwargs):
  1530. return "%s FILTER (WHERE %s)" % (
  1531. funcfilter.func._compiler_dispatch(self, **kwargs),
  1532. funcfilter.criterion._compiler_dispatch(self, **kwargs),
  1533. )
  1534. def visit_extract(self, extract, **kwargs):
  1535. field = self.extract_map.get(extract.field, extract.field)
  1536. return "EXTRACT(%s FROM %s)" % (
  1537. field,
  1538. extract.expr._compiler_dispatch(self, **kwargs),
  1539. )
  1540. def visit_scalar_function_column(self, element, **kw):
  1541. compiled_fn = self.visit_function(element.fn, **kw)
  1542. compiled_col = self.visit_column(element, **kw)
  1543. return "(%s).%s" % (compiled_fn, compiled_col)
  1544. def visit_function(self, func, add_to_result_map=None, **kwargs):
  1545. if add_to_result_map is not None:
  1546. add_to_result_map(func.name, func.name, (), func.type)
  1547. disp = getattr(self, "visit_%s_func" % func.name.lower(), None)
  1548. if disp:
  1549. text = disp(func, **kwargs)
  1550. else:
  1551. name = FUNCTIONS.get(func._deannotate().__class__, None)
  1552. if name:
  1553. if func._has_args:
  1554. name += "%(expr)s"
  1555. else:
  1556. name = func.name
  1557. name = (
  1558. self.preparer.quote(name)
  1559. if self.preparer._requires_quotes_illegal_chars(name)
  1560. or isinstance(name, elements.quoted_name)
  1561. else name
  1562. )
  1563. name = name + "%(expr)s"
  1564. text = ".".join(
  1565. [
  1566. (
  1567. self.preparer.quote(tok)
  1568. if self.preparer._requires_quotes_illegal_chars(tok)
  1569. or isinstance(name, elements.quoted_name)
  1570. else tok
  1571. )
  1572. for tok in func.packagenames
  1573. ]
  1574. + [name]
  1575. ) % {"expr": self.function_argspec(func, **kwargs)}
  1576. if func._with_ordinality:
  1577. text += " WITH ORDINALITY"
  1578. return text
  1579. def visit_next_value_func(self, next_value, **kw):
  1580. return self.visit_sequence(next_value.sequence)
  1581. def visit_sequence(self, sequence, **kw):
  1582. raise NotImplementedError(
  1583. "Dialect '%s' does not support sequence increments."
  1584. % self.dialect.name
  1585. )
  1586. def function_argspec(self, func, **kwargs):
  1587. return func.clause_expr._compiler_dispatch(self, **kwargs)
  1588. def visit_compound_select(
  1589. self, cs, asfrom=False, compound_index=None, **kwargs
  1590. ):
  1591. toplevel = not self.stack
  1592. compile_state = cs._compile_state_factory(cs, self, **kwargs)
  1593. if toplevel and not self.compile_state:
  1594. self.compile_state = compile_state
  1595. compound_stmt = compile_state.statement
  1596. entry = self._default_stack_entry if toplevel else self.stack[-1]
  1597. need_result_map = toplevel or (
  1598. not compound_index
  1599. and entry.get("need_result_map_for_compound", False)
  1600. )
  1601. # indicates there is already a CompoundSelect in play
  1602. if compound_index == 0:
  1603. entry["select_0"] = cs
  1604. self.stack.append(
  1605. {
  1606. "correlate_froms": entry["correlate_froms"],
  1607. "asfrom_froms": entry["asfrom_froms"],
  1608. "selectable": cs,
  1609. "compile_state": compile_state,
  1610. "need_result_map_for_compound": need_result_map,
  1611. }
  1612. )
  1613. if compound_stmt._independent_ctes:
  1614. for cte in compound_stmt._independent_ctes:
  1615. cte._compiler_dispatch(self, **kwargs)
  1616. keyword = self.compound_keywords.get(cs.keyword)
  1617. text = (" " + keyword + " ").join(
  1618. (
  1619. c._compiler_dispatch(
  1620. self, asfrom=asfrom, compound_index=i, **kwargs
  1621. )
  1622. for i, c in enumerate(cs.selects)
  1623. )
  1624. )
  1625. kwargs["include_table"] = False
  1626. text += self.group_by_clause(cs, **dict(asfrom=asfrom, **kwargs))
  1627. text += self.order_by_clause(cs, **kwargs)
  1628. if cs._has_row_limiting_clause:
  1629. text += self._row_limit_clause(cs, **kwargs)
  1630. if self.ctes:
  1631. nesting_level = len(self.stack) if not toplevel else None
  1632. text = (
  1633. self._render_cte_clause(
  1634. nesting_level=nesting_level,
  1635. include_following_stack=True,
  1636. visiting_cte=kwargs.get("visiting_cte"),
  1637. )
  1638. + text
  1639. )
  1640. self.stack.pop(-1)
  1641. return text
  1642. def _row_limit_clause(self, cs, **kwargs):
  1643. if cs._fetch_clause is not None:
  1644. return self.fetch_clause(cs, **kwargs)
  1645. else:
  1646. return self.limit_clause(cs, **kwargs)
  1647. def _get_operator_dispatch(self, operator_, qualifier1, qualifier2):
  1648. attrname = "visit_%s_%s%s" % (
  1649. operator_.__name__,
  1650. qualifier1,
  1651. "_" + qualifier2 if qualifier2 else "",
  1652. )
  1653. return getattr(self, attrname, None)
  1654. def visit_unary(
  1655. self, unary, add_to_result_map=None, result_map_targets=(), **kw
  1656. ):
  1657. if add_to_result_map is not None:
  1658. result_map_targets += (unary,)
  1659. kw["add_to_result_map"] = add_to_result_map
  1660. kw["result_map_targets"] = result_map_targets
  1661. if unary.operator:
  1662. if unary.modifier:
  1663. raise exc.CompileError(
  1664. "Unary expression does not support operator "
  1665. "and modifier simultaneously"
  1666. )
  1667. disp = self._get_operator_dispatch(
  1668. unary.operator, "unary", "operator"
  1669. )
  1670. if disp:
  1671. return disp(unary, unary.operator, **kw)
  1672. else:
  1673. return self._generate_generic_unary_operator(
  1674. unary, OPERATORS[unary.operator], **kw
  1675. )
  1676. elif unary.modifier:
  1677. disp = self._get_operator_dispatch(
  1678. unary.modifier, "unary", "modifier"
  1679. )
  1680. if disp:
  1681. return disp(unary, unary.modifier, **kw)
  1682. else:
  1683. return self._generate_generic_unary_modifier(
  1684. unary, OPERATORS[unary.modifier], **kw
  1685. )
  1686. else:
  1687. raise exc.CompileError(
  1688. "Unary expression has no operator or modifier"
  1689. )
  1690. def visit_is_true_unary_operator(self, element, operator, **kw):
  1691. if (
  1692. element._is_implicitly_boolean
  1693. or self.dialect.supports_native_boolean
  1694. ):
  1695. return self.process(element.element, **kw)
  1696. else:
  1697. return "%s = 1" % self.process(element.element, **kw)
  1698. def visit_is_false_unary_operator(self, element, operator, **kw):
  1699. if (
  1700. element._is_implicitly_boolean
  1701. or self.dialect.supports_native_boolean
  1702. ):
  1703. return "NOT %s" % self.process(element.element, **kw)
  1704. else:
  1705. return "%s = 0" % self.process(element.element, **kw)
  1706. def visit_not_match_op_binary(self, binary, operator, **kw):
  1707. return "NOT %s" % self.visit_binary(
  1708. binary, override_operator=operators.match_op
  1709. )
  1710. def visit_not_in_op_binary(self, binary, operator, **kw):
  1711. # The brackets are required in the NOT IN operation because the empty
  1712. # case is handled using the form "(col NOT IN (null) OR 1 = 1)".
  1713. # The presence of the OR makes the brackets required.
  1714. return "(%s)" % self._generate_generic_binary(
  1715. binary, OPERATORS[operator], **kw
  1716. )
  1717. def visit_empty_set_op_expr(self, type_, expand_op):
  1718. if expand_op is operators.not_in_op:
  1719. if len(type_) > 1:
  1720. return "(%s)) OR (1 = 1" % (
  1721. ", ".join("NULL" for element in type_)
  1722. )
  1723. else:
  1724. return "NULL) OR (1 = 1"
  1725. elif expand_op is operators.in_op:
  1726. if len(type_) > 1:
  1727. return "(%s)) AND (1 != 1" % (
  1728. ", ".join("NULL" for element in type_)
  1729. )
  1730. else:
  1731. return "NULL) AND (1 != 1"
  1732. else:
  1733. return self.visit_empty_set_expr(type_)
  1734. def visit_empty_set_expr(self, element_types):
  1735. raise NotImplementedError(
  1736. "Dialect '%s' does not support empty set expression."
  1737. % self.dialect.name
  1738. )
  1739. def _literal_execute_expanding_parameter_literal_binds(
  1740. self, parameter, values, bind_expression_template=None
  1741. ):
  1742. typ_dialect_impl = parameter.type._unwrapped_dialect_impl(self.dialect)
  1743. if not values:
  1744. # empty IN expression. note we don't need to use
  1745. # bind_expression_template here because there are no
  1746. # expressions to render.
  1747. if typ_dialect_impl._is_tuple_type:
  1748. replacement_expression = (
  1749. "VALUES " if self.dialect.tuple_in_values else ""
  1750. ) + self.visit_empty_set_op_expr(
  1751. parameter.type.types, parameter.expand_op
  1752. )
  1753. else:
  1754. replacement_expression = self.visit_empty_set_op_expr(
  1755. [parameter.type], parameter.expand_op
  1756. )
  1757. elif typ_dialect_impl._is_tuple_type or (
  1758. typ_dialect_impl._isnull
  1759. and isinstance(values[0], util.collections_abc.Sequence)
  1760. and not isinstance(
  1761. values[0], util.string_types + util.binary_types
  1762. )
  1763. ):
  1764. if typ_dialect_impl._has_bind_expression:
  1765. raise NotImplementedError(
  1766. "bind_expression() on TupleType not supported with "
  1767. "literal_binds"
  1768. )
  1769. replacement_expression = (
  1770. "VALUES " if self.dialect.tuple_in_values else ""
  1771. ) + ", ".join(
  1772. "(%s)"
  1773. % (
  1774. ", ".join(
  1775. self.render_literal_value(value, param_type)
  1776. for value, param_type in zip(
  1777. tuple_element, parameter.type.types
  1778. )
  1779. )
  1780. )
  1781. for i, tuple_element in enumerate(values)
  1782. )
  1783. else:
  1784. if bind_expression_template:
  1785. post_compile_pattern = self._post_compile_pattern
  1786. m = post_compile_pattern.search(bind_expression_template)
  1787. assert m and m.group(
  1788. 2
  1789. ), "unexpected format for expanding parameter"
  1790. tok = m.group(2).split("~~")
  1791. be_left, be_right = tok[1], tok[3]
  1792. replacement_expression = ", ".join(
  1793. "%s%s%s"
  1794. % (
  1795. be_left,
  1796. self.render_literal_value(value, parameter.type),
  1797. be_right,
  1798. )
  1799. for value in values
  1800. )
  1801. else:
  1802. replacement_expression = ", ".join(
  1803. self.render_literal_value(value, parameter.type)
  1804. for value in values
  1805. )
  1806. return (), replacement_expression
  1807. def _literal_execute_expanding_parameter(self, name, parameter, values):
  1808. if parameter.literal_execute:
  1809. return self._literal_execute_expanding_parameter_literal_binds(
  1810. parameter, values
  1811. )
  1812. typ_dialect_impl = parameter.type._unwrapped_dialect_impl(self.dialect)
  1813. if not values:
  1814. to_update = []
  1815. if typ_dialect_impl._is_tuple_type:
  1816. replacement_expression = self.visit_empty_set_op_expr(
  1817. parameter.type.types, parameter.expand_op
  1818. )
  1819. else:
  1820. replacement_expression = self.visit_empty_set_op_expr(
  1821. [parameter.type], parameter.expand_op
  1822. )
  1823. elif typ_dialect_impl._is_tuple_type or (
  1824. typ_dialect_impl._isnull
  1825. and isinstance(values[0], util.collections_abc.Sequence)
  1826. and not isinstance(
  1827. values[0], util.string_types + util.binary_types
  1828. )
  1829. ):
  1830. assert not typ_dialect_impl._is_array
  1831. to_update = [
  1832. ("%s_%s_%s" % (name, i, j), value)
  1833. for i, tuple_element in enumerate(values, 1)
  1834. for j, value in enumerate(tuple_element, 1)
  1835. ]
  1836. replacement_expression = (
  1837. "VALUES " if self.dialect.tuple_in_values else ""
  1838. ) + ", ".join(
  1839. "(%s)"
  1840. % (
  1841. ", ".join(
  1842. self.bindtemplate
  1843. % {"name": to_update[i * len(tuple_element) + j][0]}
  1844. for j, value in enumerate(tuple_element)
  1845. )
  1846. )
  1847. for i, tuple_element in enumerate(values)
  1848. )
  1849. else:
  1850. to_update = [
  1851. ("%s_%s" % (name, i), value)
  1852. for i, value in enumerate(values, 1)
  1853. ]
  1854. replacement_expression = ", ".join(
  1855. self.bindtemplate % {"name": key} for key, value in to_update
  1856. )
  1857. return to_update, replacement_expression
  1858. def visit_binary(
  1859. self,
  1860. binary,
  1861. override_operator=None,
  1862. eager_grouping=False,
  1863. from_linter=None,
  1864. lateral_from_linter=None,
  1865. **kw
  1866. ):
  1867. if from_linter and operators.is_comparison(binary.operator):
  1868. if lateral_from_linter is not None:
  1869. enclosing_lateral = kw["enclosing_lateral"]
  1870. lateral_from_linter.edges.update(
  1871. itertools.product(
  1872. binary.left._from_objects + [enclosing_lateral],
  1873. binary.right._from_objects + [enclosing_lateral],
  1874. )
  1875. )
  1876. else:
  1877. from_linter.edges.update(
  1878. itertools.product(
  1879. binary.left._from_objects, binary.right._from_objects
  1880. )
  1881. )
  1882. # don't allow "? = ?" to render
  1883. if (
  1884. self.ansi_bind_rules
  1885. and isinstance(binary.left, elements.BindParameter)
  1886. and isinstance(binary.right, elements.BindParameter)
  1887. ):
  1888. kw["literal_execute"] = True
  1889. operator_ = override_operator or binary.operator
  1890. disp = self._get_operator_dispatch(operator_, "binary", None)
  1891. if disp:
  1892. return disp(binary, operator_, **kw)
  1893. else:
  1894. try:
  1895. opstring = OPERATORS[operator_]
  1896. except KeyError as err:
  1897. util.raise_(
  1898. exc.UnsupportedCompilationError(self, operator_),
  1899. replace_context=err,
  1900. )
  1901. else:
  1902. return self._generate_generic_binary(
  1903. binary,
  1904. opstring,
  1905. from_linter=from_linter,
  1906. lateral_from_linter=lateral_from_linter,
  1907. **kw
  1908. )
  1909. def visit_function_as_comparison_op_binary(self, element, operator, **kw):
  1910. return self.process(element.sql_function, **kw)
  1911. def visit_mod_binary(self, binary, operator, **kw):
  1912. if self.preparer._double_percents:
  1913. return (
  1914. self.process(binary.left, **kw)
  1915. + " %% "
  1916. + self.process(binary.right, **kw)
  1917. )
  1918. else:
  1919. return (
  1920. self.process(binary.left, **kw)
  1921. + " % "
  1922. + self.process(binary.right, **kw)
  1923. )
  1924. def visit_custom_op_binary(self, element, operator, **kw):
  1925. kw["eager_grouping"] = operator.eager_grouping
  1926. return self._generate_generic_binary(
  1927. element,
  1928. " " + self.escape_literal_column(operator.opstring) + " ",
  1929. **kw
  1930. )
  1931. def visit_custom_op_unary_operator(self, element, operator, **kw):
  1932. return self._generate_generic_unary_operator(
  1933. element, self.escape_literal_column(operator.opstring) + " ", **kw
  1934. )
  1935. def visit_custom_op_unary_modifier(self, element, operator, **kw):
  1936. return self._generate_generic_unary_modifier(
  1937. element, " " + self.escape_literal_column(operator.opstring), **kw
  1938. )
  1939. def _generate_generic_binary(
  1940. self, binary, opstring, eager_grouping=False, **kw
  1941. ):
  1942. _in_binary = kw.get("_in_binary", False)
  1943. kw["_in_binary"] = True
  1944. kw["_binary_op"] = binary.operator
  1945. text = (
  1946. binary.left._compiler_dispatch(
  1947. self, eager_grouping=eager_grouping, **kw
  1948. )
  1949. + opstring
  1950. + binary.right._compiler_dispatch(
  1951. self, eager_grouping=eager_grouping, **kw
  1952. )
  1953. )
  1954. if _in_binary and eager_grouping:
  1955. text = "(%s)" % text
  1956. return text
  1957. def _generate_generic_unary_operator(self, unary, opstring, **kw):
  1958. return opstring + unary.element._compiler_dispatch(self, **kw)
  1959. def _generate_generic_unary_modifier(self, unary, opstring, **kw):
  1960. return unary.element._compiler_dispatch(self, **kw) + opstring
  1961. @util.memoized_property
  1962. def _like_percent_literal(self):
  1963. return elements.literal_column("'%'", type_=sqltypes.STRINGTYPE)
  1964. def visit_contains_op_binary(self, binary, operator, **kw):
  1965. binary = binary._clone()
  1966. percent = self._like_percent_literal
  1967. binary.right = percent.concat(binary.right).concat(percent)
  1968. return self.visit_like_op_binary(binary, operator, **kw)
  1969. def visit_not_contains_op_binary(self, binary, operator, **kw):
  1970. binary = binary._clone()
  1971. percent = self._like_percent_literal
  1972. binary.right = percent.concat(binary.right).concat(percent)
  1973. return self.visit_not_like_op_binary(binary, operator, **kw)
  1974. def visit_startswith_op_binary(self, binary, operator, **kw):
  1975. binary = binary._clone()
  1976. percent = self._like_percent_literal
  1977. binary.right = percent._rconcat(binary.right)
  1978. return self.visit_like_op_binary(binary, operator, **kw)
  1979. def visit_not_startswith_op_binary(self, binary, operator, **kw):
  1980. binary = binary._clone()
  1981. percent = self._like_percent_literal
  1982. binary.right = percent._rconcat(binary.right)
  1983. return self.visit_not_like_op_binary(binary, operator, **kw)
  1984. def visit_endswith_op_binary(self, binary, operator, **kw):
  1985. binary = binary._clone()
  1986. percent = self._like_percent_literal
  1987. binary.right = percent.concat(binary.right)
  1988. return self.visit_like_op_binary(binary, operator, **kw)
  1989. def visit_not_endswith_op_binary(self, binary, operator, **kw):
  1990. binary = binary._clone()
  1991. percent = self._like_percent_literal
  1992. binary.right = percent.concat(binary.right)
  1993. return self.visit_not_like_op_binary(binary, operator, **kw)
  1994. def visit_like_op_binary(self, binary, operator, **kw):
  1995. escape = binary.modifiers.get("escape", None)
  1996. # TODO: use ternary here, not "and"/ "or"
  1997. return "%s LIKE %s" % (
  1998. binary.left._compiler_dispatch(self, **kw),
  1999. binary.right._compiler_dispatch(self, **kw),
  2000. ) + (
  2001. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  2002. if escape
  2003. else ""
  2004. )
  2005. def visit_not_like_op_binary(self, binary, operator, **kw):
  2006. escape = binary.modifiers.get("escape", None)
  2007. return "%s NOT LIKE %s" % (
  2008. binary.left._compiler_dispatch(self, **kw),
  2009. binary.right._compiler_dispatch(self, **kw),
  2010. ) + (
  2011. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  2012. if escape
  2013. else ""
  2014. )
  2015. def visit_ilike_op_binary(self, binary, operator, **kw):
  2016. escape = binary.modifiers.get("escape", None)
  2017. return "lower(%s) LIKE lower(%s)" % (
  2018. binary.left._compiler_dispatch(self, **kw),
  2019. binary.right._compiler_dispatch(self, **kw),
  2020. ) + (
  2021. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  2022. if escape
  2023. else ""
  2024. )
  2025. def visit_not_ilike_op_binary(self, binary, operator, **kw):
  2026. escape = binary.modifiers.get("escape", None)
  2027. return "lower(%s) NOT LIKE lower(%s)" % (
  2028. binary.left._compiler_dispatch(self, **kw),
  2029. binary.right._compiler_dispatch(self, **kw),
  2030. ) + (
  2031. " ESCAPE " + self.render_literal_value(escape, sqltypes.STRINGTYPE)
  2032. if escape
  2033. else ""
  2034. )
  2035. def visit_between_op_binary(self, binary, operator, **kw):
  2036. symmetric = binary.modifiers.get("symmetric", False)
  2037. return self._generate_generic_binary(
  2038. binary, " BETWEEN SYMMETRIC " if symmetric else " BETWEEN ", **kw
  2039. )
  2040. def visit_not_between_op_binary(self, binary, operator, **kw):
  2041. symmetric = binary.modifiers.get("symmetric", False)
  2042. return self._generate_generic_binary(
  2043. binary,
  2044. " NOT BETWEEN SYMMETRIC " if symmetric else " NOT BETWEEN ",
  2045. **kw
  2046. )
  2047. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  2048. raise exc.CompileError(
  2049. "%s dialect does not support regular expressions"
  2050. % self.dialect.name
  2051. )
  2052. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  2053. raise exc.CompileError(
  2054. "%s dialect does not support regular expressions"
  2055. % self.dialect.name
  2056. )
  2057. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  2058. raise exc.CompileError(
  2059. "%s dialect does not support regular expression replacements"
  2060. % self.dialect.name
  2061. )
  2062. def visit_bindparam(
  2063. self,
  2064. bindparam,
  2065. within_columns_clause=False,
  2066. literal_binds=False,
  2067. skip_bind_expression=False,
  2068. literal_execute=False,
  2069. render_postcompile=False,
  2070. **kwargs
  2071. ):
  2072. if not skip_bind_expression:
  2073. impl = bindparam.type.dialect_impl(self.dialect)
  2074. if impl._has_bind_expression:
  2075. bind_expression = impl.bind_expression(bindparam)
  2076. wrapped = self.process(
  2077. bind_expression,
  2078. skip_bind_expression=True,
  2079. within_columns_clause=within_columns_clause,
  2080. literal_binds=literal_binds and not bindparam.expanding,
  2081. literal_execute=literal_execute,
  2082. render_postcompile=render_postcompile,
  2083. **kwargs
  2084. )
  2085. if bindparam.expanding:
  2086. # for postcompile w/ expanding, move the "wrapped" part
  2087. # of this into the inside
  2088. m = re.match(
  2089. r"^(.*)\(__\[POSTCOMPILE_(\S+?)\]\)(.*)$", wrapped
  2090. )
  2091. assert m, "unexpected format for expanding parameter"
  2092. wrapped = "(__[POSTCOMPILE_%s~~%s~~REPL~~%s~~])" % (
  2093. m.group(2),
  2094. m.group(1),
  2095. m.group(3),
  2096. )
  2097. if literal_binds:
  2098. ret = self.render_literal_bindparam(
  2099. bindparam,
  2100. within_columns_clause=True,
  2101. bind_expression_template=wrapped,
  2102. **kwargs
  2103. )
  2104. return "(%s)" % ret
  2105. return wrapped
  2106. if not literal_binds:
  2107. literal_execute = (
  2108. literal_execute
  2109. or bindparam.literal_execute
  2110. or (within_columns_clause and self.ansi_bind_rules)
  2111. )
  2112. post_compile = literal_execute or bindparam.expanding
  2113. else:
  2114. post_compile = False
  2115. if literal_binds:
  2116. ret = self.render_literal_bindparam(
  2117. bindparam, within_columns_clause=True, **kwargs
  2118. )
  2119. if bindparam.expanding:
  2120. ret = "(%s)" % ret
  2121. return ret
  2122. name = self._truncate_bindparam(bindparam)
  2123. if name in self.binds:
  2124. existing = self.binds[name]
  2125. if existing is not bindparam:
  2126. if (
  2127. (existing.unique or bindparam.unique)
  2128. and not existing.proxy_set.intersection(
  2129. bindparam.proxy_set
  2130. )
  2131. and not existing._cloned_set.intersection(
  2132. bindparam._cloned_set
  2133. )
  2134. ):
  2135. raise exc.CompileError(
  2136. "Bind parameter '%s' conflicts with "
  2137. "unique bind parameter of the same name" % name
  2138. )
  2139. elif existing.expanding != bindparam.expanding:
  2140. raise exc.CompileError(
  2141. "Can't reuse bound parameter name '%s' in both "
  2142. "'expanding' (e.g. within an IN expression) and "
  2143. "non-expanding contexts. If this parameter is to "
  2144. "receive a list/array value, set 'expanding=True' on "
  2145. "it for expressions that aren't IN, otherwise use "
  2146. "a different parameter name." % (name,)
  2147. )
  2148. elif existing._is_crud or bindparam._is_crud:
  2149. raise exc.CompileError(
  2150. "bindparam() name '%s' is reserved "
  2151. "for automatic usage in the VALUES or SET "
  2152. "clause of this "
  2153. "insert/update statement. Please use a "
  2154. "name other than column name when using bindparam() "
  2155. "with insert() or update() (for example, 'b_%s')."
  2156. % (bindparam.key, bindparam.key)
  2157. )
  2158. self.binds[bindparam.key] = self.binds[name] = bindparam
  2159. # if we are given a cache key that we're going to match against,
  2160. # relate the bindparam here to one that is most likely present
  2161. # in the "extracted params" portion of the cache key. this is used
  2162. # to set up a positional mapping that is used to determine the
  2163. # correct parameters for a subsequent use of this compiled with
  2164. # a different set of parameter values. here, we accommodate for
  2165. # parameters that may have been cloned both before and after the cache
  2166. # key was been generated.
  2167. ckbm = self._cache_key_bind_match
  2168. if ckbm:
  2169. for bp in bindparam._cloned_set:
  2170. if bp.key in ckbm:
  2171. cb = ckbm[bp.key]
  2172. ckbm[cb].append(bindparam)
  2173. if bindparam.isoutparam:
  2174. self.has_out_parameters = True
  2175. if post_compile:
  2176. if render_postcompile:
  2177. self._render_postcompile = True
  2178. if literal_execute:
  2179. self.literal_execute_params |= {bindparam}
  2180. else:
  2181. self.post_compile_params |= {bindparam}
  2182. ret = self.bindparam_string(
  2183. name,
  2184. post_compile=post_compile,
  2185. expanding=bindparam.expanding,
  2186. **kwargs
  2187. )
  2188. if bindparam.expanding:
  2189. ret = "(%s)" % ret
  2190. return ret
  2191. def render_literal_bindparam(
  2192. self,
  2193. bindparam,
  2194. render_literal_value=NO_ARG,
  2195. bind_expression_template=None,
  2196. **kw
  2197. ):
  2198. if render_literal_value is not NO_ARG:
  2199. value = render_literal_value
  2200. else:
  2201. if bindparam.value is None and bindparam.callable is None:
  2202. op = kw.get("_binary_op", None)
  2203. if op and op not in (operators.is_, operators.is_not):
  2204. util.warn_limited(
  2205. "Bound parameter '%s' rendering literal NULL in a SQL "
  2206. "expression; comparisons to NULL should not use "
  2207. "operators outside of 'is' or 'is not'",
  2208. (bindparam.key,),
  2209. )
  2210. return self.process(sqltypes.NULLTYPE, **kw)
  2211. value = bindparam.effective_value
  2212. if bindparam.expanding:
  2213. leep = self._literal_execute_expanding_parameter_literal_binds
  2214. to_update, replacement_expr = leep(
  2215. bindparam,
  2216. value,
  2217. bind_expression_template=bind_expression_template,
  2218. )
  2219. return replacement_expr
  2220. else:
  2221. return self.render_literal_value(value, bindparam.type)
  2222. def render_literal_value(self, value, type_):
  2223. """Render the value of a bind parameter as a quoted literal.
  2224. This is used for statement sections that do not accept bind parameters
  2225. on the target driver/database.
  2226. This should be implemented by subclasses using the quoting services
  2227. of the DBAPI.
  2228. """
  2229. processor = type_._cached_literal_processor(self.dialect)
  2230. if processor:
  2231. try:
  2232. return processor(value)
  2233. except Exception as e:
  2234. util.raise_(
  2235. exc.CompileError(
  2236. "Could not render literal value "
  2237. '"%s" '
  2238. "with datatype "
  2239. "%s; see parent stack trace for "
  2240. "more detail."
  2241. % (
  2242. sql_util._repr_single_value(value),
  2243. type_,
  2244. )
  2245. ),
  2246. from_=e,
  2247. )
  2248. else:
  2249. raise exc.CompileError(
  2250. "No literal value renderer is available for literal value "
  2251. '"%s" with datatype %s'
  2252. % (sql_util._repr_single_value(value), type_)
  2253. )
  2254. def _truncate_bindparam(self, bindparam):
  2255. if bindparam in self.bind_names:
  2256. return self.bind_names[bindparam]
  2257. bind_name = bindparam.key
  2258. if isinstance(bind_name, elements._truncated_label):
  2259. bind_name = self._truncated_identifier("bindparam", bind_name)
  2260. # add to bind_names for translation
  2261. self.bind_names[bindparam] = bind_name
  2262. return bind_name
  2263. def _truncated_identifier(self, ident_class, name):
  2264. if (ident_class, name) in self.truncated_names:
  2265. return self.truncated_names[(ident_class, name)]
  2266. anonname = name.apply_map(self.anon_map)
  2267. if len(anonname) > self.label_length - 6:
  2268. counter = self.truncated_names.get(ident_class, 1)
  2269. truncname = (
  2270. anonname[0 : max(self.label_length - 6, 0)]
  2271. + "_"
  2272. + hex(counter)[2:]
  2273. )
  2274. self.truncated_names[ident_class] = counter + 1
  2275. else:
  2276. truncname = anonname
  2277. self.truncated_names[(ident_class, name)] = truncname
  2278. return truncname
  2279. def _anonymize(self, name):
  2280. return name % self.anon_map
  2281. def bindparam_string(
  2282. self,
  2283. name,
  2284. positional_names=None,
  2285. post_compile=False,
  2286. expanding=False,
  2287. escaped_from=None,
  2288. **kw
  2289. ):
  2290. if self.positional:
  2291. if positional_names is not None:
  2292. positional_names.append(name)
  2293. else:
  2294. self.positiontup.append(name)
  2295. self.positiontup_level[name] = len(self.stack)
  2296. if not escaped_from:
  2297. if _BIND_TRANSLATE_RE.search(name):
  2298. # not quite the translate use case as we want to
  2299. # also get a quick boolean if we even found
  2300. # unusual characters in the name
  2301. new_name = _BIND_TRANSLATE_RE.sub(
  2302. lambda m: _BIND_TRANSLATE_CHARS[m.group(0)],
  2303. name,
  2304. )
  2305. escaped_from = name
  2306. name = new_name
  2307. if escaped_from:
  2308. if not self.escaped_bind_names:
  2309. self.escaped_bind_names = {}
  2310. self.escaped_bind_names[escaped_from] = name
  2311. if post_compile:
  2312. return "__[POSTCOMPILE_%s]" % name
  2313. else:
  2314. return self.bindtemplate % {"name": name}
  2315. def visit_cte(
  2316. self,
  2317. cte,
  2318. asfrom=False,
  2319. ashint=False,
  2320. fromhints=None,
  2321. visiting_cte=None,
  2322. from_linter=None,
  2323. **kwargs
  2324. ):
  2325. self._init_cte_state()
  2326. kwargs["visiting_cte"] = cte
  2327. cte_name = cte.name
  2328. if isinstance(cte_name, elements._truncated_label):
  2329. cte_name = self._truncated_identifier("alias", cte_name)
  2330. is_new_cte = True
  2331. embedded_in_current_named_cte = False
  2332. _reference_cte = cte._get_reference_cte()
  2333. if _reference_cte in self.level_name_by_cte:
  2334. cte_level, _ = self.level_name_by_cte[_reference_cte]
  2335. assert _ == cte_name
  2336. else:
  2337. cte_level = len(self.stack) if cte.nesting else 1
  2338. cte_level_name = (cte_level, cte_name)
  2339. if cte_level_name in self.ctes_by_level_name:
  2340. existing_cte = self.ctes_by_level_name[cte_level_name]
  2341. embedded_in_current_named_cte = visiting_cte is existing_cte
  2342. # we've generated a same-named CTE that we are enclosed in,
  2343. # or this is the same CTE. just return the name.
  2344. if cte is existing_cte._restates or cte is existing_cte:
  2345. is_new_cte = False
  2346. elif existing_cte is cte._restates:
  2347. # we've generated a same-named CTE that is
  2348. # enclosed in us - we take precedence, so
  2349. # discard the text for the "inner".
  2350. del self.ctes[existing_cte]
  2351. existing_cte_reference_cte = existing_cte._get_reference_cte()
  2352. # TODO: determine if these assertions are correct. they
  2353. # pass for current test cases
  2354. # assert existing_cte_reference_cte is _reference_cte
  2355. # assert existing_cte_reference_cte is existing_cte
  2356. del self.level_name_by_cte[existing_cte_reference_cte]
  2357. else:
  2358. # if the two CTEs are deep-copy identical, consider them
  2359. # the same, **if** they are clones, that is, they came from
  2360. # the ORM or other visit method
  2361. if (
  2362. cte._is_clone_of is not None
  2363. or existing_cte._is_clone_of is not None
  2364. ) and cte.compare(existing_cte):
  2365. is_new_cte = False
  2366. else:
  2367. raise exc.CompileError(
  2368. "Multiple, unrelated CTEs found with "
  2369. "the same name: %r" % cte_name
  2370. )
  2371. if not asfrom and not is_new_cte:
  2372. return None
  2373. if cte._cte_alias is not None:
  2374. pre_alias_cte = cte._cte_alias
  2375. cte_pre_alias_name = cte._cte_alias.name
  2376. if isinstance(cte_pre_alias_name, elements._truncated_label):
  2377. cte_pre_alias_name = self._truncated_identifier(
  2378. "alias", cte_pre_alias_name
  2379. )
  2380. else:
  2381. pre_alias_cte = cte
  2382. cte_pre_alias_name = None
  2383. if is_new_cte:
  2384. self.ctes_by_level_name[cte_level_name] = cte
  2385. self.level_name_by_cte[_reference_cte] = cte_level_name
  2386. if (
  2387. "autocommit" in cte.element._execution_options
  2388. and "autocommit" not in self.execution_options
  2389. ):
  2390. self.execution_options = self.execution_options.union(
  2391. {
  2392. "autocommit": cte.element._execution_options[
  2393. "autocommit"
  2394. ]
  2395. }
  2396. )
  2397. if self.positional:
  2398. self.cte_level[cte] = cte_level
  2399. if pre_alias_cte not in self.ctes:
  2400. self.visit_cte(pre_alias_cte, **kwargs)
  2401. if not cte_pre_alias_name and cte not in self.ctes:
  2402. if cte.recursive:
  2403. self.ctes_recursive = True
  2404. text = self.preparer.format_alias(cte, cte_name)
  2405. if cte.recursive:
  2406. if isinstance(cte.element, selectable.Select):
  2407. col_source = cte.element
  2408. elif isinstance(cte.element, selectable.CompoundSelect):
  2409. col_source = cte.element.selects[0]
  2410. else:
  2411. assert False, "cte should only be against SelectBase"
  2412. # TODO: can we get at the .columns_plus_names collection
  2413. # that is already (or will be?) generated for the SELECT
  2414. # rather than calling twice?
  2415. recur_cols = [
  2416. # TODO: proxy_name is not technically safe,
  2417. # see test_cte->
  2418. # test_with_recursive_no_name_currently_buggy. not
  2419. # clear what should be done with such a case
  2420. fallback_label_name or proxy_name
  2421. for (
  2422. _,
  2423. proxy_name,
  2424. fallback_label_name,
  2425. c,
  2426. repeated,
  2427. ) in (col_source._generate_columns_plus_names(True))
  2428. if not repeated
  2429. ]
  2430. text += "(%s)" % (
  2431. ", ".join(
  2432. self.preparer.format_label_name(
  2433. ident, anon_map=self.anon_map
  2434. )
  2435. for ident in recur_cols
  2436. )
  2437. )
  2438. if self.positional:
  2439. kwargs["positional_names"] = self.cte_positional[cte] = []
  2440. assert kwargs.get("subquery", False) is False
  2441. if not self.stack:
  2442. # toplevel, this is a stringify of the
  2443. # cte directly. just compile the inner
  2444. # the way alias() does.
  2445. return cte.element._compiler_dispatch(
  2446. self, asfrom=asfrom, **kwargs
  2447. )
  2448. else:
  2449. prefixes = self._generate_prefixes(
  2450. cte, cte._prefixes, **kwargs
  2451. )
  2452. inner = cte.element._compiler_dispatch(
  2453. self, asfrom=True, **kwargs
  2454. )
  2455. text += " AS %s\n(%s)" % (prefixes, inner)
  2456. if cte._suffixes:
  2457. text += " " + self._generate_prefixes(
  2458. cte, cte._suffixes, **kwargs
  2459. )
  2460. self.ctes[cte] = text
  2461. if asfrom:
  2462. if from_linter:
  2463. from_linter.froms[cte] = cte_name
  2464. if not is_new_cte and embedded_in_current_named_cte:
  2465. return self.preparer.format_alias(cte, cte_name)
  2466. if cte_pre_alias_name:
  2467. text = self.preparer.format_alias(cte, cte_pre_alias_name)
  2468. if self.preparer._requires_quotes(cte_name):
  2469. cte_name = self.preparer.quote(cte_name)
  2470. text += self.get_render_as_alias_suffix(cte_name)
  2471. return text
  2472. else:
  2473. return self.preparer.format_alias(cte, cte_name)
  2474. def visit_table_valued_alias(self, element, **kw):
  2475. if element.joins_implicitly:
  2476. kw["from_linter"] = None
  2477. if element._is_lateral:
  2478. return self.visit_lateral(element, **kw)
  2479. else:
  2480. return self.visit_alias(element, **kw)
  2481. def visit_table_valued_column(self, element, **kw):
  2482. return self.visit_column(element, **kw)
  2483. def visit_alias(
  2484. self,
  2485. alias,
  2486. asfrom=False,
  2487. ashint=False,
  2488. iscrud=False,
  2489. fromhints=None,
  2490. subquery=False,
  2491. lateral=False,
  2492. enclosing_alias=None,
  2493. from_linter=None,
  2494. **kwargs
  2495. ):
  2496. if lateral:
  2497. if "enclosing_lateral" not in kwargs:
  2498. # if lateral is set and enclosing_lateral is not
  2499. # present, we assume we are being called directly
  2500. # from visit_lateral() and we need to set enclosing_lateral.
  2501. assert alias._is_lateral
  2502. kwargs["enclosing_lateral"] = alias
  2503. # for lateral objects, we track a second from_linter that is...
  2504. # lateral! to the level above us.
  2505. if (
  2506. from_linter
  2507. and "lateral_from_linter" not in kwargs
  2508. and "enclosing_lateral" in kwargs
  2509. ):
  2510. kwargs["lateral_from_linter"] = from_linter
  2511. if enclosing_alias is not None and enclosing_alias.element is alias:
  2512. inner = alias.element._compiler_dispatch(
  2513. self,
  2514. asfrom=asfrom,
  2515. ashint=ashint,
  2516. iscrud=iscrud,
  2517. fromhints=fromhints,
  2518. lateral=lateral,
  2519. enclosing_alias=alias,
  2520. **kwargs
  2521. )
  2522. if subquery and (asfrom or lateral):
  2523. inner = "(%s)" % (inner,)
  2524. return inner
  2525. else:
  2526. enclosing_alias = kwargs["enclosing_alias"] = alias
  2527. if asfrom or ashint:
  2528. if isinstance(alias.name, elements._truncated_label):
  2529. alias_name = self._truncated_identifier("alias", alias.name)
  2530. else:
  2531. alias_name = alias.name
  2532. if ashint:
  2533. return self.preparer.format_alias(alias, alias_name)
  2534. elif asfrom:
  2535. if from_linter:
  2536. from_linter.froms[alias] = alias_name
  2537. inner = alias.element._compiler_dispatch(
  2538. self, asfrom=True, lateral=lateral, **kwargs
  2539. )
  2540. if subquery:
  2541. inner = "(%s)" % (inner,)
  2542. ret = inner + self.get_render_as_alias_suffix(
  2543. self.preparer.format_alias(alias, alias_name)
  2544. )
  2545. if alias._supports_derived_columns and alias._render_derived:
  2546. ret += "(%s)" % (
  2547. ", ".join(
  2548. "%s%s"
  2549. % (
  2550. self.preparer.quote(col.name),
  2551. " %s"
  2552. % self.dialect.type_compiler.process(
  2553. col.type, **kwargs
  2554. )
  2555. if alias._render_derived_w_types
  2556. else "",
  2557. )
  2558. for col in alias.c
  2559. )
  2560. )
  2561. if fromhints and alias in fromhints:
  2562. ret = self.format_from_hint_text(
  2563. ret, alias, fromhints[alias], iscrud
  2564. )
  2565. return ret
  2566. else:
  2567. # note we cancel the "subquery" flag here as well
  2568. return alias.element._compiler_dispatch(
  2569. self, lateral=lateral, **kwargs
  2570. )
  2571. def visit_subquery(self, subquery, **kw):
  2572. kw["subquery"] = True
  2573. return self.visit_alias(subquery, **kw)
  2574. def visit_lateral(self, lateral_, **kw):
  2575. kw["lateral"] = True
  2576. return "LATERAL %s" % self.visit_alias(lateral_, **kw)
  2577. def visit_tablesample(self, tablesample, asfrom=False, **kw):
  2578. text = "%s TABLESAMPLE %s" % (
  2579. self.visit_alias(tablesample, asfrom=True, **kw),
  2580. tablesample._get_method()._compiler_dispatch(self, **kw),
  2581. )
  2582. if tablesample.seed is not None:
  2583. text += " REPEATABLE (%s)" % (
  2584. tablesample.seed._compiler_dispatch(self, **kw)
  2585. )
  2586. return text
  2587. def visit_values(self, element, asfrom=False, from_linter=None, **kw):
  2588. kw.setdefault("literal_binds", element.literal_binds)
  2589. v = "VALUES %s" % ", ".join(
  2590. self.process(
  2591. elements.Tuple(
  2592. types=element._column_types, *elem
  2593. ).self_group(),
  2594. **kw
  2595. )
  2596. for chunk in element._data
  2597. for elem in chunk
  2598. )
  2599. if isinstance(element.name, elements._truncated_label):
  2600. name = self._truncated_identifier("values", element.name)
  2601. else:
  2602. name = element.name
  2603. if element._is_lateral:
  2604. lateral = "LATERAL "
  2605. else:
  2606. lateral = ""
  2607. if asfrom:
  2608. if from_linter:
  2609. from_linter.froms[element] = (
  2610. name if name is not None else "(unnamed VALUES element)"
  2611. )
  2612. if name:
  2613. v = "%s(%s)%s (%s)" % (
  2614. lateral,
  2615. v,
  2616. self.get_render_as_alias_suffix(self.preparer.quote(name)),
  2617. (
  2618. ", ".join(
  2619. c._compiler_dispatch(
  2620. self, include_table=False, **kw
  2621. )
  2622. for c in element.columns
  2623. )
  2624. ),
  2625. )
  2626. else:
  2627. v = "%s(%s)" % (lateral, v)
  2628. return v
  2629. def get_render_as_alias_suffix(self, alias_name_text):
  2630. return " AS " + alias_name_text
  2631. def _add_to_result_map(self, keyname, name, objects, type_):
  2632. if keyname is None or keyname == "*":
  2633. self._ordered_columns = False
  2634. self._ad_hoc_textual = True
  2635. if type_._is_tuple_type:
  2636. raise exc.CompileError(
  2637. "Most backends don't support SELECTing "
  2638. "from a tuple() object. If this is an ORM query, "
  2639. "consider using the Bundle object."
  2640. )
  2641. self._result_columns.append((keyname, name, objects, type_))
  2642. def _label_returning_column(
  2643. self, stmt, column, column_clause_args=None, **kw
  2644. ):
  2645. """Render a column with necessary labels inside of a RETURNING clause.
  2646. This method is provided for individual dialects in place of calling
  2647. the _label_select_column method directly, so that the two use cases
  2648. of RETURNING vs. SELECT can be disambiguated going forward.
  2649. .. versionadded:: 1.4.21
  2650. """
  2651. return self._label_select_column(
  2652. None,
  2653. column,
  2654. True,
  2655. False,
  2656. {} if column_clause_args is None else column_clause_args,
  2657. **kw
  2658. )
  2659. def _label_select_column(
  2660. self,
  2661. select,
  2662. column,
  2663. populate_result_map,
  2664. asfrom,
  2665. column_clause_args,
  2666. name=None,
  2667. proxy_name=None,
  2668. fallback_label_name=None,
  2669. within_columns_clause=True,
  2670. column_is_repeated=False,
  2671. need_column_expressions=False,
  2672. ):
  2673. """produce labeled columns present in a select()."""
  2674. impl = column.type.dialect_impl(self.dialect)
  2675. if impl._has_column_expression and (
  2676. need_column_expressions or populate_result_map
  2677. ):
  2678. col_expr = impl.column_expression(column)
  2679. else:
  2680. col_expr = column
  2681. if populate_result_map:
  2682. # pass an "add_to_result_map" callable into the compilation
  2683. # of embedded columns. this collects information about the
  2684. # column as it will be fetched in the result and is coordinated
  2685. # with cursor.description when the query is executed.
  2686. add_to_result_map = self._add_to_result_map
  2687. # if the SELECT statement told us this column is a repeat,
  2688. # wrap the callable with one that prevents the addition of the
  2689. # targets
  2690. if column_is_repeated:
  2691. _add_to_result_map = add_to_result_map
  2692. def add_to_result_map(keyname, name, objects, type_):
  2693. _add_to_result_map(keyname, name, (), type_)
  2694. # if we redefined col_expr for type expressions, wrap the
  2695. # callable with one that adds the original column to the targets
  2696. elif col_expr is not column:
  2697. _add_to_result_map = add_to_result_map
  2698. def add_to_result_map(keyname, name, objects, type_):
  2699. _add_to_result_map(
  2700. keyname, name, (column,) + objects, type_
  2701. )
  2702. else:
  2703. add_to_result_map = None
  2704. # this method is used by some of the dialects for RETURNING,
  2705. # which has different inputs. _label_returning_column was added
  2706. # as the better target for this now however for 1.4 we will keep
  2707. # _label_select_column directly compatible with this use case.
  2708. # these assertions right now set up the current expected inputs
  2709. assert within_columns_clause, (
  2710. "_label_select_column is only relevant within "
  2711. "the columns clause of a SELECT or RETURNING"
  2712. )
  2713. if isinstance(column, elements.Label):
  2714. if col_expr is not column:
  2715. result_expr = _CompileLabel(
  2716. col_expr, column.name, alt_names=(column.element,)
  2717. )
  2718. else:
  2719. result_expr = col_expr
  2720. elif name:
  2721. # here, _columns_plus_names has determined there's an explicit
  2722. # label name we need to use. this is the default for
  2723. # tablenames_plus_columnnames as well as when columns are being
  2724. # deduplicated on name
  2725. assert (
  2726. proxy_name is not None
  2727. ), "proxy_name is required if 'name' is passed"
  2728. result_expr = _CompileLabel(
  2729. col_expr,
  2730. name,
  2731. alt_names=(
  2732. proxy_name,
  2733. # this is a hack to allow legacy result column lookups
  2734. # to work as they did before; this goes away in 2.0.
  2735. # TODO: this only seems to be tested indirectly
  2736. # via test/orm/test_deprecations.py. should be a
  2737. # resultset test for this
  2738. column._tq_label,
  2739. ),
  2740. )
  2741. else:
  2742. # determine here whether this column should be rendered in
  2743. # a labelled context or not, as we were given no required label
  2744. # name from the caller. Here we apply heuristics based on the kind
  2745. # of SQL expression involved.
  2746. if col_expr is not column:
  2747. # type-specific expression wrapping the given column,
  2748. # so we render a label
  2749. render_with_label = True
  2750. elif isinstance(column, elements.ColumnClause):
  2751. # table-bound column, we render its name as a label if we are
  2752. # inside of a subquery only
  2753. render_with_label = (
  2754. asfrom
  2755. and not column.is_literal
  2756. and column.table is not None
  2757. )
  2758. elif isinstance(column, elements.TextClause):
  2759. render_with_label = False
  2760. elif isinstance(column, elements.UnaryExpression):
  2761. render_with_label = column.wraps_column_expression or asfrom
  2762. elif (
  2763. # general class of expressions that don't have a SQL-column
  2764. # addressible name. includes scalar selects, bind parameters,
  2765. # SQL functions, others
  2766. not isinstance(column, elements.NamedColumn)
  2767. # deeper check that indicates there's no natural "name" to
  2768. # this element, which accommodates for custom SQL constructs
  2769. # that might have a ".name" attribute (but aren't SQL
  2770. # functions) but are not implementing this more recently added
  2771. # base class. in theory the "NamedColumn" check should be
  2772. # enough, however here we seek to maintain legacy behaviors
  2773. # as well.
  2774. and column._non_anon_label is None
  2775. ):
  2776. render_with_label = True
  2777. else:
  2778. render_with_label = False
  2779. if render_with_label:
  2780. if not fallback_label_name:
  2781. # used by the RETURNING case right now. we generate it
  2782. # here as 3rd party dialects may be referring to
  2783. # _label_select_column method directly instead of the
  2784. # just-added _label_returning_column method
  2785. assert not column_is_repeated
  2786. fallback_label_name = column._anon_name_label
  2787. fallback_label_name = (
  2788. elements._truncated_label(fallback_label_name)
  2789. if not isinstance(
  2790. fallback_label_name, elements._truncated_label
  2791. )
  2792. else fallback_label_name
  2793. )
  2794. result_expr = _CompileLabel(
  2795. col_expr, fallback_label_name, alt_names=(proxy_name,)
  2796. )
  2797. else:
  2798. result_expr = col_expr
  2799. column_clause_args.update(
  2800. within_columns_clause=within_columns_clause,
  2801. add_to_result_map=add_to_result_map,
  2802. )
  2803. return result_expr._compiler_dispatch(self, **column_clause_args)
  2804. def format_from_hint_text(self, sqltext, table, hint, iscrud):
  2805. hinttext = self.get_from_hint_text(table, hint)
  2806. if hinttext:
  2807. sqltext += " " + hinttext
  2808. return sqltext
  2809. def get_select_hint_text(self, byfroms):
  2810. return None
  2811. def get_from_hint_text(self, table, text):
  2812. return None
  2813. def get_crud_hint_text(self, table, text):
  2814. return None
  2815. def get_statement_hint_text(self, hint_texts):
  2816. return " ".join(hint_texts)
  2817. _default_stack_entry = util.immutabledict(
  2818. [("correlate_froms", frozenset()), ("asfrom_froms", frozenset())]
  2819. )
  2820. def _display_froms_for_select(
  2821. self, select_stmt, asfrom, lateral=False, **kw
  2822. ):
  2823. # utility method to help external dialects
  2824. # get the correct from list for a select.
  2825. # specifically the oracle dialect needs this feature
  2826. # right now.
  2827. toplevel = not self.stack
  2828. entry = self._default_stack_entry if toplevel else self.stack[-1]
  2829. compile_state = select_stmt._compile_state_factory(select_stmt, self)
  2830. correlate_froms = entry["correlate_froms"]
  2831. asfrom_froms = entry["asfrom_froms"]
  2832. if asfrom and not lateral:
  2833. froms = compile_state._get_display_froms(
  2834. explicit_correlate_froms=correlate_froms.difference(
  2835. asfrom_froms
  2836. ),
  2837. implicit_correlate_froms=(),
  2838. )
  2839. else:
  2840. froms = compile_state._get_display_froms(
  2841. explicit_correlate_froms=correlate_froms,
  2842. implicit_correlate_froms=asfrom_froms,
  2843. )
  2844. return froms
  2845. translate_select_structure = None
  2846. """if not ``None``, should be a callable which accepts ``(select_stmt,
  2847. **kw)`` and returns a select object. this is used for structural changes
  2848. mostly to accommodate for LIMIT/OFFSET schemes
  2849. """
  2850. def visit_select(
  2851. self,
  2852. select_stmt,
  2853. asfrom=False,
  2854. insert_into=False,
  2855. fromhints=None,
  2856. compound_index=None,
  2857. select_wraps_for=None,
  2858. lateral=False,
  2859. from_linter=None,
  2860. **kwargs
  2861. ):
  2862. assert select_wraps_for is None, (
  2863. "SQLAlchemy 1.4 requires use of "
  2864. "the translate_select_structure hook for structural "
  2865. "translations of SELECT objects"
  2866. )
  2867. # initial setup of SELECT. the compile_state_factory may now
  2868. # be creating a totally different SELECT from the one that was
  2869. # passed in. for ORM use this will convert from an ORM-state
  2870. # SELECT to a regular "Core" SELECT. other composed operations
  2871. # such as computation of joins will be performed.
  2872. kwargs["within_columns_clause"] = False
  2873. compile_state = select_stmt._compile_state_factory(
  2874. select_stmt, self, **kwargs
  2875. )
  2876. select_stmt = compile_state.statement
  2877. toplevel = not self.stack
  2878. if toplevel and not self.compile_state:
  2879. self.compile_state = compile_state
  2880. is_embedded_select = compound_index is not None or insert_into
  2881. # translate step for Oracle, SQL Server which often need to
  2882. # restructure the SELECT to allow for LIMIT/OFFSET and possibly
  2883. # other conditions
  2884. if self.translate_select_structure:
  2885. new_select_stmt = self.translate_select_structure(
  2886. select_stmt, asfrom=asfrom, **kwargs
  2887. )
  2888. # if SELECT was restructured, maintain a link to the originals
  2889. # and assemble a new compile state
  2890. if new_select_stmt is not select_stmt:
  2891. compile_state_wraps_for = compile_state
  2892. select_wraps_for = select_stmt
  2893. select_stmt = new_select_stmt
  2894. compile_state = select_stmt._compile_state_factory(
  2895. select_stmt, self, **kwargs
  2896. )
  2897. select_stmt = compile_state.statement
  2898. entry = self._default_stack_entry if toplevel else self.stack[-1]
  2899. populate_result_map = need_column_expressions = (
  2900. toplevel
  2901. or entry.get("need_result_map_for_compound", False)
  2902. or entry.get("need_result_map_for_nested", False)
  2903. )
  2904. # indicates there is a CompoundSelect in play and we are not the
  2905. # first select
  2906. if compound_index:
  2907. populate_result_map = False
  2908. # this was first proposed as part of #3372; however, it is not
  2909. # reached in current tests and could possibly be an assertion
  2910. # instead.
  2911. if not populate_result_map and "add_to_result_map" in kwargs:
  2912. del kwargs["add_to_result_map"]
  2913. froms = self._setup_select_stack(
  2914. select_stmt, compile_state, entry, asfrom, lateral, compound_index
  2915. )
  2916. column_clause_args = kwargs.copy()
  2917. column_clause_args.update(
  2918. {"within_label_clause": False, "within_columns_clause": False}
  2919. )
  2920. text = "SELECT " # we're off to a good start !
  2921. if select_stmt._hints:
  2922. hint_text, byfrom = self._setup_select_hints(select_stmt)
  2923. if hint_text:
  2924. text += hint_text + " "
  2925. else:
  2926. byfrom = None
  2927. if select_stmt._independent_ctes:
  2928. for cte in select_stmt._independent_ctes:
  2929. cte._compiler_dispatch(self, **kwargs)
  2930. if select_stmt._prefixes:
  2931. text += self._generate_prefixes(
  2932. select_stmt, select_stmt._prefixes, **kwargs
  2933. )
  2934. text += self.get_select_precolumns(select_stmt, **kwargs)
  2935. # the actual list of columns to print in the SELECT column list.
  2936. inner_columns = [
  2937. c
  2938. for c in [
  2939. self._label_select_column(
  2940. select_stmt,
  2941. column,
  2942. populate_result_map,
  2943. asfrom,
  2944. column_clause_args,
  2945. name=name,
  2946. proxy_name=proxy_name,
  2947. fallback_label_name=fallback_label_name,
  2948. column_is_repeated=repeated,
  2949. need_column_expressions=need_column_expressions,
  2950. )
  2951. for (
  2952. name,
  2953. proxy_name,
  2954. fallback_label_name,
  2955. column,
  2956. repeated,
  2957. ) in compile_state.columns_plus_names
  2958. ]
  2959. if c is not None
  2960. ]
  2961. if populate_result_map and select_wraps_for is not None:
  2962. # if this select was generated from translate_select,
  2963. # rewrite the targeted columns in the result map
  2964. translate = dict(
  2965. zip(
  2966. [
  2967. name
  2968. for (
  2969. key,
  2970. proxy_name,
  2971. fallback_label_name,
  2972. name,
  2973. repeated,
  2974. ) in compile_state.columns_plus_names
  2975. ],
  2976. [
  2977. name
  2978. for (
  2979. key,
  2980. proxy_name,
  2981. fallback_label_name,
  2982. name,
  2983. repeated,
  2984. ) in compile_state_wraps_for.columns_plus_names
  2985. ],
  2986. )
  2987. )
  2988. self._result_columns = [
  2989. (key, name, tuple(translate.get(o, o) for o in obj), type_)
  2990. for key, name, obj, type_ in self._result_columns
  2991. ]
  2992. text = self._compose_select_body(
  2993. text,
  2994. select_stmt,
  2995. compile_state,
  2996. inner_columns,
  2997. froms,
  2998. byfrom,
  2999. toplevel,
  3000. kwargs,
  3001. )
  3002. if select_stmt._statement_hints:
  3003. per_dialect = [
  3004. ht
  3005. for (dialect_name, ht) in select_stmt._statement_hints
  3006. if dialect_name in ("*", self.dialect.name)
  3007. ]
  3008. if per_dialect:
  3009. text += " " + self.get_statement_hint_text(per_dialect)
  3010. # In compound query, CTEs are shared at the compound level
  3011. if self.ctes and (not is_embedded_select or toplevel):
  3012. nesting_level = len(self.stack) if not toplevel else None
  3013. text = (
  3014. self._render_cte_clause(
  3015. nesting_level=nesting_level,
  3016. visiting_cte=kwargs.get("visiting_cte"),
  3017. )
  3018. + text
  3019. )
  3020. if select_stmt._suffixes:
  3021. text += " " + self._generate_prefixes(
  3022. select_stmt, select_stmt._suffixes, **kwargs
  3023. )
  3024. self.stack.pop(-1)
  3025. return text
  3026. def _setup_select_hints(self, select):
  3027. byfrom = dict(
  3028. [
  3029. (
  3030. from_,
  3031. hinttext
  3032. % {"name": from_._compiler_dispatch(self, ashint=True)},
  3033. )
  3034. for (from_, dialect), hinttext in select._hints.items()
  3035. if dialect in ("*", self.dialect.name)
  3036. ]
  3037. )
  3038. hint_text = self.get_select_hint_text(byfrom)
  3039. return hint_text, byfrom
  3040. def _setup_select_stack(
  3041. self, select, compile_state, entry, asfrom, lateral, compound_index
  3042. ):
  3043. correlate_froms = entry["correlate_froms"]
  3044. asfrom_froms = entry["asfrom_froms"]
  3045. if compound_index == 0:
  3046. entry["select_0"] = select
  3047. elif compound_index:
  3048. select_0 = entry["select_0"]
  3049. numcols = len(select_0._all_selected_columns)
  3050. if len(compile_state.columns_plus_names) != numcols:
  3051. raise exc.CompileError(
  3052. "All selectables passed to "
  3053. "CompoundSelect must have identical numbers of "
  3054. "columns; select #%d has %d columns, select "
  3055. "#%d has %d"
  3056. % (
  3057. 1,
  3058. numcols,
  3059. compound_index + 1,
  3060. len(select._all_selected_columns),
  3061. )
  3062. )
  3063. if asfrom and not lateral:
  3064. froms = compile_state._get_display_froms(
  3065. explicit_correlate_froms=correlate_froms.difference(
  3066. asfrom_froms
  3067. ),
  3068. implicit_correlate_froms=(),
  3069. )
  3070. else:
  3071. froms = compile_state._get_display_froms(
  3072. explicit_correlate_froms=correlate_froms,
  3073. implicit_correlate_froms=asfrom_froms,
  3074. )
  3075. new_correlate_froms = set(selectable._from_objects(*froms))
  3076. all_correlate_froms = new_correlate_froms.union(correlate_froms)
  3077. new_entry = {
  3078. "asfrom_froms": new_correlate_froms,
  3079. "correlate_froms": all_correlate_froms,
  3080. "selectable": select,
  3081. "compile_state": compile_state,
  3082. }
  3083. self.stack.append(new_entry)
  3084. return froms
  3085. def _compose_select_body(
  3086. self,
  3087. text,
  3088. select,
  3089. compile_state,
  3090. inner_columns,
  3091. froms,
  3092. byfrom,
  3093. toplevel,
  3094. kwargs,
  3095. ):
  3096. text += ", ".join(inner_columns)
  3097. if self.linting & COLLECT_CARTESIAN_PRODUCTS:
  3098. from_linter = FromLinter({}, set())
  3099. warn_linting = self.linting & WARN_LINTING
  3100. if toplevel:
  3101. self.from_linter = from_linter
  3102. else:
  3103. from_linter = None
  3104. warn_linting = False
  3105. if froms:
  3106. text += " \nFROM "
  3107. if select._hints:
  3108. text += ", ".join(
  3109. [
  3110. f._compiler_dispatch(
  3111. self,
  3112. asfrom=True,
  3113. fromhints=byfrom,
  3114. from_linter=from_linter,
  3115. **kwargs
  3116. )
  3117. for f in froms
  3118. ]
  3119. )
  3120. else:
  3121. text += ", ".join(
  3122. [
  3123. f._compiler_dispatch(
  3124. self,
  3125. asfrom=True,
  3126. from_linter=from_linter,
  3127. **kwargs
  3128. )
  3129. for f in froms
  3130. ]
  3131. )
  3132. else:
  3133. text += self.default_from()
  3134. if select._where_criteria:
  3135. t = self._generate_delimited_and_list(
  3136. select._where_criteria, from_linter=from_linter, **kwargs
  3137. )
  3138. if t:
  3139. text += " \nWHERE " + t
  3140. if warn_linting:
  3141. from_linter.warn()
  3142. if select._group_by_clauses:
  3143. text += self.group_by_clause(select, **kwargs)
  3144. if select._having_criteria:
  3145. t = self._generate_delimited_and_list(
  3146. select._having_criteria, **kwargs
  3147. )
  3148. if t:
  3149. text += " \nHAVING " + t
  3150. if select._order_by_clauses:
  3151. text += self.order_by_clause(select, **kwargs)
  3152. if select._has_row_limiting_clause:
  3153. text += self._row_limit_clause(select, **kwargs)
  3154. if select._for_update_arg is not None:
  3155. text += self.for_update_clause(select, **kwargs)
  3156. return text
  3157. def _generate_prefixes(self, stmt, prefixes, **kw):
  3158. clause = " ".join(
  3159. prefix._compiler_dispatch(self, **kw)
  3160. for prefix, dialect_name in prefixes
  3161. if dialect_name is None or dialect_name == self.dialect.name
  3162. )
  3163. if clause:
  3164. clause += " "
  3165. return clause
  3166. def _render_cte_clause(
  3167. self,
  3168. nesting_level=None,
  3169. include_following_stack=False,
  3170. visiting_cte=None,
  3171. ):
  3172. """
  3173. include_following_stack
  3174. Also render the nesting CTEs on the next stack. Useful for
  3175. SQL structures like UNION or INSERT that can wrap SELECT
  3176. statements containing nesting CTEs.
  3177. """
  3178. if not self.ctes:
  3179. return ""
  3180. if nesting_level and nesting_level > 1:
  3181. ctes = util.OrderedDict()
  3182. for cte in list(self.ctes.keys()):
  3183. cte_level, cte_name = self.level_name_by_cte[
  3184. cte._get_reference_cte()
  3185. ]
  3186. is_rendered_level = cte_level == nesting_level or (
  3187. include_following_stack and cte_level == nesting_level + 1
  3188. )
  3189. if not (cte.nesting and is_rendered_level):
  3190. continue
  3191. ctes[cte] = self.ctes[cte]
  3192. else:
  3193. ctes = self.ctes
  3194. if not ctes:
  3195. return ""
  3196. ctes_recursive = any([cte.recursive for cte in ctes])
  3197. if self.positional:
  3198. self.cte_order[visiting_cte].extend(ctes)
  3199. if visiting_cte is None and self.cte_order:
  3200. assert self.positiontup is not None
  3201. def get_nested_positional(cte):
  3202. if cte in self.cte_order:
  3203. children = self.cte_order.pop(cte)
  3204. to_add = list(
  3205. itertools.chain.from_iterable(
  3206. get_nested_positional(child_cte)
  3207. for child_cte in children
  3208. )
  3209. )
  3210. if cte in self.cte_positional:
  3211. return reorder_positional(
  3212. self.cte_positional[cte],
  3213. to_add,
  3214. self.cte_level[children[0]],
  3215. )
  3216. else:
  3217. return to_add
  3218. else:
  3219. return self.cte_positional.get(cte, [])
  3220. def reorder_positional(pos, to_add, level):
  3221. if not level:
  3222. return to_add + pos
  3223. index = 0
  3224. for index, name in enumerate(reversed(pos)):
  3225. if self.positiontup_level[name] < level: # type: ignore[index] # noqa: E501
  3226. break
  3227. return pos[:-index] + to_add + pos[-index:]
  3228. to_add = get_nested_positional(None)
  3229. self.positiontup = reorder_positional(
  3230. self.positiontup, to_add, nesting_level
  3231. )
  3232. cte_text = self.get_cte_preamble(ctes_recursive) + " "
  3233. cte_text += ", \n".join([txt for txt in ctes.values()])
  3234. cte_text += "\n "
  3235. if nesting_level and nesting_level > 1:
  3236. for cte in list(ctes.keys()):
  3237. cte_level, cte_name = self.level_name_by_cte[
  3238. cte._get_reference_cte()
  3239. ]
  3240. del self.ctes[cte]
  3241. del self.ctes_by_level_name[(cte_level, cte_name)]
  3242. del self.level_name_by_cte[cte._get_reference_cte()]
  3243. return cte_text
  3244. def get_cte_preamble(self, recursive):
  3245. if recursive:
  3246. return "WITH RECURSIVE"
  3247. else:
  3248. return "WITH"
  3249. def get_select_precolumns(self, select, **kw):
  3250. """Called when building a ``SELECT`` statement, position is just
  3251. before column list.
  3252. """
  3253. if select._distinct_on:
  3254. util.warn_deprecated(
  3255. "DISTINCT ON is currently supported only by the PostgreSQL "
  3256. "dialect. Use of DISTINCT ON for other backends is currently "
  3257. "silently ignored, however this usage is deprecated, and will "
  3258. "raise CompileError in a future release for all backends "
  3259. "that do not support this syntax.",
  3260. version="1.4",
  3261. )
  3262. return "DISTINCT " if select._distinct else ""
  3263. def group_by_clause(self, select, **kw):
  3264. """allow dialects to customize how GROUP BY is rendered."""
  3265. group_by = self._generate_delimited_list(
  3266. select._group_by_clauses, OPERATORS[operators.comma_op], **kw
  3267. )
  3268. if group_by:
  3269. return " GROUP BY " + group_by
  3270. else:
  3271. return ""
  3272. def order_by_clause(self, select, **kw):
  3273. """allow dialects to customize how ORDER BY is rendered."""
  3274. order_by = self._generate_delimited_list(
  3275. select._order_by_clauses, OPERATORS[operators.comma_op], **kw
  3276. )
  3277. if order_by:
  3278. return " ORDER BY " + order_by
  3279. else:
  3280. return ""
  3281. def for_update_clause(self, select, **kw):
  3282. return " FOR UPDATE"
  3283. def returning_clause(self, stmt, returning_cols):
  3284. raise exc.CompileError(
  3285. "RETURNING is not supported by this "
  3286. "dialect's statement compiler."
  3287. )
  3288. def limit_clause(self, select, **kw):
  3289. text = ""
  3290. if select._limit_clause is not None:
  3291. text += "\n LIMIT " + self.process(select._limit_clause, **kw)
  3292. if select._offset_clause is not None:
  3293. if select._limit_clause is None:
  3294. text += "\n LIMIT -1"
  3295. text += " OFFSET " + self.process(select._offset_clause, **kw)
  3296. return text
  3297. def fetch_clause(self, select, **kw):
  3298. text = ""
  3299. if select._offset_clause is not None:
  3300. text += "\n OFFSET %s ROWS" % self.process(
  3301. select._offset_clause, **kw
  3302. )
  3303. if select._fetch_clause is not None:
  3304. text += "\n FETCH FIRST %s%s ROWS %s" % (
  3305. self.process(select._fetch_clause, **kw),
  3306. " PERCENT" if select._fetch_clause_options["percent"] else "",
  3307. "WITH TIES"
  3308. if select._fetch_clause_options["with_ties"]
  3309. else "ONLY",
  3310. )
  3311. return text
  3312. def visit_table(
  3313. self,
  3314. table,
  3315. asfrom=False,
  3316. iscrud=False,
  3317. ashint=False,
  3318. fromhints=None,
  3319. use_schema=True,
  3320. from_linter=None,
  3321. **kwargs
  3322. ):
  3323. if from_linter:
  3324. from_linter.froms[table] = table.fullname
  3325. if asfrom or ashint:
  3326. effective_schema = self.preparer.schema_for_object(table)
  3327. if use_schema and effective_schema:
  3328. ret = (
  3329. self.preparer.quote_schema(effective_schema)
  3330. + "."
  3331. + self.preparer.quote(table.name)
  3332. )
  3333. else:
  3334. ret = self.preparer.quote(table.name)
  3335. if fromhints and table in fromhints:
  3336. ret = self.format_from_hint_text(
  3337. ret, table, fromhints[table], iscrud
  3338. )
  3339. return ret
  3340. else:
  3341. return ""
  3342. def visit_join(self, join, asfrom=False, from_linter=None, **kwargs):
  3343. if from_linter:
  3344. from_linter.edges.update(
  3345. itertools.product(
  3346. join.left._from_objects, join.right._from_objects
  3347. )
  3348. )
  3349. if join.full:
  3350. join_type = " FULL OUTER JOIN "
  3351. elif join.isouter:
  3352. join_type = " LEFT OUTER JOIN "
  3353. else:
  3354. join_type = " JOIN "
  3355. return (
  3356. join.left._compiler_dispatch(
  3357. self, asfrom=True, from_linter=from_linter, **kwargs
  3358. )
  3359. + join_type
  3360. + join.right._compiler_dispatch(
  3361. self, asfrom=True, from_linter=from_linter, **kwargs
  3362. )
  3363. + " ON "
  3364. # TODO: likely need asfrom=True here?
  3365. + join.onclause._compiler_dispatch(
  3366. self, from_linter=from_linter, **kwargs
  3367. )
  3368. )
  3369. def _setup_crud_hints(self, stmt, table_text):
  3370. dialect_hints = dict(
  3371. [
  3372. (table, hint_text)
  3373. for (table, dialect), hint_text in stmt._hints.items()
  3374. if dialect in ("*", self.dialect.name)
  3375. ]
  3376. )
  3377. if stmt.table in dialect_hints:
  3378. table_text = self.format_from_hint_text(
  3379. table_text, stmt.table, dialect_hints[stmt.table], True
  3380. )
  3381. return dialect_hints, table_text
  3382. def visit_insert(self, insert_stmt, **kw):
  3383. compile_state = insert_stmt._compile_state_factory(
  3384. insert_stmt, self, **kw
  3385. )
  3386. insert_stmt = compile_state.statement
  3387. toplevel = not self.stack
  3388. if toplevel:
  3389. self.isinsert = True
  3390. if not self.dml_compile_state:
  3391. self.dml_compile_state = compile_state
  3392. if not self.compile_state:
  3393. self.compile_state = compile_state
  3394. self.stack.append(
  3395. {
  3396. "correlate_froms": set(),
  3397. "asfrom_froms": set(),
  3398. "selectable": insert_stmt,
  3399. }
  3400. )
  3401. crud_params = crud._get_crud_params(
  3402. self, insert_stmt, compile_state, **kw
  3403. )
  3404. if (
  3405. not crud_params
  3406. and not self.dialect.supports_default_values
  3407. and not self.dialect.supports_default_metavalue
  3408. and not self.dialect.supports_empty_insert
  3409. ):
  3410. raise exc.CompileError(
  3411. "The '%s' dialect with current database "
  3412. "version settings does not support empty "
  3413. "inserts." % self.dialect.name
  3414. )
  3415. if compile_state._has_multi_parameters:
  3416. if not self.dialect.supports_multivalues_insert:
  3417. raise exc.CompileError(
  3418. "The '%s' dialect with current database "
  3419. "version settings does not support "
  3420. "in-place multirow inserts." % self.dialect.name
  3421. )
  3422. crud_params_single = crud_params[0]
  3423. else:
  3424. crud_params_single = crud_params
  3425. preparer = self.preparer
  3426. supports_default_values = self.dialect.supports_default_values
  3427. text = "INSERT "
  3428. if insert_stmt._prefixes:
  3429. text += self._generate_prefixes(
  3430. insert_stmt, insert_stmt._prefixes, **kw
  3431. )
  3432. text += "INTO "
  3433. table_text = preparer.format_table(insert_stmt.table)
  3434. if insert_stmt._hints:
  3435. _, table_text = self._setup_crud_hints(insert_stmt, table_text)
  3436. if insert_stmt._independent_ctes:
  3437. for cte in insert_stmt._independent_ctes:
  3438. cte._compiler_dispatch(self, **kw)
  3439. text += table_text
  3440. if crud_params_single or not supports_default_values:
  3441. text += " (%s)" % ", ".join(
  3442. [expr for c, expr, value in crud_params_single]
  3443. )
  3444. if self.returning or insert_stmt._returning:
  3445. returning_clause = self.returning_clause(
  3446. insert_stmt, self.returning or insert_stmt._returning
  3447. )
  3448. if self.returning_precedes_values:
  3449. text += " " + returning_clause
  3450. else:
  3451. returning_clause = None
  3452. if insert_stmt.select is not None:
  3453. # placed here by crud.py
  3454. select_text = self.process(
  3455. self.stack[-1]["insert_from_select"], insert_into=True, **kw
  3456. )
  3457. if self.ctes and self.dialect.cte_follows_insert:
  3458. nesting_level = len(self.stack) if not toplevel else None
  3459. text += " %s%s" % (
  3460. self._render_cte_clause(
  3461. nesting_level=nesting_level,
  3462. include_following_stack=True,
  3463. visiting_cte=kw.get("visiting_cte"),
  3464. ),
  3465. select_text,
  3466. )
  3467. else:
  3468. text += " %s" % select_text
  3469. elif not crud_params and supports_default_values:
  3470. text += " DEFAULT VALUES"
  3471. elif compile_state._has_multi_parameters:
  3472. text += " VALUES %s" % (
  3473. ", ".join(
  3474. "(%s)"
  3475. % (", ".join(value for c, expr, value in crud_param_set))
  3476. for crud_param_set in crud_params
  3477. )
  3478. )
  3479. else:
  3480. insert_single_values_expr = ", ".join(
  3481. [value for c, expr, value in crud_params]
  3482. )
  3483. text += " VALUES (%s)" % insert_single_values_expr
  3484. if toplevel:
  3485. self.insert_single_values_expr = insert_single_values_expr
  3486. if insert_stmt._post_values_clause is not None:
  3487. post_values_clause = self.process(
  3488. insert_stmt._post_values_clause, **kw
  3489. )
  3490. if post_values_clause:
  3491. text += " " + post_values_clause
  3492. if returning_clause and not self.returning_precedes_values:
  3493. text += " " + returning_clause
  3494. if self.ctes and not self.dialect.cte_follows_insert:
  3495. nesting_level = len(self.stack) if not toplevel else None
  3496. text = (
  3497. self._render_cte_clause(
  3498. nesting_level=nesting_level,
  3499. include_following_stack=True,
  3500. visiting_cte=kw.get("visiting_cte"),
  3501. )
  3502. + text
  3503. )
  3504. self.stack.pop(-1)
  3505. return text
  3506. def update_limit_clause(self, update_stmt):
  3507. """Provide a hook for MySQL to add LIMIT to the UPDATE"""
  3508. return None
  3509. def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw):
  3510. """Provide a hook to override the initial table clause
  3511. in an UPDATE statement.
  3512. MySQL overrides this.
  3513. """
  3514. kw["asfrom"] = True
  3515. return from_table._compiler_dispatch(self, iscrud=True, **kw)
  3516. def update_from_clause(
  3517. self, update_stmt, from_table, extra_froms, from_hints, **kw
  3518. ):
  3519. """Provide a hook to override the generation of an
  3520. UPDATE..FROM clause.
  3521. MySQL and MSSQL override this.
  3522. """
  3523. raise NotImplementedError(
  3524. "This backend does not support multiple-table "
  3525. "criteria within UPDATE"
  3526. )
  3527. def visit_update(self, update_stmt, **kw):
  3528. compile_state = update_stmt._compile_state_factory(
  3529. update_stmt, self, **kw
  3530. )
  3531. update_stmt = compile_state.statement
  3532. toplevel = not self.stack
  3533. if toplevel:
  3534. self.isupdate = True
  3535. if not self.dml_compile_state:
  3536. self.dml_compile_state = compile_state
  3537. if not self.compile_state:
  3538. self.compile_state = compile_state
  3539. extra_froms = compile_state._extra_froms
  3540. is_multitable = bool(extra_froms)
  3541. if is_multitable:
  3542. # main table might be a JOIN
  3543. main_froms = set(selectable._from_objects(update_stmt.table))
  3544. render_extra_froms = [
  3545. f for f in extra_froms if f not in main_froms
  3546. ]
  3547. correlate_froms = main_froms.union(extra_froms)
  3548. else:
  3549. render_extra_froms = []
  3550. correlate_froms = {update_stmt.table}
  3551. self.stack.append(
  3552. {
  3553. "correlate_froms": correlate_froms,
  3554. "asfrom_froms": correlate_froms,
  3555. "selectable": update_stmt,
  3556. }
  3557. )
  3558. text = "UPDATE "
  3559. if update_stmt._prefixes:
  3560. text += self._generate_prefixes(
  3561. update_stmt, update_stmt._prefixes, **kw
  3562. )
  3563. table_text = self.update_tables_clause(
  3564. update_stmt, update_stmt.table, render_extra_froms, **kw
  3565. )
  3566. crud_params = crud._get_crud_params(
  3567. self, update_stmt, compile_state, **kw
  3568. )
  3569. if update_stmt._hints:
  3570. dialect_hints, table_text = self._setup_crud_hints(
  3571. update_stmt, table_text
  3572. )
  3573. else:
  3574. dialect_hints = None
  3575. if update_stmt._independent_ctes:
  3576. for cte in update_stmt._independent_ctes:
  3577. cte._compiler_dispatch(self, **kw)
  3578. text += table_text
  3579. text += " SET "
  3580. text += ", ".join(expr + "=" + value for c, expr, value in crud_params)
  3581. if self.returning or update_stmt._returning:
  3582. if self.returning_precedes_values:
  3583. text += " " + self.returning_clause(
  3584. update_stmt, self.returning or update_stmt._returning
  3585. )
  3586. if extra_froms:
  3587. extra_from_text = self.update_from_clause(
  3588. update_stmt,
  3589. update_stmt.table,
  3590. render_extra_froms,
  3591. dialect_hints,
  3592. **kw
  3593. )
  3594. if extra_from_text:
  3595. text += " " + extra_from_text
  3596. if update_stmt._where_criteria:
  3597. t = self._generate_delimited_and_list(
  3598. update_stmt._where_criteria, **kw
  3599. )
  3600. if t:
  3601. text += " WHERE " + t
  3602. limit_clause = self.update_limit_clause(update_stmt)
  3603. if limit_clause:
  3604. text += " " + limit_clause
  3605. if (
  3606. self.returning or update_stmt._returning
  3607. ) and not self.returning_precedes_values:
  3608. text += " " + self.returning_clause(
  3609. update_stmt, self.returning or update_stmt._returning
  3610. )
  3611. if self.ctes:
  3612. nesting_level = len(self.stack) if not toplevel else None
  3613. text = (
  3614. self._render_cte_clause(
  3615. nesting_level=nesting_level,
  3616. visiting_cte=kw.get("visiting_cte"),
  3617. )
  3618. + text
  3619. )
  3620. self.stack.pop(-1)
  3621. return text
  3622. def delete_extra_from_clause(
  3623. self, update_stmt, from_table, extra_froms, from_hints, **kw
  3624. ):
  3625. """Provide a hook to override the generation of an
  3626. DELETE..FROM clause.
  3627. This can be used to implement DELETE..USING for example.
  3628. MySQL and MSSQL override this.
  3629. """
  3630. raise NotImplementedError(
  3631. "This backend does not support multiple-table "
  3632. "criteria within DELETE"
  3633. )
  3634. def delete_table_clause(self, delete_stmt, from_table, extra_froms):
  3635. return from_table._compiler_dispatch(self, asfrom=True, iscrud=True)
  3636. def visit_delete(self, delete_stmt, **kw):
  3637. compile_state = delete_stmt._compile_state_factory(
  3638. delete_stmt, self, **kw
  3639. )
  3640. delete_stmt = compile_state.statement
  3641. toplevel = not self.stack
  3642. if toplevel:
  3643. self.isdelete = True
  3644. if not self.dml_compile_state:
  3645. self.dml_compile_state = compile_state
  3646. if not self.compile_state:
  3647. self.compile_state = compile_state
  3648. extra_froms = compile_state._extra_froms
  3649. correlate_froms = {delete_stmt.table}.union(extra_froms)
  3650. self.stack.append(
  3651. {
  3652. "correlate_froms": correlate_froms,
  3653. "asfrom_froms": correlate_froms,
  3654. "selectable": delete_stmt,
  3655. }
  3656. )
  3657. text = "DELETE "
  3658. if delete_stmt._prefixes:
  3659. text += self._generate_prefixes(
  3660. delete_stmt, delete_stmt._prefixes, **kw
  3661. )
  3662. text += "FROM "
  3663. table_text = self.delete_table_clause(
  3664. delete_stmt, delete_stmt.table, extra_froms
  3665. )
  3666. if delete_stmt._hints:
  3667. dialect_hints, table_text = self._setup_crud_hints(
  3668. delete_stmt, table_text
  3669. )
  3670. else:
  3671. dialect_hints = None
  3672. if delete_stmt._independent_ctes:
  3673. for cte in delete_stmt._independent_ctes:
  3674. cte._compiler_dispatch(self, **kw)
  3675. text += table_text
  3676. if delete_stmt._returning:
  3677. if self.returning_precedes_values:
  3678. text += " " + self.returning_clause(
  3679. delete_stmt, delete_stmt._returning
  3680. )
  3681. if extra_froms:
  3682. extra_from_text = self.delete_extra_from_clause(
  3683. delete_stmt,
  3684. delete_stmt.table,
  3685. extra_froms,
  3686. dialect_hints,
  3687. **kw
  3688. )
  3689. if extra_from_text:
  3690. text += " " + extra_from_text
  3691. if delete_stmt._where_criteria:
  3692. t = self._generate_delimited_and_list(
  3693. delete_stmt._where_criteria, **kw
  3694. )
  3695. if t:
  3696. text += " WHERE " + t
  3697. if delete_stmt._returning and not self.returning_precedes_values:
  3698. text += " " + self.returning_clause(
  3699. delete_stmt, delete_stmt._returning
  3700. )
  3701. if self.ctes:
  3702. nesting_level = len(self.stack) if not toplevel else None
  3703. text = (
  3704. self._render_cte_clause(
  3705. nesting_level=nesting_level,
  3706. visiting_cte=kw.get("visiting_cte"),
  3707. )
  3708. + text
  3709. )
  3710. self.stack.pop(-1)
  3711. return text
  3712. def visit_savepoint(self, savepoint_stmt):
  3713. return "SAVEPOINT %s" % self.preparer.format_savepoint(savepoint_stmt)
  3714. def visit_rollback_to_savepoint(self, savepoint_stmt):
  3715. return "ROLLBACK TO SAVEPOINT %s" % self.preparer.format_savepoint(
  3716. savepoint_stmt
  3717. )
  3718. def visit_release_savepoint(self, savepoint_stmt):
  3719. return "RELEASE SAVEPOINT %s" % self.preparer.format_savepoint(
  3720. savepoint_stmt
  3721. )
  3722. class StrSQLCompiler(SQLCompiler):
  3723. """A :class:`.SQLCompiler` subclass which allows a small selection
  3724. of non-standard SQL features to render into a string value.
  3725. The :class:`.StrSQLCompiler` is invoked whenever a Core expression
  3726. element is directly stringified without calling upon the
  3727. :meth:`_expression.ClauseElement.compile` method.
  3728. It can render a limited set
  3729. of non-standard SQL constructs to assist in basic stringification,
  3730. however for more substantial custom or dialect-specific SQL constructs,
  3731. it will be necessary to make use of
  3732. :meth:`_expression.ClauseElement.compile`
  3733. directly.
  3734. .. seealso::
  3735. :ref:`faq_sql_expression_string`
  3736. """
  3737. def _fallback_column_name(self, column):
  3738. return "<name unknown>"
  3739. @util.preload_module("sqlalchemy.engine.url")
  3740. def visit_unsupported_compilation(self, element, err, **kw):
  3741. if element.stringify_dialect != "default":
  3742. url = util.preloaded.engine_url
  3743. dialect = url.URL.create(element.stringify_dialect).get_dialect()()
  3744. compiler = dialect.statement_compiler(dialect, None)
  3745. if not isinstance(compiler, StrSQLCompiler):
  3746. return compiler.process(element)
  3747. return super(StrSQLCompiler, self).visit_unsupported_compilation(
  3748. element, err
  3749. )
  3750. def visit_getitem_binary(self, binary, operator, **kw):
  3751. return "%s[%s]" % (
  3752. self.process(binary.left, **kw),
  3753. self.process(binary.right, **kw),
  3754. )
  3755. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  3756. return self.visit_getitem_binary(binary, operator, **kw)
  3757. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  3758. return self.visit_getitem_binary(binary, operator, **kw)
  3759. def visit_sequence(self, seq, **kw):
  3760. return "<next sequence value: %s>" % self.preparer.format_sequence(seq)
  3761. def returning_clause(self, stmt, returning_cols):
  3762. columns = [
  3763. self._label_select_column(
  3764. None, c, True, False, {}, fallback_label_name=c._non_anon_label
  3765. )
  3766. for c in base._select_iterables(returning_cols)
  3767. ]
  3768. return "RETURNING " + ", ".join(columns)
  3769. def update_from_clause(
  3770. self, update_stmt, from_table, extra_froms, from_hints, **kw
  3771. ):
  3772. kw["asfrom"] = True
  3773. return "FROM " + ", ".join(
  3774. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  3775. for t in extra_froms
  3776. )
  3777. def delete_extra_from_clause(
  3778. self, update_stmt, from_table, extra_froms, from_hints, **kw
  3779. ):
  3780. kw["asfrom"] = True
  3781. return ", " + ", ".join(
  3782. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  3783. for t in extra_froms
  3784. )
  3785. def visit_empty_set_expr(self, type_):
  3786. return "SELECT 1 WHERE 1!=1"
  3787. def get_from_hint_text(self, table, text):
  3788. return "[%s]" % text
  3789. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  3790. return self._generate_generic_binary(binary, " <regexp> ", **kw)
  3791. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  3792. return self._generate_generic_binary(binary, " <not regexp> ", **kw)
  3793. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  3794. return "<regexp replace>(%s, %s)" % (
  3795. binary.left._compiler_dispatch(self, **kw),
  3796. binary.right._compiler_dispatch(self, **kw),
  3797. )
  3798. class DDLCompiler(Compiled):
  3799. @util.memoized_property
  3800. def sql_compiler(self):
  3801. return self.dialect.statement_compiler(
  3802. self.dialect, None, schema_translate_map=self.schema_translate_map
  3803. )
  3804. @util.memoized_property
  3805. def type_compiler(self):
  3806. return self.dialect.type_compiler
  3807. def construct_params(
  3808. self, params=None, extracted_parameters=None, escape_names=True
  3809. ):
  3810. return None
  3811. def visit_ddl(self, ddl, **kwargs):
  3812. # table events can substitute table and schema name
  3813. context = ddl.context
  3814. if isinstance(ddl.target, schema.Table):
  3815. context = context.copy()
  3816. preparer = self.preparer
  3817. path = preparer.format_table_seq(ddl.target)
  3818. if len(path) == 1:
  3819. table, sch = path[0], ""
  3820. else:
  3821. table, sch = path[-1], path[0]
  3822. context.setdefault("table", table)
  3823. context.setdefault("schema", sch)
  3824. context.setdefault("fullname", preparer.format_table(ddl.target))
  3825. return self.sql_compiler.post_process_text(ddl.statement % context)
  3826. def visit_create_schema(self, create, **kw):
  3827. schema = self.preparer.format_schema(create.element)
  3828. return "CREATE SCHEMA " + schema
  3829. def visit_drop_schema(self, drop, **kw):
  3830. schema = self.preparer.format_schema(drop.element)
  3831. text = "DROP SCHEMA " + schema
  3832. if drop.cascade:
  3833. text += " CASCADE"
  3834. return text
  3835. def visit_create_table(self, create, **kw):
  3836. table = create.element
  3837. preparer = self.preparer
  3838. text = "\nCREATE "
  3839. if table._prefixes:
  3840. text += " ".join(table._prefixes) + " "
  3841. text += "TABLE "
  3842. if create.if_not_exists:
  3843. text += "IF NOT EXISTS "
  3844. text += preparer.format_table(table) + " "
  3845. create_table_suffix = self.create_table_suffix(table)
  3846. if create_table_suffix:
  3847. text += create_table_suffix + " "
  3848. text += "("
  3849. separator = "\n"
  3850. # if only one primary key, specify it along with the column
  3851. first_pk = False
  3852. for create_column in create.columns:
  3853. column = create_column.element
  3854. try:
  3855. processed = self.process(
  3856. create_column, first_pk=column.primary_key and not first_pk
  3857. )
  3858. if processed is not None:
  3859. text += separator
  3860. separator = ", \n"
  3861. text += "\t" + processed
  3862. if column.primary_key:
  3863. first_pk = True
  3864. except exc.CompileError as ce:
  3865. util.raise_(
  3866. exc.CompileError(
  3867. util.u("(in table '%s', column '%s'): %s")
  3868. % (table.description, column.name, ce.args[0])
  3869. ),
  3870. from_=ce,
  3871. )
  3872. const = self.create_table_constraints(
  3873. table,
  3874. _include_foreign_key_constraints=create.include_foreign_key_constraints, # noqa
  3875. )
  3876. if const:
  3877. text += separator + "\t" + const
  3878. text += "\n)%s\n\n" % self.post_create_table(table)
  3879. return text
  3880. def visit_create_column(self, create, first_pk=False, **kw):
  3881. column = create.element
  3882. if column.system:
  3883. return None
  3884. text = self.get_column_specification(column, first_pk=first_pk)
  3885. const = " ".join(
  3886. self.process(constraint) for constraint in column.constraints
  3887. )
  3888. if const:
  3889. text += " " + const
  3890. return text
  3891. def create_table_constraints(
  3892. self, table, _include_foreign_key_constraints=None, **kw
  3893. ):
  3894. # On some DB order is significant: visit PK first, then the
  3895. # other constraints (engine.ReflectionTest.testbasic failed on FB2)
  3896. constraints = []
  3897. if table.primary_key:
  3898. constraints.append(table.primary_key)
  3899. all_fkcs = table.foreign_key_constraints
  3900. if _include_foreign_key_constraints is not None:
  3901. omit_fkcs = all_fkcs.difference(_include_foreign_key_constraints)
  3902. else:
  3903. omit_fkcs = set()
  3904. constraints.extend(
  3905. [
  3906. c
  3907. for c in table._sorted_constraints
  3908. if c is not table.primary_key and c not in omit_fkcs
  3909. ]
  3910. )
  3911. return ", \n\t".join(
  3912. p
  3913. for p in (
  3914. self.process(constraint)
  3915. for constraint in constraints
  3916. if (
  3917. constraint._create_rule is None
  3918. or constraint._create_rule(self)
  3919. )
  3920. and (
  3921. not self.dialect.supports_alter
  3922. or not getattr(constraint, "use_alter", False)
  3923. )
  3924. )
  3925. if p is not None
  3926. )
  3927. def visit_drop_table(self, drop, **kw):
  3928. text = "\nDROP TABLE "
  3929. if drop.if_exists:
  3930. text += "IF EXISTS "
  3931. return text + self.preparer.format_table(drop.element)
  3932. def visit_drop_view(self, drop, **kw):
  3933. return "\nDROP VIEW " + self.preparer.format_table(drop.element)
  3934. def _verify_index_table(self, index):
  3935. if index.table is None:
  3936. raise exc.CompileError(
  3937. "Index '%s' is not associated " "with any table." % index.name
  3938. )
  3939. def visit_create_index(
  3940. self, create, include_schema=False, include_table_schema=True, **kw
  3941. ):
  3942. index = create.element
  3943. self._verify_index_table(index)
  3944. preparer = self.preparer
  3945. text = "CREATE "
  3946. if index.unique:
  3947. text += "UNIQUE "
  3948. if index.name is None:
  3949. raise exc.CompileError(
  3950. "CREATE INDEX requires that the index have a name"
  3951. )
  3952. text += "INDEX "
  3953. if create.if_not_exists:
  3954. text += "IF NOT EXISTS "
  3955. text += "%s ON %s (%s)" % (
  3956. self._prepared_index_name(index, include_schema=include_schema),
  3957. preparer.format_table(
  3958. index.table, use_schema=include_table_schema
  3959. ),
  3960. ", ".join(
  3961. self.sql_compiler.process(
  3962. expr, include_table=False, literal_binds=True
  3963. )
  3964. for expr in index.expressions
  3965. ),
  3966. )
  3967. return text
  3968. def visit_drop_index(self, drop, **kw):
  3969. index = drop.element
  3970. if index.name is None:
  3971. raise exc.CompileError(
  3972. "DROP INDEX requires that the index have a name"
  3973. )
  3974. text = "\nDROP INDEX "
  3975. if drop.if_exists:
  3976. text += "IF EXISTS "
  3977. return text + self._prepared_index_name(index, include_schema=True)
  3978. def _prepared_index_name(self, index, include_schema=False):
  3979. if index.table is not None:
  3980. effective_schema = self.preparer.schema_for_object(index.table)
  3981. else:
  3982. effective_schema = None
  3983. if include_schema and effective_schema:
  3984. schema_name = self.preparer.quote_schema(effective_schema)
  3985. else:
  3986. schema_name = None
  3987. index_name = self.preparer.format_index(index)
  3988. if schema_name:
  3989. index_name = schema_name + "." + index_name
  3990. return index_name
  3991. def visit_add_constraint(self, create, **kw):
  3992. return "ALTER TABLE %s ADD %s" % (
  3993. self.preparer.format_table(create.element.table),
  3994. self.process(create.element),
  3995. )
  3996. def visit_set_table_comment(self, create, **kw):
  3997. return "COMMENT ON TABLE %s IS %s" % (
  3998. self.preparer.format_table(create.element),
  3999. self.sql_compiler.render_literal_value(
  4000. create.element.comment, sqltypes.String()
  4001. ),
  4002. )
  4003. def visit_drop_table_comment(self, drop, **kw):
  4004. return "COMMENT ON TABLE %s IS NULL" % self.preparer.format_table(
  4005. drop.element
  4006. )
  4007. def visit_set_column_comment(self, create, **kw):
  4008. return "COMMENT ON COLUMN %s IS %s" % (
  4009. self.preparer.format_column(
  4010. create.element, use_table=True, use_schema=True
  4011. ),
  4012. self.sql_compiler.render_literal_value(
  4013. create.element.comment, sqltypes.String()
  4014. ),
  4015. )
  4016. def visit_drop_column_comment(self, drop, **kw):
  4017. return "COMMENT ON COLUMN %s IS NULL" % self.preparer.format_column(
  4018. drop.element, use_table=True
  4019. )
  4020. def get_identity_options(self, identity_options):
  4021. text = []
  4022. if identity_options.increment is not None:
  4023. text.append("INCREMENT BY %d" % identity_options.increment)
  4024. if identity_options.start is not None:
  4025. text.append("START WITH %d" % identity_options.start)
  4026. if identity_options.minvalue is not None:
  4027. text.append("MINVALUE %d" % identity_options.minvalue)
  4028. if identity_options.maxvalue is not None:
  4029. text.append("MAXVALUE %d" % identity_options.maxvalue)
  4030. if identity_options.nominvalue is not None:
  4031. text.append("NO MINVALUE")
  4032. if identity_options.nomaxvalue is not None:
  4033. text.append("NO MAXVALUE")
  4034. if identity_options.cache is not None:
  4035. text.append("CACHE %d" % identity_options.cache)
  4036. if identity_options.cycle is not None:
  4037. text.append("CYCLE" if identity_options.cycle else "NO CYCLE")
  4038. return " ".join(text)
  4039. def visit_create_sequence(self, create, prefix=None, **kw):
  4040. text = "CREATE SEQUENCE %s" % self.preparer.format_sequence(
  4041. create.element
  4042. )
  4043. if prefix:
  4044. text += prefix
  4045. if create.element.start is None:
  4046. create.element.start = self.dialect.default_sequence_base
  4047. options = self.get_identity_options(create.element)
  4048. if options:
  4049. text += " " + options
  4050. return text
  4051. def visit_drop_sequence(self, drop, **kw):
  4052. return "DROP SEQUENCE %s" % self.preparer.format_sequence(drop.element)
  4053. def visit_drop_constraint(self, drop, **kw):
  4054. constraint = drop.element
  4055. if constraint.name is not None:
  4056. formatted_name = self.preparer.format_constraint(constraint)
  4057. else:
  4058. formatted_name = None
  4059. if formatted_name is None:
  4060. raise exc.CompileError(
  4061. "Can't emit DROP CONSTRAINT for constraint %r; "
  4062. "it has no name" % drop.element
  4063. )
  4064. return "ALTER TABLE %s DROP CONSTRAINT %s%s" % (
  4065. self.preparer.format_table(drop.element.table),
  4066. formatted_name,
  4067. drop.cascade and " CASCADE" or "",
  4068. )
  4069. def get_column_specification(self, column, **kwargs):
  4070. colspec = (
  4071. self.preparer.format_column(column)
  4072. + " "
  4073. + self.dialect.type_compiler.process(
  4074. column.type, type_expression=column
  4075. )
  4076. )
  4077. default = self.get_column_default_string(column)
  4078. if default is not None:
  4079. colspec += " DEFAULT " + default
  4080. if column.computed is not None:
  4081. colspec += " " + self.process(column.computed)
  4082. if (
  4083. column.identity is not None
  4084. and self.dialect.supports_identity_columns
  4085. ):
  4086. colspec += " " + self.process(column.identity)
  4087. if not column.nullable and (
  4088. not column.identity or not self.dialect.supports_identity_columns
  4089. ):
  4090. colspec += " NOT NULL"
  4091. return colspec
  4092. def create_table_suffix(self, table):
  4093. return ""
  4094. def post_create_table(self, table):
  4095. return ""
  4096. def get_column_default_string(self, column):
  4097. if isinstance(column.server_default, schema.DefaultClause):
  4098. if isinstance(column.server_default.arg, util.string_types):
  4099. return self.sql_compiler.render_literal_value(
  4100. column.server_default.arg, sqltypes.STRINGTYPE
  4101. )
  4102. else:
  4103. return self.sql_compiler.process(
  4104. column.server_default.arg, literal_binds=True
  4105. )
  4106. else:
  4107. return None
  4108. def visit_table_or_column_check_constraint(self, constraint, **kw):
  4109. if constraint.is_column_level:
  4110. return self.visit_column_check_constraint(constraint)
  4111. else:
  4112. return self.visit_check_constraint(constraint)
  4113. def visit_check_constraint(self, constraint, **kw):
  4114. text = ""
  4115. if constraint.name is not None:
  4116. formatted_name = self.preparer.format_constraint(constraint)
  4117. if formatted_name is not None:
  4118. text += "CONSTRAINT %s " % formatted_name
  4119. text += "CHECK (%s)" % self.sql_compiler.process(
  4120. constraint.sqltext, include_table=False, literal_binds=True
  4121. )
  4122. text += self.define_constraint_deferrability(constraint)
  4123. return text
  4124. def visit_column_check_constraint(self, constraint, **kw):
  4125. text = ""
  4126. if constraint.name is not None:
  4127. formatted_name = self.preparer.format_constraint(constraint)
  4128. if formatted_name is not None:
  4129. text += "CONSTRAINT %s " % formatted_name
  4130. text += "CHECK (%s)" % self.sql_compiler.process(
  4131. constraint.sqltext, include_table=False, literal_binds=True
  4132. )
  4133. text += self.define_constraint_deferrability(constraint)
  4134. return text
  4135. def visit_primary_key_constraint(self, constraint, **kw):
  4136. if len(constraint) == 0:
  4137. return ""
  4138. text = ""
  4139. if constraint.name is not None:
  4140. formatted_name = self.preparer.format_constraint(constraint)
  4141. if formatted_name is not None:
  4142. text += "CONSTRAINT %s " % formatted_name
  4143. text += "PRIMARY KEY "
  4144. text += "(%s)" % ", ".join(
  4145. self.preparer.quote(c.name)
  4146. for c in (
  4147. constraint.columns_autoinc_first
  4148. if constraint._implicit_generated
  4149. else constraint.columns
  4150. )
  4151. )
  4152. text += self.define_constraint_deferrability(constraint)
  4153. return text
  4154. def visit_foreign_key_constraint(self, constraint, **kw):
  4155. preparer = self.preparer
  4156. text = ""
  4157. if constraint.name is not None:
  4158. formatted_name = self.preparer.format_constraint(constraint)
  4159. if formatted_name is not None:
  4160. text += "CONSTRAINT %s " % formatted_name
  4161. remote_table = list(constraint.elements)[0].column.table
  4162. text += "FOREIGN KEY(%s) REFERENCES %s (%s)" % (
  4163. ", ".join(
  4164. preparer.quote(f.parent.name) for f in constraint.elements
  4165. ),
  4166. self.define_constraint_remote_table(
  4167. constraint, remote_table, preparer
  4168. ),
  4169. ", ".join(
  4170. preparer.quote(f.column.name) for f in constraint.elements
  4171. ),
  4172. )
  4173. text += self.define_constraint_match(constraint)
  4174. text += self.define_constraint_cascades(constraint)
  4175. text += self.define_constraint_deferrability(constraint)
  4176. return text
  4177. def define_constraint_remote_table(self, constraint, table, preparer):
  4178. """Format the remote table clause of a CREATE CONSTRAINT clause."""
  4179. return preparer.format_table(table)
  4180. def visit_unique_constraint(self, constraint, **kw):
  4181. if len(constraint) == 0:
  4182. return ""
  4183. text = ""
  4184. if constraint.name is not None:
  4185. formatted_name = self.preparer.format_constraint(constraint)
  4186. if formatted_name is not None:
  4187. text += "CONSTRAINT %s " % formatted_name
  4188. text += "UNIQUE (%s)" % (
  4189. ", ".join(self.preparer.quote(c.name) for c in constraint)
  4190. )
  4191. text += self.define_constraint_deferrability(constraint)
  4192. return text
  4193. def define_constraint_cascades(self, constraint):
  4194. text = ""
  4195. if constraint.ondelete is not None:
  4196. text += " ON DELETE %s" % self.preparer.validate_sql_phrase(
  4197. constraint.ondelete, FK_ON_DELETE
  4198. )
  4199. if constraint.onupdate is not None:
  4200. text += " ON UPDATE %s" % self.preparer.validate_sql_phrase(
  4201. constraint.onupdate, FK_ON_UPDATE
  4202. )
  4203. return text
  4204. def define_constraint_deferrability(self, constraint):
  4205. text = ""
  4206. if constraint.deferrable is not None:
  4207. if constraint.deferrable:
  4208. text += " DEFERRABLE"
  4209. else:
  4210. text += " NOT DEFERRABLE"
  4211. if constraint.initially is not None:
  4212. text += " INITIALLY %s" % self.preparer.validate_sql_phrase(
  4213. constraint.initially, FK_INITIALLY
  4214. )
  4215. return text
  4216. def define_constraint_match(self, constraint):
  4217. text = ""
  4218. if constraint.match is not None:
  4219. text += " MATCH %s" % constraint.match
  4220. return text
  4221. def visit_computed_column(self, generated, **kw):
  4222. text = "GENERATED ALWAYS AS (%s)" % self.sql_compiler.process(
  4223. generated.sqltext, include_table=False, literal_binds=True
  4224. )
  4225. if generated.persisted is True:
  4226. text += " STORED"
  4227. elif generated.persisted is False:
  4228. text += " VIRTUAL"
  4229. return text
  4230. def visit_identity_column(self, identity, **kw):
  4231. text = "GENERATED %s AS IDENTITY" % (
  4232. "ALWAYS" if identity.always else "BY DEFAULT",
  4233. )
  4234. options = self.get_identity_options(identity)
  4235. if options:
  4236. text += " (%s)" % options
  4237. return text
  4238. class GenericTypeCompiler(TypeCompiler):
  4239. def visit_FLOAT(self, type_, **kw):
  4240. return "FLOAT"
  4241. def visit_REAL(self, type_, **kw):
  4242. return "REAL"
  4243. def visit_NUMERIC(self, type_, **kw):
  4244. if type_.precision is None:
  4245. return "NUMERIC"
  4246. elif type_.scale is None:
  4247. return "NUMERIC(%(precision)s)" % {"precision": type_.precision}
  4248. else:
  4249. return "NUMERIC(%(precision)s, %(scale)s)" % {
  4250. "precision": type_.precision,
  4251. "scale": type_.scale,
  4252. }
  4253. def visit_DECIMAL(self, type_, **kw):
  4254. if type_.precision is None:
  4255. return "DECIMAL"
  4256. elif type_.scale is None:
  4257. return "DECIMAL(%(precision)s)" % {"precision": type_.precision}
  4258. else:
  4259. return "DECIMAL(%(precision)s, %(scale)s)" % {
  4260. "precision": type_.precision,
  4261. "scale": type_.scale,
  4262. }
  4263. def visit_INTEGER(self, type_, **kw):
  4264. return "INTEGER"
  4265. def visit_SMALLINT(self, type_, **kw):
  4266. return "SMALLINT"
  4267. def visit_BIGINT(self, type_, **kw):
  4268. return "BIGINT"
  4269. def visit_TIMESTAMP(self, type_, **kw):
  4270. return "TIMESTAMP"
  4271. def visit_DATETIME(self, type_, **kw):
  4272. return "DATETIME"
  4273. def visit_DATE(self, type_, **kw):
  4274. return "DATE"
  4275. def visit_TIME(self, type_, **kw):
  4276. return "TIME"
  4277. def visit_CLOB(self, type_, **kw):
  4278. return "CLOB"
  4279. def visit_NCLOB(self, type_, **kw):
  4280. return "NCLOB"
  4281. def _render_string_type(self, type_, name):
  4282. text = name
  4283. if type_.length:
  4284. text += "(%d)" % type_.length
  4285. if type_.collation:
  4286. text += ' COLLATE "%s"' % type_.collation
  4287. return text
  4288. def visit_CHAR(self, type_, **kw):
  4289. return self._render_string_type(type_, "CHAR")
  4290. def visit_NCHAR(self, type_, **kw):
  4291. return self._render_string_type(type_, "NCHAR")
  4292. def visit_VARCHAR(self, type_, **kw):
  4293. return self._render_string_type(type_, "VARCHAR")
  4294. def visit_NVARCHAR(self, type_, **kw):
  4295. return self._render_string_type(type_, "NVARCHAR")
  4296. def visit_TEXT(self, type_, **kw):
  4297. return self._render_string_type(type_, "TEXT")
  4298. def visit_BLOB(self, type_, **kw):
  4299. return "BLOB"
  4300. def visit_BINARY(self, type_, **kw):
  4301. return "BINARY" + (type_.length and "(%d)" % type_.length or "")
  4302. def visit_VARBINARY(self, type_, **kw):
  4303. return "VARBINARY" + (type_.length and "(%d)" % type_.length or "")
  4304. def visit_BOOLEAN(self, type_, **kw):
  4305. return "BOOLEAN"
  4306. def visit_large_binary(self, type_, **kw):
  4307. return self.visit_BLOB(type_, **kw)
  4308. def visit_boolean(self, type_, **kw):
  4309. return self.visit_BOOLEAN(type_, **kw)
  4310. def visit_time(self, type_, **kw):
  4311. return self.visit_TIME(type_, **kw)
  4312. def visit_datetime(self, type_, **kw):
  4313. return self.visit_DATETIME(type_, **kw)
  4314. def visit_date(self, type_, **kw):
  4315. return self.visit_DATE(type_, **kw)
  4316. def visit_big_integer(self, type_, **kw):
  4317. return self.visit_BIGINT(type_, **kw)
  4318. def visit_small_integer(self, type_, **kw):
  4319. return self.visit_SMALLINT(type_, **kw)
  4320. def visit_integer(self, type_, **kw):
  4321. return self.visit_INTEGER(type_, **kw)
  4322. def visit_real(self, type_, **kw):
  4323. return self.visit_REAL(type_, **kw)
  4324. def visit_float(self, type_, **kw):
  4325. return self.visit_FLOAT(type_, **kw)
  4326. def visit_numeric(self, type_, **kw):
  4327. return self.visit_NUMERIC(type_, **kw)
  4328. def visit_string(self, type_, **kw):
  4329. return self.visit_VARCHAR(type_, **kw)
  4330. def visit_unicode(self, type_, **kw):
  4331. return self.visit_VARCHAR(type_, **kw)
  4332. def visit_text(self, type_, **kw):
  4333. return self.visit_TEXT(type_, **kw)
  4334. def visit_unicode_text(self, type_, **kw):
  4335. return self.visit_TEXT(type_, **kw)
  4336. def visit_enum(self, type_, **kw):
  4337. return self.visit_VARCHAR(type_, **kw)
  4338. def visit_null(self, type_, **kw):
  4339. raise exc.CompileError(
  4340. "Can't generate DDL for %r; "
  4341. "did you forget to specify a "
  4342. "type on this Column?" % type_
  4343. )
  4344. def visit_type_decorator(self, type_, **kw):
  4345. return self.process(type_.type_engine(self.dialect), **kw)
  4346. def visit_user_defined(self, type_, **kw):
  4347. return type_.get_col_spec(**kw)
  4348. class StrSQLTypeCompiler(GenericTypeCompiler):
  4349. def process(self, type_, **kw):
  4350. try:
  4351. _compiler_dispatch = type_._compiler_dispatch
  4352. except AttributeError:
  4353. return self._visit_unknown(type_, **kw)
  4354. else:
  4355. return _compiler_dispatch(self, **kw)
  4356. def __getattr__(self, key):
  4357. if key.startswith("visit_"):
  4358. return self._visit_unknown
  4359. else:
  4360. raise AttributeError(key)
  4361. def _visit_unknown(self, type_, **kw):
  4362. if type_.__class__.__name__ == type_.__class__.__name__.upper():
  4363. return type_.__class__.__name__
  4364. else:
  4365. return repr(type_)
  4366. def visit_null(self, type_, **kw):
  4367. return "NULL"
  4368. def visit_user_defined(self, type_, **kw):
  4369. try:
  4370. get_col_spec = type_.get_col_spec
  4371. except AttributeError:
  4372. return repr(type_)
  4373. else:
  4374. return get_col_spec(**kw)
  4375. class IdentifierPreparer(object):
  4376. """Handle quoting and case-folding of identifiers based on options."""
  4377. reserved_words = RESERVED_WORDS
  4378. legal_characters = LEGAL_CHARACTERS
  4379. illegal_initial_characters = ILLEGAL_INITIAL_CHARACTERS
  4380. schema_for_object = operator.attrgetter("schema")
  4381. """Return the .schema attribute for an object.
  4382. For the default IdentifierPreparer, the schema for an object is always
  4383. the value of the ".schema" attribute. if the preparer is replaced
  4384. with one that has a non-empty schema_translate_map, the value of the
  4385. ".schema" attribute is rendered a symbol that will be converted to a
  4386. real schema name from the mapping post-compile.
  4387. """
  4388. def __init__(
  4389. self,
  4390. dialect,
  4391. initial_quote='"',
  4392. final_quote=None,
  4393. escape_quote='"',
  4394. quote_case_sensitive_collations=True,
  4395. omit_schema=False,
  4396. ):
  4397. """Construct a new ``IdentifierPreparer`` object.
  4398. initial_quote
  4399. Character that begins a delimited identifier.
  4400. final_quote
  4401. Character that ends a delimited identifier. Defaults to
  4402. `initial_quote`.
  4403. omit_schema
  4404. Prevent prepending schema name. Useful for databases that do
  4405. not support schemae.
  4406. """
  4407. self.dialect = dialect
  4408. self.initial_quote = initial_quote
  4409. self.final_quote = final_quote or self.initial_quote
  4410. self.escape_quote = escape_quote
  4411. self.escape_to_quote = self.escape_quote * 2
  4412. self.omit_schema = omit_schema
  4413. self.quote_case_sensitive_collations = quote_case_sensitive_collations
  4414. self._strings = {}
  4415. self._double_percents = self.dialect.paramstyle in (
  4416. "format",
  4417. "pyformat",
  4418. )
  4419. def _with_schema_translate(self, schema_translate_map):
  4420. prep = self.__class__.__new__(self.__class__)
  4421. prep.__dict__.update(self.__dict__)
  4422. def symbol_getter(obj):
  4423. name = obj.schema
  4424. if name in schema_translate_map and obj._use_schema_map:
  4425. if name is not None and ("[" in name or "]" in name):
  4426. raise exc.CompileError(
  4427. "Square bracket characters ([]) not supported "
  4428. "in schema translate name '%s'" % name
  4429. )
  4430. return quoted_name(
  4431. "__[SCHEMA_%s]" % (name or "_none"), quote=False
  4432. )
  4433. else:
  4434. return obj.schema
  4435. prep.schema_for_object = symbol_getter
  4436. return prep
  4437. def _render_schema_translates(self, statement, schema_translate_map):
  4438. d = schema_translate_map
  4439. if None in d:
  4440. d["_none"] = d[None]
  4441. def replace(m):
  4442. name = m.group(2)
  4443. effective_schema = d[name]
  4444. if not effective_schema:
  4445. effective_schema = self.dialect.default_schema_name
  4446. if not effective_schema:
  4447. # TODO: no coverage here
  4448. raise exc.CompileError(
  4449. "Dialect has no default schema name; can't "
  4450. "use None as dynamic schema target."
  4451. )
  4452. return self.quote_schema(effective_schema)
  4453. return re.sub(r"(__\[SCHEMA_([^\]]+)\])", replace, statement)
  4454. def _escape_identifier(self, value):
  4455. """Escape an identifier.
  4456. Subclasses should override this to provide database-dependent
  4457. escaping behavior.
  4458. """
  4459. value = value.replace(self.escape_quote, self.escape_to_quote)
  4460. if self._double_percents:
  4461. value = value.replace("%", "%%")
  4462. return value
  4463. def _unescape_identifier(self, value):
  4464. """Canonicalize an escaped identifier.
  4465. Subclasses should override this to provide database-dependent
  4466. unescaping behavior that reverses _escape_identifier.
  4467. """
  4468. return value.replace(self.escape_to_quote, self.escape_quote)
  4469. def validate_sql_phrase(self, element, reg):
  4470. """keyword sequence filter.
  4471. a filter for elements that are intended to represent keyword sequences,
  4472. such as "INITIALLY", "INITIALLY DEFERRED", etc. no special characters
  4473. should be present.
  4474. .. versionadded:: 1.3
  4475. """
  4476. if element is not None and not reg.match(element):
  4477. raise exc.CompileError(
  4478. "Unexpected SQL phrase: %r (matching against %r)"
  4479. % (element, reg.pattern)
  4480. )
  4481. return element
  4482. def quote_identifier(self, value):
  4483. """Quote an identifier.
  4484. Subclasses should override this to provide database-dependent
  4485. quoting behavior.
  4486. """
  4487. return (
  4488. self.initial_quote
  4489. + self._escape_identifier(value)
  4490. + self.final_quote
  4491. )
  4492. def _requires_quotes(self, value):
  4493. """Return True if the given identifier requires quoting."""
  4494. lc_value = value.lower()
  4495. return (
  4496. lc_value in self.reserved_words
  4497. or value[0] in self.illegal_initial_characters
  4498. or not self.legal_characters.match(util.text_type(value))
  4499. or (lc_value != value)
  4500. )
  4501. def _requires_quotes_illegal_chars(self, value):
  4502. """Return True if the given identifier requires quoting, but
  4503. not taking case convention into account."""
  4504. return not self.legal_characters.match(util.text_type(value))
  4505. def quote_schema(self, schema, force=None):
  4506. """Conditionally quote a schema name.
  4507. The name is quoted if it is a reserved word, contains quote-necessary
  4508. characters, or is an instance of :class:`.quoted_name` which includes
  4509. ``quote`` set to ``True``.
  4510. Subclasses can override this to provide database-dependent
  4511. quoting behavior for schema names.
  4512. :param schema: string schema name
  4513. :param force: unused
  4514. .. deprecated:: 0.9
  4515. The :paramref:`.IdentifierPreparer.quote_schema.force`
  4516. parameter is deprecated and will be removed in a future
  4517. release. This flag has no effect on the behavior of the
  4518. :meth:`.IdentifierPreparer.quote` method; please refer to
  4519. :class:`.quoted_name`.
  4520. """
  4521. if force is not None:
  4522. # not using the util.deprecated_params() decorator in this
  4523. # case because of the additional function call overhead on this
  4524. # very performance-critical spot.
  4525. util.warn_deprecated(
  4526. "The IdentifierPreparer.quote_schema.force parameter is "
  4527. "deprecated and will be removed in a future release. This "
  4528. "flag has no effect on the behavior of the "
  4529. "IdentifierPreparer.quote method; please refer to "
  4530. "quoted_name().",
  4531. # deprecated 0.9. warning from 1.3
  4532. version="0.9",
  4533. )
  4534. return self.quote(schema)
  4535. def quote(self, ident, force=None):
  4536. """Conditionally quote an identifier.
  4537. The identifier is quoted if it is a reserved word, contains
  4538. quote-necessary characters, or is an instance of
  4539. :class:`.quoted_name` which includes ``quote`` set to ``True``.
  4540. Subclasses can override this to provide database-dependent
  4541. quoting behavior for identifier names.
  4542. :param ident: string identifier
  4543. :param force: unused
  4544. .. deprecated:: 0.9
  4545. The :paramref:`.IdentifierPreparer.quote.force`
  4546. parameter is deprecated and will be removed in a future
  4547. release. This flag has no effect on the behavior of the
  4548. :meth:`.IdentifierPreparer.quote` method; please refer to
  4549. :class:`.quoted_name`.
  4550. """
  4551. if force is not None:
  4552. # not using the util.deprecated_params() decorator in this
  4553. # case because of the additional function call overhead on this
  4554. # very performance-critical spot.
  4555. util.warn_deprecated(
  4556. "The IdentifierPreparer.quote.force parameter is "
  4557. "deprecated and will be removed in a future release. This "
  4558. "flag has no effect on the behavior of the "
  4559. "IdentifierPreparer.quote method; please refer to "
  4560. "quoted_name().",
  4561. # deprecated 0.9. warning from 1.3
  4562. version="0.9",
  4563. )
  4564. force = getattr(ident, "quote", None)
  4565. if force is None:
  4566. if ident in self._strings:
  4567. return self._strings[ident]
  4568. else:
  4569. if self._requires_quotes(ident):
  4570. self._strings[ident] = self.quote_identifier(ident)
  4571. else:
  4572. self._strings[ident] = ident
  4573. return self._strings[ident]
  4574. elif force:
  4575. return self.quote_identifier(ident)
  4576. else:
  4577. return ident
  4578. def format_collation(self, collation_name):
  4579. if self.quote_case_sensitive_collations:
  4580. return self.quote(collation_name)
  4581. else:
  4582. return collation_name
  4583. def format_sequence(self, sequence, use_schema=True):
  4584. name = self.quote(sequence.name)
  4585. effective_schema = self.schema_for_object(sequence)
  4586. if (
  4587. not self.omit_schema
  4588. and use_schema
  4589. and effective_schema is not None
  4590. ):
  4591. name = self.quote_schema(effective_schema) + "." + name
  4592. return name
  4593. def format_label(self, label, name=None):
  4594. return self.quote(name or label.name)
  4595. def format_alias(self, alias, name=None):
  4596. return self.quote(name or alias.name)
  4597. def format_savepoint(self, savepoint, name=None):
  4598. # Running the savepoint name through quoting is unnecessary
  4599. # for all known dialects. This is here to support potential
  4600. # third party use cases
  4601. ident = name or savepoint.ident
  4602. if self._requires_quotes(ident):
  4603. ident = self.quote_identifier(ident)
  4604. return ident
  4605. @util.preload_module("sqlalchemy.sql.naming")
  4606. def format_constraint(self, constraint, _alembic_quote=True):
  4607. naming = util.preloaded.sql_naming
  4608. if constraint.name is elements._NONE_NAME:
  4609. name = naming._constraint_name_for_table(
  4610. constraint, constraint.table
  4611. )
  4612. if name is None:
  4613. return None
  4614. else:
  4615. name = constraint.name
  4616. if constraint.__visit_name__ == "index":
  4617. return self.truncate_and_render_index_name(
  4618. name, _alembic_quote=_alembic_quote
  4619. )
  4620. else:
  4621. return self.truncate_and_render_constraint_name(
  4622. name, _alembic_quote=_alembic_quote
  4623. )
  4624. def truncate_and_render_index_name(self, name, _alembic_quote=True):
  4625. # calculate these at format time so that ad-hoc changes
  4626. # to dialect.max_identifier_length etc. can be reflected
  4627. # as IdentifierPreparer is long lived
  4628. max_ = (
  4629. self.dialect.max_index_name_length
  4630. or self.dialect.max_identifier_length
  4631. )
  4632. return self._truncate_and_render_maxlen_name(
  4633. name, max_, _alembic_quote
  4634. )
  4635. def truncate_and_render_constraint_name(self, name, _alembic_quote=True):
  4636. # calculate these at format time so that ad-hoc changes
  4637. # to dialect.max_identifier_length etc. can be reflected
  4638. # as IdentifierPreparer is long lived
  4639. max_ = (
  4640. self.dialect.max_constraint_name_length
  4641. or self.dialect.max_identifier_length
  4642. )
  4643. return self._truncate_and_render_maxlen_name(
  4644. name, max_, _alembic_quote
  4645. )
  4646. def _truncate_and_render_maxlen_name(self, name, max_, _alembic_quote):
  4647. if isinstance(name, elements._truncated_label):
  4648. if len(name) > max_:
  4649. name = name[0 : max_ - 8] + "_" + util.md5_hex(name)[-4:]
  4650. else:
  4651. self.dialect.validate_identifier(name)
  4652. if not _alembic_quote:
  4653. return name
  4654. else:
  4655. return self.quote(name)
  4656. def format_index(self, index):
  4657. return self.format_constraint(index)
  4658. def format_table(self, table, use_schema=True, name=None):
  4659. """Prepare a quoted table and schema name."""
  4660. if name is None:
  4661. name = table.name
  4662. result = self.quote(name)
  4663. effective_schema = self.schema_for_object(table)
  4664. if not self.omit_schema and use_schema and effective_schema:
  4665. result = self.quote_schema(effective_schema) + "." + result
  4666. return result
  4667. def format_schema(self, name):
  4668. """Prepare a quoted schema name."""
  4669. return self.quote(name)
  4670. def format_label_name(
  4671. self,
  4672. name,
  4673. anon_map=None,
  4674. ):
  4675. """Prepare a quoted column name."""
  4676. if anon_map is not None and isinstance(
  4677. name, elements._truncated_label
  4678. ):
  4679. name = name.apply_map(anon_map)
  4680. return self.quote(name)
  4681. def format_column(
  4682. self,
  4683. column,
  4684. use_table=False,
  4685. name=None,
  4686. table_name=None,
  4687. use_schema=False,
  4688. anon_map=None,
  4689. ):
  4690. """Prepare a quoted column name."""
  4691. if name is None:
  4692. name = column.name
  4693. if anon_map is not None and isinstance(
  4694. name, elements._truncated_label
  4695. ):
  4696. name = name.apply_map(anon_map)
  4697. if not getattr(column, "is_literal", False):
  4698. if use_table:
  4699. return (
  4700. self.format_table(
  4701. column.table, use_schema=use_schema, name=table_name
  4702. )
  4703. + "."
  4704. + self.quote(name)
  4705. )
  4706. else:
  4707. return self.quote(name)
  4708. else:
  4709. # literal textual elements get stuck into ColumnClause a lot,
  4710. # which shouldn't get quoted
  4711. if use_table:
  4712. return (
  4713. self.format_table(
  4714. column.table, use_schema=use_schema, name=table_name
  4715. )
  4716. + "."
  4717. + name
  4718. )
  4719. else:
  4720. return name
  4721. def format_table_seq(self, table, use_schema=True):
  4722. """Format table name and schema as a tuple."""
  4723. # Dialects with more levels in their fully qualified references
  4724. # ('database', 'owner', etc.) could override this and return
  4725. # a longer sequence.
  4726. effective_schema = self.schema_for_object(table)
  4727. if not self.omit_schema and use_schema and effective_schema:
  4728. return (
  4729. self.quote_schema(effective_schema),
  4730. self.format_table(table, use_schema=False),
  4731. )
  4732. else:
  4733. return (self.format_table(table, use_schema=False),)
  4734. @util.memoized_property
  4735. def _r_identifiers(self):
  4736. initial, final, escaped_final = [
  4737. re.escape(s)
  4738. for s in (
  4739. self.initial_quote,
  4740. self.final_quote,
  4741. self._escape_identifier(self.final_quote),
  4742. )
  4743. ]
  4744. r = re.compile(
  4745. r"(?:"
  4746. r"(?:%(initial)s((?:%(escaped)s|[^%(final)s])+)%(final)s"
  4747. r"|([^\.]+))(?=\.|$))+"
  4748. % {"initial": initial, "final": final, "escaped": escaped_final}
  4749. )
  4750. return r
  4751. def unformat_identifiers(self, identifiers):
  4752. """Unpack 'schema.table.column'-like strings into components."""
  4753. r = self._r_identifiers
  4754. return [
  4755. self._unescape_identifier(i)
  4756. for i in [a or b for a, b in r.findall(identifiers)]
  4757. ]