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