trilium/services/sql.js

262 lines
6.8 KiB
JavaScript
Raw Normal View History

2017-10-22 09:10:33 +08:00
"use strict";
2017-10-25 10:17:48 +08:00
const log = require('./log');
const dataDir = require('./data_dir');
const fs = require('fs');
const sqlite = require('sqlite');
const app_info = require('./app_info');
2017-12-28 05:44:15 +08:00
const resource_dir = require('./resource_dir');
async function createConnection() {
return await sqlite.open(dataDir.DOCUMENT_PATH, {Promise});
}
const dbConnected = createConnection();
2017-12-04 11:29:23 +08:00
let dbReadyResolve = null;
const dbReady = new Promise((resolve, reject) => {
dbConnected.then(async db => {
await execute("PRAGMA foreign_keys = ON");
dbReadyResolve = () => {
log.info("DB ready.");
resolve(db);
};
2017-12-04 11:29:23 +08:00
const tableResults = await getAll("SELECT name FROM sqlite_master WHERE type='table' AND name='notes'");
if (tableResults.length !== 1) {
2017-12-04 11:29:23 +08:00
log.info("Connected to db, but schema doesn't exist. Initializing schema ...");
2017-12-28 05:44:15 +08:00
const schema = fs.readFileSync(resource_dir.DB_INIT_DIR + '/schema.sql', 'UTF-8');
const notesSql = fs.readFileSync(resource_dir.DB_INIT_DIR + '/main_notes.sql', 'UTF-8');
const notesTreeSql = fs.readFileSync(resource_dir.DB_INIT_DIR + '/main_notes_tree.sql', 'UTF-8');
2018-01-08 12:52:32 +08:00
const imagesSql = fs.readFileSync(resource_dir.DB_INIT_DIR + '/main_images.sql', 'UTF-8');
const notesImageSql = fs.readFileSync(resource_dir.DB_INIT_DIR + '/main_notes_image.sql', 'UTF-8');
2017-12-04 11:29:23 +08:00
await doInTransaction(async () => {
await executeScript(schema);
await executeScript(notesSql);
await executeScript(notesTreeSql);
2018-01-08 12:52:32 +08:00
await executeScript(imagesSql);
await executeScript(notesImageSql);
2017-12-04 11:29:23 +08:00
2018-01-29 08:30:14 +08:00
const startNoteId = await getFirstValue("SELECT noteId FROM notes_tree WHERE parentNoteId = 'root' AND isDeleted = 0 ORDER BY notePosition");
await require('./options').initOptions(startNoteId);
await require('./sync_table').fillAllSyncRows();
2017-12-04 11:29:23 +08:00
});
log.info("Schema and initial content generated. Waiting for user to enter username/password to finish setup.");
2017-12-04 11:29:23 +08:00
// we don't resolve dbReady promise because user needs to setup the username and password to initialize
// the database
}
2017-12-04 11:29:23 +08:00
else {
if (!await isUserInitialized()) {
log.info("Login/password not initialized. DB not ready.");
return;
}
if (!await isDbUpToDate()) {
return;
2017-12-04 11:29:23 +08:00
}
resolve(db);
2017-12-04 11:29:23 +08:00
}
})
.catch(e => {
console.log("Error connecting to DB.", e);
process.exit(1);
});
});
2017-12-04 11:29:23 +08:00
function setDbReadyAsResolved() {
dbReadyResolve();
}
async function insert(table_name, rec, replace = false) {
2017-10-26 10:39:21 +08:00
const keys = Object.keys(rec);
if (keys.length === 0) {
log.error("Can't insert empty object into table " + table_name);
return;
}
const columns = keys.join(", ");
const questionMarks = keys.map(p => "?").join(", ");
const query = "INSERT " + (replace ? "OR REPLACE" : "") + " INTO " + table_name + "(" + columns + ") VALUES (" + questionMarks + ")";
const res = await execute(query, Object.values(rec));
return res.lastID;
}
async function replace(table_name, rec) {
return await insert(table_name, rec, true);
2017-10-30 10:22:30 +08:00
}
async function beginTransaction() {
return await wrap(async db => db.run("BEGIN"));
}
async function commit() {
return await wrap(async db => db.run("COMMIT"));
}
async function rollback() {
return await wrap(async db => db.run("ROLLBACK"));
2017-10-26 10:39:21 +08:00
}
async function getFirst(query, params = []) {
return await wrap(async db => db.get(query, ...params));
}
async function getFirstOrNull(query, params = []) {
const all = await wrap(async db => db.all(query, ...params));
2017-10-30 10:22:30 +08:00
return all.length > 0 ? all[0] : null;
}
async function getFirstValue(query, params = []) {
const row = await getFirstOrNull(query, params);
2017-10-30 10:22:30 +08:00
if (!row) {
return null;
}
return row[Object.keys(row)[0]];
}
async function getAll(query, params = []) {
return await wrap(async db => db.all(query, ...params));
}
2017-11-03 10:55:22 +08:00
async function getMap(query, params = []) {
const map = {};
const results = await getAll(query, params);
2017-11-03 10:55:22 +08:00
for (const row of results) {
const keys = Object.keys(row);
map[row[keys[0]]] = row[keys[1]];
}
return map;
}
async function getFirstColumn(query, params = []) {
2017-10-25 11:14:26 +08:00
const list = [];
const result = await getAll(query, params);
2017-10-25 11:14:26 +08:00
2017-12-15 11:16:26 +08:00
if (result.length === 0) {
return list;
}
const key = Object.keys(result[0])[0];
2017-10-25 11:14:26 +08:00
for (const row of result) {
list.push(row[key]);
}
return list;
}
async function execute(query, params = []) {
return await wrap(async db => db.run(query, ...params));
}
async function executeScript(query) {
return await wrap(async db => db.exec(query));
2017-10-16 05:31:49 +08:00
}
async function wrap(func) {
2017-11-22 11:11:27 +08:00
const thisError = new Error();
const db = await dbConnected;
2017-11-22 11:11:27 +08:00
try {
return await func(db);
}
catch (e) {
log.error("Error executing query. Inner exception: " + e.stack + thisError.stack);
thisError.message = e.stack;
throw thisError;
}
}
2017-11-29 07:33:23 +08:00
let transactionActive = false;
let transactionPromise = null;
async function doInTransaction(func) {
2017-11-29 07:33:23 +08:00
while (transactionActive) {
await transactionPromise;
}
const error = new Error(); // to capture correct stack trace in case of exception
2017-11-29 07:33:23 +08:00
transactionActive = true;
transactionPromise = new Promise(async (resolve, reject) => {
try {
await beginTransaction();
await func();
await commit();
2017-11-29 07:33:23 +08:00
transactionActive = false;
resolve();
}
catch (e) {
log.error("Error executing transaction, executing rollback. Inner exception: " + e.stack + error.stack);
await rollback();
2017-11-29 07:33:23 +08:00
transactionActive = false;
reject(e);
}
});
2017-11-29 07:33:23 +08:00
if (transactionActive) {
await transactionPromise;
}
}
async function isDbUpToDate() {
2018-01-29 08:30:14 +08:00
const dbVersion = parseInt(await getFirstValue("SELECT value FROM options WHERE name = 'db_version'"));
const upToDate = dbVersion >= app_info.db_version;
if (!upToDate) {
log.info("App db version is " + app_info.db_version + ", while db version is " + dbVersion + ". Migration needed.");
}
return upToDate;
}
async function isUserInitialized() {
2018-01-29 08:30:14 +08:00
const username = await getFirstValue("SELECT value FROM options WHERE name = 'username'");
return !!username;
}
module.exports = {
dbReady,
isUserInitialized,
insert,
2017-10-30 10:22:30 +08:00
replace,
getFirstValue,
getFirst,
getFirstOrNull,
getAll,
2017-11-03 10:55:22 +08:00
getMap,
getFirstColumn,
execute,
2017-10-16 05:31:49 +08:00
executeScript,
2017-12-04 11:29:23 +08:00
doInTransaction,
setDbReadyAsResolved,
isDbUpToDate
};