mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
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.
Turso Serverless Driver for JavaScript
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();
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" },
});
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.
Related Packages
- The @tursodatabase/database package provides the Turso in-memory database, compatible with SQLite.
- The @tursodatabase/sync package provides bidirectional sync between a local Turso database and Turso Cloud.
License
This project is licensed under the MIT license.