Notes/src/services/sql_init.ts

223 lines
6.4 KiB
TypeScript
Raw Normal View History

import log from "./log.js";
import fs from "fs";
import resourceDir from "./resource_dir.js";
import sql from "./sql.js";
import { isElectron, deferred } from "./utils.js";
import optionService from "./options.js";
import port from "./port.js";
import BOption from "../becca/entities/boption.js";
import TaskContext from "./task_context.js";
import migrationService from "./migration.js";
import cls from "./cls.js";
import config from "./config.js";
import type { OptionRow } from "../becca/entities/rows.js";
import BNote from "../becca/entities/bnote.js";
import BBranch from "../becca/entities/bbranch.js";
import zipImportService from "./import/zip.js";
import becca_loader from "../becca/becca_loader.js";
import password from "./encryption/password.js";
import backup from "./backup.js";
const dbReady = deferred<void>();
2020-06-20 12:31:38 +02:00
function schemaExists() {
return !!sql.getValue(/*sql*/`SELECT name FROM sqlite_master
WHERE type = 'table' AND name = 'options'`);
}
2020-06-20 12:31:38 +02:00
function isDbInitialized() {
if (!schemaExists()) {
return false;
}
2020-06-20 12:31:38 +02:00
const initialized = sql.getValue("SELECT value FROM options WHERE name = 'initialized'");
2025-01-09 18:07:02 +02:00
return initialized === "true";
}
2020-07-02 22:57:17 +02:00
async function initDbConnection() {
2020-06-20 21:42:41 +02:00
if (!isDbInitialized()) {
log.info(`DB not initialized, please visit setup page` + (isElectron ? "" : ` - http://[your-server-host]:${port} to see instructions on how to initialize Trilium.`));
2020-06-20 21:42:41 +02:00
return;
}
2020-07-02 22:57:17 +02:00
await migrationService.migrateIfNecessary();
sql.execute('CREATE TEMP TABLE "param_list" (`paramId` TEXT NOT NULL PRIMARY KEY)');
sql.execute(`
CREATE TABLE IF NOT EXISTS "user_data"
(
tmpID INT,
username TEXT,
email TEXT,
userIDEncryptedDataKey TEXT,
userIDVerificationHash TEXT,
salt TEXT,
derivedKey TEXT,
isSetup TEXT DEFAULT "false",
UNIQUE (tmpID),
PRIMARY KEY (tmpID)
);`)
dbReady.resolve();
}
2025-03-31 23:20:14 +03:00
async function createInitialDatabase(preserveIds?: boolean) {
2020-06-20 12:31:38 +02:00
if (isDbInitialized()) {
throw new Error("DB is already initialized");
}
const schema = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/schema.sql`, "utf-8");
const demoFile = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/demo.zip`);
2018-04-02 22:33:54 -04:00
let rootNote!: BNote;
2020-07-02 21:08:18 +02:00
// We have to import async since options init requires keyboard actions which require translations.
const optionsInitService = (await import("./options_init.js")).default;
2020-06-20 12:31:38 +02:00
sql.transactional(() => {
2021-12-28 22:59:38 +01:00
log.info("Creating database schema ...");
2020-06-20 12:31:38 +02:00
sql.executeScript(schema);
becca_loader.load();
2021-05-02 22:47:57 +02:00
2021-12-28 22:59:38 +01:00
log.info("Creating root note ...");
rootNote = new BNote({
2025-01-09 18:07:02 +02:00
noteId: "root",
title: "root",
type: "text",
mime: "text/html"
}).save();
2025-01-09 18:07:02 +02:00
rootNote.setContent("");
2019-02-20 23:07:57 +01:00
new BBranch({
2025-01-09 18:07:02 +02:00
noteId: "root",
parentNoteId: "none",
isExpanded: true,
2019-10-19 12:36:16 +02:00
notePosition: 10
}).save();
optionsInitService.initDocumentOptions();
optionsInitService.initNotSyncedOptions(true, {});
optionsInitService.initStartupOptions();
password.resetPassword();
2020-07-02 21:08:18 +02:00
});
2021-05-30 21:21:20 +02:00
log.info("Importing demo content ...");
2025-01-09 18:07:02 +02:00
const dummyTaskContext = new TaskContext("no-progress-reporting", "import", false);
2025-03-31 23:20:14 +03:00
await zipImportService.importZip(dummyTaskContext, demoFile, rootNote, {
preserveIds
});
2019-02-24 12:24:28 +01:00
2020-07-02 21:08:18 +02:00
sql.transactional(() => {
2023-05-07 15:23:46 +02:00
// this needs to happen after ZIP import,
// the previous solution was to move option initialization here, but then the important parts of initialization
// are not all in one transaction (because ZIP import is async and thus not transactional)
2018-04-02 22:33:54 -04:00
const startNoteId = sql.getValue("SELECT noteId FROM branches WHERE parentNoteId = 'root' AND isDeleted = 0 ORDER BY notePosition");
2025-01-09 18:07:02 +02:00
optionService.setOption(
"openNoteContexts",
JSON.stringify([
{
notePath: startNoteId,
active: true
}
])
);
2018-04-02 22:33:54 -04:00
});
log.info("Schema and initial content generated.");
2018-04-02 22:33:54 -04:00
2020-06-20 12:31:38 +02:00
initDbConnection();
}
2025-01-09 18:07:02 +02:00
async function createDatabaseForSync(options: OptionRow[], syncServerHost = "", syncProxy = "") {
log.info("Creating database for sync");
2020-06-20 12:31:38 +02:00
if (isDbInitialized()) {
throw new Error("DB is already initialized");
}
const schema = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/schema.sql`, "utf8");
// We have to import async since options init requires keyboard actions which require translations.
const optionsInitService = (await import("./options_init.js")).default;
2020-06-20 12:31:38 +02:00
sql.transactional(() => {
sql.executeScript(schema);
optionsInitService.initNotSyncedOptions(false, { syncServerHost, syncProxy });
// document options required for sync to kick off
for (const opt of options) {
new BOption(opt).save();
}
});
log.info("Schema and not synced options generated.");
}
2020-06-20 21:42:41 +02:00
function setDbAsInitialized() {
2020-06-20 12:31:38 +02:00
if (!isDbInitialized()) {
2025-01-09 18:07:02 +02:00
optionService.setOption("initialized", "true");
2020-06-20 12:31:38 +02:00
initDbConnection();
2019-11-30 11:36:36 +01:00
}
}
2022-02-01 21:36:52 +01:00
function optimize() {
log.info("Optimizing database");
const start = Date.now();
2022-02-01 21:36:52 +01:00
sql.execute("PRAGMA optimize");
log.info(`Optimization finished in ${Date.now() - start}ms.`);
2022-02-01 21:36:52 +01:00
}
function getDbSize() {
2024-04-03 20:47:41 +03:00
return sql.getValue<number>("SELECT page_count * page_size / 1000 as size FROM pragma_page_count(), pragma_page_size()");
}
function initializeDb() {
cls.init(initDbConnection);
log.info(`DB size: ${getDbSize()} KB`);
dbReady.then(() => {
if (config.General && config.General.noBackup === true) {
log.info("Disabling scheduled backups.");
return;
}
setInterval(() => backup.regularBackup(), 4 * 60 * 60 * 1000);
// kickoff first backup soon after start up
setTimeout(() => backup.regularBackup(), 5 * 60 * 1000);
// optimize is usually inexpensive no-op, so running it semi-frequently is not a big deal
setTimeout(() => optimize(), 60 * 60 * 1000);
setInterval(() => optimize(), 10 * 60 * 60 * 1000);
});
}
2019-01-15 20:00:24 +01:00
export default {
dbReady,
schemaExists,
isDbInitialized,
createInitialDatabase,
createDatabaseForSync,
setDbAsInitialized,
getDbSize,
initializeDb
2020-06-17 23:03:46 +02:00
};