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.

🌐 chore: translate non-English comments to English in packages/database (#10318)

LobeHub Bot02d2121355d8
diff --git a/packages/database/src/client/pglite.ts b/packages/database/src/client/pglite.ts
index 58b8b16f560..ff7bce695f3 100644
--- a/packages/database/src/client/pglite.ts
+++ b/packages/database/src/client/pglite.ts
@@ -8,7 +8,7 @@ export const initPgliteWorker = async (meta: InitMeta) => {
{ meta },
);
- // 监听 worker 状态变化
+ // Listen for worker status changes
worker.onLeaderChange(() => {
console.log('Worker leader changed, isLeader:', worker?.isLeader);
});
diff --git a/packages/database/src/core/db-adaptor.ts b/packages/database/src/core/db-adaptor.ts
index 7be62e1ed1a..1f1e184edf7 100644
--- a/packages/database/src/core/db-adaptor.ts
+++ b/packages/database/src/core/db-adaptor.ts
@@ -5,17 +5,17 @@ import { getPgliteInstance } from './electron';
import { getDBInstance } from './web-server';
/**
- * 懒加载数据库实例
- * 避免每次模块导入时都初始化数据库
+ * Lazy-load database instance
+ * Avoid initializing the database every time the module is imported
*/
let cachedDB: LobeChatDatabase | null = null;
export const getServerDB = async (): Promise<LobeChatDatabase> => {
- // 如果已经有缓存的实例,直接返回
+ // If there's already a cached instance, return it directly
if (cachedDB) return cachedDB;
try {
- // 根据环境选择合适的数据库实例
+ // Select the appropriate database instance based on the environment
cachedDB = isDesktop ? await getPgliteInstance() : getDBInstance();
return cachedDB;
} catch (error) {
diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.ts
index aaad8f7ca57..60d4a10474a 100644
--- a/packages/database/src/models/file.ts
+++ b/packages/database/src/models/file.ts
@@ -101,7 +101,7 @@ export class FileModel {
delete = async (id: string, removeGlobalFile: boolean = true, trx?: Transaction) => {
const executeInTransaction = async (tx: Transaction) => {
- // pglite 环境下不能再 transaction 中使用非事务操作,会阻塞住
+ // In pglite environment, non-transactional operations cannot be used within a transaction as it will block
const file = await this.findById(id, tx);
if (!file) return;
@@ -151,26 +151,26 @@ export class FileModel {
if (ids.length === 0) return [];
return await this.db.transaction(async (trx) => {
- // 1. 先获取文件列表,以便返回删除的文件
+ // 1. First get the file list to return the deleted files
const fileList = await trx.query.files.findMany({
where: and(inArray(files.id, ids), eq(files.userId, this.userId)),
});
if (fileList.length === 0) return [];
- // 提取需要检查的文件哈希值
+ // Extract file hashes that need to be checked
const hashList = fileList.map((file) => file.fileHash!).filter(Boolean);
- // 2. 删除相关的 chunks
+ // 2. Delete related chunks
await this.deleteFileChunks(trx as any, ids);
- // 3. 删除文件记录
+ // 3. Delete file records
await trx.delete(files).where(and(inArray(files.id, ids), eq(files.userId, this.userId)));
- // 如果不需要删除全局文件,直接返回
+ // If global files don't need to be deleted, return directly
if (!removeGlobalFile || hashList.length === 0) return fileList;
- // 4. 找出不再被引用的哈希值
+ // 4. Find hashes that are no longer referenced
const remainingFiles = await trx
.select({
fileHash: files.fileHash,
@@ -178,18 +178,18 @@ export class FileModel {
.from(files)
.where(inArray(files.fileHash, hashList));
- // 将仍在使用的哈希值放入Set中,便于快速查找
+ // Put still-in-use hashes into a Set for quick lookup
const usedHashes = new Set(remainingFiles.map((file) => file.fileHash));
- // 找出需要删除的哈希值(不再被任何文件使用的)
+ // Find hashes to delete (those no longer used by any file)
const hashesToDelete = hashList.filter((hash) => !usedHashes.has(hash));
if (hashesToDelete.length === 0) return fileList;
- // 5. 删除不再被引用的全局文件
+ // 5. Delete global files that are no longer referenced
await trx.delete(globalFiles).where(inArray(globalFiles.hashId, hashesToDelete));
- // 返回删除的文件列表
+ // Return the list of deleted files
return fileList;
});
};
@@ -206,7 +206,7 @@ export class FileModel {
knowledgeBaseId,
showFilesInKnowledgeBase,
}: QueryFileListParams = {}) => {
- // 1. query where
+ // 1. Build where clause
let whereClause = and(
q ? ilike(files.name, `%${q}%`) : undefined,
eq(files.userId, this.userId),
@@ -224,7 +224,7 @@ export class FileModel {
}
}
- // 2. order part
+ // 2. Build order clause
let orderByClause = desc(files.createdAt);
// create a map for sortable fields
@@ -241,7 +241,7 @@ export class FileModel {
orderByClause = sortFunction(sortableFields[sorter as SortableField]);
}
- // 3. build query
+ // 3. Build base query
let query = this.db
.select({
chunkTaskId: files.chunkTaskId,
@@ -256,7 +256,7 @@ export class FileModel {
})
.from(files);
- // 4. add knowledge base query
+ // 4. Add knowledge base query if needed
if (knowledgeBaseId) {
// if knowledgeBaseId is provided, it means we are querying files in a knowledge-base
@@ -269,7 +269,7 @@ export class FileModel {
),
);
}
- // 5.if we don't show files in knowledge base, we need exclude files in knowledge base
+ // 5. If we don't show files in knowledge base, exclude them
else if (!showFilesInKnowledgeBase) {
whereClause = and(
whereClause,
@@ -279,7 +279,7 @@ export class FileModel {
);
}
- // or we are just filter in the global files
+ // Otherwise, we are just filtering in the global files
return query.where(whereClause).orderBy(orderByClause);
};
@@ -347,11 +347,11 @@ export class FileModel {
),
});
- // 抽象出通用的删除 chunks 方法
+ // Abstract common method for deleting chunks
private deleteFileChunks = async (trx: PgTransaction<any>, fileIds: string[]) => {
if (fileIds.length === 0) return;
- // 获取要删除的文件相关的所有 chunk IDs(移除知识库保护逻辑)
+ // Get all chunk IDs related to the files to be deleted (knowledge base protection logic removed)
const relatedChunks = await trx
.select({ chunkId: fileChunks.chunkId })
.from(fileChunks)
@@ -361,15 +361,15 @@ export class FileModel {
if (chunkIds.length === 0) return;
- // 批量处理配置
+ // Batch processing configuration
const BATCH_SIZE = 1000;
const MAX_CONCURRENT_BATCHES = 3;
- // 分批并行处理
+ // Process in batches concurrently
for (let i = 0; i < chunkIds.length; i += BATCH_SIZE * MAX_CONCURRENT_BATCHES) {
const batchPromises = [];
- // 创建多个并行批次
+ // Create multiple parallel batches
for (let j = 0; j < MAX_CONCURRENT_BATCHES; j++) {
const startIdx = i + j * BATCH_SIZE;
if (startIdx >= chunkIds.length) break;
@@ -377,29 +377,29 @@ export class FileModel {
const batchChunkIds = chunkIds.slice(startIdx, startIdx + BATCH_SIZE);
if (batchChunkIds.length === 0) continue;
- // 按正确的删除顺序处理每个批次,失败不阻止流程
+ // Process each batch in the correct deletion order, failures do not block the flow
const batchPromise = (async () => {
- // 1. 删除 embeddings (最顶层,有外键依赖)
+ // 1. Delete embeddings (top-level, has foreign key dependencies)
try {
await trx.delete(embeddings).where(inArray(embeddings.chunkId, batchChunkIds));
} catch (e) {
- // 静默处理,不阻止删除流程
+ // Silent handling, does not block deletion process
console.warn('Failed to delete embeddings:', e);
}
- // 2. 删除 documentChunks 关联 (如果存在)
+ // 2. Delete documentChunks association (if exists)
try {
await trx.delete(documentChunks).where(inArray(documentChunks.chunkId, batchChunkIds));
} catch (e) {
- // 静默处理,不阻止删除流程
+ // Silent handling, does not block deletion process
console.warn('Failed to delete documentChunks:', e);
}
- // 3. 删除 chunks (核心数据)
+ // 3. Delete chunks (core data)
try {
await trx.delete(chunks).where(inArray(chunks.id, batchChunkIds));
} catch (e) {
- // 静默处理,不阻止删除流程
+ // Silent handling, does not block deletion process
console.warn('Failed to delete chunks:', e);
}
})();
@@ -407,15 +407,15 @@ export class FileModel {
batchPromises.push(batchPromise);
}
- // 等待当前批次的所有任务完成
+ // Wait for all tasks in the current batch to complete
await Promise.all(batchPromises);
}
- // 4. 最后删除 fileChunks 关联表记录
+ // 4. Finally delete fileChunks association table records
try {
await trx.delete(fileChunks).where(inArray(fileChunks.fileId, fileIds));
} catch (e) {
- // 静默处理,不阻止删除流程
+ // Silent handling, does not block deletion process
console.warn('Failed to delete fileChunks:', e);
}
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 6f30ad67f14..cfa0536044c 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -155,7 +155,7 @@ export class MessageModel {
})),
);
- // 获取关联的文档内容
+ // Get associated document content
const fileIds = relatedFileList.map((file) => file.id).filter(Boolean);
let documentsMap: Record<string, string> = {};
@@ -662,17 +662,17 @@ export class MessageModel {
deleteMessage = async (id: string) => {
return this.db.transaction(async (tx) => {
- // 1. 查询要删除的 message 的完整信息
+ // 1. Query the complete information of the message to be deleted
const message = await tx
.select()
.from(messages)
.where(and(eq(messages.id, id), eq(messages.userId, this.userId)))
.limit(1);
- // 如果找不到要删除的 message,直接返回
+ // If the message to be deleted is not found, return directly
if (message.length === 0) return;
- // 2. 检查 message 是否包含 tools
+ // 2. Check if the message contains tools
const toolCallIds = (message[0].tools as ChatToolPayload[])
?.map((tool) => tool.id)
.filter(Boolean);
@@ -680,7 +680,7 @@ export class MessageModel {
let relatedMessageIds: string[] = [];
if (toolCallIds?.length > 0) {
- // 3. 如果 message 包含 tools,查询出所有相关联的 message id
+ // 3. If the message contains tools, query all associated message ids
const res = await tx
.select({ id: messagePlugins.id })
.from(messagePlugins)
@@ -689,10 +689,10 @@ export class MessageModel {
relatedMessageIds = res.map((row) => row.id);
}
- // 4. 合并要删除的 message id 列表
+ // 4. Merge the list of message ids to be deleted
const messageIdsToDelete = [id, ...relatedMessageIds];
- // 5. 删除所有相关的 message
+ // 5. Delete all related messages
await tx.delete(messages).where(inArray(messages.id, messageIdsToDelete));
});
};
diff --git a/packages/database/src/schemas/file.ts b/packages/database/src/schemas/file.ts
index 032360ee6c2..301584a70af 100644
--- a/packages/database/src/schemas/file.ts
+++ b/packages/database/src/schemas/file.ts
@@ -38,7 +38,7 @@ export type NewGlobalFile = typeof globalFiles.$inferInsert;
export type GlobalFileItem = typeof globalFiles.$inferSelect;
/**
- * 文档表 - 存储文件内容或网页搜索结果
+ * Documents table - Stores file content or web search results
*/
// @ts-ignore
export const documents = pgTable(
@@ -48,7 +48,7 @@ export const documents = pgTable(
.$defaultFn(() => idGenerator('documents', 16))
.primaryKey(),
- // 基本信息
+ // Basic information
title: text('title'),
content: text('content'),
@@ -56,34 +56,34 @@ export const documents = pgTable(
fileType: varchar('file_type', { length: 255 }).notNull(),
filename: text('filename'),
- // 统计信息
+ // Statistics
totalCharCount: integer('total_char_count').notNull(),
totalLineCount: integer('total_line_count').notNull(),
- // 元数据
+ // Metadata
metadata: jsonb('metadata').$type<Record<string, any>>(),
- // 页面/块数据
+ // Page/chunk data
pages: jsonb('pages').$type<LobeDocumentPage[]>(),
- // 来源类型
+ // Source type
sourceType: text('source_type', { enum: ['file', 'web', 'api'] }).notNull(),
- source: text('source').notNull(), // 文件路径或网页URL
+ source: text('source').notNull(), // File path or web URL
- // 关联文件(可选)
+ // Associated file (optional)
// Forward reference to files table defined below
// eslint-disable-next-line @typescript-eslint/no-use-before-define
// @ts-expect-error - files is defined later in this file, forward reference is valid at runtime
// eslint-disable-next-line @typescript-eslint/no-use-before-define
fileId: text('file_id').references(() => files.id, { onDelete: 'set null' }),
- // 父文档(用于文件夹层级结构)
+ // Parent document (for folder hierarchy structure)
// @ts-ignore
parentId: varchar('parent_id', { length: 255 }).references(() => documents.id, {
onDelete: 'set null',
}),
- // 用户关联
+ // User association
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
@@ -91,7 +91,7 @@ export const documents = pgTable(
editorData: jsonb('editor_data').$type<Record<string, any>>(),
- // 时间戳
+ // Timestamps
...timestamps,
},
(table) => [
@@ -133,7 +133,7 @@ export const files = pgTable(
url: text('url').notNull(),
source: text('source').$type<FileSource>(),
- // 父文档(用于文件夹层级结构)
+ // Parent document (for folder hierarchy structure)
// @ts-ignore
parentId: varchar('parent_id', { length: 255 }).references(() => documents.id, {
onDelete: 'set null',
diff --git a/packages/database/src/schemas/message.ts b/packages/database/src/schemas/message.ts
index 2f936c81196..00327cdd70c 100644
--- a/packages/database/src/schemas/message.ts
+++ b/packages/database/src/schemas/message.ts
@@ -36,25 +36,25 @@ export const messageGroups = pgTable(
.$defaultFn(() => idGenerator('messageGroups'))
.notNull(),
- // 关联关系 - 只需要 topic 层级
+ // Association - only needs topic level
topicId: text('topic_id').references(() => topics.id, { onDelete: 'cascade' }),
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
- // 支持嵌套结构
+ // Support nested structure
// @ts-ignore
parentGroupId: varchar255('parent_group_id').references(() => messageGroups.id, {
onDelete: 'cascade',
}),
- // 关联的用户消息
+ // Associated user message
// eslint-disable-next-line @typescript-eslint/no-use-before-define
parentMessageId: text('parent_message_id').references(() => messages.id, {
onDelete: 'cascade',
}),
- // 元数据
+ // Metadata
title: varchar255('title'),
description: text('description'),
diff --git a/packages/database/src/schemas/rag.ts b/packages/database/src/schemas/rag.ts
index 84a395bb365..5e675ab50de 100644
--- a/packages/database/src/schemas/rag.ts
+++ b/packages/database/src/schemas/rag.ts
@@ -89,8 +89,8 @@ export type NewEmbeddingsItem = typeof embeddings.$inferInsert;
export type EmbeddingsSelectItem = typeof embeddings.$inferSelect;
/**
- * 文档块表 - 将文档内容分割成块并关联到 chunks 表,用于向量检索
- * 注意:此表可选,如果已经使用 pages 字段存储了文档块,可以不需要此表
+ * Document chunks table - Splits document content into chunks and associates them with the chunks table for vector retrieval
+ * Note: This table is optional, if the pages field is already being used to store document chunks, this table may not be needed
*/
export const documentChunks = pgTable(
'document_chunks',