-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtables.ts
More file actions
72 lines (69 loc) · 2.08 KB
/
tables.ts
File metadata and controls
72 lines (69 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { Database } from "@tableland/sdk";
import { randomUUID } from "crypto";
import { eq } from "drizzle-orm";
import { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../schema";
import {
NewTable,
projectTables,
tables,
teamProjects,
teams,
} from "../schema";
import { slugify } from "./utils";
export function initTables(
db: DrizzleD1Database<typeof schema>,
tbl: Database,
) {
return {
createTable: async function (
projectId: string,
name: string,
description: string,
schema: string,
) {
const tableId = randomUUID();
const slug = slugify(name);
const { sql: tableSql, params: tableParams } = db
.insert(tables)
.values({ id: tableId, name, description, schema, slug })
.toSQL();
const { sql: projectTableSql, params: projectTableParams } = db
.insert(projectTables)
.values({ tableId, projectId })
.toSQL();
await tbl.batch([
tbl.prepare(projectTableSql).bind(projectTableParams),
tbl.prepare(tableSql).bind(tableParams),
]);
const table: NewTable = { id: tableId, name, description, schema, slug };
return table;
},
tablesByProjectId: async function (projectId: string) {
const res = await db
.select({ tables })
.from(projectTables)
.innerJoin(tables, eq(projectTables.tableId, tables.id))
.where(eq(projectTables.projectId, projectId))
.orderBy(tables.name)
.all();
const mapped = res.map((r) => r.tables);
return mapped as unknown as schema.Table[];
},
tableTeam: async function (tableId: string) {
const res = await db
.select({ teams })
.from(tables)
.innerJoin(projectTables, eq(tables.id, projectTables.tableId))
.innerJoin(
teamProjects,
eq(projectTables.projectId, teamProjects.projectId),
)
.innerJoin(teams, eq(teamProjects.teamId, teams.id))
.where(eq(tables.id, tableId))
.orderBy(tables.name)
.get();
return res?.teams;
},
};
}