mm_sqlite 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,8 @@
1
1
  # mm_sqlite
2
+ [中文](./README.md) | [English](./README_EN.md)
2
3
 
3
4
  高性能SQLite数据库操作模块,提供与mm_mysql完全兼容的API接口。适用于Node.js应用的轻量级数据存储解决方案。
4
5
 
5
- [![npm version](https://img.shields.io/npm/v/mm_sqlite.svg?style=flat-square)](https://www.npmjs.com/package/mm_sqlite)
6
- [![npm downloads](https://img.shields.io/npm/dm/mm_sqlite.svg?style=flat-square)](https://www.npmjs.com/package/mm_sqlite)
7
- [![node version](https://img.shields.io/node/v/mm_sqlite.svg?style=flat-square)](https://nodejs.org/en/)
8
- [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE)
9
-
10
6
  ## 安装
11
7
 
12
8
  ```bash
@@ -16,12 +12,13 @@ npm install mm_sqlite --save
16
12
  ## 特性
17
13
 
18
14
  - 🚀 **高性能优化**:经过深度优化的SQL构建器和连接管理
19
- - 🔄 **完全兼容**:与mm_mysql模块API完全兼容
15
+ - 🔄 **完全兼容**:与mm_mysql模块API完全兼容,可无缝切换
20
16
  - 📊 **内存优化**:优化的内存使用,减少GC压力
21
17
  - 🔧 **链式调用**:流畅的SQL构建器链式调用
22
18
  - 🛡️ **错误处理**:完善的错误处理机制
23
19
  - 📈 **连接池支持**:支持连接池模式,提高并发性能
24
20
  - 🔒 **事务支持**:完整的事务处理机制
21
+ - 🔍 **类型安全**:完善的JSDoc类型注释
25
22
 
26
23
  ## 依赖要求
27
24
 
@@ -32,7 +29,7 @@ npm install mm_sqlite --save
32
29
 
33
30
  ### 基本使用
34
31
 
35
- ### 初始化和连接
32
+ #### 初始化和连接
36
33
 
37
34
  ```javascript
38
35
  const { Sqlite } = require('mm_sqlite');
@@ -62,369 +59,136 @@ const sqlite = new Sqlite({
62
59
 
63
60
  // 打开数据库连接
64
61
  await sqlite.open();
65
-
66
- // 注意:SQLite会自动创建不存在的数据库文件和目录
67
62
  ```
68
63
 
69
- ### 表操作
64
+ #### 基础操作
70
65
 
71
66
  ```javascript
72
- // 创建表
73
- await sqlite.exec(`
74
- CREATE TABLE IF NOT EXISTS users (
75
- id INTEGER PRIMARY KEY AUTOINCREMENT,
76
- username TEXT NOT NULL,
77
- email TEXT UNIQUE,
78
- age INTEGER,
79
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
80
- );
81
- `);
82
-
83
- // 删除表
84
- await sqlite.exec('DROP TABLE IF EXISTS users');
85
- ```
67
+ // 获取数据库管理器
68
+ const db = sqlite.db();
86
69
 
87
- ### 数据操作
70
+ // 设置表名
71
+ const userDb = db.new('users', 'id');
88
72
 
89
- ```javascript
90
- // 插入单条数据
91
- const insertResult = await sqlite.table('users').add({
73
+ // 插入数据
74
+ const result = await userDb.add({
92
75
  username: '张三',
93
76
  email: 'zhangsan@example.com',
94
- age: 28
77
+ age: 28,
78
+ created_at: new Date()
95
79
  });
96
- console.log('插入结果:', insertResult);
97
-
98
- // 查询多条数据
99
- const users = await sqlite.table('users').get();
100
- console.log('所有用户:', users);
101
80
 
102
- // 根据条件查询
103
- const user = await sqlite.table('users').getObj({ username: '张三' });
104
- console.log('查询用户:', user);
105
-
106
- // 使用SQL构建器
107
- const activeUsers = await sqlite
108
- .table('users')
109
- .select(['id', 'username', 'email'])
110
- .where({ age: { '>=': 18 } })
111
- .orderBy('created_at', 'DESC')
112
- .limit(10)
113
- .get();
81
+ // 查询数据
82
+ const users = await userDb.get();
114
83
 
115
84
  // 更新数据
116
- const updateResult = await sqlite.table('users').set(
117
- { id: 1 }, // 更新条件
118
- { age: 29, email: 'newname@example.com' } // 更新数据
119
- );
120
- console.log('更新结果:', updateResult);
85
+ await userDb.set({ id: 1 }, { age: 29 });
121
86
 
122
87
  // 删除数据
123
- const deleteResult = await sqlite.table('users').del({ id: 1 });
124
- console.log('删除结果:', deleteResult);
88
+ await userDb.del({ id: 1 });
125
89
  ```
126
90
 
127
- ### 批量操作
91
+ #### 高级查询
128
92
 
129
93
  ```javascript
130
- // 批量插入数据
131
- const batchInsertResult = await sqlite.table('users').addList([
132
- { username: '李四', email: 'lisi@example.com', age: 30 },
133
- { username: '王五', email: 'wangwu@example.com', age: 25 },
134
- { username: '赵六', email: 'zhaoliu@example.com', age: 32 }
135
- ], true, 100, 60000); // lock=true, batchSize=100, timeout=60000
136
- console.log('批量插入结果:', batchInsertResult);
137
-
138
- // 批量删除数据
139
- const batchDeleteResult = await sqlite.table('users').delList([
140
- { id: 2 },
141
- { id: 3 }
142
- ], false, 100, 60000); // like=false, batchSize=100, timeout=60000
143
- console.log('批量删除结果:', batchDeleteResult);
144
- ```
145
-
146
- ### 统计操作
147
-
148
- ```javascript
149
- // 统计总记录数
150
- const totalCount = await sqlite.table('users').count();
151
- console.log('总记录数:', totalCount);
152
-
153
- // 条件统计
154
- const adultCount = await sqlite.table('users').count({ age: { '>=': 18 } });
155
- console.log('成年人数量:', adultCount);
156
-
157
- // 分组统计
158
- const ageGroupCount = await sqlite.table('users').groupCount(
159
- {}, // 查询条件
160
- 'age', // 分组字段
161
- 'age, COUNT(*) as count', // 查询字段
162
- 'age DESC' // 排序规则
163
- );
164
- console.log('年龄分组统计:', ageGroupCount);
165
-
166
- // 关闭连接
167
- await sqlite.close();
168
- ```
169
-
170
- ### 高级功能
171
-
172
- #### 事务处理
173
-
174
- ```javascript
175
- // 开始事务
176
- const transaction = await sqlite.beginTransaction();
177
-
178
- try {
179
- // 在事务中执行操作
180
- await transaction.exec('INSERT INTO users (username, email) VALUES (?, ?)', ['张三', 'zhangsan@example.com']);
181
- await transaction.exec('INSERT INTO profiles (user_id, bio) VALUES (?, ?)', [1, '这是一个测试用户']);
182
-
183
- // 提交事务
184
- await transaction.commit();
185
- } catch (error) {
186
- // 回滚事务
187
- await transaction.rollback();
188
- console.error('事务执行失败:', error);
189
- }
190
- ```
191
-
192
- #### 使用事务包装器
193
-
194
- ```javascript
195
- // 使用事务包装器简化事务处理
196
- const result = await sqlite.transaction(async (transaction) => {
197
- // 在事务中执行操作
198
- await transaction.exec('INSERT INTO users (username, email) VALUES (?, ?)', ['李四', 'lisi@example.com']);
199
- await transaction.exec('INSERT INTO profiles (user_id, bio) VALUES (?, ?)', [2, '这是另一个测试用户']);
200
-
201
- return { success: true };
94
+ // 条件查询
95
+ const adultUsers = await userDb.get({
96
+ age: { _gte: 18 }
202
97
  });
203
98
 
204
- console.log('事务执行结果:', result);
205
- ```
99
+ // 分页查询
100
+ const pageUsers = await userDb.get({
101
+ _page: 1,
102
+ _size: 10,
103
+ _sort: 'created_at desc'
104
+ });
206
105
 
207
- #### 复杂查询
208
- // 多表连接查询
209
- const results = await sqlite
210
- .table('users')
211
- .select(['users.name', 'profiles.bio', 'posts.title'])
212
- .join('profiles', 'users.id = profiles.user_id')
213
- .join('posts', 'users.id = posts.author_id')
214
- .where({ 'users.status': 'active' })
215
- .like('posts.title', '教程')
216
- .groupBy('users.id')
217
- .having('COUNT(posts.id) > 0')
218
- .get();
219
-
220
- // IN查询
221
- const ids = [1, 2, 3, 4, 5];
222
- const users = await sqlite
223
- .table('users')
224
- .where('id', 'IN', ids)
225
- .get();
226
-
227
- // OR条件查询
228
- const users = await sqlite
229
- .table('users')
230
- .where({ status: 'active' })
231
- .orWhere({ role: 'admin' })
232
- .get();
106
+ // 聚合查询
107
+ const stats = await userDb.aggr({
108
+ _count: 'id',
109
+ _avg: 'age',
110
+ _max: 'age',
111
+ _min: 'age'
112
+ });
233
113
  ```
234
114
 
235
- ## 性能优化特性
236
-
237
- ### 内存优化
238
-
239
- - **DB实例缓存**:数据库实例缓存机制,避免重复创建
240
- - **SQL构建器优化**:优化的字符串拼接和参数处理
241
- - **连接管理**:智能连接池和重连机制
242
-
243
- ### 性能测试结果
244
-
245
- 经过优化后,模块性能显著提升:
246
-
247
- - **SQL构建器操作**:1,250,000+ 操作/秒
248
- - **内存使用**:平均每次迭代减少27.36字节
249
- - **连接管理**:连接实例创建内存使用减少2.1MB
250
-
251
115
  ## API参考
252
116
 
253
117
  ### Sqlite类
254
118
 
255
119
  #### 构造函数
256
-
257
120
  ```javascript
258
121
  new Sqlite(config)
259
122
  ```
260
123
 
261
- **配置参数:**
262
- - `config.dir` - 数据库文件存储目录,默认为`'./db/'`
263
- - `config.database` - 数据库文件名,默认为`'mm'`
264
- - `config.charset` - 字符集,默认为`'utf8mb4'`
265
- - `config.timezone` - 时区,默认为`'+08:00'`
266
- - `config.connect_timeout` - 连接超时时间,默认`20000ms`
267
- - `config.acquire_timeout` - 获取连接超时时间,默认`20000ms`
268
- - `config.query_timeout` - 查询超时时间,默认`20000ms`
269
- - `config.connection_limit` - 连接限制(>1启用连接池),默认`1`
270
- - `config.enable_keep_alive` - 启用保活,默认`true`
271
- - `config.keep_alive_initial_delay` - 保活初始延迟,默认`10000ms`
272
- - `config.enable_reconnect` - 启用重连,默认`true`
273
- - `config.reconnect_interval` - 重连间隔,默认`1000ms`
274
- - `config.max_reconnect_attempts` - 最大重连尝试次数,默认`5`
275
- - `config.wait_for_connections` - 等待连接,默认`true`
276
- - `config.pool_min` - 连接池最小连接数,默认`1`
277
- - `config.pool_max` - 连接池最大连接数,默认`5`
278
- - `config.pool_acquire_timeout` - 连接池获取超时,默认`30000ms`
279
- - `config.pool_idle_timeout` - 连接池空闲超时,默认`60000ms`
280
- - `config.pool_reap_interval` - 连接池清理间隔,默认`1000ms`
281
-
282
124
  #### 主要方法
283
125
 
284
- - `open(timeout)` - 打开数据库连接,返回`Promise<Boolean>`
285
- - `close()` - 关闭数据库连接,返回`Promise<Boolean>`
286
- - `getConn(timeout)` - 获取数据库连接,返回`Promise<Connection>`
287
- - `run(sql, params, timeout)` - 执行SQL查询语句,返回`Promise<Array>`
288
- - `exec(sql, params, timeout)` - 执行SQL语句(非查询操作),返回`Promise<Object>`
289
- - `read(table, condition, options)` - 读取整张表的数据,返回`Promise<Array>`
290
- - `db(database)` - 获取数据库操作实例,返回`DB`实例
291
- - `beginTransaction()` - 开始事务,返回`Promise<Object>`(事务对象)
292
- - `transaction(callback)` - 在事务中执行多个操作,返回`Promise<*>`
293
-
294
- #### 事务对象方法
295
-
296
- - `commit()` - 提交事务
297
- - `rollback()` - 回滚事务
298
- - `exec(sql, params)` - 在事务中执行SQL语句
126
+ - `open()` - 打开数据库连接
127
+ - `close()` - 关闭数据库连接
128
+ - `db()` - 获取数据库管理器实例
129
+ - `run(sql, params)` - 执行查询SQL
130
+ - `exec(sql, params)` - 执行非查询SQL
299
131
 
300
132
  ### DB类
301
133
 
302
- DB类继承自Sql类,提供SQL构建器功能。
303
-
304
- #### 主要方法
305
-
306
- - `table(tableName)` - 设置表名,返回当前实例
307
- - `add(body)` - 添加单条数据,返回`Promise<Object>`
308
- - `del(query, like)` - 删除数据,返回`Promise<Object>`
309
- - `set(query, body, like)` - 更新数据,返回`Promise<Object>`
310
- - `get(query, sort, view, like, timeout)` - 查询多条数据,返回`Promise<Array>`
311
- - `getObj(query, sort, view, like, timeout)` - 获取单条记录,返回`Promise<Object|null>`
312
- - `addList(list, lock, batchSize, timeout)` - 批量添加数据,返回`Promise<Object>`
313
- - `delList(list, like, batchSize, timeout)` - 批量删除数据,返回`Promise<Object>`
314
- - `count(query, like, timeout)` - 统计记录数,返回`Promise<Number>`
315
- - `groupCount(query, groupby, view, sort)` - 分组统计,返回`Promise<Array>`
316
- - `groupSum(query, groupby, view, sort)` - 分组求和,返回`Promise<Array>`
317
- - `groupAvg(query, groupby, view, sort)` - 分组平均值,返回`Promise<Array>`
318
-
319
- #### SQL构建器方法
320
-
321
- - `select(fields)` - 设置查询字段
322
- - `where(condition)` - 设置查询条件
323
- - `orWhere(condition)` - 设置OR查询条件
324
- - `like(field, value)` - 设置LIKE查询条件
325
- - `orderBy(field, direction)` - 设置排序
326
- - `groupBy(field)` - 设置分组
327
- - `having(condition)` - 设置HAVING条件
328
- - `limit(count)` - 设置限制数量
329
- - `offset(count)` - 设置偏移量
330
- - `join(table, condition)` - 设置表连接
331
-
332
- ## 错误处理
333
-
334
- 模块提供完善的错误处理机制:
335
-
336
- 1. **参数验证**:所有公开方法都会验证输入参数,参数不符合要求时会抛出`TypeError`
337
- 2. **SQL错误捕获**:SQL执行错误会被捕获并记录到日志中
338
- 3. **连接错误处理**:连接失败时会自动重连,超过最大重试次数后抛出错误
339
- 4. **事务错误处理**:事务执行失败时会自动回滚,确保数据一致性
340
-
341
- 错误处理示例:
342
-
343
- ```javascript
344
- // 参数验证错误
345
- try {
346
- await db.add(null); // 抛出TypeError
347
- } catch (err) {
348
- console.error('参数错误:', err.message);
349
- }
350
-
351
- // SQL执行错误
352
- try {
353
- await db.exec('SELECT * FROM non_existent_table');
354
- } catch (err) {
355
- console.error('SQL错误:', err.message);
356
- }
357
-
358
- // 事务错误处理
359
- try {
360
- await sqlite.transaction(async (tx) => {
361
- await tx.exec('INSERT INTO users (name) VALUES (?)', ['Alice']);
362
- await tx.exec('INSERT INTO users (name) VALUES (?)', [null]); // 触发错误
363
- });
364
- } catch (err) {
365
- console.error('事务执行失败:', err.message);
366
- }
367
- ```
368
-
369
- ## 性能监控
370
-
371
- 模块内置连接池和性能优化功能:
372
-
373
- 1. **连接池管理**:自动管理数据库连接,提高并发性能
374
- 2. **连接复用**:连接使用完毕后自动归还到连接池
375
- 3. **连接保活**:定期检查连接状态,自动重连失效连接
376
- 4. **超时控制**:支持连接超时、查询超时等配置
377
-
378
- 连接池配置示例:
379
-
380
- ```javascript
381
- const sqlite = new Sqlite({
382
- connection_limit: 5, // 启用连接池,最大5个连接
383
- pool_min: 1, // 最小连接数
384
- pool_max: 5, // 最大连接数
385
- pool_idle_timeout: 60000, // 空闲超时60秒
386
- enable_keep_alive: true, // 启用保活
387
- enable_reconnect: true // 启用自动重连
388
- });
389
- ```
390
-
391
- 对于大规模应用,建议在生产环境前进行压力测试,确保数据库操作满足性能要求。
392
-
393
- ## 兼容性
394
-
395
- - **Node.js版本**:支持 Node.js 12.0 及以上版本
396
- - **SQLite版本**:支持 SQLite 3.0 及以上版本
397
- - **操作系统**:支持 Windows、Linux、macOS
398
-
399
- ## FAQ
400
-
401
- ### Q: 如何处理数据库文件不存在的情况?
402
- A: 模块会自动创建数据库文件,无需手动创建。
403
-
404
- ### Q: 如何优化查询性能?
405
- A: 建议使用索引、合理设计表结构、避免全表扫描。
406
-
407
- ### Q: 如何处理并发访问?
408
- A: 模块内置连接池机制,支持并发访问。当连接数超过1时自动启用连接池。
409
-
410
- ### Q: 如何备份数据库?
411
- A: 可以直接复制数据库文件进行备份。
412
-
413
- ### Q: 如何查看SQL执行日志?
414
- A: 启用调试模式即可查看详细的SQL执行日志。
415
-
416
- ### Q: 连接池如何工作?
417
- A: 当`connection_limit`大于1时启用连接池,连接池会自动管理连接的获取和释放。
418
-
419
- ### Q: 事务处理是否安全?
420
- A: 是的,事务处理包含完整的错误处理机制,失败时会自动回滚。
421
-
422
- ### Q: 支持哪些SQL操作?
423
- A: 支持标准的CRUD操作、复杂查询、事务处理、批量操作等。
424
-
425
- ## 贡献
426
-
427
- 欢迎提交 Issue 和 Pull Request 来改进这个模块。
134
+ #### 表操作
135
+ - `addTable(table, field, type, auto, commit, timeout)` - 创建表
136
+ - `dropTable(table, timeout)` - 删除表
137
+ - `renameTable(table, new_table, timeout)` - 重命名表
138
+ - `emptyTable(table, timeout)` - 清空表
139
+ - `hasTable(table, timeout)` - 检查表是否存在
140
+
141
+ #### 字段操作
142
+ - `addField(field, type, value, not_null, auto, comment, timeout)` - 添加字段
143
+ - `delField(table, field, timeout)` - 删除字段
144
+ - `renameField(table, field, new_field, type, timeout)` - 重命名字段
145
+ - `editField(table, field, type, timeout)` - 修改字段
146
+ - `fields(table, field_name, timeout)` - 获取字段信息
147
+
148
+ #### 数据操作
149
+ - `add(data, timeout)` - 插入数据
150
+ - `set(where, data, timeout)` - 更新数据
151
+ - `del(where, timeout)` - 删除数据
152
+ - `get(where, timeout)` - 查询数据
153
+ - `getTableData(table, batchSize, timeout)` - 获取表数据
154
+
155
+ #### 事务操作
156
+ - `start()` - 开始事务
157
+ - `commit(transaction)` - 提交事务
158
+ - `back(transaction)` - 回滚事务
159
+ - `transaction(callback)` - 事务中执行操作
160
+
161
+ ## 配置参数
162
+
163
+ | 参数 | 类型 | 默认值 | 描述 |
164
+ |------|------|--------|------|
165
+ | dir | string | './db/' | 数据库文件存储目录 |
166
+ | database | string | 'mm' | 数据库文件名 |
167
+ | charset | string | 'utf8mb4' | 字符集 |
168
+ | timezone | string | '+08:00' | 时区 |
169
+ | connect_timeout | number | 20000 | 连接超时时间(ms) |
170
+ | acquire_timeout | number | 20000 | 获取连接超时时间(ms) |
171
+ | query_timeout | number | 20000 | 查询超时时间(ms) |
172
+ | connection_limit | number | 1 | 连接限制 |
173
+ | enable_keep_alive | boolean | true | 启用保活 |
174
+ | keep_alive_initial_delay | number | 10000 | 保活初始延迟(ms) |
175
+ | enable_reconnect | boolean | true | 启用重连 |
176
+ | reconnect_interval | number | 1000 | 重连间隔(ms) |
177
+ | max_reconnect_attempts | number | 5 | 最大重连尝试次数 |
178
+ | wait_for_connections | boolean | true | 等待连接 |
179
+ | pool_min | number | 1 | 连接池最小连接数 |
180
+ | pool_max | number | 5 | 连接池最大连接数 |
181
+ | pool_acquire_timeout | number | 30000 | 连接池获取超时(ms) |
182
+ | pool_idle_timeout | number | 60000 | 连接池空闲超时(ms) |
183
+ | pool_reap_interval | number | 1000 | 连接池清理间隔(ms) |
184
+
185
+ ## 开发规范
186
+
187
+ - 使用JavaScript开发,禁止使用TypeScript
188
+ - 使用JSDoc注释进行类型定义
189
+ - 遵循统一的命名规范和方法签名
190
+ - 完善的错误处理机制
191
+ - 支持异步/等待语法
428
192
 
429
193
  ## 许可证
430
194
 
@@ -432,18 +196,4 @@ MIT License
432
196
 
433
197
  ## 贡献
434
198
 
435
- 欢迎提交Issue和Pull Request来改进这个模块。提交代码前请确保:
436
-
437
- 1. 运行测试确保功能正常
438
- 2. 添加适当的注释和文档
439
- 3. 遵循项目的代码风格
440
- 4. 确保代码符合ES6+标准
441
- 5. 提交前请先拉取最新代码,解决冲突
442
-
443
- ### 开发流程
444
-
445
- 1. Fork 仓库
446
- 2. 创建特性分支 (`git checkout -b feature/AmazingFeature`)
447
- 3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
448
- 4. 推送到分支 (`git push origin feature/AmazingFeature`)
449
- 5. 打开 Pull Request
199
+ 欢迎提交Issue和Pull Request来改进这个项目。