id% dZddlZddlZddlZddlmZddlmZddlmZddlm Z dd lm Z dd lm Z dd lm Z dd lmZdd lmZddlmZddlmZddl mZddl mZdd l m Z ddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!GddeZ"Gd d!e#Z$Gd"d#e$ej%Z&Gd$d%e$ej'Z(Gd&d'e$ej)Z*ej'e(ej%e&eje"ejjeejjeej)e*iZ+id(ej,d)ejd*ejd+ejd,ejd%ej(d-ej(d#ej&d.ej&d/ejd0ejd1ejd2ejd3ejd4ed5ejd6ejejejej*ej*ej ej!ej-ej.d7Z/Gd8d9ej0Z1Gd:d;ej2Z3Gd<d=ej4Z5Gd>d?ej6Z7Gd@dAej8Z9GdBdCej:Z;dS)DacU .. dialect:: sqlite :name: SQLite .. _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: http://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 ----------------------------------- SQLite supports a non-standard 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_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 http://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.execute("create table x (a integer, b integer)") conn.execute("insert into x (a, b) values (1, 1)") conn.execute("insert into x (a, b) values (2, 2)") result = conn.execute("select x.a, x.b from x") assert result.keys() == ["a", "b"] result = conn.execute(''' 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.ResultProxy.keys` and :meth:`.RowProxy.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.ResultProxy.keys` and :meth:`.RowProxy.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).execute(''' 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) ColumnElement)compiler)BLOB)BOOLEAN)CHAR)DECIMAL)FLOAT)INTEGER)NUMERIC)REAL)SMALLINT)TEXT) TIMESTAMP)VARCHARceZdZfdZxZS) _SQliteJsoncftt|||fd}|S)Ncv |S#t$r t|tjr|cYSwxYwN) TypeError isinstancenumbersNumber)valuedefault_processors T/opt/cloudlinux/venv/lib/python3.11/site-packages/sqlalchemy/dialects/sqlite/base.pyprocessz-_SQliteJson.result_processor..processsT ((///   eW^44 LLL  s &88)superr result_processor)selfdialectcoltyper+r) __class__s @r*r-z_SQliteJson.result_processor}sI!+t44EE W       )__name__ __module__ __qualname__r- __classcell__r1s@r*r r |s8r2r cNeZdZdZdZdfd ZedZfdZdZ xZ S)_DateTimeMixinNc tt|jdi||tj||_| ||_dSdS)N)r,r9__init__recompile_reg_storage_format)r.storage_formatregexpkwr1s r*r<z_DateTimeMixin.__init__sY,nd##,22r222   6**DI  %#1D  & %r2c j|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. .. versionadded:: 1.0.0 ryearmonthdayhourminutesecond microsecondz[^0-9])r@boolr=search)r.specs r*format_is_text_affinityz&_DateTimeMixin.format_is_text_affinitysL#' '  BIi..///r2c t|tr"|jr |j|d<|jr |j|d<t t|j|fi|S)NrArB) issubclassr9r@r?r,adapt)r.clsrCr1s r*rSz_DateTimeMixin.adaptsh c> * * )# <'+';#$y )#y8 0u^T**0;;;;;r2c<||fd}|S)Nc d|zS)Nz'%s'r;)r(bps r*r+z1_DateTimeMixin.literal_processor..processsBBuII% %r2)bind_processor)r.r/r+rWs @r*literal_processorz _DateTimeMixin.literal_processors6   ) ) & & & & &r2)NN) r3r4r5r?r@r<propertyrPrSrYr6r7s@r*r9r9s DO22222200X0.<<<<<r2r9c2eZdZdZdZfdZdZdZxZS)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.:: 2011-03-15 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 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)06dc|dd}tt|j|i||r d|_dSdS)Ntruncate_microsecondsFzE%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(minute)02d:%(second)02d)popr,r\r<r@r.argskwargsr^r1s r*r<zDATETIME.__init__s_ & +BE J J&h&7777 7    r2cXtjtj|jfd}|S)Nc |dSt|r0|j|j|j|j|j|j|jdzSt|r|j|j|jdddddzStd)NrErzLSQLite DateTime type only accepts Python datetime and date objects as input.) r%rFrGrHrIrJrKrLr$)r( datetime_datedatetime_datetimeformat_s r*r+z(DATETIME.bind_processor..processs}tE#455 !J"[ 9!J#l#l#(#4""E=11 !J"[ 9#$"" :r2datetimedater@)r.r/r+rerfrgs @@@r*rXzDATETIME.bind_processorsG$- &       :r2cp|jr$tj|jtjStjSr#)r?r !str_to_datetime_processor_factoryristr_to_datetimer.r/r0s r*r-zDATETIME.result_processors6 9 .? 8, - -r2 r3r4r5__doc__r@r<rXr-r6r7s@r*r\r\smD A """"H.......r2r\c"eZdZdZdZdZdZdS)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)02dc<tj|jfd}|S)Ncz|dSt|r|j|j|jdzSt d)N)rFrGrHz;SQLite Date type only accepts Python date objects as input.)r%rFrGrHr$)r(rergs r*r+z$DATE.bind_processor..processNs^}tE=11 !J"[ 9""  -r2rh)r.r/r+rergs @@r*rXzDATE.bind_processorJs8 &      r2cp|jr$tj|jtjStjSr#)r?r rlrirj str_to_daterns r*r-zDATE.result_processor_5 9 *? 8= ) )r2N)r3r4r5rpr@rXr-r;r2r*rrrr'sD@9O******r2rrc2eZdZdZdZfdZdZdZxZS)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)06dc|dd}tt|j|i||r d|_dSdS)Nr^Fz$%(hour)02d:%(minute)02d:%(second)02d)r_r,ryr<r@r`s r*r<z TIME.__init__s` & +BE J J"dD"D3F333 J$JD  J Jr2c<tj|jfd}|S)Nc|dSt|r|j|j|j|jdzSt d)N)rIrJrKrLz;SQLite Time type only accepts Python time objects as input.)r%rIrJrKrLr$)r( datetime_timergs r*r+z$TIME.bind_processor..processsd}tE=11 !J#l#l#(#4 "" -r2)ritimer@)r.r/r+r}rgs @@r*rXzTIME.bind_processors8 &       r2cp|jr$tj|jtjStjSr#)r?r rlrir~ str_to_timerns r*r-zTIME.result_processorrwr2ror7s@r*ryryhsm>OO J J J J J,*******r2ryBIGINTrBOOLrr DATE_CHAR DATETIME_CHARDOUBLErrINTrrrr)rrry TIME_CHARrrNVARCHARNCHARceZdZejejjddddddddd d d Zd Zd Z dZ dZ dZ fdZ dZdZdZdZdZdZdZdZxZS)SQLiteCompilerz%mz%dz%Yz%Sz%Hz%jz%Mz%sz%wz%W) rGrHrFrKrIdoyrJepochdowweekc dS)NCURRENT_TIMESTAMPr;r.fnrCs r*visit_now_funczSQLiteCompiler.visit_now_funcs""r2c dS)Nz(DATETIME(CURRENT_TIMESTAMP, "localtime")r;)r.funcrCs r*visit_localtimestamp_funcz(SQLiteCompiler.visit_localtimestamp_funcs99r2c dS)N1r;r.exprrCs r* visit_truezSQLiteCompiler.visit_truesr2c dS)N0r;rs r* visit_falsezSQLiteCompiler.visit_falserr2c 2d||zS)Nzlength%s)function_argspecrs r*visit_char_length_funcz%SQLiteCompiler.visit_char_length_funcsD11"5555r2c |jjr!tt|j|fi|S|j|jfi|Sr#)r/ supports_castr,r visit_castr+clause)r.castrbr1s r*rzSQLiteCompiler.visit_castsQ < % 795..9$II&II I4< 66v66 6r2c d|j|jd|j|jfi|dS#t$r;}t jtjd|jz|Yd}~dSd}~wwxYw)NzCAST(STRFTIME('z', z ) AS INTEGER)z#%s is not a valid extract argument.replace_context) extract_mapfieldr+rKeyErrorrraise_r CompileError)r.extractrCerrs r* visit_extractzSQLiteCompiler.visit_extracts  /// W\00R0000     K 9GMI!$            s)+ A00A++A0c @d}|j|d|j|jfi|zz }|jN|j-|d|tjdzz }|d|j|jfi|zz }n&|d|jtjdfi|zz }|S)Nz LIMIT z OFFSET r) _limit_clauser+_offset_clauser literal)r.selectrCtexts r* limit_clausezSQLiteCompiler.limit_clauses   + K,$,v/C"J"Jr"J"JJ JD  ,#+ dll3;r??&C&CCC Jf.C!J!Jr!J!JJ JDD Jck!nn!C!C!C!CC CD r2c dS)Nrr;)r.rrCs r*for_update_clausez SQLiteCompiler.for_update_clausesrr2c p||jd||jS)Nz IS NOT r+leftrightr.binaryoperatorrCs r*visit_is_distinct_from_binaryz,SQLiteCompiler.visit_is_distinct_from_binary!7 LL % % % % LL & & &  r2c p||jd||jS)Nz IS rrs r* visit_isnot_distinct_from_binaryz/SQLiteCompiler.visit_isnot_distinct_from_binary'rr2c |jjtjurd}nd}||j|jfi||j|jfi|fzSNz JSON_QUOTE(JSON_EXTRACT(%s, %s))zJSON_EXTRACT(%s, %s)type_type_affinitysqltypesrr+rrr.rrrCrs r*visit_json_getitem_op_binaryz+SQLiteCompiler.visit_json_getitem_op_binary-d ; % 6 65DD)D DL + + + + DL , , , ,   r2c |jjtjurd}nd}||j|jfi||j|jfi|fzSrrrs r*!visit_json_path_getitem_op_binaryz0SQLiteCompiler.visit_json_path_getitem_op_binary8rr2cddd|ptgDddd|ptgDdS)NzSELECT , c3K|]}dVdSrNr;.0type_s r* z6SQLiteCompiler.visit_empty_set_expr..E"DDecDDDDDDr2z FROM (SELECT c3K|]}dVdSrr;rs r*rz6SQLiteCompiler.visit_empty_set_expr..Frr2z ) WHERE 1!=1)joinr)r. element_typess r*visit_empty_set_exprz#SQLiteCompiler.visit_empty_set_exprCsl IIDD}'C DDD D D D D IIDD}'C DDD D D D D  r2)r3r4r5r update_copyr SQLCompilerrrrrrrrrrrrrrrrr6r7s@r*rrs@"$"( K ###:::66677777                          r2rcbeZdZdZfdZfdZfdZfdZfdZdZ d d Z d Z xZ S) SQLiteDDLCompilerc b|jj|j|}|j|dz|z}||}|/t|jj trd|zdz}|d|zz }|j s"|dz }|j dd}||d |zz }|j r|jd ur6t|jj jd krt%jd |jj dd rtt|jj jd krRt)|jjt,jr.|js'|dz }|j dd}||d |zz }|dz }|j |d||jzz }|S)N)type_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)r/ type_compilerr+rpreparer format_columnget_column_default_stringr%server_defaultargrnullabledialect_options primary_keyrlentablecolumnsrrrRrrInteger foreign_keyscomputed)r.columnrbr0colspecron_conflict_clauses r*get_column_specificationz*SQLiteDDLCompiler.get_column_specificationKs,,44 K5  ---f55;gE0088  &/3]CC .-#- {W, ,G @ { "G!'!7!A&" "-?-???   ,$,, 0899Q>>&-  ,X6G , 0899Q>>v{98;KLL?+?>)%+%;H%E-&"&11CCCG++ ? & sT\\&/::: :Gr2ct|jdkrat|d}|jrE|jjddr-t |jjtj r |j sdStt||}|jdd}|>t|jdkr&t|djdd}||d|zz }|S)Nrrrr on_conflictrr)rrlistrrrrRrrrrrr,rvisit_primary_key_constraint)r. constraintcrrr1s r*rz.SQLiteDDLCompiler.visit_primary_key_constraints z! " "a ' 'Z  #A  G+H5oF qv4h6FGG    t&--JJ   (7A    %#j.@*A*AQ*F*F!%j!1!1!!4!DX!N)"   ) O&88 8D r2cptt||}|jdd}|mt |jdkrUt |d}t|tj r&t |djdd}||d|zz }|S)Nrrrron_conflict_uniquer) r,rvisit_unique_constraintrrrrr%r SchemaItem)r.rrrcol1r1s r*r z)SQLiteDDLCompiler.visit_unique_constraints&--EE   (7A    %#j.@*A*AQ*F*F ##A&D$ 122 (%)*%5%5a%8%H&&&("  ) O&88 8D r2ctt||}|jdd}||d|zz }|S)Nrrr)r,rvisit_check_constraintr)r.rrrr1s r*rz(SQLiteDDLCompiler.visit_check_constraints[&--DD   (7A    ) O&88 8D r2ctt||}|jddt jd|S)NrrzFSQLite does not support on conflict clause for column check constraint)r,rvisit_column_check_constraintrrr)r.rrr1s r*rz/SQLiteDDLCompiler.visit_column_check_constraints\&--KK     %h / > J"*   r2c|jdjj}|jdjj}|j|jkrdSt t ||S)Nr)elementsparentrrr r,rvisit_foreign_key_constraint)r.r local_table remote_tabler1s r*rz.SQLiteDDLCompiler.visit_foreign_key_constraintse )!,39 !*1-4:  !4 4 44*D11NN r2c0||dS)z=Format the remote table clause of a CREATE CONSTRAINT clause.F use_schema) format_table)r.rrrs r*define_constraint_remote_tablez0SQLiteDDLCompiler.define_constraint_remote_tables$$Uu$===r2FTc |j}|j}d}|jr|dz }|d|dd||jdd d fd |jDd z }|j d d}|%j |dd}|d|zz }|S)NzCREATE zUNIQUE zINDEX T)include_schemaz ON Frz (rc3RK|]!}j|ddV"dS)FT include_table literal_bindsN) sql_compilerr+)rrr.s r*rz7SQLiteDDLCompiler.visit_create_index..sX!))T*r2rrwherer z WHERE ) element_verify_index_tablerunique_prepared_index_namerrr expressionsrr#r+) r.createrinclude_table_schemaindexrr whereclausewhere_compileds ` r*visit_create_indexz$SQLiteDDLCompiler.visit_create_indexs%   '''= <  I D   % %eD % A A A A  ! !%+% ! @ @ @ @ II"-       +H5g>  "!.6657N I. .D r2c4|jdddurdSdS)Nr with_rowidFz WITHOUT ROWIDr)r)r.rs r*post_create_tablez#SQLiteDDLCompiler.post_create_tables%   *< 8E A A%%rr2)FT) r3r4r5rrr rrrrr/r2r6r7s@r*rrJs222h>(               >>> BF:r2rc>eZdZdZfdZfdZfdZdZxZS)SQLiteTypeCompilerc ,||Sr#) visit_BLOBr.rrCs r*visit_large_binaryz%SQLiteTypeCompiler.visit_large_binarysu%%%r2c t|tr|jr(tt||SdS)Nr)r%r9rPr,r4visit_DATETIMEr.rrCr1s r*r:z!SQLiteTypeCompiler.visit_DATETIMEsF5.11 #, #+T22AA%HH H"?r2c t|tr|jr(tt||SdS)Nr)r%r9rPr,r4 visit_DATEr;s r*r=zSQLiteTypeCompiler.visit_DATEF5.11 , +T22==eDD D;r2c t|tr|jr(tt||SdS)Nr)r%r9rPr,r4 visit_TIMEr;s r*r@zSQLiteTypeCompiler.visit_TIMEr>r2c dS)Nrr;r7s r* visit_JSONzSQLiteTypeCompiler.visit_JSON s vr2) r3r4r5r8r:r=r@rBr6r7s@r*r4r4s&&&#####r2r4c(eZdZegdZdS)SQLiteIdentifierPreparer)uaddafterallalteranalyzeandasascattachrbeforebeginbetweenbycascadecasercheckcollatercommitconflictrr*cross current_date current_timecurrent_timestampdatabaser deferrabledeferreddeletedescdetachdistinctdropeachelseendescapeexcept exclusiveexistsexplainfalsefailforforeignfromfullglobgrouphavingifignore immediateinr,indexed initiallyinnerinsertinstead intersectintoisisnullrkeyrlikelimitmatchnaturalnotnotnullnullofoffsetonororderouterplanpragmaprimaryqueryraise referencesreindexrenamereplacerestrictrrollbackrowrsetrtemp temporarythento transactiontriggertrueunionr'updateusingvacuumvaluesviewvirtualwhenr$N)r3r4r5rreserved_wordsr;r2r*rDrD's3Sv v v xxNNNr2rDc4eZdZejdZdZdS)SQLiteExecutionContextcR|jj p|jddS)Nsqlite_raw_colnamesF)r/_broken_dotted_colnamesexecution_optionsget)r.s r*_preserve_raw_colnamesz-SQLiteExecutionContext._preserve_raw_colnamess1 4 4 H%))*?GG r2cZ|js!d|vr|dd|fS|dfS)N.r)rsplit)r.colnames r*_translate_colnamez)SQLiteExecutionContext._translate_colnames=* !sg~~==%%b)72 2D= r2N)r3r4r5rmemoized_propertyrrr;r2r*rrs@    ! ! ! ! !r2rceZdZdZdZdZdZdZdZdZ dZ dZ dZ e ZeZeZeZeZeZeZdZejdddfejddifejddddfejd difgZdZ dZ!e"j#d d  d&d Z$dddZ%dZ&dZ'dZ(e)j*dZ+e)j*d'dZ,e)j*dZ-e)j*dZ.d'dZ/e)j*d'dZ0e)j*d'dZ1e)j*d'dZ2dZ3dZ4e)j*d'dZ5e)j*d'dZ6d Z7e)j* d'd!Z8e)j*d'd"Z9e)j*d'd#Z:e)j*d'd$Z;d'd%Z aZZ%%Zr2c$jfd}|SdS)Nc>|jdSr#)rr)connr.s r*connectz)SQLiteDialect.on_connect..connectTs"((t/CDDDDDr2)r)r.rs` r* on_connectzSQLiteDialect.on_connectQs6   + E E E E EN4r2c Hd}||}d|DS)NzPRAGMA database_listc6g|]}|ddk|dS)rrr;)rdbs r* z2SQLiteDialect.get_schema_names..`s%666"bevoo1ooor2r)r.rrCsdls r*get_schema_nameszSQLiteDialect.get_schema_names[s. "    " "666666r2c | |j|}d|z}nd}d|d}||}d|DS)N%s.sqlite_master sqlite_masterSELECT name FROM z! WHERE type='table' ORDER BY namecg|] }|d Srr;rrs r*rz1SQLiteDialect.get_table_names..m%%%3A%%%r2identifier_preparerquote_identifierrr.rr rCqschemamasterrrss r*get_table_nameszSQLiteDialect.get_table_namesbsg  .??GGG''1FF$F FF    " "%%"%%%%r2c Hd}||}d|DS)NzESELECT name FROM sqlite_temp_master WHERE type='table' ORDER BY name cg|] }|d Srr;rs r*rz6SQLiteDialect.get_temp_table_names..wrr2rr.rrCrrs r*get_temp_table_namesz"SQLiteDialect.get_temp_table_namesos5 0    " "%%"%%%%r2c Hd}||}d|DS)NzDSELECT name FROM sqlite_temp_master WHERE type='view' ORDER BY name cg|] }|d Srr;rs r*rz5SQLiteDialect.get_temp_view_names..rr2rrs r*get_temp_view_namesz!SQLiteDialect.get_temp_view_namesys5 /    " "%%"%%%%r2cR||d||}t|S)N table_infor )_get_table_pragmarM)r.r table_namer infos r* has_tablezSQLiteDialect.has_tables3%%  j&  Dzzr2c | |j|}d|z}nd}d|d}||}d|DS)Nrrrz WHERE type='view' ORDER BY namecg|] }|d Srr;rs r*rz0SQLiteDialect.get_view_names..rr2rrs r*get_view_nameszSQLiteDialect.get_view_namessg  .??GGG''1FF$F FF    " "%%"%%%%r2c \|=|j|}d|z}d|d}|||f}nI d}|||f}n.#tj$rd}|||f}YnwxYw|} | r | djSdS)NrzSELECT 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