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/query.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
// Nice async/await interface to doing basic queries.
7
8
import { callback } from "awaiting";
9
10
const { one_result, all_results } = require("../postgres-base");
11
12
import { PostgreSQL, QueryWhere } from "./types";
13
14
interface QueryOpts {
15
db: PostgreSQL;
16
query?: string;
17
select?: string[];
18
set?: { [key: string]: any };
19
jsonb_set?: object;
20
jsonb_merge?: object;
21
table?: string;
22
where?: QueryWhere;
23
one?: boolean; // if true get back one result; if false get list of all results.
24
order_by?: string;
25
limit?: number;
26
params?: any[];
27
timeout_s?: number;
28
}
29
30
export async function query(opts: QueryOpts): Promise<any> {
31
return await callback(
32
opts.one ? one_query : all_query,
33
opts.db,
34
opts.select,
35
opts.table,
36
opts.where,
37
opts.set,
38
opts.query,
39
opts.jsonb_set,
40
opts.jsonb_merge,
41
opts.order_by,
42
opts.limit,
43
opts.params,
44
opts.timeout_s
45
);
46
}
47
48
function all_query(
49
db,
50
select,
51
table,
52
where,
53
set,
54
query,
55
jsonb_set,
56
jsonb_merge,
57
order_by,
58
limit,
59
params,
60
timeout_s,
61
cb
62
): void {
63
db._query({
64
select,
65
table,
66
where,
67
set,
68
query,
69
jsonb_set,
70
jsonb_merge,
71
order_by,
72
limit,
73
params,
74
timeout_s,
75
cb: all_results(cb),
76
});
77
}
78
79
function one_query(
80
db,
81
select,
82
table,
83
where,
84
set,
85
query,
86
jsonb_set,
87
jsonb_merge,
88
order_by,
89
limit,
90
params,
91
timeout_s,
92
cb
93
): void {
94
db._query({
95
select,
96
table,
97
where,
98
set,
99
query,
100
jsonb_set,
101
jsonb_merge,
102
order_by,
103
limit,
104
params,
105
timeout_s,
106
cb: one_result(cb),
107
});
108
}
109
110