o
    [h                    @   s*  d Z ddlmZ ddlmZ ddl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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-d0lm7Z8 d-d1lm9Z9 d-d2lmZ: d-d3lm;Z; d-d4l<m=Z= d-dl<mZ d-d5l9m>Z> d-d6l9m?Z? d-d7l9m@Z@ d-d3l9m;ZA d-d8lmBZB d-d9lmCZC d-d:lmDZD d-d;lmEZE d-d<lmFZF d-d=l;mGZG eHg d>ZIeJd?ejKejLB ZMeJd@ejKejLB ZNe.ZOeZPeZQe#ZRe%ZSe0ZTeCZUeBZVeFZWe(ZXe*ZYeZZe3Z[e$Z\e'Z]e2Z^e-Z_e4Z`e/ZaeZbe,Zce1Zde&ZeeZfe)ZgeZhe Zie+Zje!Zke"Zleeeeeee:jme)e:jne!e:joe.e:jpee:jqee:jee:jjee:jjeiZri dAedBeBdCedDeCdEeDdFedGeEdHedIedJe dKedLedMe!dNe"dOe"dPedQe#i dRe$dSe%dTe&dUe'dVe(dWe*dXe)dYedZe,d[e-d\e.d]e/d^e0d_e1d`e2daeFdbe3dce4iZsG ddde dee=jtZuG dfdg dge>jvZwG dhdi die>jxZyG djdk dke>jzZ{G dldm dme>j|Z}e6j~G dndo doe=jZG dpdq dqeZdS )raz  

.. dialect:: mysql
    :name: MySQL

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

SQLAlchemy supports MySQL starting with version 4.1 through modern releases.
However, no heroic measures are taken to work around major missing
SQL features - if your server version does not support sub-selects, for
example, they won't work in SQLAlchemy either.

See the official MySQL documentation for detailed information about features
supported in any given server release.

.. _mysql_connection_timeouts:

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

MySQL features 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
------------------------------------------------

MySQL'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"
       )

The MySQL dialect 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 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``.

.. seealso::

    `The InnoDB Storage Engine
    <http://dev.mysql.com/doc/refman/5.0/en/innodb-storage-engine.html>`_ -
    on the MySQL website.

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

MySQL has 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
database itself, especially if database reflection features are
to be used.

.. _mysql_isolation_level:

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

All MySQL 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://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 MySQL connection will return true for the value of
``SELECT @@autocommit;``.

.. 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 MySQLdb and PyMySQL dialects.
From a MySQL point of view this means that the ``MySQLdb.cursors.SSCursor`` or
``pymysql.cursors.SSCursor`` class is used when building up the cursor which
will receive results.  The most typical way of invoking this feature is via the
:paramref:`.Connection.execution_options.stream_results` connection execution
option.   Server side cursors can also be enabled for all SELECT statements
unconditionally by passing ``server_side_cursors=True`` to
:func:`_sa.create_engine`.

.. versionadded:: 1.1.4 - added server-side cursor support.

.. _mysql_unicode:

Unicode
-------

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

Most MySQL 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 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 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 schema and/or server configuration may be
required.

.. seealso::

    `The utf8mb4 Character Set \
    <http://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::

    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::

    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 features 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 ``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 Extensions
--------------------

Many of the MySQL 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 MySQL statement can be executed as a string as well.

Some limited direct support for MySQL 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(..., mysql_limit=10)

* 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")

.. _mysql_insert_on_duplicate_key_update:

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

MySQL allows "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`::

    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'
    )

    conn.execute(on_duplicate_key_stmt)

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::

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

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

    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:`updates_order_parameters`.  Unlike the :class:`_expression.Update`
object,
no special flag is needed to specify the intent since the argument form is
this context is unambiguous::

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

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

.. warning::

    The :meth:`_expression.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::

    from sqlalchemy.dialects.mysql import insert

    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
    )
    conn.execute(do_update_stmt)

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.ResultProxy.rowcount`


CAST Support
------------

MySQL documents the CAST operator as available in version 4.0.2.  When using
the SQLAlchemy :func:`.cast` function, SQLAlchemy
will not render the CAST token on MySQL before this version, based on server
version detection, instead rendering the internal expression directly.

CAST may still not be desirable on an early MySQL version post-4.0.2, as it
didn't add all datatype support until 4.1.1.   If your application falls into
this narrow area, the behavior of CAST can be controlled using the
:ref:`sqlalchemy.ext.compiler_toplevel` system, as per the recipe below::

    from sqlalchemy.sql.expression import Cast
    from sqlalchemy.ext.compiler import compiles

    @compiles(Cast, 'mysql')
    def _check_mysql_version(element, compiler, **kw):
        if compiler.dialect.server_version_info < (4, 1, 0):
            return compiler.process(element.clause, **kw)
        else:
            return compiler.visit_cast(element, **kw)

The above function, which only needs to be declared once
within an application, overrides the compilation of the
:func:`.cast` construct to check for version 4.1.0 before
fully rendering CAST; else the internal element of the
construct is rendered directly.


.. _mysql_indexes:

MySQL Specific Index Options
----------------------------

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

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

MySQL provides 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`` parameter::

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

    Index('a_b_idx', my_table.c.a, my_table.c.b, mysql_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 only allows 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.

.. versionadded:: 1.1.5

.. seealso::

    `CREATE INDEX <http://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')

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

    PrimaryKeyConstraint("data", mysql_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:

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

http://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")

.. versionadded:: 1.3


.. _mysql_foreign_keys:

MySQL Foreign Keys
------------------

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

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

MySQL does not 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.  In order to use these keywords on a foreign key while having
them ignored on a MySQL backend, use a custom compile rule::

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

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

.. versionchanged:: 0.9.0 - the MySQL backend no longer silently ignores
   the ``deferrable`` or ``initially`` keyword arguments of
   :class:`_schema.ForeignKeyConstraint` and :class:`_schema.ForeignKey`.

The "MATCH" keyword is in fact more insidious, and is explicitly disallowed
by SQLAlchemy in conjunction with the MySQL backend.  This argument is
silently ignored by MySQL, 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 backend; as is the case with DEFERRABLE and
INITIALLY, custom compilation rules can be used to correct a MySQL
ForeignKeyConstraint at DDL definition time.

.. versionadded:: 0.9.0 - the MySQL backend will raise a
   :class:`.CompileError` when the ``match`` keyword is used with
   :class:`_schema.ForeignKeyConstraint` or :class:`_schema.ForeignKey`.

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

Not all MySQL 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=True
       )

.. seealso::

    :ref:`mysql_storage_engines`

.. _mysql_unique_constraints:

MySQL 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 when emitting DDL to create
these constraints.  However, MySQL does not have a unique constraint
construct that is separate from a unique index; that is, the "UNIQUE"
constraint on MySQL 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.  However, when performing
full table reflection using ``Table(..., autoload=True)``,
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's explicit_defaults_for_timestamp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

MySQL has 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
<http://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::

    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
<http://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://scott:tiger@localhost/test", echo=True)
    m.create_all(e)

output::

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

.. versionchanged:: 1.0.0 - SQLAlchemy now renders NULL or NOT NULL in all
   cases for TIMESTAMP columns, to accommodate
   ``explicit_defaults_for_timestamp``.  Prior to this version, it will
   not render "NOT NULL" for a TIMESTAMP column that is ``nullable=False``.

    )array)defaultdictN)literal_column)visitors   )
reflection)ENUM)SET)JSON)JSONIndexType)JSONPathType)
_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)log)schema)sql)types)util)default)compiler)elements)	operators)BINARY)BLOB)BOOLEAN)DATE)	VARBINARY)topological(!  Z
accessibleactionaddZadminallZalterZanalyzeandr   asascZ
asensitivebeforeZbetweenbigintbinaryblobZbothZbycallZcascadecaseZchangechar	charactercheckZcollatecolumncolumns	condition
constraintcontinueconvertcreatecrossZcubeZ	cume_distZcurrent_datecurrent_timeZcurrent_timestampcurrent_usercursorZdatabaseZ	databasesZday_hourZday_microsecondZ
day_minuteZ
day_seconddecdecimalZdeclarer3   ZdelayeddeleteZdescZdescribeZdeterministicZdistinctZdistinctrowdivdoubledropZdualZeachelseZelseifemptyZenclosedescapedexceptexistsexitZexplainfalsefetchfieldsZfirst_valuefloatZfloat4Zfloat8forforceforeignfromZfulltextfunctionZgeneral	generatedgetZgrantgroupgroupinggroupsZhavingZhigh_priorityZhour_microsecondZhour_minuteZhour_secondifignoreZignore_server_idsinindexinfileinnerZinoutZinsensitiveinsertintZint1Zint2Zint3Zint4Zint8integerintervalZintoZio_after_gtidsZio_before_gtidsisZiteratejoinZ
json_tablekeykeyskill
last_valueZlateralleadingZleaveleftlevellikelimitlinearr   linesload	localtimeZlocaltimestamplocklonglongbloblongtextloopZlow_priorityZmaster_bindZmaster_heartbeat_periodmaster_ssl_verify_server_certr   matchZmaxvalue
mediumblob	mediumint
mediumtextmemberZ	middleintZminute_microsecondZminute_secondmodmodeZmodifiesZnaturalZno_write_to_binlognotZ	nth_valueZntilenullnumericofonZone_shotoptimizeZoptimizer_costsoptionZ
optionallyororderoutouteroutfileZover	partitionZpercent_rankZpersistZpersist_only	precisionprimaryZ
privilegesZ	procedurepurgeranger   Zrankread	read_onlyr   
read_writer   Zreadsreal	recursiveZ
referencesregexpreleaserenamerepeatreplacerequireZresignalZrestrictreturnZrevokerightZrlikeZrolerowZ
row_numberrowsr/   ZschemasZsecond_microsecondselectZ	sensitive	separatorsetshowsignalZslowsmallintZsonameZspatialZspecificr0   Zsql_after_gtidsZsql_before_gtidsZsql_big_resultZsql_calc_found_rowsZsql_small_resultZsqlexceptionZsqlstateZ
sqlwarningsslstartingstatusZstoredZstraight_joinsystemtabletablesZ
terminatedtextZthentimetinyblobtinyinttinytexttoZtrailingtriggertrueZundounionuniqueunlockunsignedupdateusageZuseusingZutc_dateZutc_timeZutc_timestampvalues	varbinaryvarcharZvarcharacterZvaryingZvirtualwhenwherewhileZwindowwithwritex509xorZ
year_monthzerofillz@\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER|LOAD +DATA|REPLACE)z%\s*SET\s+(?:(?:GLOBAL|SESSION)\s+)?\wrD   rE   bitrF   booleanrI   datedatetimerX   r[   enumfixedrf   rx   ry   jsonr   r   r   r   r   ZncharZnvarcharr   r   r   r   r   	timestampr   r   r   r   r   yearc                   @   s   e Zd Zdd Zdd ZdS )MySQLExecutionContextc                 C   s
   t |S N)AUTOCOMMIT_REr   )self	statement r   /home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/sqlalchemy/dialects/mysql/base.pyshould_autocommit_text     
z,MySQLExecutionContext.should_autocommit_textc                 C   s   | j jr| j| j jS t r   )dialectZsupports_server_side_cursorsZ_dbapi_connectionrV   Z	_sscursorNotImplementedErrorr   r   r   r   create_server_side_cursor  s   z/MySQLExecutionContext.create_server_side_cursorN)__name__
__module____qualname__r   r   r   r   r   r   r     s    r   c                       s  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dZdd Z fddZdd  Zd!d" Zd#d$ Zd=d&d'Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Z d6d7 Z!d8d9 Z"d:d; Z#  Z$S )>MySQLCompilerTZmillisecondsZmillisecondc                 C   s&   | j r| j d d }|jdurdS dS )zlCalled when a ``SELECT`` statement has no froms,
        and no ``FROM`` clause is to be appended.

        Z
selectableNz
 FROM DUAL )stackZ_whereclause)r   stmtr   r   r   default_from"  s
   
zMySQLCompiler.default_fromc                 K   s   d|  | S )Nzrand%s)Zfunction_argspecr   fnkwr   r   r   visit_random_func.     zMySQLCompiler.visit_random_funcc                 K      dS )Nz	SYSDATE()r   r   r   r   r   visit_sysdate_func1     z MySQLCompiler.visit_sysdate_funcc                 K   sB  |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 }nH|j jtju rod| j|jfi || j|jfi |f }n*|j jtj	u ryd}n |j jtj
u rd| j|jfi || j|jfi |f }nd}|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)z1ELSE CAST(JSON_EXTRACT(%s, %s) AS DECIMAL(10, 6))zWHEN true THEN true ELSE falsez'ELSE JSON_UNQUOTE(JSON_EXTRACT(%s, %s))zELSE JSON_EXTRACT(%s, %s) z END)typeZ_type_affinitysqltypesr
   processr   r   IntegerNumericBooleanString)r   rE   operatorr   Zcase_expressiontype_expressionr   r   r    _render_json_extract_from_binary4  s@   z.MySQLCompiler._render_json_extract_from_binaryc                 K      | j ||fi |S r   r  r   rE   r  r   r   r   r   visit_json_getitem_op_binaryh     z*MySQLCompiler.visit_json_getitem_op_binaryc                 K   r  r   r  r  r   r   r   !visit_json_path_getitem_op_binaryk  r  z/MySQLCompiler.visit_json_path_getitem_op_binaryc                    sT  j jr'dd jD }t|fdd|D fddjjD  }njj}g }fdd|D D ]H j j }t|rVtj	d | j
d}j| dd	}n fd
d}t|i |}j| dd	}j j}	|d|	|f  q6tjtdd |D  }
|
rtdjjjddd |
D f  dd| S )Nc                 S   s   g | ]}t |qS r   )r5   Z_column_as_key.0r}   r   r   r   
<listcomp>r  s    z?MySQLCompiler.visit_on_duplicate_key_update.<locals>.<listcomp>c                    s$   g | ]}| j jv r j j| qS r   )r   cr  )r   r   r   r  w  s
    
c                    s   g | ]	}|j  vr|qS r   r}   r  r  )ordered_keysr   r   r  {  s    c                 3   s     | ]}|j  jv r|V  qd S r   )r}   r   r  col)on_duplicater   r   	<genexpr>  s    z>MySQLCompiler.visit_on_duplicate_key_update.<locals>.<genexpr>)type_F)
use_schemac                    sb   t | tjr| jjr|  }  j| _| S t | tjr/| jju r/t	dj
 j d } | S d S )NzVALUES())
isinstancer5   BindParameterr  Z_isnullZ_cloneColumnClauser   Zinserted_aliasr   preparerquotename)obj)rL   r  r   r   r   r     s   

z<MySQLCompiler.visit_on_duplicate_key_update.<locals>.replacez%s = %sc                 s   s    | ]}|j V  qd S r   r  r  r   r   r   r    s    zFAdditional column names not matching any column keys in table '%s': %s, c                 s   s    | ]}d | V  qdS )'%s'Nr   r  r   r   r   r        zON DUPLICATE KEY UPDATE )Zcurrent_executableZ_parameter_orderingr   r   r  r   r}   r5   Z_is_literalr$  r  r  
self_groupr   Zreplacement_traverser&  r'  r(  appendr2   warnr   r|   )r   r  r   Zparameter_orderingcolsZclausesvalZ
value_textr   Z	name_textZnon_matchingr   )rL   r  r  r   r   r   visit_on_duplicate_key_updaten  sB   

	z+MySQLCompiler.visit_on_duplicate_key_updatec                 K   ,   d| j |jfi || j |jfi |f S )Nzconcat(%s, %s)r  r   r   r  r   r   r   visit_concat_op_binary     z$MySQLCompiler.visit_concat_op_binaryc                 K   r3  )Nz'MATCH (%s) AGAINST (%s IN BOOLEAN MODE)r4  r  r   r   r   visit_match_op_binary  r6  z#MySQLCompiler.visit_match_op_binaryc                 C   s   |S r   r   )r   r   r   r   r   r   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 d S )
Nr   FzUNSIGNED INTEGERzSIGNED INTEGERr   r7   r
   r    r   )r  Zdialect_implr   r#  r  ZTypeDecoratorvisit_typeclauseimplr  getattrr&   r   DateTimeDateTimetype_compilerr  r  r   r	   r   Z_adapt_string_for_castZ_Binaryr
   r    r   )r   
typeclauser   r   Zadaptedr   r   r   r9    sB   	
zMySQLCompiler.visit_typeclausec                 K   s   | j jstd | j|j fi |S | |j}|d u r9td| j j|jj	  | j|j fi |S d| j|jfi ||f S )NzFCurrent MySQL version does not support CAST; the CAST will be skipped.zEDatatype %s does not support CAST on MySQL; the CAST will be skipped.zCAST(%s AS %s))
r   _supports_castr2   r/  r  Zclauser-  r@  r?  r  )r   castr   r   r   r   r   
visit_cast  s   zMySQLCompiler.visit_castc                    s*   t t| ||}| jjr|dd}|S )N\z\\)superr   render_literal_valuer   _backslash_escapesr   )r   valuer   	__class__r   r   rF    s   z"MySQLCompiler.render_literal_valuec                 K   r  )Nr   r   r   elementr   r   r   r   
visit_true  r  zMySQLCompiler.visit_truec                 K   r  )Nrc   r   rK  r   r   r   visit_false  r  zMySQLCompiler.visit_falsec                 K   s*   t |jtjr|j d S |jrdS dS )zAdd special MySQL keywords in place of DISTINCT.

        .. note::

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

        r  z	DISTINCT r   )r#  Z	_distinctr2   string_typesupper)r   r   r   r   r   r   get_select_precolumns  s
   
z#MySQLCompiler.get_select_precolumnsFc              
   K   sh   |j rd}n|jrd}nd}d| j|jfddi||| j|jfddi|d| j|jfi |fS )Nz FULL OUTER JOIN z LEFT OUTER JOIN z INNER JOIN r   asfromTz ON )fullZisouterr|   r  r   r   Zonclause)r   r|   rR  kwargsZ	join_typer   r   r   
visit_join  s   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rPjjrK|d7 }|S td	 |S )
Nz LOCK IN SHARE MODEz FOR UPDATEz OF r*  c                 3   s(    | ]}j |fd dd V  qdS )TF)ashintr!  N)r  )r  r   r   r   r   r   r  7  
    
z2MySQLCompiler.for_update_clause.<locals>.<genexpr>z NOWAITz SKIP LOCKEDzbSKIP LOCKED ignored on non-supporting MariaDB backend. This will raise an error in SQLAlchemy 1.4.)Z_for_update_argr   r   r   supports_for_update_ofr2   Z
OrderedSetr   sql_utilZsurface_selectables_onlyr|   ZnowaitZskip_locked	_is_mysqlr/  )r   r   r   tmpr   r  r   rW  r   for_update_clause+  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, %sZ18446744073709551615z 
 LIMIT %s)Z_limit_clauseZ_offset_clauser  )r   r   r   limit_clauseZoffset_clauser   r   r   r^  J  s    
zMySQLCompiler.limit_clausec                 C   s&   |j d| jj d }|rd| S d S )Nz%s_limitzLIMIT %s)rT  rm   r   r(  )r   update_stmtr   r   r   r   update_limit_clauser  s   z!MySQLCompiler.update_limit_clausec                    s$   d  fdd|gt| D S )Nr*  c                 3   s&    | ]}|j fd di V  qdS )rR  TNZ_compiler_dispatchr  trW  r   r   r  z  s
    
z5MySQLCompiler.update_tables_clause.<locals>.<genexpr>)r|   list)r   r_  
from_tableextra_fromsr   r   rW  r   update_tables_clausey  s   z"MySQLCompiler.update_tables_clausec                 K   s   d S r   r   )r   r_  re  rf  
from_hintsr   r   r   r   update_from_clause  s   z MySQLCompiler.update_from_clausec                 C   s   d}|rd}|j | dd|dS )z=If we have extra froms make sure we render any alias as hint.FT)rR  ZiscrudrV  ra  )r   delete_stmtre  rf  rV  r   r   r   delete_table_clause  s   z!MySQLCompiler.delete_table_clausec                    s&   dd  fdd|g| D  S )z4Render the DELETE .. USING clause specific to MySQL.zUSING r*  c                 3   s(    | ]}|j fd  dV  qdS )T)rR  Z	fromhintsNra  rb  rh  r   r   r   r   r    rX  z9MySQLCompiler.delete_extra_from_clause.<locals>.<genexpr>)r|   )r   rj  re  rf  rh  r   r   rl  r   delete_extra_from_clause  s   
z&MySQLCompiler.delete_extra_from_clausec                 C   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_%sNr   r  idxr   r   r   r   r    s
    
z5MySQLCompiler.visit_empty_set_expr.<locals>.<genexpr>c                 s   rn  )z_in_%sNr   ro  r   r   r   r        
)rv   r   )r|   	enumerate)r   Zelement_typesr   r   r   visit_empty_set_expr  s   

z"MySQLCompiler.visit_empty_set_exprc                 K      d|  |j|  |jf S )NzNOT (%s <=> %s)r4  r  r   r   r   visit_is_distinct_from_binary     

z+MySQLCompiler.visit_is_distinct_from_binaryc                 K   rt  )Nz	%s <=> %sr4  r  r   r   r    visit_isnot_distinct_from_binary  rv  z.MySQLCompiler.visit_isnot_distinct_from_binaryr   F)%r   r   r   Z'render_table_with_column_in_update_fromr4   SQLCompilerZextract_mapcopyr   r   r   r  r  r  r  r2  r5  r7  r8  r9  rC  rF  rM  rN  rQ  rU  r]  r^  r`  rg  ri  rk  rm  rs  ru  rw  __classcell__r   r   rI  r   r     s@    4C
&
(		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jj|j|dg}|jdur|| |j t|j	| jt
j}|js2|d n
|jr<|r<|d | |}|durL|d|  |j}|durc| j|t
 }|d|  |jdurx||jju rx|jdu rx|d d|S )	zBuilds column DDL.)r  NzNOT NULLZNULLzDEFAULT zCOMMENT ZAUTO_INCREMENTr  )r&  format_columnr   r?  r  r  Zcomputedr.  r#  Z_unwrapped_dialect_implr  r&   ZnullableZget_column_default_stringcommentsql_compilerrF  r  r   Z_autoincrement_columnZserver_defaultr|   )r   rL   r   ZcolspecZis_timestampr3   r~  literalr   r   r   get_column_specification  s:   








z)MySQLDDLCompiler.get_column_specificationc           
         s2  g }t  fdd|j D }|jdur|j|d< g d}t||}t||}tg d|D ]0}|| }|t	j
v rH j|t }|dv rR|dd	}d
}	|dv rZd	}	||	||f q4tg d|D ]&}|| }|t	j
v r j|t }|dd	}d	}	||	||f qmd	|S )z9Build table-level CREATE options like ENGINE and COLLATE.c                 3   sF    | ]\}}| d  jj r|t jjd d  |fV  qdS )z%s_r   N)
startswithr   r(  lenrP  )r  kvr   r   r   r    s    
z5MySQLDDLCompiler.post_create_table.<locals>.<genexpr>NCOMMENT)PARTITION_BY
PARTITIONSSUBPARTITIONSSUBPARTITION_BY))DEFAULT_CHARSETCOLLATE)DEFAULT_CHARACTER_SETr  )CHARSETr  )CHARACTER_SETr  )ZDATA_DIRECTORYZINDEX_DIRECTORYr  r  r  ZDEFAULT_COLLATE_r  =)Z
TABLESPACEzDEFAULT CHARACTER SETzCHARACTER SETr  ))r  r  )r  r  )r  r  )r  r  )r  r  )r  r  )dictrT  itemsr~  r   
differenceintersectionr<   sort_reflectionZ_options_of_type_stringr  rF  r  r  r   r.  r|   )
r   r   Z
table_optsoptsZpartition_optionsZnonpart_optionsZpart_optionsoptargjoinerr   r   r   post_create_table  sJ   

	


z"MySQLDDLCompiler.post_create_tablec                    sB  |j }| j}||j}fdd|jD }|}d}|jr)|d7 }|j	dd }	|	r8||	d 7 }|d||f 7 }|j
d d	   d urnt trad
 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                    sR   g | ]%} j jt|tjs!t|tjr|jtjtj	fvr!t
|n|d ddqS )FT)Zinclude_tableZliteral_binds)r  r  r#  r5   r%  ZUnaryExpressionmodifierr6   Zdesc_opZasc_opZGrouping)r  exprr   r   r   r  <  s     



	z7MySQLDDLCompiler.visit_create_index.<locals>.<listcomp>zCREATE zUNIQUE mysql_prefixr  zINDEX %s ON %s mysql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(  )r  r  r  r  r   r   r  a  s    

z6MySQLDDLCompiler.visit_create_index.<locals>.<genexpr>c                 3   s    | ]	}d | f V  qdS )r  Nr   r  r  r   r   r  n  rq  z(%s)with_parserz WITH PARSER %sr   	 USING %s)rL  Z_verify_index_tabler&  format_tabler   Zexpressions_prepared_index_namer   rT  rm   dialect_optionsr#  r  r|   zipr'  )r   rR   r   rt   r&  r   rM   r(  r   Zindex_prefixparserr   r   )r  r   r   visit_create_index6  sB   







z#MySQLDDLCompiler.visit_create_indexc                    s:   t t| |}|jd d }|r|d| j| 7 }|S )Nr  r   r  )rE  r|  visit_primary_key_constraintr  r&  r'  )r   rO   r   r   rI  r   r   r    s   
z-MySQLDDLCompiler.visit_primary_key_constraintc                 C   s&   |j }d| j|dd| j|jf S )Nz
DROP INDEX %s ON %sF)Zinclude_schema)rL  r  r&  r  r   )r   r\   rt   r   r   r   visit_drop_index  s
   z!MySQLDDLCompiler.visit_drop_indexc                 C   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   zINDEX zCONSTRAINT zCHECK zALTER TABLE %s DROP %s%s)rL  r#  	sa_schemaZForeignKeyConstraintr&  Zformat_constraintPrimaryKeyConstraintZUniqueConstraintZCheckConstraintr   _is_mariadbr  r   )r   r\   rO   Zqualconstr   r   r   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   )r   r-   CompileError)r   rO   r   r   r   define_constraint_match  s
   
z(MySQLDDLCompiler.define_constraint_matchc                 C   s(   d| j |j| j|jjt f S )NzALTER TABLE %s COMMENT %s)r&  r  rL  r  rF  r~  r  r  r   rR   r   r   r   visit_set_table_comment  s   z(MySQLDDLCompiler.visit_set_table_commentc                 C   s   d| j |j S )NzALTER TABLE %s COMMENT '')r&  r  rL  r  r   r   r   visit_drop_table_comment  s   z)MySQLDDLCompiler.visit_drop_table_commentc                 C   s,   d| j |jj| j |j| |jf S )NzALTER TABLE %s CHANGE %s %s)r&  r  rL  r   r}  r  r  r   r   r   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{  r   r   rI  r   r|    s    .UI	r|  c                       sL  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  fd=d>Z!d?d@ Z"dAdB Z#dCdD Z$dEdF Z%dGdH Z&dIdJ Z'dKdL Z(dMdN Z)  Z*S )O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   r   )r   r   specr   r   r   _extend_numeric  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 r   )r;  rm   r  defaultsr   r   r   attr     z.MySQLTypeCompiler._extend_string.<locals>.attrcharsetzCHARACTER SET %sasciiASCIIunicodeUNICODEN	collationz
COLLATE %srE   r7   nationalr  c                 S      g | ]}|d ur|qS r   r   r  r   r   r   r        z4MySQLTypeCompiler._extend_string.<locals>.<listcomp>ZNATIONALc                 S   r  r   r   r  r   r   r   r    r  )r  r|   )r   r   r  r  r  r  r  r   r  r   _extend_string  s(   z MySQLTypeCompiler._extend_stringc                 C   s   t |ttfS r   )r#  r   r   )r   r   r   r   r   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   scaler   r  r  r   r   r   r   r   r   visit_NUMERIC     

zMySQLTypeCompiler.visit_NUMERICc                 K   r  )Nr   zDECIMAL(%(precision)s)r   z!DECIMAL(%(precision)s, %(scale)s)r  r  r  r   r   r   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  r   r   r   visit_DOUBLE     zMySQLTypeCompiler.visit_DOUBLEc                 K   r  )NzREAL(%(precision)s, %(scale)s)r  r"   r  r  r   r   r   
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  r   r   r   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  r   r   r   visit_INTEGER;     zMySQLTypeCompiler.visit_INTEGERc                 K   r  )NzBIGINT(%(display_width)s)r  r   r  r  r   r   r   visit_BIGINTE  r  zMySQLTypeCompiler.visit_BIGINTc                 K   r  )NzMEDIUMINT(%(display_width)s)r  r   r  r  r   r   r   visit_MEDIUMINTO  r  z!MySQLTypeCompiler.visit_MEDIUMINTc                 K   s2   |  |r|jd ur| |d|j S | |dS )NzTINYINT(%s)r(   r  r  r   r   r   visit_TINYINTY  s
   
zMySQLTypeCompiler.visit_TINYINTc                 K   r  )NzSMALLINT(%(display_width)s)r  r#   r  r  r   r   r   visit_SMALLINTa  r  z MySQLTypeCompiler.visit_SMALLINTc                 K   s   |j d ur
d|j  S dS )NzBIT(%s)r   r  r  r   r   r   	visit_BITk  s   

zMySQLTypeCompiler.visit_BITc                 K      t |dd rd|j S dS )NfspzDATETIME(%d)r   r;  r  r  r   r   r   visit_DATETIMEq     
z MySQLTypeCompiler.visit_DATETIMEc                 K   r  )Nr:   r   r  r   r   r   
visit_DATEw  r  zMySQLTypeCompiler.visit_DATEc                 K   r  )Nr  zTIME(%d)r%   r  r  r   r   r   
visit_TIMEz  r  zMySQLTypeCompiler.visit_TIMEc                 K   r  )Nr  zTIMESTAMP(%d)r&   r  r  r   r   r   visit_TIMESTAMP  r  z!MySQLTypeCompiler.visit_TIMESTAMPc                 K   s   |j d u rdS d|j  S )Nr+   zYEAR(%s))r  r  r   r   r   
visit_YEAR  s   

zMySQLTypeCompiler.visit_YEARc                 K   s(   |j r| |i d|j  S | |i dS )NzTEXT(%d)r$   r  r  r  r   r   r   
visit_TEXT  s   zMySQLTypeCompiler.visit_TEXTc                 K      |  |i dS )Nr)   r  r  r   r   r   visit_TINYTEXT  r   z MySQLTypeCompiler.visit_TINYTEXTc                 K   r  )Nr   r  r  r   r   r   visit_MEDIUMTEXT  r   z"MySQLTypeCompiler.visit_MEDIUMTEXTc                 K   r  )Nr   r  r  r   r   r   visit_LONGTEXT  r   z MySQLTypeCompiler.visit_LONGTEXTc                 K   s,   |j r| |i d|j  S td| jj )NzVARCHAR(%d)z'VARCHAR requires a length on dialect %sr  r  r-   r  r   r(  r  r   r   r   visit_VARCHAR  s
   
zMySQLTypeCompiler.visit_VARCHARc                 K   s,   |j r| |i dd|j i S | |i dS )NCHAR(%(length)s)r  r   r  r  r   r   r   
visit_CHAR  s
   zMySQLTypeCompiler.visit_CHARc                 K   s4   |j 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  r   r   r   visit_NVARCHAR  s   
z MySQLTypeCompiler.visit_NVARCHARc                 K   s4   |j r| |ddidd|j i S | |ddidS )Nr  Tr  r  r   r  r  r   r   r   visit_NCHAR  s   zMySQLTypeCompiler.visit_NCHARc                 K   s
   d|j  S )NzVARBINARY(%d)r  r  r   r   r   visit_VARBINARY  r   z!MySQLTypeCompiler.visit_VARBINARYc                 K   r  )Nr
   r   r  r   r   r   
visit_JSON  r  zMySQLTypeCompiler.visit_JSONc                 K   s
   |  |S r   )
visit_BLOBr  r   r   r   visit_large_binary  r   z$MySQLTypeCompiler.visit_large_binaryc                    s&   |j stt| |S | d||jS Nr   )Znative_enumrE  r  
visit_enum_visit_enumerated_valuesenumsr  rI  r   r   r    s   zMySQLTypeCompiler.visit_enumc                 K   s   |j rd|j  S dS )NzBLOB(%d)r8   r  r  r   r   r   r    s   
zMySQLTypeCompiler.visit_BLOBc                 K   r  )Nr'   r   r  r   r   r   visit_TINYBLOB  r  z MySQLTypeCompiler.visit_TINYBLOBc                 K   r  )Nr   r   r  r   r   r   visit_MEDIUMBLOB  r  z"MySQLTypeCompiler.visit_MEDIUMBLOBc                 K   r  )Nr   r   r  r   r   r   visit_LONGBLOB  r  z MySQLTypeCompiler.visit_LONGBLOBc              	   C   s@   g }|D ]}| d|dd  q| |i d|d|f S )Nr+  'z''z%s(%s),)r.  r   r  r|   )r   r(  r   Zenumerated_valuesZquoted_enumser   r   r   r     s   z*MySQLTypeCompiler._visit_enumerated_valuesc                 K      |  d||jS r  r   Z_enumerated_valuesr  r   r   r   
visit_ENUM     zMySQLTypeCompiler.visit_ENUMc                 K   r  )Nr	   r	  r  r   r   r   	visit_SET  r  zMySQLTypeCompiler.visit_SETc                 K   r  )NZBOOLr   r  r   r   r   visit_BOOLEAN  r  zMySQLTypeCompiler.visit_BOOLEAN)+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  r  r  r  r  r  r  r  r  r   r
  r  r  r{  r   r   rI  r   r    sP    "





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 t| j|||d d S )N`")Zinitial_quoteZescape_quote)rE  r  __init__)r   r   server_ansiquotesr   r'  rI  r   r   r    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 r   )quote_identifier)r  ir   r   r   r  
	  s    zCMySQLIdentifierPreparer._quote_free_identifiers.<locals>.<listcomp>)tuple)r   Zidsr   r   r   _quote_free_identifiers	  s   z/MySQLIdentifierPreparer._quote_free_identifiersrx  )r   r   r   RESERVED_WORDSZreserved_wordsr  r  r{  r   r   rI  r   r    s    
r  c                	   @   s  e 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eZdZeZeZeZeZeZdZdZejdd	ife j!d
d	ifej"dd	ifej#d	d	d	d	dfgZ$						dtddZ%dd Z&e'g 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! Z0d"d# Z1	dud$d%Z2	dud&d'Z3d(d) Z4d*d+ Z5dvd,d-Z6dvd.d/Z7dvd0d1Z8d2d3 Z9d4d5 Z:dvd6d7Z;d8d9 Z<d:d; Z=e>d<d= Z?e>d>d? Z@e>d@dA ZAe>dBdC ZBe>dDdE ZCeDjEdFdG ZFeDjEdvdHdIZGeDjEdvdJdKZHeDjEdvdLdMZIeDjEdvdNdOZJeDjEdvdPdQZKeDjEdvdRdSZLdTdU ZMeDjEdvdVdWZNeDjEdvdXdYZOeDjEdvdZd[ZPeDjE		dvd\d]ZQeDjEdvd^d_ZR		dvd`daZSeTjUdbdc ZVeDjEdvdddeZWdfdg ZXdhdi ZYdjdk ZZdldm Z[dndo Z\		dwdpdqZ]dwdrdsZ^d	S )xMySQLDialectzMDetails of the MySQL dialect.
    Not used directly in application code.
    r  TF   @   format*Nr   r   )r   r  prefixr  c                 K   s6   | dd  tjj| fi | || _|| _|| _d S )NZuse_ansiquotes)popr3   DefaultDialectr  isolation_levelZ_json_serializerZ_json_deserializer)r   r   Zjson_serializerZjson_deserializerrT  r   r   r   r  I	  s
   
zMySQLDialect.__init__c                    s    j d ur fdd}|S d S )Nc                    s     |  j d S r   )set_isolation_levelr   )connr   r   r   connectY	  r  z(MySQLDialect.on_connect.<locals>.connect)r   )r   r#  r   r   r   
on_connectV	  s   
zMySQLDialect.on_connect)ZSERIALIZABLEzREAD UNCOMMITTEDzREAD COMMITTEDzREPEATABLE READc                 C   s,   | dd}t|dr|j}| || d S )Nr  r  
connection)r   hasattrr%  _set_isolation_level)r   r%  r   r   r   r   r!  i	  s   
z MySQLDialect.set_isolation_levelc                 C   sT   || j vrtd|| jd| j f | }|d|  |d |  d S )NzLInvalid value '%s' for isolation_level. Valid isolation levels for %s are %sr*  z*SET SESSION TRANSACTION ISOLATION LEVEL %sZCOMMIT)_isolation_lookupr-   ArgumentErrorr(  r|   rV   executeclose)r   r%  r   rV   r   r   r   r'  t	  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j	r;t
|tr;| }| ddS )N)         zSELECT @@transaction_isolationzSELECT @@tx_isolationzDCould not retrieve transaction isolation level for MySQL connection.r   -r  )rV   r[  server_version_infor*  fetchoner2   r/  r   r+  py3kr#  bytesdecoderP  r   )r   r%  rV   r   r1  r   r   r   get_isolation_level	  s   
z MySQLDialect.get_isolation_levelc                 C   sN   |j }| }|d | d }|  tjr"t|tr"|	 }| 
|S )NzSELECT VERSION()r   )r%  rV   r*  r1  r+  r2   r2  r#  r3  r4  _parse_server_version)r   r%  Z	dbapi_conrV   r1  r   r   r   _get_server_version_info	  s   

z%MySQLDialect._get_server_version_infoc              	   C   s~   g }t d}||D ].}z	|t| W q ty:   t d|}|r3|dd | D  n|| Y qw t	|S )Nz[.\-]z(.*)(MariaDB)(.*)c                 s   s    | ]}|r|V  qd S r   r   )r  gr   r   r   r  	  r,  z5MySQLDialect._parse_server_version.<locals>.<genexpr>)
recompilesplitr.  rx   
ValueErrorr   extendrp   r  )r   r1  versionrnZmariadbr   r   r   r6  	  s   

z"MySQLDialect._parse_server_versionc                 C   N   z|   W dS  ty&   | jdk r%t d j}|r%|d dkr%Y dS  w )zExecute a COMMIT.r,         r   r   (  N)commit	Exceptionr0  sysexc_infoargsr   Zdbapi_connectionrJ  r   r   r   	do_commit	  s   	
zMySQLDialect.do_commitc                 C   rA  )zExecute a ROLLBACK.rB  r   r   rE  N)rollbackrG  r0  rH  rI  rJ  rK  r   r   r   do_rollback	  s   
zMySQLDialect.do_rollbackc                 C   s   |j td|d d S )NzXA BEGIN :xidxidr*  r0   r   r   r%  rP  r   r   r   do_begin_twophase	  s   zMySQLDialect.do_begin_twophasec                 C   s,   |j td|d |j td|d d S )NXA END :xidrO  zXA PREPARE :xidrQ  rR  r   r   r   do_prepare_twophase	  s   z MySQLDialect.do_prepare_twophasec                 C   s0   |s|j td|d |j td|d d S )NrT  rO  zXA ROLLBACK :xidrQ  r   r%  rP  Zis_preparedZrecoverr   r   r   do_rollback_twophase	  s   z!MySQLDialect.do_rollback_twophasec                 C   s(   |s|  || |jtd|d d S )NzXA COMMIT :xidrO  )rU  r*  r0   r   rV  r   r   r   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   Zgtrid_lengthr   r  r   r   r   r   r  	  s     z4MySQLDialect.do_recover_twophase.<locals>.<listcomp>r*  )r   r%  Z	resultsetr   r   r   do_recover_twophase	  s   
z MySQLDialect.do_recover_twophasec                 C   sJ   t || jj| jjfr| |dv S t || jj| jjfr#dt|v S dS )N)i  i  i  i  i  i  z(0, '')F)r#  ZdbapiZOperationalErrorZProgrammingError_extract_error_codeZInterfaceErrorZInternalErrorstr)r   r  r%  rV   r   r   r   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 r   )_DecodingRowProxyrZ  r  r   r   r  	  s    z1MySQLDialect._compat_fetchall.<locals>.<listcomp>)Zfetchall)r   rpr  r   ra  r   _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)r1  r`  r   rb  r  r   r   r   r   _compat_fetchone
     
zMySQLDialect._compat_fetchonec                 C   rd  re  )firstr`  rf  r   r   r   _compat_first
  rh  zMySQLDialect._compat_firstc                 C      t  r   r   )r   	exceptionr   r   r   r]  
     z MySQLDialect._extract_error_codec                 C   s   | d S )NzSELECT DATABASE())r*  Zscalarr   r%  r   r   r   _get_default_schema_name
  r   z%MySQLDialect._get_default_schema_namec           	   
   C   s   d | j||}d| }d }zEz|jdd|}| d u}|  |W W |r/|  S S  tjyU } z| 	|j
dkrPW Y d }~W |rN|  dS dS  d }~ww |r]|  w w )N.DESCRIBE %sTZskip_user_error_eventsz  F)r|   identifier_preparerr  execution_optionsr*  r1  r+  r-   
DBAPIErrorr]  orig)	r   r%  
table_namer/   	full_namestrsZhaver  r   r   r   	has_table
  s@   

zMySQLDialect.has_tablec                 C   s   |  || _| | | | | | | jr!| j| | jd| _tj	
| | | jo/| jdk| _| j o9| jdk| _|   d S )Nr  )   )_detect_charset_connection_charset_detect_sql_mode_detect_ansiquotes_detect_casing_server_ansiquotesr&  ru  r3   r  
initializer[  r0  rY  r  _needs_correct_for_88718_96365_warn_for_known_db_issuesro  r   r   r   r  >
  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  	   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   _mariadb_normalized_version_infor2   r/  )r   Zmdb_versionr   r   r   r  V
  s   z&MySQLDialect._warn_for_known_db_issuesc                 C   s   | j od| j v S )NMariaDBr0  r   r   r   r   r  d
  s   zMySQLDialect._is_mariadbc                 C   s   | j  S r   )r  r   r   r   r   r[  j
  s   zMySQLDialect._is_mysqlc                 C   s   | j o| jdkS )Nr  )r  r  r   r   r   r   _is_mariadb_102n
  s   zMySQLDialect._is_mariadb_102c                 C   s*   | j r| jd}| j|d | S | jS )Nr  r,   )r  r0  rt   )r   rp  r   r   r   r  u
  s   z-MySQLDialect._mariadb_normalized_version_infoc                 C   s   | j d u p	| j dkS )N)   r   r  r  r   r   r   r   rA  
  s   
zMySQLDialect._supports_castc                 K   s   | d}dd |D S )NzSHOW schemasc                 S      g | ]}|d  qS r   r   )r  r?  r   r   r   r  
      z1MySQLDialect.get_schema_names.<locals>.<listcomp>r[  )r   r%  r   rb  r   r   r   get_schema_names
  s   
zMySQLDialect.get_schema_namesc                 K   s   |dur|}n| j }| j}| jdk r)|d| j| }dd | j||dD S |d| j| }dd | j||dD S )	z1Return a Unicode SHOW TABLES from a given schema.Nr,  r   r  zSHOW TABLES FROM %sc                 S   r  r  r   rZ  r   r   r   r  
  s    z0MySQLDialect.get_table_names.<locals>.<listcomp>ra  SHOW FULL TABLES FROM %sc                 S   s    g | ]}|d  dkr|d qS )r   z
BASE TABLEr   r   rZ  r   r   r   r  
  
    )default_schema_namer  r0  r*  ru  r  rc  )r   r%  r/   r   Zcurrent_schemar  rb  r   r   r   get_table_names
  s*   


zMySQLDialect.get_table_namesc                 K   sf   | j dk rt|d u r| j}| j dk r| ||S | j}|d| j| }dd | j||dD S )Nr  r  c                 S   s    g | ]}|d  dv r|d qS )r   )ZVIEWzSYSTEM VIEWr   r   rZ  r   r   r   r  
  r  z/MySQLDialect.get_view_names.<locals>.<listcomp>ra  )	r0  r   r  r  r  r*  ru  r  rc  )r   r%  r/   r   r  rb  r   r   r   get_view_names
  s   


zMySQLDialect.get_view_namesc                 K      | j |||fi |}|jS r   )_parsed_state_or_createtable_optionsr   r%  ry  r/   r   parsed_stater   r   r   get_table_options
  s   zMySQLDialect.get_table_optionsc                 K   r  r   )r  rM   r  r   r   r   get_columns
  s   zMySQLDialect.get_columnsc                 K   sX   | j |||fi |}|jD ]}|d dkr&dd |d D }|d d  S qg d dS )Nr  PRIMARYc                 S   r  r  r   r  sr   r   r   r  
  r  z2MySQLDialect.get_pk_constraint.<locals>.<listcomp>rM   )constrained_columnsr(  r  r~   )r   r%  ry  r/   r   r  r}   r0  r   r   r   get_pk_constraint
  s   

zMySQLDialect.get_pk_constraintc                 K   s   | j |||fi |}d }g }|jD ]S}|d d }	t|d dkr(|d d p)|}
|
s:|d u r4|jj}||kr:|}
|d }|d }i }dD ]}||drT|| ||< qF|d	 ||
|	||d
}|| q| jro| || |S )Nr   r   r   localri   )ZonupdateZondeleteFr(  )r(  r  referred_schemareferred_tablereferred_columnsoptions)	r  Zfk_constraintsr  r   r  rm   r.  r  #_correct_for_mysql_bugs_88718_96365)r   r%  ry  r/   r   r  Zdefault_schemafkeysr  ref_nameZ
ref_schemaZ	loc_namesZ	ref_namesZcon_kwr  Zfkey_dr   r   r   get_foreign_keys
  sB   
 zMySQLDialect.get_foreign_keysc           
         s4  | j dv r
dd ndd |jj  fdd|D }|r|jtdtjdd	d
|d}tt	}|D ]+\}}}||||f d< ||||f d< ||||f |
 < q6|D ]3}	||	d pm |	d f d |	d< |	d d urd |	d< fdd|	d D |	d< qdd S d S )N)r   r  c                 S   s   |   S r   lowerr  r   r   r   r    s   z?MySQLDialect._correct_for_mysql_bugs_88718_96365.<locals>.lowerc                 S   s   | S r   r   r  r   r   r   r    r  c                    s8   g | ]}|d  D ]}|d p |d |fqqS )r  r  r  r   )r  recZcol_name)r  r  r   r   r    s    
zDMySQLDialect._correct_for_mysql_bugs_88718_96365.<locals>.<listcomp>z
                    select table_schema, table_name, column_name
                    from information_schema.columns
                    where (table_schema, table_name, lower(column_name)) in
                    :table_data;
                
table_dataT)Z	expanding)r  Z
SCHEMANAMEZ	TABLENAMEr  r  c                    s   g | ]} |   qS r   r  r  )r  r   r   r  Q  s    r  )_casingr   r  r*  r0   r   Z
bindparamsZ	bindparamr   r  r  )
r   r  r%  Z
col_tuplesZcorrect_for_wrong_fk_casedr/   ZtnamecnameZfkeyr   )r  r  r  r   r    sD   




z0MySQLDialect._correct_for_mysql_bugs_88718_96365c                 K   &   | j |||fi |}dd |jD S )Nc                 S   s   g | ]}|d  |d dqS )r(  sqltext)r(  r  r   )r  r  r   r   r   r  [  s    z6MySQLDialect.get_check_constraints.<locals>.<listcomp>)r  Zck_constraintsr  r   r   r   get_check_constraintsU  s   z"MySQLDialect.get_check_constraintsc                 K   s(   | j |||fi |}d|jdd iS )Nr   Zmysql_comment)r  r  rm   r  r   r   r   get_table_comment`  s   zMySQLDialect.get_table_commentc                 K   s   | j |||fi |}g }|jD ]^}i }d}	|d }
|
dkrq|
dkr&d}	n|
dv r/|
|d< n|
d u r4n| jd|
 	 |d	 rF|d	 |d
< i }|rN||d< |d |d< dd |d D |d< |	|d< |
ri|
|d< || q|S )NFr  r  UNIQUET)ZFULLTEXTZSPATIALr  z-Converting unknown KEY type %s to a plain KEYr  Zmysql_with_parserr  r(  c                 S   r  r  r   r  r   r   r   r    r  z,MySQLDialect.get_indexes.<locals>.<listcomp>rM   column_namesr   )r  r~   loggerinfor.  )r   r%  ry  r/   r   r  Zindexesr  r  r   ZflavorZindex_dr   r   r   get_indexesg  sD   

zMySQLDialect.get_indexesc                 K   r  )Nc                 S   s:   g | ]}|d  dkr|d dd |d D |d dqS )r  r  r(  c                 S   r  r  r   r  r   r   r   r    r  zBMySQLDialect.get_unique_constraints.<locals>.<listcomp>.<listcomp>rM   )r(  r  Zduplicates_indexr   r  r   r   r   r    s    z7MySQLDialect.get_unique_constraints.<locals>.<listcomp>r  r  r   r   r   get_unique_constraints  s   z#MySQLDialect.get_unique_constraintsc                 K   s0   | j }d| j||}| j|d ||d}|S )Nrq  rz  )r  r|   ru  r  _show_create_table)r   r%  Z	view_namer/   r   r  rz  r0   r   r   r   get_view_definition  s   z MySQLDialect.get_view_definitionc                 K   s   | j ||||dd dS )N
info_cache)r  )_setup_parserrm   )r   r%  ry  r/   r   r   r   r   r    s   
z$MySQLDialect._parsed_state_or_createc                 C   s2   | j dk r| jr| j| dd}n| j}t| |S )zreturn the MySQLTableDefinitionParser, generate if needed.

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

        )r  r   Fr~  )r0  r  r&  ru  r  ZMySQLTableDefinitionParser)r   r&  r   r   r   _tabledef_parser  s   zMySQLDialect._tabledef_parserc           
      K   sh   | j }| j}d| j||}| j|d ||d}td|r.| j|d ||d}	|	||	}|
||S )Nrq  r  z^CREATE (?:ALGORITHM)?.* VIEW)r  r  r|   ru  r  r  r9  r   _describe_tableZ_describe_to_createparse)
r   r%  ry  r/   r   r  r  rz  r0   rM   r   r   r   r    s    zMySQLDialect._setup_parserc                 C   rk  r   rl  ro  r   r   r   r    rn  zMySQLDialect._detect_charsetc                 C   s^   | j }| j|d|d}|sd}n|d dkrd}n|d dkr$d}nt|d }|| _|S )zSniff out identifier case sensitivity.

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

        z,SHOW VARIABLES LIKE 'lower_case_table_names'ra  r   r   ZOFFON)r  rj  r*  rx   r  )r   r%  r  r   csr   r   r   r    s   	zMySQLDialect._detect_casingc                 C   sJ   i }| j dk r
	 |S | j}|d}| ||D ]
}|d ||d < q|S )zYPull the active COLLATIONS list from the server.

        Cached per-connection.
        )r  r   r   zSHOW COLLATIONr   r   )r0  r  r*  rc  )r   r%  Z
collationsr  r|  r   r   r   r   _detect_collations  s   

zMySQLDialect._detect_collationsc                 C   s@   | j |d| jd}|std d| _d S |d pd| _d S )NzSHOW VARIABLES LIKE 'sql_mode'ra  z[Could not retrieve SQL_MODE; please ensure the MySQL user has permissions to SHOW VARIABLESr   r   )rj  r*  r  r2   r/  	_sql_mode)r   r%  r   r   r   r   r    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  ZANSI_QUOTESZNO_BACKSLASH_ESCAPESN)r  isdigitrx   r  rG  )r   r%  r   Zmode_nor   r   r   r    s   
zMySQLDialect._detect_ansiquotesc           	   
   C   s   |du r
| j |}d| }d}z|jdd|}W n' tjyB } z| |jdkr7tj	t
||d n W Y d}~nd}~ww | j||d}|sQt
||d  S )	z&Run SHOW CREATE TABLE for a ``Table``.NzSHOW CREATE TABLE %sTrs  rt  Zreplace_contextra  r   )ru  r  rv  r*  r-   rw  r]  rx  r2   raise_NoSuchTableErrorrj  stripr0   )	r   r%  r   r  rz  r{  rb  r  r   r   r   r   r  )  s*   
zMySQLDialect._show_create_tablec           
   
   C   s   |du r
| j |}d| }d\}}zXz|jdd|}W n< tjyZ } z/| |j}	|	dkr<tj	t
||d n|	dkrOtj	td	||f |d n W Y d}~nd}~ww | j||d
}W |ri|  |S |rr|  w w )z7Run DESCRIBE for a ``Table`` and return processed rows.Nrr  NNTrs  rt  r  iL  z1Table or view named %s could not be reflected: %sra  )ru  r  rv  r*  r-   rw  r]  rx  r2   r  r  ZUnreflectableTableErrorrc  r+  )
r   r%  r   r  rz  r{  rb  r   r  coder   r   r   r  C  sH   

zMySQLDialect._describe_table)NNN)TFr   r  )_r   r   r   __doc__r(  Zsupports_alterZsupports_native_booleanZmax_identifier_lengthZmax_index_name_lengthZsupports_native_enumrY  Zsupports_sane_rowcountZsupports_sane_multi_rowcountZsupports_multivalues_insertZsupports_commentsZinline_commentsZdefault_paramstylecolspecsZcte_follows_insertr   Zstatement_compilerr|  Zddl_compilerr  r?  ischema_namesr  r&  rG  r  r  Tabler0   ZUpdater  IndexZconstruct_argumentsr  r$  r   r(  r!  r'  r5  r7  r6  rL  rN  rS  rU  rW  rX  r\  r_  rc  rg  rj  r]  rp  r}  r  r  propertyr  r[  r  r  rA  r   cacher  r  r  r  r  r  r  r  r  r  r  r  r  r  r2   Zmemoized_propertyr  r  r  r  r  r  r  r  r  r   r   r   r   r  	  s    

	







#






*S
)



r  c                   @   s8   e Zd ZdZ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)Zkoi8rZkoi8uutf16Zutf8mb4Zeucjpmsc                 C   s   || _ | j||| _d S r   )rowproxy_encoding_compatrm   r  )r   r  r  r   r   r   r  |  s   z_DecodingRowProxy.__init__c                 C   s>   | j | }t|tr| }| jrt|tjr|| jS |S r   )r  r#  _arraytostringr  r2   binary_typer4  )r   rt   itemr   r   r   __getitem__  s   

z_DecodingRowProxy.__getitem__c                 C   s@   t | j|}t|tr| }| jrt|tjr|| jS |S r   )	r;  r  r#  r  r  r  r2   r  r4  )r   r  r  r   r   r   __getattr__  s   
z_DecodingRowProxy.__getattr__N)r   r   r   r  r  r  r  r  r   r   r   r   r`  g  s    
r`  )r  r   r  collectionsr   r9  rH  Z
sqlalchemyr   Zsqlalchemy.sqlr   r   r   r  Z
enumeratedr   r	   r   r
   r   r   r1   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*   r+   r-   r.   r/   r  r0   r  r2   Zenginer3   r4   r5   r6   rZ  r7   r8   r9   r:   r;   r<   r   r  r:  Ir  r   ZSET_REZMSTimeZMSSetZMSEnumZ
MSLongBlobZMSMediumBlobZ
MSTinyBlobZMSBlobZMSBinaryZMSVarBinaryZMSNCharZ
MSNVarCharZMSCharZMSStringZ
MSLongTextZMSMediumTextZ
MSTinyTextZMSTextZMSYearZMSTimeStampZMSBitZMSSmallIntegerZMSTinyIntegerZMSMediumIntegerZMSBigIntegerZ	MSNumericZ	MSDecimalZMSDoubleZMSRealZMSFloatZ	MSIntegerr	  Floatr>  EnumZ	MatchTyper  r  ZDefaultExecutionContextr   ry  r   ZDDLCompilerr|  ZGenericTypeCompilerr  ZIdentifierPreparerr  Zclass_loggerr  r  objectr`  r   r   r   r   <module>   s        H  (
	
 !"#'       4      _