schema.py 189 KB

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