base.py 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093
  1. # dialects/mssql/base.py
  2. # Copyright (C) 2005-2026 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. """
  9. .. dialect:: mssql
  10. :name: Microsoft SQL Server
  11. :normal_support: 2012+
  12. :best_effort: 2005+
  13. .. _mssql_external_dialects:
  14. External Dialects
  15. -----------------
  16. In addition to the above DBAPI layers with native SQLAlchemy support, there
  17. are third-party dialects for other DBAPI layers that are compatible
  18. with SQL Server. See the "External Dialects" list on the
  19. :ref:`dialect_toplevel` page.
  20. .. _mssql_identity:
  21. Auto Increment Behavior / IDENTITY Columns
  22. ------------------------------------------
  23. SQL Server provides so-called "auto incrementing" behavior using the
  24. ``IDENTITY`` construct, which can be placed on any single integer column in a
  25. table. SQLAlchemy considers ``IDENTITY`` within its default "autoincrement"
  26. behavior for an integer primary key column, described at
  27. :paramref:`_schema.Column.autoincrement`. This means that by default,
  28. the first integer primary key column in a :class:`_schema.Table` will be
  29. considered to be the identity column - unless it is associated with a
  30. :class:`.Sequence` - and will generate DDL as such::
  31. from sqlalchemy import Table, MetaData, Column, Integer
  32. m = MetaData()
  33. t = Table(
  34. "t",
  35. m,
  36. Column("id", Integer, primary_key=True),
  37. Column("x", Integer),
  38. )
  39. m.create_all(engine)
  40. The above example will generate DDL as:
  41. .. sourcecode:: sql
  42. CREATE TABLE t (
  43. id INTEGER NOT NULL IDENTITY,
  44. x INTEGER NULL,
  45. PRIMARY KEY (id)
  46. )
  47. For the case where this default generation of ``IDENTITY`` is not desired,
  48. specify ``False`` for the :paramref:`_schema.Column.autoincrement` flag,
  49. on the first integer primary key column::
  50. m = MetaData()
  51. t = Table(
  52. "t",
  53. m,
  54. Column("id", Integer, primary_key=True, autoincrement=False),
  55. Column("x", Integer),
  56. )
  57. m.create_all(engine)
  58. To add the ``IDENTITY`` keyword to a non-primary key column, specify
  59. ``True`` for the :paramref:`_schema.Column.autoincrement` flag on the desired
  60. :class:`_schema.Column` object, and ensure that
  61. :paramref:`_schema.Column.autoincrement`
  62. is set to ``False`` on any integer primary key column::
  63. m = MetaData()
  64. t = Table(
  65. "t",
  66. m,
  67. Column("id", Integer, primary_key=True, autoincrement=False),
  68. Column("x", Integer, autoincrement=True),
  69. )
  70. m.create_all(engine)
  71. .. versionchanged:: 1.4 Added :class:`_schema.Identity` construct
  72. in a :class:`_schema.Column` to specify the start and increment
  73. parameters of an IDENTITY. These replace
  74. the use of the :class:`.Sequence` object in order to specify these values.
  75. .. deprecated:: 1.4
  76. The ``mssql_identity_start`` and ``mssql_identity_increment`` parameters
  77. to :class:`_schema.Column` are deprecated and should we replaced by
  78. an :class:`_schema.Identity` object. Specifying both ways of configuring
  79. an IDENTITY will result in a compile error.
  80. These options are also no longer returned as part of the
  81. ``dialect_options`` key in :meth:`_reflection.Inspector.get_columns`.
  82. Use the information in the ``identity`` key instead.
  83. .. deprecated:: 1.3
  84. The use of :class:`.Sequence` to specify IDENTITY characteristics is
  85. deprecated and will be removed in a future release. Please use
  86. the :class:`_schema.Identity` object parameters
  87. :paramref:`_schema.Identity.start` and
  88. :paramref:`_schema.Identity.increment`.
  89. .. versionchanged:: 1.4 Removed the ability to use a :class:`.Sequence`
  90. object to modify IDENTITY characteristics. :class:`.Sequence` objects
  91. now only manipulate true T-SQL SEQUENCE types.
  92. .. note::
  93. There can only be one IDENTITY column on the table. When using
  94. ``autoincrement=True`` to enable the IDENTITY keyword, SQLAlchemy does not
  95. guard against multiple columns specifying the option simultaneously. The
  96. SQL Server database will instead reject the ``CREATE TABLE`` statement.
  97. .. note::
  98. An INSERT statement which attempts to provide a value for a column that is
  99. marked with IDENTITY will be rejected by SQL Server. In order for the
  100. value to be accepted, a session-level option "SET IDENTITY_INSERT" must be
  101. enabled. The SQLAlchemy SQL Server dialect will perform this operation
  102. automatically when using a core :class:`_expression.Insert`
  103. construct; if the
  104. execution specifies a value for the IDENTITY column, the "IDENTITY_INSERT"
  105. option will be enabled for the span of that statement's invocation.However,
  106. this scenario is not high performing and should not be relied upon for
  107. normal use. If a table doesn't actually require IDENTITY behavior in its
  108. integer primary key column, the keyword should be disabled when creating
  109. the table by ensuring that ``autoincrement=False`` is set.
  110. Controlling "Start" and "Increment"
  111. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  112. Specific control over the "start" and "increment" values for
  113. the ``IDENTITY`` generator are provided using the
  114. :paramref:`_schema.Identity.start` and :paramref:`_schema.Identity.increment`
  115. parameters passed to the :class:`_schema.Identity` object::
  116. from sqlalchemy import Table, Integer, Column, Identity
  117. test = Table(
  118. "test",
  119. metadata,
  120. Column(
  121. "id", Integer, primary_key=True, Identity(start=100, increment=10)
  122. ),
  123. Column("name", String(20)),
  124. )
  125. The CREATE TABLE for the above :class:`_schema.Table` object would be:
  126. .. sourcecode:: sql
  127. CREATE TABLE test (
  128. id INTEGER NOT NULL IDENTITY(100,10) PRIMARY KEY,
  129. name VARCHAR(20) NULL,
  130. )
  131. .. note::
  132. The :class:`_schema.Identity` object supports many other parameter in
  133. addition to ``start`` and ``increment``. These are not supported by
  134. SQL Server and will be ignored when generating the CREATE TABLE ddl.
  135. .. versionchanged:: 1.3.19 The :class:`_schema.Identity` object is
  136. now used to affect the
  137. ``IDENTITY`` generator for a :class:`_schema.Column` under SQL Server.
  138. Previously, the :class:`.Sequence` object was used. As SQL Server now
  139. supports real sequences as a separate construct, :class:`.Sequence` will be
  140. functional in the normal way starting from SQLAlchemy version 1.4.
  141. Using IDENTITY with Non-Integer numeric types
  142. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  143. SQL Server also allows ``IDENTITY`` to be used with ``NUMERIC`` columns. To
  144. implement this pattern smoothly in SQLAlchemy, the primary datatype of the
  145. column should remain as ``Integer``, however the underlying implementation
  146. type deployed to the SQL Server database can be specified as ``Numeric`` using
  147. :meth:`.TypeEngine.with_variant`::
  148. from sqlalchemy import Column
  149. from sqlalchemy import Integer
  150. from sqlalchemy import Numeric
  151. from sqlalchemy import String
  152. from sqlalchemy.ext.declarative import declarative_base
  153. Base = declarative_base()
  154. class TestTable(Base):
  155. __tablename__ = "test"
  156. id = Column(
  157. Integer().with_variant(Numeric(10, 0), "mssql"),
  158. primary_key=True,
  159. autoincrement=True,
  160. )
  161. name = Column(String)
  162. In the above example, ``Integer().with_variant()`` provides clear usage
  163. information that accurately describes the intent of the code. The general
  164. restriction that ``autoincrement`` only applies to ``Integer`` is established
  165. at the metadata level and not at the per-dialect level.
  166. When using the above pattern, the primary key identifier that comes back from
  167. the insertion of a row, which is also the value that would be assigned to an
  168. ORM object such as ``TestTable`` above, will be an instance of ``Decimal()``
  169. and not ``int`` when using SQL Server. The numeric return type of the
  170. :class:`_types.Numeric` type can be changed to return floats by passing False
  171. to :paramref:`_types.Numeric.asdecimal`. To normalize the return type of the
  172. above ``Numeric(10, 0)`` to return Python ints (which also support "long"
  173. integer values in Python 3), use :class:`_types.TypeDecorator` as follows::
  174. from sqlalchemy import TypeDecorator
  175. class NumericAsInteger(TypeDecorator):
  176. "normalize floating point return values into ints"
  177. impl = Numeric(10, 0, asdecimal=False)
  178. cache_ok = True
  179. def process_result_value(self, value, dialect):
  180. if value is not None:
  181. value = int(value)
  182. return value
  183. class TestTable(Base):
  184. __tablename__ = "test"
  185. id = Column(
  186. Integer().with_variant(NumericAsInteger, "mssql"),
  187. primary_key=True,
  188. autoincrement=True,
  189. )
  190. name = Column(String)
  191. .. _mssql_insert_behavior:
  192. INSERT behavior
  193. ^^^^^^^^^^^^^^^^
  194. Handling of the ``IDENTITY`` column at INSERT time involves two key
  195. techniques. The most common is being able to fetch the "last inserted value"
  196. for a given ``IDENTITY`` column, a process which SQLAlchemy performs
  197. implicitly in many cases, most importantly within the ORM.
  198. The process for fetching this value has several variants:
  199. * In the vast majority of cases, RETURNING is used in conjunction with INSERT
  200. statements on SQL Server in order to get newly generated primary key values:
  201. .. sourcecode:: sql
  202. INSERT INTO t (x) OUTPUT inserted.id VALUES (?)
  203. As of SQLAlchemy 2.0, the :ref:`engine_insertmanyvalues` feature is also
  204. used by default to optimize many-row INSERT statements; for SQL Server
  205. the feature takes place for both RETURNING and-non RETURNING
  206. INSERT statements.
  207. .. versionchanged:: 2.0.10 The :ref:`engine_insertmanyvalues` feature for
  208. SQL Server was temporarily disabled for SQLAlchemy version 2.0.9 due to
  209. issues with row ordering. As of 2.0.10 the feature is re-enabled, with
  210. special case handling for the unit of work's requirement for RETURNING to
  211. be ordered.
  212. * When RETURNING is not available or has been disabled via
  213. ``implicit_returning=False``, either the ``scope_identity()`` function or
  214. the ``@@identity`` variable is used; behavior varies by backend:
  215. * when using PyODBC, the phrase ``; select scope_identity()`` will be
  216. appended to the end of the INSERT statement; a second result set will be
  217. fetched in order to receive the value. Given a table as::
  218. t = Table(
  219. "t",
  220. metadata,
  221. Column("id", Integer, primary_key=True),
  222. Column("x", Integer),
  223. implicit_returning=False,
  224. )
  225. an INSERT will look like:
  226. .. sourcecode:: sql
  227. INSERT INTO t (x) VALUES (?); select scope_identity()
  228. * Other dialects such as pymssql will call upon
  229. ``SELECT scope_identity() AS lastrowid`` subsequent to an INSERT
  230. statement. If the flag ``use_scope_identity=False`` is passed to
  231. :func:`_sa.create_engine`,
  232. the statement ``SELECT @@identity AS lastrowid``
  233. is used instead.
  234. A table that contains an ``IDENTITY`` column will prohibit an INSERT statement
  235. that refers to the identity column explicitly. The SQLAlchemy dialect will
  236. detect when an INSERT construct, created using a core
  237. :func:`_expression.insert`
  238. construct (not a plain string SQL), refers to the identity column, and
  239. in this case will emit ``SET IDENTITY_INSERT ON`` prior to the insert
  240. statement proceeding, and ``SET IDENTITY_INSERT OFF`` subsequent to the
  241. execution. Given this example::
  242. m = MetaData()
  243. t = Table(
  244. "t", m, Column("id", Integer, primary_key=True), Column("x", Integer)
  245. )
  246. m.create_all(engine)
  247. with engine.begin() as conn:
  248. conn.execute(t.insert(), {"id": 1, "x": 1}, {"id": 2, "x": 2})
  249. The above column will be created with IDENTITY, however the INSERT statement
  250. we emit is specifying explicit values. In the echo output we can see
  251. how SQLAlchemy handles this:
  252. .. sourcecode:: sql
  253. CREATE TABLE t (
  254. id INTEGER NOT NULL IDENTITY(1,1),
  255. x INTEGER NULL,
  256. PRIMARY KEY (id)
  257. )
  258. COMMIT
  259. SET IDENTITY_INSERT t ON
  260. INSERT INTO t (id, x) VALUES (?, ?)
  261. ((1, 1), (2, 2))
  262. SET IDENTITY_INSERT t OFF
  263. COMMIT
  264. This is an auxiliary use case suitable for testing and bulk insert scenarios.
  265. SEQUENCE support
  266. ----------------
  267. The :class:`.Sequence` object creates "real" sequences, i.e.,
  268. ``CREATE SEQUENCE``:
  269. .. sourcecode:: pycon+sql
  270. >>> from sqlalchemy import Sequence
  271. >>> from sqlalchemy.schema import CreateSequence
  272. >>> from sqlalchemy.dialects import mssql
  273. >>> print(
  274. ... CreateSequence(Sequence("my_seq", start=1)).compile(
  275. ... dialect=mssql.dialect()
  276. ... )
  277. ... )
  278. {printsql}CREATE SEQUENCE my_seq START WITH 1
  279. For integer primary key generation, SQL Server's ``IDENTITY`` construct should
  280. generally be preferred vs. sequence.
  281. .. tip::
  282. The default start value for T-SQL is ``-2**63`` instead of 1 as
  283. in most other SQL databases. Users should explicitly set the
  284. :paramref:`.Sequence.start` to 1 if that's the expected default::
  285. seq = Sequence("my_sequence", start=1)
  286. .. versionadded:: 1.4 added SQL Server support for :class:`.Sequence`
  287. .. versionchanged:: 2.0 The SQL Server dialect will no longer implicitly
  288. render "START WITH 1" for ``CREATE SEQUENCE``, which was the behavior
  289. first implemented in version 1.4.
  290. MAX on VARCHAR / NVARCHAR
  291. -------------------------
  292. SQL Server supports the special string "MAX" within the
  293. :class:`_types.VARCHAR` and :class:`_types.NVARCHAR` datatypes,
  294. to indicate "maximum length possible". The dialect currently handles this as
  295. a length of "None" in the base type, rather than supplying a
  296. dialect-specific version of these types, so that a base type
  297. specified such as ``VARCHAR(None)`` can assume "unlengthed" behavior on
  298. more than one backend without using dialect-specific types.
  299. To build a SQL Server VARCHAR or NVARCHAR with MAX length, use None::
  300. my_table = Table(
  301. "my_table",
  302. metadata,
  303. Column("my_data", VARCHAR(None)),
  304. Column("my_n_data", NVARCHAR(None)),
  305. )
  306. Collation Support
  307. -----------------
  308. Character collations are supported by the base string types,
  309. specified by the string argument "collation"::
  310. from sqlalchemy import VARCHAR
  311. Column("login", VARCHAR(32, collation="Latin1_General_CI_AS"))
  312. When such a column is associated with a :class:`_schema.Table`, the
  313. CREATE TABLE statement for this column will yield:
  314. .. sourcecode:: sql
  315. login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL
  316. LIMIT/OFFSET Support
  317. --------------------
  318. MSSQL has added support for LIMIT / OFFSET as of SQL Server 2012, via the
  319. "OFFSET n ROWS" and "FETCH NEXT n ROWS" clauses. SQLAlchemy supports these
  320. syntaxes automatically if SQL Server 2012 or greater is detected.
  321. .. versionchanged:: 1.4 support added for SQL Server "OFFSET n ROWS" and
  322. "FETCH NEXT n ROWS" syntax.
  323. For statements that specify only LIMIT and no OFFSET, all versions of SQL
  324. Server support the TOP keyword. This syntax is used for all SQL Server
  325. versions when no OFFSET clause is present. A statement such as::
  326. select(some_table).limit(5)
  327. will render similarly to:
  328. .. sourcecode:: sql
  329. SELECT TOP 5 col1, col2.. FROM table
  330. For versions of SQL Server prior to SQL Server 2012, a statement that uses
  331. LIMIT and OFFSET, or just OFFSET alone, will be rendered using the
  332. ``ROW_NUMBER()`` window function. A statement such as::
  333. select(some_table).order_by(some_table.c.col3).limit(5).offset(10)
  334. will render similarly to:
  335. .. sourcecode:: sql
  336. SELECT anon_1.col1, anon_1.col2 FROM (SELECT col1, col2,
  337. ROW_NUMBER() OVER (ORDER BY col3) AS
  338. mssql_rn FROM table WHERE t.x = :x_1) AS
  339. anon_1 WHERE mssql_rn > :param_1 AND mssql_rn <= :param_2 + :param_1
  340. Note that when using LIMIT and/or OFFSET, whether using the older
  341. or newer SQL Server syntaxes, the statement must have an ORDER BY as well,
  342. else a :class:`.CompileError` is raised.
  343. .. _mssql_comment_support:
  344. DDL Comment Support
  345. --------------------
  346. Comment support, which includes DDL rendering for attributes such as
  347. :paramref:`_schema.Table.comment` and :paramref:`_schema.Column.comment`, as
  348. well as the ability to reflect these comments, is supported assuming a
  349. supported version of SQL Server is in use. If a non-supported version such as
  350. Azure Synapse is detected at first-connect time (based on the presence
  351. of the ``fn_listextendedproperty`` SQL function), comment support including
  352. rendering and table-comment reflection is disabled, as both features rely upon
  353. SQL Server stored procedures and functions that are not available on all
  354. backend types.
  355. To force comment support to be on or off, bypassing autodetection, set the
  356. parameter ``supports_comments`` within :func:`_sa.create_engine`::
  357. e = create_engine("mssql+pyodbc://u:p@dsn", supports_comments=False)
  358. .. versionadded:: 2.0 Added support for table and column comments for
  359. the SQL Server dialect, including DDL generation and reflection.
  360. .. _mssql_isolation_level:
  361. Transaction Isolation Level
  362. ---------------------------
  363. All SQL Server dialects support setting of transaction isolation level
  364. both via a dialect-specific parameter
  365. :paramref:`_sa.create_engine.isolation_level`
  366. accepted by :func:`_sa.create_engine`,
  367. as well as the :paramref:`.Connection.execution_options.isolation_level`
  368. argument as passed to
  369. :meth:`_engine.Connection.execution_options`.
  370. This feature works by issuing the
  371. command ``SET TRANSACTION ISOLATION LEVEL <level>`` for
  372. each new connection.
  373. To set isolation level using :func:`_sa.create_engine`::
  374. engine = create_engine(
  375. "mssql+pyodbc://scott:tiger@ms_2008", isolation_level="REPEATABLE READ"
  376. )
  377. To set using per-connection execution options::
  378. connection = engine.connect()
  379. connection = connection.execution_options(isolation_level="READ COMMITTED")
  380. Valid values for ``isolation_level`` include:
  381. * ``AUTOCOMMIT`` - pyodbc / pymssql-specific
  382. * ``READ COMMITTED``
  383. * ``READ UNCOMMITTED``
  384. * ``REPEATABLE READ``
  385. * ``SERIALIZABLE``
  386. * ``SNAPSHOT`` - specific to SQL Server
  387. There are also more options for isolation level configurations, such as
  388. "sub-engine" objects linked to a main :class:`_engine.Engine` which each apply
  389. different isolation level settings. See the discussion at
  390. :ref:`dbapi_autocommit` for background.
  391. .. seealso::
  392. :ref:`dbapi_autocommit`
  393. .. _mssql_reset_on_return:
  394. Temporary Table / Resource Reset for Connection Pooling
  395. -------------------------------------------------------
  396. The :class:`.QueuePool` connection pool implementation used
  397. by the SQLAlchemy :class:`.Engine` object includes
  398. :ref:`reset on return <pool_reset_on_return>` behavior that will invoke
  399. the DBAPI ``.rollback()`` method when connections are returned to the pool.
  400. While this rollback will clear out the immediate state used by the previous
  401. transaction, it does not cover a wider range of session-level state, including
  402. temporary tables as well as other server state such as prepared statement
  403. handles and statement caches. An undocumented SQL Server procedure known
  404. as ``sp_reset_connection`` is known to be a workaround for this issue which
  405. will reset most of the session state that builds up on a connection, including
  406. temporary tables.
  407. To install ``sp_reset_connection`` as the means of performing reset-on-return,
  408. the :meth:`.PoolEvents.reset` event hook may be used, as demonstrated in the
  409. example below. The :paramref:`_sa.create_engine.pool_reset_on_return` parameter
  410. is set to ``None`` so that the custom scheme can replace the default behavior
  411. completely. The custom hook implementation calls ``.rollback()`` in any case,
  412. as it's usually important that the DBAPI's own tracking of commit/rollback
  413. will remain consistent with the state of the transaction::
  414. from sqlalchemy import create_engine
  415. from sqlalchemy import event
  416. mssql_engine = create_engine(
  417. "mssql+pyodbc://scott:tiger^5HHH@mssql2017:1433/test?driver=ODBC+Driver+17+for+SQL+Server",
  418. # disable default reset-on-return scheme
  419. pool_reset_on_return=None,
  420. )
  421. @event.listens_for(mssql_engine, "reset")
  422. def _reset_mssql(dbapi_connection, connection_record, reset_state):
  423. if not reset_state.terminate_only:
  424. dbapi_connection.execute("{call sys.sp_reset_connection}")
  425. # so that the DBAPI itself knows that the connection has been
  426. # reset
  427. dbapi_connection.rollback()
  428. .. versionchanged:: 2.0.0b3 Added additional state arguments to
  429. the :meth:`.PoolEvents.reset` event and additionally ensured the event
  430. is invoked for all "reset" occurrences, so that it's appropriate
  431. as a place for custom "reset" handlers. Previous schemes which
  432. use the :meth:`.PoolEvents.checkin` handler remain usable as well.
  433. .. seealso::
  434. :ref:`pool_reset_on_return` - in the :ref:`pooling_toplevel` documentation
  435. Nullability
  436. -----------
  437. MSSQL has support for three levels of column nullability. The default
  438. nullability allows nulls and is explicit in the CREATE TABLE
  439. construct:
  440. .. sourcecode:: sql
  441. name VARCHAR(20) NULL
  442. If ``nullable=None`` is specified then no specification is made. In
  443. other words the database's configured default is used. This will
  444. render:
  445. .. sourcecode:: sql
  446. name VARCHAR(20)
  447. If ``nullable`` is ``True`` or ``False`` then the column will be
  448. ``NULL`` or ``NOT NULL`` respectively.
  449. Date / Time Handling
  450. --------------------
  451. DATE and TIME are supported. Bind parameters are converted
  452. to datetime.datetime() objects as required by most MSSQL drivers,
  453. and results are processed from strings if needed.
  454. The DATE and TIME types are not available for MSSQL 2005 and
  455. previous - if a server version below 2008 is detected, DDL
  456. for these types will be issued as DATETIME.
  457. .. _mssql_large_type_deprecation:
  458. Large Text/Binary Type Deprecation
  459. ----------------------------------
  460. Per
  461. `SQL Server 2012/2014 Documentation <https://technet.microsoft.com/en-us/library/ms187993.aspx>`_,
  462. the ``NTEXT``, ``TEXT`` and ``IMAGE`` datatypes are to be removed from SQL
  463. Server in a future release. SQLAlchemy normally relates these types to the
  464. :class:`.UnicodeText`, :class:`_expression.TextClause` and
  465. :class:`.LargeBinary` datatypes.
  466. In order to accommodate this change, a new flag ``deprecate_large_types``
  467. is added to the dialect, which will be automatically set based on detection
  468. of the server version in use, if not otherwise set by the user. The
  469. behavior of this flag is as follows:
  470. * When this flag is ``True``, the :class:`.UnicodeText`,
  471. :class:`_expression.TextClause` and
  472. :class:`.LargeBinary` datatypes, when used to render DDL, will render the
  473. types ``NVARCHAR(max)``, ``VARCHAR(max)``, and ``VARBINARY(max)``,
  474. respectively. This is a new behavior as of the addition of this flag.
  475. * When this flag is ``False``, the :class:`.UnicodeText`,
  476. :class:`_expression.TextClause` and
  477. :class:`.LargeBinary` datatypes, when used to render DDL, will render the
  478. types ``NTEXT``, ``TEXT``, and ``IMAGE``,
  479. respectively. This is the long-standing behavior of these types.
  480. * The flag begins with the value ``None``, before a database connection is
  481. established. If the dialect is used to render DDL without the flag being
  482. set, it is interpreted the same as ``False``.
  483. * On first connection, the dialect detects if SQL Server version 2012 or
  484. greater is in use; if the flag is still at ``None``, it sets it to ``True``
  485. or ``False`` based on whether 2012 or greater is detected.
  486. * The flag can be set to either ``True`` or ``False`` when the dialect
  487. is created, typically via :func:`_sa.create_engine`::
  488. eng = create_engine(
  489. "mssql+pymssql://user:pass@host/db", deprecate_large_types=True
  490. )
  491. * Complete control over whether the "old" or "new" types are rendered is
  492. available in all SQLAlchemy versions by using the UPPERCASE type objects
  493. instead: :class:`_types.NVARCHAR`, :class:`_types.VARCHAR`,
  494. :class:`_types.VARBINARY`, :class:`_types.TEXT`, :class:`_mssql.NTEXT`,
  495. :class:`_mssql.IMAGE`
  496. will always remain fixed and always output exactly that
  497. type.
  498. .. _multipart_schema_names:
  499. Multipart Schema Names
  500. ----------------------
  501. SQL Server schemas sometimes require multiple parts to their "schema"
  502. qualifier, that is, including the database name and owner name as separate
  503. tokens, such as ``mydatabase.dbo.some_table``. These multipart names can be set
  504. at once using the :paramref:`_schema.Table.schema` argument of
  505. :class:`_schema.Table`::
  506. Table(
  507. "some_table",
  508. metadata,
  509. Column("q", String(50)),
  510. schema="mydatabase.dbo",
  511. )
  512. When performing operations such as table or component reflection, a schema
  513. argument that contains a dot will be split into separate
  514. "database" and "owner" components in order to correctly query the SQL
  515. Server information schema tables, as these two values are stored separately.
  516. Additionally, when rendering the schema name for DDL or SQL, the two
  517. components will be quoted separately for case sensitive names and other
  518. special characters. Given an argument as below::
  519. Table(
  520. "some_table",
  521. metadata,
  522. Column("q", String(50)),
  523. schema="MyDataBase.dbo",
  524. )
  525. The above schema would be rendered as ``[MyDataBase].dbo``, and also in
  526. reflection, would be reflected using "dbo" as the owner and "MyDataBase"
  527. as the database name.
  528. To control how the schema name is broken into database / owner,
  529. specify brackets (which in SQL Server are quoting characters) in the name.
  530. Below, the "owner" will be considered as ``MyDataBase.dbo`` and the
  531. "database" will be None::
  532. Table(
  533. "some_table",
  534. metadata,
  535. Column("q", String(50)),
  536. schema="[MyDataBase.dbo]",
  537. )
  538. To individually specify both database and owner name with special characters
  539. or embedded dots, use two sets of brackets::
  540. Table(
  541. "some_table",
  542. metadata,
  543. Column("q", String(50)),
  544. schema="[MyDataBase.Period].[MyOwner.Dot]",
  545. )
  546. .. versionchanged:: 1.2 the SQL Server dialect now treats brackets as
  547. identifier delimiters splitting the schema into separate database
  548. and owner tokens, to allow dots within either name itself.
  549. .. _legacy_schema_rendering:
  550. Legacy Schema Mode
  551. ------------------
  552. Very old versions of the MSSQL dialect introduced the behavior such that a
  553. schema-qualified table would be auto-aliased when used in a
  554. SELECT statement; given a table::
  555. account_table = Table(
  556. "account",
  557. metadata,
  558. Column("id", Integer, primary_key=True),
  559. Column("info", String(100)),
  560. schema="customer_schema",
  561. )
  562. this legacy mode of rendering would assume that "customer_schema.account"
  563. would not be accepted by all parts of the SQL statement, as illustrated
  564. below:
  565. .. sourcecode:: pycon+sql
  566. >>> eng = create_engine("mssql+pymssql://mydsn", legacy_schema_aliasing=True)
  567. >>> print(account_table.select().compile(eng))
  568. {printsql}SELECT account_1.id, account_1.info
  569. FROM customer_schema.account AS account_1
  570. This mode of behavior is now off by default, as it appears to have served
  571. no purpose; however in the case that legacy applications rely upon it,
  572. it is available using the ``legacy_schema_aliasing`` argument to
  573. :func:`_sa.create_engine` as illustrated above.
  574. .. deprecated:: 1.4
  575. The ``legacy_schema_aliasing`` flag is now
  576. deprecated and will be removed in a future release.
  577. .. _mssql_indexes:
  578. Clustered Index Support
  579. -----------------------
  580. The MSSQL dialect supports clustered indexes (and primary keys) via the
  581. ``mssql_clustered`` option. This option is available to :class:`.Index`,
  582. :class:`.UniqueConstraint`. and :class:`.PrimaryKeyConstraint`.
  583. For indexes this option can be combined with the ``mssql_columnstore`` one
  584. to create a clustered columnstore index.
  585. To generate a clustered index::
  586. Index("my_index", table.c.x, mssql_clustered=True)
  587. which renders the index as ``CREATE CLUSTERED INDEX my_index ON table (x)``.
  588. To generate a clustered primary key use::
  589. Table(
  590. "my_table",
  591. metadata,
  592. Column("x", ...),
  593. Column("y", ...),
  594. PrimaryKeyConstraint("x", "y", mssql_clustered=True),
  595. )
  596. which will render the table, for example, as:
  597. .. sourcecode:: sql
  598. CREATE TABLE my_table (
  599. x INTEGER NOT NULL,
  600. y INTEGER NOT NULL,
  601. PRIMARY KEY CLUSTERED (x, y)
  602. )
  603. Similarly, we can generate a clustered unique constraint using::
  604. Table(
  605. "my_table",
  606. metadata,
  607. Column("x", ...),
  608. Column("y", ...),
  609. PrimaryKeyConstraint("x"),
  610. UniqueConstraint("y", mssql_clustered=True),
  611. )
  612. To explicitly request a non-clustered primary key (for example, when
  613. a separate clustered index is desired), use::
  614. Table(
  615. "my_table",
  616. metadata,
  617. Column("x", ...),
  618. Column("y", ...),
  619. PrimaryKeyConstraint("x", "y", mssql_clustered=False),
  620. )
  621. which will render the table, for example, as:
  622. .. sourcecode:: sql
  623. CREATE TABLE my_table (
  624. x INTEGER NOT NULL,
  625. y INTEGER NOT NULL,
  626. PRIMARY KEY NONCLUSTERED (x, y)
  627. )
  628. Columnstore Index Support
  629. -------------------------
  630. The MSSQL dialect supports columnstore indexes via the ``mssql_columnstore``
  631. option. This option is available to :class:`.Index`. It be combined with
  632. the ``mssql_clustered`` option to create a clustered columnstore index.
  633. To generate a columnstore index::
  634. Index("my_index", table.c.x, mssql_columnstore=True)
  635. which renders the index as ``CREATE COLUMNSTORE INDEX my_index ON table (x)``.
  636. To generate a clustered columnstore index provide no columns::
  637. idx = Index("my_index", mssql_clustered=True, mssql_columnstore=True)
  638. # required to associate the index with the table
  639. table.append_constraint(idx)
  640. the above renders the index as
  641. ``CREATE CLUSTERED COLUMNSTORE INDEX my_index ON table``.
  642. .. versionadded:: 2.0.18
  643. MSSQL-Specific Index Options
  644. -----------------------------
  645. In addition to clustering, the MSSQL dialect supports other special options
  646. for :class:`.Index`.
  647. INCLUDE
  648. ^^^^^^^
  649. The ``mssql_include`` option renders INCLUDE(colname) for the given string
  650. names::
  651. Index("my_index", table.c.x, mssql_include=["y"])
  652. would render the index as ``CREATE INDEX my_index ON table (x) INCLUDE (y)``
  653. .. _mssql_index_where:
  654. Filtered Indexes
  655. ^^^^^^^^^^^^^^^^
  656. The ``mssql_where`` option renders WHERE(condition) for the given string
  657. names::
  658. Index("my_index", table.c.x, mssql_where=table.c.x > 10)
  659. would render the index as ``CREATE INDEX my_index ON table (x) WHERE x > 10``.
  660. .. versionadded:: 1.3.4
  661. Index ordering
  662. ^^^^^^^^^^^^^^
  663. Index ordering is available via functional expressions, such as::
  664. Index("my_index", table.c.x.desc())
  665. would render the index as ``CREATE INDEX my_index ON table (x DESC)``
  666. .. seealso::
  667. :ref:`schema_indexes_functional`
  668. Compatibility Levels
  669. --------------------
  670. MSSQL supports the notion of setting compatibility levels at the
  671. database level. This allows, for instance, to run a database that
  672. is compatible with SQL2000 while running on a SQL2005 database
  673. server. ``server_version_info`` will always return the database
  674. server version information (in this case SQL2005) and not the
  675. compatibility level information. Because of this, if running under
  676. a backwards compatibility mode SQLAlchemy may attempt to use T-SQL
  677. statements that are unable to be parsed by the database server.
  678. .. _mssql_triggers:
  679. Triggers
  680. --------
  681. SQLAlchemy by default uses OUTPUT INSERTED to get at newly
  682. generated primary key values via IDENTITY columns or other
  683. server side defaults. MS-SQL does not
  684. allow the usage of OUTPUT INSERTED on tables that have triggers.
  685. To disable the usage of OUTPUT INSERTED on a per-table basis,
  686. specify ``implicit_returning=False`` for each :class:`_schema.Table`
  687. which has triggers::
  688. Table(
  689. "mytable",
  690. metadata,
  691. Column("id", Integer, primary_key=True),
  692. # ...,
  693. implicit_returning=False,
  694. )
  695. Declarative form::
  696. class MyClass(Base):
  697. # ...
  698. __table_args__ = {"implicit_returning": False}
  699. .. _mssql_rowcount_versioning:
  700. Rowcount Support / ORM Versioning
  701. ---------------------------------
  702. The SQL Server drivers may have limited ability to return the number
  703. of rows updated from an UPDATE or DELETE statement.
  704. As of this writing, the PyODBC driver is not able to return a rowcount when
  705. OUTPUT INSERTED is used. Previous versions of SQLAlchemy therefore had
  706. limitations for features such as the "ORM Versioning" feature that relies upon
  707. accurate rowcounts in order to match version numbers with matched rows.
  708. SQLAlchemy 2.0 now retrieves the "rowcount" manually for these particular use
  709. cases based on counting the rows that arrived back within RETURNING; so while
  710. the driver still has this limitation, the ORM Versioning feature is no longer
  711. impacted by it. As of SQLAlchemy 2.0.5, ORM versioning has been fully
  712. re-enabled for the pyodbc driver.
  713. .. versionchanged:: 2.0.5 ORM versioning support is restored for the pyodbc
  714. driver. Previously, a warning would be emitted during ORM flush that
  715. versioning was not supported.
  716. Enabling Snapshot Isolation
  717. ---------------------------
  718. SQL Server has a default transaction
  719. isolation mode that locks entire tables, and causes even mildly concurrent
  720. applications to have long held locks and frequent deadlocks.
  721. Enabling snapshot isolation for the database as a whole is recommended
  722. for modern levels of concurrency support. This is accomplished via the
  723. following ALTER DATABASE commands executed at the SQL prompt:
  724. .. sourcecode:: sql
  725. ALTER DATABASE MyDatabase SET ALLOW_SNAPSHOT_ISOLATION ON
  726. ALTER DATABASE MyDatabase SET READ_COMMITTED_SNAPSHOT ON
  727. Background on SQL Server snapshot isolation is available at
  728. https://msdn.microsoft.com/en-us/library/ms175095.aspx.
  729. """ # noqa
  730. from __future__ import annotations
  731. import codecs
  732. import datetime
  733. import operator
  734. import re
  735. from typing import Any
  736. from typing import overload
  737. from typing import TYPE_CHECKING
  738. from uuid import UUID as _python_UUID
  739. from . import information_schema as ischema
  740. from .json import JSON
  741. from .json import JSONIndexType
  742. from .json import JSONPathType
  743. from ... import exc
  744. from ... import Identity
  745. from ... import schema as sa_schema
  746. from ... import Sequence
  747. from ... import sql
  748. from ... import text
  749. from ... import util
  750. from ...engine import cursor as _cursor
  751. from ...engine import default
  752. from ...engine import reflection
  753. from ...engine.reflection import ReflectionDefaults
  754. from ...sql import coercions
  755. from ...sql import compiler
  756. from ...sql import elements
  757. from ...sql import expression
  758. from ...sql import func
  759. from ...sql import quoted_name
  760. from ...sql import roles
  761. from ...sql import sqltypes
  762. from ...sql import try_cast as try_cast # noqa: F401
  763. from ...sql import util as sql_util
  764. from ...sql._typing import is_sql_compiler
  765. from ...sql.compiler import InsertmanyvaluesSentinelOpts
  766. from ...sql.elements import TryCast as TryCast # noqa: F401
  767. from ...types import BIGINT
  768. from ...types import BINARY
  769. from ...types import CHAR
  770. from ...types import DATE
  771. from ...types import DATETIME
  772. from ...types import DECIMAL
  773. from ...types import FLOAT
  774. from ...types import INTEGER
  775. from ...types import NCHAR
  776. from ...types import NUMERIC
  777. from ...types import NVARCHAR
  778. from ...types import SMALLINT
  779. from ...types import TEXT
  780. from ...types import VARCHAR
  781. from ...util import update_wrapper
  782. from ...util.typing import Literal
  783. if TYPE_CHECKING:
  784. from ...sql.ddl import DropIndex
  785. from ...sql.dml import DMLState
  786. from ...sql.selectable import TableClause
  787. # https://sqlserverbuilds.blogspot.com/
  788. MS_2017_VERSION = (14,)
  789. MS_2016_VERSION = (13,)
  790. MS_2014_VERSION = (12,)
  791. MS_2012_VERSION = (11,)
  792. MS_2008_VERSION = (10,)
  793. MS_2005_VERSION = (9,)
  794. MS_2000_VERSION = (8,)
  795. RESERVED_WORDS = {
  796. "add",
  797. "all",
  798. "alter",
  799. "and",
  800. "any",
  801. "as",
  802. "asc",
  803. "authorization",
  804. "backup",
  805. "begin",
  806. "between",
  807. "break",
  808. "browse",
  809. "bulk",
  810. "by",
  811. "cascade",
  812. "case",
  813. "check",
  814. "checkpoint",
  815. "close",
  816. "clustered",
  817. "coalesce",
  818. "collate",
  819. "column",
  820. "commit",
  821. "compute",
  822. "constraint",
  823. "contains",
  824. "containstable",
  825. "continue",
  826. "convert",
  827. "create",
  828. "cross",
  829. "current",
  830. "current_date",
  831. "current_time",
  832. "current_timestamp",
  833. "current_user",
  834. "cursor",
  835. "database",
  836. "dbcc",
  837. "deallocate",
  838. "declare",
  839. "default",
  840. "delete",
  841. "deny",
  842. "desc",
  843. "disk",
  844. "distinct",
  845. "distributed",
  846. "double",
  847. "drop",
  848. "dump",
  849. "else",
  850. "end",
  851. "errlvl",
  852. "escape",
  853. "except",
  854. "exec",
  855. "execute",
  856. "exists",
  857. "exit",
  858. "external",
  859. "fetch",
  860. "file",
  861. "fillfactor",
  862. "for",
  863. "foreign",
  864. "freetext",
  865. "freetexttable",
  866. "from",
  867. "full",
  868. "function",
  869. "goto",
  870. "grant",
  871. "group",
  872. "having",
  873. "holdlock",
  874. "identity",
  875. "identity_insert",
  876. "identitycol",
  877. "if",
  878. "in",
  879. "index",
  880. "inner",
  881. "insert",
  882. "intersect",
  883. "into",
  884. "is",
  885. "join",
  886. "key",
  887. "kill",
  888. "left",
  889. "like",
  890. "lineno",
  891. "load",
  892. "merge",
  893. "national",
  894. "nocheck",
  895. "nonclustered",
  896. "not",
  897. "null",
  898. "nullif",
  899. "of",
  900. "off",
  901. "offsets",
  902. "on",
  903. "open",
  904. "opendatasource",
  905. "openquery",
  906. "openrowset",
  907. "openxml",
  908. "option",
  909. "or",
  910. "order",
  911. "outer",
  912. "over",
  913. "percent",
  914. "pivot",
  915. "plan",
  916. "precision",
  917. "primary",
  918. "print",
  919. "proc",
  920. "procedure",
  921. "public",
  922. "raiserror",
  923. "read",
  924. "readtext",
  925. "reconfigure",
  926. "references",
  927. "replication",
  928. "restore",
  929. "restrict",
  930. "return",
  931. "revert",
  932. "revoke",
  933. "right",
  934. "rollback",
  935. "rowcount",
  936. "rowguidcol",
  937. "rule",
  938. "save",
  939. "schema",
  940. "securityaudit",
  941. "select",
  942. "session_user",
  943. "set",
  944. "setuser",
  945. "shutdown",
  946. "some",
  947. "statistics",
  948. "system_user",
  949. "table",
  950. "tablesample",
  951. "textsize",
  952. "then",
  953. "to",
  954. "top",
  955. "tran",
  956. "transaction",
  957. "trigger",
  958. "truncate",
  959. "tsequal",
  960. "union",
  961. "unique",
  962. "unpivot",
  963. "update",
  964. "updatetext",
  965. "use",
  966. "user",
  967. "values",
  968. "varying",
  969. "view",
  970. "waitfor",
  971. "when",
  972. "where",
  973. "while",
  974. "with",
  975. "writetext",
  976. }
  977. class REAL(sqltypes.REAL):
  978. """the SQL Server REAL datatype."""
  979. def __init__(self, **kw):
  980. # REAL is a synonym for FLOAT(24) on SQL server.
  981. # it is only accepted as the word "REAL" in DDL, the numeric
  982. # precision value is not allowed to be present
  983. kw.setdefault("precision", 24)
  984. super().__init__(**kw)
  985. class DOUBLE_PRECISION(sqltypes.DOUBLE_PRECISION):
  986. """the SQL Server DOUBLE PRECISION datatype.
  987. .. versionadded:: 2.0.11
  988. """
  989. def __init__(self, **kw):
  990. # DOUBLE PRECISION is a synonym for FLOAT(53) on SQL server.
  991. # it is only accepted as the word "DOUBLE PRECISION" in DDL,
  992. # the numeric precision value is not allowed to be present
  993. kw.setdefault("precision", 53)
  994. super().__init__(**kw)
  995. class TINYINT(sqltypes.Integer):
  996. __visit_name__ = "TINYINT"
  997. # MSSQL DATE/TIME types have varied behavior, sometimes returning
  998. # strings. MSDate/TIME check for everything, and always
  999. # filter bind parameters into datetime objects (required by pyodbc,
  1000. # not sure about other dialects).
  1001. class _MSDate(sqltypes.Date):
  1002. def bind_processor(self, dialect):
  1003. def process(value):
  1004. if type(value) == datetime.date:
  1005. return datetime.datetime(value.year, value.month, value.day)
  1006. else:
  1007. return value
  1008. return process
  1009. _reg = re.compile(r"(\d+)-(\d+)-(\d+)")
  1010. def result_processor(self, dialect, coltype):
  1011. def process(value):
  1012. if isinstance(value, datetime.datetime):
  1013. return value.date()
  1014. elif isinstance(value, str):
  1015. m = self._reg.match(value)
  1016. if not m:
  1017. raise ValueError(
  1018. "could not parse %r as a date value" % (value,)
  1019. )
  1020. return datetime.date(*[int(x or 0) for x in m.groups()])
  1021. else:
  1022. return value
  1023. return process
  1024. class TIME(sqltypes.TIME):
  1025. def __init__(self, precision=None, **kwargs):
  1026. self.precision = precision
  1027. super().__init__()
  1028. __zero_date = datetime.date(1900, 1, 1)
  1029. def bind_processor(self, dialect):
  1030. def process(value):
  1031. if isinstance(value, datetime.datetime):
  1032. value = datetime.datetime.combine(
  1033. self.__zero_date, value.time()
  1034. )
  1035. elif isinstance(value, datetime.time):
  1036. """issue #5339
  1037. per: https://github.com/mkleehammer/pyodbc/wiki/Tips-and-Tricks-by-Database-Platform#time-columns
  1038. pass TIME value as string
  1039. """ # noqa
  1040. value = str(value)
  1041. return value
  1042. return process
  1043. _reg = re.compile(r"(\d+):(\d+):(\d+)(?:\.(\d{0,6}))?")
  1044. def result_processor(self, dialect, coltype):
  1045. def process(value):
  1046. if isinstance(value, datetime.datetime):
  1047. return value.time()
  1048. elif isinstance(value, str):
  1049. m = self._reg.match(value)
  1050. if not m:
  1051. raise ValueError(
  1052. "could not parse %r as a time value" % (value,)
  1053. )
  1054. return datetime.time(*[int(x or 0) for x in m.groups()])
  1055. else:
  1056. return value
  1057. return process
  1058. _MSTime = TIME
  1059. class _BASETIMEIMPL(TIME):
  1060. __visit_name__ = "_BASETIMEIMPL"
  1061. class _DateTimeBase:
  1062. def bind_processor(self, dialect):
  1063. def process(value):
  1064. if type(value) == datetime.date:
  1065. return datetime.datetime(value.year, value.month, value.day)
  1066. else:
  1067. return value
  1068. return process
  1069. class _MSDateTime(_DateTimeBase, sqltypes.DateTime):
  1070. pass
  1071. class SMALLDATETIME(_DateTimeBase, sqltypes.DateTime):
  1072. __visit_name__ = "SMALLDATETIME"
  1073. class DATETIME2(_DateTimeBase, sqltypes.DateTime):
  1074. __visit_name__ = "DATETIME2"
  1075. def __init__(self, precision=None, **kw):
  1076. super().__init__(**kw)
  1077. self.precision = precision
  1078. class DATETIMEOFFSET(_DateTimeBase, sqltypes.DateTime):
  1079. __visit_name__ = "DATETIMEOFFSET"
  1080. def __init__(self, precision=None, **kw):
  1081. super().__init__(**kw)
  1082. self.precision = precision
  1083. class _UnicodeLiteral:
  1084. def literal_processor(self, dialect):
  1085. def process(value):
  1086. value = value.replace("'", "''")
  1087. if dialect.identifier_preparer._double_percents:
  1088. value = value.replace("%", "%%")
  1089. return "N'%s'" % value
  1090. return process
  1091. class _MSUnicode(_UnicodeLiteral, sqltypes.Unicode):
  1092. pass
  1093. class _MSUnicodeText(_UnicodeLiteral, sqltypes.UnicodeText):
  1094. pass
  1095. class TIMESTAMP(sqltypes._Binary):
  1096. """Implement the SQL Server TIMESTAMP type.
  1097. Note this is **completely different** than the SQL Standard
  1098. TIMESTAMP type, which is not supported by SQL Server. It
  1099. is a read-only datatype that does not support INSERT of values.
  1100. .. versionadded:: 1.2
  1101. .. seealso::
  1102. :class:`_mssql.ROWVERSION`
  1103. """
  1104. __visit_name__ = "TIMESTAMP"
  1105. # expected by _Binary to be present
  1106. length = None
  1107. def __init__(self, convert_int=False):
  1108. """Construct a TIMESTAMP or ROWVERSION type.
  1109. :param convert_int: if True, binary integer values will
  1110. be converted to integers on read.
  1111. .. versionadded:: 1.2
  1112. """
  1113. self.convert_int = convert_int
  1114. def result_processor(self, dialect, coltype):
  1115. super_ = super().result_processor(dialect, coltype)
  1116. if self.convert_int:
  1117. def process(value):
  1118. if super_:
  1119. value = super_(value)
  1120. if value is not None:
  1121. # https://stackoverflow.com/a/30403242/34549
  1122. value = int(codecs.encode(value, "hex"), 16)
  1123. return value
  1124. return process
  1125. else:
  1126. return super_
  1127. class ROWVERSION(TIMESTAMP):
  1128. """Implement the SQL Server ROWVERSION type.
  1129. The ROWVERSION datatype is a SQL Server synonym for the TIMESTAMP
  1130. datatype, however current SQL Server documentation suggests using
  1131. ROWVERSION for new datatypes going forward.
  1132. The ROWVERSION datatype does **not** reflect (e.g. introspect) from the
  1133. database as itself; the returned datatype will be
  1134. :class:`_mssql.TIMESTAMP`.
  1135. This is a read-only datatype that does not support INSERT of values.
  1136. .. versionadded:: 1.2
  1137. .. seealso::
  1138. :class:`_mssql.TIMESTAMP`
  1139. """
  1140. __visit_name__ = "ROWVERSION"
  1141. class NTEXT(sqltypes.UnicodeText):
  1142. """MSSQL NTEXT type, for variable-length unicode text up to 2^30
  1143. characters."""
  1144. __visit_name__ = "NTEXT"
  1145. class VARBINARY(sqltypes.VARBINARY, sqltypes.LargeBinary):
  1146. """The MSSQL VARBINARY type.
  1147. This type adds additional features to the core :class:`_types.VARBINARY`
  1148. type, including "deprecate_large_types" mode where
  1149. either ``VARBINARY(max)`` or IMAGE is rendered, as well as the SQL
  1150. Server ``FILESTREAM`` option.
  1151. .. seealso::
  1152. :ref:`mssql_large_type_deprecation`
  1153. """
  1154. __visit_name__ = "VARBINARY"
  1155. def __init__(self, length=None, filestream=False):
  1156. """
  1157. Construct a VARBINARY type.
  1158. :param length: optional, a length for the column for use in
  1159. DDL statements, for those binary types that accept a length,
  1160. such as the MySQL BLOB type.
  1161. :param filestream=False: if True, renders the ``FILESTREAM`` keyword
  1162. in the table definition. In this case ``length`` must be ``None``
  1163. or ``'max'``.
  1164. .. versionadded:: 1.4.31
  1165. """
  1166. self.filestream = filestream
  1167. if self.filestream and length not in (None, "max"):
  1168. raise ValueError(
  1169. "length must be None or 'max' when setting filestream"
  1170. )
  1171. super().__init__(length=length)
  1172. class IMAGE(sqltypes.LargeBinary):
  1173. __visit_name__ = "IMAGE"
  1174. class XML(sqltypes.Text):
  1175. """MSSQL XML type.
  1176. This is a placeholder type for reflection purposes that does not include
  1177. any Python-side datatype support. It also does not currently support
  1178. additional arguments, such as "CONTENT", "DOCUMENT",
  1179. "xml_schema_collection".
  1180. """
  1181. __visit_name__ = "XML"
  1182. class BIT(sqltypes.Boolean):
  1183. """MSSQL BIT type.
  1184. Both pyodbc and pymssql return values from BIT columns as
  1185. Python <class 'bool'> so just subclass Boolean.
  1186. """
  1187. __visit_name__ = "BIT"
  1188. class MONEY(sqltypes.TypeEngine):
  1189. __visit_name__ = "MONEY"
  1190. class SMALLMONEY(sqltypes.TypeEngine):
  1191. __visit_name__ = "SMALLMONEY"
  1192. class MSUUid(sqltypes.Uuid):
  1193. def bind_processor(self, dialect):
  1194. if self.native_uuid:
  1195. # this is currently assuming pyodbc; might not work for
  1196. # some other mssql driver
  1197. return None
  1198. else:
  1199. if self.as_uuid:
  1200. def process(value):
  1201. if value is not None:
  1202. value = value.hex
  1203. return value
  1204. return process
  1205. else:
  1206. def process(value):
  1207. if value is not None:
  1208. value = value.replace("-", "").replace("''", "'")
  1209. return value
  1210. return process
  1211. def literal_processor(self, dialect):
  1212. if self.native_uuid:
  1213. def process(value):
  1214. return f"""'{str(value).replace("''", "'")}'"""
  1215. return process
  1216. else:
  1217. if self.as_uuid:
  1218. def process(value):
  1219. return f"""'{value.hex}'"""
  1220. return process
  1221. else:
  1222. def process(value):
  1223. return f"""'{
  1224. value.replace("-", "").replace("'", "''")
  1225. }'"""
  1226. return process
  1227. class UNIQUEIDENTIFIER(sqltypes.Uuid[sqltypes._UUID_RETURN]):
  1228. __visit_name__ = "UNIQUEIDENTIFIER"
  1229. @overload
  1230. def __init__(
  1231. self: UNIQUEIDENTIFIER[_python_UUID], as_uuid: Literal[True] = ...
  1232. ): ...
  1233. @overload
  1234. def __init__(
  1235. self: UNIQUEIDENTIFIER[str], as_uuid: Literal[False] = ...
  1236. ): ...
  1237. def __init__(self, as_uuid: bool = True):
  1238. """Construct a :class:`_mssql.UNIQUEIDENTIFIER` type.
  1239. :param as_uuid=True: if True, values will be interpreted
  1240. as Python uuid objects, converting to/from string via the
  1241. DBAPI.
  1242. .. versionchanged: 2.0 Added direct "uuid" support to the
  1243. :class:`_mssql.UNIQUEIDENTIFIER` datatype; uuid interpretation
  1244. defaults to ``True``.
  1245. """
  1246. self.as_uuid = as_uuid
  1247. self.native_uuid = True
  1248. class SQL_VARIANT(sqltypes.TypeEngine):
  1249. __visit_name__ = "SQL_VARIANT"
  1250. # old names.
  1251. MSDateTime = _MSDateTime
  1252. MSDate = _MSDate
  1253. MSReal = REAL
  1254. MSTinyInteger = TINYINT
  1255. MSTime = TIME
  1256. MSSmallDateTime = SMALLDATETIME
  1257. MSDateTime2 = DATETIME2
  1258. MSDateTimeOffset = DATETIMEOFFSET
  1259. MSText = TEXT
  1260. MSNText = NTEXT
  1261. MSString = VARCHAR
  1262. MSNVarchar = NVARCHAR
  1263. MSChar = CHAR
  1264. MSNChar = NCHAR
  1265. MSBinary = BINARY
  1266. MSVarBinary = VARBINARY
  1267. MSImage = IMAGE
  1268. MSBit = BIT
  1269. MSMoney = MONEY
  1270. MSSmallMoney = SMALLMONEY
  1271. MSUniqueIdentifier = UNIQUEIDENTIFIER
  1272. MSVariant = SQL_VARIANT
  1273. ischema_names = {
  1274. "int": INTEGER,
  1275. "bigint": BIGINT,
  1276. "smallint": SMALLINT,
  1277. "tinyint": TINYINT,
  1278. "varchar": VARCHAR,
  1279. "nvarchar": NVARCHAR,
  1280. "char": CHAR,
  1281. "nchar": NCHAR,
  1282. "text": TEXT,
  1283. "ntext": NTEXT,
  1284. "decimal": DECIMAL,
  1285. "numeric": NUMERIC,
  1286. "float": FLOAT,
  1287. "datetime": DATETIME,
  1288. "datetime2": DATETIME2,
  1289. "datetimeoffset": DATETIMEOFFSET,
  1290. "date": DATE,
  1291. "time": TIME,
  1292. "smalldatetime": SMALLDATETIME,
  1293. "binary": BINARY,
  1294. "varbinary": VARBINARY,
  1295. "bit": BIT,
  1296. "real": REAL,
  1297. "double precision": DOUBLE_PRECISION,
  1298. "image": IMAGE,
  1299. "xml": XML,
  1300. "timestamp": TIMESTAMP,
  1301. "money": MONEY,
  1302. "smallmoney": SMALLMONEY,
  1303. "uniqueidentifier": UNIQUEIDENTIFIER,
  1304. "sql_variant": SQL_VARIANT,
  1305. }
  1306. class MSTypeCompiler(compiler.GenericTypeCompiler):
  1307. def _extend(self, spec, type_, length=None):
  1308. """Extend a string-type declaration with standard SQL
  1309. COLLATE annotations.
  1310. """
  1311. if getattr(type_, "collation", None):
  1312. collation = "COLLATE %s" % type_.collation
  1313. else:
  1314. collation = None
  1315. if not length:
  1316. length = type_.length
  1317. if length:
  1318. spec = spec + "(%s)" % length
  1319. return " ".join([c for c in (spec, collation) if c is not None])
  1320. def visit_double(self, type_, **kw):
  1321. return self.visit_DOUBLE_PRECISION(type_, **kw)
  1322. def visit_FLOAT(self, type_, **kw):
  1323. precision = getattr(type_, "precision", None)
  1324. if precision is None:
  1325. return "FLOAT"
  1326. else:
  1327. return "FLOAT(%(precision)s)" % {"precision": precision}
  1328. def visit_TINYINT(self, type_, **kw):
  1329. return "TINYINT"
  1330. def visit_TIME(self, type_, **kw):
  1331. precision = getattr(type_, "precision", None)
  1332. if precision is not None:
  1333. return "TIME(%s)" % precision
  1334. else:
  1335. return "TIME"
  1336. def visit_TIMESTAMP(self, type_, **kw):
  1337. return "TIMESTAMP"
  1338. def visit_ROWVERSION(self, type_, **kw):
  1339. return "ROWVERSION"
  1340. def visit_datetime(self, type_, **kw):
  1341. if type_.timezone:
  1342. return self.visit_DATETIMEOFFSET(type_, **kw)
  1343. else:
  1344. return self.visit_DATETIME(type_, **kw)
  1345. def visit_DATETIMEOFFSET(self, type_, **kw):
  1346. precision = getattr(type_, "precision", None)
  1347. if precision is not None:
  1348. return "DATETIMEOFFSET(%s)" % type_.precision
  1349. else:
  1350. return "DATETIMEOFFSET"
  1351. def visit_DATETIME2(self, type_, **kw):
  1352. precision = getattr(type_, "precision", None)
  1353. if precision is not None:
  1354. return "DATETIME2(%s)" % precision
  1355. else:
  1356. return "DATETIME2"
  1357. def visit_SMALLDATETIME(self, type_, **kw):
  1358. return "SMALLDATETIME"
  1359. def visit_unicode(self, type_, **kw):
  1360. return self.visit_NVARCHAR(type_, **kw)
  1361. def visit_text(self, type_, **kw):
  1362. if self.dialect.deprecate_large_types:
  1363. return self.visit_VARCHAR(type_, **kw)
  1364. else:
  1365. return self.visit_TEXT(type_, **kw)
  1366. def visit_unicode_text(self, type_, **kw):
  1367. if self.dialect.deprecate_large_types:
  1368. return self.visit_NVARCHAR(type_, **kw)
  1369. else:
  1370. return self.visit_NTEXT(type_, **kw)
  1371. def visit_NTEXT(self, type_, **kw):
  1372. return self._extend("NTEXT", type_)
  1373. def visit_TEXT(self, type_, **kw):
  1374. return self._extend("TEXT", type_)
  1375. def visit_VARCHAR(self, type_, **kw):
  1376. return self._extend("VARCHAR", type_, length=type_.length or "max")
  1377. def visit_CHAR(self, type_, **kw):
  1378. return self._extend("CHAR", type_)
  1379. def visit_NCHAR(self, type_, **kw):
  1380. return self._extend("NCHAR", type_)
  1381. def visit_NVARCHAR(self, type_, **kw):
  1382. return self._extend("NVARCHAR", type_, length=type_.length or "max")
  1383. def visit_date(self, type_, **kw):
  1384. if self.dialect.server_version_info < MS_2008_VERSION:
  1385. return self.visit_DATETIME(type_, **kw)
  1386. else:
  1387. return self.visit_DATE(type_, **kw)
  1388. def visit__BASETIMEIMPL(self, type_, **kw):
  1389. return self.visit_time(type_, **kw)
  1390. def visit_time(self, type_, **kw):
  1391. if self.dialect.server_version_info < MS_2008_VERSION:
  1392. return self.visit_DATETIME(type_, **kw)
  1393. else:
  1394. return self.visit_TIME(type_, **kw)
  1395. def visit_large_binary(self, type_, **kw):
  1396. if self.dialect.deprecate_large_types:
  1397. return self.visit_VARBINARY(type_, **kw)
  1398. else:
  1399. return self.visit_IMAGE(type_, **kw)
  1400. def visit_IMAGE(self, type_, **kw):
  1401. return "IMAGE"
  1402. def visit_XML(self, type_, **kw):
  1403. return "XML"
  1404. def visit_VARBINARY(self, type_, **kw):
  1405. text = self._extend("VARBINARY", type_, length=type_.length or "max")
  1406. if getattr(type_, "filestream", False):
  1407. text += " FILESTREAM"
  1408. return text
  1409. def visit_boolean(self, type_, **kw):
  1410. return self.visit_BIT(type_)
  1411. def visit_BIT(self, type_, **kw):
  1412. return "BIT"
  1413. def visit_JSON(self, type_, **kw):
  1414. # this is a bit of a break with SQLAlchemy's convention of
  1415. # "UPPERCASE name goes to UPPERCASE type name with no modification"
  1416. return self._extend("NVARCHAR", type_, length="max")
  1417. def visit_MONEY(self, type_, **kw):
  1418. return "MONEY"
  1419. def visit_SMALLMONEY(self, type_, **kw):
  1420. return "SMALLMONEY"
  1421. def visit_uuid(self, type_, **kw):
  1422. if type_.native_uuid:
  1423. return self.visit_UNIQUEIDENTIFIER(type_, **kw)
  1424. else:
  1425. return super().visit_uuid(type_, **kw)
  1426. def visit_UNIQUEIDENTIFIER(self, type_, **kw):
  1427. return "UNIQUEIDENTIFIER"
  1428. def visit_SQL_VARIANT(self, type_, **kw):
  1429. return "SQL_VARIANT"
  1430. class MSExecutionContext(default.DefaultExecutionContext):
  1431. _enable_identity_insert = False
  1432. _select_lastrowid = False
  1433. _lastrowid = None
  1434. dialect: MSDialect
  1435. def _opt_encode(self, statement):
  1436. if self.compiled and self.compiled.schema_translate_map:
  1437. rst = self.compiled.preparer._render_schema_translates
  1438. statement = rst(statement, self.compiled.schema_translate_map)
  1439. return statement
  1440. def pre_exec(self):
  1441. """Activate IDENTITY_INSERT if needed."""
  1442. if self.isinsert:
  1443. if TYPE_CHECKING:
  1444. assert is_sql_compiler(self.compiled)
  1445. assert isinstance(self.compiled.compile_state, DMLState)
  1446. assert isinstance(
  1447. self.compiled.compile_state.dml_table, TableClause
  1448. )
  1449. tbl = self.compiled.compile_state.dml_table
  1450. id_column = tbl._autoincrement_column
  1451. if id_column is not None and (
  1452. not isinstance(id_column.default, Sequence)
  1453. ):
  1454. insert_has_identity = True
  1455. compile_state = self.compiled.dml_compile_state
  1456. self._enable_identity_insert = (
  1457. id_column.key in self.compiled_parameters[0]
  1458. ) or (
  1459. compile_state._dict_parameters
  1460. and (id_column.key in compile_state._insert_col_keys)
  1461. )
  1462. else:
  1463. insert_has_identity = False
  1464. self._enable_identity_insert = False
  1465. self._select_lastrowid = (
  1466. not self.compiled.inline
  1467. and insert_has_identity
  1468. and not self.compiled.effective_returning
  1469. and not self._enable_identity_insert
  1470. and not self.executemany
  1471. )
  1472. if self._enable_identity_insert:
  1473. self.root_connection._cursor_execute(
  1474. self.cursor,
  1475. self._opt_encode(
  1476. "SET IDENTITY_INSERT %s ON"
  1477. % self.identifier_preparer.format_table(tbl)
  1478. ),
  1479. (),
  1480. self,
  1481. )
  1482. def post_exec(self):
  1483. """Disable IDENTITY_INSERT if enabled."""
  1484. conn = self.root_connection
  1485. if self.isinsert or self.isupdate or self.isdelete:
  1486. self._rowcount = self.cursor.rowcount
  1487. if self._select_lastrowid:
  1488. if self.dialect.use_scope_identity:
  1489. conn._cursor_execute(
  1490. self.cursor,
  1491. "SELECT scope_identity() AS lastrowid",
  1492. (),
  1493. self,
  1494. )
  1495. else:
  1496. conn._cursor_execute(
  1497. self.cursor, "SELECT @@identity AS lastrowid", (), self
  1498. )
  1499. # fetchall() ensures the cursor is consumed without closing it
  1500. row = self.cursor.fetchall()[0]
  1501. self._lastrowid = int(row[0])
  1502. self.cursor_fetch_strategy = _cursor._NO_CURSOR_DML
  1503. elif (
  1504. self.compiled is not None
  1505. and is_sql_compiler(self.compiled)
  1506. and self.compiled.effective_returning
  1507. ):
  1508. self.cursor_fetch_strategy = (
  1509. _cursor.FullyBufferedCursorFetchStrategy(
  1510. self.cursor,
  1511. self.cursor.description,
  1512. self.cursor.fetchall(),
  1513. )
  1514. )
  1515. if self._enable_identity_insert:
  1516. if TYPE_CHECKING:
  1517. assert is_sql_compiler(self.compiled)
  1518. assert isinstance(self.compiled.compile_state, DMLState)
  1519. assert isinstance(
  1520. self.compiled.compile_state.dml_table, TableClause
  1521. )
  1522. conn._cursor_execute(
  1523. self.cursor,
  1524. self._opt_encode(
  1525. "SET IDENTITY_INSERT %s OFF"
  1526. % self.identifier_preparer.format_table(
  1527. self.compiled.compile_state.dml_table
  1528. )
  1529. ),
  1530. (),
  1531. self,
  1532. )
  1533. def get_lastrowid(self):
  1534. return self._lastrowid
  1535. def handle_dbapi_exception(self, e):
  1536. if self._enable_identity_insert:
  1537. try:
  1538. self.cursor.execute(
  1539. self._opt_encode(
  1540. "SET IDENTITY_INSERT %s OFF"
  1541. % self.identifier_preparer.format_table(
  1542. self.compiled.compile_state.dml_table
  1543. )
  1544. )
  1545. )
  1546. except Exception:
  1547. pass
  1548. def fire_sequence(self, seq, type_):
  1549. return self._execute_scalar(
  1550. (
  1551. "SELECT NEXT VALUE FOR %s"
  1552. % self.identifier_preparer.format_sequence(seq)
  1553. ),
  1554. type_,
  1555. )
  1556. def get_insert_default(self, column):
  1557. if (
  1558. isinstance(column, sa_schema.Column)
  1559. and column is column.table._autoincrement_column
  1560. and isinstance(column.default, sa_schema.Sequence)
  1561. and column.default.optional
  1562. ):
  1563. return None
  1564. return super().get_insert_default(column)
  1565. class MSSQLCompiler(compiler.SQLCompiler):
  1566. returning_precedes_values = True
  1567. extract_map = util.update_copy(
  1568. compiler.SQLCompiler.extract_map,
  1569. {
  1570. "doy": "dayofyear",
  1571. "dow": "weekday",
  1572. "milliseconds": "millisecond",
  1573. "microseconds": "microsecond",
  1574. },
  1575. )
  1576. def __init__(self, *args, **kwargs):
  1577. self.tablealiases = {}
  1578. super().__init__(*args, **kwargs)
  1579. def _format_frame_clause(self, range_, **kw):
  1580. kw["literal_execute"] = True
  1581. return super()._format_frame_clause(range_, **kw)
  1582. def _with_legacy_schema_aliasing(fn):
  1583. def decorate(self, *arg, **kw):
  1584. if self.dialect.legacy_schema_aliasing:
  1585. return fn(self, *arg, **kw)
  1586. else:
  1587. super_ = getattr(super(MSSQLCompiler, self), fn.__name__)
  1588. return super_(*arg, **kw)
  1589. return decorate
  1590. def visit_now_func(self, fn, **kw):
  1591. return "CURRENT_TIMESTAMP"
  1592. def visit_current_date_func(self, fn, **kw):
  1593. return "GETDATE()"
  1594. def visit_length_func(self, fn, **kw):
  1595. return "LEN%s" % self.function_argspec(fn, **kw)
  1596. def visit_char_length_func(self, fn, **kw):
  1597. return "LEN%s" % self.function_argspec(fn, **kw)
  1598. def visit_aggregate_strings_func(self, fn, **kw):
  1599. expr = fn.clauses.clauses[0]._compiler_dispatch(self, **kw)
  1600. kw["literal_execute"] = True
  1601. delimiter = fn.clauses.clauses[1]._compiler_dispatch(self, **kw)
  1602. return f"string_agg({expr}, {delimiter})"
  1603. def visit_concat_op_expression_clauselist(
  1604. self, clauselist, operator, **kw
  1605. ):
  1606. return " + ".join(self.process(elem, **kw) for elem in clauselist)
  1607. def visit_concat_op_binary(self, binary, operator, **kw):
  1608. return "%s + %s" % (
  1609. self.process(binary.left, **kw),
  1610. self.process(binary.right, **kw),
  1611. )
  1612. def visit_true(self, expr, **kw):
  1613. return "1"
  1614. def visit_false(self, expr, **kw):
  1615. return "0"
  1616. def visit_match_op_binary(self, binary, operator, **kw):
  1617. return "CONTAINS (%s, %s)" % (
  1618. self.process(binary.left, **kw),
  1619. self.process(binary.right, **kw),
  1620. )
  1621. def get_select_precolumns(self, select, **kw):
  1622. """MS-SQL puts TOP, it's version of LIMIT here"""
  1623. s = super().get_select_precolumns(select, **kw)
  1624. if select._has_row_limiting_clause and self._use_top(select):
  1625. # ODBC drivers and possibly others
  1626. # don't support bind params in the SELECT clause on SQL Server.
  1627. # so have to use literal here.
  1628. kw["literal_execute"] = True
  1629. s += "TOP %s " % self.process(
  1630. self._get_limit_or_fetch(select), **kw
  1631. )
  1632. if select._fetch_clause is not None:
  1633. if select._fetch_clause_options["percent"]:
  1634. s += "PERCENT "
  1635. if select._fetch_clause_options["with_ties"]:
  1636. s += "WITH TIES "
  1637. return s
  1638. def get_from_hint_text(self, table, text):
  1639. return text
  1640. def get_crud_hint_text(self, table, text):
  1641. return text
  1642. def _get_limit_or_fetch(self, select):
  1643. if select._fetch_clause is None:
  1644. return select._limit_clause
  1645. else:
  1646. return select._fetch_clause
  1647. def _use_top(self, select):
  1648. return (select._offset_clause is None) and (
  1649. select._simple_int_clause(select._limit_clause)
  1650. or (
  1651. # limit can use TOP with is by itself. fetch only uses TOP
  1652. # when it needs to because of PERCENT and/or WITH TIES
  1653. # TODO: Why? shouldn't we use TOP always ?
  1654. select._simple_int_clause(select._fetch_clause)
  1655. and (
  1656. select._fetch_clause_options["percent"]
  1657. or select._fetch_clause_options["with_ties"]
  1658. )
  1659. )
  1660. )
  1661. def limit_clause(self, cs, **kwargs):
  1662. return ""
  1663. def _check_can_use_fetch_limit(self, select):
  1664. # to use ROW_NUMBER(), an ORDER BY is required.
  1665. # OFFSET are FETCH are options of the ORDER BY clause
  1666. if not select._order_by_clause.clauses:
  1667. raise exc.CompileError(
  1668. "MSSQL requires an order_by when "
  1669. "using an OFFSET or a non-simple "
  1670. "LIMIT clause"
  1671. )
  1672. if select._fetch_clause_options is not None and (
  1673. select._fetch_clause_options["percent"]
  1674. or select._fetch_clause_options["with_ties"]
  1675. ):
  1676. raise exc.CompileError(
  1677. "MSSQL needs TOP to use PERCENT and/or WITH TIES. "
  1678. "Only simple fetch without offset can be used."
  1679. )
  1680. def _row_limit_clause(self, select, **kw):
  1681. """MSSQL 2012 supports OFFSET/FETCH operators
  1682. Use it instead subquery with row_number
  1683. """
  1684. if self.dialect._supports_offset_fetch and not self._use_top(select):
  1685. self._check_can_use_fetch_limit(select)
  1686. return self.fetch_clause(
  1687. select,
  1688. fetch_clause=self._get_limit_or_fetch(select),
  1689. require_offset=True,
  1690. **kw,
  1691. )
  1692. else:
  1693. return ""
  1694. def visit_try_cast(self, element, **kw):
  1695. return "TRY_CAST (%s AS %s)" % (
  1696. self.process(element.clause, **kw),
  1697. self.process(element.typeclause, **kw),
  1698. )
  1699. def translate_select_structure(self, select_stmt, **kwargs):
  1700. """Look for ``LIMIT`` and OFFSET in a select statement, and if
  1701. so tries to wrap it in a subquery with ``row_number()`` criterion.
  1702. MSSQL 2012 and above are excluded
  1703. """
  1704. select = select_stmt
  1705. if (
  1706. select._has_row_limiting_clause
  1707. and not self.dialect._supports_offset_fetch
  1708. and not self._use_top(select)
  1709. and not getattr(select, "_mssql_visit", None)
  1710. ):
  1711. self._check_can_use_fetch_limit(select)
  1712. _order_by_clauses = [
  1713. sql_util.unwrap_label_reference(elem)
  1714. for elem in select._order_by_clause.clauses
  1715. ]
  1716. limit_clause = self._get_limit_or_fetch(select)
  1717. offset_clause = select._offset_clause
  1718. select = select._generate()
  1719. select._mssql_visit = True
  1720. select = (
  1721. select.add_columns(
  1722. sql.func.ROW_NUMBER()
  1723. .over(order_by=_order_by_clauses)
  1724. .label("mssql_rn")
  1725. )
  1726. .order_by(None)
  1727. .alias()
  1728. )
  1729. mssql_rn = sql.column("mssql_rn")
  1730. limitselect = sql.select(
  1731. *[c for c in select.c if c.key != "mssql_rn"]
  1732. )
  1733. if offset_clause is not None:
  1734. limitselect = limitselect.where(mssql_rn > offset_clause)
  1735. if limit_clause is not None:
  1736. limitselect = limitselect.where(
  1737. mssql_rn <= (limit_clause + offset_clause)
  1738. )
  1739. else:
  1740. limitselect = limitselect.where(mssql_rn <= (limit_clause))
  1741. return limitselect
  1742. else:
  1743. return select
  1744. @_with_legacy_schema_aliasing
  1745. def visit_table(self, table, mssql_aliased=False, iscrud=False, **kwargs):
  1746. if mssql_aliased is table or iscrud:
  1747. return super().visit_table(table, **kwargs)
  1748. # alias schema-qualified tables
  1749. alias = self._schema_aliased_table(table)
  1750. if alias is not None:
  1751. return self.process(alias, mssql_aliased=table, **kwargs)
  1752. else:
  1753. return super().visit_table(table, **kwargs)
  1754. @_with_legacy_schema_aliasing
  1755. def visit_alias(self, alias, **kw):
  1756. # translate for schema-qualified table aliases
  1757. kw["mssql_aliased"] = alias.element
  1758. return super().visit_alias(alias, **kw)
  1759. @_with_legacy_schema_aliasing
  1760. def visit_column(self, column, add_to_result_map=None, **kw):
  1761. if (
  1762. column.table is not None
  1763. and (not self.isupdate and not self.isdelete)
  1764. or self.is_subquery()
  1765. ):
  1766. # translate for schema-qualified table aliases
  1767. t = self._schema_aliased_table(column.table)
  1768. if t is not None:
  1769. converted = elements._corresponding_column_or_error(t, column)
  1770. if add_to_result_map is not None:
  1771. add_to_result_map(
  1772. column.name,
  1773. column.name,
  1774. (column, column.name, column.key),
  1775. column.type,
  1776. )
  1777. return super().visit_column(converted, **kw)
  1778. return super().visit_column(
  1779. column, add_to_result_map=add_to_result_map, **kw
  1780. )
  1781. def _schema_aliased_table(self, table):
  1782. if getattr(table, "schema", None) is not None:
  1783. if table not in self.tablealiases:
  1784. self.tablealiases[table] = table.alias()
  1785. return self.tablealiases[table]
  1786. else:
  1787. return None
  1788. def visit_extract(self, extract, **kw):
  1789. field = self.extract_map.get(extract.field, extract.field)
  1790. return "DATEPART(%s, %s)" % (field, self.process(extract.expr, **kw))
  1791. def visit_savepoint(self, savepoint_stmt, **kw):
  1792. return "SAVE TRANSACTION %s" % self.preparer.format_savepoint(
  1793. savepoint_stmt
  1794. )
  1795. def visit_rollback_to_savepoint(self, savepoint_stmt, **kw):
  1796. return "ROLLBACK TRANSACTION %s" % self.preparer.format_savepoint(
  1797. savepoint_stmt
  1798. )
  1799. def visit_binary(self, binary, **kwargs):
  1800. """Move bind parameters to the right-hand side of an operator, where
  1801. possible.
  1802. """
  1803. if (
  1804. isinstance(binary.left, expression.BindParameter)
  1805. and binary.operator == operator.eq
  1806. and not isinstance(binary.right, expression.BindParameter)
  1807. ):
  1808. return self.process(
  1809. expression.BinaryExpression(
  1810. binary.right, binary.left, binary.operator
  1811. ),
  1812. **kwargs,
  1813. )
  1814. return super().visit_binary(binary, **kwargs)
  1815. def returning_clause(
  1816. self, stmt, returning_cols, *, populate_result_map, **kw
  1817. ):
  1818. # SQL server returning clause requires that the columns refer to
  1819. # the virtual table names "inserted" or "deleted". Here, we make
  1820. # a simple alias of our table with that name, and then adapt the
  1821. # columns we have from the list of RETURNING columns to that new name
  1822. # so that they render as "inserted.<colname>" / "deleted.<colname>".
  1823. if stmt.is_insert or stmt.is_update:
  1824. target = stmt.table.alias("inserted")
  1825. elif stmt.is_delete:
  1826. target = stmt.table.alias("deleted")
  1827. else:
  1828. assert False, "expected Insert, Update or Delete statement"
  1829. adapter = sql_util.ClauseAdapter(target)
  1830. # adapter.traverse() takes a column from our target table and returns
  1831. # the one that is linked to the "inserted" / "deleted" tables. So in
  1832. # order to retrieve these values back from the result (e.g. like
  1833. # row[column]), tell the compiler to also add the original unadapted
  1834. # column to the result map. Before #4877, these were (unknowingly)
  1835. # falling back using string name matching in the result set which
  1836. # necessarily used an expensive KeyError in order to match.
  1837. columns = [
  1838. self._label_returning_column(
  1839. stmt,
  1840. adapter.traverse(column),
  1841. populate_result_map,
  1842. {"result_map_targets": (column,)},
  1843. fallback_label_name=fallback_label_name,
  1844. column_is_repeated=repeated,
  1845. name=name,
  1846. proxy_name=proxy_name,
  1847. **kw,
  1848. )
  1849. for (
  1850. name,
  1851. proxy_name,
  1852. fallback_label_name,
  1853. column,
  1854. repeated,
  1855. ) in stmt._generate_columns_plus_names(
  1856. True, cols=expression._select_iterables(returning_cols)
  1857. )
  1858. ]
  1859. return "OUTPUT " + ", ".join(columns)
  1860. def get_cte_preamble(self, recursive):
  1861. # SQL Server finds it too inconvenient to accept
  1862. # an entirely optional, SQL standard specified,
  1863. # "RECURSIVE" word with their "WITH",
  1864. # so here we go
  1865. return "WITH"
  1866. def label_select_column(self, select, column, asfrom):
  1867. if isinstance(column, expression.Function):
  1868. return column.label(None)
  1869. else:
  1870. return super().label_select_column(select, column, asfrom)
  1871. def for_update_clause(self, select, **kw):
  1872. # "FOR UPDATE" is only allowed on "DECLARE CURSOR" which
  1873. # SQLAlchemy doesn't use
  1874. return ""
  1875. def order_by_clause(self, select, **kw):
  1876. # MSSQL only allows ORDER BY in subqueries if there is a LIMIT:
  1877. # "The ORDER BY clause is invalid in views, inline functions,
  1878. # derived tables, subqueries, and common table expressions,
  1879. # unless TOP, OFFSET or FOR XML is also specified."
  1880. if (
  1881. self.is_subquery()
  1882. and not self._use_top(select)
  1883. and (
  1884. select._offset is None
  1885. or not self.dialect._supports_offset_fetch
  1886. )
  1887. ):
  1888. # avoid processing the order by clause if we won't end up
  1889. # using it, because we don't want all the bind params tacked
  1890. # onto the positional list if that is what the dbapi requires
  1891. return ""
  1892. order_by = self.process(select._order_by_clause, **kw)
  1893. if order_by:
  1894. return " ORDER BY " + order_by
  1895. else:
  1896. return ""
  1897. def update_from_clause(
  1898. self, update_stmt, from_table, extra_froms, from_hints, **kw
  1899. ):
  1900. """Render the UPDATE..FROM clause specific to MSSQL.
  1901. In MSSQL, if the UPDATE statement involves an alias of the table to
  1902. be updated, then the table itself must be added to the FROM list as
  1903. well. Otherwise, it is optional. Here, we add it regardless.
  1904. """
  1905. return "FROM " + ", ".join(
  1906. t._compiler_dispatch(self, asfrom=True, fromhints=from_hints, **kw)
  1907. for t in [from_table] + extra_froms
  1908. )
  1909. def delete_table_clause(self, delete_stmt, from_table, extra_froms, **kw):
  1910. """If we have extra froms make sure we render any alias as hint."""
  1911. ashint = False
  1912. if extra_froms:
  1913. ashint = True
  1914. return from_table._compiler_dispatch(
  1915. self, asfrom=True, iscrud=True, ashint=ashint, **kw
  1916. )
  1917. def delete_extra_from_clause(
  1918. self, delete_stmt, from_table, extra_froms, from_hints, **kw
  1919. ):
  1920. """Render the DELETE .. FROM clause specific to MSSQL.
  1921. Yes, it has the FROM keyword twice.
  1922. """
  1923. return "FROM " + ", ".join(
  1924. t._compiler_dispatch(self, asfrom=True, fromhints=from_hints, **kw)
  1925. for t in [from_table] + extra_froms
  1926. )
  1927. def visit_empty_set_expr(self, type_, **kw):
  1928. return "SELECT 1 WHERE 1!=1"
  1929. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  1930. return "NOT EXISTS (SELECT %s INTERSECT SELECT %s)" % (
  1931. self.process(binary.left),
  1932. self.process(binary.right),
  1933. )
  1934. def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
  1935. return "EXISTS (SELECT %s INTERSECT SELECT %s)" % (
  1936. self.process(binary.left),
  1937. self.process(binary.right),
  1938. )
  1939. def _render_json_extract_from_binary(self, binary, operator, **kw):
  1940. # note we are intentionally calling upon the process() calls in the
  1941. # order in which they appear in the SQL String as this is used
  1942. # by positional parameter rendering
  1943. if binary.type._type_affinity is sqltypes.JSON:
  1944. return "JSON_QUERY(%s, %s)" % (
  1945. self.process(binary.left, **kw),
  1946. self.process(binary.right, **kw),
  1947. )
  1948. # as with other dialects, start with an explicit test for NULL
  1949. case_expression = "CASE JSON_VALUE(%s, %s) WHEN NULL THEN NULL" % (
  1950. self.process(binary.left, **kw),
  1951. self.process(binary.right, **kw),
  1952. )
  1953. if binary.type._type_affinity is sqltypes.Integer:
  1954. type_expression = "ELSE CAST(JSON_VALUE(%s, %s) AS INTEGER)" % (
  1955. self.process(binary.left, **kw),
  1956. self.process(binary.right, **kw),
  1957. )
  1958. elif binary.type._type_affinity is sqltypes.Numeric:
  1959. type_expression = "ELSE CAST(JSON_VALUE(%s, %s) AS %s)" % (
  1960. self.process(binary.left, **kw),
  1961. self.process(binary.right, **kw),
  1962. (
  1963. "FLOAT"
  1964. if isinstance(binary.type, sqltypes.Float)
  1965. else "NUMERIC(%s, %s)"
  1966. % (binary.type.precision, binary.type.scale)
  1967. ),
  1968. )
  1969. elif binary.type._type_affinity is sqltypes.Boolean:
  1970. # the NULL handling is particularly weird with boolean, so
  1971. # explicitly return numeric (BIT) constants
  1972. type_expression = (
  1973. "WHEN 'true' THEN 1 WHEN 'false' THEN 0 ELSE NULL"
  1974. )
  1975. elif binary.type._type_affinity is sqltypes.String:
  1976. # TODO: does this comment (from mysql) apply to here, too?
  1977. # this fails with a JSON value that's a four byte unicode
  1978. # string. SQLite has the same problem at the moment
  1979. type_expression = "ELSE JSON_VALUE(%s, %s)" % (
  1980. self.process(binary.left, **kw),
  1981. self.process(binary.right, **kw),
  1982. )
  1983. else:
  1984. # other affinity....this is not expected right now
  1985. type_expression = "ELSE JSON_QUERY(%s, %s)" % (
  1986. self.process(binary.left, **kw),
  1987. self.process(binary.right, **kw),
  1988. )
  1989. return case_expression + " " + type_expression + " END"
  1990. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  1991. return self._render_json_extract_from_binary(binary, operator, **kw)
  1992. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  1993. return self._render_json_extract_from_binary(binary, operator, **kw)
  1994. def visit_sequence(self, seq, **kw):
  1995. return "NEXT VALUE FOR %s" % self.preparer.format_sequence(seq)
  1996. class MSSQLStrictCompiler(MSSQLCompiler):
  1997. """A subclass of MSSQLCompiler which disables the usage of bind
  1998. parameters where not allowed natively by MS-SQL.
  1999. A dialect may use this compiler on a platform where native
  2000. binds are used.
  2001. """
  2002. ansi_bind_rules = True
  2003. def visit_in_op_binary(self, binary, operator, **kw):
  2004. kw["literal_execute"] = True
  2005. return "%s IN %s" % (
  2006. self.process(binary.left, **kw),
  2007. self.process(binary.right, **kw),
  2008. )
  2009. def visit_not_in_op_binary(self, binary, operator, **kw):
  2010. kw["literal_execute"] = True
  2011. return "%s NOT IN %s" % (
  2012. self.process(binary.left, **kw),
  2013. self.process(binary.right, **kw),
  2014. )
  2015. def render_literal_value(self, value, type_):
  2016. """
  2017. For date and datetime values, convert to a string
  2018. format acceptable to MSSQL. That seems to be the
  2019. so-called ODBC canonical date format which looks
  2020. like this:
  2021. yyyy-mm-dd hh:mi:ss.mmm(24h)
  2022. For other data types, call the base class implementation.
  2023. """
  2024. # datetime and date are both subclasses of datetime.date
  2025. if issubclass(type(value), datetime.date):
  2026. # SQL Server wants single quotes around the date string.
  2027. return "'" + str(value) + "'"
  2028. else:
  2029. return super().render_literal_value(value, type_)
  2030. class MSDDLCompiler(compiler.DDLCompiler):
  2031. def get_column_specification(self, column, **kwargs):
  2032. colspec = self.preparer.format_column(column)
  2033. # type is not accepted in a computed column
  2034. if column.computed is not None:
  2035. colspec += " " + self.process(column.computed)
  2036. else:
  2037. colspec += " " + self.dialect.type_compiler_instance.process(
  2038. column.type, type_expression=column
  2039. )
  2040. if column.nullable is not None:
  2041. if (
  2042. not column.nullable
  2043. or column.primary_key
  2044. or isinstance(column.default, sa_schema.Sequence)
  2045. or column.autoincrement is True
  2046. or column.identity
  2047. ):
  2048. colspec += " NOT NULL"
  2049. elif column.computed is None:
  2050. # don't specify "NULL" for computed columns
  2051. colspec += " NULL"
  2052. if column.table is None:
  2053. raise exc.CompileError(
  2054. "mssql requires Table-bound columns "
  2055. "in order to generate DDL"
  2056. )
  2057. d_opt = column.dialect_options["mssql"]
  2058. start = d_opt["identity_start"]
  2059. increment = d_opt["identity_increment"]
  2060. if start is not None or increment is not None:
  2061. if column.identity:
  2062. raise exc.CompileError(
  2063. "Cannot specify options 'mssql_identity_start' and/or "
  2064. "'mssql_identity_increment' while also using the "
  2065. "'Identity' construct."
  2066. )
  2067. util.warn_deprecated(
  2068. "The dialect options 'mssql_identity_start' and "
  2069. "'mssql_identity_increment' are deprecated. "
  2070. "Use the 'Identity' object instead.",
  2071. "1.4",
  2072. )
  2073. if column.identity:
  2074. colspec += self.process(column.identity, **kwargs)
  2075. elif (
  2076. column is column.table._autoincrement_column
  2077. or column.autoincrement is True
  2078. ) and (
  2079. not isinstance(column.default, Sequence) or column.default.optional
  2080. ):
  2081. colspec += self.process(Identity(start=start, increment=increment))
  2082. else:
  2083. default = self.get_column_default_string(column)
  2084. if default is not None:
  2085. colspec += " DEFAULT " + default
  2086. return colspec
  2087. def visit_create_index(self, create, include_schema=False, **kw):
  2088. index = create.element
  2089. self._verify_index_table(index)
  2090. preparer = self.preparer
  2091. text = "CREATE "
  2092. if index.unique:
  2093. text += "UNIQUE "
  2094. # handle clustering option
  2095. clustered = index.dialect_options["mssql"]["clustered"]
  2096. if clustered is not None:
  2097. if clustered:
  2098. text += "CLUSTERED "
  2099. else:
  2100. text += "NONCLUSTERED "
  2101. # handle columnstore option (has no negative value)
  2102. columnstore = index.dialect_options["mssql"]["columnstore"]
  2103. if columnstore:
  2104. text += "COLUMNSTORE "
  2105. text += "INDEX %s ON %s" % (
  2106. self._prepared_index_name(index, include_schema=include_schema),
  2107. preparer.format_table(index.table),
  2108. )
  2109. # in some case mssql allows indexes with no columns defined
  2110. if len(index.expressions) > 0:
  2111. text += " (%s)" % ", ".join(
  2112. self.sql_compiler.process(
  2113. expr, include_table=False, literal_binds=True
  2114. )
  2115. for expr in index.expressions
  2116. )
  2117. # handle other included columns
  2118. if index.dialect_options["mssql"]["include"]:
  2119. inclusions = [
  2120. index.table.c[col] if isinstance(col, str) else col
  2121. for col in index.dialect_options["mssql"]["include"]
  2122. ]
  2123. text += " INCLUDE (%s)" % ", ".join(
  2124. [preparer.quote(c.name) for c in inclusions]
  2125. )
  2126. whereclause = index.dialect_options["mssql"]["where"]
  2127. if whereclause is not None:
  2128. whereclause = coercions.expect(
  2129. roles.DDLExpressionRole, whereclause
  2130. )
  2131. where_compiled = self.sql_compiler.process(
  2132. whereclause, include_table=False, literal_binds=True
  2133. )
  2134. text += " WHERE " + where_compiled
  2135. return text
  2136. def visit_drop_index(self, drop: DropIndex, **kw: Any) -> str:
  2137. index_name = self._prepared_index_name(
  2138. drop.element, include_schema=False
  2139. )
  2140. table_name = self.preparer.format_table(drop.element.table)
  2141. if_exists = " IF EXISTS" if drop.if_exists else ""
  2142. return f"\nDROP INDEX{if_exists} {index_name} ON {table_name}"
  2143. def visit_primary_key_constraint(self, constraint, **kw):
  2144. if len(constraint) == 0:
  2145. return ""
  2146. text = ""
  2147. if constraint.name is not None:
  2148. text += "CONSTRAINT %s " % self.preparer.format_constraint(
  2149. constraint
  2150. )
  2151. text += "PRIMARY KEY "
  2152. clustered = constraint.dialect_options["mssql"]["clustered"]
  2153. if clustered is not None:
  2154. if clustered:
  2155. text += "CLUSTERED "
  2156. else:
  2157. text += "NONCLUSTERED "
  2158. text += "(%s)" % ", ".join(
  2159. self.preparer.quote(c.name) for c in constraint
  2160. )
  2161. text += self.define_constraint_deferrability(constraint)
  2162. return text
  2163. def visit_unique_constraint(self, constraint, **kw):
  2164. if len(constraint) == 0:
  2165. return ""
  2166. text = ""
  2167. if constraint.name is not None:
  2168. formatted_name = self.preparer.format_constraint(constraint)
  2169. if formatted_name is not None:
  2170. text += "CONSTRAINT %s " % formatted_name
  2171. text += "UNIQUE %s" % self.define_unique_constraint_distinct(
  2172. constraint, **kw
  2173. )
  2174. clustered = constraint.dialect_options["mssql"]["clustered"]
  2175. if clustered is not None:
  2176. if clustered:
  2177. text += "CLUSTERED "
  2178. else:
  2179. text += "NONCLUSTERED "
  2180. text += "(%s)" % ", ".join(
  2181. self.preparer.quote(c.name) for c in constraint
  2182. )
  2183. text += self.define_constraint_deferrability(constraint)
  2184. return text
  2185. def visit_computed_column(self, generated, **kw):
  2186. text = "AS (%s)" % self.sql_compiler.process(
  2187. generated.sqltext, include_table=False, literal_binds=True
  2188. )
  2189. # explicitly check for True|False since None means server default
  2190. if generated.persisted is True:
  2191. text += " PERSISTED"
  2192. return text
  2193. def visit_set_table_comment(self, create, **kw):
  2194. schema = self.preparer.schema_for_object(create.element)
  2195. schema_name = schema if schema else self.dialect.default_schema_name
  2196. return (
  2197. "execute sp_addextendedproperty 'MS_Description', "
  2198. "{}, 'schema', {}, 'table', {}".format(
  2199. self.sql_compiler.render_literal_value(
  2200. create.element.comment, sqltypes.NVARCHAR()
  2201. ),
  2202. self.preparer.quote_schema(schema_name),
  2203. self.preparer.format_table(create.element, use_schema=False),
  2204. )
  2205. )
  2206. def visit_drop_table_comment(self, drop, **kw):
  2207. schema = self.preparer.schema_for_object(drop.element)
  2208. schema_name = schema if schema else self.dialect.default_schema_name
  2209. return (
  2210. "execute sp_dropextendedproperty 'MS_Description', 'schema', "
  2211. "{}, 'table', {}".format(
  2212. self.preparer.quote_schema(schema_name),
  2213. self.preparer.format_table(drop.element, use_schema=False),
  2214. )
  2215. )
  2216. def visit_set_column_comment(self, create, **kw):
  2217. schema = self.preparer.schema_for_object(create.element.table)
  2218. schema_name = schema if schema else self.dialect.default_schema_name
  2219. return (
  2220. "execute sp_addextendedproperty 'MS_Description', "
  2221. "{}, 'schema', {}, 'table', {}, 'column', {}".format(
  2222. self.sql_compiler.render_literal_value(
  2223. create.element.comment, sqltypes.NVARCHAR()
  2224. ),
  2225. self.preparer.quote_schema(schema_name),
  2226. self.preparer.format_table(
  2227. create.element.table, use_schema=False
  2228. ),
  2229. self.preparer.format_column(create.element),
  2230. )
  2231. )
  2232. def visit_drop_column_comment(self, drop, **kw):
  2233. schema = self.preparer.schema_for_object(drop.element.table)
  2234. schema_name = schema if schema else self.dialect.default_schema_name
  2235. return (
  2236. "execute sp_dropextendedproperty 'MS_Description', 'schema', "
  2237. "{}, 'table', {}, 'column', {}".format(
  2238. self.preparer.quote_schema(schema_name),
  2239. self.preparer.format_table(
  2240. drop.element.table, use_schema=False
  2241. ),
  2242. self.preparer.format_column(drop.element),
  2243. )
  2244. )
  2245. def visit_create_sequence(self, create, **kw):
  2246. prefix = None
  2247. if create.element.data_type is not None:
  2248. data_type = create.element.data_type
  2249. prefix = " AS %s" % self.type_compiler.process(data_type)
  2250. return super().visit_create_sequence(create, prefix=prefix, **kw)
  2251. def visit_identity_column(self, identity, **kw):
  2252. text = " IDENTITY"
  2253. if identity.start is not None or identity.increment is not None:
  2254. start = 1 if identity.start is None else identity.start
  2255. increment = 1 if identity.increment is None else identity.increment
  2256. text += "(%s,%s)" % (start, increment)
  2257. return text
  2258. class MSIdentifierPreparer(compiler.IdentifierPreparer):
  2259. reserved_words = RESERVED_WORDS
  2260. def __init__(self, dialect):
  2261. super().__init__(
  2262. dialect,
  2263. initial_quote="[",
  2264. final_quote="]",
  2265. quote_case_sensitive_collations=False,
  2266. )
  2267. def _escape_identifier(self, value):
  2268. return value.replace("]", "]]")
  2269. def _unescape_identifier(self, value):
  2270. return value.replace("]]", "]")
  2271. def quote_schema(self, schema, force=None):
  2272. """Prepare a quoted table and schema name."""
  2273. # need to re-implement the deprecation warning entirely
  2274. if force is not None:
  2275. # not using the util.deprecated_params() decorator in this
  2276. # case because of the additional function call overhead on this
  2277. # very performance-critical spot.
  2278. util.warn_deprecated(
  2279. "The IdentifierPreparer.quote_schema.force parameter is "
  2280. "deprecated and will be removed in a future release. This "
  2281. "flag has no effect on the behavior of the "
  2282. "IdentifierPreparer.quote method; please refer to "
  2283. "quoted_name().",
  2284. version="1.3",
  2285. )
  2286. dbname, owner = _schema_elements(schema)
  2287. if dbname:
  2288. result = "%s.%s" % (self.quote(dbname), self.quote(owner))
  2289. elif owner:
  2290. result = self.quote(owner)
  2291. else:
  2292. result = ""
  2293. return result
  2294. def _db_plus_owner_listing(fn):
  2295. def wrap(dialect, connection, schema=None, **kw):
  2296. dbname, owner = _owner_plus_db(dialect, schema)
  2297. return _switch_db(
  2298. dbname,
  2299. connection,
  2300. fn,
  2301. dialect,
  2302. connection,
  2303. dbname,
  2304. owner,
  2305. schema,
  2306. **kw,
  2307. )
  2308. return update_wrapper(wrap, fn)
  2309. def _db_plus_owner(fn):
  2310. def wrap(dialect, connection, tablename, schema=None, **kw):
  2311. dbname, owner = _owner_plus_db(dialect, schema)
  2312. return _switch_db(
  2313. dbname,
  2314. connection,
  2315. fn,
  2316. dialect,
  2317. connection,
  2318. tablename,
  2319. dbname,
  2320. owner,
  2321. schema,
  2322. **kw,
  2323. )
  2324. return update_wrapper(wrap, fn)
  2325. def _switch_db(dbname, connection, fn, *arg, **kw):
  2326. if dbname:
  2327. current_db = connection.exec_driver_sql("select db_name()").scalar()
  2328. if current_db != dbname:
  2329. connection.exec_driver_sql(
  2330. "use %s" % connection.dialect.identifier_preparer.quote(dbname)
  2331. )
  2332. try:
  2333. return fn(*arg, **kw)
  2334. finally:
  2335. if dbname and current_db != dbname:
  2336. connection.exec_driver_sql(
  2337. "use %s"
  2338. % connection.dialect.identifier_preparer.quote(current_db)
  2339. )
  2340. def _owner_plus_db(dialect, schema):
  2341. if not schema:
  2342. return None, dialect.default_schema_name
  2343. else:
  2344. return _schema_elements(schema)
  2345. _memoized_schema = util.LRUCache()
  2346. def _schema_elements(schema):
  2347. if isinstance(schema, quoted_name) and schema.quote:
  2348. return None, schema
  2349. if schema in _memoized_schema:
  2350. return _memoized_schema[schema]
  2351. # tests for this function are in:
  2352. # test/dialect/mssql/test_reflection.py ->
  2353. # OwnerPlusDBTest.test_owner_database_pairs
  2354. # test/dialect/mssql/test_compiler.py -> test_force_schema_*
  2355. # test/dialect/mssql/test_compiler.py -> test_schema_many_tokens_*
  2356. #
  2357. if schema.startswith("__[SCHEMA_"):
  2358. return None, schema
  2359. push = []
  2360. symbol = ""
  2361. bracket = False
  2362. has_brackets = False
  2363. for token in re.split(r"(\[|\]|\.)", schema):
  2364. if not token:
  2365. continue
  2366. if token == "[":
  2367. bracket = True
  2368. has_brackets = True
  2369. elif token == "]":
  2370. bracket = False
  2371. elif not bracket and token == ".":
  2372. if has_brackets:
  2373. push.append("[%s]" % symbol)
  2374. else:
  2375. push.append(symbol)
  2376. symbol = ""
  2377. has_brackets = False
  2378. else:
  2379. symbol += token
  2380. if symbol:
  2381. push.append(symbol)
  2382. if len(push) > 1:
  2383. dbname, owner = ".".join(push[0:-1]), push[-1]
  2384. # test for internal brackets
  2385. if re.match(r".*\].*\[.*", dbname[1:-1]):
  2386. dbname = quoted_name(dbname, quote=False)
  2387. else:
  2388. dbname = dbname.lstrip("[").rstrip("]")
  2389. elif len(push):
  2390. dbname, owner = None, push[0]
  2391. else:
  2392. dbname, owner = None, None
  2393. _memoized_schema[schema] = dbname, owner
  2394. return dbname, owner
  2395. class MSDialect(default.DefaultDialect):
  2396. # will assume it's at least mssql2005
  2397. name = "mssql"
  2398. supports_statement_cache = True
  2399. supports_default_values = True
  2400. supports_empty_insert = False
  2401. favor_returning_over_lastrowid = True
  2402. returns_native_bytes = True
  2403. supports_comments = True
  2404. supports_default_metavalue = False
  2405. """dialect supports INSERT... VALUES (DEFAULT) syntax -
  2406. SQL Server **does** support this, but **not** for the IDENTITY column,
  2407. so we can't turn this on.
  2408. """
  2409. # supports_native_uuid is partial here, so we implement our
  2410. # own impl type
  2411. execution_ctx_cls = MSExecutionContext
  2412. use_scope_identity = True
  2413. max_identifier_length = 128
  2414. schema_name = "dbo"
  2415. insert_returning = True
  2416. update_returning = True
  2417. delete_returning = True
  2418. update_returning_multifrom = True
  2419. delete_returning_multifrom = True
  2420. colspecs = {
  2421. sqltypes.DateTime: _MSDateTime,
  2422. sqltypes.Date: _MSDate,
  2423. sqltypes.JSON: JSON,
  2424. sqltypes.JSON.JSONIndexType: JSONIndexType,
  2425. sqltypes.JSON.JSONPathType: JSONPathType,
  2426. sqltypes.Time: _BASETIMEIMPL,
  2427. sqltypes.Unicode: _MSUnicode,
  2428. sqltypes.UnicodeText: _MSUnicodeText,
  2429. DATETIMEOFFSET: DATETIMEOFFSET,
  2430. DATETIME2: DATETIME2,
  2431. SMALLDATETIME: SMALLDATETIME,
  2432. DATETIME: DATETIME,
  2433. sqltypes.Uuid: MSUUid,
  2434. }
  2435. engine_config_types = default.DefaultDialect.engine_config_types.union(
  2436. {"legacy_schema_aliasing": util.asbool}
  2437. )
  2438. ischema_names = ischema_names
  2439. supports_sequences = True
  2440. sequences_optional = True
  2441. # This is actually used for autoincrement, where itentity is used that
  2442. # starts with 1.
  2443. # for sequences T-SQL's actual default is -9223372036854775808
  2444. default_sequence_base = 1
  2445. supports_native_boolean = False
  2446. non_native_boolean_check_constraint = False
  2447. supports_unicode_binds = True
  2448. postfetch_lastrowid = True
  2449. # may be changed at server inspection time for older SQL server versions
  2450. supports_multivalues_insert = True
  2451. use_insertmanyvalues = True
  2452. # note pyodbc will set this to False if fast_executemany is set,
  2453. # as of SQLAlchemy 2.0.9
  2454. use_insertmanyvalues_wo_returning = True
  2455. insertmanyvalues_implicit_sentinel = (
  2456. InsertmanyvaluesSentinelOpts.AUTOINCREMENT
  2457. | InsertmanyvaluesSentinelOpts.IDENTITY
  2458. | InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT
  2459. )
  2460. # "The incoming request has too many parameters. The server supports a "
  2461. # "maximum of 2100 parameters."
  2462. # in fact you can have 2099 parameters.
  2463. insertmanyvalues_max_parameters = 2099
  2464. _supports_offset_fetch = False
  2465. _supports_nvarchar_max = False
  2466. legacy_schema_aliasing = False
  2467. server_version_info = ()
  2468. statement_compiler = MSSQLCompiler
  2469. ddl_compiler = MSDDLCompiler
  2470. type_compiler_cls = MSTypeCompiler
  2471. preparer = MSIdentifierPreparer
  2472. construct_arguments = [
  2473. (sa_schema.PrimaryKeyConstraint, {"clustered": None}),
  2474. (sa_schema.UniqueConstraint, {"clustered": None}),
  2475. (
  2476. sa_schema.Index,
  2477. {
  2478. "clustered": None,
  2479. "include": None,
  2480. "where": None,
  2481. "columnstore": None,
  2482. },
  2483. ),
  2484. (
  2485. sa_schema.Column,
  2486. {"identity_start": None, "identity_increment": None},
  2487. ),
  2488. ]
  2489. def __init__(
  2490. self,
  2491. query_timeout=None,
  2492. use_scope_identity=True,
  2493. schema_name="dbo",
  2494. deprecate_large_types=None,
  2495. supports_comments=None,
  2496. json_serializer=None,
  2497. json_deserializer=None,
  2498. legacy_schema_aliasing=None,
  2499. ignore_no_transaction_on_rollback=False,
  2500. **opts,
  2501. ):
  2502. self.query_timeout = int(query_timeout or 0)
  2503. self.schema_name = schema_name
  2504. self.use_scope_identity = use_scope_identity
  2505. self.deprecate_large_types = deprecate_large_types
  2506. self.ignore_no_transaction_on_rollback = (
  2507. ignore_no_transaction_on_rollback
  2508. )
  2509. self._user_defined_supports_comments = uds = supports_comments
  2510. if uds is not None:
  2511. self.supports_comments = uds
  2512. if legacy_schema_aliasing is not None:
  2513. util.warn_deprecated(
  2514. "The legacy_schema_aliasing parameter is "
  2515. "deprecated and will be removed in a future release.",
  2516. "1.4",
  2517. )
  2518. self.legacy_schema_aliasing = legacy_schema_aliasing
  2519. super().__init__(**opts)
  2520. self._json_serializer = json_serializer
  2521. self._json_deserializer = json_deserializer
  2522. def do_savepoint(self, connection, name):
  2523. # give the DBAPI a push
  2524. connection.exec_driver_sql("IF @@TRANCOUNT = 0 BEGIN TRANSACTION")
  2525. super().do_savepoint(connection, name)
  2526. def do_release_savepoint(self, connection, name):
  2527. # SQL Server does not support RELEASE SAVEPOINT
  2528. pass
  2529. def do_rollback(self, dbapi_connection):
  2530. try:
  2531. super().do_rollback(dbapi_connection)
  2532. except self.dbapi.ProgrammingError as e:
  2533. if self.ignore_no_transaction_on_rollback and re.match(
  2534. r".*\b111214\b", str(e)
  2535. ):
  2536. util.warn(
  2537. "ProgrammingError 111214 "
  2538. "'No corresponding transaction found.' "
  2539. "has been suppressed via "
  2540. "ignore_no_transaction_on_rollback=True"
  2541. )
  2542. else:
  2543. raise
  2544. _isolation_lookup = {
  2545. "SERIALIZABLE",
  2546. "READ UNCOMMITTED",
  2547. "READ COMMITTED",
  2548. "REPEATABLE READ",
  2549. "SNAPSHOT",
  2550. }
  2551. def get_isolation_level_values(self, dbapi_connection):
  2552. return list(self._isolation_lookup)
  2553. def set_isolation_level(self, dbapi_connection, level):
  2554. cursor = dbapi_connection.cursor()
  2555. cursor.execute(f"SET TRANSACTION ISOLATION LEVEL {level}")
  2556. cursor.close()
  2557. if level == "SNAPSHOT":
  2558. dbapi_connection.commit()
  2559. def get_isolation_level(self, dbapi_connection):
  2560. cursor = dbapi_connection.cursor()
  2561. view_name = "sys.system_views"
  2562. try:
  2563. cursor.execute(
  2564. (
  2565. "SELECT name FROM {} WHERE name IN "
  2566. "('dm_exec_sessions', 'dm_pdw_nodes_exec_sessions')"
  2567. ).format(view_name)
  2568. )
  2569. row = cursor.fetchone()
  2570. if not row:
  2571. raise NotImplementedError(
  2572. "Can't fetch isolation level on this particular "
  2573. "SQL Server version."
  2574. )
  2575. view_name = f"sys.{row[0]}"
  2576. cursor.execute(
  2577. """
  2578. SELECT CASE transaction_isolation_level
  2579. WHEN 0 THEN NULL
  2580. WHEN 1 THEN 'READ UNCOMMITTED'
  2581. WHEN 2 THEN 'READ COMMITTED'
  2582. WHEN 3 THEN 'REPEATABLE READ'
  2583. WHEN 4 THEN 'SERIALIZABLE'
  2584. WHEN 5 THEN 'SNAPSHOT' END
  2585. AS TRANSACTION_ISOLATION_LEVEL
  2586. FROM {}
  2587. where session_id = @@SPID
  2588. """.format(
  2589. view_name
  2590. )
  2591. )
  2592. except self.dbapi.Error as err:
  2593. raise NotImplementedError(
  2594. "Can't fetch isolation level; encountered error {} when "
  2595. 'attempting to query the "{}" view.'.format(err, view_name)
  2596. ) from err
  2597. else:
  2598. row = cursor.fetchone()
  2599. return row[0].upper()
  2600. finally:
  2601. cursor.close()
  2602. def initialize(self, connection):
  2603. super().initialize(connection)
  2604. self._setup_version_attributes()
  2605. self._setup_supports_nvarchar_max(connection)
  2606. self._setup_supports_comments(connection)
  2607. def _setup_version_attributes(self):
  2608. if self.server_version_info[0] not in list(range(8, 17)):
  2609. util.warn(
  2610. "Unrecognized server version info '%s'. Some SQL Server "
  2611. "features may not function properly."
  2612. % ".".join(str(x) for x in self.server_version_info)
  2613. )
  2614. if self.server_version_info >= MS_2008_VERSION:
  2615. self.supports_multivalues_insert = True
  2616. else:
  2617. self.supports_multivalues_insert = False
  2618. if self.deprecate_large_types is None:
  2619. self.deprecate_large_types = (
  2620. self.server_version_info >= MS_2012_VERSION
  2621. )
  2622. self._supports_offset_fetch = (
  2623. self.server_version_info and self.server_version_info[0] >= 11
  2624. )
  2625. def _setup_supports_nvarchar_max(self, connection):
  2626. try:
  2627. connection.scalar(
  2628. sql.text("SELECT CAST('test max support' AS NVARCHAR(max))")
  2629. )
  2630. except exc.DBAPIError:
  2631. self._supports_nvarchar_max = False
  2632. else:
  2633. self._supports_nvarchar_max = True
  2634. def _setup_supports_comments(self, connection):
  2635. if self._user_defined_supports_comments is not None:
  2636. return
  2637. try:
  2638. connection.scalar(
  2639. sql.text(
  2640. "SELECT 1 FROM fn_listextendedproperty"
  2641. "(default, default, default, default, "
  2642. "default, default, default)"
  2643. )
  2644. )
  2645. except exc.DBAPIError:
  2646. self.supports_comments = False
  2647. else:
  2648. self.supports_comments = True
  2649. def _get_default_schema_name(self, connection):
  2650. query = sql.text("SELECT schema_name()")
  2651. default_schema_name = connection.scalar(query)
  2652. if default_schema_name is not None:
  2653. # guard against the case where the default_schema_name is being
  2654. # fed back into a table reflection function.
  2655. return quoted_name(default_schema_name, quote=True)
  2656. else:
  2657. return self.schema_name
  2658. @_db_plus_owner
  2659. def has_table(self, connection, tablename, dbname, owner, schema, **kw):
  2660. self._ensure_has_table_connection(connection)
  2661. return self._internal_has_table(connection, tablename, owner, **kw)
  2662. @reflection.cache
  2663. @_db_plus_owner
  2664. def has_sequence(
  2665. self, connection, sequencename, dbname, owner, schema, **kw
  2666. ):
  2667. sequences = ischema.sequences
  2668. s = sql.select(sequences.c.sequence_name).where(
  2669. sequences.c.sequence_name == sequencename
  2670. )
  2671. if owner:
  2672. s = s.where(sequences.c.sequence_schema == owner)
  2673. c = connection.execute(s)
  2674. return c.first() is not None
  2675. @reflection.cache
  2676. @_db_plus_owner_listing
  2677. def get_sequence_names(self, connection, dbname, owner, schema, **kw):
  2678. sequences = ischema.sequences
  2679. s = sql.select(sequences.c.sequence_name)
  2680. if owner:
  2681. s = s.where(sequences.c.sequence_schema == owner)
  2682. c = connection.execute(s)
  2683. return [row[0] for row in c]
  2684. @reflection.cache
  2685. def get_schema_names(self, connection, **kw):
  2686. s = sql.select(ischema.schemata.c.schema_name).order_by(
  2687. ischema.schemata.c.schema_name
  2688. )
  2689. schema_names = [r[0] for r in connection.execute(s)]
  2690. return schema_names
  2691. @reflection.cache
  2692. @_db_plus_owner_listing
  2693. def get_table_names(self, connection, dbname, owner, schema, **kw):
  2694. tables = ischema.tables
  2695. s = (
  2696. sql.select(tables.c.table_name)
  2697. .where(
  2698. sql.and_(
  2699. tables.c.table_schema == owner,
  2700. tables.c.table_type == "BASE TABLE",
  2701. )
  2702. )
  2703. .order_by(tables.c.table_name)
  2704. )
  2705. table_names = [r[0] for r in connection.execute(s)]
  2706. return table_names
  2707. @reflection.cache
  2708. @_db_plus_owner_listing
  2709. def get_view_names(self, connection, dbname, owner, schema, **kw):
  2710. tables = ischema.tables
  2711. s = (
  2712. sql.select(tables.c.table_name)
  2713. .where(
  2714. sql.and_(
  2715. tables.c.table_schema == owner,
  2716. tables.c.table_type == "VIEW",
  2717. )
  2718. )
  2719. .order_by(tables.c.table_name)
  2720. )
  2721. view_names = [r[0] for r in connection.execute(s)]
  2722. return view_names
  2723. @reflection.cache
  2724. def _internal_has_table(self, connection, tablename, owner, **kw):
  2725. if tablename.startswith("#"): # temporary table
  2726. # mssql does not support temporary views
  2727. # SQL Error [4103] [S0001]: "#v": Temporary views are not allowed
  2728. return bool(
  2729. connection.scalar(
  2730. # U filters on user tables only.
  2731. text("SELECT object_id(:table_name, 'U')"),
  2732. {"table_name": f"tempdb.dbo.[{tablename}]"},
  2733. )
  2734. )
  2735. else:
  2736. tables = ischema.tables
  2737. s = sql.select(tables.c.table_name).where(
  2738. sql.and_(
  2739. sql.or_(
  2740. tables.c.table_type == "BASE TABLE",
  2741. tables.c.table_type == "VIEW",
  2742. ),
  2743. tables.c.table_name == tablename,
  2744. )
  2745. )
  2746. if owner:
  2747. s = s.where(tables.c.table_schema == owner)
  2748. c = connection.execute(s)
  2749. return c.first() is not None
  2750. def _default_or_error(self, connection, tablename, owner, method, **kw):
  2751. # TODO: try to avoid having to run a separate query here
  2752. if self._internal_has_table(connection, tablename, owner, **kw):
  2753. return method()
  2754. else:
  2755. raise exc.NoSuchTableError(f"{owner}.{tablename}")
  2756. @reflection.cache
  2757. @_db_plus_owner
  2758. def get_indexes(self, connection, tablename, dbname, owner, schema, **kw):
  2759. filter_definition = (
  2760. "ind.filter_definition"
  2761. if self.server_version_info >= MS_2008_VERSION
  2762. else "NULL as filter_definition"
  2763. )
  2764. rp = connection.execution_options(future_result=True).execute(
  2765. sql.text(
  2766. f"""
  2767. select
  2768. ind.index_id,
  2769. ind.is_unique,
  2770. ind.name,
  2771. ind.type,
  2772. {filter_definition}
  2773. from
  2774. sys.indexes as ind
  2775. join sys.tables as tab on
  2776. ind.object_id = tab.object_id
  2777. join sys.schemas as sch on
  2778. sch.schema_id = tab.schema_id
  2779. where
  2780. tab.name = :tabname
  2781. and sch.name = :schname
  2782. and ind.is_primary_key = 0
  2783. and ind.type != 0
  2784. order by
  2785. ind.name
  2786. """
  2787. )
  2788. .bindparams(
  2789. sql.bindparam("tabname", tablename, ischema.CoerceUnicode()),
  2790. sql.bindparam("schname", owner, ischema.CoerceUnicode()),
  2791. )
  2792. .columns(name=sqltypes.Unicode())
  2793. )
  2794. indexes = {}
  2795. for row in rp.mappings():
  2796. indexes[row["index_id"]] = current = {
  2797. "name": row["name"],
  2798. "unique": row["is_unique"] == 1,
  2799. "column_names": [],
  2800. "include_columns": [],
  2801. "dialect_options": {},
  2802. }
  2803. do = current["dialect_options"]
  2804. index_type = row["type"]
  2805. if index_type in {1, 2}:
  2806. do["mssql_clustered"] = index_type == 1
  2807. if index_type in {5, 6}:
  2808. do["mssql_clustered"] = index_type == 5
  2809. do["mssql_columnstore"] = True
  2810. if row["filter_definition"] is not None:
  2811. do["mssql_where"] = row["filter_definition"]
  2812. rp = connection.execution_options(future_result=True).execute(
  2813. sql.text(
  2814. """
  2815. select
  2816. ind_col.index_id,
  2817. col.name,
  2818. ind_col.is_included_column
  2819. from
  2820. sys.columns as col
  2821. join sys.tables as tab on
  2822. tab.object_id = col.object_id
  2823. join sys.index_columns as ind_col on
  2824. ind_col.column_id = col.column_id
  2825. and ind_col.object_id = tab.object_id
  2826. join sys.schemas as sch on
  2827. sch.schema_id = tab.schema_id
  2828. where
  2829. tab.name = :tabname
  2830. and sch.name = :schname
  2831. order by
  2832. ind_col.index_id,
  2833. ind_col.key_ordinal
  2834. """
  2835. )
  2836. .bindparams(
  2837. sql.bindparam("tabname", tablename, ischema.CoerceUnicode()),
  2838. sql.bindparam("schname", owner, ischema.CoerceUnicode()),
  2839. )
  2840. .columns(name=sqltypes.Unicode())
  2841. )
  2842. for row in rp.mappings():
  2843. if row["index_id"] not in indexes:
  2844. continue
  2845. index_def = indexes[row["index_id"]]
  2846. is_colstore = index_def["dialect_options"].get("mssql_columnstore")
  2847. is_clustered = index_def["dialect_options"].get("mssql_clustered")
  2848. if not (is_colstore and is_clustered):
  2849. # a clustered columnstore index includes all columns but does
  2850. # not want them in the index definition
  2851. if row["is_included_column"] and not is_colstore:
  2852. # a noncludsted columnstore index reports that includes
  2853. # columns but requires that are listed as normal columns
  2854. index_def["include_columns"].append(row["name"])
  2855. else:
  2856. index_def["column_names"].append(row["name"])
  2857. for index_info in indexes.values():
  2858. # NOTE: "root level" include_columns is legacy, now part of
  2859. # dialect_options (issue #7382)
  2860. index_info["dialect_options"]["mssql_include"] = index_info[
  2861. "include_columns"
  2862. ]
  2863. if indexes:
  2864. return list(indexes.values())
  2865. else:
  2866. return self._default_or_error(
  2867. connection, tablename, owner, ReflectionDefaults.indexes, **kw
  2868. )
  2869. @reflection.cache
  2870. @_db_plus_owner
  2871. def get_view_definition(
  2872. self, connection, viewname, dbname, owner, schema, **kw
  2873. ):
  2874. view_def = connection.execute(
  2875. sql.text(
  2876. "select mod.definition "
  2877. "from sys.sql_modules as mod "
  2878. "join sys.views as views on mod.object_id = views.object_id "
  2879. "join sys.schemas as sch on views.schema_id = sch.schema_id "
  2880. "where views.name=:viewname and sch.name=:schname"
  2881. ).bindparams(
  2882. sql.bindparam("viewname", viewname, ischema.CoerceUnicode()),
  2883. sql.bindparam("schname", owner, ischema.CoerceUnicode()),
  2884. )
  2885. ).scalar()
  2886. if view_def:
  2887. return view_def
  2888. else:
  2889. raise exc.NoSuchTableError(f"{owner}.{viewname}")
  2890. @reflection.cache
  2891. def get_table_comment(self, connection, table_name, schema=None, **kw):
  2892. if not self.supports_comments:
  2893. raise NotImplementedError(
  2894. "Can't get table comments on current SQL Server version in use"
  2895. )
  2896. schema_name = schema if schema else self.default_schema_name
  2897. COMMENT_SQL = """
  2898. SELECT cast(com.value as nvarchar(max))
  2899. FROM fn_listextendedproperty('MS_Description',
  2900. 'schema', :schema, 'table', :table, NULL, NULL
  2901. ) as com;
  2902. """
  2903. comment = connection.execute(
  2904. sql.text(COMMENT_SQL).bindparams(
  2905. sql.bindparam("schema", schema_name, ischema.CoerceUnicode()),
  2906. sql.bindparam("table", table_name, ischema.CoerceUnicode()),
  2907. )
  2908. ).scalar()
  2909. if comment:
  2910. return {"text": comment}
  2911. else:
  2912. return self._default_or_error(
  2913. connection,
  2914. table_name,
  2915. None,
  2916. ReflectionDefaults.table_comment,
  2917. **kw,
  2918. )
  2919. def _temp_table_name_like_pattern(self, tablename):
  2920. # LIKE uses '%' to match zero or more characters and '_' to match any
  2921. # single character. We want to match literal underscores, so T-SQL
  2922. # requires that we enclose them in square brackets.
  2923. return tablename + (
  2924. ("[_][_][_]%") if not tablename.startswith("##") else ""
  2925. )
  2926. def _get_internal_temp_table_name(self, connection, tablename):
  2927. # it's likely that schema is always "dbo", but since we can
  2928. # get it here, let's get it.
  2929. # see https://stackoverflow.com/questions/8311959/
  2930. # specifying-schema-for-temporary-tables
  2931. try:
  2932. return connection.execute(
  2933. sql.text(
  2934. "select table_schema, table_name "
  2935. "from tempdb.information_schema.tables "
  2936. "where table_name like :p1"
  2937. ),
  2938. {"p1": self._temp_table_name_like_pattern(tablename)},
  2939. ).one()
  2940. except exc.MultipleResultsFound as me:
  2941. raise exc.UnreflectableTableError(
  2942. "Found more than one temporary table named '%s' in tempdb "
  2943. "at this time. Cannot reliably resolve that name to its "
  2944. "internal table name." % tablename
  2945. ) from me
  2946. except exc.NoResultFound as ne:
  2947. raise exc.NoSuchTableError(
  2948. "Unable to find a temporary table named '%s' in tempdb."
  2949. % tablename
  2950. ) from ne
  2951. @reflection.cache
  2952. @_db_plus_owner
  2953. def get_columns(self, connection, tablename, dbname, owner, schema, **kw):
  2954. sys_columns = ischema.sys_columns
  2955. sys_types = ischema.sys_types
  2956. sys_default_constraints = ischema.sys_default_constraints
  2957. computed_cols = ischema.computed_columns
  2958. identity_cols = ischema.identity_columns
  2959. extended_properties = ischema.extended_properties
  2960. # to access sys tables, need an object_id.
  2961. # object_id() can normally match to the unquoted name even if it
  2962. # has special characters. however it also accepts quoted names,
  2963. # which means for the special case that the name itself has
  2964. # "quotes" (e.g. brackets for SQL Server) we need to "quote" (e.g.
  2965. # bracket) that name anyway. Fixed as part of #12654
  2966. is_temp_table = tablename.startswith("#")
  2967. if is_temp_table:
  2968. owner, tablename = self._get_internal_temp_table_name(
  2969. connection, tablename
  2970. )
  2971. object_id_tokens = [self.identifier_preparer.quote(tablename)]
  2972. if owner:
  2973. object_id_tokens.insert(0, self.identifier_preparer.quote(owner))
  2974. if is_temp_table:
  2975. object_id_tokens.insert(0, "tempdb")
  2976. object_id = func.object_id(".".join(object_id_tokens))
  2977. whereclause = sys_columns.c.object_id == object_id
  2978. if self._supports_nvarchar_max:
  2979. computed_definition = computed_cols.c.definition
  2980. else:
  2981. # tds_version 4.2 does not support NVARCHAR(MAX)
  2982. computed_definition = sql.cast(
  2983. computed_cols.c.definition, NVARCHAR(4000)
  2984. )
  2985. s = (
  2986. sql.select(
  2987. sys_columns.c.name,
  2988. sys_types.c.name,
  2989. sys_columns.c.is_nullable,
  2990. sys_columns.c.max_length,
  2991. sys_columns.c.precision,
  2992. sys_columns.c.scale,
  2993. sys_default_constraints.c.definition,
  2994. sys_columns.c.collation_name,
  2995. computed_definition,
  2996. computed_cols.c.is_persisted,
  2997. identity_cols.c.is_identity,
  2998. identity_cols.c.seed_value,
  2999. identity_cols.c.increment_value,
  3000. extended_properties.c.value.label("comment"),
  3001. )
  3002. .select_from(sys_columns)
  3003. .join(
  3004. sys_types,
  3005. onclause=sys_columns.c.user_type_id
  3006. == sys_types.c.user_type_id,
  3007. )
  3008. .outerjoin(
  3009. sys_default_constraints,
  3010. sql.and_(
  3011. sys_default_constraints.c.object_id
  3012. == sys_columns.c.default_object_id,
  3013. sys_default_constraints.c.parent_column_id
  3014. == sys_columns.c.column_id,
  3015. ),
  3016. )
  3017. .outerjoin(
  3018. computed_cols,
  3019. onclause=sql.and_(
  3020. computed_cols.c.object_id == sys_columns.c.object_id,
  3021. computed_cols.c.column_id == sys_columns.c.column_id,
  3022. ),
  3023. )
  3024. .outerjoin(
  3025. identity_cols,
  3026. onclause=sql.and_(
  3027. identity_cols.c.object_id == sys_columns.c.object_id,
  3028. identity_cols.c.column_id == sys_columns.c.column_id,
  3029. ),
  3030. )
  3031. .outerjoin(
  3032. extended_properties,
  3033. onclause=sql.and_(
  3034. extended_properties.c["class"] == 1,
  3035. extended_properties.c.name == "MS_Description",
  3036. sys_columns.c.object_id == extended_properties.c.major_id,
  3037. sys_columns.c.column_id == extended_properties.c.minor_id,
  3038. ),
  3039. )
  3040. .where(whereclause)
  3041. .order_by(sys_columns.c.column_id)
  3042. )
  3043. if is_temp_table:
  3044. exec_opts = {"schema_translate_map": {"sys": "tempdb.sys"}}
  3045. else:
  3046. exec_opts = {"schema_translate_map": {}}
  3047. c = connection.execution_options(**exec_opts).execute(s)
  3048. cols = []
  3049. for row in c.mappings():
  3050. name = row[sys_columns.c.name]
  3051. type_ = row[sys_types.c.name]
  3052. nullable = row[sys_columns.c.is_nullable] == 1
  3053. maxlen = row[sys_columns.c.max_length]
  3054. numericprec = row[sys_columns.c.precision]
  3055. numericscale = row[sys_columns.c.scale]
  3056. default = row[sys_default_constraints.c.definition]
  3057. collation = row[sys_columns.c.collation_name]
  3058. definition = row[computed_definition]
  3059. is_persisted = row[computed_cols.c.is_persisted]
  3060. is_identity = row[identity_cols.c.is_identity]
  3061. identity_start = row[identity_cols.c.seed_value]
  3062. identity_increment = row[identity_cols.c.increment_value]
  3063. comment = row[extended_properties.c.value]
  3064. coltype = self.ischema_names.get(type_, None)
  3065. kwargs = {}
  3066. if coltype in (
  3067. MSBinary,
  3068. MSVarBinary,
  3069. sqltypes.LargeBinary,
  3070. ):
  3071. kwargs["length"] = maxlen if maxlen != -1 else None
  3072. elif coltype in (
  3073. MSString,
  3074. MSChar,
  3075. MSText,
  3076. ):
  3077. kwargs["length"] = maxlen if maxlen != -1 else None
  3078. if collation:
  3079. kwargs["collation"] = collation
  3080. elif coltype in (
  3081. MSNVarchar,
  3082. MSNChar,
  3083. MSNText,
  3084. ):
  3085. kwargs["length"] = maxlen // 2 if maxlen != -1 else None
  3086. if collation:
  3087. kwargs["collation"] = collation
  3088. if coltype is None:
  3089. util.warn(
  3090. "Did not recognize type '%s' of column '%s'"
  3091. % (type_, name)
  3092. )
  3093. coltype = sqltypes.NULLTYPE
  3094. else:
  3095. if issubclass(coltype, sqltypes.Numeric):
  3096. kwargs["precision"] = numericprec
  3097. if not issubclass(coltype, sqltypes.Float):
  3098. kwargs["scale"] = numericscale
  3099. coltype = coltype(**kwargs)
  3100. cdict = {
  3101. "name": name,
  3102. "type": coltype,
  3103. "nullable": nullable,
  3104. "default": default,
  3105. "autoincrement": is_identity is not None,
  3106. "comment": comment,
  3107. }
  3108. if definition is not None and is_persisted is not None:
  3109. cdict["computed"] = {
  3110. "sqltext": definition,
  3111. "persisted": is_persisted,
  3112. }
  3113. if is_identity is not None:
  3114. # identity_start and identity_increment are Decimal or None
  3115. if identity_start is None or identity_increment is None:
  3116. cdict["identity"] = {}
  3117. else:
  3118. if isinstance(coltype, sqltypes.BigInteger):
  3119. start = int(identity_start)
  3120. increment = int(identity_increment)
  3121. elif isinstance(coltype, sqltypes.Integer):
  3122. start = int(identity_start)
  3123. increment = int(identity_increment)
  3124. else:
  3125. start = identity_start
  3126. increment = identity_increment
  3127. cdict["identity"] = {
  3128. "start": start,
  3129. "increment": increment,
  3130. }
  3131. cols.append(cdict)
  3132. if cols:
  3133. return cols
  3134. else:
  3135. return self._default_or_error(
  3136. connection, tablename, owner, ReflectionDefaults.columns, **kw
  3137. )
  3138. @reflection.cache
  3139. @_db_plus_owner
  3140. def get_pk_constraint(
  3141. self, connection, tablename, dbname, owner, schema, **kw
  3142. ):
  3143. pkeys = []
  3144. TC = ischema.constraints
  3145. C = ischema.key_constraints.alias("C")
  3146. # Primary key constraints
  3147. s = (
  3148. sql.select(
  3149. C.c.column_name,
  3150. TC.c.constraint_type,
  3151. C.c.constraint_name,
  3152. func.objectproperty(
  3153. func.object_id(
  3154. C.c.table_schema + "." + C.c.constraint_name
  3155. ),
  3156. "CnstIsClustKey",
  3157. ).label("is_clustered"),
  3158. )
  3159. .where(
  3160. sql.and_(
  3161. TC.c.constraint_name == C.c.constraint_name,
  3162. TC.c.table_schema == C.c.table_schema,
  3163. C.c.table_name == tablename,
  3164. C.c.table_schema == owner,
  3165. ),
  3166. )
  3167. .order_by(TC.c.constraint_name, C.c.ordinal_position)
  3168. )
  3169. c = connection.execution_options(future_result=True).execute(s)
  3170. constraint_name = None
  3171. is_clustered = None
  3172. for row in c.mappings():
  3173. if "PRIMARY" in row[TC.c.constraint_type.name]:
  3174. pkeys.append(row["COLUMN_NAME"])
  3175. if constraint_name is None:
  3176. constraint_name = row[C.c.constraint_name.name]
  3177. if is_clustered is None:
  3178. is_clustered = row["is_clustered"]
  3179. if pkeys:
  3180. return {
  3181. "constrained_columns": pkeys,
  3182. "name": constraint_name,
  3183. "dialect_options": {"mssql_clustered": is_clustered},
  3184. }
  3185. else:
  3186. return self._default_or_error(
  3187. connection,
  3188. tablename,
  3189. owner,
  3190. ReflectionDefaults.pk_constraint,
  3191. **kw,
  3192. )
  3193. @reflection.cache
  3194. @_db_plus_owner
  3195. def get_foreign_keys(
  3196. self, connection, tablename, dbname, owner, schema, **kw
  3197. ):
  3198. # Foreign key constraints
  3199. s = (
  3200. text(
  3201. """\
  3202. WITH fk_info AS (
  3203. SELECT
  3204. ischema_ref_con.constraint_schema,
  3205. ischema_ref_con.constraint_name,
  3206. ischema_key_col.ordinal_position,
  3207. ischema_key_col.table_schema,
  3208. ischema_key_col.table_name,
  3209. ischema_ref_con.unique_constraint_schema,
  3210. ischema_ref_con.unique_constraint_name,
  3211. ischema_ref_con.match_option,
  3212. ischema_ref_con.update_rule,
  3213. ischema_ref_con.delete_rule,
  3214. ischema_key_col.column_name AS constrained_column
  3215. FROM
  3216. INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ischema_ref_con
  3217. INNER JOIN
  3218. INFORMATION_SCHEMA.KEY_COLUMN_USAGE ischema_key_col ON
  3219. ischema_key_col.table_schema = ischema_ref_con.constraint_schema
  3220. AND ischema_key_col.constraint_name =
  3221. ischema_ref_con.constraint_name
  3222. WHERE ischema_key_col.table_name = :tablename
  3223. AND ischema_key_col.table_schema = :owner
  3224. ),
  3225. constraint_info AS (
  3226. SELECT
  3227. ischema_key_col.constraint_schema,
  3228. ischema_key_col.constraint_name,
  3229. ischema_key_col.ordinal_position,
  3230. ischema_key_col.table_schema,
  3231. ischema_key_col.table_name,
  3232. ischema_key_col.column_name
  3233. FROM
  3234. INFORMATION_SCHEMA.KEY_COLUMN_USAGE ischema_key_col
  3235. ),
  3236. index_info AS (
  3237. SELECT
  3238. sys.schemas.name AS index_schema,
  3239. sys.indexes.name AS index_name,
  3240. sys.index_columns.key_ordinal AS ordinal_position,
  3241. sys.schemas.name AS table_schema,
  3242. sys.objects.name AS table_name,
  3243. sys.columns.name AS column_name
  3244. FROM
  3245. sys.indexes
  3246. INNER JOIN
  3247. sys.objects ON
  3248. sys.objects.object_id = sys.indexes.object_id
  3249. INNER JOIN
  3250. sys.schemas ON
  3251. sys.schemas.schema_id = sys.objects.schema_id
  3252. INNER JOIN
  3253. sys.index_columns ON
  3254. sys.index_columns.object_id = sys.objects.object_id
  3255. AND sys.index_columns.index_id = sys.indexes.index_id
  3256. INNER JOIN
  3257. sys.columns ON
  3258. sys.columns.object_id = sys.indexes.object_id
  3259. AND sys.columns.column_id = sys.index_columns.column_id
  3260. )
  3261. SELECT
  3262. fk_info.constraint_schema,
  3263. fk_info.constraint_name,
  3264. fk_info.ordinal_position,
  3265. fk_info.constrained_column,
  3266. constraint_info.table_schema AS referred_table_schema,
  3267. constraint_info.table_name AS referred_table_name,
  3268. constraint_info.column_name AS referred_column,
  3269. fk_info.match_option,
  3270. fk_info.update_rule,
  3271. fk_info.delete_rule
  3272. FROM
  3273. fk_info INNER JOIN constraint_info ON
  3274. constraint_info.constraint_schema =
  3275. fk_info.unique_constraint_schema
  3276. AND constraint_info.constraint_name =
  3277. fk_info.unique_constraint_name
  3278. AND constraint_info.ordinal_position = fk_info.ordinal_position
  3279. UNION
  3280. SELECT
  3281. fk_info.constraint_schema,
  3282. fk_info.constraint_name,
  3283. fk_info.ordinal_position,
  3284. fk_info.constrained_column,
  3285. index_info.table_schema AS referred_table_schema,
  3286. index_info.table_name AS referred_table_name,
  3287. index_info.column_name AS referred_column,
  3288. fk_info.match_option,
  3289. fk_info.update_rule,
  3290. fk_info.delete_rule
  3291. FROM
  3292. fk_info INNER JOIN index_info ON
  3293. index_info.index_schema = fk_info.unique_constraint_schema
  3294. AND index_info.index_name = fk_info.unique_constraint_name
  3295. AND index_info.ordinal_position = fk_info.ordinal_position
  3296. AND NOT (index_info.table_schema = fk_info.table_schema
  3297. AND index_info.table_name = fk_info.table_name)
  3298. ORDER BY fk_info.constraint_schema, fk_info.constraint_name,
  3299. fk_info.ordinal_position
  3300. """
  3301. )
  3302. .bindparams(
  3303. sql.bindparam("tablename", tablename, ischema.CoerceUnicode()),
  3304. sql.bindparam("owner", owner, ischema.CoerceUnicode()),
  3305. )
  3306. .columns(
  3307. constraint_schema=sqltypes.Unicode(),
  3308. constraint_name=sqltypes.Unicode(),
  3309. table_schema=sqltypes.Unicode(),
  3310. table_name=sqltypes.Unicode(),
  3311. constrained_column=sqltypes.Unicode(),
  3312. referred_table_schema=sqltypes.Unicode(),
  3313. referred_table_name=sqltypes.Unicode(),
  3314. referred_column=sqltypes.Unicode(),
  3315. )
  3316. )
  3317. # group rows by constraint ID, to handle multi-column FKs
  3318. fkeys = util.defaultdict(
  3319. lambda: {
  3320. "name": None,
  3321. "constrained_columns": [],
  3322. "referred_schema": None,
  3323. "referred_table": None,
  3324. "referred_columns": [],
  3325. "options": {},
  3326. }
  3327. )
  3328. for r in connection.execute(s).all():
  3329. (
  3330. _, # constraint schema
  3331. rfknm,
  3332. _, # ordinal position
  3333. scol,
  3334. rschema,
  3335. rtbl,
  3336. rcol,
  3337. # TODO: we support match=<keyword> for foreign keys so
  3338. # we can support this also, PG has match=FULL for example
  3339. # but this seems to not be a valid value for SQL Server
  3340. _, # match rule
  3341. fkuprule,
  3342. fkdelrule,
  3343. ) = r
  3344. rec = fkeys[rfknm]
  3345. rec["name"] = rfknm
  3346. if fkuprule != "NO ACTION":
  3347. rec["options"]["onupdate"] = fkuprule
  3348. if fkdelrule != "NO ACTION":
  3349. rec["options"]["ondelete"] = fkdelrule
  3350. if not rec["referred_table"]:
  3351. rec["referred_table"] = rtbl
  3352. if schema is not None or owner != rschema:
  3353. if dbname:
  3354. rschema = dbname + "." + rschema
  3355. rec["referred_schema"] = rschema
  3356. local_cols, remote_cols = (
  3357. rec["constrained_columns"],
  3358. rec["referred_columns"],
  3359. )
  3360. local_cols.append(scol)
  3361. remote_cols.append(rcol)
  3362. if fkeys:
  3363. return list(fkeys.values())
  3364. else:
  3365. return self._default_or_error(
  3366. connection,
  3367. tablename,
  3368. owner,
  3369. ReflectionDefaults.foreign_keys,
  3370. **kw,
  3371. )