tspace-mysql 1.3.0 → 1.3.2

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