sqlite.js
7.94 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
// import TaskQueue from '../utils/TaskQueue'
// import { PathUtils } from '../utils/recordManager/index'
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 = dbPath || `_doc/${name}.db`
}
_enqueue(task) {
// 使用共享的队列实例
const queueInstance = SQLite._queues[this.name]
return queueInstance.enqueue(task)
}
async init() {
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)
}
})
})
}
selectSql(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]) => {
// 优化:仅当 value 是字符串且以 { 或 [ 开头时才尝试解析
// 避免将普通数字字符串(如 "123")误解析为 Number 导致精度丢失
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
})
})
}
executeSql(sql) {
return new Promise((resolve, reject) => {
uni.$logger.local.warn(`执行SQL语句: ${sql}`)
plus.sqlite.executeSql({
name: this.name,
sql,
success: resolve,
fail: reject
})
})
}
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)
return result[0].isTable ? true : false
} 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() {
return this.closeDatabase()
}
/** 关闭 plus.sqlite 连接(与 openDatabase 配对) */
closeDatabase() {
return new Promise((resolve, reject) => {
if (!this.isOpen()) {
resolve()
return
}
plus.sqlite.closeDatabase({
name: this.name,
success: () => {
uni.$logger?.local?.info(`[SQLite] 数据库已关闭: ${this.name}`)
resolve()
},
fail: err => {
if (err && err.code === -1402) {
resolve()
return
}
reject(err)
}
})
})
}
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);
});*/