tspace-mysql 1.5.0 → 1.5.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 (53) hide show
  1. package/README.md +1856 -701
  2. package/build/cli/dump/db.js +3 -2
  3. package/build/cli/generate/make.js +17 -15
  4. package/build/cli/generate/modelDecorator.d.ts +1 -1
  5. package/build/cli/generate/modelDecorator.js +2 -3
  6. package/build/cli/index.js +45 -27
  7. package/build/cli/migrate/make.d.ts +1 -1
  8. package/build/cli/migrate/make.js +2 -2
  9. package/build/cli/migrations/make-db.d.ts +4 -0
  10. package/build/cli/migrations/make-db.js +58 -0
  11. package/build/cli/migrations/make.d.ts +2 -0
  12. package/build/cli/migrations/make.js +201 -0
  13. package/build/lib/Interface.d.ts +24 -5
  14. package/build/lib/connection/index.d.ts +5 -1
  15. package/build/lib/connection/index.js +65 -8
  16. package/build/lib/connection/options.js +2 -2
  17. package/build/lib/constants/index.js +13 -3
  18. package/build/lib/{tspace → core}/Abstracts/AbstractBuilder.d.ts +1 -1
  19. package/build/lib/{tspace → core}/Abstracts/AbstractModel.d.ts +15 -13
  20. package/build/lib/{tspace → core}/Blueprint.d.ts +14 -3
  21. package/build/lib/{tspace → core}/Blueprint.js +30 -4
  22. package/build/lib/{tspace → core}/Builder.d.ts +140 -44
  23. package/build/lib/{tspace → core}/Builder.js +772 -459
  24. package/build/lib/{tspace → core}/DB.d.ts +20 -4
  25. package/build/lib/{tspace → core}/DB.js +73 -39
  26. package/build/lib/{tspace → core}/Decorator.js +2 -2
  27. package/build/lib/{tspace → core/Handlers}/Logger.d.ts +3 -3
  28. package/build/lib/{tspace → core/Handlers}/Logger.js +4 -4
  29. package/build/lib/{tspace → core}/Handlers/Proxy.js +2 -2
  30. package/build/lib/{tspace → core}/Handlers/Relation.d.ts +2 -4
  31. package/build/lib/{tspace → core}/Handlers/Relation.js +69 -48
  32. package/build/lib/{tspace → core}/Handlers/State.d.ts +1 -1
  33. package/build/lib/{tspace → core}/Handlers/State.js +3 -3
  34. package/build/lib/{tspace → core}/Model.d.ts +358 -133
  35. package/build/lib/{tspace → core}/Model.js +1316 -558
  36. package/build/lib/core/Schema.d.ts +137 -0
  37. package/build/lib/{tspace → core}/Schema.js +147 -52
  38. package/build/lib/core/Type.d.ts +6 -0
  39. package/build/lib/core/Type.js +2 -0
  40. package/build/lib/{tspace → core}/index.d.ts +2 -1
  41. package/build/lib/{tspace → core}/index.js +3 -2
  42. package/build/lib/index.d.ts +2 -2
  43. package/build/lib/index.js +2 -2
  44. package/build/lib/utils/index.d.ts +1 -0
  45. package/build/lib/utils/index.js +17 -7
  46. package/package.json +6 -4
  47. package/build/lib/tspace/Schema.d.ts +0 -70
  48. /package/build/lib/{tspace → core}/Abstracts/AbstractBuilder.js +0 -0
  49. /package/build/lib/{tspace → core}/Abstracts/AbstractDB.d.ts +0 -0
  50. /package/build/lib/{tspace → core}/Abstracts/AbstractDB.js +0 -0
  51. /package/build/lib/{tspace → core}/Abstracts/AbstractModel.js +0 -0
  52. /package/build/lib/{tspace → core}/Decorator.d.ts +0 -0
  53. /package/build/lib/{tspace → core}/Handlers/Proxy.d.ts +0 -0
@@ -20,17 +20,22 @@ const AbstractModel_1 = require("./Abstracts/AbstractModel");
20
20
  const Proxy_1 = require("./Handlers/Proxy");
21
21
  const State_1 = require("./Handlers/State");
22
22
  const Relation_1 = require("./Handlers/Relation");
23
+ const Blueprint_1 = require("./Blueprint");
23
24
  let globalSettings = {
24
25
  softDelete: false,
25
26
  uuid: false,
26
27
  timestamp: false,
28
+ logger: false,
27
29
  };
28
30
  /**
29
31
  *
30
32
  * 'Model' class is a representation of a database table
31
33
  * @example
32
- * class User extends Model {}
33
- * new User().findMany().then(users => console.log(users))
34
+ * class User extends Model {
35
+ * ...........
36
+ * }
37
+ * const users = await new User().findMany()
38
+ * console.log(users)
34
39
  */
35
40
  class Model extends AbstractModel_1.AbstractModel {
36
41
  constructor() {
@@ -48,6 +53,19 @@ class Model extends AbstractModel_1.AbstractModel {
48
53
  this.boot();
49
54
  return new Proxy(this, Proxy_1.proxyHandler);
50
55
  }
56
+ /**
57
+ * The 'global' method is used setting global variables in models.
58
+ * @static
59
+ * @param {GlobalSetting} settings
60
+ * @example
61
+ * Model.global({
62
+ * softDelete : true,
63
+ * uuid : true,
64
+ * timestamp : true,
65
+ * logger : true,
66
+ * })
67
+ * @return {void} void
68
+ */
51
69
  static global(settings) {
52
70
  globalSettings = Object.assign({}, globalSettings, settings);
53
71
  return;
@@ -81,7 +99,7 @@ class Model extends AbstractModel_1.AbstractModel {
81
99
  */
82
100
  boot() { }
83
101
  /**
84
- * The "useObserve" pattern refers to a way of handling model events using observer classes.
102
+ * The "useObserve" method is used to pattern refers to a way of handling model events using observer classes.
85
103
  * Model events are triggered when certain actions occur on models,
86
104
  * such as creating, updating, deleting, or saving a record.
87
105
  *
@@ -117,7 +135,39 @@ class Model extends AbstractModel_1.AbstractModel {
117
135
  * }
118
136
  */
119
137
  useObserver(observer) {
120
- this._setState('OBSERVER', observer);
138
+ this.$state.set('OBSERVER', observer);
139
+ return this;
140
+ }
141
+ /**
142
+ * The "useLogger" method is used to keeping query data and changed in models.
143
+ *
144
+ * @type {object} options
145
+ * @property {boolean} options.selected - default is false
146
+ * @property {boolean} options.inserted - default is true
147
+ * @property {boolean} options.updated - default is true
148
+ * @property {boolean} options.deleted - default is true
149
+ * @example
150
+ * class User extends Model {
151
+ * constructor() {
152
+ * super()
153
+ * this.useLogger({
154
+ * selected : true,
155
+ * inserted : true,
156
+ * updated : true,
157
+ * deleted : true,
158
+ * })
159
+ * }
160
+ * }
161
+ * @return {this} this
162
+ */
163
+ useLogger({ selected = false, inserted = true, updated = true, deleted = true } = {}) {
164
+ this.$state.set('LOGGER', true);
165
+ this.$state.set('LOGGER_OPTIONS', {
166
+ selected,
167
+ inserted,
168
+ updated,
169
+ deleted
170
+ });
121
171
  return this;
122
172
  }
123
173
  /**
@@ -129,6 +179,7 @@ class Model extends AbstractModel_1.AbstractModel {
129
179
  * import { Blueprint } from 'tspace-mysql'
130
180
  * class User extends Model {
131
181
  * constructor() {
182
+ * super()
132
183
  * this.useSchema ({
133
184
  * id : new Blueprint().int().notNull().primary().autoIncrement(),
134
185
  * uuid : new Blueprint().varchar(50).null(),
@@ -142,7 +193,7 @@ class Model extends AbstractModel_1.AbstractModel {
142
193
  * @return {this} this
143
194
  */
144
195
  useSchema(schema) {
145
- this._setState('SCHEMA_TABLE', schema);
196
+ this.$state.set('SCHEMA_TABLE', schema);
146
197
  return this;
147
198
  }
148
199
  /**
@@ -154,12 +205,13 @@ class Model extends AbstractModel_1.AbstractModel {
154
205
  * @example
155
206
  * class User extends Model {
156
207
  * constructor() {
208
+ * super()
157
209
  * this.useRegistry()
158
210
  * }
159
211
  * }
160
212
  */
161
213
  useRegistry() {
162
- this._setState('REGISTRY', Object.assign(Object.assign({}, this._getState('REGISTRY')), { '$attach': this._attach, '$detach': this._detach }));
214
+ this.$state.set('REGISTRY', Object.assign(Object.assign({}, this.$state.get('REGISTRY')), { '$attach': this._attach, '$detach': this._detach }));
163
215
  return this;
164
216
  }
165
217
  /**
@@ -168,12 +220,13 @@ class Model extends AbstractModel_1.AbstractModel {
168
220
  * @example
169
221
  * class User extends Model {
170
222
  * constructor() {
223
+ * super()
171
224
  * this.useLoadRelationInRegistry()
172
225
  * }
173
226
  * }
174
227
  */
175
228
  useLoadRelationsInRegistry() {
176
- const relations = this._getState('RELATION').map((r) => String(r.name));
229
+ const relations = this.$state.get('RELATION').map((r) => String(r.name));
177
230
  if (relations.length)
178
231
  this.relations(...Array.from(new Set(relations)));
179
232
  return this;
@@ -186,12 +239,13 @@ class Model extends AbstractModel_1.AbstractModel {
186
239
  * @example
187
240
  * class User extends Model {
188
241
  * constructor() {
242
+ * super()
189
243
  * this.useBuiltInRelationsFunction()
190
244
  * }
191
245
  * }
192
246
  */
193
247
  useBuiltInRelationFunctions() {
194
- this._setState('FUNCTION_RELATION', true);
248
+ this.$state.set('FUNCTION_RELATION', true);
195
249
  return this;
196
250
  }
197
251
  /**
@@ -202,12 +256,13 @@ class Model extends AbstractModel_1.AbstractModel {
202
256
  * @example
203
257
  * class User extends Model {
204
258
  * constructor() {
259
+ * super()
205
260
  * this.usePrimaryKey()
206
261
  * }
207
262
  * }
208
263
  */
209
264
  usePrimaryKey(primary) {
210
- this._setState('PRIMARY_KEY', primary);
265
+ this.$state.set('PRIMARY_KEY', primary);
211
266
  return this;
212
267
  }
213
268
  /**
@@ -219,14 +274,15 @@ class Model extends AbstractModel_1.AbstractModel {
219
274
  * @example
220
275
  * class User extends Model {
221
276
  * constructor() {
277
+ * super()
222
278
  * this.useUUID()
223
279
  * }
224
280
  * }
225
281
  */
226
282
  useUUID(column) {
227
- this._setState('UUID', true);
283
+ this.$state.set('UUID', true);
228
284
  if (column)
229
- this._setState('UUID_FORMAT', column);
285
+ this.$state.set('UUID_FORMAT', column);
230
286
  return this;
231
287
  }
232
288
  /**
@@ -234,7 +290,7 @@ class Model extends AbstractModel_1.AbstractModel {
234
290
  * @return {this} this
235
291
  */
236
292
  useDebug() {
237
- this._setState('DEBUG', true);
293
+ this.$state.set('DEBUG', true);
238
294
  return this;
239
295
  }
240
296
  /**
@@ -244,6 +300,7 @@ class Model extends AbstractModel_1.AbstractModel {
244
300
  * @example
245
301
  * class User extends Model {
246
302
  * constructor() {
303
+ * super()
247
304
  * this.usePattern('camelCase')
248
305
  * }
249
306
  * }
@@ -254,7 +311,7 @@ class Model extends AbstractModel_1.AbstractModel {
254
311
  this.$constants('PATTERN').camelCase
255
312
  ];
256
313
  this._assertError(!allowPattern.includes(pattern), `tspace-mysql support only pattern ["${this.$constants('PATTERN').snake_case}","${this.$constants('PATTERN').camelCase}"]`);
257
- this._setState('PATTERN', pattern);
314
+ this.$state.set('PATTERN', pattern);
258
315
  this._makeTableName();
259
316
  return this;
260
317
  }
@@ -264,12 +321,13 @@ class Model extends AbstractModel_1.AbstractModel {
264
321
  * @example
265
322
  * class User extends Model {
266
323
  * constructor() {
324
+ * super()
267
325
  * this.useCamelCase()
268
326
  * }
269
327
  * }
270
328
  */
271
329
  useCamelCase() {
272
- this._setState('PATTERN', this.$constants('PATTERN').camelCase);
330
+ this.$state.set('PATTERN', this.$constants('PATTERN').camelCase);
273
331
  this._makeTableName();
274
332
  return this;
275
333
  }
@@ -279,12 +337,13 @@ class Model extends AbstractModel_1.AbstractModel {
279
337
  * @example
280
338
  * class User extends Model {
281
339
  * constructor() {
340
+ * super()
282
341
  * this.SnakeCase()
283
342
  * }
284
343
  * }
285
344
  */
286
345
  useSnakeCase() {
287
- this._setState('PATTERN', this.$constants('PATTERN').snake_case);
346
+ this.$state.set('PATTERN', this.$constants('PATTERN').snake_case);
288
347
  this._makeTableName();
289
348
  return this;
290
349
  }
@@ -305,9 +364,9 @@ class Model extends AbstractModel_1.AbstractModel {
305
364
  * }
306
365
  */
307
366
  useSoftDelete(column) {
308
- this._setState('SOFT_DELETE', true);
367
+ this.$state.set('SOFT_DELETE', true);
309
368
  if (column)
310
- this._setState('SOFT_DELETE_FORMAT', column);
369
+ this.$state.set('SOFT_DELETE_FORMAT', column);
311
370
  return this;
312
371
  }
313
372
  /**
@@ -328,9 +387,9 @@ class Model extends AbstractModel_1.AbstractModel {
328
387
  * }
329
388
  */
330
389
  useTimestamp(timestampFormat) {
331
- this._setState('TIMESTAMP', true);
390
+ this.$state.set('TIMESTAMP', true);
332
391
  if (timestampFormat) {
333
- this._setState('TIMESTAMP_FORMAT', {
392
+ this.$state.set('TIMESTAMP_FORMAT', {
334
393
  CREATED_AT: timestampFormat.createdAt,
335
394
  UPDATED_AT: timestampFormat.updatedAt
336
395
  });
@@ -349,7 +408,7 @@ class Model extends AbstractModel_1.AbstractModel {
349
408
  * }
350
409
  */
351
410
  useTable(table) {
352
- this._setState('TABLE_NAME', `\`${table}\``);
411
+ this.$state.set('TABLE_NAME', `\`${table}\``);
353
412
  return this;
354
413
  }
355
414
  /**
@@ -365,7 +424,7 @@ class Model extends AbstractModel_1.AbstractModel {
365
424
  useTableSingular() {
366
425
  var _a;
367
426
  const table = this._classToTableName((_a = this.constructor) === null || _a === void 0 ? void 0 : _a.name, { singular: true });
368
- this._setState('TABLE_NAME', `\`${this._valuePattern(table)}\``);
427
+ this.$state.set('TABLE_NAME', `\`${this._valuePattern(table)}\``);
369
428
  return this;
370
429
  }
371
430
  /**
@@ -381,7 +440,7 @@ class Model extends AbstractModel_1.AbstractModel {
381
440
  useTablePlural() {
382
441
  var _a;
383
442
  const table = this._classToTableName((_a = this.constructor) === null || _a === void 0 ? void 0 : _a.name);
384
- this._setState('TABLE_NAME', `\`${this._valuePattern(table)}\``);
443
+ this.$state.set('TABLE_NAME', `\`${this._valuePattern(table)}\``);
385
444
  return this;
386
445
  }
387
446
  /**
@@ -416,8 +475,8 @@ class Model extends AbstractModel_1.AbstractModel {
416
475
  * }
417
476
  */
418
477
  useValidationSchema(schema) {
419
- this._setState('VALIDATE_SCHEMA', true);
420
- this._setState('VALIDATE_SCHEMA_DEFINED', schema);
478
+ this.$state.set('VALIDATE_SCHEMA', true);
479
+ this.$state.set('VALIDATE_SCHEMA_DEFINED', schema);
421
480
  return this;
422
481
  }
423
482
  /**
@@ -469,10 +528,41 @@ class Model extends AbstractModel_1.AbstractModel {
469
528
  for (const func of arrayFunctions) {
470
529
  if (typeof func !== "function")
471
530
  throw new Error(`this '${func}' is not a function`);
472
- this._setState('HOOKS', [...this._getState('HOOKS'), func]);
531
+ this.$state.set('HOOKS', [...this.$state.get('HOOKS'), func]);
473
532
  }
474
533
  return this;
475
534
  }
535
+ /**
536
+ * The "column" method is used get column from your schema.
537
+ * @param {string} column
538
+ * @return {string}
539
+ */
540
+ column(column) {
541
+ return column;
542
+ }
543
+ /**
544
+ * The "beforeCreatingTable" method is used exection function when creating the table.
545
+ * @param {Function} fn functions for executing before creating the table
546
+ * @return {this} this
547
+ * @example
548
+ * class User extends Model {
549
+ * constructor() {
550
+ * this.beforeCreatingTable(async () => {
551
+ * await new User()
552
+ * .create({
553
+ * ...columns
554
+ * })
555
+ * .save()
556
+ * })
557
+ * }
558
+ * }
559
+ */
560
+ beforeCreatingTable(fn) {
561
+ if (!(fn instanceof Function))
562
+ this._assertError(`This '${fn}' is not a function`);
563
+ this.$state.set('BEFORE_CREATING_TABLE', fn);
564
+ return this;
565
+ }
476
566
  /**
477
567
  * exceptColumns for method except
478
568
  * @override
@@ -480,20 +570,20 @@ class Model extends AbstractModel_1.AbstractModel {
480
570
  */
481
571
  exceptColumns() {
482
572
  return __awaiter(this, void 0, void 0, function* () {
483
- const excepts = this._getState('EXCEPTS');
573
+ const excepts = this.$state.get('EXCEPTS');
484
574
  const hasDot = excepts.some((except) => /\./.test(except));
485
575
  const names = excepts.map((except) => {
486
576
  if (/\./.test(except))
487
577
  return except.split('.')[0];
488
578
  return null;
489
579
  }).filter((d) => d != null);
490
- const tableNames = names.length ? [...new Set(names)] : [this._getState('TABLE_NAME')];
580
+ const tableNames = names.length ? [...new Set(names)] : [this.$state.get('TABLE_NAME')];
491
581
  const removeExcepts = [];
492
582
  const schemaColumns = this.getSchemaModel();
493
583
  for (const tableName of tableNames) {
494
584
  const isHasSchema = [
495
585
  schemaColumns != null,
496
- tableName.replace(/`/g, '') === this._getState('TABLE_NAME').replace(/`/g, '')
586
+ tableName.replace(/`/g, '') === this.$state.get('TABLE_NAME').replace(/`/g, '')
497
587
  ].every(d => d);
498
588
  if (isHasSchema) {
499
589
  const columns = Object.keys(schemaColumns);
@@ -540,8 +630,8 @@ class Model extends AbstractModel_1.AbstractModel {
540
630
  buildMethodRelation(name, callback) {
541
631
  var _a, _b;
542
632
  this.relations(name);
543
- const relation = this._getState('RELATIONS').find((data) => data.name === name);
544
- this._assertError(relation == null, `This Relation "${name}" not be register in Model "${(_a = this.constructor) === null || _a === void 0 ? void 0 : _a.name}"`);
633
+ const relation = this.$state.get('RELATIONS').find((data) => data.name === name);
634
+ this._assertError(relation == null, `This Relation "${String(name)}" not be register in Model "${(_a = this.constructor) === null || _a === void 0 ? void 0 : _a.name}"`);
545
635
  const relationHasExists = (_b = Object.values(this.$constants('RELATIONSHIP'))) === null || _b === void 0 ? void 0 : _b.includes(relation.relation);
546
636
  this._assertError(!relationHasExists, `Unknown Relationship in [${this.$constants('RELATIONSHIP')}] !`);
547
637
  if (callback == null) {
@@ -553,6 +643,177 @@ class Model extends AbstractModel_1.AbstractModel {
553
643
  }
554
644
  /**
555
645
  *
646
+ * @override
647
+ * @param {string[]} ...columns
648
+ * @return {this} this
649
+ */
650
+ select(...columns) {
651
+ if (!columns.length) {
652
+ this.$state.set('SELECT', ['*']);
653
+ return this;
654
+ }
655
+ let select = columns.map((c) => {
656
+ const column = String(c);
657
+ if (column === '*' || (column.includes('*') && /\./.test(column)))
658
+ return column;
659
+ if (column.includes(this.$constants('RAW')))
660
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '').replace(/'/g, '');
661
+ return this.bindColumn(column);
662
+ });
663
+ select = [...this.$state.get('SELECT'), ...select];
664
+ if (this.$state.get('DISTINCT') && select.length) {
665
+ select[0] = String(select[0]).includes(this.$constants('DISTINCT'))
666
+ ? select[0]
667
+ : `${this.$constants('DISTINCT')} ${select[0]}`;
668
+ }
669
+ this.$state.set('SELECT', select);
670
+ return this;
671
+ }
672
+ /**
673
+ *
674
+ * @override
675
+ * @param {...string} columns
676
+ * @return {this} this
677
+ */
678
+ except(...columns) {
679
+ if (!columns.length)
680
+ return this;
681
+ const exceptColumns = this.$state.get('EXCEPTS');
682
+ this.$state.set('EXCEPTS', [
683
+ ...columns,
684
+ ...exceptColumns
685
+ ]);
686
+ return this;
687
+ }
688
+ /**
689
+ *
690
+ * @override
691
+ * @return {this} this
692
+ */
693
+ exceptTimestamp() {
694
+ let excepts = [];
695
+ if (this.$state.get('SOFT_DELETE')) {
696
+ const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
697
+ excepts = [
698
+ ...excepts,
699
+ deletedAt
700
+ ];
701
+ }
702
+ const updatedAt = this._valuePattern(this.$state.get('TIMESTAMP_FORMAT').UPDATED_AT);
703
+ const createdAt = this._valuePattern(this.$state.get('TIMESTAMP_FORMAT').CREATED_AT);
704
+ excepts = [
705
+ ...excepts,
706
+ createdAt,
707
+ updatedAt
708
+ ];
709
+ const exceptColumns = this.$state.get('EXCEPTS');
710
+ this.$state.set('EXCEPTS', [
711
+ ...excepts,
712
+ ...exceptColumns
713
+ ]);
714
+ return this;
715
+ }
716
+ /**
717
+ *
718
+ * @override
719
+ * @param {string} column
720
+ * @param {string?} order by default order = 'asc' but you can used 'asc' or 'desc'
721
+ * @return {this}
722
+ */
723
+ orderBy(column, order = 'ASC') {
724
+ let c = String(column);
725
+ if (c.includes(this.$constants('RAW')) || /\./.test(c)) {
726
+ c = c === null || c === void 0 ? void 0 : c.replace(this.$constants('RAW'), '');
727
+ if (/\./.test(c))
728
+ c = this.bindColumn(c);
729
+ }
730
+ this.$state.set('ORDER_BY', [
731
+ ...this.$state.get('ORDER_BY'),
732
+ `\`${c}\` ${order.toUpperCase()}`
733
+ ]);
734
+ return this;
735
+ }
736
+ /**
737
+ *
738
+ * @override
739
+ * @param {string?} columns [column=id]
740
+ * @return {this}
741
+ */
742
+ latest(...columns) {
743
+ let orderBy = '`id`';
744
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
745
+ orderBy = columns.map(c => {
746
+ if (/\./.test(c))
747
+ return this.bindColumn(c);
748
+ if (c.includes(this.$constants('RAW')))
749
+ return c === null || c === void 0 ? void 0 : c.replace(this.$constants('RAW'), '');
750
+ return `\`${c}\``;
751
+ }).join(', ');
752
+ }
753
+ this.$state.set('ORDER_BY', [
754
+ ...this.$state.get('ORDER_BY'),
755
+ `${orderBy} ${this.$constants('DESC')}`
756
+ ]);
757
+ return this;
758
+ }
759
+ /**
760
+ *
761
+ * @override
762
+ * @param {string?} columns [column=id]
763
+ * @return {this}
764
+ */
765
+ oldest(...columns) {
766
+ let orderBy = '`id`';
767
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
768
+ orderBy = columns.map(c => {
769
+ if (/\./.test(c))
770
+ return this.bindColumn(c);
771
+ if (c.includes(this.$constants('RAW')))
772
+ return c === null || c === void 0 ? void 0 : c.replace(this.$constants('RAW'), '');
773
+ return `\`${c}\``;
774
+ }).join(', ');
775
+ }
776
+ this.$state.set('ORDER_BY', [
777
+ ...this.$state.get('ORDER_BY'),
778
+ `${orderBy} ${this.$constants('ASC')}`
779
+ ]);
780
+ return this;
781
+ }
782
+ /**
783
+ *
784
+ * @override
785
+ * @param {string?} columns [column=id]
786
+ * @return {this}
787
+ */
788
+ groupBy(...columns) {
789
+ let groupBy = 'id';
790
+ if (columns === null || columns === void 0 ? void 0 : columns.length) {
791
+ groupBy = columns.map(column => {
792
+ if (column.includes(this.$constants('RAW')))
793
+ return column === null || column === void 0 ? void 0 : column.replace(this.$constants('RAW'), '');
794
+ return `\`${column}\``;
795
+ }).join(', ');
796
+ }
797
+ this.$state.set('GROUP_BY', `${this.$constants('GROUP_BY')} ${groupBy}`);
798
+ return this;
799
+ }
800
+ /**
801
+ * @override
802
+ * @param {string} column
803
+ * @return {string} return table.column
804
+ */
805
+ bindColumn(column, pattern = true) {
806
+ if (!/\./.test(column)) {
807
+ column = pattern ? this._valuePattern(column) : column;
808
+ return `\`${this.getTableName().replace(/`/g, '')}\`.\`${column.replace(/`/g, '')}\``;
809
+ }
810
+ let [table, c] = column.split('.');
811
+ c = pattern ? this._valuePattern(c) : c;
812
+ return `\`${table.replace(/`/g, '')}\`.\`${c.replace(/`/g, '')}\``;
813
+ }
814
+ /**
815
+ *
816
+ * @override
556
817
  * The 'makeSelectStatement' method is used to make select statement.
557
818
  * @return {Promise<string>} string
558
819
  */
@@ -578,6 +839,7 @@ class Model extends AbstractModel_1.AbstractModel {
578
839
  }
579
840
  /**
580
841
  *
842
+ * @override
581
843
  * The 'makeInsertStatement' method is used to make insert table statement.
582
844
  * @return {Promise<string>} string
583
845
  */
@@ -590,20 +852,21 @@ class Model extends AbstractModel_1.AbstractModel {
590
852
  `\`${this.getTableName()}\``,
591
853
  `(${columns.join(', ')})`,
592
854
  `${this.$constants('VALUES')}`,
593
- `(${Array(columns.length).fill('?').join(' , ')})`
855
+ `(${Array(columns.length).fill('`?`').join(' , ')})`
594
856
  ].join(' ');
595
857
  };
596
858
  if (schemaModel == null) {
597
859
  const schemaTable = yield this.getSchema();
598
- const columns = schemaTable.map(column => `\`${column.Field}\``);
860
+ const columns = schemaTable.map(column => this.bindColumn(column.Field));
599
861
  return makeStatement(columns);
600
862
  }
601
- const columns = Object.keys(schemaModel).map((column) => `\`${column}\``);
863
+ const columns = Object.keys(schemaModel).map((column) => this.bindColumn(column));
602
864
  return makeStatement(columns);
603
865
  });
604
866
  }
605
867
  /**
606
868
  *
869
+ * @override
607
870
  * The 'makeUpdateStatement' method is used to make update table statement.
608
871
  * @return {Promise<string>} string
609
872
  */
@@ -615,20 +878,23 @@ class Model extends AbstractModel_1.AbstractModel {
615
878
  `${this.$constants('UPDATE')}`,
616
879
  `\`${this.getTableName()}\``,
617
880
  `${this.$constants('SET')}`,
618
- `(${columns.join(', ')})`
881
+ `(${columns.join(', ')})`,
882
+ `${this.$constants('WHERE')}`,
883
+ `${this.bindColumn('id')} = '?'`
619
884
  ].join(' ');
620
885
  };
621
886
  if (schemaModel == null) {
622
887
  const schemaTable = yield this.getSchema();
623
- const columns = schemaTable.map(column => `\`${column.Field}\` = ?`);
888
+ const columns = schemaTable.map(column => `${this.bindColumn(column.Field)} = '?'`);
624
889
  return makeStatement(columns);
625
890
  }
626
- const columns = Object.keys(schemaModel).map((column) => `\`${column}\` = ?`);
891
+ const columns = Object.keys(schemaModel).map((column) => `${this.bindColumn(column)} = '?'`);
627
892
  return makeStatement(columns);
628
893
  });
629
894
  }
630
895
  /**
631
896
  *
897
+ * @override
632
898
  * The 'makeDeleteStatement' method is used to make delete statement.
633
899
  * @return {Promise<string>} string
634
900
  */
@@ -640,7 +906,7 @@ class Model extends AbstractModel_1.AbstractModel {
640
906
  `${this.$constants('FROM')}`,
641
907
  `\`${this.getTableName()}\``,
642
908
  `${this.$constants('WHERE')}`,
643
- `?where_expression`
909
+ `${this.bindColumn('id')} = \`?\``
644
910
  ].join(' ');
645
911
  };
646
912
  return makeStatement();
@@ -648,10 +914,11 @@ class Model extends AbstractModel_1.AbstractModel {
648
914
  }
649
915
  /**
650
916
  *
651
- * The 'makeCreateStatement' method is used to make create table statement.
917
+ * @override
918
+ * The 'makeCreateTableStatement' method is used to make create table statement.
652
919
  * @return {Promise<string>} string
653
920
  */
654
- makeCreateStatement() {
921
+ makeCreateTableStatement() {
655
922
  return __awaiter(this, void 0, void 0, function* () {
656
923
  const schemaModel = this.getSchemaModel();
657
924
  const makeStatement = (columns) => {
@@ -699,54 +966,84 @@ class Model extends AbstractModel_1.AbstractModel {
699
966
  * @return {Model} Model
700
967
  */
701
968
  copyModel(instance, options) {
702
- this._assertError(!(instance instanceof Model), 'Value is not a instanceof Model');
969
+ this._assertError(!(instance instanceof Model), 'This instance is not a instanceof Model');
703
970
  const copy = Object.fromEntries(instance.$state.get());
704
971
  const newInstance = new Model();
705
972
  newInstance.$state.clone(copy);
706
973
  newInstance.$state.set('SAVE', '');
707
974
  newInstance.$state.set('DEBUG', false);
708
- if ((options === null || options === void 0 ? void 0 : options.insert) == null)
975
+ newInstance.$state.set('LOGGER', false);
976
+ if ((options === null || options === void 0 ? void 0 : options.insert) == null || !options.insert)
709
977
  newInstance.$state.set('INSERT', '');
710
- if ((options === null || options === void 0 ? void 0 : options.update) == null)
978
+ if ((options === null || options === void 0 ? void 0 : options.update) == null || !options.update)
711
979
  newInstance.$state.set('UPDATE', '');
712
- if ((options === null || options === void 0 ? void 0 : options.delete) == null)
980
+ if ((options === null || options === void 0 ? void 0 : options.delete) == null || !options.delete)
713
981
  newInstance.$state.set('DELETE', '');
714
- if ((options === null || options === void 0 ? void 0 : options.where) == null)
982
+ if ((options === null || options === void 0 ? void 0 : options.where) == null || !options.where)
715
983
  newInstance.$state.set('WHERE', []);
716
- if ((options === null || options === void 0 ? void 0 : options.limit) == null)
984
+ if ((options === null || options === void 0 ? void 0 : options.limit) == null || !options.limit)
717
985
  newInstance.$state.set('LIMIT', '');
718
- if ((options === null || options === void 0 ? void 0 : options.offset) == null)
986
+ if ((options === null || options === void 0 ? void 0 : options.offset) == null || !options.offset)
719
987
  newInstance.$state.set('OFFSET', '');
720
- if ((options === null || options === void 0 ? void 0 : options.groupBy) == null)
988
+ if ((options === null || options === void 0 ? void 0 : options.groupBy) == null || !options.groupBy)
721
989
  newInstance.$state.set('GROUP_BY', '');
722
- if ((options === null || options === void 0 ? void 0 : options.orderBy) == null)
723
- newInstance.$state.set('ORDER_BY', '');
724
- if ((options === null || options === void 0 ? void 0 : options.select) == null)
990
+ if ((options === null || options === void 0 ? void 0 : options.orderBy) == null || !options.orderBy)
991
+ newInstance.$state.set('ORDER_BY', []);
992
+ if ((options === null || options === void 0 ? void 0 : options.select) == null || !options.select)
725
993
  newInstance.$state.set('SELECT', []);
726
- if ((options === null || options === void 0 ? void 0 : options.join) == null)
994
+ if ((options === null || options === void 0 ? void 0 : options.join) == null || !options.join)
727
995
  newInstance.$state.set('JOIN', []);
996
+ if ((options === null || options === void 0 ? void 0 : options.having) == null || !options.having)
997
+ newInstance.$state.set('HAVING', '');
728
998
  return newInstance;
729
999
  }
730
1000
  /**
731
1001
  *
732
1002
  * execute the query using raw sql syntax
733
- * @override method
1003
+ * @override
734
1004
  * @param {string} sql
735
1005
  * @return {this} this
736
1006
  */
737
1007
  _queryStatement(sql) {
738
- var _a;
739
1008
  return __awaiter(this, void 0, void 0, function* () {
1009
+ var _a;
740
1010
  try {
741
- if (this._getState('DEBUG'))
1011
+ if (this.$state.get('DEBUG'))
742
1012
  this.$utils.consoleDebug(sql);
743
- return yield this.$pool.query(sql);
1013
+ if (this.$state.get('LOGGER')) {
1014
+ const selectRegex = /^SELECT\b/i;
1015
+ const loggerOptions = this.$state.get('LOGGER_OPTIONS');
1016
+ if (selectRegex.test(sql) && loggerOptions.selected) {
1017
+ yield this._checkTableLoggerIsExists().catch(err => null);
1018
+ const result = yield this.$pool.query(sql);
1019
+ yield new DB_1.DB(this.$state.get('TABLE_LOGGER'))
1020
+ .create({
1021
+ uuid: DB_1.DB.generateUUID(),
1022
+ model: this.$state.get('MODEL_NAME'),
1023
+ query: sql,
1024
+ action: 'SELECT',
1025
+ data: result.length
1026
+ ? JSON.stringify(result.length === 1 ? result[0] : result)
1027
+ : null,
1028
+ changed: null,
1029
+ createdAt: this.$utils.timestamp(),
1030
+ updatedAt: this.$utils.timestamp()
1031
+ })
1032
+ .void()
1033
+ .save()
1034
+ .catch(_ => null);
1035
+ return result;
1036
+ }
1037
+ }
1038
+ const result = yield this.$pool.query(sql);
1039
+ return result;
744
1040
  }
745
1041
  catch (error) {
746
- if ((_a = this._getState('JOIN')) === null || _a === void 0 ? void 0 : _a.length)
1042
+ if ((_a = this.$state.get('JOIN')) === null || _a === void 0 ? void 0 : _a.length)
747
1043
  throw error;
748
- yield this._checkSchemaOrNextError(error, Number(this._getState('RETRY')));
749
- this._setState('RETRY', Number(this._getState('RETRY')) + 1);
1044
+ const retry = Number(this.$state.get('RETRY'));
1045
+ yield this._checkSchemaOrNextError(error, retry);
1046
+ this.$state.set('RETRY', retry + 1);
750
1047
  return yield this._queryStatement(sql);
751
1048
  }
752
1049
  });
@@ -754,30 +1051,138 @@ class Model extends AbstractModel_1.AbstractModel {
754
1051
  /**
755
1052
  *
756
1053
  * execute the query using raw sql syntax actions for insert update and delete
757
- * @override method
1054
+ * @override
758
1055
  * @param {Object} actions
759
1056
  * @property {Function} actions.sqlresult
760
1057
  * @property {Function} actions.returnId
761
1058
  * @return {this} this
762
1059
  */
763
- _actionStatement({ sql, returnId = false }) {
764
- var _a;
765
- return __awaiter(this, void 0, void 0, function* () {
1060
+ _actionStatement(_a) {
1061
+ return __awaiter(this, arguments, void 0, function* ({ sql, returnId = false }) {
1062
+ var _b;
766
1063
  try {
767
- if (this._getState('DEBUG'))
1064
+ if (this.$state.get('DEBUG'))
768
1065
  this.$utils.consoleDebug(sql);
769
- if (returnId) {
770
- const result = yield this.$pool.query(sql);
771
- return [result.affectedRows, result.insertId];
1066
+ if (this.$state.get('LOGGER')) {
1067
+ const updateRegex = /^UPDATE\b/i;
1068
+ const insertRegex = /^INSERT\b/i;
1069
+ const deleteRegex = /^DELETE\b/i;
1070
+ const loggerOptions = this.$state.get('LOGGER_OPTIONS');
1071
+ if (insertRegex.test(sql) && loggerOptions.inserted) {
1072
+ yield this._checkTableLoggerIsExists().catch(_ => null);
1073
+ const result = yield this.$pool.query(sql);
1074
+ const changed = yield new Model()
1075
+ .copyModel(this, {
1076
+ where: false,
1077
+ orderBy: true,
1078
+ limit: true
1079
+ })
1080
+ .where('id', result.insertId)
1081
+ .disableVoid()
1082
+ .get();
1083
+ yield new DB_1.DB(this.$state.get('TABLE_LOGGER'))
1084
+ .create({
1085
+ uuid: DB_1.DB.generateUUID(),
1086
+ model: this.$state.get('MODEL_NAME'),
1087
+ query: sql,
1088
+ action: 'INSERTD',
1089
+ data: changed.length
1090
+ ? JSON.stringify(changed.length === 1 ? changed[0] : changed)
1091
+ : null,
1092
+ changed: null,
1093
+ createdAt: this.$utils.timestamp(),
1094
+ updatedAt: this.$utils.timestamp()
1095
+ })
1096
+ .void()
1097
+ .save()
1098
+ .catch(_ => null);
1099
+ if (returnId)
1100
+ return [result.affectedRows, result.insertId];
1101
+ return result.affectedRows;
1102
+ }
1103
+ if (updateRegex.test(sql) && loggerOptions.updated) {
1104
+ yield this._checkTableLoggerIsExists().catch(err => null);
1105
+ const createdAt = this.$utils.timestamp();
1106
+ const data = yield new Model().copyModel(this, {
1107
+ where: true,
1108
+ orderBy: true,
1109
+ limit: true
1110
+ })
1111
+ .disableVoid()
1112
+ .get();
1113
+ const result = yield this.$pool.query(sql);
1114
+ const changed = yield new Model().copyModel(this, {
1115
+ where: true,
1116
+ orderBy: true,
1117
+ limit: true
1118
+ })
1119
+ .disableSoftDelete()
1120
+ .disableVoid()
1121
+ .get();
1122
+ const updatedAt = this.$utils.timestamp();
1123
+ yield new DB_1.DB(this.$state.get('TABLE_LOGGER'))
1124
+ .create({
1125
+ uuid: DB_1.DB.generateUUID(),
1126
+ model: this.$state.get('MODEL_NAME'),
1127
+ query: sql,
1128
+ action: 'UPDATED',
1129
+ data: data.length
1130
+ ? JSON.stringify(data.length === 1 ? data[0] : data)
1131
+ : null,
1132
+ changed: changed.length
1133
+ ? JSON.stringify(changed.length === 1 ? changed[0] : changed)
1134
+ : null,
1135
+ createdAt,
1136
+ updatedAt
1137
+ })
1138
+ .void()
1139
+ .save()
1140
+ .catch(_ => null);
1141
+ if (returnId)
1142
+ return [result.affectedRows, result.insertId];
1143
+ return result.affectedRows;
1144
+ }
1145
+ if (deleteRegex.test(sql) && loggerOptions.deleted) {
1146
+ yield this._checkTableLoggerIsExists().catch(err => null);
1147
+ const data = yield new Model().copyModel(this, {
1148
+ where: true,
1149
+ orderBy: true,
1150
+ limit: true
1151
+ })
1152
+ .disableVoid()
1153
+ .get();
1154
+ const result = yield this.$pool.query(sql);
1155
+ yield new DB_1.DB(this.$state.get('TABLE_LOGGER'))
1156
+ .create({
1157
+ uuid: DB_1.DB.generateUUID(),
1158
+ model: this.$state.get('MODEL_NAME'),
1159
+ query: sql,
1160
+ action: 'DELETED',
1161
+ data: data.length
1162
+ ? JSON.stringify(data.length === 1 ? data[0] : data)
1163
+ : null,
1164
+ changed: null,
1165
+ createdAt: this.$utils.timestamp(),
1166
+ updatedAt: this.$utils.timestamp()
1167
+ })
1168
+ .void()
1169
+ .save()
1170
+ .catch(_ => null);
1171
+ if (returnId)
1172
+ return [result.affectedRows, result.insertId];
1173
+ return result.affectedRows;
1174
+ }
772
1175
  }
773
- const { affectedRows: result } = yield this.$pool.query(sql);
774
- return result;
1176
+ const result = yield this.$pool.query(sql);
1177
+ if (returnId)
1178
+ return [result.affectedRows, result.insertId];
1179
+ return result.affectedRows;
775
1180
  }
776
1181
  catch (error) {
777
- if ((_a = this._getState('JOIN')) === null || _a === void 0 ? void 0 : _a.length)
1182
+ if ((_b = this.$state.get('JOIN')) === null || _b === void 0 ? void 0 : _b.length)
778
1183
  throw error;
779
- yield this._checkSchemaOrNextError(error, Number(this._getState('RETRY')));
780
- this._setState('RETRY', Number(this._getState('RETRY')) + 1);
1184
+ yield this._checkSchemaOrNextError(error, Number(this.$state.get('RETRY')));
1185
+ this.$state.set('RETRY', Number(this.$state.get('RETRY')) + 1);
781
1186
  return yield this._actionStatement({
782
1187
  sql,
783
1188
  returnId
@@ -791,7 +1196,7 @@ class Model extends AbstractModel_1.AbstractModel {
791
1196
  * @return {this} this
792
1197
  */
793
1198
  table(table) {
794
- this._setState('TABLE_NAME', `\`${table}\``);
1199
+ this.$state.set('TABLE_NAME', `\`${table}\``);
795
1200
  return this;
796
1201
  }
797
1202
  /**
@@ -800,7 +1205,16 @@ class Model extends AbstractModel_1.AbstractModel {
800
1205
  * @return {this} this
801
1206
  */
802
1207
  disableSoftDelete(condition = false) {
803
- this._setState('SOFT_DELETE', condition);
1208
+ this.$state.set('SOFT_DELETE', condition);
1209
+ return this;
1210
+ }
1211
+ /**
1212
+ * The 'disableVoid' method is used to ignore void.
1213
+ *
1214
+ * @return {this} this
1215
+ */
1216
+ disableVoid() {
1217
+ this.$state.set('VOID', false);
804
1218
  return this;
805
1219
  }
806
1220
  /**
@@ -809,7 +1223,7 @@ class Model extends AbstractModel_1.AbstractModel {
809
1223
  * @return {this} this
810
1224
  */
811
1225
  ignoreSoftDelete(condition = false) {
812
- this._setState('SOFT_DELETE', condition);
1226
+ this.$state.set('SOFT_DELETE', condition);
813
1227
  return this;
814
1228
  }
815
1229
  /**
@@ -818,7 +1232,7 @@ class Model extends AbstractModel_1.AbstractModel {
818
1232
  * @return {this} this
819
1233
  */
820
1234
  registry(func) {
821
- this._setState('REGISTRY', Object.assign(Object.assign({}, func), { attach: this._attach, detach: this._detach }));
1235
+ this.$state.set('REGISTRY', Object.assign(Object.assign({}, func), { attach: this._attach, detach: this._detach }));
822
1236
  return this;
823
1237
  }
824
1238
  /**
@@ -849,7 +1263,9 @@ class Model extends AbstractModel_1.AbstractModel {
849
1263
  */
850
1264
  with(...nameRelations) {
851
1265
  var _a;
852
- this._setState('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'default'));
1266
+ if (!nameRelations.length)
1267
+ return this;
1268
+ this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'default'));
853
1269
  return this;
854
1270
  }
855
1271
  /**
@@ -862,7 +1278,9 @@ class Model extends AbstractModel_1.AbstractModel {
862
1278
  */
863
1279
  withAll(...nameRelations) {
864
1280
  var _a;
865
- this._setState('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'all'));
1281
+ if (!nameRelations.length)
1282
+ return this;
1283
+ this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'all'));
866
1284
  return this;
867
1285
  }
868
1286
  /**
@@ -875,7 +1293,9 @@ class Model extends AbstractModel_1.AbstractModel {
875
1293
  */
876
1294
  withCount(...nameRelations) {
877
1295
  var _a;
878
- this._setState('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'count'));
1296
+ if (!nameRelations.length)
1297
+ return this;
1298
+ this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'count'));
879
1299
  return this;
880
1300
  }
881
1301
  /**
@@ -888,7 +1308,9 @@ class Model extends AbstractModel_1.AbstractModel {
888
1308
  */
889
1309
  withTrashed(...nameRelations) {
890
1310
  var _a;
891
- this._setState('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'trashed'));
1311
+ if (!nameRelations.length)
1312
+ return this;
1313
+ this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'trashed'));
892
1314
  return this;
893
1315
  }
894
1316
  /**
@@ -919,8 +1341,10 @@ class Model extends AbstractModel_1.AbstractModel {
919
1341
  */
920
1342
  withExists(...nameRelations) {
921
1343
  var _a;
922
- this._setState('RELATIONS_EXISTS', true);
923
- this._setState('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'exists'));
1344
+ if (!nameRelations.length)
1345
+ return this;
1346
+ this.$state.set('RELATIONS_EXISTS', true);
1347
+ this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'exists'));
924
1348
  return this;
925
1349
  }
926
1350
  /**
@@ -1357,7 +1781,8 @@ class Model extends AbstractModel_1.AbstractModel {
1357
1781
  */
1358
1782
  onlyTrashed() {
1359
1783
  this.disableSoftDelete();
1360
- this.whereNotNull(this._valuePattern(this._getState('SOFT_DELETE_FORMAT')));
1784
+ const column = String(this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT')));
1785
+ this.whereNotNull(column);
1361
1786
  return this;
1362
1787
  }
1363
1788
  /**
@@ -1377,17 +1802,17 @@ class Model extends AbstractModel_1.AbstractModel {
1377
1802
  restore() {
1378
1803
  return __awaiter(this, void 0, void 0, function* () {
1379
1804
  this.disableSoftDelete();
1380
- const updatedAt = this._valuePattern(this._getState('TIMESTAMP_FORMAT').UPDATED_AT);
1381
- const deletedAt = this._valuePattern(this._getState('SOFT_DELETE_FORMAT'));
1382
- const query = this._getState('TIMESTAMP')
1805
+ const updatedAt = this._valuePattern(this.$state.get('TIMESTAMP_FORMAT').UPDATED_AT);
1806
+ const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
1807
+ const query = this.$state.get('TIMESTAMP')
1383
1808
  ? `${deletedAt} = NULL , ${updatedAt} = '${this.$utils.timestamp()}'`
1384
1809
  : `${deletedAt} = NULL`;
1385
- this._setState('UPDATE', [
1810
+ this.$state.set('UPDATE', [
1386
1811
  `${this.$constants('UPDATE')}`,
1387
- `${this._getState('TABLE_NAME')}`,
1812
+ `${this.$state.get('TABLE_NAME')}`,
1388
1813
  `SET ${query}`
1389
1814
  ].join(' '));
1390
- this._setState('SAVE', 'UPDATE');
1815
+ this.$state.set('SAVE', 'UPDATE');
1391
1816
  return yield this.save();
1392
1817
  });
1393
1818
  }
@@ -1406,15 +1831,9 @@ class Model extends AbstractModel_1.AbstractModel {
1406
1831
  toTableNameAndColumn(column) {
1407
1832
  return `\`${this.getTableName()}\`.\`${this._valuePattern(column)}\``;
1408
1833
  }
1409
- _columnPattern(column) {
1410
- if (column.startsWith(this.$constants('RAW'))) {
1411
- return column.replace(`${this.$constants('RAW')} `, '').replace(this.$constants('RAW'), '');
1412
- }
1413
- return this._valuePattern(column);
1414
- }
1415
1834
  /**
1416
- * @override Method
1417
- * @param {string} column if arguments is object
1835
+ * @override
1836
+ * @param {string | K} column if arguments is object
1418
1837
  * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
1419
1838
  * @param {any?} value
1420
1839
  * @return {this} this
@@ -1423,15 +1842,15 @@ class Model extends AbstractModel_1.AbstractModel {
1423
1842
  if (typeof column === 'object' && column !== null && !Array.isArray(column)) {
1424
1843
  return this.whereObject(column);
1425
1844
  }
1426
- column = this._columnPattern(String(column));
1845
+ const c = this._columnPattern(String(column));
1427
1846
  [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
1428
1847
  value = this.$utils.escape(value);
1429
1848
  value = this._valueTrueFalse(value);
1430
- this._setState('WHERE', [
1431
- ...this._getState('WHERE'),
1849
+ this.$state.set('WHERE', [
1850
+ ...this.$state.get('WHERE'),
1432
1851
  [
1433
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1434
- `${this.bindColumn(String(column))}`,
1852
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
1853
+ `${this.bindColumn(String(c))}`,
1435
1854
  `${operator}`,
1436
1855
  `${this._checkValueHasRaw(value)}`
1437
1856
  ].join(' ')
@@ -1439,7 +1858,7 @@ class Model extends AbstractModel_1.AbstractModel {
1439
1858
  return this;
1440
1859
  }
1441
1860
  /**
1442
- * @override Method
1861
+ * @override
1443
1862
  * @param {string} column
1444
1863
  * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
1445
1864
  * @param {any?} value
@@ -1447,14 +1866,14 @@ class Model extends AbstractModel_1.AbstractModel {
1447
1866
  */
1448
1867
  orWhere(column, operator, value) {
1449
1868
  [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
1450
- column = this._columnPattern(String(column));
1869
+ const c = this._columnPattern(String(column));
1451
1870
  value = this.$utils.escape(value);
1452
1871
  value = this._valueTrueFalse(value);
1453
- this._setState('WHERE', [
1454
- ...this._getState('WHERE'),
1872
+ this.$state.set('WHERE', [
1873
+ ...this.$state.get('WHERE'),
1455
1874
  [
1456
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1457
- `${this.bindColumn(String(column))}`,
1875
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
1876
+ `${this.bindColumn(String(c))}`,
1458
1877
  `${operator}`,
1459
1878
  `${this._checkValueHasRaw(value)}`
1460
1879
  ].join(' ')
@@ -1462,7 +1881,7 @@ class Model extends AbstractModel_1.AbstractModel {
1462
1881
  return this;
1463
1882
  }
1464
1883
  /**
1465
- * @override Method
1884
+ * @override
1466
1885
  * @param {Object} columns
1467
1886
  * @return {this}
1468
1887
  */
@@ -1471,10 +1890,10 @@ class Model extends AbstractModel_1.AbstractModel {
1471
1890
  column = this._columnPattern(String(column));
1472
1891
  const operator = '=';
1473
1892
  const value = this.$utils.escape(columns[column]);
1474
- this._setState('WHERE', [
1475
- ...this._getState('WHERE'),
1893
+ this.$state.set('WHERE', [
1894
+ ...this.$state.get('WHERE'),
1476
1895
  [
1477
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1896
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
1478
1897
  `${this.bindColumn(String(column))}`,
1479
1898
  `${operator}`,
1480
1899
  `${this._checkValueHasRaw(value)}`
@@ -1484,7 +1903,7 @@ class Model extends AbstractModel_1.AbstractModel {
1484
1903
  return this;
1485
1904
  }
1486
1905
  /**
1487
- * @override Method
1906
+ * @override
1488
1907
  * @param {string} column
1489
1908
  * @param {object} property object { key , value , operator }
1490
1909
  * @property {string} property.key
@@ -1495,12 +1914,12 @@ class Model extends AbstractModel_1.AbstractModel {
1495
1914
  whereJSON(column, { key, value, operator }) {
1496
1915
  value = this.$utils.escape(value);
1497
1916
  value = this._valueTrueFalse(value);
1498
- column = this._columnPattern(String(column));
1499
- this._setState('WHERE', [
1500
- ...this._getState('WHERE'),
1917
+ const c = this._columnPattern(String(column));
1918
+ this.$state.set('WHERE', [
1919
+ ...this.$state.get('WHERE'),
1501
1920
  [
1502
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1503
- `${this.bindColumn(column)}->>'$.${key}'`,
1921
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
1922
+ `${this.bindColumn(c)}->>'$.${key}'`,
1504
1923
  `${operator == null ? "=" : operator.toLocaleUpperCase()}`,
1505
1924
  `${this._checkValueHasRaw(value)}`
1506
1925
  ].join(' ')
@@ -1508,24 +1927,24 @@ class Model extends AbstractModel_1.AbstractModel {
1508
1927
  return this;
1509
1928
  }
1510
1929
  /**
1511
- * @override Method
1930
+ * @override
1512
1931
  * @param {number} userId
1513
1932
  * @param {string?} column custom it *if column is not user_id
1514
1933
  * @return {this}
1515
1934
  */
1516
1935
  whereUser(userId, column = 'user_id') {
1517
1936
  column = this._columnPattern(String(column));
1518
- this._setState('WHERE', [
1519
- ...this._getState('WHERE'),
1937
+ this.$state.set('WHERE', [
1938
+ ...this.$state.get('WHERE'),
1520
1939
  [
1521
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1940
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
1522
1941
  `${this.bindColumn(column)} = ${this.$utils.escape(userId)}`,
1523
1942
  ].join(' ')
1524
1943
  ]);
1525
1944
  return this;
1526
1945
  }
1527
1946
  /**
1528
- * @override Method
1947
+ * @override
1529
1948
  * @param {string} column
1530
1949
  * @param {array} array
1531
1950
  * @return {this}
@@ -1533,15 +1952,15 @@ class Model extends AbstractModel_1.AbstractModel {
1533
1952
  whereIn(column, array) {
1534
1953
  if (!Array.isArray(array))
1535
1954
  throw new Error(`This 'whereIn' method is required array only`);
1536
- column = this._columnPattern(String(column));
1955
+ const c = this._columnPattern(String(column));
1537
1956
  const values = array.length
1538
1957
  ? `${array.map((value) => this._checkValueHasRaw(this.$utils.escape(value))).join(',')}`
1539
1958
  : this.$constants('NULL');
1540
- this._setState('WHERE', [
1541
- ...this._getState('WHERE'),
1959
+ this.$state.set('WHERE', [
1960
+ ...this.$state.get('WHERE'),
1542
1961
  [
1543
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1544
- `${this.bindColumn(column)}`,
1962
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
1963
+ `${this.bindColumn(c)}`,
1545
1964
  `${this.$constants('IN')}`,
1546
1965
  `(${values})`
1547
1966
  ].join(' ')
@@ -1549,7 +1968,7 @@ class Model extends AbstractModel_1.AbstractModel {
1549
1968
  return this;
1550
1969
  }
1551
1970
  /**
1552
- * @override Method
1971
+ * @override
1553
1972
  * @param {string} column
1554
1973
  * @param {array} array
1555
1974
  * @return {this}
@@ -1557,15 +1976,15 @@ class Model extends AbstractModel_1.AbstractModel {
1557
1976
  orWhereIn(column, array) {
1558
1977
  if (!Array.isArray(array))
1559
1978
  throw new Error(`This 'whereIn' method is required array only`);
1560
- column = this._columnPattern(String(column));
1979
+ const c = this._columnPattern(String(column));
1561
1980
  const values = array.length
1562
1981
  ? `${array.map((value) => this._checkValueHasRaw(this.$utils.escape(value))).join(',')}`
1563
1982
  : this.$constants('NULL');
1564
- this._setState('WHERE', [
1565
- ...this._getState('WHERE'),
1983
+ this.$state.set('WHERE', [
1984
+ ...this.$state.get('WHERE'),
1566
1985
  [
1567
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1568
- `${this.bindColumn(column)}`,
1986
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
1987
+ `${this.bindColumn(c)}`,
1569
1988
  `${this.$constants('IN')}`,
1570
1989
  `(${values})`
1571
1990
  ].join(' ')
@@ -1573,7 +1992,7 @@ class Model extends AbstractModel_1.AbstractModel {
1573
1992
  return this;
1574
1993
  }
1575
1994
  /**
1576
- * @override Method
1995
+ * @override
1577
1996
  * @param {string} column
1578
1997
  * @param {array} array
1579
1998
  * @return {this}
@@ -1581,15 +2000,15 @@ class Model extends AbstractModel_1.AbstractModel {
1581
2000
  whereNotIn(column, array) {
1582
2001
  if (!Array.isArray(array))
1583
2002
  throw new Error(`This 'whereIn' method is required array only`);
1584
- column = this._columnPattern(String(column));
2003
+ const c = this._columnPattern(String(column));
1585
2004
  if (!array.length)
1586
2005
  return this;
1587
2006
  const values = `${array.map((value) => this._checkValueHasRaw(this.$utils.escape(value))).join(',')}`;
1588
- this._setState('WHERE', [
1589
- ...this._getState('WHERE'),
2007
+ this.$state.set('WHERE', [
2008
+ ...this.$state.get('WHERE'),
1590
2009
  [
1591
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1592
- `${this.bindColumn(column)}`,
2010
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2011
+ `${this.bindColumn(c)}`,
1593
2012
  `${this.$constants('NOT_IN')}`,
1594
2013
  `(${values})`
1595
2014
  ].join(' ')
@@ -1597,7 +2016,7 @@ class Model extends AbstractModel_1.AbstractModel {
1597
2016
  return this;
1598
2017
  }
1599
2018
  /**
1600
- * @override Method
2019
+ * @override
1601
2020
  * @param {string} column
1602
2021
  * @param {array} array
1603
2022
  * @return {this}
@@ -1605,15 +2024,15 @@ class Model extends AbstractModel_1.AbstractModel {
1605
2024
  orWhereNotIn(column, array) {
1606
2025
  if (!Array.isArray(array))
1607
2026
  throw new Error(`This 'whereIn' method is required array only`);
1608
- column = this._columnPattern(String(column));
2027
+ const c = this._columnPattern(String(column));
1609
2028
  if (!array.length)
1610
2029
  return this;
1611
2030
  const values = `${array.map((value) => this._checkValueHasRaw(this.$utils.escape(value))).join(',')}`;
1612
- this._setState('WHERE', [
1613
- ...this._getState('WHERE'),
2031
+ this.$state.set('WHERE', [
2032
+ ...this.$state.get('WHERE'),
1614
2033
  [
1615
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1616
- `${this.bindColumn(column)}`,
2034
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2035
+ `${this.bindColumn(c)}`,
1617
2036
  `${this.$constants('NOT_IN')}`,
1618
2037
  `(${values})`
1619
2038
  ].join(' ')
@@ -1621,7 +2040,7 @@ class Model extends AbstractModel_1.AbstractModel {
1621
2040
  return this;
1622
2041
  }
1623
2042
  /**
1624
- * @override Method
2043
+ * @override
1625
2044
  * @param {string} column
1626
2045
  * @param {string} subQuery
1627
2046
  * @return {this}
@@ -1629,12 +2048,12 @@ class Model extends AbstractModel_1.AbstractModel {
1629
2048
  whereSubQuery(column, subQuery) {
1630
2049
  if (!this.$utils.isSubQuery(subQuery))
1631
2050
  throw new Error(`This "${subQuery}" is invalid. Sub query is should contain 1 column(s)`);
1632
- column = this._columnPattern(String(column));
1633
- this._setState('WHERE', [
1634
- ...this._getState('WHERE'),
2051
+ const c = this._columnPattern(String(column));
2052
+ this.$state.set('WHERE', [
2053
+ ...this.$state.get('WHERE'),
1635
2054
  [
1636
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1637
- `${this.bindColumn(column)}`,
2055
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2056
+ `${this.bindColumn(c)}`,
1638
2057
  `${this.$constants('IN')}`,
1639
2058
  `(${subQuery})`
1640
2059
  ].join(' ')
@@ -1642,7 +2061,7 @@ class Model extends AbstractModel_1.AbstractModel {
1642
2061
  return this;
1643
2062
  }
1644
2063
  /**
1645
- * @override Method
2064
+ * @override
1646
2065
  * @param {string} column
1647
2066
  * @param {string} subQuery
1648
2067
  * @return {this}
@@ -1650,12 +2069,12 @@ class Model extends AbstractModel_1.AbstractModel {
1650
2069
  whereNotSubQuery(column, subQuery) {
1651
2070
  if (!this.$utils.isSubQuery(subQuery))
1652
2071
  throw new Error(`This "${subQuery}" is invalid. Sub query is should contain 1 column(s)`);
1653
- column = this._columnPattern(String(column));
1654
- this._setState('WHERE', [
1655
- ...this._getState('WHERE'),
2072
+ const c = this._columnPattern(String(column));
2073
+ this.$state.set('WHERE', [
2074
+ ...this.$state.get('WHERE'),
1656
2075
  [
1657
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1658
- `${this.bindColumn(column)}`,
2076
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2077
+ `${this.bindColumn(c)}`,
1659
2078
  `${this.$constants('NOT_IN')}`,
1660
2079
  `(${subQuery})`
1661
2080
  ].join(' ')
@@ -1663,7 +2082,7 @@ class Model extends AbstractModel_1.AbstractModel {
1663
2082
  return this;
1664
2083
  }
1665
2084
  /**
1666
- * @override Method
2085
+ * @override
1667
2086
  * @param {string} column
1668
2087
  * @param {string} subQuery
1669
2088
  * @return {this}
@@ -1671,12 +2090,12 @@ class Model extends AbstractModel_1.AbstractModel {
1671
2090
  orWhereSubQuery(column, subQuery) {
1672
2091
  if (!this.$utils.isSubQuery(subQuery))
1673
2092
  throw new Error(`This "${subQuery}" is invalid. Sub query is should contain 1 column(s)`);
1674
- column = this._columnPattern(String(column));
1675
- this._setState('WHERE', [
1676
- ...this._getState('WHERE'),
2093
+ const c = this._columnPattern(String(column));
2094
+ this.$state.set('WHERE', [
2095
+ ...this.$state.get('WHERE'),
1677
2096
  [
1678
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1679
- `${this.bindColumn(column)}`,
2097
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2098
+ `${this.bindColumn(c)}`,
1680
2099
  `${this.$constants('IN')}`,
1681
2100
  `(${subQuery})`
1682
2101
  ].join(' ')
@@ -1684,7 +2103,7 @@ class Model extends AbstractModel_1.AbstractModel {
1684
2103
  return this;
1685
2104
  }
1686
2105
  /**
1687
- * @override Method
2106
+ * @override
1688
2107
  * @param {string} column
1689
2108
  * @param {string} subQuery
1690
2109
  * @return {this}
@@ -1692,12 +2111,12 @@ class Model extends AbstractModel_1.AbstractModel {
1692
2111
  orWhereNotSubQuery(column, subQuery) {
1693
2112
  if (!this.$utils.isSubQuery(subQuery))
1694
2113
  throw new Error(`This "${subQuery}" is invalid sub query (Sub query Operand should contain 1 column(s) not select * )`);
1695
- column = this._columnPattern(String(column));
1696
- this._setState('WHERE', [
1697
- ...this._getState('WHERE'),
2114
+ const c = this._columnPattern(String(column));
2115
+ this.$state.set('WHERE', [
2116
+ ...this.$state.get('WHERE'),
1698
2117
  [
1699
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1700
- `${this.bindColumn(column)}`,
2118
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2119
+ `${this.bindColumn(c)}`,
1701
2120
  `${this.$constants('NOT_IN')}`,
1702
2121
  `(${subQuery})`
1703
2122
  ].join(' ')
@@ -1705,7 +2124,7 @@ class Model extends AbstractModel_1.AbstractModel {
1705
2124
  return this;
1706
2125
  }
1707
2126
  /**
1708
- * @override Method
2127
+ * @override
1709
2128
  * @param {string} column
1710
2129
  * @param {array} array
1711
2130
  * @return {this}
@@ -1713,13 +2132,13 @@ class Model extends AbstractModel_1.AbstractModel {
1713
2132
  whereBetween(column, array) {
1714
2133
  if (!Array.isArray(array))
1715
2134
  throw new Error("Value is't array");
1716
- column = this._columnPattern(String(column));
2135
+ const c = this._columnPattern(String(column));
1717
2136
  if (!array.length) {
1718
- this._setState('WHERE', [
1719
- ...this._getState('WHERE'),
2137
+ this.$state.set('WHERE', [
2138
+ ...this.$state.get('WHERE'),
1720
2139
  [
1721
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1722
- `${this.bindColumn(column)}`,
2140
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2141
+ `${this.bindColumn(c)}`,
1723
2142
  `${this.$constants('BETWEEN')}`,
1724
2143
  `${this.$constants('NULL')}`,
1725
2144
  `${this.$constants('AND')}`,
@@ -1729,11 +2148,11 @@ class Model extends AbstractModel_1.AbstractModel {
1729
2148
  return this;
1730
2149
  }
1731
2150
  const [value1, value2] = array;
1732
- this._setState('WHERE', [
1733
- ...this._getState('WHERE'),
2151
+ this.$state.set('WHERE', [
2152
+ ...this.$state.get('WHERE'),
1734
2153
  [
1735
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1736
- `${this.bindColumn(column)}`,
2154
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2155
+ `${this.bindColumn(c)}`,
1737
2156
  `${this.$constants('BETWEEN')}`,
1738
2157
  `${this._checkValueHasRaw(this.$utils.escape(value1))}`,
1739
2158
  `${this.$constants('AND')}`,
@@ -1743,7 +2162,7 @@ class Model extends AbstractModel_1.AbstractModel {
1743
2162
  return this;
1744
2163
  }
1745
2164
  /**
1746
- * @override Method
2165
+ * @override
1747
2166
  * @param {string} column
1748
2167
  * @param {array} array
1749
2168
  * @return {this}
@@ -1751,13 +2170,13 @@ class Model extends AbstractModel_1.AbstractModel {
1751
2170
  orWhereBetween(column, array) {
1752
2171
  if (!Array.isArray(array))
1753
2172
  throw new Error("Value is't array");
1754
- column = this._columnPattern(String(column));
2173
+ const c = this._columnPattern(String(column));
1755
2174
  if (!array.length) {
1756
- this._setState('WHERE', [
1757
- ...this._getState('WHERE'),
2175
+ this.$state.set('WHERE', [
2176
+ ...this.$state.get('WHERE'),
1758
2177
  [
1759
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1760
- `${this.bindColumn(column)}`,
2178
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2179
+ `${this.bindColumn(c)}`,
1761
2180
  `${this.$constants('BETWEEN')}`,
1762
2181
  `${this.$constants('NULL')}`,
1763
2182
  `${this.$constants('AND')}`,
@@ -1767,11 +2186,11 @@ class Model extends AbstractModel_1.AbstractModel {
1767
2186
  return this;
1768
2187
  }
1769
2188
  const [value1, value2] = array;
1770
- this._setState('WHERE', [
1771
- ...this._getState('WHERE'),
2189
+ this.$state.set('WHERE', [
2190
+ ...this.$state.get('WHERE'),
1772
2191
  [
1773
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1774
- `${this.bindColumn(column)}`,
2192
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2193
+ `${this.bindColumn(c)}`,
1775
2194
  `${this.$constants('BETWEEN')}`,
1776
2195
  `${this._checkValueHasRaw(this.$utils.escape(value1))}`,
1777
2196
  `${this.$constants('AND')}`,
@@ -1781,7 +2200,7 @@ class Model extends AbstractModel_1.AbstractModel {
1781
2200
  return this;
1782
2201
  }
1783
2202
  /**
1784
- * @override Method
2203
+ * @override
1785
2204
  * @param {string} column
1786
2205
  * @param {array} array
1787
2206
  * @return {this}
@@ -1789,13 +2208,13 @@ class Model extends AbstractModel_1.AbstractModel {
1789
2208
  whereNotBetween(column, array) {
1790
2209
  if (!Array.isArray(array))
1791
2210
  throw new Error("Value is't array");
1792
- column = this._columnPattern(String(column));
2211
+ const c = this._columnPattern(String(column));
1793
2212
  if (!array.length) {
1794
- this._setState('WHERE', [
1795
- ...this._getState('WHERE'),
2213
+ this.$state.set('WHERE', [
2214
+ ...this.$state.get('WHERE'),
1796
2215
  [
1797
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1798
- `${this.bindColumn(column)}`,
2216
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2217
+ `${this.bindColumn(c)}`,
1799
2218
  `${this.$constants('NOT_BETWEEN')}`,
1800
2219
  `${this.$constants('NULL')}`,
1801
2220
  `${this.$constants('AND')}`,
@@ -1805,11 +2224,11 @@ class Model extends AbstractModel_1.AbstractModel {
1805
2224
  return this;
1806
2225
  }
1807
2226
  const [value1, value2] = array;
1808
- this._setState('WHERE', [
1809
- ...this._getState('WHERE'),
2227
+ this.$state.set('WHERE', [
2228
+ ...this.$state.get('WHERE'),
1810
2229
  [
1811
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1812
- `${this.bindColumn(column)}`,
2230
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2231
+ `${this.bindColumn(c)}`,
1813
2232
  `${this.$constants('NOT_BETWEEN')}`,
1814
2233
  `${this._checkValueHasRaw(this.$utils.escape(value1))}`,
1815
2234
  `${this.$constants('AND')}`,
@@ -1819,7 +2238,7 @@ class Model extends AbstractModel_1.AbstractModel {
1819
2238
  return this;
1820
2239
  }
1821
2240
  /**
1822
- * @override Method
2241
+ * @override
1823
2242
  * @param {string} column
1824
2243
  * @param {array} array
1825
2244
  * @return {this}
@@ -1827,13 +2246,13 @@ class Model extends AbstractModel_1.AbstractModel {
1827
2246
  orWhereNotBetween(column, array) {
1828
2247
  if (!Array.isArray(array))
1829
2248
  throw new Error("Value is't array");
1830
- column = this._columnPattern(String(column));
2249
+ const c = this._columnPattern(String(column));
1831
2250
  if (!array.length) {
1832
- this._setState('WHERE', [
1833
- ...this._getState('WHERE'),
2251
+ this.$state.set('WHERE', [
2252
+ ...this.$state.get('WHERE'),
1834
2253
  [
1835
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1836
- `${this.bindColumn(column)}`,
2254
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2255
+ `${this.bindColumn(c)}`,
1837
2256
  `${this.$constants('NOT_BETWEEN')}`,
1838
2257
  `${this.$constants('NULL')}`,
1839
2258
  `${this.$constants('AND')}`,
@@ -1843,11 +2262,11 @@ class Model extends AbstractModel_1.AbstractModel {
1843
2262
  return this;
1844
2263
  }
1845
2264
  const [value1, value2] = array;
1846
- this._setState('WHERE', [
1847
- ...this._getState('WHERE'),
2265
+ this.$state.set('WHERE', [
2266
+ ...this.$state.get('WHERE'),
1848
2267
  [
1849
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1850
- `${this.bindColumn(column)}`,
2268
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2269
+ `${this.bindColumn(c)}`,
1851
2270
  `${this.$constants('NOT_BETWEEN')}`,
1852
2271
  `${this._checkValueHasRaw(this.$utils.escape(value1))}`,
1853
2272
  `${this.$constants('AND')}`,
@@ -1857,75 +2276,75 @@ class Model extends AbstractModel_1.AbstractModel {
1857
2276
  return this;
1858
2277
  }
1859
2278
  /**
1860
- * @override Method
2279
+ * @override
1861
2280
  * @param {string} column
1862
2281
  * @return {this}
1863
2282
  */
1864
2283
  whereNull(column) {
1865
- column = this._columnPattern(String(column));
1866
- this._setState('WHERE', [
1867
- ...this._getState('WHERE'),
2284
+ const c = this._columnPattern(String(column));
2285
+ this.$state.set('WHERE', [
2286
+ ...this.$state.get('WHERE'),
1868
2287
  [
1869
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1870
- `${this.bindColumn(column)}`,
2288
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2289
+ `${this.bindColumn(c)}`,
1871
2290
  `${this.$constants('IS_NULL')}`
1872
2291
  ].join(' ')
1873
2292
  ]);
1874
2293
  return this;
1875
2294
  }
1876
2295
  /**
1877
- * @override Method
2296
+ * @override
1878
2297
  * @param {string} column
1879
2298
  * @return {this}
1880
2299
  */
1881
2300
  orWhereNull(column) {
1882
- column = this._columnPattern(String(column));
1883
- this._setState('WHERE', [
1884
- ...this._getState('WHERE'),
2301
+ const c = this._columnPattern(String(column));
2302
+ this.$state.set('WHERE', [
2303
+ ...this.$state.get('WHERE'),
1885
2304
  [
1886
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1887
- `${this.bindColumn(column)}`,
2305
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2306
+ `${this.bindColumn(c)}`,
1888
2307
  `${this.$constants('IS_NULL')}`
1889
2308
  ].join(' ')
1890
2309
  ]);
1891
2310
  return this;
1892
2311
  }
1893
2312
  /**
1894
- * @override Method
2313
+ * @override
1895
2314
  * @param {string} column
1896
2315
  * @return {this}
1897
2316
  */
1898
2317
  whereNotNull(column) {
1899
- column = this._columnPattern(String(column));
1900
- this._setState('WHERE', [
1901
- ...this._getState('WHERE'),
2318
+ const c = this._columnPattern(String(column));
2319
+ this.$state.set('WHERE', [
2320
+ ...this.$state.get('WHERE'),
1902
2321
  [
1903
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
1904
- `${this.bindColumn(column)}`,
2322
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2323
+ `${this.bindColumn(c)}`,
1905
2324
  `${this.$constants('IS_NOT_NULL')}`
1906
2325
  ].join(' ')
1907
2326
  ]);
1908
2327
  return this;
1909
2328
  }
1910
2329
  /**
1911
- * @override Method
2330
+ * @override
1912
2331
  * @param {string} column
1913
2332
  * @return {this}
1914
2333
  */
1915
2334
  orWhereNotNull(column) {
1916
- column = this._columnPattern(String(column));
1917
- this._setState('WHERE', [
1918
- ...this._getState('WHERE'),
2335
+ const c = this._columnPattern(String(column));
2336
+ this.$state.set('WHERE', [
2337
+ ...this.$state.get('WHERE'),
1919
2338
  [
1920
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
1921
- `${this.bindColumn(column)}`,
2339
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
2340
+ `${this.bindColumn(c)}`,
1922
2341
  `${this.$constants('IS_NOT_NULL')}`
1923
2342
  ].join(' ')
1924
2343
  ]);
1925
2344
  return this;
1926
2345
  }
1927
2346
  /**
1928
- * @override Method
2347
+ * @override
1929
2348
  * @param {string} column
1930
2349
  * @param {string?} operator = < > != !< !>
1931
2350
  * @param {any?} value
@@ -1933,15 +2352,15 @@ class Model extends AbstractModel_1.AbstractModel {
1933
2352
  */
1934
2353
  whereSensitive(column, operator, value) {
1935
2354
  [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
1936
- column = this._columnPattern(String(column));
2355
+ const c = this._columnPattern(String(column));
1937
2356
  value = this.$utils.escape(value);
1938
2357
  value = this._valueTrueFalse(value);
1939
- this._setState('WHERE', [
1940
- ...this._getState('WHERE'),
2358
+ this.$state.set('WHERE', [
2359
+ ...this.$state.get('WHERE'),
1941
2360
  [
1942
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
2361
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
1943
2362
  `${this.$constants('BINARY')}`,
1944
- `${this.bindColumn(column)}`,
2363
+ `${this.bindColumn(c)}`,
1945
2364
  `${operator}`,
1946
2365
  `${this._checkValueHasRaw(this.$utils.escape(value))}`
1947
2366
  ].join(' ')
@@ -1949,17 +2368,31 @@ class Model extends AbstractModel_1.AbstractModel {
1949
2368
  return this;
1950
2369
  }
1951
2370
  /**
1952
- * @override Method
2371
+ * @override
1953
2372
  * @param {string} column
1954
2373
  * @param {string?} operator = < > != !< !>
1955
2374
  * @param {any?} value
1956
2375
  * @return {this}
1957
2376
  */
1958
2377
  whereStrict(column, operator, value) {
1959
- return this.whereSensitive(column, operator, value);
2378
+ [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
2379
+ const c = this._columnPattern(String(column));
2380
+ value = this.$utils.escape(value);
2381
+ value = this._valueTrueFalse(value);
2382
+ this.$state.set('WHERE', [
2383
+ ...this.$state.get('WHERE'),
2384
+ [
2385
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2386
+ `${this.$constants('BINARY')}`,
2387
+ `${this.bindColumn(c)}`,
2388
+ `${operator}`,
2389
+ `${this._checkValueHasRaw(this.$utils.escape(value))}`
2390
+ ].join(' ')
2391
+ ]);
2392
+ return this;
1960
2393
  }
1961
2394
  /**
1962
- * @override Method
2395
+ * @override
1963
2396
  * @param {string} column
1964
2397
  * @param {string?} operator = < > != !< !>
1965
2398
  * @param {any?} value
@@ -1967,15 +2400,15 @@ class Model extends AbstractModel_1.AbstractModel {
1967
2400
  */
1968
2401
  orWhereSensitive(column, operator, value) {
1969
2402
  [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
1970
- column = this._columnPattern(String(column));
2403
+ const c = this._columnPattern(String(column));
1971
2404
  value = this.$utils.escape(value);
1972
2405
  value = this._valueTrueFalse(value);
1973
- this._setState('WHERE', [
1974
- ...this._getState('WHERE'),
2406
+ this.$state.set('WHERE', [
2407
+ ...this.$state.get('WHERE'),
1975
2408
  [
1976
- this._getState('WHERE').length ? `${this.$constants('OR')}` : '',
2409
+ this.$state.get('WHERE').length ? `${this.$constants('OR')}` : '',
1977
2410
  `${this.$constants('BINARY')}`,
1978
- `${this.bindColumn(column)}`,
2411
+ `${this.bindColumn(c)}`,
1979
2412
  `${operator}`,
1980
2413
  `${this._checkValueHasRaw(this.$utils.escape(value))}`
1981
2414
  ].join(' ')
@@ -1983,7 +2416,7 @@ class Model extends AbstractModel_1.AbstractModel {
1983
2416
  return this;
1984
2417
  }
1985
2418
  /**
1986
- * @override Method
2419
+ * @override
1987
2420
  * @param {Function} callback callback query
1988
2421
  * @return {this}
1989
2422
  */
@@ -1994,30 +2427,80 @@ class Model extends AbstractModel_1.AbstractModel {
1994
2427
  throw new Error('"whereQuery" is not supported a Promise');
1995
2428
  if (!(repository instanceof Model))
1996
2429
  throw new Error(`Unknown callback query: '${repository}'`);
1997
- const where = (repository === null || repository === void 0 ? void 0 : repository._getState('WHERE')) || [];
2430
+ const where = (repository === null || repository === void 0 ? void 0 : repository.$state.get('WHERE')) || [];
1998
2431
  if (!where.length)
1999
2432
  return this;
2000
2433
  const query = where.join(' ');
2001
- this._setState('WHERE', [
2002
- ...this._getState('WHERE'),
2434
+ this.$state.set('WHERE', [
2435
+ ...this.$state.get('WHERE'),
2003
2436
  [
2004
- this._getState('WHERE').length ? `${this.$constants('AND')}` : '',
2437
+ this.$state.get('WHERE').length
2438
+ ? `${this.$constants('AND')}`
2439
+ : '',
2005
2440
  `(${query})`
2006
2441
  ].join(' ')
2007
2442
  ]);
2008
2443
  return this;
2009
2444
  }
2010
2445
  /**
2011
- * @override Method
2446
+ * @override
2447
+ * @param {string[]} columns
2448
+ * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
2449
+ * @param {any?} value
2450
+ * @return {this}
2451
+ */
2452
+ whereAny(columns, operator, value) {
2453
+ [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
2454
+ value = this.$utils.escape(value);
2455
+ value = this._valueTrueFalse(value);
2456
+ this.whereQuery((query) => {
2457
+ for (const index in columns) {
2458
+ const column = String(columns[index]);
2459
+ if (+index === 0) {
2460
+ query.where(column, operator, value);
2461
+ continue;
2462
+ }
2463
+ query.orWhere(column, operator, value);
2464
+ }
2465
+ return query;
2466
+ });
2467
+ return this;
2468
+ }
2469
+ /**
2470
+ * The 'whereAll' method is used to clause to a database query.
2471
+ *
2472
+ * This method allows you to specify conditions that the retrieved records must meet.
2473
+ *
2474
+ * If has only 2 arguments default operator '='
2475
+ * @param {string[]} columns
2476
+ * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
2477
+ * @param {any?} value
2478
+ * @return {this}
2479
+ */
2480
+ whereAll(columns, operator, value) {
2481
+ [value, operator] = this._valueAndOperator(value, operator, arguments.length === 2);
2482
+ value = this.$utils.escape(value);
2483
+ value = this._valueTrueFalse(value);
2484
+ this.whereQuery((query) => {
2485
+ for (const key in columns) {
2486
+ const column = String(columns[key]);
2487
+ query.where(column, operator, value);
2488
+ }
2489
+ return query;
2490
+ });
2491
+ return this;
2492
+ }
2493
+ /**
2494
+ * @override
2012
2495
  * @return {promise<boolean>} promise boolean
2013
2496
  */
2014
2497
  delete() {
2015
- var _a, _b;
2016
2498
  return __awaiter(this, void 0, void 0, function* () {
2017
- this._assertError(!this._getState('where').length, "This method 'delete' is require to use 'where' conditions");
2499
+ var _a, _b;
2500
+ this._assertError(!this.$state.get('where').length, "The 'delete' method requires the use of 'where' conditions.");
2018
2501
  this.limit(1);
2019
- if (this._getState('SOFT_DELETE')) {
2020
- const deletedAt = this._valuePattern(this._getState('SOFT_DELETE_FORMAT'));
2502
+ if (this.$state.get('SOFT_DELETE')) {
2503
+ const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
2021
2504
  const sql = new Model()
2022
2505
  .copyModel(this, { where: true, limit: true })
2023
2506
  .bind(this.$pool.get())
@@ -2027,30 +2510,30 @@ class Model extends AbstractModel_1.AbstractModel {
2027
2510
  .toString();
2028
2511
  const result = yield this._actionStatement({ sql });
2029
2512
  const r = Boolean(this._resultHandler((_a = !!result) !== null && _a !== void 0 ? _a : false));
2030
- this._observer(r, 'updated');
2513
+ yield this._observer(r, 'updated');
2031
2514
  return r;
2032
2515
  }
2033
- this._setState('DELETE', [
2516
+ this.$state.set('DELETE', [
2034
2517
  `${this.$constants('DELETE')}`,
2035
- `${this._getState('FROM')}`,
2036
- `${this._getState('TABLE_NAME')}`,
2518
+ `${this.$state.get('FROM')}`,
2519
+ `${this.$state.get('TABLE_NAME')}`,
2037
2520
  ].join(' '));
2038
2521
  const result = yield this._actionStatement({ sql: this._queryBuilder().delete() });
2039
2522
  const r = Boolean(this._resultHandler((_b = !!result) !== null && _b !== void 0 ? _b : false));
2040
- this._observer(r, 'deleted');
2523
+ yield this._observer(r, 'deleted');
2041
2524
  return r;
2042
2525
  });
2043
2526
  }
2044
2527
  /**
2045
- * @override Method
2528
+ * @override
2046
2529
  * @return {promise<boolean>} promise boolean
2047
2530
  */
2048
2531
  deleteMany() {
2049
- var _a, _b;
2050
2532
  return __awaiter(this, void 0, void 0, function* () {
2051
- this._assertError(!this._getState('where').length, "This method 'delete' is require to use 'where' conditions");
2052
- if (this._getState('SOFT_DELETE')) {
2053
- const deletedAt = this._valuePattern(this._getState('SOFT_DELETE_FORMAT'));
2533
+ var _a, _b;
2534
+ this._assertError(!this.$state.get('WHERE').length, "The 'deleteMany' method requires the use of 'where' conditions.");
2535
+ if (this.$state.get('SOFT_DELETE')) {
2536
+ const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
2054
2537
  const sql = new Model()
2055
2538
  .copyModel(this, { where: true, limit: true })
2056
2539
  .bind(this.$pool.get())
@@ -2060,43 +2543,66 @@ class Model extends AbstractModel_1.AbstractModel {
2060
2543
  .toString();
2061
2544
  const result = yield this._actionStatement({ sql });
2062
2545
  const r = Boolean(this._resultHandler((_a = !!result) !== null && _a !== void 0 ? _a : false));
2063
- this._observer(r, 'updated');
2546
+ yield this._observer(r, 'updated');
2064
2547
  return r;
2065
2548
  }
2066
- this._setState('DELETE', [
2549
+ this.$state.set('DELETE', [
2067
2550
  `${this.$constants('DELETE')}`,
2068
- `${this._getState('FROM')}`,
2069
- `${this._getState('TABLE_NAME')}`,
2551
+ `${this.$state.get('FROM')}`,
2552
+ `${this.$state.get('TABLE_NAME')}`,
2070
2553
  ].join(' '));
2071
2554
  const result = yield this._actionStatement({ sql: this._queryBuilder().delete() });
2072
2555
  const r = Boolean(this._resultHandler((_b = !!result) !== null && _b !== void 0 ? _b : false));
2073
- this._observer(r, 'deleted');
2556
+ yield this._observer(r, 'deleted');
2074
2557
  return r;
2075
2558
  });
2076
2559
  }
2077
2560
  /**
2078
- * @override Method
2561
+ *
2562
+ * The 'delete' method is used to delete records from a database table based on the specified query conditions.
2563
+ *
2564
+ * It allows you to remove one or more records that match certain criteria.
2565
+ *
2566
+ * This method should be ignore the soft delete
2567
+ * @return {promise<boolean>}
2568
+ */
2569
+ forceDelete() {
2570
+ return __awaiter(this, void 0, void 0, function* () {
2571
+ var _a, _b;
2572
+ this.disableSoftDelete();
2573
+ this.$state.set('DELETE', [
2574
+ `${this.$constants('DELETE')}`,
2575
+ `${this.$state.get('FROM')}`,
2576
+ `${this.$state.get('TABLE_NAME')}`
2577
+ ].join(' '));
2578
+ const result = yield this._actionStatement({ sql: this._queryBuilder().delete() });
2579
+ if (result)
2580
+ return Boolean(this._resultHandler((_a = !!result) !== null && _a !== void 0 ? _a : false));
2581
+ return Boolean(this._resultHandler((_b = !!result) !== null && _b !== void 0 ? _b : false));
2582
+ });
2583
+ }
2584
+ /**
2585
+ *
2586
+ * @override
2587
+ * @param {Function?} cb callback function return query sql
2079
2588
  * @return {promise<Record<string,any> | null>} Record | null
2080
2589
  */
2081
2590
  first(cb) {
2082
- var _a, _b;
2083
2591
  return __awaiter(this, void 0, void 0, function* () {
2592
+ var _a, _b;
2084
2593
  this._validateMethod('first');
2085
- if (this._getState('VOID'))
2594
+ if (this.$state.get('VOID'))
2086
2595
  return this._resultHandler(undefined);
2087
- if ((_a = this._getState('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2596
+ if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2088
2597
  this.select(...yield this.exceptColumns());
2089
2598
  this.limit(1);
2090
2599
  let sql = this._queryBuilder().select();
2091
- if (this._getState('RELATIONS_EXISTS'))
2600
+ if (this.$state.get('RELATIONS_EXISTS'))
2092
2601
  sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
2093
2602
  if (cb) {
2094
2603
  const callbackSql = cb(sql);
2095
2604
  this._assertError(callbackSql == null || callbackSql === '', 'Please provide a callback for execution');
2096
- return yield this._execute({
2097
- sql: callbackSql,
2098
- type: 'GET'
2099
- });
2605
+ sql = callbackSql;
2100
2606
  }
2101
2607
  return yield this._execute({
2102
2608
  sql,
@@ -2105,27 +2611,28 @@ class Model extends AbstractModel_1.AbstractModel {
2105
2611
  });
2106
2612
  }
2107
2613
  /**
2108
- * @override Method
2614
+ * @override
2615
+ * @param {Function?} cb callback function return query sql
2109
2616
  * @return {promise<Record<string,any> | null>} Record | null
2110
2617
  */
2111
- findOne() {
2618
+ findOne(cb) {
2112
2619
  return __awaiter(this, void 0, void 0, function* () {
2113
- return yield this.first();
2620
+ return yield this.first(cb);
2114
2621
  });
2115
2622
  }
2116
2623
  /**
2117
- * @override Method
2624
+ * @override
2118
2625
  * @return {promise<object | Error>} Record | throw error
2119
2626
  */
2120
2627
  firstOrError(message, options) {
2121
- var _a, _b;
2122
2628
  return __awaiter(this, void 0, void 0, function* () {
2629
+ var _a, _b;
2123
2630
  this._validateMethod('firstOrError');
2124
- if ((_a = this._getState('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2631
+ if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2125
2632
  this.select(...yield this.exceptColumns());
2126
2633
  this.limit(1);
2127
2634
  let sql = this._queryBuilder().select();
2128
- if (this._getState('RELATIONS_EXISTS'))
2635
+ if (this.$state.get('RELATIONS_EXISTS'))
2129
2636
  sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
2130
2637
  return yield this._execute({
2131
2638
  sql,
@@ -2137,7 +2644,7 @@ class Model extends AbstractModel_1.AbstractModel {
2137
2644
  }
2138
2645
  /**
2139
2646
  *
2140
- * @override Method
2647
+ * @override
2141
2648
  * @return {promise<any>} Record | throw error
2142
2649
  */
2143
2650
  findOneOrError(message, options) {
@@ -2147,27 +2654,25 @@ class Model extends AbstractModel_1.AbstractModel {
2147
2654
  }
2148
2655
  /**
2149
2656
  *
2150
- * @override Method
2657
+ * @override
2658
+ * @param {Function?} cb callback function return query sql
2151
2659
  * @return {promise<array>} Array
2152
2660
  */
2153
2661
  get(cb) {
2154
- var _a, _b;
2155
2662
  return __awaiter(this, void 0, void 0, function* () {
2663
+ var _a, _b;
2156
2664
  this._validateMethod('get');
2157
- if (this._getState('VOID'))
2665
+ if (this.$state.get('VOID'))
2158
2666
  return [];
2159
- if ((_a = this._getState('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2667
+ if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2160
2668
  this.select(...yield this.exceptColumns());
2161
2669
  let sql = this._queryBuilder().select();
2162
- if (this._getState('RELATIONS_EXISTS'))
2670
+ if (this.$state.get('RELATIONS_EXISTS'))
2163
2671
  sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
2164
2672
  if (cb) {
2165
2673
  const callbackSql = cb(sql);
2166
2674
  this._assertError(callbackSql == null || callbackSql === '', 'Please provide a callback for execution');
2167
- return yield this._execute({
2168
- sql: callbackSql,
2169
- type: 'GET'
2170
- });
2675
+ sql = callbackSql;
2171
2676
  }
2172
2677
  return yield this._execute({
2173
2678
  sql,
@@ -2177,24 +2682,25 @@ class Model extends AbstractModel_1.AbstractModel {
2177
2682
  }
2178
2683
  /**
2179
2684
  *
2180
- * @override Method
2685
+ * @override
2686
+ * @param {Function?} cb callback function return query sql
2181
2687
  * @return {promise<array>} Array
2182
2688
  */
2183
- findMany() {
2689
+ findMany(cb) {
2184
2690
  return __awaiter(this, void 0, void 0, function* () {
2185
- return yield this.get();
2691
+ return yield this.get(cb);
2186
2692
  });
2187
2693
  }
2188
2694
  /**
2189
- * @override Method
2695
+ * @override
2190
2696
  * @param {object?} paginationOptions by default page = 1 , limit = 15
2191
2697
  * @property {number} paginationOptions.limit
2192
2698
  * @property {number} paginationOptions.page
2193
2699
  * @return {promise<Pagination>} Pagination
2194
2700
  */
2195
2701
  pagination(paginationOptions) {
2196
- var _a, _b;
2197
2702
  return __awaiter(this, void 0, void 0, function* () {
2703
+ var _a, _b;
2198
2704
  this._validateMethod('pagination');
2199
2705
  let limit = 15;
2200
2706
  let page = 1;
@@ -2202,15 +2708,15 @@ class Model extends AbstractModel_1.AbstractModel {
2202
2708
  limit = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit;
2203
2709
  page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
2204
2710
  }
2205
- if ((_a = this._getState('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2711
+ if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2206
2712
  this.select(...yield this.exceptColumns());
2207
2713
  const offset = (page - 1) * limit;
2208
- this._setState('PER_PAGE', limit);
2209
- this._setState('PAGE', page);
2714
+ this.$state.set('PER_PAGE', limit);
2715
+ this.$state.set('PAGE', page);
2210
2716
  this.limit(limit);
2211
2717
  this.offset(offset);
2212
2718
  let sql = this._queryBuilder().select();
2213
- if (this._getState('RELATIONS_EXISTS'))
2719
+ if (this.$state.get('RELATIONS_EXISTS'))
2214
2720
  sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
2215
2721
  return yield this._execute({
2216
2722
  sql,
@@ -2220,7 +2726,7 @@ class Model extends AbstractModel_1.AbstractModel {
2220
2726
  }
2221
2727
  /**
2222
2728
  *
2223
- * @override Method
2729
+ * @override
2224
2730
  * @param {?object} paginationOptions by default page = 1 , limit = 15
2225
2731
  * @property {number} paginationOptions.limit
2226
2732
  * @property {number} paginationOptions.page
@@ -2232,14 +2738,14 @@ class Model extends AbstractModel_1.AbstractModel {
2232
2738
  });
2233
2739
  }
2234
2740
  /**
2235
- * @override Method
2741
+ * @override
2236
2742
  * @param {string} column
2237
2743
  * @return {Promise<array>} Array
2238
2744
  */
2239
2745
  getGroupBy(column) {
2240
- var _a;
2241
2746
  return __awaiter(this, void 0, void 0, function* () {
2242
- if ((_a = this._getState('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2747
+ var _a;
2748
+ if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2243
2749
  this.select(...yield this.exceptColumns());
2244
2750
  this.selectRaw([
2245
2751
  `\`${column}\`,`,
@@ -2274,25 +2780,25 @@ class Model extends AbstractModel_1.AbstractModel {
2274
2780
  });
2275
2781
  }
2276
2782
  /**
2277
- * @override Method
2783
+ * @override
2278
2784
  * @param {object} data for insert
2279
2785
  * @return {this} this
2280
2786
  */
2281
2787
  insert(data) {
2282
2788
  if (!Object.keys(data).length)
2283
2789
  throw new Error('This method must be required');
2284
- this._setState('DATA', data);
2790
+ this.$state.set('DATA', data);
2285
2791
  const query = this._queryInsertModel(data);
2286
- this._setState('INSERT', [
2792
+ this.$state.set('INSERT', [
2287
2793
  `${this.$constants('INSERT')}`,
2288
- `${this._getState('TABLE_NAME')}`,
2794
+ `${this.$state.get('TABLE_NAME')}`,
2289
2795
  `${query}`
2290
2796
  ].join(' '));
2291
- this._setState('SAVE', 'INSERT');
2797
+ this.$state.set('SAVE', 'INSERT');
2292
2798
  return this;
2293
2799
  }
2294
2800
  /**
2295
- * @override Method
2801
+ * @override
2296
2802
  * @param {object} data for insert
2297
2803
  * @return {this} this
2298
2804
  */
@@ -2300,7 +2806,7 @@ class Model extends AbstractModel_1.AbstractModel {
2300
2806
  return this.insert(data);
2301
2807
  }
2302
2808
  /**
2303
- * @override Method
2809
+ * @override
2304
2810
  * @param {object} data
2305
2811
  * @param {array?} updateNotExists options for except update some records in your ${data}
2306
2812
  * @return {this} this
@@ -2314,24 +2820,24 @@ class Model extends AbstractModel_1.AbstractModel {
2314
2820
  if (c !== column)
2315
2821
  continue;
2316
2822
  const value = data[column];
2317
- data[column] = this._updateHandler(column, value);
2823
+ data = Object.assign(Object.assign({}, data), { [column]: this._updateHandler(column, value) });
2318
2824
  break;
2319
2825
  }
2320
2826
  }
2321
2827
  }
2322
- this._setState('DATA', data);
2828
+ this.$state.set('DATA', data);
2323
2829
  this.limit(1);
2324
2830
  const query = this._queryUpdateModel(data);
2325
- this._setState('UPDATE', [
2831
+ this.$state.set('UPDATE', [
2326
2832
  `${this.$constants('UPDATE')}`,
2327
- `${this._getState('TABLE_NAME')}`,
2833
+ `${this.$state.get('TABLE_NAME')}`,
2328
2834
  `${query}`
2329
2835
  ].join(' '));
2330
- this._setState('SAVE', 'UPDATE');
2836
+ this.$state.set('SAVE', 'UPDATE');
2331
2837
  return this;
2332
2838
  }
2333
2839
  /**
2334
- * @override Method
2840
+ * @override
2335
2841
  * @param {object} data
2336
2842
  * @param {array?} updateNotExists options for except update some records in your ${data}
2337
2843
  * @return {this} this
@@ -2345,23 +2851,23 @@ class Model extends AbstractModel_1.AbstractModel {
2345
2851
  if (c !== column)
2346
2852
  continue;
2347
2853
  const value = data[column];
2348
- data[column] = this._updateHandler(column, value);
2854
+ data = Object.assign(Object.assign({}, data), { [column]: this._updateHandler(column, value) });
2349
2855
  break;
2350
2856
  }
2351
2857
  }
2352
2858
  }
2353
- this._setState('DATA', data);
2859
+ this.$state.set('DATA', data);
2354
2860
  const query = this._queryUpdateModel(data);
2355
- this._setState('UPDATE', [
2861
+ this.$state.set('UPDATE', [
2356
2862
  `${this.$constants('UPDATE')}`,
2357
- `${this._getState('TABLE_NAME')}`,
2863
+ `${this.$state.get('TABLE_NAME')}`,
2358
2864
  `${query}`
2359
2865
  ].join(' '));
2360
- this._setState('SAVE', 'UPDATE');
2866
+ this.$state.set('SAVE', 'UPDATE');
2361
2867
  return this;
2362
2868
  }
2363
2869
  /**
2364
- * @override Method
2870
+ * @override
2365
2871
  * @param {object} data
2366
2872
  * @return {this} this
2367
2873
  */
@@ -2371,20 +2877,20 @@ class Model extends AbstractModel_1.AbstractModel {
2371
2877
  throw new Error('This method must be required');
2372
2878
  for (const column in data) {
2373
2879
  const value = data[column];
2374
- data[column] = this._updateHandler(column, value);
2880
+ data = Object.assign(Object.assign({}, data), { [column]: this._updateHandler(column, value) });
2375
2881
  }
2376
- this._setState('DATA', data);
2882
+ this.$state.set('DATA', data);
2377
2883
  const query = this._queryUpdateModel(data);
2378
- this._setState('UPDATE', [
2884
+ this.$state.set('UPDATE', [
2379
2885
  `${this.$constants('UPDATE')}`,
2380
- `${this._getState('TABLE_NAME')}`,
2886
+ `${this.$state.get('TABLE_NAME')}`,
2381
2887
  `${query}`
2382
2888
  ].join(' '));
2383
- this._setState('SAVE', 'UPDATE');
2889
+ this.$state.set('SAVE', 'UPDATE');
2384
2890
  return this;
2385
2891
  }
2386
2892
  /**
2387
- * @override Method
2893
+ * @override
2388
2894
  * @param {object} data for update or create
2389
2895
  * @return {this} this
2390
2896
  */
@@ -2394,22 +2900,22 @@ class Model extends AbstractModel_1.AbstractModel {
2394
2900
  throw new Error('This method must be required');
2395
2901
  const queryUpdate = this._queryUpdateModel(data);
2396
2902
  const queryInsert = this._queryInsertModel(data);
2397
- this._setState('DATA', data);
2398
- this._setState('INSERT', [
2903
+ this.$state.set('DATA', data);
2904
+ this.$state.set('INSERT', [
2399
2905
  `${this.$constants('INSERT')}`,
2400
- `${this._getState('TABLE_NAME')}`,
2906
+ `${this.$state.get('TABLE_NAME')}`,
2401
2907
  `${queryInsert}`
2402
2908
  ].join(' '));
2403
- this._setState('UPDATE', [
2909
+ this.$state.set('UPDATE', [
2404
2910
  `${this.$constants('UPDATE')}`,
2405
- `${this._getState('TABLE_NAME')}`,
2911
+ `${this.$state.get('TABLE_NAME')}`,
2406
2912
  `${queryUpdate}`
2407
2913
  ].join(' '));
2408
- this._setState('SAVE', 'UPDATE_OR_INSERT');
2914
+ this.$state.set('SAVE', 'UPDATE_OR_INSERT');
2409
2915
  return this;
2410
2916
  }
2411
2917
  /**
2412
- * @override Method
2918
+ * @override
2413
2919
  * @param {object} data for update or create
2414
2920
  * @return {this} this
2415
2921
  */
@@ -2417,7 +2923,7 @@ class Model extends AbstractModel_1.AbstractModel {
2417
2923
  return this.updateOrCreate(data);
2418
2924
  }
2419
2925
  /**
2420
- * @override Method
2926
+ * @override
2421
2927
  * @param {object} data for update or create
2422
2928
  * @return {this} this
2423
2929
  */
@@ -2425,7 +2931,7 @@ class Model extends AbstractModel_1.AbstractModel {
2425
2931
  return this.updateOrCreate(data);
2426
2932
  }
2427
2933
  /**
2428
- * @override Method
2934
+ * @override
2429
2935
  * @param {object} data for update or create
2430
2936
  * @return {this} this
2431
2937
  */
@@ -2433,25 +2939,25 @@ class Model extends AbstractModel_1.AbstractModel {
2433
2939
  return this.updateOrCreate(data);
2434
2940
  }
2435
2941
  /**
2436
- * @override Method
2942
+ * @override
2437
2943
  * @param {object} data for create
2438
2944
  * @return {this} this
2439
2945
  */
2440
2946
  createOrSelect(data) {
2441
2947
  if (!Object.keys(data).length)
2442
2948
  throw new Error('This method must be required');
2443
- this._setState('DATA', data);
2949
+ this.$state.set('DATA', data);
2444
2950
  const queryInsert = this._queryInsertModel(data);
2445
- this._setState('INSERT', [
2951
+ this.$state.set('INSERT', [
2446
2952
  `${this.$constants('INSERT')}`,
2447
- `${this._getState('TABLE_NAME')}`,
2953
+ `${this.$state.get('TABLE_NAME')}`,
2448
2954
  `${queryInsert}`
2449
2955
  ].join(' '));
2450
- this._setState('SAVE', 'INSERT_OR_SELECT');
2956
+ this.$state.set('SAVE', 'INSERT_OR_SELECT');
2451
2957
  return this;
2452
2958
  }
2453
2959
  /**
2454
- * @override Method
2960
+ * @override
2455
2961
  * @param {object} data for update or create
2456
2962
  * @return {this} this
2457
2963
  */
@@ -2459,24 +2965,24 @@ class Model extends AbstractModel_1.AbstractModel {
2459
2965
  return this.createOrSelect(data);
2460
2966
  }
2461
2967
  /**
2462
- * @override Method
2968
+ * @override
2463
2969
  * @param {Record<string,any>[]} data create multiple data
2464
2970
  * @return {this} this this
2465
2971
  */
2466
2972
  createMultiple(data) {
2467
- this._setState('DATA', data);
2973
+ this.$state.set('DATA', data);
2468
2974
  const query = this._queryInsertMultipleModel(data);
2469
- this._setState('INSERT', [
2975
+ this.$state.set('INSERT', [
2470
2976
  `${this.$constants('INSERT')}`,
2471
- `${this._getState('TABLE_NAME')}`,
2977
+ `${this.$state.get('TABLE_NAME')}`,
2472
2978
  `${query}`
2473
2979
  ].join(' '));
2474
- this._setState('SAVE', 'INSERT_MULTIPLE');
2980
+ this.$state.set('SAVE', 'INSERT_MULTIPLE');
2475
2981
  return this;
2476
2982
  }
2477
2983
  /**
2478
2984
  *
2479
- * @override Method
2985
+ * @override
2480
2986
  * @param {Record<string,any>[]} data create multiple data
2481
2987
  * @return {this} this
2482
2988
  */
@@ -2484,38 +2990,119 @@ class Model extends AbstractModel_1.AbstractModel {
2484
2990
  return this.createMultiple(data);
2485
2991
  }
2486
2992
  /**
2487
- * @override Method
2993
+ *
2994
+ * @override
2488
2995
  * @param {object} data create not exists data
2489
2996
  * @return {this} this
2490
2997
  */
2491
2998
  createNotExists(data) {
2492
2999
  this._assertError(Array.isArray(data), 'Data must be an array. Only object are supported');
2493
- this._setState('DATA', data);
3000
+ this.$state.set('DATA', data);
2494
3001
  const query = this._queryInsertModel(data);
2495
- this._setState('INSERT', [
3002
+ this.$state.set('INSERT', [
2496
3003
  `${this.$constants('INSERT')}`,
2497
- `${this._getState('TABLE_NAME')}`,
3004
+ `${this.$state.get('TABLE_NAME')}`,
2498
3005
  `${query}`
2499
3006
  ].join(' '));
2500
- this._setState('SAVE', 'INSERT_NOT_EXISTS');
3007
+ this.$state.set('SAVE', 'INSERT_NOT_EXISTS');
2501
3008
  return this;
2502
3009
  }
2503
3010
  /**
2504
- * @override Method
3011
+ *
3012
+ * @override
2505
3013
  * @param {object} data create not exists data
2506
3014
  * @return {this} this this
2507
3015
  */
2508
3016
  insertNotExists(data) {
2509
3017
  return this.createNotExists(data);
2510
3018
  }
3019
+ /**
3020
+ *
3021
+ * @override
3022
+ * @param {{when : Object , columns : Object}[]} cases update multiple data specific columns by cases update
3023
+ * @property {Record<string,string | number | boolean | null | undefined>} cases.when
3024
+ * @property {Record<string,string | number | boolean | null | undefined>} cases.columns
3025
+ * @return {this} this
3026
+ */
3027
+ updateMultiple(cases) {
3028
+ if (!cases.length)
3029
+ this._assertError(`The method 'updateMultiple' array must not be empty.`);
3030
+ this.limit(cases.length);
3031
+ const updateColumns = cases.reduce((columns, item) => {
3032
+ return (item.columns && Object.keys(item.columns).forEach(key => columns[key] = [
3033
+ this.$constants('RAW'),
3034
+ this.$constants('CASE'),
3035
+ `${this.$constants('ELSE')} ${this.bindColumn(key)}`,
3036
+ this.$constants('END')
3037
+ ]), columns);
3038
+ }, {});
3039
+ const columns = cases.reduce((columns, item) => {
3040
+ return (item.columns && Object.keys(item.columns).forEach(key => columns[key] = ''), columns);
3041
+ }, {});
3042
+ if (this.$state.get('TIMESTAMP')) {
3043
+ const updatedAt = this._valuePattern(this.$state.get('TIMESTAMP_FORMAT').UPDATED_AT);
3044
+ columns[updatedAt] = [];
3045
+ updateColumns[updatedAt] = [
3046
+ this.$constants('RAW'),
3047
+ this.$constants('CASE'),
3048
+ `${this.$constants('ELSE')} ${this.bindColumn(updatedAt)}`,
3049
+ this.$constants('END')
3050
+ ];
3051
+ }
3052
+ for (let i = cases.length - 1; i >= 0; i--) {
3053
+ const c = cases[i];
3054
+ if (c.when == null || !Object.keys(c.when).length)
3055
+ this._assertError(`This 'when' property is missing some properties`);
3056
+ if (c.columns == null || !Object.keys(c.columns).length)
3057
+ this._assertError(`This 'columns' property is missing some properties`);
3058
+ const when = Object.entries(c.when).map(([key, value]) => {
3059
+ value = this.$utils.escape(value);
3060
+ value = this._valueTrueFalse(value);
3061
+ return `${this.bindColumn(key)} = '${value}'`;
3062
+ });
3063
+ if (this.$state.get('TIMESTAMP')) {
3064
+ const updatedAt = this._valuePattern(this.$state.get('TIMESTAMP_FORMAT').UPDATED_AT);
3065
+ c.columns[updatedAt] = this.$utils.timestamp();
3066
+ }
3067
+ for (const [key, value] of Object.entries(c.columns)) {
3068
+ if (updateColumns[key] == null)
3069
+ continue;
3070
+ const startIndex = updateColumns[key].indexOf(this.$constants('CASE'));
3071
+ const str = `${this.$constants('WHEN')} ${when.join(` ${this.$constants('AND')} `)} ${this.$constants('THEN')} '${value}'`;
3072
+ updateColumns[key].splice(startIndex + 1, 0, str);
3073
+ }
3074
+ }
3075
+ for (const key in columns) {
3076
+ if (updateColumns[key] == null)
3077
+ continue;
3078
+ columns[key] = `( ${updateColumns[key].join(' ')} )`;
3079
+ }
3080
+ const keyValue = Object.entries(columns).map(([column, value]) => {
3081
+ if (typeof value === 'string' && !(value.includes(this.$constants('RAW')))) {
3082
+ value = this.$utils.escapeActions(value);
3083
+ }
3084
+ return `${this.bindColumn(column)} = ${value == null || value === 'NULL'
3085
+ ? 'NULL'
3086
+ : this._checkValueHasRaw(value)}`;
3087
+ });
3088
+ const query = `${this.$constants('SET')} ${keyValue.join(', ')}`;
3089
+ this.$state.set('DATA', columns);
3090
+ this.$state.set('UPDATE', [
3091
+ `${this.$constants('UPDATE')}`,
3092
+ `${this.$state.get('TABLE_NAME')}`,
3093
+ `${query}`
3094
+ ].join(' '));
3095
+ this.$state.set('SAVE', 'UPDATE');
3096
+ return this;
3097
+ }
2511
3098
  getSchemaModel() {
2512
3099
  if (this.$schema == null)
2513
- return this._getState('SCHEMA_TABLE');
3100
+ return this.$state.get('SCHEMA_TABLE');
2514
3101
  return this.$schema;
2515
3102
  }
2516
3103
  validation(schema) {
2517
- this._setState('VALIDATE_SCHEMA', true);
2518
- this._setState('VALIDATE_SCHEMA_DEFINED', schema);
3104
+ this.$state.set('VALIDATE_SCHEMA', true);
3105
+ this.$state.set('VALIDATE_SCHEMA_DEFINED', schema);
2519
3106
  return this;
2520
3107
  }
2521
3108
  /**
@@ -2527,28 +3114,29 @@ class Model extends AbstractModel_1.AbstractModel {
2527
3114
  return this._valuePattern(column);
2528
3115
  }
2529
3116
  /**
2530
- * @override Method
3117
+ * @override
2531
3118
  * @return {Promise<Record<string,any> | any[] | null | undefined>}
2532
3119
  */
2533
3120
  save() {
2534
3121
  return __awaiter(this, void 0, void 0, function* () {
2535
3122
  this._validateMethod('save');
2536
- switch (String(this._getState('SAVE'))) {
3123
+ switch (String(this.$state.get('SAVE'))) {
2537
3124
  case 'INSERT': return yield this._insertModel();
2538
3125
  case 'UPDATE': return yield this._updateModel();
2539
3126
  case 'INSERT_MULTIPLE': return yield this._createMultipleModel();
2540
3127
  case 'INSERT_NOT_EXISTS': return yield this._insertNotExistsModel();
2541
3128
  case 'UPDATE_OR_INSERT': return yield this._updateOrInsertModel();
2542
3129
  case 'INSERT_OR_SELECT': return yield this._insertOrSelectModel();
2543
- default: throw new Error(`Unknown this [${this._getState('SAVE')}]`);
3130
+ default: throw new Error(`Unknown this [${this.$state.get('SAVE')}]`);
2544
3131
  }
2545
3132
  });
2546
3133
  }
2547
3134
  /**
2548
3135
  *
2549
- * @override Method
3136
+ * @override
2550
3137
  * @param {number} rows number of rows
2551
- * @return {promise<any>}
3138
+ * @param {Function} callback function will be called data and index
3139
+ * @return {promise<any[]>}
2552
3140
  */
2553
3141
  faker(rows, callback) {
2554
3142
  return __awaiter(this, void 0, void 0, function* () {
@@ -2557,7 +3145,7 @@ class Model extends AbstractModel_1.AbstractModel {
2557
3145
  `${this.$constants('SHOW')}`,
2558
3146
  `${this.$constants('FIELDS')}`,
2559
3147
  `${this.$constants('FROM')}`,
2560
- `${this._getState('TABLE_NAME')}`
3148
+ `${this.$state.get('TABLE_NAME')}`
2561
3149
  ].join(' ');
2562
3150
  const schemaModel = this.getSchemaModel();
2563
3151
  const fields = schemaModel == null
@@ -2569,44 +3157,46 @@ class Model extends AbstractModel_1.AbstractModel {
2569
3157
  };
2570
3158
  });
2571
3159
  for (let row = 0; row < rows; row++) {
2572
- this._assertError(this._getState('TABLE_NAME') === '' || this._getState('TABLE_NAME') == null, "Unknow this table");
3160
+ this._assertError(this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null, "Unknow this table");
2573
3161
  let columnAndValue = {};
2574
3162
  for (const { Field: field, Type: type } of fields) {
2575
- const deletedAt = this._valuePattern(this._getState('SOFT_DELETE_FORMAT'));
3163
+ const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
2576
3164
  const passed = ['id', '_id', 'uuid', deletedAt].some(p => field === p);
2577
3165
  if (passed)
2578
3166
  continue;
2579
3167
  columnAndValue = Object.assign(Object.assign({}, columnAndValue), { [field]: this.$utils.faker(type) });
2580
3168
  }
2581
3169
  if (callback) {
2582
- data = [...data, callback(columnAndValue, row)];
3170
+ data.push(callback(columnAndValue, row));
2583
3171
  continue;
2584
3172
  }
2585
- data = [...data, columnAndValue];
3173
+ data.push(columnAndValue);
2586
3174
  }
2587
3175
  return yield this.createMultiple(data).save();
2588
3176
  });
2589
3177
  }
2590
3178
  /**
2591
3179
  * The 'Sync' method is used to check for create or update table or columns with your schema in your model.
2592
- *
2593
- * @property {boolean} force - forec always check all columns if not exists will be created
2594
- * @property {boolean} foreign - foreign key for constraint
2595
- * @return {promise<void>}
3180
+ * @type {object} options
3181
+ * @property {boolean} options.force - forec always check all columns if not exists will be created
3182
+ * @property {boolean} options.log - show log execution with sql statements
3183
+ * @property {boolean} options.foreign - check when has a foreign keys will be created
3184
+ * @property {boolean} options.changed - check when column is changed attribute will be change attribute
3185
+ * @return {Promise<void>}
2596
3186
  */
2597
- sync({ force = false, foreign = false } = {}) {
2598
- var _a, _b, _c, _d;
2599
- return __awaiter(this, void 0, void 0, function* () {
3187
+ sync() {
3188
+ return __awaiter(this, arguments, void 0, function* ({ force = false, foreign = false, changed = false } = {}) {
3189
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2600
3190
  const checkTables = yield this._queryStatement(`${this.$constants('SHOW_TABLES')} ${this.$constants('LIKE')} '${this.getTableName()}'`);
2601
3191
  const existsTables = checkTables.map((c) => Object.values(c)[0]);
2602
3192
  const schemaModel = this.getSchemaModel();
2603
3193
  if (schemaModel == null)
2604
3194
  return this._assertError(schemaModel == null, 'Schema model not found');
2605
3195
  const checkTableIsExists = existsTables.some((table) => table === this.getTableName());
2606
- const syncForeignKey = ({ schemaModel, model }) => __awaiter(this, void 0, void 0, function* () {
2607
- var _e;
3196
+ const syncForeignKey = (_j) => __awaiter(this, [_j], void 0, function* ({ schemaModel, model }) {
3197
+ var _k;
2608
3198
  for (const key in schemaModel) {
2609
- if (((_e = schemaModel[key]) === null || _e === void 0 ? void 0 : _e.foreignKey) == null)
3199
+ if (((_k = schemaModel[key]) === null || _k === void 0 ? void 0 : _k.foreignKey) == null)
2610
3200
  continue;
2611
3201
  const foreign = schemaModel[key].foreignKey;
2612
3202
  const table = typeof foreign.on === "string" ? foreign.on : foreign.on.getTableName();
@@ -2652,6 +3242,29 @@ class Model extends AbstractModel_1.AbstractModel {
2652
3242
  const schemaTable = yield this.getSchema();
2653
3243
  const schemaTableKeys = schemaTable.map((k) => k.Field);
2654
3244
  const schemaModelKeys = Object.keys(schemaModel);
3245
+ const wasChangedColumns = changed ? Object.entries(schemaModel).map(([key, value]) => {
3246
+ const find = schemaTable.find(t => t.Field === key);
3247
+ if (find == null)
3248
+ return null;
3249
+ const compare = String(find.Type).toLocaleLowerCase() !== String(value.type).toLocaleLowerCase();
3250
+ return compare ? key : null;
3251
+ }).filter(d => d != null) : [];
3252
+ if (wasChangedColumns.length) {
3253
+ for (const column of wasChangedColumns) {
3254
+ if (column == null)
3255
+ continue;
3256
+ const type = (_b = (_a = schemaModel[column]) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : null;
3257
+ const attributes = (_d = (_c = schemaModel[column]) === null || _c === void 0 ? void 0 : _c.attributes) !== null && _d !== void 0 ? _d : null;
3258
+ const sql = [
3259
+ this.$constants('ALTER_TABLE'),
3260
+ `\`${this.getTableName()}\``,
3261
+ this.$constants('CHANGE'),
3262
+ `\`${column}\``,
3263
+ `\`${column}\` ${type} ${attributes.join(' ')}`,
3264
+ ].join(' ');
3265
+ yield this._queryStatement(sql);
3266
+ }
3267
+ }
2655
3268
  const missingColumns = schemaModelKeys.filter(schemaModelKey => !schemaTableKeys.includes(schemaModelKey));
2656
3269
  if (!missingColumns.length)
2657
3270
  return;
@@ -2659,16 +3272,16 @@ class Model extends AbstractModel_1.AbstractModel {
2659
3272
  for (const column of missingColumns) {
2660
3273
  const indexWithColumn = entries.findIndex(([key]) => key === column);
2661
3274
  const findAfterIndex = indexWithColumn ? entries[indexWithColumn - 1][0] : null;
2662
- const type = (_b = (_a = schemaModel[column]) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : null;
2663
- const attributes = (_d = (_c = schemaModel[column]) === null || _c === void 0 ? void 0 : _c.attributes) !== null && _d !== void 0 ? _d : null;
3275
+ const type = (_f = (_e = schemaModel[column]) === null || _e === void 0 ? void 0 : _e.type) !== null && _f !== void 0 ? _f : null;
3276
+ const attributes = (_h = (_g = schemaModel[column]) === null || _g === void 0 ? void 0 : _g.attributes) !== null && _h !== void 0 ? _h : null;
2664
3277
  if (findAfterIndex == null || type == null || attributes == null)
2665
3278
  continue;
2666
3279
  const sql = [
2667
- 'ALTER TABLE',
3280
+ this.$constants('ALTER_TABLE'),
2668
3281
  `\`${this.getTableName()}\``,
2669
- 'ADD',
3282
+ this.$constants('ADD'),
2670
3283
  `\`${column}\` ${type} ${attributes.join(' ')}`,
2671
- 'AFTER',
3284
+ this.$constants('AFTER'), ,
2672
3285
  `\`${findAfterIndex}\``
2673
3286
  ].join(' ');
2674
3287
  yield this._queryStatement(sql);
@@ -2676,19 +3289,82 @@ class Model extends AbstractModel_1.AbstractModel {
2676
3289
  return;
2677
3290
  });
2678
3291
  }
2679
- _valuePattern(value) {
2680
- switch (this._getState('PATTERN')) {
3292
+ covertColumnSchemaToFixColumn(column) {
3293
+ const schema = this.$state.get('SCHEMA_TABLE');
3294
+ if (schema == null)
3295
+ return column;
3296
+ const find = schema[column];
3297
+ if (find == null || find.column == null) {
3298
+ return column;
3299
+ }
3300
+ return find.column;
3301
+ }
3302
+ covertFixColumnToColumnSchema(column) {
3303
+ const schema = this.$state.get('SCHEMA_TABLE');
3304
+ if (schema == null)
3305
+ return column;
3306
+ const fixColumns = [];
3307
+ for (const key in schema) {
3308
+ const find = schema[key];
3309
+ if (find.column == null)
3310
+ continue;
3311
+ fixColumns.push({
3312
+ key,
3313
+ value: find.column
3314
+ });
3315
+ }
3316
+ const findColumnSameTheColumn = fixColumns.find(fixColumn => fixColumn.value === column);
3317
+ return findColumnSameTheColumn == null ? column : findColumnSameTheColumn.key;
3318
+ }
3319
+ _valuePattern(column) {
3320
+ const fixColumn = this.covertColumnSchemaToFixColumn(column);
3321
+ switch (this.$state.get('PATTERN')) {
2681
3322
  case this.$constants('PATTERN').snake_case: {
2682
- return value.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`);
3323
+ return fixColumn === column
3324
+ ? column.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`)
3325
+ : fixColumn;
2683
3326
  }
2684
3327
  case this.$constants('PATTERN').camelCase: {
2685
- return value.replace(/(.(\_|-|\s)+.)/g, (str) => `${str[0]}${str[str.length - 1].toUpperCase()}`);
3328
+ return fixColumn === column
3329
+ ? column.replace(/(.(\_|-|\s)+.)/g, (str) => `${str[0]}${str[str.length - 1].toUpperCase()}`)
3330
+ : fixColumn;
2686
3331
  }
2687
- default: return value;
3332
+ default: return column;
2688
3333
  }
2689
3334
  }
3335
+ _checkTableLoggerIsExists() {
3336
+ return __awaiter(this, void 0, void 0, function* () {
3337
+ if (!this.$state.get('LOGGER'))
3338
+ return;
3339
+ const tableLogger = this.$state.get('TABLE_LOGGER');
3340
+ const checkTables = yield new DB_1.DB().query(`${this.$constants('SHOW_TABLES')} ${this.$constants('LIKE')} '${tableLogger}'`);
3341
+ const existsTables = checkTables.map((c) => Object.values(c)[0])[0];
3342
+ if (existsTables != null)
3343
+ return;
3344
+ const schemaLogger = {
3345
+ id: new Blueprint_1.Blueprint().int().notNull().primary().autoIncrement(),
3346
+ uuid: new Blueprint_1.Blueprint().varchar(50).null(),
3347
+ model: new Blueprint_1.Blueprint().varchar(50).null(),
3348
+ query: new Blueprint_1.Blueprint().longText().null(),
3349
+ action: new Blueprint_1.Blueprint().varchar(50).null(),
3350
+ data: new Blueprint_1.Blueprint().json().null(),
3351
+ changed: new Blueprint_1.Blueprint().json().null(),
3352
+ createdAt: new Blueprint_1.Blueprint().timestamp().null(),
3353
+ updatedAt: new Blueprint_1.Blueprint().timestamp().null()
3354
+ };
3355
+ const sql = new Schema_1.Schema().createTable(`\`${tableLogger}\``, schemaLogger);
3356
+ yield new DB_1.DB().debug(this.$state.get('DEBUG')).query(sql);
3357
+ return;
3358
+ });
3359
+ }
3360
+ _columnPattern(column) {
3361
+ if (column.startsWith(this.$constants('RAW'))) {
3362
+ return column.replace(this.$constants('RAW'), '');
3363
+ }
3364
+ return this._valuePattern(column);
3365
+ }
2690
3366
  _isPatternSnakeCase() {
2691
- return this._getState('PATTERN') === this.$constants('PATTERN').snake_case;
3367
+ return this.$state.get('PATTERN') === this.$constants('PATTERN').snake_case;
2692
3368
  }
2693
3369
  _classToTableName(className, { singular = false } = {}) {
2694
3370
  if (className == null)
@@ -2699,18 +3375,15 @@ class Model extends AbstractModel_1.AbstractModel {
2699
3375
  return pluralize_1.default.plural(this._valuePattern(tb));
2700
3376
  }
2701
3377
  _makeTableName() {
2702
- if (this.$table == null || this.$table === '') {
2703
- const tableName = this._classToTableName();
2704
- this._setState('TABLE_NAME', `\`${this._valuePattern(tableName)}\``);
2705
- return this;
2706
- }
2707
- this._setState('TABLE_NAME', `\`${this._valuePattern(this.$table)}\``);
3378
+ const tableName = this._classToTableName();
3379
+ this.$state.set('TABLE_NAME', `\`${this._valuePattern(tableName)}\``);
3380
+ this.$state.set('MODEL_NAME', this.constructor.name);
2708
3381
  return this;
2709
3382
  }
2710
3383
  _handleSoftDelete() {
2711
- if (this._getState('SOFT_DELETE')) {
2712
- const deletedAt = this._valuePattern(this._getState('SOFT_DELETE_FORMAT'));
2713
- const wheres = this._getState('WHERE');
3384
+ if (this.$state.get('SOFT_DELETE')) {
3385
+ const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
3386
+ const wheres = this.$state.get('WHERE');
2714
3387
  const softDeleteIsNull = [
2715
3388
  this.bindColumn(`${this.getTableName()}.${deletedAt}`),
2716
3389
  this.$constants('IS_NULL')
@@ -2723,6 +3396,28 @@ class Model extends AbstractModel_1.AbstractModel {
2723
3396
  }
2724
3397
  return this;
2725
3398
  }
3399
+ _handleSelect() {
3400
+ const selects = this.$state.get('SELECT');
3401
+ const hasStart = selects === null || selects === void 0 ? void 0 : selects.some(s => s.includes('*'));
3402
+ if (selects.length || hasStart)
3403
+ return this;
3404
+ const schemaColumns = this.getSchemaModel();
3405
+ if (schemaColumns == null)
3406
+ return this;
3407
+ const columns = [];
3408
+ for (const key in schemaColumns) {
3409
+ const schemaColumn = schemaColumns[key];
3410
+ if (schemaColumn.column == null) {
3411
+ columns.push(this.bindColumn(key));
3412
+ continue;
3413
+ }
3414
+ columns.push(this.bindColumn(schemaColumn.column, false));
3415
+ }
3416
+ if (!columns.length)
3417
+ return this;
3418
+ this.$state.set('SELECT', columns);
3419
+ return this;
3420
+ }
2726
3421
  /**
2727
3422
  *
2728
3423
  * generate sql statements
@@ -2730,14 +3425,15 @@ class Model extends AbstractModel_1.AbstractModel {
2730
3425
  */
2731
3426
  _queryBuilder() {
2732
3427
  this._handleSoftDelete();
3428
+ this._handleSelect();
2733
3429
  return this._buildQueryStatement();
2734
3430
  }
2735
3431
  _showOnly(data) {
2736
3432
  let result = [];
2737
- const hasNameRelation = this._getState('RELATIONS').map((w) => { var _a; return (_a = w.as) !== null && _a !== void 0 ? _a : w.name; });
3433
+ const hasNameRelation = this.$state.get('RELATIONS').map((w) => { var _a; return (_a = w.as) !== null && _a !== void 0 ? _a : w.name; });
2738
3434
  data.forEach((d) => {
2739
3435
  let newData = {};
2740
- this._getState('ONLY').forEach((only) => {
3436
+ this.$state.get('ONLY').forEach((only) => {
2741
3437
  if (d.hasOwnProperty(only))
2742
3438
  newData = Object.assign(Object.assign({}, newData), { [only]: d[only] });
2743
3439
  });
@@ -2751,14 +3447,14 @@ class Model extends AbstractModel_1.AbstractModel {
2751
3447
  }
2752
3448
  _validateSchema(data, action) {
2753
3449
  return __awaiter(this, void 0, void 0, function* () {
2754
- const validateSchema = this._getState('VALIDATE_SCHEMA');
3450
+ const validateSchema = this.$state.get('VALIDATE_SCHEMA');
2755
3451
  if (!validateSchema)
2756
3452
  return;
2757
3453
  const schemaTable = this.getSchemaModel();
2758
3454
  if (schemaTable == null) {
2759
3455
  return this._assertError(schemaTable == null, `This method "validateSchema" isn't validation without schema. Please use the method "useSchema" for define your schema`);
2760
3456
  }
2761
- const schemaTableDefined = this._getState('VALIDATE_SCHEMA_DEFINED');
3457
+ const schemaTableDefined = this.$state.get('VALIDATE_SCHEMA_DEFINED');
2762
3458
  const schema = schemaTableDefined !== null && schemaTableDefined !== void 0 ? schemaTableDefined : Object.keys(schemaTable).reduce((acc, key) => {
2763
3459
  acc[key] = schemaTable[key].valueType;
2764
3460
  return acc;
@@ -2768,6 +3464,8 @@ class Model extends AbstractModel_1.AbstractModel {
2768
3464
  const regexDate = /[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/;
2769
3465
  const regexDateTime = /[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]/;
2770
3466
  for (const column in schema) {
3467
+ if (data == null)
3468
+ continue;
2771
3469
  const s = schema[column];
2772
3470
  const r = data[column];
2773
3471
  const typeOf = (r) => this.$utils.typeOf(r);
@@ -2798,77 +3496,80 @@ class Model extends AbstractModel_1.AbstractModel {
2798
3496
  this._assertError(`This column "${column}" is must be JSON`);
2799
3497
  }
2800
3498
  }
2801
- if (s.length)
2802
- this._assertError((`${r}`.length > s.length), `This column "${column}" is more than "${s.length}" length of characters`);
2803
- if (s.maxLength)
2804
- this._assertError((`${r}`.length > s.maxLength), `This column "${column}" is more than "${s.maxLength}" length of characters`);
2805
- if (s.minLength)
2806
- this._assertError((`${r}`.length < s.minLength), `This column "${column}" is less than "${s.minLength}" length of characters`);
3499
+ if (s.length) {
3500
+ return this._assertError((`${r}`.length > s.length), `This column "${column}" is more than "${s.length}" length of characters`);
3501
+ }
3502
+ if (s.maxLength) {
3503
+ return this._assertError((`${r}`.length > s.maxLength), `This column "${column}" is more than "${s.maxLength}" length of characters`);
3504
+ }
3505
+ if (s.minLength) {
3506
+ return this._assertError((`${r}`.length < s.minLength), `This column "${column}" is less than "${s.minLength}" length of characters`);
3507
+ }
2807
3508
  if (s.max)
2808
- this._assertError(r > s.max, `This column "${column}" is more than "${s.max}"`);
3509
+ return this._assertError(r > s.max, `This column "${column}" is more than "${s.max}"`);
2809
3510
  if (s.min)
2810
- this._assertError(r < s.min, `This column "${column}" is less than "${s.min}"`);
3511
+ return this._assertError(r < s.min, `This column "${column}" is less than "${s.min}"`);
2811
3512
  if (s.enum && s.enum.length) {
2812
- this._assertError(!s.enum.some((e) => e === r), `This column "${column}" is must be in ${s.enum.map((e) => `"${e}"`)}`);
3513
+ return this._assertError(!s.enum.some((e) => e === r), `This column "${column}" is must be in ${s.enum.map((e) => `"${e}"`)}`);
2813
3514
  }
2814
3515
  if (s.match)
2815
- this._assertError(!s.match.test(r), `This column "${column}" is not match a regular expression`);
3516
+ return this._assertError(!s.match.test(r), `This column "${column}" is not match a regular expression`);
2816
3517
  if (s.fn)
2817
- this._assertError(!(yield s.fn(r)), `This column "${column}" is not valid with function`);
3518
+ return this._assertError(!(yield s.fn(r)), `This column "${column}" is not valid with function`);
2818
3519
  if (s.unique && action === 'insert') {
2819
3520
  const exist = yield new Model()
2820
3521
  .copyModel(this, { select: true, where: true, limit: true })
2821
- .where([column], r)
2822
- .debug(this._getState('DEBUG'))
3522
+ .where(column, r)
3523
+ .debug(this.$state.get('DEBUG'))
2823
3524
  .exists();
2824
- this._assertError(exist, `This column "${column}" is duplicated`);
3525
+ return this._assertError(exist, `This column "${column}" is duplicated`);
2825
3526
  }
2826
3527
  }
2827
3528
  return;
2828
3529
  });
2829
3530
  }
2830
- _execute({ sql, type, message, options }) {
2831
- var _a, _b;
2832
- return __awaiter(this, void 0, void 0, function* () {
3531
+ _execute(_a) {
3532
+ return __awaiter(this, arguments, void 0, function* ({ sql, type, message, options }) {
3533
+ var _b, _c;
2833
3534
  let result = yield this._queryStatement(sql);
2834
3535
  if (!result.length)
2835
3536
  return this._returnEmpty(type, result, message, options);
2836
- const relations = this._getState('RELATIONS');
3537
+ const relations = this.$state.get('RELATIONS');
2837
3538
  for (const relation of relations) {
2838
- result = (_b = yield ((_a = this.$relation) === null || _a === void 0 ? void 0 : _a.load(result, relation))) !== null && _b !== void 0 ? _b : [];
3539
+ result = (_c = yield ((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.load(result, relation))) !== null && _c !== void 0 ? _c : [];
2839
3540
  }
2840
- if (this._getState('HIDDEN').length)
3541
+ if (this.$state.get('HIDDEN').length)
2841
3542
  this._hiddenColumnModel(result);
2842
3543
  return (yield this._returnResult(type, result)) || this._returnEmpty(type, result, message, options);
2843
3544
  });
2844
3545
  }
2845
- _executeGroup(dataParents, type = 'GET') {
2846
- var _a, _b, _c;
2847
- return __awaiter(this, void 0, void 0, function* () {
3546
+ _executeGroup(dataParents_1) {
3547
+ return __awaiter(this, arguments, void 0, function* (dataParents, type = 'GET') {
3548
+ var _a, _b, _c;
2848
3549
  if (!dataParents.length)
2849
3550
  return this._returnEmpty(type, dataParents);
2850
- const relations = this._getState('RELATIONS');
3551
+ const relations = this.$state.get('RELATIONS');
2851
3552
  if (relations.length) {
2852
3553
  for (const relation of relations) {
2853
3554
  dataParents = (_b = yield ((_a = this.$relation) === null || _a === void 0 ? void 0 : _a.load(dataParents, relation))) !== null && _b !== void 0 ? _b : [];
2854
3555
  }
2855
3556
  }
2856
- if ((_c = this._getState('HIDDEN')) === null || _c === void 0 ? void 0 : _c.length)
3557
+ if ((_c = this.$state.get('HIDDEN')) === null || _c === void 0 ? void 0 : _c.length)
2857
3558
  this._hiddenColumnModel(dataParents);
2858
3559
  const resultData = yield this._returnResult(type, dataParents);
2859
3560
  return resultData || this._returnEmpty(type, dataParents);
2860
3561
  });
2861
3562
  }
2862
3563
  _pagination(data) {
2863
- var _a;
2864
3564
  return __awaiter(this, void 0, void 0, function* () {
2865
- const currentPage = +(this._getState('PAGE'));
2866
- const limit = Number(this._getState('PER_PAGE'));
3565
+ var _a;
3566
+ const currentPage = +(this.$state.get('PAGE'));
3567
+ const limit = Number(this.$state.get('PER_PAGE'));
2867
3568
  this._assertError(limit < 1, "This pagination needed limit minimun less 1 for limit");
2868
3569
  const total = yield new Model()
2869
- .copyModel(this, { where: true, select: true })
3570
+ .copyModel(this, { where: true })
2870
3571
  .bind(this.$pool.get())
2871
- .debug(this._getState('DEBUG'))
3572
+ .debug(this.$state.get('DEBUG'))
2872
3573
  .count();
2873
3574
  let lastPage = Math.ceil(total / limit) || 0;
2874
3575
  lastPage = lastPage > 1 ? lastPage : 1;
@@ -2901,6 +3602,13 @@ class Model extends AbstractModel_1.AbstractModel {
2901
3602
  let emptyData = null;
2902
3603
  switch (type) {
2903
3604
  case 'FIRST': {
3605
+ if (this.$state.get('RETURN_TYPE') != null) {
3606
+ const returnType = this.$state.get('RETURN_TYPE');
3607
+ emptyData = this._resultHandler(returnType === 'object'
3608
+ ? null
3609
+ : returnType === 'array' ? [] : null);
3610
+ break;
3611
+ }
2904
3612
  emptyData = null;
2905
3613
  break;
2906
3614
  }
@@ -2914,10 +3622,16 @@ class Model extends AbstractModel_1.AbstractModel {
2914
3622
  }
2915
3623
  throw Object.assign({ message }, options);
2916
3624
  }
2917
- emptyData = null;
2918
3625
  break;
2919
3626
  }
2920
3627
  case 'GET': {
3628
+ if (this.$state.get('RETURN_TYPE') != null) {
3629
+ const returnType = this.$state.get('RETURN_TYPE');
3630
+ emptyData = this._resultHandler(returnType === 'object'
3631
+ ? null
3632
+ : returnType === 'array' ? [] : null);
3633
+ break;
3634
+ }
2921
3635
  emptyData = [];
2922
3636
  break;
2923
3637
  }
@@ -2925,9 +3639,9 @@ class Model extends AbstractModel_1.AbstractModel {
2925
3639
  emptyData = {
2926
3640
  meta: {
2927
3641
  total: 0,
2928
- limit: Number(this._getState('PER_PAGE')),
3642
+ limit: Number(this.$state.get('PER_PAGE')),
2929
3643
  totalPage: 0,
2930
- currentPage: Number(this._getState('PAGE')),
3644
+ currentPage: Number(this.$state.get('PAGE')),
2931
3645
  lastPage: 0,
2932
3646
  nextPage: 0,
2933
3647
  prevPage: 0
@@ -2940,20 +3654,20 @@ class Model extends AbstractModel_1.AbstractModel {
2940
3654
  }
2941
3655
  if (this._isPatternSnakeCase()) {
2942
3656
  const empty = this.$utils.snakeCase(this._resultHandler(emptyData));
2943
- yield this.$utils.hookHandle(this._getState('HOOKS'), empty);
3657
+ yield this.$utils.hookHandle(this.$state.get('HOOKS'), empty);
2944
3658
  this._observer(empty, 'selected');
2945
3659
  return empty;
2946
3660
  }
2947
3661
  const empty = this._resultHandler(emptyData);
2948
- yield this.$utils.hookHandle(this._getState('HOOKS'), empty);
3662
+ yield this.$utils.hookHandle(this.$state.get('HOOKS'), empty);
2949
3663
  this._observer(empty, 'selected');
2950
3664
  return empty;
2951
3665
  });
2952
3666
  }
2953
3667
  _returnResult(type, data) {
2954
- var _a, _b, _c, _d, _e;
2955
3668
  return __awaiter(this, void 0, void 0, function* () {
2956
- const registry = this._getState('REGISTRY');
3669
+ var _a, _b, _c, _d, _e;
3670
+ const registry = this.$state.get('REGISTRY');
2957
3671
  if (((_a = Object.keys(registry)) === null || _a === void 0 ? void 0 : _a.length) && registry != null) {
2958
3672
  for (const d of data) {
2959
3673
  for (const name in registry) {
@@ -2961,10 +3675,10 @@ class Model extends AbstractModel_1.AbstractModel {
2961
3675
  }
2962
3676
  }
2963
3677
  }
2964
- const functionRelation = this._getState('FUNCTION_RELATION');
3678
+ const functionRelation = this.$state.get('FUNCTION_RELATION');
2965
3679
  if (functionRelation) {
2966
3680
  for (const d of data) {
2967
- for (const r of this._getState('RELATION')) {
3681
+ for (const r of this.$state.get('RELATION')) {
2968
3682
  d[`$${r.name}`] = (cb) => __awaiter(this, void 0, void 0, function* () {
2969
3683
  var _f, _g;
2970
3684
  const query = cb ? cb(new r.model()) : new r.model();
@@ -2981,38 +3695,70 @@ class Model extends AbstractModel_1.AbstractModel {
2981
3695
  }
2982
3696
  }
2983
3697
  }
2984
- if ((_b = this._getState('ONLY')) === null || _b === void 0 ? void 0 : _b.length)
3698
+ if ((_b = this.$state.get('ONLY')) === null || _b === void 0 ? void 0 : _b.length)
2985
3699
  data = this._showOnly(data);
2986
3700
  let result = null;
3701
+ let res = [];
3702
+ for (const r of data) {
3703
+ const newData = {};
3704
+ for (const origin in r) {
3705
+ const value = r[origin];
3706
+ const covert = this.covertFixColumnToColumnSchema(origin);
3707
+ if (origin === covert) {
3708
+ newData[origin] = value;
3709
+ continue;
3710
+ }
3711
+ newData[covert] = value;
3712
+ }
3713
+ if (Object.keys(newData).length) {
3714
+ res.push(newData);
3715
+ }
3716
+ }
3717
+ if (!res.length)
3718
+ res = data;
2987
3719
  switch (type) {
2988
3720
  case 'FIRST': {
2989
- if (this._getState('PLUCK')) {
2990
- const pluck = this._getState('PLUCK');
2991
- const newData = data.shift();
3721
+ if (this.$state.get('PLUCK')) {
3722
+ const pluck = this.$state.get('PLUCK');
3723
+ const newData = res[0];
2992
3724
  const checkProperty = newData.hasOwnProperty(pluck);
2993
3725
  this._assertError(!checkProperty, `Can't find property '${pluck}' of result`);
2994
3726
  result = this._resultHandler(newData[pluck]);
2995
3727
  break;
2996
3728
  }
2997
- result = this._resultHandler((_c = data.shift()) !== null && _c !== void 0 ? _c : null);
3729
+ if (this.$state.get('RETURN_TYPE') != null) {
3730
+ const returnType = this.$state.get('RETURN_TYPE');
3731
+ result = this._resultHandler(returnType === 'object'
3732
+ ? res[0]
3733
+ : returnType === 'array' ? res : [res]);
3734
+ break;
3735
+ }
3736
+ result = this._resultHandler((_c = res[0]) !== null && _c !== void 0 ? _c : null);
2998
3737
  break;
2999
3738
  }
3000
3739
  case 'FIRST_OR_ERROR': {
3001
- if (this._getState('PLUCK')) {
3002
- const pluck = this._getState('PLUCK');
3003
- const newData = data.shift();
3740
+ if (this.$state.get('PLUCK')) {
3741
+ const pluck = this.$state.get('PLUCK');
3742
+ const newData = res[0];
3004
3743
  const checkProperty = newData.hasOwnProperty(pluck);
3005
3744
  this._assertError(!checkProperty, `Can't find property '${pluck}' of result`);
3006
3745
  result = (_d = this._resultHandler(newData[pluck])) !== null && _d !== void 0 ? _d : null;
3007
3746
  break;
3008
3747
  }
3009
- result = this._resultHandler((_e = data.shift()) !== null && _e !== void 0 ? _e : null);
3748
+ if (this.$state.get('RETURN_TYPE') != null) {
3749
+ const returnType = this.$state.get('RETURN_TYPE');
3750
+ result = this._resultHandler(returnType === 'object'
3751
+ ? res[0]
3752
+ : returnType === 'array' ? res : [res]);
3753
+ break;
3754
+ }
3755
+ result = this._resultHandler((_e = res[0]) !== null && _e !== void 0 ? _e : null);
3010
3756
  break;
3011
3757
  }
3012
3758
  case 'GET': {
3013
- if (this._getState('CHUNK')) {
3759
+ if (this.$state.get('CHUNK')) {
3014
3760
  const r = data.reduce((resultArray, item, index) => {
3015
- const chunkIndex = Math.floor(index / this._getState('CHUNK'));
3761
+ const chunkIndex = Math.floor(index / this.$state.get('CHUNK'));
3016
3762
  if (!resultArray[chunkIndex])
3017
3763
  resultArray[chunkIndex] = [];
3018
3764
  resultArray[chunkIndex].push(item);
@@ -3021,31 +3767,38 @@ class Model extends AbstractModel_1.AbstractModel {
3021
3767
  result = this._resultHandler(r);
3022
3768
  break;
3023
3769
  }
3024
- if (this._getState('PLUCK')) {
3025
- const pluck = this._getState('PLUCK');
3770
+ if (this.$state.get('PLUCK')) {
3771
+ const pluck = this.$state.get('PLUCK');
3026
3772
  const newData = data.map((d) => d[pluck]);
3027
3773
  this._assertError(newData.every((d) => d == null), `Can't find property '${pluck}' of result`);
3028
3774
  result = this._resultHandler(newData);
3029
3775
  break;
3030
3776
  }
3031
- result = this._resultHandler(data);
3777
+ if (this.$state.get('RETURN_TYPE') != null) {
3778
+ const returnType = this.$state.get('RETURN_TYPE');
3779
+ result = this._resultHandler(returnType === 'object'
3780
+ ? data[0]
3781
+ : returnType === 'array' ? data : [data]);
3782
+ break;
3783
+ }
3784
+ result = this._resultHandler(res);
3032
3785
  break;
3033
3786
  }
3034
3787
  case 'PAGINATION': {
3035
- result = yield this._pagination(data);
3788
+ result = yield this._pagination(res);
3036
3789
  break;
3037
3790
  }
3038
3791
  default: {
3039
3792
  throw new Error('Missing method first get or pagination');
3040
3793
  }
3041
3794
  }
3042
- yield this.$utils.hookHandle(this._getState('HOOKS'), result);
3043
- this._observer(result, 'selected');
3795
+ yield this.$utils.hookHandle(this.$state.get('HOOKS'), result);
3796
+ yield this._observer(result, 'selected');
3044
3797
  return result;
3045
3798
  });
3046
3799
  }
3047
3800
  _hiddenColumnModel(data) {
3048
- const hiddens = this._getState('HIDDEN');
3801
+ const hiddens = this.$state.get('HIDDEN');
3049
3802
  for (const hidden of hiddens) {
3050
3803
  for (const objColumn of data) {
3051
3804
  delete objColumn[hidden];
@@ -3054,14 +3807,14 @@ class Model extends AbstractModel_1.AbstractModel {
3054
3807
  return data;
3055
3808
  }
3056
3809
  _attach(name, dataId, fields) {
3057
- var _a;
3058
3810
  return __awaiter(this, void 0, void 0, function* () {
3811
+ var _a;
3059
3812
  this._assertError(!Array.isArray(dataId), `this ${dataId} is not an array`);
3060
- const relation = (_a = this._getState('RELATION')) === null || _a === void 0 ? void 0 : _a.find((data) => data.name === name);
3813
+ const relation = (_a = this.$state.get('RELATION')) === null || _a === void 0 ? void 0 : _a.find((data) => data.name === name);
3061
3814
  this._assertError(!relation, `unknown name relation ['${name}'] in model`);
3062
3815
  const thisTable = this.$utils.columnRelation(this.constructor.name);
3063
3816
  const relationTable = this._classToTableName(relation.model.name, { singular: true });
3064
- const result = this._getState('RESULT');
3817
+ const result = this.$state.get('RESULT');
3065
3818
  try {
3066
3819
  const pivotTable = `${thisTable}_${relationTable}`;
3067
3820
  const success = yield new DB_1.DB().table(pivotTable).createMultiple(dataId.map((id) => {
@@ -3090,11 +3843,11 @@ class Model extends AbstractModel_1.AbstractModel {
3090
3843
  _detach(name, dataId) {
3091
3844
  return __awaiter(this, void 0, void 0, function* () {
3092
3845
  this._assertError(!Array.isArray(dataId), `this ${dataId} is not an array`);
3093
- const relation = this._getState('RELATION').find((data) => data.name === name);
3846
+ const relation = this.$state.get('RELATION').find((data) => data.name === name);
3094
3847
  this._assertError(!relation, `unknown name relation [${name}] in model`);
3095
3848
  const thisTable = this.$utils.columnRelation(this.constructor.name);
3096
3849
  const relationTable = this._classToTableName(relation.model.name, { singular: true });
3097
- const result = this._getState('RESULT');
3850
+ const result = this.$state.get('RESULT');
3098
3851
  try {
3099
3852
  const pivotTable = `${thisTable}_${relationTable}`;
3100
3853
  for (const id of dataId) {
@@ -3128,44 +3881,42 @@ class Model extends AbstractModel_1.AbstractModel {
3128
3881
  }
3129
3882
  _queryUpdateModel(objects) {
3130
3883
  this.$utils.covertDataToDateIfDate(objects);
3131
- if (this._getState('TIMESTAMP')) {
3132
- const updatedAt = this._valuePattern(this._getState('TIMESTAMP_FORMAT').UPDATED_AT);
3884
+ if (this.$state.get('TIMESTAMP')) {
3885
+ const updatedAt = this._valuePattern(this.$state.get('TIMESTAMP_FORMAT').UPDATED_AT);
3133
3886
  objects = Object.assign(Object.assign({}, objects), { [updatedAt]: this.$utils.timestamp() });
3134
3887
  }
3135
3888
  const keyValue = Object.entries(objects).map(([column, value]) => {
3136
- if (typeof value === 'string' && !(value.includes(this.$constants('RAW'))))
3137
- value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
3138
- return `\`${column}\` = ${value == null || value === 'NULL'
3889
+ if (typeof value === 'string' && !(value.includes(this.$constants('RAW')))) {
3890
+ value = this.$utils.escapeActions(value);
3891
+ }
3892
+ return `${this.bindColumn(column)} = ${value == null || value === 'NULL'
3139
3893
  ? 'NULL'
3140
- : typeof value === 'string' && value.includes(this.$constants('RAW'))
3141
- ? `${this.$utils.covertBooleanToNumber(value)}`.replace(this.$constants('RAW'), '')
3142
- : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
3894
+ : this._checkValueHasRaw(value)}`;
3143
3895
  });
3144
3896
  return `${this.$constants('SET')} ${keyValue.join(', ')}`;
3145
3897
  }
3146
3898
  _queryInsertModel(data) {
3147
3899
  this.$utils.covertDataToDateIfDate(data);
3148
- const hasTimestamp = Boolean(this._getState('TIMESTAMP'));
3900
+ const hasTimestamp = Boolean(this.$state.get('TIMESTAMP'));
3149
3901
  if (hasTimestamp) {
3150
- const format = this._getState('TIMESTAMP_FORMAT');
3902
+ const format = this.$state.get('TIMESTAMP_FORMAT');
3151
3903
  const createdAt = this._valuePattern(String(format === null || format === void 0 ? void 0 : format.CREATED_AT));
3152
3904
  const updatedAt = this._valuePattern(String(format === null || format === void 0 ? void 0 : format.UPDATED_AT));
3153
- data = Object.assign({ [createdAt]: this.$utils.timestamp(), [updatedAt]: this.$utils.timestamp() }, data);
3905
+ data = Object.assign(Object.assign({}, data), { [createdAt]: this.$utils.timestamp(), [updatedAt]: this.$utils.timestamp() });
3154
3906
  }
3155
- const hasUUID = data.hasOwnProperty(this._getState('UUID_FORMAT'));
3156
- if (this._getState('UUID') && !hasUUID) {
3157
- const uuidFormat = this._getState('UUID_FORMAT');
3907
+ const hasUUID = data.hasOwnProperty(this.$state.get('UUID_FORMAT'));
3908
+ if (this.$state.get('UUID') && !hasUUID) {
3909
+ const uuidFormat = this.$state.get('UUID_FORMAT');
3158
3910
  data = Object.assign({ [uuidFormat]: this.$utils.generateUUID() }, data);
3159
3911
  }
3160
- const columns = Object.keys(data).map((column) => `\`${column}\``);
3912
+ const columns = Object.keys(data).map((column) => this.bindColumn(column));
3161
3913
  const values = Object.values(data).map((value) => {
3162
- if (typeof value === 'string' && !(value.includes(this.$constants('RAW'))))
3163
- value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
3914
+ if (typeof value === 'string' && !(value.includes(this.$constants('RAW')))) {
3915
+ value = this.$utils.escapeActions(value);
3916
+ }
3164
3917
  return `${value == null || value === 'NULL'
3165
3918
  ? 'NULL'
3166
- : typeof value === 'string' && value.includes(this.$constants('RAW'))
3167
- ? `${this.$utils.covertBooleanToNumber(value)}`.replace(this.$constants('RAW'), '')
3168
- : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
3919
+ : this._checkValueHasRaw(value)}`;
3169
3920
  });
3170
3921
  const sql = [
3171
3922
  `(${columns.join(', ')})`,
@@ -3177,12 +3928,12 @@ class Model extends AbstractModel_1.AbstractModel {
3177
3928
  _queryInsertMultipleModel(data) {
3178
3929
  var _a;
3179
3930
  let values = [];
3180
- let columns = Object.keys((_a = [...data]) === null || _a === void 0 ? void 0 : _a.shift()).map((column) => `\`${column}\``);
3931
+ let columns = Object.keys((_a = [...data]) === null || _a === void 0 ? void 0 : _a.shift()).map((column) => column);
3181
3932
  for (let objects of data) {
3182
3933
  this.$utils.covertDataToDateIfDate(data);
3183
- const hasTimestamp = this._getState('TIMESTAMP');
3934
+ const hasTimestamp = this.$state.get('TIMESTAMP');
3184
3935
  if (hasTimestamp) {
3185
- const format = this._getState('TIMESTAMP_FORMAT');
3936
+ const format = this.$state.get('TIMESTAMP_FORMAT');
3186
3937
  const createdAt = this._valuePattern(format.CREATED_AT);
3187
3938
  const updatedAt = this._valuePattern(format.UPDATED_AT);
3188
3939
  objects = Object.assign(Object.assign({}, objects), { [createdAt]: this.$utils.timestamp(), [updatedAt]: this.$utils.timestamp() });
@@ -3192,23 +3943,22 @@ class Model extends AbstractModel_1.AbstractModel {
3192
3943
  `\`${updatedAt}\``
3193
3944
  ];
3194
3945
  }
3195
- const hasUUID = objects.hasOwnProperty(this._getState('UUID_FORMAT'));
3196
- if (this._getState('UUID') && !hasUUID) {
3197
- const uuidFormat = this._getState('UUID_FORMAT');
3198
- objects = Object.assign(Object.assign({}, objects), { [uuidFormat]: this.$utils.generateUUID() });
3946
+ const hasUUID = objects.hasOwnProperty(this.$state.get('UUID_FORMAT'));
3947
+ if (this.$state.get('UUID') && !hasUUID) {
3948
+ const uuidFormat = this.$state.get('UUID_FORMAT');
3949
+ objects = Object.assign({ [uuidFormat]: this.$utils.generateUUID() }, objects);
3199
3950
  columns = [
3200
- ...columns,
3201
- `\`${uuidFormat}\``
3951
+ `\`${uuidFormat}\``,
3952
+ ...columns
3202
3953
  ];
3203
3954
  }
3204
3955
  const v = Object.values(objects).map((value) => {
3205
- if (typeof value === 'string' && !(value.includes(this.$constants('RAW'))))
3206
- value = value === null || value === void 0 ? void 0 : value.replace(/'/g, '');
3956
+ if (typeof value === 'string' && !(value.includes(this.$constants('RAW')))) {
3957
+ value = this.$utils.escapeActions(value);
3958
+ }
3207
3959
  return `${value == null || value === 'NULL'
3208
3960
  ? 'NULL'
3209
- : typeof value === 'string' && value.includes(this.$constants('RAW'))
3210
- ? `${this.$utils.covertBooleanToNumber(value)}`.replace(this.$constants('RAW'), '')
3211
- : `'${this.$utils.covertBooleanToNumber(value)}'`}`;
3961
+ : this._checkValueHasRaw(value)}`;
3212
3962
  });
3213
3963
  values = [
3214
3964
  ...values,
@@ -3216,22 +3966,22 @@ class Model extends AbstractModel_1.AbstractModel {
3216
3966
  ];
3217
3967
  }
3218
3968
  return [
3219
- `(${[...new Set(columns)].join(',')})`,
3969
+ `(${[...new Set(columns.map(c => this.bindColumn(c)))].join(',')})`,
3220
3970
  `${this.$constants('VALUES')}`,
3221
3971
  `${values.join(', ')}`
3222
3972
  ].join(' ');
3223
3973
  }
3224
3974
  _insertNotExistsModel() {
3225
3975
  return __awaiter(this, void 0, void 0, function* () {
3226
- this._assertError(!this._getState('where').length, "This method 'createNotExists' is require to use 'where' conditions");
3976
+ this._assertError(!this.$state.get('where').length, "The 'createNotExists' method requires the use of 'where' conditions.");
3227
3977
  const check = (yield new Model()
3228
3978
  .copyModel(this, { where: true, select: true, limit: true })
3229
3979
  .bind(this.$pool.get())
3230
- .debug(this._getState('DEBUG'))
3980
+ .debug(this.$state.get('DEBUG'))
3231
3981
  .exists()) || false;
3232
3982
  if (check)
3233
3983
  return this._resultHandler(null);
3234
- yield this._validateSchema(this._getState('DATA'), 'insert');
3984
+ yield this._validateSchema(this.$state.get('DATA'), 'insert');
3235
3985
  const [result, id] = yield this._actionStatement({
3236
3986
  sql: this._queryBuilder().insert(),
3237
3987
  returnId: true
@@ -3241,7 +3991,7 @@ class Model extends AbstractModel_1.AbstractModel {
3241
3991
  const resultData = yield new Model()
3242
3992
  .copyModel(this, { select: true })
3243
3993
  .bind(this.$pool.get())
3244
- .debug(this._getState('DEBUG'))
3994
+ .debug(this.$state.get('DEBUG'))
3245
3995
  .where('id', id)
3246
3996
  .first();
3247
3997
  return this._resultHandler(resultData);
@@ -3249,12 +3999,12 @@ class Model extends AbstractModel_1.AbstractModel {
3249
3999
  }
3250
4000
  _insertModel() {
3251
4001
  return __awaiter(this, void 0, void 0, function* () {
3252
- yield this._validateSchema(this._getState('DATA'), 'insert');
4002
+ yield this._validateSchema(this.$state.get('DATA'), 'insert');
3253
4003
  const [result, id] = yield this._actionStatement({
3254
4004
  sql: this._queryBuilder().insert(),
3255
4005
  returnId: true
3256
4006
  });
3257
- if (this._getState('VOID'))
4007
+ if (this.$state.get('VOID'))
3258
4008
  return this._resultHandler(undefined);
3259
4009
  if (!result)
3260
4010
  return this._resultHandler(null);
@@ -3262,23 +4012,23 @@ class Model extends AbstractModel_1.AbstractModel {
3262
4012
  .copyModel(this, { select: true })
3263
4013
  .where('id', id)
3264
4014
  .bind(this.$pool.get())
3265
- .debug(this._getState('DEBUG'))
4015
+ .debug(this.$state.get('DEBUG'))
3266
4016
  .first();
3267
- this._observer(resultData, 'created');
4017
+ yield this._observer(resultData, 'created');
3268
4018
  return this._resultHandler(resultData);
3269
4019
  });
3270
4020
  }
3271
4021
  _createMultipleModel() {
3272
- var _a;
3273
4022
  return __awaiter(this, void 0, void 0, function* () {
3274
- for (const data of (_a = this._getState('DATA')) !== null && _a !== void 0 ? _a : []) {
4023
+ var _a;
4024
+ for (const data of (_a = this.$state.get('DATA')) !== null && _a !== void 0 ? _a : []) {
3275
4025
  yield this._validateSchema(data, 'insert');
3276
4026
  }
3277
4027
  const [result, id] = yield this._actionStatement({
3278
4028
  sql: this._queryBuilder().insert(),
3279
4029
  returnId: true
3280
4030
  });
3281
- if (this._getState('VOID'))
4031
+ if (this.$state.get('VOID'))
3282
4032
  return this._resultHandler(undefined);
3283
4033
  if (!result)
3284
4034
  return this._resultHandler(null);
@@ -3287,63 +4037,63 @@ class Model extends AbstractModel_1.AbstractModel {
3287
4037
  .copyModel(this, { select: true, limit: true })
3288
4038
  .bind(this.$pool.get())
3289
4039
  .whereIn('id', arrayId)
3290
- .debug(this._getState('DEBUG'))
4040
+ .debug(this.$state.get('DEBUG'))
3291
4041
  .get();
3292
4042
  const resultData = data || [];
3293
- this._observer(resultData, 'created');
4043
+ yield this._observer(resultData, 'created');
3294
4044
  return this._resultHandler(resultData);
3295
4045
  });
3296
4046
  }
3297
4047
  _updateOrInsertModel() {
3298
4048
  return __awaiter(this, void 0, void 0, function* () {
3299
- this._assertError(!this._getState('where').length, "This method 'createOrUpdate' is require to use 'where' conditions");
4049
+ this._assertError(!this.$state.get('where').length, "The 'createOrUpdate' method requires the use of 'where' conditions.");
3300
4050
  const check = (yield new Model()
3301
4051
  .copyModel(this, { select: true, where: true, limit: true })
3302
4052
  .bind(this.$pool.get())
3303
- .debug(this._getState('DEBUG'))
4053
+ .debug(this.$state.get('DEBUG'))
3304
4054
  .exists()) || false;
3305
4055
  switch (check) {
3306
4056
  case false: {
3307
- yield this._validateSchema(this._getState('DATA'), 'insert');
4057
+ yield this._validateSchema(this.$state.get('DATA'), 'insert');
3308
4058
  const [result, id] = yield this._actionStatement({
3309
4059
  sql: this._queryBuilder().insert(),
3310
4060
  returnId: true
3311
4061
  });
3312
- if (this._getState('VOID') || !result)
4062
+ if (this.$state.get('VOID') || !result)
3313
4063
  return this._resultHandler(undefined);
3314
4064
  const data = yield new Model()
3315
4065
  .copyModel(this, { select: true })
3316
4066
  .bind(this.$pool.get())
3317
4067
  .where('id', id)
3318
- .debug(this._getState('DEBUG'))
4068
+ .debug(this.$state.get('DEBUG'))
3319
4069
  .first();
3320
4070
  const resultData = data == null ? null : Object.assign(Object.assign({}, data), { $action: 'insert' });
3321
4071
  const r = this._resultHandler(resultData);
3322
- this._observer(r, 'created');
4072
+ yield this._observer(r, 'created');
3323
4073
  return r;
3324
4074
  }
3325
4075
  case true: {
3326
- yield this._validateSchema(this._getState('DATA'), 'update');
4076
+ yield this._validateSchema(this.$state.get('DATA'), 'update');
3327
4077
  const result = yield this._actionStatement({
3328
4078
  sql: this._queryBuilder().update()
3329
4079
  });
3330
- if (this._getState('VOID') || !result)
4080
+ if (this.$state.get('VOID') || !result)
3331
4081
  return this._resultHandler(undefined);
3332
4082
  const data = yield new Model()
3333
4083
  .copyModel(this, { where: true, select: true, limit: true })
3334
4084
  .bind(this.$pool.get())
3335
- .debug(this._getState('DEBUG'))
4085
+ .debug(this.$state.get('DEBUG'))
3336
4086
  .get();
3337
4087
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
3338
4088
  for (const v of data)
3339
4089
  v.$action = 'update';
3340
4090
  const r = this._resultHandler(data);
3341
- this._observer(r, 'updated');
4091
+ yield this._observer(r, 'updated');
3342
4092
  return r;
3343
4093
  }
3344
4094
  const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { $action: 'update' }) || null;
3345
4095
  const r = this._resultHandler(resultData);
3346
- this._observer(r, 'updated');
4096
+ yield this._observer(r, 'updated');
3347
4097
  return r;
3348
4098
  }
3349
4099
  }
@@ -3351,41 +4101,41 @@ class Model extends AbstractModel_1.AbstractModel {
3351
4101
  }
3352
4102
  _insertOrSelectModel() {
3353
4103
  return __awaiter(this, void 0, void 0, function* () {
3354
- this._assertError(!this._getState('where').length, "This method 'createOrSelect' is require to use 'where' conditions");
4104
+ this._assertError(!this.$state.get('where').length, "The 'createOrSelect' method requires the use of 'where' conditions.");
3355
4105
  const check = (yield new Model()
3356
4106
  .copyModel(this, { select: true, where: true, limit: true })
3357
4107
  .bind(this.$pool.get())
3358
- .debug(this._getState('DEBUG'))
4108
+ .debug(this.$state.get('DEBUG'))
3359
4109
  .exists()) || false;
3360
4110
  switch (check) {
3361
4111
  case false: {
3362
- yield this._validateSchema(this._getState('DATA'), 'insert');
4112
+ yield this._validateSchema(this.$state.get('DATA'), 'insert');
3363
4113
  const [result, id] = yield this._actionStatement({
3364
4114
  sql: this._queryBuilder().insert(),
3365
4115
  returnId: true
3366
4116
  });
3367
- if (this._getState('VOID') || !result)
4117
+ if (this.$state.get('VOID') || !result)
3368
4118
  return this._resultHandler(undefined);
3369
4119
  const data = yield new Model()
3370
4120
  .copyModel(this, { select: true })
3371
4121
  .bind(this.$pool.get())
3372
4122
  .where('id', id)
3373
- .debug(this._getState('DEBUG'))
4123
+ .debug(this.$state.get('DEBUG'))
3374
4124
  .first();
3375
4125
  const resultData = data == null
3376
4126
  ? null
3377
4127
  : Object.assign(Object.assign({}, data), { $action: 'insert' });
3378
4128
  const r = this._resultHandler(resultData);
3379
- this._observer(r, 'created');
4129
+ yield this._observer(r, 'created');
3380
4130
  return r;
3381
4131
  }
3382
4132
  case true: {
3383
- if (this._getState('VOID'))
4133
+ if (this.$state.get('VOID'))
3384
4134
  return this._resultHandler(undefined);
3385
4135
  const data = yield new Model()
3386
4136
  .copyModel(this, { select: true, where: true, limit: true })
3387
4137
  .bind(this.$pool.get())
3388
- .debug(this._getState('DEBUG'))
4138
+ .debug(this.$state.get('DEBUG'))
3389
4139
  .get();
3390
4140
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
3391
4141
  for (const v of data)
@@ -3400,25 +4150,25 @@ class Model extends AbstractModel_1.AbstractModel {
3400
4150
  }
3401
4151
  _updateModel() {
3402
4152
  return __awaiter(this, void 0, void 0, function* () {
3403
- this._assertError(!this._getState('where').length, "This method 'update' is require to use 'where' conditions");
3404
- yield this._validateSchema(this._getState('DATA'), 'update');
4153
+ this._assertError(!this.$state.get('where').length, "The 'update' method requires the use of 'where' conditions.");
4154
+ yield this._validateSchema(this.$state.get('DATA'), 'update');
3405
4155
  const sql = this._queryBuilder().update();
3406
4156
  const result = yield this._actionStatement({ sql });
3407
- if (this._getState('VOID') || !result || result == null)
4157
+ if (this.$state.get('VOID') || !result || result == null)
3408
4158
  return this._resultHandler(undefined);
3409
4159
  const data = yield new Model()
3410
4160
  .copyModel(this, { where: true, select: true, limit: true, orderBy: true })
3411
4161
  .bind(this.$pool.get())
3412
- .debug(this._getState('DEBUG'))
4162
+ .debug(this.$state.get('DEBUG'))
3413
4163
  .get();
3414
4164
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
3415
4165
  const r = this._resultHandler(data);
3416
- this._observer(r, 'updated');
4166
+ yield this._observer(r, 'updated');
3417
4167
  return r;
3418
4168
  }
3419
4169
  const resultData = (data === null || data === void 0 ? void 0 : data.shift()) || null;
3420
4170
  const r = this._resultHandler(resultData);
3421
- this._observer(r, 'updated');
4171
+ yield this._observer(r, 'updated');
3422
4172
  return r;
3423
4173
  });
3424
4174
  }
@@ -3435,6 +4185,7 @@ class Model extends AbstractModel_1.AbstractModel {
3435
4185
  'insert',
3436
4186
  'create',
3437
4187
  'update',
4188
+ 'updateMultiple',
3438
4189
  'updateMany',
3439
4190
  'updateNotExists',
3440
4191
  'delete',
@@ -3476,11 +4227,11 @@ class Model extends AbstractModel_1.AbstractModel {
3476
4227
  }
3477
4228
  }
3478
4229
  }
3479
- _checkSchemaOrNextError(e, retry = 1) {
3480
- var _a, _b, _c, _d, _e;
3481
- return __awaiter(this, void 0, void 0, function* () {
4230
+ _checkSchemaOrNextError(e_1) {
4231
+ return __awaiter(this, arguments, void 0, function* (e, retry = 1) {
4232
+ var _a, _b, _c, _d, _e;
3482
4233
  try {
3483
- if (retry > 2 || this._getState('RETRY') > 2)
4234
+ if (retry > 2 || this.$state.get('RETRY') > 2)
3484
4235
  throw e;
3485
4236
  const schemaTable = this.getSchemaModel();
3486
4237
  if (schemaTable == null)
@@ -3507,7 +4258,7 @@ class Model extends AbstractModel_1.AbstractModel {
3507
4258
  return this._stoppedRetry(e);
3508
4259
  const sql = [
3509
4260
  `${this.$constants('ALTER_TABLE')}`,
3510
- `${this._getState('TABLE_NAME')}`,
4261
+ `${this.$state.get('TABLE_NAME')}`,
3511
4262
  `${this.$constants('ADD')}`,
3512
4263
  `\`${column}\` ${type} ${attributes.join(' ')}`,
3513
4264
  `${this.$constants('AFTER')}`,
@@ -3518,9 +4269,12 @@ class Model extends AbstractModel_1.AbstractModel {
3518
4269
  }
3519
4270
  if (!errorMessage.toLocaleLowerCase().includes("doesn't exist"))
3520
4271
  return this._stoppedRetry(e);
3521
- const tableName = this._getState('TABLE_NAME');
4272
+ const tableName = this.$state.get('TABLE_NAME');
3522
4273
  const sql = new Schema_1.Schema().createTable(tableName, schemaTable);
3523
4274
  yield this._queryStatement(sql);
4275
+ const beforeCreatingTheTable = this.$state.get('BEFORE_CREATING_TABLE');
4276
+ if (beforeCreatingTheTable != null)
4277
+ yield beforeCreatingTheTable();
3524
4278
  }
3525
4279
  catch (e) {
3526
4280
  if (retry >= 2)
@@ -3530,14 +4284,14 @@ class Model extends AbstractModel_1.AbstractModel {
3530
4284
  });
3531
4285
  }
3532
4286
  _stoppedRetry(e) {
3533
- this._setState('RETRY', 2);
4287
+ this.$state.set('RETRY', 2);
3534
4288
  throw e;
3535
4289
  }
3536
4290
  _observer(result, type) {
3537
4291
  return __awaiter(this, void 0, void 0, function* () {
3538
- if (this._getState('OBSERVER') == null)
4292
+ if (this.$state.get('OBSERVER') == null)
3539
4293
  return;
3540
- const observer = this._getState('OBSERVER');
4294
+ const observer = this.$state.get('OBSERVER');
3541
4295
  const ob = new observer();
3542
4296
  yield ob[type](result);
3543
4297
  });
@@ -3545,22 +4299,22 @@ class Model extends AbstractModel_1.AbstractModel {
3545
4299
  _makeRelations() {
3546
4300
  if (this.$hasOne != null) {
3547
4301
  for (const hasOne of this.$hasOne) {
3548
- this.hasOne(Object.assign(Object.assign({}, hasOne), { name: String(hasOne.name) }));
4302
+ this.hasOne(Object.assign(Object.assign({}, hasOne), { name: hasOne.name }));
3549
4303
  }
3550
4304
  }
3551
4305
  if (this.$hasMany != null) {
3552
4306
  for (const hasMany of this.$hasMany) {
3553
- this.hasMany(Object.assign(Object.assign({}, hasMany), { name: String(hasMany.name) }));
4307
+ this.hasMany(Object.assign(Object.assign({}, hasMany), { name: hasMany.name }));
3554
4308
  }
3555
4309
  }
3556
4310
  if (this.$belongsTo != null) {
3557
4311
  for (const belongsTo of this.$belongsTo) {
3558
- this.belongsTo(Object.assign(Object.assign({}, belongsTo), { name: String(belongsTo.name) }));
4312
+ this.belongsTo(Object.assign(Object.assign({}, belongsTo), { name: belongsTo.name }));
3559
4313
  }
3560
4314
  }
3561
4315
  if (this.$belongsToMany != null) {
3562
4316
  for (const belongsToMany of this.$belongsToMany) {
3563
- this.belongsToMany(Object.assign(Object.assign({}, belongsToMany), { name: String(belongsToMany.name) }));
4317
+ this.belongsToMany(Object.assign(Object.assign({}, belongsToMany), { name: belongsToMany.name }));
3564
4318
  }
3565
4319
  }
3566
4320
  return this;
@@ -3578,6 +4332,10 @@ class Model extends AbstractModel_1.AbstractModel {
3578
4332
  this.useUUID();
3579
4333
  if (globalSettings.timestamp)
3580
4334
  this.useTimestamp();
4335
+ if (globalSettings.logger)
4336
+ this.useLogger({});
4337
+ if (this.$table != null)
4338
+ this.useTable(this.$table);
3581
4339
  if (this.$uuid != null)
3582
4340
  this.useUUID(this.$uuidColumn);
3583
4341
  if (this.$timestamp != null)