You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3527 lines
115KB

  1. # mysql/base.py
  2. # Copyright (C) 2005-2021 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: http://www.opensource.org/licenses/mit-license.php
  7. r"""
  8. .. dialect:: mysql
  9. :name: MySQL / MariaDB
  10. :full_support: 5.6, 5.7, 8.0 / 10.4, 10.5
  11. :normal_support: 5.6+ / 10+
  12. :best_effort: 5.0.2+ / 5.0.2+
  13. Supported Versions and Features
  14. -------------------------------
  15. SQLAlchemy supports MySQL starting with version 5.0.2 through modern releases,
  16. as well as all modern versions of MariaDB. See the official MySQL
  17. documentation for detailed information about features supported in any given
  18. server release.
  19. .. versionchanged:: 1.4 minimum MySQL version supported is now 5.0.2.
  20. MariaDB Support
  21. ~~~~~~~~~~~~~~~
  22. The MariaDB variant of MySQL retains fundamental compatibility with MySQL's
  23. protocols however the development of these two products continues to diverge.
  24. Within the realm of SQLAlchemy, the two databases have a small number of
  25. syntactical and behavioral differences that SQLAlchemy accommodates automatically.
  26. To connect to a MariaDB database, no changes to the database URL are required::
  27. engine = create_engine("mysql+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4")
  28. Upon first connect, the SQLAlchemy dialect employs a
  29. server version detection scheme that determines if the
  30. backing database reports as MariaDB. Based on this flag, the dialect
  31. can make different choices in those of areas where its behavior
  32. must be different.
  33. .. _mysql_mariadb_only_mode:
  34. MariaDB-Only Mode
  35. ~~~~~~~~~~~~~~~~~
  36. The dialect also supports an **optional** "MariaDB-only" mode of connection, which may be
  37. useful for the case where an application makes use of MariaDB-specific features
  38. and is not compatible with a MySQL database. To use this mode of operation,
  39. replace the "mysql" token in the above URL with "mariadb"::
  40. engine = create_engine("mariadb+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4")
  41. The above engine, upon first connect, will raise an error if the server version
  42. detection detects that the backing database is not MariaDB.
  43. When using an engine with ``"mariadb"`` as the dialect name, **all mysql-specific options
  44. that include the name "mysql" in them are now named with "mariadb"**. This means
  45. options like ``mysql_engine`` should be named ``mariadb_engine``, etc. Both
  46. "mysql" and "mariadb" options can be used simultaneously for applications that
  47. use URLs with both "mysql" and "mariadb" dialects::
  48. my_table = Table(
  49. "mytable",
  50. metadata,
  51. Column("id", Integer, primary_key=True),
  52. Column("textdata", String(50)),
  53. mariadb_engine="InnoDB",
  54. mysql_engine="InnoDB",
  55. )
  56. Index(
  57. "textdata_ix",
  58. my_table.c.textdata,
  59. mysql_prefix="FULLTEXT",
  60. mariadb_prefix="FULLTEXT",
  61. )
  62. Similar behavior will occur when the above structures are reflected, i.e. the
  63. "mariadb" prefix will be present in the option names when the database URL
  64. is based on the "mariadb" name.
  65. .. versionadded:: 1.4 Added "mariadb" dialect name supporting "MariaDB-only mode"
  66. for the MySQL dialect.
  67. .. _mysql_connection_timeouts:
  68. Connection Timeouts and Disconnects
  69. -----------------------------------
  70. MySQL / MariaDB feature an automatic connection close behavior, for connections that
  71. have been idle for a fixed period of time, defaulting to eight hours.
  72. To circumvent having this issue, use
  73. the :paramref:`_sa.create_engine.pool_recycle` option which ensures that
  74. a connection will be discarded and replaced with a new one if it has been
  75. present in the pool for a fixed number of seconds::
  76. engine = create_engine('mysql+mysqldb://...', pool_recycle=3600)
  77. For more comprehensive disconnect detection of pooled connections, including
  78. accommodation of server restarts and network issues, a pre-ping approach may
  79. be employed. See :ref:`pool_disconnects` for current approaches.
  80. .. seealso::
  81. :ref:`pool_disconnects` - Background on several techniques for dealing
  82. with timed out connections as well as database restarts.
  83. .. _mysql_storage_engines:
  84. CREATE TABLE arguments including Storage Engines
  85. ------------------------------------------------
  86. Both MySQL's and MariaDB's CREATE TABLE syntax includes a wide array of special options,
  87. including ``ENGINE``, ``CHARSET``, ``MAX_ROWS``, ``ROW_FORMAT``,
  88. ``INSERT_METHOD``, and many more.
  89. To accommodate the rendering of these arguments, specify the form
  90. ``mysql_argument_name="value"``. For example, to specify a table with
  91. ``ENGINE`` of ``InnoDB``, ``CHARSET`` of ``utf8mb4``, and ``KEY_BLOCK_SIZE``
  92. of ``1024``::
  93. Table('mytable', metadata,
  94. Column('data', String(32)),
  95. mysql_engine='InnoDB',
  96. mysql_charset='utf8mb4',
  97. mysql_key_block_size="1024"
  98. )
  99. When supporting :ref:`mysql_mariadb_only_mode` mode, similar keys against
  100. the "mariadb" prefix must be included as well. The values can of course
  101. vary independently so that different settings on MySQL vs. MariaDB may
  102. be maintained::
  103. # support both "mysql" and "mariadb-only" engine URLs
  104. Table('mytable', metadata,
  105. Column('data', String(32)),
  106. mysql_engine='InnoDB',
  107. mariadb_engine='InnoDB',
  108. mysql_charset='utf8mb4',
  109. mariadb_charset='utf8',
  110. mysql_key_block_size="1024"
  111. mariadb_key_block_size="1024"
  112. )
  113. The MySQL / MariaDB dialects will normally transfer any keyword specified as
  114. ``mysql_keyword_name`` to be rendered as ``KEYWORD_NAME`` in the
  115. ``CREATE TABLE`` statement. A handful of these names will render with a space
  116. instead of an underscore; to support this, the MySQL dialect has awareness of
  117. these particular names, which include ``DATA DIRECTORY``
  118. (e.g. ``mysql_data_directory``), ``CHARACTER SET`` (e.g.
  119. ``mysql_character_set``) and ``INDEX DIRECTORY`` (e.g.
  120. ``mysql_index_directory``).
  121. The most common argument is ``mysql_engine``, which refers to the storage
  122. engine for the table. Historically, MySQL server installations would default
  123. to ``MyISAM`` for this value, although newer versions may be defaulting
  124. to ``InnoDB``. The ``InnoDB`` engine is typically preferred for its support
  125. of transactions and foreign keys.
  126. A :class:`_schema.Table`
  127. that is created in a MySQL / MariaDB database with a storage engine
  128. of ``MyISAM`` will be essentially non-transactional, meaning any
  129. INSERT/UPDATE/DELETE statement referring to this table will be invoked as
  130. autocommit. It also will have no support for foreign key constraints; while
  131. the ``CREATE TABLE`` statement accepts foreign key options, when using the
  132. ``MyISAM`` storage engine these arguments are discarded. Reflecting such a
  133. table will also produce no foreign key constraint information.
  134. For fully atomic transactions as well as support for foreign key
  135. constraints, all participating ``CREATE TABLE`` statements must specify a
  136. transactional engine, which in the vast majority of cases is ``InnoDB``.
  137. Case Sensitivity and Table Reflection
  138. -------------------------------------
  139. Both MySQL and MariaDB have inconsistent support for case-sensitive identifier
  140. names, basing support on specific details of the underlying
  141. operating system. However, it has been observed that no matter
  142. what case sensitivity behavior is present, the names of tables in
  143. foreign key declarations are *always* received from the database
  144. as all-lower case, making it impossible to accurately reflect a
  145. schema where inter-related tables use mixed-case identifier names.
  146. Therefore it is strongly advised that table names be declared as
  147. all lower case both within SQLAlchemy as well as on the MySQL / MariaDB
  148. database itself, especially if database reflection features are
  149. to be used.
  150. .. _mysql_isolation_level:
  151. Transaction Isolation Level
  152. ---------------------------
  153. All MySQL / MariaDB dialects support setting of transaction isolation level both via a
  154. dialect-specific parameter :paramref:`_sa.create_engine.isolation_level`
  155. accepted
  156. by :func:`_sa.create_engine`, as well as the
  157. :paramref:`.Connection.execution_options.isolation_level` argument as passed to
  158. :meth:`_engine.Connection.execution_options`.
  159. This feature works by issuing the
  160. command ``SET SESSION TRANSACTION ISOLATION LEVEL <level>`` for each new
  161. connection. For the special AUTOCOMMIT isolation level, DBAPI-specific
  162. techniques are used.
  163. To set isolation level using :func:`_sa.create_engine`::
  164. engine = create_engine(
  165. "mysql://scott:tiger@localhost/test",
  166. isolation_level="READ UNCOMMITTED"
  167. )
  168. To set using per-connection execution options::
  169. connection = engine.connect()
  170. connection = connection.execution_options(
  171. isolation_level="READ COMMITTED"
  172. )
  173. Valid values for ``isolation_level`` include:
  174. * ``READ COMMITTED``
  175. * ``READ UNCOMMITTED``
  176. * ``REPEATABLE READ``
  177. * ``SERIALIZABLE``
  178. * ``AUTOCOMMIT``
  179. The special ``AUTOCOMMIT`` value makes use of the various "autocommit"
  180. attributes provided by specific DBAPIs, and is currently supported by
  181. MySQLdb, MySQL-Client, MySQL-Connector Python, and PyMySQL. Using it,
  182. the database connection will return true for the value of
  183. ``SELECT @@autocommit;``.
  184. .. seealso::
  185. :ref:`dbapi_autocommit`
  186. AUTO_INCREMENT Behavior
  187. -----------------------
  188. When creating tables, SQLAlchemy will automatically set ``AUTO_INCREMENT`` on
  189. the first :class:`.Integer` primary key column which is not marked as a
  190. foreign key::
  191. >>> t = Table('mytable', metadata,
  192. ... Column('mytable_id', Integer, primary_key=True)
  193. ... )
  194. >>> t.create()
  195. CREATE TABLE mytable (
  196. id INTEGER NOT NULL AUTO_INCREMENT,
  197. PRIMARY KEY (id)
  198. )
  199. You can disable this behavior by passing ``False`` to the
  200. :paramref:`_schema.Column.autoincrement` argument of :class:`_schema.Column`.
  201. This flag
  202. can also be used to enable auto-increment on a secondary column in a
  203. multi-column key for some storage engines::
  204. Table('mytable', metadata,
  205. Column('gid', Integer, primary_key=True, autoincrement=False),
  206. Column('id', Integer, primary_key=True)
  207. )
  208. .. _mysql_ss_cursors:
  209. Server Side Cursors
  210. -------------------
  211. Server-side cursor support is available for the mysqlclient, PyMySQL,
  212. mariadbconnector dialects and may also be available in others. This makes use
  213. of either the "buffered=True/False" flag if available or by using a class such
  214. as ``MySQLdb.cursors.SSCursor`` or ``pymysql.cursors.SSCursor`` internally.
  215. Server side cursors are enabled on a per-statement basis by using the
  216. :paramref:`.Connection.execution_options.stream_results` connection execution
  217. option::
  218. with engine.connect() as conn:
  219. result = conn.execution_options(stream_results=True).execute(text("select * from table"))
  220. Note that some kinds of SQL statements may not be supported with
  221. server side cursors; generally, only SQL statements that return rows should be
  222. used with this option.
  223. .. deprecated:: 1.4 The dialect-level server_side_cursors flag is deprecated
  224. and will be removed in a future release. Please use the
  225. :paramref:`_engine.Connection.stream_results` execution option for
  226. unbuffered cursor support.
  227. .. seealso::
  228. :ref:`engine_stream_results`
  229. .. _mysql_unicode:
  230. Unicode
  231. -------
  232. Charset Selection
  233. ~~~~~~~~~~~~~~~~~
  234. Most MySQL / MariaDB DBAPIs offer the option to set the client character set for
  235. a connection. This is typically delivered using the ``charset`` parameter
  236. in the URL, such as::
  237. e = create_engine(
  238. "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
  239. This charset is the **client character set** for the connection. Some
  240. MySQL DBAPIs will default this to a value such as ``latin1``, and some
  241. will make use of the ``default-character-set`` setting in the ``my.cnf``
  242. file as well. Documentation for the DBAPI in use should be consulted
  243. for specific behavior.
  244. The encoding used for Unicode has traditionally been ``'utf8'``. However, for
  245. MySQL versions 5.5.3 and MariaDB 5.5 on forward, a new MySQL-specific encoding
  246. ``'utf8mb4'`` has been introduced, and as of MySQL 8.0 a warning is emitted by
  247. the server if plain ``utf8`` is specified within any server-side directives,
  248. replaced with ``utf8mb3``. The rationale for this new encoding is due to the
  249. fact that MySQL's legacy utf-8 encoding only supports codepoints up to three
  250. bytes instead of four. Therefore, when communicating with a MySQL or MariaDB
  251. database that includes codepoints more than three bytes in size, this new
  252. charset is preferred, if supported by both the database as well as the client
  253. DBAPI, as in::
  254. e = create_engine(
  255. "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
  256. All modern DBAPIs should support the ``utf8mb4`` charset.
  257. In order to use ``utf8mb4`` encoding for a schema that was created with legacy
  258. ``utf8``, changes to the MySQL/MariaDB schema and/or server configuration may be
  259. required.
  260. .. seealso::
  261. `The utf8mb4 Character Set \
  262. <http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html>`_ - \
  263. in the MySQL documentation
  264. .. _mysql_binary_introducer:
  265. Dealing with Binary Data Warnings and Unicode
  266. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  267. MySQL versions 5.6, 5.7 and later (not MariaDB at the time of this writing) now
  268. emit a warning when attempting to pass binary data to the database, while a
  269. character set encoding is also in place, when the binary data itself is not
  270. valid for that encoding::
  271. default.py:509: Warning: (1300, "Invalid utf8mb4 character string:
  272. 'F9876A'")
  273. cursor.execute(statement, parameters)
  274. This warning is due to the fact that the MySQL client library is attempting to
  275. interpret the binary string as a unicode object even if a datatype such
  276. as :class:`.LargeBinary` is in use. To resolve this, the SQL statement requires
  277. a binary "character set introducer" be present before any non-NULL value
  278. that renders like this::
  279. INSERT INTO table (data) VALUES (_binary %s)
  280. These character set introducers are provided by the DBAPI driver, assuming the
  281. use of mysqlclient or PyMySQL (both of which are recommended). Add the query
  282. string parameter ``binary_prefix=true`` to the URL to repair this warning::
  283. # mysqlclient
  284. engine = create_engine(
  285. "mysql+mysqldb://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true")
  286. # PyMySQL
  287. engine = create_engine(
  288. "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true")
  289. The ``binary_prefix`` flag may or may not be supported by other MySQL drivers.
  290. SQLAlchemy itself cannot render this ``_binary`` prefix reliably, as it does
  291. not work with the NULL value, which is valid to be sent as a bound parameter.
  292. As the MySQL driver renders parameters directly into the SQL string, it's the
  293. most efficient place for this additional keyword to be passed.
  294. .. seealso::
  295. `Character set introducers <https://dev.mysql.com/doc/refman/5.7/en/charset-introducer.html>`_ - on the MySQL website
  296. ANSI Quoting Style
  297. ------------------
  298. MySQL / MariaDB feature two varieties of identifier "quoting style", one using
  299. backticks and the other using quotes, e.g. ```some_identifier``` vs.
  300. ``"some_identifier"``. All MySQL dialects detect which version
  301. is in use by checking the value of ``sql_mode`` when a connection is first
  302. established with a particular :class:`_engine.Engine`.
  303. This quoting style comes
  304. into play when rendering table and column names as well as when reflecting
  305. existing database structures. The detection is entirely automatic and
  306. no special configuration is needed to use either quoting style.
  307. MySQL / MariaDB SQL Extensions
  308. ------------------------------
  309. Many of the MySQL / MariaDB SQL extensions are handled through SQLAlchemy's generic
  310. function and operator support::
  311. table.select(table.c.password==func.md5('plaintext'))
  312. table.select(table.c.username.op('regexp')('^[a-d]'))
  313. And of course any valid SQL statement can be executed as a string as well.
  314. Some limited direct support for MySQL / MariaDB extensions to SQL is currently
  315. available.
  316. * INSERT..ON DUPLICATE KEY UPDATE: See
  317. :ref:`mysql_insert_on_duplicate_key_update`
  318. * SELECT pragma, use :meth:`_expression.Select.prefix_with` and
  319. :meth:`_query.Query.prefix_with`::
  320. select(...).prefix_with(['HIGH_PRIORITY', 'SQL_SMALL_RESULT'])
  321. * UPDATE with LIMIT::
  322. update(..., mysql_limit=10, mariadb_limit=10)
  323. * optimizer hints, use :meth:`_expression.Select.prefix_with` and
  324. :meth:`_query.Query.prefix_with`::
  325. select(...).prefix_with("/*+ NO_RANGE_OPTIMIZATION(t4 PRIMARY) */")
  326. * index hints, use :meth:`_expression.Select.with_hint` and
  327. :meth:`_query.Query.with_hint`::
  328. select(...).with_hint(some_table, "USE INDEX xyz")
  329. * MATCH operator support::
  330. from sqlalchemy.dialects.mysql import match
  331. select(...).where(match(col1, col2, against="some expr").in_boolean_mode())
  332. .. seealso::
  333. :class:`_mysql.match`
  334. .. _mysql_insert_on_duplicate_key_update:
  335. INSERT...ON DUPLICATE KEY UPDATE (Upsert)
  336. ------------------------------------------
  337. MySQL / MariaDB allow "upserts" (update or insert)
  338. of rows into a table via the ``ON DUPLICATE KEY UPDATE`` clause of the
  339. ``INSERT`` statement. A candidate row will only be inserted if that row does
  340. not match an existing primary or unique key in the table; otherwise, an UPDATE
  341. will be performed. The statement allows for separate specification of the
  342. values to INSERT versus the values for UPDATE.
  343. SQLAlchemy provides ``ON DUPLICATE KEY UPDATE`` support via the MySQL-specific
  344. :func:`.mysql.insert()` function, which provides
  345. the generative method :meth:`~.mysql.Insert.on_duplicate_key_update`:
  346. .. sourcecode:: pycon+sql
  347. >>> from sqlalchemy.dialects.mysql import insert
  348. >>> insert_stmt = insert(my_table).values(
  349. ... id='some_existing_id',
  350. ... data='inserted value')
  351. >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
  352. ... data=insert_stmt.inserted.data,
  353. ... status='U'
  354. ... )
  355. >>> print(on_duplicate_key_stmt)
  356. {opensql}INSERT INTO my_table (id, data) VALUES (%s, %s)
  357. ON DUPLICATE KEY UPDATE data = VALUES(data), status = %s
  358. Unlike PostgreSQL's "ON CONFLICT" phrase, the "ON DUPLICATE KEY UPDATE"
  359. phrase will always match on any primary key or unique key, and will always
  360. perform an UPDATE if there's a match; there are no options for it to raise
  361. an error or to skip performing an UPDATE.
  362. ``ON DUPLICATE KEY UPDATE`` is used to perform an update of the already
  363. existing row, using any combination of new values as well as values
  364. from the proposed insertion. These values are normally specified using
  365. keyword arguments passed to the
  366. :meth:`_mysql.Insert.on_duplicate_key_update`
  367. given column key values (usually the name of the column, unless it
  368. specifies :paramref:`_schema.Column.key`
  369. ) as keys and literal or SQL expressions
  370. as values:
  371. .. sourcecode:: pycon+sql
  372. >>> insert_stmt = insert(my_table).values(
  373. ... id='some_existing_id',
  374. ... data='inserted value')
  375. >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
  376. ... data="some data",
  377. ... updated_at=func.current_timestamp(),
  378. ... )
  379. >>> print(on_duplicate_key_stmt)
  380. {opensql}INSERT INTO my_table (id, data) VALUES (%s, %s)
  381. ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP
  382. In a manner similar to that of :meth:`.UpdateBase.values`, other parameter
  383. forms are accepted, including a single dictionary:
  384. .. sourcecode:: pycon+sql
  385. >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
  386. ... {"data": "some data", "updated_at": func.current_timestamp()},
  387. ... )
  388. as well as a list of 2-tuples, which will automatically provide
  389. a parameter-ordered UPDATE statement in a manner similar to that described
  390. at :ref:`updates_order_parameters`. Unlike the :class:`_expression.Update`
  391. object,
  392. no special flag is needed to specify the intent since the argument form is
  393. this context is unambiguous:
  394. .. sourcecode:: pycon+sql
  395. >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
  396. ... [
  397. ... ("data", "some data"),
  398. ... ("updated_at", func.current_timestamp()),
  399. ... ]
  400. ... )
  401. >>> print(on_duplicate_key_stmt)
  402. {opensql}INSERT INTO my_table (id, data) VALUES (%s, %s)
  403. ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP
  404. .. versionchanged:: 1.3 support for parameter-ordered UPDATE clause within
  405. MySQL ON DUPLICATE KEY UPDATE
  406. .. warning::
  407. The :meth:`_mysql.Insert.on_duplicate_key_update`
  408. method does **not** take into
  409. account Python-side default UPDATE values or generation functions, e.g.
  410. e.g. those specified using :paramref:`_schema.Column.onupdate`.
  411. These values will not be exercised for an ON DUPLICATE KEY style of UPDATE,
  412. unless they are manually specified explicitly in the parameters.
  413. In order to refer to the proposed insertion row, the special alias
  414. :attr:`_mysql.Insert.inserted` is available as an attribute on
  415. the :class:`_mysql.Insert` object; this object is a
  416. :class:`_expression.ColumnCollection` which contains all columns of the target
  417. table:
  418. .. sourcecode:: pycon+sql
  419. >>> stmt = insert(my_table).values(
  420. ... id='some_id',
  421. ... data='inserted value',
  422. ... author='jlh')
  423. >>> do_update_stmt = stmt.on_duplicate_key_update(
  424. ... data="updated value",
  425. ... author=stmt.inserted.author
  426. ... )
  427. >>> print(do_update_stmt)
  428. {opensql}INSERT INTO my_table (id, data, author) VALUES (%s, %s, %s)
  429. ON DUPLICATE KEY UPDATE data = %s, author = VALUES(author)
  430. When rendered, the "inserted" namespace will produce the expression
  431. ``VALUES(<columnname>)``.
  432. .. versionadded:: 1.2 Added support for MySQL ON DUPLICATE KEY UPDATE clause
  433. rowcount Support
  434. ----------------
  435. SQLAlchemy standardizes the DBAPI ``cursor.rowcount`` attribute to be the
  436. usual definition of "number of rows matched by an UPDATE or DELETE" statement.
  437. This is in contradiction to the default setting on most MySQL DBAPI drivers,
  438. which is "number of rows actually modified/deleted". For this reason, the
  439. SQLAlchemy MySQL dialects always add the ``constants.CLIENT.FOUND_ROWS``
  440. flag, or whatever is equivalent for the target dialect, upon connection.
  441. This setting is currently hardcoded.
  442. .. seealso::
  443. :attr:`_engine.CursorResult.rowcount`
  444. .. _mysql_indexes:
  445. MySQL / MariaDB- Specific Index Options
  446. -----------------------------------------
  447. MySQL and MariaDB-specific extensions to the :class:`.Index` construct are available.
  448. Index Length
  449. ~~~~~~~~~~~~~
  450. MySQL and MariaDB both provide an option to create index entries with a certain length, where
  451. "length" refers to the number of characters or bytes in each value which will
  452. become part of the index. SQLAlchemy provides this feature via the
  453. ``mysql_length`` and/or ``mariadb_length`` parameters::
  454. Index('my_index', my_table.c.data, mysql_length=10, mariadb_length=10)
  455. Index('a_b_idx', my_table.c.a, my_table.c.b, mysql_length={'a': 4,
  456. 'b': 9})
  457. Index('a_b_idx', my_table.c.a, my_table.c.b, mariadb_length={'a': 4,
  458. 'b': 9})
  459. Prefix lengths are given in characters for nonbinary string types and in bytes
  460. for binary string types. The value passed to the keyword argument *must* be
  461. either an integer (and, thus, specify the same prefix length value for all
  462. columns of the index) or a dict in which keys are column names and values are
  463. prefix length values for corresponding columns. MySQL and MariaDB only allow a
  464. length for a column of an index if it is for a CHAR, VARCHAR, TEXT, BINARY,
  465. VARBINARY and BLOB.
  466. Index Prefixes
  467. ~~~~~~~~~~~~~~
  468. MySQL storage engines permit you to specify an index prefix when creating
  469. an index. SQLAlchemy provides this feature via the
  470. ``mysql_prefix`` parameter on :class:`.Index`::
  471. Index('my_index', my_table.c.data, mysql_prefix='FULLTEXT')
  472. The value passed to the keyword argument will be simply passed through to the
  473. underlying CREATE INDEX, so it *must* be a valid index prefix for your MySQL
  474. storage engine.
  475. .. versionadded:: 1.1.5
  476. .. seealso::
  477. `CREATE INDEX <http://dev.mysql.com/doc/refman/5.0/en/create-index.html>`_ - MySQL documentation
  478. Index Types
  479. ~~~~~~~~~~~~~
  480. Some MySQL storage engines permit you to specify an index type when creating
  481. an index or primary key constraint. SQLAlchemy provides this feature via the
  482. ``mysql_using`` parameter on :class:`.Index`::
  483. Index('my_index', my_table.c.data, mysql_using='hash', mariadb_using='hash')
  484. As well as the ``mysql_using`` parameter on :class:`.PrimaryKeyConstraint`::
  485. PrimaryKeyConstraint("data", mysql_using='hash', mariadb_using='hash')
  486. The value passed to the keyword argument will be simply passed through to the
  487. underlying CREATE INDEX or PRIMARY KEY clause, so it *must* be a valid index
  488. type for your MySQL storage engine.
  489. More information can be found at:
  490. http://dev.mysql.com/doc/refman/5.0/en/create-index.html
  491. http://dev.mysql.com/doc/refman/5.0/en/create-table.html
  492. Index Parsers
  493. ~~~~~~~~~~~~~
  494. CREATE FULLTEXT INDEX in MySQL also supports a "WITH PARSER" option. This
  495. is available using the keyword argument ``mysql_with_parser``::
  496. Index(
  497. 'my_index', my_table.c.data,
  498. mysql_prefix='FULLTEXT', mysql_with_parser="ngram",
  499. mariadb_prefix='FULLTEXT', mariadb_with_parser="ngram",
  500. )
  501. .. versionadded:: 1.3
  502. .. _mysql_foreign_keys:
  503. MySQL / MariaDB Foreign Keys
  504. -----------------------------
  505. MySQL and MariaDB's behavior regarding foreign keys has some important caveats.
  506. Foreign Key Arguments to Avoid
  507. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  508. Neither MySQL nor MariaDB support the foreign key arguments "DEFERRABLE", "INITIALLY",
  509. or "MATCH". Using the ``deferrable`` or ``initially`` keyword argument with
  510. :class:`_schema.ForeignKeyConstraint` or :class:`_schema.ForeignKey`
  511. will have the effect of
  512. these keywords being rendered in a DDL expression, which will then raise an
  513. error on MySQL or MariaDB. In order to use these keywords on a foreign key while having
  514. them ignored on a MySQL / MariaDB backend, use a custom compile rule::
  515. from sqlalchemy.ext.compiler import compiles
  516. from sqlalchemy.schema import ForeignKeyConstraint
  517. @compiles(ForeignKeyConstraint, "mysql", "mariadb")
  518. def process(element, compiler, **kw):
  519. element.deferrable = element.initially = None
  520. return compiler.visit_foreign_key_constraint(element, **kw)
  521. The "MATCH" keyword is in fact more insidious, and is explicitly disallowed
  522. by SQLAlchemy in conjunction with the MySQL or MariaDB backends. This argument is
  523. silently ignored by MySQL / MariaDB, but in addition has the effect of ON UPDATE and ON
  524. DELETE options also being ignored by the backend. Therefore MATCH should
  525. never be used with the MySQL / MariaDB backends; as is the case with DEFERRABLE and
  526. INITIALLY, custom compilation rules can be used to correct a
  527. ForeignKeyConstraint at DDL definition time.
  528. Reflection of Foreign Key Constraints
  529. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  530. Not all MySQL / MariaDB storage engines support foreign keys. When using the
  531. very common ``MyISAM`` MySQL storage engine, the information loaded by table
  532. reflection will not include foreign keys. For these tables, you may supply a
  533. :class:`~sqlalchemy.ForeignKeyConstraint` at reflection time::
  534. Table('mytable', metadata,
  535. ForeignKeyConstraint(['other_id'], ['othertable.other_id']),
  536. autoload_with=engine
  537. )
  538. .. seealso::
  539. :ref:`mysql_storage_engines`
  540. .. _mysql_unique_constraints:
  541. MySQL / MariaDB Unique Constraints and Reflection
  542. ----------------------------------------------------
  543. SQLAlchemy supports both the :class:`.Index` construct with the
  544. flag ``unique=True``, indicating a UNIQUE index, as well as the
  545. :class:`.UniqueConstraint` construct, representing a UNIQUE constraint.
  546. Both objects/syntaxes are supported by MySQL / MariaDB when emitting DDL to create
  547. these constraints. However, MySQL / MariaDB does not have a unique constraint
  548. construct that is separate from a unique index; that is, the "UNIQUE"
  549. constraint on MySQL / MariaDB is equivalent to creating a "UNIQUE INDEX".
  550. When reflecting these constructs, the
  551. :meth:`_reflection.Inspector.get_indexes`
  552. and the :meth:`_reflection.Inspector.get_unique_constraints`
  553. methods will **both**
  554. return an entry for a UNIQUE index in MySQL / MariaDB. However, when performing
  555. full table reflection using ``Table(..., autoload_with=engine)``,
  556. the :class:`.UniqueConstraint` construct is
  557. **not** part of the fully reflected :class:`_schema.Table` construct under any
  558. circumstances; this construct is always represented by a :class:`.Index`
  559. with the ``unique=True`` setting present in the :attr:`_schema.Table.indexes`
  560. collection.
  561. TIMESTAMP / DATETIME issues
  562. ---------------------------
  563. .. _mysql_timestamp_onupdate:
  564. Rendering ON UPDATE CURRENT TIMESTAMP for MySQL / MariaDB's explicit_defaults_for_timestamp
  565. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  566. MySQL / MariaDB have historically expanded the DDL for the :class:`_types.TIMESTAMP`
  567. datatype into the phrase "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
  568. CURRENT_TIMESTAMP", which includes non-standard SQL that automatically updates
  569. the column with the current timestamp when an UPDATE occurs, eliminating the
  570. usual need to use a trigger in such a case where server-side update changes are
  571. desired.
  572. MySQL 5.6 introduced a new flag `explicit_defaults_for_timestamp
  573. <http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html
  574. #sysvar_explicit_defaults_for_timestamp>`_ which disables the above behavior,
  575. and in MySQL 8 this flag defaults to true, meaning in order to get a MySQL
  576. "on update timestamp" without changing this flag, the above DDL must be
  577. rendered explicitly. Additionally, the same DDL is valid for use of the
  578. ``DATETIME`` datatype as well.
  579. SQLAlchemy's MySQL dialect does not yet have an option to generate
  580. MySQL's "ON UPDATE CURRENT_TIMESTAMP" clause, noting that this is not a general
  581. purpose "ON UPDATE" as there is no such syntax in standard SQL. SQLAlchemy's
  582. :paramref:`_schema.Column.server_onupdate` parameter is currently not related
  583. to this special MySQL behavior.
  584. To generate this DDL, make use of the :paramref:`_schema.Column.server_default`
  585. parameter and pass a textual clause that also includes the ON UPDATE clause::
  586. from sqlalchemy import Table, MetaData, Column, Integer, String, TIMESTAMP
  587. from sqlalchemy import text
  588. metadata = MetaData()
  589. mytable = Table(
  590. "mytable",
  591. metadata,
  592. Column('id', Integer, primary_key=True),
  593. Column('data', String(50)),
  594. Column(
  595. 'last_updated',
  596. TIMESTAMP,
  597. server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
  598. )
  599. )
  600. The same instructions apply to use of the :class:`_types.DateTime` and
  601. :class:`_types.DATETIME` datatypes::
  602. from sqlalchemy import DateTime
  603. mytable = Table(
  604. "mytable",
  605. metadata,
  606. Column('id', Integer, primary_key=True),
  607. Column('data', String(50)),
  608. Column(
  609. 'last_updated',
  610. DateTime,
  611. server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")
  612. )
  613. )
  614. Even though the :paramref:`_schema.Column.server_onupdate` feature does not
  615. generate this DDL, it still may be desirable to signal to the ORM that this
  616. updated value should be fetched. This syntax looks like the following::
  617. from sqlalchemy.schema import FetchedValue
  618. class MyClass(Base):
  619. __tablename__ = 'mytable'
  620. id = Column(Integer, primary_key=True)
  621. data = Column(String(50))
  622. last_updated = Column(
  623. TIMESTAMP,
  624. server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),
  625. server_onupdate=FetchedValue()
  626. )
  627. .. _mysql_timestamp_null:
  628. TIMESTAMP Columns and NULL
  629. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  630. MySQL historically enforces that a column which specifies the
  631. TIMESTAMP datatype implicitly includes a default value of
  632. CURRENT_TIMESTAMP, even though this is not stated, and additionally
  633. sets the column as NOT NULL, the opposite behavior vs. that of all
  634. other datatypes::
  635. mysql> CREATE TABLE ts_test (
  636. -> a INTEGER,
  637. -> b INTEGER NOT NULL,
  638. -> c TIMESTAMP,
  639. -> d TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  640. -> e TIMESTAMP NULL);
  641. Query OK, 0 rows affected (0.03 sec)
  642. mysql> SHOW CREATE TABLE ts_test;
  643. +---------+-----------------------------------------------------
  644. | Table | Create Table
  645. +---------+-----------------------------------------------------
  646. | ts_test | CREATE TABLE `ts_test` (
  647. `a` int(11) DEFAULT NULL,
  648. `b` int(11) NOT NULL,
  649. `c` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  650. `d` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  651. `e` timestamp NULL DEFAULT NULL
  652. ) ENGINE=MyISAM DEFAULT CHARSET=latin1
  653. Above, we see that an INTEGER column defaults to NULL, unless it is specified
  654. with NOT NULL. But when the column is of type TIMESTAMP, an implicit
  655. default of CURRENT_TIMESTAMP is generated which also coerces the column
  656. to be a NOT NULL, even though we did not specify it as such.
  657. This behavior of MySQL can be changed on the MySQL side using the
  658. `explicit_defaults_for_timestamp
  659. <http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html
  660. #sysvar_explicit_defaults_for_timestamp>`_ configuration flag introduced in
  661. MySQL 5.6. With this server setting enabled, TIMESTAMP columns behave like
  662. any other datatype on the MySQL side with regards to defaults and nullability.
  663. However, to accommodate the vast majority of MySQL databases that do not
  664. specify this new flag, SQLAlchemy emits the "NULL" specifier explicitly with
  665. any TIMESTAMP column that does not specify ``nullable=False``. In order to
  666. accommodate newer databases that specify ``explicit_defaults_for_timestamp``,
  667. SQLAlchemy also emits NOT NULL for TIMESTAMP columns that do specify
  668. ``nullable=False``. The following example illustrates::
  669. from sqlalchemy import MetaData, Integer, Table, Column, text
  670. from sqlalchemy.dialects.mysql import TIMESTAMP
  671. m = MetaData()
  672. t = Table('ts_test', m,
  673. Column('a', Integer),
  674. Column('b', Integer, nullable=False),
  675. Column('c', TIMESTAMP),
  676. Column('d', TIMESTAMP, nullable=False)
  677. )
  678. from sqlalchemy import create_engine
  679. e = create_engine("mysql://scott:tiger@localhost/test", echo=True)
  680. m.create_all(e)
  681. output::
  682. CREATE TABLE ts_test (
  683. a INTEGER,
  684. b INTEGER NOT NULL,
  685. c TIMESTAMP NULL,
  686. d TIMESTAMP NOT NULL
  687. )
  688. .. versionchanged:: 1.0.0 - SQLAlchemy now renders NULL or NOT NULL in all
  689. cases for TIMESTAMP columns, to accommodate
  690. ``explicit_defaults_for_timestamp``. Prior to this version, it will
  691. not render "NOT NULL" for a TIMESTAMP column that is ``nullable=False``.
  692. """ # noqa
  693. from array import array as _array
  694. from collections import defaultdict
  695. from itertools import compress
  696. import re
  697. from sqlalchemy import literal_column
  698. from sqlalchemy import text
  699. from sqlalchemy.sql import visitors
  700. from . import reflection as _reflection
  701. from .enumerated import ENUM
  702. from .enumerated import SET
  703. from .json import JSON
  704. from .json import JSONIndexType
  705. from .json import JSONPathType
  706. from .types import _FloatType
  707. from .types import _IntegerType
  708. from .types import _MatchType
  709. from .types import _NumericType
  710. from .types import _StringType
  711. from .types import BIGINT
  712. from .types import BIT
  713. from .types import CHAR
  714. from .types import DATETIME
  715. from .types import DECIMAL
  716. from .types import DOUBLE
  717. from .types import FLOAT
  718. from .types import INTEGER
  719. from .types import LONGBLOB
  720. from .types import LONGTEXT
  721. from .types import MEDIUMBLOB
  722. from .types import MEDIUMINT
  723. from .types import MEDIUMTEXT
  724. from .types import NCHAR
  725. from .types import NUMERIC
  726. from .types import NVARCHAR
  727. from .types import REAL
  728. from .types import SMALLINT
  729. from .types import TEXT
  730. from .types import TIME
  731. from .types import TIMESTAMP
  732. from .types import TINYBLOB
  733. from .types import TINYINT
  734. from .types import TINYTEXT
  735. from .types import VARCHAR
  736. from .types import YEAR
  737. from ... import exc
  738. from ... import log
  739. from ... import schema as sa_schema
  740. from ... import sql
  741. from ... import types as sqltypes
  742. from ... import util
  743. from ...engine import default
  744. from ...engine import reflection
  745. from ...sql import coercions
  746. from ...sql import compiler
  747. from ...sql import elements
  748. from ...sql import functions
  749. from ...sql import operators
  750. from ...sql import roles
  751. from ...sql import util as sql_util
  752. from ...sql.sqltypes import Unicode
  753. from ...types import BINARY
  754. from ...types import BLOB
  755. from ...types import BOOLEAN
  756. from ...types import DATE
  757. from ...types import VARBINARY
  758. from ...util import topological
  759. RESERVED_WORDS = set(
  760. [
  761. "accessible",
  762. "action",
  763. "add",
  764. "admin",
  765. "all",
  766. "alter",
  767. "analyze",
  768. "and",
  769. "array", # 8.0
  770. "as",
  771. "asc",
  772. "asensitive",
  773. "before",
  774. "between",
  775. "bigint",
  776. "binary",
  777. "blob",
  778. "both",
  779. "by",
  780. "call",
  781. "cascade",
  782. "case",
  783. "change",
  784. "char",
  785. "character",
  786. "check",
  787. "collate",
  788. "column",
  789. "columns",
  790. "condition",
  791. "constraint",
  792. "continue",
  793. "convert",
  794. "create",
  795. "cross",
  796. "cube",
  797. "cume_dist",
  798. "current_date",
  799. "current_time",
  800. "current_timestamp",
  801. "current_user",
  802. "cursor",
  803. "database",
  804. "databases",
  805. "day_hour",
  806. "day_microsecond",
  807. "day_minute",
  808. "day_second",
  809. "dec",
  810. "decimal",
  811. "declare",
  812. "default",
  813. "delayed",
  814. "delete",
  815. "desc",
  816. "describe",
  817. "deterministic",
  818. "distinct",
  819. "distinctrow",
  820. "div",
  821. "double",
  822. "drop",
  823. "dual",
  824. "each",
  825. "else",
  826. "elseif",
  827. "empty",
  828. "enclosed",
  829. "escaped",
  830. "except",
  831. "exists",
  832. "exit",
  833. "explain",
  834. "false",
  835. "fetch",
  836. "fields",
  837. "first_value",
  838. "float",
  839. "float4",
  840. "float8",
  841. "for",
  842. "force",
  843. "foreign",
  844. "from",
  845. "fulltext",
  846. "function",
  847. "general",
  848. "generated",
  849. "get",
  850. "grant",
  851. "group",
  852. "grouping",
  853. "groups",
  854. "having",
  855. "high_priority",
  856. "hour_microsecond",
  857. "hour_minute",
  858. "hour_second",
  859. "if",
  860. "ignore",
  861. "ignore_server_ids",
  862. "in",
  863. "index",
  864. "infile",
  865. "inner",
  866. "inout",
  867. "insensitive",
  868. "insert",
  869. "int",
  870. "int1",
  871. "int2",
  872. "int3",
  873. "int4",
  874. "int8",
  875. "integer",
  876. "interval",
  877. "into",
  878. "io_after_gtids",
  879. "io_before_gtids",
  880. "is",
  881. "iterate",
  882. "join",
  883. "json_table",
  884. "key",
  885. "keys",
  886. "kill",
  887. "last_value",
  888. "lateral",
  889. "leading",
  890. "leave",
  891. "left",
  892. "level",
  893. "like",
  894. "limit",
  895. "linear",
  896. "linear",
  897. "lines",
  898. "load",
  899. "localtime",
  900. "localtimestamp",
  901. "lock",
  902. "long",
  903. "longblob",
  904. "longtext",
  905. "loop",
  906. "low_priority",
  907. "master_bind",
  908. "master_heartbeat_period",
  909. "master_ssl_verify_server_cert",
  910. "master_ssl_verify_server_cert",
  911. "match",
  912. "maxvalue",
  913. "mediumblob",
  914. "mediumint",
  915. "mediumtext",
  916. "member", # 8.0
  917. "middleint",
  918. "minute_microsecond",
  919. "minute_second",
  920. "mod",
  921. "mode",
  922. "modifies",
  923. "natural",
  924. "no_write_to_binlog",
  925. "not",
  926. "nth_value",
  927. "ntile",
  928. "null",
  929. "numeric",
  930. "of",
  931. "on",
  932. "one_shot",
  933. "optimize",
  934. "optimizer_costs",
  935. "option",
  936. "optionally",
  937. "or",
  938. "order",
  939. "out",
  940. "outer",
  941. "outfile",
  942. "over",
  943. "partition",
  944. "percent_rank",
  945. "persist",
  946. "persist_only",
  947. "precision",
  948. "primary",
  949. "privileges",
  950. "procedure",
  951. "purge",
  952. "range",
  953. "range",
  954. "rank",
  955. "read",
  956. "read_only",
  957. "read_only",
  958. "read_write",
  959. "read_write", # 5.1
  960. "reads",
  961. "real",
  962. "recursive",
  963. "references",
  964. "regexp",
  965. "release",
  966. "rename",
  967. "repeat",
  968. "replace",
  969. "require",
  970. "resignal",
  971. "restrict",
  972. "return",
  973. "revoke",
  974. "right",
  975. "rlike",
  976. "role",
  977. "row",
  978. "row_number",
  979. "rows",
  980. "schema",
  981. "schemas",
  982. "second_microsecond",
  983. "select",
  984. "sensitive",
  985. "separator",
  986. "set",
  987. "show",
  988. "signal",
  989. "slow", # 5.5
  990. "smallint",
  991. "soname",
  992. "spatial",
  993. "specific",
  994. "sql",
  995. "sql_after_gtids",
  996. "sql_before_gtids", # 5.6
  997. "sql_big_result",
  998. "sql_calc_found_rows",
  999. "sql_small_result",
  1000. "sqlexception",
  1001. "sqlstate",
  1002. "sqlwarning",
  1003. "ssl",
  1004. "starting",
  1005. "status",
  1006. "stored",
  1007. "straight_join",
  1008. "system",
  1009. "table",
  1010. "tables", # 4.1
  1011. "terminated",
  1012. "text",
  1013. "then",
  1014. "time",
  1015. "tinyblob",
  1016. "tinyint",
  1017. "tinytext",
  1018. "to",
  1019. "trailing",
  1020. "trigger",
  1021. "true",
  1022. "undo",
  1023. "union",
  1024. "unique",
  1025. "unlock",
  1026. "unsigned",
  1027. "update",
  1028. "usage",
  1029. "use",
  1030. "using",
  1031. "utc_date",
  1032. "utc_time",
  1033. "utc_timestamp",
  1034. "values",
  1035. "varbinary",
  1036. "varchar",
  1037. "varcharacter",
  1038. "varying",
  1039. "virtual", # 5.7
  1040. "when",
  1041. "where",
  1042. "while",
  1043. "window", # 8.0
  1044. "with",
  1045. "write",
  1046. "x509",
  1047. "xor",
  1048. "year_month",
  1049. "zerofill", # 5.0
  1050. ]
  1051. )
  1052. AUTOCOMMIT_RE = re.compile(
  1053. r"\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|LOAD +DATA|REPLACE)",
  1054. re.I | re.UNICODE,
  1055. )
  1056. SET_RE = re.compile(
  1057. r"\s*SET\s+(?:(?:GLOBAL|SESSION)\s+)?\w", re.I | re.UNICODE
  1058. )
  1059. # old names
  1060. MSTime = TIME
  1061. MSSet = SET
  1062. MSEnum = ENUM
  1063. MSLongBlob = LONGBLOB
  1064. MSMediumBlob = MEDIUMBLOB
  1065. MSTinyBlob = TINYBLOB
  1066. MSBlob = BLOB
  1067. MSBinary = BINARY
  1068. MSVarBinary = VARBINARY
  1069. MSNChar = NCHAR
  1070. MSNVarChar = NVARCHAR
  1071. MSChar = CHAR
  1072. MSString = VARCHAR
  1073. MSLongText = LONGTEXT
  1074. MSMediumText = MEDIUMTEXT
  1075. MSTinyText = TINYTEXT
  1076. MSText = TEXT
  1077. MSYear = YEAR
  1078. MSTimeStamp = TIMESTAMP
  1079. MSBit = BIT
  1080. MSSmallInteger = SMALLINT
  1081. MSTinyInteger = TINYINT
  1082. MSMediumInteger = MEDIUMINT
  1083. MSBigInteger = BIGINT
  1084. MSNumeric = NUMERIC
  1085. MSDecimal = DECIMAL
  1086. MSDouble = DOUBLE
  1087. MSReal = REAL
  1088. MSFloat = FLOAT
  1089. MSInteger = INTEGER
  1090. colspecs = {
  1091. _IntegerType: _IntegerType,
  1092. _NumericType: _NumericType,
  1093. _FloatType: _FloatType,
  1094. sqltypes.Numeric: NUMERIC,
  1095. sqltypes.Float: FLOAT,
  1096. sqltypes.Time: TIME,
  1097. sqltypes.Enum: ENUM,
  1098. sqltypes.MatchType: _MatchType,
  1099. sqltypes.JSON: JSON,
  1100. sqltypes.JSON.JSONIndexType: JSONIndexType,
  1101. sqltypes.JSON.JSONPathType: JSONPathType,
  1102. }
  1103. # Everything 3.23 through 5.1 excepting OpenGIS types.
  1104. ischema_names = {
  1105. "bigint": BIGINT,
  1106. "binary": BINARY,
  1107. "bit": BIT,
  1108. "blob": BLOB,
  1109. "boolean": BOOLEAN,
  1110. "char": CHAR,
  1111. "date": DATE,
  1112. "datetime": DATETIME,
  1113. "decimal": DECIMAL,
  1114. "double": DOUBLE,
  1115. "enum": ENUM,
  1116. "fixed": DECIMAL,
  1117. "float": FLOAT,
  1118. "int": INTEGER,
  1119. "integer": INTEGER,
  1120. "json": JSON,
  1121. "longblob": LONGBLOB,
  1122. "longtext": LONGTEXT,
  1123. "mediumblob": MEDIUMBLOB,
  1124. "mediumint": MEDIUMINT,
  1125. "mediumtext": MEDIUMTEXT,
  1126. "nchar": NCHAR,
  1127. "nvarchar": NVARCHAR,
  1128. "numeric": NUMERIC,
  1129. "set": SET,
  1130. "smallint": SMALLINT,
  1131. "text": TEXT,
  1132. "time": TIME,
  1133. "timestamp": TIMESTAMP,
  1134. "tinyblob": TINYBLOB,
  1135. "tinyint": TINYINT,
  1136. "tinytext": TINYTEXT,
  1137. "varbinary": VARBINARY,
  1138. "varchar": VARCHAR,
  1139. "year": YEAR,
  1140. }
  1141. class MySQLExecutionContext(default.DefaultExecutionContext):
  1142. def should_autocommit_text(self, statement):
  1143. return AUTOCOMMIT_RE.match(statement)
  1144. def create_server_side_cursor(self):
  1145. if self.dialect.supports_server_side_cursors:
  1146. return self._dbapi_connection.cursor(self.dialect._sscursor)
  1147. else:
  1148. raise NotImplementedError()
  1149. def fire_sequence(self, seq, type_):
  1150. return self._execute_scalar(
  1151. (
  1152. "select nextval(%s)"
  1153. % self.identifier_preparer.format_sequence(seq)
  1154. ),
  1155. type_,
  1156. )
  1157. class MySQLCompiler(compiler.SQLCompiler):
  1158. render_table_with_column_in_update_from = True
  1159. """Overridden from base SQLCompiler value"""
  1160. extract_map = compiler.SQLCompiler.extract_map.copy()
  1161. extract_map.update({"milliseconds": "millisecond"})
  1162. def default_from(self):
  1163. """Called when a ``SELECT`` statement has no froms,
  1164. and no ``FROM`` clause is to be appended.
  1165. """
  1166. if self.stack:
  1167. stmt = self.stack[-1]["selectable"]
  1168. if stmt._where_criteria:
  1169. return " FROM DUAL"
  1170. return ""
  1171. def visit_random_func(self, fn, **kw):
  1172. return "rand%s" % self.function_argspec(fn)
  1173. def visit_sequence(self, seq, **kw):
  1174. return "nextval(%s)" % self.preparer.format_sequence(seq)
  1175. def visit_sysdate_func(self, fn, **kw):
  1176. return "SYSDATE()"
  1177. def _render_json_extract_from_binary(self, binary, operator, **kw):
  1178. # note we are intentionally calling upon the process() calls in the
  1179. # order in which they appear in the SQL String as this is used
  1180. # by positional parameter rendering
  1181. if binary.type._type_affinity is sqltypes.JSON:
  1182. return "JSON_EXTRACT(%s, %s)" % (
  1183. self.process(binary.left, **kw),
  1184. self.process(binary.right, **kw),
  1185. )
  1186. # for non-JSON, MySQL doesn't handle JSON null at all so it has to
  1187. # be explicit
  1188. case_expression = "CASE JSON_EXTRACT(%s, %s) WHEN 'null' THEN NULL" % (
  1189. self.process(binary.left, **kw),
  1190. self.process(binary.right, **kw),
  1191. )
  1192. if binary.type._type_affinity is sqltypes.Integer:
  1193. type_expression = (
  1194. "ELSE CAST(JSON_EXTRACT(%s, %s) AS SIGNED INTEGER)"
  1195. % (
  1196. self.process(binary.left, **kw),
  1197. self.process(binary.right, **kw),
  1198. )
  1199. )
  1200. elif binary.type._type_affinity is sqltypes.Numeric:
  1201. if (
  1202. binary.type.scale is not None
  1203. and binary.type.precision is not None
  1204. ):
  1205. # using DECIMAL here because MySQL does not recognize NUMERIC
  1206. type_expression = (
  1207. "ELSE CAST(JSON_EXTRACT(%s, %s) AS DECIMAL(%s, %s))"
  1208. % (
  1209. self.process(binary.left, **kw),
  1210. self.process(binary.right, **kw),
  1211. binary.type.precision,
  1212. binary.type.scale,
  1213. )
  1214. )
  1215. else:
  1216. # FLOAT / REAL not added in MySQL til 8.0.17
  1217. type_expression = (
  1218. "ELSE JSON_EXTRACT(%s, %s)+0.0000000000000000000000"
  1219. % (
  1220. self.process(binary.left, **kw),
  1221. self.process(binary.right, **kw),
  1222. )
  1223. )
  1224. elif binary.type._type_affinity is sqltypes.Boolean:
  1225. # the NULL handling is particularly weird with boolean, so
  1226. # explicitly return true/false constants
  1227. type_expression = "WHEN true THEN true ELSE false"
  1228. elif binary.type._type_affinity is sqltypes.String:
  1229. # (gord): this fails with a JSON value that's a four byte unicode
  1230. # string. SQLite has the same problem at the moment
  1231. # (zzzeek): I'm not really sure. let's take a look at a test case
  1232. # that hits each backend and maybe make a requires rule for it?
  1233. type_expression = "ELSE JSON_UNQUOTE(JSON_EXTRACT(%s, %s))" % (
  1234. self.process(binary.left, **kw),
  1235. self.process(binary.right, **kw),
  1236. )
  1237. else:
  1238. # other affinity....this is not expected right now
  1239. type_expression = "ELSE JSON_EXTRACT(%s, %s)" % (
  1240. self.process(binary.left, **kw),
  1241. self.process(binary.right, **kw),
  1242. )
  1243. return case_expression + " " + type_expression + " END"
  1244. def visit_json_getitem_op_binary(self, binary, operator, **kw):
  1245. return self._render_json_extract_from_binary(binary, operator, **kw)
  1246. def visit_json_path_getitem_op_binary(self, binary, operator, **kw):
  1247. return self._render_json_extract_from_binary(binary, operator, **kw)
  1248. def visit_on_duplicate_key_update(self, on_duplicate, **kw):
  1249. statement = self.current_executable
  1250. if on_duplicate._parameter_ordering:
  1251. parameter_ordering = [
  1252. coercions.expect(roles.DMLColumnRole, key)
  1253. for key in on_duplicate._parameter_ordering
  1254. ]
  1255. ordered_keys = set(parameter_ordering)
  1256. cols = [
  1257. statement.table.c[key]
  1258. for key in parameter_ordering
  1259. if key in statement.table.c
  1260. ] + [c for c in statement.table.c if c.key not in ordered_keys]
  1261. else:
  1262. cols = statement.table.c
  1263. clauses = []
  1264. # traverses through all table columns to preserve table column order
  1265. for column in (col for col in cols if col.key in on_duplicate.update):
  1266. val = on_duplicate.update[column.key]
  1267. if coercions._is_literal(val):
  1268. val = elements.BindParameter(None, val, type_=column.type)
  1269. value_text = self.process(val.self_group(), use_schema=False)
  1270. else:
  1271. def replace(obj):
  1272. if (
  1273. isinstance(obj, elements.BindParameter)
  1274. and obj.type._isnull
  1275. ):
  1276. obj = obj._clone()
  1277. obj.type = column.type
  1278. return obj
  1279. elif (
  1280. isinstance(obj, elements.ColumnClause)
  1281. and obj.table is on_duplicate.inserted_alias
  1282. ):
  1283. obj = literal_column(
  1284. "VALUES(" + self.preparer.quote(column.name) + ")"
  1285. )
  1286. return obj
  1287. else:
  1288. # element is not replaced
  1289. return None
  1290. val = visitors.replacement_traverse(val, {}, replace)
  1291. value_text = self.process(val.self_group(), use_schema=False)
  1292. name_text = self.preparer.quote(column.name)
  1293. clauses.append("%s = %s" % (name_text, value_text))
  1294. non_matching = set(on_duplicate.update) - set(c.key for c in cols)
  1295. if non_matching:
  1296. util.warn(
  1297. "Additional column names not matching "
  1298. "any column keys in table '%s': %s"
  1299. % (
  1300. self.statement.table.name,
  1301. (", ".join("'%s'" % c for c in non_matching)),
  1302. )
  1303. )
  1304. return "ON DUPLICATE KEY UPDATE " + ", ".join(clauses)
  1305. def visit_concat_op_binary(self, binary, operator, **kw):
  1306. return "concat(%s, %s)" % (
  1307. self.process(binary.left, **kw),
  1308. self.process(binary.right, **kw),
  1309. )
  1310. _match_valid_flag_combinations = frozenset(
  1311. (
  1312. # (boolean_mode, natural_language, query_expansion)
  1313. (False, False, False),
  1314. (True, False, False),
  1315. (False, True, False),
  1316. (False, False, True),
  1317. (False, True, True),
  1318. )
  1319. )
  1320. _match_flag_expressions = (
  1321. "IN BOOLEAN MODE",
  1322. "IN NATURAL LANGUAGE MODE",
  1323. "WITH QUERY EXPANSION",
  1324. )
  1325. def visit_mysql_match(self, element, **kw):
  1326. return self.visit_match_op_binary(element, element.operator, **kw)
  1327. def visit_match_op_binary(self, binary, operator, **kw):
  1328. """
  1329. Note that `mysql_boolean_mode` is enabled by default because of
  1330. backward compatibility
  1331. """
  1332. modifiers = binary.modifiers
  1333. boolean_mode = modifiers.get("mysql_boolean_mode", True)
  1334. natural_language = modifiers.get("mysql_natural_language", False)
  1335. query_expansion = modifiers.get("mysql_query_expansion", False)
  1336. flag_combination = (boolean_mode, natural_language, query_expansion)
  1337. if flag_combination not in self._match_valid_flag_combinations:
  1338. flags = (
  1339. "in_boolean_mode=%s" % boolean_mode,
  1340. "in_natural_language_mode=%s" % natural_language,
  1341. "with_query_expansion=%s" % query_expansion,
  1342. )
  1343. flags = ", ".join(flags)
  1344. raise exc.CompileError("Invalid MySQL match flags: %s" % flags)
  1345. match_clause = binary.left
  1346. match_clause = self.process(match_clause, **kw)
  1347. against_clause = self.process(binary.right, **kw)
  1348. if any(flag_combination):
  1349. flag_expressions = compress(
  1350. self._match_flag_expressions,
  1351. flag_combination,
  1352. )
  1353. against_clause = [against_clause]
  1354. against_clause.extend(flag_expressions)
  1355. against_clause = " ".join(against_clause)
  1356. return "MATCH (%s) AGAINST (%s)" % (match_clause, against_clause)
  1357. def get_from_hint_text(self, table, text):
  1358. return text
  1359. def visit_typeclause(self, typeclause, type_=None, **kw):
  1360. if type_ is None:
  1361. type_ = typeclause.type.dialect_impl(self.dialect)
  1362. if isinstance(type_, sqltypes.TypeDecorator):
  1363. return self.visit_typeclause(typeclause, type_.impl, **kw)
  1364. elif isinstance(type_, sqltypes.Integer):
  1365. if getattr(type_, "unsigned", False):
  1366. return "UNSIGNED INTEGER"
  1367. else:
  1368. return "SIGNED INTEGER"
  1369. elif isinstance(type_, sqltypes.TIMESTAMP):
  1370. return "DATETIME"
  1371. elif isinstance(
  1372. type_,
  1373. (
  1374. sqltypes.DECIMAL,
  1375. sqltypes.DateTime,
  1376. sqltypes.Date,
  1377. sqltypes.Time,
  1378. ),
  1379. ):
  1380. return self.dialect.type_compiler.process(type_)
  1381. elif isinstance(type_, sqltypes.String) and not isinstance(
  1382. type_, (ENUM, SET)
  1383. ):
  1384. adapted = CHAR._adapt_string_for_cast(type_)
  1385. return self.dialect.type_compiler.process(adapted)
  1386. elif isinstance(type_, sqltypes._Binary):
  1387. return "BINARY"
  1388. elif isinstance(type_, sqltypes.JSON):
  1389. return "JSON"
  1390. elif isinstance(type_, sqltypes.NUMERIC):
  1391. return self.dialect.type_compiler.process(type_).replace(
  1392. "NUMERIC", "DECIMAL"
  1393. )
  1394. elif (
  1395. isinstance(type_, sqltypes.Float)
  1396. and self.dialect._support_float_cast
  1397. ):
  1398. return self.dialect.type_compiler.process(type_)
  1399. else:
  1400. return None
  1401. def visit_cast(self, cast, **kw):
  1402. type_ = self.process(cast.typeclause)
  1403. if type_ is None:
  1404. util.warn(
  1405. "Datatype %s does not support CAST on MySQL/MariaDb; "
  1406. "the CAST will be skipped."
  1407. % self.dialect.type_compiler.process(cast.typeclause.type)
  1408. )
  1409. return self.process(cast.clause.self_group(), **kw)
  1410. return "CAST(%s AS %s)" % (self.process(cast.clause, **kw), type_)
  1411. def render_literal_value(self, value, type_):
  1412. value = super(MySQLCompiler, self).render_literal_value(value, type_)
  1413. if self.dialect._backslash_escapes:
  1414. value = value.replace("\\", "\\\\")
  1415. return value
  1416. # override native_boolean=False behavior here, as
  1417. # MySQL still supports native boolean
  1418. def visit_true(self, element, **kw):
  1419. return "true"
  1420. def visit_false(self, element, **kw):
  1421. return "false"
  1422. def get_select_precolumns(self, select, **kw):
  1423. """Add special MySQL keywords in place of DISTINCT.
  1424. .. deprecated 1.4:: this usage is deprecated.
  1425. :meth:`_expression.Select.prefix_with` should be used for special
  1426. keywords at the start of a SELECT.
  1427. """
  1428. if isinstance(select._distinct, util.string_types):
  1429. util.warn_deprecated(
  1430. "Sending string values for 'distinct' is deprecated in the "
  1431. "MySQL dialect and will be removed in a future release. "
  1432. "Please use :meth:`.Select.prefix_with` for special keywords "
  1433. "at the start of a SELECT statement",
  1434. version="1.4",
  1435. )
  1436. return select._distinct.upper() + " "
  1437. return super(MySQLCompiler, self).get_select_precolumns(select, **kw)
  1438. def visit_join(self, join, asfrom=False, from_linter=None, **kwargs):
  1439. if from_linter:
  1440. from_linter.edges.add((join.left, join.right))
  1441. if join.full:
  1442. join_type = " FULL OUTER JOIN "
  1443. elif join.isouter:
  1444. join_type = " LEFT OUTER JOIN "
  1445. else:
  1446. join_type = " INNER JOIN "
  1447. return "".join(
  1448. (
  1449. self.process(
  1450. join.left, asfrom=True, from_linter=from_linter, **kwargs
  1451. ),
  1452. join_type,
  1453. self.process(
  1454. join.right, asfrom=True, from_linter=from_linter, **kwargs
  1455. ),
  1456. " ON ",
  1457. self.process(join.onclause, from_linter=from_linter, **kwargs),
  1458. )
  1459. )
  1460. def for_update_clause(self, select, **kw):
  1461. if select._for_update_arg.read:
  1462. tmp = " LOCK IN SHARE MODE"
  1463. else:
  1464. tmp = " FOR UPDATE"
  1465. if select._for_update_arg.of and self.dialect.supports_for_update_of:
  1466. tables = util.OrderedSet()
  1467. for c in select._for_update_arg.of:
  1468. tables.update(sql_util.surface_selectables_only(c))
  1469. tmp += " OF " + ", ".join(
  1470. self.process(table, ashint=True, use_schema=False, **kw)
  1471. for table in tables
  1472. )
  1473. if select._for_update_arg.nowait:
  1474. tmp += " NOWAIT"
  1475. if select._for_update_arg.skip_locked:
  1476. tmp += " SKIP LOCKED"
  1477. return tmp
  1478. def limit_clause(self, select, **kw):
  1479. # MySQL supports:
  1480. # LIMIT <limit>
  1481. # LIMIT <offset>, <limit>
  1482. # and in server versions > 3.3:
  1483. # LIMIT <limit> OFFSET <offset>
  1484. # The latter is more readable for offsets but we're stuck with the
  1485. # former until we can refine dialects by server revision.
  1486. limit_clause, offset_clause = (
  1487. select._limit_clause,
  1488. select._offset_clause,
  1489. )
  1490. if limit_clause is None and offset_clause is None:
  1491. return ""
  1492. elif offset_clause is not None:
  1493. # As suggested by the MySQL docs, need to apply an
  1494. # artificial limit if one wasn't provided
  1495. # http://dev.mysql.com/doc/refman/5.0/en/select.html
  1496. if limit_clause is None:
  1497. # hardwire the upper limit. Currently
  1498. # needed by OurSQL with Python 3
  1499. # (https://bugs.launchpad.net/oursql/+bug/686232),
  1500. # but also is consistent with the usage of the upper
  1501. # bound as part of MySQL's "syntax" for OFFSET with
  1502. # no LIMIT
  1503. return " \n LIMIT %s, %s" % (
  1504. self.process(offset_clause, **kw),
  1505. "18446744073709551615",
  1506. )
  1507. else:
  1508. return " \n LIMIT %s, %s" % (
  1509. self.process(offset_clause, **kw),
  1510. self.process(limit_clause, **kw),
  1511. )
  1512. else:
  1513. # No offset provided, so just use the limit
  1514. return " \n LIMIT %s" % (self.process(limit_clause, **kw),)
  1515. def update_limit_clause(self, update_stmt):
  1516. limit = update_stmt.kwargs.get("%s_limit" % self.dialect.name, None)
  1517. if limit:
  1518. return "LIMIT %s" % limit
  1519. else:
  1520. return None
  1521. def update_tables_clause(self, update_stmt, from_table, extra_froms, **kw):
  1522. kw["asfrom"] = True
  1523. return ", ".join(
  1524. t._compiler_dispatch(self, **kw)
  1525. for t in [from_table] + list(extra_froms)
  1526. )
  1527. def update_from_clause(
  1528. self, update_stmt, from_table, extra_froms, from_hints, **kw
  1529. ):
  1530. return None
  1531. def delete_table_clause(self, delete_stmt, from_table, extra_froms):
  1532. """If we have extra froms make sure we render any alias as hint."""
  1533. ashint = False
  1534. if extra_froms:
  1535. ashint = True
  1536. return from_table._compiler_dispatch(
  1537. self, asfrom=True, iscrud=True, ashint=ashint
  1538. )
  1539. def delete_extra_from_clause(
  1540. self, delete_stmt, from_table, extra_froms, from_hints, **kw
  1541. ):
  1542. """Render the DELETE .. USING clause specific to MySQL."""
  1543. kw["asfrom"] = True
  1544. return "USING " + ", ".join(
  1545. t._compiler_dispatch(self, fromhints=from_hints, **kw)
  1546. for t in [from_table] + extra_froms
  1547. )
  1548. def visit_empty_set_expr(self, element_types):
  1549. return (
  1550. "SELECT %(outer)s FROM (SELECT %(inner)s) "
  1551. "as _empty_set WHERE 1!=1"
  1552. % {
  1553. "inner": ", ".join(
  1554. "1 AS _in_%s" % idx
  1555. for idx, type_ in enumerate(element_types)
  1556. ),
  1557. "outer": ", ".join(
  1558. "_in_%s" % idx for idx, type_ in enumerate(element_types)
  1559. ),
  1560. }
  1561. )
  1562. def visit_is_distinct_from_binary(self, binary, operator, **kw):
  1563. return "NOT (%s <=> %s)" % (
  1564. self.process(binary.left),
  1565. self.process(binary.right),
  1566. )
  1567. def visit_is_not_distinct_from_binary(self, binary, operator, **kw):
  1568. return "%s <=> %s" % (
  1569. self.process(binary.left),
  1570. self.process(binary.right),
  1571. )
  1572. def _mariadb_regexp_flags(self, flags, pattern, **kw):
  1573. return "CONCAT('(?', %s, ')', %s)" % (
  1574. self.process(flags, **kw),
  1575. self.process(pattern, **kw),
  1576. )
  1577. def _regexp_match(self, op_string, binary, operator, **kw):
  1578. flags = binary.modifiers["flags"]
  1579. if flags is None:
  1580. return self._generate_generic_binary(binary, op_string, **kw)
  1581. elif self.dialect.is_mariadb:
  1582. return "%s%s%s" % (
  1583. self.process(binary.left, **kw),
  1584. op_string,
  1585. self._mariadb_regexp_flags(flags, binary.right),
  1586. )
  1587. else:
  1588. text = "REGEXP_LIKE(%s, %s, %s)" % (
  1589. self.process(binary.left, **kw),
  1590. self.process(binary.right, **kw),
  1591. self.process(flags, **kw),
  1592. )
  1593. if op_string == " NOT REGEXP ":
  1594. return "NOT %s" % text
  1595. else:
  1596. return text
  1597. def visit_regexp_match_op_binary(self, binary, operator, **kw):
  1598. return self._regexp_match(" REGEXP ", binary, operator, **kw)
  1599. def visit_not_regexp_match_op_binary(self, binary, operator, **kw):
  1600. return self._regexp_match(" NOT REGEXP ", binary, operator, **kw)
  1601. def visit_regexp_replace_op_binary(self, binary, operator, **kw):
  1602. flags = binary.modifiers["flags"]
  1603. replacement = binary.modifiers["replacement"]
  1604. if flags is None:
  1605. return "REGEXP_REPLACE(%s, %s, %s)" % (
  1606. self.process(binary.left, **kw),
  1607. self.process(binary.right, **kw),
  1608. self.process(replacement, **kw),
  1609. )
  1610. elif self.dialect.is_mariadb:
  1611. return "REGEXP_REPLACE(%s, %s, %s)" % (
  1612. self.process(binary.left, **kw),
  1613. self._mariadb_regexp_flags(flags, binary.right),
  1614. self.process(replacement, **kw),
  1615. )
  1616. else:
  1617. return "REGEXP_REPLACE(%s, %s, %s, %s)" % (
  1618. self.process(binary.left, **kw),
  1619. self.process(binary.right, **kw),
  1620. self.process(replacement, **kw),
  1621. self.process(flags, **kw),
  1622. )
  1623. class MySQLDDLCompiler(compiler.DDLCompiler):
  1624. def get_column_specification(self, column, **kw):
  1625. """Builds column DDL."""
  1626. colspec = [
  1627. self.preparer.format_column(column),
  1628. self.dialect.type_compiler.process(
  1629. column.type, type_expression=column
  1630. ),
  1631. ]
  1632. if column.computed is not None:
  1633. colspec.append(self.process(column.computed))
  1634. is_timestamp = isinstance(
  1635. column.type._unwrapped_dialect_impl(self.dialect),
  1636. sqltypes.TIMESTAMP,
  1637. )
  1638. if not column.nullable:
  1639. colspec.append("NOT NULL")
  1640. # see: http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#mysql_timestamp_null # noqa
  1641. elif column.nullable and is_timestamp:
  1642. colspec.append("NULL")
  1643. comment = column.comment
  1644. if comment is not None:
  1645. literal = self.sql_compiler.render_literal_value(
  1646. comment, sqltypes.String()
  1647. )
  1648. colspec.append("COMMENT " + literal)
  1649. if (
  1650. column.table is not None
  1651. and column is column.table._autoincrement_column
  1652. and (
  1653. column.server_default is None
  1654. or isinstance(column.server_default, sa_schema.Identity)
  1655. )
  1656. and not (
  1657. self.dialect.supports_sequences
  1658. and isinstance(column.default, sa_schema.Sequence)
  1659. and not column.default.optional
  1660. )
  1661. ):
  1662. colspec.append("AUTO_INCREMENT")
  1663. else:
  1664. default = self.get_column_default_string(column)
  1665. if default is not None:
  1666. colspec.append("DEFAULT " + default)
  1667. return " ".join(colspec)
  1668. def post_create_table(self, table):
  1669. """Build table-level CREATE options like ENGINE and COLLATE."""
  1670. table_opts = []
  1671. opts = dict(
  1672. (k[len(self.dialect.name) + 1 :].upper(), v)
  1673. for k, v in table.kwargs.items()
  1674. if k.startswith("%s_" % self.dialect.name)
  1675. )
  1676. if table.comment is not None:
  1677. opts["COMMENT"] = table.comment
  1678. partition_options = [
  1679. "PARTITION_BY",
  1680. "PARTITIONS",
  1681. "SUBPARTITIONS",
  1682. "SUBPARTITION_BY",
  1683. ]
  1684. nonpart_options = set(opts).difference(partition_options)
  1685. part_options = set(opts).intersection(partition_options)
  1686. for opt in topological.sort(
  1687. [
  1688. ("DEFAULT_CHARSET", "COLLATE"),
  1689. ("DEFAULT_CHARACTER_SET", "COLLATE"),
  1690. ("CHARSET", "COLLATE"),
  1691. ("CHARACTER_SET", "COLLATE"),
  1692. ],
  1693. nonpart_options,
  1694. ):
  1695. arg = opts[opt]
  1696. if opt in _reflection._options_of_type_string:
  1697. arg = self.sql_compiler.render_literal_value(
  1698. arg, sqltypes.String()
  1699. )
  1700. if opt in (
  1701. "DATA_DIRECTORY",
  1702. "INDEX_DIRECTORY",
  1703. "DEFAULT_CHARACTER_SET",
  1704. "CHARACTER_SET",
  1705. "DEFAULT_CHARSET",
  1706. "DEFAULT_COLLATE",
  1707. ):
  1708. opt = opt.replace("_", " ")
  1709. joiner = "="
  1710. if opt in (
  1711. "TABLESPACE",
  1712. "DEFAULT CHARACTER SET",
  1713. "CHARACTER SET",
  1714. "COLLATE",
  1715. ):
  1716. joiner = " "
  1717. table_opts.append(joiner.join((opt, arg)))
  1718. for opt in topological.sort(
  1719. [
  1720. ("PARTITION_BY", "PARTITIONS"),
  1721. ("PARTITION_BY", "SUBPARTITION_BY"),
  1722. ("PARTITION_BY", "SUBPARTITIONS"),
  1723. ("PARTITIONS", "SUBPARTITIONS"),
  1724. ("PARTITIONS", "SUBPARTITION_BY"),
  1725. ("SUBPARTITION_BY", "SUBPARTITIONS"),
  1726. ],
  1727. part_options,
  1728. ):
  1729. arg = opts[opt]
  1730. if opt in _reflection._options_of_type_string:
  1731. arg = self.sql_compiler.render_literal_value(
  1732. arg, sqltypes.String()
  1733. )
  1734. opt = opt.replace("_", " ")
  1735. joiner = " "
  1736. table_opts.append(joiner.join((opt, arg)))
  1737. return " ".join(table_opts)
  1738. def visit_create_index(self, create, **kw):
  1739. index = create.element
  1740. self._verify_index_table(index)
  1741. preparer = self.preparer
  1742. table = preparer.format_table(index.table)
  1743. columns = [
  1744. self.sql_compiler.process(
  1745. elements.Grouping(expr)
  1746. if (
  1747. isinstance(expr, elements.BinaryExpression)
  1748. or (
  1749. isinstance(expr, elements.UnaryExpression)
  1750. and expr.modifier
  1751. not in (operators.desc_op, operators.asc_op)
  1752. )
  1753. or isinstance(expr, functions.FunctionElement)
  1754. )
  1755. else expr,
  1756. include_table=False,
  1757. literal_binds=True,
  1758. )
  1759. for expr in index.expressions
  1760. ]
  1761. name = self._prepared_index_name(index)
  1762. text = "CREATE "
  1763. if index.unique:
  1764. text += "UNIQUE "
  1765. index_prefix = index.kwargs.get("%s_prefix" % self.dialect.name, None)
  1766. if index_prefix:
  1767. text += index_prefix + " "
  1768. text += "INDEX "
  1769. if create.if_not_exists:
  1770. text += "IF NOT EXISTS "
  1771. text += "%s ON %s " % (name, table)
  1772. length = index.dialect_options[self.dialect.name]["length"]
  1773. if length is not None:
  1774. if isinstance(length, dict):
  1775. # length value can be a (column_name --> integer value)
  1776. # mapping specifying the prefix length for each column of the
  1777. # index
  1778. columns = ", ".join(
  1779. "%s(%d)" % (expr, length[col.name])
  1780. if col.name in length
  1781. else (
  1782. "%s(%d)" % (expr, length[expr])
  1783. if expr in length
  1784. else "%s" % expr
  1785. )
  1786. for col, expr in zip(index.expressions, columns)
  1787. )
  1788. else:
  1789. # or can be an integer value specifying the same
  1790. # prefix length for all columns of the index
  1791. columns = ", ".join(
  1792. "%s(%d)" % (col, length) for col in columns
  1793. )
  1794. else:
  1795. columns = ", ".join(columns)
  1796. text += "(%s)" % columns
  1797. parser = index.dialect_options["mysql"]["with_parser"]
  1798. if parser is not None:
  1799. text += " WITH PARSER %s" % (parser,)
  1800. using = index.dialect_options["mysql"]["using"]
  1801. if using is not None:
  1802. text += " USING %s" % (preparer.quote(using))
  1803. return text
  1804. def visit_primary_key_constraint(self, constraint):
  1805. text = super(MySQLDDLCompiler, self).visit_primary_key_constraint(
  1806. constraint
  1807. )
  1808. using = constraint.dialect_options["mysql"]["using"]
  1809. if using:
  1810. text += " USING %s" % (self.preparer.quote(using))
  1811. return text
  1812. def visit_drop_index(self, drop):
  1813. index = drop.element
  1814. text = "\nDROP INDEX "
  1815. if drop.if_exists:
  1816. text += "IF EXISTS "
  1817. return text + "%s ON %s" % (
  1818. self._prepared_index_name(index, include_schema=False),
  1819. self.preparer.format_table(index.table),
  1820. )
  1821. def visit_drop_constraint(self, drop):
  1822. constraint = drop.element
  1823. if isinstance(constraint, sa_schema.ForeignKeyConstraint):
  1824. qual = "FOREIGN KEY "
  1825. const = self.preparer.format_constraint(constraint)
  1826. elif isinstance(constraint, sa_schema.PrimaryKeyConstraint):
  1827. qual = "PRIMARY KEY "
  1828. const = ""
  1829. elif isinstance(constraint, sa_schema.UniqueConstraint):
  1830. qual = "INDEX "
  1831. const = self.preparer.format_constraint(constraint)
  1832. elif isinstance(constraint, sa_schema.CheckConstraint):
  1833. if self.dialect.is_mariadb:
  1834. qual = "CONSTRAINT "
  1835. else:
  1836. qual = "CHECK "
  1837. const = self.preparer.format_constraint(constraint)
  1838. else:
  1839. qual = ""
  1840. const = self.preparer.format_constraint(constraint)
  1841. return "ALTER TABLE %s DROP %s%s" % (
  1842. self.preparer.format_table(constraint.table),
  1843. qual,
  1844. const,
  1845. )
  1846. def define_constraint_match(self, constraint):
  1847. if constraint.match is not None:
  1848. raise exc.CompileError(
  1849. "MySQL ignores the 'MATCH' keyword while at the same time "
  1850. "causes ON UPDATE/ON DELETE clauses to be ignored."
  1851. )
  1852. return ""
  1853. def visit_set_table_comment(self, create):
  1854. return "ALTER TABLE %s COMMENT %s" % (
  1855. self.preparer.format_table(create.element),
  1856. self.sql_compiler.render_literal_value(
  1857. create.element.comment, sqltypes.String()
  1858. ),
  1859. )
  1860. def visit_drop_table_comment(self, create):
  1861. return "ALTER TABLE %s COMMENT ''" % (
  1862. self.preparer.format_table(create.element)
  1863. )
  1864. def visit_set_column_comment(self, create):
  1865. return "ALTER TABLE %s CHANGE %s %s" % (
  1866. self.preparer.format_table(create.element.table),
  1867. self.preparer.format_column(create.element),
  1868. self.get_column_specification(create.element),
  1869. )
  1870. class MySQLTypeCompiler(compiler.GenericTypeCompiler):
  1871. def _extend_numeric(self, type_, spec):
  1872. "Extend a numeric-type declaration with MySQL specific extensions."
  1873. if not self._mysql_type(type_):
  1874. return spec
  1875. if type_.unsigned:
  1876. spec += " UNSIGNED"
  1877. if type_.zerofill:
  1878. spec += " ZEROFILL"
  1879. return spec
  1880. def _extend_string(self, type_, defaults, spec):
  1881. """Extend a string-type declaration with standard SQL CHARACTER SET /
  1882. COLLATE annotations and MySQL specific extensions.
  1883. """
  1884. def attr(name):
  1885. return getattr(type_, name, defaults.get(name))
  1886. if attr("charset"):
  1887. charset = "CHARACTER SET %s" % attr("charset")
  1888. elif attr("ascii"):
  1889. charset = "ASCII"
  1890. elif attr("unicode"):
  1891. charset = "UNICODE"
  1892. else:
  1893. charset = None
  1894. if attr("collation"):
  1895. collation = "COLLATE %s" % type_.collation
  1896. elif attr("binary"):
  1897. collation = "BINARY"
  1898. else:
  1899. collation = None
  1900. if attr("national"):
  1901. # NATIONAL (aka NCHAR/NVARCHAR) trumps charsets.
  1902. return " ".join(
  1903. [c for c in ("NATIONAL", spec, collation) if c is not None]
  1904. )
  1905. return " ".join(
  1906. [c for c in (spec, charset, collation) if c is not None]
  1907. )
  1908. def _mysql_type(self, type_):
  1909. return isinstance(type_, (_StringType, _NumericType))
  1910. def visit_NUMERIC(self, type_, **kw):
  1911. if type_.precision is None:
  1912. return self._extend_numeric(type_, "NUMERIC")
  1913. elif type_.scale is None:
  1914. return self._extend_numeric(
  1915. type_,
  1916. "NUMERIC(%(precision)s)" % {"precision": type_.precision},
  1917. )
  1918. else:
  1919. return self._extend_numeric(
  1920. type_,
  1921. "NUMERIC(%(precision)s, %(scale)s)"
  1922. % {"precision": type_.precision, "scale": type_.scale},
  1923. )
  1924. def visit_DECIMAL(self, type_, **kw):
  1925. if type_.precision is None:
  1926. return self._extend_numeric(type_, "DECIMAL")
  1927. elif type_.scale is None:
  1928. return self._extend_numeric(
  1929. type_,
  1930. "DECIMAL(%(precision)s)" % {"precision": type_.precision},
  1931. )
  1932. else:
  1933. return self._extend_numeric(
  1934. type_,
  1935. "DECIMAL(%(precision)s, %(scale)s)"
  1936. % {"precision": type_.precision, "scale": type_.scale},
  1937. )
  1938. def visit_DOUBLE(self, type_, **kw):
  1939. if type_.precision is not None and type_.scale is not None:
  1940. return self._extend_numeric(
  1941. type_,
  1942. "DOUBLE(%(precision)s, %(scale)s)"
  1943. % {"precision": type_.precision, "scale": type_.scale},
  1944. )
  1945. else:
  1946. return self._extend_numeric(type_, "DOUBLE")
  1947. def visit_REAL(self, type_, **kw):
  1948. if type_.precision is not None and type_.scale is not None:
  1949. return self._extend_numeric(
  1950. type_,
  1951. "REAL(%(precision)s, %(scale)s)"
  1952. % {"precision": type_.precision, "scale": type_.scale},
  1953. )
  1954. else:
  1955. return self._extend_numeric(type_, "REAL")
  1956. def visit_FLOAT(self, type_, **kw):
  1957. if (
  1958. self._mysql_type(type_)
  1959. and type_.scale is not None
  1960. and type_.precision is not None
  1961. ):
  1962. return self._extend_numeric(
  1963. type_, "FLOAT(%s, %s)" % (type_.precision, type_.scale)
  1964. )
  1965. elif type_.precision is not None:
  1966. return self._extend_numeric(
  1967. type_, "FLOAT(%s)" % (type_.precision,)
  1968. )
  1969. else:
  1970. return self._extend_numeric(type_, "FLOAT")
  1971. def visit_INTEGER(self, type_, **kw):
  1972. if self._mysql_type(type_) and type_.display_width is not None:
  1973. return self._extend_numeric(
  1974. type_,
  1975. "INTEGER(%(display_width)s)"
  1976. % {"display_width": type_.display_width},
  1977. )
  1978. else:
  1979. return self._extend_numeric(type_, "INTEGER")
  1980. def visit_BIGINT(self, type_, **kw):
  1981. if self._mysql_type(type_) and type_.display_width is not None:
  1982. return self._extend_numeric(
  1983. type_,
  1984. "BIGINT(%(display_width)s)"
  1985. % {"display_width": type_.display_width},
  1986. )
  1987. else:
  1988. return self._extend_numeric(type_, "BIGINT")
  1989. def visit_MEDIUMINT(self, type_, **kw):
  1990. if self._mysql_type(type_) and type_.display_width is not None:
  1991. return self._extend_numeric(
  1992. type_,
  1993. "MEDIUMINT(%(display_width)s)"
  1994. % {"display_width": type_.display_width},
  1995. )
  1996. else:
  1997. return self._extend_numeric(type_, "MEDIUMINT")
  1998. def visit_TINYINT(self, type_, **kw):
  1999. if self._mysql_type(type_) and type_.display_width is not None:
  2000. return self._extend_numeric(
  2001. type_, "TINYINT(%s)" % type_.display_width
  2002. )
  2003. else:
  2004. return self._extend_numeric(type_, "TINYINT")
  2005. def visit_SMALLINT(self, type_, **kw):
  2006. if self._mysql_type(type_) and type_.display_width is not None:
  2007. return self._extend_numeric(
  2008. type_,
  2009. "SMALLINT(%(display_width)s)"
  2010. % {"display_width": type_.display_width},
  2011. )
  2012. else:
  2013. return self._extend_numeric(type_, "SMALLINT")
  2014. def visit_BIT(self, type_, **kw):
  2015. if type_.length is not None:
  2016. return "BIT(%s)" % type_.length
  2017. else:
  2018. return "BIT"
  2019. def visit_DATETIME(self, type_, **kw):
  2020. if getattr(type_, "fsp", None):
  2021. return "DATETIME(%d)" % type_.fsp
  2022. else:
  2023. return "DATETIME"
  2024. def visit_DATE(self, type_, **kw):
  2025. return "DATE"
  2026. def visit_TIME(self, type_, **kw):
  2027. if getattr(type_, "fsp", None):
  2028. return "TIME(%d)" % type_.fsp
  2029. else:
  2030. return "TIME"
  2031. def visit_TIMESTAMP(self, type_, **kw):
  2032. if getattr(type_, "fsp", None):
  2033. return "TIMESTAMP(%d)" % type_.fsp
  2034. else:
  2035. return "TIMESTAMP"
  2036. def visit_YEAR(self, type_, **kw):
  2037. if type_.display_width is None:
  2038. return "YEAR"
  2039. else:
  2040. return "YEAR(%s)" % type_.display_width
  2041. def visit_TEXT(self, type_, **kw):
  2042. if type_.length:
  2043. return self._extend_string(type_, {}, "TEXT(%d)" % type_.length)
  2044. else:
  2045. return self._extend_string(type_, {}, "TEXT")
  2046. def visit_TINYTEXT(self, type_, **kw):
  2047. return self._extend_string(type_, {}, "TINYTEXT")
  2048. def visit_MEDIUMTEXT(self, type_, **kw):
  2049. return self._extend_string(type_, {}, "MEDIUMTEXT")
  2050. def visit_LONGTEXT(self, type_, **kw):
  2051. return self._extend_string(type_, {}, "LONGTEXT")
  2052. def visit_VARCHAR(self, type_, **kw):
  2053. if type_.length:
  2054. return self._extend_string(type_, {}, "VARCHAR(%d)" % type_.length)
  2055. else:
  2056. raise exc.CompileError(
  2057. "VARCHAR requires a length on dialect %s" % self.dialect.name
  2058. )
  2059. def visit_CHAR(self, type_, **kw):
  2060. if type_.length:
  2061. return self._extend_string(
  2062. type_, {}, "CHAR(%(length)s)" % {"length": type_.length}
  2063. )
  2064. else:
  2065. return self._extend_string(type_, {}, "CHAR")
  2066. def visit_NVARCHAR(self, type_, **kw):
  2067. # We'll actually generate the equiv. "NATIONAL VARCHAR" instead
  2068. # of "NVARCHAR".
  2069. if type_.length:
  2070. return self._extend_string(
  2071. type_,
  2072. {"national": True},
  2073. "VARCHAR(%(length)s)" % {"length": type_.length},
  2074. )
  2075. else:
  2076. raise exc.CompileError(
  2077. "NVARCHAR requires a length on dialect %s" % self.dialect.name
  2078. )
  2079. def visit_NCHAR(self, type_, **kw):
  2080. # We'll actually generate the equiv.
  2081. # "NATIONAL CHAR" instead of "NCHAR".
  2082. if type_.length:
  2083. return self._extend_string(
  2084. type_,
  2085. {"national": True},
  2086. "CHAR(%(length)s)" % {"length": type_.length},
  2087. )
  2088. else:
  2089. return self._extend_string(type_, {"national": True}, "CHAR")
  2090. def visit_VARBINARY(self, type_, **kw):
  2091. return "VARBINARY(%d)" % type_.length
  2092. def visit_JSON(self, type_, **kw):
  2093. return "JSON"
  2094. def visit_large_binary(self, type_, **kw):
  2095. return self.visit_BLOB(type_)
  2096. def visit_enum(self, type_, **kw):
  2097. if not type_.native_enum:
  2098. return super(MySQLTypeCompiler, self).visit_enum(type_)
  2099. else:
  2100. return self._visit_enumerated_values("ENUM", type_, type_.enums)
  2101. def visit_BLOB(self, type_, **kw):
  2102. if type_.length:
  2103. return "BLOB(%d)" % type_.length
  2104. else:
  2105. return "BLOB"
  2106. def visit_TINYBLOB(self, type_, **kw):
  2107. return "TINYBLOB"
  2108. def visit_MEDIUMBLOB(self, type_, **kw):
  2109. return "MEDIUMBLOB"
  2110. def visit_LONGBLOB(self, type_, **kw):
  2111. return "LONGBLOB"
  2112. def _visit_enumerated_values(self, name, type_, enumerated_values):
  2113. quoted_enums = []
  2114. for e in enumerated_values:
  2115. quoted_enums.append("'%s'" % e.replace("'", "''"))
  2116. return self._extend_string(
  2117. type_, {}, "%s(%s)" % (name, ",".join(quoted_enums))
  2118. )
  2119. def visit_ENUM(self, type_, **kw):
  2120. return self._visit_enumerated_values("ENUM", type_, type_.enums)
  2121. def visit_SET(self, type_, **kw):
  2122. return self._visit_enumerated_values("SET", type_, type_.values)
  2123. def visit_BOOLEAN(self, type_, **kw):
  2124. return "BOOL"
  2125. class MySQLIdentifierPreparer(compiler.IdentifierPreparer):
  2126. reserved_words = RESERVED_WORDS
  2127. def __init__(self, dialect, server_ansiquotes=False, **kw):
  2128. if not server_ansiquotes:
  2129. quote = "`"
  2130. else:
  2131. quote = '"'
  2132. super(MySQLIdentifierPreparer, self).__init__(
  2133. dialect, initial_quote=quote, escape_quote=quote
  2134. )
  2135. def _quote_free_identifiers(self, *ids):
  2136. """Unilaterally identifier-quote any number of strings."""
  2137. return tuple([self.quote_identifier(i) for i in ids if i is not None])
  2138. @log.class_logger
  2139. class MySQLDialect(default.DefaultDialect):
  2140. """Details of the MySQL dialect.
  2141. Not used directly in application code.
  2142. """
  2143. name = "mysql"
  2144. supports_statement_cache = True
  2145. supports_alter = True
  2146. # MySQL has no true "boolean" type; we
  2147. # allow for the "true" and "false" keywords, however
  2148. supports_native_boolean = False
  2149. # identifiers are 64, however aliases can be 255...
  2150. max_identifier_length = 255
  2151. max_index_name_length = 64
  2152. max_constraint_name_length = 64
  2153. supports_native_enum = True
  2154. supports_sequences = False # default for MySQL ...
  2155. # ... may be updated to True for MariaDB 10.3+ in initialize()
  2156. sequences_optional = False
  2157. supports_for_update_of = False # default for MySQL ...
  2158. # ... may be updated to True for MySQL 8+ in initialize()
  2159. # MySQL doesn't support "DEFAULT VALUES" but *does* support
  2160. # "VALUES (DEFAULT)"
  2161. supports_default_values = False
  2162. supports_default_metavalue = True
  2163. supports_sane_rowcount = True
  2164. supports_sane_multi_rowcount = False
  2165. supports_multivalues_insert = True
  2166. supports_comments = True
  2167. inline_comments = True
  2168. default_paramstyle = "format"
  2169. colspecs = colspecs
  2170. cte_follows_insert = True
  2171. statement_compiler = MySQLCompiler
  2172. ddl_compiler = MySQLDDLCompiler
  2173. type_compiler = MySQLTypeCompiler
  2174. ischema_names = ischema_names
  2175. preparer = MySQLIdentifierPreparer
  2176. is_mariadb = False
  2177. _mariadb_normalized_version_info = None
  2178. # default SQL compilation settings -
  2179. # these are modified upon initialize(),
  2180. # i.e. first connect
  2181. _backslash_escapes = True
  2182. _server_ansiquotes = False
  2183. construct_arguments = [
  2184. (sa_schema.Table, {"*": None}),
  2185. (sql.Update, {"limit": None}),
  2186. (sa_schema.PrimaryKeyConstraint, {"using": None}),
  2187. (
  2188. sa_schema.Index,
  2189. {
  2190. "using": None,
  2191. "length": None,
  2192. "prefix": None,
  2193. "with_parser": None,
  2194. },
  2195. ),
  2196. ]
  2197. def __init__(
  2198. self,
  2199. isolation_level=None,
  2200. json_serializer=None,
  2201. json_deserializer=None,
  2202. is_mariadb=None,
  2203. **kwargs
  2204. ):
  2205. kwargs.pop("use_ansiquotes", None) # legacy
  2206. default.DefaultDialect.__init__(self, **kwargs)
  2207. self.isolation_level = isolation_level
  2208. self._json_serializer = json_serializer
  2209. self._json_deserializer = json_deserializer
  2210. self._set_mariadb(is_mariadb, None)
  2211. def on_connect(self):
  2212. if self.isolation_level is not None:
  2213. def connect(conn):
  2214. self.set_isolation_level(conn, self.isolation_level)
  2215. return connect
  2216. else:
  2217. return None
  2218. _isolation_lookup = set(
  2219. [
  2220. "SERIALIZABLE",
  2221. "READ UNCOMMITTED",
  2222. "READ COMMITTED",
  2223. "REPEATABLE READ",
  2224. ]
  2225. )
  2226. def set_isolation_level(self, connection, level):
  2227. level = level.replace("_", " ")
  2228. # adjust for ConnectionFairy being present
  2229. # allows attribute set e.g. "connection.autocommit = True"
  2230. # to work properly
  2231. if hasattr(connection, "connection"):
  2232. connection = connection.connection
  2233. self._set_isolation_level(connection, level)
  2234. def _set_isolation_level(self, connection, level):
  2235. if level not in self._isolation_lookup:
  2236. raise exc.ArgumentError(
  2237. "Invalid value '%s' for isolation_level. "
  2238. "Valid isolation levels for %s are %s"
  2239. % (level, self.name, ", ".join(self._isolation_lookup))
  2240. )
  2241. cursor = connection.cursor()
  2242. cursor.execute("SET SESSION TRANSACTION ISOLATION LEVEL %s" % level)
  2243. cursor.execute("COMMIT")
  2244. cursor.close()
  2245. def get_isolation_level(self, connection):
  2246. cursor = connection.cursor()
  2247. if self._is_mysql and self.server_version_info >= (5, 7, 20):
  2248. cursor.execute("SELECT @@transaction_isolation")
  2249. else:
  2250. cursor.execute("SELECT @@tx_isolation")
  2251. row = cursor.fetchone()
  2252. if row is None:
  2253. util.warn(
  2254. "Could not retrieve transaction isolation level for MySQL "
  2255. "connection."
  2256. )
  2257. raise NotImplementedError()
  2258. val = row[0]
  2259. cursor.close()
  2260. if util.py3k and isinstance(val, bytes):
  2261. val = val.decode()
  2262. return val.upper().replace("-", " ")
  2263. @classmethod
  2264. def _is_mariadb_from_url(cls, url):
  2265. dbapi = cls.dbapi()
  2266. dialect = cls(dbapi=dbapi)
  2267. cargs, cparams = dialect.create_connect_args(url)
  2268. conn = dialect.connect(*cargs, **cparams)
  2269. try:
  2270. cursor = conn.cursor()
  2271. cursor.execute("SELECT VERSION() LIKE '%MariaDB%'")
  2272. val = cursor.fetchone()[0]
  2273. except:
  2274. raise
  2275. else:
  2276. return bool(val)
  2277. finally:
  2278. conn.close()
  2279. def _get_server_version_info(self, connection):
  2280. # get database server version info explicitly over the wire
  2281. # to avoid proxy servers like MaxScale getting in the
  2282. # way with their own values, see #4205
  2283. dbapi_con = connection.connection
  2284. cursor = dbapi_con.cursor()
  2285. cursor.execute("SELECT VERSION()")
  2286. val = cursor.fetchone()[0]
  2287. cursor.close()
  2288. if util.py3k and isinstance(val, bytes):
  2289. val = val.decode()
  2290. return self._parse_server_version(val)
  2291. def _parse_server_version(self, val):
  2292. version = []
  2293. is_mariadb = False
  2294. r = re.compile(r"[.\-+]")
  2295. tokens = r.split(val)
  2296. for token in tokens:
  2297. parsed_token = re.match(
  2298. r"^(?:(\d+)(?:a|b|c)?|(MariaDB\w*))$", token
  2299. )
  2300. if not parsed_token:
  2301. continue
  2302. elif parsed_token.group(2):
  2303. self._mariadb_normalized_version_info = tuple(version[-3:])
  2304. is_mariadb = True
  2305. else:
  2306. digit = int(parsed_token.group(1))
  2307. version.append(digit)
  2308. server_version_info = tuple(version)
  2309. self._set_mariadb(server_version_info and is_mariadb, val)
  2310. if not is_mariadb:
  2311. self._mariadb_normalized_version_info = server_version_info
  2312. if server_version_info < (5, 0, 2):
  2313. raise NotImplementedError(
  2314. "the MySQL/MariaDB dialect supports server "
  2315. "version info 5.0.2 and above."
  2316. )
  2317. # setting it here to help w the test suite
  2318. self.server_version_info = server_version_info
  2319. return server_version_info
  2320. def _set_mariadb(self, is_mariadb, server_version_info):
  2321. if is_mariadb is None:
  2322. return
  2323. if not is_mariadb and self.is_mariadb:
  2324. raise exc.InvalidRequestError(
  2325. "MySQL version %s is not a MariaDB variant."
  2326. % (server_version_info,)
  2327. )
  2328. self.is_mariadb = is_mariadb
  2329. def do_begin_twophase(self, connection, xid):
  2330. connection.execute(sql.text("XA BEGIN :xid"), dict(xid=xid))
  2331. def do_prepare_twophase(self, connection, xid):
  2332. connection.execute(sql.text("XA END :xid"), dict(xid=xid))
  2333. connection.execute(sql.text("XA PREPARE :xid"), dict(xid=xid))
  2334. def do_rollback_twophase(
  2335. self, connection, xid, is_prepared=True, recover=False
  2336. ):
  2337. if not is_prepared:
  2338. connection.execute(sql.text("XA END :xid"), dict(xid=xid))
  2339. connection.execute(sql.text("XA ROLLBACK :xid"), dict(xid=xid))
  2340. def do_commit_twophase(
  2341. self, connection, xid, is_prepared=True, recover=False
  2342. ):
  2343. if not is_prepared:
  2344. self.do_prepare_twophase(connection, xid)
  2345. connection.execute(sql.text("XA COMMIT :xid"), dict(xid=xid))
  2346. def do_recover_twophase(self, connection):
  2347. resultset = connection.exec_driver_sql("XA RECOVER")
  2348. return [row["data"][0 : row["gtrid_length"]] for row in resultset]
  2349. def is_disconnect(self, e, connection, cursor):
  2350. if isinstance(
  2351. e, (self.dbapi.OperationalError, self.dbapi.ProgrammingError)
  2352. ):
  2353. return self._extract_error_code(e) in (
  2354. 1927,
  2355. 2006,
  2356. 2013,
  2357. 2014,
  2358. 2045,
  2359. 2055,
  2360. )
  2361. elif isinstance(
  2362. e, (self.dbapi.InterfaceError, self.dbapi.InternalError)
  2363. ):
  2364. # if underlying connection is closed,
  2365. # this is the error you get
  2366. return "(0, '')" in str(e)
  2367. else:
  2368. return False
  2369. def _compat_fetchall(self, rp, charset=None):
  2370. """Proxy result rows to smooth over MySQL-Python driver
  2371. inconsistencies."""
  2372. return [_DecodingRow(row, charset) for row in rp.fetchall()]
  2373. def _compat_fetchone(self, rp, charset=None):
  2374. """Proxy a result row to smooth over MySQL-Python driver
  2375. inconsistencies."""
  2376. row = rp.fetchone()
  2377. if row:
  2378. return _DecodingRow(row, charset)
  2379. else:
  2380. return None
  2381. def _compat_first(self, rp, charset=None):
  2382. """Proxy a result row to smooth over MySQL-Python driver
  2383. inconsistencies."""
  2384. row = rp.first()
  2385. if row:
  2386. return _DecodingRow(row, charset)
  2387. else:
  2388. return None
  2389. def _extract_error_code(self, exception):
  2390. raise NotImplementedError()
  2391. def _get_default_schema_name(self, connection):
  2392. return connection.exec_driver_sql("SELECT DATABASE()").scalar()
  2393. def has_table(self, connection, table_name, schema=None):
  2394. self._ensure_has_table_connection(connection)
  2395. if schema is None:
  2396. schema = self.default_schema_name
  2397. rs = connection.execute(
  2398. text(
  2399. "SELECT COUNT(*) FROM information_schema.tables WHERE "
  2400. "table_schema = :table_schema AND "
  2401. "table_name = :table_name"
  2402. ).bindparams(
  2403. sql.bindparam("table_schema", type_=Unicode),
  2404. sql.bindparam("table_name", type_=Unicode),
  2405. ),
  2406. {
  2407. "table_schema": util.text_type(schema),
  2408. "table_name": util.text_type(table_name),
  2409. },
  2410. )
  2411. return bool(rs.scalar())
  2412. def has_sequence(self, connection, sequence_name, schema=None):
  2413. if not self.supports_sequences:
  2414. self._sequences_not_supported()
  2415. if not schema:
  2416. schema = self.default_schema_name
  2417. # MariaDB implements sequences as a special type of table
  2418. #
  2419. cursor = connection.execute(
  2420. sql.text(
  2421. "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
  2422. "WHERE TABLE_TYPE='SEQUENCE' and TABLE_NAME=:name AND "
  2423. "TABLE_SCHEMA=:schema_name"
  2424. ),
  2425. dict(name=sequence_name, schema_name=schema),
  2426. )
  2427. return cursor.first() is not None
  2428. def _sequences_not_supported(self):
  2429. raise NotImplementedError(
  2430. "Sequences are supported only by the "
  2431. "MariaDB series 10.3 or greater"
  2432. )
  2433. @reflection.cache
  2434. def get_sequence_names(self, connection, schema=None, **kw):
  2435. if not self.supports_sequences:
  2436. self._sequences_not_supported()
  2437. if not schema:
  2438. schema = self.default_schema_name
  2439. # MariaDB implements sequences as a special type of table
  2440. cursor = connection.execute(
  2441. sql.text(
  2442. "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES "
  2443. "WHERE TABLE_TYPE='SEQUENCE' and TABLE_SCHEMA=:schema_name"
  2444. ),
  2445. dict(schema_name=schema),
  2446. )
  2447. return [
  2448. row[0]
  2449. for row in self._compat_fetchall(
  2450. cursor, charset=self._connection_charset
  2451. )
  2452. ]
  2453. def initialize(self, connection):
  2454. self._connection_charset = self._detect_charset(connection)
  2455. self._detect_sql_mode(connection)
  2456. self._detect_ansiquotes(connection)
  2457. self._detect_casing(connection)
  2458. if self._server_ansiquotes:
  2459. # if ansiquotes == True, build a new IdentifierPreparer
  2460. # with the new setting
  2461. self.identifier_preparer = self.preparer(
  2462. self, server_ansiquotes=self._server_ansiquotes
  2463. )
  2464. default.DefaultDialect.initialize(self, connection)
  2465. self.supports_sequences = (
  2466. self.is_mariadb and self.server_version_info >= (10, 3)
  2467. )
  2468. self.supports_for_update_of = (
  2469. self._is_mysql and self.server_version_info >= (8,)
  2470. )
  2471. self._needs_correct_for_88718_96365 = (
  2472. not self.is_mariadb and self.server_version_info >= (8,)
  2473. )
  2474. self._warn_for_known_db_issues()
  2475. def _warn_for_known_db_issues(self):
  2476. if self.is_mariadb:
  2477. mdb_version = self._mariadb_normalized_version_info
  2478. if mdb_version > (10, 2) and mdb_version < (10, 2, 9):
  2479. util.warn(
  2480. "MariaDB %r before 10.2.9 has known issues regarding "
  2481. "CHECK constraints, which impact handling of NULL values "
  2482. "with SQLAlchemy's boolean datatype (MDEV-13596). An "
  2483. "additional issue prevents proper migrations of columns "
  2484. "with CHECK constraints (MDEV-11114). Please upgrade to "
  2485. "MariaDB 10.2.9 or greater, or use the MariaDB 10.1 "
  2486. "series, to avoid these issues." % (mdb_version,)
  2487. )
  2488. @property
  2489. def _support_float_cast(self):
  2490. if not self.server_version_info:
  2491. return False
  2492. elif self.is_mariadb:
  2493. # ref https://mariadb.com/kb/en/mariadb-1045-release-notes/
  2494. return self.server_version_info >= (10, 4, 5)
  2495. else:
  2496. # ref https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-17.html#mysqld-8-0-17-feature # noqa
  2497. return self.server_version_info >= (8, 0, 17)
  2498. @property
  2499. def _is_mariadb(self):
  2500. return self.is_mariadb
  2501. @property
  2502. def _is_mysql(self):
  2503. return not self.is_mariadb
  2504. @property
  2505. def _is_mariadb_102(self):
  2506. return self.is_mariadb and self._mariadb_normalized_version_info > (
  2507. 10,
  2508. 2,
  2509. )
  2510. @reflection.cache
  2511. def get_schema_names(self, connection, **kw):
  2512. rp = connection.exec_driver_sql("SHOW schemas")
  2513. return [r[0] for r in rp]
  2514. @reflection.cache
  2515. def get_table_names(self, connection, schema=None, **kw):
  2516. """Return a Unicode SHOW TABLES from a given schema."""
  2517. if schema is not None:
  2518. current_schema = schema
  2519. else:
  2520. current_schema = self.default_schema_name
  2521. charset = self._connection_charset
  2522. rp = connection.exec_driver_sql(
  2523. "SHOW FULL TABLES FROM %s"
  2524. % self.identifier_preparer.quote_identifier(current_schema)
  2525. )
  2526. return [
  2527. row[0]
  2528. for row in self._compat_fetchall(rp, charset=charset)
  2529. if row[1] == "BASE TABLE"
  2530. ]
  2531. @reflection.cache
  2532. def get_view_names(self, connection, schema=None, **kw):
  2533. if schema is None:
  2534. schema = self.default_schema_name
  2535. charset = self._connection_charset
  2536. rp = connection.exec_driver_sql(
  2537. "SHOW FULL TABLES FROM %s"
  2538. % self.identifier_preparer.quote_identifier(schema)
  2539. )
  2540. return [
  2541. row[0]
  2542. for row in self._compat_fetchall(rp, charset=charset)
  2543. if row[1] in ("VIEW", "SYSTEM VIEW")
  2544. ]
  2545. @reflection.cache
  2546. def get_table_options(self, connection, table_name, schema=None, **kw):
  2547. parsed_state = self._parsed_state_or_create(
  2548. connection, table_name, schema, **kw
  2549. )
  2550. return parsed_state.table_options
  2551. @reflection.cache
  2552. def get_columns(self, connection, table_name, schema=None, **kw):
  2553. parsed_state = self._parsed_state_or_create(
  2554. connection, table_name, schema, **kw
  2555. )
  2556. return parsed_state.columns
  2557. @reflection.cache
  2558. def get_pk_constraint(self, connection, table_name, schema=None, **kw):
  2559. parsed_state = self._parsed_state_or_create(
  2560. connection, table_name, schema, **kw
  2561. )
  2562. for key in parsed_state.keys:
  2563. if key["type"] == "PRIMARY":
  2564. # There can be only one.
  2565. cols = [s[0] for s in key["columns"]]
  2566. return {"constrained_columns": cols, "name": None}
  2567. return {"constrained_columns": [], "name": None}
  2568. @reflection.cache
  2569. def get_foreign_keys(self, connection, table_name, schema=None, **kw):
  2570. parsed_state = self._parsed_state_or_create(
  2571. connection, table_name, schema, **kw
  2572. )
  2573. default_schema = None
  2574. fkeys = []
  2575. for spec in parsed_state.fk_constraints:
  2576. ref_name = spec["table"][-1]
  2577. ref_schema = len(spec["table"]) > 1 and spec["table"][-2] or schema
  2578. if not ref_schema:
  2579. if default_schema is None:
  2580. default_schema = connection.dialect.default_schema_name
  2581. if schema == default_schema:
  2582. ref_schema = schema
  2583. loc_names = spec["local"]
  2584. ref_names = spec["foreign"]
  2585. con_kw = {}
  2586. for opt in ("onupdate", "ondelete"):
  2587. if spec.get(opt, False) not in ("NO ACTION", None):
  2588. con_kw[opt] = spec[opt]
  2589. fkey_d = {
  2590. "name": spec["name"],
  2591. "constrained_columns": loc_names,
  2592. "referred_schema": ref_schema,
  2593. "referred_table": ref_name,
  2594. "referred_columns": ref_names,
  2595. "options": con_kw,
  2596. }
  2597. fkeys.append(fkey_d)
  2598. if self._needs_correct_for_88718_96365:
  2599. self._correct_for_mysql_bugs_88718_96365(fkeys, connection)
  2600. return fkeys
  2601. def _correct_for_mysql_bugs_88718_96365(self, fkeys, connection):
  2602. # Foreign key is always in lower case (MySQL 8.0)
  2603. # https://bugs.mysql.com/bug.php?id=88718
  2604. # issue #4344 for SQLAlchemy
  2605. # table name also for MySQL 8.0
  2606. # https://bugs.mysql.com/bug.php?id=96365
  2607. # issue #4751 for SQLAlchemy
  2608. # for lower_case_table_names=2, information_schema.columns
  2609. # preserves the original table/schema casing, but SHOW CREATE
  2610. # TABLE does not. this problem is not in lower_case_table_names=1,
  2611. # but use case-insensitive matching for these two modes in any case.
  2612. if self._casing in (1, 2):
  2613. def lower(s):
  2614. return s.lower()
  2615. else:
  2616. # if on case sensitive, there can be two tables referenced
  2617. # with the same name different casing, so we need to use
  2618. # case-sensitive matching.
  2619. def lower(s):
  2620. return s
  2621. default_schema_name = connection.dialect.default_schema_name
  2622. col_tuples = [
  2623. (
  2624. lower(rec["referred_schema"] or default_schema_name),
  2625. lower(rec["referred_table"]),
  2626. col_name,
  2627. )
  2628. for rec in fkeys
  2629. for col_name in rec["referred_columns"]
  2630. ]
  2631. if col_tuples:
  2632. correct_for_wrong_fk_case = connection.execute(
  2633. sql.text(
  2634. """
  2635. select table_schema, table_name, column_name
  2636. from information_schema.columns
  2637. where (table_schema, table_name, lower(column_name)) in
  2638. :table_data;
  2639. """
  2640. ).bindparams(sql.bindparam("table_data", expanding=True)),
  2641. dict(table_data=col_tuples),
  2642. )
  2643. # in casing=0, table name and schema name come back in their
  2644. # exact case.
  2645. # in casing=1, table name and schema name come back in lower
  2646. # case.
  2647. # in casing=2, table name and schema name come back from the
  2648. # information_schema.columns view in the case
  2649. # that was used in CREATE DATABASE and CREATE TABLE, but
  2650. # SHOW CREATE TABLE converts them to *lower case*, therefore
  2651. # not matching. So for this case, case-insensitive lookup
  2652. # is necessary
  2653. d = defaultdict(dict)
  2654. for schema, tname, cname in correct_for_wrong_fk_case:
  2655. d[(lower(schema), lower(tname))]["SCHEMANAME"] = schema
  2656. d[(lower(schema), lower(tname))]["TABLENAME"] = tname
  2657. d[(lower(schema), lower(tname))][cname.lower()] = cname
  2658. for fkey in fkeys:
  2659. rec = d[
  2660. (
  2661. lower(fkey["referred_schema"] or default_schema_name),
  2662. lower(fkey["referred_table"]),
  2663. )
  2664. ]
  2665. fkey["referred_table"] = rec["TABLENAME"]
  2666. if fkey["referred_schema"] is not None:
  2667. fkey["referred_schema"] = rec["SCHEMANAME"]
  2668. fkey["referred_columns"] = [
  2669. rec[col.lower()] for col in fkey["referred_columns"]
  2670. ]
  2671. @reflection.cache
  2672. def get_check_constraints(self, connection, table_name, schema=None, **kw):
  2673. parsed_state = self._parsed_state_or_create(
  2674. connection, table_name, schema, **kw
  2675. )
  2676. return [
  2677. {"name": spec["name"], "sqltext": spec["sqltext"]}
  2678. for spec in parsed_state.ck_constraints
  2679. ]
  2680. @reflection.cache
  2681. def get_table_comment(self, connection, table_name, schema=None, **kw):
  2682. parsed_state = self._parsed_state_or_create(
  2683. connection, table_name, schema, **kw
  2684. )
  2685. return {
  2686. "text": parsed_state.table_options.get(
  2687. "%s_comment" % self.name, None
  2688. )
  2689. }
  2690. @reflection.cache
  2691. def get_indexes(self, connection, table_name, schema=None, **kw):
  2692. parsed_state = self._parsed_state_or_create(
  2693. connection, table_name, schema, **kw
  2694. )
  2695. indexes = []
  2696. for spec in parsed_state.keys:
  2697. dialect_options = {}
  2698. unique = False
  2699. flavor = spec["type"]
  2700. if flavor == "PRIMARY":
  2701. continue
  2702. if flavor == "UNIQUE":
  2703. unique = True
  2704. elif flavor in ("FULLTEXT", "SPATIAL"):
  2705. dialect_options["%s_prefix" % self.name] = flavor
  2706. elif flavor is None:
  2707. pass
  2708. else:
  2709. self.logger.info(
  2710. "Converting unknown KEY type %s to a plain KEY", flavor
  2711. )
  2712. pass
  2713. if spec["parser"]:
  2714. dialect_options["%s_with_parser" % (self.name)] = spec[
  2715. "parser"
  2716. ]
  2717. index_d = {}
  2718. if dialect_options:
  2719. index_d["dialect_options"] = dialect_options
  2720. index_d["name"] = spec["name"]
  2721. index_d["column_names"] = [s[0] for s in spec["columns"]]
  2722. index_d["unique"] = unique
  2723. if flavor:
  2724. index_d["type"] = flavor
  2725. indexes.append(index_d)
  2726. return indexes
  2727. @reflection.cache
  2728. def get_unique_constraints(
  2729. self, connection, table_name, schema=None, **kw
  2730. ):
  2731. parsed_state = self._parsed_state_or_create(
  2732. connection, table_name, schema, **kw
  2733. )
  2734. return [
  2735. {
  2736. "name": key["name"],
  2737. "column_names": [col[0] for col in key["columns"]],
  2738. "duplicates_index": key["name"],
  2739. }
  2740. for key in parsed_state.keys
  2741. if key["type"] == "UNIQUE"
  2742. ]
  2743. @reflection.cache
  2744. def get_view_definition(self, connection, view_name, schema=None, **kw):
  2745. charset = self._connection_charset
  2746. full_name = ".".join(
  2747. self.identifier_preparer._quote_free_identifiers(schema, view_name)
  2748. )
  2749. sql = self._show_create_table(
  2750. connection, None, charset, full_name=full_name
  2751. )
  2752. return sql
  2753. def _parsed_state_or_create(
  2754. self, connection, table_name, schema=None, **kw
  2755. ):
  2756. return self._setup_parser(
  2757. connection,
  2758. table_name,
  2759. schema,
  2760. info_cache=kw.get("info_cache", None),
  2761. )
  2762. @util.memoized_property
  2763. def _tabledef_parser(self):
  2764. """return the MySQLTableDefinitionParser, generate if needed.
  2765. The deferred creation ensures that the dialect has
  2766. retrieved server version information first.
  2767. """
  2768. preparer = self.identifier_preparer
  2769. return _reflection.MySQLTableDefinitionParser(self, preparer)
  2770. @reflection.cache
  2771. def _setup_parser(self, connection, table_name, schema=None, **kw):
  2772. charset = self._connection_charset
  2773. parser = self._tabledef_parser
  2774. full_name = ".".join(
  2775. self.identifier_preparer._quote_free_identifiers(
  2776. schema, table_name
  2777. )
  2778. )
  2779. sql = self._show_create_table(
  2780. connection, None, charset, full_name=full_name
  2781. )
  2782. if re.match(r"^CREATE (?:ALGORITHM)?.* VIEW", sql):
  2783. # Adapt views to something table-like.
  2784. columns = self._describe_table(
  2785. connection, None, charset, full_name=full_name
  2786. )
  2787. sql = parser._describe_to_create(table_name, columns)
  2788. return parser.parse(sql, charset)
  2789. def _detect_charset(self, connection):
  2790. raise NotImplementedError()
  2791. def _detect_casing(self, connection):
  2792. """Sniff out identifier case sensitivity.
  2793. Cached per-connection. This value can not change without a server
  2794. restart.
  2795. """
  2796. # http://dev.mysql.com/doc/refman/5.0/en/name-case-sensitivity.html
  2797. charset = self._connection_charset
  2798. row = self._compat_first(
  2799. connection.execute(
  2800. sql.text("SHOW VARIABLES LIKE 'lower_case_table_names'")
  2801. ),
  2802. charset=charset,
  2803. )
  2804. if not row:
  2805. cs = 0
  2806. else:
  2807. # 4.0.15 returns OFF or ON according to [ticket:489]
  2808. # 3.23 doesn't, 4.0.27 doesn't..
  2809. if row[1] == "OFF":
  2810. cs = 0
  2811. elif row[1] == "ON":
  2812. cs = 1
  2813. else:
  2814. cs = int(row[1])
  2815. self._casing = cs
  2816. return cs
  2817. def _detect_collations(self, connection):
  2818. """Pull the active COLLATIONS list from the server.
  2819. Cached per-connection.
  2820. """
  2821. collations = {}
  2822. charset = self._connection_charset
  2823. rs = connection.exec_driver_sql("SHOW COLLATION")
  2824. for row in self._compat_fetchall(rs, charset):
  2825. collations[row[0]] = row[1]
  2826. return collations
  2827. def _detect_sql_mode(self, connection):
  2828. row = self._compat_first(
  2829. connection.exec_driver_sql("SHOW VARIABLES LIKE 'sql_mode'"),
  2830. charset=self._connection_charset,
  2831. )
  2832. if not row:
  2833. util.warn(
  2834. "Could not retrieve SQL_MODE; please ensure the "
  2835. "MySQL user has permissions to SHOW VARIABLES"
  2836. )
  2837. self._sql_mode = ""
  2838. else:
  2839. self._sql_mode = row[1] or ""
  2840. def _detect_ansiquotes(self, connection):
  2841. """Detect and adjust for the ANSI_QUOTES sql mode."""
  2842. mode = self._sql_mode
  2843. if not mode:
  2844. mode = ""
  2845. elif mode.isdigit():
  2846. mode_no = int(mode)
  2847. mode = (mode_no | 4 == mode_no) and "ANSI_QUOTES" or ""
  2848. self._server_ansiquotes = "ANSI_QUOTES" in mode
  2849. # as of MySQL 5.0.1
  2850. self._backslash_escapes = "NO_BACKSLASH_ESCAPES" not in mode
  2851. def _show_create_table(
  2852. self, connection, table, charset=None, full_name=None
  2853. ):
  2854. """Run SHOW CREATE TABLE for a ``Table``."""
  2855. if full_name is None:
  2856. full_name = self.identifier_preparer.format_table(table)
  2857. st = "SHOW CREATE TABLE %s" % full_name
  2858. rp = None
  2859. try:
  2860. rp = connection.execution_options(
  2861. skip_user_error_events=True
  2862. ).exec_driver_sql(st)
  2863. except exc.DBAPIError as e:
  2864. if self._extract_error_code(e.orig) == 1146:
  2865. util.raise_(exc.NoSuchTableError(full_name), replace_context=e)
  2866. else:
  2867. raise
  2868. row = self._compat_first(rp, charset=charset)
  2869. if not row:
  2870. raise exc.NoSuchTableError(full_name)
  2871. return row[1].strip()
  2872. def _describe_table(self, connection, table, charset=None, full_name=None):
  2873. """Run DESCRIBE for a ``Table`` and return processed rows."""
  2874. if full_name is None:
  2875. full_name = self.identifier_preparer.format_table(table)
  2876. st = "DESCRIBE %s" % full_name
  2877. rp, rows = None, None
  2878. try:
  2879. try:
  2880. rp = connection.execution_options(
  2881. skip_user_error_events=True
  2882. ).exec_driver_sql(st)
  2883. except exc.DBAPIError as e:
  2884. code = self._extract_error_code(e.orig)
  2885. if code == 1146:
  2886. util.raise_(
  2887. exc.NoSuchTableError(full_name), replace_context=e
  2888. )
  2889. elif code == 1356:
  2890. util.raise_(
  2891. exc.UnreflectableTableError(
  2892. "Table or view named %s could not be "
  2893. "reflected: %s" % (full_name, e)
  2894. ),
  2895. replace_context=e,
  2896. )
  2897. else:
  2898. raise
  2899. rows = self._compat_fetchall(rp, charset=charset)
  2900. finally:
  2901. if rp:
  2902. rp.close()
  2903. return rows
  2904. class _DecodingRow(object):
  2905. """Return unicode-decoded values based on type inspection.
  2906. Smooth over data type issues (esp. with alpha driver versions) and
  2907. normalize strings as Unicode regardless of user-configured driver
  2908. encoding settings.
  2909. """
  2910. # Some MySQL-python versions can return some columns as
  2911. # sets.Set(['value']) (seriously) but thankfully that doesn't
  2912. # seem to come up in DDL queries.
  2913. _encoding_compat = {
  2914. "koi8r": "koi8_r",
  2915. "koi8u": "koi8_u",
  2916. "utf16": "utf-16-be", # MySQL's uft16 is always bigendian
  2917. "utf8mb4": "utf8", # real utf8
  2918. "eucjpms": "ujis",
  2919. }
  2920. def __init__(self, rowproxy, charset):
  2921. self.rowproxy = rowproxy
  2922. self.charset = self._encoding_compat.get(charset, charset)
  2923. def __getitem__(self, index):
  2924. item = self.rowproxy[index]
  2925. if isinstance(item, _array):
  2926. item = item.tostring()
  2927. if self.charset and isinstance(item, util.binary_type):
  2928. return item.decode(self.charset)
  2929. else:
  2930. return item
  2931. def __getattr__(self, attr):
  2932. item = getattr(self.rowproxy, attr)
  2933. if isinstance(item, _array):
  2934. item = item.tostring()
  2935. if self.charset and isinstance(item, util.binary_type):
  2936. return item.decode(self.charset)
  2937. else:
  2938. return item