Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python SQLite libraries read and write SQLite database files from Python code, beyond the sqlite3 module in the standard library. A library either adds an ORM or query layer or exposes the SQLite C API more directly than the standard module does. These libraries let desktop apps, test suites, and AI agents keep structured local data without a database server.
Popularity
SQLAlchemy has the most monthly downloads in this comparison, at 417.4M, a count that covers all its database work.
from sqlalchemy import create_engine, text
engine = create_engine("sqlite+pysqlite:///:memory:")
with engine.connect() as connection:
print(connection.execute(text("SELECT 1")).scalar())
def begin_sqlite_stmt(self, conn: sa.Connection) -> None:
# emit our own BEGIN # requires `begin_sqlite_conn` # see https://docs.sqlalchemy.org/en/20/dialects/sqlite.html#serializable-isolation-savepoints-transactional-ddl mode = SQLITE_BEGIN_MODE.get()
if mode is not None:
conn.exec_driver_sql(f"BEGIN {mode}")
aiosqlite
Bridges asyncio code to the standard sqlite3 module.
async def setup(self) -> None:
"""Set up the checkpoint database asynchronously.
This method creates the necessary tables in the SQLite database if they don't
already exist. It is called automatically when needed and should not be called
directly by the user.
"""
async with self.lock:
if self.is_setup:
return
await _ensure_connected(self.conn)
async with self.conn.executescript(
"""
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS checkpoints (
thread_id TEXT NOT NULL,
checkpoint_ns TEXT NOT NULL DEFAULT '',
checkpoint_id TEXT NOT NULL,
parent_checkpoint_id TEXT,
type TEXT,
checkpoint BLOB,
metadata BLOB,
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
);
CREATE TABLE IF NOT EXISTS writes (
thread_id TEXT NOT NULL,
checkpoint_ns TEXT NOT NULL DEFAULT '',
checkpoint_id TEXT NOT NULL,
task_id TEXT NOT NULL,
task_path TEXT NOT NULL DEFAULT '',
idx INTEGER NOT NULL,
channel TEXT NOT NULL,
type TEXT,
value BLOB,
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
);
"""
):
await self.conn.commit()
# sqlite has no ADD COLUMN IF NOT EXISTS; this migrates databases # created before `task_path` existed and is a no-op on the rest. try:
await self.conn.execute(
"ALTER TABLE writes ADD COLUMN task_path TEXT NOT NULL DEFAULT ''"
)
await self.conn.commit()
except aiosqlite.OperationalError as e:
# A read-only database from before the column can still be read; # its rows would all read back as '' anyway. if "readonly database" in str(e):
self._has_task_path = False
elif "duplicate column name" not in str(e):
raise
self.is_setup = True
Peewee
Maps Python models and query expressions to SQLite tables and SQL.
Downloads / mo
42.4M
Stars
12.0K
Last release
4.5.3
License
MIT
Strengths
Models express related SQLite tables.Declare model fields and foreign keys for related records.
Configures SQLite connection pragmas.Set journal mode and foreign-key enforcement when constructing SqliteDatabase.
Limitations
Async SQLite needs another driver.Install aiosqlite when using AsyncSqliteDatabase.
In-memory async databases share connections.Pool size does not add connections to an in-memory database.
def initialize_dataset(filename):
dataset_kw = {}
if peewee_version >= (3, 14, 9):
dataset_kw['include_views'] = True
if dataset_config['read_only']:
if peewee_version < (3, 5, 1):
die('Peewee 3.5.1 or newer is required for read-only access.')
db = SqliteDatabase('file:%s?mode=ro' % filename, uri=True)
try:
db.connect()
except OperationalError:
die('Unable to open database file in read-only mode. Ensure that '
'the database exists in order to use read-only mode.')
db.close()
else:
db = SqliteDatabase(filename)
if dataset_config['foreign_keys']:
db.pragma('foreign_keys', True, permanent=True)
if dataset_config['extensions']:
# Load extensions before performing introspection. for ext in dataset_config['extensions']:
db.load_extension(ext)
if dataset_config['startup_hook']:
dataset_config['startup_hook'](db)
dataset = SqliteDataSet(db, **dataset_kw)
dataset.ensure_cache()
dataset.close()
return dataset
def _backup_database(self, path: str, name: str, extra_sql: str = '', num_of_retries: int = 10, busy_timeout: float = 60) -> None:
for retry_count in range(num_of_retries):
try:
with closing(apsw.Connection(path)) as dest_db:
with dest_db.backup('main', self.conn, name) as b:
busy_since = None
while not b.done:
try:
b.step(128)
except apsw.BusyError as e:
# Locks on some filesystems such as SMB/CIFS # shares never succeed, so dont retry forever now = time.monotonic()
if busy_since is None:
busy_since = now
elif now - busy_since > busy_timeout:
raise apsw.BusyError(
f'Could not lock the database at {path} for {busy_timeout} seconds.'
' The filesystem it is on probably does not support file locking.'
) from e
time.sleep(0.05)
else:
busy_since = None
if extra_sql:
dest_db.cursor().execute(extra_sql)
return
except apsw.IOError as e:
# backup step() can fail transiently, either with # SQLITE_IOERR_SHORT_READ when the source database is modified # while it is being read, or with a plain SQLITE_IOERR and no # error message set on the connection, which apsw reports as # "not an error". Once step() fails the backup object is dead, # so restart the entire backup. Any other extended result code # is a genuine I/O error, and is not retried. if retry_count >= num_of_retries - 1 or getattr(e, 'extendedresult', None) not in (apsw.SQLITE_IOERR, apsw.SQLITE_IOERR_SHORT_READ):
raise
with suppress(OSError):
os.remove(path)
time.sleep(0.2)
sqlite-utils
Provides Python APIs and command-line tools for manipulating SQLite data and schemas.
Downloads / mo
1.1M
Stars
2.2K
Last release
4.2.1
License
Apache-2.0
Strengths
Creates tables when inserting records.Insert dictionaries without separately declaring the table first.
Registers Python SQL functions.Register a Python function for use inside SQL queries.
Limitations
Write calls commit separately.Use db.atomic when several writes must succeed or fail together.
The standard library's sqlite3 module covers direct SQL. SQLAlchemy and Peewee suit applications that want an ORM over SQLite. aiosqlite suits asyncio code. APSW suits code that needs the full SQLite C API, such as online backups.
Peewee is a small ORM with models, queries, and SQLite database helpers. It also has a separate asyncio API.
The sqlite3 module exposes SQLite through the standard library. It ships with Python and needs no install.
SQLModel defines database tables as Pydantic-backed model classes that work with SQLAlchemy.
aiosqlite is an asyncio bridge to the standard sqlite3 module. It runs database operations on a dedicated worker thread per connection. Code awaits each result.
APSW is a Python wrapper for the SQLite C API, with incremental backups and built-in async operation.
For coding agents
Found your SQLite library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.