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/util/db-schema/client-db.ts
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45// Client side versions of some db functions, which are used, e.g., when setting fields.67import { is_array } from "../misc";8import { SCHEMA } from "./index";910const sha1 = require("sha1");11class ClientDB {12private _primary_keys_cache;13public r;1415constructor() {16this.sha1 = this.sha1.bind(this);17this._user_set_query_project_users =18this._user_set_query_project_users.bind(this);19this._user_set_query_project_change_after =20this._user_set_query_project_change_after.bind(this);21this._user_set_query_project_change_before =22this._user_set_query_project_change_before.bind(this);23this.primary_keys = this.primary_keys.bind(this);24this.r = {};25}2627sha1(...args) {28let v;29try {30v = args31.map((x) => (typeof x === "string" ? x : JSON.stringify(x)))32.join("");33} catch (err) {34if (console != null && console.warn != null) {35console.warn("args=", args);36}37throw err;38}39return sha1(v);40}4142_user_set_query_project_users(obj) {43// client allows anything; server may be more stringent44return obj.users;45}4647_user_set_query_project_change_after(_obj, _old_val, _new_val, cb) {48cb();49}50_user_set_query_project_change_before(_obj, _old_val, _new_val, cb) {51cb();52}5354// table is either name of a table in the default SCHEMA, or55// it can be a TableSchema<any> object (for a non-virtual table).56primary_keys(table) {57if (this._primary_keys_cache == null) {58this._primary_keys_cache = {};59}60const key = typeof table == "string" ? table : table.name;61if (this._primary_keys_cache[key] != null) {62return this._primary_keys_cache[key];63}64let t = typeof table == "string" ? SCHEMA[table] : table;65if (typeof t.virtual == "string") {66t = SCHEMA[t.virtual];67}68const v = t != null ? t.primary_key : undefined;69if (v == null) {70throw Error(71`primary key for table '${table}' must be explicitly specified in schema`72);73}74if (typeof v === "string") {75return (this._primary_keys_cache[key] = [v]);76} else if (is_array(v) && typeof v == "object") {77// the typeof is just to make typescript happy78if (v.length === 0) {79throw Error("at least one primary key must specified");80}81return (this._primary_keys_cache[key] = v);82} else {83throw Error("primary key must be a string or array of strings");84}85}86}8788export const client_db = new ClientDB();899091