Skip to content

Build your personal knowledge base with Trilium Notes

client/options/database: fix the info card on the standalone version

Adorian Doran55ddfa34353d
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 20c4aa402d..e78c496fb4 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1751,6 +1751,7 @@
"title": "Database",
"info": "Database info",
"info_location": "Location",
+ "info_location_opfs": "Browser's origin private file system (OPFS)",
"info_created": "Original creation date",
"info_content": "Content",
"info_notes_one": "{{count}} note",
diff --git a/apps/client/src/widgets/type_widgets/options/database.spec.tsx b/apps/client/src/widgets/type_widgets/options/database.spec.tsx
index 7aaa39a1ba..4625e700be 100644
--- a/apps/client/src/widgets/type_widgets/options/database.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/database.spec.tsx
@@ -24,16 +24,25 @@ const setupMode = vi.hoisted(() => ({
vi.mock("../../../services/setup_mode", () => setupMode);
const DATABASE_INFO = {
- filePath: "/data/trilium/document.db",
+ filePath: "/data/trilium/document.db" as string | null,
utcDateCreated: "2020-05-17 08:30:00.000Z",
noteCount: 12,
attachmentCount: 3,
sizeBytes: 3 * 1024 * 1024
};
+/** What the info endpoint answers; replaced by the test about a database that is not a file. */
+let INFO: typeof DATABASE_INFO = DATABASE_INFO;
+
/** Set where a test needs the info card to have nothing to say. */
const failing = vi.hoisted(() => ({ info: false }));
+/** The browser build, which keeps no backups and has no path to its database. */
+const standalone = vi.hoisted(() => ({ enabled: false }));
+vi.mock("../../../services/backup_download", () => ({
+ isBackupDownloadSupported: () => standalone.enabled
+}));
+
/** What the backup page would list; emptied by the test about a database never backed up. */
let BACKUPS: { mtime: Date }[] = [];
@@ -55,7 +64,7 @@ const server = vi.hoisted(() => ({
if (failing.info) {
throw new Error("no answer");
}
- return DATABASE_INFO;
+ return INFO;
case "database/backups":
return { backupFolderPath: "/data/backup", backups: BACKUPS };
case "database/check-integrity":
@@ -129,6 +138,8 @@ beforeEach(() => {
setupMode.isStartOverPending.mockReset().mockResolvedValue(false);
setupMode.cancelStartOver.mockReset().mockResolvedValue(undefined);
failing.info = false;
+ INFO = DATABASE_INFO;
+ standalone.enabled = false;
BACKUPS = [ { mtime: new Date("2026-01-01T10:00:00Z") }, { mtime: new Date("2026-01-02T10:00:00Z") } ];
ANONYMIZED = [ ANONYMIZED_COPY ];
noteContext.setNote.mockClear();
@@ -180,6 +191,22 @@ describe("what the database is", () => {
expect(backup?.getAttribute("href")).toBe("#root/_hidden/_options/_optionsBackup");
});
+ it("names the storage where the database is no file, and drops what is not kept there", async () => {
+ standalone.enabled = true;
+ INFO = { ...DATABASE_INFO, filePath: null };
+ renderPage();
+ await settle();
+
+ // Nothing a file manager could be pointed at, so the storage is named instead of linked.
+ const [ location ] = infoValues();
+ expect(location).toBe("database.info_location_opfs");
+ expect(container.querySelector(".database-info a[href]")).toBeNull();
+
+ // The rest of the card holds: the figures come from the database itself, wherever it lives.
+ expect(infoValues()).toHaveLength(4);
+ expect(server.get).not.toHaveBeenCalledWith("database/backups");
+ });
+
it("says a database has never been backed up rather than leaving the row blank", async () => {
BACKUPS = [];
renderPage();
diff --git a/apps/client/src/widgets/type_widgets/options/database.tsx b/apps/client/src/widgets/type_widgets/options/database.tsx
index 671fd53ef1..f7864a1abb 100644
--- a/apps/client/src/widgets/type_widgets/options/database.tsx
+++ b/apps/client/src/widgets/type_widgets/options/database.tsx
@@ -12,6 +12,7 @@ import { useCallback, useEffect, useState } from "preact/hooks";
import type React from "react";
import { Trans } from "react-i18next";
+import { isBackupDownloadSupported } from "../../../services/backup_download";
import { summarizeBackups } from "../../../services/database_files";
import dialogService from "../../../services/dialog";
import { t } from "../../../services/i18n";
@@ -98,9 +99,6 @@ export default function DatabaseSettings() {
*/
function DatabaseInfo({ refreshToken }: { refreshToken: number }) {
const { data: info } = useFetch<DatabaseInfoResponse>("database/info", refreshToken);
- // The backups are the one thing here this page does nothing about, so they are read from the
- // page that does — the same listing, summarized by the same sentence its own header carries.
- const { data: backups } = useFetch<ExistingBackupsResponse>("database/backups", refreshToken);
if (!info) {
return null;
@@ -110,10 +108,13 @@ function DatabaseInfo({ refreshToken }: { refreshToken: number }) {
<div className="options-section database-info">
<Card heading={t("database.info")}>
<CardOption label={t("database.info_location")}>
- {/* Revealed rather than opened: a file manager is what the path is useful in,
- and the database's own reader is Trilium. */}
<span className="database-info-value">
- <FileLink filePath={info.filePath} />
+ {/* Revealed rather than opened: a file manager is what a path is useful in,
+ and the database's own reader is Trilium. Where there is no path, the
+ storage holding it is named instead — nothing there can be pointed at. */}
+ {info.filePath
+ ? <FileLink filePath={info.filePath} />
+ : t("database.info_location_opfs")}
</span>
</CardOption>
@@ -135,22 +136,40 @@ function DatabaseInfo({ refreshToken }: { refreshToken: number }) {
<span className="database-info-value">{formatSize(info.sizeBytes)}</span>
</CardOption>
- {backups && (
- <CardOption label={t("database.info_backup")}>
- {/* The whole value is the way to the page that acts on it: this row states
- how the backups stand, and everything else about them is done there. */}
- <span className="database-info-value">
- <a className="tn-link" href={BACKUP_PAGE_LINK}>
- {summarizeBackups(backups.backups) ?? t("database.info_no_backup")}
- </a>
- </span>
- </CardOption>
- )}
+ {/* Absent where backups are not kept at all: the browser build's one backup is a
+ download, taken there and then, so there is nothing standing to state. */}
+ {!isBackupDownloadSupported() && <BackupStanding refreshToken={refreshToken} />}
</Card>
</div>
);
}
+/**
+ * How the backups stand, and the way to the page that acts on them.
+ *
+ * The backups are the one thing on this page it does nothing about, so they are read from the page
+ * that does — the same listing, summarized by the same sentence its own header carries.
+ */
+function BackupStanding({ refreshToken }: { refreshToken: number }) {
+ const { data: backups } = useFetch<ExistingBackupsResponse>("database/backups", refreshToken);
+
+ if (!backups) {
+ return null;
+ }
+
+ return (
+ <CardOption label={t("database.info_backup")}>
+ {/* The whole value is the way to the page that acts on it: this row states how the
+ backups stand, and everything else about them is done there. */}
+ <span className="database-info-value">
+ <a className="tn-link" href={BACKUP_PAGE_LINK}>
+ {summarizeBackups(backups.backups) ?? t("database.info_no_backup")}
+ </a>
+ </span>
+ </CardOption>
+ );
+}
+
/** A note path, which is how one options page links to another. */
const BACKUP_PAGE_LINK = "#root/_hidden/_options/_optionsBackup";
diff --git a/apps/desktop/src/platform_provider.ts b/apps/desktop/src/platform_provider.ts
index 7db0f019ee..e3d499157b 100644
--- a/apps/desktop/src/platform_provider.ts
+++ b/apps/desktop/src/platform_provider.ts
@@ -1,5 +1,7 @@
import { PlatformProvider, t } from "@triliumnext/core";
+import dataDir from "@triliumnext/server/src/services/data_dir.js";
import electron from "electron";
+import path from "path";
export default class DesktopPlatformProvider implements PlatformProvider {
readonly isElectron = true;
@@ -16,6 +18,10 @@ export default class DesktopPlatformProvider implements PlatformProvider {
return process.env[key];
}
+ getDatabasePath(): string {
+ return path.resolve(dataDir.DOCUMENT_PATH);
+ }
+
/**
* Tolerate `EADDRINUSE` when this process was either launched with
* `--new-window` (the primary instance handles it via `second-instance`)
diff --git a/apps/server/src/platform_provider.ts b/apps/server/src/platform_provider.ts
index 16dc50a865..6244d629d2 100644
--- a/apps/server/src/platform_provider.ts
+++ b/apps/server/src/platform_provider.ts
@@ -1,4 +1,7 @@
import { getLog, PlatformProvider } from "@triliumnext/core";
+import path from "path";
+
+import dataDir from "./services/data_dir.js";
export default class ServerPlatformProvider implements PlatformProvider {
readonly isElectron = !!process.versions["electron"];
@@ -14,4 +17,8 @@ export default class ServerPlatformProvider implements PlatformProvider {
getEnv(key: string): string | undefined {
return process.env[key];
}
+
+ getDatabasePath(): string {
+ return path.resolve(dataDir.DOCUMENT_PATH);
+ }
}
diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.ts
index 48d1513397..282f9ae443 100644
--- a/apps/server/src/routes/api/database.spec.ts
+++ b/apps/server/src/routes/api/database.spec.ts
@@ -1,4 +1,4 @@
-import { becca, getBackup, getLog, utils, ValidationError } from "@triliumnext/core";
+import { getBackup, getLog, utils, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
import fs from "fs";
import path from "path";
@@ -27,24 +27,6 @@ describe("Database API", () => {
expect(Array.isArray(databases)).toBe(true);
});
- it("describes the database: where it is, when it began, what it holds and how large it is", () => {
- const info = databaseRoute.getDatabaseInfo();
-
- // Named in full: the desktop reveals the file in the file manager rather than opening it.
- expect(info.filePath).toBe(path.resolve(dataDir.DOCUMENT_PATH));
-
- // SQLite records nothing about when a file was made, so the root note answers for it.
- expect(info.utcDateCreated).toBe(becca.getNoteOrThrow("root").utcDateCreated);
-
- // The same figure the compaction estimate reports, so the two never disagree.
- expect(info.sizeBytes).toBe(databaseRoute.getCompactionEstimate().databaseBytes);
-
- // Counted, and the hidden subtree — launchers, options, templates — left out of the count.
- expect(info.noteCount).toBeGreaterThan(0);
- expect(info.noteCount).toBeLessThan(Object.keys(becca.notes).length);
- expect(info.attachmentCount).toBeGreaterThanOrEqual(0);
- });
-
it("runs an integrity check that reports 'ok'", () => {
const result = databaseRoute.checkIntegrity();
expect(result.results[0].integrity_check).toBe("ok");
diff --git a/apps/server/src/routes/api/database.ts b/apps/server/src/routes/api/database.ts
index 303bea274d..0358c1eaa8 100644
--- a/apps/server/src/routes/api/database.ts
+++ b/apps/server/src/routes/api/database.ts
@@ -2,11 +2,10 @@ import {
BackupDatabaseNowResponse,
CompactionEstimateResponse,
DatabaseCheckIntegrityResponse,
- DatabaseInfoResponse,
ExistingAnonymizedDatabasesResponse,
VacuumDatabaseResponse
} from "@triliumnext/commons";
-import { becca, becca_loader, consistency_checks as consistencyChecksService, getBackup, getContentCounts, getLog, utils, ValidationError } from "@triliumnext/core";
+import { becca_loader, consistency_checks as consistencyChecksService, getBackup, getDatabaseSizeBytes, getLog, getReclaimableBytes, utils, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
import fs, { readFileSync } from "fs";
import path from "path";
@@ -20,21 +19,6 @@ function getExistingBackups() {
return getBackup().getExistingBackups();
}
-/**
- * What the Database page states about the knowledge base as a whole.
- *
- * The root note stands in for the database itself: SQLite records nothing about when a file was
- * made, and the root is created once, by the very first startup that had no database to open.
- */
-function getDatabaseInfo() {
- return {
- filePath: path.resolve(dataDir.DOCUMENT_PATH),
- utcDateCreated: becca.getNoteOrThrow("root").utcDateCreated,
- ...getContentCounts(),
- sizeBytes: databaseBytes()
- } satisfies DatabaseInfoResponse;
-}
-
async function backupDatabase() {
return {
backupFile: await getBackup().backupNow("now")
@@ -45,7 +29,7 @@ function vacuumDatabase() {
// Timed from here, the two readings included: they are a pragma query each, and what the log is
// answering for is how long the whole thing held the database.
const startedAt = Date.now();
- const sizeBefore = databaseBytes();
+ const sizeBefore = getDatabaseSizeBytes();
// Announced before the rebuild starts, not only once it ends: this holds the process for minutes
// on a large database, and if it is killed or the machine goes down in the meantime, this line
@@ -53,7 +37,7 @@ function vacuumDatabase() {
getLog().info(`Compacting the database (${utils.formatSize(sizeBefore)}). This may take several minutes.`);
sql.execute("VACUUM");
- const sizeAfter = databaseBytes();
+ const sizeAfter = getDatabaseSizeBytes();
getLog().info(`Compacted the database from ${utils.formatSize(sizeBefore)}`
+ ` to ${utils.formatSize(sizeAfter)} in ${Date.now() - startedAt} ms.`);
@@ -68,28 +52,11 @@ function vacuumDatabase() {
*/
function getCompactionEstimate() {
return {
- reclaimableBytes: reclaimableBytes(),
- databaseBytes: databaseBytes()
+ reclaimableBytes: getReclaimableBytes(),
+ databaseBytes: getDatabaseSizeBytes()
} satisfies CompactionEstimateResponse;
}
-/**
- * The database's own view of its size: every page it has allocated, the free ones included. Read
- * through pragma functions rather than the file itself, so there is no path to resolve and no race
- * with the filesystem — and it is exactly the figure a vacuum moves.
- *
- * Covers the main database alone; in WAL mode the `-wal` sidecar is not part of it.
- */
-function databaseBytes(): number {
- return sql.getValue<number>("SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()");
-}
-
-/** Pages already free inside the file. A floor, not a promise: a rebuild also recovers the slack
- * left inside pages that are still in use, which no count of whole pages can see. */
-function reclaimableBytes(): number {
- return sql.getValue<number>("SELECT freelist_count * page_size FROM pragma_freelist_count(), pragma_page_size()");
-}
-
function findAndFixConsistencyIssues() {
void consistencyChecksService.runOnDemandChecks(true);
}
@@ -153,7 +120,6 @@ function downloadAnonymizedDatabase(req: Request, res: Response) {
export default {
getExistingBackups,
- getDatabaseInfo,
backupDatabase,
vacuumDatabase,
getCompactionEstimate,
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 7c999f22c3..ce38e529f9 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -143,7 +143,6 @@ function register(app: express.Application) {
route(PST, "/api/clipper/open/:noteId", clipperMiddleware, clipperRoute.openNote, apiResultHandler);
asyncRoute(GET, "/api/clipper/notes-by-url/:noteUrl", clipperMiddleware, clipperRoute.findNotesByUrl, apiResultHandler);
- apiRoute(GET, "/api/database/info", databaseRoute.getDatabaseInfo);
asyncRoute(PST, "/api/database/anonymize/:type", [auth.checkApiAuthOrElectron, csrfMiddleware], databaseRoute.anonymize, apiResultHandler);
apiRoute(GET, "/api/database/anonymized-databases", databaseRoute.getExistingAnonymizedDatabases);
route(GET, "/api/database/anonymized/download", [auth.checkApiAuthOrElectron], databaseRoute.downloadAnonymizedDatabase);
diff --git a/apps/standalone/src/lightweight/platform_provider.ts b/apps/standalone/src/lightweight/platform_provider.ts
index 639fefba0e..a6b0f35e20 100644
--- a/apps/standalone/src/lightweight/platform_provider.ts
+++ b/apps/standalone/src/lightweight/platform_provider.ts
@@ -41,4 +41,9 @@ export default class StandalonePlatformProvider implements PlatformProvider {
getEnv(key: string): string | undefined {
return this.envMap[key];
}
+
+ /** The browser owns the storage the database lives in, and gives out no path to it. */
+ getDatabasePath(): null {
+ return null;
+ }
}
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 7a6b557c70..4740fb07d9 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -125,8 +125,11 @@ export interface SpaceUsageCounts {
/** What the database is: where it lives, when it began, what it holds and how large it has grown. */
export interface DatabaseInfoResponse extends SpaceUsageCounts {
- /** Absolute path of the database file, its name included. */
- filePath: string;
+ /**
+ * Absolute path of the database file, its name included. Null where the database is not a file
+ * the user can reach: the browser build keeps it in storage the browser owns, which has no path.
+ */
+ filePath: string | null;
/** When the root note was created, standing in for when the knowledge base itself was. */
utcDateCreated: string;
/**
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index dd556a1c0a..4a2ef5d11b 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -144,6 +144,7 @@ export { type ImageProvider, type ImageFormat, type ImageCompressionOutcome, typ
export { default as imageCompressionService } from "./services/image_compression";
export { default as imageInventoryService, type ImageInventoryOptions } from "./services/image_inventory";
export { getContentCounts } from "./services/space_usage";
+export { getDatabaseSizeBytes, getReclaimableBytes } from "./services/database_size";
export { default as imageInfoService } from "./services/image_info";
export { estimateJpegQuality } from "./services/jpeg_quality";
export { inspectImage, type InspectedImage, UNKNOWN_FORMAT } from "./services/image_inspect";
diff --git a/packages/trilium-core/src/routes/api/database_info.spec.ts b/packages/trilium-core/src/routes/api/database_info.spec.ts
new file mode 100644
index 0000000000..fea605bbff
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/database_info.spec.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+
+import becca from "../../becca/becca.js";
+import { getDatabaseSizeBytes } from "../../services/database_size.js";
+import { getPlatform } from "../../services/platform.js";
+import databaseInfoRoute from "./database_info.js";
+
+describe("database info", () => {
+ it("describes the database: where it is, when it began, what it holds and how large it is", () => {
+ const info = databaseInfoRoute.getDatabaseInfo();
+
+ // Whatever the platform answers, including nothing at all: the browser build keeps the
+ // database in storage that has no path, and the page names the storage instead.
+ expect(info.filePath).toBe(getPlatform().getDatabasePath?.() ?? null);
+
+ // SQLite records nothing about when a file was made, so the root note answers for it.
+ expect(info.utcDateCreated).toBe(becca.getNoteOrThrow("root").utcDateCreated);
+
+ // Measured through the same pragmas everything else measures the database with.
+ expect(info.sizeBytes).toBe(getDatabaseSizeBytes());
+
+ // Counted, and the hidden subtree — launchers, options, templates — left out of the count.
+ expect(info.noteCount).toBeGreaterThan(0);
+ expect(info.noteCount).toBeLessThan(Object.keys(becca.notes).length);
+ expect(info.attachmentCount).toBeGreaterThanOrEqual(0);
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/database_info.ts b/packages/trilium-core/src/routes/api/database_info.ts
new file mode 100644
index 0000000000..5f58cbdb72
--- /dev/null
+++ b/packages/trilium-core/src/routes/api/database_info.ts
@@ -0,0 +1,28 @@
+import type { DatabaseInfoResponse } from "@triliumnext/commons";
+
+import becca from "../../becca/becca.js";
+import { getDatabaseSizeBytes } from "../../services/database_size.js";
+import { getPlatform } from "../../services/platform.js";
+import { getContentCounts } from "../../services/space_usage.js";
+
+/**
+ * What the Database options page states about the knowledge base as a whole.
+ *
+ * Everything here is read from the database itself, which is what lets the page read the same on a
+ * platform whose database is not a file at all. The two exceptions are answered by the platform: the
+ * path, where there is one, and the root note standing in for the database's own age — SQLite
+ * records nothing about when a file was made, and the root is created once, by the very first
+ * startup that had no database to open.
+ */
+function getDatabaseInfo() {
+ return {
+ filePath: getPlatform().getDatabasePath?.() ?? null,
+ utcDateCreated: becca.getNoteOrThrow("root").utcDateCreated,
+ ...getContentCounts(),
+ sizeBytes: getDatabaseSizeBytes()
+ } satisfies DatabaseInfoResponse;
+}
+
+export default {
+ getDatabaseInfo
+};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 868f5065db..0488a9254a 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -32,6 +32,7 @@ import exportRoute from "./api/export";
import scriptRoute from "./api/script";
import backendLogRoute from "./api/backend_log";
import backupRoute from "./api/backup";
+import databaseInfoRoute from "./api/database_info";
import passwordApiRoute from "./api/password";
import loginApiRoute from "./api/login";
import fontsRoute from "./api/fonts";
@@ -296,6 +297,8 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans
apiRoute(GET, "/api/app-info", appInfoRoute.getAppInfo);
asyncApiRoute(GET, "/api/backend-log", backendLogRoute.getBackendLog);
+ apiRoute(GET, "/api/database/info", databaseInfoRoute.getDatabaseInfo);
+
// Backup routes
asyncApiRoute(GET, "/api/database/backups", backupRoute.getExistingBackups);
asyncApiRoute(PST, "/api/database/backup-database", backupRoute.backupDatabase);
diff --git a/packages/trilium-core/src/services/database_size.spec.ts b/packages/trilium-core/src/services/database_size.spec.ts
new file mode 100644
index 0000000000..e969bf3302
--- /dev/null
+++ b/packages/trilium-core/src/services/database_size.spec.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+
+import { getDatabaseSizeBytes, getReclaimableBytes } from "./database_size.js";
+
+describe("database size", () => {
+ it("measures the database through pragmas, on every engine the core runs on", () => {
+ const size = getDatabaseSizeBytes();
+ const reclaimable = getReclaimableBytes();
+
+ // Runs against better-sqlite3 under the server suite and against sql.js under the standalone
+ // one: pragma functions are the part of this worth pinning down, since only one of the two
+ // engines is the one these figures were first written for.
+ expect(size).toBeGreaterThan(0);
+ expect(reclaimable).toBeGreaterThanOrEqual(0);
+ expect(reclaimable).toBeLessThan(size);
+ });
+});
diff --git a/packages/trilium-core/src/services/database_size.ts b/packages/trilium-core/src/services/database_size.ts
new file mode 100644
index 0000000000..498d8f3c3a
--- /dev/null
+++ b/packages/trilium-core/src/services/database_size.ts
@@ -0,0 +1,28 @@
+import { getSql } from "./sql/index.js";
+
+/**
+ * How large the database is, and how much of that it is not using.
+ *
+ * Both are read through pragmas rather than off the filesystem: there is no path to resolve and no
+ * race with whoever is writing, the figures are exactly the ones a vacuum moves — and where the
+ * database is not a file the user can reach at all, as in the browser, they are the only reading
+ * there is.
+ *
+ * @module
+ */
+
+/**
+ * Every page the database has allocated, the free ones included. Covers the main database alone; in
+ * WAL mode the `-wal` sidecar is not part of it.
+ */
+export function getDatabaseSizeBytes(): number {
+ return getSql().getValue<number>("SELECT page_count * page_size FROM pragma_page_count(), pragma_page_size()");
+}
+
+/**
+ * Pages already free inside the file. A floor, not a promise: a rebuild also recovers the slack left
+ * inside pages that are still in use, which no count of whole pages can see.
+ */
+export function getReclaimableBytes(): number {
+ return getSql().getValue<number>("SELECT freelist_count * page_size FROM pragma_freelist_count(), pragma_page_size()");
+}
diff --git a/packages/trilium-core/src/services/platform.ts b/packages/trilium-core/src/services/platform.ts
index fed9529e38..09cd499b4a 100644
--- a/packages/trilium-core/src/services/platform.ts
+++ b/packages/trilium-core/src/services/platform.ts
@@ -9,6 +9,12 @@ export interface PlatformProvider {
readonly isMac: boolean;
readonly isWindows: boolean;
readonly isLinux: boolean;
+ /**
+ * Where the database file is, for the platforms whose database is a file the user can reach.
+ * Null where it is not — the browser build keeps it in storage the browser owns, which has no
+ * path to give — and absent where a platform does not answer at all.
+ */
+ getDatabasePath?(): string | null;
/**
* Lets a platform decide whether an HTTP-server startup error should be
* swallowed (logged-only) rather than treated as fatal. The desktop uses