Commit Graph

44 Commits

Author SHA1 Message Date
Pekka Enberg
910cab5251 serverless/js: fix query failure on column names that are array properties
Rows from the cursor endpoint are built as arrays with one extra
property per column name, so the compat ResultSet rows can be read by
index and by name. Defining a column-name property that the array
already owns throws, so a query returning such a column fails outright
("Cannot redefine property", or "Cannot convert a BigInt value to a
number" with safeIntegers()).

Never overwrite a property the row already has. This is the rule
@libsql/hrana-client and libsql-client use for their rows. As a side
effect, compat rows with duplicate column names now keep the first value
by name instead of the last, matching libsql-client.

Tests: new "Statement.all() [column names that are JavaScript object
properties]" conformance test in testing/conformance/javascript covering
length, map, toString and hasOwnProperty. Run with PROVIDER=serverless
against a local `turso dev` server it fails on the unfixed driver and
passes with the fix.
2026-10-06 10:02:35 +03:00
Pekka Enberg
58c0cf2970 Merge 'serverless/compat: add reconnect support' from Ishwar
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
2026-09-01 19:57:41 +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
a368eab3af js: return full per-statement details from batch() in every driver
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>
2026-08-28 10:40:25 -07:00
Ishwar
66109f601e serverless/compat: avoid redundant session close on reconnect
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.
2026-08-27 11:19:50 +05:30
Ishwar
ff354d7bda serverless/compat: add reconnect support
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
2026-08-26 12:50:37 +05:30
Pekka Enberg
669f9d8cb8 Merge 'Fix JavaScript serverless driver URL normalization' from Pekka Enberg
Fix few issues while working on Rust serverless driver.

Closes #8000
2026-07-27 08:39:52 +03:00
Nikita Sivukhin
165ec52e0a tests and docstring 2026-07-24 12:02:35 +02:00
Nikita Sivukhin
c1a9bda71d run transactionAsync over separate session 2026-07-24 11:52:36 +02:00
Pekka Enberg
4ce97b0506 serverless/javascript: accept turso:// URLs
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.
2026-07-23 17:25:44 +03:00
Pekka Enberg
81699dccbf serverless/javascript: strip trailing slashes from all normalized URLs
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
2026-07-23 17:25:44 +03:00
Pekka Enberg
7b5fbf8aa1 Merge 'bindings/js, serverless/js: collapse duplicate column names in expanded rows' from Pekka Enberg
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
2026-07-21 07:43:32 +03:00
Nikita Sivukhin
1262625452 Merge branch 'main' into fix-async-txn-ts-simple 2026-07-20 22:16:28 +02:00
Pekka Enberg
f52724d450 bindings/js, serverless/js: collapse duplicate column names in expanded rows
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.
2026-07-20 20:11:59 +03:00
Pekka Enberg
3e246552e9 serverless: remove Connection.execute() from the main API
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.
2026-07-20 18:29:15 +03:00
Nikita Sivukhin
8cd8552c93 per-transaction lock to avoid race in case of concurrent execution within transaction 2026-07-20 15:26:15 +02:00
Nikita Sivukhin
b4bcdf0af6 Merge branch 'main' into fix-async-txn-ts-simple
# Conflicts:
#	testing/conformance/javascript/__test__/async.test.js
2026-07-17 16:14:08 +02:00
Nikita Sivukhin
149635b0c8 use transactionAsync instead of transaction 2026-07-17 16:09:13 +02:00
Nikita Sivukhin
6931576650 wip 2026-07-17 15:28:14 +02:00
Nikita Sivukhin
344cea792d Merge branch 'main' into request-headers-serverless 2026-07-17 15:00:34 +02:00
Nikita Sivukhin
a86208e996 wip 2026-07-17 14:59:46 +02:00
Nikita Sivukhin
74311642b0 allow to pass arbitrary request headers in the queries through queryOptions 2026-07-17 13:37:15 +02:00
Pekka Enberg
cbfd05b1de serverless/javascript: fix stale inTransaction after execute and batch
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.
2026-07-17 09:33:00 +03:00
Pekka Enberg
45e80cfe26 Return per-statement results from batch()
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().
2026-06-18 09:09:38 +03:00
Nikita Sivukhin
083ccc811d Merge 'serverless/javascript: add option for custom request headers' from Nikita Sivukhin
Simple PR to allow user to set arbitrary request headers for serverless
driver. For example:
```js
const conn = connect({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
  requestHeaders: { "x-custom-header": "value" },
});
```

Reviewed-by: Pekka Enberg <penberg@iki.fi>

Closes #7403
2026-06-11 21:36:39 +04:00
Nikita Sivukhin
90ae357645 add validation for requestHeaders parameter 2026-06-11 19:25:27 +02:00
Pedro Muniz
7715979bd0 Merge 'Preserve JS row positional values' from Pedro Muniz
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
2026-06-08 16:22:28 -03:00
Nikita Sivukhin
2006463cff add requestHeaders option so that user can set arbitrary headers for serverless driver 2026-06-08 08:58:08 +02:00
pedrocarlo
4c0febfed2 Preserve JS row positional values 2026-06-02 18:58:41 -03:00
Pekka Enberg
34ae4061ca Merge 'serverless/javascript: Fix stack overflow error with large blobs' from Henry
Fixes https://github.com/tursodatabase/turso/issues/7330
No AI

Closes #7331
2026-06-02 18:54:17 +03:00
mcmah309
42a4ea085b Fix serverless stackoverflow issue for large blobs 2026-06-02 14:26:56 +03:00
Pekka Enberg
e5ddef05ed javascript: Fix Database.inTransaction property
Fix the inTransaction property to probe the database connection whether
it is in a transaction or not.
2026-06-01 18:36:54 +03:00
Pekka Enberg
f6a16e8299 Add Database.batch() to the JavaScript SDKs
The batch() method executes an array of SQL statements over a single
connection and returns aggregated `rowsAffected` and `lastInsertRowid`. Each
statement is either a SQL string or a `{ sql, args }` object with positional
or named bind parameters; named-args objects are forwarded to the underlying
engine as named parameters rather than collapsed via Object.values().

By default the batch is non-transactional: each statement runs in its own
autocommit step. Passing a `mode` -- `deferred`, `immediate`, `exclusive`, or
`concurrent` -- makes the batch atomic. You can also use `batch()` with the
transaction API to make it transactional.

The serverless driver implements atomic batch as a a single SQL over HTTP
request. The wire payload chains BEGIN, the user statements, COMMIT, and
ROLLBACK as a single batch using the server-side condition operators.
2026-05-19 16:25:07 +03:00
Pekka Enberg
27ba5c5a29 bindings/javascript: Add concurrent transaction support
Expose a `concurrent` mode on the transaction wrapper alongside the
existing `deferred`, `immediate`, and `exclusive` modes, so users can
write `db.transaction(fn).concurrent()` to run the body under
`BEGIN CONCURRENT`.
2026-05-18 15:44:19 +03:00
Pekka Enberg
b8763de6df serverless/javascript: Add bind parameter support to Database API 2026-05-04 13:46:48 +03:00
Akira Noda
faed3df7ee serverless/javascript: preserve zero lastInsertRowid 2026-04-30 12:35:57 +09:00
Pekka Enberg
fbf3a7939c serverless/javascript: Encode out-of-range integers as float
Number.isInteger(Number.MAX_VALUE) returns true, so encodeValue() sent
it as { type: 'integer', value: '1.7976931348623157e+308' }, which the
server rejected with HTTP 400 when parsing as i64. Switch to
Number.isSafeInteger so values outside ±2^53 fall through to the float
branch.
2026-04-28 11:33:39 +03:00
Glauber Costa
8430a26743 fix prepare() losing transaction baton in serverless driver
Connection.prepare() created a throwaway Session for the describe call,
which had no baton and therefore ran on a separate server-side connection.
This meant it could not see uncommitted DDL (e.g. CREATE TABLE) from the
current transaction.

Use this.session instead and serialize through execLock, matching how
exec() and execute() already work.

Fixes #6562

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-24 17:33:59 -04:00
Glauber Costa
2a4bae2286 fix empty blob decoding returning null in serverless driver
decodeValue() returned null for blobs without a base64 field (e.g.
{"type":"blob"} with no base64 key). Now returns Buffer.alloc(0),
matching the turso NAPI driver behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-24 08:55:31 -04:00
Glauber Costa
5f89ba0bf5 fix serverless driver stale baton after HTTP error
When executeCursor() or executePipeline() throws due to an HTTP error,
the baton was never cleared. Subsequent requests sent the stale baton,
causing the server to reject them with HTTP 400.

Reset baton to null on error in executeRaw(), batch(), describe(), and
sequence().

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-24 02:00:03 -04:00
Glauber Costa
66e24ac59b fix serverless driver conformance for empty blobs and falsy rowids
The serverless driver diverged from the database driver in three cases:
- Empty blobs (base64 '') decoded to null instead of empty Buffer
- Unpadded base64 strings could fail in strict environments
- last_insert_rowid of 0 was dropped (falsy check), and numeric type
  from the database driver was not handled

Add conformance tests to testing/javascript async test suite.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-24 01:04:52 -04:00
Pekka Enberg
c4f85a8a54 serverless/javascript: Interactive transaction support
Prepared statements used to allocate their own session, so a BEGIN
issued on the Connection didn't actually bracket anything run through
them — each stmt.run()/get()/all() went out on an independent stream
under auto-commit. Code that looked transactional wasn't.

Connection.prepare() now hands statements the connection's session
via Statement.fromSession() and its exec lock, which they acquire
around each call. A BEGIN on the connection bounds every prepared-
statement call until COMMIT or ROLLBACK. iterate() would deadlock
nested queries on the same connection if it held the lock across
yields, so on shared-session statements it buffers via all().

Tests cover commit visibility across connections, rollback discarding
writes, and error-then-rollback-then-reuse.

The compat layer's client.transaction() — previously throwing
NOT_IMPLEMENTED — now builds on the same primitives and is cross-
validated against @libsql/client.
2026-04-18 14:49:12 +03:00
Pekka Enberg
7025d453fe serverless: add query timeout support with AbortSignal
Add per-connection defaultQueryTimeout and per-query queryTimeout
options to the serverless driver, matching the API from the native
JS bindings. Stalled fetch() or stream reads now abort instead of
hanging forever, which prevents the AsyncLock from blocking all
subsequent queries on the connection.

Introduces TimeoutError (subclass of DatabaseError, code "TIMEOUT")
so callers can distinguish timeouts from other errors and decide
whether to retry or fail gracefully.
2026-03-30 13:48:54 +03:00
Pekka Enberg
4e144df120 Move @tursodatabase/serverless to serverless/javascript
Reorganize serverless SDKs under a top-level serverless/ directory
to support multi-language serverless drivers alongside the existing
bindings/ convention.
2026-03-26 08:15:10 +02:00