SQLAlchemy 2.1.0b1__cp313-cp313-win_arm64.whl

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