SQLite

Support for the SQLite database.

DBAPI Support

The following dialect/DBAPI options are available. Please refer to individual DBAPI sections for connect information.

Date and Time Types

SQLite does not have built-in DATE, TIME, or DATETIME types, and pysqlite doesnot provide out of the box functionality for translating values between Pythondatetime objects and a SQLite-supported format. SQLAlchemy’s ownDateTime and related types provide date formattingand parsing functionality when SQLite is used. The implementation classes areDATETIME, DATE and TIME.These types represent dates and times as ISO formatted strings, which alsonicely support ordering. There’s no reliance on typical “libc” internals forthese functions so historical dates are fully supported.

Ensuring Text affinity

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

See also

Type Affinity -in the SQLite documentation

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 anynon-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 notequivalent to the implicit autoincrement feature; this keyword is notrecommended for general use. SQLAlchemy does not render this keywordunless 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 columnwhen rendering DDL, add the flag sqlite_autoincrement=True to the Tableconstruct:

  1. Table('sometable', metadata,
  2. Column('id', Integer, primary_key=True),
  3. sqlite_autoincrement=True)

Allowing autoincrement behavior SQLAlchemy types other than Integer/INTEGER

SQLite’s typing model is based on naming conventions. Among other things, thismeans that any type name which contains the substring "INT" will bedetermined to be of “integer affinity”. A type named "BIGINT","SPECIAL_INT" or even "XYZINTQPR", will be considered by SQLite to beof “integer” affinity. However, the SQLite autoincrement feature, whetherimplicitly or explicitly enabled, requires that the name of the column’s typeis exactly the string “INTEGER”. Therefore, if an application uses a typelike BigInteger for a primary key, on SQLite this type will need tobe rendered as the name "INTEGER" when emitting the initial CREATETABLE statement in order for the autoincrement behavior to be available.

One approach to achieve this is to use Integer on SQLiteonly using TypeEngine.with_variant():

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

Another is to use a subclass of BigInteger that overrides its DDLname to be INTEGER when compiled against SQLite:

  1. from sqlalchemy import BigInteger
  2. from sqlalchemy.ext.compiler import compiles
  3.  
  4. class SLBigInteger(BigInteger):
  5. pass
  6.  
  7. @compiles(SLBigInteger, 'sqlite')
  8. def bi_c(element, compiler, **kw):
  9. return "INTEGER"
  10.  
  11. @compiles(SLBigInteger)
  12. def bi_c(element, compiler, **kw):
  13. return compiler.visit_BIGINT(element, **kw)
  14.  
  15.  
  16. table = Table(
  17. "my_table", metadata,
  18. Column("id", SLBigInteger(), primary_key=True)
  19. )

See also

TypeEngine.with_variant()

Custom SQL Constructs and Compilation Extension

Datatypes In SQLite Version 3

Database Locking Behavior / Concurrency

SQLite is not designed for a high level of write concurrency. The databaseitself, being a file, is locked completely during write operations withintransactions, 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 isalways in a transaction; there is no connection.begin() method,only connection.commit() and connection.rollback(), upon which anew transaction is to be begun immediately. This may seem to implythat the SQLite driver would in theory allow only a single filehandle on aparticular database file at any time; however, there are severalfactors both within SQLite itself as well as within the pysqlite driverwhich loosen this restriction significantly.

However, no matter what locking modes are used, SQLite will still alwayslock the database file once a transaction is started and DML (e.g. INSERT,UPDATE, DELETE) has at least been emitted, and this will blockother 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 outwith an error.

This behavior becomes more critical when used in conjunction with theSQLAlchemy ORM. SQLAlchemy’s Session object by default runswithin a transaction, and with its autoflush model, may emit DML precedingany SELECT statement. This may lead to a SQLite database that locksmore quickly than is expected. The locking mode of SQLite and the pysqlitedriver can be manipulated to some degree, however it should be noted thatachieving a high degree of write-concurrency with SQLite is a losing battle.

For more information on SQLite’s lack of write concurrency by design, pleaseseeSituations Where Another RDBMS May Work Better - High Concurrency near the bottom of the page.

The following subsections introduce areas that are impacted by SQLite’sfile-based architecture and additionally will usually require workarounds towork when using the pysqlite driver.

Transaction Isolation Level

SQLite supports “transaction isolation” in a non-standard way, along twoaxes. One is that of thePRAGMA read_uncommittedinstruction. This setting can essentially switch SQLite between itsdefault mode of SERIALIZABLE isolation, and a “dirty read” isolationmode normally referred to as READ UNCOMMITTED.

SQLAlchemy ties into this PRAGMA statement using thecreate_engine.isolation_level parameter of 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 bythe pysqlite driver’s default behavior.

The other axis along which SQLite’s transactional locking is impacted isvia the nature of the BEGIN statement used. The three varietiesare “deferred”, “immediate”, and “exclusive”, as described atBEGIN TRANSACTION. A straightBEGIN statement uses the “deferred” mode, where the database file isnot locked until the first read or write operation, and read access remainsopen to other transactions until the first write operation. But again,it is critical to note that the pysqlite driver interferes with this behaviorby not even emitting BEGIN until the first write operation.

Warning

SQLite’s transactional scope is impacted by unresolvedissues in the pysqlite driver, which defers BEGIN statements to a greaterdegree than is often feasible. See the section Serializable isolation / Savepoints / Transactional DDLfor techniques to work around this behavior.

SAVEPOINT Support

SQLite supports SAVEPOINTs, which only function once a transaction isbegun. SQLAlchemy’s SAVEPOINT support is available using theConnection.begin_nested() method at the Core level, andSession.begin_nested() at the ORM level. However, SAVEPOINTswon’t work at all with pysqlite unless workarounds are taken.

Warning

SQLite’s SAVEPOINT feature is impacted by unresolvedissues in the pysqlite driver, which defers BEGIN statements to a greaterdegree than is often feasible. See the section Serializable isolation / Savepoints / Transactional DDLfor techniques to work around this behavior.

Transactional DDL

The SQLite database supports transactional 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 issuesin the pysqlite driver, which fails to emit BEGIN and additionallyforces a COMMIT to cancel any transaction when DDL is encountered.See the section Serializable isolation / Savepoints / Transactional DDLfor techniques to work around this behavior.

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 thetable.

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_KEYor SQLITE_OMIT_TRIGGER symbols enabled.

  • The PRAGMA foreign_keys = ON statement must be emitted on allconnections before use.

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

  1. from sqlalchemy.engine import Engine
  2. from sqlalchemy import event
  3.  
  4. @event.listens_for(Engine, "connect")
  5. def set_sqlite_pragma(dbapi_connection, connection_record):
  6. cursor = dbapi_connection.cursor()
  7. cursor.execute("PRAGMA foreign_keys=ON")
  8. cursor.close()

Warning

When SQLite foreign keys are enabled, it is not possibleto emit CREATE or DROP statements for tables that containmutually-dependent foreign key constraints;to emit the DDL for these tables requires that ALTER TABLE be used tocreate or drop these constraints separately, for which SQLite hasno support.

See also

SQLite Foreign Key Support- on the SQLite web site.

Events - SQLAlchemy event API.

ON CONFLICT support for constraints

SQLite supports a non-standard clause known as ON CONFLICT which can be appliedto primary key, unique, check, and not null constraints. In DDL, it isrendered either within the “CONSTRAINT” clause or within the column definitionitself depending on the location of the target constraint. To render thisclause within DDL, the extension parameter sqlite_on_conflict can bespecified with a string conflict resolution algorithm within thePrimaryKeyConstraint, UniqueConstraint,CheckConstraint objects. Within the Column object, thereare individual parameters sqlite_on_conflict_not_null,sqlite_on_conflict_primary_key, sqlite_on_conflict_unique which eachcorrespond to the three types of relevant constraint types that can beindicated from a Column object.

See also

ON CONFLICT - in the SQLitedocumentation

New in version 1.3.

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

  1. some_table = Table(
  2. 'some_table', metadata,
  3. Column('id', Integer, primary_key=True),
  4. Column('data', Integer),
  5. UniqueConstraint('id', 'data', sqlite_on_conflict='IGNORE')
  6. )

The above renders CREATE TABLE DDL as:

  1. CREATE TABLE some_table (
  2. id INTEGER NOT NULL,
  3. data INTEGER,
  4. PRIMARY KEY (id),
  5. UNIQUE (id, data) ON CONFLICT IGNORE
  6. )

When using the Column.unique flag to add a UNIQUE constraintto a single column, the sqlite_on_conflict_unique parameter canbe added to the Column as well, which will be added to theUNIQUE constraint in the DDL:

  1. some_table = Table(
  2. 'some_table', metadata,
  3. Column('id', Integer, primary_key=True),
  4. Column('data', Integer, unique=True,
  5. sqlite_on_conflict_unique='IGNORE')
  6. )

rendering:

  1. CREATE TABLE some_table (
  2. id INTEGER NOT NULL,
  3. data INTEGER,
  4. PRIMARY KEY (id),
  5. UNIQUE (data) ON CONFLICT IGNORE
  6. )

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

  1. some_table = Table(
  2. 'some_table', metadata,
  3. Column('id', Integer, primary_key=True),
  4. Column('data', Integer, nullable=False,
  5. sqlite_on_conflict_not_null='FAIL')
  6. )

this renders the column inline ON CONFLICT phrase:

  1. CREATE TABLE some_table (
  2. id INTEGER NOT NULL,
  3. data INTEGER NOT NULL ON CONFLICT FAIL,
  4. PRIMARY KEY (id)
  5. )

Similarly, for an inline primary key, use sqlite_on_conflict_primary_key:

  1. some_table = Table(
  2. 'some_table', metadata,
  3. Column('id', Integer, primary_key=True,
  4. sqlite_on_conflict_primary_key='FAIL')
  5. )

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

  1. CREATE TABLE some_table (
  2. id INTEGER NOT NULL,
  3. PRIMARY KEY (id) ON CONFLICT FAIL
  4. )

Type Reflection

SQLite types are unlike those of most other database backends, in thatthe string name of the type usually does not correspond to a “type” in aone-to-one fashion. Instead, SQLite links per-column typing behaviorto one of five so-called “type affinities” based on a string matchingpattern for the type.

SQLAlchemy’s reflection process, when inspecting types, uses a simplelookup table to link the keywords returned to provided SQLAlchemy types.This lookup table is present within the SQLite dialect as it is for allother 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 athttp://www.sqlite.org/datatype3.html section 2.1.

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

BIGINT, BLOB,BOOLEAN, BOOLEAN,CHAR, DATE,DATETIME, FLOAT,DECIMAL, FLOAT,INTEGER, INTEGER,NUMERIC, REAL,SMALLINT, TEXT,TIME, TIMESTAMP,VARCHAR, NVARCHAR,NCHAR

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

  • INTEGER is returned if the type name includes thestring INT

  • TEXT is returned if the type name includes thestring CHAR, CLOB or TEXT

  • NullType is returned if the type name includes thestring BLOB

  • REAL is returned if the type name includes the stringREAL, FLOA or DOUB.

  • Otherwise, the NUMERIC type is used.

New in version 0.9.3: Support for SQLite type affinity rules when reflectingcolumns.

Partial Indexes

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

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

The index will be rendered at create time as:

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

New in version 0.9.9.

Dotted Column Names

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

Changed in version 1.1: The following SQLite issue has been resolved as of version 3.10.0of SQLite. SQLAlchemy as of 1.1 automatically disables its internalworkarounds based on detection of this version.

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

  1. import sqlite3
  2.  
  3. assert sqlite3.sqlite_version_info < (3, 10, 0), "bug is fixed in this version"
  4.  
  5. conn = sqlite3.connect(":memory:")
  6. cursor = conn.cursor()
  7.  
  8. cursor.execute("create table x (a integer, b integer)")
  9. cursor.execute("insert into x (a, b) values (1, 1)")
  10. cursor.execute("insert into x (a, b) values (2, 2)")
  11.  
  12. cursor.execute("select x.a, x.b from x")
  13. assert [c[0] for c in cursor.description] == ['a', 'b']
  14.  
  15. cursor.execute('''
  16. select x.a, x.b from x where a=1
  17. union
  18. select x.a, x.b from x where a=2
  19. ''')
  20. assert [c[0] for c in cursor.description] == ['a', 'b'], \
  21. [c[0] for c in cursor.description]

The second assertion fails:

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

Where above, the driver incorrectly reports the names of the columnsincluding 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 matchto the original statement, so the SQLAlchemy dialect has no choice butto filter these out:

  1. from sqlalchemy import create_engine
  2.  
  3. eng = create_engine("sqlite://")
  4. conn = eng.connect()
  5.  
  6. conn.execute("create table x (a integer, b integer)")
  7. conn.execute("insert into x (a, b) values (1, 1)")
  8. conn.execute("insert into x (a, b) values (2, 2)")
  9.  
  10. result = conn.execute("select x.a, x.b from x")
  11. assert result.keys() == ["a", "b"]
  12.  
  13. result = conn.execute('''
  14. select x.a, x.b from x where a=1
  15. union
  16. select x.a, x.b from x where a=2
  17. ''')
  18. assert result.keys() == ["a", "b"]

Note that above, even though SQLAlchemy filters out the dots, bothnames are still addressable:

  1. >>> row = result.first()
  2. >>> row["a"]
  3. 1
  4. >>> row["x.a"]
  5. 1
  6. >>> row["b"]
  7. 1
  8. >>> row["x.b"]
  9. 1

Therefore, the workaround applied by SQLAlchemy only impactsResultProxy.keys() and RowProxy.keys() in the public API. Inthe very specific case where an application is forced to use column names thatcontain dots, and the functionality of ResultProxy.keys() andRowProxy.keys() is required to return these dotted names unmodified,the sqlite_raw_colnames execution option may be provided, either on aper-Connection basis:

  1. result = conn.execution_options(sqlite_raw_colnames=True).execute('''
  2. select x.a, x.b from x where a=1
  3. union
  4. select x.a, x.b from x where a=2
  5. ''')
  6. assert result.keys() == ["x.a", "x.b"]

or on a per-Engine basis:

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

When using the per-Engine execution option, note thatCore and ORM queries that use UNION may not function properly.

SQLite Data Types

As with all SQLAlchemy dialects, all UPPERCASE types that are known to bevalid with SQLite are importable from the top level dialect, whetherthey originate from sqlalchemy.types or from the local dialect:

  1. from sqlalchemy.dialects.sqlite import \
  2. BLOB, BOOLEAN, CHAR, DATE, DATETIME, DECIMAL, FLOAT, \
  3. INTEGER, NUMERIC, JSON, SMALLINT, TEXT, TIME, TIMESTAMP, \
  4. VARCHAR
  • class sqlalchemy.dialects.sqlite.DATETIME(*args, **kwargs)
  • Bases: sqlalchemy.dialects.sqlite.base._DateTimeMixin, sqlalchemy.types.DateTime

Represent a Python datetime object in SQLite using a string.

The default string storage format is:

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

e.g.:

  1. 2011-03-15 12:05:57.10558

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

  1. import re
  2. from sqlalchemy.dialects.sqlite import DATETIME
  3.  
  4. dt = DATETIME(storage_format="%(year)04d/%(month)02d/%(day)02d "
  5. "%(hour)02d:%(min)02d:%(second)02d",
  6. regexp=r"(\d+)/(\d+)/(\d+) (\d+)-(\d+)-(\d+)"
  7. )
  • Parameters
    • storage_format – format string which will be applied to the dictwith keys year, month, day, hour, minute, second, and microsecond.

    • regexp – regular expression which will be applied to incoming resultrows. If the regexp contains named groups, the resulting match dict isapplied to the Python datetime() constructor as keyword arguments.Otherwise, if positional groups are used, the datetime() constructoris called with positional arguments via*map(int, match_obj.groups(0)).

  • class sqlalchemy.dialects.sqlite.DATE(storage_format=None, regexp=None, **kw)
  • Bases: sqlalchemy.dialects.sqlite.base._DateTimeMixin, sqlalchemy.types.Date

Represent a Python date object in SQLite using a string.

The default string storage format is:

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

e.g.:

  1. 2011-03-15

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

  1. import re
  2. from sqlalchemy.dialects.sqlite import DATE
  3.  
  4. d = DATE(
  5. storage_format="%(month)02d/%(day)02d/%(year)04d",
  6. regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)")
  7. )
  • Parameters
    • storage_format – format string which will be applied to thedict with keys year, month, and day.

    • regexp – regular expression which will be applied toincoming result rows. If the regexp contains named groups, theresulting match dict is applied to the Python date() constructoras keyword arguments. Otherwise, if positional groups are used, thedate() constructor is called with positional arguments via*map(int, match_obj.groups(0)).

SQLite JSON type.

SQLite supports JSON as of version 3.9 through its JSON1 extension. Notethat JSON1 is aloadable extension and as suchmay not be available, or may require run-time loading.

The sqlite.JSON type supports persistence of JSON valuesas well as the core index operations provided by types.JSONdatatype, by adapting the operations to render the JSON_EXTRACTfunction wrapped in the JSON_QUOTE function at the database level.Extracted values are quoted in order to ensure that the results arealways JSON string values.

New in version 1.3.

See also

JSON1

  • class sqlalchemy.dialects.sqlite.TIME(*args, **kwargs)
  • Bases: sqlalchemy.dialects.sqlite.base._DateTimeMixin, sqlalchemy.types.Time

Represent a Python time object in SQLite using a string.

The default string storage format is:

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

e.g.:

  1. 12:05:57.10558

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

  1. import re
  2. from sqlalchemy.dialects.sqlite import TIME
  3.  
  4. t = TIME(storage_format="%(hour)02d-%(minute)02d-"
  5. "%(second)02d-%(microsecond)06d",
  6. regexp=re.compile("(\d+)-(\d+)-(\d+)-(?:-(\d+))?")
  7. )
  • Parameters
    • storage_format – format string which will be applied to the dictwith keys hour, minute, second, and microsecond.

    • regexp – regular expression which will be applied to incoming resultrows. If the regexp contains named groups, the resulting match dict isapplied to the Python time() constructor as keyword arguments. Otherwise,if positional groups are used, the time() constructor is called withpositional arguments via *map(int, match_obj.groups(0)).

Pysqlite

Support for the SQLite database via the pysqlite driver.

Note that pysqlite is the same driver as the sqlite3module included with the Python distribution.

DBAPI

Documentation and download information (if applicable) for pysqlite is available at:http://docs.python.org/library/sqlite3.html

Connecting

Connect String:

  1. sqlite+pysqlite:///file_path

Driver

The sqlite3 Python DBAPI is standard on all modern Python versions;for cPython and Pypy, no additional installation is necessary.

Connect Strings

The file specification for the SQLite database is taken as the “database”portion of the URL. Note that the format of a SQLAlchemy url is:

  1. driver://user:pass@host/database

This means that the actual filename to be used starts with the characters tothe right of the third slash. So connecting to a relative filepathlooks like:

  1. # relative path
  2. e = create_engine('sqlite:///path/to/database.db')

An absolute path, which is denoted by starting with a slash, means youneed four slashes:

  1. # absolute path
  2. e = create_engine('sqlite:////path/to/database.db')

To use a Windows path, regular drive specifications and backslashes can beused. Double backslashes are probably needed:

  1. # absolute path on Windows
  2. e = create_engine('sqlite:///C:\\path\\to\\database.db')

The sqlite :memory: identifier is the default if no filepath ispresent. Specify sqlite:// and nothing else:

  1. # in-memory database
  2. e = create_engine('sqlite://')

URI Connections

Modern versions of SQLite support an alternative system of connecting using adriver level URI, which has the advantagethat additional driver-level arguments can be passed including options such as“read only”. The Python sqlite3 driver supports this mode under modern Python3 versions. The SQLAlchemy pysqlite driver supports this mode of use byspecifing “uri=true” in the URL query string. The SQLite-level “URI” is keptas the “database” portion of the SQLAlchemy url (that is, following a slash):

  1. e = create_engine("sqlite:///file:path/to/database?mode=ro&uri=true")

Note

The “uri=true” parameter must appear in the query stringof the URL. It will not currently work as expected if it is onlypresent in the create_engine.connect_args parameter dictionary.

The logic reconciles the simultaneous presence of SQLAlchemy’s query string andSQLite’s query string by separating out the parameters that belong to thePython sqlite3 driver vs. those that belong to the SQLite URI. This isachieved through the use of a fixed list of parameters known to be accepted bythe Python side of the driver. For example, to include a URL that indicatesthe Python sqlite3 “timeout” and “check_same_thread” parameters, along with theSQLite “mode” and “nolock” parameters, they can all be passed together on thequery string:

  1. e = create_engine(
  2. "sqlite:///file:path/to/database?"
  3. "check_same_thread=true&timeout=10&mode=ro&nolock=1&uri=true"
  4. )

Above, the pysqlite / sqlite3 DBAPI would be passed arguments as:

  1. sqlite3.connect(
  2. "file:path/to/database?mode=ro&nolock=1",
  3. check_same_thread=True, timeout=10, uri=True
  4. )

Regarding future parameters added to either the Python or native drivers. newparameter names added to the SQLite URI scheme should be automaticallyaccommodated by this scheme. New parameter names added to the Python driverside can be accommodated by specifying them in thecreate_engine.connect_args dictionary, until dialect support isadded by SQLAlchemy. For the less likely case that the native SQLite driveradds a new parameter name that overlaps with one of the existing, known Pythondriver parameters (such as “timeout” perhaps), SQLAlchemy’s dialect wouldrequire adjustment for the URL scheme to continue to support this.

As is always the case for all SQLAlchemy dialects, the entire “URL” processcan be bypassed in create_engine() through the use of thecreate_engine.creator parameter which allows for a custom callablethat creates a Python sqlite3 driver level connection directly.

New in version 1.3.9.

See also

Uniform Resource Identifiers - inthe SQLite documentation

Compatibility with sqlite3 “native” date and datetime types

The pysqlite driver includes the sqlite3.PARSE_DECLTYPES andsqlite3.PARSE_COLNAMES options, which have the effect of any columnor expression explicitly cast as “date” or “timestamp” will be convertedto a Python date or datetime object. The date and datetime types providedwith the pysqlite dialect are not currently compatible with these options,since they render the ISO date/datetime including microseconds, whichpysqlite’s driver does not. Additionally, SQLAlchemy does not atthis time automatically render the “cast” syntax required for thefreestanding functions “current_timestamp” and “current_date” to returndatetime/date types natively. Unfortunately, pysqlitedoes not provide the standard DBAPI types in cursor.description,leaving SQLAlchemy with no way to detect these types on the flywithout expensive per-row type checks.

Keeping in mind that pysqlite’s parsing option is not recommended,nor should be necessary, for use with SQLAlchemy, usage of PARSE_DECLTYPEScan be forced if one configures “native_datetime=True” on create_engine():

  1. engine = create_engine('sqlite://',
  2. connect_args={'detect_types':
  3. sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES},
  4. native_datetime=True
  5. )

With this flag enabled, the DATE and TIMESTAMP types (but note - not theDATETIME or TIME types…confused yet ?) will not perform any bind parameteror result processing. Execution of “func.current_date()” will return a string.“func.current_timestamp()” is registered as returning a DATETIME type inSQLAlchemy, so this function still receives SQLAlchemy-level resultprocessing.

Threading/Pooling Behavior

Pysqlite’s default behavior is to prohibit the usage of a single connectionin more than one thread. This is originally intended to work with olderversions of SQLite that did not support multithreaded operation undervarious circumstances. In particular, older SQLite versionsdid not allow a :memory: database to be used in multiple threadsunder any circumstances.

Pysqlite does include a now-undocumented flag known ascheck_same_thread which will disable this check, however note thatpysqlite connections are still not safe to use in concurrently in multiplethreads. In particular, any statement execution calls would need to beexternally mutexed, as Pysqlite does not provide for thread-safe propagationof error messages among other things. So while even :memory: databasescan be shared among threads in modern SQLite, Pysqlite doesn’t provide enoughthread-safety to make this usage worth it.

SQLAlchemy sets up pooling to work with Pysqlite’s default behavior:

  • When a :memory: SQLite database is specified, the dialect by defaultwill use SingletonThreadPool. This pool maintains a singleconnection per thread, so that all access to the engine within the currentthread use the same :memory: database - other threads would access adifferent :memory: database.

  • When a file-based database is specified, the dialect will useNullPool as the source of connections. This pool closes anddiscards connections which are returned to the pool immediately. SQLitefile-based connections have extremely low overhead, so pooling is notnecessary. The scheme also prevents a connection from being used again ina different thread and works best with SQLite’s coarse-grained file locking.

Using a Memory Database in Multiple Threads

To use a :memory: database in a multithreaded scenario, the sameconnection object must be shared among threads, since the database existsonly within the scope of that connection. TheStaticPool implementation will maintain a single connectionglobally, and the check_same_thread flag can be passed to Pysqliteas False:

  1. from sqlalchemy.pool import StaticPool
  2. engine = create_engine('sqlite://',
  3. connect_args={'check_same_thread':False},
  4. poolclass=StaticPool)

Note that using a :memory: database in multiple threads requires a recentversion of SQLite.

Using Temporary Tables with SQLite

Due to the way SQLite deals with temporary tables, if you wish to use atemporary table in a file-based SQLite database across multiple checkoutsfrom the connection pool, such as when using an ORM Session wherethe temporary table should continue to remain after Session.commit() orSession.rollback() is called, a pool which maintains a singleconnection must be used. Use SingletonThreadPool if the scope isonly needed within the current thread, or StaticPool is scope isneeded within multiple threads for this case:

  1. # maintain the same connection per thread
  2. from sqlalchemy.pool import SingletonThreadPool
  3. engine = create_engine('sqlite:///mydb.db',
  4. poolclass=SingletonThreadPool)
  5.  
  6.  
  7. # maintain the same connection across all threads
  8. from sqlalchemy.pool import StaticPool
  9. engine = create_engine('sqlite:///mydb.db',
  10. poolclass=StaticPool)

Note that SingletonThreadPool should be configured for the numberof threads that are to be used; beyond that number, connections will beclosed out in a non deterministic way.

Unicode

The pysqlite driver only returns Python unicode objects in result sets,never plain strings, and accommodates unicode objects within boundparameter values in all cases. Regardless of the SQLAlchemy string type inuse, string-based result values will by Python unicode in Python 2.The Unicode type should still be used to indicate those columns thatrequire unicode, however, so that non-unicode values passed inadvertentlywill emit a warning. Pysqlite will emit an error if a non-unicode stringis passed containing non-ASCII characters.

Serializable isolation / Savepoints / Transactional DDL

In the section Database Locking Behavior / Concurrency, we refer to the pysqlitedriver’s assortment of issues that prevent several features of SQLitefrom working correctly. The pysqlite DBAPI driver has severallong-standing bugs which impact the correctness of its transactionalbehavior. In its default mode of operation, SQLite features such asSERIALIZABLE isolation, transactional DDL, and SAVEPOINT support arenon-functional, and in order to use these features, workarounds mustbe taken.

The issue is essentially that the driver attempts to second-guess the user’sintent, failing to start transactions and sometimes ending them prematurely, inan effort to minimize the SQLite databases’s file locking behavior, eventhough SQLite itself uses “shared” locks for read-only activities.

SQLAlchemy chooses to not alter this behavior by default, as it is thelong-expected behavior of the pysqlite driver; if and when the pysqlitedriver attempts to repair these issues, that will be more of a driver towardsdefaults for SQLAlchemy.

The good news is that with a few events, we can implement transactionalsupport fully, by disabling pysqlite’s feature entirely and emitting BEGINourselves. This is achieved using two event listeners:

  1. from sqlalchemy import create_engine, event
  2.  
  3. engine = create_engine("sqlite:///myfile.db")
  4.  
  5. @event.listens_for(engine, "connect")
  6. def do_connect(dbapi_connection, connection_record):
  7. # disable pysqlite's emitting of the BEGIN statement entirely.
  8. # also stops it from emitting COMMIT before any DDL.
  9. dbapi_connection.isolation_level = None
  10.  
  11. @event.listens_for(engine, "begin")
  12. def do_begin(conn):
  13. # emit our own BEGIN
  14. conn.execute("BEGIN")

Above, we intercept a new pysqlite connection and disable any transactionalintegration. Then, at the point at which SQLAlchemy knows that transactionscope is to begin, we emit "BEGIN" ourselves.

When we take control of "BEGIN", we can also control directly SQLite’slocking modes, introduced atBEGIN TRANSACTION,by adding the desired locking mode to our "BEGIN":

  1. @event.listens_for(engine, "begin")def do_begin(conn): conn.execute("BEGIN EXCLUSIVE")

See also

BEGIN TRANSACTION -on the SQLite site

sqlite3 SELECT does not BEGIN a transaction -on the Python bug tracker

sqlite3 module breaks transactions and potentially corrupts data -on the Python bug tracker

Pysqlcipher

Support for the SQLite database via the pysqlcipher driver.

pysqlcipher is a fork of the standard pysqlite driver to makeuse of the SQLCipher backend.

pysqlcipher3 is a fork of pysqlcipher for Python 3. This dialectwill attempt to import it if pysqlcipher is non-present.

New in version 1.1.4: - added fallback import for pysqlcipher3

New in version 0.9.9: - added pysqlcipher dialect

DBAPI

Documentation and download information (if applicable) for pysqlcipher is available at:https://pypi.python.org/pypi/pysqlcipher

Connecting

Connect String:

  1. sqlite+pysqlcipher://:passphrase/file_path[?kdf_iter=<iter>]

Driver

The driver here is thepysqlcipherdriver, which makes use of the SQLCipher engine. This system essentiallyintroduces new PRAGMA commands to SQLite which allows the setting of apassphrase and other encryption parameters, allowing the databasefile to be encrypted.

pysqlcipher3 is a fork of pysqlcipher with support for Python 3,the driver is the same.

Connect Strings

The format of the connect string is in every way the same as thatof the pysqlite driver, except that the“password” field is now accepted, which should contain a passphrase:

  1. e = create_engine('sqlite+pysqlcipher://:testing@/foo.db')

For an absolute file path, two leading slashes should be used for thedatabase name:

  1. e = create_engine('sqlite+pysqlcipher://:testing@//path/to/foo.db')

A selection of additional encryption-related pragmas supported by SQLCipheras documented at https://www.zetetic.net/sqlcipher/sqlcipher-api/ can be passedin the query string, and will result in that PRAGMA being called for eachnew connection. Currently, cipher, kdf_itercipher_page_size and cipher_use_hmac are supported:

  1. e = create_engine('sqlite+pysqlcipher://:testing@/foo.db?cipher=aes-256-cfb&kdf_iter=64000')

Pooling Behavior

The driver makes a change to the default pool behavior of pysqliteas described in Threading/Pooling Behavior. The pysqlcipher driverhas been observed to be significantly slower on connection than thepysqlite driver, most likely due to the encryption overhead, so thedialect here defaults to using the SingletonThreadPoolimplementation,instead of the NullPool pool used by pysqlite. As always, the poolimplementation is entirely configurable using thecreate_engine.poolclass parameter; the StaticPool maybe more feasible for single-threaded use, or NullPool may be usedto prevent unencrypted connections from being held open for long periods oftime, at the expense of slower startup time for new connections.