84 Commits

Author SHA1 Message Date
Pekka Enberg
5b4b9515fd Merge 'bindings/python: fix sqlite+aioturso on SQLAlchemy 2.0.46 and later' from Orthel Toralen
`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
2026-10-15 11:32:45 +03:00
Jussi Saurio
b46ded716e bindings/python: connect sync tests to the local server over 127.0.0.1
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.
2026-10-14 09:36:51 +03:00
Orthel Toralen
bed7ded346 fix: add .has_stop=False and do_terminate() override for compatibility with SQLAlchemy >= v2.0.46 2026-10-03 20:15:24 -04:00
Jussi Saurio
4616801fce ci: start Python jobs directly and batch checkpoint inserts
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.
2026-09-22 09:27:54 +03:00
PThorpe92
9fe63ac8f0 SDK/drivers: make parameterized batches safe and consistent
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.
2026-08-28 10:40:26 -07:00
Glauber Costa
e29fe1033d add a parameterized batch API to the embedded and serverless Python drivers
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>
2026-08-28 10:40:26 -07:00
Orthel Toralen
be8de4b1ec bindings/python: reject sqlite3.Row row_factory with explicit error 2026-07-27 21:33:39 -04:00
Orthel Toralen
e51acf2932 chore: remove stale doc string. get_foreign_keys() is now supported. 2026-07-13 13:48:19 -04:00
Orthel Toralen
80717b9e0a chore: add guard for unsupported sqlalchemy versions 2026-07-10 23:52:59 -04:00
Orthel Toralen
6eb593063d docs: minor rewording to make doc strings clearer and more concise 2026-07-10 23:52:59 -04:00
Orthel Toralen
345f72fd59 refactor: remove table reflection exclusions for sqlite features now supported by Turso 2026-07-10 23:52:59 -04:00
Glauber Costa
a631e02736 bindings/python: make sync full_write atomic via temp file + rename
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>
2026-07-10 15:13:15 -05:00
Nikita Sivukhin
52d1d6ffec Merge 'propagate push/pull thresholds to the python and golang SDK' from Nikita Sivukhin
Add pull/push thresholds to the Python/Golang sync SDKs:
```py
turso.sync.connect(..., pull_bytes_threshold=t1, push_operations_threshold=t2)
```
```go
db, err := NewTursoSyncDb(context.Background(), TursoSyncDbConfig{
  ...
  PullBytesThreshold: t1,
  PushOperationsThreshold: t2,
})
```

Reviewed-by: Jussi Saurio <jussi.saurio@gmail.com>

Closes #7675
2026-07-03 00:36:00 +04:00
Glauber Costa
5fae0eab44 python: release the GIL and expose interrupt() / set_query_timeout()
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>
2026-06-30 19:26:36 -05:00
Nikita Sivukhin
8d09e9d03d propagate push/pull thresholds to the python and golang SDK 2026-06-30 13:20:45 +02:00
Pekka Enberg
8a625a8470 python: enable Tantivy FTS and add tests
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.
2026-06-09 10:06:34 +03:00
Akira Noda
3c7fd2a94f bindings/python: Add SQLAlchemy asyncio dialect 2026-04-24 13:15:14 +09:00
Akira Noda
bb58bf5322 feat: named parameter support in python binding 2026-04-22 15:00:00 +09:00
Pekka Enberg
e0b306bfd6 Merge 'Add SQLAlchemy dialect for Python bindings' from Orthel Toralen
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
2026-02-27 09:54:53 +02:00
Orthel Toralen
f7b1e21a7b fix: fix linter issues 2026-02-26 04:42:57 -05:00
Orthel Toralen
02a9324fa5 fix: prevent sync server hang and port retry failure on Windows
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>
2026-02-26 02:30:01 -05:00
Orthel Toralen
8729c9cd16 chore: remap sync_url to remote_url for libsql-sqlalchemy compatibility; break up long create_connect_args() function to please the linter 2026-02-25 00:18:06 -05:00
Orthel Toralen
5ff3a9998c test: extend testing suite to cover additional sqlalchemy-dialect cases 2026-02-25 00:18:06 -05:00
Orthel Toralen
9ca8d67694 python: fix SQLAlchemy dialect table reflection for unsupported PRAGMAs
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>
2026-02-25 00:18:06 -05:00
Orthel Toralen
2456098213 python: add SQLAlchemy dialect for pyturso
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>
2026-02-25 00:18:06 -05:00
Pekka Enberg
86bd9684f5 Fix Windows Python sync test failing on reserved ports
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.
2026-02-08 17:04:18 +02:00
Pekka Enberg
bcd4647ce5 Detect sync server process death in Python test health check
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.
2026-02-08 14:23:02 +02:00
Pekka Enberg
3fe9edec53 python: Add timeouts to prevent sync tests from hanging on Windows CI
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().
2026-02-06 14:21:27 +02:00
Avinash Sajjanshetty
4784e784a3 fix python encryption test 2026-01-28 11:27:39 +05:30
Avinash Sajjanshetty
5c59f1e1af Add a simple encryption test in python bindings 2026-01-20 16:55:52 +05:30
Nikita Sivukhin
a70b4a6dd9 Merge branch 'main' into save-sync-configuration 2025-12-26 17:49:21 +04:00
Nikita Sivukhin
28094f4b0b fix python bindings 2025-12-26 17:22:34 +04:00
Preston Thorpe
1704794d0e Merge 'Sdk kit refactoring' from Nikita Sivukhin
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
2025-12-24 17:38:46 -05:00
Nikita Sivukhin
3913206abc fix python test 2025-12-23 15:55:57 +04:00
Nikita Sivukhin
51e162e8cf uv ruff 2025-12-23 15:34:43 +04:00
Nikita Sivukhin
e109b837b0 adjust python bindings 2025-12-23 15:34:43 +04:00
Nikita Sivukhin
8b04ce7235 rename partial_sync_opts to partial_sync_experimental for Python driver 2025-12-22 21:52:11 +04:00
Nikita Sivukhin
fc21324c61 fix test 2025-12-21 15:47:19 +04:00
Nikita Sivukhin
f94f38623d uvx ruff check --fix 2025-12-21 14:29:10 +04:00
Nikita Sivukhin
0270505210 fix exception type 2025-12-21 14:28:52 +04:00
Nikita Sivukhin
1393482f1f add concurrency test in python 2025-12-21 12:10:23 +04:00
Nikita Sivukhin
9326b0c6c0 fix tests 2025-12-19 13:24:26 +04:00
Nikita Sivukhin
9032c61e52 reformat python 2025-12-18 16:39:25 +04:00
Nikita Sivukhin
7fc026d0db add local mode for python and go tests 2025-12-18 16:25:29 +04:00
Nikita Sivukhin
5ab69bcf20 rename speculative load to prefetch (docs already uses this terminology) 2025-12-16 13:59:39 +04:00
Pekka Enberg
df9c39cd1c core: Fix integrity_check pragma code generation
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.
2025-12-15 09:46:46 +02:00
Nikita Sivukhin
f409875c69 adjust python tests a little bit 2025-12-10 18:37:28 +04:00
Nikita Sivukhin
0c73e875eb fix assertion in python test 2025-12-10 18:23:44 +04:00
Nikita Sivukhin
aac3a699ce fix partial sync config after rebase 2025-12-09 16:01:12 +04:00
Nikita Sivukhin
c1ca743503 adjust test 2025-12-09 15:42:29 +04:00