@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
mdx 87 lines 1.94 KB
Raw
1 ---
2 title: "Part 3: Query Tenant Notes"
3 description: Read and write a tenant's notes with Drizzle, then try it out.
4 sidebar:
5 order: 3
6 ---
7
8 Each request reads the tenant from the URL and only touches that tenant's database.
9
10 ## Install the driver
11
12 ```diff lang="sh"
13 +pnpm add @alchemy.run/drizzle drizzle-orm @effect/sql-libsql
14 ```
15
16 ## Connect to the tenant's database
17
18 ```diff lang="typescript"
19 +import * as Drizzle from "@alchemy.run/drizzle/LibSQL";
20
21 if (resource === "notes") {
22 + const db = yield* Drizzle.LibSQL(tenants.connect(tenant));
23 }
24 ```
25
26 `tenants.connect(tenant)` returns the database's URL and a token. The connection opens on the first query and closes when the request ends.
27
28 ## List notes
29
30 ```diff lang="typescript"
31 case "GET": {
32 + const notes = yield* db.select().from(Notes);
33 + return yield* HttpServerResponse.json({ notes });
34 }
35 ```
36
37 ## Add a note
38
39 ```diff lang="typescript"
40 case "POST": {
41 + const { body } = (yield* request.json) as { body: string };
42 + const [note] = yield* db.insert(Notes).values({ body }).returning();
43 + return yield* HttpServerResponse.json({ note });
44 }
45 ```
46
47 ## Deploy
48
49 ```diff lang="sh"
50 +pnpm alchemy deploy
51 ```
52
53 Alchemy prints the Worker's `url`.
54
55 ## Create two tenants
56
57 ```diff lang="sh"
58 +curl -X POST $URL/tenants/acme
59 +curl -X POST $URL/tenants/globex
60 ```
61
62 Each call creates a database with the tenant's name. Names must be unique in your Turso organization.
63
64 ## Write a note
65
66 ```diff lang="sh"
67 +curl -X POST $URL/tenants/acme/notes -d '{"body":"hello from acme"}'
68 +curl $URL/tenants/acme/notes
69 ```
70
71 `acme` sees its note. `globex` has its own database, still empty:
72
73 ```diff lang="sh"
74 +curl $URL/tenants/globex/notes
75 ```
76
77 ## Clean up
78
79 ```diff lang="sh"
80 +pnpm alchemy destroy
81 ```
82
83 This deletes the `Tenants` group and every tenant database in it.
84
85 :::note
86 If you change the schema later, the template gets the new migration but existing tenants don't. See [Database per tenant](/turso/database-per-tenant#update-existing-tenants).
87 :::