@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, 06:00 UTC

main
mdx 88 lines 2.46 KB
Raw
1 ---
2 title: Database per tenant
3 description: Give each customer their own Turso database.
4 ---
5
6 Give each customer their own database. Their data stays separate, and removing a customer is just deleting their database.
7
8 The [tutorial](/turso/tutorial/part-1) builds this step by step.
9
10 ## Give a Worker a group
11
12 ```typescript
13 const tenants = yield* Turso.ManageDatabases(Tenants);
14 ```
15
16 Add `Turso.ManageDatabasesHttp` to the Worker. The Worker gets two tokens:
17
18 - An API token that can create and delete databases, but only in `Tenants`.
19 - A database token that can run SQL on every database in `Tenants`.
20
21 Your own Turso API token stays on your machine.
22
23 ## Create a tenant
24
25 ```typescript
26 const acme = yield* tenants.create("acme");
27 ```
28
29 Names must be unique in your organization. Add a prefix if several stages or apps share it.
30
31 ## Start every tenant from a template
32
33 ```typescript
34 const acme = yield* tenants.create("acme", {
35 seed: { type: "database", name: yield* templateName },
36 });
37 ```
38
39 Copy a template database so new tenants start with your tables. See [Create the template database](/turso/tutorial/part-1).
40
41 ## Query a tenant
42
43 ```typescript
44 const sql = yield* SQL.LibSQL(tenants.connect("acme"));
45 const notes = yield* sql`SELECT * FROM notes`;
46 ```
47
48 `connect` works with [Drizzle.LibSQL](/sql/drizzle/libsql) too. The connection opens on the first query and closes when the request ends.
49
50 ## List and delete tenants
51
52 ```typescript
53 const all = yield* tenants.list();
54 const acme = yield* tenants.get("acme"); // undefined when missing
55 yield* tenants.delete("acme");
56 ```
57
58 `delete` doesn't fail if the database is already gone.
59
60 ## Update existing tenants
61
62 New migrations run on the template, not on tenants you already created.
63
64 If you know your tenants ahead of time, create each one in the Stack so every deploy updates it:
65
66 ```typescript
67 for (const name of ["acme", "globex"]) {
68 yield* Turso.Database(name, { name, group: group.name, migrations: "./migrations" });
69 }
70 ```
71
72 For tenants your app creates, run the change on each one from the Worker. Write it so running it twice is safe:
73
74 ```typescript
75 for (const { name } of yield* tenants.list()) {
76 const sql = yield* SQL.LibSQL(tenants.connect(name));
77 yield* sql`CREATE INDEX IF NOT EXISTS notes_created ON notes (created_at)`;
78 }
79 ```
80
81 ## Destroying the Stack
82
83 Destroying the Stack deletes the group and every tenant database in it.
84
85 ## Where next
86
87 - [ManageDatabases reference](/providers/turso/reference/group#managedatabases)
88 - [Tokens](/turso/tokens)