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
fix(setup): rebuild partial schema on every setup path, not just sync resubmit
Elian Dorana8f346565cb8
diff --git a/packages/trilium-core/src/routes/api/setup.ts b/packages/trilium-core/src/routes/api/setup.tsindex 0048e8b49a..18ca3ef2e5 100644--- a/packages/trilium-core/src/routes/api/setup.ts+++ b/packages/trilium-core/src/routes/api/setup.ts@@ -27,7 +27,7 @@ function setupSyncFromServer(req: Request): Promise<SetupSyncFromServerResponse>return setupService.setupSyncFromSyncServer(syncServerHost, syncProxy, password, maxBlobContentSize);}-function saveSyncSeed(req: Request) {+async function saveSyncSeed(req: Request) {const { options, syncVersion } = req.body;const log = getLog();@@ -46,7 +46,9 @@ function saveSyncSeed(req: Request) {log.info("Saved sync seed.");- sqlInit.createDatabaseForSync(options);+ // Awaited so a failure surfaces as an error response to the pushing desktop+ // instead of an unhandled rejection with a 2xx already sent.+ await sqlInit.createDatabaseForSync(options);}/**diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.tsindex 634c568737..aac8ae8316 100644--- a/packages/trilium-core/src/services/sql_init.ts+++ b/packages/trilium-core/src/services/sql_init.ts@@ -138,6 +138,8 @@ async function createInitialDatabase(skipDemoDb?: boolean, locale?: string) {const sql = getSql();const log = getLog();sql.transactional(() => {+ wipePartialSchema();+log.info("Creating database schema ...");sql.executeScript(schema);@@ -262,20 +264,7 @@ async function createDatabaseForSync(options: OptionRow[], syncServerHost = "",const { initNotSyncedOptions } = await import("./options_init.js");sql.transactional(() => {- if (schemaExists()) {- // A previous sync-from-server attempt failed mid-way (schema created, sync never- // converged) and the user re-submitted the setup form — possibly pointing at a- // DIFFERENT server. Rebuild from scratch: the partially pulled rows belong to the- // old seed and would poison the new sync (#10548).- log.info("Schema exists from a previous unfinished sync setup — wiping it before re-creating.");-- const objects = sql.getRows<{ name: string; type: string }>(- /*sql*/`SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%'`- );- for (const { name, type } of objects) {- sql.execute(`DROP ${type === "view" ? "VIEW" : "TABLE"} IF EXISTS "${name.replace(/"/g, '""')}"`);- }- }+ wipePartialSchema();sql.executeScript(schema);@@ -290,4 +279,28 @@ async function createDatabaseForSync(options: OptionRow[], syncServerHost = "",log.info("Schema and not synced options generated.");}+/**+ * Drops every table and view left behind by a FAILED sync-from-server attempt (schema+ * created, sync never converged, `initialized` still false — see #10548). From that state+ * the setup wizard lets the user take any path again: resubmit the sync form, sync from a+ * desktop, or create a new document — all of which rebuild the schema and must start from+ * a clean slate, since the partially pulled rows may even belong to a different server.+ * No-op on a virgin database.+ */+function wipePartialSchema() {+ if (!schemaExists()) {+ return;+ }++ getLog().info("Schema exists from a previous unfinished setup — wiping it before re-creating.");++ const sql = getSql();+ const objects = sql.getRows<{ name: string; type: string }>(+ /*sql*/`SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%'`+ );+ for (const { name, type } of objects) {+ sql.execute(`DROP ${type === "view" ? "VIEW" : "TABLE"} IF EXISTS "${name.replace(/"/g, '""')}"`);+ }+}+export default { isDbInitialized, createDatabaseForSync, setDbAsInitialized, schemaExists, getDbSize, initDbConnection, dbReady, initializeDb, createInitialDatabase };diff --git a/packages/trilium-core/src/services/sql_init_resetup.spec.ts b/packages/trilium-core/src/services/sql_init_resetup.spec.tsindex 95ea13369d..c07d1a3a7b 100644--- a/packages/trilium-core/src/services/sql_init_resetup.spec.ts+++ b/packages/trilium-core/src/services/sql_init_resetup.spec.ts@@ -5,16 +5,17 @@ import { getSql } from "./sql/index.js";import sqlInit from "./sql_init.js";/**- * Re-running the sync-from-server setup after a FAILED first attempt (#10548).+ * Re-running setup after a FAILED sync-from-server attempt (#10548).** A failed initial sync leaves the database in a half-way state: the schema and the* seed options exist, but `initialized` is still false. The user must be able to go- * back in the setup wizard, correct the server address/credentials and submit again —- * which calls createDatabaseForSync a second time. That call must rebuild the database- * from scratch (the partial pull may contain rows from a *different* server) instead of- * failing on the already-existing schema.+ * back in the setup wizard and take ANY path again — resubmit the sync form+ * (createDatabaseForSync), or give up on syncing and create a new document instead+ * (createInitialDatabase). Both must rebuild the database from scratch (the partial+ * pull may contain rows from a *different* server) instead of failing on the+ * already-existing schema.*- * Own spec file: this test intentionally destroys and rebuilds the fixture DB, and the+ * Own spec file: these tests intentionally destroy and rebuild the fixture DB, and the* per-file fork isolation keeps that away from every other suite.*/describe("createDatabaseForSync on a partially set-up database", () => {@@ -47,4 +48,22 @@ describe("createDatabaseForSync on a partially set-up database", () => {expect(sql.getValue<string>("SELECT value FROM options WHERE name = 'documentSecret'")).toBe("resetup-doc-secret");expect(sql.getValue<string>("SELECT value FROM options WHERE name = 'syncServerHost'")).toBe("http://corrected-server:8080");});++ it("also rebuilds when the user gives up on syncing and creates a new document instead", async () => {+ const sql = getSql();++ // Failed-setup state again, with a marker row standing in for partially pulled data.+ sql.execute("UPDATE options SET value = 'false' WHERE name = 'initialized'");+ sql.execute(/*sql*/`INSERT INTO notes (noteId, title, type, mime, isProtected, isDeleted, dateCreated, dateModified, utcDateCreated, utcDateModified)+ VALUES ('stalePulled1', 'stale', 'text', 'text/html', 0, 0, '2026-07-18', '2026-07-18', '2026-07-18', '2026-07-18')`);+ expect(sqlInit.schemaExists()).toBe(true);+ expect(sqlInit.isDbInitialized()).toBe(false);++ await cls.init(() => sqlInit.createInitialDatabase(true, "en"));++ // A pristine new document: initialized, root note present, no leftovers.+ expect(sqlInit.isDbInitialized()).toBe(true);+ expect(sql.getValue<number>("SELECT COUNT(*) FROM notes WHERE noteId = 'root'")).toBe(1);+ expect(sql.getValue<number>("SELECT COUNT(*) FROM notes WHERE noteId = 'stalePulled1'")).toBe(0);+ });});