base.py 131 KB

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