schema.py 223 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122
  1. # sql/schema.py
  2. # Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. """The schema module provides the building blocks for database metadata.
  8. Each element within this module describes a database entity which can be
  9. created and dropped, or is otherwise part of such an entity. Examples include
  10. tables, columns, sequences, and indexes.
  11. All entities are subclasses of :class:`~sqlalchemy.schema.SchemaItem`, and as
  12. defined in this module they are intended to be agnostic of any vendor-specific
  13. constructs.
  14. A collection of entities are grouped into a unit called
  15. :class:`~sqlalchemy.schema.MetaData`. MetaData serves as a logical grouping of
  16. schema elements, and can also be associated with an actual database connection
  17. such that operations involving the contained elements can contact the database
  18. as needed.
  19. Two of the elements here also build upon their "syntactic" counterparts, which
  20. are defined in :class:`~sqlalchemy.sql.expression.`, specifically
  21. :class:`~sqlalchemy.schema.Table` and :class:`~sqlalchemy.schema.Column`.
  22. Since these objects are part of the SQL expression language, they are usable
  23. as components in SQL expressions.
  24. """
  25. from __future__ import annotations
  26. from abc import ABC
  27. import collections
  28. from enum import Enum
  29. import operator
  30. import typing
  31. from typing import Any
  32. from typing import Callable
  33. from typing import cast
  34. from typing import Collection
  35. from typing import Dict
  36. from typing import Iterable
  37. from typing import Iterator
  38. from typing import List
  39. from typing import Mapping
  40. from typing import NoReturn
  41. from typing import Optional
  42. from typing import overload
  43. from typing import Sequence as _typing_Sequence
  44. from typing import Set
  45. from typing import Tuple
  46. from typing import TYPE_CHECKING
  47. from typing import TypeVar
  48. from typing import Union
  49. from . import coercions
  50. from . import ddl
  51. from . import roles
  52. from . import type_api
  53. from . import visitors
  54. from .base import _DefaultDescriptionTuple
  55. from .base import _NoneName
  56. from .base import _SentinelColumnCharacterization
  57. from .base import _SentinelDefaultCharacterization
  58. from .base import DedupeColumnCollection
  59. from .base import DialectKWArgs
  60. from .base import Executable
  61. from .base import SchemaEventTarget as SchemaEventTarget
  62. from .coercions import _document_text_coercion
  63. from .elements import ClauseElement
  64. from .elements import ColumnClause
  65. from .elements import ColumnElement
  66. from .elements import quoted_name
  67. from .elements import TextClause
  68. from .selectable import TableClause
  69. from .type_api import to_instance
  70. from .visitors import ExternallyTraversible
  71. from .visitors import InternalTraversal
  72. from .. import event
  73. from .. import exc
  74. from .. import inspection
  75. from .. import util
  76. from ..util import HasMemoized
  77. from ..util.typing import Final
  78. from ..util.typing import Literal
  79. from ..util.typing import Protocol
  80. from ..util.typing import Self
  81. from ..util.typing import TypedDict
  82. from ..util.typing import TypeGuard
  83. if typing.TYPE_CHECKING:
  84. from ._typing import _AutoIncrementType
  85. from ._typing import _DDLColumnArgument
  86. from ._typing import _InfoType
  87. from ._typing import _TextCoercedExpressionArgument
  88. from ._typing import _TypeEngineArgument
  89. from .base import ReadOnlyColumnCollection
  90. from .compiler import DDLCompiler
  91. from .elements import BindParameter
  92. from .functions import Function
  93. from .type_api import TypeEngine
  94. from .visitors import _TraverseInternalsType
  95. from .visitors import anon_map
  96. from ..engine import Connection
  97. from ..engine import Engine
  98. from ..engine.interfaces import _CoreMultiExecuteParams
  99. from ..engine.interfaces import CoreExecuteOptionsParameter
  100. from ..engine.interfaces import ExecutionContext
  101. from ..engine.mock import MockConnection
  102. from ..engine.reflection import _ReflectionInfo
  103. from ..sql.selectable import FromClause
  104. _T = TypeVar("_T", bound="Any")
  105. _SI = TypeVar("_SI", bound="SchemaItem")
  106. _TAB = TypeVar("_TAB", bound="Table")
  107. _CreateDropBind = Union["Engine", "Connection", "MockConnection"]
  108. _ConstraintNameArgument = Optional[Union[str, _NoneName]]
  109. _ServerDefaultArgument = Union[
  110. "FetchedValue", str, TextClause, ColumnElement[Any]
  111. ]
  112. class SchemaConst(Enum):
  113. RETAIN_SCHEMA = 1
  114. """Symbol indicating that a :class:`_schema.Table`, :class:`.Sequence`
  115. or in some cases a :class:`_schema.ForeignKey` object, in situations
  116. where the object is being copied for a :meth:`.Table.to_metadata`
  117. operation, should retain the schema name that it already has.
  118. """
  119. BLANK_SCHEMA = 2
  120. """Symbol indicating that a :class:`_schema.Table` or :class:`.Sequence`
  121. should have 'None' for its schema, even if the parent
  122. :class:`_schema.MetaData` has specified a schema.
  123. .. seealso::
  124. :paramref:`_schema.MetaData.schema`
  125. :paramref:`_schema.Table.schema`
  126. :paramref:`.Sequence.schema`
  127. """
  128. NULL_UNSPECIFIED = 3
  129. """Symbol indicating the "nullable" keyword was not passed to a Column.
  130. This is used to distinguish between the use case of passing
  131. ``nullable=None`` to a :class:`.Column`, which has special meaning
  132. on some backends such as SQL Server.
  133. """
  134. RETAIN_SCHEMA: Final[
  135. Literal[SchemaConst.RETAIN_SCHEMA]
  136. ] = SchemaConst.RETAIN_SCHEMA
  137. BLANK_SCHEMA: Final[
  138. Literal[SchemaConst.BLANK_SCHEMA]
  139. ] = SchemaConst.BLANK_SCHEMA
  140. NULL_UNSPECIFIED: Final[
  141. Literal[SchemaConst.NULL_UNSPECIFIED]
  142. ] = SchemaConst.NULL_UNSPECIFIED
  143. def _get_table_key(name: str, schema: Optional[str]) -> str:
  144. if schema is None:
  145. return name
  146. else:
  147. return schema + "." + name
  148. # this should really be in sql/util.py but we'd have to
  149. # break an import cycle
  150. def _copy_expression(
  151. expression: ColumnElement[Any],
  152. source_table: Optional[Table],
  153. target_table: Optional[Table],
  154. ) -> ColumnElement[Any]:
  155. if source_table is None or target_table is None:
  156. return expression
  157. fixed_source_table = source_table
  158. fixed_target_table = target_table
  159. def replace(
  160. element: ExternallyTraversible, **kw: Any
  161. ) -> Optional[ExternallyTraversible]:
  162. if (
  163. isinstance(element, Column)
  164. and element.table is fixed_source_table
  165. and element.key in fixed_source_table.c
  166. ):
  167. return fixed_target_table.c[element.key]
  168. else:
  169. return None
  170. return cast(
  171. ColumnElement[Any],
  172. visitors.replacement_traverse(expression, {}, replace),
  173. )
  174. @inspection._self_inspects
  175. class SchemaItem(SchemaEventTarget, visitors.Visitable):
  176. """Base class for items that define a database schema."""
  177. __visit_name__ = "schema_item"
  178. create_drop_stringify_dialect = "default"
  179. def _init_items(self, *args: SchemaItem, **kw: Any) -> None:
  180. """Initialize the list of child items for this SchemaItem."""
  181. for item in args:
  182. if item is not None:
  183. try:
  184. spwd = item._set_parent_with_dispatch
  185. except AttributeError as err:
  186. raise exc.ArgumentError(
  187. "'SchemaItem' object, such as a 'Column' or a "
  188. f"'Constraint' expected, got {item!r}"
  189. ) from err
  190. else:
  191. spwd(self, **kw)
  192. def __repr__(self) -> str:
  193. return util.generic_repr(self, omit_kwarg=["info"])
  194. @util.memoized_property
  195. def info(self) -> _InfoType:
  196. """Info dictionary associated with the object, allowing user-defined
  197. data to be associated with this :class:`.SchemaItem`.
  198. The dictionary is automatically generated when first accessed.
  199. It can also be specified in the constructor of some objects,
  200. such as :class:`_schema.Table` and :class:`_schema.Column`.
  201. """
  202. return {}
  203. def _schema_item_copy(self, schema_item: _SI) -> _SI:
  204. if "info" in self.__dict__:
  205. schema_item.info = self.info.copy()
  206. schema_item.dispatch._update(self.dispatch)
  207. return schema_item
  208. _use_schema_map = True
  209. class HasConditionalDDL:
  210. """define a class that includes the :meth:`.HasConditionalDDL.ddl_if`
  211. method, allowing for conditional rendering of DDL.
  212. Currently applies to constraints and indexes.
  213. .. versionadded:: 2.0
  214. """
  215. _ddl_if: Optional[ddl.DDLIf] = None
  216. def ddl_if(
  217. self,
  218. dialect: Optional[str] = None,
  219. callable_: Optional[ddl.DDLIfCallable] = None,
  220. state: Optional[Any] = None,
  221. ) -> Self:
  222. r"""apply a conditional DDL rule to this schema item.
  223. These rules work in a similar manner to the
  224. :meth:`.ExecutableDDLElement.execute_if` callable, with the added
  225. feature that the criteria may be checked within the DDL compilation
  226. phase for a construct such as :class:`.CreateTable`.
  227. :meth:`.HasConditionalDDL.ddl_if` currently applies towards the
  228. :class:`.Index` construct as well as all :class:`.Constraint`
  229. constructs.
  230. :param dialect: string name of a dialect, or a tuple of string names
  231. to indicate multiple dialect types.
  232. :param callable\_: a callable that is constructed using the same form
  233. as that described in
  234. :paramref:`.ExecutableDDLElement.execute_if.callable_`.
  235. :param state: any arbitrary object that will be passed to the
  236. callable, if present.
  237. .. versionadded:: 2.0
  238. .. seealso::
  239. :ref:`schema_ddl_ddl_if` - background and usage examples
  240. """
  241. self._ddl_if = ddl.DDLIf(dialect, callable_, state)
  242. return self
  243. class HasSchemaAttr(SchemaItem):
  244. """schema item that includes a top-level schema name"""
  245. schema: Optional[str]
  246. class Table(
  247. DialectKWArgs, HasSchemaAttr, TableClause, inspection.Inspectable["Table"]
  248. ):
  249. r"""Represent a table in a database.
  250. e.g.::
  251. mytable = Table(
  252. "mytable", metadata,
  253. Column('mytable_id', Integer, primary_key=True),
  254. Column('value', String(50))
  255. )
  256. The :class:`_schema.Table`
  257. object constructs a unique instance of itself based
  258. on its name and optional schema name within the given
  259. :class:`_schema.MetaData` object. Calling the :class:`_schema.Table`
  260. constructor with the same name and same :class:`_schema.MetaData` argument
  261. a second time will return the *same* :class:`_schema.Table`
  262. object - in this way
  263. the :class:`_schema.Table` constructor acts as a registry function.
  264. .. seealso::
  265. :ref:`metadata_describing` - Introduction to database metadata
  266. """
  267. __visit_name__ = "table"
  268. if TYPE_CHECKING:
  269. @util.ro_non_memoized_property
  270. def primary_key(self) -> PrimaryKeyConstraint:
  271. ...
  272. @util.ro_non_memoized_property
  273. def foreign_keys(self) -> Set[ForeignKey]:
  274. ...
  275. _columns: DedupeColumnCollection[Column[Any]]
  276. _sentinel_column: Optional[Column[Any]]
  277. constraints: Set[Constraint]
  278. """A collection of all :class:`_schema.Constraint` objects associated with
  279. this :class:`_schema.Table`.
  280. Includes :class:`_schema.PrimaryKeyConstraint`,
  281. :class:`_schema.ForeignKeyConstraint`, :class:`_schema.UniqueConstraint`,
  282. :class:`_schema.CheckConstraint`. A separate collection
  283. :attr:`_schema.Table.foreign_key_constraints` refers to the collection
  284. of all :class:`_schema.ForeignKeyConstraint` objects, and the
  285. :attr:`_schema.Table.primary_key` attribute refers to the single
  286. :class:`_schema.PrimaryKeyConstraint` associated with the
  287. :class:`_schema.Table`.
  288. .. seealso::
  289. :attr:`_schema.Table.constraints`
  290. :attr:`_schema.Table.primary_key`
  291. :attr:`_schema.Table.foreign_key_constraints`
  292. :attr:`_schema.Table.indexes`
  293. :class:`_reflection.Inspector`
  294. """
  295. indexes: Set[Index]
  296. """A collection of all :class:`_schema.Index` objects associated with this
  297. :class:`_schema.Table`.
  298. .. seealso::
  299. :meth:`_reflection.Inspector.get_indexes`
  300. """
  301. _traverse_internals: _TraverseInternalsType = (
  302. TableClause._traverse_internals
  303. + [("schema", InternalTraversal.dp_string)]
  304. )
  305. if TYPE_CHECKING:
  306. @util.ro_non_memoized_property
  307. def columns(self) -> ReadOnlyColumnCollection[str, Column[Any]]:
  308. ...
  309. @util.ro_non_memoized_property
  310. def exported_columns(
  311. self,
  312. ) -> ReadOnlyColumnCollection[str, Column[Any]]:
  313. ...
  314. @util.ro_non_memoized_property
  315. def c(self) -> ReadOnlyColumnCollection[str, Column[Any]]:
  316. ...
  317. def _gen_cache_key(
  318. self, anon_map: anon_map, bindparams: List[BindParameter[Any]]
  319. ) -> Tuple[Any, ...]:
  320. if self._annotations:
  321. return (self,) + self._annotations_cache_key
  322. else:
  323. return (self,)
  324. if not typing.TYPE_CHECKING:
  325. # typing tools seem to be inconsistent in how they handle
  326. # __new__, so suggest this pattern for classes that use
  327. # __new__. apply typing to the __init__ method normally
  328. @util.deprecated_params(
  329. mustexist=(
  330. "1.4",
  331. "Deprecated alias of :paramref:`_schema.Table.must_exist`",
  332. ),
  333. )
  334. def __new__(cls, *args: Any, **kw: Any) -> Any:
  335. return cls._new(*args, **kw)
  336. @classmethod
  337. def _new(cls, *args: Any, **kw: Any) -> Any:
  338. if not args and not kw:
  339. # python3k pickle seems to call this
  340. return object.__new__(cls)
  341. try:
  342. name, metadata, args = args[0], args[1], args[2:]
  343. except IndexError:
  344. raise TypeError(
  345. "Table() takes at least two positional-only "
  346. "arguments 'name' and 'metadata'"
  347. )
  348. schema = kw.get("schema", None)
  349. if schema is None:
  350. schema = metadata.schema
  351. elif schema is BLANK_SCHEMA:
  352. schema = None
  353. keep_existing = kw.get("keep_existing", False)
  354. extend_existing = kw.get("extend_existing", False)
  355. if keep_existing and extend_existing:
  356. msg = "keep_existing and extend_existing are mutually exclusive."
  357. raise exc.ArgumentError(msg)
  358. must_exist = kw.pop("must_exist", kw.pop("mustexist", False))
  359. key = _get_table_key(name, schema)
  360. if key in metadata.tables:
  361. if not keep_existing and not extend_existing and bool(args):
  362. raise exc.InvalidRequestError(
  363. f"Table '{key}' is already defined for this MetaData "
  364. "instance. Specify 'extend_existing=True' "
  365. "to redefine "
  366. "options and columns on an "
  367. "existing Table object."
  368. )
  369. table = metadata.tables[key]
  370. if extend_existing:
  371. table._init_existing(*args, **kw)
  372. return table
  373. else:
  374. if must_exist:
  375. raise exc.InvalidRequestError(f"Table '{key}' not defined")
  376. table = object.__new__(cls)
  377. table.dispatch.before_parent_attach(table, metadata)
  378. metadata._add_table(name, schema, table)
  379. try:
  380. table.__init__(name, metadata, *args, _no_init=False, **kw)
  381. table.dispatch.after_parent_attach(table, metadata)
  382. return table
  383. except Exception:
  384. with util.safe_reraise():
  385. metadata._remove_table(name, schema)
  386. def __init__(
  387. self,
  388. name: str,
  389. metadata: MetaData,
  390. *args: SchemaItem,
  391. schema: Optional[Union[str, Literal[SchemaConst.BLANK_SCHEMA]]] = None,
  392. quote: Optional[bool] = None,
  393. quote_schema: Optional[bool] = None,
  394. autoload_with: Optional[Union[Engine, Connection]] = None,
  395. autoload_replace: bool = True,
  396. keep_existing: bool = False,
  397. extend_existing: bool = False,
  398. resolve_fks: bool = True,
  399. include_columns: Optional[Collection[str]] = None,
  400. implicit_returning: bool = True,
  401. comment: Optional[str] = None,
  402. info: Optional[Dict[Any, Any]] = None,
  403. listeners: Optional[
  404. _typing_Sequence[Tuple[str, Callable[..., Any]]]
  405. ] = None,
  406. prefixes: Optional[_typing_Sequence[str]] = None,
  407. # used internally in the metadata.reflect() process
  408. _extend_on: Optional[Set[Table]] = None,
  409. # used by __new__ to bypass __init__
  410. _no_init: bool = True,
  411. # dialect-specific keyword args
  412. **kw: Any,
  413. ) -> None:
  414. r"""Constructor for :class:`_schema.Table`.
  415. :param name: The name of this table as represented in the database.
  416. The table name, along with the value of the ``schema`` parameter,
  417. forms a key which uniquely identifies this :class:`_schema.Table`
  418. within
  419. the owning :class:`_schema.MetaData` collection.
  420. Additional calls to :class:`_schema.Table` with the same name,
  421. metadata,
  422. and schema name will return the same :class:`_schema.Table` object.
  423. Names which contain no upper case characters
  424. will be treated as case insensitive names, and will not be quoted
  425. unless they are a reserved word or contain special characters.
  426. A name with any number of upper case characters is considered
  427. to be case sensitive, and will be sent as quoted.
  428. To enable unconditional quoting for the table name, specify the flag
  429. ``quote=True`` to the constructor, or use the :class:`.quoted_name`
  430. construct to specify the name.
  431. :param metadata: a :class:`_schema.MetaData`
  432. object which will contain this
  433. table. The metadata is used as a point of association of this table
  434. with other tables which are referenced via foreign key. It also
  435. may be used to associate this table with a particular
  436. :class:`.Connection` or :class:`.Engine`.
  437. :param \*args: Additional positional arguments are used primarily
  438. to add the list of :class:`_schema.Column`
  439. objects contained within this
  440. table. Similar to the style of a CREATE TABLE statement, other
  441. :class:`.SchemaItem` constructs may be added here, including
  442. :class:`.PrimaryKeyConstraint`, and
  443. :class:`_schema.ForeignKeyConstraint`.
  444. :param autoload_replace: Defaults to ``True``; when using
  445. :paramref:`_schema.Table.autoload_with`
  446. in conjunction with :paramref:`_schema.Table.extend_existing`,
  447. indicates
  448. that :class:`_schema.Column` objects present in the already-existing
  449. :class:`_schema.Table`
  450. object should be replaced with columns of the same
  451. name retrieved from the autoload process. When ``False``, columns
  452. already present under existing names will be omitted from the
  453. reflection process.
  454. Note that this setting does not impact :class:`_schema.Column` objects
  455. specified programmatically within the call to :class:`_schema.Table`
  456. that
  457. also is autoloading; those :class:`_schema.Column` objects will always
  458. replace existing columns of the same name when
  459. :paramref:`_schema.Table.extend_existing` is ``True``.
  460. .. seealso::
  461. :paramref:`_schema.Table.autoload_with`
  462. :paramref:`_schema.Table.extend_existing`
  463. :param autoload_with: An :class:`_engine.Engine` or
  464. :class:`_engine.Connection` object,
  465. or a :class:`_reflection.Inspector` object as returned by
  466. :func:`_sa.inspect`
  467. against one, with which this :class:`_schema.Table`
  468. object will be reflected.
  469. When set to a non-None value, the autoload process will take place
  470. for this table against the given engine or connection.
  471. .. seealso::
  472. :ref:`metadata_reflection_toplevel`
  473. :meth:`_events.DDLEvents.column_reflect`
  474. :ref:`metadata_reflection_dbagnostic_types`
  475. :param extend_existing: When ``True``, indicates that if this
  476. :class:`_schema.Table` is already present in the given
  477. :class:`_schema.MetaData`,
  478. apply further arguments within the constructor to the existing
  479. :class:`_schema.Table`.
  480. If :paramref:`_schema.Table.extend_existing` or
  481. :paramref:`_schema.Table.keep_existing` are not set,
  482. and the given name
  483. of the new :class:`_schema.Table` refers to a :class:`_schema.Table`
  484. that is
  485. already present in the target :class:`_schema.MetaData` collection,
  486. and
  487. this :class:`_schema.Table`
  488. specifies additional columns or other constructs
  489. or flags that modify the table's state, an
  490. error is raised. The purpose of these two mutually-exclusive flags
  491. is to specify what action should be taken when a
  492. :class:`_schema.Table`
  493. is specified that matches an existing :class:`_schema.Table`,
  494. yet specifies
  495. additional constructs.
  496. :paramref:`_schema.Table.extend_existing`
  497. will also work in conjunction
  498. with :paramref:`_schema.Table.autoload_with` to run a new reflection
  499. operation against the database, even if a :class:`_schema.Table`
  500. of the same name is already present in the target
  501. :class:`_schema.MetaData`; newly reflected :class:`_schema.Column`
  502. objects
  503. and other options will be added into the state of the
  504. :class:`_schema.Table`, potentially overwriting existing columns
  505. and options of the same name.
  506. As is always the case with :paramref:`_schema.Table.autoload_with`,
  507. :class:`_schema.Column` objects can be specified in the same
  508. :class:`_schema.Table`
  509. constructor, which will take precedence. Below, the existing
  510. table ``mytable`` will be augmented with :class:`_schema.Column`
  511. objects
  512. both reflected from the database, as well as the given
  513. :class:`_schema.Column`
  514. named "y"::
  515. Table("mytable", metadata,
  516. Column('y', Integer),
  517. extend_existing=True,
  518. autoload_with=engine
  519. )
  520. .. seealso::
  521. :paramref:`_schema.Table.autoload_with`
  522. :paramref:`_schema.Table.autoload_replace`
  523. :paramref:`_schema.Table.keep_existing`
  524. :param implicit_returning: True by default - indicates that
  525. RETURNING can be used, typically by the ORM, in order to fetch
  526. server-generated values such as primary key values and
  527. server side defaults, on those backends which support RETURNING.
  528. In modern SQLAlchemy there is generally no reason to alter this
  529. setting, except for some backend specific cases
  530. (see :ref:`mssql_triggers` in the SQL Server dialect documentation
  531. for one such example).
  532. :param include_columns: A list of strings indicating a subset of
  533. columns to be loaded via the ``autoload`` operation; table columns who
  534. aren't present in this list will not be represented on the resulting
  535. ``Table`` object. Defaults to ``None`` which indicates all columns
  536. should be reflected.
  537. :param resolve_fks: Whether or not to reflect :class:`_schema.Table`
  538. objects
  539. related to this one via :class:`_schema.ForeignKey` objects, when
  540. :paramref:`_schema.Table.autoload_with` is
  541. specified. Defaults to True. Set to False to disable reflection of
  542. related tables as :class:`_schema.ForeignKey`
  543. objects are encountered; may be
  544. used either to save on SQL calls or to avoid issues with related tables
  545. that can't be accessed. Note that if a related table is already present
  546. in the :class:`_schema.MetaData` collection, or becomes present later,
  547. a
  548. :class:`_schema.ForeignKey` object associated with this
  549. :class:`_schema.Table` will
  550. resolve to that table normally.
  551. .. versionadded:: 1.3
  552. .. seealso::
  553. :paramref:`.MetaData.reflect.resolve_fks`
  554. :param info: Optional data dictionary which will be populated into the
  555. :attr:`.SchemaItem.info` attribute of this object.
  556. :param keep_existing: When ``True``, indicates that if this Table
  557. is already present in the given :class:`_schema.MetaData`, ignore
  558. further arguments within the constructor to the existing
  559. :class:`_schema.Table`, and return the :class:`_schema.Table`
  560. object as
  561. originally created. This is to allow a function that wishes
  562. to define a new :class:`_schema.Table` on first call, but on
  563. subsequent calls will return the same :class:`_schema.Table`,
  564. without any of the declarations (particularly constraints)
  565. being applied a second time.
  566. If :paramref:`_schema.Table.extend_existing` or
  567. :paramref:`_schema.Table.keep_existing` are not set,
  568. and the given name
  569. of the new :class:`_schema.Table` refers to a :class:`_schema.Table`
  570. that is
  571. already present in the target :class:`_schema.MetaData` collection,
  572. and
  573. this :class:`_schema.Table`
  574. specifies additional columns or other constructs
  575. or flags that modify the table's state, an
  576. error is raised. The purpose of these two mutually-exclusive flags
  577. is to specify what action should be taken when a
  578. :class:`_schema.Table`
  579. is specified that matches an existing :class:`_schema.Table`,
  580. yet specifies
  581. additional constructs.
  582. .. seealso::
  583. :paramref:`_schema.Table.extend_existing`
  584. :param listeners: A list of tuples of the form ``(<eventname>, <fn>)``
  585. which will be passed to :func:`.event.listen` upon construction.
  586. This alternate hook to :func:`.event.listen` allows the establishment
  587. of a listener function specific to this :class:`_schema.Table` before
  588. the "autoload" process begins. Historically this has been intended
  589. for use with the :meth:`.DDLEvents.column_reflect` event, however
  590. note that this event hook may now be associated with the
  591. :class:`_schema.MetaData` object directly::
  592. def listen_for_reflect(table, column_info):
  593. "handle the column reflection event"
  594. # ...
  595. t = Table(
  596. 'sometable',
  597. autoload_with=engine,
  598. listeners=[
  599. ('column_reflect', listen_for_reflect)
  600. ])
  601. .. seealso::
  602. :meth:`_events.DDLEvents.column_reflect`
  603. :param must_exist: When ``True``, indicates that this Table must already
  604. be present in the given :class:`_schema.MetaData` collection, else
  605. an exception is raised.
  606. :param prefixes:
  607. A list of strings to insert after CREATE in the CREATE TABLE
  608. statement. They will be separated by spaces.
  609. :param quote: Force quoting of this table's name on or off, corresponding
  610. to ``True`` or ``False``. When left at its default of ``None``,
  611. the column identifier will be quoted according to whether the name is
  612. case sensitive (identifiers with at least one upper case character are
  613. treated as case sensitive), or if it's a reserved word. This flag
  614. is only needed to force quoting of a reserved word which is not known
  615. by the SQLAlchemy dialect.
  616. .. note:: setting this flag to ``False`` will not provide
  617. case-insensitive behavior for table reflection; table reflection
  618. will always search for a mixed-case name in a case sensitive
  619. fashion. Case insensitive names are specified in SQLAlchemy only
  620. by stating the name with all lower case characters.
  621. :param quote_schema: same as 'quote' but applies to the schema identifier.
  622. :param schema: The schema name for this table, which is required if
  623. the table resides in a schema other than the default selected schema
  624. for the engine's database connection. Defaults to ``None``.
  625. If the owning :class:`_schema.MetaData` of this :class:`_schema.Table`
  626. specifies its
  627. own :paramref:`_schema.MetaData.schema` parameter,
  628. then that schema name will
  629. be applied to this :class:`_schema.Table`
  630. if the schema parameter here is set
  631. to ``None``. To set a blank schema name on a :class:`_schema.Table`
  632. that
  633. would otherwise use the schema set on the owning
  634. :class:`_schema.MetaData`,
  635. specify the special symbol :attr:`.BLANK_SCHEMA`.
  636. The quoting rules for the schema name are the same as those for the
  637. ``name`` parameter, in that quoting is applied for reserved words or
  638. case-sensitive names; to enable unconditional quoting for the schema
  639. name, specify the flag ``quote_schema=True`` to the constructor, or use
  640. the :class:`.quoted_name` construct to specify the name.
  641. :param comment: Optional string that will render an SQL comment on table
  642. creation.
  643. .. versionadded:: 1.2 Added the :paramref:`_schema.Table.comment`
  644. parameter
  645. to :class:`_schema.Table`.
  646. :param \**kw: Additional keyword arguments not mentioned above are
  647. dialect specific, and passed in the form ``<dialectname>_<argname>``.
  648. See the documentation regarding an individual dialect at
  649. :ref:`dialect_toplevel` for detail on documented arguments.
  650. """ # noqa: E501
  651. if _no_init:
  652. # don't run __init__ from __new__ by default;
  653. # __new__ has a specific place that __init__ is called
  654. return
  655. super().__init__(quoted_name(name, quote))
  656. self.metadata = metadata
  657. if schema is None:
  658. self.schema = metadata.schema
  659. elif schema is BLANK_SCHEMA:
  660. self.schema = None
  661. else:
  662. quote_schema = quote_schema
  663. assert isinstance(schema, str)
  664. self.schema = quoted_name(schema, quote_schema)
  665. self._sentinel_column = None
  666. self.indexes = set()
  667. self.constraints = set()
  668. PrimaryKeyConstraint(
  669. _implicit_generated=True
  670. )._set_parent_with_dispatch(self)
  671. self.foreign_keys = set() # type: ignore
  672. self._extra_dependencies: Set[Table] = set()
  673. if self.schema is not None:
  674. self.fullname = "%s.%s" % (self.schema, self.name)
  675. else:
  676. self.fullname = self.name
  677. self.implicit_returning = implicit_returning
  678. _reflect_info = kw.pop("_reflect_info", None)
  679. self.comment = comment
  680. if info is not None:
  681. self.info = info
  682. if listeners is not None:
  683. for evt, fn in listeners:
  684. event.listen(self, evt, fn)
  685. self._prefixes = prefixes if prefixes else []
  686. self._extra_kwargs(**kw)
  687. # load column definitions from the database if 'autoload' is defined
  688. # we do it after the table is in the singleton dictionary to support
  689. # circular foreign keys
  690. if autoload_with is not None:
  691. self._autoload(
  692. metadata,
  693. autoload_with,
  694. include_columns,
  695. _extend_on=_extend_on,
  696. _reflect_info=_reflect_info,
  697. resolve_fks=resolve_fks,
  698. )
  699. # initialize all the column, etc. objects. done after reflection to
  700. # allow user-overrides
  701. self._init_items(
  702. *args,
  703. allow_replacements=extend_existing
  704. or keep_existing
  705. or autoload_with,
  706. all_names={},
  707. )
  708. def _autoload(
  709. self,
  710. metadata: MetaData,
  711. autoload_with: Union[Engine, Connection],
  712. include_columns: Optional[Collection[str]],
  713. exclude_columns: Collection[str] = (),
  714. resolve_fks: bool = True,
  715. _extend_on: Optional[Set[Table]] = None,
  716. _reflect_info: _ReflectionInfo | None = None,
  717. ) -> None:
  718. insp = inspection.inspect(autoload_with)
  719. with insp._inspection_context() as conn_insp:
  720. conn_insp.reflect_table(
  721. self,
  722. include_columns,
  723. exclude_columns,
  724. resolve_fks,
  725. _extend_on=_extend_on,
  726. _reflect_info=_reflect_info,
  727. )
  728. @property
  729. def _sorted_constraints(self) -> List[Constraint]:
  730. """Return the set of constraints as a list, sorted by creation
  731. order.
  732. """
  733. return sorted(self.constraints, key=lambda c: c._creation_order)
  734. @property
  735. def foreign_key_constraints(self) -> Set[ForeignKeyConstraint]:
  736. """:class:`_schema.ForeignKeyConstraint` objects referred to by this
  737. :class:`_schema.Table`.
  738. This list is produced from the collection of
  739. :class:`_schema.ForeignKey`
  740. objects currently associated.
  741. .. seealso::
  742. :attr:`_schema.Table.constraints`
  743. :attr:`_schema.Table.foreign_keys`
  744. :attr:`_schema.Table.indexes`
  745. """
  746. return {
  747. fkc.constraint
  748. for fkc in self.foreign_keys
  749. if fkc.constraint is not None
  750. }
  751. def _init_existing(self, *args: Any, **kwargs: Any) -> None:
  752. autoload_with = kwargs.pop("autoload_with", None)
  753. autoload = kwargs.pop("autoload", autoload_with is not None)
  754. autoload_replace = kwargs.pop("autoload_replace", True)
  755. schema = kwargs.pop("schema", None)
  756. _extend_on = kwargs.pop("_extend_on", None)
  757. _reflect_info = kwargs.pop("_reflect_info", None)
  758. # these arguments are only used with _init()
  759. extend_existing = kwargs.pop("extend_existing", False)
  760. keep_existing = kwargs.pop("keep_existing", False)
  761. assert extend_existing
  762. assert not keep_existing
  763. if schema and schema != self.schema:
  764. raise exc.ArgumentError(
  765. f"Can't change schema of existing table "
  766. f"from '{self.schema}' to '{schema}'",
  767. )
  768. include_columns = kwargs.pop("include_columns", None)
  769. if include_columns is not None:
  770. for c in self.c:
  771. if c.name not in include_columns:
  772. self._columns.remove(c)
  773. resolve_fks = kwargs.pop("resolve_fks", True)
  774. for key in ("quote", "quote_schema"):
  775. if key in kwargs:
  776. raise exc.ArgumentError(
  777. "Can't redefine 'quote' or 'quote_schema' arguments"
  778. )
  779. # update `self` with these kwargs, if provided
  780. self.comment = kwargs.pop("comment", self.comment)
  781. self.implicit_returning = kwargs.pop(
  782. "implicit_returning", self.implicit_returning
  783. )
  784. self.info = kwargs.pop("info", self.info)
  785. exclude_columns: _typing_Sequence[str]
  786. if autoload:
  787. if not autoload_replace:
  788. # don't replace columns already present.
  789. # we'd like to do this for constraints also however we don't
  790. # have simple de-duping for unnamed constraints.
  791. exclude_columns = [c.name for c in self.c]
  792. else:
  793. exclude_columns = ()
  794. self._autoload(
  795. self.metadata,
  796. autoload_with,
  797. include_columns,
  798. exclude_columns,
  799. resolve_fks,
  800. _extend_on=_extend_on,
  801. _reflect_info=_reflect_info,
  802. )
  803. all_names = {c.name: c for c in self.c}
  804. self._extra_kwargs(**kwargs)
  805. self._init_items(*args, allow_replacements=True, all_names=all_names)
  806. def _extra_kwargs(self, **kwargs: Any) -> None:
  807. self._validate_dialect_kwargs(kwargs)
  808. def _init_collections(self) -> None:
  809. pass
  810. def _reset_exported(self) -> None:
  811. pass
  812. @util.ro_non_memoized_property
  813. def _autoincrement_column(self) -> Optional[Column[int]]:
  814. return self.primary_key._autoincrement_column
  815. @util.ro_memoized_property
  816. def _sentinel_column_characteristics(
  817. self,
  818. ) -> _SentinelColumnCharacterization:
  819. """determine a candidate column (or columns, in case of a client
  820. generated composite primary key) which can be used as an
  821. "insert sentinel" for an INSERT statement.
  822. The returned structure, :class:`_SentinelColumnCharacterization`,
  823. includes all the details needed by :class:`.Dialect` and
  824. :class:`.SQLCompiler` to determine if these column(s) can be used
  825. as an INSERT..RETURNING sentinel for a particular database
  826. dialect.
  827. .. versionadded:: 2.0.10
  828. """
  829. sentinel_is_explicit = False
  830. sentinel_is_autoinc = False
  831. the_sentinel: Optional[_typing_Sequence[Column[Any]]] = None
  832. # see if a column was explicitly marked "insert_sentinel=True".
  833. explicit_sentinel_col = self._sentinel_column
  834. if explicit_sentinel_col is not None:
  835. the_sentinel = (explicit_sentinel_col,)
  836. sentinel_is_explicit = True
  837. autoinc_col = self._autoincrement_column
  838. if sentinel_is_explicit and explicit_sentinel_col is autoinc_col:
  839. assert autoinc_col is not None
  840. sentinel_is_autoinc = True
  841. elif explicit_sentinel_col is None and autoinc_col is not None:
  842. the_sentinel = (autoinc_col,)
  843. sentinel_is_autoinc = True
  844. default_characterization = _SentinelDefaultCharacterization.UNKNOWN
  845. if the_sentinel:
  846. the_sentinel_zero = the_sentinel[0]
  847. if the_sentinel_zero.identity:
  848. if the_sentinel_zero.identity._increment_is_negative:
  849. if sentinel_is_explicit:
  850. raise exc.InvalidRequestError(
  851. "Can't use IDENTITY default with negative "
  852. "increment as an explicit sentinel column"
  853. )
  854. else:
  855. if sentinel_is_autoinc:
  856. autoinc_col = None
  857. sentinel_is_autoinc = False
  858. the_sentinel = None
  859. else:
  860. default_characterization = (
  861. _SentinelDefaultCharacterization.IDENTITY
  862. )
  863. elif (
  864. the_sentinel_zero.default is None
  865. and the_sentinel_zero.server_default is None
  866. ):
  867. if the_sentinel_zero.nullable:
  868. raise exc.InvalidRequestError(
  869. f"Column {the_sentinel_zero} has been marked as a "
  870. "sentinel "
  871. "column with no default generation function; it "
  872. "at least needs to be marked nullable=False assuming "
  873. "user-populated sentinel values will be used."
  874. )
  875. default_characterization = (
  876. _SentinelDefaultCharacterization.NONE
  877. )
  878. elif the_sentinel_zero.default is not None:
  879. if the_sentinel_zero.default.is_sentinel:
  880. default_characterization = (
  881. _SentinelDefaultCharacterization.SENTINEL_DEFAULT
  882. )
  883. elif default_is_sequence(the_sentinel_zero.default):
  884. if the_sentinel_zero.default._increment_is_negative:
  885. if sentinel_is_explicit:
  886. raise exc.InvalidRequestError(
  887. "Can't use SEQUENCE default with negative "
  888. "increment as an explicit sentinel column"
  889. )
  890. else:
  891. if sentinel_is_autoinc:
  892. autoinc_col = None
  893. sentinel_is_autoinc = False
  894. the_sentinel = None
  895. default_characterization = (
  896. _SentinelDefaultCharacterization.SEQUENCE
  897. )
  898. elif the_sentinel_zero.default.is_callable:
  899. default_characterization = (
  900. _SentinelDefaultCharacterization.CLIENTSIDE
  901. )
  902. elif the_sentinel_zero.server_default is not None:
  903. if sentinel_is_explicit:
  904. raise exc.InvalidRequestError(
  905. f"Column {the_sentinel[0]} can't be a sentinel column "
  906. "because it uses an explicit server side default "
  907. "that's not the Identity() default."
  908. )
  909. default_characterization = (
  910. _SentinelDefaultCharacterization.SERVERSIDE
  911. )
  912. if the_sentinel is None and self.primary_key:
  913. assert autoinc_col is None
  914. # determine for non-autoincrement pk if all elements are
  915. # client side
  916. for _pkc in self.primary_key:
  917. if _pkc.server_default is not None or (
  918. _pkc.default and not _pkc.default.is_callable
  919. ):
  920. break
  921. else:
  922. the_sentinel = tuple(self.primary_key)
  923. default_characterization = (
  924. _SentinelDefaultCharacterization.CLIENTSIDE
  925. )
  926. return _SentinelColumnCharacterization(
  927. the_sentinel,
  928. sentinel_is_explicit,
  929. sentinel_is_autoinc,
  930. default_characterization,
  931. )
  932. @property
  933. def autoincrement_column(self) -> Optional[Column[int]]:
  934. """Returns the :class:`.Column` object which currently represents
  935. the "auto increment" column, if any, else returns None.
  936. This is based on the rules for :class:`.Column` as defined by the
  937. :paramref:`.Column.autoincrement` parameter, which generally means the
  938. column within a single integer column primary key constraint that is
  939. not constrained by a foreign key. If the table does not have such
  940. a primary key constraint, then there's no "autoincrement" column.
  941. A :class:`.Table` may have only one column defined as the
  942. "autoincrement" column.
  943. .. versionadded:: 2.0.4
  944. .. seealso::
  945. :paramref:`.Column.autoincrement`
  946. """
  947. return self._autoincrement_column
  948. @property
  949. def key(self) -> str:
  950. """Return the 'key' for this :class:`_schema.Table`.
  951. This value is used as the dictionary key within the
  952. :attr:`_schema.MetaData.tables` collection. It is typically the same
  953. as that of :attr:`_schema.Table.name` for a table with no
  954. :attr:`_schema.Table.schema`
  955. set; otherwise it is typically of the form
  956. ``schemaname.tablename``.
  957. """
  958. return _get_table_key(self.name, self.schema)
  959. def __repr__(self) -> str:
  960. return "Table(%s)" % ", ".join(
  961. [repr(self.name)]
  962. + [repr(self.metadata)]
  963. + [repr(x) for x in self.columns]
  964. + ["%s=%s" % (k, repr(getattr(self, k))) for k in ["schema"]]
  965. )
  966. def __str__(self) -> str:
  967. return _get_table_key(self.description, self.schema)
  968. def add_is_dependent_on(self, table: Table) -> None:
  969. """Add a 'dependency' for this Table.
  970. This is another Table object which must be created
  971. first before this one can, or dropped after this one.
  972. Usually, dependencies between tables are determined via
  973. ForeignKey objects. However, for other situations that
  974. create dependencies outside of foreign keys (rules, inheriting),
  975. this method can manually establish such a link.
  976. """
  977. self._extra_dependencies.add(table)
  978. def append_column(
  979. self, column: ColumnClause[Any], replace_existing: bool = False
  980. ) -> None:
  981. """Append a :class:`_schema.Column` to this :class:`_schema.Table`.
  982. The "key" of the newly added :class:`_schema.Column`, i.e. the
  983. value of its ``.key`` attribute, will then be available
  984. in the ``.c`` collection of this :class:`_schema.Table`, and the
  985. column definition will be included in any CREATE TABLE, SELECT,
  986. UPDATE, etc. statements generated from this :class:`_schema.Table`
  987. construct.
  988. Note that this does **not** change the definition of the table
  989. as it exists within any underlying database, assuming that
  990. table has already been created in the database. Relational
  991. databases support the addition of columns to existing tables
  992. using the SQL ALTER command, which would need to be
  993. emitted for an already-existing table that doesn't contain
  994. the newly added column.
  995. :param replace_existing: When ``True``, allows replacing existing
  996. columns. When ``False``, the default, an warning will be raised
  997. if a column with the same ``.key`` already exists. A future
  998. version of sqlalchemy will instead rise a warning.
  999. .. versionadded:: 1.4.0
  1000. """
  1001. try:
  1002. column._set_parent_with_dispatch(
  1003. self,
  1004. allow_replacements=replace_existing,
  1005. all_names={c.name: c for c in self.c},
  1006. )
  1007. except exc.DuplicateColumnError as de:
  1008. raise exc.DuplicateColumnError(
  1009. f"{de.args[0]} Specify replace_existing=True to "
  1010. "Table.append_column() to replace an "
  1011. "existing column."
  1012. ) from de
  1013. def append_constraint(self, constraint: Union[Index, Constraint]) -> None:
  1014. """Append a :class:`_schema.Constraint` to this
  1015. :class:`_schema.Table`.
  1016. This has the effect of the constraint being included in any
  1017. future CREATE TABLE statement, assuming specific DDL creation
  1018. events have not been associated with the given
  1019. :class:`_schema.Constraint` object.
  1020. Note that this does **not** produce the constraint within the
  1021. relational database automatically, for a table that already exists
  1022. in the database. To add a constraint to an
  1023. existing relational database table, the SQL ALTER command must
  1024. be used. SQLAlchemy also provides the
  1025. :class:`.AddConstraint` construct which can produce this SQL when
  1026. invoked as an executable clause.
  1027. """
  1028. constraint._set_parent_with_dispatch(self)
  1029. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  1030. metadata = parent
  1031. assert isinstance(metadata, MetaData)
  1032. metadata._add_table(self.name, self.schema, self)
  1033. self.metadata = metadata
  1034. def create(self, bind: _CreateDropBind, checkfirst: bool = False) -> None:
  1035. """Issue a ``CREATE`` statement for this
  1036. :class:`_schema.Table`, using the given
  1037. :class:`.Connection` or :class:`.Engine`
  1038. for connectivity.
  1039. .. seealso::
  1040. :meth:`_schema.MetaData.create_all`.
  1041. """
  1042. bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
  1043. def drop(self, bind: _CreateDropBind, checkfirst: bool = False) -> None:
  1044. """Issue a ``DROP`` statement for this
  1045. :class:`_schema.Table`, using the given
  1046. :class:`.Connection` or :class:`.Engine` for connectivity.
  1047. .. seealso::
  1048. :meth:`_schema.MetaData.drop_all`.
  1049. """
  1050. bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
  1051. @util.deprecated(
  1052. "1.4",
  1053. ":meth:`_schema.Table.tometadata` is renamed to "
  1054. ":meth:`_schema.Table.to_metadata`",
  1055. )
  1056. def tometadata(
  1057. self,
  1058. metadata: MetaData,
  1059. schema: Union[str, Literal[SchemaConst.RETAIN_SCHEMA]] = RETAIN_SCHEMA,
  1060. referred_schema_fn: Optional[
  1061. Callable[
  1062. [Table, Optional[str], ForeignKeyConstraint, Optional[str]],
  1063. Optional[str],
  1064. ]
  1065. ] = None,
  1066. name: Optional[str] = None,
  1067. ) -> Table:
  1068. """Return a copy of this :class:`_schema.Table`
  1069. associated with a different
  1070. :class:`_schema.MetaData`.
  1071. See :meth:`_schema.Table.to_metadata` for a full description.
  1072. """
  1073. return self.to_metadata(
  1074. metadata,
  1075. schema=schema,
  1076. referred_schema_fn=referred_schema_fn,
  1077. name=name,
  1078. )
  1079. def to_metadata(
  1080. self,
  1081. metadata: MetaData,
  1082. schema: Union[str, Literal[SchemaConst.RETAIN_SCHEMA]] = RETAIN_SCHEMA,
  1083. referred_schema_fn: Optional[
  1084. Callable[
  1085. [Table, Optional[str], ForeignKeyConstraint, Optional[str]],
  1086. Optional[str],
  1087. ]
  1088. ] = None,
  1089. name: Optional[str] = None,
  1090. ) -> Table:
  1091. """Return a copy of this :class:`_schema.Table` associated with a
  1092. different :class:`_schema.MetaData`.
  1093. E.g.::
  1094. m1 = MetaData()
  1095. user = Table('user', m1, Column('id', Integer, primary_key=True))
  1096. m2 = MetaData()
  1097. user_copy = user.to_metadata(m2)
  1098. .. versionchanged:: 1.4 The :meth:`_schema.Table.to_metadata` function
  1099. was renamed from :meth:`_schema.Table.tometadata`.
  1100. :param metadata: Target :class:`_schema.MetaData` object,
  1101. into which the
  1102. new :class:`_schema.Table` object will be created.
  1103. :param schema: optional string name indicating the target schema.
  1104. Defaults to the special symbol :attr:`.RETAIN_SCHEMA` which indicates
  1105. that no change to the schema name should be made in the new
  1106. :class:`_schema.Table`. If set to a string name, the new
  1107. :class:`_schema.Table`
  1108. will have this new name as the ``.schema``. If set to ``None``, the
  1109. schema will be set to that of the schema set on the target
  1110. :class:`_schema.MetaData`, which is typically ``None`` as well,
  1111. unless
  1112. set explicitly::
  1113. m2 = MetaData(schema='newschema')
  1114. # user_copy_one will have "newschema" as the schema name
  1115. user_copy_one = user.to_metadata(m2, schema=None)
  1116. m3 = MetaData() # schema defaults to None
  1117. # user_copy_two will have None as the schema name
  1118. user_copy_two = user.to_metadata(m3, schema=None)
  1119. :param referred_schema_fn: optional callable which can be supplied
  1120. in order to provide for the schema name that should be assigned
  1121. to the referenced table of a :class:`_schema.ForeignKeyConstraint`.
  1122. The callable accepts this parent :class:`_schema.Table`, the
  1123. target schema that we are changing to, the
  1124. :class:`_schema.ForeignKeyConstraint` object, and the existing
  1125. "target schema" of that constraint. The function should return the
  1126. string schema name that should be applied. To reset the schema
  1127. to "none", return the symbol :data:`.BLANK_SCHEMA`. To effect no
  1128. change, return ``None`` or :data:`.RETAIN_SCHEMA`.
  1129. .. versionchanged:: 1.4.33 The ``referred_schema_fn`` function
  1130. may return the :data:`.BLANK_SCHEMA` or :data:`.RETAIN_SCHEMA`
  1131. symbols.
  1132. E.g.::
  1133. def referred_schema_fn(table, to_schema,
  1134. constraint, referred_schema):
  1135. if referred_schema == 'base_tables':
  1136. return referred_schema
  1137. else:
  1138. return to_schema
  1139. new_table = table.to_metadata(m2, schema="alt_schema",
  1140. referred_schema_fn=referred_schema_fn)
  1141. :param name: optional string name indicating the target table name.
  1142. If not specified or None, the table name is retained. This allows
  1143. a :class:`_schema.Table` to be copied to the same
  1144. :class:`_schema.MetaData` target
  1145. with a new name.
  1146. """
  1147. if name is None:
  1148. name = self.name
  1149. actual_schema: Optional[str]
  1150. if schema is RETAIN_SCHEMA:
  1151. actual_schema = self.schema
  1152. elif schema is None:
  1153. actual_schema = metadata.schema
  1154. else:
  1155. actual_schema = schema
  1156. key = _get_table_key(name, actual_schema)
  1157. if key in metadata.tables:
  1158. util.warn(
  1159. f"Table '{self.description}' already exists within the given "
  1160. "MetaData - not copying."
  1161. )
  1162. return metadata.tables[key]
  1163. args = []
  1164. for col in self.columns:
  1165. args.append(col._copy(schema=actual_schema))
  1166. table = Table(
  1167. name,
  1168. metadata,
  1169. schema=actual_schema,
  1170. comment=self.comment,
  1171. *args,
  1172. **self.kwargs,
  1173. )
  1174. for const in self.constraints:
  1175. if isinstance(const, ForeignKeyConstraint):
  1176. referred_schema = const._referred_schema
  1177. if referred_schema_fn:
  1178. fk_constraint_schema = referred_schema_fn(
  1179. self, actual_schema, const, referred_schema
  1180. )
  1181. else:
  1182. fk_constraint_schema = (
  1183. actual_schema
  1184. if referred_schema == self.schema
  1185. else None
  1186. )
  1187. table.append_constraint(
  1188. const._copy(
  1189. schema=fk_constraint_schema, target_table=table
  1190. )
  1191. )
  1192. elif not const._type_bound:
  1193. # skip unique constraints that would be generated
  1194. # by the 'unique' flag on Column
  1195. if const._column_flag:
  1196. continue
  1197. table.append_constraint(
  1198. const._copy(schema=actual_schema, target_table=table)
  1199. )
  1200. for index in self.indexes:
  1201. # skip indexes that would be generated
  1202. # by the 'index' flag on Column
  1203. if index._column_flag:
  1204. continue
  1205. Index(
  1206. index.name,
  1207. unique=index.unique,
  1208. *[
  1209. _copy_expression(expr, self, table)
  1210. for expr in index._table_bound_expressions
  1211. ],
  1212. _table=table,
  1213. **index.kwargs,
  1214. )
  1215. return self._schema_item_copy(table)
  1216. class Column(DialectKWArgs, SchemaItem, ColumnClause[_T]):
  1217. """Represents a column in a database table."""
  1218. __visit_name__ = "column"
  1219. inherit_cache = True
  1220. key: str
  1221. server_default: Optional[FetchedValue]
  1222. def __init__(
  1223. self,
  1224. __name_pos: Optional[
  1225. Union[str, _TypeEngineArgument[_T], SchemaEventTarget]
  1226. ] = None,
  1227. __type_pos: Optional[
  1228. Union[_TypeEngineArgument[_T], SchemaEventTarget]
  1229. ] = None,
  1230. *args: SchemaEventTarget,
  1231. name: Optional[str] = None,
  1232. type_: Optional[_TypeEngineArgument[_T]] = None,
  1233. autoincrement: _AutoIncrementType = "auto",
  1234. default: Optional[Any] = None,
  1235. doc: Optional[str] = None,
  1236. key: Optional[str] = None,
  1237. index: Optional[bool] = None,
  1238. unique: Optional[bool] = None,
  1239. info: Optional[_InfoType] = None,
  1240. nullable: Optional[
  1241. Union[bool, Literal[SchemaConst.NULL_UNSPECIFIED]]
  1242. ] = SchemaConst.NULL_UNSPECIFIED,
  1243. onupdate: Optional[Any] = None,
  1244. primary_key: bool = False,
  1245. server_default: Optional[_ServerDefaultArgument] = None,
  1246. server_onupdate: Optional[FetchedValue] = None,
  1247. quote: Optional[bool] = None,
  1248. system: bool = False,
  1249. comment: Optional[str] = None,
  1250. insert_sentinel: bool = False,
  1251. _omit_from_statements: bool = False,
  1252. _proxies: Optional[Any] = None,
  1253. **dialect_kwargs: Any,
  1254. ):
  1255. r"""
  1256. Construct a new ``Column`` object.
  1257. :param name: The name of this column as represented in the database.
  1258. This argument may be the first positional argument, or specified
  1259. via keyword.
  1260. Names which contain no upper case characters
  1261. will be treated as case insensitive names, and will not be quoted
  1262. unless they are a reserved word. Names with any number of upper
  1263. case characters will be quoted and sent exactly. Note that this
  1264. behavior applies even for databases which standardize upper
  1265. case names as case insensitive such as Oracle.
  1266. The name field may be omitted at construction time and applied
  1267. later, at any time before the Column is associated with a
  1268. :class:`_schema.Table`. This is to support convenient
  1269. usage within the :mod:`~sqlalchemy.ext.declarative` extension.
  1270. :param type\_: The column's type, indicated using an instance which
  1271. subclasses :class:`~sqlalchemy.types.TypeEngine`. If no arguments
  1272. are required for the type, the class of the type can be sent
  1273. as well, e.g.::
  1274. # use a type with arguments
  1275. Column('data', String(50))
  1276. # use no arguments
  1277. Column('level', Integer)
  1278. The ``type`` argument may be the second positional argument
  1279. or specified by keyword.
  1280. If the ``type`` is ``None`` or is omitted, it will first default to
  1281. the special type :class:`.NullType`. If and when this
  1282. :class:`_schema.Column` is made to refer to another column using
  1283. :class:`_schema.ForeignKey` and/or
  1284. :class:`_schema.ForeignKeyConstraint`, the type
  1285. of the remote-referenced column will be copied to this column as
  1286. well, at the moment that the foreign key is resolved against that
  1287. remote :class:`_schema.Column` object.
  1288. :param \*args: Additional positional arguments include various
  1289. :class:`.SchemaItem` derived constructs which will be applied
  1290. as options to the column. These include instances of
  1291. :class:`.Constraint`, :class:`_schema.ForeignKey`,
  1292. :class:`.ColumnDefault`, :class:`.Sequence`, :class:`.Computed`
  1293. :class:`.Identity`. In some cases an
  1294. equivalent keyword argument is available such as ``server_default``,
  1295. ``default`` and ``unique``.
  1296. :param autoincrement: Set up "auto increment" semantics for an
  1297. **integer primary key column with no foreign key dependencies**
  1298. (see later in this docstring for a more specific definition).
  1299. This may influence the :term:`DDL` that will be emitted for
  1300. this column during a table create, as well as how the column
  1301. will be considered when INSERT statements are compiled and
  1302. executed.
  1303. The default value is the string ``"auto"``,
  1304. which indicates that a single-column (i.e. non-composite) primary key
  1305. that is of an INTEGER type with no other client-side or server-side
  1306. default constructs indicated should receive auto increment semantics
  1307. automatically. Other values include ``True`` (force this column to
  1308. have auto-increment semantics for a :term:`composite primary key` as
  1309. well), ``False`` (this column should never have auto-increment
  1310. semantics), and the string ``"ignore_fk"`` (special-case for foreign
  1311. key columns, see below).
  1312. The term "auto increment semantics" refers both to the kind of DDL
  1313. that will be emitted for the column within a CREATE TABLE statement,
  1314. when methods such as :meth:`.MetaData.create_all` and
  1315. :meth:`.Table.create` are invoked, as well as how the column will be
  1316. considered when an INSERT statement is compiled and emitted to the
  1317. database:
  1318. * **DDL rendering** (i.e. :meth:`.MetaData.create_all`,
  1319. :meth:`.Table.create`): When used on a :class:`.Column` that has
  1320. no other
  1321. default-generating construct associated with it (such as a
  1322. :class:`.Sequence` or :class:`.Identity` construct), the parameter
  1323. will imply that database-specific keywords such as PostgreSQL
  1324. ``SERIAL``, MySQL ``AUTO_INCREMENT``, or ``IDENTITY`` on SQL Server
  1325. should also be rendered. Not every database backend has an
  1326. "implied" default generator available; for example the Oracle
  1327. backend always needs an explicit construct such as
  1328. :class:`.Identity` to be included with a :class:`.Column` in order
  1329. for the DDL rendered to include auto-generating constructs to also
  1330. be produced in the database.
  1331. * **INSERT semantics** (i.e. when a :func:`_sql.insert` construct is
  1332. compiled into a SQL string and is then executed on a database using
  1333. :meth:`_engine.Connection.execute` or equivalent): A single-row
  1334. INSERT statement will be known to produce a new integer primary key
  1335. value automatically for this column, which will be accessible
  1336. after the statement is invoked via the
  1337. :attr:`.CursorResult.inserted_primary_key` attribute upon the
  1338. :class:`_result.Result` object. This also applies towards use of the
  1339. ORM when ORM-mapped objects are persisted to the database,
  1340. indicating that a new integer primary key will be available to
  1341. become part of the :term:`identity key` for that object. This
  1342. behavior takes place regardless of what DDL constructs are
  1343. associated with the :class:`_schema.Column` and is independent
  1344. of the "DDL Rendering" behavior discussed in the previous note
  1345. above.
  1346. The parameter may be set to ``True`` to indicate that a column which
  1347. is part of a composite (i.e. multi-column) primary key should
  1348. have autoincrement semantics, though note that only one column
  1349. within a primary key may have this setting. It can also
  1350. be set to ``True`` to indicate autoincrement semantics on a
  1351. column that has a client-side or server-side default configured,
  1352. however note that not all dialects can accommodate all styles
  1353. of default as an "autoincrement". It can also be
  1354. set to ``False`` on a single-column primary key that has a
  1355. datatype of INTEGER in order to disable auto increment semantics
  1356. for that column.
  1357. The setting *only* has an effect for columns which are:
  1358. * Integer derived (i.e. INT, SMALLINT, BIGINT).
  1359. * Part of the primary key
  1360. * Not referring to another column via :class:`_schema.ForeignKey`,
  1361. unless
  1362. the value is specified as ``'ignore_fk'``::
  1363. # turn on autoincrement for this column despite
  1364. # the ForeignKey()
  1365. Column('id', ForeignKey('other.id'),
  1366. primary_key=True, autoincrement='ignore_fk')
  1367. It is typically not desirable to have "autoincrement" enabled on a
  1368. column that refers to another via foreign key, as such a column is
  1369. required to refer to a value that originates from elsewhere.
  1370. The setting has these effects on columns that meet the
  1371. above criteria:
  1372. * DDL issued for the column, if the column does not already include
  1373. a default generating construct supported by the backend such as
  1374. :class:`.Identity`, will include database-specific
  1375. keywords intended to signify this column as an
  1376. "autoincrement" column for specific backends. Behavior for
  1377. primary SQLAlchemy dialects includes:
  1378. * AUTO INCREMENT on MySQL and MariaDB
  1379. * SERIAL on PostgreSQL
  1380. * IDENTITY on MS-SQL - this occurs even without the
  1381. :class:`.Identity` construct as the
  1382. :paramref:`.Column.autoincrement` parameter pre-dates this
  1383. construct.
  1384. * SQLite - SQLite integer primary key columns are implicitly
  1385. "auto incrementing" and no additional keywords are rendered;
  1386. to render the special SQLite keyword ``AUTOINCREMENT``
  1387. is not included as this is unnecessary and not recommended
  1388. by the database vendor. See the section
  1389. :ref:`sqlite_autoincrement` for more background.
  1390. * Oracle - The Oracle dialect has no default "autoincrement"
  1391. feature available at this time, instead the :class:`.Identity`
  1392. construct is recommended to achieve this (the :class:`.Sequence`
  1393. construct may also be used).
  1394. * Third-party dialects - consult those dialects' documentation
  1395. for details on their specific behaviors.
  1396. * When a single-row :func:`_sql.insert` construct is compiled and
  1397. executed, which does not set the :meth:`_sql.Insert.inline`
  1398. modifier, newly generated primary key values for this column
  1399. will be automatically retrieved upon statement execution
  1400. using a method specific to the database driver in use:
  1401. * MySQL, SQLite - calling upon ``cursor.lastrowid()``
  1402. (see
  1403. `https://www.python.org/dev/peps/pep-0249/#lastrowid
  1404. <https://www.python.org/dev/peps/pep-0249/#lastrowid>`_)
  1405. * PostgreSQL, SQL Server, Oracle - use RETURNING or an equivalent
  1406. construct when rendering an INSERT statement, and then retrieving
  1407. the newly generated primary key values after execution
  1408. * PostgreSQL, Oracle for :class:`_schema.Table` objects that
  1409. set :paramref:`_schema.Table.implicit_returning` to False -
  1410. for a :class:`.Sequence` only, the :class:`.Sequence` is invoked
  1411. explicitly before the INSERT statement takes place so that the
  1412. newly generated primary key value is available to the client
  1413. * SQL Server for :class:`_schema.Table` objects that
  1414. set :paramref:`_schema.Table.implicit_returning` to False -
  1415. the ``SELECT scope_identity()`` construct is used after the
  1416. INSERT statement is invoked to retrieve the newly generated
  1417. primary key value.
  1418. * Third-party dialects - consult those dialects' documentation
  1419. for details on their specific behaviors.
  1420. * For multiple-row :func:`_sql.insert` constructs invoked with
  1421. a list of parameters (i.e. "executemany" semantics), primary-key
  1422. retrieving behaviors are generally disabled, however there may
  1423. be special APIs that may be used to retrieve lists of new
  1424. primary key values for an "executemany", such as the psycopg2
  1425. "fast insertmany" feature. Such features are very new and
  1426. may not yet be well covered in documentation.
  1427. :param default: A scalar, Python callable, or
  1428. :class:`_expression.ColumnElement` expression representing the
  1429. *default value* for this column, which will be invoked upon insert
  1430. if this column is otherwise not specified in the VALUES clause of
  1431. the insert. This is a shortcut to using :class:`.ColumnDefault` as
  1432. a positional argument; see that class for full detail on the
  1433. structure of the argument.
  1434. Contrast this argument to
  1435. :paramref:`_schema.Column.server_default`
  1436. which creates a default generator on the database side.
  1437. .. seealso::
  1438. :ref:`metadata_defaults_toplevel`
  1439. :param doc: optional String that can be used by the ORM or similar
  1440. to document attributes on the Python side. This attribute does
  1441. **not** render SQL comments; use the
  1442. :paramref:`_schema.Column.comment`
  1443. parameter for this purpose.
  1444. :param key: An optional string identifier which will identify this
  1445. ``Column`` object on the :class:`_schema.Table`.
  1446. When a key is provided,
  1447. this is the only identifier referencing the ``Column`` within the
  1448. application, including ORM attribute mapping; the ``name`` field
  1449. is used only when rendering SQL.
  1450. :param index: When ``True``, indicates that a :class:`_schema.Index`
  1451. construct will be automatically generated for this
  1452. :class:`_schema.Column`, which will result in a "CREATE INDEX"
  1453. statement being emitted for the :class:`_schema.Table` when the DDL
  1454. create operation is invoked.
  1455. Using this flag is equivalent to making use of the
  1456. :class:`_schema.Index` construct explicitly at the level of the
  1457. :class:`_schema.Table` construct itself::
  1458. Table(
  1459. "some_table",
  1460. metadata,
  1461. Column("x", Integer),
  1462. Index("ix_some_table_x", "x")
  1463. )
  1464. To add the :paramref:`_schema.Index.unique` flag to the
  1465. :class:`_schema.Index`, set both the
  1466. :paramref:`_schema.Column.unique` and
  1467. :paramref:`_schema.Column.index` flags to True simultaneously,
  1468. which will have the effect of rendering the "CREATE UNIQUE INDEX"
  1469. DDL instruction instead of "CREATE INDEX".
  1470. The name of the index is generated using the
  1471. :ref:`default naming convention <constraint_default_naming_convention>`
  1472. which for the :class:`_schema.Index` construct is of the form
  1473. ``ix_<tablename>_<columnname>``.
  1474. As this flag is intended only as a convenience for the common case
  1475. of adding a single-column, default configured index to a table
  1476. definition, explicit use of the :class:`_schema.Index` construct
  1477. should be preferred for most use cases, including composite indexes
  1478. that encompass more than one column, indexes with SQL expressions
  1479. or ordering, backend-specific index configuration options, and
  1480. indexes that use a specific name.
  1481. .. note:: the :attr:`_schema.Column.index` attribute on
  1482. :class:`_schema.Column`
  1483. **does not indicate** if this column is indexed or not, only
  1484. if this flag was explicitly set here. To view indexes on
  1485. a column, view the :attr:`_schema.Table.indexes` collection
  1486. or use :meth:`_reflection.Inspector.get_indexes`.
  1487. .. seealso::
  1488. :ref:`schema_indexes`
  1489. :ref:`constraint_naming_conventions`
  1490. :paramref:`_schema.Column.unique`
  1491. :param info: Optional data dictionary which will be populated into the
  1492. :attr:`.SchemaItem.info` attribute of this object.
  1493. :param nullable: When set to ``False``, will cause the "NOT NULL"
  1494. phrase to be added when generating DDL for the column. When
  1495. ``True``, will normally generate nothing (in SQL this defaults to
  1496. "NULL"), except in some very specific backend-specific edge cases
  1497. where "NULL" may render explicitly.
  1498. Defaults to ``True`` unless :paramref:`_schema.Column.primary_key`
  1499. is also ``True`` or the column specifies a :class:`_sql.Identity`,
  1500. in which case it defaults to ``False``.
  1501. This parameter is only used when issuing CREATE TABLE statements.
  1502. .. note::
  1503. When the column specifies a :class:`_sql.Identity` this
  1504. parameter is in general ignored by the DDL compiler. The
  1505. PostgreSQL database allows nullable identity column by
  1506. setting this parameter to ``True`` explicitly.
  1507. :param onupdate: A scalar, Python callable, or
  1508. :class:`~sqlalchemy.sql.expression.ClauseElement` representing a
  1509. default value to be applied to the column within UPDATE
  1510. statements, which will be invoked upon update if this column is not
  1511. present in the SET clause of the update. This is a shortcut to
  1512. using :class:`.ColumnDefault` as a positional argument with
  1513. ``for_update=True``.
  1514. .. seealso::
  1515. :ref:`metadata_defaults` - complete discussion of onupdate
  1516. :param primary_key: If ``True``, marks this column as a primary key
  1517. column. Multiple columns can have this flag set to specify
  1518. composite primary keys. As an alternative, the primary key of a
  1519. :class:`_schema.Table` can be specified via an explicit
  1520. :class:`.PrimaryKeyConstraint` object.
  1521. :param server_default: A :class:`.FetchedValue` instance, str, Unicode
  1522. or :func:`~sqlalchemy.sql.expression.text` construct representing
  1523. the DDL DEFAULT value for the column.
  1524. String types will be emitted as-is, surrounded by single quotes::
  1525. Column('x', Text, server_default="val")
  1526. x TEXT DEFAULT 'val'
  1527. A :func:`~sqlalchemy.sql.expression.text` expression will be
  1528. rendered as-is, without quotes::
  1529. Column('y', DateTime, server_default=text('NOW()'))
  1530. y DATETIME DEFAULT NOW()
  1531. Strings and text() will be converted into a
  1532. :class:`.DefaultClause` object upon initialization.
  1533. This parameter can also accept complex combinations of contextually
  1534. valid SQLAlchemy expressions or constructs::
  1535. from sqlalchemy import create_engine
  1536. from sqlalchemy import Table, Column, MetaData, ARRAY, Text
  1537. from sqlalchemy.dialects.postgresql import array
  1538. engine = create_engine(
  1539. 'postgresql+psycopg2://scott:tiger@localhost/mydatabase'
  1540. )
  1541. metadata_obj = MetaData()
  1542. tbl = Table(
  1543. "foo",
  1544. metadata_obj,
  1545. Column("bar",
  1546. ARRAY(Text),
  1547. server_default=array(["biz", "bang", "bash"])
  1548. )
  1549. )
  1550. metadata_obj.create_all(engine)
  1551. The above results in a table created with the following SQL::
  1552. CREATE TABLE foo (
  1553. bar TEXT[] DEFAULT ARRAY['biz', 'bang', 'bash']
  1554. )
  1555. Use :class:`.FetchedValue` to indicate that an already-existing
  1556. column will generate a default value on the database side which
  1557. will be available to SQLAlchemy for post-fetch after inserts. This
  1558. construct does not specify any DDL and the implementation is left
  1559. to the database, such as via a trigger.
  1560. .. seealso::
  1561. :ref:`server_defaults` - complete discussion of server side
  1562. defaults
  1563. :param server_onupdate: A :class:`.FetchedValue` instance
  1564. representing a database-side default generation function,
  1565. such as a trigger. This
  1566. indicates to SQLAlchemy that a newly generated value will be
  1567. available after updates. This construct does not actually
  1568. implement any kind of generation function within the database,
  1569. which instead must be specified separately.
  1570. .. warning:: This directive **does not** currently produce MySQL's
  1571. "ON UPDATE CURRENT_TIMESTAMP()" clause. See
  1572. :ref:`mysql_timestamp_onupdate` for background on how to
  1573. produce this clause.
  1574. .. seealso::
  1575. :ref:`triggered_columns`
  1576. :param quote: Force quoting of this column's name on or off,
  1577. corresponding to ``True`` or ``False``. When left at its default
  1578. of ``None``, the column identifier will be quoted according to
  1579. whether the name is case sensitive (identifiers with at least one
  1580. upper case character are treated as case sensitive), or if it's a
  1581. reserved word. This flag is only needed to force quoting of a
  1582. reserved word which is not known by the SQLAlchemy dialect.
  1583. :param unique: When ``True``, and the :paramref:`_schema.Column.index`
  1584. parameter is left at its default value of ``False``,
  1585. indicates that a :class:`_schema.UniqueConstraint`
  1586. construct will be automatically generated for this
  1587. :class:`_schema.Column`,
  1588. which will result in a "UNIQUE CONSTRAINT" clause referring
  1589. to this column being included
  1590. in the ``CREATE TABLE`` statement emitted, when the DDL create
  1591. operation for the :class:`_schema.Table` object is invoked.
  1592. When this flag is ``True`` while the
  1593. :paramref:`_schema.Column.index` parameter is simultaneously
  1594. set to ``True``, the effect instead is that a
  1595. :class:`_schema.Index` construct which includes the
  1596. :paramref:`_schema.Index.unique` parameter set to ``True``
  1597. is generated. See the documentation for
  1598. :paramref:`_schema.Column.index` for additional detail.
  1599. Using this flag is equivalent to making use of the
  1600. :class:`_schema.UniqueConstraint` construct explicitly at the
  1601. level of the :class:`_schema.Table` construct itself::
  1602. Table(
  1603. "some_table",
  1604. metadata,
  1605. Column("x", Integer),
  1606. UniqueConstraint("x")
  1607. )
  1608. The :paramref:`_schema.UniqueConstraint.name` parameter
  1609. of the unique constraint object is left at its default value
  1610. of ``None``; in the absence of a :ref:`naming convention <constraint_naming_conventions>`
  1611. for the enclosing :class:`_schema.MetaData`, the UNIQUE CONSTRAINT
  1612. construct will be emitted as unnamed, which typically invokes
  1613. a database-specific naming convention to take place.
  1614. As this flag is intended only as a convenience for the common case
  1615. of adding a single-column, default configured unique constraint to a table
  1616. definition, explicit use of the :class:`_schema.UniqueConstraint` construct
  1617. should be preferred for most use cases, including composite constraints
  1618. that encompass more than one column, backend-specific index configuration options, and
  1619. constraints that use a specific name.
  1620. .. note:: the :attr:`_schema.Column.unique` attribute on
  1621. :class:`_schema.Column`
  1622. **does not indicate** if this column has a unique constraint or
  1623. not, only if this flag was explicitly set here. To view
  1624. indexes and unique constraints that may involve this column,
  1625. view the
  1626. :attr:`_schema.Table.indexes` and/or
  1627. :attr:`_schema.Table.constraints` collections or use
  1628. :meth:`_reflection.Inspector.get_indexes` and/or
  1629. :meth:`_reflection.Inspector.get_unique_constraints`
  1630. .. seealso::
  1631. :ref:`schema_unique_constraint`
  1632. :ref:`constraint_naming_conventions`
  1633. :paramref:`_schema.Column.index`
  1634. :param system: When ``True``, indicates this is a "system" column,
  1635. that is a column which is automatically made available by the
  1636. database, and should not be included in the columns list for a
  1637. ``CREATE TABLE`` statement.
  1638. For more elaborate scenarios where columns should be
  1639. conditionally rendered differently on different backends,
  1640. consider custom compilation rules for :class:`.CreateColumn`.
  1641. :param comment: Optional string that will render an SQL comment on
  1642. table creation.
  1643. .. versionadded:: 1.2 Added the
  1644. :paramref:`_schema.Column.comment`
  1645. parameter to :class:`_schema.Column`.
  1646. :param insert_sentinel: Marks this :class:`_schema.Column` as an
  1647. :term:`insert sentinel` used for optimizing the performance of the
  1648. :term:`insertmanyvalues` feature for tables that don't
  1649. otherwise have qualifying primary key configurations.
  1650. .. versionadded:: 2.0.10
  1651. .. seealso::
  1652. :func:`_schema.insert_sentinel` - all in one helper for declaring
  1653. sentinel columns
  1654. :ref:`engine_insertmanyvalues`
  1655. :ref:`engine_insertmanyvalues_sentinel_columns`
  1656. """ # noqa: E501, RST201, RST202
  1657. l_args = [__name_pos, __type_pos] + list(args)
  1658. del args
  1659. if l_args:
  1660. if isinstance(l_args[0], str):
  1661. if name is not None:
  1662. raise exc.ArgumentError(
  1663. "May not pass name positionally and as a keyword."
  1664. )
  1665. name = l_args.pop(0) # type: ignore
  1666. elif l_args[0] is None:
  1667. l_args.pop(0)
  1668. if l_args:
  1669. coltype = l_args[0]
  1670. if hasattr(coltype, "_sqla_type"):
  1671. if type_ is not None:
  1672. raise exc.ArgumentError(
  1673. "May not pass type_ positionally and as a keyword."
  1674. )
  1675. type_ = l_args.pop(0) # type: ignore
  1676. elif l_args[0] is None:
  1677. l_args.pop(0)
  1678. if name is not None:
  1679. name = quoted_name(name, quote)
  1680. elif quote is not None:
  1681. raise exc.ArgumentError(
  1682. "Explicit 'name' is required when " "sending 'quote' argument"
  1683. )
  1684. # name = None is expected to be an interim state
  1685. # note this use case is legacy now that ORM declarative has a
  1686. # dedicated "column" construct local to the ORM
  1687. super().__init__(name, type_) # type: ignore
  1688. self.key = key if key is not None else name # type: ignore
  1689. self.primary_key = primary_key
  1690. self._insert_sentinel = insert_sentinel
  1691. self._omit_from_statements = _omit_from_statements
  1692. self._user_defined_nullable = udn = nullable
  1693. if udn is not NULL_UNSPECIFIED:
  1694. self.nullable = udn
  1695. else:
  1696. self.nullable = not primary_key
  1697. # these default to None because .index and .unique is *not*
  1698. # an informational flag about Column - there can still be an
  1699. # Index or UniqueConstraint referring to this Column.
  1700. self.index = index
  1701. self.unique = unique
  1702. self.system = system
  1703. self.doc = doc
  1704. self.autoincrement: _AutoIncrementType = autoincrement
  1705. self.constraints = set()
  1706. self.foreign_keys = set()
  1707. self.comment = comment
  1708. self.computed = None
  1709. self.identity = None
  1710. # check if this Column is proxying another column
  1711. if _proxies is not None:
  1712. self._proxies = _proxies
  1713. else:
  1714. # otherwise, add DDL-related events
  1715. self._set_type(self.type)
  1716. if default is not None:
  1717. if not isinstance(default, (ColumnDefault, Sequence)):
  1718. default = ColumnDefault(default)
  1719. self.default = default
  1720. l_args.append(default)
  1721. else:
  1722. self.default = None
  1723. if onupdate is not None:
  1724. if not isinstance(onupdate, (ColumnDefault, Sequence)):
  1725. onupdate = ColumnDefault(onupdate, for_update=True)
  1726. self.onupdate = onupdate
  1727. l_args.append(onupdate)
  1728. else:
  1729. self.onupdate = None
  1730. if server_default is not None:
  1731. if isinstance(server_default, FetchedValue):
  1732. server_default = server_default._as_for_update(False)
  1733. l_args.append(server_default)
  1734. else:
  1735. server_default = DefaultClause(server_default)
  1736. l_args.append(server_default)
  1737. self.server_default = server_default
  1738. if server_onupdate is not None:
  1739. if isinstance(server_onupdate, FetchedValue):
  1740. server_onupdate = server_onupdate._as_for_update(True)
  1741. l_args.append(server_onupdate)
  1742. else:
  1743. server_onupdate = DefaultClause(
  1744. server_onupdate, for_update=True
  1745. )
  1746. l_args.append(server_onupdate)
  1747. self.server_onupdate = server_onupdate
  1748. self._init_items(*cast(_typing_Sequence[SchemaItem], l_args))
  1749. util.set_creation_order(self)
  1750. if info is not None:
  1751. self.info = info
  1752. self._extra_kwargs(**dialect_kwargs)
  1753. table: Table
  1754. constraints: Set[Constraint]
  1755. foreign_keys: Set[ForeignKey]
  1756. """A collection of all :class:`_schema.ForeignKey` marker objects
  1757. associated with this :class:`_schema.Column`.
  1758. Each object is a member of a :class:`_schema.Table`-wide
  1759. :class:`_schema.ForeignKeyConstraint`.
  1760. .. seealso::
  1761. :attr:`_schema.Table.foreign_keys`
  1762. """
  1763. index: Optional[bool]
  1764. """The value of the :paramref:`_schema.Column.index` parameter.
  1765. Does not indicate if this :class:`_schema.Column` is actually indexed
  1766. or not; use :attr:`_schema.Table.indexes`.
  1767. .. seealso::
  1768. :attr:`_schema.Table.indexes`
  1769. """
  1770. unique: Optional[bool]
  1771. """The value of the :paramref:`_schema.Column.unique` parameter.
  1772. Does not indicate if this :class:`_schema.Column` is actually subject to
  1773. a unique constraint or not; use :attr:`_schema.Table.indexes` and
  1774. :attr:`_schema.Table.constraints`.
  1775. .. seealso::
  1776. :attr:`_schema.Table.indexes`
  1777. :attr:`_schema.Table.constraints`.
  1778. """
  1779. computed: Optional[Computed]
  1780. identity: Optional[Identity]
  1781. def _set_type(self, type_: TypeEngine[Any]) -> None:
  1782. assert self.type._isnull or type_ is self.type
  1783. self.type = type_
  1784. if isinstance(self.type, SchemaEventTarget):
  1785. self.type._set_parent_with_dispatch(self)
  1786. for impl in self.type._variant_mapping.values():
  1787. if isinstance(impl, SchemaEventTarget):
  1788. impl._set_parent_with_dispatch(self)
  1789. @HasMemoized.memoized_attribute
  1790. def _default_description_tuple(self) -> _DefaultDescriptionTuple:
  1791. """used by default.py -> _process_execute_defaults()"""
  1792. return _DefaultDescriptionTuple._from_column_default(self.default)
  1793. @HasMemoized.memoized_attribute
  1794. def _onupdate_description_tuple(self) -> _DefaultDescriptionTuple:
  1795. """used by default.py -> _process_execute_defaults()"""
  1796. return _DefaultDescriptionTuple._from_column_default(self.onupdate)
  1797. @util.memoized_property
  1798. def _gen_static_annotations_cache_key(self) -> bool: # type: ignore
  1799. """special attribute used by cache key gen, if true, we will
  1800. use a static cache key for the annotations dictionary, else we
  1801. will generate a new cache key for annotations each time.
  1802. Added for #8790
  1803. """
  1804. return self.table is not None and self.table._is_table
  1805. def _extra_kwargs(self, **kwargs: Any) -> None:
  1806. self._validate_dialect_kwargs(kwargs)
  1807. def __str__(self) -> str:
  1808. if self.name is None:
  1809. return "(no name)"
  1810. elif self.table is not None:
  1811. if self.table.named_with_column:
  1812. return self.table.description + "." + self.description
  1813. else:
  1814. return self.description
  1815. else:
  1816. return self.description
  1817. def references(self, column: Column[Any]) -> bool:
  1818. """Return True if this Column references the given column via foreign
  1819. key."""
  1820. for fk in self.foreign_keys:
  1821. if fk.column.proxy_set.intersection(column.proxy_set):
  1822. return True
  1823. else:
  1824. return False
  1825. def append_foreign_key(self, fk: ForeignKey) -> None:
  1826. fk._set_parent_with_dispatch(self)
  1827. def __repr__(self) -> str:
  1828. kwarg = []
  1829. if self.key != self.name:
  1830. kwarg.append("key")
  1831. if self.primary_key:
  1832. kwarg.append("primary_key")
  1833. if not self.nullable:
  1834. kwarg.append("nullable")
  1835. if self.onupdate:
  1836. kwarg.append("onupdate")
  1837. if self.default:
  1838. kwarg.append("default")
  1839. if self.server_default:
  1840. kwarg.append("server_default")
  1841. if self.comment:
  1842. kwarg.append("comment")
  1843. return "Column(%s)" % ", ".join(
  1844. [repr(self.name)]
  1845. + [repr(self.type)]
  1846. + [repr(x) for x in self.foreign_keys if x is not None]
  1847. + [repr(x) for x in self.constraints]
  1848. + [
  1849. (
  1850. self.table is not None
  1851. and "table=<%s>" % self.table.description
  1852. or "table=None"
  1853. )
  1854. ]
  1855. + ["%s=%s" % (k, repr(getattr(self, k))) for k in kwarg]
  1856. )
  1857. def _set_parent( # type: ignore[override]
  1858. self,
  1859. parent: SchemaEventTarget,
  1860. *,
  1861. all_names: Dict[str, Column[Any]],
  1862. allow_replacements: bool,
  1863. **kw: Any,
  1864. ) -> None:
  1865. table = parent
  1866. assert isinstance(table, Table)
  1867. if not self.name:
  1868. raise exc.ArgumentError(
  1869. "Column must be constructed with a non-blank name or "
  1870. "assign a non-blank .name before adding to a Table."
  1871. )
  1872. self._reset_memoizations()
  1873. if self.key is None:
  1874. self.key = self.name
  1875. existing = getattr(self, "table", None)
  1876. if existing is not None and existing is not table:
  1877. raise exc.ArgumentError(
  1878. f"Column object '{self.key}' already "
  1879. f"assigned to Table '{existing.description}'"
  1880. )
  1881. extra_remove = None
  1882. existing_col = None
  1883. conflicts_on = ""
  1884. if self.key in table._columns:
  1885. existing_col = table._columns[self.key]
  1886. if self.key == self.name:
  1887. conflicts_on = "name"
  1888. else:
  1889. conflicts_on = "key"
  1890. elif self.name in all_names:
  1891. existing_col = all_names[self.name]
  1892. extra_remove = {existing_col}
  1893. conflicts_on = "name"
  1894. if existing_col is not None:
  1895. if existing_col is not self:
  1896. if not allow_replacements:
  1897. raise exc.DuplicateColumnError(
  1898. f"A column with {conflicts_on} "
  1899. f"""'{
  1900. self.key if conflicts_on == 'key' else self.name
  1901. }' """
  1902. f"is already present in table '{table.name}'."
  1903. )
  1904. for fk in existing_col.foreign_keys:
  1905. table.foreign_keys.remove(fk)
  1906. if fk.constraint in table.constraints:
  1907. # this might have been removed
  1908. # already, if it's a composite constraint
  1909. # and more than one col being replaced
  1910. table.constraints.remove(fk.constraint)
  1911. if extra_remove and existing_col is not None and self.key == self.name:
  1912. util.warn(
  1913. f'Column with user-specified key "{existing_col.key}" is '
  1914. "being replaced with "
  1915. f'plain named column "{self.name}", '
  1916. f'key "{existing_col.key}" is being removed. If this is a '
  1917. "reflection operation, specify autoload_replace=False to "
  1918. "prevent this replacement."
  1919. )
  1920. table._columns.replace(self, extra_remove=extra_remove)
  1921. all_names[self.name] = self
  1922. self.table = table
  1923. if self._insert_sentinel:
  1924. if self.table._sentinel_column is not None:
  1925. raise exc.ArgumentError(
  1926. "a Table may have only one explicit sentinel column"
  1927. )
  1928. self.table._sentinel_column = self
  1929. if self.primary_key:
  1930. table.primary_key._replace(self)
  1931. elif self.key in table.primary_key:
  1932. raise exc.ArgumentError(
  1933. f"Trying to redefine primary-key column '{self.key}' as a "
  1934. f"non-primary-key column on table '{table.fullname}'"
  1935. )
  1936. if self.index:
  1937. if isinstance(self.index, str):
  1938. raise exc.ArgumentError(
  1939. "The 'index' keyword argument on Column is boolean only. "
  1940. "To create indexes with a specific name, create an "
  1941. "explicit Index object external to the Table."
  1942. )
  1943. table.append_constraint(
  1944. Index(
  1945. None, self.key, unique=bool(self.unique), _column_flag=True
  1946. )
  1947. )
  1948. elif self.unique:
  1949. if isinstance(self.unique, str):
  1950. raise exc.ArgumentError(
  1951. "The 'unique' keyword argument on Column is boolean "
  1952. "only. To create unique constraints or indexes with a "
  1953. "specific name, append an explicit UniqueConstraint to "
  1954. "the Table's list of elements, or create an explicit "
  1955. "Index object external to the Table."
  1956. )
  1957. table.append_constraint(
  1958. UniqueConstraint(self.key, _column_flag=True)
  1959. )
  1960. self._setup_on_memoized_fks(lambda fk: fk._set_remote_table(table))
  1961. if self.identity and (
  1962. isinstance(self.default, Sequence)
  1963. or isinstance(self.onupdate, Sequence)
  1964. ):
  1965. raise exc.ArgumentError(
  1966. "An column cannot specify both Identity and Sequence."
  1967. )
  1968. def _setup_on_memoized_fks(self, fn: Callable[..., Any]) -> None:
  1969. fk_keys = [
  1970. ((self.table.key, self.key), False),
  1971. ((self.table.key, self.name), True),
  1972. ]
  1973. for fk_key, link_to_name in fk_keys:
  1974. if fk_key in self.table.metadata._fk_memos:
  1975. for fk in self.table.metadata._fk_memos[fk_key]:
  1976. if fk.link_to_name is link_to_name:
  1977. fn(fk)
  1978. def _on_table_attach(self, fn: Callable[..., Any]) -> None:
  1979. if self.table is not None:
  1980. fn(self, self.table)
  1981. else:
  1982. event.listen(self, "after_parent_attach", fn)
  1983. @util.deprecated(
  1984. "1.4",
  1985. "The :meth:`_schema.Column.copy` method is deprecated "
  1986. "and will be removed in a future release.",
  1987. )
  1988. def copy(self, **kw: Any) -> Column[Any]:
  1989. return self._copy(**kw)
  1990. def _copy(self, **kw: Any) -> Column[Any]:
  1991. """Create a copy of this ``Column``, uninitialized.
  1992. This is used in :meth:`_schema.Table.to_metadata` and by the ORM.
  1993. """
  1994. # Constraint objects plus non-constraint-bound ForeignKey objects
  1995. args: List[SchemaItem] = [
  1996. c._copy(**kw) for c in self.constraints if not c._type_bound
  1997. ] + [c._copy(**kw) for c in self.foreign_keys if not c.constraint]
  1998. # ticket #5276
  1999. column_kwargs = {}
  2000. for dialect_name in self.dialect_options:
  2001. dialect_options = self.dialect_options[dialect_name]._non_defaults
  2002. for (
  2003. dialect_option_key,
  2004. dialect_option_value,
  2005. ) in dialect_options.items():
  2006. column_kwargs[
  2007. dialect_name + "_" + dialect_option_key
  2008. ] = dialect_option_value
  2009. server_default = self.server_default
  2010. server_onupdate = self.server_onupdate
  2011. if isinstance(server_default, (Computed, Identity)):
  2012. # TODO: likely should be copied in all cases
  2013. args.append(server_default._copy(**kw))
  2014. server_default = server_onupdate = None
  2015. type_ = self.type
  2016. if isinstance(type_, SchemaEventTarget):
  2017. type_ = type_.copy(**kw)
  2018. # TODO: DefaultGenerator is not copied here! it's just used again
  2019. # with _set_parent() pointing to the old column. see the new
  2020. # use of _copy() in the new _merge() method
  2021. c = self._constructor(
  2022. name=self.name,
  2023. type_=type_,
  2024. key=self.key,
  2025. primary_key=self.primary_key,
  2026. unique=self.unique,
  2027. system=self.system,
  2028. # quote=self.quote, # disabled 2013-08-27 (commit 031ef080)
  2029. index=self.index,
  2030. autoincrement=self.autoincrement,
  2031. default=self.default,
  2032. server_default=server_default,
  2033. onupdate=self.onupdate,
  2034. server_onupdate=server_onupdate,
  2035. doc=self.doc,
  2036. comment=self.comment,
  2037. _omit_from_statements=self._omit_from_statements,
  2038. insert_sentinel=self._insert_sentinel,
  2039. *args,
  2040. **column_kwargs,
  2041. )
  2042. # copy the state of "nullable" exactly, to accommodate for
  2043. # ORM flipping the .nullable flag directly
  2044. c.nullable = self.nullable
  2045. c._user_defined_nullable = self._user_defined_nullable
  2046. return self._schema_item_copy(c)
  2047. def _merge(self, other: Column[Any]) -> None:
  2048. """merge the elements of another column into this one.
  2049. this is used by ORM pep-593 merge and will likely need a lot
  2050. of fixes.
  2051. """
  2052. if self.primary_key:
  2053. other.primary_key = True
  2054. if self.autoincrement != "auto" and other.autoincrement == "auto":
  2055. other.autoincrement = self.autoincrement
  2056. if self.system:
  2057. other.system = self.system
  2058. if self.info:
  2059. other.info.update(self.info)
  2060. type_ = self.type
  2061. if not type_._isnull and other.type._isnull:
  2062. if isinstance(type_, SchemaEventTarget):
  2063. type_ = type_.copy()
  2064. other.type = type_
  2065. if isinstance(type_, SchemaEventTarget):
  2066. type_._set_parent_with_dispatch(other)
  2067. for impl in type_._variant_mapping.values():
  2068. if isinstance(impl, SchemaEventTarget):
  2069. impl._set_parent_with_dispatch(other)
  2070. if (
  2071. self._user_defined_nullable is not NULL_UNSPECIFIED
  2072. and other._user_defined_nullable is NULL_UNSPECIFIED
  2073. ):
  2074. other.nullable = self.nullable
  2075. other._user_defined_nullable = self._user_defined_nullable
  2076. if self.default is not None and other.default is None:
  2077. new_default = self.default._copy()
  2078. new_default._set_parent(other)
  2079. if self.server_default and other.server_default is None:
  2080. new_server_default = self.server_default
  2081. if isinstance(new_server_default, FetchedValue):
  2082. new_server_default = new_server_default._copy()
  2083. new_server_default._set_parent(other)
  2084. else:
  2085. other.server_default = new_server_default
  2086. if self.server_onupdate and other.server_onupdate is None:
  2087. new_server_onupdate = self.server_onupdate
  2088. new_server_onupdate = new_server_onupdate._copy()
  2089. new_server_onupdate._set_parent(other)
  2090. if self.onupdate and other.onupdate is None:
  2091. new_onupdate = self.onupdate._copy()
  2092. new_onupdate._set_parent(other)
  2093. if self.index and not other.index:
  2094. other.index = True
  2095. if self.doc and other.doc is None:
  2096. other.doc = self.doc
  2097. if self.comment and other.comment is None:
  2098. other.comment = self.comment
  2099. if self.unique and not other.unique:
  2100. other.unique = True
  2101. for const in self.constraints:
  2102. if not const._type_bound:
  2103. new_const = const._copy()
  2104. new_const._set_parent(other)
  2105. for fk in self.foreign_keys:
  2106. if not fk.constraint:
  2107. new_fk = fk._copy()
  2108. new_fk._set_parent(other)
  2109. def _make_proxy(
  2110. self,
  2111. selectable: FromClause,
  2112. name: Optional[str] = None,
  2113. key: Optional[str] = None,
  2114. name_is_truncatable: bool = False,
  2115. compound_select_cols: Optional[
  2116. _typing_Sequence[ColumnElement[Any]]
  2117. ] = None,
  2118. **kw: Any,
  2119. ) -> Tuple[str, ColumnClause[_T]]:
  2120. """Create a *proxy* for this column.
  2121. This is a copy of this ``Column`` referenced by a different parent
  2122. (such as an alias or select statement). The column should
  2123. be used only in select scenarios, as its full DDL/default
  2124. information is not transferred.
  2125. """
  2126. fk = [
  2127. ForeignKey(
  2128. col if col is not None else f._colspec,
  2129. _unresolvable=col is None,
  2130. _constraint=f.constraint,
  2131. )
  2132. for f, col in [
  2133. (fk, fk._resolve_column(raiseerr=False))
  2134. for fk in self.foreign_keys
  2135. ]
  2136. ]
  2137. if name is None and self.name is None:
  2138. raise exc.InvalidRequestError(
  2139. "Cannot initialize a sub-selectable"
  2140. " with this Column object until its 'name' has "
  2141. "been assigned."
  2142. )
  2143. try:
  2144. c = self._constructor(
  2145. coercions.expect(
  2146. roles.TruncatedLabelRole, name if name else self.name
  2147. )
  2148. if name_is_truncatable
  2149. else (name or self.name),
  2150. self.type,
  2151. # this may actually be ._proxy_key when the key is incoming
  2152. key=key if key else name if name else self.key,
  2153. primary_key=self.primary_key,
  2154. nullable=self.nullable,
  2155. _proxies=list(compound_select_cols)
  2156. if compound_select_cols
  2157. else [self],
  2158. *fk,
  2159. )
  2160. except TypeError as err:
  2161. raise TypeError(
  2162. "Could not create a copy of this %r object. "
  2163. "Ensure the class includes a _constructor() "
  2164. "attribute or method which accepts the "
  2165. "standard Column constructor arguments, or "
  2166. "references the Column class itself." % self.__class__
  2167. ) from err
  2168. c.table = selectable
  2169. c._propagate_attrs = selectable._propagate_attrs
  2170. if selectable._is_clone_of is not None:
  2171. c._is_clone_of = selectable._is_clone_of.columns.get(c.key)
  2172. if self.primary_key:
  2173. selectable.primary_key.add(c) # type: ignore
  2174. if fk:
  2175. selectable.foreign_keys.update(fk) # type: ignore
  2176. return c.key, c
  2177. def insert_sentinel(
  2178. name: Optional[str] = None,
  2179. type_: Optional[_TypeEngineArgument[_T]] = None,
  2180. *,
  2181. default: Optional[Any] = None,
  2182. omit_from_statements: bool = True,
  2183. ) -> Column[Any]:
  2184. """Provides a surrogate :class:`_schema.Column` that will act as a
  2185. dedicated insert :term:`sentinel` column, allowing efficient bulk
  2186. inserts with deterministic RETURNING sorting for tables that
  2187. don't otherwise have qualifying primary key configurations.
  2188. Adding this column to a :class:`.Table` object requires that a
  2189. corresponding database table actually has this column present, so if adding
  2190. it to an existing model, existing database tables would need to be migrated
  2191. (e.g. using ALTER TABLE or similar) to include this column.
  2192. For background on how this object is used, see the section
  2193. :ref:`engine_insertmanyvalues_sentinel_columns` as part of the
  2194. section :ref:`engine_insertmanyvalues`.
  2195. The :class:`_schema.Column` returned will be a nullable integer column by
  2196. default and make use of a sentinel-specific default generator used only in
  2197. "insertmanyvalues" operations.
  2198. .. seealso::
  2199. :func:`_orm.orm_insert_sentinel`
  2200. :paramref:`_schema.Column.insert_sentinel`
  2201. :ref:`engine_insertmanyvalues`
  2202. :ref:`engine_insertmanyvalues_sentinel_columns`
  2203. .. versionadded:: 2.0.10
  2204. """
  2205. return Column(
  2206. name=name,
  2207. type_=type_api.INTEGERTYPE if type_ is None else type_,
  2208. default=default
  2209. if default is not None
  2210. else _InsertSentinelColumnDefault(),
  2211. _omit_from_statements=omit_from_statements,
  2212. insert_sentinel=True,
  2213. )
  2214. class ForeignKey(DialectKWArgs, SchemaItem):
  2215. """Defines a dependency between two columns.
  2216. ``ForeignKey`` is specified as an argument to a :class:`_schema.Column`
  2217. object,
  2218. e.g.::
  2219. t = Table("remote_table", metadata,
  2220. Column("remote_id", ForeignKey("main_table.id"))
  2221. )
  2222. Note that ``ForeignKey`` is only a marker object that defines
  2223. a dependency between two columns. The actual constraint
  2224. is in all cases represented by the :class:`_schema.ForeignKeyConstraint`
  2225. object. This object will be generated automatically when
  2226. a ``ForeignKey`` is associated with a :class:`_schema.Column` which
  2227. in turn is associated with a :class:`_schema.Table`. Conversely,
  2228. when :class:`_schema.ForeignKeyConstraint` is applied to a
  2229. :class:`_schema.Table`,
  2230. ``ForeignKey`` markers are automatically generated to be
  2231. present on each associated :class:`_schema.Column`, which are also
  2232. associated with the constraint object.
  2233. Note that you cannot define a "composite" foreign key constraint,
  2234. that is a constraint between a grouping of multiple parent/child
  2235. columns, using ``ForeignKey`` objects. To define this grouping,
  2236. the :class:`_schema.ForeignKeyConstraint` object must be used, and applied
  2237. to the :class:`_schema.Table`. The associated ``ForeignKey`` objects
  2238. are created automatically.
  2239. The ``ForeignKey`` objects associated with an individual
  2240. :class:`_schema.Column`
  2241. object are available in the `foreign_keys` collection
  2242. of that column.
  2243. Further examples of foreign key configuration are in
  2244. :ref:`metadata_foreignkeys`.
  2245. """
  2246. __visit_name__ = "foreign_key"
  2247. parent: Column[Any]
  2248. _table_column: Optional[Column[Any]]
  2249. def __init__(
  2250. self,
  2251. column: _DDLColumnArgument,
  2252. _constraint: Optional[ForeignKeyConstraint] = None,
  2253. use_alter: bool = False,
  2254. name: _ConstraintNameArgument = None,
  2255. onupdate: Optional[str] = None,
  2256. ondelete: Optional[str] = None,
  2257. deferrable: Optional[bool] = None,
  2258. initially: Optional[str] = None,
  2259. link_to_name: bool = False,
  2260. match: Optional[str] = None,
  2261. info: Optional[_InfoType] = None,
  2262. comment: Optional[str] = None,
  2263. _unresolvable: bool = False,
  2264. **dialect_kw: Any,
  2265. ):
  2266. r"""
  2267. Construct a column-level FOREIGN KEY.
  2268. The :class:`_schema.ForeignKey` object when constructed generates a
  2269. :class:`_schema.ForeignKeyConstraint`
  2270. which is associated with the parent
  2271. :class:`_schema.Table` object's collection of constraints.
  2272. :param column: A single target column for the key relationship. A
  2273. :class:`_schema.Column` object or a column name as a string:
  2274. ``tablename.columnkey`` or ``schema.tablename.columnkey``.
  2275. ``columnkey`` is the ``key`` which has been assigned to the column
  2276. (defaults to the column name itself), unless ``link_to_name`` is
  2277. ``True`` in which case the rendered name of the column is used.
  2278. :param name: Optional string. An in-database name for the key if
  2279. `constraint` is not provided.
  2280. :param onupdate: Optional string. If set, emit ON UPDATE <value> when
  2281. issuing DDL for this constraint. Typical values include CASCADE,
  2282. DELETE and RESTRICT.
  2283. :param ondelete: Optional string. If set, emit ON DELETE <value> when
  2284. issuing DDL for this constraint. Typical values include CASCADE,
  2285. DELETE and RESTRICT.
  2286. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT
  2287. DEFERRABLE when issuing DDL for this constraint.
  2288. :param initially: Optional string. If set, emit INITIALLY <value> when
  2289. issuing DDL for this constraint.
  2290. :param link_to_name: if True, the string name given in ``column`` is
  2291. the rendered name of the referenced column, not its locally
  2292. assigned ``key``.
  2293. :param use_alter: passed to the underlying
  2294. :class:`_schema.ForeignKeyConstraint`
  2295. to indicate the constraint should
  2296. be generated/dropped externally from the CREATE TABLE/ DROP TABLE
  2297. statement. See :paramref:`_schema.ForeignKeyConstraint.use_alter`
  2298. for further description.
  2299. .. seealso::
  2300. :paramref:`_schema.ForeignKeyConstraint.use_alter`
  2301. :ref:`use_alter`
  2302. :param match: Optional string. If set, emit MATCH <value> when issuing
  2303. DDL for this constraint. Typical values include SIMPLE, PARTIAL
  2304. and FULL.
  2305. :param info: Optional data dictionary which will be populated into the
  2306. :attr:`.SchemaItem.info` attribute of this object.
  2307. :param comment: Optional string that will render an SQL comment on
  2308. foreign key constraint creation.
  2309. .. versionadded:: 2.0
  2310. :param \**dialect_kw: Additional keyword arguments are dialect
  2311. specific, and passed in the form ``<dialectname>_<argname>``. The
  2312. arguments are ultimately handled by a corresponding
  2313. :class:`_schema.ForeignKeyConstraint`.
  2314. See the documentation regarding
  2315. an individual dialect at :ref:`dialect_toplevel` for detail on
  2316. documented arguments.
  2317. """
  2318. self._colspec = coercions.expect(roles.DDLReferredColumnRole, column)
  2319. self._unresolvable = _unresolvable
  2320. if isinstance(self._colspec, str):
  2321. self._table_column = None
  2322. else:
  2323. self._table_column = self._colspec
  2324. if not isinstance(
  2325. self._table_column.table, (type(None), TableClause)
  2326. ):
  2327. raise exc.ArgumentError(
  2328. "ForeignKey received Column not bound "
  2329. "to a Table, got: %r" % self._table_column.table
  2330. )
  2331. # the linked ForeignKeyConstraint.
  2332. # ForeignKey will create this when parent Column
  2333. # is attached to a Table, *or* ForeignKeyConstraint
  2334. # object passes itself in when creating ForeignKey
  2335. # markers.
  2336. self.constraint = _constraint
  2337. # .parent is not Optional under normal use
  2338. self.parent = None # type: ignore
  2339. self.use_alter = use_alter
  2340. self.name = name
  2341. self.onupdate = onupdate
  2342. self.ondelete = ondelete
  2343. self.deferrable = deferrable
  2344. self.initially = initially
  2345. self.link_to_name = link_to_name
  2346. self.match = match
  2347. self.comment = comment
  2348. if info:
  2349. self.info = info
  2350. self._unvalidated_dialect_kw = dialect_kw
  2351. def __repr__(self) -> str:
  2352. return "ForeignKey(%r)" % self._get_colspec()
  2353. @util.deprecated(
  2354. "1.4",
  2355. "The :meth:`_schema.ForeignKey.copy` method is deprecated "
  2356. "and will be removed in a future release.",
  2357. )
  2358. def copy(self, *, schema: Optional[str] = None, **kw: Any) -> ForeignKey:
  2359. return self._copy(schema=schema, **kw)
  2360. def _copy(self, *, schema: Optional[str] = None, **kw: Any) -> ForeignKey:
  2361. """Produce a copy of this :class:`_schema.ForeignKey` object.
  2362. The new :class:`_schema.ForeignKey` will not be bound
  2363. to any :class:`_schema.Column`.
  2364. This method is usually used by the internal
  2365. copy procedures of :class:`_schema.Column`, :class:`_schema.Table`,
  2366. and :class:`_schema.MetaData`.
  2367. :param schema: The returned :class:`_schema.ForeignKey` will
  2368. reference the original table and column name, qualified
  2369. by the given string schema name.
  2370. """
  2371. fk = ForeignKey(
  2372. self._get_colspec(schema=schema),
  2373. use_alter=self.use_alter,
  2374. name=self.name,
  2375. onupdate=self.onupdate,
  2376. ondelete=self.ondelete,
  2377. deferrable=self.deferrable,
  2378. initially=self.initially,
  2379. link_to_name=self.link_to_name,
  2380. match=self.match,
  2381. comment=self.comment,
  2382. **self._unvalidated_dialect_kw,
  2383. )
  2384. return self._schema_item_copy(fk)
  2385. def _get_colspec(
  2386. self,
  2387. schema: Optional[
  2388. Union[
  2389. str,
  2390. Literal[SchemaConst.RETAIN_SCHEMA, SchemaConst.BLANK_SCHEMA],
  2391. ]
  2392. ] = None,
  2393. table_name: Optional[str] = None,
  2394. _is_copy: bool = False,
  2395. ) -> str:
  2396. """Return a string based 'column specification' for this
  2397. :class:`_schema.ForeignKey`.
  2398. This is usually the equivalent of the string-based "tablename.colname"
  2399. argument first passed to the object's constructor.
  2400. """
  2401. if schema not in (None, RETAIN_SCHEMA):
  2402. _schema, tname, colname = self._column_tokens
  2403. if table_name is not None:
  2404. tname = table_name
  2405. if schema is BLANK_SCHEMA:
  2406. return "%s.%s" % (tname, colname)
  2407. else:
  2408. return "%s.%s.%s" % (schema, tname, colname)
  2409. elif table_name:
  2410. schema, tname, colname = self._column_tokens
  2411. if schema:
  2412. return "%s.%s.%s" % (schema, table_name, colname)
  2413. else:
  2414. return "%s.%s" % (table_name, colname)
  2415. elif self._table_column is not None:
  2416. if self._table_column.table is None:
  2417. if _is_copy:
  2418. raise exc.InvalidRequestError(
  2419. f"Can't copy ForeignKey object which refers to "
  2420. f"non-table bound Column {self._table_column!r}"
  2421. )
  2422. else:
  2423. return self._table_column.key
  2424. return "%s.%s" % (
  2425. self._table_column.table.fullname,
  2426. self._table_column.key,
  2427. )
  2428. else:
  2429. assert isinstance(self._colspec, str)
  2430. return self._colspec
  2431. @property
  2432. def _referred_schema(self) -> Optional[str]:
  2433. return self._column_tokens[0]
  2434. def _table_key(self) -> Any:
  2435. if self._table_column is not None:
  2436. if self._table_column.table is None:
  2437. return None
  2438. else:
  2439. return self._table_column.table.key
  2440. else:
  2441. schema, tname, colname = self._column_tokens
  2442. return _get_table_key(tname, schema)
  2443. target_fullname = property(_get_colspec)
  2444. def references(self, table: Table) -> bool:
  2445. """Return True if the given :class:`_schema.Table`
  2446. is referenced by this
  2447. :class:`_schema.ForeignKey`."""
  2448. return table.corresponding_column(self.column) is not None
  2449. def get_referent(self, table: FromClause) -> Optional[Column[Any]]:
  2450. """Return the :class:`_schema.Column` in the given
  2451. :class:`_schema.Table` (or any :class:`.FromClause`)
  2452. referenced by this :class:`_schema.ForeignKey`.
  2453. Returns None if this :class:`_schema.ForeignKey`
  2454. does not reference the given
  2455. :class:`_schema.Table`.
  2456. """
  2457. # our column is a Column, and any subquery etc. proxying us
  2458. # would be doing so via another Column, so that's what would
  2459. # be returned here
  2460. return table.columns.corresponding_column(self.column) # type: ignore
  2461. @util.memoized_property
  2462. def _column_tokens(self) -> Tuple[Optional[str], str, Optional[str]]:
  2463. """parse a string-based _colspec into its component parts."""
  2464. m = self._get_colspec().split(".")
  2465. if m is None:
  2466. raise exc.ArgumentError(
  2467. f"Invalid foreign key column specification: {self._colspec}"
  2468. )
  2469. if len(m) == 1:
  2470. tname = m.pop()
  2471. colname = None
  2472. else:
  2473. colname = m.pop()
  2474. tname = m.pop()
  2475. # A FK between column 'bar' and table 'foo' can be
  2476. # specified as 'foo', 'foo.bar', 'dbo.foo.bar',
  2477. # 'otherdb.dbo.foo.bar'. Once we have the column name and
  2478. # the table name, treat everything else as the schema
  2479. # name. Some databases (e.g. Sybase) support
  2480. # inter-database foreign keys. See tickets#1341 and --
  2481. # indirectly related -- Ticket #594. This assumes that '.'
  2482. # will never appear *within* any component of the FK.
  2483. if len(m) > 0:
  2484. schema = ".".join(m)
  2485. else:
  2486. schema = None
  2487. return schema, tname, colname
  2488. def _resolve_col_tokens(self) -> Tuple[Table, str, Optional[str]]:
  2489. if self.parent is None:
  2490. raise exc.InvalidRequestError(
  2491. "this ForeignKey object does not yet have a "
  2492. "parent Column associated with it."
  2493. )
  2494. elif self.parent.table is None:
  2495. raise exc.InvalidRequestError(
  2496. "this ForeignKey's parent column is not yet associated "
  2497. "with a Table."
  2498. )
  2499. parenttable = self.parent.table
  2500. if self._unresolvable:
  2501. schema, tname, colname = self._column_tokens
  2502. tablekey = _get_table_key(tname, schema)
  2503. return parenttable, tablekey, colname
  2504. # assertion
  2505. # basically Column._make_proxy() sends the actual
  2506. # target Column to the ForeignKey object, so the
  2507. # string resolution here is never called.
  2508. for c in self.parent.base_columns:
  2509. if isinstance(c, Column):
  2510. assert c.table is parenttable
  2511. break
  2512. else:
  2513. assert False
  2514. ######################
  2515. schema, tname, colname = self._column_tokens
  2516. if schema is None and parenttable.metadata.schema is not None:
  2517. schema = parenttable.metadata.schema
  2518. tablekey = _get_table_key(tname, schema)
  2519. return parenttable, tablekey, colname
  2520. def _link_to_col_by_colstring(
  2521. self, parenttable: Table, table: Table, colname: Optional[str]
  2522. ) -> Column[Any]:
  2523. _column = None
  2524. if colname is None:
  2525. # colname is None in the case that ForeignKey argument
  2526. # was specified as table name only, in which case we
  2527. # match the column name to the same column on the
  2528. # parent.
  2529. # this use case wasn't working in later 1.x series
  2530. # as it had no test coverage; fixed in 2.0
  2531. parent = self.parent
  2532. assert parent is not None
  2533. key = parent.key
  2534. _column = table.c.get(key, None)
  2535. elif self.link_to_name:
  2536. key = colname
  2537. for c in table.c:
  2538. if c.name == colname:
  2539. _column = c
  2540. else:
  2541. key = colname
  2542. _column = table.c.get(colname, None)
  2543. if _column is None:
  2544. raise exc.NoReferencedColumnError(
  2545. "Could not initialize target column "
  2546. f"for ForeignKey '{self._colspec}' "
  2547. f"on table '{parenttable.name}': "
  2548. f"table '{table.name}' has no column named '{key}'",
  2549. table.name,
  2550. key,
  2551. )
  2552. return _column
  2553. def _set_target_column(self, column: Column[Any]) -> None:
  2554. assert self.parent is not None
  2555. # propagate TypeEngine to parent if it didn't have one
  2556. if self.parent.type._isnull:
  2557. self.parent.type = column.type
  2558. # super-edgy case, if other FKs point to our column,
  2559. # they'd get the type propagated out also.
  2560. def set_type(fk: ForeignKey) -> None:
  2561. if fk.parent.type._isnull:
  2562. fk.parent.type = column.type
  2563. self.parent._setup_on_memoized_fks(set_type)
  2564. self.column = column # type: ignore
  2565. @util.ro_memoized_property
  2566. def column(self) -> Column[Any]:
  2567. """Return the target :class:`_schema.Column` referenced by this
  2568. :class:`_schema.ForeignKey`.
  2569. If no target column has been established, an exception
  2570. is raised.
  2571. """
  2572. return self._resolve_column()
  2573. @overload
  2574. def _resolve_column(self, *, raiseerr: Literal[True] = ...) -> Column[Any]:
  2575. ...
  2576. @overload
  2577. def _resolve_column(
  2578. self, *, raiseerr: bool = ...
  2579. ) -> Optional[Column[Any]]:
  2580. ...
  2581. def _resolve_column(
  2582. self, *, raiseerr: bool = True
  2583. ) -> Optional[Column[Any]]:
  2584. _column: Column[Any]
  2585. if isinstance(self._colspec, str):
  2586. parenttable, tablekey, colname = self._resolve_col_tokens()
  2587. if self._unresolvable or tablekey not in parenttable.metadata:
  2588. if not raiseerr:
  2589. return None
  2590. raise exc.NoReferencedTableError(
  2591. f"Foreign key associated with column "
  2592. f"'{self.parent}' could not find "
  2593. f"table '{tablekey}' with which to generate a "
  2594. f"foreign key to target column '{colname}'",
  2595. tablekey,
  2596. )
  2597. elif parenttable.key not in parenttable.metadata:
  2598. if not raiseerr:
  2599. return None
  2600. raise exc.InvalidRequestError(
  2601. f"Table {parenttable} is no longer associated with its "
  2602. "parent MetaData"
  2603. )
  2604. else:
  2605. table = parenttable.metadata.tables[tablekey]
  2606. return self._link_to_col_by_colstring(
  2607. parenttable, table, colname
  2608. )
  2609. elif hasattr(self._colspec, "__clause_element__"):
  2610. _column = self._colspec.__clause_element__()
  2611. return _column
  2612. else:
  2613. _column = self._colspec
  2614. return _column
  2615. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  2616. assert isinstance(parent, Column)
  2617. if self.parent is not None and self.parent is not parent:
  2618. raise exc.InvalidRequestError(
  2619. "This ForeignKey already has a parent !"
  2620. )
  2621. self.parent = parent
  2622. self.parent.foreign_keys.add(self)
  2623. self.parent._on_table_attach(self._set_table)
  2624. def _set_remote_table(self, table: Table) -> None:
  2625. parenttable, _, colname = self._resolve_col_tokens()
  2626. _column = self._link_to_col_by_colstring(parenttable, table, colname)
  2627. self._set_target_column(_column)
  2628. assert self.constraint is not None
  2629. self.constraint._validate_dest_table(table)
  2630. def _remove_from_metadata(self, metadata: MetaData) -> None:
  2631. parenttable, table_key, colname = self._resolve_col_tokens()
  2632. fk_key = (table_key, colname)
  2633. if self in metadata._fk_memos[fk_key]:
  2634. # TODO: no test coverage for self not in memos
  2635. metadata._fk_memos[fk_key].remove(self)
  2636. def _set_table(self, column: Column[Any], table: Table) -> None:
  2637. # standalone ForeignKey - create ForeignKeyConstraint
  2638. # on the hosting Table when attached to the Table.
  2639. assert isinstance(table, Table)
  2640. if self.constraint is None:
  2641. self.constraint = ForeignKeyConstraint(
  2642. [],
  2643. [],
  2644. use_alter=self.use_alter,
  2645. name=self.name,
  2646. onupdate=self.onupdate,
  2647. ondelete=self.ondelete,
  2648. deferrable=self.deferrable,
  2649. initially=self.initially,
  2650. match=self.match,
  2651. comment=self.comment,
  2652. **self._unvalidated_dialect_kw,
  2653. )
  2654. self.constraint._append_element(column, self)
  2655. self.constraint._set_parent_with_dispatch(table)
  2656. table.foreign_keys.add(self)
  2657. # set up remote ".column" attribute, or a note to pick it
  2658. # up when the other Table/Column shows up
  2659. if isinstance(self._colspec, str):
  2660. parenttable, table_key, colname = self._resolve_col_tokens()
  2661. fk_key = (table_key, colname)
  2662. if table_key in parenttable.metadata.tables:
  2663. table = parenttable.metadata.tables[table_key]
  2664. try:
  2665. _column = self._link_to_col_by_colstring(
  2666. parenttable, table, colname
  2667. )
  2668. except exc.NoReferencedColumnError:
  2669. # this is OK, we'll try later
  2670. pass
  2671. else:
  2672. self._set_target_column(_column)
  2673. parenttable.metadata._fk_memos[fk_key].append(self)
  2674. elif hasattr(self._colspec, "__clause_element__"):
  2675. _column = self._colspec.__clause_element__()
  2676. self._set_target_column(_column)
  2677. else:
  2678. _column = self._colspec
  2679. self._set_target_column(_column)
  2680. if TYPE_CHECKING:
  2681. def default_is_sequence(
  2682. obj: Optional[DefaultGenerator],
  2683. ) -> TypeGuard[Sequence]:
  2684. ...
  2685. def default_is_clause_element(
  2686. obj: Optional[DefaultGenerator],
  2687. ) -> TypeGuard[ColumnElementColumnDefault]:
  2688. ...
  2689. def default_is_scalar(
  2690. obj: Optional[DefaultGenerator],
  2691. ) -> TypeGuard[ScalarElementColumnDefault]:
  2692. ...
  2693. else:
  2694. default_is_sequence = operator.attrgetter("is_sequence")
  2695. default_is_clause_element = operator.attrgetter("is_clause_element")
  2696. default_is_scalar = operator.attrgetter("is_scalar")
  2697. class DefaultGenerator(Executable, SchemaItem):
  2698. """Base class for column *default* values.
  2699. This object is only present on column.default or column.onupdate.
  2700. It's not valid as a server default.
  2701. """
  2702. __visit_name__ = "default_generator"
  2703. _is_default_generator = True
  2704. is_sequence = False
  2705. is_identity = False
  2706. is_server_default = False
  2707. is_clause_element = False
  2708. is_callable = False
  2709. is_scalar = False
  2710. has_arg = False
  2711. is_sentinel = False
  2712. column: Optional[Column[Any]]
  2713. def __init__(self, for_update: bool = False) -> None:
  2714. self.for_update = for_update
  2715. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  2716. if TYPE_CHECKING:
  2717. assert isinstance(parent, Column)
  2718. self.column = parent
  2719. if self.for_update:
  2720. self.column.onupdate = self
  2721. else:
  2722. self.column.default = self
  2723. def _copy(self) -> DefaultGenerator:
  2724. raise NotImplementedError()
  2725. def _execute_on_connection(
  2726. self,
  2727. connection: Connection,
  2728. distilled_params: _CoreMultiExecuteParams,
  2729. execution_options: CoreExecuteOptionsParameter,
  2730. ) -> Any:
  2731. util.warn_deprecated(
  2732. "Using the .execute() method to invoke a "
  2733. "DefaultGenerator object is deprecated; please use "
  2734. "the .scalar() method.",
  2735. "2.0",
  2736. )
  2737. return self._execute_on_scalar(
  2738. connection, distilled_params, execution_options
  2739. )
  2740. def _execute_on_scalar(
  2741. self,
  2742. connection: Connection,
  2743. distilled_params: _CoreMultiExecuteParams,
  2744. execution_options: CoreExecuteOptionsParameter,
  2745. ) -> Any:
  2746. return connection._execute_default(
  2747. self, distilled_params, execution_options
  2748. )
  2749. class ColumnDefault(DefaultGenerator, ABC):
  2750. """A plain default value on a column.
  2751. This could correspond to a constant, a callable function,
  2752. or a SQL clause.
  2753. :class:`.ColumnDefault` is generated automatically
  2754. whenever the ``default``, ``onupdate`` arguments of
  2755. :class:`_schema.Column` are used. A :class:`.ColumnDefault`
  2756. can be passed positionally as well.
  2757. For example, the following::
  2758. Column('foo', Integer, default=50)
  2759. Is equivalent to::
  2760. Column('foo', Integer, ColumnDefault(50))
  2761. """
  2762. arg: Any
  2763. @overload
  2764. def __new__(
  2765. cls, arg: Callable[..., Any], for_update: bool = ...
  2766. ) -> CallableColumnDefault:
  2767. ...
  2768. @overload
  2769. def __new__(
  2770. cls, arg: ColumnElement[Any], for_update: bool = ...
  2771. ) -> ColumnElementColumnDefault:
  2772. ...
  2773. # if I return ScalarElementColumnDefault here, which is what's actually
  2774. # returned, mypy complains that
  2775. # overloads overlap w/ incompatible return types.
  2776. @overload
  2777. def __new__(cls, arg: object, for_update: bool = ...) -> ColumnDefault:
  2778. ...
  2779. def __new__(
  2780. cls, arg: Any = None, for_update: bool = False
  2781. ) -> ColumnDefault:
  2782. """Construct a new :class:`.ColumnDefault`.
  2783. :param arg: argument representing the default value.
  2784. May be one of the following:
  2785. * a plain non-callable Python value, such as a
  2786. string, integer, boolean, or other simple type.
  2787. The default value will be used as is each time.
  2788. * a SQL expression, that is one which derives from
  2789. :class:`_expression.ColumnElement`. The SQL expression will
  2790. be rendered into the INSERT or UPDATE statement,
  2791. or in the case of a primary key column when
  2792. RETURNING is not used may be
  2793. pre-executed before an INSERT within a SELECT.
  2794. * A Python callable. The function will be invoked for each
  2795. new row subject to an INSERT or UPDATE.
  2796. The callable must accept exactly
  2797. zero or one positional arguments. The one-argument form
  2798. will receive an instance of the :class:`.ExecutionContext`,
  2799. which provides contextual information as to the current
  2800. :class:`_engine.Connection` in use as well as the current
  2801. statement and parameters.
  2802. """
  2803. if isinstance(arg, FetchedValue):
  2804. raise exc.ArgumentError(
  2805. "ColumnDefault may not be a server-side default type."
  2806. )
  2807. elif callable(arg):
  2808. cls = CallableColumnDefault
  2809. elif isinstance(arg, ClauseElement):
  2810. cls = ColumnElementColumnDefault
  2811. elif arg is not None:
  2812. cls = ScalarElementColumnDefault
  2813. return object.__new__(cls)
  2814. def __repr__(self) -> str:
  2815. return f"{self.__class__.__name__}({self.arg!r})"
  2816. class ScalarElementColumnDefault(ColumnDefault):
  2817. """default generator for a fixed scalar Python value
  2818. .. versionadded: 2.0
  2819. """
  2820. is_scalar = True
  2821. has_arg = True
  2822. def __init__(self, arg: Any, for_update: bool = False) -> None:
  2823. self.for_update = for_update
  2824. self.arg = arg
  2825. def _copy(self) -> ScalarElementColumnDefault:
  2826. return ScalarElementColumnDefault(
  2827. arg=self.arg, for_update=self.for_update
  2828. )
  2829. class _InsertSentinelColumnDefault(ColumnDefault):
  2830. """Default generator that's specific to the use of a "sentinel" column
  2831. when using the insertmanyvalues feature.
  2832. This default is used as part of the :func:`_schema.insert_sentinel`
  2833. construct.
  2834. """
  2835. is_sentinel = True
  2836. for_update = False
  2837. arg = None
  2838. def __new__(cls) -> _InsertSentinelColumnDefault:
  2839. return object.__new__(cls)
  2840. def __init__(self) -> None:
  2841. pass
  2842. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  2843. col = cast("Column[Any]", parent)
  2844. if not col._insert_sentinel:
  2845. raise exc.ArgumentError(
  2846. "The _InsertSentinelColumnDefault may only be applied to a "
  2847. "Column marked as insert_sentinel=True"
  2848. )
  2849. elif not col.nullable:
  2850. raise exc.ArgumentError(
  2851. "The _InsertSentinelColumnDefault may only be applied to a "
  2852. "Column that is nullable"
  2853. )
  2854. super()._set_parent(parent, **kw)
  2855. def _copy(self) -> _InsertSentinelColumnDefault:
  2856. return _InsertSentinelColumnDefault()
  2857. _SQLExprDefault = Union["ColumnElement[Any]", "TextClause"]
  2858. class ColumnElementColumnDefault(ColumnDefault):
  2859. """default generator for a SQL expression
  2860. .. versionadded:: 2.0
  2861. """
  2862. is_clause_element = True
  2863. has_arg = True
  2864. arg: _SQLExprDefault
  2865. def __init__(
  2866. self,
  2867. arg: _SQLExprDefault,
  2868. for_update: bool = False,
  2869. ) -> None:
  2870. self.for_update = for_update
  2871. self.arg = arg
  2872. def _copy(self) -> ColumnElementColumnDefault:
  2873. return ColumnElementColumnDefault(
  2874. arg=self.arg, for_update=self.for_update
  2875. )
  2876. @util.memoized_property
  2877. @util.preload_module("sqlalchemy.sql.sqltypes")
  2878. def _arg_is_typed(self) -> bool:
  2879. sqltypes = util.preloaded.sql_sqltypes
  2880. return not isinstance(self.arg.type, sqltypes.NullType)
  2881. class _CallableColumnDefaultProtocol(Protocol):
  2882. def __call__(self, context: ExecutionContext) -> Any:
  2883. ...
  2884. class CallableColumnDefault(ColumnDefault):
  2885. """default generator for a callable Python function
  2886. .. versionadded:: 2.0
  2887. """
  2888. is_callable = True
  2889. arg: _CallableColumnDefaultProtocol
  2890. has_arg = True
  2891. def __init__(
  2892. self,
  2893. arg: Union[_CallableColumnDefaultProtocol, Callable[[], Any]],
  2894. for_update: bool = False,
  2895. ) -> None:
  2896. self.for_update = for_update
  2897. self.arg = self._maybe_wrap_callable(arg)
  2898. def _copy(self) -> CallableColumnDefault:
  2899. return CallableColumnDefault(arg=self.arg, for_update=self.for_update)
  2900. def _maybe_wrap_callable(
  2901. self, fn: Union[_CallableColumnDefaultProtocol, Callable[[], Any]]
  2902. ) -> _CallableColumnDefaultProtocol:
  2903. """Wrap callables that don't accept a context.
  2904. This is to allow easy compatibility with default callables
  2905. that aren't specific to accepting of a context.
  2906. """
  2907. try:
  2908. argspec = util.get_callable_argspec(fn, no_self=True)
  2909. except TypeError:
  2910. return util.wrap_callable(lambda ctx: fn(), fn) # type: ignore
  2911. defaulted = argspec[3] is not None and len(argspec[3]) or 0
  2912. positionals = len(argspec[0]) - defaulted
  2913. if positionals == 0:
  2914. return util.wrap_callable(lambda ctx: fn(), fn) # type: ignore
  2915. elif positionals == 1:
  2916. return fn # type: ignore
  2917. else:
  2918. raise exc.ArgumentError(
  2919. "ColumnDefault Python function takes zero or one "
  2920. "positional arguments"
  2921. )
  2922. class IdentityOptions:
  2923. """Defines options for a named database sequence or an identity column.
  2924. .. versionadded:: 1.3.18
  2925. .. seealso::
  2926. :class:`.Sequence`
  2927. """
  2928. def __init__(
  2929. self,
  2930. start: Optional[int] = None,
  2931. increment: Optional[int] = None,
  2932. minvalue: Optional[int] = None,
  2933. maxvalue: Optional[int] = None,
  2934. nominvalue: Optional[bool] = None,
  2935. nomaxvalue: Optional[bool] = None,
  2936. cycle: Optional[bool] = None,
  2937. cache: Optional[int] = None,
  2938. order: Optional[bool] = None,
  2939. ) -> None:
  2940. """Construct a :class:`.IdentityOptions` object.
  2941. See the :class:`.Sequence` documentation for a complete description
  2942. of the parameters.
  2943. :param start: the starting index of the sequence.
  2944. :param increment: the increment value of the sequence.
  2945. :param minvalue: the minimum value of the sequence.
  2946. :param maxvalue: the maximum value of the sequence.
  2947. :param nominvalue: no minimum value of the sequence.
  2948. :param nomaxvalue: no maximum value of the sequence.
  2949. :param cycle: allows the sequence to wrap around when the maxvalue
  2950. or minvalue has been reached.
  2951. :param cache: optional integer value; number of future values in the
  2952. sequence which are calculated in advance.
  2953. :param order: optional boolean value; if ``True``, renders the
  2954. ORDER keyword.
  2955. """
  2956. self.start = start
  2957. self.increment = increment
  2958. self.minvalue = minvalue
  2959. self.maxvalue = maxvalue
  2960. self.nominvalue = nominvalue
  2961. self.nomaxvalue = nomaxvalue
  2962. self.cycle = cycle
  2963. self.cache = cache
  2964. self.order = order
  2965. @property
  2966. def _increment_is_negative(self) -> bool:
  2967. return self.increment is not None and self.increment < 0
  2968. class Sequence(HasSchemaAttr, IdentityOptions, DefaultGenerator):
  2969. """Represents a named database sequence.
  2970. The :class:`.Sequence` object represents the name and configurational
  2971. parameters of a database sequence. It also represents
  2972. a construct that can be "executed" by a SQLAlchemy :class:`_engine.Engine`
  2973. or :class:`_engine.Connection`,
  2974. rendering the appropriate "next value" function
  2975. for the target database and returning a result.
  2976. The :class:`.Sequence` is typically associated with a primary key column::
  2977. some_table = Table(
  2978. 'some_table', metadata,
  2979. Column('id', Integer, Sequence('some_table_seq', start=1),
  2980. primary_key=True)
  2981. )
  2982. When CREATE TABLE is emitted for the above :class:`_schema.Table`, if the
  2983. target platform supports sequences, a CREATE SEQUENCE statement will
  2984. be emitted as well. For platforms that don't support sequences,
  2985. the :class:`.Sequence` construct is ignored.
  2986. .. seealso::
  2987. :ref:`defaults_sequences`
  2988. :class:`.CreateSequence`
  2989. :class:`.DropSequence`
  2990. """
  2991. __visit_name__ = "sequence"
  2992. is_sequence = True
  2993. column: Optional[Column[Any]]
  2994. data_type: Optional[TypeEngine[int]]
  2995. def __init__(
  2996. self,
  2997. name: str,
  2998. start: Optional[int] = None,
  2999. increment: Optional[int] = None,
  3000. minvalue: Optional[int] = None,
  3001. maxvalue: Optional[int] = None,
  3002. nominvalue: Optional[bool] = None,
  3003. nomaxvalue: Optional[bool] = None,
  3004. cycle: Optional[bool] = None,
  3005. schema: Optional[Union[str, Literal[SchemaConst.BLANK_SCHEMA]]] = None,
  3006. cache: Optional[int] = None,
  3007. order: Optional[bool] = None,
  3008. data_type: Optional[_TypeEngineArgument[int]] = None,
  3009. optional: bool = False,
  3010. quote: Optional[bool] = None,
  3011. metadata: Optional[MetaData] = None,
  3012. quote_schema: Optional[bool] = None,
  3013. for_update: bool = False,
  3014. ) -> None:
  3015. """Construct a :class:`.Sequence` object.
  3016. :param name: the name of the sequence.
  3017. :param start: the starting index of the sequence. This value is
  3018. used when the CREATE SEQUENCE command is emitted to the database
  3019. as the value of the "START WITH" clause. If ``None``, the
  3020. clause is omitted, which on most platforms indicates a starting
  3021. value of 1.
  3022. .. versionchanged:: 2.0 The :paramref:`.Sequence.start` parameter
  3023. is required in order to have DDL emit "START WITH". This is a
  3024. reversal of a change made in version 1.4 which would implicitly
  3025. render "START WITH 1" if the :paramref:`.Sequence.start` were
  3026. not included. See :ref:`change_7211` for more detail.
  3027. :param increment: the increment value of the sequence. This
  3028. value is used when the CREATE SEQUENCE command is emitted to
  3029. the database as the value of the "INCREMENT BY" clause. If ``None``,
  3030. the clause is omitted, which on most platforms indicates an
  3031. increment of 1.
  3032. :param minvalue: the minimum value of the sequence. This
  3033. value is used when the CREATE SEQUENCE command is emitted to
  3034. the database as the value of the "MINVALUE" clause. If ``None``,
  3035. the clause is omitted, which on most platforms indicates a
  3036. minvalue of 1 and -2^63-1 for ascending and descending sequences,
  3037. respectively.
  3038. :param maxvalue: the maximum value of the sequence. This
  3039. value is used when the CREATE SEQUENCE command is emitted to
  3040. the database as the value of the "MAXVALUE" clause. If ``None``,
  3041. the clause is omitted, which on most platforms indicates a
  3042. maxvalue of 2^63-1 and -1 for ascending and descending sequences,
  3043. respectively.
  3044. :param nominvalue: no minimum value of the sequence. This
  3045. value is used when the CREATE SEQUENCE command is emitted to
  3046. the database as the value of the "NO MINVALUE" clause. If ``None``,
  3047. the clause is omitted, which on most platforms indicates a
  3048. minvalue of 1 and -2^63-1 for ascending and descending sequences,
  3049. respectively.
  3050. :param nomaxvalue: no maximum value of the sequence. This
  3051. value is used when the CREATE SEQUENCE command is emitted to
  3052. the database as the value of the "NO MAXVALUE" clause. If ``None``,
  3053. the clause is omitted, which on most platforms indicates a
  3054. maxvalue of 2^63-1 and -1 for ascending and descending sequences,
  3055. respectively.
  3056. :param cycle: allows the sequence to wrap around when the maxvalue
  3057. or minvalue has been reached by an ascending or descending sequence
  3058. respectively. This value is used when the CREATE SEQUENCE command
  3059. is emitted to the database as the "CYCLE" clause. If the limit is
  3060. reached, the next number generated will be the minvalue or maxvalue,
  3061. respectively. If cycle=False (the default) any calls to nextval
  3062. after the sequence has reached its maximum value will return an
  3063. error.
  3064. :param schema: optional schema name for the sequence, if located
  3065. in a schema other than the default. The rules for selecting the
  3066. schema name when a :class:`_schema.MetaData`
  3067. is also present are the same
  3068. as that of :paramref:`_schema.Table.schema`.
  3069. :param cache: optional integer value; number of future values in the
  3070. sequence which are calculated in advance. Renders the CACHE keyword
  3071. understood by Oracle and PostgreSQL.
  3072. :param order: optional boolean value; if ``True``, renders the
  3073. ORDER keyword, understood by Oracle, indicating the sequence is
  3074. definitively ordered. May be necessary to provide deterministic
  3075. ordering using Oracle RAC.
  3076. :param data_type: The type to be returned by the sequence, for
  3077. dialects that allow us to choose between INTEGER, BIGINT, etc.
  3078. (e.g., mssql).
  3079. .. versionadded:: 1.4.0
  3080. :param optional: boolean value, when ``True``, indicates that this
  3081. :class:`.Sequence` object only needs to be explicitly generated
  3082. on backends that don't provide another way to generate primary
  3083. key identifiers. Currently, it essentially means, "don't create
  3084. this sequence on the PostgreSQL backend, where the SERIAL keyword
  3085. creates a sequence for us automatically".
  3086. :param quote: boolean value, when ``True`` or ``False``, explicitly
  3087. forces quoting of the :paramref:`_schema.Sequence.name` on or off.
  3088. When left at its default of ``None``, normal quoting rules based
  3089. on casing and reserved words take place.
  3090. :param quote_schema: Set the quoting preferences for the ``schema``
  3091. name.
  3092. :param metadata: optional :class:`_schema.MetaData` object which this
  3093. :class:`.Sequence` will be associated with. A :class:`.Sequence`
  3094. that is associated with a :class:`_schema.MetaData`
  3095. gains the following
  3096. capabilities:
  3097. * The :class:`.Sequence` will inherit the
  3098. :paramref:`_schema.MetaData.schema`
  3099. parameter specified to the target :class:`_schema.MetaData`, which
  3100. affects the production of CREATE / DROP DDL, if any.
  3101. * The :meth:`.Sequence.create` and :meth:`.Sequence.drop` methods
  3102. automatically use the engine bound to the :class:`_schema.MetaData`
  3103. object, if any.
  3104. * The :meth:`_schema.MetaData.create_all` and
  3105. :meth:`_schema.MetaData.drop_all`
  3106. methods will emit CREATE / DROP for this :class:`.Sequence`,
  3107. even if the :class:`.Sequence` is not associated with any
  3108. :class:`_schema.Table` / :class:`_schema.Column`
  3109. that's a member of this
  3110. :class:`_schema.MetaData`.
  3111. The above behaviors can only occur if the :class:`.Sequence` is
  3112. explicitly associated with the :class:`_schema.MetaData`
  3113. via this parameter.
  3114. .. seealso::
  3115. :ref:`sequence_metadata` - full discussion of the
  3116. :paramref:`.Sequence.metadata` parameter.
  3117. :param for_update: Indicates this :class:`.Sequence`, when associated
  3118. with a :class:`_schema.Column`,
  3119. should be invoked for UPDATE statements
  3120. on that column's table, rather than for INSERT statements, when
  3121. no value is otherwise present for that column in the statement.
  3122. """
  3123. DefaultGenerator.__init__(self, for_update=for_update)
  3124. IdentityOptions.__init__(
  3125. self,
  3126. start=start,
  3127. increment=increment,
  3128. minvalue=minvalue,
  3129. maxvalue=maxvalue,
  3130. nominvalue=nominvalue,
  3131. nomaxvalue=nomaxvalue,
  3132. cycle=cycle,
  3133. cache=cache,
  3134. order=order,
  3135. )
  3136. self.column = None
  3137. self.name = quoted_name(name, quote)
  3138. self.optional = optional
  3139. if schema is BLANK_SCHEMA:
  3140. self.schema = schema = None
  3141. elif metadata is not None and schema is None and metadata.schema:
  3142. self.schema = schema = metadata.schema
  3143. else:
  3144. self.schema = quoted_name.construct(schema, quote_schema)
  3145. self.metadata = metadata
  3146. self._key = _get_table_key(name, schema)
  3147. if metadata:
  3148. self._set_metadata(metadata)
  3149. if data_type is not None:
  3150. self.data_type = to_instance(data_type)
  3151. else:
  3152. self.data_type = None
  3153. @util.preload_module("sqlalchemy.sql.functions")
  3154. def next_value(self) -> Function[int]:
  3155. """Return a :class:`.next_value` function element
  3156. which will render the appropriate increment function
  3157. for this :class:`.Sequence` within any SQL expression.
  3158. """
  3159. return util.preloaded.sql_functions.func.next_value(self)
  3160. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  3161. column = parent
  3162. assert isinstance(column, Column)
  3163. super()._set_parent(column)
  3164. column._on_table_attach(self._set_table)
  3165. def _copy(self) -> Sequence:
  3166. return Sequence(
  3167. name=self.name,
  3168. start=self.start,
  3169. increment=self.increment,
  3170. minvalue=self.minvalue,
  3171. maxvalue=self.maxvalue,
  3172. nominvalue=self.nominvalue,
  3173. nomaxvalue=self.nomaxvalue,
  3174. cycle=self.cycle,
  3175. schema=self.schema,
  3176. cache=self.cache,
  3177. order=self.order,
  3178. data_type=self.data_type,
  3179. optional=self.optional,
  3180. metadata=self.metadata,
  3181. for_update=self.for_update,
  3182. )
  3183. def _set_table(self, column: Column[Any], table: Table) -> None:
  3184. self._set_metadata(table.metadata)
  3185. def _set_metadata(self, metadata: MetaData) -> None:
  3186. self.metadata = metadata
  3187. self.metadata._sequences[self._key] = self
  3188. def create(self, bind: _CreateDropBind, checkfirst: bool = True) -> None:
  3189. """Creates this sequence in the database."""
  3190. bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
  3191. def drop(self, bind: _CreateDropBind, checkfirst: bool = True) -> None:
  3192. """Drops this sequence from the database."""
  3193. bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
  3194. def _not_a_column_expr(self) -> NoReturn:
  3195. raise exc.InvalidRequestError(
  3196. f"This {self.__class__.__name__} cannot be used directly "
  3197. "as a column expression. Use func.next_value(sequence) "
  3198. "to produce a 'next value' function that's usable "
  3199. "as a column element."
  3200. )
  3201. @inspection._self_inspects
  3202. class FetchedValue(SchemaEventTarget):
  3203. """A marker for a transparent database-side default.
  3204. Use :class:`.FetchedValue` when the database is configured
  3205. to provide some automatic default for a column.
  3206. E.g.::
  3207. Column('foo', Integer, FetchedValue())
  3208. Would indicate that some trigger or default generator
  3209. will create a new value for the ``foo`` column during an
  3210. INSERT.
  3211. .. seealso::
  3212. :ref:`triggered_columns`
  3213. """
  3214. is_server_default = True
  3215. reflected = False
  3216. has_argument = False
  3217. is_clause_element = False
  3218. is_identity = False
  3219. column: Optional[Column[Any]]
  3220. def __init__(self, for_update: bool = False) -> None:
  3221. self.for_update = for_update
  3222. def _as_for_update(self, for_update: bool) -> FetchedValue:
  3223. if for_update == self.for_update:
  3224. return self
  3225. else:
  3226. return self._clone(for_update)
  3227. def _copy(self) -> FetchedValue:
  3228. return FetchedValue(self.for_update)
  3229. def _clone(self, for_update: bool) -> Self:
  3230. n = self.__class__.__new__(self.__class__)
  3231. n.__dict__.update(self.__dict__)
  3232. n.__dict__.pop("column", None)
  3233. n.for_update = for_update
  3234. return n
  3235. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  3236. column = parent
  3237. assert isinstance(column, Column)
  3238. self.column = column
  3239. if self.for_update:
  3240. self.column.server_onupdate = self
  3241. else:
  3242. self.column.server_default = self
  3243. def __repr__(self) -> str:
  3244. return util.generic_repr(self)
  3245. class DefaultClause(FetchedValue):
  3246. """A DDL-specified DEFAULT column value.
  3247. :class:`.DefaultClause` is a :class:`.FetchedValue`
  3248. that also generates a "DEFAULT" clause when
  3249. "CREATE TABLE" is emitted.
  3250. :class:`.DefaultClause` is generated automatically
  3251. whenever the ``server_default``, ``server_onupdate`` arguments of
  3252. :class:`_schema.Column` are used. A :class:`.DefaultClause`
  3253. can be passed positionally as well.
  3254. For example, the following::
  3255. Column('foo', Integer, server_default="50")
  3256. Is equivalent to::
  3257. Column('foo', Integer, DefaultClause("50"))
  3258. """
  3259. has_argument = True
  3260. def __init__(
  3261. self,
  3262. arg: Union[str, ClauseElement, TextClause],
  3263. for_update: bool = False,
  3264. _reflected: bool = False,
  3265. ) -> None:
  3266. util.assert_arg_type(arg, (str, ClauseElement, TextClause), "arg")
  3267. super().__init__(for_update)
  3268. self.arg = arg
  3269. self.reflected = _reflected
  3270. def _copy(self) -> DefaultClause:
  3271. return DefaultClause(
  3272. arg=self.arg, for_update=self.for_update, _reflected=self.reflected
  3273. )
  3274. def __repr__(self) -> str:
  3275. return "DefaultClause(%r, for_update=%r)" % (self.arg, self.for_update)
  3276. class Constraint(DialectKWArgs, HasConditionalDDL, SchemaItem):
  3277. """A table-level SQL constraint.
  3278. :class:`_schema.Constraint` serves as the base class for the series of
  3279. constraint objects that can be associated with :class:`_schema.Table`
  3280. objects, including :class:`_schema.PrimaryKeyConstraint`,
  3281. :class:`_schema.ForeignKeyConstraint`
  3282. :class:`_schema.UniqueConstraint`, and
  3283. :class:`_schema.CheckConstraint`.
  3284. """
  3285. __visit_name__ = "constraint"
  3286. _creation_order: int
  3287. _column_flag: bool
  3288. def __init__(
  3289. self,
  3290. name: _ConstraintNameArgument = None,
  3291. deferrable: Optional[bool] = None,
  3292. initially: Optional[str] = None,
  3293. info: Optional[_InfoType] = None,
  3294. comment: Optional[str] = None,
  3295. _create_rule: Optional[Any] = None,
  3296. _type_bound: bool = False,
  3297. **dialect_kw: Any,
  3298. ) -> None:
  3299. r"""Create a SQL constraint.
  3300. :param name:
  3301. Optional, the in-database name of this ``Constraint``.
  3302. :param deferrable:
  3303. Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
  3304. issuing DDL for this constraint.
  3305. :param initially:
  3306. Optional string. If set, emit INITIALLY <value> when issuing DDL
  3307. for this constraint.
  3308. :param info: Optional data dictionary which will be populated into the
  3309. :attr:`.SchemaItem.info` attribute of this object.
  3310. :param comment: Optional string that will render an SQL comment on
  3311. foreign key constraint creation.
  3312. .. versionadded:: 2.0
  3313. :param \**dialect_kw: Additional keyword arguments are dialect
  3314. specific, and passed in the form ``<dialectname>_<argname>``. See
  3315. the documentation regarding an individual dialect at
  3316. :ref:`dialect_toplevel` for detail on documented arguments.
  3317. :param _create_rule:
  3318. used internally by some datatypes that also create constraints.
  3319. :param _type_bound:
  3320. used internally to indicate that this constraint is associated with
  3321. a specific datatype.
  3322. """
  3323. self.name = name
  3324. self.deferrable = deferrable
  3325. self.initially = initially
  3326. if info:
  3327. self.info = info
  3328. self._create_rule = _create_rule
  3329. self._type_bound = _type_bound
  3330. util.set_creation_order(self)
  3331. self._validate_dialect_kwargs(dialect_kw)
  3332. self.comment = comment
  3333. def _should_create_for_compiler(
  3334. self, compiler: DDLCompiler, **kw: Any
  3335. ) -> bool:
  3336. if self._create_rule is not None and not self._create_rule(compiler):
  3337. return False
  3338. elif self._ddl_if is not None:
  3339. return self._ddl_if._should_execute(
  3340. ddl.CreateConstraint(self), self, None, compiler=compiler, **kw
  3341. )
  3342. else:
  3343. return True
  3344. @property
  3345. def table(self) -> Table:
  3346. try:
  3347. if isinstance(self.parent, Table):
  3348. return self.parent
  3349. except AttributeError:
  3350. pass
  3351. raise exc.InvalidRequestError(
  3352. "This constraint is not bound to a table. Did you "
  3353. "mean to call table.append_constraint(constraint) ?"
  3354. )
  3355. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  3356. assert isinstance(parent, (Table, Column))
  3357. self.parent = parent
  3358. parent.constraints.add(self)
  3359. @util.deprecated(
  3360. "1.4",
  3361. "The :meth:`_schema.Constraint.copy` method is deprecated "
  3362. "and will be removed in a future release.",
  3363. )
  3364. def copy(self, **kw: Any) -> Self:
  3365. return self._copy(**kw)
  3366. def _copy(self, **kw: Any) -> Self:
  3367. raise NotImplementedError()
  3368. class ColumnCollectionMixin:
  3369. """A :class:`_expression.ColumnCollection` of :class:`_schema.Column`
  3370. objects.
  3371. This collection represents the columns which are referred to by
  3372. this object.
  3373. """
  3374. _columns: DedupeColumnCollection[Column[Any]]
  3375. _allow_multiple_tables = False
  3376. _pending_colargs: List[Optional[Union[str, Column[Any]]]]
  3377. if TYPE_CHECKING:
  3378. def _set_parent_with_dispatch(
  3379. self, parent: SchemaEventTarget, **kw: Any
  3380. ) -> None:
  3381. ...
  3382. def __init__(
  3383. self,
  3384. *columns: _DDLColumnArgument,
  3385. _autoattach: bool = True,
  3386. _column_flag: bool = False,
  3387. _gather_expressions: Optional[
  3388. List[Union[str, ColumnElement[Any]]]
  3389. ] = None,
  3390. ) -> None:
  3391. self._column_flag = _column_flag
  3392. self._columns = DedupeColumnCollection()
  3393. processed_expressions: Optional[
  3394. List[Union[ColumnElement[Any], str]]
  3395. ] = _gather_expressions
  3396. if processed_expressions is not None:
  3397. self._pending_colargs = []
  3398. for (
  3399. expr,
  3400. _,
  3401. _,
  3402. add_element,
  3403. ) in coercions.expect_col_expression_collection(
  3404. roles.DDLConstraintColumnRole, columns
  3405. ):
  3406. self._pending_colargs.append(add_element)
  3407. processed_expressions.append(expr)
  3408. else:
  3409. self._pending_colargs = [
  3410. coercions.expect(roles.DDLConstraintColumnRole, column)
  3411. for column in columns
  3412. ]
  3413. if _autoattach and self._pending_colargs:
  3414. self._check_attach()
  3415. def _check_attach(self, evt: bool = False) -> None:
  3416. col_objs = [c for c in self._pending_colargs if isinstance(c, Column)]
  3417. cols_w_table = [c for c in col_objs if isinstance(c.table, Table)]
  3418. cols_wo_table = set(col_objs).difference(cols_w_table)
  3419. if cols_wo_table:
  3420. # feature #3341 - place event listeners for Column objects
  3421. # such that when all those cols are attached, we autoattach.
  3422. assert not evt, "Should not reach here on event call"
  3423. # issue #3411 - don't do the per-column auto-attach if some of the
  3424. # columns are specified as strings.
  3425. has_string_cols = {
  3426. c for c in self._pending_colargs if c is not None
  3427. }.difference(col_objs)
  3428. if not has_string_cols:
  3429. def _col_attached(column: Column[Any], table: Table) -> None:
  3430. # this isinstance() corresponds with the
  3431. # isinstance() above; only want to count Table-bound
  3432. # columns
  3433. if isinstance(table, Table):
  3434. cols_wo_table.discard(column)
  3435. if not cols_wo_table:
  3436. self._check_attach(evt=True)
  3437. self._cols_wo_table = cols_wo_table
  3438. for col in cols_wo_table:
  3439. col._on_table_attach(_col_attached)
  3440. return
  3441. columns = cols_w_table
  3442. tables = {c.table for c in columns}
  3443. if len(tables) == 1:
  3444. self._set_parent_with_dispatch(tables.pop())
  3445. elif len(tables) > 1 and not self._allow_multiple_tables:
  3446. table = columns[0].table
  3447. others = [c for c in columns[1:] if c.table is not table]
  3448. if others:
  3449. # black could not format this inline
  3450. other_str = ", ".join("'%s'" % c for c in others)
  3451. raise exc.ArgumentError(
  3452. f"Column(s) {other_str} "
  3453. f"are not part of table '{table.description}'."
  3454. )
  3455. @util.ro_memoized_property
  3456. def columns(self) -> ReadOnlyColumnCollection[str, Column[Any]]:
  3457. return self._columns.as_readonly()
  3458. @util.ro_memoized_property
  3459. def c(self) -> ReadOnlyColumnCollection[str, Column[Any]]:
  3460. return self._columns.as_readonly()
  3461. def _col_expressions(
  3462. self, parent: Union[Table, Column[Any]]
  3463. ) -> List[Optional[Column[Any]]]:
  3464. if isinstance(parent, Column):
  3465. result: List[Optional[Column[Any]]] = [
  3466. c for c in self._pending_colargs if isinstance(c, Column)
  3467. ]
  3468. assert len(result) == len(self._pending_colargs)
  3469. return result
  3470. else:
  3471. try:
  3472. return [
  3473. parent.c[col] if isinstance(col, str) else col
  3474. for col in self._pending_colargs
  3475. ]
  3476. except KeyError as ke:
  3477. raise exc.ConstraintColumnNotFoundError(
  3478. f"Can't create {self.__class__.__name__} "
  3479. f"on table '{parent.description}': no column "
  3480. f"named '{ke.args[0]}' is present."
  3481. ) from ke
  3482. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  3483. assert isinstance(parent, (Table, Column))
  3484. for col in self._col_expressions(parent):
  3485. if col is not None:
  3486. self._columns.add(col)
  3487. class ColumnCollectionConstraint(ColumnCollectionMixin, Constraint):
  3488. """A constraint that proxies a ColumnCollection."""
  3489. def __init__(
  3490. self,
  3491. *columns: _DDLColumnArgument,
  3492. name: _ConstraintNameArgument = None,
  3493. deferrable: Optional[bool] = None,
  3494. initially: Optional[str] = None,
  3495. info: Optional[_InfoType] = None,
  3496. _autoattach: bool = True,
  3497. _column_flag: bool = False,
  3498. _gather_expressions: Optional[List[_DDLColumnArgument]] = None,
  3499. **dialect_kw: Any,
  3500. ) -> None:
  3501. r"""
  3502. :param \*columns:
  3503. A sequence of column names or Column objects.
  3504. :param name:
  3505. Optional, the in-database name of this constraint.
  3506. :param deferrable:
  3507. Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
  3508. issuing DDL for this constraint.
  3509. :param initially:
  3510. Optional string. If set, emit INITIALLY <value> when issuing DDL
  3511. for this constraint.
  3512. :param \**dialect_kw: other keyword arguments including
  3513. dialect-specific arguments are propagated to the :class:`.Constraint`
  3514. superclass.
  3515. """
  3516. Constraint.__init__(
  3517. self,
  3518. name=name,
  3519. deferrable=deferrable,
  3520. initially=initially,
  3521. info=info,
  3522. **dialect_kw,
  3523. )
  3524. ColumnCollectionMixin.__init__(
  3525. self, *columns, _autoattach=_autoattach, _column_flag=_column_flag
  3526. )
  3527. columns: ReadOnlyColumnCollection[str, Column[Any]]
  3528. """A :class:`_expression.ColumnCollection` representing the set of columns
  3529. for this constraint.
  3530. """
  3531. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  3532. assert isinstance(parent, (Column, Table))
  3533. Constraint._set_parent(self, parent)
  3534. ColumnCollectionMixin._set_parent(self, parent)
  3535. def __contains__(self, x: Any) -> bool:
  3536. return x in self._columns
  3537. @util.deprecated(
  3538. "1.4",
  3539. "The :meth:`_schema.ColumnCollectionConstraint.copy` method "
  3540. "is deprecated and will be removed in a future release.",
  3541. )
  3542. def copy(
  3543. self,
  3544. *,
  3545. target_table: Optional[Table] = None,
  3546. **kw: Any,
  3547. ) -> ColumnCollectionConstraint:
  3548. return self._copy(target_table=target_table, **kw)
  3549. def _copy(
  3550. self,
  3551. *,
  3552. target_table: Optional[Table] = None,
  3553. **kw: Any,
  3554. ) -> ColumnCollectionConstraint:
  3555. # ticket #5276
  3556. constraint_kwargs = {}
  3557. for dialect_name in self.dialect_options:
  3558. dialect_options = self.dialect_options[dialect_name]._non_defaults
  3559. for (
  3560. dialect_option_key,
  3561. dialect_option_value,
  3562. ) in dialect_options.items():
  3563. constraint_kwargs[
  3564. dialect_name + "_" + dialect_option_key
  3565. ] = dialect_option_value
  3566. assert isinstance(self.parent, Table)
  3567. c = self.__class__(
  3568. name=self.name,
  3569. deferrable=self.deferrable,
  3570. initially=self.initially,
  3571. *[
  3572. _copy_expression(expr, self.parent, target_table)
  3573. for expr in self._columns
  3574. ],
  3575. comment=self.comment,
  3576. **constraint_kwargs,
  3577. )
  3578. return self._schema_item_copy(c)
  3579. def contains_column(self, col: Column[Any]) -> bool:
  3580. """Return True if this constraint contains the given column.
  3581. Note that this object also contains an attribute ``.columns``
  3582. which is a :class:`_expression.ColumnCollection` of
  3583. :class:`_schema.Column` objects.
  3584. """
  3585. return self._columns.contains_column(col)
  3586. def __iter__(self) -> Iterator[Column[Any]]:
  3587. return iter(self._columns)
  3588. def __len__(self) -> int:
  3589. return len(self._columns)
  3590. class CheckConstraint(ColumnCollectionConstraint):
  3591. """A table- or column-level CHECK constraint.
  3592. Can be included in the definition of a Table or Column.
  3593. """
  3594. _allow_multiple_tables = True
  3595. __visit_name__ = "table_or_column_check_constraint"
  3596. @_document_text_coercion(
  3597. "sqltext",
  3598. ":class:`.CheckConstraint`",
  3599. ":paramref:`.CheckConstraint.sqltext`",
  3600. )
  3601. def __init__(
  3602. self,
  3603. sqltext: _TextCoercedExpressionArgument[Any],
  3604. name: _ConstraintNameArgument = None,
  3605. deferrable: Optional[bool] = None,
  3606. initially: Optional[str] = None,
  3607. table: Optional[Table] = None,
  3608. info: Optional[_InfoType] = None,
  3609. _create_rule: Optional[Any] = None,
  3610. _autoattach: bool = True,
  3611. _type_bound: bool = False,
  3612. **dialect_kw: Any,
  3613. ) -> None:
  3614. r"""Construct a CHECK constraint.
  3615. :param sqltext:
  3616. A string containing the constraint definition, which will be used
  3617. verbatim, or a SQL expression construct. If given as a string,
  3618. the object is converted to a :func:`_expression.text` object.
  3619. If the textual
  3620. string includes a colon character, escape this using a backslash::
  3621. CheckConstraint(r"foo ~ E'a(?\:b|c)d")
  3622. :param name:
  3623. Optional, the in-database name of the constraint.
  3624. :param deferrable:
  3625. Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
  3626. issuing DDL for this constraint.
  3627. :param initially:
  3628. Optional string. If set, emit INITIALLY <value> when issuing DDL
  3629. for this constraint.
  3630. :param info: Optional data dictionary which will be populated into the
  3631. :attr:`.SchemaItem.info` attribute of this object.
  3632. """
  3633. self.sqltext = coercions.expect(roles.DDLExpressionRole, sqltext)
  3634. columns: List[Column[Any]] = []
  3635. visitors.traverse(self.sqltext, {}, {"column": columns.append})
  3636. super().__init__(
  3637. name=name,
  3638. deferrable=deferrable,
  3639. initially=initially,
  3640. _create_rule=_create_rule,
  3641. info=info,
  3642. _type_bound=_type_bound,
  3643. _autoattach=_autoattach,
  3644. *columns,
  3645. **dialect_kw,
  3646. )
  3647. if table is not None:
  3648. self._set_parent_with_dispatch(table)
  3649. @property
  3650. def is_column_level(self) -> bool:
  3651. return not isinstance(self.parent, Table)
  3652. @util.deprecated(
  3653. "1.4",
  3654. "The :meth:`_schema.CheckConstraint.copy` method is deprecated "
  3655. "and will be removed in a future release.",
  3656. )
  3657. def copy(
  3658. self, *, target_table: Optional[Table] = None, **kw: Any
  3659. ) -> CheckConstraint:
  3660. return self._copy(target_table=target_table, **kw)
  3661. def _copy(
  3662. self, *, target_table: Optional[Table] = None, **kw: Any
  3663. ) -> CheckConstraint:
  3664. if target_table is not None:
  3665. # note that target_table is None for the copy process of
  3666. # a column-bound CheckConstraint, so this path is not reached
  3667. # in that case.
  3668. sqltext = _copy_expression(self.sqltext, self.table, target_table)
  3669. else:
  3670. sqltext = self.sqltext
  3671. c = CheckConstraint(
  3672. sqltext,
  3673. name=self.name,
  3674. initially=self.initially,
  3675. deferrable=self.deferrable,
  3676. _create_rule=self._create_rule,
  3677. table=target_table,
  3678. comment=self.comment,
  3679. _autoattach=False,
  3680. _type_bound=self._type_bound,
  3681. )
  3682. return self._schema_item_copy(c)
  3683. class ForeignKeyConstraint(ColumnCollectionConstraint):
  3684. """A table-level FOREIGN KEY constraint.
  3685. Defines a single column or composite FOREIGN KEY ... REFERENCES
  3686. constraint. For a no-frills, single column foreign key, adding a
  3687. :class:`_schema.ForeignKey` to the definition of a :class:`_schema.Column`
  3688. is a
  3689. shorthand equivalent for an unnamed, single column
  3690. :class:`_schema.ForeignKeyConstraint`.
  3691. Examples of foreign key configuration are in :ref:`metadata_foreignkeys`.
  3692. """
  3693. __visit_name__ = "foreign_key_constraint"
  3694. def __init__(
  3695. self,
  3696. columns: _typing_Sequence[_DDLColumnArgument],
  3697. refcolumns: _typing_Sequence[_DDLColumnArgument],
  3698. name: _ConstraintNameArgument = None,
  3699. onupdate: Optional[str] = None,
  3700. ondelete: Optional[str] = None,
  3701. deferrable: Optional[bool] = None,
  3702. initially: Optional[str] = None,
  3703. use_alter: bool = False,
  3704. link_to_name: bool = False,
  3705. match: Optional[str] = None,
  3706. table: Optional[Table] = None,
  3707. info: Optional[_InfoType] = None,
  3708. comment: Optional[str] = None,
  3709. **dialect_kw: Any,
  3710. ) -> None:
  3711. r"""Construct a composite-capable FOREIGN KEY.
  3712. :param columns: A sequence of local column names. The named columns
  3713. must be defined and present in the parent Table. The names should
  3714. match the ``key`` given to each column (defaults to the name) unless
  3715. ``link_to_name`` is True.
  3716. :param refcolumns: A sequence of foreign column names or Column
  3717. objects. The columns must all be located within the same Table.
  3718. :param name: Optional, the in-database name of the key.
  3719. :param onupdate: Optional string. If set, emit ON UPDATE <value> when
  3720. issuing DDL for this constraint. Typical values include CASCADE,
  3721. DELETE and RESTRICT.
  3722. :param ondelete: Optional string. If set, emit ON DELETE <value> when
  3723. issuing DDL for this constraint. Typical values include CASCADE,
  3724. DELETE and RESTRICT.
  3725. :param deferrable: Optional bool. If set, emit DEFERRABLE or NOT
  3726. DEFERRABLE when issuing DDL for this constraint.
  3727. :param initially: Optional string. If set, emit INITIALLY <value> when
  3728. issuing DDL for this constraint.
  3729. :param link_to_name: if True, the string name given in ``column`` is
  3730. the rendered name of the referenced column, not its locally assigned
  3731. ``key``.
  3732. :param use_alter: If True, do not emit the DDL for this constraint as
  3733. part of the CREATE TABLE definition. Instead, generate it via an
  3734. ALTER TABLE statement issued after the full collection of tables
  3735. have been created, and drop it via an ALTER TABLE statement before
  3736. the full collection of tables are dropped.
  3737. The use of :paramref:`_schema.ForeignKeyConstraint.use_alter` is
  3738. particularly geared towards the case where two or more tables
  3739. are established within a mutually-dependent foreign key constraint
  3740. relationship; however, the :meth:`_schema.MetaData.create_all` and
  3741. :meth:`_schema.MetaData.drop_all`
  3742. methods will perform this resolution
  3743. automatically, so the flag is normally not needed.
  3744. .. seealso::
  3745. :ref:`use_alter`
  3746. :param match: Optional string. If set, emit MATCH <value> when issuing
  3747. DDL for this constraint. Typical values include SIMPLE, PARTIAL
  3748. and FULL.
  3749. :param info: Optional data dictionary which will be populated into the
  3750. :attr:`.SchemaItem.info` attribute of this object.
  3751. :param comment: Optional string that will render an SQL comment on
  3752. foreign key constraint creation.
  3753. .. versionadded:: 2.0
  3754. :param \**dialect_kw: Additional keyword arguments are dialect
  3755. specific, and passed in the form ``<dialectname>_<argname>``. See
  3756. the documentation regarding an individual dialect at
  3757. :ref:`dialect_toplevel` for detail on documented arguments.
  3758. """
  3759. Constraint.__init__(
  3760. self,
  3761. name=name,
  3762. deferrable=deferrable,
  3763. initially=initially,
  3764. info=info,
  3765. comment=comment,
  3766. **dialect_kw,
  3767. )
  3768. self.onupdate = onupdate
  3769. self.ondelete = ondelete
  3770. self.link_to_name = link_to_name
  3771. self.use_alter = use_alter
  3772. self.match = match
  3773. if len(set(columns)) != len(refcolumns):
  3774. if len(set(columns)) != len(columns):
  3775. # e.g. FOREIGN KEY (a, a) REFERENCES r (b, c)
  3776. raise exc.ArgumentError(
  3777. "ForeignKeyConstraint with duplicate source column "
  3778. "references are not supported."
  3779. )
  3780. else:
  3781. # e.g. FOREIGN KEY (a) REFERENCES r (b, c)
  3782. # paraphrasing
  3783. # https://www.postgresql.org/docs/current/static/ddl-constraints.html
  3784. raise exc.ArgumentError(
  3785. "ForeignKeyConstraint number "
  3786. "of constrained columns must match the number of "
  3787. "referenced columns."
  3788. )
  3789. # standalone ForeignKeyConstraint - create
  3790. # associated ForeignKey objects which will be applied to hosted
  3791. # Column objects (in col.foreign_keys), either now or when attached
  3792. # to the Table for string-specified names
  3793. self.elements = [
  3794. ForeignKey(
  3795. refcol,
  3796. _constraint=self,
  3797. name=self.name,
  3798. onupdate=self.onupdate,
  3799. ondelete=self.ondelete,
  3800. use_alter=self.use_alter,
  3801. link_to_name=self.link_to_name,
  3802. match=self.match,
  3803. deferrable=self.deferrable,
  3804. initially=self.initially,
  3805. **self.dialect_kwargs,
  3806. )
  3807. for refcol in refcolumns
  3808. ]
  3809. ColumnCollectionMixin.__init__(self, *columns)
  3810. if table is not None:
  3811. if hasattr(self, "parent"):
  3812. assert table is self.parent
  3813. self._set_parent_with_dispatch(table)
  3814. def _append_element(self, column: Column[Any], fk: ForeignKey) -> None:
  3815. self._columns.add(column)
  3816. self.elements.append(fk)
  3817. columns: ReadOnlyColumnCollection[str, Column[Any]]
  3818. """A :class:`_expression.ColumnCollection` representing the set of columns
  3819. for this constraint.
  3820. """
  3821. elements: List[ForeignKey]
  3822. """A sequence of :class:`_schema.ForeignKey` objects.
  3823. Each :class:`_schema.ForeignKey`
  3824. represents a single referring column/referred
  3825. column pair.
  3826. This collection is intended to be read-only.
  3827. """
  3828. @property
  3829. def _elements(self) -> util.OrderedDict[str, ForeignKey]:
  3830. # legacy - provide a dictionary view of (column_key, fk)
  3831. return util.OrderedDict(zip(self.column_keys, self.elements))
  3832. @property
  3833. def _referred_schema(self) -> Optional[str]:
  3834. for elem in self.elements:
  3835. return elem._referred_schema
  3836. else:
  3837. return None
  3838. @property
  3839. def referred_table(self) -> Table:
  3840. """The :class:`_schema.Table` object to which this
  3841. :class:`_schema.ForeignKeyConstraint` references.
  3842. This is a dynamically calculated attribute which may not be available
  3843. if the constraint and/or parent table is not yet associated with
  3844. a metadata collection that contains the referred table.
  3845. """
  3846. return self.elements[0].column.table
  3847. def _validate_dest_table(self, table: Table) -> None:
  3848. table_keys = {elem._table_key() for elem in self.elements}
  3849. if None not in table_keys and len(table_keys) > 1:
  3850. elem0, elem1 = sorted(table_keys)[0:2]
  3851. raise exc.ArgumentError(
  3852. f"ForeignKeyConstraint on "
  3853. f"{table.fullname}({self._col_description}) refers to "
  3854. f"multiple remote tables: {elem0} and {elem1}"
  3855. )
  3856. @property
  3857. def column_keys(self) -> _typing_Sequence[str]:
  3858. """Return a list of string keys representing the local
  3859. columns in this :class:`_schema.ForeignKeyConstraint`.
  3860. This list is either the original string arguments sent
  3861. to the constructor of the :class:`_schema.ForeignKeyConstraint`,
  3862. or if the constraint has been initialized with :class:`_schema.Column`
  3863. objects, is the string ``.key`` of each element.
  3864. """
  3865. if hasattr(self, "parent"):
  3866. return self._columns.keys()
  3867. else:
  3868. return [
  3869. col.key if isinstance(col, ColumnElement) else str(col)
  3870. for col in self._pending_colargs
  3871. ]
  3872. @property
  3873. def _col_description(self) -> str:
  3874. return ", ".join(self.column_keys)
  3875. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  3876. table = parent
  3877. assert isinstance(table, Table)
  3878. Constraint._set_parent(self, table)
  3879. ColumnCollectionConstraint._set_parent(self, table)
  3880. for col, fk in zip(self._columns, self.elements):
  3881. if not hasattr(fk, "parent") or fk.parent is not col:
  3882. fk._set_parent_with_dispatch(col)
  3883. self._validate_dest_table(table)
  3884. @util.deprecated(
  3885. "1.4",
  3886. "The :meth:`_schema.ForeignKeyConstraint.copy` method is deprecated "
  3887. "and will be removed in a future release.",
  3888. )
  3889. def copy(
  3890. self,
  3891. *,
  3892. schema: Optional[str] = None,
  3893. target_table: Optional[Table] = None,
  3894. **kw: Any,
  3895. ) -> ForeignKeyConstraint:
  3896. return self._copy(schema=schema, target_table=target_table, **kw)
  3897. def _copy(
  3898. self,
  3899. *,
  3900. schema: Optional[str] = None,
  3901. target_table: Optional[Table] = None,
  3902. **kw: Any,
  3903. ) -> ForeignKeyConstraint:
  3904. fkc = ForeignKeyConstraint(
  3905. [x.parent.key for x in self.elements],
  3906. [
  3907. x._get_colspec(
  3908. schema=schema,
  3909. table_name=target_table.name
  3910. if target_table is not None
  3911. and x._table_key() == x.parent.table.key
  3912. else None,
  3913. _is_copy=True,
  3914. )
  3915. for x in self.elements
  3916. ],
  3917. name=self.name,
  3918. onupdate=self.onupdate,
  3919. ondelete=self.ondelete,
  3920. use_alter=self.use_alter,
  3921. deferrable=self.deferrable,
  3922. initially=self.initially,
  3923. link_to_name=self.link_to_name,
  3924. match=self.match,
  3925. comment=self.comment,
  3926. )
  3927. for self_fk, other_fk in zip(self.elements, fkc.elements):
  3928. self_fk._schema_item_copy(other_fk)
  3929. return self._schema_item_copy(fkc)
  3930. class PrimaryKeyConstraint(ColumnCollectionConstraint):
  3931. """A table-level PRIMARY KEY constraint.
  3932. The :class:`.PrimaryKeyConstraint` object is present automatically
  3933. on any :class:`_schema.Table` object; it is assigned a set of
  3934. :class:`_schema.Column` objects corresponding to those marked with
  3935. the :paramref:`_schema.Column.primary_key` flag::
  3936. >>> my_table = Table('mytable', metadata,
  3937. ... Column('id', Integer, primary_key=True),
  3938. ... Column('version_id', Integer, primary_key=True),
  3939. ... Column('data', String(50))
  3940. ... )
  3941. >>> my_table.primary_key
  3942. PrimaryKeyConstraint(
  3943. Column('id', Integer(), table=<mytable>,
  3944. primary_key=True, nullable=False),
  3945. Column('version_id', Integer(), table=<mytable>,
  3946. primary_key=True, nullable=False)
  3947. )
  3948. The primary key of a :class:`_schema.Table` can also be specified by using
  3949. a :class:`.PrimaryKeyConstraint` object explicitly; in this mode of usage,
  3950. the "name" of the constraint can also be specified, as well as other
  3951. options which may be recognized by dialects::
  3952. my_table = Table('mytable', metadata,
  3953. Column('id', Integer),
  3954. Column('version_id', Integer),
  3955. Column('data', String(50)),
  3956. PrimaryKeyConstraint('id', 'version_id',
  3957. name='mytable_pk')
  3958. )
  3959. The two styles of column-specification should generally not be mixed.
  3960. An warning is emitted if the columns present in the
  3961. :class:`.PrimaryKeyConstraint`
  3962. don't match the columns that were marked as ``primary_key=True``, if both
  3963. are present; in this case, the columns are taken strictly from the
  3964. :class:`.PrimaryKeyConstraint` declaration, and those columns otherwise
  3965. marked as ``primary_key=True`` are ignored. This behavior is intended to
  3966. be backwards compatible with previous behavior.
  3967. For the use case where specific options are to be specified on the
  3968. :class:`.PrimaryKeyConstraint`, but the usual style of using
  3969. ``primary_key=True`` flags is still desirable, an empty
  3970. :class:`.PrimaryKeyConstraint` may be specified, which will take on the
  3971. primary key column collection from the :class:`_schema.Table` based on the
  3972. flags::
  3973. my_table = Table('mytable', metadata,
  3974. Column('id', Integer, primary_key=True),
  3975. Column('version_id', Integer, primary_key=True),
  3976. Column('data', String(50)),
  3977. PrimaryKeyConstraint(name='mytable_pk',
  3978. mssql_clustered=True)
  3979. )
  3980. """
  3981. __visit_name__ = "primary_key_constraint"
  3982. def __init__(
  3983. self,
  3984. *columns: _DDLColumnArgument,
  3985. name: Optional[str] = None,
  3986. deferrable: Optional[bool] = None,
  3987. initially: Optional[str] = None,
  3988. info: Optional[_InfoType] = None,
  3989. _implicit_generated: bool = False,
  3990. **dialect_kw: Any,
  3991. ) -> None:
  3992. self._implicit_generated = _implicit_generated
  3993. super().__init__(
  3994. *columns,
  3995. name=name,
  3996. deferrable=deferrable,
  3997. initially=initially,
  3998. info=info,
  3999. **dialect_kw,
  4000. )
  4001. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  4002. table = parent
  4003. assert isinstance(table, Table)
  4004. super()._set_parent(table)
  4005. if table.primary_key is not self:
  4006. table.constraints.discard(table.primary_key)
  4007. table.primary_key = self # type: ignore
  4008. table.constraints.add(self)
  4009. table_pks = [c for c in table.c if c.primary_key]
  4010. if (
  4011. self._columns
  4012. and table_pks
  4013. and set(table_pks) != set(self._columns)
  4014. ):
  4015. # black could not format these inline
  4016. table_pk_str = ", ".join("'%s'" % c.name for c in table_pks)
  4017. col_str = ", ".join("'%s'" % c.name for c in self._columns)
  4018. util.warn(
  4019. f"Table '{table.name}' specifies columns "
  4020. f"{table_pk_str} as "
  4021. f"primary_key=True, "
  4022. f"not matching locally specified columns {col_str}; "
  4023. f"setting the "
  4024. f"current primary key columns to "
  4025. f"{col_str}. "
  4026. f"This warning "
  4027. f"may become an exception in a future release"
  4028. )
  4029. table_pks[:] = []
  4030. for c in self._columns:
  4031. c.primary_key = True
  4032. if c._user_defined_nullable is NULL_UNSPECIFIED:
  4033. c.nullable = False
  4034. if table_pks:
  4035. self._columns.extend(table_pks)
  4036. def _reload(self, columns: Iterable[Column[Any]]) -> None:
  4037. """repopulate this :class:`.PrimaryKeyConstraint` given
  4038. a set of columns.
  4039. Existing columns in the table that are marked as primary_key=True
  4040. are maintained.
  4041. Also fires a new event.
  4042. This is basically like putting a whole new
  4043. :class:`.PrimaryKeyConstraint` object on the parent
  4044. :class:`_schema.Table` object without actually replacing the object.
  4045. The ordering of the given list of columns is also maintained; these
  4046. columns will be appended to the list of columns after any which
  4047. are already present.
  4048. """
  4049. # set the primary key flag on new columns.
  4050. # note any existing PK cols on the table also have their
  4051. # flag still set.
  4052. for col in columns:
  4053. col.primary_key = True
  4054. self._columns.extend(columns)
  4055. PrimaryKeyConstraint._autoincrement_column._reset(self) # type: ignore
  4056. self._set_parent_with_dispatch(self.table)
  4057. def _replace(self, col: Column[Any]) -> None:
  4058. PrimaryKeyConstraint._autoincrement_column._reset(self) # type: ignore
  4059. self._columns.replace(col)
  4060. self.dispatch._sa_event_column_added_to_pk_constraint(self, col)
  4061. @property
  4062. def columns_autoinc_first(self) -> List[Column[Any]]:
  4063. autoinc = self._autoincrement_column
  4064. if autoinc is not None:
  4065. return [autoinc] + [c for c in self._columns if c is not autoinc]
  4066. else:
  4067. return list(self._columns)
  4068. @util.ro_memoized_property
  4069. def _autoincrement_column(self) -> Optional[Column[int]]:
  4070. def _validate_autoinc(col: Column[Any], autoinc_true: bool) -> bool:
  4071. if col.type._type_affinity is None or not issubclass(
  4072. col.type._type_affinity,
  4073. (
  4074. type_api.INTEGERTYPE._type_affinity,
  4075. type_api.NUMERICTYPE._type_affinity,
  4076. ),
  4077. ):
  4078. if autoinc_true:
  4079. raise exc.ArgumentError(
  4080. f"Column type {col.type} on column '{col}' is not "
  4081. f"compatible with autoincrement=True"
  4082. )
  4083. else:
  4084. return False
  4085. elif (
  4086. not isinstance(col.default, (type(None), Sequence))
  4087. and not autoinc_true
  4088. ):
  4089. return False
  4090. elif (
  4091. col.server_default is not None
  4092. and not isinstance(col.server_default, Identity)
  4093. and not autoinc_true
  4094. ):
  4095. return False
  4096. elif col.foreign_keys and col.autoincrement not in (
  4097. True,
  4098. "ignore_fk",
  4099. ):
  4100. return False
  4101. return True
  4102. if len(self._columns) == 1:
  4103. col = list(self._columns)[0]
  4104. if col.autoincrement is True:
  4105. _validate_autoinc(col, True)
  4106. return col
  4107. elif col.autoincrement in (
  4108. "auto",
  4109. "ignore_fk",
  4110. ) and _validate_autoinc(col, False):
  4111. return col
  4112. else:
  4113. return None
  4114. else:
  4115. autoinc = None
  4116. for col in self._columns:
  4117. if col.autoincrement is True:
  4118. _validate_autoinc(col, True)
  4119. if autoinc is not None:
  4120. raise exc.ArgumentError(
  4121. f"Only one Column may be marked "
  4122. f"autoincrement=True, found both "
  4123. f"{col.name} and {autoinc.name}."
  4124. )
  4125. else:
  4126. autoinc = col
  4127. return autoinc
  4128. class UniqueConstraint(ColumnCollectionConstraint):
  4129. """A table-level UNIQUE constraint.
  4130. Defines a single column or composite UNIQUE constraint. For a no-frills,
  4131. single column constraint, adding ``unique=True`` to the ``Column``
  4132. definition is a shorthand equivalent for an unnamed, single column
  4133. UniqueConstraint.
  4134. """
  4135. __visit_name__ = "unique_constraint"
  4136. class Index(
  4137. DialectKWArgs, ColumnCollectionMixin, HasConditionalDDL, SchemaItem
  4138. ):
  4139. """A table-level INDEX.
  4140. Defines a composite (one or more column) INDEX.
  4141. E.g.::
  4142. sometable = Table("sometable", metadata,
  4143. Column("name", String(50)),
  4144. Column("address", String(100))
  4145. )
  4146. Index("some_index", sometable.c.name)
  4147. For a no-frills, single column index, adding
  4148. :class:`_schema.Column` also supports ``index=True``::
  4149. sometable = Table("sometable", metadata,
  4150. Column("name", String(50), index=True)
  4151. )
  4152. For a composite index, multiple columns can be specified::
  4153. Index("some_index", sometable.c.name, sometable.c.address)
  4154. Functional indexes are supported as well, typically by using the
  4155. :data:`.func` construct in conjunction with table-bound
  4156. :class:`_schema.Column` objects::
  4157. Index("some_index", func.lower(sometable.c.name))
  4158. An :class:`.Index` can also be manually associated with a
  4159. :class:`_schema.Table`,
  4160. either through inline declaration or using
  4161. :meth:`_schema.Table.append_constraint`. When this approach is used,
  4162. the names
  4163. of the indexed columns can be specified as strings::
  4164. Table("sometable", metadata,
  4165. Column("name", String(50)),
  4166. Column("address", String(100)),
  4167. Index("some_index", "name", "address")
  4168. )
  4169. To support functional or expression-based indexes in this form, the
  4170. :func:`_expression.text` construct may be used::
  4171. from sqlalchemy import text
  4172. Table("sometable", metadata,
  4173. Column("name", String(50)),
  4174. Column("address", String(100)),
  4175. Index("some_index", text("lower(name)"))
  4176. )
  4177. .. seealso::
  4178. :ref:`schema_indexes` - General information on :class:`.Index`.
  4179. :ref:`postgresql_indexes` - PostgreSQL-specific options available for
  4180. the :class:`.Index` construct.
  4181. :ref:`mysql_indexes` - MySQL-specific options available for the
  4182. :class:`.Index` construct.
  4183. :ref:`mssql_indexes` - MSSQL-specific options available for the
  4184. :class:`.Index` construct.
  4185. """
  4186. __visit_name__ = "index"
  4187. table: Optional[Table]
  4188. expressions: _typing_Sequence[Union[str, ColumnElement[Any]]]
  4189. _table_bound_expressions: _typing_Sequence[ColumnElement[Any]]
  4190. def __init__(
  4191. self,
  4192. name: Optional[str],
  4193. *expressions: _DDLColumnArgument,
  4194. unique: bool = False,
  4195. quote: Optional[bool] = None,
  4196. info: Optional[_InfoType] = None,
  4197. _table: Optional[Table] = None,
  4198. _column_flag: bool = False,
  4199. **dialect_kw: Any,
  4200. ) -> None:
  4201. r"""Construct an index object.
  4202. :param name:
  4203. The name of the index
  4204. :param \*expressions:
  4205. Column expressions to include in the index. The expressions
  4206. are normally instances of :class:`_schema.Column`, but may also
  4207. be arbitrary SQL expressions which ultimately refer to a
  4208. :class:`_schema.Column`.
  4209. :param unique=False:
  4210. Keyword only argument; if True, create a unique index.
  4211. :param quote=None:
  4212. Keyword only argument; whether to apply quoting to the name of
  4213. the index. Works in the same manner as that of
  4214. :paramref:`_schema.Column.quote`.
  4215. :param info=None: Optional data dictionary which will be populated
  4216. into the :attr:`.SchemaItem.info` attribute of this object.
  4217. :param \**dialect_kw: Additional keyword arguments not mentioned above
  4218. are dialect specific, and passed in the form
  4219. ``<dialectname>_<argname>``. See the documentation regarding an
  4220. individual dialect at :ref:`dialect_toplevel` for detail on
  4221. documented arguments.
  4222. """
  4223. self.table = table = None
  4224. self.name = quoted_name.construct(name, quote)
  4225. self.unique = unique
  4226. if info is not None:
  4227. self.info = info
  4228. # TODO: consider "table" argument being public, but for
  4229. # the purpose of the fix here, it starts as private.
  4230. if _table is not None:
  4231. table = _table
  4232. self._validate_dialect_kwargs(dialect_kw)
  4233. self.expressions = []
  4234. # will call _set_parent() if table-bound column
  4235. # objects are present
  4236. ColumnCollectionMixin.__init__(
  4237. self,
  4238. *expressions,
  4239. _column_flag=_column_flag,
  4240. _gather_expressions=self.expressions,
  4241. )
  4242. if table is not None:
  4243. self._set_parent(table)
  4244. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  4245. table = parent
  4246. assert isinstance(table, Table)
  4247. ColumnCollectionMixin._set_parent(self, table)
  4248. if self.table is not None and table is not self.table:
  4249. raise exc.ArgumentError(
  4250. f"Index '{self.name}' is against table "
  4251. f"'{self.table.description}', and "
  4252. f"cannot be associated with table '{table.description}'."
  4253. )
  4254. self.table = table
  4255. table.indexes.add(self)
  4256. expressions = self.expressions
  4257. col_expressions = self._col_expressions(table)
  4258. assert len(expressions) == len(col_expressions)
  4259. exprs = []
  4260. for expr, colexpr in zip(expressions, col_expressions):
  4261. if isinstance(expr, ClauseElement):
  4262. exprs.append(expr)
  4263. elif colexpr is not None:
  4264. exprs.append(colexpr)
  4265. else:
  4266. assert False
  4267. self.expressions = self._table_bound_expressions = exprs
  4268. def create(self, bind: _CreateDropBind, checkfirst: bool = False) -> None:
  4269. """Issue a ``CREATE`` statement for this
  4270. :class:`.Index`, using the given
  4271. :class:`.Connection` or :class:`.Engine`` for connectivity.
  4272. .. seealso::
  4273. :meth:`_schema.MetaData.create_all`.
  4274. """
  4275. bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
  4276. def drop(self, bind: _CreateDropBind, checkfirst: bool = False) -> None:
  4277. """Issue a ``DROP`` statement for this
  4278. :class:`.Index`, using the given
  4279. :class:`.Connection` or :class:`.Engine` for connectivity.
  4280. .. seealso::
  4281. :meth:`_schema.MetaData.drop_all`.
  4282. """
  4283. bind._run_ddl_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
  4284. def __repr__(self) -> str:
  4285. exprs: _typing_Sequence[Any] # noqa: F842
  4286. return "Index(%s)" % (
  4287. ", ".join(
  4288. [repr(self.name)]
  4289. + [repr(e) for e in self.expressions]
  4290. + (self.unique and ["unique=True"] or [])
  4291. )
  4292. )
  4293. _NamingSchemaCallable = Callable[[Constraint, Table], str]
  4294. _NamingSchemaDirective = Union[str, _NamingSchemaCallable]
  4295. class _NamingSchemaTD(TypedDict, total=False):
  4296. fk: _NamingSchemaDirective
  4297. pk: _NamingSchemaDirective
  4298. ix: _NamingSchemaDirective
  4299. ck: _NamingSchemaDirective
  4300. uq: _NamingSchemaDirective
  4301. _NamingSchemaParameter = Union[
  4302. # it seems like the TypedDict here is useful for pylance typeahead,
  4303. # and not much else
  4304. _NamingSchemaTD,
  4305. # there is no form that allows Union[Type[Any], str] to work in all
  4306. # cases, including breaking out Mapping[] entries for each combination
  4307. # even, therefore keys must be `Any` (see #10264)
  4308. Mapping[Any, _NamingSchemaDirective],
  4309. ]
  4310. DEFAULT_NAMING_CONVENTION: _NamingSchemaParameter = util.immutabledict(
  4311. {"ix": "ix_%(column_0_label)s"}
  4312. )
  4313. class MetaData(HasSchemaAttr):
  4314. """A collection of :class:`_schema.Table`
  4315. objects and their associated schema
  4316. constructs.
  4317. Holds a collection of :class:`_schema.Table` objects as well as
  4318. an optional binding to an :class:`_engine.Engine` or
  4319. :class:`_engine.Connection`. If bound, the :class:`_schema.Table` objects
  4320. in the collection and their columns may participate in implicit SQL
  4321. execution.
  4322. The :class:`_schema.Table` objects themselves are stored in the
  4323. :attr:`_schema.MetaData.tables` dictionary.
  4324. :class:`_schema.MetaData` is a thread-safe object for read operations.
  4325. Construction of new tables within a single :class:`_schema.MetaData`
  4326. object,
  4327. either explicitly or via reflection, may not be completely thread-safe.
  4328. .. seealso::
  4329. :ref:`metadata_describing` - Introduction to database metadata
  4330. """
  4331. __visit_name__ = "metadata"
  4332. def __init__(
  4333. self,
  4334. schema: Optional[str] = None,
  4335. quote_schema: Optional[bool] = None,
  4336. naming_convention: Optional[_NamingSchemaParameter] = None,
  4337. info: Optional[_InfoType] = None,
  4338. ) -> None:
  4339. """Create a new MetaData object.
  4340. :param schema:
  4341. The default schema to use for the :class:`_schema.Table`,
  4342. :class:`.Sequence`, and potentially other objects associated with
  4343. this :class:`_schema.MetaData`. Defaults to ``None``.
  4344. .. seealso::
  4345. :ref:`schema_metadata_schema_name` - details on how the
  4346. :paramref:`_schema.MetaData.schema` parameter is used.
  4347. :paramref:`_schema.Table.schema`
  4348. :paramref:`.Sequence.schema`
  4349. :param quote_schema:
  4350. Sets the ``quote_schema`` flag for those :class:`_schema.Table`,
  4351. :class:`.Sequence`, and other objects which make usage of the
  4352. local ``schema`` name.
  4353. :param info: Optional data dictionary which will be populated into the
  4354. :attr:`.SchemaItem.info` attribute of this object.
  4355. :param naming_convention: a dictionary referring to values which
  4356. will establish default naming conventions for :class:`.Constraint`
  4357. and :class:`.Index` objects, for those objects which are not given
  4358. a name explicitly.
  4359. The keys of this dictionary may be:
  4360. * a constraint or Index class, e.g. the :class:`.UniqueConstraint`,
  4361. :class:`_schema.ForeignKeyConstraint` class, the :class:`.Index`
  4362. class
  4363. * a string mnemonic for one of the known constraint classes;
  4364. ``"fk"``, ``"pk"``, ``"ix"``, ``"ck"``, ``"uq"`` for foreign key,
  4365. primary key, index, check, and unique constraint, respectively.
  4366. * the string name of a user-defined "token" that can be used
  4367. to define new naming tokens.
  4368. The values associated with each "constraint class" or "constraint
  4369. mnemonic" key are string naming templates, such as
  4370. ``"uq_%(table_name)s_%(column_0_name)s"``,
  4371. which describe how the name should be composed. The values
  4372. associated with user-defined "token" keys should be callables of the
  4373. form ``fn(constraint, table)``, which accepts the constraint/index
  4374. object and :class:`_schema.Table` as arguments, returning a string
  4375. result.
  4376. The built-in names are as follows, some of which may only be
  4377. available for certain types of constraint:
  4378. * ``%(table_name)s`` - the name of the :class:`_schema.Table`
  4379. object
  4380. associated with the constraint.
  4381. * ``%(referred_table_name)s`` - the name of the
  4382. :class:`_schema.Table`
  4383. object associated with the referencing target of a
  4384. :class:`_schema.ForeignKeyConstraint`.
  4385. * ``%(column_0_name)s`` - the name of the :class:`_schema.Column`
  4386. at
  4387. index position "0" within the constraint.
  4388. * ``%(column_0N_name)s`` - the name of all :class:`_schema.Column`
  4389. objects in order within the constraint, joined without a
  4390. separator.
  4391. * ``%(column_0_N_name)s`` - the name of all
  4392. :class:`_schema.Column`
  4393. objects in order within the constraint, joined with an
  4394. underscore as a separator.
  4395. * ``%(column_0_label)s``, ``%(column_0N_label)s``,
  4396. ``%(column_0_N_label)s`` - the label of either the zeroth
  4397. :class:`_schema.Column` or all :class:`.Columns`, separated with
  4398. or without an underscore
  4399. * ``%(column_0_key)s``, ``%(column_0N_key)s``,
  4400. ``%(column_0_N_key)s`` - the key of either the zeroth
  4401. :class:`_schema.Column` or all :class:`.Columns`, separated with
  4402. or without an underscore
  4403. * ``%(referred_column_0_name)s``, ``%(referred_column_0N_name)s``
  4404. ``%(referred_column_0_N_name)s``, ``%(referred_column_0_key)s``,
  4405. ``%(referred_column_0N_key)s``, ... column tokens which
  4406. render the names/keys/labels of columns that are referenced
  4407. by a :class:`_schema.ForeignKeyConstraint`.
  4408. * ``%(constraint_name)s`` - a special key that refers to the
  4409. existing name given to the constraint. When this key is
  4410. present, the :class:`.Constraint` object's existing name will be
  4411. replaced with one that is composed from template string that
  4412. uses this token. When this token is present, it is required that
  4413. the :class:`.Constraint` is given an explicit name ahead of time.
  4414. * user-defined: any additional token may be implemented by passing
  4415. it along with a ``fn(constraint, table)`` callable to the
  4416. naming_convention dictionary.
  4417. .. versionadded:: 1.3.0 - added new ``%(column_0N_name)s``,
  4418. ``%(column_0_N_name)s``, and related tokens that produce
  4419. concatenations of names, keys, or labels for all columns referred
  4420. to by a given constraint.
  4421. .. seealso::
  4422. :ref:`constraint_naming_conventions` - for detailed usage
  4423. examples.
  4424. """
  4425. if schema is not None and not isinstance(schema, str):
  4426. raise exc.ArgumentError(
  4427. "expected schema argument to be a string, "
  4428. f"got {type(schema)}."
  4429. )
  4430. self.tables = util.FacadeDict()
  4431. self.schema = quoted_name.construct(schema, quote_schema)
  4432. self.naming_convention = (
  4433. naming_convention
  4434. if naming_convention
  4435. else DEFAULT_NAMING_CONVENTION
  4436. )
  4437. if info:
  4438. self.info = info
  4439. self._schemas: Set[str] = set()
  4440. self._sequences: Dict[str, Sequence] = {}
  4441. self._fk_memos: Dict[
  4442. Tuple[str, Optional[str]], List[ForeignKey]
  4443. ] = collections.defaultdict(list)
  4444. tables: util.FacadeDict[str, Table]
  4445. """A dictionary of :class:`_schema.Table`
  4446. objects keyed to their name or "table key".
  4447. The exact key is that determined by the :attr:`_schema.Table.key`
  4448. attribute;
  4449. for a table with no :attr:`_schema.Table.schema` attribute,
  4450. this is the same
  4451. as :attr:`_schema.Table.name`. For a table with a schema,
  4452. it is typically of the
  4453. form ``schemaname.tablename``.
  4454. .. seealso::
  4455. :attr:`_schema.MetaData.sorted_tables`
  4456. """
  4457. def __repr__(self) -> str:
  4458. return "MetaData()"
  4459. def __contains__(self, table_or_key: Union[str, Table]) -> bool:
  4460. if not isinstance(table_or_key, str):
  4461. table_or_key = table_or_key.key
  4462. return table_or_key in self.tables
  4463. def _add_table(
  4464. self, name: str, schema: Optional[str], table: Table
  4465. ) -> None:
  4466. key = _get_table_key(name, schema)
  4467. self.tables._insert_item(key, table)
  4468. if schema:
  4469. self._schemas.add(schema)
  4470. def _remove_table(self, name: str, schema: Optional[str]) -> None:
  4471. key = _get_table_key(name, schema)
  4472. removed = dict.pop(self.tables, key, None)
  4473. if removed is not None:
  4474. for fk in removed.foreign_keys:
  4475. fk._remove_from_metadata(self)
  4476. if self._schemas:
  4477. self._schemas = {
  4478. t.schema for t in self.tables.values() if t.schema is not None
  4479. }
  4480. def __getstate__(self) -> Dict[str, Any]:
  4481. return {
  4482. "tables": self.tables,
  4483. "schema": self.schema,
  4484. "schemas": self._schemas,
  4485. "sequences": self._sequences,
  4486. "fk_memos": self._fk_memos,
  4487. "naming_convention": self.naming_convention,
  4488. }
  4489. def __setstate__(self, state: Dict[str, Any]) -> None:
  4490. self.tables = state["tables"]
  4491. self.schema = state["schema"]
  4492. self.naming_convention = state["naming_convention"]
  4493. self._sequences = state["sequences"]
  4494. self._schemas = state["schemas"]
  4495. self._fk_memos = state["fk_memos"]
  4496. def clear(self) -> None:
  4497. """Clear all Table objects from this MetaData."""
  4498. dict.clear(self.tables) # type: ignore
  4499. self._schemas.clear()
  4500. self._fk_memos.clear()
  4501. def remove(self, table: Table) -> None:
  4502. """Remove the given Table object from this MetaData."""
  4503. self._remove_table(table.name, table.schema)
  4504. @property
  4505. def sorted_tables(self) -> List[Table]:
  4506. """Returns a list of :class:`_schema.Table` objects sorted in order of
  4507. foreign key dependency.
  4508. The sorting will place :class:`_schema.Table`
  4509. objects that have dependencies
  4510. first, before the dependencies themselves, representing the
  4511. order in which they can be created. To get the order in which
  4512. the tables would be dropped, use the ``reversed()`` Python built-in.
  4513. .. warning::
  4514. The :attr:`.MetaData.sorted_tables` attribute cannot by itself
  4515. accommodate automatic resolution of dependency cycles between
  4516. tables, which are usually caused by mutually dependent foreign key
  4517. constraints. When these cycles are detected, the foreign keys
  4518. of these tables are omitted from consideration in the sort.
  4519. A warning is emitted when this condition occurs, which will be an
  4520. exception raise in a future release. Tables which are not part
  4521. of the cycle will still be returned in dependency order.
  4522. To resolve these cycles, the
  4523. :paramref:`_schema.ForeignKeyConstraint.use_alter` parameter may be
  4524. applied to those constraints which create a cycle. Alternatively,
  4525. the :func:`_schema.sort_tables_and_constraints` function will
  4526. automatically return foreign key constraints in a separate
  4527. collection when cycles are detected so that they may be applied
  4528. to a schema separately.
  4529. .. versionchanged:: 1.3.17 - a warning is emitted when
  4530. :attr:`.MetaData.sorted_tables` cannot perform a proper sort
  4531. due to cyclical dependencies. This will be an exception in a
  4532. future release. Additionally, the sort will continue to return
  4533. other tables not involved in the cycle in dependency order which
  4534. was not the case previously.
  4535. .. seealso::
  4536. :func:`_schema.sort_tables`
  4537. :func:`_schema.sort_tables_and_constraints`
  4538. :attr:`_schema.MetaData.tables`
  4539. :meth:`_reflection.Inspector.get_table_names`
  4540. :meth:`_reflection.Inspector.get_sorted_table_and_fkc_names`
  4541. """
  4542. return ddl.sort_tables(
  4543. sorted(self.tables.values(), key=lambda t: t.key) # type: ignore
  4544. )
  4545. @util.preload_module("sqlalchemy.engine.reflection")
  4546. def reflect(
  4547. self,
  4548. bind: Union[Engine, Connection],
  4549. schema: Optional[str] = None,
  4550. views: bool = False,
  4551. only: Union[
  4552. _typing_Sequence[str], Callable[[str, MetaData], bool], None
  4553. ] = None,
  4554. extend_existing: bool = False,
  4555. autoload_replace: bool = True,
  4556. resolve_fks: bool = True,
  4557. **dialect_kwargs: Any,
  4558. ) -> None:
  4559. r"""Load all available table definitions from the database.
  4560. Automatically creates ``Table`` entries in this ``MetaData`` for any
  4561. table available in the database but not yet present in the
  4562. ``MetaData``. May be called multiple times to pick up tables recently
  4563. added to the database, however no special action is taken if a table
  4564. in this ``MetaData`` no longer exists in the database.
  4565. :param bind:
  4566. A :class:`.Connection` or :class:`.Engine` used to access the
  4567. database.
  4568. :param schema:
  4569. Optional, query and reflect tables from an alternate schema.
  4570. If None, the schema associated with this :class:`_schema.MetaData`
  4571. is used, if any.
  4572. :param views:
  4573. If True, also reflect views (materialized and plain).
  4574. :param only:
  4575. Optional. Load only a sub-set of available named tables. May be
  4576. specified as a sequence of names or a callable.
  4577. If a sequence of names is provided, only those tables will be
  4578. reflected. An error is raised if a table is requested but not
  4579. available. Named tables already present in this ``MetaData`` are
  4580. ignored.
  4581. If a callable is provided, it will be used as a boolean predicate to
  4582. filter the list of potential table names. The callable is called
  4583. with a table name and this ``MetaData`` instance as positional
  4584. arguments and should return a true value for any table to reflect.
  4585. :param extend_existing: Passed along to each :class:`_schema.Table` as
  4586. :paramref:`_schema.Table.extend_existing`.
  4587. :param autoload_replace: Passed along to each :class:`_schema.Table`
  4588. as
  4589. :paramref:`_schema.Table.autoload_replace`.
  4590. :param resolve_fks: if True, reflect :class:`_schema.Table`
  4591. objects linked
  4592. to :class:`_schema.ForeignKey` objects located in each
  4593. :class:`_schema.Table`.
  4594. For :meth:`_schema.MetaData.reflect`,
  4595. this has the effect of reflecting
  4596. related tables that might otherwise not be in the list of tables
  4597. being reflected, for example if the referenced table is in a
  4598. different schema or is omitted via the
  4599. :paramref:`.MetaData.reflect.only` parameter. When False,
  4600. :class:`_schema.ForeignKey` objects are not followed to the
  4601. :class:`_schema.Table`
  4602. in which they link, however if the related table is also part of the
  4603. list of tables that would be reflected in any case, the
  4604. :class:`_schema.ForeignKey` object will still resolve to its related
  4605. :class:`_schema.Table` after the :meth:`_schema.MetaData.reflect`
  4606. operation is
  4607. complete. Defaults to True.
  4608. .. versionadded:: 1.3.0
  4609. .. seealso::
  4610. :paramref:`_schema.Table.resolve_fks`
  4611. :param \**dialect_kwargs: Additional keyword arguments not mentioned
  4612. above are dialect specific, and passed in the form
  4613. ``<dialectname>_<argname>``. See the documentation regarding an
  4614. individual dialect at :ref:`dialect_toplevel` for detail on
  4615. documented arguments.
  4616. .. seealso::
  4617. :ref:`metadata_reflection_toplevel`
  4618. :meth:`_events.DDLEvents.column_reflect` - Event used to customize
  4619. the reflected columns. Usually used to generalize the types using
  4620. :meth:`_types.TypeEngine.as_generic`
  4621. :ref:`metadata_reflection_dbagnostic_types` - describes how to
  4622. reflect tables using general types.
  4623. """
  4624. with inspection.inspect(bind)._inspection_context() as insp:
  4625. reflect_opts: Any = {
  4626. "autoload_with": insp,
  4627. "extend_existing": extend_existing,
  4628. "autoload_replace": autoload_replace,
  4629. "resolve_fks": resolve_fks,
  4630. "_extend_on": set(),
  4631. }
  4632. reflect_opts.update(dialect_kwargs)
  4633. if schema is None:
  4634. schema = self.schema
  4635. if schema is not None:
  4636. reflect_opts["schema"] = schema
  4637. kind = util.preloaded.engine_reflection.ObjectKind.TABLE
  4638. available: util.OrderedSet[str] = util.OrderedSet(
  4639. insp.get_table_names(schema)
  4640. )
  4641. if views:
  4642. kind = util.preloaded.engine_reflection.ObjectKind.ANY
  4643. available.update(insp.get_view_names(schema))
  4644. try:
  4645. available.update(insp.get_materialized_view_names(schema))
  4646. except NotImplementedError:
  4647. pass
  4648. if schema is not None:
  4649. available_w_schema: util.OrderedSet[str] = util.OrderedSet(
  4650. [f"{schema}.{name}" for name in available]
  4651. )
  4652. else:
  4653. available_w_schema = available
  4654. current = set(self.tables)
  4655. if only is None:
  4656. load = [
  4657. name
  4658. for name, schname in zip(available, available_w_schema)
  4659. if extend_existing or schname not in current
  4660. ]
  4661. elif callable(only):
  4662. load = [
  4663. name
  4664. for name, schname in zip(available, available_w_schema)
  4665. if (extend_existing or schname not in current)
  4666. and only(name, self)
  4667. ]
  4668. else:
  4669. missing = [name for name in only if name not in available]
  4670. if missing:
  4671. s = schema and (" schema '%s'" % schema) or ""
  4672. missing_str = ", ".join(missing)
  4673. raise exc.InvalidRequestError(
  4674. f"Could not reflect: requested table(s) not available "
  4675. f"in {bind.engine!r}{s}: ({missing_str})"
  4676. )
  4677. load = [
  4678. name
  4679. for name in only
  4680. if extend_existing or name not in current
  4681. ]
  4682. # pass the available tables so the inspector can
  4683. # choose to ignore the filter_names
  4684. _reflect_info = insp._get_reflection_info(
  4685. schema=schema,
  4686. filter_names=load,
  4687. available=available,
  4688. kind=kind,
  4689. scope=util.preloaded.engine_reflection.ObjectScope.ANY,
  4690. **dialect_kwargs,
  4691. )
  4692. reflect_opts["_reflect_info"] = _reflect_info
  4693. for name in load:
  4694. try:
  4695. Table(name, self, **reflect_opts)
  4696. except exc.UnreflectableTableError as uerr:
  4697. util.warn(f"Skipping table {name}: {uerr}")
  4698. def create_all(
  4699. self,
  4700. bind: _CreateDropBind,
  4701. tables: Optional[_typing_Sequence[Table]] = None,
  4702. checkfirst: bool = True,
  4703. ) -> None:
  4704. """Create all tables stored in this metadata.
  4705. Conditional by default, will not attempt to recreate tables already
  4706. present in the target database.
  4707. :param bind:
  4708. A :class:`.Connection` or :class:`.Engine` used to access the
  4709. database.
  4710. :param tables:
  4711. Optional list of ``Table`` objects, which is a subset of the total
  4712. tables in the ``MetaData`` (others are ignored).
  4713. :param checkfirst:
  4714. Defaults to True, don't issue CREATEs for tables already present
  4715. in the target database.
  4716. """
  4717. bind._run_ddl_visitor(
  4718. ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables
  4719. )
  4720. def drop_all(
  4721. self,
  4722. bind: _CreateDropBind,
  4723. tables: Optional[_typing_Sequence[Table]] = None,
  4724. checkfirst: bool = True,
  4725. ) -> None:
  4726. """Drop all tables stored in this metadata.
  4727. Conditional by default, will not attempt to drop tables not present in
  4728. the target database.
  4729. :param bind:
  4730. A :class:`.Connection` or :class:`.Engine` used to access the
  4731. database.
  4732. :param tables:
  4733. Optional list of ``Table`` objects, which is a subset of the
  4734. total tables in the ``MetaData`` (others are ignored).
  4735. :param checkfirst:
  4736. Defaults to True, only issue DROPs for tables confirmed to be
  4737. present in the target database.
  4738. """
  4739. bind._run_ddl_visitor(
  4740. ddl.SchemaDropper, self, checkfirst=checkfirst, tables=tables
  4741. )
  4742. class Computed(FetchedValue, SchemaItem):
  4743. """Defines a generated column, i.e. "GENERATED ALWAYS AS" syntax.
  4744. The :class:`.Computed` construct is an inline construct added to the
  4745. argument list of a :class:`_schema.Column` object::
  4746. from sqlalchemy import Computed
  4747. Table('square', metadata_obj,
  4748. Column('side', Float, nullable=False),
  4749. Column('area', Float, Computed('side * side'))
  4750. )
  4751. See the linked documentation below for complete details.
  4752. .. versionadded:: 1.3.11
  4753. .. seealso::
  4754. :ref:`computed_ddl`
  4755. """
  4756. __visit_name__ = "computed_column"
  4757. column: Optional[Column[Any]]
  4758. @_document_text_coercion(
  4759. "sqltext", ":class:`.Computed`", ":paramref:`.Computed.sqltext`"
  4760. )
  4761. def __init__(
  4762. self, sqltext: _DDLColumnArgument, persisted: Optional[bool] = None
  4763. ) -> None:
  4764. """Construct a GENERATED ALWAYS AS DDL construct to accompany a
  4765. :class:`_schema.Column`.
  4766. :param sqltext:
  4767. A string containing the column generation expression, which will be
  4768. used verbatim, or a SQL expression construct, such as a
  4769. :func:`_expression.text`
  4770. object. If given as a string, the object is converted to a
  4771. :func:`_expression.text` object.
  4772. :param persisted:
  4773. Optional, controls how this column should be persisted by the
  4774. database. Possible values are:
  4775. * ``None``, the default, it will use the default persistence
  4776. defined by the database.
  4777. * ``True``, will render ``GENERATED ALWAYS AS ... STORED``, or the
  4778. equivalent for the target database if supported.
  4779. * ``False``, will render ``GENERATED ALWAYS AS ... VIRTUAL``, or
  4780. the equivalent for the target database if supported.
  4781. Specifying ``True`` or ``False`` may raise an error when the DDL
  4782. is emitted to the target database if the database does not support
  4783. that persistence option. Leaving this parameter at its default
  4784. of ``None`` is guaranteed to succeed for all databases that support
  4785. ``GENERATED ALWAYS AS``.
  4786. """
  4787. self.sqltext = coercions.expect(roles.DDLExpressionRole, sqltext)
  4788. self.persisted = persisted
  4789. self.column = None
  4790. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  4791. assert isinstance(parent, Column)
  4792. if not isinstance(
  4793. parent.server_default, (type(None), Computed)
  4794. ) or not isinstance(parent.server_onupdate, (type(None), Computed)):
  4795. raise exc.ArgumentError(
  4796. "A generated column cannot specify a server_default or a "
  4797. "server_onupdate argument"
  4798. )
  4799. self.column = parent
  4800. parent.computed = self
  4801. self.column.server_onupdate = self
  4802. self.column.server_default = self
  4803. def _as_for_update(self, for_update: bool) -> FetchedValue:
  4804. return self
  4805. @util.deprecated(
  4806. "1.4",
  4807. "The :meth:`_schema.Computed.copy` method is deprecated "
  4808. "and will be removed in a future release.",
  4809. )
  4810. def copy(
  4811. self, *, target_table: Optional[Table] = None, **kw: Any
  4812. ) -> Computed:
  4813. return self._copy(target_table=target_table, **kw)
  4814. def _copy(
  4815. self, *, target_table: Optional[Table] = None, **kw: Any
  4816. ) -> Computed:
  4817. sqltext = _copy_expression(
  4818. self.sqltext,
  4819. self.column.table if self.column is not None else None,
  4820. target_table,
  4821. )
  4822. g = Computed(sqltext, persisted=self.persisted)
  4823. return self._schema_item_copy(g)
  4824. class Identity(IdentityOptions, FetchedValue, SchemaItem):
  4825. """Defines an identity column, i.e. "GENERATED { ALWAYS | BY DEFAULT }
  4826. AS IDENTITY" syntax.
  4827. The :class:`.Identity` construct is an inline construct added to the
  4828. argument list of a :class:`_schema.Column` object::
  4829. from sqlalchemy import Identity
  4830. Table('foo', metadata_obj,
  4831. Column('id', Integer, Identity())
  4832. Column('description', Text),
  4833. )
  4834. See the linked documentation below for complete details.
  4835. .. versionadded:: 1.4
  4836. .. seealso::
  4837. :ref:`identity_ddl`
  4838. """
  4839. __visit_name__ = "identity_column"
  4840. is_identity = True
  4841. def __init__(
  4842. self,
  4843. always: bool = False,
  4844. on_null: Optional[bool] = None,
  4845. start: Optional[int] = None,
  4846. increment: Optional[int] = None,
  4847. minvalue: Optional[int] = None,
  4848. maxvalue: Optional[int] = None,
  4849. nominvalue: Optional[bool] = None,
  4850. nomaxvalue: Optional[bool] = None,
  4851. cycle: Optional[bool] = None,
  4852. cache: Optional[int] = None,
  4853. order: Optional[bool] = None,
  4854. ) -> None:
  4855. """Construct a GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY DDL
  4856. construct to accompany a :class:`_schema.Column`.
  4857. See the :class:`.Sequence` documentation for a complete description
  4858. of most parameters.
  4859. .. note::
  4860. MSSQL supports this construct as the preferred alternative to
  4861. generate an IDENTITY on a column, but it uses non standard
  4862. syntax that only support :paramref:`_schema.Identity.start`
  4863. and :paramref:`_schema.Identity.increment`.
  4864. All other parameters are ignored.
  4865. :param always:
  4866. A boolean, that indicates the type of identity column.
  4867. If ``False`` is specified, the default, then the user-specified
  4868. value takes precedence.
  4869. If ``True`` is specified, a user-specified value is not accepted (
  4870. on some backends, like PostgreSQL, OVERRIDING SYSTEM VALUE, or
  4871. similar, may be specified in an INSERT to override the sequence
  4872. value).
  4873. Some backends also have a default value for this parameter,
  4874. ``None`` can be used to omit rendering this part in the DDL. It
  4875. will be treated as ``False`` if a backend does not have a default
  4876. value.
  4877. :param on_null:
  4878. Set to ``True`` to specify ON NULL in conjunction with a
  4879. ``always=False`` identity column. This option is only supported on
  4880. some backends, like Oracle.
  4881. :param start: the starting index of the sequence.
  4882. :param increment: the increment value of the sequence.
  4883. :param minvalue: the minimum value of the sequence.
  4884. :param maxvalue: the maximum value of the sequence.
  4885. :param nominvalue: no minimum value of the sequence.
  4886. :param nomaxvalue: no maximum value of the sequence.
  4887. :param cycle: allows the sequence to wrap around when the maxvalue
  4888. or minvalue has been reached.
  4889. :param cache: optional integer value; number of future values in the
  4890. sequence which are calculated in advance.
  4891. :param order: optional boolean value; if true, renders the
  4892. ORDER keyword.
  4893. """
  4894. IdentityOptions.__init__(
  4895. self,
  4896. start=start,
  4897. increment=increment,
  4898. minvalue=minvalue,
  4899. maxvalue=maxvalue,
  4900. nominvalue=nominvalue,
  4901. nomaxvalue=nomaxvalue,
  4902. cycle=cycle,
  4903. cache=cache,
  4904. order=order,
  4905. )
  4906. self.always = always
  4907. self.on_null = on_null
  4908. self.column = None
  4909. def _set_parent(self, parent: SchemaEventTarget, **kw: Any) -> None:
  4910. assert isinstance(parent, Column)
  4911. if not isinstance(
  4912. parent.server_default, (type(None), Identity)
  4913. ) or not isinstance(parent.server_onupdate, type(None)):
  4914. raise exc.ArgumentError(
  4915. "A column with an Identity object cannot specify a "
  4916. "server_default or a server_onupdate argument"
  4917. )
  4918. if parent.autoincrement is False:
  4919. raise exc.ArgumentError(
  4920. "A column with an Identity object cannot specify "
  4921. "autoincrement=False"
  4922. )
  4923. self.column = parent
  4924. parent.identity = self
  4925. if parent._user_defined_nullable is NULL_UNSPECIFIED:
  4926. parent.nullable = False
  4927. parent.server_default = self
  4928. def _as_for_update(self, for_update: bool) -> FetchedValue:
  4929. return self
  4930. @util.deprecated(
  4931. "1.4",
  4932. "The :meth:`_schema.Identity.copy` method is deprecated "
  4933. "and will be removed in a future release.",
  4934. )
  4935. def copy(self, **kw: Any) -> Identity:
  4936. return self._copy(**kw)
  4937. def _copy(self, **kw: Any) -> Identity:
  4938. i = Identity(
  4939. always=self.always,
  4940. on_null=self.on_null,
  4941. start=self.start,
  4942. increment=self.increment,
  4943. minvalue=self.minvalue,
  4944. maxvalue=self.maxvalue,
  4945. nominvalue=self.nominvalue,
  4946. nomaxvalue=self.nomaxvalue,
  4947. cycle=self.cycle,
  4948. cache=self.cache,
  4949. order=self.order,
  4950. )
  4951. return self._schema_item_copy(i)