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/set-pg-params.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
// This is used in postgres-base to set postgres parameters for a single query
7
// https://www.postgresql.org/docs/10/sql-set.html
8
9
import { Client } from "pg";
10
import { getLogger } from "@cocalc/backend/logger";
11
12
const L = getLogger("db:set-pg-params").debug;
13
14
interface Opts {
15
client: Client;
16
query: string;
17
params: string[];
18
pg_params: { [key: string]: string };
19
cb: (err?, result?) => void;
20
}
21
22
// Run the actual query after a setup query in a transaction; this is
23
// used by __do_query in postgres-base
24
export async function do_query_with_pg_params(opts: Opts): Promise<void> {
25
const { client, query, params, pg_params, cb } = opts;
26
27
try {
28
await client.query("BEGIN");
29
for (const [k, v] of Object.entries(pg_params)) {
30
// SET LOCAL: only for this transaction!
31
// NOTE: interestingly, $1, $2 params do not work … but this isn't user-facing
32
const q = `SET LOCAL ${k} TO ${v}`;
33
L(`Setting query param: ${k}=${v}`);
34
await client.query(q);
35
}
36
const res = await client.query(query, params);
37
await client.query("COMMIT");
38
cb(undefined, res);
39
} catch (err) {
40
L(`ROLLBACK -- err=${err}`);
41
await client.query("ROLLBACK");
42
cb(err);
43
}
44
}
45
46