Path: blob/master/src/packages/database/postgres/set-pg-params.ts
1503 views
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45// This is used in postgres-base to set postgres parameters for a single query6// https://www.postgresql.org/docs/10/sql-set.html78import { Client } from "pg";9import { getLogger } from "@cocalc/backend/logger";1011const L = getLogger("db:set-pg-params").debug;1213interface Opts {14client: Client;15query: string;16params: string[];17pg_params: { [key: string]: string };18cb: (err?, result?) => void;19}2021// Run the actual query after a setup query in a transaction; this is22// used by __do_query in postgres-base23export async function do_query_with_pg_params(opts: Opts): Promise<void> {24const { client, query, params, pg_params, cb } = opts;2526try {27await client.query("BEGIN");28for (const [k, v] of Object.entries(pg_params)) {29// SET LOCAL: only for this transaction!30// NOTE: interestingly, $1, $2 params do not work … but this isn't user-facing31const q = `SET LOCAL ${k} TO ${v}`;32L(`Setting query param: ${k}=${v}`);33await client.query(q);34}35const res = await client.query(query, params);36await client.query("COMMIT");37cb(undefined, res);38} catch (err) {39L(`ROLLBACK -- err=${err}`);40await client.query("ROLLBACK");41cb(err);42}43}444546