baja-lite 1.0.1 → 1.0.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/cjs/sql.js CHANGED
@@ -37,7 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  var _a, _b, _c;
38
38
  var _d, _e, _f;
39
39
  Object.defineProperty(exports, "__esModule", { value: true });
40
- exports.LetsGo = exports.MethodCache = exports.excuteWithCache = exports.clearMethodCache = exports.MethodLock = exports.excuteWithLock = exports.GetRedisLock = exports.getRedisDB = exports.SqlService = exports.DeclareService = exports.DeclareClass = exports.DB = exports.Field = exports.SqliteMemory = exports.SqlType = exports.SqlQueryMode = exports.SqlTemplateMode = exports.SqlSelectMode = exports.SqlDelMode = exports.SqlInsertMode = exports.SqlSyncMode = exports.DBType = void 0;
40
+ exports.Boot = exports.MethodCache = exports.excuteWithCache = exports.clearMethodCache = exports.MethodLock = exports.excuteWithLock = exports.GetRedisLock = exports.getRedisDB = exports.SqlService = exports.DeclareService = exports.DeclareClass = exports.DB = exports.Field = exports.SqliteMemory = exports.SqlType = exports.SelectResult = exports.TemplateResult = exports.SelectMode = exports.DeleteMode = exports.InsertMode = exports.SyncMode = exports.DBType = void 0;
41
41
  require("reflect-metadata");
42
42
  const error_1 = require("./error");
43
43
  const tslib_1 = __importDefault(require("tslib"));
@@ -47,6 +47,7 @@ const string_1 = require("./string");
47
47
  const pino_1 = __importDefault(require("pino"));
48
48
  const fn_1 = require("./fn");
49
49
  const math_1 = require("./math");
50
+ const mustache_1 = __importDefault(require("mustache"));
50
51
  // #region 常量
51
52
  const _daoDBName = Symbol('dbName');
52
53
  const _tableName = Symbol('tableName');
@@ -59,7 +60,7 @@ const _deleteState = Symbol('deleteState');
59
60
  const _transformer = Symbol('transformer');
60
61
  const _index = Symbol('index');
61
62
  const _def = Symbol('def');
62
- const _sqlCache = Symbol('sqlCache');
63
+ const _sqlCache = Symbol('sqlMap');
63
64
  const _dao = Symbol('dao');
64
65
  const _primaryDB = Symbol('primaryDB');
65
66
  const _dbType = Symbol('dbType');
@@ -90,21 +91,21 @@ var DBType;
90
91
  DBType[DBType["Redis"] = 4] = "Redis";
91
92
  DBType[DBType["RedisLock"] = 5] = "RedisLock";
92
93
  })(DBType || (exports.DBType = DBType = {}));
93
- var SqlSyncMode;
94
- (function (SqlSyncMode) {
94
+ var SyncMode;
95
+ (function (SyncMode) {
95
96
  /** 同步执行 */
96
- SqlSyncMode[SqlSyncMode["Sync"] = 0] = "Sync";
97
+ SyncMode[SyncMode["Sync"] = 0] = "Sync";
97
98
  /** 异步执行 */
98
- SqlSyncMode[SqlSyncMode["Async"] = 1] = "Async";
99
- })(SqlSyncMode || (exports.SqlSyncMode = SqlSyncMode = {}));
100
- var SqlInsertMode;
101
- (function (SqlInsertMode) {
99
+ SyncMode[SyncMode["Async"] = 1] = "Async";
100
+ })(SyncMode || (exports.SyncMode = SyncMode = {}));
101
+ var InsertMode;
102
+ (function (InsertMode) {
102
103
  /**
103
104
  # 默认使用
104
105
  ** 支持单个、批量,语法 `INSERT INTO XX VALUES (第一条数据), (第二条数据);`
105
106
  ** 批量执行有性能优势,但无法利用数据库的sql预编译功能
106
107
  */
107
- SqlInsertMode[SqlInsertMode["Insert"] = 0] = "Insert";
108
+ InsertMode[InsertMode["Insert"] = 0] = "Insert";
108
109
  /**
109
110
  # 利用临时表
110
111
  ## 执行步骤
@@ -116,16 +117,16 @@ var SqlInsertMode;
116
117
  1. 适用于:主键不会冲突、非自增
117
118
  2. 临时表的结构复制正式表
118
119
  */
119
- SqlInsertMode[SqlInsertMode["InsertWithTempTable"] = 1] = "InsertWithTempTable";
120
- SqlInsertMode[SqlInsertMode["InsertIfNotExists"] = 2] = "InsertIfNotExists";
120
+ InsertMode[InsertMode["InsertWithTempTable"] = 1] = "InsertWithTempTable";
121
+ InsertMode[InsertMode["InsertIfNotExists"] = 2] = "InsertIfNotExists";
121
122
  /**
122
123
  # 插入或者更新
123
124
  1. 判断依据是主键
124
125
  */
125
- SqlInsertMode[SqlInsertMode["Replace"] = 3] = "Replace";
126
- })(SqlInsertMode || (exports.SqlInsertMode = SqlInsertMode = {}));
127
- var SqlDelMode;
128
- (function (SqlDelMode) {
126
+ InsertMode[InsertMode["Replace"] = 3] = "Replace";
127
+ })(InsertMode || (exports.InsertMode = InsertMode = {}));
128
+ var DeleteMode;
129
+ (function (DeleteMode) {
129
130
  /**
130
131
  ##常规删除 默认
131
132
  ### 例一
@@ -133,16 +134,16 @@ var SqlDelMode;
133
134
  ### 例二
134
135
  `DELETE FROM WHERE (id = 1 AND idx = 11) OR (id = 2 AND idx = 22)`
135
136
  */
136
- SqlDelMode[SqlDelMode["Common"] = 0] = "Common";
137
+ DeleteMode[DeleteMode["Common"] = 0] = "Common";
137
138
  /*
138
139
  ## 借助临时表
139
140
  ### 注意:必须保证where的字段都相同,否则会漏删数据
140
141
  DELETE FROM 正式表 INNER JOIN 临时表 WHERE 字段1 = 字段1 AND 字段2 = 字段2
141
142
  */
142
- SqlDelMode[SqlDelMode["TempTable"] = 1] = "TempTable";
143
- })(SqlDelMode || (exports.SqlDelMode = SqlDelMode = {}));
144
- var SqlSelectMode;
145
- (function (SqlSelectMode) {
143
+ DeleteMode[DeleteMode["TempTable"] = 1] = "TempTable";
144
+ })(DeleteMode || (exports.DeleteMode = DeleteMode = {}));
145
+ var SelectMode;
146
+ (function (SelectMode) {
146
147
  /**
147
148
  ##常规 默认
148
149
  ### 例一
@@ -150,46 +151,70 @@ var SqlSelectMode;
150
151
  ### 例二
151
152
  `SELECT * FROM WHERE (id = 1 AND idx = 11) OR (id = 2 AND idx = 22)`
152
153
  */
153
- SqlSelectMode[SqlSelectMode["Common"] = 0] = "Common";
154
+ SelectMode[SelectMode["Common"] = 0] = "Common";
154
155
  /*
155
156
  ## 借助临时表
156
157
  ### 注意:必须保证where的字段都相同,否则会漏删数据
157
158
  SELECT * FROM 正式表 INNER JOIN 临时表 WHERE 字段1 = 字段1 AND 字段2 = 字段2
158
159
  */
159
- SqlSelectMode[SqlSelectMode["TempTable"] = 1] = "TempTable";
160
- })(SqlSelectMode || (exports.SqlSelectMode = SqlSelectMode = {}));
161
- var SqlTemplateMode;
162
- (function (SqlTemplateMode) {
163
- /** 确定返回一个,如果不是一个,将报错,返回类型是T */
164
- SqlTemplateMode[SqlTemplateMode["AssertOne"] = 0] = "AssertOne";
165
- /** 可能返回一个,返回类型是T|null */
166
- SqlTemplateMode[SqlTemplateMode["NotSureOne"] = 1] = "NotSureOne";
167
- /** 返回多个 */
168
- SqlTemplateMode[SqlTemplateMode["Many"] = 2] = "Many";
160
+ SelectMode[SelectMode["TempTable"] = 1] = "TempTable";
161
+ })(SelectMode || (exports.SelectMode = SelectMode = {}));
162
+ var TemplateResult;
163
+ (function (TemplateResult) {
164
+ /** 确定返回一条记录,如果不是一个,将报错,返回类型是T */
165
+ TemplateResult[TemplateResult["AssertOne"] = 0] = "AssertOne";
166
+ /** 可能返回一条记录,返回类型是T|null */
167
+ TemplateResult[TemplateResult["NotSureOne"] = 1] = "NotSureOne";
168
+ /** 返回多条记录 */
169
+ TemplateResult[TemplateResult["Many"] = 2] = "Many";
169
170
  /** 仅查询记录数量 */
170
- SqlTemplateMode[SqlTemplateMode["Count"] = 3] = "Count";
171
- })(SqlTemplateMode || (exports.SqlTemplateMode = SqlTemplateMode = {}));
172
- var SqlQueryMode;
173
- (function (SqlQueryMode) {
174
- SqlQueryMode[SqlQueryMode["One_Row_One_Column_Assert"] = 0] = "One_Row_One_Column_Assert";
175
- SqlQueryMode[SqlQueryMode["One_Row_One_Column_NotSure"] = 1] = "One_Row_One_Column_NotSure";
176
- SqlQueryMode[SqlQueryMode["One_Row_Many_Column_Assert"] = 2] = "One_Row_Many_Column_Assert";
177
- SqlQueryMode[SqlQueryMode["One_Row_Many_Column_NotSure"] = 3] = "One_Row_Many_Column_NotSure";
178
- SqlQueryMode[SqlQueryMode["Many_Row_One_Column"] = 4] = "Many_Row_One_Column";
179
- SqlQueryMode[SqlQueryMode["Many_Row_Many_Column"] = 5] = "Many_Row_Many_Column";
180
- })(SqlQueryMode || (exports.SqlQueryMode = SqlQueryMode = {}));
171
+ TemplateResult[TemplateResult["Count"] = 3] = "Count";
172
+ })(TemplateResult || (exports.TemplateResult = TemplateResult = {}));
173
+ var SelectResult;
174
+ (function (SelectResult) {
175
+ SelectResult[SelectResult["One_Row_One_Column_Assert"] = 0] = "One_Row_One_Column_Assert";
176
+ SelectResult[SelectResult["One_Row_One_Column_NotSure"] = 1] = "One_Row_One_Column_NotSure";
177
+ SelectResult[SelectResult["One_Row_Many_Column_Assert"] = 2] = "One_Row_Many_Column_Assert";
178
+ SelectResult[SelectResult["One_Row_Many_Column_NotSure"] = 3] = "One_Row_Many_Column_NotSure";
179
+ SelectResult[SelectResult["Many_Row_One_Column"] = 4] = "Many_Row_One_Column";
180
+ SelectResult[SelectResult["Many_Row_Many_Column"] = 5] = "Many_Row_Many_Column";
181
+ })(SelectResult || (exports.SelectResult = SelectResult = {}));
181
182
  var SqlType;
182
183
  (function (SqlType) {
183
- SqlType[SqlType["bigint"] = 0] = "bigint";
184
- SqlType[SqlType["char"] = 1] = "char";
185
- SqlType[SqlType["decimal"] = 2] = "decimal";
184
+ SqlType[SqlType["tinyint"] = 0] = "tinyint";
185
+ SqlType[SqlType["smallint"] = 1] = "smallint";
186
+ SqlType[SqlType["mediumint"] = 2] = "mediumint";
186
187
  SqlType[SqlType["int"] = 3] = "int";
187
- SqlType[SqlType["longtext"] = 4] = "longtext";
188
- SqlType[SqlType["mediumtext"] = 5] = "mediumtext";
189
- SqlType[SqlType["smallint"] = 6] = "smallint";
190
- SqlType[SqlType["text"] = 7] = "text";
191
- SqlType[SqlType["tinyint"] = 8] = "tinyint";
192
- SqlType[SqlType["varchar"] = 9] = "varchar";
188
+ SqlType[SqlType["bigint"] = 4] = "bigint";
189
+ SqlType[SqlType["float"] = 5] = "float";
190
+ SqlType[SqlType["double"] = 6] = "double";
191
+ SqlType[SqlType["decimal"] = 7] = "decimal";
192
+ SqlType[SqlType["date"] = 8] = "date";
193
+ SqlType[SqlType["time"] = 9] = "time";
194
+ SqlType[SqlType["year"] = 10] = "year";
195
+ SqlType[SqlType["datetime"] = 11] = "datetime";
196
+ SqlType[SqlType["timestamp"] = 12] = "timestamp";
197
+ SqlType[SqlType["char"] = 13] = "char";
198
+ SqlType[SqlType["varchar"] = 14] = "varchar";
199
+ SqlType[SqlType["tinyblob"] = 15] = "tinyblob";
200
+ SqlType[SqlType["tinytext"] = 16] = "tinytext";
201
+ SqlType[SqlType["blob"] = 17] = "blob";
202
+ SqlType[SqlType["text"] = 18] = "text";
203
+ SqlType[SqlType["mediumblob"] = 19] = "mediumblob";
204
+ SqlType[SqlType["mediumtext"] = 20] = "mediumtext";
205
+ SqlType[SqlType["longblob"] = 21] = "longblob";
206
+ SqlType[SqlType["longtext"] = 22] = "longtext";
207
+ SqlType[SqlType["set"] = 23] = "set";
208
+ SqlType[SqlType["enum"] = 24] = "enum";
209
+ SqlType[SqlType["json"] = 25] = "json";
210
+ SqlType[SqlType["geometry"] = 26] = "geometry";
211
+ SqlType[SqlType["point"] = 27] = "point";
212
+ SqlType[SqlType["linestring"] = 28] = "linestring";
213
+ SqlType[SqlType["polygon"] = 29] = "polygon";
214
+ SqlType[SqlType["multipoint"] = 30] = "multipoint";
215
+ SqlType[SqlType["multilinestring"] = 31] = "multilinestring";
216
+ SqlType[SqlType["multipolygon"] = 32] = "multipolygon";
217
+ SqlType[SqlType["geometrycollection"] = 33] = "geometrycollection";
193
218
  })(SqlType || (exports.SqlType = SqlType = {}));
194
219
  exports.SqliteMemory = ':memory:';
195
220
  const _defOption = {
@@ -210,7 +235,7 @@ class MysqlConnection {
210
235
  return { affectedRows: 0, insertId: 0n };
211
236
  }
212
237
  ;
213
- if (sync === SqlSyncMode.Sync) {
238
+ if (sync === SyncMode.Sync) {
214
239
  logger.warn('MYSQL not suppouted sync mode');
215
240
  return { affectedRows: 0, insertId: 0n };
216
241
  }
@@ -218,7 +243,7 @@ class MysqlConnection {
218
243
  if (globalThis[_GlobalSqlOption].log === 'trace') {
219
244
  logger.trace(sqlstring_1.default.format(sql, params));
220
245
  }
221
- return new Promise(async (resolve) => {
246
+ return new Promise(async (resolve, reject) => {
222
247
  try {
223
248
  const [_result] = await this[_daoConnection].execute(sql, params);
224
249
  const result = _result;
@@ -233,7 +258,7 @@ class MysqlConnection {
233
258
  sql: ${sql},
234
259
  params: ${params}
235
260
  `);
236
- throw error;
261
+ reject(error);
237
262
  }
238
263
  });
239
264
  }
@@ -243,7 +268,7 @@ class MysqlConnection {
243
268
  return null;
244
269
  }
245
270
  ;
246
- if (sync === SqlSyncMode.Sync) {
271
+ if (sync === SyncMode.Sync) {
247
272
  logger.warn('MYSQL not suppouted sync mode');
248
273
  return null;
249
274
  }
@@ -251,7 +276,7 @@ class MysqlConnection {
251
276
  if (globalThis[_GlobalSqlOption].log === 'trace') {
252
277
  logger.trace(sqlstring_1.default.format(sql, params));
253
278
  }
254
- return new Promise(async (resolve) => {
279
+ return new Promise(async (resolve, reject) => {
255
280
  try {
256
281
  const [result] = await this[_daoConnection].query(sql, params);
257
282
  if (result && result[0]) {
@@ -269,7 +294,7 @@ class MysqlConnection {
269
294
  sql: ${sql},
270
295
  params: ${params}
271
296
  `);
272
- throw error;
297
+ reject(error);
273
298
  }
274
299
  });
275
300
  }
@@ -279,7 +304,7 @@ class MysqlConnection {
279
304
  return null;
280
305
  }
281
306
  ;
282
- if (sync === SqlSyncMode.Sync) {
307
+ if (sync === SyncMode.Sync) {
283
308
  logger.warn('MYSQL not suppouted sync mode');
284
309
  return null;
285
310
  }
@@ -287,7 +312,7 @@ class MysqlConnection {
287
312
  if (globalThis[_GlobalSqlOption].log === 'trace') {
288
313
  logger.trace(sqlstring_1.default.format(sql, params));
289
314
  }
290
- return new Promise(async (resolve) => {
315
+ return new Promise(async (resolve, reject) => {
291
316
  try {
292
317
  const [result] = await this[_daoConnection].query(sql, params);
293
318
  if (globalThis[_GlobalSqlOption].log === 'trace') {
@@ -303,7 +328,7 @@ class MysqlConnection {
303
328
  sql: ${sql},
304
329
  params: ${params}
305
330
  `);
306
- throw error;
331
+ reject(error);
307
332
  }
308
333
  });
309
334
  }
@@ -313,7 +338,7 @@ class MysqlConnection {
313
338
  return [];
314
339
  }
315
340
  ;
316
- if (sync === SqlSyncMode.Sync) {
341
+ if (sync === SyncMode.Sync) {
317
342
  logger.warn('MYSQL not suppouted sync mode');
318
343
  return [];
319
344
  }
@@ -321,7 +346,7 @@ class MysqlConnection {
321
346
  if (globalThis[_GlobalSqlOption].log === 'trace') {
322
347
  logger.trace(sqlstring_1.default.format(sql, params));
323
348
  }
324
- return new Promise(async (resolve) => {
349
+ return new Promise(async (resolve, reject) => {
325
350
  try {
326
351
  const [result] = await this[_daoConnection].query(sql, params);
327
352
  if (globalThis[_GlobalSqlOption].log === 'trace') {
@@ -337,7 +362,7 @@ class MysqlConnection {
337
362
  sql: ${sql},
338
363
  params: ${params}
339
364
  `);
340
- throw error;
365
+ reject(error);
341
366
  }
342
367
  });
343
368
  }
@@ -347,7 +372,7 @@ class MysqlConnection {
347
372
  return [];
348
373
  }
349
374
  ;
350
- if (sync === SqlSyncMode.Sync) {
375
+ if (sync === SyncMode.Sync) {
351
376
  logger.warn('MYSQL not suppouted sync mode');
352
377
  return [];
353
378
  }
@@ -355,7 +380,7 @@ class MysqlConnection {
355
380
  if (globalThis[_GlobalSqlOption].log === 'trace') {
356
381
  logger.trace(sqlstring_1.default.format(sql, params));
357
382
  }
358
- return new Promise(async (resolve) => {
383
+ return new Promise(async (resolve, reject) => {
359
384
  try {
360
385
  const [result] = await this[_daoConnection].query(sql, params);
361
386
  if (globalThis[_GlobalSqlOption].log === 'trace') {
@@ -369,12 +394,12 @@ class MysqlConnection {
369
394
  sql: ${sql},
370
395
  params: ${params}
371
396
  `);
372
- throw error;
397
+ reject(error);
373
398
  }
374
399
  });
375
400
  }
376
401
  realse(sync) {
377
- if (sync === SqlSyncMode.Sync) {
402
+ if (sync === SyncMode.Sync) {
378
403
  try {
379
404
  this[_daoConnection]?.release();
380
405
  }
@@ -390,28 +415,33 @@ class Mysql {
390
415
  this[_daoDB] = pool;
391
416
  }
392
417
  createConnection(sync) {
393
- if (sync === SqlSyncMode.Sync) {
418
+ if (sync === SyncMode.Sync) {
394
419
  logger.error('MYSQL not suppouted sync mode');
395
420
  return null;
396
421
  }
397
422
  ;
398
- return new Promise(async (resolve) => {
399
- const connection = await this[_daoDB].getConnection();
400
- logger.debug('create new!');
401
- resolve(new MysqlConnection(connection));
423
+ return new Promise(async (resolve, reject) => {
424
+ try {
425
+ const connection = await this[_daoDB].getConnection();
426
+ logger.debug('create new!');
427
+ resolve(new MysqlConnection(connection));
428
+ }
429
+ catch (error) {
430
+ reject(error);
431
+ }
402
432
  });
403
433
  }
404
434
  transaction(sync, fn, conn) {
405
- if (sync === SqlSyncMode.Sync) {
435
+ if (sync === SyncMode.Sync) {
406
436
  logger.warn('MYSQL not suppouted sync mode');
407
437
  return null;
408
438
  }
409
439
  ;
410
- return new Promise(async (resolve) => {
440
+ return new Promise(async (resolve, reject) => {
411
441
  let needCommit = false;
412
442
  let newConn = false;
413
443
  if (!conn) {
414
- conn = await this.createConnection(SqlSyncMode.Async) ?? undefined;
444
+ conn = await this.createConnection(SyncMode.Async) ?? undefined;
415
445
  newConn = true;
416
446
  }
417
447
  if (conn?.[_inTransaction] !== true) {
@@ -437,7 +467,7 @@ class Mysql {
437
467
  logger.debug('rollback end!');
438
468
  conn[_inTransaction] = false;
439
469
  logger.error(error);
440
- throw error;
470
+ reject(error);
441
471
  }
442
472
  finally {
443
473
  try {
@@ -456,7 +486,7 @@ class Mysql {
456
486
  });
457
487
  }
458
488
  close(sync) {
459
- if (sync === SqlSyncMode.Sync) {
489
+ if (sync === SyncMode.Sync) {
460
490
  this[_daoDB]?.destroy();
461
491
  }
462
492
  ;
@@ -480,7 +510,7 @@ class SqliteConnection {
480
510
  return { affectedRows: 0, insertId: 0n };
481
511
  }
482
512
  ;
483
- if (sync === SqlSyncMode.Async) {
513
+ if (sync === SyncMode.Async) {
484
514
  logger.warn(`SQLITE not suppoted async mode`);
485
515
  return { affectedRows: 0, insertId: 0n };
486
516
  }
@@ -511,7 +541,7 @@ class SqliteConnection {
511
541
  return null;
512
542
  }
513
543
  ;
514
- if (sync === SqlSyncMode.Async) {
544
+ if (sync === SyncMode.Async) {
515
545
  logger.warn(`SQLITE not suppoted async mode`);
516
546
  return null;
517
547
  }
@@ -537,7 +567,7 @@ class SqliteConnection {
537
567
  return null;
538
568
  }
539
569
  ;
540
- if (sync === SqlSyncMode.Async) {
570
+ if (sync === SyncMode.Async) {
541
571
  return null;
542
572
  }
543
573
  ;
@@ -562,7 +592,7 @@ class SqliteConnection {
562
592
  return [];
563
593
  }
564
594
  ;
565
- if (sync === SqlSyncMode.Async) {
595
+ if (sync === SyncMode.Async) {
566
596
  logger.warn(`SQLITE not suppoted async mode`);
567
597
  return [];
568
598
  }
@@ -588,7 +618,7 @@ class SqliteConnection {
588
618
  return [];
589
619
  }
590
620
  ;
591
- if (sync === SqlSyncMode.Async) {
621
+ if (sync === SyncMode.Async) {
592
622
  logger.warn(`SQLITE not suppoted async mode`);
593
623
  return [];
594
624
  }
@@ -627,7 +657,7 @@ class Sqlite {
627
657
  `);
628
658
  }
629
659
  createConnection(sync) {
630
- if (sync === SqlSyncMode.Async) {
660
+ if (sync === SyncMode.Async) {
631
661
  logger.error(`SQLITE not suppoted async mode`);
632
662
  return null;
633
663
  }
@@ -635,13 +665,13 @@ class Sqlite {
635
665
  return new SqliteConnection(this[_daoDB]);
636
666
  }
637
667
  transaction(sync, fn, conn) {
638
- if (sync === SqlSyncMode.Async) {
668
+ if (sync === SyncMode.Async) {
639
669
  logger.warn(`SQLITE not suppoted async mode`);
640
670
  return null;
641
671
  }
642
672
  ;
643
673
  if (!conn) {
644
- conn = this.createConnection(SqlSyncMode.Sync) ?? undefined;
674
+ conn = this.createConnection(SyncMode.Sync) ?? undefined;
645
675
  }
646
676
  if (conn[_inTransaction] !== true) {
647
677
  return this[_daoDB].transaction(() => {
@@ -657,13 +687,13 @@ class Sqlite {
657
687
  }
658
688
  }
659
689
  close(sync) {
660
- if (sync === SqlSyncMode.Sync) {
690
+ if (sync === SyncMode.Sync) {
661
691
  this[_daoDB].close();
662
692
  }
663
693
  ;
664
694
  }
665
695
  backup(sync, name) {
666
- if (sync === SqlSyncMode.Sync) {
696
+ if (sync === SyncMode.Sync) {
667
697
  this[_daoDB].backup(name);
668
698
  }
669
699
  ;
@@ -685,7 +715,7 @@ class SqliteRemoteConnection {
685
715
  return { affectedRows: 0, insertId: 0n };
686
716
  }
687
717
  ;
688
- if (sync === SqlSyncMode.Sync) {
718
+ if (sync === SyncMode.Sync) {
689
719
  logger.warn('SqliteRemote not suppouted sync mode');
690
720
  return { affectedRows: 0, insertId: 0n };
691
721
  }
@@ -693,7 +723,7 @@ class SqliteRemoteConnection {
693
723
  if (globalThis[_GlobalSqlOption].log === 'trace') {
694
724
  logger.trace(sqlstring_1.default.format(sql, params));
695
725
  }
696
- return new Promise(async (resolve) => {
726
+ return new Promise(async (resolve, reject) => {
697
727
  try {
698
728
  const { affectedRows, insertId } = await this[_daoConnection].execute(this[_sqliteRemoteName], sql, params);
699
729
  resolve({ affectedRows, insertId: insertId ? BigInt(insertId) : 0n });
@@ -704,7 +734,7 @@ class SqliteRemoteConnection {
704
734
  sql: ${sql},
705
735
  params: ${params}
706
736
  `);
707
- throw error;
737
+ reject(error);
708
738
  }
709
739
  });
710
740
  }
@@ -714,7 +744,7 @@ class SqliteRemoteConnection {
714
744
  return null;
715
745
  }
716
746
  ;
717
- if (sync === SqlSyncMode.Sync) {
747
+ if (sync === SyncMode.Sync) {
718
748
  logger.warn('SqliteRemote not suppouted sync mode');
719
749
  return null;
720
750
  }
@@ -722,7 +752,7 @@ class SqliteRemoteConnection {
722
752
  if (globalThis[_GlobalSqlOption].log === 'trace') {
723
753
  logger.trace(sqlstring_1.default.format(sql, params));
724
754
  }
725
- return new Promise(async (resolve) => {
755
+ return new Promise(async (resolve, reject) => {
726
756
  try {
727
757
  const r = await this[_daoConnection].pluck(this[_sqliteRemoteName], sql, params);
728
758
  resolve(r);
@@ -733,7 +763,7 @@ class SqliteRemoteConnection {
733
763
  sql: ${sql},
734
764
  params: ${params}
735
765
  `);
736
- throw error;
766
+ reject(error);
737
767
  }
738
768
  });
739
769
  }
@@ -743,7 +773,7 @@ class SqliteRemoteConnection {
743
773
  return null;
744
774
  }
745
775
  ;
746
- if (sync === SqlSyncMode.Sync) {
776
+ if (sync === SyncMode.Sync) {
747
777
  logger.warn('SqliteRemote not suppouted sync mode');
748
778
  return null;
749
779
  }
@@ -751,7 +781,7 @@ class SqliteRemoteConnection {
751
781
  if (globalThis[_GlobalSqlOption].log === 'trace') {
752
782
  logger.trace(sqlstring_1.default.format(sql, params));
753
783
  }
754
- return new Promise(async (resolve) => {
784
+ return new Promise(async (resolve, reject) => {
755
785
  try {
756
786
  const r = await this[_daoConnection].get(this[_sqliteRemoteName], sql, params);
757
787
  resolve(r);
@@ -762,7 +792,7 @@ class SqliteRemoteConnection {
762
792
  sql: ${sql},
763
793
  params: ${params}
764
794
  `);
765
- throw error;
795
+ reject(error);
766
796
  }
767
797
  });
768
798
  }
@@ -772,7 +802,7 @@ class SqliteRemoteConnection {
772
802
  return [];
773
803
  }
774
804
  ;
775
- if (sync === SqlSyncMode.Sync) {
805
+ if (sync === SyncMode.Sync) {
776
806
  logger.warn('SqliteRemote not suppouted sync mode');
777
807
  return [];
778
808
  }
@@ -780,7 +810,7 @@ class SqliteRemoteConnection {
780
810
  if (globalThis[_GlobalSqlOption].log === 'trace') {
781
811
  logger.trace(sqlstring_1.default.format(sql, params));
782
812
  }
783
- return new Promise(async (resolve) => {
813
+ return new Promise(async (resolve, reject) => {
784
814
  try {
785
815
  const r = await this[_daoConnection].raw(this[_sqliteRemoteName], sql, params);
786
816
  resolve(r);
@@ -791,7 +821,7 @@ class SqliteRemoteConnection {
791
821
  sql: ${sql},
792
822
  params: ${params}
793
823
  `);
794
- throw error;
824
+ reject(error);
795
825
  }
796
826
  });
797
827
  }
@@ -801,7 +831,7 @@ class SqliteRemoteConnection {
801
831
  return [];
802
832
  }
803
833
  ;
804
- if (sync === SqlSyncMode.Sync) {
834
+ if (sync === SyncMode.Sync) {
805
835
  logger.warn('SqliteRemote not suppouted sync mode');
806
836
  return [];
807
837
  }
@@ -809,7 +839,7 @@ class SqliteRemoteConnection {
809
839
  if (globalThis[_GlobalSqlOption].log === 'trace') {
810
840
  logger.trace(sqlstring_1.default.format(sql, params));
811
841
  }
812
- return new Promise(async (resolve) => {
842
+ return new Promise(async (resolve, reject) => {
813
843
  try {
814
844
  const r = await this[_daoConnection].query(this[_sqliteRemoteName], sql, params);
815
845
  resolve(r);
@@ -820,7 +850,7 @@ class SqliteRemoteConnection {
820
850
  sql: ${sql},
821
851
  params: ${params}
822
852
  `);
823
- throw error;
853
+ reject(error);
824
854
  }
825
855
  });
826
856
  }
@@ -834,7 +864,7 @@ class SqliteRemote {
834
864
  this[_sqliteRemoteName] = name;
835
865
  }
836
866
  createConnection(sync) {
837
- if (sync === SqlSyncMode.Sync) {
867
+ if (sync === SyncMode.Sync) {
838
868
  logger.error('SQLITEREMOTE not suppouted sync mode');
839
869
  return null;
840
870
  }
@@ -848,7 +878,7 @@ class SqliteRemote {
848
878
  return null;
849
879
  }
850
880
  close(sync) {
851
- if (sync === SqlSyncMode.Async) {
881
+ if (sync === SyncMode.Async) {
852
882
  return new Promise(async () => {
853
883
  await this[_daoConnection].close();
854
884
  });
@@ -856,7 +886,7 @@ class SqliteRemote {
856
886
  ;
857
887
  }
858
888
  backup(sync, name) {
859
- if (sync === SqlSyncMode.Async) {
889
+ if (sync === SyncMode.Async) {
860
890
  return new Promise(async () => {
861
891
  await this[_daoConnection].backup(this[_sqliteRemoteName], name);
862
892
  });
@@ -864,7 +894,7 @@ class SqliteRemote {
864
894
  ;
865
895
  }
866
896
  remove(sync) {
867
- if (sync === SqlSyncMode.Async) {
897
+ if (sync === SyncMode.Async) {
868
898
  return new Promise(async () => {
869
899
  await this[_daoConnection].remove();
870
900
  });
@@ -872,7 +902,7 @@ class SqliteRemote {
872
902
  ;
873
903
  }
874
904
  restore(sync, name) {
875
- if (sync === SqlSyncMode.Async) {
905
+ if (sync === SyncMode.Async) {
876
906
  return new Promise(async () => {
877
907
  await this[_daoConnection].restore(this[_sqliteRemoteName], name);
878
908
  });
@@ -880,34 +910,301 @@ class SqliteRemote {
880
910
  ;
881
911
  }
882
912
  }
913
+ class Build {
914
+ /**
915
+ *
916
+ * @param count 是否是count查询
917
+ * @param isSum 是否是sum查询
918
+ * @param param
919
+ */
920
+ constructor(isCount, isSum, param = {}) {
921
+ this.brage = { haveOrderBy: false, haveLimit: false };
922
+ this.isCount = isCount;
923
+ this.isSum = isSum;
924
+ Object.assign(this, param);
925
+ }
926
+ /**
927
+ *
928
+ * 当分页时将函数内包含的内容替换为COUNT(1)
929
+ * @returns
930
+ * @memberof Build
931
+ */
932
+ pageTag() {
933
+ return (text, render) => {
934
+ if (this.isCount === true) {
935
+ return Build.page;
936
+ }
937
+ else if (this.isSum !== true) {
938
+ return render(text);
939
+ }
940
+ };
941
+ }
942
+ /**
943
+ *
944
+ * 汇总查询专用
945
+ * @returns
946
+ * @memberof Build
947
+ */
948
+ sumTag() {
949
+ return (text, render) => {
950
+ if (this.isSum !== true) {
951
+ return '';
952
+ }
953
+ else {
954
+ return render(text);
955
+ }
956
+ };
957
+ }
958
+ /**
959
+ *
960
+ * 当分页时、汇总时忽略函数内包含的内容
961
+ * @returns
962
+ * @memberof Build
963
+ */
964
+ pageIgnoreTag() {
965
+ return (text, render) => {
966
+ if (this.isCount === true || this.isSum === true) {
967
+ return '';
968
+ }
969
+ else {
970
+ return render(text);
971
+ }
972
+ };
973
+ }
974
+ /**
975
+ *
976
+ * 将查询条件包起来,如果条件内容不为空,则自动添加WHERE,同时将第一个条件的and、or替换为空
977
+ * 例如:
978
+ * {{#whereTag}}
979
+ * and name = 1
980
+ * and page = 2
981
+ * {{/whereTag}}
982
+ * 输出
983
+ * where name = 1 and page = 2
984
+ * @returns
985
+ * @memberof Build
986
+ */
987
+ where() {
988
+ return (text, render) => {
989
+ let data = render(text);
990
+ data = data.trim();
991
+ if (data) {
992
+ data = data.replace(/and|or/i, '');
993
+ return ` WHERE ${data} `;
994
+ }
995
+ else {
996
+ return '';
997
+ }
998
+ };
999
+ }
1000
+ /**
1001
+ * 删除第一个and、or
1002
+ * 删除最后一个,
1003
+ * 删除最后一个;
1004
+ * @memberof Build
1005
+ */
1006
+ trim() {
1007
+ return (text, render) => {
1008
+ let data = render(text);
1009
+ data = data.trim();
1010
+ if (data) {
1011
+ data = data.replace(/(^and\s)|(^or\s)|(,$)|(;$)/i, '');
1012
+ return data;
1013
+ }
1014
+ else {
1015
+ return '';
1016
+ }
1017
+ };
1018
+ }
1019
+ /**
1020
+ * 分页时将排序部分代码用此函数包起来,可以自动拼接order by
1021
+ * 查询条数时,自动忽略此部分
1022
+ * etc
1023
+ * {{#orderTag}} name desc, age asc {{/orderTag}}
1024
+ * ===
1025
+ * ORDER BY name desc, age asc
1026
+ * @returns
1027
+ * @memberof Build
1028
+ */
1029
+ orderTag() {
1030
+ return (text, render) => {
1031
+ if (this.isCount === true || this.isSum === true) {
1032
+ return '';
1033
+ }
1034
+ else {
1035
+ this.brage.haveOrderBy = true;
1036
+ const orderBy = new Array();
1037
+ const renderOrder = render(text);
1038
+ if (/\S/.test(renderOrder)) {
1039
+ orderBy.push(renderOrder);
1040
+ }
1041
+ return orderBy.length > 0 ? ` ORDER BY ${orderBy.join(',')} ` : '';
1042
+ }
1043
+ };
1044
+ }
1045
+ limitTag() {
1046
+ return (text, render) => {
1047
+ if (this.isCount === true || this.isSum === true) {
1048
+ return '';
1049
+ }
1050
+ else {
1051
+ this.brage.haveOrderBy = true;
1052
+ const orderBy = new Array();
1053
+ const renderOrder = render(text);
1054
+ if (/\S/.test(renderOrder)) {
1055
+ orderBy.push(renderOrder);
1056
+ }
1057
+ return orderBy.length > 0 ? ` ORDER BY ${orderBy.join(',')} ` : '';
1058
+ }
1059
+ };
1060
+ }
1061
+ /**
1062
+ *
1063
+ * 分页时将分组部分代码用此函数包起来,可以自动拼接GROUP BY
1064
+ * 当分页时、汇总时,自动忽略此部分
1065
+ * etc
1066
+ * {{#groupTag}} name, age {{/groupTag}}
1067
+ * ===
1068
+ * group by name.age
1069
+ * @returns
1070
+ * @memberof Build
1071
+ */
1072
+ groupTag() {
1073
+ return (text, render) => {
1074
+ if (this.isCount === true || this.isSum === true) {
1075
+ return '';
1076
+ }
1077
+ else {
1078
+ const groupBy = render(text) || '';
1079
+ return /\S/.test(groupBy) ? ` GROUP BY ${groupBy} ` : '';
1080
+ }
1081
+ };
1082
+ }
1083
+ /**
1084
+ *
1085
+ * beetween and
1086
+ * etc.
1087
+ * {{#between}} AND t.createtime | ({{createtime}}) {{/between}}
1088
+ * createtime: 1,2
1089
+ * ===
1090
+ * AND t.createtime BETWEEN 1 AND 2
1091
+ * @returns
1092
+ * @memberof Build
1093
+ */
1094
+ between() {
1095
+ return (text, render) => {
1096
+ const result = render(text);
1097
+ if (/\(([\w\W]+)\)/.exec(result)) {
1098
+ return render(text).replace(/\(([\w\W]+)\)/, (a, b) => {
1099
+ if (a && b) {
1100
+ const xx = b.split(',');
1101
+ return `'${xx[0]}' AND '${xx[1]}'`;
1102
+ }
1103
+ else {
1104
+ return '';
1105
+ }
1106
+ }).replace(/\|/, ' BETWEEN ');
1107
+ }
1108
+ else {
1109
+ return '';
1110
+ }
1111
+ };
1112
+ }
1113
+ /**
1114
+ *
1115
+ * 距离计算,单位米
1116
+ * etc
1117
+ * {{#distanceTag}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distanceTag}}
1118
+ * ===
1119
+ * ROUND(ST_DISTANCE(POINT(longitude1, latitude1), POINT({{longitude}}, {{latitude}}))*111195, 2)
1120
+ * 可根据需求自行将数据转换为千米,例如
1121
+ * {{#distanceTag}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distanceTag}} / 1000
1122
+ * @returns
1123
+ * @memberof Build
1124
+ */
1125
+ distanceTag() {
1126
+ return (text, render) => {
1127
+ const result = render(text);
1128
+ if (/\(([^()]+)\)/.exec(result)) {
1129
+ let index = 0;
1130
+ return render(text).replace(/\(([^()]+)\)/g, (a, b) => {
1131
+ if (a && b) {
1132
+ const xx = b.split(',');
1133
+ if (index === 0) {
1134
+ index++;
1135
+ return ` ROUND(ST_DISTANCE(POINT(${xx[0]}, ${xx[1]}) `;
1136
+ }
1137
+ else {
1138
+ return ` POINT(${xx[0]}, ${xx[1]}))*111195, 2)`;
1139
+ }
1140
+ }
1141
+ else {
1142
+ return '';
1143
+ }
1144
+ });
1145
+ }
1146
+ else {
1147
+ return '';
1148
+ }
1149
+ };
1150
+ }
1151
+ }
1152
+ Build.page = 'COUNT(1) zccw1986 ';
883
1153
  class SqlCache {
884
1154
  constructor() {
885
- this.cache = {};
1155
+ this.sqlMap = {};
1156
+ this.sqlFNMap = {};
886
1157
  }
887
1158
  async init(options) {
1159
+ if (options.sqlMap) {
1160
+ this.sqlMap = options.sqlMap;
1161
+ }
888
1162
  if (options.sqlDir) {
889
1163
  const sqlFis = globalThis[_fs].readdirSync(options.sqlDir);
890
1164
  for (const modeName of sqlFis) {
891
- const name = globalThis[_path].basename(modeName, globalThis[_path].extname(modeName));
892
- const obj = await Promise.resolve(`${globalThis[_path].join(options.sqlDir, modeName)}`).then(s => __importStar(require(s)));
893
- for (const [key, fn] of Object.entries(obj)) {
894
- this.cache[`${name}.${String(key)}`] = fn;
1165
+ const extname = globalThis[_path].extname(modeName);
1166
+ const name = globalThis[_path].basename(modeName, extname);
1167
+ const file = globalThis[_path].join(options.sqlDir, modeName);
1168
+ if (extname === 'mu') {
1169
+ const parser = new MUParser(name, globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString());
1170
+ let source = parser.next();
1171
+ while (source != null) {
1172
+ this.sqlMap[source[0]] = source[1];
1173
+ logger.debug(`sql: ${source[0]} found!`);
1174
+ source = parser.next();
1175
+ }
1176
+ }
1177
+ else if (extname === '.js') {
1178
+ const obj = (await Promise.resolve(`${globalThis[_path].join(options.sqlDir, modeName)}`).then(s => __importStar(require(s)))).default;
1179
+ for (const [key, fn] of Object.entries(obj)) {
1180
+ this.sqlMap[`${name}.${String(key)}`] = fn;
1181
+ }
895
1182
  }
896
1183
  }
897
1184
  }
898
- else if (options.sqlCache) {
899
- this.cache = options.sqlCache;
1185
+ if (options.sqlFNMap) {
1186
+ this.sqlFNMap = options.sqlFNMap;
1187
+ }
1188
+ if (options.sqlFNDir) {
1189
+ const sqlFis = globalThis[_fs].readdirSync(options.sqlDir);
1190
+ for (const modeName of sqlFis) {
1191
+ const extname = globalThis[_path].extname(modeName);
1192
+ const name = globalThis[_path].basename(modeName, extname);
1193
+ const file = globalThis[_path].join(options.sqlDir, modeName);
1194
+ if (extname === 'mu') {
1195
+ this.sqlFNMap[name] = globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString();
1196
+ }
1197
+ }
900
1198
  }
901
1199
  }
902
- load(sqlid, params, context, isPage) {
903
- const sqlSource = this.cache[sqlid];
1200
+ load(sqlid, options) {
1201
+ const sqlSource = this.sqlMap[sqlid];
904
1202
  error_1.Throw.if(!sqlSource, `指定的语句${sqlid}不存在!`);
905
- if (typeof sqlSource === 'string') {
906
- return sqlSource;
907
- }
908
- else {
909
- return sqlSource(params, context, isPage);
910
- }
1203
+ const _sql = typeof sqlSource === 'function' ? sqlSource(options) : sqlSource;
1204
+ const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1205
+ const sql = mustache_1.default.render(_sql, buildParam, this.sqlFNMap);
1206
+ logger.debug(sqlid, sql);
1207
+ return sql;
911
1208
  }
912
1209
  }
913
1210
  // #endregion
@@ -934,17 +1231,17 @@ function P(skipConn = false) {
934
1231
  const startTime = +new Date();
935
1232
  // option
936
1233
  const option = args[0] = Object.assign({}, globalThis[_GlobalSqlOption], this[_SqlOption], args[0]);
937
- option.sync ?? (option.sync = SqlSyncMode.Async);
1234
+ option.sync ?? (option.sync = SyncMode.Async);
938
1235
  const dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
939
1236
  option.dao = globalThis[_dao][this[_dbType]][dbName];
940
1237
  error_1.Throw.if(!option.dao, `not found db:${String(dbName)}(${this[_dbType]})`);
941
1238
  option.tableName = option?.tableName ?? this[_tableName];
942
1239
  const tableES = sqlstring_1.default.escapeId(option.tableName);
943
1240
  if (this[_dbType] === DBType.Sqlite) {
944
- error_1.Throw.if(option.sync === SqlSyncMode.Async, 'sqlite can not Async!');
1241
+ error_1.Throw.if(option.sync === SyncMode.Async, 'sqlite can not Async!');
945
1242
  // 连接共享
946
1243
  if (skipConn === false && !option.conn) {
947
- option.conn = option.dao.createConnection(SqlSyncMode.Sync);
1244
+ option.conn = option.dao.createConnection(SyncMode.Sync);
948
1245
  }
949
1246
  else {
950
1247
  needRealseConn = false;
@@ -952,20 +1249,20 @@ function P(skipConn = false) {
952
1249
  if (skipConn === false) {
953
1250
  const lastVersion = this[_sqlite_version] ?? '0.0.1';
954
1251
  // 检查表
955
- const tableCheckResult = option.conn.pluck(SqlSyncMode.Sync, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
1252
+ const tableCheckResult = option.conn.pluck(SyncMode.Sync, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
956
1253
  if (tableCheckResult) {
957
1254
  // 旧版本
958
- const tableVersion = option.conn.pluck(SqlSyncMode.Sync, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
1255
+ const tableVersion = option.conn.pluck(SyncMode.Sync, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
959
1256
  if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
960
1257
  // 更新版本
961
- const columns = (0, iterare_1.default)(option.conn.query(SqlSyncMode.Sync, `PRAGMA table_info(${tableES})`))
1258
+ const columns = (0, iterare_1.default)(option.conn.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
962
1259
  .filter(c => this[_fields].hasOwnProperty(c.name))
963
1260
  .map(c => sqlstring_1.default.escapeId(c.name))
964
1261
  .join(',');
965
1262
  const rtable = sqlstring_1.default.escapeId(`${option.tableName}_${tableVersion.replace(/\./, '_')}`);
966
- option.conn.execute(SqlSyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
967
- option.conn.execute(SqlSyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
968
- option.conn.execute(SqlSyncMode.Sync, `
1263
+ option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
1264
+ option.conn.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1265
+ option.conn.execute(SyncMode.Sync, `
969
1266
  CREATE TABLE IF NOT EXISTS ${tableES}(
970
1267
  ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
971
1268
  ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
@@ -973,22 +1270,22 @@ function P(skipConn = false) {
973
1270
  `);
974
1271
  if (this[_index] && this[_index].length) {
975
1272
  for (const index of this[_index]) {
976
- option.conn.execute(SqlSyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1273
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
977
1274
  }
978
1275
  }
979
- option.conn.execute(SqlSyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
980
- option.conn.execute(SqlSyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
981
- option.conn.execute(SqlSyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
1276
+ option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1277
+ option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1278
+ option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
982
1279
  // 更新完毕,保存版本号
983
- option.conn.execute(SqlSyncMode.Sync, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
1280
+ option.conn.execute(SyncMode.Sync, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
984
1281
  }
985
1282
  else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
986
- option.conn.execute(SqlSyncMode.Sync, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1283
+ option.conn.execute(SyncMode.Sync, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
987
1284
  }
988
1285
  }
989
1286
  else { // 表不存在
990
1287
  // 创建表
991
- option.conn.execute(SqlSyncMode.Sync, `
1288
+ option.conn.execute(SyncMode.Sync, `
992
1289
  CREATE TABLE IF NOT EXISTS ${tableES} (
993
1290
  ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
994
1291
  ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
@@ -997,10 +1294,10 @@ function P(skipConn = false) {
997
1294
  `);
998
1295
  if (this[_index] && this[_index].length) {
999
1296
  for (const index of this[_index]) {
1000
- option.conn.execute(SqlSyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1297
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1001
1298
  }
1002
1299
  }
1003
- option.conn.execute(SqlSyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1300
+ option.conn.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1004
1301
  }
1005
1302
  }
1006
1303
  try {
@@ -1019,7 +1316,7 @@ function P(skipConn = false) {
1019
1316
  finally {
1020
1317
  if (needRealseConn && option && option.conn) {
1021
1318
  try {
1022
- option.conn.realse(SqlSyncMode.Sync);
1319
+ option.conn.realse(SyncMode.Sync);
1023
1320
  }
1024
1321
  catch (error) {
1025
1322
  }
@@ -1027,11 +1324,11 @@ function P(skipConn = false) {
1027
1324
  }
1028
1325
  }
1029
1326
  else if (this[_dbType] === DBType.SqliteRemote) {
1030
- error_1.Throw.if(option.sync === SqlSyncMode.Sync, 'SqliteRemote remote can not sync!');
1031
- return new Promise(async (resolve) => {
1327
+ error_1.Throw.if(option.sync === SyncMode.Sync, 'SqliteRemote remote can not sync!');
1328
+ return new Promise(async (resolve, reject) => {
1032
1329
  // 连接共享
1033
1330
  if (skipConn === false && !option.conn) {
1034
- (option).conn = await option.dao.createConnection(SqlSyncMode.Async);
1331
+ (option).conn = await option.dao.createConnection(SyncMode.Async);
1035
1332
  }
1036
1333
  else {
1037
1334
  needRealseConn = false;
@@ -1039,20 +1336,20 @@ function P(skipConn = false) {
1039
1336
  if (skipConn === false) {
1040
1337
  const lastVersion = this[_sqlite_version] ?? '0.0.1';
1041
1338
  // 检查表
1042
- const tableCheckResult = await option.conn.pluck(SqlSyncMode.Async, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
1339
+ const tableCheckResult = await option.conn.pluck(SyncMode.Async, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
1043
1340
  if (tableCheckResult) {
1044
1341
  // 旧版本
1045
- const tableVersion = await option.conn.pluck(SqlSyncMode.Async, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
1342
+ const tableVersion = await option.conn.pluck(SyncMode.Async, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
1046
1343
  if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1047
1344
  // 更新版本
1048
- const columns = (0, iterare_1.default)(await option.conn.query(SqlSyncMode.Async, `PRAGMA table_info(${tableES})`))
1345
+ const columns = (0, iterare_1.default)(await option.conn.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
1049
1346
  .filter(c => this[_fields].hasOwnProperty(c.name))
1050
1347
  .map(c => sqlstring_1.default.escapeId(c.name))
1051
1348
  .join(',');
1052
1349
  const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
1053
- await option.conn.execute(SqlSyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
1054
- await option.conn.execute(SqlSyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1055
- await option.conn.execute(SqlSyncMode.Async, `
1350
+ await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
1351
+ await option.conn.execute(SyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1352
+ await option.conn.execute(SyncMode.Async, `
1056
1353
  CREATE TABLE IF NOT EXISTS ${tableES}(
1057
1354
  ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
1058
1355
  ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
@@ -1060,22 +1357,22 @@ function P(skipConn = false) {
1060
1357
  `);
1061
1358
  if (this[_index] && this[_index].length) {
1062
1359
  for (const index of this[_index]) {
1063
- await option.conn.execute(SqlSyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1360
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1064
1361
  }
1065
1362
  }
1066
- await option.conn.execute(SqlSyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1067
- await option.conn.execute(SqlSyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1068
- await option.conn.execute(SqlSyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
1363
+ await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1364
+ await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
1365
+ await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
1069
1366
  // 更新完毕,保存版本号
1070
- await option.conn.execute(SqlSyncMode.Async, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
1367
+ await option.conn.execute(SyncMode.Async, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
1071
1368
  }
1072
1369
  else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
1073
- await option.conn.execute(SqlSyncMode.Async, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1370
+ await option.conn.execute(SyncMode.Async, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1074
1371
  }
1075
1372
  }
1076
1373
  else { // 表不存在
1077
1374
  // 创建表
1078
- await option.conn.execute(SqlSyncMode.Async, `
1375
+ await option.conn.execute(SyncMode.Async, `
1079
1376
  CREATE TABLE IF NOT EXISTS ${tableES}(
1080
1377
  ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
1081
1378
  ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
@@ -1083,10 +1380,10 @@ function P(skipConn = false) {
1083
1380
  `);
1084
1381
  if (this[_index] && this[_index].length) {
1085
1382
  for (const index of this[_index]) {
1086
- await option.conn.execute(SqlSyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${sqlstring_1.default.escapeId(option.tableName)} ("${index}");`);
1383
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${sqlstring_1.default.escapeId(option.tableName)} ("${index}");`);
1087
1384
  }
1088
1385
  }
1089
- await option.conn.execute(SqlSyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1386
+ await option.conn.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
1090
1387
  }
1091
1388
  }
1092
1389
  try {
@@ -1096,12 +1393,12 @@ function P(skipConn = false) {
1096
1393
  }
1097
1394
  catch (error) {
1098
1395
  console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
1099
- throw error;
1396
+ reject(error);
1100
1397
  }
1101
1398
  finally {
1102
1399
  if (needRealseConn && option && option.conn) {
1103
1400
  try {
1104
- option.conn.realse(SqlSyncMode.Sync);
1401
+ option.conn.realse(SyncMode.Sync);
1105
1402
  }
1106
1403
  catch (error) {
1107
1404
  }
@@ -1110,11 +1407,11 @@ function P(skipConn = false) {
1110
1407
  });
1111
1408
  }
1112
1409
  else if (this[_dbType] === DBType.Mysql) {
1113
- return new Promise(async (resolve) => {
1410
+ return new Promise(async (resolve, reject) => {
1114
1411
  try {
1115
1412
  // 连接共享
1116
1413
  if (skipConn === false && !option.conn) {
1117
- (option).conn = await option.dao.createConnection(SqlSyncMode.Async);
1414
+ (option).conn = await option.dao.createConnection(SyncMode.Async);
1118
1415
  }
1119
1416
  else {
1120
1417
  needRealseConn = false;
@@ -1125,12 +1422,12 @@ function P(skipConn = false) {
1125
1422
  }
1126
1423
  catch (error) {
1127
1424
  console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
1128
- throw error;
1425
+ reject(error);
1129
1426
  }
1130
1427
  finally {
1131
1428
  if (needRealseConn && option && option.conn) {
1132
1429
  try {
1133
- option.conn.realse(SqlSyncMode.Sync);
1430
+ option.conn.realse(SyncMode.Sync);
1134
1431
  }
1135
1432
  catch (error) {
1136
1433
  }
@@ -1179,19 +1476,19 @@ const Field = (config) => {
1179
1476
  field.esName = sqlstring_1.default.escapeId(propertyName);
1180
1477
  const hasDef = field.hasOwnProperty('def') === true;
1181
1478
  switch (field.type) {
1182
- case SqlType.bigint: {
1183
- field[DBType.Mysql] = `${field.esName} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1479
+ case SqlType.tinyint: {
1480
+ field[DBType.Mysql] = `${field.esName} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1184
1481
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1185
1482
  break;
1186
1483
  }
1187
- case SqlType.char: {
1188
- field[DBType.Mysql] = `${field.esName} char(${config.length1 ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1189
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1484
+ case SqlType.smallint: {
1485
+ field[DBType.Mysql] = `${field.esName} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1486
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1190
1487
  break;
1191
1488
  }
1192
- case SqlType.decimal: {
1193
- field[DBType.Mysql] = `${field.esName} decimal(${config.length1 ?? 1}, ${config.length2 ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1194
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1489
+ case SqlType.mediumint: {
1490
+ field[DBType.Mysql] = `${field.esName} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1491
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1195
1492
  break;
1196
1493
  }
1197
1494
  case SqlType.int: {
@@ -1199,6 +1496,26 @@ const Field = (config) => {
1199
1496
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1200
1497
  break;
1201
1498
  }
1499
+ case SqlType.bigint: {
1500
+ field[DBType.Mysql] = `${field.esName} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1501
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1502
+ break;
1503
+ }
1504
+ case SqlType.float: {
1505
+ field[DBType.Mysql] = `${field.esName} float(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1506
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1507
+ break;
1508
+ }
1509
+ case SqlType.double: {
1510
+ field[DBType.Mysql] = `${field.esName} double(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1511
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1512
+ break;
1513
+ }
1514
+ case SqlType.decimal: {
1515
+ field[DBType.Mysql] = `${field.esName} decimal(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1516
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1517
+ break;
1518
+ }
1202
1519
  case SqlType.longtext: {
1203
1520
  field[DBType.Mysql] = `${field.esName} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1204
1521
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
@@ -1209,8 +1526,58 @@ const Field = (config) => {
1209
1526
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1210
1527
  break;
1211
1528
  }
1212
- case SqlType.smallint: {
1213
- field[DBType.Mysql] = `${field.esName} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1529
+ case SqlType.text: {
1530
+ field[DBType.Mysql] = `${field.esName} text ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1531
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1532
+ break;
1533
+ }
1534
+ case SqlType.date: {
1535
+ field[DBType.Mysql] = `${field.esName} date ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1536
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1537
+ break;
1538
+ }
1539
+ case SqlType.time: {
1540
+ field[DBType.Mysql] = `${field.esName} time ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1541
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1542
+ break;
1543
+ }
1544
+ case SqlType.year: {
1545
+ field[DBType.Mysql] = `${field.esName} year ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1546
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1547
+ break;
1548
+ }
1549
+ case SqlType.datetime: {
1550
+ field[DBType.Mysql] = `${field.esName} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1551
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1552
+ break;
1553
+ }
1554
+ case SqlType.timestamp: {
1555
+ field[DBType.Mysql] = `${field.esName} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1556
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1557
+ break;
1558
+ }
1559
+ case SqlType.char: {
1560
+ field[DBType.Mysql] = `${field.esName} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1561
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1562
+ break;
1563
+ }
1564
+ case SqlType.varchar: {
1565
+ field[DBType.Mysql] = `${field.esName} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1566
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1567
+ break;
1568
+ }
1569
+ case SqlType.tinyblob: {
1570
+ field[DBType.Mysql] = `${field.esName} tinyblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1571
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1572
+ break;
1573
+ }
1574
+ case SqlType.tinytext: {
1575
+ field[DBType.Mysql] = `${field.esName} tinytext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1576
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1577
+ break;
1578
+ }
1579
+ case SqlType.blob: {
1580
+ field[DBType.Mysql] = `${field.esName} binary ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1214
1581
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1215
1582
  break;
1216
1583
  }
@@ -1219,13 +1586,78 @@ const Field = (config) => {
1219
1586
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1220
1587
  break;
1221
1588
  }
1222
- case SqlType.tinyint: {
1223
- field[DBType.Mysql] = `${field.esName} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1589
+ case SqlType.mediumblob: {
1590
+ field[DBType.Mysql] = `${field.esName} mediumblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1224
1591
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1225
1592
  break;
1226
1593
  }
1227
- case SqlType.varchar: {
1228
- field[DBType.Mysql] = `${field.esName} varchar(${config.length1 ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1594
+ case SqlType.mediumtext: {
1595
+ field[DBType.Mysql] = `${field.esName} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1596
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1597
+ break;
1598
+ }
1599
+ case SqlType.longblob: {
1600
+ field[DBType.Mysql] = `${field.esName} longblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1601
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1602
+ break;
1603
+ }
1604
+ case SqlType.longtext: {
1605
+ field[DBType.Mysql] = `${field.esName} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1606
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1607
+ break;
1608
+ }
1609
+ case SqlType.set: {
1610
+ field[DBType.Mysql] = `${field.esName} set ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1611
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1612
+ break;
1613
+ }
1614
+ case SqlType.enum: {
1615
+ field[DBType.Mysql] = `${field.esName} enum ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1616
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1617
+ break;
1618
+ }
1619
+ case SqlType.json: {
1620
+ field[DBType.Mysql] = `${field.esName} json ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1621
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1622
+ break;
1623
+ }
1624
+ case SqlType.geometry: {
1625
+ field[DBType.Mysql] = `${field.esName} geometry ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1626
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1627
+ break;
1628
+ }
1629
+ case SqlType.point: {
1630
+ field[DBType.Mysql] = `${field.esName} point ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1631
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1632
+ break;
1633
+ }
1634
+ case SqlType.linestring: {
1635
+ field[DBType.Mysql] = `${field.esName} linestring ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1636
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1637
+ break;
1638
+ }
1639
+ case SqlType.polygon: {
1640
+ field[DBType.Mysql] = `${field.esName} polygon ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1641
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1642
+ break;
1643
+ }
1644
+ case SqlType.multipoint: {
1645
+ field[DBType.Mysql] = `${field.esName} multipoint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1646
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1647
+ break;
1648
+ }
1649
+ case SqlType.multilinestring: {
1650
+ field[DBType.Mysql] = `${field.esName} multilinestring ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1651
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1652
+ break;
1653
+ }
1654
+ case SqlType.multipolygon: {
1655
+ field[DBType.Mysql] = `${field.esName} multipolygon ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1656
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1657
+ break;
1658
+ }
1659
+ case SqlType.geometrycollection: {
1660
+ field[DBType.Mysql] = `${field.esName} geometrycollection ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1229
1661
  field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1230
1662
  break;
1231
1663
  }
@@ -1385,7 +1817,7 @@ class SqlService {
1385
1817
  const sqls = [];
1386
1818
  const tableName = sqlstring_1.default.escapeId(option.tableName);
1387
1819
  switch (option?.mode) {
1388
- case SqlInsertMode.InsertIfNotExists: {
1820
+ case InsertMode.InsertIfNotExists: {
1389
1821
  const conditions = option.existConditionOtherThanIds || this[_ids];
1390
1822
  error_1.Throw.if(!conditions, 'not found where condition for insertIfNotExists!');
1391
1823
  error_1.Throw.if(conditions.length === 0, 'insertIfNotExists must have not null where!');
@@ -1424,7 +1856,7 @@ class SqlService {
1424
1856
  ${selects};`;
1425
1857
  sqls.push({ sql, params });
1426
1858
  }
1427
- case SqlInsertMode.Replace: {
1859
+ case InsertMode.Replace: {
1428
1860
  const finalColumns = new Set();
1429
1861
  const params = datas
1430
1862
  .map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
@@ -1452,7 +1884,7 @@ class SqlService {
1452
1884
  `;
1453
1885
  sqls.push({ sql, params });
1454
1886
  }
1455
- case SqlInsertMode.Insert: {
1887
+ case InsertMode.Insert: {
1456
1888
  const finalColumns = new Set();
1457
1889
  const params = datas
1458
1890
  .map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
@@ -1480,7 +1912,7 @@ class SqlService {
1480
1912
  `;
1481
1913
  sqls.push({ sql, params });
1482
1914
  }
1483
- case SqlInsertMode.InsertWithTempTable: {
1915
+ case InsertMode.InsertWithTempTable: {
1484
1916
  const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
1485
1917
  const tableTempESC = sqlstring_1.default.escapeId(tableTemp);
1486
1918
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
@@ -1523,16 +1955,16 @@ class SqlService {
1523
1955
  return sqls;
1524
1956
  }
1525
1957
  insert(option) {
1526
- option.mode ?? (option.mode = SqlInsertMode.Insert);
1958
+ option.mode ?? (option.mode = InsertMode.Insert);
1527
1959
  const isArray = option.data instanceof Array;
1528
1960
  const datas = option.data instanceof Array ? option.data : [option.data];
1529
- if (option.sync === SqlSyncMode.Sync) {
1961
+ if (option.sync === SyncMode.Sync) {
1530
1962
  const fn = () => {
1531
1963
  const result = (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.SyncTrust, datas, _data => {
1532
1964
  const sqls = this._insert(_data, option);
1533
1965
  let result = 0n;
1534
1966
  for (const { sql, params } of sqls) {
1535
- const dd = option.conn.execute(SqlSyncMode.Sync, sql, params);
1967
+ const dd = option.conn.execute(SyncMode.Sync, sql, params);
1536
1968
  if (dd.insertId) {
1537
1969
  result += dd.insertId;
1538
1970
  }
@@ -1548,17 +1980,17 @@ class SqlService {
1548
1980
  return fn();
1549
1981
  }
1550
1982
  else {
1551
- return option?.dao?.transaction(SqlSyncMode.Sync, fn, option?.conn);
1983
+ return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn);
1552
1984
  }
1553
1985
  }
1554
1986
  else if (isArray) {
1555
1987
  const fn = async () => {
1556
- return await option?.dao?.transaction(SqlSyncMode.Async, async () => {
1988
+ return await option?.dao?.transaction(SyncMode.Async, async () => {
1557
1989
  const result = await (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
1558
1990
  const sqls = this._insert(_data, option);
1559
1991
  let result = 0n;
1560
1992
  for (const { sql, params } of sqls) {
1561
- const dd = await option?.conn.execute(SqlSyncMode.Async, sql, params);
1993
+ const dd = await option?.conn.execute(SyncMode.Async, sql, params);
1562
1994
  if (dd.insertId) {
1563
1995
  result += dd.insertId;
1564
1996
  }
@@ -1573,7 +2005,7 @@ class SqlService {
1573
2005
  resolve((await fn()));
1574
2006
  }
1575
2007
  else {
1576
- await option?.dao?.transaction(SqlSyncMode.Async, async () => resolve((await fn())), option?.conn);
2008
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
1577
2009
  }
1578
2010
  });
1579
2011
  }
@@ -1583,7 +2015,7 @@ class SqlService {
1583
2015
  const sqls = this._insert(_data, option);
1584
2016
  let result = 0n;
1585
2017
  for (const { sql, params } of sqls) {
1586
- const dd = await option.conn.execute(SqlSyncMode.Async, sql, params);
2018
+ const dd = await option.conn.execute(SyncMode.Async, sql, params);
1587
2019
  if (dd.insertId) {
1588
2020
  result += dd.insertId;
1589
2021
  }
@@ -1597,7 +2029,7 @@ class SqlService {
1597
2029
  resolve((await fn()));
1598
2030
  }
1599
2031
  else {
1600
- await option?.dao?.transaction(SqlSyncMode.Async, async () => resolve((await fn())), option?.conn);
2032
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
1601
2033
  }
1602
2034
  });
1603
2035
  }
@@ -1638,13 +2070,13 @@ class SqlService {
1638
2070
  update(option) {
1639
2071
  error_1.Throw.if(!this[_ids] || this[_ids].length === 0, 'not found id');
1640
2072
  const datas = option.data instanceof Array ? option.data : [option.data];
1641
- if (option.sync === SqlSyncMode.Sync) {
2073
+ if (option.sync === SyncMode.Sync) {
1642
2074
  const fn = () => {
1643
2075
  const result = (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.SyncTrust, datas, _data => {
1644
2076
  const sqls = this._update(_data, option);
1645
2077
  let result = 0;
1646
2078
  for (const { sql, params } of sqls) {
1647
- const dd = option.conn.execute(SqlSyncMode.Sync, sql, params);
2079
+ const dd = option.conn.execute(SyncMode.Sync, sql, params);
1648
2080
  if (dd.affectedRows) {
1649
2081
  result += dd.affectedRows;
1650
2082
  }
@@ -1657,7 +2089,7 @@ class SqlService {
1657
2089
  return fn();
1658
2090
  }
1659
2091
  else {
1660
- return option?.dao?.transaction(SqlSyncMode.Sync, fn, option?.conn);
2092
+ return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn);
1661
2093
  }
1662
2094
  }
1663
2095
  else {
@@ -1666,7 +2098,7 @@ class SqlService {
1666
2098
  const sqls = this._update(_data, option);
1667
2099
  let result = 0;
1668
2100
  for (const { sql, params } of sqls) {
1669
- const dd = await option.conn.execute(SqlSyncMode.Async, sql, params);
2101
+ const dd = await option.conn.execute(SyncMode.Async, sql, params);
1670
2102
  if (dd.affectedRows) {
1671
2103
  result += dd.affectedRows;
1672
2104
  }
@@ -1680,7 +2112,7 @@ class SqlService {
1680
2112
  resolve((await fn()));
1681
2113
  }
1682
2114
  else {
1683
- await option?.dao?.transaction(SqlSyncMode.Async, async () => resolve((await fn())), option?.conn);
2115
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
1684
2116
  }
1685
2117
  });
1686
2118
  }
@@ -1691,7 +2123,7 @@ class SqlService {
1691
2123
  error_1.Throw.if(!option.id && !option.where, 'not found id or where!');
1692
2124
  error_1.Throw.if(!!option.id && !!this[_ids] && this[_ids].length > 1, 'muit id must set where!');
1693
2125
  error_1.Throw.if(!!option.id && !!option.where, 'id and where only one can set!');
1694
- option.mode ?? (option.mode = SqlDelMode.Common);
2126
+ option.mode ?? (option.mode = DeleteMode.Common);
1695
2127
  const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
1696
2128
  const tableTempESC = sqlstring_1.default.escapeId(tableTemp);
1697
2129
  const tableNameESC = sqlstring_1.default.escapeId(option?.tableName);
@@ -1702,7 +2134,7 @@ class SqlService {
1702
2134
  }
1703
2135
  const wheres = option.where instanceof Array ? option.where : [option.where];
1704
2136
  const sqls = [];
1705
- if (option.mode === SqlDelMode.Common) {
2137
+ if (option.mode === DeleteMode.Common) {
1706
2138
  const params = new Array();
1707
2139
  const whereSql = (0, iterare_1.default)(wheres).map(where => {
1708
2140
  return `(
@@ -1759,11 +2191,11 @@ class SqlService {
1759
2191
  }
1760
2192
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
1761
2193
  }
1762
- if (option.sync === SqlSyncMode.Sync) {
2194
+ if (option.sync === SyncMode.Sync) {
1763
2195
  const fn = () => {
1764
2196
  let result = 0;
1765
2197
  for (const { sql, params } of sqls) {
1766
- const dd = option.conn.execute(SqlSyncMode.Sync, sql, params);
2198
+ const dd = option.conn.execute(SyncMode.Sync, sql, params);
1767
2199
  result += dd.affectedRows;
1768
2200
  }
1769
2201
  return result;
@@ -1772,14 +2204,14 @@ class SqlService {
1772
2204
  return fn();
1773
2205
  }
1774
2206
  else {
1775
- return option?.dao?.transaction(SqlSyncMode.Sync, fn, option?.conn);
2207
+ return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn);
1776
2208
  }
1777
2209
  }
1778
2210
  else {
1779
2211
  const fn = async () => {
1780
2212
  let result = 0;
1781
2213
  for (const { sql, params } of sqls) {
1782
- const dd = await option.conn.execute(SqlSyncMode.Async, sql, params);
2214
+ const dd = await option.conn.execute(SyncMode.Async, sql, params);
1783
2215
  result += dd.affectedRows;
1784
2216
  }
1785
2217
  return result;
@@ -1789,25 +2221,25 @@ class SqlService {
1789
2221
  resolve((await fn()));
1790
2222
  }
1791
2223
  else {
1792
- await option?.dao?.transaction(SqlSyncMode.Async, async () => resolve((await fn())), option?.conn);
2224
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
1793
2225
  }
1794
2226
  });
1795
2227
  }
1796
2228
  }
1797
- _select(resultMode, result, error) {
1798
- switch (resultMode) {
1799
- case SqlTemplateMode.AssertOne: {
2229
+ _template(templateResult, result, error) {
2230
+ switch (templateResult) {
2231
+ case TemplateResult.AssertOne: {
1800
2232
  error_1.Throw.if(!result || result.length !== 1, error);
1801
2233
  return result[0];
1802
2234
  }
1803
- case SqlTemplateMode.NotSureOne: {
2235
+ case TemplateResult.NotSureOne: {
1804
2236
  error_1.Throw.if(!result, error);
1805
2237
  return result[0] ?? null;
1806
2238
  }
1807
- case SqlTemplateMode.Many: {
2239
+ case TemplateResult.Many: {
1808
2240
  return result;
1809
2241
  }
1810
- case SqlTemplateMode.Count: {
2242
+ case TemplateResult.Count: {
1811
2243
  return result[0].ct;
1812
2244
  }
1813
2245
  }
@@ -1818,8 +2250,8 @@ class SqlService {
1818
2250
  error_1.Throw.if(!option.id && !option.where, 'not found id or where!');
1819
2251
  error_1.Throw.if(!!option.id && !!this[_ids] && this[_ids].length > 1, 'muit id must set where!');
1820
2252
  error_1.Throw.if(!!option.id && !!option.where, 'id and where only one can set!');
1821
- option.mode ?? (option.mode = SqlSelectMode.Common);
1822
- option.resultMode ?? (option.resultMode = SqlTemplateMode.AssertOne);
2253
+ option.mode ?? (option.mode = SelectMode.Common);
2254
+ option.templateResult ?? (option.templateResult = TemplateResult.AssertOne);
1823
2255
  option.error ?? (option.error = 'error data!');
1824
2256
  const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
1825
2257
  const tableTempESC = sqlstring_1.default.escapeId(tableTemp);
@@ -1829,11 +2261,11 @@ class SqlService {
1829
2261
  const ids = option.id instanceof Array ? option.id : [option.id];
1830
2262
  option.where = ids.map(i => ({ [idName]: i }));
1831
2263
  }
1832
- const columns = option.resultMode === SqlTemplateMode.Count ? 'COUNT(1) ct' : (0, iterare_1.default)((option.columns ?? this[_columns])).map((K) => `a.${this[_fields][K]?.esName}`).join(',');
2264
+ const columns = option.templateResult === TemplateResult.Count ? 'COUNT(1) ct' : (0, iterare_1.default)((option.columns ?? this[_columns])).map((K) => `a.${this[_fields][K]?.esName}`).join(',');
1833
2265
  const wheres = option.where instanceof Array ? option.where : [option.where];
1834
2266
  const sqls = [];
1835
2267
  let resultIndex = -1;
1836
- if (option.mode === SqlSelectMode.Common) {
2268
+ if (option.mode === SelectMode.Common) {
1837
2269
  const params = new Array();
1838
2270
  const whereSql = (0, iterare_1.default)(wheres).map(where => {
1839
2271
  return `SELECT ${columns} FROM ${tableNameESC} a WHERE
@@ -1854,79 +2286,79 @@ class SqlService {
1854
2286
  sqls.push({ sql: `SELECT ${columns} FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.esName} = b.${this[_fields][K]?.esName}`).join(' AND ')};` });
1855
2287
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
1856
2288
  }
1857
- if (option.sync === SqlSyncMode.Sync) {
2289
+ if (option.sync === SyncMode.Sync) {
1858
2290
  let result;
1859
2291
  for (let i = 0; i < sqls.length; i++) {
1860
2292
  if (i === resultIndex) {
1861
- result = option.conn.query(SqlSyncMode.Sync, sqls[i]?.sql, sqls[i]?.params);
2293
+ result = option.conn.query(SyncMode.Sync, sqls[i]?.sql, sqls[i]?.params);
1862
2294
  }
1863
2295
  else {
1864
- option.conn.execute(SqlSyncMode.Sync, sqls[i]?.sql, sqls[i]?.params);
2296
+ option.conn.execute(SyncMode.Sync, sqls[i]?.sql, sqls[i]?.params);
1865
2297
  }
1866
2298
  }
1867
- return this._select(option.resultMode, result, option.error);
2299
+ return this._template(option.templateResult, result, option.error);
1868
2300
  }
1869
2301
  else {
1870
2302
  return new Promise(async (resolve) => {
1871
2303
  let result;
1872
2304
  for (let i = 0; i < sqls.length; i++) {
1873
2305
  if (i === resultIndex) {
1874
- result = await option.conn.query(SqlSyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2306
+ result = await option.conn.query(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
1875
2307
  }
1876
2308
  else {
1877
- await option.conn.execute(SqlSyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2309
+ await option.conn.execute(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
1878
2310
  }
1879
2311
  }
1880
- resolve(this._select(option.resultMode, result, option.error));
2312
+ resolve(this._template(option.templateResult, result, option.error));
1881
2313
  });
1882
2314
  }
1883
2315
  }
1884
- _query(resultMode, result, def, errorMsg, multiple) {
2316
+ _select(templateResult, result, def, errorMsg, multiple) {
1885
2317
  if (multiple === true) {
1886
- switch (resultMode) {
1887
- case SqlQueryMode.One_Row_One_Column_NotSure: {
2318
+ switch (templateResult) {
2319
+ case SelectResult.One_Row_One_Column_NotSure: {
1888
2320
  try {
1889
2321
  return result.map((r) => Object.values(r)[0]);
1890
2322
  }
1891
2323
  catch (error) {
1892
2324
  }
1893
2325
  }
1894
- case SqlQueryMode.One_Row_One_Column_Assert: {
2326
+ case SelectResult.One_Row_One_Column_Assert: {
1895
2327
  try {
1896
2328
  return (0, iterare_1.default)(result).map((r) => Object.values(r)[0]).filter((r) => r !== null).toArray();
1897
2329
  }
1898
2330
  catch (error) {
1899
2331
  }
1900
2332
  }
1901
- case SqlQueryMode.One_Row_Many_Column_NotSure: {
2333
+ case SelectResult.One_Row_Many_Column_NotSure: {
1902
2334
  try {
1903
2335
  return result.map((r) => r[0]);
1904
2336
  }
1905
2337
  catch (error) {
1906
2338
  }
1907
2339
  }
1908
- case SqlQueryMode.One_Row_Many_Column_Assert: {
2340
+ case SelectResult.One_Row_Many_Column_Assert: {
1909
2341
  try {
1910
2342
  return (0, iterare_1.default)(result).map((r) => r[0]).filter((r) => r !== null).toArray();
1911
2343
  }
1912
2344
  catch (error) {
1913
2345
  }
1914
2346
  }
1915
- case SqlQueryMode.Many_Row_One_Column: {
2347
+ case SelectResult.Many_Row_One_Column: {
1916
2348
  try {
1917
2349
  return result.map((rx) => rx.map((r) => Object.values(r)[0]));
1918
2350
  }
1919
2351
  catch (error) {
1920
2352
  }
1921
2353
  }
1922
- case SqlQueryMode.Many_Row_Many_Column: {
2354
+ case SelectResult.Many_Row_Many_Column: {
1923
2355
  return result;
1924
2356
  }
1925
2357
  }
1926
2358
  }
1927
2359
  else {
1928
- switch (resultMode) {
1929
- case SqlQueryMode.One_Row_One_Column_NotSure: {
2360
+ switch (templateResult) {
2361
+ case SelectResult.One_Row_One_Column_NotSure: {
1930
2362
  try {
1931
2363
  return Object.values(result[0])[0];
1932
2364
  }
@@ -1934,7 +2366,7 @@ class SqlService {
1934
2366
  return def;
1935
2367
  }
1936
2368
  }
1937
- case SqlQueryMode.One_Row_One_Column_Assert: {
2369
+ case SelectResult.One_Row_One_Column_Assert: {
1938
2370
  try {
1939
2371
  return Object.values(result[0])[0];
1940
2372
  }
@@ -1944,15 +2376,15 @@ class SqlService {
1944
2376
  error_1.Throw.now(errorMsg ?? 'not found data!');
1945
2377
  }
1946
2378
  }
1947
- case SqlQueryMode.One_Row_Many_Column_NotSure: {
2379
+ case SelectResult.One_Row_Many_Column_NotSure: {
1948
2380
  return result[0] ?? null;
1949
2381
  }
1950
- case SqlQueryMode.One_Row_Many_Column_Assert: {
2382
+ case SelectResult.One_Row_Many_Column_Assert: {
1951
2383
  const data = result[0];
1952
2384
  error_1.Throw.if(data === null, errorMsg ?? 'not found data!');
1953
2385
  return data ?? null;
1954
2386
  }
1955
- case SqlQueryMode.Many_Row_One_Column: {
2387
+ case SelectResult.Many_Row_One_Column: {
1956
2388
  try {
1957
2389
  return result.map((r) => Object.values(r)[0]);
1958
2390
  }
@@ -1960,7 +2392,7 @@ class SqlService {
1960
2392
  return def;
1961
2393
  }
1962
2394
  }
1963
- case SqlQueryMode.Many_Row_Many_Column: {
2395
+ case SelectResult.Many_Row_Many_Column: {
1964
2396
  return result;
1965
2397
  }
1966
2398
  }
@@ -1968,11 +2400,11 @@ class SqlService {
1968
2400
  }
1969
2401
  select(option) {
1970
2402
  error_1.Throw.if(!option.sqlId && !option.sql, 'not found sql!');
1971
- option.resultMode ?? (option.resultMode = SqlQueryMode.Many_Row_Many_Column);
1972
- option.sql ?? (option.sql = globalThis[_sqlCache].load(option.sqlId, option.context, option.isPage));
2403
+ option.selectResult ?? (option.selectResult = SelectResult.Many_Row_Many_Column);
1973
2404
  option.defValue ?? (option.defValue = null);
1974
- logger.debug(option.sql);
1975
2405
  const _params = Object.assign({}, option.context, option.params);
2406
+ option.sql ?? (option.sql = globalThis[_sqlCache].load(option.sqlId, { ctx: option.context, isCount: option.isCount, ..._params }));
2407
+ logger.debug(option.sql);
1976
2408
  const params = [];
1977
2409
  const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
1978
2410
  if (_params.hasOwnProperty(key)) {
@@ -1982,22 +2414,22 @@ class SqlService {
1982
2414
  }
1983
2415
  return txt;
1984
2416
  });
1985
- if (option.sync === SqlSyncMode.Sync) {
1986
- const result = option.conn.query(SqlSyncMode.Sync, sql, params);
1987
- return this._query(option.resultMode, result, option.defValue, option.errorMsg, option.multiple);
2417
+ if (option.sync === SyncMode.Sync) {
2418
+ const result = option.conn.query(SyncMode.Sync, sql, params);
2419
+ return this._select(option.selectResult, result, option.defValue, option.errorMsg, option.multiple);
1988
2420
  }
1989
2421
  else {
1990
2422
  return new Promise(async (resolve) => {
1991
- const result = await option.conn.query(SqlSyncMode.Async, sql, params);
1992
- resolve(this._query(option.resultMode, result, option.defValue, option.errorMsg, option.multiple));
2423
+ const result = await option.conn.query(SyncMode.Async, sql, params);
2424
+ resolve(this._select(option.selectResult, result, option.defValue, option.errorMsg, option.multiple));
1993
2425
  });
1994
2426
  }
1995
2427
  }
1996
2428
  excute(option) {
1997
2429
  error_1.Throw.if(!option.sqlId && !option.sql, 'not found sql!');
1998
- option.sql ?? (option.sql = globalThis[_sqlCache].load(option.sqlId, option.context));
1999
- logger.debug(option.sql);
2000
2430
  const _params = Object.assign({}, option.context, option.params);
2431
+ option.sql ?? (option.sql = globalThis[_sqlCache].load(option.sqlId, { ctx: option.context, ..._params }));
2432
+ logger.debug(option.sql);
2001
2433
  const params = [];
2002
2434
  const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2003
2435
  if (_params.hasOwnProperty(key)) {
@@ -2007,24 +2439,24 @@ class SqlService {
2007
2439
  }
2008
2440
  return txt;
2009
2441
  });
2010
- if (option.sync === SqlSyncMode.Sync) {
2011
- const result = option.conn.execute(SqlSyncMode.Sync, sql, params);
2442
+ if (option.sync === SyncMode.Sync) {
2443
+ const result = option.conn.execute(SyncMode.Sync, sql, params);
2012
2444
  return result.affectedRows;
2013
2445
  }
2014
2446
  else {
2015
2447
  return new Promise(async (resolve) => {
2016
- const result = await option.conn.execute(SqlSyncMode.Async, sql, params);
2448
+ const result = await option.conn.execute(SyncMode.Async, sql, params);
2017
2449
  resolve(result.affectedRows);
2018
2450
  });
2019
2451
  }
2020
2452
  }
2021
2453
  transaction(option) {
2022
- if (option.sync === SqlSyncMode.Sync) {
2023
- return option.dao.transaction(SqlSyncMode.Sync, option.fn);
2454
+ if (option.sync === SyncMode.Sync) {
2455
+ return option.dao.transaction(SyncMode.Sync, option.fn);
2024
2456
  }
2025
2457
  else {
2026
2458
  return new Promise(async (resolve) => {
2027
- const rt = await option.dao.transaction(SqlSyncMode.Async, option.fn);
2459
+ const rt = await option.dao.transaction(SyncMode.Async, option.fn);
2028
2460
  resolve(rt);
2029
2461
  });
2030
2462
  }
@@ -2964,7 +3396,7 @@ class StreamQuery extends StreamBuild {
2964
3396
  this._service = service;
2965
3397
  }
2966
3398
  select(option) {
2967
- option.sync ?? (option.sync = SqlSyncMode.Async);
3399
+ option.sync ?? (option.sync = SyncMode.Async);
2968
3400
  const { where, params } = this.where();
2969
3401
  const sql = `
2970
3402
  SELECT
@@ -2972,29 +3404,29 @@ class StreamQuery extends StreamBuild {
2972
3404
  FROM ${this._table}
2973
3405
  ${where ? ' WHERE ' : ''}
2974
3406
  ${where}`;
2975
- if (option.sync === SqlSyncMode.Async) {
2976
- switch (option.resultMode) {
2977
- case SqlQueryMode.Many_Row_Many_Column: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
2978
- case SqlQueryMode.Many_Row_One_Column: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
2979
- case SqlQueryMode.One_Row_Many_Column_Assert: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
2980
- case SqlQueryMode.One_Row_One_Column_Assert: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
2981
- case SqlQueryMode.One_Row_Many_Column_NotSure: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
2982
- case SqlQueryMode.One_Row_One_Column_NotSure: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3407
+ if (option.sync === SyncMode.Async) {
3408
+ switch (option.selectResult) {
3409
+ case SelectResult.Many_Row_Many_Column: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3410
+ case SelectResult.Many_Row_One_Column: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3411
+ case SelectResult.One_Row_Many_Column_Assert: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3412
+ case SelectResult.One_Row_One_Column_Assert: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3413
+ case SelectResult.One_Row_Many_Column_NotSure: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3414
+ case SelectResult.One_Row_One_Column_NotSure: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
2983
3415
  }
2984
3416
  }
2985
3417
  else {
2986
- switch (option.resultMode) {
2987
- case SqlQueryMode.Many_Row_Many_Column: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
2988
- case SqlQueryMode.Many_Row_One_Column: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
2989
- case SqlQueryMode.One_Row_Many_Column_Assert: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
2990
- case SqlQueryMode.One_Row_One_Column_Assert: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
2991
- case SqlQueryMode.One_Row_Many_Column_NotSure: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
2992
- case SqlQueryMode.One_Row_One_Column_NotSure: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3418
+ switch (option.selectResult) {
3419
+ case SelectResult.Many_Row_Many_Column: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3420
+ case SelectResult.Many_Row_One_Column: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3421
+ case SelectResult.One_Row_Many_Column_Assert: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3422
+ case SelectResult.One_Row_One_Column_Assert: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3423
+ case SelectResult.One_Row_Many_Column_NotSure: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3424
+ case SelectResult.One_Row_One_Column_NotSure: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
2993
3425
  }
2994
3426
  }
2995
3427
  }
2996
3428
  update(option) {
2997
- option.sync ?? (option.sync = SqlSyncMode.Async);
3429
+ option.sync ?? (option.sync = SyncMode.Async);
2998
3430
  const { where, params } = this.where();
2999
3431
  const sets = new Array(...this._updateColumns);
3000
3432
  if (this._updates) {
@@ -3006,11 +3438,11 @@ class StreamQuery extends StreamBuild {
3006
3438
  }
3007
3439
  if (sets.length > 0) {
3008
3440
  const sql = `UPDATE ${this._table} SET ${sets.join(',')} ${where}`;
3009
- if (option.sync === SqlSyncMode.Async) {
3010
- return this._service.excute({ sync: SqlSyncMode.Async, sql, params });
3441
+ if (option.sync === SyncMode.Async) {
3442
+ return this._service.excute({ sync: SyncMode.Async, sql, params });
3011
3443
  }
3012
3444
  else {
3013
- return this._service.excute({ sync: SqlSyncMode.Sync, sql, params });
3445
+ return this._service.excute({ sync: SyncMode.Sync, sql, params });
3014
3446
  }
3015
3447
  }
3016
3448
  else {
@@ -3018,14 +3450,14 @@ class StreamQuery extends StreamBuild {
3018
3450
  }
3019
3451
  }
3020
3452
  delete(option) {
3021
- option.sync ?? (option.sync = SqlSyncMode.Async);
3453
+ option.sync ?? (option.sync = SyncMode.Async);
3022
3454
  const { where, params } = this.where();
3023
3455
  const sql = `DELETE FROM ${this._table} ${where}`;
3024
- if (option.sync === SqlSyncMode.Async) {
3025
- return this._service.excute({ sync: SqlSyncMode.Async, sql, params });
3456
+ if (option.sync === SyncMode.Async) {
3457
+ return this._service.excute({ sync: SyncMode.Async, sql, params });
3026
3458
  }
3027
3459
  else {
3028
- return this._service.excute({ sync: SqlSyncMode.Sync, sql, params });
3460
+ return this._service.excute({ sync: SyncMode.Sync, sql, params });
3029
3461
  }
3030
3462
  }
3031
3463
  }
@@ -3254,15 +3686,137 @@ function MethodCache(config) {
3254
3686
  };
3255
3687
  }
3256
3688
  exports.MethodCache = MethodCache;
3257
- const LetsGo = async function (options) {
3689
+ class MUParser {
3690
+ constructor(modelName, file) {
3691
+ this.linNumber = 0;
3692
+ this.status = 0;
3693
+ this.lineSeparator = '\n';
3694
+ this.modelName = modelName;
3695
+ this.files = file.replace(/\r/g, '').split(this.lineSeparator);
3696
+ this.skipHeader();
3697
+ }
3698
+ next() {
3699
+ let sqlId = this.readSqlId();
3700
+ if (this.status === MUParser.END || !sqlId) {
3701
+ return null;
3702
+ }
3703
+ // 去掉可能的尾部空格
3704
+ sqlId = sqlId.trim();
3705
+ this.skipComment();
3706
+ if (this.status === MUParser.END) {
3707
+ return null;
3708
+ }
3709
+ const sql = this.readSql();
3710
+ return [`${this.modelName}.${sqlId}`, sql];
3711
+ }
3712
+ skipHeader() {
3713
+ while (true) {
3714
+ const line = this.nextLine();
3715
+ if (!line) {
3716
+ return;
3717
+ }
3718
+ if (this.status === MUParser.END) {
3719
+ return;
3720
+ }
3721
+ if (line.startsWith('===')) {
3722
+ return;
3723
+ }
3724
+ }
3725
+ }
3726
+ nextLine() {
3727
+ const line = this.files[this.linNumber];
3728
+ this.linNumber++;
3729
+ if (line === undefined) {
3730
+ this.status = MUParser.END;
3731
+ }
3732
+ // 保存最后读的俩行
3733
+ this.lastlastLine = this.lastLine;
3734
+ this.lastLine = line;
3735
+ return line;
3736
+ }
3737
+ readSqlId() {
3738
+ return this.lastlastLine;
3739
+ }
3740
+ skipComment() {
3741
+ let findComment = false;
3742
+ while (true) {
3743
+ let line = this.nextLine();
3744
+ if (this.status === MUParser.END || !line) {
3745
+ return;
3746
+ }
3747
+ line = line.trim();
3748
+ if (!findComment && line.length === 0) {
3749
+ continue;
3750
+ }
3751
+ if (line.startsWith('*')) {
3752
+ // 注释符号
3753
+ findComment = true;
3754
+ continue;
3755
+ }
3756
+ else {
3757
+ if (line.length === 0) {
3758
+ continue;
3759
+ }
3760
+ else if (line.startsWith('```') || line.startsWith('~~~')) {
3761
+ // 忽略以code block开头的符号
3762
+ continue;
3763
+ }
3764
+ else {
3765
+ // 注释结束
3766
+ return;
3767
+ }
3768
+ }
3769
+ }
3770
+ }
3771
+ readSql() {
3772
+ const list = [];
3773
+ if (this.lastLine) {
3774
+ list.push(this.lastLine);
3775
+ while (true) {
3776
+ const line = this.nextLine();
3777
+ if (line) {
3778
+ if (this.status === MUParser.END) {
3779
+ return this.getBuildSql(list);
3780
+ }
3781
+ if (line.startsWith('===')) {
3782
+ // 删除下一个sqlId表示
3783
+ list.pop();
3784
+ return this.getBuildSql(list);
3785
+ }
3786
+ list.push(line);
3787
+ }
3788
+ else {
3789
+ return '';
3790
+ }
3791
+ }
3792
+ }
3793
+ else {
3794
+ return '';
3795
+ }
3796
+ }
3797
+ getBuildSql(list) {
3798
+ const sb = [];
3799
+ for (const str of list) {
3800
+ const s = str.trim();
3801
+ if (s.startsWith('```') || s.startsWith('~~~')) {
3802
+ // 忽略以code block开头的符号
3803
+ continue;
3804
+ }
3805
+ sb.push(str);
3806
+ }
3807
+ return sb.join(this.lineSeparator);
3808
+ }
3809
+ }
3810
+ MUParser.END = 1;
3811
+ const Boot = async function (options) {
3258
3812
  globalThis[_GlobalSqlOption] = Object.assign({}, _defOption, options);
3259
3813
  if (options.sqlDir) {
3260
- globalThis[_path] = Promise.resolve().then(() => __importStar(require('path')));
3261
- globalThis[_fs] = Promise.resolve().then(() => __importStar(require('fs')));
3814
+ globalThis[_path] = await Promise.resolve().then(() => __importStar(require('path')));
3815
+ globalThis[_fs] = await Promise.resolve().then(() => __importStar(require('fs')));
3262
3816
  }
3263
3817
  logger.level = options.log ?? 'info';
3264
3818
  globalThis[_sqlCache] = new SqlCache();
3265
- if (options.sqlCache || options.sqlDir) {
3819
+ if (options.sqlMap || options.sqlDir) {
3266
3820
  await globalThis[_sqlCache].init(options);
3267
3821
  }
3268
3822
  globalThis[_dao] = {
@@ -3377,4 +3931,4 @@ const LetsGo = async function (options) {
3377
3931
  globalThis[_EventBus] = event;
3378
3932
  }
3379
3933
  };
3380
- exports.LetsGo = LetsGo;
3934
+ exports.Boot = Boot;