Path: blob/master/src/packages/util/db-schema/client-db.ts
5787 views
/*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";9import { sha1 } from "@cocalc/util/misc";1011class 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_manage_users_owner_only =20this._user_set_query_project_manage_users_owner_only.bind(this);21this._user_set_query_project_change_after =22this._user_set_query_project_change_after.bind(this);23this._user_set_query_project_change_before =24this._user_set_query_project_change_before.bind(this);25this.primary_keys = this.primary_keys.bind(this);26this.r = {};27}2829sha1(...args) {30let v;31try {32v = args33.map((x) => (typeof x === "string" ? x : JSON.stringify(x)))34.join("");35} catch (err) {36if (console != null && console.warn != null) {37console.warn("args=", args);38}39throw err;40}41return sha1(v);42}4344_user_set_query_project_users(obj) {45// client allows anything; server may be more stringent46return obj.users;47}4849_user_set_query_project_manage_users_owner_only(obj) {50return obj.manage_users_owner_only;51}5253_user_set_query_project_change_after(_obj, _old_val, _new_val, cb) {54cb();55}56_user_set_query_project_change_before(_obj, _old_val, _new_val, cb) {57cb();58}5960// table is either name of a table in the default SCHEMA, or61// it can be a TableSchema<any> object (for a non-virtual table).62primary_keys(table) {63if (this._primary_keys_cache == null) {64this._primary_keys_cache = {};65}66const key = typeof table == "string" ? table : table.name;67if (this._primary_keys_cache[key] != null) {68return this._primary_keys_cache[key];69}70let t = typeof table == "string" ? SCHEMA[table] : table;71if (typeof t.virtual == "string") {72t = SCHEMA[t.virtual];73}74const v = t != null ? t.primary_key : undefined;75if (v == null) {76throw Error(77`primary key for table '${table}' must be explicitly specified in schema`,78);79}80if (typeof v === "string") {81return (this._primary_keys_cache[key] = [v]);82} else if (is_array(v) && typeof v == "object") {83// the typeof is just to make typescript happy84if (v.length === 0) {85throw Error("at least one primary key must specified");86}87return (this._primary_keys_cache[key] = v);88} else {89throw Error("primary key must be a string or array of strings");90}91}92}9394export const client_db = new ClientDB();959697