tspace-mysql 1.2.9 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +64 -14
  2. package/dist/cli/dump/db.d.ts +4 -4
  3. package/dist/cli/dump/db.js +25 -25
  4. package/dist/cli/generate/make.d.ts +4 -4
  5. package/dist/cli/generate/make.js +45 -45
  6. package/dist/cli/generate/model.d.ts +2 -2
  7. package/dist/cli/generate/model.js +6 -6
  8. package/dist/cli/index.d.ts +2 -2
  9. package/dist/cli/index.js +58 -58
  10. package/dist/cli/migrate/make.d.ts +4 -4
  11. package/dist/cli/migrate/make.js +30 -30
  12. package/dist/cli/models/make.d.ts +4 -4
  13. package/dist/cli/models/make.js +51 -51
  14. package/dist/cli/models/model.d.ts +2 -2
  15. package/dist/cli/models/model.js +20 -11
  16. package/dist/cli/query/index.d.ts +4 -4
  17. package/dist/cli/query/index.js +7 -7
  18. package/dist/cli/tables/make.d.ts +4 -4
  19. package/dist/cli/tables/make.js +26 -26
  20. package/dist/cli/tables/table.d.ts +2 -2
  21. package/dist/cli/tables/table.js +6 -6
  22. package/dist/lib/connection/index.d.ts +30 -30
  23. package/dist/lib/connection/index.js +144 -143
  24. package/dist/lib/connection/options.d.ts +15 -4
  25. package/dist/lib/connection/options.js +43 -42
  26. package/dist/lib/constants/index.d.ts +5 -8
  27. package/dist/lib/constants/index.js +162 -158
  28. package/dist/lib/index.d.ts +8 -8
  29. package/dist/lib/index.js +36 -36
  30. package/dist/lib/tspace/{AbstractDatabase.d.ts → AbstractBuilder.d.ts} +124 -116
  31. package/dist/lib/tspace/{AbstractDatabase.js → AbstractBuilder.js} +36 -34
  32. package/dist/lib/tspace/AbstractDB.d.ts +18 -18
  33. package/dist/lib/tspace/AbstractDB.js +11 -11
  34. package/dist/lib/tspace/AbstractModel.d.ts +41 -41
  35. package/dist/lib/tspace/AbstractModel.js +11 -11
  36. package/dist/lib/tspace/Blueprint.d.ts +136 -136
  37. package/dist/lib/tspace/Blueprint.js +228 -228
  38. package/dist/lib/tspace/{Database.d.ts → Builder.d.ts} +833 -706
  39. package/dist/lib/tspace/{Database.js → Builder.js} +2556 -2363
  40. package/dist/lib/tspace/DB.d.ts +152 -126
  41. package/dist/lib/tspace/DB.js +373 -264
  42. package/dist/lib/tspace/Interface.d.ts +110 -109
  43. package/dist/lib/tspace/Interface.js +2 -2
  44. package/dist/lib/tspace/Logger.d.ts +8 -8
  45. package/dist/lib/tspace/Logger.js +49 -49
  46. package/dist/lib/tspace/Model.d.ts +708 -609
  47. package/dist/lib/tspace/Model.js +2520 -2477
  48. package/dist/lib/tspace/ProxyHandler.d.ts +14 -14
  49. package/dist/lib/tspace/ProxyHandler.js +31 -31
  50. package/dist/lib/tspace/Schema.d.ts +8 -8
  51. package/dist/lib/tspace/Schema.js +45 -44
  52. package/dist/lib/tspace/index.d.ts +15 -15
  53. package/dist/lib/tspace/index.js +20 -20
  54. package/dist/lib/utils/index.d.ts +15 -15
  55. package/dist/lib/utils/index.js +155 -165
  56. package/package.json +2 -4
@@ -1,2363 +1,2556 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- var __importDefault = (this && this.__importDefault) || function (mod) {
23
- return (mod && mod.__esModule) ? mod : { "default": mod };
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.Database = void 0;
27
- const fs_1 = __importDefault(require("fs"));
28
- const sql_formatter_1 = require("sql-formatter");
29
- const AbstractDatabase_1 = __importDefault(require("./AbstractDatabase"));
30
- const utils_1 = __importDefault(require("../utils"));
31
- const constants_1 = require("../constants");
32
- const DB_1 = __importDefault(require("./DB"));
33
- const connection_1 = require("../connection");
34
- class Database extends AbstractDatabase_1.default {
35
- constructor() {
36
- super();
37
- this._initialConnection();
38
- }
39
- /**
40
- *
41
- * @param {string} column
42
- * @return {this}
43
- */
44
- pluck(column) {
45
- this.$state.set('PLUCK', column);
46
- return this;
47
- }
48
- /**
49
- *
50
- * @param {...string} columns
51
- * @return {this} this
52
- */
53
- except(...columns) {
54
- this.$state.set('EXCEPT', columns.length ? columns : ['id']);
55
- return this;
56
- }
57
- /**
58
- * data alaways will return void
59
- * @return {this} this
60
- */
61
- void() {
62
- this.$state.set('VOID', true);
63
- return this;
64
- }
65
- /**
66
- *
67
- * @param {...string} columns show only colums selected
68
- * @return {this} this
69
- */
70
- only(...columns) {
71
- this.$state.set('ONLY', columns);
72
- return this;
73
- }
74
- /**
75
- *
76
- * @param {string=} column [column=id]
77
- * @return {this} this
78
- */
79
- distinct(column = 'id') {
80
- this.$state.set('SELECT', [
81
- `${this.$constants('SELECT')}`,
82
- `${this.$constants('DISTINCT')}`,
83
- `${column}`
84
- ].join(' '));
85
- return this;
86
- }
87
- /**
88
- * select data form table
89
- * @param {Array<string>} ...columns
90
- * @return {this} this
91
- */
92
- select(...columns) {
93
- let select = '*';
94
- if (columns === null || columns === void 0 ? void 0 : columns.length)
95
- select = columns.join(', ');
96
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${select}`);
97
- return this;
98
- }
99
- /**
100
- * chunks data from array
101
- * @param {number} chunk
102
- * @return {this} this
103
- */
104
- chunk(chunk) {
105
- this.$state.set('CHUNK', chunk);
106
- return this;
107
- }
108
- /**
109
- *
110
- * @param {string | number | undefined | null | Boolean} condition when condition true will return query callback
111
- * @return {this} this
112
- */
113
- when(condition, callback) {
114
- if (condition)
115
- callback(this);
116
- return this;
117
- }
118
- /**
119
- * if has 2 arguments default operator '='
120
- * @param {string} column
121
- * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
122
- * @param {any?} value
123
- * @return {this}
124
- */
125
- resetWhere() {
126
- this.$state.set('WHERE', '');
127
- return this;
128
- }
129
- /**
130
- * if has 2 arguments default operator '='
131
- * @param {string} column
132
- * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
133
- * @param {any?} value
134
- * @return {this}
135
- */
136
- where(column, operator, value) {
137
- [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
138
- value = this.$utils.escape(value);
139
- value = this._valueTrueFalse(value);
140
- if (!this._queryWhereIsExists()) {
141
- this.$state.set('WHERE', [
142
- `${this.$constants('WHERE')}`,
143
- `${this._bindTableAndColumnInQueryWhere(column)} ${operator} '${value}'`
144
- ].join(' '));
145
- return this;
146
- }
147
- this.$state.set('WHERE', [
148
- `${this.$state.get('WHERE')}`,
149
- `${this.$constants('AND')}`,
150
- `${this._bindTableAndColumnInQueryWhere(column)} ${operator} '${value}'`
151
- ].join(' '));
152
- return this;
153
- }
154
- /**
155
- * where using object operator only '='
156
- * @param {Object} columns
157
- * @return {this}
158
- */
159
- whereObject(columns) {
160
- for (const column in columns) {
161
- const operator = '=';
162
- const value = columns[column];
163
- if (!this._queryWhereIsExists()) {
164
- this.$state.set('WHERE', [
165
- `${this.$constants('WHERE')}`,
166
- `${this._bindTableAndColumnInQueryWhere(column)} ${operator} '${value}'`
167
- ].join(' '));
168
- continue;
169
- }
170
- this.$state.set('WHERE', [
171
- `${this.$state.get('WHERE')}`,
172
- `${this.$constants('AND')}`,
173
- `${this._bindTableAndColumnInQueryWhere(column)} ${operator} '${value}'`
174
- ].join(' '));
175
- }
176
- return this;
177
- }
178
- /**
179
- * if has 2 arguments default operator '='
180
- * @param {string} column
181
- * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
182
- * @param {any?} value
183
- * @return {this}
184
- */
185
- orWhere(column, operator, value) {
186
- [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
187
- value = this.$utils.escape(value);
188
- if (!this._queryWhereIsExists()) {
189
- this.$state.set('WHERE', [
190
- `${this.$constants('WHERE')}`,
191
- `${this._bindTableAndColumnInQueryWhere(column)} ${operator} '${value}'`
192
- ].join(' '));
193
- return this;
194
- }
195
- this.$state.set('WHERE', [
196
- `${this.$state.get('WHERE')}`,
197
- `${this.$constants('OR')}`,
198
- `${this._bindTableAndColumnInQueryWhere(column)} ${operator} '${value}'`
199
- ].join(' '));
200
- return this;
201
- }
202
- /**
203
- *
204
- * @param {string} sql where column with raw sql
205
- * @return {this} this
206
- */
207
- whereRaw(sql) {
208
- if (!this._queryWhereIsExists()) {
209
- this.$state.set('WHERE', [
210
- `${this.$constants('WHERE')}`,
211
- `${sql}`
212
- ].join(' '));
213
- return this;
214
- }
215
- this.$state.set('WHERE', [
216
- `${this.$state.get('WHERE')}`,
217
- `${this.$constants('AND')}`,
218
- `${sql}`
219
- ].join(' '));
220
- return this;
221
- }
222
- /**
223
- *
224
- * @param {string} query where column with raw sql
225
- * @return {this} this
226
- */
227
- orWhereRaw(sql) {
228
- if (!this._queryWhereIsExists()) {
229
- this.$state.set('WHERE', [
230
- `${this.$constants('WHERE')}`,
231
- `${sql}`
232
- ].join(' '));
233
- return this;
234
- }
235
- this.$state.set('WHERE', [
236
- `${this.$state.get('WHERE')}`,
237
- `${this.$constants('OR')}`,
238
- `${sql}`
239
- ].join(' '));
240
- return this;
241
- }
242
- /**
243
- *
244
- * @param {string} tableAndLocalKey
245
- * @param {string?} tableAndForeignKey
246
- * @return {this}
247
- */
248
- whereReference(tableAndLocalKey, tableAndForeignKey) {
249
- if (!this._queryWhereIsExists()) {
250
- this.$state.set('WHERE', [
251
- `${this.$constants('WHERE')}`,
252
- `${tableAndLocalKey} = ${tableAndForeignKey}`
253
- ].join(' '));
254
- return this;
255
- }
256
- this.$state.set('WHERE', [
257
- `${this.$state.get('WHERE')}`,
258
- `${this.$constants('AND')}`,
259
- `${tableAndLocalKey} = ${tableAndForeignKey}`
260
- ].join(' '));
261
- return this;
262
- }
263
- /**
264
- *
265
- * where exists
266
- * @param {string} sql
267
- * @return {this}
268
- */
269
- whereExists(sql) {
270
- if (!this._queryWhereIsExists()) {
271
- this.$state.set('WHERE', [
272
- `${this.$constants('WHERE')}`,
273
- `${this.$constants('EXISTS')}`,
274
- `(${sql})`
275
- ].join(' '));
276
- return this;
277
- }
278
- this.$state.set('WHERE', [
279
- `${this.$state.get('WHERE')}`,
280
- `${this.$constants('AND')}`,
281
- `${this.$constants('EXISTS')}`,
282
- `(${sql})`
283
- ].join(' '));
284
- return this;
285
- }
286
- /**
287
- *
288
- * @param {number} id
289
- * @param {string?} column custom it *if column is not id
290
- * @return {this} this
291
- */
292
- whereId(id, column = 'id') {
293
- if (!this._queryWhereIsExists()) {
294
- this.$state.set('WHERE', [
295
- `${this.$constants('WHERE')}`,
296
- `${this._bindTableAndColumnInQueryWhere(column)} = '${id}'`
297
- ].join(' '));
298
- return this;
299
- }
300
- this.$state.set('WHERE', [
301
- `${this.$state.get('WHERE')}`,
302
- `${this.$constants('AND')}`,
303
- `${this._bindTableAndColumnInQueryWhere(column)} = '${id}'`
304
- ].join(' '));
305
- return this;
306
- }
307
- /**
308
- *
309
- * @param {string} email where using email
310
- * @return {this}
311
- */
312
- whereEmail(email) {
313
- const column = 'email';
314
- email = this.$utils.escape(email);
315
- if (!this._queryWhereIsExists()) {
316
- this.$state.set('WHERE', [
317
- `${this.$constants('WHERE')}`,
318
- `${this._bindTableAndColumnInQueryWhere(column)} = '${email}'`
319
- ].join(' '));
320
- return this;
321
- }
322
- this.$state.set('WHERE', [
323
- `${this.$state.get('WHERE')}`,
324
- `${this.$constants('AND')}`,
325
- `${this._bindTableAndColumnInQueryWhere(column)} = '${email}'`
326
- ].join(' '));
327
- return this;
328
- }
329
- /**
330
- *
331
- * @param {number} id
332
- * @param {string?} column custom it *if column is not user_id
333
- * @return {this}
334
- */
335
- whereUser(id, column = 'user_id') {
336
- id = this.$utils.escape(id);
337
- if (!this._queryWhereIsExists()) {
338
- this.$state.set('WHERE', [
339
- `${this.$constants('WHERE')}`,
340
- `${this._bindTableAndColumnInQueryWhere(column)} = '${id}'`
341
- ].join(' '));
342
- return this;
343
- }
344
- this.$state.set('WHERE', [
345
- `${this.$state.get('WHERE')}`,
346
- `${this.$constants('AND')}`,
347
- `${this._bindTableAndColumnInQueryWhere(column)} = '${id}'`
348
- ].join(' '));
349
- return this;
350
- }
351
- /**
352
- * using array value where in value in array
353
- * @param {string} column
354
- * @param {array} array
355
- * @return {this}
356
- */
357
- whereIn(column, array) {
358
- if (!Array.isArray(array))
359
- throw new Error(`[${array}] is't array`);
360
- if (!array.length)
361
- array = ['0'];
362
- const values = `${array.map((value) => `\'${value}\'`).join(',')}`;
363
- if (!this._queryWhereIsExists()) {
364
- this.$state.set('WHERE', [
365
- `${this.$constants('WHERE')}`,
366
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${values})`
367
- ].join(' '));
368
- return this;
369
- }
370
- this.$state.set('WHERE', [
371
- `${this.$state.get('WHERE')}`,
372
- `${this.$constants('AND')}`,
373
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${values})`
374
- ].join(' '));
375
- return this;
376
- }
377
- /**
378
- * or where in data using array values
379
- * @param {string} column
380
- * @param {array} array
381
- * @return {this}
382
- */
383
- orWhereIn(column, array) {
384
- const sql = this.$state.get('WHERE');
385
- if (!Array.isArray(array))
386
- throw new Error(`[${array}] is't array`);
387
- if (!array.length)
388
- array = ['0'];
389
- const values = `${array.map((value) => `\'${value}\'`).join(',')}`;
390
- if (!sql.includes(this.$constants('WHERE'))) {
391
- this.$state.set('WHERE', [
392
- `${this.$constants('WHERE')}`,
393
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${values})`
394
- ].join(' '));
395
- return this;
396
- }
397
- this.$state.set('WHERE', [
398
- `${this.$state.get('WHERE')}`,
399
- `${this.$constants('OR')}`,
400
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${values})`
401
- ].join(' '));
402
- return this;
403
- }
404
- /**
405
- * where not in data using array values
406
- * @param {string} column
407
- * @param {array} array
408
- * @return {this}
409
- */
410
- whereNotIn(column, array) {
411
- const sql = this.$state.get('WHERE');
412
- if (!Array.isArray(array))
413
- throw new Error(`[${array}] is't array`);
414
- if (!array.length)
415
- array = ['0'];
416
- const values = `${array.map((value) => `\'${value}\'`).join(',')}`;
417
- if (!sql.includes(this.$constants('WHERE'))) {
418
- this.$state.set('WHERE', [
419
- `${this.$constants('WHERE')}`,
420
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('NOT_IN')} (${values})`
421
- ].join(' '));
422
- return this;
423
- }
424
- this.$state.set('WHERE', [
425
- `${this.$state.get('WHERE')}`,
426
- `${this.$constants('AND')}`,
427
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('NOT_IN')} (${values})`
428
- ].join(' '));
429
- return this;
430
- }
431
- /**
432
- * where sub query using sub query sql
433
- * @param {string} column
434
- * @param {string} subQuery
435
- * @return {this}
436
- */
437
- whereSubQuery(column, subQuery) {
438
- const whereSubQuery = this.$state.get('WHERE');
439
- subQuery = this.$utils.escapeSubQuery(subQuery);
440
- if (!whereSubQuery.includes(this.$constants('WHERE'))) {
441
- this.$state.set('WHERE', [
442
- `${this.$constants('WHERE')}`,
443
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${subQuery})`
444
- ].join(' '));
445
- return this;
446
- }
447
- this.$state.set('WHERE', [
448
- `${this.$state.get('WHERE')}`,
449
- `${this.$constants('AND')}`,
450
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${subQuery})`
451
- ].join(' '));
452
- return this;
453
- }
454
- /**
455
- * where not sub query using sub query sql
456
- * @param {string} column
457
- * @param {string} subQuery
458
- * @return {this}
459
- */
460
- whereNotSubQuery(column, subQuery) {
461
- const whereSubQuery = this.$state.get('WHERE');
462
- subQuery = this.$utils.escapeSubQuery(subQuery);
463
- if (!whereSubQuery.includes(this.$constants('WHERE'))) {
464
- this.$state.set('WHERE', [
465
- `${this.$constants('WHERE')}`,
466
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${subQuery})`
467
- ].join(' '));
468
- return this;
469
- }
470
- this.$state.set('WHERE', [
471
- `${this.$state.get('WHERE')}`,
472
- `${this.$constants('AND')}`,
473
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('NOT_IN')} (${subQuery})`
474
- ].join(' '));
475
- return this;
476
- }
477
- /**
478
- * or where not sub query using query sql
479
- * @param {string} column
480
- * @param {string} subQuery
481
- * @return {this}
482
- */
483
- orWhereSubQuery(column, subQuery) {
484
- const whereSubQuery = this.$state.get('WHERE');
485
- subQuery = this.$utils.escapeSubQuery(subQuery);
486
- if (!whereSubQuery.includes(this.$constants('WHERE'))) {
487
- this.$state.set('WHERE', [
488
- `${this.$constants('WHERE')}`,
489
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${subQuery})`
490
- ].join(' '));
491
- return this;
492
- }
493
- this.$state.set('WHERE', [
494
- `${this.$state.get('WHERE')}`,
495
- `${this.$constants('OR')}`,
496
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')} (${subQuery})`
497
- ].join(' '));
498
- return this;
499
- }
500
- /**
501
- * where between using [value1, value2]
502
- * @param {string} column
503
- * @param {array} array
504
- * @return {this}
505
- */
506
- whereBetween(column, array) {
507
- if (!Array.isArray(array))
508
- throw new Error("Value is't array");
509
- if (!array.length)
510
- array = ['0', '0'];
511
- let [value1, value2] = array;
512
- value1 = this.$utils.escape(value1);
513
- value2 = this.$utils.escape(value2);
514
- if (!this._queryWhereIsExists()) {
515
- this.$state.set('WHERE', [
516
- `${this.$constants('WHERE')}`,
517
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('BETWEEN')}`,
518
- `'${value1}' ${this.$constants('AND')} '${value2}'`
519
- ].join(' '));
520
- return this;
521
- }
522
- this.$state.set('WHERE', [
523
- `${this.$state.get('WHERE')}`,
524
- `${this.$constants('AND')}`,
525
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('BETWEEN')}`,
526
- `'${value1}' ${this.$constants('AND')} '${value2}'`
527
- ].join(' '));
528
- return this;
529
- }
530
- /**
531
- * where null using NULL
532
- * @param {string} column
533
- * @return {this}
534
- */
535
- whereNull(column) {
536
- if (!this._queryWhereIsExists()) {
537
- this.$state.set('WHERE', [
538
- `${this.$constants('WHERE')}`,
539
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IS_NULL')}`
540
- ].join(' '));
541
- return this;
542
- }
543
- this.$state.set('WHERE', [
544
- `${this.$state.get('WHERE')}`,
545
- `${this.$constants('AND')}`,
546
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IS_NULL')}`
547
- ].join(' '));
548
- return this;
549
- }
550
- /**
551
- * where not null using NULL
552
- * @param {string} column
553
- * @return {this}
554
- */
555
- whereNotNull(column) {
556
- if (!this._queryWhereIsExists()) {
557
- this.$state.set('WHERE', [
558
- `${this.$constants('WHERE')}`,
559
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IS_NOT_NULL')}`
560
- ].join(' '));
561
- return this;
562
- }
563
- this.$state.set('WHERE', [
564
- `${this.$state.get('WHERE')}`,
565
- `${this.$constants('AND')}`,
566
- `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IS_NOT_NULL')}`
567
- ].join(' '));
568
- return this;
569
- }
570
- /**
571
- * where sensitive (uppercase, lowercase)
572
- * @param {string} column
573
- * @param {string?} operator = < > != !< !>
574
- * @param {any?} value
575
- * @return {this}
576
- */
577
- whereSensitive(column, operator, value) {
578
- [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
579
- value = this.$utils.escape(value);
580
- value = this._valueTrueFalse(value);
581
- if (!this._queryWhereIsExists()) {
582
- this.$state.set('WHERE', [
583
- `${this.$constants('WHERE')}`,
584
- `BINARY ${this._bindTableAndColumnInQueryWhere(column)} ${operator} '${value}'`
585
- ].join(' '));
586
- return this;
587
- }
588
- this.$state.set('WHERE', [
589
- `${this.$state.get('WHERE')}`,
590
- `${this.$constants('AND')}`,
591
- `BINARY ${this._bindTableAndColumnInQueryWhere(column)} ${operator} '${value}'`
592
- ].join(' '));
593
- return this;
594
- }
595
- /**
596
- * where group query
597
- * @param {function} callback callback query
598
- * @return {this}
599
- */
600
- whereQuery(callback) {
601
- var _a;
602
- const db = new DB_1.default((_a = this.$state.get('TABLE_NAME')) === null || _a === void 0 ? void 0 : _a.replace(/`/g, ''));
603
- const repository = callback(db);
604
- if (!(repository instanceof DB_1.default)) {
605
- throw new Error(`unknown callback query: '[${repository}]'`);
606
- }
607
- const where = (repository === null || repository === void 0 ? void 0 : repository.$state.get('WHERE')) || '';
608
- if (where === '') {
609
- throw new Error(`unknown callback query with where condition`);
610
- }
611
- if (this._queryWhereIsExists()) {
612
- const query = where.replace('WHERE', '');
613
- this.$state.set('WHERE', [
614
- `${this.$state.get('WHERE')}`,
615
- `${this.$constants('AND')}`,
616
- `(${query})`
617
- ].join(' '));
618
- return this;
619
- }
620
- const query = where.replace('WHERE', '');
621
- this.$state.set('WHERE', [
622
- `${this.$constants('WHERE')}`,
623
- `(${query})`
624
- ].join(' '));
625
- return this;
626
- }
627
- /**
628
- * select by cases
629
- * @param {array} cases array object [{ when : 'id < 7' , then : 'id is than under 7'}]
630
- * @param {string} as
631
- * @return {this}
632
- */
633
- case(cases, as) {
634
- let query = [this.$constants('CASE')];
635
- for (let i = 0; i < cases.length; i++) {
636
- const c = cases[i];
637
- if (cases.length - 1 === i) {
638
- if (c.then == null)
639
- throw new Error(`can't find then condition`);
640
- query = [
641
- ...query,
642
- `${this.$constants('ELSE')} '${c.then}'`,
643
- `${this.$constants('END')}`
644
- ];
645
- continue;
646
- }
647
- if (c.when == null)
648
- throw new Error(`can't find when condition`);
649
- if (c.then == null)
650
- throw new Error(`can't find then condition`);
651
- query = [
652
- ...query,
653
- `${this.$constants('WHEN')} ${c.when} ${this.$constants('THEN')} '${c.then}'`
654
- ];
655
- }
656
- if (query.length <= 1)
657
- return this;
658
- this.$state.set('SELECT', `${this.$state.get('SELECT')}, ${query.join(' ')} ${this.$constants('AS')} ${as}`);
659
- return this;
660
- }
661
- /**
662
- *
663
- * @param {string} condition
664
- * @return {this}
665
- */
666
- having(condition) {
667
- this.$state.set('HAVING', condition);
668
- return this;
669
- }
670
- /**
671
- *
672
- * @param {string} pk talbe.pk
673
- * @param {string} fk talbe.fk
674
- * @return {this}
675
- */
676
- join(pk, fk) {
677
- var _a;
678
- const table = (_a = fk.split('.')) === null || _a === void 0 ? void 0 : _a.shift();
679
- if (this.$state.get('JOIN')) {
680
- this.$state.set('JOIN', [
681
- `${this.$state.get('JOIN')}`,
682
- `${this.$constants('INNER_JOIN')}`,
683
- `${table} ${this.$constants('ON')} ${pk} = ${fk}`
684
- ].join(' '));
685
- return this;
686
- }
687
- this.$state.set('JOIN', [
688
- `${this.$constants('INNER_JOIN')}`,
689
- `${table} ${this.$constants('ON')} ${pk} = ${fk}`
690
- ].join(' '));
691
- return this;
692
- }
693
- /**
694
- *
695
- * @param {string} pk talbe.pk
696
- * @param {string} fk talbe.fk
697
- * @return {this}
698
- */
699
- rightJoin(pk, fk) {
700
- var _a;
701
- const table = (_a = fk.split('.')) === null || _a === void 0 ? void 0 : _a.shift();
702
- if (this.$state.get('JOIN')) {
703
- this.$state.set('JOIN', [
704
- `${this.$state.get('JOIN')}`,
705
- `${this.$constants('RIGHT_JOIN')}`,
706
- `${table} ${this.$constants('ON')} ${pk} = ${fk}`
707
- ].join(' '));
708
- return this;
709
- }
710
- this.$state.set('JOIN', [
711
- `${this.$constants('RIGHT_JOIN')}`,
712
- `${table} ${this.$constants('ON')} ${pk} = ${fk}`
713
- ].join(' '));
714
- return this;
715
- }
716
- /**
717
- *
718
- * @param {string} pk talbe.pk
719
- * @param {string} fk talbe.fk
720
- * @return {this}
721
- */
722
- leftJoin(pk, fk) {
723
- var _a;
724
- const table = (_a = fk.split('.')) === null || _a === void 0 ? void 0 : _a.shift();
725
- if (this.$state.get('JOIN')) {
726
- this.$state.set('JOIN', [
727
- `${this.$state.get('JOIN')}`,
728
- `${this.$constants('LEFT_JOIN')}`,
729
- `${table} ${this.$constants('ON')} ${pk} = ${fk}`
730
- ].join(' '));
731
- return this;
732
- }
733
- this.$state.set('JOIN', [
734
- `${this.$constants('LEFT_JOIN')}`,
735
- `${table} ${this.$constants('ON')} ${pk} = ${fk}`
736
- ].join(' '));
737
- return this;
738
- }
739
- /**
740
- *
741
- * @param {string} pk talbe.pk
742
- * @param {string} fk talbe.fk
743
- * @return {this}
744
- */
745
- crossJoin(pk, fk) {
746
- var _a;
747
- const table = (_a = fk.split('.')) === null || _a === void 0 ? void 0 : _a.shift();
748
- if (this.$state.get('JOIN')) {
749
- this.$state.set('JOIN', [
750
- `${this.$state.get('JOIN')}`,
751
- `${this.$constants('CROSS_JOIN')}`,
752
- `${table} ${this.$constants('ON')} ${pk} = ${fk}`
753
- ].join(' '));
754
- return this;
755
- }
756
- this.$state.set('JOIN', [
757
- `${this.$constants('CROSS_JOIN')}`,
758
- `${table} ${this.$constants('ON')} ${pk} = ${fk}`
759
- ].join(' '));
760
- return this;
761
- }
762
- /**
763
- *
764
- * @param {string} column
765
- * @param {string?} order [order=asc] asc, desc
766
- * @return {this}
767
- */
768
- orderBy(column, order = this.$constants('ASC')) {
769
- if (this.$state.get('ORDER_BY')) {
770
- this.$state.set('ORDER_BY', [
771
- `${this.$state.get('ORDER_BY')}`,
772
- `,${column} ${order.toUpperCase()}`
773
- ].join(' '));
774
- return this;
775
- }
776
- this.$state.set('ORDER_BY', [
777
- `${this.$constants('ORDER_BY')}`,
778
- `${column} ${order.toUpperCase()}`
779
- ].join(' '));
780
- return this;
781
- }
782
- /**
783
- *
784
- * @param {string?} column [column=id]
785
- * @return {this}
786
- */
787
- latest(...columns) {
788
- let orderByDefault = 'id';
789
- if (columns === null || columns === void 0 ? void 0 : columns.length)
790
- orderByDefault = columns.join(', ');
791
- this.$state.set('ORDER_BY', [
792
- `${this.$constants('ORDER_BY')}`,
793
- `${orderByDefault} ${this.$constants('DESC')}`
794
- ].join(' '));
795
- return this;
796
- }
797
- /**
798
- *
799
- * @param {string?} column [column=id]
800
- * @return {this}
801
- */
802
- oldest(...columns) {
803
- let orderByDefault = 'id';
804
- if (columns === null || columns === void 0 ? void 0 : columns.length)
805
- orderByDefault = columns.join(', ');
806
- this.$state.set('ORDER_BY', [
807
- `${this.$constants('ORDER_BY')}`,
808
- `${orderByDefault} ${this.$constants('ASC')}`
809
- ].join(' '));
810
- return this;
811
- }
812
- /**
813
- *
814
- * @param {string?} column [column=id]
815
- * @return {this}
816
- */
817
- groupBy(...columns) {
818
- let groupBy = 'id';
819
- if (columns === null || columns === void 0 ? void 0 : columns.length)
820
- groupBy = columns.join(', ');
821
- this.$state.set('GROUP_BY', `${this.$constants('GROUP_BY')} ${groupBy}`);
822
- return this;
823
- }
824
- /**
825
- *
826
- * @param {number=} number [number=1]
827
- * @return {this}
828
- */
829
- limit(number = 1) {
830
- this.$state.set('LIMIT', `${this.$constants('LIMIT')} ${number}`);
831
- return this;
832
- }
833
- /**
834
- *
835
- * @param {number=} number [number=1]
836
- * @return {this}
837
- */
838
- offset(number = 1) {
839
- this.$state.set('OFFSET', `${this.$constants('OFFSET')} ${number}`);
840
- return this;
841
- }
842
- /**
843
- *
844
- * @param {...string} columns
845
- * @return {this} this
846
- */
847
- hidden(...columns) {
848
- this.$state.set('HIDDEN', columns);
849
- return this;
850
- }
851
- /**
852
- *
853
- * update data in the database
854
- * @param {object} data
855
- * @return {this} this
856
- */
857
- update(data) {
858
- const query = this._queryUpdate(data);
859
- this.$state.set('UPDATE', [
860
- `${this.$constants('UPDATE')}`,
861
- `${this.$state.get('TABLE_NAME')}`,
862
- `${query}`
863
- ].join(' '));
864
- this.$state.set('SAVE', 'UPDATE');
865
- return this;
866
- }
867
- /**
868
- *
869
- * insert data into the database
870
- * @param {object} data
871
- * @return {this} this
872
- */
873
- insert(data) {
874
- const query = this._queryInsert(data);
875
- this.$state.set('INSERT', [
876
- `${this.$constants('INSERT')}`,
877
- `${this.$state.get('TABLE_NAME')}`,
878
- `${query}`
879
- ].join(' '));
880
- this.$state.set('SAVE', 'INSERT');
881
- return this;
882
- }
883
- /**
884
- *
885
- * insert data into the database
886
- * @param {object} data
887
- * @return {this} this
888
- */
889
- create(data) {
890
- const query = this._queryInsert(data);
891
- this.$state.set('INSERT', [
892
- `${this.$constants('INSERT')}`,
893
- `${this.$state.get('TABLE_NAME')}`,
894
- `${query}`
895
- ].join(' '));
896
- this.$state.set('SAVE', 'INSERT');
897
- return this;
898
- }
899
- /**
900
- *
901
- * insert muliple data into the database
902
- * @param {array} data create multiple data
903
- * @return {this} this this
904
- */
905
- createMultiple(data) {
906
- const query = this._queryInsertMultiple(data);
907
- this.$state.set('INSERT', [
908
- `${this.$constants('INSERT')}`,
909
- `${this.$state.get('TABLE_NAME')}`,
910
- `${query}`
911
- ].join(' '));
912
- this.$state.set('SAVE', 'INSERT_MULTIPLE');
913
- return this;
914
- }
915
- /**
916
- *
917
- * insert muliple data into the database
918
- * @param {array} data create multiple data
919
- * @return {this} this this
920
- */
921
- insertMultiple(data) {
922
- const query = this._queryInsertMultiple(data);
923
- this.$state.set('INSERT', [
924
- `${this.$constants('INSERT')}`,
925
- `${this.$state.get('TABLE_NAME')}`,
926
- `${query}`
927
- ].join(' '));
928
- this.$state.set('SAVE', 'INSERT_MULTIPLE');
929
- return this;
930
- }
931
- /**
932
- *
933
- * @return {string} return sql query
934
- */
935
- toString() {
936
- return this._buildQuery();
937
- }
938
- /**
939
- *
940
- * @return {string} return sql query
941
- */
942
- toSQL() {
943
- return this._buildQuery();
944
- }
945
- /**
946
- *
947
- * @param {boolean} debug debug sql statements
948
- * @return {this} this this
949
- */
950
- debug(debug = true) {
951
- this.$state.set('DEBUG', debug);
952
- return this;
953
- }
954
- /**
955
- *
956
- * @param {boolean} debug debug sql statements
957
- * @return {this} this this
958
- */
959
- dd(debug = true) {
960
- this.$state.set('DEBUG', debug);
961
- return this;
962
- }
963
- /**
964
- * hook function when execute returned result to callback function
965
- * @param {Function} func function for callback result
966
- * @return {this}
967
- */
968
- hook(func) {
969
- if (typeof func !== "function")
970
- throw new Error(`this '${func}' is not a function`);
971
- this.$state.set('HOOK', [...this.$state.get('HOOK'), func]);
972
- return this;
973
- }
974
- /**
975
- *
976
- * @param {object} data create not exists data
977
- * @return {this} this this
978
- */
979
- createNotExists(data) {
980
- const query = this._queryInsert(data);
981
- this.$state.set('INSERT', [
982
- `${this.$constants('INSERT')}`,
983
- `${this.$state.get('TABLE_NAME')}`,
984
- `${query}`
985
- ].join(' '));
986
- this.$state.set('SAVE', 'INSERT_NOT_EXISTS');
987
- return this;
988
- }
989
- /**
990
- *
991
- * @param {object} data insert not exists data
992
- * @return {this} this this
993
- */
994
- insertNotExists(data) {
995
- this.createNotExists(data);
996
- return this;
997
- }
998
- /**
999
- *
1000
- * check data if exists if exists then update. if not exists insert
1001
- * @param {object} data insert or update data
1002
- * @return {this} this this
1003
- */
1004
- updateOrCreate(data) {
1005
- const queryUpdate = this._queryUpdate(data);
1006
- const queryInsert = this._queryInsert(data);
1007
- this.$state.set('INSERT', [
1008
- `${this.$constants('INSERT')}`,
1009
- `${this.$state.get('TABLE_NAME')}`,
1010
- `${queryInsert}`
1011
- ].join(' '));
1012
- this.$state.set('UPDATE', [
1013
- `${this.$constants('UPDATE')}`,
1014
- `${this.$state.get('TABLE_NAME')}`,
1015
- `${queryUpdate}`
1016
- ].join(' '));
1017
- this.$state.set('SAVE', 'UPDATE_OR_INSERT');
1018
- return this;
1019
- }
1020
- /**
1021
- *
1022
- * check data if exists if exists then update. if not exists insert
1023
- * @param {object} data insert or update data
1024
- * @return {this} this this
1025
- */
1026
- updateOrInsert(data) {
1027
- this.updateOrCreate(data);
1028
- return this;
1029
- }
1030
- /**
1031
- *
1032
- * check data if exists if exists then update. if not exists insert
1033
- * @param {object} data insert or update data
1034
- * @return {this} this this
1035
- */
1036
- insertOrUpdate(data) {
1037
- this.updateOrCreate(data);
1038
- return this;
1039
- }
1040
- /**
1041
- *
1042
- * check data if exists if exists then update. if not exists insert
1043
- * @param {object} data create or update data
1044
- * @return {this} this this
1045
- */
1046
- createOrUpdate(data) {
1047
- this.updateOrCreate(data);
1048
- return this;
1049
- }
1050
- /**
1051
- *
1052
- * @param {Object} options options for connection database with credentials
1053
- * @param {string} option.host
1054
- * @param {number} option.port
1055
- * @param {string} option.database
1056
- * @param {string} option.user
1057
- * @param {string} option.password
1058
- * @return {this} this
1059
- */
1060
- connection(options) {
1061
- const { host, port, database, username: user, password } = options, others = __rest(options, ["host", "port", "database", "username", "password"]);
1062
- const pool = new connection_1.PoolConnection(Object.assign({ host,
1063
- port,
1064
- database,
1065
- user,
1066
- password }, others));
1067
- this.$pool.set(pool.connection());
1068
- return this;
1069
- }
1070
- /**
1071
- *
1072
- * @param {Function} pool pool connection database
1073
- * @return {this} this
1074
- */
1075
- pool(pool) {
1076
- if (!(pool === null || pool === void 0 ? void 0 : pool.hasOwnProperty('query'))) {
1077
- throw new Error('pool must have a query property');
1078
- }
1079
- this.$pool.set(pool);
1080
- return this;
1081
- }
1082
- /**
1083
- * make sure this connection has same transaction in pool connection
1084
- * @param {object} connection pool database
1085
- * @return {this} this
1086
- */
1087
- bind(connection) {
1088
- if (!(connection === null || connection === void 0 ? void 0 : connection.hasOwnProperty('query'))) {
1089
- throw new Error('connection must have a query property');
1090
- }
1091
- if (typeof connection.query !== 'function') {
1092
- throw new Error('connection must have a query function');
1093
- }
1094
- this.$pool.set(connection);
1095
- return this;
1096
- }
1097
- /**
1098
- * exceptColumns for method except
1099
- * @return {promise<string>} string
1100
- */
1101
- exceptColumns() {
1102
- return __awaiter(this, void 0, void 0, function* () {
1103
- const sql = [
1104
- `${this.$constants('SHOW')}`,
1105
- `${this.$constants('COLUMNS')}`,
1106
- `${this.$constants('FROM')}`,
1107
- `${this.$state.get('TABLE_NAME')}`
1108
- ].join(' ');
1109
- const rawColumns = yield this.queryStatement(sql);
1110
- const columns = rawColumns.map((column) => column.Field);
1111
- const removeExcept = columns.filter((column) => !this.$state.get('EXCEPT').includes(column));
1112
- return removeExcept.join(', ');
1113
- });
1114
- }
1115
- /**
1116
- * execute sql statements with raw sql query
1117
- * @param {string} sql sql execute return data
1118
- * @return {promise<any>}
1119
- */
1120
- rawQuery(sql) {
1121
- return __awaiter(this, void 0, void 0, function* () {
1122
- return yield this.queryStatement(sql);
1123
- });
1124
- }
1125
- /**
1126
- *
1127
- * plus value then update
1128
- * @param {string} column
1129
- * @param {number} value
1130
- * @return {promise<any>}
1131
- */
1132
- increment(column = 'id', value = 1) {
1133
- return __awaiter(this, void 0, void 0, function* () {
1134
- const query = `${this.$constants('SET')} ${column} = ${column} + ${value}`;
1135
- this.$state.set('UPDATE', [
1136
- `${this.$constants('UPDATE')}`,
1137
- `${this.$state.get('TABLE_NAME')}`,
1138
- `${query}`
1139
- ].join(' '));
1140
- return yield this._update(true);
1141
- });
1142
- }
1143
- /**
1144
- *
1145
- * minus value then update
1146
- * @param {string} column
1147
- * @param {number} value
1148
- * @return {promise<any>}
1149
- */
1150
- decrement(column = 'id', value = 1) {
1151
- return __awaiter(this, void 0, void 0, function* () {
1152
- const query = `${this.$constants('SET')} ${column} = ${column} - ${value}`;
1153
- this.$state.set('UPDATE', [
1154
- `${this.$constants('UPDATE')}`,
1155
- `${this.$state.get('TABLE_NAME')}`,
1156
- `${query}`
1157
- ].join(' '));
1158
- return yield this._update(true);
1159
- });
1160
- }
1161
- /**
1162
- * execute data without condition
1163
- * @return {promise<any>}
1164
- */
1165
- all() {
1166
- return __awaiter(this, void 0, void 0, function* () {
1167
- return yield this.queryStatement([
1168
- `${this.$constants('SELECT')}`,
1169
- `*`,
1170
- `${this.$constants('FROM')}`,
1171
- `${this.$state.get('TABLE_NAME')}`
1172
- ].join(' '));
1173
- });
1174
- }
1175
- /**
1176
- *
1177
- * execute data with where by id
1178
- * @param {number} id
1179
- * @return {promise<any>}
1180
- */
1181
- find(id) {
1182
- return __awaiter(this, void 0, void 0, function* () {
1183
- const result = yield this.queryStatement([
1184
- `${this.$constants('SELECT')}`,
1185
- `*`,
1186
- `${this.$constants('FROM')}`,
1187
- `${this.$state.get('TABLE_NAME')}`,
1188
- `${this.$constants('WHERE')} id = ${id}`
1189
- ].join(' '));
1190
- return (result === null || result === void 0 ? void 0 : result.shift()) || null;
1191
- });
1192
- }
1193
- /**
1194
- *
1195
- * execute data page & limit
1196
- * @param {?object} paginationOptions
1197
- * @param {number} paginationOptions.limit default 15
1198
- * @param {number} paginationOptions.page default 1
1199
- * @return {promise<Pagination>}
1200
- */
1201
- pagination(paginationOptions) {
1202
- var _a, _b;
1203
- return __awaiter(this, void 0, void 0, function* () {
1204
- let limit = 15;
1205
- let page = 1;
1206
- if (paginationOptions != null) {
1207
- limit = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit;
1208
- page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
1209
- }
1210
- const currentPage = page;
1211
- const nextPage = currentPage + 1;
1212
- const prevPage = currentPage - 1 === 0 ? 1 : currentPage - 1;
1213
- const offset = (page - 1) * limit;
1214
- let sql = this._buildQuery();
1215
- sql = sql.replace(this.$state.get('LIMIT'), `${limit} ${this.$constants('OFFSET')} ${offset}`);
1216
- if (!sql.includes(this.$constants('LIMIT'))) {
1217
- sql = [
1218
- `${sql}`,
1219
- `${this.$constants('LIMIT')}`,
1220
- `${limit}`,
1221
- `${this.$constants('OFFSET')} ${offset}`
1222
- ].join(' ');
1223
- }
1224
- const result = yield this.queryStatement(sql);
1225
- if ((_a = this.$state.get('HIDDEN')) === null || _a === void 0 ? void 0 : _a.length)
1226
- this._hiddenColumn(result);
1227
- if (!result.length)
1228
- return {
1229
- meta: {
1230
- total: 0,
1231
- limit,
1232
- total_page: 0,
1233
- current_page: currentPage,
1234
- last_page: 0,
1235
- next_page: 0,
1236
- prev_page: 0
1237
- },
1238
- data: []
1239
- };
1240
- this.$state.set('SELECT', [
1241
- `${this.$constants('SELECT')}`,
1242
- `${this.$constants('COUNT')}(*)`,
1243
- `${this.$constants('AS')} total`
1244
- ].join(' '));
1245
- sql = this._buildQuery();
1246
- const count = yield this.queryStatement(sql);
1247
- const total = count.shift().total || 0;
1248
- let lastPage = Math.ceil(total / limit) || 0;
1249
- lastPage = lastPage > 1 ? lastPage : 1;
1250
- const totalPage = (_b = result === null || result === void 0 ? void 0 : result.length) !== null && _b !== void 0 ? _b : 0;
1251
- return {
1252
- meta: {
1253
- total_page: totalPage,
1254
- total,
1255
- limit,
1256
- current_page: currentPage,
1257
- last_page: lastPage,
1258
- next_page: nextPage,
1259
- prev_page: prevPage
1260
- },
1261
- data: result !== null && result !== void 0 ? result : []
1262
- };
1263
- });
1264
- }
1265
- /**
1266
- *
1267
- * execute data useing page & limit
1268
- * @param {?object} paginationOptions
1269
- * @param {number} paginationOptions.limit
1270
- * @param {number} paginationOptions.page
1271
- * @return {promise<Pagination>}
1272
- */
1273
- paginate(paginationOptions) {
1274
- return __awaiter(this, void 0, void 0, function* () {
1275
- let limit = 15;
1276
- let page = 1;
1277
- if (paginationOptions != null) {
1278
- limit = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit;
1279
- page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
1280
- }
1281
- return yield this.pagination({ limit, page });
1282
- });
1283
- }
1284
- /**
1285
- *
1286
- * execute data return object | null
1287
- * @return {promise<object | null>}
1288
- */
1289
- first() {
1290
- var _a, _b;
1291
- return __awaiter(this, void 0, void 0, function* () {
1292
- if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
1293
- this.select(yield this.exceptColumns());
1294
- let sql = this._buildQuery();
1295
- if (!sql.includes(this.$constants('LIMIT')))
1296
- sql = `${sql} ${this.$constants('LIMIT')} 1`;
1297
- else
1298
- sql = sql.replace(this.$state.get('LIMIT'), `${this.$constants('LIMIT')} 1`);
1299
- const result = yield this.queryStatement(sql);
1300
- if ((_b = this.$state.get('HIDDEN')) === null || _b === void 0 ? void 0 : _b.length)
1301
- this._hiddenColumn(result);
1302
- if (this.$state.get('PLUCK')) {
1303
- const pluck = this.$state.get('PLUCK');
1304
- const newData = result === null || result === void 0 ? void 0 : result.shift();
1305
- const checkProperty = newData.hasOwnProperty(pluck);
1306
- if (!checkProperty)
1307
- throw new Error(`can't find property '${pluck}' of result`);
1308
- const r = newData[pluck] || null;
1309
- const hook = this.$state.get('HOOK');
1310
- for (let i in hook)
1311
- yield hook[i](r);
1312
- return r;
1313
- }
1314
- const r = (result === null || result === void 0 ? void 0 : result.shift()) || null;
1315
- const hook = this.$state.get('HOOK');
1316
- for (let i in hook)
1317
- yield hook[i](r);
1318
- return r;
1319
- });
1320
- }
1321
- /**
1322
- *
1323
- * execute data return object | throw rror
1324
- * @return {promise<object | null>}
1325
- */
1326
- findOne() {
1327
- return __awaiter(this, void 0, void 0, function* () {
1328
- return yield this.first();
1329
- });
1330
- }
1331
- /**
1332
- *
1333
- * execute data return object | throw Error
1334
- * @return {promise<object | Error>}
1335
- */
1336
- firstOrError(message, options) {
1337
- var _a, _b;
1338
- return __awaiter(this, void 0, void 0, function* () {
1339
- if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
1340
- this.select(yield this.exceptColumns());
1341
- let sql = this._buildQuery();
1342
- if (!sql.includes(this.$constants('LIMIT')))
1343
- sql = `${sql} ${this.$constants('LIMIT')} 1`;
1344
- else
1345
- sql = sql.replace(this.$state.get('LIMIT'), `${this.$constants('LIMIT')} 1`);
1346
- const result = yield this.queryStatement(sql);
1347
- if ((_b = this.$state.get('HIDDEN')) === null || _b === void 0 ? void 0 : _b.length)
1348
- this._hiddenColumn(result);
1349
- if (this.$state.get('PLUCK')) {
1350
- const pluck = this.$state.get('PLUCK');
1351
- const newData = result === null || result === void 0 ? void 0 : result.shift();
1352
- const checkProperty = newData.hasOwnProperty(pluck);
1353
- if (!checkProperty)
1354
- throw new Error(`can't find property '${pluck}' of result`);
1355
- const data = newData[pluck] || null;
1356
- if (data == null) {
1357
- if (options == null) {
1358
- throw { message, code: 400 };
1359
- }
1360
- throw Object.assign({ message }, options);
1361
- }
1362
- const hook = this.$state.get('HOOK');
1363
- for (let i in hook)
1364
- yield hook[i](data);
1365
- return data;
1366
- }
1367
- const data = (result === null || result === void 0 ? void 0 : result.shift()) || null;
1368
- if (data == null) {
1369
- if (options == null) {
1370
- throw { message, code: 400 };
1371
- }
1372
- throw Object.assign({ message }, options);
1373
- }
1374
- const hook = this.$state.get('HOOK');
1375
- for (let i in hook)
1376
- yield hook[i](data);
1377
- return data;
1378
- });
1379
- }
1380
- /**
1381
- *
1382
- * execute data return object | null
1383
- * @return {promise<object | null>}
1384
- */
1385
- findOneOrError(message, options) {
1386
- return __awaiter(this, void 0, void 0, function* () {
1387
- return this.firstOrError(message, options);
1388
- });
1389
- }
1390
- /**
1391
- *
1392
- * execute data return Array
1393
- * @return {promise<Array<any>>}
1394
- */
1395
- get() {
1396
- var _a, _b;
1397
- return __awaiter(this, void 0, void 0, function* () {
1398
- if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
1399
- this.select(yield this.exceptColumns());
1400
- const sql = this._buildQuery();
1401
- const result = yield this.queryStatement(sql);
1402
- if ((_b = this.$state.get('HIDDEN')) === null || _b === void 0 ? void 0 : _b.length)
1403
- this._hiddenColumn(result);
1404
- if (this.$state.get('CHUNK')) {
1405
- const data = result.reduce((resultArray, item, index) => {
1406
- const chunkIndex = Math.floor(index / this.$state.get('CHUNK'));
1407
- if (!resultArray[chunkIndex])
1408
- resultArray[chunkIndex] = [];
1409
- resultArray[chunkIndex].push(item);
1410
- return resultArray;
1411
- }, []);
1412
- const hook = this.$state.get('HOOK');
1413
- for (let i in hook)
1414
- yield hook[i](data || []);
1415
- return data || [];
1416
- }
1417
- if (this.$state.get('PLUCK')) {
1418
- const pluck = this.$state.get('PLUCK');
1419
- const newData = result.map((d) => d[pluck]);
1420
- if (newData.every((d) => d == null)) {
1421
- throw new Error(`can't find property '${pluck}' of result`);
1422
- }
1423
- const hook = this.$state.get('HOOK');
1424
- for (let i in hook)
1425
- yield hook[i](newData || []);
1426
- return newData || [];
1427
- }
1428
- const hook = this.$state.get('HOOK');
1429
- for (let i in hook)
1430
- yield hook[i](result || []);
1431
- return result || [];
1432
- });
1433
- }
1434
- /**
1435
- *
1436
- * execute data return Array
1437
- * @return {promise<Array<any>>}
1438
- */
1439
- findMany() {
1440
- return __awaiter(this, void 0, void 0, function* () {
1441
- return yield this.get();
1442
- });
1443
- }
1444
- /**
1445
- *
1446
- * execute data return json of result
1447
- * @return {promise<string>}
1448
- */
1449
- toJSON() {
1450
- var _a, _b;
1451
- return __awaiter(this, void 0, void 0, function* () {
1452
- if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
1453
- this.select(yield this.exceptColumns());
1454
- const sql = this._buildQuery();
1455
- const result = yield this.queryStatement(sql);
1456
- if ((_b = this.$state.get('HIDDEN')) === null || _b === void 0 ? void 0 : _b.length)
1457
- this._hiddenColumn(result);
1458
- return JSON.stringify(result);
1459
- });
1460
- }
1461
- /**
1462
- *
1463
- * execute data return array of results
1464
- * @param {string=} column [column=id]
1465
- * @return {promise<Array>}
1466
- */
1467
- toArray(column = 'id') {
1468
- return __awaiter(this, void 0, void 0, function* () {
1469
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${column}`);
1470
- const sql = this._buildQuery();
1471
- const result = yield this.queryStatement(sql);
1472
- const toArray = result.map((data) => data[column]);
1473
- return toArray;
1474
- });
1475
- }
1476
- /**
1477
- *
1478
- * execute data return number of results
1479
- * @param {string=} column [column=id]
1480
- * @return {promise<number>}
1481
- */
1482
- count(column = 'id') {
1483
- var _a;
1484
- return __awaiter(this, void 0, void 0, function* () {
1485
- this.$state.set('SELECT', [
1486
- `${this.$constants('SELECT')}`,
1487
- `${this.$constants('COUNT')}(${column})`,
1488
- `${this.$constants('AS')} total`
1489
- ].join(' '));
1490
- const sql = this._buildQuery();
1491
- const result = yield this.queryStatement(sql);
1492
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.total) || 0;
1493
- });
1494
- }
1495
- /**
1496
- *
1497
- * execute data return result is exists
1498
- * @return {promise<boolean>}
1499
- */
1500
- exists() {
1501
- var _a;
1502
- return __awaiter(this, void 0, void 0, function* () {
1503
- const result = yield this.queryStatement([
1504
- `${this.$constants('SELECT')}`,
1505
- `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
1506
- `*`,
1507
- `${this.$state.get('FROM')}`,
1508
- `${this.$state.get('TABLE_NAME')}`,
1509
- `${this.$state.get('WHERE')}`,
1510
- `${this.$constants('LIMIT')} 1) ${this.$constants('AS')} 'exists'`
1511
- ].join(' '));
1512
- return !!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false;
1513
- });
1514
- }
1515
- /**
1516
- *
1517
- * execute data return average of results
1518
- * @param {string=} column [column=id]
1519
- * @return {promise<number>}
1520
- */
1521
- avg(column = 'id') {
1522
- var _a;
1523
- return __awaiter(this, void 0, void 0, function* () {
1524
- this.$state.set('SELECT', [
1525
- `${this.$constants('SELECT')}`,
1526
- `${this.$constants('AVG')}(${column})`,
1527
- `${this.$constants('AS')} avg`
1528
- ].join(' '));
1529
- const sql = this._buildQuery();
1530
- const result = yield this.queryStatement(sql);
1531
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.avg) || 0;
1532
- });
1533
- }
1534
- /**
1535
- *
1536
- * execute data return summary of results
1537
- * @param {string=} column [column=id]
1538
- * @return {promise<number>}
1539
- */
1540
- sum(column = 'id') {
1541
- var _a;
1542
- return __awaiter(this, void 0, void 0, function* () {
1543
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('SUM')}(${column}) ${this.$constants('AS')} sum`);
1544
- const sql = this._buildQuery();
1545
- const result = yield this.queryStatement(sql);
1546
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0;
1547
- });
1548
- }
1549
- /**
1550
- *
1551
- * execute data return maximum of results
1552
- * @param {string=} column [column=id]
1553
- * @return {promise<number>}
1554
- */
1555
- max(column = 'id') {
1556
- var _a;
1557
- return __awaiter(this, void 0, void 0, function* () {
1558
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MAX')}(${column}) ${this.$constants('AS')} max`);
1559
- const sql = this._buildQuery();
1560
- const result = yield this.queryStatement(sql);
1561
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0;
1562
- });
1563
- }
1564
- /**
1565
- *
1566
- * execute data return minimum of results
1567
- * @param {string=} column [column=id]
1568
- * @return {promise<number>}
1569
- */
1570
- min(column = 'id') {
1571
- var _a;
1572
- return __awaiter(this, void 0, void 0, function* () {
1573
- this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MIN')}(${column}) ${this.$constants('AS')} min`);
1574
- const sql = this._buildQuery();
1575
- const result = yield this.queryStatement(sql);
1576
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0;
1577
- });
1578
- }
1579
- /**
1580
- *
1581
- * delete data from database
1582
- * @return {promise<boolean>}
1583
- */
1584
- delete() {
1585
- var _a;
1586
- return __awaiter(this, void 0, void 0, function* () {
1587
- if (!this.$state.get('WHERE')) {
1588
- throw new Error("can't delete without where condition");
1589
- }
1590
- this.$state.set('DELETE', [
1591
- `${this.$constants('DELETE')}`,
1592
- `${this.$state.get('FROM')}`,
1593
- `${this.$state.get('TABLE_NAME')}`,
1594
- `${this.$state.get('WHERE')}`
1595
- ].join(' '));
1596
- const result = yield this.actionStatement({ sql: this.$state.get('DELETE') });
1597
- if (result)
1598
- return (_a = !!result) !== null && _a !== void 0 ? _a : false;
1599
- return false;
1600
- });
1601
- }
1602
- /**
1603
- *
1604
- * delete data from database ignore where condition
1605
- * @return {promise<boolean>}
1606
- */
1607
- forceDelete() {
1608
- var _a;
1609
- return __awaiter(this, void 0, void 0, function* () {
1610
- this.$state.set('DELETE', [
1611
- `${this.$constants('DELETE')}`,
1612
- `${this.$state.get('FROM')}`,
1613
- `${this.$state.get('TABLE_NAME')}`,
1614
- `${this.$state.get('WHERE')}`
1615
- ].join(' '));
1616
- const result = yield this.actionStatement({ sql: this.$state.get('DELETE') });
1617
- if (result)
1618
- return (_a = !!result) !== null && _a !== void 0 ? _a : false;
1619
- return false;
1620
- });
1621
- }
1622
- /**
1623
- *
1624
- * execute data return Array *grouping results in column
1625
- * @param {string} column
1626
- * @return {promise<Array>}
1627
- */
1628
- getGroupBy(column) {
1629
- return __awaiter(this, void 0, void 0, function* () {
1630
- this.$state.set('GROUP_BY', `${this.$constants('GROUP_BY')} ${column}`);
1631
- this.$state.set('SELECT', [
1632
- `${this.$state.get('SELECT')}`,
1633
- `, ${this.$constants('GROUP_CONCAT')}(id)`,
1634
- `${this.$constants('AS')} data`
1635
- ].join(' '));
1636
- const sql = this._buildQuery();
1637
- const results = yield this.queryStatement(sql);
1638
- let data = [];
1639
- results.forEach((result) => {
1640
- var _a, _b;
1641
- const splits = (_b = (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.split(',')) !== null && _b !== void 0 ? _b : '0';
1642
- splits.forEach((split) => data = [...data, split]);
1643
- });
1644
- const sqlGroups = [
1645
- `${this.$constants('SELECT')}`,
1646
- `*`,
1647
- `${this.$constants('FROM')}`,
1648
- `${this.$state.get('TABLE_NAME')}`,
1649
- `${this.$constants('WHERE')} id ${this.$constants('IN')}`,
1650
- `(${data.map((a) => `\'${a}\'`).join(',') || ['0']})`
1651
- ].join(' ');
1652
- const groups = yield this.queryStatement(sqlGroups);
1653
- const resultData = results.map((result) => {
1654
- const id = result[column];
1655
- const newData = groups.filter((data) => data[column] === id);
1656
- return ({
1657
- [column]: id,
1658
- data: newData
1659
- });
1660
- });
1661
- return resultData;
1662
- });
1663
- }
1664
- /**
1665
- *
1666
- * execute data return grouping results by index
1667
- * @param {string} column
1668
- * @return {promise<Array>}
1669
- */
1670
- findManyGroupBy(column) {
1671
- return __awaiter(this, void 0, void 0, function* () {
1672
- return yield this.getGroupBy(column);
1673
- });
1674
- }
1675
- /**
1676
- * execute data when save *action [insert , update]
1677
- * @return {Promise<any>} promise
1678
- */
1679
- save() {
1680
- return __awaiter(this, void 0, void 0, function* () {
1681
- const attributes = this.$attributes;
1682
- if (attributes != null) {
1683
- while (true) {
1684
- if (this.$state.get('WHERE')) {
1685
- const query = this._queryUpdate(attributes);
1686
- this.$state.set('UPDATE', [
1687
- `${this.$constants('UPDATE')}`,
1688
- `${this.$state.get('TABLE_NAME')}`,
1689
- `${query}`
1690
- ].join(' '));
1691
- this.$state.set('SAVE', 'UPDATE');
1692
- break;
1693
- }
1694
- const query = this._queryInsert(attributes);
1695
- this.$state.set('INSERT', [
1696
- `${this.$constants('INSERT')}`,
1697
- `${this.$state.get('TABLE_NAME')}`,
1698
- `${query}`
1699
- ].join(' '));
1700
- this.$state.set('SAVE', 'INSERT');
1701
- break;
1702
- }
1703
- }
1704
- switch (this.$state.get('SAVE')) {
1705
- case 'INSERT_MULTIPLE': return yield this._createMultiple();
1706
- case 'INSERT': return yield this._create();
1707
- case 'UPDATE': return yield this._update();
1708
- case 'INSERT_NOT_EXISTS': return yield this._insertNotExists();
1709
- case 'UPDATE_OR_INSERT': return yield this._updateOrInsert();
1710
- default: throw new Error(`unknown this [${this.$state.get('SAVE')}]`);
1711
- }
1712
- });
1713
- }
1714
- /**
1715
- *
1716
- * show columns in table
1717
- * @param {string=} table table name
1718
- * @return {Promise<Array>}
1719
- */
1720
- showColumns(table = this.$state.get('TABLE_NAME')) {
1721
- return __awaiter(this, void 0, void 0, function* () {
1722
- const sql = [
1723
- `${this.$constants('SHOW')}`,
1724
- `${this.$constants('COLUMNS')}`,
1725
- `${this.$constants('FROM')}`,
1726
- `\`${table.replace(/\`/g, '')}\``
1727
- ].join(' ');
1728
- const rawColumns = yield this.queryStatement(sql);
1729
- const columns = rawColumns.map((column) => column.Field);
1730
- return columns;
1731
- });
1732
- }
1733
- /**
1734
- *
1735
- * show schemas in table
1736
- * @param {string=} table [table= current table name]
1737
- * @return {Promise<Array>}
1738
- */
1739
- showSchemas(table = this.$state.get('TABLE_NAME')) {
1740
- return __awaiter(this, void 0, void 0, function* () {
1741
- const sql = [
1742
- `${this.$constants('SHOW')}`,
1743
- `${this.$constants('COLUMNS')}`,
1744
- `${this.$constants('FROM')}`,
1745
- `\`${table.replace(/\`/g, '')}\``
1746
- ].join(' ');
1747
- const raw = yield this.queryStatement(sql);
1748
- const schemas = raw.map((r) => {
1749
- const schema = [];
1750
- schema.push(`${r.Field}`);
1751
- schema.push(`${r.Type}`);
1752
- if (r.Null === 'YES') {
1753
- schema.push(`NULL`);
1754
- }
1755
- if (r.Null === 'NO') {
1756
- schema.push(`NOT NULL`);
1757
- }
1758
- if (r.Key === 'PRI') {
1759
- schema.push(`PRIMARY KEY`);
1760
- }
1761
- if (r.Key === 'UNI') {
1762
- schema.push(`UNIQUE`);
1763
- }
1764
- if (r.Default) {
1765
- schema.push(`DEFAULT '${r.Default}'`);
1766
- }
1767
- if (r.Extra) {
1768
- schema.push(`${r.Extra.toUpperCase()}`);
1769
- }
1770
- return schema.join(' ');
1771
- });
1772
- return schemas;
1773
- });
1774
- }
1775
- /**
1776
- *
1777
- * show values in table
1778
- * @param {string=} table table name
1779
- * @return {Promise<Array>}
1780
- */
1781
- showValues(table = this.$state.get('TABLE_NAME')) {
1782
- return __awaiter(this, void 0, void 0, function* () {
1783
- const sql = [
1784
- `${this.$constants('SELECT')}`,
1785
- '*',
1786
- `${this.$constants('FROM')}`,
1787
- `\`${table.replace(/\`/g, '')}\``
1788
- ].join(' ');
1789
- const raw = yield this.queryStatement(sql);
1790
- const values = raw.map((value) => {
1791
- return `(${Object.values(value).map((v) => {
1792
- return v == null ? 'NULL' : `'${v}'`;
1793
- }).join(',')})`;
1794
- });
1795
- return values;
1796
- });
1797
- }
1798
- /**
1799
- *
1800
- * backup this database intro new database same server or to another server
1801
- * @param {Object} backupOptions
1802
- * @param {string} backup.database
1803
- * @param {object?} backup.to
1804
- * @param {string} backup.to.host
1805
- * @param {number} backup.to.port
1806
- * @param {string} backup.to.database
1807
- * @param {string} backup.to.username
1808
- * @param {string} backup.to.password
1809
-
1810
- * @return {Promise<boolean>}
1811
- */
1812
- backup({ database, to }) {
1813
- return __awaiter(this, void 0, void 0, function* () {
1814
- const tables = yield this.queryStatement('SHOW TABLES');
1815
- let backup = [];
1816
- for (const t of tables) {
1817
- const table = String(Object.values(t).shift());
1818
- const schemas = yield this.showSchemas(table);
1819
- const createTableSQL = [
1820
- `${this.$constants('CREATE_TABLE_NOT_EXISTS')}`,
1821
- `\`${database}.${table}\``,
1822
- `(${schemas.join(',')})`,
1823
- `${this.$constants('ENGINE')}`,
1824
- ];
1825
- const values = yield this.showValues(table);
1826
- let valueSQL = [];
1827
- if (values.length) {
1828
- const columns = yield this.showColumns(table);
1829
- valueSQL = [
1830
- `${this.$constants('INSERT')}`,
1831
- `\`${database}.${table}\``,
1832
- `(${columns.map((column) => `\`${column}\``).join(',')})`,
1833
- `${this.$constants('VALUES')} ${values.join(',')}`
1834
- ];
1835
- }
1836
- backup = [
1837
- ...backup,
1838
- {
1839
- table: createTableSQL.join(' '),
1840
- values: valueSQL.join(' '),
1841
- }
1842
- ];
1843
- }
1844
- if (to != null && Object.keys(to).length)
1845
- this.connection(to);
1846
- yield this.queryStatement(`${this.$constants('CREATE_DATABASE_NOT_EXISTS')} \`${database}\``);
1847
- for (const b of backup) {
1848
- yield this.queryStatement(b.table);
1849
- if (b.values) {
1850
- yield this.queryStatement(b.values);
1851
- }
1852
- }
1853
- return true;
1854
- });
1855
- }
1856
- /**
1857
- *
1858
- * backup database intro file
1859
- * @param {Object} backupOptions
1860
- * @param {string} backup.database
1861
- * @param {object?} backup.filePath
1862
- * @param {object?} backup.connection
1863
- * @param {string} backup.connection.host
1864
- * @param {number} backup.connection.port
1865
- * @param {string} backup.connection.database
1866
- * @param {string} backup.connection.username
1867
- * @param {string} backup.connection.password
1868
-
1869
- * @return {Promise<boolean>}
1870
- */
1871
- backupToFile({ filePath, database, connection }) {
1872
- var _a, _b;
1873
- return __awaiter(this, void 0, void 0, function* () {
1874
- const tables = yield this.queryStatement(this.$constants('SHOW_TABLES'));
1875
- let backup = [];
1876
- for (const t of tables) {
1877
- const table = String((_a = Object.values(t)) === null || _a === void 0 ? void 0 : _a.shift());
1878
- const schemas = yield this.showSchemas(table);
1879
- const createTableSQL = [
1880
- `${this.$constants('CREATE_TABLE_NOT_EXISTS')}`,
1881
- `\`${table}\``,
1882
- `(${schemas.join(',')})`,
1883
- `${this.$constants('ENGINE')};`,
1884
- ];
1885
- const values = yield this.showValues(table);
1886
- let valueSQL = [];
1887
- if (values.length) {
1888
- const columns = yield this.showColumns(table);
1889
- valueSQL = [
1890
- `${this.$constants('INSERT')}`,
1891
- `\`${table}\``,
1892
- `(${columns.map((column) => `\`${column}\``).join(',')})`,
1893
- `${this.$constants('VALUES')} ${values.join(',')};`
1894
- ];
1895
- }
1896
- backup = [
1897
- ...backup,
1898
- {
1899
- table: createTableSQL.join(' '),
1900
- values: valueSQL.join(' ')
1901
- }
1902
- ];
1903
- }
1904
- if (connection != null && ((_b = Object.keys(connection)) === null || _b === void 0 ? void 0 : _b.length))
1905
- this.connection(connection);
1906
- let sql = [
1907
- `SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";`,
1908
- `START TRANSACTION;`,
1909
- `SET time_zone = "+00:00";`,
1910
- `${this.$constants('CREATE_DATABASE_NOT_EXISTS')} \`${database}\`;`,
1911
- `USE \`${database}\`;`
1912
- ];
1913
- for (const b of backup) {
1914
- sql = [...sql, b.table];
1915
- if (b.values) {
1916
- sql = [...sql, b.values];
1917
- }
1918
- }
1919
- fs_1.default.writeFileSync(filePath, (0, sql_formatter_1.format)([...sql, 'COMMIT;'].join('\n'), {
1920
- language: 'spark',
1921
- tabWidth: 2,
1922
- keywordCase: 'upper',
1923
- linesBetweenQueries: 1,
1924
- }));
1925
- return;
1926
- });
1927
- }
1928
- /**
1929
- *
1930
- * fake data
1931
- * @param {number} rows number of rows
1932
- * @return {promise<any>}
1933
- */
1934
- faker(rows = 1) {
1935
- return __awaiter(this, void 0, void 0, function* () {
1936
- let data = [];
1937
- const sql = [
1938
- `${this.$constants('SHOW')}`,
1939
- `${this.$constants('FIELDS')}`,
1940
- `${this.$constants('FROM')}`,
1941
- `${this.$state.get('TABLE_NAME')}`
1942
- ].join(' ');
1943
- const fields = yield this.queryStatement(sql);
1944
- for (let row = 0; row < rows; row++) {
1945
- if (this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null) {
1946
- throw new Error("unknow this table");
1947
- }
1948
- let columnAndValue = {};
1949
- for (const { Field: field, Type: type } of fields) {
1950
- const passed = field.toLowerCase() === 'id' ||
1951
- field.toLowerCase() === '_id' ||
1952
- field.toLowerCase() === 'uuid';
1953
- if (passed)
1954
- continue;
1955
- columnAndValue = Object.assign(Object.assign({}, columnAndValue), { [field]: this.$utils.faker(type) });
1956
- }
1957
- data = [...data, columnAndValue];
1958
- }
1959
- const query = this._queryInsertMultiple(data);
1960
- this.$state.set('INSERT', [
1961
- `${this.$constants('INSERT')}`,
1962
- `${this.$state.get('TABLE_NAME')}`,
1963
- `${query}`
1964
- ].join(' '));
1965
- this.$state.set('SAVE', 'INSERT_MULTIPLE');
1966
- return this.save();
1967
- });
1968
- }
1969
- /**
1970
- *
1971
- * truncate of table
1972
- * @return {promise<boolean>}
1973
- */
1974
- truncate() {
1975
- return __awaiter(this, void 0, void 0, function* () {
1976
- const sql = [
1977
- `${this.$constants('TRUNCATE_TABLE')}`,
1978
- `${this.$state.get('TABLE_NAME')}`
1979
- ].join(' ');
1980
- yield this.queryStatement(sql);
1981
- return true;
1982
- });
1983
- }
1984
- /**
1985
- *
1986
- * drop of table
1987
- * @return {promise<boolean>}
1988
- */
1989
- drop() {
1990
- return __awaiter(this, void 0, void 0, function* () {
1991
- const sql = [
1992
- `${this.$constants('DROP_TABLE')}`,
1993
- `${this.$state.get('TABLE_NAME')}`
1994
- ].join(' ');
1995
- yield this.queryStatement(sql);
1996
- return true;
1997
- });
1998
- }
1999
- _queryWhereIsExists() {
2000
- var _a;
2001
- return ((_a = this.$state.get('WHERE')) === null || _a === void 0 ? void 0 : _a.includes(this.$constants('WHERE'))) || false;
2002
- }
2003
- _bindTableAndColumnInQueryWhere(column) {
2004
- return `${this.$state.get('TABLE_NAME')}.\`${column}\``;
2005
- }
2006
- _insertNotExists() {
2007
- return __awaiter(this, void 0, void 0, function* () {
2008
- if (!this.$state.get('WHERE'))
2009
- throw new Error("Can't insert not exists without where condition");
2010
- let sql = [
2011
- `${this.$constants('SELECT')}`,
2012
- `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
2013
- `*`,
2014
- `${this.$state.get('FROM')}`,
2015
- `${this.$state.get('TABLE_NAME')}`,
2016
- `${this.$state.get('WHERE')}`,
2017
- `${this.$constants('LIMIT')} 1)`,
2018
- `${this.$constants('AS')} 'exists'`
2019
- ].join(' ');
2020
- const [{ exists: result }] = yield this.queryStatement(sql);
2021
- const check = !!Number.parseInt(result);
2022
- switch (check) {
2023
- case false: {
2024
- const [result, id] = yield this.actionStatement({
2025
- sql: this.$state.get('INSERT'),
2026
- returnId: true
2027
- });
2028
- if (this.$state.get('VOID'))
2029
- return null;
2030
- if (result) {
2031
- const sql = [
2032
- `${this.$state.get('SELECT')}`,
2033
- `${this.$state.get('FROM')}`,
2034
- `${this.$state.get('TABLE_NAME')}`,
2035
- `${this.$constants('WHERE')} id = ${id}`
2036
- ].join(' ');
2037
- const data = yield this.queryStatement(sql);
2038
- return (data === null || data === void 0 ? void 0 : data.shift()) || null;
2039
- }
2040
- return null;
2041
- }
2042
- default: return null;
2043
- }
2044
- });
2045
- }
2046
- queryStatement(sql) {
2047
- return __awaiter(this, void 0, void 0, function* () {
2048
- if (this.$state.get('DEBUG'))
2049
- this.$utils.consoleDebug(sql);
2050
- const result = yield this.$pool.query(sql);
2051
- return result;
2052
- });
2053
- }
2054
- actionStatement({ sql, returnId = false }) {
2055
- return __awaiter(this, void 0, void 0, function* () {
2056
- if (this.$state.get('DEBUG'))
2057
- this.$utils.consoleDebug(sql);
2058
- if (returnId) {
2059
- const result = yield this.$pool.query(sql);
2060
- return [result.affectedRows, result.insertId];
2061
- }
2062
- const { affectedRows: result } = yield this.$pool.query(sql);
2063
- return result;
2064
- });
2065
- }
2066
- _create() {
2067
- return __awaiter(this, void 0, void 0, function* () {
2068
- const [result, id] = yield this.actionStatement({
2069
- sql: this.$state.get('INSERT'),
2070
- returnId: true
2071
- });
2072
- if (this.$state.get('VOID'))
2073
- return null;
2074
- if (result) {
2075
- const sql = [
2076
- `${this.$state.get('SELECT')}`,
2077
- `${this.$state.get('FROM')}`,
2078
- `${this.$state.get('TABLE_NAME')}`,
2079
- `${this.$constants('WHERE')} id = ${id}`
2080
- ].join(' ');
2081
- const data = yield this.queryStatement(sql);
2082
- const result = (data === null || data === void 0 ? void 0 : data.shift()) || null;
2083
- this.$state.set('RESULT', result);
2084
- return result;
2085
- }
2086
- return null;
2087
- });
2088
- }
2089
- _createMultiple() {
2090
- return __awaiter(this, void 0, void 0, function* () {
2091
- const [result, id] = yield this.actionStatement({
2092
- sql: this.$state.get('INSERT'),
2093
- returnId: true
2094
- });
2095
- if (this.$state.get('VOID'))
2096
- return null;
2097
- if (result) {
2098
- const arrayId = [...Array(result)].map((_, i) => i + id);
2099
- const sql = [
2100
- `${this.$state.get('SELECT')}`,
2101
- `${this.$state.get('FROM')}`,
2102
- `${this.$state.get('TABLE_NAME')}`,
2103
- `${this.$constants('WHERE')} id`,
2104
- `${this.$constants('IN')} (${arrayId})`
2105
- ].join(' ');
2106
- const data = yield this.queryStatement(sql);
2107
- const resultData = data || null;
2108
- this.$state.set('RESULT', resultData);
2109
- return resultData;
2110
- }
2111
- return null;
2112
- });
2113
- }
2114
- _updateOrInsert() {
2115
- return __awaiter(this, void 0, void 0, function* () {
2116
- if (!this.$state.get('WHERE')) {
2117
- throw new Error("Can't update or insert without where condition");
2118
- }
2119
- let sql = [
2120
- `${this.$constants('SELECT')}`,
2121
- `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
2122
- `*`,
2123
- `${this.$state.get('FROM')}`,
2124
- `${this.$state.get('TABLE_NAME')}`,
2125
- `${this.$state.get('WHERE')}`,
2126
- `${this.$constants('LIMIT')} 1)`,
2127
- `${this.$constants('AS')} 'exists'`
2128
- ].join(' ');
2129
- let check = false;
2130
- const [{ exists: result }] = yield this.queryStatement(sql);
2131
- check = !!parseInt(result);
2132
- switch (check) {
2133
- case false: {
2134
- const [result, id] = yield this.actionStatement({
2135
- sql: this.$state.get('INSERT'),
2136
- returnId: true
2137
- });
2138
- if (this.$state.get('VOID'))
2139
- return null;
2140
- if (result) {
2141
- const sql = [
2142
- `${this.$state.get('SELECT')}`,
2143
- `${this.$state.get('FROM')}`,
2144
- `${this.$state.get('TABLE_NAME')}`,
2145
- `${this.$constants('WHERE')} id = ${id}`
2146
- ].join(' ');
2147
- const data = yield this.queryStatement(sql);
2148
- const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'insert' }) || null;
2149
- this.$state.set('RESULT', resultData);
2150
- return resultData;
2151
- }
2152
- return null;
2153
- }
2154
- case true: {
2155
- const result = yield this.actionStatement({
2156
- sql: [
2157
- `${this.$state.get('UPDATE')}`,
2158
- `${this.$state.get('WHERE')}`
2159
- ].join(' ')
2160
- });
2161
- if (this.$state.get('VOID'))
2162
- return null;
2163
- if (result) {
2164
- const data = yield this.queryStatement([
2165
- `${this.$state.get('SELECT')}`,
2166
- `${this.$state.get('FROM')}`,
2167
- `${this.$state.get('TABLE_NAME')}`,
2168
- `${this.$state.get('WHERE')}`
2169
- ].join(' '));
2170
- if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2171
- for (const val of data) {
2172
- val.action_status = 'update';
2173
- }
2174
- return data || [];
2175
- }
2176
- return Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'update' }) || null;
2177
- }
2178
- return null;
2179
- }
2180
- default: {
2181
- return null;
2182
- }
2183
- }
2184
- });
2185
- }
2186
- _update(ignoreWhere = false) {
2187
- return __awaiter(this, void 0, void 0, function* () {
2188
- if (!this.$state.get('WHERE') && !ignoreWhere)
2189
- throw new Error("can't update without where condition");
2190
- const result = yield this.actionStatement({
2191
- sql: [
2192
- `${this.$state.get('UPDATE')}`, `${this.$state.get('WHERE')}`
2193
- ].join(' ')
2194
- });
2195
- if (this.$state.get('VOID'))
2196
- return null;
2197
- if (!result)
2198
- return null;
2199
- const sql = [
2200
- `${this.$state.get('SELECT')}`,
2201
- `${this.$state.get('FROM')}`,
2202
- `${this.$state.get('TABLE_NAME')}`,
2203
- `${this.$state.get('WHERE')}`
2204
- ].join(' ');
2205
- const data = yield this.queryStatement(sql);
2206
- if ((data === null || data === void 0 ? void 0 : data.length) > 1)
2207
- return data || [];
2208
- const res = (data === null || data === void 0 ? void 0 : data.shift()) || null;
2209
- this.$state.set('RESULT', res);
2210
- return res;
2211
- });
2212
- }
2213
- _hiddenColumn(data) {
2214
- var _a;
2215
- const hidden = this.$state.get('HIDDEN');
2216
- if ((_a = Object.keys(data)) === null || _a === void 0 ? void 0 : _a.length) {
2217
- hidden.forEach((column) => {
2218
- data.forEach((objColumn) => {
2219
- delete objColumn[column];
2220
- });
2221
- });
2222
- }
2223
- return data;
2224
- }
2225
- _queryUpdate(data) {
2226
- const values = Object.entries(data).map(([column, value]) => {
2227
- if (typeof value === 'string')
2228
- value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
2229
- return `${column} = ${value == null || value === 'NULL'
2230
- ? 'NULL'
2231
- : typeof value === 'string' && value.startsWith(this.$constants('RAW'))
2232
- ? `${this.$utils.covertBooleanToNumber(value)}`.replace(this.$constants('RAW'), '')
2233
- : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
2234
- });
2235
- return `${this.$constants('SET')} ${values}`;
2236
- }
2237
- _queryInsert(data) {
2238
- const columns = Object.keys(data).map((column) => `\`${column}\``);
2239
- const values = Object.values(data).map((value) => {
2240
- if (typeof value === 'string')
2241
- value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
2242
- return `${value == null || value === 'NULL'
2243
- ? 'NULL'
2244
- : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
2245
- });
2246
- return [
2247
- `(${columns})`,
2248
- `${this.$constants('VALUES')}`,
2249
- `(${values})`
2250
- ].join(' ');
2251
- }
2252
- _queryInsertMultiple(data) {
2253
- var _a;
2254
- let values = [];
2255
- for (let objects of data) {
2256
- const vals = Object.values(objects).map((value) => {
2257
- if (typeof value === 'string')
2258
- value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
2259
- return `${value == null || value === 'NULL'
2260
- ? 'NULL'
2261
- : typeof value === 'string' && value.includes(this.$constants('RAW'))
2262
- ? `${this.$utils.covertBooleanToNumber(value)}`.replace(this.$constants('RAW'), '')
2263
- : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
2264
- });
2265
- values.push(`(${vals.join(',')})`);
2266
- }
2267
- const columns = Object.keys((_a = [...data]) === null || _a === void 0 ? void 0 : _a.shift()).map((column) => `\`${column}\``);
2268
- return [
2269
- `(${columns})`,
2270
- `${this.$constants('VALUES')}`,
2271
- `${values.join(',')}`
2272
- ].join(' ');
2273
- }
2274
- _valueAndOperator(value, operator, useDefault = false) {
2275
- if (useDefault)
2276
- return [operator, '='];
2277
- if (operator == null)
2278
- throw new Error('bad arguments');
2279
- if (operator.toUpperCase() === this.$constants('LIKE')) {
2280
- operator = operator.toUpperCase();
2281
- }
2282
- return [value, operator];
2283
- }
2284
- _valueTrueFalse(value) {
2285
- if (value === true)
2286
- return 1;
2287
- if (value === false)
2288
- return 0;
2289
- return value;
2290
- }
2291
- _buildQuery() {
2292
- let sql = [];
2293
- while (true) {
2294
- if (this.$state.get('INSERT')) {
2295
- sql = [
2296
- this.$state.get('INSERT')
2297
- ];
2298
- break;
2299
- }
2300
- if (this.$state.get('UPDATE')) {
2301
- sql = [
2302
- this.$state.get('UPDATE'),
2303
- this.$state.get('WHERE')
2304
- ];
2305
- break;
2306
- }
2307
- if (this.$state.get('DELETE')) {
2308
- sql = [
2309
- this.$state.get('DELETE')
2310
- ];
2311
- break;
2312
- }
2313
- sql = [
2314
- this.$state.get('SELECT'),
2315
- this.$state.get('FROM'),
2316
- this.$state.get('TABLE_NAME'),
2317
- this.$state.get('JOIN'),
2318
- this.$state.get('WHERE'),
2319
- this.$state.get('GROUP_BY'),
2320
- this.$state.get('HAVING'),
2321
- this.$state.get('ORDER_BY'),
2322
- this.$state.get('LIMIT'),
2323
- this.$state.get('OFFSET')
2324
- ];
2325
- break;
2326
- }
2327
- return sql.filter(s => s !== '' || s == null).join(' ');
2328
- }
2329
- _initialConnection() {
2330
- this.$utils = utils_1.default;
2331
- this.$pool = (() => {
2332
- let pool = connection_1.Pool;
2333
- return {
2334
- query: (sql) => __awaiter(this, void 0, void 0, function* () { return yield pool.query(sql); }),
2335
- get: () => pool,
2336
- set: (newConnection) => {
2337
- pool = newConnection;
2338
- return;
2339
- }
2340
- };
2341
- })();
2342
- this.$logger = (() => {
2343
- let logger = [];
2344
- return {
2345
- get: () => logger,
2346
- set: (data) => {
2347
- logger = [...logger, data];
2348
- return;
2349
- },
2350
- check: (data) => logger.indexOf(data) != -1
2351
- };
2352
- })();
2353
- this.$constants = (name) => {
2354
- if (name == null)
2355
- return constants_1.CONSTANTS;
2356
- if (!constants_1.CONSTANTS.hasOwnProperty(name.toUpperCase()))
2357
- throw new Error(`not found constants : ${name}`);
2358
- return constants_1.CONSTANTS[name.toUpperCase()];
2359
- };
2360
- }
2361
- }
2362
- exports.Database = Database;
2363
- exports.default = Database;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ var __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.Builder = void 0;
27
+ const fs_1 = __importDefault(require("fs"));
28
+ const sql_formatter_1 = require("sql-formatter");
29
+ const AbstractBuilder_1 = require("./AbstractBuilder");
30
+ const utils_1 = require("../utils");
31
+ const constants_1 = require("../constants");
32
+ const DB_1 = require("./DB");
33
+ const connection_1 = require("../connection");
34
+ class Builder extends AbstractBuilder_1.AbstractBuilder {
35
+ constructor() {
36
+ super();
37
+ this._initialConnection();
38
+ }
39
+ /**
40
+ *
41
+ * @param {string} column
42
+ * @return {this}
43
+ */
44
+ pluck(column) {
45
+ this.$state.set('PLUCK', column);
46
+ return this;
47
+ }
48
+ /**
49
+ *
50
+ * @param {...string} columns
51
+ * @return {this} this
52
+ */
53
+ except(...columns) {
54
+ this.$state.set('EXCEPT', columns.length ? columns : ['id']);
55
+ return this;
56
+ }
57
+ /**
58
+ * data alaways will return void
59
+ * @return {this} this
60
+ */
61
+ void() {
62
+ this.$state.set('VOID', true);
63
+ return this;
64
+ }
65
+ /**
66
+ *
67
+ * @param {...string} columns show only colums selected
68
+ * @return {this} this
69
+ */
70
+ only(...columns) {
71
+ this.$state.set('ONLY', columns);
72
+ return this;
73
+ }
74
+ /**
75
+ *
76
+ * @param {string=} column [column=id]
77
+ * @return {this} this
78
+ */
79
+ distinct(column = 'id') {
80
+ this.$state.set('SELECT', [
81
+ `${this.$constants('SELECT')}`,
82
+ `${this.$constants('DISTINCT')}`,
83
+ `${column}`
84
+ ].join(' '));
85
+ return this;
86
+ }
87
+ /**
88
+ * select data form table
89
+ * @param {Array<string>} ...columns
90
+ * @return {this} this
91
+ */
92
+ select(...columns) {
93
+ let select = '*';
94
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
95
+ select = columns.map((column) => {
96
+ if (column.includes(this.$constants('RAW')))
97
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '').replace(/'/g, '');
98
+ return `\`${column}\``;
99
+ }).join(', ');
100
+ }
101
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${select}`);
102
+ return this;
103
+ }
104
+ selectRaw(...columns) {
105
+ let select = '*';
106
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
107
+ select = columns.map((column) => {
108
+ if (column.includes(this.$constants('RAW')))
109
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '').replace(/'/g, '');
110
+ return column;
111
+ }).join(', ');
112
+ }
113
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${select}`);
114
+ return this;
115
+ }
116
+ /**
117
+ * chunks data from array
118
+ * @param {number} chunk
119
+ * @return {this} this
120
+ */
121
+ chunk(chunk) {
122
+ this.$state.set('CHUNK', chunk);
123
+ return this;
124
+ }
125
+ /**
126
+ *
127
+ * @param {string | number | undefined | null | Boolean} condition when condition true will return query callback
128
+ * @return {this} this
129
+ */
130
+ when(condition, callback) {
131
+ if (condition)
132
+ callback(this);
133
+ return this;
134
+ }
135
+ /**
136
+ * if has 2 arguments default operator '='
137
+ * @param {string} column
138
+ * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
139
+ * @param {any?} value
140
+ * @return {this}
141
+ */
142
+ resetWhere() {
143
+ this.$state.set('WHERE', '');
144
+ return this;
145
+ }
146
+ /**
147
+ * if has 2 arguments default operator '='
148
+ * @param {string} column if arguments is object
149
+ * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
150
+ * @param {any?} value
151
+ * @return {this}
152
+ */
153
+ where(column, operator, value) {
154
+ if (typeof column === 'object' && column !== null && !Array.isArray(column)) {
155
+ return this.whereObject(column);
156
+ }
157
+ [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
158
+ value = this.$utils.escape(value);
159
+ value = this._valueTrueFalse(value);
160
+ this.$state.set('WHERE', [
161
+ this._queryWhereIsExists()
162
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
163
+ : `${this.$constants('WHERE')}`,
164
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
165
+ `${operator}`,
166
+ `${this._checkValueHasRaw(value)}`
167
+ ].join(' '));
168
+ return this;
169
+ }
170
+ /**
171
+ * where using object operator only '='
172
+ * @param {Object} columns
173
+ * @return {this}
174
+ */
175
+ whereObject(columns) {
176
+ for (const column in columns) {
177
+ const operator = '=';
178
+ const value = this.$utils.escape(columns[column]);
179
+ this.$state.set('WHERE', [
180
+ this._queryWhereIsExists()
181
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
182
+ : `${this.$constants('WHERE')}`,
183
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
184
+ `${operator}`,
185
+ `${this._checkValueHasRaw(value)}`
186
+ ].join(' '));
187
+ }
188
+ return this;
189
+ }
190
+ /**
191
+ * if has 2 arguments default operator '='
192
+ * @param {string} column
193
+ * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
194
+ * @param {any?} value
195
+ * @return {this}
196
+ */
197
+ orWhere(column, operator, value) {
198
+ [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
199
+ value = this.$utils.escape(value);
200
+ value = this._valueTrueFalse(value);
201
+ this.$state.set('WHERE', [
202
+ this._queryWhereIsExists()
203
+ ? `${this.$state.get('WHERE')} ${this.$constants('OR')}`
204
+ : `${this.$constants('WHERE')}`,
205
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
206
+ `${operator}`,
207
+ `${this._checkValueHasRaw(value)}`
208
+ ].join(' '));
209
+ return this;
210
+ }
211
+ /**
212
+ *
213
+ * @param {string} sql where column with raw sql
214
+ * @return {this} this
215
+ */
216
+ whereRaw(sql) {
217
+ this.$state.set('WHERE', [
218
+ this._queryWhereIsExists()
219
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
220
+ : `${this.$constants('WHERE')}`,
221
+ `${sql}`,
222
+ ].join(' '));
223
+ return this;
224
+ }
225
+ /**
226
+ *
227
+ * @param {string} query where column with raw sql
228
+ * @return {this} this
229
+ */
230
+ orWhereRaw(sql) {
231
+ this.$state.set('WHERE', [
232
+ this._queryWhereIsExists()
233
+ ? `${this.$state.get('WHERE')} ${this.$constants('OR')}`
234
+ : `${this.$constants('WHERE')}`,
235
+ `${sql}`,
236
+ ].join(' '));
237
+ return this;
238
+ }
239
+ /**
240
+ *
241
+ * @param {string} tableAndLocalKey
242
+ * @param {string?} tableAndForeignKey
243
+ * @return {this}
244
+ */
245
+ whereReference(tableAndLocalKey, tableAndForeignKey) {
246
+ this.$state.set('WHERE', [
247
+ this._queryWhereIsExists()
248
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
249
+ : `${this.$constants('WHERE')}`,
250
+ `${tableAndLocalKey} = ${tableAndForeignKey}`
251
+ ].join(' '));
252
+ return this;
253
+ }
254
+ /**
255
+ *
256
+ * where exists
257
+ * @param {string} sql
258
+ * @return {this}
259
+ */
260
+ whereExists(sql) {
261
+ this.$state.set('WHERE', [
262
+ this._queryWhereIsExists()
263
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
264
+ : `${this.$constants('WHERE')}`,
265
+ `${this.$constants('EXISTS')}`,
266
+ `(${sql})`
267
+ ].join(' '));
268
+ return this;
269
+ }
270
+ /**
271
+ *
272
+ * @param {number} id
273
+ * @return {this} this
274
+ */
275
+ whereId(id, column = 'id') {
276
+ this.$state.set('WHERE', [
277
+ this._queryWhereIsExists()
278
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
279
+ : `${this.$constants('WHERE')}`,
280
+ `${this._bindTableAndColumnInQueryWhere(column)} = ${id}`,
281
+ ].join(' '));
282
+ return this;
283
+ }
284
+ /**
285
+ *
286
+ * @param {string} email where using email
287
+ * @return {this}
288
+ */
289
+ whereEmail(email) {
290
+ const column = 'email';
291
+ this.$state.set('WHERE', [
292
+ this._queryWhereIsExists()
293
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
294
+ : `${this.$constants('WHERE')}`,
295
+ `${this._bindTableAndColumnInQueryWhere(column)} = ${this.$utils.escape(email)}`,
296
+ ].join(' '));
297
+ return this;
298
+ }
299
+ /**
300
+ *
301
+ * @param {number} userId
302
+ * @param {string?} column custom it *if column is not user_id
303
+ * @return {this}
304
+ */
305
+ whereUser(userId, column = 'user_id') {
306
+ this.$state.set('WHERE', [
307
+ this._queryWhereIsExists()
308
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
309
+ : `${this.$constants('WHERE')}`,
310
+ `${this._bindTableAndColumnInQueryWhere(column)} = ${this.$utils.escape(userId)}`,
311
+ ].join(' '));
312
+ return this;
313
+ }
314
+ /**
315
+ * using array value where in value in array
316
+ * @param {string} column
317
+ * @param {array} array
318
+ * @return {this}
319
+ */
320
+ whereIn(column, array) {
321
+ if (!Array.isArray(array))
322
+ throw new Error(`[${array}] is't array`);
323
+ if (!array.length)
324
+ return this;
325
+ const values = `${array.map((value) => this._checkValueHasRaw(this.$utils.escape(value))).join(',')}`;
326
+ this.$state.set('WHERE', [
327
+ this._queryWhereIsExists()
328
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
329
+ : `${this.$constants('WHERE')}`,
330
+ `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')}`,
331
+ `${this.$constants('IN')}`,
332
+ `(${values})`
333
+ ].join(' '));
334
+ return this;
335
+ }
336
+ /**
337
+ * or where in data using array values
338
+ * @param {string} column
339
+ * @param {array} array
340
+ * @return {this}
341
+ */
342
+ orWhereIn(column, array) {
343
+ if (!Array.isArray(array))
344
+ throw new Error(`[${array}] is't array`);
345
+ if (!array.length)
346
+ return this;
347
+ const values = `${array.map((value) => this._checkValueHasRaw(this.$utils.escape(value))).join(',')}`;
348
+ this.$state.set('WHERE', [
349
+ this._queryWhereIsExists()
350
+ ? `${this.$state.get('WHERE')} ${this.$constants('OR')}`
351
+ : `${this.$constants('WHERE')}`,
352
+ `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('IN')}`,
353
+ `${this.$constants('IN')}`,
354
+ `(${values})`
355
+ ].join(' '));
356
+ return this;
357
+ }
358
+ /**
359
+ * where not in data using array values
360
+ * @param {string} column
361
+ * @param {array} array
362
+ * @return {this}
363
+ */
364
+ whereNotIn(column, array) {
365
+ const sql = this.$state.get('WHERE');
366
+ if (!Array.isArray(array))
367
+ throw new Error(`[${array}] is't array`);
368
+ if (!array.length)
369
+ return this;
370
+ const values = `${array.map((value) => this._checkValueHasRaw(this.$utils.escape(value))).join(',')}`;
371
+ this.$state.set('WHERE', [
372
+ this._queryWhereIsExists()
373
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
374
+ : `${this.$constants('WHERE')}`,
375
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
376
+ `${this.$constants('NOT_IN')}`,
377
+ `(${values})`
378
+ ].join(' '));
379
+ return this;
380
+ }
381
+ /**
382
+ * where not in data using array values
383
+ * @param {string} column
384
+ * @param {array} array
385
+ * @return {this}
386
+ */
387
+ orWhereNotIn(column, array) {
388
+ if (!Array.isArray(array))
389
+ throw new Error(`[${array}] is't array`);
390
+ if (!array.length)
391
+ return this;
392
+ const values = `${array.map((value) => this._checkValueHasRaw(this.$utils.escape(value))).join(',')}`;
393
+ this.$state.set('WHERE', [
394
+ this._queryWhereIsExists()
395
+ ? `${this.$state.get('WHERE')} ${this.$constants('OR')}`
396
+ : `${this.$constants('WHERE')}`,
397
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
398
+ `${this.$constants('NOT_IN')}`,
399
+ `(${values})`
400
+ ].join(' '));
401
+ return this;
402
+ }
403
+ /**
404
+ * where sub query using sub query sql
405
+ * @param {string} column
406
+ * @param {string} subQuery
407
+ * @return {this}
408
+ */
409
+ whereSubQuery(column, subQuery) {
410
+ this.$state.set('WHERE', [
411
+ this._queryWhereIsExists()
412
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
413
+ : `${this.$constants('WHERE')}`,
414
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
415
+ `${this.$constants('IN')}`,
416
+ `(${this.$utils.escape(subQuery)})`
417
+ ].join(' '));
418
+ return this;
419
+ }
420
+ /**
421
+ * where not sub query using sub query sql
422
+ * @param {string} column
423
+ * @param {string} subQuery
424
+ * @return {this}
425
+ */
426
+ whereNotSubQuery(column, subQuery) {
427
+ this.$state.set('WHERE', [
428
+ this._queryWhereIsExists()
429
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
430
+ : `${this.$constants('WHERE')}`,
431
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
432
+ `${this.$constants('NOT_IN')}`,
433
+ `(${this.$utils.escape(subQuery)})`
434
+ ].join(' '));
435
+ return this;
436
+ }
437
+ /**
438
+ * or where not sub query using query sql
439
+ * @param {string} column
440
+ * @param {string} subQuery
441
+ * @return {this}
442
+ */
443
+ orWhereSubQuery(column, subQuery) {
444
+ this.$state.set('WHERE', [
445
+ this._queryWhereIsExists()
446
+ ? `${this.$state.get('WHERE')} ${this.$constants('OR')}`
447
+ : `${this.$constants('WHERE')}`,
448
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
449
+ `${this.$constants('IN')}`,
450
+ `(${this.$utils.escape(subQuery)})`
451
+ ].join(' '));
452
+ return this;
453
+ }
454
+ /**
455
+ * or where not sub query using query sql
456
+ * @param {string} column
457
+ * @param {string} subQuery
458
+ * @return {this}
459
+ */
460
+ orWhereNotSubQuery(column, subQuery) {
461
+ this.$state.set('WHERE', [
462
+ this._queryWhereIsExists()
463
+ ? `${this.$state.get('WHERE')} ${this.$constants('OR')}`
464
+ : `${this.$constants('WHERE')}`,
465
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
466
+ `${this.$constants('NOT_IN')}`,
467
+ `(${this.$utils.escape(subQuery)})`
468
+ ].join(' '));
469
+ return this;
470
+ }
471
+ /**
472
+ * where between using [value1, value2]
473
+ * @param {string} column
474
+ * @param {array} array
475
+ * @return {this}
476
+ */
477
+ whereBetween(column, array) {
478
+ if (!Array.isArray(array))
479
+ throw new Error("Value is't array");
480
+ if (!array.length)
481
+ return this;
482
+ const [value1, value2] = array;
483
+ this.$state.set('WHERE', [
484
+ this._queryWhereIsExists()
485
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
486
+ : `${this.$constants('WHERE')}`,
487
+ `${this._bindTableAndColumnInQueryWhere(column)} ${this.$constants('BETWEEN')}`,
488
+ `'${this.$utils.escape(value1)}' ${this.$constants('AND')} '${this.$utils.escape(value2)}'`
489
+ ].join(' '));
490
+ return this;
491
+ }
492
+ /**
493
+ * where null using NULL
494
+ * @param {string} column
495
+ * @return {this}
496
+ */
497
+ whereNull(column) {
498
+ this.$state.set('WHERE', [
499
+ this._queryWhereIsExists()
500
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
501
+ : `${this.$constants('WHERE')}`,
502
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
503
+ `${this.$constants('IS_NULL')}`
504
+ ].join(' '));
505
+ return this;
506
+ }
507
+ /**
508
+ * where not null using NULL
509
+ * @param {string} column
510
+ * @return {this}
511
+ */
512
+ whereNotNull(column) {
513
+ this.$state.set('WHERE', [
514
+ this._queryWhereIsExists()
515
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
516
+ : `${this.$constants('WHERE')}`,
517
+ `${this._bindTableAndColumnInQueryWhere(column)}`,
518
+ `${this.$constants('IS_NOT_NULL')}`
519
+ ].join(' '));
520
+ return this;
521
+ }
522
+ /**
523
+ * where sensitive (uppercase, lowercase)
524
+ * @param {string} column
525
+ * @param {string?} operator = < > != !< !>
526
+ * @param {any?} value
527
+ * @return {this}
528
+ */
529
+ whereSensitive(column, operator, value) {
530
+ [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
531
+ value = this.$utils.escape(value);
532
+ value = this._valueTrueFalse(value);
533
+ this.$state.set('WHERE', [
534
+ this._queryWhereIsExists()
535
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
536
+ : `${this.$constants('WHERE')}`,
537
+ `BINARY ${this._bindTableAndColumnInQueryWhere(column)}`,
538
+ `${operator}`,
539
+ `${this._checkValueHasRaw(this.$utils.escape(value))}`
540
+ ].join(' '));
541
+ return this;
542
+ }
543
+ /**
544
+ * where Strict (uppercase, lowercase)
545
+ * @param {string} column
546
+ * @param {string?} operator = < > != !< !>
547
+ * @param {any?} value
548
+ * @return {this}
549
+ */
550
+ whereStrict(column, operator, value) {
551
+ return this.whereSensitive(column, operator, value);
552
+ }
553
+ /**
554
+ * where group query
555
+ * @param {function} callback callback query
556
+ * @return {this}
557
+ */
558
+ whereQuery(callback) {
559
+ var _a;
560
+ const db = new DB_1.DB((_a = this.$state.get('TABLE_NAME')) === null || _a === void 0 ? void 0 : _a.replace(/`/g, ''));
561
+ const repository = callback(db);
562
+ if (!(repository instanceof DB_1.DB)) {
563
+ throw new Error(`unknown callback query: '[${repository}]'`);
564
+ }
565
+ const where = (repository === null || repository === void 0 ? void 0 : repository.$state.get('WHERE')) || '';
566
+ if (where === '')
567
+ return this;
568
+ const query = where.replace('WHERE', '');
569
+ this.$state.set('WHERE', [
570
+ this._queryWhereIsExists()
571
+ ? `${this.$state.get('WHERE')} ${this.$constants('AND')}`
572
+ : `${this.$constants('WHERE')}`,
573
+ `(${query})`
574
+ ].join(' '));
575
+ return this;
576
+ }
577
+ /**
578
+ * select by cases
579
+ * @param {array} cases array object [{ when : 'id < 7' , then : 'id is than under 7'}]
580
+ * @param {string} as
581
+ * @return {this}
582
+ */
583
+ case(cases, as) {
584
+ let query = [this.$constants('CASE')];
585
+ for (let i = 0; i < cases.length; i++) {
586
+ const c = cases[i];
587
+ if (cases.length - 1 === i) {
588
+ if (c.then == null)
589
+ throw new Error(`can't find then condition`);
590
+ query = [
591
+ ...query,
592
+ `${this.$constants('ELSE')} '${c.then}'`,
593
+ `${this.$constants('END')}`
594
+ ];
595
+ continue;
596
+ }
597
+ if (c.when == null)
598
+ throw new Error(`can't find when condition`);
599
+ if (c.then == null)
600
+ throw new Error(`can't find then condition`);
601
+ query = [
602
+ ...query,
603
+ `${this.$constants('WHEN')} ${c.when} ${this.$constants('THEN')} '${c.then}'`
604
+ ];
605
+ }
606
+ if (query.length <= 1)
607
+ return this;
608
+ this.$state.set('SELECT', `${this.$state.get('SELECT')}, ${query.join(' ')} ${this.$constants('AS')} ${as}`);
609
+ return this;
610
+ }
611
+ /**
612
+ *
613
+ * @param {string} pk talbe.pk
614
+ * @param {string} fk talbe.fk
615
+ * @return {this}
616
+ */
617
+ join(pk, fk) {
618
+ var _a;
619
+ const table = (_a = fk.split('.')) === null || _a === void 0 ? void 0 : _a.shift();
620
+ if (this.$state.get('JOIN')) {
621
+ this.$state.set('JOIN', [
622
+ `${this.$state.get('JOIN')}`,
623
+ `${this.$constants('INNER_JOIN')}`,
624
+ `${table} ${this.$constants('ON')} ${pk} = ${fk}`
625
+ ].join(' '));
626
+ return this;
627
+ }
628
+ this.$state.set('JOIN', [
629
+ `${this.$constants('INNER_JOIN')}`,
630
+ `${table} ${this.$constants('ON')} ${pk} = ${fk}`
631
+ ].join(' '));
632
+ return this;
633
+ }
634
+ /**
635
+ *
636
+ * @param {string} pk talbe.pk
637
+ * @param {string} fk talbe.fk
638
+ * @return {this}
639
+ */
640
+ rightJoin(pk, fk) {
641
+ var _a;
642
+ const table = (_a = fk.split('.')) === null || _a === void 0 ? void 0 : _a.shift();
643
+ if (this.$state.get('JOIN')) {
644
+ this.$state.set('JOIN', [
645
+ `${this.$state.get('JOIN')}`,
646
+ `${this.$constants('RIGHT_JOIN')}`,
647
+ `${table} ${this.$constants('ON')} ${pk} = ${fk}`
648
+ ].join(' '));
649
+ return this;
650
+ }
651
+ this.$state.set('JOIN', [
652
+ `${this.$constants('RIGHT_JOIN')}`,
653
+ `${table} ${this.$constants('ON')} ${pk} = ${fk}`
654
+ ].join(' '));
655
+ return this;
656
+ }
657
+ /**
658
+ *
659
+ * @param {string} pk talbe.pk
660
+ * @param {string} fk talbe.fk
661
+ * @return {this}
662
+ */
663
+ leftJoin(pk, fk) {
664
+ var _a;
665
+ const table = (_a = fk.split('.')) === null || _a === void 0 ? void 0 : _a.shift();
666
+ if (this.$state.get('JOIN')) {
667
+ this.$state.set('JOIN', [
668
+ `${this.$state.get('JOIN')}`,
669
+ `${this.$constants('LEFT_JOIN')}`,
670
+ `${table} ${this.$constants('ON')} ${pk} = ${fk}`
671
+ ].join(' '));
672
+ return this;
673
+ }
674
+ this.$state.set('JOIN', [
675
+ `${this.$constants('LEFT_JOIN')}`,
676
+ `${table} ${this.$constants('ON')} ${pk} = ${fk}`
677
+ ].join(' '));
678
+ return this;
679
+ }
680
+ /**
681
+ *
682
+ * @param {string} pk talbe.pk
683
+ * @param {string} fk talbe.fk
684
+ * @return {this}
685
+ */
686
+ crossJoin(pk, fk) {
687
+ var _a;
688
+ const table = (_a = fk.split('.')) === null || _a === void 0 ? void 0 : _a.shift();
689
+ if (this.$state.get('JOIN')) {
690
+ this.$state.set('JOIN', [
691
+ `${this.$state.get('JOIN')}`,
692
+ `${this.$constants('CROSS_JOIN')}`,
693
+ `${table} ${this.$constants('ON')} ${pk} = ${fk}`
694
+ ].join(' '));
695
+ return this;
696
+ }
697
+ this.$state.set('JOIN', [
698
+ `${this.$constants('CROSS_JOIN')}`,
699
+ `${table} ${this.$constants('ON')} ${pk} = ${fk}`
700
+ ].join(' '));
701
+ return this;
702
+ }
703
+ /**
704
+ * sort the result in ASC or DESC order.
705
+ * @param {string} column
706
+ * @param {string?} order [order=asc] asc, desc
707
+ * @return {this}
708
+ */
709
+ orderBy(column, order = this.$constants('ASC')) {
710
+ if (typeof column !== 'string')
711
+ return this;
712
+ if (column.includes(this.$constants('RAW'))) {
713
+ column = column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
714
+ this.$state.set('ORDER_BY', [
715
+ `${this.$constants('ORDER_BY')}`,
716
+ `${column} ${order.toUpperCase()}`
717
+ ].join(' '));
718
+ return this;
719
+ }
720
+ this.$state.set('ORDER_BY', [
721
+ `${this.$constants('ORDER_BY')}`,
722
+ `\`${column}\` ${order.toUpperCase()}`
723
+ ].join(' '));
724
+ return this;
725
+ }
726
+ /**
727
+ * sort the result in ASC or DESC order. can using with raw query
728
+ * @param {string} column
729
+ * @param {string?} order [order=asc] asc, desc
730
+ * @return {this}
731
+ */
732
+ orderByRaw(column, order = this.$constants('ASC')) {
733
+ if (column.includes(this.$constants('RAW'))) {
734
+ column = column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
735
+ }
736
+ this.$state.set('ORDER_BY', [
737
+ `${this.$constants('ORDER_BY')}`,
738
+ `${column} ${order.toUpperCase()}`
739
+ ].join(' '));
740
+ return this;
741
+ }
742
+ /**
743
+ * sort the result in using DESC for order by.
744
+ * @param {string?} columns [column=id]
745
+ * @return {this}
746
+ */
747
+ latest(...columns) {
748
+ let orderByDefault = 'id';
749
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
750
+ orderByDefault = columns.map(column => {
751
+ if (column.includes(this.$constants('RAW')))
752
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
753
+ return `\`${column}\``;
754
+ }).join(', ');
755
+ }
756
+ this.$state.set('ORDER_BY', [
757
+ `${this.$constants('ORDER_BY')}`,
758
+ `${orderByDefault} ${this.$constants('DESC')}`
759
+ ].join(' '));
760
+ return this;
761
+ }
762
+ /**
763
+ * sort the result in using DESC for order by. can using with raw query
764
+ * @param {string?} columns [column=id]
765
+ * @return {this}
766
+ */
767
+ latestRaw(...columns) {
768
+ let orderByDefault = 'id';
769
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
770
+ orderByDefault = columns.map(column => {
771
+ if (column.includes(this.$constants('RAW')))
772
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
773
+ return column;
774
+ }).join(', ');
775
+ }
776
+ this.$state.set('ORDER_BY', [
777
+ `${this.$constants('ORDER_BY')}`,
778
+ `${orderByDefault} ${this.$constants('DESC')}`
779
+ ].join(' '));
780
+ return this;
781
+ }
782
+ /**
783
+ * sort the result in using ASC for order by.
784
+ * @param {string?} columns [column=id]
785
+ * @return {this}
786
+ */
787
+ oldest(...columns) {
788
+ let orderByDefault = 'id';
789
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
790
+ orderByDefault = columns.map(column => {
791
+ if (column.includes(this.$constants('RAW')))
792
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
793
+ return `\`${column}\``;
794
+ }).join(', ');
795
+ }
796
+ this.$state.set('ORDER_BY', [
797
+ `${this.$constants('ORDER_BY')}`,
798
+ `${orderByDefault} ${this.$constants('ASC')}`
799
+ ].join(' '));
800
+ return this;
801
+ }
802
+ /**
803
+ * sort the result in using ASC for order by. can using with raw query
804
+ * @param {string?} columns [column=id]
805
+ * @return {this}
806
+ */
807
+ oldestRaw(...columns) {
808
+ let orderByDefault = 'id';
809
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
810
+ orderByDefault = columns.map(column => {
811
+ if (column.includes(this.$constants('RAW')))
812
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
813
+ return column;
814
+ }).join(', ');
815
+ }
816
+ this.$state.set('ORDER_BY', [
817
+ `${this.$constants('ORDER_BY')}`,
818
+ `${orderByDefault} ${this.$constants('ASC')}`
819
+ ].join(' '));
820
+ return this;
821
+ }
822
+ /**
823
+ *
824
+ * @param {string?} columns [column=id]
825
+ * @return {this}
826
+ */
827
+ groupBy(...columns) {
828
+ let groupBy = 'id';
829
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
830
+ groupBy = columns.map(column => {
831
+ if (column.includes(this.$constants('RAW')))
832
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
833
+ return `\`${column}\``;
834
+ }).join(', ');
835
+ }
836
+ this.$state.set('GROUP_BY', `${this.$constants('GROUP_BY')} ${groupBy}`);
837
+ return this;
838
+ }
839
+ /**
840
+ *
841
+ * @param {string?} columns [column=id]
842
+ * @return {this}
843
+ */
844
+ groupByRaw(...columns) {
845
+ let groupBy = 'id';
846
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
847
+ groupBy = columns.map(column => {
848
+ if (column.includes(this.$constants('RAW')))
849
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
850
+ return column;
851
+ }).join(', ');
852
+ }
853
+ this.$state.set('GROUP_BY', `${this.$constants('GROUP_BY')} ${groupBy}`);
854
+ return this;
855
+ }
856
+ /**
857
+ *
858
+ * @param {string} condition
859
+ * @return {this}
860
+ */
861
+ having(condition) {
862
+ if (condition.includes(this.$constants('RAW'))) {
863
+ condition = condition === null || condition === void 0 ? void 0 : condition.replace(this.$constants('RAW'), '');
864
+ this.$state.set('HAVING', `${this.$constants('HAVING')} ${condition}`);
865
+ return this;
866
+ }
867
+ this.$state.set('HAVING', `${this.$constants('HAVING')} \`${condition}\``);
868
+ return this;
869
+ }
870
+ /**
871
+ *
872
+ * @param {string} condition
873
+ * @return {this}
874
+ */
875
+ havingRaw(condition) {
876
+ if (condition.includes(this.$constants('RAW'))) {
877
+ condition = condition === null || condition === void 0 ? void 0 : condition.replace(this.$constants('RAW'), '');
878
+ }
879
+ this.$state.set('HAVING', `${this.$constants('HAVING')} ${condition}`);
880
+ return this;
881
+ }
882
+ /**
883
+ * sort the result in random order.
884
+ * @return {this}
885
+ */
886
+ random() {
887
+ this.$state.set('ORDER_BY', `${this.$constants('ORDER_BY')} ${this.$constants('RAND')}`);
888
+ return this;
889
+ }
890
+ /**
891
+ * sort the result in random order.
892
+ * @return {this}
893
+ */
894
+ inRandom() {
895
+ return this.random();
896
+ }
897
+ /**
898
+ * limit data
899
+ * @param {number=} number [number=1]
900
+ * @return {this}
901
+ */
902
+ limit(number = 1) {
903
+ this.$state.set('LIMIT', `${this.$constants('LIMIT')} ${number}`);
904
+ return this;
905
+ }
906
+ /**
907
+ * limit data
908
+ * @param {number=} number [number=1]
909
+ * @return {this}
910
+ */
911
+ take(number = 1) {
912
+ return this.limit(number);
913
+ }
914
+ /**
915
+ *
916
+ * @param {number=} number [number=1]
917
+ * @return {this}
918
+ */
919
+ offset(number = 1) {
920
+ this.$state.set('OFFSET', `${this.$constants('OFFSET')} ${number}`);
921
+ if (!this.$state.get('LIMIT'))
922
+ this.$state.set('LIMIT', `${this.$constants('LIMIT')} ${number}`);
923
+ return this;
924
+ }
925
+ /**
926
+ *
927
+ * @param {number=} number [number=1]
928
+ * @return {this}
929
+ */
930
+ skip(number = 1) {
931
+ return this.offset(number);
932
+ }
933
+ /**
934
+ *
935
+ * @param {...string} columns
936
+ * @return {this} this
937
+ */
938
+ hidden(...columns) {
939
+ this.$state.set('HIDDEN', columns);
940
+ return this;
941
+ }
942
+ /**
943
+ *
944
+ * update data in the database
945
+ * @param {object} data
946
+ * @return {this} this
947
+ */
948
+ update(data) {
949
+ const query = this._queryUpdate(data);
950
+ this.$state.set('UPDATE', [
951
+ `${this.$constants('UPDATE')}`,
952
+ `${this.$state.get('TABLE_NAME')}`,
953
+ `${query}`
954
+ ].join(' '));
955
+ this.$state.set('SAVE', 'UPDATE');
956
+ return this;
957
+ }
958
+ /**
959
+ *
960
+ * insert data into the database
961
+ * @param {object} data
962
+ * @return {this} this
963
+ */
964
+ insert(data) {
965
+ const query = this._queryInsert(data);
966
+ this.$state.set('INSERT', [
967
+ `${this.$constants('INSERT')}`,
968
+ `${this.$state.get('TABLE_NAME')}`,
969
+ `${query}`
970
+ ].join(' '));
971
+ this.$state.set('SAVE', 'INSERT');
972
+ return this;
973
+ }
974
+ /**
975
+ *
976
+ * insert data into the database
977
+ * @param {object} data
978
+ * @return {this} this
979
+ */
980
+ create(data) {
981
+ const query = this._queryInsert(data);
982
+ this.$state.set('INSERT', [
983
+ `${this.$constants('INSERT')}`,
984
+ `${this.$state.get('TABLE_NAME')}`,
985
+ `${query}`
986
+ ].join(' '));
987
+ this.$state.set('SAVE', 'INSERT');
988
+ return this;
989
+ }
990
+ /**
991
+ *
992
+ * insert muliple data into the database
993
+ * @param {array} data create multiple data
994
+ * @return {this} this this
995
+ */
996
+ createMultiple(data) {
997
+ const query = this._queryInsertMultiple(data);
998
+ this.$state.set('INSERT', [
999
+ `${this.$constants('INSERT')}`,
1000
+ `${this.$state.get('TABLE_NAME')}`,
1001
+ `${query}`
1002
+ ].join(' '));
1003
+ this.$state.set('SAVE', 'INSERT_MULTIPLE');
1004
+ return this;
1005
+ }
1006
+ /**
1007
+ *
1008
+ * insert muliple data into the database
1009
+ * @param {array} data create multiple data
1010
+ * @return {this} this this
1011
+ */
1012
+ insertMultiple(data) {
1013
+ const query = this._queryInsertMultiple(data);
1014
+ this.$state.set('INSERT', [
1015
+ `${this.$constants('INSERT')}`,
1016
+ `${this.$state.get('TABLE_NAME')}`,
1017
+ `${query}`
1018
+ ].join(' '));
1019
+ this.$state.set('SAVE', 'INSERT_MULTIPLE');
1020
+ return this;
1021
+ }
1022
+ /**
1023
+ *
1024
+ * @return {string} return sql query
1025
+ */
1026
+ toString() {
1027
+ return this._buildQuery();
1028
+ }
1029
+ /**
1030
+ *
1031
+ * @return {string} return sql query
1032
+ */
1033
+ toSQL() {
1034
+ return this._buildQuery();
1035
+ }
1036
+ /**
1037
+ *
1038
+ * @param {boolean} debug debug sql statements
1039
+ * @return {this} this this
1040
+ */
1041
+ debug(debug = true) {
1042
+ this.$state.set('DEBUG', debug);
1043
+ return this;
1044
+ }
1045
+ /**
1046
+ *
1047
+ * @param {boolean} debug debug sql statements
1048
+ * @return {this} this this
1049
+ */
1050
+ dd(debug = true) {
1051
+ this.$state.set('DEBUG', debug);
1052
+ return this;
1053
+ }
1054
+ /**
1055
+ * hook function when execute returned result to callback function
1056
+ * @param {Function} func function for callback result
1057
+ * @return {this}
1058
+ */
1059
+ hook(func) {
1060
+ if (typeof func !== "function")
1061
+ throw new Error(`this '${func}' is not a function`);
1062
+ this.$state.set('HOOK', [...this.$state.get('HOOK'), func]);
1063
+ return this;
1064
+ }
1065
+ /**
1066
+ * hook function when execute returned result to callback function
1067
+ * @param {Function} func function for callback result
1068
+ * @return {this}
1069
+ */
1070
+ before(func) {
1071
+ if (typeof func !== "function")
1072
+ throw new Error(`this '${func}' is not a function`);
1073
+ this.$state.set('HOOK', [...this.$state.get('HOOK'), func]);
1074
+ return this;
1075
+ }
1076
+ /**
1077
+ *
1078
+ * @param {object} data create not exists data
1079
+ * @return {this} this this
1080
+ */
1081
+ createNotExists(data) {
1082
+ const query = this._queryInsert(data);
1083
+ this.$state.set('INSERT', [
1084
+ `${this.$constants('INSERT')}`,
1085
+ `${this.$state.get('TABLE_NAME')}`,
1086
+ `${query}`
1087
+ ].join(' '));
1088
+ this.$state.set('SAVE', 'INSERT_NOT_EXISTS');
1089
+ return this;
1090
+ }
1091
+ /**
1092
+ *
1093
+ * @param {object} data insert not exists data
1094
+ * @return {this} this this
1095
+ */
1096
+ insertNotExists(data) {
1097
+ this.createNotExists(data);
1098
+ return this;
1099
+ }
1100
+ /**
1101
+ *
1102
+ * check data if exists if exists then return result. if not exists insert data
1103
+ * @param {object} data insert data
1104
+ * @return {this} this this
1105
+ */
1106
+ createOrSelect(data) {
1107
+ const queryInsert = this._queryInsert(data);
1108
+ this.$state.set('INSERT', [
1109
+ `${this.$constants('INSERT')}`,
1110
+ `${this.$state.get('TABLE_NAME')}`,
1111
+ `${queryInsert}`
1112
+ ].join(' '));
1113
+ this.$state.set('SAVE', 'INSERT_OR_SELECT');
1114
+ return this;
1115
+ }
1116
+ /**
1117
+ *
1118
+ * check data if exists if exists then update. if not exists insert
1119
+ * @param {object} data insert or update data
1120
+ * @return {this} this this
1121
+ */
1122
+ insertOrSelect(data) {
1123
+ this.createOrSelect(data);
1124
+ return this;
1125
+ }
1126
+ /**
1127
+ *
1128
+ * check data if exists if exists then update. if not exists insert
1129
+ * @param {object} data insert or update data
1130
+ * @return {this} this this
1131
+ */
1132
+ updateOrCreate(data) {
1133
+ const queryUpdate = this._queryUpdate(data);
1134
+ const queryInsert = this._queryInsert(data);
1135
+ this.$state.set('INSERT', [
1136
+ `${this.$constants('INSERT')}`,
1137
+ `${this.$state.get('TABLE_NAME')}`,
1138
+ `${queryInsert}`
1139
+ ].join(' '));
1140
+ this.$state.set('UPDATE', [
1141
+ `${this.$constants('UPDATE')}`,
1142
+ `${this.$state.get('TABLE_NAME')}`,
1143
+ `${queryUpdate}`
1144
+ ].join(' '));
1145
+ this.$state.set('SAVE', 'UPDATE_OR_INSERT');
1146
+ return this;
1147
+ }
1148
+ /**
1149
+ *
1150
+ * check data if exists if exists then update. if not exists insert
1151
+ * @param {object} data insert or update data
1152
+ * @return {this} this this
1153
+ */
1154
+ updateOrInsert(data) {
1155
+ this.updateOrCreate(data);
1156
+ return this;
1157
+ }
1158
+ /**
1159
+ *
1160
+ * check data if exists if exists then update. if not exists insert
1161
+ * @param {object} data insert or update data
1162
+ * @return {this} this this
1163
+ */
1164
+ insertOrUpdate(data) {
1165
+ this.updateOrCreate(data);
1166
+ return this;
1167
+ }
1168
+ /**
1169
+ *
1170
+ * check data if exists if exists then update. if not exists insert
1171
+ * @param {object} data create or update data
1172
+ * @return {this} this this
1173
+ */
1174
+ createOrUpdate(data) {
1175
+ this.updateOrCreate(data);
1176
+ return this;
1177
+ }
1178
+ /**
1179
+ *
1180
+ * @param {Object} options options for connection database with credentials
1181
+ * @param {string} option.host
1182
+ * @param {number} option.port
1183
+ * @param {string} option.database
1184
+ * @param {string} option.user
1185
+ * @param {string} option.password
1186
+ * @return {this} this
1187
+ */
1188
+ connection(options) {
1189
+ const { host, port, database, username: user, password } = options, others = __rest(options, ["host", "port", "database", "username", "password"]);
1190
+ const pool = new connection_1.PoolConnection(Object.assign({ host,
1191
+ port,
1192
+ database,
1193
+ user,
1194
+ password }, others));
1195
+ this.$pool.set(pool.connection());
1196
+ return this;
1197
+ }
1198
+ /**
1199
+ *
1200
+ * @param {Function} pool pool connection database
1201
+ * @return {this} this
1202
+ */
1203
+ pool(pool) {
1204
+ if (!(pool === null || pool === void 0 ? void 0 : pool.hasOwnProperty('query'))) {
1205
+ throw new Error('pool must have a query property');
1206
+ }
1207
+ this.$pool.set(pool);
1208
+ return this;
1209
+ }
1210
+ /**
1211
+ * make sure this connection has same transaction in pool connection
1212
+ * @param {object} connection pool database
1213
+ * @return {this} this
1214
+ */
1215
+ bind(connection) {
1216
+ if (!(connection === null || connection === void 0 ? void 0 : connection.hasOwnProperty('query'))) {
1217
+ throw new Error('connection must have a query property');
1218
+ }
1219
+ if (typeof connection.query !== 'function') {
1220
+ throw new Error('connection must have a query function');
1221
+ }
1222
+ this.$pool.set(connection);
1223
+ return this;
1224
+ }
1225
+ /**
1226
+ * exceptColumns for method except
1227
+ * @return {promise<string>} string
1228
+ */
1229
+ exceptColumns() {
1230
+ return __awaiter(this, void 0, void 0, function* () {
1231
+ const sql = [
1232
+ `${this.$constants('SHOW')}`,
1233
+ `${this.$constants('COLUMNS')}`,
1234
+ `${this.$constants('FROM')}`,
1235
+ `${this.$state.get('TABLE_NAME')}`
1236
+ ].join(' ');
1237
+ const rawColumns = yield this.queryStatement(sql);
1238
+ const columns = rawColumns.map((column) => column.Field);
1239
+ const removeExcept = columns.filter((column) => !this.$state.get('EXCEPT').includes(column));
1240
+ return removeExcept.join(', ');
1241
+ });
1242
+ }
1243
+ /**
1244
+ * execute sql statements with raw sql query
1245
+ * @param {string} sql sql execute return data
1246
+ * @return {promise<any>}
1247
+ */
1248
+ rawQuery(sql) {
1249
+ return __awaiter(this, void 0, void 0, function* () {
1250
+ return yield this.queryStatement(sql);
1251
+ });
1252
+ }
1253
+ /**
1254
+ *
1255
+ * plus value then update
1256
+ * @param {string} column
1257
+ * @param {number} value
1258
+ * @return {promise<any>}
1259
+ */
1260
+ increment(column = 'id', value = 1) {
1261
+ return __awaiter(this, void 0, void 0, function* () {
1262
+ const query = `${this.$constants('SET')} ${column} = ${column} + ${value}`;
1263
+ this.$state.set('UPDATE', [
1264
+ `${this.$constants('UPDATE')}`,
1265
+ `${this.$state.get('TABLE_NAME')}`,
1266
+ `${query}`
1267
+ ].join(' '));
1268
+ return yield this._update(true);
1269
+ });
1270
+ }
1271
+ /**
1272
+ *
1273
+ * minus value then update
1274
+ * @param {string} column
1275
+ * @param {number} value
1276
+ * @return {promise<any>}
1277
+ */
1278
+ decrement(column = 'id', value = 1) {
1279
+ return __awaiter(this, void 0, void 0, function* () {
1280
+ const query = `${this.$constants('SET')} ${column} = ${column} - ${value}`;
1281
+ this.$state.set('UPDATE', [
1282
+ `${this.$constants('UPDATE')}`,
1283
+ `${this.$state.get('TABLE_NAME')}`,
1284
+ `${query}`
1285
+ ].join(' '));
1286
+ return yield this._update(true);
1287
+ });
1288
+ }
1289
+ /**
1290
+ * execute data without condition
1291
+ * @return {promise<any>}
1292
+ */
1293
+ all() {
1294
+ return __awaiter(this, void 0, void 0, function* () {
1295
+ return yield this.queryStatement([
1296
+ `${this.$constants('SELECT')}`,
1297
+ `*`,
1298
+ `${this.$constants('FROM')}`,
1299
+ `${this.$state.get('TABLE_NAME')}`
1300
+ ].join(' '));
1301
+ });
1302
+ }
1303
+ /**
1304
+ *
1305
+ * execute data with where by primary key default = id
1306
+ * @param {number} id
1307
+ * @return {promise<any>}
1308
+ */
1309
+ find(id) {
1310
+ return __awaiter(this, void 0, void 0, function* () {
1311
+ const result = yield this.queryStatement([
1312
+ `${this.$constants('SELECT')}`,
1313
+ `*`,
1314
+ `${this.$constants('FROM')}`,
1315
+ `${this.$state.get('TABLE_NAME')}`,
1316
+ `${this.$constants('WHERE')} id = ${id}`
1317
+ ].join(' '));
1318
+ return (result === null || result === void 0 ? void 0 : result.shift()) || null;
1319
+ });
1320
+ }
1321
+ /**
1322
+ *
1323
+ * execute data page & limit
1324
+ * @param {?object} paginationOptions
1325
+ * @param {number} paginationOptions.limit default 15
1326
+ * @param {number} paginationOptions.page default 1
1327
+ * @return {promise<Pagination>}
1328
+ */
1329
+ pagination(paginationOptions) {
1330
+ var _a, _b;
1331
+ return __awaiter(this, void 0, void 0, function* () {
1332
+ let limit = 15;
1333
+ let page = 1;
1334
+ if (paginationOptions != null) {
1335
+ limit = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit;
1336
+ page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
1337
+ }
1338
+ const currentPage = page;
1339
+ const nextPage = currentPage + 1;
1340
+ const prevPage = currentPage - 1 === 0 ? 1 : currentPage - 1;
1341
+ const offset = (page - 1) * limit;
1342
+ let sql = this._buildQuery();
1343
+ sql = sql.replace(this.$state.get('LIMIT'), `${limit} ${this.$constants('OFFSET')} ${offset}`);
1344
+ if (!sql.includes(this.$constants('LIMIT'))) {
1345
+ sql = [
1346
+ `${sql}`,
1347
+ `${this.$constants('LIMIT')}`,
1348
+ `${limit}`,
1349
+ `${this.$constants('OFFSET')} ${offset}`
1350
+ ].join(' ');
1351
+ }
1352
+ const result = yield this.queryStatement(sql);
1353
+ if ((_a = this.$state.get('HIDDEN')) === null || _a === void 0 ? void 0 : _a.length)
1354
+ this._hiddenColumn(result);
1355
+ if (!result.length)
1356
+ return {
1357
+ meta: {
1358
+ total: 0,
1359
+ limit,
1360
+ total_page: 0,
1361
+ current_page: currentPage,
1362
+ last_page: 0,
1363
+ next_page: 0,
1364
+ prev_page: 0
1365
+ },
1366
+ data: []
1367
+ };
1368
+ this.$state.set('SELECT', [
1369
+ `${this.$constants('SELECT')}`,
1370
+ `${this.$constants('COUNT')}(*)`,
1371
+ `${this.$constants('AS')} total`
1372
+ ].join(' '));
1373
+ sql = this._buildQuery();
1374
+ const count = yield this.queryStatement(sql);
1375
+ const total = count.shift().total || 0;
1376
+ let lastPage = Math.ceil(total / limit) || 0;
1377
+ lastPage = lastPage > 1 ? lastPage : 1;
1378
+ const totalPage = (_b = result === null || result === void 0 ? void 0 : result.length) !== null && _b !== void 0 ? _b : 0;
1379
+ return {
1380
+ meta: {
1381
+ total_page: totalPage,
1382
+ total,
1383
+ limit,
1384
+ current_page: currentPage,
1385
+ last_page: lastPage,
1386
+ next_page: nextPage,
1387
+ prev_page: prevPage
1388
+ },
1389
+ data: result !== null && result !== void 0 ? result : []
1390
+ };
1391
+ });
1392
+ }
1393
+ /**
1394
+ *
1395
+ * execute data useing page & limit
1396
+ * @param {?object} paginationOptions
1397
+ * @param {number} paginationOptions.limit
1398
+ * @param {number} paginationOptions.page
1399
+ * @return {promise<Pagination>}
1400
+ */
1401
+ paginate(paginationOptions) {
1402
+ return __awaiter(this, void 0, void 0, function* () {
1403
+ let limit = 15;
1404
+ let page = 1;
1405
+ if (paginationOptions != null) {
1406
+ limit = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit;
1407
+ page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
1408
+ }
1409
+ return yield this.pagination({ limit, page });
1410
+ });
1411
+ }
1412
+ /**
1413
+ *
1414
+ * execute data return object | null
1415
+ * @return {promise<object | null>}
1416
+ */
1417
+ first() {
1418
+ var _a, _b;
1419
+ return __awaiter(this, void 0, void 0, function* () {
1420
+ if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
1421
+ this.select(yield this.exceptColumns());
1422
+ this.limit(1);
1423
+ let sql = this._buildQuery();
1424
+ const result = yield this.queryStatement(sql);
1425
+ if ((_b = this.$state.get('HIDDEN')) === null || _b === void 0 ? void 0 : _b.length)
1426
+ this._hiddenColumn(result);
1427
+ if (this.$state.get('PLUCK')) {
1428
+ const pluck = this.$state.get('PLUCK');
1429
+ const newData = result === null || result === void 0 ? void 0 : result.shift();
1430
+ const checkProperty = newData.hasOwnProperty(pluck);
1431
+ if (!checkProperty)
1432
+ throw new Error(`can't find property '${pluck}' of result`);
1433
+ const r = newData[pluck] || null;
1434
+ const hook = this.$state.get('HOOK');
1435
+ for (let i in hook)
1436
+ yield hook[i](r);
1437
+ return r;
1438
+ }
1439
+ const r = (result === null || result === void 0 ? void 0 : result.shift()) || null;
1440
+ const hook = this.$state.get('HOOK');
1441
+ for (let i in hook)
1442
+ yield hook[i](r);
1443
+ return r;
1444
+ });
1445
+ }
1446
+ /**
1447
+ *
1448
+ * execute data return object | throw rror
1449
+ * @return {promise<object | null>}
1450
+ */
1451
+ findOne() {
1452
+ return __awaiter(this, void 0, void 0, function* () {
1453
+ return yield this.first();
1454
+ });
1455
+ }
1456
+ /**
1457
+ *
1458
+ * execute data return object | throw Error
1459
+ * @return {promise<object | Error>}
1460
+ */
1461
+ firstOrError(message, options) {
1462
+ var _a, _b;
1463
+ return __awaiter(this, void 0, void 0, function* () {
1464
+ if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
1465
+ this.select(yield this.exceptColumns());
1466
+ let sql = this._buildQuery();
1467
+ if (!sql.includes(this.$constants('LIMIT')))
1468
+ sql = `${sql} ${this.$constants('LIMIT')} 1`;
1469
+ else
1470
+ sql = sql.replace(this.$state.get('LIMIT'), `${this.$constants('LIMIT')} 1`);
1471
+ const result = yield this.queryStatement(sql);
1472
+ if ((_b = this.$state.get('HIDDEN')) === null || _b === void 0 ? void 0 : _b.length)
1473
+ this._hiddenColumn(result);
1474
+ if (this.$state.get('PLUCK')) {
1475
+ const pluck = this.$state.get('PLUCK');
1476
+ const newData = result === null || result === void 0 ? void 0 : result.shift();
1477
+ const checkProperty = newData.hasOwnProperty(pluck);
1478
+ if (!checkProperty)
1479
+ throw new Error(`can't find property '${pluck}' of result`);
1480
+ const data = newData[pluck] || null;
1481
+ if (data == null) {
1482
+ if (options == null) {
1483
+ throw { message, code: 400 };
1484
+ }
1485
+ throw Object.assign({ message }, options);
1486
+ }
1487
+ const hook = this.$state.get('HOOK');
1488
+ for (let i in hook)
1489
+ yield hook[i](data);
1490
+ return data;
1491
+ }
1492
+ const data = (result === null || result === void 0 ? void 0 : result.shift()) || null;
1493
+ if (data == null) {
1494
+ if (options == null) {
1495
+ throw { message, code: 400 };
1496
+ }
1497
+ throw Object.assign({ message }, options);
1498
+ }
1499
+ const hook = this.$state.get('HOOK');
1500
+ for (let i in hook)
1501
+ yield hook[i](data);
1502
+ return data;
1503
+ });
1504
+ }
1505
+ /**
1506
+ *
1507
+ * execute data return object | null
1508
+ * @return {promise<object | null>}
1509
+ */
1510
+ findOneOrError(message, options) {
1511
+ return __awaiter(this, void 0, void 0, function* () {
1512
+ return this.firstOrError(message, options);
1513
+ });
1514
+ }
1515
+ /**
1516
+ *
1517
+ * execute data return Array
1518
+ * @return {promise<Array<any>>}
1519
+ */
1520
+ get() {
1521
+ var _a, _b;
1522
+ return __awaiter(this, void 0, void 0, function* () {
1523
+ if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
1524
+ this.select(yield this.exceptColumns());
1525
+ const sql = this._buildQuery();
1526
+ const result = yield this.queryStatement(sql);
1527
+ if ((_b = this.$state.get('HIDDEN')) === null || _b === void 0 ? void 0 : _b.length)
1528
+ this._hiddenColumn(result);
1529
+ if (this.$state.get('CHUNK')) {
1530
+ const data = result.reduce((resultArray, item, index) => {
1531
+ const chunkIndex = Math.floor(index / this.$state.get('CHUNK'));
1532
+ if (!resultArray[chunkIndex])
1533
+ resultArray[chunkIndex] = [];
1534
+ resultArray[chunkIndex].push(item);
1535
+ return resultArray;
1536
+ }, []);
1537
+ const hook = this.$state.get('HOOK');
1538
+ for (let i in hook)
1539
+ yield hook[i](data || []);
1540
+ return data || [];
1541
+ }
1542
+ if (this.$state.get('PLUCK')) {
1543
+ const pluck = this.$state.get('PLUCK');
1544
+ const newData = result.map((d) => d[pluck]);
1545
+ if (newData.every((d) => d == null)) {
1546
+ throw new Error(`can't find property '${pluck}' of result`);
1547
+ }
1548
+ const hook = this.$state.get('HOOK');
1549
+ for (let i in hook)
1550
+ yield hook[i](newData || []);
1551
+ return newData || [];
1552
+ }
1553
+ const hook = this.$state.get('HOOK');
1554
+ for (let i in hook)
1555
+ yield hook[i](result || []);
1556
+ return result || [];
1557
+ });
1558
+ }
1559
+ /**
1560
+ *
1561
+ * execute data return Array
1562
+ * @return {promise<Array<any>>}
1563
+ */
1564
+ findMany() {
1565
+ return __awaiter(this, void 0, void 0, function* () {
1566
+ return yield this.get();
1567
+ });
1568
+ }
1569
+ /**
1570
+ *
1571
+ * execute data return json of result
1572
+ * @return {promise<string>}
1573
+ */
1574
+ toJSON() {
1575
+ var _a, _b;
1576
+ return __awaiter(this, void 0, void 0, function* () {
1577
+ if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
1578
+ this.select(yield this.exceptColumns());
1579
+ const sql = this._buildQuery();
1580
+ const result = yield this.queryStatement(sql);
1581
+ if ((_b = this.$state.get('HIDDEN')) === null || _b === void 0 ? void 0 : _b.length)
1582
+ this._hiddenColumn(result);
1583
+ return JSON.stringify(result);
1584
+ });
1585
+ }
1586
+ /**
1587
+ *
1588
+ * execute data return array of results
1589
+ * @param {string=} column [column=id]
1590
+ * @return {promise<Array>}
1591
+ */
1592
+ toArray(column = 'id') {
1593
+ return __awaiter(this, void 0, void 0, function* () {
1594
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${column}`);
1595
+ const sql = this._buildQuery();
1596
+ const result = yield this.queryStatement(sql);
1597
+ const toArray = result.map((data) => data[column]);
1598
+ return toArray;
1599
+ });
1600
+ }
1601
+ /**
1602
+ *
1603
+ * execute data return number of results
1604
+ * @param {string=} column [column=id]
1605
+ * @return {promise<number>}
1606
+ */
1607
+ count(column = 'id') {
1608
+ var _a;
1609
+ return __awaiter(this, void 0, void 0, function* () {
1610
+ this.$state.set('SELECT', [
1611
+ `${this.$constants('SELECT')}`,
1612
+ `${this.$constants('COUNT')}(${column})`,
1613
+ `${this.$constants('AS')} total`
1614
+ ].join(' '));
1615
+ const sql = this._buildQuery();
1616
+ const result = yield this.queryStatement(sql);
1617
+ return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.total) || 0;
1618
+ });
1619
+ }
1620
+ /**
1621
+ *
1622
+ * execute data return result is exists
1623
+ * @return {promise<boolean>}
1624
+ */
1625
+ exists() {
1626
+ var _a;
1627
+ return __awaiter(this, void 0, void 0, function* () {
1628
+ const result = yield this.queryStatement([
1629
+ `${this.$constants('SELECT')}`,
1630
+ `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
1631
+ `*`,
1632
+ `${this.$state.get('FROM')}`,
1633
+ `${this.$state.get('TABLE_NAME')}`,
1634
+ `${this.$state.get('WHERE')}`,
1635
+ `${this.$constants('LIMIT')} 1) ${this.$constants('AS')} 'exists'`
1636
+ ].join(' '));
1637
+ return !!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false;
1638
+ });
1639
+ }
1640
+ /**
1641
+ *
1642
+ * execute data return average of results
1643
+ * @param {string=} column [column=id]
1644
+ * @return {promise<number>}
1645
+ */
1646
+ avg(column = 'id') {
1647
+ var _a;
1648
+ return __awaiter(this, void 0, void 0, function* () {
1649
+ this.$state.set('SELECT', [
1650
+ `${this.$constants('SELECT')}`,
1651
+ `${this.$constants('AVG')}(${column})`,
1652
+ `${this.$constants('AS')} avg`
1653
+ ].join(' '));
1654
+ const sql = this._buildQuery();
1655
+ const result = yield this.queryStatement(sql);
1656
+ return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.avg) || 0;
1657
+ });
1658
+ }
1659
+ /**
1660
+ *
1661
+ * execute data return summary of results
1662
+ * @param {string=} column [column=id]
1663
+ * @return {promise<number>}
1664
+ */
1665
+ sum(column = 'id') {
1666
+ var _a;
1667
+ return __awaiter(this, void 0, void 0, function* () {
1668
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('SUM')}(${column}) ${this.$constants('AS')} sum`);
1669
+ const sql = this._buildQuery();
1670
+ const result = yield this.queryStatement(sql);
1671
+ return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0;
1672
+ });
1673
+ }
1674
+ /**
1675
+ *
1676
+ * execute data return maximum of results
1677
+ * @param {string=} column [column=id]
1678
+ * @return {promise<number>}
1679
+ */
1680
+ max(column = 'id') {
1681
+ var _a;
1682
+ return __awaiter(this, void 0, void 0, function* () {
1683
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MAX')}(${column}) ${this.$constants('AS')} max`);
1684
+ const sql = this._buildQuery();
1685
+ const result = yield this.queryStatement(sql);
1686
+ return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0;
1687
+ });
1688
+ }
1689
+ /**
1690
+ *
1691
+ * execute data return minimum of results
1692
+ * @param {string=} column [column=id]
1693
+ * @return {promise<number>}
1694
+ */
1695
+ min(column = 'id') {
1696
+ var _a;
1697
+ return __awaiter(this, void 0, void 0, function* () {
1698
+ this.$state.set('SELECT', `${this.$constants('SELECT')} ${this.$constants('MIN')}(${column}) ${this.$constants('AS')} min`);
1699
+ const sql = this._buildQuery();
1700
+ const result = yield this.queryStatement(sql);
1701
+ return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0;
1702
+ });
1703
+ }
1704
+ /**
1705
+ *
1706
+ * delete data from database
1707
+ * @return {promise<boolean>}
1708
+ */
1709
+ delete() {
1710
+ var _a;
1711
+ return __awaiter(this, void 0, void 0, function* () {
1712
+ if (!this.$state.get('WHERE')) {
1713
+ throw new Error("can't delete without where condition");
1714
+ }
1715
+ this.$state.set('DELETE', [
1716
+ `${this.$constants('DELETE')}`,
1717
+ `${this.$state.get('FROM')}`,
1718
+ `${this.$state.get('TABLE_NAME')}`,
1719
+ `${this.$state.get('WHERE')}`
1720
+ ].join(' '));
1721
+ const result = yield this.actionStatement({ sql: this.$state.get('DELETE') });
1722
+ if (result)
1723
+ return (_a = !!result) !== null && _a !== void 0 ? _a : false;
1724
+ return false;
1725
+ });
1726
+ }
1727
+ /**
1728
+ *
1729
+ * delete data from database ignore where condition
1730
+ * @return {promise<boolean>}
1731
+ */
1732
+ forceDelete() {
1733
+ var _a;
1734
+ return __awaiter(this, void 0, void 0, function* () {
1735
+ this.$state.set('DELETE', [
1736
+ `${this.$constants('DELETE')}`,
1737
+ `${this.$state.get('FROM')}`,
1738
+ `${this.$state.get('TABLE_NAME')}`,
1739
+ `${this.$state.get('WHERE')}`
1740
+ ].join(' '));
1741
+ const result = yield this.actionStatement({ sql: this.$state.get('DELETE') });
1742
+ if (result)
1743
+ return (_a = !!result) !== null && _a !== void 0 ? _a : false;
1744
+ return false;
1745
+ });
1746
+ }
1747
+ /**
1748
+ *
1749
+ * execute data return Array *grouping results in column
1750
+ * @param {string} column
1751
+ * @return {promise<Array>}
1752
+ */
1753
+ getGroupBy(column) {
1754
+ return __awaiter(this, void 0, void 0, function* () {
1755
+ this.$state.set('GROUP_BY', `${this.$constants('GROUP_BY')} ${column}`);
1756
+ this.$state.set('SELECT', [
1757
+ `${this.$state.get('SELECT')}`,
1758
+ `, ${this.$constants('GROUP_CONCAT')}(id)`,
1759
+ `${this.$constants('AS')} data`
1760
+ ].join(' '));
1761
+ const sql = this._buildQuery();
1762
+ const results = yield this.queryStatement(sql);
1763
+ let data = [];
1764
+ results.forEach((result) => {
1765
+ var _a, _b;
1766
+ const splits = (_b = (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.split(',')) !== null && _b !== void 0 ? _b : '0';
1767
+ splits.forEach((split) => data = [...data, split]);
1768
+ });
1769
+ const sqlGroups = [
1770
+ `${this.$constants('SELECT')}`,
1771
+ `*`,
1772
+ `${this.$constants('FROM')}`,
1773
+ `${this.$state.get('TABLE_NAME')}`,
1774
+ `${this.$constants('WHERE')} id ${this.$constants('IN')}`,
1775
+ `(${data.map((a) => `\'${a}\'`).join(',') || ['0']})`
1776
+ ].join(' ');
1777
+ const groups = yield this.queryStatement(sqlGroups);
1778
+ const resultData = results.map((result) => {
1779
+ const id = result[column];
1780
+ const newData = groups.filter((data) => data[column] === id);
1781
+ return ({
1782
+ [column]: id,
1783
+ data: newData
1784
+ });
1785
+ });
1786
+ return resultData;
1787
+ });
1788
+ }
1789
+ /**
1790
+ *
1791
+ * execute data return grouping results by index
1792
+ * @param {string} column
1793
+ * @return {promise<Array>}
1794
+ */
1795
+ findManyGroupBy(column) {
1796
+ return __awaiter(this, void 0, void 0, function* () {
1797
+ return yield this.getGroupBy(column);
1798
+ });
1799
+ }
1800
+ /**
1801
+ * execute data when save *action [insert , update]
1802
+ * @return {Promise<any>} promise
1803
+ */
1804
+ save() {
1805
+ return __awaiter(this, void 0, void 0, function* () {
1806
+ const attributes = this.$attributes;
1807
+ if (attributes != null) {
1808
+ while (true) {
1809
+ if (this.$state.get('WHERE')) {
1810
+ const query = this._queryUpdate(attributes);
1811
+ this.$state.set('UPDATE', [
1812
+ `${this.$constants('UPDATE')}`,
1813
+ `${this.$state.get('TABLE_NAME')}`,
1814
+ `${query}`
1815
+ ].join(' '));
1816
+ this.$state.set('SAVE', 'UPDATE');
1817
+ break;
1818
+ }
1819
+ const query = this._queryInsert(attributes);
1820
+ this.$state.set('INSERT', [
1821
+ `${this.$constants('INSERT')}`,
1822
+ `${this.$state.get('TABLE_NAME')}`,
1823
+ `${query}`
1824
+ ].join(' '));
1825
+ this.$state.set('SAVE', 'INSERT');
1826
+ break;
1827
+ }
1828
+ }
1829
+ switch (this.$state.get('SAVE')) {
1830
+ case 'INSERT_MULTIPLE': return yield this._insertMultiple();
1831
+ case 'INSERT': return yield this._insert();
1832
+ case 'UPDATE': return yield this._update();
1833
+ case 'INSERT_NOT_EXISTS': return yield this._insertNotExists();
1834
+ case 'UPDATE_OR_INSERT': return yield this._updateOrInsert();
1835
+ case 'INSERT_OR_SELECT': return yield this._insertOrSelect();
1836
+ default: throw new Error(`unknown this [${this.$state.get('SAVE')}]`);
1837
+ }
1838
+ });
1839
+ }
1840
+ /**
1841
+ *
1842
+ * show columns in table
1843
+ * @param {string=} table table name
1844
+ * @return {Promise<Array>}
1845
+ */
1846
+ showColumns(table = this.$state.get('TABLE_NAME')) {
1847
+ return __awaiter(this, void 0, void 0, function* () {
1848
+ const sql = [
1849
+ `${this.$constants('SHOW')}`,
1850
+ `${this.$constants('COLUMNS')}`,
1851
+ `${this.$constants('FROM')}`,
1852
+ `\`${table.replace(/\`/g, '')}\``
1853
+ ].join(' ');
1854
+ const rawColumns = yield this.queryStatement(sql);
1855
+ const columns = rawColumns.map((column) => column.Field);
1856
+ return columns;
1857
+ });
1858
+ }
1859
+ /**
1860
+ *
1861
+ * show schemas in table
1862
+ * @param {string=} table [table= current table name]
1863
+ * @return {Promise<Array>}
1864
+ */
1865
+ showSchemas(table = this.$state.get('TABLE_NAME')) {
1866
+ return __awaiter(this, void 0, void 0, function* () {
1867
+ const sql = [
1868
+ `${this.$constants('SHOW')}`,
1869
+ `${this.$constants('COLUMNS')}`,
1870
+ `${this.$constants('FROM')}`,
1871
+ `\`${table.replace(/\`/g, '')}\``
1872
+ ].join(' ');
1873
+ const raw = yield this.queryStatement(sql);
1874
+ const schemas = raw.map((r) => {
1875
+ const schema = [];
1876
+ schema.push(`${r.Field}`);
1877
+ schema.push(`${r.Type}`);
1878
+ if (r.Null === 'YES') {
1879
+ schema.push(`NULL`);
1880
+ }
1881
+ if (r.Null === 'NO') {
1882
+ schema.push(`NOT NULL`);
1883
+ }
1884
+ if (r.Key === 'PRI') {
1885
+ schema.push(`PRIMARY KEY`);
1886
+ }
1887
+ if (r.Key === 'UNI') {
1888
+ schema.push(`UNIQUE`);
1889
+ }
1890
+ if (r.Default) {
1891
+ schema.push(`DEFAULT '${r.Default}'`);
1892
+ }
1893
+ if (r.Extra) {
1894
+ schema.push(`${r.Extra.toUpperCase()}`);
1895
+ }
1896
+ return schema.join(' ');
1897
+ });
1898
+ return schemas;
1899
+ });
1900
+ }
1901
+ /**
1902
+ *
1903
+ * show values in table
1904
+ * @param {string=} table table name
1905
+ * @return {Promise<Array>}
1906
+ */
1907
+ showValues(table = this.$state.get('TABLE_NAME')) {
1908
+ return __awaiter(this, void 0, void 0, function* () {
1909
+ const sql = [
1910
+ `${this.$constants('SELECT')}`,
1911
+ '*',
1912
+ `${this.$constants('FROM')}`,
1913
+ `\`${table.replace(/\`/g, '')}\``
1914
+ ].join(' ');
1915
+ const raw = yield this.queryStatement(sql);
1916
+ const values = raw.map((value) => {
1917
+ return `(${Object.values(value).map((v) => {
1918
+ return v == null ? 'NULL' : `'${v}'`;
1919
+ }).join(',')})`;
1920
+ });
1921
+ return values;
1922
+ });
1923
+ }
1924
+ /**
1925
+ *
1926
+ * backup this database intro new database same server or to another server
1927
+ * @param {Object} backupOptions
1928
+ * @param {string} backup.database
1929
+ * @param {object?} backup.to
1930
+ * @param {string} backup.to.host
1931
+ * @param {number} backup.to.port
1932
+ * @param {string} backup.to.database
1933
+ * @param {string} backup.to.username
1934
+ * @param {string} backup.to.password
1935
+
1936
+ * @return {Promise<boolean>}
1937
+ */
1938
+ backup({ database, to }) {
1939
+ return __awaiter(this, void 0, void 0, function* () {
1940
+ const tables = yield this.queryStatement('SHOW TABLES');
1941
+ let backup = [];
1942
+ for (const t of tables) {
1943
+ const table = String(Object.values(t).shift());
1944
+ const schemas = yield this.showSchemas(table);
1945
+ const createTableSQL = [
1946
+ `${this.$constants('CREATE_TABLE_NOT_EXISTS')}`,
1947
+ `\`${database}.${table}\``,
1948
+ `(${schemas.join(',')})`,
1949
+ `${this.$constants('ENGINE')}`,
1950
+ ];
1951
+ const values = yield this.showValues(table);
1952
+ let valueSQL = [];
1953
+ if (values.length) {
1954
+ const columns = yield this.showColumns(table);
1955
+ valueSQL = [
1956
+ `${this.$constants('INSERT')}`,
1957
+ `\`${database}.${table}\``,
1958
+ `(${columns.map((column) => `\`${column}\``).join(',')})`,
1959
+ `${this.$constants('VALUES')} ${values.join(',')}`
1960
+ ];
1961
+ }
1962
+ backup = [
1963
+ ...backup,
1964
+ {
1965
+ table: createTableSQL.join(' '),
1966
+ values: valueSQL.join(' '),
1967
+ }
1968
+ ];
1969
+ }
1970
+ if (to != null && Object.keys(to).length)
1971
+ this.connection(to);
1972
+ yield this.queryStatement(`${this.$constants('CREATE_DATABASE_NOT_EXISTS')} \`${database}\``);
1973
+ for (const b of backup) {
1974
+ yield this.queryStatement(b.table);
1975
+ if (b.values) {
1976
+ yield this.queryStatement(b.values);
1977
+ }
1978
+ }
1979
+ return true;
1980
+ });
1981
+ }
1982
+ /**
1983
+ *
1984
+ * backup database intro file
1985
+ * @param {Object} backupOptions
1986
+ * @param {string} backup.database
1987
+ * @param {object?} backup.filePath
1988
+ * @param {object?} backup.connection
1989
+ * @param {string} backup.connection.host
1990
+ * @param {number} backup.connection.port
1991
+ * @param {string} backup.connection.database
1992
+ * @param {string} backup.connection.username
1993
+ * @param {string} backup.connection.password
1994
+
1995
+ * @return {Promise<boolean>}
1996
+ */
1997
+ backupToFile({ filePath, database, connection }) {
1998
+ var _a, _b;
1999
+ return __awaiter(this, void 0, void 0, function* () {
2000
+ const tables = yield this.queryStatement(this.$constants('SHOW_TABLES'));
2001
+ let backup = [];
2002
+ for (const t of tables) {
2003
+ const table = String((_a = Object.values(t)) === null || _a === void 0 ? void 0 : _a.shift());
2004
+ const schemas = yield this.showSchemas(table);
2005
+ const createTableSQL = [
2006
+ `${this.$constants('CREATE_TABLE_NOT_EXISTS')}`,
2007
+ `\`${table}\``,
2008
+ `(${schemas.join(',')})`,
2009
+ `${this.$constants('ENGINE')};`,
2010
+ ];
2011
+ const values = yield this.showValues(table);
2012
+ let valueSQL = [];
2013
+ if (values.length) {
2014
+ const columns = yield this.showColumns(table);
2015
+ valueSQL = [
2016
+ `${this.$constants('INSERT')}`,
2017
+ `\`${table}\``,
2018
+ `(${columns.map((column) => `\`${column}\``).join(',')})`,
2019
+ `${this.$constants('VALUES')} ${values.join(',')};`
2020
+ ];
2021
+ }
2022
+ backup = [
2023
+ ...backup,
2024
+ {
2025
+ table: createTableSQL.join(' '),
2026
+ values: valueSQL.join(' ')
2027
+ }
2028
+ ];
2029
+ }
2030
+ if (connection != null && ((_b = Object.keys(connection)) === null || _b === void 0 ? void 0 : _b.length))
2031
+ this.connection(connection);
2032
+ let sql = [
2033
+ `SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";`,
2034
+ `START TRANSACTION;`,
2035
+ `SET time_zone = "+00:00";`,
2036
+ `${this.$constants('CREATE_DATABASE_NOT_EXISTS')} \`${database}\`;`,
2037
+ `USE \`${database}\`;`
2038
+ ];
2039
+ for (const b of backup) {
2040
+ sql = [...sql, b.table];
2041
+ if (b.values) {
2042
+ sql = [...sql, b.values];
2043
+ }
2044
+ }
2045
+ fs_1.default.writeFileSync(filePath, (0, sql_formatter_1.format)([...sql, 'COMMIT;'].join('\n'), {
2046
+ language: 'spark',
2047
+ tabWidth: 2,
2048
+ linesBetweenQueries: 1,
2049
+ }));
2050
+ return;
2051
+ });
2052
+ }
2053
+ /**
2054
+ *
2055
+ * fake data
2056
+ * @param {number} rows number of rows
2057
+ * @return {promise<any>}
2058
+ */
2059
+ faker(rows = 1) {
2060
+ return __awaiter(this, void 0, void 0, function* () {
2061
+ let data = [];
2062
+ const sql = [
2063
+ `${this.$constants('SHOW')}`,
2064
+ `${this.$constants('FIELDS')}`,
2065
+ `${this.$constants('FROM')}`,
2066
+ `${this.$state.get('TABLE_NAME')}`
2067
+ ].join(' ');
2068
+ const fields = yield this.queryStatement(sql);
2069
+ for (let row = 0; row < rows; row++) {
2070
+ if (this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null) {
2071
+ throw new Error("Unknow this table name");
2072
+ }
2073
+ let columnAndValue = {};
2074
+ for (const { Field: field, Type: type } of fields) {
2075
+ const passed = field.toLowerCase() === 'id' ||
2076
+ field.toLowerCase() === '_id' ||
2077
+ field.toLowerCase() === 'uuid';
2078
+ if (passed)
2079
+ continue;
2080
+ columnAndValue = Object.assign(Object.assign({}, columnAndValue), { [field]: this.$utils.faker(type) });
2081
+ }
2082
+ data = [...data, columnAndValue];
2083
+ }
2084
+ const query = this._queryInsertMultiple(data);
2085
+ this.$state.set('INSERT', [
2086
+ `${this.$constants('INSERT')}`,
2087
+ `${this.$state.get('TABLE_NAME')}`,
2088
+ `${query}`
2089
+ ].join(' '));
2090
+ this.$state.set('SAVE', 'INSERT_MULTIPLE');
2091
+ return this.save();
2092
+ });
2093
+ }
2094
+ /**
2095
+ *
2096
+ * truncate of table
2097
+ * @return {promise<boolean>}
2098
+ */
2099
+ truncate() {
2100
+ return __awaiter(this, void 0, void 0, function* () {
2101
+ const sql = [
2102
+ `${this.$constants('TRUNCATE_TABLE')}`,
2103
+ `${this.$state.get('TABLE_NAME')}`
2104
+ ].join(' ');
2105
+ yield this.queryStatement(sql);
2106
+ return true;
2107
+ });
2108
+ }
2109
+ /**
2110
+ *
2111
+ * drop of table
2112
+ * @return {promise<boolean>}
2113
+ */
2114
+ drop() {
2115
+ return __awaiter(this, void 0, void 0, function* () {
2116
+ const sql = [
2117
+ `${this.$constants('DROP_TABLE')}`,
2118
+ `${this.$state.get('TABLE_NAME')}`
2119
+ ].join(' ');
2120
+ yield this.queryStatement(sql);
2121
+ return true;
2122
+ });
2123
+ }
2124
+ _queryWhereIsExists() {
2125
+ var _a;
2126
+ return ((_a = this.$state.get('WHERE')) === null || _a === void 0 ? void 0 : _a.includes(this.$constants('WHERE'))) || false;
2127
+ }
2128
+ _bindTableAndColumnInQueryWhere(column) {
2129
+ return `${this.$state.get('TABLE_NAME')}.\`${column}\``;
2130
+ }
2131
+ _insertNotExists() {
2132
+ return __awaiter(this, void 0, void 0, function* () {
2133
+ if (!this.$state.get('WHERE'))
2134
+ throw new Error("Can't insert not exists without where condition");
2135
+ let sql = [
2136
+ `${this.$constants('SELECT')}`,
2137
+ `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
2138
+ `*`,
2139
+ `${this.$state.get('FROM')}`,
2140
+ `${this.$state.get('TABLE_NAME')}`,
2141
+ `${this.$state.get('WHERE')}`,
2142
+ `${this.$constants('LIMIT')} 1)`,
2143
+ `${this.$constants('AS')} 'exists'`
2144
+ ].join(' ');
2145
+ const [{ exists: result }] = yield this.queryStatement(sql);
2146
+ const check = !!Number.parseInt(result);
2147
+ switch (check) {
2148
+ case false: {
2149
+ const [result, id] = yield this.actionStatement({
2150
+ sql: this.$state.get('INSERT'),
2151
+ returnId: true
2152
+ });
2153
+ if (this.$state.get('VOID'))
2154
+ return null;
2155
+ if (result) {
2156
+ const sql = [
2157
+ `${this.$state.get('SELECT')}`,
2158
+ `${this.$state.get('FROM')}`,
2159
+ `${this.$state.get('TABLE_NAME')}`,
2160
+ `${this.$constants('WHERE')} id = ${id}`
2161
+ ].join(' ');
2162
+ const data = yield this.queryStatement(sql);
2163
+ return (data === null || data === void 0 ? void 0 : data.shift()) || null;
2164
+ }
2165
+ return null;
2166
+ }
2167
+ default: return null;
2168
+ }
2169
+ });
2170
+ }
2171
+ queryStatement(sql) {
2172
+ return __awaiter(this, void 0, void 0, function* () {
2173
+ if (this.$state.get('DEBUG'))
2174
+ this.$utils.consoleDebug(sql);
2175
+ const result = yield this.$pool.query(sql);
2176
+ return result;
2177
+ });
2178
+ }
2179
+ actionStatement({ sql, returnId = false }) {
2180
+ return __awaiter(this, void 0, void 0, function* () {
2181
+ if (this.$state.get('DEBUG'))
2182
+ this.$utils.consoleDebug(sql);
2183
+ if (returnId) {
2184
+ const result = yield this.$pool.query(sql);
2185
+ return [result.affectedRows, result.insertId];
2186
+ }
2187
+ const { affectedRows: result } = yield this.$pool.query(sql);
2188
+ return result;
2189
+ });
2190
+ }
2191
+ _insert() {
2192
+ return __awaiter(this, void 0, void 0, function* () {
2193
+ const [result, id] = yield this.actionStatement({
2194
+ sql: this.$state.get('INSERT'),
2195
+ returnId: true
2196
+ });
2197
+ if (this.$state.get('VOID'))
2198
+ return null;
2199
+ if (result) {
2200
+ const sql = [
2201
+ `${this.$state.get('SELECT')}`,
2202
+ `${this.$state.get('FROM')}`,
2203
+ `${this.$state.get('TABLE_NAME')}`,
2204
+ `${this.$constants('WHERE')} id = ${id}`
2205
+ ].join(' ');
2206
+ const data = yield this.queryStatement(sql);
2207
+ const result = (data === null || data === void 0 ? void 0 : data.shift()) || null;
2208
+ this.$state.set('RESULT', result);
2209
+ return result;
2210
+ }
2211
+ return null;
2212
+ });
2213
+ }
2214
+ _checkValueHasRaw(value) {
2215
+ return typeof value === 'string' && value.startsWith(this.$constants('RAW'))
2216
+ ? value.replace(`${this.$constants('RAW')} `, '').replace(this.$constants('RAW'), '')
2217
+ : `'${value}'`;
2218
+ }
2219
+ _insertMultiple() {
2220
+ return __awaiter(this, void 0, void 0, function* () {
2221
+ const [result, id] = yield this.actionStatement({
2222
+ sql: this.$state.get('INSERT'),
2223
+ returnId: true
2224
+ });
2225
+ if (this.$state.get('VOID'))
2226
+ return null;
2227
+ if (result) {
2228
+ const arrayId = [...Array(result)].map((_, i) => i + id);
2229
+ const sql = [
2230
+ `${this.$state.get('SELECT')}`,
2231
+ `${this.$state.get('FROM')}`,
2232
+ `${this.$state.get('TABLE_NAME')}`,
2233
+ `${this.$constants('WHERE')} id`,
2234
+ `${this.$constants('IN')} (${arrayId})`
2235
+ ].join(' ');
2236
+ const data = yield this.queryStatement(sql);
2237
+ const resultData = data || null;
2238
+ this.$state.set('RESULT', resultData);
2239
+ return resultData;
2240
+ }
2241
+ return null;
2242
+ });
2243
+ }
2244
+ _insertOrSelect() {
2245
+ return __awaiter(this, void 0, void 0, function* () {
2246
+ if (!this.$state.get('WHERE')) {
2247
+ throw new Error("Can't create or select without where condition");
2248
+ }
2249
+ let sql = [
2250
+ `${this.$constants('SELECT')}`,
2251
+ `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
2252
+ `*`,
2253
+ `${this.$state.get('FROM')}`,
2254
+ `${this.$state.get('TABLE_NAME')}`,
2255
+ `${this.$state.get('WHERE')}`,
2256
+ `${this.$constants('LIMIT')} 1)`,
2257
+ `${this.$constants('AS')} 'exists'`
2258
+ ].join(' ');
2259
+ let check = false;
2260
+ const [{ exists: result }] = yield this.queryStatement(sql);
2261
+ check = !!parseInt(result);
2262
+ switch (check) {
2263
+ case false: {
2264
+ const [result, id] = yield this.actionStatement({
2265
+ sql: this.$state.get('INSERT'),
2266
+ returnId: true
2267
+ });
2268
+ if (this.$state.get('VOID'))
2269
+ return null;
2270
+ if (result) {
2271
+ const sql = [
2272
+ `${this.$state.get('SELECT')}`,
2273
+ `${this.$state.get('FROM')}`,
2274
+ `${this.$state.get('TABLE_NAME')}`,
2275
+ `${this.$constants('WHERE')} id = ${id}`
2276
+ ].join(' ');
2277
+ const data = yield this.queryStatement(sql);
2278
+ const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'insert' }) || null;
2279
+ this.$state.set('RESULT', resultData);
2280
+ return resultData;
2281
+ }
2282
+ return null;
2283
+ }
2284
+ case true: {
2285
+ const data = yield this.queryStatement([
2286
+ `${this.$state.get('SELECT')}`,
2287
+ `${this.$state.get('FROM')}`,
2288
+ `${this.$state.get('TABLE_NAME')}`,
2289
+ `${this.$state.get('WHERE')}`
2290
+ ].join(' '));
2291
+ if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2292
+ for (const val of data) {
2293
+ val.action_status = 'select';
2294
+ }
2295
+ return data || [];
2296
+ }
2297
+ return Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'select' }) || null;
2298
+ }
2299
+ default: {
2300
+ return null;
2301
+ }
2302
+ }
2303
+ });
2304
+ }
2305
+ _updateOrInsert() {
2306
+ return __awaiter(this, void 0, void 0, function* () {
2307
+ if (!this.$state.get('WHERE')) {
2308
+ throw new Error("Can't update or insert without where condition");
2309
+ }
2310
+ let sql = [
2311
+ `${this.$constants('SELECT')}`,
2312
+ `${this.$constants('EXISTS')}(${this.$constants('SELECT')}`,
2313
+ `*`,
2314
+ `${this.$state.get('FROM')}`,
2315
+ `${this.$state.get('TABLE_NAME')}`,
2316
+ `${this.$state.get('WHERE')}`,
2317
+ `${this.$constants('LIMIT')} 1)`,
2318
+ `${this.$constants('AS')} 'exists'`
2319
+ ].join(' ');
2320
+ let check = false;
2321
+ const [{ exists: result }] = yield this.queryStatement(sql);
2322
+ check = !!parseInt(result);
2323
+ switch (check) {
2324
+ case false: {
2325
+ const [result, id] = yield this.actionStatement({
2326
+ sql: this.$state.get('INSERT'),
2327
+ returnId: true
2328
+ });
2329
+ if (this.$state.get('VOID'))
2330
+ return null;
2331
+ if (result) {
2332
+ const sql = [
2333
+ `${this.$state.get('SELECT')}`,
2334
+ `${this.$state.get('FROM')}`,
2335
+ `${this.$state.get('TABLE_NAME')}`,
2336
+ `${this.$constants('WHERE')} id = ${id}`
2337
+ ].join(' ');
2338
+ const data = yield this.queryStatement(sql);
2339
+ const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'insert' }) || null;
2340
+ this.$state.set('RESULT', resultData);
2341
+ return resultData;
2342
+ }
2343
+ return null;
2344
+ }
2345
+ case true: {
2346
+ const result = yield this.actionStatement({
2347
+ sql: [
2348
+ `${this.$state.get('UPDATE')}`,
2349
+ `${this.$state.get('WHERE')}`
2350
+ ].join(' ')
2351
+ });
2352
+ if (this.$state.get('VOID'))
2353
+ return null;
2354
+ if (result) {
2355
+ const data = yield this.queryStatement([
2356
+ `${this.$state.get('SELECT')}`,
2357
+ `${this.$state.get('FROM')}`,
2358
+ `${this.$state.get('TABLE_NAME')}`,
2359
+ `${this.$state.get('WHERE')}`
2360
+ ].join(' '));
2361
+ if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2362
+ for (const val of data) {
2363
+ val.action_status = 'update';
2364
+ }
2365
+ return data || [];
2366
+ }
2367
+ return Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'update' }) || null;
2368
+ }
2369
+ return null;
2370
+ }
2371
+ default: {
2372
+ return null;
2373
+ }
2374
+ }
2375
+ });
2376
+ }
2377
+ _update(ignoreWhere = false) {
2378
+ return __awaiter(this, void 0, void 0, function* () {
2379
+ if (!this.$state.get('WHERE') && !ignoreWhere)
2380
+ throw new Error("can't update without where condition");
2381
+ const result = yield this.actionStatement({
2382
+ sql: [
2383
+ `${this.$state.get('UPDATE')}`, `${this.$state.get('WHERE')}`
2384
+ ].join(' ')
2385
+ });
2386
+ if (this.$state.get('VOID'))
2387
+ return null;
2388
+ if (!result)
2389
+ return null;
2390
+ const sql = [
2391
+ `${this.$state.get('SELECT')}`,
2392
+ `${this.$state.get('FROM')}`,
2393
+ `${this.$state.get('TABLE_NAME')}`,
2394
+ `${this.$state.get('WHERE')}`
2395
+ ].join(' ');
2396
+ const data = yield this.queryStatement(sql);
2397
+ if ((data === null || data === void 0 ? void 0 : data.length) > 1)
2398
+ return data || [];
2399
+ const res = (data === null || data === void 0 ? void 0 : data.shift()) || null;
2400
+ this.$state.set('RESULT', res);
2401
+ return res;
2402
+ });
2403
+ }
2404
+ _hiddenColumn(data) {
2405
+ var _a;
2406
+ const hidden = this.$state.get('HIDDEN');
2407
+ if ((_a = Object.keys(data)) === null || _a === void 0 ? void 0 : _a.length) {
2408
+ hidden.forEach((column) => {
2409
+ data.forEach((objColumn) => {
2410
+ delete objColumn[column];
2411
+ });
2412
+ });
2413
+ }
2414
+ return data;
2415
+ }
2416
+ _queryUpdate(data) {
2417
+ const values = Object.entries(data).map(([column, value]) => {
2418
+ if (typeof value === 'string' && !(value.includes(this.$constants('RAW'))))
2419
+ value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
2420
+ return `\`${column}\` = ${value == null || value === 'NULL'
2421
+ ? 'NULL'
2422
+ : typeof value === 'string' && value.includes(this.$constants('RAW'))
2423
+ ? `${this.$utils.covertBooleanToNumber(value)}`.replace(this.$constants('RAW'), '')
2424
+ : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
2425
+ });
2426
+ return `${this.$constants('SET')} ${values}`;
2427
+ }
2428
+ _queryInsert(data) {
2429
+ const columns = Object.keys(data).map((column) => `\`${column}\``);
2430
+ const values = Object.values(data).map((value) => {
2431
+ if (typeof value === 'string' && !(value.includes(this.$constants('RAW'))))
2432
+ value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
2433
+ return `${value == null || value === 'NULL'
2434
+ ? 'NULL'
2435
+ : typeof value === 'string' && value.includes(this.$constants('RAW'))
2436
+ ? `${this.$utils.covertBooleanToNumber(value)}`.replace(this.$constants('RAW'), '')
2437
+ : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
2438
+ });
2439
+ return [
2440
+ `(${columns})`,
2441
+ `${this.$constants('VALUES')}`,
2442
+ `(${values})`
2443
+ ].join(' ');
2444
+ }
2445
+ _queryInsertMultiple(data) {
2446
+ var _a;
2447
+ let values = [];
2448
+ for (let objects of data) {
2449
+ const vals = Object.values(objects).map((value) => {
2450
+ if (typeof value === 'string')
2451
+ value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
2452
+ return `${value == null || value === 'NULL'
2453
+ ? 'NULL'
2454
+ : typeof value === 'string' && value.includes(this.$constants('RAW'))
2455
+ ? `${this.$utils.covertBooleanToNumber(value)}`.replace(this.$constants('RAW'), '')
2456
+ : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
2457
+ });
2458
+ values.push(`(${vals.join(',')})`);
2459
+ }
2460
+ const columns = Object.keys((_a = [...data]) === null || _a === void 0 ? void 0 : _a.shift()).map((column) => `\`${column}\``);
2461
+ return [
2462
+ `(${columns})`,
2463
+ `${this.$constants('VALUES')}`,
2464
+ `${values.join(',')}`
2465
+ ].join(' ');
2466
+ }
2467
+ _valueAndOperator(value, operator, useDefault = false) {
2468
+ if (useDefault)
2469
+ return [operator, '='];
2470
+ if (operator == null)
2471
+ throw new Error('bad arguments');
2472
+ if (operator.toUpperCase() === this.$constants('LIKE')) {
2473
+ operator = operator.toUpperCase();
2474
+ }
2475
+ return [value, operator];
2476
+ }
2477
+ _valueTrueFalse(value) {
2478
+ if (value === true)
2479
+ return 1;
2480
+ if (value === false)
2481
+ return 0;
2482
+ return value;
2483
+ }
2484
+ _buildQuery() {
2485
+ let sql = [];
2486
+ while (true) {
2487
+ if (this.$state.get('INSERT')) {
2488
+ sql = [
2489
+ this.$state.get('INSERT')
2490
+ ];
2491
+ break;
2492
+ }
2493
+ if (this.$state.get('UPDATE')) {
2494
+ sql = [
2495
+ this.$state.get('UPDATE'),
2496
+ this.$state.get('WHERE')
2497
+ ];
2498
+ break;
2499
+ }
2500
+ if (this.$state.get('DELETE')) {
2501
+ sql = [
2502
+ this.$state.get('DELETE')
2503
+ ];
2504
+ break;
2505
+ }
2506
+ sql = [
2507
+ this.$state.get('SELECT'),
2508
+ this.$state.get('FROM'),
2509
+ this.$state.get('TABLE_NAME'),
2510
+ this.$state.get('JOIN'),
2511
+ this.$state.get('WHERE'),
2512
+ this.$state.get('GROUP_BY'),
2513
+ this.$state.get('HAVING'),
2514
+ this.$state.get('ORDER_BY'),
2515
+ this.$state.get('LIMIT'),
2516
+ this.$state.get('OFFSET')
2517
+ ];
2518
+ break;
2519
+ }
2520
+ return sql.filter(s => s !== '' || s == null).join(' ');
2521
+ }
2522
+ _initialConnection() {
2523
+ this.$utils = utils_1.utils;
2524
+ this.$pool = (() => {
2525
+ let pool = connection_1.Pool;
2526
+ return {
2527
+ query: (sql) => __awaiter(this, void 0, void 0, function* () { return yield pool.query(sql); }),
2528
+ get: () => pool,
2529
+ set: (newConnection) => {
2530
+ pool = newConnection;
2531
+ return;
2532
+ }
2533
+ };
2534
+ })();
2535
+ this.$logger = (() => {
2536
+ let logger = [];
2537
+ return {
2538
+ get: () => logger,
2539
+ set: (data) => {
2540
+ logger = [...logger, data];
2541
+ return;
2542
+ },
2543
+ check: (data) => logger.indexOf(data) != -1
2544
+ };
2545
+ })();
2546
+ this.$constants = (name) => {
2547
+ if (name == null)
2548
+ return constants_1.CONSTANTS;
2549
+ if (!constants_1.CONSTANTS.hasOwnProperty(name.toUpperCase()))
2550
+ throw new Error(`not found constants : ${name}`);
2551
+ return constants_1.CONSTANTS[name.toUpperCase()];
2552
+ };
2553
+ }
2554
+ }
2555
+ exports.Builder = Builder;
2556
+ exports.default = Builder;