Metadata-Version: 2.4
Name: turbosqlite
Version: 0.1.0
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Framework :: AsyncIO
Classifier: Topic :: Database
License-File: LICENSE-MIT
License-File: LICENSE-APACHE
Summary: Fast SQLite for Python: a Rust core with SQLite compiled in, sync and asyncio APIs
Keywords: sqlite,async,asyncio,database,rust
Author: 4thel00z
License-Expression: MIT OR Apache-2.0
Requires-Python: >=3.12
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/4thel00z/turbosqlite
Project-URL: Issues, https://github.com/4thel00z/turbosqlite/issues
Project-URL: Repository, https://github.com/4thel00z/turbosqlite

<p align="center">
  <img src="https://raw.githubusercontent.com/4thel00z/turbosqlite/main/assets/logo.svg" width="128" height="128" alt="turbosqlite logo">
</p>

<h1 align="center">turbosqlite</h1>

<p align="center">
  <strong>Fast SQLite for Python. A Rust core with SQLite compiled in, sync and asyncio APIs, and a RAM-first mode whose commits take under a microsecond.</strong>
</p>

<p align="center">
  <a href="https://github.com/4thel00z/turbosqlite/actions/workflows/ci.yml"><img src="https://github.com/4thel00z/turbosqlite/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://pypi.org/project/turbosqlite/"><img src="https://img.shields.io/pypi/v/turbosqlite" alt="PyPI"></a>
  <img src="https://img.shields.io/badge/python-3.12%2B-3776AB?logo=python&logoColor=white" alt="Python 3.12+">
  <img src="https://img.shields.io/badge/rust-2021-000000?logo=rust&logoColor=white" alt="Rust 2021">
  <img src="https://img.shields.io/badge/sqlite-3.53.1-003B57?logo=sqlite&logoColor=white" alt="SQLite 3.53.1">
  <img src="https://img.shields.io/badge/asyncio-native-teal" alt="asyncio native">
  <a href="#license"><img src="https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg" alt="MIT OR Apache-2.0"></a>
</p>

<p align="center">
  <a href="#usage">Usage</a> ·
  <a href="#asyncio">asyncio</a> ·
  <a href="#ram-first-mode">RAM-first mode</a> ·
  <a href="#benchmarks">Benchmarks</a> ·
  <a href="#development">Development</a>
</p>

---

Python's SQLite bindings spend most of each call outside SQLite: building cursors, converting rows through generic paths, and, for asyncio, hopping to a thread and back for every statement. turbosqlite removes that overhead. SQLite 3.53.1 is compiled into the extension with tuned flags, rows are built directly through the CPython API, prepared statements are cached per connection, and the asyncio API runs cheap statements on the event loop thread instead of a worker.

## Highlights

- **3–5× faster than `sqlite3`, about 2× faster than apsw** on point reads, 1000-row scans and bulk inserts, with the same pragmas on both sides ([benchmarks](#benchmarks)).
- **asyncio without a thread hop per call**: a read that finishes within 50 µs runs inline on the loop thread. Point reads take 0.94 µs against aiosqlite's 83 µs.
- **RAM-first mode**: the database lives in memory, a commit returns in under 1 µs, and `await db.durable()` resolves once a background thread has written the commit to disk. Commits that arrive together share one sync.
- **Crash-tested recovery**: the page log is checksummed, a torn tail is cut off, and a test kills the process with SIGKILL during log writes and checkpoints, then checks that every commit acknowledged by `durable()` is still there.
- **`close()` waits for the disk**: it commits a transaction left open and returns only after every commit is on disk, in both modes. `with` and `async with` blocks roll back instead when they exit on an exception.
- **Cancellation interrupts the statement**: cancelling the awaiting task stops SQLite within a thousand VM instructions; the worker does not keep running the query.
- **SQLite compiled in**: same version everywhere, FTS5 and math functions enabled, no dependency on the system library.

## Install

```bash
pip install turbosqlite        # import turbosqlite
```

Wheels cover CPython 3.12–3.14 on Linux (glibc and musl, x86_64 and aarch64) and macOS (arm64 and x86_64). Windows is not supported. To build from source you need [uv](https://docs.astral.sh/uv/) and a Rust toolchain:

```bash
git clone https://github.com/4thel00z/turbosqlite && cd turbosqlite
make sync       # venv plus dev tools
make develop    # build the extension into the venv
```

## Usage

```python
import turbosqlite

with turbosqlite.connect("app.db") as db:
    db.execute("create table if not exists users(id integer primary key, name text)")
    db.run("insert into users(name) values (?)", ("ada",))      # 1, the changed-row count
    db.many("insert into users(name) values (?)", [("grace",), ("linus",)])

    by_id = db.prepare("select id, name from users where id = ?")
    by_id.one((1,))        # (1, 'ada'), or None when there is no row
    by_id.value((1,))      # 1, the first column only
    db.all("select * from users where name like :p", {"p": "a%"})   # [(1, 'ada')]
```

Every query method takes the SQL and optional parameters, a sequence for `?` or a mapping for `:name`, and returns plain Python values:

| Method | Returns |
|---|---|
| `one(sql, params)` | the first row as a tuple, or `None` |
| `value(sql, params)` | the first column of the first row, or `None` |
| `all(sql, params)` | every row, as a list of tuples |
| `run(sql, params)` | the number of changed rows |
| `many(sql, rows)` | runs once per parameter set, returns the total changed rows |
| `execute(script)` | runs one or more statements without parameters |
| `prepare(sql)` | a `Statement` with the same methods, minus the SQL argument |
| `durable()` | waits until every commit so far is on disk |
| `close()` | commits an open transaction, then closes once every commit is on disk |

Methods that take SQL text reuse a cached prepared statement, so `db.one(sql, ...)` in a loop costs about the same as a `Statement`. Connections also expose `last_rowid`, `total_changes` and `in_transaction`. Errors are `SqliteError` and its subclasses `IntegrityError`, `BusyError` and `InterruptedError`.

`connect(path, *, exclusive=True, timeout=5.0, ram=False, commit_on_close=True)` opens file databases in WAL mode with `synchronous=normal`, exclusive locking, a large page cache and memory-mapped reads. Pass `exclusive=False` to share the file with other processes; a locked database is retried for `timeout` seconds before `BusyError`.

## asyncio

```python
async with turbosqlite.connect_async("app.db") as db:
    row = await db.one("select * from users where id = ?", (1,))
    rows = await asyncio.gather(*(db.one("select name from users where id = ?", (i,)) for i in range(100)))
```

`AsyncConnection` has the same methods as `Connection`; each returns an awaitable future.

- A read-only statement runs on the event loop thread when the connection is idle and finishes within 50 µs. A statement that exceeds the budget is stopped, moved to the worker, and stays there.
- Writes to a file database and slower statements run on the connection's own worker thread, in submission order.
- Finished results wake the loop through one pipe write per batch of completions, not one per future.
- Cancelling the awaiting task interrupts the running statement.

`connect_async(path, *, exclusive=True, timeout=5.0, inline=True, ram=False, commit_on_close=True)`; `inline=False` sends every statement to the worker.

## RAM-first mode

```python
async with turbosqlite.connect_async("app.db", ram=True) as db:
    await db.run("insert into users(name) values (?)", ("ada",))   # returns once in RAM
    await db.durable()                                              # returns once on disk
```

The database file is loaded into memory. A commit returns as soon as it is in RAM. A background thread appends the pages each commit wrote to `app.db-ramlog`, batching commits that arrive within 10 ms into one write and one sync. `durable()` waits until every commit made so far is on disk; calling it once after many commits makes them durable for the cost of a single sync. In asyncio, autocommit writes also run inline on the loop thread, because a commit no longer waits for the disk.

Opening the database replays the log. Closing it, or letting the log pass 64 MiB, writes the log back into `app.db`, which stays an ordinary SQLite database that any other tool can open.

<details>
<summary><strong>Recovery, and the limits of RAM-first mode</strong></summary>

How the log stays safe:

- Every record carries a CRC-32 and a sequence number. Replay stops at the first torn or out-of-order record and cuts the log back to the last valid one.
- The log header records the database file's length and a checksum of its first 100 bytes. If the file was changed by something else since the log was written, opening it fails instead of replaying the log over newer data.
- A checkpoint appends and syncs a marker before it writes the database file, so recovery can finish a checkpoint that was interrupted.
- An `flock` on the log keeps a second process from opening the same database in RAM-first mode.

Limits:

- The whole database lives in RAM. While it grows, the copy can briefly take twice its size.
- One process owns the database while it is open. The `exclusive` option has no effect.
- Commits not yet covered by `durable()` can be lost in a crash: up to 10 ms of them, plus the time a sync takes.
- Every commit logs whole 4 KiB pages, even for a one-row change.
- Nothing slows commits down when they outpace the disk.
- Recovery and checkpoints read the whole log into memory.

</details>

### Durability and closing

`durable()` uses `F_FULLFSYNC` on macOS, which flushes the drive's own cache, and `fdatasync` elsewhere. On a database that is not RAM-first it runs a WAL checkpoint synced the same way.

`close()` commits a transaction left open, then returns once every commit is on disk, as if `durable()` ran first. With `commit_on_close=False` it rolls that transaction back instead. If the commit fails, for example on a deferred foreign key, `close()` raises (`IntegrityError`), rolls back, and closes the connection anyway. The async close also waits for writes still queued on the worker.

`with connect(...) as db:` and `async with connect_async(...) as db:` close on exit. Leaving the block normally commits an open transaction according to `commit_on_close`; leaving it because of an exception always rolls it back, as `sqlite3`'s context manager does. A connection that is garbage collected without `close()` behaves like `close()`, but any error is lost.

## Benchmarks

Apple M3 Pro, macOS 27.2, CPython 3.12. Each number is the best of several runs, in µs per operation; lower is better. Every comparison uses the same pragmas on both sides unless a row says otherwise. Reproduce with `make bench`.

**Sync, file database in WAL mode** (`benchmarks/bench.py`)

| library | point read | scan 1000 rows | insert, per row |
|---|---:|---:|---:|
| sqlite3, stock settings | 4.19 | 390.1 | 0.646 |
| sqlite3, matched | 1.98 | 381.7 | 0.661 |
| apsw, matched | 1.06 | 185.1 | 0.341 |
| **turbosqlite** | **0.59** | **84.8** | **0.163** |

**asyncio, file database in WAL mode** (`benchmarks/bench_async.py`)

| library | point read | 1000 gathered reads, per read | scan 1000 rows | insert + commit |
|---|---:|---:|---:|---:|
| aiosqlite | 83.04 | 49.00 | 437.2 | 63.95 |
| **turbosqlite** | **0.94** | **1.21** | **117.3** | **27.99** |

**Commits** (`benchmarks/bench_ram.py`)

| setup | sync commit | asyncio commit |
|---|---:|---:|
| sqlite3, `synchronous=off`, journal in memory | 4.11 | |
| apsw, `synchronous=off`, journal in memory | 3.26 | |
| aiosqlite, `synchronous=off`, journal in memory | | 31.41 |
| **turbosqlite `ram=True`** | **0.92** | **1.27** |

**Commits on disk**, flushed with `F_FULLFSYNC`

| setup | µs per commit |
|---|---:|
| sqlite3, `synchronous=full`, each commit synced | 2168 |
| turbosqlite `ram=True`, `durable()` after each commit | 2807 |
| **turbosqlite `ram=True`, 10,000 commits then one `durable()`** | **2.06** |

A commit that must be on disk before the next one starts is bound by the drive's flush, and turbosqlite is no faster there. The gain comes from many commits sharing one sync.

## How it works

- **SQLite compiled in** with `SQLITE_THREADSAFE=2` (no per-call mutexes; each connection is serialized by its owner), `DEFAULT_MEMSTATUS=0`, and deprecated and shared-cache code left out.
- **Rows built directly**: tuples, ints, floats, strings and bytes are created with CPython API calls straight from SQLite's column buffers. Text and blob parameters are bound without a copy.
- **Statement cache**: every connection keeps its prepared statements, so SQL text is parsed once.
- **Inline asyncio**: a progress handler enforces the 50 µs budget for statements on the loop thread and checks the cancellation flag for statements on the worker.
- **RAM-first VFS**: a custom SQLite VFS keeps the main database file in memory and records each commit's dirty pages when SQLite signals the end of the commit (`SQLITE_FCNTL_COMMIT_PHASETWO`). Every other file goes to the default VFS.

## Development

```console
$ make help

Setup
  sync            Create the venv and install the dev tools (maturin, pytest, apsw, aiosqlite)

Build
  develop         Build the extension with optimizations into the venv
  develop-debug   Build the extension unoptimized, for quicker rebuilds
  wheel           Build a release wheel into target/wheels
  build           Compile the Rust workspace
  clean           Remove build artifacts and caches

Checks
  fmt             Format all crates
  fmt-check       Fail on unformatted code, changing nothing
  lint            rustfmt check plus clippy with warnings denied
  test-rs         Run the Rust unit tests (page log format)
  test-py         Build, then run the Python tests (sync, asyncio, RAM-first, crash recovery)
  test            Run every test
  ci              Everything a pull request has to pass, in order

Benchmarks
  bench           Run every benchmark against sqlite3, apsw and aiosqlite
  bench-sync      Sync point reads, scans and commits against sqlite3 and apsw
  bench-async     asyncio reads and commits against aiosqlite
  bench-ram       RAM-first commits and durable() against every binding
```

The workspace has two crates: `turbosqlite-core` (SQLite build, connection handles, RAM-first VFS and page log) and `turbosqlite-py` (the pyo3 extension). Production Rust code denies `unwrap`, `expect` and `panic` through workspace lints.

CI runs `make lint` and `make test` on Linux x86_64, Linux aarch64 and macOS for Python 3.12, 3.13 and 3.14. To release, bump `version` in `pyproject.toml`, then push a matching tag (`git tag v0.1.0 && git push origin v0.1.0`). The release workflow builds the wheels and the sdist, attests them, and uploads them to PyPI through trusted publishing, so no PyPI token is stored anywhere.

## License

Licensed under either of [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option.

