Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
standalone/backup import: skip SQLite integrity check for imported databases while in standalone mode
Adorian Dorancfd988dbd111
diff --git a/apps/standalone/src/lightweight/database_restore.spec.ts b/apps/standalone/src/lightweight/database_restore.spec.tsindex 152520795f..f55d55afe2 100644--- a/apps/standalone/src/lightweight/database_restore.spec.ts+++ b/apps/standalone/src/lightweight/database_restore.spec.ts@@ -63,6 +63,8 @@ async function containerOf(payload: Uint8Array, options: { passphrase?: string;/** A pool that keeps its databases in memory and answers the checks however the test says. */function fakePool() {const files = new Map<string, Uint8Array>();+ /** Every statement the checks put to the candidate, so a test can say what was not asked. */+ const asked: string[] = [];const answers = {integrity: "ok",tables: [ "options", "notes", "branches", "blobs" ],@@ -76,10 +78,12 @@ function fakePool() {}}selectValue(sql: string, params?: unknown[]) {+ asked.push(sql);if (sql.includes("quick_check")) return answers.integrity;return answers.options[String((params ?? [])[0])];}- selectValues() {+ selectValues(sql: string) {+ asked.push(sql);return answers.tables;}close() { /* nothing to release */ }@@ -102,7 +106,7 @@ function fakePool() {}};- return { files, answers, pool: pool as unknown as SAHPoolUtil };+ return { asked, files, answers, pool: pool as unknown as SAHPoolUtil };}function concat(chunks: Uint8Array[]): Uint8Array {@@ -229,6 +233,20 @@ describe("restoring from a picked backup", () => {expect(files.get(CANDIDATE_NAME)).toEqual(original);});+ it("checks the database without reading all of it", async () => {+ const { asked, pool } = fakePool();+ const { target } = fakeTarget(pool);++ await restoreDatabase(target, new Blob([ databaseBytes() ]));++ // The one check whose cost grows with the database is left out here, where every page would+ // come back through the pool into a WebAssembly engine.+ expect(asked.some((sql) => sql.includes("quick_check"))).toBe(false);+ // The rest is still asked: the schema and the version are what accept a database.+ expect(asked.some((sql) => sql.includes("sqlite_master"))).toBe(true);+ expect(asked.some((sql) => sql.includes("options"))).toBe(true);+ });+it("says what it is doing as it goes", async () => {const { pool } = fakePool();const { target } = fakeTarget(pool);diff --git a/apps/standalone/src/lightweight/database_restore.ts b/apps/standalone/src/lightweight/database_restore.tsindex 6590010c5d..b52add06d9 100644--- a/apps/standalone/src/lightweight/database_restore.ts+++ b/apps/standalone/src/lightweight/database_restore.ts@@ -180,12 +180,23 @@ async function stageCandidate(await Promise.all([ unwrapped, imported ]);}-/** Opens the candidate and puts it through the checks every platform shares. */+/**+ * Opens the candidate and puts it through the checks every platform shares, minus the scan.+ *+ * `PRAGMA quick_check` reads every page, and here every page comes back through the pool's+ * synchronous access handles into a WebAssembly database engine, which is the slowest reader of the+ * three platforms and the one with a user watching a setup screen that cannot say how far along it+ * is. What it would find is largely accounted for already: a container's payload is checked against+ * a SHA-256 recorded when the backup was written, and any file is opened, its schema parsed and its+ * options read before it is accepted. The remaining case, a plain `.db` damaged somewhere no schema+ * read reaches, surfaces the way it would in any other Trilium, which never scans its database+ * either except when asked to from the options screen.+ */function validate(pool: SAHPoolUtil, candidate: string): DatabaseValidation {const db = new pool.OpfsSAHPoolDb(candidate);try {- return validateDatabase(candidateOf(db));+ return validateDatabase(candidateOf(db), { skipIntegrityCheck: true });} catch (e) {// What a database too damaged to query throws is this driver's business, not the checks'.return {diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 6ffa5682fb..16d562257e 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -29,7 +29,8 @@ export {type DatabaseValidation,looksLikeSqlite,OLDEST_SUPPORTED_DB_VERSION,- validateDatabase+ validateDatabase,+ type ValidationOptions} from "./services/database_validation";export * as protected_session from "./services/protected_session";export { default as data_encryption } from "./services/encryption/data_encryption";diff --git a/packages/trilium-core/src/services/database_validation.spec.ts b/packages/trilium-core/src/services/database_validation.spec.tsindex c084e8dd44..6c7bb7311d 100644--- a/packages/trilium-core/src/services/database_validation.spec.ts+++ b/packages/trilium-core/src/services/database_validation.spec.ts@@ -107,6 +107,27 @@ describe("validating a candidate database", () => {.toMatchObject({ valid: false, rejection: "not-a-trilium-database" });});+ it("leaves the scan out when asked to, and keeps every other check", () => {+ const asked: string[] = [];+ const watched: CandidateDatabase = {+ integrityCheck: () => { asked.push("integrity"); return "malformed database schema"; },+ tableNames: () => { asked.push("tables"); return TRILIUM_TABLES; },+ option: (name) => {+ asked.push(`option:${name}`);+ return name === "initialized" ? "true" : String(appInfo.dbVersion);+ }+ };++ // Accepted despite an integrity check that would have failed, because it is never put.+ expect(validateDatabase(watched, { skipIntegrityCheck: true }))+ .toMatchObject({ valid: true, dbVersion: appInfo.dbVersion });+ expect(asked).toEqual([ "tables", "option:initialized", "option:dbVersion" ]);++ // Nothing else is waived: a database that is not ours is still refused.+ expect(validateDatabase(candidate({ tables: [ "recipes" ] }), { skipIntegrityCheck: true }))+ .toMatchObject({ valid: false, rejection: "not-a-trilium-database" });+ });+it("asks the cheapest questions first, so a damaged database is not read for its options", () => {const asked: string[] = [];const damaged: CandidateDatabase = {diff --git a/packages/trilium-core/src/services/database_validation.ts b/packages/trilium-core/src/services/database_validation.tsindex c672f91acf..694dd4836d 100644--- a/packages/trilium-core/src/services/database_validation.ts+++ b/packages/trilium-core/src/services/database_validation.ts@@ -49,7 +49,10 @@ export type DatabaseValidation =* Each is a plain read: nothing here writes, and nothing needs the whole database at once.*/export interface CandidateDatabase {- /** What `PRAGMA quick_check` answers, which is `"ok"` and nothing else when all is well. */+ /**+ * What `PRAGMA quick_check` answers, which is `"ok"` and nothing else when all is well. Not+ * asked at all when {@link ValidationOptions.skipIntegrityCheck} is set.+ */integrityCheck(): string;/** The names of the tables it has. */tableNames(): string[];@@ -79,18 +82,30 @@ export function looksLikeSqlite(head: Uint8Array): boolean {return true;}+/** What a platform may leave out of the checks, and why it is allowed to. */+export interface ValidationOptions {+ /**+ * Leaves out `PRAGMA quick_check`, which is the only check whose cost grows with the database.+ *+ * For a platform where that scan is prohibitive, and where the bytes have already been accounted+ * for by other means. Everything else here is a handful of small reads and is always done.+ */+ skipIntegrityCheck?: boolean;+}+/*** Puts an open candidate through every check, in the order that answers most cheaply first.** `PRAGMA quick_check` reads the whole database, which for a large one is not instant. It is worth* it: a restore that succeeds and leaves the user with a corrupt document is worse than one that- * takes another minute to say no.+ * takes another minute to say no. Where it is not worth it, see+ * {@link ValidationOptions.skipIntegrityCheck}.** @throws whatever the driver throws on a database too damaged to query; the caller knows its own* driver's failures and turns them into {@link DatabaseRejection}.*/-export function validateDatabase(db: CandidateDatabase): DatabaseValidation {- const integrity = db.integrityCheck();+export function validateDatabase(db: CandidateDatabase, options: ValidationOptions = {}): DatabaseValidation {+ const integrity = options.skipIntegrityCheck ? "ok" : db.integrityCheck();if (integrity !== "ok") {return reject("damaged-database", `The database failed its integrity check: ${integrity}`);}