o
    g                    @  sN  d Z ddlmZ ddl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+ G d%d& d&e	Z,G d'd( d(Z-G d)d* d*e-ej.Z/G d+d, d,e-ej0Z1G d-d. d.e-ej2Z3ej0e1ej.e/ej	e,ej	j
e
ej	jeej2e3iZ4i d/ej5d0ej d1ej!d2ej!d3ej"d,ej1d4ej1d*ej/d5ej/d6ej6d7ej#d8ej$d9ej%d:ej%d;e	d<ej&d=ej'ej(ej)ej3ej3ej*ej+ej7ej8d>Z9G d?d@ d@ej:Z;G dAdB dBej<Z=G dCdD dDej>Z?G dEdF dFej@ZAG dGdH dHejBZCG dIdJ dJejDZEdS )Ka|  
.. dialect:: sqlite
    :name: SQLite
    :normal_support: 3.12+
    :best_effort: 3.7.16+

.. _sqlite_datetime:

Date and Time Types
-------------------

SQLite does not have built-in DATE, TIME, or DATETIME types, and pysqlite does
not provide out of the box functionality for translating values between Python
`datetime` objects and a SQLite-supported format. SQLAlchemy's own
:class:`~sqlalchemy.types.DateTime` and related types provide date formatting
and parsing functionality when SQLite is used. The implementation classes are
:class:`_sqlite.DATETIME`, :class:`_sqlite.DATE` and :class:`_sqlite.TIME`.
These types represent dates and times as ISO formatted strings, which also
nicely support ordering. There's no reliance on typical "libc" internals for
these functions so historical dates are fully supported.

Ensuring Text affinity
^^^^^^^^^^^^^^^^^^^^^^

The DDL rendered for these types is the standard ``DATE``, ``TIME``
and ``DATETIME`` indicators.    However, custom storage formats can also be
applied to these types.   When the
storage format is detected as containing no alpha characters, the DDL for
these types is rendered as ``DATE_CHAR``, ``TIME_CHAR``, and ``DATETIME_CHAR``,
so that the column continues to have textual affinity.

.. seealso::

    `Type Affinity <https://www.sqlite.org/datatype3.html#affinity>`_ -
    in the SQLite documentation

.. _sqlite_autoincrement:

SQLite Auto Incrementing Behavior
----------------------------------

Background on SQLite's autoincrement is at: https://sqlite.org/autoinc.html

Key concepts:

* SQLite has an implicit "auto increment" feature that takes place for any
  non-composite primary-key column that is specifically created using
  "INTEGER PRIMARY KEY" for the type + primary key.

* SQLite also has an explicit "AUTOINCREMENT" keyword, that is **not**
  equivalent to the implicit autoincrement feature; this keyword is not
  recommended for general use.  SQLAlchemy does not render this keyword
  unless a special SQLite-specific directive is used (see below).  However,
  it still requires that the column's type is named "INTEGER".

Using the AUTOINCREMENT Keyword
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To specifically render the AUTOINCREMENT keyword on the primary key column
when rendering DDL, add the flag ``sqlite_autoincrement=True`` to the Table
construct::

    Table(
        "sometable",
        metadata,
        Column("id", Integer, primary_key=True),
        sqlite_autoincrement=True,
    )

Allowing autoincrement behavior SQLAlchemy types other than Integer/INTEGER
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

SQLite's typing model is based on naming conventions.  Among other things, this
means that any type name which contains the substring ``"INT"`` will be
determined to be of "integer affinity".  A type named ``"BIGINT"``,
``"SPECIAL_INT"`` or even ``"XYZINTQPR"``, will be considered by SQLite to be
of "integer" affinity.  However, **the SQLite autoincrement feature, whether
implicitly or explicitly enabled, requires that the name of the column's type
is exactly the string "INTEGER"**.  Therefore, if an application uses a type
like :class:`.BigInteger` for a primary key, on SQLite this type will need to
be rendered as the name ``"INTEGER"`` when emitting the initial ``CREATE
TABLE`` statement in order for the autoincrement behavior to be available.

One approach to achieve this is to use :class:`.Integer` on SQLite
only using :meth:`.TypeEngine.with_variant`::

    table = Table(
        "my_table",
        metadata,
        Column(
            "id",
            BigInteger().with_variant(Integer, "sqlite"),
            primary_key=True,
        ),
    )

Another is to use a subclass of :class:`.BigInteger` that overrides its DDL
name to be ``INTEGER`` when compiled against SQLite::

    from sqlalchemy import BigInteger
    from sqlalchemy.ext.compiler import compiles


    class SLBigInteger(BigInteger):
        pass


    @compiles(SLBigInteger, "sqlite")
    def bi_c(element, compiler, **kw):
        return "INTEGER"


    @compiles(SLBigInteger)
    def bi_c(element, compiler, **kw):
        return compiler.visit_BIGINT(element, **kw)


    table = Table(
        "my_table", metadata, Column("id", SLBigInteger(), primary_key=True)
    )

.. seealso::

    :meth:`.TypeEngine.with_variant`

    :ref:`sqlalchemy.ext.compiler_toplevel`

    `Datatypes In SQLite Version 3 <https://sqlite.org/datatype3.html>`_

.. _sqlite_concurrency:

Database Locking Behavior / Concurrency
---------------------------------------

SQLite is not designed for a high level of write concurrency. The database
itself, being a file, is locked completely during write operations within
transactions, meaning exactly one "connection" (in reality a file handle)
has exclusive access to the database during this period - all other
"connections" will be blocked during this time.

The Python DBAPI specification also calls for a connection model that is
always in a transaction; there is no ``connection.begin()`` method,
only ``connection.commit()`` and ``connection.rollback()``, upon which a
new transaction is to be begun immediately.  This may seem to imply
that the SQLite driver would in theory allow only a single filehandle on a
particular database file at any time; however, there are several
factors both within SQLite itself as well as within the pysqlite driver
which loosen this restriction significantly.

However, no matter what locking modes are used, SQLite will still always
lock the database file once a transaction is started and DML (e.g. INSERT,
UPDATE, DELETE) has at least been emitted, and this will block
other transactions at least at the point that they also attempt to emit DML.
By default, the length of time on this block is very short before it times out
with an error.

This behavior becomes more critical when used in conjunction with the
SQLAlchemy ORM.  SQLAlchemy's :class:`.Session` object by default runs
within a transaction, and with its autoflush model, may emit DML preceding
any SELECT statement.   This may lead to a SQLite database that locks
more quickly than is expected.   The locking mode of SQLite and the pysqlite
driver can be manipulated to some degree, however it should be noted that
achieving a high degree of write-concurrency with SQLite is a losing battle.

For more information on SQLite's lack of write concurrency by design, please
see
`Situations Where Another RDBMS May Work Better - High Concurrency
<https://www.sqlite.org/whentouse.html>`_ near the bottom of the page.

The following subsections introduce areas that are impacted by SQLite's
file-based architecture and additionally will usually require workarounds to
work when using the pysqlite driver.

.. _sqlite_isolation_level:

Transaction Isolation Level / Autocommit
----------------------------------------

SQLite supports "transaction isolation" in a non-standard way, along two
axes.  One is that of the
`PRAGMA read_uncommitted <https://www.sqlite.org/pragma.html#pragma_read_uncommitted>`_
instruction.   This setting can essentially switch SQLite between its
default mode of ``SERIALIZABLE`` isolation, and a "dirty read" isolation
mode normally referred to as ``READ UNCOMMITTED``.

SQLAlchemy ties into this PRAGMA statement using the
:paramref:`_sa.create_engine.isolation_level` parameter of
:func:`_sa.create_engine`.
Valid values for this parameter when used with SQLite are ``"SERIALIZABLE"``
and ``"READ UNCOMMITTED"`` corresponding to a value of 0 and 1, respectively.
SQLite defaults to ``SERIALIZABLE``, however its behavior is impacted by
the pysqlite driver's default behavior.

When using the pysqlite driver, the ``"AUTOCOMMIT"`` isolation level is also
available, which will alter the pysqlite connection using the ``.isolation_level``
attribute on the DBAPI connection and set it to None for the duration
of the setting.

.. versionadded:: 1.3.16 added support for SQLite AUTOCOMMIT isolation level
   when using the pysqlite / sqlite3 SQLite driver.


The other axis along which SQLite's transactional locking is impacted is
via the nature of the ``BEGIN`` statement used.   The three varieties
are "deferred", "immediate", and "exclusive", as described at
`BEGIN TRANSACTION <https://sqlite.org/lang_transaction.html>`_.   A straight
``BEGIN`` statement uses the "deferred" mode, where the database file is
not locked until the first read or write operation, and read access remains
open to other transactions until the first write operation.  But again,
it is critical to note that the pysqlite driver interferes with this behavior
by *not even emitting BEGIN* until the first write operation.

.. warning::

    SQLite's transactional scope is impacted by unresolved
    issues in the pysqlite driver, which defers BEGIN statements to a greater
    degree than is often feasible. See the section :ref:`pysqlite_serializable`
    or :ref:`aiosqlite_serializable` for techniques to work around this behavior.

.. seealso::

    :ref:`dbapi_autocommit`

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

The SQLite dialect supports SQLite 3.35's  ``INSERT|UPDATE|DELETE..RETURNING``
syntax.   ``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())

    # UPDATE..RETURNING
    result = connection.execute(
        table.update()
        .where(table.c.name == "foo")
        .values(name="bar")
        .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 SQLite RETURNING

SAVEPOINT Support
----------------------------

SQLite supports SAVEPOINTs, which only function once a transaction is
begun.   SQLAlchemy's SAVEPOINT support is available using the
:meth:`_engine.Connection.begin_nested` method at the Core level, and
:meth:`.Session.begin_nested` at the ORM level.   However, SAVEPOINTs
won't work at all with pysqlite unless workarounds are taken.

.. warning::

    SQLite's SAVEPOINT feature is impacted by unresolved
    issues in the pysqlite and aiosqlite drivers, which defer BEGIN statements
    to a greater degree than is often feasible. See the sections
    :ref:`pysqlite_serializable` and :ref:`aiosqlite_serializable`
    for techniques to work around this behavior.

Transactional DDL
----------------------------

The SQLite database supports transactional :term:`DDL` as well.
In this case, the pysqlite driver is not only failing to start transactions,
it also is ending any existing transaction when DDL is detected, so again,
workarounds are required.

.. warning::

    SQLite's transactional DDL is impacted by unresolved issues
    in the pysqlite driver, which fails to emit BEGIN and additionally
    forces a COMMIT to cancel any transaction when DDL is encountered.
    See the section :ref:`pysqlite_serializable`
    for techniques to work around this behavior.

.. _sqlite_foreign_keys:

Foreign Key Support
-------------------

SQLite supports FOREIGN KEY syntax when emitting CREATE statements for tables,
however by default these constraints have no effect on the operation of the
table.

Constraint checking on SQLite has three prerequisites:

* At least version 3.6.19 of SQLite must be in use
* The SQLite library must be compiled *without* the SQLITE_OMIT_FOREIGN_KEY
  or SQLITE_OMIT_TRIGGER symbols enabled.
* The ``PRAGMA foreign_keys = ON`` statement must be emitted on all
  connections before use -- including the initial call to
  :meth:`sqlalchemy.schema.MetaData.create_all`.

SQLAlchemy allows for the ``PRAGMA`` statement to be emitted automatically for
new connections through the usage of events::

    from sqlalchemy.engine import Engine
    from sqlalchemy import event


    @event.listens_for(Engine, "connect")
    def set_sqlite_pragma(dbapi_connection, connection_record):
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()

.. warning::

    When SQLite foreign keys are enabled, it is **not possible**
    to emit CREATE or DROP statements for tables that contain
    mutually-dependent foreign key constraints;
    to emit the DDL for these tables requires that ALTER TABLE be used to
    create or drop these constraints separately, for which SQLite has
    no support.

.. seealso::

    `SQLite Foreign Key Support <https://www.sqlite.org/foreignkeys.html>`_
    - on the SQLite web site.

    :ref:`event_toplevel` - SQLAlchemy event API.

    :ref:`use_alter` - more information on SQLAlchemy's facilities for handling
     mutually-dependent foreign key constraints.

.. _sqlite_on_conflict_ddl:

ON CONFLICT support for constraints
-----------------------------------

.. seealso:: This section describes the :term:`DDL` version of "ON CONFLICT" for
   SQLite, which occurs within a CREATE TABLE statement.  For "ON CONFLICT" as
   applied to an INSERT statement, see :ref:`sqlite_on_conflict_insert`.

SQLite supports a non-standard DDL clause known as ON CONFLICT which can be applied
to primary key, unique, check, and not null constraints.   In DDL, it is
rendered either within the "CONSTRAINT" clause or within the column definition
itself depending on the location of the target constraint.    To render this
clause within DDL, the extension parameter ``sqlite_on_conflict`` can be
specified with a string conflict resolution algorithm within the
:class:`.PrimaryKeyConstraint`, :class:`.UniqueConstraint`,
:class:`.CheckConstraint` objects.  Within the :class:`_schema.Column` object,
there
are individual parameters ``sqlite_on_conflict_not_null``,
``sqlite_on_conflict_primary_key``, ``sqlite_on_conflict_unique`` which each
correspond to the three types of relevant constraint types that can be
indicated from a :class:`_schema.Column` object.

.. seealso::

    `ON CONFLICT <https://www.sqlite.org/lang_conflict.html>`_ - in the SQLite
    documentation

.. versionadded:: 1.3


The ``sqlite_on_conflict`` parameters accept a  string argument which is just
the resolution name to be chosen, which on SQLite can be one of ROLLBACK,
ABORT, FAIL, IGNORE, and REPLACE.   For example, to add a UNIQUE constraint
that specifies the IGNORE algorithm::

    some_table = Table(
        "some_table",
        metadata,
        Column("id", Integer, primary_key=True),
        Column("data", Integer),
        UniqueConstraint("id", "data", sqlite_on_conflict="IGNORE"),
    )

The above renders CREATE TABLE DDL as:

.. sourcecode:: sql

    CREATE TABLE some_table (
        id INTEGER NOT NULL,
        data INTEGER,
        PRIMARY KEY (id),
        UNIQUE (id, data) ON CONFLICT IGNORE
    )


When using the :paramref:`_schema.Column.unique`
flag to add a UNIQUE constraint
to a single column, the ``sqlite_on_conflict_unique`` parameter can
be added to the :class:`_schema.Column` as well, which will be added to the
UNIQUE constraint in the DDL::

    some_table = Table(
        "some_table",
        metadata,
        Column("id", Integer, primary_key=True),
        Column(
            "data", Integer, unique=True, sqlite_on_conflict_unique="IGNORE"
        ),
    )

rendering:

.. sourcecode:: sql

    CREATE TABLE some_table (
        id INTEGER NOT NULL,
        data INTEGER,
        PRIMARY KEY (id),
        UNIQUE (data) ON CONFLICT IGNORE
    )

To apply the FAIL algorithm for a NOT NULL constraint,
``sqlite_on_conflict_not_null`` is used::

    some_table = Table(
        "some_table",
        metadata,
        Column("id", Integer, primary_key=True),
        Column(
            "data", Integer, nullable=False, sqlite_on_conflict_not_null="FAIL"
        ),
    )

this renders the column inline ON CONFLICT phrase:

.. sourcecode:: sql

    CREATE TABLE some_table (
        id INTEGER NOT NULL,
        data INTEGER NOT NULL ON CONFLICT FAIL,
        PRIMARY KEY (id)
    )


Similarly, for an inline primary key, use ``sqlite_on_conflict_primary_key``::

    some_table = Table(
        "some_table",
        metadata,
        Column(
            "id",
            Integer,
            primary_key=True,
            sqlite_on_conflict_primary_key="FAIL",
        ),
    )

SQLAlchemy renders the PRIMARY KEY constraint separately, so the conflict
resolution algorithm is applied to the constraint itself:

.. sourcecode:: sql

    CREATE TABLE some_table (
        id INTEGER NOT NULL,
        PRIMARY KEY (id) ON CONFLICT FAIL
    )

.. _sqlite_on_conflict_insert:

INSERT...ON CONFLICT (Upsert)
-----------------------------

.. seealso:: This section describes the :term:`DML` version of "ON CONFLICT" for
   SQLite, which occurs within an INSERT statement.  For "ON CONFLICT" as
   applied to a CREATE TABLE statement, see :ref:`sqlite_on_conflict_ddl`.

From version 3.24.0 onwards, SQLite supports "upserts" (update or insert)
of rows into a table via the ``ON CONFLICT`` clause of the ``INSERT``
statement. A candidate row will only be inserted if that row does not violate
any unique or primary key constraints. In the case of a unique constraint violation, a
secondary action can occur which can be either "DO UPDATE", indicating that
the data in the target row should be updated, or "DO NOTHING", which indicates
to silently skip this row.

Conflicts are determined using columns that are part of existing unique
constraints and indexes.  These constraints are identified by stating the
columns and conditions that comprise the indexes.

SQLAlchemy provides ``ON CONFLICT`` support via the SQLite-specific
:func:`_sqlite.insert()` function, which provides
the generative methods :meth:`_sqlite.Insert.on_conflict_do_update`
and :meth:`_sqlite.Insert.on_conflict_do_nothing`:

.. sourcecode:: pycon+sql

    >>> from sqlalchemy.dialects.sqlite import insert

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

    >>> do_update_stmt = insert_stmt.on_conflict_do_update(
    ...     index_elements=["id"], set_=dict(data="updated value")
    ... )

    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
    ON CONFLICT (id) DO UPDATE SET data = ?{stop}

    >>> do_nothing_stmt = insert_stmt.on_conflict_do_nothing(index_elements=["id"])

    >>> print(do_nothing_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
    ON CONFLICT (id) DO NOTHING

.. versionadded:: 1.4

.. seealso::

    `Upsert
    <https://sqlite.org/lang_UPSERT.html>`_
    - in the SQLite documentation.


Specifying the Target
^^^^^^^^^^^^^^^^^^^^^

Both methods supply the "target" of the conflict using column inference:

* The :paramref:`_sqlite.Insert.on_conflict_do_update.index_elements` argument
  specifies a sequence containing string column names, :class:`_schema.Column`
  objects, and/or SQL expression elements, which would identify a unique index
  or unique constraint.

* When using :paramref:`_sqlite.Insert.on_conflict_do_update.index_elements`
  to infer an index, a partial index can be inferred by also specifying the
  :paramref:`_sqlite.Insert.on_conflict_do_update.index_where` parameter:

  .. sourcecode:: pycon+sql

        >>> stmt = insert(my_table).values(user_email="a@b.com", data="inserted data")

        >>> do_update_stmt = stmt.on_conflict_do_update(
        ...     index_elements=[my_table.c.user_email],
        ...     index_where=my_table.c.user_email.like("%@gmail.com"),
        ...     set_=dict(data=stmt.excluded.data),
        ... )

        >>> print(do_update_stmt)
        {printsql}INSERT INTO my_table (data, user_email) VALUES (?, ?)
        ON CONFLICT (user_email)
        WHERE user_email LIKE '%@gmail.com'
        DO UPDATE SET data = excluded.data

The SET Clause
^^^^^^^^^^^^^^^

``ON CONFLICT...DO 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 specified using the
:paramref:`_sqlite.Insert.on_conflict_do_update.set_` parameter.  This
parameter accepts a dictionary which consists of direct values
for UPDATE:

.. sourcecode:: pycon+sql

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

    >>> do_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=["id"], set_=dict(data="updated value")
    ... )

    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?)
    ON CONFLICT (id) DO UPDATE SET data = ?

.. warning::

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

Updating using the Excluded INSERT Values
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In order to refer to the proposed insertion row, the special alias
:attr:`~.sqlite.Insert.excluded` is available as an attribute on
the :class:`_sqlite.Insert` object; this object creates an "excluded." prefix
on a column, that informs the DO UPDATE to update the row with the value that
would have been inserted had the constraint not failed:

.. sourcecode:: pycon+sql

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

    >>> do_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=["id"],
    ...     set_=dict(data="updated value", author=stmt.excluded.author),
    ... )

    >>> print(do_update_stmt)
    {printsql}INSERT INTO my_table (id, data, author) VALUES (?, ?, ?)
    ON CONFLICT (id) DO UPDATE SET data = ?, author = excluded.author

Additional WHERE Criteria
^^^^^^^^^^^^^^^^^^^^^^^^^

The :meth:`_sqlite.Insert.on_conflict_do_update` method also accepts
a WHERE clause using the :paramref:`_sqlite.Insert.on_conflict_do_update.where`
parameter, which will limit those rows which receive an UPDATE:

.. sourcecode:: pycon+sql

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

    >>> on_update_stmt = stmt.on_conflict_do_update(
    ...     index_elements=["id"],
    ...     set_=dict(data="updated value", author=stmt.excluded.author),
    ...     where=(my_table.c.status == 2),
    ... )
    >>> print(on_update_stmt)
    {printsql}INSERT INTO my_table (id, data, author) VALUES (?, ?, ?)
    ON CONFLICT (id) DO UPDATE SET data = ?, author = excluded.author
    WHERE my_table.status = ?


Skipping Rows with DO NOTHING
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

``ON CONFLICT`` may be used to skip inserting a row entirely
if any conflict with a unique constraint occurs; below this is illustrated
using the :meth:`_sqlite.Insert.on_conflict_do_nothing` method:

.. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
    >>> stmt = stmt.on_conflict_do_nothing(index_elements=["id"])
    >>> print(stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?) ON CONFLICT (id) DO NOTHING


If ``DO NOTHING`` is used without specifying any columns or constraint,
it has the effect of skipping the INSERT for any unique violation which
occurs:

.. sourcecode:: pycon+sql

    >>> stmt = insert(my_table).values(id="some_id", data="inserted value")
    >>> stmt = stmt.on_conflict_do_nothing()
    >>> print(stmt)
    {printsql}INSERT INTO my_table (id, data) VALUES (?, ?) ON CONFLICT DO NOTHING

.. _sqlite_type_reflection:

Type Reflection
---------------

SQLite types are unlike those of most other database backends, in that
the string name of the type usually does not correspond to a "type" in a
one-to-one fashion.  Instead, SQLite links per-column typing behavior
to one of five so-called "type affinities" based on a string matching
pattern for the type.

SQLAlchemy's reflection process, when inspecting types, uses a simple
lookup table to link the keywords returned to provided SQLAlchemy types.
This lookup table is present within the SQLite dialect as it is for all
other dialects.  However, the SQLite dialect has a different "fallback"
routine for when a particular type name is not located in the lookup map;
it instead implements the SQLite "type affinity" scheme located at
https://www.sqlite.org/datatype3.html section 2.1.

The provided typemap will make direct associations from an exact string
name match for the following types:

:class:`_types.BIGINT`, :class:`_types.BLOB`,
:class:`_types.BOOLEAN`, :class:`_types.BOOLEAN`,
:class:`_types.CHAR`, :class:`_types.DATE`,
:class:`_types.DATETIME`, :class:`_types.FLOAT`,
:class:`_types.DECIMAL`, :class:`_types.FLOAT`,
:class:`_types.INTEGER`, :class:`_types.INTEGER`,
:class:`_types.NUMERIC`, :class:`_types.REAL`,
:class:`_types.SMALLINT`, :class:`_types.TEXT`,
:class:`_types.TIME`, :class:`_types.TIMESTAMP`,
:class:`_types.VARCHAR`, :class:`_types.NVARCHAR`,
:class:`_types.NCHAR`

When a type name does not match one of the above types, the "type affinity"
lookup is used instead:

* :class:`_types.INTEGER` is returned if the type name includes the
  string ``INT``
* :class:`_types.TEXT` is returned if the type name includes the
  string ``CHAR``, ``CLOB`` or ``TEXT``
* :class:`_types.NullType` is returned if the type name includes the
  string ``BLOB``
* :class:`_types.REAL` is returned if the type name includes the string
  ``REAL``, ``FLOA`` or ``DOUB``.
* Otherwise, the :class:`_types.NUMERIC` type is used.

.. _sqlite_partial_index:

Partial Indexes
---------------

A partial index, e.g. one which uses a WHERE clause, can be specified
with the DDL system using the argument ``sqlite_where``::

    tbl = Table("testtbl", m, Column("data", Integer))
    idx = Index(
        "test_idx1",
        tbl.c.data,
        sqlite_where=and_(tbl.c.data > 5, tbl.c.data < 10),
    )

The index will be rendered at create time as:

.. sourcecode:: sql

    CREATE INDEX test_idx1 ON testtbl (data)
    WHERE data > 5 AND data < 10

.. _sqlite_dotted_column_names:

Dotted Column Names
-------------------

Using table or column names that explicitly have periods in them is
**not recommended**.   While this is generally a bad idea for relational
databases in general, as the dot is a syntactically significant character,
the SQLite driver up until version **3.10.0** of SQLite has a bug which
requires that SQLAlchemy filter out these dots in result sets.

The bug, entirely outside of SQLAlchemy, can be illustrated thusly::

    import sqlite3

    assert sqlite3.sqlite_version_info < (
        3,
        10,
        0,
    ), "bug is fixed in this version"

    conn = sqlite3.connect(":memory:")
    cursor = conn.cursor()

    cursor.execute("create table x (a integer, b integer)")
    cursor.execute("insert into x (a, b) values (1, 1)")
    cursor.execute("insert into x (a, b) values (2, 2)")

    cursor.execute("select x.a, x.b from x")
    assert [c[0] for c in cursor.description] == ["a", "b"]

    cursor.execute(
        """
        select x.a, x.b from x where a=1
        union
        select x.a, x.b from x where a=2
        """
    )
    assert [c[0] for c in cursor.description] == ["a", "b"], [
        c[0] for c in cursor.description
    ]

The second assertion fails:

.. sourcecode:: text

    Traceback (most recent call last):
      File "test.py", line 19, in <module>
        [c[0] for c in cursor.description]
    AssertionError: ['x.a', 'x.b']

Where above, the driver incorrectly reports the names of the columns
including the name of the table, which is entirely inconsistent vs.
when the UNION is not present.

SQLAlchemy relies upon column names being predictable in how they match
to the original statement, so the SQLAlchemy dialect has no choice but
to filter these out::


    from sqlalchemy import create_engine

    eng = create_engine("sqlite://")
    conn = eng.connect()

    conn.exec_driver_sql("create table x (a integer, b integer)")
    conn.exec_driver_sql("insert into x (a, b) values (1, 1)")
    conn.exec_driver_sql("insert into x (a, b) values (2, 2)")

    result = conn.exec_driver_sql("select x.a, x.b from x")
    assert result.keys() == ["a", "b"]

    result = conn.exec_driver_sql(
        """
        select x.a, x.b from x where a=1
        union
        select x.a, x.b from x where a=2
        """
    )
    assert result.keys() == ["a", "b"]

Note that above, even though SQLAlchemy filters out the dots, *both
names are still addressable*::

    >>> row = result.first()
    >>> row["a"]
    1
    >>> row["x.a"]
    1
    >>> row["b"]
    1
    >>> row["x.b"]
    1

Therefore, the workaround applied by SQLAlchemy only impacts
:meth:`_engine.CursorResult.keys` and :meth:`.Row.keys()` in the public API. In
the very specific case where an application is forced to use column names that
contain dots, and the functionality of :meth:`_engine.CursorResult.keys` and
:meth:`.Row.keys()` is required to return these dotted names unmodified,
the ``sqlite_raw_colnames`` execution option may be provided, either on a
per-:class:`_engine.Connection` basis::

    result = conn.execution_options(sqlite_raw_colnames=True).exec_driver_sql(
        """
        select x.a, x.b from x where a=1
        union
        select x.a, x.b from x where a=2
        """
    )
    assert result.keys() == ["x.a", "x.b"]

or on a per-:class:`_engine.Engine` basis::

    engine = create_engine(
        "sqlite://", execution_options={"sqlite_raw_colnames": True}
    )

When using the per-:class:`_engine.Engine` execution option, note that
**Core and ORM queries that use UNION may not function properly**.

SQLite-specific table options
-----------------------------

One option for CREATE TABLE is supported directly by the SQLite
dialect in conjunction with the :class:`_schema.Table` construct:

* ``WITHOUT ROWID``::

    Table("some_table", metadata, ..., sqlite_with_rowid=False)

*
  ``STRICT``::

    Table("some_table", metadata, ..., sqlite_strict=True)

  .. versionadded:: 2.0.37

.. seealso::

    `SQLite CREATE TABLE options
    <https://www.sqlite.org/lang_createtable.html>`_

.. _sqlite_include_internal:

Reflecting internal schema tables
----------------------------------

Reflection methods that return lists of tables will omit so-called
"SQLite internal schema object" names, which are considered by SQLite
as any object name that is prefixed with ``sqlite_``.  An example of
such an object is the ``sqlite_sequence`` table that's generated when
the ``AUTOINCREMENT`` column parameter is used.   In order to return
these objects, the parameter ``sqlite_include_internal=True`` may be
passed to methods such as :meth:`_schema.MetaData.reflect` or
:meth:`.Inspector.get_table_names`.

.. versionadded:: 2.0  Added the ``sqlite_include_internal=True`` parameter.
   Previously, these tables were not ignored by SQLAlchemy reflection
   methods.

.. note::

    The ``sqlite_include_internal`` parameter does not refer to the
    "system" tables that are present in schemas such as ``sqlite_master``.

.. seealso::

    `SQLite Internal Schema Objects <https://www.sqlite.org/fileformat2.html#intschema>`_ - in the SQLite
    documentation.

    )annotationsN)Optional   )JSON)JSONIndexType)JSONPathType   )excschema)sql)text)types)util)default)
processors)
reflection)ReflectionDefaults)	coercions)ColumnElement)compiler)elements)roles)BLOB)BOOLEAN)CHAR)DECIMAL)FLOAT)INTEGER)NUMERIC)REAL)SMALLINT)TEXT)	TIMESTAMP)VARCHARc                      s   e Zd Z fddZ  ZS )_SQliteJsonc                   s   t  ||  fdd}|S )Nc                   s0   z | W S  t y   t| tjr|  Y S  w N)	TypeError
isinstancenumbersNumbervaluedefault_processor a/var/www/html/ecg_monitoring/venv/lib/python3.10/site-packages/sqlalchemy/dialects/sqlite/base.pyprocess  s   
z-_SQliteJson.result_processor.<locals>.process)superresult_processor)selfdialectcoltyper1   	__class__r-   r0   r3     s   	z_SQliteJson.result_processor)__name__
__module____qualname__r3   __classcell__r/   r/   r7   r0   r%     s    r%   c                      sF   e Zd ZdZdZd
 fdd	Zedd Z fddZdd	 Z	  Z
S )_DateTimeMixinNc                   s<   t  jdi | |d urt|| _|d ur|| _d S d S )Nr/   )r2   __init__recompile_reg_storage_format)r4   storage_formatregexpkwr7   r/   r0   r>     s   
z_DateTimeMixin.__init__c              	   C  s*   | j dddddddd }ttd|S )a?  return True if the storage format will automatically imply
        a TEXT affinity.

        If the storage format contains no non-numeric characters,
        it will imply a NUMERIC storage format on SQLite; in this case,
        the type will generate its DDL as DATE_CHAR, DATETIME_CHAR,
        TIME_CHAR.

        r   yearmonthdayhourminutesecondmicrosecondz[^0-9])rB   boolr?   search)r4   specr/   r/   r0   format_is_text_affinity  s   	z&_DateTimeMixin.format_is_text_affinityc                   s>   t |tr| jr| j|d< | jr| j|d< t j|fi |S )NrC   rD   )
issubclassr=   rB   rA   r2   adapt)r4   clsrE   r7   r/   r0   rS     s   


z_DateTimeMixin.adaptc                   s   |  |  fdd}|S )Nc                   s   d |  S )N'%s'r/   r+   bpr/   r0   r1     s   z1_DateTimeMixin.literal_processor.<locals>.process)bind_processorr4   r5   r1   r/   rV   r0   literal_processor  s   
z _DateTimeMixin.literal_processor)NN)r9   r:   r;   rA   rB   r>   propertyrQ   rS   rZ   r<   r/   r/   r7   r0   r=     s    
r=   c                      4   e Zd ZdZdZ fddZdd Zdd Z  ZS )	DATETIMEa  Represent a Python datetime object in SQLite using a string.

    The default string storage format is::

        "%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"

    e.g.:

    .. sourcecode:: text

        2021-03-15 12:05:57.105542

    The incoming storage format is by default parsed using the
    Python ``datetime.fromisoformat()`` function.

    .. versionchanged:: 2.0  ``datetime.fromisoformat()`` is used for default
       datetime string parsing.

    The storage format can be customized to some degree using the
    ``storage_format`` and ``regexp`` parameters, such as::

        import re
        from sqlalchemy.dialects.sqlite import DATETIME

        dt = DATETIME(
            storage_format=(
                "%(year)04d/%(month)02d/%(day)02d %(hour)02d:%(minute)02d:%(second)02d"
            ),
            regexp=r"(\d+)/(\d+)/(\d+) (\d+)-(\d+)-(\d+)",
        )

    :param storage_format: format string which will be applied to the dict
     with keys year, month, day, hour, minute, second, and microsecond.

    :param regexp: regular expression which will be applied to incoming result
     rows, replacing the use of ``datetime.fromisoformat()`` to parse incoming
     strings. If the regexp contains named groups, the resulting match dict is
     applied to the Python datetime() constructor as keyword arguments.
     Otherwise, if positional groups are used, the datetime() constructor
     is called with positional arguments via
     ``*map(int, match_obj.groups(0))``.

    zW%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06dc                   P   | dd}t j|i | |r&d|vsJ dd|vs!J dd| _d S d S )Ntruncate_microsecondsFrC   DYou can specify only one of truncate_microseconds or storage_format.rD   <You can specify only one of truncate_microseconds or regexp.zE%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02dpopr2   r>   rB   r4   argskwargsr_   r7   r/   r0   r>   .  s   

zDATETIME.__init__c                   s&   t j t j | j fdd}|S )Nc              	     sl   | d u rd S t | r| j| j| j| j| j| j| jd S t |  r2| j| j| jddddd S td)NrF   r   zLSQLite DateTime type only accepts Python datetime and date objects as input.)	r(   rG   rH   rI   rJ   rK   rL   rM   r'   r+   datetime_datedatetime_datetimeformat_r/   r0   r1   D  s2   

	
z(DATETIME.bind_processor.<locals>.processdatetimedaterB   rY   r/   rg   r0   rX   ?  s
   zDATETIME.bind_processorc                 C  s   | j rt| j tjS tjS r&   )rA   r   !str_to_datetime_processor_factoryrl   str_to_datetimer4   r5   r6   r/   r/   r0   r3   c  
   zDATETIME.result_processor	r9   r:   r;   __doc__rB   r>   rX   r3   r<   r/   r/   r7   r0   r]     s    -$r]   c                   @  s$   e Zd ZdZdZdd Zdd ZdS )DATEaN  Represent a Python date object in SQLite using a string.

    The default string storage format is::

        "%(year)04d-%(month)02d-%(day)02d"

    e.g.:

    .. sourcecode:: text

        2011-03-15

    The incoming storage format is by default parsed using the
    Python ``date.fromisoformat()`` function.

    .. versionchanged:: 2.0  ``date.fromisoformat()`` is used for default
       date string parsing.


    The storage format can be customized to some degree using the
    ``storage_format`` and ``regexp`` parameters, such as::

        import re
        from sqlalchemy.dialects.sqlite import DATE

        d = DATE(
            storage_format="%(month)02d/%(day)02d/%(year)04d",
            regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)"),
        )

    :param storage_format: format string which will be applied to the
     dict with keys year, month, and day.

    :param regexp: regular expression which will be applied to
     incoming result rows, replacing the use of ``date.fromisoformat()`` to
     parse incoming strings. If the regexp contains named groups, the resulting
     match dict is applied to the Python date() constructor as keyword
     arguments. Otherwise, if positional groups are used, the date()
     constructor is called with positional arguments via
     ``*map(int, match_obj.groups(0))``.

    z %(year)04d-%(month)02d-%(day)02dc                      t j | j fdd}|S )Nc                   s4   | d u rd S t |  r| j| j| jd S td)N)rG   rH   rI   z;SQLite Date type only accepts Python date objects as input.)r(   rG   rH   rI   r'   r+   rh   rj   r/   r0   r1     s   
z$DATE.bind_processor.<locals>.processrk   rY   r/   rv   r0   rX     s   zDATE.bind_processorc                 C     | j rt| j tjS tjS r&   )rA   r   rn   rl   rm   str_to_daterp   r/   r/   r0   r3     rq   zDATE.result_processorN)r9   r:   r;   rs   rB   rX   r3   r/   r/   r/   r0   rt   l  s
    +rt   c                      r\   )	TIMEa  Represent a Python time object in SQLite using a string.

    The default string storage format is::

        "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d"

    e.g.:

    .. sourcecode:: text

        12:05:57.10558

    The incoming storage format is by default parsed using the
    Python ``time.fromisoformat()`` function.

    .. versionchanged:: 2.0  ``time.fromisoformat()`` is used for default
       time string parsing.

    The storage format can be customized to some degree using the
    ``storage_format`` and ``regexp`` parameters, such as::

        import re
        from sqlalchemy.dialects.sqlite import TIME

        t = TIME(
            storage_format="%(hour)02d-%(minute)02d-%(second)02d-%(microsecond)06d",
            regexp=re.compile("(\d+)-(\d+)-(\d+)-(?:-(\d+))?"),
        )

    :param storage_format: format string which will be applied to the dict
     with keys hour, minute, second, and microsecond.

    :param regexp: regular expression which will be applied to incoming result
     rows, replacing the use of ``datetime.fromisoformat()`` to parse incoming
     strings. If the regexp contains named groups, the resulting match dict is
     applied to the Python time() constructor as keyword arguments. Otherwise,
     if positional groups are used, the time() constructor is called with
     positional arguments via ``*map(int, match_obj.groups(0))``.

    z6%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06dc                   r^   )Nr_   FrC   r`   rD   ra   z$%(hour)02d:%(minute)02d:%(second)02drb   rd   r7   r/   r0   r>     s   


zTIME.__init__c                   ru   )Nc                   s8   | d u rd S t |  r| j| j| j| jd S td)N)rJ   rK   rL   rM   z;SQLite Time type only accepts Python time objects as input.)r(   rJ   rK   rL   rM   r'   r+   datetime_timerj   r/   r0   r1     s   
z$TIME.bind_processor.<locals>.process)rl   timerB   rY   r/   rz   r0   rX     s   zTIME.bind_processorc                 C  rw   r&   )rA   r   rn   rl   r|   str_to_timerp   r/   r/   r0   r3     rq   zTIME.result_processorrr   r/   r/   r7   r0   ry     s    )ry   BIGINTr   BOOLr   r   	DATE_CHARDATETIME_CHARDOUBLEr   r   INTr   r   r   r    )r!   r"   ry   	TIME_CHARr#   r$   NVARCHARNCHARc                      s  e Zd Zeejjddddddddd	d
d
Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Z f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d,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Zd<d= Z   Z!S )>SQLiteCompilerz%mz%dz%Yz%Sz%Hz%jz%Mz%sz%wz%W)
rH   rI   rG   rL   rJ   doyrK   epochdowweekc                 K  s0   | j |jfi |d d| j |jfi |  S )Nz / z
(%s + 0.0)r1   leftrightr4   binaryoperatorrE   r/   r/   r0   visit_truediv_binaryH  s   z#SQLiteCompiler.visit_truediv_binaryc                 K     dS )NCURRENT_TIMESTAMPr/   r4   fnrE   r/   r/   r0   visit_now_funcO     zSQLiteCompiler.visit_now_funcc                 K  r   )Nz(DATETIME(CURRENT_TIMESTAMP, "localtime")r/   )r4   funcrE   r/   r/   r0   visit_localtimestamp_funcR  r   z(SQLiteCompiler.visit_localtimestamp_funcc                 K  r   )N1r/   r4   exprrE   r/   r/   r0   
visit_trueU  r   zSQLiteCompiler.visit_truec                 K  r   )N0r/   r   r/   r/   r0   visit_falseX  r   zSQLiteCompiler.visit_falsec                 K     d|  | S )Nzlength%sfunction_argspecr   r/   r/   r0   visit_char_length_func[     z%SQLiteCompiler.visit_char_length_funcc                 K  r   )Nzgroup_concat%sr   r   r/   r/   r0   visit_aggregate_strings_func^  r   z+SQLiteCompiler.visit_aggregate_strings_funcc                   s0   | j jrt j|fi |S | j|jfi |S r&   )r5   supports_castr2   
visit_castr1   clause)r4   castrf   r7   r/   r0   r   a  s   zSQLiteCompiler.visit_castc              
   K  sR   zd| j |j | j|jfi |f W S  ty( } z	td|j |d }~ww )Nz#CAST(STRFTIME('%s', %s) AS INTEGER)z#%s is not a valid extract argument.)extract_mapfieldr1   r   KeyErrorr	   CompileError)r4   extractrE   errr/   r/   r0   visit_extractg  s   
zSQLiteCompiler.visit_extractc                  s"   d|d< t  j||fd|i|S )NFinclude_tablepopulate_result_map)r2   returning_clause)r4   stmtreturning_colsr   rE   r7   r/   r0   r   r  s   zSQLiteCompiler.returning_clausec                 K  s   d}|j d ur|d| j|j fi | 7 }|jd ur;|j d u r+|d| td 7 }|d| j|jfi | 7 }|S |d| jtdfi | 7 }|S )N z
 LIMIT z OFFSET r   )_limit_clauser1   _offset_clauser   literal)r4   selectrE   r   r/   r/   r0   limit_clause  s   


 zSQLiteCompiler.limit_clausec                 K  r   )Nr   r/   )r4   r   rE   r/   r/   r0   for_update_clause  s   z SQLiteCompiler.for_update_clausec                   s(   dd< dd  fdd|D  S )NTasfromzFROM , c                 3  s&    | ]}|j fd  iV  qdS )	fromhintsN)_compiler_dispatch).0t
from_hintsrE   r4   r/   r0   	<genexpr>  s
    
z4SQLiteCompiler.update_from_clause.<locals>.<genexpr>)join)r4   update_stmt
from_tableextra_fromsr   rE   r/   r   r0   update_from_clause  s   
z!SQLiteCompiler.update_from_clausec                 K     d|  |j|  |jf S )Nz%s IS NOT %sr   r   r/   r/   r0   visit_is_distinct_from_binary     

z,SQLiteCompiler.visit_is_distinct_from_binaryc                 K  r   )Nz%s IS %sr   r   r/   r/   r0   !visit_is_not_distinct_from_binary  r   z0SQLiteCompiler.visit_is_not_distinct_from_binaryc                 K  D   |j jtju r
d}nd}|| j|jfi || j|jfi |f S Nz JSON_QUOTE(JSON_EXTRACT(%s, %s))zJSON_EXTRACT(%s, %s)type_type_affinitysqltypesr   r1   r   r   r4   r   r   rE   r   r/   r/   r0   visit_json_getitem_op_binary     z+SQLiteCompiler.visit_json_getitem_op_binaryc                 K  r   r   r   r   r/   r/   r0   !visit_json_path_getitem_op_binary  r   z0SQLiteCompiler.visit_json_path_getitem_op_binaryc                 K  
   |  |S r&   )visit_empty_set_expr)r4   type_	expand_oprE   r/   r/   r0   visit_empty_set_op_expr  s   
z&SQLiteCompiler.visit_empty_set_op_exprc                 K  s<   dd dd |pt gD d dd |pt gD f S )Nz%SELECT %s FROM (SELECT %s) WHERE 1!=1r   c                 s      | ]}d V  qdS r   Nr/   r   r   r/   r/   r0   r         z6SQLiteCompiler.visit_empty_set_expr.<locals>.<genexpr>c                 s  r   r   r/   r   r/   r/   r0   r     r   )r   r   )r4   element_typesrE   r/   r/   r0   r     s   z#SQLiteCompiler.visit_empty_set_exprc                 K     | j |dfi |S )Nz REGEXP _generate_generic_binaryr   r/   r/   r0   visit_regexp_match_op_binary     z+SQLiteCompiler.visit_regexp_match_op_binaryc                 K  r   )Nz NOT REGEXP r   r   r/   r/   r0    visit_not_regexp_match_op_binary  r   z/SQLiteCompiler.visit_not_regexp_match_op_binaryc                   sZ   |j d ur)dd fdd|j D  }|jd ur'|d j|jdddd 7 }|S d	}|S )
Nz(%s)r   c                 3  s6    | ]}t |tr j|n j|d d dV  qdS )Fr   
use_schemaN)r(   strpreparerquoter1   r   cr4   r/   r0   r     s    
z5SQLiteCompiler._on_conflict_target.<locals>.<genexpr>	 WHERE %sFT)r   r   literal_executer   )inferred_target_elementsr   inferred_target_whereclauser1   )r4   r   rE   target_textr/   r   r0   _on_conflict_target  s   




z"SQLiteCompiler._on_conflict_targetc                 K  s"   | j |fi |}|rd| S dS )NzON CONFLICT %s DO NOTHINGzON CONFLICT DO NOTHING)r   )r4   on_conflictrE   r   r/   r/   r0   visit_on_conflict_do_nothing  s   z+SQLiteCompiler.visit_on_conflict_do_nothingc                 K  s  |}| j |fi |}g }t|j}| jd d }|jj}|D ]T}	|	j}
|
|v r.||
}n|	|v r8||	}nqt	|rHt
jd ||	jd}nt|t
jrZ|jjrZ| }|	j|_| j| dd}| j|	j}|d||f  q|rtd| jjjdd	d
 |D f  | D ]+\}}t|tr| j|n| j|dd}| jttj|dd}|d||f  qd|}|jd ur|d| j|jddd 7 }d||f S )Nr   
selectable)r   Fr   z%s = %szFAdditional column names not matching any column keys in table '%s': %sr   c                 s  s    | ]}d | V  qdS )rU   Nr/   r   r/   r/   r0   r     s    z=SQLiteCompiler.visit_on_conflict_do_update.<locals>.<genexpr>r   Tr   zON CONFLICT %s DO UPDATE SET %s) r   dictupdate_values_to_setstacktabler   keyrc   r   _is_literalr   BindParameterr   r(   _isnull_cloner1   
self_groupr   r   nameappendr   warncurrent_executabler   itemsr   expectr   ExpressionElementRoleupdate_whereclause)r4   r   rE   r   r   action_set_opsset_parametersinsert_statementcolsr   col_keyr,   
value_textkey_textkvaction_textr/   r/   r0   visit_on_conflict_do_update  s`   





z*SQLiteCompiler.visit_on_conflict_do_updatec                 K  sB   d|d< | j |dfi |}| j |dfi |}d| d| dS )NTeager_groupingz | z & (z - )r   )r4   r   r   rE   or_and_r/   r/   r0   visit_bitwise_xor_op_binary-  s   z*SQLiteCompiler.visit_bitwise_xor_op_binary)"r9   r:   r;   r   update_copyr   SQLCompilerr   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/   r7   r0   r   7  sP    	Cr   c                      sp   e Zd Zdd Z fddZ fddZ fddZ fd	d
Z fddZdd Z		dddZ
dd Z  ZS )SQLiteDDLCompilerc                 K  sH  | j jj|j|d}| j|d | }| |}|d ur0t|jj	t
r*d| d }|d| 7 }|jsH|d7 }|jd d }|d urH|d	| 7 }|jr|jd
u r^t|jjjdkr^td|jjd d rt|jjjdkrt|jjtjr|js|d7 }|jd d }|d ur|d	| 7 }|d7 }|jd ur|d| |j 7 }|S )N)type_expression r  r  z	 DEFAULT z	 NOT NULLsqliteon_conflict_not_null ON CONFLICT Tr   z@SQLite does not support autoincrement for composite primary keysautoincrementz PRIMARY KEYon_conflict_primary_keyz AUTOINCREMENT)r5   type_compiler_instancer1   r   r   format_columnget_column_default_stringr(   server_defaultargr   nullabledialect_optionsprimary_keyr(  lenr   columnsr	   r   rR   r   r   Integerforeign_keyscomputed)r4   columnrf   r6   colspecr   on_conflict_clauser/   r/   r0   get_column_specification6  sN   


z*SQLiteDDLCompiler.get_column_specificationc                   s   t |jdkr%t|d }|jr%|jjd d r%t|jjt	j
r%|js%d S t |}|jd d }|d u rHt |jdkrHt|d jd d }|d urR|d| 7 }|S )Nr   r   r%  r(  r   r)  r'  )r2  r3  listr1  r   r0  rR   r   r   r   r4  r5  r2   visit_primary_key_constraint)r4   
constraintrE   r   r   r9  r7   r/   r0   r<  i  s,   z.SQLiteDDLCompiler.visit_primary_key_constraintc                   sv   t  |}|jd d }|d u r/t|jdkr/t|d }t|tjr/t|d jd d }|d ur9|d| 7 }|S )Nr%  r   r   r   on_conflict_uniquer'  )	r2   visit_unique_constraintr0  r2  r3  r;  r(   r   
SchemaItem)r4   r=  rE   r   r9  col1r7   r/   r0   r?    s   z)SQLiteDDLCompiler.visit_unique_constraintc                   s2   t  |}|jd d }|d ur|d| 7 }|S )Nr%  r   r'  )r2   visit_check_constraintr0  )r4   r=  rE   r   r9  r7   r/   r0   rB    s   z(SQLiteDDLCompiler.visit_check_constraintc                   s,   t  |}|jd d d urtd|S )Nr%  r   zFSQLite does not support on conflict clause for column check constraint)r2   visit_column_check_constraintr0  r	   r   )r4   r=  rE   r   r7   r/   r0   rC    s   z/SQLiteDDLCompiler.visit_column_check_constraintc                   s8   |j d jj}|j d jj}|j|jkrd S t |S )Nr   )r   parentr   r7  r   r2   visit_foreign_key_constraint)r4   r=  rE   local_tableremote_tabler7   r/   r0   rE    s
   z.SQLiteDDLCompiler.visit_foreign_key_constraintc                 C  s   |j |ddS )z=Format the remote table clause of a CREATE CONSTRAINT clause.Fr   )format_table)r4   r=  r   r   r/   r/   r0   define_constraint_remote_table  s   z0SQLiteDDLCompiler.define_constraint_remote_tableFTc           
   	     s   |j } |  j}d}|jr|d7 }|d7 }|jr|d7 }|d j|dd|j|jdd	d
 fdd|j	D f 7 }|j
d d }|d urX jj|ddd}	|d|	 7 }|S )NzCREATE zUNIQUE zINDEX zIF NOT EXISTS z%s ON %s (%s)T)include_schemaFr   r   c                 3  s"    | ]} j j|d ddV  qdS )FTr   literal_bindsN)sql_compilerr1   )r   r   r   r/   r0   r     s    
z7SQLiteDDLCompiler.visit_create_index.<locals>.<genexpr>r%  whererK  z WHERE )element_verify_index_tabler   uniqueif_not_exists_prepared_index_namerH  r   r   expressionsr0  rM  r1   )
r4   createrJ  include_table_schemarE   indexr   r   whereclausewhere_compiledr/   r   r0   visit_create_index  s.   
z$SQLiteDDLCompiler.visit_create_indexc                 C  s<   d}|j d d du r|d7 }|j d d du r|d7 }|S )	Nr   r%  
with_rowidFz
 WITHOUT ROWIDstrictTz
 STRICT)r0  )r4   r   r   r/   r/   r0   post_create_table  s   z#SQLiteDDLCompiler.post_create_table)FT)r9   r:   r;   r:  r<  r?  rB  rC  rE  rI  rZ  r]  r<   r/   r/   r7   r0   r"  5  s    3	
#r"  c                      sD   e Zd Zdd Z fddZ fddZ fddZd	d
 Z  ZS )SQLiteTypeCompilerc                 K  r   r&   )
visit_BLOBr4   r   rE   r/   r/   r0   visit_large_binary     
z%SQLiteTypeCompiler.visit_large_binaryc                       t |tr|jrt |S dS )Nr   )r(   r=   rQ   r2   visit_DATETIMEr`  r7   r/   r0   rd       z!SQLiteTypeCompiler.visit_DATETIMEc                   rc  )Nr   )r(   r=   rQ   r2   
visit_DATEr`  r7   r/   r0   rf    re  zSQLiteTypeCompiler.visit_DATEc                   rc  )Nr   )r(   r=   rQ   r2   
visit_TIMEr`  r7   r/   r0   rg    re  zSQLiteTypeCompiler.visit_TIMEc                 K  r   )Nr   r/   r`  r/   r/   r0   
visit_JSON  s   zSQLiteTypeCompiler.visit_JSON)	r9   r:   r;   ra  rd  rf  rg  rh  r<   r/   r/   r7   r0   r^    s    			r^  c                   @  s   e Zd Zh dZdS )SQLiteIdentifierPreparer>u   asbyifinisofonortoaddallandascendforr  notrowsetcaser   descdropeachelsefailfromfullglobintor   r   likenullplantempthentrueviewwhenafteralterbegincheckcrossfalsegrouprW  innerlimitmatchorderouterqueryraiser   r   unionusingrN  attachbeforer7  commitrU  deletedetachescapeexceptexistshavingignoreinsertisnulloffsetpragmarenamer   rQ  updatevacuumvaluesanalyzebetweencascadecollater   explainforeignindexedinsteadnaturalnotnullprimaryreindexreplacetriggervirtualconflictdatabasedeferreddistinctrestrictrollback	exclusive	immediate	initially	intersect	temporaryr=  
deferrable
referencestransactioncurrent_datecurrent_timer(  current_timestampN)r9   r:   r;   reserved_wordsr/   r/   r/   r0   ri    s    ri  c                   @  s"   e Zd Zejdd Zdd ZdS )SQLiteExecutionContextc                 C  s   | j j p| jddS )Nsqlite_raw_colnamesF)r5   _broken_dotted_colnamesexecution_optionsgetr   r/   r/   r0   _preserve_raw_colnames  s   
z-SQLiteExecutionContext._preserve_raw_colnamesc                 C  s(   | j sd|v r|dd |fS |d fS )N.r   )r  split)r4   colnamer/   r/   r0   _translate_colname  s   z)SQLiteExecutionContext._translate_colnameN)r9   r:   r;   r   memoized_propertyr  r  r/   r/   r/   r0   r    s    
r  c                   @  s6  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dZdZdZdZ	 dZ	 dZeZeZeZeZeZeZe Z e!j"ddddfe!j#ddife!j$dddd	fe!j%d
difgZ&dZ'dZ(e)j*ddd					dLddZ+e),dddZ-dd Z.dd Z/dd Z0e1j2dd Z3dd Z4dMd$d%Z5e1j2	dNd&d'Z6e1j2	dOd(d)Z7e1j2	dOd*d+Z8e1j2dPd,d-Z9d.d/ Z:e1j2	dNd0d1Z;e1j2dPd2d3Z<e1j2dPd4d5Z=d6d7 Z>d8d9 Z?e1j2dPd:d;Z@e1j2dPd<d=ZAd>d? ZBe1j2	dPd@dAZCe1j2dPdBdCZDe1j2dPdDdEZEdFdG ZFe1j2dPdHdIZGdPdJdKZHdS )QSQLiteDialectr%  FTNULLqmark)r(  r[  r\  rN  N)r)  r&  r>  r   )1.3.7zThe _json_serializer argument to the SQLite dialect has been renamed to the correct name of json_serializer.  The old argument name will be removed in a future release.)r  zThe _json_deserializer argument to the SQLite dialect has been renamed to the correct name of json_deserializer.  The old argument name will be removed in a future release.)_json_serializer_json_deserializerc                 K  s   t jj| fi | |r|}|r|}|| _|| _|| _| jd urp| jjdk r0t	d| jjf  | jjdk | _
| jjdk| _| jjdk| _| jjdk| _| jjdk | _| jjdk s\tjred	 | _ | _| _| jjd
k rrd| _d S d S d S )N)r         zSQLite version %s is older than 3.7.16, and will not support right nested joins, as are sometimes used in more complex ORM scenarios.  SQLAlchemy 1.4 and above no longer tries to rewrite these joins.)r   
   r   )r   r      )r      r   )r   r     )r         )r   #   F)r       r   i  )r   DefaultDialectr>   r  r  native_datetimedbapisqlite_version_infor   r	  r  supports_default_valuesr   supports_multivalues_insert_broken_fk_pragma_quotespypyupdate_returningdelete_returninginsert_returninginsertmanyvalues_max_parameters)r4   r  json_serializerjson_deserializerr  r  rf   r/   r/   r0   r>     s>   


)zSQLiteDialect.__init__r   r   )READ UNCOMMITTEDSERIALIZABLEc                 C  s
   t | jS r&   )r;  _isolation_lookup)r4   dbapi_connectionr/   r/   r0   get_isolation_level_values:  rb  z(SQLiteDialect.get_isolation_level_valuesc                 C  s.   | j | }| }|d|  |  d S )NzPRAGMA read_uncommitted = )r  cursorexecuteclose)r4   r  levelisolation_levelr  r/   r/   r0   set_isolation_level=  s   
z!SQLiteDialect.set_isolation_levelc                 C  sX   |  }|d | }|r|d }nd}|  |dkr dS |dkr&dS J d| )NzPRAGMA read_uncommittedr   r  r   r  FzUnknown isolation level %s)r  r   fetchoner  )r4   r  r  resr,   r/   r/   r0   get_isolation_levelD  s   

z!SQLiteDialect.get_isolation_levelc                 K  s   d}| |}dd |D S )NzPRAGMA database_listc                 S  s    g | ]}|d  dkr|d  qS )r   r  r/   )r   dbr/   r/   r0   
<listcomp>_       z2SQLiteDialect.get_schema_names.<locals>.<listcomp>)exec_driver_sql)r4   
connectionrE   sdlr/   r/   r0   get_schema_namesZ  s   
zSQLiteDialect.get_schema_namesc                 C  s.   |d ur| j |}| d| }|S |}|S )Nr  )identifier_preparerquote_identifier)r4   r   
table_nameqschemar  r/   r/   r0   _format_schemaa  s   zSQLiteDialect._format_schemar   r   r   r   Optional[str]sqlite_include_internalrN   c                 C  s6   |  ||}|sd}nd}d| d| d| d}|S )Nz) AND name NOT LIKE 'sqlite~_%' ESCAPE '~'r   zSELECT name FROM z WHERE type=''z ORDER BY name)r  )r4   r   r   r   r  mainfilter_tabler  r/   r/   r0   _sqlite_main_queryi  s   z SQLiteDialect._sqlite_main_queryc                 K  &   |  dd||}||  }|S )Nsqlite_masterr   r  r  scalarsrt  r4   r  r   r  rE   r  namesr/   r/   r0   get_table_names|  
   zSQLiteDialect.get_table_namesc                 K  &   |  ddd |}||  }|S )Nsqlite_temp_masterr   r  r4   r  r  rE   r  r   r/   r/   r0   get_temp_table_names  r"  z"SQLiteDialect.get_temp_table_namesc                 K  r#  )Nr$  r  r  r%  r/   r/   r0   get_temp_view_names  r"  z!SQLiteDialect.get_temp_view_namesc                 K  sF   |  | |d ur|| j|fi |vrdS | j|d||d}t|S )NF
table_infor
   )_ensure_has_table_connectionr  _get_table_pragmarN   )r4   r  r  r   rE   infor/   r/   r0   	has_table  s   
zSQLiteDialect.has_tablec                 C  r   )Nr  r/   )r4   r  r/   r/   r0   _get_default_schema_name  r   z&SQLiteDialect._get_default_schema_namec                 K  r  )Nr  r  r  r  r/   r/   r0   get_view_names  r"  zSQLiteDialect.get_view_namesc           
      K  s   |d ur| j |}| d}d|f }|||f}nzd}|||f}W n tjy:   d}|||f}Y nw | }	|	rF|	d jS t|rR| d| |)Nz.sqlite_masterz1SELECT sql FROM %s WHERE name = ? AND type='view'zzSELECT sql FROM  (SELECT * FROM sqlite_master UNION ALL   SELECT * FROM sqlite_temp_master) WHERE name = ? AND type='view'z<SELECT sql FROM sqlite_master WHERE name = ? AND type='view'r   r  )r  r  r  r	   
DBAPIErrorfetchallr   NoSuchTableError)
r4   r  	view_namer   rE   r  masterr  rsresultr/   r/   r0   get_view_definition  s0   

z!SQLiteDialect.get_view_definitionc                 K  sH  d}| j dkr	d}| j||||d}g }d }|D ]m}	|	d }
|	d  }|	d  }|	d }|	d	 }|dkr9|	d
 nd}|dkr@qt|}|dk}|d u rv|rv| j|||fi |}td| tjtj	B }|soJ d| |
d }|| |
||||||| q|r|S | |||st|r| d| |t S )Nr(  )r      table_xinfor
   r   r  r         r  r   zcreate table .*?\((.*)\)$zcreate table not found in r  )server_version_infor*  upperrN   _get_table_sqlr?   r  stripDOTALL
IGNORECASEr  r  _get_column_infor,  r	   r1  r   r3  )r4   r  r  r   rE   r  r+  r3  tablesqlrz  r  r   r/  r   r1  hidden	generated	persistedr  r/   r/   r0   get_columns  sj   


zSQLiteDialect.get_columnsc	                 C  s   |rt jdd|t jd}t jdd|t jd }| |}	|d ur%t|}||	|||d}
|rPd}|rId}t t || |t j}|rI|d}||d|
d	< |
S )
NrD  r   )flagsalways)r  r   r/  r   r1  z@[^,]*\s+GENERATED\s+ALWAYS\s+AS\s+\((.*)\)\s*(?:virtual|stored)?r   )sqltextrE  r6  )	r?   subr@  r>  _resolve_type_affinityr   rO   r  r  )r4   r  r   r/  r   r1  rD  rE  rB  r6   r8  rI  patternr  r/   r/   r0   rA  	  s0   

zSQLiteDialect._get_column_infoc                 C  s  t d|}|r|d}|d}nd}d}|| jv r"| j| }n5d|v r*tj}n-d|v s6d|v s6d|v r:tj}nd	|v s@|sDtj}nd
|v sPd|v sPd|v rTtj}ntj	}|durt 
d|}z|dd |D  }W |S  ty   td||f  | }Y |S w | }|S )aZ  Return a data type from a reflected column, using affinity rules.

        SQLite's goal for universal compatibility introduces some complexity
        during reflection, as a column's defined type might not actually be a
        type that SQLite understands - or indeed, my not be defined *at all*.
        Internally, SQLite handles this with a 'data type affinity' for each
        column definition, mapping to one of 'TEXT', 'NUMERIC', 'INTEGER',
        'REAL', or 'NONE' (raw bits). The algorithm that determines this is
        listed in https://www.sqlite.org/datatype3.html section 2.1.

        This method allows SQLAlchemy to support that algorithm, while still
        providing access to smarter reflection utilities by recognizing
        column definitions that SQLite only supports through affinity (like
        DATE and DOUBLE).

        z([\w ]+)(\(.*?\))?r   r  r   r   r   CLOBr"   r   r    FLOADOUBNz(\d+)c                 S  s   g | ]}t |qS r/   )int)r   ar/   r/   r0   r	  j	      z8SQLiteDialect._resolve_type_affinity.<locals>.<listcomp>zNCould not instantiate type %s with reflected arguments %s; using no arguments.)r?   r  r  ischema_namesr   r   r"   NullTyper    r   findallr'   r   r	  )r4   r   r  r6   re   r/   r/   r0   rK  A	  sB   

z$SQLiteDialect._resolve_type_affinityc                 K  s   d }| j |||d}|rd}t||tj}|r|dnd }| j|||fi |}	dd |	D }	|	jdd d d	d |	D }
|
rG|
|d
S t S )Nr
   zCONSTRAINT (\w+) PRIMARY KEYr   c                 S  s    g | ]}| d ddkr|qS )r1  r   r  r   colr/   r/   r0   r	  	  r
  z3SQLiteDialect.get_pk_constraint.<locals>.<listcomp>c                 S  s
   |  dS )Nr1  rV  )rX  r/   r/   r0   <lambda>	  s   
 z1SQLiteDialect.get_pk_constraint.<locals>.<lambda>r  c                 S  s   g | ]}|d  qS )r  r/   rW  r/   r/   r0   r	  	  rR  )constrained_columnsr  )	r=  r?   rO   Ir  rF  sortr   pk_constraint)r4   r  r  r   rE   constraint_name
table_data
PK_PATTERNr5  r  pkeysr/   r/   r0   get_pk_constraintw	  s   
zSQLiteDialect.get_pk_constraintc              	     s  j |d||d}i }|D ]k}|d |d |d |d f\}}	}
}|sBzj||	fd|i|}|d }W n tjyA   g }Y nw g }jrNtd	d
|	}	||v rW|| }nd g ||	|i d }||< |||< |d |
 |rx|d | qdd   fdd| D }j	|||dfdd}g }| D ]-\}}}}} |||}||vrt
d||f  q||}||d< ||d< || q||  |r|S t S )Nforeign_key_listr
   r   r  r   r9  r   r[  z^[\"\[`\']|[\"\]`\']$r   )r  r[  referred_schemareferred_tablereferred_columnsoptionsrg  c                 S  s   t | |f t | S r&   )tupler[  rf  rg  r/   r/   r0   fk_sig	  s   z.SQLiteDialect.get_foreign_keys.<locals>.fk_sigc                   s&   i | ]} |d  |d |d |qS rj  r/   )r   fk)rk  r/   r0   
<dictcomp>	  s    z2SQLiteDialect.get_foreign_keys.<locals>.<dictcomp>c                  3  s.   d u rd S d} t | t jD ]}|dddddddd	\}}}}}}}}	t |}|s3|}nt |}|p=|}i }
t d
| D ]1}|drb|dd  	 }|ra|dkra||
d< qH|dry|dd  	 }|ry|dkry||
d< qH|rd| v|
d< |	r|	 |
d< |||||
fV  qd S )Na  (?:CONSTRAINT (\w+) +)?FOREIGN KEY *\( *(.+?) *\) +REFERENCES +(?:(?:"(.+?)")|([a-z0-9_]+)) *\( *((?:(?:"[^"]+"|[a-z0-9_]+) *(?:, *)?)+)\) *((?:ON (?:DELETE|UPDATE) (?:SET NULL|SET DEFAULT|CASCADE|RESTRICT|NO ACTION) *)*)((?:NOT +)?DEFERRABLE)?(?: +INITIALLY +(DEFERRED|IMMEDIATE))?r   r  r   r9  r:  r  r  r  z
 *\bON\b *DELETEz	NO ACTIONondeleteUPDATEonupdateNOTr  r  )
r?   finditerr\  r  r;  _find_cols_in_sigr  r<  
startswithr>  )
FK_PATTERNr  r_  r[  referred_quoted_namereferred_namerg  onupdatedeleter  r  rh  tokenro  rq  r4   r`  r/   r0   	parse_fks	  s`   	


z1SQLiteDialect.get_foreign_keys.<locals>.parse_fkszhWARNING: SQL-parsed foreign key constraint '%s' could not be located in PRAGMA foreign_keys for table %sr  rh  )r*  rc  r	   r1  r  r?   rJ  r  r  r=  r   r	  rc   extendr   r5  )r4   r  r  r   rE   
pragma_fksfksrz  numerical_idrtbllcolrcolreferred_pkrg  rl  keys_by_signaturer|  fkeysr_  r[  rx  rh  sigr  r/   )rk  r4   r`  r0   get_foreign_keys	  s   $

	A
zSQLiteDialect.get_foreign_keysc                 c  s2    t d|t jD ]}|dp|dV  q	d S )Nz(?:"(.+?)")|([a-z0-9_]+)r   r  )r?   rs  r\  r  )r4   r  r  r/   r/   r0   rt  6
  s   zSQLiteDialect._find_cols_in_sigc                   s   i } j ||f|dd|D ]}|d dsqt|d }|||< q j||fd|i|g } fdd}	|	 D ]\}
}t|}||v rW|| |
|d	}|| q<|r\|S t S )
NT)r   include_auto_indexesr  sqlite_autoindexcolumn_namesr   c                  3  s    d u rd S d} d}t | t jD ]}|dd\}}|t |fV  qt |t jD ]}t |dp>|d}d |fV  q0d S )Nz,(?:CONSTRAINT "?(.+?)"? +)?UNIQUE *\((.+?)\)zJ(?:(".+?")|(?:[\[`])?([a-z0-9_]+)(?:[\]`])?)[\t ]+[a-z0-9_ ]+?[\t ]+UNIQUEr   r  )r?   rs  r\  r  r;  rt  )UNIQUE_PATTERNINLINE_UNIQUE_PATTERNr  r  r  r{  r/   r0   	parse_uqsP
  s   z7SQLiteDialect.get_unique_constraints.<locals>.parse_uqs)r  r  )get_indexesru  ri  r=  rc   r  r   unique_constraints)r4   r  r  r   rE   auto_index_by_sigidxr  r  r  r  r  parsed_constraintr/   r{  r0   get_unique_constraints:
  sB   




z$SQLiteDialect.get_unique_constraintsc           
      K  s   | j ||fd|i|}d}g }t||pdtjD ]}|d}	|	r*tdd|	}	||d|	d q|jdd	 d
 |rB|S t	 S )Nr   z-(?:CONSTRAINT (.+) +)?CHECK *\( *(.+) *\),? *r   r   z^"|"$r  )rI  r  c                 S     | d pdS Nr  ~r/   dr/   r/   r0   rY  
      z5SQLiteDialect.get_check_constraints.<locals>.<lambda>rZ  )
r=  r?   rs  r\  r  rJ  r  r]  r   check_constraints)
r4   r  r  r   rE   r`  CHECK_PATTERNcksr  r  r/   r/   r0   get_check_constraintss
  s$   
z#SQLiteDialect.get_check_constraintsc              	   K  s  | j |d||d}g }tdtj}|rd| j| }nd}|dd}	|D ]Z}
|	s3|
d d	r3q'|t	|
d g |
d
 i d t
|
dkr|
d rdd|i }|||
d f}| }||}|d u rrtd|
d   q'|d}t||d d d< q't|D ]1}| j |d|d |d}|D ]!}
|
d
 d u rtd|d   ||  n
|d |
d
  qq|jdd d |r|S | |||st|r| d| |t S )N
index_listr
   z\)\s+where\s+(.+)%s.r   r  Fr   r  r  )r  r  rQ  r0  r:  r9  zISELECT sql FROM %(schema)ssqlite_master WHERE name = ? AND type = 'index'r   z6Failed to look up filter predicate of partial index %sr   r0  sqlite_where
index_infor  z;Skipped unsupported reflection of expression-based index %sr  c                 S  r  r  r/   r  r/   r/   r0   rY  
  r  z+SQLiteDialect.get_indexes.<locals>.<lambda>rZ  r  )r*  r?   r@   r@  r  r  rc   ru  r  r   r2  r  scalarrO   r   r	  r  r   r;  remover]  r,  r	   r1  r   indexes)r4   r  r  r   rE   pragma_indexesr  partial_pred_reschema_exprr  rz  r  r4  	index_sqlpredicate_match	predicater  pragma_indexr/   r/   r0   r  
  s   



zSQLiteDialect.get_indexesc                 C  s   |dv S )N>   r  sqlite_schemar$  sqlite_temp_schemar/   )r4   r  r/   r/   r0   _is_sys_table
  s   zSQLiteDialect._is_sys_tablec           	      K  s   |rd| j | }nd}zdd|i }|||f}W n tjy3   dd|i }|||f}Y nw | }|d u rJ| |sJt| | |S )Nr  r   zSELECT sql FROM  (SELECT * FROM %(schema)ssqlite_master UNION ALL   SELECT * FROM %(schema)ssqlite_temp_master) WHERE name = ? AND type in ('table', 'view')r   zTSELECT sql FROM %(schema)ssqlite_master WHERE name = ? AND type in ('table', 'view'))r  r  r  r	   r/  r  r  r1  )	r4   r  r  r   rE   r  r  r4  r,   r/   r/   r0   r=  
  s,   
zSQLiteDialect._get_table_sqlc                 C  s   | j j}|d urd|| dg}nddg}||}|D ]!}| | d| d}||}	|	js5|	 }
ng }
|
r=|
  S qg S )NzPRAGMA r  zPRAGMA main.zPRAGMA temp.r  r  )r  r  r  _soft_closedr0  )r4   r  r  r  r   r   
statementsqtable	statementr  r5  r/   r/   r0   r*    s   

zSQLiteDialect._get_table_pragma)FNNNN)r   r   r   r   r   r  r  rN   )NF)Fr&   )Ir9   r:   r;   r  supports_alterr  supports_default_metavalue supports_sane_rowcount_returningsupports_empty_insertr   r  use_insertmanyvaluestuple_in_valuessupports_statement_cache#insert_null_pk_still_autoincrementsr  r  update_returning_multifromr  default_metavalue_tokendefault_paramstyler  execution_ctx_clsr   statement_compilerr"  ddl_compilerr^  type_compiler_clsri  r   rS  colspecs	sa_schemaTableIndexColumn
Constraintconstruct_argumentsr  r  r   deprecated_paramsr>   immutabledictr  r  r  r  r   cacher  r  r  r!  r&  r'  r,  r-  r.  r6  rF  rA  rK  rc  r  rt  r  r  r  r  r=  r*  r/   r/   r/   r0   r    s    E

				!=,6 *8 Yr  )Frs   
__future__r   rl   r)   r?   typingr   jsonr   r   r   r   r	   r   r  r   r   r   r   r   enginer   r   r   engine.reflectionr   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r=   DateTimer]   Datert   Timery   r  r~   r   r   r   rS  r!  r   DDLCompilerr"  GenericTypeCompilerr^  IdentifierPreparerri  DefaultExecutionContextr  r  r  r/   r/   r/   r0   <module>   s   	       2pLZ		
  5&z