Commit Graph

249 Commits

Author SHA1 Message Date
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
Pekka Enberg
fb7c20bf17 Merge 'Fix documentation typos (committed/occurred)' from KAWACU Kennedy
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
2026-09-01 07:46:10 +03:00
KAWACU Kennedy
a5d2aab705 Fix typo: bindings/python/py-bindings-tests.mdx 2026-08-28 22:51:42 +02:00
KAWACU Kennedy
117091fb05 Fix typo: bindings/python/py-bindings-tests-aio.mdx 2026-08-28 22:51:34 +02:00
KAWACU Kennedy
e104cfd059 Fix typo: bindings/python/py-bindings-db.mdx 2026-08-28 22:51:27 +02:00
KAWACU Kennedy
350dc88af5 Fix typo: bindings/python/py-bindings-db-aio.mdx 2026-08-28 22:51:20 +02: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
Glauber Costa
323a63aef0 bindings/python: read last_insert_rowid from the engine
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>
2026-08-28 10:40:25 -07:00
Pekka Enberg
a644dd43d6 Unify SQLite tracking version to 3.50.4
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
2026-08-18 09:57:57 +03:00
Marc-André Moreau
99f7c34ae5 Expose page codecs through SDK kit ABI
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2026-08-10 13:54:09 +03:00
Preston Thorpe
f6671e7456 Merge 'sync: auto-detect the remote pull protocol' from Preston Thorpe
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
2026-07-28 11:37:10 -07:00
Pekka Enberg
1860dbf046 Merge 'bindings: accept turso:// scheme in sync remote URLs' from Pekka Enberg
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
2026-07-28 17:56:45 +03:00
Mikaël Francoeur
97301801be Merge 'bindings/python: Reject sqlite3.Row when used as a row_factory with an explicit TypeError' from Orthel Toralen
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
2026-07-28 09:12:01 -04:00
Pekka Enberg
8a4e755da1 bindings: accept turso:// scheme in sync remote URLs
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
2026-07-28 15:54:09 +03:00
Mikaël Francoeur
dbac0ced00 load sqlite3 lazily on type errors 2026-07-27 21:52:44 -04:00
Orthel Toralen
be8de4b1ec bindings/python: reject sqlite3.Row row_factory with explicit error 2026-07-27 21:33:39 -04:00
PThorpe92
106cf991fc sync: auto-detect the remote pull protocol 2026-07-27 16:13:28 -07:00
Pekka Enberg
364edf731f bindings/python: update package description and status classifier
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.
2026-07-26 20:12:34 +03:00
Nur
51a152892c Fix: use IoBackend in bindings and tests 2026-07-17 13:53:55 -04:00
Pekka Enberg
b3abdaecf8 Merge 'bindings/python: enable SQLAlchemy reflection now supported by turso, bump min version to 2.0.45' from Orthel Toralen
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
2026-07-14 10:11:37 +03:00
Orthel Toralen
e0bf3e6ce2 chore: remove depreciation warning for sync_url cparam 2026-07-13 13:49:44 -04:00
Orthel Toralen
e51acf2932 chore: remove stale doc string. get_foreign_keys() is now supported. 2026-07-13 13:48:19 -04:00
Pekka Enberg
d115b414ad Merge 'Drop the beta warning' from Glauber Costa
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
2026-07-12 08:52:00 +03:00
Orthel Toralen
80717b9e0a chore: add guard for unsupported sqlalchemy versions 2026-07-10 23:52:59 -04:00
Orthel Toralen
ab63f06384 refactor/docs: moved class meathods that were duplicated for each dialect into the _TursoDialectMixin class. Updated SQLALCHEMY_DIALECT.md to clarify isolation_level paramater reference, consolidated repetive sync examples. 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
0ba8261d64 chore: add deprecation warnings for sync_url -> remote_url shim 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
PThorpe92
57955e6a33 impl sync for mvcc journal mode in sync engine 2026-07-07 09:23:33 -07:00
Glauber Costa
1679062d8c docs: drop the beta warning for 0.7
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>
2026-07-03 10:56:57 -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
Mikaël Francoeur
135ad1f10e general cleanup 2026-07-01 10:03:52 -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
19c8d96bea Update to PyO3 0.29.0 2026-06-15 14:07:33 +03: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
Pekka Enberg
ad37c8c1aa bindings/python: enable PyO3 abi3-py310 for a single cross-version wheel
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.
2026-05-20 16:32:37 +03:00
Nikita Sivukhin
6dd61f571e add pullBytesThreshold option to limit size of initial pull for bootstrap 2026-04-26 19:19:58 +02:00
Nikita Sivukhin
ab28113c56 add optional (for now) param to split push in batches 2026-04-26 18:39:09 +02: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
cf918e1a9e Update pytest to 9.0.3
Fixes CVE-2025-71176 (vulnerable tmpdir handling).
2026-04-17 20:17:24 +03:00
Pekka Enberg
ff3ae4d888 Merge 'Convert Python bindings to declarative PyO3 module syntax' from Kilian Hu
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
2026-03-26 15:29:59 +02:00
Pekka Enberg
92797133ba sdk-kit: Fix Database.close() not finalizing statements
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
2026-03-25 15:32:54 +02:00
Kilian Hu
94006d5757 Convert Python bindings to declarative PyO3 module syntax 2026-03-24 16:29:19 +01:00
Kilian Hu
650f4c61cb bindings/python: upgrade PyO3 to 0.28.2 and maturin to 1.12.6 2026-03-22 21:14:05 +01:00
Kilian Hu
9e5d6de805 chore: drop python 3.9 and add python 3.14 2026-03-18 18:54:23 +01: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