baja-lite 1.0.4 → 1.0.5

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.
Files changed (74) hide show
  1. package/cjs/boot-remote.d.ts +2 -0
  2. package/cjs/boot-remote.js +35 -0
  3. package/cjs/boot.d.ts +2 -0
  4. package/cjs/boot.js +152 -0
  5. package/cjs/code.d.ts +1 -0
  6. package/cjs/code.js +345 -1
  7. package/cjs/convert-xml.d.ts +10 -0
  8. package/cjs/convert-xml.js +413 -0
  9. package/cjs/enum.d.ts +10 -0
  10. package/cjs/enum.js +32 -0
  11. package/cjs/error.js +1 -1
  12. package/cjs/index.d.ts +2 -0
  13. package/cjs/index.js +2 -0
  14. package/cjs/object.d.ts +7 -1
  15. package/cjs/object.js +36 -2
  16. package/cjs/sql.d.ts +405 -148
  17. package/cjs/sql.js +1229 -861
  18. package/cjs/sqlite.d.ts +38 -0
  19. package/cjs/sqlite.js +194 -0
  20. package/cjs/test-mysql.d.ts +1 -1
  21. package/cjs/test-mysql.js +72 -63
  22. package/cjs/test-sqlite.d.ts +1 -1
  23. package/cjs/test-sqlite.js +3 -1
  24. package/cjs/test-xml.d.ts +1 -0
  25. package/cjs/test-xml.js +75 -0
  26. package/es/boot-remote.d.ts +2 -0
  27. package/es/boot-remote.js +31 -0
  28. package/es/boot.d.ts +2 -0
  29. package/es/boot.js +125 -0
  30. package/es/code.d.ts +1 -0
  31. package/es/code.js +341 -2
  32. package/es/convert-xml.d.ts +10 -0
  33. package/es/convert-xml.js +409 -0
  34. package/es/enum.d.ts +10 -0
  35. package/es/enum.js +28 -0
  36. package/es/error.js +1 -1
  37. package/es/index.d.ts +2 -0
  38. package/es/index.js +2 -0
  39. package/es/object.d.ts +7 -1
  40. package/es/object.js +28 -1
  41. package/es/sql.d.ts +405 -148
  42. package/es/sql.js +1099 -735
  43. package/es/sqlite.d.ts +38 -0
  44. package/es/sqlite.js +164 -0
  45. package/es/test-mysql.d.ts +1 -1
  46. package/es/test-mysql.js +72 -63
  47. package/es/test-sqlite.d.ts +1 -1
  48. package/es/test-sqlite.js +3 -1
  49. package/es/test-xml.d.ts +1 -0
  50. package/es/test-xml.js +70 -0
  51. package/package.json +10 -7
  52. package/src/boot-remote.ts +31 -0
  53. package/src/boot.ts +129 -0
  54. package/src/code.ts +326 -1
  55. package/src/convert-xml.ts +461 -0
  56. package/src/enum.ts +31 -0
  57. package/src/error.ts +1 -1
  58. package/src/index.ts +3 -1
  59. package/src/object.ts +47 -14
  60. package/src/sql.ts +1145 -787
  61. package/src/sqlite.ts +161 -0
  62. package/src/test-mysql.ts +72 -63
  63. package/src/test-sqlite.ts +3 -1
  64. package/src/test-xml.ts +70 -0
  65. package/cjs/constant.d.ts +0 -13
  66. package/cjs/constant.js +0 -19
  67. package/cjs/redis.d.ts +0 -0
  68. package/cjs/redis.js +0 -1
  69. package/es/constant.d.ts +0 -13
  70. package/es/constant.js +0 -16
  71. package/es/redis.d.ts +0 -0
  72. package/es/redis.js +0 -1
  73. package/src/constant.ts +0 -14
  74. package/src/redis.ts +0 -0
package/src/sql.ts CHANGED
@@ -1,4 +1,3 @@
1
- import 'reflect-metadata';
2
1
  import { Throw } from './error';
3
2
  import tslib from 'tslib';
4
3
  import Sqlstring from 'sqlstring';
@@ -6,12 +5,19 @@ import iterare from 'iterare';
6
5
  import { emptyString } from './string';
7
6
  import pino from 'pino';
8
7
  import { excuteSplit, ExcuteSplitMode, sleep } from './fn';
9
- import { add } from './math';
8
+ import { add, calc } from './math';
10
9
  import mustache, { PartialsOrLookupFn } from 'mustache';
10
+ import { C2P, C2P2, P2C } from './object';
11
+ import { format } from 'sql-formatter';
12
+ import HTML from 'html-parse-stringify';
13
+ import { XML, convert } from './convert-xml';
11
14
 
12
15
  // #region 常量
13
16
  const _daoDBName = Symbol('dbName');
14
17
  const _tableName = Symbol('tableName');
18
+ const _className = Symbol('className');
19
+ const _ClassName = Symbol('ClassName');
20
+ const _vueName = Symbol('vueName');
15
21
  const _ids = Symbol('ids');
16
22
  const _columns = Symbol('columns');
17
23
  const _columnsNoId = Symbol('columnsNoId');
@@ -21,9 +27,9 @@ const _deleteState = Symbol('deleteState');
21
27
  const _transformer = Symbol('transformer');
22
28
  const _index = Symbol('index');
23
29
  const _def = Symbol('def');
24
- const _sqlCache = Symbol('sqlMap');
25
- const _dao = Symbol('dao');
26
- const _primaryDB = Symbol('primaryDB');
30
+ export const _sqlCache = Symbol('sqlMap');
31
+ export const _dao = Symbol('dao');
32
+ export const _primaryDB = Symbol('primaryDB');
27
33
  const _dbType = Symbol('dbType');
28
34
  const _sqlite_version = Symbol('sqlite_version');
29
35
  const _daoConnection = Symbol('daoConnection');
@@ -31,16 +37,18 @@ const _inTransaction = Symbol('inTransaction');
31
37
  const _daoDB = Symbol('daoDB');
32
38
  const _sqliteRemoteName = Symbol('sqliteRemoteName');
33
39
  const _SqlOption = Symbol('SqlOption');
34
- const _GlobalSqlOption = Symbol('GlobalSqlOption');
35
- const _EventBus = Symbol('EventBus');
36
- const _path = Symbol('path');
37
- const _fs = Symbol('fs');
38
- const logger = pino({
39
- name: 'sql',
40
- transport: {
41
- target: 'pino-pretty'
42
- }
43
- });
40
+ export const _Hump = Symbol('Hump');
41
+ export const _GlobalSqlOption = Symbol('GlobalSqlOption');
42
+ export const _EventBus = Symbol('EventBus');
43
+ export const _path = Symbol('path');
44
+ export const _fs = Symbol('fs');
45
+ export const logger =
46
+ process.env['NODE_ENV'] !== 'production' ? pino({
47
+ name: 'sql',
48
+ transport: {
49
+ target: 'pino-pretty'
50
+ }
51
+ }) : pino({ name: 'sql' });
44
52
  // #endregion
45
53
 
46
54
  // #region 可选配置
@@ -171,6 +179,9 @@ export enum SqlType {
171
179
  geometrycollection
172
180
 
173
181
  }
182
+ export enum ColumnMode {
183
+ NONE, HUMP
184
+ }
174
185
  export const SqliteMemory = ':memory:';
175
186
  // #endregion
176
187
 
@@ -186,7 +197,7 @@ interface MethodOption {
186
197
  /** 调用时,仅在开启事务时需要主动传入,传入方式: */
187
198
  conn?: Connection | null;
188
199
  }
189
- const _defOption = {
200
+ export const _defOption = {
190
201
  maxDeal: 500,
191
202
  skipUndefined: true,
192
203
  skipNull: true,
@@ -232,7 +243,7 @@ interface ServiceOption {
232
243
  ```
233
244
  可以继承该接口来约束格式
234
245
  */
235
- interface GlobalSqlOption {
246
+ export interface GlobalSqlOption2 {
236
247
  /** 增改忽略Undefined */
237
248
  skipUndefined?: boolean;
238
249
  /** 增改忽略NULL */
@@ -241,6 +252,51 @@ interface GlobalSqlOption {
241
252
  skipEmptyString?: boolean;
242
253
  /** 批量增改时,每次执行最多处理的记录数量 */
243
254
  maxDeal?: number;
255
+ SqliteRemote?: {
256
+ /**
257
+ ## 单一数据源
258
+ ```
259
+ db: 'd:/1.db'
260
+ ```
261
+ ## 多数据源:传入多个Mysql2的连接配置
262
+ ```
263
+ db: {
264
+ db1: 'd:/1.db',
265
+ db2: 'd:/2.db'
266
+ }
267
+ ```
268
+ 不支持 `SqliteMemory`
269
+ */
270
+ db: Record<string, string> | string,
271
+ /** 远程SQLITE接口实现,适用于Electron, 采用Ipc 的handel机制实现 */
272
+ service: SqliteRemoteInterface
273
+ },
274
+ /** 日志等级 */
275
+ log?: 'trace' | 'debug' | 'info' | 'warn',
276
+ /**
277
+ 作用与sqlDir类似,不同在于sqlMap`不需要`目录,而是直接指定一个sqlModel对象,对象的格式和sqlDir的文件内容一样。
278
+ ** 适用于简单使用
279
+ */
280
+ sqlMap?: SqlModel;
281
+ /**
282
+ 作用与sqlFnDir类似,不同在于sqlFNMap`不需要`目录,而是直接指定一个 Record<string, string>,对象的格式和sqlFnDir的文件内容一样。
283
+ ** 适用于简单使用
284
+ */
285
+ sqlFNMap?: Record<string, string>;
286
+ }
287
+ /**
288
+ # 全局行为配置文件
289
+ MYSQL编码: 'utf8mb4', utf8mb4_general_ci'
290
+ ### `sqlDir?: string;` 数据库查询语句存放目录.存放格式为 export.default 的js、ts, 存放内容满足格式:
291
+
292
+ ```
293
+ interface SqlModel {
294
+ [key: string]: string | ((params: { [k: string]: any }, context: any, isCount?: boolean) => string)
295
+ }
296
+ ```
297
+ 可以继承该接口来约束格式
298
+ */
299
+ export interface GlobalSqlOption extends GlobalSqlOption2 {
244
300
  /**
245
301
  初始化MYSQL链接 支持多数据源
246
302
  ## 单一数据源: 直接传入Mysql2的连接配置
@@ -282,27 +338,6 @@ interface GlobalSqlOption {
282
338
  路径 = `SqliteMemory` 将创建内存库
283
339
  */
284
340
  Sqlite?: Record<string, string> | string,
285
- SqliteRemote?: {
286
- /**
287
- ## 单一数据源
288
- ```
289
- db: 'd:/1.db'
290
- ```
291
- ## 多数据源:传入多个Mysql2的连接配置
292
- ```
293
- db: {
294
- db1: 'd:/1.db',
295
- db2: 'd:/2.db'
296
- }
297
- ```
298
- 不支持 `SqliteMemory`
299
- */
300
- db: Record<string, string> | string,
301
- /** 远程SQLITE接口实现,适用于Electron, 采用Ipc 的handel机制实现 */
302
- service: SqliteRemoteInterface
303
- },
304
- /** 日志等级 */
305
- log?: 'trace' | 'debug' | 'info' | 'warn',
306
341
  /**
307
342
  ## 日志文件存放路径,该目录下文件名是模块名,例如有一个文件名为 `user.js`,内容为:
308
343
  ```
@@ -335,22 +370,11 @@ interface GlobalSqlOption {
335
370
  ## 也支持.mu文件,格式略
336
371
  */
337
372
  sqlDir?: string;
338
- /**
339
- 作用与sqlDir类似,不同在于sqlMap`不需要`目录,而是直接指定一个sqlModel对象,对象的格式和sqlDir的文件内容一样。
340
- ** 适用于简单使用
341
- */
342
- sqlMap?: SqlModel;
343
373
  /**
344
374
  ## [mustache](https://mustache.github.io/) 编译时的[模板](https://github.com/janl/mustache.js#:~:text=requires%20only%20this%3A-,%7B%7B%3E%20next_more%7D%7D,-Why%3F%20Because%20the)
345
375
  ** 文件名就是模板名
346
376
  */
347
377
  sqlFNDir?: string;
348
- /**
349
- 作用与sqlFnDir类似,不同在于sqlFNMap`不需要`目录,而是直接指定一个 Record<string, string>,对象的格式和sqlFnDir的文件内容一样。
350
- ** 适用于简单使用
351
- */
352
- sqlFNMap?: Record<string, string>;
353
-
354
378
  /**
355
379
  [REDIS初始化文档](https://github.com/redis/ioredis?tab=readme-ov-file#:~:text=connect%20to%20by%3A-,new%20Redis()%3B,-//%20Connect%20to%20127.0.0.1)
356
380
  ```
@@ -375,23 +399,59 @@ interface GlobalSqlOption {
375
399
  ```
376
400
  */
377
401
  Redis?: Record<string, Record<string, any>> | Record<string, any>;
402
+
403
+ /**
404
+ * `列名与属性映射` 是否自动将下划线转为驼峰,默认NONE,即不转.
405
+ * 当设置为columnMode.HUMP时,切记将代码生成器中属性名称改对
406
+ * # 自定义sql查询时,无法自动转换哦,可使用标签转换:
407
+ *```
408
+ SELECT
409
+ * {{#hump}} seller_sku2, seller_sku {{/hump}}
410
+ * ```
411
+ * 转换为
412
+ *```
413
+ SELECT
414
+ * {{#hump}} seller_sku2 sellerSku2, seller_sku sellerSku {{/hump}}
415
+ * ```
416
+ */
417
+ columnMode?: ColumnMode;
378
418
  }
419
+
379
420
  interface FieldOption extends Object {
380
421
  type?: SqlType;
381
- name?: string;
422
+ /** @deprecated 属性名称:TS注解不需要,JS手动注入需要 */
423
+ P?: string;
382
424
  length?: number;
383
425
  scale?: number;
384
426
  def?: any;
385
427
  index?: boolean;
386
428
  id?: boolean;
387
- logicDelete?: string;
429
+ logicDelete?: string | number;
430
+ /** 仅在生成 表时有效 */
388
431
  notNull?: boolean;
432
+ comment?: string;
433
+ /** sqlite 无效,与UUID只能有一个 */
434
+ uuidShort?: boolean;
435
+ /** 与uuidShort只能有一个 */
436
+ uuid?: boolean;
389
437
  }
390
438
  interface AField extends FieldOption {
391
- esName: string;
392
- [DBType.Mysql]: string;
393
- [DBType.Sqlite]: string;
394
- [DBType.SqliteRemote]: string;
439
+ /** 安全列名 */
440
+ C2: () => string;
441
+ /** @deprecated 数据列名称 */
442
+ C?: () => string;
443
+ /** 查询用:b_id bId */
444
+ C3: () => string;
445
+
446
+ [DBType.Mysql]: () => string;
447
+ [DBType.Sqlite]: () => string;
448
+ [DBType.SqliteRemote]: () => string;
449
+ }
450
+ export interface PageQuery<L> {
451
+ sum?: Record<string, number>;
452
+ total?: number;
453
+ size?: number;
454
+ records?: L[];
395
455
  }
396
456
  // #endregion
397
457
 
@@ -399,14 +459,14 @@ interface AField extends FieldOption {
399
459
  /** sqlite electron服务端需要支持的接口 */
400
460
  export interface SqliteRemoteInterface {
401
461
  execute(dbName: string, sql?: string, params?: any): | Promise<{ affectedRows: number; insertId: bigint; }>
402
- pluck<One_Row_Many_Column = any>(dbName: string, sql?: string, params?: any): Promise<One_Row_Many_Column | undefined>;
403
- get<One_Row_Many_Column = any>(dbName: string, sql?: string, params?: any): Promise<One_Row_Many_Column | undefined>;
462
+ pluck<One_Row_Many_Column = any>(dbName: string, sql?: string, params?: any): Promise<One_Row_Many_Column | null>;
463
+ get<One_Row_Many_Column = any>(dbName: string, sql?: string, params?: any): Promise<One_Row_Many_Column | null>;
404
464
  raw<Many_Row_One_Column = any>(dbName: string, sql?: string, params?: any): Promise<Many_Row_One_Column[]>;
405
465
  query<Many_Row_Many_Column = any>(dbName: string, sql?: string, params?: any): Promise<Many_Row_Many_Column[]>;
406
466
 
407
467
  initDB(dbName: string): Promise<void>;
408
- backup(dbName: string, name: string): Promise<void>;
409
- restore(dbName: string, name: string): Promise<void>;
468
+ export(dbName: string): Promise<void>;
469
+ restore(dbName: string, fromName: string): Promise<void>;
410
470
  };
411
471
  interface Connection {
412
472
  [_daoConnection]: any;
@@ -617,7 +677,7 @@ class MysqlConnection implements Connection {
617
677
  };
618
678
  }
619
679
  }
620
- class Mysql implements Dao {
680
+ export class Mysql implements Dao {
621
681
  [_daoDB]: any;
622
682
  constructor(pool: any) {
623
683
  this[_daoDB] = pool;
@@ -633,7 +693,7 @@ class Mysql implements Dao {
633
693
  return new Promise<Connection>(async (resolve, reject) => {
634
694
  try {
635
695
  const connection = await this[_daoDB].getConnection();
636
- logger.debug('create new!');
696
+ logger.debug('create new connection!');
637
697
  resolve(new MysqlConnection(connection));
638
698
  } catch (error) {
639
699
  reject(error);
@@ -851,7 +911,7 @@ class SqliteConnection implements Connection {
851
911
  realse(sync: SyncMode): Promise<void> | void {
852
912
  }
853
913
  }
854
- class Sqlite implements Dao {
914
+ export class Sqlite implements Dao {
855
915
  [_daoDB]: any;
856
916
  constructor(db: any) {
857
917
  this[_daoDB] = db;
@@ -929,7 +989,7 @@ class Sqlite implements Dao {
929
989
  restore(sync: SyncMode, name: string): Promise<void> | void {
930
990
  }
931
991
  }
932
- class SqliteRemoteConnection implements Connection {
992
+ export class SqliteRemoteConnection implements Connection {
933
993
  [_daoConnection]: SqliteRemoteInterface;
934
994
  [_sqliteRemoteName]: string;
935
995
  [_inTransaction] = false;
@@ -1078,7 +1138,7 @@ class SqliteRemoteConnection implements Connection {
1078
1138
  realse(sync: SyncMode): Promise<void> | void {
1079
1139
  }
1080
1140
  }
1081
- class SqliteRemote implements Dao {
1141
+ export class SqliteRemote implements Dao {
1082
1142
  [_sqliteRemoteName]: string;
1083
1143
  [_daoDB]: SqliteRemoteInterface;
1084
1144
 
@@ -1095,8 +1155,12 @@ class SqliteRemote implements Dao {
1095
1155
  logger.error('SQLITEREMOTE not suppouted sync mode');
1096
1156
  return null;
1097
1157
  };
1098
- return new Promise<Connection>(async resolve => {
1099
- resolve(new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]));
1158
+ return new Promise<Connection>(async (resolve, reject) => {
1159
+ try {
1160
+ resolve(new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]));
1161
+ } catch (error) {
1162
+ reject(error);
1163
+ }
1100
1164
  });
1101
1165
  }
1102
1166
 
@@ -1112,8 +1176,12 @@ class SqliteRemote implements Dao {
1112
1176
  close(sync: SyncMode.Async): Promise<void>;
1113
1177
  close(sync: SyncMode): Promise<void> | void {
1114
1178
  if (sync === SyncMode.Async) {
1115
- return new Promise(async () => {
1116
- await this[_daoConnection].close();
1179
+ return new Promise(async (resolve, reject) => {
1180
+ try {
1181
+ await this[_daoConnection].close();
1182
+ } catch (error) {
1183
+ reject(error);
1184
+ }
1117
1185
  });
1118
1186
  };
1119
1187
  }
@@ -1122,8 +1190,12 @@ class SqliteRemote implements Dao {
1122
1190
  backup(sync: SyncMode.Async, name: string): Promise<void>;
1123
1191
  backup(sync: SyncMode, name: string): Promise<void> | void {
1124
1192
  if (sync === SyncMode.Async) {
1125
- return new Promise(async () => {
1126
- await this[_daoConnection].backup(this[_sqliteRemoteName], name);
1193
+ return new Promise(async (resolve, reject) => {
1194
+ try {
1195
+ await this[_daoConnection].backup(this[_sqliteRemoteName], name);
1196
+ } catch (error) {
1197
+ reject(error);
1198
+ }
1127
1199
  });
1128
1200
  };
1129
1201
  }
@@ -1132,8 +1204,12 @@ class SqliteRemote implements Dao {
1132
1204
  remove(sync: SyncMode.Async): Promise<void>;
1133
1205
  remove(sync: SyncMode): Promise<void> | void {
1134
1206
  if (sync === SyncMode.Async) {
1135
- return new Promise(async () => {
1136
- await this[_daoConnection].remove();
1207
+ return new Promise(async (resolve, reject) => {
1208
+ try {
1209
+ await this[_daoConnection].remove();
1210
+ } catch (error) {
1211
+ reject(error);
1212
+ }
1137
1213
  });
1138
1214
  };
1139
1215
  }
@@ -1142,8 +1218,12 @@ class SqliteRemote implements Dao {
1142
1218
  restore(sync: SyncMode.Async, name: string): Promise<void>;
1143
1219
  restore(sync: SyncMode, name: string): Promise<void> | void {
1144
1220
  if (sync === SyncMode.Async) {
1145
- return new Promise(async () => {
1146
- await this[_daoConnection].restore(this[_sqliteRemoteName], name);
1221
+ return new Promise(async (resolve, reject) => {
1222
+ try {
1223
+ await this[_daoConnection].restore(this[_sqliteRemoteName], name);
1224
+ } catch (error) {
1225
+ reject(error);
1226
+ }
1147
1227
  });
1148
1228
  };
1149
1229
  }
@@ -1161,7 +1241,7 @@ export type SqlModel = Record<string, string | (
1161
1241
  orderBy?: string;
1162
1242
  [k: string]: any;
1163
1243
  }) => string
1164
- )>;
1244
+ ) | XML[]>;
1165
1245
  class Build {
1166
1246
  private static page = 'COUNT(1) zccw1986 ';
1167
1247
  private isCount: boolean;
@@ -1188,7 +1268,7 @@ class Build {
1188
1268
  * @returns
1189
1269
  * @memberof Build
1190
1270
  */
1191
- pageTag() {
1271
+ page() {
1192
1272
  return (text: string, render: (text: string) => string) => {
1193
1273
  if (this.isCount === true) {
1194
1274
  return Build.page;
@@ -1199,11 +1279,11 @@ class Build {
1199
1279
  }
1200
1280
  /**
1201
1281
  *
1202
- * 汇总查询专用
1282
+ * 包含的内容只在汇总查询时有效,否则是空白
1203
1283
  * @returns
1204
1284
  * @memberof Build
1205
1285
  */
1206
- sumTag() {
1286
+ sum() {
1207
1287
  return (text: string, render: (text: string) => string) => {
1208
1288
  if (this.isSum !== true) {
1209
1289
  return '';
@@ -1212,13 +1292,14 @@ class Build {
1212
1292
  }
1213
1293
  };
1214
1294
  }
1295
+
1215
1296
  /**
1216
1297
  *
1217
1298
  * 当分页时、汇总时忽略函数内包含的内容
1218
1299
  * @returns
1219
1300
  * @memberof Build
1220
1301
  */
1221
- pageIgnoreTag() {
1302
+ notPage() {
1222
1303
  return (text: string, render: (text: string) => string) => {
1223
1304
  if (this.isCount === true || this.isSum === true) {
1224
1305
  return '';
@@ -1242,8 +1323,7 @@ class Build {
1242
1323
  */
1243
1324
  where() {
1244
1325
  return (text: string, render: (text: string) => string) => {
1245
- let data = render(text);
1246
- data = data.trim();
1326
+ let data = render(text).trim();
1247
1327
  if (data) {
1248
1328
  data = data.replace(/and|or/i, '');
1249
1329
  return ` WHERE ${data} `;
@@ -1252,6 +1332,33 @@ class Build {
1252
1332
  }
1253
1333
  };
1254
1334
  }
1335
+ /**
1336
+ * ```
1337
+ * SELECT
1338
+ * {{#hump}}
1339
+ * a.event_id, a.event_name eventName
1340
+ * {{/hump}}
1341
+ * FROM...
1342
+ * ```
1343
+ * 编译后:
1344
+ * ```
1345
+ * SELECT
1346
+ * a.event_id eventId, a.event_name eventName
1347
+ * FROM...
1348
+ * ```
1349
+ */
1350
+ hump() {
1351
+ return (text: string, render: (text: string) => string) => {
1352
+ let data = render(text).trim();
1353
+ const datas = data.split(',');
1354
+ for (let i = 0; i < datas.length; i++) {
1355
+ if (datas[i]?.match(/\s|\t/) === null) {
1356
+ datas[i] = `${datas[i]} ${datas[i]!.replace(/[a-zA-Z0-9]+\./, '').replace(/_([a-z])/g, (a, b, c) => b.toUpperCase())}`;
1357
+ }
1358
+ }
1359
+ return datas.join(',');
1360
+ };
1361
+ }
1255
1362
  /**
1256
1363
  * 删除第一个and、or
1257
1364
  * 删除最后一个,
@@ -1274,13 +1381,13 @@ class Build {
1274
1381
  * 分页时将排序部分代码用此函数包起来,可以自动拼接order by
1275
1382
  * 查询条数时,自动忽略此部分
1276
1383
  * etc
1277
- * {{#orderTag}} name desc, age asc {{/orderTag}}
1384
+ * {{#order}} name desc, age asc {{/order}}
1278
1385
  * ===
1279
1386
  * ORDER BY name desc, age asc
1280
1387
  * @returns
1281
1388
  * @memberof Build
1282
1389
  */
1283
- orderTag() {
1390
+ order() {
1284
1391
  return (text: string, render: (text: string) => string) => {
1285
1392
  if (this.isCount === true || this.isSum === true) {
1286
1393
  return '';
@@ -1295,7 +1402,7 @@ class Build {
1295
1402
  }
1296
1403
  };
1297
1404
  }
1298
- limitTag() {
1405
+ limit() {
1299
1406
  return (text: string, render: (text: string) => string) => {
1300
1407
  if (this.isCount === true || this.isSum === true) {
1301
1408
  return '';
@@ -1315,13 +1422,13 @@ class Build {
1315
1422
  * 分页时将分组部分代码用此函数包起来,可以自动拼接GROUP BY
1316
1423
  * 当分页时、汇总时,自动忽略此部分
1317
1424
  * etc
1318
- * {{#groupTag}} name, age {{/groupTag}}
1425
+ * {{#between}} name, age {{/between}}
1319
1426
  * ===
1320
1427
  * group by name.age
1321
1428
  * @returns
1322
1429
  * @memberof Build
1323
1430
  */
1324
- groupTag() {
1431
+ group() {
1325
1432
  return (text: string, render: (text: string) => string) => {
1326
1433
  if (this.isCount === true || this.isSum === true) {
1327
1434
  return '';
@@ -1365,15 +1472,15 @@ class Build {
1365
1472
  *
1366
1473
  * 距离计算,单位米
1367
1474
  * etc
1368
- * {{#distanceTag}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distanceTag}}
1475
+ * {{#distance}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distance}}
1369
1476
  * ===
1370
1477
  * ROUND(ST_DISTANCE(POINT(longitude1, latitude1), POINT({{longitude}}, {{latitude}}))*111195, 2)
1371
1478
  * 可根据需求自行将数据转换为千米,例如
1372
- * {{#distanceTag}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distanceTag}} / 1000
1479
+ * {{#distance}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distance}} / 1000
1373
1480
  * @returns
1374
1481
  * @memberof Build
1375
1482
  */
1376
- distanceTag() {
1483
+ distance() {
1377
1484
  return (text: string, render: (text: string) => string) => {
1378
1485
  const result = render(text);
1379
1486
  if (/\(([^()]+)\)/.exec(result)) {
@@ -1397,7 +1504,31 @@ class Build {
1397
1504
  };
1398
1505
  }
1399
1506
  }
1400
- class SqlCache {
1507
+
1508
+ function replaceCdata(rawText: string) {
1509
+ var cdataRegex = new RegExp('(<!\\[CDATA\\[)([\\s\\S]*?)(\\]\\]>)', 'g');
1510
+ var matches = rawText.match(cdataRegex);
1511
+
1512
+ if (matches != null && matches.length > 0) {
1513
+ for (var z = 0; z < matches.length; z++) {
1514
+ var regex = new RegExp('(<!\\[CDATA\\[)([\\s\\S]*?)(\\]\\]>)', 'g');
1515
+ var m = regex.exec(matches[z]!);
1516
+
1517
+ var cdataText = m![2];
1518
+ cdataText = cdataText!.replace(/\&/g, '&amp;');
1519
+ cdataText = cdataText!.replace(/\</g, '&lt;');
1520
+ cdataText = cdataText!.replace(/\>/g, '&gt;');
1521
+ cdataText = cdataText!.replace(/\"/g, '&quot;');
1522
+
1523
+ rawText = rawText.replace(m![0], cdataText);
1524
+ }
1525
+ }
1526
+ return rawText;
1527
+ }
1528
+
1529
+
1530
+
1531
+ export class SqlCache {
1401
1532
  private sqlMap: SqlModel = {};
1402
1533
  private sqlFNMap: PartialsOrLookupFn = {};
1403
1534
  async init(options: {
@@ -1407,26 +1538,53 @@ class SqlCache {
1407
1538
  if (options.sqlMap) {
1408
1539
  this.sqlMap = options.sqlMap;
1409
1540
  }
1541
+ const queryTypes = ['sql', 'select', 'insert', 'update', 'delete'];
1410
1542
  if (options.sqlDir) {
1411
1543
  const sqlFis = globalThis[_fs].readdirSync(options.sqlDir);
1412
1544
  for (const modeName of sqlFis) {
1545
+ logger.debug(`sql: ${modeName} start explain!`);
1413
1546
  const extname = globalThis[_path].extname(modeName);
1414
1547
  const name = globalThis[_path].basename(modeName, extname);
1415
1548
  const file = globalThis[_path].join(options.sqlDir, modeName);
1416
- if (extname === 'mu') {
1549
+ let ct = 0;
1550
+ if (extname === '.mu') {
1417
1551
  const parser = new MUParser(name, globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString());
1418
1552
  let source = parser.next();
1419
1553
  while (source != null) {
1554
+ ct++;
1420
1555
  this.sqlMap[source[0]] = source[1];
1421
1556
  logger.debug(`sql: ${source[0]} found!`);
1422
1557
  source = parser.next();
1423
1558
  }
1559
+
1424
1560
  } else if (extname === '.js') {
1425
1561
  const obj = (await import(globalThis[_path].join(options.sqlDir, modeName))).default as SqlModel;
1426
1562
  for (const [key, fn] of Object.entries(obj)) {
1563
+ ct++;
1564
+
1427
1565
  this.sqlMap[`${name}.${String(key)}`] = fn;
1428
1566
  }
1567
+ } else if (extname === '.xml') {
1568
+ const root = (HTML.parse(replaceCdata(globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString())) as XML[])[0];
1569
+ if(root){
1570
+ const mappers = root.children;
1571
+ for (const mapper of mappers) {
1572
+ console.log(mapper);
1573
+ if (mapper.type === 'tag' && mapper.name === 'mapper') {
1574
+ for (const am of mapper.children) {
1575
+ if (am.type === 'tag') {
1576
+ Throw.if(!queryTypes.includes(am.name), `${name}错误,${am.name}不支持!`);
1577
+ am.id = am.attrs['id'];
1578
+ Throw.if(!am.id, `${name}错误,没有为此块设置id:${am}`);
1579
+ this.sqlMap[`${name}.${am.id!}`] = am.children;
1580
+ }
1581
+ }
1582
+ }
1583
+ }
1584
+ }
1585
+
1429
1586
  }
1587
+ logger.debug(`sql: ${modeName} explain over[${ct}]!`);
1430
1588
  }
1431
1589
  }
1432
1590
  if (options.sqlFNMap) {
@@ -1444,7 +1602,7 @@ class SqlCache {
1444
1602
  }
1445
1603
  }
1446
1604
  }
1447
- load(sqlid: string, options: {
1605
+ load(sqlids: string[], options: {
1448
1606
  ctx: any;
1449
1607
  isCount?: boolean;
1450
1608
  isSum?: boolean;
@@ -1453,13 +1611,29 @@ class SqlCache {
1453
1611
  orderBy?: string;
1454
1612
  [k: string]: any;
1455
1613
  }): string {
1456
- const sqlSource = this.sqlMap[sqlid];
1457
- Throw.if(!sqlSource, `指定的语句${sqlid}不存在!`);
1458
- const _sql = typeof sqlSource === 'function' ? sqlSource(options) : sqlSource!;
1459
- const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1460
- const sql = mustache.render(_sql, buildParam, this.sqlFNMap);
1461
- logger.debug(sqlid, sql);
1462
- return sql;
1614
+ let sqlSource: any;
1615
+ for (const sqlid of sqlids) {
1616
+ sqlSource = this.sqlMap[sqlid];
1617
+ if (sqlSource) {
1618
+ break;
1619
+ }
1620
+ }
1621
+ const matchSqlid = sqlids.map(i => i.split('.')[0]!);
1622
+ Throw.if(!sqlSource, `指定的语句${sqlids.join('|')}不存在!`);
1623
+ if (typeof sqlSource === 'function') {
1624
+ const _sql = sqlSource(options);
1625
+ const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1626
+ const sql = mustache.render(_sql, buildParam, this.sqlFNMap);
1627
+ return format(sql);
1628
+ } else if (typeof sqlSource === 'string') {
1629
+ const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1630
+ const sql = mustache.render(sqlSource, buildParam, this.sqlFNMap);
1631
+ return format(sql);
1632
+ } else if (typeof sqlSource === 'object') {
1633
+ const sql = convert(sqlSource, options, matchSqlid, this.sqlMap as Record<string, XML[]>);
1634
+ return format(sql);
1635
+ }
1636
+ return '';
1463
1637
  }
1464
1638
  }
1465
1639
  // #endregion
@@ -1489,6 +1663,8 @@ function P<T extends object>(skipConn = false) {
1489
1663
  const option = args[0] = Object.assign({}, globalThis[_GlobalSqlOption], this[_SqlOption], args[0]) as (MethodOption & { sync?: SyncMode; });
1490
1664
  option.sync ??= SyncMode.Async;
1491
1665
  const dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
1666
+ const dddx = this[_dbType];
1667
+ logger.info(dddx);
1492
1668
  option!.dao = globalThis[_dao][this[_dbType]!][dbName] as Dao;
1493
1669
  Throw.if(!option!.dao, `not found db:${String(dbName)}(${this[_dbType]})`);
1494
1670
  option!.tableName = option?.tableName ?? this[_tableName];
@@ -1511,7 +1687,7 @@ function P<T extends object>(skipConn = false) {
1511
1687
  if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1512
1688
  // 更新版本
1513
1689
  const columns = iterare<{ name: string }>(option!.conn!.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
1514
- .filter(c => this[_fields]!.hasOwnProperty(c.name))
1690
+ .filter(c => this[_fields]!.hasOwnProperty(C2P(c.name, globalThis[_Hump])))
1515
1691
  .map(c => Sqlstring.escapeId(c.name))
1516
1692
  .join(',');
1517
1693
 
@@ -1520,13 +1696,13 @@ function P<T extends object>(skipConn = false) {
1520
1696
  option!.conn!.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1521
1697
  option!.conn!.execute(SyncMode.Sync, `
1522
1698
  CREATE TABLE IF NOT EXISTS ${tableES}(
1523
- ${Object.values(this[_fields]!).map(K => K[DBType.Sqlite]).join(',')}
1524
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields]![i]?.esName).join(',')})` : ''}
1699
+ ${Object.values(this[_fields]!).map(K => K[DBType.Sqlite]()).join(',')}
1700
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields]![i]?.C2()).join(',')})` : ''}
1525
1701
  );
1526
1702
  `);
1527
1703
  if (this[_index] && this[_index].length) {
1528
1704
  for (const index of this[_index]) {
1529
- option!.conn!.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1705
+ option!.conn!.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields]![index]?.C2()}");`);
1530
1706
  }
1531
1707
  }
1532
1708
  option!.conn!.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
@@ -1541,14 +1717,14 @@ function P<T extends object>(skipConn = false) {
1541
1717
  // 创建表
1542
1718
  option!.conn!.execute(SyncMode.Sync, `
1543
1719
  CREATE TABLE IF NOT EXISTS ${tableES} (
1544
- ${Object.values(this[_fields]!).map(K => K[DBType.Sqlite]).join(',')}
1545
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields]![i]?.esName).join(',')})` : ''}
1720
+ ${Object.values(this[_fields]!).map(K => K[DBType.Sqlite]()).join(',')}
1721
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields]![i]?.C2()).join(',')})` : ''}
1546
1722
 
1547
1723
  );
1548
1724
  `);
1549
1725
  if (this[_index] && this[_index].length) {
1550
1726
  for (const index of this[_index]) {
1551
- option!.conn!.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1727
+ option!.conn!.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields]![index]?.C2()}");`);
1552
1728
  }
1553
1729
  }
1554
1730
  option!.conn!.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option!.tableName, lastVersion]);
@@ -1592,7 +1768,7 @@ function P<T extends object>(skipConn = false) {
1592
1768
  if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1593
1769
  // 更新版本
1594
1770
  const columns = iterare<{ name: string }>(await option!.conn!.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
1595
- .filter(c => this[_fields]!.hasOwnProperty(c.name))
1771
+ .filter(c => this[_fields]!.hasOwnProperty(C2P(c.name, globalThis[_Hump])))
1596
1772
  .map(c => Sqlstring.escapeId(c.name))
1597
1773
  .join(',');
1598
1774
 
@@ -1601,13 +1777,13 @@ function P<T extends object>(skipConn = false) {
1601
1777
  await option!.conn!.execute(SyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1602
1778
  await option!.conn!.execute(SyncMode.Async, `
1603
1779
  CREATE TABLE IF NOT EXISTS ${tableES}(
1604
- ${Object.values(this[_fields]!).map(K => K[DBType.Sqlite]).join(',')}
1605
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields]![i]?.esName).join(',')})` : ''}
1780
+ ${Object.values(this[_fields]!).map(K => K[DBType.Sqlite]()).join(',')}
1781
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields]![i]?.C2()).join(',')})` : ''}
1606
1782
  );
1607
1783
  `);
1608
1784
  if (this[_index] && this[_index].length) {
1609
1785
  for (const index of this[_index]) {
1610
- await option!.conn!.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1786
+ await option!.conn!.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields]![index]?.C2()}");`);
1611
1787
  }
1612
1788
  }
1613
1789
  await option!.conn!.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
@@ -1622,13 +1798,13 @@ function P<T extends object>(skipConn = false) {
1622
1798
  // 创建表
1623
1799
  await option!.conn!.execute(SyncMode.Async, `
1624
1800
  CREATE TABLE IF NOT EXISTS ${tableES}(
1625
- ${Object.values(this[_fields]!).map(K => K[DBType.Sqlite]).join(',')}
1626
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields]![i]?.esName).join(',')})` : ''}
1801
+ ${Object.values(this[_fields]!).map(K => K[DBType.Sqlite]()).join(',')}
1802
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields]![i]?.C2()).join(',')})` : ''}
1627
1803
  );
1628
1804
  `);
1629
1805
  if (this[_index] && this[_index].length) {
1630
1806
  for (const index of this[_index]) {
1631
- await option!.conn!.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${Sqlstring.escapeId(option!.tableName)} ("${index}");`);
1807
+ await option!.conn!.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${Sqlstring.escapeId(option!.tableName)} ("${this[_fields]![index]?.C2()}");`);
1632
1808
  }
1633
1809
  }
1634
1810
  await option!.conn!.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option!.tableName, lastVersion]);
@@ -1682,27 +1858,40 @@ function P<T extends object>(skipConn = false) {
1682
1858
  };
1683
1859
  }
1684
1860
  const FieldFilter = (
1685
- K: string, V: any, def: any,
1686
- option?: MethodOption & { finalColumns?: Set<string>; tempColumns?: Array<string>; def?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; }
1861
+ K: string, V: any, def: any, uuidColumn: boolean,
1862
+ option?: MethodOption & { finalColumns?: Set<string>; tempColumns?: Array<string>; insert?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; }
1687
1863
  ) => {
1688
1864
  let ret = 0;
1689
- if (V === null) {
1690
- if (option?.skipNull !== true) {
1691
- ret = 1;
1692
- V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : null;
1693
- }
1694
- } else if (V === undefined) {
1695
- if (option?.skipUndefined !== true) {
1865
+ // 如果是插入操作且字段是UUID,则不进行空值检查
1866
+ // 只有在非插入或者非UUID时,进行空置检查
1867
+ if (option?.insert === true && uuidColumn === true) {
1868
+ ret = 1;
1869
+ if (V === undefined) {
1870
+ V = null;
1871
+ } else if (emptyString(`${V ?? ''}`)) {
1872
+ V = '';
1873
+ } else {
1696
1874
  ret = 1;
1697
- V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : null;
1698
1875
  }
1699
- } else if (emptyString(`${V ?? ''}`)) {
1700
- if (option?.skipEmptyString !== true) {
1876
+ } else {
1877
+ if (V === null) {
1878
+ if (option?.skipNull !== true) {
1879
+ ret = 1;
1880
+ V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : null;
1881
+ }
1882
+ } else if (V === undefined) {
1883
+ if (option?.skipUndefined !== true) {
1884
+ ret = 1;
1885
+ V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : null;
1886
+ }
1887
+ } else if (emptyString(`${V ?? ''}`)) {
1888
+ if (option?.skipEmptyString !== true) {
1889
+ ret = 1;
1890
+ V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : '';
1891
+ }
1892
+ } else {
1701
1893
  ret = 1;
1702
- V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : '';
1703
1894
  }
1704
- } else {
1705
- ret = 1;
1706
1895
  }
1707
1896
  if (ret === 1) {
1708
1897
  option?.finalColumns?.add(K);
@@ -1710,204 +1899,203 @@ const FieldFilter = (
1710
1899
  }
1711
1900
  return [ret, V];
1712
1901
  }
1713
- const MYSQLCHARSET = `CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci`
1902
+ const MYSQLCHARSET = `CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci`;
1714
1903
  export const Field = (config: FieldOption) => {
1715
1904
  config.type ??= SqlType.varchar;
1716
1905
  return (object: object, propertyName: string) => {
1717
1906
  const field = config as AField;
1718
- field.name = propertyName;
1719
- field.esName = Sqlstring.escapeId(propertyName);
1907
+ field.P = propertyName;
1908
+ field.C = () => P2C(propertyName, globalThis[_Hump]);
1909
+ field.C2 = () => Sqlstring.escapeId(P2C(propertyName, globalThis[_Hump]));
1910
+ field.C3 = () => `${Sqlstring.escapeId(P2C(propertyName, globalThis[_Hump]))} ${propertyName}`;
1720
1911
  const hasDef = field.hasOwnProperty('def') === true;
1721
1912
  switch (field.type) {
1722
1913
  case SqlType.tinyint: {
1723
- field[DBType.Mysql] = `${field.esName} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1724
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1914
+ field[DBType.Mysql] = () => `${field.C2()} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1915
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1725
1916
  break;
1726
1917
  }
1727
1918
  case SqlType.smallint: {
1728
- field[DBType.Mysql] = `${field.esName} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1729
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1919
+ field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1920
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1730
1921
  break;
1731
1922
  }
1732
1923
  case SqlType.mediumint: {
1733
- field[DBType.Mysql] = `${field.esName} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1734
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1924
+ field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1925
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1735
1926
  break;
1736
1927
  }
1737
1928
  case SqlType.int: {
1738
- field[DBType.Mysql] = `${field.esName} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1739
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1929
+ field[DBType.Mysql] = () => `${field.C2()} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1930
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1740
1931
  break;
1741
1932
  }
1742
1933
  case SqlType.bigint: {
1743
- field[DBType.Mysql] = `${field.esName} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1744
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1934
+ field[DBType.Mysql] = () => `${field.C2()} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1935
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1745
1936
  break;
1746
1937
  }
1747
-
1748
1938
  case SqlType.float: {
1749
- field[DBType.Mysql] = `${field.esName} float(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1750
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1939
+ field[DBType.Mysql] = () => `${field.C2()} float(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1940
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1751
1941
  break;
1752
1942
  }
1753
1943
  case SqlType.double: {
1754
- field[DBType.Mysql] = `${field.esName} double(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1755
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1944
+ field[DBType.Mysql] = () => `${field.C2()} double(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1945
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1756
1946
  break;
1757
1947
  }
1758
1948
  case SqlType.decimal: {
1759
- field[DBType.Mysql] = `${field.esName} decimal(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1760
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1949
+ field[DBType.Mysql] = () => `${field.C2()} decimal(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1950
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1761
1951
  break;
1762
1952
  }
1763
1953
 
1764
1954
  case SqlType.longtext: {
1765
- field[DBType.Mysql] = `${field.esName} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1766
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1955
+ field[DBType.Mysql] = () => `${field.C2()} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1956
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1767
1957
  break;
1768
1958
  }
1769
1959
  case SqlType.mediumtext: {
1770
- field[DBType.Mysql] = `${field.esName} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1771
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1960
+ field[DBType.Mysql] = () => `${field.C2()} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1961
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1772
1962
  break;
1773
1963
  }
1774
1964
  case SqlType.text: {
1775
- field[DBType.Mysql] = `${field.esName} text ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1776
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1965
+ field[DBType.Mysql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1966
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1777
1967
  break;
1778
1968
  }
1779
-
1780
1969
  case SqlType.date: {
1781
- field[DBType.Mysql] = `${field.esName} date ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1782
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1970
+ field[DBType.Mysql] = () => `${field.C2()} date ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1971
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1783
1972
  break;
1784
1973
  }
1785
1974
  case SqlType.time: {
1786
- field[DBType.Mysql] = `${field.esName} time ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1787
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1975
+ field[DBType.Mysql] = () => `${field.C2()} time ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1976
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1788
1977
  break;
1789
1978
  }
1790
1979
  case SqlType.year: {
1791
- field[DBType.Mysql] = `${field.esName} year ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1792
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1980
+ field[DBType.Mysql] = () => `${field.C2()} year ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1981
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1793
1982
  break;
1794
1983
  }
1795
1984
  case SqlType.datetime: {
1796
- field[DBType.Mysql] = `${field.esName} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1797
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1985
+ field[DBType.Mysql] = () => `${field.C2()} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1986
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1798
1987
  break;
1799
1988
  }
1800
1989
  case SqlType.timestamp: {
1801
- field[DBType.Mysql] = `${field.esName} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1802
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1990
+ field[DBType.Mysql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1991
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1803
1992
  break;
1804
1993
  }
1805
-
1806
1994
  case SqlType.char: {
1807
- field[DBType.Mysql] = `${field.esName} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1808
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1995
+ field[DBType.Mysql] = () => `${field.C2()} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1996
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1809
1997
  break;
1810
1998
  }
1811
1999
  case SqlType.varchar: {
1812
- field[DBType.Mysql] = `${field.esName} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1813
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2000
+ field[DBType.Mysql] = () => `${field.C2()} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2001
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1814
2002
  break;
1815
2003
  }
1816
2004
  case SqlType.tinyblob: {
1817
- field[DBType.Mysql] = `${field.esName} tinyblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1818
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2005
+ field[DBType.Mysql] = () => `${field.C2()} tinyblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2006
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1819
2007
  break;
1820
2008
  }
1821
2009
  case SqlType.tinytext: {
1822
- field[DBType.Mysql] = `${field.esName} tinytext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1823
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2010
+ field[DBType.Mysql] = () => `${field.C2()} tinytext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2011
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1824
2012
  break;
1825
2013
  }
1826
2014
  case SqlType.blob: {
1827
- field[DBType.Mysql] = `${field.esName} binary ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1828
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2015
+ field[DBType.Mysql] = () => `${field.C2()} binary ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2016
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1829
2017
  break;
1830
2018
  }
1831
2019
  case SqlType.text: {
1832
- field[DBType.Mysql] = `${field.esName} text ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1833
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2020
+ field[DBType.Mysql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2021
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1834
2022
  break;
1835
2023
  }
1836
2024
  case SqlType.mediumblob: {
1837
- field[DBType.Mysql] = `${field.esName} mediumblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1838
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2025
+ field[DBType.Mysql] = () => `${field.C2()} mediumblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2026
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1839
2027
  break;
1840
2028
  }
1841
2029
  case SqlType.mediumtext: {
1842
- field[DBType.Mysql] = `${field.esName} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1843
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2030
+ field[DBType.Mysql] = () => `${field.C2()} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2031
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1844
2032
  break;
1845
2033
  }
1846
2034
  case SqlType.longblob: {
1847
- field[DBType.Mysql] = `${field.esName} longblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1848
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2035
+ field[DBType.Mysql] = () => `${field.C2()} longblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2036
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1849
2037
  break;
1850
2038
  }
1851
2039
  case SqlType.longtext: {
1852
- field[DBType.Mysql] = `${field.esName} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1853
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2040
+ field[DBType.Mysql] = () => `${field.C2()} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2041
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1854
2042
  break;
1855
2043
  }
1856
2044
 
1857
2045
  case SqlType.set: {
1858
- field[DBType.Mysql] = `${field.esName} set ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1859
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2046
+ field[DBType.Mysql] = () => `${field.C2()} set ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2047
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1860
2048
  break;
1861
2049
  }
1862
2050
  case SqlType.enum: {
1863
- field[DBType.Mysql] = `${field.esName} enum ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1864
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2051
+ field[DBType.Mysql] = () => `${field.C2()} enum ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2052
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1865
2053
  break;
1866
2054
  }
1867
2055
  case SqlType.json: {
1868
- field[DBType.Mysql] = `${field.esName} json ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1869
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2056
+ field[DBType.Mysql] = () => `${field.C2()} json ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2057
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1870
2058
  break;
1871
2059
  }
1872
2060
 
1873
2061
  case SqlType.geometry: {
1874
- field[DBType.Mysql] = `${field.esName} geometry ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1875
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2062
+ field[DBType.Mysql] = () => `${field.C2()} geometry ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2063
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1876
2064
  break;
1877
2065
  }
1878
2066
  case SqlType.point: {
1879
- field[DBType.Mysql] = `${field.esName} point ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1880
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2067
+ field[DBType.Mysql] = () => `${field.C2()} point ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2068
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1881
2069
  break;
1882
2070
  }
1883
2071
  case SqlType.linestring: {
1884
- field[DBType.Mysql] = `${field.esName} linestring ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1885
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2072
+ field[DBType.Mysql] = () => `${field.C2()} linestring ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2073
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1886
2074
  break;
1887
2075
  }
1888
2076
  case SqlType.polygon: {
1889
- field[DBType.Mysql] = `${field.esName} polygon ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1890
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2077
+ field[DBType.Mysql] = () => `${field.C2()} polygon ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2078
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1891
2079
  break;
1892
2080
  }
1893
2081
  case SqlType.multipoint: {
1894
- field[DBType.Mysql] = `${field.esName} multipoint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1895
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2082
+ field[DBType.Mysql] = () => `${field.C2()} multipoint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2083
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1896
2084
  break;
1897
2085
  }
1898
2086
  case SqlType.multilinestring: {
1899
- field[DBType.Mysql] = `${field.esName} multilinestring ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1900
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2087
+ field[DBType.Mysql] = () => `${field.C2()} multilinestring ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2088
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1901
2089
  break;
1902
2090
  }
1903
2091
  case SqlType.multipolygon: {
1904
- field[DBType.Mysql] = `${field.esName} multipolygon ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1905
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2092
+ field[DBType.Mysql] = () => `${field.C2()} multipolygon ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2093
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1906
2094
  break;
1907
2095
  }
1908
2096
  case SqlType.geometrycollection: {
1909
- field[DBType.Mysql] = `${field.esName} geometrycollection ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1910
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
2097
+ field[DBType.Mysql] = () => `${field.C2()} geometrycollection ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
2098
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1911
2099
  break;
1912
2100
  }
1913
2101
  };
@@ -1939,7 +2127,6 @@ export const Field = (config: FieldOption) => {
1939
2127
  if (hasDef) {
1940
2128
  __def[propertyName] = field.def;
1941
2129
  }
1942
-
1943
2130
  Reflect.defineMetadata(_fields, __fields, object);
1944
2131
  Reflect.defineMetadata(_columns, __columns, object);
1945
2132
  Reflect.defineMetadata(_columnsNoId, __columnsNoId, object);
@@ -1962,8 +2149,14 @@ export const DB = (config: ServiceOption) => {
1962
2149
  const __deleteState = Reflect.getMetadata(_deleteState, config.clz.prototype);
1963
2150
  const __index = Reflect.getMetadata(_index, config.clz.prototype);
1964
2151
  const __def = Reflect.getMetadata(_def, config.clz.prototype);
2152
+ const className = config.tableName?.replace(/_(\w)/g, (a: string, b: string) => b.toUpperCase());
2153
+ const ClassName = className?.replace(/\w/, (v: string) => v.toUpperCase());
2154
+ const vueName = config.tableName?.replace(/_/g, '-');
1965
2155
  return class extends constructor {
1966
2156
  [_tableName] = config.tableName;
2157
+ [_className] = className;
2158
+ [_ClassName] = ClassName;
2159
+ [_vueName] = vueName;
1967
2160
  [_daoDBName] = config.dbName;
1968
2161
  [_dbType] = config.dbType ?? DBType.Mysql;
1969
2162
  [_sqlite_version] = config.sqliteVersion;
@@ -1983,14 +2176,17 @@ export const DB = (config: ServiceOption) => {
1983
2176
  option?: MethodOption & {
1984
2177
  finalColumns?: Set<string>;
1985
2178
  tempColumns?: Array<string>;
1986
- def?: boolean;
2179
+ insert?: boolean;
1987
2180
  skipId?: boolean;
2181
+ skipNull?: boolean;
2182
+ skipUndefined?: boolean;
2183
+ skipEmptyString?: boolean;
1988
2184
  onFieldExists?: (K: string, V: any) => void;
1989
2185
  }
1990
2186
  ) => {
1991
2187
  return Object.fromEntries(
1992
2188
  iterare(option?.skipId === true ? __columnsNoId : __columns)
1993
- .map(K => [K, FieldFilter(K as string, data[K as string], __def, option)])
2189
+ .map(K => [K, FieldFilter(K as string, data[K as string], __def, __fields[K as string].uuid === true || __fields[K as string].uuidShort === true, option)])
1994
2190
  .filter(data => {
1995
2191
  if ((data[1] as any)[0] === 1) {
1996
2192
  if (option?.onFieldExists) {
@@ -2022,7 +2218,7 @@ export const DB = (config: ServiceOption) => {
2022
2218
  */
2023
2219
  export function DeclareClass(clz: any, FieldOptions: FieldOption[]) {
2024
2220
  for (const item of FieldOptions) {
2025
- tslib.__decorate([Field(item)], clz.prototype, item.name, void 0);
2221
+ tslib.__decorate([Field(item)], clz.prototype, item.P, void 0);
2026
2222
  }
2027
2223
  }
2028
2224
  /**
@@ -2052,6 +2248,9 @@ export function DeclareService(clz: any, config: ServiceOption) {
2052
2248
  */
2053
2249
  export class SqlService<T extends object> {
2054
2250
  private [_tableName]?: string;
2251
+ private [_className]?: string;
2252
+ private [_ClassName]?: string;
2253
+ private [_vueName]?: string;
2055
2254
  private [_daoDBName]?: string;
2056
2255
  private [_ids]?: string[];
2057
2256
  private [_fields]?: Record<string, AField>;
@@ -2064,12 +2263,21 @@ export class SqlService<T extends object> {
2064
2263
  private [_sqlite_version]?: string;
2065
2264
  private [_index]?: string[];
2066
2265
  private [_def]?: Partial<T>;
2067
- private [_transformer]?: (data: Partial<T>, option?: MethodOption & { finalColumns?: Set<string>; def?: boolean; skipId?: boolean; onFieldExists?: (K: string, V: any) => void; }) => Partial<T>;
2266
+ public [_transformer]?: <L = T>(data: Partial<L>, option?: MethodOption & {
2267
+ finalColumns?: Set<string>;
2268
+ insert?: boolean;
2269
+ skipId?: boolean;
2270
+ skipNull?: boolean;
2271
+ skipUndefined?: boolean;
2272
+ skipEmptyString?: boolean;
2273
+ onFieldExists?: (K: string, V: any) => void;
2274
+ }) => Partial<T>;
2068
2275
  private _insert(
2069
2276
  datas: Partial<T>[],
2070
2277
  option: MethodOption & {
2071
2278
  mode?: InsertMode;
2072
2279
  existConditionOtherThanIds?: (keyof T)[];
2280
+ replaceWithDef?: boolean;
2073
2281
  }): { sql: string; params?: any[] }[] {
2074
2282
  const sqls: { sql: string; params?: any[] }[] = [];
2075
2283
  const tableName = Sqlstring.escapeId(option!.tableName);
@@ -2078,28 +2286,37 @@ export class SqlService<T extends object> {
2078
2286
  const conditions = option!.existConditionOtherThanIds || this[_ids];
2079
2287
  Throw.if(!conditions, 'not found where condition for insertIfNotExists!');
2080
2288
  Throw.if(conditions!.length === 0, 'insertIfNotExists must have not null where!');
2081
- const where = iterare<string>(conditions! as string[]).map(c => `${this[_fields]![c]?.esName} = ?`).join(' AND ');
2289
+ const where = iterare<string>(conditions! as string[]).map(c => `${this[_fields]![c]?.C2()} = ?`).join(' AND ');
2082
2290
  const finalColumns = new Set<string>();
2083
2291
  const whereColumns = conditions! as string[];
2084
- const params = datas
2085
- .map(data => this[_transformer]!(data, { ...option, finalColumns, def: true }))
2086
- .flatMap(data => {
2087
- const result: any[] = [];
2292
+ const params: any[] = [];
2293
+ const questMarks = datas
2294
+ .map(data => this[_transformer]!(data, { ...option, finalColumns, insert: true }))
2295
+ .map(data => {
2088
2296
  const questMark = new Array<string>();
2089
2297
  for (const column of finalColumns) {
2090
- questMark.push('?');
2091
- result.push(
2092
- data.hasOwnProperty(column)
2093
- ? data[column]
2094
- : this[_def] && this[_def].hasOwnProperty(column)
2095
- ? this[_def][column]
2096
- : null
2097
- );
2298
+ const V = data.hasOwnProperty(column)
2299
+ ? data[column]
2300
+ : this[_def] && this[_def].hasOwnProperty(column)
2301
+ ? this[_def][column]
2302
+ : null;
2303
+ if (V === null) {
2304
+ const field = this[_fields]![column];
2305
+ if (field?.uuid) {
2306
+ questMark.push('UUID()');
2307
+ } else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2308
+ questMark.push('UUID_SHORT()');
2309
+ } else {
2310
+ questMark.push('?');
2311
+ params.push(V);
2312
+ }
2313
+ } else {
2314
+ questMark.push('?');
2315
+ params.push(V);
2316
+ }
2098
2317
  }
2099
-
2100
2318
  for (const column of whereColumns) {
2101
- questMark.push('?');
2102
- result.push(
2319
+ params.push(
2103
2320
  data.hasOwnProperty(column)
2104
2321
  ? data[column]
2105
2322
  : this[_def] && this[_def].hasOwnProperty(column)
@@ -2107,118 +2324,147 @@ export class SqlService<T extends object> {
2107
2324
  : null
2108
2325
  );
2109
2326
  }
2110
- return result;
2327
+ return `SELECT ${questMark.join(',')} FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ${tableName} WHERE ${where})`;
2111
2328
  });
2112
- const quests = new Array<string>(finalColumns.size).fill('?').join(',');
2113
- const columnNames = iterare<string>(finalColumns).map(i => this[_fields]![i]?.esName).join(',');
2114
- const selects = iterare<string>(new Array<string>(datas.length)).map(() => `SELECT ${quests} FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ${tableName} WHERE ${where})`).join(' UNION ALL ');
2115
- const sql = `INSERT INTO
2116
- ${tableName}
2117
- (${columnNames})
2118
- ${selects};`;
2329
+ const columnNames = iterare<string>(finalColumns).map(i => this[_fields]![i]?.C2()).join(',');
2330
+ const sql = format(`INSERT INTO
2331
+ ${tableName}
2332
+ (${columnNames})
2333
+ ${questMarks.join(' UNION ALL ')};`);
2119
2334
  sqls.push({ sql, params });
2335
+ break;
2120
2336
  }
2121
2337
  case InsertMode.Replace: {
2122
2338
  const finalColumns = new Set<string>();
2123
- const params = datas
2124
- .map(data => this[_transformer]!(data, { ...option, finalColumns, def: true }))
2125
- .flatMap(data => {
2126
- const result: any[] = [];
2339
+ const params: any[] = [];
2340
+ const questMarks = datas
2341
+ .map(data => this[_transformer]!(data, { ...option, finalColumns, insert: true }))
2342
+ .map(data => {
2127
2343
  const questMark = new Array<string>();
2128
2344
  for (const column of finalColumns) {
2129
- questMark.push('?');
2130
- result.push(
2131
- data.hasOwnProperty(column)
2132
- ? data[column]
2133
- : this[_def] && this[_def].hasOwnProperty(column)
2134
- ? this[_def][column]
2135
- : null
2136
- );
2345
+ const V = data.hasOwnProperty(column)
2346
+ ? data[column]
2347
+ : this[_def] && this[_def].hasOwnProperty(column)
2348
+ ? this[_def][column]
2349
+ : null;
2350
+ if (V === null) {
2351
+ const field = this[_fields]![column];
2352
+ if (field?.uuid) {
2353
+ questMark.push('UUID()');
2354
+ } else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2355
+ questMark.push('UUID_SHORT()');
2356
+ } else {
2357
+ questMark.push('?');
2358
+ params.push(V);
2359
+ }
2360
+ } else {
2361
+ questMark.push('?');
2362
+ params.push(V);
2363
+ }
2137
2364
  }
2138
- return result;
2365
+ return `(${questMark.join(',')})`;
2139
2366
  });
2140
- const quests = new Array<string>(finalColumns.size).fill('?').join(',');
2141
- const columnNames = iterare<string>(finalColumns).map(i => this[_fields]![i]?.esName).join(',');
2142
- const questMarks = iterare<string>(new Array<string>(datas.length)).map(() => `(${quests})`).join(',');
2143
- const sql = `
2367
+ const columnNames = iterare(finalColumns).map(i => this[_fields]![i]?.C2()).join(',');
2368
+ const sql = format(`
2144
2369
  ${this[_dbType] === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
2145
2370
  ${tableName}
2146
2371
  (${columnNames})
2147
2372
  VALUES ${questMarks};
2148
- `;
2373
+ `);
2149
2374
  sqls.push({ sql, params });
2375
+ break;
2150
2376
  }
2151
2377
  case InsertMode.Insert: {
2152
2378
  const finalColumns = new Set<string>();
2153
- const params = datas
2154
- .map(data => this[_transformer]!(data, { ...option, finalColumns, def: true }))
2155
- .flatMap(data => {
2156
- const result: any[] = [];
2379
+ const params: any[] = [];
2380
+ const questMarks = datas
2381
+ .map(data => this[_transformer]!(data, { ...option, finalColumns, insert: true }))
2382
+ .map(data => {
2157
2383
  const questMark = new Array<string>();
2158
2384
  for (const column of finalColumns) {
2159
- questMark.push('?');
2160
- result.push(
2161
- data.hasOwnProperty(column)
2162
- ? data[column]
2163
- : this[_def] && this[_def].hasOwnProperty(column)
2164
- ? this[_def][column]
2165
- : null
2166
- );
2385
+ const V = data.hasOwnProperty(column)
2386
+ ? data[column]
2387
+ : this[_def] && this[_def].hasOwnProperty(column)
2388
+ ? this[_def][column]
2389
+ : null;
2390
+ if (V === null) {
2391
+ const field = this[_fields]![column];
2392
+ if (field?.uuid) {
2393
+ questMark.push('UUID()');
2394
+ } else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2395
+ questMark.push('UUID_SHORT()');
2396
+ } else {
2397
+ questMark.push('?');
2398
+ params.push(V);
2399
+ }
2400
+ } else {
2401
+ questMark.push('?');
2402
+ params.push(V);
2403
+ }
2167
2404
  }
2168
- return result;
2405
+ return `(${questMark.join(',')})`;
2169
2406
  });
2170
- const quests = new Array<string>(finalColumns.size).fill('?').join(',');
2171
- const columnNames = iterare(finalColumns).map(i => this[_fields]![i]?.esName).join(',');
2172
- const questMarks = iterare(new Array<string>(datas.length)).map(() => `(${quests})`).join(',');
2173
- const sql = `
2407
+ const columnNames = iterare(finalColumns).map(i => this[_fields]![i]?.C2()).join(',');
2408
+ const sql = format(`
2174
2409
  INSERT INTO
2175
2410
  ${tableName}
2176
2411
  (${columnNames})
2177
2412
  VALUES ${questMarks};
2178
- `;
2413
+ `);
2414
+
2179
2415
  sqls.push({ sql, params });
2416
+ break;
2180
2417
  }
2181
2418
  case InsertMode.InsertWithTempTable: {
2182
2419
  const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
2183
2420
  const tableTempESC = Sqlstring.escapeId(tableTemp);
2184
2421
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2185
2422
  const finalColumns = new Set<string>();
2186
- const params = datas
2187
- .map(data => this[_transformer]!(data, { ...option, finalColumns, def: true }))
2188
- .flatMap(data => {
2189
- const result: any[] = [];
2423
+ const params: any[] = [];
2424
+ const questMarks = datas
2425
+ .map(data => this[_transformer]!(data, { ...option, finalColumns, insert: true }))
2426
+ .map(data => {
2190
2427
  const questMark = new Array<string>();
2191
2428
  for (const column of finalColumns) {
2192
- questMark.push('?');
2193
- result.push(
2194
- data.hasOwnProperty(column)
2195
- ? data[column]
2196
- : this[_def] && this[_def].hasOwnProperty(column)
2197
- ? this[_def][column]
2198
- : null
2199
- );
2429
+ const V = data.hasOwnProperty(column)
2430
+ ? data[column]
2431
+ : this[_def] && this[_def].hasOwnProperty(column)
2432
+ ? this[_def][column]
2433
+ : null;
2434
+ if (V === null) {
2435
+ const field = this[_fields]![column];
2436
+ if (field?.uuid) {
2437
+ questMark.push('UUID()');
2438
+ } else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2439
+ questMark.push('UUID_SHORT()');
2440
+ } else {
2441
+ questMark.push('?');
2442
+ params.push(V);
2443
+ }
2444
+ } else {
2445
+ questMark.push('?');
2446
+ params.push(V);
2447
+ }
2200
2448
  }
2201
- return result;
2449
+ return `(${questMark.join(',')})`
2202
2450
  });
2203
2451
  const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: Array.from(finalColumns) })!;
2204
2452
  sqls.push(..._sqls);
2205
-
2206
- const quests = new Array<string>(finalColumns.size).fill('?').join(',');
2207
- const columnNames = iterare(finalColumns).map(i => this[_fields]![i]?.esName).join(',');
2208
- const questMarks = iterare(new Array<string>(datas.length)).map(() => `(${quests})`).join(',');
2453
+ const columnNames = iterare(finalColumns).map(i => this[_fields]![i]?.C2()).join(',');
2209
2454
  sqls.push({
2210
- sql: `
2455
+ sql: format(`
2211
2456
  INSERT INTO
2212
2457
  ${tableTemp}
2213
2458
  (${columnNames})
2214
2459
  VALUES ${questMarks};
2215
- `, params
2460
+ `), params
2216
2461
  });
2217
2462
  sqls.push({
2218
- sql: `INSERT INTO ${Sqlstring.escapeId(option.tableName)} (${columnNames})
2219
- SELECT ${columnNames} FROM ${tableTemp};`
2463
+ sql: format(`INSERT INTO ${Sqlstring.escapeId(option.tableName)} (${columnNames})
2464
+ SELECT ${columnNames} FROM ${tableTemp};`)
2220
2465
  });
2221
2466
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2467
+ break;
2222
2468
  }
2223
2469
  }
2224
2470
  return sqls;
@@ -2244,18 +2490,19 @@ export class SqlService<T extends object> {
2244
2490
  2. `insertIfNotExists`: 通过主键或者existConditionOtherThanIds字段判断数据是否存在,不存在才插入,存在则不执行
2245
2491
  3. `replace`: 只支持用主键判断, 存在更新, 不存在插入
2246
2492
  11. `existConditionOtherThanIds`: insertIfNotExists时判断同一记录的字段名称,默认情况下按照ID判断,设置existConditionOtherThanIds后,不用id
2493
+ 12. `replaceWithDef` replace时,是否带入默认值? 默认true
2247
2494
  ### 返回值是最后一次插入的主键ID,对于自增ID表适用
2248
2495
  1. 如果主键是自增批量操作,且期望返回所有记录的ID,那么需要设置 `option 中的 every = true`,此时效率降低
2249
2496
  * @param {{[P in keyof T]?: T[P]}} data
2250
2497
  * @param {MethodOption} [option]
2251
2498
  * @memberof SqlServer
2252
2499
  */
2253
- insert(option: MethodOption & { data: Partial<T>; sync?: SyncMode.Async; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; }): Promise<bigint>;
2254
- insert(option: MethodOption & { data: Partial<T>[]; sync?: SyncMode.Async; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; }): Promise<bigint[]>;
2255
- insert(option: MethodOption & { data: Partial<T>; sync: SyncMode.Sync; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; }): bigint;
2256
- insert(option: MethodOption & { data: Partial<T>[]; sync: SyncMode.Sync; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; }): bigint[];
2500
+ insert(option: MethodOption & { data: Partial<T>; sync?: SyncMode.Async; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; replaceWithDef?: boolean; }): Promise<bigint>;
2501
+ insert(option: MethodOption & { data: Partial<T>[]; sync?: SyncMode.Async; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; replaceWithDef?: boolean; }): Promise<bigint[]>;
2502
+ insert(option: MethodOption & { data: Partial<T>; sync: SyncMode.Sync; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; replaceWithDef?: boolean; }): bigint;
2503
+ insert(option: MethodOption & { data: Partial<T>[]; sync: SyncMode.Sync; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; replaceWithDef?: boolean; }): bigint[];
2257
2504
  @P<T>()
2258
- insert(option: MethodOption & { data: Partial<T> | Array<Partial<T>>; sync?: SyncMode; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; }): bigint | bigint[] | Promise<bigint> | Promise<bigint[]> {
2505
+ insert(option: MethodOption & { data: Partial<T> | Array<Partial<T>>; sync?: SyncMode; mode?: InsertMode; existConditionOtherThanIds?: (keyof T)[]; every?: boolean; temp?: boolean; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; maxDeal?: number; replaceWithDef?: boolean; }): bigint | bigint[] | Promise<bigint> | Promise<bigint[]> {
2259
2506
  option.mode ??= InsertMode.Insert;
2260
2507
  const isArray = option.data instanceof Array;
2261
2508
  const datas = option.data instanceof Array ? option.data : [option.data];
@@ -2278,7 +2525,7 @@ export class SqlService<T extends object> {
2278
2525
  if (isArray) return result;
2279
2526
  else return result[0]!;
2280
2527
  };
2281
- if (option?.conn?.[_inTransaction] === true) {
2528
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2282
2529
  return fn();
2283
2530
  } else {
2284
2531
  return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn)!;
@@ -2303,11 +2550,15 @@ export class SqlService<T extends object> {
2303
2550
  return result;
2304
2551
  }, option?.conn);
2305
2552
  };
2306
- return new Promise<bigint[]>(async (resolve) => {
2307
- if (option?.conn?.[_inTransaction] === true) {
2308
- resolve((await fn())!);
2309
- } else {
2310
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2553
+ return new Promise<bigint[]>(async (resolve, reject) => {
2554
+ try {
2555
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2556
+ resolve((await fn())!);
2557
+ } else {
2558
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2559
+ }
2560
+ } catch (error) {
2561
+ reject(error);
2311
2562
  }
2312
2563
  });
2313
2564
  } else {
@@ -2328,11 +2579,15 @@ export class SqlService<T extends object> {
2328
2579
  );
2329
2580
  return result[0]!;
2330
2581
  };
2331
- return new Promise<bigint>(async (resolve) => {
2332
- if (option?.conn?.[_inTransaction] === true) {
2333
- resolve((await fn())!);
2334
- } else {
2335
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2582
+ return new Promise<bigint>(async (resolve, reject) => {
2583
+ try {
2584
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2585
+ resolve((await fn())!);
2586
+ } else {
2587
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2588
+ }
2589
+ } catch (error) {
2590
+ reject(error);
2336
2591
  }
2337
2592
  });
2338
2593
  }
@@ -2341,7 +2596,7 @@ export class SqlService<T extends object> {
2341
2596
  private _update(datas: Array<Partial<T>>, option: MethodOption): { sql: string; params?: any[] }[] {
2342
2597
  const sqls: { sql: string; params?: any[] }[] = [];
2343
2598
  const tableName = Sqlstring.escapeId(option?.tableName);
2344
- const where = `WHEN ${iterare(this[_ids]!).map(c => `${this[_fields]![c]?.esName} = ?`).join(' AND ')} THEN ?`;
2599
+ const where = `WHEN ${iterare(this[_ids]!).map(c => `${this[_fields]![c]?.C2()} = ?`).join(' AND ')} THEN ?`;
2345
2600
  const columnMaps: Record<string, {
2346
2601
  where: string[];
2347
2602
  params: any[];
@@ -2366,13 +2621,13 @@ export class SqlService<T extends object> {
2366
2621
  }
2367
2622
  );
2368
2623
  }
2369
- const sql = `UPDATE ${tableName} SET ${iterare(this[_columnsNoId]!)
2624
+ const sql = format(`UPDATE ${tableName} SET ${iterare(this[_columnsNoId]!)
2370
2625
  .filter(K => columnMaps[K]!.where.length > 0)
2371
2626
  .map(K => {
2372
2627
  params.push(...columnMaps[K]!.params);
2373
- return `${this[_fields]![K]?.esName} = CASE ${columnMaps[K]!.where.join(' ')} ELSE ${this[_fields]![K]?.esName} END`
2628
+ return `${this[_fields]![K]?.C2()} = CASE ${columnMaps[K]!.where.join(' ')} ELSE ${this[_fields]![K]?.C2()} END`
2374
2629
  })
2375
- .join(',')};`
2630
+ .join(',')};`);
2376
2631
  sqls.push({ sql, params });
2377
2632
  return sqls;
2378
2633
  }
@@ -2418,7 +2673,7 @@ export class SqlService<T extends object> {
2418
2673
  );
2419
2674
  return result.reduce((a, b) => a + b);
2420
2675
  };
2421
- if (option?.conn?.[_inTransaction] === true) {
2676
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2422
2677
  return fn();
2423
2678
  } else {
2424
2679
  return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn)!;
@@ -2441,11 +2696,15 @@ export class SqlService<T extends object> {
2441
2696
  );
2442
2697
  return result.reduce((a, b) => a + b);
2443
2698
  };
2444
- return new Promise<number>(async (resolve) => {
2445
- if (option?.conn?.[_inTransaction] === true) {
2446
- resolve((await fn())!);
2447
- } else {
2448
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2699
+ return new Promise<number>(async (resolve, reject) => {
2700
+ try {
2701
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2702
+ resolve((await fn())!);
2703
+ } else {
2704
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2705
+ }
2706
+ } catch (error) {
2707
+ reject(error);
2449
2708
  }
2450
2709
  });
2451
2710
  }
@@ -2507,19 +2766,19 @@ export class SqlService<T extends object> {
2507
2766
  return `(
2508
2767
  ${Object.entries(where).map(([K, V]) => {
2509
2768
  params.push(V);
2510
- return `${K} = ?`;
2769
+ return `${this[_fields]![K]?.C2()} = ?`;
2511
2770
  }).join(' AND ')}
2512
2771
  )`;
2513
2772
  }).join(' OR ');
2514
2773
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2515
2774
  sqls.push({
2516
- sql: `
2517
- UPDATE ${tableNameESC} SET ${this[_fields]![this[_stateFileName]]?.esName} = ${Sqlstring.escape(this[_deleteState])}
2775
+ sql: format(`
2776
+ UPDATE ${tableNameESC} SET ${this[_fields]![this[_stateFileName]]?.C2()} = ${Sqlstring.escape(this[_deleteState])}
2518
2777
  WHERE ${whereSql};
2519
- `, params
2778
+ `), params
2520
2779
  });
2521
2780
  } else {
2522
- sqls.push({ sql: `DELETE FROM ${tableNameESC} WHERE ${whereSql};`, params });
2781
+ sqls.push({ sql: format(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`), params });
2523
2782
  }
2524
2783
  } else {
2525
2784
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
@@ -2530,26 +2789,28 @@ export class SqlService<T extends object> {
2530
2789
  case DBType.Mysql: {
2531
2790
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2532
2791
  sqls.push({
2533
- sql: `UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields]![K]?.esName} = b.${this[_fields]![K]?.esName}`).join(' AND ')}
2534
- SET a.${this[_fields]![this[_stateFileName]]?.esName} = ${Sqlstring.escape(this[_deleteState])};`
2792
+ sql: format(`UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields]![K]?.C2()} = b.${this[_fields]![K]?.C2()}`).join(' AND ')}
2793
+ SET a.${this[_fields]![this[_stateFileName]]?.C2()} = ${Sqlstring.escape(this[_deleteState])};`)
2535
2794
  });
2536
2795
  } else {
2537
2796
  sqls.push({
2538
- sql: `DELETE a.* FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields]![K]?.esName} = b.${this[_fields]![K]?.esName}`).join(' AND ')};`
2797
+ sql: format(`DELETE a.* FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields]![K]?.C2()} = b.${this[_fields]![K]?.C2()}`).join(' AND ')};`)
2539
2798
  });
2540
2799
  }
2800
+ break;
2541
2801
  }
2542
2802
  case DBType.Sqlite:
2543
2803
  case DBType.SqliteRemote: {
2544
- const columnNames = iterare(delWhere).map(K => this[_fields]![K]?.esName).join(',');
2804
+ const columnNames = iterare(delWhere).map(K => this[_fields]![K]?.C2()).join(',');
2545
2805
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2546
2806
  sqls.push({
2547
- sql: `UPDATE ${tableNameESC} SET ${this[_fields]![this[_stateFileName]]?.esName} = ${Sqlstring.escape(this[_deleteState])}
2548
- WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`
2807
+ sql: format(`UPDATE ${tableNameESC} SET ${this[_fields]![this[_stateFileName]]?.C2()} = ${Sqlstring.escape(this[_deleteState])}
2808
+ WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`)
2549
2809
  });
2550
2810
  } else {
2551
- sqls.push({ sql: `DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});` });
2811
+ sqls.push({ sql: format(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`) });
2552
2812
  }
2813
+ break;
2553
2814
  }
2554
2815
  }
2555
2816
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
@@ -2564,7 +2825,7 @@ export class SqlService<T extends object> {
2564
2825
  }
2565
2826
  return result;
2566
2827
  };
2567
- if (option?.conn?.[_inTransaction] === true) {
2828
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2568
2829
  return fn();
2569
2830
  } else {
2570
2831
  return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn)!;
@@ -2578,11 +2839,15 @@ export class SqlService<T extends object> {
2578
2839
  }
2579
2840
  return result;
2580
2841
  };
2581
- return new Promise<number>(async (resolve) => {
2582
- if (option?.conn?.[_inTransaction] === true) {
2583
- resolve((await fn())!);
2584
- } else {
2585
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2842
+ return new Promise<number>(async (resolve, reject) => {
2843
+ try {
2844
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2845
+ resolve((await fn())!);
2846
+ } else {
2847
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())!), option?.conn);
2848
+ }
2849
+ } catch (error) {
2850
+ reject(error);
2586
2851
  }
2587
2852
  });
2588
2853
  }
@@ -2629,20 +2894,20 @@ export class SqlService<T extends object> {
2629
2894
  8. `dao`: 永远不需要传入该值
2630
2895
 
2631
2896
  */
2632
- template(option: MethodOption & { templateResult?: TemplateResult.AssertOne; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): Promise<T>;
2633
- template(option: MethodOption & { sync: SyncMode.Sync; templateResult?: TemplateResult.AssertOne; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): T;
2634
- template(option: MethodOption & { sync: SyncMode.Async; templateResult?: TemplateResult.AssertOne; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): Promise<T>;
2635
- template(option: MethodOption & { templateResult: TemplateResult.Count; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): Promise<number>;
2636
- template(option: MethodOption & { sync: SyncMode.Sync; templateResult: TemplateResult.Count; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): number;
2637
- template(option: MethodOption & { sync: SyncMode.Async; templateResult: TemplateResult.Count; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): Promise<number>;
2638
- template(option: MethodOption & { templateResult: TemplateResult.NotSureOne; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): Promise<T | null>;
2639
- template(option: MethodOption & { sync: SyncMode.Sync; templateResult: TemplateResult.NotSureOne; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): T | null;
2640
- template(option: MethodOption & { sync: SyncMode.Async; templateResult: TemplateResult.NotSureOne; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): Promise<T | null>;
2641
- template(option: MethodOption & { templateResult: TemplateResult.Many; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): Promise<T[]>;
2642
- template(option: MethodOption & { sync: SyncMode.Sync; templateResult: TemplateResult.Many; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): T[];
2643
- template(option: MethodOption & { sync: SyncMode.Async; templateResult: TemplateResult.Many; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): Promise<T[]>;
2897
+ template<L = T>(option: MethodOption & { templateResult?: TemplateResult.AssertOne; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): Promise<L>;
2898
+ template<L = T>(option: MethodOption & { sync: SyncMode.Sync; templateResult?: TemplateResult.AssertOne; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): L;
2899
+ template<L = T>(option: MethodOption & { sync: SyncMode.Async; templateResult?: TemplateResult.AssertOne; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): Promise<L>;
2900
+ template<L = T>(option: MethodOption & { templateResult: TemplateResult.Count; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): Promise<number>;
2901
+ template<L = T>(option: MethodOption & { sync: SyncMode.Sync; templateResult: TemplateResult.Count; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): number;
2902
+ template<L = T>(option: MethodOption & { sync: SyncMode.Async; templateResult: TemplateResult.Count; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): Promise<number>;
2903
+ template<L = T>(option: MethodOption & { templateResult: TemplateResult.NotSureOne; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): Promise<L | null>;
2904
+ template<L = T>(option: MethodOption & { sync: SyncMode.Sync; templateResult: TemplateResult.NotSureOne; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): L | null;
2905
+ template<L = T>(option: MethodOption & { sync: SyncMode.Async; templateResult: TemplateResult.NotSureOne; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): Promise<L | null>;
2906
+ template<L = T>(option: MethodOption & { templateResult: TemplateResult.Many; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): Promise<L[]>;
2907
+ template<L = T>(option: MethodOption & { sync: SyncMode.Sync; templateResult: TemplateResult.Many; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): L[];
2908
+ template<L = T>(option: MethodOption & { sync: SyncMode.Async; templateResult: TemplateResult.Many; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): Promise<L[]>;
2644
2909
  @P<T>()
2645
- template(option: MethodOption & { sync?: SyncMode; templateResult?: TemplateResult; id?: string | number | Array<string | number>; where?: Partial<T> | Array<Partial<T>>; mode?: SelectMode; error?: string; columns?: (keyof T)[]; }): number | T | null | T[] | Promise<number | T | null | T[]> {
2910
+ template<L = T>(option: MethodOption & { sync?: SyncMode; templateResult?: TemplateResult; id?: string | number | Array<string | number>; where?: Partial<L> | Array<Partial<L>>; skipUndefined?: boolean; skipNull?: boolean; skipEmptyString?: boolean; mode?: SelectMode; error?: string; columns?: (keyof L)[]; }): number | L | null | L[] | Promise<number | L | null | L[]> {
2646
2911
  Throw.if(!!this[_ids] && this[_ids].length > 1 && !option.where, 'muit id must set where!');
2647
2912
  Throw.if((!this[_ids] || this[_ids].length === 0) && !option.where, 'if not set id on class, must set where!');
2648
2913
  Throw.if(!option.id && !option.where, 'not found id or where!');
@@ -2659,30 +2924,30 @@ export class SqlService<T extends object> {
2659
2924
  if (option.id) {
2660
2925
  const idName = this[_ids]![0]!;
2661
2926
  const ids = option.id instanceof Array ? option.id : [option.id];
2662
- option.where = ids.map(i => ({ [idName]: i })) as Array<Partial<T>>;
2927
+ option.where = ids.map(i => ({ [idName]: i })) as Array<Partial<L>>;
2663
2928
  }
2664
- const columns = option.templateResult === TemplateResult.Count ? 'COUNT(1) ct' : iterare((option.columns as unknown as string[] ?? this[_columns])!).map((K: any) => `a.${this[_fields]![K]?.esName}`).join(',');
2929
+ const columns = option.templateResult === TemplateResult.Count ? 'COUNT(1) ct' : iterare((option.columns as unknown as string[] ?? this[_columns])!).map((K: any) => `a.${this[_fields]![K]?.C3()}`).join(',');
2665
2930
  const wheres = option.where instanceof Array ? option.where : [option.where!];
2666
2931
  const sqls: { sql: string; params?: any[] }[] = [];
2667
2932
  let resultIndex = -1;
2668
2933
  if (option.mode === SelectMode.Common) {
2669
2934
  const params = new Array<any>();
2670
- const whereSql = iterare(wheres).map(where => {
2935
+ const whereSql = format(iterare(wheres).map(where => this[_transformer]!(where, option)).map(where => {
2671
2936
  return `SELECT ${columns} FROM ${tableNameESC} a WHERE
2672
2937
  ${Object.entries(where).map(([K, V]) => {
2673
2938
  params.push(V);
2674
- return `${K} = ?`;
2939
+ return `${this[_fields]![K]?.C2()} = ?`;
2675
2940
  }).join(' AND ')}`;
2676
- }).join(' UNION ALL ');
2941
+ }).join(' UNION ALL '));
2677
2942
  sqls.push({ sql: whereSql, params });
2678
2943
  resultIndex = 0;
2679
2944
  } else {
2680
2945
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2681
2946
  const delWhere = Object.keys(wheres[0] as unknown as any);
2682
- const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' })!;
2947
+ const _sqls = this._createTable<L>({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' })!;
2683
2948
  sqls.push(..._sqls);
2684
2949
  resultIndex = sqls.length;
2685
- 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 ')};` });
2950
+ sqls.push({ sql: format(`SELECT ${columns} FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields]![K]?.C2()} = b.${this[_fields]![K]?.C2()}`).join(' AND ')};`) });
2686
2951
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2687
2952
  }
2688
2953
 
@@ -2697,21 +2962,25 @@ export class SqlService<T extends object> {
2697
2962
  }
2698
2963
  return this._template(option.templateResult, result, option.error);
2699
2964
  } else {
2700
- return new Promise<T | null | T[]>(async (resolve) => {
2701
- let result: any;
2702
- for (let i = 0; i < sqls.length; i++) {
2703
- if (i === resultIndex) {
2704
- result = await option!.conn!.query(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2705
- } else {
2706
- await option!.conn!.execute(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2965
+ return new Promise<L | null | L[]>(async (resolve, reject) => {
2966
+ try {
2967
+ let result: any;
2968
+ for (let i = 0; i < sqls.length; i++) {
2969
+ if (i === resultIndex) {
2970
+ result = await option!.conn!.query(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2971
+ } else {
2972
+ await option!.conn!.execute(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2973
+ }
2707
2974
  }
2975
+ resolve(this._template(option.templateResult!, result, option.error));
2976
+ } catch (error) {
2977
+ reject(error);
2708
2978
  }
2709
- resolve(this._template(option.templateResult!, result, option.error));
2710
2979
  });
2711
2980
  }
2712
2981
  }
2713
2982
 
2714
- private _select<L = T>(templateResult: SelectResult, result: any, def: L | null, errorMsg?: string, multiple?: boolean) {
2983
+ private _select<L = T>(templateResult: SelectResult, result: any, def: L | null, errorMsg?: string, multiple?: boolean, hump?: boolean) {
2715
2984
  if (multiple === true) {
2716
2985
  switch (templateResult) {
2717
2986
  case SelectResult.One_Row_One_Column_NotSure: {
@@ -2728,12 +2997,18 @@ export class SqlService<T extends object> {
2728
2997
  }
2729
2998
  case SelectResult.One_Row_Many_Column_NotSure: {
2730
2999
  try {
3000
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
3001
+ return result.map((r: any) => C2P2(r[0]) as L);
3002
+ }
2731
3003
  return result.map((r: any) => r[0] as L);
2732
3004
  } catch (error) {
2733
3005
  }
2734
3006
  }
2735
3007
  case SelectResult.One_Row_Many_Column_Assert: {
2736
3008
  try {
3009
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
3010
+ return iterare(result).map((r: any) => C2P2(r[0]) as L).filter((r: L) => r !== null).toArray();
3011
+ }
2737
3012
  return iterare(result).map((r: any) => r[0] as L).filter((r: L) => r !== null).toArray();
2738
3013
  } catch (error) {
2739
3014
  }
@@ -2745,7 +3020,11 @@ export class SqlService<T extends object> {
2745
3020
  }
2746
3021
  }
2747
3022
  case SelectResult.Many_Row_Many_Column: {
2748
- return result as L[];
3023
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
3024
+ return iterare(result).map((r: any) => r.map((rr: any) => C2P2(rr) as L)).toArray();
3025
+ } else {
3026
+ return result as L[];
3027
+ }
2749
3028
  }
2750
3029
  }
2751
3030
  } else {
@@ -2766,12 +3045,21 @@ export class SqlService<T extends object> {
2766
3045
  }
2767
3046
  }
2768
3047
  case SelectResult.One_Row_Many_Column_NotSure: {
2769
- return (result[0] as L) ?? null;
3048
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
3049
+ return (C2P2(result[0]) as L) ?? null;
3050
+ } else {
3051
+ return (result[0] as L) ?? null;
3052
+ }
3053
+
2770
3054
  }
2771
3055
  case SelectResult.One_Row_Many_Column_Assert: {
2772
3056
  const data = result[0] as L;
2773
- Throw.if(data === null, errorMsg ?? 'not found data!');
2774
- return data ?? null;
3057
+ Throw.if(data === null || data === undefined, errorMsg ?? 'not found data!');
3058
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
3059
+ return C2P2(data as any) ?? null;
3060
+ } else {
3061
+ return data ?? null;
3062
+ }
2775
3063
  }
2776
3064
  case SelectResult.Many_Row_One_Column: {
2777
3065
  try {
@@ -2781,7 +3069,11 @@ export class SqlService<T extends object> {
2781
3069
  }
2782
3070
  }
2783
3071
  case SelectResult.Many_Row_Many_Column: {
2784
- return result as L[];
3072
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
3073
+ return iterare(result).map((r: any) => C2P2(r) as L).toArray();
3074
+ } else {
3075
+ return result as L[];
3076
+ }
2785
3077
  }
2786
3078
  }
2787
3079
  }
@@ -2813,20 +3105,19 @@ export class SqlService<T extends object> {
2813
3105
  9. `dao`: 永远不需要传入该值
2814
3106
 
2815
3107
  */
2816
- select<L = T>(option: MethodOption & { sync?: SyncMode.Async; selectResult?: SelectResult.Many_Row_Many_Column | SelectResult.Many_Row_One_Column; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string }): Promise<L[]>;
2817
- select<L = T>(option: MethodOption & { sync?: SyncMode.Async; selectResult: SelectResult.One_Row_Many_Column_Assert | SelectResult.One_Row_One_Column_Assert; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string; }): Promise<L>;
2818
- select<L = T>(option: MethodOption & { sync?: SyncMode.Async; selectResult: SelectResult.One_Row_Many_Column_NotSure | SelectResult.One_Row_One_Column_NotSure; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string }): Promise<L | null>;
2819
- select<L = T>(option: MethodOption & { sync: SyncMode.Sync; selectResult?: SelectResult.Many_Row_Many_Column | SelectResult.Many_Row_One_Column; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string }): L[];
2820
- select<L = T>(option: MethodOption & { sync: SyncMode.Sync; selectResult: SelectResult.One_Row_Many_Column_Assert | SelectResult.One_Row_One_Column_Assert; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string; }): L;
2821
- select<L = T>(option: MethodOption & { sync: SyncMode.Sync; selectResult: SelectResult.One_Row_Many_Column_NotSure | SelectResult.One_Row_One_Column_NotSure; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string }): L | null;
3108
+ select<L = T>(option: MethodOption & { hump?: boolean; sync?: SyncMode.Async; selectResult?: SelectResult.Many_Row_Many_Column | SelectResult.Many_Row_One_Column; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string }): Promise<L[]>;
3109
+ select<L = T>(option: MethodOption & { hump?: boolean; sync?: SyncMode.Async; selectResult: SelectResult.One_Row_Many_Column_Assert | SelectResult.One_Row_One_Column_Assert; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string; }): Promise<L>;
3110
+ select<L = T>(option: MethodOption & { hump?: boolean; sync?: SyncMode.Async; selectResult: SelectResult.One_Row_Many_Column_NotSure | SelectResult.One_Row_One_Column_NotSure; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string }): Promise<L | null>;
3111
+ select<L = T>(option: MethodOption & { hump?: boolean; sync: SyncMode.Sync; selectResult?: SelectResult.Many_Row_Many_Column | SelectResult.Many_Row_One_Column; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string }): L[];
3112
+ select<L = T>(option: MethodOption & { hump?: boolean; sync: SyncMode.Sync; selectResult: SelectResult.One_Row_Many_Column_Assert | SelectResult.One_Row_One_Column_Assert; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string; }): L;
3113
+ select<L = T>(option: MethodOption & { hump?: boolean; sync: SyncMode.Sync; selectResult: SelectResult.One_Row_Many_Column_NotSure | SelectResult.One_Row_One_Column_NotSure; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string }): L | null;
2822
3114
  @P<T>()
2823
- select<L = T>(option: MethodOption & { sync?: SyncMode; selectResult?: SelectResult; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string; }): null | L | L[] | Promise<null | L | L[]> {
3115
+ select<L = T>(option: MethodOption & { hump?: boolean; sync?: SyncMode; selectResult?: SelectResult; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; isCount?: boolean; defValue?: L | null; multiple?: boolean; errorMsg?: string; }): null | L | L[] | Promise<null | L | L[]> {
2824
3116
  Throw.if(!option.sqlId && !option.sql, 'not found sql!');
2825
3117
  option.selectResult ??= SelectResult.Many_Row_Many_Column;
2826
3118
  option.defValue ??= null;
2827
3119
  const _params = Object.assign({}, option.context, option.params);
2828
- option.sql ??= globalThis[_sqlCache].load(option.sqlId, { ctx: option.context, isCount: option.isCount, ..._params });
2829
- logger.debug(option.sql);
3120
+ option.sql ??= globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: option.isCount, ..._params });
2830
3121
  const params: any[] = [];
2831
3122
  const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2832
3123
  if (_params.hasOwnProperty(key)) {
@@ -2834,15 +3125,31 @@ export class SqlService<T extends object> {
2834
3125
  params.push(V);
2835
3126
  return Sqlstring.escape(_params[key]);
2836
3127
  }
3128
+ const _key = C2P(key);
3129
+ if (_params.hasOwnProperty(_key)) {
3130
+ const V = _params[_key];
3131
+ params.push(V);
3132
+ return Sqlstring.escape(_params[_key]);
3133
+ }
3134
+ const __key = P2C(key);
3135
+ if (_params.hasOwnProperty(__key)) {
3136
+ const V = _params[__key];
3137
+ params.push(V);
3138
+ return Sqlstring.escape(_params[__key]);
3139
+ }
2837
3140
  return txt;
2838
3141
  });
2839
3142
  if (option.sync === SyncMode.Sync) {
2840
3143
  const result = option!.conn!.query(SyncMode.Sync, sql, params);
2841
- return this._select<L>(option.selectResult, result, option.defValue, option.errorMsg, option.multiple);
3144
+ return this._select<L>(option.selectResult, result, option.defValue, option.errorMsg, option.multiple, option.hump);
2842
3145
  } else {
2843
- return new Promise<L | null | L[]>(async (resolve) => {
2844
- const result = await option!.conn!.query(SyncMode.Async, sql, params);
2845
- resolve(this._select<L>(option.selectResult!, result, option.defValue!, option.errorMsg, option.multiple));
3146
+ return new Promise<L | null | L[]>(async (resolve, reject) => {
3147
+ try {
3148
+ const result = await option!.conn!.query(SyncMode.Async, sql, params);
3149
+ resolve(this._select<L>(option.selectResult!, result, option.defValue!, option.errorMsg, option.multiple));
3150
+ } catch (error) {
3151
+ reject(error);
3152
+ }
2846
3153
  });
2847
3154
  }
2848
3155
  }
@@ -2868,8 +3175,7 @@ export class SqlService<T extends object> {
2868
3175
  excute<L = T>(option: MethodOption & { sync?: SyncMode; sqlId?: string; sql?: string; params?: Record<string, any>; context?: any; }): number | Promise<number> {
2869
3176
  Throw.if(!option.sqlId && !option.sql, 'not found sql!');
2870
3177
  const _params = Object.assign({}, option.context, option.params);
2871
- option.sql ??= globalThis[_sqlCache].load(option.sqlId, { ctx: option.context, ..._params });
2872
- logger.debug(option.sql);
3178
+ option.sql ??= globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, ..._params });
2873
3179
  const params: any[] = [];
2874
3180
  const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2875
3181
  if (_params.hasOwnProperty(key)) {
@@ -2877,15 +3183,31 @@ export class SqlService<T extends object> {
2877
3183
  params.push(V);
2878
3184
  return Sqlstring.escape(_params[key]);
2879
3185
  }
3186
+ const _key = C2P(key);
3187
+ if (_params.hasOwnProperty(_key)) {
3188
+ const V = _params[_key];
3189
+ params.push(V);
3190
+ return Sqlstring.escape(_params[_key]);
3191
+ }
3192
+ const __key = P2C(key);
3193
+ if (_params.hasOwnProperty(__key)) {
3194
+ const V = _params[__key];
3195
+ params.push(V);
3196
+ return Sqlstring.escape(_params[__key]);
3197
+ }
2880
3198
  return txt;
2881
3199
  });
2882
3200
  if (option.sync === SyncMode.Sync) {
2883
3201
  const result = option!.conn!.execute(SyncMode.Sync, sql, params);
2884
3202
  return result.affectedRows;
2885
3203
  } else {
2886
- return new Promise<number>(async (resolve) => {
2887
- const result = await option!.conn!.execute(SyncMode.Async, sql, params);
2888
- resolve(result.affectedRows);
3204
+ return new Promise<number>(async (resolve, reject) => {
3205
+ try {
3206
+ const result = await option!.conn!.execute(SyncMode.Async, sql, params);
3207
+ resolve(result.affectedRows);
3208
+ } catch (error) {
3209
+ reject(error);
3210
+ }
2889
3211
  });
2890
3212
  }
2891
3213
  }
@@ -2914,15 +3236,129 @@ export class SqlService<T extends object> {
2914
3236
  if (option.sync === SyncMode.Sync) {
2915
3237
  return option!.dao!.transaction(SyncMode.Sync, option.fn as (conn: Connection) => L)!;
2916
3238
  } else {
2917
- return new Promise(async (resolve) => {
2918
- const rt = await option!.dao!.transaction(SyncMode.Async, option.fn as (conn: Connection) => Promise<L>);
2919
- resolve(rt);
2920
- });
2921
- }
3239
+ return new Promise(async (resolve, reject) => {
3240
+ try {
3241
+ const rt = await option!.dao!.transaction(SyncMode.Async, option.fn as (conn: Connection) => Promise<L>);
3242
+ resolve(rt);
3243
+ } catch (error) {
3244
+ reject(error);
3245
+ }
3246
+ });
3247
+ }
2922
3248
  }
2923
3249
 
2924
- stream(option?: MethodOption) {
2925
- return new StreamQuery(option?.tableName ?? this[_tableName]!, this);
3250
+ stream<L extends object = T>(option?: MethodOption) {
3251
+ return new StreamQuery<L>(option?.tableName ?? this[_tableName]!, this as any, this[_fields]!, this[_columns]!);
3252
+ }
3253
+
3254
+
3255
+ page<L = T>(option: MethodOption & { sync?: SyncMode.Async; sqlId: string; context?: any; params: Record<string, any>; pageSize: number; pageNumber: number; limitSelf: boolean; countSelf: boolean; sumSelf: boolean; orderBy?: string; }): Promise<PageQuery<L>>;
3256
+ page<L = T>(option: MethodOption & { sync: SyncMode.Sync; sqlId: string; context?: any; params: Record<string, any>; pageSize: number; pageNumber: number; limitSelf: boolean; countSelf: boolean; sumSelf: boolean; orderBy?: string; }): PageQuery<L>;
3257
+ @P<T>()
3258
+ page<L = T>(option: MethodOption & { sync?: SyncMode; sqlId: string; context?: any; params: Record<string, any>; pageSize: number; pageNumber: number; limitSelf: boolean; countSelf: boolean; sumSelf: boolean; orderBy?: string; }): PageQuery<L> | Promise<PageQuery<L>> {
3259
+ const result: PageQuery<L> = {
3260
+ sum: {},
3261
+ records: [],
3262
+ size: 0,
3263
+ total: 0
3264
+ };
3265
+ Object.assign(option.params, {
3266
+ limitStart: calc(option.pageNumber).sub(1).mul(option.pageSize).over(),
3267
+ limitEnd: calc(option.pageSize).over(),
3268
+ orderBy: option.orderBy
3269
+ });
3270
+ let sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: false, ...option.params });
3271
+ let sqlSum = '';
3272
+ let sqlCount = '';
3273
+ if (option.sumSelf === true) {
3274
+ sqlSum = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: false, isSum: true, ...option.params });
3275
+ }
3276
+ if (option.limitSelf !== true) {
3277
+ if (option.countSelf !== true) {
3278
+ }
3279
+ if (option.orderBy) {
3280
+ sql = `${sql} ORDER BY ${option.orderBy}`;
3281
+ }
3282
+ if (option.pageSize > 0) {
3283
+ sql = `${sql} LIMIT ${option.params['limitStart']}, ${option.pageSize}`;
3284
+ }
3285
+ }
3286
+ if (option.pageSize > 0) {
3287
+ if (option.countSelf === true) {
3288
+ sqlCount = globalThis[_sqlCache].load(this._matchSqlid(`${option.sqlId}_count`), { ctx: option.context, isCount: true, isSum: false, ...option.params });
3289
+ } else {
3290
+ sqlCount = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: true, isSum: false, ...option.params });
3291
+ }
3292
+ }
3293
+ if (option.sync === SyncMode.Sync) {
3294
+ if (sqlCount) {
3295
+ result.total = this.select<number>({
3296
+ ...option,
3297
+ sql: sqlCount,
3298
+ sync: SyncMode.Sync,
3299
+ selectResult: SelectResult.One_Row_One_Column_Assert
3300
+ });
3301
+ result.size = calc(result.total)
3302
+ .add(option.pageSize - 1)
3303
+ .div(option.pageSize)
3304
+ .round(0, 2)
3305
+ .over();
3306
+ }
3307
+ if (sqlSum) {
3308
+ result.sum = this.select<Record<string, number>>({
3309
+ ...option,
3310
+ sql: sqlSum,
3311
+ sync: SyncMode.Sync,
3312
+ selectResult: SelectResult.One_Row_Many_Column_Assert
3313
+ });
3314
+ }
3315
+ if (sql) {
3316
+ result.records = this.select<L>({
3317
+ ...option,
3318
+ sql,
3319
+ sync: SyncMode.Sync,
3320
+ selectResult: SelectResult.Many_Row_Many_Column
3321
+ });
3322
+ }
3323
+ return result;
3324
+ } else {
3325
+ return new Promise<PageQuery<L>>(async (resolve, reject) => {
3326
+ try {
3327
+ if (sqlCount) {
3328
+ result.total = await this.select<number>({
3329
+ ...option,
3330
+ sql: sqlCount,
3331
+ sync: SyncMode.Async,
3332
+ selectResult: SelectResult.One_Row_One_Column_Assert
3333
+ });
3334
+ result.size = calc(result.total)
3335
+ .add(option.pageSize - 1)
3336
+ .div(option.pageSize)
3337
+ .round(0, 2)
3338
+ .over();
3339
+ }
3340
+ if (sqlSum) {
3341
+ result.sum = await this.select<Record<string, number>>({
3342
+ ...option,
3343
+ sql: sqlSum,
3344
+ sync: SyncMode.Async,
3345
+ selectResult: SelectResult.One_Row_Many_Column_Assert
3346
+ });
3347
+ }
3348
+ if (sql) {
3349
+ result.records = await this.select<L>({
3350
+ ...option,
3351
+ sql,
3352
+ sync: SyncMode.Async,
3353
+ selectResult: SelectResult.Many_Row_Many_Column
3354
+ });
3355
+ }
3356
+ resolve(result);
3357
+ } catch (error) {
3358
+ reject(error);
3359
+ }
3360
+ });
3361
+ }
2926
3362
  }
2927
3363
 
2928
3364
  /**
@@ -2937,11 +3373,11 @@ export class SqlService<T extends object> {
2937
3373
  4. 自定义字段名称:字符串数组
2938
3374
  ** `index` 表的索引,设置方式同ID
2939
3375
  */
2940
- private _createTable({ tableName, temp = true, columns, data, id = 'auto', index = 'auto' }: {
3376
+ private _createTable<L = T>({ tableName, temp = true, columns, data, id = 'auto', index = 'auto' }: {
2941
3377
  tableName?: string;
2942
3378
  temp?: boolean,
2943
3379
  columns?: string[];
2944
- data?: Array<Partial<T>>;
3380
+ data?: Array<Partial<L>>;
2945
3381
  id?: 'auto' | 'all' | 'none' | string[];
2946
3382
  index?: 'auto' | 'all' | 'none' | string[];
2947
3383
  } = {}): { sql: string; params?: any[] }[] {
@@ -2970,66 +3406,73 @@ export class SqlService<T extends object> {
2970
3406
  tableName = Sqlstring.escapeId(tableName ?? this[_tableName]);
2971
3407
  switch (this[_dbType]) {
2972
3408
  case DBType.Mysql: {
2973
- let sql = `CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
2974
- ${columns.map(K => this[_fields]![K]![DBType.Mysql]).join(',')}
2975
- ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields]![i]?.esName).join(',')}) USING BTREE ` : ''}
2976
- ${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields]![i]?.esName} (${this[_fields]![i]?.esName})`).join(',')} ` : ''}
2977
- ) ENGINE=MEMORY;`;
3409
+ let sql = format(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3410
+ ${columns.map(K => this[_fields]![K]![DBType.Mysql]()).join(',')}
3411
+ ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields]![i]?.C2()).join(',')}) USING BTREE ` : ''}
3412
+ ${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields]![i]?.C2()} (${this[_fields]![i]?.C2()})`).join(',')} ` : ''}
3413
+ ) ENGINE=MEMORY;`);
2978
3414
  sqls.push({ sql });
2979
3415
  if (data && data.length > 0) {
2980
3416
  const params: any[] = [];
2981
3417
  let first = true;
2982
- sql = `INSERT INTO ${tableName} (${columns.map(c => Sqlstring.escapeId(c)).join(',')})
3418
+ sql = format(`INSERT INTO ${tableName} (${columns.map(c => this[_fields]![c]?.C2()).join(',')})
2983
3419
  ${(data).map(d => {
2984
3420
  const r = `SELECT ${Object.entries(d).map(([K, V]) => {
2985
3421
  params.push(V);
2986
- return `? ${first ? this[_fields]![K]?.esName : ''}`;
3422
+ return `? ${first ? this[_fields]![K]?.C2() : ''}`;
2987
3423
  }).join(',')}`;
2988
3424
  first = false;
2989
3425
  return r;
2990
- }).join(' UNION ALL ')}`;
3426
+ }).join(' UNION ALL ')}`);
2991
3427
  sqls.push({ sql, params });
2992
3428
  }
2993
3429
  break;
2994
3430
  }
2995
3431
  case DBType.Sqlite:
2996
3432
  case DBType.SqliteRemote: {
2997
- let sql = `CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
2998
- ${columns.map(K => this[_fields]![K]![DBType.Sqlite]).join(',')}
2999
- ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields]![i]?.esName).join(',')}) ` : ''}
3000
- );`;
3433
+ let sql = format(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
3434
+ ${columns.map(K => this[_fields]![K]![DBType.Sqlite]()).join(',')}
3435
+ ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields]![i]?.C2()).join(',')}) ` : ''}
3436
+ );`);
3001
3437
  sqls.push({ sql });
3002
3438
  if (indexs) {
3003
3439
  for (const index of indexs) {
3004
- sql = `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields]![index]?.esName});`;
3440
+ sql = format(`CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields]![index]?.C2()});`);
3005
3441
  sqls.push({ sql });
3006
3442
  }
3007
3443
  }
3008
3444
  if (data && data.length > 0) {
3009
3445
  const params: any[] = [];
3010
3446
  let first = true;
3011
- sql = `INSERT INTO ${tableName} (${columns.map(c => Sqlstring.escapeId(c)).join(',')})
3447
+ sql = format(`INSERT INTO ${tableName} (${columns.map(c => this[_fields]![c]?.C2()).join(',')})
3012
3448
  ${(data).map(d => {
3013
3449
  const r = `SELECT ${Object.entries(d).map(([K, V]) => {
3014
3450
  params.push(V);
3015
- return `? ${first ? this[_fields]![K]?.esName : ''}`;
3451
+ return `? ${first ? this[_fields]![K]?.C2() : ''}`;
3016
3452
  }).join(',')}`;
3017
3453
  first = false;
3018
3454
  return r;
3019
- }).join(' UNION ALL ')}`;
3455
+ }).join(' UNION ALL ')}`);
3020
3456
  sqls.push({ sql, params });
3021
3457
  }
3458
+ break;
3022
3459
  }
3023
3460
  }
3024
3461
  return sqls;
3025
3462
  }
3026
3463
 
3464
+ private _matchSqlid(sqlid?: string) {
3465
+ sqlid ??= '';
3466
+ if(sqlid.includes('.')) return [sqlid];
3467
+ else return [`${this[_tableName]}.${sqlid}`, `${this[_className]}.${sqlid}`, `${this[_ClassName]}.${sqlid}`, `${this[_vueName]}.${sqlid}`];
3468
+ }
3469
+
3027
3470
  }
3028
3471
  /** 是否进行下一个动作 */
3029
3472
  const IF_PROCEED = function <T extends object>() {
3030
3473
  return function (_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
3031
3474
  const fn = descriptor.value;
3032
- descriptor.value = function (this: StreamCondition<T>) {
3475
+ descriptor.value = function (this: StreamQuery<T>) {
3033
3476
  if (this.if_proceed === true) {
3034
3477
  // eslint-disable-next-line prefer-rest-params
3035
3478
  const args = Array.from(arguments);
@@ -3056,21 +3499,42 @@ const IF_EXEC = function <T extends object>(def: any) {
3056
3499
  };
3057
3500
  };
3058
3501
  };
3059
- class StreamCondition<T extends object> {
3060
- protected _prefix = 0;
3061
- protected _index = 0;
3502
+ class StreamQuery<T extends object> {
3503
+ private _prefix = 0;
3504
+ private _index = 0;
3062
3505
 
3063
- protected _wheres: string[] = [];
3506
+ private _wheres: string[] = [];
3064
3507
 
3065
- protected _andQuerys: StreamCondition<T>[] = [];
3066
- protected _orQuerys: StreamCondition<T>[] = [];
3508
+ private _andQuerys: StreamQuery<T>[] = [];
3509
+ private _orQuerys: StreamQuery<T>[] = [];
3067
3510
 
3068
- protected _paramKeys: Record<string, string[] | Record<string, string> | string> = {};
3069
- protected _param: Record<string, any> = {};
3511
+ private _paramKeys: Record<string, string[] | Record<string, string> | string> = {};
3512
+ private _param: Record<string, any> = {};
3070
3513
  public if_proceed = true;
3071
3514
  public if_exec = true;
3072
- constructor() {
3515
+ private _table: string;
3516
+
3517
+ private _distinct = false;
3518
+ private _columns: string[] = [];
3519
+
3520
+ private _updates?: Partial<T>;
3521
+ private _updateColumns: string[] = [];
3522
+
3523
+ private _groups: string[] = [];
3524
+ private _orders: string[] = [];
3525
+
3526
+ private _startRow = 0;
3527
+ private _pageSize = 0;
3528
+
3529
+ private _service: SqlService<T>;
3530
+ private [_fields]: Record<string, AField>;
3531
+ private [_columns]: string[];
3532
+ constructor(table: string, service: SqlService<T>, __fields: Record<string, AField>, __columns: string[]) {
3073
3533
  this._prefix = parseInt(`${Math.random() * 1000}`);
3534
+ this._table = table;
3535
+ this._service = service;
3536
+ this[_fields] = __fields;
3537
+ this[_columns] = __columns;
3074
3538
  }
3075
3539
  /** 将当前stream重置 */
3076
3540
  reset() {
@@ -3078,8 +3542,15 @@ class StreamCondition<T extends object> {
3078
3542
  this._wheres.length = 0;
3079
3543
  this._param = {};
3080
3544
  this._paramKeys = {};
3545
+ this._pageSize = 0;
3546
+ this._startRow = 0;
3547
+ this._orders.length = 0;
3548
+ this._groups.length = 0;
3549
+ this._columns.length = 0;
3550
+ this._updateColumns.length = 0;
3081
3551
  return this;
3082
3552
  }
3553
+ // #region 条件
3083
3554
  /** 为下次链条执行提供条件判断:非异步方法跳过,异步方法不执行并返回默认值 */
3084
3555
  @IF_PROCEED<T>()
3085
3556
  if(condition: boolean) {
@@ -3090,23 +3561,33 @@ class StreamCondition<T extends object> {
3090
3561
  eq(key: keyof T, value: string | number, { name }: { name?: string } = {}) { return this._(key, value, '=', { name }); }
3091
3562
  @IF_PROCEED<T>()
3092
3563
  eqT(t: Partial<T>, { name }: { name?: string } = {}) {
3093
- if (name && this._paramKeys[name]) {
3094
- for (const [key, pname] of Object.entries(this._paramKeys[name] as Record<string, string>)) {
3095
- this._param[pname as string] = t[key];
3096
- }
3097
- } else {
3098
- const paramKeys: Record<string, string> = {};
3099
- for (const [key, value] of Object.entries(t)) {
3100
- const pkey = `p${this._prefix}${this._index++}`;
3101
- this._wheres.push(`AND ${String(key)} = :${pkey} `);
3102
- this._param[pkey] = value;
3103
- if (name) {
3104
- paramKeys[key] = pkey;
3564
+ if (t) {
3565
+ t = this._service[_transformer]!(t, {
3566
+ skipNull: true,
3567
+ skipUndefined: true,
3568
+ skipEmptyString: true
3569
+ });
3570
+ const keys = Object.keys(t);
3571
+ if (keys.length > 0) {
3572
+ if (name && this._paramKeys[name]) {
3573
+ for (const [key, pname] of Object.entries(this._paramKeys[name] as Record<string, string>)) {
3574
+ this._param[pname as string] = t[key];
3575
+ }
3576
+ } else {
3577
+ const paramKeys: Record<string, string> = {};
3578
+ for (const [key, value] of Object.entries(t)) {
3579
+ const pkey = `p${this._prefix}${this._index++}`;
3580
+ this._wheres.push(`AND ${this[_fields]![String(key)]?.C2()} = :${pkey} `);
3581
+ this._param[pkey] = value;
3582
+ if (name) {
3583
+ paramKeys[key] = pkey;
3584
+ }
3585
+ }
3586
+ if (name) {
3587
+ this._paramKeys[name] = paramKeys;
3588
+ }
3105
3589
  }
3106
3590
  }
3107
- if (name) {
3108
- this._paramKeys[name] = paramKeys;
3109
- }
3110
3591
  }
3111
3592
  return this;
3112
3593
  }
@@ -3159,21 +3640,21 @@ class StreamCondition<T extends object> {
3159
3640
  @IF_PROCEED<T>()
3160
3641
  notPreciseLike(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, not: 'NOT', force }); }
3161
3642
  @IF_PROCEED<T>()
3162
- glob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, left: '%', right: '%', force, op: 'glob' }); }
3643
+ glob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, left: '%', right: '%', force, op: 'GLOB' }); }
3163
3644
  @IF_PROCEED<T>()
3164
- notGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, left: '%', right: '%', not: 'NOT', force, op: 'glob' }); }
3645
+ notGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, left: '%', right: '%', not: 'NOT', force, op: 'GLOB' }); }
3165
3646
  @IF_PROCEED<T>()
3166
- leftGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, left: '%', force, op: 'glob' }); }
3647
+ leftGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, left: '%', force, op: 'GLOB' }); }
3167
3648
  @IF_PROCEED<T>()
3168
- notLeftGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, left: '%', not: 'NOT', force, op: 'glob' }); }
3649
+ notLeftGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, left: '%', not: 'NOT', force, op: 'GLOB' }); }
3169
3650
  @IF_PROCEED<T>()
3170
- rightGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, right: '%', force, op: 'glob' }); }
3651
+ rightGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, right: '%', force, op: 'GLOB' }); }
3171
3652
  @IF_PROCEED<T>()
3172
- notRightGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, right: '%', not: 'NOT', force, op: 'glob' }); }
3653
+ notRightGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, right: '%', not: 'NOT', force, op: 'GLOB' }); }
3173
3654
  @IF_PROCEED<T>()
3174
- PreciseGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, force, op: 'glob' }); }
3655
+ PreciseGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, force, op: 'GLOB' }); }
3175
3656
  @IF_PROCEED<T>()
3176
- notPreciseGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, not: 'NOT', force, op: 'glob' }); }
3657
+ notPreciseGlob(key: keyof T, value: string | number, { name, force }: { name?: string; force?: boolean; } = {}) { return this._like(key, value, { name, not: 'NOT', force, op: 'GLOB' }); }
3177
3658
  @IF_PROCEED<T>()
3178
3659
  in(key: keyof T, value: Array<string | number>, { name, force }: { name?: string; force?: boolean; } = {}) { return this._in(key, value, { name, force }); }
3179
3660
  @IF_PROCEED<T>()
@@ -3217,18 +3698,183 @@ class StreamCondition<T extends object> {
3217
3698
  @IF_PROCEED<T>()
3218
3699
  notIncludes(key: keyof T, value: string | number, { name }: { name?: string } = {}) { return this._includes(key, value, { name, not: 'NOT' }); }
3219
3700
  @IF_PROCEED<T>()
3220
- and(fn: (stream: StreamCondition<T>) => boolean | void) { const stream = new StreamCondition<T>(); const ret = fn(stream); if (ret !== false) { this._andQuerys.push(stream); } return this; }
3701
+ and(fn: StreamQuery<T> | ((stream: StreamQuery<T>) => boolean | void)) {
3702
+ if (fn instanceof StreamQuery) {
3703
+ this._andQuerys.push(fn);
3704
+ } else {
3705
+ const stream = new StreamQuery<T>(this._table, this._service, this[_fields], this[_columns]);
3706
+ const ret = fn(stream);
3707
+ if (ret !== false) { this._andQuerys.push(stream); }
3708
+ }
3709
+ return this;
3710
+ }
3711
+ @IF_PROCEED<T>()
3712
+ or(fn: StreamQuery<T> | ((stream: StreamQuery<T>) => boolean | void)) {
3713
+ if (fn instanceof StreamQuery) {
3714
+ this._andQuerys.push(fn);
3715
+ } else {
3716
+ const stream = new StreamQuery<T>(this._table, this._service, this[_fields], this[_columns]!);
3717
+ const ret = fn(stream);
3718
+ if (ret !== false) { this._orQuerys.push(stream); }
3719
+ }
3720
+ return this;
3721
+ }
3722
+
3723
+ @IF_PROCEED<T>()
3724
+ groupBy(...keys: (keyof T)[]) { this._groups.push(...keys.map(key => `${this[_fields]![String(key)]?.C2()}`)); return this; }
3221
3725
  @IF_PROCEED<T>()
3222
- or(fn: (stream: StreamCondition<T>) => boolean | void) { const stream = new StreamCondition<T>(); const ret = fn(stream); if (ret !== false) { this._orQuerys.push(stream); } return this; }
3223
- protected where() {
3726
+ groupBy2(...keys: string[]) { this._groups.push(...keys); return this; }
3727
+ @IF_PROCEED<T>()
3728
+ asc(...keys: (keyof T)[]) { this._orders.push(...keys.map(key => `${this[_fields]![String(key)]?.C2()} ASC`)); return this; }
3729
+ @IF_PROCEED<T>()
3730
+ asc2(...keys: string[]) { this._orders.push(...keys.map(key => `${key} ASC`)); return this; }
3731
+ @IF_PROCEED<T>()
3732
+ desc(...keys: (keyof T)[]) { this._orders.push(...keys.map(key => `${this[_fields]![String(key)]?.C2()} DESC`)); return this; }
3733
+ @IF_PROCEED<T>()
3734
+ desc2(...keys: string[]) { this._orders.push(...keys.map(key => `${key} ASC`)); return this; }
3735
+ @IF_PROCEED<T>()
3736
+ limit(startRow: number, pageSize: number) { this._startRow = startRow; this._pageSize = pageSize; return this; }
3737
+ @IF_PROCEED<T>()
3738
+ page(pageNumber: number, pageSize: number) { this._startRow = ((pageNumber || 1) - 1) * pageSize; this._pageSize = pageSize; return this; }
3739
+ @IF_PROCEED<T>()
3740
+ table(_table: string) { this._table = _table; return this; }
3741
+ @IF_PROCEED<T>()
3742
+ distinct(on = true) { this._distinct = on; return this; }
3743
+ @IF_PROCEED<T>()
3744
+ countDistinct(key: keyof T, countName?: string,) { this._columns.push(`COUNT(DISTINCT ${this[_fields]![String(key)]?.C2()}) ${countName || `${this[_fields]![String(key)]?.C2()}`}`); return this; }
3745
+ @IF_PROCEED<T>()
3746
+ count(countName?: string) { this._columns.push(`COUNT(1) ${countName ?? 'ct'}`); return this; }
3747
+ @IF_PROCEED<T>()
3748
+ sum(key: keyof T, legName?: string, distinct?: boolean) { this._columns.push(`SUM(${distinct ? 'DISTINCT' : ''} ${this[_fields]![String(key)]?.C2()}) ${legName || `${this[_fields]![String(key)]?.C2()}`}`); return this; }
3749
+ @IF_PROCEED<T>()
3750
+ avg(key: keyof T, legName?: string, distinct?: boolean) { this._columns.push(`AVG(${distinct ? 'DISTINCT' : ''} ${this[_fields]![String(key)]?.C2()}) ${legName || `${this[_fields]![String(key)]?.C2()}`}`); return this; }
3751
+ @IF_PROCEED<T>()
3752
+ max(key: keyof T, legName?: string, distinct?: boolean) { this._columns.push(`MAX(${distinct ? 'DISTINCT' : ''} ${this[_fields]![String(key)]?.C2()}) ${legName || `${this[_fields]![String(key)]?.C2()}`}`); return this; }
3753
+ @IF_PROCEED<T>()
3754
+ min(key: keyof T, legName?: string, distinct?: boolean) { this._columns.push(`MIN(${distinct ? 'DISTINCT' : ''} ${this[_fields]![String(key)]?.C2()}) ${legName || `${this[_fields]![String(key)]?.C2()}`}`); return this; }
3755
+ @IF_PROCEED<T>()
3756
+ groupConcat(key: keyof T, param?: { distinct?: boolean, separator?: string, asc?: (keyof T)[], desc?: (keyof T)[], groupName?: string }): this {
3757
+ this._columns.push(`GROUP_CONCAT(
3758
+ ${param && param.distinct ? 'DISTINCT' : ''} ${this[_fields]![String(key)]?.C2()}
3759
+ ${param && param.asc && param.asc.length > 0 ? `ORDER BY ${param.asc.map(i => `${this[_fields]![String(i)]?.C2()} ASC`)} ` : ''}
3760
+ ${param && param.desc && param.desc.length > 0 ? `${param && param.asc && param.asc.length > 0 ? '' : 'ORDER BY'} ${param.desc.map(i => `${this[_fields]![String(i)]?.C2()} DESC`)} ` : ''}
3761
+ SEPARATOR '${param && param.separator || ','}'
3762
+ ) ${param && param.groupName || `${this[_fields]![String(key)]?.C2()}`}`);
3763
+ return this;
3764
+ }
3765
+ @IF_PROCEED<T>()
3766
+ select(...key: (keyof T)[]) { this._columns.push(...(key.map(k => this[_fields]![String(k)]!.C3()))); return this; }
3767
+ @IF_PROCEED<T>()
3768
+ select2(sql: string, param?: Record<string, any>) { this._columns.push(`${sql}`); Object.assign(this._param, param); return this; }
3769
+ @IF_PROCEED<T>()
3770
+ update(key: keyof T, value: T[keyof T]) { this._updates ??= {}; this._updates[key] = value; return this; }
3771
+ @IF_PROCEED<T>()
3772
+ update2(sql: string, param?: Record<string, any>) { this._updateColumns.push(sql); Object.assign(this._param, param); return this; }
3773
+ @IF_PROCEED<T>()
3774
+ updateT(t: Partial<T>) { this._updates ??= {}; Object.assign(this._updates, t); return this; }
3775
+ @IF_PROCEED<T>()
3776
+ replace(key: keyof T, valueToFind: T[keyof T], valueToReplace: T[keyof T]) {
3777
+ const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
3778
+ this._updateColumns.push(` ${this[_fields]![String(key)]?.C2()} = REPLACE(${this[_fields]![String(key)]?.C2()}, :${pkey1}, :${pkey2}) `);
3779
+ this._param[pkey1] = valueToFind as any;
3780
+ this._param[pkey2] = valueToReplace as any;
3781
+ return this;
3782
+ }
3783
+ // #endregion
3784
+
3785
+ excuteSelect<L = T>(option?: MethodOption & { sync?: SyncMode.Async; selectResult?: SelectResult.Many_Row_Many_Column | SelectResult.Many_Row_One_Column; }): Promise<L[]>;
3786
+ excuteSelect<L = T>(option: MethodOption & { sync?: SyncMode.Async; selectResult: SelectResult.One_Row_Many_Column_Assert | SelectResult.One_Row_One_Column_Assert; errorMsg?: string; }): Promise<L>;
3787
+ excuteSelect<L = T>(option: MethodOption & { sync?: SyncMode.Async; selectResult: SelectResult.One_Row_Many_Column_NotSure | SelectResult.One_Row_One_Column_NotSure; }): Promise<L | null>;
3788
+ excuteSelect<L = T>(option: MethodOption & { sync: SyncMode.Sync; selectResult: SelectResult.Many_Row_Many_Column | SelectResult.Many_Row_One_Column; }): L[];
3789
+ excuteSelect<L = T>(option: MethodOption & { sync: SyncMode.Sync; selectResult: SelectResult.One_Row_Many_Column_Assert | SelectResult.One_Row_One_Column_Assert; errorMsg?: string; }): L;
3790
+ excuteSelect<L = T>(option: MethodOption & { sync: SyncMode.Sync; selectResult: SelectResult.One_Row_Many_Column_NotSure | SelectResult.One_Row_One_Column_NotSure; }): L | null;
3791
+ @IF_EXEC<T>(null)
3792
+ excuteSelect<L = T>(option?: MethodOption & { sync?: SyncMode; selectResult?: SelectResult; errorMsg?: string; }): null | L | L[] | Promise<null | L | L[]> {
3793
+ option ??= {};
3794
+ option.sync ??= SyncMode.Async;
3795
+ option.selectResult ??= SelectResult.Many_Row_Many_Column;
3796
+ const { where, params } = this._where();
3797
+ let sql = `
3798
+ SELECT
3799
+ ${this._distinct ? 'DISTINCT' : ''} ${this._columns && this._columns.length > 0 ? this._columns.join(',') : this[_columns].map(key => this[_fields]![String(key)]?.C3()).join(',')}
3800
+ FROM ${this._table}
3801
+ ${where ? ' WHERE ' : ''}
3802
+ ${where}
3803
+ `;
3804
+ if (this._startRow && this._pageSize) {
3805
+ sql += `LIMIT ${this._startRow}, ${this._pageSize}`;
3806
+ } else if (this._startRow) {
3807
+ sql += `LIMIT ${this._startRow}`;
3808
+ }
3809
+ if (option.sync === SyncMode.Async) {
3810
+ switch (option.selectResult) {
3811
+ case SelectResult.Many_Row_Many_Column: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3812
+ case SelectResult.Many_Row_One_Column: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3813
+ case SelectResult.One_Row_Many_Column_Assert: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3814
+ case SelectResult.One_Row_One_Column_Assert: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3815
+ case SelectResult.One_Row_Many_Column_NotSure: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3816
+ case SelectResult.One_Row_One_Column_NotSure: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3817
+ }
3818
+ } else {
3819
+ switch (option.selectResult) {
3820
+ case SelectResult.Many_Row_Many_Column: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3821
+ case SelectResult.Many_Row_One_Column: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3822
+ case SelectResult.One_Row_Many_Column_Assert: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3823
+ case SelectResult.One_Row_One_Column_Assert: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3824
+ case SelectResult.One_Row_Many_Column_NotSure: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3825
+ case SelectResult.One_Row_One_Column_NotSure: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3826
+ }
3827
+ }
3828
+ }
3829
+ excuteUpdate(option?: MethodOption & { sync?: SyncMode.Async }): Promise<number>;
3830
+ excuteUpdate(option: MethodOption & { sync: SyncMode.Sync }): number;
3831
+ @IF_EXEC<T>(0)
3832
+ excuteUpdate(option?: MethodOption & { sync?: SyncMode }): number | Promise<number> {
3833
+ option ??= {};
3834
+ option.sync ??= SyncMode.Async;
3835
+ const { where, params } = this._where();
3836
+ const sets = new Array<string>(...this._updateColumns);
3837
+ if (this._updates) {
3838
+ for (const [K, V] of Object.entries(this._updates)) {
3839
+ const pkey = `p${this._prefix}${this._index++}`;
3840
+ sets.push(` ${K} = :${pkey} `);
3841
+ params[pkey] = V;
3842
+ }
3843
+ }
3844
+ if (sets.length > 0) {
3845
+ const sql = `UPDATE ${this._table} SET ${sets.join(',')} ${where}`;
3846
+ if (option.sync === SyncMode.Async) {
3847
+ return this._service.excute({ sync: SyncMode.Async, sql, params });
3848
+ } else {
3849
+ return this._service.excute({ sync: SyncMode.Sync, sql, params });
3850
+ }
3851
+ } else {
3852
+ return 0;
3853
+ }
3854
+ }
3855
+ excuteDelete(option?: MethodOption & { sync?: SyncMode.Async }): Promise<number>;
3856
+ excuteDelete(option: MethodOption & { sync: SyncMode.Sync }): number;
3857
+ @IF_EXEC<T>(0)
3858
+ excuteDelete(option?: MethodOption & { sync?: SyncMode }): number | Promise<number> {
3859
+ option ??= {};
3860
+ option.sync ??= SyncMode.Async;
3861
+ const { where, params } = this._where();
3862
+ const sql = `DELETE FROM ${this._table} ${where}`;
3863
+ if (option.sync === SyncMode.Async) {
3864
+ return this._service.excute({ sync: SyncMode.Async, sql, params });
3865
+ } else {
3866
+ return this._service.excute({ sync: SyncMode.Sync, sql, params });
3867
+ }
3868
+ }
3869
+ private _where() {
3224
3870
  const wheres = new Array<string>();
3225
3871
  const sql = this._wheres.join(' ');
3226
3872
  if (sql) {
3227
- wheres.push(`(${sql})`);
3873
+ wheres.push(`(${sql.replace(/^and|^or/i, '')})`);
3228
3874
  }
3229
3875
  if (this._orQuerys.length > 0) {
3230
3876
  for (const query of this._orQuerys) {
3231
- const { where, params } = query.where();
3877
+ const { where, params } = query._where();
3232
3878
  if (where) {
3233
3879
  wheres.push(` OR (${where}) `);
3234
3880
  }
@@ -3237,7 +3883,7 @@ class StreamCondition<T extends object> {
3237
3883
  }
3238
3884
  if (this._andQuerys.length > 0) {
3239
3885
  for (const query of this._andQuerys) {
3240
- const { where, params } = query.where();
3886
+ const { where, params } = query._where();
3241
3887
  if (where) {
3242
3888
  wheres.push(` AND (${where}) `);
3243
3889
  }
@@ -3251,7 +3897,7 @@ class StreamCondition<T extends object> {
3251
3897
  this._param[this._paramKeys[name] as string] = value;
3252
3898
  } else {
3253
3899
  const pkey = `p${this._prefix}${this._index++}`;
3254
- this._wheres.push(`AND ${String(key)} ${not} ${op} :${pkey} `);
3900
+ this._wheres.push(`AND ${this[_fields]![String(key)]?.C2()} ${not} ${op} :${pkey} `);
3255
3901
  this._param[pkey] = value;
3256
3902
  if (name) {
3257
3903
  this._paramKeys[name] = pkey;
@@ -3260,11 +3906,11 @@ class StreamCondition<T extends object> {
3260
3906
  return this;
3261
3907
  }
3262
3908
  private _null(key: keyof T, not = ''): this {
3263
- this._wheres.push(`AND ${String(key)} is ${not} null`);
3909
+ this._wheres.push(`AND ${this[_fields]![String(key)]?.C2()} IS ${not} NULL`);
3264
3910
  return this;
3265
3911
  }
3266
3912
  private _key(key1: keyof T, key2: keyof T, op: string, not = '') {
3267
- this._wheres.push(`AND ${String(key1)} ${not} ${op} ${String(key2)} `);
3913
+ this._wheres.push(`AND ${this[_fields]![String(key1)]?.C2()} ${not} ${op} ${this[_fields]![String(key2)]?.C2()} `);
3268
3914
  return this;
3269
3915
  }
3270
3916
  private _between(key: keyof T, value1: string | number, value2: string | number, { not = '', name = '' } = {}) {
@@ -3273,7 +3919,7 @@ class StreamCondition<T extends object> {
3273
3919
  this._param[this._paramKeys[name]![1]] = value2;
3274
3920
  } else {
3275
3921
  const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
3276
- this._wheres.push(`AND ${String(key)} ${not} BETWEEN :${pkey1} AND :${pkey2}`);
3922
+ this._wheres.push(`AND ${this[_fields]![String(key)]?.C2()} ${not} BETWEEN :${pkey1} AND :${pkey2}`);
3277
3923
  this._param[pkey1] = value1;
3278
3924
  this._param[pkey2] = value2;
3279
3925
  if (name) {
@@ -3288,7 +3934,7 @@ class StreamCondition<T extends object> {
3288
3934
  this._param[this._paramKeys[name] as string] = value;
3289
3935
  } else {
3290
3936
  const pkey = `p${this._prefix}${this._index++}`;
3291
- this._wheres.push(`AND ${String(key)} ${not} IN (:${pkey}) `);
3937
+ this._wheres.push(`AND ${this[_fields]![String(key)]?.C2()} ${not} IN (:${pkey}) `);
3292
3938
  this._param[pkey] = value;
3293
3939
  if (name) {
3294
3940
  this._paramKeys[name] = pkey;
@@ -3304,7 +3950,7 @@ class StreamCondition<T extends object> {
3304
3950
  this._param[this._paramKeys[name] as string] = value;
3305
3951
  } else {
3306
3952
  const pkey = `p${this._prefix}${this._index++}`;
3307
- this._wheres.push(`AND (${String(key1)} << 8) + ${String(key2)} ${not} ${op} :${pkey} `);
3953
+ this._wheres.push(`AND (${this[_fields]![String(key1)]?.C2()} << 8) + ${this[_fields]![String(key2)]?.C2()} ${not} ${op} :${pkey} `);
3308
3954
  this._param[pkey] = value;
3309
3955
  if (name) {
3310
3956
  this._paramKeys[name] = pkey;
@@ -3317,7 +3963,7 @@ class StreamCondition<T extends object> {
3317
3963
  this._param[this._paramKeys[name] as string] = value;
3318
3964
  } else {
3319
3965
  const pkey = `p${this._prefix}${this._index++}`;
3320
- this._wheres.push(`AND MATCH(${keys.join(',')}) AGAINST (:${pkey} ${append ?? ''})`);
3966
+ this._wheres.push(`AND MATCH(${keys.map(key => this[_fields]![String(key)]?.C2()).join(',')}) AGAINST (:${pkey} ${append ?? ''})`);
3321
3967
  this._param[pkey] = value;
3322
3968
  if (name) {
3323
3969
  this._paramKeys[name] = pkey;
@@ -3330,7 +3976,7 @@ class StreamCondition<T extends object> {
3330
3976
  this._param[this._paramKeys[name] as string] = value;
3331
3977
  } else {
3332
3978
  const pkey = `p${this._prefix}${this._index++}`;
3333
- this._wheres.push(`AND NOT POW(2, ${String(key)}) & :${pkey}`);
3979
+ this._wheres.push(`AND NOT POW(2, ${this[_fields]![String(key)]?.C2()}) & :${pkey}`);
3334
3980
  this._param[pkey] = value;
3335
3981
  if (name) {
3336
3982
  this._paramKeys[name] = pkey;
@@ -3344,7 +3990,7 @@ class StreamCondition<T extends object> {
3344
3990
  this._param[this._paramKeys[name] as string] = value;
3345
3991
  } else {
3346
3992
  const pkey = `p${this._prefix}${this._index++}`;
3347
- this._wheres.push(`AND ${String(key)} ${not} ${op} CONCAT('${left}', :${pkey}, '${right}') `);
3993
+ this._wheres.push(`AND ${this[_fields]![String(key)]?.C2()} ${not} ${op} CONCAT('${left}', :${pkey}, '${right}') `);
3348
3994
  this._param[pkey] = value;
3349
3995
  if (name) {
3350
3996
  this._paramKeys[name] = pkey;
@@ -3360,7 +4006,7 @@ class StreamCondition<T extends object> {
3360
4006
  this._param[this._paramKeys[name] as string] = value;
3361
4007
  } else {
3362
4008
  const pkey = `p${this._prefix}${this._index++}`;
3363
- this._wheres.push(`AND LOCATE(${String(key)}, :${pkey}) ${not ? '=' : ''} 0`);
4009
+ this._wheres.push(`AND LOCATE(${this[_fields]![String(key)]?.C2()}, :${pkey}) ${not ? '=' : ''} 0`);
3364
4010
  this._param[pkey] = value;
3365
4011
  if (name) {
3366
4012
  this._paramKeys[name] = pkey;
@@ -3369,177 +4015,20 @@ class StreamCondition<T extends object> {
3369
4015
  return this;
3370
4016
  }
3371
4017
  }
3372
- class StreamBuild<T extends object> extends StreamCondition<T>{
3373
- protected _table: string;
3374
-
3375
- protected _distinct = false;
3376
- protected _columns: string[] = [];
3377
-
3378
- protected _updates?: Partial<T>;
3379
- protected _updateColumns: string[] = [];
3380
-
3381
- protected _groups: (keyof T)[] = [];
3382
- protected _orders: string[] = [];
3383
-
3384
- protected _startRow = 0;
3385
- protected _pageSize = 0;
3386
-
3387
- constructor(table: string) {
3388
- super();
3389
- this._table = table;
3390
- }
3391
- /** 将当前stream重置 */
3392
- reset() {
3393
- super.reset();
3394
- this._pageSize = 0;
3395
- this._startRow = 0;
3396
- this._orders.length = 0;
3397
- this._groups.length = 0;
3398
- this._columns.length = 0;
3399
- this._updateColumns.length = 0;
3400
- return this;
3401
- }
3402
- @IF_PROCEED<T>()
3403
- groupBy(key: keyof T) { this._groups.push(key); return this; }
3404
- @IF_PROCEED<T>()
3405
- asc(...keys: (keyof T)[]) { this._orders.push(...keys.map(key => `${String(key)} ASC`)); return this; }
3406
- @IF_PROCEED<T>()
3407
- desc(...keys: (keyof T)[]) { this._orders.push(...keys.map(key => `${String(key)} DESC`)); return this; }
3408
- @IF_PROCEED<T>()
3409
- limit(startRow: number, pageSize: number) { this._startRow = startRow; this._pageSize = pageSize; return this; }
3410
- @IF_PROCEED<T>()
3411
- page(pageNumber: number, pageSize: number) { this._startRow = ((pageNumber || 1) - 1) * pageSize; this._pageSize = pageSize; return this; }
3412
- @IF_PROCEED<T>()
3413
- table(_table: string) { this._table = _table; return this; }
3414
- @IF_PROCEED<T>()
3415
- distinct(on = true) { this._distinct = on; return this; }
3416
- @IF_PROCEED<T>()
3417
- count(key: keyof T, countName?: string, distinct?: boolean) { this._columns.push(`COUNT(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${countName || `${String(key)}`}`); return this; }
3418
- @IF_PROCEED<T>()
3419
- sum(key: keyof T, legName?: string, distinct?: boolean) { this._columns.push(`SUM(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
3420
- @IF_PROCEED<T>()
3421
- avg(key: keyof T, legName?: string, distinct?: boolean) { this._columns.push(`AVG(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
3422
- @IF_PROCEED<T>()
3423
- max(key: keyof T, legName?: string, distinct?: boolean) { this._columns.push(`MAX(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
3424
- @IF_PROCEED<T>()
3425
- min(key: keyof T, legName?: string, distinct?: boolean) { this._columns.push(`MIN(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
3426
- @IF_PROCEED<T>()
3427
- groupConcat(key: keyof T, param?: { distinct?: boolean, separator?: string, asc?: (keyof T)[], desc?: (keyof T)[], groupName?: string }): this {
3428
- this._columns.push(`GROUP_CONCAT(
3429
- ${param && param.distinct ? 'DISTINCT' : ''} ${String(key)}
3430
- ${param && param.asc && param.asc.length > 0 ? `ORDER BY ${param.asc.map(i => `${String(i)} ASC`)} ` : ''}
3431
- ${param && param.desc && param.desc.length > 0 ? `${param && param.asc && param.asc.length > 0 ? '' : 'ORDER BY'} ${param.desc.map(i => `${String(i)} DESC`)} ` : ''}
3432
- SEPARATOR '${param && param.separator || ','}'
3433
- ) ${param && param.groupName || `${String(key)}`}`);
3434
- return this;
3435
- }
3436
- @IF_PROCEED<T>()
3437
- selectColumn(...key: (keyof T)[]) { this._columns.push(...(key.map(k => k as string))); return this; }
3438
- @IF_PROCEED<T>()
3439
- updateColumn(key: keyof T, value: T[keyof T]) { this._updates ??= {}; this._updates[key] = value; return this; }
3440
- @IF_PROCEED<T>()
3441
- updateT(t: Partial<T>) { this._updates ??= {}; Object.assign(this._updates, t); return this; }
3442
- @IF_PROCEED<T>()
3443
- replace(key: keyof T, valueToFind: T[keyof T], valueToReplace: T[keyof T]) {
3444
- const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
3445
- this._updateColumns.push(` ${String(key)} = REPLACE(${String(key)}, :${pkey1}, :${pkey2}) `);
3446
- this._param[pkey1] = valueToFind as any;
3447
- this._param[pkey2] = valueToReplace as any;
3448
- return this;
3449
- }
3450
- }
3451
- class StreamQuery<T extends object> extends StreamBuild<T>{
3452
- private _service: SqlService<T>;
3453
- constructor(table: string, service: SqlService<T>) {
3454
- super(table);
3455
- this._service = service;
3456
- }
3457
- select<L = T>(option: { sync?: SyncMode.Async; selectResult: SelectResult.Many_Row_Many_Column | SelectResult.Many_Row_One_Column; }): Promise<L[]>;
3458
- select<L = T>(option: { sync?: SyncMode.Async; selectResult: SelectResult.One_Row_Many_Column_Assert | SelectResult.One_Row_One_Column_Assert; errorMsg?: string; }): Promise<L>;
3459
- select<L = T>(option: { sync?: SyncMode.Async; selectResult: SelectResult.One_Row_Many_Column_NotSure | SelectResult.One_Row_One_Column_NotSure; }): Promise<L | null>;
3460
- select<L = T>(option: { sync: SyncMode.Sync; selectResult: SelectResult.Many_Row_Many_Column | SelectResult.Many_Row_One_Column; }): L[];
3461
- select<L = T>(option: { sync: SyncMode.Sync; selectResult: SelectResult.One_Row_Many_Column_Assert | SelectResult.One_Row_One_Column_Assert; errorMsg?: string; }): L;
3462
- select<L = T>(option: { sync: SyncMode.Sync; selectResult: SelectResult.One_Row_Many_Column_NotSure | SelectResult.One_Row_One_Column_NotSure; }): L | null;
3463
- @IF_EXEC<T>(null)
3464
- select<L = T>(option: { sync?: SyncMode; selectResult: SelectResult; errorMsg?: string; }): null | L | L[] | Promise<null | L | L[]> {
3465
- option.sync ??= SyncMode.Async;
3466
- const { where, params } = this.where();
3467
- const sql = `
3468
- SELECT
3469
- ${this._columns && this._columns.length > 0 ? this._columns.join(',') : '*'}
3470
- FROM ${this._table}
3471
- ${where ? ' WHERE ' : ''}
3472
- ${where}`;
3473
-
3474
- if (option.sync === SyncMode.Async) {
3475
- switch (option.selectResult) {
3476
- case SelectResult.Many_Row_Many_Column: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3477
- case SelectResult.Many_Row_One_Column: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3478
- case SelectResult.One_Row_Many_Column_Assert: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3479
- case SelectResult.One_Row_One_Column_Assert: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3480
- case SelectResult.One_Row_Many_Column_NotSure: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3481
- case SelectResult.One_Row_One_Column_NotSure: return this._service.select<L>({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3482
- }
3483
- } else {
3484
- switch (option.selectResult) {
3485
- case SelectResult.Many_Row_Many_Column: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3486
- case SelectResult.Many_Row_One_Column: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3487
- case SelectResult.One_Row_Many_Column_Assert: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3488
- case SelectResult.One_Row_One_Column_Assert: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3489
- case SelectResult.One_Row_Many_Column_NotSure: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3490
- case SelectResult.One_Row_One_Column_NotSure: return this._service.select<L>({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3491
- }
3492
- }
3493
- }
3494
- update(option: { sync?: SyncMode.Async }): Promise<number>;
3495
- update(option: { sync: SyncMode.Sync }): number;
3496
- @IF_EXEC<T>(0)
3497
- update(option: { sync?: SyncMode }): number | Promise<number> {
3498
- option.sync ??= SyncMode.Async;
3499
- const { where, params } = this.where();
3500
- const sets = new Array<string>(...this._updateColumns);
3501
- if (this._updates) {
3502
- for (const [K, V] of Object.entries(this._updates)) {
3503
- const pkey = `p${this._prefix}${this._index++}`;
3504
- sets.push(` ${K} = :${pkey} `);
3505
- params[pkey] = V;
3506
- }
3507
- }
3508
- if (sets.length > 0) {
3509
- const sql = `UPDATE ${this._table} SET ${sets.join(',')} ${where}`;
3510
- if (option.sync === SyncMode.Async) {
3511
- return this._service.excute({ sync: SyncMode.Async, sql, params });
3512
- } else {
3513
- return this._service.excute({ sync: SyncMode.Sync, sql, params });
3514
- }
3515
- } else {
3516
- return 0;
3517
- }
3518
- }
3519
- delete(option: { sync?: SyncMode.Async }): Promise<number>;
3520
- delete(option: { sync: SyncMode.Sync }): number;
3521
- @IF_EXEC<T>(0)
3522
- delete(option: { sync?: SyncMode }): number | Promise<number> {
3523
- option.sync ??= SyncMode.Async;
3524
- const { where, params } = this.where();
3525
- const sql = `DELETE FROM ${this._table} ${where}`;
3526
- if (option.sync === SyncMode.Async) {
3527
- return this._service.excute({ sync: SyncMode.Async, sql, params });
3528
- } else {
3529
- return this._service.excute({ sync: SyncMode.Sync, sql, params });
3530
- }
3531
- }
3532
- }
3533
4018
  /**
3534
4019
  获取REDIS客户端,
3535
4020
  # [查看库的API](https://github.com/redis/ioredis?tab=readme-ov-file)
3536
4021
  # [REDIS API](http://doc.redisfans.com/)
3537
4022
  REDIS 的API 可以直接用,将方法名转为小写
4023
+ ```
4024
+ // 设置<Redis>来获得代码提示
4025
+ getRedisDB<Redis>('').exists(?)
4026
+ ```
3538
4027
  */
3539
- export function getRedisDB(db?: string) {
4028
+ export function getRedisDB<T = any>(db?: string): T {
3540
4029
  const rd = globalThis[_dao][DBType.Redis][db ?? _primaryDB];
3541
4030
  Throw.if(!rd, 'not found redis!');
3542
- return rd;
4031
+ return rd as T;
3543
4032
  }
3544
4033
  /**
3545
4034
  redlock
@@ -3776,13 +4265,12 @@ export function MethodCache<T = any>(config: {
3776
4265
  };
3777
4266
  };
3778
4267
  }
3779
-
3780
4268
  class MUParser {
3781
4269
  static END = 1;
3782
4270
  private modelName: string;
3783
4271
  private linNumber = 0;
3784
- private lastLine?: string;
3785
- private lastlastLine?: string;
4272
+ private lastLine: string = '';
4273
+ private lastlastLine: string = '';
3786
4274
  private status = 0;
3787
4275
  private lineSeparator = '\n';
3788
4276
  private files: string[];
@@ -3792,8 +4280,8 @@ class MUParser {
3792
4280
  this.skipHeader();
3793
4281
  }
3794
4282
  next(): [string, string] | null {
3795
- let sqlId: string | undefined = this.readSqlId();
3796
- if (this.status === MUParser.END || !sqlId) {
4283
+ let sqlId: string = this.readSqlId();
4284
+ if (this.status === MUParser.END) {
3797
4285
  return null;
3798
4286
  }
3799
4287
  // 去掉可能的尾部空格
@@ -3807,14 +4295,17 @@ class MUParser {
3807
4295
  }
3808
4296
  private skipHeader(): void {
3809
4297
  while (true) {
3810
- const line: string | undefined = this.nextLine();
3811
- if (!line) { return; }
3812
- if (this.status === MUParser.END) { return; }
3813
- if (line.startsWith('===')) { return; }
4298
+ const line: string = this.nextLine();
4299
+ if (this.status === MUParser.END) {
4300
+ return;
4301
+ }
4302
+ if (line.startsWith('===')) {
4303
+ return;
4304
+ }
3814
4305
  }
3815
4306
  }
3816
- private nextLine(): string | undefined {
3817
- const line: string | undefined = this.files[this.linNumber];
4307
+ private nextLine(): string {
4308
+ const line: string = this.files[this.linNumber]!;
3818
4309
  this.linNumber++;
3819
4310
  if (line === undefined) {
3820
4311
  this.status = MUParser.END;
@@ -3824,14 +4315,14 @@ class MUParser {
3824
4315
  this.lastLine = line;
3825
4316
  return line;
3826
4317
  }
3827
- private readSqlId(): string | undefined {
4318
+ private readSqlId(): string {
3828
4319
  return this.lastlastLine;
3829
4320
  }
3830
4321
  private skipComment(): void {
3831
4322
  let findComment = false;
3832
4323
  while (true) {
3833
- let line: string | undefined = this.nextLine();
3834
- if (this.status === MUParser.END || !line) {
4324
+ let line: string = this.nextLine();
4325
+ if (this.status === MUParser.END) {
3835
4326
  return;
3836
4327
  }
3837
4328
  line = line.trim();
@@ -3857,26 +4348,20 @@ class MUParser {
3857
4348
  }
3858
4349
  private readSql(): string {
3859
4350
  const list: string[] = [];
3860
- if (this.lastLine) {
3861
- list.push(this.lastLine);
3862
- while (true) {
3863
- const line: string | undefined = this.nextLine();
3864
- if (line) {
3865
- if (this.status === MUParser.END) {
3866
- return this.getBuildSql(list);
3867
- }
3868
- if (line.startsWith('===')) {
3869
- // 删除下一个sqlId表示
3870
- list.pop();
3871
- return this.getBuildSql(list);
3872
- }
3873
- list.push(line);
3874
- } else {
3875
- return '';
3876
- }
4351
+ list.push(this.lastLine);
4352
+ while (true) {
4353
+ const line: string = this.nextLine();
4354
+
4355
+ if (this.status === MUParser.END) {
4356
+ return this.getBuildSql(list);
3877
4357
  }
3878
- } else {
3879
- return '';
4358
+
4359
+ if (line.startsWith('===')) {
4360
+ // 删除下一个sqlId表示
4361
+ list.pop();
4362
+ return this.getBuildSql(list);
4363
+ }
4364
+ list.push(line);
3880
4365
  }
3881
4366
  }
3882
4367
  private getBuildSql(list: string[]): string {
@@ -3892,130 +4377,3 @@ class MUParser {
3892
4377
  return sb.join(this.lineSeparator);
3893
4378
  }
3894
4379
  }
3895
-
3896
- export const Boot = async function (options: GlobalSqlOption) {
3897
- globalThis[_GlobalSqlOption] = Object.assign({}, _defOption, options);
3898
- if (options.sqlDir) {
3899
- globalThis[_path] = await import('path');
3900
- globalThis[_fs] = await import('fs');
3901
- }
3902
- logger.level = options.log ?? 'info';
3903
- globalThis[_sqlCache] = new SqlCache();
3904
- if (options.sqlMap || options.sqlDir) {
3905
- await globalThis[_sqlCache].init(options);
3906
- }
3907
- globalThis[_dao] = {
3908
- [DBType.Mongo]: {},
3909
- [DBType.Mysql]: {},
3910
- [DBType.Sqlite]: {},
3911
- [DBType.SqliteRemote]: {},
3912
- [DBType.Redis]: {}
3913
- };
3914
- if (options.Mysql) {
3915
- const { createPool } = await import('mysql2/promise');
3916
- if (options.Mysql['host']) {
3917
- globalThis[_dao][DBType.Mysql][_primaryDB] = new Mysql(createPool({
3918
- ...options.Mysql,
3919
- multipleStatements: true,
3920
- decimalNumbers: true,
3921
- supportBigNumbers: true
3922
- }));
3923
- } else {
3924
- let flag = false;
3925
- for (const [key, option] of Object.entries(options.Mysql)) {
3926
- const db = new Mysql(createPool({
3927
- ...option,
3928
- multipleStatements: true,
3929
- decimalNumbers: true,
3930
- supportBigNumbers: true
3931
- }));
3932
- if (flag === false) {
3933
- globalThis[_dao][DBType.Mysql][_primaryDB] = db;
3934
- flag = true;
3935
- }
3936
- globalThis[_dao][DBType.Mysql][key] = db;
3937
- }
3938
- }
3939
- }
3940
- if (options.Sqlite) {
3941
- const BetterSqlite3 = await import('better-sqlite3');
3942
- if (typeof options.Sqlite === 'string') {
3943
- globalThis[_dao][DBType.Sqlite][_primaryDB] = new Sqlite(new BetterSqlite3.default(options.Sqlite, { fileMustExist: false }));
3944
- } else {
3945
- let flag = false;
3946
- for (const [key, fileName] of Object.entries(options.Sqlite)) {
3947
- const db = new Sqlite(new BetterSqlite3.default(fileName, { fileMustExist: false }));
3948
- if (flag === false) {
3949
- globalThis[_dao][DBType.Sqlite][_primaryDB] = db;
3950
- flag = true;
3951
- }
3952
- globalThis[_dao][DBType.Sqlite][key] = db;
3953
- }
3954
- }
3955
- }
3956
- if (options.SqliteRemote) {
3957
- if (typeof options.SqliteRemote.db === 'string') {
3958
- await options.SqliteRemote.service.initDB(options.SqliteRemote.db);
3959
- globalThis[_dao][DBType.SqliteRemote][_primaryDB] = new SqliteRemote(options.SqliteRemote.service, options.SqliteRemote.db);
3960
- } else {
3961
- let flag = false;
3962
- for (const [key, fileName] of Object.entries(options.SqliteRemote.db)) {
3963
- await options.SqliteRemote.service.initDB(fileName);
3964
- const db = new SqliteRemote(options.SqliteRemote.service, fileName);
3965
- if (flag === false) {
3966
- globalThis[_dao][DBType.SqliteRemote][_primaryDB] = db;
3967
- flag = true;
3968
- }
3969
- globalThis[_dao][DBType.SqliteRemote][key] = db;
3970
- }
3971
- }
3972
- }
3973
- if (options.Redis) {
3974
- const { Redis } = await import('ioredis');
3975
- if (options.Redis['host']) {
3976
- globalThis[_dao][DBType.Redis][_primaryDB] = new Redis(options.Redis);
3977
- } else {
3978
- let flag = false;
3979
- for (const [key, option] of Object.entries(options.Redis)) {
3980
- const db = new Redis(option);
3981
- if (flag === false) {
3982
- globalThis[_dao][DBType.Redis][_primaryDB] = db;
3983
- flag = true;
3984
- }
3985
- globalThis[_dao][DBType.Redis][key] = db;
3986
- }
3987
- }
3988
- const clients = Object.values(globalThis[_dao][DBType.Redis]) as any;
3989
- const Redlock = await import('redlock');
3990
- globalThis[_dao][DBType.RedisLock] = new Redlock.default(
3991
- clients,
3992
- {
3993
- // The expected clock drift; for more details see:
3994
- // http://redis.io/topics/distlock
3995
- driftFactor: 0.01, // multiplied by lock ttl to determine drift time
3996
-
3997
- // The max number of times Redlock will attempt to lock a resource
3998
- // before erroring.
3999
- retryCount: 10,
4000
-
4001
- // the time in ms between attempts
4002
- retryDelay: 200, // time in ms
4003
-
4004
- // the max time in ms randomly added to retries
4005
- // to improve performance under high contention
4006
- // see https://www.awsarchitectureblog.com/2015/03/backoff.html
4007
- retryJitter: 200, // time in ms
4008
-
4009
- // The minimum remaining time on a lock before an extension is automatically
4010
- // attempted with the `using` API.
4011
- automaticExtensionThreshold: 500, // time in ms
4012
- }
4013
- );
4014
- const { EventEmitter } = await import('events');
4015
- const event = new EventEmitter({ captureRejections: true });
4016
- event.on('error', error => {
4017
- logger.error('event-bus', error);
4018
- });
4019
- globalThis[_EventBus] = event;
4020
- }
4021
- }