$ cat docs/recipes/d1-drizzle.md
Recipe: D1 and DrizzleReceita: D1 e Drizzle
Cloudflare D1 with Drizzle: bindings checked at startup, the owner checked before the handler and again in the query.Cloudflare D1 com Drizzle: bindings conferidos na subida, o dono conferido antes do handler e de novo na consulta.
Validate the bindingsValidar os bindings
@tupik/env declares DB: binding.d1(). withEnv checks it on the first request of each isolate; a missing binding answers a generic 500 and logs the problem once. Handlers read the typed value with getEnv<Vars>(ctx).
O @tupik/env declara DB: binding.d1(). O withEnv confere na primeira requisição de cada isolate; binding ausente responde um 500 genérico e vai para o log uma vez. Os handlers leem o valor tipado com getEnv<Vars>(ctx).
Owner in two placesDono em dois lugares
access.owner loads only the owner id and runs before the handler: a note of another user answers 404, so its existence is not revealed. The handler query also filters by ctx.principal.id. If someone later removes the rule, the query is still safe.
O access.owner carrega só o id do dono e roda antes do handler: a nota de outro usuário responde 404, sem revelar que existe. A consulta do handler também filtra por ctx.principal.id. Se alguém tirar a regra depois, a consulta continua segura.
Select the columns you return. A select() of the whole row is what tupik/no-raw-row-response warns about; a response schema also cuts undeclared fields.
Selecione as colunas que devolve. Um select() da linha inteira é o que o tupik/no-raw-row-response aponta; um schema de resposta também corta campos não declarados.
import { createApp, createModule } from '@tupik/core';
import { getEnv } from '@tupik/edge';
import { binding, defineEnv, secret, withEnv, type InferEnv } from '@tupik/env';
import { D1SessionStore, session } from '@tupik/middleware';
import { and, eq } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/d1';
import { sqliteTable, text } from 'drizzle-orm/sqlite-core';
import { z } from 'zod';
// the Worker refuses to run without these
const env = defineEnv({ DB: binding.d1<D1Database>(), CSRF_SECRET: secret({ minLength: 32 }) });
type Vars = InferEnv<typeof env>;
const notes = sqliteTable('notes', {
id: text('id').primaryKey(),
ownerId: text('owner_id').notNull(),
title: text('title').notNull(),
body: text('body').notNull(),
});
type User = { id: string };
declare module '@tupik/core' {
interface TupikRegister {
principal: User;
}
}
const sessions = session<User>({ store: new D1SessionStore({ database: (bindings) => (bindings as Vars).DB }) });
const db = (ctx: Parameters<typeof getEnv>[0]) => drizzle(getEnv<Vars>(ctx).DB);
const notesModule = createModule('/notes').get('/:id', {
schema: { params: z.object({ id: z.string() }) },
// owner rule: someone else's note answers 404
access: {
owner: async (ctx) => {
const row = await db(ctx).select({ ownerId: notes.ownerId }).from(notes).where(eq(notes.id, ctx.params.id)).get();
return row?.ownerId;
},
},
handler: async (ctx) =>
// the owner is in the WHERE too, so the query is safe on its own
db(ctx)
.select({ id: notes.id, title: notes.title, body: notes.body })
.from(notes)
.where(and(eq(notes.id, ctx.params.id), eq(notes.ownerId, ctx.principal.id)))
.get(),
});
const app = createApp({ authenticate: (ctx) => sessions.get(ctx).data ?? null })
.use(sessions)
.register(notesModule);
export default { fetch: withEnv(env, (request, vars, ctx: ExecutionContext) => app.fetch(request, vars, ctx)) };import { createApp, createModule } from '@tupik/core';
import { getEnv } from '@tupik/edge';
import { binding, defineEnv, secret, withEnv, type InferEnv } from '@tupik/env';
import { D1SessionStore, session } from '@tupik/middleware';
import { and, eq } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/d1';
import { sqliteTable, text } from 'drizzle-orm/sqlite-core';
import { z } from 'zod';
// o Worker não roda sem eles
const env = defineEnv({ DB: binding.d1<D1Database>(), CSRF_SECRET: secret({ minLength: 32 }) });
type Vars = InferEnv<typeof env>;
const notes = sqliteTable('notes', {
id: text('id').primaryKey(),
ownerId: text('owner_id').notNull(),
title: text('title').notNull(),
body: text('body').notNull(),
});
type User = { id: string };
declare module '@tupik/core' {
interface TupikRegister {
principal: User;
}
}
const sessions = session<User>({ store: new D1SessionStore({ database: (bindings) => (bindings as Vars).DB }) });
const db = (ctx: Parameters<typeof getEnv>[0]) => drizzle(getEnv<Vars>(ctx).DB);
const notesModule = createModule('/notes').get('/:id', {
schema: { params: z.object({ id: z.string() }) },
// regra de dono: a nota de outro responde 404
access: {
owner: async (ctx) => {
const row = await db(ctx).select({ ownerId: notes.ownerId }).from(notes).where(eq(notes.id, ctx.params.id)).get();
return row?.ownerId;
},
},
handler: async (ctx) =>
// o dono também está no WHERE, então a consulta é segura sozinha
db(ctx)
.select({ id: notes.id, title: notes.title, body: notes.body })
.from(notes)
.where(and(eq(notes.id, ctx.params.id), eq(notes.ownerId, ctx.principal.id)))
.get(),
});
const app = createApp({ authenticate: (ctx) => sessions.get(ctx).data ?? null })
.use(sessions)
.register(notesModule);
export default { fetch: withEnv(env, (request, vars, ctx: ExecutionContext) => app.fetch(request, vars, ctx)) }; Sessions on the same databaseSessões no mesmo banco
D1SessionStore keeps sessions in a tupik_sessions table. Run D1SessionStore.schema() once as a migration (it returns the SQL). Revocation is immediate because D1 is consistent.
O D1SessionStore guarda as sessões numa tabela tupik_sessions. Rode D1SessionStore.schema() uma vez como migration (ele devolve o SQL). A revogação é imediata porque o D1 é consistente.
What can go wrongO que pode dar errado
- The owner query and the handler query run separately. Keep the owner filter in the handler query so a race or a missing rule cannot leak a row.
getEnvthrows when the runtime passed no env (tests without bindings). In tests, callapp.fetch(request, env)with a fake env.- Expired sessions stay in the table until
purgeExpired()runs. Call it from a Cron Trigger.
- A consulta do dono e a do handler rodam separadas. Mantenha o filtro de dono na consulta do handler para que uma corrida ou uma regra ausente não vaze a linha.
- O
getEnvlança erro quando o runtime não passou env (testes sem bindings). Nos testes, chameapp.fetch(request, env)com um env falso. - Sessões vencidas ficam na tabela até o
purgeExpired()rodar. Chame num Cron Trigger.