Notes/src/share/sql.ts

40 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-10-16 22:13:34 +02:00
"use strict";
import Database from "better-sqlite3";
import dataDir from "../services/data_dir.js";
import sql_init from "../services/sql_init.js";
2021-10-16 22:13:34 +02:00
let dbConnection!: Database.Database;
2021-10-16 22:13:34 +02:00
sql_init.dbReady.then(() => {
dbConnection = new Database(dataDir.DOCUMENT_PATH, { readonly: true });
[`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();
}
});
2021-10-16 22:13:34 +02:00
});
});
2024-04-09 21:50:47 +03:00
function getRawRows<T>(query: string, params = []): T[] {
return dbConnection.prepare(query).raw().all(params) as T[];
2021-10-16 22:13:34 +02:00
}
2024-04-09 22:13:01 +03:00
function getRow<T>(query: string, params: string[] = []): T {
2024-04-09 21:50:47 +03:00
return dbConnection.prepare(query).get(params) as T;
2021-10-16 22:13:34 +02:00
}
function getColumn<T>(query: string, params: string[] = []): T[] {
2024-04-09 21:50:47 +03:00
return dbConnection.prepare(query).pluck().all(params) as T[];
2021-10-16 22:13:34 +02:00
}
export default {
2021-10-16 22:13:34 +02:00
getRawRows,
2021-12-23 12:54:21 +01:00
getRow,
2021-10-16 22:13:34 +02:00
getColumn
};