base.py 116 KB

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