o
    g(                    @  s  d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	Z	ddl
mZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddlm"Z" ddlm#Z# ddlm$Z$ ddlm%Z% ddlm&Z& ddlm'Z' ddlm(Z( dd lm)Z) dd!lm*Z* dd"lm+Z+ dd#lm,Z, dd$lm-Z- dd%lm.Z. dd&lm/Z/ dd'lm0Z0 dd(lm1Z1 dd)lm2Z2 dd*lm3Z3 dd+lm4Z4 dd,lm5Z5 dd-lm6Z6 dd.lm7Z7 dd/lm8Z8 d0d1lm9Z9 d0d2lm:Z: d0d3lm;Z; d0d4lm<Z= d0d5lm>Z> d0d6lm?Z? d0d7l@mAZB d0d8l@mCZC d0d	l@mZ d0d9lDmEZE d0d:l>mFZF d0d;l>mGZG d0d<l>mHZH d0d=l>mIZI d0d>l>mJZJ d0d?l>mKZK d0d@l>mLZL d0d6l>m?ZM d0dAl>mNZN d0dBlOmPZP d0dClOmQZQ d0dDlRmSZS d0dElmTZT d0dFlmUZU d0dGlmVZV d0dHlmWZW d0dIlmXZX d0dJlmYZY d0dKl?mZZZ e	[dLe	j\e	j]B Z^e2Z_eZ`eZae'Zbe)Zce4ZdeUZeeTZfeYZge,Zhe.Zie!Zje7Zke(Zle+Zme6Zne1Zoe8Zpe3Zqe Zre0Zse5Zte*ZueZve-Zwe#Zxe$Zye/Zze%Z{e&Z|eeeeeeeLj}e-eLj~e%eLje$eLje2eLjeeLjeeLjeeLjjeeLjjeiZi dMedNeTdOe dPeUdQeVdRe!dSeWdTe"dUe#dVe$dWedXe#dYe%dZe&d[e&d\ed]e'i d^e(d_e)d`e*dae+dbe,dce.dde-deedfe0dge1dhe2die3dje4dke5dle6dmeXdneYe7e8doZG dpdq dqeCjZG drds dseGjQZG dtdu dueGjZG dvdw dweGjZG dxdy dyeGjZG dzd{ d{eZe;jG d|d} d}eCjZG d~d dZe>jde>de7de>de7de>de7ddd4ZdS )an  

.. dialect:: mysql
    :name: MySQL / MariaDB
    :normal_support: 5.6+ / 10+
    :best_effort: 5.0.2+ / 5.0.2+

Supported Versions and Features
-------------------------------

SQLAlchemy supports MySQL starting with version 5.0.2 through modern releases,
as well as all modern versions of MariaDB.   See the official MySQL
documentation for detailed information about features supported in any given
server release.

.. versionchanged:: 1.4  minimum MySQL version supported is now 5.0.2.

MariaDB Support
~~~~~~~~~~~~~~~

The MariaDB variant of MySQL retains fundamental compatibility with MySQL's
protocols however the development of these two products continues to diverge.
Within the realm of SQLAlchemy, the two databases have a small number of
syntactical and behavioral differences that SQLAlchemy accommodates automatically.
To connect to a MariaDB database, no changes to the database URL are required::


    engine = create_engine(
        "mysql+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
    )

Upon first connect, the SQLAlchemy dialect employs a
server version detection scheme that determines if the
backing database reports as MariaDB.  Based on this flag, the dialect
can make different choices in those of areas where its behavior
must be different.

.. _mysql_mariadb_only_mode:

MariaDB-Only Mode
~~~~~~~~~~~~~~~~~

The dialect also supports an **optional** "MariaDB-only" mode of connection, which may be
useful for the case where an application makes use of MariaDB-specific features
and is not compatible with a MySQL database.    To use this mode of operation,
replace the "mysql" token in the above URL with "mariadb"::

    engine = create_engine(
        "mariadb+pymysql://user:pass@some_mariadb/dbname?charset=utf8mb4"
    )

The above engine, upon first connect, will raise an error if the server version
detection detects that the backing database is not MariaDB.

When using an engine with ``"mariadb"`` as the dialect name, **all mysql-specific options
that include the name "mysql" in them are now named with "mariadb"**.  This means
options like ``mysql_engine`` should be named ``mariadb_engine``, etc.  Both
"mysql" and "mariadb" options can be used simultaneously for applications that
use URLs with both "mysql" and "mariadb" dialects::

    my_table = Table(
        "mytable",
        metadata,
        Column("id", Integer, primary_key=True),
        Column("textdata", String(50)),
        mariadb_engine="InnoDB",
        mysql_engine="InnoDB",
    )

    Index(
        "textdata_ix",
        my_table.c.textdata,
        mysql_prefix="FULLTEXT",
        mariadb_prefix="FULLTEXT",
    )

Similar behavior will occur when the above structures are reflected, i.e. the
"mariadb" prefix will be present in the option names when the database URL
is based on the "mariadb" name.

.. versionadded:: 1.4 Added "mariadb" dialect name supporting "MariaDB-only mode"
   for the MySQL dialect.

.. _mysql_connection_timeouts:

Connection Timeouts and Disconnects
-----------------------------------

MySQL / MariaDB feature an automatic connection close behavior, for connections that
have been idle for a fixed period of time, defaulting to eight hours.
To circumvent having this issue, use
the :paramref:`_sa.create_engine.pool_recycle` option which ensures that
a connection will be discarded and replaced with a new one if it has been
present in the pool for a fixed number of seconds::

    engine = create_engine("mysql+mysqldb://...", pool_recycle=3600)

For more comprehensive disconnect detection of pooled connections, including
accommodation of  server restarts and network issues, a pre-ping approach may
be employed.  See :ref:`pool_disconnects` for current approaches.

.. seealso::

    :ref:`pool_disconnects` - Background on several techniques for dealing
    with timed out connections as well as database restarts.

.. _mysql_storage_engines:

CREATE TABLE arguments including Storage Engines
------------------------------------------------

Both MySQL's and MariaDB's CREATE TABLE syntax includes a wide array of special options,
including ``ENGINE``, ``CHARSET``, ``MAX_ROWS``, ``ROW_FORMAT``,
``INSERT_METHOD``, and many more.
To accommodate the rendering of these arguments, specify the form
``mysql_argument_name="value"``.  For example, to specify a table with
``ENGINE`` of ``InnoDB``, ``CHARSET`` of ``utf8mb4``, and ``KEY_BLOCK_SIZE``
of ``1024``::

  Table(
      "mytable",
      metadata,
      Column("data", String(32)),
      mysql_engine="InnoDB",
      mysql_charset="utf8mb4",
      mysql_key_block_size="1024",
  )

When supporting :ref:`mysql_mariadb_only_mode` mode, similar keys against
the "mariadb" prefix must be included as well.  The values can of course
vary independently so that different settings on MySQL vs. MariaDB may
be maintained::

  # support both "mysql" and "mariadb-only" engine URLs

  Table(
      "mytable",
      metadata,
      Column("data", String(32)),
      mysql_engine="InnoDB",
      mariadb_engine="InnoDB",
      mysql_charset="utf8mb4",
      mariadb_charset="utf8",
      mysql_key_block_size="1024",
      mariadb_key_block_size="1024",
  )

The MySQL / MariaDB dialects will normally transfer any keyword specified as
``mysql_keyword_name`` to be rendered as ``KEYWORD_NAME`` in the
``CREATE TABLE`` statement.  A handful of these names will render with a space
instead of an underscore; to support this, the MySQL dialect has awareness of
these particular names, which include ``DATA DIRECTORY``
(e.g. ``mysql_data_directory``), ``CHARACTER SET`` (e.g.
``mysql_character_set``) and ``INDEX DIRECTORY`` (e.g.
``mysql_index_directory``).

The most common argument is ``mysql_engine``, which refers to the storage
engine for the table.  Historically, MySQL server installations would default
to ``MyISAM`` for this value, although newer versions may be defaulting
to ``InnoDB``.  The ``InnoDB`` engine is typically preferred for its support
of transactions and foreign keys.

A :class:`_schema.Table`
that is created in a MySQL / MariaDB database with a storage engine
of ``MyISAM`` will be essentially non-transactional, meaning any
INSERT/UPDATE/DELETE statement referring to this table will be invoked as
autocommit.   It also will have no support for foreign key constraints; while
the ``CREATE TABLE`` statement accepts foreign key options, when using the
``MyISAM`` storage engine these arguments are discarded.  Reflecting such a
table will also produce no foreign key constraint information.

For fully atomic transactions as well as support for foreign key
constraints, all participating ``CREATE TABLE`` statements must specify a
transactional engine, which in the vast majority of cases is ``InnoDB``.


Case Sensitivity and Table Reflection
-------------------------------------

Both MySQL and MariaDB have inconsistent support for case-sensitive identifier
names, basing support on specific details of the underlying
operating system. However, it has been observed that no matter
what case sensitivity behavior is present, the names of tables in
foreign key declarations are *always* received from the database
as all-lower case, making it impossible to accurately reflect a
schema where inter-related tables use mixed-case identifier names.

Therefore it is strongly advised that table names be declared as
all lower case both within SQLAlchemy as well as on the MySQL / MariaDB
database itself, especially if database reflection features are
to be used.

.. _mysql_isolation_level:

Transaction Isolation Level
---------------------------

All MySQL / MariaDB dialects support setting of transaction isolation level both via a
dialect-specific parameter :paramref:`_sa.create_engine.isolation_level`
accepted
by :func:`_sa.create_engine`, as well as the
:paramref:`.Connection.execution_options.isolation_level` argument as passed to
:meth:`_engine.Connection.execution_options`.
This feature works by issuing the
command ``SET SESSION TRANSACTION ISOLATION LEVEL <level>`` for each new
connection.  For the special AUTOCOMMIT isolation level, DBAPI-specific
techniques are used.

To set isolation level using :func:`_sa.create_engine`::

    engine = create_engine(
        "mysql+mysqldb://scott:tiger@localhost/test",
        isolation_level="READ UNCOMMITTED",
    )

To set using per-connection execution options::

    connection = engine.connect()
    connection = connection.execution_options(isolation_level="READ COMMITTED")

Valid values for ``isolation_level`` include:

* ``READ COMMITTED``
* ``READ UNCOMMITTED``
* ``REPEATABLE READ``
* ``SERIALIZABLE``
* ``AUTOCOMMIT``

The special ``AUTOCOMMIT`` value makes use of the various "autocommit"
attributes provided by specific DBAPIs, and is currently supported by
MySQLdb, MySQL-Client, MySQL-Connector Python, and PyMySQL.   Using it,
the database connection will return true for the value of
``SELECT @@autocommit;``.

There are also more options for isolation level configurations, such as
"sub-engine" objects linked to a main :class:`_engine.Engine` which each apply
different isolation level settings.  See the discussion at
:ref:`dbapi_autocommit` for background.

.. seealso::

    :ref:`dbapi_autocommit`

AUTO_INCREMENT Behavior
-----------------------

When creating tables, SQLAlchemy will automatically set ``AUTO_INCREMENT`` on
the first :class:`.Integer` primary key column which is not marked as a
foreign key::

  >>> t = Table(
  ...     "mytable", metadata, Column("mytable_id", Integer, primary_key=True)
  ... )
  >>> t.create()
  CREATE TABLE mytable (
          id INTEGER NOT NULL AUTO_INCREMENT,
          PRIMARY KEY (id)
  )

You can disable this behavior by passing ``False`` to the
:paramref:`_schema.Column.autoincrement` argument of :class:`_schema.Column`.
This flag
can also be used to enable auto-increment on a secondary column in a
multi-column key for some storage engines::

  Table(
      "mytable",
      metadata,
      Column("gid", Integer, primary_key=True, autoincrement=False),
      Column("id", Integer, primary_key=True),
  )

.. _mysql_ss_cursors:

Server Side Cursors
-------------------

Server-side cursor support is available for the mysqlclient, PyMySQL,
mariadbconnector dialects and may also be available in others.   This makes use
of either the "buffered=True/False" flag if available or by using a class such
as ``MySQLdb.cursors.SSCursor`` or ``pymysql.cursors.SSCursor`` internally.


Server side cursors are enabled on a per-statement basis by using the
:paramref:`.Connection.execution_options.stream_results` connection execution
option::

    with engine.connect() as conn:
        result = conn.execution_options(stream_results=True).execute(
            text("select * from table")
        )

Note that some kinds of SQL statements may not be supported with
server side cursors; generally, only SQL statements that return rows should be
used with this option.

.. deprecated:: 1.4  The dialect-level server_side_cursors flag is deprecated
   and will be removed in a future release.  Please use the
   :paramref:`_engine.Connection.stream_results` execution option for
   unbuffered cursor support.

.. seealso::

    :ref:`engine_stream_results`

.. _mysql_unicode:

Unicode
-------

Charset Selection
~~~~~~~~~~~~~~~~~

Most MySQL / MariaDB DBAPIs offer the option to set the client character set for
a connection.   This is typically delivered using the ``charset`` parameter
in the URL, such as::

    e = create_engine(
        "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4"
    )

This charset is the **client character set** for the connection.  Some
MySQL DBAPIs will default this to a value such as ``latin1``, and some
will make use of the ``default-character-set`` setting in the ``my.cnf``
file as well.   Documentation for the DBAPI in use should be consulted
for specific behavior.

The encoding used for Unicode has traditionally been ``'utf8'``.  However, for
MySQL versions 5.5.3 and MariaDB 5.5 on forward, a new MySQL-specific encoding
``'utf8mb4'`` has been introduced, and as of MySQL 8.0 a warning is emitted by
the server if plain ``utf8`` is specified within any server-side directives,
replaced with ``utf8mb3``.  The rationale for this new encoding is due to the
fact that MySQL's legacy utf-8 encoding only supports codepoints up to three
bytes instead of four.  Therefore, when communicating with a MySQL or MariaDB
database that includes codepoints more than three bytes in size, this new
charset is preferred, if supported by both the database as well as the client
DBAPI, as in::

    e = create_engine(
        "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4"
    )

All modern DBAPIs should support the ``utf8mb4`` charset.

In order to use ``utf8mb4`` encoding for a schema that was created with  legacy
``utf8``, changes to the MySQL/MariaDB schema and/or server configuration may be
required.

.. seealso::

    `The utf8mb4 Character Set \
    <https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html>`_ - \
    in the MySQL documentation

.. _mysql_binary_introducer:

Dealing with Binary Data Warnings and Unicode
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

MySQL versions 5.6, 5.7 and later (not MariaDB at the time of this writing) now
emit a warning when attempting to pass binary data to the database, while a
character set encoding is also in place, when the binary data itself is not
valid for that encoding:

.. sourcecode:: text

    default.py:509: Warning: (1300, "Invalid utf8mb4 character string:
    'F9876A'")
      cursor.execute(statement, parameters)

This warning is due to the fact that the MySQL client library is attempting to
interpret the binary string as a unicode object even if a datatype such
as :class:`.LargeBinary` is in use.   To resolve this, the SQL statement requires
a binary "character set introducer" be present before any non-NULL value
that renders like this:

.. sourcecode:: sql

    INSERT INTO table (data) VALUES (_binary %s)

These character set introducers are provided by the DBAPI driver, assuming the
use of mysqlclient or PyMySQL (both of which are recommended).  Add the query
string parameter ``binary_prefix=true`` to the URL to repair this warning::

    # mysqlclient
    engine = create_engine(
        "mysql+mysqldb://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true"
    )

    # PyMySQL
    engine = create_engine(
        "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4&binary_prefix=true"
    )

The ``binary_prefix`` flag may or may not be supported by other MySQL drivers.

SQLAlchemy itself cannot render this ``_binary`` prefix reliably, as it does
not work with the NULL value, which is valid to be sent as a bound parameter.
As the MySQL driver renders parameters directly into the SQL string, it's the
most efficient place for this additional keyword to be passed.

.. seealso::

    `Character set introducers <https://dev.mysql.com/doc/refman/5.7/en/charset-introducer.html>`_ - on the MySQL website


ANSI Quoting Style
------------------

MySQL / MariaDB feature two varieties of identifier "quoting style", one using
backticks and the other using quotes, e.g. ```some_identifier```  vs.
``"some_identifier"``.   All MySQL dialects detect which version
is in use by checking the value of :ref:`sql_mode<mysql_sql_mode>` when a connection is first
established with a particular :class:`_engine.Engine`.
This quoting style comes
into play when rendering table and column names as well as when reflecting
existing database structures.  The detection is entirely automatic and
no special configuration is needed to use either quoting style.


.. _mysql_sql_mode:

Changing the sql_mode
---------------------

MySQL supports operating in multiple
`Server SQL Modes <https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html>`_  for
both Servers and Clients. To change the ``sql_mode`` for a given application, a
developer can leverage SQLAlchemy's Events system.

In the following example, the event system is used to set the ``sql_mode`` on
the ``first_connect`` and ``connect`` events::

    from sqlalchemy import create_engine, event

    eng = create_engine(
        "mysql+mysqldb://scott:tiger@localhost/test", echo="debug"
    )


    # `insert=True` will ensure this is the very first listener to run
    @event.listens_for(eng, "connect", insert=True)
    def connect(dbapi_connection, connection_record):
        cursor = dbapi_connection.cursor()
        cursor.execute("SET sql_mode = 'STRICT_ALL_TABLES'")


    conn = eng.connect()

In the example illustrated above, the "connect" event will invoke the "SET"
statement on the connection at the moment a particular DBAPI connection is
first created for a given Pool, before the connection is made available to the
connection pool.  Additionally, because the function was registered with
``insert=True``, it will be prepended to the internal list of registered
functions.


MySQL / MariaDB SQL Extensions
------------------------------

Many of the MySQL / MariaDB SQL extensions are handled through SQLAlchemy's generic
function and operator support::

  table.select(table.c.password == func.md5("plaintext"))
  table.select(table.c.username.op("regexp")("^[a-d]"))

And of course any valid SQL statement can be executed as a string as well.

Some limited direct support for MySQL / MariaDB extensions to SQL is currently
available.

* INSERT..ON DUPLICATE KEY UPDATE:  See
  :ref:`mysql_insert_on_duplicate_key_update`

* SELECT pragma, use :meth:`_expression.Select.prefix_with` and
  :meth:`_query.Query.prefix_with`::

    select(...).prefix_with(["HIGH_PRIORITY", "SQL_SMALL_RESULT"])

* UPDATE with LIMIT::

    update(...).with_dialect_options(mysql_limit=10, mariadb_limit=10)

* DELETE
  with LIMIT::

    delete(...).with_dialect_options(mysql_limit=10, mariadb_limit=10)

  .. versionadded:: 2.0.37 Added delete with limit

* optimizer hints, use :meth:`_expression.Select.prefix_with` and
  :meth:`_query.Query.prefix_with`::

    select(...).prefix_with("/*+ NO_RANGE_OPTIMIZATION(t4 PRIMARY) */")

* index hints, use :meth:`_expression.Select.with_hint` and
  :meth:`_query.Query.with_hint`::

    select(...).with_hint(some_table, "USE INDEX xyz")

* MATCH
  operator support::

        from sqlalchemy.dialects.mysql import match

        select(...).where(match(col1, col2, against="some expr").in_boolean_mode())

  .. seealso::

    :class:`_mysql.match`

INSERT/DELETE...RETURNING
-------------------------

The MariaDB dialect supports 10.5+'s ``INSERT..RETURNING`` and
``DELETE..RETURNING`` (10.0+) syntaxes.   ``INSERT..RETURNING`` may be used
automatically in some cases in order to fetch newly generated identifiers in
place of the traditional approach of using ``cursor.lastrowid``, however
``cursor.lastrowid`` is currently still preferred for simple single-statement
cases for its better performance.

To specify an explicit ``RETURNING`` clause, use the
:meth:`._UpdateBase.returning` method on a per-statement basis::

    # INSERT..RETURNING
    result = connection.execute(
        table.insert().values(name="foo").returning(table.c.col1, table.c.col2)
    )
    print(result.all())

    # DELETE..RETURNING
    result = connection.execute(
        table.delete()
        .where(table.c.name == "foo")
        .returning(table.c.col1, table.c.col2)
    )
    print(result.all())

.. versionadded:: 2.0  Added support for MariaDB RETURNING

.. _mysql_insert_on_duplicate_key_update:

INSERT...ON DUPLICATE KEY UPDATE (Upsert)
------------------------------------------

MySQL / MariaDB allow "upserts" (update or insert)
of rows into a table via the ``ON DUPLICATE KEY UPDATE`` clause of the
``INSERT`` statement.  A candidate row will only be inserted if that row does
not match an existing primary or unique key in the table; otherwise, an UPDATE
will be performed.   The statement allows for separate specification of the
values to INSERT versus the values for UPDATE.

SQLAlchemy provides ``ON DUPLICATE KEY UPDATE`` support via the MySQL-specific
:func:`.mysql.insert()` function, which provides
the generative method :meth:`~.mysql.Insert.on_duplicate_key_update`:

.. sourcecode:: pycon+sql

    >>> from sqlalchemy.dialects.mysql import insert

    >>> insert_stmt = insert(my_table).values(
    ...     id="some_existing_id", data="inserted value"
    ... )

    >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
    ...     data=insert_stmt.inserted.data, status="U"
    ... )
    >>> print(on_duplicate_key_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%s, %s)
    ON DUPLICATE KEY UPDATE data = VALUES(data), status = %s


Unlike PostgreSQL's "ON CONFLICT" phrase, the "ON DUPLICATE KEY UPDATE"
phrase will always match on any primary key or unique key, and will always
perform an UPDATE if there's a match; there are no options for it to raise
an error or to skip performing an UPDATE.

``ON DUPLICATE KEY UPDATE`` is used to perform an update of the already
existing row, using any combination of new values as well as values
from the proposed insertion.   These values are normally specified using
keyword arguments passed to the
:meth:`_mysql.Insert.on_duplicate_key_update`
given column key values (usually the name of the column, unless it
specifies :paramref:`_schema.Column.key`
) as keys and literal or SQL expressions
as values:

.. sourcecode:: pycon+sql

    >>> insert_stmt = insert(my_table).values(
    ...     id="some_existing_id", data="inserted value"
    ... )

    >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
    ...     data="some data",
    ...     updated_at=func.current_timestamp(),
    ... )

    >>> print(on_duplicate_key_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%s, %s)
    ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP

In a manner similar to that of :meth:`.UpdateBase.values`, other parameter
forms are accepted, including a single dictionary:

.. sourcecode:: pycon+sql

    >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
    ...     {"data": "some data", "updated_at": func.current_timestamp()},
    ... )

as well as a list of 2-tuples, which will automatically provide
a parameter-ordered UPDATE statement in a manner similar to that described
at :ref:`tutorial_parameter_ordered_updates`.  Unlike the :class:`_expression.Update`
object,
no special flag is needed to specify the intent since the argument form is
this context is unambiguous:

.. sourcecode:: pycon+sql

    >>> on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(
    ...     [
    ...         ("data", "some data"),
    ...         ("updated_at", func.current_timestamp()),
    ...     ]
    ... )

    >>> print(on_duplicate_key_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (%s, %s)
    ON DUPLICATE KEY UPDATE data = %s, updated_at = CURRENT_TIMESTAMP

.. versionchanged:: 1.3 support for parameter-ordered UPDATE clause within
   MySQL ON DUPLICATE KEY UPDATE

.. warning::

    The :meth:`_mysql.Insert.on_duplicate_key_update`
    method does **not** take into
    account Python-side default UPDATE values or generation functions, e.g.
    e.g. those specified using :paramref:`_schema.Column.onupdate`.
    These values will not be exercised for an ON DUPLICATE KEY style of UPDATE,
    unless they are manually specified explicitly in the parameters.



In order to refer to the proposed insertion row, the special alias
:attr:`_mysql.Insert.inserted` is available as an attribute on
the :class:`_mysql.Insert` object; this object is a
:class:`_expression.ColumnCollection` which contains all columns of the target
table:

.. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(
    ...     id="some_id", data="inserted value", author="jlh"
    ... )

    >>> do_update_stmt = stmt.on_duplicate_key_update(
    ...     data="updated value", author=stmt.inserted.author
    ... )

    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data, author) VALUES (%s, %s, %s)
    ON DUPLICATE KEY UPDATE data = %s, author = VALUES(author)

When rendered, the "inserted" namespace will produce the expression
``VALUES(<columnname>)``.

.. versionadded:: 1.2 Added support for MySQL ON DUPLICATE KEY UPDATE clause



rowcount Support
----------------

SQLAlchemy standardizes the DBAPI ``cursor.rowcount`` attribute to be the
usual definition of "number of rows matched by an UPDATE or DELETE" statement.
This is in contradiction to the default setting on most MySQL DBAPI drivers,
which is "number of rows actually modified/deleted".  For this reason, the
SQLAlchemy MySQL dialects always add the ``constants.CLIENT.FOUND_ROWS``
flag, or whatever is equivalent for the target dialect, upon connection.
This setting is currently hardcoded.

.. seealso::

    :attr:`_engine.CursorResult.rowcount`


.. _mysql_indexes:

MySQL / MariaDB- Specific Index Options
-----------------------------------------

MySQL and MariaDB-specific extensions to the :class:`.Index` construct are available.

Index Length
~~~~~~~~~~~~~

MySQL and MariaDB both provide an option to create index entries with a certain length, where
"length" refers to the number of characters or bytes in each value which will
become part of the index. SQLAlchemy provides this feature via the
``mysql_length`` and/or ``mariadb_length`` parameters::

    Index("my_index", my_table.c.data, mysql_length=10, mariadb_length=10)

    Index("a_b_idx", my_table.c.a, my_table.c.b, mysql_length={"a": 4, "b": 9})

    Index(
        "a_b_idx", my_table.c.a, my_table.c.b, mariadb_length={"a": 4, "b": 9}
    )

Prefix lengths are given in characters for nonbinary string types and in bytes
for binary string types. The value passed to the keyword argument *must* be
either an integer (and, thus, specify the same prefix length value for all
columns of the index) or a dict in which keys are column names and values are
prefix length values for corresponding columns. MySQL and MariaDB only allow a
length for a column of an index if it is for a CHAR, VARCHAR, TEXT, BINARY,
VARBINARY and BLOB.

Index Prefixes
~~~~~~~~~~~~~~

MySQL storage engines permit you to specify an index prefix when creating
an index. SQLAlchemy provides this feature via the
``mysql_prefix`` parameter on :class:`.Index`::

    Index("my_index", my_table.c.data, mysql_prefix="FULLTEXT")

The value passed to the keyword argument will be simply passed through to the
underlying CREATE INDEX, so it *must* be a valid index prefix for your MySQL
storage engine.

.. seealso::

    `CREATE INDEX <https://dev.mysql.com/doc/refman/5.0/en/create-index.html>`_ - MySQL documentation

Index Types
~~~~~~~~~~~~~

Some MySQL storage engines permit you to specify an index type when creating
an index or primary key constraint. SQLAlchemy provides this feature via the
``mysql_using`` parameter on :class:`.Index`::

    Index(
        "my_index", my_table.c.data, mysql_using="hash", mariadb_using="hash"
    )

As well as the ``mysql_using`` parameter on :class:`.PrimaryKeyConstraint`::

    PrimaryKeyConstraint("data", mysql_using="hash", mariadb_using="hash")

The value passed to the keyword argument will be simply passed through to the
underlying CREATE INDEX or PRIMARY KEY clause, so it *must* be a valid index
type for your MySQL storage engine.

More information can be found at:

https://dev.mysql.com/doc/refman/5.0/en/create-index.html

https://dev.mysql.com/doc/refman/5.0/en/create-table.html

Index Parsers
~~~~~~~~~~~~~

CREATE FULLTEXT INDEX in MySQL also supports a "WITH PARSER" option.  This
is available using the keyword argument ``mysql_with_parser``::

    Index(
        "my_index",
        my_table.c.data,
        mysql_prefix="FULLTEXT",
        mysql_with_parser="ngram",
        mariadb_prefix="FULLTEXT",
        mariadb_with_parser="ngram",
    )

.. versionadded:: 1.3


.. _mysql_foreign_keys:

MySQL / MariaDB Foreign Keys
-----------------------------

MySQL and MariaDB's behavior regarding foreign keys has some important caveats.

Foreign Key Arguments to Avoid
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Neither MySQL nor MariaDB support the foreign key arguments "DEFERRABLE", "INITIALLY",
or "MATCH".  Using the ``deferrable`` or ``initially`` keyword argument with
:class:`_schema.ForeignKeyConstraint` or :class:`_schema.ForeignKey`
will have the effect of
these keywords being rendered in a DDL expression, which will then raise an
error on MySQL or MariaDB.  In order to use these keywords on a foreign key while having
them ignored on a MySQL / MariaDB backend, use a custom compile rule::

    from sqlalchemy.ext.compiler import compiles
    from sqlalchemy.schema import ForeignKeyConstraint


    @compiles(ForeignKeyConstraint, "mysql", "mariadb")
    def process(element, compiler, **kw):
        element.deferrable = element.initially = None
        return compiler.visit_foreign_key_constraint(element, **kw)

The "MATCH" keyword is in fact more insidious, and is explicitly disallowed
by SQLAlchemy in conjunction with the MySQL or MariaDB backends.  This argument is
silently ignored by MySQL / MariaDB, but in addition has the effect of ON UPDATE and ON
DELETE options also being ignored by the backend.   Therefore MATCH should
never be used with the MySQL / MariaDB backends; as is the case with DEFERRABLE and
INITIALLY, custom compilation rules can be used to correct a
ForeignKeyConstraint at DDL definition time.

Reflection of Foreign Key Constraints
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Not all MySQL / MariaDB storage engines support foreign keys.  When using the
very common ``MyISAM`` MySQL storage engine, the information loaded by table
reflection will not include foreign keys.  For these tables, you may supply a
:class:`~sqlalchemy.ForeignKeyConstraint` at reflection time::

  Table(
      "mytable",
      metadata,
      ForeignKeyConstraint(["other_id"], ["othertable.other_id"]),
      autoload_with=engine,
  )

.. seealso::

    :ref:`mysql_storage_engines`

.. _mysql_unique_constraints:

MySQL / MariaDB Unique Constraints and Reflection
----------------------------------------------------

SQLAlchemy supports both the :class:`.Index` construct with the
flag ``unique=True``, indicating a UNIQUE index, as well as the
:class:`.UniqueConstraint` construct, representing a UNIQUE constraint.
Both objects/syntaxes are supported by MySQL / MariaDB when emitting DDL to create
these constraints.  However, MySQL / MariaDB does not have a unique constraint
construct that is separate from a unique index; that is, the "UNIQUE"
constraint on MySQL / MariaDB is equivalent to creating a "UNIQUE INDEX".

When reflecting these constructs, the
:meth:`_reflection.Inspector.get_indexes`
and the :meth:`_reflection.Inspector.get_unique_constraints`
methods will **both**
return an entry for a UNIQUE index in MySQL / MariaDB.  However, when performing
full table reflection using ``Table(..., autoload_with=engine)``,
the :class:`.UniqueConstraint` construct is
**not** part of the fully reflected :class:`_schema.Table` construct under any
circumstances; this construct is always represented by a :class:`.Index`
with the ``unique=True`` setting present in the :attr:`_schema.Table.indexes`
collection.


TIMESTAMP / DATETIME issues
---------------------------

.. _mysql_timestamp_onupdate:

Rendering ON UPDATE CURRENT TIMESTAMP for MySQL / MariaDB's explicit_defaults_for_timestamp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

MySQL / MariaDB have historically expanded the DDL for the :class:`_types.TIMESTAMP`
datatype into the phrase "TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP", which includes non-standard SQL that automatically updates
the column with the current timestamp when an UPDATE occurs, eliminating the
usual need to use a trigger in such a case where server-side update changes are
desired.

MySQL 5.6 introduced a new flag `explicit_defaults_for_timestamp
<https://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html
#sysvar_explicit_defaults_for_timestamp>`_ which disables the above behavior,
and in MySQL 8 this flag defaults to true, meaning in order to get a MySQL
"on update timestamp" without changing this flag, the above DDL must be
rendered explicitly.   Additionally, the same DDL is valid for use of the
``DATETIME`` datatype as well.

SQLAlchemy's MySQL dialect does not yet have an option to generate
MySQL's "ON UPDATE CURRENT_TIMESTAMP" clause, noting that this is not a general
purpose "ON UPDATE" as there is no such syntax in standard SQL.  SQLAlchemy's
:paramref:`_schema.Column.server_onupdate` parameter is currently not related
to this special MySQL behavior.

To generate this DDL, make use of the :paramref:`_schema.Column.server_default`
parameter and pass a textual clause that also includes the ON UPDATE clause::

    from sqlalchemy import Table, MetaData, Column, Integer, String, TIMESTAMP
    from sqlalchemy import text

    metadata = MetaData()

    mytable = Table(
        "mytable",
        metadata,
        Column("id", Integer, primary_key=True),
        Column("data", String(50)),
        Column(
            "last_updated",
            TIMESTAMP,
            server_default=text(
                "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
            ),
        ),
    )

The same instructions apply to use of the :class:`_types.DateTime` and
:class:`_types.DATETIME` datatypes::

    from sqlalchemy import DateTime

    mytable = Table(
        "mytable",
        metadata,
        Column("id", Integer, primary_key=True),
        Column("data", String(50)),
        Column(
            "last_updated",
            DateTime,
            server_default=text(
                "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
            ),
        ),
    )

Even though the :paramref:`_schema.Column.server_onupdate` feature does not
generate this DDL, it still may be desirable to signal to the ORM that this
updated value should be fetched.  This syntax looks like the following::

    from sqlalchemy.schema import FetchedValue


    class MyClass(Base):
        __tablename__ = "mytable"

        id = Column(Integer, primary_key=True)
        data = Column(String(50))
        last_updated = Column(
            TIMESTAMP,
            server_default=text(
                "CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
            ),
            server_onupdate=FetchedValue(),
        )

.. _mysql_timestamp_null:

TIMESTAMP Columns and NULL
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

MySQL historically enforces that a column which specifies the
TIMESTAMP datatype implicitly includes a default value of
CURRENT_TIMESTAMP, even though this is not stated, and additionally
sets the column as NOT NULL, the opposite behavior vs. that of all
other datatypes:

.. sourcecode:: text

    mysql> CREATE TABLE ts_test (
        -> a INTEGER,
        -> b INTEGER NOT NULL,
        -> c TIMESTAMP,
        -> d TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        -> e TIMESTAMP NULL);
    Query OK, 0 rows affected (0.03 sec)

    mysql> SHOW CREATE TABLE ts_test;
    +---------+-----------------------------------------------------
    | Table   | Create Table
    +---------+-----------------------------------------------------
    | ts_test | CREATE TABLE `ts_test` (
      `a` int(11) DEFAULT NULL,
      `b` int(11) NOT NULL,
      `c` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      `d` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `e` timestamp NULL DEFAULT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1

Above, we see that an INTEGER column defaults to NULL, unless it is specified
with NOT NULL.   But when the column is of type TIMESTAMP, an implicit
default of CURRENT_TIMESTAMP is generated which also coerces the column
to be a NOT NULL, even though we did not specify it as such.

This behavior of MySQL can be changed on the MySQL side using the
`explicit_defaults_for_timestamp
<https://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html
#sysvar_explicit_defaults_for_timestamp>`_ configuration flag introduced in
MySQL 5.6.  With this server setting enabled, TIMESTAMP columns behave like
any other datatype on the MySQL side with regards to defaults and nullability.

However, to accommodate the vast majority of MySQL databases that do not
specify this new flag, SQLAlchemy emits the "NULL" specifier explicitly with
any TIMESTAMP column that does not specify ``nullable=False``.   In order to
accommodate newer databases that specify ``explicit_defaults_for_timestamp``,
SQLAlchemy also emits NOT NULL for TIMESTAMP columns that do specify
``nullable=False``.   The following example illustrates::

    from sqlalchemy import MetaData, Integer, Table, Column, text
    from sqlalchemy.dialects.mysql import TIMESTAMP

    m = MetaData()
    t = Table(
        "ts_test",
        m,
        Column("a", Integer),
        Column("b", Integer, nullable=False),
        Column("c", TIMESTAMP),
        Column("d", TIMESTAMP, nullable=False),
    )


    from sqlalchemy import create_engine

    e = create_engine("mysql+mysqldb://scott:tiger@localhost/test", echo=True)
    m.create_all(e)

output:

.. sourcecode:: sql

    CREATE TABLE ts_test (
        a INTEGER,
        b INTEGER NOT NULL,
        c TIMESTAMP NULL,
        d TIMESTAMP NOT NULL
    )

    )annotations)array)defaultdict)compressN)cast   )
reflection)ENUM)SET)JSON)JSONIndexType)JSONPathType)RESERVED_WORDS_MARIADB)RESERVED_WORDS_MYSQL)
_FloatType)_IntegerType)
_MatchType)_NumericType)_StringType)BIGINT)BIT)CHAR)DATETIME)DECIMAL)DOUBLE)FLOAT)INTEGER)LONGBLOB)LONGTEXT)
MEDIUMBLOB)	MEDIUMINT)
MEDIUMTEXT)NCHAR)NUMERIC)NVARCHAR)REAL)SMALLINT)TEXT)TIME)	TIMESTAMP)TINYBLOB)TINYINT)TINYTEXT)VARCHAR)YEAR   )exc)literal_column)log)schema)sql)util)cursor)default)ReflectionDefaults)	coercions)compiler)elements)	functions)	operators)roles)sqltypes)visitors)InsertmanyvaluesSentinelOpts)SQLCompiler)SchemaConst)BINARY)BLOB)BOOLEAN)DATE)UUID)	VARBINARY)topologicalz%\s*SET\s+(?:(?:GLOBAL|SESSION)\s+)?\wbigintbinarybitblobbooleanchardatedatetimedecimaldoubleenumfixedfloatintintegerjsonlongbloblongtext
mediumblob	mediumint
mediumtextncharnvarcharnumericsetsmallinttexttime	timestamptinyblobtinyinttinytextuuid	varbinary)varcharyearc                   @  s$   e Zd Zdd Zdd Zdd ZdS )MySQLExecutionContextc                 C  sR   | j r#tt| jjr%| jjs't| jdd tt| jj	D g | _
d S d S d S d S )Nc                 S  s   g | ]}|j d fqS N)keyname).0entry rt   `/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/dialects/mysql/base.py
<listcomp>  s    z3MySQLExecutionContext.post_exec.<locals>.<listcomp>)isdeleter   rB   compiledeffective_returningr6   description_cursor FullyBufferedCursorFetchStrategy_result_columnscursor_fetch_strategyselfrt   rt   ru   	post_exec  s$   zMySQLExecutionContext.post_execc                 C  s   | j jr| j| j jS t rp   )dialectsupports_server_side_cursors_dbapi_connectionr6   	_sscursorNotImplementedErrorr   rt   rt   ru   create_server_side_cursor  s   z/MySQLExecutionContext.create_server_side_cursorc                 C  s   |  d| j| |S )Nzselect nextval(%s))_execute_scalaridentifier_preparerformat_sequence)r   seqtype_rt   rt   ru   fire_sequence  s   
z#MySQLExecutionContext.fire_sequenceN)__name__
__module____qualname__r   r   r   rt   rt   rt   ru   ro     s    ro   c                      sx  e Zd ZdZ	 ejj Zeddi dd Z	dd Z
dd	 Zd
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZedZdZdd Zd d! Zd"d# ZdTd%d&Zd'd( Z fd)d*Zd+d, Zd-d. Z fd/d0Z dUd2d3Z!d4d5 Z"d6d7 Z#d8d9 Z$d:d; Z%d<d= Z&d>d? Z'd@dA Z(dBdC Z)dDdE Z*dFdG Z+dHdI Z,dJdK Z-dLdM Z.dNdO Z/dPdQ Z0dRdS Z1  Z2S )VMySQLCompilerTmillisecondsmillisecondc                 C  s"   | j r| j d d }|jrdS dS )zlCalled when a ``SELECT`` statement has no froms,
        and no ``FROM`` clause is to be appended.

        
selectablez
 FROM DUAL )stack_where_criteria)r   stmtrt   rt   ru   default_from  s
   zMySQLCompiler.default_fromc                 K  s   d|  | S )Nzrand%s)function_argspecr   fnkwrt   rt   ru   visit_random_func     zMySQLCompiler.visit_random_funcc                   s&   d  fdd|jD }| dS )N, c                 3  "    | ]}|j fi  V  qd S rp   _compiler_dispatchrr   elemr   r   rt   ru   	<genexpr>      
z2MySQLCompiler.visit_rollup_func.<locals>.<genexpr>z WITH ROLLUPjoinclauses)r   r   r   clausert   r   ru   visit_rollup_func  s   
zMySQLCompiler.visit_rollup_funcc                   s,    fdd|j D \}}d| d| dS )Nc                 3  r   rp   r   r   r   rt   ru   r     r   z=MySQLCompiler.visit_aggregate_strings_func.<locals>.<genexpr>zgroup_concat(z SEPARATOR ))r   )r   r   r   expr	delimeterrt   r   ru   visit_aggregate_strings_func  s   
z*MySQLCompiler.visit_aggregate_strings_funcc                 K  s   d| j | S )Nznextval(%s))preparerr   )r   r   r   rt   rt   ru   visit_sequence	     zMySQLCompiler.visit_sequencec                 K     dS )Nz	SYSDATE()rt   r   rt   rt   ru   visit_sysdate_func     z MySQLCompiler.visit_sysdate_funcc                 K  s  |j jtju rd| j|jfi || j|jfi |f S d| j|jfi || j|jfi |f }|j jtju rQd| j|jfi || j|jfi |f }n|j jtju r|j j	d ur|j j
d urd| j|jfi || j|jfi ||j j
|j j	f }nUd| j|jfi || j|jfi |f }n>|j jtju rd}n4|j jtju rd| j|jfi || j|jfi |f }nd| j|jfi || j|jfi |f }|d	 | d
 S )NzJSON_EXTRACT(%s, %s)z/CASE JSON_EXTRACT(%s, %s) WHEN 'null' THEN NULLz1ELSE CAST(JSON_EXTRACT(%s, %s) AS SIGNED INTEGER)z2ELSE CAST(JSON_EXTRACT(%s, %s) AS DECIMAL(%s, %s))z2ELSE JSON_EXTRACT(%s, %s)+0.0000000000000000000000zWHEN true THEN true ELSE falsez'ELSE JSON_UNQUOTE(JSON_EXTRACT(%s, %s))zELSE JSON_EXTRACT(%s, %s) z END)type_type_affinityr?   r   processleftrightIntegerNumericscale	precisionBooleanString)r   rL   operatorr   case_expressiontype_expressionrt   rt   ru    _render_json_extract_from_binary  sZ   z.MySQLCompiler._render_json_extract_from_binaryc                 K     | j ||fi |S rp   r   r   rL   r   r   rt   rt   ru   visit_json_getitem_op_binaryW     z*MySQLCompiler.visit_json_getitem_op_binaryc                 K  r   rp   r   r   rt   rt   ru   !visit_json_path_getitem_op_binaryZ  r   z/MySQLCompiler.visit_json_path_getitem_op_binaryc                   s  j jr'dd jD }t|fdd|D fddjjD  }njj}g }jd u o5jjrEjj	 dkrCd nd fdd|D D ]Jj
j }t|rntjd |jd	}j| d
d}n fdd}t|i |}j| d
d}jj}	|d|	|f  qNtj
dd |D  }
|
rtdjjjddd |
D f  rd  dd| S dd| S )Nc                 S  s   g | ]	}t tj|qS rt   )r9   expectr>   DMLColumnRolerr   keyrt   rt   ru   rv   a  s    z?MySQLCompiler.visit_on_duplicate_key_update.<locals>.<listcomp>c                   s$   g | ]}| j jv r j j| qS rt   )tablecr   )	statementrt   ru   rv   f  s
    
c                   s   g | ]	}|j  vr|qS rt   r   rr   r   )ordered_keysrt   ru   rv   j  s    newnew_1c                 3  s     | ]}|j  jv r|V  qd S rp   )r   updaterr   col)on_duplicatert   ru   r   {  s    z>MySQLCompiler.visit_on_duplicate_key_update.<locals>.<genexpr>)r   F)
use_schemac                   s   t | tjr| jjr|  } j| _| S t | tjrA| jju rAr2  dj	
| j }t|S dj	
| j d}t|S d S )N.zVALUES(r   )
isinstancer;   BindParameterr   _isnull_cloneColumnClauser   inserted_aliasr   quotenamer1   )objcolumn_literal_clause)_on_dup_alias_namecolumnr   requires_mysql8_aliasr   rt   ru   replace  s(   

z<MySQLCompiler.visit_on_duplicate_key_update.<locals>.replacez%s = %sc                 S  s   h | ]}|j qS rt   r   r   rt   rt   ru   	<setcomp>  s    z>MySQLCompiler.visit_on_duplicate_key_update.<locals>.<setcomp>zFAdditional column names not matching any column keys in table '%s': %sr   c                 s  s    | ]}d | V  qdS )'%s'Nrt   r   rt   rt   ru   r     s    zAS z ON DUPLICATE KEY UPDATE zON DUPLICATE KEY UPDATE )current_executable_parameter_orderingrc   r   r   selectr   $_requires_alias_for_on_duplicate_keyr   lowerr   r   r9   _is_literalr;   r   r   r   
self_groupr@   replacement_traverser   r   appendr5   warnr   r   )r   r   r   parameter_orderingcolsr   val
value_textr   	name_textnon_matchingrt   )r   r   r   r   r   r   r   ru   visit_on_duplicate_key_update]  sZ   


	z+MySQLCompiler.visit_on_duplicate_key_updatec                   s    dd  fdd|jD  S )Nz
concat(%s)r   c                 3  s"    | ]}j |fi  V  qd S rp   r   r   r   rt   ru   r     s     zFMySQLCompiler.visit_concat_op_expression_clauselist.<locals>.<genexpr>r   )r   
clauselistr   r   rt   r   ru   %visit_concat_op_expression_clauselist  s   z3MySQLCompiler.visit_concat_op_expression_clauselistc                 K  s,   d| j |jfi || j |jfi |f S )Nzconcat(%s, %s)r   r   r   r   rt   rt   ru   visit_concat_op_binary  s   z$MySQLCompiler.visit_concat_op_binary))FFF)TFF)FTF)FFT)FTT)zIN BOOLEAN MODEzIN NATURAL LANGUAGE MODEzWITH QUERY EXPANSIONc                 K  s   | j ||jfi |S rp   )visit_match_op_binaryr   r   elementr   rt   rt   ru   visit_mysql_match     zMySQLCompiler.visit_mysql_matchc                 K  s   |j }|dd}|dd}|dd}|||f}|| jvr6d| d| d| f}	d	|	}	td
|	 |j}
| j|
fi |}
| j|jfi |}t	|rct
| j|}|g}|| d|}d|
|f S )zp
        Note that `mysql_boolean_mode` is enabled by default because of
        backward compatibility
        mysql_boolean_modeTmysql_natural_languageFmysql_query_expansionzin_boolean_mode=%szin_natural_language_mode=%szwith_query_expansion=%sr   zInvalid MySQL match flags: %sr   zMATCH (%s) AGAINST (%s))	modifiersget_match_valid_flag_combinationsr   r0   CompileErrorr   r   r   anyr   _match_flag_expressionsextend)r   rL   r   r   r  boolean_modenatural_languagequery_expansionflag_combinationflagsmatch_clauseagainst_clauseflag_expressionsrt   rt   ru   r    s0   




z#MySQLCompiler.visit_match_op_binaryc                 C  s   |S rp   rt   )r   r   re   rt   rt   ru   get_from_hint_text  r   z MySQLCompiler.get_from_hint_textNc                 K  s*  |d u r|j | j}t|tjr| j||jfi |S t|tjr,t	|ddr*dS dS t|tj
r4dS t|tjtjtjtjfrH| jj|S t|tjrat|ttfsat|}| jj|S t|tjridS t|tjrqdS t|tjr| jj|dd	S t|tjr| jjr| jj|S d S )
NunsignedFzUNSIGNED INTEGERzSIGNED INTEGERr   rD   r   r#   r   )r   dialect_implr   r   r?   TypeDecoratorvisit_typeclauseimplr   getattrr)   r   DateTimeDateTimetype_compiler_instancer   r   r	   r
   r   _adapt_string_for_cast_Binaryr   r#   r   Float_support_float_cast)r   
typeclauser   r   adaptedrt   rt   ru   r"    sL   	

zMySQLCompiler.visit_typeclausec                 K  sd   |  |j}|d u r$td| jj |jj  | j |j fi |S d| j |jfi ||f S )NzMDatatype %s does not support CAST on MySQL/MariaDb; the CAST will be skipped.zCAST(%s AS %s))	r   r-  r5   r   r   r(  r   r   r   )r   r   r   r   rt   rt   ru   
visit_cast1  s   zMySQLCompiler.visit_castc                   s&   t  ||}| jjr|dd}|S )N\z\\)superrender_literal_valuer   _backslash_escapesr   )r   valuer   	__class__rt   ru   r2  ?  s   z"MySQLCompiler.render_literal_valuec                 K  r   )Ntruert   r  rt   rt   ru   
visit_trueG  r   zMySQLCompiler.visit_truec                 K  r   )Nfalsert   r  rt   rt   ru   visit_falseJ  r   zMySQLCompiler.visit_falsec                   s<   t |jtrtjddd |j d S t j|fi |S )zAdd special MySQL keywords in place of DISTINCT.

        .. deprecated:: 1.4  This usage is deprecated.
           :meth:`_expression.Select.prefix_with` should be used for special
           keywords at the start of a SELECT.

        zSending string values for 'distinct' is deprecated in the MySQL dialect and will be removed in a future release.  Please use :meth:`.Select.prefix_with` for special keywords at the start of a SELECT statementz1.4)versionr   )r   	_distinctstrr5   warn_deprecatedupperr1  get_select_precolumns)r   r   r   r5  rt   ru   r@  M  s   z#MySQLCompiler.get_select_precolumnsFc              
   K  s   |r|j |j|jf |jrd}n|jrd}nd}d| j|jfd|d||| j|jfd|d|d| j|jfd|i|fS )	Nz FULL OUTER JOIN z LEFT OUTER JOIN z INNER JOIN r   T)asfromfrom_linterz ON rB  )	edgesaddr   r   fullisouterr   r   onclause)r   r   rA  rB  kwargs	join_typert   rt   ru   
visit_joina  s6   zMySQLCompiler.visit_joinc                   s   |j jrd}nd}|j jr5jjr5t }|j jD ]
}|t	| q|dd
 fdd|D  7 }|j jr=|d7 }|j jrE|d7 }|S )	Nz LOCK IN SHARE MODEz FOR UPDATEz OF r   c                 3  s(    | ]}j |fd dd V  qdS )TF)ashintr   Nr  )rr   r   r   rt   ru   r     s
    
z2MySQLCompiler.for_update_clause.<locals>.<genexpr>z NOWAITz SKIP LOCKED)_for_update_argreadofr   supports_for_update_ofr5   
OrderedSetr   sql_utilsurface_selectables_onlyr   nowaitskip_locked)r   r   r   tmptablesr   rt   r   ru   for_update_clausez  s   zMySQLCompiler.for_update_clausec                 K  s   |j |j}}|d u r|d u rdS |d ur:|d u r&d| j|fi |df S d| j|fi || j|fi |f S d| j|fi |f S )Nr   z 
 LIMIT %s, %s18446744073709551615z 
 LIMIT %s)_limit_clause_offset_clauser   )r   r   r   limit_clauseoffset_clausert   rt   ru   r[    s    
zMySQLCompiler.limit_clausec                 C  0   |j d| jj d }|d urdt| S d S Nz%s_limitzLIMIT rH  r  r   r   rX   )r   update_stmtlimitrt   rt   ru   update_limit_clause     z!MySQLCompiler.update_limit_clausec                 C  r]  r^  r_  )r   delete_stmtra  rt   rt   ru   delete_limit_clause  rc  z!MySQLCompiler.delete_limit_clausec                   s,   d d< d  fdd|gt| D S )NTrA  r   c                 3  r   rp   r   rr   tr   rt   ru   r     s
    
z5MySQLCompiler.update_tables_clause.<locals>.<genexpr>)r   list)r   r`  
from_tableextra_fromsr   rt   r   ru   update_tables_clause  s   z"MySQLCompiler.update_tables_clausec                 K  s   d S rp   rt   )r   r`  ri  rj  
from_hintsr   rt   rt   ru   update_from_clause  s   z MySQLCompiler.update_from_clausec                 K  s&   d}|rd}|j | fdd|d|S )z=If we have extra froms make sure we render any alias as hint.FT)rA  iscrudrK  r   )r   rd  ri  rj  r   rK  rt   rt   ru   delete_table_clause  s   z!MySQLCompiler.delete_table_clausec                   s.   dd< dd  fdd|g| D  S )z4Render the DELETE .. USING clause specific to MySQL.TrA  zUSING r   c                 3  s&    | ]}|j fd  iV  qdS )	fromhintsNr   rf  rl  r   r   rt   ru   r     s
    
z9MySQLCompiler.delete_extra_from_clause.<locals>.<genexpr>)r   )r   rd  ri  rj  rl  r   rt   rq  ru   delete_extra_from_clause  s   
z&MySQLCompiler.delete_extra_from_clausec                 K  s6   dd dd t|D d dd t|D d S )NzASELECT %(outer)s FROM (SELECT %(inner)s) as _empty_set WHERE 1!=1r   c                 s      | ]	\}}d | V  qdS )z1 AS _in_%sNrt   rr   idxr   rt   rt   ru   r     s
    
z5MySQLCompiler.visit_empty_set_expr.<locals>.<genexpr>c                 s  rs  )z_in_%sNrt   rt  rt   rt   ru   r         
)innerouter)r   	enumerate)r   element_typesr   rt   rt   ru   visit_empty_set_expr  s   

z"MySQLCompiler.visit_empty_set_exprc                 K     d|  |j|  |jf S )NzNOT (%s <=> %s)r  r   rt   rt   ru   visit_is_distinct_from_binary     

z+MySQLCompiler.visit_is_distinct_from_binaryc                 K  r|  )Nz	%s <=> %sr  r   rt   rt   ru   !visit_is_not_distinct_from_binary  r~  z/MySQLCompiler.visit_is_not_distinct_from_binaryc                 K  s$   d|  |tj| j|fi |f S )NzCONCAT('(?', %s, ')', %s))r2  r?   
STRINGTYPEr   )r   r  patternr   rt   rt   ru   _mariadb_regexp_flags  s   z#MySQLCompiler._mariadb_regexp_flagsc                 K  s   |j d }|d u r| j||fi |S | jjr+d| j|jfi ||| ||jf S d| j|jfi || j|jfi || |t	j
f }|dkrOd| S |S )Nr  z%s%s%szREGEXP_LIKE(%s, %s, %s) NOT REGEXP zNOT %s)r  _generate_generic_binaryr   
is_mariadbr   r   r  r   r2  r?   r  )r   	op_stringrL   r   r   r  re   rt   rt   ru   _regexp_match  s"   
zMySQLCompiler._regexp_matchc                 K     | j d||fi |S )Nz REGEXP r  r   rt   rt   ru   visit_regexp_match_op_binary  r  z*MySQLCompiler.visit_regexp_match_op_binaryc                 K  r  )Nr  r  r   rt   rt   ru    visit_not_regexp_match_op_binary  r  z.MySQLCompiler.visit_not_regexp_match_op_binaryc                 K  s   |j d }|d u rd| j|jfi || j|jfi |f S | jjrEd| j|jfi || ||jjd | j|jjd fi |f S d| j|jfi || j|jfi || |t	j
f S )Nr  zREGEXP_REPLACE(%s, %s)zREGEXP_REPLACE(%s, %s, %s)r   r   )r  r   r   r   r   r  r  r   r2  r?   r  )r   rL   r   r   r  rt   rt   ru   visit_regexp_replace_op_binary"  s"   
z,MySQLCompiler.visit_regexp_replace_op_binaryrp   )FN)3r   r   r   'render_table_with_column_in_update_fromr:   rB   extract_mapcopyr   r   r   r   r   r   r   r   r   r   r  r  r  	frozensetr  r  r
  r  r  r"  r/  r2  r8  r:  r@  rJ  rW  r[  rb  re  rk  rm  ro  rr  r{  r}  r  r  r  r  r  r  __classcell__rt   rt   r5  ru   r     s^    H[*
+
'	
r   c                      sd   e Zd Zdd Zdd Zdd Z fddZd	d
 Zdd Zdd Z	dd Z
dd Zdd Z  ZS )MySQLDDLCompilerc                 K  s|  | j jdu r|jdur|jtju rd|_| j|| j j	j
|j|dg}|jdur2|| 
|j t|j| j tj}|jsF|d n
|jrP|rP|d |j}|durg| j|t }|d|  |jdur||jju r|jdu s~t|jtjr| j jrt|jtjr|jjr|d n&| |}|durt|jjt j!r| j j"r|d| d	 n|d
|  d#|S )zBuilds column DDL.TN)r   zNOT NULLNULLzCOMMENT AUTO_INCREMENTz	DEFAULT (r   zDEFAULT r   )$r   r  computed_user_defined_nullablerC   NULL_UNSPECIFIEDnullabler   format_columnr(  r   r   r   r   _unwrapped_dialect_implr?   r)   commentsql_compilerr2  r   r   _autoincrement_columnserver_default	sa_schemaIdentitysupports_sequencesr7   Sequenceoptionalget_column_default_stringargr<   FunctionElement_support_default_functionr   )r   r   r   colspecis_timestampr  literalr7   rt   rt   ru   get_column_specification8  s`   






	


z)MySQLDDLCompiler.get_column_specificationc           
        s.  g } fdd|j  D }|jdur|j|d< g d}t||}t||}tg d|D ]0}|| }|tj	v rF j
|t }|dv rP|dd	}d
}	|dv rXd	}	||	||f q2tg d|D ]&}|| }|tj	v r j
|t }|dd	}d	}	||	||f qkd	|S )z9Build table-level CREATE options like ENGINE and COLLATE.c                   s@   i | ]\}}| d  jj r|t jjd d  |qS )z%s_r   N)
startswithr   r   lenr?  )rr   kvr   rt   ru   
<dictcomp>~  s    z6MySQLDDLCompiler.post_create_table.<locals>.<dictcomp>NCOMMENT)PARTITION_BY
PARTITIONSSUBPARTITIONSSUBPARTITION_BY))DEFAULT_CHARSETCOLLATE)DEFAULT_CHARACTER_SETr  )CHARSETr  )CHARACTER_SETr  )DATA_DIRECTORYINDEX_DIRECTORYr  r  r  DEFAULT_COLLATE_r   =)
TABLESPACEzDEFAULT CHARACTER SETzCHARACTER SETr  ))r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )rH  itemsr  rc   
differenceintersectionrJ   sort_reflection_options_of_type_stringr  r2  r?   r   r   r   r   )
r   r   
table_optsoptspartition_optionsnonpart_optionspart_optionsoptr  joinerrt   r   ru   post_create_tabley  sJ   


	


z"MySQLDDLCompiler.post_create_tablec                   sd  |j }| j}||j}fdd|jD }|}d}|jr)|d7 }|j	dj
j d }	|	r<||	d 7 }|d7 }|jrG|d7 }|d	||f 7 }|jj
j d
   d urt trrd fddt|j|D }nd fdd|D }nd|}|d| 7 }|jd d }
|
d ur|d|
f 7 }|jd d }|d ur|d|| 7 }|S )Nc                   s^   g | ]+} j jt|tjs"t|tjr|jtjtj	fvs"t|t
jr't|n|d ddqS )FT)include_tableliteral_binds)r  r   r   r;   BinaryExpressionUnaryExpressionmodifierr=   desc_opasc_opr<   r  Grouping)rr   r   r   rt   ru   rv     s$    





z7MySQLDDLCompiler.visit_create_index.<locals>.<listcomp>zCREATE zUNIQUE 	%s_prefixr   INDEX zIF NOT EXISTS z	%s ON %s lengthr   c                 3  sP    | ]#\}}|j  v rd | |j  f n| v r d | | f nd| V  qdS )%s(%d)z%sNr   )rr   r   r   r  rt   ru   r     s    


z6MySQLDDLCompiler.visit_create_index.<locals>.<genexpr>c                 3  s    | ]	}d | f V  qdS )r  Nrt   r   r  rt   ru   r     rv  z(%s)mysqlwith_parserz WITH PARSER %susing	 USING %s)r	  _verify_index_tabler   format_tabler   expressions_prepared_index_nameuniquerH  r  r   r   if_not_existsdialect_optionsr   dictr   zipr   )r   creater   indexr   r   columnsr   re   index_prefixparserr  rt   )r  r   ru   visit_create_index  sH   








z#MySQLDDLCompiler.visit_create_indexc                   s6   t  |}|jd d }|r|d| j| 7 }|S )Nr  r  r  )r1  visit_primary_key_constraintr  r   r   )r   
constraintr   re   r  r5  rt   ru   r    s
   z-MySQLDDLCompiler.visit_primary_key_constraintc                 K  s<   |j }d}|jr|d7 }|d| j|dd| j|jf  S )Nz
DROP INDEX z
IF EXISTS z%s ON %sF)include_schema)r	  	if_existsr  r   r  r   )r   dropr   r  re   rt   rt   ru   visit_drop_index$  s   z!MySQLDDLCompiler.visit_drop_indexc                 K  s   |j }t|tjrd}| j|}n8t|tjrd}d}n-t|tjr,d}| j|}nt|tjrB| j	j
r9d}nd}| j|}nd}| j|}d| j|j||f S )NzFOREIGN KEY zPRIMARY KEY r   r  zCONSTRAINT zCHECK zALTER TABLE %s DROP %s%s)r	  r   r  ForeignKeyConstraintr   format_constraintPrimaryKeyConstraintUniqueConstraintCheckConstraintr   r  r  r   )r   r  r   r  qualconstrt   rt   ru   visit_drop_constraint/  s,   z&MySQLDDLCompiler.visit_drop_constraintc                 C  s   |j d ur
tddS )NzjMySQL ignores the 'MATCH' keyword while at the same time causes ON UPDATE/ON DELETE clauses to be ignored.r   )matchr0   r  )r   r  rt   rt   ru   define_constraint_matchI  s
   
z(MySQLDDLCompiler.define_constraint_matchc                 K  s(   d| j |j| j|jjt f S )NzALTER TABLE %s COMMENT %s)r   r  r	  r  r2  r  r?   r   r   r  r   rt   rt   ru   visit_set_table_commentQ  s   z(MySQLDDLCompiler.visit_set_table_commentc                 K  s   d| j |j S )NzALTER TABLE %s COMMENT '')r   r  r	  r   rt   rt   ru   visit_drop_table_commentY  s   z)MySQLDDLCompiler.visit_drop_table_commentc                 K  s,   d| j |jj| j |j| |jf S )NzALTER TABLE %s CHANGE %s %s)r   r  r	  r   r  r  r   rt   rt   ru   visit_set_column_comment^  s
   
z)MySQLDDLCompiler.visit_set_column_comment)r   r   r   r  r  r  r  r  r  r  r  r  r  r  rt   rt   r5  ru   r  7  s    ATPr  c                      sT  e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z! fd?d@Z"dAdB Z#dCdD Z$dEdF Z%dGdH Z&dIdJ Z'dKdL Z(dMdN Z)dOdP Z*  Z+S )QMySQLTypeCompilerc                 C  s.   |  |s|S |jr|d7 }|jr|d7 }|S )zAExtend a numeric-type declaration with MySQL specific extensions.z	 UNSIGNEDz	 ZEROFILL)_mysql_typer  zerofill)r   r   specrt   rt   ru   _extend_numericg  s   
z!MySQLTypeCompiler._extend_numericc                   s    fdd}|drd|d }n|drd}n	|dr d}nd	}|d
r,dj  }n	|dr3d}nd	}|drFddd d||fD S ddd |||fD S )zExtend a string-type declaration with standard SQL CHARACTER SET /
        COLLATE annotations and MySQL specific extensions.

        c                   s   t |  | S rp   )r$  r  r  defaultsr   rt   ru   attry  s   z.MySQLTypeCompiler._extend_string.<locals>.attrcharsetzCHARACTER SET %sasciiASCIIunicodeUNICODEN	collationz
COLLATE %srL   rD   nationalr   c                 S     g | ]}|d ur|qS rp   rt   r   rt   rt   ru   rv         z4MySQLTypeCompiler._extend_string.<locals>.<listcomp>NATIONALc                 S  r  rp   rt   r   rt   rt   ru   rv     r  )r  r   )r   r   r
  r  r  r  r  rt   r	  ru   _extend_strings  s(   z MySQLTypeCompiler._extend_stringc                 C  s   t |ttfS rp   )r   r   r   )r   r   rt   rt   ru   r    r   zMySQLTypeCompiler._mysql_typec                 K  P   |j d u r| |dS |jd u r| |dd|j i S | |d|j |jd S )Nr#   zNUMERIC(%(precision)s)r   z!NUMERIC(%(precision)s, %(scale)s)r   r   r   r  r   r   r   r   rt   rt   ru   visit_NUMERIC     

zMySQLTypeCompiler.visit_NUMERICc                 K  r  )Nr   zDECIMAL(%(precision)s)r   z!DECIMAL(%(precision)s, %(scale)s)r  r  r  rt   rt   ru   visit_DECIMAL  r  zMySQLTypeCompiler.visit_DECIMALc                 K  :   |j d ur|jd ur| |d|j |jd S | |dS )Nz DOUBLE(%(precision)s, %(scale)s)r  r   r   r   r  r  rt   rt   ru   visit_DOUBLE     zMySQLTypeCompiler.visit_DOUBLEc                 K  r  )NzREAL(%(precision)s, %(scale)s)r  r%   r  r  rt   rt   ru   
visit_REAL  r!  zMySQLTypeCompiler.visit_REALc                 K  s`   |  |r|jd ur|jd ur| |d|j|jf S |jd ur*| |d|jf S | |dS )NzFLOAT(%s, %s)z	FLOAT(%s)r   )r  r   r   r  r  rt   rt   ru   visit_FLOAT  s   


zMySQLTypeCompiler.visit_FLOATc                 K  6   |  |r|jd ur| |dd|ji S | |dS )NzINTEGER(%(display_width)s)display_widthr   r  r%  r  r  rt   rt   ru   visit_INTEGER     zMySQLTypeCompiler.visit_INTEGERc                 K  r$  )NzBIGINT(%(display_width)s)r%  r   r&  r  rt   rt   ru   visit_BIGINT  r(  zMySQLTypeCompiler.visit_BIGINTc                 K  r$  )NzMEDIUMINT(%(display_width)s)r%  r    r&  r  rt   rt   ru   visit_MEDIUMINT  r(  z!MySQLTypeCompiler.visit_MEDIUMINTc                 K  s2   |  |r|jd ur| |d|j S | |dS )NzTINYINT(%s)r+   r&  r  rt   rt   ru   visit_TINYINT  s
   
zMySQLTypeCompiler.visit_TINYINTc                 K  r$  )NzSMALLINT(%(display_width)s)r%  r&   r&  r  rt   rt   ru   visit_SMALLINT 	  r(  z MySQLTypeCompiler.visit_SMALLINTc                 K     |j d ur
d|j  S dS )NzBIT(%s)r   r  r  rt   rt   ru   	visit_BIT
	     

zMySQLTypeCompiler.visit_BITc                 K     t |dd rd|j S dS )NfspzDATETIME(%d)r   r$  r1  r  rt   rt   ru   visit_DATETIME	     
z MySQLTypeCompiler.visit_DATETIMEc                 K  r   )NrG   rt   r  rt   rt   ru   
visit_DATE	  r   zMySQLTypeCompiler.visit_DATEc                 K  r0  )Nr1  zTIME(%d)r(   r2  r  rt   rt   ru   
visit_TIME	  r4  zMySQLTypeCompiler.visit_TIMEc                 K  r0  )Nr1  zTIMESTAMP(%d)r)   r2  r  rt   rt   ru   visit_TIMESTAMP	  r4  z!MySQLTypeCompiler.visit_TIMESTAMPc                 K  s   |j d u rdS d|j  S )Nr.   zYEAR(%s))r%  r  rt   rt   ru   
visit_YEAR%	  s   

zMySQLTypeCompiler.visit_YEARc                 K  s,   |j d ur| |i d|j  S | |i dS )NzTEXT(%d)r'   r  r  r  rt   rt   ru   
visit_TEXT+	  s   
zMySQLTypeCompiler.visit_TEXTc                 K     |  |i dS )Nr,   r  r  rt   rt   ru   visit_TINYTEXT1	  r   z MySQLTypeCompiler.visit_TINYTEXTc                 K  r;  )Nr!   r<  r  rt   rt   ru   visit_MEDIUMTEXT4	  r   z"MySQLTypeCompiler.visit_MEDIUMTEXTc                 K  r;  )Nr   r<  r  rt   rt   ru   visit_LONGTEXT7	  r   z MySQLTypeCompiler.visit_LONGTEXTc                 K  s0   |j d ur| |i d|j  S td| jj )NzVARCHAR(%d)z'VARCHAR requires a length on dialect %sr  r  r0   r  r   r   r  rt   rt   ru   visit_VARCHAR:	  s
   

zMySQLTypeCompiler.visit_VARCHARc                 K  s0   |j d ur| |i dd|j i S | |i dS )NCHAR(%(length)s)r  r   r9  r  rt   rt   ru   
visit_CHARB	  s
   
zMySQLTypeCompiler.visit_CHARc                 K  s8   |j d ur| |ddidd|j i S td| jj )Nr  TzVARCHAR(%(length)s)r  z(NVARCHAR requires a length on dialect %sr@  r  rt   rt   ru   visit_NVARCHARJ	  s   

z MySQLTypeCompiler.visit_NVARCHARc                 K  s8   |j d ur| |ddidd|j i S | |ddidS )Nr  TrB  r  r   r9  r  rt   rt   ru   visit_NCHARX	  s   
zMySQLTypeCompiler.visit_NCHARc                 K  r   )NrH   rt   r  rt   rt   ru   
visit_UUIDd	  r   zMySQLTypeCompiler.visit_UUIDc                 K  s
   d|j  S )NzVARBINARY(%d)r  r  rt   rt   ru   visit_VARBINARYg	     
z!MySQLTypeCompiler.visit_VARBINARYc                 K  r   )Nr   rt   r  rt   rt   ru   
visit_JSONj	  r   zMySQLTypeCompiler.visit_JSONc                 K  s
   |  |S rp   )
visit_BLOBr  rt   rt   ru   visit_large_binarym	  rH  z$MySQLTypeCompiler.visit_large_binaryc                   s"   |j s	t |S | d||jS Nr	   )native_enumr1  
visit_enum_visit_enumerated_valuesenumsr  r5  rt   ru   rN  p	  s   zMySQLTypeCompiler.visit_enumc                 K  r-  )NzBLOB(%d)rE   r  r  rt   rt   ru   rJ  v	  r/  zMySQLTypeCompiler.visit_BLOBc                 K  r   )Nr*   rt   r  rt   rt   ru   visit_TINYBLOB|	  r   z MySQLTypeCompiler.visit_TINYBLOBc                 K  r   )Nr   rt   r  rt   rt   ru   visit_MEDIUMBLOB	  r   z"MySQLTypeCompiler.visit_MEDIUMBLOBc                 K  r   )Nr   rt   r  rt   rt   ru   visit_LONGBLOB	  r   z MySQLTypeCompiler.visit_LONGBLOBc              	   C  sV   g }|D ]}| j jjr|dd}|d|dd  q| |i d|d|f S )N%z%%r   'z''z%s(%s),)r   r   _double_percentsr   r   r  r   )r   r   r   enumerated_valuesquoted_enumsert   rt   ru   rO  	  s   
z*MySQLTypeCompiler._visit_enumerated_valuesc                 K     |  d||jS rL  )rO  rP  r  rt   rt   ru   
visit_ENUM	  r   zMySQLTypeCompiler.visit_ENUMc                 K  r[  )Nr
   )rO  valuesr  rt   rt   ru   	visit_SET	  r   zMySQLTypeCompiler.visit_SETc                 K  r   )NBOOLrt   r  rt   rt   ru   visit_BOOLEAN	  r   zMySQLTypeCompiler.visit_BOOLEAN),r   r   r   r  r  r  r  r  r   r"  r#  r'  r)  r*  r+  r,  r.  r3  r5  r6  r7  r8  r:  r=  r>  r?  rA  rC  rD  rE  rF  rG  rI  rK  rN  rJ  rQ  rR  rS  rO  r\  r^  r`  r  rt   rt   r5  ru   r  f  sR    "






r  c                      s*   e Zd ZeZd fdd	Zdd Z  ZS )MySQLIdentifierPreparerFc                   s$   |sd}nd}t  j|||d d S )N`")initial_quoteescape_quote)r1  __init__)r   r   server_ansiquotesr   r   r5  rt   ru   rf  	  s   z MySQLIdentifierPreparer.__init__c                   s   t  fdd|D S )z4Unilaterally identifier-quote any number of strings.c                   s   g | ]}|d ur  |qS rp   )quote_identifier)rr   ir   rt   ru   rv   	  s    zCMySQLIdentifierPreparer._quote_free_identifiers.<locals>.<listcomp>)tuple)r   idsrt   r   ru   _quote_free_identifiers	  s   z/MySQLIdentifierPreparer._quote_free_identifiers)F)r   r   r   r   reserved_wordsrf  rl  r  rt   rt   r5  ru   ra  	  s    ra  c                   @  s   e Zd ZeZdS )MariaDBIdentifierPreparerN)r   r   r   r   rm  rt   rt   rt   ru   rn  	  s    rn  c                
   @  s`  e Zd ZU dZdZdZdZdZdZdZ	dZ
dZdZdZdZdZdZdZdZdZdZded< ejZdZdZdZdZdZdZd	Ze Z dZ!e"Z#e$Z%e&Z'e(Z(e)Z*dZ+d
Z,dZ-dZ.e/j0dd
ife1j2dd
ife1j3dd
ife/j4dd
ife/j5d
d
d
d
dfgZ6	
	
	
d{ddZ7dd Z8dd Z9dd Z:e;dd Z<dd Z=dd Z>dd Z?dd  Z@d!d" ZA	d|d#d$ZB	d|d%d&ZCd'd( ZDd)d* ZEd}d+d,ZFd}d-d.ZGd}d/d0ZHd1d2 ZId3d4 ZJeKjLd}d5d6ZMeKjLd}d7d8ZNd9d: ZOeKjLd}d;d<ZPd=d> ZQd?d@ ZReSdAdB ZTeSdCdD ZUeSdEdF ZVeSdGdH ZWeSdIdJ ZXeKjLdKdL ZYeKjLd}dMdNZZeKjLd}dOdPZ[eKjLd}dQdRZ\eKjLd}dSdTZ]eKjLd}dUdVZ^eKjLd}dWdXZ_dYdZ Z`eKjLd}d[d\ZaeKjLd}d]d^ZbeKjLd}d_d`ZceKjL	
d}dadbZdeKjLd}dcddZe	
d}dedfZfegjhdgdh ZieKjLd}didjZjdkdl Zkdmdn Zldodp Zmdqdr Zndsdt Zodudv Zp	
d~dwdxZqd~dydzZrd
S )MySQLDialectzMDetails of the MySQL dialect.
    Not used directly in application code.
    r  TF   @   booluse_insertmanyvaluesformatN*ra  r  )r  r  prefixr  c                 K  s<   | dd  tjj| fi | || _|| _| |d  d S )Nuse_ansiquotes)popr7   DefaultDialectrf  _json_serializer_json_deserializer_set_mariadb)r   json_serializerjson_deserializerr  rH  rt   rt   ru   rf  
  s
   zMySQLDialect.__init__c                 C  r   )N)SERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READrt   )r   
dbapi_connrt   rt   ru   get_isolation_level_values
  r   z'MySQLDialect.get_isolation_level_valuesc                 C  s.   |  }|d|  |d |  d S )Nz(SET SESSION TRANSACTION ISOLATION LEVEL COMMIT)r6   executeclose)r   dbapi_connectionlevelr6   rt   rt   ru   set_isolation_level
  s   
z MySQLDialect.set_isolation_levelc                 C  s   |  }| jr| jdkr|d n|d | }|d u r'td t |d }|  t	|t
r8| }| ddS )N)         zSELECT @@transaction_isolationzSELECT @@tx_isolationzDCould not retrieve transaction isolation level for MySQL connection.r   -r   )r6   	_is_mysqlserver_version_infor  fetchoner5   r   r   r  r   bytesdecoder?  r   )r   r  r6   rowr   rt   rt   ru   get_isolation_level#
  s   

z MySQLDialect.get_isolation_levelc           	      C  sz   |   }| |d}||\}}|j|i |}zz| }|d | d }W n    t|W |  S |  w )N)dbapiz!SELECT VERSION() LIKE '%MariaDB%'r   )import_dbapicreate_connect_argsconnectr6   r  r  rr  r  )	clsurlr  r   cargscparamsconnr6   r   rt   rt   ru   _is_mariadb_from_url6
  s   

z!MySQLDialect._is_mariadb_from_urlc                 C  sH   |j }| }|d | d }|  t|tr| }| |S )NzSELECT VERSION()r   )	
connectionr6   r  r  r  r   r  r  _parse_server_version)r   r  	dbapi_conr6   r   rt   rt   ru   _get_server_version_infoH
  s   


z%MySQLDialect._get_server_version_infoc           
      C  s   g }d}t d}||}|D ](}t d|}|sq|dr,t|dd  | _d}qt|d}|| qt|}	| 	|	oB||	 |sJ|	| _|	dk rRt
d	|	| _|	S )
NFz[.\-+]z"^(?:(\d+)(?:a|b|c)?|(MariaDB\w*))$   Tr   )r  r   r  zGthe MySQL/MariaDB dialect supports server version info 5.0.2 and above.)recompilesplitr  grouprj   _mariadb_normalized_version_inforX   r   r|  r   r  )
r   r   r;  r  rtokenstokenparsed_tokendigitr  rt   rt   ru   r  V
  s6   


z"MySQLDialect._parse_server_versionc                 C  s^   |d u rd S |s| j rtddtt|f |r*t| _| | | _d| _	d| _
|| _ d S )Nz*MySQL version %s is not a MariaDB variant.r   T)r  r0   InvalidRequestErrorr   mapr=  rn  r   r   delete_returninginsert_returning)r   r  r  rt   rt   ru   r|  |
  s   

zMySQLDialect._set_mariadbc                 C  s   | tdt|d d S )NzXA BEGIN :xidxidr  r4   re   r  r   r  r  rt   rt   ru   do_begin_twophase
  s   zMySQLDialect.do_begin_twophasec                 C  s4   | tdt|d | tdt|d d S )NXA END :xidr  zXA PREPARE :xidr  r  rt   rt   ru   do_prepare_twophase
  s   z MySQLDialect.do_prepare_twophasec                 C  s8   |s| tdt|d | tdt|d d S )Nr  r  zXA ROLLBACK :xidr  r   r  r  is_preparedrecoverrt   rt   ru   do_rollback_twophase
  s   z!MySQLDialect.do_rollback_twophasec                 C  s,   |s|  || |tdt|d d S )NzXA COMMIT :xidr  )r  r  r4   re   r  r  rt   rt   ru   do_commit_twophase
  s   zMySQLDialect.do_commit_twophasec                 C  s   | d}dd |D S )Nz
XA RECOVERc                 S  s    g | ]}|d  d|d  qS )datar   gtrid_lengthrt   rr   r  rt   rt   ru   rv   
  s     z4MySQLDialect.do_recover_twophase.<locals>.<listcomp>exec_driver_sql)r   r  	resultsetrt   rt   ru   do_recover_twophase
  s   
z MySQLDialect.do_recover_twophasec                 C  sT   t || jj| jj| jjfr| |dv rdS t || jj| jjfr(dt|v S dS )N)i  i  i  i  i  i  i  Tz(0, '')F)r   r  OperationalErrorProgrammingErrorInterfaceError_extract_error_codeInternalErrorr=  )r   rZ  r  r6   rt   rt   ru   is_disconnect
  s   	zMySQLDialect.is_disconnectc                   s    fdd|  D S )zMProxy result rows to smooth over MySQL-Python driver
        inconsistencies.c                   s   g | ]}t | qS rt   )_DecodingRowr  r  rt   ru   rv   
  s    z1MySQLDialect._compat_fetchall.<locals>.<listcomp>)fetchall)r   rpr  rt   r  ru   _compat_fetchall
  s   zMySQLDialect._compat_fetchallc                 C     |  }|rt||S dS zNProxy a result row to smooth over MySQL-Python driver
        inconsistencies.N)r  r  r   r  r  r  rt   rt   ru   _compat_fetchone
     
zMySQLDialect._compat_fetchonec                 C  r  r  )firstr  r  rt   rt   ru   _compat_first
  r  zMySQLDialect._compat_firstc                 C     t  rp   r   )r   	exceptionrt   rt   ru   r  
     z MySQLDialect._extract_error_codec                 C  s   | d S )NzSELECT DATABASE())r  scalarr   r  rt   rt   ru   _get_default_schema_name
  r   z%MySQLDialect._get_default_schema_namec              
   K  s   |  | |d u r| j}|d usJ d| j||}z&|jd| ddid}| d uW  d    W S 1 s;w   Y  W d S  tjy_ } z| 	|j
dv rZW Y d }~dS  d }~ww )Nr   z	DESCRIBE skip_user_error_eventsT)execution_options)z  i  i  F)_ensure_has_table_connectiondefault_schema_namer   r   rl  r  r  r0   
DBAPIErrorr  orig)r   r  
table_namer3   r   	full_namersrZ  rt   rt   ru   	has_table
  s.   

(zMySQLDialect.has_tablec                 K  sF   | j s|   |s| j}|tdtt|t|d}| d uS )NzSELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='SEQUENCE' and TABLE_NAME=:name AND TABLE_SCHEMA=:schema_name)r   schema_name)	r  _sequences_not_supportedr  r  r4   re   r  r=  r  )r   r  sequence_namer3   r   r6   rt   rt   ru   has_sequence  s   zMySQLDialect.has_sequencec                 C  s   t d)NzBSequences are supported only by the MariaDB series 10.3 or greaterr  r   rt   rt   ru   r  )  s   z%MySQLDialect._sequences_not_supportedc                 K  sJ   | j s|   |s| j}|tdt|d}dd | j|| jdD S )NzjSELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='SEQUENCE' and TABLE_SCHEMA=:schema_name)r  c                 S     g | ]}|d  qS r   rt   r  rt   rt   ru   rv   =  s    z3MySQLDialect.get_sequence_names.<locals>.<listcomp>r  )	r  r  r  r  r4   re   r  r  _connection_charset)r   r  r3   r   r6   rt   rt   ru   get_sequence_names/  s   zMySQLDialect.get_sequence_namesc                 C  s   |  || _tj| | | | | | | | | jr(| j	| | jd| _
| jo/| jdk| _| jo8| jdk| _| j oB| jdk| _| joK| jdk| _| joT| jdk| _| jo]| jdk| _|   d S )N)rg  )
   r/   )   )r  r   r  )r  r  )r  r   r  )_detect_charsetr  r7   ry  
initialize_detect_sql_mode_detect_ansiquotes_detect_casing_server_ansiquotesr   r   r  r  r  r  rO  _needs_correct_for_88718_96365r  r  r   _warn_for_known_db_issuesr  rt   rt   ru   r  D  s,   


zMySQLDialect.initializec                 C  s<   | j r| j}|dkr|dk rtd|f  d S d S d S d S )Nr  r  )r  r  	   a`  MariaDB %r before 10.2.9 has known issues regarding CHECK constraints, which impact handling of NULL values with SQLAlchemy's boolean datatype (MDEV-13596). An additional issue prevents proper migrations of columns with CHECK constraints (MDEV-11114).  Please upgrade to MariaDB 10.2.9 or greater, or use the MariaDB 10.1 series, to avoid these issues.)r  r  r5   r   )r   mdb_versionrt   rt   ru   r  s  s   z&MySQLDialect._warn_for_known_db_issuesc                 C  $   | j sdS | jr| j dkS | j dkS )NF)r     r  )r  r      r  r  r   rt   rt   ru   r,    
   

z MySQLDialect._support_float_castc                 C  r  )NF)r  r  r   )r  r      r   r   rt   rt   ru   r    r  z&MySQLDialect._support_default_functionc                 C  s   | j S rp   r  r   rt   rt   ru   _is_mariadb  s   zMySQLDialect._is_mariadbc                 C  s   | j  S rp   r  r   rt   rt   ru   r    s   zMySQLDialect._is_mysqlc                 C  s   | j o| jdkS )Nr  )r  r  r   rt   rt   ru   _is_mariadb_102  s   zMySQLDialect._is_mariadb_102c                 K  s   | d}dd |D S )NzSHOW schemasc                 S  r  r  rt   )rr   r  rt   rt   ru   rv         z1MySQLDialect.get_schema_names.<locals>.<listcomp>r  )r   r  r   r  rt   rt   ru   get_schema_names  s   
zMySQLDialect.get_schema_namesc                 K  sH   |dur|}n| j }| j}|d| j| }dd | j||dD S )z1Return a Unicode SHOW TABLES from a given schema.NSHOW FULL TABLES FROM %sc                 S  s    g | ]}|d  dkr|d qS )r   z
BASE TABLEr   rt   r  rt   rt   ru   rv     
    z0MySQLDialect.get_table_names.<locals>.<listcomp>r  r  r  r  r   rh  r  )r   r  r3   r   current_schemar  r  rt   rt   ru   get_table_names  s   
zMySQLDialect.get_table_namesc                 K  sB   |d u r| j }| j}|d| j| }dd | j||dD S )Nr  c                 S  s    g | ]}|d  dv r|d qS )r   )VIEWzSYSTEM VIEWr   rt   r  rt   rt   ru   rv     r	  z/MySQLDialect.get_view_names.<locals>.<listcomp>r  r
  )r   r  r3   r   r  r  rt   rt   ru   get_view_names  s   
zMySQLDialect.get_view_namesc                 K  *   | j |||fi |}|jr|jS t S rp   )_parsed_state_or_createtable_optionsr8   r   r  r  r3   r   parsed_statert   rt   ru   get_table_options     zMySQLDialect.get_table_optionsc                 K  r  rp   )r  r  r8   r  rt   rt   ru   get_columns  r  zMySQLDialect.get_columnsc                 K  sV   | j |||fi |}|jD ]}|d dkr&dd |d D }|d d  S qt S )Nr   PRIMARYc                 S  r  r  rt   rr   srt   rt   ru   rv     r  z2MySQLDialect.get_pk_constraint.<locals>.<listcomp>r  )constrained_columnsr   )r  keysr8   pk_constraint)r   r  r  r3   r   r  r   r   rt   rt   ru   get_pk_constraint  s   
zMySQLDialect.get_pk_constraintc                 K  s   | j |||fi |}d }g }|jD ]U}|d d }	t|d dkr(|d d p)|}
|
s:|d u r4|jj}||kr:|}
|d }|d }i }dD ]}||dd	vrV|| ||< qF|d
 ||
|	||d}|| q| jrq| || |ru|S t	
 S )Nr   r   r   localforeign)onupdateondeleteF)z	NO ACTIONNr   )r   r  referred_schemareferred_tablereferred_columnsoptions)r  fk_constraintsr  r   r  r  r   r  #_correct_for_mysql_bugs_88718_96365r8   foreign_keys)r   r  r  r3   r   r  default_schemafkeysr  ref_name
ref_schema	loc_names	ref_namescon_kwr  fkey_drt   rt   ru   get_foreign_keys  sB   
 zMySQLDialect.get_foreign_keysc                   s  | j dv r
dd }ndd }|jj}tdd }|D ]  | d p"|}| d } d	 D ]}|| | | q.q|rtjd
d | D  }	tt	j
jt	j
jt	j
j|	}
||
}tt}|D ]+\}}}||||||f d< ||||||f d< ||||||f | < qd|D ]3}|||d p|||d f   d |d< |d d ur d |d<  fdd|d	 D |d	< qd S d S )N)r   r  c                 S  s   |   S rp   r   r  rt   rt   ru   r   )  s   z?MySQLDialect._correct_for_mysql_bugs_88718_96365.<locals>.lowerc                 S  s   | S rp   rt   r4  rt   rt   ru   r   0  r   c                   S  s   t tS rp   )r   rh  rt   rt   rt   ru   <lambda>8  s    zBMySQLDialect._correct_for_mysql_bugs_88718_96365.<locals>.<lambda>r#  r$  r%  c                 s  s<    | ]\}}t tjj|kt jd d | D  V  qdS )c                 s  s:    | ]\}}t tjj|kt jtjj|V  qd S rp   )	r4   and__info_columnsr   r  funcr   column_namein_)rr   r   r  rt   rt   ru   r   F  s    

zMMySQLDialect._correct_for_mysql_bugs_88718_96365.<locals>.<genexpr>.<genexpr>N)r4   r6  r7  r   table_schemaor_r  )rr   r3   rV  rt   rt   ru   r   B  s    

zCMySQLDialect._correct_for_mysql_bugs_88718_96365.<locals>.<genexpr>
SCHEMANAME	TABLENAMEc                   s   g | ]} |   qS rt   r3  r   recrt   ru   rv   y  s    zDMySQLDialect._correct_for_mysql_bugs_88718_96365.<locals>.<listcomp>)_casingr   r  r   r   r4   r<  r  r   r7  r   r;  r  r9  wherer  r  r   )r   r+  r  r   r  schema_by_table_by_columnschtblcol_name	conditionr   correct_for_wrong_fk_casedr3   tnamecnamefkeyrt   r?  ru   r(    sX   




.z0MySQLDialect._correct_for_mysql_bugs_88718_96365c                 K  F   | j |||fi |}dd |jD }|jdd d |r|S t S )Nc                 S  s   g | ]}|d  |d dqS )r   sqltext)r   rN  rt   )rr   r  rt   rt   ru   rv     s    z6MySQLDialect.get_check_constraints.<locals>.<listcomp>c                 S     | d pdS Nr   ~rt   rI  rt   rt   ru   r5        z4MySQLDialect.get_check_constraints.<locals>.<lambda>r   )r  ck_constraintsr  r8   check_constraints)r   r  r  r3   r   r  cksrt   rt   ru   get_check_constraints}  s   z"MySQLDialect.get_check_constraintsc                 K  sD   | j |||fi |}|j| j dd }|d urd|iS t S )N_commentre   )r  r  r  r   r8   table_comment)r   r  r  r3   r   r  r  rt   rt   ru   get_table_comment  s   zMySQLDialect.get_table_commentc                 K  s.  | j |||fi |}g }|jD ]v}i }d}	|d }
|
dkrq|
dkr&d}	n|
dv r2|
|d| j < n|
d u r7n| jd|
 	 |d	 rL|d	 |d
| j < i }|d |d< dd |d D |d< dd |d D }|rq||d| j < |	|d< |
r{|
|d< |r||d< || q|jdd d |r|S t S )NFr   r  UNIQUET)FULLTEXTSPATIALr  z-Converting unknown KEY type %s to a plain KEYr  z%s_with_parserr   c                 S  r  r  rt   r  rt   rt   ru   rv     r  z,MySQLDialect.get_indexes.<locals>.<listcomp>r  column_namesc                 S  s&   i | ]}|d  dur|d |d  qS )r   Nr   rt   r  rt   rt   ru   r    s     z,MySQLDialect.get_indexes.<locals>.<dictcomp>z	%s_lengthr  r  c                 S  rO  rP  rt   rR  rt   rt   ru   r5    rS  z*MySQLDialect.get_indexes.<locals>.<lambda>r   )	r  r  r   loggerinfor   r  r8   indexes)r   r  r  r3   r   r  ra  r  r  r  flavorindex_dmysql_lengthrt   rt   ru   get_indexes  sT   
zMySQLDialect.get_indexesc                 K  rM  )Nc                 S  s:   g | ]}|d  dkr|d dd |d D |d dqS )r   r[  r   c                 S  r  r  rt   r   rt   rt   ru   rv     r  zBMySQLDialect.get_unique_constraints.<locals>.<listcomp>.<listcomp>r  )r   r^  duplicates_indexrt   r   rt   rt   ru   rv     s    z7MySQLDialect.get_unique_constraints.<locals>.<listcomp>c                 S  rO  rP  rt   rR  rt   rt   ru   r5    rS  z5MySQLDialect.get_unique_constraints.<locals>.<lambda>r   )r  r  r  r8   unique_constraints)r   r  r  r3   r   r  ucsrt   rt   ru   get_unique_constraints  s   	z#MySQLDialect.get_unique_constraintsc                 K  sH   | j }d| j||}| j|d ||d}| dr"t||S )Nr   r  zCREATE TABLE)	r  r   r   rl  _show_create_tabler?  r  r0   NoSuchTableError)r   r  	view_namer3   r   r  r  r4   rt   rt   ru   get_view_definition  s   
z MySQLDialect.get_view_definitionc                 K  s   | j ||||dd dS )N
info_cache)ro  )_setup_parserr  )r   r  r  r3   r   rt   rt   ru   r    s   
z$MySQLDialect._parsed_state_or_createc                 C  s   | j }t| |S )zreturn the MySQLTableDefinitionParser, generate if needed.

        The deferred creation ensures that the dialect has
        retrieved server version information first.

        )r   r  MySQLTableDefinitionParser)r   r   rt   rt   ru   _tabledef_parser  s   zMySQLDialect._tabledef_parserc           
      K  sf   | j }| j}d| j||}| j|d ||d}||r-| j|d ||d}	|||	}|	||S )Nr   rj  )
r  rr  r   r   rl  rk  _check_view_describe_table_describe_to_createparse)
r   r  r  r3   r   r  r  r  r4   r  rt   rt   ru   rp    s    
zMySQLDialect._setup_parserc                 C  sX   | j }| jr| jdk rd| }d}nd| }d}||}| j||d}|s(d S || S )N)r     zSHOW VARIABLES LIKE '%s'r   zSELECT @@%sr   r  )r  r  r  r  )r   r  setting_namer  r4   	fetch_colshow_varr  rt   rt   ru   _fetch_setting  s   
zMySQLDialect._fetch_settingc                 C  r  rp   r  r  rt   rt   ru   r  (  r  zMySQLDialect._detect_charsetc                 C  sH   |  |d}|du rd}n|dkrd}n|dkrd}nt|}|| _|S )zSniff out identifier case sensitivity.

        Cached per-connection. This value can not change without a server
        restart.

        lower_case_table_namesNr   OFFONr   )r{  rX   rA  )r   r  settingcsrt   rt   ru   r  +  s   	zMySQLDialect._detect_casingc                 C  s:   i }| j }|d}| ||D ]
}|d ||d < q|S )zYPull the active COLLATIONS list from the server.

        Cached per-connection.
        zSHOW COLLATIONr   r   )r  r  r  )r   r  
collationsr  r  r  rt   rt   ru   _detect_collationsC  s   
zMySQLDialect._detect_collationsc                 C  s6   |  |d}|d u rtd d| _d S |pd| _d S )Nsql_modez[Could not retrieve SQL_MODE; please ensure the MySQL user has permissions to SHOW VARIABLESr   )r{  r5   r   	_sql_mode)r   r  r  rt   rt   ru   r  P  s   
zMySQLDialect._detect_sql_modec                 C  sL   | j }|sd}n| rt|}|dB |krdpd}d|v | _d|v| _dS )z/Detect and adjust for the ANSI_QUOTES sql mode.r   r  ANSI_QUOTESNO_BACKSLASH_ESCAPESN)r  isdigitrX   r  r3  )r   r  modemode_nort   rt   ru   r  \  s   
zMySQLDialect._detect_ansiquotesc           	   
   C  s   |du r
| j |}d| }d}z|jdd|}W n tjy7 } z| |jdkr2t|| d}~ww | j	||d}|sFt||d 
 S )z&Run SHOW CREATE TABLE for a ``Table``.NzSHOW CREATE TABLE %sTr  r  r  r   )r   r  r  r  r0   r  r  r  rl  r  strip)	r   r  r   r  r  str  rZ  r  rt   rt   ru   rk  k  s(   
zMySQLDialect._show_create_tablec           
   
   C  s   |du r
| j |}d| }d\}}zHz|jdd|}W n, tjyJ } z| |j}	|	dkr7t|||	dkrEt	d||f | d}~ww | j
||d	}W |rY|  |S |rb|  w w )
z7Run DESCRIBE for a ``Table`` and return processed rows.NzDESCRIBE %sNNTr  r  iL  z1Table or view named %s could not be reflected: %sr  )r   r  r  r  r0   r  r  r  rl  UnreflectableTableErrorr  r  )
r   r  r   r  r  r  r  rowsrZ  codert   rt   ru   rt    sB   
zMySQLDialect._describe_table)NNN)TFrp   r  )sr   r   r   __doc__r   supports_statement_cachesupports_altersupports_native_booleanmax_identifier_lengthmax_index_name_lengthmax_constraint_name_lengthdiv_is_floordivsupports_native_enumreturns_native_bytesr  sequences_optionalrO  r   supports_default_valuessupports_default_metavaluers  __annotations__rA   ANY_AUTOINCREMENT"insertmanyvalues_implicit_sentinelsupports_sane_rowcountsupports_sane_multi_rowcountsupports_multivalues_insert#insert_null_pk_still_autoincrementssupports_commentsinline_commentsdefault_paramstylecolspecscte_follows_insertr   statement_compilerr  ddl_compilerr  type_compiler_clsischema_namesra  r   r  r  r3  r  r  Tabler4   UpdateDeleter  Indexconstruct_argumentsrf  r  r  r  classmethodr  r  r  r|  r  r  r  r  r  r  r  r  r  r  r  r   cacher  r  r  r  r  r  propertyr,  r  r  r  r  r  r  r  r  r  r  r2  r(  rW  rZ  re  ri  rn  r  r5   memoized_propertyrr  rp  r{  r  r  r  r  r  rk  rt  rt   rt   rt   ru   ro  	  s  
 

&






-/







		)d
3




ro  c                   @  s:   e Zd ZdZdddddddZdd	 Zd
d Zdd ZdS )r  zReturn unicode-decoded values based on type inspection.

    Smooth over data type issues (esp. with alpha driver versions) and
    normalize strings as Unicode regardless of user-configured driver
    encoding settings.

    koi8_rkoi8_uz	utf-16-beutf8ujis)koi8rkoi8uutf16utf8mb4utf8mb3eucjpmsc                 C  s   || _ | j||| _d S rp   )rowproxy_encoding_compatr  r  )r   r  r  rt   rt   ru   rf    s   z_DecodingRow.__init__c                 C  s<   | j | }t|tr| }| jrt|tr|| jS |S rp   )r  r   _arraytostringr  r  r  )r   r  itemrt   rt   ru   __getitem__  s   

z_DecodingRow.__getitem__c                 C  s>   t | j|}t|tr| }| jrt|tr|| jS |S rp   )r$  r  r   r  r  r  r  r  )r   r  r  rt   rt   ru   __getattr__  s   
z_DecodingRow.__getattr__N)r   r   r   r  r  rf  r  r  rt   rt   rt   ru   r    s    

r  r  r;  rq  r  r9  information_schema)r  
__future__r   r   r  collectionsr   	itertoolsr   r  typingr   r   r   r  
enumeratedr	   r
   rZ   r   r   r   rm  r   r   typesr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r0   r1   r2   r3   r  r4   r5   enginer6   r{   r7   engine.reflectionr8   r9   r:   r;   r<   r=   r>   r?   rQ  r@   sql.compilerrA   rB   
sql.schemarC   rD   rE   rF   rG   rH   rI   rJ   r  Ir  SET_REMSTimeMSSetMSEnum
MSLongBlobMSMediumBlob
MSTinyBlobMSBlobMSBinaryMSVarBinaryMSNChar
MSNVarCharMSCharMSString
MSLongTextMSMediumText
MSTinyTextMSTextMSYearMSTimeStampMSBitMSSmallIntegerMSTinyIntegerMSMediumIntegerMSBigInteger	MSNumeric	MSDecimalMSDoubleMSRealMSFloat	MSIntegerr   r+  Doubler'  Enum	MatchTyper  r  DefaultExecutionContextro   r   DDLCompilerr  GenericTypeCompilerr  IdentifierPreparerra  rn  class_loggerry  ro  r  r   r   r7  rt   rt   rt   ru   <module>   s  	        	
 !"#(+    T  1  5       |/
