Commit b48e560d by liimin

feat(sqlite): 优化数据库路径获取并添加缓存机制

- 在 PathUtils 中实现两级缓存(内存和持久化存储)以提升文件系统根路径获取性能
- 修改 SQLite 类,使其通过 PathUtils 获取数据库完整路径,避免硬编码
- 增强数据库打开逻辑,添加重复打开检测和错误处理(如 -1402 错误视为成功)
- 在 recordManager 索引文件中导出新增的 FileUploadManager 模块
1 parent b8619668
import TaskQueue from '../utils/TaskQueue' import TaskQueue from '../utils/TaskQueue'
import {PathUtils} from '../utils/recordManager/index'
class SQLite { class SQLite {
static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例 static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例
...@@ -9,6 +9,7 @@ class SQLite { ...@@ -9,6 +9,7 @@ class SQLite {
this.description = description || 'SQLite DB' this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null this.db = null
this.dbPath = null // 存储数据库的完整路径
// 初始化该数据库的队列(如果不存在) // 初始化该数据库的队列(如果不存在)
if (!SQLite._queues[name]) { if (!SQLite._queues[name]) {
SQLite._queues[name] = new TaskQueue(`SQLite:${name}`) SQLite._queues[name] = new TaskQueue(`SQLite:${name}`)
...@@ -21,13 +22,48 @@ class SQLite { ...@@ -21,13 +22,48 @@ class SQLite {
return queueInstance.enqueue(task) return queueInstance.enqueue(task)
} }
init() { async init() {
return new Promise((resolve, reject) => { // 如果已经有路径,直接使用
if (this.dbPath) {
uni.$logger?.local?.info(`[SQLite] 使用已有路径: ${this.dbPath}`)
return this.openDatabase()
}
// 获取当前文档目录路径
const rootPath = await PathUtils.getFilePath()
this.dbPath = `${rootPath}${this.name}.db`
uni.$logger?.local?.info(`[SQLite] 数据库路径已确定: ${this.dbPath}`)
return this.openDatabase()
}
/**
* 打开数据库
*/
openDatabase() {
return new Promise((resolve, reject) => {
uni.$logger?.local?.info(`[SQLite] 尝试打开数据库: path=${this.dbPath}`)
const isOpen = this.isOpen()
if (isOpen) {
uni.$logger?.local?.info(`[SQLite] 数据库已打开,跳过重复打开`)
resolve(true)
return
}
plus.sqlite.openDatabase({ plus.sqlite.openDatabase({
name: this.name, // 数据库名称 name: this.name,
path: `_doc/${this.name}.db`, // 数据库地址 path: this.dbPath,
success: resolve, // 直接使用 resolve success: (e) => {
fail: reject // 直接使用 reject uni.$logger?.local?.info(`[SQLite] ✅ 数据库打开成功`)
resolve(e)
},
fail: (e) => {
// 处理 -1402 错误 (Same Name Already Open),视为成功
if (e.code === -1402) {
uni.$logger?.local?.warn(`[SQLite] ⚠️ 数据库已打开 (Code -1402), 视为成功: ${this.name}`)
resolve(e)
return
}
uni.$logger?.local?.error(`[SQLite] ❌ 数据库打开失败: ${JSON.stringify(e)}`)
reject(e)
}
}) })
}) })
} }
...@@ -158,7 +194,7 @@ class SQLite { ...@@ -158,7 +194,7 @@ class SQLite {
isOpen() { isOpen() {
let isopen = plus.sqlite.isOpenDatabase({ let isopen = plus.sqlite.isOpenDatabase({
name: this.name, name: this.name,
path: `_doc/${this.name}.db` path: this.dbPath
}) })
return isopen return isopen
} }
......
...@@ -8,6 +8,10 @@ class PathUtils { ...@@ -8,6 +8,10 @@ class PathUtils {
// 默认文件保存路径 (相对于 _doc/) // 默认文件保存路径 (相对于 _doc/)
static DEFAULT_SAVE_PATH = `_doc/${this.SAVE_DIR_NAME}/` static DEFAULT_SAVE_PATH = `_doc/${this.SAVE_DIR_NAME}/`
static CACHED_ROOT_PATH = null
// 本地缓存键名
static ROOT_PATH_CACHE_KEY = 'sqlite_root_path_cache'
/** /**
* 路径拼接工具 * 路径拼接工具
* @param {...string} args 路径片段 * @param {...string} args 路径片段
...@@ -43,16 +47,42 @@ class PathUtils { ...@@ -43,16 +47,42 @@ class PathUtils {
* @returns {Promise<string>} * @returns {Promise<string>}
*/ */
static getFilePath() { static getFilePath() {
return new Promise(resolve => { // 1. 优先使用内存缓存,性能最高
// #ifdef APP-PLUS if (this.CACHED_ROOT_PATH) {
plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) { uni.$logger?.local?.info(`[PathUtils] 命中内存缓存,根路径: ${this.CACHED_ROOT_PATH}`);
resolve(fs.root.fullPath) return Promise.resolve(this.CACHED_ROOT_PATH);
}) }
// #endif
// #ifndef APP-PLUS // 2. 尝试读取持久化缓存
resolve('') const storageCache = uni.getStorageSync(this.ROOT_PATH_CACHE_KEY);
// #endif if (storageCache) {
}) uni.$logger?.local?.info(`[PathUtils] 命中本地缓存,根路径: ${storageCache}`);
// 同步到内存缓存
this.CACHED_ROOT_PATH = storageCache;
return Promise.resolve(this.CACHED_ROOT_PATH);
}
// 3. 无缓存,请求原生文件系统API
return new Promise((resolve, reject) => {
if (!plus) {
reject(new Error('[PathUtils] plus runtime 未初始化'));
return;
}
plus.io.requestFileSystem(
plus.io.PRIVATE_DOC,
(fs) => {
const fullPath = fs.root.fullPath;
uni.$logger?.local?.info(`[PathUtils] 请求原生API获取根路径: ${fullPath}`);
// 写入两级缓存
this.CACHED_ROOT_PATH = fullPath;
uni.setStorageSync(this.ROOT_PATH_CACHE_KEY, fullPath);
resolve(fullPath);
},
(error) => {
reject(new Error(`[PathUtils] 获取文件系统失败: ${JSON.stringify(error)}`));
}
);
});
} }
/** /**
......
...@@ -4,8 +4,8 @@ ...@@ -4,8 +4,8 @@
* @Author: limin * @Author: limin
* @Date: 2024-06-28 17:12:39 * @Date: 2024-06-28 17:12:39
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-03-11 18:07:04 * @LastEditTime: 2026-02-09 18:09:37
* @FilePath: \gl_tape\utils\recordManager\index.js * @FilePath: \simgle_app\utils\recordManager\index.js
*/ */
// import { singleton } from '../utils.js' // import { singleton } from '../utils.js'
import AudioManager from './AudioManager.js' import AudioManager from './AudioManager.js'
...@@ -21,6 +21,7 @@ import TimeoutService from './TimeoutService.js' ...@@ -21,6 +21,7 @@ import TimeoutService from './TimeoutService.js'
import RecordSaveService from './RecordSaveService.js' import RecordSaveService from './RecordSaveService.js'
import UploadService from './UploadService.js' import UploadService from './UploadService.js'
import PathUtils from './PathUtils.js' import PathUtils from './PathUtils.js'
import FileUploadManager from './FileUploadManager.js'
// const SingleDBTempRecord = singleton(TempRecord) // const SingleDBTempRecord = singleton(TempRecord)
export { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory,TimeoutService,RecordSaveService,UploadService,PathUtils } export { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory,TimeoutService,RecordSaveService,UploadService,PathUtils,FileUploadManager }
export default { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory,TimeoutService,RecordSaveService,UploadService,PathUtils } export default { AudioManager, DBRecord, DBManager, RecordDto, TempRecord, helpler, StrategyFactory,TimeoutService,RecordSaveService,UploadService,PathUtils,FileUploadManager }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!