baja-lite 1.3.27 → 1.3.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/boot-remote.d.ts +2 -0
- package/{src/boot-remote.ts → boot-remote.js} +6 -7
- package/boot.d.ts +2 -0
- package/{src/boot.ts → boot.js} +31 -38
- package/code.d.ts +2 -0
- package/{src/code.ts → code.js} +71 -66
- package/convert-xml.d.ts +10 -0
- package/{src/convert-xml.ts → convert-xml.js} +105 -155
- package/enum.d.ts +18 -0
- package/enum.js +59 -0
- package/error.d.ts +5 -0
- package/error.js +13 -0
- package/fn.d.ts +128 -0
- package/fn.js +172 -0
- package/{src/index.ts → index.d.ts} +11 -12
- package/index.js +11 -0
- package/list.d.ts +10 -0
- package/{src/list.ts → list.js} +8 -9
- package/math.d.ts +83 -0
- package/math.js +451 -0
- package/object.d.ts +83 -0
- package/object.js +221 -0
- package/package.json +1 -1
- package/snowflake.d.ts +12 -0
- package/{src/snowflake.ts → snowflake.js} +33 -52
- package/sql.d.ts +1798 -0
- package/sql.js +4802 -0
- package/sqlite.d.ts +32 -0
- package/{src/sqlite.ts → sqlite.js} +53 -52
- package/string.d.ts +17 -0
- package/string.js +105 -0
- package/test-mysql.d.ts +2 -0
- package/test-mysql.js +109 -0
- package/test-postgresql.d.ts +2 -0
- package/{src/test-postgresql.ts → test-postgresql.js} +91 -80
- package/test-sqlite.d.ts +1 -0
- package/{src/test-sqlite.ts → test-sqlite.js} +90 -80
- package/test-xml.d.ts +1 -0
- package/{src/test-xml.ts → test-xml.js} +1 -1
- package/test.d.ts +1 -0
- package/{src/test.ts → test.js} +2 -3
- package/wx/base.d.ts +11 -0
- package/wx/base.js +78 -0
- package/wx/mini.d.ts +52 -0
- package/wx/mini.js +112 -0
- package/wx/organ.d.ts +65 -0
- package/wx/organ.js +171 -0
- package/{src/wx/types.ts → wx/types.d.ts} +21 -10
- package/wx/types.js +1 -0
- package/wx.js +3 -0
- package/.eslintignore +0 -7
- package/.eslintrc.cjs +0 -89
- package/.prettierrc +0 -4
- package/.vscode/settings.json +0 -8
- package/ci.js +0 -29
- package/package-cjs.json +0 -17
- package/src/enum.ts +0 -71
- package/src/error.ts +0 -11
- package/src/fn.ts +0 -295
- package/src/math.ts +0 -405
- package/src/object.ts +0 -247
- package/src/sql.ts +0 -5023
- package/src/string.ts +0 -111
- package/src/test-mysql.ts +0 -144
- package/src/wx/base.ts +0 -76
- package/src/wx/mini.ts +0 -147
- package/src/wx/organ.ts +0 -290
- package/tsconfig.cjs.json +0 -42
- package/tsconfig.json +0 -44
- package/tsconfig.tsbuildinfo +0 -1
- package/xml/event-report.xml +0 -13
- package/yarn.lock +0 -1757
- /package/{Readme.md → README.md} +0 -0
- /package/{src/wx.ts → wx.d.ts} +0 -0
package/sql.js
ADDED
|
@@ -0,0 +1,4802 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var _b, _c, _d, _e;
|
|
11
|
+
var _f, _g, _h, _j;
|
|
12
|
+
import { decode, DecodeError, encode, ExtensionCodec } from "@msgpack/msgpack";
|
|
13
|
+
import { _columns, _columnsNoId, _def, _deleteState, _fields, _Hump, _ids, _index, _logicIds, _stateFileName, DBType, Field } from 'baja-lite-field';
|
|
14
|
+
import HTML from 'html-parse-stringify';
|
|
15
|
+
import * as ite from 'iterare';
|
|
16
|
+
import LGet from 'lodash.get';
|
|
17
|
+
import mustache from 'mustache';
|
|
18
|
+
import pino from 'pino';
|
|
19
|
+
import { formatDialect, mysql, postgresql, sqlite } from 'sql-formatter';
|
|
20
|
+
import tslib from 'tslib';
|
|
21
|
+
import { convert } from './convert-xml.js';
|
|
22
|
+
import { Throw } from './error.js';
|
|
23
|
+
import { excuteSplit, ExcuteSplitMode, sleep } from './fn.js';
|
|
24
|
+
import { ArrayList } from './list.js';
|
|
25
|
+
import { add, calc, ten2Any } from './math.js';
|
|
26
|
+
import { C2P, C2P2, P2C } from './object.js';
|
|
27
|
+
import { emptyString } from './string.js';
|
|
28
|
+
const iterate = ite.iterate;
|
|
29
|
+
BigInt.prototype.toJSON = function () { return this.toString(); };
|
|
30
|
+
const BIGINT_EXT_TYPE = 0;
|
|
31
|
+
export const extensionCodec = new ExtensionCodec();
|
|
32
|
+
extensionCodec.register({
|
|
33
|
+
type: BIGINT_EXT_TYPE,
|
|
34
|
+
encode(input) {
|
|
35
|
+
if (typeof input === "bigint") {
|
|
36
|
+
if (input <= Number.MAX_SAFE_INTEGER && input >= Number.MIN_SAFE_INTEGER) {
|
|
37
|
+
return encode(Number(input));
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
return encode(String(input));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
decode(data) {
|
|
48
|
+
const val = decode(data);
|
|
49
|
+
if (!(typeof val === "string" || typeof val === "number")) {
|
|
50
|
+
throw new DecodeError(`unexpected BigInt source: ${val} (${typeof val})`);
|
|
51
|
+
}
|
|
52
|
+
return BigInt(val);
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
// #region 常量
|
|
56
|
+
const _daoDBName = Symbol('dbName');
|
|
57
|
+
const _tableName = Symbol('tableName');
|
|
58
|
+
const _className = Symbol('className');
|
|
59
|
+
const _ClassName = Symbol('ClassName');
|
|
60
|
+
const _vueName = Symbol('vueName');
|
|
61
|
+
const _transformer = Symbol('transformer');
|
|
62
|
+
const _comment = Symbol('comment');
|
|
63
|
+
export const _sqlCache = Symbol('sqlMap');
|
|
64
|
+
export const _dao = Symbol('dao');
|
|
65
|
+
export const _primaryDB = '______primaryDB_______';
|
|
66
|
+
const _dbType = Symbol('dbType');
|
|
67
|
+
const _sqlite_version = Symbol('sqlite_version');
|
|
68
|
+
const _daoConnection = Symbol('daoConnection');
|
|
69
|
+
const _inTransaction = Symbol('inTransaction');
|
|
70
|
+
const _daoDB = Symbol('daoDB');
|
|
71
|
+
const _sqliteRemoteName = Symbol('sqliteRemoteName');
|
|
72
|
+
const _SqlOption = Symbol('SqlOption');
|
|
73
|
+
const _resultMap = Symbol('resultMap');
|
|
74
|
+
const _resultMap_SQLID = Symbol('resultMap_SQLID');
|
|
75
|
+
export const _enums = Symbol('_enums');
|
|
76
|
+
export const _GlobalSqlOption = Symbol('GlobalSqlOption');
|
|
77
|
+
export const _EventBus = Symbol('EventBus');
|
|
78
|
+
export const _path = Symbol('path');
|
|
79
|
+
export const _fs = Symbol('fs');
|
|
80
|
+
export const logger = process.env['NODE_ENV'] !== 'production' ? pino({
|
|
81
|
+
name: 'sql',
|
|
82
|
+
transport: {
|
|
83
|
+
target: 'pino-pretty'
|
|
84
|
+
}
|
|
85
|
+
}) : pino({ name: 'sql' });
|
|
86
|
+
globalThis[_resultMap_SQLID] = {};
|
|
87
|
+
// #endregion
|
|
88
|
+
// #region 可选配置
|
|
89
|
+
export var MapperIfUndefined;
|
|
90
|
+
(function (MapperIfUndefined) {
|
|
91
|
+
MapperIfUndefined[MapperIfUndefined["Null"] = 0] = "Null";
|
|
92
|
+
MapperIfUndefined[MapperIfUndefined["Skip"] = 1] = "Skip";
|
|
93
|
+
MapperIfUndefined[MapperIfUndefined["Zero"] = 2] = "Zero";
|
|
94
|
+
MapperIfUndefined[MapperIfUndefined["EmptyString"] = 3] = "EmptyString";
|
|
95
|
+
})(MapperIfUndefined || (MapperIfUndefined = {}));
|
|
96
|
+
;
|
|
97
|
+
export var SyncMode;
|
|
98
|
+
(function (SyncMode) {
|
|
99
|
+
/** 同步执行 */
|
|
100
|
+
SyncMode[SyncMode["Sync"] = 0] = "Sync";
|
|
101
|
+
/** 异步执行 */
|
|
102
|
+
SyncMode[SyncMode["Async"] = 1] = "Async";
|
|
103
|
+
})(SyncMode || (SyncMode = {}));
|
|
104
|
+
export var InsertMode;
|
|
105
|
+
(function (InsertMode) {
|
|
106
|
+
/**
|
|
107
|
+
# 默认使用
|
|
108
|
+
** 支持单个、批量,语法 `INSERT INTO XX VALUES (第一条数据), (第二条数据);`
|
|
109
|
+
** 批量执行有性能优势,但无法利用数据库的sql预编译功能
|
|
110
|
+
*/
|
|
111
|
+
InsertMode[InsertMode["Insert"] = 0] = "Insert";
|
|
112
|
+
/**
|
|
113
|
+
# 利用临时表
|
|
114
|
+
## 执行步骤
|
|
115
|
+
1. 建立临时表(从正式表复制)
|
|
116
|
+
2. 数据全部进入临时表
|
|
117
|
+
3. 临时表数据转移到正式表: `INSERT INTO 正式表 SELECT * FROM 临时表`
|
|
118
|
+
4. 删除临时表
|
|
119
|
+
## 注意
|
|
120
|
+
1. 适用于:主键不会冲突、非自增
|
|
121
|
+
2. 临时表的结构复制正式表
|
|
122
|
+
*/
|
|
123
|
+
InsertMode[InsertMode["InsertWithTempTable"] = 1] = "InsertWithTempTable";
|
|
124
|
+
InsertMode[InsertMode["InsertIfNotExists"] = 2] = "InsertIfNotExists";
|
|
125
|
+
/**
|
|
126
|
+
# 插入或者更新
|
|
127
|
+
1. 判断依据是主键
|
|
128
|
+
*/
|
|
129
|
+
InsertMode[InsertMode["Replace"] = 3] = "Replace";
|
|
130
|
+
})(InsertMode || (InsertMode = {}));
|
|
131
|
+
export var DeleteMode;
|
|
132
|
+
(function (DeleteMode) {
|
|
133
|
+
/**
|
|
134
|
+
##常规删除 默认
|
|
135
|
+
### 例一
|
|
136
|
+
`DELETE FROM WHERE (id = 1) OR (id = 2)`
|
|
137
|
+
### 例二
|
|
138
|
+
`DELETE FROM WHERE (id = 1 AND idx = 11) OR (id = 2 AND idx = 22)`
|
|
139
|
+
*/
|
|
140
|
+
DeleteMode[DeleteMode["Common"] = 0] = "Common";
|
|
141
|
+
/*
|
|
142
|
+
## 借助临时表
|
|
143
|
+
### 注意:必须保证where的字段都相同,否则会漏删数据
|
|
144
|
+
DELETE FROM 正式表 INNER JOIN 临时表 WHERE 字段1 = 字段1 AND 字段2 = 字段2
|
|
145
|
+
*/
|
|
146
|
+
DeleteMode[DeleteMode["TempTable"] = 1] = "TempTable";
|
|
147
|
+
})(DeleteMode || (DeleteMode = {}));
|
|
148
|
+
export var SelectMode;
|
|
149
|
+
(function (SelectMode) {
|
|
150
|
+
/**
|
|
151
|
+
##常规 默认
|
|
152
|
+
### 例一
|
|
153
|
+
`SELECT * FROM WHERE (id = 1) OR (id = 2)`
|
|
154
|
+
### 例二
|
|
155
|
+
`SELECT * FROM WHERE (id = 1 AND idx = 11) OR (id = 2 AND idx = 22)`
|
|
156
|
+
*/
|
|
157
|
+
SelectMode[SelectMode["Common"] = 0] = "Common";
|
|
158
|
+
/*
|
|
159
|
+
## 借助临时表
|
|
160
|
+
### 注意:必须保证where的字段都相同,否则会漏删数据
|
|
161
|
+
SELECT * FROM 正式表 INNER JOIN 临时表 WHERE 字段1 = 字段1 AND 字段2 = 字段2
|
|
162
|
+
*/
|
|
163
|
+
SelectMode[SelectMode["TempTable"] = 1] = "TempTable";
|
|
164
|
+
})(SelectMode || (SelectMode = {}));
|
|
165
|
+
export var TemplateResult;
|
|
166
|
+
(function (TemplateResult) {
|
|
167
|
+
/** 确定返回一条记录,如果不是一个,将报错,返回类型是T */
|
|
168
|
+
TemplateResult[TemplateResult["AssertOne"] = 0] = "AssertOne";
|
|
169
|
+
/** 可能返回一条记录,返回类型是T|null */
|
|
170
|
+
TemplateResult[TemplateResult["NotSureOne"] = 1] = "NotSureOne";
|
|
171
|
+
/** 返回多条记录 */
|
|
172
|
+
TemplateResult[TemplateResult["Many"] = 2] = "Many";
|
|
173
|
+
/** 返回多条记录并封装ArrayList */
|
|
174
|
+
TemplateResult[TemplateResult["ManyList"] = 3] = "ManyList";
|
|
175
|
+
/** 仅查询记录数量 */
|
|
176
|
+
TemplateResult[TemplateResult["Count"] = 4] = "Count";
|
|
177
|
+
})(TemplateResult || (TemplateResult = {}));
|
|
178
|
+
export var SelectResult;
|
|
179
|
+
(function (SelectResult) {
|
|
180
|
+
/** 一行一列 确定非空 */
|
|
181
|
+
SelectResult[SelectResult["R_C_Assert"] = 0] = "R_C_Assert";
|
|
182
|
+
/** 一行一列 可能空 */
|
|
183
|
+
SelectResult[SelectResult["R_C_NotSure"] = 1] = "R_C_NotSure";
|
|
184
|
+
/** 一行多列 确定非空 */
|
|
185
|
+
SelectResult[SelectResult["R_CS_Assert"] = 2] = "R_CS_Assert";
|
|
186
|
+
/** 一行多列 可能空 */
|
|
187
|
+
SelectResult[SelectResult["R_CS_NotSure"] = 3] = "R_CS_NotSure";
|
|
188
|
+
/** 多行一列 */
|
|
189
|
+
SelectResult[SelectResult["RS_C"] = 4] = "RS_C";
|
|
190
|
+
/** 多行一列并封装ArrayList */
|
|
191
|
+
SelectResult[SelectResult["RS_C_List"] = 5] = "RS_C_List";
|
|
192
|
+
/** 多行多列 */
|
|
193
|
+
SelectResult[SelectResult["RS_CS"] = 6] = "RS_CS";
|
|
194
|
+
/** 多行多列并封装ArrayList */
|
|
195
|
+
SelectResult[SelectResult["RS_CS_List"] = 7] = "RS_CS_List";
|
|
196
|
+
})(SelectResult || (SelectResult = {}));
|
|
197
|
+
export var ColumnMode;
|
|
198
|
+
(function (ColumnMode) {
|
|
199
|
+
ColumnMode[ColumnMode["NONE"] = 0] = "NONE";
|
|
200
|
+
ColumnMode[ColumnMode["HUMP"] = 1] = "HUMP";
|
|
201
|
+
})(ColumnMode || (ColumnMode = {}));
|
|
202
|
+
export const SqliteMemory = ':memory:';
|
|
203
|
+
export const _defOption = {
|
|
204
|
+
maxDeal: 500,
|
|
205
|
+
skipUndefined: true,
|
|
206
|
+
skipNull: true,
|
|
207
|
+
skipEmptyString: true
|
|
208
|
+
};
|
|
209
|
+
;
|
|
210
|
+
class MysqlConnection {
|
|
211
|
+
constructor(conn) {
|
|
212
|
+
this[_b] = false;
|
|
213
|
+
this[_daoConnection] = conn;
|
|
214
|
+
}
|
|
215
|
+
execute(sync, sql, params) {
|
|
216
|
+
logger.debug(sql, params ?? '');
|
|
217
|
+
if (!sql) {
|
|
218
|
+
return { affectedRows: 0, insertId: 0n };
|
|
219
|
+
}
|
|
220
|
+
;
|
|
221
|
+
if (sync === SyncMode.Sync) {
|
|
222
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
223
|
+
return { affectedRows: 0, insertId: 0n };
|
|
224
|
+
}
|
|
225
|
+
;
|
|
226
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
227
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
228
|
+
}
|
|
229
|
+
return new Promise(async (resolve, reject) => {
|
|
230
|
+
try {
|
|
231
|
+
const [_result] = await this[_daoConnection].execute(sql, params);
|
|
232
|
+
const result = _result;
|
|
233
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
234
|
+
logger.trace(result);
|
|
235
|
+
}
|
|
236
|
+
resolve({ affectedRows: result.affectedRows, insertId: result.insertId });
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
logger.error(`
|
|
240
|
+
error: ${error},
|
|
241
|
+
sql: ${sql},
|
|
242
|
+
params: ${params}
|
|
243
|
+
`);
|
|
244
|
+
reject(error);
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
pluck(sync, sql, params) {
|
|
249
|
+
logger.debug(sql, params ?? '');
|
|
250
|
+
if (!sql) {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
;
|
|
254
|
+
if (sync === SyncMode.Sync) {
|
|
255
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
;
|
|
259
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
260
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
261
|
+
}
|
|
262
|
+
return new Promise(async (resolve, reject) => {
|
|
263
|
+
try {
|
|
264
|
+
const [result] = await this[_daoConnection].query(sql, params);
|
|
265
|
+
if (result && result[0]) {
|
|
266
|
+
const r = Object.values(result[0])[0];
|
|
267
|
+
if (r === null)
|
|
268
|
+
resolve(r);
|
|
269
|
+
else
|
|
270
|
+
resolve(r);
|
|
271
|
+
}
|
|
272
|
+
resolve(null);
|
|
273
|
+
}
|
|
274
|
+
catch (error) {
|
|
275
|
+
logger.error(`
|
|
276
|
+
error: ${error},
|
|
277
|
+
sql: ${sql},
|
|
278
|
+
params: ${params}
|
|
279
|
+
`);
|
|
280
|
+
reject(error);
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
get(sync, sql, params) {
|
|
285
|
+
logger.debug(sql, params ?? '');
|
|
286
|
+
if (!sql) {
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
;
|
|
290
|
+
if (sync === SyncMode.Sync) {
|
|
291
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
;
|
|
295
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
296
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
297
|
+
}
|
|
298
|
+
return new Promise(async (resolve, reject) => {
|
|
299
|
+
try {
|
|
300
|
+
const [result] = await this[_daoConnection].query(sql, params);
|
|
301
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
302
|
+
logger.trace(result);
|
|
303
|
+
}
|
|
304
|
+
if (result && result[0])
|
|
305
|
+
resolve(result[0]);
|
|
306
|
+
resolve(null);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
logger.error(`
|
|
310
|
+
error: ${error},
|
|
311
|
+
sql: ${sql},
|
|
312
|
+
params: ${params}
|
|
313
|
+
`);
|
|
314
|
+
reject(error);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
raw(sync, sql, params) {
|
|
319
|
+
logger.debug(sql, params ?? '');
|
|
320
|
+
if (!sql) {
|
|
321
|
+
return [];
|
|
322
|
+
}
|
|
323
|
+
;
|
|
324
|
+
if (sync === SyncMode.Sync) {
|
|
325
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
326
|
+
return [];
|
|
327
|
+
}
|
|
328
|
+
;
|
|
329
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
330
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
331
|
+
}
|
|
332
|
+
return new Promise(async (resolve, reject) => {
|
|
333
|
+
try {
|
|
334
|
+
const [result] = await this[_daoConnection].query(sql, params);
|
|
335
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
336
|
+
logger.trace(result);
|
|
337
|
+
}
|
|
338
|
+
if (result)
|
|
339
|
+
resolve(result.map((i) => Object.values(i)[0]));
|
|
340
|
+
resolve([]);
|
|
341
|
+
}
|
|
342
|
+
catch (error) {
|
|
343
|
+
logger.error(`
|
|
344
|
+
error: ${error},
|
|
345
|
+
sql: ${sql},
|
|
346
|
+
params: ${params}
|
|
347
|
+
`);
|
|
348
|
+
reject(error);
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
query(sync, sql, params) {
|
|
353
|
+
logger.debug(sql, params ?? '');
|
|
354
|
+
if (!sql) {
|
|
355
|
+
return [];
|
|
356
|
+
}
|
|
357
|
+
;
|
|
358
|
+
if (sync === SyncMode.Sync) {
|
|
359
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
360
|
+
return [];
|
|
361
|
+
}
|
|
362
|
+
;
|
|
363
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
364
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
365
|
+
}
|
|
366
|
+
return new Promise(async (resolve, reject) => {
|
|
367
|
+
try {
|
|
368
|
+
const [result] = await this[_daoConnection].query(sql, params);
|
|
369
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
370
|
+
logger.trace(result);
|
|
371
|
+
}
|
|
372
|
+
resolve(result);
|
|
373
|
+
}
|
|
374
|
+
catch (error) {
|
|
375
|
+
logger.error(`
|
|
376
|
+
error: ${error},
|
|
377
|
+
sql: ${sql},
|
|
378
|
+
params: ${params}
|
|
379
|
+
`);
|
|
380
|
+
reject(error);
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
realse(sync) {
|
|
385
|
+
if (sync === SyncMode.Sync) {
|
|
386
|
+
try {
|
|
387
|
+
this[_daoConnection]?.release();
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
_b = _inTransaction;
|
|
396
|
+
export class Mysql {
|
|
397
|
+
constructor(pool) {
|
|
398
|
+
this[_daoDB] = pool;
|
|
399
|
+
}
|
|
400
|
+
async keepAlive() {
|
|
401
|
+
const connection = await this[_daoDB].getConnection();
|
|
402
|
+
connection.query('SELECT 1 FROM DUAL');
|
|
403
|
+
setTimeout(async () => await this.keepAlive(), 60000);
|
|
404
|
+
}
|
|
405
|
+
createConnection(sync) {
|
|
406
|
+
if (sync === SyncMode.Sync) {
|
|
407
|
+
logger.error('MYSQL not suppouted sync mode');
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
;
|
|
411
|
+
return new Promise(async (resolve, reject) => {
|
|
412
|
+
try {
|
|
413
|
+
const connection = await this[_daoDB].getConnection();
|
|
414
|
+
logger.debug('create new connection!');
|
|
415
|
+
resolve(new MysqlConnection(connection));
|
|
416
|
+
}
|
|
417
|
+
catch (error) {
|
|
418
|
+
reject(error);
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
transaction(sync, fn, conn) {
|
|
423
|
+
if (sync === SyncMode.Sync) {
|
|
424
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
;
|
|
428
|
+
return new Promise(async (resolve, reject) => {
|
|
429
|
+
let needCommit = false;
|
|
430
|
+
let newConn = false;
|
|
431
|
+
if (!conn) {
|
|
432
|
+
conn = await this.createConnection(SyncMode.Async) ?? undefined;
|
|
433
|
+
newConn = true;
|
|
434
|
+
}
|
|
435
|
+
if (conn?.[_inTransaction] !== true) {
|
|
436
|
+
needCommit = true;
|
|
437
|
+
logger.debug('beginTransaction begin!');
|
|
438
|
+
await conn[_daoConnection].beginTransaction();
|
|
439
|
+
logger.debug('beginTransaction end!');
|
|
440
|
+
}
|
|
441
|
+
conn[_inTransaction] = true;
|
|
442
|
+
try {
|
|
443
|
+
const result = await fn(conn);
|
|
444
|
+
if (needCommit === true) {
|
|
445
|
+
logger.debug('commit begin!');
|
|
446
|
+
await conn[_daoConnection].commit();
|
|
447
|
+
conn[_inTransaction] = false;
|
|
448
|
+
logger.debug('commit end!');
|
|
449
|
+
}
|
|
450
|
+
resolve(result);
|
|
451
|
+
}
|
|
452
|
+
catch (error) {
|
|
453
|
+
logger.debug('rollback begin!');
|
|
454
|
+
await conn[_daoConnection].rollback();
|
|
455
|
+
logger.debug('rollback end!');
|
|
456
|
+
conn[_inTransaction] = false;
|
|
457
|
+
logger.error(error);
|
|
458
|
+
reject(error);
|
|
459
|
+
}
|
|
460
|
+
finally {
|
|
461
|
+
try {
|
|
462
|
+
if (needCommit === true) {
|
|
463
|
+
conn[_inTransaction] = false;
|
|
464
|
+
}
|
|
465
|
+
if (newConn === true) {
|
|
466
|
+
logger.debug('release begin!');
|
|
467
|
+
conn[_daoConnection].release();
|
|
468
|
+
logger.debug('release end!');
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
catch (error) {
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
close(sync) {
|
|
477
|
+
if (sync === SyncMode.Sync) {
|
|
478
|
+
this[_daoDB]?.destroy();
|
|
479
|
+
}
|
|
480
|
+
;
|
|
481
|
+
}
|
|
482
|
+
backup(sync, name) {
|
|
483
|
+
}
|
|
484
|
+
remove(sync) {
|
|
485
|
+
}
|
|
486
|
+
restore(sync, name) {
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
class PostgresqlConnection {
|
|
490
|
+
constructor(conn) {
|
|
491
|
+
this[_c] = false;
|
|
492
|
+
this[_daoConnection] = conn;
|
|
493
|
+
}
|
|
494
|
+
execute(sync, sql, params) {
|
|
495
|
+
logger.debug(sql, params ?? '');
|
|
496
|
+
if (!sql) {
|
|
497
|
+
return { affectedRows: 0, insertId: 0n };
|
|
498
|
+
}
|
|
499
|
+
;
|
|
500
|
+
if (sync === SyncMode.Sync) {
|
|
501
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
502
|
+
return { affectedRows: 0, insertId: 0n };
|
|
503
|
+
}
|
|
504
|
+
;
|
|
505
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
506
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
507
|
+
}
|
|
508
|
+
return new Promise(async (resolve, reject) => {
|
|
509
|
+
try {
|
|
510
|
+
let index = 1;
|
|
511
|
+
const { rowCount } = await this[_daoConnection].query({
|
|
512
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
513
|
+
values: params
|
|
514
|
+
});
|
|
515
|
+
const result = rowCount;
|
|
516
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
517
|
+
logger.trace(result);
|
|
518
|
+
}
|
|
519
|
+
resolve({ affectedRows: result.affectedRows, insertId: result.insertId });
|
|
520
|
+
}
|
|
521
|
+
catch (error) {
|
|
522
|
+
logger.error(`
|
|
523
|
+
error: ${error},
|
|
524
|
+
sql: ${sql},
|
|
525
|
+
params: ${params}
|
|
526
|
+
`);
|
|
527
|
+
reject(error);
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
pluck(sync, sql, params) {
|
|
532
|
+
logger.debug(sql, params ?? '');
|
|
533
|
+
if (!sql) {
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
;
|
|
537
|
+
if (sync === SyncMode.Sync) {
|
|
538
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
539
|
+
return null;
|
|
540
|
+
}
|
|
541
|
+
;
|
|
542
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
543
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
544
|
+
}
|
|
545
|
+
return new Promise(async (resolve, reject) => {
|
|
546
|
+
try {
|
|
547
|
+
let index = 1;
|
|
548
|
+
const { rows } = await this[_daoConnection].query({
|
|
549
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
550
|
+
values: params
|
|
551
|
+
});
|
|
552
|
+
if (rows && rows[0]) {
|
|
553
|
+
const r = Object.values(rows[0])[0];
|
|
554
|
+
if (r === null)
|
|
555
|
+
resolve(r);
|
|
556
|
+
else
|
|
557
|
+
resolve(r);
|
|
558
|
+
}
|
|
559
|
+
resolve(null);
|
|
560
|
+
}
|
|
561
|
+
catch (error) {
|
|
562
|
+
logger.error(`
|
|
563
|
+
error: ${error},
|
|
564
|
+
sql: ${sql},
|
|
565
|
+
params: ${params}
|
|
566
|
+
`);
|
|
567
|
+
reject(error);
|
|
568
|
+
}
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
get(sync, sql, params) {
|
|
572
|
+
logger.debug(sql, params ?? '');
|
|
573
|
+
if (!sql) {
|
|
574
|
+
return null;
|
|
575
|
+
}
|
|
576
|
+
;
|
|
577
|
+
if (sync === SyncMode.Sync) {
|
|
578
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
579
|
+
return null;
|
|
580
|
+
}
|
|
581
|
+
;
|
|
582
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
583
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
584
|
+
}
|
|
585
|
+
return new Promise(async (resolve, reject) => {
|
|
586
|
+
try {
|
|
587
|
+
let index = 1;
|
|
588
|
+
const { rows } = await this[_daoConnection].query({
|
|
589
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
590
|
+
values: params
|
|
591
|
+
});
|
|
592
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
593
|
+
logger.trace(rows);
|
|
594
|
+
}
|
|
595
|
+
if (rows && rows[0])
|
|
596
|
+
resolve(rows[0]);
|
|
597
|
+
resolve(null);
|
|
598
|
+
}
|
|
599
|
+
catch (error) {
|
|
600
|
+
logger.error(`
|
|
601
|
+
error: ${error},
|
|
602
|
+
sql: ${sql},
|
|
603
|
+
params: ${params}
|
|
604
|
+
`);
|
|
605
|
+
reject(error);
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
raw(sync, sql, params) {
|
|
610
|
+
logger.debug(sql, params ?? '');
|
|
611
|
+
if (!sql) {
|
|
612
|
+
return [];
|
|
613
|
+
}
|
|
614
|
+
;
|
|
615
|
+
if (sync === SyncMode.Sync) {
|
|
616
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
617
|
+
return [];
|
|
618
|
+
}
|
|
619
|
+
;
|
|
620
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
621
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
622
|
+
}
|
|
623
|
+
return new Promise(async (resolve, reject) => {
|
|
624
|
+
try {
|
|
625
|
+
let index = 1;
|
|
626
|
+
const { rows } = await this[_daoConnection].query({
|
|
627
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
628
|
+
values: params
|
|
629
|
+
});
|
|
630
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
631
|
+
logger.trace(rows);
|
|
632
|
+
}
|
|
633
|
+
if (rows)
|
|
634
|
+
resolve(rows.map((i) => Object.values(i)[0]));
|
|
635
|
+
resolve([]);
|
|
636
|
+
}
|
|
637
|
+
catch (error) {
|
|
638
|
+
logger.error(`
|
|
639
|
+
error: ${error},
|
|
640
|
+
sql: ${sql},
|
|
641
|
+
params: ${params}
|
|
642
|
+
`);
|
|
643
|
+
reject(error);
|
|
644
|
+
}
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
query(sync, sql, params) {
|
|
648
|
+
logger.debug(sql, params ?? '');
|
|
649
|
+
if (!sql) {
|
|
650
|
+
return [];
|
|
651
|
+
}
|
|
652
|
+
;
|
|
653
|
+
if (sync === SyncMode.Sync) {
|
|
654
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
655
|
+
return [];
|
|
656
|
+
}
|
|
657
|
+
;
|
|
658
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
659
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
660
|
+
}
|
|
661
|
+
return new Promise(async (resolve, reject) => {
|
|
662
|
+
try {
|
|
663
|
+
let index = 1;
|
|
664
|
+
const { rows } = await this[_daoConnection].query({
|
|
665
|
+
text: sql.replace(/\?/g, () => `$${index++}`),
|
|
666
|
+
values: params
|
|
667
|
+
});
|
|
668
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
669
|
+
logger.trace(rows);
|
|
670
|
+
}
|
|
671
|
+
resolve(rows);
|
|
672
|
+
}
|
|
673
|
+
catch (error) {
|
|
674
|
+
logger.error(`
|
|
675
|
+
error: ${error},
|
|
676
|
+
sql: ${sql},
|
|
677
|
+
params: ${params}
|
|
678
|
+
`);
|
|
679
|
+
reject(error);
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
realse(sync) {
|
|
684
|
+
if (sync === SyncMode.Sync) {
|
|
685
|
+
try {
|
|
686
|
+
this[_daoConnection]?.release();
|
|
687
|
+
}
|
|
688
|
+
catch (error) {
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
_c = _inTransaction;
|
|
695
|
+
export class Postgresql {
|
|
696
|
+
constructor(pool) {
|
|
697
|
+
this[_daoDB] = pool;
|
|
698
|
+
}
|
|
699
|
+
async keepAlive() {
|
|
700
|
+
const connection = await this[_daoDB].connect();
|
|
701
|
+
connection.query('SELECT 1');
|
|
702
|
+
setTimeout(async () => await this.keepAlive(), 60000);
|
|
703
|
+
}
|
|
704
|
+
createConnection(sync) {
|
|
705
|
+
if (sync === SyncMode.Sync) {
|
|
706
|
+
logger.error('Postgresql not suppouted sync mode');
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
709
|
+
;
|
|
710
|
+
return new Promise(async (resolve, reject) => {
|
|
711
|
+
try {
|
|
712
|
+
const connection = await this[_daoDB].connect();
|
|
713
|
+
logger.debug('create new connection!');
|
|
714
|
+
resolve(new PostgresqlConnection(connection));
|
|
715
|
+
}
|
|
716
|
+
catch (error) {
|
|
717
|
+
reject(error);
|
|
718
|
+
}
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
transaction(sync, fn, conn) {
|
|
722
|
+
if (sync === SyncMode.Sync) {
|
|
723
|
+
logger.warn('Postgresql not suppouted sync mode');
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
;
|
|
727
|
+
return new Promise(async (resolve, reject) => {
|
|
728
|
+
let needCommit = false;
|
|
729
|
+
let newConn = false;
|
|
730
|
+
if (!conn) {
|
|
731
|
+
conn = await this.createConnection(SyncMode.Async) ?? undefined;
|
|
732
|
+
newConn = true;
|
|
733
|
+
}
|
|
734
|
+
if (conn?.[_inTransaction] !== true) {
|
|
735
|
+
needCommit = true;
|
|
736
|
+
logger.debug('beginTransaction begin!');
|
|
737
|
+
await conn[_daoConnection].query('BEGIN');
|
|
738
|
+
logger.debug('beginTransaction end!');
|
|
739
|
+
}
|
|
740
|
+
conn[_inTransaction] = true;
|
|
741
|
+
try {
|
|
742
|
+
const result = await fn(conn);
|
|
743
|
+
if (needCommit === true) {
|
|
744
|
+
logger.debug('commit begin!');
|
|
745
|
+
await conn[_daoConnection].query('COMMIT');
|
|
746
|
+
conn[_inTransaction] = false;
|
|
747
|
+
logger.debug('commit end!');
|
|
748
|
+
}
|
|
749
|
+
resolve(result);
|
|
750
|
+
}
|
|
751
|
+
catch (error) {
|
|
752
|
+
logger.debug('rollback begin!');
|
|
753
|
+
await conn[_daoConnection].query('ROLLBACK');
|
|
754
|
+
logger.debug('rollback end!');
|
|
755
|
+
conn[_inTransaction] = false;
|
|
756
|
+
logger.error(error);
|
|
757
|
+
reject(error);
|
|
758
|
+
}
|
|
759
|
+
finally {
|
|
760
|
+
try {
|
|
761
|
+
if (needCommit === true) {
|
|
762
|
+
conn[_inTransaction] = false;
|
|
763
|
+
}
|
|
764
|
+
if (newConn === true) {
|
|
765
|
+
logger.debug('release begin!');
|
|
766
|
+
conn[_daoConnection].release();
|
|
767
|
+
logger.debug('release end!');
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
catch (error) {
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
close(sync) {
|
|
776
|
+
if (sync === SyncMode.Sync) {
|
|
777
|
+
this[_daoDB]?.end();
|
|
778
|
+
}
|
|
779
|
+
;
|
|
780
|
+
}
|
|
781
|
+
backup(sync, name) {
|
|
782
|
+
}
|
|
783
|
+
remove(sync) {
|
|
784
|
+
}
|
|
785
|
+
restore(sync, name) {
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
class SqliteConnection {
|
|
789
|
+
constructor(conn) {
|
|
790
|
+
this[_d] = false;
|
|
791
|
+
this[_daoConnection] = conn;
|
|
792
|
+
}
|
|
793
|
+
execute(sync, sql, params) {
|
|
794
|
+
try {
|
|
795
|
+
logger.debug(sql, params ?? '');
|
|
796
|
+
if (!sql) {
|
|
797
|
+
return { affectedRows: 0, insertId: 0n };
|
|
798
|
+
}
|
|
799
|
+
;
|
|
800
|
+
if (sync === SyncMode.Async) {
|
|
801
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
802
|
+
return { affectedRows: 0, insertId: 0n };
|
|
803
|
+
}
|
|
804
|
+
;
|
|
805
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
806
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
807
|
+
}
|
|
808
|
+
const result = this[_daoConnection].prepare(sql).run(params ?? {});
|
|
809
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
810
|
+
logger.trace(result);
|
|
811
|
+
}
|
|
812
|
+
const { changes, lastInsertRowid } = result;
|
|
813
|
+
return { affectedRows: changes, insertId: lastInsertRowid ? BigInt(lastInsertRowid) : 0n };
|
|
814
|
+
}
|
|
815
|
+
catch (error) {
|
|
816
|
+
logger.error(`
|
|
817
|
+
error: ${error},
|
|
818
|
+
sql: ${sql},
|
|
819
|
+
params: ${params}
|
|
820
|
+
`);
|
|
821
|
+
throw error;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
pluck(sync, sql, params) {
|
|
825
|
+
try {
|
|
826
|
+
logger.debug(sql, params ?? '');
|
|
827
|
+
if (!sql) {
|
|
828
|
+
return null;
|
|
829
|
+
}
|
|
830
|
+
;
|
|
831
|
+
if (sync === SyncMode.Async) {
|
|
832
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
833
|
+
return null;
|
|
834
|
+
}
|
|
835
|
+
;
|
|
836
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
837
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
838
|
+
}
|
|
839
|
+
return this[_daoConnection].prepare(sql).pluck().get(params ?? {});
|
|
840
|
+
}
|
|
841
|
+
catch (error) {
|
|
842
|
+
logger.error(`
|
|
843
|
+
error: ${error},
|
|
844
|
+
sql: ${sql},
|
|
845
|
+
params: ${params}
|
|
846
|
+
`);
|
|
847
|
+
throw error;
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
get(sync, sql, params) {
|
|
851
|
+
try {
|
|
852
|
+
logger.debug(sql, params ?? '');
|
|
853
|
+
if (!sql) {
|
|
854
|
+
return null;
|
|
855
|
+
}
|
|
856
|
+
;
|
|
857
|
+
if (sync === SyncMode.Async) {
|
|
858
|
+
return null;
|
|
859
|
+
}
|
|
860
|
+
;
|
|
861
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
862
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
863
|
+
}
|
|
864
|
+
return this[_daoConnection].prepare(sql).get(params ?? {});
|
|
865
|
+
}
|
|
866
|
+
catch (error) {
|
|
867
|
+
logger.error(`
|
|
868
|
+
error: ${error},
|
|
869
|
+
sql: ${sql},
|
|
870
|
+
params: ${params}
|
|
871
|
+
`);
|
|
872
|
+
throw error;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
raw(sync, sql, params) {
|
|
876
|
+
try {
|
|
877
|
+
logger.debug(sql, params ?? '');
|
|
878
|
+
if (!sql) {
|
|
879
|
+
return [];
|
|
880
|
+
}
|
|
881
|
+
;
|
|
882
|
+
if (sync === SyncMode.Async) {
|
|
883
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
884
|
+
return [];
|
|
885
|
+
}
|
|
886
|
+
;
|
|
887
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
888
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
889
|
+
}
|
|
890
|
+
return this[_daoConnection].prepare(sql).raw().all(params ?? {});
|
|
891
|
+
}
|
|
892
|
+
catch (error) {
|
|
893
|
+
logger.error(`
|
|
894
|
+
error: ${error},
|
|
895
|
+
sql: ${sql},
|
|
896
|
+
params: ${params}
|
|
897
|
+
`);
|
|
898
|
+
throw error;
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
query(sync, sql, params) {
|
|
902
|
+
try {
|
|
903
|
+
logger.debug(sql, params ?? '');
|
|
904
|
+
if (!sql) {
|
|
905
|
+
return [];
|
|
906
|
+
}
|
|
907
|
+
;
|
|
908
|
+
if (sync === SyncMode.Async) {
|
|
909
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
910
|
+
return [];
|
|
911
|
+
}
|
|
912
|
+
;
|
|
913
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
914
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
915
|
+
}
|
|
916
|
+
return this[_daoConnection].prepare(sql).all(params ?? {});
|
|
917
|
+
}
|
|
918
|
+
catch (error) {
|
|
919
|
+
logger.error(`
|
|
920
|
+
error: ${error},
|
|
921
|
+
sql: ${sql},
|
|
922
|
+
params: ${params}
|
|
923
|
+
`);
|
|
924
|
+
throw error;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
realse(sync) {
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
_d = _inTransaction;
|
|
931
|
+
export class Sqlite {
|
|
932
|
+
constructor(db) {
|
|
933
|
+
this[_daoDB] = db;
|
|
934
|
+
this[_daoDB].pragma('journal_mode = WAL');
|
|
935
|
+
this[_daoDB].exec(`
|
|
936
|
+
CREATE TABLE IF NOT EXISTS DUAL ( ______id INTEGER NOT NULL, PRIMARY KEY ( ______id ));
|
|
937
|
+
DELETE FROM DUAL;
|
|
938
|
+
INSERT INTO DUAL (______id ) VALUES ( 1 );
|
|
939
|
+
CREATE TABLE IF NOT EXISTS TABLE_VERSION (
|
|
940
|
+
______tableName text NOT NULL,
|
|
941
|
+
______version text NOT NULL,
|
|
942
|
+
PRIMARY KEY ( ______tableName )
|
|
943
|
+
);
|
|
944
|
+
`);
|
|
945
|
+
}
|
|
946
|
+
createConnection(sync) {
|
|
947
|
+
if (sync === SyncMode.Async) {
|
|
948
|
+
logger.error(`SQLITE not suppoted async mode`);
|
|
949
|
+
return null;
|
|
950
|
+
}
|
|
951
|
+
;
|
|
952
|
+
return new SqliteConnection(this[_daoDB]);
|
|
953
|
+
}
|
|
954
|
+
transaction(sync, fn, conn) {
|
|
955
|
+
if (sync === SyncMode.Async) {
|
|
956
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
957
|
+
return null;
|
|
958
|
+
}
|
|
959
|
+
;
|
|
960
|
+
if (!conn) {
|
|
961
|
+
conn = this.createConnection(SyncMode.Sync) ?? undefined;
|
|
962
|
+
}
|
|
963
|
+
if (conn[_inTransaction] !== true) {
|
|
964
|
+
return this[_daoDB].transaction(() => {
|
|
965
|
+
conn[_inTransaction] = true;
|
|
966
|
+
const rt = fn(conn);
|
|
967
|
+
conn[_inTransaction] = false;
|
|
968
|
+
return rt;
|
|
969
|
+
})();
|
|
970
|
+
}
|
|
971
|
+
else {
|
|
972
|
+
const rt = fn(conn);
|
|
973
|
+
return rt;
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
close(sync) {
|
|
977
|
+
if (sync === SyncMode.Sync) {
|
|
978
|
+
this[_daoDB].close();
|
|
979
|
+
}
|
|
980
|
+
;
|
|
981
|
+
}
|
|
982
|
+
backup(sync, name) {
|
|
983
|
+
if (sync === SyncMode.Sync) {
|
|
984
|
+
this[_daoDB].backup(name);
|
|
985
|
+
}
|
|
986
|
+
;
|
|
987
|
+
}
|
|
988
|
+
remove(sync) {
|
|
989
|
+
}
|
|
990
|
+
restore(sync, name) {
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
export class SqliteRemoteConnection {
|
|
994
|
+
constructor(conn, name) {
|
|
995
|
+
this[_e] = false;
|
|
996
|
+
this[_daoConnection] = conn;
|
|
997
|
+
this[_sqliteRemoteName] = name;
|
|
998
|
+
}
|
|
999
|
+
execute(sync, sql, params) {
|
|
1000
|
+
logger.debug(sql, params ?? '');
|
|
1001
|
+
if (!sql) {
|
|
1002
|
+
return { affectedRows: 0, insertId: 0n };
|
|
1003
|
+
}
|
|
1004
|
+
;
|
|
1005
|
+
if (sync === SyncMode.Sync) {
|
|
1006
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
1007
|
+
return { affectedRows: 0, insertId: 0n };
|
|
1008
|
+
}
|
|
1009
|
+
;
|
|
1010
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1011
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
1012
|
+
}
|
|
1013
|
+
return new Promise(async (resolve, reject) => {
|
|
1014
|
+
try {
|
|
1015
|
+
const data = await this[_daoConnection].execute(encode([this[_sqliteRemoteName], sql, params], { extensionCodec }));
|
|
1016
|
+
const { affectedRows, insertId } = decode(data, { extensionCodec });
|
|
1017
|
+
resolve({ affectedRows, insertId: insertId ? BigInt(insertId) : 0n });
|
|
1018
|
+
}
|
|
1019
|
+
catch (error) {
|
|
1020
|
+
logger.error(`
|
|
1021
|
+
error: ${error},
|
|
1022
|
+
sql: ${sql},
|
|
1023
|
+
params: ${params}
|
|
1024
|
+
`);
|
|
1025
|
+
reject(error);
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
pluck(sync, sql, params) {
|
|
1030
|
+
logger.debug(sql, params ?? '');
|
|
1031
|
+
if (!sql) {
|
|
1032
|
+
return null;
|
|
1033
|
+
}
|
|
1034
|
+
;
|
|
1035
|
+
if (sync === SyncMode.Sync) {
|
|
1036
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
1037
|
+
return null;
|
|
1038
|
+
}
|
|
1039
|
+
;
|
|
1040
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1041
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
1042
|
+
}
|
|
1043
|
+
return new Promise(async (resolve, reject) => {
|
|
1044
|
+
try {
|
|
1045
|
+
const data = await this[_daoConnection].pluck(encode([this[_sqliteRemoteName], sql, params], { extensionCodec }));
|
|
1046
|
+
const r = decode(data, { extensionCodec });
|
|
1047
|
+
resolve(r);
|
|
1048
|
+
}
|
|
1049
|
+
catch (error) {
|
|
1050
|
+
logger.error(`
|
|
1051
|
+
error: ${error},
|
|
1052
|
+
sql: ${sql},
|
|
1053
|
+
params: ${params}
|
|
1054
|
+
`);
|
|
1055
|
+
reject(error);
|
|
1056
|
+
}
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
get(sync, sql, params) {
|
|
1060
|
+
logger.debug(sql, params ?? '');
|
|
1061
|
+
if (!sql) {
|
|
1062
|
+
return null;
|
|
1063
|
+
}
|
|
1064
|
+
;
|
|
1065
|
+
if (sync === SyncMode.Sync) {
|
|
1066
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
1067
|
+
return null;
|
|
1068
|
+
}
|
|
1069
|
+
;
|
|
1070
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1071
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
1072
|
+
}
|
|
1073
|
+
return new Promise(async (resolve, reject) => {
|
|
1074
|
+
try {
|
|
1075
|
+
const data = await this[_daoConnection].get(encode([this[_sqliteRemoteName], sql, params], { extensionCodec }));
|
|
1076
|
+
const r = decode(data, { extensionCodec });
|
|
1077
|
+
resolve(r);
|
|
1078
|
+
}
|
|
1079
|
+
catch (error) {
|
|
1080
|
+
logger.error(`
|
|
1081
|
+
error: ${error},
|
|
1082
|
+
sql: ${sql},
|
|
1083
|
+
params: ${params}
|
|
1084
|
+
`);
|
|
1085
|
+
reject(error);
|
|
1086
|
+
}
|
|
1087
|
+
});
|
|
1088
|
+
}
|
|
1089
|
+
raw(sync, sql, params) {
|
|
1090
|
+
logger.debug(sql, params ?? '');
|
|
1091
|
+
if (!sql) {
|
|
1092
|
+
return [];
|
|
1093
|
+
}
|
|
1094
|
+
;
|
|
1095
|
+
if (sync === SyncMode.Sync) {
|
|
1096
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
1097
|
+
return [];
|
|
1098
|
+
}
|
|
1099
|
+
;
|
|
1100
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1101
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
1102
|
+
}
|
|
1103
|
+
return new Promise(async (resolve, reject) => {
|
|
1104
|
+
try {
|
|
1105
|
+
const data = await this[_daoConnection].raw(encode([this[_sqliteRemoteName], sql, params], { extensionCodec }));
|
|
1106
|
+
const r = decode(data, { extensionCodec });
|
|
1107
|
+
resolve(r);
|
|
1108
|
+
}
|
|
1109
|
+
catch (error) {
|
|
1110
|
+
logger.error(`
|
|
1111
|
+
error: ${error},
|
|
1112
|
+
sql: ${sql},
|
|
1113
|
+
params: ${params}
|
|
1114
|
+
`);
|
|
1115
|
+
reject(error);
|
|
1116
|
+
}
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
query(sync, sql, params) {
|
|
1120
|
+
logger.debug(sql, params ?? '');
|
|
1121
|
+
if (!sql) {
|
|
1122
|
+
return [];
|
|
1123
|
+
}
|
|
1124
|
+
;
|
|
1125
|
+
if (sync === SyncMode.Sync) {
|
|
1126
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
1127
|
+
return [];
|
|
1128
|
+
}
|
|
1129
|
+
;
|
|
1130
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
1131
|
+
logger.trace(`${sql}\n,${JSON.stringify(params ?? '')}`);
|
|
1132
|
+
}
|
|
1133
|
+
return new Promise(async (resolve, reject) => {
|
|
1134
|
+
try {
|
|
1135
|
+
const data = await this[_daoConnection].query(encode([this[_sqliteRemoteName], sql, params], { extensionCodec }));
|
|
1136
|
+
const r = decode(data, { extensionCodec });
|
|
1137
|
+
resolve(r);
|
|
1138
|
+
}
|
|
1139
|
+
catch (error) {
|
|
1140
|
+
logger.error(`
|
|
1141
|
+
error: ${error},
|
|
1142
|
+
sql: ${sql},
|
|
1143
|
+
params: ${params}
|
|
1144
|
+
`);
|
|
1145
|
+
reject(error);
|
|
1146
|
+
}
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
realse(sync) {
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
_e = _inTransaction;
|
|
1153
|
+
export class SqliteRemote {
|
|
1154
|
+
constructor(db, name) {
|
|
1155
|
+
this[_daoDB] = db;
|
|
1156
|
+
this[_sqliteRemoteName] = name;
|
|
1157
|
+
}
|
|
1158
|
+
createConnection(sync) {
|
|
1159
|
+
if (sync === SyncMode.Sync) {
|
|
1160
|
+
logger.error('SQLITEREMOTE not suppouted sync mode');
|
|
1161
|
+
return null;
|
|
1162
|
+
}
|
|
1163
|
+
;
|
|
1164
|
+
return new Promise(async (resolve, reject) => {
|
|
1165
|
+
if (!this.connection) {
|
|
1166
|
+
this.connection = new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]);
|
|
1167
|
+
}
|
|
1168
|
+
try {
|
|
1169
|
+
resolve(this.connection);
|
|
1170
|
+
}
|
|
1171
|
+
catch (error) {
|
|
1172
|
+
reject(error);
|
|
1173
|
+
}
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
transaction(sync, fn, conn) {
|
|
1177
|
+
logger.warn(`SQLITEREMOTE not suppoted transaction`);
|
|
1178
|
+
return null;
|
|
1179
|
+
}
|
|
1180
|
+
close(sync) {
|
|
1181
|
+
if (sync === SyncMode.Async) {
|
|
1182
|
+
return this[_daoDB]?.close(this[_sqliteRemoteName]);
|
|
1183
|
+
}
|
|
1184
|
+
;
|
|
1185
|
+
}
|
|
1186
|
+
backup(sync, exportPath) {
|
|
1187
|
+
if (sync === SyncMode.Async) {
|
|
1188
|
+
return this[_daoDB]?.export(this[_sqliteRemoteName], exportPath);
|
|
1189
|
+
}
|
|
1190
|
+
;
|
|
1191
|
+
}
|
|
1192
|
+
remove(sync) {
|
|
1193
|
+
}
|
|
1194
|
+
restore(sync, importPath) {
|
|
1195
|
+
if (sync === SyncMode.Async) {
|
|
1196
|
+
return this[_daoDB]?.restore(this[_sqliteRemoteName], importPath);
|
|
1197
|
+
}
|
|
1198
|
+
;
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
class Build {
|
|
1202
|
+
/**
|
|
1203
|
+
*
|
|
1204
|
+
* @param count 是否是count查询
|
|
1205
|
+
* @param isSum 是否是sum查询
|
|
1206
|
+
* @param param
|
|
1207
|
+
*/
|
|
1208
|
+
constructor(isCount, isSum, param = {}) {
|
|
1209
|
+
this.isCount = isCount;
|
|
1210
|
+
this.isSum = isSum;
|
|
1211
|
+
this.orderBy = param.sortName ? `${param.sortName} ${param.sortType ?? 'ASC'}` : '';
|
|
1212
|
+
Object.assign(this, param);
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
*
|
|
1216
|
+
* 当分页时将函数内包含的内容替换为COUNT(1)
|
|
1217
|
+
* @returns
|
|
1218
|
+
* @memberof Build
|
|
1219
|
+
*/
|
|
1220
|
+
page() {
|
|
1221
|
+
return (text, render) => {
|
|
1222
|
+
if (this.isCount === true) {
|
|
1223
|
+
return Build.page;
|
|
1224
|
+
}
|
|
1225
|
+
else if (this.isSum !== true) {
|
|
1226
|
+
return render(text);
|
|
1227
|
+
}
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
*
|
|
1232
|
+
* 包含的内容只在汇总查询时有效,否则是空白
|
|
1233
|
+
* @returns
|
|
1234
|
+
* @memberof Build
|
|
1235
|
+
*/
|
|
1236
|
+
sum() {
|
|
1237
|
+
return (text, render) => {
|
|
1238
|
+
if (this.isSum !== true) {
|
|
1239
|
+
return '';
|
|
1240
|
+
}
|
|
1241
|
+
else {
|
|
1242
|
+
return render(text);
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
*
|
|
1248
|
+
* 当分页时、汇总时忽略函数内包含的内容
|
|
1249
|
+
* @returns
|
|
1250
|
+
* @memberof Build
|
|
1251
|
+
*/
|
|
1252
|
+
notPage() {
|
|
1253
|
+
return (text, render) => {
|
|
1254
|
+
if (this.isCount === true || this.isSum === true) {
|
|
1255
|
+
return '';
|
|
1256
|
+
}
|
|
1257
|
+
else {
|
|
1258
|
+
return render(text);
|
|
1259
|
+
}
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
/**
|
|
1263
|
+
*
|
|
1264
|
+
* 将查询条件包起来,如果条件内容不为空,则自动添加WHERE,同时将第一个条件的and、or替换为空
|
|
1265
|
+
* 例如:
|
|
1266
|
+
* {{#whereTag}}
|
|
1267
|
+
* and name = 1
|
|
1268
|
+
* and page = 2
|
|
1269
|
+
* {{/whereTag}}
|
|
1270
|
+
* 输出
|
|
1271
|
+
* where name = 1 and page = 2
|
|
1272
|
+
* @returns
|
|
1273
|
+
* @memberof Build
|
|
1274
|
+
*/
|
|
1275
|
+
where() {
|
|
1276
|
+
return (text, render) => {
|
|
1277
|
+
let data = render(text).trim();
|
|
1278
|
+
if (data) {
|
|
1279
|
+
data = data.replace(/and|or/i, '');
|
|
1280
|
+
return ` WHERE ${data} `;
|
|
1281
|
+
}
|
|
1282
|
+
else {
|
|
1283
|
+
return '';
|
|
1284
|
+
}
|
|
1285
|
+
};
|
|
1286
|
+
}
|
|
1287
|
+
/**
|
|
1288
|
+
* ```
|
|
1289
|
+
* SELECT
|
|
1290
|
+
* {{#hump}}
|
|
1291
|
+
* a.event_id, a.event_name eventName
|
|
1292
|
+
* {{/hump}}
|
|
1293
|
+
* FROM...
|
|
1294
|
+
* ```
|
|
1295
|
+
* 编译后:
|
|
1296
|
+
* ```
|
|
1297
|
+
* SELECT
|
|
1298
|
+
* a.event_id eventId, a.event_name eventName
|
|
1299
|
+
* FROM...
|
|
1300
|
+
* ```
|
|
1301
|
+
*/
|
|
1302
|
+
hump() {
|
|
1303
|
+
return (text, render) => {
|
|
1304
|
+
let data = render(text).trim();
|
|
1305
|
+
const datas = data.split(',');
|
|
1306
|
+
for (let i = 0; i < datas.length; i++) {
|
|
1307
|
+
if (datas[i]?.match(/\s|\t/) === null) {
|
|
1308
|
+
datas[i] = `${datas[i]} ${datas[i].replace(/[a-zA-Z0-9]+\./, '').replace(/_([a-z])/g, (a, b, c) => b.toUpperCase())}`;
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
return ` ${datas.join(',')} `;
|
|
1312
|
+
};
|
|
1313
|
+
}
|
|
1314
|
+
/**
|
|
1315
|
+
* 删除第一个and、or
|
|
1316
|
+
* 删除最后一个,
|
|
1317
|
+
* 删除最后一个;
|
|
1318
|
+
* @memberof Build
|
|
1319
|
+
*/
|
|
1320
|
+
trim() {
|
|
1321
|
+
return (text, render) => {
|
|
1322
|
+
let data = render(text);
|
|
1323
|
+
data = data.trim();
|
|
1324
|
+
if (data) {
|
|
1325
|
+
data = data.replace(/(^and\s)|(^or\s)|(,$)|(;$)/i, '');
|
|
1326
|
+
return data;
|
|
1327
|
+
}
|
|
1328
|
+
else {
|
|
1329
|
+
return '';
|
|
1330
|
+
}
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* 分页时将排序部分代码用此函数包起来,可以自动拼接order by
|
|
1335
|
+
* 查询条数时,自动忽略此部分
|
|
1336
|
+
* etc
|
|
1337
|
+
* {{#order}} name desc, age asc {{/order}}
|
|
1338
|
+
* ===
|
|
1339
|
+
* ORDER BY name desc, age asc
|
|
1340
|
+
* @returns
|
|
1341
|
+
* @memberof Build
|
|
1342
|
+
*/
|
|
1343
|
+
order() {
|
|
1344
|
+
return (text, render) => {
|
|
1345
|
+
if (this.isCount === true || this.isSum === true) {
|
|
1346
|
+
return '';
|
|
1347
|
+
}
|
|
1348
|
+
else {
|
|
1349
|
+
const orderBy = new Array();
|
|
1350
|
+
if (this.orderBy) {
|
|
1351
|
+
orderBy.push(this.orderBy);
|
|
1352
|
+
}
|
|
1353
|
+
const renderOrder = render(text);
|
|
1354
|
+
if (/\S/.test(renderOrder)) {
|
|
1355
|
+
orderBy.push(renderOrder);
|
|
1356
|
+
}
|
|
1357
|
+
return orderBy.length > 0 ? ` ORDER BY ${orderBy.join(',')} ` : '';
|
|
1358
|
+
}
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
*
|
|
1363
|
+
* 分页时将分组部分代码用此函数包起来,可以自动拼接GROUP BY
|
|
1364
|
+
* 当分页时、汇总时,自动忽略此部分
|
|
1365
|
+
* etc
|
|
1366
|
+
* {{#between}} name, age {{/between}}
|
|
1367
|
+
* ===
|
|
1368
|
+
* group by name.age
|
|
1369
|
+
* @returns
|
|
1370
|
+
* @memberof Build
|
|
1371
|
+
*/
|
|
1372
|
+
group() {
|
|
1373
|
+
return (text, render) => {
|
|
1374
|
+
if (this.isCount === true || this.isSum === true) {
|
|
1375
|
+
return '';
|
|
1376
|
+
}
|
|
1377
|
+
else {
|
|
1378
|
+
const groupBy = render(text) || '';
|
|
1379
|
+
return /\S/.test(groupBy) ? ` GROUP BY ${groupBy} ` : '';
|
|
1380
|
+
}
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
*
|
|
1385
|
+
* beetween and
|
|
1386
|
+
* etc.
|
|
1387
|
+
* {{#between}} AND t.createtime | ({{createtime}}) {{/between}}
|
|
1388
|
+
* createtime: 1,2
|
|
1389
|
+
* ===
|
|
1390
|
+
* AND t.createtime BETWEEN 1 AND 2
|
|
1391
|
+
* @returns
|
|
1392
|
+
* @memberof Build
|
|
1393
|
+
*/
|
|
1394
|
+
between() {
|
|
1395
|
+
return (text, render) => {
|
|
1396
|
+
const result = render(text);
|
|
1397
|
+
if (/\(([\w\W]+)\)/.exec(result)) {
|
|
1398
|
+
return render(text).replace(/\(([\w\W]+)\)/, (a, b) => {
|
|
1399
|
+
if (a && b) {
|
|
1400
|
+
const xx = b.split(',');
|
|
1401
|
+
return `'${xx[0]}' AND '${xx[1]}'`;
|
|
1402
|
+
}
|
|
1403
|
+
else {
|
|
1404
|
+
return '';
|
|
1405
|
+
}
|
|
1406
|
+
}).replace(/\|/, ' BETWEEN ');
|
|
1407
|
+
}
|
|
1408
|
+
else {
|
|
1409
|
+
return '';
|
|
1410
|
+
}
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
*
|
|
1415
|
+
* 距离计算,单位米
|
|
1416
|
+
* etc
|
|
1417
|
+
* {{#distance}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distance}}
|
|
1418
|
+
* ===
|
|
1419
|
+
* ROUND(ST_DISTANCE(POINT(longitude1, latitude1), POINT({{longitude}}, {{latitude}}))*111195, 2)
|
|
1420
|
+
* 可根据需求自行将数据转换为千米,例如
|
|
1421
|
+
* {{#distance}} (t.longitude, t.latitude), ({{longitude}}, {{latitude}}) {{/distance}} / 1000
|
|
1422
|
+
* @returns
|
|
1423
|
+
* @memberof Build
|
|
1424
|
+
*/
|
|
1425
|
+
distance() {
|
|
1426
|
+
return (text, render) => {
|
|
1427
|
+
const result = render(text);
|
|
1428
|
+
if (/\(([^()]+)\)/.exec(result)) {
|
|
1429
|
+
let index = 0;
|
|
1430
|
+
return render(text).replace(/\(([^()]+)\)/g, (a, b) => {
|
|
1431
|
+
if (a && b) {
|
|
1432
|
+
const xx = b.split(',');
|
|
1433
|
+
if (index === 0) {
|
|
1434
|
+
index++;
|
|
1435
|
+
return ` ROUND(ST_DISTANCE(POINT(${xx[0]}, ${xx[1]}) `;
|
|
1436
|
+
}
|
|
1437
|
+
else {
|
|
1438
|
+
return ` POINT(${xx[0]}, ${xx[1]}))*111195, 2)`;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
else {
|
|
1442
|
+
return '';
|
|
1443
|
+
}
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
else {
|
|
1447
|
+
return '';
|
|
1448
|
+
}
|
|
1449
|
+
};
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* * PROBLEM_TYPE = 枚举名
|
|
1453
|
+
* * t.problemtype = 列名
|
|
1454
|
+
*
|
|
1455
|
+
* ```
|
|
1456
|
+
* {{#enumTag}} PROBLEM_TYPE(t.problemtype) {{/enumTag}}
|
|
1457
|
+
* ```
|
|
1458
|
+
*/
|
|
1459
|
+
enum() {
|
|
1460
|
+
return (text) => {
|
|
1461
|
+
const matchs = text.match(/([a-zA-Z_]+)\(([^()]+)\)/);
|
|
1462
|
+
if (matchs) {
|
|
1463
|
+
const [_a, MapName, Column] = matchs;
|
|
1464
|
+
if (MapName && Column) {
|
|
1465
|
+
const map = globalThis[_enums].GlobalMap[MapName.trim()];
|
|
1466
|
+
if (map) {
|
|
1467
|
+
return ` CASE
|
|
1468
|
+
${Object.entries(map).map(([k, v]) => `WHEN ${Column} = '${k}' THEN '${v}'`).join(' ')}
|
|
1469
|
+
END `;
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
return "''";
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
Build.page = 'COUNT(1) zccw1986 ';
|
|
1478
|
+
function replaceCdata(rawText) {
|
|
1479
|
+
var cdataRegex = new RegExp('(<!\\[CDATA\\[)([\\s\\S]*?)(\\]\\]>)', 'g');
|
|
1480
|
+
var matches = rawText.match(cdataRegex);
|
|
1481
|
+
if (matches != null && matches.length > 0) {
|
|
1482
|
+
for (var z = 0; z < matches.length; z++) {
|
|
1483
|
+
var regex = new RegExp('(<!\\[CDATA\\[)([\\s\\S]*?)(\\]\\]>)', 'g');
|
|
1484
|
+
var m = regex.exec(matches[z]);
|
|
1485
|
+
var cdataText = m[2];
|
|
1486
|
+
cdataText = cdataText.replace(/\&/g, '&');
|
|
1487
|
+
cdataText = cdataText.replace(/\</g, '<');
|
|
1488
|
+
cdataText = cdataText.replace(/\>/g, '>');
|
|
1489
|
+
cdataText = cdataText.replace(/\"/g, '"');
|
|
1490
|
+
rawText = rawText.replace(m[0], cdataText);
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
return rawText;
|
|
1494
|
+
}
|
|
1495
|
+
function _flatData(result, i, length, keys, V) {
|
|
1496
|
+
var _f;
|
|
1497
|
+
const key = keys[i];
|
|
1498
|
+
if (i < length) {
|
|
1499
|
+
result[_f = key] ?? (result[_f] = {});
|
|
1500
|
+
i++;
|
|
1501
|
+
_flatData(result[key], i, length, keys, V);
|
|
1502
|
+
}
|
|
1503
|
+
else {
|
|
1504
|
+
result[key] = V;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
/**
|
|
1508
|
+
* ifUndefined默认是MapperIfUndefined.Skip
|
|
1509
|
+
*/
|
|
1510
|
+
export function flatData(options) {
|
|
1511
|
+
if (typeof options.mapper === 'string') {
|
|
1512
|
+
const name = options.mapper;
|
|
1513
|
+
options.mapper = globalThis[_resultMap][name];
|
|
1514
|
+
Throw.if(!options.mapper, `not found mapper!${name}`);
|
|
1515
|
+
}
|
|
1516
|
+
options.mapperIfUndefined ?? (options.mapperIfUndefined = MapperIfUndefined.Skip);
|
|
1517
|
+
options.mapper = options.mapper;
|
|
1518
|
+
const result = {};
|
|
1519
|
+
for (const [columnName, keys, def] of options.mapper) {
|
|
1520
|
+
let V = options.data[columnName];
|
|
1521
|
+
if (V === undefined) {
|
|
1522
|
+
if (options.mapperIfUndefined === MapperIfUndefined.Null) {
|
|
1523
|
+
V = null;
|
|
1524
|
+
}
|
|
1525
|
+
else if (options.mapperIfUndefined === MapperIfUndefined.Zero) {
|
|
1526
|
+
V = 0;
|
|
1527
|
+
}
|
|
1528
|
+
else if (options.mapperIfUndefined === MapperIfUndefined.EmptyString) {
|
|
1529
|
+
V = '';
|
|
1530
|
+
}
|
|
1531
|
+
else if (def !== undefined) {
|
|
1532
|
+
V = def;
|
|
1533
|
+
}
|
|
1534
|
+
else {
|
|
1535
|
+
continue;
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
_flatData(result, 0, keys.length - 1, keys, V);
|
|
1539
|
+
}
|
|
1540
|
+
return result;
|
|
1541
|
+
}
|
|
1542
|
+
export class SqlCache {
|
|
1543
|
+
constructor() {
|
|
1544
|
+
this.sqlMap = {};
|
|
1545
|
+
this.sqlFNMap = {};
|
|
1546
|
+
}
|
|
1547
|
+
async _read(jsMode, sqlDir, queryTypes, rootName) {
|
|
1548
|
+
const sqlFis = globalThis[_fs].readdirSync(sqlDir);
|
|
1549
|
+
for (const modeName of sqlFis) {
|
|
1550
|
+
const file = globalThis[_path].join(sqlDir, modeName);
|
|
1551
|
+
const stat = globalThis[_fs].statSync(file);
|
|
1552
|
+
if (stat.isDirectory()) {
|
|
1553
|
+
await this._read(jsMode, file, queryTypes, modeName);
|
|
1554
|
+
}
|
|
1555
|
+
else {
|
|
1556
|
+
const extname = globalThis[_path].extname(modeName);
|
|
1557
|
+
const name = globalThis[_path].basename(modeName, extname);
|
|
1558
|
+
let ct = 0;
|
|
1559
|
+
if (extname === '.mu') {
|
|
1560
|
+
logger.debug(`sql: ${file} start explain!`);
|
|
1561
|
+
const parser = new MUParser(rootName || name, globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString());
|
|
1562
|
+
let source = parser.next();
|
|
1563
|
+
while (source != null) {
|
|
1564
|
+
ct++;
|
|
1565
|
+
this.sqlMap[source[0]] = source[1];
|
|
1566
|
+
logger.debug(`sql: ${source[0]} found!`);
|
|
1567
|
+
source = parser.next();
|
|
1568
|
+
}
|
|
1569
|
+
logger.debug(`sql: ${file} explain over[${ct}]!`);
|
|
1570
|
+
}
|
|
1571
|
+
else if (jsMode === true && extname === '.js') {
|
|
1572
|
+
logger.debug(`sql: ${file} start explain!`);
|
|
1573
|
+
const obj = (await import(globalThis[_path].join(sqlDir, modeName))).default;
|
|
1574
|
+
for (const [key, fn] of Object.entries(obj)) {
|
|
1575
|
+
ct++;
|
|
1576
|
+
this.sqlMap[`${rootName || name}.${String(key)}`] = fn;
|
|
1577
|
+
}
|
|
1578
|
+
logger.debug(`sql: ${file} explain over[${ct}]!`);
|
|
1579
|
+
}
|
|
1580
|
+
else if (extname === '.xml') {
|
|
1581
|
+
logger.debug(`sql: ${file} start explain!`);
|
|
1582
|
+
const root = HTML.parse(replaceCdata(globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString()))[0];
|
|
1583
|
+
if (root) {
|
|
1584
|
+
const mappers = root.children;
|
|
1585
|
+
for (const mapper of mappers) {
|
|
1586
|
+
if (mapper.type === 'tag' && mapper.name === 'mapper') {
|
|
1587
|
+
for (const am of mapper.children) {
|
|
1588
|
+
if (am.type === 'tag') {
|
|
1589
|
+
Throw.if(!queryTypes.includes(am.name), `${rootName} ${name}错误,${am.name}不支持!`);
|
|
1590
|
+
am.id = am.attrs['id'];
|
|
1591
|
+
Throw.if(!am.id, `${rootName} ${name}错误,没有为此块设置id:${am}`);
|
|
1592
|
+
if (am.name === 'resultMap') {
|
|
1593
|
+
ct++;
|
|
1594
|
+
globalThis[_resultMap] ?? (globalThis[_resultMap] = {});
|
|
1595
|
+
const keys = [];
|
|
1596
|
+
this.readResultMap(am.children, keys, []);
|
|
1597
|
+
globalThis[_resultMap][am.id] = keys;
|
|
1598
|
+
logger.debug(`sql_resultMap: ${am.id} found!`);
|
|
1599
|
+
}
|
|
1600
|
+
else {
|
|
1601
|
+
this.sqlMap[`${rootName || name}.${am.id}`] = am.children;
|
|
1602
|
+
if (am.attrs['resultMap']) {
|
|
1603
|
+
globalThis[_resultMap_SQLID][`${rootName || name}.${am.id}`] = am.attrs['resultMap'];
|
|
1604
|
+
logger.debug(`sql: autoMapper: ${rootName || name}.${am.id}-${am.attrs['resultMap']}`);
|
|
1605
|
+
}
|
|
1606
|
+
logger.debug(`sql: ${rootName || name}.${am.id} found!`);
|
|
1607
|
+
ct++;
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
logger.debug(`sql: ${file} explain over[${ct}]!`);
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
*
|
|
1621
|
+
* ```
|
|
1622
|
+
// 第一个元素=列名,第二个元素是属性路径,
|
|
1623
|
+
[
|
|
1624
|
+
['dit_id', ['id']], // 列名ditid,对应属性id
|
|
1625
|
+
['event_id', ['eventMainInfo', 'id']] // 列名event_id对应属性eventMainInfo.id
|
|
1626
|
+
]
|
|
1627
|
+
* ```
|
|
1628
|
+
* @param am
|
|
1629
|
+
* @param keys
|
|
1630
|
+
*/
|
|
1631
|
+
readResultMap(ams, keys, key) {
|
|
1632
|
+
for (const am of ams) {
|
|
1633
|
+
if (am.type === 'tag') {
|
|
1634
|
+
if (am.name === 'result' || am.name === 'id') {
|
|
1635
|
+
keys.push([am.attrs['column'], [...key, am.attrs['property']]]);
|
|
1636
|
+
}
|
|
1637
|
+
else {
|
|
1638
|
+
this.readResultMap(am.children, keys, [...key, am.attrs['property']]);
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
async init(options) {
|
|
1644
|
+
if (options.sqlMap) {
|
|
1645
|
+
this.sqlMap = options.sqlMap;
|
|
1646
|
+
}
|
|
1647
|
+
const queryTypes = ['sql', 'select', 'insert', 'update', 'delete', 'resultMap'];
|
|
1648
|
+
if (options.sqlDir) {
|
|
1649
|
+
await this._read(options.jsMode === true, options.sqlDir, queryTypes, '');
|
|
1650
|
+
}
|
|
1651
|
+
if (options.sqlFNMap) {
|
|
1652
|
+
this.sqlFNMap = options.sqlFNMap;
|
|
1653
|
+
}
|
|
1654
|
+
if (options.sqlFNDir) {
|
|
1655
|
+
const sqlFis = globalThis[_fs].readdirSync(options.sqlDir);
|
|
1656
|
+
for (const modeName of sqlFis) {
|
|
1657
|
+
const extname = globalThis[_path].extname(modeName);
|
|
1658
|
+
const name = globalThis[_path].basename(modeName, extname);
|
|
1659
|
+
const file = globalThis[_path].join(options.sqlDir, modeName);
|
|
1660
|
+
if (extname === 'mu') {
|
|
1661
|
+
this.sqlFNMap[name] = globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString();
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
if (options.sqlMapperMap) {
|
|
1666
|
+
globalThis[_resultMap] = options.sqlFNMap;
|
|
1667
|
+
}
|
|
1668
|
+
if (options.sqlMapperDir) {
|
|
1669
|
+
const sqlFis = globalThis[_fs].readdirSync(options.sqlDir);
|
|
1670
|
+
globalThis[_resultMap] ?? (globalThis[_resultMap] = {});
|
|
1671
|
+
for (const modeName of sqlFis) {
|
|
1672
|
+
const extname = globalThis[_path].extname(modeName);
|
|
1673
|
+
const name = globalThis[_path].basename(modeName, extname);
|
|
1674
|
+
const file = globalThis[_path].join(options.sqlDir, modeName);
|
|
1675
|
+
if (extname === 'json') {
|
|
1676
|
+
globalThis[_resultMap][name] = JSON.parse(globalThis[_fs].readFileSync(file, { encoding: 'utf-8' }).toString());
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
load(sqlids, options) {
|
|
1682
|
+
let sqlSource;
|
|
1683
|
+
for (const sqlid of sqlids) {
|
|
1684
|
+
sqlSource = this.sqlMap[sqlid];
|
|
1685
|
+
if (sqlSource) {
|
|
1686
|
+
break;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
const matchSqlid = sqlids.map(i => i.split('.')[0]);
|
|
1690
|
+
Throw.if(!sqlSource, `指定的语句${sqlids.join('|')}不存在!`);
|
|
1691
|
+
const buildParam = new Build(options.isCount === true, options.isSum === true, options);
|
|
1692
|
+
if (typeof sqlSource === 'function') {
|
|
1693
|
+
const _sql = sqlSource(options);
|
|
1694
|
+
return mustache.render(_sql, buildParam, this.sqlFNMap);
|
|
1695
|
+
}
|
|
1696
|
+
else if (typeof sqlSource === 'string') {
|
|
1697
|
+
return mustache.render(sqlSource, buildParam, this.sqlFNMap);
|
|
1698
|
+
}
|
|
1699
|
+
else if (typeof sqlSource === 'object') {
|
|
1700
|
+
const _sql = convert(sqlSource, options, matchSqlid, this.sqlMap);
|
|
1701
|
+
return mustache.render(_sql, buildParam, this.sqlFNMap);
|
|
1702
|
+
}
|
|
1703
|
+
return '';
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
// #endregion
|
|
1707
|
+
/**
|
|
1708
|
+
|
|
1709
|
+
## 所有service中内置方法定义规则
|
|
1710
|
+
** 方法第一个参数必须是 sync: SyncMode
|
|
1711
|
+
** 方法最后一个参数必须是 option
|
|
1712
|
+
|
|
1713
|
+
## sync 表示是否是同步方法
|
|
1714
|
+
|
|
1715
|
+
因为mysql是异步、sqlite是同步,导致必须通过一个标识来区分,否则将必须为两种数据库设置不同的service,失去了意义
|
|
1716
|
+
|
|
1717
|
+
## option 额外控制参数
|
|
1718
|
+
|
|
1719
|
+
## length
|
|
1720
|
+
方法的参数数量
|
|
1721
|
+
*/
|
|
1722
|
+
function P(skipConn = false) {
|
|
1723
|
+
return (_target, propertyKey, descriptor) => {
|
|
1724
|
+
const fn = descriptor.value;
|
|
1725
|
+
descriptor.value = function (...args) {
|
|
1726
|
+
let needRealseConn = true;
|
|
1727
|
+
const startTime = +new Date();
|
|
1728
|
+
// option
|
|
1729
|
+
const option = args[0] = Object.assign({}, globalThis[_GlobalSqlOption], this[_SqlOption], args[0]);
|
|
1730
|
+
option.sync ?? (option.sync = SyncMode.Async);
|
|
1731
|
+
option.tableName = option?.tableName ?? this[_tableName];
|
|
1732
|
+
option.dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
|
|
1733
|
+
option.dbType = this[_dbType] ?? globalThis[_GlobalSqlOption].dbType ?? DBType.Mysql;
|
|
1734
|
+
option.dao = globalThis[_dao][option.dbType][option.dbName];
|
|
1735
|
+
if (option.dbType === DBType.Sqlite) {
|
|
1736
|
+
if (!option.dao) {
|
|
1737
|
+
const db = new Sqlite(new globalThis[_GlobalSqlOption].BetterSqlite3(option.dbName, { fileMustExist: false }));
|
|
1738
|
+
if (globalThis[_dao][option.dbType][_primaryDB] === undefined) {
|
|
1739
|
+
globalThis[_dao][option.dbType][_primaryDB] = db;
|
|
1740
|
+
}
|
|
1741
|
+
globalThis[_dao][option.dbType][option.dbName] = db;
|
|
1742
|
+
option.dao = db;
|
|
1743
|
+
}
|
|
1744
|
+
Throw.if(option.sync === SyncMode.Async, 'sqlite can not Async!');
|
|
1745
|
+
// 连接共享
|
|
1746
|
+
if (skipConn === false && !option.conn) {
|
|
1747
|
+
option.conn = option.dao.createConnection(SyncMode.Sync);
|
|
1748
|
+
}
|
|
1749
|
+
else {
|
|
1750
|
+
needRealseConn = false;
|
|
1751
|
+
}
|
|
1752
|
+
try {
|
|
1753
|
+
const result = fn.call(this, ...args);
|
|
1754
|
+
logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
|
|
1755
|
+
return result;
|
|
1756
|
+
}
|
|
1757
|
+
catch (error) {
|
|
1758
|
+
try {
|
|
1759
|
+
console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
|
|
1760
|
+
}
|
|
1761
|
+
catch (error) {
|
|
1762
|
+
}
|
|
1763
|
+
throw error;
|
|
1764
|
+
}
|
|
1765
|
+
finally {
|
|
1766
|
+
if (needRealseConn && option && option.conn) {
|
|
1767
|
+
try {
|
|
1768
|
+
option.conn.realse(SyncMode.Sync);
|
|
1769
|
+
}
|
|
1770
|
+
catch (error) {
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
else if (option.dbType === DBType.SqliteRemote) {
|
|
1776
|
+
if (!option.dao) {
|
|
1777
|
+
globalThis[_GlobalSqlOption].SqliteRemote.service.initDB(option.dbName);
|
|
1778
|
+
const db = new SqliteRemote(globalThis[_GlobalSqlOption].SqliteRemote.service, option.dbName);
|
|
1779
|
+
if (globalThis[_dao][option.dbType][_primaryDB] === undefined) {
|
|
1780
|
+
globalThis[_dao][option.dbType][_primaryDB] = db;
|
|
1781
|
+
}
|
|
1782
|
+
globalThis[_dao][option.dbType][option.dbName] = db;
|
|
1783
|
+
option.dao = db;
|
|
1784
|
+
}
|
|
1785
|
+
Throw.if(option.sync === SyncMode.Sync, 'SqliteRemote remote can not sync!');
|
|
1786
|
+
return new Promise(async (resolve, reject) => {
|
|
1787
|
+
// 连接共享
|
|
1788
|
+
if (skipConn === false && !option.conn) {
|
|
1789
|
+
(option).conn = await option.dao.createConnection(SyncMode.Async);
|
|
1790
|
+
}
|
|
1791
|
+
else {
|
|
1792
|
+
needRealseConn = false;
|
|
1793
|
+
}
|
|
1794
|
+
try {
|
|
1795
|
+
const result = await fn.call(this, ...args);
|
|
1796
|
+
logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
|
|
1797
|
+
resolve(result);
|
|
1798
|
+
}
|
|
1799
|
+
catch (error) {
|
|
1800
|
+
console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
|
|
1801
|
+
reject(error);
|
|
1802
|
+
}
|
|
1803
|
+
finally {
|
|
1804
|
+
if (needRealseConn && option && option.conn) {
|
|
1805
|
+
try {
|
|
1806
|
+
option.conn.realse(SyncMode.Sync);
|
|
1807
|
+
}
|
|
1808
|
+
catch (error) {
|
|
1809
|
+
}
|
|
1810
|
+
}
|
|
1811
|
+
}
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
else if (option.dbType === DBType.Mysql) {
|
|
1815
|
+
Throw.if(!option.dao, `not found db:${String(option.dbName)}(${option.dbType})`);
|
|
1816
|
+
return new Promise(async (resolve, reject) => {
|
|
1817
|
+
try {
|
|
1818
|
+
// 连接共享
|
|
1819
|
+
if (skipConn === false && !option.conn) {
|
|
1820
|
+
(option).conn = await option.dao.createConnection(SyncMode.Async);
|
|
1821
|
+
}
|
|
1822
|
+
else {
|
|
1823
|
+
needRealseConn = false;
|
|
1824
|
+
}
|
|
1825
|
+
const result = await fn.call(this, ...args);
|
|
1826
|
+
logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
|
|
1827
|
+
resolve(result);
|
|
1828
|
+
}
|
|
1829
|
+
catch (error) {
|
|
1830
|
+
console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
|
|
1831
|
+
reject(error);
|
|
1832
|
+
}
|
|
1833
|
+
finally {
|
|
1834
|
+
if (needRealseConn && option && option.conn) {
|
|
1835
|
+
try {
|
|
1836
|
+
option.conn.realse(SyncMode.Sync);
|
|
1837
|
+
}
|
|
1838
|
+
catch (error) {
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
});
|
|
1843
|
+
}
|
|
1844
|
+
else if (option.dbType === DBType.Postgresql) {
|
|
1845
|
+
Throw.if(!option.dao, `not found db:${String(option.dbName)}(${option.dbType})`);
|
|
1846
|
+
return new Promise(async (resolve, reject) => {
|
|
1847
|
+
try {
|
|
1848
|
+
// 连接共享
|
|
1849
|
+
if (skipConn === false && !option.conn) {
|
|
1850
|
+
(option).conn = await option.dao.createConnection(SyncMode.Async);
|
|
1851
|
+
}
|
|
1852
|
+
else {
|
|
1853
|
+
needRealseConn = false;
|
|
1854
|
+
}
|
|
1855
|
+
const result = await fn.call(this, ...args);
|
|
1856
|
+
logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
|
|
1857
|
+
resolve(result);
|
|
1858
|
+
}
|
|
1859
|
+
catch (error) {
|
|
1860
|
+
console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
|
|
1861
|
+
reject(error);
|
|
1862
|
+
}
|
|
1863
|
+
finally {
|
|
1864
|
+
if (needRealseConn && option && option.conn) {
|
|
1865
|
+
try {
|
|
1866
|
+
option.conn.realse(SyncMode.Sync);
|
|
1867
|
+
}
|
|
1868
|
+
catch (error) {
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
});
|
|
1873
|
+
}
|
|
1874
|
+
};
|
|
1875
|
+
};
|
|
1876
|
+
}
|
|
1877
|
+
const FieldFilter = (K, V, def, uuidColumn, option) => {
|
|
1878
|
+
let ret = 0;
|
|
1879
|
+
// 如果是插入操作且字段是UUID,则不进行空值检查
|
|
1880
|
+
// 只有在非插入或者非UUID时,进行空置检查
|
|
1881
|
+
if (option?.insert === true && uuidColumn === true) {
|
|
1882
|
+
ret = 1;
|
|
1883
|
+
if (V === undefined || emptyString(`${V ?? ''}`)) {
|
|
1884
|
+
V = null;
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
else {
|
|
1888
|
+
if (V === null) {
|
|
1889
|
+
if (option?.skipNull !== true) {
|
|
1890
|
+
ret = 1;
|
|
1891
|
+
V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : null;
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
else if (V === undefined) {
|
|
1895
|
+
if (option?.skipUndefined !== true) {
|
|
1896
|
+
ret = 1;
|
|
1897
|
+
V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : null;
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
else if (emptyString(`${V ?? ''}`)) {
|
|
1901
|
+
if (option?.skipEmptyString !== true) {
|
|
1902
|
+
ret = 1;
|
|
1903
|
+
V = option?.insert === true && def && def.hasOwnProperty(K) ? def[K] : '';
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
else {
|
|
1907
|
+
ret = 1;
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
if (ret === 1) {
|
|
1911
|
+
option?.finalColumns?.add(K);
|
|
1912
|
+
option?.tempColumns?.push(K);
|
|
1913
|
+
}
|
|
1914
|
+
return [ret, V];
|
|
1915
|
+
};
|
|
1916
|
+
const formatDialects = {
|
|
1917
|
+
[DBType.Mysql]: mysql,
|
|
1918
|
+
[DBType.Sqlite]: sqlite,
|
|
1919
|
+
[DBType.SqliteRemote]: sqlite,
|
|
1920
|
+
[DBType.Postgresql]: postgresql,
|
|
1921
|
+
};
|
|
1922
|
+
export const DB = (config) => {
|
|
1923
|
+
return function (constructor) {
|
|
1924
|
+
var _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
|
|
1925
|
+
const __ids = Reflect.getMetadata(_ids, config.clz.prototype) || new Array;
|
|
1926
|
+
const __logicIds = Reflect.getMetadata(_logicIds, config.clz.prototype) || new Array;
|
|
1927
|
+
const __fields = Reflect.getMetadata(_fields, config.clz.prototype);
|
|
1928
|
+
const __columns = Reflect.getMetadata(_columns, config.clz.prototype);
|
|
1929
|
+
const __columnsNoId = Reflect.getMetadata(_columnsNoId, config.clz.prototype);
|
|
1930
|
+
const __stateFileName = Reflect.getMetadata(_stateFileName, config.clz.prototype);
|
|
1931
|
+
const __deleteState = Reflect.getMetadata(_deleteState, config.clz.prototype);
|
|
1932
|
+
const __index = Reflect.getMetadata(_index, config.clz.prototype);
|
|
1933
|
+
const __def = Reflect.getMetadata(_def, config.clz.prototype);
|
|
1934
|
+
const __dbType = config.dbType;
|
|
1935
|
+
const className = config.tableName?.replace(/_(\w)/g, (a, b) => b.toUpperCase());
|
|
1936
|
+
const ClassName = className?.replace(/\w/, (v) => v.toUpperCase());
|
|
1937
|
+
const vueName = config.tableName?.replace(/_/g, '-');
|
|
1938
|
+
return _0 = class extends constructor {
|
|
1939
|
+
constructor() {
|
|
1940
|
+
super(...arguments);
|
|
1941
|
+
this[_f] = config.tableName;
|
|
1942
|
+
this[_g] = className;
|
|
1943
|
+
this[_h] = ClassName;
|
|
1944
|
+
this[_j] = vueName;
|
|
1945
|
+
this[_k] = config.dbName;
|
|
1946
|
+
this[_l] = __dbType;
|
|
1947
|
+
this[_m] = config.sqliteVersion;
|
|
1948
|
+
this[_o] = Object.assign({}, _defOption, config);
|
|
1949
|
+
this[_p] = __ids;
|
|
1950
|
+
this[_q] = __logicIds;
|
|
1951
|
+
this[_r] = __fields;
|
|
1952
|
+
this[_s] = __columns;
|
|
1953
|
+
this[_t] = __columnsNoId;
|
|
1954
|
+
this[_u] = __index;
|
|
1955
|
+
this[_v] = __def;
|
|
1956
|
+
this[_w] = config.comment;
|
|
1957
|
+
this[_x] = __stateFileName;
|
|
1958
|
+
this[_y] = __deleteState;
|
|
1959
|
+
this[_z] = (data, option) => {
|
|
1960
|
+
return Object.fromEntries(iterate(option?.skipId === true ? __columnsNoId : __columns)
|
|
1961
|
+
.map(K => [K, FieldFilter(K, data[K], __def, __fields[K].uuid === true || __fields[K].uuidShort === true, option)])
|
|
1962
|
+
.filter(data => {
|
|
1963
|
+
if (data[1][0] === 1) {
|
|
1964
|
+
if (__fields[data[0]].Data2SQL) {
|
|
1965
|
+
data[1][1] = __fields[data[0]].Data2SQL(data[1][1]);
|
|
1966
|
+
}
|
|
1967
|
+
if (option?.onFieldExists) {
|
|
1968
|
+
option.onFieldExists(data[0], data[1][1]);
|
|
1969
|
+
}
|
|
1970
|
+
return true;
|
|
1971
|
+
}
|
|
1972
|
+
else {
|
|
1973
|
+
return false;
|
|
1974
|
+
}
|
|
1975
|
+
})
|
|
1976
|
+
.map(data => [data[0], data[1][1]])
|
|
1977
|
+
.toArray());
|
|
1978
|
+
};
|
|
1979
|
+
}
|
|
1980
|
+
},
|
|
1981
|
+
_f = _tableName,
|
|
1982
|
+
_g = _className,
|
|
1983
|
+
_h = _ClassName,
|
|
1984
|
+
_j = _vueName,
|
|
1985
|
+
_k = _daoDBName,
|
|
1986
|
+
_l = _dbType,
|
|
1987
|
+
_m = _sqlite_version,
|
|
1988
|
+
_o = _SqlOption,
|
|
1989
|
+
_p = _ids,
|
|
1990
|
+
_q = _logicIds,
|
|
1991
|
+
_r = _fields,
|
|
1992
|
+
_s = _columns,
|
|
1993
|
+
_t = _columnsNoId,
|
|
1994
|
+
_u = _index,
|
|
1995
|
+
_v = _def,
|
|
1996
|
+
_w = _comment,
|
|
1997
|
+
_x = _stateFileName,
|
|
1998
|
+
_y = _deleteState,
|
|
1999
|
+
_z = _transformer,
|
|
2000
|
+
_0;
|
|
2001
|
+
};
|
|
2002
|
+
};
|
|
2003
|
+
/**
|
|
2004
|
+
js项目中实体类注解替代品,只要确保函数被执行即可,举例:
|
|
2005
|
+
```
|
|
2006
|
+
// 声明一个class
|
|
2007
|
+
export class AmaFuck {}
|
|
2008
|
+
DeclareClass(AmaFuck, [
|
|
2009
|
+
{ type: "String", name: "SellerSKU" },
|
|
2010
|
+
{ type: "String", name: "SellerSKU2" },
|
|
2011
|
+
{ type: "String", name: "site" }
|
|
2012
|
+
]);
|
|
2013
|
+
```
|
|
2014
|
+
*/
|
|
2015
|
+
export function DeclareClass(clz, FieldOptions) {
|
|
2016
|
+
for (const item of FieldOptions) {
|
|
2017
|
+
tslib.__decorate([Field(item)], clz.prototype, item.P, void 0);
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
/**
|
|
2021
|
+
JS项目中,service注解代替,举例:
|
|
2022
|
+
```
|
|
2023
|
+
// 声明一个service,注意这里的let
|
|
2024
|
+
export let AmaService = class AmaService extends SqlService {};
|
|
2025
|
+
AmaService = DeclareService(AmaService, {
|
|
2026
|
+
tableName: "ama_fuck2",
|
|
2027
|
+
clz: AmaFuck,
|
|
2028
|
+
dbType: DBType.Sqlite,
|
|
2029
|
+
sqliteVersion: "0.0.3"
|
|
2030
|
+
});
|
|
2031
|
+
```
|
|
2032
|
+
*/
|
|
2033
|
+
export function DeclareService(clz, config) {
|
|
2034
|
+
return tslib.__decorate([DB(config)], clz);
|
|
2035
|
+
}
|
|
2036
|
+
/**
|
|
2037
|
+
## 数据库服务
|
|
2038
|
+
### 注解DB
|
|
2039
|
+
|
|
2040
|
+
### 泛型 T,同DB注解中的clz
|
|
2041
|
+
** 服务中所有方法默认以该类型为准
|
|
2042
|
+
**
|
|
2043
|
+
|
|
2044
|
+
*/
|
|
2045
|
+
export class SqlService {
|
|
2046
|
+
_insert(datas, option) {
|
|
2047
|
+
const sqls = [];
|
|
2048
|
+
const tableName = option.tableName;
|
|
2049
|
+
switch (option?.mode) {
|
|
2050
|
+
case InsertMode.InsertIfNotExists: {
|
|
2051
|
+
const conditions = option.existConditionOtherThanIds || this[_ids];
|
|
2052
|
+
Throw.if(!conditions, 'not found where condition for insertIfNotExists!');
|
|
2053
|
+
Throw.if(conditions.length === 0, 'insertIfNotExists must have not null where!');
|
|
2054
|
+
const where = iterate(conditions).map(c => `${this[_fields][c]?.C2()} = ?`).join(' AND ');
|
|
2055
|
+
const finalColumns = new Set();
|
|
2056
|
+
const whereColumns = conditions;
|
|
2057
|
+
const params = [];
|
|
2058
|
+
const questMarks = datas
|
|
2059
|
+
.map(data => this[_transformer](data, { ...option, finalColumns, insert: true }))
|
|
2060
|
+
.map(data => {
|
|
2061
|
+
const questMark = new Array();
|
|
2062
|
+
for (const column of finalColumns) {
|
|
2063
|
+
const V = data.hasOwnProperty(column)
|
|
2064
|
+
? data[column]
|
|
2065
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
2066
|
+
? this[_def][column]
|
|
2067
|
+
: null;
|
|
2068
|
+
if (V === null) {
|
|
2069
|
+
const field = this[_fields][column];
|
|
2070
|
+
if (field?.uuid) {
|
|
2071
|
+
switch (option.dbType) {
|
|
2072
|
+
case DBType.Postgresql:
|
|
2073
|
+
questMark.push('gen_random_uuid()');
|
|
2074
|
+
break;
|
|
2075
|
+
default:
|
|
2076
|
+
questMark.push('UUID()');
|
|
2077
|
+
break;
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
else if (field?.uuidShort) {
|
|
2081
|
+
switch (option.dbType) {
|
|
2082
|
+
case DBType.Postgresql:
|
|
2083
|
+
questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
|
|
2084
|
+
break;
|
|
2085
|
+
case DBType.Mysql:
|
|
2086
|
+
questMark.push('UUID_SHORT()');
|
|
2087
|
+
break;
|
|
2088
|
+
default:
|
|
2089
|
+
questMark.push('?');
|
|
2090
|
+
params.push(V);
|
|
2091
|
+
break;
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
else {
|
|
2095
|
+
questMark.push('?');
|
|
2096
|
+
params.push(V);
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
else {
|
|
2100
|
+
questMark.push('?');
|
|
2101
|
+
params.push(V);
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
2104
|
+
for (const column of whereColumns) {
|
|
2105
|
+
params.push(data.hasOwnProperty(column)
|
|
2106
|
+
? data[column]
|
|
2107
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
2108
|
+
? this[_def][column]
|
|
2109
|
+
: null);
|
|
2110
|
+
}
|
|
2111
|
+
return `SELECT ${questMark.join(',')} FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ${tableName} WHERE ${where})`;
|
|
2112
|
+
});
|
|
2113
|
+
const columnNames = iterate(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
|
|
2114
|
+
const sql = formatDialect(`INSERT INTO
|
|
2115
|
+
${tableName}
|
|
2116
|
+
(${columnNames})
|
|
2117
|
+
${questMarks.join(' UNION ALL ')};`, { dialect: formatDialects[option.dbType] });
|
|
2118
|
+
sqls.push({ sql, params });
|
|
2119
|
+
break;
|
|
2120
|
+
}
|
|
2121
|
+
case InsertMode.Replace: {
|
|
2122
|
+
const finalColumns = new Set();
|
|
2123
|
+
const params = [];
|
|
2124
|
+
const questMarks = datas
|
|
2125
|
+
.map(data => this[_transformer](data, { ...option, finalColumns, insert: true }))
|
|
2126
|
+
.map(data => {
|
|
2127
|
+
const questMark = new Array();
|
|
2128
|
+
for (const column of finalColumns) {
|
|
2129
|
+
const V = data.hasOwnProperty(column)
|
|
2130
|
+
? data[column]
|
|
2131
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
2132
|
+
? this[_def][column]
|
|
2133
|
+
: null;
|
|
2134
|
+
if (V === null) {
|
|
2135
|
+
const field = this[_fields][column];
|
|
2136
|
+
if (field?.uuid) {
|
|
2137
|
+
switch (option.dbType) {
|
|
2138
|
+
case DBType.Postgresql:
|
|
2139
|
+
questMark.push('gen_random_uuid()');
|
|
2140
|
+
break;
|
|
2141
|
+
default:
|
|
2142
|
+
questMark.push('UUID()');
|
|
2143
|
+
break;
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
else if (field?.uuidShort) {
|
|
2147
|
+
switch (option.dbType) {
|
|
2148
|
+
case DBType.Postgresql:
|
|
2149
|
+
questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
|
|
2150
|
+
break;
|
|
2151
|
+
case DBType.Mysql:
|
|
2152
|
+
questMark.push('UUID_SHORT()');
|
|
2153
|
+
break;
|
|
2154
|
+
default:
|
|
2155
|
+
questMark.push('?');
|
|
2156
|
+
params.push(V);
|
|
2157
|
+
break;
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
else {
|
|
2161
|
+
questMark.push('?');
|
|
2162
|
+
params.push(V);
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
else {
|
|
2166
|
+
questMark.push('?');
|
|
2167
|
+
params.push(V);
|
|
2168
|
+
}
|
|
2169
|
+
}
|
|
2170
|
+
return `(${questMark.join(',')})`;
|
|
2171
|
+
});
|
|
2172
|
+
const columnNames = iterate(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
|
|
2173
|
+
const sql = formatDialect(`
|
|
2174
|
+
${option.dbType === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
|
|
2175
|
+
${tableName}
|
|
2176
|
+
(${columnNames})
|
|
2177
|
+
VALUES ${questMarks};
|
|
2178
|
+
`, { dialect: formatDialects[option.dbType] });
|
|
2179
|
+
sqls.push({ sql, params });
|
|
2180
|
+
break;
|
|
2181
|
+
}
|
|
2182
|
+
case InsertMode.Insert: {
|
|
2183
|
+
const finalColumns = new Set();
|
|
2184
|
+
const params = [];
|
|
2185
|
+
const questMarks = datas
|
|
2186
|
+
.map(data => this[_transformer](data, { ...option, finalColumns, insert: true }))
|
|
2187
|
+
.map(data => {
|
|
2188
|
+
const questMark = new Array();
|
|
2189
|
+
for (const column of finalColumns) {
|
|
2190
|
+
const V = data.hasOwnProperty(column)
|
|
2191
|
+
? data[column]
|
|
2192
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
2193
|
+
? this[_def][column]
|
|
2194
|
+
: null;
|
|
2195
|
+
if (V === null) {
|
|
2196
|
+
const field = this[_fields][column];
|
|
2197
|
+
if (field?.uuid) {
|
|
2198
|
+
switch (option.dbType) {
|
|
2199
|
+
case DBType.Postgresql:
|
|
2200
|
+
questMark.push('gen_random_uuid()');
|
|
2201
|
+
break;
|
|
2202
|
+
default:
|
|
2203
|
+
questMark.push('UUID()');
|
|
2204
|
+
break;
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
else if (field?.uuidShort) {
|
|
2208
|
+
switch (option.dbType) {
|
|
2209
|
+
case DBType.Postgresql:
|
|
2210
|
+
questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
|
|
2211
|
+
break;
|
|
2212
|
+
case DBType.Mysql:
|
|
2213
|
+
questMark.push('UUID_SHORT()');
|
|
2214
|
+
break;
|
|
2215
|
+
default:
|
|
2216
|
+
questMark.push('?');
|
|
2217
|
+
params.push(V);
|
|
2218
|
+
break;
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
else {
|
|
2222
|
+
questMark.push('?');
|
|
2223
|
+
params.push(V);
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
else {
|
|
2227
|
+
questMark.push('?');
|
|
2228
|
+
params.push(V);
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
return `(${questMark.join(',')})`;
|
|
2232
|
+
});
|
|
2233
|
+
const columnNames = iterate(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
|
|
2234
|
+
const sql = formatDialect(`
|
|
2235
|
+
INSERT INTO
|
|
2236
|
+
${tableName}
|
|
2237
|
+
(${columnNames})
|
|
2238
|
+
VALUES ${questMarks};
|
|
2239
|
+
`, { dialect: formatDialects[option.dbType] });
|
|
2240
|
+
sqls.push({ sql, params });
|
|
2241
|
+
break;
|
|
2242
|
+
}
|
|
2243
|
+
case InsertMode.InsertWithTempTable: {
|
|
2244
|
+
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
2245
|
+
const tableTempESC = tableTemp;
|
|
2246
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2247
|
+
const finalColumns = new Set();
|
|
2248
|
+
const params = [];
|
|
2249
|
+
const questMarks = datas
|
|
2250
|
+
.map(data => this[_transformer](data, { ...option, finalColumns, insert: true }))
|
|
2251
|
+
.map(data => {
|
|
2252
|
+
const questMark = new Array();
|
|
2253
|
+
for (const column of finalColumns) {
|
|
2254
|
+
const V = data.hasOwnProperty(column)
|
|
2255
|
+
? data[column]
|
|
2256
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
2257
|
+
? this[_def][column]
|
|
2258
|
+
: null;
|
|
2259
|
+
if (V === null) {
|
|
2260
|
+
const field = this[_fields][column];
|
|
2261
|
+
if (field?.uuid) {
|
|
2262
|
+
switch (option.dbType) {
|
|
2263
|
+
case DBType.Postgresql:
|
|
2264
|
+
questMark.push('gen_random_uuid()');
|
|
2265
|
+
break;
|
|
2266
|
+
default:
|
|
2267
|
+
questMark.push('UUID()');
|
|
2268
|
+
break;
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
else if (field?.uuidShort) {
|
|
2272
|
+
switch (option.dbType) {
|
|
2273
|
+
case DBType.Postgresql:
|
|
2274
|
+
questMark.push(`encode(uuid_send(gen_random_uuid()::uuid),'base64')`);
|
|
2275
|
+
break;
|
|
2276
|
+
case DBType.Mysql:
|
|
2277
|
+
questMark.push('UUID_SHORT()');
|
|
2278
|
+
break;
|
|
2279
|
+
default:
|
|
2280
|
+
questMark.push('?');
|
|
2281
|
+
params.push(V);
|
|
2282
|
+
break;
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
else {
|
|
2286
|
+
questMark.push('?');
|
|
2287
|
+
params.push(V);
|
|
2288
|
+
}
|
|
2289
|
+
}
|
|
2290
|
+
else {
|
|
2291
|
+
questMark.push('?');
|
|
2292
|
+
params.push(V);
|
|
2293
|
+
}
|
|
2294
|
+
}
|
|
2295
|
+
return `(${questMark.join(',')})`;
|
|
2296
|
+
});
|
|
2297
|
+
const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: Array.from(finalColumns) });
|
|
2298
|
+
sqls.push(..._sqls);
|
|
2299
|
+
const columnNames = iterate(finalColumns).map(i => this[_fields][i]?.C2()).join(',');
|
|
2300
|
+
sqls.push({
|
|
2301
|
+
sql: formatDialect(`
|
|
2302
|
+
INSERT INTO
|
|
2303
|
+
${tableTemp}
|
|
2304
|
+
(${columnNames})
|
|
2305
|
+
VALUES ${questMarks};
|
|
2306
|
+
`, { dialect: formatDialects[option.dbType] }), params
|
|
2307
|
+
});
|
|
2308
|
+
sqls.push({
|
|
2309
|
+
sql: formatDialect(`INSERT INTO ${option.tableName} (${columnNames})
|
|
2310
|
+
SELECT ${columnNames} FROM ${tableTemp};`, { dialect: formatDialects[option.dbType] })
|
|
2311
|
+
});
|
|
2312
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2313
|
+
break;
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
return sqls;
|
|
2317
|
+
}
|
|
2318
|
+
insert(option) {
|
|
2319
|
+
option.mode ?? (option.mode = InsertMode.Insert);
|
|
2320
|
+
const isArray = option.data instanceof Array;
|
|
2321
|
+
const datas = option.data instanceof Array ? option.data : [option.data];
|
|
2322
|
+
if (datas.length === 0)
|
|
2323
|
+
return 0n;
|
|
2324
|
+
if (option.sync === SyncMode.Sync) {
|
|
2325
|
+
const fn = () => {
|
|
2326
|
+
const result = excuteSplit(ExcuteSplitMode.SyncTrust, datas, _data => {
|
|
2327
|
+
const sqls = this._insert(_data, option);
|
|
2328
|
+
let result = 0n;
|
|
2329
|
+
for (const { sql, params } of sqls) {
|
|
2330
|
+
const dd = option.conn.execute(SyncMode.Sync, sql, params);
|
|
2331
|
+
if (dd.insertId) {
|
|
2332
|
+
result += BigInt(dd.insertId);
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
return result;
|
|
2336
|
+
}, { everyLength: option?.every === true ? 1 : option?.maxDeal });
|
|
2337
|
+
if (isArray)
|
|
2338
|
+
return result;
|
|
2339
|
+
else
|
|
2340
|
+
return result[0];
|
|
2341
|
+
};
|
|
2342
|
+
if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2343
|
+
return fn();
|
|
2344
|
+
}
|
|
2345
|
+
else {
|
|
2346
|
+
return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn);
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
else if (isArray) {
|
|
2350
|
+
const fn = async () => {
|
|
2351
|
+
const result = await excuteSplit(ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
|
|
2352
|
+
const sqls = this._insert(_data, option);
|
|
2353
|
+
let result = 0n;
|
|
2354
|
+
for (const { sql, params } of sqls) {
|
|
2355
|
+
const dd = await option.conn.execute(SyncMode.Async, sql, params);
|
|
2356
|
+
if (dd.insertId) {
|
|
2357
|
+
result += BigInt(dd.insertId);
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
return result;
|
|
2361
|
+
}, { everyLength: option?.every === true ? 1 : option?.maxDeal });
|
|
2362
|
+
return result;
|
|
2363
|
+
};
|
|
2364
|
+
if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2365
|
+
return fn();
|
|
2366
|
+
}
|
|
2367
|
+
else {
|
|
2368
|
+
return option?.dao?.transaction(SyncMode.Async, fn, option?.conn);
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
else {
|
|
2372
|
+
const fn = async () => {
|
|
2373
|
+
const result = await excuteSplit(ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
|
|
2374
|
+
const sqls = this._insert(_data, option);
|
|
2375
|
+
let result = 0n;
|
|
2376
|
+
for (const { sql, params } of sqls) {
|
|
2377
|
+
const dd = await option.conn.execute(SyncMode.Async, sql, params);
|
|
2378
|
+
if (dd.insertId) {
|
|
2379
|
+
result += dd.insertId;
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
return result;
|
|
2383
|
+
}, { everyLength: 1 });
|
|
2384
|
+
return result[0];
|
|
2385
|
+
};
|
|
2386
|
+
if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2387
|
+
return fn();
|
|
2388
|
+
}
|
|
2389
|
+
else {
|
|
2390
|
+
return option?.dao?.transaction(SyncMode.Async, fn, option?.conn);
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
_update(datas, option) {
|
|
2395
|
+
const sqls = [];
|
|
2396
|
+
const tableName = option?.tableName;
|
|
2397
|
+
const where = `WHEN ${iterate(this[_ids]).map(c => `${this[_fields][c]?.C2()} = ?`).join(' AND ')} THEN ?`;
|
|
2398
|
+
const columnMaps = Object.fromEntries(this[_columnsNoId].map(c => [c, {
|
|
2399
|
+
where: new Array(),
|
|
2400
|
+
params: []
|
|
2401
|
+
}]));
|
|
2402
|
+
const params = [];
|
|
2403
|
+
for (const data of datas) {
|
|
2404
|
+
const ids = this[_ids].map(i => {
|
|
2405
|
+
Throw.if(!data[i], `UPDATE ID NOT EXISTS!${JSON.stringify(data)}`);
|
|
2406
|
+
return data[i];
|
|
2407
|
+
});
|
|
2408
|
+
this[_transformer](data, {
|
|
2409
|
+
...option,
|
|
2410
|
+
skipId: true,
|
|
2411
|
+
onFieldExists: (K, V) => {
|
|
2412
|
+
columnMaps[K]?.where.push(where);
|
|
2413
|
+
columnMaps[K]?.params.push(...ids, V);
|
|
2414
|
+
}
|
|
2415
|
+
});
|
|
2416
|
+
}
|
|
2417
|
+
const sql = formatDialect(`UPDATE ${tableName} SET ${iterate(this[_columnsNoId])
|
|
2418
|
+
.filter(K => columnMaps[K].where.length > 0)
|
|
2419
|
+
.map(K => {
|
|
2420
|
+
params.push(...columnMaps[K].params);
|
|
2421
|
+
return `${this[_fields][K]?.C2()} = CASE ${columnMaps[K].where.join(' ')} ELSE ${this[_fields][K]?.C2()} END`;
|
|
2422
|
+
})
|
|
2423
|
+
.join(',')};`, { dialect: formatDialects[option.dbType] });
|
|
2424
|
+
sqls.push({ sql, params });
|
|
2425
|
+
return sqls;
|
|
2426
|
+
}
|
|
2427
|
+
update(option) {
|
|
2428
|
+
Throw.if(!this[_ids] || this[_ids].length === 0, 'not found id');
|
|
2429
|
+
const datas = option.data instanceof Array ? option.data : [option.data];
|
|
2430
|
+
if (datas.length === 0)
|
|
2431
|
+
return 0;
|
|
2432
|
+
if (option.sync === SyncMode.Sync) {
|
|
2433
|
+
const fn = () => {
|
|
2434
|
+
const result = excuteSplit(ExcuteSplitMode.SyncTrust, datas, _data => {
|
|
2435
|
+
const sqls = this._update(_data, option);
|
|
2436
|
+
let result = 0;
|
|
2437
|
+
for (const { sql, params } of sqls) {
|
|
2438
|
+
const dd = option.conn.execute(SyncMode.Sync, sql, params);
|
|
2439
|
+
if (dd.affectedRows) {
|
|
2440
|
+
result += dd.affectedRows;
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
return result;
|
|
2444
|
+
}, { everyLength: option?.maxDeal });
|
|
2445
|
+
return result.length > 0 ? result.reduce((a, b) => a + b) : 0;
|
|
2446
|
+
};
|
|
2447
|
+
if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2448
|
+
return fn();
|
|
2449
|
+
}
|
|
2450
|
+
else {
|
|
2451
|
+
return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn);
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
else {
|
|
2455
|
+
const fn = async () => {
|
|
2456
|
+
const result = await excuteSplit(ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
|
|
2457
|
+
const sqls = this._update(_data, option);
|
|
2458
|
+
let result = 0;
|
|
2459
|
+
for (const { sql, params } of sqls) {
|
|
2460
|
+
const dd = await option.conn.execute(SyncMode.Async, sql, params);
|
|
2461
|
+
if (dd.affectedRows) {
|
|
2462
|
+
result += dd.affectedRows;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
return result;
|
|
2466
|
+
}, { everyLength: option?.maxDeal });
|
|
2467
|
+
return result.length > 0 ? result.reduce((a, b) => a + b) : 0;
|
|
2468
|
+
};
|
|
2469
|
+
if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2470
|
+
return fn();
|
|
2471
|
+
}
|
|
2472
|
+
else {
|
|
2473
|
+
return option?.dao?.transaction(SyncMode.Async, fn, option?.conn);
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
delete(option) {
|
|
2478
|
+
Throw.if(!!this[_ids] && this[_ids].length > 1 && !option.where, 'muit id must set where!');
|
|
2479
|
+
Throw.if((!this[_ids] || this[_ids].length === 0) && !option.where, 'if not set id on class, must set where!');
|
|
2480
|
+
Throw.if(!option.id && !option.where, 'not found id or where!');
|
|
2481
|
+
Throw.if(!!option.id && !!this[_ids] && this[_ids].length > 1, 'muit id must set where!');
|
|
2482
|
+
Throw.if(!!option.id && !!option.where, 'id and where only one can set!');
|
|
2483
|
+
option.mode ?? (option.mode = DeleteMode.Common);
|
|
2484
|
+
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
2485
|
+
const tableTempESC = tableTemp;
|
|
2486
|
+
const tableNameESC = option?.tableName;
|
|
2487
|
+
if (option.id) {
|
|
2488
|
+
const idName = this[_ids][0];
|
|
2489
|
+
const ids = option.id instanceof Array ? option.id : [option.id];
|
|
2490
|
+
option.where = ids.map(i => ({ [idName]: i }));
|
|
2491
|
+
}
|
|
2492
|
+
const wheres = option.where instanceof Array ? option.where : [option.where];
|
|
2493
|
+
if (wheres.length === 0) {
|
|
2494
|
+
return 0;
|
|
2495
|
+
}
|
|
2496
|
+
const sqls = [];
|
|
2497
|
+
if (option.mode === DeleteMode.Common) {
|
|
2498
|
+
const params = new Array();
|
|
2499
|
+
const whereSql = iterate(wheres).map(where => {
|
|
2500
|
+
return `(
|
|
2501
|
+
${Object.entries(where).map(([K, V]) => {
|
|
2502
|
+
params.push(V);
|
|
2503
|
+
return `${this[_fields][K]?.C2()} = ?`;
|
|
2504
|
+
}).join(' AND ')}
|
|
2505
|
+
)`;
|
|
2506
|
+
}).join(' OR ');
|
|
2507
|
+
if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
|
|
2508
|
+
params.unshift(this[_deleteState]);
|
|
2509
|
+
sqls.push({
|
|
2510
|
+
sql: formatDialect(`
|
|
2511
|
+
UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
|
|
2512
|
+
WHERE ${whereSql};
|
|
2513
|
+
`, { dialect: formatDialects[option.dbType] }), params
|
|
2514
|
+
});
|
|
2515
|
+
}
|
|
2516
|
+
else {
|
|
2517
|
+
sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE ${whereSql};`, { dialect: formatDialects[option.dbType] }), params });
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
else {
|
|
2521
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2522
|
+
const delWhere = Object.keys(wheres[0]);
|
|
2523
|
+
const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
|
|
2524
|
+
sqls.push(..._sqls);
|
|
2525
|
+
switch (option.dbType) {
|
|
2526
|
+
case DBType.Mysql: {
|
|
2527
|
+
if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
|
|
2528
|
+
sqls.push({
|
|
2529
|
+
sql: formatDialect(`UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.C2()} = b.${this[_fields][K]?.C2()}`).join(' AND ')}
|
|
2530
|
+
SET a.${this[_fields][this[_stateFileName]]?.C2()} = ?;`, { dialect: formatDialects[option.dbType] }),
|
|
2531
|
+
params: [this[_deleteState]]
|
|
2532
|
+
});
|
|
2533
|
+
}
|
|
2534
|
+
else {
|
|
2535
|
+
sqls.push({
|
|
2536
|
+
sql: formatDialect(`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 ')};`, { dialect: formatDialects[option.dbType] })
|
|
2537
|
+
});
|
|
2538
|
+
}
|
|
2539
|
+
break;
|
|
2540
|
+
}
|
|
2541
|
+
case DBType.Sqlite:
|
|
2542
|
+
case DBType.SqliteRemote: {
|
|
2543
|
+
const columnNames = iterate(delWhere).map(K => this[_fields][K]?.C2()).join(',');
|
|
2544
|
+
if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
|
|
2545
|
+
sqls.push({
|
|
2546
|
+
sql: formatDialect(`UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.C2()} = ?
|
|
2547
|
+
WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: formatDialects[option.dbType] }),
|
|
2548
|
+
params: [this[_deleteState]]
|
|
2549
|
+
});
|
|
2550
|
+
}
|
|
2551
|
+
else {
|
|
2552
|
+
sqls.push({ sql: formatDialect(`DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`, { dialect: formatDialects[option.dbType] }) });
|
|
2553
|
+
}
|
|
2554
|
+
break;
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2558
|
+
}
|
|
2559
|
+
if (option.sync === SyncMode.Sync) {
|
|
2560
|
+
const fn = () => {
|
|
2561
|
+
let result = 0;
|
|
2562
|
+
for (const { sql, params } of sqls) {
|
|
2563
|
+
const dd = option.conn.execute(SyncMode.Sync, sql, params);
|
|
2564
|
+
result += dd.affectedRows;
|
|
2565
|
+
}
|
|
2566
|
+
return result;
|
|
2567
|
+
};
|
|
2568
|
+
if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2569
|
+
return fn();
|
|
2570
|
+
}
|
|
2571
|
+
else {
|
|
2572
|
+
return option?.dao?.transaction(SyncMode.Sync, fn, option?.conn);
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
else {
|
|
2576
|
+
const fn = async () => {
|
|
2577
|
+
let result = 0;
|
|
2578
|
+
for (const { sql, params } of sqls) {
|
|
2579
|
+
const dd = await option.conn.execute(SyncMode.Async, sql, params);
|
|
2580
|
+
result += dd.affectedRows;
|
|
2581
|
+
}
|
|
2582
|
+
return result;
|
|
2583
|
+
};
|
|
2584
|
+
if (option.dbType === DBType.SqliteRemote || option?.conn?.[_inTransaction] === true) {
|
|
2585
|
+
return fn();
|
|
2586
|
+
}
|
|
2587
|
+
else {
|
|
2588
|
+
return option?.dao?.transaction(SyncMode.Async, fn, option?.conn);
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
_template(templateResult, result, error) {
|
|
2593
|
+
switch (templateResult) {
|
|
2594
|
+
case TemplateResult.AssertOne: {
|
|
2595
|
+
Throw.if(!result || result.length !== 1, error);
|
|
2596
|
+
return result[0];
|
|
2597
|
+
}
|
|
2598
|
+
case TemplateResult.NotSureOne: {
|
|
2599
|
+
return result && result.length > 0 ? result[0] ?? null : null;
|
|
2600
|
+
}
|
|
2601
|
+
case TemplateResult.Many: {
|
|
2602
|
+
return result;
|
|
2603
|
+
}
|
|
2604
|
+
case TemplateResult.Count: {
|
|
2605
|
+
return result[0].ct;
|
|
2606
|
+
}
|
|
2607
|
+
case TemplateResult.ManyList: {
|
|
2608
|
+
return new ArrayList(result[0]);
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
}
|
|
2612
|
+
template(option) {
|
|
2613
|
+
Throw.if(!!this[_ids] && this[_ids].length > 1 && !option.where, 'muit id must set where!');
|
|
2614
|
+
Throw.if((!this[_ids] || this[_ids].length === 0) && !option.where, 'if not set id on class, must set where!');
|
|
2615
|
+
Throw.if(!option.id && !option.where, 'not found id or where!');
|
|
2616
|
+
Throw.if(!!option.id && !!this[_ids] && this[_ids].length > 1, 'muit id must set where!');
|
|
2617
|
+
Throw.if(!!option.id && !!option.where, 'id and where only one can set!');
|
|
2618
|
+
option.mode ?? (option.mode = SelectMode.Common);
|
|
2619
|
+
option.templateResult ?? (option.templateResult = TemplateResult.AssertOne);
|
|
2620
|
+
option.error ?? (option.error = 'error data!');
|
|
2621
|
+
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
2622
|
+
const tableTempESC = tableTemp;
|
|
2623
|
+
const tableNameESC = option?.tableName;
|
|
2624
|
+
if (option.id) {
|
|
2625
|
+
const idName = this[_ids][0];
|
|
2626
|
+
const ids = option.id instanceof Array ? option.id : [option.id];
|
|
2627
|
+
option.where = ids.map(i => ({ [idName]: i }));
|
|
2628
|
+
}
|
|
2629
|
+
const columns = option.templateResult === TemplateResult.Count ? 'COUNT(1) ct' : iterate((option.columns ?? this[_columns])).map((K) => `a.${this[_fields][K]?.C3()}`).join(',');
|
|
2630
|
+
const wheres = option.where instanceof Array ? option.where : [option.where];
|
|
2631
|
+
const sqls = [];
|
|
2632
|
+
let resultIndex = -1;
|
|
2633
|
+
if (option.mode === SelectMode.Common) {
|
|
2634
|
+
const params = new Array();
|
|
2635
|
+
const whereSql = formatDialect(iterate(wheres).map(where => this[_transformer](where, option)).map(where => {
|
|
2636
|
+
return `SELECT ${columns} FROM ${tableNameESC} a WHERE
|
|
2637
|
+
${Object.entries(where).map(([K, V]) => {
|
|
2638
|
+
params.push(V);
|
|
2639
|
+
return `${this[_fields][K]?.C2()} = ?`;
|
|
2640
|
+
}).join(' AND ')}`;
|
|
2641
|
+
}).join(' UNION ALL '), { dialect: formatDialects[option.dbType] });
|
|
2642
|
+
sqls.push({ sql: whereSql, params });
|
|
2643
|
+
resultIndex = 0;
|
|
2644
|
+
}
|
|
2645
|
+
else {
|
|
2646
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2647
|
+
const delWhere = Object.keys(wheres[0]);
|
|
2648
|
+
const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
|
|
2649
|
+
sqls.push(..._sqls);
|
|
2650
|
+
resultIndex = sqls.length;
|
|
2651
|
+
sqls.push({ sql: formatDialect(`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 ')};`, { dialect: formatDialects[option.dbType] }) });
|
|
2652
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
2653
|
+
}
|
|
2654
|
+
if (option.sync === SyncMode.Sync) {
|
|
2655
|
+
let result;
|
|
2656
|
+
for (let i = 0; i < sqls.length; i++) {
|
|
2657
|
+
if (i === resultIndex) {
|
|
2658
|
+
result = option.conn.query(SyncMode.Sync, sqls[i]?.sql, sqls[i]?.params);
|
|
2659
|
+
}
|
|
2660
|
+
else {
|
|
2661
|
+
option.conn.execute(SyncMode.Sync, sqls[i]?.sql, sqls[i]?.params);
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
return this._template(option.templateResult, result, option.error);
|
|
2665
|
+
}
|
|
2666
|
+
else {
|
|
2667
|
+
return new Promise(async (resolve, reject) => {
|
|
2668
|
+
try {
|
|
2669
|
+
let result;
|
|
2670
|
+
for (let i = 0; i < sqls.length; i++) {
|
|
2671
|
+
if (i === resultIndex) {
|
|
2672
|
+
result = await option.conn.query(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
|
|
2673
|
+
}
|
|
2674
|
+
else {
|
|
2675
|
+
await option.conn.execute(SyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
resolve(this._template(option.templateResult, result, option.error));
|
|
2679
|
+
}
|
|
2680
|
+
catch (error) {
|
|
2681
|
+
reject(error);
|
|
2682
|
+
}
|
|
2683
|
+
});
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
_select(templateResult, result, def, errorMsg, hump, mapper, mapperIfUndefined) {
|
|
2687
|
+
switch (templateResult) {
|
|
2688
|
+
case SelectResult.R_C_NotSure: {
|
|
2689
|
+
try {
|
|
2690
|
+
return Object.values(result[0])[0];
|
|
2691
|
+
}
|
|
2692
|
+
catch (error) {
|
|
2693
|
+
return def;
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
case SelectResult.R_C_Assert: {
|
|
2697
|
+
try {
|
|
2698
|
+
return Object.values(result[0])[0];
|
|
2699
|
+
}
|
|
2700
|
+
catch (error) {
|
|
2701
|
+
if (def !== undefined)
|
|
2702
|
+
return def;
|
|
2703
|
+
Throw.now(errorMsg ?? 'not found data!');
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
case SelectResult.R_CS_NotSure: {
|
|
2707
|
+
if (mapper) {
|
|
2708
|
+
return flatData({ data: result[0], mapper, mapperIfUndefined });
|
|
2709
|
+
}
|
|
2710
|
+
else if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
|
|
2711
|
+
return C2P2(result[0]) ?? null;
|
|
2712
|
+
}
|
|
2713
|
+
else {
|
|
2714
|
+
return result[0] ?? null;
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
case SelectResult.R_CS_Assert: {
|
|
2718
|
+
const data = result[0];
|
|
2719
|
+
Throw.if(data === null || data === undefined, errorMsg ?? 'not found data!');
|
|
2720
|
+
if (mapper) {
|
|
2721
|
+
return flatData({ data, mapper, mapperIfUndefined });
|
|
2722
|
+
}
|
|
2723
|
+
else if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
|
|
2724
|
+
return C2P2(data) ?? null;
|
|
2725
|
+
}
|
|
2726
|
+
else {
|
|
2727
|
+
return data ?? null;
|
|
2728
|
+
}
|
|
2729
|
+
}
|
|
2730
|
+
case SelectResult.RS_C: {
|
|
2731
|
+
try {
|
|
2732
|
+
return result.map((r) => Object.values(r)[0]);
|
|
2733
|
+
}
|
|
2734
|
+
catch (error) {
|
|
2735
|
+
return result;
|
|
2736
|
+
}
|
|
2737
|
+
}
|
|
2738
|
+
case SelectResult.RS_CS: {
|
|
2739
|
+
if (mapper) {
|
|
2740
|
+
return iterate(result).map((data) => flatData({ data, mapper, mapperIfUndefined })).toArray();
|
|
2741
|
+
}
|
|
2742
|
+
else if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
|
|
2743
|
+
return iterate(result).map((r) => C2P2(r)).toArray();
|
|
2744
|
+
}
|
|
2745
|
+
else {
|
|
2746
|
+
return result;
|
|
2747
|
+
}
|
|
2748
|
+
}
|
|
2749
|
+
case SelectResult.RS_C_List: {
|
|
2750
|
+
try {
|
|
2751
|
+
return new ArrayList(result.map((r) => Object.values(r)[0]));
|
|
2752
|
+
}
|
|
2753
|
+
catch (error) {
|
|
2754
|
+
return new ArrayList();
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
2757
|
+
case SelectResult.RS_CS_List: {
|
|
2758
|
+
if (mapper) {
|
|
2759
|
+
return new ArrayList(iterate(result).map((data) => flatData({ data, mapper, mapperIfUndefined })).toArray());
|
|
2760
|
+
}
|
|
2761
|
+
else if (hump === true || (hump === undefined && globalThis[_Hump] === true)) {
|
|
2762
|
+
return new ArrayList(iterate(result).map((r) => C2P2(r)).toArray());
|
|
2763
|
+
}
|
|
2764
|
+
else {
|
|
2765
|
+
return new ArrayList();
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
}
|
|
2769
|
+
}
|
|
2770
|
+
select(option) {
|
|
2771
|
+
Throw.if(!option.sqlId && !option.sql, 'not found sql!');
|
|
2772
|
+
option.selectResult ?? (option.selectResult = SelectResult.RS_CS);
|
|
2773
|
+
option.defValue ?? (option.defValue = null);
|
|
2774
|
+
if (option.sqlId && globalThis[_resultMap_SQLID][option.sqlId] && !option.mapper) {
|
|
2775
|
+
option.mapper = globalThis[_resultMap_SQLID][option.sqlId];
|
|
2776
|
+
}
|
|
2777
|
+
const _params = Object.assign({}, option.context, option.params);
|
|
2778
|
+
option.sql ?? (option.sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: option.isCount, ..._params }));
|
|
2779
|
+
const { sql, params } = this._generSql(option.dbType, option.sql, _params);
|
|
2780
|
+
if (option.sync === SyncMode.Sync) {
|
|
2781
|
+
const result = option.conn.query(SyncMode.Sync, sql, params);
|
|
2782
|
+
return this._select(option.selectResult, result, option.defValue, option.errorMsg, option.hump, option.mapper, option.mapperIfUndefined);
|
|
2783
|
+
}
|
|
2784
|
+
else {
|
|
2785
|
+
return new Promise(async (resolve, reject) => {
|
|
2786
|
+
try {
|
|
2787
|
+
const result = await option.conn.query(SyncMode.Async, sql, params);
|
|
2788
|
+
resolve(this._select(option.selectResult, result, option.defValue, option.errorMsg, option.hump, option.mapper, option.mapperIfUndefined));
|
|
2789
|
+
}
|
|
2790
|
+
catch (error) {
|
|
2791
|
+
reject(error);
|
|
2792
|
+
}
|
|
2793
|
+
});
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
excute(option) {
|
|
2797
|
+
Throw.if(!option.sqlId && !option.sql, 'not found sql!');
|
|
2798
|
+
const _params = Object.assign({}, option.context, option.params);
|
|
2799
|
+
option.sql ?? (option.sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, ..._params }));
|
|
2800
|
+
const { sql, params } = this._generSql(option.dbType, option.sql, _params);
|
|
2801
|
+
if (option.sync === SyncMode.Sync) {
|
|
2802
|
+
const result = option.conn.execute(SyncMode.Sync, sql, params);
|
|
2803
|
+
return result.affectedRows;
|
|
2804
|
+
}
|
|
2805
|
+
else {
|
|
2806
|
+
return new Promise(async (resolve, reject) => {
|
|
2807
|
+
try {
|
|
2808
|
+
const result = await option.conn.execute(SyncMode.Async, sql, params);
|
|
2809
|
+
resolve(result.affectedRows);
|
|
2810
|
+
}
|
|
2811
|
+
catch (error) {
|
|
2812
|
+
reject(error);
|
|
2813
|
+
}
|
|
2814
|
+
});
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
transaction(option) {
|
|
2818
|
+
if (option.sync === SyncMode.Sync) {
|
|
2819
|
+
return option.dao.transaction(SyncMode.Sync, option.fn);
|
|
2820
|
+
}
|
|
2821
|
+
else {
|
|
2822
|
+
return new Promise(async (resolve, reject) => {
|
|
2823
|
+
try {
|
|
2824
|
+
const rt = await option.dao.transaction(SyncMode.Async, option.fn);
|
|
2825
|
+
resolve(rt);
|
|
2826
|
+
}
|
|
2827
|
+
catch (error) {
|
|
2828
|
+
reject(error);
|
|
2829
|
+
}
|
|
2830
|
+
});
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2833
|
+
stream() {
|
|
2834
|
+
return new StreamQuery(this, this[_fields], this[_columns]);
|
|
2835
|
+
}
|
|
2836
|
+
page(option) {
|
|
2837
|
+
const result = {
|
|
2838
|
+
sum: {},
|
|
2839
|
+
records: [],
|
|
2840
|
+
size: 0,
|
|
2841
|
+
total: 0
|
|
2842
|
+
};
|
|
2843
|
+
option.pageNumber ?? (option.pageNumber = 1);
|
|
2844
|
+
option.pageSize ?? (option.pageSize = 0);
|
|
2845
|
+
if (option.hump === true || (option.hump === undefined && globalThis[_Hump] === true) && option.sortName) {
|
|
2846
|
+
option.sortName = P2C(option.sortName);
|
|
2847
|
+
}
|
|
2848
|
+
Object.assign(option.params, {
|
|
2849
|
+
limitStart: calc(option.pageNumber).sub(1).mul(option.pageSize).over(),
|
|
2850
|
+
limitEnd: option.pageSize - 0,
|
|
2851
|
+
sortName: option.sortName ?? undefined,
|
|
2852
|
+
sortType: option.sortType ?? undefined
|
|
2853
|
+
});
|
|
2854
|
+
let sql = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: false, ...option.params });
|
|
2855
|
+
let sqlSum = '';
|
|
2856
|
+
let sqlCount = '';
|
|
2857
|
+
if (option.sumSelf === true) {
|
|
2858
|
+
sqlSum = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: false, isSum: true, ...option.params });
|
|
2859
|
+
}
|
|
2860
|
+
if (option.limitSelf !== true) {
|
|
2861
|
+
if (option.countSelf !== true) {
|
|
2862
|
+
}
|
|
2863
|
+
if (option.pageSize > 0) {
|
|
2864
|
+
sql = `${sql} LIMIT ${option.params['limitStart']}, ${option.pageSize}`;
|
|
2865
|
+
}
|
|
2866
|
+
}
|
|
2867
|
+
if (option.pageSize > 0) {
|
|
2868
|
+
if (option.countSelf === true) {
|
|
2869
|
+
sqlCount = globalThis[_sqlCache].load(this._matchSqlid(`${option.sqlId}_count`), { ctx: option.context, isCount: true, isSum: false, ...option.params });
|
|
2870
|
+
}
|
|
2871
|
+
else {
|
|
2872
|
+
sqlCount = globalThis[_sqlCache].load(this._matchSqlid(option.sqlId), { ctx: option.context, isCount: true, isSum: false, ...option.params });
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
if (option.sync === SyncMode.Sync) {
|
|
2876
|
+
if (sqlCount) {
|
|
2877
|
+
result.total = this.select({
|
|
2878
|
+
...option,
|
|
2879
|
+
sql: sqlCount,
|
|
2880
|
+
sync: SyncMode.Sync,
|
|
2881
|
+
selectResult: SelectResult.R_C_Assert
|
|
2882
|
+
});
|
|
2883
|
+
result.size = calc(result.total)
|
|
2884
|
+
.add(option.pageSize - 1)
|
|
2885
|
+
.div(option.pageSize)
|
|
2886
|
+
.round(0, 2)
|
|
2887
|
+
.over();
|
|
2888
|
+
}
|
|
2889
|
+
if (sqlSum) {
|
|
2890
|
+
result.sum = this.select({
|
|
2891
|
+
...option,
|
|
2892
|
+
sql: sqlSum,
|
|
2893
|
+
sync: SyncMode.Sync,
|
|
2894
|
+
selectResult: SelectResult.R_CS_Assert
|
|
2895
|
+
});
|
|
2896
|
+
}
|
|
2897
|
+
if (sql) {
|
|
2898
|
+
result.records = this.select({
|
|
2899
|
+
...option,
|
|
2900
|
+
sql,
|
|
2901
|
+
sync: SyncMode.Sync,
|
|
2902
|
+
selectResult: SelectResult.RS_CS
|
|
2903
|
+
});
|
|
2904
|
+
}
|
|
2905
|
+
return result;
|
|
2906
|
+
}
|
|
2907
|
+
else {
|
|
2908
|
+
return new Promise(async (resolve, reject) => {
|
|
2909
|
+
try {
|
|
2910
|
+
if (sqlCount) {
|
|
2911
|
+
result.total = await this.select({
|
|
2912
|
+
...option,
|
|
2913
|
+
sql: sqlCount,
|
|
2914
|
+
sync: SyncMode.Async,
|
|
2915
|
+
selectResult: SelectResult.R_C_Assert
|
|
2916
|
+
});
|
|
2917
|
+
result.size = calc(result.total)
|
|
2918
|
+
.add(option.pageSize ?? 10 - 1)
|
|
2919
|
+
.div(option.pageSize)
|
|
2920
|
+
.round(0, 2)
|
|
2921
|
+
.over();
|
|
2922
|
+
}
|
|
2923
|
+
if (sqlSum) {
|
|
2924
|
+
result.sum = await this.select({
|
|
2925
|
+
...option,
|
|
2926
|
+
sql: sqlSum,
|
|
2927
|
+
sync: SyncMode.Async,
|
|
2928
|
+
selectResult: SelectResult.R_CS_Assert
|
|
2929
|
+
});
|
|
2930
|
+
}
|
|
2931
|
+
if (sql) {
|
|
2932
|
+
result.records = await this.select({
|
|
2933
|
+
...option,
|
|
2934
|
+
sql,
|
|
2935
|
+
sync: SyncMode.Async,
|
|
2936
|
+
selectResult: SelectResult.RS_CS
|
|
2937
|
+
});
|
|
2938
|
+
}
|
|
2939
|
+
resolve(result);
|
|
2940
|
+
}
|
|
2941
|
+
catch (error) {
|
|
2942
|
+
reject(error);
|
|
2943
|
+
}
|
|
2944
|
+
});
|
|
2945
|
+
}
|
|
2946
|
+
}
|
|
2947
|
+
/**
|
|
2948
|
+
* 导出数据,可以为EJS-EXCEL直接使用
|
|
2949
|
+
* @param list
|
|
2950
|
+
* @returns
|
|
2951
|
+
*/
|
|
2952
|
+
exp(list) {
|
|
2953
|
+
Throw.if(list.length === 0, 'not found data!');
|
|
2954
|
+
const columnTitles = new Array();
|
|
2955
|
+
const keys = this[_fields] ?
|
|
2956
|
+
iterate(Object.entries(this[_fields]))
|
|
2957
|
+
.filter(([K, F]) => (F.id !== true && F.exportable !== false) || (F.id === true && F.exportable === true))
|
|
2958
|
+
.map(([K, F]) => {
|
|
2959
|
+
columnTitles.push(F.comment ?? K);
|
|
2960
|
+
return K;
|
|
2961
|
+
}).toArray()
|
|
2962
|
+
: Object.keys(list[0]).filter(K => !this[_ids]?.includes(K));
|
|
2963
|
+
const title = this[_comment] ?? this[_tableName];
|
|
2964
|
+
const titleSpan = `A1:${ten2Any(keys.length)}1`;
|
|
2965
|
+
const datas = list.map(data => keys.map(k => data[k] ?? ''));
|
|
2966
|
+
return { title, titleSpan, columnTitles, datas };
|
|
2967
|
+
}
|
|
2968
|
+
/**
|
|
2969
|
+
* 导入数据的模板
|
|
2970
|
+
* @returns
|
|
2971
|
+
*/
|
|
2972
|
+
imp() {
|
|
2973
|
+
Throw.if(!this[_fields], 'not set fields!');
|
|
2974
|
+
const columnTitles = new Array();
|
|
2975
|
+
const keys = iterate(Object.entries(this[_fields]))
|
|
2976
|
+
.filter(([K, F]) => (F.id !== true && F.exportable !== false) || (F.id === true && F.exportable === true))
|
|
2977
|
+
.map(([K, F]) => {
|
|
2978
|
+
columnTitles.push(F.comment ?? K);
|
|
2979
|
+
return K;
|
|
2980
|
+
}).toArray();
|
|
2981
|
+
const title = this[_comment] ?? this[_tableName];
|
|
2982
|
+
const titleSpan = `A1:${ten2Any(keys.length)}1`;
|
|
2983
|
+
return { title, titleSpan, columnTitles };
|
|
2984
|
+
}
|
|
2985
|
+
init(option) {
|
|
2986
|
+
var _f;
|
|
2987
|
+
const tableES = option.tableName;
|
|
2988
|
+
(_f = option).force ?? (_f.force = false);
|
|
2989
|
+
if (option.dbType === DBType.Sqlite) {
|
|
2990
|
+
if (option?.force) {
|
|
2991
|
+
option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${tableES};`);
|
|
2992
|
+
}
|
|
2993
|
+
const lastVersion = this[_sqlite_version] ?? '0.0.1';
|
|
2994
|
+
// 检查表
|
|
2995
|
+
const tableCheckResult = option.conn.pluck(SyncMode.Sync, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
|
|
2996
|
+
if (tableCheckResult) {
|
|
2997
|
+
// 旧版本
|
|
2998
|
+
const tableVersion = option.conn.pluck(SyncMode.Sync, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
|
|
2999
|
+
if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
|
|
3000
|
+
// 更新版本
|
|
3001
|
+
const columns = iterate(option.conn.query(SyncMode.Sync, `PRAGMA table_info(${tableES})`))
|
|
3002
|
+
.filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
|
|
3003
|
+
.map(c => c.name)
|
|
3004
|
+
.join(',');
|
|
3005
|
+
const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
|
|
3006
|
+
option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
|
|
3007
|
+
option.conn.execute(SyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
|
|
3008
|
+
option.conn.execute(SyncMode.Sync, `
|
|
3009
|
+
CREATE TABLE IF NOT EXISTS ${tableES}(
|
|
3010
|
+
${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
|
|
3011
|
+
${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
|
|
3012
|
+
);
|
|
3013
|
+
`);
|
|
3014
|
+
if (this[_index] && this[_index].length) {
|
|
3015
|
+
for (const index of this[_index]) {
|
|
3016
|
+
option.conn.execute(SyncMode.Sync, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
|
|
3017
|
+
}
|
|
3018
|
+
}
|
|
3019
|
+
option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
3020
|
+
option.conn.execute(SyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
3021
|
+
option.conn.execute(SyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
|
|
3022
|
+
// 更新完毕,保存版本号
|
|
3023
|
+
option.conn.execute(SyncMode.Sync, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
|
|
3024
|
+
}
|
|
3025
|
+
else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
|
|
3026
|
+
option.conn.execute(SyncMode.Sync, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
|
|
3027
|
+
}
|
|
3028
|
+
}
|
|
3029
|
+
else { // 表不存在
|
|
3030
|
+
// 创建表
|
|
3031
|
+
option.conn.execute(SyncMode.Sync, `
|
|
3032
|
+
CREATE TABLE IF NOT EXISTS ${tableES} (
|
|
3033
|
+
${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
|
|
3034
|
+
${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
|
|
3035
|
+
|
|
3036
|
+
);
|
|
3037
|
+
`);
|
|
3038
|
+
if (this[_index] && this[_index].length) {
|
|
3039
|
+
for (const index of this[_index]) {
|
|
3040
|
+
option.conn.execute(SyncMode.Sync, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
option.conn.execute(SyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
else if (option.dbType === DBType.SqliteRemote) {
|
|
3047
|
+
return new Promise(async (resolve, reject) => {
|
|
3048
|
+
try {
|
|
3049
|
+
if (option?.force) {
|
|
3050
|
+
await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${tableES};`);
|
|
3051
|
+
}
|
|
3052
|
+
const lastVersion = this[_sqlite_version] ?? '0.0.1';
|
|
3053
|
+
// 检查表
|
|
3054
|
+
const tableCheckResult = await option.conn.pluck(SyncMode.Async, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
|
|
3055
|
+
if (tableCheckResult) {
|
|
3056
|
+
// 旧版本
|
|
3057
|
+
const tableVersion = await option.conn.pluck(SyncMode.Async, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
|
|
3058
|
+
if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
|
|
3059
|
+
// 更新版本
|
|
3060
|
+
const columns = iterate(await option.conn.query(SyncMode.Async, `PRAGMA table_info(${tableES})`))
|
|
3061
|
+
.filter(c => this[_fields].hasOwnProperty(C2P(c.name, globalThis[_Hump])))
|
|
3062
|
+
.map(c => c.name)
|
|
3063
|
+
.join(',');
|
|
3064
|
+
const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
|
|
3065
|
+
await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
|
|
3066
|
+
await option.conn.execute(SyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
|
|
3067
|
+
await option.conn.execute(SyncMode.Async, `
|
|
3068
|
+
CREATE TABLE IF NOT EXISTS ${tableES}(
|
|
3069
|
+
${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
|
|
3070
|
+
${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
|
|
3071
|
+
);
|
|
3072
|
+
`);
|
|
3073
|
+
if (this[_index] && this[_index].length) {
|
|
3074
|
+
for (const index of this[_index]) {
|
|
3075
|
+
await option.conn.execute(SyncMode.Async, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableES} ("${this[_fields][index]?.C2()}");`);
|
|
3076
|
+
}
|
|
3077
|
+
}
|
|
3078
|
+
await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
3079
|
+
await option.conn.execute(SyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
3080
|
+
await option.conn.execute(SyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
|
|
3081
|
+
// 更新完毕,保存版本号
|
|
3082
|
+
await option.conn.execute(SyncMode.Async, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
|
|
3083
|
+
}
|
|
3084
|
+
else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
|
|
3085
|
+
await option.conn.execute(SyncMode.Async, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
|
|
3086
|
+
}
|
|
3087
|
+
}
|
|
3088
|
+
else { // 表不存在
|
|
3089
|
+
// 创建表
|
|
3090
|
+
await option.conn.execute(SyncMode.Async, `
|
|
3091
|
+
CREATE TABLE IF NOT EXISTS ${tableES}(
|
|
3092
|
+
${Object.values(this[_fields]).map(K => K[DBType.Sqlite]()).join(',')}
|
|
3093
|
+
${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.C2()).join(',')})` : ''}
|
|
3094
|
+
);
|
|
3095
|
+
`);
|
|
3096
|
+
if (this[_index] && this[_index].length) {
|
|
3097
|
+
for (const index of this[_index]) {
|
|
3098
|
+
await option.conn.execute(SyncMode.Async, `CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${option.tableName} ("${this[_fields][index]?.C2()}");`);
|
|
3099
|
+
}
|
|
3100
|
+
}
|
|
3101
|
+
await option.conn.execute(SyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
|
|
3102
|
+
}
|
|
3103
|
+
resolve();
|
|
3104
|
+
}
|
|
3105
|
+
catch (error) {
|
|
3106
|
+
reject(error);
|
|
3107
|
+
}
|
|
3108
|
+
});
|
|
3109
|
+
}
|
|
3110
|
+
}
|
|
3111
|
+
close(option) {
|
|
3112
|
+
delete globalThis[_dao][option.dbType][option.dbName];
|
|
3113
|
+
if (option?.sync === SyncMode.Async) {
|
|
3114
|
+
return option.dao.close(SyncMode.Async);
|
|
3115
|
+
}
|
|
3116
|
+
else if (option?.sync === SyncMode.Sync) {
|
|
3117
|
+
option.dao.close(SyncMode.Sync);
|
|
3118
|
+
}
|
|
3119
|
+
}
|
|
3120
|
+
/**
|
|
3121
|
+
#创建表
|
|
3122
|
+
** `tableName` 表名称
|
|
3123
|
+
** `temp` 是否是临时表,默认true
|
|
3124
|
+
** `columns` 字符串数组,默认是当前实体类全部字段,通过`columns` 可以创建部分字段临时表
|
|
3125
|
+
** `id` 表的主键设置 4种:
|
|
3126
|
+
1. `auto`: `columns`中已经在当前实体类配置的ID作为主键 `默认`
|
|
3127
|
+
2. `all`: `columns`中所有字段全部当主键
|
|
3128
|
+
3. `none`: 没有主键
|
|
3129
|
+
4. 自定义字段名称:字符串数组
|
|
3130
|
+
** `index` 表的索引,设置方式同ID
|
|
3131
|
+
*/
|
|
3132
|
+
_createTable({ tableName, temp = true, columns, data, id = 'auto', index = 'auto', dbType } = {}) {
|
|
3133
|
+
const sqls = [];
|
|
3134
|
+
columns = columns || this[_columns];
|
|
3135
|
+
let ids;
|
|
3136
|
+
if (id === 'auto') {
|
|
3137
|
+
ids = this[_ids]?.filter(i => columns?.includes(i));
|
|
3138
|
+
}
|
|
3139
|
+
else if (id === 'all') {
|
|
3140
|
+
ids = columns;
|
|
3141
|
+
}
|
|
3142
|
+
else if (id === 'none') {
|
|
3143
|
+
ids = undefined;
|
|
3144
|
+
}
|
|
3145
|
+
else {
|
|
3146
|
+
ids = id;
|
|
3147
|
+
}
|
|
3148
|
+
let indexs;
|
|
3149
|
+
if (index === 'auto') {
|
|
3150
|
+
indexs = this[_index]?.filter(i => columns?.includes(i));
|
|
3151
|
+
}
|
|
3152
|
+
else if (index === 'all') {
|
|
3153
|
+
indexs = columns;
|
|
3154
|
+
}
|
|
3155
|
+
else if (index === 'none') {
|
|
3156
|
+
indexs = undefined;
|
|
3157
|
+
}
|
|
3158
|
+
else {
|
|
3159
|
+
indexs = index;
|
|
3160
|
+
}
|
|
3161
|
+
tableName = tableName ?? this[_tableName];
|
|
3162
|
+
switch (dbType) {
|
|
3163
|
+
case DBType.Mysql: {
|
|
3164
|
+
let sql = formatDialect(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
|
|
3165
|
+
${columns.map(K => this[_fields][K][DBType.Mysql]()).join(',')}
|
|
3166
|
+
${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) USING BTREE ` : ''}
|
|
3167
|
+
${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields][i]?.C2()} (${this[_fields][i]?.C2()})`).join(',')} ` : ''}
|
|
3168
|
+
) ENGINE=MEMORY;`, { dialect: mysql });
|
|
3169
|
+
sqls.push({ sql });
|
|
3170
|
+
if (data && data.length > 0) {
|
|
3171
|
+
const params = [];
|
|
3172
|
+
let first = true;
|
|
3173
|
+
sql = formatDialect(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
|
|
3174
|
+
${(data).map(d => {
|
|
3175
|
+
const r = `SELECT ${Object.entries(d).map(([K, V]) => {
|
|
3176
|
+
params.push(V);
|
|
3177
|
+
return `? ${first ? this[_fields][K]?.C2() : ''}`;
|
|
3178
|
+
}).join(',')}`;
|
|
3179
|
+
first = false;
|
|
3180
|
+
return r;
|
|
3181
|
+
}).join(' UNION ALL ')}`, { dialect: mysql });
|
|
3182
|
+
sqls.push({ sql, params });
|
|
3183
|
+
}
|
|
3184
|
+
break;
|
|
3185
|
+
}
|
|
3186
|
+
case DBType.Sqlite:
|
|
3187
|
+
case DBType.SqliteRemote: {
|
|
3188
|
+
let sql = formatDialect(`CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
|
|
3189
|
+
${columns.map(K => this[_fields][K][DBType.Sqlite]()).join(',')}
|
|
3190
|
+
${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.C2()).join(',')}) ` : ''}
|
|
3191
|
+
);`, { dialect: sqlite });
|
|
3192
|
+
sqls.push({ sql });
|
|
3193
|
+
if (indexs) {
|
|
3194
|
+
for (const index of indexs) {
|
|
3195
|
+
sql = formatDialect(`CREATE INDEX ${`${index}_${Math.random()}`.replace(/\./, '')} ON ${tableName} (${this[_fields][index]?.C2()});`, { dialect: sqlite });
|
|
3196
|
+
sqls.push({ sql });
|
|
3197
|
+
}
|
|
3198
|
+
}
|
|
3199
|
+
if (data && data.length > 0) {
|
|
3200
|
+
const params = [];
|
|
3201
|
+
let first = true;
|
|
3202
|
+
sql = formatDialect(`INSERT INTO ${tableName} (${columns.map(c => this[_fields][c]?.C2()).join(',')})
|
|
3203
|
+
${(data).map(d => {
|
|
3204
|
+
const r = `SELECT ${Object.entries(d).map(([K, V]) => {
|
|
3205
|
+
params.push(V);
|
|
3206
|
+
return `? ${first ? this[_fields][K]?.C2() : ''}`;
|
|
3207
|
+
}).join(',')}`;
|
|
3208
|
+
first = false;
|
|
3209
|
+
return r;
|
|
3210
|
+
}).join(' UNION ALL ')}`, { dialect: sqlite });
|
|
3211
|
+
sqls.push({ sql, params });
|
|
3212
|
+
}
|
|
3213
|
+
break;
|
|
3214
|
+
}
|
|
3215
|
+
}
|
|
3216
|
+
return sqls;
|
|
3217
|
+
}
|
|
3218
|
+
_matchSqlid(sqlid) {
|
|
3219
|
+
sqlid ?? (sqlid = '');
|
|
3220
|
+
if (sqlid.includes('.'))
|
|
3221
|
+
return [sqlid];
|
|
3222
|
+
else
|
|
3223
|
+
return [`${this[_tableName]}.${sqlid}`, `${this[_className]}.${sqlid}`, `${this[_ClassName]}.${sqlid}`, `${this[_vueName]}.${sqlid}`];
|
|
3224
|
+
}
|
|
3225
|
+
_setParam(v, ps) {
|
|
3226
|
+
if (v instanceof Array) {
|
|
3227
|
+
ps.push(...v);
|
|
3228
|
+
return v.map(i => '?').join(',');
|
|
3229
|
+
}
|
|
3230
|
+
else {
|
|
3231
|
+
ps.push(v);
|
|
3232
|
+
return '?';
|
|
3233
|
+
}
|
|
3234
|
+
}
|
|
3235
|
+
_generSql(dbType, _sql, _params) {
|
|
3236
|
+
const params = [];
|
|
3237
|
+
const sql = formatDialect(_sql?.replace(/\:(\w+)/g, (txt, key) => {
|
|
3238
|
+
let V = LGet(_params, key);
|
|
3239
|
+
if (V !== undefined) {
|
|
3240
|
+
return this._setParam(V, params);
|
|
3241
|
+
}
|
|
3242
|
+
const _key = C2P(key);
|
|
3243
|
+
V = LGet(_params, _key);
|
|
3244
|
+
if (V !== undefined) {
|
|
3245
|
+
return this._setParam(V, params);
|
|
3246
|
+
}
|
|
3247
|
+
const __key = P2C(key);
|
|
3248
|
+
V = LGet(_params, __key);
|
|
3249
|
+
if (V !== undefined) {
|
|
3250
|
+
return this._setParam(V, params);
|
|
3251
|
+
}
|
|
3252
|
+
return txt;
|
|
3253
|
+
}), { dialect: formatDialects[dbType] });
|
|
3254
|
+
return { params, sql };
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
__decorate([
|
|
3258
|
+
P(),
|
|
3259
|
+
__metadata("design:type", Function),
|
|
3260
|
+
__metadata("design:paramtypes", [Object]),
|
|
3261
|
+
__metadata("design:returntype", Object)
|
|
3262
|
+
], SqlService.prototype, "insert", null);
|
|
3263
|
+
__decorate([
|
|
3264
|
+
P(),
|
|
3265
|
+
__metadata("design:type", Function),
|
|
3266
|
+
__metadata("design:paramtypes", [Object]),
|
|
3267
|
+
__metadata("design:returntype", Object)
|
|
3268
|
+
], SqlService.prototype, "update", null);
|
|
3269
|
+
__decorate([
|
|
3270
|
+
P(),
|
|
3271
|
+
__metadata("design:type", Function),
|
|
3272
|
+
__metadata("design:paramtypes", [Object]),
|
|
3273
|
+
__metadata("design:returntype", Object)
|
|
3274
|
+
], SqlService.prototype, "delete", null);
|
|
3275
|
+
__decorate([
|
|
3276
|
+
P(),
|
|
3277
|
+
__metadata("design:type", Function),
|
|
3278
|
+
__metadata("design:paramtypes", [Object]),
|
|
3279
|
+
__metadata("design:returntype", Object)
|
|
3280
|
+
], SqlService.prototype, "template", null);
|
|
3281
|
+
__decorate([
|
|
3282
|
+
P(),
|
|
3283
|
+
__metadata("design:type", Function),
|
|
3284
|
+
__metadata("design:paramtypes", [Object]),
|
|
3285
|
+
__metadata("design:returntype", Object)
|
|
3286
|
+
], SqlService.prototype, "select", null);
|
|
3287
|
+
__decorate([
|
|
3288
|
+
P(),
|
|
3289
|
+
__metadata("design:type", Function),
|
|
3290
|
+
__metadata("design:paramtypes", [Object]),
|
|
3291
|
+
__metadata("design:returntype", Object)
|
|
3292
|
+
], SqlService.prototype, "excute", null);
|
|
3293
|
+
__decorate([
|
|
3294
|
+
P(true),
|
|
3295
|
+
__metadata("design:type", Function),
|
|
3296
|
+
__metadata("design:paramtypes", [Object]),
|
|
3297
|
+
__metadata("design:returntype", Object)
|
|
3298
|
+
], SqlService.prototype, "transaction", null);
|
|
3299
|
+
__decorate([
|
|
3300
|
+
P(),
|
|
3301
|
+
__metadata("design:type", Function),
|
|
3302
|
+
__metadata("design:paramtypes", [Object]),
|
|
3303
|
+
__metadata("design:returntype", Object)
|
|
3304
|
+
], SqlService.prototype, "page", null);
|
|
3305
|
+
__decorate([
|
|
3306
|
+
P(),
|
|
3307
|
+
__metadata("design:type", Function),
|
|
3308
|
+
__metadata("design:paramtypes", [Object]),
|
|
3309
|
+
__metadata("design:returntype", Object)
|
|
3310
|
+
], SqlService.prototype, "init", null);
|
|
3311
|
+
__decorate([
|
|
3312
|
+
P(),
|
|
3313
|
+
__metadata("design:type", Function),
|
|
3314
|
+
__metadata("design:paramtypes", [Object]),
|
|
3315
|
+
__metadata("design:returntype", Object)
|
|
3316
|
+
], SqlService.prototype, "close", null);
|
|
3317
|
+
/** 是否进行下一个动作 */
|
|
3318
|
+
const IF_PROCEED = function () {
|
|
3319
|
+
return function (_target, _propertyKey, descriptor) {
|
|
3320
|
+
const fn = descriptor.value;
|
|
3321
|
+
descriptor.value = function () {
|
|
3322
|
+
if (this.if_proceed === true) {
|
|
3323
|
+
// eslint-disable-next-line prefer-rest-params
|
|
3324
|
+
const args = Array.from(arguments);
|
|
3325
|
+
fn.call(this, ...args);
|
|
3326
|
+
}
|
|
3327
|
+
else {
|
|
3328
|
+
this.if_proceed = true;
|
|
3329
|
+
}
|
|
3330
|
+
return this;
|
|
3331
|
+
};
|
|
3332
|
+
};
|
|
3333
|
+
};
|
|
3334
|
+
/*** 是否执行最终查询/操作*/
|
|
3335
|
+
const IF_EXEC = function (def) {
|
|
3336
|
+
return function (_target, _propertyKey, descriptor) {
|
|
3337
|
+
const fn = descriptor.value;
|
|
3338
|
+
descriptor.value = async function () {
|
|
3339
|
+
if (this.if_proceed === true && this.if_exec === true) {
|
|
3340
|
+
// eslint-disable-next-line prefer-rest-params
|
|
3341
|
+
const args = Array.from(arguments);
|
|
3342
|
+
return await fn.call(this, ...args);
|
|
3343
|
+
}
|
|
3344
|
+
else {
|
|
3345
|
+
return def;
|
|
3346
|
+
}
|
|
3347
|
+
};
|
|
3348
|
+
};
|
|
3349
|
+
};
|
|
3350
|
+
class StreamQuery {
|
|
3351
|
+
constructor(service, __fields, __columns) {
|
|
3352
|
+
this._prefix = 0;
|
|
3353
|
+
this._index = 0;
|
|
3354
|
+
this._wheres = [];
|
|
3355
|
+
this._andQuerys = [];
|
|
3356
|
+
this._orQuerys = [];
|
|
3357
|
+
this._paramKeys = {};
|
|
3358
|
+
this._param = {};
|
|
3359
|
+
this.if_proceed = true;
|
|
3360
|
+
this.if_exec = true;
|
|
3361
|
+
this._distinct = false;
|
|
3362
|
+
this._columns = [];
|
|
3363
|
+
this._updateColumns = [];
|
|
3364
|
+
this._groups = [];
|
|
3365
|
+
this._orders = [];
|
|
3366
|
+
this._startRow = 0;
|
|
3367
|
+
this._pageSize = 0;
|
|
3368
|
+
this._prefix = parseInt(`${Math.random() * 1000}`);
|
|
3369
|
+
this._service = service;
|
|
3370
|
+
this[_fields] = __fields;
|
|
3371
|
+
this[_columns] = __columns;
|
|
3372
|
+
}
|
|
3373
|
+
/** 将当前stream重置 */
|
|
3374
|
+
reset() {
|
|
3375
|
+
this._index = 0;
|
|
3376
|
+
this._wheres.length = 0;
|
|
3377
|
+
this._param = {};
|
|
3378
|
+
this._paramKeys = {};
|
|
3379
|
+
this._pageSize = 0;
|
|
3380
|
+
this._startRow = 0;
|
|
3381
|
+
this._orders.length = 0;
|
|
3382
|
+
this._groups.length = 0;
|
|
3383
|
+
this._columns.length = 0;
|
|
3384
|
+
this._updateColumns.length = 0;
|
|
3385
|
+
return this;
|
|
3386
|
+
}
|
|
3387
|
+
// #region 条件
|
|
3388
|
+
/** 为下次链条执行提供条件判断:非异步方法跳过,异步方法不执行并返回默认值 */
|
|
3389
|
+
if(condition) {
|
|
3390
|
+
this.if_proceed = condition;
|
|
3391
|
+
return this;
|
|
3392
|
+
}
|
|
3393
|
+
eqs(keys, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this.__(keys, value, '=', { paramName, skipEmptyString, breakExcuteIfSkip }); }
|
|
3394
|
+
eq(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._(key, value, '=', { paramName, skipEmptyString, breakExcuteIfSkip }); }
|
|
3395
|
+
eqT(t, { name: paramName = '', breakExcuteIfSkip = false } = {}) {
|
|
3396
|
+
let exe = false;
|
|
3397
|
+
if (t) {
|
|
3398
|
+
t = this._service[_transformer](t, {
|
|
3399
|
+
skipNull: true,
|
|
3400
|
+
skipUndefined: true,
|
|
3401
|
+
skipEmptyString: true
|
|
3402
|
+
});
|
|
3403
|
+
const keys = Object.keys(t);
|
|
3404
|
+
if (keys.length > 0) {
|
|
3405
|
+
if (paramName && this._paramKeys[paramName]) {
|
|
3406
|
+
for (const [key, pname] of Object.entries(this._paramKeys[paramName])) {
|
|
3407
|
+
this._param[pname] = t[key];
|
|
3408
|
+
}
|
|
3409
|
+
}
|
|
3410
|
+
else {
|
|
3411
|
+
const paramKeys = {};
|
|
3412
|
+
for (const [key, value] of Object.entries(t)) {
|
|
3413
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3414
|
+
this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} = :${pkey} `);
|
|
3415
|
+
this._param[pkey] = value;
|
|
3416
|
+
if (paramName) {
|
|
3417
|
+
paramKeys[key] = pkey;
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
if (paramName) {
|
|
3421
|
+
this._paramKeys[paramName] = paramKeys;
|
|
3422
|
+
}
|
|
3423
|
+
}
|
|
3424
|
+
exe = true;
|
|
3425
|
+
}
|
|
3426
|
+
}
|
|
3427
|
+
if (breakExcuteIfSkip === true && exe === false) {
|
|
3428
|
+
this.if_exec = false;
|
|
3429
|
+
}
|
|
3430
|
+
return this;
|
|
3431
|
+
}
|
|
3432
|
+
notEq(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._(key, value, '<>', { paramName, skipEmptyString, breakExcuteIfSkip }); }
|
|
3433
|
+
eqWith(key1, key2) { return this._key(key1, key2, '='); }
|
|
3434
|
+
notEqWith(key1, key2) { return this._key(key1, key2, '<>'); }
|
|
3435
|
+
regexp(key, regexp, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._(key, regexp, 'REGEXP', { paramName, skipEmptyString: true, breakExcuteIfSkip }); }
|
|
3436
|
+
notRegexp(key, regexp, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._(key, regexp, 'REGEXP', { paramName, skipEmptyString: true, not: 'NOT', breakExcuteIfSkip }); }
|
|
3437
|
+
/** (key1 << 8) + key2 = value */
|
|
3438
|
+
shiftEq(key1, key2, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._shift(key1, key2, value, '=', { paramName, breakExcuteIfSkip }); }
|
|
3439
|
+
/** (key1 << 8) + key2 <> value */
|
|
3440
|
+
shiftNotEq(key1, key2, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._shift(key1, key2, value, '<>', { paramName, breakExcuteIfSkip }); }
|
|
3441
|
+
grate(key, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._(key, value, '>', { paramName, skipEmptyString: true, breakExcuteIfSkip }); }
|
|
3442
|
+
grateEq(key, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._(key, value, '>=', { paramName, skipEmptyString: true, breakExcuteIfSkip }); }
|
|
3443
|
+
grateWith(key1, key2) { return this._key(key1, key2, '>'); }
|
|
3444
|
+
grateEqWith(key1, key2) { return this._key(key1, key2, '>='); }
|
|
3445
|
+
less(key, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._(key, value, '<', { paramName, skipEmptyString: true, breakExcuteIfSkip }); }
|
|
3446
|
+
lessEq(key, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._(key, value, '<=', { paramName, skipEmptyString: true, breakExcuteIfSkip }); }
|
|
3447
|
+
lessWith(key1, key2) { return this._key(key1, key2, '<'); }
|
|
3448
|
+
lessEqWith(key1, key2) { return this._key(key1, key2, '<='); }
|
|
3449
|
+
like(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, left: '%', right: '%', breakExcuteIfSkip }); }
|
|
3450
|
+
notLike(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, left: '%', right: '%', not: 'NOT', breakExcuteIfSkip }); }
|
|
3451
|
+
leftLike(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, left: '%', breakExcuteIfSkip }); }
|
|
3452
|
+
notLeftLike(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, left: '%', not: 'NOT', breakExcuteIfSkip }); }
|
|
3453
|
+
rightLike(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, right: '%', breakExcuteIfSkip }); }
|
|
3454
|
+
notRightLike(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, right: '%', not: 'NOT', breakExcuteIfSkip }); }
|
|
3455
|
+
PreciseLike(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, breakExcuteIfSkip }); }
|
|
3456
|
+
notPreciseLike(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, not: 'NOT', breakExcuteIfSkip }); }
|
|
3457
|
+
glob(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, left: '%', right: '%', breakExcuteIfSkip, op: 'GLOB' }); }
|
|
3458
|
+
notGlob(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, left: '%', right: '%', not: 'NOT', breakExcuteIfSkip, op: 'GLOB' }); }
|
|
3459
|
+
leftGlob(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, left: '%', breakExcuteIfSkip, op: 'GLOB' }); }
|
|
3460
|
+
notLeftGlob(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, left: '%', not: 'NOT', breakExcuteIfSkip, op: 'GLOB' }); }
|
|
3461
|
+
rightGlob(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, right: '%', breakExcuteIfSkip, op: 'GLOB' }); }
|
|
3462
|
+
notRightGlob(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, right: '%', not: 'NOT', breakExcuteIfSkip, op: 'GLOB' }); }
|
|
3463
|
+
PreciseGlob(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, breakExcuteIfSkip, op: 'GLOB' }); }
|
|
3464
|
+
notPreciseGlob(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._like(key, value, { paramName, skipEmptyString, not: 'NOT', breakExcuteIfSkip, op: 'GLOB' }); }
|
|
3465
|
+
in(key, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._in(key, value, { paramName, breakExcuteIfSkip }); }
|
|
3466
|
+
notIn(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._in(key, value, { paramName, skipEmptyString, not: 'NOT', breakExcuteIfSkip }); }
|
|
3467
|
+
in2(key, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._in2(key, value, { paramName, breakExcuteIfSkip }); }
|
|
3468
|
+
notIn2(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._in2(key, value, { paramName, skipEmptyString, not: 'NOT', breakExcuteIfSkip }); }
|
|
3469
|
+
isNULL(key) { return this._null(key); }
|
|
3470
|
+
isNotNULL(key) { return this._null(key, 'NOT'); }
|
|
3471
|
+
between(key, value1, value2, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._between(key, value1, value2, { paramName, skipEmptyString, breakExcuteIfSkip }); }
|
|
3472
|
+
notBetween(key, value1, value2, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._between(key, value1, value2, { paramName, skipEmptyString, not: 'NOT', breakExcuteIfSkip }); }
|
|
3473
|
+
pow(key, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._pow(key, value, { paramName, breakExcuteIfSkip }); }
|
|
3474
|
+
notPow(key, value, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._pow(key, value, { paramName, not: 'NOT', breakExcuteIfSkip }); }
|
|
3475
|
+
powWith(key, values, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._pow(key, add(...values.map(value => Math.pow(2, +value))), { paramName, breakExcuteIfSkip }); }
|
|
3476
|
+
notPowWith(key, values, { paramName = '', breakExcuteIfSkip = false } = {}) { return this._pow(key, add(...values.map(value => Math.pow(2, +value))), { paramName, not: 'NOT', breakExcuteIfSkip }); }
|
|
3477
|
+
/** MATCH(key1, key2, key3) AGAINST (value) */
|
|
3478
|
+
match(value, keys, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._match(value, keys, { paramName, skipEmptyString, breakExcuteIfSkip }); }
|
|
3479
|
+
/** NOT MATCH(key1, key2, key3) AGAINST (value) */
|
|
3480
|
+
notMatch(value, keys, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._match(value, keys, { paramName, skipEmptyString, not: 'NOT', breakExcuteIfSkip }); }
|
|
3481
|
+
/** MATCH(key1, key2, key3) AGAINST (value) IN BOOLEAN MODE*/
|
|
3482
|
+
matchBoolean(value, keys, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._match(value, keys, { paramName, skipEmptyString, breakExcuteIfSkip, append: 'IN BOOLEAN MODE' }); }
|
|
3483
|
+
/** NOT MATCH(key1, key2, key3) AGAINST (value) IN BOOLEAN MODE */
|
|
3484
|
+
notMatchBoolean(value, keys, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._match(value, keys, { paramName, skipEmptyString, breakExcuteIfSkip, not: 'NOT', append: 'IN BOOLEAN MODE' }); }
|
|
3485
|
+
/** MATCH(key1, key2, key3) AGAINST (value) WITH QUERY EXPANSION*/
|
|
3486
|
+
matchQuery(value, keys, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._match(value, keys, { paramName, skipEmptyString, breakExcuteIfSkip, append: 'WITH QUERY EXPANSION' }); }
|
|
3487
|
+
/** NOT MATCH(key1, key2, key3) AGAINST (value) WITH QUERY EXPANSION*/
|
|
3488
|
+
notMatchQuery(value, keys, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._match(value, keys, { paramName, skipEmptyString, breakExcuteIfSkip, not: 'NOT', append: 'WITH QUERY EXPANSION' }); }
|
|
3489
|
+
includes(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._includes(key, value, { paramName, skipEmptyString, breakExcuteIfSkip }); }
|
|
3490
|
+
notIncludes(key, value, { paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) { return this._includes(key, value, { paramName, skipEmptyString, not: 'NOT', breakExcuteIfSkip }); }
|
|
3491
|
+
and(fn) {
|
|
3492
|
+
if (fn instanceof StreamQuery) {
|
|
3493
|
+
this._andQuerys.push(fn);
|
|
3494
|
+
}
|
|
3495
|
+
else {
|
|
3496
|
+
const stream = new StreamQuery(this._service, this[_fields], this[_columns]);
|
|
3497
|
+
const ret = fn(stream);
|
|
3498
|
+
if (ret !== false) {
|
|
3499
|
+
this._andQuerys.push(stream);
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
return this;
|
|
3503
|
+
}
|
|
3504
|
+
or(fn) {
|
|
3505
|
+
if (fn instanceof StreamQuery) {
|
|
3506
|
+
this._andQuerys.push(fn);
|
|
3507
|
+
}
|
|
3508
|
+
else {
|
|
3509
|
+
const stream = new StreamQuery(this._service, this[_fields], this[_columns]);
|
|
3510
|
+
const ret = fn(stream);
|
|
3511
|
+
if (ret !== false) {
|
|
3512
|
+
this._orQuerys.push(stream);
|
|
3513
|
+
}
|
|
3514
|
+
}
|
|
3515
|
+
return this;
|
|
3516
|
+
}
|
|
3517
|
+
groupBy(...keys) { this._groups.push(...keys.map(key => `${this[_fields][String(key)]?.C2()}`)); return this; }
|
|
3518
|
+
groupBy2(...keys) { this._groups.push(...keys.map(key => `${this[_fields][String(key)]?.C2()}`)); return this; }
|
|
3519
|
+
asc(...keys) { this._orders.push(...keys.map(key => `${this[_fields][String(key)]?.C2()} ASC`)); return this; }
|
|
3520
|
+
asc2(...keys) { this._orders.push(...keys.map(key => `${this[_fields][String(key)]?.C2()} ASC`)); return this; }
|
|
3521
|
+
desc(...keys) { this._orders.push(...keys.map(key => `${this[_fields][String(key)]?.C2()} DESC`)); return this; }
|
|
3522
|
+
desc2(...keys) { this._orders.push(...keys.map(key => `${this[_fields][String(key)]?.C2()} ASC`)); return this; }
|
|
3523
|
+
limit(startRow, pageSize) { this._startRow = startRow; this._pageSize = pageSize; return this; }
|
|
3524
|
+
page(pageNumber, pageSize) { this._startRow = ((pageNumber || 1) - 1) * pageSize; this._pageSize = pageSize; return this; }
|
|
3525
|
+
distinct(on = true) { this._distinct = on; return this; }
|
|
3526
|
+
countDistinct(key, countName) { this._columns.push(`COUNT(DISTINCT ${this[_fields][String(key)]?.C2()}) ${countName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
|
|
3527
|
+
count(countName) { this._columns.push(`COUNT(1) ${countName ?? 'ct'}`); return this; }
|
|
3528
|
+
sum(key, legName, distinct) { this._columns.push(`SUM(${distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}) ${legName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
|
|
3529
|
+
avg(key, legName, distinct) { this._columns.push(`AVG(${distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}) ${legName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
|
|
3530
|
+
max(key, legName, distinct) { this._columns.push(`MAX(${distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}) ${legName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
|
|
3531
|
+
min(key, legName, distinct) { this._columns.push(`MIN(${distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}) ${legName || `${this[_fields][String(key)]?.C2()}`}`); return this; }
|
|
3532
|
+
groupConcat(key, param) {
|
|
3533
|
+
this._columns.push(`GROUP_CONCAT(
|
|
3534
|
+
${param && param.distinct ? 'DISTINCT' : ''} ${this[_fields][String(key)]?.C2()}
|
|
3535
|
+
${param && param.asc && param.asc.length > 0 ? `ORDER BY ${param.asc.map(i => `${this[_fields][String(i)]?.C2()} ASC`)} ` : ''}
|
|
3536
|
+
${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`)} ` : ''}
|
|
3537
|
+
SEPARATOR '${param && param.separator || ','}'
|
|
3538
|
+
) ${param && param.groupName || `${this[_fields][String(key)]?.C2()}`}`);
|
|
3539
|
+
return this;
|
|
3540
|
+
}
|
|
3541
|
+
select(...key) { this._columns.push(...(key.map(k => this[_fields][String(k)].C3()))); return this; }
|
|
3542
|
+
select2(sql, param) { this._columns.push(`${sql}`); Object.assign(this._param, param); return this; }
|
|
3543
|
+
update(key, value) { this._updates ?? (this._updates = {}); this._updates[this[_fields][String(key)]?.C2()] = value; return this; }
|
|
3544
|
+
update2(sql, param) { this._updateColumns.push(sql); Object.assign(this._param, param); return this; }
|
|
3545
|
+
updateT(t) {
|
|
3546
|
+
this._updates ?? (this._updates = {});
|
|
3547
|
+
for (const [key, value] of Object.entries(t)) {
|
|
3548
|
+
this._updates[this[_fields][String(key)]?.C2()] = value;
|
|
3549
|
+
}
|
|
3550
|
+
Object.assign(this._updates, t);
|
|
3551
|
+
return this;
|
|
3552
|
+
}
|
|
3553
|
+
replace(key, valueToFind, valueToReplace) {
|
|
3554
|
+
const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
|
|
3555
|
+
this._updateColumns.push(` ${this[_fields][String(key)]?.C2()} = REPLACE(${this[_fields][String(key)]?.C2()}, :${pkey1}, :${pkey2}) `);
|
|
3556
|
+
this._param[pkey1] = valueToFind;
|
|
3557
|
+
this._param[pkey2] = valueToReplace;
|
|
3558
|
+
return this;
|
|
3559
|
+
}
|
|
3560
|
+
excuteSelect(option) {
|
|
3561
|
+
option ?? (option = {});
|
|
3562
|
+
option.sync ?? (option.sync = SyncMode.Async);
|
|
3563
|
+
option.selectResult ?? (option.selectResult = SelectResult.RS_CS);
|
|
3564
|
+
const { where, params } = this._where();
|
|
3565
|
+
let sql = `
|
|
3566
|
+
SELECT
|
|
3567
|
+
${this._distinct ? 'DISTINCT' : ''} ${this._columns && this._columns.length > 0 ? this._columns.join(',') : this[_columns].map(key => this[_fields][String(key)]?.C3()).join(',')}
|
|
3568
|
+
FROM ${option.tableName ?? this._service[_tableName]}
|
|
3569
|
+
${where ? ' WHERE ' : ''}
|
|
3570
|
+
${where}
|
|
3571
|
+
${this._groups.length > 0 ? `GROUP BY ${this._groups.join(',')} ` : ''}
|
|
3572
|
+
${this._orders.length > 0 ? `ORDER BY ${this._orders.join(',')} ` : ''}
|
|
3573
|
+
`;
|
|
3574
|
+
if (this._startRow && this._pageSize) {
|
|
3575
|
+
sql += `LIMIT ${this._startRow}, ${this._pageSize}`;
|
|
3576
|
+
}
|
|
3577
|
+
else if (this._startRow) {
|
|
3578
|
+
sql += `LIMIT ${this._startRow}`;
|
|
3579
|
+
}
|
|
3580
|
+
if (option.sync === SyncMode.Async) {
|
|
3581
|
+
switch (option.selectResult) {
|
|
3582
|
+
case SelectResult.RS_CS: return this._service.select({ ...option, sync: SyncMode.Async, selectResult: SelectResult.RS_CS, sql, params });
|
|
3583
|
+
case SelectResult.RS_C: return this._service.select({ ...option, sync: SyncMode.Async, selectResult: SelectResult.RS_C, sql, params });
|
|
3584
|
+
case SelectResult.RS_CS_List: return this._service.select({ ...option, sync: SyncMode.Async, selectResult: SelectResult.RS_CS_List, sql, params });
|
|
3585
|
+
case SelectResult.RS_C_List: return this._service.select({ ...option, sync: SyncMode.Async, selectResult: SelectResult.RS_C_List, sql, params });
|
|
3586
|
+
case SelectResult.R_CS_Assert: return this._service.select({ ...option, sync: SyncMode.Async, selectResult: SelectResult.R_CS_Assert, sql, params });
|
|
3587
|
+
case SelectResult.R_C_Assert: return this._service.select({ ...option, sync: SyncMode.Async, selectResult: SelectResult.R_C_Assert, sql, params });
|
|
3588
|
+
case SelectResult.R_CS_NotSure: return this._service.select({ ...option, sync: SyncMode.Async, selectResult: SelectResult.R_CS_NotSure, sql, params });
|
|
3589
|
+
case SelectResult.R_C_NotSure: return this._service.select({ ...option, sync: SyncMode.Async, selectResult: SelectResult.R_C_NotSure, sql, params });
|
|
3590
|
+
}
|
|
3591
|
+
}
|
|
3592
|
+
else {
|
|
3593
|
+
switch (option.selectResult) {
|
|
3594
|
+
case SelectResult.RS_CS: return this._service.select({ ...option, sync: SyncMode.Sync, selectResult: SelectResult.RS_CS, sql, params });
|
|
3595
|
+
case SelectResult.RS_C: return this._service.select({ ...option, sync: SyncMode.Sync, selectResult: SelectResult.RS_C, sql, params });
|
|
3596
|
+
case SelectResult.RS_CS_List: return this._service.select({ ...option, sync: SyncMode.Sync, selectResult: SelectResult.RS_CS_List, sql, params });
|
|
3597
|
+
case SelectResult.RS_C_List: return this._service.select({ ...option, sync: SyncMode.Sync, selectResult: SelectResult.RS_C_List, sql, params });
|
|
3598
|
+
case SelectResult.R_CS_Assert: return this._service.select({ ...option, sync: SyncMode.Sync, selectResult: SelectResult.R_CS_Assert, sql, params });
|
|
3599
|
+
case SelectResult.R_C_Assert: return this._service.select({ ...option, sync: SyncMode.Sync, selectResult: SelectResult.R_C_Assert, sql, params });
|
|
3600
|
+
case SelectResult.R_CS_NotSure: return this._service.select({ ...option, sync: SyncMode.Sync, selectResult: SelectResult.R_CS_NotSure, sql, params });
|
|
3601
|
+
case SelectResult.R_C_NotSure: return this._service.select({ ...option, sync: SyncMode.Sync, selectResult: SelectResult.R_C_NotSure, sql, params });
|
|
3602
|
+
}
|
|
3603
|
+
}
|
|
3604
|
+
}
|
|
3605
|
+
excutePage(option) {
|
|
3606
|
+
option ?? (option = {});
|
|
3607
|
+
option.sync ?? (option.sync = SyncMode.Async);
|
|
3608
|
+
const { where, params } = this._where();
|
|
3609
|
+
const result = {
|
|
3610
|
+
records: [],
|
|
3611
|
+
size: 0,
|
|
3612
|
+
total: 0
|
|
3613
|
+
};
|
|
3614
|
+
let sql = `
|
|
3615
|
+
SELECT
|
|
3616
|
+
${this._distinct ? 'DISTINCT' : ''} ${this._columns && this._columns.length > 0 ? this._columns.join(',') : this[_columns].map(key => this[_fields][String(key)]?.C3()).join(',')}
|
|
3617
|
+
FROM ${option.tableName ?? this._service[_tableName]}
|
|
3618
|
+
${where ? ' WHERE ' : ''}
|
|
3619
|
+
${where}
|
|
3620
|
+
${this._groups.length > 0 ? `GROUP BY ${this._groups.join(',')} ` : ''}
|
|
3621
|
+
${this._orders.length > 0 ? `ORDER BY ${this._orders.join(',')} ` : ''}
|
|
3622
|
+
`;
|
|
3623
|
+
if (this._startRow && this._pageSize) {
|
|
3624
|
+
sql += `LIMIT ${this._startRow}, ${this._pageSize}`;
|
|
3625
|
+
}
|
|
3626
|
+
else if (this._startRow) {
|
|
3627
|
+
sql += `LIMIT ${this._startRow}`;
|
|
3628
|
+
}
|
|
3629
|
+
const sqlCount = `
|
|
3630
|
+
SELECT COUNT(1)
|
|
3631
|
+
FROM ${option.tableName ?? this._service[_tableName]}
|
|
3632
|
+
${where ? ' WHERE ' : ''}
|
|
3633
|
+
${where}
|
|
3634
|
+
${this._groups.length > 0 ? `GROUP BY ${this._groups.join(',')} ` : ''}
|
|
3635
|
+
${this._orders.length > 0 ? `ORDER BY ${this._orders.join(',')} ` : ''}
|
|
3636
|
+
`;
|
|
3637
|
+
if (option.sync === SyncMode.Sync) {
|
|
3638
|
+
result.total = this._service.select({
|
|
3639
|
+
...option,
|
|
3640
|
+
params,
|
|
3641
|
+
sql: sqlCount,
|
|
3642
|
+
sync: SyncMode.Sync,
|
|
3643
|
+
selectResult: SelectResult.R_C_Assert
|
|
3644
|
+
});
|
|
3645
|
+
result.size = calc(result.total)
|
|
3646
|
+
.add(this._pageSize - 1)
|
|
3647
|
+
.div(this._pageSize)
|
|
3648
|
+
.round(0, 2)
|
|
3649
|
+
.over();
|
|
3650
|
+
result.records = this._service.select({
|
|
3651
|
+
...option,
|
|
3652
|
+
params,
|
|
3653
|
+
sql,
|
|
3654
|
+
sync: SyncMode.Sync,
|
|
3655
|
+
selectResult: SelectResult.RS_CS
|
|
3656
|
+
});
|
|
3657
|
+
return result;
|
|
3658
|
+
}
|
|
3659
|
+
else {
|
|
3660
|
+
return new Promise(async (resolve, reject) => {
|
|
3661
|
+
try {
|
|
3662
|
+
result.total = await this._service.select({
|
|
3663
|
+
...option,
|
|
3664
|
+
params,
|
|
3665
|
+
sql: sqlCount,
|
|
3666
|
+
sync: SyncMode.Async,
|
|
3667
|
+
selectResult: SelectResult.R_C_Assert
|
|
3668
|
+
});
|
|
3669
|
+
result.size = calc(result.total)
|
|
3670
|
+
.add(this._pageSize - 1)
|
|
3671
|
+
.div(this._pageSize)
|
|
3672
|
+
.round(0, 2)
|
|
3673
|
+
.over();
|
|
3674
|
+
result.records = await this._service.select({
|
|
3675
|
+
...option,
|
|
3676
|
+
params,
|
|
3677
|
+
sql,
|
|
3678
|
+
sync: SyncMode.Async,
|
|
3679
|
+
selectResult: SelectResult.RS_CS
|
|
3680
|
+
});
|
|
3681
|
+
resolve(result);
|
|
3682
|
+
}
|
|
3683
|
+
catch (error) {
|
|
3684
|
+
reject(error);
|
|
3685
|
+
}
|
|
3686
|
+
});
|
|
3687
|
+
}
|
|
3688
|
+
}
|
|
3689
|
+
excuteUpdate(option) {
|
|
3690
|
+
option ?? (option = {});
|
|
3691
|
+
option.sync ?? (option.sync = SyncMode.Async);
|
|
3692
|
+
const { where, params } = this._where();
|
|
3693
|
+
const sets = new Array(...this._updateColumns);
|
|
3694
|
+
if (this._updates) {
|
|
3695
|
+
for (const [K, V] of Object.entries(this._updates)) {
|
|
3696
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3697
|
+
sets.push(` ${K} = :${pkey} `);
|
|
3698
|
+
params[pkey] = V;
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
if (sets.length > 0) {
|
|
3702
|
+
const sql = `UPDATE ${option.tableName ?? this._service[_tableName]} SET ${sets.join(',')}
|
|
3703
|
+
${where ? ' WHERE ' : ''}
|
|
3704
|
+
${where}
|
|
3705
|
+
`;
|
|
3706
|
+
if (option.sync === SyncMode.Async) {
|
|
3707
|
+
return this._service.excute({ ...option, sync: SyncMode.Async, sql, params });
|
|
3708
|
+
}
|
|
3709
|
+
else {
|
|
3710
|
+
return this._service.excute({ ...option, sync: SyncMode.Sync, sql, params });
|
|
3711
|
+
}
|
|
3712
|
+
}
|
|
3713
|
+
else {
|
|
3714
|
+
return 0;
|
|
3715
|
+
}
|
|
3716
|
+
}
|
|
3717
|
+
excuteDelete(option) {
|
|
3718
|
+
option ?? (option = {});
|
|
3719
|
+
option.sync ?? (option.sync = SyncMode.Async);
|
|
3720
|
+
const { where, params } = this._where();
|
|
3721
|
+
const sql = `DELETE FROM ${option.tableName ?? this._service[_tableName]}
|
|
3722
|
+
${where ? ' WHERE ' : ''}
|
|
3723
|
+
${where}
|
|
3724
|
+
`;
|
|
3725
|
+
if (option.sync === SyncMode.Async) {
|
|
3726
|
+
return this._service.excute({ ...option, sync: SyncMode.Async, sql, params });
|
|
3727
|
+
}
|
|
3728
|
+
else {
|
|
3729
|
+
return this._service.excute({ ...option, sync: SyncMode.Sync, sql, params });
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
_where() {
|
|
3733
|
+
const wheres = new Array();
|
|
3734
|
+
const sql = this._wheres.join(' ');
|
|
3735
|
+
if (sql) {
|
|
3736
|
+
wheres.push(`(${sql.replace(/^and|^or/i, '')})`);
|
|
3737
|
+
}
|
|
3738
|
+
if (this._orQuerys.length > 0) {
|
|
3739
|
+
for (const query of this._orQuerys) {
|
|
3740
|
+
const { where, params } = query._where();
|
|
3741
|
+
if (where) {
|
|
3742
|
+
wheres.push(` OR (${where}) `);
|
|
3743
|
+
}
|
|
3744
|
+
Object.assign(this._param, params);
|
|
3745
|
+
}
|
|
3746
|
+
}
|
|
3747
|
+
if (this._andQuerys.length > 0) {
|
|
3748
|
+
for (const query of this._andQuerys) {
|
|
3749
|
+
const { where, params } = query._where();
|
|
3750
|
+
if (where) {
|
|
3751
|
+
wheres.push(` AND (${where}) `);
|
|
3752
|
+
}
|
|
3753
|
+
Object.assign(this._param, params);
|
|
3754
|
+
}
|
|
3755
|
+
}
|
|
3756
|
+
return { where: wheres.join(' '), params: this._param };
|
|
3757
|
+
}
|
|
3758
|
+
_(key, value, op, { not = '', paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) {
|
|
3759
|
+
if (value === null
|
|
3760
|
+
|| value === undefined
|
|
3761
|
+
|| (emptyString(`${value ?? ''}`) && skipEmptyString === true)) {
|
|
3762
|
+
if (breakExcuteIfSkip === true) {
|
|
3763
|
+
this.if_exec = false;
|
|
3764
|
+
}
|
|
3765
|
+
return this;
|
|
3766
|
+
}
|
|
3767
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3768
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3769
|
+
}
|
|
3770
|
+
else {
|
|
3771
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3772
|
+
this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} ${not} ${op} :${pkey} `);
|
|
3773
|
+
this._param[pkey] = value;
|
|
3774
|
+
if (paramName) {
|
|
3775
|
+
this._paramKeys[paramName] = pkey;
|
|
3776
|
+
}
|
|
3777
|
+
}
|
|
3778
|
+
return this;
|
|
3779
|
+
}
|
|
3780
|
+
__(keys, value, op, { not = '', paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) {
|
|
3781
|
+
if (value === null
|
|
3782
|
+
|| value === undefined
|
|
3783
|
+
|| (emptyString(`${value ?? ''}`) && skipEmptyString === true)) {
|
|
3784
|
+
if (breakExcuteIfSkip === true) {
|
|
3785
|
+
this.if_exec = false;
|
|
3786
|
+
}
|
|
3787
|
+
return this;
|
|
3788
|
+
}
|
|
3789
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3790
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3791
|
+
}
|
|
3792
|
+
else {
|
|
3793
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3794
|
+
this._wheres.push(`AND (${keys.map(key => `${this[_fields][String(key)]?.C2()} ${not} ${op} :${pkey} `).join(' OR ')})`);
|
|
3795
|
+
this._param[pkey] = value;
|
|
3796
|
+
if (paramName) {
|
|
3797
|
+
this._paramKeys[paramName] = pkey;
|
|
3798
|
+
}
|
|
3799
|
+
}
|
|
3800
|
+
return this;
|
|
3801
|
+
}
|
|
3802
|
+
_null(key, not = '') {
|
|
3803
|
+
this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} IS ${not} NULL`);
|
|
3804
|
+
return this;
|
|
3805
|
+
}
|
|
3806
|
+
_key(key1, key2, op, not = '') {
|
|
3807
|
+
this._wheres.push(`AND ${this[_fields][String(key1)]?.C2()} ${not} ${op} ${this[_fields][String(key2)]?.C2()} `);
|
|
3808
|
+
return this;
|
|
3809
|
+
}
|
|
3810
|
+
_between(key, value1, value2, { not = '', paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) {
|
|
3811
|
+
if (value1 === null
|
|
3812
|
+
|| value1 === undefined
|
|
3813
|
+
|| (emptyString(`${value1 ?? ''}`) && skipEmptyString === true)
|
|
3814
|
+
|| value2 === null
|
|
3815
|
+
|| value2 === undefined
|
|
3816
|
+
|| (emptyString(`${value2 ?? ''}`) && skipEmptyString === true)) {
|
|
3817
|
+
if (breakExcuteIfSkip === true) {
|
|
3818
|
+
this.if_exec = false;
|
|
3819
|
+
}
|
|
3820
|
+
return this;
|
|
3821
|
+
}
|
|
3822
|
+
if (paramName && this._paramKeys[paramName]) {
|
|
3823
|
+
this._param[this._paramKeys[paramName][0]] = value1;
|
|
3824
|
+
this._param[this._paramKeys[paramName][1]] = value2;
|
|
3825
|
+
}
|
|
3826
|
+
else {
|
|
3827
|
+
const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
|
|
3828
|
+
this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} ${not} BETWEEN :${pkey1} AND :${pkey2}`);
|
|
3829
|
+
this._param[pkey1] = value1;
|
|
3830
|
+
this._param[pkey2] = value2;
|
|
3831
|
+
if (paramName) {
|
|
3832
|
+
this._paramKeys[paramName] = [pkey1, pkey2];
|
|
3833
|
+
}
|
|
3834
|
+
}
|
|
3835
|
+
return this;
|
|
3836
|
+
}
|
|
3837
|
+
_in(key, value, { not = '', paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) {
|
|
3838
|
+
if (value && value.length > 0 && skipEmptyString === true) {
|
|
3839
|
+
value = value.filter(v => !emptyString(`${v ?? ''}`));
|
|
3840
|
+
}
|
|
3841
|
+
if (value && value.length > 0) {
|
|
3842
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3843
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3844
|
+
}
|
|
3845
|
+
else {
|
|
3846
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3847
|
+
this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} ${not} IN (:${pkey}) `);
|
|
3848
|
+
this._param[pkey] = value;
|
|
3849
|
+
if (paramName) {
|
|
3850
|
+
this._paramKeys[paramName] = pkey;
|
|
3851
|
+
}
|
|
3852
|
+
}
|
|
3853
|
+
}
|
|
3854
|
+
else if (breakExcuteIfSkip !== true) {
|
|
3855
|
+
this.if_exec = false;
|
|
3856
|
+
}
|
|
3857
|
+
return this;
|
|
3858
|
+
}
|
|
3859
|
+
_in2(key, value, { not = '', paramName = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) {
|
|
3860
|
+
const skip = emptyString(`${value ?? ''}`) && skipEmptyString === true;
|
|
3861
|
+
if (!skip) {
|
|
3862
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3863
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3864
|
+
}
|
|
3865
|
+
else {
|
|
3866
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3867
|
+
this._wheres.push(`AND :${pkey} ${not} IN (${key.map(k => this[_fields][String(k)]?.C2()).join(',')}) `);
|
|
3868
|
+
this._param[pkey] = value;
|
|
3869
|
+
if (paramName) {
|
|
3870
|
+
this._paramKeys[paramName] = pkey;
|
|
3871
|
+
}
|
|
3872
|
+
}
|
|
3873
|
+
}
|
|
3874
|
+
else if (breakExcuteIfSkip !== true) {
|
|
3875
|
+
this.if_exec = false;
|
|
3876
|
+
}
|
|
3877
|
+
return this;
|
|
3878
|
+
}
|
|
3879
|
+
_shift(key1, key2, value, op, { not = '', paramName = '', breakExcuteIfSkip = false } = {}) {
|
|
3880
|
+
if (value === null
|
|
3881
|
+
|| value === undefined
|
|
3882
|
+
|| emptyString(`${value ?? ''}`)) {
|
|
3883
|
+
if (breakExcuteIfSkip === true) {
|
|
3884
|
+
this.if_exec = false;
|
|
3885
|
+
}
|
|
3886
|
+
return this;
|
|
3887
|
+
}
|
|
3888
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3889
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3890
|
+
}
|
|
3891
|
+
else {
|
|
3892
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3893
|
+
this._wheres.push(`AND (${this[_fields][String(key1)]?.C2()} << 8) + ${this[_fields][String(key2)]?.C2()} ${not} ${op} :${pkey} `);
|
|
3894
|
+
this._param[pkey] = value;
|
|
3895
|
+
if (paramName) {
|
|
3896
|
+
this._paramKeys[paramName] = pkey;
|
|
3897
|
+
}
|
|
3898
|
+
}
|
|
3899
|
+
return this;
|
|
3900
|
+
}
|
|
3901
|
+
_match(value, keys, { paramName = '', not = '', append = '', skipEmptyString = true, breakExcuteIfSkip = false } = {}) {
|
|
3902
|
+
if (value === null
|
|
3903
|
+
|| value === undefined
|
|
3904
|
+
|| emptyString(`${value ?? ''}`)) {
|
|
3905
|
+
if (breakExcuteIfSkip === true) {
|
|
3906
|
+
this.if_exec = false;
|
|
3907
|
+
}
|
|
3908
|
+
return this;
|
|
3909
|
+
}
|
|
3910
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3911
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3912
|
+
}
|
|
3913
|
+
else {
|
|
3914
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3915
|
+
this._wheres.push(`AND ${not} MATCH(${keys.map(key => this[_fields][String(key)]?.C2()).join(',')}) AGAINST (:${pkey} ${append ?? ''})`);
|
|
3916
|
+
this._param[pkey] = value;
|
|
3917
|
+
if (paramName) {
|
|
3918
|
+
this._paramKeys[paramName] = pkey;
|
|
3919
|
+
}
|
|
3920
|
+
}
|
|
3921
|
+
return this;
|
|
3922
|
+
}
|
|
3923
|
+
_pow(key, value, { not = '', paramName = '', breakExcuteIfSkip = false } = {}) {
|
|
3924
|
+
if (value === null
|
|
3925
|
+
|| value === undefined
|
|
3926
|
+
|| emptyString(`${value ?? ''}`)) {
|
|
3927
|
+
if (breakExcuteIfSkip === true) {
|
|
3928
|
+
this.if_exec = false;
|
|
3929
|
+
}
|
|
3930
|
+
return this;
|
|
3931
|
+
}
|
|
3932
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3933
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3934
|
+
}
|
|
3935
|
+
else {
|
|
3936
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3937
|
+
this._wheres.push(`AND ${not} POW(2, ${this[_fields][String(key)]?.C2()}) & :${pkey}`);
|
|
3938
|
+
this._param[pkey] = value;
|
|
3939
|
+
if (paramName) {
|
|
3940
|
+
this._paramKeys[paramName] = pkey;
|
|
3941
|
+
}
|
|
3942
|
+
}
|
|
3943
|
+
return this;
|
|
3944
|
+
}
|
|
3945
|
+
_like(key, value, { not = '', left = '', right = '', paramName = '', op = 'LIKE', skipEmptyString = true, breakExcuteIfSkip = false } = {}) {
|
|
3946
|
+
if (value === null
|
|
3947
|
+
|| value === undefined
|
|
3948
|
+
|| (emptyString(`${value ?? ''}`) && skipEmptyString === true)) {
|
|
3949
|
+
if (breakExcuteIfSkip === true) {
|
|
3950
|
+
this.if_exec = false;
|
|
3951
|
+
}
|
|
3952
|
+
return this;
|
|
3953
|
+
}
|
|
3954
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3955
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3956
|
+
}
|
|
3957
|
+
else {
|
|
3958
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3959
|
+
this._wheres.push(`AND ${this[_fields][String(key)]?.C2()} ${not} ${op} CONCAT('${left}', :${pkey}, '${right}') `);
|
|
3960
|
+
this._param[pkey] = value;
|
|
3961
|
+
if (paramName) {
|
|
3962
|
+
this._paramKeys[paramName] = pkey;
|
|
3963
|
+
}
|
|
3964
|
+
}
|
|
3965
|
+
return this;
|
|
3966
|
+
}
|
|
3967
|
+
_includes(key, value, { not = '', paramName = '', skipEmptyString = true, breakExcuteIfSkip = true } = {}) {
|
|
3968
|
+
if (value === null
|
|
3969
|
+
|| value === undefined
|
|
3970
|
+
|| (emptyString(`${value ?? ''}`) && skipEmptyString === true)) {
|
|
3971
|
+
if (breakExcuteIfSkip === true) {
|
|
3972
|
+
this.if_exec = false;
|
|
3973
|
+
}
|
|
3974
|
+
return this;
|
|
3975
|
+
}
|
|
3976
|
+
if (paramName !== undefined && this._paramKeys.hasOwnProperty(paramName)) {
|
|
3977
|
+
this._param[this._paramKeys[paramName]] = value;
|
|
3978
|
+
}
|
|
3979
|
+
else {
|
|
3980
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3981
|
+
this._wheres.push(`AND LOCATE(${this[_fields][String(key)]?.C2()}, :${pkey}) ${not ? '=' : '>'} 0`);
|
|
3982
|
+
this._param[pkey] = value;
|
|
3983
|
+
if (paramName) {
|
|
3984
|
+
this._paramKeys[paramName] = pkey;
|
|
3985
|
+
}
|
|
3986
|
+
}
|
|
3987
|
+
return this;
|
|
3988
|
+
}
|
|
3989
|
+
}
|
|
3990
|
+
__decorate([
|
|
3991
|
+
IF_PROCEED(),
|
|
3992
|
+
__metadata("design:type", Function),
|
|
3993
|
+
__metadata("design:paramtypes", [Boolean]),
|
|
3994
|
+
__metadata("design:returntype", void 0)
|
|
3995
|
+
], StreamQuery.prototype, "if", null);
|
|
3996
|
+
__decorate([
|
|
3997
|
+
IF_PROCEED(),
|
|
3998
|
+
__metadata("design:type", Function),
|
|
3999
|
+
__metadata("design:paramtypes", [Array, Object, Object]),
|
|
4000
|
+
__metadata("design:returntype", void 0)
|
|
4001
|
+
], StreamQuery.prototype, "eqs", null);
|
|
4002
|
+
__decorate([
|
|
4003
|
+
IF_PROCEED(),
|
|
4004
|
+
__metadata("design:type", Function),
|
|
4005
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4006
|
+
__metadata("design:returntype", void 0)
|
|
4007
|
+
], StreamQuery.prototype, "eq", null);
|
|
4008
|
+
__decorate([
|
|
4009
|
+
IF_PROCEED(),
|
|
4010
|
+
__metadata("design:type", Function),
|
|
4011
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4012
|
+
__metadata("design:returntype", void 0)
|
|
4013
|
+
], StreamQuery.prototype, "eqT", null);
|
|
4014
|
+
__decorate([
|
|
4015
|
+
IF_PROCEED(),
|
|
4016
|
+
__metadata("design:type", Function),
|
|
4017
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4018
|
+
__metadata("design:returntype", void 0)
|
|
4019
|
+
], StreamQuery.prototype, "notEq", null);
|
|
4020
|
+
__decorate([
|
|
4021
|
+
IF_PROCEED(),
|
|
4022
|
+
__metadata("design:type", Function),
|
|
4023
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4024
|
+
__metadata("design:returntype", void 0)
|
|
4025
|
+
], StreamQuery.prototype, "eqWith", null);
|
|
4026
|
+
__decorate([
|
|
4027
|
+
IF_PROCEED(),
|
|
4028
|
+
__metadata("design:type", Function),
|
|
4029
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4030
|
+
__metadata("design:returntype", void 0)
|
|
4031
|
+
], StreamQuery.prototype, "notEqWith", null);
|
|
4032
|
+
__decorate([
|
|
4033
|
+
IF_PROCEED(),
|
|
4034
|
+
__metadata("design:type", Function),
|
|
4035
|
+
__metadata("design:paramtypes", [Object, String, Object]),
|
|
4036
|
+
__metadata("design:returntype", void 0)
|
|
4037
|
+
], StreamQuery.prototype, "regexp", null);
|
|
4038
|
+
__decorate([
|
|
4039
|
+
IF_PROCEED(),
|
|
4040
|
+
__metadata("design:type", Function),
|
|
4041
|
+
__metadata("design:paramtypes", [Object, String, Object]),
|
|
4042
|
+
__metadata("design:returntype", void 0)
|
|
4043
|
+
], StreamQuery.prototype, "notRegexp", null);
|
|
4044
|
+
__decorate([
|
|
4045
|
+
IF_PROCEED(),
|
|
4046
|
+
__metadata("design:type", Function),
|
|
4047
|
+
__metadata("design:paramtypes", [Object, Object, Number, Object]),
|
|
4048
|
+
__metadata("design:returntype", void 0)
|
|
4049
|
+
], StreamQuery.prototype, "shiftEq", null);
|
|
4050
|
+
__decorate([
|
|
4051
|
+
IF_PROCEED(),
|
|
4052
|
+
__metadata("design:type", Function),
|
|
4053
|
+
__metadata("design:paramtypes", [Object, Object, Number, Object]),
|
|
4054
|
+
__metadata("design:returntype", void 0)
|
|
4055
|
+
], StreamQuery.prototype, "shiftNotEq", null);
|
|
4056
|
+
__decorate([
|
|
4057
|
+
IF_PROCEED(),
|
|
4058
|
+
__metadata("design:type", Function),
|
|
4059
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4060
|
+
__metadata("design:returntype", void 0)
|
|
4061
|
+
], StreamQuery.prototype, "grate", null);
|
|
4062
|
+
__decorate([
|
|
4063
|
+
IF_PROCEED(),
|
|
4064
|
+
__metadata("design:type", Function),
|
|
4065
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4066
|
+
__metadata("design:returntype", void 0)
|
|
4067
|
+
], StreamQuery.prototype, "grateEq", null);
|
|
4068
|
+
__decorate([
|
|
4069
|
+
IF_PROCEED(),
|
|
4070
|
+
__metadata("design:type", Function),
|
|
4071
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4072
|
+
__metadata("design:returntype", void 0)
|
|
4073
|
+
], StreamQuery.prototype, "grateWith", null);
|
|
4074
|
+
__decorate([
|
|
4075
|
+
IF_PROCEED(),
|
|
4076
|
+
__metadata("design:type", Function),
|
|
4077
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4078
|
+
__metadata("design:returntype", void 0)
|
|
4079
|
+
], StreamQuery.prototype, "grateEqWith", null);
|
|
4080
|
+
__decorate([
|
|
4081
|
+
IF_PROCEED(),
|
|
4082
|
+
__metadata("design:type", Function),
|
|
4083
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4084
|
+
__metadata("design:returntype", void 0)
|
|
4085
|
+
], StreamQuery.prototype, "less", null);
|
|
4086
|
+
__decorate([
|
|
4087
|
+
IF_PROCEED(),
|
|
4088
|
+
__metadata("design:type", Function),
|
|
4089
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4090
|
+
__metadata("design:returntype", void 0)
|
|
4091
|
+
], StreamQuery.prototype, "lessEq", null);
|
|
4092
|
+
__decorate([
|
|
4093
|
+
IF_PROCEED(),
|
|
4094
|
+
__metadata("design:type", Function),
|
|
4095
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4096
|
+
__metadata("design:returntype", void 0)
|
|
4097
|
+
], StreamQuery.prototype, "lessWith", null);
|
|
4098
|
+
__decorate([
|
|
4099
|
+
IF_PROCEED(),
|
|
4100
|
+
__metadata("design:type", Function),
|
|
4101
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4102
|
+
__metadata("design:returntype", void 0)
|
|
4103
|
+
], StreamQuery.prototype, "lessEqWith", null);
|
|
4104
|
+
__decorate([
|
|
4105
|
+
IF_PROCEED(),
|
|
4106
|
+
__metadata("design:type", Function),
|
|
4107
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4108
|
+
__metadata("design:returntype", void 0)
|
|
4109
|
+
], StreamQuery.prototype, "like", null);
|
|
4110
|
+
__decorate([
|
|
4111
|
+
IF_PROCEED(),
|
|
4112
|
+
__metadata("design:type", Function),
|
|
4113
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4114
|
+
__metadata("design:returntype", void 0)
|
|
4115
|
+
], StreamQuery.prototype, "notLike", null);
|
|
4116
|
+
__decorate([
|
|
4117
|
+
IF_PROCEED(),
|
|
4118
|
+
__metadata("design:type", Function),
|
|
4119
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4120
|
+
__metadata("design:returntype", void 0)
|
|
4121
|
+
], StreamQuery.prototype, "leftLike", null);
|
|
4122
|
+
__decorate([
|
|
4123
|
+
IF_PROCEED(),
|
|
4124
|
+
__metadata("design:type", Function),
|
|
4125
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4126
|
+
__metadata("design:returntype", void 0)
|
|
4127
|
+
], StreamQuery.prototype, "notLeftLike", null);
|
|
4128
|
+
__decorate([
|
|
4129
|
+
IF_PROCEED(),
|
|
4130
|
+
__metadata("design:type", Function),
|
|
4131
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4132
|
+
__metadata("design:returntype", void 0)
|
|
4133
|
+
], StreamQuery.prototype, "rightLike", null);
|
|
4134
|
+
__decorate([
|
|
4135
|
+
IF_PROCEED(),
|
|
4136
|
+
__metadata("design:type", Function),
|
|
4137
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4138
|
+
__metadata("design:returntype", void 0)
|
|
4139
|
+
], StreamQuery.prototype, "notRightLike", null);
|
|
4140
|
+
__decorate([
|
|
4141
|
+
IF_PROCEED(),
|
|
4142
|
+
__metadata("design:type", Function),
|
|
4143
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4144
|
+
__metadata("design:returntype", void 0)
|
|
4145
|
+
], StreamQuery.prototype, "PreciseLike", null);
|
|
4146
|
+
__decorate([
|
|
4147
|
+
IF_PROCEED(),
|
|
4148
|
+
__metadata("design:type", Function),
|
|
4149
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4150
|
+
__metadata("design:returntype", void 0)
|
|
4151
|
+
], StreamQuery.prototype, "notPreciseLike", null);
|
|
4152
|
+
__decorate([
|
|
4153
|
+
IF_PROCEED(),
|
|
4154
|
+
__metadata("design:type", Function),
|
|
4155
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4156
|
+
__metadata("design:returntype", void 0)
|
|
4157
|
+
], StreamQuery.prototype, "glob", null);
|
|
4158
|
+
__decorate([
|
|
4159
|
+
IF_PROCEED(),
|
|
4160
|
+
__metadata("design:type", Function),
|
|
4161
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4162
|
+
__metadata("design:returntype", void 0)
|
|
4163
|
+
], StreamQuery.prototype, "notGlob", null);
|
|
4164
|
+
__decorate([
|
|
4165
|
+
IF_PROCEED(),
|
|
4166
|
+
__metadata("design:type", Function),
|
|
4167
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4168
|
+
__metadata("design:returntype", void 0)
|
|
4169
|
+
], StreamQuery.prototype, "leftGlob", null);
|
|
4170
|
+
__decorate([
|
|
4171
|
+
IF_PROCEED(),
|
|
4172
|
+
__metadata("design:type", Function),
|
|
4173
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4174
|
+
__metadata("design:returntype", void 0)
|
|
4175
|
+
], StreamQuery.prototype, "notLeftGlob", null);
|
|
4176
|
+
__decorate([
|
|
4177
|
+
IF_PROCEED(),
|
|
4178
|
+
__metadata("design:type", Function),
|
|
4179
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4180
|
+
__metadata("design:returntype", void 0)
|
|
4181
|
+
], StreamQuery.prototype, "rightGlob", null);
|
|
4182
|
+
__decorate([
|
|
4183
|
+
IF_PROCEED(),
|
|
4184
|
+
__metadata("design:type", Function),
|
|
4185
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4186
|
+
__metadata("design:returntype", void 0)
|
|
4187
|
+
], StreamQuery.prototype, "notRightGlob", null);
|
|
4188
|
+
__decorate([
|
|
4189
|
+
IF_PROCEED(),
|
|
4190
|
+
__metadata("design:type", Function),
|
|
4191
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4192
|
+
__metadata("design:returntype", void 0)
|
|
4193
|
+
], StreamQuery.prototype, "PreciseGlob", null);
|
|
4194
|
+
__decorate([
|
|
4195
|
+
IF_PROCEED(),
|
|
4196
|
+
__metadata("design:type", Function),
|
|
4197
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4198
|
+
__metadata("design:returntype", void 0)
|
|
4199
|
+
], StreamQuery.prototype, "notPreciseGlob", null);
|
|
4200
|
+
__decorate([
|
|
4201
|
+
IF_PROCEED(),
|
|
4202
|
+
__metadata("design:type", Function),
|
|
4203
|
+
__metadata("design:paramtypes", [Object, Array, Object]),
|
|
4204
|
+
__metadata("design:returntype", void 0)
|
|
4205
|
+
], StreamQuery.prototype, "in", null);
|
|
4206
|
+
__decorate([
|
|
4207
|
+
IF_PROCEED(),
|
|
4208
|
+
__metadata("design:type", Function),
|
|
4209
|
+
__metadata("design:paramtypes", [Object, Array, Object]),
|
|
4210
|
+
__metadata("design:returntype", void 0)
|
|
4211
|
+
], StreamQuery.prototype, "notIn", null);
|
|
4212
|
+
__decorate([
|
|
4213
|
+
IF_PROCEED(),
|
|
4214
|
+
__metadata("design:type", Function),
|
|
4215
|
+
__metadata("design:paramtypes", [Array, Object, Object]),
|
|
4216
|
+
__metadata("design:returntype", void 0)
|
|
4217
|
+
], StreamQuery.prototype, "in2", null);
|
|
4218
|
+
__decorate([
|
|
4219
|
+
IF_PROCEED(),
|
|
4220
|
+
__metadata("design:type", Function),
|
|
4221
|
+
__metadata("design:paramtypes", [Array, Object, Object]),
|
|
4222
|
+
__metadata("design:returntype", void 0)
|
|
4223
|
+
], StreamQuery.prototype, "notIn2", null);
|
|
4224
|
+
__decorate([
|
|
4225
|
+
IF_PROCEED(),
|
|
4226
|
+
__metadata("design:type", Function),
|
|
4227
|
+
__metadata("design:paramtypes", [Object]),
|
|
4228
|
+
__metadata("design:returntype", void 0)
|
|
4229
|
+
], StreamQuery.prototype, "isNULL", null);
|
|
4230
|
+
__decorate([
|
|
4231
|
+
IF_PROCEED(),
|
|
4232
|
+
__metadata("design:type", Function),
|
|
4233
|
+
__metadata("design:paramtypes", [Object]),
|
|
4234
|
+
__metadata("design:returntype", void 0)
|
|
4235
|
+
], StreamQuery.prototype, "isNotNULL", null);
|
|
4236
|
+
__decorate([
|
|
4237
|
+
IF_PROCEED(),
|
|
4238
|
+
__metadata("design:type", Function),
|
|
4239
|
+
__metadata("design:paramtypes", [Object, Object, Object, Object]),
|
|
4240
|
+
__metadata("design:returntype", void 0)
|
|
4241
|
+
], StreamQuery.prototype, "between", null);
|
|
4242
|
+
__decorate([
|
|
4243
|
+
IF_PROCEED(),
|
|
4244
|
+
__metadata("design:type", Function),
|
|
4245
|
+
__metadata("design:paramtypes", [Object, Object, Object, Object]),
|
|
4246
|
+
__metadata("design:returntype", void 0)
|
|
4247
|
+
], StreamQuery.prototype, "notBetween", null);
|
|
4248
|
+
__decorate([
|
|
4249
|
+
IF_PROCEED(),
|
|
4250
|
+
__metadata("design:type", Function),
|
|
4251
|
+
__metadata("design:paramtypes", [Object, Number, Object]),
|
|
4252
|
+
__metadata("design:returntype", void 0)
|
|
4253
|
+
], StreamQuery.prototype, "pow", null);
|
|
4254
|
+
__decorate([
|
|
4255
|
+
IF_PROCEED(),
|
|
4256
|
+
__metadata("design:type", Function),
|
|
4257
|
+
__metadata("design:paramtypes", [Object, Number, Object]),
|
|
4258
|
+
__metadata("design:returntype", void 0)
|
|
4259
|
+
], StreamQuery.prototype, "notPow", null);
|
|
4260
|
+
__decorate([
|
|
4261
|
+
IF_PROCEED(),
|
|
4262
|
+
__metadata("design:type", Function),
|
|
4263
|
+
__metadata("design:paramtypes", [Object, Array, Object]),
|
|
4264
|
+
__metadata("design:returntype", void 0)
|
|
4265
|
+
], StreamQuery.prototype, "powWith", null);
|
|
4266
|
+
__decorate([
|
|
4267
|
+
IF_PROCEED(),
|
|
4268
|
+
__metadata("design:type", Function),
|
|
4269
|
+
__metadata("design:paramtypes", [Object, Array, Object]),
|
|
4270
|
+
__metadata("design:returntype", void 0)
|
|
4271
|
+
], StreamQuery.prototype, "notPowWith", null);
|
|
4272
|
+
__decorate([
|
|
4273
|
+
IF_PROCEED(),
|
|
4274
|
+
__metadata("design:type", Function),
|
|
4275
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
4276
|
+
__metadata("design:returntype", void 0)
|
|
4277
|
+
], StreamQuery.prototype, "match", null);
|
|
4278
|
+
__decorate([
|
|
4279
|
+
IF_PROCEED(),
|
|
4280
|
+
__metadata("design:type", Function),
|
|
4281
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
4282
|
+
__metadata("design:returntype", void 0)
|
|
4283
|
+
], StreamQuery.prototype, "notMatch", null);
|
|
4284
|
+
__decorate([
|
|
4285
|
+
IF_PROCEED(),
|
|
4286
|
+
__metadata("design:type", Function),
|
|
4287
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
4288
|
+
__metadata("design:returntype", void 0)
|
|
4289
|
+
], StreamQuery.prototype, "matchBoolean", null);
|
|
4290
|
+
__decorate([
|
|
4291
|
+
IF_PROCEED(),
|
|
4292
|
+
__metadata("design:type", Function),
|
|
4293
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
4294
|
+
__metadata("design:returntype", void 0)
|
|
4295
|
+
], StreamQuery.prototype, "notMatchBoolean", null);
|
|
4296
|
+
__decorate([
|
|
4297
|
+
IF_PROCEED(),
|
|
4298
|
+
__metadata("design:type", Function),
|
|
4299
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
4300
|
+
__metadata("design:returntype", void 0)
|
|
4301
|
+
], StreamQuery.prototype, "matchQuery", null);
|
|
4302
|
+
__decorate([
|
|
4303
|
+
IF_PROCEED(),
|
|
4304
|
+
__metadata("design:type", Function),
|
|
4305
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
4306
|
+
__metadata("design:returntype", void 0)
|
|
4307
|
+
], StreamQuery.prototype, "notMatchQuery", null);
|
|
4308
|
+
__decorate([
|
|
4309
|
+
IF_PROCEED(),
|
|
4310
|
+
__metadata("design:type", Function),
|
|
4311
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4312
|
+
__metadata("design:returntype", void 0)
|
|
4313
|
+
], StreamQuery.prototype, "includes", null);
|
|
4314
|
+
__decorate([
|
|
4315
|
+
IF_PROCEED(),
|
|
4316
|
+
__metadata("design:type", Function),
|
|
4317
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4318
|
+
__metadata("design:returntype", void 0)
|
|
4319
|
+
], StreamQuery.prototype, "notIncludes", null);
|
|
4320
|
+
__decorate([
|
|
4321
|
+
IF_PROCEED(),
|
|
4322
|
+
__metadata("design:type", Function),
|
|
4323
|
+
__metadata("design:paramtypes", [Object]),
|
|
4324
|
+
__metadata("design:returntype", void 0)
|
|
4325
|
+
], StreamQuery.prototype, "and", null);
|
|
4326
|
+
__decorate([
|
|
4327
|
+
IF_PROCEED(),
|
|
4328
|
+
__metadata("design:type", Function),
|
|
4329
|
+
__metadata("design:paramtypes", [Object]),
|
|
4330
|
+
__metadata("design:returntype", void 0)
|
|
4331
|
+
], StreamQuery.prototype, "or", null);
|
|
4332
|
+
__decorate([
|
|
4333
|
+
IF_PROCEED(),
|
|
4334
|
+
__metadata("design:type", Function),
|
|
4335
|
+
__metadata("design:paramtypes", [Object]),
|
|
4336
|
+
__metadata("design:returntype", void 0)
|
|
4337
|
+
], StreamQuery.prototype, "groupBy", null);
|
|
4338
|
+
__decorate([
|
|
4339
|
+
IF_PROCEED(),
|
|
4340
|
+
__metadata("design:type", Function),
|
|
4341
|
+
__metadata("design:paramtypes", [String]),
|
|
4342
|
+
__metadata("design:returntype", void 0)
|
|
4343
|
+
], StreamQuery.prototype, "groupBy2", null);
|
|
4344
|
+
__decorate([
|
|
4345
|
+
IF_PROCEED(),
|
|
4346
|
+
__metadata("design:type", Function),
|
|
4347
|
+
__metadata("design:paramtypes", [Object]),
|
|
4348
|
+
__metadata("design:returntype", void 0)
|
|
4349
|
+
], StreamQuery.prototype, "asc", null);
|
|
4350
|
+
__decorate([
|
|
4351
|
+
IF_PROCEED(),
|
|
4352
|
+
__metadata("design:type", Function),
|
|
4353
|
+
__metadata("design:paramtypes", [String]),
|
|
4354
|
+
__metadata("design:returntype", void 0)
|
|
4355
|
+
], StreamQuery.prototype, "asc2", null);
|
|
4356
|
+
__decorate([
|
|
4357
|
+
IF_PROCEED(),
|
|
4358
|
+
__metadata("design:type", Function),
|
|
4359
|
+
__metadata("design:paramtypes", [Object]),
|
|
4360
|
+
__metadata("design:returntype", void 0)
|
|
4361
|
+
], StreamQuery.prototype, "desc", null);
|
|
4362
|
+
__decorate([
|
|
4363
|
+
IF_PROCEED(),
|
|
4364
|
+
__metadata("design:type", Function),
|
|
4365
|
+
__metadata("design:paramtypes", [String]),
|
|
4366
|
+
__metadata("design:returntype", void 0)
|
|
4367
|
+
], StreamQuery.prototype, "desc2", null);
|
|
4368
|
+
__decorate([
|
|
4369
|
+
IF_PROCEED(),
|
|
4370
|
+
__metadata("design:type", Function),
|
|
4371
|
+
__metadata("design:paramtypes", [Number, Number]),
|
|
4372
|
+
__metadata("design:returntype", void 0)
|
|
4373
|
+
], StreamQuery.prototype, "limit", null);
|
|
4374
|
+
__decorate([
|
|
4375
|
+
IF_PROCEED(),
|
|
4376
|
+
__metadata("design:type", Function),
|
|
4377
|
+
__metadata("design:paramtypes", [Number, Number]),
|
|
4378
|
+
__metadata("design:returntype", void 0)
|
|
4379
|
+
], StreamQuery.prototype, "page", null);
|
|
4380
|
+
__decorate([
|
|
4381
|
+
IF_PROCEED(),
|
|
4382
|
+
__metadata("design:type", Function),
|
|
4383
|
+
__metadata("design:paramtypes", [Object]),
|
|
4384
|
+
__metadata("design:returntype", void 0)
|
|
4385
|
+
], StreamQuery.prototype, "distinct", null);
|
|
4386
|
+
__decorate([
|
|
4387
|
+
IF_PROCEED(),
|
|
4388
|
+
__metadata("design:type", Function),
|
|
4389
|
+
__metadata("design:paramtypes", [Object, String]),
|
|
4390
|
+
__metadata("design:returntype", void 0)
|
|
4391
|
+
], StreamQuery.prototype, "countDistinct", null);
|
|
4392
|
+
__decorate([
|
|
4393
|
+
IF_PROCEED(),
|
|
4394
|
+
__metadata("design:type", Function),
|
|
4395
|
+
__metadata("design:paramtypes", [String]),
|
|
4396
|
+
__metadata("design:returntype", void 0)
|
|
4397
|
+
], StreamQuery.prototype, "count", null);
|
|
4398
|
+
__decorate([
|
|
4399
|
+
IF_PROCEED(),
|
|
4400
|
+
__metadata("design:type", Function),
|
|
4401
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
4402
|
+
__metadata("design:returntype", void 0)
|
|
4403
|
+
], StreamQuery.prototype, "sum", null);
|
|
4404
|
+
__decorate([
|
|
4405
|
+
IF_PROCEED(),
|
|
4406
|
+
__metadata("design:type", Function),
|
|
4407
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
4408
|
+
__metadata("design:returntype", void 0)
|
|
4409
|
+
], StreamQuery.prototype, "avg", null);
|
|
4410
|
+
__decorate([
|
|
4411
|
+
IF_PROCEED(),
|
|
4412
|
+
__metadata("design:type", Function),
|
|
4413
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
4414
|
+
__metadata("design:returntype", void 0)
|
|
4415
|
+
], StreamQuery.prototype, "max", null);
|
|
4416
|
+
__decorate([
|
|
4417
|
+
IF_PROCEED(),
|
|
4418
|
+
__metadata("design:type", Function),
|
|
4419
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
4420
|
+
__metadata("design:returntype", void 0)
|
|
4421
|
+
], StreamQuery.prototype, "min", null);
|
|
4422
|
+
__decorate([
|
|
4423
|
+
IF_PROCEED(),
|
|
4424
|
+
__metadata("design:type", Function),
|
|
4425
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4426
|
+
__metadata("design:returntype", Object)
|
|
4427
|
+
], StreamQuery.prototype, "groupConcat", null);
|
|
4428
|
+
__decorate([
|
|
4429
|
+
IF_PROCEED(),
|
|
4430
|
+
__metadata("design:type", Function),
|
|
4431
|
+
__metadata("design:paramtypes", [Object]),
|
|
4432
|
+
__metadata("design:returntype", void 0)
|
|
4433
|
+
], StreamQuery.prototype, "select", null);
|
|
4434
|
+
__decorate([
|
|
4435
|
+
IF_PROCEED(),
|
|
4436
|
+
__metadata("design:type", Function),
|
|
4437
|
+
__metadata("design:paramtypes", [String, Object]),
|
|
4438
|
+
__metadata("design:returntype", void 0)
|
|
4439
|
+
], StreamQuery.prototype, "select2", null);
|
|
4440
|
+
__decorate([
|
|
4441
|
+
IF_PROCEED(),
|
|
4442
|
+
__metadata("design:type", Function),
|
|
4443
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
4444
|
+
__metadata("design:returntype", void 0)
|
|
4445
|
+
], StreamQuery.prototype, "update", null);
|
|
4446
|
+
__decorate([
|
|
4447
|
+
IF_PROCEED(),
|
|
4448
|
+
__metadata("design:type", Function),
|
|
4449
|
+
__metadata("design:paramtypes", [String, Object]),
|
|
4450
|
+
__metadata("design:returntype", void 0)
|
|
4451
|
+
], StreamQuery.prototype, "update2", null);
|
|
4452
|
+
__decorate([
|
|
4453
|
+
IF_PROCEED(),
|
|
4454
|
+
__metadata("design:type", Function),
|
|
4455
|
+
__metadata("design:paramtypes", [Object]),
|
|
4456
|
+
__metadata("design:returntype", void 0)
|
|
4457
|
+
], StreamQuery.prototype, "updateT", null);
|
|
4458
|
+
__decorate([
|
|
4459
|
+
IF_PROCEED(),
|
|
4460
|
+
__metadata("design:type", Function),
|
|
4461
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
4462
|
+
__metadata("design:returntype", void 0)
|
|
4463
|
+
], StreamQuery.prototype, "replace", null);
|
|
4464
|
+
__decorate([
|
|
4465
|
+
IF_EXEC(null),
|
|
4466
|
+
__metadata("design:type", Function),
|
|
4467
|
+
__metadata("design:paramtypes", [Object]),
|
|
4468
|
+
__metadata("design:returntype", Object)
|
|
4469
|
+
], StreamQuery.prototype, "excuteSelect", null);
|
|
4470
|
+
__decorate([
|
|
4471
|
+
IF_EXEC(null),
|
|
4472
|
+
__metadata("design:type", Function),
|
|
4473
|
+
__metadata("design:paramtypes", [Object]),
|
|
4474
|
+
__metadata("design:returntype", Object)
|
|
4475
|
+
], StreamQuery.prototype, "excutePage", null);
|
|
4476
|
+
__decorate([
|
|
4477
|
+
IF_EXEC(0),
|
|
4478
|
+
__metadata("design:type", Function),
|
|
4479
|
+
__metadata("design:paramtypes", [Object]),
|
|
4480
|
+
__metadata("design:returntype", Object)
|
|
4481
|
+
], StreamQuery.prototype, "excuteUpdate", null);
|
|
4482
|
+
__decorate([
|
|
4483
|
+
IF_EXEC(0),
|
|
4484
|
+
__metadata("design:type", Function),
|
|
4485
|
+
__metadata("design:paramtypes", [Object]),
|
|
4486
|
+
__metadata("design:returntype", Object)
|
|
4487
|
+
], StreamQuery.prototype, "excuteDelete", null);
|
|
4488
|
+
/**
|
|
4489
|
+
获取REDIS客户端,
|
|
4490
|
+
# [查看库的API](https://github.com/redis/ioredis?tab=readme-ov-file)
|
|
4491
|
+
# [REDIS API](http://doc.redisfans.com/)
|
|
4492
|
+
REDIS 的API 可以直接用,将方法名转为小写
|
|
4493
|
+
```
|
|
4494
|
+
// 设置<Redis>来获得代码提示
|
|
4495
|
+
getRedisDB<Redis>('').exists(?)
|
|
4496
|
+
```
|
|
4497
|
+
*/
|
|
4498
|
+
export function getRedisDB(db) {
|
|
4499
|
+
const rd = globalThis[_dao][DBType.Redis][db ?? _primaryDB];
|
|
4500
|
+
Throw.if(!rd, 'not found redis!');
|
|
4501
|
+
return rd;
|
|
4502
|
+
}
|
|
4503
|
+
/**
|
|
4504
|
+
redlock
|
|
4505
|
+
*/
|
|
4506
|
+
export async function GetRedisLock(key, lockMaxActive) {
|
|
4507
|
+
const lock = globalThis[_dao][DBType.RedisLock];
|
|
4508
|
+
Throw.if(!lock, 'not found lock!');
|
|
4509
|
+
const db = getRedisDB();
|
|
4510
|
+
let initLock;
|
|
4511
|
+
try {
|
|
4512
|
+
initLock = await lock.acquire([`[lockex]${key}`], 5000);
|
|
4513
|
+
const count = await db.get(key);
|
|
4514
|
+
if (count === null || parseInt(count) < (lockMaxActive ?? 1)) {
|
|
4515
|
+
await db.incr(key);
|
|
4516
|
+
return true;
|
|
4517
|
+
}
|
|
4518
|
+
else {
|
|
4519
|
+
return false;
|
|
4520
|
+
}
|
|
4521
|
+
}
|
|
4522
|
+
catch (er) {
|
|
4523
|
+
return await GetRedisLock(key, lockMaxActive);
|
|
4524
|
+
}
|
|
4525
|
+
finally {
|
|
4526
|
+
if (initLock) {
|
|
4527
|
+
try {
|
|
4528
|
+
await initLock.release();
|
|
4529
|
+
// eslint-disable-next-line no-empty
|
|
4530
|
+
}
|
|
4531
|
+
catch (error) {
|
|
4532
|
+
}
|
|
4533
|
+
}
|
|
4534
|
+
}
|
|
4535
|
+
}
|
|
4536
|
+
;
|
|
4537
|
+
export async function excuteWithLock(config, fn__) {
|
|
4538
|
+
const key = `[lock]${typeof config.key === 'function' ? config.key() : config.key}`;
|
|
4539
|
+
const db = getRedisDB();
|
|
4540
|
+
let wait_time = 0;
|
|
4541
|
+
const fn = async () => {
|
|
4542
|
+
const lock = await GetRedisLock(key, config.lockMaxActive);
|
|
4543
|
+
if (lock === false) {
|
|
4544
|
+
if (config.lockWait !== false && ((config.lockMaxWaitTime ?? 0) === 0 || (wait_time + (config.lockRetryInterval ?? 100)) <= (config.lockMaxWaitTime ?? 0))) {
|
|
4545
|
+
logger.debug(`get lock ${key} fail, retry after ${config.lockRetryInterval ?? 100}ms...`);
|
|
4546
|
+
await sleep(config.lockRetryInterval ?? 100);
|
|
4547
|
+
wait_time += (config.lockRetryInterval ?? 100);
|
|
4548
|
+
return await fn();
|
|
4549
|
+
}
|
|
4550
|
+
else {
|
|
4551
|
+
logger.debug(`get lock ${key} fail`);
|
|
4552
|
+
throw new Error(config.errorMessage || `get lock fail: ${key}`);
|
|
4553
|
+
}
|
|
4554
|
+
}
|
|
4555
|
+
else {
|
|
4556
|
+
logger.debug(`get lock ${key} ok!`);
|
|
4557
|
+
await db.get('other').pexpire(key, config.lockMaxTime ?? 60000);
|
|
4558
|
+
try {
|
|
4559
|
+
return await fn__();
|
|
4560
|
+
}
|
|
4561
|
+
finally {
|
|
4562
|
+
logger.debug(`unlock ${key} ok!`);
|
|
4563
|
+
await db.get('other').decr(key);
|
|
4564
|
+
}
|
|
4565
|
+
}
|
|
4566
|
+
};
|
|
4567
|
+
return await fn();
|
|
4568
|
+
}
|
|
4569
|
+
/** 与缓存共用时,需要在缓存之前:有缓存则返回缓存,否则加锁执行并缓存,后续队列全部返回缓存,跳过执行 */
|
|
4570
|
+
export function MethodLock(config) {
|
|
4571
|
+
return function (target, _propertyKey, descriptor) {
|
|
4572
|
+
const fn__ = descriptor.value;
|
|
4573
|
+
descriptor.value = async function (...args) {
|
|
4574
|
+
config.key = typeof config.key === 'function' ? config.key.call(target, ...args) : config.key;
|
|
4575
|
+
return await excuteWithLock(config, async () => await fn__.call(this, ...args));
|
|
4576
|
+
};
|
|
4577
|
+
};
|
|
4578
|
+
}
|
|
4579
|
+
async function setMethodCache(config, devid) {
|
|
4580
|
+
const db = getRedisDB();
|
|
4581
|
+
if (config.result !== null && config.result !== undefined) {
|
|
4582
|
+
// 映射关系存放
|
|
4583
|
+
if (config.clearKey && config.clearKey.length > 0) {
|
|
4584
|
+
for (const clear of config.clearKey) {
|
|
4585
|
+
await db.sadd(`[cache-parent]${clear}`, config.key);
|
|
4586
|
+
await db.sadd(`[cache-child]${config.key}`, clear);
|
|
4587
|
+
}
|
|
4588
|
+
}
|
|
4589
|
+
if (config.autoClearTime) { // 自动清空
|
|
4590
|
+
await db.set(`[cache]${config.key}`, JSON.stringify(config.result), 'EX', config.autoClearTime * 60);
|
|
4591
|
+
// 订阅:清空 clear list
|
|
4592
|
+
if (config.clearKey && config.clearKey.length > 0) {
|
|
4593
|
+
globalThis[_EventBus].on(`[cache]${config.key}`, async (key) => {
|
|
4594
|
+
await clearChild(key, true);
|
|
4595
|
+
});
|
|
4596
|
+
}
|
|
4597
|
+
}
|
|
4598
|
+
else {
|
|
4599
|
+
await db.set(`[cache]${config.key}`, JSON.stringify(config.result));
|
|
4600
|
+
}
|
|
4601
|
+
if (devid) {
|
|
4602
|
+
// 订阅:清空 clear list
|
|
4603
|
+
globalThis[_EventBus].on(`user-${devid}`, async function (key) {
|
|
4604
|
+
await clearChild(key);
|
|
4605
|
+
});
|
|
4606
|
+
}
|
|
4607
|
+
}
|
|
4608
|
+
}
|
|
4609
|
+
export async function clearMethodCache(key) {
|
|
4610
|
+
const db = getRedisDB();
|
|
4611
|
+
let type = await db.type(`[cache-parent]${key}`);
|
|
4612
|
+
if (type === 'set') {
|
|
4613
|
+
await clearParent(key);
|
|
4614
|
+
}
|
|
4615
|
+
type = await db.type(`[cache]${key}`);
|
|
4616
|
+
if (type !== 'none') {
|
|
4617
|
+
await clearChild(key);
|
|
4618
|
+
}
|
|
4619
|
+
}
|
|
4620
|
+
async function clearChild(key, skipDel = false) {
|
|
4621
|
+
const db = getRedisDB();
|
|
4622
|
+
if (skipDel === false) {
|
|
4623
|
+
await db.del(`[cache]${key}`);
|
|
4624
|
+
}
|
|
4625
|
+
const childtype = await db.type(`[cache-child]${key}`);
|
|
4626
|
+
if (childtype === 'set') {
|
|
4627
|
+
const parentKeys = await db.smembers(`[cache-child]${key}`);
|
|
4628
|
+
for (const clear of parentKeys) {
|
|
4629
|
+
const type = await db.type(`[cache-parent]${clear}`);
|
|
4630
|
+
if (type === 'set') {
|
|
4631
|
+
await db.srem(`[cache-parent]${clear}`, key);
|
|
4632
|
+
}
|
|
4633
|
+
}
|
|
4634
|
+
await db.del(`[cache-child]${key}`);
|
|
4635
|
+
}
|
|
4636
|
+
}
|
|
4637
|
+
async function clearParent(clearKey) {
|
|
4638
|
+
const db = getRedisDB();
|
|
4639
|
+
const keys = await db.smembers(`[cache-parent]${clearKey}`);
|
|
4640
|
+
if (keys) {
|
|
4641
|
+
for (const key of keys) {
|
|
4642
|
+
logger.debug(`cache ${key} cleared!`);
|
|
4643
|
+
await clearChild(key);
|
|
4644
|
+
}
|
|
4645
|
+
}
|
|
4646
|
+
}
|
|
4647
|
+
export async function excuteWithCache(config, fn) {
|
|
4648
|
+
const db = getRedisDB();
|
|
4649
|
+
const cache = await db.get(`[cache]${config.key}`);
|
|
4650
|
+
if (cache) {
|
|
4651
|
+
logger.debug(`cache ${config.key} hit!`);
|
|
4652
|
+
return JSON.parse(cache);
|
|
4653
|
+
}
|
|
4654
|
+
else {
|
|
4655
|
+
logger.debug(`cache ${config.key} miss!`);
|
|
4656
|
+
const result = await fn();
|
|
4657
|
+
await setMethodCache({
|
|
4658
|
+
key: config.key,
|
|
4659
|
+
clearKey: config.clearKey,
|
|
4660
|
+
autoClearTime: config.autoClearTime,
|
|
4661
|
+
result
|
|
4662
|
+
});
|
|
4663
|
+
return result;
|
|
4664
|
+
}
|
|
4665
|
+
}
|
|
4666
|
+
export function MethodCache(config) {
|
|
4667
|
+
return function (target, _propertyKey, descriptor) {
|
|
4668
|
+
const fn = descriptor.value;
|
|
4669
|
+
descriptor.value = async function (...args) {
|
|
4670
|
+
const key = typeof config.key === 'function' ? config.key.call(this, ...args) : config.key;
|
|
4671
|
+
const db = getRedisDB();
|
|
4672
|
+
const cache = await db.get('other').get(`[cache]${key}`);
|
|
4673
|
+
if (cache) {
|
|
4674
|
+
logger.debug(`cache ${key} hit!`);
|
|
4675
|
+
return JSON.parse(cache);
|
|
4676
|
+
}
|
|
4677
|
+
else {
|
|
4678
|
+
logger.debug(`cache ${key} miss!`);
|
|
4679
|
+
const result = await fn.call(this, ...args);
|
|
4680
|
+
const clearKey = config.clearKey ? typeof config.clearKey === 'function' ? config.clearKey.call(this, ...args) : config.clearKey : undefined;
|
|
4681
|
+
await setMethodCache({
|
|
4682
|
+
key,
|
|
4683
|
+
clearKey,
|
|
4684
|
+
autoClearTime: config.autoClearTime,
|
|
4685
|
+
result
|
|
4686
|
+
}, config.clearWithSession && this.ctx.me && this.ctx.me.devid);
|
|
4687
|
+
return result;
|
|
4688
|
+
}
|
|
4689
|
+
};
|
|
4690
|
+
};
|
|
4691
|
+
}
|
|
4692
|
+
class MUParser {
|
|
4693
|
+
constructor(modelName, file) {
|
|
4694
|
+
this.linNumber = 0;
|
|
4695
|
+
this.lastLine = '';
|
|
4696
|
+
this.lastlastLine = '';
|
|
4697
|
+
this.status = 0;
|
|
4698
|
+
this.lineSeparator = '\n';
|
|
4699
|
+
this.modelName = modelName;
|
|
4700
|
+
this.files = file.replace(/\r/g, '').split(this.lineSeparator);
|
|
4701
|
+
this.skipHeader();
|
|
4702
|
+
}
|
|
4703
|
+
next() {
|
|
4704
|
+
let sqlId = this.readSqlId();
|
|
4705
|
+
if (this.status === MUParser.END) {
|
|
4706
|
+
return null;
|
|
4707
|
+
}
|
|
4708
|
+
// 去掉可能的尾部空格
|
|
4709
|
+
sqlId = sqlId.trim();
|
|
4710
|
+
this.skipComment();
|
|
4711
|
+
if (this.status === MUParser.END) {
|
|
4712
|
+
return null;
|
|
4713
|
+
}
|
|
4714
|
+
const sql = this.readSql();
|
|
4715
|
+
return [`${this.modelName}.${sqlId}`, sql];
|
|
4716
|
+
}
|
|
4717
|
+
skipHeader() {
|
|
4718
|
+
while (true) {
|
|
4719
|
+
const line = this.nextLine();
|
|
4720
|
+
if (this.status === MUParser.END) {
|
|
4721
|
+
return;
|
|
4722
|
+
}
|
|
4723
|
+
if (line.startsWith('===')) {
|
|
4724
|
+
return;
|
|
4725
|
+
}
|
|
4726
|
+
}
|
|
4727
|
+
}
|
|
4728
|
+
nextLine() {
|
|
4729
|
+
const line = this.files[this.linNumber];
|
|
4730
|
+
this.linNumber++;
|
|
4731
|
+
if (line === undefined) {
|
|
4732
|
+
this.status = MUParser.END;
|
|
4733
|
+
}
|
|
4734
|
+
// 保存最后读的俩行
|
|
4735
|
+
this.lastlastLine = this.lastLine;
|
|
4736
|
+
this.lastLine = line;
|
|
4737
|
+
return line;
|
|
4738
|
+
}
|
|
4739
|
+
readSqlId() {
|
|
4740
|
+
return this.lastlastLine;
|
|
4741
|
+
}
|
|
4742
|
+
skipComment() {
|
|
4743
|
+
let findComment = false;
|
|
4744
|
+
while (true) {
|
|
4745
|
+
let line = this.nextLine();
|
|
4746
|
+
if (this.status === MUParser.END) {
|
|
4747
|
+
return;
|
|
4748
|
+
}
|
|
4749
|
+
line = line.trim();
|
|
4750
|
+
if (!findComment && line.length === 0) {
|
|
4751
|
+
continue;
|
|
4752
|
+
}
|
|
4753
|
+
if (line.startsWith('*')) {
|
|
4754
|
+
// 注释符号
|
|
4755
|
+
findComment = true;
|
|
4756
|
+
continue;
|
|
4757
|
+
}
|
|
4758
|
+
else {
|
|
4759
|
+
if (line.length === 0) {
|
|
4760
|
+
continue;
|
|
4761
|
+
}
|
|
4762
|
+
else if (line.startsWith('```') || line.startsWith('~~~')) {
|
|
4763
|
+
// 忽略以code block开头的符号
|
|
4764
|
+
continue;
|
|
4765
|
+
}
|
|
4766
|
+
else {
|
|
4767
|
+
// 注释结束
|
|
4768
|
+
return;
|
|
4769
|
+
}
|
|
4770
|
+
}
|
|
4771
|
+
}
|
|
4772
|
+
}
|
|
4773
|
+
readSql() {
|
|
4774
|
+
const list = [];
|
|
4775
|
+
list.push(this.lastLine);
|
|
4776
|
+
while (true) {
|
|
4777
|
+
const line = this.nextLine();
|
|
4778
|
+
if (this.status === MUParser.END) {
|
|
4779
|
+
return this.getBuildSql(list);
|
|
4780
|
+
}
|
|
4781
|
+
if (line.startsWith('===')) {
|
|
4782
|
+
// 删除下一个sqlId表示
|
|
4783
|
+
list.pop();
|
|
4784
|
+
return this.getBuildSql(list);
|
|
4785
|
+
}
|
|
4786
|
+
list.push(line);
|
|
4787
|
+
}
|
|
4788
|
+
}
|
|
4789
|
+
getBuildSql(list) {
|
|
4790
|
+
const sb = [];
|
|
4791
|
+
for (const str of list) {
|
|
4792
|
+
const s = str.trim();
|
|
4793
|
+
if (s.startsWith('```') || s.startsWith('~~~')) {
|
|
4794
|
+
// 忽略以code block开头的符号
|
|
4795
|
+
continue;
|
|
4796
|
+
}
|
|
4797
|
+
sb.push(str);
|
|
4798
|
+
}
|
|
4799
|
+
return sb.join(this.lineSeparator);
|
|
4800
|
+
}
|
|
4801
|
+
}
|
|
4802
|
+
MUParser.END = 1;
|