CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/database/postgres/schema/table.ts
Views: 687
1
import { client_db } from "@cocalc/util/schema";
2
import getLogger from "@cocalc/backend/logger";
3
import { quoteField } from "./util";
4
import { pgType } from "./pg-type";
5
import type { Client } from "@cocalc/database/pool";
6
import { createIndexes } from "./indexes";
7
import type { TableSchema } from "./types";
8
9
const log = getLogger("db:schema:table");
10
11
export function primaryKeys(table: string | TableSchema): string[] {
12
return client_db.primary_keys(table);
13
}
14
15
export function primaryKey(table: string | TableSchema): string {
16
const v = primaryKeys(table);
17
if (v.length != 1) {
18
throw Error(
19
`compound primary key tables not yet supported - table=${table}`,
20
);
21
}
22
return v[0];
23
}
24
25
export async function createTable(
26
db: Client,
27
schema: TableSchema,
28
): Promise<void> {
29
log.debug("createTable", schema.name, " creating SQL query");
30
if (schema.virtual) {
31
throw Error(`table '${schema.name}' is virtual`);
32
return;
33
}
34
const columns: string[] = [];
35
const primary_keys = primaryKeys(schema);
36
for (const column in schema.fields) {
37
const info = schema.fields[column];
38
let s = `${quoteField(column)} ${pgType(info)}`;
39
if (info.unique) {
40
s += " UNIQUE";
41
}
42
if (info.not_null) {
43
s += " NOT NULL";
44
}
45
if (info.pg_check) {
46
s += " " + info.pg_check;
47
}
48
columns.push(s);
49
}
50
const query = `CREATE TABLE ${schema.name} (${columns.join(
51
", ",
52
)}, PRIMARY KEY(${primary_keys.join(", ")}))`;
53
log.debug("createTable", schema.name, " running query...", query);
54
await db.query(query);
55
await createIndexes(db, schema);
56
}
57
58