Kysely is a fully type-safe SQL query builder — it compiles TypeScript method chains to SQL without hiding the query structure. UUID v7 primary keys integrate at the TypeScript type level using the Generated helper, and Kysely’s where/orderBy API maps directly to the cursor pagination pattern UUID v7 enables. See UUID in Databases for storage fundamentals.
Install dependencies
npm install kysely pg uuid
npm install -D @types/pg @types/uuid
Enable pg_uuidv7 in PostgreSQL
CREATE EXTENSION IF NOT EXISTS "pg_uuidv7";
CREATE TABLE orders (
id UUID NOT NULL DEFAULT gen_random_uuid_v7() PRIMARY KEY,
customer_id UUID NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
total NUMERIC(10, 2) NOT NULL
);
Database type definitions
import { Generated, Selectable, Insertable } from 'kysely';
interface OrderTable {
id: Generated<string>; // UUID v7 — database default
customer_id: string;
status: Generated<string>;
total: number;
}
interface Database {
orders: OrderTable;
}
// Convenience types
type Order = Selectable<OrderTable>;
type NewOrder = Insertable<OrderTable>;
Kysely instance
import { Kysely, PostgresDialect } from 'kysely';
import { Pool } from 'pg';
const db = new Kysely<Database>({
dialect: new PostgresDialect({
pool: new Pool({ connectionString: process.env.DATABASE_URL }),
}),
});
Insert — database-generated UUID v7
// Database generates UUID v7 via gen_random_uuid_v7() default
async function createOrder(customerId: string, total: number): Promise<Order> {
return db
.insertInto('orders')
.values({ customer_id: customerId, total })
.returningAll()
.executeTakeFirstOrThrow();
}
Insert — client-generated UUID v7
import { v7 as uuidv7 } from 'uuid';
// Client assigns UUID v7 — useful for idempotency or pre-known IDs
async function createOrderWithId(customerId: string, total: number): Promise<Order> {
const id = uuidv7();
return db
.insertInto('orders')
.values({ id, customer_id: customerId, total })
.returningAll()
.executeTakeFirstOrThrow();
}
Cursor pagination
interface PageResult {
data: Order[];
nextCursor: string | null;
}
async function listOrders(
customerId: string,
cursor?: string,
limit = 20,
): Promise<PageResult> {
let query = db
.selectFrom('orders')
.selectAll()
.where('customer_id', '=', customerId);
if (cursor) {
// UUID v7 lexicographic > cursor = created after cursor
query = query.where('id', '>', cursor);
}
const rows = await query
.orderBy('id', 'asc') // UUID v7 sort = chronological
.limit(limit + 1)
.execute();
const hasMore = rows.length > limit;
const data = hasMore ? rows.slice(0, limit) : rows;
const nextCursor = hasMore ? data.at(-1)!.id : null;
return { data, nextCursor };
}
Time-range query
// Orders in the last hour — using uuid_extract_timestamp() from pg_uuidv7
async function recentOrders(): Promise<Order[]> {
return db
.selectFrom('orders')
.selectAll()
.where(
(eb) => eb.raw<boolean>(
"uuid_extract_timestamp(id) > now() - interval '1 hour'"
)
)
.orderBy('id', 'asc')
.execute();
}
Extract timestamp on the client
function extractTimestamp(id: string): Date {
const hex = id.replace(/-/g, '').slice(0, 12);
return new Date(parseInt(hex, 16));
}
// Example
const order = await createOrder('customer-id', 49.99);
const createdAt = extractTimestamp(order.id);
console.log(`Order created at: ${createdAt.toISOString()}`);
Transaction with UUID v7
async function createOrderWithItems(
customerId: string,
total: number,
items: { sku: string; quantity: number }[],
) {
return db.transaction().execute(async (trx) => {
const id = uuidv7();
const order = await trx
.insertInto('orders')
.values({ id, customer_id: customerId, total })
.returningAll()
.executeTakeFirstOrThrow();
// UUID v7 for each item — all generated at the same millisecond, differ by random bits
for (const item of items) {
await trx
.insertInto('order_items' as any)
.values({ id: uuidv7(), order_id: order.id, ...item })
.execute();
}
return order;
});
}
Further reading
- UUID v7 in Drizzle + PostgreSQL
- UUID v7 for Cursor Pagination
- UUID v7 in Prisma + PostgreSQL
- UUID in JavaScript
- UUID in Databases — Storage and Indexing
External references
Frequently asked questions
How do I define a UUID v7 column in Kysely?
Use Generated<string> in the table interface for database-generated UUID v7 defaults: id: Generated<string>. For client-generated UUIDs, use id: string and pass uuidv7() explicitly in the insert. Kysely maps TypeScript string to PostgreSQL uuid — both Generated<string> and plain string work. See UUID v7 in Drizzle + PostgreSQL for comparison.
How does Kysely cursor pagination work with UUID v7?
Use .where('id', '>', cursor).orderBy('id', 'asc'). Kysely compiles this to WHERE id > $1 ORDER BY id ASC. UUID v7's lexicographic order equals chronological, so no created_at column is needed. The last row's id becomes the next cursor. See UUID v7 for Cursor Pagination.
Does Kysely support UUID v7 with connection pooling (pg pool)?
Yes. Kysely wraps node-postgres (pg) or postgres.js via a dialect. UUID v7 values are passed as strings in parameterized queries — the driver sends them as PostgreSQL uuid literals. No special driver configuration is needed. See UUID in JavaScript for the Node.js runtime context.