tspace-mysql 1.6.4 → 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 (39) 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 +26 -17
  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/Builder.d.ts +51 -3
  15. package/build/lib/core/Builder.js +162 -24
  16. package/build/lib/core/Builder.js.map +1 -1
  17. package/build/lib/core/DB.d.ts +15 -2
  18. package/build/lib/core/DB.js +17 -0
  19. package/build/lib/core/DB.js.map +1 -1
  20. package/build/lib/core/Handlers/Relation.d.ts +3 -3
  21. package/build/lib/core/Handlers/Relation.js +75 -54
  22. package/build/lib/core/Handlers/Relation.js.map +1 -1
  23. package/build/lib/core/Handlers/State.d.ts +130 -2
  24. package/build/lib/core/Handlers/State.js +3 -3
  25. package/build/lib/core/Handlers/State.js.map +1 -1
  26. package/build/lib/core/Model.d.ts +73 -17
  27. package/build/lib/core/Model.js +282 -203
  28. package/build/lib/core/Model.js.map +1 -1
  29. package/build/lib/core/Schema.js +1 -1
  30. package/build/lib/types.d.ts +3 -3
  31. package/build/lib/utils/index.d.ts +4 -1
  32. package/build/lib/utils/index.js +29 -4
  33. package/build/lib/utils/index.js.map +1 -1
  34. package/build/tests/03-Model.test.js +83 -14
  35. package/build/tests/03-Model.test.js.map +1 -1
  36. package/build/tests/schema-spec.d.ts +19 -2
  37. package/build/tests/schema-spec.js +12 -11
  38. package/build/tests/schema-spec.js.map +1 -1
  39. 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
@@ -2798,7 +2926,7 @@ class Model extends AbstractModel_1.AbstractModel {
2798
2926
  */
2799
2927
  first(cb) {
2800
2928
  return __awaiter(this, void 0, void 0, function* () {
2801
- var _a, _b;
2929
+ var _a;
2802
2930
  this._validateMethod('first');
2803
2931
  if (this.$state.get('VOID'))
2804
2932
  return this._resultHandler(undefined);
@@ -2807,7 +2935,7 @@ class Model extends AbstractModel_1.AbstractModel {
2807
2935
  this.limit(1);
2808
2936
  let sql = this._queryBuilder().select();
2809
2937
  if (this.$state.get('RELATIONS_EXISTS'))
2810
- sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
2938
+ sql = String(this.$relation.loadExists());
2811
2939
  if (cb) {
2812
2940
  const callbackSql = cb(sql);
2813
2941
  if (callbackSql == null || callbackSql === '') {
@@ -2837,18 +2965,18 @@ class Model extends AbstractModel_1.AbstractModel {
2837
2965
  */
2838
2966
  firstOrError(message, options) {
2839
2967
  return __awaiter(this, void 0, void 0, function* () {
2840
- var _a, _b;
2968
+ var _a;
2841
2969
  this._validateMethod('firstOrError');
2842
2970
  if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2843
2971
  this.select(...yield this.exceptColumns());
2844
2972
  this.limit(1);
2845
2973
  let sql = this._queryBuilder().select();
2846
2974
  if (this.$state.get('RELATIONS_EXISTS'))
2847
- sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
2975
+ sql = String(this.$relation.loadExists());
2848
2976
  return yield this._execute({
2849
2977
  sql,
2850
2978
  type: 'FIRST_OR_ERROR',
2851
- message,
2979
+ message: message == null ? 'The data does not exist.' : message,
2852
2980
  options
2853
2981
  });
2854
2982
  });
@@ -2871,7 +2999,7 @@ class Model extends AbstractModel_1.AbstractModel {
2871
2999
  */
2872
3000
  get(cb) {
2873
3001
  return __awaiter(this, void 0, void 0, function* () {
2874
- var _a, _b;
3002
+ var _a;
2875
3003
  this._validateMethod('get');
2876
3004
  if (this.$state.get('VOID'))
2877
3005
  return [];
@@ -2879,7 +3007,7 @@ class Model extends AbstractModel_1.AbstractModel {
2879
3007
  this.select(...yield this.exceptColumns());
2880
3008
  let sql = this._queryBuilder().select();
2881
3009
  if (this.$state.get('RELATIONS_EXISTS'))
2882
- sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
3010
+ sql = String(this.$relation.loadExists());
2883
3011
  if (cb) {
2884
3012
  const callbackSql = cb(sql);
2885
3013
  if (callbackSql == null || callbackSql === '') {
@@ -2913,7 +3041,7 @@ class Model extends AbstractModel_1.AbstractModel {
2913
3041
  */
2914
3042
  pagination(paginationOptions) {
2915
3043
  return __awaiter(this, void 0, void 0, function* () {
2916
- var _a, _b;
3044
+ var _a;
2917
3045
  this._validateMethod('pagination');
2918
3046
  let limit = 15;
2919
3047
  let page = 1;
@@ -2921,7 +3049,6 @@ class Model extends AbstractModel_1.AbstractModel {
2921
3049
  limit = ((paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.limit) || limit);
2922
3050
  page = (paginationOptions === null || paginationOptions === void 0 ? void 0 : paginationOptions.page) || page;
2923
3051
  }
2924
- limit = limit > 1000 ? 1000 : limit;
2925
3052
  if ((_a = this.$state.get('EXCEPTS')) === null || _a === void 0 ? void 0 : _a.length)
2926
3053
  this.select(...yield this.exceptColumns());
2927
3054
  const offset = (page - 1) * limit;
@@ -2931,7 +3058,7 @@ class Model extends AbstractModel_1.AbstractModel {
2931
3058
  this.offset(offset);
2932
3059
  let sql = this._queryBuilder().select();
2933
3060
  if (this.$state.get('RELATIONS_EXISTS'))
2934
- sql = String((_b = this.$relation) === null || _b === void 0 ? void 0 : _b.loadExists());
3061
+ sql = String(this.$relation.loadExists());
2935
3062
  return yield this._execute({
2936
3063
  sql,
2937
3064
  type: 'PAGINATION'
@@ -3386,41 +3513,46 @@ class Model extends AbstractModel_1.AbstractModel {
3386
3513
  */
3387
3514
  faker(rows, callback) {
3388
3515
  return __awaiter(this, void 0, void 0, function* () {
3389
- const data = [];
3390
- const sql = [
3391
- `${this.$constants('SHOW')}`,
3392
- `${this.$constants('FIELDS')}`,
3393
- `${this.$constants('FROM')}`,
3394
- `${this.$state.get('TABLE_NAME')}`
3395
- ].join(' ');
3516
+ if (this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null) {
3517
+ throw this._assertError("Unknow table.");
3518
+ }
3396
3519
  const schemaModel = this.getSchemaModel();
3397
3520
  const fields = schemaModel == null
3398
- ? yield this._queryStatement(sql)
3521
+ ? yield this.getSchema()
3399
3522
  : Object.entries(schemaModel).map(([key, value]) => {
3400
3523
  return {
3401
3524
  Field: key,
3402
3525
  Type: value.type
3403
3526
  };
3404
3527
  });
3405
- if (this.$state.get('TABLE_NAME') === '' || this.$state.get('TABLE_NAME') == null) {
3406
- throw this._assertError("Unknow this table.");
3407
- }
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);
3408
3532
  for (let row = 0; row < rows; row++) {
3409
3533
  let columnAndValue = {};
3410
3534
  for (const { Field: field, Type: type } of fields) {
3411
- const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
3412
- const passed = ['id', '_id', 'uuid', deletedAt].some(p => field === p);
3413
- if (passed)
3535
+ if (passed(field))
3414
3536
  continue;
3415
- 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) });
3416
3540
  }
3417
3541
  if (callback) {
3418
- data.push(callback(columnAndValue, row));
3542
+ fakers.push(callback(columnAndValue, row));
3419
3543
  continue;
3420
3544
  }
3421
- 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
+ });
3422
3554
  }
3423
- yield this.createMultiple(data).void().save();
3555
+ yield Promise.allSettled(promises.map((v) => v()));
3424
3556
  return;
3425
3557
  });
3426
3558
  }
@@ -3538,45 +3670,14 @@ class Model extends AbstractModel_1.AbstractModel {
3538
3670
  return;
3539
3671
  });
3540
3672
  }
3541
- covertColumnSchemaToFixColumn(column) {
3542
- const schema = this.$state.get('SCHEMA_TABLE');
3543
- if (schema == null)
3544
- return column;
3545
- const find = schema[column];
3546
- if (find == null || find.column == null) {
3547
- return column;
3548
- }
3549
- return find.column;
3550
- }
3551
- covertFixColumnToColumnSchema(column) {
3552
- const schema = this.$state.get('SCHEMA_TABLE');
3553
- if (schema == null)
3554
- return column;
3555
- const fixColumns = [];
3556
- for (const key in schema) {
3557
- const find = schema[key];
3558
- if (find.column == null)
3559
- continue;
3560
- fixColumns.push({
3561
- key,
3562
- value: find.column
3563
- });
3564
- }
3565
- const findColumnSameTheColumn = fixColumns.find(fixColumn => fixColumn.value === column);
3566
- return findColumnSameTheColumn == null ? column : findColumnSameTheColumn.key;
3567
- }
3568
3673
  _valuePattern(column) {
3569
- const fixColumn = this.covertColumnSchemaToFixColumn(column);
3570
3674
  switch (this.$state.get('PATTERN')) {
3571
3675
  case this.$constants('PATTERN').snake_case: {
3572
- return fixColumn === column
3573
- ? column.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`)
3574
- : fixColumn;
3676
+ return column.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`);
3575
3677
  }
3576
3678
  case this.$constants('PATTERN').camelCase: {
3577
- return fixColumn === column
3578
- ? column.replace(/(.(_|-|\s)+.)/g, (str) => `${str[0]}${str[str.length - 1].toUpperCase()}`)
3579
- : fixColumn;
3679
+ return column
3680
+ .replace(/(.(_|-|\s)+.)/g, (str) => `${str[0]}${str[str.length - 1].toUpperCase()}`);
3580
3681
  }
3581
3682
  default: return column;
3582
3683
  }
@@ -3630,21 +3731,29 @@ class Model extends AbstractModel_1.AbstractModel {
3630
3731
  return this;
3631
3732
  }
3632
3733
  _handleSoftDelete() {
3633
- if (this.$state.get('SOFT_DELETE')) {
3634
- const deletedAt = this._valuePattern(this.$state.get('SOFT_DELETE_FORMAT'));
3635
- const wheres = this.$state.get('WHERE');
3636
- const softDeleteIsNull = [
3637
- this.bindColumn(`${this.getTableName()}.${deletedAt}`),
3638
- this.$constants('IS_NULL')
3639
- ].join(' ');
3640
- if (!wheres.some((where) => where.includes(softDeleteIsNull))) {
3641
- this.whereNull(deletedAt);
3642
- return this;
3643
- }
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);
3644
3744
  return this;
3645
3745
  }
3646
3746
  return this;
3647
3747
  }
3748
+ _handleGlobalScope() {
3749
+ if (!this.$state.get('GLOBAL_SCOPE'))
3750
+ return this;
3751
+ const globalScopeQuery = this.$state.get('GLOBAL_SCOPE_QUERY');
3752
+ if (globalScopeQuery != null && typeof globalScopeQuery === 'function') {
3753
+ globalScopeQuery();
3754
+ }
3755
+ return this;
3756
+ }
3648
3757
  _handleSelect() {
3649
3758
  const selects = this.$state.get('SELECT');
3650
3759
  const hasStart = selects === null || selects === void 0 ? void 0 : selects.some(s => s.includes('*'));
@@ -3673,8 +3782,9 @@ class Model extends AbstractModel_1.AbstractModel {
3673
3782
  * @override
3674
3783
  */
3675
3784
  _queryBuilder() {
3676
- this._handleSoftDelete();
3785
+ this._handleGlobalScope();
3677
3786
  this._handleSelect();
3787
+ this._handleSoftDelete();
3678
3788
  return this._buildQueryStatement();
3679
3789
  }
3680
3790
  _showOnly(data) {
@@ -3786,36 +3896,20 @@ class Model extends AbstractModel_1.AbstractModel {
3786
3896
  }
3787
3897
  _execute(_a) {
3788
3898
  return __awaiter(this, arguments, void 0, function* ({ sql, type, message, options }) {
3789
- var _b, _c;
3899
+ var _b;
3790
3900
  let result = yield this._queryStatement(sql);
3791
3901
  if (!result.length)
3792
3902
  return this._returnEmpty(type, result, message, options);
3793
3903
  const relations = this.$state.get('RELATIONS');
3794
3904
  for (const relation of relations) {
3795
- 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;
3796
3907
  }
3797
3908
  if (this.$state.get('HIDDEN').length)
3798
3909
  this._hiddenColumnModel(result);
3799
3910
  return (yield this._returnResult(type, result)) || this._returnEmpty(type, result, message, options);
3800
3911
  });
3801
3912
  }
3802
- _executeGroup(dataParents_1) {
3803
- return __awaiter(this, arguments, void 0, function* (dataParents, type = 'GET') {
3804
- var _a, _b, _c;
3805
- if (!dataParents.length)
3806
- return this._returnEmpty(type, dataParents);
3807
- const relations = this.$state.get('RELATIONS');
3808
- if (relations.length) {
3809
- for (const relation of relations) {
3810
- dataParents = (_b = yield ((_a = this.$relation) === null || _a === void 0 ? void 0 : _a.load(dataParents, relation))) !== null && _b !== void 0 ? _b : [];
3811
- }
3812
- }
3813
- if ((_c = this.$state.get('HIDDEN')) === null || _c === void 0 ? void 0 : _c.length)
3814
- this._hiddenColumnModel(dataParents);
3815
- const resultData = yield this._returnResult(type, dataParents);
3816
- return resultData || this._returnEmpty(type, dataParents);
3817
- });
3818
- }
3819
3913
  _pagination(data) {
3820
3914
  return __awaiter(this, void 0, void 0, function* () {
3821
3915
  var _a;
@@ -3938,10 +4032,10 @@ class Model extends AbstractModel_1.AbstractModel {
3938
4032
  for (const d of data) {
3939
4033
  for (const r of this.$state.get('RELATION')) {
3940
4034
  d[`$${r.name}`] = (cb) => __awaiter(this, void 0, void 0, function* () {
3941
- var _f, _g;
4035
+ var _f;
3942
4036
  const query = cb ? cb(new r.model()) : new r.model();
3943
4037
  r.query = query;
3944
- 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 : [];
3945
4039
  const relationIsHasOneOrBelongsTo = [
3946
4040
  this.$constants('RELATIONSHIP').hasOne,
3947
4041
  this.$constants('RELATIONSHIP').belongsTo
@@ -3957,21 +4051,6 @@ class Model extends AbstractModel_1.AbstractModel {
3957
4051
  data = this._showOnly(data);
3958
4052
  let result = null;
3959
4053
  let res = [];
3960
- for (const r of data) {
3961
- const newData = {};
3962
- for (const origin in r) {
3963
- const value = r[origin];
3964
- const covert = this.covertFixColumnToColumnSchema(origin);
3965
- if (origin === covert) {
3966
- newData[origin] = value;
3967
- continue;
3968
- }
3969
- newData[covert] = value;
3970
- }
3971
- if (Object.keys(newData).length) {
3972
- res.push(newData);
3973
- }
3974
- }
3975
4054
  if (!res.length)
3976
4055
  res = data;
3977
4056
  switch (type) {
@@ -4215,11 +4294,11 @@ class Model extends AbstractModel_1.AbstractModel {
4215
4294
  var _a;
4216
4295
  let values = [];
4217
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');
4218
4299
  for (let objects of data) {
4219
4300
  this.$utils.covertDataToDateIfDate(data);
4220
- const hasTimestamp = this.$state.get('TIMESTAMP');
4221
4301
  if (hasTimestamp) {
4222
- const format = this.$state.get('TIMESTAMP_FORMAT');
4223
4302
  const createdAt = this._valuePattern(format.CREATED_AT);
4224
4303
  const updatedAt = this._valuePattern(format.UPDATED_AT);
4225
4304
  objects = Object.assign(Object.assign({}, objects), { [createdAt]: this.$utils.timestamp(), [updatedAt]: this.$utils.timestamp() });