Commit 991d9ad6 by liimin

fix(db): 确保数据库操作前初始化并过滤无效字段

- 在 DBBase 的所有数据库操作方法中添加 await this.init() 调用,防止数据库未初始化导致的错误
- 在 SQLite.insert() 方法中增加字段过滤逻辑,只插入表中存在的列,避免插入不存在的字段导致 SQL 错误
- 添加表结构缓存机制,通过 PRAGMA table_info 查询表列信息并缓存,提高插入性能
- 移除 RecordData 类型中已不使用的字段(fileName、filePath、recordId、status)
- 修复 executeSql 错误处理,不再忽略类型转换错误(9010007),改为统一记录错误日志
1 parent 5cddd549
...@@ -42,6 +42,7 @@ export default class DBBase implements IDBBase { ...@@ -42,6 +42,7 @@ export default class DBBase implements IDBBase {
* @returns {Array} - 包含新记录的更新后的记录列表 * @returns {Array} - 包含新记录的更新后的记录列表
*/ */
async addRecord(record: UTSJSONObject): Promise<void> { async addRecord(record: UTSJSONObject): Promise<void> {
await this.init();
await this.db.insert(this.table_name, record); await this.db.insert(this.table_name, record);
} }
...@@ -51,6 +52,7 @@ export default class DBBase implements IDBBase { ...@@ -51,6 +52,7 @@ export default class DBBase implements IDBBase {
* @returns {void} - 此函数不返回任何值 * @returns {void} - 此函数不返回任何值
*/ */
async clearRecords(): Promise<void> { async clearRecords(): Promise<void> {
await this.init();
// delete 需要 where 参数,这里可能是清空表 // delete 需要 where 参数,这里可能是清空表
// sqlite.uts 的 delete 实现:`DELETE FROM ${tabName} WHERE ${whereStr}` // sqlite.uts 的 delete 实现:`DELETE FROM ${tabName} WHERE ${whereStr}`
// 如果 where 为空,SQL 会变成 `DELETE FROM ${tabName} WHERE ` -> 语法错误 // 如果 where 为空,SQL 会变成 `DELETE FROM ${tabName} WHERE ` -> 语法错误
...@@ -93,6 +95,7 @@ export default class DBBase implements IDBBase { ...@@ -93,6 +95,7 @@ export default class DBBase implements IDBBase {
* *
*/ */
async getRecordById(id: any): Promise<null | UTSJSONObject> { async getRecordById(id: any): Promise<null | UTSJSONObject> {
await this.init();
const where = { id }; const where = { id };
const records = await this.db.select(this.table_name, where, null); const records = await this.db.select(this.table_name, where, null);
// records 是 any[],需要断言 // records 是 any[],需要断言
...@@ -108,6 +111,7 @@ export default class DBBase implements IDBBase { ...@@ -108,6 +111,7 @@ export default class DBBase implements IDBBase {
* @returns {Array} - 从 storageApi 获取的记录列表 * @returns {Array} - 从 storageApi 获取的记录列表
*/ */
async getRecords(): Promise<any[]> { async getRecords(): Promise<any[]> {
await this.init();
return this.db.select(this.table_name, null, null); return this.db.select(this.table_name, null, null);
} }
...@@ -117,6 +121,7 @@ export default class DBBase implements IDBBase { ...@@ -117,6 +121,7 @@ export default class DBBase implements IDBBase {
* @returns {Array} - 记录列表 * @returns {Array} - 记录列表
*/ */
async getRecordsByWhere(where: UTSJSONObject): Promise<any[]> { async getRecordsByWhere(where: UTSJSONObject): Promise<any[]> {
await this.init();
return this.db.select(this.table_name, where, null); return this.db.select(this.table_name, where, null);
} }
...@@ -158,6 +163,7 @@ export default class DBBase implements IDBBase { ...@@ -158,6 +163,7 @@ export default class DBBase implements IDBBase {
* @returns {Array} - 移除记录后的更新后的记录列表 * @returns {Array} - 移除记录后的更新后的记录列表
*/ */
async removeRecord(id: any): Promise<any> { async removeRecord(id: any): Promise<any> {
await this.init();
const where = { id }; const where = { id };
return this.db.delete(this.table_name, where); return this.db.delete(this.table_name, where);
} }
...@@ -189,6 +195,7 @@ export default class DBBase implements IDBBase { ...@@ -189,6 +195,7 @@ export default class DBBase implements IDBBase {
* @throws {Error} 如果记录数组中找不到具有给定 id 的记录,将抛出错误 * @throws {Error} 如果记录数组中找不到具有给定 id 的记录,将抛出错误
*/ */
async updateRecord(setData: UTSJSONObject, where: null | UTSJSONObject): Promise<any> { async updateRecord(setData: UTSJSONObject, where: null | UTSJSONObject): Promise<any> {
await this.init();
// const { id, ...record } = setData // UTS 不支持解构剩余参数 // const { id, ...record } = setData // UTS 不支持解构剩余参数
// 如果没有 where,尝试从 setData 中提取 id // 如果没有 where,尝试从 setData 中提取 id
......
...@@ -16,6 +16,7 @@ import { logger } from "../logger/index.uts"; ...@@ -16,6 +16,7 @@ import { logger } from "../logger/index.uts";
export default class SQLite { export default class SQLite {
static _queues = new Map<string, TaskQueue>(); static _queues = new Map<string, TaskQueue>();
static _tableColumnsCache = new Map<string, string[]>();
db: any | null = null; db: any | null = null;
dbPath: null | string = null; dbPath: null | string = null;
...@@ -41,6 +42,7 @@ export default class SQLite { ...@@ -41,6 +42,7 @@ export default class SQLite {
*/ */
async addColumns(tableName: string, columns: UTSJSONObject[]): Promise<void> { async addColumns(tableName: string, columns: UTSJSONObject[]): Promise<void> {
try { try {
this.clearTableColumnsCache(tableName);
const colArr = columns; // 避免在 for 循环中直接迭代参数导致类型问题(虽然应该没问题) const colArr = columns; // 避免在 for 循环中直接迭代参数导致类型问题(虽然应该没问题)
for (const column of colArr) { for (const column of colArr) {
const name = column.name; const name = column.name;
...@@ -57,6 +59,7 @@ export default class SQLite { ...@@ -57,6 +59,7 @@ export default class SQLite {
} }
} }
} }
this.clearTableColumnsCache(tableName);
} catch (error) { } catch (error) {
logger.error(`添加字段失败 error - > ${error}`); logger.error(`添加字段失败 error - > ${error}`);
throw new Error(`Add columns failed: ${error}`); throw new Error(`Add columns failed: ${error}`);
...@@ -92,6 +95,7 @@ export default class SQLite { ...@@ -92,6 +95,7 @@ export default class SQLite {
// 创建新表示例 // 创建新表示例
createTable(tableName: string, columns: string[]): Promise<any | null> { createTable(tableName: string, columns: string[]): Promise<any | null> {
this.clearTableColumnsCache(tableName);
const sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(", ")})`; const sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(", ")})`;
return this.executeSql(sql); return this.executeSql(sql);
} }
...@@ -125,11 +129,8 @@ export default class SQLite { ...@@ -125,11 +129,8 @@ export default class SQLite {
resolve(res); resolve(res);
}, },
fail: (err: SqliteFail) => { fail: (err: SqliteFail) => {
// Ignore cast error for executeSql too if it happens console.error(`[SQLite] executeSql 执行失败: ${err}`);
if (err.errCode == 9_010_007) { if (err.errCode == 9_010_007) {
logger.warn(`[SQLite] executeSql encountered cast error (9010007), assuming success. SQL: ${sql}`);
// 9010007 means boolean returned (likely true), so we return something non-null to avoid NPE in TaskQueue or subsequent calls
// Returning a dummy object is safer than null if caller expects object
resolve({ result: "success_with_cast_warning" }); resolve({ result: "success_with_cast_warning" });
} else { } else {
reject(err); reject(err);
...@@ -168,15 +169,22 @@ export default class SQLite { ...@@ -168,15 +169,22 @@ export default class SQLite {
} }
// 插入示例 // 插入示例
insert(tabName: string, keyValues: UTSJSONObject): Promise<any | null> { async insert(tabName: string, keyValues: UTSJSONObject): Promise<any | null> {
const map = keyValues.toMap(); const map = keyValues.toMap();
const valStr: UTSArray<string> = []; const valStr: UTSArray<string> = [];
const keyList: UTSArray<string> = []; const keyList: UTSArray<string> = [];
const tableColumns = await this.getTableColumns(tabName);
const shouldFilter = tableColumns.length > 0;
map.forEach((value, key) => { map.forEach((value, key) => {
if (!shouldFilter || tableColumns.includes(key)) {
keyList.push(key); keyList.push(key);
valStr.push(`${this.formatValue(value)}`); valStr.push(`${this.formatValue(value)}`);
}
}); });
if (keyList.length === 0) {
throw new Error(`Insert into ${tabName} has no valid columns`);
}
const keyStr = keyList.join(", "); const keyStr = keyList.join(", ");
const sql = `INSERT INTO ${tabName} (${keyStr}) VALUES (${valStr.join(", ")})`; const sql = `INSERT INTO ${tabName} (${keyStr}) VALUES (${valStr.join(", ")})`;
return this.executeSql(sql); return this.executeSql(sql);
...@@ -416,6 +424,10 @@ export default class SQLite { ...@@ -416,6 +424,10 @@ export default class SQLite {
return this.executeSql(sql); return this.executeSql(sql);
} }
private clearTableColumnsCache(tableName: string) {
SQLite._tableColumnsCache.delete(this.getTableCacheKey(tableName));
}
private enqueue(task: () => Promise<any>): Promise<any | null> { private enqueue(task: () => Promise<any>): Promise<any | null> {
const queue = SQLite._queues.get(this.name); const queue = SQLite._queues.get(this.name);
if (queue != null) { if (queue != null) {
...@@ -423,4 +435,29 @@ export default class SQLite { ...@@ -423,4 +435,29 @@ export default class SQLite {
} }
return Promise.reject(new Error(`Queue for ${this.name} not found`)) as Promise<any | null>; return Promise.reject(new Error(`Queue for ${this.name} not found`)) as Promise<any | null>;
} }
private getTableCacheKey(tableName: string): string {
return `${this.name}:${tableName}`;
}
private async getTableColumns(tableName: string): Promise<string[]> {
const cacheKey = this.getTableCacheKey(tableName);
const cached = SQLite._tableColumnsCache.get(cacheKey);
if (cached != null && cached.length > 0) {
return cached;
}
const columnInfo = await this.selectSql(`PRAGMA table_info(${tableName})`);
const columns: string[] = [];
columnInfo.forEach((row: any) => {
const rowObj = row as UTSJSONObject;
const name = rowObj.name;
if (typeof name === "string" && name != "") {
columns.push(name);
}
});
if (columns.length > 0) {
SQLite._tableColumnsCache.set(cacheKey, columns);
}
return columns;
}
} }
...@@ -6,7 +6,7 @@ import type { IDBRecord, RecordData } from "./types"; ...@@ -6,7 +6,7 @@ import type { IDBRecord, RecordData } from "./types";
* @Author: limin * @Author: limin
* @Date: 2025-01-02 18:34:39 * @Date: 2025-01-02 18:34:39
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2026-03-13 19:52:30 * @LastEditTime: 2026-03-13 21:15:11
* @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\DBRecord.uts * @FilePath: \venus\apps\uniappX\uniapp-x-tape\services\recorder\DBRecord.uts
*/ */
import DBBase from "../db/DBBase.uts"; import DBBase from "../db/DBBase.uts";
......
...@@ -9,8 +9,6 @@ export type RecordData = { ...@@ -9,8 +9,6 @@ export type RecordData = {
channelType?: null | number channelType?: null | number
customerName?: null | string customerName?: null | string
endReasonType?: null | number endReasonType?: null | number
fileName?: null | string
filePath?: null | string
id: string id: string
loginPhone?: null | string loginPhone?: null | string
merchantId?: null | number merchantId?: null | number
...@@ -23,7 +21,6 @@ export type RecordData = { ...@@ -23,7 +21,6 @@ export type RecordData = {
receptionEndTime?: null | string receptionEndTime?: null | string
receptionStartTime?: null | string receptionStartTime?: null | string
receptionStatus?: null | number receptionStatus?: null | number
recordId?: null | string
recordStatus?: null | number // 0: recording, 1: completed recordStatus?: null | number // 0: recording, 1: completed
recordUrlList?: null | RecordFile[] recordUrlList?: null | RecordFile[]
salesName?: null | string salesName?: null | string
...@@ -31,8 +28,6 @@ export type RecordData = { ...@@ -31,8 +28,6 @@ export type RecordData = {
serviceMerchantId?: null | number serviceMerchantId?: null | number
staffName?: null | string staffName?: null | string
staffUuid?: null | string staffUuid?: null | string
// Upload task fields
status?: number | null
} }
export type FileInfo = { export type FileInfo = {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!