`create_async_engine("sqlite+aioturso:///...")` fails on SQLAlchemy
2.0.46 and later:
```python
AttributeError: 'AsyncAdapt_turso_dbapi' object has no attribute 'has_stop'
```
`AioTursoDialect` inherits from SQLAlchemy's `SQLiteDialect_aiosqlite`,
but it wraps connections in SQLAlchemy's generic
`AsyncAdapt_dbapi_connection`, not in the aiosqlite connection class.
SQLAlchemy 2.0.46 added two things to `SQLiteDialect_aiosqlite` that
only work with aiosqlite's DBAPI module and connection class:
- `__init__()` reads `dbapi.has_stop`. It uses the value to decide
whether the pool may call `terminate()` on connections that were
garbage-collected without being returned. `AsyncAdapt_turso_dbapi` has
no `has_stop` attribute, so creating the engine fails.
- `do_terminate()` calls `dbapi_connection.terminate()`. The pool calls
`do_terminate()` when it invalidates a connection, for example after
`conn.invalidate()` or a cancelled query, and when it recycles a
connection. `AsyncAdapt_dbapi_connection` has no `terminate()` method.
The pool logs the `AttributeError` and opens a new connection, but the
old turso connection is never closed and its worker thread keeps
running.
### This PR:
- Sets `has_stop = False` on `AsyncAdapt_turso_dbapi`, because
`turso.aio.Connection` has no `stop()` method. SQLAlchemy then sets
`has_terminate = False` and drops garbage-collected connections without
trying to close them, as it did on 2.0.45.
- Overrides `do_terminate()` on `AioTursoDialect` to call `close()`,
which is what `do_terminate()` did on 2.0.45. The pool calls
`do_terminate()` from inside SQLAlchemy's greenlet, so `close()` can
wait for turso's async close.
- Adds regression tests to `tests/test_sqlalchemy_async.py` for three
cases: creating a file-database engine, running a query and disposing
the engine; invalidating a connection; and cancelling a running query.
The last two tests check that the pool logs no errors and that no turso
worker threads are left after `dispose()`.
Every released pyturso version that includes the async dialect (0.6.0
and later) fails on SQLAlchemy 2.0.46 and later, including 2.1.x.
The SQLAlchemy tests already catch the crash, but CI never runs them:
`.github/workflows/python.yml` only runs the `test_database*.py` files,
and `uv.lock` locks SQLAlchemy at 2.0.45, the last version that works.
This PR does not change the CI workflow. Claude Code (Claude Opus 5.5)
checked the fix against the SQLAlchemy source, wrote the regression
tests and reviewed this description. The tests fail without the fix on
SQLAlchemy 2.0.46, 2.0.54 and 2.1.2, and pass with it on 2.0.45, 2.0.54
and 2.1.2.
Closes#9477
On Windows the Python sync tests took ~5 min per test file, against
~42 s on macOS. The time goes into connections, not work: e.g.
test_bootstrap 10.16 s on Windows vs 0.23 s on macOS, and
test_partial_sync_segment_size (many requests) 122.9 s vs 1.05 s, while
the data-heavy test_pull_bytes_threshold took about the same on both.
The local sync server listens on 0.0.0.0 (IPv4 only), but the tests
connected to "localhost". Windows resolves localhost to ::1 first, and a
refused connection there takes about 2 s before the client falls back to
127.0.0.1, on every new connection. That fits the numbers above; the
Windows CI timings of this change will confirm it.
Connect to 127.0.0.1 directly. The persisted-URL assertion now checks for
the server URL itself instead of the "http://localhost" prefix.
The Python test matrix used versions 3.10 and 3.14 on every run. The configure-strategy job returned those fixed values. The matrix now lists them directly.
Python sync tests need tursodb. CI now builds only that binary with cargo build -p turso_cli --bin tursodb --locked.
Each checkpoint test now commits after four inserts. It still writes 1,024 rows and checks for a WAL larger than 1 MiB.
Tests: The focused tursodb build and all 18 Python sync tests passed. The workflow YAML parsed.
Rebased doc-only version of the earlier #7615. Focuses only on
documentation files (`.mdx`/`.md`) that have no conflict risk — the
source-file changes were dropped since those have diverged on main.
Fixes several `commited` → `committed` and `occured` → `occurred` typos
across the Go/Python bindings docs, the sync server doc, and the
Antithesis README.
Closes#8556
Parameterized batches could produce different effects across embedded and
serverless drivers when a later bind value was invalid. Embedded Rust also
allowed cloned connections to interleave work with a batch, and managed
batches allowed transaction-control statements to escape their wrapper.
Rollback failures were hidden, while serverless Rust could retain a stale
last-insert rowid when COMMIT failed after a successful insert.
Validate every batch input before execution, reject transaction-control SQL
before opening a managed transaction, and hold an operation-wide gate for
embedded Rust batches. Preserve both the primary and rollback errors, and
carry successful statement rowids through serverless batch decoding even
when a synthetic transaction step fails. Reject malformed serverless batch
responses instead of treating incomplete transaction steps as success.
Add Connection.batch(statements, mode=None) to turso (bindings/python,
inherited by the sync driver's ConnectionSync and exposed on the aio
wrapper) and to turso_serverless, with the same signature and semantics
per the driver API parity requirement.
Statements are SQL strings or (sql, parameters) pairs and execute in
order, stopping at the first failure; the raised exception keeps its
DB-API class, prefixes the message with the zero-based statement index,
and carries batch_index and batch_results attributes — the latter with
one entry per statement, so callers can tell exactly which statements
took effect before the failure. A client-side value encoding failure is
reported the same way. With mode set (deferred, immediate, exclusive,
concurrent) the statements are wrapped in BEGIN/COMMIT with a ROLLBACK
on failure for all-or-nothing execution. batch() never opens a legacy
implicit transaction; statements join an already-open transaction, in
which case mode is ignored.
Each statement's BatchResult carries rows, description, rowcount, and
lastrowid, plus the server-side execution statistics rows_read,
rows_written, and query_duration_ms reported by the serverless protocol
(the embedded engine does not report them per statement). The
serverless driver sends the whole batch, including the transaction
wrapper, as a single pipeline request, so a multi-statement
parameterized batch is one HTTP round trip.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The driver learned the rowid of an INSERT by preparing and executing
SELECT last_insert_rowid() after every INSERT/REPLACE — a full extra
statement per insert. Expose the engine's connection-level rowid
through the native module and read it directly. Besides removing the
per-insert overhead, this is needed by the upcoming parameterized batch
API, where a per-statement rowid fetch would otherwise double the
statement count of insert-heavy batches.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
SQLite has lots of variation in behavior across versions. Turso core
already was tracking 3.50.4, but as it turns out, CI and some of the
bindings had different ideas. Fix that to track 3.50.4 consistenty
across the project, and make the version number explicit in README.md
and COMPAT.md
Syncing against an MVCC-mode database requires the sync engine to use
logical-log
pulls, but this was gated behind an opt-in flag (`logical_mvcc_pull`)
that the JS,
Python, Go, and react-native SDKs never exposed. Every SDK client
pulling from an
MVCC database bootstrapped a stale base and then failed with:
```
status=400 "MVCC incremental pull-updates requires stream_kind=mvcc_logical_log"
```
Even after plumbing the flag through, users would have to know their
database's
journal mode and configure the client accordingly/we don't want to force
a client to configure this flag.
The protocol is a property of the server, so the client should learn it
there.
## Solution
The server now advertises its pull protocol in every pull-updates
response.
The engine reads it on first contact and persists it in the sync
metadata:
- New `remote_pull_protocol` field in `DatabaseMetadata`: `unknown`,
`pages`,
or `mvcc_logical`. Old metadata files deserialize to `unknown` and are
migrated on load from the existing `logical_mvcc_pull_active` bool
whenever
the replica already holds a revision.
- `DatabaseSyncEngineOpts.logical_mvcc_pull` is now `Option<bool>`.
`None`
(the new default) auto-detects; `Some(true/false)` forces a protocol
and
remains available in every SDK as an escape hatch.
`Builder::with_logical_mvcc_pull`
keeps its signature.
- For servers that predate the header field, detection falls back to the
shape
of the advertised revision: MVCC revisions contain `log_offset`, WAL
diskless
revisions only `generation`/`wal_fragment_no`.
- A replica created with deferred bootstrap stays `unknown` until its
first
pull; that request is wire-identical to the existing no-revision page
request,
so the response tells us the protocol before any mode-specific
behavior kicks in.
- Partial sync or remote encryption combined with an MVCC remote is now
a hard
error at configuration/detection time.
### Deferred bootstrap ("converted to cloud sync later")
A replica created with deferred bootstrap has already committed to a
local
journal mode before the remote's protocol is knowable. When first
contact
detects an MVCC remote and the local database is still in WAL mode, the
engine now converts it in place with `PRAGMA journal_mode = 'mvcc'`
(core
already implements the full transition for populated databases: WAL
checkpoint, header rewrite, MvStore bootstrap over the existing btree)
before applying the remote base as replace-base. Local changes survive
via
the existing CDC replay, and the conversion is durable across reopens.
Without this, applying an MVCC-headered base into a WAL-mode process
would
leave the file header and the running journal mode disagreeing: the
process
keeps WAL semantics while the next open reads the MVCC header and starts
an
empty MvStore: essentially an uncoordinated journal mode flip across
restarts.
### CDC Guard
also added here: since `replace-base` preserves local data by replaying
the CDC log, so a database file that lived outside
the sync engine (user tables present but an empty CDC log before the
first sync) is rejected with a
descriptive error instead of silently dropping its rows.
Reviewed-by: Nikita Sivukhin (@sivukhin)
Closes#8057
The sync packages (Rust, Python, JavaScript, React Native, Go) only
rewrote libsql:// remote URLs to https://, so turso:// URLs were either
rejected or passed through unmodified and failed at request time. The
serverless packages already accept both schemes; normalize turso:// the
same way in every sync binding so the two URL forms are interchangeable.
Tests: normalize_base_url_schemes in bindings/rust, TestSyncNormalizeUrl
in bindings/go
Reviewed-by: Glauber Costa <glommer@gmail.com>
Closes#8070
This PR addresses a user-reported bug on the Turso user Discord when
using sqlite3.Row as a row factory:
```python
conn.row_factory = sqlite3.Row # assignment succeeds
conn.execute("SELECT * FROM t").fetchone() # Crashes with a TypeError
```
The issue is that Turso calls the configured row factory with a Turso
Cursor, but `sqlite3.Row` only accepts a stdlib `sqlite3.Cursor`. We do
not support mixing database libraries like this. The fix is
straightforward. Detect when `sqlite3.Row` or a subclass is used as a
Turso row factory, and raise an explicit TypeError when rows are
fetched.
Defining a row_factory with `conn.row_factory = sqlite3.Row` is a common
Python pattern users are accustomed to using with Python's standard
library sqlite3 implementation. However, this will not work with
pyturso.
Our _apply_row_factory() method in lib.py returns:
```python
rf(self, Row(self, row_values))
```
If rf has been defined with sqlite3.Row, sqlite3.Row.__new__ performs an
isinstance check on the arguments and discovers that *self* is a
`turso.Cursor` object rather than a `sqlite3.Cursor` and rejects it with
a TypeError.
```bash
>> TypeError: Row() argument 1 must be sqlite3.Cursor, not Cursor
```
This failure path misdiagnoses the real issue: the user is attempting to
use `sqlite3.Row` to define a pyturso row factory. Turso's row class
should be used to create the row_factory instead:
```python
conn.row_factory = turso.Row
```
By emitting our own TypeError instead, the user clearly understands the
correct pattern to use:
```python
if isinstance(rf, type) and issubclass(rf, _stdlib_sqlite3.Row):
raise TypeError("sqlite3.Row is not supported as a row_factory on turso connections; use turso.Row instead")
```
Claude was used to verify the bug, research sqlite3 behavior, write
tests and validate that the code change would not affect other callers.
## Files changed:
- bindings/python/turso/lib.py:844: imports stdlib sqlite3 and rejects
sqlite3.Row subclasses with the explicit TypeError.
- bindings/python/tests/test_database.py:409: adds 3 regression tests.
## Validation:
targeted tests pass:
```bash
uv run pytest bindings/python/tests/test_database.py -k "stdlib_sqlite3_row or turso_row_factory_works"
```
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>
Closes#8056
The sync packages (Rust, Python, JavaScript, React Native, Go) only
rewrote libsql:// remote URLs to https://, so turso:// URLs were either
rejected or passed through unmodified and failed at request time. The
serverless packages already accept both schemes; normalize turso:// the
same way in every sync binding so the two URL forms are interchangeable.
Tests: normalize_base_url_schemes in bindings/rust, TestSyncNormalizeUrl
in bindings/go
Turso is no longer a work-in-progress: it runs in production at
multiple organizations. Align the PyPI description with the README
tagline and bump the development status classifier from Alpha to
Beta.
This PR updates the Turso Python binding's SQLAlchemy dialect to enable
reflection features that Turso now supports, and does some related
housekeeping:
- Remove overrides for table reflection methods that depended on
previously unsupported SQLite PRAGMAs (`foreign_key_list`, `index_list`)
- Move methods duplicated across the three dialect classes into the
central `_TursoDialectMixin` (~50 fewer lines)
- Bump the minimum SQLAlchemy version to >= 2.0.45 and add a guard that
fails with an explicit message on older versions
- Add a deprecation warning when `sync_url` is passed via connection
parameters
- Add test coverage for the newly enabled reflection methods (foreign
keys, indexes, unique and check constraints, and their `get_multi_*`
variants) plus a version-guard regression test
- Update docs: remove redundant sync examples, make the SQLAlchemy
version requirement explicit
When we first introduced SQLAlchemy support, several SQLAlchemy
reflection functions depended on SQLite PRAGMAs that Turso did not
support at the time (`foreign_key_list`, `index_list`). To prevent
errors, we overrode them to return empty results. Subsequent Turso
updates enabled those PRAGMAs, so the overrides are no longer needed and
actively hide real schema information.
We originally pinned SQLAlchemy to 2.0+. Two things now require a higher
floor: async dialect support depends on `AsyncAdapt_dbapi_module` (first
shipped in 2.0.42), and the newly enabled CHECK constraint reflection
depends on a fix for tables with multiple CHECK constraints (shipped in
2.0.45). Testing also showed that older versions fail with confusing
errors about SQLAlchemy internals, so the new guard raises an explicit
message telling users to upgrade.
The first version of the dialect added a shim accepting libsql-style
`sync_url` in place of `remote_url`. Since we may not keep this
indefinitely, the shim now emits a `DeprecationWarning` directing users
to `remote_url`.
Clean-up: each of the three dialect classes had its own identical
`on_connect()`, `get_isolation_level()`, and `set_isolation_level()`
methods; these now live once in `_TursoDialectMixin`. The docs'
duplicated sync examples in Quick Start and Sync Operations are
consolidated into one.
Claude Opus 4.8 and Fable 5 were used to verify which reflection
functions are now supported, assist in generating and reviewing code,
and write tests. All generated code was carefully reviewed.
Closes#7816
0.7 ships next week, and Turso now runs in production at multiple
organizations — the top-of-page "this software is in BETA, use caution
with production data" warning no longer reflects reality, and it's the
first thing every visitor reads.
## What changed
- **About**: the ⚠️ BETA warning blockquote is gone. In its place, a
one-line status note: Turso runs in production today, with a pointer to
the FAQ for where the project stands on the way to 1.0.
- **FAQ "Is Turso Database ready for production use?"**: now opens with
"Yes" and the production users, followed by the testing story (DST,
Antithesis). The honest caveats stay, but softened: not yet 1.0, some
features explicitly experimental, and backups recommended as "the same
discipline you would apply to any database" rather than as a data-loss
threat.
- **New FAQ "How compatible is Turso Database with SQLite?"**: we're not
at 100% yet, COMPAT.md tracks the details, the gap is closing quickly,
and full compatibility is a requirement for 1.0.
- **libSQL FAQ**: still flatly said "libSQL is production ready, Turso
Database is not", contradicting the rest of the page. Now: both run in
production; libSQL is more battle-tested, Turso Database is where
development effort is focused.
The goal is to neither scare nor oversell: no data-loss warning up top,
but the README still says clearly that we are pre-1.0 and that some
SQLite differences remain.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Closes#7735
The sync engine's full_write handler wrote the replica metadata file in
place with open(path, 'wb'), so a concurrent reader (another connection
opening the same replica) could observe an empty or truncated file and fail
with 'meta must be initialized before open' or a deserialization error.
Write to a temp file and os.replace() it over the target, matching the
atomic write the JavaScript binding already does.
Tests: test_concurrent_open_existing_replica (fails on the previous
truncate-in-place write, passes now)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Turso runs in production at multiple organizations, so the "this
software is in BETA, use caution with production data" warning no
longer reflects reality. It appeared in the main README, was
copy-pasted in 11 bindings READMEs (what users see on npm, PyPI, and
pkg.go.dev), and was printed by tursodb at every shell startup.
- README: remove the warning blockquote from About, leaving a one-line
status pointer. Rewrite the production-readiness FAQ to lead with
production use and the testing story, keeping the honest caveats in
softer form: not yet 1.0, some features experimental, keep backups
as with any database. Add a FAQ on SQLite compatibility (gap tracked
in COMPAT.md, closing quickly, required for 1.0), and fix the libSQL
FAQ, which still claimed Turso Database is not production ready.
- bindings READMEs: replace the warning with the same softened status
line, linking to the FAQ.
- cli: remove the startup banner line entirely, matching the SQLite
shell.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The Python SDK held the GIL for the entire duration of query execution
(PyTursoStatement::step/execute/run_io/finalize never released it), so two
Python threads could never be inside the engine at once. That serialized
concurrent reads (~1.0x speedup across threads) even though the engine itself
can run them in parallel, and it made cancellation impossible: a watchdog
thread could not run to abort a slow query.
The core engine already supports cancellation (Connection::interrupt, enforced
in the VDBE step loop) and a native per-statement deadline
(Connection::set_query_timeout); the plumbing just stopped below the SDK.
This wires both through and releases the GIL during execution:
- sdk-kit: expose interrupt() / set_query_timeout() / get_query_timeout() on
rsapi::TursoConnection.
- python binding: wrap step/execute/run_io/finalize in py.detach(...) so other
threads run during query execution; expose interrupt() (stdlib sqlite3 parity)
and set_query_timeout()/get_query_timeout() on PyTursoConnection.
- high-level Connection: interrupt(), set_query_timeout(), get_query_timeout().
interrupt() mirrors sqlite3.Connection.interrupt(); set_query_timeout() is a
Turso extension (SQLite has only busy_timeout + progress_handler) that needs no
watchdog thread.
Now that sdk-kit's rsapi::TursoConnection exposes interrupt() and
set_query_timeout(), the other language SDKs (Rust, Go, Java, JS, .NET) should
expose them too, so cancellation/timeouts are available everywhere. We're doing
Python first to keep this change small and focused; the remaining SDKs can wrap
the same rsapi surface in follow-ups.
Tests: tests/test_interrupt.py asserts a watchdog thread can interrupt a running
query (only possible once the GIL is released), that the query timeout fires,
and that a background Python thread makes progress during a query.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The `fts` cargo feature (which pulls in tantivy) propagated from `core`
to `sdk-kit` but stopped there: `py-turso` depended on `turso_sdk_kit`
without enabling `fts`, so `CREATE INDEX ... USING fts` failed at runtime
even with the `index_method` experimental flag set.
Enable `turso_sdk_kit/fts` in the Python binding so FTS is compiled into
the wheel. Usage is SQL-only and gated at runtime via
`turso.connect(..., experimental_features="index_method")`.
Add three FTS tests to test_database.py (run unconditionally in CI on all
platforms) covering fts_match, fts_score ordering, and fts_highlight.
Using the stable ABI lets one wheel target Python 3.10 and every newer
3.x, replacing the per-minor-version matrix. Drops --find-interpreter
from the release wheel builds so maturin emits one cp310-abi3 wheel per
platform instead of one per interpreter.
This PR converts the Python bindings from the old function-based
`#[pymodule]` style to the new and recommended declarative style.
Also updating `uv.lock` which I forgot to do in
https://github.com/tursodatabase/turso/pull/6103
- The declarative style is less verbose and easier to read
- As seen in https://github.com/PyO3/pyo3/issues/3900 declarative
modules will be the recommended way of using PyO3 and function-based
modules are going to be deprecated, quote:
> Before v0.23 (or later?):
> - [x] Deprecate `#[pyfn]`
> - [ ] **Deprecate "function-based" modules**
- Another quote from one of the PyO3 maintainers
https://github.com/PyO3/pyo3/issues/3900#issuecomment-2010429992
> I agree that imperative modules should be deprecated and replaced
with these modules as soon as possible.
- The docs have also been rewritten to use the declarative style, see
https://github.com/PyO3/pyo3/pull/5430
- Declarative modules are better supported by `experimental-inspect`
(https://github.com/PyO3/pyo3/issues/5137) which I'd like to attempt
using in a future PR for type stub generation.
I've used Claude Code with Opus 4.6 to search through the PyO3 docs and
various GitHub issues and PRs to validate the idea and to make the code
changes to `bindings/python/src/lib.rs`.
Closes#6122
TursoConnection.close() dropped the connection but left outstanding
TursoStatement objects alive. Each statement holds Arc<Connection> ->
Arc<Database> through its inner turso_core::Statement, keeping the Weak
in DATABASE_MANAGER upgradeable. After a file rename, reopening the same
path returned the stale Database.
Fix by tracking every statement handle in TursoConnection and dropping
all inner statements when close() is called. This pushes the fix from
the individual bindings (JavaScript commit 93067cd75) down into the SDK
so all bindings get it for free.
The statement is now wrapped in Arc<Mutex<Option<Statement>>>
(StatementHandle). TursoConnection holds Weak refs to all handles and
sets them to None on close(), breaking the reference chain. All
TursoStatement methods check for the finalized state and return errors
or defaults. finalize() also sets the handle to None after completing
execution.
API changes:
- column_name() returns String instead of Cow<str>
- row_value() returns owned Value instead of borrowed ValueRef
- C API row_value_* functions access the handle directly via macro