U a*b@sdZddlZddlZddlZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddl mZddl mZddl mZddl mZddl mZdd l m Z ddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#dd lm$Z$Gd!d"d"eZ%Gd#d$d$e&Z'Gd%d&d&e'ej(Z)Gd'd(d(e'ej*Z+Gd)d*d*e'ej,Z-ej*e+ej(e)eje%ejjeejjeej,e-iZ.ej/ejejejejej+ej+ej)ej)ejejejejejeejej ej!ej"ej-ej-ej#ej$ej0ej1d+Z2Gd,d-d-ej3Z4Gd.d/d/ej5Z6Gd0d1d1ej7Z8Gd2d3d3ej9Z:Gd4d5d5ej;ZdS)8a&s .. dialect:: sqlite :name: SQLite :full_support: 3.21, 3.28+ :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` for techniques to work around this behavior. .. seealso:: :ref:`dbapi_autocommit` 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 driver, which defers BEGIN statements to a greater degree than is often feasible. See the section :ref:`pysqlite_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. 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:: 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:: 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:: 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:: 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) {opensql}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) {opensql}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) {opensql}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) {opensql}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) {opensql}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) {opensql}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) {opensql}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) {opensql}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. .. versionadded:: 0.9.3 Support for SQLite type affinity rules when reflecting columns. .. _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:: CREATE INDEX test_idx1 ON testtbl (data) WHERE data > 5 AND data < 10 .. versionadded:: 0.9.9 .. _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. .. versionchanged:: 1.1 The following SQLite issue has been resolved as of version 3.10.0 of SQLite. SQLAlchemy as of **1.1** automatically disables its internal workarounds based on detection of this version. 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:: 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) .. seealso:: `SQLite CREATE TABLE options `_ N)JSON) JSONIndexType) JSONPathType)exc) processorsschema)sql)types)util)default) reflection) coercions) ColumnElement)compiler)elements)roles)BLOB)BOOLEAN)CHAR)DECIMAL)FLOAT)INTEGER)NUMERIC)REAL)SMALLINT)TEXT) TIMESTAMP)VARCHARcseZdZfddZZS) _SQliteJsoncs"tt|||fdd}|S)Ncs:z |WStk r4t|tjr.|YSYnXdSN) TypeError isinstancenumbersNumbervalueZdefault_processor`C:\Users\vtejo\AppData\Local\Temp\pip-unpacked-wheel-nyjtotrf\sqlalchemy\dialects\sqlite\base.pyprocessUs   z-_SQliteJson.result_processor..process)superr!result_processor)selfdialectcoltyper, __class__r)r+r.Ps   z_SQliteJson.result_processor)__name__ __module__ __qualname__r. __classcell__r*r*r2r+r!Osr!csFeZdZdZdZd fdd ZeddZfddZdd Z Z S) _DateTimeMixinNc s8tt|jf||dk r&t||_|dk r4||_dSr")r-r8__init__recompile_reg_storage_format)r/storage_formatregexpkwr2r*r+r9es  z_DateTimeMixin.__init__c Cs*|jdddddddd}ttd|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. .. versionadded:: 1.0.0 ryearmonthdayhourminutesecond microsecondz[^0-9])r=boolr:search)r/specr*r*r+format_is_text_affinityls  z&_DateTimeMixin.format_is_text_affinityc s>t|tr*|jr|j|d<|jr*|j|d<tt|j|f|S)Nr>r?) issubclassr8r=r<r-adapt)r/clsr@r2r*r+rNs    z_DateTimeMixin.adaptcs||fdd}|S)Ncs d|S)N'%s'r*r'Zbpr*r+r,sz1_DateTimeMixin.literal_processor..process)bind_processorr/r0r,r*rQr+literal_processors  z _DateTimeMixin.literal_processor)NN) r4r5r6r<r=r9propertyrLrNrTr7r*r*r2r+r8as  r8cs4eZdZdZdZfddZddZddZZS) 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.:: 2021-03-15 12:05:57.105542 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. 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)06dcsL|dd}tt|j|||rHd|ks2tdd|ksBtdd|_dS)Ntruncate_microsecondsFr>DYou can specify only one of truncate_microseconds or storage_format.r?.processdatetimedater=rSr*r_r+rRs zDATETIME.bind_processorcCs |jrt|jtjStjSdSr")r<r!str_to_datetime_processor_factoryrcZstr_to_datetimer/r0r1r*r*r+r.s zDATETIME.result_processor r4r5r6__doc__r=r9rRr.r7r*r*r2r+rVs " $rVc@s$eZdZdZdZddZddZdS)DATEaRepresent a Python date object in SQLite using a string. The default string storage format is:: "%(year)04d-%(month)02d-%(day)02d" e.g.:: 2011-03-15 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. 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)02dcstj|jfdd}|S)Ncs8|dkr dSt|r,|j|j|jdStddS)N)rBrCrDz;SQLite Date type only accepts Python date objects as input.)r$rBrCrDr#r'r`rar*r+r,!s z$DATE.bind_processor..processrbrSr*rjr+rRszDATE.bind_processorcCs |jrt|jtjStjSdSr")r<rrercrdZ str_to_daterfr*r*r+r.2s zDATE.result_processorN)r4r5r6rhr=rRr.r*r*r*r+ris rics4eZdZdZdZfddZddZddZZS) TIMEaZRepresent 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.:: 12:05:57.10558 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. 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)06dcsL|dd}tt|j|||rHd|ks2tdd|ksBtdd|_dS)NrWFr>rXr?rYz$%(hour)02d:%(minute)02d:%(second)02d)rZr-rkr9r[r=r\r2r*r+r9]s   z TIME.__init__cstj|jfdd}|S)Ncs<|dkr dSt|r0|j|j|j|jdStddS)N)rErFrGrHz;SQLite Time type only accepts Python time objects as input.)r$rErFrGrHr#r'Z datetime_timerar*r+r,os z$TIME.bind_processor..process)rctimer=rSr*rlr+rRkszTIME.bind_processorcCs |jrt|jtjStjSdSr")r<rrercrmZ str_to_timerfr*r*r+r.s zTIME.result_processorrgr*r*r2r+rk;s  rk)BIGINTrBOOLrrri DATE_CHARrV DATETIME_CHARDOUBLErrINTrrrrrrrk TIME_CHARrr NVARCHARNCHARcseZdZeejjddddddddd d d Zd d ZddZ ddZ ddZ ddZ fddZ ddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3ZZS)4SQLiteCompilerz%mz%dz%Yz%Sz%Hz%jz%Mz%sz%wz%W) rCrDrBrGrEZdoyrFepochZdowweekcKsdS)NZCURRENT_TIMESTAMPr*r/fnr@r*r*r+visit_now_funcszSQLiteCompiler.visit_now_funccKsdS)Nz(DATETIME(CURRENT_TIMESTAMP, "localtime")r*)r/funcr@r*r*r+visit_localtimestamp_funcsz(SQLiteCompiler.visit_localtimestamp_funccKsdS)N1r*r/exprr@r*r*r+ visit_trueszSQLiteCompiler.visit_truecKsdS)N0r*rr*r*r+ visit_falseszSQLiteCompiler.visit_falsecKsd||S)Nzlength%s)Zfunction_argspecrzr*r*r+visit_char_length_funcsz%SQLiteCompiler.visit_char_length_funcc s0|jjrtt|j|f|S|j|jf|SdSr")r0 supports_castr-rw visit_castr,clause)r/castr^r2r*r+rszSQLiteCompiler.visit_castc Ksdz"d|j|j|j|jf|fWStk r^}ztjtd|j|dW5d}~XYnXdS)Nz#CAST(STRFTIME('%s', %s) AS INTEGER)z#%s is not a valid extract argument.Zreplace_context) extract_mapfieldr,rKeyErrorr raise_r CompileError)r/extractr@errr*r*r+ visit_extracts zSQLiteCompiler.visit_extractcKsd}|jdk r&|d|j|jf|7}|jdk rl|jdkrR|d|td7}|d|j|jf|7}n|d|jtdf|7}|S)Nz LIMIT z OFFSET r)Z _limit_clauser,Z_offset_clauser literal)r/selectr@textr*r*r+ limit_clauses   zSQLiteCompiler.limit_clausecKsdS)Nrr*)r/rr@r*r*r+for_update_clausesz SQLiteCompiler.for_update_clausecKsd||j||jfS)Nz %s IS NOT %sr,leftrightr/binaryoperatorr@r*r*r+visit_is_distinct_from_binarys  z,SQLiteCompiler.visit_is_distinct_from_binarycKsd||j||jfS)Nz%s IS %srrr*r*r+!visit_is_not_distinct_from_binarys  z0SQLiteCompiler.visit_is_not_distinct_from_binarycKs<|jjtjkrd}nd}||j|jf||j|jf|fSNz JSON_QUOTE(JSON_EXTRACT(%s, %s))zJSON_EXTRACT(%s, %s)type_type_affinitysqltypesrr,rrr/rrr@rr*r*r+visit_json_getitem_op_binarysz+SQLiteCompiler.visit_json_getitem_op_binarycKs<|jjtjkrd}nd}||j|jf||j|jf|fSrrrr*r*r+!visit_json_path_getitem_op_binary sz0SQLiteCompiler.visit_json_path_getitem_op_binarycCs ||Sr")visit_empty_set_expr)r/type_Z expand_opr*r*r+visit_empty_set_op_exprsz&SQLiteCompiler.visit_empty_set_op_exprcCs<dddd|ptgDddd|p0tgDfS)Nz%SELECT %s FROM (SELECT %s) WHERE 1!=1, css|] }dVqdSrNr*.0rr*r*r+ sz6SQLiteCompiler.visit_empty_set_expr..css|] }dVqdSrr*rr*r*r+rs)joinr)r/Z element_typesr*r*r+rsz#SQLiteCompiler.visit_empty_set_exprcKs|j|df|S)Nz REGEXP Z_generate_generic_binaryrr*r*r+visit_regexp_match_op_binary!sz+SQLiteCompiler.visit_regexp_match_op_binarycKs|j|df|S)Nz NOT REGEXP rrr*r*r+ visit_not_regexp_match_op_binary$sz/SQLiteCompiler.visit_not_regexp_match_op_binaryc sn|jdk rd|j}nT|jdk rfddfdd|jD}|jdk rj|dj|jdddd7}nd }|S) Nz(%s)rc3s6|].}t|tjrj|nj|dddVqdS)F include_table use_schemaN)r$r string_typespreparerquoter,rcr/r*r+r+s z5SQLiteCompiler._on_conflict_target.. WHERE %sFT)rr literal_bindsr)Zconstraint_targetZinferred_target_elementsrZinferred_target_whereclauser,)r/rr@ target_textr*rr+_on_conflict_target's      z"SQLiteCompiler._on_conflict_targetcKs"|j|f|}|rd|SdSdS)NzON CONFLICT %s DO NOTHINGzON CONFLICT DO NOTHING)r)r/ on_conflictr@rr*r*r+visit_on_conflict_do_nothing@sz+SQLiteCompiler.visit_on_conflict_do_nothingcKs|}|j|f|}g}t|j}|jdd}|jj}|D]} | j} | |krX|| } n| |kr:|| } nq:t | rt j d| | j d} n$t | t j r| j jr| } | j | _ |j| dd} |j| } |d| | fq:|rvtd|jjjdd d |Df|D]\\}}t |tjr:|j|n |j|dd} |jttj|dd} |d| | fqd|}|jdk r|d |j|jd dd 7}d||fS)NrZ selectable)rFrz%s = %szFAdditional column names not matching any column keys in table '%s': %srcss|]}d|VqdS)rPNr*rr*r*r+rusz=SQLiteCompiler.visit_on_conflict_do_update..rTrzON CONFLICT %s DO UPDATE SET %s) rdictZupdate_values_to_setstacktablerkeyrZrZ _is_literalrZ BindParameterrr$Z_isnullZ_cloner,Z self_grouprrappendr warnZcurrent_executablenameritemsrexpectrZExpressionElementRoleZupdate_whereclause)r/rr@rrZaction_set_opsZset_parametersZinsert_statementcolsrZcol_keyr(Z value_textZkey_textkvZ action_textr*r*r+visit_on_conflict_do_updateIsd            z*SQLiteCompiler.visit_on_conflict_do_update)r4r5r6r Z update_copyr SQLCompilerrr|r~rrrrrrrrrrrrrrrrrrr7r*r*r2r+rwsD     rwcsneZdZddZfddZfddZfddZfd d Zfd d Zd dZ dddZ ddZ Z S)SQLiteDDLCompilercKsV|jjj|j|d}|j|d|}||}|dk r`t|jj t rTd|d}|d|7}|j s|d7}|j dd}|dk r|d |7}|j r2|jd krt|jj jd krtd |jj dd r2t|jj jd kr2t|jjtjr2|js2|d7}|j dd}|dk r*|d |7}|d7}|jdk rR|d||j7}|S)N)Ztype_expression ()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)r0 type_compilerr,rrZ format_columnZget_column_default_stringr$Zserver_defaultargrnullabledialect_options primary_keyrlenrcolumnsrrrMrrInteger foreign_keyscomputed)r/columnr^r1colspecron_conflict_clauser*r*r+get_column_specificationsV       z*SQLiteDDLCompiler.get_column_specificationcst|jdkrJt|d}|jrJ|jjddrJt|jjt j rJ|j sJdSt t ||}|jdd}|dkrt|jdkrt|djdd}|dk r|d|7}|S)Nrrrrrrr)rrlistrrrrMrrrrrr-rvisit_primary_key_constraint)r/ constraintrrrr2r*r+rs0   z.SQLiteDDLCompiler.visit_primary_key_constraintcsztt||}|jdd}|dkrbt|jdkrbt|d}t|tj rbt|djdd}|dk rv|d|7}|S)Nrrrron_conflict_uniquer) r-rvisit_unique_constraintrrrrr$r Z SchemaItem)r/rrrZcol1r2r*r+rs"     z)SQLiteDDLCompiler.visit_unique_constraintcs6tt||}|jdd}|dk r2|d|7}|S)Nrrr)r-rvisit_check_constraintr)r/rrrr2r*r+rs  z(SQLiteDDLCompiler.visit_check_constraintcs0tt||}|jdddk r,td|S)NrrzFSQLite does not support on conflict clause for column check constraint)r-rvisit_column_check_constraintrrr)r/rrr2r*r+rs z/SQLiteDDLCompiler.visit_column_check_constraintcs@|jdjj}|jdjj}|j|jkr,dStt||SdS)Nr)rparentrrr r-rvisit_foreign_key_constraint)r/rZ local_tableZ remote_tabler2r*r+rs  z.SQLiteDDLCompiler.visit_foreign_key_constraintcCs|j|ddS)z=Format the remote table clause of a CREATE CONSTRAINT clause.Fr) format_table)r/rrrr*r*r+define_constraint_remote_tablesz0SQLiteDDLCompiler.define_constraint_remote_tableFTc s|j}|j}d}|jr(|d7}|d7}|jr>|d7}|dj|dd|j|jdd d fd d |j Df7}|j d d}|dk rj j |ddd}|d|7}|S)NzCREATE zUNIQUE zINDEX zIF NOT EXISTS z %s ON %s (%s)T)include_schemaFrrc3s |]}jj|dddVqdS)FTrrN) sql_compilerr,)rrrr*r+r3s z7SQLiteDDLCompiler.visit_create_index..rwhererz WHERE ) elementZ_verify_index_tableruniqueZ if_not_existsZ_prepared_index_namerrrZ expressionsrrr,) r/createrZinclude_table_schemaindexrrZ whereclauseZwhere_compiledr*rr+visit_create_index!s2    z$SQLiteDDLCompiler.visit_create_indexcCs|jdddkrdSdS)Nr with_rowidFz WITHOUT ROWIDr)r)r/rr*r*r+post_create_tableDsz#SQLiteDDLCompiler.post_create_table)FT) r4r5r6rrrrrrrrrr7r*r*r2r+rs4     #rcsDeZdZddZfddZfddZfddZd d ZZS) SQLiteTypeCompilercKs ||Sr")Z visit_BLOBr/rr@r*r*r+visit_large_binaryKsz%SQLiteTypeCompiler.visit_large_binaryc s(t|tr|jr tt||SdSdS)Nrq)r$r8rLr-rvisit_DATETIMErr2r*r+rNs z!SQLiteTypeCompiler.visit_DATETIMEc s(t|tr|jr tt||SdSdS)Nrp)r$r8rLr-r visit_DATErr2r*r+rWs zSQLiteTypeCompiler.visit_DATEc s(t|tr|jr tt||SdSdS)Nrt)r$r8rLr-r visit_TIMErr2r*r+r`s zSQLiteTypeCompiler.visit_TIMEcKsdS)Nrr*rr*r*r+ visit_JSONiszSQLiteTypeCompiler.visit_JSON) r4r5r6rrrrrr7r*r*r2r+rJs  rcv@seZdZeddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtduguZdvS)wSQLiteIdentifierPrepareraddafterallZalterZanalyzeandasZascattachrZbeforebeginZbetweenZbyZcascadeZcasercheckZcollatercommitconflictrrZcrossZ current_date current_timeZcurrent_timestampZdatabaserZ deferrabledeferreddeletedescdetachZdistinctZdropZeachelseendescapeexceptZ exclusiveexistsexplainfalseZfailforZforeignfromfullglobgroupZhavingifignoreZ immediateinrZindexedZ initiallyinnerinsertZinsteadZ intersectZintoisZisnullrrrZlikelimitmatchZnaturalnotZnotnullnullZofoffsetonororderouterZplanpragmaZprimaryqueryraiseZ referencesZreindexrenamereplaceZrestrictrrollbackrowrsetrtemp temporaryZthentoZ transactionZtriggertrueunionrupdateZusingZvacuumvaluesviewZvirtualwhenrN)r4r5r6r:Zreserved_wordsr*r*r*r+rpsrc@s"eZdZejddZddZdS)SQLiteExecutionContextcCs|jj p|jddS)NZsqlite_raw_colnamesF)r0_broken_dotted_colnamesZexecution_optionsgetrr*r*r+_preserve_raw_colnamess  z-SQLiteExecutionContext._preserve_raw_colnamescCs,|js d|kr |dd|fS|dfSdS)N.r)rGsplit)r/Zcolnamer*r*r+_translate_colnamesz)SQLiteExecutionContext._translate_colnameN)r4r5r6r Zmemoized_propertyrGrJr*r*r*r+rDs rDc@seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZeZeZeZeZeZeZeZdZejdddfejddifejddddfej d difgZ!dZ"dZ#e$j%d d d d>d dZ&dddZ'ddZ(ddZ)ddZ*e+j,ddZ-e+j,d?ddZ.e+j,ddZ/e+j,ddZ0d@d d!Z1d"d#Z2e+j,dAd$d%Z3e+j,dBd&d'Z4e+j,dCd(d)Z5d*d+Z6d,d-Z7e+j,dDd.d/Z8e+j,dEd0d1Z9d2d3Z:e+j,dFd4d5Z;e+j,dGd6d7ZdJd.connect)rX)r/rkr*rr+ on_connects  zSQLiteDialect.on_connectcKsd}||}dd|DS)NzPRAGMA database_listcSs g|]}|ddkr|dqS)rr;r*)rdbr*r*r+ s z2SQLiteDialect.get_schema_names..exec_driver_sql)r/rer@sdlr*r*r+get_schema_namess zSQLiteDialect.get_schema_namescKsD|dk r|j|}d|}nd}d|f}||}dd|DS)N%s.sqlite_master sqlite_masterz4SELECT name FROM %s WHERE type='table' ORDER BY namecSsg|] }|dqSrr*rr9r*r*r+rnsz1SQLiteDialect.get_table_names..identifier_preparerquote_identifierrpr/rer r@qschemamasterrqrsr*r*r+get_table_namess   zSQLiteDialect.get_table_namescKsd}||}dd|DS)NzESELECT name FROM sqlite_temp_master WHERE type='table' ORDER BY name cSsg|] }|dqSrvr*rwr*r*r+rnsz6SQLiteDialect.get_temp_table_names..ror/rer@rqr~r*r*r+get_temp_table_namess z"SQLiteDialect.get_temp_table_namescKsd}||}dd|DS)NzDSELECT name FROM sqlite_temp_master WHERE type='view' ORDER BY name cSsg|] }|dqSrvr*rwr*r*r+rnsz5SQLiteDialect.get_temp_view_names..rorr*r*r+get_temp_view_namess z!SQLiteDialect.get_temp_view_namescCs$|||j|d||d}t|S)N table_infor )Z_ensure_has_table_connection_get_table_pragmarI)r/re table_namer infor*r*r+ has_tables zSQLiteDialect.has_tablecCsdS)Nmainr*)r/rer*r*r+_get_default_schema_namesz&SQLiteDialect._get_default_schema_namecKsD|dk r|j|}d|}nd}d|f}||}dd|DS)Nrtruz3SELECT name FROM %s WHERE type='view' ORDER BY namecSsg|] }|dqSrvr*rwr*r*r+rnsz0SQLiteDialect.get_view_names..rxr{r*r*r+get_view_namess   zSQLiteDialect.get_view_namesc Ks|dk r6|j|}d|}d|f}|||f}n@zd}|||f}Wn(tjk rtd}|||f}YnX|} | r| djSdS)Nrtz1SELECT 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