Part 3: Query Tenant Notes
Each request reads the tenant from the URL and only touches that tenant’s database.
Install the driver
Section titled “Install the driver”pnpm add drizzle-orm @effect/sql-libsqlConnect to the tenant’s database
Section titled “Connect to the tenant’s database”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.
List notes
Section titled “List notes”case "GET": { const notes = yield* db.select().from(Notes); return yield* HttpServerResponse.json({ notes });}Add a note
Section titled “Add a note”case "POST": { const { body } = (yield* request.json) as { body: string }; const [note] = yield* db.insert(Notes).values({ body }).returning(); return yield* HttpServerResponse.json({ note });}Deploy
Section titled “Deploy”pnpm alchemy deployAlchemy prints the Worker’s url.
Create two tenants
Section titled “Create two tenants”curl -X POST $URL/tenants/acmecurl -X POST $URL/tenants/globexEach call creates a database with the tenant’s name. Names must be unique in your Turso organization.
Write a note
Section titled “Write a note”curl -X POST $URL/tenants/acme/notes -d '{"body":"hello from acme"}'curl $URL/tenants/acme/notesacme sees its note. globex has its own database, still empty:
curl $URL/tenants/globex/notesClean up
Section titled “Clean up”pnpm alchemy destroyThis deletes the Tenants group and every tenant database in it.