Turso is a distributed SQLite platform built on LibSQL — a fork of SQLite with replication, encryption, and remote access. It runs SQLite at the edge with replicas close to users. UUID v7 as primary keys is the natural choice: TEXT storage sorts chronologically, eliminating secondary time indexes, and the random bits prevent collisions across distributed writes. See UUID in SQLite for the storage format background.

Setup

npm install @libsql/client uuid drizzle-orm drizzle-kit

LibSQL client with UUID v7

import { createClient } from '@libsql/client';
import { v7 as uuidv7 } from 'uuid';

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

// Schema
await db.execute(`
  CREATE TABLE IF NOT EXISTS orders (
    id       TEXT PRIMARY KEY,  -- UUID v7, lexicographic sort = time order
    customer TEXT NOT NULL,
    total    REAL NOT NULL
  )
`);

// Insert with UUID v7
async function createOrder(customer: string, total: number) {
  const id = uuidv7();
  await db.execute({
    sql: 'INSERT INTO orders (id, customer, total) VALUES (?, ?, ?)',
    args: [id, customer, total],
  });
  return id;
}

Cursor pagination with UUID v7

async function listOrders(cursor?: string, limit = 20) {
  const result = cursor
    ? await db.execute({
        sql: 'SELECT id, customer, total FROM orders WHERE id > ? ORDER BY id LIMIT ?',
        args: [cursor, limit],
      })
    : await db.execute({
        sql: 'SELECT id, customer, total FROM orders ORDER BY id LIMIT ?',
        args: [limit],
      });

  const rows = result.rows as { id: string; customer: string; total: number }[];
  const nextCursor = rows.length === limit ? rows[rows.length - 1].id : null;
  return { rows, nextCursor };
}

UUID v7 lexicographic ordering means WHERE id > cursor ORDER BY id gives correct chronological pagination. See UUID v7 for Cursor Pagination.

Drizzle ORM with Turso

// schema.ts
import { sqliteTable, text, real } from 'drizzle-orm/sqlite-core';
import { v7 as uuidv7 } from 'uuid';

export const orders = sqliteTable('orders', {
  id:       text('id').primaryKey().$defaultFn(() => uuidv7()),
  customer: text('customer').notNull(),
  total:    real('total').notNull(),
});
// db.ts
import { drizzle } from 'drizzle-orm/libsql';
import { createClient } from '@libsql/client';
import * as schema from './schema';

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

export const db = drizzle(client, { schema });
// usage
import { db } from './db';
import { orders } from './schema';
import { gt } from 'drizzle-orm';

// Insert — UUID v7 generated by $defaultFn
const [order] = await db.insert(orders)
  .values({ customer: 'Alice', total: 49.99 })
  .returning();

// Paginate
const page = await db.select().from(orders)
  .where(cursor ? gt(orders.id, cursor) : undefined)
  .orderBy(orders.id)
  .limit(20);

See UUID in Drizzle ORM for the full migration setup.

Cloudflare Workers + Turso + UUID v7

// worker.ts (Cloudflare Workers)
import { createClient } from '@libsql/client/web';
import { v7 as uuidv7 } from 'uuid';

export default {
  async fetch(request: Request, env: Env) {
    const db = createClient({
      url: env.TURSO_DATABASE_URL,
      authToken: env.TURSO_AUTH_TOKEN,
    });

    if (request.method === 'POST') {
      const body = await request.json<{ customer: string; total: number }>();
      const id = uuidv7();

      await db.execute({
        sql: 'INSERT INTO orders (id, customer, total) VALUES (?, ?, ?)',
        args: [id, body.customer, body.total],
      });

      return Response.json({ id }, { status: 201 });
    }

    return new Response('Not found', { status: 404 });
  },
};

See UUID in Edge Functions for the broader edge runtime context.

Further reading

External references

Frequently asked questions

How do I store UUIDs in Turso?

Store UUID v7 as TEXT (36 characters) in Turso SQLite. SQLite has TEXT affinity for UUID strings, and UUID v7 sorts correctly in lexicographic ORDER BY because the timestamp prefix is big-endian hex. This eliminates the need for a separate created_at index for time-ordered queries. See UUID in SQLite.

Does Turso have a built-in UUID function?

SQLite and LibSQL have no built-in uuidv7(). Generate UUID v7 in your application with the uuid npm package and pass the string value to your queries. The LibSQL driver binds UUID strings directly.

How does UUID v7 work with Turso's database replicas?

Turso replicates writes from the primary to regional replicas. UUID v7 values generated in different regions do not collide because the 74 random bits provide sufficient entropy globally. Since UUID v7 encodes creation time, values from different regions sort correctly by creation time when the primary merges them — the timestamp prefix ensures global chronological order.