Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

refactor(documents): simplified document fts management (#17)

Corentin THOMASSETc00b2b5bbd88
diff --git a/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx b/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
index 4e7a1796..e2903eb7 100644
--- a/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
+++ b/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx
@@ -67,13 +67,28 @@ export const CommandPaletteProvider: ParentComponent = (props) => {
},
));
- const getCommandData = () => [
+ createEffect(on(
+ getIsCommandPaletteOpen,
+ (isCommandPaletteOpen) => {
+ if (isCommandPaletteOpen) {
+ setMatchingDocuments([]);
+ }
+ },
+ ));
+
+ const getCommandData = (): {
+ label: string;
+ forceMatch?: boolean;
+ options: { label: string; icon: string; action: () => void; forceMatch?: boolean }[];
+ }[] => [
{
label: 'Documents',
+ forceMatch: true,
options: getMatchingDocuments().map(document => ({
label: document.name,
icon: getDocumentIcon({ document }),
action: () => navigate(`/organizations/${params.organizationId}/documents/${document.id}`),
+ forceMatch: true,
})),
},
{
@@ -110,11 +125,13 @@ export const CommandPaletteProvider: ParentComponent = (props) => {
closeCommandPalette: () => setIsCommandPaletteOpen(false),
}}
>
+
<CommandDialog
class="rounded-lg border shadow-md"
open={getIsCommandPaletteOpen()}
onOpenChange={setIsCommandPaletteOpen}
>
+
<CommandInput placeholder="Search commands" onValueChange={setSearchQuery} />
<CommandList>
<Show when={getIsLoading()}>
@@ -123,16 +140,18 @@ export const CommandPaletteProvider: ParentComponent = (props) => {
</CommandLoading>
</Show>
<Show when={!getIsLoading()}>
- <CommandEmpty>
- No results found.
- </CommandEmpty>
+ <Show when={getMatchingDocuments().length === 0}>
+ <CommandEmpty>
+ No results found.
+ </CommandEmpty>
+ </Show>
<For each={getCommandData().filter(section => section.options.length > 0)}>
{section => (
- <CommandGroup heading={section.label}>
+ <CommandGroup heading={section.label} forceMount={section.forceMatch ?? false}>
<For each={section.options}>
{item => (
- <CommandItem onSelect={() => onCommandSelect(item)}>
+ <CommandItem onSelect={() => onCommandSelect(item)} forceMount={item.forceMatch ?? false}>
<span class={cn('mr-2 ml-2 size-4 text-primary', item.icon)} />
<span>{item.label}</span>
</CommandItem>
diff --git a/apps/papra-client/src/modules/documents/components/documents-paginated-list.component.tsx b/apps/papra-client/src/modules/documents/components/documents-paginated-list.component.tsx
index 2ddeedf1..666eead9 100644
--- a/apps/papra-client/src/modules/documents/components/documents-paginated-list.component.tsx
+++ b/apps/papra-client/src/modules/documents/components/documents-paginated-list.component.tsx
@@ -48,7 +48,7 @@ export const DocumentsPaginatedList: Component<{ organizationId: string }> = (pr
</A>
<div class="text-xs text-muted-foreground lh-tight">
- {formatBytes({ bytes: data.row.original.size, base: 1000 })}
+ {formatBytes({ bytes: data.row.original.originalSize, base: 1000 })}
{' '}
-
{' '}
diff --git a/apps/papra-client/src/modules/documents/documents.types.ts b/apps/papra-client/src/modules/documents/documents.types.ts
index e658f30a..0297bb61 100644
--- a/apps/papra-client/src/modules/documents/documents.types.ts
+++ b/apps/papra-client/src/modules/documents/documents.types.ts
@@ -3,7 +3,7 @@ export type Document = {
organizationId: string;
name: string;
mimeType: string;
- size: number;
+ originalSize: number;
createdAt: Date;
updatedAt?: Date;
};
diff --git a/apps/papra-client/src/modules/documents/pages/documents.page.tsx b/apps/papra-client/src/modules/documents/pages/documents.page.tsx
index 4e5ce558..43142551 100644
--- a/apps/papra-client/src/modules/documents/pages/documents.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/documents.page.tsx
@@ -33,7 +33,7 @@ const DocumentCard: Component<{ document: Document; organizationId?: string }> =
</A>
<div class="text-xs text-muted-foreground lh-tight">
- {formatBytes({ bytes: props.document.size, base: 1000 })}
+ {formatBytes({ bytes: props.document.originalSize, base: 1000 })}
{' '}
-
{' '}
diff --git a/apps/papra-server/migrations/0000_lame_wendell_rand.sql b/apps/papra-server/migrations/0000_busy_iron_fist.sql
similarity index 94%
rename from apps/papra-server/migrations/0000_lame_wendell_rand.sql
rename to apps/papra-server/migrations/0000_busy_iron_fist.sql
index 3fdc4cd8..3dbf7a05 100644
--- a/apps/papra-server/migrations/0000_lame_wendell_rand.sql
+++ b/apps/papra-server/migrations/0000_busy_iron_fist.sql
@@ -21,10 +21,8 @@ CREATE TABLE `documents` (
`deleted_by` text,
`original_name` text NOT NULL,
`original_size` integer DEFAULT 0 NOT NULL,
- `storage_key` text NOT NULL,
+ `original_storage_key` text NOT NULL,
`name` text NOT NULL,
- `size` integer DEFAULT 0 NOT NULL,
- `status` text DEFAULT 'pending' NOT NULL,
`mime_type` text NOT NULL,
`content` text DEFAULT '' NOT NULL,
FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade,
diff --git a/apps/papra-server/migrations/0001_supreme_odin.sql b/apps/papra-server/migrations/0001_unknown_umar.sql
similarity index 64%
rename from apps/papra-server/migrations/0001_supreme_odin.sql
rename to apps/papra-server/migrations/0001_unknown_umar.sql
index 7cc1a0cd..7e5095dd 100644
--- a/apps/papra-server/migrations/0001_supreme_odin.sql
+++ b/apps/papra-server/migrations/0001_unknown_umar.sql
@@ -1,6 +1,6 @@
--- Custom SQL migration file, put your code below! --
+-- Migration for adding full-text search virtual table for documents
-CREATE VIRTUAL TABLE documents_fts USING fts5(id UNINDEXED, name, original_name, content, content='documents', prefix='2 3 4');
+CREATE VIRTUAL TABLE documents_fts USING fts5(id UNINDEXED, name, original_name, content, prefix='2 3 4');
--> statement-breakpoint
-- Copy data from documents to documents_fts for existing records
@@ -14,11 +14,10 @@ END;
--> statement-breakpoint
CREATE TRIGGER trigger_documents_fts_update AFTER UPDATE ON documents BEGIN
- INSERT INTO documents_fts(documents_fts, id) VALUES('delete', old.id);
- INSERT INTO documents_fts(id, name, original_name, content) VALUES (new.id, new.name, new.original_name, new.content);
+ UPDATE documents_fts SET name = new.name, original_name = new.original_name, content = new.content WHERE id = new.id;
END;
--> statement-breakpoint
CREATE TRIGGER trigger_documents_fts_delete AFTER DELETE ON documents BEGIN
- INSERT INTO documents_fts(documents_fts, id) VALUES('delete', old.id);
-END;
\ No newline at end of file
+ DELETE FROM documents_fts WHERE id = old.id;
+END;
diff --git a/apps/papra-server/migrations/meta/0000_snapshot.json b/apps/papra-server/migrations/meta/0000_snapshot.json
index 7fdd0fae..92eee675 100644
--- a/apps/papra-server/migrations/meta/0000_snapshot.json
+++ b/apps/papra-server/migrations/meta/0000_snapshot.json
@@ -1,7 +1,7 @@
{
"version": "6",
"dialect": "sqlite",
- "id": "74d7233a-2257-411c-b8cd-b5df0523bbff",
+ "id": "3be32f9a-68f4-4aee-9fed-e3d89ba031c0",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"auth_tokens": {
@@ -162,8 +162,8 @@
"autoincrement": false,
"default": 0
},
- "storage_key": {
- "name": "storage_key",
+ "original_storage_key": {
+ "name": "original_storage_key",
"type": "text",
"primaryKey": false,
"notNull": true,
@@ -176,22 +176,6 @@
"notNull": true,
"autoincrement": false
},
- "size": {
- "name": "size",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false,
- "default": "'pending'"
- },
"mime_type": {
"name": "mime_type",
"type": "text",
diff --git a/apps/papra-server/migrations/meta/0001_snapshot.json b/apps/papra-server/migrations/meta/0001_snapshot.json
index 07b06d8d..1ca44976 100644
--- a/apps/papra-server/migrations/meta/0001_snapshot.json
+++ b/apps/papra-server/migrations/meta/0001_snapshot.json
@@ -1,6 +1,6 @@
{
- "id": "b40309ae-eb2f-4eb4-9cce-a6ccb6ddc820",
- "prevId": "74d7233a-2257-411c-b8cd-b5df0523bbff",
+ "id": "f209c9bf-ecfe-4240-a1c7-4731fed516b4",
+ "prevId": "3be32f9a-68f4-4aee-9fed-e3d89ba031c0",
"version": "6",
"dialect": "sqlite",
"tables": {
@@ -162,8 +162,8 @@
"autoincrement": false,
"default": 0
},
- "storage_key": {
- "name": "storage_key",
+ "original_storage_key": {
+ "name": "original_storage_key",
"type": "text",
"primaryKey": false,
"notNull": true,
@@ -176,22 +176,6 @@
"notNull": true,
"autoincrement": false
},
- "size": {
- "name": "size",
- "type": "integer",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false,
- "default": 0
- },
- "status": {
- "name": "status",
- "type": "text",
- "primaryKey": false,
- "notNull": true,
- "autoincrement": false,
- "default": "'pending'"
- },
"mime_type": {
"name": "mime_type",
"type": "text",
diff --git a/apps/papra-server/migrations/meta/_journal.json b/apps/papra-server/migrations/meta/_journal.json
index 3bcf3f1f..d84b371d 100644
--- a/apps/papra-server/migrations/meta/_journal.json
+++ b/apps/papra-server/migrations/meta/_journal.json
@@ -5,15 +5,15 @@
{
"idx": 0,
"version": "6",
- "when": 1736080578539,
- "tag": "0000_lame_wendell_rand",
+ "when": 1736198123938,
+ "tag": "0000_busy_iron_fist",
"breakpoints": true
},
{
"idx": 1,
"version": "6",
- "when": 1736080611791,
- "tag": "0001_supreme_odin",
+ "when": 1736198126637,
+ "tag": "0001_unknown_umar",
"breakpoints": true
}
]
diff --git a/apps/papra-server/src/modules/documents/documents.repository.test.ts b/apps/papra-server/src/modules/documents/documents.repository.test.ts
index 239846f3..aede97dd 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.test.ts
@@ -20,7 +20,7 @@ describe('documents repository', () => {
mimeType: 'application/pdf',
name: 'Document 1',
originalName: 'document-1.pdf',
- storageKey: 'document-1.pdf',
+ originalStorageKey: 'document-1.pdf',
});
expect(document).to.include({
@@ -29,7 +29,7 @@ describe('documents repository', () => {
mimeType: 'application/pdf',
name: 'Document 1',
originalName: 'document-1.pdf',
- storageKey: 'document-1.pdf',
+ originalStorageKey: 'document-1.pdf',
isDeleted: false,
});
@@ -46,7 +46,7 @@ describe('documents repository', () => {
mimeType: 'application/pdf',
name: 'Document 1',
originalName: 'document-1.pdf',
- storageKey: 'document-1.pdf',
+ originalStorageKey: 'document-1.pdf',
isDeleted: false,
});
@@ -72,9 +72,9 @@ describe('documents repository', () => {
organizations: [{ id: 'organization-1', name: 'Organization 1' }],
organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
documents: [
- { id: 'doc-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', storageKey: '', mimeType: 'application/pdf' },
- { id: 'doc-2', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', storageKey: '', mimeType: 'application/pdf' },
- { id: 'doc-3', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', storageKey: '', mimeType: 'application/pdf' },
+ { id: 'doc-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf' },
+ { id: 'doc-2', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', originalStorageKey: '', mimeType: 'application/pdf' },
+ { id: 'doc-3', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', originalStorageKey: '', mimeType: 'application/pdf' },
],
});
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index bf7d9cc8..4ce3e368 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -81,7 +81,7 @@ function setupCreateDocumentRoute({ app }: { app: ServerInstance }) {
organizationId,
documentsRepository,
documentsStorageService,
-
+
});
return context.json({
@@ -248,7 +248,7 @@ function setupGetDocumentFileRoute({ app }: { app: ServerInstance }) {
const documentsStorageService = await createDocumentStorageService({ config });
- const { fileStream } = await documentsStorageService.getFileStream({ storageKey: document.storageKey });
+ const { fileStream } = await documentsStorageService.getFileStream({ storageKey: document.originalStorageKey });
return context.body(
fileStream,
diff --git a/apps/papra-server/src/modules/documents/documents.table.test.ts b/apps/papra-server/src/modules/documents/documents.table.test.ts
new file mode 100644
index 00000000..b3caa9bb
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/documents.table.test.ts
@@ -0,0 +1,178 @@
+import { eq, sql } from 'drizzle-orm';
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { documentsTable } from './documents.table';
+
+describe('documents table', () => {
+ describe('table documents_fts', () => {
+ describe('the documents_fts table is synchronized with the documents table using triggers', async () => {
+ test('when inserting a document, a corresponding row is inserted in the documents_fts table', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'user-1', email: '[email protected]' }],
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
+ });
+
+ await db.insert(documentsTable).values([
+ {
+ id: 'document-1',
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Document 1',
+ originalName: 'document-1.pdf',
+ originalStorageKey: 'document-1.pdf',
+ content: 'lorem ipsum',
+ },
+ {
+ id: 'document-2',
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Photo 1',
+ originalName: 'photo-1.jpg',
+ originalStorageKey: 'photo-1.jpg',
+ content: 'dolor sit amet',
+ },
+ ]);
+
+ const { rows } = await db.run(sql`SELECT * FROM documents_fts;`);
+
+ expect(rows).to.eql([
+ {
+ id: 'document-1',
+ name: 'Document 1',
+ content: 'lorem ipsum',
+ original_name: 'document-1.pdf',
+ },
+ {
+ id: 'document-2',
+ name: 'Photo 1',
+ content: 'dolor sit amet',
+ original_name: 'photo-1.jpg',
+ },
+ ]);
+
+ const { rows: searchResults } = await db.run(sql`SELECT * FROM documents_fts WHERE documents_fts MATCH 'lorem';`);
+
+ expect(searchResults).to.eql([
+ {
+ id: 'document-1',
+ name: 'Document 1',
+ content: 'lorem ipsum',
+ original_name: 'document-1.pdf',
+ },
+ ]);
+ });
+
+ test('when updating a document, the corresponding row in the documents_fts table is updated', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'user-1', email: '[email protected]' }],
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
+ });
+
+ await db.insert(documentsTable).values([
+ {
+ id: 'document-1',
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Document 1',
+ originalName: 'document-1.pdf',
+ originalStorageKey: 'document-1.pdf',
+ content: 'lorem ipsum',
+ },
+ {
+ id: 'document-2',
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Photo 1',
+ originalName: 'photo-1.jpg',
+ originalStorageKey: 'photo-1.jpg',
+ content: 'dolor sit amet',
+ },
+ ]);
+
+ await db.update(documentsTable).set({ content: 'foo bar baz' }).where(eq(documentsTable.id, 'document-1'));
+
+ const { rows } = await db.run(sql`SELECT * FROM documents_fts;`);
+
+ expect(rows).to.eql([
+ {
+ id: 'document-1',
+ name: 'Document 1',
+ content: 'foo bar baz',
+ original_name: 'document-1.pdf',
+ },
+ {
+ id: 'document-2',
+ name: 'Photo 1',
+ content: 'dolor sit amet',
+ original_name: 'photo-1.jpg',
+ },
+ ]);
+
+ const { rows: searchResults } = await db.run(sql`SELECT * FROM documents_fts WHERE documents_fts MATCH 'foo';`);
+
+ expect(searchResults).to.eql([
+ {
+ id: 'document-1',
+ name: 'Document 1',
+ content: 'foo bar baz',
+ original_name: 'document-1.pdf',
+ },
+ ]);
+ });
+
+ test('when deleting a document, the corresponding row in the documents_fts table is deleted', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'user-1', email: '[email protected]' }],
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
+ });
+
+ await db.insert(documentsTable).values([
+ {
+ id: 'document-1',
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Document 1',
+ originalName: 'document-1.pdf',
+ originalStorageKey: 'document-1.pdf',
+ content: 'lorem ipsum',
+ },
+ {
+ id: 'document-2',
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Photo 1',
+ originalName: 'photo-1.jpg',
+ originalStorageKey: 'photo-1.jpg',
+ content: 'dolor sit amet',
+ },
+ ]);
+
+ await db.delete(documentsTable).where(eq(documentsTable.id, 'document-1'));
+
+ const { rows } = await db.run(sql`SELECT * FROM documents_fts;`);
+
+ expect(rows).to.eql([
+ {
+ id: 'document-2',
+ name: 'Photo 1',
+ content: 'dolor sit amet',
+ original_name: 'photo-1.jpg',
+ },
+ ]);
+
+ const { rows: searchResults } = await db.run(sql`SELECT * FROM documents_fts WHERE documents_fts MATCH 'lorem';`);
+
+ expect(searchResults).to.eql([]);
+ });
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/documents.table.ts b/apps/papra-server/src/modules/documents/documents.table.ts
index 1a56b90a..a9af7c53 100644
--- a/apps/papra-server/src/modules/documents/documents.table.ts
+++ b/apps/papra-server/src/modules/documents/documents.table.ts
@@ -14,14 +14,11 @@ export const documentsTable = sqliteTable('documents', {
deletedBy: text('deleted_by').references(() => usersTable.id, { onDelete: 'set null', onUpdate: 'cascade' }),
originalName: text('original_name').notNull(),
- // originalChecksum: text('original_checksum').notNull(),
originalSize: integer('original_size').notNull().default(0),
- storageKey: text('storage_key').notNull(),
+ originalStorageKey: text('original_storage_key').notNull(),
name: text('name').notNull(),
- // mimeType: text('mime_type').notNull(),
- size: integer('size').notNull().default(0),
- status: text('status').notNull().default('pending'),
mimeType: text('mime_type').notNull(),
content: text('content').notNull().default(''),
+
});
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.test.ts b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
index 78c07ad6..72af13d5 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
@@ -39,9 +39,8 @@ describe('documents usecases', () => {
createdBy: 'user-1',
name: 'file.txt',
originalName: 'file.txt',
- size: 7,
originalSize: 7,
- storageKey: 'organization-1/originals/doc_1.txt',
+ originalStorageKey: 'organization-1/originals/doc_1.txt',
mimeType: 'text/plain',
deletedBy: null,
deletedAt: null,
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.ts
index 6093e92c..7dfb24d9 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts
@@ -42,9 +42,8 @@ export async function createDocument({
organizationId,
originalName: fileName,
createdBy: userId,
- size,
originalSize: size,
- storageKey,
+ originalStorageKey: storageKey,
mimeType,
});