tspace-mysql 1.6.3 → 1.6.5-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +0 -9
  2. package/build/lib/connection/index.d.ts +1 -0
  3. package/build/lib/connection/index.js +34 -25
  4. package/build/lib/connection/index.js.map +1 -1
  5. package/build/lib/connection/options.js +17 -15
  6. package/build/lib/connection/options.js.map +1 -1
  7. package/build/lib/constants/index.d.ts +96 -1
  8. package/build/lib/constants/index.js +3 -0
  9. package/build/lib/constants/index.js.map +1 -1
  10. package/build/lib/core/Abstracts/AbstractBuilder.d.ts +5 -7
  11. package/build/lib/core/Abstracts/AbstractBuilder.js +0 -5
  12. package/build/lib/core/Abstracts/AbstractBuilder.js.map +1 -1
  13. package/build/lib/core/Abstracts/AbstractModel.d.ts +16 -16
  14. package/build/lib/core/Blueprint.d.ts +1 -1
  15. package/build/lib/core/Blueprint.js +1 -1
  16. package/build/lib/core/Builder.d.ts +51 -3
  17. package/build/lib/core/Builder.js +162 -32
  18. package/build/lib/core/Builder.js.map +1 -1
  19. package/build/lib/core/DB.d.ts +16 -3
  20. package/build/lib/core/DB.js +17 -0
  21. package/build/lib/core/DB.js.map +1 -1
  22. package/build/lib/core/Handlers/Relation.d.ts +3 -3
  23. package/build/lib/core/Handlers/Relation.js +75 -54
  24. package/build/lib/core/Handlers/Relation.js.map +1 -1
  25. package/build/lib/core/Handlers/State.d.ts +130 -2
  26. package/build/lib/core/Handlers/State.js +3 -3
  27. package/build/lib/core/Handlers/State.js.map +1 -1
  28. package/build/lib/core/Model.d.ts +73 -17
  29. package/build/lib/core/Model.js +283 -216
  30. package/build/lib/core/Model.js.map +1 -1
  31. package/build/lib/core/Repository.d.ts +2 -2
  32. package/build/lib/core/Schema.js +4 -4
  33. package/build/lib/core/Schema.js.map +1 -1
  34. package/build/lib/core/index.js.map +1 -1
  35. package/build/lib/types.d.ts +3 -3
  36. package/build/lib/utils/index.d.ts +4 -2
  37. package/build/lib/utils/index.js +29 -17
  38. package/build/lib/utils/index.js.map +1 -1
  39. package/build/tests/03-Model.test.js +83 -14
  40. package/build/tests/03-Model.test.js.map +1 -1
  41. package/build/tests/schema-spec.d.ts +19 -2
  42. package/build/tests/schema-spec.js +12 -11
  43. package/build/tests/schema-spec.js.map +1 -1
  44. package/package.json +1 -1
@@ -117,6 +117,45 @@ class Model extends AbstractModel_1.AbstractModel {
117
117
  static get instance() {
118
118
  return new this();
119
119
  }
120
+ globalScope(callback) {
121
+ const model = new Model().table(this.getTableName());
122
+ const repository = callback(model);
123
+ if (repository instanceof Promise)
124
+ throw new Error('"whereQuery" is not supported a Promise');
125
+ if (!(repository instanceof Model))
126
+ throw new Error(`Unknown callback query: '${repository}'`);
127
+ this.$state.set('GLOBAL_SCOPE_QUERY', () => {
128
+ const where = (repository === null || repository === void 0 ? void 0 : repository.$state.get('WHERE')) || [];
129
+ const select = (repository === null || repository === void 0 ? void 0 : repository.$state.get('SELECT')) || [];
130
+ const orderBy = (repository === null || repository === void 0 ? void 0 : repository.$state.get('ORDER_BY')) || [];
131
+ const limit = (repository === null || repository === void 0 ? void 0 : repository.$state.get('LIMIT')) || null;
132
+ if (where.length) {
133
+ this.$state.set('WHERE', [
134
+ ...this.$state.get('WHERE'),
135
+ [
136
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
137
+ ...where
138
+ ].join(' ')
139
+ ]);
140
+ }
141
+ if (select.length) {
142
+ this.$state.set('SELECT', [
143
+ ...this.$state.get('SELECT'),
144
+ ...select
145
+ ]);
146
+ }
147
+ if (orderBy.length) {
148
+ this.$state.set('ORDER_BY', [
149
+ ...this.$state.get('ORDER_BY'),
150
+ ...orderBy
151
+ ]);
152
+ }
153
+ if (limit != null) {
154
+ this.$state.set('LIMIT', limit);
155
+ }
156
+ });
157
+ return this;
158
+ }
120
159
  /**
121
160
  * The 'define' method is a special method that you can define within a model.
122
161
  * @example
@@ -641,14 +680,7 @@ class Model extends AbstractModel_1.AbstractModel {
641
680
  removeExcepts.push(hasDot ? removeExcept.map(r => `${tableName}.${r}`) : removeExcept);
642
681
  continue;
643
682
  }
644
- const sql = [
645
- `${this.$constants('SHOW')}`,
646
- `${this.$constants('COLUMNS')}`,
647
- `${this.$constants('FROM')}`,
648
- `${tableName}`
649
- ].join(' ');
650
- const rawColumns = yield this._queryStatement(sql);
651
- const columns = rawColumns.map((column) => column.Field);
683
+ const columns = yield this.getColumns();
652
684
  const removeExcept = columns.filter((column) => {
653
685
  return excepts.every((except) => {
654
686
  if (/\./.test(except)) {
@@ -729,6 +761,16 @@ class Model extends AbstractModel_1.AbstractModel {
729
761
  this.$state.set('SELECT', select);
730
762
  return this;
731
763
  }
764
+ /**
765
+ *
766
+ * @override
767
+ * @param {...string} columns
768
+ * @returns {this} this
769
+ */
770
+ hidden(...columns) {
771
+ this.$state.set('HIDDEN', columns);
772
+ return this;
773
+ }
732
774
  /**
733
775
  *
734
776
  * @override
@@ -781,15 +823,16 @@ class Model extends AbstractModel_1.AbstractModel {
781
823
  * @returns {this}
782
824
  */
783
825
  orderBy(column, order = 'ASC') {
784
- let c = String(column);
785
- if (c.includes(this.$constants('RAW')) || /\./.test(c)) {
786
- c = c === null || c === void 0 ? void 0 : c.replace(this.$constants('RAW'), '');
826
+ const orderBy = [column].map(c => {
787
827
  if (/\./.test(c))
788
- c = this.bindColumn(c);
789
- }
828
+ return this.bindColumn(c.replace(/'/g, ''));
829
+ if (c.includes(this.$constants('RAW')))
830
+ return c === null || c === void 0 ? void 0 : c.replace(this.$constants('RAW'), '');
831
+ return this.bindColumn(c);
832
+ }).join(', ');
790
833
  this.$state.set('ORDER_BY', [
791
834
  ...this.$state.get('ORDER_BY'),
792
- `\`${c}\` ${order.toUpperCase()}`
835
+ `${orderBy} ${order.toUpperCase()}`
793
836
  ]);
794
837
  return this;
795
838
  }
@@ -804,10 +847,10 @@ class Model extends AbstractModel_1.AbstractModel {
804
847
  if (columns === null || columns === void 0 ? void 0 : columns.length) {
805
848
  orderBy = columns.map(c => {
806
849
  if (/\./.test(c))
807
- return this.bindColumn(c);
850
+ return this.bindColumn(c.replace(/'/g, ''));
808
851
  if (c.includes(this.$constants('RAW')))
809
852
  return c === null || c === void 0 ? void 0 : c.replace(this.$constants('RAW'), '');
810
- return `\`${c}\``;
853
+ return this.bindColumn(c);
811
854
  }).join(', ');
812
855
  }
813
856
  this.$state.set('ORDER_BY', [
@@ -827,10 +870,10 @@ class Model extends AbstractModel_1.AbstractModel {
827
870
  if (columns === null || columns === void 0 ? void 0 : columns.length) {
828
871
  orderBy = columns.map(c => {
829
872
  if (/\./.test(c))
830
- return this.bindColumn(c);
873
+ return this.bindColumn(c.replace(/'/g, ''));
831
874
  if (c.includes(this.$constants('RAW')))
832
875
  return c === null || c === void 0 ? void 0 : c.replace(this.$constants('RAW'), '');
833
- return `\`${c}\``;
876
+ return this.bindColumn(c);
834
877
  }).join(', ');
835
878
  }
836
879
  this.$state.set('ORDER_BY', [
@@ -850,10 +893,10 @@ class Model extends AbstractModel_1.AbstractModel {
850
893
  if (columns === null || columns === void 0 ? void 0 : columns.length) {
851
894
  groupBy = columns.map(c => {
852
895
  if (/\./.test(c))
853
- return this.bindColumn(c);
896
+ return this.bindColumn(c.replace(/'/g, ''));
854
897
  if (c.includes(this.$constants('RAW')))
855
898
  return c === null || c === void 0 ? void 0 : c.replace(this.$constants('RAW'), '');
856
- return `\`${c}\``;
899
+ return this.bindColumn(c);
857
900
  }).join(', ');
858
901
  }
859
902
  this.$state.set('GROUP_BY', [
@@ -1071,38 +1114,46 @@ class Model extends AbstractModel_1.AbstractModel {
1071
1114
  * @param {string} sql
1072
1115
  * @returns {this} this
1073
1116
  */
1074
- _queryStatement(sql) {
1075
- return __awaiter(this, void 0, void 0, function* () {
1117
+ _queryStatement(sql_1) {
1118
+ return __awaiter(this, arguments, void 0, function* (sql, { retry = false } = {}) {
1076
1119
  var _a;
1077
1120
  try {
1078
- if (this.$state.get('DEBUG'))
1079
- this.$utils.consoleDebug(sql);
1080
- if (this.$state.get('LOGGER')) {
1121
+ const logger = (results) => __awaiter(this, void 0, void 0, function* () {
1081
1122
  const selectRegex = /^SELECT\b/i;
1082
1123
  const loggerOptions = this.$state.get('LOGGER_OPTIONS');
1083
- if (selectRegex.test(sql) && loggerOptions.selected) {
1084
- yield this._checkTableLoggerIsExists().catch(err => null);
1085
- const result = yield this.$pool.query(sql);
1086
- yield new DB_1.DB(this.$state.get('TABLE_LOGGER'))
1087
- .create({
1088
- uuid: DB_1.DB.generateUUID(),
1089
- model: this.$state.get('MODEL_NAME'),
1090
- query: sql,
1091
- action: 'SELECT',
1092
- data: result.length
1093
- ? JSON.stringify(result.length === 1 ? result[0] : result)
1094
- : null,
1095
- changed: null,
1096
- createdAt: this.$utils.timestamp(),
1097
- updatedAt: this.$utils.timestamp()
1098
- })
1099
- .void()
1100
- .save()
1101
- .catch(_ => null);
1102
- return result;
1103
- }
1124
+ if (!(selectRegex.test(sql) && loggerOptions.selected))
1125
+ return;
1126
+ yield this._checkTableLoggerIsExists().catch(_ => null);
1127
+ yield new DB_1.DB(this.$state.get('TABLE_LOGGER'))
1128
+ .create({
1129
+ uuid: DB_1.DB.generateUUID(),
1130
+ model: this.$state.get('MODEL_NAME'),
1131
+ query: sql,
1132
+ action: 'SELECT',
1133
+ data: results.length
1134
+ ? JSON.stringify(results.length === 1 ? results[0] : results)
1135
+ : null,
1136
+ changed: null,
1137
+ createdAt: this.$utils.timestamp(),
1138
+ updatedAt: this.$utils.timestamp()
1139
+ })
1140
+ .void()
1141
+ .save()
1142
+ .catch(_ => null);
1143
+ });
1144
+ if (this.$state.get('DEBUG')) {
1145
+ this.$utils.consoleDebug(sql, retry);
1146
+ const startTime = +new Date();
1147
+ const result = yield this.$pool.query(sql);
1148
+ const endTime = +new Date();
1149
+ this.$utils.consoleExec(startTime, endTime);
1150
+ if (this.$state.get('LOGGER'))
1151
+ yield logger(result);
1152
+ return result;
1104
1153
  }
1105
1154
  const result = yield this.$pool.query(sql);
1155
+ if (this.$state.get('LOGGER'))
1156
+ yield logger(result);
1106
1157
  return result;
1107
1158
  }
1108
1159
  catch (error) {
@@ -1111,7 +1162,7 @@ class Model extends AbstractModel_1.AbstractModel {
1111
1162
  const retry = Number(this.$state.get('RETRY'));
1112
1163
  yield this._checkSchemaOrNextError(error, retry);
1113
1164
  this.$state.set('RETRY', retry + 1);
1114
- return yield this._queryStatement(sql);
1165
+ return yield this._queryStatement(sql, { retry: true });
1115
1166
  }
1116
1167
  });
1117
1168
  }
@@ -1258,7 +1309,8 @@ class Model extends AbstractModel_1.AbstractModel {
1258
1309
  });
1259
1310
  }
1260
1311
  /**
1261
- * Assign table name
1312
+ * The 'table' method is used to set the table name.
1313
+ *
1262
1314
  * @param {string} table table name
1263
1315
  * @returns {this} this
1264
1316
  */
@@ -1267,8 +1319,19 @@ class Model extends AbstractModel_1.AbstractModel {
1267
1319
  return this;
1268
1320
  }
1269
1321
  /**
1270
- * Assign ignore delete_at in model
1271
- * @param {boolean} condition
1322
+ * The 'from' method is used to set the table name.
1323
+ *
1324
+ * @param {string} table table name
1325
+ * @returns {this} this
1326
+ */
1327
+ from(table) {
1328
+ this.$state.set('TABLE_NAME', `\`${table}\``);
1329
+ return this;
1330
+ }
1331
+ /**
1332
+ * The 'disableSoftDelete' method is used to disable the soft delete.
1333
+ *
1334
+ * @param {boolean} condition
1272
1335
  * @returns {this} this
1273
1336
  */
1274
1337
  disableSoftDelete(condition = false) {
@@ -1276,7 +1339,16 @@ class Model extends AbstractModel_1.AbstractModel {
1276
1339
  return this;
1277
1340
  }
1278
1341
  /**
1279
- * The 'disableVoid' method is used to ignore void.
1342
+ * The 'ignoreSoftDelete' method is used to disable the soft delete.
1343
+ * @param {boolean} condition
1344
+ * @returns {this} this
1345
+ */
1346
+ ignoreSoftDelete(condition = false) {
1347
+ this.$state.set('SOFT_DELETE', condition);
1348
+ return this;
1349
+ }
1350
+ /**
1351
+ * The 'disableVoid' method is used to disable void.
1280
1352
  *
1281
1353
  * @returns {this} this
1282
1354
  */
@@ -1285,12 +1357,30 @@ class Model extends AbstractModel_1.AbstractModel {
1285
1357
  return this;
1286
1358
  }
1287
1359
  /**
1288
- * Assign ignore delete_at in model
1289
- * @param {boolean} condition
1360
+ * The 'ignoreVoid' method is used to ignore void.
1361
+ *
1290
1362
  * @returns {this} this
1291
1363
  */
1292
- ignoreSoftDelete(condition = false) {
1293
- this.$state.set('SOFT_DELETE', condition);
1364
+ ignoreVoid() {
1365
+ this.$state.set('VOID', false);
1366
+ return this;
1367
+ }
1368
+ /**
1369
+ * The 'disabledGlobalScope' method is used to disable globalScope.
1370
+ *
1371
+ * @returns {this} this
1372
+ */
1373
+ disabledGlobalScope(condition = false) {
1374
+ this.$state.set('GLOBAL_SCOPE', condition);
1375
+ return this;
1376
+ }
1377
+ /**
1378
+ * The 'ignoreGlobalScope' method is used to disable globalScope.
1379
+ *
1380
+ * @returns {this} this
1381
+ */
1382
+ ignoreGlobalScope(condition = false) {
1383
+ this.$state.set('GLOBAL_SCOPE', condition);
1294
1384
  return this;
1295
1385
  }
1296
1386
  /**
@@ -1331,10 +1421,9 @@ class Model extends AbstractModel_1.AbstractModel {
1331
1421
  *
1332
1422
  */
1333
1423
  with(...nameRelations) {
1334
- var _a;
1335
1424
  if (!nameRelations.length)
1336
1425
  return this;
1337
- this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'default'));
1426
+ this.$state.set('RELATIONS', this.$relation.apply(nameRelations, 'default'));
1338
1427
  return this;
1339
1428
  }
1340
1429
  /**
@@ -1377,10 +1466,9 @@ class Model extends AbstractModel_1.AbstractModel {
1377
1466
  * @returns {this} this
1378
1467
  */
1379
1468
  withAll(...nameRelations) {
1380
- var _a;
1381
1469
  if (!nameRelations.length)
1382
1470
  return this;
1383
- this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'all'));
1471
+ this.$state.set('RELATIONS', this.$relation.apply(nameRelations, 'all'));
1384
1472
  return this;
1385
1473
  }
1386
1474
  /**
@@ -1402,10 +1490,9 @@ class Model extends AbstractModel_1.AbstractModel {
1402
1490
  * @returns {this} this
1403
1491
  */
1404
1492
  withCount(...nameRelations) {
1405
- var _a;
1406
1493
  if (!nameRelations.length)
1407
1494
  return this;
1408
- this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'count'));
1495
+ this.$state.set('RELATIONS', this.$relation.apply(nameRelations, 'count'));
1409
1496
  return this;
1410
1497
  }
1411
1498
  /**
@@ -1415,10 +1502,9 @@ class Model extends AbstractModel_1.AbstractModel {
1415
1502
  * @returns {this} this
1416
1503
  */
1417
1504
  relationsCount(...nameRelations) {
1418
- var _a;
1419
1505
  if (!nameRelations.length)
1420
1506
  return this;
1421
- this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'count'));
1507
+ this.$state.set('RELATIONS', this.$relation.apply(nameRelations, 'count'));
1422
1508
  return this;
1423
1509
  }
1424
1510
  /**
@@ -1431,10 +1517,9 @@ class Model extends AbstractModel_1.AbstractModel {
1431
1517
  * @returns {this} this
1432
1518
  */
1433
1519
  withTrashed(...nameRelations) {
1434
- var _a;
1435
1520
  if (!nameRelations.length)
1436
1521
  return this;
1437
- this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'trashed'));
1522
+ this.$state.set('RELATIONS', this.$relation.apply(nameRelations, 'trashed'));
1438
1523
  return this;
1439
1524
  }
1440
1525
  /**
@@ -1477,11 +1562,10 @@ class Model extends AbstractModel_1.AbstractModel {
1477
1562
  * await new User().withExists('posts').findMany()
1478
1563
  */
1479
1564
  withExists(...nameRelations) {
1480
- var _a;
1481
1565
  if (!nameRelations.length)
1482
1566
  return this;
1483
1567
  this.$state.set('RELATIONS_EXISTS', true);
1484
- this.$state.set('RELATIONS', (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.apply(nameRelations, 'exists'));
1568
+ this.$state.set('RELATIONS', this.$relation.apply(nameRelations, 'exists'));
1485
1569
  return this;
1486
1570
  }
1487
1571
  /**
@@ -1594,13 +1678,12 @@ class Model extends AbstractModel_1.AbstractModel {
1594
1678
  * @returns {this} this
1595
1679
  */
1596
1680
  withQuery(nameRelation, callback, options = { pivot: false }) {
1597
- var _a, _b;
1598
1681
  this.with(nameRelation);
1599
1682
  if (options.pivot) {
1600
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.callbackPivot(String(nameRelation), callback);
1683
+ this.$relation.callbackPivot(String(nameRelation), callback);
1601
1684
  return this;
1602
1685
  }
1603
- (_b = this.$relation) === null || _b === void 0 ? void 0 : _b.callback(String(nameRelation), callback);
1686
+ this.$relation.callback(String(nameRelation), callback);
1604
1687
  return this;
1605
1688
  }
1606
1689
  /**
@@ -1637,12 +1720,12 @@ class Model extends AbstractModel_1.AbstractModel {
1637
1720
  * }
1638
1721
  *
1639
1722
  * await new User().relations('posts')
1640
- * .relationsQuery('posts', (query : Post) => {
1723
+ * .relationQuery('posts', (query : Post) => {
1641
1724
  * return query.relations('comments','user')
1642
- * .relationsQuery('comments', (query : Comment) => {
1725
+ * .relationQuery('comments', (query : Comment) => {
1643
1726
  * return query.relations('user','post')
1644
1727
  * })
1645
- * .relationsQuery('user', (query : User) => {
1728
+ * .relationQuery('user', (query : User) => {
1646
1729
  * return query.relations('posts').relationsQuery('posts',(query : Post)=> {
1647
1730
  * return query.relations('comments','user')
1648
1731
  * // relation n, n, ...n
@@ -1664,8 +1747,7 @@ class Model extends AbstractModel_1.AbstractModel {
1664
1747
  * @returns {Model} model instance
1665
1748
  */
1666
1749
  findWithQuery(nameRelation) {
1667
- var _a;
1668
- const instanceCallback = (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.returnCallback(nameRelation);
1750
+ const instanceCallback = this.$relation.returnCallback(String(nameRelation));
1669
1751
  return instanceCallback == null ? null : instanceCallback;
1670
1752
  }
1671
1753
  /**
@@ -1685,8 +1767,7 @@ class Model extends AbstractModel_1.AbstractModel {
1685
1767
  * @returns {this} this
1686
1768
  */
1687
1769
  hasOne({ name, as, model, localKey, foreignKey, freezeTable }) {
1688
- var _a;
1689
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.hasOne({
1770
+ this.$relation.hasOne({
1690
1771
  name,
1691
1772
  as,
1692
1773
  model,
@@ -1713,8 +1794,7 @@ class Model extends AbstractModel_1.AbstractModel {
1713
1794
  * @returns {this} this
1714
1795
  */
1715
1796
  hasMany({ name, as, model, localKey, foreignKey, freezeTable }) {
1716
- var _a;
1717
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.hasMany({
1797
+ this.$relation.hasMany({
1718
1798
  name,
1719
1799
  as,
1720
1800
  model,
@@ -1741,8 +1821,7 @@ class Model extends AbstractModel_1.AbstractModel {
1741
1821
  * @returns {this} this
1742
1822
  */
1743
1823
  belongsTo({ name, as, model, localKey, foreignKey, freezeTable }) {
1744
- var _a;
1745
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.belongsTo({
1824
+ this.$relation.belongsTo({
1746
1825
  name,
1747
1826
  as,
1748
1827
  model,
@@ -1772,8 +1851,7 @@ class Model extends AbstractModel_1.AbstractModel {
1772
1851
  * @returns {this} this
1773
1852
  */
1774
1853
  belongsToMany({ name, as, model, localKey, foreignKey, freezeTable, pivot, oldVersion, modelPivot }) {
1775
- var _a;
1776
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.belongsToMany({
1854
+ this.$relation.belongsToMany({
1777
1855
  name,
1778
1856
  as,
1779
1857
  model,
@@ -1801,8 +1879,7 @@ class Model extends AbstractModel_1.AbstractModel {
1801
1879
  * @returns {this} this
1802
1880
  */
1803
1881
  hasOneBuilder({ name, as, model, localKey, foreignKey, freezeTable }, callback) {
1804
- var _a;
1805
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.hasOneBuilder({
1882
+ this.$relation.hasOneBuilder({
1806
1883
  name,
1807
1884
  as,
1808
1885
  model,
@@ -1827,8 +1904,7 @@ class Model extends AbstractModel_1.AbstractModel {
1827
1904
  * @returns {this} this
1828
1905
  */
1829
1906
  hasManyBuilder({ name, as, model, localKey, foreignKey, freezeTable }, callback) {
1830
- var _a;
1831
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.hasManyBuilder({
1907
+ this.$relation.hasManyBuilder({
1832
1908
  name,
1833
1909
  as,
1834
1910
  model,
@@ -1852,8 +1928,7 @@ class Model extends AbstractModel_1.AbstractModel {
1852
1928
  * @returns {this} this
1853
1929
  */
1854
1930
  belongsToBuilder({ name, as, model, localKey, foreignKey, freezeTable }, callback) {
1855
- var _a;
1856
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.belongsToBuilder({
1931
+ this.$relation.belongsToBuilder({
1857
1932
  name,
1858
1933
  as,
1859
1934
  model,
@@ -1878,8 +1953,7 @@ class Model extends AbstractModel_1.AbstractModel {
1878
1953
  * @returns {this} this
1879
1954
  */
1880
1955
  belongsToManyBuilder({ name, as, model, localKey, foreignKey, freezeTable, pivot, oldVersion, modelPivot }, callback) {
1881
- var _a;
1882
- (_a = this.$relation) === null || _a === void 0 ? void 0 : _a.belongsToManyBuilder({
1956
+ this.$relation.belongsToManyBuilder({
1883
1957
  name,
1884
1958
  as,
1885
1959
  model,
@@ -2012,6 +2086,60 @@ class Model extends AbstractModel_1.AbstractModel {
2012
2086
  ]);
2013
2087
  return this;
2014
2088
  }
2089
+ /**
2090
+ * @override
2091
+ * @param {string} column
2092
+ * @param {number} day
2093
+ * @returns {this}
2094
+ */
2095
+ whereDay(column, day) {
2096
+ this.$state.set('WHERE', [
2097
+ ...this.$state.get('WHERE'),
2098
+ [
2099
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2100
+ `DAY(${this.bindColumn(String(column))})`,
2101
+ `=`,
2102
+ `'${`00${this.$utils.escape(day)}`.slice(-2)}'`
2103
+ ].join(' ')
2104
+ ]);
2105
+ return this;
2106
+ }
2107
+ /**
2108
+ * @override
2109
+ * @param {string} column
2110
+ * @param {number} month
2111
+ * @returns {this}
2112
+ */
2113
+ whereMonth(column, month) {
2114
+ this.$state.set('WHERE', [
2115
+ ...this.$state.get('WHERE'),
2116
+ [
2117
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2118
+ `MONTH(${this.bindColumn(String(column))})`,
2119
+ `=`,
2120
+ `'${`00${this.$utils.escape(month)}`.slice(-2)}'`
2121
+ ].join(' ')
2122
+ ]);
2123
+ return this;
2124
+ }
2125
+ /**
2126
+ * @override
2127
+ * @param {string} column
2128
+ * @param {number} year
2129
+ * @returns {this}
2130
+ */
2131
+ whereYear(column, year) {
2132
+ this.$state.set('WHERE', [
2133
+ ...this.$state.get('WHERE'),
2134
+ [
2135
+ this.$state.get('WHERE').length ? `${this.$constants('AND')}` : '',
2136
+ `YEAR(${this.bindColumn(String(column))})`,
2137
+ `=`,
2138
+ `'${`0000${this.$utils.escape(year)}`.slice(-4)}'`
2139
+ ].join(' ')
2140
+ ]);
2141
+ return this;
2142
+ }
2015
2143
  /**
2016
2144
  * @override
2017
2145
  * @param {Object} columns
@@ -2239,9 +2367,6 @@ class Model extends AbstractModel_1.AbstractModel {
2239
2367
  * @returns {this}
2240
2368
  */
2241
2369
  whereSubQuery(column, subQuery) {
2242
- if (!this.$utils.isSubQuery(subQuery)) {
2243
- throw this._assertError(`This "subQuery" is invalid. Sub query is should contain 1 column(s)`);
2244
- }
2245
2370
  const c = this._columnPattern(String(column));
2246
2371
  this.$state.set('WHERE', [
2247
2372
  ...this.$state.get('WHERE'),
@@ -2261,9 +2386,6 @@ class Model extends AbstractModel_1.AbstractModel {
2261
2386
  * @returns {this}
2262
2387
  */
2263
2388
  whereNotSubQuery(column, subQuery) {
2264
- if (!this.$utils.isSubQuery(subQuery)) {
2265
- throw this._assertError(`This "subQuery" is invalid. Sub query is should contain 1 column(s)`);
2266
- }
2267
2389
  const c = this._columnPattern(String(column));
2268
2390
  this.$state.set('WHERE', [
2269
2391
  ...this.$state.get('WHERE'),
@@ -2283,9 +2405,6 @@ class Model extends AbstractModel_1.AbstractModel {
2283
2405
  * @returns {this}
2284
2406
  */
2285
2407
  orWhereSubQuery(column, subQuery) {
2286
- if (!this.$utils.isSubQuery(subQuery)) {
2287
- throw this._assertError(`This "subQuery" is invalid. Sub query is should contain 1 column(s)`);
2288
- }
2289
2408
  const c = this._columnPattern(String(column));
2290
2409
  this.$state.set('WHERE', [
2291
2410
  ...this.$state.get('WHERE'),
@@ -2307,9 +2426,6 @@ class Model extends AbstractModel_1.AbstractModel {
2307
2426
  * @returns {this}
2308
2427
  */
2309
2428
  orWhereNotSubQuery(column, subQuery) {
2310
- if (!this.$utils.isSubQuery(subQuery)) {
2311
- throw this._assertError(`This "subQuery" is invalid. Sub query is should contain 1 column(s)`);
2312
- }
2313
2429
  const c = this._columnPattern(String(column));
2314
2430
  this.$state.set('WHERE', [
2315
2431
  ...this.$state.get('WHERE'),
@@ -2810,7 +2926,7 @@ class Model extends AbstractModel_1.AbstractModel {
2810
2926
  */
2811
2927
  first(cb) {
2812
2928
  return __awaiter(this, void 0, void 0, function* () {
2813
- var _a, _b;
2929
+ var _a;
2814
2930
  this._validateMethod('first');
2815
2931
  if (this.$state.get('VOID'))
2816
2932
  return this._resultHandler(undefined);
@@ -2819,7 +2935,7 @@ class Model extends AbstractModel_1.AbstractModel {
2819
2935
  this.limit(1);
2820
2936
  let sql = this._queryBuilder().select();
2821
2937
  if (this.$state.get('RELATIONS_EXISTS'))
2822
- sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
2938
+ sql = String(this.$relation.loadExists());
2823
2939
  if (cb) {
2824
2940
  const callbackSql = cb(sql);
2825
2941
  if (callbackSql == null || callbackSql === '') {
@@ -2849,18 +2965,18 @@ class Model extends AbstractModel_1.AbstractModel {
2849
2965
  */
2850
2966
  firstOrError(message, options) {
2851
2967
  return __awaiter(this, void 0, void 0, function* () {
2852
- var _a, _b;
2968
+ var _a;
2853
2969
  this._validateMethod('firstOrError');
2854
2970
  if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2855
2971
  this.select(...yield this.exceptColumns());
2856
2972
  this.limit(1);
2857
2973
  let sql = this._queryBuilder().select();
2858
2974
  if (this.$state.get('RELATIONS_EXISTS'))
2859
- sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
2975
+ sql = String(this.$relation.loadExists());
2860
2976
  return yield this._execute({
2861
2977
  sql,
2862
2978
  type: 'FIRST_OR_ERROR',
2863
- message,
2979
+ message: message == null ? 'The data does not exist.' : message,
2864
2980
  options
2865
2981
  });
2866
2982
  });
@@ -2883,7 +2999,7 @@ class Model extends AbstractModel_1.AbstractModel {
2883
2999
  */
2884
3000
  get(cb) {
2885
3001
  return __awaiter(this, void 0, void 0, function* () {
2886
- var _a, _b;
3002
+ var _a;
2887
3003
  this._validateMethod('get');
2888
3004
  if (this.$state.get('VOID'))
2889
3005
  return [];
@@ -2891,7 +3007,7 @@ class Model extends AbstractModel_1.AbstractModel {
2891
3007
  this.select(...yield this.exceptColumns());
2892
3008
  let sql = this._queryBuilder().select();
2893
3009
  if (this.$state.get('RELATIONS_EXISTS'))
2894
- sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
3010
+ sql = String(this.$relation.loadExists());
2895
3011
  if (cb) {
2896
3012
  const callbackSql = cb(sql);
2897
3013
  if (callbackSql == null || callbackSql === '') {
@@ -2925,7 +3041,7 @@ class Model extends AbstractModel_1.AbstractModel {
2925
3041
  */
2926
3042
  pagination(paginationOptions) {
2927
3043
  return __awaiter(this, void 0, void 0, function* () {
2928
- var _a, _b;
3044
+ var _a;
2929
3045
  this._validateMethod('pagination');
2930
3046
  let limit = 15;
2931
3047
  let page = 1;
@@ -2933,7 +3049,6 @@ class Model extends AbstractModel_1.AbstractModel {
2933
3049
  limit = ((paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit);
2934
3050
  page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
2935
3051
  }
2936
- limit = limit > 1000 ? 1000 : limit;
2937
3052
  if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2938
3053
  this.select(...yield this.exceptColumns());
2939
3054
  const offset = (page - 1) * limit;
@@ -2943,7 +3058,7 @@ class Model extends AbstractModel_1.AbstractModel {
2943
3058
  this.offset(offset);
2944
3059
  let sql = this._queryBuilder().select();
2945
3060
  if (this.$state.get('RELATIONS_EXISTS'))
2946
- sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
3061
+ sql = String(this.$relation.loadExists());
2947
3062
  return yield this._execute({
2948
3063
  sql,
2949
3064
  type: 'PAGINATION'
@@ -3398,41 +3513,46 @@ class Model extends AbstractModel_1.AbstractModel {
3398
3513
  */
3399
3514
  faker(rows, callback) {
3400
3515
  return __awaiter(this, void 0, void 0, function* () {
3401
- const data = [];
3402
- const sql = [
3403
- `${this.$constants('SHOW')}`,
3404
- `${this.$constants('FIELDS')}`,
3405
- `${this.$constants('FROM')}`,
3406
- `${this.$state.get('TABLE_NAME')}`
3407
- ].join(' ');
3516
+ if (this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null) {
3517
+ throw this._assertError("Unknow table.");
3518
+ }
3408
3519
  const schemaModel = this.getSchemaModel();
3409
3520
  const fields = schemaModel == null
3410
- ? yield this._queryStatement(sql)
3521
+ ? yield this.getSchema()
3411
3522
  : Object.entries(schemaModel).map(([key, value]) => {
3412
3523
  return {
3413
3524
  Field: key,
3414
3525
  Type: value.type
3415
3526
  };
3416
3527
  });
3417
- if (this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null) {
3418
- throw this._assertError("Unknow this table.");
3419
- }
3528
+ const fakers = [];
3529
+ const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
3530
+ const uuid = this.$state.get('UUID_FORMAT');
3531
+ const passed = (field) => ['id', '_id', deletedAt].some(p => field === p);
3420
3532
  for (let row = 0; row < rows; row++) {
3421
3533
  let columnAndValue = {};
3422
3534
  for (const { Field: field, Type: type } of fields) {
3423
- const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
3424
- const passed = ['id', '_id', 'uuid', deletedAt].some(p => field === p);
3425
- if (passed)
3535
+ if (passed(field))
3426
3536
  continue;
3427
- columnAndValue = Object.assign(Object.assign({}, columnAndValue), { [field]: this.$utils.faker(type) });
3537
+ columnAndValue = Object.assign(Object.assign({}, columnAndValue), { [field]: field === uuid
3538
+ ? this.$utils.faker('uuid')
3539
+ : this.$utils.faker(type) });
3428
3540
  }
3429
3541
  if (callback) {
3430
- data.push(callback(columnAndValue, row));
3542
+ fakers.push(callback(columnAndValue, row));
3431
3543
  continue;
3432
3544
  }
3433
- data.push(columnAndValue);
3545
+ fakers.push(columnAndValue);
3546
+ }
3547
+ const chunkedData = this.$utils.chunkArray([...fakers], 500);
3548
+ const promises = [];
3549
+ const table = this.getTableName();
3550
+ for (const data of chunkedData) {
3551
+ promises.push(() => {
3552
+ return new DB_1.DB(table).createMultiple([...data]).void().save();
3553
+ });
3434
3554
  }
3435
- yield this.createMultiple(data).void().save();
3555
+ yield Promise.allSettled(promises.map((v) => v()));
3436
3556
  return;
3437
3557
  });
3438
3558
  }
@@ -3452,7 +3572,7 @@ class Model extends AbstractModel_1.AbstractModel {
3452
3572
  const existsTables = checkTables.map((c) => Object.values(c)[0]);
3453
3573
  const schemaModel = this.getSchemaModel();
3454
3574
  if (schemaModel == null)
3455
- throw this._assertError(schemaModel == null, 'Schema model not found');
3575
+ throw this._assertError('The schema model does not exist.');
3456
3576
  const checkTableIsExists = existsTables.some((table) => table === this.getTableName());
3457
3577
  const syncForeignKey = (_j) => __awaiter(this, [_j], void 0, function* ({ schemaModel, model }) {
3458
3578
  var _k;
@@ -3550,45 +3670,14 @@ class Model extends AbstractModel_1.AbstractModel {
3550
3670
  return;
3551
3671
  });
3552
3672
  }
3553
- covertColumnSchemaToFixColumn(column) {
3554
- const schema = this.$state.get('SCHEMA_TABLE');
3555
- if (schema == null)
3556
- return column;
3557
- const find = schema[column];
3558
- if (find == null || find.column == null) {
3559
- return column;
3560
- }
3561
- return find.column;
3562
- }
3563
- covertFixColumnToColumnSchema(column) {
3564
- const schema = this.$state.get('SCHEMA_TABLE');
3565
- if (schema == null)
3566
- return column;
3567
- const fixColumns = [];
3568
- for (const key in schema) {
3569
- const find = schema[key];
3570
- if (find.column == null)
3571
- continue;
3572
- fixColumns.push({
3573
- key,
3574
- value: find.column
3575
- });
3576
- }
3577
- const findColumnSameTheColumn = fixColumns.find(fixColumn => fixColumn.value === column);
3578
- return findColumnSameTheColumn == null ? column : findColumnSameTheColumn.key;
3579
- }
3580
3673
  _valuePattern(column) {
3581
- const fixColumn = this.covertColumnSchemaToFixColumn(column);
3582
3674
  switch (this.$state.get('PATTERN')) {
3583
3675
  case this.$constants('PATTERN').snake_case: {
3584
- return fixColumn === column
3585
- ? column.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`)
3586
- : fixColumn;
3676
+ return column.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`);
3587
3677
  }
3588
3678
  case this.$constants('PATTERN').camelCase: {
3589
- return fixColumn === column
3590
- ? column.replace(/(.(_|-|\s)+.)/g, (str) => `${str[0]}${str[str.length - 1].toUpperCase()}`)
3591
- : fixColumn;
3679
+ return column
3680
+ .replace(/(.(_|-|\s)+.)/g, (str) => `${str[0]}${str[str.length - 1].toUpperCase()}`);
3592
3681
  }
3593
3682
  default: return column;
3594
3683
  }
@@ -3642,18 +3731,26 @@ class Model extends AbstractModel_1.AbstractModel {
3642
3731
  return this;
3643
3732
  }
3644
3733
  _handleSoftDelete() {
3645
- if (this.$state.get('SOFT_DELETE')) {
3646
- const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
3647
- const wheres = this.$state.get('WHERE');
3648
- const softDeleteIsNull = [
3649
- this.bindColumn(`${this.getTableName()}.${deletedAt}`),
3650
- this.$constants('IS_NULL')
3651
- ].join(' ');
3652
- if (!wheres.some((where) => where.includes(softDeleteIsNull))) {
3653
- this.whereNull(deletedAt);
3654
- return this;
3655
- }
3734
+ if (!this.$state.get('SOFT_DELETE'))
3735
+ return this;
3736
+ const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
3737
+ const wheres = this.$state.get('WHERE');
3738
+ const softDeleteIsNull = [
3739
+ this.bindColumn(`${this.getTableName()}.${deletedAt}`),
3740
+ this.$constants('IS_NULL')
3741
+ ].join(' ');
3742
+ if (!wheres.some((where) => where.includes(softDeleteIsNull))) {
3743
+ this.whereNull(deletedAt);
3744
+ return this;
3745
+ }
3746
+ return this;
3747
+ }
3748
+ _handleGlobalScope() {
3749
+ if (!this.$state.get('GLOBAL_SCOPE'))
3656
3750
  return this;
3751
+ const globalScopeQuery = this.$state.get('GLOBAL_SCOPE_QUERY');
3752
+ if (globalScopeQuery != null && typeof globalScopeQuery === 'function') {
3753
+ globalScopeQuery();
3657
3754
  }
3658
3755
  return this;
3659
3756
  }
@@ -3685,8 +3782,9 @@ class Model extends AbstractModel_1.AbstractModel {
3685
3782
  * @override
3686
3783
  */
3687
3784
  _queryBuilder() {
3688
- this._handleSoftDelete();
3785
+ this._handleGlobalScope();
3689
3786
  this._handleSelect();
3787
+ this._handleSoftDelete();
3690
3788
  return this._buildQueryStatement();
3691
3789
  }
3692
3790
  _showOnly(data) {
@@ -3798,36 +3896,20 @@ class Model extends AbstractModel_1.AbstractModel {
3798
3896
  }
3799
3897
  _execute(_a) {
3800
3898
  return __awaiter(this, arguments, void 0, function* ({ sql, type, message, options }) {
3801
- var _b, _c;
3899
+ var _b;
3802
3900
  let result = yield this._queryStatement(sql);
3803
3901
  if (!result.length)
3804
3902
  return this._returnEmpty(type, result, message, options);
3805
3903
  const relations = this.$state.get('RELATIONS');
3806
3904
  for (const relation of relations) {
3807
- result = (_c = yield ((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.load(result, relation))) !== null && _c !== void 0 ? _c : [];
3905
+ const loaded = (_b = yield this.$relation.load(result, relation)) !== null && _b !== void 0 ? _b : [];
3906
+ result = loaded;
3808
3907
  }
3809
3908
  if (this.$state.get('HIDDEN').length)
3810
3909
  this._hiddenColumnModel(result);
3811
3910
  return (yield this._returnResult(type, result)) || this._returnEmpty(type, result, message, options);
3812
3911
  });
3813
3912
  }
3814
- _executeGroup(dataParents_1) {
3815
- return __awaiter(this, arguments, void 0, function* (dataParents, type = 'GET') {
3816
- var _a, _b, _c;
3817
- if (!dataParents.length)
3818
- return this._returnEmpty(type, dataParents);
3819
- const relations = this.$state.get('RELATIONS');
3820
- if (relations.length) {
3821
- for (const relation of relations) {
3822
- dataParents = (_b = yield ((_a = this.$relation) === null || _a === void 0 ? void 0 : _a.load(dataParents, relation))) !== null && _b !== void 0 ? _b : [];
3823
- }
3824
- }
3825
- if ((_c = this.$state.get('HIDDEN')) === null || _c === void 0 ? void 0 : _c.length)
3826
- this._hiddenColumnModel(dataParents);
3827
- const resultData = yield this._returnResult(type, dataParents);
3828
- return resultData || this._returnEmpty(type, dataParents);
3829
- });
3830
- }
3831
3913
  _pagination(data) {
3832
3914
  return __awaiter(this, void 0, void 0, function* () {
3833
3915
  var _a;
@@ -3950,10 +4032,10 @@ class Model extends AbstractModel_1.AbstractModel {
3950
4032
  for (const d of data) {
3951
4033
  for (const r of this.$state.get('RELATION')) {
3952
4034
  d[`$${r.name}`] = (cb) => __awaiter(this, void 0, void 0, function* () {
3953
- var _f, _g;
4035
+ var _f;
3954
4036
  const query = cb ? cb(new r.model()) : new r.model();
3955
4037
  r.query = query;
3956
- const dataFromRelation = (_g = yield ((_f = this.$relation) === null || _f === void 0 ? void 0 : _f.load([d], r))) !== null && _g !== void 0 ? _g : [];
4038
+ const dataFromRelation = (_f = yield this.$relation.load([d], r)) !== null && _f !== void 0 ? _f : [];
3957
4039
  const relationIsHasOneOrBelongsTo = [
3958
4040
  this.$constants('RELATIONSHIP').hasOne,
3959
4041
  this.$constants('RELATIONSHIP').belongsTo
@@ -3969,21 +4051,6 @@ class Model extends AbstractModel_1.AbstractModel {
3969
4051
  data = this._showOnly(data);
3970
4052
  let result = null;
3971
4053
  let res = [];
3972
- for (const r of data) {
3973
- const newData = {};
3974
- for (const origin in r) {
3975
- const value = r[origin];
3976
- const covert = this.covertFixColumnToColumnSchema(origin);
3977
- if (origin === covert) {
3978
- newData[origin] = value;
3979
- continue;
3980
- }
3981
- newData[covert] = value;
3982
- }
3983
- if (Object.keys(newData).length) {
3984
- res.push(newData);
3985
- }
3986
- }
3987
4054
  if (!res.length)
3988
4055
  res = data;
3989
4056
  switch (type) {
@@ -4227,11 +4294,11 @@ class Model extends AbstractModel_1.AbstractModel {
4227
4294
  var _a;
4228
4295
  let values = [];
4229
4296
  let columns = Object.keys((_a = [...data]) === null || _a === void 0 ? void 0 : _a.shift()).map((column) => column);
4297
+ const hasTimestamp = this.$state.get('TIMESTAMP');
4298
+ const format = this.$state.get('TIMESTAMP_FORMAT');
4230
4299
  for (let objects of data) {
4231
4300
  this.$utils.covertDataToDateIfDate(data);
4232
- const hasTimestamp = this.$state.get('TIMESTAMP');
4233
4301
  if (hasTimestamp) {
4234
- const format = this.$state.get('TIMESTAMP_FORMAT');
4235
4302
  const createdAt = this._valuePattern(format.CREATED_AT);
4236
4303
  const updatedAt = this._valuePattern(format.UPDATED_AT);
4237
4304
  objects = Object.assign(Object.assign({}, objects), { [createdAt]: this.$utils.timestamp(), [updatedAt]: this.$utils.timestamp() });