SQLAlchemy 2.1.0b2__cp313-cp313t-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 (270) hide show
  1. sqlalchemy/__init__.py +298 -0
  2. sqlalchemy/connectors/__init__.py +18 -0
  3. sqlalchemy/connectors/aioodbc.py +171 -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 +89 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4166 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +285 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +220 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +126 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +698 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +226 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +214 -0
  21. sqlalchemy/dialects/mysql/base.py +3877 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +106 -0
  23. sqlalchemy/dialects/mysql/dml.py +279 -0
  24. sqlalchemy/dialects/mysql/enumerated.py +277 -0
  25. sqlalchemy/dialects/mysql/expression.py +146 -0
  26. sqlalchemy/dialects/mysql/json.py +92 -0
  27. sqlalchemy/dialects/mysql/mariadb.py +67 -0
  28. sqlalchemy/dialects/mysql/mariadbconnector.py +330 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +296 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +312 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +157 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +156 -0
  34. sqlalchemy/dialects/mysql/reflection.py +724 -0
  35. sqlalchemy/dialects/mysql/reserved_words.py +570 -0
  36. sqlalchemy/dialects/mysql/types.py +845 -0
  37. sqlalchemy/dialects/oracle/__init__.py +85 -0
  38. sqlalchemy/dialects/oracle/base.py +3977 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1601 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +158 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +909 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +368 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +171 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +229 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1323 -0
  50. sqlalchemy/dialects/postgresql/base.py +5789 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +593 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +423 -0
  55. sqlalchemy/dialects/postgresql/json.py +408 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +521 -0
  57. sqlalchemy/dialects/postgresql/operators.py +130 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +670 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +344 -0
  60. sqlalchemy/dialects/postgresql/provision.py +184 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +799 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +61 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +57 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +321 -0
  68. sqlalchemy/dialects/sqlite/base.py +3063 -0
  69. sqlalchemy/dialects/sqlite/dml.py +279 -0
  70. sqlalchemy/dialects/sqlite/json.py +100 -0
  71. sqlalchemy/dialects/sqlite/provision.py +229 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +161 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +754 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp313t-win_arm64.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp313t-win_arm64.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +633 -0
  80. sqlalchemy/engine/_row_cy.cp313t-win_arm64.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp313t-win_arm64.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3354 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2421 -0
  88. sqlalchemy/engine/default.py +2402 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3495 -0
  91. sqlalchemy/engine/mock.py +134 -0
  92. sqlalchemy/engine/processors.py +82 -0
  93. sqlalchemy/engine/reflection.py +2100 -0
  94. sqlalchemy/engine/result.py +1966 -0
  95. sqlalchemy/engine/row.py +397 -0
  96. sqlalchemy/engine/strategies.py +16 -0
  97. sqlalchemy/engine/url.py +922 -0
  98. sqlalchemy/engine/util.py +156 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +674 -0
  102. sqlalchemy/event/base.py +472 -0
  103. sqlalchemy/event/legacy.py +258 -0
  104. sqlalchemy/event/registry.py +390 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +922 -0
  107. sqlalchemy/ext/__init__.py +11 -0
  108. sqlalchemy/ext/associationproxy.py +2072 -0
  109. sqlalchemy/ext/asyncio/__init__.py +29 -0
  110. sqlalchemy/ext/asyncio/base.py +281 -0
  111. sqlalchemy/ext/asyncio/engine.py +1487 -0
  112. sqlalchemy/ext/asyncio/exc.py +21 -0
  113. sqlalchemy/ext/asyncio/result.py +994 -0
  114. sqlalchemy/ext/asyncio/scoping.py +1679 -0
  115. sqlalchemy/ext/asyncio/session.py +2007 -0
  116. sqlalchemy/ext/automap.py +1701 -0
  117. sqlalchemy/ext/baked.py +559 -0
  118. sqlalchemy/ext/compiler.py +600 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +560 -0
  121. sqlalchemy/ext/horizontal_shard.py +481 -0
  122. sqlalchemy/ext/hybrid.py +1877 -0
  123. sqlalchemy/ext/indexable.py +364 -0
  124. sqlalchemy/ext/instrumentation.py +450 -0
  125. sqlalchemy/ext/mutable.py +1081 -0
  126. sqlalchemy/ext/orderinglist.py +439 -0
  127. sqlalchemy/ext/serializer.py +185 -0
  128. sqlalchemy/future/__init__.py +16 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +174 -0
  131. sqlalchemy/log.py +283 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +179 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +976 -0
  137. sqlalchemy/orm/bulk_persistence.py +2152 -0
  138. sqlalchemy/orm/clsregistry.py +582 -0
  139. sqlalchemy/orm/collections.py +1568 -0
  140. sqlalchemy/orm/context.py +3471 -0
  141. sqlalchemy/orm/decl_api.py +2280 -0
  142. sqlalchemy/orm/decl_base.py +2309 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +307 -0
  146. sqlalchemy/orm/evaluator.py +379 -0
  147. sqlalchemy/orm/events.py +3386 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +746 -0
  151. sqlalchemy/orm/interfaces.py +1589 -0
  152. sqlalchemy/orm/loading.py +1684 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4411 -0
  155. sqlalchemy/orm/path_registry.py +829 -0
  156. sqlalchemy/orm/persistence.py +1789 -0
  157. sqlalchemy/orm/properties.py +973 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3570 -0
  160. sqlalchemy/orm/scoping.py +2232 -0
  161. sqlalchemy/orm/session.py +5403 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3492 -0
  165. sqlalchemy/orm/strategy_options.py +2562 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +798 -0
  168. sqlalchemy/orm/util.py +2438 -0
  169. sqlalchemy/orm/writeonly.py +694 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1522 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +582 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +74 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +397 -0
  178. sqlalchemy/sql/_dml_constructors.py +132 -0
  179. sqlalchemy/sql/_elements_constructors.py +2164 -0
  180. sqlalchemy/sql/_orm_types.py +20 -0
  181. sqlalchemy/sql/_selectable_constructors.py +840 -0
  182. sqlalchemy/sql/_typing.py +487 -0
  183. sqlalchemy/sql/_util_cy.cp313t-win_arm64.pyd +0 -0
  184. sqlalchemy/sql/_util_cy.py +127 -0
  185. sqlalchemy/sql/annotation.py +590 -0
  186. sqlalchemy/sql/base.py +2699 -0
  187. sqlalchemy/sql/cache_key.py +1066 -0
  188. sqlalchemy/sql/coercions.py +1373 -0
  189. sqlalchemy/sql/compiler.py +8327 -0
  190. sqlalchemy/sql/crud.py +1815 -0
  191. sqlalchemy/sql/ddl.py +1928 -0
  192. sqlalchemy/sql/default_comparator.py +654 -0
  193. sqlalchemy/sql/dml.py +1977 -0
  194. sqlalchemy/sql/elements.py +6033 -0
  195. sqlalchemy/sql/events.py +458 -0
  196. sqlalchemy/sql/expression.py +172 -0
  197. sqlalchemy/sql/functions.py +2305 -0
  198. sqlalchemy/sql/lambdas.py +1443 -0
  199. sqlalchemy/sql/naming.py +209 -0
  200. sqlalchemy/sql/operators.py +2897 -0
  201. sqlalchemy/sql/roles.py +332 -0
  202. sqlalchemy/sql/schema.py +6703 -0
  203. sqlalchemy/sql/selectable.py +7553 -0
  204. sqlalchemy/sql/sqltypes.py +4093 -0
  205. sqlalchemy/sql/traversals.py +1042 -0
  206. sqlalchemy/sql/type_api.py +2446 -0
  207. sqlalchemy/sql/util.py +1495 -0
  208. sqlalchemy/sql/visitors.py +1157 -0
  209. sqlalchemy/testing/__init__.py +96 -0
  210. sqlalchemy/testing/assertions.py +1007 -0
  211. sqlalchemy/testing/assertsql.py +519 -0
  212. sqlalchemy/testing/asyncio.py +128 -0
  213. sqlalchemy/testing/config.py +440 -0
  214. sqlalchemy/testing/engines.py +483 -0
  215. sqlalchemy/testing/entities.py +117 -0
  216. sqlalchemy/testing/exclusions.py +476 -0
  217. sqlalchemy/testing/fixtures/__init__.py +30 -0
  218. sqlalchemy/testing/fixtures/base.py +384 -0
  219. sqlalchemy/testing/fixtures/mypy.py +247 -0
  220. sqlalchemy/testing/fixtures/orm.py +227 -0
  221. sqlalchemy/testing/fixtures/sql.py +538 -0
  222. sqlalchemy/testing/pickleable.py +155 -0
  223. sqlalchemy/testing/plugin/__init__.py +6 -0
  224. sqlalchemy/testing/plugin/bootstrap.py +51 -0
  225. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  226. sqlalchemy/testing/plugin/pytestplugin.py +892 -0
  227. sqlalchemy/testing/profiling.py +329 -0
  228. sqlalchemy/testing/provision.py +613 -0
  229. sqlalchemy/testing/requirements.py +1978 -0
  230. sqlalchemy/testing/schema.py +198 -0
  231. sqlalchemy/testing/suite/__init__.py +19 -0
  232. sqlalchemy/testing/suite/test_cte.py +237 -0
  233. sqlalchemy/testing/suite/test_ddl.py +420 -0
  234. sqlalchemy/testing/suite/test_dialect.py +776 -0
  235. sqlalchemy/testing/suite/test_insert.py +630 -0
  236. sqlalchemy/testing/suite/test_reflection.py +3557 -0
  237. sqlalchemy/testing/suite/test_results.py +660 -0
  238. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  239. sqlalchemy/testing/suite/test_select.py +2112 -0
  240. sqlalchemy/testing/suite/test_sequence.py +317 -0
  241. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  242. sqlalchemy/testing/suite/test_types.py +2271 -0
  243. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  244. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  245. sqlalchemy/testing/util.py +535 -0
  246. sqlalchemy/testing/warnings.py +52 -0
  247. sqlalchemy/types.py +76 -0
  248. sqlalchemy/util/__init__.py +158 -0
  249. sqlalchemy/util/_collections.py +688 -0
  250. sqlalchemy/util/_collections_cy.cp313t-win_arm64.pyd +0 -0
  251. sqlalchemy/util/_collections_cy.pxd +8 -0
  252. sqlalchemy/util/_collections_cy.py +516 -0
  253. sqlalchemy/util/_has_cython.py +46 -0
  254. sqlalchemy/util/_immutabledict_cy.cp313t-win_arm64.pyd +0 -0
  255. sqlalchemy/util/_immutabledict_cy.py +240 -0
  256. sqlalchemy/util/compat.py +299 -0
  257. sqlalchemy/util/concurrency.py +322 -0
  258. sqlalchemy/util/cython.py +79 -0
  259. sqlalchemy/util/deprecations.py +401 -0
  260. sqlalchemy/util/langhelpers.py +2320 -0
  261. sqlalchemy/util/preloaded.py +152 -0
  262. sqlalchemy/util/queue.py +304 -0
  263. sqlalchemy/util/tool_support.py +201 -0
  264. sqlalchemy/util/topological.py +120 -0
  265. sqlalchemy/util/typing.py +711 -0
  266. sqlalchemy-2.1.0b2.dist-info/METADATA +269 -0
  267. sqlalchemy-2.1.0b2.dist-info/RECORD +270 -0
  268. sqlalchemy-2.1.0b2.dist-info/WHEEL +5 -0
  269. sqlalchemy-2.1.0b2.dist-info/licenses/LICENSE +19 -0
  270. sqlalchemy-2.1.0b2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,698 @@
1
+ # dialects/mssql/pyodbc.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
+ r"""
10
+ .. dialect:: mssql+pyodbc
11
+ :name: PyODBC
12
+ :dbapi: pyodbc
13
+ :connectstring: mssql+pyodbc://<username>:<password>@<dsnname>
14
+ :url: https://pypi.org/project/pyodbc/
15
+
16
+ Connecting to PyODBC
17
+ --------------------
18
+
19
+ The URL here is to be translated to PyODBC connection strings, as
20
+ detailed in `ConnectionStrings <https://code.google.com/p/pyodbc/wiki/ConnectionStrings>`_.
21
+
22
+ DSN Connections
23
+ ^^^^^^^^^^^^^^^
24
+
25
+ A DSN connection in ODBC means that a pre-existing ODBC datasource is
26
+ configured on the client machine. The application then specifies the name
27
+ of this datasource, which encompasses details such as the specific ODBC driver
28
+ in use as well as the network address of the database. Assuming a datasource
29
+ is configured on the client, a basic DSN-based connection looks like::
30
+
31
+ engine = create_engine("mssql+pyodbc://scott:tiger@some_dsn")
32
+
33
+ Which above, will pass the following connection string to PyODBC:
34
+
35
+ .. sourcecode:: text
36
+
37
+ DSN=some_dsn;UID=scott;PWD=tiger
38
+
39
+ If the username and password are omitted, the DSN form will also add
40
+ the ``Trusted_Connection=yes`` directive to the ODBC string.
41
+
42
+ Hostname Connections
43
+ ^^^^^^^^^^^^^^^^^^^^
44
+
45
+ Hostname-based connections are also supported by pyodbc. These are often
46
+ easier to use than a DSN and have the additional advantage that the specific
47
+ database name to connect towards may be specified locally in the URL, rather
48
+ than it being fixed as part of a datasource configuration.
49
+
50
+ When using a hostname connection, the driver name must also be specified in the
51
+ query parameters of the URL. As these names usually have spaces in them, the
52
+ name must be URL encoded which means using plus signs for spaces::
53
+
54
+ engine = create_engine(
55
+ "mssql+pyodbc://scott:tiger@myhost:port/databasename?driver=ODBC+Driver+17+for+SQL+Server"
56
+ )
57
+
58
+ The ``driver`` keyword is significant to the pyodbc dialect and must be
59
+ specified in lowercase.
60
+
61
+ Any other names passed in the query string are passed through in the pyodbc
62
+ connect string, such as ``authentication``, ``TrustServerCertificate``, etc.
63
+ Multiple keyword arguments must be separated by an ampersand (``&``); these
64
+ will be translated to semicolons when the pyodbc connect string is generated
65
+ internally::
66
+
67
+ e = create_engine(
68
+ "mssql+pyodbc://scott:tiger@mssql2017:1433/test?"
69
+ "driver=ODBC+Driver+18+for+SQL+Server&TrustServerCertificate=yes"
70
+ "&authentication=ActiveDirectoryIntegrated"
71
+ )
72
+
73
+ The equivalent URL can be constructed using :class:`_sa.engine.URL`::
74
+
75
+ from sqlalchemy.engine import URL
76
+
77
+ connection_url = URL.create(
78
+ "mssql+pyodbc",
79
+ username="scott",
80
+ password="tiger",
81
+ host="mssql2017",
82
+ port=1433,
83
+ database="test",
84
+ query={
85
+ "driver": "ODBC Driver 18 for SQL Server",
86
+ "TrustServerCertificate": "yes",
87
+ "authentication": "ActiveDirectoryIntegrated",
88
+ },
89
+ )
90
+
91
+ Pass through exact Pyodbc string
92
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
93
+
94
+ A PyODBC connection string can also be sent in pyodbc's format directly, as
95
+ specified in `the PyODBC documentation
96
+ <https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-databases>`_,
97
+ using the parameter ``odbc_connect``. A :class:`_sa.engine.URL` object
98
+ can help make this easier::
99
+
100
+ from sqlalchemy.engine import URL
101
+
102
+ connection_string = "DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password"
103
+ connection_url = URL.create(
104
+ "mssql+pyodbc", query={"odbc_connect": connection_string}
105
+ )
106
+
107
+ engine = create_engine(connection_url)
108
+
109
+ .. _mssql_pyodbc_access_tokens:
110
+
111
+ Connecting to databases with access tokens
112
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
113
+
114
+ Some database servers are set up to only accept access tokens for login. For
115
+ example, SQL Server allows the use of Azure Active Directory tokens to connect
116
+ to databases. This requires creating a credential object using the
117
+ ``azure-identity`` library. More information about the authentication step can be
118
+ found in `Microsoft's documentation
119
+ <https://docs.microsoft.com/en-us/azure/developer/python/azure-sdk-authenticate?tabs=bash>`_.
120
+
121
+ After getting an engine, the credentials need to be sent to ``pyodbc.connect``
122
+ each time a connection is requested. One way to do this is to set up an event
123
+ listener on the engine that adds the credential token to the dialect's connect
124
+ call. This is discussed more generally in :ref:`engines_dynamic_tokens`. For
125
+ SQL Server in particular, this is passed as an ODBC connection attribute with
126
+ a data structure `described by Microsoft
127
+ <https://docs.microsoft.com/en-us/sql/connect/odbc/using-azure-active-directory#authenticating-with-an-access-token>`_.
128
+
129
+ The following code snippet will create an engine that connects to an Azure SQL
130
+ database using Azure credentials::
131
+
132
+ import struct
133
+ from sqlalchemy import create_engine, event
134
+ from sqlalchemy.engine.url import URL
135
+ from azure import identity
136
+
137
+ # Connection option for access tokens, as defined in msodbcsql.h
138
+ SQL_COPT_SS_ACCESS_TOKEN = 1256
139
+ TOKEN_URL = "https://database.windows.net/" # The token URL for any Azure SQL database
140
+
141
+ connection_string = "mssql+pyodbc://@my-server.database.windows.net/myDb?driver=ODBC+Driver+17+for+SQL+Server"
142
+
143
+ engine = create_engine(connection_string)
144
+
145
+ azure_credentials = identity.DefaultAzureCredential()
146
+
147
+
148
+ @event.listens_for(engine, "do_connect")
149
+ def provide_token(dialect, conn_rec, cargs, cparams):
150
+ # remove the "Trusted_Connection" parameter that SQLAlchemy adds
151
+ cargs[0] = cargs[0].replace(";Trusted_Connection=Yes", "")
152
+
153
+ # create token credential
154
+ raw_token = azure_credentials.get_token(TOKEN_URL).token.encode(
155
+ "utf-16-le"
156
+ )
157
+ token_struct = struct.pack(
158
+ f"<I{len(raw_token)}s", len(raw_token), raw_token
159
+ )
160
+
161
+ # apply it to keyword arguments
162
+ cparams["attrs_before"] = {SQL_COPT_SS_ACCESS_TOKEN: token_struct}
163
+
164
+ .. tip::
165
+
166
+ The ``Trusted_Connection`` token is currently added by the SQLAlchemy
167
+ pyodbc dialect when no username or password is present. This needs
168
+ to be removed per Microsoft's
169
+ `documentation for Azure access tokens
170
+ <https://docs.microsoft.com/en-us/sql/connect/odbc/using-azure-active-directory#authenticating-with-an-access-token>`_,
171
+ stating that a connection string when using an access token must not contain
172
+ ``UID``, ``PWD``, ``Authentication`` or ``Trusted_Connection`` parameters.
173
+
174
+ .. _azure_synapse_ignore_no_transaction_on_rollback:
175
+
176
+ Avoiding transaction-related exceptions on Azure Synapse Analytics
177
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
178
+
179
+ Azure Synapse Analytics has a significant difference in its transaction
180
+ handling compared to plain SQL Server; in some cases an error within a Synapse
181
+ transaction can cause it to be arbitrarily terminated on the server side, which
182
+ then causes the DBAPI ``.rollback()`` method (as well as ``.commit()``) to
183
+ fail. The issue prevents the usual DBAPI contract of allowing ``.rollback()``
184
+ to pass silently if no transaction is present as the driver does not expect
185
+ this condition. The symptom of this failure is an exception with a message
186
+ resembling 'No corresponding transaction found. (111214)' when attempting to
187
+ emit a ``.rollback()`` after an operation had a failure of some kind.
188
+
189
+ This specific case can be handled by passing ``ignore_no_transaction_on_rollback=True`` to
190
+ the SQL Server dialect via the :func:`_sa.create_engine` function as follows::
191
+
192
+ engine = create_engine(
193
+ connection_url, ignore_no_transaction_on_rollback=True
194
+ )
195
+
196
+ Using the above parameter, the dialect will catch ``ProgrammingError``
197
+ exceptions raised during ``connection.rollback()`` and emit a warning
198
+ if the error message contains code ``111214``, however will not raise
199
+ an exception.
200
+
201
+ .. versionadded:: 1.4.40 Added the
202
+ ``ignore_no_transaction_on_rollback=True`` parameter.
203
+
204
+ Enable autocommit for Azure SQL Data Warehouse (DW) connections
205
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
206
+
207
+ Azure SQL Data Warehouse does not support transactions,
208
+ and that can cause problems with SQLAlchemy's "autobegin" (and implicit
209
+ commit/rollback) behavior. We can avoid these problems by enabling autocommit
210
+ at both the pyodbc and engine levels::
211
+
212
+ connection_url = sa.engine.URL.create(
213
+ "mssql+pyodbc",
214
+ username="scott",
215
+ password="tiger",
216
+ host="dw.azure.example.com",
217
+ database="mydb",
218
+ query={
219
+ "driver": "ODBC Driver 17 for SQL Server",
220
+ "autocommit": "True",
221
+ },
222
+ )
223
+
224
+ engine = create_engine(connection_url).execution_options(
225
+ isolation_level="AUTOCOMMIT"
226
+ )
227
+
228
+ Avoiding sending large string parameters as TEXT/NTEXT
229
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
230
+
231
+ By default, for historical reasons, Microsoft's ODBC drivers for SQL Server
232
+ send long string parameters (greater than 4000 SBCS characters or 2000 Unicode
233
+ characters) as TEXT/NTEXT values. TEXT and NTEXT have been deprecated for many
234
+ years and are starting to cause compatibility issues with newer versions of
235
+ SQL_Server/Azure. For example, see `this
236
+ issue <https://github.com/mkleehammer/pyodbc/issues/835>`_.
237
+
238
+ Starting with ODBC Driver 18 for SQL Server we can override the legacy
239
+ behavior and pass long strings as varchar(max)/nvarchar(max) using the
240
+ ``LongAsMax=Yes`` connection string parameter::
241
+
242
+ connection_url = sa.engine.URL.create(
243
+ "mssql+pyodbc",
244
+ username="scott",
245
+ password="tiger",
246
+ host="mssqlserver.example.com",
247
+ database="mydb",
248
+ query={
249
+ "driver": "ODBC Driver 18 for SQL Server",
250
+ "LongAsMax": "Yes",
251
+ },
252
+ )
253
+
254
+ Pyodbc Pooling / connection close behavior
255
+ ------------------------------------------
256
+
257
+ PyODBC uses internal `pooling
258
+ <https://github.com/mkleehammer/pyodbc/wiki/The-pyodbc-Module#pooling>`_ by
259
+ default, which means connections will be longer lived than they are within
260
+ SQLAlchemy itself. As SQLAlchemy has its own pooling behavior, it is often
261
+ preferable to disable this behavior. This behavior can only be disabled
262
+ globally at the PyODBC module level, **before** any connections are made::
263
+
264
+ import pyodbc
265
+
266
+ pyodbc.pooling = False
267
+
268
+ # don't use the engine before pooling is set to False
269
+ engine = create_engine("mssql+pyodbc://user:pass@dsn")
270
+
271
+ If this variable is left at its default value of ``True``, **the application
272
+ will continue to maintain active database connections**, even when the
273
+ SQLAlchemy engine itself fully discards a connection or if the engine is
274
+ disposed.
275
+
276
+ .. seealso::
277
+
278
+ `pooling <https://github.com/mkleehammer/pyodbc/wiki/The-pyodbc-Module#pooling>`_ -
279
+ in the PyODBC documentation.
280
+
281
+ Driver / Unicode Support
282
+ -------------------------
283
+
284
+ PyODBC works best with Microsoft ODBC drivers, particularly in the area
285
+ of Unicode support on both Python 2 and Python 3.
286
+
287
+ Using the FreeTDS ODBC drivers on Linux or OSX with PyODBC is **not**
288
+ recommended; there have been historically many Unicode-related issues
289
+ in this area, including before Microsoft offered ODBC drivers for Linux
290
+ and OSX. Now that Microsoft offers drivers for all platforms, for
291
+ PyODBC support these are recommended. FreeTDS remains relevant for
292
+ non-ODBC drivers such as pymssql where it works very well.
293
+
294
+
295
+ Rowcount Support
296
+ ----------------
297
+
298
+ Previous limitations with the SQLAlchemy ORM's "versioned rows" feature with
299
+ Pyodbc have been resolved as of SQLAlchemy 2.0.5. See the notes at
300
+ :ref:`mssql_rowcount_versioning`.
301
+
302
+ .. _mssql_pyodbc_fastexecutemany:
303
+
304
+ Fast Executemany Mode
305
+ ---------------------
306
+
307
+ The PyODBC driver includes support for a "fast executemany" mode of execution
308
+ which greatly reduces round trips for a DBAPI ``executemany()`` call when using
309
+ Microsoft ODBC drivers, for **limited size batches that fit in memory**. The
310
+ feature is enabled by setting the attribute ``.fast_executemany`` on the DBAPI
311
+ cursor when an executemany call is to be used. The SQLAlchemy PyODBC SQL
312
+ Server dialect supports this parameter by passing the
313
+ ``fast_executemany`` parameter to
314
+ :func:`_sa.create_engine` , when using the **Microsoft ODBC driver only**::
315
+
316
+ engine = create_engine(
317
+ "mssql+pyodbc://scott:tiger@mssql2017:1433/test?driver=ODBC+Driver+17+for+SQL+Server",
318
+ fast_executemany=True,
319
+ )
320
+
321
+ .. versionchanged:: 2.0.9 - the ``fast_executemany`` parameter now has its
322
+ intended effect of this PyODBC feature taking effect for all INSERT
323
+ statements that are executed with multiple parameter sets, which don't
324
+ include RETURNING. Previously, SQLAlchemy 2.0's :term:`insertmanyvalues`
325
+ feature would cause ``fast_executemany`` to not be used in most cases
326
+ even if specified.
327
+
328
+ .. seealso::
329
+
330
+ `fast executemany <https://github.com/mkleehammer/pyodbc/wiki/Features-beyond-the-DB-API#fast_executemany>`_
331
+ - on github
332
+
333
+ .. _mssql_pyodbc_setinputsizes:
334
+
335
+ Setinputsizes Support
336
+ -----------------------
337
+
338
+ As of version 2.0, the pyodbc ``cursor.setinputsizes()`` method is used for
339
+ all statement executions, except for ``cursor.executemany()`` calls when
340
+ fast_executemany=True where it is not supported (assuming
341
+ :ref:`insertmanyvalues <engine_insertmanyvalues>` is kept enabled,
342
+ "fastexecutemany" will not take place for INSERT statements in any case).
343
+
344
+ The use of ``cursor.setinputsizes()`` can be disabled by passing
345
+ ``use_setinputsizes=False`` to :func:`_sa.create_engine`.
346
+
347
+ When ``use_setinputsizes`` is left at its default of ``True``, the
348
+ specific per-type symbols passed to ``cursor.setinputsizes()`` can be
349
+ programmatically customized using the :meth:`.DialectEvents.do_setinputsizes`
350
+ hook. See that method for usage examples.
351
+
352
+ .. versionchanged:: 2.0 The mssql+pyodbc dialect now defaults to using
353
+ ``use_setinputsizes=True`` for all statement executions with the exception of
354
+ cursor.executemany() calls when fast_executemany=True. The behavior can
355
+ be turned off by passing ``use_setinputsizes=False`` to
356
+ :func:`_sa.create_engine`.
357
+
358
+ """ # noqa
359
+
360
+
361
+ import datetime
362
+ import decimal
363
+ import re
364
+ import struct
365
+
366
+ from .base import _MSDateTime
367
+ from .base import _MSUnicode
368
+ from .base import _MSUnicodeText
369
+ from .base import BINARY
370
+ from .base import DATETIMEOFFSET
371
+ from .base import MSDialect
372
+ from .base import VARBINARY
373
+ from .json import JSON as _MSJson
374
+ from .json import JSONIndexType as _MSJsonIndexType
375
+ from .json import JSONPathType as _MSJsonPathType
376
+ from ... import exc
377
+ from ... import types as sqltypes
378
+ from ... import util
379
+ from ...connectors.pyodbc import PyODBCConnector
380
+
381
+
382
+ class _ms_numeric_pyodbc:
383
+ """Turns Decimals with adjusted() < 0 or > 7 into strings.
384
+
385
+ The routines here are needed for older pyodbc versions
386
+ as well as current mxODBC versions.
387
+
388
+ """
389
+
390
+ def bind_processor(self, dialect):
391
+ super_process = super().bind_processor(dialect)
392
+
393
+ if not dialect._need_decimal_fix:
394
+ return super_process
395
+
396
+ def process(value):
397
+ if self.asdecimal and isinstance(value, decimal.Decimal):
398
+ adjusted = value.adjusted()
399
+ if adjusted < 0:
400
+ return self._small_dec_to_string(value)
401
+ elif adjusted > 7:
402
+ return self._large_dec_to_string(value)
403
+
404
+ if super_process:
405
+ return super_process(value)
406
+ else:
407
+ return value
408
+
409
+ return process
410
+
411
+ # these routines needed for older versions of pyodbc.
412
+ # as of 2.1.8 this logic is integrated.
413
+
414
+ def _small_dec_to_string(self, value):
415
+ return "%s0.%s%s" % (
416
+ (value < 0 and "-" or ""),
417
+ "0" * (abs(value.adjusted()) - 1),
418
+ "".join([str(nint) for nint in value.as_tuple()[1]]),
419
+ )
420
+
421
+ def _large_dec_to_string(self, value):
422
+ _int = value.as_tuple()[1]
423
+ if "E" in str(value):
424
+ result = "%s%s%s" % (
425
+ (value < 0 and "-" or ""),
426
+ "".join([str(s) for s in _int]),
427
+ "0" * (value.adjusted() - (len(_int) - 1)),
428
+ )
429
+ else:
430
+ if (len(_int) - 1) > value.adjusted():
431
+ result = "%s%s.%s" % (
432
+ (value < 0 and "-" or ""),
433
+ "".join([str(s) for s in _int][0 : value.adjusted() + 1]),
434
+ "".join([str(s) for s in _int][value.adjusted() + 1 :]),
435
+ )
436
+ else:
437
+ result = "%s%s" % (
438
+ (value < 0 and "-" or ""),
439
+ "".join([str(s) for s in _int][0 : value.adjusted() + 1]),
440
+ )
441
+ return result
442
+
443
+
444
+ class _MSNumeric_pyodbc(_ms_numeric_pyodbc, sqltypes.Numeric):
445
+ pass
446
+
447
+
448
+ class _MSFloat_pyodbc(_ms_numeric_pyodbc, sqltypes.Float):
449
+ pass
450
+
451
+
452
+ class _ms_binary_pyodbc:
453
+ """Wraps binary values in dialect-specific Binary wrapper.
454
+ If the value is null, return a pyodbc-specific BinaryNull
455
+ object to prevent pyODBC [and FreeTDS] from defaulting binary
456
+ NULL types to SQLWCHAR and causing implicit conversion errors.
457
+ """
458
+
459
+ def bind_processor(self, dialect):
460
+ if dialect.dbapi is None:
461
+ return None
462
+
463
+ DBAPIBinary = dialect.dbapi.Binary
464
+
465
+ def process(value):
466
+ if value is not None:
467
+ return DBAPIBinary(value)
468
+ else:
469
+ # pyodbc-specific
470
+ return dialect.dbapi.BinaryNull
471
+
472
+ return process
473
+
474
+
475
+ class _ODBCDateTimeBindProcessor:
476
+ """Add bind processors to handle datetimeoffset behaviors"""
477
+
478
+ has_tz = False
479
+
480
+ def bind_processor(self, dialect):
481
+ def process(value):
482
+ if value is None:
483
+ return None
484
+ elif isinstance(value, str):
485
+ # if a string was passed directly, allow it through
486
+ return value
487
+ elif not value.tzinfo or (not self.timezone and not self.has_tz):
488
+ # for DateTime(timezone=False)
489
+ return value
490
+ else:
491
+ # for DATETIMEOFFSET or DateTime(timezone=True)
492
+ #
493
+ # Convert to string format required by T-SQL
494
+ dto_string = value.strftime("%Y-%m-%d %H:%M:%S.%f %z")
495
+ # offset needs a colon, e.g., -0700 -> -07:00
496
+ # "UTC offset in the form (+-)HHMM[SS[.ffffff]]"
497
+ # backend currently rejects seconds / fractional seconds
498
+ dto_string = re.sub(
499
+ r"([\+\-]\d{2})([\d\.]+)$", r"\1:\2", dto_string
500
+ )
501
+ return dto_string
502
+
503
+ return process
504
+
505
+
506
+ class _ODBCDateTime(_ODBCDateTimeBindProcessor, _MSDateTime):
507
+ pass
508
+
509
+
510
+ class _ODBCDATETIMEOFFSET(_ODBCDateTimeBindProcessor, DATETIMEOFFSET):
511
+ has_tz = True
512
+
513
+
514
+ class _VARBINARY_pyodbc(_ms_binary_pyodbc, VARBINARY):
515
+ pass
516
+
517
+
518
+ class _BINARY_pyodbc(_ms_binary_pyodbc, BINARY):
519
+ pass
520
+
521
+
522
+ class _String_pyodbc(sqltypes.String):
523
+ def get_dbapi_type(self, dbapi):
524
+ if self.length in (None, "max") or self.length >= 2000:
525
+ return (dbapi.SQL_VARCHAR, 0, 0)
526
+ else:
527
+ return dbapi.SQL_VARCHAR
528
+
529
+
530
+ class _Unicode_pyodbc(_MSUnicode):
531
+ def get_dbapi_type(self, dbapi):
532
+ if self.length in (None, "max") or self.length >= 2000:
533
+ return (dbapi.SQL_WVARCHAR, 0, 0)
534
+ else:
535
+ return dbapi.SQL_WVARCHAR
536
+
537
+
538
+ class _UnicodeText_pyodbc(_MSUnicodeText):
539
+ def get_dbapi_type(self, dbapi):
540
+ if self.length in (None, "max") or self.length >= 2000:
541
+ return (dbapi.SQL_WVARCHAR, 0, 0)
542
+ else:
543
+ return dbapi.SQL_WVARCHAR
544
+
545
+
546
+ class _JSON_pyodbc(_MSJson):
547
+ def get_dbapi_type(self, dbapi):
548
+ return (dbapi.SQL_WVARCHAR, 0, 0)
549
+
550
+
551
+ class _JSONIndexType_pyodbc(_MSJsonIndexType):
552
+ def get_dbapi_type(self, dbapi):
553
+ return dbapi.SQL_WVARCHAR
554
+
555
+
556
+ class _JSONPathType_pyodbc(_MSJsonPathType):
557
+ def get_dbapi_type(self, dbapi):
558
+ return dbapi.SQL_WVARCHAR
559
+
560
+
561
+ class MSDialect_pyodbc(PyODBCConnector, MSDialect):
562
+ supports_statement_cache = True
563
+
564
+ scope_identity_must_be_embedded = True
565
+
566
+ # note this parameter is no longer used by the ORM or default dialect
567
+ # see #9414
568
+ supports_sane_rowcount_returning = False
569
+
570
+ colspecs = util.update_copy(
571
+ MSDialect.colspecs,
572
+ {
573
+ sqltypes.Numeric: _MSNumeric_pyodbc,
574
+ sqltypes.Float: _MSFloat_pyodbc,
575
+ BINARY: _BINARY_pyodbc,
576
+ # support DateTime(timezone=True)
577
+ sqltypes.DateTime: _ODBCDateTime,
578
+ DATETIMEOFFSET: _ODBCDATETIMEOFFSET,
579
+ # SQL Server dialect has a VARBINARY that is just to support
580
+ # "deprecate_large_types" w/ VARBINARY(max), but also we must
581
+ # handle the usual SQL standard VARBINARY
582
+ VARBINARY: _VARBINARY_pyodbc,
583
+ sqltypes.VARBINARY: _VARBINARY_pyodbc,
584
+ sqltypes.LargeBinary: _VARBINARY_pyodbc,
585
+ sqltypes.String: _String_pyodbc,
586
+ sqltypes.Unicode: _Unicode_pyodbc,
587
+ sqltypes.UnicodeText: _UnicodeText_pyodbc,
588
+ sqltypes.JSON: _JSON_pyodbc,
589
+ sqltypes.JSON.JSONIndexType: _JSONIndexType_pyodbc,
590
+ sqltypes.JSON.JSONPathType: _JSONPathType_pyodbc,
591
+ # this excludes Enum from the string/VARCHAR thing for now
592
+ # it looks like Enum's adaptation doesn't really support the
593
+ # String type itself having a dialect-level impl
594
+ sqltypes.Enum: sqltypes.Enum,
595
+ },
596
+ )
597
+
598
+ def __init__(
599
+ self,
600
+ fast_executemany=False,
601
+ use_setinputsizes=True,
602
+ **params,
603
+ ):
604
+ super().__init__(use_setinputsizes=use_setinputsizes, **params)
605
+ self.use_scope_identity = (
606
+ self.use_scope_identity
607
+ and self.dbapi
608
+ and hasattr(self.dbapi.Cursor, "nextset")
609
+ )
610
+ self._need_decimal_fix = self.dbapi and self._dbapi_version() < (
611
+ 2,
612
+ 1,
613
+ 8,
614
+ )
615
+ self.fast_executemany = fast_executemany
616
+ if fast_executemany:
617
+ self.use_insertmanyvalues_wo_returning = False
618
+
619
+ def _get_server_version_info(self, connection):
620
+ try:
621
+ # "Version of the instance of SQL Server, in the form
622
+ # of 'major.minor.build.revision'"
623
+ raw = connection.exec_driver_sql(
624
+ "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)"
625
+ ).scalar()
626
+ except exc.DBAPIError:
627
+ # SQL Server docs indicate this function isn't present prior to
628
+ # 2008. Before we had the VARCHAR cast above, pyodbc would also
629
+ # fail on this query.
630
+ return super()._get_server_version_info(connection)
631
+ else:
632
+ version = []
633
+ r = re.compile(r"[.\-]")
634
+ for n in r.split(raw):
635
+ try:
636
+ version.append(int(n))
637
+ except ValueError:
638
+ pass
639
+ return tuple(version)
640
+
641
+ def on_connect(self):
642
+ super_ = super().on_connect()
643
+
644
+ def on_connect(conn):
645
+ if super_ is not None:
646
+ super_(conn)
647
+
648
+ self._setup_timestampoffset_type(conn)
649
+
650
+ return on_connect
651
+
652
+ def _setup_timestampoffset_type(self, connection):
653
+ # output converter function for datetimeoffset
654
+ def _handle_datetimeoffset(dto_value):
655
+ tup = struct.unpack("<6hI2h", dto_value)
656
+ return datetime.datetime(
657
+ tup[0],
658
+ tup[1],
659
+ tup[2],
660
+ tup[3],
661
+ tup[4],
662
+ tup[5],
663
+ tup[6] // 1000,
664
+ datetime.timezone(
665
+ datetime.timedelta(hours=tup[7], minutes=tup[8])
666
+ ),
667
+ )
668
+
669
+ odbc_SQL_SS_TIMESTAMPOFFSET = -155 # as defined in SQLNCLI.h
670
+ connection.add_output_converter(
671
+ odbc_SQL_SS_TIMESTAMPOFFSET, _handle_datetimeoffset
672
+ )
673
+
674
+ def do_executemany(self, cursor, statement, parameters, context=None):
675
+ if self.fast_executemany:
676
+ cursor.fast_executemany = True
677
+ super().do_executemany(cursor, statement, parameters, context=context)
678
+
679
+ def is_disconnect(self, e, connection, cursor):
680
+ if isinstance(e, self.dbapi.Error):
681
+ code = e.args[0]
682
+ if code in {
683
+ "08S01",
684
+ "01000",
685
+ "01002",
686
+ "08003",
687
+ "08007",
688
+ "08S02",
689
+ "08001",
690
+ "HYT00",
691
+ "HY010",
692
+ "10054",
693
+ }:
694
+ return True
695
+ return super().is_disconnect(e, connection, cursor)
696
+
697
+
698
+ dialect = MSDialect_pyodbc