Skip to content

Build your personal knowledge base with Trilium Notes

client/options/database: add an info card

Adorian Doran789dbaf7add2
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index b6270fa782..d3455829e3 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1748,6 +1748,15 @@
},
"database": {
"title": "Database",
+ "info": "Database info",
+ "info_location": "Location",
+ "info_created": "Original creation date",
+ "info_content": "Content",
+ "info_notes_one": "{{count}} note",
+ "info_notes_other": "{{count}} notes",
+ "info_attachments_one": "{{count}} attachment",
+ "info_attachments_other": "{{count}} attachments",
+ "info_size": "Size",
"maintenance": "Maintenance",
"start_over_description": "Switch to a new blank database, start again syncing with a new server or restore a backup. You will be prompted to backup your data before discarding the existing data.",
"start_over": "Start over",
diff --git a/apps/client/src/widgets/react/DirectoryLink.tsx b/apps/client/src/widgets/react/DirectoryLink.tsx
index 3ed223e61a..5ba37ec951 100644
--- a/apps/client/src/widgets/react/DirectoryLink.tsx
+++ b/apps/client/src/widgets/react/DirectoryLink.tsx
@@ -1,18 +1,31 @@
+import type { ComponentChildren } from "preact";
+
import openService from "../../services/open.js";
import { isElectron } from "../../services/utils.js";
+interface DirectoryLinkProps {
+ directory: string;
+ /**
+ * What to show in place of the path itself, for a link that stands for something inside the
+ * directory it opens — a file, named in full, with the file manager landing on its folder.
+ */
+ children?: ComponentChildren;
+}
+
/**
* A filesystem location, opened in the OS file manager on click. Only the desktop application can
* open anything, so everywhere else the path is shown as plain (selectable) text.
*/
-export default function DirectoryLink({ directory }: { directory: string }) {
+export default function DirectoryLink({ directory, children }: DirectoryLinkProps) {
+ const label = children ?? directory;
+
if (isElectron()) {
const onClick = (e: MouseEvent) => {
e.preventDefault();
openService.openDirectory(directory);
};
- return <a className="tn-link selectable-text" href="#" onClick={onClick}>{directory}</a>;
+ return <a className="tn-link selectable-text" href="#" onClick={onClick}>{label}</a>;
}
- return <span className="selectable-text">{directory}</span>;
+ return <span className="selectable-text">{label}</span>;
}
diff --git a/apps/client/src/widgets/type_widgets/options/database.css b/apps/client/src/widgets/type_widgets/options/database.css
index a44b60b20c..6ff0a35484 100644
--- a/apps/client/src/widgets/type_widgets/options/database.css
+++ b/apps/client/src/widgets/type_widgets/options/database.css
@@ -1,3 +1,12 @@
+/* Facts, not controls: unlike the buttons the card rows are built around, a value gives way when
+ the line runs short, and a path breaks wherever it must rather than widening the card. */
+.database-info .database-info-value {
+ flex-shrink: 1;
+ min-width: 0;
+ text-align: end;
+ overflow-wrap: anywhere;
+}
+
/* The notice sits above the cards it precedes, so the gap belongs under it. */
.admonition.start-over-pending {
margin-bottom: 16px;
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 35cf5c8447..61c0908749 100644
--- a/apps/client/src/widgets/type_widgets/options/database.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/database.spec.tsx
@@ -1,8 +1,11 @@
import { render } from "preact";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-// t() returns the key so assertions are deterministic and not tied to English text.
-vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+// t() returns the key so assertions are deterministic and not tied to English text; a counted
+// string carries its count, which is the part of those the page decides.
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string, params?: { count?: number }) => params?.count === undefined ? key : `${key}=${params.count}`
+}));
const setupMode = vi.hoisted(() => ({
canBootToSetup: vi.fn(() => true),
@@ -12,10 +15,27 @@ const setupMode = vi.hoisted(() => ({
}));
vi.mock("../../../services/setup_mode", () => setupMode);
-// The maintenance and anonymization cards call the backend as they render and as they are used.
+const DATABASE_INFO = {
+ filePath: "/data/trilium/document.db",
+ directoryPath: "/data/trilium",
+ utcDateCreated: "2020-05-17 08:30:00.000Z",
+ noteCount: 12,
+ attachmentCount: 3,
+ sizeBytes: 3 * 1024 * 1024
+};
+
+/** Set where a test needs the info card to have nothing to say. */
+const failing = vi.hoisted(() => ({ info: false }));
+
+// The info, maintenance and anonymization cards call the backend as they render and as they are used.
const server = vi.hoisted(() => ({
get: vi.fn(async (url: string) => {
switch (url) {
+ case "database/info":
+ if (failing.info) {
+ throw new Error("no answer");
+ }
+ return DATABASE_INFO;
case "database/check-integrity":
return { results: [{ integrity_check: "ok" }] };
case "database/anonymized-databases":
@@ -65,6 +85,7 @@ beforeEach(() => {
setupMode.startOver.mockReset().mockResolvedValue("restarting");
setupMode.isStartOverPending.mockReset().mockResolvedValue(false);
setupMode.cancelStartOver.mockReset().mockResolvedValue(undefined);
+ failing.info = false;
server.get.mockClear();
server.post.mockClear();
server.postWithTimeout.mockClear();
@@ -78,6 +99,52 @@ afterEach(() => {
vi.useRealTimers();
});
+describe("what the database is", () => {
+ /** The facts of the info card, in the order the card states them. */
+ function infoValues() {
+ return [ ...container.querySelectorAll(".database-info .database-info-value") ]
+ .map((value) => value.textContent);
+ }
+
+ it("states where it lives, when it began, what it holds and how large it has grown", async () => {
+ renderPage();
+ await settle();
+
+ expect(server.get).toHaveBeenCalledWith("database/info");
+
+ const [ location, created, content, size ] = infoValues();
+ // The file is named in full; the link behind it opens the folder holding it, since that is
+ // what a file manager can be pointed at.
+ expect(location).toBe(DATABASE_INFO.filePath);
+ expect(created).toContain("2020");
+ expect(content).toBe("database.info_notes=12, database.info_attachments=3");
+ expect(size).toBe("3 MiB");
+ });
+
+ it("reads the figures again once the database has been compacted", async () => {
+ renderPage();
+ await settle();
+
+ button("vacuum-database-button")?.click();
+ await settle();
+
+ // Compacting is the one action on the page that changes what the card states, and a size
+ // left saying what it did before the rebuild would be plainly wrong.
+ expect(server.get.mock.calls.filter(([ url ]) => url === "database/info")).toHaveLength(2);
+ });
+
+ it("says nothing at all where the figures cannot be had", async () => {
+ failing.info = true;
+ renderPage();
+ await settle();
+
+ // A card of empty rows would state no less, and rather less clearly. The rest of the page
+ // stands: each card answers for itself.
+ expect(container.querySelector(".database-info")).toBeNull();
+ expect(button("check-integrity-button")).not.toBeNull();
+ });
+});
+
describe("database maintenance", () => {
it("runs each check against its own endpoint, and says how it went", async () => {
renderPage();
diff --git a/apps/client/src/widgets/type_widgets/options/database.tsx b/apps/client/src/widgets/type_widgets/options/database.tsx
index c0204aee6c..7ffb70438e 100644
--- a/apps/client/src/widgets/type_widgets/options/database.tsx
+++ b/apps/client/src/widgets/type_widgets/options/database.tsx
@@ -4,6 +4,7 @@ import {
AnonymizedDbResponse,
DatabaseAnonymizeResponse,
DatabaseCheckIntegrityResponse,
+ DatabaseInfoResponse,
ExistingAnonymizedDatabasesResponse
} from "@triliumnext/commons";
import { useCallback, useEffect, useState } from "preact/hooks";
@@ -17,9 +18,13 @@ import {
startOver
} from "../../../services/setup_mode";
import toast from "../../../services/toast";
+import { formatSize } from "../../../services/utils";
+import { formatDateTime } from "../../../utils/formatters";
import Admonition from "../../react/Admonition";
import Button from "../../react/Button";
import { Card, CardOption } from "../../react/Card";
+import DirectoryLink from "../../react/DirectoryLink";
+import { useFetch } from "../../react/use_fetch";
import DatabaseFileList from "./components/DatabaseFileList";
import OptionsPageHeader from "./components/OptionsPageHeader";
@@ -32,6 +37,10 @@ import OptionsPageHeader from "./components/OptionsPageHeader";
*/
export default function DatabaseSettings() {
const startOverState = useStartOver();
+ // Compacting is the one action on this page that changes what the card above it states, so the
+ // figures are read again once a rebuild has finished rather than left saying what they did.
+ const [ infoToken, setInfoToken ] = useState(0);
+ const refreshInfo = useCallback(() => setInfoToken((token) => token + 1), []);
return (
<>
@@ -54,15 +63,63 @@ export default function DatabaseSettings() {
</Admonition>
)}
- <MaintenanceOptions />
+ <DatabaseInfo refreshToken={infoToken} />
+ <MaintenanceOptions onDatabaseCompacted={refreshInfo} />
<AnonymizationOptions />
<StartOverOption state={startOverState} />
</>
);
}
+/**
+ * What the database is, before anything is done to it: where its file is, how far back it goes, how
+ * much it holds and how large it has grown.
+ *
+ * Nothing is shown until the figures arrive, and nothing at all where they cannot be had. A card of
+ * empty rows would state no less than a card that is not there, and rather less clearly.
+ */
+function DatabaseInfo({ refreshToken }: { refreshToken: number }) {
+ const { data: info } = useFetch<DatabaseInfoResponse>("database/info", refreshToken);
+
+ if (!info) {
+ return null;
+ }
+
+ return (
+ <div className="options-section database-info">
+ <Card heading={t("database.info")}>
+ <CardOption label={t("database.info_location")}>
+ {/* The file is named in full, while the link opens the folder holding it: a
+ file manager is what the path is useful in, not the database's own reader. */}
+ <span className="database-info-value">
+ <DirectoryLink directory={info.directoryPath}>{info.filePath}</DirectoryLink>
+ </span>
+ </CardOption>
+
+ <CardOption label={t("database.info_created")}>
+ <span className="database-info-value">
+ {formatDateTime(info.utcDateCreated, "long", "none")}
+ </span>
+ </CardOption>
+
+ <CardOption label={t("database.info_content")}>
+ <span className="database-info-value">
+ {t("database.info_notes", { count: info.noteCount })}
+ {", "}
+ {t("database.info_attachments", { count: info.attachmentCount })}
+ </span>
+ </CardOption>
+
+ <CardOption label={t("database.info_size")}>
+ <span className="database-info-value">{formatSize(info.sizeBytes)}</span>
+ </CardOption>
+ </Card>
+ </div>
+ );
+}
+
/** Checks and repairs that act on the database file itself, rather than on what is kept in it. */
-function MaintenanceOptions() {
+function MaintenanceOptions({ onDatabaseCompacted }: { onDatabaseCompacted: () => void }) {
return (
<div className="options-section database-maintenance">
<Card heading={t("database.maintenance")}>
@@ -98,7 +155,10 @@ function MaintenanceOptions() {
name="vacuum-database-button"
text={t("vacuum_database.button_text")}
size="micro"
- onClick={vacuumDatabase}
+ onClick={async () => {
+ await vacuumDatabase();
+ onDatabaseCompacted();
+ }}
/>
</CardOption>
</Card>
diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.ts
index bc535f4362..a1a8987299 100644
--- a/apps/server/src/routes/api/database.spec.ts
+++ b/apps/server/src/routes/api/database.spec.ts
@@ -1,4 +1,4 @@
-import { getBackup, getLog, utils, ValidationError } from "@triliumnext/core";
+import { becca, getBackup, getLog, utils, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
import fs from "fs";
import path from "path";
@@ -27,6 +27,27 @@ 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();
+ const filePath = path.resolve(dataDir.DOCUMENT_PATH);
+
+ // The file is named in full, and the directory separately: what a file manager can be
+ // pointed at is the folder, never the database itself.
+ expect(info.filePath).toBe(filePath);
+ expect(info.directoryPath).toBe(path.dirname(filePath));
+
+ // 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 9e87227250..178b471266 100644
--- a/apps/server/src/routes/api/database.ts
+++ b/apps/server/src/routes/api/database.ts
@@ -2,10 +2,11 @@ import {
BackupDatabaseNowResponse,
CompactionEstimateResponse,
DatabaseCheckIntegrityResponse,
+ DatabaseInfoResponse,
ExistingAnonymizedDatabasesResponse,
VacuumDatabaseResponse
} from "@triliumnext/commons";
-import { becca_loader, consistency_checks as consistencyChecksService, getBackup, getLog, utils, ValidationError } from "@triliumnext/core";
+import { becca, becca_loader, consistency_checks as consistencyChecksService, getBackup, getContentCounts, getLog, utils, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
import fs, { readFileSync } from "fs";
import path from "path";
@@ -19,6 +20,24 @@ 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() {
+ const filePath = path.resolve(dataDir.DOCUMENT_PATH);
+
+ return {
+ filePath,
+ directoryPath: path.dirname(filePath),
+ utcDateCreated: becca.getNoteOrThrow("root").utcDateCreated,
+ ...getContentCounts(),
+ sizeBytes: databaseBytes()
+ } satisfies DatabaseInfoResponse;
+}
+
async function backupDatabase() {
return {
backupFile: await getBackup().backupNow("now")
@@ -119,6 +138,7 @@ 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 884e5b430c..a01f1ba7b5 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -143,6 +143,7 @@ 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/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index e39f6539c0..31a9eac810 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -109,6 +109,35 @@ export interface DatabaseCheckIntegrityResponse {
}[];
}
+/**
+ * How much the knowledge base holds, counted rather than measured: the two figures the Database
+ * page states, produced without the pass over every blob that the space usage pages take.
+ *
+ * The hidden subtree is left out of both — launchers, options and the like are the application's
+ * own furniture, not anything the user put there.
+ */
+export interface SpaceUsageCounts {
+ /** Live notes reachable outside the hidden subtree. */
+ noteCount: number;
+ /** Attachments those notes own; the ones belonging to revisions are history, and left out. */
+ attachmentCount: number;
+}
+
+/** 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;
+ /** The directory holding it, which is what a file manager can be pointed at. */
+ directoryPath: string;
+ /** When the root note was created, standing in for when the knowledge base itself was. */
+ utcDateCreated: string;
+ /**
+ * What the database occupies now, free pages included — the same figure the compaction estimate
+ * reports, so the two never disagree about how large the file is.
+ */
+ sizeBytes: number;
+}
+
/**
* What rebuilding the database file gave back, measured either side of the vacuum. Erasing content
* does not shrink the file — the pages it frees stay allocated on the freelist — so this difference
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index 921b52f21e..dd556a1c0a 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -143,6 +143,7 @@ export { InAppHelpProvider } from "./services/in_app_help";
export { type ImageProvider, type ImageFormat, type ImageCompressionOutcome, type ImageCompressionRequest, type ProcessedImage, getImageProvider } from "./services/image_provider";
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 { 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/services/space_usage.spec.ts b/packages/trilium-core/src/services/space_usage.spec.ts
index 82b0bd7f07..7330261a15 100644
--- a/packages/trilium-core/src/services/space_usage.spec.ts
+++ b/packages/trilium-core/src/services/space_usage.spec.ts
@@ -1,7 +1,16 @@
import { SpaceUsageSizes } from "@triliumnext/commons";
import { describe, expect, it } from "vitest";
-import { buildCanonicalForest, buildNotePath, collectSubtreeNoteIds, computeSubtreeTotals } from "./space_usage.js";
+import {
+ buildCanonicalForest,
+ buildNotePath,
+ collectSubtreeNoteIds,
+ computeSubtreeTotals,
+ DEFAULT_OVERVIEW_LIMIT,
+ getContentCounts,
+ getOverview
+} from "./space_usage.js";
+import { getSql } from "./sql/index.js";
/** Builds a forest from a plain parent → ordered children map; extras model orphan roots. */
function forestOf(edges: Record<string, string[]>, extraNoteIds: string[] = []) {
@@ -161,3 +170,38 @@ describe("buildNotePath", () => {
expect(buildNotePath(forest.parentByNoteId, "lost")).toEqual([ "lost" ]);
});
});
+
+describe("getContentCounts", () => {
+ /** A row rather than an entity: the count is taken off the table, and nothing else is needed. */
+ function insertAttachment(attachmentId: string, ownerId: string) {
+ getSql().execute(`
+ INSERT INTO attachments (attachmentId, ownerId, role, mime, title, isDeleted, dateModified, utcDateModified)
+ VALUES (?, ?, 'file', 'text/plain', 'spec attachment', 0, '2026-01-01 00:00:00.000+00:00', '2026-01-01 00:00:00.000Z')`,
+ [ attachmentId, ownerId ]);
+ }
+
+ it("counts the notes the overview counts, so the two never state different figures", () => {
+ const overview = getOverview({ includeRevisions: false, limit: DEFAULT_OVERVIEW_LIMIT });
+
+ expect(getContentCounts().noteCount).toBe(overview.total.noteCount);
+ // The equality above only means something where the two differ: every database carries a
+ // hidden subtree, and none of it is the user's doing.
+ expect(overview.hiddenNotes.noteCount).toBeGreaterThan(0);
+ });
+
+ it("counts the attachments notes own, leaving out history and the hidden subtree", () => {
+ const before = getContentCounts().attachmentCount;
+
+ insertAttachment("spec_att_note", "root");
+ insertAttachment("spec_att_hidden", "_hidden");
+ // No note carries this ID, which is what an attachment owned by a revision looks like here.
+ insertAttachment("spec_att_revision", "spec_revision_owner");
+
+ try {
+ expect(getContentCounts().attachmentCount).toBe(before + 1);
+ } finally {
+ getSql().execute(
+ "DELETE FROM attachments WHERE attachmentId IN ('spec_att_note', 'spec_att_hidden', 'spec_att_revision')");
+ }
+ });
+});
diff --git a/packages/trilium-core/src/services/space_usage.ts b/packages/trilium-core/src/services/space_usage.ts
index 0544ee9ed6..79d99c2a79 100644
--- a/packages/trilium-core/src/services/space_usage.ts
+++ b/packages/trilium-core/src/services/space_usage.ts
@@ -2,6 +2,7 @@ import {
EraseExcessRevisionsOptions,
SpaceUsageBucket,
SpaceUsageContent,
+ SpaceUsageCounts,
SpaceUsageDeletedNotes,
SpaceUsageNoteResponse,
SpaceUsageOverviewResponse,
@@ -107,6 +108,27 @@ function buildOverview({ includeRevisions, limit }: { includeRevisions: boolean,
};
}
+/**
+ * What the knowledge base holds, counted without measuring any of it.
+ *
+ * Cheap enough to answer a page that merely states the figures — a walk of the tree becca already
+ * holds plus one query over the attachment rows — where the overview above reads every blob in the
+ * database. What counts as visible is the canonical forest all the same, so this and the space usage
+ * pages never disagree about how many notes there are: the hidden subtree stays out, and a bookmark,
+ * being a clone into it, stays in.
+ */
+export function getContentCounts(): SpaceUsageCounts {
+ const visibleNoteIds = new Set(buildForestFromBecca().userNoteIds);
+ const ownerIds = getSql().getColumn<string>("SELECT ownerId FROM attachments WHERE isDeleted = 0");
+
+ return {
+ noteCount: visibleNoteIds.size,
+ // An owner is either a note or a revision, and a revision ID matches no note, so the
+ // attachments belonging to history drop out of the count on their own.
+ attachmentCount: ownerIds.filter((ownerId) => visibleNoteIds.has(ownerId)).length
+ };
+}
+
export function getNoteUsage(
noteId: string,
revisionOptions: EraseExcessRevisionsOptions = {}