SQLAlchemy 2.1.0b1__cp313-cp313-win_arm64.whl

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