Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(database): add document history table and update related models

Innei64fc6d4bbd39
diff --git a/docs/development/database-schema.dbml b/docs/development/database-schema.dbml
index 17ef1d94238..f4f5d9858ce 100644
--- a/docs/development/database-schema.dbml
+++ b/docs/development/database-schema.dbml
@@ -507,6 +507,20 @@ table chat_groups_agents {
}
}
+table document_histories {
+ id varchar(255) [pk, not null]
+ document_id varchar(255) [not null]
+ user_id text [not null]
+ editor_data jsonb [not null]
+ save_source text [not null]
+ saved_at "timestamp with time zone" [not null]
+
+ indexes {
+ (document_id, saved_at) [name: 'document_histories_document_id_saved_at_idx']
+ (user_id, saved_at) [name: 'document_histories_user_id_saved_at_idx']
+ }
+}
+
table documents {
id varchar(255) [pk, not null]
title text
@@ -1976,6 +1990,10 @@ ref: unstructured_chunks.file_id - files.id
ref: document_chunks.document_id > documents.id
+ref: document_histories.document_id > documents.id
+
+ref: document_histories.user_id - users.id
+
ref: documents.file_id > files.id
ref: file_chunks.file_id - files.id
diff --git a/packages/database/migrations/0098_add_document_history.sql b/packages/database/migrations/0098_add_document_history.sql
index 0ea9d1f0182..c4591650be6 100644
--- a/packages/database/migrations/0098_add_document_history.sql
+++ b/packages/database/migrations/0098_add_document_history.sql
@@ -2,22 +2,14 @@ CREATE TABLE IF NOT EXISTS "document_histories" (
"id" varchar(255) PRIMARY KEY NOT NULL,
"document_id" varchar(255) NOT NULL,
"user_id" text NOT NULL,
- "version" integer NOT NULL,
- "storage_kind" text NOT NULL,
- "payload" jsonb NOT NULL,
- "base_version" integer,
+ "editor_data" jsonb NOT NULL,
"save_source" text NOT NULL,
- "saved_at" timestamp with time zone NOT NULL,
- "created_at" timestamp with time zone DEFAULT now() NOT NULL
+ "saved_at" timestamp with time zone NOT NULL
);
--> statement-breakpoint
-ALTER TABLE "documents" ADD COLUMN IF NOT EXISTS "version" integer DEFAULT 1 NOT NULL;--> statement-breakpoint
-ALTER TABLE "documents" ALTER COLUMN "version" SET DEFAULT 1;--> statement-breakpoint
-ALTER TABLE "documents" ALTER COLUMN "version" SET NOT NULL;--> statement-breakpoint
ALTER TABLE "document_histories" DROP CONSTRAINT IF EXISTS "document_histories_document_id_documents_id_fk";--> statement-breakpoint
ALTER TABLE "document_histories" ADD CONSTRAINT "document_histories_document_id_documents_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."documents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "document_histories" DROP CONSTRAINT IF EXISTS "document_histories_user_id_users_id_fk";--> statement-breakpoint
ALTER TABLE "document_histories" ADD CONSTRAINT "document_histories_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
-CREATE UNIQUE INDEX IF NOT EXISTS "document_histories_document_id_version_unique" ON "document_histories" USING btree ("document_id","version");--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "document_histories_document_id_saved_at_idx" ON "document_histories" USING btree ("document_id","saved_at");--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "document_histories_user_id_saved_at_idx" ON "document_histories" USING btree ("user_id","saved_at");
diff --git a/packages/database/migrations/meta/0098_snapshot.json b/packages/database/migrations/meta/0098_snapshot.json
index a0f079e4819..08730ca52d8 100644
--- a/packages/database/migrations/meta/0098_snapshot.json
+++ b/packages/database/migrations/meta/0098_snapshot.json
@@ -6,7 +6,7 @@
},
"dialect": "postgresql",
"enums": {},
- "id": "5d44d9cc-8c23-4366-b533-724789e8079d",
+ "id": "cabb477f-3c4c-46af-9421-16bb0f1926b9",
"policies": {},
"prevId": "9f1fcd61-445c-446c-8511-1f40f014e0ae",
"roles": {},
@@ -3883,30 +3883,12 @@
"primaryKey": false,
"notNull": true
},
- "version": {
- "name": "version",
- "type": "integer",
- "primaryKey": false,
- "notNull": true
- },
- "storage_kind": {
- "name": "storage_kind",
- "type": "text",
- "primaryKey": false,
- "notNull": true
- },
- "payload": {
- "name": "payload",
+ "editor_data": {
+ "name": "editor_data",
"type": "jsonb",
"primaryKey": false,
"notNull": true
},
- "base_version": {
- "name": "base_version",
- "type": "integer",
- "primaryKey": false,
- "notNull": false
- },
"save_source": {
"name": "save_source",
"type": "text",
@@ -3918,37 +3900,9 @@
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
- },
- "created_at": {
- "name": "created_at",
- "type": "timestamp with time zone",
- "primaryKey": false,
- "notNull": true,
- "default": "now()"
}
},
"indexes": {
- "document_histories_document_id_version_unique": {
- "name": "document_histories_document_id_version_unique",
- "columns": [
- {
- "expression": "document_id",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- },
- {
- "expression": "version",
- "isExpression": false,
- "asc": true,
- "nulls": "last"
- }
- ],
- "isUnique": true,
- "concurrently": false,
- "method": "btree",
- "with": {}
- },
"document_histories_document_id_saved_at_idx": {
"name": "document_histories_document_id_saved_at_idx",
"columns": [
@@ -4076,13 +4030,6 @@
"primaryKey": false,
"notNull": false
},
- "version": {
- "name": "version",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "default": 1
- },
"pages": {
"name": "pages",
"type": "jsonb",
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
index 454d44bf08c..7d50f550fc7 100644
--- a/packages/database/migrations/meta/_journal.json
+++ b/packages/database/migrations/meta/_journal.json
@@ -690,7 +690,7 @@
{
"idx": 98,
"version": "7",
- "when": 1775841373545,
+ "when": 1776234919716,
"tag": "0098_add_document_history",
"breakpoints": true
}
diff --git a/packages/database/src/models/__tests__/document.test.ts b/packages/database/src/models/__tests__/document.test.ts
index c82a8a56880..6603ae46c08 100644
--- a/packages/database/src/models/__tests__/document.test.ts
+++ b/packages/database/src/models/__tests__/document.test.ts
@@ -80,7 +80,6 @@ describe('DocumentModel', () => {
expect(result).toBeDefined();
expect(result.content).toBe('Test content');
expect(result.fileId).toBe(file.id);
- expect(result.version).toBe(1);
});
});
diff --git a/packages/database/src/models/__tests__/documentHistory.test.ts b/packages/database/src/models/__tests__/documentHistory.test.ts
index b6b052e13e4..1c7d15daf66 100644
--- a/packages/database/src/models/__tests__/documentHistory.test.ts
+++ b/packages/database/src/models/__tests__/documentHistory.test.ts
@@ -64,64 +64,33 @@ describe('DocumentHistoryModel', () => {
const created = await historyModel.create({
documentId,
- payload: { editorData: { blocks: [] } },
+ editorData: { blocks: [] },
saveSource: 'autosave',
savedAt: new Date('2026-04-11T00:00:00.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
expect(created).toMatchObject({
documentId,
saveSource: 'autosave',
- storageKind: 'snapshot',
userId,
- version: 1,
});
const stored = await historyModel.findById(created.id);
expect(stored).toMatchObject({
documentId,
- version: 1,
- payload: { editorData: { blocks: [] } },
+ editorData: { blocks: [] },
});
});
- it('should enforce unique document version history rows', async () => {
- const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
-
- await historyModel.create({
- documentId,
- payload: { editorData: { blocks: [{ id: 'a' }] } },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:00.000Z'),
- storageKind: 'snapshot',
- version: 1,
- });
-
- await expect(
- historyModel.create({
- documentId,
- payload: { editorData: { blocks: [{ id: 'b' }] } },
- saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:01:00.000Z'),
- storageKind: 'patch',
- version: 1,
- }),
- ).rejects.toThrow();
- });
-
it('should reject history rows for documents owned by another user', async () => {
const otherDocumentId = await createTestDocument(documentModel2, fileModel2, 'Other content');
await expect(
historyModel.create({
documentId: otherDocumentId,
- payload: { editorData: { blocks: [] } },
+ editorData: { blocks: [] },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:00.000Z'),
- storageKind: 'snapshot',
- version: 1,
}),
).rejects.toThrow('Document not found');
@@ -135,128 +104,85 @@ describe('DocumentHistoryModel', () => {
});
describe('list', () => {
- it('should return document history rows ordered by version descending', async () => {
+ it('should return document history rows ordered by savedAt descending', async () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
await historyModel.create({
documentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 1 },
saveSource: 'autosave',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
await historyModel.create({
documentId,
- payload: { editorData: { version: 2 } },
+ editorData: { tag: 2 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:02.000Z'),
- storageKind: 'patch',
- version: 2,
});
await historyModel.create({
documentId,
- payload: { editorData: { version: 3 } },
+ editorData: { tag: 3 },
saveSource: 'restore',
savedAt: new Date('2026-04-11T00:00:03.000Z'),
- storageKind: 'snapshot',
- version: 3,
});
const rows = await historyModel.list({ documentId });
- expect(rows.map((row) => row.version)).toEqual([3, 2, 1]);
- expect(rows[0]).toMatchObject({ saveSource: 'restore', storageKind: 'snapshot' });
+ expect(rows.map((row) => (row.editorData as any).tag)).toEqual([3, 2, 1]);
+ expect(rows[0]).toMatchObject({ saveSource: 'restore' });
});
- it('should support pagination anchors and limits', async () => {
+ it('should support pagination via beforeSavedAt and limit', async () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
await historyModel.create({
documentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 1 },
saveSource: 'autosave',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
await historyModel.create({
documentId,
- payload: { editorData: { version: 2 } },
+ editorData: { tag: 2 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:02.000Z'),
- storageKind: 'patch',
- version: 2,
});
await historyModel.create({
documentId,
- payload: { editorData: { version: 3 } },
+ editorData: { tag: 3 },
saveSource: 'restore',
savedAt: new Date('2026-04-11T00:00:03.000Z'),
- storageKind: 'snapshot',
- version: 3,
});
- const anchored = await historyModel.list({ beforeVersion: 3, documentId, limit: 1 });
+ const anchored = await historyModel.list({
+ beforeSavedAt: new Date('2026-04-11T00:00:03.000Z'),
+ documentId,
+ limit: 1,
+ });
expect(anchored).toHaveLength(1);
- expect(anchored[0]?.version).toBe(2);
+ expect((anchored[0]?.editorData as any).tag).toBe(2);
});
+ });
- it('should keep pagination stable when savedAt order differs from version order', async () => {
+ describe('findLatestByDocumentId', () => {
+ it('should return the most recent history row by savedAt', async () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
await historyModel.create({
documentId,
- payload: { editorData: { version: 1 } },
- saveSource: 'autosave',
- savedAt: new Date('2026-04-11T00:00:03.000Z'),
- storageKind: 'snapshot',
- version: 1,
- });
- await historyModel.create({
- documentId,
- payload: { editorData: { version: 2 } },
+ editorData: { tag: 1 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'patch',
- version: 2,
});
- await historyModel.create({
+ const latest = await historyModel.create({
documentId,
- payload: { editorData: { version: 3 } },
- saveSource: 'restore',
- savedAt: new Date('2026-04-11T00:00:02.000Z'),
- storageKind: 'snapshot',
- version: 3,
- });
-
- const firstPage = await historyModel.list({ documentId, limit: 2 });
- const secondPage = await historyModel.list({
- beforeVersion: firstPage.at(-1)?.version,
- documentId,
- limit: 2,
- });
-
- expect(firstPage.map((row) => row.version)).toEqual([3, 2]);
- expect(secondPage.map((row) => row.version)).toEqual([1]);
- });
- });
-
- describe('findByDocumentIdAndVersion', () => {
- it('should find a history row by document id and version', async () => {
- const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
-
- await historyModel.create({
- documentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 2 },
saveSource: 'manual',
- savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
+ savedAt: new Date('2026-04-11T00:00:02.000Z'),
});
- const row = await historyModel.findByDocumentIdAndVersion(documentId, 1);
- expect(row).toMatchObject({ documentId, version: 1, userId });
+ const row = await historyModel.findLatestByDocumentId(documentId);
+ expect(row?.id).toBe(latest.id);
});
});
@@ -267,19 +193,15 @@ describe('DocumentHistoryModel', () => {
const created = await historyModel.create({
documentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 1 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
const otherCreated = await historyModel2.create({
documentId: otherDocumentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 1 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
await historyModel.delete(created.id);
@@ -297,27 +219,21 @@ describe('DocumentHistoryModel', () => {
await historyModel.create({
documentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 1 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
await historyModel.create({
documentId,
- payload: { editorData: { version: 2 } },
+ editorData: { tag: 2 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:02.000Z'),
- storageKind: 'patch',
- version: 2,
});
await historyModel2.create({
documentId: otherDocumentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 1 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
await historyModel.deleteByDocumentId(documentId);
@@ -331,35 +247,21 @@ describe('DocumentHistoryModel', () => {
});
describe('schema assumptions', () => {
- it('should keep document version defaulted to 1 for new documents', async () => {
- const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
-
- const document = await serverDB.query.documents.findFirst({
- where: eq(documents.id, documentId),
- });
-
- expect(document?.version).toBe(1);
- });
-
it('should keep user scoped history rows isolated', async () => {
const documentId = await createTestDocument(documentModel, fileModel, 'Initial content');
const otherDocumentId = await createTestDocument(documentModel2, fileModel2, 'Other content');
const first = await historyModel.create({
documentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 1 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
await historyModel2.create({
documentId: otherDocumentId,
- payload: { editorData: { version: 1 } },
+ editorData: { tag: 1 },
saveSource: 'manual',
savedAt: new Date('2026-04-11T00:00:01.000Z'),
- storageKind: 'snapshot',
- version: 1,
});
const rows = await historyModel.list({ documentId });
diff --git a/packages/database/src/models/document.ts b/packages/database/src/models/document.ts
index e7b9d0faa25..7eb886450f2 100644
--- a/packages/database/src/models/document.ts
+++ b/packages/database/src/models/document.ts
@@ -81,7 +81,6 @@ export class DocumentModel {
title: documents.title,
totalCharCount: documents.totalCharCount,
totalLineCount: documents.totalLineCount,
- version: documents.version,
updatedAt: documents.updatedAt,
userId: documents.userId,
// Exclude large fields: content, pages, editorData
@@ -103,7 +102,6 @@ export class DocumentModel {
content: null,
editorData: null,
pages: null,
- version: item.version,
})) as DocumentItem[];
return { items, total: totalResult[0].count };
diff --git a/packages/database/src/models/documentHistory.ts b/packages/database/src/models/documentHistory.ts
index 657be965874..33db361ef68 100644
--- a/packages/database/src/models/documentHistory.ts
+++ b/packages/database/src/models/documentHistory.ts
@@ -5,7 +5,7 @@ import { documentHistories, documents } from '../schemas';
import type { LobeChatDatabase } from '../type';
export interface QueryDocumentHistoryParams {
- beforeVersion?: number;
+ beforeSavedAt?: Date;
documentId: string;
limit?: number;
}
@@ -69,25 +69,6 @@ export class DocumentHistoryModel {
return result;
};
- findByDocumentIdAndVersion = async (
- documentId: string,
- version: number,
- ): Promise<DocumentHistoryItem | undefined> => {
- const [result] = await this.db
- .select()
- .from(documentHistories)
- .where(
- and(
- eq(documentHistories.documentId, documentId),
- eq(documentHistories.version, version),
- eq(documentHistories.userId, this.userId),
- ),
- )
- .limit(1);
-
- return result;
- };
-
findLatestByDocumentId = async (documentId: string): Promise<DocumentHistoryItem | undefined> => {
const [result] = await this.db
.select()
@@ -98,14 +79,14 @@ export class DocumentHistoryModel {
eq(documentHistories.userId, this.userId),
),
)
- .orderBy(desc(documentHistories.version))
+ .orderBy(desc(documentHistories.savedAt), desc(documentHistories.id))
.limit(1);
return result;
};
list = async ({
- beforeVersion,
+ beforeSavedAt,
documentId,
limit = 50,
}: QueryDocumentHistoryParams): Promise<DocumentHistoryItem[]> => {
@@ -114,19 +95,15 @@ export class DocumentHistoryModel {
eq(documentHistories.userId, this.userId),
];
- if (beforeVersion !== undefined) {
- conditions.push(lt(documentHistories.version, beforeVersion));
+ if (beforeSavedAt !== undefined) {
+ conditions.push(lt(documentHistories.savedAt, beforeSavedAt));
}
return this.db
.select()
.from(documentHistories)
.where(and(...conditions))
- .orderBy(
- desc(documentHistories.version),
- desc(documentHistories.savedAt),
- desc(documentHistories.id),
- )
+ .orderBy(desc(documentHistories.savedAt), desc(documentHistories.id))
.limit(limit);
};
diff --git a/packages/database/src/schemas/documentHistory.ts b/packages/database/src/schemas/documentHistory.ts
index 7b2449f63d1..fe9c94722c0 100644
--- a/packages/database/src/schemas/documentHistory.ts
+++ b/packages/database/src/schemas/documentHistory.ts
@@ -1,7 +1,7 @@
-import { index, integer, jsonb, pgTable, text, uniqueIndex } from 'drizzle-orm/pg-core';
+import { index, jsonb, pgTable, text } from 'drizzle-orm/pg-core';
import { createNanoId } from '../utils/idGenerator';
-import { createdAt, timestamptz, varchar255 } from './_helpers';
+import { timestamptz, varchar255 } from './_helpers';
import { documents } from './file';
import { users } from './user';
@@ -19,21 +19,13 @@ export const documentHistories = pgTable(
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
- version: integer('version').notNull(),
- storageKind: text('storage_kind', { enum: ['snapshot', 'patch'] }).notNull(),
- payload: jsonb('payload').$type<Record<string, any>>().notNull(),
- baseVersion: integer('base_version'),
+ editorData: jsonb('editor_data').$type<Record<string, any>>().notNull(),
saveSource: text('save_source', {
enum: ['autosave', 'manual', 'restore', 'system'],
}).notNull(),
savedAt: timestamptz('saved_at').notNull(),
- createdAt: createdAt(),
},
(table) => [
- uniqueIndex('document_histories_document_id_version_unique').on(
- table.documentId,
- table.version,
- ),
index('document_histories_document_id_saved_at_idx').on(table.documentId, table.savedAt),
index('document_histories_user_id_saved_at_idx').on(table.userId, table.savedAt),
],
diff --git a/packages/database/src/schemas/file.ts b/packages/database/src/schemas/file.ts
index 7f95d277dc4..eeddce70ac9 100644
--- a/packages/database/src/schemas/file.ts
+++ b/packages/database/src/schemas/file.ts
@@ -67,7 +67,6 @@ export const documents = pgTable(
// Metadata
metadata: jsonb('metadata').$type<Record<string, any>>(),
- version: integer('version').notNull().default(1),
// Page/chunk data
pages: jsonb('pages').$type<LobeDocumentPage[]>(),