mm_sql 1.3.8 → 1.3.9

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,6 +1,6 @@
1
1
  # mm_sql
2
2
 
3
- 一个通用的SQL帮助类,支持通过切换db_type实现对不同数据库的操作,包括MySQL和SQLite等。
3
+ 一个通用的SQL帮助类,支持通过切换db_type实现对不同数据库的操作,包括MySQL和SQLite等,提供统一的API接口,支持异步操作、事务处理和批量操作。
4
4
 
5
5
  ## 安装
6
6
 
@@ -10,8 +10,8 @@ npm install mm_sql
10
10
 
11
11
  ## 依赖
12
12
 
13
- - mm_mysql: ^2.0.3
14
- - mm_sqlite: ^1.0.0
13
+ - mm_mysql: ^2.1.1
14
+ - mm_sqlite: ^1.1.3
15
15
 
16
16
  ## 使用方法
17
17
 
@@ -19,7 +19,7 @@ npm install mm_sql
19
19
 
20
20
  ```javascript
21
21
  // 引入模块
22
- const Sql = require('mm_sql');
22
+ const { Sql } = require('mm_sql');
23
23
 
24
24
  // 创建实例(默认使用MySQL)
25
25
  const sql = new Sql({
@@ -31,10 +31,7 @@ const sql = new Sql({
31
31
  table: 'users'
32
32
  });
33
33
 
34
- // 初始化连接
35
- await sql.init();
36
-
37
- // 查询数据
34
+ // 直接使用(自动初始化连接)
38
35
  const users = await sql.get({ status: 1 }, 'created_at DESC');
39
36
 
40
37
  // 销毁连接
@@ -45,7 +42,7 @@ await sql.destroy();
45
42
 
46
43
  ```javascript
47
44
  // 创建MySQL实例
48
- const mysqlSql = new Sql({
45
+ const sql = new Sql({
49
46
  db_type: 'mysql',
50
47
  host: 'localhost',
51
48
  user: 'root',
@@ -55,13 +52,13 @@ const mysqlSql = new Sql({
55
52
  });
56
53
 
57
54
  // 切换到SQLite
58
- const sqliteSql = mysqlSql.use('sqlite', {
55
+ const sqliteSql = sql.use('sqlite', {
56
+ dir: '/db/',
59
57
  database: 'sqlite.db',
60
58
  table: 'users'
61
59
  });
62
60
 
63
- // 使用SQLite进行操作
64
- await sqliteSql.init();
61
+ // 使用SQLite进行操作(自动初始化连接)
65
62
  const data = await sqliteSql.get({});
66
63
  ```
67
64
 
@@ -104,6 +101,13 @@ const updateResult = await sql.set(
104
101
  { name: '李四', age: 26 } // 更新字段
105
102
  );
106
103
 
104
+ // 使用where属性修改数据
105
+ const updateResult2 = await sql.set({
106
+ where: { id: 1 },
107
+ name: '李四',
108
+ age: 26
109
+ });
110
+
107
111
  // 删除数据
108
112
  const deleteResult = await sql.del({ id: 1 });
109
113
 
@@ -136,15 +140,42 @@ const delListResult = await sql.delList([
136
140
  ]);
137
141
  ```
138
142
 
139
- #### 模型操作
143
+ #### 字段操作方法
144
+
145
+ ```javascript
146
+ // 添加字段
147
+ await sql.addField('phone', 'varchar(20)', '');
148
+
149
+ // 修改字段
150
+ await sql.setField('phone', 'varchar(11)', '0');
151
+
152
+ // 删除字段
153
+ await sql.delField('phone');
154
+
155
+ // 重命名字段
156
+ await sql.renameField('old_name', 'new_name');
157
+
158
+ // 编辑字段(高级)
159
+ await sql.editField('field_name', 'varchar(100)', 'NOT NULL DEFAULT \'\'');
160
+ ```
161
+
162
+ #### 表操作方法
140
163
 
141
164
  ```javascript
142
- // 获取模型对象
143
- const model = await sql.getObj({ id: 1 });
165
+ // 检查表是否存在
166
+ const exists = await sql.hasTable();
144
167
 
145
- // 直接修改模型属性会自动更新到数据库
146
- model.name = '新名称'; // 自动执行UPDATE操作
147
- model.age += 1; // 自动执行UPDATE操作,增加年龄
168
+ // 创建表
169
+ await sql.addTable('new_table', {
170
+ id: 'INTEGER PRIMARY KEY AUTOINCREMENT',
171
+ name: 'varchar(255) NOT NULL DEFAULT \'\'
172
+ });
173
+
174
+ // 删除表
175
+ await sql.delTable();
176
+
177
+ // 备份表
178
+ await sql.backupTable('backup_table');
148
179
  ```
149
180
 
150
181
  ### 4. 配置选项
@@ -170,20 +201,41 @@ const sql = new Sql({
170
201
  password: '',
171
202
  database: '',
172
203
  charset: 'utf8mb4',
204
+ connect_timeout: 10000, // 连接超时时间(毫秒)
205
+ query_timeout: 30000, // 查询超时时间(毫秒)
173
206
 
174
207
  // SQLite配置
175
- database: 'db.sqlite', // SQLite数据库文件路径
208
+ dir: '/db/', // SQLite数据库文件存储目录
209
+ database: 'db.sqlite', // SQLite数据库文件名
176
210
 
177
211
  // 其他配置
178
212
  filter: {}, // 过滤参数
179
- separator: '|' // 分隔符,用于多条件查询
213
+ separator: '|', // 分隔符,用于多条件查询
214
+ way: 'add del set get', // 请求方式
215
+ field_hide: ['*password*', '*token*'] // 隐藏字段
180
216
  });
181
217
  ```
182
218
 
183
219
  ## 事务操作
184
220
 
185
221
  ```javascript
186
- // MySQL事务示例
222
+ // 使用事务方法
223
+ await sql.start(); // 开始事务
224
+
225
+ try {
226
+ // 在事务中执行操作
227
+ await sql.add({ name: '测试用户1', age: 30 });
228
+ await sql.add({ name: '测试用户2', age: 25 });
229
+
230
+ await sql.commit(); // 提交事务
231
+ } catch (error) {
232
+ await sql.back(); // 回滚事务
233
+ console.error('事务执行失败:', error);
234
+ } finally {
235
+ await sql.end(); // 结束事务
236
+ }
237
+
238
+ // 直接执行事务SQL(MySQL)
187
239
  const mysqlTransactionResult = await sql.exec(`
188
240
  START TRANSACTION;
189
241
  INSERT INTO users (name, age) VALUES ('测试用户', 30);
@@ -191,7 +243,7 @@ const mysqlTransactionResult = await sql.exec(`
191
243
  COMMIT;
192
244
  `);
193
245
 
194
- // SQLite事务示例
246
+ // 直接执行事务SQL(SQLite
195
247
  const sqliteTransactionResult = await sql.exec(`
196
248
  BEGIN TRANSACTION;
197
249
  INSERT INTO users (name, age) VALUES ('测试用户', 30);
@@ -213,8 +265,31 @@ const sqlTemplate = {
213
265
  };
214
266
 
215
267
  // 使用模板构建查询条件
216
- const query = sql.tpl_query({ name: '张', age: 20 }, sqlTemplate);
217
- // 生成的查询条件: "`name` LIKE \"张%\" && `age` > 20"
268
+ const query = sql.tplQuery({ name: '张', age: 20 }, sqlTemplate);
269
+ // 生成的查询条件: "`name` LIKE \"张%\" AND `age` > 20"
270
+
271
+ // 使用模板构建更新语句
272
+ const body = sql.tplBody({ name: '李四', age: 25 }, {
273
+ name: '`name` = {0}',
274
+ age: '`age` = {0}'
275
+ });
276
+ // 生成的更新语句: "`name` = '李四', `age` = 25"
277
+
278
+ // 使用配置文件定义SQL模板
279
+ const config = {
280
+ "query": {
281
+ "name": "`name` like '%{0}%'"
282
+ },
283
+ "where": {
284
+ "uid": "`uid` = {0}"
285
+ },
286
+ "update": {
287
+ "name": "`name` = {0}"
288
+ }
289
+ };
290
+
291
+ // 使用配置文件中的模板
292
+ const queryFromConfig = sql.tplQuery({ name: '张' }, config.query);
218
293
  ```
219
294
 
220
295
  ### 2. 自定义SQL执行
@@ -225,14 +300,21 @@ const result = await sql.run('SELECT * FROM users WHERE status = 1');
225
300
 
226
301
  // 执行自定义更新SQL
227
302
  const updateResult = await sql.exec('UPDATE users SET status = 0 WHERE id = 1');
228
- ```
303
+
304
+ // 执行带参数的SQL
305
+ const user = await sql.run('SELECT * FROM users WHERE id = ?', [1]);
306
+
307
+ // 执行带超时的SQL
308
+ const timeoutResult = await sql.run('SELECT * FROM users WHERE status = 1', [], 5000);
229
309
 
230
310
  ## 注意事项
231
311
 
232
- 1. 使用前必须先调用`init()`方法初始化连接
233
- 2. 使用完成后应调用`destroy()`方法销毁连接,避免资源泄漏
312
+ 1. 可以直接使用方法,系统会自动初始化连接,无需手动调用`init()`方法
313
+ 2. 使用完成后建议调用`destroy()`方法销毁连接,避免资源泄漏
234
314
  3. 切换数据库类型时会重新创建适配器,原来的连接会被关闭
235
315
  4. 为提高性能,系统会缓存数据库适配器,相同配置的实例会复用适配器
316
+ 5. 不同数据库的SQL语法可能有所差异,请根据实际使用的数据库类型调整SQL语句
317
+ 6. 事务操作中,建议使用`start()`/`commit()`/`back()`/`end()`方法,确保事务正确处理
236
318
 
237
319
  ## 支持的数据库类型
238
320
 
package/index.js CHANGED
@@ -17,7 +17,12 @@ class Sql {
17
17
  * 配置信息
18
18
  */
19
19
  this.config = Object.assign({
20
- db_type: 'mysql'
20
+ scope: 'sys',
21
+ db_type: 'mysql',
22
+ dir: '/db/',
23
+ host: 'localhost',
24
+ port: 3306,
25
+ database: ''
21
26
  }, config || {});
22
27
 
23
28
  /**
@@ -49,12 +54,12 @@ Sql.prototype._createSqlAdapter = function () {
49
54
  // 根据数据库类型选择不同的初始化方式
50
55
  if (this.config.db_type === 'mysql') {
51
56
  // 创建MySQL实例
52
- const Mysql = adapter.Mysql;
53
- this._adapter = new Mysql(this.config);
57
+ const admin = adapter.mysqlAdmin;
58
+ this._adapter = admin(this.config.scope, this.config);
54
59
  } else if (this.config.db_type === 'sqlite') {
55
60
  // SQLite应该有类似的结构
56
- const Sqlite = adapter.Sqlite;
57
- this._adapter = new Sqlite(this.config);
61
+ const admin = adapter.sqliteAdmin;
62
+ this._adapter = admin(this.config.scope, this.config);
58
63
  } else {
59
64
  // 其他数据库类型直接使用Sql类(如果存在)
60
65
  const AdapterClass = adapter.Sql;
@@ -135,6 +140,7 @@ Sql.prototype.getConnectionInfo = function () {
135
140
  db_type: this.config.db_type,
136
141
  host: this.config.host || 'localhost',
137
142
  port: this.config.port || 3306,
143
+ dir: this.config.dir || '/db/',
138
144
  database: this.config.database || ''
139
145
  };
140
146
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mm_sql",
3
- "version": "1.3.8",
3
+ "version": "1.3.9",
4
4
  "description": "一个通用的SQL帮助类,支持通过切换db_type实现对不同数据库的操作,包括MySQL和SQLite等",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -41,7 +41,7 @@
41
41
  "node": ">=12.0.0"
42
42
  },
43
43
  "dependencies": {
44
- "mm_mysql": "^2.1.1",
45
- "mm_sqlite": "^1.1.2"
44
+ "mm_mysql": "^2.2.0",
45
+ "mm_sqlite": "^1.1.4"
46
46
  }
47
47
  }
package/test2.js CHANGED
@@ -1,10 +1,10 @@
1
1
  const { Sql } = require('./index.js');
2
-
2
+ require('mm_logs');
3
3
  async function test() {
4
4
  var sql = new Sql({
5
5
  // 数据库类型 mysql, sqlite, postgres
6
6
  db_type: 'sqlite',
7
- host: '/db/',
7
+ dir: "/db/".fullname() + "/",
8
8
  user: 'root',
9
9
  password: 'Asd159357',
10
10
  database: 'mm'
@@ -15,17 +15,35 @@ async function test() {
15
15
 
16
16
  var db = sql.db();
17
17
  db.table = "user_account";
18
+ // 添加表
18
19
  var res = await db.addTable('user_account', 'user_id');
19
- await db.addField('user_account', 'vip', 'INT', '0');
20
- await db.addField('user_account', 'gm', 'INT', '0');
21
20
  console.log("添加表结果:", res);
21
+
22
+ // 添加字段(不需要指定表名,因为已通过db.table设置)
23
+ var res2 = await db.addField('vip', 'INT', '0');
24
+ var res3 = await db.addField('gm', 'INT', '0');
25
+ console.log("添加字段结果:", res2, res3);
22
26
  db.key = "user_id";
23
27
  var user = await db.getObj({
24
28
  user_id: 1
25
29
  });
26
- user.vip = 5;
27
- user.gm = 5;
28
- await $.sleep(3000);
30
+
31
+ if (!user) {
32
+ // 如果用户不存在,创建一个新用户
33
+ user = {
34
+ user_id: 1,
35
+ vip: 5,
36
+ gm: 5
37
+ };
38
+ await db.add(user);
39
+ } else {
40
+ // 如果用户存在,更新其属性
41
+ user.vip = 5;
42
+ user.gm = 5;
43
+ await db.set({ user_id: 1 }, user);
44
+ }
45
+ // 使用原生的setTimeout实现延迟
46
+ await new Promise(resolve => setTimeout(resolve, 3000));
29
47
  db.size = 1;
30
48
  var list = await db.get({
31
49
  user_id: 1
@@ -33,4 +51,11 @@ async function test() {
33
51
  console.log("查询结果:", list);
34
52
  }
35
53
 
36
- test();
54
+ // 调用test函数并处理异常
55
+ test().catch(err => {
56
+ console.error('测试过程中发生错误:', err);
57
+ process.exit(1);
58
+ }).finally(() => {
59
+ // 确保程序以零退出码结束
60
+ process.exit(0);
61
+ });
package/db/mm.db DELETED
Binary file
package/localhostmm.db DELETED
File without changes