schema.py 191 KB

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