sqlite.js
9.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import TaskQueue from '../utils/TaskQueue'
class SQLite {
static _queues = {} // 静态队列字典,key为数据库名,value为 TaskQueue 实例
constructor(name, version, description, size, dbPath) {
this.name = name
this.version = version || '1.0'
this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null
this.dbPath = `_doc/${name}.db` // 存储数据库的完整路径
// 初始化该数据库的队列(如果不存在)
if (!SQLite._queues[name]) {
SQLite._queues[name] = new TaskQueue(`SQLite:${name}`)
}
}
_enqueue(task) {
// 使用共享的队列实例
const queueInstance = SQLite._queues[this.name]
return queueInstance.enqueue(task)
}
async init() {
// 如果已经有路径,直接使用
// 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({
name: this.name,
path: this.dbPath,
success: (e) => {
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)
}
})
})
}
_shouldRetryDbError(error) {
const text = typeof error === 'string' ? error : error?.message || JSON.stringify(error || {})
return /disk I\/O error|readonly database|Cannot create file private directory|not open/i.test(text)
}
closeDatabase() {
return new Promise((resolve) => {
try {
if (!this.isOpen()) {
resolve(true)
return
}
plus.sqlite.closeDatabase({
name: this.name,
path: this.dbPath,
success: () => resolve(true),
fail: () => resolve(true)
})
} catch (e) {
resolve(true)
}
})
}
async reopenDatabase() {
await this.closeDatabase()
await this.openDatabase()
}
_selectSqlOnce(sql) {
return new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.selectSql({
name: this.name,
sql,
success: result => {
const processedRows = result.map(row =>
Object.fromEntries(
Object.entries(row).map(([key, value]) => {
if (typeof value === 'string' && (value.startsWith('{') || value.startsWith('['))) {
try {
return [key, JSON.parse(value)]
} catch {
return [key, value]
}
}
return [key, value]
})
)
)
resolve(processedRows)
},
fail: reject
})
})
}
_executeSqlOnce(sql) {
return new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.executeSql({
name: this.name,
sql,
success: resolve,
fail: reject
})
})
}
selectSql(sql) {
return this._enqueue(async () => {
try {
return await this._selectSqlOnce(sql)
} catch (error) {
if (!this._shouldRetryDbError(error)) throw error
uni.$logger?.local?.warn?.(`[SQLite] select retry once due to db error: ${error?.message || error}`)
await this.reopenDatabase()
return this._selectSqlOnce(sql)
}
})
}
executeSql(sql) {
return this._enqueue(async () => {
try {
return await this._executeSqlOnce(sql)
} catch (error) {
if (!this._shouldRetryDbError(error)) throw error
uni.$logger?.local?.warn?.(`[SQLite] execute retry once due to db error: ${error?.message || error}`)
await this.reopenDatabase()
return this._executeSqlOnce(sql)
}
})
}
async isTableExists(tableName) {
const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'`
try {
const result = await this.selectSql(sql)
if (!Array.isArray(result) || result.length === 0) {
uni.$logger?.local?.warn?.(`[SQLite] isTableExists empty result, treat as not exists: ${tableName}`)
return false
}
const first = result[0] || {}
const count = Number(first.isTable)
return Number.isFinite(count) ? count > 0 : !!first.isTable
} catch (error) {
console.error('检查表是否存在出错: ', error)
throw error
}
}
// 创建新表示例
createTable(tableName, columns) {
const sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(', ')})`
return this.executeSql(sql)
}
// 查询示例
select(tabName, where, order) {
let sql = `SELECT * FROM ${tabName}`
if (where) {
const dataKeys = Object.keys(where)
const conditions = dataKeys.map(key => `${key}=${JSON.stringify(where[key])}`).join(' AND ')
sql += ` WHERE ${conditions}`
}
if (order) {
const orderKey = Object.keys(order)[0] // 获取排序字段
const orderType = order[orderKey] // 获取排序类型
sql += ` ORDER BY ${orderKey} ${orderType}`
}
return this.selectSql(sql)
}
// 插入示例
insert(tabName, keyValues) {
const keys = Object.keys(keyValues)
const keyStr = keys.join(', ')
const valStr = keys
.map(key => {
const value = keyValues[key]
// 使用公共方法进行格式化
return `${this.formatValue(value)}`
})
.join(', ')
const sql = `INSERT INTO ${tabName} (${keyStr}) VALUES (${valStr})`
return this.executeSql(sql)
}
// 更新示例
update(tabName, setData, where) {
const dataKeys = Object.keys(setData)
const setStr = dataKeys
.map(key => {
const value = setData[key]
return `${key} = ${this.formatValue(value)}`
})
.join(', ')
const whereKeys = Object.keys(where)
const whereStr = whereKeys
.map(key => {
const value = where[key]
return `${key} = ${this.formatValue(value)}`
})
.join(' AND ')
const sql = `UPDATE ${tabName} SET ${setStr} WHERE ${whereStr}`
return this.executeSql(sql)
}
// 删除示例
delete(tabName, where) {
const whereKeys = Object.keys(where)
const whereStr = whereKeys
.map(key => {
const value = where[key]
return `${key} = ${this.formatValue(value)}`
})
.join(' AND ')
const sql = `DELETE FROM ${tabName} WHERE ${whereStr}`
return this.executeSql(sql)
}
isOpen() {
let isopen = plus.sqlite.isOpenDatabase({
name: this.name,
path: this.dbPath
})
return isopen
}
close() {
if (this.db) {
this.db.close()
this.db = null
console.log('数据库连接已关闭')
}
}
drop(tabName) {
const sql = `DROP TABLE IF EXISTS ${tabName}`
return this.executeSql(sql)
}
formatValue(value) {
let strVal = ''
if (typeof value === 'object' && value !== null) {
strVal = JSON.stringify(value)
} else {
strVal = String(value)
}
// SQL 中转义单引号的方法是将 ' 替换为 ''
return `'${strVal.replace(/'/g, "''")}'`
}
/**
* 检查指定字段是否存在于表中
* @param {string} tableName - 表名
* @param {string} columnName - 要检查的字段名
* @returns {Promise<boolean>} - 字段存在返回true,否则返回false
*/
async isColumnExists(tableName, columnName) {
try {
const columnInfo = await this.selectSql(`PRAGMA table_info(${tableName})`)
return columnInfo.some(col => col.name === columnName)
} catch (error) {
console.error(`检查字段是否存在失败 error - > ${error.message}`)
throw new Error(error.message)
}
}
/**
* 批量添加字段到表中
* @param {string} tableName - 表名
* @param {Array<{name: string, definition: string}>} columns - 要添加的字段数组
* @returns {Promise<void>}
*/
async addColumns(tableName, columns) {
try {
for (const column of columns) {
const { name, definition = 'TEXT DEFAULT ""' } = column
await this.executeSql(`ALTER TABLE ${tableName} ADD COLUMN ${name} ${definition}`)
}
} catch (error) {
console.error(`批量添加列失败 error - > ${error.message}`)
throw new Error(error.message)
}
}
}
export default SQLite
// 使用示例
/* const db = new SQLite('mydb', '1.0', 'Test DB', 1 * 1024 * 1024);
db.init().then(() => {
// 进行数据库操作
}).catch(error => {
console.error('数据库初始化失败: ', error);
});*/