SQLAlchemy 2.1.0b2__cp313-cp313t-win_arm64.whl

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