Adds the missing `reconnect(): void` method to the
`@tursodatabase/serverless/compat` client.
The method resets the closed state, closes the previous session
asynchronously, and replaces it with a fresh lazy Session.
Also adds regression coverage for reconnecting after `close()` and
reconnecting an already active client.
`@tursodatabase/serverless/compat` is intended to provide compatibility
with the `@libsql/client` Client interface, but it was missing
`reconnect()`.
This prevented the compat client from being a complete drop-in
replacement and meant a closed client could not be restored for further
use.
Fixes#8451
AI was used as an assistant during repository exploration,
implementation planning, and test development. The implementation and
resulting diff were reviewed and validated manually.
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Closes#8507
esbuild 0.27.7 falls in the range GHSA-g7r4-m6w7-qqqr names, so the
lockfile shipped a version that can read arbitrary files when its
development server runs on Windows. Nothing here starts that server --
tsup only uses the build API -- but the package should not carry a
flagged version.
tsup 8.5.1 is the newest release and asks for esbuild ^0.27.0, which
cannot reach a fixed version on its own: within that range only 0.27.0
through 0.27.2 are unaffected, and those are older than what is locked.
An override lifts esbuild past the range instead of downgrading it. tsup
builds against 0.28.2 without complaint and emits byte-identical output.
Tests: npm ci; npm run build (dist hashes unchanged from the 0.27.7
build); npx ava integration-tests/protocol.test.mjs; npm audit reports no
vulnerabilities.
Ever since the libSQL days, the batch API has had the same complaint:
you
could not get the result of each individual statement, and when a batch
failed you could not tell which statement failed — or what had already
taken effect. With Turso we have a blank slate, and it turns out the
protocol never was the limitation: a batch response carries complete
per-statement information (results, last insert rowid, error codes, and
the execution statistics `rows_read`, `rows_written`,
`query_duration_ms`; PROTOCOL.md §6.2, §8.4, §9.1). The drivers just
dropped it. This PR takes the opportunity to do it right.
Every driver now exposes one `batch()` API that returns everything the
protocol reports, per statement, in one HTTP round trip:
- **Per-statement results**: rows, affected row count, last insert
rowid, and the server-side execution statistics.
- **Failure visibility**: statements execute in order and stop at the
first failure; the error identifies the failing statement by index
*and* carries one entry per statement — the completed statement's
result, or null/None for the failing statement and the ones that never
ran. In a non-atomic batch the completed statements are committed, and
the caller can finally see exactly what took effect.
- **Atomic mode**: the transactional variant wraps the statements in
`BEGIN <mode>` / `COMMIT` with a conditional `ROLLBACK`, carried by
the
same single request.
Per driver:
- **JavaScript** (`serverless/javascript`, existing public API —
extended
compatibly): each `ResultSet` gains `lastInsertRowid`, `rowsRead`,
`rowsWritten`, `queryDurationMs`; the thrown `DatabaseError` gains
`batchIndex` and `batchResults`. `batch()` moves from the cursor
endpoint to a pipeline batch request because the cursor stream's
`step_end` does not carry the statistics. Non-atomic batches are now
gated on the previous statement succeeding — previously statements
after a failure kept executing server-side.
- **Rust** (new API, `bindings/rust` + `serverless/rust` in one commit
per the driver-parity rule): `Connection::batch` /
`Connection::transactional_batch`,
`BatchStatement`/`IntoBatchStatement`
inputs, `BatchResult` with stats accessors, and
`Error::BatchStatementFailed { index, error, results }`. The sync
driver shares the embedded `Connection`, so all three backends expose
the same API.
- **Python** (new API, `bindings/python` + `serverless/python` in one
commit): `Connection.batch(statements, mode=None)` on the DB-API
surface (sync, aio, and the sync-database driver via inheritance),
raising the classified DB-API exception with `batch_index` and
`batch_results` attributes.
The parity requirement itself is codified first, in
`serverless/conformance/differential/README.md` ("Driver API parity")
with a pointer from the AGENTS.md core principles.
**Deliberately skipped: Go.** The Go serverless driver is a plain
`database/sql` driver, and `database/sql` has no batch surface, so it is
less obvious what to do there: libsql-client-go's precedent is splitting
multi-statement SQL client-side (with a vendored ANTLR SQLite parser)
inside `Exec`, while the alternative is a driver-specific `Batch` API
outside the standard interface. That trade-off deserves its own
discussion and PR.
The batch behavior is property-tested: a `param_batch` operation in the
shared differential vocabulary (`spec/ops.json`) generates 1-4
parameterized statements — including planted failures and atomic modes —
and all three language harnesses (fast-check, hypothesis, hegel) assert
that the embedded and serverless drivers agree on every statement's
result, the failing index, and the partial results carried by the error.
Building those harnesses caught two real driver bugs before the tests
ever ran: the embedded JS driver had no batch error surface at all, and
the embedded Rust driver reported the connection's stale change counter
for row-returning statements inside a batch.
Follow-ups, out of scope here:
- Whether the JS `compat` (libsql-compat) layer should surface the new
per-statement `ResultSet` fields on success; it is kept libsql-shaped
here (the error path does preserve `batchIndex`/`batchResults`).
- Driver-wide preservation of `extended_code` on errors (today only the
Python serverless `ServerError` keeps it).
- A batch entry containing multi-statement SQL ("a; b") errors on the
embedded drivers but the server prepares only the first statement — an
embedded/serverless divergence worth its own discussion.
Also rides along in the JS commit: four env-gated integration tests
still
asserted positional access on expanded rows, which f52724d45 removed on
purpose; CI never runs those tests, so they had drifted.
Tested against a live libsql-server and against Turso Cloud: Rust 44
unit + 58 conformance tests plus the hegel parity property, Python 73
serverless + 236 embedded plus the hypothesis parity property,
JavaScript 42 integration tests plus the fast-check parity property, and
protocol-level coverage asserting a parameterized multi-statement batch
in a single pipeline POST.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Closes#8535
Refresh tar, brace-expansion, and js-yaml to fixed versions in the serverless package and differential test locks.
Tests: npm ci --ignore-scripts; npm run build; npx ava integration-tests/protocol.test.mjs; npm audit --package-lock-only
Co-authored-by: pedro muniz <pedro.muniz.carlo@gmail.com>
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.
State the parity requirement in the serverless differential conformance
spec — each serverless driver exposes the same public API as its
language's embedded driver, and non-JavaScript serverless drivers track
the JavaScript driver's capabilities — and reference it from the
AGENTS.md core principles.
Add the param_batch operation to the shared vocabulary (spec/ops.json,
documented in operations.md) and implement it in the JavaScript,
Python, and Rust harnesses: 1-4 statements through the batch() API —
parameterized INSERTs drawing from the adversarial value pool, SELECTs,
and statements from error_sqls — optionally atomic via a mode of
deferred or immediate. The embedded and serverless drivers must agree
on every statement's result; on failure they must agree on the failing
statement's index and on the per-statement results carried by the
error, entry by entry. An agreed batch failure leaves well-defined
state, so the harnesses keep comparing later operations — that is what
catches an atomic batch that reports the right index but fails to roll
back. The server-side execution statistics are excluded from the
comparison: the serverless driver reports them and the embedded driver
does not, by design.
The embedded drivers execute a batch as a sequential loop that stops at
the first error, so the comparison is the oracle for the serverless
batch: one pipeline request must behave exactly like sequential
execution that stops at the first failure.
The Rust generator fails the suite deterministically, with an
actionable message, when ops.json contains an operation it does not
implement, instead of panicking mid-case on an unknown id.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The protocol reports complete per-statement information for a batch —
results, last insert rowid, error codes, and the execution statistics
rows_read, rows_written, and query_duration_ms — but batch() dropped
most of it. Extend the batch API compatibly, in the serverless driver
and in the embedded driver (@tursodatabase/database, whose
DatabasePromise is shared by the wasm and sync drivers), per the driver
API parity requirement:
- Each ResultSet also carries lastInsertRowid, plus rowsRead,
rowsWritten, and queryDurationMs on the serverless driver (the
embedded engine does not report those per statement). The
lastInsertRowid key is present only on entries whose statement
inserted, so `"lastInsertRowid" in resultSet` detects an insert.
- The serverless batch() uses a pipeline batch request instead of the
cursor endpoint, because the cursor stream does not carry the
statistics, and gates each statement on its predecessor succeeding,
so execution stops at the first failure instead of running the
remaining statements against a failed batch — the embedded driver's
sequential semantics.
- The thrown error carries batchIndex (the zero-based index of the
failing statement) and batchResults (one entry per statement: the
completed statement's ResultSet, or null for the failing and skipped
ones; empty when a bind value fails to encode client-side before
anything is sent), so callers can tell exactly which statements took
effect.
- The libsql-compat batch() returns the full libSQL ResultSet shape —
lastInsertRowid and toJSON() included, matching @libsql/client, whose
batch() returns the same ResultSet as execute() — and both of its
batch entry points preserve batchIndex and batchResults on the
LibsqlError they throw.
The JavaScript conformance contract covers the per-statement detail
fields. Also update the serverless integration tests that still
asserted positional access on expanded rows, removed in f52724d45.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Guard session.close() with the previous open state so reconnecting an already-closed client does not trigger a duplicate close request against the old session.
Add the missing reconnect() method to the compatibility client so it
matches the @libsql/client Client interface and can restore usability
after close().
Reconnect discards the previous session and creates a fresh lazy session
for subsequent requests.
Tests: added reconnect regression coverage
Fixes#8451
Only the JavaScript serverless driver supported a remote encryption key,
sent as the x-turso-encryption-key header. Add the same support to the
Go, Python, and Rust drivers:
- Go: remote_encryption_key DSN parameter and
Connector.WithRemoteEncryptionKey
- Python: connect(remote_encryption_key=...)
- Rust: Builder::with_remote_encryption_key
Document the header in PROTOCOL.md section 3.1 and make it an enforced
property: the shared differential spec gains a tests.encryption_header
entry, and every harness now runs a property test against a local stub
HTTP server asserting that a driver configured with a key attaches the
header to every request on both the pipeline and cursor endpoints, and
that a driver without a key never sends it. These tests need no Turso
Cloud database and never skip.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The Rust serverless driver rewrites both libsql:// and turso:// URLs
to https://, but the JavaScript driver only handled libsql://. Accept
turso:// as well so the drivers agree on supported URL schemes.
normalizeUrl never trimmed trailing slashes, so a URL like
https://db.turso.io/ produced requests to
https://db.turso.io//v3/pipeline. A base_url returned by the server
(section 4.6 of the protocol) was also adopted verbatim at every call
site, causing the same double slash on every subsequent request.
Trim trailing slashes in normalizeUrl and run server-returned base
URLs through it.
Tests: npx tsc --noEmit
Add property-based differential tests that compare an embedded Turso
driver against the serverless driver of the same language, running
against a live Turso Cloud database configured with TURSO_DATABASE_URL
and TURSO_AUTH_TOKEN. The tests skip when the variables are unset.
Random operation sequences (DDL, DML, queries, parameter binding,
transactions, batches, triggers, error cases) execute on both drivers,
and every result must match: success or failure, column names and
counts, row counts, value type tags, cell values, affected row counts,
and last insert rowids. Because the workloads are generated, the suite
finds divergences no hand-written test covers, and fast-check shrinks
failures to a minimal reproducing sequence.
The shared operation vocabulary lives in
serverless/conformance/differential/spec/ops.json so every language
harness faces the same workloads; each harness lives next to the driver
it tests. The JavaScript harness in serverless/javascript/differential
covers @tursodatabase/serverless against the native
@tursodatabase/database driver; since the serverless driver mirrors the
embedded API, one adapter drives both sides and any API divergence
fails the suite.
Co-authored-by: Pekka Enberg <penberg@iki.fi>
Expanded rows grew hidden non-enumerable positional properties ("0",
"1", ...) in 4c0febfed ("Preserve JS row positional values") to work
around duplicate column names collapsing in object rows. That is a
Turso-only extension: neither better-sqlite3 nor libsql attaches
positional keys to expanded rows, so the conformance suite failed under
PROVIDER=better-sqlite3 and PROVIDER=libsql, and a result column
literally named "0" would collide with the synthetic property.
Remove the positional properties from the native binding's expanded row
mode and the serverless driver's createExpandedRow so expanded rows are
plain objects where duplicate names collapse, exactly like
better-sqlite3 and libsql. Positional access remains available through
raw mode, and the libsql-client compat surface keeps its genuine hybrid
rows built by Session.createRowObject.
The divergence went unnoticed because CI only ran the conformance suite
under PROVIDER=turso; the workflow now also runs it against
better-sqlite3 so drop-in incompatibilities fail in CI.
Tests: rewrote the positional-value tests to assert the collapsing
behavior plus raw-mode access, so they pass identically under the
turso, better-sqlite3, and libsql providers.
Closes#7907
Expanded rows grew hidden non-enumerable positional properties ("0",
"1", ...) in 4c0febfed ("Preserve JS row positional values") to work
around duplicate column names collapsing in object rows. That is a
Turso-only extension: neither better-sqlite3 nor libsql attaches
positional keys to expanded rows, so the conformance suite failed under
PROVIDER=better-sqlite3 and PROVIDER=libsql, and a result column
literally named "0" would collide with the synthetic property.
Remove the positional properties from the native binding's expanded row
mode and the serverless driver's createExpandedRow so expanded rows are
plain objects where duplicate names collapse, exactly like
better-sqlite3 and libsql. Positional access remains available through
raw mode, and the libsql-client compat surface keeps its genuine hybrid
rows built by Session.createRowObject.
The divergence went unnoticed because CI only ran the conformance suite
under PROVIDER=turso; the workflow now also runs it against
better-sqlite3 so drop-in incompatibilities fail in CI.
Tests: rewrote the positional-value tests to assert the collapsing
behavior plus raw-mode access, so they pass identically under the
turso, better-sqlite3, and libsql providers.
The serverless driver's main entry point is meant to mirror the native
@tursodatabase/database surface, which has no execute() — it exposes
prepare/run/get/all/iterate/exec/batch/pragma/transaction. Connection.execute()
was a libsql-client-ism on that surface, and it returned the raw protocol
result shape rather than the {changes, lastInsertRowid} / row-array contracts
the sibling methods use.
The libsql compatibility layer keeps its own execute(), which talks to
Session.execute() directly and never went through Connection.execute(), so the
compat surface is unaffected.
Tests: rewrote the serverless integration tests and the serverless-only
conformance tests against exec/run/get/all; tsc and the package build pass.
Both suites need a live TURSO_DATABASE_URL and were not run.
The prepare()/Statement.run()/iterate() tests called `client.prepare(...)`
without awaiting it. Connection.prepare is async (returns Promise<Statement>),
so `stmt` was a Promise and `stmt.get/run/iterate` were "not a function". Add
the missing await.
This was surfaced running the JS suite against a live libsql-server.
All 46 JS integration tests pass against the live server.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
The driver caches the server's get_autocommit answer to back the
synchronous Connection.inTransaction property, but only describe and
sequence refreshed it. execute() and batch() went through the cursor
endpoint, which cannot carry a get_autocommit probe, so the cached
flag went stale. After a raw BEGIN IMMEDIATE batch hit a constraint
error, the server-side write transaction stayed open (statement-level
ABORT) while inTransaction still read false, so cleanup code skipped
ROLLBACK and the leaked transaction starved every other writer until
timeout.
Learn the transaction state in-band instead: every cursor batch gets a
trailing SELECT 1 step gated on the is_autocommit condition. The
server executes the step only when the connection is in autocommit,
so its presence in the entry stream is the authoritative answer, with
no extra round trip and no change to the streaming transport. A shared
wrapper filters the probe's entries out of the stream and falls back
to a standalone get_autocommit pipeline request when the stream ends
abnormally (fatal error entry or the consumer stops iterating early),
where the probe answer is unreliable.
Non-atomic batch() now defers its first step error until the stream is
drained instead of throwing immediately, so the probe is still
observed; the server ran the remaining unconditioned steps either way,
so the observable semantics are unchanged.
With the flag accurate, an atomic batch inside a manually-opened
transaction now joins it (mode ignored) instead of failing on a nested
BEGIN, matching batch() inside transaction(); the conformance test
pinning the old failure mode now pins the join contract.
Tests: testing/conformance/javascript async.test.js and compat.test.js
(PROVIDER=turso, PROVIDER=serverless against sqld, including the
queryTimeout cases), serverless/javascript integration-tests, and a
direct check that a 20MB row-producing batch streams successfully.
Make the JavaScript batch() return an array of ResultSet, one per input
statement, matching the libSQL client contract. Each ResultSet carries
that statement's columns, columnTypes, rows (with both positional and
named access), rowsAffected, and a BigInt lastInsertRowid.
Previously the native Database.batch() returned an aggregate
{ rowsAffected, lastInsertRowid } and discarded rows, while the
libSQL-compat client.batch() ignored statement args and collapsed all
statements into a single result. This reworks every layer:
- Native Database.batch() reads each statement's columns, collects rows
in raw mode, and builds one ResultSet per statement.
- session.batch() requests rows (want_rows) and returns one raw result
per statement, preserving the atomic Hrana condition chain.
- Connection.batch() shapes each result into a libSQL ResultSet.
- compat client.batch() binds args and runs the batch atomically.
Add conformance tests for both the native Database.batch() and the
libSQL-compat client.batch().
I think JS has problems overall. But my guess here is that there is some
positional property that we were not adding.
Closes https://github.com/tursodatabase/turso/issues/7278
Vibed as Im not quite a JS script kiddie
Reviewed-by: Mikaël Francoeur (@LeMikaelF)
Reviewed-by: Pekka Enberg <penberg@iki.fi>
Closes#7285