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
refactor(core): move imported-note date-setting into BNote
Elian Doran31b64b009ca9
diff --git a/packages/trilium-core/src/becca/entities/bnote.ts b/packages/trilium-core/src/becca/entities/bnote.tsindex a8bf85f166..0b8e474706 100644--- a/packages/trilium-core/src/becca/entities/bnote.ts+++ b/packages/trilium-core/src/becca/entities/bnote.ts@@ -1655,6 +1655,39 @@ class BNote extends AbstractBeccaEntity<BNote> {return formatDownloadTitle(this.title, this.type, this.mime);}+ /**+ * Forces explicit creation/modification timestamps onto the note and its blob, persisting them+ * immediately with raw SQL. This deliberately bypasses the automatic "now" stamping that+ * {@link beforeSaving} applies on every regular save, which is why importers that need to preserve+ * the source's original dates (ENEX, OneNote, …) call this *after* the note and its content have+ * been saved.+ *+ * Both arguments are UTC datetimes in Trilium's DB format (e.g. `2023-08-21 23:38:51.110Z`); the+ * matching local-time columns are derived from them. Either may be omitted to leave that pair at+ * its current value.+ */+ setDateCreatedAndModified(utcDateCreated?: string, utcDateModified?: string) {+ const toLocalDbFormat = (utc: string) => dayjs(utc).format(dateUtils.LOCAL_DATETIME_FORMAT);++ if (utcDateCreated) {+ this.utcDateCreated = utcDateCreated;+ this.dateCreated = toLocalDbFormat(utcDateCreated);+ }+ if (utcDateModified) {+ this.utcDateModified = utcDateModified;+ this.dateModified = toLocalDbFormat(utcDateModified);+ }++ const sql = getSql();+ sql.execute(+ /*sql*/`UPDATE notes+ SET dateCreated = ?, utcDateCreated = ?, dateModified = ?, utcDateModified = ?+ WHERE noteId = ?`,+ [this.dateCreated, this.utcDateCreated, this.dateModified, this.utcDateModified, this.noteId]+ );+ sql.execute(/*sql*/`UPDATE blobs SET utcDateModified = ? WHERE blobId = ?`, [this.utcDateModified, this.blobId]);+ }+override beforeSaving() {super.beforeSaving();diff --git a/packages/trilium-core/src/becca/entities/bnote_content.spec.ts b/packages/trilium-core/src/becca/entities/bnote_content.spec.tsindex 054270228e..48136e3e2c 100644--- a/packages/trilium-core/src/becca/entities/bnote_content.spec.ts+++ b/packages/trilium-core/src/becca/entities/bnote_content.spec.ts@@ -8,6 +8,8 @@ import eraseService from "../../services/erase.js";import noteService from "../../services/notes.js";import optionService from "../../services/options.js";import protectedSessionService from "../../services/protected_session.js";+import { getSql } from "../../services/sql/index.js";+import date_utils from "../../services/utils/date.js";import Module from "module";import { encodeUtf8, unwrapStringOrBuffer } from "../../services/utils/binary.js";@@ -94,6 +96,43 @@ describe("BNote content / misc getters", () => {});});+ describe("setDateCreatedAndModified (forces import dates, bypassing beforeSaving)", () => {+ it("persists explicit UTC dates, derives the local columns, and keeps the blob in step", () => {+ const note = createNote();+ const utcDateCreated = "2021-03-04 05:06:07.000Z";+ const utcDateModified = "2022-08-09 10:11:12.000Z";++ getContext().init(() => note.setDateCreatedAndModified(utcDateCreated, utcDateModified));++ // the in-memory entity reflects the forced dates+ expect(note.utcDateCreated).toBe(utcDateCreated);+ expect(note.utcDateModified).toBe(utcDateModified);+ expect(note.dateCreated).toBe(dayjs(utcDateCreated).format(date_utils.LOCAL_DATETIME_FORMAT));+ expect(note.dateModified).toBe(dayjs(utcDateModified).format(date_utils.LOCAL_DATETIME_FORMAT));++ // and so does the persisted row — i.e. beforeSaving's "now" stamping did not win+ const row = getSql().getRow<{ utcDateCreated: string; utcDateModified: string }>(+ "SELECT utcDateCreated, utcDateModified FROM notes WHERE noteId = ?",+ [note.noteId]+ );+ expect(row.utcDateCreated).toBe(utcDateCreated);+ expect(row.utcDateModified).toBe(utcDateModified);++ const blobModified = getSql().getValue<string>("SELECT utcDateModified FROM blobs WHERE blobId = ?", [note.blobId]);+ expect(blobModified).toBe(utcDateModified);+ });++ it("leaves a date pair untouched when its argument is omitted", () => {+ const note = createNote();+ const originalUtcCreated = note.utcDateCreated;++ getContext().init(() => note.setDateCreatedAndModified(undefined, "2030-01-02 03:04:05.000Z"));++ expect(note.utcDateCreated).toBe(originalUtcCreated);+ expect(note.utcDateModified).toBe("2030-01-02 03:04:05.000Z");+ });+ });+describe("type / mime predicates (lines 266-321)", () => {it("isJson", () => {const json = buildNote({ id: `json-${counter++}`, type: "code", mime: "application/json" });diff --git a/packages/trilium-core/src/services/import/enex.ts b/packages/trilium-core/src/services/import/enex.tsindex ca4f3215da..36ff486129 100644--- a/packages/trilium-core/src/services/import/enex.ts+++ b/packages/trilium-core/src/services/import/enex.ts@@ -1,9 +1,7 @@import type { AttributeType } from "@triliumnext/commons";-import { dayjs } from "@triliumnext/commons";import sax from "sax";import type BNote from "../../becca/entities/bnote.js";-import date_utils from "../utils/date.js";import * as utils from "../utils/index.js";import imageService from "../image.js";import { getLog } from "../log.js";@@ -14,7 +12,6 @@ import { escapeHtml, md5 } from "../utils/index.js";import { decodeBase64 } from "../utils/binary.js";import type { File } from "./common.js";import { sanitizeHtml } from "../sanitizer.js";-import { getSql } from "../sql/index.js";/*** date format is e.g. 20181121T193703Z or 2013-04-14T16:19:00.000Z (Mac evernote, see #3496)@@ -230,32 +227,6 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, p}};- const sql = getSql();-- function updateDates(note: BNote, utcDateCreated?: string, utcDateModified?: string) {- // it's difficult to force custom dateCreated and dateModified to Note entity, so we do it post-creation with SQL- const dateCreated = formatDateTimeToLocalDbFormat(utcDateCreated, false);- const dateModified = formatDateTimeToLocalDbFormat(utcDateModified, false);- sql.execute(- `- UPDATE notes- SET dateCreated = ?,- utcDateCreated = ?,- dateModified = ?,- utcDateModified = ?- WHERE noteId = ?`,- [dateCreated, utcDateCreated, dateModified, utcDateModified, note.noteId]- );-- sql.execute(- `- UPDATE blobs- SET utcDateModified = ?- WHERE blobId = ?`,- [utcDateModified, note.blobId]- );- }-function saveNote() {// make a copy because stream continues with the next call and note gets overwrittenlet { title, content, attributes, resources, utcDateCreated, utcDateModified } = note;@@ -361,7 +332,7 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, pnoteService.asyncPostProcessContent(noteEntity, content);- updateDates(noteEntity, utcDateCreated, utcDateModified);+ noteEntity.setDateCreatedAndModified(utcDateCreated, utcDateModified);}parser.onclosetag = (tag) => {@@ -389,21 +360,4 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, preturn rootNote;}-function formatDateTimeToLocalDbFormat(- utcDateFromEnex: Date | string | null | undefined,- keepUtc: boolean-): string | undefined {- if (!utcDateFromEnex) {- return undefined;- }-- const parsedDate = dayjs(utcDateFromEnex);-- if (!parsedDate.isValid()) {- return undefined;- }-- return (keepUtc ? parsedDate.utc() : parsedDate).format(date_utils.LOCAL_DATETIME_FORMAT);-}-export default { importEnex };