base.py 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084
  1. # dialects/mssql/base.py
  2. # Copyright (C) 2005-2025 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 overload
  736. from typing import TYPE_CHECKING
  737. from uuid import UUID as _python_UUID
  738. from . import information_schema as ischema
  739. from .json import JSON
  740. from .json import JSONIndexType
  741. from .json import JSONPathType
  742. from ... import exc
  743. from ... import Identity
  744. from ... import schema as sa_schema
  745. from ... import Sequence
  746. from ... import sql
  747. from ... import text
  748. from ... import util
  749. from ...engine import cursor as _cursor
  750. from ...engine import default
  751. from ...engine import reflection
  752. from ...engine.reflection import ReflectionDefaults
  753. from ...sql import coercions
  754. from ...sql import compiler
  755. from ...sql import elements
  756. from ...sql import expression
  757. from ...sql import func
  758. from ...sql import quoted_name
  759. from ...sql import roles
  760. from ...sql import sqltypes
  761. from ...sql import try_cast as try_cast # noqa: F401
  762. from ...sql import util as sql_util
  763. from ...sql._typing import is_sql_compiler
  764. from ...sql.compiler import InsertmanyvaluesSentinelOpts
  765. from ...sql.elements import TryCast as TryCast # noqa: F401
  766. from ...types import BIGINT
  767. from ...types import BINARY
  768. from ...types import CHAR
  769. from ...types import DATE
  770. from ...types import DATETIME
  771. from ...types import DECIMAL
  772. from ...types import FLOAT
  773. from ...types import INTEGER
  774. from ...types import NCHAR
  775. from ...types import NUMERIC
  776. from ...types import NVARCHAR
  777. from ...types import SMALLINT
  778. from ...types import TEXT
  779. from ...types import VARCHAR
  780. from ...util import update_wrapper
  781. from ...util.typing import Literal
  782. if TYPE_CHECKING:
  783. from ...sql.dml import DMLState
  784. from ...sql.selectable import TableClause
  785. # https://sqlserverbuilds.blogspot.com/
  786. MS_2017_VERSION = (14,)
  787. MS_2016_VERSION = (13,)
  788. MS_2014_VERSION = (12,)
  789. MS_2012_VERSION = (11,)
  790. MS_2008_VERSION = (10,)
  791. MS_2005_VERSION = (9,)
  792. MS_2000_VERSION = (8,)
  793. RESERVED_WORDS = {
  794. "add",
  795. "all",
  796. "alter",
  797. "and",
  798. "any",
  799. "as",
  800. "asc",
  801. "authorization",
  802. "backup",
  803. "begin",
  804. "between",
  805. "break",
  806. "browse",
  807. "bulk",
  808. "by",
  809. "cascade",
  810. "case",
  811. "check",
  812. "checkpoint",
  813. "close",
  814. "clustered",
  815. "coalesce",
  816. "collate",
  817. "column",
  818. "commit",
  819. "compute",
  820. "constraint",
  821. "contains",
  822. "containstable",
  823. "continue",
  824. "convert",
  825. "create",
  826. "cross",
  827. "current",
  828. "current_date",
  829. "current_time",
  830. "current_timestamp",
  831. "current_user",
  832. "cursor",
  833. "database",
  834. "dbcc",
  835. "deallocate",
  836. "declare",
  837. "default",
  838. "delete",
  839. "deny",
  840. "desc",
  841. "disk",
  842. "distinct",
  843. "distributed",
  844. "double",
  845. "drop",
  846. "dump",
  847. "else",
  848. "end",
  849. "errlvl",
  850. "escape",
  851. "except",
  852. "exec",
  853. "execute",
  854. "exists",
  855. "exit",
  856. "external",
  857. "fetch",
  858. "file",
  859. "fillfactor",
  860. "for",
  861. "foreign",
  862. "freetext",
  863. "freetexttable",
  864. "from",
  865. "full",
  866. "function",
  867. "goto",
  868. "grant",
  869. "group",
  870. "having",
  871. "holdlock",
  872. "identity",
  873. "identity_insert",
  874. "identitycol",
  875. "if",
  876. "in",
  877. "index",
  878. "inner",
  879. "insert",
  880. "intersect",
  881. "into",
  882. "is",
  883. "join",
  884. "key",
  885. "kill",
  886. "left",
  887. "like",
  888. "lineno",
  889. "load",
  890. "merge",
  891. "national",
  892. "nocheck",
  893. "nonclustered",
  894. "not",
  895. "null",
  896. "nullif",
  897. "of",
  898. "off",
  899. "offsets",
  900. "on",
  901. "open",
  902. "opendatasource",
  903. "openquery",
  904. "openrowset",
  905. "openxml",
  906. "option",
  907. "or",
  908. "order",
  909. "outer",
  910. "over",
  911. "percent",
  912. "pivot",
  913. "plan",
  914. "precision",
  915. "primary",
  916. "print",
  917. "proc",
  918. "procedure",
  919. "public",
  920. "raiserror",
  921. "read",
  922. "readtext",
  923. "reconfigure",
  924. "references",
  925. "replication",
  926. "restore",
  927. "restrict",
  928. "return",
  929. "revert",
  930. "revoke",
  931. "right",
  932. "rollback",
  933. "rowcount",
  934. "rowguidcol",
  935. "rule",
  936. "save",
  937. "schema",
  938. "securityaudit",
  939. "select",
  940. "session_user",
  941. "set",
  942. "setuser",
  943. "shutdown",
  944. "some",
  945. "statistics",
  946. "system_user",
  947. "table",
  948. "tablesample",
  949. "textsize",
  950. "then",
  951. "to",
  952. "top",
  953. "tran",
  954. "transaction",
  955. "trigger",
  956. "truncate",
  957. "tsequal",
  958. "union",
  959. "unique",
  960. "unpivot",
  961. "update",
  962. "updatetext",
  963. "use",
  964. "user",
  965. "values",
  966. "varying",
  967. "view",
  968. "waitfor",
  969. "when",
  970. "where",
  971. "while",
  972. "with",
  973. "writetext",
  974. }
  975. class REAL(sqltypes.REAL):
  976. """the SQL Server REAL datatype."""
  977. def __init__(self, **kw):
  978. # REAL is a synonym for FLOAT(24) on SQL server.
  979. # it is only accepted as the word "REAL" in DDL, the numeric
  980. # precision value is not allowed to be present
  981. kw.setdefault("precision", 24)
  982. super().__init__(**kw)
  983. class DOUBLE_PRECISION(sqltypes.DOUBLE_PRECISION):
  984. """the SQL Server DOUBLE PRECISION datatype.
  985. .. versionadded:: 2.0.11
  986. """
  987. def __init__(self, **kw):
  988. # DOUBLE PRECISION is a synonym for FLOAT(53) on SQL server.
  989. # it is only accepted as the word "DOUBLE PRECISION" in DDL,
  990. # the numeric precision value is not allowed to be present
  991. kw.setdefault("precision", 53)
  992. super().__init__(**kw)
  993. class TINYINT(sqltypes.Integer):
  994. __visit_name__ = "TINYINT"
  995. # MSSQL DATE/TIME types have varied behavior, sometimes returning
  996. # strings. MSDate/TIME check for everything, and always
  997. # filter bind parameters into datetime objects (required by pyodbc,
  998. # not sure about other dialects).
  999. class _MSDate(sqltypes.Date):
  1000. def bind_processor(self, dialect):
  1001. def process(value):
  1002. if type(value) == datetime.date:
  1003. return datetime.datetime(value.year, value.month, value.day)
  1004. else:
  1005. return value
  1006. return process
  1007. _reg = re.compile(r"(\d+)-(\d+)-(\d+)")
  1008. def result_processor(self, dialect, coltype):
  1009. def process(value):
  1010. if isinstance(value, datetime.datetime):
  1011. return value.date()
  1012. elif isinstance(value, str):
  1013. m = self._reg.match(value)
  1014. if not m:
  1015. raise ValueError(
  1016. "could not parse %r as a date value" % (value,)
  1017. )
  1018. return datetime.date(*[int(x or 0) for x in m.groups()])
  1019. else:
  1020. return value
  1021. return process
  1022. class TIME(sqltypes.TIME):
  1023. def __init__(self, precision=None, **kwargs):
  1024. self.precision = precision
  1025. super().__init__()
  1026. __zero_date = datetime.date(1900, 1, 1)
  1027. def bind_processor(self, dialect):
  1028. def process(value):
  1029. if isinstance(value, datetime.datetime):
  1030. value = datetime.datetime.combine(
  1031. self.__zero_date, value.time()
  1032. )
  1033. elif isinstance(value, datetime.time):
  1034. """issue #5339
  1035. per: https://github.com/mkleehammer/pyodbc/wiki/Tips-and-Tricks-by-Database-Platform#time-columns
  1036. pass TIME value as string
  1037. """ # noqa
  1038. value = str(value)
  1039. return value
  1040. return process
  1041. _reg = re.compile(r"(\d+):(\d+):(\d+)(?:\.(\d{0,6}))?")
  1042. def result_processor(self, dialect, coltype):
  1043. def process(value):
  1044. if isinstance(value, datetime.datetime):
  1045. return value.time()
  1046. elif isinstance(value, str):
  1047. m = self._reg.match(value)
  1048. if not m:
  1049. raise ValueError(
  1050. "could not parse %r as a time value" % (value,)
  1051. )
  1052. return datetime.time(*[int(x or 0) for x in m.groups()])
  1053. else:
  1054. return value
  1055. return process
  1056. _MSTime = TIME
  1057. class _BASETIMEIMPL(TIME):
  1058. __visit_name__ = "_BASETIMEIMPL"
  1059. class _DateTimeBase:
  1060. def bind_processor(self, dialect):
  1061. def process(value):
  1062. if type(value) == datetime.date:
  1063. return datetime.datetime(value.year, value.month, value.day)
  1064. else:
  1065. return value
  1066. return process
  1067. class _MSDateTime(_DateTimeBase, sqltypes.DateTime):
  1068. pass
  1069. class SMALLDATETIME(_DateTimeBase, sqltypes.DateTime):
  1070. __visit_name__ = "SMALLDATETIME"
  1071. class DATETIME2(_DateTimeBase, sqltypes.DateTime):
  1072. __visit_name__ = "DATETIME2"
  1073. def __init__(self, precision=None, **kw):
  1074. super().__init__(**kw)
  1075. self.precision = precision
  1076. class DATETIMEOFFSET(_DateTimeBase, sqltypes.DateTime):
  1077. __visit_name__ = "DATETIMEOFFSET"
  1078. def __init__(self, precision=None, **kw):
  1079. super().__init__(**kw)
  1080. self.precision = precision
  1081. class _UnicodeLiteral:
  1082. def literal_processor(self, dialect):
  1083. def process(value):
  1084. value = value.replace("'", "''")
  1085. if dialect.identifier_preparer._double_percents:
  1086. value = value.replace("%", "%%")
  1087. return "N'%s'" % value
  1088. return process
  1089. class _MSUnicode(_UnicodeLiteral, sqltypes.Unicode):
  1090. pass
  1091. class _MSUnicodeText(_UnicodeLiteral, sqltypes.UnicodeText):
  1092. pass
  1093. class TIMESTAMP(sqltypes._Binary):
  1094. """Implement the SQL Server TIMESTAMP type.
  1095. Note this is **completely different** than the SQL Standard
  1096. TIMESTAMP type, which is not supported by SQL Server. It
  1097. is a read-only datatype that does not support INSERT of values.
  1098. .. versionadded:: 1.2
  1099. .. seealso::
  1100. :class:`_mssql.ROWVERSION`
  1101. """
  1102. __visit_name__ = "TIMESTAMP"
  1103. # expected by _Binary to be present
  1104. length = None
  1105. def __init__(self, convert_int=False):
  1106. """Construct a TIMESTAMP or ROWVERSION type.
  1107. :param convert_int: if True, binary integer values will
  1108. be converted to integers on read.
  1109. .. versionadded:: 1.2
  1110. """
  1111. self.convert_int = convert_int
  1112. def result_processor(self, dialect, coltype):
  1113. super_ = super().result_processor(dialect, coltype)
  1114. if self.convert_int:
  1115. def process(value):
  1116. if super_:
  1117. value = super_(value)
  1118. if value is not None:
  1119. # https://stackoverflow.com/a/30403242/34549
  1120. value = int(codecs.encode(value, "hex"), 16)
  1121. return value
  1122. return process
  1123. else:
  1124. return super_
  1125. class ROWVERSION(TIMESTAMP):
  1126. """Implement the SQL Server ROWVERSION type.
  1127. The ROWVERSION datatype is a SQL Server synonym for the TIMESTAMP
  1128. datatype, however current SQL Server documentation suggests using
  1129. ROWVERSION for new datatypes going forward.
  1130. The ROWVERSION datatype does **not** reflect (e.g. introspect) from the
  1131. database as itself; the returned datatype will be
  1132. :class:`_mssql.TIMESTAMP`.
  1133. This is a read-only datatype that does not support INSERT of values.
  1134. .. versionadded:: 1.2
  1135. .. seealso::
  1136. :class:`_mssql.TIMESTAMP`
  1137. """
  1138. __visit_name__ = "ROWVERSION"
  1139. class NTEXT(sqltypes.UnicodeText):
  1140. """MSSQL NTEXT type, for variable-length unicode text up to 2^30
  1141. characters."""
  1142. __visit_name__ = "NTEXT"
  1143. class VARBINARY(sqltypes.VARBINARY, sqltypes.LargeBinary):
  1144. """The MSSQL VARBINARY type.
  1145. This type adds additional features to the core :class:`_types.VARBINARY`
  1146. type, including "deprecate_large_types" mode where
  1147. either ``VARBINARY(max)`` or IMAGE is rendered, as well as the SQL
  1148. Server ``FILESTREAM`` option.
  1149. .. seealso::
  1150. :ref:`mssql_large_type_deprecation`
  1151. """
  1152. __visit_name__ = "VARBINARY"
  1153. def __init__(self, length=None, filestream=False):
  1154. """
  1155. Construct a VARBINARY type.
  1156. :param length: optional, a length for the column for use in
  1157. DDL statements, for those binary types that accept a length,
  1158. such as the MySQL BLOB type.
  1159. :param filestream=False: if True, renders the ``FILESTREAM`` keyword
  1160. in the table definition. In this case ``length`` must be ``None``
  1161. or ``'max'``.
  1162. .. versionadded:: 1.4.31
  1163. """
  1164. self.filestream = filestream
  1165. if self.filestream and length not in (None, "max"):
  1166. raise ValueError(
  1167. "length must be None or 'max' when setting filestream"
  1168. )
  1169. super().__init__(length=length)
  1170. class IMAGE(sqltypes.LargeBinary):
  1171. __visit_name__ = "IMAGE"
  1172. class XML(sqltypes.Text):
  1173. """MSSQL XML type.
  1174. This is a placeholder type for reflection purposes that does not include
  1175. any Python-side datatype support. It also does not currently support
  1176. additional arguments, such as "CONTENT", "DOCUMENT",
  1177. "xml_schema_collection".
  1178. """
  1179. __visit_name__ = "XML"
  1180. class BIT(sqltypes.Boolean):
  1181. """MSSQL BIT type.
  1182. Both pyodbc and pymssql return values from BIT columns as
  1183. Python <class 'bool'> so just subclass Boolean.
  1184. """
  1185. __visit_name__ = "BIT"
  1186. class MONEY(sqltypes.TypeEngine):
  1187. __visit_name__ = "MONEY"
  1188. class SMALLMONEY(sqltypes.TypeEngine):
  1189. __visit_name__ = "SMALLMONEY"
  1190. class MSUUid(sqltypes.Uuid):
  1191. def bind_processor(self, dialect):
  1192. if self.native_uuid:
  1193. # this is currently assuming pyodbc; might not work for
  1194. # some other mssql driver
  1195. return None
  1196. else:
  1197. if self.as_uuid:
  1198. def process(value):
  1199. if value is not None:
  1200. value = value.hex
  1201. return value
  1202. return process
  1203. else:
  1204. def process(value):
  1205. if value is not None:
  1206. value = value.replace("-", "").replace("''", "'")
  1207. return value
  1208. return process
  1209. def literal_processor(self, dialect):
  1210. if self.native_uuid:
  1211. def process(value):
  1212. return f"""'{str(value).replace("''", "'")}'"""
  1213. return process
  1214. else:
  1215. if self.as_uuid:
  1216. def process(value):
  1217. return f"""'{value.hex}'"""
  1218. return process
  1219. else:
  1220. def process(value):
  1221. return f"""'{
  1222. value.replace("-", "").replace("'", "''")
  1223. }'"""
  1224. return process
  1225. class UNIQUEIDENTIFIER(sqltypes.Uuid[sqltypes._UUID_RETURN]):
  1226. __visit_name__ = "UNIQUEIDENTIFIER"
  1227. @overload
  1228. def __init__(
  1229. self: UNIQUEIDENTIFIER[_python_UUID], as_uuid: Literal[True] = ...
  1230. ): ...
  1231. @overload
  1232. def __init__(
  1233. self: UNIQUEIDENTIFIER[str], as_uuid: Literal[False] = ...
  1234. ): ...
  1235. def __init__(self, as_uuid: bool = True):
  1236. """Construct a :class:`_mssql.UNIQUEIDENTIFIER` type.
  1237. :param as_uuid=True: if True, values will be interpreted
  1238. as Python uuid objects, converting to/from string via the
  1239. DBAPI.
  1240. .. versionchanged: 2.0 Added direct "uuid" support to the
  1241. :class:`_mssql.UNIQUEIDENTIFIER` datatype; uuid interpretation
  1242. defaults to ``True``.
  1243. """
  1244. self.as_uuid = as_uuid
  1245. self.native_uuid = True
  1246. class SQL_VARIANT(sqltypes.TypeEngine):
  1247. __visit_name__ = "SQL_VARIANT"
  1248. # old names.
  1249. MSDateTime = _MSDateTime
  1250. MSDate = _MSDate
  1251. MSReal = REAL
  1252. MSTinyInteger = TINYINT
  1253. MSTime = TIME
  1254. MSSmallDateTime = SMALLDATETIME
  1255. MSDateTime2 = DATETIME2
  1256. MSDateTimeOffset = DATETIMEOFFSET
  1257. MSText = TEXT
  1258. MSNText = NTEXT
  1259. MSString = VARCHAR
  1260. MSNVarchar = NVARCHAR
  1261. MSChar = CHAR
  1262. MSNChar = NCHAR
  1263. MSBinary = BINARY
  1264. MSVarBinary = VARBINARY
  1265. MSImage = IMAGE
  1266. MSBit = BIT
  1267. MSMoney = MONEY
  1268. MSSmallMoney = SMALLMONEY
  1269. MSUniqueIdentifier = UNIQUEIDENTIFIER
  1270. MSVariant = SQL_VARIANT
  1271. ischema_names = {
  1272. "int": INTEGER,
  1273. "bigint": BIGINT,
  1274. "smallint": SMALLINT,
  1275. "tinyint": TINYINT,
  1276. "varchar": VARCHAR,
  1277. "nvarchar": NVARCHAR,
  1278. "char": CHAR,
  1279. "nchar": NCHAR,
  1280. "text": TEXT,
  1281. "ntext": NTEXT,
  1282. "decimal": DECIMAL,
  1283. "numeric": NUMERIC,
  1284. "float": FLOAT,
  1285. "datetime": DATETIME,
  1286. "datetime2": DATETIME2,
  1287. "datetimeoffset": DATETIMEOFFSET,
  1288. "date": DATE,
  1289. "time": TIME,
  1290. "smalldatetime": SMALLDATETIME,
  1291. "binary": BINARY,
  1292. "varbinary": VARBINARY,
  1293. "bit": BIT,
  1294. "real": REAL,
  1295. "double precision": DOUBLE_PRECISION,
  1296. "image": IMAGE,
  1297. "xml": XML,
  1298. "timestamp": TIMESTAMP,
  1299. "money": MONEY,
  1300. "smallmoney": SMALLMONEY,
  1301. "uniqueidentifier": UNIQUEIDENTIFIER,
  1302. "sql_variant": SQL_VARIANT,
  1303. }
  1304. class MSTypeCompiler(compiler.GenericTypeCompiler):
  1305. def _extend(self, spec, type_, length=None):
  1306. """Extend a string-type declaration with standard SQL
  1307. COLLATE annotations.
  1308. """
  1309. if getattr(type_, "collation", None):
  1310. collation = "COLLATE %s" % type_.collation
  1311. else:
  1312. collation = None
  1313. if not length:
  1314. length = type_.length
  1315. if length:
  1316. spec = spec + "(%s)" % length
  1317. return " ".join([c for c in (spec, collation) if c is not None])
  1318. def visit_double(self, type_, **kw):
  1319. return self.visit_DOUBLE_PRECISION(type_, **kw)
  1320. def visit_FLOAT(self, type_, **kw):
  1321. precision = getattr(type_, "precision", None)
  1322. if precision is None:
  1323. return "FLOAT"
  1324. else:
  1325. return "FLOAT(%(precision)s)" % {"precision": precision}
  1326. def visit_TINYINT(self, type_, **kw):
  1327. return "TINYINT"
  1328. def visit_TIME(self, type_, **kw):
  1329. precision = getattr(type_, "precision", None)
  1330. if precision is not None:
  1331. return "TIME(%s)" % precision
  1332. else:
  1333. return "TIME"
  1334. def visit_TIMESTAMP(self, type_, **kw):
  1335. return "TIMESTAMP"
  1336. def visit_ROWVERSION(self, type_, **kw):
  1337. return "ROWVERSION"
  1338. def visit_datetime(self, type_, **kw):
  1339. if type_.timezone:
  1340. return self.visit_DATETIMEOFFSET(type_, **kw)
  1341. else:
  1342. return self.visit_DATETIME(type_, **kw)
  1343. def visit_DATETIMEOFFSET(self, type_, **kw):
  1344. precision = getattr(type_, "precision", None)
  1345. if precision is not None:
  1346. return "DATETIMEOFFSET(%s)" % type_.precision
  1347. else:
  1348. return "DATETIMEOFFSET"
  1349. def visit_DATETIME2(self, type_, **kw):
  1350. precision = getattr(type_, "precision", None)
  1351. if precision is not None:
  1352. return "DATETIME2(%s)" % precision
  1353. else:
  1354. return "DATETIME2"
  1355. def visit_SMALLDATETIME(self, type_, **kw):
  1356. return "SMALLDATETIME"
  1357. def visit_unicode(self, type_, **kw):
  1358. return self.visit_NVARCHAR(type_, **kw)
  1359. def visit_text(self, type_, **kw):
  1360. if self.dialect.deprecate_large_types:
  1361. return self.visit_VARCHAR(type_, **kw)
  1362. else:
  1363. return self.visit_TEXT(type_, **kw)
  1364. def visit_unicode_text(self, type_, **kw):
  1365. if self.dialect.deprecate_large_types:
  1366. return self.visit_NVARCHAR(type_, **kw)
  1367. else:
  1368. return self.visit_NTEXT(type_, **kw)
  1369. def visit_NTEXT(self, type_, **kw):
  1370. return self._extend("NTEXT", type_)
  1371. def visit_TEXT(self, type_, **kw):
  1372. return self._extend("TEXT", type_)
  1373. def visit_VARCHAR(self, type_, **kw):
  1374. return self._extend("VARCHAR", type_, length=type_.length or "max")
  1375. def visit_CHAR(self, type_, **kw):
  1376. return self._extend("CHAR", type_)
  1377. def visit_NCHAR(self, type_, **kw):
  1378. return self._extend("NCHAR", type_)
  1379. def visit_NVARCHAR(self, type_, **kw):
  1380. return self._extend("NVARCHAR", type_, length=type_.length or "max")
  1381. def visit_date(self, type_, **kw):
  1382. if self.dialect.server_version_info < MS_2008_VERSION:
  1383. return self.visit_DATETIME(type_, **kw)
  1384. else:
  1385. return self.visit_DATE(type_, **kw)
  1386. def visit__BASETIMEIMPL(self, type_, **kw):
  1387. return self.visit_time(type_, **kw)
  1388. def visit_time(self, type_, **kw):
  1389. if self.dialect.server_version_info < MS_2008_VERSION:
  1390. return self.visit_DATETIME(type_, **kw)
  1391. else:
  1392. return self.visit_TIME(type_, **kw)
  1393. def visit_large_binary(self, type_, **kw):
  1394. if self.dialect.deprecate_large_types:
  1395. return self.visit_VARBINARY(type_, **kw)
  1396. else:
  1397. return self.visit_IMAGE(type_, **kw)
  1398. def visit_IMAGE(self, type_, **kw):
  1399. return "IMAGE"
  1400. def visit_XML(self, type_, **kw):
  1401. return "XML"
  1402. def visit_VARBINARY(self, type_, **kw):
  1403. text = self._extend("VARBINARY", type_, length=type_.length or "max")
  1404. if getattr(type_, "filestream", False):
  1405. text += " FILESTREAM"
  1406. return text
  1407. def visit_boolean(self, type_, **kw):
  1408. return self.visit_BIT(type_)
  1409. def visit_BIT(self, type_, **kw):
  1410. return "BIT"
  1411. def visit_JSON(self, type_, **kw):
  1412. # this is a bit of a break with SQLAlchemy's convention of
  1413. # "UPPERCASE name goes to UPPERCASE type name with no modification"
  1414. return self._extend("NVARCHAR", type_, length="max")
  1415. def visit_MONEY(self, type_, **kw):
  1416. return "MONEY"
  1417. def visit_SMALLMONEY(self, type_, **kw):
  1418. return "SMALLMONEY"
  1419. def visit_uuid(self, type_, **kw):
  1420. if type_.native_uuid:
  1421. return self.visit_UNIQUEIDENTIFIER(type_, **kw)
  1422. else:
  1423. return super().visit_uuid(type_, **kw)
  1424. def visit_UNIQUEIDENTIFIER(self, type_, **kw):
  1425. return "UNIQUEIDENTIFIER"
  1426. def visit_SQL_VARIANT(self, type_, **kw):
  1427. return "SQL_VARIANT"
  1428. class MSExecutionContext(default.DefaultExecutionContext):
  1429. _enable_identity_insert = False
  1430. _select_lastrowid = False
  1431. _lastrowid = None
  1432. dialect: MSDialect
  1433. def _opt_encode(self, statement):
  1434. if self.compiled and self.compiled.schema_translate_map:
  1435. rst = self.compiled.preparer._render_schema_translates
  1436. statement = rst(statement, self.compiled.schema_translate_map)
  1437. return statement
  1438. def pre_exec(self):
  1439. """Activate IDENTITY_INSERT if needed."""
  1440. if self.isinsert:
  1441. if TYPE_CHECKING:
  1442. assert is_sql_compiler(self.compiled)
  1443. assert isinstance(self.compiled.compile_state, DMLState)
  1444. assert isinstance(
  1445. self.compiled.compile_state.dml_table, TableClause
  1446. )
  1447. tbl = self.compiled.compile_state.dml_table
  1448. id_column = tbl._autoincrement_column
  1449. if id_column is not None and (
  1450. not isinstance(id_column.default, Sequence)
  1451. ):
  1452. insert_has_identity = True
  1453. compile_state = self.compiled.dml_compile_state
  1454. self._enable_identity_insert = (
  1455. id_column.key in self.compiled_parameters[0]
  1456. ) or (
  1457. compile_state._dict_parameters
  1458. and (id_column.key in compile_state._insert_col_keys)
  1459. )
  1460. else:
  1461. insert_has_identity = False
  1462. self._enable_identity_insert = False
  1463. self._select_lastrowid = (
  1464. not self.compiled.inline
  1465. and insert_has_identity
  1466. and not self.compiled.effective_returning
  1467. and not self._enable_identity_insert
  1468. and not self.executemany
  1469. )
  1470. if self._enable_identity_insert:
  1471. self.root_connection._cursor_execute(
  1472. self.cursor,
  1473. self._opt_encode(
  1474. "SET IDENTITY_INSERT %s ON"
  1475. % self.identifier_preparer.format_table(tbl)
  1476. ),
  1477. (),
  1478. self,
  1479. )
  1480. def post_exec(self):
  1481. """Disable IDENTITY_INSERT if enabled."""
  1482. conn = self.root_connection
  1483. if self.isinsert or self.isupdate or self.isdelete:
  1484. self._rowcount = self.cursor.rowcount
  1485. if self._select_lastrowid:
  1486. if self.dialect.use_scope_identity:
  1487. conn._cursor_execute(
  1488. self.cursor,
  1489. "SELECT scope_identity() AS lastrowid",
  1490. (),
  1491. self,
  1492. )
  1493. else:
  1494. conn._cursor_execute(
  1495. self.cursor, "SELECT @@identity AS lastrowid", (), self
  1496. )
  1497. # fetchall() ensures the cursor is consumed without closing it
  1498. row = self.cursor.fetchall()[0]
  1499. self._lastrowid = int(row[0])
  1500. self.cursor_fetch_strategy = _cursor._NO_CURSOR_DML
  1501. elif (
  1502. self.compiled is not None
  1503. and is_sql_compiler(self.compiled)
  1504. and self.compiled.effective_returning
  1505. ):
  1506. self.cursor_fetch_strategy = (
  1507. _cursor.FullyBufferedCursorFetchStrategy(
  1508. self.cursor,
  1509. self.cursor.description,
  1510. self.cursor.fetchall(),
  1511. )
  1512. )
  1513. if self._enable_identity_insert:
  1514. if TYPE_CHECKING:
  1515. assert is_sql_compiler(self.compiled)
  1516. assert isinstance(self.compiled.compile_state, DMLState)
  1517. assert isinstance(
  1518. self.compiled.compile_state.dml_table, TableClause
  1519. )
  1520. conn._cursor_execute(
  1521. self.cursor,
  1522. self._opt_encode(
  1523. "SET IDENTITY_INSERT %s OFF"
  1524. % self.identifier_preparer.format_table(
  1525. self.compiled.compile_state.dml_table
  1526. )
  1527. ),
  1528. (),
  1529. self,
  1530. )
  1531. def get_lastrowid(self):
  1532. return self._lastrowid
  1533. def handle_dbapi_exception(self, e):
  1534. if self._enable_identity_insert:
  1535. try:
  1536. self.cursor.execute(
  1537. self._opt_encode(
  1538. "SET IDENTITY_INSERT %s OFF"
  1539. % self.identifier_preparer.format_table(
  1540. self.compiled.compile_state.dml_table
  1541. )
  1542. )
  1543. )
  1544. except Exception:
  1545. pass
  1546. def fire_sequence(self, seq, type_):
  1547. return self._execute_scalar(
  1548. (
  1549. "SELECT NEXT VALUE FOR %s"
  1550. % self.identifier_preparer.format_sequence(seq)
  1551. ),
  1552. type_,
  1553. )
  1554. def get_insert_default(self, column):
  1555. if (
  1556. isinstance(column, sa_schema.Column)
  1557. and column is column.table._autoincrement_column
  1558. and isinstance(column.default, sa_schema.Sequence)
  1559. and column.default.optional
  1560. ):
  1561. return None
  1562. return super().get_insert_default(column)
  1563. class MSSQLCompiler(compiler.SQLCompiler):
  1564. returning_precedes_values = True
  1565. extract_map = util.update_copy(
  1566. compiler.SQLCompiler.extract_map,
  1567. {
  1568. "doy": "dayofyear",
  1569. "dow": "weekday",
  1570. "milliseconds": "millisecond",
  1571. "microseconds": "microsecond",
  1572. },
  1573. )
  1574. def __init__(self, *args, **kwargs):
  1575. self.tablealiases = {}
  1576. super().__init__(*args, **kwargs)
  1577. def _format_frame_clause(self, range_, **kw):
  1578. kw["literal_execute"] = True
  1579. return super()._format_frame_clause(range_, **kw)
  1580. def _with_legacy_schema_aliasing(fn):
  1581. def decorate(self, *arg, **kw):
  1582. if self.dialect.legacy_schema_aliasing:
  1583. return fn(self, *arg, **kw)
  1584. else:
  1585. super_ = getattr(super(MSSQLCompiler, self), fn.__name__)
  1586. return super_(*arg, **kw)
  1587. return decorate
  1588. def visit_now_func(self, fn, **kw):
  1589. return "CURRENT_TIMESTAMP"
  1590. def visit_current_date_func(self, fn, **kw):
  1591. return "GETDATE()"
  1592. def visit_length_func(self, fn, **kw):
  1593. return "LEN%s" % self.function_argspec(fn, **kw)
  1594. def visit_char_length_func(self, fn, **kw):
  1595. return "LEN%s" % self.function_argspec(fn, **kw)
  1596. def visit_aggregate_strings_func(self, fn, **kw):
  1597. expr = fn.clauses.clauses[0]._compiler_dispatch(self, **kw)
  1598. kw["literal_execute"] = True
  1599. delimeter = fn.clauses.clauses[1]._compiler_dispatch(self, **kw)
  1600. return f"string_agg({expr}, {delimeter})"
  1601. def visit_concat_op_expression_clauselist(
  1602. self, clauselist, operator, **kw
  1603. ):
  1604. return " + ".join(self.process(elem, **kw) for elem in clauselist)
  1605. def visit_concat_op_binary(self, binary, operator, **kw):
  1606. return "%s + %s" % (
  1607. self.process(binary.left, **kw),
  1608. self.process(binary.right, **kw),
  1609. )
  1610. def visit_true(self, expr, **kw):
  1611. return "1"
  1612. def visit_false(self, expr, **kw):
  1613. return "0"
  1614. def visit_match_op_binary(self, binary, operator, **kw):
  1615. return "CONTAINS (%s, %s)" % (
  1616. self.process(binary.left, **kw),
  1617. self.process(binary.right, **kw),
  1618. )
  1619. def get_select_precolumns(self, select, **kw):
  1620. """MS-SQL puts TOP, it's version of LIMIT here"""
  1621. s = super().get_select_precolumns(select, **kw)
  1622. if select._has_row_limiting_clause and self._use_top(select):
  1623. # ODBC drivers and possibly others
  1624. # don't support bind params in the SELECT clause on SQL Server.
  1625. # so have to use literal here.
  1626. kw["literal_execute"] = True
  1627. s += "TOP %s " % self.process(
  1628. self._get_limit_or_fetch(select), **kw
  1629. )
  1630. if select._fetch_clause is not None:
  1631. if select._fetch_clause_options["percent"]:
  1632. s += "PERCENT "
  1633. if select._fetch_clause_options["with_ties"]:
  1634. s += "WITH TIES "
  1635. return s
  1636. def get_from_hint_text(self, table, text):
  1637. return text
  1638. def get_crud_hint_text(self, table, text):
  1639. return text
  1640. def _get_limit_or_fetch(self, select):
  1641. if select._fetch_clause is None:
  1642. return select._limit_clause
  1643. else:
  1644. return select._fetch_clause
  1645. def _use_top(self, select):
  1646. return (select._offset_clause is None) and (
  1647. select._simple_int_clause(select._limit_clause)
  1648. or (
  1649. # limit can use TOP with is by itself. fetch only uses TOP
  1650. # when it needs to because of PERCENT and/or WITH TIES
  1651. # TODO: Why? shouldn't we use TOP always ?
  1652. select._simple_int_clause(select._fetch_clause)
  1653. and (
  1654. select._fetch_clause_options["percent"]
  1655. or select._fetch_clause_options["with_ties"]
  1656. )
  1657. )
  1658. )
  1659. def limit_clause(self, cs, **kwargs):
  1660. return ""
  1661. def _check_can_use_fetch_limit(self, select):
  1662. # to use ROW_NUMBER(), an ORDER BY is required.
  1663. # OFFSET are FETCH are options of the ORDER BY clause
  1664. if not select._order_by_clause.clauses:
  1665. raise exc.CompileError(
  1666. "MSSQL requires an order_by when "
  1667. "using an OFFSET or a non-simple "
  1668. "LIMIT clause"
  1669. )
  1670. if select._fetch_clause_options is not None and (
  1671. select._fetch_clause_options["percent"]
  1672. or select._fetch_clause_options["with_ties"]
  1673. ):
  1674. raise exc.CompileError(
  1675. "MSSQL needs TOP to use PERCENT and/or WITH TIES. "
  1676. "Only simple fetch without offset can be used."
  1677. )
  1678. def _row_limit_clause(self, select, **kw):
  1679. """MSSQL 2012 supports OFFSET/FETCH operators
  1680. Use it instead subquery with row_number
  1681. """
  1682. if self.dialect._supports_offset_fetch and not self._use_top(select):
  1683. self._check_can_use_fetch_limit(select)
  1684. return self.fetch_clause(
  1685. select,
  1686. fetch_clause=self._get_limit_or_fetch(select),
  1687. require_offset=True,
  1688. **kw,
  1689. )
  1690. else:
  1691. return ""
  1692. def visit_try_cast(self, element, **kw):
  1693. return "TRY_CAST (%s AS %s)" % (
  1694. self.process(element.clause, **kw),
  1695. self.process(element.typeclause, **kw),
  1696. )
  1697. def translate_select_structure(self, select_stmt, **kwargs):
  1698. """Look for ``LIMIT`` and OFFSET in a select statement, and if
  1699. so tries to wrap it in a subquery with ``row_number()`` criterion.
  1700. MSSQL 2012 and above are excluded
  1701. """
  1702. select = select_stmt
  1703. if (
  1704. select._has_row_limiting_clause
  1705. and not self.dialect._supports_offset_fetch
  1706. and not self._use_top(select)
  1707. and not getattr(select, "_mssql_visit", None)
  1708. ):
  1709. self._check_can_use_fetch_limit(select)
  1710. _order_by_clauses = [
  1711. sql_util.unwrap_label_reference(elem)
  1712. for elem in select._order_by_clause.clauses
  1713. ]
  1714. limit_clause = self._get_limit_or_fetch(select)
  1715. offset_clause = select._offset_clause
  1716. select = select._generate()
  1717. select._mssql_visit = True
  1718. select = (
  1719. select.add_columns(
  1720. sql.func.ROW_NUMBER()
  1721. .over(order_by=_order_by_clauses)
  1722. .label("mssql_rn")
  1723. )
  1724. .order_by(None)
  1725. .alias()
  1726. )
  1727. mssql_rn = sql.column("mssql_rn")
  1728. limitselect = sql.select(
  1729. *[c for c in select.c if c.key != "mssql_rn"]
  1730. )
  1731. if offset_clause is not None:
  1732. limitselect = limitselect.where(mssql_rn > offset_clause)
  1733. if limit_clause is not None:
  1734. limitselect = limitselect.where(
  1735. mssql_rn <= (limit_clause + offset_clause)
  1736. )
  1737. else:
  1738. limitselect = limitselect.where(mssql_rn <= (limit_clause))
  1739. return limitselect
  1740. else:
  1741. return select
  1742. @_with_legacy_schema_aliasing
  1743. def visit_table(self, table, mssql_aliased=False, iscrud=False, **kwargs):
  1744. if mssql_aliased is table or iscrud:
  1745. return super().visit_table(table, **kwargs)
  1746. # alias schema-qualified tables
  1747. alias = self._schema_aliased_table(table)
  1748. if alias is not None:
  1749. return self.process(alias, mssql_aliased=table, **kwargs)
  1750. else:
  1751. return super().visit_table(table, **kwargs)
  1752. @_with_legacy_schema_aliasing
  1753. def visit_alias(self, alias, **kw):
  1754. # translate for schema-qualified table aliases
  1755. kw["mssql_aliased"] = alias.element
  1756. return super().visit_alias(alias, **kw)
  1757. @_with_legacy_schema_aliasing
  1758. def visit_column(self, column, add_to_result_map=None, **kw):
  1759. if (
  1760. column.table is not None
  1761. and (not self.isupdate and not self.isdelete)
  1762. or self.is_subquery()
  1763. ):
  1764. # translate for schema-qualified table aliases
  1765. t = self._schema_aliased_table(column.table)
  1766. if t is not None:
  1767. converted = elements._corresponding_column_or_error(t, column)
  1768. if add_to_result_map is not None:
  1769. add_to_result_map(
  1770. column.name,
  1771. column.name,
  1772. (column, column.name, column.key),
  1773. column.type,
  1774. )
  1775. return super().visit_column(converted, **kw)
  1776. return super().visit_column(
  1777. column, add_to_result_map=add_to_result_map, **kw
  1778. )
  1779. def _schema_aliased_table(self, table):
  1780. if getattr(table, "schema", None) is not None:
  1781. if table not in self.tablealiases:
  1782. self.tablealiases[table] = table.alias()
  1783. return self.tablealiases[table]
  1784. else:
  1785. return None
  1786. def visit_extract(self, extract, **kw):
  1787. field = self.extract_map.get(extract.field, extract.field)
  1788. return "DATEPART(%s, %s)" % (field, self.process(extract.expr, **kw))
  1789. def visit_savepoint(self, savepoint_stmt, **kw):
  1790. return "SAVE TRANSACTION %s" % self.preparer.format_savepoint(
  1791. savepoint_stmt
  1792. )
  1793. def visit_rollback_to_savepoint(self, savepoint_stmt, **kw):
  1794. return "ROLLBACK TRANSACTION %s" % self.preparer.format_savepoint(
  1795. savepoint_stmt
  1796. )
  1797. def visit_binary(self, binary, **kwargs):
  1798. """Move bind parameters to the right-hand side of an operator, where
  1799. possible.
  1800. """
  1801. if (
  1802. isinstance(binary.left, expression.BindParameter)
  1803. and binary.operator == operator.eq
  1804. and not isinstance(binary.right, expression.BindParameter)
  1805. ):
  1806. return self.process(
  1807. expression.BinaryExpression(
  1808. binary.right, binary.left, binary.operator
  1809. ),
  1810. **kwargs,
  1811. )
  1812. return super().visit_binary(binary, **kwargs)
  1813. def returning_clause(
  1814. self, stmt, returning_cols, *, populate_result_map, **kw
  1815. ):
  1816. # SQL server returning clause requires that the columns refer to
  1817. # the virtual table names "inserted" or "deleted". Here, we make
  1818. # a simple alias of our table with that name, and then adapt the
  1819. # columns we have from the list of RETURNING columns to that new name
  1820. # so that they render as "inserted.<colname>" / "deleted.<colname>".
  1821. if stmt.is_insert or stmt.is_update:
  1822. target = stmt.table.alias("inserted")
  1823. elif stmt.is_delete:
  1824. target = stmt.table.alias("deleted")
  1825. else:
  1826. assert False, "expected Insert, Update or Delete statement"
  1827. adapter = sql_util.ClauseAdapter(target)
  1828. # adapter.traverse() takes a column from our target table and returns
  1829. # the one that is linked to the "inserted" / "deleted" tables. So in
  1830. # order to retrieve these values back from the result (e.g. like
  1831. # row[column]), tell the compiler to also add the original unadapted
  1832. # column to the result map. Before #4877, these were (unknowingly)
  1833. # falling back using string name matching in the result set which
  1834. # necessarily used an expensive KeyError in order to match.
  1835. columns = [
  1836. self._label_returning_column(
  1837. stmt,
  1838. adapter.traverse(column),
  1839. populate_result_map,
  1840. {"result_map_targets": (column,)},
  1841. fallback_label_name=fallback_label_name,
  1842. column_is_repeated=repeated,
  1843. name=name,
  1844. proxy_name=proxy_name,
  1845. **kw,
  1846. )
  1847. for (
  1848. name,
  1849. proxy_name,
  1850. fallback_label_name,
  1851. column,
  1852. repeated,
  1853. ) in stmt._generate_columns_plus_names(
  1854. True, cols=expression._select_iterables(returning_cols)
  1855. )
  1856. ]
  1857. return "OUTPUT " + ", ".join(columns)
  1858. def get_cte_preamble(self, recursive):
  1859. # SQL Server finds it too inconvenient to accept
  1860. # an entirely optional, SQL standard specified,
  1861. # "RECURSIVE" word with their "WITH",
  1862. # so here we go
  1863. return "WITH"
  1864. def label_select_column(self, select, column, asfrom):
  1865. if isinstance(column, expression.Function):
  1866. return column.label(None)
  1867. else:
  1868. return super().label_select_column(select, column, asfrom)
  1869. def for_update_clause(self, select, **kw):
  1870. # "FOR UPDATE" is only allowed on "DECLARE CURSOR" which
  1871. # SQLAlchemy doesn't use
  1872. return ""
  1873. def order_by_clause(self, select, **kw):
  1874. # MSSQL only allows ORDER BY in subqueries if there is a LIMIT:
  1875. # "The ORDER BY clause is invalid in views, inline functions,
  1876. # derived tables, subqueries, and common table expressions,
  1877. # unless TOP, OFFSET or FOR XML is also specified."
  1878. if (
  1879. self.is_subquery()
  1880. and not self._use_top(select)
  1881. and (
  1882. select._offset is None
  1883. or not self.dialect._supports_offset_fetch
  1884. )
  1885. ):
  1886. # avoid processing the order by clause if we won't end up
  1887. # using it, because we don't want all the bind params tacked
  1888. # onto the positional list if that is what the dbapi requires
  1889. return ""
  1890. order_by = self.process(select._order_by_clause, **kw)
  1891. if order_by:
  1892. return " ORDER BY " + order_by
  1893. else:
  1894. return ""
  1895. def update_from_clause(
  1896. self, update_stmt, from_table, extra_froms, from_hints, **kw
  1897. ):
  1898. """Render the UPDATE..FROM clause specific to MSSQL.
  1899. In MSSQL, if the UPDATE statement involves an alias of the table to
  1900. be updated, then the table itself must be added to the FROM list as
  1901. well. Otherwise, it is optional. Here, we add it regardless.
  1902. """
  1903. return "FROM " + ", ".join(
  1904. t._compiler_dispatch(self, asfrom=True, fromhints=from_hints, **kw)
  1905. for t in [from_table] + extra_froms
  1906. )
  1907. def delete_table_clause(self, delete_stmt, from_table, extra_froms, **kw):
  1908. """If we have extra froms make sure we render any alias as hint."""
  1909. ashint = False
  1910. if extra_froms:
  1911. ashint = True
  1912. return from_table._compiler_dispatch(
  1913. self, asfrom=True, iscrud=True, ashint=ashint, **kw
  1914. )
  1915. def delete_extra_from_clause(
  1916. self, delete_stmt, from_table, extra_froms, from_hints, **kw
  1917. ):
  1918. """Render the DELETE .. FROM clause specific to MSSQL.
  1919. Yes, it has the FROM keyword twice.
  1920. """
  1921. return "FROM " + ", ".join(
  1922. t._compiler_dispatch(self, asfrom=True, fromhints=from_hints, **kw)
  1923. for t in [from_table] + extra_froms
  1924. )
  1925. def visit_empty_set_expr(self, type_, **kw):
  1926. return "SELECT 1 WHERE 1!=1"
  1927. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  1928. return "NOT EXISTS (SELECT %s INTERSECT SELECT %s)" % (
  1929. self.process(binary.left),
  1930. self.process(binary.right),
  1931. )
  1932. def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
  1933. return "EXISTS (SELECT %s INTERSECT SELECT %s)" % (
  1934. self.process(binary.left),
  1935. self.process(binary.right),
  1936. )
  1937. def _render_json_extract_from_binary(self, binary, operator, **kw):
  1938. # note we are intentionally calling upon the process() calls in the
  1939. # order in which they appear in the SQL String as this is used
  1940. # by positional parameter rendering
  1941. if binary.type._type_affinity is sqltypes.JSON:
  1942. return "JSON_QUERY(%s, %s)" % (
  1943. self.process(binary.left, **kw),
  1944. self.process(binary.right, **kw),
  1945. )
  1946. # as with other dialects, start with an explicit test for NULL
  1947. case_expression = "CASE JSON_VALUE(%s, %s) WHEN NULL THEN NULL" % (
  1948. self.process(binary.left, **kw),
  1949. self.process(binary.right, **kw),
  1950. )
  1951. if binary.type._type_affinity is sqltypes.Integer:
  1952. type_expression = "ELSE CAST(JSON_VALUE(%s, %s) AS INTEGER)" % (
  1953. self.process(binary.left, **kw),
  1954. self.process(binary.right, **kw),
  1955. )
  1956. elif binary.type._type_affinity is sqltypes.Numeric:
  1957. type_expression = "ELSE CAST(JSON_VALUE(%s, %s) AS %s)" % (
  1958. self.process(binary.left, **kw),
  1959. self.process(binary.right, **kw),
  1960. (
  1961. "FLOAT"
  1962. if isinstance(binary.type, sqltypes.Float)
  1963. else "NUMERIC(%s, %s)"
  1964. % (binary.type.precision, binary.type.scale)
  1965. ),
  1966. )
  1967. elif binary.type._type_affinity is sqltypes.Boolean:
  1968. # the NULL handling is particularly weird with boolean, so
  1969. # explicitly return numeric (BIT) constants
  1970. type_expression = (
  1971. "WHEN 'true' THEN 1 WHEN 'false' THEN 0 ELSE NULL"
  1972. )
  1973. elif binary.type._type_affinity is sqltypes.String:
  1974. # TODO: does this comment (from mysql) apply to here, too?
  1975. # this fails with a JSON value that's a four byte unicode
  1976. # string. SQLite has the same problem at the moment
  1977. type_expression = "ELSE JSON_VALUE(%s, %s)" % (
  1978. self.process(binary.left, **kw),
  1979. self.process(binary.right, **kw),
  1980. )
  1981. else:
  1982. # other affinity....this is not expected right now
  1983. type_expression = "ELSE JSON_QUERY(%s, %s)" % (
  1984. self.process(binary.left, **kw),
  1985. self.process(binary.right, **kw),
  1986. )
  1987. return case_expression + " " + type_expression + " END"
  1988. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  1989. return self._render_json_extract_from_binary(binary, operator, **kw)
  1990. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  1991. return self._render_json_extract_from_binary(binary, operator, **kw)
  1992. def visit_sequence(self, seq, **kw):
  1993. return "NEXT VALUE FOR %s" % self.preparer.format_sequence(seq)
  1994. class MSSQLStrictCompiler(MSSQLCompiler):
  1995. """A subclass of MSSQLCompiler which disables the usage of bind
  1996. parameters where not allowed natively by MS-SQL.
  1997. A dialect may use this compiler on a platform where native
  1998. binds are used.
  1999. """
  2000. ansi_bind_rules = True
  2001. def visit_in_op_binary(self, binary, operator, **kw):
  2002. kw["literal_execute"] = True
  2003. return "%s IN %s" % (
  2004. self.process(binary.left, **kw),
  2005. self.process(binary.right, **kw),
  2006. )
  2007. def visit_not_in_op_binary(self, binary, operator, **kw):
  2008. kw["literal_execute"] = True
  2009. return "%s NOT IN %s" % (
  2010. self.process(binary.left, **kw),
  2011. self.process(binary.right, **kw),
  2012. )
  2013. def render_literal_value(self, value, type_):
  2014. """
  2015. For date and datetime values, convert to a string
  2016. format acceptable to MSSQL. That seems to be the
  2017. so-called ODBC canonical date format which looks
  2018. like this:
  2019. yyyy-mm-dd hh:mi:ss.mmm(24h)
  2020. For other data types, call the base class implementation.
  2021. """
  2022. # datetime and date are both subclasses of datetime.date
  2023. if issubclass(type(value), datetime.date):
  2024. # SQL Server wants single quotes around the date string.
  2025. return "'" + str(value) + "'"
  2026. else:
  2027. return super().render_literal_value(value, type_)
  2028. class MSDDLCompiler(compiler.DDLCompiler):
  2029. def get_column_specification(self, column, **kwargs):
  2030. colspec = self.preparer.format_column(column)
  2031. # type is not accepted in a computed column
  2032. if column.computed is not None:
  2033. colspec += " " + self.process(column.computed)
  2034. else:
  2035. colspec += " " + self.dialect.type_compiler_instance.process(
  2036. column.type, type_expression=column
  2037. )
  2038. if column.nullable is not None:
  2039. if (
  2040. not column.nullable
  2041. or column.primary_key
  2042. or isinstance(column.default, sa_schema.Sequence)
  2043. or column.autoincrement is True
  2044. or column.identity
  2045. ):
  2046. colspec += " NOT NULL"
  2047. elif column.computed is None:
  2048. # don't specify "NULL" for computed columns
  2049. colspec += " NULL"
  2050. if column.table is None:
  2051. raise exc.CompileError(
  2052. "mssql requires Table-bound columns "
  2053. "in order to generate DDL"
  2054. )
  2055. d_opt = column.dialect_options["mssql"]
  2056. start = d_opt["identity_start"]
  2057. increment = d_opt["identity_increment"]
  2058. if start is not None or increment is not None:
  2059. if column.identity:
  2060. raise exc.CompileError(
  2061. "Cannot specify options 'mssql_identity_start' and/or "
  2062. "'mssql_identity_increment' while also using the "
  2063. "'Identity' construct."
  2064. )
  2065. util.warn_deprecated(
  2066. "The dialect options 'mssql_identity_start' and "
  2067. "'mssql_identity_increment' are deprecated. "
  2068. "Use the 'Identity' object instead.",
  2069. "1.4",
  2070. )
  2071. if column.identity:
  2072. colspec += self.process(column.identity, **kwargs)
  2073. elif (
  2074. column is column.table._autoincrement_column
  2075. or column.autoincrement is True
  2076. ) and (
  2077. not isinstance(column.default, Sequence) or column.default.optional
  2078. ):
  2079. colspec += self.process(Identity(start=start, increment=increment))
  2080. else:
  2081. default = self.get_column_default_string(column)
  2082. if default is not None:
  2083. colspec += " DEFAULT " + default
  2084. return colspec
  2085. def visit_create_index(self, create, include_schema=False, **kw):
  2086. index = create.element
  2087. self._verify_index_table(index)
  2088. preparer = self.preparer
  2089. text = "CREATE "
  2090. if index.unique:
  2091. text += "UNIQUE "
  2092. # handle clustering option
  2093. clustered = index.dialect_options["mssql"]["clustered"]
  2094. if clustered is not None:
  2095. if clustered:
  2096. text += "CLUSTERED "
  2097. else:
  2098. text += "NONCLUSTERED "
  2099. # handle columnstore option (has no negative value)
  2100. columnstore = index.dialect_options["mssql"]["columnstore"]
  2101. if columnstore:
  2102. text += "COLUMNSTORE "
  2103. text += "INDEX %s ON %s" % (
  2104. self._prepared_index_name(index, include_schema=include_schema),
  2105. preparer.format_table(index.table),
  2106. )
  2107. # in some case mssql allows indexes with no columns defined
  2108. if len(index.expressions) > 0:
  2109. text += " (%s)" % ", ".join(
  2110. self.sql_compiler.process(
  2111. expr, include_table=False, literal_binds=True
  2112. )
  2113. for expr in index.expressions
  2114. )
  2115. # handle other included columns
  2116. if index.dialect_options["mssql"]["include"]:
  2117. inclusions = [
  2118. index.table.c[col] if isinstance(col, str) else col
  2119. for col in index.dialect_options["mssql"]["include"]
  2120. ]
  2121. text += " INCLUDE (%s)" % ", ".join(
  2122. [preparer.quote(c.name) for c in inclusions]
  2123. )
  2124. whereclause = index.dialect_options["mssql"]["where"]
  2125. if whereclause is not None:
  2126. whereclause = coercions.expect(
  2127. roles.DDLExpressionRole, whereclause
  2128. )
  2129. where_compiled = self.sql_compiler.process(
  2130. whereclause, include_table=False, literal_binds=True
  2131. )
  2132. text += " WHERE " + where_compiled
  2133. return text
  2134. def visit_drop_index(self, drop, **kw):
  2135. return "\nDROP INDEX %s ON %s" % (
  2136. self._prepared_index_name(drop.element, include_schema=False),
  2137. self.preparer.format_table(drop.element.table),
  2138. )
  2139. def visit_primary_key_constraint(self, constraint, **kw):
  2140. if len(constraint) == 0:
  2141. return ""
  2142. text = ""
  2143. if constraint.name is not None:
  2144. text += "CONSTRAINT %s " % self.preparer.format_constraint(
  2145. constraint
  2146. )
  2147. text += "PRIMARY KEY "
  2148. clustered = constraint.dialect_options["mssql"]["clustered"]
  2149. if clustered is not None:
  2150. if clustered:
  2151. text += "CLUSTERED "
  2152. else:
  2153. text += "NONCLUSTERED "
  2154. text += "(%s)" % ", ".join(
  2155. self.preparer.quote(c.name) for c in constraint
  2156. )
  2157. text += self.define_constraint_deferrability(constraint)
  2158. return text
  2159. def visit_unique_constraint(self, constraint, **kw):
  2160. if len(constraint) == 0:
  2161. return ""
  2162. text = ""
  2163. if constraint.name is not None:
  2164. formatted_name = self.preparer.format_constraint(constraint)
  2165. if formatted_name is not None:
  2166. text += "CONSTRAINT %s " % formatted_name
  2167. text += "UNIQUE %s" % self.define_unique_constraint_distinct(
  2168. constraint, **kw
  2169. )
  2170. clustered = constraint.dialect_options["mssql"]["clustered"]
  2171. if clustered is not None:
  2172. if clustered:
  2173. text += "CLUSTERED "
  2174. else:
  2175. text += "NONCLUSTERED "
  2176. text += "(%s)" % ", ".join(
  2177. self.preparer.quote(c.name) for c in constraint
  2178. )
  2179. text += self.define_constraint_deferrability(constraint)
  2180. return text
  2181. def visit_computed_column(self, generated, **kw):
  2182. text = "AS (%s)" % self.sql_compiler.process(
  2183. generated.sqltext, include_table=False, literal_binds=True
  2184. )
  2185. # explicitly check for True|False since None means server default
  2186. if generated.persisted is True:
  2187. text += " PERSISTED"
  2188. return text
  2189. def visit_set_table_comment(self, create, **kw):
  2190. schema = self.preparer.schema_for_object(create.element)
  2191. schema_name = schema if schema else self.dialect.default_schema_name
  2192. return (
  2193. "execute sp_addextendedproperty 'MS_Description', "
  2194. "{}, 'schema', {}, 'table', {}".format(
  2195. self.sql_compiler.render_literal_value(
  2196. create.element.comment, sqltypes.NVARCHAR()
  2197. ),
  2198. self.preparer.quote_schema(schema_name),
  2199. self.preparer.format_table(create.element, use_schema=False),
  2200. )
  2201. )
  2202. def visit_drop_table_comment(self, drop, **kw):
  2203. schema = self.preparer.schema_for_object(drop.element)
  2204. schema_name = schema if schema else self.dialect.default_schema_name
  2205. return (
  2206. "execute sp_dropextendedproperty 'MS_Description', 'schema', "
  2207. "{}, 'table', {}".format(
  2208. self.preparer.quote_schema(schema_name),
  2209. self.preparer.format_table(drop.element, use_schema=False),
  2210. )
  2211. )
  2212. def visit_set_column_comment(self, create, **kw):
  2213. schema = self.preparer.schema_for_object(create.element.table)
  2214. schema_name = schema if schema else self.dialect.default_schema_name
  2215. return (
  2216. "execute sp_addextendedproperty 'MS_Description', "
  2217. "{}, 'schema', {}, 'table', {}, 'column', {}".format(
  2218. self.sql_compiler.render_literal_value(
  2219. create.element.comment, sqltypes.NVARCHAR()
  2220. ),
  2221. self.preparer.quote_schema(schema_name),
  2222. self.preparer.format_table(
  2223. create.element.table, use_schema=False
  2224. ),
  2225. self.preparer.format_column(create.element),
  2226. )
  2227. )
  2228. def visit_drop_column_comment(self, drop, **kw):
  2229. schema = self.preparer.schema_for_object(drop.element.table)
  2230. schema_name = schema if schema else self.dialect.default_schema_name
  2231. return (
  2232. "execute sp_dropextendedproperty 'MS_Description', 'schema', "
  2233. "{}, 'table', {}, 'column', {}".format(
  2234. self.preparer.quote_schema(schema_name),
  2235. self.preparer.format_table(
  2236. drop.element.table, use_schema=False
  2237. ),
  2238. self.preparer.format_column(drop.element),
  2239. )
  2240. )
  2241. def visit_create_sequence(self, create, **kw):
  2242. prefix = None
  2243. if create.element.data_type is not None:
  2244. data_type = create.element.data_type
  2245. prefix = " AS %s" % self.type_compiler.process(data_type)
  2246. return super().visit_create_sequence(create, prefix=prefix, **kw)
  2247. def visit_identity_column(self, identity, **kw):
  2248. text = " IDENTITY"
  2249. if identity.start is not None or identity.increment is not None:
  2250. start = 1 if identity.start is None else identity.start
  2251. increment = 1 if identity.increment is None else identity.increment
  2252. text += "(%s,%s)" % (start, increment)
  2253. return text
  2254. class MSIdentifierPreparer(compiler.IdentifierPreparer):
  2255. reserved_words = RESERVED_WORDS
  2256. def __init__(self, dialect):
  2257. super().__init__(
  2258. dialect,
  2259. initial_quote="[",
  2260. final_quote="]",
  2261. quote_case_sensitive_collations=False,
  2262. )
  2263. def _escape_identifier(self, value):
  2264. return value.replace("]", "]]")
  2265. def _unescape_identifier(self, value):
  2266. return value.replace("]]", "]")
  2267. def quote_schema(self, schema, force=None):
  2268. """Prepare a quoted table and schema name."""
  2269. # need to re-implement the deprecation warning entirely
  2270. if force is not None:
  2271. # not using the util.deprecated_params() decorator in this
  2272. # case because of the additional function call overhead on this
  2273. # very performance-critical spot.
  2274. util.warn_deprecated(
  2275. "The IdentifierPreparer.quote_schema.force parameter is "
  2276. "deprecated and will be removed in a future release. This "
  2277. "flag has no effect on the behavior of the "
  2278. "IdentifierPreparer.quote method; please refer to "
  2279. "quoted_name().",
  2280. version="1.3",
  2281. )
  2282. dbname, owner = _schema_elements(schema)
  2283. if dbname:
  2284. result = "%s.%s" % (self.quote(dbname), self.quote(owner))
  2285. elif owner:
  2286. result = self.quote(owner)
  2287. else:
  2288. result = ""
  2289. return result
  2290. def _db_plus_owner_listing(fn):
  2291. def wrap(dialect, connection, schema=None, **kw):
  2292. dbname, owner = _owner_plus_db(dialect, schema)
  2293. return _switch_db(
  2294. dbname,
  2295. connection,
  2296. fn,
  2297. dialect,
  2298. connection,
  2299. dbname,
  2300. owner,
  2301. schema,
  2302. **kw,
  2303. )
  2304. return update_wrapper(wrap, fn)
  2305. def _db_plus_owner(fn):
  2306. def wrap(dialect, connection, tablename, schema=None, **kw):
  2307. dbname, owner = _owner_plus_db(dialect, schema)
  2308. return _switch_db(
  2309. dbname,
  2310. connection,
  2311. fn,
  2312. dialect,
  2313. connection,
  2314. tablename,
  2315. dbname,
  2316. owner,
  2317. schema,
  2318. **kw,
  2319. )
  2320. return update_wrapper(wrap, fn)
  2321. def _switch_db(dbname, connection, fn, *arg, **kw):
  2322. if dbname:
  2323. current_db = connection.exec_driver_sql("select db_name()").scalar()
  2324. if current_db != dbname:
  2325. connection.exec_driver_sql(
  2326. "use %s" % connection.dialect.identifier_preparer.quote(dbname)
  2327. )
  2328. try:
  2329. return fn(*arg, **kw)
  2330. finally:
  2331. if dbname and current_db != dbname:
  2332. connection.exec_driver_sql(
  2333. "use %s"
  2334. % connection.dialect.identifier_preparer.quote(current_db)
  2335. )
  2336. def _owner_plus_db(dialect, schema):
  2337. if not schema:
  2338. return None, dialect.default_schema_name
  2339. else:
  2340. return _schema_elements(schema)
  2341. _memoized_schema = util.LRUCache()
  2342. def _schema_elements(schema):
  2343. if isinstance(schema, quoted_name) and schema.quote:
  2344. return None, schema
  2345. if schema in _memoized_schema:
  2346. return _memoized_schema[schema]
  2347. # tests for this function are in:
  2348. # test/dialect/mssql/test_reflection.py ->
  2349. # OwnerPlusDBTest.test_owner_database_pairs
  2350. # test/dialect/mssql/test_compiler.py -> test_force_schema_*
  2351. # test/dialect/mssql/test_compiler.py -> test_schema_many_tokens_*
  2352. #
  2353. if schema.startswith("__[SCHEMA_"):
  2354. return None, schema
  2355. push = []
  2356. symbol = ""
  2357. bracket = False
  2358. has_brackets = False
  2359. for token in re.split(r"(\[|\]|\.)", schema):
  2360. if not token:
  2361. continue
  2362. if token == "[":
  2363. bracket = True
  2364. has_brackets = True
  2365. elif token == "]":
  2366. bracket = False
  2367. elif not bracket and token == ".":
  2368. if has_brackets:
  2369. push.append("[%s]" % symbol)
  2370. else:
  2371. push.append(symbol)
  2372. symbol = ""
  2373. has_brackets = False
  2374. else:
  2375. symbol += token
  2376. if symbol:
  2377. push.append(symbol)
  2378. if len(push) > 1:
  2379. dbname, owner = ".".join(push[0:-1]), push[-1]
  2380. # test for internal brackets
  2381. if re.match(r".*\].*\[.*", dbname[1:-1]):
  2382. dbname = quoted_name(dbname, quote=False)
  2383. else:
  2384. dbname = dbname.lstrip("[").rstrip("]")
  2385. elif len(push):
  2386. dbname, owner = None, push[0]
  2387. else:
  2388. dbname, owner = None, None
  2389. _memoized_schema[schema] = dbname, owner
  2390. return dbname, owner
  2391. class MSDialect(default.DefaultDialect):
  2392. # will assume it's at least mssql2005
  2393. name = "mssql"
  2394. supports_statement_cache = True
  2395. supports_default_values = True
  2396. supports_empty_insert = False
  2397. favor_returning_over_lastrowid = True
  2398. returns_native_bytes = True
  2399. supports_comments = True
  2400. supports_default_metavalue = False
  2401. """dialect supports INSERT... VALUES (DEFAULT) syntax -
  2402. SQL Server **does** support this, but **not** for the IDENTITY column,
  2403. so we can't turn this on.
  2404. """
  2405. # supports_native_uuid is partial here, so we implement our
  2406. # own impl type
  2407. execution_ctx_cls = MSExecutionContext
  2408. use_scope_identity = True
  2409. max_identifier_length = 128
  2410. schema_name = "dbo"
  2411. insert_returning = True
  2412. update_returning = True
  2413. delete_returning = True
  2414. update_returning_multifrom = True
  2415. delete_returning_multifrom = True
  2416. colspecs = {
  2417. sqltypes.DateTime: _MSDateTime,
  2418. sqltypes.Date: _MSDate,
  2419. sqltypes.JSON: JSON,
  2420. sqltypes.JSON.JSONIndexType: JSONIndexType,
  2421. sqltypes.JSON.JSONPathType: JSONPathType,
  2422. sqltypes.Time: _BASETIMEIMPL,
  2423. sqltypes.Unicode: _MSUnicode,
  2424. sqltypes.UnicodeText: _MSUnicodeText,
  2425. DATETIMEOFFSET: DATETIMEOFFSET,
  2426. DATETIME2: DATETIME2,
  2427. SMALLDATETIME: SMALLDATETIME,
  2428. DATETIME: DATETIME,
  2429. sqltypes.Uuid: MSUUid,
  2430. }
  2431. engine_config_types = default.DefaultDialect.engine_config_types.union(
  2432. {"legacy_schema_aliasing": util.asbool}
  2433. )
  2434. ischema_names = ischema_names
  2435. supports_sequences = True
  2436. sequences_optional = True
  2437. # This is actually used for autoincrement, where itentity is used that
  2438. # starts with 1.
  2439. # for sequences T-SQL's actual default is -9223372036854775808
  2440. default_sequence_base = 1
  2441. supports_native_boolean = False
  2442. non_native_boolean_check_constraint = False
  2443. supports_unicode_binds = True
  2444. postfetch_lastrowid = True
  2445. # may be changed at server inspection time for older SQL server versions
  2446. supports_multivalues_insert = True
  2447. use_insertmanyvalues = True
  2448. # note pyodbc will set this to False if fast_executemany is set,
  2449. # as of SQLAlchemy 2.0.9
  2450. use_insertmanyvalues_wo_returning = True
  2451. insertmanyvalues_implicit_sentinel = (
  2452. InsertmanyvaluesSentinelOpts.AUTOINCREMENT
  2453. | InsertmanyvaluesSentinelOpts.IDENTITY
  2454. | InsertmanyvaluesSentinelOpts.USE_INSERT_FROM_SELECT
  2455. )
  2456. # "The incoming request has too many parameters. The server supports a "
  2457. # "maximum of 2100 parameters."
  2458. # in fact you can have 2099 parameters.
  2459. insertmanyvalues_max_parameters = 2099
  2460. _supports_offset_fetch = False
  2461. _supports_nvarchar_max = False
  2462. legacy_schema_aliasing = False
  2463. server_version_info = ()
  2464. statement_compiler = MSSQLCompiler
  2465. ddl_compiler = MSDDLCompiler
  2466. type_compiler_cls = MSTypeCompiler
  2467. preparer = MSIdentifierPreparer
  2468. construct_arguments = [
  2469. (sa_schema.PrimaryKeyConstraint, {"clustered": None}),
  2470. (sa_schema.UniqueConstraint, {"clustered": None}),
  2471. (
  2472. sa_schema.Index,
  2473. {
  2474. "clustered": None,
  2475. "include": None,
  2476. "where": None,
  2477. "columnstore": None,
  2478. },
  2479. ),
  2480. (
  2481. sa_schema.Column,
  2482. {"identity_start": None, "identity_increment": None},
  2483. ),
  2484. ]
  2485. def __init__(
  2486. self,
  2487. query_timeout=None,
  2488. use_scope_identity=True,
  2489. schema_name="dbo",
  2490. deprecate_large_types=None,
  2491. supports_comments=None,
  2492. json_serializer=None,
  2493. json_deserializer=None,
  2494. legacy_schema_aliasing=None,
  2495. ignore_no_transaction_on_rollback=False,
  2496. **opts,
  2497. ):
  2498. self.query_timeout = int(query_timeout or 0)
  2499. self.schema_name = schema_name
  2500. self.use_scope_identity = use_scope_identity
  2501. self.deprecate_large_types = deprecate_large_types
  2502. self.ignore_no_transaction_on_rollback = (
  2503. ignore_no_transaction_on_rollback
  2504. )
  2505. self._user_defined_supports_comments = uds = supports_comments
  2506. if uds is not None:
  2507. self.supports_comments = uds
  2508. if legacy_schema_aliasing is not None:
  2509. util.warn_deprecated(
  2510. "The legacy_schema_aliasing parameter is "
  2511. "deprecated and will be removed in a future release.",
  2512. "1.4",
  2513. )
  2514. self.legacy_schema_aliasing = legacy_schema_aliasing
  2515. super().__init__(**opts)
  2516. self._json_serializer = json_serializer
  2517. self._json_deserializer = json_deserializer
  2518. def do_savepoint(self, connection, name):
  2519. # give the DBAPI a push
  2520. connection.exec_driver_sql("IF @@TRANCOUNT = 0 BEGIN TRANSACTION")
  2521. super().do_savepoint(connection, name)
  2522. def do_release_savepoint(self, connection, name):
  2523. # SQL Server does not support RELEASE SAVEPOINT
  2524. pass
  2525. def do_rollback(self, dbapi_connection):
  2526. try:
  2527. super().do_rollback(dbapi_connection)
  2528. except self.dbapi.ProgrammingError as e:
  2529. if self.ignore_no_transaction_on_rollback and re.match(
  2530. r".*\b111214\b", str(e)
  2531. ):
  2532. util.warn(
  2533. "ProgrammingError 111214 "
  2534. "'No corresponding transaction found.' "
  2535. "has been suppressed via "
  2536. "ignore_no_transaction_on_rollback=True"
  2537. )
  2538. else:
  2539. raise
  2540. _isolation_lookup = {
  2541. "SERIALIZABLE",
  2542. "READ UNCOMMITTED",
  2543. "READ COMMITTED",
  2544. "REPEATABLE READ",
  2545. "SNAPSHOT",
  2546. }
  2547. def get_isolation_level_values(self, dbapi_connection):
  2548. return list(self._isolation_lookup)
  2549. def set_isolation_level(self, dbapi_connection, level):
  2550. cursor = dbapi_connection.cursor()
  2551. cursor.execute(f"SET TRANSACTION ISOLATION LEVEL {level}")
  2552. cursor.close()
  2553. if level == "SNAPSHOT":
  2554. dbapi_connection.commit()
  2555. def get_isolation_level(self, dbapi_connection):
  2556. cursor = dbapi_connection.cursor()
  2557. view_name = "sys.system_views"
  2558. try:
  2559. cursor.execute(
  2560. (
  2561. "SELECT name FROM {} WHERE name IN "
  2562. "('dm_exec_sessions', 'dm_pdw_nodes_exec_sessions')"
  2563. ).format(view_name)
  2564. )
  2565. row = cursor.fetchone()
  2566. if not row:
  2567. raise NotImplementedError(
  2568. "Can't fetch isolation level on this particular "
  2569. "SQL Server version."
  2570. )
  2571. view_name = f"sys.{row[0]}"
  2572. cursor.execute(
  2573. """
  2574. SELECT CASE transaction_isolation_level
  2575. WHEN 0 THEN NULL
  2576. WHEN 1 THEN 'READ UNCOMMITTED'
  2577. WHEN 2 THEN 'READ COMMITTED'
  2578. WHEN 3 THEN 'REPEATABLE READ'
  2579. WHEN 4 THEN 'SERIALIZABLE'
  2580. WHEN 5 THEN 'SNAPSHOT' END
  2581. AS TRANSACTION_ISOLATION_LEVEL
  2582. FROM {}
  2583. where session_id = @@SPID
  2584. """.format(
  2585. view_name
  2586. )
  2587. )
  2588. except self.dbapi.Error as err:
  2589. raise NotImplementedError(
  2590. "Can't fetch isolation level; encountered error {} when "
  2591. 'attempting to query the "{}" view.'.format(err, view_name)
  2592. ) from err
  2593. else:
  2594. row = cursor.fetchone()
  2595. return row[0].upper()
  2596. finally:
  2597. cursor.close()
  2598. def initialize(self, connection):
  2599. super().initialize(connection)
  2600. self._setup_version_attributes()
  2601. self._setup_supports_nvarchar_max(connection)
  2602. self._setup_supports_comments(connection)
  2603. def _setup_version_attributes(self):
  2604. if self.server_version_info[0] not in list(range(8, 17)):
  2605. util.warn(
  2606. "Unrecognized server version info '%s'. Some SQL Server "
  2607. "features may not function properly."
  2608. % ".".join(str(x) for x in self.server_version_info)
  2609. )
  2610. if self.server_version_info >= MS_2008_VERSION:
  2611. self.supports_multivalues_insert = True
  2612. else:
  2613. self.supports_multivalues_insert = False
  2614. if self.deprecate_large_types is None:
  2615. self.deprecate_large_types = (
  2616. self.server_version_info >= MS_2012_VERSION
  2617. )
  2618. self._supports_offset_fetch = (
  2619. self.server_version_info and self.server_version_info[0] >= 11
  2620. )
  2621. def _setup_supports_nvarchar_max(self, connection):
  2622. try:
  2623. connection.scalar(
  2624. sql.text("SELECT CAST('test max support' AS NVARCHAR(max))")
  2625. )
  2626. except exc.DBAPIError:
  2627. self._supports_nvarchar_max = False
  2628. else:
  2629. self._supports_nvarchar_max = True
  2630. def _setup_supports_comments(self, connection):
  2631. if self._user_defined_supports_comments is not None:
  2632. return
  2633. try:
  2634. connection.scalar(
  2635. sql.text(
  2636. "SELECT 1 FROM fn_listextendedproperty"
  2637. "(default, default, default, default, "
  2638. "default, default, default)"
  2639. )
  2640. )
  2641. except exc.DBAPIError:
  2642. self.supports_comments = False
  2643. else:
  2644. self.supports_comments = True
  2645. def _get_default_schema_name(self, connection):
  2646. query = sql.text("SELECT schema_name()")
  2647. default_schema_name = connection.scalar(query)
  2648. if default_schema_name is not None:
  2649. # guard against the case where the default_schema_name is being
  2650. # fed back into a table reflection function.
  2651. return quoted_name(default_schema_name, quote=True)
  2652. else:
  2653. return self.schema_name
  2654. @_db_plus_owner
  2655. def has_table(self, connection, tablename, dbname, owner, schema, **kw):
  2656. self._ensure_has_table_connection(connection)
  2657. return self._internal_has_table(connection, tablename, owner, **kw)
  2658. @reflection.cache
  2659. @_db_plus_owner
  2660. def has_sequence(
  2661. self, connection, sequencename, dbname, owner, schema, **kw
  2662. ):
  2663. sequences = ischema.sequences
  2664. s = sql.select(sequences.c.sequence_name).where(
  2665. sequences.c.sequence_name == sequencename
  2666. )
  2667. if owner:
  2668. s = s.where(sequences.c.sequence_schema == owner)
  2669. c = connection.execute(s)
  2670. return c.first() is not None
  2671. @reflection.cache
  2672. @_db_plus_owner_listing
  2673. def get_sequence_names(self, connection, dbname, owner, schema, **kw):
  2674. sequences = ischema.sequences
  2675. s = sql.select(sequences.c.sequence_name)
  2676. if owner:
  2677. s = s.where(sequences.c.sequence_schema == owner)
  2678. c = connection.execute(s)
  2679. return [row[0] for row in c]
  2680. @reflection.cache
  2681. def get_schema_names(self, connection, **kw):
  2682. s = sql.select(ischema.schemata.c.schema_name).order_by(
  2683. ischema.schemata.c.schema_name
  2684. )
  2685. schema_names = [r[0] for r in connection.execute(s)]
  2686. return schema_names
  2687. @reflection.cache
  2688. @_db_plus_owner_listing
  2689. def get_table_names(self, connection, dbname, owner, schema, **kw):
  2690. tables = ischema.tables
  2691. s = (
  2692. sql.select(tables.c.table_name)
  2693. .where(
  2694. sql.and_(
  2695. tables.c.table_schema == owner,
  2696. tables.c.table_type == "BASE TABLE",
  2697. )
  2698. )
  2699. .order_by(tables.c.table_name)
  2700. )
  2701. table_names = [r[0] for r in connection.execute(s)]
  2702. return table_names
  2703. @reflection.cache
  2704. @_db_plus_owner_listing
  2705. def get_view_names(self, connection, dbname, owner, schema, **kw):
  2706. tables = ischema.tables
  2707. s = (
  2708. sql.select(tables.c.table_name)
  2709. .where(
  2710. sql.and_(
  2711. tables.c.table_schema == owner,
  2712. tables.c.table_type == "VIEW",
  2713. )
  2714. )
  2715. .order_by(tables.c.table_name)
  2716. )
  2717. view_names = [r[0] for r in connection.execute(s)]
  2718. return view_names
  2719. @reflection.cache
  2720. def _internal_has_table(self, connection, tablename, owner, **kw):
  2721. if tablename.startswith("#"): # temporary table
  2722. # mssql does not support temporary views
  2723. # SQL Error [4103] [S0001]: "#v": Temporary views are not allowed
  2724. return bool(
  2725. connection.scalar(
  2726. # U filters on user tables only.
  2727. text("SELECT object_id(:table_name, 'U')"),
  2728. {"table_name": f"tempdb.dbo.[{tablename}]"},
  2729. )
  2730. )
  2731. else:
  2732. tables = ischema.tables
  2733. s = sql.select(tables.c.table_name).where(
  2734. sql.and_(
  2735. sql.or_(
  2736. tables.c.table_type == "BASE TABLE",
  2737. tables.c.table_type == "VIEW",
  2738. ),
  2739. tables.c.table_name == tablename,
  2740. )
  2741. )
  2742. if owner:
  2743. s = s.where(tables.c.table_schema == owner)
  2744. c = connection.execute(s)
  2745. return c.first() is not None
  2746. def _default_or_error(self, connection, tablename, owner, method, **kw):
  2747. # TODO: try to avoid having to run a separate query here
  2748. if self._internal_has_table(connection, tablename, owner, **kw):
  2749. return method()
  2750. else:
  2751. raise exc.NoSuchTableError(f"{owner}.{tablename}")
  2752. @reflection.cache
  2753. @_db_plus_owner
  2754. def get_indexes(self, connection, tablename, dbname, owner, schema, **kw):
  2755. filter_definition = (
  2756. "ind.filter_definition"
  2757. if self.server_version_info >= MS_2008_VERSION
  2758. else "NULL as filter_definition"
  2759. )
  2760. rp = connection.execution_options(future_result=True).execute(
  2761. sql.text(
  2762. f"""
  2763. select
  2764. ind.index_id,
  2765. ind.is_unique,
  2766. ind.name,
  2767. ind.type,
  2768. {filter_definition}
  2769. from
  2770. sys.indexes as ind
  2771. join sys.tables as tab on
  2772. ind.object_id = tab.object_id
  2773. join sys.schemas as sch on
  2774. sch.schema_id = tab.schema_id
  2775. where
  2776. tab.name = :tabname
  2777. and sch.name = :schname
  2778. and ind.is_primary_key = 0
  2779. and ind.type != 0
  2780. order by
  2781. ind.name
  2782. """
  2783. )
  2784. .bindparams(
  2785. sql.bindparam("tabname", tablename, ischema.CoerceUnicode()),
  2786. sql.bindparam("schname", owner, ischema.CoerceUnicode()),
  2787. )
  2788. .columns(name=sqltypes.Unicode())
  2789. )
  2790. indexes = {}
  2791. for row in rp.mappings():
  2792. indexes[row["index_id"]] = current = {
  2793. "name": row["name"],
  2794. "unique": row["is_unique"] == 1,
  2795. "column_names": [],
  2796. "include_columns": [],
  2797. "dialect_options": {},
  2798. }
  2799. do = current["dialect_options"]
  2800. index_type = row["type"]
  2801. if index_type in {1, 2}:
  2802. do["mssql_clustered"] = index_type == 1
  2803. if index_type in {5, 6}:
  2804. do["mssql_clustered"] = index_type == 5
  2805. do["mssql_columnstore"] = True
  2806. if row["filter_definition"] is not None:
  2807. do["mssql_where"] = row["filter_definition"]
  2808. rp = connection.execution_options(future_result=True).execute(
  2809. sql.text(
  2810. """
  2811. select
  2812. ind_col.index_id,
  2813. col.name,
  2814. ind_col.is_included_column
  2815. from
  2816. sys.columns as col
  2817. join sys.tables as tab on
  2818. tab.object_id = col.object_id
  2819. join sys.index_columns as ind_col on
  2820. ind_col.column_id = col.column_id
  2821. and ind_col.object_id = tab.object_id
  2822. join sys.schemas as sch on
  2823. sch.schema_id = tab.schema_id
  2824. where
  2825. tab.name = :tabname
  2826. and sch.name = :schname
  2827. """
  2828. )
  2829. .bindparams(
  2830. sql.bindparam("tabname", tablename, ischema.CoerceUnicode()),
  2831. sql.bindparam("schname", owner, ischema.CoerceUnicode()),
  2832. )
  2833. .columns(name=sqltypes.Unicode())
  2834. )
  2835. for row in rp.mappings():
  2836. if row["index_id"] not in indexes:
  2837. continue
  2838. index_def = indexes[row["index_id"]]
  2839. is_colstore = index_def["dialect_options"].get("mssql_columnstore")
  2840. is_clustered = index_def["dialect_options"].get("mssql_clustered")
  2841. if not (is_colstore and is_clustered):
  2842. # a clustered columnstore index includes all columns but does
  2843. # not want them in the index definition
  2844. if row["is_included_column"] and not is_colstore:
  2845. # a noncludsted columnstore index reports that includes
  2846. # columns but requires that are listed as normal columns
  2847. index_def["include_columns"].append(row["name"])
  2848. else:
  2849. index_def["column_names"].append(row["name"])
  2850. for index_info in indexes.values():
  2851. # NOTE: "root level" include_columns is legacy, now part of
  2852. # dialect_options (issue #7382)
  2853. index_info["dialect_options"]["mssql_include"] = index_info[
  2854. "include_columns"
  2855. ]
  2856. if indexes:
  2857. return list(indexes.values())
  2858. else:
  2859. return self._default_or_error(
  2860. connection, tablename, owner, ReflectionDefaults.indexes, **kw
  2861. )
  2862. @reflection.cache
  2863. @_db_plus_owner
  2864. def get_view_definition(
  2865. self, connection, viewname, dbname, owner, schema, **kw
  2866. ):
  2867. view_def = connection.execute(
  2868. sql.text(
  2869. "select mod.definition "
  2870. "from sys.sql_modules as mod "
  2871. "join sys.views as views on mod.object_id = views.object_id "
  2872. "join sys.schemas as sch on views.schema_id = sch.schema_id "
  2873. "where views.name=:viewname and sch.name=:schname"
  2874. ).bindparams(
  2875. sql.bindparam("viewname", viewname, ischema.CoerceUnicode()),
  2876. sql.bindparam("schname", owner, ischema.CoerceUnicode()),
  2877. )
  2878. ).scalar()
  2879. if view_def:
  2880. return view_def
  2881. else:
  2882. raise exc.NoSuchTableError(f"{owner}.{viewname}")
  2883. @reflection.cache
  2884. def get_table_comment(self, connection, table_name, schema=None, **kw):
  2885. if not self.supports_comments:
  2886. raise NotImplementedError(
  2887. "Can't get table comments on current SQL Server version in use"
  2888. )
  2889. schema_name = schema if schema else self.default_schema_name
  2890. COMMENT_SQL = """
  2891. SELECT cast(com.value as nvarchar(max))
  2892. FROM fn_listextendedproperty('MS_Description',
  2893. 'schema', :schema, 'table', :table, NULL, NULL
  2894. ) as com;
  2895. """
  2896. comment = connection.execute(
  2897. sql.text(COMMENT_SQL).bindparams(
  2898. sql.bindparam("schema", schema_name, ischema.CoerceUnicode()),
  2899. sql.bindparam("table", table_name, ischema.CoerceUnicode()),
  2900. )
  2901. ).scalar()
  2902. if comment:
  2903. return {"text": comment}
  2904. else:
  2905. return self._default_or_error(
  2906. connection,
  2907. table_name,
  2908. None,
  2909. ReflectionDefaults.table_comment,
  2910. **kw,
  2911. )
  2912. def _temp_table_name_like_pattern(self, tablename):
  2913. # LIKE uses '%' to match zero or more characters and '_' to match any
  2914. # single character. We want to match literal underscores, so T-SQL
  2915. # requires that we enclose them in square brackets.
  2916. return tablename + (
  2917. ("[_][_][_]%") if not tablename.startswith("##") else ""
  2918. )
  2919. def _get_internal_temp_table_name(self, connection, tablename):
  2920. # it's likely that schema is always "dbo", but since we can
  2921. # get it here, let's get it.
  2922. # see https://stackoverflow.com/questions/8311959/
  2923. # specifying-schema-for-temporary-tables
  2924. try:
  2925. return connection.execute(
  2926. sql.text(
  2927. "select table_schema, table_name "
  2928. "from tempdb.information_schema.tables "
  2929. "where table_name like :p1"
  2930. ),
  2931. {"p1": self._temp_table_name_like_pattern(tablename)},
  2932. ).one()
  2933. except exc.MultipleResultsFound as me:
  2934. raise exc.UnreflectableTableError(
  2935. "Found more than one temporary table named '%s' in tempdb "
  2936. "at this time. Cannot reliably resolve that name to its "
  2937. "internal table name." % tablename
  2938. ) from me
  2939. except exc.NoResultFound as ne:
  2940. raise exc.NoSuchTableError(
  2941. "Unable to find a temporary table named '%s' in tempdb."
  2942. % tablename
  2943. ) from ne
  2944. @reflection.cache
  2945. @_db_plus_owner
  2946. def get_columns(self, connection, tablename, dbname, owner, schema, **kw):
  2947. sys_columns = ischema.sys_columns
  2948. sys_types = ischema.sys_types
  2949. sys_default_constraints = ischema.sys_default_constraints
  2950. computed_cols = ischema.computed_columns
  2951. identity_cols = ischema.identity_columns
  2952. extended_properties = ischema.extended_properties
  2953. # to access sys tables, need an object_id.
  2954. # object_id() can normally match to the unquoted name even if it
  2955. # has special characters. however it also accepts quoted names,
  2956. # which means for the special case that the name itself has
  2957. # "quotes" (e.g. brackets for SQL Server) we need to "quote" (e.g.
  2958. # bracket) that name anyway. Fixed as part of #12654
  2959. is_temp_table = tablename.startswith("#")
  2960. if is_temp_table:
  2961. owner, tablename = self._get_internal_temp_table_name(
  2962. connection, tablename
  2963. )
  2964. object_id_tokens = [self.identifier_preparer.quote(tablename)]
  2965. if owner:
  2966. object_id_tokens.insert(0, self.identifier_preparer.quote(owner))
  2967. if is_temp_table:
  2968. object_id_tokens.insert(0, "tempdb")
  2969. object_id = func.object_id(".".join(object_id_tokens))
  2970. whereclause = sys_columns.c.object_id == object_id
  2971. if self._supports_nvarchar_max:
  2972. computed_definition = computed_cols.c.definition
  2973. else:
  2974. # tds_version 4.2 does not support NVARCHAR(MAX)
  2975. computed_definition = sql.cast(
  2976. computed_cols.c.definition, NVARCHAR(4000)
  2977. )
  2978. s = (
  2979. sql.select(
  2980. sys_columns.c.name,
  2981. sys_types.c.name,
  2982. sys_columns.c.is_nullable,
  2983. sys_columns.c.max_length,
  2984. sys_columns.c.precision,
  2985. sys_columns.c.scale,
  2986. sys_default_constraints.c.definition,
  2987. sys_columns.c.collation_name,
  2988. computed_definition,
  2989. computed_cols.c.is_persisted,
  2990. identity_cols.c.is_identity,
  2991. identity_cols.c.seed_value,
  2992. identity_cols.c.increment_value,
  2993. extended_properties.c.value.label("comment"),
  2994. )
  2995. .select_from(sys_columns)
  2996. .join(
  2997. sys_types,
  2998. onclause=sys_columns.c.user_type_id
  2999. == sys_types.c.user_type_id,
  3000. )
  3001. .outerjoin(
  3002. sys_default_constraints,
  3003. sql.and_(
  3004. sys_default_constraints.c.object_id
  3005. == sys_columns.c.default_object_id,
  3006. sys_default_constraints.c.parent_column_id
  3007. == sys_columns.c.column_id,
  3008. ),
  3009. )
  3010. .outerjoin(
  3011. computed_cols,
  3012. onclause=sql.and_(
  3013. computed_cols.c.object_id == sys_columns.c.object_id,
  3014. computed_cols.c.column_id == sys_columns.c.column_id,
  3015. ),
  3016. )
  3017. .outerjoin(
  3018. identity_cols,
  3019. onclause=sql.and_(
  3020. identity_cols.c.object_id == sys_columns.c.object_id,
  3021. identity_cols.c.column_id == sys_columns.c.column_id,
  3022. ),
  3023. )
  3024. .outerjoin(
  3025. extended_properties,
  3026. onclause=sql.and_(
  3027. extended_properties.c["class"] == 1,
  3028. extended_properties.c.name == "MS_Description",
  3029. sys_columns.c.object_id == extended_properties.c.major_id,
  3030. sys_columns.c.column_id == extended_properties.c.minor_id,
  3031. ),
  3032. )
  3033. .where(whereclause)
  3034. .order_by(sys_columns.c.column_id)
  3035. )
  3036. if is_temp_table:
  3037. exec_opts = {"schema_translate_map": {"sys": "tempdb.sys"}}
  3038. else:
  3039. exec_opts = {"schema_translate_map": {}}
  3040. c = connection.execution_options(**exec_opts).execute(s)
  3041. cols = []
  3042. for row in c.mappings():
  3043. name = row[sys_columns.c.name]
  3044. type_ = row[sys_types.c.name]
  3045. nullable = row[sys_columns.c.is_nullable] == 1
  3046. maxlen = row[sys_columns.c.max_length]
  3047. numericprec = row[sys_columns.c.precision]
  3048. numericscale = row[sys_columns.c.scale]
  3049. default = row[sys_default_constraints.c.definition]
  3050. collation = row[sys_columns.c.collation_name]
  3051. definition = row[computed_definition]
  3052. is_persisted = row[computed_cols.c.is_persisted]
  3053. is_identity = row[identity_cols.c.is_identity]
  3054. identity_start = row[identity_cols.c.seed_value]
  3055. identity_increment = row[identity_cols.c.increment_value]
  3056. comment = row[extended_properties.c.value]
  3057. coltype = self.ischema_names.get(type_, None)
  3058. kwargs = {}
  3059. if coltype in (
  3060. MSBinary,
  3061. MSVarBinary,
  3062. sqltypes.LargeBinary,
  3063. ):
  3064. kwargs["length"] = maxlen if maxlen != -1 else None
  3065. elif coltype in (
  3066. MSString,
  3067. MSChar,
  3068. MSText,
  3069. ):
  3070. kwargs["length"] = maxlen if maxlen != -1 else None
  3071. if collation:
  3072. kwargs["collation"] = collation
  3073. elif coltype in (
  3074. MSNVarchar,
  3075. MSNChar,
  3076. MSNText,
  3077. ):
  3078. kwargs["length"] = maxlen // 2 if maxlen != -1 else None
  3079. if collation:
  3080. kwargs["collation"] = collation
  3081. if coltype is None:
  3082. util.warn(
  3083. "Did not recognize type '%s' of column '%s'"
  3084. % (type_, name)
  3085. )
  3086. coltype = sqltypes.NULLTYPE
  3087. else:
  3088. if issubclass(coltype, sqltypes.Numeric):
  3089. kwargs["precision"] = numericprec
  3090. if not issubclass(coltype, sqltypes.Float):
  3091. kwargs["scale"] = numericscale
  3092. coltype = coltype(**kwargs)
  3093. cdict = {
  3094. "name": name,
  3095. "type": coltype,
  3096. "nullable": nullable,
  3097. "default": default,
  3098. "autoincrement": is_identity is not None,
  3099. "comment": comment,
  3100. }
  3101. if definition is not None and is_persisted is not None:
  3102. cdict["computed"] = {
  3103. "sqltext": definition,
  3104. "persisted": is_persisted,
  3105. }
  3106. if is_identity is not None:
  3107. # identity_start and identity_increment are Decimal or None
  3108. if identity_start is None or identity_increment is None:
  3109. cdict["identity"] = {}
  3110. else:
  3111. if isinstance(coltype, sqltypes.BigInteger):
  3112. start = int(identity_start)
  3113. increment = int(identity_increment)
  3114. elif isinstance(coltype, sqltypes.Integer):
  3115. start = int(identity_start)
  3116. increment = int(identity_increment)
  3117. else:
  3118. start = identity_start
  3119. increment = identity_increment
  3120. cdict["identity"] = {
  3121. "start": start,
  3122. "increment": increment,
  3123. }
  3124. cols.append(cdict)
  3125. if cols:
  3126. return cols
  3127. else:
  3128. return self._default_or_error(
  3129. connection, tablename, owner, ReflectionDefaults.columns, **kw
  3130. )
  3131. @reflection.cache
  3132. @_db_plus_owner
  3133. def get_pk_constraint(
  3134. self, connection, tablename, dbname, owner, schema, **kw
  3135. ):
  3136. pkeys = []
  3137. TC = ischema.constraints
  3138. C = ischema.key_constraints.alias("C")
  3139. # Primary key constraints
  3140. s = (
  3141. sql.select(
  3142. C.c.column_name,
  3143. TC.c.constraint_type,
  3144. C.c.constraint_name,
  3145. func.objectproperty(
  3146. func.object_id(
  3147. C.c.table_schema + "." + C.c.constraint_name
  3148. ),
  3149. "CnstIsClustKey",
  3150. ).label("is_clustered"),
  3151. )
  3152. .where(
  3153. sql.and_(
  3154. TC.c.constraint_name == C.c.constraint_name,
  3155. TC.c.table_schema == C.c.table_schema,
  3156. C.c.table_name == tablename,
  3157. C.c.table_schema == owner,
  3158. ),
  3159. )
  3160. .order_by(TC.c.constraint_name, C.c.ordinal_position)
  3161. )
  3162. c = connection.execution_options(future_result=True).execute(s)
  3163. constraint_name = None
  3164. is_clustered = None
  3165. for row in c.mappings():
  3166. if "PRIMARY" in row[TC.c.constraint_type.name]:
  3167. pkeys.append(row["COLUMN_NAME"])
  3168. if constraint_name is None:
  3169. constraint_name = row[C.c.constraint_name.name]
  3170. if is_clustered is None:
  3171. is_clustered = row["is_clustered"]
  3172. if pkeys:
  3173. return {
  3174. "constrained_columns": pkeys,
  3175. "name": constraint_name,
  3176. "dialect_options": {"mssql_clustered": is_clustered},
  3177. }
  3178. else:
  3179. return self._default_or_error(
  3180. connection,
  3181. tablename,
  3182. owner,
  3183. ReflectionDefaults.pk_constraint,
  3184. **kw,
  3185. )
  3186. @reflection.cache
  3187. @_db_plus_owner
  3188. def get_foreign_keys(
  3189. self, connection, tablename, dbname, owner, schema, **kw
  3190. ):
  3191. # Foreign key constraints
  3192. s = (
  3193. text(
  3194. """\
  3195. WITH fk_info AS (
  3196. SELECT
  3197. ischema_ref_con.constraint_schema,
  3198. ischema_ref_con.constraint_name,
  3199. ischema_key_col.ordinal_position,
  3200. ischema_key_col.table_schema,
  3201. ischema_key_col.table_name,
  3202. ischema_ref_con.unique_constraint_schema,
  3203. ischema_ref_con.unique_constraint_name,
  3204. ischema_ref_con.match_option,
  3205. ischema_ref_con.update_rule,
  3206. ischema_ref_con.delete_rule,
  3207. ischema_key_col.column_name AS constrained_column
  3208. FROM
  3209. INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ischema_ref_con
  3210. INNER JOIN
  3211. INFORMATION_SCHEMA.KEY_COLUMN_USAGE ischema_key_col ON
  3212. ischema_key_col.table_schema = ischema_ref_con.constraint_schema
  3213. AND ischema_key_col.constraint_name =
  3214. ischema_ref_con.constraint_name
  3215. WHERE ischema_key_col.table_name = :tablename
  3216. AND ischema_key_col.table_schema = :owner
  3217. ),
  3218. constraint_info AS (
  3219. SELECT
  3220. ischema_key_col.constraint_schema,
  3221. ischema_key_col.constraint_name,
  3222. ischema_key_col.ordinal_position,
  3223. ischema_key_col.table_schema,
  3224. ischema_key_col.table_name,
  3225. ischema_key_col.column_name
  3226. FROM
  3227. INFORMATION_SCHEMA.KEY_COLUMN_USAGE ischema_key_col
  3228. ),
  3229. index_info AS (
  3230. SELECT
  3231. sys.schemas.name AS index_schema,
  3232. sys.indexes.name AS index_name,
  3233. sys.index_columns.key_ordinal AS ordinal_position,
  3234. sys.schemas.name AS table_schema,
  3235. sys.objects.name AS table_name,
  3236. sys.columns.name AS column_name
  3237. FROM
  3238. sys.indexes
  3239. INNER JOIN
  3240. sys.objects ON
  3241. sys.objects.object_id = sys.indexes.object_id
  3242. INNER JOIN
  3243. sys.schemas ON
  3244. sys.schemas.schema_id = sys.objects.schema_id
  3245. INNER JOIN
  3246. sys.index_columns ON
  3247. sys.index_columns.object_id = sys.objects.object_id
  3248. AND sys.index_columns.index_id = sys.indexes.index_id
  3249. INNER JOIN
  3250. sys.columns ON
  3251. sys.columns.object_id = sys.indexes.object_id
  3252. AND sys.columns.column_id = sys.index_columns.column_id
  3253. )
  3254. SELECT
  3255. fk_info.constraint_schema,
  3256. fk_info.constraint_name,
  3257. fk_info.ordinal_position,
  3258. fk_info.constrained_column,
  3259. constraint_info.table_schema AS referred_table_schema,
  3260. constraint_info.table_name AS referred_table_name,
  3261. constraint_info.column_name AS referred_column,
  3262. fk_info.match_option,
  3263. fk_info.update_rule,
  3264. fk_info.delete_rule
  3265. FROM
  3266. fk_info INNER JOIN constraint_info ON
  3267. constraint_info.constraint_schema =
  3268. fk_info.unique_constraint_schema
  3269. AND constraint_info.constraint_name =
  3270. fk_info.unique_constraint_name
  3271. AND constraint_info.ordinal_position = fk_info.ordinal_position
  3272. UNION
  3273. SELECT
  3274. fk_info.constraint_schema,
  3275. fk_info.constraint_name,
  3276. fk_info.ordinal_position,
  3277. fk_info.constrained_column,
  3278. index_info.table_schema AS referred_table_schema,
  3279. index_info.table_name AS referred_table_name,
  3280. index_info.column_name AS referred_column,
  3281. fk_info.match_option,
  3282. fk_info.update_rule,
  3283. fk_info.delete_rule
  3284. FROM
  3285. fk_info INNER JOIN index_info ON
  3286. index_info.index_schema = fk_info.unique_constraint_schema
  3287. AND index_info.index_name = fk_info.unique_constraint_name
  3288. AND index_info.ordinal_position = fk_info.ordinal_position
  3289. ORDER BY fk_info.constraint_schema, fk_info.constraint_name,
  3290. fk_info.ordinal_position
  3291. """
  3292. )
  3293. .bindparams(
  3294. sql.bindparam("tablename", tablename, ischema.CoerceUnicode()),
  3295. sql.bindparam("owner", owner, ischema.CoerceUnicode()),
  3296. )
  3297. .columns(
  3298. constraint_schema=sqltypes.Unicode(),
  3299. constraint_name=sqltypes.Unicode(),
  3300. table_schema=sqltypes.Unicode(),
  3301. table_name=sqltypes.Unicode(),
  3302. constrained_column=sqltypes.Unicode(),
  3303. referred_table_schema=sqltypes.Unicode(),
  3304. referred_table_name=sqltypes.Unicode(),
  3305. referred_column=sqltypes.Unicode(),
  3306. )
  3307. )
  3308. # group rows by constraint ID, to handle multi-column FKs
  3309. fkeys = util.defaultdict(
  3310. lambda: {
  3311. "name": None,
  3312. "constrained_columns": [],
  3313. "referred_schema": None,
  3314. "referred_table": None,
  3315. "referred_columns": [],
  3316. "options": {},
  3317. }
  3318. )
  3319. for r in connection.execute(s).all():
  3320. (
  3321. _, # constraint schema
  3322. rfknm,
  3323. _, # ordinal position
  3324. scol,
  3325. rschema,
  3326. rtbl,
  3327. rcol,
  3328. # TODO: we support match=<keyword> for foreign keys so
  3329. # we can support this also, PG has match=FULL for example
  3330. # but this seems to not be a valid value for SQL Server
  3331. _, # match rule
  3332. fkuprule,
  3333. fkdelrule,
  3334. ) = r
  3335. rec = fkeys[rfknm]
  3336. rec["name"] = rfknm
  3337. if fkuprule != "NO ACTION":
  3338. rec["options"]["onupdate"] = fkuprule
  3339. if fkdelrule != "NO ACTION":
  3340. rec["options"]["ondelete"] = fkdelrule
  3341. if not rec["referred_table"]:
  3342. rec["referred_table"] = rtbl
  3343. if schema is not None or owner != rschema:
  3344. if dbname:
  3345. rschema = dbname + "." + rschema
  3346. rec["referred_schema"] = rschema
  3347. local_cols, remote_cols = (
  3348. rec["constrained_columns"],
  3349. rec["referred_columns"],
  3350. )
  3351. local_cols.append(scol)
  3352. remote_cols.append(rcol)
  3353. if fkeys:
  3354. return list(fkeys.values())
  3355. else:
  3356. return self._default_or_error(
  3357. connection,
  3358. tablename,
  3359. owner,
  3360. ReflectionDefaults.foreign_keys,
  3361. **kw,
  3362. )