Drizzle <> Turso Database Serverless
This guide assumes familiarity with:
- Database connection basics with Drizzle
- Turso Database - website
- Turso Database serverless driver - website & GitHub
According to the official website, Turso is the small database to power your big dreams in the age of AI.
Step 1 - Install packages
npm
yarn
pnpm
bun
npm i drizzle-orm@rc @tursodatabase/serverless
npm i -D drizzle-kit@rc
Step 2 - Initialize the driver and make a query
import { drizzle } from 'drizzle-orm/tursodatabase-serverless';
const db = drizzle({
connection: {
url: process.env.TURSO_URL,
authToken: process.env.TURSO_TOKEN
}
});
const result = await db.all('select 1');If you need to provide your existing drivers:
import { connect } from '@tursodatabase/serverless';
import { drizzle } from 'drizzle-orm/tursodatabase-serverless';
const client = connect({
url: process.env.TURSO_URL,
authToken: process.env.TURSO_TOKEN
});
const db = drizzle({ client });
const result = await db.all('select 1');Transaction modes
You can set the transaction mode with the behavior option. Drizzle passes it to the driver, which opens the transaction with BEGIN <mode>.
Without behavior, a plain BEGIN is used, which SQLite runs as deferred.
import { drizzle } from 'drizzle-orm/tursodatabase-serverless';
import { users } from './schema';
const db = drizzle({ connection: { url: process.env.TURSO_URL, authToken: process.env.TURSO_TOKEN } });
await db.transaction(async (tx) => {
await tx.insert(users).values({ name: 'Dan' });
}, {
behavior: 'immediate', // 'deferred' | 'immediate' | 'exclusive' | 'concurrent'
});deferred- takes the lock on the first read or writeimmediate- takes the write lock at the start of the transactionexclusive- takes the write lock at the start and blocks other connectionsconcurrent- lets several write transactions run at the same time. It needs MVCC to be turned on in Turso Database
Nested tx.transaction() calls use savepoints and don’t take a behavior option.
What’s next?
Manage schema
Query data