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 (#10613)

LobeHub Botbe49eec2ed7c
diff --git a/packages/database/src/core/electron.ts b/packages/database/src/core/electron.ts
index 2ed53aec993..207248573e5 100644
--- a/packages/database/src/core/electron.ts
+++ b/packages/database/src/core/electron.ts
@@ -12,7 +12,7 @@ import * as schema from '../schemas';
import { LobeChatDatabase } from '../type';
import migrations from './migrations.json';
-// 用于实例管理的全局对象
+// Global object for instance management
interface LobeGlobal {
pgDB?: LobeChatDatabase;
pgDBInitPromise?: Promise<LobeChatDatabase>;
@@ -22,7 +22,7 @@ interface LobeGlobal {
};
}
-// 确保 globalThis 有我们的命名空间
+// Ensure globalThis has our namespace
declare global {
// eslint-disable-next-line no-var
var __LOBE__: LobeGlobal;
@@ -33,20 +33,20 @@ if (!globalThis.__LOBE__) {
}
/**
- * 尝试创建一个文件锁来确保单例模式
- * 返回 true 表示成功获取锁,false 表示已有其他实例正在运行
+ * Attempt to create a file lock to ensure singleton pattern
+ * Returns true if lock acquired successfully, false if another instance is already running
*/
const acquireLock = async (dbPath: string): Promise<boolean> => {
try {
- // 数据库锁文件路径
+ // Database lock file path
const lockPath = `${dbPath}.lock`;
- // 尝试创建锁文件
+ // Attempt to create lock file
if (!fs.existsSync(lockPath)) {
- // 创建锁文件并写入当前进程 ID
+ // Create lock file and write current process ID
fs.writeFileSync(lockPath, process.pid.toString(), 'utf8');
- // 保存锁信息到全局对象
+ // Save lock information to global object
if (!globalThis.__LOBE__.pgDBLock) {
globalThis.__LOBE__.pgDBLock = {
acquired: true,
@@ -58,19 +58,19 @@ const acquireLock = async (dbPath: string): Promise<boolean> => {
return true;
}
- // 检查锁文件是否过期(超过5分钟未更新)
+ // Check if lock file has expired (not updated for over 5 minutes)
const stats = fs.statSync(lockPath);
const currentTime = Date.now();
const modifiedTime = stats.mtime.getTime();
- // 如果锁文件超过5分钟未更新,视为过期锁
+ // If lock file hasn't been updated for over 5 minutes, consider it expired
if (currentTime - modifiedTime > 5 * 60 * 1000) {
- // 删除过期锁文件
+ // Delete expired lock file
fs.unlinkSync(lockPath);
- // 重新创建锁文件
+ // Recreate lock file
fs.writeFileSync(lockPath, process.pid.toString(), 'utf8');
- // 保存锁信息到全局对象
+ // Save lock information to global object
if (!globalThis.__LOBE__.pgDBLock) {
globalThis.__LOBE__.pgDBLock = {
acquired: true,
@@ -91,7 +91,7 @@ const acquireLock = async (dbPath: string): Promise<boolean> => {
};
/**
- * 释放文件锁
+ * Release file lock
*/
const releaseLock = () => {
if (globalThis.__LOBE__.pgDBLock?.acquired && globalThis.__LOBE__.pgDBLock.lockPath) {
@@ -105,7 +105,7 @@ const releaseLock = () => {
}
};
-// 在进程退出时释放锁
+// Release lock on process exit
process.on('exit', releaseLock);
process.on('SIGINT', () => {
releaseLock();
@@ -129,15 +129,15 @@ const migrateDatabase = async (db: LobeChatDatabase): Promise<void> => {
console.log('schemaHash:', hash);
- // 如果哈希值相同,看下表是否全了
+ // If hash is the same, check if all tables exist
if (hash === cacheHash) {
try {
const drizzleMigration = new DrizzleMigrationModel(db);
- // 检查数据库中是否存在表
+ // Check if tables exist in the database
const tableCount = await drizzleMigration.getTableCounts();
- // 如果表数量大于0,则认为数据库已正确初始化
+ // If table count is greater than 0, assume database is properly initialized
if (tableCount > 0) {
console.log('✅ Electron DB schema already synced');
return;
@@ -152,7 +152,7 @@ const migrateDatabase = async (db: LobeChatDatabase): Promise<void> => {
console.log('🚀 Starting Electron DB migration...');
try {
- // 执行迁移
+ // Execute migration
// @ts-expect-error
await db.dialect.migrate(migrations, db.session, {});
@@ -162,10 +162,10 @@ const migrateDatabase = async (db: LobeChatDatabase): Promise<void> => {
} catch (error) {
console.error('❌ Electron database schema migration failed', error);
- // 尝试查询迁移表数据
+ // Attempt to query migration table data
let migrationsTableData: MigrationTableItem[] = [];
try {
- // 尝试查询迁移表
+ // Attempt to query migration table
const drizzleMigration = new DrizzleMigrationModel(db);
migrationsTableData = await drizzleMigration.getMigrationList();
} catch (queryError) {
@@ -184,12 +184,12 @@ const migrateDatabase = async (db: LobeChatDatabase): Promise<void> => {
};
/**
- * 检查当前是否有活跃的数据库实例,如果有则尝试关闭它
+ * Check if there's an active database instance and attempt to close it if exists
*/
const checkAndCleanupExistingInstance = async () => {
if (globalThis.__LOBE__.pgDB) {
try {
- // 尝试关闭现有的 PGlite 实例 (如果客户端有 close 方法)
+ // Attempt to close existing PGlite instance (if client has close method)
// @ts-expect-error
const client = globalThis.__LOBE__.pgDB?.dialect?.client;
@@ -198,11 +198,11 @@ const checkAndCleanupExistingInstance = async () => {
console.log('✅ Successfully closed previous PGlite instance');
}
- // 重置全局引用
+ // Reset global reference
globalThis.__LOBE__.pgDB = undefined;
} catch (error) {
console.error('❌ Failed to close previous PGlite instance:', error);
- // 继续执行,创建新实例
+ // Continue execution and create new instance
}
}
};
@@ -220,19 +220,19 @@ export const getPgliteInstance = async (): Promise<LobeChatDatabase> => {
}),
);
- // 已经初始化完成,直接返回实例
+ // Already initialized, return instance directly
if (globalThis.__LOBE__.pgDB) return globalThis.__LOBE__.pgDB;
- // 有初始化进行中的Promise,等待它完成
+ // Initialization promise in progress, wait for it to complete
if (globalThis.__LOBE__.pgDBInitPromise) {
console.log('Waiting for existing initialization promise to complete');
return globalThis.__LOBE__.pgDBInitPromise;
}
- // 防止多次调用引起的竞态条件
+ // Prevent race conditions from multiple calls
if (isInitializing) {
console.log('Already initializing, waiting for result');
- // 创建新的 Promise 等待初始化完成
+ // Create new Promise to wait for initialization to complete
return new Promise((resolve, reject) => {
const checkInterval = setInterval(() => {
if (globalThis.__LOBE__.pgDB) {
@@ -248,12 +248,12 @@ export const getPgliteInstance = async (): Promise<LobeChatDatabase> => {
isInitializing = true;
- // 创建初始化Promise并保存
+ // Create and save initialization Promise
globalThis.__LOBE__.pgDBInitPromise = (async () => {
- // 再次检查,以防在等待过程中已有其他调用初始化成功
+ // Check again in case another call succeeded during wait
if (globalThis.__LOBE__.pgDB) return globalThis.__LOBE__.pgDB;
- // 先获取数据库路径
+ // Get database path first
let dbPath: string = '';
try {
dbPath = await electronIpcClient.getDatabasePath();
@@ -263,34 +263,34 @@ export const getPgliteInstance = async (): Promise<LobeChatDatabase> => {
console.log('Database path:', dbPath);
try {
- // 尝试获取数据库锁
+ // Attempt to acquire database lock
const lockAcquired = await acquireLock(dbPath);
if (!lockAcquired) {
throw new Error('Cannot acquire database lock. Another instance might be using it.');
}
- // 检查并清理可能存在的旧实例
+ // Check and cleanup any existing old instances
await checkAndCleanupExistingInstance();
- // 创建新的 PGlite 实例
+ // Create new PGlite instance
console.log('Creating new PGlite instance');
const client = new PGlite(dbPath, {
extensions: { vector },
- // 增加选项以提高稳定性
+ // Add options to improve stability
relaxedDurability: true,
});
- // 等待数据库就绪
+ // Wait for database to be ready
await client.waitReady;
console.log('PGlite state:', client.ready);
- // 创建 Drizzle 数据库实例
+ // Create Drizzle database instance
const db = pgliteDrizzle({ client, schema }) as unknown as LobeChatDatabase;
- // 执行迁移
+ // Execute migration
await migrateDatabase(db);
- // 保存实例引用
+ // Save instance reference
globalThis.__LOBE__.pgDB = db;
console.log('✅ PGlite instance successfully initialized');
@@ -298,9 +298,9 @@ export const getPgliteInstance = async (): Promise<LobeChatDatabase> => {
return db;
} catch (error) {
console.error('❌ Failed to initialize PGlite instance:', error);
- // 清空初始化Promise,允许下次重试
+ // Clear initialization Promise to allow retry next time
globalThis.__LOBE__.pgDBInitPromise = undefined;
- // 释放可能已获取的锁
+ // Release potentially acquired lock
releaseLock();
throw error;
} finally {
diff --git a/packages/database/src/repositories/aiInfra/index.ts b/packages/database/src/repositories/aiInfra/index.ts
index 03ec1348585..5dc9826d403 100644
--- a/packages/database/src/repositories/aiInfra/index.ts
+++ b/packages/database/src/repositories/aiInfra/index.ts
@@ -24,8 +24,8 @@ import { LobeChatDatabase } from '../../type';
type DecryptUserKeyVaults = (encryptKeyVaultsStr: string | null) => Promise<any>;
/**
- * Provider 级默认表(只在本地内置模型没给出 settings.searchImpl 和 settings.searchProvider 时使用)
- * 注意:不在 DB 存储,纯读取时注入
+ * Provider-level search defaults (only used when built-in models don't provide settings.searchImpl and settings.searchProvider)
+ * Note: Not stored in DB, only injected during read
*/
const PROVIDER_SEARCH_DEFAULTS: Record<
string,
@@ -40,12 +40,12 @@ const PROVIDER_SEARCH_DEFAULTS: Record<
hunyuan: { searchImpl: 'params' },
jina: { searchImpl: 'internal' },
minimax: { searchImpl: 'params' },
- // openai: 默认 params,但对 -search- 型号做 internal 特判
+ // openai: defaults to params, but -search- models use internal as special case
openai: { searchImpl: 'params' },
- // perplexity: 默认 internal
+ // perplexity: defaults to internal
perplexity: { searchImpl: 'internal' },
qwen: { searchImpl: 'params' },
- spark: { searchImpl: 'params' }, // 某些模型(如 max-32k)若内置标了 internal,会优先使用内置
+ spark: { searchImpl: 'params' }, // Some models (like max-32k) will prioritize built-in if marked as internal
stepfun: { searchImpl: 'params' },
vertexai: { searchImpl: 'params', searchProvider: 'google' },
wenxin: { searchImpl: 'params' },
@@ -53,7 +53,7 @@ const PROVIDER_SEARCH_DEFAULTS: Record<
zhipu: { searchImpl: 'params' },
};
-// 特殊模型配置 - 模型级别的特殊设置会覆盖服务商默认配置
+// Special model configuration - model-level settings override provider defaults
const MODEL_SEARCH_DEFAULTS: Record<
string,
Record<string, { searchImpl?: 'tool' | 'params' | 'internal'; searchProvider?: string }>
@@ -61,15 +61,15 @@ const MODEL_SEARCH_DEFAULTS: Record<
openai: {
'gpt-4o-mini-search-preview': { searchImpl: 'internal' },
'gpt-4o-search-preview': { searchImpl: 'internal' },
- // 可在此处添加其他特殊模型配置
+ // Add other special model configurations here
},
spark: {
'max-32k': { searchImpl: 'internal' },
},
- // 可在此处添加其他服务商的特殊模型配置
+ // Add special model configurations for other providers here
};
-// 根据 providerId + modelId 推断默认 settings
+// Infer default settings based on providerId + modelId
const inferProviderSearchDefaults = (
providerId: string | undefined,
modelId: string,
@@ -82,11 +82,11 @@ const inferProviderSearchDefaults = (
return (providerId && PROVIDER_SEARCH_DEFAULTS[providerId]) || PROVIDER_SEARCH_DEFAULTS.default;
};
-// 仅在读取时注入 settings; 根据 abilities.search 来添加或删去settings 中的 search 相关字段
+// Only inject settings during read; add or remove search-related fields in settings based on abilities.search
const injectSearchSettings = (providerId: string, item: any) => {
const abilities = item?.abilities || {};
- // 模型显式关闭搜索能力:移除 settings 中的 search 相关字段,确保 UI 不显示启用模型内置搜索
+ // Model explicitly disables search capability: remove search-related fields from settings to prevent UI from showing built-in search
if (abilities.search === false) {
if (item?.settings?.searchImpl || item?.settings?.searchProvider) {
const next = { ...item } as any;
@@ -100,12 +100,12 @@ const injectSearchSettings = (providerId: string, item: any) => {
return item;
}
- // 模型显式开启搜索能力:添加 settings 中的 search 相关字段
+ // Model explicitly enables search capability: add search-related fields to settings
else if (abilities.search === true) {
- // 内置(本地)模型如果已经带了任一字段,直接保留,不覆盖
+ // If built-in (local) model already has either field, preserve it without overriding
if (item?.settings?.searchImpl || item?.settings?.searchProvider) return item;
- // 否则按 providerId + modelId
+ // Otherwise use providerId + modelId
const searchSettings = inferProviderSearchDefaults(providerId, item.id);
return {
@@ -117,7 +117,7 @@ const injectSearchSettings = (providerId: string, item: any) => {
};
}
- // 兼容老版本中数据库没有存储 abilities.search 字段的情况
+ // Compatibility for legacy versions where database doesn't store abilities.search field
return item;
};
@@ -146,7 +146,7 @@ export class AiInfraRepos {
getAiProviderList = async () => {
const userProviders = await this.aiProviderModel.getAiProviderList();
- // 1. 先创建一个基于 DEFAULT_MODEL_PROVIDER_LIST id 顺序的映射
+ // 1. First create a mapping based on DEFAULT_MODEL_PROVIDER_LIST id order
const orderMap = new Map(DEFAULT_MODEL_PROVIDER_LIST.map((item, index) => [item.id, index]));
const builtinProviders = DEFAULT_MODEL_PROVIDER_LIST.map((item) => ({
@@ -161,7 +161,7 @@ export class AiInfraRepos {
const mergedProviders = mergeArrayById(builtinProviders, userProviders);
- // 3. 根据 orderMap 排序
+ // 3. Sort based on orderMap
return mergedProviders.sort((a, b) => {
const orderA = orderMap.get(a.id) ?? Number.MAX_SAFE_INTEGER;
const orderB = orderMap.get(b.id) ?? Number.MAX_SAFE_INTEGER;
@@ -205,7 +205,7 @@ export class AiInfraRepos {
.map<EnabledAiModel & { enabled?: boolean | null }>((item) => {
const user = allModels.find((m) => m.id === item.id && m.providerId === provider.id);
- // 用户未修改本地模型
+ // User hasn't modified local model
if (!user)
return {
...item,
@@ -229,7 +229,7 @@ export class AiInfraRepos {
sort: user.sort || undefined,
type: user.type || item.type,
};
- return injectSearchSettings(provider.id, mergedModel); // 用户修改本地模型,检查搜索设置
+ return injectSearchSettings(provider.id, mergedModel); // User modified local model, check search settings
})
.filter((item) => (filterEnabled ? item.enabled : true));
},
@@ -237,7 +237,7 @@ export class AiInfraRepos {
);
const enabledProviderIds = new Set(enabledProviders.map((item) => item.id));
- // 用户数据库模型,检查搜索设置
+ // User database models, check search settings
const appendedUserModels = allModels
.filter((item) =>
filterEnabled ? enabledProviderIds.has(item.providerId) && item.enabled : true,
@@ -284,7 +284,7 @@ export class AiInfraRepos {
const defaultModels: AiProviderModelListItem[] =
(await this.fetchBuiltinModels(providerId)) || [];
- // 这里不修改搜索设置不影响使用,但是为了get数据统一
+ // Not modifying search settings here doesn't affect usage, but done for data consistency on get
const mergedModel = mergeArrayById(defaultModels, aiModels) as AiProviderModelListItem[];
return mergedModel.map((m) => injectSearchSettings(providerId, m));
diff --git a/packages/database/src/repositories/dataExporter/index.ts b/packages/database/src/repositories/dataExporter/index.ts
index 657e35e802c..00a1d1629e5 100644
--- a/packages/database/src/repositories/dataExporter/index.ts
+++ b/packages/database/src/repositories/dataExporter/index.ts
@@ -105,11 +105,11 @@ export class DataExporterRepos {
try {
const conditions = [];
- // 处理每个关联条件
+ // Process each relation condition
for (const relation of config.relations) {
const sourceData = existingData[relation.sourceTable] || [];
- // 如果源数据为空,这个表可能无法查询到任何数据
+ // If source data is empty, this table may not be able to query any data
if (sourceData.length === 0) {
console.log(
`Source table ${relation.sourceTable} has no data, skipping query for ${table}`,
@@ -121,18 +121,18 @@ export class DataExporterRepos {
conditions.push(inArray(tableObj[relation.field], sourceIds));
}
- // 如果表有userId字段并且不是users表,添加用户过滤
+ // If table has userId field and is not the users table, add user filter
if ('userId' in tableObj && table !== 'users' && !config.relations) {
conditions.push(eq(tableObj.userId, this.userId));
}
- // 组合所有条件
+ // Combine all conditions
const where = conditions.length === 1 ? conditions[0] : and(...conditions);
// @ts-expect-error query
const result = await this.db.query[table].findMany({ where });
- // 只对使用 userId 查询的表移除 userId 字段
+ // Only remove userId field for tables queried with userId
console.log(`Successfully exported table: ${table}, count: ${result.length}`);
return config.relations ? result : this.removeUserId(result);
} catch (error) {
@@ -147,16 +147,16 @@ export class DataExporterRepos {
if (!tableObj) throw new Error(`Table ${table} not found`);
try {
- // 如果有关联配置,使用关联查询
+ // If there's relation config, use relation query
- // 默认使用 userId 查询,特殊情况使用 userField
+ // Default to querying with userId, use userField for special cases
const userField = config.userField || 'userId';
const where = eq(tableObj[userField], this.userId);
// @ts-expect-error query
const result = await this.db.query[table].findMany({ where });
- // 只对使用 userId 查询的表移除 userId 字段
+ // Only remove userId field for tables queried with userId
console.log(`Successfully exported table: ${table}, count: ${result.length}`);
return this.removeUserId(result);
} catch (error) {
@@ -168,7 +168,7 @@ export class DataExporterRepos {
async export(concurrency = 10) {
const result: Record<string, any[]> = {};
- // 1. 首先并发查询所有基础表
+ // 1. First query all base tables concurrently
console.log('Querying base tables...');
const baseResults = await pMap(
DATA_EXPORT_CONFIG.baseTables,
@@ -176,17 +176,17 @@ export class DataExporterRepos {
{ concurrency },
);
- // 更新结果集
+ // Update result set
baseResults.forEach(({ table, data }) => {
result[table] = data;
});
- // 2. 然后并发查询所有关联表
+ // 2. Then query all relation tables concurrently
const relationResults = await pMap(
DATA_EXPORT_CONFIG.relationTables,
async (config) => {
- // 检查所有依赖的源表是否有数据
+ // Check if all dependent source tables have data
const allSourcesHaveData = config.relations.every(
(relation) => (result[relation.sourceTable] || []).length > 0,
);
@@ -204,7 +204,7 @@ export class DataExporterRepos {
{ concurrency },
);
- // 更新结果集
+ // Update result set
relationResults.forEach(({ table, data }) => {
result[table] = data;
});
diff --git a/packages/database/src/repositories/tableViewer/index.ts b/packages/database/src/repositories/tableViewer/index.ts
index 3237be2cafe..755462e9e77 100644
--- a/packages/database/src/repositories/tableViewer/index.ts
+++ b/packages/database/src/repositories/tableViewer/index.ts
@@ -19,7 +19,7 @@ export class TableViewerRepo {
}
/**
- * 获取数据库中所有的表
+ * Get all tables in the database
*/
async getAllTables(schema = 'public'): Promise<TableBasicInfo[]> {
const query = sql`
@@ -47,7 +47,7 @@ export class TableViewerRepo {
}
/**
- * 获取指定表的详细结构信息
+ * Get detailed structure information for a specified table
*/
async getTableDetails(tableName: string): Promise<TableColumnInfo[]> {
const query = sql`
@@ -56,7 +56,7 @@ export class TableViewerRepo {
c.data_type,
c.is_nullable,
c.column_default,
- -- 主键信息
+ -- Primary key information
(
SELECT true
FROM information_schema.table_constraints tc
@@ -66,7 +66,7 @@ export class TableViewerRepo {
AND kcu.column_name = c.column_name
AND tc.constraint_type = 'PRIMARY KEY'
) is_primary_key,
- -- 外键信息
+ -- Foreign key information
(
SELECT json_build_object(
'table', ccu.table_name,
@@ -100,15 +100,15 @@ export class TableViewerRepo {
}
/**
- * 获取表数据,支持分页、排序和筛选
+ * Get table data with support for pagination, sorting, and filtering
*/
async getTableData(tableName: string, pagination: PaginationParams, filters?: FilterCondition[]) {
const offset = (pagination.page - 1) * pagination.pageSize;
- // 构建基础查询
+ // Build base query
let baseQuery = sql`SELECT * FROM ${sql.identifier(tableName)}`;
- // 添加筛选条件
+ // Add filter conditions
if (filters && filters.length > 0) {
const whereConditions = filters.map((filter) => {
const column = sql.identifier(filter.column);
@@ -135,19 +135,19 @@ export class TableViewerRepo {
baseQuery = sql`${baseQuery} WHERE ${sql.join(whereConditions, sql` AND `)}`;
}
- // 添加排序
+ // Add sorting
if (pagination.sortBy) {
const direction = pagination.sortOrder === 'desc' ? sql`DESC` : sql`ASC`;
baseQuery = sql`${baseQuery} ORDER BY ${sql.identifier(pagination.sortBy)} ${direction}`;
}
- // 添加分页
+ // Add pagination
const query = sql`${baseQuery} LIMIT ${pagination.pageSize} OFFSET ${offset}`;
- // 获取总数
+ // Get total count
const countQuery = sql`SELECT COUNT(*) as total FROM ${sql.identifier(tableName)}`;
- // 并行执行查询
+ // Execute queries in parallel
const [data, count] = await Promise.all([this.db.execute(query), this.db.execute(countQuery)]);
return {
@@ -161,7 +161,7 @@ export class TableViewerRepo {
}
/**
- * 更新表中的一行数据
+ * Update a row in the table
*/
async updateRow(
tableName: string,
@@ -185,7 +185,7 @@ export class TableViewerRepo {
}
/**
- * 删除表中的一行数据
+ * Delete a row from the table
*/
async deleteRow(tableName: string, id: string, primaryKeyColumn: string) {
const query = sql`
@@ -197,7 +197,7 @@ export class TableViewerRepo {
}
/**
- * 插入新行数据
+ * Insert new row data
*/
async insertRow(tableName: string, data: Record<string, any>) {
const columns = Object.keys(data).map((key) => sql.identifier(key));
@@ -218,7 +218,7 @@ export class TableViewerRepo {
}
/**
- * 获取表的总记录数
+ * Get total record count of a table
*/
async getTableCount(tableName: string): Promise<number> {
const query = sql`SELECT COUNT(*) as total FROM ${sql.identifier(tableName)}`;
@@ -227,7 +227,7 @@ export class TableViewerRepo {
}
/**
- * 批量删除数据
+ * Batch delete data
*/
async batchDelete(tableName: string, ids: string[], primaryKeyColumn: string) {
const query = sql`
@@ -239,7 +239,7 @@ export class TableViewerRepo {
}
/**
- * 导出表数据(支持分页导出)
+ * Export table data (supports paginated export)
*/
async exportTableData(
tableName: string,