SQLAlchemy 2.1.0rc1__cp315-cp315-win32.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 (276) hide show
  1. sqlalchemy/__init__.py +299 -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 +248 -0
  6. sqlalchemy/dialects/__init__.py +62 -0
  7. sqlalchemy/dialects/_typing.py +29 -0
  8. sqlalchemy/dialects/mssql/__init__.py +88 -0
  9. sqlalchemy/dialects/mssql/aioodbc.py +63 -0
  10. sqlalchemy/dialects/mssql/base.py +4833 -0
  11. sqlalchemy/dialects/mssql/information_schema.py +345 -0
  12. sqlalchemy/dialects/mssql/json.py +140 -0
  13. sqlalchemy/dialects/mssql/mssqlpython.py +242 -0
  14. sqlalchemy/dialects/mssql/provision.py +196 -0
  15. sqlalchemy/dialects/mssql/pymssql.py +130 -0
  16. sqlalchemy/dialects/mssql/pyodbc.py +697 -0
  17. sqlalchemy/dialects/mysql/__init__.py +106 -0
  18. sqlalchemy/dialects/mysql/_mariadb_shim.py +312 -0
  19. sqlalchemy/dialects/mysql/aiomysql.py +260 -0
  20. sqlalchemy/dialects/mysql/asyncmy.py +241 -0
  21. sqlalchemy/dialects/mysql/base.py +3896 -0
  22. sqlalchemy/dialects/mysql/cymysql.py +107 -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 +314 -0
  29. sqlalchemy/dialects/mysql/mysqlconnector.py +291 -0
  30. sqlalchemy/dialects/mysql/mysqldb.py +318 -0
  31. sqlalchemy/dialects/mysql/provision.py +153 -0
  32. sqlalchemy/dialects/mysql/pymysql.py +188 -0
  33. sqlalchemy/dialects/mysql/pyodbc.py +157 -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 +3847 -0
  39. sqlalchemy/dialects/oracle/cx_oracle.py +1736 -0
  40. sqlalchemy/dialects/oracle/dictionary.py +507 -0
  41. sqlalchemy/dialects/oracle/json.py +157 -0
  42. sqlalchemy/dialects/oracle/oracledb.py +898 -0
  43. sqlalchemy/dialects/oracle/provision.py +288 -0
  44. sqlalchemy/dialects/oracle/types.py +367 -0
  45. sqlalchemy/dialects/oracle/vector.py +366 -0
  46. sqlalchemy/dialects/postgresql/__init__.py +170 -0
  47. sqlalchemy/dialects/postgresql/_psycopg_common.py +232 -0
  48. sqlalchemy/dialects/postgresql/array.py +534 -0
  49. sqlalchemy/dialects/postgresql/asyncpg.py +1318 -0
  50. sqlalchemy/dialects/postgresql/base.py +5935 -0
  51. sqlalchemy/dialects/postgresql/bitstring.py +327 -0
  52. sqlalchemy/dialects/postgresql/dml.py +360 -0
  53. sqlalchemy/dialects/postgresql/ext.py +599 -0
  54. sqlalchemy/dialects/postgresql/hstore.py +422 -0
  55. sqlalchemy/dialects/postgresql/json.py +411 -0
  56. sqlalchemy/dialects/postgresql/named_types.py +535 -0
  57. sqlalchemy/dialects/postgresql/operators.py +129 -0
  58. sqlalchemy/dialects/postgresql/pg8000.py +655 -0
  59. sqlalchemy/dialects/postgresql/pg_catalog.py +345 -0
  60. sqlalchemy/dialects/postgresql/provision.py +202 -0
  61. sqlalchemy/dialects/postgresql/psycopg.py +800 -0
  62. sqlalchemy/dialects/postgresql/psycopg2.py +860 -0
  63. sqlalchemy/dialects/postgresql/psycopg2cffi.py +62 -0
  64. sqlalchemy/dialects/postgresql/ranges.py +1002 -0
  65. sqlalchemy/dialects/postgresql/types.py +388 -0
  66. sqlalchemy/dialects/sqlite/__init__.py +59 -0
  67. sqlalchemy/dialects/sqlite/aiosqlite.py +375 -0
  68. sqlalchemy/dialects/sqlite/base.py +3103 -0
  69. sqlalchemy/dialects/sqlite/dml.py +314 -0
  70. sqlalchemy/dialects/sqlite/json.py +134 -0
  71. sqlalchemy/dialects/sqlite/provision.py +237 -0
  72. sqlalchemy/dialects/sqlite/pysqlcipher.py +166 -0
  73. sqlalchemy/dialects/sqlite/pysqlite.py +959 -0
  74. sqlalchemy/dialects/type_migration_guidelines.txt +145 -0
  75. sqlalchemy/engine/__init__.py +62 -0
  76. sqlalchemy/engine/_processors_cy.cp315-win32.pyd +0 -0
  77. sqlalchemy/engine/_processors_cy.py +92 -0
  78. sqlalchemy/engine/_result_cy.cp315-win32.pyd +0 -0
  79. sqlalchemy/engine/_result_cy.py +711 -0
  80. sqlalchemy/engine/_row_cy.cp315-win32.pyd +0 -0
  81. sqlalchemy/engine/_row_cy.py +232 -0
  82. sqlalchemy/engine/_util_cy.cp315-win32.pyd +0 -0
  83. sqlalchemy/engine/_util_cy.py +136 -0
  84. sqlalchemy/engine/base.py +3357 -0
  85. sqlalchemy/engine/characteristics.py +155 -0
  86. sqlalchemy/engine/create.py +877 -0
  87. sqlalchemy/engine/cursor.py +2425 -0
  88. sqlalchemy/engine/default.py +2627 -0
  89. sqlalchemy/engine/events.py +965 -0
  90. sqlalchemy/engine/interfaces.py +3636 -0
  91. sqlalchemy/engine/mock.py +133 -0
  92. sqlalchemy/engine/processors.py +83 -0
  93. sqlalchemy/engine/reflection.py +2141 -0
  94. sqlalchemy/engine/result.py +2012 -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 +164 -0
  99. sqlalchemy/event/__init__.py +26 -0
  100. sqlalchemy/event/api.py +220 -0
  101. sqlalchemy/event/attr.py +675 -0
  102. sqlalchemy/event/base.py +473 -0
  103. sqlalchemy/event/legacy.py +259 -0
  104. sqlalchemy/event/registry.py +391 -0
  105. sqlalchemy/events.py +17 -0
  106. sqlalchemy/exc.py +939 -0
  107. sqlalchemy/ext/__init__.py +10 -0
  108. sqlalchemy/ext/associationproxy.py +2073 -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 +2006 -0
  116. sqlalchemy/ext/automap.py +1702 -0
  117. sqlalchemy/ext/baked.py +558 -0
  118. sqlalchemy/ext/compiler.py +601 -0
  119. sqlalchemy/ext/declarative/__init__.py +65 -0
  120. sqlalchemy/ext/declarative/extensions.py +561 -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 +440 -0
  127. sqlalchemy/ext/serializer.py +184 -0
  128. sqlalchemy/future/__init__.py +17 -0
  129. sqlalchemy/future/engine.py +15 -0
  130. sqlalchemy/inspection.py +188 -0
  131. sqlalchemy/log.py +279 -0
  132. sqlalchemy/orm/__init__.py +176 -0
  133. sqlalchemy/orm/_orm_constructors.py +2694 -0
  134. sqlalchemy/orm/_typing.py +180 -0
  135. sqlalchemy/orm/attributes.py +2868 -0
  136. sqlalchemy/orm/base.py +991 -0
  137. sqlalchemy/orm/bulk_persistence.py +2168 -0
  138. sqlalchemy/orm/clsregistry.py +630 -0
  139. sqlalchemy/orm/collections.py +1569 -0
  140. sqlalchemy/orm/context.py +3475 -0
  141. sqlalchemy/orm/decl_api.py +2283 -0
  142. sqlalchemy/orm/decl_base.py +2320 -0
  143. sqlalchemy/orm/dependency.py +1306 -0
  144. sqlalchemy/orm/descriptor_props.py +1183 -0
  145. sqlalchemy/orm/dynamic.py +306 -0
  146. sqlalchemy/orm/evaluator.py +378 -0
  147. sqlalchemy/orm/events.py +3387 -0
  148. sqlalchemy/orm/exc.py +237 -0
  149. sqlalchemy/orm/identity.py +302 -0
  150. sqlalchemy/orm/instrumentation.py +749 -0
  151. sqlalchemy/orm/interfaces.py +1595 -0
  152. sqlalchemy/orm/loading.py +1712 -0
  153. sqlalchemy/orm/mapped_collection.py +557 -0
  154. sqlalchemy/orm/mapper.py +4465 -0
  155. sqlalchemy/orm/path_registry.py +907 -0
  156. sqlalchemy/orm/persistence.py +1790 -0
  157. sqlalchemy/orm/properties.py +972 -0
  158. sqlalchemy/orm/query.py +3528 -0
  159. sqlalchemy/orm/relationships.py +3608 -0
  160. sqlalchemy/orm/scoping.py +2233 -0
  161. sqlalchemy/orm/session.py +5468 -0
  162. sqlalchemy/orm/state.py +1175 -0
  163. sqlalchemy/orm/state_changes.py +196 -0
  164. sqlalchemy/orm/strategies.py +3552 -0
  165. sqlalchemy/orm/strategy_options.py +2648 -0
  166. sqlalchemy/orm/sync.py +164 -0
  167. sqlalchemy/orm/unitofwork.py +797 -0
  168. sqlalchemy/orm/util.py +2461 -0
  169. sqlalchemy/orm/writeonly.py +701 -0
  170. sqlalchemy/pool/__init__.py +41 -0
  171. sqlalchemy/pool/base.py +1540 -0
  172. sqlalchemy/pool/events.py +375 -0
  173. sqlalchemy/pool/impl.py +583 -0
  174. sqlalchemy/py.typed +0 -0
  175. sqlalchemy/schema.py +75 -0
  176. sqlalchemy/sql/__init__.py +156 -0
  177. sqlalchemy/sql/_annotated_cols.py +402 -0
  178. sqlalchemy/sql/_cache_key_cy.cp315-win32.pyd +0 -0
  179. sqlalchemy/sql/_cache_key_cy.py +363 -0
  180. sqlalchemy/sql/_dml_constructors.py +132 -0
  181. sqlalchemy/sql/_elements_constructors.py +2190 -0
  182. sqlalchemy/sql/_orm_types.py +19 -0
  183. sqlalchemy/sql/_selectable_constructors.py +840 -0
  184. sqlalchemy/sql/_typing.py +500 -0
  185. sqlalchemy/sql/_util_cy.cp315-win32.pyd +0 -0
  186. sqlalchemy/sql/_util_cy.pxd +11 -0
  187. sqlalchemy/sql/_util_cy.py +127 -0
  188. sqlalchemy/sql/annotation.py +590 -0
  189. sqlalchemy/sql/base.py +2702 -0
  190. sqlalchemy/sql/cache_key.py +915 -0
  191. sqlalchemy/sql/coercions.py +1373 -0
  192. sqlalchemy/sql/compiler.py +8453 -0
  193. sqlalchemy/sql/crud.py +1816 -0
  194. sqlalchemy/sql/ddl.py +1962 -0
  195. sqlalchemy/sql/default_comparator.py +660 -0
  196. sqlalchemy/sql/dml.py +2018 -0
  197. sqlalchemy/sql/elements.py +6057 -0
  198. sqlalchemy/sql/events.py +458 -0
  199. sqlalchemy/sql/expression.py +171 -0
  200. sqlalchemy/sql/functions.py +2380 -0
  201. sqlalchemy/sql/lambdas.py +1442 -0
  202. sqlalchemy/sql/naming.py +204 -0
  203. sqlalchemy/sql/operators.py +2909 -0
  204. sqlalchemy/sql/roles.py +332 -0
  205. sqlalchemy/sql/schema.py +7075 -0
  206. sqlalchemy/sql/selectable.py +7634 -0
  207. sqlalchemy/sql/sqltypes.py +4130 -0
  208. sqlalchemy/sql/traversals.py +1041 -0
  209. sqlalchemy/sql/type_api.py +2450 -0
  210. sqlalchemy/sql/util.py +1496 -0
  211. sqlalchemy/sql/visitors.py +1153 -0
  212. sqlalchemy/testing/__init__.py +97 -0
  213. sqlalchemy/testing/assertions.py +1007 -0
  214. sqlalchemy/testing/assertsql.py +519 -0
  215. sqlalchemy/testing/asyncio.py +128 -0
  216. sqlalchemy/testing/cancellation.py +237 -0
  217. sqlalchemy/testing/config.py +440 -0
  218. sqlalchemy/testing/engines.py +482 -0
  219. sqlalchemy/testing/entities.py +117 -0
  220. sqlalchemy/testing/exclusions.py +501 -0
  221. sqlalchemy/testing/fixtures/__init__.py +30 -0
  222. sqlalchemy/testing/fixtures/base.py +426 -0
  223. sqlalchemy/testing/fixtures/mypy.py +247 -0
  224. sqlalchemy/testing/fixtures/orm.py +227 -0
  225. sqlalchemy/testing/fixtures/sql.py +538 -0
  226. sqlalchemy/testing/pickleable.py +155 -0
  227. sqlalchemy/testing/plugin/__init__.py +6 -0
  228. sqlalchemy/testing/plugin/bootstrap.py +50 -0
  229. sqlalchemy/testing/plugin/plugin_base.py +828 -0
  230. sqlalchemy/testing/plugin/pytestplugin.py +896 -0
  231. sqlalchemy/testing/profiles_file.py +350 -0
  232. sqlalchemy/testing/profiling.py +294 -0
  233. sqlalchemy/testing/provision.py +633 -0
  234. sqlalchemy/testing/requirements.py +1971 -0
  235. sqlalchemy/testing/schema.py +198 -0
  236. sqlalchemy/testing/suite/__init__.py +19 -0
  237. sqlalchemy/testing/suite/test_cte.py +237 -0
  238. sqlalchemy/testing/suite/test_ddl.py +420 -0
  239. sqlalchemy/testing/suite/test_dialect.py +776 -0
  240. sqlalchemy/testing/suite/test_insert.py +630 -0
  241. sqlalchemy/testing/suite/test_reflection.py +3815 -0
  242. sqlalchemy/testing/suite/test_results.py +660 -0
  243. sqlalchemy/testing/suite/test_rowcount.py +258 -0
  244. sqlalchemy/testing/suite/test_select.py +2112 -0
  245. sqlalchemy/testing/suite/test_sequence.py +317 -0
  246. sqlalchemy/testing/suite/test_table_via_select.py +686 -0
  247. sqlalchemy/testing/suite/test_types.py +2271 -0
  248. sqlalchemy/testing/suite/test_unicode_ddl.py +189 -0
  249. sqlalchemy/testing/suite/test_update_delete.py +139 -0
  250. sqlalchemy/testing/util.py +575 -0
  251. sqlalchemy/testing/warnings.py +52 -0
  252. sqlalchemy/types.py +75 -0
  253. sqlalchemy/util/__init__.py +165 -0
  254. sqlalchemy/util/_collections.py +688 -0
  255. sqlalchemy/util/_collections_cy.cp315-win32.pyd +0 -0
  256. sqlalchemy/util/_collections_cy.pxd +8 -0
  257. sqlalchemy/util/_collections_cy.py +516 -0
  258. sqlalchemy/util/_has_cython.py +48 -0
  259. sqlalchemy/util/_immutabledict_cy.cp315-win32.pyd +0 -0
  260. sqlalchemy/util/_immutabledict_cy.py +240 -0
  261. sqlalchemy/util/compat.py +298 -0
  262. sqlalchemy/util/concurrency.py +272 -0
  263. sqlalchemy/util/cython.py +95 -0
  264. sqlalchemy/util/deprecations.py +401 -0
  265. sqlalchemy/util/langhelpers.py +2797 -0
  266. sqlalchemy/util/preloaded.py +153 -0
  267. sqlalchemy/util/queue.py +304 -0
  268. sqlalchemy/util/tool_support.py +202 -0
  269. sqlalchemy/util/topological.py +120 -0
  270. sqlalchemy/util/typing.py +709 -0
  271. sqlalchemy-2.1.0rc1.dist-info/METADATA +270 -0
  272. sqlalchemy-2.1.0rc1.dist-info/RECORD +276 -0
  273. sqlalchemy-2.1.0rc1.dist-info/WHEEL +5 -0
  274. sqlalchemy-2.1.0rc1.dist-info/licenses/AUTHORS +30 -0
  275. sqlalchemy-2.1.0rc1.dist-info/licenses/LICENSE +19 -0
  276. sqlalchemy-2.1.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3896 @@
1
+ # dialects/mysql/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
+
8
+
9
+ r"""
10
+
11
+ .. dialect:: mysql
12
+ :name: MySQL / MariaDB
13
+ :normal_support: 5.6+ / 10+
14
+ :best_effort: 5.0.2+ / 5.0.2+
15
+
16
+ Supported Versions and Features
17
+ -------------------------------
18
+
19
+ SQLAlchemy supports MySQL starting with version 5.0.2 through modern releases,
20
+ as well as all modern versions of MariaDB. See the official MySQL
21
+ documentation for detailed information about features supported in any given
22
+ server release.
23
+
24
+ .. versionchanged:: 1.4 minimum MySQL version supported is now 5.0.2.
25
+
26
+ MariaDB Support
27
+ ~~~~~~~~~~~~~~~
28
+
29
+ The MariaDB variant of MySQL retains fundamental compatibility with MySQL's
30
+ protocols however the development of these two products continues to diverge.
31
+ Within the realm of SQLAlchemy, the two databases have a small number of
32
+ syntactical and behavioral differences that SQLAlchemy accommodates automatically.
33
+ To connect to a MariaDB database, no changes to the database URL are required::
34
+
35
+
36
+ engine = create_engine(
37
+ "mysql+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
38
+ )
39
+
40
+ Upon first connect, the SQLAlchemy dialect employs a
41
+ server version detection scheme that determines if the
42
+ backing database reports as MariaDB. Based on this flag, the dialect
43
+ can make different choices in those of areas where its behavior
44
+ must be different.
45
+
46
+ .. _mysql_mariadb_only_mode:
47
+
48
+ MariaDB-Only Mode
49
+ ~~~~~~~~~~~~~~~~~
50
+
51
+ The dialect also supports an **optional** "MariaDB-only" mode of connection, which may be
52
+ useful for the case where an application makes use of MariaDB-specific features
53
+ and is not compatible with a MySQL database. To use this mode of operation,
54
+ replace the "mysql" token in the above URL with "mariadb"::
55
+
56
+ engine = create_engine(
57
+ "mariadb+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
58
+ )
59
+
60
+ The above engine, upon first connect, will raise an error if the server version
61
+ detection detects that the backing database is not MariaDB.
62
+
63
+ When using an engine with ``"mariadb"`` as the dialect name, **all mysql-specific options
64
+ that include the name "mysql" in them are now named with "mariadb"**. This means
65
+ options like ``mysql_engine`` should be named ``mariadb_engine``, etc. Both
66
+ "mysql" and "mariadb" options can be used simultaneously for applications that
67
+ use URLs with both "mysql" and "mariadb" dialects::
68
+
69
+ my_table = Table(
70
+ "mytable",
71
+ metadata,
72
+ Column("id", Integer, primary_key=True),
73
+ Column("textdata", String(50)),
74
+ mariadb_engine="InnoDB",
75
+ mysql_engine="InnoDB",
76
+ )
77
+
78
+ Index(
79
+ "textdata_ix",
80
+ my_table.c.textdata,
81
+ mysql_prefix="FULLTEXT",
82
+ mariadb_prefix="FULLTEXT",
83
+ )
84
+
85
+ Similar behavior will occur when the above structures are reflected, i.e. the
86
+ "mariadb" prefix will be present in the option names when the database URL
87
+ is based on the "mariadb" name.
88
+
89
+ .. versionadded:: 1.4 Added "mariadb" dialect name supporting "MariaDB-only mode"
90
+ for the MySQL dialect.
91
+
92
+ .. _mysql_connection_timeouts:
93
+
94
+ Connection Timeouts and Disconnects
95
+ -----------------------------------
96
+
97
+ MySQL / MariaDB feature an automatic connection close behavior, for connections that
98
+ have been idle for a fixed period of time, defaulting to eight hours.
99
+ To circumvent having this issue, use
100
+ the :paramref:`_sa.create_engine.pool_recycle` option which ensures that
101
+ a connection will be discarded and replaced with a new one if it has been
102
+ present in the pool for a fixed number of seconds::
103
+
104
+ engine = create_engine("mysql+mysqldb://...", pool_recycle=3600)
105
+
106
+ For more comprehensive disconnect detection of pooled connections, including
107
+ accommodation of server restarts and network issues, a pre-ping approach may
108
+ be employed. See :ref:`pool_disconnects` for current approaches.
109
+
110
+ .. seealso::
111
+
112
+ :ref:`pool_disconnects` - Background on several techniques for dealing
113
+ with timed out connections as well as database restarts.
114
+
115
+ .. _mysql_storage_engines:
116
+
117
+ CREATE TABLE arguments including Storage Engines
118
+ ------------------------------------------------
119
+
120
+ Both MySQL's and MariaDB's CREATE TABLE syntax includes a wide array of special options,
121
+ including ``ENGINE``, ``CHARSET``, ``MAX_ROWS``, ``ROW_FORMAT``,
122
+ ``INSERT_METHOD``, and many more.
123
+ To accommodate the rendering of these arguments, specify the form
124
+ ``mysql_argument_name="value"``. For example, to specify a table with
125
+ ``ENGINE`` of ``InnoDB``, ``CHARSET`` of ``utf8mb4``, and ``KEY_BLOCK_SIZE``
126
+ of ``1024``::
127
+
128
+ Table(
129
+ "mytable",
130
+ metadata,
131
+ Column("data", String(32)),
132
+ mysql_engine="InnoDB",
133
+ mysql_charset="utf8mb4",
134
+ mysql_key_block_size="1024",
135
+ )
136
+
137
+ When supporting :ref:`mysql_mariadb_only_mode` mode, similar keys against
138
+ the "mariadb" prefix must be included as well. The values can of course
139
+ vary independently so that different settings on MySQL vs. MariaDB may
140
+ be maintained::
141
+
142
+ # support both "mysql" and "mariadb-only" engine URLs
143
+
144
+ Table(
145
+ "mytable",
146
+ metadata,
147
+ Column("data", String(32)),
148
+ mysql_engine="InnoDB",
149
+ mariadb_engine="InnoDB",
150
+ mysql_charset="utf8mb4",
151
+ mariadb_charset="utf8",
152
+ mysql_key_block_size="1024",
153
+ mariadb_key_block_size="1024",
154
+ )
155
+
156
+ The MySQL / MariaDB dialects will normally transfer any keyword specified as
157
+ ``mysql_keyword_name`` to be rendered as ``KEYWORD_NAME`` in the
158
+ ``CREATE TABLE`` statement. A handful of these names will render with a space
159
+ instead of an underscore; to support this, the MySQL dialect has awareness of
160
+ these particular names, which include ``DATA DIRECTORY``
161
+ (e.g. ``mysql_data_directory``), ``CHARACTER SET`` (e.g.
162
+ ``mysql_character_set``) and ``INDEX DIRECTORY`` (e.g.
163
+ ``mysql_index_directory``).
164
+
165
+ The most common argument is ``mysql_engine``, which refers to the storage
166
+ engine for the table. Historically, MySQL server installations would default
167
+ to ``MyISAM`` for this value, although newer versions may be defaulting
168
+ to ``InnoDB``. The ``InnoDB`` engine is typically preferred for its support
169
+ of transactions and foreign keys.
170
+
171
+ A :class:`_schema.Table`
172
+ that is created in a MySQL / MariaDB database with a storage engine
173
+ of ``MyISAM`` will be essentially non-transactional, meaning any
174
+ INSERT/UPDATE/DELETE statement referring to this table will be invoked as
175
+ autocommit. It also will have no support for foreign key constraints; while
176
+ the ``CREATE TABLE`` statement accepts foreign key options, when using the
177
+ ``MyISAM`` storage engine these arguments are discarded. Reflecting such a
178
+ table will also produce no foreign key constraint information.
179
+
180
+ For fully atomic transactions as well as support for foreign key
181
+ constraints, all participating ``CREATE TABLE`` statements must specify a
182
+ transactional engine, which in the vast majority of cases is ``InnoDB``.
183
+
184
+ Partitioning can similarly be specified using similar options.
185
+ In the example below the create table will specify ``PARTITION_BY``,
186
+ ``PARTITIONS``, ``SUBPARTITIONS`` and ``SUBPARTITION_BY``::
187
+
188
+ # can also use mariadb_* prefix
189
+ Table(
190
+ "testtable",
191
+ MetaData(),
192
+ Column("id", Integer(), primary_key=True, autoincrement=True),
193
+ Column("other_id", Integer(), primary_key=True, autoincrement=False),
194
+ mysql_partitions="2",
195
+ mysql_partition_by="KEY(other_id)",
196
+ mysql_subpartition_by="HASH(some_expr)",
197
+ mysql_subpartitions="2",
198
+ )
199
+
200
+ This will render:
201
+
202
+ .. sourcecode:: sql
203
+
204
+ CREATE TABLE testtable (
205
+ id INTEGER NOT NULL AUTO_INCREMENT,
206
+ other_id INTEGER NOT NULL,
207
+ PRIMARY KEY (id, other_id)
208
+ )PARTITION BY KEY(other_id) PARTITIONS 2 SUBPARTITION BY HASH(some_expr) SUBPARTITIONS 2
209
+
210
+ Case Sensitivity and Table Reflection
211
+ -------------------------------------
212
+
213
+ Both MySQL and MariaDB have inconsistent support for case-sensitive identifier
214
+ names, basing support on specific details of the underlying
215
+ operating system. However, it has been observed that no matter
216
+ what case sensitivity behavior is present, the names of tables in
217
+ foreign key declarations are *always* received from the database
218
+ as all-lower case, making it impossible to accurately reflect a
219
+ schema where inter-related tables use mixed-case identifier names.
220
+
221
+ Therefore it is strongly advised that table names be declared as
222
+ all lower case both within SQLAlchemy as well as on the MySQL / MariaDB
223
+ database itself, especially if database reflection features are
224
+ to be used.
225
+
226
+ .. _mysql_isolation_level:
227
+
228
+ Transaction Isolation Level
229
+ ---------------------------
230
+
231
+ All MySQL / MariaDB dialects support setting of transaction isolation level both via a
232
+ dialect-specific parameter :paramref:`_sa.create_engine.isolation_level`
233
+ accepted
234
+ by :func:`_sa.create_engine`, as well as the
235
+ :paramref:`.Connection.execution_options.isolation_level` argument as passed to
236
+ :meth:`_engine.Connection.execution_options`.
237
+ This feature works by issuing the
238
+ command ``SET SESSION TRANSACTION ISOLATION LEVEL <level>`` for each new
239
+ connection. For the special AUTOCOMMIT isolation level, DBAPI-specific
240
+ techniques are used.
241
+
242
+ To set isolation level using :func:`_sa.create_engine`::
243
+
244
+ engine = create_engine(
245
+ "mysql+mysqldb://scott:tiger@localhost/test",
246
+ isolation_level="READ UNCOMMITTED",
247
+ )
248
+
249
+ To set using per-connection execution options::
250
+
251
+ connection = engine.connect()
252
+ connection = connection.execution_options(isolation_level="READ COMMITTED")
253
+
254
+ Valid values for ``isolation_level`` include:
255
+
256
+ * ``READ COMMITTED``
257
+ * ``READ UNCOMMITTED``
258
+ * ``REPEATABLE READ``
259
+ * ``SERIALIZABLE``
260
+ * ``AUTOCOMMIT``
261
+
262
+ The special ``AUTOCOMMIT`` value makes use of the various "autocommit"
263
+ attributes provided by specific DBAPIs, and is currently supported by
264
+ MySQLdb, MySQL-Client, MySQL-Connector Python, and PyMySQL. Using it,
265
+ the database connection will return true for the value of
266
+ ``SELECT @@autocommit;``.
267
+
268
+ There are also more options for isolation level configurations, such as
269
+ "sub-engine" objects linked to a main :class:`_engine.Engine` which each apply
270
+ different isolation level settings. See the discussion at
271
+ :ref:`dbapi_autocommit` for background.
272
+
273
+ .. seealso::
274
+
275
+ :ref:`dbapi_autocommit`
276
+
277
+ AUTO_INCREMENT Behavior
278
+ -----------------------
279
+
280
+ When creating tables, SQLAlchemy will automatically set ``AUTO_INCREMENT`` on
281
+ the first :class:`.Integer` primary key column which is not marked as a
282
+ foreign key::
283
+
284
+ >>> t = Table(
285
+ ... "mytable", metadata, Column("mytable_id", Integer, primary_key=True)
286
+ ... )
287
+ >>> t.create()
288
+ CREATE TABLE mytable (
289
+ id INTEGER NOT NULL AUTO_INCREMENT,
290
+ PRIMARY KEY (id)
291
+ )
292
+
293
+ You can disable this behavior by passing ``False`` to the
294
+ :paramref:`_schema.Column.autoincrement` argument of :class:`_schema.Column`.
295
+ This flag
296
+ can also be used to enable auto-increment on a secondary column in a
297
+ multi-column key for some storage engines::
298
+
299
+ Table(
300
+ "mytable",
301
+ metadata,
302
+ Column("gid", Integer, primary_key=True, autoincrement=False),
303
+ Column("id", Integer, primary_key=True),
304
+ )
305
+
306
+ .. _mysql_ss_cursors:
307
+
308
+ Server Side Cursors
309
+ -------------------
310
+
311
+ Server-side cursor support is available for the mysqlclient, PyMySQL,
312
+ mariadbconnector dialects and may also be available in others. This makes use
313
+ of either the "buffered=True/False" flag if available or by using a class such
314
+ as ``MySQLdb.cursors.SSCursor`` or ``pymysql.cursors.SSCursor`` internally.
315
+
316
+
317
+ Server side cursors are enabled on a per-statement basis by using the
318
+ :paramref:`.Connection.execution_options.stream_results` connection execution
319
+ option::
320
+
321
+ with engine.connect() as conn:
322
+ result = conn.execution_options(stream_results=True).execute(
323
+ text("select * from table")
324
+ )
325
+
326
+ Note that some kinds of SQL statements may not be supported with
327
+ server side cursors; generally, only SQL statements that return rows should be
328
+ used with this option.
329
+
330
+ .. deprecated:: 1.4 The dialect-level server_side_cursors flag is deprecated
331
+ and will be removed in a future release. Please use the
332
+ :paramref:`_engine.Connection.stream_results` execution option for
333
+ unbuffered cursor support.
334
+
335
+ .. seealso::
336
+
337
+ :ref:`engine_stream_results`
338
+
339
+ .. _mysql_unicode:
340
+
341
+ Unicode
342
+ -------
343
+
344
+ Charset Selection
345
+ ~~~~~~~~~~~~~~~~~
346
+
347
+ Most MySQL / MariaDB DBAPIs offer the option to set the client character set for
348
+ a connection. This is typically delivered using the ``charset`` parameter
349
+ in the URL, such as::
350
+
351
+ e = create_engine(
352
+ "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4"
353
+ )
354
+
355
+ This charset is the **client character set** for the connection. Some
356
+ MySQL DBAPIs will default this to a value such as ``latin1``, and some
357
+ will make use of the ``default-character-set`` setting in the ``my.cnf``
358
+ file as well. Documentation for the DBAPI in use should be consulted
359
+ for specific behavior.
360
+
361
+ The encoding used for Unicode has traditionally been ``'utf8'``. However, for
362
+ MySQL versions 5.5.3 and MariaDB 5.5 on forward, a new MySQL-specific encoding
363
+ ``'utf8mb4'`` has been introduced, and as of MySQL 8.0 a warning is emitted by
364
+ the server if plain ``utf8`` is specified within any server-side directives,
365
+ replaced with ``utf8mb3``. The rationale for this new encoding is due to the
366
+ fact that MySQL's legacy utf-8 encoding only supports codepoints up to three
367
+ bytes instead of four. Therefore, when communicating with a MySQL or MariaDB
368
+ database that includes codepoints more than three bytes in size, this new
369
+ charset is preferred, if supported by both the database as well as the client
370
+ DBAPI, as in::
371
+
372
+ e = create_engine(
373
+ "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4"
374
+ )
375
+
376
+ All modern DBAPIs should support the ``utf8mb4`` charset.
377
+
378
+ In order to use ``utf8mb4`` encoding for a schema that was created with legacy
379
+ ``utf8``, changes to the MySQL/MariaDB schema and/or server configuration may be
380
+ required.
381
+
382
+ .. seealso::
383
+
384
+ `The utf8mb4 Character Set \
385
+ <https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html>`_ - \
386
+ in the MySQL documentation
387
+
388
+ .. _mysql_binary_introducer:
389
+
390
+ Dealing with Binary Data Warnings and Unicode
391
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
392
+
393
+ MySQL versions 5.6, 5.7 and later (not MariaDB at the time of this writing) now
394
+ emit a warning when attempting to pass binary data to the database, while a
395
+ character set encoding is also in place, when the binary data itself is not
396
+ valid for that encoding:
397
+
398
+ .. sourcecode:: text
399
+
400
+ default.py:509: Warning: (1300, "Invalid utf8mb4 character string:
401
+ 'F9876A'")
402
+ cursor.execute(statement, parameters)
403
+
404
+ This warning is due to the fact that the MySQL client library is attempting to
405
+ interpret the binary string as a unicode object even if a datatype such
406
+ as :class:`.LargeBinary` is in use. To resolve this, the SQL statement requires
407
+ a binary "character set introducer" be present before any non-NULL value
408
+ that renders like this:
409
+
410
+ .. sourcecode:: sql
411
+
412
+ INSERT INTO table (data) VALUES (_binary %s)
413
+
414
+ These character set introducers are provided by the DBAPI driver, assuming the
415
+ use of mysqlclient or PyMySQL (both of which are recommended). Add the query
416
+ string parameter ``binary_prefix=true`` to the URL to repair this warning::
417
+
418
+ # mysqlclient
419
+ engine = create_engine(
420
+ "mysql+mysqldb://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true"
421
+ )
422
+
423
+ # PyMySQL
424
+ engine = create_engine(
425
+ "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true"
426
+ )
427
+
428
+ The ``binary_prefix`` flag may or may not be supported by other MySQL drivers.
429
+
430
+ SQLAlchemy itself cannot render this ``_binary`` prefix reliably, as it does
431
+ not work with the NULL value, which is valid to be sent as a bound parameter.
432
+ As the MySQL driver renders parameters directly into the SQL string, it's the
433
+ most efficient place for this additional keyword to be passed.
434
+
435
+ .. seealso::
436
+
437
+ `Character set introducers <https://dev.mysql.com/doc/refman/5.7/en/charset-introducer.html>`_ - on the MySQL website
438
+
439
+
440
+ ANSI Quoting Style
441
+ ------------------
442
+
443
+ MySQL / MariaDB feature two varieties of identifier "quoting style", one using
444
+ backticks and the other using quotes, e.g. ```some_identifier``` vs.
445
+ ``"some_identifier"``. All MySQL dialects detect which version
446
+ is in use by checking the value of :ref:`sql_mode<mysql_sql_mode>` when a connection is first
447
+ established with a particular :class:`_engine.Engine`.
448
+ This quoting style comes
449
+ into play when rendering table and column names as well as when reflecting
450
+ existing database structures. The detection is entirely automatic and
451
+ no special configuration is needed to use either quoting style.
452
+
453
+
454
+ .. _mysql_sql_mode:
455
+
456
+ Changing the sql_mode
457
+ ---------------------
458
+
459
+ MySQL supports operating in multiple
460
+ `Server SQL Modes <https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html>`_ for
461
+ both Servers and Clients. To change the ``sql_mode`` for a given application, a
462
+ developer can leverage SQLAlchemy's Events system.
463
+
464
+ In the following example, the event system is used to set the ``sql_mode`` on
465
+ the ``first_connect`` and ``connect`` events::
466
+
467
+ from sqlalchemy import create_engine, event
468
+
469
+ eng = create_engine(
470
+ "mysql+mysqldb://scott:tiger@localhost/test", echo="debug"
471
+ )
472
+
473
+
474
+ # `insert=True` will ensure this is the very first listener to run
475
+ @event.listens_for(eng, "connect", insert=True)
476
+ def connect(dbapi_connection, connection_record):
477
+ cursor = dbapi_connection.cursor()
478
+ cursor.execute("SET sql_mode = 'STRICT_ALL_TABLES'")
479
+
480
+
481
+ conn = eng.connect()
482
+
483
+ In the example illustrated above, the "connect" event will invoke the "SET"
484
+ statement on the connection at the moment a particular DBAPI connection is
485
+ first created for a given Pool, before the connection is made available to the
486
+ connection pool. Additionally, because the function was registered with
487
+ ``insert=True``, it will be prepended to the internal list of registered
488
+ functions.
489
+
490
+
491
+ MySQL / MariaDB SQL Extensions
492
+ ------------------------------
493
+
494
+ Many of the MySQL / MariaDB SQL extensions are handled through SQLAlchemy's generic
495
+ function and operator support::
496
+
497
+ table.select(table.c.password == func.md5("plaintext"))
498
+ table.select(table.c.username.op("regexp")("^[a-d]"))
499
+
500
+ And of course any valid SQL statement can be executed as a string as well.
501
+
502
+ Some limited direct support for MySQL / MariaDB extensions to SQL is currently
503
+ available.
504
+
505
+ * INSERT..ON DUPLICATE KEY UPDATE: See
506
+ :ref:`mysql_insert_on_duplicate_key_update`
507
+
508
+ * SELECT pragma, use :meth:`_expression.Select.prefix_with` and
509
+ :meth:`_query.Query.prefix_with`::
510
+
511
+ select(...).prefix_with(["HIGH_PRIORITY", "SQL_SMALL_RESULT"])
512
+
513
+ * UPDATE
514
+ with LIMIT::
515
+
516
+ from sqlalchemy.dialects.mysql import limit
517
+
518
+ update(...).ext(limit(10))
519
+
520
+ .. versionchanged:: 2.1 the :func:`_mysql.limit()` extension supersedes the
521
+ previous use of ``mysql_limit``
522
+
523
+ * DELETE
524
+ with LIMIT::
525
+
526
+ from sqlalchemy.dialects.mysql import limit
527
+
528
+ delete(...).ext(limit(10))
529
+
530
+ .. versionchanged:: 2.1 the :func:`_mysql.limit()` extension supersedes the
531
+ previous use of ``mysql_limit``
532
+
533
+ * DELETE with an explicit ``USING`` expression such as a JOIN, use
534
+ :meth:`_sql.Delete.using`. See :ref:`tutorial_multi_table_deletes`.
535
+
536
+ .. versionadded:: 2.1
537
+
538
+ * optimizer hints, use :meth:`_expression.Select.prefix_with` and
539
+ :meth:`_query.Query.prefix_with`::
540
+
541
+ select(...).prefix_with("/*+ NO_RANGE_OPTIMIZATION(t4 PRIMARY) */")
542
+
543
+ * index hints, use :meth:`_expression.Select.with_hint` and
544
+ :meth:`_query.Query.with_hint`::
545
+
546
+ select(...).with_hint(some_table, "USE INDEX xyz")
547
+
548
+ * MATCH
549
+ operator support::
550
+
551
+ from sqlalchemy.dialects.mysql import match
552
+
553
+ select(...).where(match(col1, col2, against="some expr").in_boolean_mode())
554
+
555
+ .. seealso::
556
+
557
+ :class:`_mysql.match`
558
+
559
+ INSERT/DELETE...RETURNING
560
+ -------------------------
561
+
562
+ The MariaDB dialect supports 10.5+'s ``INSERT..RETURNING`` and
563
+ ``DELETE..RETURNING`` (10.0+) syntaxes. ``INSERT..RETURNING`` may be used
564
+ automatically in some cases in order to fetch newly generated identifiers in
565
+ place of the traditional approach of using ``cursor.lastrowid``, however
566
+ ``cursor.lastrowid`` is currently still preferred for simple single-statement
567
+ cases for its better performance.
568
+
569
+ To specify an explicit ``RETURNING`` clause, use the
570
+ :meth:`._UpdateBase.returning` method on a per-statement basis::
571
+
572
+ # INSERT..RETURNING
573
+ result = connection.execute(
574
+ table.insert().values(name="foo").returning(table.c.col1, table.c.col2)
575
+ )
576
+ print(result.all())
577
+
578
+ # DELETE..RETURNING
579
+ result = connection.execute(
580
+ table.delete()
581
+ .where(table.c.name == "foo")
582
+ .returning(table.c.col1, table.c.col2)
583
+ )
584
+ print(result.all())
585
+
586
+ .. versionadded:: 2.0 Added support for MariaDB RETURNING
587
+
588
+ .. _mysql_insert_on_duplicate_key_update:
589
+
590
+ INSERT...ON DUPLICATE KEY UPDATE (Upsert)
591
+ ------------------------------------------
592
+
593
+ MySQL / MariaDB allow "upserts" (update or insert)
594
+ of rows into a table via the ``ON DUPLICATE KEY UPDATE`` clause of the
595
+ ``INSERT`` statement. A candidate row will only be inserted if that row does
596
+ not match an existing primary or unique key in the table; otherwise, an UPDATE
597
+ will be performed. The statement allows for separate specification of the
598
+ values to INSERT versus the values for UPDATE.
599
+
600
+ SQLAlchemy provides ``ON DUPLICATE KEY UPDATE`` support via the MySQL-specific
601
+ :func:`.mysql.insert()` function, which provides
602
+ the generative method :meth:`~.mysql.Insert.on_duplicate_key_update`:
603
+
604
+ .. sourcecode:: pycon+sql
605
+
606
+ >>> from sqlalchemy.dialects.mysql import insert
607
+
608
+ >>> insert_stmt = insert(my_table).values(
609
+ ... id="some_existing_id", data="inserted value"
610
+ ... )
611
+
612
+ >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
613
+ ... data=insert_stmt.inserted.data, status="U"
614
+ ... )
615
+ >>> print(on_duplicate_key_stmt)
616
+ {printsql}INSERT INTO my_table (id, data) VALUES (%s, %s)
617
+ ON DUPLICATE KEY UPDATE data = VALUES(data), status = %s
618
+
619
+
620
+ Unlike PostgreSQL's "ON CONFLICT" phrase, the "ON DUPLICATE KEY UPDATE"
621
+ phrase will always match on any primary key or unique key, and will always
622
+ perform an UPDATE if there's a match; there are no options for it to raise
623
+ an error or to skip performing an UPDATE.
624
+
625
+ ``ON DUPLICATE KEY UPDATE`` is used to perform an update of the already
626
+ existing row, using any combination of new values as well as values
627
+ from the proposed insertion. These values are normally specified using
628
+ keyword arguments passed to the
629
+ :meth:`_mysql.Insert.on_duplicate_key_update`
630
+ given column key values (usually the name of the column, unless it
631
+ specifies :paramref:`_schema.Column.key`
632
+ ) as keys and literal or SQL expressions
633
+ as values:
634
+
635
+ .. sourcecode:: pycon+sql
636
+
637
+ >>> insert_stmt = insert(my_table).values(
638
+ ... id="some_existing_id", data="inserted value"
639
+ ... )
640
+
641
+ >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
642
+ ... data="some data",
643
+ ... updated_at=func.current_timestamp(),
644
+ ... )
645
+
646
+ >>> print(on_duplicate_key_stmt)
647
+ {printsql}INSERT INTO my_table (id, data) VALUES (%s, %s)
648
+ ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP
649
+
650
+ In a manner similar to that of :meth:`.UpdateBase.values`, other parameter
651
+ forms are accepted, including a single dictionary:
652
+
653
+ .. sourcecode:: pycon+sql
654
+
655
+ >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
656
+ ... {"data": "some data", "updated_at": func.current_timestamp()},
657
+ ... )
658
+
659
+ as well as a list of 2-tuples, which will automatically provide
660
+ a parameter-ordered UPDATE statement in a manner similar to that described
661
+ at :ref:`tutorial_parameter_ordered_updates`. Unlike the :class:`_expression.Update`
662
+ object,
663
+ no special flag is needed to specify the intent since the argument form is
664
+ this context is unambiguous:
665
+
666
+ .. sourcecode:: pycon+sql
667
+
668
+ >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
669
+ ... [
670
+ ... ("data", "some data"),
671
+ ... ("updated_at", func.current_timestamp()),
672
+ ... ]
673
+ ... )
674
+
675
+ >>> print(on_duplicate_key_stmt)
676
+ {printsql}INSERT INTO my_table (id, data) VALUES (%s, %s)
677
+ ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP
678
+
679
+ .. warning::
680
+
681
+ The :meth:`_mysql.Insert.on_duplicate_key_update`
682
+ method does **not** take into
683
+ account Python-side default UPDATE values or generation functions, e.g.
684
+ e.g. those specified using :paramref:`_schema.Column.onupdate`.
685
+ These values will not be exercised for an ON DUPLICATE KEY style of UPDATE,
686
+ unless they are manually specified explicitly in the parameters.
687
+
688
+
689
+
690
+ In order to refer to the proposed insertion row, the special alias
691
+ :attr:`_mysql.Insert.inserted` is available as an attribute on
692
+ the :class:`_mysql.Insert` object; this object is a
693
+ :class:`_expression.ColumnCollection` which contains all columns of the target
694
+ table:
695
+
696
+ .. sourcecode:: pycon+sql
697
+
698
+ >>> stmt = insert(my_table).values(
699
+ ... id="some_id", data="inserted value", author="jlh"
700
+ ... )
701
+
702
+ >>> do_update_stmt = stmt.on_duplicate_key_update(
703
+ ... data="updated value", author=stmt.inserted.author
704
+ ... )
705
+
706
+ >>> print(do_update_stmt)
707
+ {printsql}INSERT INTO my_table (id, data, author) VALUES (%s, %s, %s)
708
+ ON DUPLICATE KEY UPDATE data = %s, author = VALUES(author)
709
+
710
+ When rendered, the "inserted" namespace will produce the expression
711
+ ``VALUES(<columnname>)``.
712
+
713
+ rowcount Support
714
+ ----------------
715
+
716
+ SQLAlchemy standardizes the DBAPI ``cursor.rowcount`` attribute to be the
717
+ usual definition of "number of rows matched by an UPDATE or DELETE" statement.
718
+ This is in contradiction to the default setting on most MySQL DBAPI drivers,
719
+ which is "number of rows actually modified/deleted". For this reason, the
720
+ SQLAlchemy MySQL dialects always add the ``constants.CLIENT.FOUND_ROWS``
721
+ flag, or whatever is equivalent for the target dialect, upon connection.
722
+ This setting is currently hardcoded.
723
+
724
+ .. seealso::
725
+
726
+ :attr:`_engine.CursorResult.rowcount`
727
+
728
+
729
+ .. _mysql_indexes:
730
+
731
+ MySQL / MariaDB- Specific Index Options
732
+ -----------------------------------------
733
+
734
+ MySQL and MariaDB-specific extensions to the :class:`.Index` construct are available.
735
+
736
+ Index Length
737
+ ~~~~~~~~~~~~~
738
+
739
+ MySQL and MariaDB both provide an option to create index entries with a certain length, where
740
+ "length" refers to the number of characters or bytes in each value which will
741
+ become part of the index. SQLAlchemy provides this feature via the
742
+ ``mysql_length`` and/or ``mariadb_length`` parameters::
743
+
744
+ Index("my_index", my_table.c.data, mysql_length=10, mariadb_length=10)
745
+
746
+ Index("a_b_idx", my_table.c.a, my_table.c.b, mysql_length={"a": 4, "b": 9})
747
+
748
+ Index(
749
+ "a_b_idx", my_table.c.a, my_table.c.b, mariadb_length={"a": 4, "b": 9}
750
+ )
751
+
752
+ Prefix lengths are given in characters for nonbinary string types and in bytes
753
+ for binary string types. The value passed to the keyword argument *must* be
754
+ either an integer (and, thus, specify the same prefix length value for all
755
+ columns of the index) or a dict in which keys are column names and values are
756
+ prefix length values for corresponding columns. MySQL and MariaDB only allow a
757
+ length for a column of an index if it is for a CHAR, VARCHAR, TEXT, BINARY,
758
+ VARBINARY and BLOB.
759
+
760
+ Index Prefixes
761
+ ~~~~~~~~~~~~~~
762
+
763
+ MySQL storage engines permit you to specify an index prefix when creating
764
+ an index. SQLAlchemy provides this feature via the
765
+ ``mysql_prefix`` parameter on :class:`.Index`::
766
+
767
+ Index("my_index", my_table.c.data, mysql_prefix="FULLTEXT")
768
+
769
+ The value passed to the keyword argument will be simply passed through to the
770
+ underlying CREATE INDEX, so it *must* be a valid index prefix for your MySQL
771
+ storage engine.
772
+
773
+ .. seealso::
774
+
775
+ `CREATE INDEX <https://dev.mysql.com/doc/refman/5.0/en/create-index.html>`_ - MySQL documentation
776
+
777
+ Index Types
778
+ ~~~~~~~~~~~~~
779
+
780
+ Some MySQL storage engines permit you to specify an index type when creating
781
+ an index or primary key constraint. SQLAlchemy provides this feature via the
782
+ ``mysql_using`` parameter on :class:`.Index`::
783
+
784
+ Index(
785
+ "my_index", my_table.c.data, mysql_using="hash", mariadb_using="hash"
786
+ )
787
+
788
+ As well as the ``mysql_using`` parameter on :class:`.PrimaryKeyConstraint`::
789
+
790
+ PrimaryKeyConstraint("data", mysql_using="hash", mariadb_using="hash")
791
+
792
+ The value passed to the keyword argument will be simply passed through to the
793
+ underlying CREATE INDEX or PRIMARY KEY clause, so it *must* be a valid index
794
+ type for your MySQL storage engine.
795
+
796
+ More information can be found at:
797
+
798
+ https://dev.mysql.com/doc/refman/5.0/en/create-index.html
799
+
800
+ https://dev.mysql.com/doc/refman/5.0/en/create-table.html
801
+
802
+ Index Parsers
803
+ ~~~~~~~~~~~~~
804
+
805
+ CREATE FULLTEXT INDEX in MySQL also supports a "WITH PARSER" option. This
806
+ is available using the keyword argument ``mysql_with_parser``::
807
+
808
+ Index(
809
+ "my_index",
810
+ my_table.c.data,
811
+ mysql_prefix="FULLTEXT",
812
+ mysql_with_parser="ngram",
813
+ mariadb_prefix="FULLTEXT",
814
+ mariadb_with_parser="ngram",
815
+ )
816
+
817
+ .. _mysql_foreign_keys:
818
+
819
+ MySQL / MariaDB Foreign Keys
820
+ -----------------------------
821
+
822
+ MySQL and MariaDB's behavior regarding foreign keys has some important caveats.
823
+
824
+ Foreign Key Arguments to Avoid
825
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
826
+
827
+ Neither MySQL nor MariaDB support the foreign key arguments "DEFERRABLE", "INITIALLY",
828
+ or "MATCH". Using the ``deferrable`` or ``initially`` keyword argument with
829
+ :class:`_schema.ForeignKeyConstraint` or :class:`_schema.ForeignKey`
830
+ will have the effect of
831
+ these keywords being rendered in a DDL expression, which will then raise an
832
+ error on MySQL or MariaDB. In order to use these keywords on a foreign key while having
833
+ them ignored on a MySQL / MariaDB backend, use a custom compile rule::
834
+
835
+ from sqlalchemy.ext.compiler import compiles
836
+ from sqlalchemy.schema import ForeignKeyConstraint
837
+
838
+
839
+ @compiles(ForeignKeyConstraint, "mysql", "mariadb")
840
+ def process(element, compiler, **kw):
841
+ element.deferrable = element.initially = None
842
+ return compiler.visit_foreign_key_constraint(element, **kw)
843
+
844
+ The "MATCH" keyword is in fact more insidious, and is explicitly disallowed
845
+ by SQLAlchemy in conjunction with the MySQL or MariaDB backends. This argument is
846
+ silently ignored by MySQL / MariaDB, but in addition has the effect of ON UPDATE and ON
847
+ DELETE options also being ignored by the backend. Therefore MATCH should
848
+ never be used with the MySQL / MariaDB backends; as is the case with DEFERRABLE and
849
+ INITIALLY, custom compilation rules can be used to correct a
850
+ ForeignKeyConstraint at DDL definition time.
851
+
852
+ Reflection of Foreign Key Constraints
853
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
854
+
855
+ Not all MySQL / MariaDB storage engines support foreign keys. When using the
856
+ very common ``MyISAM`` MySQL storage engine, the information loaded by table
857
+ reflection will not include foreign keys. For these tables, you may supply a
858
+ :class:`~sqlalchemy.ForeignKeyConstraint` at reflection time::
859
+
860
+ Table(
861
+ "mytable",
862
+ metadata,
863
+ ForeignKeyConstraint(["other_id"], ["othertable.other_id"]),
864
+ autoload_with=engine,
865
+ )
866
+
867
+ .. seealso::
868
+
869
+ :ref:`mysql_storage_engines`
870
+
871
+ .. _mysql_unique_constraints:
872
+
873
+ MySQL / MariaDB Unique Constraints and Reflection
874
+ ----------------------------------------------------
875
+
876
+ SQLAlchemy supports both the :class:`.Index` construct with the
877
+ flag ``unique=True``, indicating a UNIQUE index, as well as the
878
+ :class:`.UniqueConstraint` construct, representing a UNIQUE constraint.
879
+ Both objects/syntaxes are supported by MySQL / MariaDB when emitting DDL to create
880
+ these constraints. However, MySQL / MariaDB does not have a unique constraint
881
+ construct that is separate from a unique index; that is, the "UNIQUE"
882
+ constraint on MySQL / MariaDB is equivalent to creating a "UNIQUE INDEX".
883
+
884
+ When reflecting these constructs, the
885
+ :meth:`_reflection.Inspector.get_indexes`
886
+ and the :meth:`_reflection.Inspector.get_unique_constraints`
887
+ methods will **both**
888
+ return an entry for a UNIQUE index in MySQL / MariaDB. However, when performing
889
+ full table reflection using ``Table(..., autoload_with=engine)``,
890
+ the :class:`.UniqueConstraint` construct is
891
+ **not** part of the fully reflected :class:`_schema.Table` construct under any
892
+ circumstances; this construct is always represented by a :class:`.Index`
893
+ with the ``unique=True`` setting present in the :attr:`_schema.Table.indexes`
894
+ collection.
895
+
896
+
897
+ TIMESTAMP / DATETIME issues
898
+ ---------------------------
899
+
900
+ .. _mysql_timestamp_onupdate:
901
+
902
+ Rendering ON UPDATE CURRENT TIMESTAMP for MySQL / MariaDB's explicit_defaults_for_timestamp
903
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
904
+
905
+ MySQL / MariaDB have historically expanded the DDL for the :class:`_types.TIMESTAMP`
906
+ datatype into the phrase "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
907
+ CURRENT_TIMESTAMP", which includes non-standard SQL that automatically updates
908
+ the column with the current timestamp when an UPDATE occurs, eliminating the
909
+ usual need to use a trigger in such a case where server-side update changes are
910
+ desired.
911
+
912
+ MySQL 5.6 introduced a new flag `explicit_defaults_for_timestamp
913
+ <https://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html
914
+ #sysvar_explicit_defaults_for_timestamp>`_ which disables the above behavior,
915
+ and in MySQL 8 this flag defaults to true, meaning in order to get a MySQL
916
+ "on update timestamp" without changing this flag, the above DDL must be
917
+ rendered explicitly. Additionally, the same DDL is valid for use of the
918
+ ``DATETIME`` datatype as well.
919
+
920
+ SQLAlchemy's MySQL dialect does not yet have an option to generate
921
+ MySQL's "ON UPDATE CURRENT_TIMESTAMP" clause, noting that this is not a general
922
+ purpose "ON UPDATE" as there is no such syntax in standard SQL. SQLAlchemy's
923
+ :paramref:`_schema.Column.server_onupdate` parameter is currently not related
924
+ to this special MySQL behavior.
925
+
926
+ To generate this DDL, make use of the :paramref:`_schema.Column.server_default`
927
+ parameter and pass a textual clause that also includes the ON UPDATE clause::
928
+
929
+ from sqlalchemy import Table, MetaData, Column, Integer, String, TIMESTAMP
930
+ from sqlalchemy import text
931
+
932
+ metadata = MetaData()
933
+
934
+ mytable = Table(
935
+ "mytable",
936
+ metadata,
937
+ Column("id", Integer, primary_key=True),
938
+ Column("data", String(50)),
939
+ Column(
940
+ "last_updated",
941
+ TIMESTAMP,
942
+ server_default=text(
943
+ "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
944
+ ),
945
+ ),
946
+ )
947
+
948
+ The same instructions apply to use of the :class:`_types.DateTime` and
949
+ :class:`_types.DATETIME` datatypes::
950
+
951
+ from sqlalchemy import DateTime
952
+
953
+ mytable = Table(
954
+ "mytable",
955
+ metadata,
956
+ Column("id", Integer, primary_key=True),
957
+ Column("data", String(50)),
958
+ Column(
959
+ "last_updated",
960
+ DateTime,
961
+ server_default=text(
962
+ "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
963
+ ),
964
+ ),
965
+ )
966
+
967
+ Even though the :paramref:`_schema.Column.server_onupdate` feature does not
968
+ generate this DDL, it still may be desirable to signal to the ORM that this
969
+ updated value should be fetched. This syntax looks like the following::
970
+
971
+ from sqlalchemy.schema import FetchedValue
972
+
973
+
974
+ class MyClass(Base):
975
+ __tablename__ = "mytable"
976
+
977
+ id = Column(Integer, primary_key=True)
978
+ data = Column(String(50))
979
+ last_updated = Column(
980
+ TIMESTAMP,
981
+ server_default=text(
982
+ "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
983
+ ),
984
+ server_onupdate=FetchedValue(),
985
+ )
986
+
987
+ .. _mysql_timestamp_null:
988
+
989
+ TIMESTAMP Columns and NULL
990
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
991
+
992
+ MySQL historically enforces that a column which specifies the
993
+ TIMESTAMP datatype implicitly includes a default value of
994
+ CURRENT_TIMESTAMP, even though this is not stated, and additionally
995
+ sets the column as NOT NULL, the opposite behavior vs. that of all
996
+ other datatypes:
997
+
998
+ .. sourcecode:: text
999
+
1000
+ mysql> CREATE TABLE ts_test (
1001
+ -> a INTEGER,
1002
+ -> b INTEGER NOT NULL,
1003
+ -> c TIMESTAMP,
1004
+ -> d TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
1005
+ -> e TIMESTAMP NULL);
1006
+ Query OK, 0 rows affected (0.03 sec)
1007
+
1008
+ mysql> SHOW CREATE TABLE ts_test;
1009
+ +---------+-----------------------------------------------------
1010
+ | Table | Create Table
1011
+ +---------+-----------------------------------------------------
1012
+ | ts_test | CREATE TABLE `ts_test` (
1013
+ `a` int(11) DEFAULT NULL,
1014
+ `b` int(11) NOT NULL,
1015
+ `c` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
1016
+ `d` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
1017
+ `e` timestamp NULL DEFAULT NULL
1018
+ ) ENGINE=MyISAM DEFAULT CHARSET=latin1
1019
+
1020
+ Above, we see that an INTEGER column defaults to NULL, unless it is specified
1021
+ with NOT NULL. But when the column is of type TIMESTAMP, an implicit
1022
+ default of CURRENT_TIMESTAMP is generated which also coerces the column
1023
+ to be a NOT NULL, even though we did not specify it as such.
1024
+
1025
+ This behavior of MySQL can be changed on the MySQL side using the
1026
+ `explicit_defaults_for_timestamp
1027
+ <https://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html
1028
+ #sysvar_explicit_defaults_for_timestamp>`_ configuration flag introduced in
1029
+ MySQL 5.6. With this server setting enabled, TIMESTAMP columns behave like
1030
+ any other datatype on the MySQL side with regards to defaults and nullability.
1031
+
1032
+ However, to accommodate the vast majority of MySQL databases that do not
1033
+ specify this new flag, SQLAlchemy emits the "NULL" specifier explicitly with
1034
+ any TIMESTAMP column that does not specify ``nullable=False``. In order to
1035
+ accommodate newer databases that specify ``explicit_defaults_for_timestamp``,
1036
+ SQLAlchemy also emits NOT NULL for TIMESTAMP columns that do specify
1037
+ ``nullable=False``. The following example illustrates::
1038
+
1039
+ from sqlalchemy import MetaData, Integer, Table, Column, text
1040
+ from sqlalchemy.dialects.mysql import TIMESTAMP
1041
+
1042
+ m = MetaData()
1043
+ t = Table(
1044
+ "ts_test",
1045
+ m,
1046
+ Column("a", Integer),
1047
+ Column("b", Integer, nullable=False),
1048
+ Column("c", TIMESTAMP),
1049
+ Column("d", TIMESTAMP, nullable=False),
1050
+ )
1051
+
1052
+
1053
+ from sqlalchemy import create_engine
1054
+
1055
+ e = create_engine("mysql+mysqldb://scott:tiger@localhost/test", echo=True)
1056
+ m.create_all(e)
1057
+
1058
+ output:
1059
+
1060
+ .. sourcecode:: sql
1061
+
1062
+ CREATE TABLE ts_test (
1063
+ a INTEGER,
1064
+ b INTEGER NOT NULL,
1065
+ c TIMESTAMP NULL,
1066
+ d TIMESTAMP NOT NULL
1067
+ )
1068
+
1069
+ """ # noqa
1070
+
1071
+ from __future__ import annotations
1072
+
1073
+ from collections import defaultdict
1074
+ from itertools import compress
1075
+ import re
1076
+ from typing import Any
1077
+ from typing import Callable
1078
+ from typing import cast
1079
+ from typing import NoReturn
1080
+ from typing import Optional
1081
+ from typing import overload
1082
+ from typing import Sequence
1083
+ from typing import TYPE_CHECKING
1084
+ from typing import TypeVar
1085
+ from typing import Union
1086
+
1087
+ from . import _mariadb_shim
1088
+ from . import reflection as _reflection
1089
+ from .enumerated import ENUM
1090
+ from .enumerated import SET
1091
+ from .json import JSON
1092
+ from .json import JSONIndexType
1093
+ from .json import JSONPathType
1094
+ from .reserved_words import RESERVED_WORDS_MYSQL
1095
+ from .types import _FloatType
1096
+ from .types import _IntegerType
1097
+ from .types import _MatchType
1098
+ from .types import _NumericCommonType
1099
+ from .types import _NumericType
1100
+ from .types import _StringType
1101
+ from .types import BIGINT
1102
+ from .types import BIT
1103
+ from .types import CHAR
1104
+ from .types import DATETIME
1105
+ from .types import DECIMAL
1106
+ from .types import DOUBLE
1107
+ from .types import FLOAT
1108
+ from .types import INTEGER
1109
+ from .types import LONGBLOB
1110
+ from .types import LONGTEXT
1111
+ from .types import MEDIUMBLOB
1112
+ from .types import MEDIUMINT
1113
+ from .types import MEDIUMTEXT
1114
+ from .types import NCHAR
1115
+ from .types import NUMERIC
1116
+ from .types import NVARCHAR
1117
+ from .types import REAL
1118
+ from .types import SMALLINT
1119
+ from .types import TEXT
1120
+ from .types import TIME
1121
+ from .types import TIMESTAMP
1122
+ from .types import TINYBLOB
1123
+ from .types import TINYINT
1124
+ from .types import TINYTEXT
1125
+ from .types import VARCHAR
1126
+ from .types import YEAR
1127
+ from ... import exc
1128
+ from ... import literal_column
1129
+ from ... import schema as sa_schema
1130
+ from ... import sql
1131
+ from ... import util
1132
+ from ...engine import default
1133
+ from ...engine import reflection
1134
+ from ...engine.reflection import ReflectionDefaults
1135
+ from ...sql import coercions
1136
+ from ...sql import compiler
1137
+ from ...sql import elements
1138
+ from ...sql import functions
1139
+ from ...sql import operators
1140
+ from ...sql import roles
1141
+ from ...sql import sqltypes
1142
+ from ...sql import util as sql_util
1143
+ from ...sql import visitors
1144
+ from ...sql.compiler import InsertmanyvaluesSentinelOpts
1145
+ from ...types import BINARY
1146
+ from ...types import BLOB
1147
+ from ...types import BOOLEAN
1148
+ from ...types import DATE
1149
+ from ...types import LargeBinary
1150
+ from ...types import UUID
1151
+ from ...types import VARBINARY
1152
+ from ...util import OrderedSet
1153
+ from ...util import topological
1154
+
1155
+ if TYPE_CHECKING:
1156
+
1157
+ from ...dialects.mysql import expression
1158
+ from ...dialects.mysql.dml import DMLLimitClause
1159
+ from ...dialects.mysql.dml import OnDuplicateClause
1160
+ from ...engine.base import Connection
1161
+ from ...engine.cursor import CursorResult
1162
+ from ...engine.interfaces import DBAPIConnection
1163
+ from ...engine.interfaces import DBAPICursor
1164
+ from ...engine.interfaces import DBAPIModule
1165
+ from ...engine.interfaces import IsolationLevel
1166
+ from ...engine.interfaces import PoolProxiedConnection
1167
+ from ...engine.interfaces import ReflectedCheckConstraint
1168
+ from ...engine.interfaces import ReflectedColumn
1169
+ from ...engine.interfaces import ReflectedForeignKeyConstraint
1170
+ from ...engine.interfaces import ReflectedIndex
1171
+ from ...engine.interfaces import ReflectedPrimaryKeyConstraint
1172
+ from ...engine.interfaces import ReflectedTableComment
1173
+ from ...engine.interfaces import ReflectedUniqueConstraint
1174
+ from ...engine.result import _Ts
1175
+ from ...engine.row import Row
1176
+ from ...schema import Table
1177
+ from ...sql import ddl
1178
+ from ...sql import selectable
1179
+ from ...sql.dml import _DMLTableElement
1180
+ from ...sql.dml import Delete
1181
+ from ...sql.dml import Update
1182
+ from ...sql.dml import ValuesBase
1183
+ from ...sql.functions import aggregate_strings
1184
+ from ...sql.functions import random
1185
+ from ...sql.functions import rollup
1186
+ from ...sql.functions import sysdate
1187
+ from ...sql.sqltypes import _JSON_VALUE
1188
+ from ...sql.type_api import TypeEngine
1189
+ from ...sql.visitors import ExternallyTraversible
1190
+ from ...util.typing import TupleAny
1191
+ from ...util.typing import Unpack
1192
+
1193
+ _T = TypeVar("_T", bound=Any)
1194
+ SET_RE = re.compile(
1195
+ r"\s*SET\s+(?:(?:GLOBAL|SESSION)\s+)?\w", re.I | re.UNICODE
1196
+ )
1197
+
1198
+ # old names
1199
+ MSTime = TIME
1200
+ MSSet = SET
1201
+ MSEnum = ENUM
1202
+ MSLongBlob = LONGBLOB
1203
+ MSMediumBlob = MEDIUMBLOB
1204
+ MSTinyBlob = TINYBLOB
1205
+ MSBlob = BLOB
1206
+ MSBinary = BINARY
1207
+ MSVarBinary = VARBINARY
1208
+ MSNChar = NCHAR
1209
+ MSNVarChar = NVARCHAR
1210
+ MSChar = CHAR
1211
+ MSString = VARCHAR
1212
+ MSLongText = LONGTEXT
1213
+ MSMediumText = MEDIUMTEXT
1214
+ MSTinyText = TINYTEXT
1215
+ MSText = TEXT
1216
+ MSYear = YEAR
1217
+ MSTimeStamp = TIMESTAMP
1218
+ MSBit = BIT
1219
+ MSSmallInteger = SMALLINT
1220
+ MSTinyInteger = TINYINT
1221
+ MSMediumInteger = MEDIUMINT
1222
+ MSBigInteger = BIGINT
1223
+ MSNumeric = NUMERIC
1224
+ MSDecimal = DECIMAL
1225
+ MSDouble = DOUBLE
1226
+ MSReal = REAL
1227
+ MSFloat = FLOAT
1228
+ MSInteger = INTEGER
1229
+
1230
+ colspecs = {
1231
+ _IntegerType: _IntegerType,
1232
+ _NumericCommonType: _NumericCommonType,
1233
+ _NumericType: _NumericType,
1234
+ _FloatType: _FloatType,
1235
+ sqltypes.Numeric: NUMERIC,
1236
+ sqltypes.Float: FLOAT,
1237
+ sqltypes.Double: DOUBLE,
1238
+ sqltypes.Time: TIME,
1239
+ sqltypes.Enum: ENUM,
1240
+ sqltypes.MatchType: _MatchType,
1241
+ sqltypes.JSON: JSON,
1242
+ sqltypes.JSON.JSONIndexType: JSONIndexType,
1243
+ sqltypes.JSON.JSONPathType: JSONPathType,
1244
+ }
1245
+
1246
+ # Everything 3.23 through 5.1 excepting OpenGIS types.
1247
+ ischema_names = {
1248
+ "bigint": BIGINT,
1249
+ "binary": BINARY,
1250
+ "bit": BIT,
1251
+ "blob": BLOB,
1252
+ "boolean": BOOLEAN,
1253
+ "char": CHAR,
1254
+ "date": DATE,
1255
+ "datetime": DATETIME,
1256
+ "decimal": DECIMAL,
1257
+ "double": DOUBLE,
1258
+ "enum": ENUM,
1259
+ "fixed": DECIMAL,
1260
+ "float": FLOAT,
1261
+ "int": INTEGER,
1262
+ "integer": INTEGER,
1263
+ "json": JSON,
1264
+ "longblob": LONGBLOB,
1265
+ "longtext": LONGTEXT,
1266
+ "mediumblob": MEDIUMBLOB,
1267
+ "mediumint": MEDIUMINT,
1268
+ "mediumtext": MEDIUMTEXT,
1269
+ "nchar": NCHAR,
1270
+ "nvarchar": NVARCHAR,
1271
+ "numeric": NUMERIC,
1272
+ "set": SET,
1273
+ "smallint": SMALLINT,
1274
+ "text": TEXT,
1275
+ "time": TIME,
1276
+ "timestamp": TIMESTAMP,
1277
+ "tinyblob": TINYBLOB,
1278
+ "tinyint": TINYINT,
1279
+ "tinytext": TINYTEXT,
1280
+ "uuid": UUID,
1281
+ "varbinary": VARBINARY,
1282
+ "varchar": VARCHAR,
1283
+ "year": YEAR,
1284
+ }
1285
+
1286
+
1287
+ class MySQLExecutionContext(
1288
+ _mariadb_shim.MariadbExecutionContextShim, default.DefaultExecutionContext
1289
+ ):
1290
+ def create_server_side_cursor(self) -> DBAPICursor:
1291
+ if self.dialect.supports_server_side_cursors:
1292
+ return self._dbapi_connection.cursor(
1293
+ self.dialect._sscursor # type: ignore[attr-defined]
1294
+ )
1295
+ else:
1296
+ raise NotImplementedError()
1297
+
1298
+
1299
+ class MySQLCompiler(
1300
+ _mariadb_shim.MariaDBSQLCompilerShim, compiler.SQLCompiler
1301
+ ):
1302
+ dialect: MySQLDialect
1303
+ render_table_with_column_in_update_from = True
1304
+ """Overridden from base SQLCompiler value"""
1305
+
1306
+ extract_map = compiler.SQLCompiler.extract_map.copy()
1307
+ extract_map.update({"milliseconds": "millisecond"})
1308
+
1309
+ def default_from(self) -> str:
1310
+ """Called when a ``SELECT`` statement has no froms,
1311
+ and no ``FROM`` clause is to be appended.
1312
+
1313
+ """
1314
+ if self.stack:
1315
+ stmt = self.stack[-1]["selectable"]
1316
+ if stmt._where_criteria: # type: ignore[attr-defined]
1317
+ return " FROM DUAL"
1318
+
1319
+ return ""
1320
+
1321
+ def visit_random_func(self, fn: random, **kw: Any) -> str:
1322
+ return "rand%s" % self.function_argspec(fn)
1323
+
1324
+ def visit_rollup_func(self, fn: rollup[Any], **kw: Any) -> str:
1325
+ clause = ", ".join(
1326
+ elem._compiler_dispatch(self, **kw) for elem in fn.clauses
1327
+ )
1328
+ return f"{clause} WITH ROLLUP"
1329
+
1330
+ def visit_aggregate_strings_func(
1331
+ self, fn: aggregate_strings, **kw: Any
1332
+ ) -> str:
1333
+
1334
+ order_by = getattr(fn.clauses, "aggregate_order_by", None)
1335
+
1336
+ cl = list(fn.clauses)
1337
+ expr, delimiter = cl[0:2]
1338
+
1339
+ literal_exec = dict(kw)
1340
+ literal_exec["literal_execute"] = True
1341
+
1342
+ if order_by is not None:
1343
+ return (
1344
+ f"group_concat({expr._compiler_dispatch(self, **kw)} "
1345
+ f"ORDER BY {order_by._compiler_dispatch(self, **kw)} "
1346
+ "SEPARATOR "
1347
+ f"{delimiter._compiler_dispatch(self, **literal_exec)})"
1348
+ )
1349
+ else:
1350
+ return (
1351
+ f"group_concat({expr._compiler_dispatch(self, **kw)} "
1352
+ "SEPARATOR "
1353
+ f"{delimiter._compiler_dispatch(self, **literal_exec)})"
1354
+ )
1355
+
1356
+ def visit_sysdate_func(self, fn: sysdate, **kw: Any) -> str:
1357
+ return "SYSDATE()"
1358
+
1359
+ def _render_json_extract_from_binary(
1360
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1361
+ ) -> str:
1362
+ # note we are intentionally calling upon the process() calls in the
1363
+ # order in which they appear in the SQL String as this is used
1364
+ # by positional parameter rendering
1365
+
1366
+ if binary.type._type_affinity is sqltypes.JSON:
1367
+ return "JSON_EXTRACT(%s, %s)" % (
1368
+ self.process(binary.left, **kw),
1369
+ self.process(binary.right, **kw),
1370
+ )
1371
+
1372
+ # for non-JSON, MySQL doesn't handle JSON null at all so it has to
1373
+ # be explicit
1374
+ case_expression = "CASE JSON_EXTRACT(%s, %s) WHEN 'null' THEN NULL" % (
1375
+ self.process(binary.left, **kw),
1376
+ self.process(binary.right, **kw),
1377
+ )
1378
+
1379
+ if binary.type._type_affinity is sqltypes.Integer:
1380
+ type_expression = (
1381
+ "ELSE CAST(JSON_EXTRACT(%s, %s) AS SIGNED INTEGER)"
1382
+ % (
1383
+ self.process(binary.left, **kw),
1384
+ self.process(binary.right, **kw),
1385
+ )
1386
+ )
1387
+ elif binary.type._type_affinity in (sqltypes.Numeric, sqltypes.Float):
1388
+ binary_type = cast(sqltypes.Numeric[Any], binary.type)
1389
+ if (
1390
+ binary_type.scale is not None
1391
+ and binary_type.precision is not None
1392
+ ):
1393
+ # using DECIMAL here because MySQL does not recognize NUMERIC
1394
+ type_expression = (
1395
+ "ELSE CAST(JSON_EXTRACT(%s, %s) AS DECIMAL(%s, %s))"
1396
+ % (
1397
+ self.process(binary.left, **kw),
1398
+ self.process(binary.right, **kw),
1399
+ binary_type.precision,
1400
+ binary_type.scale,
1401
+ )
1402
+ )
1403
+ else:
1404
+ # FLOAT / REAL not added in MySQL til 8.0.17
1405
+ type_expression = (
1406
+ "ELSE JSON_EXTRACT(%s, %s)+0.0000000000000000000000"
1407
+ % (
1408
+ self.process(binary.left, **kw),
1409
+ self.process(binary.right, **kw),
1410
+ )
1411
+ )
1412
+ elif binary.type._type_affinity is sqltypes.Boolean:
1413
+ # the NULL handling is particularly weird with boolean, so
1414
+ # explicitly return true/false constants
1415
+ type_expression = "WHEN true THEN true ELSE false"
1416
+ elif binary.type._type_affinity is sqltypes.String:
1417
+ # (gord): this fails with a JSON value that's a four byte unicode
1418
+ # string. SQLite has the same problem at the moment
1419
+ # (zzzeek): I'm not really sure. let's take a look at a test case
1420
+ # that hits each backend and maybe make a requires rule for it?
1421
+ type_expression = "ELSE JSON_UNQUOTE(JSON_EXTRACT(%s, %s))" % (
1422
+ self.process(binary.left, **kw),
1423
+ self.process(binary.right, **kw),
1424
+ )
1425
+ else:
1426
+ # other affinity....this is not expected right now
1427
+ type_expression = "ELSE JSON_EXTRACT(%s, %s)" % (
1428
+ self.process(binary.left, **kw),
1429
+ self.process(binary.right, **kw),
1430
+ )
1431
+
1432
+ return case_expression + " " + type_expression + " END"
1433
+
1434
+ def visit_json_getitem_op_binary(
1435
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1436
+ ) -> str:
1437
+ return self._render_json_extract_from_binary(binary, operator, **kw)
1438
+
1439
+ def visit_json_path_getitem_op_binary(
1440
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1441
+ ) -> str:
1442
+ return self._render_json_extract_from_binary(binary, operator, **kw)
1443
+
1444
+ def visit_on_duplicate_key_update(
1445
+ self, on_duplicate: OnDuplicateClause, **kw: Any
1446
+ ) -> str:
1447
+ statement: ValuesBase = self.current_executable
1448
+
1449
+ cols: list[elements.KeyedColumnElement[Any]]
1450
+ if on_duplicate._parameter_ordering:
1451
+ parameter_ordering = [
1452
+ coercions.expect(roles.DMLColumnRole, key)
1453
+ for key in on_duplicate._parameter_ordering
1454
+ ]
1455
+ ordered_keys = set(parameter_ordering)
1456
+ cols = [
1457
+ statement.table.c[key]
1458
+ for key in parameter_ordering
1459
+ if key in statement.table.c
1460
+ ] + [c for c in statement.table.c if c.key not in ordered_keys]
1461
+ else:
1462
+ cols = list(statement.table.c)
1463
+
1464
+ clauses = []
1465
+
1466
+ requires_mysql8_alias = statement.select is None and (
1467
+ self.dialect._requires_alias_for_on_duplicate_key
1468
+ )
1469
+
1470
+ if requires_mysql8_alias:
1471
+ if statement.table.name.lower() == "new": # type: ignore[union-attr] # noqa: E501
1472
+ _on_dup_alias_name = "new_1"
1473
+ else:
1474
+ _on_dup_alias_name = "new"
1475
+
1476
+ on_duplicate_update = {
1477
+ coercions.expect_as_key(roles.DMLColumnRole, key): value
1478
+ for key, value in on_duplicate.update.items()
1479
+ }
1480
+
1481
+ # traverses through all table columns to preserve table column order
1482
+ for column in (col for col in cols if col.key in on_duplicate_update):
1483
+ val = on_duplicate_update[column.key]
1484
+
1485
+ def replace(
1486
+ element: ExternallyTraversible, **kw: Any
1487
+ ) -> Optional[ExternallyTraversible]:
1488
+ if (
1489
+ isinstance(element, elements.BindParameter)
1490
+ and element.type._isnull
1491
+ ):
1492
+ return element._with_binary_element_type(column.type)
1493
+ elif (
1494
+ isinstance(element, elements.ColumnClause)
1495
+ and element.table is on_duplicate.inserted_alias
1496
+ ):
1497
+ if requires_mysql8_alias:
1498
+ column_literal_clause = (
1499
+ f"{_on_dup_alias_name}."
1500
+ f"{self.preparer.quote(element.name)}"
1501
+ )
1502
+ else:
1503
+ column_literal_clause = (
1504
+ f"VALUES({self.preparer.quote(element.name)})"
1505
+ )
1506
+ return literal_column(column_literal_clause)
1507
+ else:
1508
+ # element is not replaced
1509
+ return None
1510
+
1511
+ val = visitors.replacement_traverse(val, {}, replace)
1512
+ value_text = self.process(val.self_group(), use_schema=False)
1513
+
1514
+ name_text = self.preparer.quote(column.name)
1515
+ clauses.append("%s = %s" % (name_text, value_text))
1516
+
1517
+ non_matching = set(on_duplicate_update) - {c.key for c in cols}
1518
+ if non_matching:
1519
+ util.warn(
1520
+ "Additional column names not matching "
1521
+ "any column keys in table '%s': %s"
1522
+ % (
1523
+ self.statement.table.name, # type: ignore[union-attr]
1524
+ ", ".join("'%s'" % c for c in non_matching),
1525
+ )
1526
+ )
1527
+
1528
+ if requires_mysql8_alias:
1529
+ return (
1530
+ f"AS {_on_dup_alias_name} "
1531
+ f"ON DUPLICATE KEY UPDATE {', '.join(clauses)}"
1532
+ )
1533
+ else:
1534
+ return f"ON DUPLICATE KEY UPDATE {', '.join(clauses)}"
1535
+
1536
+ def visit_concat_op_expression_clauselist(
1537
+ self, clauselist: elements.ClauseList, operator: Any, **kw: Any
1538
+ ) -> str:
1539
+ return "concat(%s)" % ", ".join(
1540
+ self.process(elem, **kw) for elem in clauselist.clauses
1541
+ )
1542
+
1543
+ def visit_concat_op_binary(
1544
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1545
+ ) -> str:
1546
+ return "concat(%s, %s)" % (
1547
+ self.process(binary.left, **kw),
1548
+ self.process(binary.right, **kw),
1549
+ )
1550
+
1551
+ _match_valid_flag_combinations = frozenset(
1552
+ (
1553
+ # (boolean_mode, natural_language, query_expansion)
1554
+ (False, False, False),
1555
+ (True, False, False),
1556
+ (False, True, False),
1557
+ (False, False, True),
1558
+ (False, True, True),
1559
+ )
1560
+ )
1561
+
1562
+ _match_flag_expressions = (
1563
+ "IN BOOLEAN MODE",
1564
+ "IN NATURAL LANGUAGE MODE",
1565
+ "WITH QUERY EXPANSION",
1566
+ )
1567
+
1568
+ def visit_mysql_match(self, element: expression.match, **kw: Any) -> str:
1569
+ return self.visit_match_op_binary(element, element.operator, **kw)
1570
+
1571
+ def visit_match_op_binary(
1572
+ self, binary: expression.match, operator: Any, **kw: Any
1573
+ ) -> str:
1574
+ """
1575
+ Note that `mysql_boolean_mode` is enabled by default because of
1576
+ backward compatibility
1577
+ """
1578
+
1579
+ modifiers = binary.modifiers
1580
+
1581
+ boolean_mode = modifiers.get("mysql_boolean_mode", True)
1582
+ natural_language = modifiers.get("mysql_natural_language", False)
1583
+ query_expansion = modifiers.get("mysql_query_expansion", False)
1584
+
1585
+ flag_combination = (boolean_mode, natural_language, query_expansion)
1586
+
1587
+ if flag_combination not in self._match_valid_flag_combinations:
1588
+ flags = (
1589
+ "in_boolean_mode=%s" % boolean_mode,
1590
+ "in_natural_language_mode=%s" % natural_language,
1591
+ "with_query_expansion=%s" % query_expansion,
1592
+ )
1593
+
1594
+ flags_str = ", ".join(flags)
1595
+
1596
+ raise exc.CompileError("Invalid MySQL match flags: %s" % flags_str)
1597
+
1598
+ match_clause = self.process(binary.left, **kw)
1599
+ against_clause = self.process(binary.right, **kw)
1600
+
1601
+ if any(flag_combination):
1602
+ flag_expressions = compress(
1603
+ self._match_flag_expressions,
1604
+ flag_combination,
1605
+ )
1606
+
1607
+ against_clause = " ".join([against_clause, *flag_expressions])
1608
+
1609
+ return "MATCH (%s) AGAINST (%s)" % (match_clause, against_clause)
1610
+
1611
+ def get_from_hint_text(
1612
+ self, table: selectable.FromClause, text: Optional[str]
1613
+ ) -> Optional[str]:
1614
+ return text
1615
+
1616
+ def visit_typeclause(
1617
+ self,
1618
+ typeclause: elements.TypeClause,
1619
+ type_: Optional[TypeEngine[Any]] = None,
1620
+ **kw: Any,
1621
+ ) -> Optional[str]:
1622
+ if type_ is None:
1623
+ type_ = typeclause.type.dialect_impl(self.dialect)
1624
+ if isinstance(type_, sqltypes.TypeDecorator):
1625
+ return self.visit_typeclause(typeclause, type_.impl, **kw) # type: ignore[arg-type] # noqa: E501
1626
+ elif isinstance(type_, sqltypes.Integer):
1627
+ if getattr(type_, "unsigned", False):
1628
+ return "UNSIGNED INTEGER"
1629
+ else:
1630
+ return "SIGNED INTEGER"
1631
+ elif isinstance(type_, sqltypes.TIMESTAMP):
1632
+ return "DATETIME"
1633
+ elif isinstance(
1634
+ type_,
1635
+ (
1636
+ sqltypes.DECIMAL,
1637
+ sqltypes.DateTime,
1638
+ sqltypes.Date,
1639
+ sqltypes.Time,
1640
+ ),
1641
+ ):
1642
+ return self.dialect.type_compiler_instance.process(type_)
1643
+ elif isinstance(type_, sqltypes.String) and not isinstance(
1644
+ type_, (ENUM, SET)
1645
+ ):
1646
+ adapted = CHAR._adapt_string_for_cast(type_)
1647
+ return self.dialect.type_compiler_instance.process(adapted)
1648
+ elif isinstance(type_, sqltypes._Binary):
1649
+ return "BINARY"
1650
+ elif isinstance(type_, sqltypes.JSON):
1651
+ return "JSON"
1652
+ elif isinstance(type_, sqltypes.NUMERIC):
1653
+ return self.dialect.type_compiler_instance.process(type_).replace(
1654
+ "NUMERIC", "DECIMAL"
1655
+ )
1656
+ elif (
1657
+ isinstance(type_, sqltypes.Float)
1658
+ and self.dialect._support_float_cast
1659
+ ):
1660
+ return self.dialect.type_compiler_instance.process(type_)
1661
+ else:
1662
+ return None
1663
+
1664
+ def visit_cast(self, cast: elements.Cast[Any], **kw: Any) -> str:
1665
+ type_ = self.process(cast.typeclause)
1666
+ if type_ is None:
1667
+ util.warn(
1668
+ "Datatype %s does not support CAST on MySQL/MariaDb; "
1669
+ "the CAST will be skipped."
1670
+ % self.dialect.type_compiler_instance.process(
1671
+ cast.typeclause.type
1672
+ )
1673
+ )
1674
+ return self.process(cast.clause.self_group(), **kw)
1675
+
1676
+ return "CAST(%s AS %s)" % (self.process(cast.clause, **kw), type_)
1677
+
1678
+ def render_literal_value(
1679
+ self, value: Optional[str], type_: TypeEngine[Any]
1680
+ ) -> str:
1681
+ value = super().render_literal_value(value, type_)
1682
+ if self.dialect._backslash_escapes:
1683
+ value = value.replace("\\", "\\\\")
1684
+ return value
1685
+
1686
+ # override native_boolean=False behavior here, as
1687
+ # MySQL still supports native boolean
1688
+ def visit_true(self, expr: elements.True_, **kw: Any) -> str:
1689
+ return "true"
1690
+
1691
+ def visit_false(self, expr: elements.False_, **kw: Any) -> str:
1692
+ return "false"
1693
+
1694
+ def get_select_precolumns(
1695
+ self, select: selectable.Select[Any], **kw: Any
1696
+ ) -> str:
1697
+ """Add special MySQL keywords in place of DISTINCT.
1698
+
1699
+ .. deprecated:: 1.4 This usage is deprecated.
1700
+ :meth:`_expression.Select.prefix_with` should be used for special
1701
+ keywords at the start of a SELECT.
1702
+
1703
+ """
1704
+ if isinstance(select._distinct, str):
1705
+ util.warn_deprecated(
1706
+ "Sending string values for 'distinct' is deprecated in the "
1707
+ "MySQL dialect and will be removed in a future release. "
1708
+ "Please use :meth:`.Select.prefix_with` for special keywords "
1709
+ "at the start of a SELECT statement",
1710
+ version="1.4",
1711
+ )
1712
+ return select._distinct.upper() + " "
1713
+
1714
+ return super().get_select_precolumns(select, **kw)
1715
+
1716
+ def visit_join(
1717
+ self,
1718
+ join: selectable.Join,
1719
+ asfrom: bool = False,
1720
+ from_linter: Optional[compiler.FromLinter] = None,
1721
+ **kwargs: Any,
1722
+ ) -> str:
1723
+ if from_linter:
1724
+ from_linter.edges.add((join.left, join.right))
1725
+
1726
+ if join.full:
1727
+ join_type = " FULL OUTER JOIN "
1728
+ elif join.isouter:
1729
+ join_type = " LEFT OUTER JOIN "
1730
+ else:
1731
+ join_type = " INNER JOIN "
1732
+
1733
+ return "".join(
1734
+ (
1735
+ self.process(
1736
+ join.left, asfrom=True, from_linter=from_linter, **kwargs
1737
+ ),
1738
+ join_type,
1739
+ self.process(
1740
+ join.right, asfrom=True, from_linter=from_linter, **kwargs
1741
+ ),
1742
+ " ON ",
1743
+ self.process(join.onclause, from_linter=from_linter, **kwargs), # type: ignore[arg-type] # noqa: E501
1744
+ )
1745
+ )
1746
+
1747
+ def for_update_clause(
1748
+ self, select: selectable.GenerativeSelect, **kw: Any
1749
+ ) -> str:
1750
+ assert select._for_update_arg is not None
1751
+ if select._for_update_arg.read:
1752
+ if self.dialect.use_mysql_for_share:
1753
+ tmp = " FOR SHARE"
1754
+ else:
1755
+ tmp = " LOCK IN SHARE MODE"
1756
+ else:
1757
+ tmp = " FOR UPDATE"
1758
+
1759
+ if select._for_update_arg.of and self.dialect.supports_for_update_of:
1760
+ tables: util.OrderedSet[elements.ClauseElement] = util.OrderedSet()
1761
+ for c in select._for_update_arg.of:
1762
+ tables.update(sql_util.surface_selectables_only(c))
1763
+
1764
+ tmp += " OF " + ", ".join(
1765
+ self.process(table, ashint=True, use_schema=False, **kw)
1766
+ for table in tables
1767
+ )
1768
+
1769
+ if select._for_update_arg.nowait:
1770
+ tmp += " NOWAIT"
1771
+
1772
+ if select._for_update_arg.skip_locked:
1773
+ tmp += " SKIP LOCKED"
1774
+
1775
+ return tmp
1776
+
1777
+ def limit_clause(
1778
+ self, select: selectable.GenerativeSelect, **kw: Any
1779
+ ) -> str:
1780
+ # MySQL supports:
1781
+ # LIMIT <limit>
1782
+ # LIMIT <offset>, <limit>
1783
+ # and in server versions > 3.3:
1784
+ # LIMIT <limit> OFFSET <offset>
1785
+ # The latter is more readable for offsets but we're stuck with the
1786
+ # former until we can refine dialects by server revision.
1787
+
1788
+ limit_clause, offset_clause = (
1789
+ select._limit_clause,
1790
+ select._offset_clause,
1791
+ )
1792
+
1793
+ if limit_clause is None and offset_clause is None:
1794
+ return ""
1795
+ elif offset_clause is not None:
1796
+ # As suggested by the MySQL docs, need to apply an
1797
+ # artificial limit if one wasn't provided
1798
+ # https://dev.mysql.com/doc/refman/5.0/en/select.html
1799
+ if limit_clause is None:
1800
+ # TODO: remove ??
1801
+ # hardwire the upper limit. Currently
1802
+ # needed consistent with the usage of the upper
1803
+ # bound as part of MySQL's "syntax" for OFFSET with
1804
+ # no LIMIT.
1805
+ return " \n LIMIT %s, %s" % (
1806
+ self.process(offset_clause, **kw),
1807
+ "18446744073709551615",
1808
+ )
1809
+ else:
1810
+ return " \n LIMIT %s, %s" % (
1811
+ self.process(offset_clause, **kw),
1812
+ self.process(limit_clause, **kw),
1813
+ )
1814
+ else:
1815
+ assert limit_clause is not None
1816
+ # No offset provided, so just use the limit
1817
+ return " \n LIMIT %s" % (self.process(limit_clause, **kw),)
1818
+
1819
+ def update_post_criteria_clause(
1820
+ self, update_stmt: Update, **kw: Any
1821
+ ) -> Optional[str]:
1822
+ limit = update_stmt.kwargs.get("%s_limit" % self.dialect.name, None)
1823
+ supertext = super().update_post_criteria_clause(update_stmt, **kw)
1824
+
1825
+ if limit is not None:
1826
+ limit_text = f"LIMIT {int(limit)}"
1827
+ if supertext is not None:
1828
+ return f"{limit_text} {supertext}"
1829
+ else:
1830
+ return limit_text
1831
+ else:
1832
+ return supertext
1833
+
1834
+ def delete_post_criteria_clause(
1835
+ self, delete_stmt: Delete, **kw: Any
1836
+ ) -> Optional[str]:
1837
+ limit = delete_stmt.kwargs.get("%s_limit" % self.dialect.name, None)
1838
+ supertext = super().delete_post_criteria_clause(delete_stmt, **kw)
1839
+
1840
+ if limit is not None:
1841
+ limit_text = f"LIMIT {int(limit)}"
1842
+ if supertext is not None:
1843
+ return f"{limit_text} {supertext}"
1844
+ else:
1845
+ return limit_text
1846
+ else:
1847
+ return supertext
1848
+
1849
+ def visit_mysql_dml_limit_clause(
1850
+ self, element: DMLLimitClause, **kw: Any
1851
+ ) -> str:
1852
+ kw["literal_execute"] = True
1853
+ return f"LIMIT {self.process(element._limit_clause, **kw)}"
1854
+
1855
+ def update_tables_clause(
1856
+ self,
1857
+ update_stmt: Update,
1858
+ from_table: _DMLTableElement,
1859
+ extra_froms: list[selectable.FromClause],
1860
+ **kw: Any,
1861
+ ) -> str:
1862
+ kw["asfrom"] = True
1863
+ return ", ".join(
1864
+ t._compiler_dispatch(self, **kw)
1865
+ for t in [from_table] + list(extra_froms)
1866
+ )
1867
+
1868
+ def update_from_clause(
1869
+ self,
1870
+ update_stmt: Update,
1871
+ from_table: _DMLTableElement,
1872
+ extra_froms: list[selectable.FromClause],
1873
+ from_hints: Any,
1874
+ **kw: Any,
1875
+ ) -> None:
1876
+ return None
1877
+
1878
+ def delete_table_clause(
1879
+ self,
1880
+ delete_stmt: Delete,
1881
+ from_table: _DMLTableElement,
1882
+ extra_froms: list[selectable.FromClause],
1883
+ **kw: Any,
1884
+ ) -> str:
1885
+ """If we have extra froms make sure we render any alias as hint."""
1886
+ ashint = False
1887
+ if extra_froms:
1888
+ ashint = True
1889
+ return from_table._compiler_dispatch(
1890
+ self, asfrom=True, iscrud=True, ashint=ashint, **kw
1891
+ )
1892
+
1893
+ def delete_extra_from_clause(
1894
+ self,
1895
+ delete_stmt: Delete,
1896
+ from_table: _DMLTableElement,
1897
+ extra_froms: list[selectable.FromClause],
1898
+ from_hints: Any,
1899
+ **kw: Any,
1900
+ ) -> str:
1901
+ """Render the DELETE .. USING clause specific to MySQL."""
1902
+ kw["asfrom"] = True
1903
+ if any(
1904
+ from_table in elem._cloned_set
1905
+ for extra_from in extra_froms
1906
+ for elem in sql_util.surface_selectables_only(extra_from)
1907
+ ):
1908
+ froms = extra_froms
1909
+ else:
1910
+ froms = [from_table] + extra_froms
1911
+
1912
+ return "USING " + ", ".join(
1913
+ t._compiler_dispatch(self, fromhints=from_hints, **kw)
1914
+ for t in froms
1915
+ )
1916
+
1917
+ def visit_empty_set_expr(
1918
+ self, element_types: list[TypeEngine[Any]], **kw: Any
1919
+ ) -> str:
1920
+ return (
1921
+ "SELECT %(outer)s FROM (SELECT %(inner)s) as _empty_set WHERE 1!=1"
1922
+ % {
1923
+ "inner": ", ".join(
1924
+ "1 AS _in_%s" % idx
1925
+ for idx, type_ in enumerate(element_types)
1926
+ ),
1927
+ "outer": ", ".join(
1928
+ "_in_%s" % idx for idx, type_ in enumerate(element_types)
1929
+ ),
1930
+ }
1931
+ )
1932
+
1933
+ def visit_is_distinct_from_binary(
1934
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1935
+ ) -> str:
1936
+ return "NOT (%s <=> %s)" % (
1937
+ self.process(binary.left),
1938
+ self.process(binary.right),
1939
+ )
1940
+
1941
+ def visit_is_not_distinct_from_binary(
1942
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1943
+ ) -> str:
1944
+ return "%s <=> %s" % (
1945
+ self.process(binary.left),
1946
+ self.process(binary.right),
1947
+ )
1948
+
1949
+ def _mysql_regexp_match(
1950
+ self,
1951
+ op_string: str,
1952
+ binary: elements.BinaryExpression[Any],
1953
+ operator: Any,
1954
+ **kw: Any,
1955
+ ) -> str:
1956
+ flags = binary.modifiers["flags"]
1957
+
1958
+ text = "REGEXP_LIKE(%s, %s, %s)" % (
1959
+ self.process(binary.left, **kw),
1960
+ self.process(binary.right, **kw),
1961
+ self.render_literal_value(flags, sqltypes.STRINGTYPE),
1962
+ )
1963
+ if op_string == " NOT REGEXP ":
1964
+ return "NOT %s" % text
1965
+ else:
1966
+ return text
1967
+
1968
+ def _regexp_match(
1969
+ self,
1970
+ op_string: str,
1971
+ binary: elements.BinaryExpression[Any],
1972
+ operator: Any,
1973
+ **kw: Any,
1974
+ ) -> str:
1975
+ assert binary.modifiers is not None
1976
+ flags = binary.modifiers["flags"]
1977
+ if flags is None:
1978
+ return self._generate_generic_binary(binary, op_string, **kw)
1979
+ else:
1980
+ return self.dialect._dispatch_for_vendor(
1981
+ self._mysql_regexp_match,
1982
+ self._mariadb_regexp_match,
1983
+ op_string,
1984
+ binary,
1985
+ operator,
1986
+ **kw,
1987
+ )
1988
+
1989
+ def visit_regexp_match_op_binary(
1990
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1991
+ ) -> str:
1992
+ return self._regexp_match(" REGEXP ", binary, operator, **kw)
1993
+
1994
+ def visit_not_regexp_match_op_binary(
1995
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
1996
+ ) -> str:
1997
+ return self._regexp_match(" NOT REGEXP ", binary, operator, **kw)
1998
+
1999
+ def visit_regexp_replace_op_binary(
2000
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
2001
+ ) -> str:
2002
+ assert binary.modifiers is not None
2003
+ flags = binary.modifiers["flags"]
2004
+ if flags is None:
2005
+ return "REGEXP_REPLACE(%s, %s)" % (
2006
+ self.process(binary.left, **kw),
2007
+ self.process(binary.right, **kw),
2008
+ )
2009
+ else:
2010
+ return self.dialect._dispatch_for_vendor(
2011
+ self._mysql_regexp_replace_op_binary,
2012
+ self._mariadb_regexp_replace_op_binary,
2013
+ binary,
2014
+ operator,
2015
+ **kw,
2016
+ )
2017
+
2018
+ def _mysql_regexp_replace_op_binary(
2019
+ self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
2020
+ ) -> str:
2021
+ flags = binary.modifiers["flags"]
2022
+
2023
+ return "REGEXP_REPLACE(%s, %s, %s)" % (
2024
+ self.process(binary.left, **kw),
2025
+ self.process(binary.right, **kw),
2026
+ self.render_literal_value(flags, sqltypes.STRINGTYPE),
2027
+ )
2028
+
2029
+
2030
+ class MySQLDDLCompiler(
2031
+ _mariadb_shim.MariaDBDDLCompilerShim, compiler.DDLCompiler
2032
+ ):
2033
+ dialect: MySQLDialect
2034
+
2035
+ def get_column_specification(
2036
+ self, column: sa_schema.Column[Any], **kw: Any
2037
+ ) -> str:
2038
+ """Builds column DDL."""
2039
+
2040
+ return self.dialect._dispatch_for_vendor(
2041
+ self._mysql_get_column_specification,
2042
+ self._mariadb_get_column_specification,
2043
+ column,
2044
+ **kw,
2045
+ )
2046
+
2047
+ def _mysql_get_column_specification(
2048
+ self,
2049
+ column: sa_schema.Column[Any],
2050
+ *,
2051
+ _force_column_to_nullable: bool = False,
2052
+ **kw: Any,
2053
+ ) -> str:
2054
+
2055
+ colspec = [
2056
+ self.preparer.format_column(column),
2057
+ self.dialect.type_compiler_instance.process(
2058
+ column.type, type_expression=column
2059
+ ),
2060
+ ]
2061
+
2062
+ if column.computed is not None:
2063
+ colspec.append(self.process(column.computed))
2064
+
2065
+ is_timestamp = isinstance(
2066
+ column.type._unwrapped_dialect_impl(self.dialect),
2067
+ sqltypes.TIMESTAMP,
2068
+ )
2069
+
2070
+ if not column.nullable and not _force_column_to_nullable:
2071
+ colspec.append("NOT NULL")
2072
+
2073
+ # see: https://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql_timestamp_null # noqa
2074
+ elif column.nullable and is_timestamp:
2075
+ colspec.append("NULL")
2076
+
2077
+ comment = column.comment
2078
+ if comment is not None:
2079
+ literal = self.sql_compiler.render_literal_value(
2080
+ comment, sqltypes.String()
2081
+ )
2082
+ colspec.append("COMMENT " + literal)
2083
+
2084
+ if (
2085
+ column.table is not None
2086
+ and column is column.table._autoincrement_column
2087
+ and (
2088
+ column.server_default is None
2089
+ or isinstance(column.server_default, sa_schema.Identity)
2090
+ )
2091
+ and not (
2092
+ self.dialect.supports_sequences
2093
+ and isinstance(column.default, sa_schema.Sequence)
2094
+ and not column.default.optional
2095
+ )
2096
+ ):
2097
+ colspec.append("AUTO_INCREMENT")
2098
+ else:
2099
+ default = self.get_column_default_string(column)
2100
+
2101
+ if default is not None:
2102
+ if (
2103
+ self.dialect._support_default_function
2104
+ and not re.match(r"^\s*[\'\"\(]", default)
2105
+ and not re.search(r"ON +UPDATE", default, re.I)
2106
+ and not re.match(
2107
+ r"\bnow\(\d+\)|\bcurrent_timestamp\(\d+\)",
2108
+ default,
2109
+ re.I,
2110
+ )
2111
+ and re.match(r".*\W.*", default)
2112
+ ):
2113
+ colspec.append(f"DEFAULT ({default})")
2114
+ else:
2115
+ colspec.append("DEFAULT " + default)
2116
+ return " ".join(colspec)
2117
+
2118
+ def post_create_table(self, table: sa_schema.Table) -> str:
2119
+ """Build table-level CREATE options like ENGINE and COLLATE."""
2120
+
2121
+ table_opts = []
2122
+
2123
+ opts = {
2124
+ k[len(self.dialect.name) + 1 :].upper(): v
2125
+ for k, v in table.kwargs.items()
2126
+ if k.startswith("%s_" % self.dialect.name)
2127
+ }
2128
+
2129
+ if table.comment is not None:
2130
+ opts["COMMENT"] = table.comment
2131
+
2132
+ partition_options = [
2133
+ "PARTITION_BY",
2134
+ "PARTITIONS",
2135
+ "SUBPARTITIONS",
2136
+ "SUBPARTITION_BY",
2137
+ ]
2138
+
2139
+ nonpart_options = OrderedSet(opts).difference(partition_options)
2140
+ part_options = OrderedSet(opts).intersection(partition_options)
2141
+
2142
+ for opt in topological.sort(
2143
+ [
2144
+ ("DEFAULT_CHARSET", "COLLATE"),
2145
+ ("DEFAULT_CHARACTER_SET", "COLLATE"),
2146
+ ("CHARSET", "COLLATE"),
2147
+ ("CHARACTER_SET", "COLLATE"),
2148
+ ],
2149
+ nonpart_options,
2150
+ ):
2151
+ arg = opts[opt]
2152
+ if opt in _reflection._options_of_type_string:
2153
+ arg = self.sql_compiler.render_literal_value(
2154
+ arg, sqltypes.String()
2155
+ )
2156
+
2157
+ if opt in (
2158
+ "DATA_DIRECTORY",
2159
+ "INDEX_DIRECTORY",
2160
+ "DEFAULT_CHARACTER_SET",
2161
+ "CHARACTER_SET",
2162
+ "DEFAULT_CHARSET",
2163
+ "DEFAULT_COLLATE",
2164
+ ):
2165
+ opt = opt.replace("_", " ")
2166
+
2167
+ joiner = "="
2168
+ if opt in (
2169
+ "TABLESPACE",
2170
+ "DEFAULT CHARACTER SET",
2171
+ "CHARACTER SET",
2172
+ "COLLATE",
2173
+ ):
2174
+ joiner = " "
2175
+
2176
+ table_opts.append(joiner.join((opt, arg)))
2177
+
2178
+ for opt in topological.sort(
2179
+ [
2180
+ ("PARTITION_BY", "PARTITIONS"),
2181
+ ("PARTITION_BY", "SUBPARTITION_BY"),
2182
+ ("PARTITION_BY", "SUBPARTITIONS"),
2183
+ ("PARTITIONS", "SUBPARTITIONS"),
2184
+ ("PARTITIONS", "SUBPARTITION_BY"),
2185
+ ("SUBPARTITION_BY", "SUBPARTITIONS"),
2186
+ ],
2187
+ part_options,
2188
+ ):
2189
+ arg = opts[opt]
2190
+ if opt in _reflection._options_of_type_string:
2191
+ arg = self.sql_compiler.render_literal_value(
2192
+ arg, sqltypes.String()
2193
+ )
2194
+
2195
+ opt = opt.replace("_", " ")
2196
+ joiner = " "
2197
+
2198
+ table_opts.append(joiner.join((opt, arg)))
2199
+
2200
+ return " ".join(table_opts)
2201
+
2202
+ def visit_create_index(self, create: ddl.CreateIndex, **kw: Any) -> str: # type: ignore[override] # noqa: E501
2203
+ index = create.element
2204
+ self._verify_index_table(index)
2205
+ preparer = self.preparer
2206
+ table = preparer.format_table(index.table) # type: ignore[arg-type]
2207
+
2208
+ columns = [
2209
+ self.sql_compiler.process(
2210
+ (
2211
+ elements.Grouping(expr) # type: ignore[arg-type]
2212
+ if (
2213
+ isinstance(expr, elements.BinaryExpression)
2214
+ or (
2215
+ isinstance(expr, elements.UnaryExpression)
2216
+ and expr.modifier
2217
+ not in (operators.desc_op, operators.asc_op)
2218
+ )
2219
+ or isinstance(expr, functions.FunctionElement)
2220
+ )
2221
+ else expr
2222
+ ),
2223
+ include_table=False,
2224
+ literal_binds=True,
2225
+ )
2226
+ for expr in index.expressions
2227
+ ]
2228
+
2229
+ name = self._prepared_index_name(index)
2230
+
2231
+ text = "CREATE "
2232
+ if index.unique:
2233
+ text += "UNIQUE "
2234
+
2235
+ index_prefix = index.get_dialect_option(self.dialect, "prefix")
2236
+ if index_prefix:
2237
+ text += index_prefix + " "
2238
+
2239
+ text += "INDEX "
2240
+ if create.if_not_exists:
2241
+ text += "IF NOT EXISTS "
2242
+ text += "%s ON %s " % (name, table)
2243
+
2244
+ length = index.get_dialect_option(self.dialect, "length")
2245
+ if length is not None:
2246
+ if isinstance(length, dict):
2247
+ # length value can be a (column_name --> integer value)
2248
+ # mapping specifying the prefix length for each column of the
2249
+ # index
2250
+ columns_str = ", ".join(
2251
+ (
2252
+ "%s(%d)" % (expr, length[col.name]) # type: ignore[union-attr] # noqa: E501
2253
+ if col.name in length # type: ignore[union-attr]
2254
+ else (
2255
+ "%s(%d)" % (expr, length[expr])
2256
+ if expr in length
2257
+ else "%s" % expr
2258
+ )
2259
+ )
2260
+ for col, expr in zip(index.expressions, columns)
2261
+ )
2262
+ else:
2263
+ # or can be an integer value specifying the same
2264
+ # prefix length for all columns of the index
2265
+ columns_str = ", ".join(
2266
+ "%s(%d)" % (col, length) for col in columns
2267
+ )
2268
+ else:
2269
+ columns_str = ", ".join(columns)
2270
+ text += "(%s)" % columns_str
2271
+
2272
+ parser = index.get_dialect_option(
2273
+ self.dialect, "with_parser", deprecated_fallback="mysql"
2274
+ )
2275
+ if parser is not None:
2276
+ text += " WITH PARSER %s" % (parser,)
2277
+
2278
+ using = index.get_dialect_option(
2279
+ self.dialect, "using", deprecated_fallback="mysql"
2280
+ )
2281
+ if using is not None:
2282
+ text += " USING %s" % (preparer.quote(using))
2283
+
2284
+ return text
2285
+
2286
+ def visit_primary_key_constraint(
2287
+ self, constraint: sa_schema.PrimaryKeyConstraint, **kw: Any
2288
+ ) -> str:
2289
+ text = super().visit_primary_key_constraint(constraint)
2290
+ using = constraint.get_dialect_option(
2291
+ self.dialect, "using", deprecated_fallback="mysql"
2292
+ )
2293
+ if using:
2294
+ text += " USING %s" % (self.preparer.quote(using))
2295
+ return text
2296
+
2297
+ def visit_drop_index(self, drop: ddl.DropIndex, **kw: Any) -> str:
2298
+ index = drop.element
2299
+ text = "\nDROP INDEX "
2300
+ if drop.if_exists:
2301
+ text += "IF EXISTS "
2302
+
2303
+ return text + "%s ON %s" % (
2304
+ self._prepared_index_name(index, include_schema=False),
2305
+ self.preparer.format_table(index.table), # type: ignore[arg-type]
2306
+ )
2307
+
2308
+ def visit_drop_constraint(
2309
+ self, drop: ddl.DropConstraint, **kw: Any
2310
+ ) -> str:
2311
+ constraint = drop.element
2312
+ if isinstance(constraint, sa_schema.ForeignKeyConstraint):
2313
+ qual = "FOREIGN KEY "
2314
+ const = self.preparer.format_constraint(constraint)
2315
+ elif isinstance(constraint, sa_schema.PrimaryKeyConstraint):
2316
+ qual = "PRIMARY KEY "
2317
+ const = ""
2318
+ elif isinstance(constraint, sa_schema.UniqueConstraint):
2319
+ qual = "INDEX "
2320
+ const = self.preparer.format_constraint(constraint)
2321
+ elif isinstance(constraint, sa_schema.CheckConstraint):
2322
+ return self.dialect._dispatch_for_vendor(
2323
+ self._mysql_visit_drop_check_constraint,
2324
+ self._mariadb_visit_drop_check_constraint,
2325
+ drop,
2326
+ **kw,
2327
+ )
2328
+ else:
2329
+ qual = ""
2330
+ const = self.preparer.format_constraint(constraint)
2331
+ return "ALTER TABLE %s DROP %s%s" % (
2332
+ self.preparer.format_table(constraint.table),
2333
+ qual,
2334
+ const,
2335
+ )
2336
+
2337
+ def _mysql_visit_drop_check_constraint(
2338
+ self, drop: ddl.DropConstraint, **kw: Any
2339
+ ) -> str:
2340
+ constraint = drop.element
2341
+ qual = "CHECK "
2342
+ const = self.preparer.format_constraint(constraint)
2343
+ return "ALTER TABLE %s DROP %s%s" % (
2344
+ self.preparer.format_table(constraint.table),
2345
+ qual,
2346
+ const,
2347
+ )
2348
+
2349
+ def define_constraint_match(
2350
+ self, constraint: sa_schema.ForeignKeyConstraint
2351
+ ) -> str:
2352
+ if constraint.match is not None:
2353
+ raise exc.CompileError(
2354
+ "MySQL ignores the 'MATCH' keyword while at the same time "
2355
+ "causes ON UPDATE/ON DELETE clauses to be ignored."
2356
+ )
2357
+ return ""
2358
+
2359
+ def visit_set_table_comment(
2360
+ self, create: ddl.SetTableComment, **kw: Any
2361
+ ) -> str:
2362
+ return "ALTER TABLE %s COMMENT %s" % (
2363
+ self.preparer.format_table(create.element),
2364
+ self.sql_compiler.render_literal_value(
2365
+ create.element.comment, sqltypes.String()
2366
+ ),
2367
+ )
2368
+
2369
+ def visit_drop_table_comment(
2370
+ self, drop: ddl.DropTableComment, **kw: Any
2371
+ ) -> str:
2372
+ return "ALTER TABLE %s COMMENT ''" % (
2373
+ self.preparer.format_table(drop.element)
2374
+ )
2375
+
2376
+ def visit_set_column_comment(
2377
+ self, create: ddl.SetColumnComment, **kw: Any
2378
+ ) -> str:
2379
+ return "ALTER TABLE %s CHANGE %s %s" % (
2380
+ self.preparer.format_table(create.element.table),
2381
+ self.preparer.format_column(create.element),
2382
+ self.get_column_specification(create.element),
2383
+ )
2384
+
2385
+
2386
+ class MySQLTypeCompiler(
2387
+ _mariadb_shim.MariaDBTypeCompilerShim, compiler.GenericTypeCompiler
2388
+ ):
2389
+ def _extend_numeric(self, type_: _NumericCommonType, spec: str) -> str:
2390
+ "Extend a numeric-type declaration with MySQL specific extensions."
2391
+
2392
+ if not self._mysql_type(type_):
2393
+ return spec
2394
+
2395
+ if type_.unsigned:
2396
+ spec += " UNSIGNED"
2397
+ if type_.zerofill:
2398
+ spec += " ZEROFILL"
2399
+ return spec
2400
+
2401
+ def _extend_string(
2402
+ self, type_: _StringType, defaults: dict[str, Any], spec: str
2403
+ ) -> str:
2404
+ """Extend a string-type declaration with standard SQL CHARACTER SET /
2405
+ COLLATE annotations and MySQL specific extensions.
2406
+
2407
+ """
2408
+
2409
+ def attr(name: str) -> Any:
2410
+ return getattr(type_, name, defaults.get(name))
2411
+
2412
+ if attr("charset"):
2413
+ charset = "CHARACTER SET %s" % attr("charset")
2414
+ elif attr("ascii"):
2415
+ charset = "ASCII"
2416
+ elif attr("unicode"):
2417
+ charset = "UNICODE"
2418
+ else:
2419
+
2420
+ charset = None
2421
+
2422
+ if attr("collation"):
2423
+ collation = "COLLATE %s" % type_.collation
2424
+ elif attr("binary"):
2425
+ collation = "BINARY"
2426
+ else:
2427
+ collation = None
2428
+
2429
+ if attr("national"):
2430
+ # NATIONAL (aka NCHAR/NVARCHAR) trumps charsets.
2431
+ return " ".join(
2432
+ [c for c in ("NATIONAL", spec, collation) if c is not None]
2433
+ )
2434
+ return " ".join(
2435
+ [c for c in (spec, charset, collation) if c is not None]
2436
+ )
2437
+
2438
+ def _mysql_type(self, type_: Any) -> bool:
2439
+ return isinstance(type_, (_StringType, _NumericCommonType))
2440
+
2441
+ def visit_NUMERIC(self, type_: NUMERIC, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2442
+ if type_.precision is None:
2443
+ return self._extend_numeric(type_, "NUMERIC")
2444
+ elif type_.scale is None:
2445
+ return self._extend_numeric(
2446
+ type_,
2447
+ "NUMERIC(%(precision)s)" % {"precision": type_.precision},
2448
+ )
2449
+ else:
2450
+ return self._extend_numeric(
2451
+ type_,
2452
+ "NUMERIC(%(precision)s, %(scale)s)"
2453
+ % {"precision": type_.precision, "scale": type_.scale},
2454
+ )
2455
+
2456
+ def visit_DECIMAL(self, type_: DECIMAL, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2457
+ if type_.precision is None:
2458
+ return self._extend_numeric(type_, "DECIMAL")
2459
+ elif type_.scale is None:
2460
+ return self._extend_numeric(
2461
+ type_,
2462
+ "DECIMAL(%(precision)s)" % {"precision": type_.precision},
2463
+ )
2464
+ else:
2465
+ return self._extend_numeric(
2466
+ type_,
2467
+ "DECIMAL(%(precision)s, %(scale)s)"
2468
+ % {"precision": type_.precision, "scale": type_.scale},
2469
+ )
2470
+
2471
+ def visit_DOUBLE(self, type_: DOUBLE, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2472
+ if type_.precision is not None and type_.scale is not None:
2473
+ return self._extend_numeric(
2474
+ type_,
2475
+ "DOUBLE(%(precision)s, %(scale)s)"
2476
+ % {"precision": type_.precision, "scale": type_.scale},
2477
+ )
2478
+ else:
2479
+ return self._extend_numeric(type_, "DOUBLE")
2480
+
2481
+ def visit_REAL(self, type_: REAL, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2482
+ if type_.precision is not None and type_.scale is not None:
2483
+ return self._extend_numeric(
2484
+ type_,
2485
+ "REAL(%(precision)s, %(scale)s)"
2486
+ % {"precision": type_.precision, "scale": type_.scale},
2487
+ )
2488
+ else:
2489
+ return self._extend_numeric(type_, "REAL")
2490
+
2491
+ def visit_FLOAT(self, type_: FLOAT, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2492
+ if (
2493
+ self._mysql_type(type_)
2494
+ and type_.scale is not None
2495
+ and type_.precision is not None
2496
+ ):
2497
+ return self._extend_numeric(
2498
+ type_, "FLOAT(%s, %s)" % (type_.precision, type_.scale)
2499
+ )
2500
+ elif type_.precision is not None:
2501
+ return self._extend_numeric(
2502
+ type_, "FLOAT(%s)" % (type_.precision,)
2503
+ )
2504
+ else:
2505
+ return self._extend_numeric(type_, "FLOAT")
2506
+
2507
+ def visit_INTEGER(self, type_: INTEGER, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2508
+ if self._mysql_type(type_) and type_.display_width is not None:
2509
+ return self._extend_numeric(
2510
+ type_,
2511
+ "INTEGER(%(display_width)s)"
2512
+ % {"display_width": type_.display_width},
2513
+ )
2514
+ else:
2515
+ return self._extend_numeric(type_, "INTEGER")
2516
+
2517
+ def visit_BIGINT(self, type_: BIGINT, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2518
+ if self._mysql_type(type_) and type_.display_width is not None:
2519
+ return self._extend_numeric(
2520
+ type_,
2521
+ "BIGINT(%(display_width)s)"
2522
+ % {"display_width": type_.display_width},
2523
+ )
2524
+ else:
2525
+ return self._extend_numeric(type_, "BIGINT")
2526
+
2527
+ def visit_MEDIUMINT(self, type_: MEDIUMINT, **kw: Any) -> str:
2528
+ if self._mysql_type(type_) and type_.display_width is not None:
2529
+ return self._extend_numeric(
2530
+ type_,
2531
+ "MEDIUMINT(%(display_width)s)"
2532
+ % {"display_width": type_.display_width},
2533
+ )
2534
+ else:
2535
+ return self._extend_numeric(type_, "MEDIUMINT")
2536
+
2537
+ def visit_TINYINT(self, type_: TINYINT, **kw: Any) -> str:
2538
+ if self._mysql_type(type_) and type_.display_width is not None:
2539
+ return self._extend_numeric(
2540
+ type_, "TINYINT(%s)" % type_.display_width
2541
+ )
2542
+ else:
2543
+ return self._extend_numeric(type_, "TINYINT")
2544
+
2545
+ def visit_SMALLINT(self, type_: SMALLINT, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2546
+ if self._mysql_type(type_) and type_.display_width is not None:
2547
+ return self._extend_numeric(
2548
+ type_,
2549
+ "SMALLINT(%(display_width)s)"
2550
+ % {"display_width": type_.display_width},
2551
+ )
2552
+ else:
2553
+ return self._extend_numeric(type_, "SMALLINT")
2554
+
2555
+ def visit_BIT(self, type_: BIT, **kw: Any) -> str:
2556
+ if type_.length is not None:
2557
+ return "BIT(%s)" % type_.length
2558
+ else:
2559
+ return "BIT"
2560
+
2561
+ def visit_DATETIME(self, type_: DATETIME, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2562
+ if getattr(type_, "fsp", None):
2563
+ return "DATETIME(%d)" % type_.fsp # type: ignore[str-format]
2564
+ else:
2565
+ return "DATETIME"
2566
+
2567
+ def visit_DATE(self, type_: DATE, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2568
+ return "DATE"
2569
+
2570
+ def visit_TIME(self, type_: TIME, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2571
+ if getattr(type_, "fsp", None):
2572
+ return "TIME(%d)" % type_.fsp # type: ignore[str-format]
2573
+ else:
2574
+ return "TIME"
2575
+
2576
+ def visit_TIMESTAMP(self, type_: TIMESTAMP, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2577
+ if getattr(type_, "fsp", None):
2578
+ return "TIMESTAMP(%d)" % type_.fsp # type: ignore[str-format]
2579
+ else:
2580
+ return "TIMESTAMP"
2581
+
2582
+ def visit_YEAR(self, type_: YEAR, **kw: Any) -> str:
2583
+ if type_.display_width is None:
2584
+ return "YEAR"
2585
+ else:
2586
+ return "YEAR(%s)" % type_.display_width
2587
+
2588
+ def visit_TEXT(self, type_: TEXT, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2589
+ if type_.length is not None:
2590
+ return self._extend_string(type_, {}, "TEXT(%d)" % type_.length)
2591
+ else:
2592
+ return self._extend_string(type_, {}, "TEXT")
2593
+
2594
+ def visit_TINYTEXT(self, type_: TINYTEXT, **kw: Any) -> str:
2595
+ return self._extend_string(type_, {}, "TINYTEXT")
2596
+
2597
+ def visit_MEDIUMTEXT(self, type_: MEDIUMTEXT, **kw: Any) -> str:
2598
+ return self._extend_string(type_, {}, "MEDIUMTEXT")
2599
+
2600
+ def visit_LONGTEXT(self, type_: LONGTEXT, **kw: Any) -> str:
2601
+ return self._extend_string(type_, {}, "LONGTEXT")
2602
+
2603
+ def visit_VARCHAR(self, type_: VARCHAR, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2604
+ if type_.length is not None:
2605
+ return self._extend_string(type_, {}, "VARCHAR(%d)" % type_.length)
2606
+ else:
2607
+ raise exc.CompileError(
2608
+ "VARCHAR requires a length on dialect %s" % self.dialect.name
2609
+ )
2610
+
2611
+ def visit_CHAR(self, type_: CHAR, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2612
+ if type_.length is not None:
2613
+ return self._extend_string(
2614
+ type_, {}, "CHAR(%(length)s)" % {"length": type_.length}
2615
+ )
2616
+ else:
2617
+ return self._extend_string(type_, {}, "CHAR")
2618
+
2619
+ def visit_NVARCHAR(self, type_: NVARCHAR, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2620
+ # We'll actually generate the equiv. "NATIONAL VARCHAR" instead
2621
+ # of "NVARCHAR".
2622
+ if type_.length is not None:
2623
+ return self._extend_string(
2624
+ type_,
2625
+ {"national": True},
2626
+ "VARCHAR(%(length)s)" % {"length": type_.length},
2627
+ )
2628
+ else:
2629
+ raise exc.CompileError(
2630
+ "NVARCHAR requires a length on dialect %s" % self.dialect.name
2631
+ )
2632
+
2633
+ def visit_NCHAR(self, type_: NCHAR, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2634
+ # We'll actually generate the equiv.
2635
+ # "NATIONAL CHAR" instead of "NCHAR".
2636
+ if type_.length is not None:
2637
+ return self._extend_string(
2638
+ type_,
2639
+ {"national": True},
2640
+ "CHAR(%(length)s)" % {"length": type_.length},
2641
+ )
2642
+ else:
2643
+ return self._extend_string(type_, {"national": True}, "CHAR")
2644
+
2645
+ def visit_UUID(self, type_: UUID[Any], **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2646
+ return "UUID"
2647
+
2648
+ def visit_VARBINARY(self, type_: VARBINARY, **kw: Any) -> str:
2649
+ return "VARBINARY(%d)" % type_.length # type: ignore[str-format]
2650
+
2651
+ def visit_JSON(self, type_: JSON[Any], **kw: Any) -> str:
2652
+ return "JSON"
2653
+
2654
+ def visit_large_binary(self, type_: LargeBinary, **kw: Any) -> str:
2655
+ return self.visit_BLOB(type_)
2656
+
2657
+ def visit_enum(self, type_: ENUM, **kw: Any) -> str: # type: ignore[override] # NOQA: E501
2658
+ if not type_.native_enum:
2659
+ return super().visit_enum(type_)
2660
+ else:
2661
+ return self._visit_enumerated_values("ENUM", type_, type_.enums)
2662
+
2663
+ def visit_BLOB(self, type_: LargeBinary, **kw: Any) -> str:
2664
+ if type_.length is not None:
2665
+ return "BLOB(%d)" % type_.length
2666
+ else:
2667
+ return "BLOB"
2668
+
2669
+ def visit_TINYBLOB(self, type_: TINYBLOB, **kw: Any) -> str:
2670
+ return "TINYBLOB"
2671
+
2672
+ def visit_MEDIUMBLOB(self, type_: MEDIUMBLOB, **kw: Any) -> str:
2673
+ return "MEDIUMBLOB"
2674
+
2675
+ def visit_LONGBLOB(self, type_: LONGBLOB, **kw: Any) -> str:
2676
+ return "LONGBLOB"
2677
+
2678
+ def _visit_enumerated_values(
2679
+ self, name: str, type_: _StringType, enumerated_values: Sequence[str]
2680
+ ) -> str:
2681
+ quoted_enums = []
2682
+ for e in enumerated_values:
2683
+ if self.dialect.identifier_preparer._double_percents:
2684
+ e = e.replace("%", "%%")
2685
+ quoted_enums.append("'%s'" % e.replace("'", "''"))
2686
+ return self._extend_string(
2687
+ type_, {}, "%s(%s)" % (name, ",".join(quoted_enums))
2688
+ )
2689
+
2690
+ def visit_ENUM(self, type_: ENUM, **kw: Any) -> str:
2691
+ return self._visit_enumerated_values("ENUM", type_, type_.enums)
2692
+
2693
+ def visit_SET(self, type_: SET, **kw: Any) -> str:
2694
+ return self._visit_enumerated_values("SET", type_, type_.values)
2695
+
2696
+ def visit_BOOLEAN(self, type_: sqltypes.Boolean, **kw: Any) -> str:
2697
+ return "BOOL"
2698
+
2699
+
2700
+ class MySQLIdentifierPreparer(
2701
+ _mariadb_shim.MariaDBIdentifierPreparerShim, compiler.IdentifierPreparer
2702
+ ):
2703
+ reserved_words = RESERVED_WORDS_MYSQL
2704
+
2705
+ def __init__(
2706
+ self,
2707
+ dialect: default.DefaultDialect,
2708
+ server_ansiquotes: bool = False,
2709
+ **kw: Any,
2710
+ ):
2711
+ if not server_ansiquotes:
2712
+ quote = "`"
2713
+ else:
2714
+ quote = '"'
2715
+
2716
+ super().__init__(dialect, initial_quote=quote, escape_quote=quote)
2717
+
2718
+ def _quote_free_identifiers(self, *ids: Optional[str]) -> tuple[str, ...]:
2719
+ """Unilaterally identifier-quote any number of strings."""
2720
+
2721
+ return tuple([self.quote_identifier(i) for i in ids if i is not None])
2722
+
2723
+
2724
+ class MySQLDialect(_mariadb_shim.MariaDBShim, default.DefaultDialect):
2725
+ """Details of the MySQL dialect.
2726
+ Not used directly in application code.
2727
+ """
2728
+
2729
+ name = "mysql"
2730
+
2731
+ is_mariadb = False
2732
+
2733
+ supports_statement_cache = True
2734
+
2735
+ supports_alter = True
2736
+
2737
+ # MySQL has no true "boolean" type; we
2738
+ # allow for the "true" and "false" keywords, however
2739
+ supports_native_boolean = False
2740
+
2741
+ # support for BIT type; mysqlconnector coerces result values automatically,
2742
+ # all other MySQL DBAPIs require a conversion routine
2743
+ supports_native_bit = False
2744
+
2745
+ # identifiers are 64, however aliases can be 255...
2746
+ max_identifier_length = 255
2747
+ max_index_name_length = 64
2748
+ max_constraint_name_length = 64
2749
+
2750
+ div_is_floordiv = False
2751
+
2752
+ supports_native_enum = True
2753
+
2754
+ returns_native_bytes = True
2755
+
2756
+ # ... may be updated to True for MariaDB 10.3+ in initialize()
2757
+ supports_sequences = False
2758
+
2759
+ sequences_optional = False
2760
+
2761
+ # ... may be updated to True for MySQL 8+ in initialize()
2762
+ supports_for_update_of = False
2763
+
2764
+ # mysql 8.0.1 uses this syntax
2765
+ use_mysql_for_share = False
2766
+
2767
+ # Only available ... ... in MySQL 8+
2768
+ _requires_alias_for_on_duplicate_key = False
2769
+
2770
+ # MySQL doesn't support "DEFAULT VALUES" but *does* support
2771
+ # "VALUES (DEFAULT)"
2772
+ supports_default_values = False
2773
+ supports_default_metavalue = True
2774
+
2775
+ use_insertmanyvalues: bool = True
2776
+ insertmanyvalues_implicit_sentinel = (
2777
+ InsertmanyvaluesSentinelOpts.ANY_AUTOINCREMENT
2778
+ )
2779
+
2780
+ supports_sane_rowcount = True
2781
+ supports_sane_multi_rowcount = False
2782
+ supports_multivalues_insert = True
2783
+ insert_null_pk_still_autoincrements = True
2784
+
2785
+ supports_comments = True
2786
+ inline_comments = True
2787
+ default_paramstyle = "format"
2788
+ colspecs = colspecs
2789
+
2790
+ cte_follows_insert = True
2791
+
2792
+ statement_compiler = MySQLCompiler
2793
+ ddl_compiler = MySQLDDLCompiler
2794
+ type_compiler_cls = MySQLTypeCompiler
2795
+ ischema_names = ischema_names
2796
+ preparer: type[MySQLIdentifierPreparer] = MySQLIdentifierPreparer
2797
+
2798
+ # default SQL compilation settings -
2799
+ # these are modified upon initialize(),
2800
+ # i.e. first connect
2801
+ _backslash_escapes = True
2802
+ _server_ansiquotes = False
2803
+ _casing = 0
2804
+ _support_default_function = True
2805
+ _support_float_cast = False
2806
+
2807
+ server_version_info: tuple[int, ...]
2808
+ identifier_preparer: MySQLIdentifierPreparer
2809
+
2810
+ construct_arguments = [
2811
+ (sa_schema.Table, {"*": None}),
2812
+ (sql.Update, {"limit": None}),
2813
+ (sql.Delete, {"limit": None}),
2814
+ (sa_schema.PrimaryKeyConstraint, {"using": None}),
2815
+ (
2816
+ sa_schema.Index,
2817
+ {
2818
+ "using": None,
2819
+ "length": None,
2820
+ "prefix": None,
2821
+ "with_parser": None,
2822
+ },
2823
+ ),
2824
+ ]
2825
+
2826
+ def __init__(
2827
+ self,
2828
+ json_serializer: Callable[[_JSON_VALUE], str] | None = None,
2829
+ json_deserializer: Callable[[str], _JSON_VALUE] | None = None,
2830
+ is_mariadb: Optional[bool] = None,
2831
+ **kwargs: Any,
2832
+ ) -> None:
2833
+ kwargs.pop("use_ansiquotes", None) # legacy
2834
+ default.DefaultDialect.__init__(self, **kwargs)
2835
+ self._json_serializer = json_serializer
2836
+ self._json_deserializer = json_deserializer
2837
+ self._set_mariadb(is_mariadb, ())
2838
+
2839
+ def get_isolation_level_values(
2840
+ self, dbapi_conn: DBAPIConnection
2841
+ ) -> Sequence[IsolationLevel]:
2842
+ return (
2843
+ "SERIALIZABLE",
2844
+ "READ UNCOMMITTED",
2845
+ "READ COMMITTED",
2846
+ "REPEATABLE READ",
2847
+ )
2848
+
2849
+ def set_isolation_level(
2850
+ self, dbapi_connection: DBAPIConnection, level: IsolationLevel
2851
+ ) -> None:
2852
+ cursor = dbapi_connection.cursor()
2853
+ cursor.execute(f"SET SESSION TRANSACTION ISOLATION LEVEL {level}")
2854
+ cursor.execute("COMMIT")
2855
+ cursor.close()
2856
+
2857
+ def get_isolation_level(
2858
+ self, dbapi_connection: DBAPIConnection
2859
+ ) -> IsolationLevel:
2860
+ cursor = dbapi_connection.cursor()
2861
+ if self._is_mysql and self.server_version_info >= (5, 7, 20):
2862
+ cursor.execute("SELECT @@transaction_isolation")
2863
+ else:
2864
+ cursor.execute("SELECT @@tx_isolation")
2865
+ row = cursor.fetchone()
2866
+ if row is None:
2867
+ util.warn(
2868
+ "Could not retrieve transaction isolation level for MySQL "
2869
+ "connection."
2870
+ )
2871
+ raise NotImplementedError()
2872
+ val = row[0]
2873
+ cursor.close()
2874
+ if isinstance(val, bytes):
2875
+ val = val.decode()
2876
+ return val.upper().replace("-", " ") # type: ignore[no-any-return]
2877
+
2878
+ def _get_server_version_info(
2879
+ self, connection: Connection
2880
+ ) -> tuple[int, ...]:
2881
+ # get database server version info explicitly over the wire
2882
+ # to avoid proxy servers like MaxScale getting in the
2883
+ # way with their own values, see #4205
2884
+ dbapi_con = connection.connection
2885
+ cursor = dbapi_con.cursor()
2886
+ cursor.execute("SELECT VERSION()")
2887
+
2888
+ val = cursor.fetchone()[0] # type: ignore[index]
2889
+ cursor.close()
2890
+ if isinstance(val, bytes):
2891
+ val = val.decode()
2892
+
2893
+ return self._parse_server_version(val)
2894
+
2895
+ def _parse_server_version(self, val: str) -> tuple[int, ...]:
2896
+ version: list[int] = []
2897
+ is_mariadb = False
2898
+
2899
+ r = re.compile(r"[.\-+]")
2900
+ tokens = r.split(val)
2901
+
2902
+ _mariadb_normalized_version_info = None
2903
+ for token in tokens:
2904
+ parsed_token = re.match(
2905
+ r"^(?:(\d+)(?:a|b|c)?|(MariaDB\w*))$", token
2906
+ )
2907
+ if not parsed_token:
2908
+ continue
2909
+ elif parsed_token.group(2):
2910
+ _mariadb_normalized_version_info = tuple(version[-3:])
2911
+ is_mariadb = True
2912
+ else:
2913
+ digit = int(parsed_token.group(1))
2914
+ version.append(digit)
2915
+
2916
+ if _mariadb_normalized_version_info:
2917
+ server_version_info = _mariadb_normalized_version_info
2918
+ else:
2919
+ server_version_info = tuple(version)
2920
+
2921
+ self._set_mariadb(
2922
+ bool(server_version_info and is_mariadb), server_version_info
2923
+ )
2924
+
2925
+ if server_version_info < (5, 0, 2):
2926
+ raise NotImplementedError(
2927
+ "the MySQL/MariaDB dialect supports server "
2928
+ "version info 5.0.2 and above."
2929
+ )
2930
+
2931
+ # setting it here to help w the test suite
2932
+ self.server_version_info = server_version_info
2933
+ return server_version_info
2934
+
2935
+ def do_begin_twophase(self, connection: Connection, xid: Any) -> None:
2936
+ connection.execute(sql.text("XA BEGIN :xid"), dict(xid=xid))
2937
+
2938
+ def do_prepare_twophase(self, connection: Connection, xid: Any) -> None:
2939
+ connection.execute(sql.text("XA END :xid"), dict(xid=xid))
2940
+ connection.execute(sql.text("XA PREPARE :xid"), dict(xid=xid))
2941
+
2942
+ def do_rollback_twophase(
2943
+ self,
2944
+ connection: Connection,
2945
+ xid: Any,
2946
+ is_prepared: bool = True,
2947
+ recover: bool = False,
2948
+ ) -> None:
2949
+ if not is_prepared:
2950
+ connection.execute(sql.text("XA END :xid"), dict(xid=xid))
2951
+ connection.execute(sql.text("XA ROLLBACK :xid"), dict(xid=xid))
2952
+
2953
+ def do_commit_twophase(
2954
+ self,
2955
+ connection: Connection,
2956
+ xid: Any,
2957
+ is_prepared: bool = True,
2958
+ recover: bool = False,
2959
+ ) -> None:
2960
+ if not is_prepared:
2961
+ self.do_prepare_twophase(connection, xid)
2962
+ connection.execute(sql.text("XA COMMIT :xid"), dict(xid=xid))
2963
+
2964
+ def do_recover_twophase(self, connection: Connection) -> list[Any]:
2965
+ resultset = connection.exec_driver_sql("XA RECOVER")
2966
+ return [
2967
+ row["data"][0 : row["gtrid_length"]]
2968
+ for row in resultset.mappings()
2969
+ ]
2970
+
2971
+ def is_disconnect(
2972
+ self,
2973
+ e: DBAPIModule.Error,
2974
+ connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]],
2975
+ cursor: Optional[DBAPICursor],
2976
+ ) -> bool:
2977
+ if isinstance(
2978
+ e,
2979
+ (
2980
+ self.dbapi.OperationalError, # type: ignore[union-attr]
2981
+ self.dbapi.ProgrammingError, # type: ignore[union-attr]
2982
+ self.dbapi.InterfaceError, # type: ignore[union-attr]
2983
+ ),
2984
+ ) and self._extract_error_code(e) in (
2985
+ 1927,
2986
+ 2006,
2987
+ 2013,
2988
+ 2014,
2989
+ 2045,
2990
+ 2055,
2991
+ 4031,
2992
+ ):
2993
+ return True
2994
+ elif isinstance(
2995
+ e, (self.dbapi.InterfaceError, self.dbapi.InternalError) # type: ignore[union-attr] # noqa: E501
2996
+ ):
2997
+ # if underlying connection is closed,
2998
+ # this is the error you get
2999
+ return "(0, '')" in str(e)
3000
+ else:
3001
+ return False
3002
+
3003
+ def _compat_fetchall(
3004
+ self, rp: CursorResult[Unpack[TupleAny]], charset: Optional[str] = None
3005
+ ) -> Union[Sequence[Row[Unpack[TupleAny]]], Sequence[_DecodingRow]]:
3006
+ """Proxy result rows to smooth over MySQL-Python driver
3007
+ inconsistencies."""
3008
+
3009
+ return [_DecodingRow(row, charset) for row in rp.fetchall()]
3010
+
3011
+ def _compat_fetchone(
3012
+ self, rp: CursorResult[Unpack[TupleAny]], charset: Optional[str] = None
3013
+ ) -> Union[Row[Unpack[TupleAny]], None, _DecodingRow]:
3014
+ """Proxy a result row to smooth over MySQL-Python driver
3015
+ inconsistencies."""
3016
+
3017
+ row = rp.fetchone()
3018
+ if row:
3019
+ return _DecodingRow(row, charset)
3020
+ else:
3021
+ return None
3022
+
3023
+ def _compat_first(
3024
+ self, rp: CursorResult[Unpack[TupleAny]], charset: Optional[str] = None
3025
+ ) -> Optional[_DecodingRow]:
3026
+ """Proxy a result row to smooth over MySQL-Python driver
3027
+ inconsistencies."""
3028
+
3029
+ row = rp.first()
3030
+ if row:
3031
+ return _DecodingRow(row, charset)
3032
+ else:
3033
+ return None
3034
+
3035
+ def _extract_error_code(
3036
+ self, exception: DBAPIModule.Error
3037
+ ) -> Optional[int]:
3038
+ raise NotImplementedError()
3039
+
3040
+ def _get_default_schema_name(self, connection: Connection) -> str:
3041
+ return connection.exec_driver_sql("SELECT DATABASE()").scalar() # type: ignore[return-value] # noqa: E501
3042
+
3043
+ @reflection.cache
3044
+ def has_table(
3045
+ self,
3046
+ connection: Connection,
3047
+ table_name: str,
3048
+ schema: Optional[str] = None,
3049
+ **kw: Any,
3050
+ ) -> bool:
3051
+ self._ensure_has_table_connection(connection)
3052
+
3053
+ if schema is None:
3054
+ schema = self.default_schema_name
3055
+
3056
+ assert schema is not None
3057
+
3058
+ full_name = ".".join(
3059
+ self.identifier_preparer._quote_free_identifiers(
3060
+ schema, table_name
3061
+ )
3062
+ )
3063
+
3064
+ # DESCRIBE *must* be used because there is no information schema
3065
+ # table that returns information on temp tables that is consistently
3066
+ # available on MariaDB / MySQL / engine-agnostic etc.
3067
+ # therefore we have no choice but to use DESCRIBE and an error catch
3068
+ # to detect "False". See issue #9058
3069
+
3070
+ try:
3071
+ with connection.exec_driver_sql(
3072
+ f"DESCRIBE {full_name}",
3073
+ execution_options={"skip_user_error_events": True},
3074
+ ) as rs:
3075
+ return rs.fetchone() is not None
3076
+ except exc.DBAPIError as e:
3077
+ # https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html # noqa: E501
3078
+ # there are a lot of codes that *may* pop up here at some point
3079
+ # but we continue to be fairly conservative. We include:
3080
+ # 1146: Table '%s.%s' doesn't exist - what every MySQL has emitted
3081
+ # for decades
3082
+ #
3083
+ # mysql 8 suddenly started emitting:
3084
+ # 1049: Unknown database '%s' - for nonexistent schema
3085
+ #
3086
+ # also added:
3087
+ # 1051: Unknown table '%s' - not known to emit
3088
+ #
3089
+ # there's more "doesn't exist" kinds of messages but they are
3090
+ # less clear if mysql 8 would suddenly start using one of those
3091
+ if self._extract_error_code(e.orig) in (1146, 1049, 1051): # type: ignore[arg-type, operator] # noqa: E501
3092
+ return False
3093
+ raise
3094
+
3095
+ @reflection.cache
3096
+ def has_sequence(
3097
+ self,
3098
+ connection: Connection,
3099
+ sequence_name: str,
3100
+ schema: Optional[str] = None,
3101
+ **kw: Any,
3102
+ ) -> bool:
3103
+ if not self.supports_sequences:
3104
+ self._sequences_not_supported()
3105
+ if not schema:
3106
+ schema = self.default_schema_name
3107
+ # MariaDB implements sequences as a special type of table
3108
+ #
3109
+ cursor = connection.execute(
3110
+ sql.text(
3111
+ "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
3112
+ "WHERE TABLE_TYPE='SEQUENCE' and TABLE_NAME=:name AND "
3113
+ "TABLE_SCHEMA=:schema_name"
3114
+ ),
3115
+ dict(
3116
+ name=str(sequence_name),
3117
+ schema_name=str(schema),
3118
+ ),
3119
+ )
3120
+ return cursor.first() is not None
3121
+
3122
+ def _sequences_not_supported(self) -> NoReturn:
3123
+ raise NotImplementedError(
3124
+ "Sequences are supported only by the "
3125
+ "MariaDB series 10.3 or greater"
3126
+ )
3127
+
3128
+ @reflection.cache
3129
+ def get_sequence_names(
3130
+ self, connection: Connection, schema: Optional[str] = None, **kw: Any
3131
+ ) -> list[str]:
3132
+ if not self.supports_sequences:
3133
+ self._sequences_not_supported()
3134
+ if not schema:
3135
+ schema = self.default_schema_name
3136
+ # MariaDB implements sequences as a special type of table
3137
+ cursor = connection.execute(
3138
+ sql.text(
3139
+ "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
3140
+ "WHERE TABLE_TYPE='SEQUENCE' and TABLE_SCHEMA=:schema_name"
3141
+ ),
3142
+ dict(schema_name=schema),
3143
+ )
3144
+ return [
3145
+ row[0]
3146
+ for row in self._compat_fetchall(
3147
+ cursor, charset=self._connection_charset
3148
+ )
3149
+ ]
3150
+
3151
+ def _dispatch_for_vendor(
3152
+ self,
3153
+ mysql_callable: Callable[..., _T],
3154
+ mariadb_callable: Callable[..., _T],
3155
+ *arg: Any,
3156
+ **kw: Any,
3157
+ ) -> _T:
3158
+ if not self.is_mariadb:
3159
+ return mysql_callable(*arg, **kw)
3160
+ else:
3161
+ return mariadb_callable(*arg, **kw)
3162
+
3163
+ def initialize(self, connection: Connection) -> None:
3164
+ # this is driver-based, does not need server version info
3165
+ # and is fairly critical for even basic SQL operations
3166
+ self._connection_charset: Optional[str] = self._detect_charset(
3167
+ connection
3168
+ )
3169
+
3170
+ # call super().initialize() because we need to have
3171
+ # server_version_info set up. in 1.4 under python 2 only this does the
3172
+ # "check unicode returns" thing, which is the one area that some
3173
+ # SQL gets compiled within initialize() currently
3174
+ default.DefaultDialect.initialize(self, connection)
3175
+
3176
+ self._detect_sql_mode(connection)
3177
+ self._detect_ansiquotes(connection) # depends on sql mode
3178
+ self._detect_casing(connection)
3179
+ if self._server_ansiquotes:
3180
+ # if ansiquotes == True, build a new IdentifierPreparer
3181
+ # with the new setting
3182
+ self.identifier_preparer = self.preparer(
3183
+ self, server_ansiquotes=self._server_ansiquotes
3184
+ )
3185
+
3186
+ self._dispatch_for_vendor(
3187
+ self._initialize_mysql, self._initialize_mariadb, connection
3188
+ )
3189
+
3190
+ def _initialize_mysql(self, connection: Connection) -> None:
3191
+ assert not self.is_mariadb
3192
+
3193
+ self.supports_for_update_of = self.server_version_info >= (8,)
3194
+
3195
+ self.use_mysql_for_share = self.server_version_info >= (8, 0, 1)
3196
+
3197
+ self._needs_correct_for_88718_96365 = self.server_version_info >= (
3198
+ 8,
3199
+ ) and (self.server_version_info < (8, 0, 14) or self._casing == 2)
3200
+
3201
+ self._requires_alias_for_on_duplicate_key = (
3202
+ self.server_version_info >= (8, 0, 20)
3203
+ )
3204
+
3205
+ # ref https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html # noqa
3206
+ self._support_default_function = self.server_version_info >= (8, 0, 13)
3207
+
3208
+ # ref https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-17.html#mysqld-8-0-17-feature # noqa
3209
+ self._support_float_cast = self.server_version_info >= (8, 0, 17)
3210
+
3211
+ @property
3212
+ def _is_mysql(self) -> bool:
3213
+ return not self.is_mariadb
3214
+
3215
+ @reflection.cache
3216
+ def get_schema_names(self, connection: Connection, **kw: Any) -> list[str]:
3217
+ rp = connection.exec_driver_sql("SHOW schemas")
3218
+ return [r[0] for r in rp]
3219
+
3220
+ @reflection.cache
3221
+ def get_table_names(
3222
+ self, connection: Connection, schema: Optional[str] = None, **kw: Any
3223
+ ) -> list[str]:
3224
+ """Return a Unicode SHOW TABLES from a given schema."""
3225
+ if schema is not None:
3226
+ current_schema: str = schema
3227
+ else:
3228
+ current_schema = self.default_schema_name # type: ignore[assignment] # noqa: E501
3229
+
3230
+ charset = self._connection_charset
3231
+
3232
+ rp = connection.exec_driver_sql(
3233
+ "SHOW FULL TABLES FROM %s"
3234
+ % self.identifier_preparer.quote_identifier(current_schema)
3235
+ )
3236
+
3237
+ return [
3238
+ row[0]
3239
+ for row in self._compat_fetchall(rp, charset=charset)
3240
+ if row[1] == "BASE TABLE"
3241
+ ]
3242
+
3243
+ @reflection.cache
3244
+ def get_view_names(
3245
+ self, connection: Connection, schema: Optional[str] = None, **kw: Any
3246
+ ) -> list[str]:
3247
+ if schema is None:
3248
+ schema = self.default_schema_name
3249
+ assert schema is not None
3250
+ charset = self._connection_charset
3251
+ rp = connection.exec_driver_sql(
3252
+ "SHOW FULL TABLES FROM %s"
3253
+ % self.identifier_preparer.quote_identifier(schema)
3254
+ )
3255
+ return [
3256
+ row[0]
3257
+ for row in self._compat_fetchall(rp, charset=charset)
3258
+ if row[1] in ("VIEW", "SYSTEM VIEW")
3259
+ ]
3260
+
3261
+ @reflection.cache
3262
+ def get_table_options(
3263
+ self,
3264
+ connection: Connection,
3265
+ table_name: str,
3266
+ schema: Optional[str] = None,
3267
+ **kw: Any,
3268
+ ) -> dict[str, Any]:
3269
+ parsed_state = self._parsed_state_or_create(
3270
+ connection, table_name, schema, **kw
3271
+ )
3272
+ if parsed_state.table_options:
3273
+ return parsed_state.table_options
3274
+ else:
3275
+ return ReflectionDefaults.table_options()
3276
+
3277
+ @reflection.cache
3278
+ def get_columns(
3279
+ self,
3280
+ connection: Connection,
3281
+ table_name: str,
3282
+ schema: Optional[str] = None,
3283
+ **kw: Any,
3284
+ ) -> list[ReflectedColumn]:
3285
+ parsed_state = self._parsed_state_or_create(
3286
+ connection, table_name, schema, **kw
3287
+ )
3288
+ if parsed_state.columns:
3289
+ return parsed_state.columns
3290
+ else:
3291
+ return ReflectionDefaults.columns()
3292
+
3293
+ @reflection.cache
3294
+ def get_pk_constraint(
3295
+ self,
3296
+ connection: Connection,
3297
+ table_name: str,
3298
+ schema: Optional[str] = None,
3299
+ **kw: Any,
3300
+ ) -> ReflectedPrimaryKeyConstraint:
3301
+ parsed_state = self._parsed_state_or_create(
3302
+ connection, table_name, schema, **kw
3303
+ )
3304
+ for key in parsed_state.keys:
3305
+ if key["type"] == "PRIMARY":
3306
+ # There can be only one.
3307
+ cols = [s[0] for s in key["columns"]]
3308
+ return {"constrained_columns": cols, "name": None}
3309
+ return ReflectionDefaults.pk_constraint()
3310
+
3311
+ @reflection.cache
3312
+ def get_foreign_keys(
3313
+ self,
3314
+ connection: Connection,
3315
+ table_name: str,
3316
+ schema: Optional[str] = None,
3317
+ **kw: Any,
3318
+ ) -> list[ReflectedForeignKeyConstraint]:
3319
+ parsed_state = self._parsed_state_or_create(
3320
+ connection, table_name, schema, **kw
3321
+ )
3322
+ default_schema = None
3323
+
3324
+ fkeys: list[ReflectedForeignKeyConstraint] = []
3325
+
3326
+ for spec in parsed_state.fk_constraints:
3327
+ ref_name = spec["table"][-1]
3328
+ ref_schema = len(spec["table"]) > 1 and spec["table"][-2] or schema
3329
+
3330
+ if not ref_schema:
3331
+ if default_schema is None:
3332
+ default_schema = connection.dialect.default_schema_name
3333
+ if schema == default_schema:
3334
+ ref_schema = schema
3335
+
3336
+ loc_names = spec["local"]
3337
+ ref_names = spec["foreign"]
3338
+
3339
+ con_kw = {}
3340
+ for opt in ("onupdate", "ondelete"):
3341
+ if spec.get(opt, False) not in ("NO ACTION", None):
3342
+ con_kw[opt] = spec[opt]
3343
+
3344
+ fkey_d: ReflectedForeignKeyConstraint = {
3345
+ "name": spec["name"],
3346
+ "constrained_columns": loc_names,
3347
+ "referred_schema": ref_schema,
3348
+ "referred_table": ref_name,
3349
+ "referred_columns": ref_names,
3350
+ "options": con_kw,
3351
+ }
3352
+ fkeys.append(fkey_d)
3353
+
3354
+ if self._is_mysql and self._needs_correct_for_88718_96365:
3355
+ self._correct_for_mysql_bugs_88718_96365(fkeys, connection)
3356
+
3357
+ return fkeys if fkeys else ReflectionDefaults.foreign_keys()
3358
+
3359
+ def _correct_for_mysql_bugs_88718_96365(
3360
+ self,
3361
+ fkeys: list[ReflectedForeignKeyConstraint],
3362
+ connection: Connection,
3363
+ ) -> None:
3364
+ # Foreign key is always in lower case (MySQL 8.0)
3365
+ # https://bugs.mysql.com/bug.php?id=88718
3366
+ # issue #4344 for SQLAlchemy
3367
+
3368
+ # table name also for MySQL 8.0
3369
+ # https://bugs.mysql.com/bug.php?id=96365
3370
+ # issue #4751 for SQLAlchemy
3371
+
3372
+ # for lower_case_table_names=2, information_schema.columns
3373
+ # preserves the original table/schema casing, but SHOW CREATE
3374
+ # TABLE does not. this problem is not in lower_case_table_names=1,
3375
+ # but use case-insensitive matching for these two modes in any case.
3376
+
3377
+ if self._casing in (1, 2):
3378
+
3379
+ def lower(s: str) -> str:
3380
+ return s.lower()
3381
+
3382
+ else:
3383
+ # if on case sensitive, there can be two tables referenced
3384
+ # with the same name different casing, so we need to use
3385
+ # case-sensitive matching.
3386
+ def lower(s: str) -> str:
3387
+ return s
3388
+
3389
+ default_schema_name: str = connection.dialect.default_schema_name # type: ignore[assignment] # noqa: E501
3390
+
3391
+ # NOTE: using (table_schema, table_name, lower(column_name)) in (...)
3392
+ # is very slow since mysql does not seem able to properly use indexse.
3393
+ # Unpack the where condition instead.
3394
+ schema_by_table_by_column: defaultdict[
3395
+ str, defaultdict[str, list[str]]
3396
+ ] = defaultdict(lambda: defaultdict(list))
3397
+ for rec in fkeys:
3398
+ sch = lower(rec["referred_schema"] or default_schema_name)
3399
+ tbl = lower(rec["referred_table"])
3400
+ for col_name in rec["referred_columns"]:
3401
+ schema_by_table_by_column[sch][tbl].append(col_name)
3402
+
3403
+ if schema_by_table_by_column:
3404
+
3405
+ condition = sql.or_(
3406
+ *(
3407
+ sql.and_(
3408
+ _info_columns.c.table_schema == schema,
3409
+ sql.or_(
3410
+ *(
3411
+ sql.and_(
3412
+ _info_columns.c.table_name == table,
3413
+ sql.func.lower(
3414
+ _info_columns.c.column_name
3415
+ ).in_(columns),
3416
+ )
3417
+ for table, columns in tables.items()
3418
+ )
3419
+ ),
3420
+ )
3421
+ for schema, tables in schema_by_table_by_column.items()
3422
+ )
3423
+ )
3424
+
3425
+ select = sql.select(
3426
+ _info_columns.c.table_schema,
3427
+ _info_columns.c.table_name,
3428
+ _info_columns.c.column_name,
3429
+ ).where(condition)
3430
+
3431
+ correct_for_wrong_fk_case: CursorResult[str, str, str] = (
3432
+ connection.execute(select)
3433
+ )
3434
+
3435
+ # in casing=0, table name and schema name come back in their
3436
+ # exact case.
3437
+ # in casing=1, table name and schema name come back in lower
3438
+ # case.
3439
+ # in casing=2, table name and schema name come back from the
3440
+ # information_schema.columns view in the case
3441
+ # that was used in CREATE DATABASE and CREATE TABLE, but
3442
+ # SHOW CREATE TABLE converts them to *lower case*, therefore
3443
+ # not matching. So for this case, case-insensitive lookup
3444
+ # is necessary
3445
+ d: defaultdict[tuple[str, str], dict[str, str]] = defaultdict(dict)
3446
+ for schema, tname, cname in correct_for_wrong_fk_case:
3447
+ d[(lower(schema), lower(tname))]["SCHEMANAME"] = schema
3448
+ d[(lower(schema), lower(tname))]["TABLENAME"] = tname
3449
+ d[(lower(schema), lower(tname))][cname.lower()] = cname
3450
+
3451
+ for fkey in fkeys:
3452
+ rec_b = d[
3453
+ (
3454
+ lower(fkey["referred_schema"] or default_schema_name),
3455
+ lower(fkey["referred_table"]),
3456
+ )
3457
+ ]
3458
+
3459
+ fkey["referred_table"] = rec_b["TABLENAME"]
3460
+ if fkey["referred_schema"] is not None:
3461
+ fkey["referred_schema"] = rec_b["SCHEMANAME"]
3462
+
3463
+ fkey["referred_columns"] = [
3464
+ rec_b[col.lower()] for col in fkey["referred_columns"]
3465
+ ]
3466
+
3467
+ @reflection.cache
3468
+ def get_check_constraints(
3469
+ self,
3470
+ connection: Connection,
3471
+ table_name: str,
3472
+ schema: Optional[str] = None,
3473
+ **kw: Any,
3474
+ ) -> list[ReflectedCheckConstraint]:
3475
+ parsed_state = self._parsed_state_or_create(
3476
+ connection, table_name, schema, **kw
3477
+ )
3478
+
3479
+ cks: list[ReflectedCheckConstraint] = [
3480
+ {"name": spec["name"], "sqltext": spec["sqltext"]}
3481
+ for spec in parsed_state.ck_constraints
3482
+ ]
3483
+ cks.sort(key=lambda d: d["name"] or "~") # sort None as last
3484
+ return cks if cks else ReflectionDefaults.check_constraints()
3485
+
3486
+ @reflection.cache
3487
+ def get_table_comment(
3488
+ self,
3489
+ connection: Connection,
3490
+ table_name: str,
3491
+ schema: Optional[str] = None,
3492
+ **kw: Any,
3493
+ ) -> ReflectedTableComment:
3494
+ parsed_state = self._parsed_state_or_create(
3495
+ connection, table_name, schema, **kw
3496
+ )
3497
+ comment = parsed_state.table_options.get(f"{self.name}_comment", None)
3498
+ if comment is not None:
3499
+ return {"text": comment}
3500
+ else:
3501
+ return ReflectionDefaults.table_comment()
3502
+
3503
+ @reflection.cache
3504
+ def get_indexes(
3505
+ self,
3506
+ connection: Connection,
3507
+ table_name: str,
3508
+ schema: Optional[str] = None,
3509
+ **kw: Any,
3510
+ ) -> list[ReflectedIndex]:
3511
+ parsed_state = self._parsed_state_or_create(
3512
+ connection, table_name, schema, **kw
3513
+ )
3514
+
3515
+ indexes: list[ReflectedIndex] = []
3516
+
3517
+ for spec in parsed_state.keys:
3518
+ dialect_options = {}
3519
+ unique = False
3520
+ flavor = spec["type"]
3521
+ if flavor == "PRIMARY":
3522
+ continue
3523
+ if flavor == "UNIQUE":
3524
+ unique = True
3525
+ elif flavor in ("FULLTEXT", "SPATIAL"):
3526
+ dialect_options[f"{self.name}_prefix"] = flavor
3527
+ elif flavor is not None:
3528
+ util.warn(
3529
+ f"Converting unknown KEY type {flavor} to a plain KEY"
3530
+ )
3531
+
3532
+ if spec["parser"]:
3533
+ dialect_options[f"{self.name}_with_parser"] = spec["parser"]
3534
+
3535
+ index_d: ReflectedIndex = {
3536
+ "name": spec["name"],
3537
+ "column_names": [s[0] for s in spec["columns"]],
3538
+ "unique": unique,
3539
+ }
3540
+
3541
+ mysql_length = {
3542
+ s[0]: s[1] for s in spec["columns"] if s[1] is not None
3543
+ }
3544
+ if mysql_length:
3545
+ dialect_options[f"{self.name}_length"] = mysql_length
3546
+
3547
+ if dialect_options:
3548
+ index_d["dialect_options"] = dialect_options
3549
+
3550
+ indexes.append(index_d)
3551
+ indexes.sort(key=lambda d: d["name"] or "~") # sort None as last
3552
+ return indexes if indexes else ReflectionDefaults.indexes()
3553
+
3554
+ @reflection.cache
3555
+ def get_unique_constraints(
3556
+ self,
3557
+ connection: Connection,
3558
+ table_name: str,
3559
+ schema: Optional[str] = None,
3560
+ **kw: Any,
3561
+ ) -> list[ReflectedUniqueConstraint]:
3562
+ parsed_state = self._parsed_state_or_create(
3563
+ connection, table_name, schema, **kw
3564
+ )
3565
+
3566
+ ucs: list[ReflectedUniqueConstraint] = [
3567
+ {
3568
+ "name": key["name"],
3569
+ "column_names": [col[0] for col in key["columns"]],
3570
+ "duplicates_index": key["name"],
3571
+ }
3572
+ for key in parsed_state.keys
3573
+ if key["type"] == "UNIQUE"
3574
+ ]
3575
+ ucs.sort(key=lambda d: d["name"] or "~") # sort None as last
3576
+ if ucs:
3577
+ return ucs
3578
+ else:
3579
+ return ReflectionDefaults.unique_constraints()
3580
+
3581
+ @reflection.cache
3582
+ def get_view_definition(
3583
+ self,
3584
+ connection: Connection,
3585
+ view_name: str,
3586
+ schema: Optional[str] = None,
3587
+ **kw: Any,
3588
+ ) -> str:
3589
+ charset = self._connection_charset
3590
+ full_name = ".".join(
3591
+ self.identifier_preparer._quote_free_identifiers(schema, view_name)
3592
+ )
3593
+ sql = self._show_create_table(
3594
+ connection, None, charset, full_name=full_name
3595
+ )
3596
+ if sql.upper().startswith("CREATE TABLE"):
3597
+ # it's a table, not a view
3598
+ raise exc.NoSuchTableError(full_name)
3599
+ return sql
3600
+
3601
+ def _parsed_state_or_create(
3602
+ self,
3603
+ connection: Connection,
3604
+ table_name: str,
3605
+ schema: Optional[str] = None,
3606
+ **kw: Any,
3607
+ ) -> _reflection.ReflectedState:
3608
+ return self._setup_parser(
3609
+ connection,
3610
+ table_name,
3611
+ schema,
3612
+ info_cache=kw.get("info_cache", None),
3613
+ )
3614
+
3615
+ @util.memoized_property
3616
+ def _tabledef_parser(self) -> _reflection.MySQLTableDefinitionParser:
3617
+ """return the MySQLTableDefinitionParser, generate if needed.
3618
+
3619
+ The deferred creation ensures that the dialect has
3620
+ retrieved server version information first.
3621
+
3622
+ """
3623
+ preparer = self.identifier_preparer
3624
+ return _reflection.MySQLTableDefinitionParser(self, preparer)
3625
+
3626
+ @reflection.cache
3627
+ def _setup_parser(
3628
+ self,
3629
+ connection: Connection,
3630
+ table_name: str,
3631
+ schema: Optional[str] = None,
3632
+ **kw: Any,
3633
+ ) -> _reflection.ReflectedState:
3634
+ charset = self._connection_charset
3635
+ parser = self._tabledef_parser
3636
+ full_name = ".".join(
3637
+ self.identifier_preparer._quote_free_identifiers(
3638
+ schema, table_name
3639
+ )
3640
+ )
3641
+ sql = self._show_create_table(
3642
+ connection, None, charset, full_name=full_name
3643
+ )
3644
+ if parser._check_view(sql):
3645
+ # Adapt views to something table-like.
3646
+ columns = self._describe_table(
3647
+ connection, None, charset, full_name=full_name
3648
+ )
3649
+ sql = parser._describe_to_create(
3650
+ table_name, columns # type: ignore[arg-type]
3651
+ )
3652
+ return parser.parse(sql, charset)
3653
+
3654
+ def _fetch_setting(
3655
+ self, connection: Connection, setting_name: str
3656
+ ) -> Optional[str]:
3657
+ charset = self._connection_charset
3658
+
3659
+ if self.server_version_info and self.server_version_info < (5, 6):
3660
+ sql = "SHOW VARIABLES LIKE '%s'" % setting_name
3661
+ fetch_col = 1
3662
+ else:
3663
+ sql = "SELECT @@%s" % setting_name
3664
+ fetch_col = 0
3665
+
3666
+ show_var = connection.exec_driver_sql(sql)
3667
+ row = self._compat_first(show_var, charset=charset)
3668
+ if not row:
3669
+ return None
3670
+ else:
3671
+ return cast(Optional[str], row[fetch_col])
3672
+
3673
+ def _detect_charset(self, connection: Connection) -> str:
3674
+ raise NotImplementedError()
3675
+
3676
+ def _detect_casing(self, connection: Connection) -> int:
3677
+ """Sniff out identifier case sensitivity.
3678
+
3679
+ Cached per-connection. This value can not change without a server
3680
+ restart.
3681
+
3682
+ """
3683
+ # https://dev.mysql.com/doc/refman/en/identifier-case-sensitivity.html
3684
+
3685
+ setting = self._fetch_setting(connection, "lower_case_table_names")
3686
+ if setting is None:
3687
+ cs = 0
3688
+ else:
3689
+ # 4.0.15 returns OFF or ON according to [ticket:489]
3690
+ # 3.23 doesn't, 4.0.27 doesn't..
3691
+ if setting == "OFF":
3692
+ cs = 0
3693
+ elif setting == "ON":
3694
+ cs = 1
3695
+ else:
3696
+ cs = int(setting)
3697
+ self._casing = cs
3698
+ return cs
3699
+
3700
+ def _detect_collations(self, connection: Connection) -> dict[str, str]:
3701
+ """Pull the active COLLATIONS list from the server.
3702
+
3703
+ Cached per-connection.
3704
+ """
3705
+
3706
+ collations = {}
3707
+ charset = self._connection_charset
3708
+ rs = connection.exec_driver_sql("SHOW COLLATION")
3709
+ for row in self._compat_fetchall(rs, charset):
3710
+ collations[row[0]] = row[1]
3711
+ return collations
3712
+
3713
+ def _detect_sql_mode(self, connection: Connection) -> None:
3714
+ setting = self._fetch_setting(connection, "sql_mode")
3715
+
3716
+ if setting is None:
3717
+ util.warn(
3718
+ "Could not retrieve SQL_MODE; please ensure the "
3719
+ "MySQL user has permissions to SHOW VARIABLES"
3720
+ )
3721
+ self._sql_mode = ""
3722
+ else:
3723
+ self._sql_mode = setting or ""
3724
+
3725
+ def _detect_ansiquotes(self, connection: Connection) -> None:
3726
+ """Detect and adjust for the ANSI_QUOTES sql mode."""
3727
+
3728
+ mode = self._sql_mode
3729
+ if not mode:
3730
+ mode = ""
3731
+ elif mode.isdigit():
3732
+ mode_no = int(mode)
3733
+ mode = (mode_no | 4 == mode_no) and "ANSI_QUOTES" or ""
3734
+
3735
+ self._server_ansiquotes = "ANSI_QUOTES" in mode
3736
+
3737
+ # as of MySQL 5.0.1
3738
+ self._backslash_escapes = "NO_BACKSLASH_ESCAPES" not in mode
3739
+
3740
+ @overload
3741
+ def _show_create_table(
3742
+ self,
3743
+ connection: Connection,
3744
+ table: Optional[Table],
3745
+ charset: Optional[str],
3746
+ full_name: str,
3747
+ ) -> str: ...
3748
+
3749
+ @overload
3750
+ def _show_create_table(
3751
+ self,
3752
+ connection: Connection,
3753
+ table: Table,
3754
+ charset: Optional[str] = None,
3755
+ full_name: None = None,
3756
+ ) -> str: ...
3757
+
3758
+ def _show_create_table(
3759
+ self,
3760
+ connection: Connection,
3761
+ table: Optional[Table],
3762
+ charset: Optional[str] = None,
3763
+ full_name: Optional[str] = None,
3764
+ ) -> str:
3765
+ """Run SHOW CREATE TABLE for a ``Table``."""
3766
+
3767
+ if full_name is None:
3768
+ assert table is not None
3769
+ full_name = self.identifier_preparer.format_table(table)
3770
+ st = "SHOW CREATE TABLE %s" % full_name
3771
+
3772
+ try:
3773
+ rp = connection.execution_options(
3774
+ skip_user_error_events=True
3775
+ ).exec_driver_sql(st)
3776
+ except exc.DBAPIError as e:
3777
+ if self._extract_error_code(e.orig) == 1146: # type: ignore[arg-type] # noqa: E501
3778
+ raise exc.NoSuchTableError(full_name) from e
3779
+ else:
3780
+ raise
3781
+ row = self._compat_first(rp, charset=charset)
3782
+ if not row:
3783
+ raise exc.NoSuchTableError(full_name)
3784
+ return cast(str, row[1]).strip()
3785
+
3786
+ @overload
3787
+ def _describe_table(
3788
+ self,
3789
+ connection: Connection,
3790
+ table: Optional[Table],
3791
+ charset: Optional[str],
3792
+ full_name: str,
3793
+ ) -> Union[Sequence[Row[Unpack[TupleAny]]], Sequence[_DecodingRow]]: ...
3794
+
3795
+ @overload
3796
+ def _describe_table(
3797
+ self,
3798
+ connection: Connection,
3799
+ table: Table,
3800
+ charset: Optional[str] = None,
3801
+ full_name: None = None,
3802
+ ) -> Union[Sequence[Row[Unpack[TupleAny]]], Sequence[_DecodingRow]]: ...
3803
+
3804
+ def _describe_table(
3805
+ self,
3806
+ connection: Connection,
3807
+ table: Optional[Table],
3808
+ charset: Optional[str] = None,
3809
+ full_name: Optional[str] = None,
3810
+ ) -> Union[Sequence[Row[Unpack[TupleAny]]], Sequence[_DecodingRow]]:
3811
+ """Run DESCRIBE for a ``Table`` and return processed rows."""
3812
+
3813
+ if full_name is None:
3814
+ assert table is not None
3815
+ full_name = self.identifier_preparer.format_table(table)
3816
+ st = "DESCRIBE %s" % full_name
3817
+
3818
+ rp, rows = None, None
3819
+ try:
3820
+ try:
3821
+ rp = connection.execution_options(
3822
+ skip_user_error_events=True
3823
+ ).exec_driver_sql(st)
3824
+ except exc.DBAPIError as e:
3825
+ code = self._extract_error_code(e.orig) # type: ignore[arg-type] # noqa: E501
3826
+ if code == 1146:
3827
+ raise exc.NoSuchTableError(full_name) from e
3828
+
3829
+ elif code == 1356:
3830
+ raise exc.UnreflectableTableError(
3831
+ "Table or view named %s could not be reflected: %s"
3832
+ % (full_name, e)
3833
+ ) from e
3834
+
3835
+ else:
3836
+ raise
3837
+ rows = self._compat_fetchall(rp, charset=charset)
3838
+ finally:
3839
+ if rp:
3840
+ rp.close()
3841
+ return rows
3842
+
3843
+
3844
+ class _DecodingRow:
3845
+ """Return unicode-decoded values based on type inspection.
3846
+
3847
+ Smooth over data type issues (esp. with alpha driver versions) and
3848
+ normalize strings as Unicode regardless of user-configured driver
3849
+ encoding settings.
3850
+
3851
+ """
3852
+
3853
+ # Some MySQL-python versions can return some columns as
3854
+ # sets.Set(['value']) (seriously) but thankfully that doesn't
3855
+ # seem to come up in DDL queries.
3856
+
3857
+ _encoding_compat: dict[str, str] = {
3858
+ "koi8r": "koi8_r",
3859
+ "koi8u": "koi8_u",
3860
+ "utf16": "utf-16-be", # MySQL's uft16 is always bigendian
3861
+ "utf8mb4": "utf8", # real utf8
3862
+ "utf8mb3": "utf8", # real utf8; saw this happen on CI but I cannot
3863
+ # reproduce, possibly mariadb10.6 related
3864
+ "eucjpms": "ujis",
3865
+ }
3866
+
3867
+ def __init__(self, rowproxy: Row[Unpack[_Ts]], charset: Optional[str]):
3868
+ self.rowproxy = rowproxy
3869
+ self.charset = (
3870
+ self._encoding_compat.get(charset, charset)
3871
+ if charset is not None
3872
+ else None
3873
+ )
3874
+
3875
+ def __getitem__(self, index: int) -> Any:
3876
+ item = self.rowproxy[index]
3877
+ if self.charset and isinstance(item, bytes):
3878
+ return item.decode(self.charset)
3879
+ else:
3880
+ return item
3881
+
3882
+ def __getattr__(self, attr: str) -> Any:
3883
+ item = getattr(self.rowproxy, attr)
3884
+ if self.charset and isinstance(item, bytes):
3885
+ return item.decode(self.charset)
3886
+ else:
3887
+ return item
3888
+
3889
+
3890
+ _info_columns = sql.table(
3891
+ "columns",
3892
+ sql.column("table_schema", VARCHAR(64)),
3893
+ sql.column("table_name", VARCHAR(64)),
3894
+ sql.column("column_name", VARCHAR(64)),
3895
+ schema="information_schema",
3896
+ )