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/es/sql.js CHANGED
@@ -8,8 +8,7 @@ var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
10
  var _a, _b, _c;
11
- var _d, _e, _f;
12
- import 'reflect-metadata';
11
+ var _d, _e, _f, _g;
13
12
  import { Throw } from './error';
14
13
  import tslib from 'tslib';
15
14
  import Sqlstring from 'sqlstring';
@@ -17,11 +16,18 @@ import iterare from 'iterare';
17
16
  import { emptyString } from './string';
18
17
  import pino from 'pino';
19
18
  import { excuteSplit, ExcuteSplitMode, sleep } from './fn';
20
- import { add } from './math';
19
+ import { add, calc } from './math';
21
20
  import mustache from 'mustache';
21
+ import { C2P, C2P2, P2C } from './object';
22
+ import { format } from 'sql-formatter';
23
+ import HTML from 'html-parse-stringify';
24
+ import { convert } from './convert-xml';
22
25
  // #region 常量
23
26
  const _daoDBName = Symbol('dbName');
24
27
  const _tableName = Symbol('tableName');
28
+ const _className = Symbol('className');
29
+ const _ClassName = Symbol('ClassName');
30
+ const _vueName = Symbol('vueName');
25
31
  const _ids = Symbol('ids');
26
32
  const _columns = Symbol('columns');
27
33
  const _columnsNoId = Symbol('columnsNoId');
@@ -31,9 +37,9 @@ const _deleteState = Symbol('deleteState');
31
37
  const _transformer = Symbol('transformer');
32
38
  const _index = Symbol('index');
33
39
  const _def = Symbol('def');
34
- const _sqlCache = Symbol('sqlMap');
35
- const _dao = Symbol('dao');
36
- const _primaryDB = Symbol('primaryDB');
40
+ export const _sqlCache = Symbol('sqlMap');
41
+ export const _dao = Symbol('dao');
42
+ export const _primaryDB = Symbol('primaryDB');
37
43
  const _dbType = Symbol('dbType');
38
44
  const _sqlite_version = Symbol('sqlite_version');
39
45
  const _daoConnection = Symbol('daoConnection');
@@ -41,16 +47,17 @@ const _inTransaction = Symbol('inTransaction');
41
47
  const _daoDB = Symbol('daoDB');
42
48
  const _sqliteRemoteName = Symbol('sqliteRemoteName');
43
49
  const _SqlOption = Symbol('SqlOption');
44
- const _GlobalSqlOption = Symbol('GlobalSqlOption');
45
- const _EventBus = Symbol('EventBus');
46
- const _path = Symbol('path');
47
- const _fs = Symbol('fs');
48
- const logger = pino({
50
+ export const _Hump = Symbol('Hump');
51
+ export const _GlobalSqlOption = Symbol('GlobalSqlOption');
52
+ export const _EventBus = Symbol('EventBus');
53
+ export const _path = Symbol('path');
54
+ export const _fs = Symbol('fs');
55
+ export const logger = process.env['NODE_ENV'] !== 'production' ? pino({
49
56
  name: 'sql',
50
57
  transport: {
51
58
  target: 'pino-pretty'
52
59
  }
53
- });
60
+ }) : pino({ name: 'sql' });
54
61
  // #endregion
55
62
  // #region 可选配置
56
63
  export var DBType;
@@ -187,8 +194,13 @@ export var SqlType;
187
194
  SqlType[SqlType["multipolygon"] = 32] = "multipolygon";
188
195
  SqlType[SqlType["geometrycollection"] = 33] = "geometrycollection";
189
196
  })(SqlType || (SqlType = {}));
197
+ export var ColumnMode;
198
+ (function (ColumnMode) {
199
+ ColumnMode[ColumnMode["NONE"] = 0] = "NONE";
200
+ ColumnMode[ColumnMode["HUMP"] = 1] = "HUMP";
201
+ })(ColumnMode || (ColumnMode = {}));
190
202
  export const SqliteMemory = ':memory:';
191
- const _defOption = {
203
+ export const _defOption = {
192
204
  maxDeal: 500,
193
205
  skipUndefined: true,
194
206
  skipNull: true,
@@ -381,7 +393,7 @@ class MysqlConnection {
381
393
  }
382
394
  }
383
395
  _a = _inTransaction;
384
- class Mysql {
396
+ export class Mysql {
385
397
  constructor(pool) {
386
398
  this[_daoDB] = pool;
387
399
  }
@@ -394,7 +406,7 @@ class Mysql {
394
406
  return new Promise(async (resolve, reject) => {
395
407
  try {
396
408
  const connection = await this[_daoDB].getConnection();
397
- logger.debug('create new!');
409
+ logger.debug('create new connection!');
398
410
  resolve(new MysqlConnection(connection));
399
411
  }
400
412
  catch (error) {
@@ -612,7 +624,7 @@ class SqliteConnection {
612
624
  }
613
625
  }
614
626
  _b = _inTransaction;
615
- class Sqlite {
627
+ export class Sqlite {
616
628
  constructor(db) {
617
629
  this[_daoDB] = db;
618
630
  this[_daoDB].pragma('journal_mode = WAL');
@@ -674,7 +686,7 @@ class Sqlite {
674
686
  restore(sync, name) {
675
687
  }
676
688
  }
677
- class SqliteRemoteConnection {
689
+ export class SqliteRemoteConnection {
678
690
  constructor(conn, name) {
679
691
  this[_c] = false;
680
692
  this[_daoConnection] = conn;
@@ -829,7 +841,7 @@ class SqliteRemoteConnection {
829
841
  }
830
842
  }
831
843
  _c = _inTransaction;
832
- class SqliteRemote {
844
+ export class SqliteRemote {
833
845
  constructor(db, name) {
834
846
  this[_daoDB] = db;
835
847
  this[_sqliteRemoteName] = name;
@@ -840,8 +852,13 @@ class SqliteRemote {
840
852
  return null;
841
853
  }
842
854
  ;
843
- return new Promise(async (resolve) => {
844
- resolve(new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]));
855
+ return new Promise(async (resolve, reject) => {
856
+ try {
857
+ resolve(new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]));
858
+ }
859
+ catch (error) {
860
+ reject(error);
861
+ }
845
862
  });
846
863
  }
847
864
  transaction(sync, fn, conn) {
@@ -850,32 +867,52 @@ class SqliteRemote {
850
867
  }
851
868
  close(sync) {
852
869
  if (sync === SyncMode.Async) {
853
- return new Promise(async () => {
854
- await this[_daoConnection].close();
870
+ return new Promise(async (resolve, reject) => {
871
+ try {
872
+ await this[_daoConnection].close();
873
+ }
874
+ catch (error) {
875
+ reject(error);
876
+ }
855
877
  });
856
878
  }
857
879
  ;
858
880
  }
859
881
  backup(sync, name) {
860
882
  if (sync === SyncMode.Async) {
861
- return new Promise(async () => {
862
- await this[_daoConnection].backup(this[_sqliteRemoteName], name);
883
+ return new Promise(async (resolve, reject) => {
884
+ try {
885
+ await this[_daoConnection].backup(this[_sqliteRemoteName], name);
886
+ }
887
+ catch (error) {
888
+ reject(error);
889
+ }
863
890
  });
864
891
  }
865
892
  ;
866
893
  }
867
894
  remove(sync) {
868
895
  if (sync === SyncMode.Async) {
869
- return new Promise(async () => {
870
- await this[_daoConnection].remove();
896
+ return new Promise(async (resolve, reject) => {
897
+ try {
898
+ await this[_daoConnection].remove();
899
+ }
900
+ catch (error) {
901
+ reject(error);
902
+ }
871
903
  });
872
904
  }
873
905
  ;
874
906
  }
875
907
  restore(sync, name) {
876
908
  if (sync === SyncMode.Async) {
877
- return new Promise(async () => {
878
- await this[_daoConnection].restore(this[_sqliteRemoteName], name);
909
+ return new Promise(async (resolve, reject) => {
910
+ try {
911
+ await this[_daoConnection].restore(this[_sqliteRemoteName], name);
912
+ }
913
+ catch (error) {
914
+ reject(error);
915
+ }
879
916
  });
880
917
  }
881
918
  ;
@@ -900,7 +937,7 @@ class Build {
900
937
  * @returns
901
938
  * @memberof Build
902
939
  */
903
- pageTag() {
940
+ page() {
904
941
  return (text, render) => {
905
942
  if (this.isCount === true) {
906
943
  return Build.page;
@@ -912,11 +949,11 @@ class Build {
912
949
  }
913
950
  /**
914
951
  *
915
- * 汇总查询专用
952
+ * 包含的内容只在汇总查询时有效,否则是空白
916
953
  * @returns
917
954
  * @memberof Build
918
955
  */
919
- sumTag() {
956
+ sum() {
920
957
  return (text, render) => {
921
958
  if (this.isSum !== true) {
922
959
  return '';
@@ -932,7 +969,7 @@ class Build {
932
969
  * @returns
933
970
  * @memberof Build
934
971
  */
935
- pageIgnoreTag() {
972
+ notPage() {
936
973
  return (text, render) => {
937
974
  if (this.isCount === true || this.isSum === true) {
938
975
  return '';
@@ -957,8 +994,7 @@ class Build {
957
994
  */
958
995
  where() {
959
996
  return (text, render) => {
960
- let data = render(text);
961
- data = data.trim();
997
+ let data = render(text).trim();
962
998
  if (data) {
963
999
  data = data.replace(/and|or/i, '');
964
1000
  return ` WHERE ${data} `;
@@ -968,6 +1004,33 @@ class Build {
968
1004
  }
969
1005
  };
970
1006
  }
1007
+ /**
1008
+ * ```
1009
+ * SELECT
1010
+ * {{#hump}}
1011
+ * a.event_id, a.event_name eventName
1012
+ * {{/hump}}
1013
+ * FROM...
1014
+ * ```
1015
+ * 编译后:
1016
+ * ```
1017
+ * SELECT
1018
+ * a.event_id eventId, a.event_name eventName
1019
+ * FROM...
1020
+ * ```
1021
+ */
1022
+ hump() {
1023
+ return (text, render) => {
1024
+ let data = render(text).trim();
1025
+ const datas = data.split(',');
1026
+ for (let i = 0; i < datas.length; i++) {
1027
+ if (datas[i]?.match(/\s|\t/) === null) {
1028
+ datas[i] = `${datas[i]} ${datas[i].replace(/[a-zA-Z0-9]+\./, '').replace(/_([a-z])/g, (a, b, c) => b.toUpperCase())}`;
1029
+ }
1030
+ }
1031
+ return datas.join(',');
1032
+ };
1033
+ }
971
1034
  /**
972
1035
  * 删除第一个and、or
973
1036
  * 删除最后一个,
@@ -991,13 +1054,13 @@ class Build {
991
1054
  * 分页时将排序部分代码用此函数包起来,可以自动拼接order by
992
1055
  * 查询条数时,自动忽略此部分
993
1056
  * etc
994
- * {{#orderTag}} name desc, age asc {{/orderTag}}
1057
+ * {{#order}} name desc, age asc {{/order}}
995
1058
  * ===
996
1059
  * ORDER BY name desc, age asc
997
1060
  * @returns
998
1061
  * @memberof Build
999
1062
  */
1000
- orderTag() {
1063
+ order() {
1001
1064
  return (text, render) => {
1002
1065
  if (this.isCount === true || this.isSum === true) {
1003
1066
  return '';
@@ -1013,7 +1076,7 @@ class Build {
1013
1076
  }
1014
1077
  };
1015
1078
  }
1016
- limitTag() {
1079
+ limit() {
1017
1080
  return (text, render) => {
1018
1081
  if (this.isCount === true || this.isSum === true) {
1019
1082
  return '';
@@ -1034,13 +1097,13 @@ class Build {
1034
1097
  * 分页时将分组部分代码用此函数包起来,可以自动拼接GROUP BY
1035
1098
  * 当分页时、汇总时,自动忽略此部分
1036
1099
  * etc
1037
- * {{#groupTag}} name, age {{/groupTag}}
1100
+ * {{#between}} name, age {{/between}}
1038
1101
  * ===
1039
1102
  * group by name.age
1040
1103
  * @returns
1041
1104
  * @memberof Build
1042
1105
  */
1043
- groupTag() {
1106
+ group() {
1044
1107
  return (text, render) => {
1045
1108
  if (this.isCount === true || this.isSum === true) {
1046
1109
  return '';
@@ -1085,15 +1148,15 @@ class Build {
1085
1148
  *
1086
1149
  * 距离计算,单位米
1087
1150
  * etc
1088
- * {{#distanceTag}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distanceTag}}
1151
+ * {{#distance}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distance}}
1089
1152
  * ===
1090
1153
  * ROUND(ST_DISTANCE(POINT(longitude1, latitude1), POINT({{longitude}}, {{latitude}}))*111195, 2)
1091
1154
  * 可根据需求自行将数据转换为千米,例如
1092
- * {{#distanceTag}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distanceTag}} / 1000
1155
+ * {{#distance}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distance}} / 1000
1093
1156
  * @returns
1094
1157
  * @memberof Build
1095
1158
  */
1096
- distanceTag() {
1159
+ distance() {
1097
1160
  return (text, render) => {
1098
1161
  const result = render(text);
1099
1162
  if (/\(([^()]+)\)/.exec(result)) {
@@ -1121,7 +1184,24 @@ class Build {
1121
1184
  }
1122
1185
  }
1123
1186
  Build.page = 'COUNT(1) zccw1986 ';
1124
- class SqlCache {
1187
+ function replaceCdata(rawText) {
1188
+ var cdataRegex = new RegExp('(<!\\[CDATA\\[)([\\s\\S]*?)(\\]\\]>)', 'g');
1189
+ var matches = rawText.match(cdataRegex);
1190
+ if (matches != null && matches.length > 0) {
1191
+ for (var z = 0; z < matches.length; z++) {
1192
+ var regex = new RegExp('(<!\\[CDATA\\[)([\\s\\S]*?)(\\]\\]>)', 'g');
1193
+ var m = regex.exec(matches[z]);
1194
+ var cdataText = m[2];
1195
+ cdataText = cdataText.replace(/\&/g, '&amp;');
1196
+ cdataText = cdataText.replace(/\</g, '&lt;');
1197
+ cdataText = cdataText.replace(/\>/g, '&gt;');
1198
+ cdataText = cdataText.replace(/\"/g, '&quot;');
1199
+ rawText = rawText.replace(m[0], cdataText);
1200
+ }
1201
+ }
1202
+ return rawText;
1203
+ }
1204
+ export class SqlCache {
1125
1205
  constructor() {
1126
1206
  this.sqlMap = {};
1127
1207
  this.sqlFNMap = {};
@@ -1130,16 +1210,20 @@ class SqlCache {
1130
1210
  if (options.sqlMap) {
1131
1211
  this.sqlMap = options.sqlMap;
1132
1212
  }
1213
+ const queryTypes = ['sql', 'select', 'insert', 'update', 'delete'];
1133
1214
  if (options.sqlDir) {
1134
1215
  const sqlFis = globalThis[_fs].readdirSync(options.sqlDir);
1135
1216
  for (const modeName of sqlFis) {
1217
+ logger.debug(`sql: ${modeName} start explain!`);
1136
1218
  const extname = globalThis[_path].extname(modeName);
1137
1219
  const name = globalThis[_path].basename(modeName, extname);
1138
1220
  const file = globalThis[_path].join(options.sqlDir, modeName);
1139
- if (extname === 'mu') {
1221
+ let ct = 0;
1222
+ if (extname === '.mu') {
1140
1223
  const parser = new MUParser(name, globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString());
1141
1224
  let source = parser.next();
1142
1225
  while (source != null) {
1226
+ ct++;
1143
1227
  this.sqlMap[source[0]] = source[1];
1144
1228
  logger.debug(`sql: ${source[0]} found!`);
1145
1229
  source = parser.next();
@@ -1148,9 +1232,30 @@ class SqlCache {
1148
1232
  else if (extname === '.js') {
1149
1233
  const obj = (await import(globalThis[_path].join(options.sqlDir, modeName))).default;
1150
1234
  for (const [key, fn] of Object.entries(obj)) {
1235
+ ct++;
1151
1236
  this.sqlMap[`${name}.${String(key)}`] = fn;
1152
1237
  }
1153
1238
  }
1239
+ else if (extname === '.xml') {
1240
+ const root = HTML.parse(replaceCdata(globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString()))[0];
1241
+ if (root) {
1242
+ const mappers = root.children;
1243
+ for (const mapper of mappers) {
1244
+ console.log(mapper);
1245
+ if (mapper.type === 'tag' && mapper.name === 'mapper') {
1246
+ for (const am of mapper.children) {
1247
+ if (am.type === 'tag') {
1248
+ Throw.if(!queryTypes.includes(am.name), `${name}错误,${am.name}不支持!`);
1249
+ am.id = am.attrs['id'];
1250
+ Throw.if(!am.id, `${name}错误,没有为此块设置id:${am}`);
1251
+ this.sqlMap[`${name}.${am.id}`] = am.children;
1252
+ }
1253
+ }
1254
+ }
1255
+ }
1256
+ }
1257
+ }
1258
+ logger.debug(`sql: ${modeName} explain over[${ct}]!`);
1154
1259
  }
1155
1260
  }
1156
1261
  if (options.sqlFNMap) {
@@ -1168,14 +1273,32 @@ class SqlCache {
1168
1273
  }
1169
1274
  }
1170
1275
  }
1171
- load(sqlid, options) {
1172
- const sqlSource = this.sqlMap[sqlid];
1173
- Throw.if(!sqlSource, `指定的语句${sqlid}不存在!`);
1174
- const _sql = typeof sqlSource === 'function' ? sqlSource(options) : sqlSource;
1175
- const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1176
- const sql = mustache.render(_sql, buildParam, this.sqlFNMap);
1177
- logger.debug(sqlid, sql);
1178
- return sql;
1276
+ load(sqlids, options) {
1277
+ let sqlSource;
1278
+ for (const sqlid of sqlids) {
1279
+ sqlSource = this.sqlMap[sqlid];
1280
+ if (sqlSource) {
1281
+ break;
1282
+ }
1283
+ }
1284
+ const matchSqlid = sqlids.map(i => i.split('.')[0]);
1285
+ Throw.if(!sqlSource, `指定的语句${sqlids.join('|')}不存在!`);
1286
+ if (typeof sqlSource === 'function') {
1287
+ const _sql = sqlSource(options);
1288
+ const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1289
+ const sql = mustache.render(_sql, buildParam, this.sqlFNMap);
1290
+ return format(sql);
1291
+ }
1292
+ else if (typeof sqlSource === 'string') {
1293
+ const buildParam = new Build(options.isCount === true, options.isSum === true, options);
1294
+ const sql = mustache.render(sqlSource, buildParam, this.sqlFNMap);
1295
+ return format(sql);
1296
+ }
1297
+ else if (typeof sqlSource === 'object') {
1298
+ const sql = convert(sqlSource, options, matchSqlid, this.sqlMap);
1299
+ return format(sql);
1300
+ }
1301
+ return '';
1179
1302
  }
1180
1303
  }
1181
1304
  // #endregion
@@ -1204,6 +1327,8 @@ function P(skipConn = false) {
1204
1327
  const option = args[0] = Object.assign({}, globalThis[_GlobalSqlOption], this[_SqlOption], args[0]);
1205
1328
  option.sync ?? (option.sync = SyncMode.Async);
1206
1329
  const dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
1330
+ const dddx = this[_dbType];
1331
+ logger.info(dddx);
1207
1332
  option.dao = globalThis[_dao][this[_dbType]][dbName];
1208
1333
  Throw.if(!option.dao, `not found db:${String(dbName)}(${this[_dbType]})`);
1209
1334
  option.tableName = option?.tableName ?? this[_tableName];
@@ -1227,7 +1352,7 @@ function P(skipConn = false) {
1227
1352
  if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1228
1353
  // 更新版本
1229
1354
  const columns = iterare(option.conn.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
1230
- .filter(c => this[_fields].hasOwnProperty(c.name))
1355
+ .filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
1231
1356
  .map(c => Sqlstring.escapeId(c.name))
1232
1357
  .join(',');
1233
1358
  const rtable = Sqlstring.escapeId(`${option.tableName}_${tableVersion.replace(/\./, '_')}`);
@@ -1235,13 +1360,13 @@ function P(skipConn = false) {
1235
1360
  option.conn.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1236
1361
  option.conn.execute(SyncMode.Sync, `
1237
1362
  CREATE TABLE IF NOT EXISTS ${tableES}(
1238
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
1239
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
1363
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1364
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1240
1365
  );
1241
1366
  `);
1242
1367
  if (this[_index] && this[_index].length) {
1243
1368
  for (const index of this[_index]) {
1244
- option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1369
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1245
1370
  }
1246
1371
  }
1247
1372
  option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
@@ -1258,14 +1383,14 @@ function P(skipConn = false) {
1258
1383
  // 创建表
1259
1384
  option.conn.execute(SyncMode.Sync, `
1260
1385
  CREATE TABLE IF NOT EXISTS ${tableES} (
1261
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
1262
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
1386
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1387
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1263
1388
 
1264
1389
  );
1265
1390
  `);
1266
1391
  if (this[_index] && this[_index].length) {
1267
1392
  for (const index of this[_index]) {
1268
- option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1393
+ option.conn.execute(SyncMode.Sync, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1269
1394
  }
1270
1395
  }
1271
1396
  option.conn.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
@@ -1314,7 +1439,7 @@ function P(skipConn = false) {
1314
1439
  if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
1315
1440
  // 更新版本
1316
1441
  const columns = iterare(await option.conn.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
1317
- .filter(c => this[_fields].hasOwnProperty(c.name))
1442
+ .filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
1318
1443
  .map(c => Sqlstring.escapeId(c.name))
1319
1444
  .join(',');
1320
1445
  const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
@@ -1322,13 +1447,13 @@ function P(skipConn = false) {
1322
1447
  await option.conn.execute(SyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
1323
1448
  await option.conn.execute(SyncMode.Async, `
1324
1449
  CREATE TABLE IF NOT EXISTS ${tableES}(
1325
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
1326
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
1450
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1451
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1327
1452
  );
1328
1453
  `);
1329
1454
  if (this[_index] && this[_index].length) {
1330
1455
  for (const index of this[_index]) {
1331
- await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
1456
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
1332
1457
  }
1333
1458
  }
1334
1459
  await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
@@ -1345,13 +1470,13 @@ function P(skipConn = false) {
1345
1470
  // 创建表
1346
1471
  await option.conn.execute(SyncMode.Async, `
1347
1472
  CREATE TABLE IF NOT EXISTS ${tableES}(
1348
- ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
1349
- ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
1473
+ ${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
1474
+ ${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
1350
1475
  );
1351
1476
  `);
1352
1477
  if (this[_index] && this[_index].length) {
1353
1478
  for (const index of this[_index]) {
1354
- await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${Sqlstring.escapeId(option.tableName)} ("${index}");`);
1479
+ await option.conn.execute(SyncMode.Async, `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${Sqlstring.escapeId(option.tableName)} ("${this[_fields][index]?.C2()}");`);
1355
1480
  }
1356
1481
  }
1357
1482
  await option.conn.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
@@ -1409,28 +1534,44 @@ function P(skipConn = false) {
1409
1534
  };
1410
1535
  };
1411
1536
  }
1412
- const FieldFilter = (K, V, def, option) => {
1537
+ const FieldFilter = (K, V, def, uuidColumn, option) => {
1413
1538
  let ret = 0;
1414
- if (V === null) {
1415
- if (option?.skipNull !== true) {
1416
- ret = 1;
1417
- V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : null;
1539
+ // 如果是插入操作且字段是UUID,则不进行空值检查
1540
+ // 只有在非插入或者非UUID时,进行空置检查
1541
+ if (option?.insert === true && uuidColumn === true) {
1542
+ ret = 1;
1543
+ if (V === undefined) {
1544
+ V = null;
1418
1545
  }
1419
- }
1420
- else if (V === undefined) {
1421
- if (option?.skipUndefined !== true) {
1422
- ret = 1;
1423
- V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : null;
1546
+ else if (emptyString(`${V ?? ''}`)) {
1547
+ V = '';
1424
1548
  }
1425
- }
1426
- else if (emptyString(`${V ?? ''}`)) {
1427
- if (option?.skipEmptyString !== true) {
1549
+ else {
1428
1550
  ret = 1;
1429
- V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : '';
1430
1551
  }
1431
1552
  }
1432
1553
  else {
1433
- ret = 1;
1554
+ if (V === null) {
1555
+ if (option?.skipNull !== true) {
1556
+ ret = 1;
1557
+ V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : null;
1558
+ }
1559
+ }
1560
+ else if (V === undefined) {
1561
+ if (option?.skipUndefined !== true) {
1562
+ ret = 1;
1563
+ V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : null;
1564
+ }
1565
+ }
1566
+ else if (emptyString(`${V ?? ''}`)) {
1567
+ if (option?.skipEmptyString !== true) {
1568
+ ret = 1;
1569
+ V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : '';
1570
+ }
1571
+ }
1572
+ else {
1573
+ ret = 1;
1574
+ }
1434
1575
  }
1435
1576
  if (ret === 1) {
1436
1577
  option?.finalColumns?.add(K);
@@ -1443,193 +1584,195 @@ export const Field = (config) => {
1443
1584
  config.type ?? (config.type = SqlType.varchar);
1444
1585
  return (object, propertyName) => {
1445
1586
  const field = config;
1446
- field.name = propertyName;
1447
- field.esName = Sqlstring.escapeId(propertyName);
1587
+ field.P = propertyName;
1588
+ field.C = () => P2C(propertyName, globalThis[_Hump]);
1589
+ field.C2 = () => Sqlstring.escapeId(P2C(propertyName, globalThis[_Hump]));
1590
+ field.C3 = () => `${Sqlstring.escapeId(P2C(propertyName, globalThis[_Hump]))} ${propertyName}`;
1448
1591
  const hasDef = field.hasOwnProperty('def') === true;
1449
1592
  switch (field.type) {
1450
1593
  case SqlType.tinyint: {
1451
- field[DBType.Mysql] = `${field.esName} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1452
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1594
+ field[DBType.Mysql] = () => `${field.C2()} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1595
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1453
1596
  break;
1454
1597
  }
1455
1598
  case SqlType.smallint: {
1456
- field[DBType.Mysql] = `${field.esName} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1457
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1599
+ field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1600
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1458
1601
  break;
1459
1602
  }
1460
1603
  case SqlType.mediumint: {
1461
- field[DBType.Mysql] = `${field.esName} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1462
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1604
+ field[DBType.Mysql] = () => `${field.C2()} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1605
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1463
1606
  break;
1464
1607
  }
1465
1608
  case SqlType.int: {
1466
- field[DBType.Mysql] = `${field.esName} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
1467
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1609
+ field[DBType.Mysql] = () => `${field.C2()} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1610
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1468
1611
  break;
1469
1612
  }
1470
1613
  case SqlType.bigint: {
1471
- field[DBType.Mysql] = `${field.esName} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1472
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1614
+ field[DBType.Mysql] = () => `${field.C2()} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1615
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1473
1616
  break;
1474
1617
  }
1475
1618
  case SqlType.float: {
1476
- field[DBType.Mysql] = `${field.esName} float(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1477
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1619
+ field[DBType.Mysql] = () => `${field.C2()} float(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1620
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1478
1621
  break;
1479
1622
  }
1480
1623
  case SqlType.double: {
1481
- field[DBType.Mysql] = `${field.esName} double(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1482
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1624
+ field[DBType.Mysql] = () => `${field.C2()} double(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1625
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1483
1626
  break;
1484
1627
  }
1485
1628
  case SqlType.decimal: {
1486
- field[DBType.Mysql] = `${field.esName} decimal(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
1487
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
1629
+ field[DBType.Mysql] = () => `${field.C2()} decimal(${config.length ?? 1}, ${config.scale ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? `DEFAULT '${field.def}'` : ''} `;
1630
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} real`;
1488
1631
  break;
1489
1632
  }
1490
1633
  case SqlType.longtext: {
1491
- field[DBType.Mysql] = `${field.esName} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1492
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1634
+ field[DBType.Mysql] = () => `${field.C2()} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1635
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1493
1636
  break;
1494
1637
  }
1495
1638
  case SqlType.mediumtext: {
1496
- field[DBType.Mysql] = `${field.esName} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1497
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1639
+ field[DBType.Mysql] = () => `${field.C2()} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1640
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1498
1641
  break;
1499
1642
  }
1500
1643
  case SqlType.text: {
1501
- field[DBType.Mysql] = `${field.esName} text ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1502
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1644
+ field[DBType.Mysql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1645
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1503
1646
  break;
1504
1647
  }
1505
1648
  case SqlType.date: {
1506
- field[DBType.Mysql] = `${field.esName} date ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1507
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1649
+ field[DBType.Mysql] = () => `${field.C2()} date ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1650
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1508
1651
  break;
1509
1652
  }
1510
1653
  case SqlType.time: {
1511
- field[DBType.Mysql] = `${field.esName} time ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1512
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1654
+ field[DBType.Mysql] = () => `${field.C2()} time ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1655
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1513
1656
  break;
1514
1657
  }
1515
1658
  case SqlType.year: {
1516
- field[DBType.Mysql] = `${field.esName} year ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1517
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1659
+ field[DBType.Mysql] = () => `${field.C2()} year ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1660
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1518
1661
  break;
1519
1662
  }
1520
1663
  case SqlType.datetime: {
1521
- field[DBType.Mysql] = `${field.esName} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1522
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1664
+ field[DBType.Mysql] = () => `${field.C2()} datetime ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1665
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1523
1666
  break;
1524
1667
  }
1525
1668
  case SqlType.timestamp: {
1526
- field[DBType.Mysql] = `${field.esName} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1527
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
1669
+ field[DBType.Mysql] = () => `${field.C2()} timestamp ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1670
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} integer`;
1528
1671
  break;
1529
1672
  }
1530
1673
  case SqlType.char: {
1531
- field[DBType.Mysql] = `${field.esName} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1532
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1674
+ field[DBType.Mysql] = () => `${field.C2()} char(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1675
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1533
1676
  break;
1534
1677
  }
1535
1678
  case SqlType.varchar: {
1536
- field[DBType.Mysql] = `${field.esName} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1537
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1679
+ field[DBType.Mysql] = () => `${field.C2()} varchar(${config.length ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1680
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1538
1681
  break;
1539
1682
  }
1540
1683
  case SqlType.tinyblob: {
1541
- field[DBType.Mysql] = `${field.esName} tinyblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1542
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1684
+ field[DBType.Mysql] = () => `${field.C2()} tinyblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1685
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1543
1686
  break;
1544
1687
  }
1545
1688
  case SqlType.tinytext: {
1546
- field[DBType.Mysql] = `${field.esName} tinytext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1547
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1689
+ field[DBType.Mysql] = () => `${field.C2()} tinytext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1690
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1548
1691
  break;
1549
1692
  }
1550
1693
  case SqlType.blob: {
1551
- field[DBType.Mysql] = `${field.esName} binary ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1552
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1694
+ field[DBType.Mysql] = () => `${field.C2()} binary ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1695
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1553
1696
  break;
1554
1697
  }
1555
1698
  case SqlType.text: {
1556
- field[DBType.Mysql] = `${field.esName} text ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1557
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1699
+ field[DBType.Mysql] = () => `${field.C2()} text ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1700
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1558
1701
  break;
1559
1702
  }
1560
1703
  case SqlType.mediumblob: {
1561
- field[DBType.Mysql] = `${field.esName} mediumblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1562
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1704
+ field[DBType.Mysql] = () => `${field.C2()} mediumblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1705
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1563
1706
  break;
1564
1707
  }
1565
1708
  case SqlType.mediumtext: {
1566
- field[DBType.Mysql] = `${field.esName} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1567
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1709
+ field[DBType.Mysql] = () => `${field.C2()} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1710
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1568
1711
  break;
1569
1712
  }
1570
1713
  case SqlType.longblob: {
1571
- field[DBType.Mysql] = `${field.esName} longblob ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1572
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1714
+ field[DBType.Mysql] = () => `${field.C2()} longblob ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1715
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1573
1716
  break;
1574
1717
  }
1575
1718
  case SqlType.longtext: {
1576
- field[DBType.Mysql] = `${field.esName} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1577
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1719
+ field[DBType.Mysql] = () => `${field.C2()} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1720
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1578
1721
  break;
1579
1722
  }
1580
1723
  case SqlType.set: {
1581
- field[DBType.Mysql] = `${field.esName} set ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1582
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1724
+ field[DBType.Mysql] = () => `${field.C2()} set ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1725
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1583
1726
  break;
1584
1727
  }
1585
1728
  case SqlType.enum: {
1586
- field[DBType.Mysql] = `${field.esName} enum ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1587
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1729
+ field[DBType.Mysql] = () => `${field.C2()} enum ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1730
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1588
1731
  break;
1589
1732
  }
1590
1733
  case SqlType.json: {
1591
- field[DBType.Mysql] = `${field.esName} json ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1592
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1734
+ field[DBType.Mysql] = () => `${field.C2()} json ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1735
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1593
1736
  break;
1594
1737
  }
1595
1738
  case SqlType.geometry: {
1596
- field[DBType.Mysql] = `${field.esName} geometry ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1597
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1739
+ field[DBType.Mysql] = () => `${field.C2()} geometry ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1740
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1598
1741
  break;
1599
1742
  }
1600
1743
  case SqlType.point: {
1601
- field[DBType.Mysql] = `${field.esName} point ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1602
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1744
+ field[DBType.Mysql] = () => `${field.C2()} point ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1745
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1603
1746
  break;
1604
1747
  }
1605
1748
  case SqlType.linestring: {
1606
- field[DBType.Mysql] = `${field.esName} linestring ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1607
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1749
+ field[DBType.Mysql] = () => `${field.C2()} linestring ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1750
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1608
1751
  break;
1609
1752
  }
1610
1753
  case SqlType.polygon: {
1611
- field[DBType.Mysql] = `${field.esName} polygon ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1612
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1754
+ field[DBType.Mysql] = () => `${field.C2()} polygon ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1755
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1613
1756
  break;
1614
1757
  }
1615
1758
  case SqlType.multipoint: {
1616
- field[DBType.Mysql] = `${field.esName} multipoint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1617
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1759
+ field[DBType.Mysql] = () => `${field.C2()} multipoint ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1760
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1618
1761
  break;
1619
1762
  }
1620
1763
  case SqlType.multilinestring: {
1621
- field[DBType.Mysql] = `${field.esName} multilinestring ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1622
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1764
+ field[DBType.Mysql] = () => `${field.C2()} multilinestring ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1765
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1623
1766
  break;
1624
1767
  }
1625
1768
  case SqlType.multipolygon: {
1626
- field[DBType.Mysql] = `${field.esName} multipolygon ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1627
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1769
+ field[DBType.Mysql] = () => `${field.C2()} multipolygon ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1770
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1628
1771
  break;
1629
1772
  }
1630
1773
  case SqlType.geometrycollection: {
1631
- field[DBType.Mysql] = `${field.esName} geometrycollection ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
1632
- field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
1774
+ field[DBType.Mysql] = () => `${field.C2()} geometrycollection ${config.notNull === true ? 'NOT NULL' : ''} ${MYSQLCHARSET} ${hasDef ? `DEFAULT '${field.def}'` : ''}`;
1775
+ field[DBType.SqliteRemote] = field[DBType.Sqlite] = () => `${field.C2()} text`;
1633
1776
  break;
1634
1777
  }
1635
1778
  }
@@ -1676,7 +1819,7 @@ export const Field = (config) => {
1676
1819
  };
1677
1820
  export const DB = (config) => {
1678
1821
  return function (constructor) {
1679
- var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
1822
+ var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
1680
1823
  const __ids = Reflect.getMetadata(_ids, config.clz.prototype) || new Array;
1681
1824
  const __fields = Reflect.getMetadata(_fields, config.clz.prototype);
1682
1825
  const __columns = Reflect.getMetadata(_columns, config.clz.prototype);
@@ -1685,25 +1828,31 @@ export const DB = (config) => {
1685
1828
  const __deleteState = Reflect.getMetadata(_deleteState, config.clz.prototype);
1686
1829
  const __index = Reflect.getMetadata(_index, config.clz.prototype);
1687
1830
  const __def = Reflect.getMetadata(_def, config.clz.prototype);
1688
- return _t = class extends constructor {
1831
+ const className = config.tableName?.replace(/_(\w)/g, (a, b) => b.toUpperCase());
1832
+ const ClassName = className?.replace(/\w/, (v) => v.toUpperCase());
1833
+ const vueName = config.tableName?.replace(/_/g, '-');
1834
+ return _w = class extends constructor {
1689
1835
  constructor() {
1690
1836
  super(...arguments);
1691
1837
  this[_d] = config.tableName;
1692
- this[_e] = config.dbName;
1693
- this[_f] = config.dbType ?? DBType.Mysql;
1694
- this[_g] = config.sqliteVersion;
1695
- this[_h] = Object.assign({}, _defOption, config);
1696
- this[_j] = __ids;
1697
- this[_k] = __fields;
1698
- this[_l] = __columns;
1699
- this[_m] = __columnsNoId;
1700
- this[_o] = __index;
1701
- this[_p] = __def;
1702
- this[_q] = __stateFileName;
1703
- this[_r] = __deleteState;
1704
- this[_s] = (data, option) => {
1838
+ this[_e] = className;
1839
+ this[_f] = ClassName;
1840
+ this[_g] = vueName;
1841
+ this[_h] = config.dbName;
1842
+ this[_j] = config.dbType ?? DBType.Mysql;
1843
+ this[_k] = config.sqliteVersion;
1844
+ this[_l] = Object.assign({}, _defOption, config);
1845
+ this[_m] = __ids;
1846
+ this[_o] = __fields;
1847
+ this[_p] = __columns;
1848
+ this[_q] = __columnsNoId;
1849
+ this[_r] = __index;
1850
+ this[_s] = __def;
1851
+ this[_t] = __stateFileName;
1852
+ this[_u] = __deleteState;
1853
+ this[_v] = (data, option) => {
1705
1854
  return Object.fromEntries(iterare(option?.skipId === true ? __columnsNoId : __columns)
1706
- .map(K => [K, FieldFilter(K, data[K], __def, option)])
1855
+ .map(K => [K, FieldFilter(K, data[K], __def, __fields[K].uuid === true || __fields[K].uuidShort === true, option)])
1707
1856
  .filter(data => {
1708
1857
  if (data[1][0] === 1) {
1709
1858
  if (option?.onFieldExists) {
@@ -1721,20 +1870,23 @@ export const DB = (config) => {
1721
1870
  }
1722
1871
  },
1723
1872
  _d = _tableName,
1724
- _e = _daoDBName,
1725
- _f = _dbType,
1726
- _g = _sqlite_version,
1727
- _h = _SqlOption,
1728
- _j = _ids,
1729
- _k = _fields,
1730
- _l = _columns,
1731
- _m = _columnsNoId,
1732
- _o = _index,
1733
- _p = _def,
1734
- _q = _stateFileName,
1735
- _r = _deleteState,
1736
- _s = _transformer,
1737
- _t;
1873
+ _e = _className,
1874
+ _f = _ClassName,
1875
+ _g = _vueName,
1876
+ _h = _daoDBName,
1877
+ _j = _dbType,
1878
+ _k = _sqlite_version,
1879
+ _l = _SqlOption,
1880
+ _m = _ids,
1881
+ _o = _fields,
1882
+ _p = _columns,
1883
+ _q = _columnsNoId,
1884
+ _r = _index,
1885
+ _s = _def,
1886
+ _t = _stateFileName,
1887
+ _u = _deleteState,
1888
+ _v = _transformer,
1889
+ _w;
1738
1890
  };
1739
1891
  };
1740
1892
  /**
@@ -1751,7 +1903,7 @@ export const DB = (config) => {
1751
1903
  */
1752
1904
  export function DeclareClass(clz, FieldOptions) {
1753
1905
  for (const item of FieldOptions) {
1754
- tslib.__decorate([Field(item)], clz.prototype, item.name, void 0);
1906
+ tslib.__decorate([Field(item)], clz.prototype, item.P, void 0);
1755
1907
  }
1756
1908
  }
1757
1909
  /**
@@ -1788,135 +1940,194 @@ export class SqlService {
1788
1940
  const conditions = option.existConditionOtherThanIds || this[_ids];
1789
1941
  Throw.if(!conditions, 'not found where condition for insertIfNotExists!');
1790
1942
  Throw.if(conditions.length === 0, 'insertIfNotExists must have not null where!');
1791
- const where = iterare(conditions).map(c => `${this[_fields][c]?.esName} = ?`).join(' AND ');
1943
+ const where = iterare(conditions).map(c => `${this[_fields][c]?.C2()} = ?`).join(' AND ');
1792
1944
  const finalColumns = new Set();
1793
1945
  const whereColumns = conditions;
1794
- const params = datas
1795
- .map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
1796
- .flatMap(data => {
1797
- const result = [];
1946
+ const params = [];
1947
+ const questMarks = datas
1948
+ .map(data => this[_transformer](data, { ...option, finalColumns, insert: true }))
1949
+ .map(data => {
1798
1950
  const questMark = new Array();
1799
1951
  for (const column of finalColumns) {
1800
- questMark.push('?');
1801
- result.push(data.hasOwnProperty(column)
1952
+ const V = data.hasOwnProperty(column)
1802
1953
  ? data[column]
1803
1954
  : this[_def] && this[_def].hasOwnProperty(column)
1804
1955
  ? this[_def][column]
1805
- : null);
1956
+ : null;
1957
+ if (V === null) {
1958
+ const field = this[_fields][column];
1959
+ if (field?.uuid) {
1960
+ questMark.push('UUID()');
1961
+ }
1962
+ else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
1963
+ questMark.push('UUID_SHORT()');
1964
+ }
1965
+ else {
1966
+ questMark.push('?');
1967
+ params.push(V);
1968
+ }
1969
+ }
1970
+ else {
1971
+ questMark.push('?');
1972
+ params.push(V);
1973
+ }
1806
1974
  }
1807
1975
  for (const column of whereColumns) {
1808
- questMark.push('?');
1809
- result.push(data.hasOwnProperty(column)
1976
+ params.push(data.hasOwnProperty(column)
1810
1977
  ? data[column]
1811
1978
  : this[_def] && this[_def].hasOwnProperty(column)
1812
1979
  ? this[_def][column]
1813
1980
  : null);
1814
1981
  }
1815
- return result;
1982
+ return `SELECT ${questMark.join(',')} FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ${tableName} WHERE ${where})`;
1816
1983
  });
1817
- const quests = new Array(finalColumns.size).fill('?').join(',');
1818
- const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.esName).join(',');
1819
- const selects = iterare(new Array(datas.length)).map(() => `SELECT ${quests} FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ${tableName} WHERE ${where})`).join(' UNION ALL ');
1820
- const sql = `INSERT INTO
1821
- ${tableName}
1822
- (${columnNames})
1823
- ${selects};`;
1984
+ const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
1985
+ const sql = format(`INSERT INTO
1986
+ ${tableName}
1987
+ (${columnNames})
1988
+ ${questMarks.join(' UNION ALL ')};`);
1824
1989
  sqls.push({ sql, params });
1990
+ break;
1825
1991
  }
1826
1992
  case InsertMode.Replace: {
1827
1993
  const finalColumns = new Set();
1828
- const params = datas
1829
- .map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
1830
- .flatMap(data => {
1831
- const result = [];
1994
+ const params = [];
1995
+ const questMarks = datas
1996
+ .map(data => this[_transformer](data, { ...option, finalColumns, insert: true }))
1997
+ .map(data => {
1832
1998
  const questMark = new Array();
1833
1999
  for (const column of finalColumns) {
1834
- questMark.push('?');
1835
- result.push(data.hasOwnProperty(column)
2000
+ const V = data.hasOwnProperty(column)
1836
2001
  ? data[column]
1837
2002
  : this[_def] && this[_def].hasOwnProperty(column)
1838
2003
  ? this[_def][column]
1839
- : null);
2004
+ : null;
2005
+ if (V === null) {
2006
+ const field = this[_fields][column];
2007
+ if (field?.uuid) {
2008
+ questMark.push('UUID()');
2009
+ }
2010
+ else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2011
+ questMark.push('UUID_SHORT()');
2012
+ }
2013
+ else {
2014
+ questMark.push('?');
2015
+ params.push(V);
2016
+ }
2017
+ }
2018
+ else {
2019
+ questMark.push('?');
2020
+ params.push(V);
2021
+ }
1840
2022
  }
1841
- return result;
2023
+ return `(${questMark.join(',')})`;
1842
2024
  });
1843
- const quests = new Array(finalColumns.size).fill('?').join(',');
1844
- const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.esName).join(',');
1845
- const questMarks = iterare(new Array(datas.length)).map(() => `(${quests})`).join(',');
1846
- const sql = `
2025
+ const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2026
+ const sql = format(`
1847
2027
  ${this[_dbType] === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
1848
2028
  ${tableName}
1849
2029
  (${columnNames})
1850
2030
  VALUES ${questMarks};
1851
- `;
2031
+ `);
1852
2032
  sqls.push({ sql, params });
2033
+ break;
1853
2034
  }
1854
2035
  case InsertMode.Insert: {
1855
2036
  const finalColumns = new Set();
1856
- const params = datas
1857
- .map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
1858
- .flatMap(data => {
1859
- const result = [];
2037
+ const params = [];
2038
+ const questMarks = datas
2039
+ .map(data => this[_transformer](data, { ...option, finalColumns, insert: true }))
2040
+ .map(data => {
1860
2041
  const questMark = new Array();
1861
2042
  for (const column of finalColumns) {
1862
- questMark.push('?');
1863
- result.push(data.hasOwnProperty(column)
2043
+ const V = data.hasOwnProperty(column)
1864
2044
  ? data[column]
1865
2045
  : this[_def] && this[_def].hasOwnProperty(column)
1866
2046
  ? this[_def][column]
1867
- : null);
2047
+ : null;
2048
+ if (V === null) {
2049
+ const field = this[_fields][column];
2050
+ if (field?.uuid) {
2051
+ questMark.push('UUID()');
2052
+ }
2053
+ else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2054
+ questMark.push('UUID_SHORT()');
2055
+ }
2056
+ else {
2057
+ questMark.push('?');
2058
+ params.push(V);
2059
+ }
2060
+ }
2061
+ else {
2062
+ questMark.push('?');
2063
+ params.push(V);
2064
+ }
1868
2065
  }
1869
- return result;
2066
+ return `(${questMark.join(',')})`;
1870
2067
  });
1871
- const quests = new Array(finalColumns.size).fill('?').join(',');
1872
- const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.esName).join(',');
1873
- const questMarks = iterare(new Array(datas.length)).map(() => `(${quests})`).join(',');
1874
- const sql = `
2068
+ const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
2069
+ const sql = format(`
1875
2070
  INSERT INTO
1876
2071
  ${tableName}
1877
2072
  (${columnNames})
1878
2073
  VALUES ${questMarks};
1879
- `;
2074
+ `);
1880
2075
  sqls.push({ sql, params });
2076
+ break;
1881
2077
  }
1882
2078
  case InsertMode.InsertWithTempTable: {
1883
2079
  const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
1884
2080
  const tableTempESC = Sqlstring.escapeId(tableTemp);
1885
2081
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
1886
2082
  const finalColumns = new Set();
1887
- const params = datas
1888
- .map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
1889
- .flatMap(data => {
1890
- const result = [];
2083
+ const params = [];
2084
+ const questMarks = datas
2085
+ .map(data => this[_transformer](data, { ...option, finalColumns, insert: true }))
2086
+ .map(data => {
1891
2087
  const questMark = new Array();
1892
2088
  for (const column of finalColumns) {
1893
- questMark.push('?');
1894
- result.push(data.hasOwnProperty(column)
2089
+ const V = data.hasOwnProperty(column)
1895
2090
  ? data[column]
1896
2091
  : this[_def] && this[_def].hasOwnProperty(column)
1897
2092
  ? this[_def][column]
1898
- : null);
2093
+ : null;
2094
+ if (V === null) {
2095
+ const field = this[_fields][column];
2096
+ if (field?.uuid) {
2097
+ questMark.push('UUID()');
2098
+ }
2099
+ else if (field?.uuidShort && this[_dbType] === DBType.Mysql) {
2100
+ questMark.push('UUID_SHORT()');
2101
+ }
2102
+ else {
2103
+ questMark.push('?');
2104
+ params.push(V);
2105
+ }
2106
+ }
2107
+ else {
2108
+ questMark.push('?');
2109
+ params.push(V);
2110
+ }
1899
2111
  }
1900
- return result;
2112
+ return `(${questMark.join(',')})`;
1901
2113
  });
1902
2114
  const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: Array.from(finalColumns) });
1903
2115
  sqls.push(..._sqls);
1904
- const quests = new Array(finalColumns.size).fill('?').join(',');
1905
- const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.esName).join(',');
1906
- const questMarks = iterare(new Array(datas.length)).map(() => `(${quests})`).join(',');
2116
+ const columnNames = iterare(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
1907
2117
  sqls.push({
1908
- sql: `
2118
+ sql: format(`
1909
2119
  INSERT INTO
1910
2120
  ${tableTemp}
1911
2121
  (${columnNames})
1912
2122
  VALUES ${questMarks};
1913
- `, params
2123
+ `), params
1914
2124
  });
1915
2125
  sqls.push({
1916
- sql: `INSERT INTO ${Sqlstring.escapeId(option.tableName)} (${columnNames})
1917
- SELECT ${columnNames} FROM ${tableTemp};`
2126
+ sql: format(`INSERT INTO ${Sqlstring.escapeId(option.tableName)} (${columnNames})
2127
+ SELECT ${columnNames} FROM ${tableTemp};`)
1918
2128
  });
1919
2129
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2130
+ break;
1920
2131
  }
1921
2132
  }
1922
2133
  return sqls;
@@ -1943,7 +2154,7 @@ export class SqlService {
1943
2154
  else
1944
2155
  return result[0];
1945
2156
  };
1946
- if (option?.conn?.[_inTransaction] === true) {
2157
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
1947
2158
  return fn();
1948
2159
  }
1949
2160
  else {
@@ -1967,12 +2178,17 @@ export class SqlService {
1967
2178
  return result;
1968
2179
  }, option?.conn);
1969
2180
  };
1970
- return new Promise(async (resolve) => {
1971
- if (option?.conn?.[_inTransaction] === true) {
1972
- resolve((await fn()));
2181
+ return new Promise(async (resolve, reject) => {
2182
+ try {
2183
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2184
+ resolve((await fn()));
2185
+ }
2186
+ else {
2187
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2188
+ }
1973
2189
  }
1974
- else {
1975
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2190
+ catch (error) {
2191
+ reject(error);
1976
2192
  }
1977
2193
  });
1978
2194
  }
@@ -1991,12 +2207,17 @@ export class SqlService {
1991
2207
  }, { everyLength: 1 });
1992
2208
  return result[0];
1993
2209
  };
1994
- return new Promise(async (resolve) => {
1995
- if (option?.conn?.[_inTransaction] === true) {
1996
- resolve((await fn()));
2210
+ return new Promise(async (resolve, reject) => {
2211
+ try {
2212
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2213
+ resolve((await fn()));
2214
+ }
2215
+ else {
2216
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2217
+ }
1997
2218
  }
1998
- else {
1999
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2219
+ catch (error) {
2220
+ reject(error);
2000
2221
  }
2001
2222
  });
2002
2223
  }
@@ -2004,7 +2225,7 @@ export class SqlService {
2004
2225
  _update(datas, option) {
2005
2226
  const sqls = [];
2006
2227
  const tableName = Sqlstring.escapeId(option?.tableName);
2007
- const where = `WHEN ${iterare(this[_ids]).map(c => `${this[_fields][c]?.esName} = ?`).join(' AND ')} THEN ?`;
2228
+ const where = `WHEN ${iterare(this[_ids]).map(c => `${this[_fields][c]?.C2()} = ?`).join(' AND ')} THEN ?`;
2008
2229
  const columnMaps = Object.fromEntries(this[_columnsNoId].map(c => [c, {
2009
2230
  where: new Array(),
2010
2231
  params: []
@@ -2024,13 +2245,13 @@ export class SqlService {
2024
2245
  }
2025
2246
  });
2026
2247
  }
2027
- const sql = `UPDATE ${tableName} SET ${iterare(this[_columnsNoId])
2248
+ const sql = format(`UPDATE ${tableName} SET ${iterare(this[_columnsNoId])
2028
2249
  .filter(K => columnMaps[K].where.length > 0)
2029
2250
  .map(K => {
2030
2251
  params.push(...columnMaps[K].params);
2031
- return `${this[_fields][K]?.esName} = CASE ${columnMaps[K].where.join(' ')} ELSE ${this[_fields][K]?.esName} END`;
2252
+ return `${this[_fields][K]?.C2()} = CASE ${columnMaps[K].where.join(' ')} ELSE ${this[_fields][K]?.C2()} END`;
2032
2253
  })
2033
- .join(',')};`;
2254
+ .join(',')};`);
2034
2255
  sqls.push({ sql, params });
2035
2256
  return sqls;
2036
2257
  }
@@ -2052,7 +2273,7 @@ export class SqlService {
2052
2273
  }, { everyLength: option?.maxDeal });
2053
2274
  return result.reduce((a, b) => a + b);
2054
2275
  };
2055
- if (option?.conn?.[_inTransaction] === true) {
2276
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2056
2277
  return fn();
2057
2278
  }
2058
2279
  else {
@@ -2074,12 +2295,17 @@ export class SqlService {
2074
2295
  }, { everyLength: option?.maxDeal });
2075
2296
  return result.reduce((a, b) => a + b);
2076
2297
  };
2077
- return new Promise(async (resolve) => {
2078
- if (option?.conn?.[_inTransaction] === true) {
2079
- resolve((await fn()));
2298
+ return new Promise(async (resolve, reject) => {
2299
+ try {
2300
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2301
+ resolve((await fn()));
2302
+ }
2303
+ else {
2304
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2305
+ }
2080
2306
  }
2081
- else {
2082
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2307
+ catch (error) {
2308
+ reject(error);
2083
2309
  }
2084
2310
  });
2085
2311
  }
@@ -2107,20 +2333,20 @@ export class SqlService {
2107
2333
  return `(
2108
2334
  ${Object.entries(where).map(([K, V]) => {
2109
2335
  params.push(V);
2110
- return `${K} = ?`;
2336
+ return `${this[_fields][K]?.C2()} = ?`;
2111
2337
  }).join(' AND ')}
2112
2338
  )`;
2113
2339
  }).join(' OR ');
2114
2340
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2115
2341
  sqls.push({
2116
- sql: `
2117
- UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.esName} = ${Sqlstring.escape(this[_deleteState])}
2342
+ sql: format(`
2343
+ UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ${Sqlstring.escape(this[_deleteState])}
2118
2344
  WHERE ${whereSql};
2119
- `, params
2345
+ `), params
2120
2346
  });
2121
2347
  }
2122
2348
  else {
2123
- sqls.push({ sql: `DELETE FROM ${tableNameESC} WHERE ${whereSql};`, params });
2349
+ sqls.push({ sql: format(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`), params });
2124
2350
  }
2125
2351
  }
2126
2352
  else {
@@ -2132,28 +2358,30 @@ export class SqlService {
2132
2358
  case DBType.Mysql: {
2133
2359
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2134
2360
  sqls.push({
2135
- sql: `UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.esName} = b.${this[_fields][K]?.esName}`).join(' AND ')}
2136
- SET a.${this[_fields][this[_stateFileName]]?.esName} = ${Sqlstring.escape(this[_deleteState])};`
2361
+ 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 ')}
2362
+ SET a.${this[_fields][this[_stateFileName]]?.C2()} = ${Sqlstring.escape(this[_deleteState])};`)
2137
2363
  });
2138
2364
  }
2139
2365
  else {
2140
2366
  sqls.push({
2141
- 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 ')};`
2367
+ 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 ')};`)
2142
2368
  });
2143
2369
  }
2370
+ break;
2144
2371
  }
2145
2372
  case DBType.Sqlite:
2146
2373
  case DBType.SqliteRemote: {
2147
- const columnNames = iterare(delWhere).map(K => this[_fields][K]?.esName).join(',');
2374
+ const columnNames = iterare(delWhere).map(K => this[_fields][K]?.C2()).join(',');
2148
2375
  if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
2149
2376
  sqls.push({
2150
- sql: `UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.esName} = ${Sqlstring.escape(this[_deleteState])}
2151
- WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`
2377
+ sql: format(`UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ${Sqlstring.escape(this[_deleteState])}
2378
+ WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`)
2152
2379
  });
2153
2380
  }
2154
2381
  else {
2155
- sqls.push({ sql: `DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});` });
2382
+ sqls.push({ sql: format(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`) });
2156
2383
  }
2384
+ break;
2157
2385
  }
2158
2386
  }
2159
2387
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
@@ -2167,7 +2395,7 @@ export class SqlService {
2167
2395
  }
2168
2396
  return result;
2169
2397
  };
2170
- if (option?.conn?.[_inTransaction] === true) {
2398
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2171
2399
  return fn();
2172
2400
  }
2173
2401
  else {
@@ -2183,12 +2411,17 @@ export class SqlService {
2183
2411
  }
2184
2412
  return result;
2185
2413
  };
2186
- return new Promise(async (resolve) => {
2187
- if (option?.conn?.[_inTransaction] === true) {
2188
- resolve((await fn()));
2414
+ return new Promise(async (resolve, reject) => {
2415
+ try {
2416
+ if (this[_dbType] === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
2417
+ resolve((await fn()));
2418
+ }
2419
+ else {
2420
+ await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2421
+ }
2189
2422
  }
2190
- else {
2191
- await option?.dao?.transaction(SyncMode.Async, async () => resolve((await fn())), option?.conn);
2423
+ catch (error) {
2424
+ reject(error);
2192
2425
  }
2193
2426
  });
2194
2427
  }
@@ -2228,19 +2461,19 @@ export class SqlService {
2228
2461
  const ids = option.id instanceof Array ? option.id : [option.id];
2229
2462
  option.where = ids.map(i => ({ [idName]: i }));
2230
2463
  }
2231
- const columns = option.templateResult === TemplateResult.Count ? 'COUNT(1) ct' : iterare((option.columns ?? this[_columns])).map((K) => `a.${this[_fields][K]?.esName}`).join(',');
2464
+ const columns = option.templateResult === TemplateResult.Count ? 'COUNT(1) ct' : iterare((option.columns ?? this[_columns])).map((K) => `a.${this[_fields][K]?.C3()}`).join(',');
2232
2465
  const wheres = option.where instanceof Array ? option.where : [option.where];
2233
2466
  const sqls = [];
2234
2467
  let resultIndex = -1;
2235
2468
  if (option.mode === SelectMode.Common) {
2236
2469
  const params = new Array();
2237
- const whereSql = iterare(wheres).map(where => {
2470
+ const whereSql = format(iterare(wheres).map(where => this[_transformer](where, option)).map(where => {
2238
2471
  return `SELECT ${columns} FROM ${tableNameESC} a WHERE
2239
2472
  ${Object.entries(where).map(([K, V]) => {
2240
2473
  params.push(V);
2241
- return `${K} = ?`;
2474
+ return `${this[_fields][K]?.C2()} = ?`;
2242
2475
  }).join(' AND ')}`;
2243
- }).join(' UNION ALL ');
2476
+ }).join(' UNION ALL '));
2244
2477
  sqls.push({ sql: whereSql, params });
2245
2478
  resultIndex = 0;
2246
2479
  }
@@ -2250,7 +2483,7 @@ export class SqlService {
2250
2483
  const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
2251
2484
  sqls.push(..._sqls);
2252
2485
  resultIndex = sqls.length;
2253
- 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 ')};` });
2486
+ 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 ')};`) });
2254
2487
  sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
2255
2488
  }
2256
2489
  if (option.sync === SyncMode.Sync) {
@@ -2266,21 +2499,26 @@ export class SqlService {
2266
2499
  return this._template(option.templateResult, result, option.error);
2267
2500
  }
2268
2501
  else {
2269
- return new Promise(async (resolve) => {
2270
- let result;
2271
- for (let i = 0; i < sqls.length; i++) {
2272
- if (i === resultIndex) {
2273
- result = await option.conn.query(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2274
- }
2275
- else {
2276
- await option.conn.execute(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2502
+ return new Promise(async (resolve, reject) => {
2503
+ try {
2504
+ let result;
2505
+ for (let i = 0; i < sqls.length; i++) {
2506
+ if (i === resultIndex) {
2507
+ result = await option.conn.query(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2508
+ }
2509
+ else {
2510
+ await option.conn.execute(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
2511
+ }
2277
2512
  }
2513
+ resolve(this._template(option.templateResult, result, option.error));
2514
+ }
2515
+ catch (error) {
2516
+ reject(error);
2278
2517
  }
2279
- resolve(this._template(option.templateResult, result, option.error));
2280
2518
  });
2281
2519
  }
2282
2520
  }
2283
- _select(templateResult, result, def, errorMsg, multiple) {
2521
+ _select(templateResult, result, def, errorMsg, multiple, hump) {
2284
2522
  if (multiple === true) {
2285
2523
  switch (templateResult) {
2286
2524
  case SelectResult.One_Row_One_Column_NotSure: {
@@ -2299,6 +2537,9 @@ export class SqlService {
2299
2537
  }
2300
2538
  case SelectResult.One_Row_Many_Column_NotSure: {
2301
2539
  try {
2540
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
2541
+ return result.map((r) => C2P2(r[0]));
2542
+ }
2302
2543
  return result.map((r) => r[0]);
2303
2544
  }
2304
2545
  catch (error) {
@@ -2306,6 +2547,9 @@ export class SqlService {
2306
2547
  }
2307
2548
  case SelectResult.One_Row_Many_Column_Assert: {
2308
2549
  try {
2550
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
2551
+ return iterare(result).map((r) => C2P2(r[0])).filter((r) => r !== null).toArray();
2552
+ }
2309
2553
  return iterare(result).map((r) => r[0]).filter((r) => r !== null).toArray();
2310
2554
  }
2311
2555
  catch (error) {
@@ -2319,7 +2563,12 @@ export class SqlService {
2319
2563
  }
2320
2564
  }
2321
2565
  case SelectResult.Many_Row_Many_Column: {
2322
- return result;
2566
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
2567
+ return iterare(result).map((r) => r.map((rr) => C2P2(rr))).toArray();
2568
+ }
2569
+ else {
2570
+ return result;
2571
+ }
2323
2572
  }
2324
2573
  }
2325
2574
  }
@@ -2344,12 +2593,22 @@ export class SqlService {
2344
2593
  }
2345
2594
  }
2346
2595
  case SelectResult.One_Row_Many_Column_NotSure: {
2347
- return result[0] ?? null;
2596
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
2597
+ return C2P2(result[0]) ?? null;
2598
+ }
2599
+ else {
2600
+ return result[0] ?? null;
2601
+ }
2348
2602
  }
2349
2603
  case SelectResult.One_Row_Many_Column_Assert: {
2350
2604
  const data = result[0];
2351
- Throw.if(data === null, errorMsg ?? 'not found data!');
2352
- return data ?? null;
2605
+ Throw.if(data === null || data === undefined, errorMsg ?? 'not found data!');
2606
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
2607
+ return C2P2(data) ?? null;
2608
+ }
2609
+ else {
2610
+ return data ?? null;
2611
+ }
2353
2612
  }
2354
2613
  case SelectResult.Many_Row_One_Column: {
2355
2614
  try {
@@ -2360,7 +2619,12 @@ export class SqlService {
2360
2619
  }
2361
2620
  }
2362
2621
  case SelectResult.Many_Row_Many_Column: {
2363
- return result;
2622
+ if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
2623
+ return iterare(result).map((r) => C2P2(r)).toArray();
2624
+ }
2625
+ else {
2626
+ return result;
2627
+ }
2364
2628
  }
2365
2629
  }
2366
2630
  }
@@ -2370,8 +2634,7 @@ export class SqlService {
2370
2634
  option.selectResult ?? (option.selectResult = SelectResult.Many_Row_Many_Column);
2371
2635
  option.defValue ?? (option.defValue = null);
2372
2636
  const _params = Object.assign({}, option.context, option.params);
2373
- option.sql ?? (option.sql = globalThis[_sqlCache].load(option.sqlId, { ctx: option.context, isCount: option.isCount, ..._params }));
2374
- logger.debug(option.sql);
2637
+ option.sql ?? (option.sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: option.isCount, ..._params }));
2375
2638
  const params = [];
2376
2639
  const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2377
2640
  if (_params.hasOwnProperty(key)) {
@@ -2379,24 +2642,40 @@ export class SqlService {
2379
2642
  params.push(V);
2380
2643
  return Sqlstring.escape(_params[key]);
2381
2644
  }
2645
+ const _key = C2P(key);
2646
+ if (_params.hasOwnProperty(_key)) {
2647
+ const V = _params[_key];
2648
+ params.push(V);
2649
+ return Sqlstring.escape(_params[_key]);
2650
+ }
2651
+ const __key = P2C(key);
2652
+ if (_params.hasOwnProperty(__key)) {
2653
+ const V = _params[__key];
2654
+ params.push(V);
2655
+ return Sqlstring.escape(_params[__key]);
2656
+ }
2382
2657
  return txt;
2383
2658
  });
2384
2659
  if (option.sync === SyncMode.Sync) {
2385
2660
  const result = option.conn.query(SyncMode.Sync, sql, params);
2386
- return this._select(option.selectResult, result, option.defValue, option.errorMsg, option.multiple);
2661
+ return this._select(option.selectResult, result, option.defValue, option.errorMsg, option.multiple, option.hump);
2387
2662
  }
2388
2663
  else {
2389
- return new Promise(async (resolve) => {
2390
- const result = await option.conn.query(SyncMode.Async, sql, params);
2391
- resolve(this._select(option.selectResult, result, option.defValue, option.errorMsg, option.multiple));
2664
+ return new Promise(async (resolve, reject) => {
2665
+ try {
2666
+ const result = await option.conn.query(SyncMode.Async, sql, params);
2667
+ resolve(this._select(option.selectResult, result, option.defValue, option.errorMsg, option.multiple));
2668
+ }
2669
+ catch (error) {
2670
+ reject(error);
2671
+ }
2392
2672
  });
2393
2673
  }
2394
2674
  }
2395
2675
  excute(option) {
2396
2676
  Throw.if(!option.sqlId && !option.sql, 'not found sql!');
2397
2677
  const _params = Object.assign({}, option.context, option.params);
2398
- option.sql ?? (option.sql = globalThis[_sqlCache].load(option.sqlId, { ctx: option.context, ..._params }));
2399
- logger.debug(option.sql);
2678
+ option.sql ?? (option.sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, ..._params }));
2400
2679
  const params = [];
2401
2680
  const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
2402
2681
  if (_params.hasOwnProperty(key)) {
@@ -2404,6 +2683,18 @@ export class SqlService {
2404
2683
  params.push(V);
2405
2684
  return Sqlstring.escape(_params[key]);
2406
2685
  }
2686
+ const _key = C2P(key);
2687
+ if (_params.hasOwnProperty(_key)) {
2688
+ const V = _params[_key];
2689
+ params.push(V);
2690
+ return Sqlstring.escape(_params[_key]);
2691
+ }
2692
+ const __key = P2C(key);
2693
+ if (_params.hasOwnProperty(__key)) {
2694
+ const V = _params[__key];
2695
+ params.push(V);
2696
+ return Sqlstring.escape(_params[__key]);
2697
+ }
2407
2698
  return txt;
2408
2699
  });
2409
2700
  if (option.sync === SyncMode.Sync) {
@@ -2411,9 +2702,14 @@ export class SqlService {
2411
2702
  return result.affectedRows;
2412
2703
  }
2413
2704
  else {
2414
- return new Promise(async (resolve) => {
2415
- const result = await option.conn.execute(SyncMode.Async, sql, params);
2416
- resolve(result.affectedRows);
2705
+ return new Promise(async (resolve, reject) => {
2706
+ try {
2707
+ const result = await option.conn.execute(SyncMode.Async, sql, params);
2708
+ resolve(result.affectedRows);
2709
+ }
2710
+ catch (error) {
2711
+ reject(error);
2712
+ }
2417
2713
  });
2418
2714
  }
2419
2715
  }
@@ -2422,14 +2718,127 @@ export class SqlService {
2422
2718
  return option.dao.transaction(SyncMode.Sync, option.fn);
2423
2719
  }
2424
2720
  else {
2425
- return new Promise(async (resolve) => {
2426
- const rt = await option.dao.transaction(SyncMode.Async, option.fn);
2427
- resolve(rt);
2721
+ return new Promise(async (resolve, reject) => {
2722
+ try {
2723
+ const rt = await option.dao.transaction(SyncMode.Async, option.fn);
2724
+ resolve(rt);
2725
+ }
2726
+ catch (error) {
2727
+ reject(error);
2728
+ }
2428
2729
  });
2429
2730
  }
2430
2731
  }
2431
2732
  stream(option) {
2432
- return new StreamQuery(option?.tableName ?? this[_tableName], this);
2733
+ return new StreamQuery(option?.tableName ?? this[_tableName], this, this[_fields], this[_columns]);
2734
+ }
2735
+ page(option) {
2736
+ const result = {
2737
+ sum: {},
2738
+ records: [],
2739
+ size: 0,
2740
+ total: 0
2741
+ };
2742
+ Object.assign(option.params, {
2743
+ limitStart: calc(option.pageNumber).sub(1).mul(option.pageSize).over(),
2744
+ limitEnd: calc(option.pageSize).over(),
2745
+ orderBy: option.orderBy
2746
+ });
2747
+ let sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: false, ...option.params });
2748
+ let sqlSum = '';
2749
+ let sqlCount = '';
2750
+ if (option.sumSelf === true) {
2751
+ sqlSum = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: false, isSum: true, ...option.params });
2752
+ }
2753
+ if (option.limitSelf !== true) {
2754
+ if (option.countSelf !== true) {
2755
+ }
2756
+ if (option.orderBy) {
2757
+ sql = `${sql} ORDER BY ${option.orderBy}`;
2758
+ }
2759
+ if (option.pageSize > 0) {
2760
+ sql = `${sql} LIMIT ${option.params['limitStart']}, ${option.pageSize}`;
2761
+ }
2762
+ }
2763
+ if (option.pageSize > 0) {
2764
+ if (option.countSelf === true) {
2765
+ sqlCount = globalThis[_sqlCache].load(this._matchSqlid(`${option.sqlId}_count`), { ctx: option.context, isCount: true, isSum: false, ...option.params });
2766
+ }
2767
+ else {
2768
+ sqlCount = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: true, isSum: false, ...option.params });
2769
+ }
2770
+ }
2771
+ if (option.sync === SyncMode.Sync) {
2772
+ if (sqlCount) {
2773
+ result.total = this.select({
2774
+ ...option,
2775
+ sql: sqlCount,
2776
+ sync: SyncMode.Sync,
2777
+ selectResult: SelectResult.One_Row_One_Column_Assert
2778
+ });
2779
+ result.size = calc(result.total)
2780
+ .add(option.pageSize - 1)
2781
+ .div(option.pageSize)
2782
+ .round(0, 2)
2783
+ .over();
2784
+ }
2785
+ if (sqlSum) {
2786
+ result.sum = this.select({
2787
+ ...option,
2788
+ sql: sqlSum,
2789
+ sync: SyncMode.Sync,
2790
+ selectResult: SelectResult.One_Row_Many_Column_Assert
2791
+ });
2792
+ }
2793
+ if (sql) {
2794
+ result.records = this.select({
2795
+ ...option,
2796
+ sql,
2797
+ sync: SyncMode.Sync,
2798
+ selectResult: SelectResult.Many_Row_Many_Column
2799
+ });
2800
+ }
2801
+ return result;
2802
+ }
2803
+ else {
2804
+ return new Promise(async (resolve, reject) => {
2805
+ try {
2806
+ if (sqlCount) {
2807
+ result.total = await this.select({
2808
+ ...option,
2809
+ sql: sqlCount,
2810
+ sync: SyncMode.Async,
2811
+ selectResult: SelectResult.One_Row_One_Column_Assert
2812
+ });
2813
+ result.size = calc(result.total)
2814
+ .add(option.pageSize - 1)
2815
+ .div(option.pageSize)
2816
+ .round(0, 2)
2817
+ .over();
2818
+ }
2819
+ if (sqlSum) {
2820
+ result.sum = await this.select({
2821
+ ...option,
2822
+ sql: sqlSum,
2823
+ sync: SyncMode.Async,
2824
+ selectResult: SelectResult.One_Row_Many_Column_Assert
2825
+ });
2826
+ }
2827
+ if (sql) {
2828
+ result.records = await this.select({
2829
+ ...option,
2830
+ sql,
2831
+ sync: SyncMode.Async,
2832
+ selectResult: SelectResult.Many_Row_Many_Column
2833
+ });
2834
+ }
2835
+ resolve(result);
2836
+ }
2837
+ catch (error) {
2838
+ reject(error);
2839
+ }
2840
+ });
2841
+ }
2433
2842
  }
2434
2843
  /**
2435
2844
  #创建表
@@ -2475,59 +2884,67 @@ export class SqlService {
2475
2884
  tableName = Sqlstring.escapeId(tableName ?? this[_tableName]);
2476
2885
  switch (this[_dbType]) {
2477
2886
  case DBType.Mysql: {
2478
- let sql = `CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
2479
- ${columns.map(K => this[_fields][K][DBType.Mysql]).join(',')}
2480
- ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.esName).join(',')}) USING BTREE ` : ''}
2481
- ${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields][i]?.esName} (${this[_fields][i]?.esName})`).join(',')} ` : ''}
2482
- ) ENGINE=MEMORY;`;
2887
+ let sql = format(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
2888
+ ${columns.map(K => this[_fields][K][DBType.Mysql]()).join(',')}
2889
+ ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) USING BTREE ` : ''}
2890
+ ${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields][i]?.C2()} (${this[_fields][i]?.C2()})`).join(',')} ` : ''}
2891
+ ) ENGINE=MEMORY;`);
2483
2892
  sqls.push({ sql });
2484
2893
  if (data && data.length > 0) {
2485
2894
  const params = [];
2486
2895
  let first = true;
2487
- sql = `INSERT INTO ${tableName} (${columns.map(c => Sqlstring.escapeId(c)).join(',')})
2896
+ sql = format(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
2488
2897
  ${(data).map(d => {
2489
2898
  const r = `SELECT ${Object.entries(d).map(([K, V]) => {
2490
2899
  params.push(V);
2491
- return `? ${first ? this[_fields][K]?.esName : ''}`;
2900
+ return `? ${first ? this[_fields][K]?.C2() : ''}`;
2492
2901
  }).join(',')}`;
2493
2902
  first = false;
2494
2903
  return r;
2495
- }).join(' UNION ALL ')}`;
2904
+ }).join(' UNION ALL ')}`);
2496
2905
  sqls.push({ sql, params });
2497
2906
  }
2498
2907
  break;
2499
2908
  }
2500
2909
  case DBType.Sqlite:
2501
2910
  case DBType.SqliteRemote: {
2502
- let sql = `CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
2503
- ${columns.map(K => this[_fields][K][DBType.Sqlite]).join(',')}
2504
- ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.esName).join(',')}) ` : ''}
2505
- );`;
2911
+ let sql = format(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
2912
+ ${columns.map(K => this[_fields][K][DBType.Sqlite]()).join(',')}
2913
+ ${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) ` : ''}
2914
+ );`);
2506
2915
  sqls.push({ sql });
2507
2916
  if (indexs) {
2508
2917
  for (const index of indexs) {
2509
- sql = `CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields][index]?.esName});`;
2918
+ sql = format(`CREATE INDEX ${Sqlstring.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields][index]?.C2()});`);
2510
2919
  sqls.push({ sql });
2511
2920
  }
2512
2921
  }
2513
2922
  if (data && data.length > 0) {
2514
2923
  const params = [];
2515
2924
  let first = true;
2516
- sql = `INSERT INTO ${tableName} (${columns.map(c => Sqlstring.escapeId(c)).join(',')})
2925
+ sql = format(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
2517
2926
  ${(data).map(d => {
2518
2927
  const r = `SELECT ${Object.entries(d).map(([K, V]) => {
2519
2928
  params.push(V);
2520
- return `? ${first ? this[_fields][K]?.esName : ''}`;
2929
+ return `? ${first ? this[_fields][K]?.C2() : ''}`;
2521
2930
  }).join(',')}`;
2522
2931
  first = false;
2523
2932
  return r;
2524
- }).join(' UNION ALL ')}`;
2933
+ }).join(' UNION ALL ')}`);
2525
2934
  sqls.push({ sql, params });
2526
2935
  }
2936
+ break;
2527
2937
  }
2528
2938
  }
2529
2939
  return sqls;
2530
2940
  }
2941
+ _matchSqlid(sqlid) {
2942
+ sqlid ?? (sqlid = '');
2943
+ if (sqlid.includes('.'))
2944
+ return [sqlid];
2945
+ else
2946
+ return [`${this[_tableName]}.${sqlid}`, `${this[_className]}.${sqlid}`, `${this[_ClassName]}.${sqlid}`, `${this[_vueName]}.${sqlid}`];
2947
+ }
2531
2948
  }
2532
2949
  __decorate([
2533
2950
  P(),
@@ -2571,6 +2988,12 @@ __decorate([
2571
2988
  __metadata("design:paramtypes", [Object]),
2572
2989
  __metadata("design:returntype", Object)
2573
2990
  ], SqlService.prototype, "transaction", null);
2991
+ __decorate([
2992
+ P(),
2993
+ __metadata("design:type", Function),
2994
+ __metadata("design:paramtypes", [Object]),
2995
+ __metadata("design:returntype", Object)
2996
+ ], SqlService.prototype, "page", null);
2574
2997
  /** 是否进行下一个动作 */
2575
2998
  const IF_PROCEED = function () {
2576
2999
  return function (_target, _propertyKey, descriptor) {
@@ -2604,8 +3027,8 @@ const IF_EXEC = function (def) {
2604
3027
  };
2605
3028
  };
2606
3029
  };
2607
- class StreamCondition {
2608
- constructor() {
3030
+ class StreamQuery {
3031
+ constructor(table, service, __fields, __columns) {
2609
3032
  this._prefix = 0;
2610
3033
  this._index = 0;
2611
3034
  this._wheres = [];
@@ -2615,7 +3038,18 @@ class StreamCondition {
2615
3038
  this._param = {};
2616
3039
  this.if_proceed = true;
2617
3040
  this.if_exec = true;
3041
+ this._distinct = false;
3042
+ this._columns = [];
3043
+ this._updateColumns = [];
3044
+ this._groups = [];
3045
+ this._orders = [];
3046
+ this._startRow = 0;
3047
+ this._pageSize = 0;
2618
3048
  this._prefix = parseInt(`${Math.random() * 1000}`);
3049
+ this._table = table;
3050
+ this._service = service;
3051
+ this[_fields] = __fields;
3052
+ this[_columns] = __columns;
2619
3053
  }
2620
3054
  /** 将当前stream重置 */
2621
3055
  reset() {
@@ -2623,8 +3057,15 @@ class StreamCondition {
2623
3057
  this._wheres.length = 0;
2624
3058
  this._param = {};
2625
3059
  this._paramKeys = {};
3060
+ this._pageSize = 0;
3061
+ this._startRow = 0;
3062
+ this._orders.length = 0;
3063
+ this._groups.length = 0;
3064
+ this._columns.length = 0;
3065
+ this._updateColumns.length = 0;
2626
3066
  return this;
2627
3067
  }
3068
+ // #region 条件
2628
3069
  /** 为下次链条执行提供条件判断:非异步方法跳过,异步方法不执行并返回默认值 */
2629
3070
  if(condition) {
2630
3071
  this.if_proceed = condition;
@@ -2632,23 +3073,33 @@ class StreamCondition {
2632
3073
  }
2633
3074
  eq(key, value, { name } = {}) { return this._(key, value, '=', { name }); }
2634
3075
  eqT(t, { name } = {}) {
2635
- if (name && this._paramKeys[name]) {
2636
- for (const [key, pname] of Object.entries(this._paramKeys[name])) {
2637
- this._param[pname] = t[key];
2638
- }
2639
- }
2640
- else {
2641
- const paramKeys = {};
2642
- for (const [key, value] of Object.entries(t)) {
2643
- const pkey = `p${this._prefix}${this._index++}`;
2644
- this._wheres.push(`AND ${String(key)} = :${pkey} `);
2645
- this._param[pkey] = value;
2646
- if (name) {
2647
- paramKeys[key] = pkey;
3076
+ if (t) {
3077
+ t = this._service[_transformer](t, {
3078
+ skipNull: true,
3079
+ skipUndefined: true,
3080
+ skipEmptyString: true
3081
+ });
3082
+ const keys = Object.keys(t);
3083
+ if (keys.length > 0) {
3084
+ if (name && this._paramKeys[name]) {
3085
+ for (const [key, pname] of Object.entries(this._paramKeys[name])) {
3086
+ this._param[pname] = t[key];
3087
+ }
3088
+ }
3089
+ else {
3090
+ const paramKeys = {};
3091
+ for (const [key, value] of Object.entries(t)) {
3092
+ const pkey = `p${this._prefix}${this._index++}`;
3093
+ this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} = :${pkey} `);
3094
+ this._param[pkey] = value;
3095
+ if (name) {
3096
+ paramKeys[key] = pkey;
3097
+ }
3098
+ }
3099
+ if (name) {
3100
+ this._paramKeys[name] = paramKeys;
3101
+ }
2648
3102
  }
2649
- }
2650
- if (name) {
2651
- this._paramKeys[name] = paramKeys;
2652
3103
  }
2653
3104
  }
2654
3105
  return this;
@@ -2678,14 +3129,14 @@ class StreamCondition {
2678
3129
  notRightLike(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', not: 'NOT', force }); }
2679
3130
  PreciseLike(key, value, { name, force } = {}) { return this._like(key, value, { name, force }); }
2680
3131
  notPreciseLike(key, value, { name, force } = {}) { return this._like(key, value, { name, not: 'NOT', force }); }
2681
- glob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', right: '%', force, op: 'glob' }); }
2682
- notGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', right: '%', not: 'NOT', force, op: 'glob' }); }
2683
- leftGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', force, op: 'glob' }); }
2684
- notLeftGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', not: 'NOT', force, op: 'glob' }); }
2685
- rightGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', force, op: 'glob' }); }
2686
- notRightGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', not: 'NOT', force, op: 'glob' }); }
2687
- PreciseGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, force, op: 'glob' }); }
2688
- notPreciseGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, not: 'NOT', force, op: 'glob' }); }
3132
+ glob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', right: '%', force, op: 'GLOB' }); }
3133
+ notGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', right: '%', not: 'NOT', force, op: 'GLOB' }); }
3134
+ leftGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', force, op: 'GLOB' }); }
3135
+ notLeftGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', not: 'NOT', force, op: 'GLOB' }); }
3136
+ rightGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', force, op: 'GLOB' }); }
3137
+ notRightGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', not: 'NOT', force, op: 'GLOB' }); }
3138
+ PreciseGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, force, op: 'GLOB' }); }
3139
+ notPreciseGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, not: 'NOT', force, op: 'GLOB' }); }
2689
3140
  in(key, value, { name, force } = {}) { return this._in(key, value, { name, force }); }
2690
3141
  notIn(key, value, { name, force } = {}) { return this._in(key, value, { name, not: 'NOT', force }); }
2691
3142
  isNULL(key) { return this._null(key); }
@@ -2710,21 +3161,154 @@ class StreamCondition {
2710
3161
  notMatchQuery(value, keys, { name } = {}) { return this._match(value, keys, { name, not: 'NOT', append: 'WITH QUERY EXPANSION' }); }
2711
3162
  includes(key, value, { name } = {}) { return this._includes(key, value, { name }); }
2712
3163
  notIncludes(key, value, { name } = {}) { return this._includes(key, value, { name, not: 'NOT' }); }
2713
- and(fn) { const stream = new StreamCondition(); const ret = fn(stream); if (ret !== false) {
2714
- this._andQuerys.push(stream);
2715
- } return this; }
2716
- or(fn) { const stream = new StreamCondition(); const ret = fn(stream); if (ret !== false) {
2717
- this._orQuerys.push(stream);
2718
- } return this; }
2719
- where() {
3164
+ and(fn) {
3165
+ if (fn instanceof StreamQuery) {
3166
+ this._andQuerys.push(fn);
3167
+ }
3168
+ else {
3169
+ const stream = new StreamQuery(this._table, this._service, this[_fields], this[_columns]);
3170
+ const ret = fn(stream);
3171
+ if (ret !== false) {
3172
+ this._andQuerys.push(stream);
3173
+ }
3174
+ }
3175
+ return this;
3176
+ }
3177
+ or(fn) {
3178
+ if (fn instanceof StreamQuery) {
3179
+ this._andQuerys.push(fn);
3180
+ }
3181
+ else {
3182
+ const stream = new StreamQuery(this._table, this._service, this[_fields], this[_columns]);
3183
+ const ret = fn(stream);
3184
+ if (ret !== false) {
3185
+ this._orQuerys.push(stream);
3186
+ }
3187
+ }
3188
+ return this;
3189
+ }
3190
+ groupBy(...keys) { this._groups.push(...keys.map(key => `${this[_fields][String(key)]?.C2()}`)); return this; }
3191
+ groupBy2(...keys) { this._groups.push(...keys); return this; }
3192
+ asc(...keys) { this._orders.push(...keys.map(key => `${this[_fields][String(key)]?.C2()} ASC`)); return this; }
3193
+ asc2(...keys) { this._orders.push(...keys.map(key => `${key} ASC`)); return this; }
3194
+ desc(...keys) { this._orders.push(...keys.map(key => `${this[_fields][String(key)]?.C2()} DESC`)); return this; }
3195
+ desc2(...keys) { this._orders.push(...keys.map(key => `${key} ASC`)); return this; }
3196
+ limit(startRow, pageSize) { this._startRow = startRow; this._pageSize = pageSize; return this; }
3197
+ page(pageNumber, pageSize) { this._startRow = ((pageNumber || 1) - 1) * pageSize; this._pageSize = pageSize; return this; }
3198
+ table(_table) { this._table = _table; return this; }
3199
+ distinct(on = true) { this._distinct = on; return this; }
3200
+ countDistinct(key, countName) { this._columns.push(`COUNT(DISTINCT ${this[_fields][String(key)]?.C2()}) ${countName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
3201
+ count(countName) { this._columns.push(`COUNT(1) ${countName ?? 'ct'}`); return this; }
3202
+ sum(key, legName, distinct) { this._columns.push(`SUM(${distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}) ${legName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
3203
+ avg(key, legName, distinct) { this._columns.push(`AVG(${distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}) ${legName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
3204
+ max(key, legName, distinct) { this._columns.push(`MAX(${distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}) ${legName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
3205
+ min(key, legName, distinct) { this._columns.push(`MIN(${distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}) ${legName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
3206
+ groupConcat(key, param) {
3207
+ this._columns.push(`GROUP_CONCAT(
3208
+ ${param && param.distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}
3209
+ ${param && param.asc && param.asc.length > 0 ? `ORDER BY ${param.asc.map(i => `${this[_fields][String(i)]?.C2()} ASC`)} ` : ''}
3210
+ ${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`)} ` : ''}
3211
+ SEPARATOR '${param && param.separator || ','}'
3212
+ ) ${param && param.groupName || `${this[_fields][String(key)]?.C2()}`}`);
3213
+ return this;
3214
+ }
3215
+ select(...key) { this._columns.push(...(key.map(k => this[_fields][String(k)].C3()))); return this; }
3216
+ select2(sql, param) { this._columns.push(`${sql}`); Object.assign(this._param, param); return this; }
3217
+ update(key, value) { this._updates ?? (this._updates = {}); this._updates[key] = value; return this; }
3218
+ update2(sql, param) { this._updateColumns.push(sql); Object.assign(this._param, param); return this; }
3219
+ updateT(t) { this._updates ?? (this._updates = {}); Object.assign(this._updates, t); return this; }
3220
+ replace(key, valueToFind, valueToReplace) {
3221
+ const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
3222
+ this._updateColumns.push(` ${this[_fields][String(key)]?.C2()} = REPLACE(${this[_fields][String(key)]?.C2()}, :${pkey1}, :${pkey2}) `);
3223
+ this._param[pkey1] = valueToFind;
3224
+ this._param[pkey2] = valueToReplace;
3225
+ return this;
3226
+ }
3227
+ excuteSelect(option) {
3228
+ option ?? (option = {});
3229
+ option.sync ?? (option.sync = SyncMode.Async);
3230
+ option.selectResult ?? (option.selectResult = SelectResult.Many_Row_Many_Column);
3231
+ const { where, params } = this._where();
3232
+ let sql = `
3233
+ SELECT
3234
+ ${this._distinct ? 'DISTINCT' : ''} ${this._columns && this._columns.length > 0 ? this._columns.join(',') : this[_columns].map(key => this[_fields][String(key)]?.C3()).join(',')}
3235
+ FROM ${this._table}
3236
+ ${where ? ' WHERE ' : ''}
3237
+ ${where}
3238
+ `;
3239
+ if (this._startRow && this._pageSize) {
3240
+ sql += `LIMIT ${this._startRow}, ${this._pageSize}`;
3241
+ }
3242
+ else if (this._startRow) {
3243
+ sql += `LIMIT ${this._startRow}`;
3244
+ }
3245
+ if (option.sync === SyncMode.Async) {
3246
+ switch (option.selectResult) {
3247
+ case SelectResult.Many_Row_Many_Column: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3248
+ case SelectResult.Many_Row_One_Column: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3249
+ case SelectResult.One_Row_Many_Column_Assert: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3250
+ case SelectResult.One_Row_One_Column_Assert: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3251
+ case SelectResult.One_Row_Many_Column_NotSure: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3252
+ case SelectResult.One_Row_One_Column_NotSure: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3253
+ }
3254
+ }
3255
+ else {
3256
+ switch (option.selectResult) {
3257
+ case SelectResult.Many_Row_Many_Column: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3258
+ case SelectResult.Many_Row_One_Column: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3259
+ case SelectResult.One_Row_Many_Column_Assert: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3260
+ case SelectResult.One_Row_One_Column_Assert: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3261
+ case SelectResult.One_Row_Many_Column_NotSure: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3262
+ case SelectResult.One_Row_One_Column_NotSure: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3263
+ }
3264
+ }
3265
+ }
3266
+ excuteUpdate(option) {
3267
+ option ?? (option = {});
3268
+ option.sync ?? (option.sync = SyncMode.Async);
3269
+ const { where, params } = this._where();
3270
+ const sets = new Array(...this._updateColumns);
3271
+ if (this._updates) {
3272
+ for (const [K, V] of Object.entries(this._updates)) {
3273
+ const pkey = `p${this._prefix}${this._index++}`;
3274
+ sets.push(` ${K} = :${pkey} `);
3275
+ params[pkey] = V;
3276
+ }
3277
+ }
3278
+ if (sets.length > 0) {
3279
+ const sql = `UPDATE ${this._table} SET ${sets.join(',')} ${where}`;
3280
+ if (option.sync === SyncMode.Async) {
3281
+ return this._service.excute({ sync: SyncMode.Async, sql, params });
3282
+ }
3283
+ else {
3284
+ return this._service.excute({ sync: SyncMode.Sync, sql, params });
3285
+ }
3286
+ }
3287
+ else {
3288
+ return 0;
3289
+ }
3290
+ }
3291
+ excuteDelete(option) {
3292
+ option ?? (option = {});
3293
+ option.sync ?? (option.sync = SyncMode.Async);
3294
+ const { where, params } = this._where();
3295
+ const sql = `DELETE FROM ${this._table} ${where}`;
3296
+ if (option.sync === SyncMode.Async) {
3297
+ return this._service.excute({ sync: SyncMode.Async, sql, params });
3298
+ }
3299
+ else {
3300
+ return this._service.excute({ sync: SyncMode.Sync, sql, params });
3301
+ }
3302
+ }
3303
+ _where() {
2720
3304
  const wheres = new Array();
2721
3305
  const sql = this._wheres.join(' ');
2722
3306
  if (sql) {
2723
- wheres.push(`(${sql})`);
3307
+ wheres.push(`(${sql.replace(/^and|^or/i, '')})`);
2724
3308
  }
2725
3309
  if (this._orQuerys.length > 0) {
2726
3310
  for (const query of this._orQuerys) {
2727
- const { where, params } = query.where();
3311
+ const { where, params } = query._where();
2728
3312
  if (where) {
2729
3313
  wheres.push(` OR (${where}) `);
2730
3314
  }
@@ -2733,7 +3317,7 @@ class StreamCondition {
2733
3317
  }
2734
3318
  if (this._andQuerys.length > 0) {
2735
3319
  for (const query of this._andQuerys) {
2736
- const { where, params } = query.where();
3320
+ const { where, params } = query._where();
2737
3321
  if (where) {
2738
3322
  wheres.push(` AND (${where}) `);
2739
3323
  }
@@ -2748,7 +3332,7 @@ class StreamCondition {
2748
3332
  }
2749
3333
  else {
2750
3334
  const pkey = `p${this._prefix}${this._index++}`;
2751
- this._wheres.push(`AND ${String(key)} ${not} ${op} :${pkey} `);
3335
+ this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} ${not} ${op} :${pkey} `);
2752
3336
  this._param[pkey] = value;
2753
3337
  if (name) {
2754
3338
  this._paramKeys[name] = pkey;
@@ -2757,11 +3341,11 @@ class StreamCondition {
2757
3341
  return this;
2758
3342
  }
2759
3343
  _null(key, not = '') {
2760
- this._wheres.push(`AND ${String(key)} is ${not} null`);
3344
+ this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} IS ${not} NULL`);
2761
3345
  return this;
2762
3346
  }
2763
3347
  _key(key1, key2, op, not = '') {
2764
- this._wheres.push(`AND ${String(key1)} ${not} ${op} ${String(key2)} `);
3348
+ this._wheres.push(`AND ${this[_fields][String(key1)]?.C2()} ${not} ${op} ${this[_fields][String(key2)]?.C2()} `);
2765
3349
  return this;
2766
3350
  }
2767
3351
  _between(key, value1, value2, { not = '', name = '' } = {}) {
@@ -2771,7 +3355,7 @@ class StreamCondition {
2771
3355
  }
2772
3356
  else {
2773
3357
  const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
2774
- this._wheres.push(`AND ${String(key)} ${not} BETWEEN :${pkey1} AND :${pkey2}`);
3358
+ this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} ${not} BETWEEN :${pkey1} AND :${pkey2}`);
2775
3359
  this._param[pkey1] = value1;
2776
3360
  this._param[pkey2] = value2;
2777
3361
  if (name) {
@@ -2787,7 +3371,7 @@ class StreamCondition {
2787
3371
  }
2788
3372
  else {
2789
3373
  const pkey = `p${this._prefix}${this._index++}`;
2790
- this._wheres.push(`AND ${String(key)} ${not} IN (:${pkey}) `);
3374
+ this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} ${not} IN (:${pkey}) `);
2791
3375
  this._param[pkey] = value;
2792
3376
  if (name) {
2793
3377
  this._paramKeys[name] = pkey;
@@ -2805,7 +3389,7 @@ class StreamCondition {
2805
3389
  }
2806
3390
  else {
2807
3391
  const pkey = `p${this._prefix}${this._index++}`;
2808
- this._wheres.push(`AND (${String(key1)} << 8) + ${String(key2)} ${not} ${op} :${pkey} `);
3392
+ this._wheres.push(`AND (${this[_fields][String(key1)]?.C2()} << 8) + ${this[_fields][String(key2)]?.C2()} ${not} ${op} :${pkey} `);
2809
3393
  this._param[pkey] = value;
2810
3394
  if (name) {
2811
3395
  this._paramKeys[name] = pkey;
@@ -2819,7 +3403,7 @@ class StreamCondition {
2819
3403
  }
2820
3404
  else {
2821
3405
  const pkey = `p${this._prefix}${this._index++}`;
2822
- this._wheres.push(`AND MATCH(${keys.join(',')}) AGAINST (:${pkey} ${append ?? ''})`);
3406
+ this._wheres.push(`AND MATCH(${keys.map(key => this[_fields][String(key)]?.C2()).join(',')}) AGAINST (:${pkey} ${append ?? ''})`);
2823
3407
  this._param[pkey] = value;
2824
3408
  if (name) {
2825
3409
  this._paramKeys[name] = pkey;
@@ -2833,7 +3417,7 @@ class StreamCondition {
2833
3417
  }
2834
3418
  else {
2835
3419
  const pkey = `p${this._prefix}${this._index++}`;
2836
- this._wheres.push(`AND NOT POW(2, ${String(key)}) & :${pkey}`);
3420
+ this._wheres.push(`AND NOT POW(2, ${this[_fields][String(key)]?.C2()}) & :${pkey}`);
2837
3421
  this._param[pkey] = value;
2838
3422
  if (name) {
2839
3423
  this._paramKeys[name] = pkey;
@@ -2848,7 +3432,7 @@ class StreamCondition {
2848
3432
  }
2849
3433
  else {
2850
3434
  const pkey = `p${this._prefix}${this._index++}`;
2851
- this._wheres.push(`AND ${String(key)} ${not} ${op} CONCAT('${left}', :${pkey}, '${right}') `);
3435
+ this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} ${not} ${op} CONCAT('${left}', :${pkey}, '${right}') `);
2852
3436
  this._param[pkey] = value;
2853
3437
  if (name) {
2854
3438
  this._paramKeys[name] = pkey;
@@ -2866,7 +3450,7 @@ class StreamCondition {
2866
3450
  }
2867
3451
  else {
2868
3452
  const pkey = `p${this._prefix}${this._index++}`;
2869
- this._wheres.push(`AND LOCATE(${String(key)}, :${pkey}) ${not ? '=' : ''} 0`);
3453
+ this._wheres.push(`AND LOCATE(${this[_fields][String(key)]?.C2()}, :${pkey}) ${not ? '=' : ''} 0`);
2870
3454
  this._param[pkey] = value;
2871
3455
  if (name) {
2872
3456
  this._paramKeys[name] = pkey;
@@ -2880,576 +3464,490 @@ __decorate([
2880
3464
  __metadata("design:type", Function),
2881
3465
  __metadata("design:paramtypes", [Boolean]),
2882
3466
  __metadata("design:returntype", void 0)
2883
- ], StreamCondition.prototype, "if", null);
3467
+ ], StreamQuery.prototype, "if", null);
2884
3468
  __decorate([
2885
3469
  IF_PROCEED(),
2886
3470
  __metadata("design:type", Function),
2887
3471
  __metadata("design:paramtypes", [Object, Object, Object]),
2888
3472
  __metadata("design:returntype", void 0)
2889
- ], StreamCondition.prototype, "eq", null);
3473
+ ], StreamQuery.prototype, "eq", null);
2890
3474
  __decorate([
2891
3475
  IF_PROCEED(),
2892
3476
  __metadata("design:type", Function),
2893
3477
  __metadata("design:paramtypes", [Object, Object]),
2894
3478
  __metadata("design:returntype", void 0)
2895
- ], StreamCondition.prototype, "eqT", null);
3479
+ ], StreamQuery.prototype, "eqT", null);
2896
3480
  __decorate([
2897
3481
  IF_PROCEED(),
2898
3482
  __metadata("design:type", Function),
2899
3483
  __metadata("design:paramtypes", [Object, Object, Object]),
2900
3484
  __metadata("design:returntype", void 0)
2901
- ], StreamCondition.prototype, "notEq", null);
3485
+ ], StreamQuery.prototype, "notEq", null);
2902
3486
  __decorate([
2903
3487
  IF_PROCEED(),
2904
3488
  __metadata("design:type", Function),
2905
3489
  __metadata("design:paramtypes", [Object, Object]),
2906
3490
  __metadata("design:returntype", void 0)
2907
- ], StreamCondition.prototype, "eqWith", null);
3491
+ ], StreamQuery.prototype, "eqWith", null);
2908
3492
  __decorate([
2909
3493
  IF_PROCEED(),
2910
3494
  __metadata("design:type", Function),
2911
3495
  __metadata("design:paramtypes", [Object, Object]),
2912
3496
  __metadata("design:returntype", void 0)
2913
- ], StreamCondition.prototype, "notEqWith", null);
3497
+ ], StreamQuery.prototype, "notEqWith", null);
2914
3498
  __decorate([
2915
3499
  IF_PROCEED(),
2916
3500
  __metadata("design:type", Function),
2917
3501
  __metadata("design:paramtypes", [Object, String, Object]),
2918
3502
  __metadata("design:returntype", void 0)
2919
- ], StreamCondition.prototype, "regexp", null);
3503
+ ], StreamQuery.prototype, "regexp", null);
2920
3504
  __decorate([
2921
3505
  IF_PROCEED(),
2922
3506
  __metadata("design:type", Function),
2923
3507
  __metadata("design:paramtypes", [Object, String, Object]),
2924
3508
  __metadata("design:returntype", void 0)
2925
- ], StreamCondition.prototype, "notRegexp", null);
3509
+ ], StreamQuery.prototype, "notRegexp", null);
2926
3510
  __decorate([
2927
3511
  IF_PROCEED(),
2928
3512
  __metadata("design:type", Function),
2929
3513
  __metadata("design:paramtypes", [Object, Object, Number, Object]),
2930
3514
  __metadata("design:returntype", void 0)
2931
- ], StreamCondition.prototype, "shiftEq", null);
3515
+ ], StreamQuery.prototype, "shiftEq", null);
2932
3516
  __decorate([
2933
3517
  IF_PROCEED(),
2934
3518
  __metadata("design:type", Function),
2935
3519
  __metadata("design:paramtypes", [Object, Object, Number, Object]),
2936
3520
  __metadata("design:returntype", void 0)
2937
- ], StreamCondition.prototype, "shiftNotEq", null);
3521
+ ], StreamQuery.prototype, "shiftNotEq", null);
2938
3522
  __decorate([
2939
3523
  IF_PROCEED(),
2940
3524
  __metadata("design:type", Function),
2941
3525
  __metadata("design:paramtypes", [Object, Object, Object]),
2942
3526
  __metadata("design:returntype", void 0)
2943
- ], StreamCondition.prototype, "grate", null);
3527
+ ], StreamQuery.prototype, "grate", null);
2944
3528
  __decorate([
2945
3529
  IF_PROCEED(),
2946
3530
  __metadata("design:type", Function),
2947
3531
  __metadata("design:paramtypes", [Object, Object, Object]),
2948
3532
  __metadata("design:returntype", void 0)
2949
- ], StreamCondition.prototype, "grateEq", null);
3533
+ ], StreamQuery.prototype, "grateEq", null);
2950
3534
  __decorate([
2951
3535
  IF_PROCEED(),
2952
3536
  __metadata("design:type", Function),
2953
3537
  __metadata("design:paramtypes", [Object, Object]),
2954
3538
  __metadata("design:returntype", void 0)
2955
- ], StreamCondition.prototype, "grateWith", null);
3539
+ ], StreamQuery.prototype, "grateWith", null);
2956
3540
  __decorate([
2957
3541
  IF_PROCEED(),
2958
3542
  __metadata("design:type", Function),
2959
3543
  __metadata("design:paramtypes", [Object, Object]),
2960
3544
  __metadata("design:returntype", void 0)
2961
- ], StreamCondition.prototype, "grateEqWith", null);
3545
+ ], StreamQuery.prototype, "grateEqWith", null);
2962
3546
  __decorate([
2963
3547
  IF_PROCEED(),
2964
3548
  __metadata("design:type", Function),
2965
3549
  __metadata("design:paramtypes", [Object, Object, Object]),
2966
3550
  __metadata("design:returntype", void 0)
2967
- ], StreamCondition.prototype, "less", null);
3551
+ ], StreamQuery.prototype, "less", null);
2968
3552
  __decorate([
2969
3553
  IF_PROCEED(),
2970
3554
  __metadata("design:type", Function),
2971
3555
  __metadata("design:paramtypes", [Object, Object, Object]),
2972
3556
  __metadata("design:returntype", void 0)
2973
- ], StreamCondition.prototype, "lessEq", null);
3557
+ ], StreamQuery.prototype, "lessEq", null);
2974
3558
  __decorate([
2975
3559
  IF_PROCEED(),
2976
3560
  __metadata("design:type", Function),
2977
3561
  __metadata("design:paramtypes", [Object, Object]),
2978
3562
  __metadata("design:returntype", void 0)
2979
- ], StreamCondition.prototype, "lessWith", null);
3563
+ ], StreamQuery.prototype, "lessWith", null);
2980
3564
  __decorate([
2981
3565
  IF_PROCEED(),
2982
3566
  __metadata("design:type", Function),
2983
3567
  __metadata("design:paramtypes", [Object, Object]),
2984
3568
  __metadata("design:returntype", void 0)
2985
- ], StreamCondition.prototype, "lessEqWith", null);
3569
+ ], StreamQuery.prototype, "lessEqWith", null);
2986
3570
  __decorate([
2987
3571
  IF_PROCEED(),
2988
3572
  __metadata("design:type", Function),
2989
3573
  __metadata("design:paramtypes", [Object, Object, Object]),
2990
3574
  __metadata("design:returntype", void 0)
2991
- ], StreamCondition.prototype, "like", null);
3575
+ ], StreamQuery.prototype, "like", null);
2992
3576
  __decorate([
2993
3577
  IF_PROCEED(),
2994
3578
  __metadata("design:type", Function),
2995
3579
  __metadata("design:paramtypes", [Object, Object, Object]),
2996
3580
  __metadata("design:returntype", void 0)
2997
- ], StreamCondition.prototype, "notLike", null);
3581
+ ], StreamQuery.prototype, "notLike", null);
2998
3582
  __decorate([
2999
3583
  IF_PROCEED(),
3000
3584
  __metadata("design:type", Function),
3001
3585
  __metadata("design:paramtypes", [Object, Object, Object]),
3002
3586
  __metadata("design:returntype", void 0)
3003
- ], StreamCondition.prototype, "leftLike", null);
3587
+ ], StreamQuery.prototype, "leftLike", null);
3004
3588
  __decorate([
3005
3589
  IF_PROCEED(),
3006
3590
  __metadata("design:type", Function),
3007
3591
  __metadata("design:paramtypes", [Object, Object, Object]),
3008
3592
  __metadata("design:returntype", void 0)
3009
- ], StreamCondition.prototype, "notLeftLike", null);
3593
+ ], StreamQuery.prototype, "notLeftLike", null);
3010
3594
  __decorate([
3011
3595
  IF_PROCEED(),
3012
3596
  __metadata("design:type", Function),
3013
3597
  __metadata("design:paramtypes", [Object, Object, Object]),
3014
3598
  __metadata("design:returntype", void 0)
3015
- ], StreamCondition.prototype, "rightLike", null);
3599
+ ], StreamQuery.prototype, "rightLike", null);
3016
3600
  __decorate([
3017
3601
  IF_PROCEED(),
3018
3602
  __metadata("design:type", Function),
3019
3603
  __metadata("design:paramtypes", [Object, Object, Object]),
3020
3604
  __metadata("design:returntype", void 0)
3021
- ], StreamCondition.prototype, "notRightLike", null);
3605
+ ], StreamQuery.prototype, "notRightLike", null);
3022
3606
  __decorate([
3023
3607
  IF_PROCEED(),
3024
3608
  __metadata("design:type", Function),
3025
3609
  __metadata("design:paramtypes", [Object, Object, Object]),
3026
3610
  __metadata("design:returntype", void 0)
3027
- ], StreamCondition.prototype, "PreciseLike", null);
3611
+ ], StreamQuery.prototype, "PreciseLike", null);
3028
3612
  __decorate([
3029
3613
  IF_PROCEED(),
3030
3614
  __metadata("design:type", Function),
3031
3615
  __metadata("design:paramtypes", [Object, Object, Object]),
3032
3616
  __metadata("design:returntype", void 0)
3033
- ], StreamCondition.prototype, "notPreciseLike", null);
3617
+ ], StreamQuery.prototype, "notPreciseLike", null);
3034
3618
  __decorate([
3035
3619
  IF_PROCEED(),
3036
3620
  __metadata("design:type", Function),
3037
3621
  __metadata("design:paramtypes", [Object, Object, Object]),
3038
3622
  __metadata("design:returntype", void 0)
3039
- ], StreamCondition.prototype, "glob", null);
3623
+ ], StreamQuery.prototype, "glob", null);
3040
3624
  __decorate([
3041
3625
  IF_PROCEED(),
3042
3626
  __metadata("design:type", Function),
3043
3627
  __metadata("design:paramtypes", [Object, Object, Object]),
3044
3628
  __metadata("design:returntype", void 0)
3045
- ], StreamCondition.prototype, "notGlob", null);
3629
+ ], StreamQuery.prototype, "notGlob", null);
3046
3630
  __decorate([
3047
3631
  IF_PROCEED(),
3048
3632
  __metadata("design:type", Function),
3049
3633
  __metadata("design:paramtypes", [Object, Object, Object]),
3050
3634
  __metadata("design:returntype", void 0)
3051
- ], StreamCondition.prototype, "leftGlob", null);
3635
+ ], StreamQuery.prototype, "leftGlob", null);
3052
3636
  __decorate([
3053
3637
  IF_PROCEED(),
3054
3638
  __metadata("design:type", Function),
3055
3639
  __metadata("design:paramtypes", [Object, Object, Object]),
3056
3640
  __metadata("design:returntype", void 0)
3057
- ], StreamCondition.prototype, "notLeftGlob", null);
3641
+ ], StreamQuery.prototype, "notLeftGlob", null);
3058
3642
  __decorate([
3059
3643
  IF_PROCEED(),
3060
3644
  __metadata("design:type", Function),
3061
3645
  __metadata("design:paramtypes", [Object, Object, Object]),
3062
3646
  __metadata("design:returntype", void 0)
3063
- ], StreamCondition.prototype, "rightGlob", null);
3647
+ ], StreamQuery.prototype, "rightGlob", null);
3064
3648
  __decorate([
3065
3649
  IF_PROCEED(),
3066
3650
  __metadata("design:type", Function),
3067
3651
  __metadata("design:paramtypes", [Object, Object, Object]),
3068
3652
  __metadata("design:returntype", void 0)
3069
- ], StreamCondition.prototype, "notRightGlob", null);
3653
+ ], StreamQuery.prototype, "notRightGlob", null);
3070
3654
  __decorate([
3071
3655
  IF_PROCEED(),
3072
3656
  __metadata("design:type", Function),
3073
3657
  __metadata("design:paramtypes", [Object, Object, Object]),
3074
3658
  __metadata("design:returntype", void 0)
3075
- ], StreamCondition.prototype, "PreciseGlob", null);
3659
+ ], StreamQuery.prototype, "PreciseGlob", null);
3076
3660
  __decorate([
3077
3661
  IF_PROCEED(),
3078
3662
  __metadata("design:type", Function),
3079
3663
  __metadata("design:paramtypes", [Object, Object, Object]),
3080
3664
  __metadata("design:returntype", void 0)
3081
- ], StreamCondition.prototype, "notPreciseGlob", null);
3665
+ ], StreamQuery.prototype, "notPreciseGlob", null);
3082
3666
  __decorate([
3083
3667
  IF_PROCEED(),
3084
3668
  __metadata("design:type", Function),
3085
3669
  __metadata("design:paramtypes", [Object, Array, Object]),
3086
3670
  __metadata("design:returntype", void 0)
3087
- ], StreamCondition.prototype, "in", null);
3671
+ ], StreamQuery.prototype, "in", null);
3088
3672
  __decorate([
3089
3673
  IF_PROCEED(),
3090
3674
  __metadata("design:type", Function),
3091
3675
  __metadata("design:paramtypes", [Object, Array, Object]),
3092
3676
  __metadata("design:returntype", void 0)
3093
- ], StreamCondition.prototype, "notIn", null);
3677
+ ], StreamQuery.prototype, "notIn", null);
3094
3678
  __decorate([
3095
3679
  IF_PROCEED(),
3096
3680
  __metadata("design:type", Function),
3097
3681
  __metadata("design:paramtypes", [Object]),
3098
3682
  __metadata("design:returntype", void 0)
3099
- ], StreamCondition.prototype, "isNULL", null);
3683
+ ], StreamQuery.prototype, "isNULL", null);
3100
3684
  __decorate([
3101
3685
  IF_PROCEED(),
3102
3686
  __metadata("design:type", Function),
3103
3687
  __metadata("design:paramtypes", [Object]),
3104
3688
  __metadata("design:returntype", void 0)
3105
- ], StreamCondition.prototype, "isNotNULL", null);
3689
+ ], StreamQuery.prototype, "isNotNULL", null);
3106
3690
  __decorate([
3107
3691
  IF_PROCEED(),
3108
3692
  __metadata("design:type", Function),
3109
3693
  __metadata("design:paramtypes", [Object, Object, Object, Object]),
3110
3694
  __metadata("design:returntype", void 0)
3111
- ], StreamCondition.prototype, "between", null);
3695
+ ], StreamQuery.prototype, "between", null);
3112
3696
  __decorate([
3113
3697
  IF_PROCEED(),
3114
3698
  __metadata("design:type", Function),
3115
3699
  __metadata("design:paramtypes", [Object, Object, Object, Object]),
3116
3700
  __metadata("design:returntype", void 0)
3117
- ], StreamCondition.prototype, "notBetween", null);
3701
+ ], StreamQuery.prototype, "notBetween", null);
3118
3702
  __decorate([
3119
3703
  IF_PROCEED(),
3120
3704
  __metadata("design:type", Function),
3121
3705
  __metadata("design:paramtypes", [Object, Number, Object]),
3122
3706
  __metadata("design:returntype", void 0)
3123
- ], StreamCondition.prototype, "pow", null);
3707
+ ], StreamQuery.prototype, "pow", null);
3124
3708
  __decorate([
3125
3709
  IF_PROCEED(),
3126
3710
  __metadata("design:type", Function),
3127
3711
  __metadata("design:paramtypes", [Object, Number, Object]),
3128
3712
  __metadata("design:returntype", void 0)
3129
- ], StreamCondition.prototype, "notPow", null);
3713
+ ], StreamQuery.prototype, "notPow", null);
3130
3714
  __decorate([
3131
3715
  IF_PROCEED(),
3132
3716
  __metadata("design:type", Function),
3133
3717
  __metadata("design:paramtypes", [Object, Array, Object]),
3134
3718
  __metadata("design:returntype", void 0)
3135
- ], StreamCondition.prototype, "powWith", null);
3719
+ ], StreamQuery.prototype, "powWith", null);
3136
3720
  __decorate([
3137
3721
  IF_PROCEED(),
3138
3722
  __metadata("design:type", Function),
3139
3723
  __metadata("design:paramtypes", [Object, Array, Object]),
3140
3724
  __metadata("design:returntype", void 0)
3141
- ], StreamCondition.prototype, "notPowWith", null);
3725
+ ], StreamQuery.prototype, "notPowWith", null);
3142
3726
  __decorate([
3143
3727
  IF_PROCEED(),
3144
3728
  __metadata("design:type", Function),
3145
3729
  __metadata("design:paramtypes", [String, Array, Object]),
3146
3730
  __metadata("design:returntype", void 0)
3147
- ], StreamCondition.prototype, "match", null);
3731
+ ], StreamQuery.prototype, "match", null);
3148
3732
  __decorate([
3149
3733
  IF_PROCEED(),
3150
3734
  __metadata("design:type", Function),
3151
3735
  __metadata("design:paramtypes", [String, Array, Object]),
3152
3736
  __metadata("design:returntype", void 0)
3153
- ], StreamCondition.prototype, "notMatch", null);
3737
+ ], StreamQuery.prototype, "notMatch", null);
3154
3738
  __decorate([
3155
3739
  IF_PROCEED(),
3156
3740
  __metadata("design:type", Function),
3157
3741
  __metadata("design:paramtypes", [String, Array, Object]),
3158
3742
  __metadata("design:returntype", void 0)
3159
- ], StreamCondition.prototype, "matchBoolean", null);
3743
+ ], StreamQuery.prototype, "matchBoolean", null);
3160
3744
  __decorate([
3161
3745
  IF_PROCEED(),
3162
3746
  __metadata("design:type", Function),
3163
3747
  __metadata("design:paramtypes", [String, Array, Object]),
3164
3748
  __metadata("design:returntype", void 0)
3165
- ], StreamCondition.prototype, "notMatchBoolean", null);
3749
+ ], StreamQuery.prototype, "notMatchBoolean", null);
3166
3750
  __decorate([
3167
3751
  IF_PROCEED(),
3168
3752
  __metadata("design:type", Function),
3169
3753
  __metadata("design:paramtypes", [String, Array, Object]),
3170
3754
  __metadata("design:returntype", void 0)
3171
- ], StreamCondition.prototype, "matchQuery", null);
3755
+ ], StreamQuery.prototype, "matchQuery", null);
3172
3756
  __decorate([
3173
3757
  IF_PROCEED(),
3174
3758
  __metadata("design:type", Function),
3175
3759
  __metadata("design:paramtypes", [String, Array, Object]),
3176
3760
  __metadata("design:returntype", void 0)
3177
- ], StreamCondition.prototype, "notMatchQuery", null);
3761
+ ], StreamQuery.prototype, "notMatchQuery", null);
3178
3762
  __decorate([
3179
3763
  IF_PROCEED(),
3180
3764
  __metadata("design:type", Function),
3181
3765
  __metadata("design:paramtypes", [Object, Object, Object]),
3182
3766
  __metadata("design:returntype", void 0)
3183
- ], StreamCondition.prototype, "includes", null);
3767
+ ], StreamQuery.prototype, "includes", null);
3184
3768
  __decorate([
3185
3769
  IF_PROCEED(),
3186
3770
  __metadata("design:type", Function),
3187
3771
  __metadata("design:paramtypes", [Object, Object, Object]),
3188
3772
  __metadata("design:returntype", void 0)
3189
- ], StreamCondition.prototype, "notIncludes", null);
3773
+ ], StreamQuery.prototype, "notIncludes", null);
3190
3774
  __decorate([
3191
3775
  IF_PROCEED(),
3192
3776
  __metadata("design:type", Function),
3193
- __metadata("design:paramtypes", [Function]),
3777
+ __metadata("design:paramtypes", [Object]),
3194
3778
  __metadata("design:returntype", void 0)
3195
- ], StreamCondition.prototype, "and", null);
3779
+ ], StreamQuery.prototype, "and", null);
3196
3780
  __decorate([
3197
3781
  IF_PROCEED(),
3198
3782
  __metadata("design:type", Function),
3199
- __metadata("design:paramtypes", [Function]),
3783
+ __metadata("design:paramtypes", [Object]),
3200
3784
  __metadata("design:returntype", void 0)
3201
- ], StreamCondition.prototype, "or", null);
3202
- class StreamBuild extends StreamCondition {
3203
- constructor(table) {
3204
- super();
3205
- this._distinct = false;
3206
- this._columns = [];
3207
- this._updateColumns = [];
3208
- this._groups = [];
3209
- this._orders = [];
3210
- this._startRow = 0;
3211
- this._pageSize = 0;
3212
- this._table = table;
3213
- }
3214
- /** 将当前stream重置 */
3215
- reset() {
3216
- super.reset();
3217
- this._pageSize = 0;
3218
- this._startRow = 0;
3219
- this._orders.length = 0;
3220
- this._groups.length = 0;
3221
- this._columns.length = 0;
3222
- this._updateColumns.length = 0;
3223
- return this;
3224
- }
3225
- groupBy(key) { this._groups.push(key); return this; }
3226
- asc(...keys) { this._orders.push(...keys.map(key => `${String(key)} ASC`)); return this; }
3227
- desc(...keys) { this._orders.push(...keys.map(key => `${String(key)} DESC`)); return this; }
3228
- limit(startRow, pageSize) { this._startRow = startRow; this._pageSize = pageSize; return this; }
3229
- page(pageNumber, pageSize) { this._startRow = ((pageNumber || 1) - 1) * pageSize; this._pageSize = pageSize; return this; }
3230
- table(_table) { this._table = _table; return this; }
3231
- distinct(on = true) { this._distinct = on; return this; }
3232
- count(key, countName, distinct) { this._columns.push(`COUNT(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${countName || `${String(key)}`}`); return this; }
3233
- sum(key, legName, distinct) { this._columns.push(`SUM(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
3234
- avg(key, legName, distinct) { this._columns.push(`AVG(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
3235
- max(key, legName, distinct) { this._columns.push(`MAX(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
3236
- min(key, legName, distinct) { this._columns.push(`MIN(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
3237
- groupConcat(key, param) {
3238
- this._columns.push(`GROUP_CONCAT(
3239
- ${param && param.distinct ? 'DISTINCT' : ''} ${String(key)}
3240
- ${param && param.asc && param.asc.length > 0 ? `ORDER BY ${param.asc.map(i => `${String(i)} ASC`)} ` : ''}
3241
- ${param && param.desc && param.desc.length > 0 ? `${param && param.asc && param.asc.length > 0 ? '' : 'ORDER BY'} ${param.desc.map(i => `${String(i)} DESC`)} ` : ''}
3242
- SEPARATOR '${param && param.separator || ','}'
3243
- ) ${param && param.groupName || `${String(key)}`}`);
3244
- return this;
3245
- }
3246
- selectColumn(...key) { this._columns.push(...(key.map(k => k))); return this; }
3247
- updateColumn(key, value) { this._updates ?? (this._updates = {}); this._updates[key] = value; return this; }
3248
- updateT(t) { this._updates ?? (this._updates = {}); Object.assign(this._updates, t); return this; }
3249
- replace(key, valueToFind, valueToReplace) {
3250
- const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
3251
- this._updateColumns.push(` ${String(key)} = REPLACE(${String(key)}, :${pkey1}, :${pkey2}) `);
3252
- this._param[pkey1] = valueToFind;
3253
- this._param[pkey2] = valueToReplace;
3254
- return this;
3255
- }
3256
- }
3785
+ ], StreamQuery.prototype, "or", null);
3257
3786
  __decorate([
3258
3787
  IF_PROCEED(),
3259
3788
  __metadata("design:type", Function),
3260
3789
  __metadata("design:paramtypes", [Object]),
3261
3790
  __metadata("design:returntype", void 0)
3262
- ], StreamBuild.prototype, "groupBy", null);
3791
+ ], StreamQuery.prototype, "groupBy", null);
3792
+ __decorate([
3793
+ IF_PROCEED(),
3794
+ __metadata("design:type", Function),
3795
+ __metadata("design:paramtypes", [String]),
3796
+ __metadata("design:returntype", void 0)
3797
+ ], StreamQuery.prototype, "groupBy2", null);
3263
3798
  __decorate([
3264
3799
  IF_PROCEED(),
3265
3800
  __metadata("design:type", Function),
3266
3801
  __metadata("design:paramtypes", [Object]),
3267
3802
  __metadata("design:returntype", void 0)
3268
- ], StreamBuild.prototype, "asc", null);
3803
+ ], StreamQuery.prototype, "asc", null);
3804
+ __decorate([
3805
+ IF_PROCEED(),
3806
+ __metadata("design:type", Function),
3807
+ __metadata("design:paramtypes", [String]),
3808
+ __metadata("design:returntype", void 0)
3809
+ ], StreamQuery.prototype, "asc2", null);
3269
3810
  __decorate([
3270
3811
  IF_PROCEED(),
3271
3812
  __metadata("design:type", Function),
3272
3813
  __metadata("design:paramtypes", [Object]),
3273
3814
  __metadata("design:returntype", void 0)
3274
- ], StreamBuild.prototype, "desc", null);
3815
+ ], StreamQuery.prototype, "desc", null);
3816
+ __decorate([
3817
+ IF_PROCEED(),
3818
+ __metadata("design:type", Function),
3819
+ __metadata("design:paramtypes", [String]),
3820
+ __metadata("design:returntype", void 0)
3821
+ ], StreamQuery.prototype, "desc2", null);
3275
3822
  __decorate([
3276
3823
  IF_PROCEED(),
3277
3824
  __metadata("design:type", Function),
3278
3825
  __metadata("design:paramtypes", [Number, Number]),
3279
3826
  __metadata("design:returntype", void 0)
3280
- ], StreamBuild.prototype, "limit", null);
3827
+ ], StreamQuery.prototype, "limit", null);
3281
3828
  __decorate([
3282
3829
  IF_PROCEED(),
3283
3830
  __metadata("design:type", Function),
3284
3831
  __metadata("design:paramtypes", [Number, Number]),
3285
3832
  __metadata("design:returntype", void 0)
3286
- ], StreamBuild.prototype, "page", null);
3833
+ ], StreamQuery.prototype, "page", null);
3287
3834
  __decorate([
3288
3835
  IF_PROCEED(),
3289
3836
  __metadata("design:type", Function),
3290
3837
  __metadata("design:paramtypes", [String]),
3291
3838
  __metadata("design:returntype", void 0)
3292
- ], StreamBuild.prototype, "table", null);
3839
+ ], StreamQuery.prototype, "table", null);
3293
3840
  __decorate([
3294
3841
  IF_PROCEED(),
3295
3842
  __metadata("design:type", Function),
3296
3843
  __metadata("design:paramtypes", [Object]),
3297
3844
  __metadata("design:returntype", void 0)
3298
- ], StreamBuild.prototype, "distinct", null);
3845
+ ], StreamQuery.prototype, "distinct", null);
3299
3846
  __decorate([
3300
3847
  IF_PROCEED(),
3301
3848
  __metadata("design:type", Function),
3302
- __metadata("design:paramtypes", [Object, String, Boolean]),
3849
+ __metadata("design:paramtypes", [Object, String]),
3303
3850
  __metadata("design:returntype", void 0)
3304
- ], StreamBuild.prototype, "count", null);
3851
+ ], StreamQuery.prototype, "countDistinct", null);
3852
+ __decorate([
3853
+ IF_PROCEED(),
3854
+ __metadata("design:type", Function),
3855
+ __metadata("design:paramtypes", [String]),
3856
+ __metadata("design:returntype", void 0)
3857
+ ], StreamQuery.prototype, "count", null);
3305
3858
  __decorate([
3306
3859
  IF_PROCEED(),
3307
3860
  __metadata("design:type", Function),
3308
3861
  __metadata("design:paramtypes", [Object, String, Boolean]),
3309
3862
  __metadata("design:returntype", void 0)
3310
- ], StreamBuild.prototype, "sum", null);
3863
+ ], StreamQuery.prototype, "sum", null);
3311
3864
  __decorate([
3312
3865
  IF_PROCEED(),
3313
3866
  __metadata("design:type", Function),
3314
3867
  __metadata("design:paramtypes", [Object, String, Boolean]),
3315
3868
  __metadata("design:returntype", void 0)
3316
- ], StreamBuild.prototype, "avg", null);
3869
+ ], StreamQuery.prototype, "avg", null);
3317
3870
  __decorate([
3318
3871
  IF_PROCEED(),
3319
3872
  __metadata("design:type", Function),
3320
3873
  __metadata("design:paramtypes", [Object, String, Boolean]),
3321
3874
  __metadata("design:returntype", void 0)
3322
- ], StreamBuild.prototype, "max", null);
3875
+ ], StreamQuery.prototype, "max", null);
3323
3876
  __decorate([
3324
3877
  IF_PROCEED(),
3325
3878
  __metadata("design:type", Function),
3326
3879
  __metadata("design:paramtypes", [Object, String, Boolean]),
3327
3880
  __metadata("design:returntype", void 0)
3328
- ], StreamBuild.prototype, "min", null);
3881
+ ], StreamQuery.prototype, "min", null);
3329
3882
  __decorate([
3330
3883
  IF_PROCEED(),
3331
3884
  __metadata("design:type", Function),
3332
3885
  __metadata("design:paramtypes", [Object, Object]),
3333
3886
  __metadata("design:returntype", Object)
3334
- ], StreamBuild.prototype, "groupConcat", null);
3887
+ ], StreamQuery.prototype, "groupConcat", null);
3335
3888
  __decorate([
3336
3889
  IF_PROCEED(),
3337
3890
  __metadata("design:type", Function),
3338
3891
  __metadata("design:paramtypes", [Object]),
3339
3892
  __metadata("design:returntype", void 0)
3340
- ], StreamBuild.prototype, "selectColumn", null);
3893
+ ], StreamQuery.prototype, "select", null);
3894
+ __decorate([
3895
+ IF_PROCEED(),
3896
+ __metadata("design:type", Function),
3897
+ __metadata("design:paramtypes", [String, Object]),
3898
+ __metadata("design:returntype", void 0)
3899
+ ], StreamQuery.prototype, "select2", null);
3341
3900
  __decorate([
3342
3901
  IF_PROCEED(),
3343
3902
  __metadata("design:type", Function),
3344
3903
  __metadata("design:paramtypes", [Object, Object]),
3345
3904
  __metadata("design:returntype", void 0)
3346
- ], StreamBuild.prototype, "updateColumn", null);
3905
+ ], StreamQuery.prototype, "update", null);
3906
+ __decorate([
3907
+ IF_PROCEED(),
3908
+ __metadata("design:type", Function),
3909
+ __metadata("design:paramtypes", [String, Object]),
3910
+ __metadata("design:returntype", void 0)
3911
+ ], StreamQuery.prototype, "update2", null);
3347
3912
  __decorate([
3348
3913
  IF_PROCEED(),
3349
3914
  __metadata("design:type", Function),
3350
3915
  __metadata("design:paramtypes", [Object]),
3351
3916
  __metadata("design:returntype", void 0)
3352
- ], StreamBuild.prototype, "updateT", null);
3917
+ ], StreamQuery.prototype, "updateT", null);
3353
3918
  __decorate([
3354
3919
  IF_PROCEED(),
3355
3920
  __metadata("design:type", Function),
3356
3921
  __metadata("design:paramtypes", [Object, Object, Object]),
3357
3922
  __metadata("design:returntype", void 0)
3358
- ], StreamBuild.prototype, "replace", null);
3359
- class StreamQuery extends StreamBuild {
3360
- constructor(table, service) {
3361
- super(table);
3362
- this._service = service;
3363
- }
3364
- select(option) {
3365
- option.sync ?? (option.sync = SyncMode.Async);
3366
- const { where, params } = this.where();
3367
- const sql = `
3368
- SELECT
3369
- ${this._columns && this._columns.length > 0 ? this._columns.join(',') : '*'}
3370
- FROM ${this._table}
3371
- ${where ? ' WHERE ' : ''}
3372
- ${where}`;
3373
- if (option.sync === SyncMode.Async) {
3374
- switch (option.selectResult) {
3375
- case SelectResult.Many_Row_Many_Column: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3376
- case SelectResult.Many_Row_One_Column: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3377
- case SelectResult.One_Row_Many_Column_Assert: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3378
- case SelectResult.One_Row_One_Column_Assert: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3379
- case SelectResult.One_Row_Many_Column_NotSure: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3380
- case SelectResult.One_Row_One_Column_NotSure: return this._service.select({ sync: SyncMode.Async, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3381
- }
3382
- }
3383
- else {
3384
- switch (option.selectResult) {
3385
- case SelectResult.Many_Row_Many_Column: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
3386
- case SelectResult.Many_Row_One_Column: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
3387
- case SelectResult.One_Row_Many_Column_Assert: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
3388
- case SelectResult.One_Row_One_Column_Assert: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
3389
- case SelectResult.One_Row_Many_Column_NotSure: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3390
- case SelectResult.One_Row_One_Column_NotSure: return this._service.select({ sync: SyncMode.Sync, selectResult: SelectResult.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
3391
- }
3392
- }
3393
- }
3394
- update(option) {
3395
- option.sync ?? (option.sync = SyncMode.Async);
3396
- const { where, params } = this.where();
3397
- const sets = new Array(...this._updateColumns);
3398
- if (this._updates) {
3399
- for (const [K, V] of Object.entries(this._updates)) {
3400
- const pkey = `p${this._prefix}${this._index++}`;
3401
- sets.push(` ${K} = :${pkey} `);
3402
- params[pkey] = V;
3403
- }
3404
- }
3405
- if (sets.length > 0) {
3406
- const sql = `UPDATE ${this._table} SET ${sets.join(',')} ${where}`;
3407
- if (option.sync === SyncMode.Async) {
3408
- return this._service.excute({ sync: SyncMode.Async, sql, params });
3409
- }
3410
- else {
3411
- return this._service.excute({ sync: SyncMode.Sync, sql, params });
3412
- }
3413
- }
3414
- else {
3415
- return 0;
3416
- }
3417
- }
3418
- delete(option) {
3419
- option.sync ?? (option.sync = SyncMode.Async);
3420
- const { where, params } = this.where();
3421
- const sql = `DELETE FROM ${this._table} ${where}`;
3422
- if (option.sync === SyncMode.Async) {
3423
- return this._service.excute({ sync: SyncMode.Async, sql, params });
3424
- }
3425
- else {
3426
- return this._service.excute({ sync: SyncMode.Sync, sql, params });
3427
- }
3428
- }
3429
- }
3923
+ ], StreamQuery.prototype, "replace", null);
3430
3924
  __decorate([
3431
3925
  IF_EXEC(null),
3432
3926
  __metadata("design:type", Function),
3433
3927
  __metadata("design:paramtypes", [Object]),
3434
3928
  __metadata("design:returntype", Object)
3435
- ], StreamQuery.prototype, "select", null);
3929
+ ], StreamQuery.prototype, "excuteSelect", null);
3436
3930
  __decorate([
3437
3931
  IF_EXEC(0),
3438
3932
  __metadata("design:type", Function),
3439
3933
  __metadata("design:paramtypes", [Object]),
3440
3934
  __metadata("design:returntype", Object)
3441
- ], StreamQuery.prototype, "update", null);
3935
+ ], StreamQuery.prototype, "excuteUpdate", null);
3442
3936
  __decorate([
3443
3937
  IF_EXEC(0),
3444
3938
  __metadata("design:type", Function),
3445
3939
  __metadata("design:paramtypes", [Object]),
3446
3940
  __metadata("design:returntype", Object)
3447
- ], StreamQuery.prototype, "delete", null);
3941
+ ], StreamQuery.prototype, "excuteDelete", null);
3448
3942
  /**
3449
3943
  获取REDIS客户端,
3450
3944
  # [查看库的API](https://github.com/redis/ioredis?tab=readme-ov-file)
3451
3945
  # [REDIS API](http://doc.redisfans.com/)
3452
3946
  REDIS 的API 可以直接用,将方法名转为小写
3947
+ ```
3948
+ // 设置<Redis>来获得代码提示
3949
+ getRedisDB<Redis>('').exists(?)
3950
+ ```
3453
3951
  */
3454
3952
  export function getRedisDB(db) {
3455
3953
  const rd = globalThis[_dao][DBType.Redis][db ?? _primaryDB];
@@ -3648,6 +4146,8 @@ export function MethodCache(config) {
3648
4146
  class MUParser {
3649
4147
  constructor(modelName, file) {
3650
4148
  this.linNumber = 0;
4149
+ this.lastLine = '';
4150
+ this.lastlastLine = '';
3651
4151
  this.status = 0;
3652
4152
  this.lineSeparator = '\n';
3653
4153
  this.modelName = modelName;
@@ -3656,7 +4156,7 @@ class MUParser {
3656
4156
  }
3657
4157
  next() {
3658
4158
  let sqlId = this.readSqlId();
3659
- if (this.status === MUParser.END || !sqlId) {
4159
+ if (this.status === MUParser.END) {
3660
4160
  return null;
3661
4161
  }
3662
4162
  // 去掉可能的尾部空格
@@ -3671,9 +4171,6 @@ class MUParser {
3671
4171
  skipHeader() {
3672
4172
  while (true) {
3673
4173
  const line = this.nextLine();
3674
- if (!line) {
3675
- return;
3676
- }
3677
4174
  if (this.status === MUParser.END) {
3678
4175
  return;
3679
4176
  }
@@ -3700,7 +4197,7 @@ class MUParser {
3700
4197
  let findComment = false;
3701
4198
  while (true) {
3702
4199
  let line = this.nextLine();
3703
- if (this.status === MUParser.END || !line) {
4200
+ if (this.status === MUParser.END) {
3704
4201
  return;
3705
4202
  }
3706
4203
  line = line.trim();
@@ -3729,28 +4226,18 @@ class MUParser {
3729
4226
  }
3730
4227
  readSql() {
3731
4228
  const list = [];
3732
- if (this.lastLine) {
3733
- list.push(this.lastLine);
3734
- while (true) {
3735
- const line = this.nextLine();
3736
- if (line) {
3737
- if (this.status === MUParser.END) {
3738
- return this.getBuildSql(list);
3739
- }
3740
- if (line.startsWith('===')) {
3741
- // 删除下一个sqlId表示
3742
- list.pop();
3743
- return this.getBuildSql(list);
3744
- }
3745
- list.push(line);
3746
- }
3747
- else {
3748
- return '';
3749
- }
4229
+ list.push(this.lastLine);
4230
+ while (true) {
4231
+ const line = this.nextLine();
4232
+ if (this.status === MUParser.END) {
4233
+ return this.getBuildSql(list);
3750
4234
  }
3751
- }
3752
- else {
3753
- return '';
4235
+ if (line.startsWith('===')) {
4236
+ // 删除下一个sqlId表示
4237
+ list.pop();
4238
+ return this.getBuildSql(list);
4239
+ }
4240
+ list.push(line);
3754
4241
  }
3755
4242
  }
3756
4243
  getBuildSql(list) {
@@ -3767,126 +4254,3 @@ class MUParser {
3767
4254
  }
3768
4255
  }
3769
4256
  MUParser.END = 1;
3770
- export const Boot = async function (options) {
3771
- globalThis[_GlobalSqlOption] = Object.assign({}, _defOption, options);
3772
- if (options.sqlDir) {
3773
- globalThis[_path] = await import('path');
3774
- globalThis[_fs] = await import('fs');
3775
- }
3776
- logger.level = options.log ?? 'info';
3777
- globalThis[_sqlCache] = new SqlCache();
3778
- if (options.sqlMap || options.sqlDir) {
3779
- await globalThis[_sqlCache].init(options);
3780
- }
3781
- globalThis[_dao] = {
3782
- [DBType.Mongo]: {},
3783
- [DBType.Mysql]: {},
3784
- [DBType.Sqlite]: {},
3785
- [DBType.SqliteRemote]: {},
3786
- [DBType.Redis]: {}
3787
- };
3788
- if (options.Mysql) {
3789
- const { createPool } = await import('mysql2/promise');
3790
- if (options.Mysql['host']) {
3791
- globalThis[_dao][DBType.Mysql][_primaryDB] = new Mysql(createPool({
3792
- ...options.Mysql,
3793
- multipleStatements: true,
3794
- decimalNumbers: true,
3795
- supportBigNumbers: true
3796
- }));
3797
- }
3798
- else {
3799
- let flag = false;
3800
- for (const [key, option] of Object.entries(options.Mysql)) {
3801
- const db = new Mysql(createPool({
3802
- ...option,
3803
- multipleStatements: true,
3804
- decimalNumbers: true,
3805
- supportBigNumbers: true
3806
- }));
3807
- if (flag === false) {
3808
- globalThis[_dao][DBType.Mysql][_primaryDB] = db;
3809
- flag = true;
3810
- }
3811
- globalThis[_dao][DBType.Mysql][key] = db;
3812
- }
3813
- }
3814
- }
3815
- if (options.Sqlite) {
3816
- const BetterSqlite3 = await import('better-sqlite3');
3817
- if (typeof options.Sqlite === 'string') {
3818
- globalThis[_dao][DBType.Sqlite][_primaryDB] = new Sqlite(new BetterSqlite3.default(options.Sqlite, { fileMustExist: false }));
3819
- }
3820
- else {
3821
- let flag = false;
3822
- for (const [key, fileName] of Object.entries(options.Sqlite)) {
3823
- const db = new Sqlite(new BetterSqlite3.default(fileName, { fileMustExist: false }));
3824
- if (flag === false) {
3825
- globalThis[_dao][DBType.Sqlite][_primaryDB] = db;
3826
- flag = true;
3827
- }
3828
- globalThis[_dao][DBType.Sqlite][key] = db;
3829
- }
3830
- }
3831
- }
3832
- if (options.SqliteRemote) {
3833
- if (typeof options.SqliteRemote.db === 'string') {
3834
- await options.SqliteRemote.service.initDB(options.SqliteRemote.db);
3835
- globalThis[_dao][DBType.SqliteRemote][_primaryDB] = new SqliteRemote(options.SqliteRemote.service, options.SqliteRemote.db);
3836
- }
3837
- else {
3838
- let flag = false;
3839
- for (const [key, fileName] of Object.entries(options.SqliteRemote.db)) {
3840
- await options.SqliteRemote.service.initDB(fileName);
3841
- const db = new SqliteRemote(options.SqliteRemote.service, fileName);
3842
- if (flag === false) {
3843
- globalThis[_dao][DBType.SqliteRemote][_primaryDB] = db;
3844
- flag = true;
3845
- }
3846
- globalThis[_dao][DBType.SqliteRemote][key] = db;
3847
- }
3848
- }
3849
- }
3850
- if (options.Redis) {
3851
- const { Redis } = await import('ioredis');
3852
- if (options.Redis['host']) {
3853
- globalThis[_dao][DBType.Redis][_primaryDB] = new Redis(options.Redis);
3854
- }
3855
- else {
3856
- let flag = false;
3857
- for (const [key, option] of Object.entries(options.Redis)) {
3858
- const db = new Redis(option);
3859
- if (flag === false) {
3860
- globalThis[_dao][DBType.Redis][_primaryDB] = db;
3861
- flag = true;
3862
- }
3863
- globalThis[_dao][DBType.Redis][key] = db;
3864
- }
3865
- }
3866
- const clients = Object.values(globalThis[_dao][DBType.Redis]);
3867
- const Redlock = await import('redlock');
3868
- globalThis[_dao][DBType.RedisLock] = new Redlock.default(clients, {
3869
- // The expected clock drift; for more details see:
3870
- // http://redis.io/topics/distlock
3871
- driftFactor: 0.01, // multiplied by lock ttl to determine drift time
3872
- // The max number of times Redlock will attempt to lock a resource
3873
- // before erroring.
3874
- retryCount: 10,
3875
- // the time in ms between attempts
3876
- retryDelay: 200, // time in ms
3877
- // the max time in ms randomly added to retries
3878
- // to improve performance under high contention
3879
- // see https://www.awsarchitectureblog.com/2015/03/backoff.html
3880
- retryJitter: 200, // time in ms
3881
- // The minimum remaining time on a lock before an extension is automatically
3882
- // attempted with the `using` API.
3883
- automaticExtensionThreshold: 500, // time in ms
3884
- });
3885
- const { EventEmitter } = await import('events');
3886
- const event = new EventEmitter({ captureRejections: true });
3887
- event.on('error', error => {
3888
- logger.error('event-bus', error);
3889
- });
3890
- globalThis[_EventBus] = event;
3891
- }
3892
- };