base.py 116 KB

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