gT rdZddlmZddlZddlZddlZddlmZddlm Z ddlm Z ddlm Z d d l m Z d d l mZd d l mZd d l mZd dl mZd dl mZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd dlmZd d lmZd dlm Z d dlm!Z!d dlm"Z"d dlm#Z#d dlm$Z$d dlm%Z%d dlm&Z&d d lm'Z'd d!lm(Z(d d"lm)Z)d d#lm*Z*d d$lm+Z+Gd%d&e Z,Gd'd(Z-Gd)d*e-ej\Z/Gd+d,e-ej`Z1Gd-d.e-ejdZ3ej`e1ej\e/eje,ejje ejje ejde3iZ4id/ejjd0ej@d1ejBd2ejBd3ejDd,ejbd4ejbd*ej^d5ej^d6ejld7ejFd8ejHd9ejJd:ejJd;e dZ9Gd?d@ejtZ;GdAdBejxZ=GdCdDej|Z?GdEdFejZAGdGdHejZCGdIdJejZEy)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 `_ - 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 `_ .. _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 `_ 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 `_ 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 `_. 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 `_ - 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 `_ - 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 `_ - 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 [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 `_ .. _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 `_ - in the SQLite documentation. ) annotationsN)Optional)JSON) JSONIndexType) JSONPathType)excschema)sql)text)types)util)default) processors) reflection)ReflectionDefaults) coercions) ColumnElement)compiler)elements)roles)BLOB)BOOLEAN)CHAR)DECIMAL)FLOAT)INTEGER)NUMERIC)REAL)SMALLINT)TEXT) TIMESTAMP)VARCHARceZdZfdZxZS) _SQliteJsonc4t|||fd}|S)Ncn |S#t$r t|tjr|cYSwxYwN) TypeError isinstancenumbersNumber)valuedefault_processors P/opt/hc_python/lib64/python3.12/site-packages/sqlalchemy/dialects/sqlite/base.pyprocessz-_SQliteJson.result_processor..processs8 (// eW^^4 L  s  %44)superresult_processor)selfdialectcoltyper2r0 __class__s @r1r4z_SQliteJson.result_processors!!G4WgF )__name__ __module__ __qualname__r4 __classcell__r8s@r1r'r's   r9r'cHeZdZdZdZdfd ZedZfdZdZ xZ S)_DateTimeMixinNc pt|di||tj||_|||_yy)N)r3__init__recompile_reg_storage_format)r5storage_formatregexpkwr8s r1rCz_DateTimeMixin.__init__s< 2   6*DI  %#1D  &r9c n|jddddddddz}ttjd|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. ryearmonthdayhourminutesecond microsecondz[^0-9])rGboolrDsearch)r5specs r1format_is_text_affinityz&_DateTimeMixin.format_is_text_affinitysF##'  BIIi.//r9c t|tr6|jr|j|d<|jr|j|d<t ||fi|S)NrHrI) issubclassr@rGrFr3adapt)r5clsrJr8s r1rZz_DateTimeMixin.adaptsO c> *##'+';';#$yy#yy8 w}S'B''r9c4|j|fd}|S)Ncd|zS)N'%s'rB)r/bps r1r2z1_DateTimeMixin.literal_processor..processsBuI% %r9)bind_processor)r5r6r2r_s @r1literal_processorz _DateTimeMixin.literal_processors   ) &r9)NN) r:r;r<rFrGrCpropertyrWrZrar=r>s@r1r@r@s0 DO200*(r9r@c2eZdZdZdZfdZdZdZxZS)DATETIMEaRepresent 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|jdd}t||i||rd|vsJdd|vsJdd|_yy)Ntruncate_microsecondsFrHDYou can specify only one of truncate_microseconds or storage_format.rI.processDs}E#45!JJ"[[ 99!JJ#ll#ll#(#4#4"E=1!JJ"[[ 99#$" :r9datetimedaterG)r5r6r2rprqrrs @@@r1r`zDATETIME.bind_processor?s/$-- && :r9c|jr.tj|jtjStjSr*)rFr!str_to_datetime_processor_factoryrtstr_to_datetimer5r6r7s r1r4zDATETIME.result_processorcs9 99?? 8,, -- -r9 r:r;r<__doc__rGrCr`r4r=r>s@r1rdrds$*Z A ""H.r9rdc eZdZdZdZdZdZy)DATEaNRepresent 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\d+)/(?P\d+)/(?P\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)02dcNtj|jfd}|S)Nc|yt|r'|j|j|jdzSt d)N)rMrNrOz;SQLite Date type only accepts Python date objects as input.)r,rMrNrOr+)r/rprrs r1r2z$DATE.bind_processor..processsP}E=1!JJ"[[ 99"  -r9rs)r5r6r2rprrs @@r1r`zDATE.bind_processors# && r9c|jr.tj|jtjStj Sr*)rFrrwrtru str_to_daterys r1r4zDATE.result_processor7 99?? 8== )) )r9N)r:r;r<r{rGr`r4rBr9r1r}r}ls)V9O**r9r}c2eZdZdZdZfdZdZdZxZS)TIMEaRepresent 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|jdd}t||i||rd|vsJdd|vsJdd|_yy)NrfFrHrgrIrhz$%(hour)02d:%(minute)02d:%(second)02drirks r1rCz TIME.__init__sq & +BE J $)&) #61 B 16) 3 )$JD  !r9cNtj|jfd}|S)Nc|yt|r2|j|j|j|jdzSt d)N)rPrQrRrSz;SQLite Time type only accepts Python time objects as input.)r,rPrQrRrSr+)r/ datetime_timerrs r1r2z$TIME.bind_processor..processsY}E=1!JJ#ll#ll#(#4#4 " -r9)rttimerG)r5r6r2rrrs @@r1r`zTIME.bind_processors# &&  r9c|jr.tj|jtjStj Sr*)rFrrwrtr str_to_timerys r1r4zTIME.result_processorrr9rzr>s@r1rrs!'ROO J,*r9rBIGINTrBOOLrr DATE_CHAR DATETIME_CHARDOUBLErrINTrrr r!)r"r#r TIME_CHARr$r%NVARCHARNCHARceZdZejej jddddddddd d d Zd Zd Z dZ dZ dZ dZ dZfdZdZfdZdZdZdZdZdZdZdZdZdZdZd Zd!Zd"Zd#Zd$Z xZ!S)%SQLiteCompilerz%mz%dz%Yz%Sz%Hz%jz%Mz%sz%wz%W) rNrOrMrRrPdoyrQepochdowweekc |j|jfi|dzd|j|jfi|zzS)Nz / z (%s + 0.0)r2leftrightr5binaryoperatorrJs r1visit_truediv_binaryz#SQLiteCompiler.visit_truediv_binaryHsG DLL + + \T\\&,,="== > r9c y)NCURRENT_TIMESTAMPrBr5fnrJs r1visit_now_funczSQLiteCompiler.visit_now_funcOs"r9c y)Nz(DATETIME(CURRENT_TIMESTAMP, "localtime")rB)r5funcrJs r1visit_localtimestamp_funcz(SQLiteCompiler.visit_localtimestamp_funcRs9r9c y)N1rBr5exprrJs r1 visit_truezSQLiteCompiler.visit_trueUr9c y)N0rBrs r1 visit_falsezSQLiteCompiler.visit_falseXrr9c *d|j|zS)Nzlength%sfunction_argspecrs r1visit_char_length_funcz%SQLiteCompiler.visit_char_length_func[sD11"555r9c *d|j|zS)Nzgroup_concat%srrs r1visit_aggregate_strings_funcz+SQLiteCompiler.visit_aggregate_strings_func^s$"7"7";;;r9c |jjrt| |fi|S|j|j fi|Sr*)r6 supports_castr3 visit_castr2clause)r5castrmr8s r1rzSQLiteCompiler.visit_castas? << % %7%d5f5 54<< 6v6 6r9c d|j|jd|j|jfi|dS#t$r(}t j d|jz|d}~wwxYw)NzCAST(STRFTIME('z', z ) AS INTEGER)z#%s is not a valid extract argument.) extract_mapfieldr2rKeyErrorr CompileError)r5extractrJerrs r1 visit_extractzSQLiteCompiler.visit_extractgsn   / W\\0R0  ""5 E  s:< A-#A((A-c 4d|d<t|||fd|i|S)NF include_tablepopulate_result_map)r3returning_clause)r5stmtreturning_colsrrJr8s r1rzSQLiteCompiler.returning_clausers6$?w' . 6I MO  r9c d}|j#|d|j|jfi|zz }|j[|j*|d|jtjdzz }|d|j|jfi|zz }|S|d|jtjdfi|zz }|S)Nz LIMIT z OFFSET r) _limit_clauser2_offset_clauser literal)r5selectrJrs r1 limit_clausezSQLiteCompiler.limit_clauses    + K,$,,v/C/C"Jr"JJ JD  ,##+ dll3;;r?&CCC Jf.C.C!Jr!JJ JD  Jckk!n!C!CC CD r9c y)NrrB)r5rrJs r1for_update_clausez SQLiteCompiler.for_update_clausesr9c Pdd<ddjfd|DzS)NTasfromzFROM , c3HK|]}|jfdiyw) fromhintsN)_compiler_dispatch).0t from_hintsrJr5s r1 z4SQLiteCompiler.update_from_clause..s0#   !A  B Br B s")join)r5 update_stmt from_table extra_fromsrrJs` ``r1update_from_clausez!SQLiteCompiler.update_from_clauses38 #  #    r9c t|j|jd|j|jS)Nz IS NOT rrs r1visit_is_distinct_from_binaryz,SQLiteCompiler.visit_is_distinct_from_binary, LL % LL &  r9c t|j|jd|j|jS)Nz IS rrs r1!visit_is_not_distinct_from_binaryz0SQLiteCompiler.visit_is_not_distinct_from_binaryrr9c |jjtjurd}nd}||j|j fi||j|j fi|fzSNz JSON_QUOTE(JSON_EXTRACT(%s, %s))zJSON_EXTRACT(%s, %s)type_type_affinitysqltypesrr2rrr5rrrJrs r1visit_json_getitem_op_binaryz+SQLiteCompiler.visit_json_getitem_op_binaryb ;; % % 65D)D DLL + + DLL , ,   r9c |jjtjurd}nd}||j|j fi||j|j fi|fzSrrrs r1!visit_json_path_getitem_op_binaryz0SQLiteCompiler.visit_json_path_getitem_op_binaryrr9c $|j|Sr*)visit_empty_set_expr)r5type_ expand_oprJs r1visit_empty_set_op_exprz&SQLiteCompiler.visit_empty_set_op_exprs((//r9c ddjd|xs tgDddjd|xs tgDdS)NzSELECT rc3 K|]}dywrNrBrrs r1rz6SQLiteCompiler.visit_empty_set_expr..D'Cec'C z FROM (SELECT c3 K|]}dywrrBrs r1rz6SQLiteCompiler.visit_empty_set_expr..rrz ) WHERE 1!=1)rr)r5 element_typesrJs r1rz#SQLiteCompiler.visit_empty_set_exprsH IID}'C 'CD D IID}'C 'CD D  r9c *|j|dfi|S)Nz REGEXP _generate_generic_binaryrs r1visit_regexp_match_op_binaryz+SQLiteCompiler.visit_regexp_match_op_binarys,t,,VZF2FFr9c *|j|dfi|S)Nz NOT REGEXP rrs r1 visit_not_regexp_match_op_binaryz/SQLiteCompiler.visit_not_regexp_match_op_binarys,t,,V^JrJJr9c |jZddjfd|jDz}|j%|dj|jdddzz }|Sd}|S) Nz(%s)rc3K|]C}t|trjj|nj |ddEyw)Fr use_schemaN)r,strpreparerquoter2)rcr5s r1rz5SQLiteCompiler._on_conflict_target..sP- 9A"!S)MM''*auOP9sA A  WHERE %sFT)rr literal_executer)inferred_target_elementsrinferred_target_whereclauser2)r5rrJ target_texts` r1_on_conflict_targetz"SQLiteCompiler._on_conflict_targets  * * 6 499-  88 -$K11={T\\66"'$$( .:.  Kr9c 8|j|fi|}|rd|zSy)NzON CONFLICT %s DO NOTHINGzON CONFLICT DO NOTHING)r)r5 on_conflictrJrs r1visit_on_conflict_do_nothingz+SQLiteCompiler.visit_on_conflict_do_nothings*.d..{AbA .< <+r9c n|}|j|fi|}g}t|j}|jdd}|jj }|D]!} | j } | |vr|j| } n| |vr|j| } n=tj| r#tjd| | j} nQt| tjr7| jjr!| j} | j| _ |j!| j#d} |j$j'| j(} |j+| d| $|rt-j.d|j0jj(dd j3d |D|j5D]\}}t|t6r|j$j'|n|j!|d} |j!tj8t:j<|d} |j+| d| d j3|}|j>$|d |j!|j>d d zz }d|d|S)Nr selectable)rFr z = z?Additional column names not matching any column keys in table 'z': rc3&K|] }d|z yw)r^NrB)rrs r1rz=SQLiteCompiler.visit_on_conflict_do_update..sB>avz>srTr z ON CONFLICT z DO UPDATE SET ) rdictupdate_values_to_setstacktablerkeyrjr _is_literalr BindParameterrr,_isnull_cloner2 self_grouprrnameappendrwarncurrent_executableritemsr expectrExpressionElementRoleupdate_whereclause)r5rrJrraction_set_opsset_parametersinsert_statementcolsrcol_keyr/ value_textkey_textkv action_texts r1visit_on_conflict_do_updatez*SQLiteCompiler.visit_on_conflict_do_updatesi.d..{AbA f99: ::b>,7%%''AeeG.(&**73n$&**1-$$U+ ..tU!&&Iuh&<&<= **!LLNE!"EJe&6&6&8UKJ}}**1662H  ! !x"D E/4  II++1166YYB>BB  ',,.1"!S)MM''*aE: "\\$$U%@%@!D$* %%8Z&HI/ii/  $ $ 0 ;))%*6* K5@MMr9c nd|d<|j|dfi|}|j|dfi|}d|d|dS)NTeager_groupingz | z & (z - )r)r5rrrJor_and_s r1visit_bitwise_xor_op_binaryz*SQLiteCompiler.visit_bitwise_xor_op_binary-sT# +d++FE@R@,t,,VUAbA3%s4&""r9)"r:r;r<r update_copyr SQLCompilerrrrrrrrrrrrrrrrrrrrrrrrrr:rAr=r>s@r1rr7s"$""(( K  #:6<7          0  GK.,ANF#r9rcbeZdZdZfdZfdZfdZfdZfdZdZ d dZ d Z xZ S) SQLiteDDLCompilerc |jjj|j|}|jj |dz|z}|j |}|4t|jjtrd|zdz}|d|zz }|js!|dz }|jdd}||d |zz }|jr|jd urAt|j jj"d k7rt%j&d |j jdd rt|j jj"d k(r`t)|jj*t,j.r2|j0s&|dz }|jdd}||d |zz }|dz }|j2!|d|j|j2zz }|S)N)type_expression r=r>z DEFAULT z NOT NULLsqliteon_conflict_not_null ON CONFLICT Trz@SQLite does not support autoincrement for composite primary keys autoincrementz PRIMARY KEYon_conflict_primary_keyz AUTOINCREMENT)r6type_compiler_instancer2rr format_columnget_column_default_stringr,server_defaultargrnullabledialect_options primary_keyrLlenr!columnsr rrYrrInteger foreign_keyscomputed)r5columnrmr7colspecron_conflict_clauses r1get_column_specificationz*SQLiteDDLCompiler.get_column_specification6s,,55== KK> ----f5;gE008  &//33]C-#- {W, ,G { "G!'!7!7!A&" "-?-???   $$, 00889Q>&&-  ,,X6G 00889Q>v{{998;K;KL++>)%+%;%;H%E-&"&11CCCG++ ?? & sT\\&//:: :Gr9c t|jdk(rqt|d}|jrW|jj ddr;t |jjtjr |jsyt|5|}|j dd}|6t|jdk(rt|dj dd}||d|zz }|S)NrrrIrLrrMrK)rVrWlistrUr!rTrYrrrrXrYr3visit_primary_key_constraint)r5 constraintrJrrr]r8s r1raz.SQLiteDDLCompiler.visit_primary_key_constraintis z!! "a 'Z #A GG++H5oFqvv44h6F6FGw3J?'77A    %#j.@.@*AQ*F!%j!1!!4!D!DX!N)"   ) O&88 8D r9c t||}|jdd}|^t|jdk(rFt |d}t |tjrt |djdd}||d|zz }|S)NrIrrron_conflict_uniquerK) r3visit_unique_constraintrTrVrWr`r,r SchemaItem)r5rbrJrr]col1r8s r1rez)SQLiteDDLCompiler.visit_unique_constraintsw.z:'77A    %#j.@.@*AQ*F #A&D$ 1 12%)*%5a%8%H%H&&&("  ) O&88 8D r9c ^t||}|jdd}||d|zz }|S)NrIrrK)r3visit_check_constraintrT)r5rbrJrr]r8s r1riz(SQLiteDDLCompiler.visit_check_constraintsHw-j9'77A    ) O&88 8D r9c tt||}|jddtjd|S)NrIrzFSQLite does not support on conflict clause for column check constraint)r3visit_column_check_constraintrTr r)r5rbrJrr8s r1rkz/SQLiteDDLCompiler.visit_column_check_constraintsGw4Z@  % %h / > J""*   r9c |jdjj}|jdjj}|j|jk7ryt ||S)Nr)rparentr!r[r r3visit_foreign_key_constraint)r5rbrJ local_table remote_tabler8s r1rnz.SQLiteDDLCompiler.visit_foreign_key_constraintsb ))!,3399 !**1-44::   !4!4 477 C Cr9c(|j|dS)z=Format the remote table clause of a CREATE CONSTRAINT clause.Fr) format_table)r5rbr!rs r1define_constraint_remote_tablez0SQLiteDDLCompiler.define_constraint_remote_tables$$Uu$==r9c |j}j|j}d}|jr|dz }|dz }|jr|dz }|j |dd|j |jd d d jfd |jDd z }|jdd}|&jj|dd} |d| zz }|S)NzCREATE zUNIQUE zINDEX zIF NOT EXISTS T)include_schemaz ON Frz (rc3ZK|]"}jj|dd$yw)FTr literal_bindsN) sql_compilerr2)rrr5s r1rz7SQLiteDDLCompiler.visit_create_index..s:.D!!))T*.s(+r>rIwhererwz WHERE ) element_verify_index_tablerunique if_not_exists_prepared_index_namerrr!r expressionsrTryr2) r5createruinclude_table_schemarJindexrr whereclausewhere_compileds ` r1visit_create_indexz$SQLiteDDLCompiler.visit_create_indexs   '== << I D     $ $D  % %eD % A  ! !%++% ! @ II"--    ++H5g>  "!..6657N I. .D r9cg}|jdds|jd|jddr|jd|rddj|zSy) NrI with_rowidz WITHOUT ROWIDstrictSTRICTz z, r)rTr)r)r5r! table_optionss r1post_create_tablez#SQLiteDDLCompiler.post_create_tablesc $$X.|<   1   *8 4   * 6;;}55 5r9)FT) r:r;r<r^rarerirkrnrsrrr=r>s@r1rErE5s:1f:$  D> BF!F r9rEc>eZdZdZfdZfdZfdZdZxZS)SQLiteTypeCompilerc $|j|Sr*) visit_BLOBr5rrJs r1visit_large_binaryz%SQLiteTypeCompiler.visit_large_binarysu%%r9c \t|tr |jrt||Sy)Nr)r,r@rWr3visit_DATETIMEr5rrJr8s r1rz!SQLiteTypeCompiler.visit_DATETIMEs)5.1,,7)%0 0"r9c \t|tr |jrt||Sy)Nr)r,r@rWr3 visit_DATErs r1rzSQLiteTypeCompiler.visit_DATE)5.1,,7%e, ,r9c \t|tr |jrt||Sy)Nr)r,r@rWr3 visit_TIMErs r1rzSQLiteTypeCompiler.visit_TIMErr9c y)NrrBrs r1 visit_JSONzSQLiteTypeCompiler.visit_JSONsr9) r:r;r<rrrrrr=r>s@r1rrs&#r9rceZdZhdZy)SQLiteIdentifierPreparer>uasbyifinisofonortoaddallandascendforr"notrowsetcaserdescdropeachelsefailfromfullglobintorrlikenullplantempthentrueviewwhenafteralterbegincheckcrossfalsegrouprinnerlimitmatchorderouterqueryraiserr!unionusingrzattachbeforer[commitrdeletedetachescapeexceptexistshavingignoreinsertisnulloffsetpragmarenamerr}updatevacuumvaluesanalyzebetweencascadecollaterexplainforeignindexedinsteadnaturalnotnullprimaryreindexreplacetriggervirtualconflictdatabasedeferreddistinctrestrictrollback exclusive immediate initially intersect temporaryrb deferrable references transaction current_date current_timerLcurrent_timestampN)r:r;r<reserved_wordsrBr9r1rrs vNr9rc6eZdZejdZdZy)SQLiteExecutionContextcl|jj xs|jjddS)Nsqlite_raw_colnamesF)r6_broken_dotted_colnamesexecution_optionsget)r5s r1_preserve_raw_colnamesz-SQLiteExecutionContext._preserve_raw_colnamess6 44 4 H%%))*?G r9cV|jsd|vr|jdd|fS|dfS)N.r)r split)r5colnames r1_translate_colnamez)SQLiteExecutionContext._translate_colnames6**sg~==%b)72 2D= r9N)r:r;r<rmemoized_propertyr rrBr9r1rrs   !r9rceZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZ dZ dZeZeZeZeZeZeZe Z e!jDddddfe!jFddife!jHdddd fe!jJd difgZ&dZ'dZ(e)jTd d  d+dZ+e)jXdddZ-dZ.dZ/dZ0e1jddZ3dZ4 d,dZ5e1jd d-dZ6e1jd d.dZ7e1jd d.dZ8e1jdd/dZ9dZ:e1jd d-dZ;e1jdd/dZd!Z?e1jdd/d"Z@e1jdd/d#ZAd$ZBe1jd d/d%ZCe1jdd/d&ZDe1jdd/d'ZEd(ZFe1jdd/d)ZGd/d*ZHy)0 SQLiteDialectrIFTNULLqmark)rLrrrzN)rMrJrdr)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.)rzThe _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 tjj|fi||r|}|r|}||_||_||_|j <|j jdkr-tjd|j jd|j jdk|_ |j jdk\|_ |j jdk\|_ |j jdk\|_ |j jdk|_|j jd kstjrd x|_x|_|_|j jd krd |_yyy) N)r zSQLite version z 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 ri)rDefaultDialectrCrrnative_datetimedbapisqlite_version_inforr*r supports_default_valuesrsupports_multivalues_insert_broken_fk_pragma_quotespypyupdate_returningdelete_returninginsert_returninginsertmanyvalues_max_parameters)r5r'json_serializerjson_deserializerrrrms r1rCzSQLiteDialect.__init__sy. ''77 .O  2  /"3 / :: !zz-- : zz55 8,0::+I+IM,D ( ,0::+I+IN,D ( "&!?!?9!LD  ..  ,-1JJ,J,JN-D ) zz--7499%(=)zz-- :7:4;S "r9rr)READ UNCOMMITTED SERIALIZABLEc,t|jSr*)r`_isolation_lookup)r5dbapi_connections r1get_isolation_level_valuesz(SQLiteDialect.get_isolation_level_values@sD**++r9c|j|}|j}|jd||jy)NzPRAGMA read_uncommitted = )r7cursorexecuteclose)r5r8levelisolation_levelr;s r1set_isolation_levelz!SQLiteDialect.set_isolation_levelCs>007!((*3O3DEF r9c|j}|jd|j}|r|d}nd}|j|dk(ry|dk(ryJd|z)NzPRAGMA read_uncommittedrr5rr4zUnknown isolation level %s)r;r<fetchoner=)r5r8r;resr/s r1get_isolation_levelz!SQLiteDialect.get_isolation_levelJsi!((*01oo FEE  A:! aZ% >6> >5r9c jd}|j|}|Dcgc]}|ddk7s |dc}Scc}w)NzPRAGMA database_listrr)exec_driver_sql)r5 connectionrJsdldbs r1get_schema_nameszSQLiteDialect.get_schema_names`s= "  ' ' * "6"bevo1666s 00cV|$|jj|}|d|}|S|}|S)Nr)identifier_preparerquote_identifier)r5r table_nameqschemar(s r1_format_schemazSQLiteDialect._format_schemagsA  ..??GGYa |,D D r9cP|j||}|sd}nd}d|d|d|d}|S)Nz) AND name NOT LIKE 'sqlite~_%' ESCAPE '~'rzSELECT name FROM z WHERE type=''z ORDER BY name)rQ)r5r!rr sqlite_include_internalmain filter_tablers r1_sqlite_main_queryz SQLiteDialect._sqlite_main_queryosP""651&FLLv& '<.1    r9c |jdd||}|j|jj}|S)N sqlite_masterr!rWrFscalarsrr5rGr rTrJrnamess r1get_table_nameszSQLiteDialect.get_table_namessG'' Wf.E **5199;??A r9c |jddd|}|j|jj}|S)Nsqlite_temp_masterr!rZr5rGrTrJrr]s r1get_temp_table_namesz"SQLiteDialect.get_temp_table_namessG'' '41H **5199;??A r9c |jddd|}|j|jj}|S)Nr`rrZras r1get_temp_view_namesz!SQLiteDialect.get_temp_view_namessG'' &$0G **5199;??A r9c |j||||j|fi|vry|j|d||}t|S)NF table_infor )_ensure_has_table_connectionrK_get_table_pragmarT)r5rGrOr rJinfos r1 has_tablezSQLiteDialect.has_tablesg ))*5  &0E0E0E 1 1 # %%  j& Dzr9cy)NrUrB)r5rGs r1_get_default_schema_namez&SQLiteDialect._get_default_schema_namesr9c |jdd||}|j|jj}|S)NrYrrZr\s r1get_view_nameszSQLiteDialect.get_view_namessG'' VV-D **5199;??A r9c |:|jj|}|d}d|d}|j||f}n d}|j||f}|j } | r| dj Stj|r |d||#tj$rd}|j||f}YmwxYw)Nz.sqlite_masterzSELECT sql FROM z 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