Skip to content

Part 3: Query Tenant Notes

Each request reads the tenant from the URL and only touches that tenant’s database.

Terminal window
pnpm add drizzle-orm @effect/sql-libsql
import * as Drizzle from "alchemy/Drizzle/LibSQL";
if (resource === "notes") {
const db = yield* Drizzle.LibSQL(tenants.connect(tenant));
}

tenants.connect(tenant) returns the database’s URL and a token. The connection opens on the first query and closes when the request ends.

case "GET": {
const notes = yield* db.select().from(Notes);
return yield* HttpServerResponse.json({ notes });
}
case "POST": {
const { body } = (yield* request.json) as { body: string };
const [note] = yield* db.insert(Notes).values({ body }).returning();
return yield* HttpServerResponse.json({ note });
}
Terminal window
pnpm alchemy deploy

Alchemy prints the Worker’s url.

Terminal window
curl -X POST $URL/tenants/acme
curl -X POST $URL/tenants/globex

Each call creates a database with the tenant’s name. Names must be unique in your Turso organization.

Terminal window
curl -X POST $URL/tenants/acme/notes -d '{"body":"hello from acme"}'
curl $URL/tenants/acme/notes

acme sees its note. globex has its own database, still empty:

Terminal window
curl $URL/tenants/globex/notes
Terminal window
pnpm alchemy destroy

This deletes the Tenants group and every tenant database in it.