tspace-mysql 1.3.4 → 1.3.6

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.
@@ -15,8 +15,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.Model = void 0;
16
16
  const pluralize_1 = __importDefault(require("pluralize"));
17
17
  const DB_1 = require("./DB");
18
+ const Schema_1 = require("./Schema");
18
19
  const AbstractModel_1 = require("./AbstractModel");
19
20
  const ProxyHandler_1 = require("./ProxyHandler");
21
+ const StateHandler_1 = require("./StateHandler");
20
22
  class Model extends AbstractModel_1.AbstractModel {
21
23
  constructor() {
22
24
  super();
@@ -36,30 +38,84 @@ class Model extends AbstractModel_1.AbstractModel {
36
38
  /**
37
39
  *
38
40
  * define for initialize of models
41
+ * @example
42
+ * class User extends Model {
43
+ * define() {
44
+ * this.useUUID()
45
+ * this.usePrimaryKey('id')
46
+ * this.useTimestamp()
47
+ * this.useSoftDelete()
48
+ * }
49
+ * }
39
50
  * @return {void} void
40
51
  */
41
52
  define() { }
42
53
  /**
43
54
  *
44
- * boot for initialize of models
55
+ * boot for initialize of models like constructor()
56
+ * @example
57
+ * class User extends Model {
58
+ * boot() {
59
+ * this.useUUID()
60
+ * this.usePrimaryKey('id')
61
+ * this.useTimestamp()
62
+ * this.useSoftDelete()
63
+ * }
64
+ * }
45
65
  * @return {void} void
46
66
  */
47
67
  boot() { }
48
68
  /**
49
69
  *
50
- * Assign function callback in model
70
+ * Assign auto create table when not exists table
71
+ * @param {object} schema using Blueprint for schema
72
+ * @example
73
+ * import { Blueprint } from 'tspace-mysql'
74
+ * class User extends Model {
75
+ * constructor() {
76
+ * this.useCreateTableIfNotExists ({
77
+ * id : new Blueprint().int().notNull().primary().autoIncrement(),
78
+ * uuid : new Blueprint().varchar(50).null(),
79
+ * email : new Blueprint().varchar(50).null(),
80
+ * name : new Blueprint().varchar(255).null(),
81
+ * created_at : new Blueprint().timestamp().null(),
82
+ * updated_at : new Blueprint().timestamp().null()
83
+ * })
84
+ * }
85
+ * }
86
+ * @return {this} this
87
+ */
88
+ useCreateTableIfNotExists(schema) {
89
+ this.$state.set('CREATE_TABLE', schema);
90
+ return this;
91
+ }
92
+ /**
93
+ *
94
+ * Assign function callback in model like constructor()
95
+ * @example
96
+ * class User extends Model {
97
+ * constructor() {
98
+ * this.useRegistry()
99
+ * }
100
+ * }
51
101
  * @return {this} this
52
102
  */
53
103
  useRegistry() {
54
- this.$state.set('REGISTRY', Object.assign(Object.assign({}, this.$state.get('REGISTRY')), { attach: this._attach, detach: this._detach }));
104
+ this.$state.set('REGISTRY', Object.assign(Object.assign({}, this.$state.get('REGISTRY')), { '$attach': this._attach, '$detach': this._detach }));
55
105
  return this;
56
106
  }
57
107
  /**
58
108
  *
59
109
  * Assign model calling all relationships in model
110
+ * @example
111
+ * class User extends Model {
112
+ * constructor() {
113
+ * this.useLoadRelationInRegistry()
114
+ * }
115
+ * }
60
116
  * @return {this} this
61
117
  */
62
- useLoadRelationInRegistry() {
118
+ useLoadRelationsInRegistry() {
63
119
  const relations = this.$state.get('RELATION').map((r) => String(r.name));
64
120
  if (relations.length)
65
121
  this.with(...Array.from(new Set(relations)));
@@ -68,6 +124,12 @@ class Model extends AbstractModel_1.AbstractModel {
68
124
  /**
69
125
  *
70
126
  * Assign model built-in relation functions to a results
127
+ * @example
128
+ * class User extends Model {
129
+ * constructor() {
130
+ * this.useBuiltInRelationsFunction()
131
+ * }
132
+ * }
71
133
  * @return {this} this
72
134
  */
73
135
  useBuiltInRelationFunctions() {
@@ -77,6 +139,13 @@ class Model extends AbstractModel_1.AbstractModel {
77
139
  /**
78
140
  *
79
141
  * Assign primary column in model
142
+ * @param {string} primary
143
+ * @example
144
+ * class User extends Model {
145
+ * constructor() {
146
+ * this.usePrimaryKey()
147
+ * }
148
+ * }
80
149
  * @return {this} this
81
150
  */
82
151
  usePrimaryKey(primary) {
@@ -86,6 +155,12 @@ class Model extends AbstractModel_1.AbstractModel {
86
155
  /**
87
156
  * Assign generate uuid when creating in model
88
157
  * @param {string?} column [column=uuid] make new name column for custom column replace uuid with this
158
+ * @example
159
+ * class User extends Model {
160
+ * constructor() {
161
+ * this.useUUID()
162
+ * }
163
+ * }
89
164
  * @return {this} this
90
165
  */
91
166
  useUUID(column) {
@@ -106,6 +181,12 @@ class Model extends AbstractModel_1.AbstractModel {
106
181
  *
107
182
  * Assign in model use pattern [snake_case , camelCase]
108
183
  * @param {string} pattern
184
+ * @example
185
+ * class User extends Model {
186
+ * constructor() {
187
+ * this.usePattern('camelCase')
188
+ * }
189
+ * }
109
190
  * @return {this} this
110
191
  */
111
192
  usePattern(pattern) {
@@ -121,7 +202,13 @@ class Model extends AbstractModel_1.AbstractModel {
121
202
  *
122
203
  * Assign in model show data not be deleted
123
204
  * Relations has reference this method
124
- * @param {string?} column
205
+ * @param {string?} column default deleted_at
206
+ * @example
207
+ * class User extends Model {
208
+ * constructor() {
209
+ * this.useSoftDelete('delete_at')
210
+ * }
211
+ * }
125
212
  * @return {this} this
126
213
  */
127
214
  useSoftDelete(column) {
@@ -136,6 +223,15 @@ class Model extends AbstractModel_1.AbstractModel {
136
223
  * @param {object} timestampFormat
137
224
  * @property {string} timestampFormat.createdAt - change new name column replace by default [created at]
138
225
  * @property {string} timestampFormat.updatedAt - change new name column replace by default updated at
226
+ * @example
227
+ * class User extends Model {
228
+ * constructor() {
229
+ * this.useTimestamp({
230
+ * createdAt : 'createdAt',
231
+ * updatedAt : 'updatedAt'
232
+ * })
233
+ * }
234
+ * }
139
235
  * @return {this} this
140
236
  */
141
237
  useTimestamp(timestampFormat) {
@@ -152,6 +248,12 @@ class Model extends AbstractModel_1.AbstractModel {
152
248
  *
153
249
  * Assign table name in model
154
250
  * @param {string} table table name in database
251
+ * @example
252
+ * class User extends Model {
253
+ * constructor() {
254
+ * this.useTable('setTableNameIsUser') // => 'setTableNameIsUser'
255
+ * }
256
+ * }
155
257
  * @return {this} this
156
258
  */
157
259
  useTable(table) {
@@ -161,6 +263,12 @@ class Model extends AbstractModel_1.AbstractModel {
161
263
  /**
162
264
  *
163
265
  * Assign table name in model with signgular pattern
266
+ * @example
267
+ * class User extends Model {
268
+ * constructor() {
269
+ * this.useTableSingular() // => 'user'
270
+ * }
271
+ * }
164
272
  * @return {this} this
165
273
  */
166
274
  useTableSingular() {
@@ -172,6 +280,12 @@ class Model extends AbstractModel_1.AbstractModel {
172
280
  /**
173
281
  *
174
282
  * Assign table name in model with pluarl pattern
283
+ * @example
284
+ * class User extends Model {
285
+ * constructor() {
286
+ * this.useTablePlural() // => 'users'
287
+ * }
288
+ * }
175
289
  * @return {this} this
176
290
  */
177
291
  useTablePlural() {
@@ -183,7 +297,18 @@ class Model extends AbstractModel_1.AbstractModel {
183
297
  /**
184
298
  *
185
299
  * Assign schema column in model for validation data types
186
- * @param {Object<Function>} schema types (String Number and Date)
300
+ * @param {Object<NumberConstructor | StringConstructor | DateConstructor>} schema types (String Number and Date)
301
+ * @example
302
+ * class User extends Model {
303
+ * constructor() {
304
+ * this.useSchema({
305
+ * id : Number,
306
+ * email : String,
307
+ * name : String,
308
+ * date : Date
309
+ * })
310
+ * }
311
+ * }
187
312
  * @return {this} this
188
313
  */
189
314
  useSchema(schema) {
@@ -192,11 +317,17 @@ class Model extends AbstractModel_1.AbstractModel {
192
317
  }
193
318
  /**
194
319
  * Assign hook function when execute returned results to callback function
195
- * @param {Function} arrayFunction function for callback result
320
+ * @param {Array<Function>} arrayFunctions functions for callback result
321
+ * @example
322
+ * class User extends Model {
323
+ * constructor() {
324
+ * this.useHook([(results) => console.log(results)])
325
+ * }
326
+ * }
196
327
  * @return {this}
197
328
  */
198
- useHook(functions) {
199
- for (const func of functions) {
329
+ useHook(arrayFunctions) {
330
+ for (const func of arrayFunctions) {
200
331
  if (typeof func !== "function")
201
332
  throw new Error(`this '${func}' is not a function`);
202
333
  this.$state.set('HOOK', [...this.$state.get('HOOK'), func]);
@@ -211,7 +342,7 @@ class Model extends AbstractModel_1.AbstractModel {
211
342
  return __awaiter(this, void 0, void 0, function* () {
212
343
  if (this.$state.get('SCHEMA')) {
213
344
  const columns = Object.keys(this.$state.get('SCHEMA'));
214
- const removeExcept = columns.filter((column) => !this.$state.get('EXCEPT').includes(column));
345
+ const removeExcept = columns.filter((column) => !String(this.$state.get('EXCEPT')).includes(column));
215
346
  return removeExcept;
216
347
  }
217
348
  const rawColumns = yield this.queryStatement([
@@ -221,7 +352,7 @@ class Model extends AbstractModel_1.AbstractModel {
221
352
  `${this.$state.get('TABLE_NAME')}`
222
353
  ].join(' '));
223
354
  const columns = rawColumns.map((column) => column.Field);
224
- const removeExcept = columns.filter((column) => !this.$state.get('EXCEPT').includes(column));
355
+ const removeExcept = columns.filter((column) => !String(this.$state.get('EXCEPT')).includes(column));
225
356
  return removeExcept;
226
357
  });
227
358
  }
@@ -276,16 +407,65 @@ class Model extends AbstractModel_1.AbstractModel {
276
407
  newInstance.$state.set('DELETE', '');
277
408
  if ((options === null || options === void 0 ? void 0 : options.where) == null)
278
409
  newInstance.$state.set('WHERE', '');
410
+ if ((options === null || options === void 0 ? void 0 : options.limit) == null)
411
+ newInstance.$state.set('LIMIT', '');
412
+ if ((options === null || options === void 0 ? void 0 : options.offset) == null)
413
+ newInstance.$state.set('OFFSET', '');
414
+ newInstance.$state.set('SAVE', '');
279
415
  return newInstance;
280
416
  }
281
417
  /**
282
- * Assign ignore delete_at in model
283
- * @param {boolean} condition
418
+ *
419
+ * execute the query using raw sql syntax
420
+ * @override method
421
+ * @param {string} sql
284
422
  * @return {this} this
285
423
  */
286
- ignoreSoftDelete(condition = false) {
287
- this.$state.set('SOFT_DELETE', condition);
288
- return this;
424
+ queryStatement(sql) {
425
+ return __awaiter(this, void 0, void 0, function* () {
426
+ try {
427
+ if (this.$state.get('DEBUG'))
428
+ this.$utils.consoleDebug(sql);
429
+ this.$state.set('QUERIES', this.$state.get('QUERIES') + 1);
430
+ const result = yield this.$pool.query(sql);
431
+ return result;
432
+ }
433
+ catch (e) {
434
+ yield this._tryToCreateTable(e);
435
+ return yield this.queryStatement(sql);
436
+ }
437
+ });
438
+ }
439
+ /**
440
+ *
441
+ * execute the query using raw sql syntax actions for insert update and delete
442
+ * @override method
443
+ * @param {Object} actions
444
+ * @property {Function} actions.sql
445
+ * @property {Function} actions.returnId
446
+ * @return {this} this
447
+ */
448
+ actionStatement({ sql, returnId = false }) {
449
+ return __awaiter(this, void 0, void 0, function* () {
450
+ try {
451
+ if (this.$state.get('DEBUG'))
452
+ this.$utils.consoleDebug(sql);
453
+ this.$state.set('QUERIES', this.$state.get('QUERIES') + 1);
454
+ if (returnId) {
455
+ const result = yield this.$pool.query(sql);
456
+ return [result.affectedRows, result.insertId];
457
+ }
458
+ const { affectedRows: result } = yield this.$pool.query(sql);
459
+ return result;
460
+ }
461
+ catch (e) {
462
+ yield this._tryToCreateTable(e);
463
+ return yield this.actionStatement({
464
+ sql,
465
+ returnId
466
+ });
467
+ }
468
+ });
289
469
  }
290
470
  /**
291
471
  * Assign table name
@@ -305,6 +485,15 @@ class Model extends AbstractModel_1.AbstractModel {
305
485
  this.$state.set('SOFT_DELETE', condition);
306
486
  return this;
307
487
  }
488
+ /**
489
+ * Assign ignore delete_at in model
490
+ * @param {boolean} condition
491
+ * @return {this} this
492
+ */
493
+ ignoreSoftDelete(condition = false) {
494
+ this.$state.set('SOFT_DELETE', condition);
495
+ return this;
496
+ }
308
497
  /**
309
498
  * Assign build in function to result of data
310
499
  * @param {object} func
@@ -318,6 +507,24 @@ class Model extends AbstractModel_1.AbstractModel {
318
507
  *
319
508
  * Use relations in registry of model return result of relation query
320
509
  * @param {...string} nameRelations ...name registry in models using (hasOne , hasMany , belongsTo , belongsToMany)
510
+ * @example
511
+ * import { Model } from 'tspace-mysql'
512
+ * class User extends Model {
513
+ * constructor(){
514
+ * super()
515
+ * this.hasMany({ name : 'posts' , model : Post })
516
+ * }
517
+ * }
518
+ *
519
+ * class Post extends Model {
520
+ * constructor(){
521
+ * super()
522
+ * this.hasMany({ name : 'comments' , model : Comment })
523
+ * this.belongsTo({ name : 'user' , model : User })
524
+ * }
525
+ * }
526
+ * // use with for results of relationship
527
+ * await new User().with('posts').findMany()
321
528
  * @return {this} this
322
529
  */
323
530
  with(...nameRelations) {
@@ -359,6 +566,24 @@ class Model extends AbstractModel_1.AbstractModel {
359
566
  *
360
567
  * Use relations in registry of model return only exists result of relation query
361
568
  * @param {...string} nameRelations if data exists return blank
569
+ * @example
570
+ * import { Model } from 'tspace-mysql'
571
+ * class User extends Model {
572
+ * constructor(){
573
+ * super()
574
+ * this.hasMany({ name : 'posts' , model : Post })
575
+ * }
576
+ * }
577
+ *
578
+ * class Post extends Model {
579
+ * constructor(){
580
+ * super()
581
+ * this.hasMany({ name : 'comments' , model : Comment })
582
+ * this.belongsTo({ name : 'user' , model : User })
583
+ * }
584
+ * }
585
+ * // use with for results of relationship if relations is exists
586
+ * await new User().withExists('posts').findMany()
362
587
  * @return {this} this
363
588
  */
364
589
  withExists(...nameRelations) {
@@ -381,6 +606,24 @@ class Model extends AbstractModel_1.AbstractModel {
381
606
  *
382
607
  * Use relations in registry of model return only exists result of relation query
383
608
  * @param {...string} nameRelations if data exists return blank
609
+ * @example
610
+ * import { Model } from 'tspace-mysql'
611
+ * class User extends Model {
612
+ * constructor(){
613
+ * super()
614
+ * this.hasMany({ name : 'posts' , model : Post })
615
+ * }
616
+ * }
617
+ *
618
+ * class Post extends Model {
619
+ * constructor(){
620
+ * super()
621
+ * this.hasMany({ name : 'comments' , model : Comment })
622
+ * this.belongsTo({ name : 'user' , model : User })
623
+ * }
624
+ * }
625
+ * // use with for results of relationship if relations is exists
626
+ * await new User().has('posts').findMany()
384
627
  * @return {this} this
385
628
  */
386
629
  has(...nameRelations) {
@@ -391,6 +634,45 @@ class Model extends AbstractModel_1.AbstractModel {
391
634
  * Use relation '${name}' registry of model return callback this query model
392
635
  * @param {string} nameRelation name relation in registry in your model
393
636
  * @param {function} callback query callback
637
+ * @example
638
+ * import { Model } from 'tspace-mysql'
639
+ * class User extends Model {
640
+ * constructor(){
641
+ * super()
642
+ * this.hasMany({ name : 'posts' , model : Post })
643
+ * }
644
+ * }
645
+ *
646
+ * class Post extends Model {
647
+ * constructor(){
648
+ * super()
649
+ * this.hasMany({ name : 'comments' , model : Comment })
650
+ * this.belongsTo({ name : 'user' , model : User })
651
+ * }
652
+ * }
653
+ *
654
+ * class Comment extends Model {
655
+ * constructor(){
656
+ * super()
657
+ * this.hasMany({ name : 'users' , model : User })
658
+ * this.belongsTo({ name : 'post' , model : Post })
659
+ * }
660
+ * }
661
+ *
662
+ * await new User().with('posts')
663
+ * .withQuery('posts', (query : Post) => {
664
+ * return query.with('comments','user')
665
+ * .withQuery('comments', (query : Comment) => {
666
+ * return query.with('user','post')
667
+ * })
668
+ * .withQuery('user', (query : User) => {
669
+ * return query.with('posts').withQuery('posts',(query : Post)=> {
670
+ * return query.with('comments','user')
671
+ * // relation n, n, ...n
672
+ * })
673
+ * })
674
+ * })
675
+ * .findMany()
394
676
  * @return {this} this
395
677
  */
396
678
  withQuery(nameRelation, callback) {
@@ -404,8 +686,26 @@ class Model extends AbstractModel_1.AbstractModel {
404
686
  }
405
687
  /**
406
688
  *
407
- * Use relations in registry of model retrun result of relation query
689
+ * Use relations in registry of model return result of relation query
408
690
  * @param {...string} nameRelations ...name registry in models using (hasOne , hasMany , belongsTo , belongsToMany)
691
+ * @example
692
+ * import { Model } from 'tspace-mysql'
693
+ * class User extends Model {
694
+ * constructor(){
695
+ * super()
696
+ * this.hasMany({ name : 'posts' , model : Post })
697
+ * }
698
+ * }
699
+ *
700
+ * class Post extends Model {
701
+ * constructor(){
702
+ * super()
703
+ * this.hasMany({ name : 'comments' , model : Comment })
704
+ * this.belongsTo({ name : 'user' , model : User })
705
+ * }
706
+ * }
707
+ * // use with for results of relationship
708
+ * await new User().relations('posts').findMany()
409
709
  * @return {this} this
410
710
  */
411
711
  relations(...nameRelations) {
@@ -415,7 +715,25 @@ class Model extends AbstractModel_1.AbstractModel {
415
715
  *
416
716
  * Use relations in registry of model return only exists result of relation query
417
717
  * @param {...string} nameRelations if data exists return blank
418
- * @return {this}
718
+ * @example
719
+ * import { Model } from 'tspace-mysql'
720
+ * class User extends Model {
721
+ * constructor(){
722
+ * super()
723
+ * this.hasMany({ name : 'posts' , model : Post })
724
+ * }
725
+ * }
726
+ *
727
+ * class Post extends Model {
728
+ * constructor(){
729
+ * super()
730
+ * this.hasMany({ name : 'comments' , model : Comment })
731
+ * this.belongsTo({ name : 'user' , model : User })
732
+ * }
733
+ * }
734
+ * // use with for results of relationship if relations is exists
735
+ * await new User().relationsExists('posts').findMany()
736
+ * @return {this} this
419
737
  */
420
738
  relationsExists(...nameRelations) {
421
739
  return this.withExists(...nameRelations);
@@ -425,6 +743,45 @@ class Model extends AbstractModel_1.AbstractModel {
425
743
  * Use relation '${name}' registry of model return callback this query model
426
744
  * @param {string} nameRelation name relation in registry in your model
427
745
  * @param {function} callback query callback
746
+ * @example
747
+ * import { Model } from 'tspace-mysql'
748
+ * class User extends Model {
749
+ * constructor(){
750
+ * super()
751
+ * this.hasMany({ name : 'posts' , model : Post })
752
+ * }
753
+ * }
754
+ *
755
+ * class Post extends Model {
756
+ * constructor(){
757
+ * super()
758
+ * this.hasMany({ name : 'comments' , model : Comment })
759
+ * this.belongsTo({ name : 'user' , model : User })
760
+ * }
761
+ * }
762
+ *
763
+ * class Comment extends Model {
764
+ * constructor(){
765
+ * super()
766
+ * this.hasMany({ name : 'users' , model : User })
767
+ * this.belongsTo({ name : 'post' , model : Post })
768
+ * }
769
+ * }
770
+ *
771
+ * await new User().with('posts')
772
+ * .relationQuery('posts', (query : Post) => {
773
+ * return query.with('comments','user')
774
+ * .relationQuery('comments', (query : Comment) => {
775
+ * return query.with('user','post')
776
+ * })
777
+ * .relationQuery('user', (query : User) => {
778
+ * return query.with('posts').relationQuery('posts',(query : Post)=> {
779
+ * return query.with('comments','user')
780
+ * // relation n, n, ...n
781
+ * })
782
+ * })
783
+ * })
784
+ * .findMany()
428
785
  * @return {this} this
429
786
  */
430
787
  relationQuery(nameRelation, callback) {
@@ -741,7 +1098,10 @@ class Model extends AbstractModel_1.AbstractModel {
741
1098
  * @return {string}
742
1099
  */
743
1100
  toString() {
744
- return this._buildQueryModel();
1101
+ const sql = this._buildQueryModel();
1102
+ if (this.$state.get('DEBUG'))
1103
+ this.$utils.consoleDebug(sql);
1104
+ return this.resultHandler(sql);
745
1105
  }
746
1106
  /**
747
1107
  *
@@ -749,7 +1109,10 @@ class Model extends AbstractModel_1.AbstractModel {
749
1109
  * @return {string}
750
1110
  */
751
1111
  toSQL() {
752
- return this._buildQueryModel();
1112
+ const sql = this._buildQueryModel();
1113
+ if (this.$state.get('DEBUG'))
1114
+ this.$utils.consoleDebug(sql);
1115
+ return this.resultHandler(sql);
753
1116
  }
754
1117
  /**
755
1118
  *
@@ -762,7 +1125,7 @@ class Model extends AbstractModel_1.AbstractModel {
762
1125
  const result = yield this.queryStatement(sql);
763
1126
  if (this.$state.get('HIDDEN').length)
764
1127
  this._hiddenColumnModel(result);
765
- return JSON.stringify(result);
1128
+ return this.resultHandler(JSON.stringify(result));
766
1129
  });
767
1130
  }
768
1131
  /**
@@ -777,7 +1140,7 @@ class Model extends AbstractModel_1.AbstractModel {
777
1140
  const sql = this._buildQueryModel();
778
1141
  const result = yield this.queryStatement(sql);
779
1142
  const toArray = result.map((data) => data[column]);
780
- return toArray;
1143
+ return this.resultHandler(toArray);
781
1144
  });
782
1145
  }
783
1146
  /**
@@ -789,10 +1152,10 @@ class Model extends AbstractModel_1.AbstractModel {
789
1152
  avg(column = 'id') {
790
1153
  var _a;
791
1154
  return __awaiter(this, void 0, void 0, function* () {
792
- this.selectRaw(`${this.$constants('AVG')}(${column}) ${this.$constants('AS')} avg`);
1155
+ this.selectRaw(`${this.$constants('AVG')}(${column}) ${this.$constants('AS')} \`avg\``);
793
1156
  const sql = this._buildQueryModel();
794
1157
  const result = yield this.queryStatement(sql);
795
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.avg) || 0;
1158
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.avg) || 0));
796
1159
  });
797
1160
  }
798
1161
  /**
@@ -804,10 +1167,10 @@ class Model extends AbstractModel_1.AbstractModel {
804
1167
  sum(column = 'id') {
805
1168
  var _a;
806
1169
  return __awaiter(this, void 0, void 0, function* () {
807
- this.selectRaw(`${this.$constants('SUM')}(${column}) ${this.$constants('AS')} sum`);
1170
+ this.selectRaw(`${this.$constants('SUM')}(${column}) ${this.$constants('AS')} \`sum\``);
808
1171
  const sql = this._buildQueryModel();
809
1172
  const result = yield this.queryStatement(sql);
810
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0;
1173
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.sum) || 0));
811
1174
  });
812
1175
  }
813
1176
  /**
@@ -819,10 +1182,10 @@ class Model extends AbstractModel_1.AbstractModel {
819
1182
  max(column = 'id') {
820
1183
  var _a;
821
1184
  return __awaiter(this, void 0, void 0, function* () {
822
- this.selectRaw(`${this.$constants('MAX')}(${column}) ${this.$constants('AS')} max`);
1185
+ this.selectRaw(`${this.$constants('MAX')}(${column}) ${this.$constants('AS')} \`max\``);
823
1186
  const sql = this._buildQueryModel();
824
1187
  const result = yield this.queryStatement(sql);
825
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0;
1188
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.max) || 0));
826
1189
  });
827
1190
  }
828
1191
  /**
@@ -834,10 +1197,10 @@ class Model extends AbstractModel_1.AbstractModel {
834
1197
  min(column = 'id') {
835
1198
  var _a;
836
1199
  return __awaiter(this, void 0, void 0, function* () {
837
- this.selectRaw(`${this.$constants('MIN')}(${column}) ${this.$constants('AS')} min`);
1200
+ this.selectRaw(`${this.$constants('MIN')}(${column}) ${this.$constants('AS')} \`min\``);
838
1201
  const sql = this._buildQueryModel();
839
1202
  const result = yield this.queryStatement(sql);
840
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0;
1203
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.min) || 0));
841
1204
  });
842
1205
  }
843
1206
  /**
@@ -849,10 +1212,10 @@ class Model extends AbstractModel_1.AbstractModel {
849
1212
  count(column = 'id') {
850
1213
  var _a;
851
1214
  return __awaiter(this, void 0, void 0, function* () {
852
- this.selectRaw(`${this.$constants('COUNT')}(${column}) ${this.$constants('AS')} total`);
1215
+ this.selectRaw(`${this.$constants('COUNT')}(${column}) ${this.$constants('AS')} \`total\``);
853
1216
  const sql = this._buildQueryModel();
854
1217
  const result = yield this.queryStatement(sql);
855
- return ((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.total) || 0;
1218
+ return Number(this.resultHandler(((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.total) || 0));
856
1219
  });
857
1220
  }
858
1221
  /**
@@ -869,9 +1232,9 @@ class Model extends AbstractModel_1.AbstractModel {
869
1232
  `${this.$constants('SELECT')}`,
870
1233
  `${this.$constants('EXISTS')}`,
871
1234
  `(${sql})`,
872
- `${this.$constants('AS')} 'exists'`
1235
+ `${this.$constants('AS')} \`exists\``
873
1236
  ].join(' '));
874
- return !!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false;
1237
+ return Boolean(this.resultHandler(!!((_a = result === null || result === void 0 ? void 0 : result.shift()) === null || _a === void 0 ? void 0 : _a.exists) || false));
875
1238
  });
876
1239
  }
877
1240
  /**
@@ -899,7 +1262,7 @@ class Model extends AbstractModel_1.AbstractModel {
899
1262
  }
900
1263
  this.$state.set('UPDATE', `${sql} ${this.$state.get('WHERE')}`);
901
1264
  const result = yield this.actionStatement({ sql: this.$state.get('UPDATE') });
902
- return (_a = !!result) !== null && _a !== void 0 ? _a : false;
1265
+ return Boolean(this.resultHandler((_a = !!result) !== null && _a !== void 0 ? _a : false));
903
1266
  }
904
1267
  this.$state.set('DELETE', [
905
1268
  `${this.$constants('DELETE')}`,
@@ -908,25 +1271,7 @@ class Model extends AbstractModel_1.AbstractModel {
908
1271
  `${this.$state.get('WHERE')}`
909
1272
  ].join(' '));
910
1273
  const result = yield this.actionStatement({ sql: this.$state.get('DELETE') });
911
- return (_b = !!result) !== null && _b !== void 0 ? _b : false;
912
- });
913
- }
914
- /**
915
- *
916
- * force delete data from the database
917
- * @return {promise<boolean>}
918
- */
919
- forceDelete() {
920
- var _a;
921
- return __awaiter(this, void 0, void 0, function* () {
922
- const sql = [
923
- `${this.$constants('DELETE')}`,
924
- `${this.$state.get('FROM')}`,
925
- `${this.$state.get('TABLE_NAME')}`,
926
- `${this.$state.get('WHERE')}`
927
- ].join(' ');
928
- const result = yield this.actionStatement({ sql });
929
- return (_a = !!result) !== null && _a !== void 0 ? _a : false;
1274
+ return Boolean(this.resultHandler((_b = !!result) !== null && _b !== void 0 ? _b : false));
930
1275
  });
931
1276
  }
932
1277
  /**
@@ -939,14 +1284,20 @@ class Model extends AbstractModel_1.AbstractModel {
939
1284
  return __awaiter(this, void 0, void 0, function* () {
940
1285
  this._validateMethod('first');
941
1286
  if (this.$state.get('VOID'))
942
- return null;
1287
+ return this.resultHandler(null);
943
1288
  if ((_a = this.$state.get('EXCEPT')) === null || _a === void 0 ? void 0 : _a.length)
944
1289
  this.select(...yield this.exceptColumns());
945
1290
  this.limit(1);
946
1291
  if (this.$state.get('RELATIONS_EXISTS')) {
947
- return yield this._execute({ sql: this._queryRelationsExists(), type: 'FIRST' });
1292
+ return yield this._execute({
1293
+ sql: this._queryRelationsExists(),
1294
+ type: 'FIRST'
1295
+ });
948
1296
  }
949
- return yield this._execute({ sql: this._buildQueryModel(), type: 'FIRST' });
1297
+ return yield this._execute({
1298
+ sql: this._buildQueryModel(),
1299
+ type: 'FIRST'
1300
+ });
950
1301
  });
951
1302
  }
952
1303
  /**
@@ -972,9 +1323,17 @@ class Model extends AbstractModel_1.AbstractModel {
972
1323
  this.select(...yield this.exceptColumns());
973
1324
  this.limit(1);
974
1325
  if (this.$state.get('RELATIONS_EXISTS')) {
975
- return yield this._execute({ sql: this._queryRelationsExists(), type: 'FIRST_OR_ERROR', message, options });
1326
+ return yield this._execute({
1327
+ sql: this._queryRelationsExists(),
1328
+ type: 'FIRST_OR_ERROR', message, options
1329
+ });
976
1330
  }
977
- return yield this._execute({ sql: this._buildQueryModel(), type: 'FIRST_OR_ERROR', message, options });
1331
+ return yield this._execute({
1332
+ sql: this._buildQueryModel(),
1333
+ type: 'FIRST_OR_ERROR',
1334
+ message,
1335
+ options
1336
+ });
978
1337
  });
979
1338
  }
980
1339
  /**
@@ -992,43 +1351,6 @@ class Model extends AbstractModel_1.AbstractModel {
992
1351
  * @override Method
993
1352
  * @return {promise<array>}
994
1353
  */
995
- all() {
996
- return __awaiter(this, void 0, void 0, function* () {
997
- const sql = [
998
- `${this.$constants('SELECT')}`,
999
- `*`,
1000
- `${this.$constants('FROM')}`,
1001
- `${this.$state.get('TABLE_NAME')}`
1002
- ].join(' ');
1003
- const result = yield this.queryStatement(sql);
1004
- return result;
1005
- });
1006
- }
1007
- /**
1008
- *
1009
- * @override Method
1010
- * @return {promise<object | null>}
1011
- */
1012
- find(id) {
1013
- return __awaiter(this, void 0, void 0, function* () {
1014
- this._validateMethod('find');
1015
- this._handleSoftDelete();
1016
- const result = yield this.queryStatement([
1017
- `${this.$constants('SELECT')}`,
1018
- `*`,
1019
- `${this.$constants('FROM')}`,
1020
- `${this.$state.get('TABLE_NAME')}`,
1021
- `${this.$constants('WHERE')}`,
1022
- `${this.$state.get('PRIMARY_KEY')} = ${id}`
1023
- ].join(' '));
1024
- return (result === null || result === void 0 ? void 0 : result.shift()) || null;
1025
- });
1026
- }
1027
- /**
1028
- *
1029
- * @override Method
1030
- * @return {promise<array>}
1031
- */
1032
1354
  get() {
1033
1355
  var _a;
1034
1356
  return __awaiter(this, void 0, void 0, function* () {
@@ -1040,7 +1362,10 @@ class Model extends AbstractModel_1.AbstractModel {
1040
1362
  let sql = this._buildQueryModel();
1041
1363
  if (this.$state.get('RELATIONS_EXISTS'))
1042
1364
  sql = this._queryRelationsExists();
1043
- return yield this._execute({ sql, type: 'GET' });
1365
+ return yield this._execute({
1366
+ sql,
1367
+ type: 'GET'
1368
+ });
1044
1369
  });
1045
1370
  }
1046
1371
  /**
@@ -1081,7 +1406,10 @@ class Model extends AbstractModel_1.AbstractModel {
1081
1406
  let sql = this._buildQueryModel();
1082
1407
  if (this.$state.get('RELATIONS_EXISTS'))
1083
1408
  sql = this._queryRelationsExists();
1084
- return yield this._execute({ sql, type: 'PAGINATION' });
1409
+ return yield this._execute({
1410
+ sql,
1411
+ type: 'PAGINATION'
1412
+ });
1085
1413
  });
1086
1414
  }
1087
1415
  /**
@@ -1141,7 +1469,7 @@ class Model extends AbstractModel_1.AbstractModel {
1141
1469
  data: newData
1142
1470
  });
1143
1471
  });
1144
- return resultData;
1472
+ return this.resultHandler(resultData);
1145
1473
  });
1146
1474
  }
1147
1475
  /**
@@ -1322,7 +1650,7 @@ class Model extends AbstractModel_1.AbstractModel {
1322
1650
  }
1323
1651
  /**
1324
1652
  *
1325
- * get schema of table
1653
+ * get schema from table
1326
1654
  * @return {this} this this
1327
1655
  */
1328
1656
  getSchema() {
@@ -1404,14 +1732,14 @@ class Model extends AbstractModel_1.AbstractModel {
1404
1732
  break;
1405
1733
  }
1406
1734
  }
1407
- switch (this.$state.get('SAVE')) {
1408
- case 'INSERT_MULTIPLE': return yield this._createMultipleModel();
1735
+ switch (String(this.$state.get('SAVE'))) {
1409
1736
  case 'INSERT': return yield this._insertModel();
1410
1737
  case 'UPDATE': return yield this._updateModel();
1738
+ case 'INSERT_MULTIPLE': return yield this._createMultipleModel();
1411
1739
  case 'INSERT_NOT_EXISTS': return yield this._insertNotExistsModel();
1412
1740
  case 'UPDATE_OR_INSERT': return yield this._updateOrInsertModel();
1413
1741
  case 'INSERT_OR_SELECT': return yield this._insertOrSelectModel();
1414
- default: throw new Error(`unknown this [${this.$state.get('SAVE')}]`);
1742
+ default: throw new Error(`Unknown this [${this.$state.get('SAVE')}]`);
1415
1743
  }
1416
1744
  });
1417
1745
  }
@@ -1432,7 +1760,7 @@ class Model extends AbstractModel_1.AbstractModel {
1432
1760
  ].join(' ');
1433
1761
  const fields = yield this.queryStatement(sql);
1434
1762
  for (let row = 0; row < rows; row++) {
1435
- this._assertError(this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null, "unknow this table");
1763
+ this._assertError(this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null, "Unknow this table");
1436
1764
  let columnAndValue = {};
1437
1765
  for (const { Field: field, Type: type } of fields) {
1438
1766
  const passed = ['id', '_id', 'uuid', 'deleted_at', 'deletedAt'].some(p => field.toLowerCase() === p);
@@ -1471,8 +1799,8 @@ class Model extends AbstractModel_1.AbstractModel {
1471
1799
  className = this.constructor.name;
1472
1800
  const tb = className.replace(/([A-Z])/g, (str) => '_' + str.toLowerCase()).slice(1);
1473
1801
  if (singular)
1474
- return tb;
1475
- return pluralize_1.default.plural(tb);
1802
+ return this._valuePattern(tb);
1803
+ return pluralize_1.default.plural(this._valuePattern(tb));
1476
1804
  }
1477
1805
  _makeTableName() {
1478
1806
  const tb = this._classToTableName();
@@ -1536,7 +1864,17 @@ class Model extends AbstractModel_1.AbstractModel {
1536
1864
  pluralize_1.default.singular((_d = relationModel.query) === null || _d === void 0 ? void 0 : _d._tableName())
1537
1865
  ].sort().join('_'));
1538
1866
  }
1539
- return { name, as, relation, table, localKey, foreignKey, model, pivot, oldVersion };
1867
+ return {
1868
+ name,
1869
+ as,
1870
+ relation,
1871
+ table,
1872
+ localKey,
1873
+ foreignKey,
1874
+ model,
1875
+ pivot,
1876
+ oldVersion
1877
+ };
1540
1878
  }
1541
1879
  _handleSoftDelete() {
1542
1880
  if (this.$state.get('SOFT_DELETE')) {
@@ -1558,7 +1896,8 @@ class Model extends AbstractModel_1.AbstractModel {
1558
1896
  if (this.$state.get('UPDATE')) {
1559
1897
  sql = [
1560
1898
  this.$state.get('UPDATE'),
1561
- this.$state.get('WHERE')
1899
+ this.$state.get('WHERE'),
1900
+ this.$state.get('LIMIT'),
1562
1901
  ];
1563
1902
  break;
1564
1903
  }
@@ -1635,7 +1974,7 @@ class Model extends AbstractModel_1.AbstractModel {
1635
1974
  continue;
1636
1975
  this._assertError(`This column [ ${column} ] is invalid schema field type`);
1637
1976
  }
1638
- if (result[column] === null)
1977
+ if (result[column] == null)
1639
1978
  continue;
1640
1979
  if (typeOf(result[column]) === typeOf(new s()))
1641
1980
  continue;
@@ -1890,24 +2229,17 @@ class Model extends AbstractModel_1.AbstractModel {
1890
2229
  });
1891
2230
  }
1892
2231
  _pagination(data) {
1893
- var _a, _b;
2232
+ var _a;
1894
2233
  return __awaiter(this, void 0, void 0, function* () {
1895
2234
  const currentPage = +(this.$state.get('PAGE'));
1896
- this.selectRaw([
1897
- `${this.$constants('COUNT')}(${this.$state.get('PRIMARY_KEY')})`,
1898
- `${this.$constants('AS')}`,
1899
- `total`
1900
- ].join(' '));
1901
2235
  const limit = Number(this.$state.get('PER_PAGE'));
1902
2236
  this._assertError(limit < 1, "minimun less 1 of limit");
1903
- const sql = this._buildQueryModel();
1904
- const res = yield this.queryStatement(sql);
1905
- const total = (_a = res.shift().total) !== null && _a !== void 0 ? _a : 0;
2237
+ const total = yield new Model().copyModel(this, { where: true }).count('*');
1906
2238
  let lastPage = Math.ceil(total / limit) || 0;
1907
2239
  lastPage = lastPage > 1 ? lastPage : 1;
1908
2240
  const nextPage = currentPage + 1;
1909
2241
  const prevPage = currentPage - 1 === 0 ? 1 : currentPage - 1;
1910
- const totalPage = (_b = data === null || data === void 0 ? void 0 : data.length) !== null && _b !== void 0 ? _b : 0;
2242
+ const totalPage = (_a = data === null || data === void 0 ? void 0 : data.length) !== null && _a !== void 0 ? _a : 0;
1911
2243
  const meta = {
1912
2244
  total,
1913
2245
  limit,
@@ -1918,21 +2250,17 @@ class Model extends AbstractModel_1.AbstractModel {
1918
2250
  prevPage,
1919
2251
  };
1920
2252
  if (this._isPatternSnakeCase()) {
1921
- return this.$utils.snakeCase(this._result({
2253
+ return this.$utils.snakeCase(this.resultHandler({
1922
2254
  meta,
1923
2255
  data
1924
2256
  }));
1925
2257
  }
1926
- return this._result({
2258
+ return this.resultHandler({
1927
2259
  meta,
1928
2260
  data
1929
2261
  });
1930
2262
  });
1931
2263
  }
1932
- _result(data) {
1933
- this.$state.get('RESULT', data);
1934
- return data;
1935
- }
1936
2264
  _returnEmpty(type, result, message, options) {
1937
2265
  return __awaiter(this, void 0, void 0, function* () {
1938
2266
  let emptyData = null;
@@ -1978,13 +2306,13 @@ class Model extends AbstractModel_1.AbstractModel {
1978
2306
  }
1979
2307
  }
1980
2308
  if (this._isPatternSnakeCase()) {
1981
- const empty = this.$utils.snakeCase(this._result(emptyData));
2309
+ const empty = this.$utils.snakeCase(this.resultHandler(emptyData));
1982
2310
  const hook = this.$state.get('HOOK');
1983
2311
  for (let i in hook)
1984
2312
  yield hook[i](empty);
1985
2313
  return empty;
1986
2314
  }
1987
- const empty = this._result(emptyData);
2315
+ const empty = this.resultHandler(emptyData);
1988
2316
  const hook = this.$state.get('HOOK');
1989
2317
  for (let i in hook)
1990
2318
  yield hook[i](empty);
@@ -2031,10 +2359,10 @@ class Model extends AbstractModel_1.AbstractModel {
2031
2359
  const newData = data.shift();
2032
2360
  const checkProperty = newData.hasOwnProperty(pluck);
2033
2361
  this._assertError(!checkProperty, `Can't find property '${pluck}' of result`);
2034
- result = this._result(newData[pluck]);
2362
+ result = this.resultHandler(newData[pluck]);
2035
2363
  break;
2036
2364
  }
2037
- result = this._result((_c = data.shift()) !== null && _c !== void 0 ? _c : null);
2365
+ result = this.resultHandler((_c = data.shift()) !== null && _c !== void 0 ? _c : null);
2038
2366
  break;
2039
2367
  }
2040
2368
  case 'FIRST_OR_ERROR': {
@@ -2043,10 +2371,10 @@ class Model extends AbstractModel_1.AbstractModel {
2043
2371
  const newData = data.shift();
2044
2372
  const checkProperty = newData.hasOwnProperty(pluck);
2045
2373
  this._assertError(!checkProperty, `Can't find property '${pluck}' of result`);
2046
- result = (_d = this._result(newData[pluck])) !== null && _d !== void 0 ? _d : null;
2374
+ result = (_d = this.resultHandler(newData[pluck])) !== null && _d !== void 0 ? _d : null;
2047
2375
  break;
2048
2376
  }
2049
- result = this._result((_e = data.shift()) !== null && _e !== void 0 ? _e : null);
2377
+ result = this.resultHandler((_e = data.shift()) !== null && _e !== void 0 ? _e : null);
2050
2378
  break;
2051
2379
  }
2052
2380
  case 'GET': {
@@ -2058,17 +2386,17 @@ class Model extends AbstractModel_1.AbstractModel {
2058
2386
  resultArray[chunkIndex].push(item);
2059
2387
  return resultArray;
2060
2388
  }, []);
2061
- result = this._result(r);
2389
+ result = this.resultHandler(r);
2062
2390
  break;
2063
2391
  }
2064
2392
  if (this.$state.get('PLUCK')) {
2065
2393
  const pluck = this.$state.get('PLUCK');
2066
2394
  const newData = data.map((d) => d[pluck]);
2067
2395
  this._assertError(newData.every((d) => d == null), `Can't find property '${pluck}' of result`);
2068
- result = this._result(newData);
2396
+ result = this.resultHandler(newData);
2069
2397
  break;
2070
2398
  }
2071
- result = this._result(data);
2399
+ result = this.resultHandler(data);
2072
2400
  break;
2073
2401
  }
2074
2402
  case 'PAGINATION': {
@@ -2184,11 +2512,11 @@ class Model extends AbstractModel_1.AbstractModel {
2184
2512
  return `${this.$constants('SET')} ${keyValue.join(', ')}`;
2185
2513
  }
2186
2514
  _queryInsertModel(objects) {
2187
- const hasTimestamp = this.$state.get('TIMESTAMP');
2515
+ const hasTimestamp = Boolean(this.$state.get('TIMESTAMP'));
2188
2516
  if (hasTimestamp) {
2189
2517
  const format = this.$state.get('TIMESTAMP_FORMAT');
2190
- const createdAt = this._valuePattern(format.CREATED_AT);
2191
- const updatedAt = this._valuePattern(format.UPDATED_AT);
2518
+ const createdAt = this._valuePattern(String(format === null || format === void 0 ? void 0 : format.CREATED_AT));
2519
+ const updatedAt = this._valuePattern(String(format === null || format === void 0 ? void 0 : format.UPDATED_AT));
2192
2520
  objects = Object.assign(Object.assign({}, objects), { [createdAt]: this.$utils.timestamp(), [updatedAt]: this.$utils.timestamp() });
2193
2521
  }
2194
2522
  const hasUUID = objects.hasOwnProperty(this.$state.get('UUID_FORMAT'));
@@ -2261,17 +2589,17 @@ class Model extends AbstractModel_1.AbstractModel {
2261
2589
  _insertNotExistsModel() {
2262
2590
  return __awaiter(this, void 0, void 0, function* () {
2263
2591
  this._assertError(!this.$state.get('WHERE'), "Can't insert [insertNotExists] without where condition");
2264
- const clone = new Model().bind(this.$pool.get()).copyModel(this, { where: true });
2592
+ const clone = new Model().copyModel(this, { where: true }).bind(this.$pool.get());
2265
2593
  const check = (yield clone.exists()) || false;
2266
2594
  if (check)
2267
- return null;
2595
+ return this.resultHandler(null);
2268
2596
  const [result, id] = yield this.actionStatement({
2269
2597
  sql: this.$state.get('INSERT'),
2270
2598
  returnId: true
2271
2599
  });
2272
2600
  if (!result)
2273
- return null;
2274
- return yield new Model().bind(this.$pool.get()).copyModel(this).where('id', id).first();
2601
+ return this.resultHandler(null);
2602
+ return yield new Model().copyModel(this).bind(this.$pool.get()).where('id', id).first();
2275
2603
  });
2276
2604
  }
2277
2605
  _insertModel() {
@@ -2281,13 +2609,14 @@ class Model extends AbstractModel_1.AbstractModel {
2281
2609
  returnId: true
2282
2610
  });
2283
2611
  if (this.$state.get('VOID'))
2284
- return null;
2612
+ return this.resultHandler(null);
2285
2613
  if (!result)
2286
- return null;
2287
- return yield new Model().copyModel(this)
2614
+ return this.resultHandler(null);
2615
+ const resultData = yield new Model().copyModel(this)
2288
2616
  .where('id', id)
2289
2617
  .bind(this.$pool.get())
2290
2618
  .first();
2619
+ return this.resultHandler(resultData);
2291
2620
  });
2292
2621
  }
2293
2622
  _createMultipleModel() {
@@ -2297,20 +2626,19 @@ class Model extends AbstractModel_1.AbstractModel {
2297
2626
  returnId: true
2298
2627
  });
2299
2628
  if (this.$state.get('VOID'))
2300
- return null;
2629
+ return this.resultHandler(null);
2301
2630
  if (!result)
2302
- return null;
2631
+ return this.resultHandler(null);
2303
2632
  const arrayId = [...Array(result)].map((_, i) => i + id);
2304
2633
  const data = new Model().copyModel(this).bind(this.$pool.get()).whereIn('id', arrayId).get();
2305
2634
  const resultData = data || [];
2306
- this.$state.set('RESULT', resultData);
2307
- return resultData;
2635
+ return this.resultHandler(resultData);
2308
2636
  });
2309
2637
  }
2310
2638
  _updateOrInsertModel() {
2311
2639
  return __awaiter(this, void 0, void 0, function* () {
2312
2640
  this._assertError(!this.$state.get('WHERE'), "Can not update or insert [updateOrInsert] without where condition");
2313
- const clone = new Model().bind(this.$pool.get()).copyModel(this, { where: true });
2641
+ const clone = new Model().copyModel(this, { where: true }).bind(this.$pool.get());
2314
2642
  const check = (yield clone.exists()) || false;
2315
2643
  switch (check) {
2316
2644
  case false: {
@@ -2318,95 +2646,79 @@ class Model extends AbstractModel_1.AbstractModel {
2318
2646
  sql: this.$state.get('INSERT'),
2319
2647
  returnId: true
2320
2648
  });
2321
- if (this.$state.get('VOID'))
2322
- return null;
2323
- if (!result)
2324
- return null;
2325
- const data = yield new Model().bind(this.$pool.get()).copyModel(this).where('id', id).first();
2649
+ if (this.$state.get('VOID') || !result)
2650
+ return this.resultHandler(null);
2651
+ const data = yield new Model().copyModel(this).bind(this.$pool.get()).where('id', id).first();
2326
2652
  const resultData = data == null
2327
2653
  ? null
2328
- : Object.assign(Object.assign({}, data), { action_status: 'insert' });
2329
- this.$state.set('RESULT', resultData);
2330
- return resultData;
2654
+ : Object.assign(Object.assign({}, data), { $action: 'insert' });
2655
+ return this.resultHandler(resultData);
2331
2656
  }
2332
2657
  case true: {
2333
2658
  const result = yield this.actionStatement({
2334
2659
  sql: new Model().copyModel(this, { update: true, where: true }).toString()
2335
2660
  });
2336
- if (this.$state.get('VOID'))
2337
- return null;
2338
- if (!result)
2339
- return null;
2340
- const data = yield new Model().bind(this.$pool.get()).copyModel(this, { where: true }).get();
2661
+ if (this.$state.get('VOID') || !result)
2662
+ return this.resultHandler(null);
2663
+ const data = yield new Model().copyModel(this, { where: true }).bind(this.$pool.get()).get();
2341
2664
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2342
2665
  for (const v of data)
2343
- v.action_status = 'update';
2344
- this.$state.set('RESULT', data);
2345
- return data || [];
2666
+ v.$action = 'update';
2667
+ return this.resultHandler(data || []);
2346
2668
  }
2347
- const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'update' }) || null;
2348
- this.$state.set('RESULT', resultData);
2349
- return resultData;
2669
+ const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { $action: 'update' }) || null;
2670
+ return this.resultHandler(resultData);
2350
2671
  }
2351
2672
  }
2352
2673
  });
2353
2674
  }
2354
2675
  _insertOrSelectModel() {
2355
2676
  return __awaiter(this, void 0, void 0, function* () {
2356
- this._assertError(!this.$state.get('WHERE'), "Can not update or insert [updateOrInsert] without where condition");
2357
- const clone = new Model().bind(this.$pool.get()).copyModel(this, { where: true });
2677
+ this._assertError(!this.$state.get('WHERE'), "Can not create or select [createOrSelect] without where condition");
2678
+ const clone = new Model().copyModel(this, { where: true }).bind(this.$pool.get());
2358
2679
  const check = (yield clone.exists()) || false;
2359
2680
  switch (check) {
2360
2681
  case false: {
2361
2682
  const [result, id] = yield this.actionStatement({
2362
- sql: this.$state.get('INSERT'),
2683
+ sql: String(this.$state.get('INSERT')),
2363
2684
  returnId: true
2364
2685
  });
2365
- if (this.$state.get('VOID'))
2366
- return null;
2367
- if (!result)
2368
- return null;
2369
- const data = yield new Model().bind(this.$pool.get()).copyModel(this).where('id', id).first();
2686
+ if (this.$state.get('VOID') || !result)
2687
+ return this.resultHandler(null);
2688
+ const data = yield new Model().copyModel(this).bind(this.$pool.get()).where('id', id).first();
2370
2689
  const resultData = data == null
2371
2690
  ? null
2372
- : Object.assign(Object.assign({}, data), { action_status: 'insert' });
2373
- this.$state.set('RESULT', resultData);
2374
- return resultData;
2691
+ : Object.assign(Object.assign({}, data), { $action: 'insert' });
2692
+ return this.resultHandler(resultData);
2375
2693
  }
2376
2694
  case true: {
2377
2695
  if (this.$state.get('VOID'))
2378
- return null;
2379
- const data = yield new Model().bind(this.$pool.get()).copyModel(this, { where: true }).get();
2696
+ return this.resultHandler(null);
2697
+ const data = yield new Model().copyModel(this, { where: true }).bind(this.$pool.get()).get();
2380
2698
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2381
2699
  for (const v of data)
2382
- v.action_status = 'select';
2383
- this.$state.set('RESULT', data);
2384
- return data || [];
2700
+ v.$action = 'select';
2701
+ return this.resultHandler(data || []);
2385
2702
  }
2386
- const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { action_status: 'select' }) || null;
2387
- this.$state.set('RESULT', resultData);
2388
- return resultData;
2703
+ const resultData = Object.assign(Object.assign({}, data === null || data === void 0 ? void 0 : data.shift()), { $action: 'select' }) || null;
2704
+ return this.resultHandler(resultData);
2389
2705
  }
2390
2706
  }
2391
2707
  });
2392
2708
  }
2393
2709
  _updateModel() {
2394
2710
  return __awaiter(this, void 0, void 0, function* () {
2395
- this._assertError(!this.$state.get('WHERE'), "can not update [ update ] without where condition");
2711
+ this._assertError(!String(this.$state.get('WHERE')), "can not update [ update ] without where condition");
2396
2712
  const sql = this._buildQueryModel();
2397
2713
  const result = yield this.actionStatement({ sql });
2398
- if (this.$state.get('VOID'))
2399
- return null;
2400
- if (result == null || !result)
2401
- return null;
2402
- const data = yield new Model().bind(this.$pool.get()).copyModel(this, { where: true }).get();
2714
+ if (this.$state.get('VOID') || !result || result == null)
2715
+ return this.resultHandler(null);
2716
+ const data = yield new Model().copyModel(this, { where: true }).bind(this.$pool.get()).get();
2403
2717
  if ((data === null || data === void 0 ? void 0 : data.length) > 1) {
2404
- this.$state.set('RESULT', data);
2405
- return data || [];
2718
+ return this.resultHandler(data || []);
2406
2719
  }
2407
2720
  const resultData = (data === null || data === void 0 ? void 0 : data.shift()) || null;
2408
- this.$state.set('RESULT', resultData);
2409
- return resultData;
2721
+ return this.resultHandler(resultData);
2410
2722
  });
2411
2723
  }
2412
2724
  _assertError(condition = true, message = 'error') {
@@ -2474,40 +2786,42 @@ class Model extends AbstractModel_1.AbstractModel {
2474
2786
  const methodCallings = this.$logger.get();
2475
2787
  const methodsNotAllowed = methodChangeStatements;
2476
2788
  const findMethodNotAllowed = methodCallings.find((methodCalling) => methodsNotAllowed.includes(methodCalling));
2477
- this._assertError(methodCallings.some((methodCalling) => methodsNotAllowed.includes(methodCalling)), `this method ${method} can't using method : [ ${findMethodNotAllowed} ]`);
2789
+ this._assertError(methodCallings.some((methodCalling) => methodsNotAllowed.includes(methodCalling)), `This method "${method}" can't using method : [ ${findMethodNotAllowed} ]`);
2478
2790
  break;
2479
2791
  }
2480
2792
  case 'save': {
2481
2793
  const methodCallings = this.$logger.get();
2482
2794
  const methodsSomeAllowed = methodChangeStatements;
2483
- this._assertError(!methodCallings.some((methodCalling) => methodsSomeAllowed.includes(methodCalling)), `this ${method} method need some : [ ${methodsSomeAllowed.join(', ')} ] methods`);
2795
+ this._assertError(!methodCallings.some((methodCalling) => methodsSomeAllowed.includes(methodCalling)), `This ${method} method need some : [ ${methodsSomeAllowed.join(', ')} ] methods`);
2484
2796
  break;
2485
2797
  }
2486
2798
  }
2487
2799
  }
2800
+ _tryToCreateTable(e) {
2801
+ var _a;
2802
+ return __awaiter(this, void 0, void 0, function* () {
2803
+ const createTable = this.$state.get('CREATE_TABLE');
2804
+ if (createTable == null)
2805
+ throw e;
2806
+ const errorMessage = (_a = e === null || e === void 0 ? void 0 : e.message) !== null && _a !== void 0 ? _a : '';
2807
+ const errorWhenTableIsNotExists = "doesn't exist";
2808
+ if (!errorMessage.toLocaleLowerCase().includes(errorWhenTableIsNotExists))
2809
+ throw e;
2810
+ if (this.$state.get('QUERIES') > 3)
2811
+ throw e;
2812
+ try {
2813
+ const tableName = this.$state.get('TABLE_NAME');
2814
+ yield new Schema_1.Schema()
2815
+ .debug(this.$state.get('DEBUG'))
2816
+ .createTable(tableName, createTable);
2817
+ }
2818
+ catch (e) {
2819
+ throw e;
2820
+ }
2821
+ });
2822
+ }
2488
2823
  _initialModel() {
2489
- this.$state = (() => {
2490
- let db = new Map(Object.entries(Object.assign({}, this.$constants('MODEL'))));
2491
- let original = new Map(Object.entries(Object.assign({}, this.$constants('MODEL'))));
2492
- return {
2493
- original: () => original,
2494
- get: (key) => {
2495
- if (key == null)
2496
- return db;
2497
- this._assertError(!db.has(key), `can't get this [ ${key} `);
2498
- return db.get(key);
2499
- },
2500
- set: (key, value) => {
2501
- this._assertError(!db.has(key), `can't set this [ ${key} ]`);
2502
- db.set(key, value);
2503
- return;
2504
- },
2505
- clone: (data) => {
2506
- db = new Map(Object.entries(Object.assign({}, data)));
2507
- return;
2508
- }
2509
- };
2510
- })();
2824
+ this.$state = new StateHandler_1.StateHandler(this.$constants('MODEL'));
2511
2825
  this._makeTableName();
2512
2826
  return this;
2513
2827
  }