Files
dougal-software/lib/www/server/lib/db/connection.js
D. Berge d3336c6cf7 Add fetchRow DB function.
Helper function to fetch a row at a time using a cursor.
2022-03-07 21:16:43 +01:00

80 lines
1.7 KiB
JavaScript

const { Pool, Client, types } = require('pg');
const cfg = require("../config");
const pool = new Pool(cfg.db);
const numericTypeOIDs = [ 20, 21, 23, 700, 701, 1700 ];
numericTypeOIDs.forEach(oid => {
types.setTypeParser(oid, function (v) { return Number(v); });
})
// const jsonTypeOIDs = [ 114, 3802 ];
// jsonTypeOIDs.forEach(oid => {
// types.setTypeParser(oid, function (v) { return JSON.parse(v); });
// })
const transaction = {
async begin (client) {
return await client.query("BEGIN;");
},
async commit (client) {
return await client.query("COMMIT;");
},
async rollback (client) {
return await client.query("ROLLBACK;");
}
};
async function setSurvey (projectId, client) {
if (!client) {
client = await pool.connect();
}
if (projectId) {
await client.query("CALL set_survey($1);", [projectId]);
} else {
await client.query("SET search_path TO public;");
}
return client;
}
async function schema2pid (schema, client) {
if (!client) {
client = await pool.connect();
}
const res = await client.query("SELECT pid FROM projects WHERE schema = $1", [schema]);
client.release();
return res.rows[0] && res.rows[0].pid;;
}
/** Fetch one row from a database cursor.
*
* @a cursor A query cursor
*
* @returns A row object if there are any rows left to consume.
* @returns Undefined when all the rows (if any) have been consumed.
*/
async function fetchRow (cursor) {
return new Promise((resolve, reject) => {
cursor.read(1, (err, rows) => {
if (err) {
reject(err);
} else if (rows.length) {
resolve(rows[0]);
} else {
resolve(); // undefined
}
});
});
}
module.exports = {
pool,
transaction,
setSurvey,
schema2pid,
fetchRow
};