baja-lite 1.0.0
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/LICENSE +21 -0
- package/README.md +1 -0
- package/cjs/constant.d.ts +13 -0
- package/cjs/constant.js +19 -0
- package/cjs/error.d.ts +5 -0
- package/cjs/error.js +16 -0
- package/cjs/fn.d.ts +128 -0
- package/cjs/fn.js +169 -0
- package/cjs/index.d.ts +8 -0
- package/cjs/index.js +24 -0
- package/cjs/math.d.ts +69 -0
- package/cjs/math.js +435 -0
- package/cjs/now.d.ts +7 -0
- package/cjs/now.js +26 -0
- package/cjs/object.d.ts +77 -0
- package/cjs/object.js +212 -0
- package/cjs/set-ex.d.ts +171 -0
- package/cjs/set-ex.js +336 -0
- package/cjs/sql.d.ts +1216 -0
- package/cjs/sql.js +3380 -0
- package/cjs/string.d.ts +18 -0
- package/cjs/string.js +124 -0
- package/cjs/test-mysql.d.ts +1 -0
- package/cjs/test-mysql.js +108 -0
- package/cjs/test-sqlite.d.ts +1 -0
- package/cjs/test-sqlite.js +89 -0
- package/cjs/test.d.ts +1 -0
- package/cjs/test.js +4 -0
- package/es/constant.d.ts +13 -0
- package/es/constant.js +16 -0
- package/es/error.d.ts +5 -0
- package/es/error.js +13 -0
- package/es/fn.d.ts +128 -0
- package/es/fn.js +162 -0
- package/es/index.d.ts +8 -0
- package/es/index.js +8 -0
- package/es/math.d.ts +69 -0
- package/es/math.js +414 -0
- package/es/now.d.ts +7 -0
- package/es/now.js +16 -0
- package/es/object.d.ts +77 -0
- package/es/object.js +196 -0
- package/es/set-ex.d.ts +171 -0
- package/es/set-ex.js +332 -0
- package/es/sql.d.ts +1216 -0
- package/es/sql.js +3338 -0
- package/es/string.d.ts +18 -0
- package/es/string.js +109 -0
- package/es/test-mysql.d.ts +1 -0
- package/es/test-mysql.js +106 -0
- package/es/test-sqlite.d.ts +1 -0
- package/es/test-sqlite.js +87 -0
- package/es/test.d.ts +1 -0
- package/es/test.js +2 -0
- package/package.json +66 -0
package/cjs/sql.js
ADDED
|
@@ -0,0 +1,3380 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
19
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
20
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
21
|
+
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;
|
|
22
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
23
|
+
};
|
|
24
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
25
|
+
if (mod && mod.__esModule) return mod;
|
|
26
|
+
var result = {};
|
|
27
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
28
|
+
__setModuleDefault(result, mod);
|
|
29
|
+
return result;
|
|
30
|
+
};
|
|
31
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
32
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
33
|
+
};
|
|
34
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
35
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
36
|
+
};
|
|
37
|
+
var _a, _b, _c;
|
|
38
|
+
var _d, _e, _f;
|
|
39
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
40
|
+
exports.LetsGo = exports.MethodCache = exports.excuteWithCache = exports.clearMethodCache = exports.MethodLock = exports.excuteWithLock = exports.GetRedisLock = exports.getRedisDB = exports.SqlService = exports.DeclareService = exports.DeclareClass = exports.DB = exports.Field = exports.SqliteMemory = exports.SqlType = exports.SqlQueryMode = exports.SqlTemplateMode = exports.SqlSelectMode = exports.SqlDelMode = exports.SqlInsertMode = exports.SqlSyncMode = exports.DBType = void 0;
|
|
41
|
+
require("reflect-metadata");
|
|
42
|
+
const error_1 = require("./error");
|
|
43
|
+
const tslib_1 = __importDefault(require("tslib"));
|
|
44
|
+
const sqlstring_1 = __importDefault(require("sqlstring"));
|
|
45
|
+
const iterare_1 = __importDefault(require("iterare"));
|
|
46
|
+
const string_1 = require("./string");
|
|
47
|
+
const pino_1 = __importDefault(require("pino"));
|
|
48
|
+
const fn_1 = require("./fn");
|
|
49
|
+
const math_1 = require("./math");
|
|
50
|
+
// #region 常量
|
|
51
|
+
const _daoDBName = Symbol('dbName');
|
|
52
|
+
const _tableName = Symbol('tableName');
|
|
53
|
+
const _ids = Symbol('ids');
|
|
54
|
+
const _columns = Symbol('columns');
|
|
55
|
+
const _columnsNoId = Symbol('columnsNoId');
|
|
56
|
+
const _fields = Symbol('fields');
|
|
57
|
+
const _stateFileName = Symbol('stateFileName');
|
|
58
|
+
const _deleteState = Symbol('deleteState');
|
|
59
|
+
const _transformer = Symbol('transformer');
|
|
60
|
+
const _index = Symbol('index');
|
|
61
|
+
const _def = Symbol('def');
|
|
62
|
+
const _sqlCache = Symbol('sqlCache');
|
|
63
|
+
const _dao = Symbol('dao');
|
|
64
|
+
const _primaryDB = Symbol('primaryDB');
|
|
65
|
+
const _dbType = Symbol('dbType');
|
|
66
|
+
const _sqlite_version = Symbol('sqlite_version');
|
|
67
|
+
const _daoConnection = Symbol('daoConnection');
|
|
68
|
+
const _inTransaction = Symbol('inTransaction');
|
|
69
|
+
const _daoDB = Symbol('daoDB');
|
|
70
|
+
const _sqliteRemoteName = Symbol('sqliteRemoteName');
|
|
71
|
+
const _SqlOption = Symbol('SqlOption');
|
|
72
|
+
const _GlobalSqlOption = Symbol('GlobalSqlOption');
|
|
73
|
+
const _EventBus = Symbol('EventBus');
|
|
74
|
+
const _path = Symbol('path');
|
|
75
|
+
const _fs = Symbol('fs');
|
|
76
|
+
const logger = (0, pino_1.default)({
|
|
77
|
+
name: 'sql',
|
|
78
|
+
transport: {
|
|
79
|
+
target: 'pino-pretty'
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
// #endregion
|
|
83
|
+
// #region 可选配置
|
|
84
|
+
var DBType;
|
|
85
|
+
(function (DBType) {
|
|
86
|
+
DBType[DBType["Mysql"] = 0] = "Mysql";
|
|
87
|
+
DBType[DBType["Sqlite"] = 1] = "Sqlite";
|
|
88
|
+
DBType[DBType["Mongo"] = 2] = "Mongo";
|
|
89
|
+
DBType[DBType["SqliteRemote"] = 3] = "SqliteRemote";
|
|
90
|
+
DBType[DBType["Redis"] = 4] = "Redis";
|
|
91
|
+
DBType[DBType["RedisLock"] = 5] = "RedisLock";
|
|
92
|
+
})(DBType || (exports.DBType = DBType = {}));
|
|
93
|
+
var SqlSyncMode;
|
|
94
|
+
(function (SqlSyncMode) {
|
|
95
|
+
/** 同步执行 */
|
|
96
|
+
SqlSyncMode[SqlSyncMode["Sync"] = 0] = "Sync";
|
|
97
|
+
/** 异步执行 */
|
|
98
|
+
SqlSyncMode[SqlSyncMode["Async"] = 1] = "Async";
|
|
99
|
+
})(SqlSyncMode || (exports.SqlSyncMode = SqlSyncMode = {}));
|
|
100
|
+
var SqlInsertMode;
|
|
101
|
+
(function (SqlInsertMode) {
|
|
102
|
+
/**
|
|
103
|
+
# 默认使用
|
|
104
|
+
** 支持单个、批量,语法 `INSERT INTO XX VALUES (第一条数据), (第二条数据);`
|
|
105
|
+
** 批量执行有性能优势,但无法利用数据库的sql预编译功能
|
|
106
|
+
*/
|
|
107
|
+
SqlInsertMode[SqlInsertMode["Insert"] = 0] = "Insert";
|
|
108
|
+
/**
|
|
109
|
+
# 利用临时表
|
|
110
|
+
## 执行步骤
|
|
111
|
+
1. 建立临时表(从正式表复制)
|
|
112
|
+
2. 数据全部进入临时表
|
|
113
|
+
3. 临时表数据转移到正式表: `INSERT INTO 正式表 SELECT * FROM 临时表`
|
|
114
|
+
4. 删除临时表
|
|
115
|
+
## 注意
|
|
116
|
+
1. 适用于:主键不会冲突、非自增
|
|
117
|
+
2. 临时表的结构复制正式表
|
|
118
|
+
*/
|
|
119
|
+
SqlInsertMode[SqlInsertMode["InsertWithTempTable"] = 1] = "InsertWithTempTable";
|
|
120
|
+
SqlInsertMode[SqlInsertMode["InsertIfNotExists"] = 2] = "InsertIfNotExists";
|
|
121
|
+
/**
|
|
122
|
+
# 插入或者更新
|
|
123
|
+
1. 判断依据是主键
|
|
124
|
+
*/
|
|
125
|
+
SqlInsertMode[SqlInsertMode["Replace"] = 3] = "Replace";
|
|
126
|
+
})(SqlInsertMode || (exports.SqlInsertMode = SqlInsertMode = {}));
|
|
127
|
+
var SqlDelMode;
|
|
128
|
+
(function (SqlDelMode) {
|
|
129
|
+
/**
|
|
130
|
+
##常规删除 默认
|
|
131
|
+
### 例一
|
|
132
|
+
`DELETE FROM WHERE (id = 1) OR (id = 2)`
|
|
133
|
+
### 例二
|
|
134
|
+
`DELETE FROM WHERE (id = 1 AND idx = 11) OR (id = 2 AND idx = 22)`
|
|
135
|
+
*/
|
|
136
|
+
SqlDelMode[SqlDelMode["Common"] = 0] = "Common";
|
|
137
|
+
/*
|
|
138
|
+
## 借助临时表
|
|
139
|
+
### 注意:必须保证where的字段都相同,否则会漏删数据
|
|
140
|
+
DELETE FROM 正式表 INNER JOIN 临时表 WHERE 字段1 = 字段1 AND 字段2 = 字段2
|
|
141
|
+
*/
|
|
142
|
+
SqlDelMode[SqlDelMode["TempTable"] = 1] = "TempTable";
|
|
143
|
+
})(SqlDelMode || (exports.SqlDelMode = SqlDelMode = {}));
|
|
144
|
+
var SqlSelectMode;
|
|
145
|
+
(function (SqlSelectMode) {
|
|
146
|
+
/**
|
|
147
|
+
##常规 默认
|
|
148
|
+
### 例一
|
|
149
|
+
`SELECT * FROM WHERE (id = 1) OR (id = 2)`
|
|
150
|
+
### 例二
|
|
151
|
+
`SELECT * FROM WHERE (id = 1 AND idx = 11) OR (id = 2 AND idx = 22)`
|
|
152
|
+
*/
|
|
153
|
+
SqlSelectMode[SqlSelectMode["Common"] = 0] = "Common";
|
|
154
|
+
/*
|
|
155
|
+
## 借助临时表
|
|
156
|
+
### 注意:必须保证where的字段都相同,否则会漏删数据
|
|
157
|
+
SELECT * FROM 正式表 INNER JOIN 临时表 WHERE 字段1 = 字段1 AND 字段2 = 字段2
|
|
158
|
+
*/
|
|
159
|
+
SqlSelectMode[SqlSelectMode["TempTable"] = 1] = "TempTable";
|
|
160
|
+
})(SqlSelectMode || (exports.SqlSelectMode = SqlSelectMode = {}));
|
|
161
|
+
var SqlTemplateMode;
|
|
162
|
+
(function (SqlTemplateMode) {
|
|
163
|
+
/** 确定返回一个,如果不是一个,将报错,返回类型是T */
|
|
164
|
+
SqlTemplateMode[SqlTemplateMode["AssertOne"] = 0] = "AssertOne";
|
|
165
|
+
/** 可能返回一个,返回类型是T|null */
|
|
166
|
+
SqlTemplateMode[SqlTemplateMode["NotSureOne"] = 1] = "NotSureOne";
|
|
167
|
+
/** 返回多个 */
|
|
168
|
+
SqlTemplateMode[SqlTemplateMode["Many"] = 2] = "Many";
|
|
169
|
+
/** 仅查询记录数量 */
|
|
170
|
+
SqlTemplateMode[SqlTemplateMode["Count"] = 3] = "Count";
|
|
171
|
+
})(SqlTemplateMode || (exports.SqlTemplateMode = SqlTemplateMode = {}));
|
|
172
|
+
var SqlQueryMode;
|
|
173
|
+
(function (SqlQueryMode) {
|
|
174
|
+
SqlQueryMode[SqlQueryMode["One_Row_One_Column_Assert"] = 0] = "One_Row_One_Column_Assert";
|
|
175
|
+
SqlQueryMode[SqlQueryMode["One_Row_One_Column_NotSure"] = 1] = "One_Row_One_Column_NotSure";
|
|
176
|
+
SqlQueryMode[SqlQueryMode["One_Row_Many_Column_Assert"] = 2] = "One_Row_Many_Column_Assert";
|
|
177
|
+
SqlQueryMode[SqlQueryMode["One_Row_Many_Column_NotSure"] = 3] = "One_Row_Many_Column_NotSure";
|
|
178
|
+
SqlQueryMode[SqlQueryMode["Many_Row_One_Column"] = 4] = "Many_Row_One_Column";
|
|
179
|
+
SqlQueryMode[SqlQueryMode["Many_Row_Many_Column"] = 5] = "Many_Row_Many_Column";
|
|
180
|
+
})(SqlQueryMode || (exports.SqlQueryMode = SqlQueryMode = {}));
|
|
181
|
+
var SqlType;
|
|
182
|
+
(function (SqlType) {
|
|
183
|
+
SqlType[SqlType["bigint"] = 0] = "bigint";
|
|
184
|
+
SqlType[SqlType["char"] = 1] = "char";
|
|
185
|
+
SqlType[SqlType["decimal"] = 2] = "decimal";
|
|
186
|
+
SqlType[SqlType["int"] = 3] = "int";
|
|
187
|
+
SqlType[SqlType["longtext"] = 4] = "longtext";
|
|
188
|
+
SqlType[SqlType["mediumtext"] = 5] = "mediumtext";
|
|
189
|
+
SqlType[SqlType["smallint"] = 6] = "smallint";
|
|
190
|
+
SqlType[SqlType["text"] = 7] = "text";
|
|
191
|
+
SqlType[SqlType["tinyint"] = 8] = "tinyint";
|
|
192
|
+
SqlType[SqlType["varchar"] = 9] = "varchar";
|
|
193
|
+
})(SqlType || (exports.SqlType = SqlType = {}));
|
|
194
|
+
exports.SqliteMemory = ':memory:';
|
|
195
|
+
const _defOption = {
|
|
196
|
+
maxDeal: 500,
|
|
197
|
+
skipUndefined: true,
|
|
198
|
+
skipNull: true,
|
|
199
|
+
skipEmptyString: true
|
|
200
|
+
};
|
|
201
|
+
;
|
|
202
|
+
class MysqlConnection {
|
|
203
|
+
constructor(conn) {
|
|
204
|
+
this[_a] = false;
|
|
205
|
+
this[_daoConnection] = conn;
|
|
206
|
+
}
|
|
207
|
+
execute(sync, sql, params) {
|
|
208
|
+
logger.debug(sql, params ?? '');
|
|
209
|
+
if (!sql) {
|
|
210
|
+
return { affectedRows: 0, insertId: 0n };
|
|
211
|
+
}
|
|
212
|
+
;
|
|
213
|
+
if (sync === SqlSyncMode.Sync) {
|
|
214
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
215
|
+
return { affectedRows: 0, insertId: 0n };
|
|
216
|
+
}
|
|
217
|
+
;
|
|
218
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
219
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
220
|
+
}
|
|
221
|
+
return new Promise(async (resolve) => {
|
|
222
|
+
try {
|
|
223
|
+
const [_result] = await this[_daoConnection].execute(sql, params);
|
|
224
|
+
const result = _result;
|
|
225
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
226
|
+
logger.trace(result);
|
|
227
|
+
}
|
|
228
|
+
resolve({ affectedRows: result.affectedRows, insertId: result.insertId });
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
logger.error(`
|
|
232
|
+
error: ${error},
|
|
233
|
+
sql: ${sql},
|
|
234
|
+
params: ${params}
|
|
235
|
+
`);
|
|
236
|
+
throw error;
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
pluck(sync, sql, params) {
|
|
241
|
+
logger.debug(sql, params ?? '');
|
|
242
|
+
if (!sql) {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
;
|
|
246
|
+
if (sync === SqlSyncMode.Sync) {
|
|
247
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
248
|
+
return null;
|
|
249
|
+
}
|
|
250
|
+
;
|
|
251
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
252
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
253
|
+
}
|
|
254
|
+
return new Promise(async (resolve) => {
|
|
255
|
+
try {
|
|
256
|
+
const [result] = await this[_daoConnection].query(sql, params);
|
|
257
|
+
if (result && result[0]) {
|
|
258
|
+
const r = Object.values(result[0])[0];
|
|
259
|
+
if (r === null)
|
|
260
|
+
resolve(r);
|
|
261
|
+
else
|
|
262
|
+
resolve(r);
|
|
263
|
+
}
|
|
264
|
+
resolve(null);
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
logger.error(`
|
|
268
|
+
error: ${error},
|
|
269
|
+
sql: ${sql},
|
|
270
|
+
params: ${params}
|
|
271
|
+
`);
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
get(sync, sql, params) {
|
|
277
|
+
logger.debug(sql, params ?? '');
|
|
278
|
+
if (!sql) {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
;
|
|
282
|
+
if (sync === SqlSyncMode.Sync) {
|
|
283
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
;
|
|
287
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
288
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
289
|
+
}
|
|
290
|
+
return new Promise(async (resolve) => {
|
|
291
|
+
try {
|
|
292
|
+
const [result] = await this[_daoConnection].query(sql, params);
|
|
293
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
294
|
+
logger.trace(result);
|
|
295
|
+
}
|
|
296
|
+
if (result && result[0])
|
|
297
|
+
resolve(result[0]);
|
|
298
|
+
resolve(null);
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
logger.error(`
|
|
302
|
+
error: ${error},
|
|
303
|
+
sql: ${sql},
|
|
304
|
+
params: ${params}
|
|
305
|
+
`);
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
raw(sync, sql, params) {
|
|
311
|
+
logger.debug(sql, params ?? '');
|
|
312
|
+
if (!sql) {
|
|
313
|
+
return [];
|
|
314
|
+
}
|
|
315
|
+
;
|
|
316
|
+
if (sync === SqlSyncMode.Sync) {
|
|
317
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
318
|
+
return [];
|
|
319
|
+
}
|
|
320
|
+
;
|
|
321
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
322
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
323
|
+
}
|
|
324
|
+
return new Promise(async (resolve) => {
|
|
325
|
+
try {
|
|
326
|
+
const [result] = await this[_daoConnection].query(sql, params);
|
|
327
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
328
|
+
logger.trace(result);
|
|
329
|
+
}
|
|
330
|
+
if (result)
|
|
331
|
+
resolve(result.map((i) => Object.values(i)[0]));
|
|
332
|
+
resolve([]);
|
|
333
|
+
}
|
|
334
|
+
catch (error) {
|
|
335
|
+
logger.error(`
|
|
336
|
+
error: ${error},
|
|
337
|
+
sql: ${sql},
|
|
338
|
+
params: ${params}
|
|
339
|
+
`);
|
|
340
|
+
throw error;
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
query(sync, sql, params) {
|
|
345
|
+
logger.debug(sql, params ?? '');
|
|
346
|
+
if (!sql) {
|
|
347
|
+
return [];
|
|
348
|
+
}
|
|
349
|
+
;
|
|
350
|
+
if (sync === SqlSyncMode.Sync) {
|
|
351
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
352
|
+
return [];
|
|
353
|
+
}
|
|
354
|
+
;
|
|
355
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
356
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
357
|
+
}
|
|
358
|
+
return new Promise(async (resolve) => {
|
|
359
|
+
try {
|
|
360
|
+
const [result] = await this[_daoConnection].query(sql, params);
|
|
361
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
362
|
+
logger.trace(result);
|
|
363
|
+
}
|
|
364
|
+
resolve(result);
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
logger.error(`
|
|
368
|
+
error: ${error},
|
|
369
|
+
sql: ${sql},
|
|
370
|
+
params: ${params}
|
|
371
|
+
`);
|
|
372
|
+
throw error;
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
realse(sync) {
|
|
377
|
+
if (sync === SqlSyncMode.Sync) {
|
|
378
|
+
try {
|
|
379
|
+
this[_daoConnection]?.release();
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
_a = _inTransaction;
|
|
388
|
+
class Mysql {
|
|
389
|
+
constructor(pool) {
|
|
390
|
+
this[_daoDB] = pool;
|
|
391
|
+
}
|
|
392
|
+
createConnection(sync) {
|
|
393
|
+
if (sync === SqlSyncMode.Sync) {
|
|
394
|
+
logger.error('MYSQL not suppouted sync mode');
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
;
|
|
398
|
+
return new Promise(async (resolve) => {
|
|
399
|
+
const connection = await this[_daoDB].getConnection();
|
|
400
|
+
logger.debug('create new!');
|
|
401
|
+
resolve(new MysqlConnection(connection));
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
transaction(sync, fn, conn) {
|
|
405
|
+
if (sync === SqlSyncMode.Sync) {
|
|
406
|
+
logger.warn('MYSQL not suppouted sync mode');
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
;
|
|
410
|
+
return new Promise(async (resolve) => {
|
|
411
|
+
let needCommit = false;
|
|
412
|
+
let newConn = false;
|
|
413
|
+
if (!conn) {
|
|
414
|
+
conn = await this.createConnection(SqlSyncMode.Async) ?? undefined;
|
|
415
|
+
newConn = true;
|
|
416
|
+
}
|
|
417
|
+
if (conn?.[_inTransaction] !== true) {
|
|
418
|
+
needCommit = true;
|
|
419
|
+
logger.debug('beginTransaction begin!');
|
|
420
|
+
await conn[_daoConnection].beginTransaction();
|
|
421
|
+
logger.debug('beginTransaction end!');
|
|
422
|
+
}
|
|
423
|
+
conn[_inTransaction] = true;
|
|
424
|
+
try {
|
|
425
|
+
const result = await fn(conn);
|
|
426
|
+
if (needCommit === true) {
|
|
427
|
+
logger.debug('commit begin!');
|
|
428
|
+
await conn[_daoConnection].commit();
|
|
429
|
+
conn[_inTransaction] = false;
|
|
430
|
+
logger.debug('commit end!');
|
|
431
|
+
}
|
|
432
|
+
resolve(result);
|
|
433
|
+
}
|
|
434
|
+
catch (error) {
|
|
435
|
+
logger.debug('rollback begin!');
|
|
436
|
+
await conn[_daoConnection].rollback();
|
|
437
|
+
logger.debug('rollback end!');
|
|
438
|
+
conn[_inTransaction] = false;
|
|
439
|
+
logger.error(error);
|
|
440
|
+
throw error;
|
|
441
|
+
}
|
|
442
|
+
finally {
|
|
443
|
+
try {
|
|
444
|
+
if (needCommit === true) {
|
|
445
|
+
conn[_inTransaction] = false;
|
|
446
|
+
}
|
|
447
|
+
if (newConn === true) {
|
|
448
|
+
logger.debug('release begin!');
|
|
449
|
+
conn[_daoConnection].release();
|
|
450
|
+
logger.debug('release end!');
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
close(sync) {
|
|
459
|
+
if (sync === SqlSyncMode.Sync) {
|
|
460
|
+
this[_daoDB]?.destroy();
|
|
461
|
+
}
|
|
462
|
+
;
|
|
463
|
+
}
|
|
464
|
+
backup(sync, name) {
|
|
465
|
+
}
|
|
466
|
+
remove(sync) {
|
|
467
|
+
}
|
|
468
|
+
restore(sync, name) {
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
class SqliteConnection {
|
|
472
|
+
constructor(conn) {
|
|
473
|
+
this[_b] = false;
|
|
474
|
+
this[_daoConnection] = conn;
|
|
475
|
+
}
|
|
476
|
+
execute(sync, sql, params) {
|
|
477
|
+
try {
|
|
478
|
+
logger.debug(sql, params ?? '');
|
|
479
|
+
if (!sql) {
|
|
480
|
+
return { affectedRows: 0, insertId: 0n };
|
|
481
|
+
}
|
|
482
|
+
;
|
|
483
|
+
if (sync === SqlSyncMode.Async) {
|
|
484
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
485
|
+
return { affectedRows: 0, insertId: 0n };
|
|
486
|
+
}
|
|
487
|
+
;
|
|
488
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
489
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
490
|
+
}
|
|
491
|
+
const result = this[_daoConnection].prepare(sql).run(params ?? {});
|
|
492
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
493
|
+
logger.trace(result);
|
|
494
|
+
}
|
|
495
|
+
const { changes, lastInsertRowid } = result;
|
|
496
|
+
return { affectedRows: changes, insertId: lastInsertRowid ? BigInt(lastInsertRowid) : 0n };
|
|
497
|
+
}
|
|
498
|
+
catch (error) {
|
|
499
|
+
logger.error(`
|
|
500
|
+
error: ${error},
|
|
501
|
+
sql: ${sql},
|
|
502
|
+
params: ${params}
|
|
503
|
+
`);
|
|
504
|
+
throw error;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
pluck(sync, sql, params) {
|
|
508
|
+
try {
|
|
509
|
+
logger.debug(sql, params ?? '');
|
|
510
|
+
if (!sql) {
|
|
511
|
+
return null;
|
|
512
|
+
}
|
|
513
|
+
;
|
|
514
|
+
if (sync === SqlSyncMode.Async) {
|
|
515
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
516
|
+
return null;
|
|
517
|
+
}
|
|
518
|
+
;
|
|
519
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
520
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
521
|
+
}
|
|
522
|
+
return this[_daoConnection].prepare(sql).pluck().get(params ?? {});
|
|
523
|
+
}
|
|
524
|
+
catch (error) {
|
|
525
|
+
logger.error(`
|
|
526
|
+
error: ${error},
|
|
527
|
+
sql: ${sql},
|
|
528
|
+
params: ${params}
|
|
529
|
+
`);
|
|
530
|
+
throw error;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
get(sync, sql, params) {
|
|
534
|
+
try {
|
|
535
|
+
logger.debug(sql, params ?? '');
|
|
536
|
+
if (!sql) {
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
;
|
|
540
|
+
if (sync === SqlSyncMode.Async) {
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
543
|
+
;
|
|
544
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
545
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
546
|
+
}
|
|
547
|
+
return this[_daoConnection].prepare(sql).get(params ?? {});
|
|
548
|
+
}
|
|
549
|
+
catch (error) {
|
|
550
|
+
logger.error(`
|
|
551
|
+
error: ${error},
|
|
552
|
+
sql: ${sql},
|
|
553
|
+
params: ${params}
|
|
554
|
+
`);
|
|
555
|
+
throw error;
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
raw(sync, sql, params) {
|
|
559
|
+
try {
|
|
560
|
+
logger.debug(sql, params ?? '');
|
|
561
|
+
if (!sql) {
|
|
562
|
+
return [];
|
|
563
|
+
}
|
|
564
|
+
;
|
|
565
|
+
if (sync === SqlSyncMode.Async) {
|
|
566
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
567
|
+
return [];
|
|
568
|
+
}
|
|
569
|
+
;
|
|
570
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
571
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
572
|
+
}
|
|
573
|
+
return this[_daoConnection].prepare(sql).raw().all(params ?? {});
|
|
574
|
+
}
|
|
575
|
+
catch (error) {
|
|
576
|
+
logger.error(`
|
|
577
|
+
error: ${error},
|
|
578
|
+
sql: ${sql},
|
|
579
|
+
params: ${params}
|
|
580
|
+
`);
|
|
581
|
+
throw error;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
query(sync, sql, params) {
|
|
585
|
+
try {
|
|
586
|
+
logger.debug(sql, params ?? '');
|
|
587
|
+
if (!sql) {
|
|
588
|
+
return [];
|
|
589
|
+
}
|
|
590
|
+
;
|
|
591
|
+
if (sync === SqlSyncMode.Async) {
|
|
592
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
593
|
+
return [];
|
|
594
|
+
}
|
|
595
|
+
;
|
|
596
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
597
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
598
|
+
}
|
|
599
|
+
return this[_daoConnection].prepare(sql).all(params ?? {});
|
|
600
|
+
}
|
|
601
|
+
catch (error) {
|
|
602
|
+
logger.error(`
|
|
603
|
+
error: ${error},
|
|
604
|
+
sql: ${sql},
|
|
605
|
+
params: ${params}
|
|
606
|
+
`);
|
|
607
|
+
throw error;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
realse(sync) {
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
_b = _inTransaction;
|
|
614
|
+
class Sqlite {
|
|
615
|
+
constructor(db) {
|
|
616
|
+
this[_daoDB] = db;
|
|
617
|
+
this[_daoDB].pragma('journal_mode = WAL');
|
|
618
|
+
this[_daoDB].exec(`
|
|
619
|
+
CREATE TABLE IF NOT EXISTS DUAL ( ______id INTEGER NOT NULL, PRIMARY KEY ( ______id ));
|
|
620
|
+
DELETE FROM DUAL;
|
|
621
|
+
INSERT INTO DUAL (______id ) VALUES ( 1 );
|
|
622
|
+
CREATE TABLE IF NOT EXISTS TABLE_VERSION (
|
|
623
|
+
______tableName text NOT NULL,
|
|
624
|
+
______version text NOT NULL,
|
|
625
|
+
PRIMARY KEY ( ______tableName )
|
|
626
|
+
);
|
|
627
|
+
`);
|
|
628
|
+
}
|
|
629
|
+
createConnection(sync) {
|
|
630
|
+
if (sync === SqlSyncMode.Async) {
|
|
631
|
+
logger.error(`SQLITE not suppoted async mode`);
|
|
632
|
+
return null;
|
|
633
|
+
}
|
|
634
|
+
;
|
|
635
|
+
return new SqliteConnection(this[_daoDB]);
|
|
636
|
+
}
|
|
637
|
+
transaction(sync, fn, conn) {
|
|
638
|
+
if (sync === SqlSyncMode.Async) {
|
|
639
|
+
logger.warn(`SQLITE not suppoted async mode`);
|
|
640
|
+
return null;
|
|
641
|
+
}
|
|
642
|
+
;
|
|
643
|
+
if (!conn) {
|
|
644
|
+
conn = this.createConnection(SqlSyncMode.Sync) ?? undefined;
|
|
645
|
+
}
|
|
646
|
+
if (conn[_inTransaction] !== true) {
|
|
647
|
+
return this[_daoDB].transaction(() => {
|
|
648
|
+
conn[_inTransaction] = true;
|
|
649
|
+
const rt = fn(conn);
|
|
650
|
+
conn[_inTransaction] = false;
|
|
651
|
+
return rt;
|
|
652
|
+
})();
|
|
653
|
+
}
|
|
654
|
+
else {
|
|
655
|
+
const rt = fn(conn);
|
|
656
|
+
return rt;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
close(sync) {
|
|
660
|
+
if (sync === SqlSyncMode.Sync) {
|
|
661
|
+
this[_daoDB].close();
|
|
662
|
+
}
|
|
663
|
+
;
|
|
664
|
+
}
|
|
665
|
+
backup(sync, name) {
|
|
666
|
+
if (sync === SqlSyncMode.Sync) {
|
|
667
|
+
this[_daoDB].backup(name);
|
|
668
|
+
}
|
|
669
|
+
;
|
|
670
|
+
}
|
|
671
|
+
remove(sync) {
|
|
672
|
+
}
|
|
673
|
+
restore(sync, name) {
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
class SqliteRemoteConnection {
|
|
677
|
+
constructor(conn, name) {
|
|
678
|
+
this[_c] = false;
|
|
679
|
+
this[_daoConnection] = conn;
|
|
680
|
+
this[_sqliteRemoteName] = name;
|
|
681
|
+
}
|
|
682
|
+
execute(sync, sql, params) {
|
|
683
|
+
logger.debug(sql, params ?? '');
|
|
684
|
+
if (!sql) {
|
|
685
|
+
return { affectedRows: 0, insertId: 0n };
|
|
686
|
+
}
|
|
687
|
+
;
|
|
688
|
+
if (sync === SqlSyncMode.Sync) {
|
|
689
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
690
|
+
return { affectedRows: 0, insertId: 0n };
|
|
691
|
+
}
|
|
692
|
+
;
|
|
693
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
694
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
695
|
+
}
|
|
696
|
+
return new Promise(async (resolve) => {
|
|
697
|
+
try {
|
|
698
|
+
const { affectedRows, insertId } = await this[_daoConnection].execute(this[_sqliteRemoteName], sql, params);
|
|
699
|
+
resolve({ affectedRows, insertId: insertId ? BigInt(insertId) : 0n });
|
|
700
|
+
}
|
|
701
|
+
catch (error) {
|
|
702
|
+
logger.error(`
|
|
703
|
+
error: ${error},
|
|
704
|
+
sql: ${sql},
|
|
705
|
+
params: ${params}
|
|
706
|
+
`);
|
|
707
|
+
throw error;
|
|
708
|
+
}
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
pluck(sync, sql, params) {
|
|
712
|
+
logger.debug(sql, params ?? '');
|
|
713
|
+
if (!sql) {
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
;
|
|
717
|
+
if (sync === SqlSyncMode.Sync) {
|
|
718
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
719
|
+
return null;
|
|
720
|
+
}
|
|
721
|
+
;
|
|
722
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
723
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
724
|
+
}
|
|
725
|
+
return new Promise(async (resolve) => {
|
|
726
|
+
try {
|
|
727
|
+
const r = await this[_daoConnection].pluck(this[_sqliteRemoteName], sql, params);
|
|
728
|
+
resolve(r);
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
logger.error(`
|
|
732
|
+
error: ${error},
|
|
733
|
+
sql: ${sql},
|
|
734
|
+
params: ${params}
|
|
735
|
+
`);
|
|
736
|
+
throw error;
|
|
737
|
+
}
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
get(sync, sql, params) {
|
|
741
|
+
logger.debug(sql, params ?? '');
|
|
742
|
+
if (!sql) {
|
|
743
|
+
return null;
|
|
744
|
+
}
|
|
745
|
+
;
|
|
746
|
+
if (sync === SqlSyncMode.Sync) {
|
|
747
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
748
|
+
return null;
|
|
749
|
+
}
|
|
750
|
+
;
|
|
751
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
752
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
753
|
+
}
|
|
754
|
+
return new Promise(async (resolve) => {
|
|
755
|
+
try {
|
|
756
|
+
const r = await this[_daoConnection].get(this[_sqliteRemoteName], sql, params);
|
|
757
|
+
resolve(r);
|
|
758
|
+
}
|
|
759
|
+
catch (error) {
|
|
760
|
+
logger.error(`
|
|
761
|
+
error: ${error},
|
|
762
|
+
sql: ${sql},
|
|
763
|
+
params: ${params}
|
|
764
|
+
`);
|
|
765
|
+
throw error;
|
|
766
|
+
}
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
raw(sync, sql, params) {
|
|
770
|
+
logger.debug(sql, params ?? '');
|
|
771
|
+
if (!sql) {
|
|
772
|
+
return [];
|
|
773
|
+
}
|
|
774
|
+
;
|
|
775
|
+
if (sync === SqlSyncMode.Sync) {
|
|
776
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
777
|
+
return [];
|
|
778
|
+
}
|
|
779
|
+
;
|
|
780
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
781
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
782
|
+
}
|
|
783
|
+
return new Promise(async (resolve) => {
|
|
784
|
+
try {
|
|
785
|
+
const r = await this[_daoConnection].raw(this[_sqliteRemoteName], sql, params);
|
|
786
|
+
resolve(r);
|
|
787
|
+
}
|
|
788
|
+
catch (error) {
|
|
789
|
+
logger.error(`
|
|
790
|
+
error: ${error},
|
|
791
|
+
sql: ${sql},
|
|
792
|
+
params: ${params}
|
|
793
|
+
`);
|
|
794
|
+
throw error;
|
|
795
|
+
}
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
query(sync, sql, params) {
|
|
799
|
+
logger.debug(sql, params ?? '');
|
|
800
|
+
if (!sql) {
|
|
801
|
+
return [];
|
|
802
|
+
}
|
|
803
|
+
;
|
|
804
|
+
if (sync === SqlSyncMode.Sync) {
|
|
805
|
+
logger.warn('SqliteRemote not suppouted sync mode');
|
|
806
|
+
return [];
|
|
807
|
+
}
|
|
808
|
+
;
|
|
809
|
+
if (globalThis[_GlobalSqlOption].log === 'trace') {
|
|
810
|
+
logger.trace(sqlstring_1.default.format(sql, params));
|
|
811
|
+
}
|
|
812
|
+
return new Promise(async (resolve) => {
|
|
813
|
+
try {
|
|
814
|
+
const r = await this[_daoConnection].query(this[_sqliteRemoteName], sql, params);
|
|
815
|
+
resolve(r);
|
|
816
|
+
}
|
|
817
|
+
catch (error) {
|
|
818
|
+
logger.error(`
|
|
819
|
+
error: ${error},
|
|
820
|
+
sql: ${sql},
|
|
821
|
+
params: ${params}
|
|
822
|
+
`);
|
|
823
|
+
throw error;
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
realse(sync) {
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
_c = _inTransaction;
|
|
831
|
+
class SqliteRemote {
|
|
832
|
+
constructor(db, name) {
|
|
833
|
+
this[_daoDB] = db;
|
|
834
|
+
this[_sqliteRemoteName] = name;
|
|
835
|
+
}
|
|
836
|
+
createConnection(sync) {
|
|
837
|
+
if (sync === SqlSyncMode.Sync) {
|
|
838
|
+
logger.error('SQLITEREMOTE not suppouted sync mode');
|
|
839
|
+
return null;
|
|
840
|
+
}
|
|
841
|
+
;
|
|
842
|
+
return new Promise(async (resolve) => {
|
|
843
|
+
resolve(new SqliteRemoteConnection(this[_daoDB], this[_sqliteRemoteName]));
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
transaction(sync, fn, conn) {
|
|
847
|
+
logger.warn(`SQLITEREMOTE not suppoted transaction`);
|
|
848
|
+
return null;
|
|
849
|
+
}
|
|
850
|
+
close(sync) {
|
|
851
|
+
if (sync === SqlSyncMode.Async) {
|
|
852
|
+
return new Promise(async () => {
|
|
853
|
+
await this[_daoConnection].close();
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
;
|
|
857
|
+
}
|
|
858
|
+
backup(sync, name) {
|
|
859
|
+
if (sync === SqlSyncMode.Async) {
|
|
860
|
+
return new Promise(async () => {
|
|
861
|
+
await this[_daoConnection].backup(this[_sqliteRemoteName], name);
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
;
|
|
865
|
+
}
|
|
866
|
+
remove(sync) {
|
|
867
|
+
if (sync === SqlSyncMode.Async) {
|
|
868
|
+
return new Promise(async () => {
|
|
869
|
+
await this[_daoConnection].remove();
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
;
|
|
873
|
+
}
|
|
874
|
+
restore(sync, name) {
|
|
875
|
+
if (sync === SqlSyncMode.Async) {
|
|
876
|
+
return new Promise(async () => {
|
|
877
|
+
await this[_daoConnection].restore(this[_sqliteRemoteName], name);
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
;
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
class SqlCache {
|
|
884
|
+
constructor() {
|
|
885
|
+
this.cache = {};
|
|
886
|
+
}
|
|
887
|
+
async init(options) {
|
|
888
|
+
if (options.sqlDir) {
|
|
889
|
+
const sqlFis = globalThis[_fs].readdirSync(options.sqlDir);
|
|
890
|
+
for (const modeName of sqlFis) {
|
|
891
|
+
const name = globalThis[_path].basename(modeName, globalThis[_path].extname(modeName));
|
|
892
|
+
const obj = await Promise.resolve(`${globalThis[_path].join(options.sqlDir, modeName)}`).then(s => __importStar(require(s)));
|
|
893
|
+
for (const [key, fn] of Object.entries(obj)) {
|
|
894
|
+
this.cache[`${name}.${String(key)}`] = fn;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
else if (options.sqlCache) {
|
|
899
|
+
this.cache = options.sqlCache;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
load(sqlid, params, context, isPage) {
|
|
903
|
+
const sqlSource = this.cache[sqlid];
|
|
904
|
+
error_1.Throw.if(!sqlSource, `指定的语句${sqlid}不存在!`);
|
|
905
|
+
if (typeof sqlSource === 'string') {
|
|
906
|
+
return sqlSource;
|
|
907
|
+
}
|
|
908
|
+
else {
|
|
909
|
+
return sqlSource(params, context, isPage);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
// #endregion
|
|
914
|
+
/**
|
|
915
|
+
|
|
916
|
+
## 所有service中内置方法定义规则
|
|
917
|
+
** 方法第一个参数必须是 sync: SyncMode
|
|
918
|
+
** 方法最后一个参数必须是 option
|
|
919
|
+
|
|
920
|
+
## sync 表示是否是同步方法
|
|
921
|
+
|
|
922
|
+
因为mysql是异步、sqlite是同步,导致必须通过一个标识来区分,否则将必须为两种数据库设置不同的service,失去了意义
|
|
923
|
+
|
|
924
|
+
## option 额外控制参数
|
|
925
|
+
|
|
926
|
+
## length
|
|
927
|
+
方法的参数数量
|
|
928
|
+
*/
|
|
929
|
+
function P(skipConn = false) {
|
|
930
|
+
return (_target, propertyKey, descriptor) => {
|
|
931
|
+
const fn = descriptor.value;
|
|
932
|
+
descriptor.value = function (...args) {
|
|
933
|
+
let needRealseConn = true;
|
|
934
|
+
const startTime = +new Date();
|
|
935
|
+
// option
|
|
936
|
+
const option = args[0] = Object.assign({}, globalThis[_GlobalSqlOption], this[_SqlOption], args[0]);
|
|
937
|
+
option.sync ?? (option.sync = SqlSyncMode.Async);
|
|
938
|
+
const dbName = option?.dbName ?? this[_daoDBName] ?? _primaryDB;
|
|
939
|
+
option.dao = globalThis[_dao][this[_dbType]][dbName];
|
|
940
|
+
error_1.Throw.if(!option.dao, `not found db:${String(dbName)}(${this[_dbType]})`);
|
|
941
|
+
option.tableName = option?.tableName ?? this[_tableName];
|
|
942
|
+
const tableES = sqlstring_1.default.escapeId(option.tableName);
|
|
943
|
+
if (this[_dbType] === DBType.Sqlite) {
|
|
944
|
+
error_1.Throw.if(option.sync === SqlSyncMode.Async, 'sqlite can not Async!');
|
|
945
|
+
// 连接共享
|
|
946
|
+
if (skipConn === false && !option.conn) {
|
|
947
|
+
option.conn = option.dao.createConnection(SqlSyncMode.Sync);
|
|
948
|
+
}
|
|
949
|
+
else {
|
|
950
|
+
needRealseConn = false;
|
|
951
|
+
}
|
|
952
|
+
if (skipConn === false) {
|
|
953
|
+
const lastVersion = this[_sqlite_version] ?? '0.0.1';
|
|
954
|
+
// 检查表
|
|
955
|
+
const tableCheckResult = option.conn.pluck(SqlSyncMode.Sync, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
|
|
956
|
+
if (tableCheckResult) {
|
|
957
|
+
// 旧版本
|
|
958
|
+
const tableVersion = option.conn.pluck(SqlSyncMode.Sync, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
|
|
959
|
+
if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
|
|
960
|
+
// 更新版本
|
|
961
|
+
const columns = (0, iterare_1.default)(option.conn.query(SqlSyncMode.Sync, `PRAGMA table_info(${tableES})`))
|
|
962
|
+
.filter(c => this[_fields].hasOwnProperty(c.name))
|
|
963
|
+
.map(c => sqlstring_1.default.escapeId(c.name))
|
|
964
|
+
.join(',');
|
|
965
|
+
const rtable = sqlstring_1.default.escapeId(`${option.tableName}_${tableVersion.replace(/\./, '_')}`);
|
|
966
|
+
option.conn.execute(SqlSyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
|
|
967
|
+
option.conn.execute(SqlSyncMode.Sync, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
|
|
968
|
+
option.conn.execute(SqlSyncMode.Sync, `
|
|
969
|
+
CREATE TABLE IF NOT EXISTS ${tableES}(
|
|
970
|
+
${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
|
|
971
|
+
${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
|
|
972
|
+
);
|
|
973
|
+
`);
|
|
974
|
+
if (this[_index] && this[_index].length) {
|
|
975
|
+
for (const index of this[_index]) {
|
|
976
|
+
option.conn.execute(SqlSyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
option.conn.execute(SqlSyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
980
|
+
option.conn.execute(SqlSyncMode.Sync, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
981
|
+
option.conn.execute(SqlSyncMode.Sync, `DROP TABLE IF EXISTS ${rtable};`);
|
|
982
|
+
// 更新完毕,保存版本号
|
|
983
|
+
option.conn.execute(SqlSyncMode.Sync, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
|
|
984
|
+
}
|
|
985
|
+
else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
|
|
986
|
+
option.conn.execute(SqlSyncMode.Sync, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
else { // 表不存在
|
|
990
|
+
// 创建表
|
|
991
|
+
option.conn.execute(SqlSyncMode.Sync, `
|
|
992
|
+
CREATE TABLE IF NOT EXISTS ${tableES} (
|
|
993
|
+
${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
|
|
994
|
+
${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
|
|
995
|
+
|
|
996
|
+
);
|
|
997
|
+
`);
|
|
998
|
+
if (this[_index] && this[_index].length) {
|
|
999
|
+
for (const index of this[_index]) {
|
|
1000
|
+
option.conn.execute(SqlSyncMode.Sync, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
option.conn.execute(SqlSyncMode.Sync, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
try {
|
|
1007
|
+
const result = fn.call(this, ...args);
|
|
1008
|
+
logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
|
|
1009
|
+
return result;
|
|
1010
|
+
}
|
|
1011
|
+
catch (error) {
|
|
1012
|
+
try {
|
|
1013
|
+
console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
|
|
1014
|
+
}
|
|
1015
|
+
catch (error) {
|
|
1016
|
+
}
|
|
1017
|
+
throw error;
|
|
1018
|
+
}
|
|
1019
|
+
finally {
|
|
1020
|
+
if (needRealseConn && option && option.conn) {
|
|
1021
|
+
try {
|
|
1022
|
+
option.conn.realse(SqlSyncMode.Sync);
|
|
1023
|
+
}
|
|
1024
|
+
catch (error) {
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
else if (this[_dbType] === DBType.SqliteRemote) {
|
|
1030
|
+
error_1.Throw.if(option.sync === SqlSyncMode.Sync, 'SqliteRemote remote can not sync!');
|
|
1031
|
+
return new Promise(async (resolve) => {
|
|
1032
|
+
// 连接共享
|
|
1033
|
+
if (skipConn === false && !option.conn) {
|
|
1034
|
+
(option).conn = await option.dao.createConnection(SqlSyncMode.Async);
|
|
1035
|
+
}
|
|
1036
|
+
else {
|
|
1037
|
+
needRealseConn = false;
|
|
1038
|
+
}
|
|
1039
|
+
if (skipConn === false) {
|
|
1040
|
+
const lastVersion = this[_sqlite_version] ?? '0.0.1';
|
|
1041
|
+
// 检查表
|
|
1042
|
+
const tableCheckResult = await option.conn.pluck(SqlSyncMode.Async, `SELECT COUNT(1) t FROM sqlite_master WHERE TYPE = 'table' AND name = ?`, [option.tableName]);
|
|
1043
|
+
if (tableCheckResult) {
|
|
1044
|
+
// 旧版本
|
|
1045
|
+
const tableVersion = await option.conn.pluck(SqlSyncMode.Async, 'SELECT ______version v from TABLE_VERSION WHERE ______tableName = ?', [option.tableName]);
|
|
1046
|
+
if (tableVersion && tableVersion < lastVersion) { // 发现需要升级的版本
|
|
1047
|
+
// 更新版本
|
|
1048
|
+
const columns = (0, iterare_1.default)(await option.conn.query(SqlSyncMode.Async, `PRAGMA table_info(${tableES})`))
|
|
1049
|
+
.filter(c => this[_fields].hasOwnProperty(c.name))
|
|
1050
|
+
.map(c => sqlstring_1.default.escapeId(c.name))
|
|
1051
|
+
.join(',');
|
|
1052
|
+
const rtable = `${option.tableName}_${tableVersion.replace(/\./, '_')}`;
|
|
1053
|
+
await option.conn.execute(SqlSyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
|
|
1054
|
+
await option.conn.execute(SqlSyncMode.Async, `ALTER TABLE ${tableES} RENAME TO ${rtable};`);
|
|
1055
|
+
await option.conn.execute(SqlSyncMode.Async, `
|
|
1056
|
+
CREATE TABLE IF NOT EXISTS ${tableES}(
|
|
1057
|
+
${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
|
|
1058
|
+
${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
|
|
1059
|
+
);
|
|
1060
|
+
`);
|
|
1061
|
+
if (this[_index] && this[_index].length) {
|
|
1062
|
+
for (const index of this[_index]) {
|
|
1063
|
+
await option.conn.execute(SqlSyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableES} ("${index}");`);
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
await option.conn.execute(SqlSyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
1067
|
+
await option.conn.execute(SqlSyncMode.Async, `INSERT INTO ${tableES} (${columns}) SELECT ${columns} FROM ${rtable};`);
|
|
1068
|
+
await option.conn.execute(SqlSyncMode.Async, `DROP TABLE IF EXISTS ${rtable};`);
|
|
1069
|
+
// 更新完毕,保存版本号
|
|
1070
|
+
await option.conn.execute(SqlSyncMode.Async, 'UPDATE TABLE_VERSION SET ______version = ? WHERE ______tableName = ?', [option.tableName, lastVersion]);
|
|
1071
|
+
}
|
|
1072
|
+
else if (!tableVersion) { // 不需要升级情况:没有旧的版本号
|
|
1073
|
+
await option.conn.execute(SqlSyncMode.Async, 'INSERT INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
else { // 表不存在
|
|
1077
|
+
// 创建表
|
|
1078
|
+
await option.conn.execute(SqlSyncMode.Async, `
|
|
1079
|
+
CREATE TABLE IF NOT EXISTS ${tableES}(
|
|
1080
|
+
${Object.values(this[_fields]).map(K => K[DBType.Sqlite]).join(',')}
|
|
1081
|
+
${this[_ids] && this[_ids].length ? `, PRIMARY KEY (${this[_ids].map(i => this[_fields][i]?.esName).join(',')})` : ''}
|
|
1082
|
+
);
|
|
1083
|
+
`);
|
|
1084
|
+
if (this[_index] && this[_index].length) {
|
|
1085
|
+
for (const index of this[_index]) {
|
|
1086
|
+
await option.conn.execute(SqlSyncMode.Async, `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${sqlstring_1.default.escapeId(option.tableName)} ("${index}");`);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
await option.conn.execute(SqlSyncMode.Async, 'INSERT OR REPLACE INTO TABLE_VERSION (______tableName, ______version ) VALUES ( ?, ? )', [option.tableName, lastVersion]);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
try {
|
|
1093
|
+
const result = await fn.call(this, ...args);
|
|
1094
|
+
logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
|
|
1095
|
+
resolve(result);
|
|
1096
|
+
}
|
|
1097
|
+
catch (error) {
|
|
1098
|
+
console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
|
|
1099
|
+
throw error;
|
|
1100
|
+
}
|
|
1101
|
+
finally {
|
|
1102
|
+
if (needRealseConn && option && option.conn) {
|
|
1103
|
+
try {
|
|
1104
|
+
option.conn.realse(SqlSyncMode.Sync);
|
|
1105
|
+
}
|
|
1106
|
+
catch (error) {
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
else if (this[_dbType] === DBType.Mysql) {
|
|
1113
|
+
return new Promise(async (resolve) => {
|
|
1114
|
+
try {
|
|
1115
|
+
// 连接共享
|
|
1116
|
+
if (skipConn === false && !option.conn) {
|
|
1117
|
+
(option).conn = await option.dao.createConnection(SqlSyncMode.Async);
|
|
1118
|
+
}
|
|
1119
|
+
else {
|
|
1120
|
+
needRealseConn = false;
|
|
1121
|
+
}
|
|
1122
|
+
const result = await fn.call(this, ...args);
|
|
1123
|
+
logger.info(`${propertyKey}:${option.tableName}:use ${+new Date() - startTime}ms`);
|
|
1124
|
+
resolve(result);
|
|
1125
|
+
}
|
|
1126
|
+
catch (error) {
|
|
1127
|
+
console.error(`service ${propertyKey} have an error:${error}, it's argumens: ${JSON.stringify(args.filter(i => typeof i !== 'object' || (typeof i === 'object' && !i.insert)))}`);
|
|
1128
|
+
throw error;
|
|
1129
|
+
}
|
|
1130
|
+
finally {
|
|
1131
|
+
if (needRealseConn && option && option.conn) {
|
|
1132
|
+
try {
|
|
1133
|
+
option.conn.realse(SqlSyncMode.Sync);
|
|
1134
|
+
}
|
|
1135
|
+
catch (error) {
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
const FieldFilter = (K, V, def, option) => {
|
|
1145
|
+
let ret = 0;
|
|
1146
|
+
if (V === null) {
|
|
1147
|
+
if (option?.skipNull !== true) {
|
|
1148
|
+
ret = 1;
|
|
1149
|
+
V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : null;
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
else if (V === undefined) {
|
|
1153
|
+
if (option?.skipUndefined !== true) {
|
|
1154
|
+
ret = 1;
|
|
1155
|
+
V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : null;
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
else if ((0, string_1.emptyString)(`${V ?? ''}`)) {
|
|
1159
|
+
if (option?.skipEmptyString !== true) {
|
|
1160
|
+
ret = 1;
|
|
1161
|
+
V = option?.def === true && def && def.hasOwnProperty(K) ? def[K] : '';
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
else {
|
|
1165
|
+
ret = 1;
|
|
1166
|
+
}
|
|
1167
|
+
if (ret === 1) {
|
|
1168
|
+
option?.finalColumns?.add(K);
|
|
1169
|
+
option?.tempColumns?.push(K);
|
|
1170
|
+
}
|
|
1171
|
+
return [ret, V];
|
|
1172
|
+
};
|
|
1173
|
+
const MYSQLCHARSET = `CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci`;
|
|
1174
|
+
const Field = (config) => {
|
|
1175
|
+
config.type ?? (config.type = SqlType.varchar);
|
|
1176
|
+
return (object, propertyName) => {
|
|
1177
|
+
const field = config;
|
|
1178
|
+
field.name = propertyName;
|
|
1179
|
+
field.esName = sqlstring_1.default.escapeId(propertyName);
|
|
1180
|
+
const hasDef = field.hasOwnProperty('def') === true;
|
|
1181
|
+
switch (field.type) {
|
|
1182
|
+
case SqlType.bigint: {
|
|
1183
|
+
field[DBType.Mysql] = `${field.esName} bigint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
|
|
1184
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
|
|
1185
|
+
break;
|
|
1186
|
+
}
|
|
1187
|
+
case SqlType.char: {
|
|
1188
|
+
field[DBType.Mysql] = `${field.esName} char(${config.length1 ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
|
|
1189
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
|
|
1190
|
+
break;
|
|
1191
|
+
}
|
|
1192
|
+
case SqlType.decimal: {
|
|
1193
|
+
field[DBType.Mysql] = `${field.esName} decimal(${config.length1 ?? 1}, ${config.length2 ?? 2}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} `;
|
|
1194
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} real`;
|
|
1195
|
+
break;
|
|
1196
|
+
}
|
|
1197
|
+
case SqlType.int: {
|
|
1198
|
+
field[DBType.Mysql] = `${field.esName} int ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
|
|
1199
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} integer`;
|
|
1200
|
+
break;
|
|
1201
|
+
}
|
|
1202
|
+
case SqlType.longtext: {
|
|
1203
|
+
field[DBType.Mysql] = `${field.esName} longtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
|
|
1204
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
|
|
1205
|
+
break;
|
|
1206
|
+
}
|
|
1207
|
+
case SqlType.mediumtext: {
|
|
1208
|
+
field[DBType.Mysql] = `${field.esName} mediumtext ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
|
|
1209
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
|
|
1210
|
+
break;
|
|
1211
|
+
}
|
|
1212
|
+
case SqlType.smallint: {
|
|
1213
|
+
field[DBType.Mysql] = `${field.esName} smallint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
|
|
1214
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
|
|
1215
|
+
break;
|
|
1216
|
+
}
|
|
1217
|
+
case SqlType.text: {
|
|
1218
|
+
field[DBType.Mysql] = `${field.esName} text ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
|
|
1219
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
|
|
1220
|
+
break;
|
|
1221
|
+
}
|
|
1222
|
+
case SqlType.tinyint: {
|
|
1223
|
+
field[DBType.Mysql] = `${field.esName} tinyint ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''}`;
|
|
1224
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
|
|
1225
|
+
break;
|
|
1226
|
+
}
|
|
1227
|
+
case SqlType.varchar: {
|
|
1228
|
+
field[DBType.Mysql] = `${field.esName} varchar(${config.length1 ?? 1}) ${config.notNull === true ? 'NOT NULL' : ''} ${hasDef ? field.def : ''} ${MYSQLCHARSET}`;
|
|
1229
|
+
field[DBType.SqliteRemote] = field[DBType.Sqlite] = `${field.esName} text`;
|
|
1230
|
+
break;
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
;
|
|
1234
|
+
let __fields = Reflect.getMetadata(_fields, object);
|
|
1235
|
+
let __columns = Reflect.getMetadata(_columns, object);
|
|
1236
|
+
let __columnsNoId = Reflect.getMetadata(_columnsNoId, object);
|
|
1237
|
+
let __ids = Reflect.getMetadata(_ids, object);
|
|
1238
|
+
let __index = Reflect.getMetadata(_index, object);
|
|
1239
|
+
let __def = Reflect.getMetadata(_def, object);
|
|
1240
|
+
if (!__fields) {
|
|
1241
|
+
__fields = {};
|
|
1242
|
+
__columns = [];
|
|
1243
|
+
__columnsNoId = [];
|
|
1244
|
+
__ids = [];
|
|
1245
|
+
__index = [];
|
|
1246
|
+
__def = {};
|
|
1247
|
+
}
|
|
1248
|
+
__fields[propertyName] = field;
|
|
1249
|
+
__columns.push(propertyName);
|
|
1250
|
+
if (field.id === true) {
|
|
1251
|
+
__ids.push(propertyName);
|
|
1252
|
+
}
|
|
1253
|
+
else {
|
|
1254
|
+
__columnsNoId.push(propertyName);
|
|
1255
|
+
}
|
|
1256
|
+
if (field.index === true) {
|
|
1257
|
+
__index.push(propertyName);
|
|
1258
|
+
}
|
|
1259
|
+
if (hasDef) {
|
|
1260
|
+
__def[propertyName] = field.def;
|
|
1261
|
+
}
|
|
1262
|
+
Reflect.defineMetadata(_fields, __fields, object);
|
|
1263
|
+
Reflect.defineMetadata(_columns, __columns, object);
|
|
1264
|
+
Reflect.defineMetadata(_columnsNoId, __columnsNoId, object);
|
|
1265
|
+
Reflect.defineMetadata(_ids, __ids, object);
|
|
1266
|
+
Reflect.defineMetadata(_index, __index, object);
|
|
1267
|
+
Reflect.defineMetadata(_def, __def, object);
|
|
1268
|
+
if (field.hasOwnProperty('logicDelete')) {
|
|
1269
|
+
Reflect.defineMetadata(_deleteState, field.logicDelete, object);
|
|
1270
|
+
Reflect.defineMetadata(_stateFileName, propertyName, object);
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
};
|
|
1274
|
+
exports.Field = Field;
|
|
1275
|
+
const DB = (config) => {
|
|
1276
|
+
return function (constructor) {
|
|
1277
|
+
var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
|
|
1278
|
+
const __ids = Reflect.getMetadata(_ids, config.clz.prototype) || new Array;
|
|
1279
|
+
const __fields = Reflect.getMetadata(_fields, config.clz.prototype);
|
|
1280
|
+
const __columns = Reflect.getMetadata(_columns, config.clz.prototype);
|
|
1281
|
+
const __columnsNoId = __columns.filter((c) => __ids.includes(c) === false);
|
|
1282
|
+
const __stateFileName = Reflect.getMetadata(_stateFileName, config.clz.prototype);
|
|
1283
|
+
const __deleteState = Reflect.getMetadata(_deleteState, config.clz.prototype);
|
|
1284
|
+
const __index = Reflect.getMetadata(_index, config.clz.prototype);
|
|
1285
|
+
const __def = Reflect.getMetadata(_def, config.clz.prototype);
|
|
1286
|
+
return _t = class extends constructor {
|
|
1287
|
+
constructor() {
|
|
1288
|
+
super(...arguments);
|
|
1289
|
+
this[_d] = config.tableName;
|
|
1290
|
+
this[_e] = config.dbName;
|
|
1291
|
+
this[_f] = config.dbType ?? DBType.Mysql;
|
|
1292
|
+
this[_g] = config.sqliteVersion;
|
|
1293
|
+
this[_h] = Object.assign({}, _defOption, config);
|
|
1294
|
+
this[_j] = __ids;
|
|
1295
|
+
this[_k] = __fields;
|
|
1296
|
+
this[_l] = __columns;
|
|
1297
|
+
this[_m] = __columnsNoId;
|
|
1298
|
+
this[_o] = __index;
|
|
1299
|
+
this[_p] = __def;
|
|
1300
|
+
this[_q] = __stateFileName;
|
|
1301
|
+
this[_r] = __deleteState;
|
|
1302
|
+
this[_s] = (data, option) => {
|
|
1303
|
+
return Object.fromEntries((0, iterare_1.default)(option?.skipId === true ? __columnsNoId : __columns)
|
|
1304
|
+
.map(K => [K, FieldFilter(K, data[K], __def, option)])
|
|
1305
|
+
.filter(data => {
|
|
1306
|
+
if (data[1][0] === 1) {
|
|
1307
|
+
if (option?.onFieldExists) {
|
|
1308
|
+
option.onFieldExists(data[0], data[1][1]);
|
|
1309
|
+
}
|
|
1310
|
+
return true;
|
|
1311
|
+
}
|
|
1312
|
+
else {
|
|
1313
|
+
return false;
|
|
1314
|
+
}
|
|
1315
|
+
})
|
|
1316
|
+
.map(data => [data[0], data[1][1]])
|
|
1317
|
+
.toArray());
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
},
|
|
1321
|
+
_d = _tableName,
|
|
1322
|
+
_e = _daoDBName,
|
|
1323
|
+
_f = _dbType,
|
|
1324
|
+
_g = _sqlite_version,
|
|
1325
|
+
_h = _SqlOption,
|
|
1326
|
+
_j = _ids,
|
|
1327
|
+
_k = _fields,
|
|
1328
|
+
_l = _columns,
|
|
1329
|
+
_m = _columnsNoId,
|
|
1330
|
+
_o = _index,
|
|
1331
|
+
_p = _def,
|
|
1332
|
+
_q = _stateFileName,
|
|
1333
|
+
_r = _deleteState,
|
|
1334
|
+
_s = _transformer,
|
|
1335
|
+
_t;
|
|
1336
|
+
};
|
|
1337
|
+
};
|
|
1338
|
+
exports.DB = DB;
|
|
1339
|
+
/**
|
|
1340
|
+
js项目中实体类注解替代品,只要确保函数被执行即可,举例:
|
|
1341
|
+
```
|
|
1342
|
+
// 声明一个class
|
|
1343
|
+
export class AmaFuck {}
|
|
1344
|
+
DeclareClass(AmaFuck, [
|
|
1345
|
+
{ type: "String", name: "SellerSKU" },
|
|
1346
|
+
{ type: "String", name: "SellerSKU2" },
|
|
1347
|
+
{ type: "String", name: "site" }
|
|
1348
|
+
]);
|
|
1349
|
+
```
|
|
1350
|
+
*/
|
|
1351
|
+
function DeclareClass(clz, FieldOptions) {
|
|
1352
|
+
for (const item of FieldOptions) {
|
|
1353
|
+
tslib_1.default.__decorate([(0, exports.Field)(item)], clz.prototype, item.name, void 0);
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
exports.DeclareClass = DeclareClass;
|
|
1357
|
+
/**
|
|
1358
|
+
JS项目中,service注解代替,举例:
|
|
1359
|
+
```
|
|
1360
|
+
// 声明一个service,注意这里的let
|
|
1361
|
+
export let AmaService = class AmaService extends SqlService {};
|
|
1362
|
+
AmaService = DeclareService(AmaService, {
|
|
1363
|
+
tableName: "ama_fuck2",
|
|
1364
|
+
clz: AmaFuck,
|
|
1365
|
+
dbType: DBType.Sqlite,
|
|
1366
|
+
sqliteVersion: "0.0.3"
|
|
1367
|
+
});
|
|
1368
|
+
```
|
|
1369
|
+
*/
|
|
1370
|
+
function DeclareService(clz, config) {
|
|
1371
|
+
return tslib_1.default.__decorate([(0, exports.DB)(config)], clz);
|
|
1372
|
+
}
|
|
1373
|
+
exports.DeclareService = DeclareService;
|
|
1374
|
+
/**
|
|
1375
|
+
## 数据库服务
|
|
1376
|
+
### 注解DB
|
|
1377
|
+
|
|
1378
|
+
### 泛型 T,同DB注解中的clz
|
|
1379
|
+
** 服务中所有方法默认以该类型为准
|
|
1380
|
+
**
|
|
1381
|
+
|
|
1382
|
+
*/
|
|
1383
|
+
class SqlService {
|
|
1384
|
+
_insert(datas, option) {
|
|
1385
|
+
const sqls = [];
|
|
1386
|
+
const tableName = sqlstring_1.default.escapeId(option.tableName);
|
|
1387
|
+
switch (option?.mode) {
|
|
1388
|
+
case SqlInsertMode.InsertIfNotExists: {
|
|
1389
|
+
const conditions = option.existConditionOtherThanIds || this[_ids];
|
|
1390
|
+
error_1.Throw.if(!conditions, 'not found where condition for insertIfNotExists!');
|
|
1391
|
+
error_1.Throw.if(conditions.length === 0, 'insertIfNotExists must have not null where!');
|
|
1392
|
+
const where = (0, iterare_1.default)(conditions).map(c => `${this[_fields][c]?.esName} = ?`).join(' AND ');
|
|
1393
|
+
const finalColumns = new Set();
|
|
1394
|
+
const whereColumns = conditions;
|
|
1395
|
+
const params = datas
|
|
1396
|
+
.map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
|
|
1397
|
+
.flatMap(data => {
|
|
1398
|
+
const result = [];
|
|
1399
|
+
const questMark = new Array();
|
|
1400
|
+
for (const column of finalColumns) {
|
|
1401
|
+
questMark.push('?');
|
|
1402
|
+
result.push(data.hasOwnProperty(column)
|
|
1403
|
+
? data[column]
|
|
1404
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
1405
|
+
? this[_def][column]
|
|
1406
|
+
: null);
|
|
1407
|
+
}
|
|
1408
|
+
for (const column of whereColumns) {
|
|
1409
|
+
questMark.push('?');
|
|
1410
|
+
result.push(data.hasOwnProperty(column)
|
|
1411
|
+
? data[column]
|
|
1412
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
1413
|
+
? this[_def][column]
|
|
1414
|
+
: null);
|
|
1415
|
+
}
|
|
1416
|
+
return result;
|
|
1417
|
+
});
|
|
1418
|
+
const quests = new Array(finalColumns.size).fill('?').join(',');
|
|
1419
|
+
const columnNames = (0, iterare_1.default)(finalColumns).map(i => this[_fields][i]?.esName).join(',');
|
|
1420
|
+
const selects = (0, iterare_1.default)(new Array(datas.length)).map(() => `SELECT ${quests} FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM ${tableName} WHERE ${where})`).join(' UNION ALL ');
|
|
1421
|
+
const sql = `INSERT INTO
|
|
1422
|
+
${tableName}
|
|
1423
|
+
(${columnNames})
|
|
1424
|
+
${selects};`;
|
|
1425
|
+
sqls.push({ sql, params });
|
|
1426
|
+
}
|
|
1427
|
+
case SqlInsertMode.Replace: {
|
|
1428
|
+
const finalColumns = new Set();
|
|
1429
|
+
const params = datas
|
|
1430
|
+
.map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
|
|
1431
|
+
.flatMap(data => {
|
|
1432
|
+
const result = [];
|
|
1433
|
+
const questMark = new Array();
|
|
1434
|
+
for (const column of finalColumns) {
|
|
1435
|
+
questMark.push('?');
|
|
1436
|
+
result.push(data.hasOwnProperty(column)
|
|
1437
|
+
? data[column]
|
|
1438
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
1439
|
+
? this[_def][column]
|
|
1440
|
+
: null);
|
|
1441
|
+
}
|
|
1442
|
+
return result;
|
|
1443
|
+
});
|
|
1444
|
+
const quests = new Array(finalColumns.size).fill('?').join(',');
|
|
1445
|
+
const columnNames = (0, iterare_1.default)(finalColumns).map(i => this[_fields][i]?.esName).join(',');
|
|
1446
|
+
const questMarks = (0, iterare_1.default)(new Array(datas.length)).map(() => `(${quests})`).join(',');
|
|
1447
|
+
const sql = `
|
|
1448
|
+
${this[_dbType] === DBType.Mysql ? '' : 'INSERT OR'} REPLACE INTO
|
|
1449
|
+
${tableName}
|
|
1450
|
+
(${columnNames})
|
|
1451
|
+
VALUES ${questMarks};
|
|
1452
|
+
`;
|
|
1453
|
+
sqls.push({ sql, params });
|
|
1454
|
+
}
|
|
1455
|
+
case SqlInsertMode.Insert: {
|
|
1456
|
+
const finalColumns = new Set();
|
|
1457
|
+
const params = datas
|
|
1458
|
+
.map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
|
|
1459
|
+
.flatMap(data => {
|
|
1460
|
+
const result = [];
|
|
1461
|
+
const questMark = new Array();
|
|
1462
|
+
for (const column of finalColumns) {
|
|
1463
|
+
questMark.push('?');
|
|
1464
|
+
result.push(data.hasOwnProperty(column)
|
|
1465
|
+
? data[column]
|
|
1466
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
1467
|
+
? this[_def][column]
|
|
1468
|
+
: null);
|
|
1469
|
+
}
|
|
1470
|
+
return result;
|
|
1471
|
+
});
|
|
1472
|
+
const quests = new Array(finalColumns.size).fill('?').join(',');
|
|
1473
|
+
const columnNames = (0, iterare_1.default)(finalColumns).map(i => this[_fields][i]?.esName).join(',');
|
|
1474
|
+
const questMarks = (0, iterare_1.default)(new Array(datas.length)).map(() => `(${quests})`).join(',');
|
|
1475
|
+
const sql = `
|
|
1476
|
+
INSERT INTO
|
|
1477
|
+
${tableName}
|
|
1478
|
+
(${columnNames})
|
|
1479
|
+
VALUES ${questMarks};
|
|
1480
|
+
`;
|
|
1481
|
+
sqls.push({ sql, params });
|
|
1482
|
+
}
|
|
1483
|
+
case SqlInsertMode.InsertWithTempTable: {
|
|
1484
|
+
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
1485
|
+
const tableTempESC = sqlstring_1.default.escapeId(tableTemp);
|
|
1486
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
1487
|
+
const finalColumns = new Set();
|
|
1488
|
+
const params = datas
|
|
1489
|
+
.map(data => this[_transformer](data, { ...option, finalColumns, def: true }))
|
|
1490
|
+
.flatMap(data => {
|
|
1491
|
+
const result = [];
|
|
1492
|
+
const questMark = new Array();
|
|
1493
|
+
for (const column of finalColumns) {
|
|
1494
|
+
questMark.push('?');
|
|
1495
|
+
result.push(data.hasOwnProperty(column)
|
|
1496
|
+
? data[column]
|
|
1497
|
+
: this[_def] && this[_def].hasOwnProperty(column)
|
|
1498
|
+
? this[_def][column]
|
|
1499
|
+
: null);
|
|
1500
|
+
}
|
|
1501
|
+
return result;
|
|
1502
|
+
});
|
|
1503
|
+
const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: Array.from(finalColumns) });
|
|
1504
|
+
sqls.push(..._sqls);
|
|
1505
|
+
const quests = new Array(finalColumns.size).fill('?').join(',');
|
|
1506
|
+
const columnNames = (0, iterare_1.default)(finalColumns).map(i => this[_fields][i]?.esName).join(',');
|
|
1507
|
+
const questMarks = (0, iterare_1.default)(new Array(datas.length)).map(() => `(${quests})`).join(',');
|
|
1508
|
+
sqls.push({
|
|
1509
|
+
sql: `
|
|
1510
|
+
INSERT INTO
|
|
1511
|
+
${tableTemp}
|
|
1512
|
+
(${columnNames})
|
|
1513
|
+
VALUES ${questMarks};
|
|
1514
|
+
`, params
|
|
1515
|
+
});
|
|
1516
|
+
sqls.push({
|
|
1517
|
+
sql: `INSERT INTO ${sqlstring_1.default.escapeId(option.tableName)} (${columnNames})
|
|
1518
|
+
SELECT ${columnNames} FROM ${tableTemp};`
|
|
1519
|
+
});
|
|
1520
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
return sqls;
|
|
1524
|
+
}
|
|
1525
|
+
insert(option) {
|
|
1526
|
+
option.mode ?? (option.mode = SqlInsertMode.Insert);
|
|
1527
|
+
const isArray = option.data instanceof Array;
|
|
1528
|
+
const datas = option.data instanceof Array ? option.data : [option.data];
|
|
1529
|
+
if (option.sync === SqlSyncMode.Sync) {
|
|
1530
|
+
const fn = () => {
|
|
1531
|
+
const result = (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.SyncTrust, datas, _data => {
|
|
1532
|
+
const sqls = this._insert(_data, option);
|
|
1533
|
+
let result = 0n;
|
|
1534
|
+
for (const { sql, params } of sqls) {
|
|
1535
|
+
const dd = option.conn.execute(SqlSyncMode.Sync, sql, params);
|
|
1536
|
+
if (dd.insertId) {
|
|
1537
|
+
result += dd.insertId;
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
return result;
|
|
1541
|
+
}, { everyLength: option?.every === true ? 1 : option?.maxDeal });
|
|
1542
|
+
if (isArray)
|
|
1543
|
+
return result;
|
|
1544
|
+
else
|
|
1545
|
+
return result[0];
|
|
1546
|
+
};
|
|
1547
|
+
if (option?.conn?.[_inTransaction] === true) {
|
|
1548
|
+
return fn();
|
|
1549
|
+
}
|
|
1550
|
+
else {
|
|
1551
|
+
return option?.dao?.transaction(SqlSyncMode.Sync, fn, option?.conn);
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
else if (isArray) {
|
|
1555
|
+
const fn = async () => {
|
|
1556
|
+
return await option?.dao?.transaction(SqlSyncMode.Async, async () => {
|
|
1557
|
+
const result = await (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
|
|
1558
|
+
const sqls = this._insert(_data, option);
|
|
1559
|
+
let result = 0n;
|
|
1560
|
+
for (const { sql, params } of sqls) {
|
|
1561
|
+
const dd = await option?.conn.execute(SqlSyncMode.Async, sql, params);
|
|
1562
|
+
if (dd.insertId) {
|
|
1563
|
+
result += dd.insertId;
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
return result;
|
|
1567
|
+
}, { everyLength: option?.every === true ? 1 : option?.maxDeal });
|
|
1568
|
+
return result;
|
|
1569
|
+
}, option?.conn);
|
|
1570
|
+
};
|
|
1571
|
+
return new Promise(async (resolve) => {
|
|
1572
|
+
if (option?.conn?.[_inTransaction] === true) {
|
|
1573
|
+
resolve((await fn()));
|
|
1574
|
+
}
|
|
1575
|
+
else {
|
|
1576
|
+
await option?.dao?.transaction(SqlSyncMode.Async, async () => resolve((await fn())), option?.conn);
|
|
1577
|
+
}
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
else {
|
|
1581
|
+
const fn = async () => {
|
|
1582
|
+
const result = await (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
|
|
1583
|
+
const sqls = this._insert(_data, option);
|
|
1584
|
+
let result = 0n;
|
|
1585
|
+
for (const { sql, params } of sqls) {
|
|
1586
|
+
const dd = await option.conn.execute(SqlSyncMode.Async, sql, params);
|
|
1587
|
+
if (dd.insertId) {
|
|
1588
|
+
result += dd.insertId;
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
return result;
|
|
1592
|
+
}, { everyLength: 1 });
|
|
1593
|
+
return result[0];
|
|
1594
|
+
};
|
|
1595
|
+
return new Promise(async (resolve) => {
|
|
1596
|
+
if (option?.conn?.[_inTransaction] === true) {
|
|
1597
|
+
resolve((await fn()));
|
|
1598
|
+
}
|
|
1599
|
+
else {
|
|
1600
|
+
await option?.dao?.transaction(SqlSyncMode.Async, async () => resolve((await fn())), option?.conn);
|
|
1601
|
+
}
|
|
1602
|
+
});
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
_update(datas, option) {
|
|
1606
|
+
const sqls = [];
|
|
1607
|
+
const tableName = sqlstring_1.default.escapeId(option?.tableName);
|
|
1608
|
+
const where = `WHEN ${(0, iterare_1.default)(this[_ids]).map(c => `${this[_fields][c]?.esName} = ?`).join(' AND ')} THEN ?`;
|
|
1609
|
+
const columnMaps = Object.fromEntries(this[_columnsNoId].map(c => [c, {
|
|
1610
|
+
where: new Array(),
|
|
1611
|
+
params: []
|
|
1612
|
+
}]));
|
|
1613
|
+
const params = [];
|
|
1614
|
+
for (const data of datas) {
|
|
1615
|
+
const ids = this[_ids].map(i => {
|
|
1616
|
+
error_1.Throw.if(!data[i], `UPDATE ID NOT EXISTS!${JSON.stringify(data)}`);
|
|
1617
|
+
return data[i];
|
|
1618
|
+
});
|
|
1619
|
+
this[_transformer](data, {
|
|
1620
|
+
...option,
|
|
1621
|
+
skipId: true,
|
|
1622
|
+
onFieldExists: (K, V) => {
|
|
1623
|
+
columnMaps[K]?.where.push(where);
|
|
1624
|
+
columnMaps[K]?.params.push(...ids, V);
|
|
1625
|
+
}
|
|
1626
|
+
});
|
|
1627
|
+
}
|
|
1628
|
+
const sql = `UPDATE ${tableName} SET ${(0, iterare_1.default)(this[_columnsNoId])
|
|
1629
|
+
.filter(K => columnMaps[K].where.length > 0)
|
|
1630
|
+
.map(K => {
|
|
1631
|
+
params.push(...columnMaps[K].params);
|
|
1632
|
+
return `${this[_fields][K]?.esName} = CASE ${columnMaps[K].where.join(' ')} ELSE ${this[_fields][K]?.esName} END`;
|
|
1633
|
+
})
|
|
1634
|
+
.join(',')};`;
|
|
1635
|
+
sqls.push({ sql, params });
|
|
1636
|
+
return sqls;
|
|
1637
|
+
}
|
|
1638
|
+
update(option) {
|
|
1639
|
+
error_1.Throw.if(!this[_ids] || this[_ids].length === 0, 'not found id');
|
|
1640
|
+
const datas = option.data instanceof Array ? option.data : [option.data];
|
|
1641
|
+
if (option.sync === SqlSyncMode.Sync) {
|
|
1642
|
+
const fn = () => {
|
|
1643
|
+
const result = (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.SyncTrust, datas, _data => {
|
|
1644
|
+
const sqls = this._update(_data, option);
|
|
1645
|
+
let result = 0;
|
|
1646
|
+
for (const { sql, params } of sqls) {
|
|
1647
|
+
const dd = option.conn.execute(SqlSyncMode.Sync, sql, params);
|
|
1648
|
+
if (dd.affectedRows) {
|
|
1649
|
+
result += dd.affectedRows;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
return result;
|
|
1653
|
+
}, { everyLength: option?.maxDeal });
|
|
1654
|
+
return result.reduce((a, b) => a + b);
|
|
1655
|
+
};
|
|
1656
|
+
if (option?.conn?.[_inTransaction] === true) {
|
|
1657
|
+
return fn();
|
|
1658
|
+
}
|
|
1659
|
+
else {
|
|
1660
|
+
return option?.dao?.transaction(SqlSyncMode.Sync, fn, option?.conn);
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
else {
|
|
1664
|
+
const fn = async () => {
|
|
1665
|
+
const result = await (0, fn_1.excuteSplit)(fn_1.ExcuteSplitMode.AsyncTrust, datas, async (_data) => {
|
|
1666
|
+
const sqls = this._update(_data, option);
|
|
1667
|
+
let result = 0;
|
|
1668
|
+
for (const { sql, params } of sqls) {
|
|
1669
|
+
const dd = await option.conn.execute(SqlSyncMode.Async, sql, params);
|
|
1670
|
+
if (dd.affectedRows) {
|
|
1671
|
+
result += dd.affectedRows;
|
|
1672
|
+
}
|
|
1673
|
+
}
|
|
1674
|
+
return result;
|
|
1675
|
+
}, { everyLength: option?.maxDeal });
|
|
1676
|
+
return result.reduce((a, b) => a + b);
|
|
1677
|
+
};
|
|
1678
|
+
return new Promise(async (resolve) => {
|
|
1679
|
+
if (option?.conn?.[_inTransaction] === true) {
|
|
1680
|
+
resolve((await fn()));
|
|
1681
|
+
}
|
|
1682
|
+
else {
|
|
1683
|
+
await option?.dao?.transaction(SqlSyncMode.Async, async () => resolve((await fn())), option?.conn);
|
|
1684
|
+
}
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
delete(option) {
|
|
1689
|
+
error_1.Throw.if(!!this[_ids] && this[_ids].length > 1 && !option.where, 'muit id must set where!');
|
|
1690
|
+
error_1.Throw.if((!this[_ids] || this[_ids].length === 0) && !option.where, 'if not set id on class, must set where!');
|
|
1691
|
+
error_1.Throw.if(!option.id && !option.where, 'not found id or where!');
|
|
1692
|
+
error_1.Throw.if(!!option.id && !!this[_ids] && this[_ids].length > 1, 'muit id must set where!');
|
|
1693
|
+
error_1.Throw.if(!!option.id && !!option.where, 'id and where only one can set!');
|
|
1694
|
+
option.mode ?? (option.mode = SqlDelMode.Common);
|
|
1695
|
+
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
1696
|
+
const tableTempESC = sqlstring_1.default.escapeId(tableTemp);
|
|
1697
|
+
const tableNameESC = sqlstring_1.default.escapeId(option?.tableName);
|
|
1698
|
+
if (option.id) {
|
|
1699
|
+
const idName = this[_ids][0];
|
|
1700
|
+
const ids = option.id instanceof Array ? option.id : [option.id];
|
|
1701
|
+
option.where = ids.map(i => ({ [idName]: i }));
|
|
1702
|
+
}
|
|
1703
|
+
const wheres = option.where instanceof Array ? option.where : [option.where];
|
|
1704
|
+
const sqls = [];
|
|
1705
|
+
if (option.mode === SqlDelMode.Common) {
|
|
1706
|
+
const params = new Array();
|
|
1707
|
+
const whereSql = (0, iterare_1.default)(wheres).map(where => {
|
|
1708
|
+
return `(
|
|
1709
|
+
${Object.entries(where).map(([K, V]) => {
|
|
1710
|
+
params.push(V);
|
|
1711
|
+
return `${K} = ?`;
|
|
1712
|
+
}).join(' AND ')}
|
|
1713
|
+
)`;
|
|
1714
|
+
}).join(' OR ');
|
|
1715
|
+
if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
|
|
1716
|
+
sqls.push({
|
|
1717
|
+
sql: `
|
|
1718
|
+
UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.esName} = ${sqlstring_1.default.escape(this[_deleteState])}
|
|
1719
|
+
WHERE ${whereSql};
|
|
1720
|
+
`, params
|
|
1721
|
+
});
|
|
1722
|
+
}
|
|
1723
|
+
else {
|
|
1724
|
+
sqls.push({ sql: `DELETE FROM ${tableNameESC} WHERE ${whereSql};`, params });
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
else {
|
|
1728
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
1729
|
+
const delWhere = Object.keys(wheres[0]);
|
|
1730
|
+
const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
|
|
1731
|
+
sqls.push(..._sqls);
|
|
1732
|
+
switch (this[_dbType]) {
|
|
1733
|
+
case DBType.Mysql: {
|
|
1734
|
+
if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
|
|
1735
|
+
sqls.push({
|
|
1736
|
+
sql: `UPDATE ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.esName} = b.${this[_fields][K]?.esName}`).join(' AND ')}
|
|
1737
|
+
SET a.${this[_fields][this[_stateFileName]]?.esName} = ${sqlstring_1.default.escape(this[_deleteState])};`
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
else {
|
|
1741
|
+
sqls.push({
|
|
1742
|
+
sql: `DELETE a.* FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.esName} = b.${this[_fields][K]?.esName}`).join(' AND ')};`
|
|
1743
|
+
});
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
case DBType.Sqlite:
|
|
1747
|
+
case DBType.SqliteRemote: {
|
|
1748
|
+
const columnNames = (0, iterare_1.default)(delWhere).map(K => this[_fields][K]?.esName).join(',');
|
|
1749
|
+
if (this[_stateFileName] !== undefined && option.forceDelete !== true) {
|
|
1750
|
+
sqls.push({
|
|
1751
|
+
sql: `UPDATE ${tableNameESC} SET ${this[_fields][this[_stateFileName]]?.esName} = ${sqlstring_1.default.escape(this[_deleteState])}
|
|
1752
|
+
WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});`
|
|
1753
|
+
});
|
|
1754
|
+
}
|
|
1755
|
+
else {
|
|
1756
|
+
sqls.push({ sql: `DELETE FROM ${tableNameESC} WHERE (${columnNames}) IN (SELECT ${columnNames} FROM ${tableTempESC});` });
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
1761
|
+
}
|
|
1762
|
+
if (option.sync === SqlSyncMode.Sync) {
|
|
1763
|
+
const fn = () => {
|
|
1764
|
+
let result = 0;
|
|
1765
|
+
for (const { sql, params } of sqls) {
|
|
1766
|
+
const dd = option.conn.execute(SqlSyncMode.Sync, sql, params);
|
|
1767
|
+
result += dd.affectedRows;
|
|
1768
|
+
}
|
|
1769
|
+
return result;
|
|
1770
|
+
};
|
|
1771
|
+
if (option?.conn?.[_inTransaction] === true) {
|
|
1772
|
+
return fn();
|
|
1773
|
+
}
|
|
1774
|
+
else {
|
|
1775
|
+
return option?.dao?.transaction(SqlSyncMode.Sync, fn, option?.conn);
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
else {
|
|
1779
|
+
const fn = async () => {
|
|
1780
|
+
let result = 0;
|
|
1781
|
+
for (const { sql, params } of sqls) {
|
|
1782
|
+
const dd = await option.conn.execute(SqlSyncMode.Async, sql, params);
|
|
1783
|
+
result += dd.affectedRows;
|
|
1784
|
+
}
|
|
1785
|
+
return result;
|
|
1786
|
+
};
|
|
1787
|
+
return new Promise(async (resolve) => {
|
|
1788
|
+
if (option?.conn?.[_inTransaction] === true) {
|
|
1789
|
+
resolve((await fn()));
|
|
1790
|
+
}
|
|
1791
|
+
else {
|
|
1792
|
+
await option?.dao?.transaction(SqlSyncMode.Async, async () => resolve((await fn())), option?.conn);
|
|
1793
|
+
}
|
|
1794
|
+
});
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
_select(resultMode, result, error) {
|
|
1798
|
+
switch (resultMode) {
|
|
1799
|
+
case SqlTemplateMode.AssertOne: {
|
|
1800
|
+
error_1.Throw.if(!result || result.length !== 1, error);
|
|
1801
|
+
return result[0];
|
|
1802
|
+
}
|
|
1803
|
+
case SqlTemplateMode.NotSureOne: {
|
|
1804
|
+
error_1.Throw.if(!result, error);
|
|
1805
|
+
return result[0] ?? null;
|
|
1806
|
+
}
|
|
1807
|
+
case SqlTemplateMode.Many: {
|
|
1808
|
+
return result;
|
|
1809
|
+
}
|
|
1810
|
+
case SqlTemplateMode.Count: {
|
|
1811
|
+
return result[0].ct;
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
template(option) {
|
|
1816
|
+
error_1.Throw.if(!!this[_ids] && this[_ids].length > 1 && !option.where, 'muit id must set where!');
|
|
1817
|
+
error_1.Throw.if((!this[_ids] || this[_ids].length === 0) && !option.where, 'if not set id on class, must set where!');
|
|
1818
|
+
error_1.Throw.if(!option.id && !option.where, 'not found id or where!');
|
|
1819
|
+
error_1.Throw.if(!!option.id && !!this[_ids] && this[_ids].length > 1, 'muit id must set where!');
|
|
1820
|
+
error_1.Throw.if(!!option.id && !!option.where, 'id and where only one can set!');
|
|
1821
|
+
option.mode ?? (option.mode = SqlSelectMode.Common);
|
|
1822
|
+
option.resultMode ?? (option.resultMode = SqlTemplateMode.AssertOne);
|
|
1823
|
+
option.error ?? (option.error = 'error data!');
|
|
1824
|
+
const tableTemp = `${option?.tableName}_${Math.random()}`.replace(/\./, '');
|
|
1825
|
+
const tableTempESC = sqlstring_1.default.escapeId(tableTemp);
|
|
1826
|
+
const tableNameESC = sqlstring_1.default.escapeId(option?.tableName);
|
|
1827
|
+
if (option.id) {
|
|
1828
|
+
const idName = this[_ids][0];
|
|
1829
|
+
const ids = option.id instanceof Array ? option.id : [option.id];
|
|
1830
|
+
option.where = ids.map(i => ({ [idName]: i }));
|
|
1831
|
+
}
|
|
1832
|
+
const columns = option.resultMode === SqlTemplateMode.Count ? 'COUNT(1) ct' : (0, iterare_1.default)((option.columns ?? this[_columns])).map((K) => `a.${this[_fields][K]?.esName}`).join(',');
|
|
1833
|
+
const wheres = option.where instanceof Array ? option.where : [option.where];
|
|
1834
|
+
const sqls = [];
|
|
1835
|
+
let resultIndex = -1;
|
|
1836
|
+
if (option.mode === SqlSelectMode.Common) {
|
|
1837
|
+
const params = new Array();
|
|
1838
|
+
const whereSql = (0, iterare_1.default)(wheres).map(where => {
|
|
1839
|
+
return `SELECT ${columns} FROM ${tableNameESC} a WHERE
|
|
1840
|
+
${Object.entries(where).map(([K, V]) => {
|
|
1841
|
+
params.push(V);
|
|
1842
|
+
return `${K} = ?`;
|
|
1843
|
+
}).join(' AND ')}`;
|
|
1844
|
+
}).join(' UNION ALL ');
|
|
1845
|
+
sqls.push({ sql: whereSql, params });
|
|
1846
|
+
resultIndex = 0;
|
|
1847
|
+
}
|
|
1848
|
+
else {
|
|
1849
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
1850
|
+
const delWhere = Object.keys(wheres[0]);
|
|
1851
|
+
const _sqls = this._createTable({ tableName: tableTemp, temp: true, columns: delWhere, data: wheres, index: 'all', id: 'none' });
|
|
1852
|
+
sqls.push(..._sqls);
|
|
1853
|
+
resultIndex = sqls.length;
|
|
1854
|
+
sqls.push({ sql: `SELECT ${columns} FROM ${tableNameESC} a INNER JOIN ${tableTempESC} b ON ${delWhere.map(K => `a.${this[_fields][K]?.esName} = b.${this[_fields][K]?.esName}`).join(' AND ')};` });
|
|
1855
|
+
sqls.push({ sql: `DROP TABLE IF EXISTS ${tableTempESC};` });
|
|
1856
|
+
}
|
|
1857
|
+
if (option.sync === SqlSyncMode.Sync) {
|
|
1858
|
+
let result;
|
|
1859
|
+
for (let i = 0; i < sqls.length; i++) {
|
|
1860
|
+
if (i === resultIndex) {
|
|
1861
|
+
result = option.conn.query(SqlSyncMode.Sync, sqls[i]?.sql, sqls[i]?.params);
|
|
1862
|
+
}
|
|
1863
|
+
else {
|
|
1864
|
+
option.conn.execute(SqlSyncMode.Sync, sqls[i]?.sql, sqls[i]?.params);
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
return this._select(option.resultMode, result, option.error);
|
|
1868
|
+
}
|
|
1869
|
+
else {
|
|
1870
|
+
return new Promise(async (resolve) => {
|
|
1871
|
+
let result;
|
|
1872
|
+
for (let i = 0; i < sqls.length; i++) {
|
|
1873
|
+
if (i === resultIndex) {
|
|
1874
|
+
result = await option.conn.query(SqlSyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
|
|
1875
|
+
}
|
|
1876
|
+
else {
|
|
1877
|
+
await option.conn.execute(SqlSyncMode.Async, sqls[i]?.sql, sqls[i]?.params);
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
resolve(this._select(option.resultMode, result, option.error));
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
_query(resultMode, result, def, errorMsg, multiple) {
|
|
1885
|
+
if (multiple === true) {
|
|
1886
|
+
switch (resultMode) {
|
|
1887
|
+
case SqlQueryMode.One_Row_One_Column_NotSure: {
|
|
1888
|
+
try {
|
|
1889
|
+
return result.map((r) => Object.values(r)[0]);
|
|
1890
|
+
}
|
|
1891
|
+
catch (error) {
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
case SqlQueryMode.One_Row_One_Column_Assert: {
|
|
1895
|
+
try {
|
|
1896
|
+
return (0, iterare_1.default)(result).map((r) => Object.values(r)[0]).filter((r) => r !== null).toArray();
|
|
1897
|
+
}
|
|
1898
|
+
catch (error) {
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1901
|
+
case SqlQueryMode.One_Row_Many_Column_NotSure: {
|
|
1902
|
+
try {
|
|
1903
|
+
return result.map((r) => r[0]);
|
|
1904
|
+
}
|
|
1905
|
+
catch (error) {
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
case SqlQueryMode.One_Row_Many_Column_Assert: {
|
|
1909
|
+
try {
|
|
1910
|
+
return (0, iterare_1.default)(result).map((r) => r[0]).filter((r) => r !== null).toArray();
|
|
1911
|
+
}
|
|
1912
|
+
catch (error) {
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
case SqlQueryMode.Many_Row_One_Column: {
|
|
1916
|
+
try {
|
|
1917
|
+
return result.map((rx) => rx.map((r) => Object.values(r)[0]));
|
|
1918
|
+
}
|
|
1919
|
+
catch (error) {
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
case SqlQueryMode.Many_Row_Many_Column: {
|
|
1923
|
+
return result;
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
else {
|
|
1928
|
+
switch (resultMode) {
|
|
1929
|
+
case SqlQueryMode.One_Row_One_Column_NotSure: {
|
|
1930
|
+
try {
|
|
1931
|
+
return Object.values(result[0])[0];
|
|
1932
|
+
}
|
|
1933
|
+
catch (error) {
|
|
1934
|
+
return def;
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
case SqlQueryMode.One_Row_One_Column_Assert: {
|
|
1938
|
+
try {
|
|
1939
|
+
return Object.values(result[0])[0];
|
|
1940
|
+
}
|
|
1941
|
+
catch (error) {
|
|
1942
|
+
if (def !== undefined)
|
|
1943
|
+
return def;
|
|
1944
|
+
error_1.Throw.now(errorMsg ?? 'not found data!');
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
case SqlQueryMode.One_Row_Many_Column_NotSure: {
|
|
1948
|
+
return result[0] ?? null;
|
|
1949
|
+
}
|
|
1950
|
+
case SqlQueryMode.One_Row_Many_Column_Assert: {
|
|
1951
|
+
const data = result[0];
|
|
1952
|
+
error_1.Throw.if(data === null, errorMsg ?? 'not found data!');
|
|
1953
|
+
return data ?? null;
|
|
1954
|
+
}
|
|
1955
|
+
case SqlQueryMode.Many_Row_One_Column: {
|
|
1956
|
+
try {
|
|
1957
|
+
return result.map((r) => Object.values(r)[0]);
|
|
1958
|
+
}
|
|
1959
|
+
catch (error) {
|
|
1960
|
+
return def;
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
case SqlQueryMode.Many_Row_Many_Column: {
|
|
1964
|
+
return result;
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
}
|
|
1969
|
+
select(option) {
|
|
1970
|
+
error_1.Throw.if(!option.sqlId && !option.sql, 'not found sql!');
|
|
1971
|
+
option.resultMode ?? (option.resultMode = SqlQueryMode.Many_Row_Many_Column);
|
|
1972
|
+
option.sql ?? (option.sql = globalThis[_sqlCache].load(option.sqlId, option.context, option.isPage));
|
|
1973
|
+
option.defValue ?? (option.defValue = null);
|
|
1974
|
+
logger.debug(option.sql);
|
|
1975
|
+
const _params = Object.assign({}, option.context, option.params);
|
|
1976
|
+
const params = [];
|
|
1977
|
+
const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
|
|
1978
|
+
if (_params.hasOwnProperty(key)) {
|
|
1979
|
+
const V = _params[key];
|
|
1980
|
+
params.push(V);
|
|
1981
|
+
return sqlstring_1.default.escape(_params[key]);
|
|
1982
|
+
}
|
|
1983
|
+
return txt;
|
|
1984
|
+
});
|
|
1985
|
+
if (option.sync === SqlSyncMode.Sync) {
|
|
1986
|
+
const result = option.conn.query(SqlSyncMode.Sync, sql, params);
|
|
1987
|
+
return this._query(option.resultMode, result, option.defValue, option.errorMsg, option.multiple);
|
|
1988
|
+
}
|
|
1989
|
+
else {
|
|
1990
|
+
return new Promise(async (resolve) => {
|
|
1991
|
+
const result = await option.conn.query(SqlSyncMode.Async, sql, params);
|
|
1992
|
+
resolve(this._query(option.resultMode, result, option.defValue, option.errorMsg, option.multiple));
|
|
1993
|
+
});
|
|
1994
|
+
}
|
|
1995
|
+
}
|
|
1996
|
+
excute(option) {
|
|
1997
|
+
error_1.Throw.if(!option.sqlId && !option.sql, 'not found sql!');
|
|
1998
|
+
option.sql ?? (option.sql = globalThis[_sqlCache].load(option.sqlId, option.context));
|
|
1999
|
+
logger.debug(option.sql);
|
|
2000
|
+
const _params = Object.assign({}, option.context, option.params);
|
|
2001
|
+
const params = [];
|
|
2002
|
+
const sql = option.sql?.replace(/\:(\w+)/g, (txt, key) => {
|
|
2003
|
+
if (_params.hasOwnProperty(key)) {
|
|
2004
|
+
const V = _params[key];
|
|
2005
|
+
params.push(V);
|
|
2006
|
+
return sqlstring_1.default.escape(_params[key]);
|
|
2007
|
+
}
|
|
2008
|
+
return txt;
|
|
2009
|
+
});
|
|
2010
|
+
if (option.sync === SqlSyncMode.Sync) {
|
|
2011
|
+
const result = option.conn.execute(SqlSyncMode.Sync, sql, params);
|
|
2012
|
+
return result.affectedRows;
|
|
2013
|
+
}
|
|
2014
|
+
else {
|
|
2015
|
+
return new Promise(async (resolve) => {
|
|
2016
|
+
const result = await option.conn.execute(SqlSyncMode.Async, sql, params);
|
|
2017
|
+
resolve(result.affectedRows);
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
transaction(option) {
|
|
2022
|
+
if (option.sync === SqlSyncMode.Sync) {
|
|
2023
|
+
return option.dao.transaction(SqlSyncMode.Sync, option.fn);
|
|
2024
|
+
}
|
|
2025
|
+
else {
|
|
2026
|
+
return new Promise(async (resolve) => {
|
|
2027
|
+
const rt = await option.dao.transaction(SqlSyncMode.Async, option.fn);
|
|
2028
|
+
resolve(rt);
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
stream(option) {
|
|
2033
|
+
return new StreamQuery(option?.tableName ?? this[_tableName], this);
|
|
2034
|
+
}
|
|
2035
|
+
/**
|
|
2036
|
+
#创建表
|
|
2037
|
+
** `tableName` 表名称
|
|
2038
|
+
** `temp` 是否是临时表,默认true
|
|
2039
|
+
** `columns` 字符串数组,默认是当前实体类全部字段,通过`columns` 可以创建部分字段临时表
|
|
2040
|
+
** `id` 表的主键设置 4种:
|
|
2041
|
+
1. `auto`: `columns`中已经在当前实体类配置的ID作为主键 `默认`
|
|
2042
|
+
2. `all`: `columns`中所有字段全部当主键
|
|
2043
|
+
3. `none`: 没有主键
|
|
2044
|
+
4. 自定义字段名称:字符串数组
|
|
2045
|
+
** `index` 表的索引,设置方式同ID
|
|
2046
|
+
*/
|
|
2047
|
+
_createTable({ tableName, temp = true, columns, data, id = 'auto', index = 'auto' } = {}) {
|
|
2048
|
+
const sqls = [];
|
|
2049
|
+
columns = columns || this[_columns];
|
|
2050
|
+
let ids;
|
|
2051
|
+
if (id === 'auto') {
|
|
2052
|
+
ids = this[_ids]?.filter(i => columns?.includes(i));
|
|
2053
|
+
}
|
|
2054
|
+
else if (id === 'all') {
|
|
2055
|
+
ids = columns;
|
|
2056
|
+
}
|
|
2057
|
+
else if (id === 'none') {
|
|
2058
|
+
ids = undefined;
|
|
2059
|
+
}
|
|
2060
|
+
else {
|
|
2061
|
+
ids = id;
|
|
2062
|
+
}
|
|
2063
|
+
let indexs;
|
|
2064
|
+
if (index === 'auto') {
|
|
2065
|
+
indexs = this[_index]?.filter(i => columns?.includes(i));
|
|
2066
|
+
}
|
|
2067
|
+
else if (index === 'all') {
|
|
2068
|
+
indexs = columns;
|
|
2069
|
+
}
|
|
2070
|
+
else if (index === 'none') {
|
|
2071
|
+
indexs = undefined;
|
|
2072
|
+
}
|
|
2073
|
+
else {
|
|
2074
|
+
indexs = index;
|
|
2075
|
+
}
|
|
2076
|
+
tableName = sqlstring_1.default.escapeId(tableName ?? this[_tableName]);
|
|
2077
|
+
switch (this[_dbType]) {
|
|
2078
|
+
case DBType.Mysql: {
|
|
2079
|
+
let sql = `CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
|
|
2080
|
+
${columns.map(K => this[_fields][K][DBType.Mysql]).join(',')}
|
|
2081
|
+
${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.esName).join(',')}) USING BTREE ` : ''}
|
|
2082
|
+
${indexs && indexs.length ? `,${indexs.map(i => `KEY ${this[_fields][i]?.esName} (${this[_fields][i]?.esName})`).join(',')} ` : ''}
|
|
2083
|
+
) ENGINE=MEMORY;`;
|
|
2084
|
+
sqls.push({ sql });
|
|
2085
|
+
if (data && data.length > 0) {
|
|
2086
|
+
const params = [];
|
|
2087
|
+
let first = true;
|
|
2088
|
+
sql = `INSERT INTO ${tableName} (${columns.map(c => sqlstring_1.default.escapeId(c)).join(',')})
|
|
2089
|
+
${(data).map(d => {
|
|
2090
|
+
const r = `SELECT ${Object.entries(d).map(([K, V]) => {
|
|
2091
|
+
params.push(V);
|
|
2092
|
+
return `? ${first ? this[_fields][K]?.esName : ''}`;
|
|
2093
|
+
}).join(',')}`;
|
|
2094
|
+
first = false;
|
|
2095
|
+
return r;
|
|
2096
|
+
}).join(' UNION ALL ')}`;
|
|
2097
|
+
sqls.push({ sql, params });
|
|
2098
|
+
}
|
|
2099
|
+
break;
|
|
2100
|
+
}
|
|
2101
|
+
case DBType.Sqlite:
|
|
2102
|
+
case DBType.SqliteRemote: {
|
|
2103
|
+
let sql = `CREATE ${temp === true ? 'TEMPORARY' : ''} TABLE IF NOT EXISTS ${tableName}(
|
|
2104
|
+
${columns.map(K => this[_fields][K][DBType.Sqlite]).join(',')}
|
|
2105
|
+
${ids && ids.length ? `,PRIMARY KEY (${ids.map(i => this[_fields][i]?.esName).join(',')}) ` : ''}
|
|
2106
|
+
);`;
|
|
2107
|
+
sqls.push({ sql });
|
|
2108
|
+
if (indexs) {
|
|
2109
|
+
for (const index of indexs) {
|
|
2110
|
+
sql = `CREATE INDEX ${sqlstring_1.default.escapeId(`${index}_${Math.random()}`.replace(/\./, ''))} ON ${tableName} (${this[_fields][index]?.esName});`;
|
|
2111
|
+
sqls.push({ sql });
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
if (data && data.length > 0) {
|
|
2115
|
+
const params = [];
|
|
2116
|
+
let first = true;
|
|
2117
|
+
sql = `INSERT INTO ${tableName} (${columns.map(c => sqlstring_1.default.escapeId(c)).join(',')})
|
|
2118
|
+
${(data).map(d => {
|
|
2119
|
+
const r = `SELECT ${Object.entries(d).map(([K, V]) => {
|
|
2120
|
+
params.push(V);
|
|
2121
|
+
return `? ${first ? this[_fields][K]?.esName : ''}`;
|
|
2122
|
+
}).join(',')}`;
|
|
2123
|
+
first = false;
|
|
2124
|
+
return r;
|
|
2125
|
+
}).join(' UNION ALL ')}`;
|
|
2126
|
+
sqls.push({ sql, params });
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
return sqls;
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
exports.SqlService = SqlService;
|
|
2134
|
+
__decorate([
|
|
2135
|
+
P(),
|
|
2136
|
+
__metadata("design:type", Function),
|
|
2137
|
+
__metadata("design:paramtypes", [Object]),
|
|
2138
|
+
__metadata("design:returntype", Object)
|
|
2139
|
+
], SqlService.prototype, "insert", null);
|
|
2140
|
+
__decorate([
|
|
2141
|
+
P(),
|
|
2142
|
+
__metadata("design:type", Function),
|
|
2143
|
+
__metadata("design:paramtypes", [Object]),
|
|
2144
|
+
__metadata("design:returntype", Object)
|
|
2145
|
+
], SqlService.prototype, "update", null);
|
|
2146
|
+
__decorate([
|
|
2147
|
+
P(),
|
|
2148
|
+
__metadata("design:type", Function),
|
|
2149
|
+
__metadata("design:paramtypes", [Object]),
|
|
2150
|
+
__metadata("design:returntype", Object)
|
|
2151
|
+
], SqlService.prototype, "delete", null);
|
|
2152
|
+
__decorate([
|
|
2153
|
+
P(),
|
|
2154
|
+
__metadata("design:type", Function),
|
|
2155
|
+
__metadata("design:paramtypes", [Object]),
|
|
2156
|
+
__metadata("design:returntype", Object)
|
|
2157
|
+
], SqlService.prototype, "template", null);
|
|
2158
|
+
__decorate([
|
|
2159
|
+
P(),
|
|
2160
|
+
__metadata("design:type", Function),
|
|
2161
|
+
__metadata("design:paramtypes", [Object]),
|
|
2162
|
+
__metadata("design:returntype", Object)
|
|
2163
|
+
], SqlService.prototype, "select", null);
|
|
2164
|
+
__decorate([
|
|
2165
|
+
P(),
|
|
2166
|
+
__metadata("design:type", Function),
|
|
2167
|
+
__metadata("design:paramtypes", [Object]),
|
|
2168
|
+
__metadata("design:returntype", Object)
|
|
2169
|
+
], SqlService.prototype, "excute", null);
|
|
2170
|
+
__decorate([
|
|
2171
|
+
P(true),
|
|
2172
|
+
__metadata("design:type", Function),
|
|
2173
|
+
__metadata("design:paramtypes", [Object]),
|
|
2174
|
+
__metadata("design:returntype", Object)
|
|
2175
|
+
], SqlService.prototype, "transaction", null);
|
|
2176
|
+
/** 是否进行下一个动作 */
|
|
2177
|
+
const IF_PROCEED = function () {
|
|
2178
|
+
return function (_target, _propertyKey, descriptor) {
|
|
2179
|
+
const fn = descriptor.value;
|
|
2180
|
+
descriptor.value = function () {
|
|
2181
|
+
if (this.if_proceed === true) {
|
|
2182
|
+
// eslint-disable-next-line prefer-rest-params
|
|
2183
|
+
const args = Array.from(arguments);
|
|
2184
|
+
fn.call(this, ...args);
|
|
2185
|
+
}
|
|
2186
|
+
else {
|
|
2187
|
+
this.if_proceed = true;
|
|
2188
|
+
}
|
|
2189
|
+
return this;
|
|
2190
|
+
};
|
|
2191
|
+
};
|
|
2192
|
+
};
|
|
2193
|
+
/*** 是否执行最终查询/操作*/
|
|
2194
|
+
const IF_EXEC = function (def) {
|
|
2195
|
+
return function (_target, _propertyKey, descriptor) {
|
|
2196
|
+
const fn = descriptor.value;
|
|
2197
|
+
descriptor.value = async function () {
|
|
2198
|
+
if (this.if_proceed === true && this.if_exec === true) {
|
|
2199
|
+
// eslint-disable-next-line prefer-rest-params
|
|
2200
|
+
const args = Array.from(arguments);
|
|
2201
|
+
return await fn.call(this, ...args);
|
|
2202
|
+
}
|
|
2203
|
+
else {
|
|
2204
|
+
return def;
|
|
2205
|
+
}
|
|
2206
|
+
};
|
|
2207
|
+
};
|
|
2208
|
+
};
|
|
2209
|
+
class StreamCondition {
|
|
2210
|
+
constructor() {
|
|
2211
|
+
this._prefix = 0;
|
|
2212
|
+
this._index = 0;
|
|
2213
|
+
this._wheres = [];
|
|
2214
|
+
this._andQuerys = [];
|
|
2215
|
+
this._orQuerys = [];
|
|
2216
|
+
this._paramKeys = {};
|
|
2217
|
+
this._param = {};
|
|
2218
|
+
this.if_proceed = true;
|
|
2219
|
+
this.if_exec = true;
|
|
2220
|
+
this._prefix = parseInt(`${Math.random() * 1000}`);
|
|
2221
|
+
}
|
|
2222
|
+
/** 将当前stream重置 */
|
|
2223
|
+
reset() {
|
|
2224
|
+
this._index = 0;
|
|
2225
|
+
this._wheres.length = 0;
|
|
2226
|
+
this._param = {};
|
|
2227
|
+
this._paramKeys = {};
|
|
2228
|
+
return this;
|
|
2229
|
+
}
|
|
2230
|
+
/** 为下次链条执行提供条件判断:非异步方法跳过,异步方法不执行并返回默认值 */
|
|
2231
|
+
if(condition) {
|
|
2232
|
+
this.if_proceed = condition;
|
|
2233
|
+
return this;
|
|
2234
|
+
}
|
|
2235
|
+
eq(key, value, { name } = {}) { return this._(key, value, '=', { name }); }
|
|
2236
|
+
eqT(t, { name } = {}) {
|
|
2237
|
+
if (name && this._paramKeys[name]) {
|
|
2238
|
+
for (const [key, pname] of Object.entries(this._paramKeys[name])) {
|
|
2239
|
+
this._param[pname] = t[key];
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
else {
|
|
2243
|
+
const paramKeys = {};
|
|
2244
|
+
for (const [key, value] of Object.entries(t)) {
|
|
2245
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
2246
|
+
this._wheres.push(`AND ${String(key)} = :${pkey} `);
|
|
2247
|
+
this._param[pkey] = value;
|
|
2248
|
+
if (name) {
|
|
2249
|
+
paramKeys[key] = pkey;
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
if (name) {
|
|
2253
|
+
this._paramKeys[name] = paramKeys;
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
return this;
|
|
2257
|
+
}
|
|
2258
|
+
notEq(key, value, { name } = {}) { return this._(key, value, '<>', { name }); }
|
|
2259
|
+
eqWith(key1, key2) { return this._key(key1, key2, '='); }
|
|
2260
|
+
notEqWith(key1, key2) { return this._key(key1, key2, '<>'); }
|
|
2261
|
+
regexp(key, regexp, { name } = {}) { return this._(key, regexp, 'REGEXP', { name }); }
|
|
2262
|
+
notRegexp(key, regexp, { name } = {}) { return this._(key, regexp, 'REGEXP', { name, not: 'NOT' }); }
|
|
2263
|
+
/** (key1 << 8) + key2 = value */
|
|
2264
|
+
shiftEq(key1, key2, value, { name } = {}) { return this._shift(key1, key2, value, '=', { name }); }
|
|
2265
|
+
/** (key1 << 8) + key2 <> value */
|
|
2266
|
+
shiftNotEq(key1, key2, value, { name } = {}) { return this._shift(key1, key2, value, '<>', { name }); }
|
|
2267
|
+
grate(key, value, { name } = {}) { return this._(key, value, '>', { name }); }
|
|
2268
|
+
grateEq(key, value, { name } = {}) { return this._(key, value, '>=', { name }); }
|
|
2269
|
+
grateWith(key1, key2) { return this._key(key1, key2, '>'); }
|
|
2270
|
+
grateEqWith(key1, key2) { return this._key(key1, key2, '>='); }
|
|
2271
|
+
less(key, value, { name } = {}) { return this._(key, value, '<', { name }); }
|
|
2272
|
+
lessEq(key, value, { name } = {}) { return this._(key, value, '<=', { name }); }
|
|
2273
|
+
lessWith(key1, key2) { return this._key(key1, key2, '<'); }
|
|
2274
|
+
lessEqWith(key1, key2) { return this._key(key1, key2, '<='); }
|
|
2275
|
+
like(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', right: '%', force }); }
|
|
2276
|
+
notLike(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', right: '%', not: 'NOT', force }); }
|
|
2277
|
+
leftLike(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', force }); }
|
|
2278
|
+
notLeftLike(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', not: 'NOT', force }); }
|
|
2279
|
+
rightLike(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', force }); }
|
|
2280
|
+
notRightLike(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', not: 'NOT', force }); }
|
|
2281
|
+
PreciseLike(key, value, { name, force } = {}) { return this._like(key, value, { name, force }); }
|
|
2282
|
+
notPreciseLike(key, value, { name, force } = {}) { return this._like(key, value, { name, not: 'NOT', force }); }
|
|
2283
|
+
glob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', right: '%', force, op: 'glob' }); }
|
|
2284
|
+
notGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', right: '%', not: 'NOT', force, op: 'glob' }); }
|
|
2285
|
+
leftGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', force, op: 'glob' }); }
|
|
2286
|
+
notLeftGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, left: '%', not: 'NOT', force, op: 'glob' }); }
|
|
2287
|
+
rightGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', force, op: 'glob' }); }
|
|
2288
|
+
notRightGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, right: '%', not: 'NOT', force, op: 'glob' }); }
|
|
2289
|
+
PreciseGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, force, op: 'glob' }); }
|
|
2290
|
+
notPreciseGlob(key, value, { name, force } = {}) { return this._like(key, value, { name, not: 'NOT', force, op: 'glob' }); }
|
|
2291
|
+
in(key, value, { name, force } = {}) { return this._in(key, value, { name, force }); }
|
|
2292
|
+
notIn(key, value, { name, force } = {}) { return this._in(key, value, { name, not: 'NOT', force }); }
|
|
2293
|
+
isNULL(key) { return this._null(key); }
|
|
2294
|
+
isNotNULL(key) { return this._null(key, 'NOT'); }
|
|
2295
|
+
between(key, value1, value2, { name } = {}) { return this._between(key, value1, value2, { name }); }
|
|
2296
|
+
notBetween(key, value1, value2, { name } = {}) { return this._between(key, value1, value2, { name, not: 'NOT' }); }
|
|
2297
|
+
pow(key, value, { name } = {}) { return this._pow(key, value, { name }); }
|
|
2298
|
+
notPow(key, value, { name } = {}) { return this._pow(key, value, { name, not: 'NOT' }); }
|
|
2299
|
+
powWith(key, values, { name } = {}) { return this._pow(key, (0, math_1.add)(...values.map(value => Math.pow(2, +value))), { name }); }
|
|
2300
|
+
notPowWith(key, values, { name } = {}) { return this._pow(key, (0, math_1.add)(...values.map(value => Math.pow(2, +value))), { name, not: 'NOT' }); }
|
|
2301
|
+
/** MATCH(key1, key2, key3) AGAINST (value) */
|
|
2302
|
+
match(value, keys, { name } = {}) { return this._match(value, keys, { name }); }
|
|
2303
|
+
/** NOT MATCH(key1, key2, key3) AGAINST (value) */
|
|
2304
|
+
notMatch(value, keys, { name } = {}) { return this._match(value, keys, { name, not: 'NOT' }); }
|
|
2305
|
+
/** MATCH(key1, key2, key3) AGAINST (value) IN BOOLEAN MODE*/
|
|
2306
|
+
matchBoolean(value, keys, { name } = {}) { return this._match(value, keys, { name, append: 'IN BOOLEAN MODE' }); }
|
|
2307
|
+
/** NOT MATCH(key1, key2, key3) AGAINST (value) IN BOOLEAN MODE */
|
|
2308
|
+
notMatchBoolean(value, keys, { name } = {}) { return this._match(value, keys, { name, not: 'NOT', append: 'IN BOOLEAN MODE' }); }
|
|
2309
|
+
/** MATCH(key1, key2, key3) AGAINST (value) WITH QUERY EXPANSION*/
|
|
2310
|
+
matchQuery(value, keys, { name } = {}) { return this._match(value, keys, { name, append: 'WITH QUERY EXPANSION' }); }
|
|
2311
|
+
/** NOT MATCH(key1, key2, key3) AGAINST (value) WITH QUERY EXPANSION*/
|
|
2312
|
+
notMatchQuery(value, keys, { name } = {}) { return this._match(value, keys, { name, not: 'NOT', append: 'WITH QUERY EXPANSION' }); }
|
|
2313
|
+
includes(key, value, { name } = {}) { return this._includes(key, value, { name }); }
|
|
2314
|
+
notIncludes(key, value, { name } = {}) { return this._includes(key, value, { name, not: 'NOT' }); }
|
|
2315
|
+
and(fn) { const stream = new StreamCondition(); const ret = fn(stream); if (ret !== false) {
|
|
2316
|
+
this._andQuerys.push(stream);
|
|
2317
|
+
} return this; }
|
|
2318
|
+
or(fn) { const stream = new StreamCondition(); const ret = fn(stream); if (ret !== false) {
|
|
2319
|
+
this._orQuerys.push(stream);
|
|
2320
|
+
} return this; }
|
|
2321
|
+
where() {
|
|
2322
|
+
const wheres = new Array();
|
|
2323
|
+
const sql = this._wheres.join(' ');
|
|
2324
|
+
if (sql) {
|
|
2325
|
+
wheres.push(`(${sql})`);
|
|
2326
|
+
}
|
|
2327
|
+
if (this._orQuerys.length > 0) {
|
|
2328
|
+
for (const query of this._orQuerys) {
|
|
2329
|
+
const { where, params } = query.where();
|
|
2330
|
+
if (where) {
|
|
2331
|
+
wheres.push(` OR (${where}) `);
|
|
2332
|
+
}
|
|
2333
|
+
Object.assign(this._param, params);
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
if (this._andQuerys.length > 0) {
|
|
2337
|
+
for (const query of this._andQuerys) {
|
|
2338
|
+
const { where, params } = query.where();
|
|
2339
|
+
if (where) {
|
|
2340
|
+
wheres.push(` AND (${where}) `);
|
|
2341
|
+
}
|
|
2342
|
+
Object.assign(this._param, params);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
return { where: wheres.join(' '), params: this._param };
|
|
2346
|
+
}
|
|
2347
|
+
_(key, value, op, { not = '', name = '' } = {}) {
|
|
2348
|
+
if (name !== undefined && this._paramKeys.hasOwnProperty(name)) {
|
|
2349
|
+
this._param[this._paramKeys[name]] = value;
|
|
2350
|
+
}
|
|
2351
|
+
else {
|
|
2352
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
2353
|
+
this._wheres.push(`AND ${String(key)} ${not} ${op} :${pkey} `);
|
|
2354
|
+
this._param[pkey] = value;
|
|
2355
|
+
if (name) {
|
|
2356
|
+
this._paramKeys[name] = pkey;
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
2359
|
+
return this;
|
|
2360
|
+
}
|
|
2361
|
+
_null(key, not = '') {
|
|
2362
|
+
this._wheres.push(`AND ${String(key)} is ${not} null`);
|
|
2363
|
+
return this;
|
|
2364
|
+
}
|
|
2365
|
+
_key(key1, key2, op, not = '') {
|
|
2366
|
+
this._wheres.push(`AND ${String(key1)} ${not} ${op} ${String(key2)} `);
|
|
2367
|
+
return this;
|
|
2368
|
+
}
|
|
2369
|
+
_between(key, value1, value2, { not = '', name = '' } = {}) {
|
|
2370
|
+
if (name && this._paramKeys[name]) {
|
|
2371
|
+
this._param[this._paramKeys[name][0]] = value1;
|
|
2372
|
+
this._param[this._paramKeys[name][1]] = value2;
|
|
2373
|
+
}
|
|
2374
|
+
else {
|
|
2375
|
+
const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
|
|
2376
|
+
this._wheres.push(`AND ${String(key)} ${not} BETWEEN :${pkey1} AND :${pkey2}`);
|
|
2377
|
+
this._param[pkey1] = value1;
|
|
2378
|
+
this._param[pkey2] = value2;
|
|
2379
|
+
if (name) {
|
|
2380
|
+
this._paramKeys[name] = [pkey1, pkey2];
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
return this;
|
|
2384
|
+
}
|
|
2385
|
+
_in(key, value, { not = '', name = '', force = false } = {}) {
|
|
2386
|
+
if (value && value.length > 0) {
|
|
2387
|
+
if (name !== undefined && this._paramKeys.hasOwnProperty(name)) {
|
|
2388
|
+
this._param[this._paramKeys[name]] = value;
|
|
2389
|
+
}
|
|
2390
|
+
else {
|
|
2391
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
2392
|
+
this._wheres.push(`AND ${String(key)} ${not} IN (:${pkey}) `);
|
|
2393
|
+
this._param[pkey] = value;
|
|
2394
|
+
if (name) {
|
|
2395
|
+
this._paramKeys[name] = pkey;
|
|
2396
|
+
}
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
else if (force !== true) {
|
|
2400
|
+
this.if_exec = false;
|
|
2401
|
+
}
|
|
2402
|
+
return this;
|
|
2403
|
+
}
|
|
2404
|
+
_shift(key1, key2, value, op, { not = '', name = '' } = {}) {
|
|
2405
|
+
if (name !== undefined && this._paramKeys.hasOwnProperty(name)) {
|
|
2406
|
+
this._param[this._paramKeys[name]] = value;
|
|
2407
|
+
}
|
|
2408
|
+
else {
|
|
2409
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
2410
|
+
this._wheres.push(`AND (${String(key1)} << 8) + ${String(key2)} ${not} ${op} :${pkey} `);
|
|
2411
|
+
this._param[pkey] = value;
|
|
2412
|
+
if (name) {
|
|
2413
|
+
this._paramKeys[name] = pkey;
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
return this;
|
|
2417
|
+
}
|
|
2418
|
+
_match(value, keys, { name, not, append } = {}) {
|
|
2419
|
+
if (name !== undefined && this._paramKeys.hasOwnProperty(name)) {
|
|
2420
|
+
this._param[this._paramKeys[name]] = value;
|
|
2421
|
+
}
|
|
2422
|
+
else {
|
|
2423
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
2424
|
+
this._wheres.push(`AND MATCH(${keys.join(',')}) AGAINST (:${pkey} ${append ?? ''})`);
|
|
2425
|
+
this._param[pkey] = value;
|
|
2426
|
+
if (name) {
|
|
2427
|
+
this._paramKeys[name] = pkey;
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
return this;
|
|
2431
|
+
}
|
|
2432
|
+
_pow(key, value, { name } = {}) {
|
|
2433
|
+
if (name !== undefined && this._paramKeys.hasOwnProperty(name)) {
|
|
2434
|
+
this._param[this._paramKeys[name]] = value;
|
|
2435
|
+
}
|
|
2436
|
+
else {
|
|
2437
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
2438
|
+
this._wheres.push(`AND NOT POW(2, ${String(key)}) & :${pkey}`);
|
|
2439
|
+
this._param[pkey] = value;
|
|
2440
|
+
if (name) {
|
|
2441
|
+
this._paramKeys[name] = pkey;
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
return this;
|
|
2445
|
+
}
|
|
2446
|
+
_like(key, value, { not = '', left = '', right = '', name = '', op = 'LIKE', force = false } = {}) {
|
|
2447
|
+
if (value !== null && value !== undefined && value !== '') {
|
|
2448
|
+
if (name !== undefined && this._paramKeys.hasOwnProperty(name)) {
|
|
2449
|
+
this._param[this._paramKeys[name]] = value;
|
|
2450
|
+
}
|
|
2451
|
+
else {
|
|
2452
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
2453
|
+
this._wheres.push(`AND ${String(key)} ${not} ${op} CONCAT('${left}', :${pkey}, '${right}') `);
|
|
2454
|
+
this._param[pkey] = value;
|
|
2455
|
+
if (name) {
|
|
2456
|
+
this._paramKeys[name] = pkey;
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
else if (force !== true) {
|
|
2461
|
+
this.if_exec = false;
|
|
2462
|
+
}
|
|
2463
|
+
return this;
|
|
2464
|
+
}
|
|
2465
|
+
_includes(key, value, { not = '', name = '' } = {}) {
|
|
2466
|
+
if (name !== undefined && this._paramKeys.hasOwnProperty(name)) {
|
|
2467
|
+
this._param[this._paramKeys[name]] = value;
|
|
2468
|
+
}
|
|
2469
|
+
else {
|
|
2470
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
2471
|
+
this._wheres.push(`AND LOCATE(${String(key)}, :${pkey}) ${not ? '=' : ''} 0`);
|
|
2472
|
+
this._param[pkey] = value;
|
|
2473
|
+
if (name) {
|
|
2474
|
+
this._paramKeys[name] = pkey;
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
return this;
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
__decorate([
|
|
2481
|
+
IF_PROCEED(),
|
|
2482
|
+
__metadata("design:type", Function),
|
|
2483
|
+
__metadata("design:paramtypes", [Boolean]),
|
|
2484
|
+
__metadata("design:returntype", void 0)
|
|
2485
|
+
], StreamCondition.prototype, "if", null);
|
|
2486
|
+
__decorate([
|
|
2487
|
+
IF_PROCEED(),
|
|
2488
|
+
__metadata("design:type", Function),
|
|
2489
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2490
|
+
__metadata("design:returntype", void 0)
|
|
2491
|
+
], StreamCondition.prototype, "eq", null);
|
|
2492
|
+
__decorate([
|
|
2493
|
+
IF_PROCEED(),
|
|
2494
|
+
__metadata("design:type", Function),
|
|
2495
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2496
|
+
__metadata("design:returntype", void 0)
|
|
2497
|
+
], StreamCondition.prototype, "eqT", null);
|
|
2498
|
+
__decorate([
|
|
2499
|
+
IF_PROCEED(),
|
|
2500
|
+
__metadata("design:type", Function),
|
|
2501
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2502
|
+
__metadata("design:returntype", void 0)
|
|
2503
|
+
], StreamCondition.prototype, "notEq", null);
|
|
2504
|
+
__decorate([
|
|
2505
|
+
IF_PROCEED(),
|
|
2506
|
+
__metadata("design:type", Function),
|
|
2507
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2508
|
+
__metadata("design:returntype", void 0)
|
|
2509
|
+
], StreamCondition.prototype, "eqWith", null);
|
|
2510
|
+
__decorate([
|
|
2511
|
+
IF_PROCEED(),
|
|
2512
|
+
__metadata("design:type", Function),
|
|
2513
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2514
|
+
__metadata("design:returntype", void 0)
|
|
2515
|
+
], StreamCondition.prototype, "notEqWith", null);
|
|
2516
|
+
__decorate([
|
|
2517
|
+
IF_PROCEED(),
|
|
2518
|
+
__metadata("design:type", Function),
|
|
2519
|
+
__metadata("design:paramtypes", [Object, String, Object]),
|
|
2520
|
+
__metadata("design:returntype", void 0)
|
|
2521
|
+
], StreamCondition.prototype, "regexp", null);
|
|
2522
|
+
__decorate([
|
|
2523
|
+
IF_PROCEED(),
|
|
2524
|
+
__metadata("design:type", Function),
|
|
2525
|
+
__metadata("design:paramtypes", [Object, String, Object]),
|
|
2526
|
+
__metadata("design:returntype", void 0)
|
|
2527
|
+
], StreamCondition.prototype, "notRegexp", null);
|
|
2528
|
+
__decorate([
|
|
2529
|
+
IF_PROCEED(),
|
|
2530
|
+
__metadata("design:type", Function),
|
|
2531
|
+
__metadata("design:paramtypes", [Object, Object, Number, Object]),
|
|
2532
|
+
__metadata("design:returntype", void 0)
|
|
2533
|
+
], StreamCondition.prototype, "shiftEq", null);
|
|
2534
|
+
__decorate([
|
|
2535
|
+
IF_PROCEED(),
|
|
2536
|
+
__metadata("design:type", Function),
|
|
2537
|
+
__metadata("design:paramtypes", [Object, Object, Number, Object]),
|
|
2538
|
+
__metadata("design:returntype", void 0)
|
|
2539
|
+
], StreamCondition.prototype, "shiftNotEq", null);
|
|
2540
|
+
__decorate([
|
|
2541
|
+
IF_PROCEED(),
|
|
2542
|
+
__metadata("design:type", Function),
|
|
2543
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2544
|
+
__metadata("design:returntype", void 0)
|
|
2545
|
+
], StreamCondition.prototype, "grate", null);
|
|
2546
|
+
__decorate([
|
|
2547
|
+
IF_PROCEED(),
|
|
2548
|
+
__metadata("design:type", Function),
|
|
2549
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2550
|
+
__metadata("design:returntype", void 0)
|
|
2551
|
+
], StreamCondition.prototype, "grateEq", null);
|
|
2552
|
+
__decorate([
|
|
2553
|
+
IF_PROCEED(),
|
|
2554
|
+
__metadata("design:type", Function),
|
|
2555
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2556
|
+
__metadata("design:returntype", void 0)
|
|
2557
|
+
], StreamCondition.prototype, "grateWith", null);
|
|
2558
|
+
__decorate([
|
|
2559
|
+
IF_PROCEED(),
|
|
2560
|
+
__metadata("design:type", Function),
|
|
2561
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2562
|
+
__metadata("design:returntype", void 0)
|
|
2563
|
+
], StreamCondition.prototype, "grateEqWith", null);
|
|
2564
|
+
__decorate([
|
|
2565
|
+
IF_PROCEED(),
|
|
2566
|
+
__metadata("design:type", Function),
|
|
2567
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2568
|
+
__metadata("design:returntype", void 0)
|
|
2569
|
+
], StreamCondition.prototype, "less", null);
|
|
2570
|
+
__decorate([
|
|
2571
|
+
IF_PROCEED(),
|
|
2572
|
+
__metadata("design:type", Function),
|
|
2573
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2574
|
+
__metadata("design:returntype", void 0)
|
|
2575
|
+
], StreamCondition.prototype, "lessEq", null);
|
|
2576
|
+
__decorate([
|
|
2577
|
+
IF_PROCEED(),
|
|
2578
|
+
__metadata("design:type", Function),
|
|
2579
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2580
|
+
__metadata("design:returntype", void 0)
|
|
2581
|
+
], StreamCondition.prototype, "lessWith", null);
|
|
2582
|
+
__decorate([
|
|
2583
|
+
IF_PROCEED(),
|
|
2584
|
+
__metadata("design:type", Function),
|
|
2585
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2586
|
+
__metadata("design:returntype", void 0)
|
|
2587
|
+
], StreamCondition.prototype, "lessEqWith", null);
|
|
2588
|
+
__decorate([
|
|
2589
|
+
IF_PROCEED(),
|
|
2590
|
+
__metadata("design:type", Function),
|
|
2591
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2592
|
+
__metadata("design:returntype", void 0)
|
|
2593
|
+
], StreamCondition.prototype, "like", null);
|
|
2594
|
+
__decorate([
|
|
2595
|
+
IF_PROCEED(),
|
|
2596
|
+
__metadata("design:type", Function),
|
|
2597
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2598
|
+
__metadata("design:returntype", void 0)
|
|
2599
|
+
], StreamCondition.prototype, "notLike", null);
|
|
2600
|
+
__decorate([
|
|
2601
|
+
IF_PROCEED(),
|
|
2602
|
+
__metadata("design:type", Function),
|
|
2603
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2604
|
+
__metadata("design:returntype", void 0)
|
|
2605
|
+
], StreamCondition.prototype, "leftLike", null);
|
|
2606
|
+
__decorate([
|
|
2607
|
+
IF_PROCEED(),
|
|
2608
|
+
__metadata("design:type", Function),
|
|
2609
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2610
|
+
__metadata("design:returntype", void 0)
|
|
2611
|
+
], StreamCondition.prototype, "notLeftLike", null);
|
|
2612
|
+
__decorate([
|
|
2613
|
+
IF_PROCEED(),
|
|
2614
|
+
__metadata("design:type", Function),
|
|
2615
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2616
|
+
__metadata("design:returntype", void 0)
|
|
2617
|
+
], StreamCondition.prototype, "rightLike", null);
|
|
2618
|
+
__decorate([
|
|
2619
|
+
IF_PROCEED(),
|
|
2620
|
+
__metadata("design:type", Function),
|
|
2621
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2622
|
+
__metadata("design:returntype", void 0)
|
|
2623
|
+
], StreamCondition.prototype, "notRightLike", null);
|
|
2624
|
+
__decorate([
|
|
2625
|
+
IF_PROCEED(),
|
|
2626
|
+
__metadata("design:type", Function),
|
|
2627
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2628
|
+
__metadata("design:returntype", void 0)
|
|
2629
|
+
], StreamCondition.prototype, "PreciseLike", null);
|
|
2630
|
+
__decorate([
|
|
2631
|
+
IF_PROCEED(),
|
|
2632
|
+
__metadata("design:type", Function),
|
|
2633
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2634
|
+
__metadata("design:returntype", void 0)
|
|
2635
|
+
], StreamCondition.prototype, "notPreciseLike", null);
|
|
2636
|
+
__decorate([
|
|
2637
|
+
IF_PROCEED(),
|
|
2638
|
+
__metadata("design:type", Function),
|
|
2639
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2640
|
+
__metadata("design:returntype", void 0)
|
|
2641
|
+
], StreamCondition.prototype, "glob", null);
|
|
2642
|
+
__decorate([
|
|
2643
|
+
IF_PROCEED(),
|
|
2644
|
+
__metadata("design:type", Function),
|
|
2645
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2646
|
+
__metadata("design:returntype", void 0)
|
|
2647
|
+
], StreamCondition.prototype, "notGlob", null);
|
|
2648
|
+
__decorate([
|
|
2649
|
+
IF_PROCEED(),
|
|
2650
|
+
__metadata("design:type", Function),
|
|
2651
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2652
|
+
__metadata("design:returntype", void 0)
|
|
2653
|
+
], StreamCondition.prototype, "leftGlob", null);
|
|
2654
|
+
__decorate([
|
|
2655
|
+
IF_PROCEED(),
|
|
2656
|
+
__metadata("design:type", Function),
|
|
2657
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2658
|
+
__metadata("design:returntype", void 0)
|
|
2659
|
+
], StreamCondition.prototype, "notLeftGlob", null);
|
|
2660
|
+
__decorate([
|
|
2661
|
+
IF_PROCEED(),
|
|
2662
|
+
__metadata("design:type", Function),
|
|
2663
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2664
|
+
__metadata("design:returntype", void 0)
|
|
2665
|
+
], StreamCondition.prototype, "rightGlob", null);
|
|
2666
|
+
__decorate([
|
|
2667
|
+
IF_PROCEED(),
|
|
2668
|
+
__metadata("design:type", Function),
|
|
2669
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2670
|
+
__metadata("design:returntype", void 0)
|
|
2671
|
+
], StreamCondition.prototype, "notRightGlob", null);
|
|
2672
|
+
__decorate([
|
|
2673
|
+
IF_PROCEED(),
|
|
2674
|
+
__metadata("design:type", Function),
|
|
2675
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2676
|
+
__metadata("design:returntype", void 0)
|
|
2677
|
+
], StreamCondition.prototype, "PreciseGlob", null);
|
|
2678
|
+
__decorate([
|
|
2679
|
+
IF_PROCEED(),
|
|
2680
|
+
__metadata("design:type", Function),
|
|
2681
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2682
|
+
__metadata("design:returntype", void 0)
|
|
2683
|
+
], StreamCondition.prototype, "notPreciseGlob", null);
|
|
2684
|
+
__decorate([
|
|
2685
|
+
IF_PROCEED(),
|
|
2686
|
+
__metadata("design:type", Function),
|
|
2687
|
+
__metadata("design:paramtypes", [Object, Array, Object]),
|
|
2688
|
+
__metadata("design:returntype", void 0)
|
|
2689
|
+
], StreamCondition.prototype, "in", null);
|
|
2690
|
+
__decorate([
|
|
2691
|
+
IF_PROCEED(),
|
|
2692
|
+
__metadata("design:type", Function),
|
|
2693
|
+
__metadata("design:paramtypes", [Object, Array, Object]),
|
|
2694
|
+
__metadata("design:returntype", void 0)
|
|
2695
|
+
], StreamCondition.prototype, "notIn", null);
|
|
2696
|
+
__decorate([
|
|
2697
|
+
IF_PROCEED(),
|
|
2698
|
+
__metadata("design:type", Function),
|
|
2699
|
+
__metadata("design:paramtypes", [Object]),
|
|
2700
|
+
__metadata("design:returntype", void 0)
|
|
2701
|
+
], StreamCondition.prototype, "isNULL", null);
|
|
2702
|
+
__decorate([
|
|
2703
|
+
IF_PROCEED(),
|
|
2704
|
+
__metadata("design:type", Function),
|
|
2705
|
+
__metadata("design:paramtypes", [Object]),
|
|
2706
|
+
__metadata("design:returntype", void 0)
|
|
2707
|
+
], StreamCondition.prototype, "isNotNULL", null);
|
|
2708
|
+
__decorate([
|
|
2709
|
+
IF_PROCEED(),
|
|
2710
|
+
__metadata("design:type", Function),
|
|
2711
|
+
__metadata("design:paramtypes", [Object, Object, Object, Object]),
|
|
2712
|
+
__metadata("design:returntype", void 0)
|
|
2713
|
+
], StreamCondition.prototype, "between", null);
|
|
2714
|
+
__decorate([
|
|
2715
|
+
IF_PROCEED(),
|
|
2716
|
+
__metadata("design:type", Function),
|
|
2717
|
+
__metadata("design:paramtypes", [Object, Object, Object, Object]),
|
|
2718
|
+
__metadata("design:returntype", void 0)
|
|
2719
|
+
], StreamCondition.prototype, "notBetween", null);
|
|
2720
|
+
__decorate([
|
|
2721
|
+
IF_PROCEED(),
|
|
2722
|
+
__metadata("design:type", Function),
|
|
2723
|
+
__metadata("design:paramtypes", [Object, Number, Object]),
|
|
2724
|
+
__metadata("design:returntype", void 0)
|
|
2725
|
+
], StreamCondition.prototype, "pow", null);
|
|
2726
|
+
__decorate([
|
|
2727
|
+
IF_PROCEED(),
|
|
2728
|
+
__metadata("design:type", Function),
|
|
2729
|
+
__metadata("design:paramtypes", [Object, Number, Object]),
|
|
2730
|
+
__metadata("design:returntype", void 0)
|
|
2731
|
+
], StreamCondition.prototype, "notPow", null);
|
|
2732
|
+
__decorate([
|
|
2733
|
+
IF_PROCEED(),
|
|
2734
|
+
__metadata("design:type", Function),
|
|
2735
|
+
__metadata("design:paramtypes", [Object, Array, Object]),
|
|
2736
|
+
__metadata("design:returntype", void 0)
|
|
2737
|
+
], StreamCondition.prototype, "powWith", null);
|
|
2738
|
+
__decorate([
|
|
2739
|
+
IF_PROCEED(),
|
|
2740
|
+
__metadata("design:type", Function),
|
|
2741
|
+
__metadata("design:paramtypes", [Object, Array, Object]),
|
|
2742
|
+
__metadata("design:returntype", void 0)
|
|
2743
|
+
], StreamCondition.prototype, "notPowWith", null);
|
|
2744
|
+
__decorate([
|
|
2745
|
+
IF_PROCEED(),
|
|
2746
|
+
__metadata("design:type", Function),
|
|
2747
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
2748
|
+
__metadata("design:returntype", void 0)
|
|
2749
|
+
], StreamCondition.prototype, "match", null);
|
|
2750
|
+
__decorate([
|
|
2751
|
+
IF_PROCEED(),
|
|
2752
|
+
__metadata("design:type", Function),
|
|
2753
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
2754
|
+
__metadata("design:returntype", void 0)
|
|
2755
|
+
], StreamCondition.prototype, "notMatch", null);
|
|
2756
|
+
__decorate([
|
|
2757
|
+
IF_PROCEED(),
|
|
2758
|
+
__metadata("design:type", Function),
|
|
2759
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
2760
|
+
__metadata("design:returntype", void 0)
|
|
2761
|
+
], StreamCondition.prototype, "matchBoolean", null);
|
|
2762
|
+
__decorate([
|
|
2763
|
+
IF_PROCEED(),
|
|
2764
|
+
__metadata("design:type", Function),
|
|
2765
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
2766
|
+
__metadata("design:returntype", void 0)
|
|
2767
|
+
], StreamCondition.prototype, "notMatchBoolean", null);
|
|
2768
|
+
__decorate([
|
|
2769
|
+
IF_PROCEED(),
|
|
2770
|
+
__metadata("design:type", Function),
|
|
2771
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
2772
|
+
__metadata("design:returntype", void 0)
|
|
2773
|
+
], StreamCondition.prototype, "matchQuery", null);
|
|
2774
|
+
__decorate([
|
|
2775
|
+
IF_PROCEED(),
|
|
2776
|
+
__metadata("design:type", Function),
|
|
2777
|
+
__metadata("design:paramtypes", [String, Array, Object]),
|
|
2778
|
+
__metadata("design:returntype", void 0)
|
|
2779
|
+
], StreamCondition.prototype, "notMatchQuery", null);
|
|
2780
|
+
__decorate([
|
|
2781
|
+
IF_PROCEED(),
|
|
2782
|
+
__metadata("design:type", Function),
|
|
2783
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2784
|
+
__metadata("design:returntype", void 0)
|
|
2785
|
+
], StreamCondition.prototype, "includes", null);
|
|
2786
|
+
__decorate([
|
|
2787
|
+
IF_PROCEED(),
|
|
2788
|
+
__metadata("design:type", Function),
|
|
2789
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2790
|
+
__metadata("design:returntype", void 0)
|
|
2791
|
+
], StreamCondition.prototype, "notIncludes", null);
|
|
2792
|
+
__decorate([
|
|
2793
|
+
IF_PROCEED(),
|
|
2794
|
+
__metadata("design:type", Function),
|
|
2795
|
+
__metadata("design:paramtypes", [Function]),
|
|
2796
|
+
__metadata("design:returntype", void 0)
|
|
2797
|
+
], StreamCondition.prototype, "and", null);
|
|
2798
|
+
__decorate([
|
|
2799
|
+
IF_PROCEED(),
|
|
2800
|
+
__metadata("design:type", Function),
|
|
2801
|
+
__metadata("design:paramtypes", [Function]),
|
|
2802
|
+
__metadata("design:returntype", void 0)
|
|
2803
|
+
], StreamCondition.prototype, "or", null);
|
|
2804
|
+
class StreamBuild extends StreamCondition {
|
|
2805
|
+
constructor(table) {
|
|
2806
|
+
super();
|
|
2807
|
+
this._distinct = false;
|
|
2808
|
+
this._columns = [];
|
|
2809
|
+
this._updateColumns = [];
|
|
2810
|
+
this._groups = [];
|
|
2811
|
+
this._orders = [];
|
|
2812
|
+
this._startRow = 0;
|
|
2813
|
+
this._pageSize = 0;
|
|
2814
|
+
this._table = table;
|
|
2815
|
+
}
|
|
2816
|
+
/** 将当前stream重置 */
|
|
2817
|
+
reset() {
|
|
2818
|
+
super.reset();
|
|
2819
|
+
this._pageSize = 0;
|
|
2820
|
+
this._startRow = 0;
|
|
2821
|
+
this._orders.length = 0;
|
|
2822
|
+
this._groups.length = 0;
|
|
2823
|
+
this._columns.length = 0;
|
|
2824
|
+
this._updateColumns.length = 0;
|
|
2825
|
+
return this;
|
|
2826
|
+
}
|
|
2827
|
+
groupBy(key) { this._groups.push(key); return this; }
|
|
2828
|
+
asc(...keys) { this._orders.push(...keys.map(key => `${String(key)} ASC`)); return this; }
|
|
2829
|
+
desc(...keys) { this._orders.push(...keys.map(key => `${String(key)} DESC`)); return this; }
|
|
2830
|
+
limit(startRow, pageSize) { this._startRow = startRow; this._pageSize = pageSize; return this; }
|
|
2831
|
+
page(pageNumber, pageSize) { this._startRow = ((pageNumber || 1) - 1) * pageSize; this._pageSize = pageSize; return this; }
|
|
2832
|
+
table(_table) { this._table = _table; return this; }
|
|
2833
|
+
distinct(on = true) { this._distinct = on; return this; }
|
|
2834
|
+
count(key, countName, distinct) { this._columns.push(`COUNT(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${countName || `${String(key)}`}`); return this; }
|
|
2835
|
+
sum(key, legName, distinct) { this._columns.push(`SUM(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
|
|
2836
|
+
avg(key, legName, distinct) { this._columns.push(`AVG(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
|
|
2837
|
+
max(key, legName, distinct) { this._columns.push(`MAX(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
|
|
2838
|
+
min(key, legName, distinct) { this._columns.push(`MIN(${distinct ? 'DISTINCT' : ''} ${String(key)}) ${legName || `${String(key)}`}`); return this; }
|
|
2839
|
+
groupConcat(key, param) {
|
|
2840
|
+
this._columns.push(`GROUP_CONCAT(
|
|
2841
|
+
${param && param.distinct ? 'DISTINCT' : ''} ${String(key)}
|
|
2842
|
+
${param && param.asc && param.asc.length > 0 ? `ORDER BY ${param.asc.map(i => `${String(i)} ASC`)} ` : ''}
|
|
2843
|
+
${param && param.desc && param.desc.length > 0 ? `${param && param.asc && param.asc.length > 0 ? '' : 'ORDER BY'} ${param.desc.map(i => `${String(i)} DESC`)} ` : ''}
|
|
2844
|
+
SEPARATOR '${param && param.separator || ','}'
|
|
2845
|
+
) ${param && param.groupName || `${String(key)}`}`);
|
|
2846
|
+
return this;
|
|
2847
|
+
}
|
|
2848
|
+
selectColumn(...key) { this._columns.push(...(key.map(k => k))); return this; }
|
|
2849
|
+
updateColumn(key, value) { this._updates ?? (this._updates = {}); this._updates[key] = value; return this; }
|
|
2850
|
+
updateT(t) { this._updates ?? (this._updates = {}); Object.assign(this._updates, t); return this; }
|
|
2851
|
+
replace(key, valueToFind, valueToReplace) {
|
|
2852
|
+
const [pkey1, pkey2] = [`p${this._prefix}${this._index++}`, `p${this._prefix}${this._index++}`];
|
|
2853
|
+
this._updateColumns.push(` ${String(key)} = REPLACE(${String(key)}, :${pkey1}, :${pkey2}) `);
|
|
2854
|
+
this._param[pkey1] = valueToFind;
|
|
2855
|
+
this._param[pkey2] = valueToReplace;
|
|
2856
|
+
return this;
|
|
2857
|
+
}
|
|
2858
|
+
}
|
|
2859
|
+
__decorate([
|
|
2860
|
+
IF_PROCEED(),
|
|
2861
|
+
__metadata("design:type", Function),
|
|
2862
|
+
__metadata("design:paramtypes", [Object]),
|
|
2863
|
+
__metadata("design:returntype", void 0)
|
|
2864
|
+
], StreamBuild.prototype, "groupBy", null);
|
|
2865
|
+
__decorate([
|
|
2866
|
+
IF_PROCEED(),
|
|
2867
|
+
__metadata("design:type", Function),
|
|
2868
|
+
__metadata("design:paramtypes", [Object]),
|
|
2869
|
+
__metadata("design:returntype", void 0)
|
|
2870
|
+
], StreamBuild.prototype, "asc", null);
|
|
2871
|
+
__decorate([
|
|
2872
|
+
IF_PROCEED(),
|
|
2873
|
+
__metadata("design:type", Function),
|
|
2874
|
+
__metadata("design:paramtypes", [Object]),
|
|
2875
|
+
__metadata("design:returntype", void 0)
|
|
2876
|
+
], StreamBuild.prototype, "desc", null);
|
|
2877
|
+
__decorate([
|
|
2878
|
+
IF_PROCEED(),
|
|
2879
|
+
__metadata("design:type", Function),
|
|
2880
|
+
__metadata("design:paramtypes", [Number, Number]),
|
|
2881
|
+
__metadata("design:returntype", void 0)
|
|
2882
|
+
], StreamBuild.prototype, "limit", null);
|
|
2883
|
+
__decorate([
|
|
2884
|
+
IF_PROCEED(),
|
|
2885
|
+
__metadata("design:type", Function),
|
|
2886
|
+
__metadata("design:paramtypes", [Number, Number]),
|
|
2887
|
+
__metadata("design:returntype", void 0)
|
|
2888
|
+
], StreamBuild.prototype, "page", null);
|
|
2889
|
+
__decorate([
|
|
2890
|
+
IF_PROCEED(),
|
|
2891
|
+
__metadata("design:type", Function),
|
|
2892
|
+
__metadata("design:paramtypes", [String]),
|
|
2893
|
+
__metadata("design:returntype", void 0)
|
|
2894
|
+
], StreamBuild.prototype, "table", null);
|
|
2895
|
+
__decorate([
|
|
2896
|
+
IF_PROCEED(),
|
|
2897
|
+
__metadata("design:type", Function),
|
|
2898
|
+
__metadata("design:paramtypes", [Object]),
|
|
2899
|
+
__metadata("design:returntype", void 0)
|
|
2900
|
+
], StreamBuild.prototype, "distinct", null);
|
|
2901
|
+
__decorate([
|
|
2902
|
+
IF_PROCEED(),
|
|
2903
|
+
__metadata("design:type", Function),
|
|
2904
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
2905
|
+
__metadata("design:returntype", void 0)
|
|
2906
|
+
], StreamBuild.prototype, "count", null);
|
|
2907
|
+
__decorate([
|
|
2908
|
+
IF_PROCEED(),
|
|
2909
|
+
__metadata("design:type", Function),
|
|
2910
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
2911
|
+
__metadata("design:returntype", void 0)
|
|
2912
|
+
], StreamBuild.prototype, "sum", null);
|
|
2913
|
+
__decorate([
|
|
2914
|
+
IF_PROCEED(),
|
|
2915
|
+
__metadata("design:type", Function),
|
|
2916
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
2917
|
+
__metadata("design:returntype", void 0)
|
|
2918
|
+
], StreamBuild.prototype, "avg", null);
|
|
2919
|
+
__decorate([
|
|
2920
|
+
IF_PROCEED(),
|
|
2921
|
+
__metadata("design:type", Function),
|
|
2922
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
2923
|
+
__metadata("design:returntype", void 0)
|
|
2924
|
+
], StreamBuild.prototype, "max", null);
|
|
2925
|
+
__decorate([
|
|
2926
|
+
IF_PROCEED(),
|
|
2927
|
+
__metadata("design:type", Function),
|
|
2928
|
+
__metadata("design:paramtypes", [Object, String, Boolean]),
|
|
2929
|
+
__metadata("design:returntype", void 0)
|
|
2930
|
+
], StreamBuild.prototype, "min", null);
|
|
2931
|
+
__decorate([
|
|
2932
|
+
IF_PROCEED(),
|
|
2933
|
+
__metadata("design:type", Function),
|
|
2934
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2935
|
+
__metadata("design:returntype", Object)
|
|
2936
|
+
], StreamBuild.prototype, "groupConcat", null);
|
|
2937
|
+
__decorate([
|
|
2938
|
+
IF_PROCEED(),
|
|
2939
|
+
__metadata("design:type", Function),
|
|
2940
|
+
__metadata("design:paramtypes", [Object]),
|
|
2941
|
+
__metadata("design:returntype", void 0)
|
|
2942
|
+
], StreamBuild.prototype, "selectColumn", null);
|
|
2943
|
+
__decorate([
|
|
2944
|
+
IF_PROCEED(),
|
|
2945
|
+
__metadata("design:type", Function),
|
|
2946
|
+
__metadata("design:paramtypes", [Object, Object]),
|
|
2947
|
+
__metadata("design:returntype", void 0)
|
|
2948
|
+
], StreamBuild.prototype, "updateColumn", null);
|
|
2949
|
+
__decorate([
|
|
2950
|
+
IF_PROCEED(),
|
|
2951
|
+
__metadata("design:type", Function),
|
|
2952
|
+
__metadata("design:paramtypes", [Object]),
|
|
2953
|
+
__metadata("design:returntype", void 0)
|
|
2954
|
+
], StreamBuild.prototype, "updateT", null);
|
|
2955
|
+
__decorate([
|
|
2956
|
+
IF_PROCEED(),
|
|
2957
|
+
__metadata("design:type", Function),
|
|
2958
|
+
__metadata("design:paramtypes", [Object, Object, Object]),
|
|
2959
|
+
__metadata("design:returntype", void 0)
|
|
2960
|
+
], StreamBuild.prototype, "replace", null);
|
|
2961
|
+
class StreamQuery extends StreamBuild {
|
|
2962
|
+
constructor(table, service) {
|
|
2963
|
+
super(table);
|
|
2964
|
+
this._service = service;
|
|
2965
|
+
}
|
|
2966
|
+
select(option) {
|
|
2967
|
+
option.sync ?? (option.sync = SqlSyncMode.Async);
|
|
2968
|
+
const { where, params } = this.where();
|
|
2969
|
+
const sql = `
|
|
2970
|
+
SELECT
|
|
2971
|
+
${this._columns && this._columns.length > 0 ? this._columns.join(',') : '*'}
|
|
2972
|
+
FROM ${this._table}
|
|
2973
|
+
${where ? ' WHERE ' : ''}
|
|
2974
|
+
${where}`;
|
|
2975
|
+
if (option.sync === SqlSyncMode.Async) {
|
|
2976
|
+
switch (option.resultMode) {
|
|
2977
|
+
case SqlQueryMode.Many_Row_Many_Column: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
|
|
2978
|
+
case SqlQueryMode.Many_Row_One_Column: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
|
|
2979
|
+
case SqlQueryMode.One_Row_Many_Column_Assert: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
|
|
2980
|
+
case SqlQueryMode.One_Row_One_Column_Assert: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
|
|
2981
|
+
case SqlQueryMode.One_Row_Many_Column_NotSure: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
|
|
2982
|
+
case SqlQueryMode.One_Row_One_Column_NotSure: return this._service.select({ sync: SqlSyncMode.Async, resultMode: SqlQueryMode.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
|
|
2983
|
+
}
|
|
2984
|
+
}
|
|
2985
|
+
else {
|
|
2986
|
+
switch (option.resultMode) {
|
|
2987
|
+
case SqlQueryMode.Many_Row_Many_Column: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.Many_Row_Many_Column, errorMsg: option.errorMsg, sql, params });
|
|
2988
|
+
case SqlQueryMode.Many_Row_One_Column: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.Many_Row_One_Column, errorMsg: option.errorMsg, sql, params });
|
|
2989
|
+
case SqlQueryMode.One_Row_Many_Column_Assert: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.One_Row_Many_Column_Assert, errorMsg: option.errorMsg, sql, params });
|
|
2990
|
+
case SqlQueryMode.One_Row_One_Column_Assert: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.One_Row_One_Column_Assert, errorMsg: option.errorMsg, sql, params });
|
|
2991
|
+
case SqlQueryMode.One_Row_Many_Column_NotSure: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.One_Row_Many_Column_NotSure, errorMsg: option.errorMsg, sql, params });
|
|
2992
|
+
case SqlQueryMode.One_Row_One_Column_NotSure: return this._service.select({ sync: SqlSyncMode.Sync, resultMode: SqlQueryMode.One_Row_One_Column_NotSure, errorMsg: option.errorMsg, sql, params });
|
|
2993
|
+
}
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
update(option) {
|
|
2997
|
+
option.sync ?? (option.sync = SqlSyncMode.Async);
|
|
2998
|
+
const { where, params } = this.where();
|
|
2999
|
+
const sets = new Array(...this._updateColumns);
|
|
3000
|
+
if (this._updates) {
|
|
3001
|
+
for (const [K, V] of Object.entries(this._updates)) {
|
|
3002
|
+
const pkey = `p${this._prefix}${this._index++}`;
|
|
3003
|
+
sets.push(` ${K} = :${pkey} `);
|
|
3004
|
+
params[pkey] = V;
|
|
3005
|
+
}
|
|
3006
|
+
}
|
|
3007
|
+
if (sets.length > 0) {
|
|
3008
|
+
const sql = `UPDATE ${this._table} SET ${sets.join(',')} ${where}`;
|
|
3009
|
+
if (option.sync === SqlSyncMode.Async) {
|
|
3010
|
+
return this._service.excute({ sync: SqlSyncMode.Async, sql, params });
|
|
3011
|
+
}
|
|
3012
|
+
else {
|
|
3013
|
+
return this._service.excute({ sync: SqlSyncMode.Sync, sql, params });
|
|
3014
|
+
}
|
|
3015
|
+
}
|
|
3016
|
+
else {
|
|
3017
|
+
return 0;
|
|
3018
|
+
}
|
|
3019
|
+
}
|
|
3020
|
+
delete(option) {
|
|
3021
|
+
option.sync ?? (option.sync = SqlSyncMode.Async);
|
|
3022
|
+
const { where, params } = this.where();
|
|
3023
|
+
const sql = `DELETE FROM ${this._table} ${where}`;
|
|
3024
|
+
if (option.sync === SqlSyncMode.Async) {
|
|
3025
|
+
return this._service.excute({ sync: SqlSyncMode.Async, sql, params });
|
|
3026
|
+
}
|
|
3027
|
+
else {
|
|
3028
|
+
return this._service.excute({ sync: SqlSyncMode.Sync, sql, params });
|
|
3029
|
+
}
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
__decorate([
|
|
3033
|
+
IF_EXEC(null),
|
|
3034
|
+
__metadata("design:type", Function),
|
|
3035
|
+
__metadata("design:paramtypes", [Object]),
|
|
3036
|
+
__metadata("design:returntype", Object)
|
|
3037
|
+
], StreamQuery.prototype, "select", null);
|
|
3038
|
+
__decorate([
|
|
3039
|
+
IF_EXEC(0),
|
|
3040
|
+
__metadata("design:type", Function),
|
|
3041
|
+
__metadata("design:paramtypes", [Object]),
|
|
3042
|
+
__metadata("design:returntype", Object)
|
|
3043
|
+
], StreamQuery.prototype, "update", null);
|
|
3044
|
+
__decorate([
|
|
3045
|
+
IF_EXEC(0),
|
|
3046
|
+
__metadata("design:type", Function),
|
|
3047
|
+
__metadata("design:paramtypes", [Object]),
|
|
3048
|
+
__metadata("design:returntype", Object)
|
|
3049
|
+
], StreamQuery.prototype, "delete", null);
|
|
3050
|
+
/**
|
|
3051
|
+
获取REDIS客户端,
|
|
3052
|
+
# [查看库的API](https://github.com/redis/ioredis?tab=readme-ov-file)
|
|
3053
|
+
# [REDIS API](http://doc.redisfans.com/)
|
|
3054
|
+
REDIS 的API 可以直接用,将方法名转为小写
|
|
3055
|
+
*/
|
|
3056
|
+
function getRedisDB(db) {
|
|
3057
|
+
const rd = globalThis[_dao][DBType.Redis][db ?? _primaryDB];
|
|
3058
|
+
error_1.Throw.if(!rd, 'not found redis!');
|
|
3059
|
+
return rd;
|
|
3060
|
+
}
|
|
3061
|
+
exports.getRedisDB = getRedisDB;
|
|
3062
|
+
/**
|
|
3063
|
+
redlock
|
|
3064
|
+
*/
|
|
3065
|
+
async function GetRedisLock(key, lockMaxActive) {
|
|
3066
|
+
const lock = globalThis[_dao][DBType.RedisLock];
|
|
3067
|
+
error_1.Throw.if(!lock, 'not found lock!');
|
|
3068
|
+
const db = getRedisDB();
|
|
3069
|
+
let initLock;
|
|
3070
|
+
try {
|
|
3071
|
+
initLock = await lock.acquire([`[lockex]${key}`], 5000);
|
|
3072
|
+
const count = await db.get(key);
|
|
3073
|
+
if (count === null || parseInt(count) < (lockMaxActive ?? 1)) {
|
|
3074
|
+
await db.incr(key);
|
|
3075
|
+
return true;
|
|
3076
|
+
}
|
|
3077
|
+
else {
|
|
3078
|
+
return false;
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
catch (er) {
|
|
3082
|
+
return await GetRedisLock(key, lockMaxActive);
|
|
3083
|
+
}
|
|
3084
|
+
finally {
|
|
3085
|
+
if (initLock) {
|
|
3086
|
+
try {
|
|
3087
|
+
await initLock.release();
|
|
3088
|
+
// eslint-disable-next-line no-empty
|
|
3089
|
+
}
|
|
3090
|
+
catch (error) {
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
}
|
|
3094
|
+
}
|
|
3095
|
+
exports.GetRedisLock = GetRedisLock;
|
|
3096
|
+
;
|
|
3097
|
+
async function excuteWithLock(config, fn__) {
|
|
3098
|
+
const key = `[lock]${typeof config.key === 'function' ? config.key() : config.key}`;
|
|
3099
|
+
const db = getRedisDB();
|
|
3100
|
+
let wait_time = 0;
|
|
3101
|
+
const fn = async () => {
|
|
3102
|
+
const lock = await GetRedisLock(key, config.lockMaxActive);
|
|
3103
|
+
if (lock === false) {
|
|
3104
|
+
if (config.lockWait !== false && ((config.lockMaxWaitTime ?? 0) === 0 || (wait_time + (config.lockRetryInterval ?? 100)) <= (config.lockMaxWaitTime ?? 0))) {
|
|
3105
|
+
logger.debug(`get lock ${key} fail, retry after ${config.lockRetryInterval ?? 100}ms...`);
|
|
3106
|
+
await (0, fn_1.sleep)(config.lockRetryInterval ?? 100);
|
|
3107
|
+
wait_time += (config.lockRetryInterval ?? 100);
|
|
3108
|
+
return await fn();
|
|
3109
|
+
}
|
|
3110
|
+
else {
|
|
3111
|
+
logger.debug(`get lock ${key} fail`);
|
|
3112
|
+
throw new Error(config.errorMessage || `get lock fail: ${key}`);
|
|
3113
|
+
}
|
|
3114
|
+
}
|
|
3115
|
+
else {
|
|
3116
|
+
logger.debug(`get lock ${key} ok!`);
|
|
3117
|
+
await db.get('other').pexpire(key, config.lockMaxTime ?? 60000);
|
|
3118
|
+
try {
|
|
3119
|
+
return await fn__();
|
|
3120
|
+
}
|
|
3121
|
+
finally {
|
|
3122
|
+
logger.debug(`unlock ${key} ok!`);
|
|
3123
|
+
await db.get('other').decr(key);
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
};
|
|
3127
|
+
return await fn();
|
|
3128
|
+
}
|
|
3129
|
+
exports.excuteWithLock = excuteWithLock;
|
|
3130
|
+
/** 与缓存共用时,需要在缓存之前:有缓存则返回缓存,否则加锁执行并缓存,后续队列全部返回缓存,跳过执行 */
|
|
3131
|
+
function MethodLock(config) {
|
|
3132
|
+
return function (target, _propertyKey, descriptor) {
|
|
3133
|
+
const fn__ = descriptor.value;
|
|
3134
|
+
descriptor.value = async function (...args) {
|
|
3135
|
+
config.key = typeof config.key === 'function' ? config.key.call(target, ...args) : config.key;
|
|
3136
|
+
return await excuteWithLock(config, async () => await fn__.call(this, ...args));
|
|
3137
|
+
};
|
|
3138
|
+
};
|
|
3139
|
+
}
|
|
3140
|
+
exports.MethodLock = MethodLock;
|
|
3141
|
+
async function setMethodCache(config, devid) {
|
|
3142
|
+
const db = getRedisDB();
|
|
3143
|
+
if (config.result !== null && config.result !== undefined) {
|
|
3144
|
+
// 映射关系存放
|
|
3145
|
+
if (config.clearKey && config.clearKey.length > 0) {
|
|
3146
|
+
for (const clear of config.clearKey) {
|
|
3147
|
+
await db.sadd(`[cache-parent]${clear}`, config.key);
|
|
3148
|
+
await db.sadd(`[cache-child]${config.key}`, clear);
|
|
3149
|
+
}
|
|
3150
|
+
}
|
|
3151
|
+
if (config.autoClearTime) { // 自动清空
|
|
3152
|
+
await db.set(`[cache]${config.key}`, JSON.stringify(config.result), 'EX', config.autoClearTime * 60);
|
|
3153
|
+
// 订阅:清空 clear list
|
|
3154
|
+
if (config.clearKey && config.clearKey.length > 0) {
|
|
3155
|
+
globalThis[_EventBus].on(`[cache]${config.key}`, async (key) => {
|
|
3156
|
+
await clearChild(key, true);
|
|
3157
|
+
});
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
else {
|
|
3161
|
+
await db.set(`[cache]${config.key}`, JSON.stringify(config.result));
|
|
3162
|
+
}
|
|
3163
|
+
if (devid) {
|
|
3164
|
+
// 订阅:清空 clear list
|
|
3165
|
+
globalThis[_EventBus].on(`user-${devid}`, async function (key) {
|
|
3166
|
+
await clearChild(key);
|
|
3167
|
+
});
|
|
3168
|
+
}
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
async function clearMethodCache(key) {
|
|
3172
|
+
const db = getRedisDB();
|
|
3173
|
+
let type = await db.type(`[cache-parent]${key}`);
|
|
3174
|
+
if (type === 'set') {
|
|
3175
|
+
await clearParent(key);
|
|
3176
|
+
}
|
|
3177
|
+
type = await db.type(`[cache]${key}`);
|
|
3178
|
+
if (type !== 'none') {
|
|
3179
|
+
await clearChild(key);
|
|
3180
|
+
}
|
|
3181
|
+
}
|
|
3182
|
+
exports.clearMethodCache = clearMethodCache;
|
|
3183
|
+
async function clearChild(key, skipDel = false) {
|
|
3184
|
+
const db = getRedisDB();
|
|
3185
|
+
if (skipDel === false) {
|
|
3186
|
+
await db.del(`[cache]${key}`);
|
|
3187
|
+
}
|
|
3188
|
+
const childtype = await db.type(`[cache-child]${key}`);
|
|
3189
|
+
if (childtype === 'set') {
|
|
3190
|
+
const parentKeys = await db.smembers(`[cache-child]${key}`);
|
|
3191
|
+
for (const clear of parentKeys) {
|
|
3192
|
+
const type = await db.type(`[cache-parent]${clear}`);
|
|
3193
|
+
if (type === 'set') {
|
|
3194
|
+
await db.srem(`[cache-parent]${clear}`, key);
|
|
3195
|
+
}
|
|
3196
|
+
}
|
|
3197
|
+
await db.del(`[cache-child]${key}`);
|
|
3198
|
+
}
|
|
3199
|
+
}
|
|
3200
|
+
async function clearParent(clearKey) {
|
|
3201
|
+
const db = getRedisDB();
|
|
3202
|
+
const keys = await db.smembers(`[cache-parent]${clearKey}`);
|
|
3203
|
+
if (keys) {
|
|
3204
|
+
for (const key of keys) {
|
|
3205
|
+
logger.debug(`cache ${key} cleared!`);
|
|
3206
|
+
await clearChild(key);
|
|
3207
|
+
}
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
async function excuteWithCache(config, fn) {
|
|
3211
|
+
const db = getRedisDB();
|
|
3212
|
+
const cache = await db.get(`[cache]${config.key}`);
|
|
3213
|
+
if (cache) {
|
|
3214
|
+
logger.debug(`cache ${config.key} hit!`);
|
|
3215
|
+
return JSON.parse(cache);
|
|
3216
|
+
}
|
|
3217
|
+
else {
|
|
3218
|
+
logger.debug(`cache ${config.key} miss!`);
|
|
3219
|
+
const result = await fn();
|
|
3220
|
+
await setMethodCache({
|
|
3221
|
+
key: config.key,
|
|
3222
|
+
clearKey: config.clearKey,
|
|
3223
|
+
autoClearTime: config.autoClearTime,
|
|
3224
|
+
result
|
|
3225
|
+
});
|
|
3226
|
+
return result;
|
|
3227
|
+
}
|
|
3228
|
+
}
|
|
3229
|
+
exports.excuteWithCache = excuteWithCache;
|
|
3230
|
+
function MethodCache(config) {
|
|
3231
|
+
return function (target, _propertyKey, descriptor) {
|
|
3232
|
+
const fn = descriptor.value;
|
|
3233
|
+
descriptor.value = async function (...args) {
|
|
3234
|
+
const key = typeof config.key === 'function' ? config.key.call(this, ...args) : config.key;
|
|
3235
|
+
const db = getRedisDB();
|
|
3236
|
+
const cache = await db.get('other').get(`[cache]${key}`);
|
|
3237
|
+
if (cache) {
|
|
3238
|
+
logger.debug(`cache ${key} hit!`);
|
|
3239
|
+
return JSON.parse(cache);
|
|
3240
|
+
}
|
|
3241
|
+
else {
|
|
3242
|
+
logger.debug(`cache ${key} miss!`);
|
|
3243
|
+
const result = await fn.call(this, ...args);
|
|
3244
|
+
const clearKey = config.clearKey ? typeof config.clearKey === 'function' ? config.clearKey.call(this, ...args) : config.clearKey : undefined;
|
|
3245
|
+
await setMethodCache({
|
|
3246
|
+
key,
|
|
3247
|
+
clearKey,
|
|
3248
|
+
autoClearTime: config.autoClearTime,
|
|
3249
|
+
result
|
|
3250
|
+
}, config.clearWithSession && this.ctx.me && this.ctx.me.devid);
|
|
3251
|
+
return result;
|
|
3252
|
+
}
|
|
3253
|
+
};
|
|
3254
|
+
};
|
|
3255
|
+
}
|
|
3256
|
+
exports.MethodCache = MethodCache;
|
|
3257
|
+
const LetsGo = async function (options) {
|
|
3258
|
+
globalThis[_GlobalSqlOption] = Object.assign({}, _defOption, options);
|
|
3259
|
+
if (options.sqlDir) {
|
|
3260
|
+
globalThis[_path] = Promise.resolve().then(() => __importStar(require('path')));
|
|
3261
|
+
globalThis[_fs] = Promise.resolve().then(() => __importStar(require('fs')));
|
|
3262
|
+
}
|
|
3263
|
+
logger.level = options.log ?? 'info';
|
|
3264
|
+
globalThis[_sqlCache] = new SqlCache();
|
|
3265
|
+
if (options.sqlCache || options.sqlDir) {
|
|
3266
|
+
await globalThis[_sqlCache].init(options);
|
|
3267
|
+
}
|
|
3268
|
+
globalThis[_dao] = {
|
|
3269
|
+
[DBType.Mongo]: {},
|
|
3270
|
+
[DBType.Mysql]: {},
|
|
3271
|
+
[DBType.Sqlite]: {},
|
|
3272
|
+
[DBType.SqliteRemote]: {},
|
|
3273
|
+
[DBType.Redis]: {}
|
|
3274
|
+
};
|
|
3275
|
+
if (options.Mysql) {
|
|
3276
|
+
const { createPool } = await Promise.resolve().then(() => __importStar(require('mysql2/promise')));
|
|
3277
|
+
if (options.Mysql['host']) {
|
|
3278
|
+
globalThis[_dao][DBType.Mysql][_primaryDB] = new Mysql(createPool({
|
|
3279
|
+
...options.Mysql,
|
|
3280
|
+
multipleStatements: true,
|
|
3281
|
+
decimalNumbers: true,
|
|
3282
|
+
supportBigNumbers: true
|
|
3283
|
+
}));
|
|
3284
|
+
}
|
|
3285
|
+
else {
|
|
3286
|
+
let flag = false;
|
|
3287
|
+
for (const [key, option] of Object.entries(options.Mysql)) {
|
|
3288
|
+
const db = new Mysql(createPool({
|
|
3289
|
+
...option,
|
|
3290
|
+
multipleStatements: true,
|
|
3291
|
+
decimalNumbers: true,
|
|
3292
|
+
supportBigNumbers: true
|
|
3293
|
+
}));
|
|
3294
|
+
if (flag === false) {
|
|
3295
|
+
globalThis[_dao][DBType.Mysql][_primaryDB] = db;
|
|
3296
|
+
flag = true;
|
|
3297
|
+
}
|
|
3298
|
+
globalThis[_dao][DBType.Mysql][key] = db;
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
}
|
|
3302
|
+
if (options.Sqlite) {
|
|
3303
|
+
const BetterSqlite3 = await Promise.resolve().then(() => __importStar(require('better-sqlite3')));
|
|
3304
|
+
if (typeof options.Sqlite === 'string') {
|
|
3305
|
+
globalThis[_dao][DBType.Sqlite][_primaryDB] = new Sqlite(new BetterSqlite3.default(options.Sqlite, { fileMustExist: false }));
|
|
3306
|
+
}
|
|
3307
|
+
else {
|
|
3308
|
+
let flag = false;
|
|
3309
|
+
for (const [key, fileName] of Object.entries(options.Sqlite)) {
|
|
3310
|
+
const db = new Sqlite(new BetterSqlite3.default(fileName, { fileMustExist: false }));
|
|
3311
|
+
if (flag === false) {
|
|
3312
|
+
globalThis[_dao][DBType.Sqlite][_primaryDB] = db;
|
|
3313
|
+
flag = true;
|
|
3314
|
+
}
|
|
3315
|
+
globalThis[_dao][DBType.Sqlite][key] = db;
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
}
|
|
3319
|
+
if (options.SqliteRemote) {
|
|
3320
|
+
if (typeof options.SqliteRemote.db === 'string') {
|
|
3321
|
+
await options.SqliteRemote.service.initDB(options.SqliteRemote.db);
|
|
3322
|
+
globalThis[_dao][DBType.SqliteRemote][_primaryDB] = new SqliteRemote(options.SqliteRemote.service, options.SqliteRemote.db);
|
|
3323
|
+
}
|
|
3324
|
+
else {
|
|
3325
|
+
let flag = false;
|
|
3326
|
+
for (const [key, fileName] of Object.entries(options.SqliteRemote.db)) {
|
|
3327
|
+
await options.SqliteRemote.service.initDB(fileName);
|
|
3328
|
+
const db = new SqliteRemote(options.SqliteRemote.service, fileName);
|
|
3329
|
+
if (flag === false) {
|
|
3330
|
+
globalThis[_dao][DBType.SqliteRemote][_primaryDB] = db;
|
|
3331
|
+
flag = true;
|
|
3332
|
+
}
|
|
3333
|
+
globalThis[_dao][DBType.SqliteRemote][key] = db;
|
|
3334
|
+
}
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
3337
|
+
if (options.Redis) {
|
|
3338
|
+
const { Redis } = await Promise.resolve().then(() => __importStar(require('ioredis')));
|
|
3339
|
+
if (options.Redis['host']) {
|
|
3340
|
+
globalThis[_dao][DBType.Redis][_primaryDB] = new Redis(options.Redis);
|
|
3341
|
+
}
|
|
3342
|
+
else {
|
|
3343
|
+
let flag = false;
|
|
3344
|
+
for (const [key, option] of Object.entries(options.Redis)) {
|
|
3345
|
+
const db = new Redis(option);
|
|
3346
|
+
if (flag === false) {
|
|
3347
|
+
globalThis[_dao][DBType.Redis][_primaryDB] = db;
|
|
3348
|
+
flag = true;
|
|
3349
|
+
}
|
|
3350
|
+
globalThis[_dao][DBType.Redis][key] = db;
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
const clients = Object.values(globalThis[_dao][DBType.Redis]);
|
|
3354
|
+
const Redlock = await Promise.resolve().then(() => __importStar(require('Redlock')));
|
|
3355
|
+
globalThis[_dao][DBType.RedisLock] = new Redlock.default(clients, {
|
|
3356
|
+
// The expected clock drift; for more details see:
|
|
3357
|
+
// http://redis.io/topics/distlock
|
|
3358
|
+
driftFactor: 0.01, // multiplied by lock ttl to determine drift time
|
|
3359
|
+
// The max number of times Redlock will attempt to lock a resource
|
|
3360
|
+
// before erroring.
|
|
3361
|
+
retryCount: 10,
|
|
3362
|
+
// the time in ms between attempts
|
|
3363
|
+
retryDelay: 200, // time in ms
|
|
3364
|
+
// the max time in ms randomly added to retries
|
|
3365
|
+
// to improve performance under high contention
|
|
3366
|
+
// see https://www.awsarchitectureblog.com/2015/03/backoff.html
|
|
3367
|
+
retryJitter: 200, // time in ms
|
|
3368
|
+
// The minimum remaining time on a lock before an extension is automatically
|
|
3369
|
+
// attempted with the `using` API.
|
|
3370
|
+
automaticExtensionThreshold: 500, // time in ms
|
|
3371
|
+
});
|
|
3372
|
+
const { EventEmitter } = await Promise.resolve().then(() => __importStar(require('events')));
|
|
3373
|
+
const event = new EventEmitter({ captureRejections: true });
|
|
3374
|
+
event.on('error', error => {
|
|
3375
|
+
logger.error('event-bus', error);
|
|
3376
|
+
});
|
|
3377
|
+
globalThis[_EventBus] = event;
|
|
3378
|
+
}
|
|
3379
|
+
};
|
|
3380
|
+
exports.LetsGo = LetsGo;
|