Notes/src/services/sql.js

275 lines
6.2 KiB
JavaScript
Raw Normal View History

2017-10-21 21:10:33 -04:00
"use strict";
2017-10-24 22:17:48 -04:00
const log = require('./log');
const cls = require('./cls');
2020-06-20 21:42:41 +02:00
const Database = require('better-sqlite3');
const dataDir = require('./data_dir');
2020-06-20 21:42:41 +02:00
const dbConnection = new Database(dataDir.DOCUMENT_PATH);
dbConnection.pragma('journal_mode = WAL');
2017-12-03 22:29:23 -05:00
2020-06-15 17:56:53 +02:00
[`exit`, `SIGINT`, `SIGUSR1`, `SIGUSR2`, `SIGTERM`].forEach(eventType => {
process.on(eventType, () => {
if (dbConnection) {
// closing connection is especially important to fold -wal file into the main DB file
// (see https://sqlite.org/tempfiles.html for details)
dbConnection.close();
}
});
});
2020-06-20 12:31:38 +02:00
function insert(tableName, rec, replace = false) {
2017-10-25 22:39:21 -04:00
const keys = Object.keys(rec);
if (keys.length === 0) {
log.error("Can't insert empty object into table " + tableName);
2017-10-25 22:39:21 -04:00
return;
}
const columns = keys.join(", ");
const questionMarks = keys.map(p => "?").join(", ");
const query = "INSERT " + (replace ? "OR REPLACE" : "") + " INTO " + tableName + "(" + columns + ") VALUES (" + questionMarks + ")";
2020-06-20 12:31:38 +02:00
const res = execute(query, Object.values(rec));
2020-06-17 23:03:46 +02:00
return res.lastInsertRowid;
}
2020-06-20 12:31:38 +02:00
function replace(tableName, rec) {
return insert(tableName, rec, true);
}
2020-06-20 12:31:38 +02:00
function upsert(tableName, primaryKey, rec) {
const keys = Object.keys(rec);
if (keys.length === 0) {
log.error("Can't upsert empty object into table " + tableName);
return;
}
const columns = keys.join(", ");
2020-06-17 23:03:46 +02:00
const questionMarks = keys.map(colName => "@" + colName).join(", ");
2020-06-17 23:03:46 +02:00
const updateMarks = keys.map(colName => `${colName} = @${colName}`).join(", ");
const query = `INSERT INTO ${tableName} (${columns}) VALUES (${questionMarks})
ON CONFLICT (${primaryKey}) DO UPDATE SET ${updateMarks}`;
2020-06-17 23:03:46 +02:00
for (const idx in rec) {
if (rec[idx] === true || rec[idx] === false) {
rec[idx] = rec[idx] ? 1 : 0;
}
}
2020-06-20 12:31:38 +02:00
execute(query, rec);
2017-10-29 22:22:30 -04:00
}
2020-06-17 23:03:46 +02:00
const statementCache = {};
function stmt(sql) {
if (!(sql in statementCache)) {
statementCache[sql] = dbConnection.prepare(sql);
}
return statementCache[sql];
}
function beginTransaction() {
return stmt("BEGIN").run();
}
2020-06-17 23:03:46 +02:00
function commit() {
return stmt("COMMIT").run();
}
2020-06-17 23:03:46 +02:00
function rollback() {
return stmt("ROLLBACK").run();
2017-10-25 22:39:21 -04:00
}
2020-06-20 12:31:38 +02:00
function getRow(query, params = []) {
2020-06-20 21:42:41 +02:00
return wrap(query, s => s.get(params));
}
2020-06-20 12:31:38 +02:00
function getRowOrNull(query, params = []) {
const all = getRows(query, params);
2017-10-29 22:22:30 -04:00
return all.length > 0 ? all[0] : null;
}
2020-06-20 12:31:38 +02:00
function getValue(query, params = []) {
const row = getRowOrNull(query, params);
2017-10-29 22:22:30 -04:00
if (!row) {
return null;
}
return row[Object.keys(row)[0]];
}
const PARAM_LIMIT = 900; // actual limit is 999
// this is to overcome 999 limit of number of query parameters
2020-06-20 12:31:38 +02:00
function getManyRows(query, params) {
let results = [];
while (params.length > 0) {
const curParams = params.slice(0, Math.min(params.length, PARAM_LIMIT));
params = params.slice(curParams.length);
2020-06-17 23:03:46 +02:00
const curParamsObj = {};
let j = 1;
for (const param of curParams) {
curParamsObj['param' + j++] = param;
}
let i = 1;
2020-06-17 23:03:46 +02:00
const questionMarks = curParams.map(() => ":param" + i++).join(",");
const curQuery = query.replace(/\?\?\?/g, questionMarks);
const subResults = dbConnection.prepare(curQuery).all(curParamsObj);
results = results.concat(subResults);
}
return results;
}
2020-06-20 12:31:38 +02:00
function getRows(query, params = []) {
2020-06-20 21:42:41 +02:00
return wrap(query, s => s.all(params));
}
function iterateRows(query, params = []) {
return stmt(query).iterate(params);
}
2020-06-20 12:31:38 +02:00
function getMap(query, params = []) {
2017-11-02 22:55:22 -04:00
const map = {};
2020-06-20 12:31:38 +02:00
const results = getRows(query, params);
2017-11-02 22:55:22 -04:00
for (const row of results) {
const keys = Object.keys(row);
map[row[keys[0]]] = row[keys[1]];
}
return map;
}
2020-06-20 12:31:38 +02:00
function getColumn(query, params = []) {
2017-10-24 23:14:26 -04:00
const list = [];
2020-06-20 12:31:38 +02:00
const result = getRows(query, params);
2017-10-24 23:14:26 -04:00
2017-12-14 22:16:26 -05:00
if (result.length === 0) {
return list;
}
const key = Object.keys(result[0])[0];
2017-10-24 23:14:26 -04:00
for (const row of result) {
list.push(row[key]);
}
return list;
}
2020-06-20 12:31:38 +02:00
function execute(query, params = []) {
startTransactionIfNecessary();
2020-06-20 21:42:41 +02:00
return wrap(query, s => s.run(params));
}
2020-06-20 12:31:38 +02:00
function executeWithoutTransaction(query, params = []) {
dbConnection.run(query, params);
}
2020-06-20 12:31:38 +02:00
function executeMany(query, params) {
startTransactionIfNecessary();
2020-06-20 12:31:38 +02:00
getManyRows(query, params);
2019-11-01 22:09:51 +01:00
}
2020-06-20 12:31:38 +02:00
function executeScript(query) {
startTransactionIfNecessary();
2020-06-20 21:42:41 +02:00
return dbConnection.exec(query);
2017-10-15 17:31:49 -04:00
}
2020-06-20 21:42:41 +02:00
function wrap(query, func) {
const startTimestamp = Date.now();
2020-06-20 21:42:41 +02:00
const result = func(stmt(query));
2017-11-21 22:11:27 -05:00
2020-06-20 21:42:41 +02:00
const milliseconds = Date.now() - startTimestamp;
if (milliseconds >= 20) {
2020-06-20 21:42:41 +02:00
if (query.includes("WITH RECURSIVE")) {
log.info(`Slow recursive query took ${milliseconds}ms.`);
}
else {
log.info(`Slow query took ${milliseconds}ms: ${query}`);
}
}
2020-06-20 21:42:41 +02:00
return result;
}
2020-06-20 12:31:38 +02:00
function startTransactionIfNecessary() {
2020-06-20 21:42:41 +02:00
if (!cls.get('isTransactional') || dbConnection.inTransaction) {
return;
}
2020-06-20 12:31:38 +02:00
beginTransaction();
}
2020-06-20 12:31:38 +02:00
function transactional(func) {
// if the CLS is already transactional then the whole transaction is handled by higher level transactional() call
2020-06-15 17:56:53 +02:00
if (cls.get('isTransactional')) {
2020-06-20 12:31:38 +02:00
return func();
}
2020-06-15 17:56:53 +02:00
cls.set('isTransactional', true); // this signals that transaction will be needed if there's a write operation
try {
2020-06-20 12:31:38 +02:00
const ret = func();
2020-06-20 21:42:41 +02:00
if (dbConnection.inTransaction) {
2020-06-20 12:31:38 +02:00
commit();
// note that sync rows sent from this action will be sent again by scheduled periodic ping
2020-01-31 22:32:24 +01:00
require('./ws.js').sendPingToAllClients();
}
return ret;
}
catch (e) {
2020-06-20 21:42:41 +02:00
if (dbConnection.inTransaction) {
2020-06-20 12:31:38 +02:00
rollback();
2020-06-14 00:35:53 +02:00
}
throw e;
}
finally {
cls.namespace.set('isTransactional', false);
2017-11-28 18:33:23 -05:00
}
}
module.exports = {
dbConnection,
insert,
2017-10-29 22:22:30 -04:00
replace,
getValue,
getRow,
getRowOrNull,
getRows,
2020-06-20 21:42:41 +02:00
iterateRows,
getManyRows,
2017-11-02 22:55:22 -04:00
getMap,
getColumn,
execute,
2020-06-14 00:35:53 +02:00
executeWithoutTransaction,
2019-11-01 22:09:51 +01:00
executeMany,
2017-10-15 17:31:49 -04:00
executeScript,
transactional,
upsert
};