Files
turso/serverless/javascript
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
..
2026-07-27 17:37:35 +03:00
2026-07-27 17:37:35 +03:00

Turso Serverless Driver for JavaScript

npm

Chat with other users of Turso on Discord


About

A serverless database driver for Turso Cloud, using only fetch(). Connect to your database from serverless and edge functions, such as Cloudflare Workers and Vercel.

Installation

npm install @tursodatabase/serverless

Getting Started

Basic Usage

import { connect } from "@tursodatabase/serverless";

const conn = connect({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

// Prepare a statement
const stmt = conn.prepare("SELECT * FROM users WHERE id = ?");

// Get first row
const row = await stmt.get([123]);
console.log(row);

// Get all rows
const rows = await stmt.all([123]);
console.log(rows);

// Iterate through rows (streaming)
for await (const row of stmt.iterate([123])) {
  console.log(row);
}

Batch Operations

// Execute multiple statements in a batch
await conn.batch([
  "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT)",
  "INSERT INTO users (email) VALUES ('user@example.com')",
  "INSERT INTO users (email) VALUES ('admin@example.com')",
]);

// Parameterized batch statements also work
await conn.transaction(async () => {
  await conn.batch([
    { sql: "INSERT INTO users (email) VALUES (?)", args: ["alice@example.com"] },
    { sql: "INSERT INTO users (email) VALUES (?)", args: ["bob@example.com"] },
  ]);
}).concurrent();

The whole batch is one HTTP request, and the statements execute in order, stopping at the first failure. Each returned ResultSet carries the statement's rows, rowsAffected, and lastInsertRowid, plus the server-side execution statistics rowsRead, rowsWritten, and queryDurationMs:

const results = await conn.batch([
  { sql: "INSERT INTO users (email) VALUES (?)", args: ["carol@example.com"] },
  "SELECT COUNT(*) AS n FROM users",
]);
console.log(results[0].lastInsertRowid, results[1].rows[0].n);
console.log(results[1].rowsRead, results[1].queryDurationMs);

When a statement fails, the thrown error identifies it and carries the results of the statements that completed:

try {
  await conn.batch([...statements]);
} catch (e) {
  // e.batchIndex: zero-based index of the failing statement.
  // e.batchResults: one entry per statement — the completed statement's
  // ResultSet, or null for the failing statement and those never run.
}

Custom Headers

Requests can carry extra HTTP headers, e.g. for routing through a gateway:

const conn = connect({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
  // Extra headers attached to every request. Applied after the standard
  // headers, so they can override e.g. `Authorization`. Setting the `Host`
  // key throws — fetch forbids it.
  requestHeaders: { "x-custom-header": "value" },
});

Headers can also be set per query via the trailing query-options argument. They apply to that call only and are merged over the connection-level requestHeaders, so a query can override a header the connection sets:

await conn.all("SELECT * FROM users", {
  requestHeaders: { "X-Turso-Request-Identity": "abc123" },
});

// Also accepted by run()/get()/iterate() and prepared statements:
await conn.run("INSERT INTO users (email) VALUES (?)", "user@example.com", {
  requestHeaders: { "X-Turso-Request-Identity": "abc124" },
});

Per-query headers are attached to exactly the HTTP request(s) issued by that call. Inside a conn.transaction(...) callback each statement still carries only its own per-query headers — the BEGIN/COMMIT/ROLLBACK requests are issued by the transaction wrapper itself and carry just the connection-level headers. To stamp every request of a transaction (including BEGIN and COMMIT), set the header at the connection level, or use an atomic batch, which sends the whole transaction as a single HTTP request:

// One HTTP request: BEGIN, both inserts, and COMMIT all carry the header.
await conn.batch([
  { sql: "INSERT INTO users (email) VALUES (?)", args: ["alice@example.com"] },
  { sql: "INSERT INTO users (email) VALUES (?)", args: ["bob@example.com"] },
], "immediate", {
  requestHeaders: { "X-Turso-Request-Identity": "abc125" },
});

libSQL Compatibility Layer

For existing libSQL applications, use the compatibility layer:

import { createClient } from "@tursodatabase/serverless/compat";

const client = createClient({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

// Execute a single SQL statement
const result = await client.execute("SELECT * FROM users WHERE id = ?", [123]);
console.log(result.rows);

// Execute multiple statements in a batch
await client.batch([
  "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT)",
  "INSERT INTO users (email) VALUES ('user@example.com')",
  "INSERT INTO users (email) VALUES ('admin@example.com')",
]);

Examples

Check out the examples/ directory for complete usage examples.

API Reference

For complete API documentation, see JavaScript API Reference.

License

This project is licensed under the MIT license.

Support