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