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 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>
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.
This PR adds a SQLAlchemy dialect for pyturso with two connection modes:
- `sqlite+turso://` — local database connections via `turso.connect()`
- `sqlite+turso_sync://` — sync-enabled connections via
`turso.sync.connect()` with `pull()`/`push()` support
This PR adds a SQLAlchemy dialect for pyturso with two connection
modes:
- `sqlite+turso://` — local database connections via `turso.connect()`
- `sqlite+turso_sync://` — sync-enabled connections via
`turso.sync.connect()` with `pull()`/`push()` support
Claude Code provided invaluable assistance in development and
documentation of this PR. Claude assisted in research to close gaps in
my knowledge of SQLAlchemy dialects and DB-API, helped evaluate design
trade-offs between syntactic consistency and correctness, and generated
code and tests once decisions were made. Claude and I also spent
considerable time in chats, imagining the foot-guns developers may
encounter and devising solutions to neutralize them.
## Implementation Details
### Summary of Changes
- **`turso/sqlalchemy/dialect.py`** — `TursoDialect`,
`TursoSyncDialect`, shared `_TursoDialectMixin` for PRAGMA overrides,
and `get_sync_connection()` helper
- **`turso/sqlalchemy/__init__.py`** — public API exports
- **DB-API 2.0 compliance** — added
`sqlite_version`/`sqlite_version_info` to `turso/lib.py`, re-exported
DB-API attributes and exception hierarchy in `turso/sync/__init__.py`
- **Entry points** in `pyproject.toml` for automatic dialect
registration
- **Documentation** — `SQLALCHEMY_DIALECT.md` covering URL formats, sync
operations, architecture, overrides, and limitations
- **74 tests** — unit tests for URL parsing, dialect attributes,
reflection overrides, pool selection, isolation levels; integration
tests for CRUD, ORM, Pandas `to_sql`, transactions, joins, unicode,
error propagation
### Design decisions
- **Inherits from `SQLiteDialect_pysqlite`** — reuses SQLAlchemy's
battle-tested SQLite dialect, overriding only what Turso needs
- **`_TursoDialectMixin`** — Shared mixin overriding reflection
methods that rely on unsupported PRAGMAs (foreign_key_list, index_list)
and sqlite_temp_master. Returns empty results with debug logging instead
of raising errors, preventing MetaData.reflect(), Alembic, and Pandas
df.to_sql(if_exists='replace') from breaking.
- **`on_connect()` returns `None`** — skips pysqlite's REGEXP function
setup since Turso doesn't support `create_function`
- **Isolation level** — `get_isolation_level()` returns SERIALIZABLE,
`set_isolation_level()` is a no-op (set at connection time)
- **Pool selection** — `SingletonThreadPool` for `:memory:`, `QueuePool`
for file databases
- **get_sync_connection()** - A helper function that exposes the
underlying turso_sync connection.
### Test results
| Test Suite | Result |
|------------|--------|
| SQLAlchemy unit/integration | 69 passed, 5 skipped (sync needs
server), 97.5% dialect coverage |
| Existing Python binding tests | 210 passed, no regressions |
| Real-world tests (Turso Cloud/local embedded replicas) | 31 passed —
ORM, Pandas, sync push/pull |
### Files changed
| File | Change |
|------|--------|
| `bindings/python/turso/sqlalchemy/dialect.py` | New — dialect
implementations |
| `bindings/python/turso/sqlalchemy/__init__.py` | New — module exports
|
| `bindings/python/turso/lib.py` | Added `sqlite_version`,
`sqlite_version_info` |
| `bindings/python/turso/__init__.py` | Re-export new version attrs |
| `bindings/python/turso/sync/__init__.py` | Re-export DB-API 2.0 attrs
+ exceptions |
| `bindings/python/pyproject.toml` | Entry points + sqlalchemy optional
dep |
| `bindings/python/tests/test_sqlalchemy.py` | New — 71 tests |
| `bindings/python/SQLALCHEMY_DIALECT.md` | New — documentation |
| `licenses/bindings/python/sqlalchemy-mit-license.md` | New —
SQLAlchemy MIT license |
| `NOTICE.md` | Added SQLAlchemy dependency entry |
### Usage
```python
from sqlalchemy import create_engine, text
# Local / in-memory
engine = create_engine("sqlite+turso:///:memory:")
# Sync (connect_args — familiar to libsql-sqlalchemy users. We accept sync_url as well for compatibility)
engine = create_engine(
"sqlite+turso_sync:///local.db",
connect_args={
"remote_url": "https://your-db.turso.io",
"auth_token": "your-token",
}
)
# Sync (URL query parameters)
engine = create_engine(
"sqlite+turso_sync:///local.db"
"?remote_url=https://your-db.turso.io"
"&auth_token=your-token"
)
# Access sync operations
from turso.sqlalchemy import get_sync_connection
with engine.connect() as conn:
sync = get_sync_connection(conn) # Unwraps the underlying turso.sync connection
sync.pull()
result = conn.execute(text("SELECT * FROM users"))
conn.commit()
sync.push()
```
Closes#5590
Two fixes for Windows-specific sync test failures observed in CI run
58479384622:
1. Add 30-second read timeout to sync server TCP connections
(cli/sync_server.rs). The server handles connections sequentially;
without a timeout, a stalled TCP connection blocks read() indefinitely,
starving subsequent connections. Reproduced on Windows 11: without
the fix tests hang; with the timeout all 9 sync tests pass (277s
as timeouts fire and recover). Linux is unaffected due to cleaner
TCP teardown.
2. Add Windows WSAEADDRINUSE (os error 10048) to the port retry check
in tests/utils.py. Windows reports this error code instead of the
Unix "address already in use" string when a port is still in
TIME_WAIT.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Turso doesn't support PRAGMA foreign_key_list and PRAGMA index_list,
which SQLAlchemy uses for table reflection. This caused errors when
using Pandas df.to_sql() with if_exists='replace'.
Add _TursoDialectMixin that overrides reflection methods to return
empty results instead of executing unsupported PRAGMAs:
- get_foreign_keys() / get_multi_foreign_keys()
- get_indexes() / get_multi_indexes()
- get_unique_constraints() / get_multi_unique_constraints()
- get_check_constraints() / get_multi_check_constraints()
Foreign keys and indexes still work at runtime, they just can't be
introspected through SQLAlchemy's inspector.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implement SQLAlchemy integration with two dialects:
- sqlite+turso:// for basic local database connections
- sqlite+turso_sync:// for sync-enabled connections with remote support
The dialects extend SQLiteDialect_pysqlite and provide:
- URL parsing for connection arguments
- get_sync_connection() helper for accessing pull/push/checkpoint/stats
- Statement caching support
- Proper isolation level handling
Also adds sqlite_version and sqlite_version_info to turso module
for SQLAlchemy compatibility checks.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
On Windows, randomly chosen ports can land in OS-reserved ranges
(Hyper-V, WinNAT), causing "os error 10013" (permission denied).
Retry server startup with a different port up to 5 times when a
port-binding error is detected.
The health check loop polled the HTTP endpoint for 30s without ever
checking whether the server process was still alive. If the server
crashed on startup (e.g. port collision), the test silently burned
the full timeout getting "connection refused" before reporting a
useless error.
Check process liveness each iteration so we fail immediately with
the actual exit code and stderr output.
The test_bootstrap_concurrency test hangs indefinitely on Windows because
multiprocessing.Barrier.wait() and Process.join() have no timeouts. Also
add a 30s deadline to the TursoServer startup wait loop and per-request
timeouts to requests.get().
This PR adds few missing methods to the SDK-KIT which will be necessary
for rust bindings and also propagate more config parameters which
includes VFS and encryption opts
Encryption opts must be set with `experimental_features: "encryption"`
in order to be used.
Also, this PR refactors rsapi of the sdk-kit to be more rust idiomatic
and ergonomic.
Reviewed-by: Avinash Sajjanshetty (@avinassh)
Closes#4336
The translate_integrity_check function was missing a call to
add_pragma_result_column, causing num_columns() to return 0.
This made the Python bindings treat it as a non-row-returning
statement, finalizing it during execute() and leaving fetchone()
to return None instead of ("ok",).
Spotted by Antithesis.