tspace-mysql 1.9.0 → 1.9.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 (108) hide show
  1. package/README.md +4357 -133
  2. package/dist/lib/config/index.d.ts +2 -2
  3. package/dist/lib/config/index.js +24 -16
  4. package/dist/lib/config/index.js.map +1 -1
  5. package/dist/lib/constants/index.d.ts +10 -1
  6. package/dist/lib/constants/index.js +11 -2
  7. package/dist/lib/constants/index.js.map +1 -1
  8. package/dist/lib/core/Abstracts/AbstractBuilder.d.ts +11 -7
  9. package/dist/lib/core/Abstracts/AbstractBuilder.js +11 -13
  10. package/dist/lib/core/Abstracts/AbstractBuilder.js.map +1 -1
  11. package/dist/lib/core/Abstracts/AbstractDB.d.ts +4 -1
  12. package/dist/lib/core/Abstracts/AbstractDB.js.map +1 -1
  13. package/dist/lib/core/Abstracts/AbstractView.js.map +1 -1
  14. package/dist/lib/core/Blueprint.d.ts +30 -10
  15. package/dist/lib/core/Blueprint.js +39 -14
  16. package/dist/lib/core/Blueprint.js.map +1 -1
  17. package/dist/lib/core/Builder.d.ts +263 -9
  18. package/dist/lib/core/Builder.js +610 -347
  19. package/dist/lib/core/Builder.js.map +1 -1
  20. package/dist/lib/core/Cache/DBCache.js +19 -20
  21. package/dist/lib/core/Cache/DBCache.js.map +1 -1
  22. package/dist/lib/core/Cache/MemoryCache.js +3 -3
  23. package/dist/lib/core/Cache/MemoryCache.js.map +1 -1
  24. package/dist/lib/core/Cache/RedisCache.js +27 -17
  25. package/dist/lib/core/Cache/RedisCache.js.map +1 -1
  26. package/dist/lib/core/Cache/index.js +5 -4
  27. package/dist/lib/core/Cache/index.js.map +1 -1
  28. package/dist/lib/core/Contracts/AlterTable.d.ts +152 -0
  29. package/dist/lib/core/Contracts/AlterTable.js +243 -0
  30. package/dist/lib/core/Contracts/AlterTable.js.map +1 -0
  31. package/dist/lib/core/Contracts/Audit.js +2 -5
  32. package/dist/lib/core/Contracts/Audit.js.map +1 -1
  33. package/dist/lib/core/DB.d.ts +101 -9
  34. package/dist/lib/core/DB.js +168 -29
  35. package/dist/lib/core/DB.js.map +1 -1
  36. package/dist/lib/core/Decorator.d.ts +144 -16
  37. package/dist/lib/core/Decorator.js +156 -14
  38. package/dist/lib/core/Decorator.js.map +1 -1
  39. package/dist/lib/core/Driver/index.d.ts +43 -9
  40. package/dist/lib/core/Driver/index.js +9 -7
  41. package/dist/lib/core/Driver/index.js.map +1 -1
  42. package/dist/lib/core/Driver/mariadb/MariadbDriver.js +74 -27
  43. package/dist/lib/core/Driver/mariadb/MariadbDriver.js.map +1 -1
  44. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.d.ts +45 -9
  45. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js +165 -21
  46. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js.map +1 -1
  47. package/dist/lib/core/Driver/mongodb/MongodbDriver.d.ts +24 -0
  48. package/dist/lib/core/Driver/mongodb/MongodbDriver.js +255 -0
  49. package/dist/lib/core/Driver/mongodb/MongodbDriver.js.map +1 -0
  50. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.d.ts +141 -0
  51. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js +563 -0
  52. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js.map +1 -0
  53. package/dist/lib/core/Driver/mysql/MysqlDriver.js +105 -95
  54. package/dist/lib/core/Driver/mysql/MysqlDriver.js.map +1 -1
  55. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.d.ts +45 -9
  56. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js +165 -21
  57. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js.map +1 -1
  58. package/dist/lib/core/Driver/postgres/PostgresDriver.js +97 -72
  59. package/dist/lib/core/Driver/postgres/PostgresDriver.js.map +1 -1
  60. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.d.ts +50 -9
  61. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js +296 -41
  62. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js.map +1 -1
  63. package/dist/lib/core/Driver/sqlite/SqliteDriver.d.ts +20 -0
  64. package/dist/lib/core/Driver/sqlite/SqliteDriver.js +192 -0
  65. package/dist/lib/core/Driver/sqlite/SqliteDriver.js.map +1 -0
  66. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.d.ts +144 -0
  67. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js +689 -0
  68. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js.map +1 -0
  69. package/dist/lib/core/JoinModel.js +2 -2
  70. package/dist/lib/core/JoinModel.js.map +1 -1
  71. package/dist/lib/core/Meta.d.ts +17 -11
  72. package/dist/lib/core/Meta.js +25 -19
  73. package/dist/lib/core/Meta.js.map +1 -1
  74. package/dist/lib/core/Model.d.ts +450 -108
  75. package/dist/lib/core/Model.js +1031 -587
  76. package/dist/lib/core/Model.js.map +1 -1
  77. package/dist/lib/{tools/index.d.ts → core/Package.d.ts} +11 -3
  78. package/dist/lib/{tools/index.js → core/Package.js} +20 -7
  79. package/dist/lib/core/Package.js.map +1 -0
  80. package/dist/lib/core/Pool.js +42 -30
  81. package/dist/lib/core/Pool.js.map +1 -1
  82. package/dist/lib/core/Queue.d.ts +240 -0
  83. package/dist/lib/core/Queue.js +686 -0
  84. package/dist/lib/core/Queue.js.map +1 -0
  85. package/dist/lib/core/RelationManager.js +27 -25
  86. package/dist/lib/core/RelationManager.js.map +1 -1
  87. package/dist/lib/core/Repository.d.ts +73 -207
  88. package/dist/lib/core/Repository.js +120 -235
  89. package/dist/lib/core/Repository.js.map +1 -1
  90. package/dist/lib/core/Schema.d.ts +218 -0
  91. package/dist/lib/core/Schema.js +370 -65
  92. package/dist/lib/core/Schema.js.map +1 -1
  93. package/dist/lib/core/StateManager.d.ts +25 -12
  94. package/dist/lib/core/StateManager.js +10 -5
  95. package/dist/lib/core/StateManager.js.map +1 -1
  96. package/dist/lib/core/UtilityTypes.d.ts +85 -56
  97. package/dist/lib/core/UtilityTypes.js.map +1 -1
  98. package/dist/lib/core/index.d.ts +4 -0
  99. package/dist/lib/core/index.js +6 -2
  100. package/dist/lib/core/index.js.map +1 -1
  101. package/dist/lib/types/decorator/index.d.ts +1 -1
  102. package/dist/lib/types/index.d.ts +69 -22
  103. package/dist/lib/types/repository/index.d.ts +68 -37
  104. package/dist/lib/utils/index.d.ts +11 -1
  105. package/dist/lib/utils/index.js +58 -2
  106. package/dist/lib/utils/index.js.map +1 -1
  107. package/package.json +14 -6
  108. package/dist/lib/tools/index.js.map +0 -1
@@ -48,6 +48,7 @@ const Cache_1 = require("./Cache");
48
48
  const JoinModel_1 = require("./JoinModel");
49
49
  const constants_1 = require("../constants");
50
50
  const Decorator_1 = require("./Decorator");
51
+ const Repository_1 = __importDefault(require("./Repository"));
51
52
  let globalSettings = {
52
53
  softDelete: false,
53
54
  debug: false,
@@ -164,12 +165,389 @@ class Model extends AbstractModel_1.AbstractModel {
164
165
  static get instance() {
165
166
  return new this();
166
167
  }
168
+ /**
169
+ * The 'query' method is used to return instance
170
+ * @static
171
+ * @example
172
+ * const user = await User.query().where('id',1).findOne();
173
+ * console.log(user);
174
+ */
175
+ static query() {
176
+ return new this();
177
+ }
178
+ /**
179
+ *
180
+ * The 'find' method is used to retrieve a single record from a database table by its primary key.
181
+ *
182
+ * It allows you to retrieve a single record from a database table that meets the specified criteria.
183
+ * @type {?object} options
184
+ * @property {?object} options.select
185
+ * @property {?object} options.except
186
+ * @property {?object[]} options.orderBy
187
+ * @property {?string[]} options.groupBy
188
+ * @property {?string} options.having
189
+ * @property {?number} options.limit
190
+ * @property {?number} options.offset
191
+ * @property {?object} options.where
192
+ * @property {?string[]} options.whereRaw
193
+ * @property {?object} options.whereQuery
194
+ * @property {?{condition,callback}} options.when
195
+ * @property {?{localKey , referenceKey}[]} options.join
196
+ * @property {?{localKey , referenceKey}[]} options.rightJoin
197
+ * @property {?{localKey , referenceKey}[]} options.leftJoin
198
+ * @property {?string[]} options.relations
199
+ * @property {string[]} options.relationExists
200
+ * @property {?{condition,callback}} options.relationQuery
201
+ * @property {?boolean} options.debug
202
+ * @returns {promise<object>[]}
203
+ *
204
+ * @example
205
+ * import { User } from '../Models/User'
206
+ *
207
+ * const users = await User.find({
208
+ * select : { id: true, name: true },
209
+ * where : {
210
+ * id: 1
211
+ * }
212
+ * })
213
+ *
214
+ */
215
+ static async find(primaryKey, options = {}) {
216
+ return await (0, Repository_1.default)(this).find(primaryKey, options);
217
+ }
218
+ /**
219
+ *
220
+ * The 'findOne' method is used to retrieve the get record that matches the query conditions.
221
+ *
222
+ * It allows you to retrieve a single record from a database table that meets the specified criteria.
223
+ * @type {?object} options
224
+ * @property {?object} options.select
225
+ * @property {?object} options.except
226
+ * @property {?object[]} options.orderBy
227
+ * @property {?string[]} options.groupBy
228
+ * @property {?string} options.having
229
+ * @property {?number} options.limit
230
+ * @property {?number} options.offset
231
+ * @property {?object} options.where
232
+ * @property {?string[]} options.whereRaw
233
+ * @property {?object} options.whereQuery
234
+ * @property {?{condition,callback}} options.when
235
+ * @property {?{localKey , referenceKey}[]} options.join
236
+ * @property {?{localKey , referenceKey}[]} options.rightJoin
237
+ * @property {?{localKey , referenceKey}[]} options.leftJoin
238
+ * @property {?string[]} options.relations
239
+ * @property {string[]} options.relationExists
240
+ * @property {?{condition,callback}} options.relationQuery
241
+ * @property {?boolean} options.debug
242
+ * @returns {promise<object>[]}
243
+ *
244
+ * @example
245
+ * import { User } from '../Models/User'
246
+ *
247
+ * const users = await User.findOne({
248
+ * select : { id: true, name: true },
249
+ * where : {
250
+ * id: 1
251
+ * }
252
+ * })
253
+ *
254
+ */
255
+ static async findOne(options = {}) {
256
+ return await (0, Repository_1.default)(this).findOne(options);
257
+ }
258
+ /**
259
+ *
260
+ * The 'findMany' method is used to retrieve the get record that matches the query conditions.
261
+ *
262
+ * It allows you to retrieve a single record from a database table that meets the specified criteria.
263
+ * @type {?object} options
264
+ * @property {?object} options.select
265
+ * @property {?object} options.except
266
+ * @property {?object[]} options.orderBy
267
+ * @property {?string[]} options.groupBy
268
+ * @property {?string} options.having
269
+ * @property {?number} options.limit
270
+ * @property {?number} options.offset
271
+ * @property {?object} options.where
272
+ * @property {?string[]} options.whereRaw
273
+ * @property {?object} options.whereQuery
274
+ * @property {?{condition,callback}} options.when
275
+ * @property {?{localKey , referenceKey}[]} options.join
276
+ * @property {?{localKey , referenceKey}[]} options.rightJoin
277
+ * @property {?{localKey , referenceKey}[]} options.leftJoin
278
+ * @property {?string[]} options.relations
279
+ * @property {string[]} options.relationExists
280
+ * @property {?{condition,callback}} options.relationQuery
281
+ * @property {?boolean} options.debug
282
+ * @returns {promise<object>[]}
283
+ *
284
+ * @example
285
+ * import { User } from '../Models/User'
286
+ *
287
+ * const users = await User.findMany({
288
+ * select : { id: true, name: true },
289
+ * where : {
290
+ * id: 1
291
+ * }
292
+ * })
293
+ *
294
+ */
295
+ static async findMany(options = {}) {
296
+ return await (0, Repository_1.default)(this).findMany(options);
297
+ }
298
+ /**
299
+ *
300
+ * The 'paginate' method is used to perform pagination on a set of database query results obtained through the Query Builder.
301
+ *
302
+ * It allows you to split a large set of query results into smaller, more manageable pages,
303
+ * making it easier to display data in a web application and improve user experience.
304
+ * @type {?object} options
305
+ * @property {?object} options.select
306
+ * @property {?object} options.except
307
+ * @property {?object[]} options.orderBy
308
+ * @property {?string[]} options.groupBy
309
+ * @property {?string} options.having
310
+ * @property {?number} options.limit
311
+ * @property {?number} options.offset
312
+ * @property {?object} options.where
313
+ * @property {?string[]} options.whereRaw
314
+ * @property {?object} options.whereQuery
315
+ * @property {?{condition,callback}} options.when
316
+ * @property {?{localKey , referenceKey}[]} options.join
317
+ * @property {?{localKey , referenceKey}[]} options.rightJoin
318
+ * @property {?{localKey , referenceKey}[]} options.leftJoin
319
+ * @property {?string[]} options.relations
320
+ * @property {string[]} options.relationExists
321
+ * @property {?{condition,callback}} options.relationQuery
322
+ * @property {?boolean} options.debug
323
+ * @property {?number} options.page
324
+ * @returns {promise<{ meta , data[]}>}
325
+ *
326
+ * @example
327
+ * import { User } from '../Models/User'
328
+ *
329
+ * const users = await User.paginate({
330
+ * limit:15,
331
+ * page: 1,
332
+ * select : { id: true, name: true },
333
+ * where : {
334
+ * id: 1
335
+ * }
336
+ * })
337
+ */
338
+ static async paginate(options = {}) {
339
+ return await (0, Repository_1.default)(this).paginate(options);
340
+ }
341
+ /**
342
+ * The 'exists' method is used to determine if any records exist in the database table that match the query conditions.
343
+ *
344
+ * It returns a boolean value indicating whether there are any matching records.
345
+ * @type {?object} options
346
+ * @property {?object} options.select
347
+ * @property {?object} options.except
348
+ * @property {?object[]} options.orderBy
349
+ * @property {?string[]} options.groupBy
350
+ * @property {?string} options.having
351
+ * @property {?number} options.limit
352
+ * @property {?number} options.offset
353
+ * @property {?object} options.where
354
+ * @property {?string[]} options.whereRaw
355
+ * @property {?object} options.whereQuery
356
+ * @property {?{condition,callback}} options.when
357
+ * @property {?{localKey , referenceKey}[]} options.join
358
+ * @property {?{localKey , referenceKey}[]} options.rightJoin
359
+ * @property {?{localKey , referenceKey}[]} options.leftJoin
360
+ * @property {?boolean} options.debug
361
+ * @property {?number} options.page
362
+ *
363
+ * @example
364
+ * import { User } from '../Models/User'
365
+ *
366
+ * const users = await User.exists({
367
+ * where : {
368
+ * id: 1
369
+ * }
370
+ * })
371
+ *
372
+ */
373
+ static async exists(options) {
374
+ return await (0, Repository_1.default)(this).exists(options);
375
+ }
376
+ /**
377
+ * The 'toQuery' method is used to retrieve the raw SQL query that would be executed by a query builder instance without actually executing it.
378
+ *
379
+ * This method is particularly useful for debugging and understanding the SQL queries generated by your application.
380
+ * @type {?object} options
381
+ * @property {?object} options.select
382
+ * @property {?object} options.except
383
+ * @property {?object[]} options.orderBy
384
+ * @property {?string[]} options.groupBy
385
+ * @property {?string} options.having
386
+ * @property {?number} options.limit
387
+ * @property {?number} options.offset
388
+ * @property {?object} options.where
389
+ * @property {?string[]} options.whereRaw
390
+ * @property {?object} options.whereQuery
391
+ * @property {?{condition,callback}} options.when
392
+ * @property {?{localKey , referenceKey}[]} options.join
393
+ * @property {?{localKey , referenceKey}[]} options.rightJoin
394
+ * @property {?{localKey , referenceKey}[]} options.leftJoin
395
+ * @property {?boolean} options.debug
396
+ * @property {?number} options.page
397
+ *
398
+ * @example
399
+ * import { User } from '../Models/User'
400
+ *
401
+ * const users = await User.exists({
402
+ * where : {
403
+ * id: 1
404
+ * }
405
+ * })
406
+ *
407
+ */
408
+ static toQuery(options) {
409
+ return (0, Repository_1.default)(this).toString(options);
410
+ }
411
+ /**
412
+ * The 'create' method is used to insert a new record into a database table associated.
413
+ *
414
+ * It simplifies the process of creating and inserting records.
415
+ * @type {object} options
416
+ * @property {object} options.data
417
+ * @property {?boolean} options.debug
418
+ * @property {?transaction} options.transaction
419
+ * @return {promise<T.Result<M>>}
420
+ */
421
+ static async create(options) {
422
+ return (0, Repository_1.default)(this).create(options);
423
+ }
424
+ /**
425
+ * The 'createMany' method is used to insert a new records into a database table associated.
426
+ *
427
+ * It simplifies the process of creating and inserting records with an array.
428
+ * @type {object} options
429
+ * @property {object[]} options.data
430
+ * @property {?boolean} options.debug
431
+ * @property {?transaction} options.transaction
432
+ * @return {promise<TS[]>}
433
+ */
434
+ static async createMany(options) {
435
+ return (0, Repository_1.default)(this).createMany(options);
436
+ }
437
+ /**
438
+ *
439
+ * The 'createOrUpdate' method allows you to update an existing record in a database table if it exists or create a new record if it does not exist.
440
+ *
441
+ * This method is particularly useful when you want to update a record based on certain conditions and,
442
+ * if the record matching those conditions doesn't exist, create a new one with the provided data.
443
+ * @type {object} options
444
+ * @property {object} options.data
445
+ * @property {object} options.where
446
+ * @property {?boolean} options.debug
447
+ * @return {promise<NR extends true ? undefined : T.Result<M>[]>}
448
+ */
449
+ static async createOrUpdate(options) {
450
+ return (0, Repository_1.default)(this).createOrUpdate(options);
451
+ }
452
+ /**
453
+ * The 'createNotExists' method to insert data into a database table while ignoring any duplicate key constraint violations.
454
+ *
455
+ * This method is particularly useful when you want to insert records into a table and ensure that duplicates are not inserted,
456
+ * but without raising an error or exception if duplicates are encountered.
457
+ *
458
+ * @type {object} options
459
+ * @property {object} options.data
460
+ * @property {object} options.where
461
+ * @property {?boolean} options.debug
462
+ * @property {?transaction} options.transaction
463
+ * @return {promise<T | null>}
464
+ */
465
+ static async createNotExists(options) {
466
+ return (0, Repository_1.default)(this).createNotExists(options);
467
+ }
468
+ /**
469
+ *
470
+ * The 'createOrSelect' method to insert data into a database table while select any duplicate key constraint violations.
471
+ *
472
+ * This method is particularly useful when you want to insert records into a table and ensure that duplicates are not inserted,
473
+ * but if exists should be returns a result.
474
+ * @type {object} options
475
+ * @property {object} options.data
476
+ * @property {object} options.where
477
+ * @property {?boolean} options.debug
478
+ * @return {promise<T.Result<M>>}
479
+ */
480
+ static async createOrSelect(options) {
481
+ return (0, Repository_1.default)(this).createOrSelect(options);
482
+ }
483
+ /**
484
+ * The 'update' method is used to update existing records in a database table that are associated.
485
+ *
486
+ * It simplifies the process of updating records by allowing you to specify the values to be updated using a single call.
487
+ *
488
+ * It allows you to remove one record that match certain criteria.
489
+ * @type {object} options
490
+ * @property {object} options.data
491
+ * @property {object} options.where
492
+ * @property {?boolean} options.debug
493
+ * @property {?transaction} options.transaction
494
+ * @return {promise< NR extends true ? undefined : T.Result<M> | null>}
495
+ */
496
+ static async update(options) {
497
+ return (0, Repository_1.default)(this).update(options);
498
+ }
499
+ /**
500
+ * The 'updateMany' method is used to update existing records in a database table that are associated.
501
+ *
502
+ * It simplifies the process of updating records by allowing you to specify the values to be updated using a single call.
503
+ *
504
+ * It allows you to remove more records that match certain criteria.
505
+ * @type {object} options
506
+ * @property {object} options.data
507
+ * @property {object} options.where
508
+ * @property {?boolean} options.debug
509
+ * @property {?transaction} options.transaction
510
+ * @return {promise<T.Result<M>[]>}
511
+ */
512
+ static async updateMany(options) {
513
+ return (0, Repository_1.default)(this).updateMany(options);
514
+ }
167
515
  /**
168
516
  * The 'cache' method is used get the functions from the Cache
169
- * @returns {TCache} cache
517
+ * @returns {TCacheModel} cache
170
518
  */
171
519
  static get cache() {
172
- return Cache_1.Cache;
520
+ const getCacheKey = (key) => {
521
+ const db = new this().database();
522
+ const table = new this().getTableName();
523
+ return `${db}:${table}:${key}`;
524
+ };
525
+ return {
526
+ provider: () => Cache_1.Cache.provider(),
527
+ driver: (driver) => Cache_1.Cache.driver(driver),
528
+ all: async () => {
529
+ return await Cache_1.Cache.all();
530
+ },
531
+ clear: async () => {
532
+ return await Cache_1.Cache.clear();
533
+ },
534
+ get: async (key, options) => {
535
+ const cacheKey = options?.namespace ? getCacheKey(key) : key;
536
+ return await Cache_1.Cache.get(cacheKey);
537
+ },
538
+ exists: async (key, options) => {
539
+ const cacheKey = options?.namespace ? getCacheKey(key) : key;
540
+ return await Cache_1.Cache.exists(cacheKey);
541
+ },
542
+ set: async (key, value, ms, options) => {
543
+ const cacheKey = options?.namespace ? getCacheKey(key) : key;
544
+ return await Cache_1.Cache.set(cacheKey, value, ms);
545
+ },
546
+ delete: async (key, options) => {
547
+ const cacheKey = options?.namespace ? getCacheKey(key) : key;
548
+ return await Cache_1.Cache.delete(cacheKey);
549
+ },
550
+ };
173
551
  }
174
552
  /**
175
553
  * The 'boot' method is a special method that you can define within a model.
@@ -219,18 +597,12 @@ class Model extends AbstractModel_1.AbstractModel {
219
597
  this.$state.set("SELECT", [...this.$state.get("SELECT"), ...select]);
220
598
  }
221
599
  if (except.length) {
222
- this.$state.set("EXCEPTS", [
223
- ...this.$state.get("EXCEPTS"),
224
- ...except
225
- ]);
600
+ this.$state.set("EXCEPTS", [...this.$state.get("EXCEPTS"), ...except]);
226
601
  }
227
602
  if (where.length) {
228
603
  this.$state.set("WHERE", [
229
604
  ...this.$state.get("WHERE"),
230
- [
231
- this.$state.get("WHERE").length ? `${this.$constants("AND")}` : "",
232
- ...where,
233
- ].join(" "),
605
+ ...where
234
606
  ]);
235
607
  }
236
608
  if (groupBy.length) {
@@ -370,31 +742,31 @@ class Model extends AbstractModel_1.AbstractModel {
370
742
  return this;
371
743
  }
372
744
  /**
373
- * The "useTransform " method is used to define value transformers for model columns..
374
- *
375
- * Each transformer defines how a value is converted:
376
- * - `to` : before persisting to the database
377
- * - `from` : after retrieving from the database
378
- *
379
- * Transformers can be synchronous or asynchronous.
380
- *
381
- * @param {object} transforms
382
- * @example
383
- * import { Blueprint } from 'tspace-mysql';
384
- * class User extends Model {
385
- * boot() {
386
- * this.useTransform({
387
- * name : {
388
- * to : async (v) => `${v}-> transform@before`,
389
- * from : async (v) => `${v}-> transform@after`,
390
- * },
391
- * })
392
- * }
393
- * }
394
- * @returns {this} this
395
- */
745
+ * The "useTransform " method is used to define value transformers for model columns..
746
+ *
747
+ * Each transformer defines how a value is converted:
748
+ * - `to` : before persisting to the database
749
+ * - `from` : after retrieving from the database
750
+ *
751
+ * Transformers can be synchronous or asynchronous.
752
+ *
753
+ * @param {object} transforms
754
+ * @example
755
+ * import { Blueprint } from 'tspace-mysql';
756
+ * class User extends Model {
757
+ * boot() {
758
+ * this.useTransform({
759
+ * name : {
760
+ * to : async (v) => `${v}-> transform@before`,
761
+ * from : async (v) => `${v}-> transform@after`,
762
+ * },
763
+ * })
764
+ * }
765
+ * }
766
+ * @returns {this} this
767
+ */
396
768
  useTransform(transforms) {
397
- this.$state.set('TRANSFORMS', transforms);
769
+ this.$state.set("TRANSFORMS", transforms);
398
770
  return this;
399
771
  }
400
772
  /**
@@ -453,11 +825,11 @@ class Model extends AbstractModel_1.AbstractModel {
453
825
  */
454
826
  usePattern(pattern) {
455
827
  const allowPattern = [
456
- this.$constants("PATTERN").snakeCase,
828
+ this.$constants("PATTERN").snake_case,
457
829
  this.$constants("PATTERN").camelCase,
458
830
  ];
459
831
  if (!allowPattern.includes(pattern)) {
460
- throw this._assertError(`The 'tspace-mysql' support only pattern '${this.$constants("PATTERN").snakeCase}',
832
+ throw this._assertError(`The 'tspace-mysql' support only pattern '${this.$constants("PATTERN").snake_case}',
461
833
  '${this.$constants("PATTERN").camelCase}'`);
462
834
  }
463
835
  this.$state.set("PATTERN", pattern);
@@ -490,7 +862,7 @@ class Model extends AbstractModel_1.AbstractModel {
490
862
  * }
491
863
  */
492
864
  useSnakeCase() {
493
- this.$state.set("PATTERN", this.$constants("PATTERN").snakeCase);
865
+ this.$state.set("PATTERN", this.$constants("PATTERN").snake_case);
494
866
  this._makeTableName();
495
867
  return this;
496
868
  }
@@ -746,7 +1118,7 @@ class Model extends AbstractModel_1.AbstractModel {
746
1118
  * this
747
1119
  * .useLifecycle("beforeInsert", fnA)
748
1120
  * .useLifecycle("afterInsert", fnB);
749
- */
1121
+ */
750
1122
  useLifecycle(type, funcs) {
751
1123
  const MAP = {
752
1124
  beforeInsert: "LIFECYCLE_BEFORE_INSERTS",
@@ -886,7 +1258,9 @@ class Model extends AbstractModel_1.AbstractModel {
886
1258
  return except !== column;
887
1259
  });
888
1260
  });
889
- removeExcepts.push(hasDot ? removeExcept.map((r) => `\`${tableName}\`.${r}`) : removeExcept);
1261
+ removeExcepts.push(hasDot
1262
+ ? removeExcept.map((r) => `\`${tableName}\`.${r}`)
1263
+ : removeExcept);
890
1264
  }
891
1265
  return removeExcepts.flat();
892
1266
  }
@@ -898,13 +1272,11 @@ class Model extends AbstractModel_1.AbstractModel {
898
1272
  */
899
1273
  buildMethodRelation(name, callback) {
900
1274
  this.relations(name);
901
- const relation = this.$state
902
- .get("RELATIONS")
903
- .find((v) => v.name === name);
1275
+ const relation = this.$state.get("RELATIONS").find((v) => v.name === name);
904
1276
  if (relation == null) {
905
1277
  throw this._assertError(`This Relation '${String(name)}' not be register in Model '${this.constructor?.name}'.`);
906
1278
  }
907
- const relationHasExists = Object.values(this.$constants("RELATIONSHIP"))?.includes(relation.relation);
1279
+ const relationHasExists = Object.values(this.$constants("RELATIONSHIP"))?.includes(relation.relation ?? "");
908
1280
  if (!relationHasExists) {
909
1281
  throw this._assertError(`Unknown relationship in '${this.$constants("RELATIONSHIP")}'.`);
910
1282
  }
@@ -951,12 +1323,19 @@ class Model extends AbstractModel_1.AbstractModel {
951
1323
  * @param {Object} object
952
1324
  * @property {string} key key of cache
953
1325
  * @property {number} expires ms
1326
+ * @property {boolean} namespace whether to use namespace for cache key, default is false, namespace is `${database}:${table}:${key}`
954
1327
  * @returns {this} this
955
1328
  */
956
- cache({ key, expires }) {
1329
+ cache({ key, expires, namespace }) {
1330
+ const getCacheKey = (key) => {
1331
+ const db = this.database();
1332
+ const table = this.getTableName();
1333
+ return `${db}:${table}:${key}`;
1334
+ };
1335
+ const cacheKey = namespace ? getCacheKey(key) : key;
957
1336
  this.$state.set("CACHE", {
958
- key,
959
- expires,
1337
+ key: cacheKey,
1338
+ expires
960
1339
  });
961
1340
  return this;
962
1341
  }
@@ -1346,8 +1725,6 @@ class Model extends AbstractModel_1.AbstractModel {
1346
1725
  newInstance.$state.set("SAVE", null);
1347
1726
  newInstance.$state.set("DEBUG", false);
1348
1727
  newInstance.$state.set("LOGGER", false);
1349
- newInstance.$state.set("AUDIT", null);
1350
- newInstance.$state.set("AUDIT_METADATA", null);
1351
1728
  newInstance.$state.set("LIFECYCLE_BEFORE_INSERTS", []);
1352
1729
  newInstance.$state.set("LIFECYCLE_BEFORE_UPDATES", []);
1353
1730
  newInstance.$state.set("LIFECYCLE_BEFORE_REMOVES", []);
@@ -1389,7 +1766,7 @@ class Model extends AbstractModel_1.AbstractModel {
1389
1766
  */
1390
1767
  async _queryStatement(sql, { retry = false } = {}) {
1391
1768
  try {
1392
- sql = this._queryBuilder({ onFormat: true }).format([sql]);
1769
+ sql = this._queryBuilder().format([sql]);
1393
1770
  const getResults = async (sql) => {
1394
1771
  if (this.$state.get("DEBUG")) {
1395
1772
  const startTime = +new Date();
@@ -1423,7 +1800,6 @@ class Model extends AbstractModel_1.AbstractModel {
1423
1800
  throw error;
1424
1801
  const retryCount = Number(this.$state.get("RETRY"));
1425
1802
  await this._checkSchemaOrNextError(error, retryCount, error);
1426
- this.$state.set("RETRY", retryCount + 1);
1427
1803
  return await this._queryStatement(sql, { retry: true });
1428
1804
  }
1429
1805
  }
@@ -1436,7 +1812,7 @@ class Model extends AbstractModel_1.AbstractModel {
1436
1812
  */
1437
1813
  async _actionStatement(sql, { retry = false } = {}) {
1438
1814
  try {
1439
- sql = this._queryBuilder({ onFormat: true }).format([sql]);
1815
+ sql = this._queryBuilder().format([sql]);
1440
1816
  const getResults = async (sql) => {
1441
1817
  if (this.$state.get("DEBUG")) {
1442
1818
  const startTime = +new Date();
@@ -1470,7 +1846,6 @@ class Model extends AbstractModel_1.AbstractModel {
1470
1846
  if (this.$state.get("JOIN")?.length)
1471
1847
  throw error;
1472
1848
  await this._checkSchemaOrNextError(error, retryCount, error);
1473
- this.$state.set("RETRY", retryCount + 1);
1474
1849
  return await this._actionStatement(sql, { retry: true });
1475
1850
  }
1476
1851
  }
@@ -2325,9 +2700,7 @@ class Model extends AbstractModel_1.AbstractModel {
2325
2700
  const query = this.$state.get("TIMESTAMP")
2326
2701
  ? `${deletedAt} = NULL , ${updatedAt} = '${this.$utils.timestamp()}'`
2327
2702
  : `${deletedAt} = NULL`;
2328
- this.$state.set("UPDATE", [
2329
- `${query}`
2330
- ]);
2703
+ this.$state.set("UPDATE", [`${query}`]);
2331
2704
  this.$state.set("SAVE", "UPDATE");
2332
2705
  return (await this.save());
2333
2706
  }
@@ -2349,7 +2722,7 @@ class Model extends AbstractModel_1.AbstractModel {
2349
2722
  /**
2350
2723
  * @override
2351
2724
  * @param {string | K} column if arguments is object
2352
- * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
2725
+ * @param {string?} operator "=" | "<" | ">" | "!=" | "<>" | "<=" | ">=" | "LIKE" | "like"
2353
2726
  * @param {any?} value
2354
2727
  * @returns {this} this
2355
2728
  */
@@ -2358,9 +2731,6 @@ class Model extends AbstractModel_1.AbstractModel {
2358
2731
  return this.whereObject(column);
2359
2732
  }
2360
2733
  [value, operator] = this.$utils.valueAndOperator(value, operator, arguments.length === 2);
2361
- value = this.$utils.transfromDateToDateString(value);
2362
- value = this.$utils.escape(value);
2363
- value = this.$utils.transfromBooleanToNumber(value);
2364
2734
  const blueprint = this._getBlueprintByColumn(String(column));
2365
2735
  if (blueprint?.isVirtual) {
2366
2736
  const sql = blueprint.sql?.where;
@@ -2371,7 +2741,7 @@ class Model extends AbstractModel_1.AbstractModel {
2371
2741
  if (Array.isArray(value)) {
2372
2742
  const values = value
2373
2743
  ? `${value
2374
- .map((value) => this.$utils.transfromValueHasRaw(this.$utils.escape(value)))
2744
+ .map((value) => this.$utils.formatQueryValue(value))
2375
2745
  .join(",")}`
2376
2746
  : this.$constants(this.$constants("NULL"));
2377
2747
  return this.whereRaw(`${sql} ${this.$constants("IN")} (${values})`);
@@ -2385,32 +2755,19 @@ class Model extends AbstractModel_1.AbstractModel {
2385
2755
  if (Array.isArray(value)) {
2386
2756
  return this.whereIn(column, value);
2387
2757
  }
2388
- const wheres = this.$state.get("WHERE");
2758
+ const formatedValue = this.$utils.formatQueryValue(value);
2389
2759
  this.$state.set("WHERE", [
2390
- ...wheres,
2391
- [
2392
- wheres.length ? `${this.$constants("AND")}` : "",
2393
- `${this.bindColumn(String(column))}`,
2394
- `${operator}`,
2395
- `${this.$utils.transfromValueHasRaw(value)}`,
2396
- ]
2397
- .join(" ")
2398
- .replace(/^\s+/, "")
2760
+ ...this.$state.get("WHERE"),
2761
+ {
2762
+ column: this.bindColumn(String(column)),
2763
+ operator: operator,
2764
+ value: formatedValue
2765
+ }
2399
2766
  ]);
2400
2767
  return this;
2401
2768
  }
2402
- /**
2403
- * @override
2404
- * @param {string} column
2405
- * @param {string?} operator ['=', '<', '>' ,'!=', '!<', '!>' ,'LIKE']
2406
- * @param {any?} value
2407
- * @returns {this}
2408
- */
2409
2769
  orWhere(column, operator, value) {
2410
2770
  [value, operator] = this.$utils.valueAndOperator(value, operator, arguments.length === 2);
2411
- value = this.$utils.escape(value);
2412
- value = this.$utils.transfromBooleanToNumber(value);
2413
- value = this.$utils.transfromDateToDateString(value);
2414
2771
  const blueprint = this._getBlueprintByColumn(String(column));
2415
2772
  if (blueprint?.isVirtual) {
2416
2773
  const sql = blueprint.sql?.where;
@@ -2421,7 +2778,7 @@ class Model extends AbstractModel_1.AbstractModel {
2421
2778
  if (Array.isArray(value)) {
2422
2779
  const values = value
2423
2780
  ? `${value
2424
- .map((value) => this.$utils.transfromValueHasRaw(this.$utils.escape(value)))
2781
+ .map((value) => this.$utils.formatQueryValue(value))
2425
2782
  .join(",")}`
2426
2783
  : this.$constants(this.$constants("NULL"));
2427
2784
  return this.orWhereRaw(`${sql} ${this.$constants("IN")} (${values})`);
@@ -2435,17 +2792,15 @@ class Model extends AbstractModel_1.AbstractModel {
2435
2792
  if (Array.isArray(value)) {
2436
2793
  return this.orWhereIn(column, value);
2437
2794
  }
2438
- const wheres = this.$state.get("WHERE");
2795
+ const formatedValue = this.$utils.formatQueryValue(value);
2439
2796
  this.$state.set("WHERE", [
2440
- ...wheres,
2441
- [
2442
- wheres.length ? `${this.$constants("OR")}` : "",
2443
- `${this.bindColumn(String(column))}`,
2444
- `${operator}`,
2445
- `${this.$utils.transfromValueHasRaw(value)}`,
2446
- ]
2447
- .join(" ")
2448
- .replace(/^\s+/, ""),
2797
+ ...this.$state.get("WHERE"),
2798
+ {
2799
+ column: this.bindColumn(String(column)),
2800
+ operator: operator,
2801
+ value: formatedValue,
2802
+ condition: 'OR'
2803
+ }
2449
2804
  ]);
2450
2805
  return this;
2451
2806
  }
@@ -2456,17 +2811,13 @@ class Model extends AbstractModel_1.AbstractModel {
2456
2811
  * @returns {this}
2457
2812
  */
2458
2813
  whereDay(column, day) {
2459
- const wheres = this.$state.get("WHERE");
2460
2814
  this.$state.set("WHERE", [
2461
- ...wheres,
2462
- [
2463
- wheres.length ? `${this.$constants("AND")}` : "",
2464
- `DAY(${this.bindColumn(String(column))})`,
2465
- `=`,
2466
- `'${`00${this.$utils.escape(day)}`.slice(-2)}'`,
2467
- ]
2468
- .join(" ")
2469
- .replace(/^\s+/, ""),
2815
+ ...this.$state.get("WHERE"),
2816
+ {
2817
+ column: `DAY(${this.bindColumn(String(column))})`,
2818
+ operator: '=',
2819
+ value: `'${`00${this.$utils.escape(day)}`.slice(-2)}'`,
2820
+ }
2470
2821
  ]);
2471
2822
  return this;
2472
2823
  }
@@ -2477,17 +2828,13 @@ class Model extends AbstractModel_1.AbstractModel {
2477
2828
  * @returns {this}
2478
2829
  */
2479
2830
  whereMonth(column, month) {
2480
- const wheres = this.$state.get("WHERE");
2481
2831
  this.$state.set("WHERE", [
2482
- ...wheres,
2483
- [
2484
- wheres.length ? `${this.$constants("AND")}` : "",
2485
- `MONTH(${this.bindColumn(String(column))})`,
2486
- `=`,
2487
- `'${`00${this.$utils.escape(month)}`.slice(-2)}'`,
2488
- ]
2489
- .join(" ")
2490
- .replace(/^\s+/, ""),
2832
+ ...this.$state.get("WHERE"),
2833
+ {
2834
+ column: `MONTH(${this.bindColumn(String(column))})`,
2835
+ operator: '=',
2836
+ value: `'${`00${this.$utils.escape(month)}`.slice(-2)}'`,
2837
+ }
2491
2838
  ]);
2492
2839
  return this;
2493
2840
  }
@@ -2498,17 +2845,13 @@ class Model extends AbstractModel_1.AbstractModel {
2498
2845
  * @returns {this}
2499
2846
  */
2500
2847
  whereYear(column, year) {
2501
- const wheres = this.$state.get("WHERE");
2502
2848
  this.$state.set("WHERE", [
2503
- ...wheres,
2504
- [
2505
- wheres.length ? `${this.$constants("AND")}` : "",
2506
- `YEAR(${this.bindColumn(String(column))})`,
2507
- `=`,
2508
- `'${`0000${this.$utils.escape(year)}`.slice(-4)}'`,
2509
- ]
2510
- .join(" ")
2511
- .replace(/^\s+/, ""),
2849
+ ...this.$state.get("WHERE"),
2850
+ {
2851
+ column: `YEAR(${this.bindColumn(String(column))})`,
2852
+ operator: '=',
2853
+ value: `'${`0000${this.$utils.escape(year)}`.slice(-2)}'`,
2854
+ }
2512
2855
  ]);
2513
2856
  return this;
2514
2857
  }
@@ -2579,9 +2922,11 @@ class Model extends AbstractModel_1.AbstractModel {
2579
2922
  }
2580
2923
  default: {
2581
2924
  if (useOp.op.includes("|")) {
2925
+ //@ts-ignore
2582
2926
  this.orWhere(c, useOp.op.replace("|", ""), useOp.value);
2583
2927
  break;
2584
2928
  }
2929
+ //@ts-ignore
2585
2930
  this.where(c, useOp.op, useOp.value);
2586
2931
  }
2587
2932
  }
@@ -2598,19 +2943,14 @@ class Model extends AbstractModel_1.AbstractModel {
2598
2943
  * @returns {this}
2599
2944
  */
2600
2945
  whereJSON(column, { key, value, operator }) {
2601
- value = this.$utils.escape(value);
2602
- value = this.$utils.transfromBooleanToNumber(value);
2603
- const wheres = this.$state.get("WHERE");
2946
+ const formatedValue = this.$utils.formatQueryValue(value);
2604
2947
  this.$state.set("WHERE", [
2605
- ...wheres,
2606
- [
2607
- wheres.length ? `${this.$constants("AND")}` : "",
2608
- `${this.bindColumn(String(column))}->>'$.${key}'`,
2609
- `${operator == null ? "=" : operator.toLocaleUpperCase()}`,
2610
- `${this.$utils.transfromValueHasRaw(value)}`,
2611
- ]
2612
- .join(" ")
2613
- .replace(/^\s+/, ""),
2948
+ ...this.$state.get("WHERE"),
2949
+ {
2950
+ column: `${this.bindColumn(String(column))}->>'$.${key}'`,
2951
+ operator: `${operator == null ? "=" : operator.toLocaleUpperCase()}`,
2952
+ value: formatedValue
2953
+ }
2614
2954
  ]);
2615
2955
  return this;
2616
2956
  }
@@ -2633,15 +2973,14 @@ class Model extends AbstractModel_1.AbstractModel {
2633
2973
  * @returns {this}
2634
2974
  */
2635
2975
  whereUser(userId, column = "user_id") {
2636
- const wheres = this.$state.get("WHERE");
2976
+ const formatedValue = this.$utils.formatQueryValue(userId);
2637
2977
  this.$state.set("WHERE", [
2638
- ...wheres,
2639
- [
2640
- wheres.length ? `${this.$constants("AND")}` : "",
2641
- `${this.bindColumn(column)} = ${this.$utils.escape(userId)}`,
2642
- ]
2643
- .join(" ")
2644
- .replace(/^\s+/, ""),
2978
+ ...this.$state.get("WHERE"),
2979
+ {
2980
+ column: this.bindColumn(String(column)),
2981
+ operator: '=',
2982
+ value: formatedValue
2983
+ }
2645
2984
  ]);
2646
2985
  return this;
2647
2986
  }
@@ -2654,14 +2993,11 @@ class Model extends AbstractModel_1.AbstractModel {
2654
2993
  if (sql instanceof Model && !sql.$state.get("SELECT").length) {
2655
2994
  sql.select1();
2656
2995
  }
2657
- const wheres = this.$state.get("WHERE");
2658
2996
  this.$state.set("WHERE", [
2659
- ...wheres,
2660
- [
2661
- wheres.length ? `${this.$constants("AND")}` : "",
2662
- `${this.$constants("EXISTS")}`,
2663
- `(${sql})`,
2664
- ].join(" "),
2997
+ ...this.$state.get("WHERE"),
2998
+ {
2999
+ value: `${this.$constants("EXISTS")} (${sql})`
3000
+ }
2665
3001
  ]);
2666
3002
  return this;
2667
3003
  }
@@ -2674,29 +3010,32 @@ class Model extends AbstractModel_1.AbstractModel {
2674
3010
  whereIn(column, array) {
2675
3011
  if (!Array.isArray(array))
2676
3012
  array = [array];
2677
- const values = array.length
2678
- ? `${array
2679
- .map((value) => this.$utils.transfromValueHasRaw(this.$utils.escape(value)))
2680
- .join(",")}`
2681
- : this.$constants(this.$constants("NULL"));
3013
+ if (!array.length) {
3014
+ array = [DB_1.DB.raw(this.$constants("NULL"))];
3015
+ }
2682
3016
  const blueprint = this._getBlueprintByColumn(String(column));
2683
3017
  if (blueprint?.isVirtual) {
3018
+ const values = array.length ? `${array
3019
+ .map((value) => {
3020
+ return this.$utils.formatQueryValue(value);
3021
+ })
3022
+ .join(",")}`
3023
+ : this.$constants(this.$constants("NULL"));
2684
3024
  const sql = blueprint.sql?.where;
2685
3025
  if (sql) {
2686
3026
  return this.whereRaw(`${sql} ${this.$constants("IN")} (${values})`);
2687
3027
  }
2688
3028
  }
2689
- const wheres = this.$state.get("WHERE");
2690
3029
  this.$state.set("WHERE", [
2691
- ...wheres,
2692
- [
2693
- wheres.length ? `${this.$constants("AND")}` : "",
2694
- `${this.bindColumn(String(column))}`,
2695
- `${this.$constants("IN")}`,
2696
- `(${values})`,
2697
- ]
2698
- .join(" ")
2699
- .replace(/^\s+/, ""),
3030
+ ...this.$state.get("WHERE"),
3031
+ {
3032
+ column: this.bindColumn(String(column)),
3033
+ operator: `${this.$constants("IN")}`,
3034
+ value: array
3035
+ .map((value) => {
3036
+ return this.$utils.formatQueryValue(value);
3037
+ })
3038
+ }
2700
3039
  ]);
2701
3040
  return this;
2702
3041
  }
@@ -2709,22 +3048,33 @@ class Model extends AbstractModel_1.AbstractModel {
2709
3048
  orWhereIn(column, array) {
2710
3049
  if (!Array.isArray(array))
2711
3050
  array = [array];
2712
- const values = array.length
2713
- ? `${array
2714
- .map((value) => this.$utils.transfromValueHasRaw(this.$utils.escape(value)))
3051
+ if (!array.length) {
3052
+ array = [DB_1.DB.raw(this.$constants("NULL"))];
3053
+ }
3054
+ const blueprint = this._getBlueprintByColumn(String(column));
3055
+ if (blueprint?.isVirtual) {
3056
+ const values = array.length ? `${array
3057
+ .map((value) => {
3058
+ return this.$utils.formatQueryValue(value);
3059
+ })
2715
3060
  .join(",")}`
2716
- : this.$constants(this.$constants("NULL"));
2717
- const wheres = this.$state.get("WHERE");
3061
+ : this.$constants(this.$constants("NULL"));
3062
+ const sql = blueprint.sql?.where;
3063
+ if (sql) {
3064
+ return this.orWhereRaw(`${sql} ${this.$constants("IN")} (${values})`);
3065
+ }
3066
+ }
2718
3067
  this.$state.set("WHERE", [
2719
- ...wheres,
2720
- [
2721
- wheres.length ? `${this.$constants("OR")}` : "",
2722
- `${this.bindColumn(String(column))}`,
2723
- `${this.$constants("IN")}`,
2724
- `(${values})`,
2725
- ]
2726
- .join(" ")
2727
- .replace(/^\s+/, ""),
3068
+ ...this.$state.get("WHERE"),
3069
+ {
3070
+ column: this.bindColumn(String(column)),
3071
+ condition: 'OR',
3072
+ operator: `${this.$constants("IN")}`,
3073
+ value: array
3074
+ .map((value) => {
3075
+ return this.$utils.formatQueryValue(value);
3076
+ })
3077
+ }
2728
3078
  ]);
2729
3079
  return this;
2730
3080
  }
@@ -2737,22 +3087,32 @@ class Model extends AbstractModel_1.AbstractModel {
2737
3087
  whereNotIn(column, array) {
2738
3088
  if (!Array.isArray(array))
2739
3089
  array = [array];
2740
- if (!array.length)
2741
- return this;
2742
- const values = `${array
2743
- .map((value) => this.$utils.transfromValueHasRaw(this.$utils.escape(value)))
2744
- .join(",")}`;
2745
- const wheres = this.$state.get("WHERE");
3090
+ if (!array.length) {
3091
+ array = [DB_1.DB.raw(this.$constants("NULL"))];
3092
+ }
3093
+ const blueprint = this._getBlueprintByColumn(String(column));
3094
+ if (blueprint?.isVirtual) {
3095
+ const values = array.length ? `${array
3096
+ .map((value) => {
3097
+ return this.$utils.formatQueryValue(value);
3098
+ })
3099
+ .join(",")}`
3100
+ : this.$constants(this.$constants("NULL"));
3101
+ const sql = blueprint.sql?.where;
3102
+ if (sql) {
3103
+ return this.whereRaw(`${sql} ${this.$constants("NOT_IN")} (${values})`);
3104
+ }
3105
+ }
2746
3106
  this.$state.set("WHERE", [
2747
- ...wheres,
2748
- [
2749
- wheres.length ? `${this.$constants("AND")}` : "",
2750
- `${this.bindColumn(String(column))}`,
2751
- `${this.$constants("NOT_IN")}`,
2752
- `(${values})`,
2753
- ]
2754
- .join(" ")
2755
- .replace(/^\s+/, ""),
3107
+ ...this.$state.get("WHERE"),
3108
+ {
3109
+ column: this.bindColumn(String(column)),
3110
+ operator: `${this.$constants("NOT_IN")}`,
3111
+ value: array
3112
+ .map((value) => {
3113
+ return this.$utils.formatQueryValue(value);
3114
+ })
3115
+ }
2756
3116
  ]);
2757
3117
  return this;
2758
3118
  }
@@ -2765,22 +3125,33 @@ class Model extends AbstractModel_1.AbstractModel {
2765
3125
  orWhereNotIn(column, array) {
2766
3126
  if (!Array.isArray(array))
2767
3127
  array = [array];
2768
- if (!array.length)
2769
- return this;
2770
- const values = `${array
2771
- .map((value) => this.$utils.transfromValueHasRaw(this.$utils.escape(value)))
2772
- .join(",")}`;
2773
- const wheres = this.$state.get("WHERE");
3128
+ if (!array.length) {
3129
+ array = [DB_1.DB.raw(this.$constants("NULL"))];
3130
+ }
3131
+ const blueprint = this._getBlueprintByColumn(String(column));
3132
+ if (blueprint?.isVirtual) {
3133
+ const values = array.length ? `${array
3134
+ .map((value) => {
3135
+ return this.$utils.formatQueryValue(value);
3136
+ })
3137
+ .join(",")}`
3138
+ : this.$constants(this.$constants("NULL"));
3139
+ const sql = blueprint.sql?.where;
3140
+ if (sql) {
3141
+ return this.orWhereRaw(`${sql} ${this.$constants("NOT_IN")} (${values})`);
3142
+ }
3143
+ }
2774
3144
  this.$state.set("WHERE", [
2775
- ...wheres,
2776
- [
2777
- wheres.length ? `${this.$constants("OR")}` : "",
2778
- `${this.bindColumn(String(column))}`,
2779
- `${this.$constants("NOT_IN")}`,
2780
- `(${values})`,
2781
- ]
2782
- .join(" ")
2783
- .replace(/^\s+/, ""),
3145
+ ...this.$state.get("WHERE"),
3146
+ {
3147
+ column: this.bindColumn(String(column)),
3148
+ operator: `${this.$constants("NOT_IN")}`,
3149
+ condition: 'OR',
3150
+ value: array
3151
+ .map((value) => {
3152
+ return this.$utils.formatQueryValue(value);
3153
+ })
3154
+ }
2784
3155
  ]);
2785
3156
  return this;
2786
3157
  }
@@ -2794,17 +3165,13 @@ class Model extends AbstractModel_1.AbstractModel {
2794
3165
  if (subQuery instanceof Model && !subQuery.$state.get("SELECT").length) {
2795
3166
  subQuery.select("id");
2796
3167
  }
2797
- const wheres = this.$state.get("WHERE");
2798
3168
  this.$state.set("WHERE", [
2799
- ...wheres,
2800
- [
2801
- wheres.length ? `${this.$constants("AND")}` : "",
2802
- `${this.bindColumn(String(column))}`,
2803
- options.operator,
2804
- `(${subQuery})`,
2805
- ]
2806
- .join(" ")
2807
- .replace(/^\s+/, ""),
3169
+ ...this.$state.get("WHERE"),
3170
+ {
3171
+ column: this.bindColumn(String(column)),
3172
+ operator: options.operator,
3173
+ value: `(${subQuery})`
3174
+ }
2808
3175
  ]);
2809
3176
  return this;
2810
3177
  }
@@ -2818,17 +3185,13 @@ class Model extends AbstractModel_1.AbstractModel {
2818
3185
  if (subQuery instanceof Model && !subQuery.$state.get("SELECT").length) {
2819
3186
  subQuery.select("id");
2820
3187
  }
2821
- const wheres = this.$state.get("WHERE");
2822
3188
  this.$state.set("WHERE", [
2823
- ...wheres,
2824
- [
2825
- wheres.length ? `${this.$constants("AND")}` : "",
2826
- `${this.bindColumn(String(column))}`,
2827
- options.operator,
2828
- `(${subQuery})`,
2829
- ]
2830
- .join(" ")
2831
- .replace(/^\s+/, ""),
3189
+ ...this.$state.get("WHERE"),
3190
+ {
3191
+ column: this.bindColumn(String(column)),
3192
+ operator: options.operator,
3193
+ value: `(${subQuery})`
3194
+ }
2832
3195
  ]);
2833
3196
  return this;
2834
3197
  }
@@ -2842,17 +3205,14 @@ class Model extends AbstractModel_1.AbstractModel {
2842
3205
  if (subQuery instanceof Model && !subQuery.$state.get("SELECT").length) {
2843
3206
  subQuery.select("id");
2844
3207
  }
2845
- const wheres = this.$state.get("WHERE");
2846
3208
  this.$state.set("WHERE", [
2847
- ...wheres,
2848
- [
2849
- wheres.length ? `${this.$constants("OR")}` : "",
2850
- `${this.bindColumn(String(column))}`,
2851
- options.operator,
2852
- `(${subQuery})`,
2853
- ]
2854
- .join(" ")
2855
- .replace(/^\s+/, ""),
3209
+ ...this.$state.get("WHERE"),
3210
+ {
3211
+ column: this.bindColumn(String(column)),
3212
+ operator: options.operator,
3213
+ condition: 'OR',
3214
+ value: `(${subQuery})`
3215
+ }
2856
3216
  ]);
2857
3217
  return this;
2858
3218
  }
@@ -2866,17 +3226,14 @@ class Model extends AbstractModel_1.AbstractModel {
2866
3226
  if (subQuery instanceof Model && !subQuery.$state.get("SELECT").length) {
2867
3227
  subQuery.select("id");
2868
3228
  }
2869
- const wheres = this.$state.get("WHERE");
2870
3229
  this.$state.set("WHERE", [
2871
- ...wheres,
2872
- [
2873
- wheres.length ? `${this.$constants("OR")}` : "",
2874
- `${this.bindColumn(String(column))}`,
2875
- options.operator,
2876
- `(${subQuery})`,
2877
- ]
2878
- .join(" ")
2879
- .replace(/^\s+/, ""),
3230
+ ...this.$state.get("WHERE"),
3231
+ {
3232
+ column: this.bindColumn(String(column)),
3233
+ operator: options.operator,
3234
+ condition: 'OR',
3235
+ value: `(${subQuery})`
3236
+ }
2880
3237
  ]);
2881
3238
  return this;
2882
3239
  }
@@ -2887,36 +3244,24 @@ class Model extends AbstractModel_1.AbstractModel {
2887
3244
  * @returns {this}
2888
3245
  */
2889
3246
  whereBetween(column, array) {
2890
- const wheres = this.$state.get("WHERE");
2891
3247
  if (!array.length) {
2892
- this.$state.set("WHERE", [
2893
- ...wheres,
2894
- [
2895
- wheres.length ? `${this.$constants("AND")}` : "",
2896
- `${this.bindColumn(String(column))}`,
2897
- `${this.$constants("BETWEEN")}`,
2898
- `${this.$constants(this.$constants("NULL"))}`,
2899
- `${this.$constants("AND")}`,
2900
- `${this.$constants(this.$constants("NULL"))}`,
2901
- ]
2902
- .join(" ")
2903
- .replace(/^\s+/, ""),
3248
+ return this.whereBetween(column, [
3249
+ DB_1.DB.raw(this.$constants("NULL")),
3250
+ DB_1.DB.raw(this.$constants("NULL"))
2904
3251
  ]);
2905
- return this;
2906
3252
  }
2907
- const [value1, value2] = array;
3253
+ let [value1, value2] = array;
2908
3254
  this.$state.set("WHERE", [
2909
- ...wheres,
2910
- [
2911
- wheres.length ? `${this.$constants("AND")}` : "",
2912
- `${this.bindColumn(String(column))}`,
2913
- `${this.$constants("BETWEEN")}`,
2914
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value1))}`,
2915
- `${this.$constants("AND")}`,
2916
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value2))}`,
2917
- ]
2918
- .join(" ")
2919
- .replace(/^\s+/, ""),
3255
+ ...this.$state.get("WHERE"),
3256
+ {
3257
+ column: this.bindColumn(String(column)),
3258
+ operator: `${this.$constants("BETWEEN")}`,
3259
+ value: [
3260
+ `${this.$utils.formatQueryValue(value1)}`,
3261
+ `${this.$constants("AND")}`,
3262
+ `${this.$utils.formatQueryValue(value2)}`,
3263
+ ].join(" ")
3264
+ }
2920
3265
  ]);
2921
3266
  return this;
2922
3267
  }
@@ -2927,36 +3272,22 @@ class Model extends AbstractModel_1.AbstractModel {
2927
3272
  * @returns {this}
2928
3273
  */
2929
3274
  orWhereBetween(column, array) {
2930
- const wheres = this.$state.get("WHERE");
2931
3275
  if (!array.length) {
2932
- this.$state.set("WHERE", [
2933
- ...wheres,
2934
- [
2935
- wheres.length ? `${this.$constants("OR")}` : "",
2936
- `${this.bindColumn(String(column))}`,
2937
- `${this.$constants("BETWEEN")}`,
2938
- `${this.$constants(this.$constants("NULL"))}`,
2939
- `${this.$constants("AND")}`,
2940
- `${this.$constants(this.$constants("NULL"))}`,
2941
- ]
2942
- .join(" ")
2943
- .replace(/^\s+/, ""),
2944
- ]);
2945
- return this;
3276
+ return this.orWhereBetween(column, [DB_1.DB.raw(this.$constants("NULL")), DB_1.DB.raw(this.$constants("NULL"))]);
2946
3277
  }
2947
- const [value1, value2] = array;
3278
+ let [value1, value2] = array;
2948
3279
  this.$state.set("WHERE", [
2949
- ...wheres,
2950
- [
2951
- wheres.length ? `${this.$constants("OR")}` : "",
2952
- `${this.bindColumn(String(column))}`,
2953
- `${this.$constants("BETWEEN")}`,
2954
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value1))}`,
2955
- `${this.$constants("AND")}`,
2956
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value2))}`,
2957
- ]
2958
- .join(" ")
2959
- .replace(/^\s+/, ""),
3280
+ ...this.$state.get("WHERE"),
3281
+ {
3282
+ column: this.bindColumn(String(column)),
3283
+ operator: `${this.$constants("BETWEEN")}`,
3284
+ condition: 'OR',
3285
+ value: [
3286
+ `${this.$utils.formatQueryValue(value1)}`,
3287
+ `${this.$constants("AND")}`,
3288
+ `${this.$utils.formatQueryValue(value2)}`
3289
+ ].join(" ")
3290
+ }
2960
3291
  ]);
2961
3292
  return this;
2962
3293
  }
@@ -2967,36 +3298,24 @@ class Model extends AbstractModel_1.AbstractModel {
2967
3298
  * @returns {this}
2968
3299
  */
2969
3300
  whereNotBetween(column, array) {
2970
- const wheres = this.$state.get("WHERE");
2971
3301
  if (!array.length) {
2972
- this.$state.set("WHERE", [
2973
- ...wheres,
2974
- [
2975
- wheres.length ? `${this.$constants("AND")}` : "",
2976
- `${this.bindColumn(String(column))}`,
2977
- `${this.$constants("NOT_BETWEEN")}`,
2978
- `${this.$constants(this.$constants("NULL"))}`,
2979
- `${this.$constants("AND")}`,
2980
- `${this.$constants(this.$constants("NULL"))}`,
2981
- ]
2982
- .join(" ")
2983
- .replace(/^\s+/, ""),
3302
+ return this.whereNotBetween(column, [
3303
+ DB_1.DB.raw(this.$constants("NULL")),
3304
+ DB_1.DB.raw(this.$constants("NULL"))
2984
3305
  ]);
2985
- return this;
2986
3306
  }
2987
3307
  const [value1, value2] = array;
2988
3308
  this.$state.set("WHERE", [
2989
- ...wheres,
2990
- [
2991
- wheres.length ? `${this.$constants("AND")}` : "",
2992
- `${this.bindColumn(String(column))}`,
2993
- `${this.$constants("NOT_BETWEEN")}`,
2994
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value1))}`,
2995
- `${this.$constants("AND")}`,
2996
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value2))}`,
2997
- ]
2998
- .join(" ")
2999
- .replace(/^\s+/, ""),
3309
+ ...this.$state.get("WHERE"),
3310
+ {
3311
+ column: this.bindColumn(String(column)),
3312
+ operator: `${this.$constants("NOT_BETWEEN")}`,
3313
+ value: [
3314
+ `${this.$utils.formatQueryValue(value1)}`,
3315
+ `${this.$constants("AND")}`,
3316
+ `${this.$utils.formatQueryValue(value2)}`,
3317
+ ].join(" ")
3318
+ }
3000
3319
  ]);
3001
3320
  return this;
3002
3321
  }
@@ -3007,36 +3326,25 @@ class Model extends AbstractModel_1.AbstractModel {
3007
3326
  * @returns {this}
3008
3327
  */
3009
3328
  orWhereNotBetween(column, array) {
3010
- const wheres = this.$state.get("WHERE");
3011
3329
  if (!array.length) {
3012
- this.$state.set("WHERE", [
3013
- ...wheres,
3014
- [
3015
- wheres.length ? `${this.$constants("OR")}` : "",
3016
- `${this.bindColumn(String(column))}`,
3017
- `${this.$constants("NOT_BETWEEN")}`,
3018
- `${this.$constants(this.$constants("NULL"))}`,
3019
- `${this.$constants("AND")}`,
3020
- `${this.$constants(this.$constants("NULL"))}`,
3021
- ]
3022
- .join(" ")
3023
- .replace(/^\s+/, ""),
3330
+ return this.orWhereNotBetween(column, [
3331
+ DB_1.DB.raw(this.$constants("NULL")),
3332
+ DB_1.DB.raw(this.$constants("NULL"))
3024
3333
  ]);
3025
- return this;
3026
3334
  }
3027
3335
  const [value1, value2] = array;
3028
3336
  this.$state.set("WHERE", [
3029
3337
  ...this.$state.get("WHERE"),
3030
- [
3031
- this.$state.get("WHERE").length ? `${this.$constants("OR")}` : "",
3032
- `${this.bindColumn(String(column))}`,
3033
- `${this.$constants("NOT_BETWEEN")}`,
3034
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value1))}`,
3035
- `${this.$constants("AND")}`,
3036
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value2))}`,
3037
- ]
3038
- .join(" ")
3039
- .replace(/^\s+/, ""),
3338
+ {
3339
+ column: this.bindColumn(String(column)),
3340
+ operator: `${this.$constants("NOT_BETWEEN")}`,
3341
+ condition: 'OR',
3342
+ value: [
3343
+ `${this.$utils.formatQueryValue(value1)}`,
3344
+ `${this.$constants("AND")}`,
3345
+ `${this.$utils.formatQueryValue(value2)}`,
3346
+ ].join(" ")
3347
+ }
3040
3348
  ]);
3041
3349
  return this;
3042
3350
  }
@@ -3046,16 +3354,12 @@ class Model extends AbstractModel_1.AbstractModel {
3046
3354
  * @returns {this}
3047
3355
  */
3048
3356
  whereNull(column) {
3049
- const wheres = this.$state.get("WHERE");
3050
3357
  this.$state.set("WHERE", [
3051
- ...wheres,
3052
- [
3053
- wheres.length ? `${this.$constants("AND")}` : "",
3054
- `${this.bindColumn(String(column))}`,
3055
- `${this.$constants("IS_NULL")}`,
3056
- ]
3057
- .join(" ")
3058
- .replace(/^\s+/, ""),
3358
+ ...this.$state.get("WHERE"),
3359
+ {
3360
+ column: this.bindColumn(String(column)),
3361
+ operator: `${this.$constants("IS_NULL")}`,
3362
+ }
3059
3363
  ]);
3060
3364
  return this;
3061
3365
  }
@@ -3065,16 +3369,13 @@ class Model extends AbstractModel_1.AbstractModel {
3065
3369
  * @returns {this}
3066
3370
  */
3067
3371
  orWhereNull(column) {
3068
- const wheres = this.$state.get("WHERE");
3069
3372
  this.$state.set("WHERE", [
3070
- ...wheres,
3071
- [
3072
- wheres.length ? `${this.$constants("OR")}` : "",
3073
- `${this.bindColumn(String(column))}`,
3074
- `${this.$constants("IS_NULL")}`,
3075
- ]
3076
- .join(" ")
3077
- .replace(/^\s+/, ""),
3373
+ ...this.$state.get("WHERE"),
3374
+ {
3375
+ column: this.bindColumn(String(column)),
3376
+ operator: `${this.$constants("IS_NULL")}`,
3377
+ condition: 'OR'
3378
+ }
3078
3379
  ]);
3079
3380
  return this;
3080
3381
  }
@@ -3084,16 +3385,12 @@ class Model extends AbstractModel_1.AbstractModel {
3084
3385
  * @returns {this}
3085
3386
  */
3086
3387
  whereNotNull(column) {
3087
- const wheres = this.$state.get("WHERE");
3088
3388
  this.$state.set("WHERE", [
3089
- ...wheres,
3090
- [
3091
- wheres.length ? `${this.$constants("AND")}` : "",
3092
- `${this.bindColumn(String(column))}`,
3093
- `${this.$constants("IS_NOT_NULL")}`,
3094
- ]
3095
- .join(" ")
3096
- .replace(/^\s+/, ""),
3389
+ ...this.$state.get("WHERE"),
3390
+ {
3391
+ column: this.bindColumn(String(column)),
3392
+ operator: `${this.$constants("IS_NOT_NULL")}`,
3393
+ }
3097
3394
  ]);
3098
3395
  return this;
3099
3396
  }
@@ -3103,16 +3400,13 @@ class Model extends AbstractModel_1.AbstractModel {
3103
3400
  * @returns {this}
3104
3401
  */
3105
3402
  orWhereNotNull(column) {
3106
- const wheres = this.$state.get("WHERE");
3107
3403
  this.$state.set("WHERE", [
3108
- ...wheres,
3109
- [
3110
- wheres.length ? `${this.$constants("OR")}` : "",
3111
- `${this.bindColumn(String(column))}`,
3112
- `${this.$constants("IS_NOT_NULL")}`,
3113
- ]
3114
- .join(" ")
3115
- .replace(/^\s+/, ""),
3404
+ ...this.$state.get("WHERE"),
3405
+ {
3406
+ column: this.bindColumn(String(column)),
3407
+ operator: `${this.$constants("IS_NOT_NULL")}`,
3408
+ condition: 'OR'
3409
+ }
3116
3410
  ]);
3117
3411
  return this;
3118
3412
  }
@@ -3125,20 +3419,13 @@ class Model extends AbstractModel_1.AbstractModel {
3125
3419
  */
3126
3420
  whereSensitive(column, operator, value) {
3127
3421
  [value, operator] = this.$utils.valueAndOperator(value, operator, arguments.length === 2);
3128
- value = this.$utils.escape(value);
3129
- value = this.$utils.transfromBooleanToNumber(value);
3130
- const wheres = this.$state.get("WHERE");
3131
3422
  this.$state.set("WHERE", [
3132
- ...wheres,
3133
- [
3134
- wheres.length ? `${this.$constants("AND")}` : "",
3135
- `${this.$constants("BINARY")}`,
3136
- `${this.bindColumn(String(column))}`,
3137
- `${operator}`,
3138
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value))}`,
3139
- ]
3140
- .join(" ")
3141
- .replace(/^\s+/, ""),
3423
+ ...this.$state.get("WHERE"),
3424
+ {
3425
+ column: `${this.$constants("BINARY")} ${this.bindColumn(String(column))}`,
3426
+ operator,
3427
+ value: `${this.$utils.formatQueryValue(value)}`
3428
+ }
3142
3429
  ]);
3143
3430
  return this;
3144
3431
  }
@@ -3151,20 +3438,13 @@ class Model extends AbstractModel_1.AbstractModel {
3151
3438
  */
3152
3439
  whereStrict(column, operator, value) {
3153
3440
  [value, operator] = this.$utils.valueAndOperator(value, operator, arguments.length === 2);
3154
- value = this.$utils.escape(value);
3155
- value = this.$utils.transfromBooleanToNumber(value);
3156
- const wheres = this.$state.get("WHERE");
3157
3441
  this.$state.set("WHERE", [
3158
- ...wheres,
3159
- [
3160
- wheres.length ? `${this.$constants("AND")}` : "",
3161
- `${this.$constants("BINARY")}`,
3162
- `${this.bindColumn(String(column))}`,
3163
- `${operator}`,
3164
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value))}`,
3165
- ]
3166
- .join(" ")
3167
- .replace(/^\s+/, ""),
3442
+ ...this.$state.get("WHERE"),
3443
+ {
3444
+ column: `${this.$constants("BINARY")} ${this.bindColumn(String(column))}`,
3445
+ operator,
3446
+ value: `${this.$utils.formatQueryValue(value)}`,
3447
+ }
3168
3448
  ]);
3169
3449
  return this;
3170
3450
  }
@@ -3177,20 +3457,14 @@ class Model extends AbstractModel_1.AbstractModel {
3177
3457
  */
3178
3458
  orWhereSensitive(column, operator, value) {
3179
3459
  [value, operator] = this.$utils.valueAndOperator(value, operator, arguments.length === 2);
3180
- value = this.$utils.escape(value);
3181
- value = this.$utils.transfromBooleanToNumber(value);
3182
- const wheres = this.$state.get("WHERE");
3183
3460
  this.$state.set("WHERE", [
3184
- ...wheres,
3185
- [
3186
- wheres.length ? `${this.$constants("OR")}` : "",
3187
- `${this.$constants("BINARY")}`,
3188
- `${this.bindColumn(String(column))}`,
3189
- `${operator}`,
3190
- `${this.$utils.transfromValueHasRaw(this.$utils.escape(value))}`,
3191
- ]
3192
- .join(" ")
3193
- .replace(/^\s+/, ""),
3461
+ ...this.$state.get("WHERE"),
3462
+ {
3463
+ column: `${this.$constants("BINARY")} ${this.bindColumn(String(column))}`,
3464
+ operator,
3465
+ condition: 'OR',
3466
+ value: `${this.$utils.formatQueryValue(value)}`,
3467
+ }
3194
3468
  ]);
3195
3469
  return this;
3196
3470
  }
@@ -3240,16 +3514,29 @@ class Model extends AbstractModel_1.AbstractModel {
3240
3514
  const where = repository?.$state.get("WHERE") || [];
3241
3515
  if (!where.length)
3242
3516
  return this;
3243
- const query = where.join(" ");
3244
- const wheres = this.$state.get("WHERE");
3245
3517
  this.$state.set("WHERE", [
3246
- ...wheres,
3247
- [
3248
- wheres.length ? `${this.$constants("AND")}` : "",
3249
- `(${query})`,
3250
- ]
3251
- .join(" ")
3252
- .replace(/^\s+/, ""),
3518
+ ...this.$state.get("WHERE"),
3519
+ ...this.$utils.nestConditions(repository?.$state.get("WHERE"))
3520
+ ]);
3521
+ return this;
3522
+ }
3523
+ /**
3524
+ * @override
3525
+ * @param {Function} callback callback query
3526
+ * @returns {this}
3527
+ */
3528
+ orWhereQuery(callback) {
3529
+ const copy = new Model().copyModel(this);
3530
+ const repository = callback(copy);
3531
+ if (repository instanceof Promise) {
3532
+ throw this._assertError('The "orWhereQuery" method is not supported a Promise');
3533
+ }
3534
+ if (!(repository instanceof Model)) {
3535
+ throw this._assertError(`Unknown callback query: '${repository}'`);
3536
+ }
3537
+ this.$state.set("WHERE", [
3538
+ ...this.$state.get("WHERE"),
3539
+ ...this.$utils.nestConditions(repository?.$state.get("WHERE"), 'OR')
3253
3540
  ]);
3254
3541
  return this;
3255
3542
  }
@@ -3262,8 +3549,6 @@ class Model extends AbstractModel_1.AbstractModel {
3262
3549
  */
3263
3550
  whereAny(columns, operator, value) {
3264
3551
  [value, operator] = this.$utils.valueAndOperator(value, operator, arguments.length === 2);
3265
- value = this.$utils.escape(value);
3266
- value = this.$utils.transfromBooleanToNumber(value);
3267
3552
  this.whereQuery((query) => {
3268
3553
  for (const index in columns) {
3269
3554
  const column = String(columns[index]);
@@ -3290,8 +3575,6 @@ class Model extends AbstractModel_1.AbstractModel {
3290
3575
  */
3291
3576
  whereAll(columns, operator, value) {
3292
3577
  [value, operator] = this.$utils.valueAndOperator(value, operator, arguments.length === 2);
3293
- value = this.$utils.escape(value);
3294
- value = this.$utils.transfromBooleanToNumber(value);
3295
3578
  this.whereQuery((query) => {
3296
3579
  for (const key in columns) {
3297
3580
  const column = String(columns[key]);
@@ -3361,8 +3644,10 @@ class Model extends AbstractModel_1.AbstractModel {
3361
3644
  * @returns {this}
3362
3645
  */
3363
3646
  join(localKey, referenceKey) {
3364
- if ((typeof localKey === "function" && typeof localKey === "function") &&
3365
- (this._isModel(localKey) && this._isModel(referenceKey))) {
3647
+ if (typeof localKey === "function" &&
3648
+ typeof localKey === "function" &&
3649
+ this._isModel(localKey) &&
3650
+ this._isModel(referenceKey)) {
3366
3651
  return this.joinModel(localKey, referenceKey);
3367
3652
  }
3368
3653
  this._handleJoin("INNER_JOIN", localKey, referenceKey);
@@ -3376,8 +3661,10 @@ class Model extends AbstractModel_1.AbstractModel {
3376
3661
  * @returns {this}
3377
3662
  */
3378
3663
  rightJoin(localKey, referenceKey) {
3379
- if ((typeof localKey === "function" && typeof localKey === "function") &&
3380
- (this._isModel(localKey) && this._isModel(referenceKey))) {
3664
+ if (typeof localKey === "function" &&
3665
+ typeof localKey === "function" &&
3666
+ this._isModel(localKey) &&
3667
+ this._isModel(referenceKey)) {
3381
3668
  return this.joinModel(localKey, referenceKey);
3382
3669
  }
3383
3670
  this._handleJoin("RIGHT_JOIN", localKey, referenceKey);
@@ -3391,8 +3678,10 @@ class Model extends AbstractModel_1.AbstractModel {
3391
3678
  * @returns {this}
3392
3679
  */
3393
3680
  leftJoin(localKey, referenceKey) {
3394
- if ((typeof localKey === "function" && typeof localKey === "function") &&
3395
- (this._isModel(localKey) && this._isModel(referenceKey))) {
3681
+ if (typeof localKey === "function" &&
3682
+ typeof localKey === "function" &&
3683
+ this._isModel(localKey) &&
3684
+ this._isModel(referenceKey)) {
3396
3685
  return this.joinModel(localKey, referenceKey);
3397
3686
  }
3398
3687
  this._handleJoin("LEFT_JOIN", localKey, referenceKey);
@@ -3405,8 +3694,10 @@ class Model extends AbstractModel_1.AbstractModel {
3405
3694
  * @returns {this}
3406
3695
  */
3407
3696
  crossJoin(localKey, referenceKey) {
3408
- if ((typeof localKey === "function" && typeof localKey === "function") &&
3409
- (this._isModel(localKey) && this._isModel(referenceKey))) {
3697
+ if (typeof localKey === "function" &&
3698
+ typeof localKey === "function" &&
3699
+ this._isModel(localKey) &&
3700
+ this._isModel(referenceKey)) {
3410
3701
  return this.joinModel(localKey, referenceKey);
3411
3702
  }
3412
3703
  this._handleJoin("CROSS_JOIN", localKey, referenceKey);
@@ -3562,6 +3853,103 @@ class Model extends AbstractModel_1.AbstractModel {
3562
3853
  }
3563
3854
  return this;
3564
3855
  }
3856
+ /**
3857
+ *
3858
+ * @override
3859
+ * @param {string=} column [column=id]
3860
+ * @returns {promise<number>}
3861
+ */
3862
+ async count(c) {
3863
+ await this._prepareQueryPipeline();
3864
+ const distinct = this.$state.get("DISTINCT");
3865
+ let column = c == null ? this.$state.get('PRIMARY_KEY') : String(c);
3866
+ column === "*"
3867
+ ? "*"
3868
+ : distinct
3869
+ ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3870
+ : `${this.bindColumn(column)}`;
3871
+ this.selectRaw([
3872
+ `${this.$constants("COUNT")}(${column})`,
3873
+ `${this.$constants("AS")}`,
3874
+ "\`aggregate\`",
3875
+ ].join(" "));
3876
+ const sql = this._queryBuilder().select();
3877
+ const result = await this._queryStatement(sql);
3878
+ return Number(this._resultHandler(result.reduce((prev, cur) => prev + Number(cur?.aggregate ?? 0), 0) || 0));
3879
+ }
3880
+ /**
3881
+ *
3882
+ * @override
3883
+ * @param {string=} column [column=id]
3884
+ * @returns {promise<number>}
3885
+ */
3886
+ async avg(c) {
3887
+ await this._prepareQueryPipeline();
3888
+ const distinct = this.$state.get("DISTINCT");
3889
+ let column = c == null ? this.$state.get('PRIMARY_KEY') : String(c);
3890
+ column = distinct
3891
+ ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3892
+ : `${this.bindColumn(column)}`;
3893
+ this.selectRaw(`${this.$constants("AVG")}(${column}) ${this.$constants("AS")} \`aggregate\``);
3894
+ const sql = this._queryBuilder().select();
3895
+ const result = await this._queryStatement(sql);
3896
+ return Number(this._resultHandler((result.reduce((prev, cur) => prev + Number(cur?.aggregate ?? 0), 0) ||
3897
+ 0) / result.length));
3898
+ }
3899
+ /**
3900
+ *
3901
+ * @override
3902
+ * @param {string=} column [column=id]
3903
+ * @returns {promise<number>}
3904
+ */
3905
+ async sum(c) {
3906
+ await this._prepareQueryPipeline();
3907
+ let column = c == null ? this.$state.get('PRIMARY_KEY') : String(c);
3908
+ const distinct = this.$state.get("DISTINCT");
3909
+ column = distinct
3910
+ ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3911
+ : `${this.bindColumn(column)}`;
3912
+ this.selectRaw(`${this.$constants("SUM")}(${column}) ${this.$constants("AS")} \`aggregate\``);
3913
+ const sql = this._queryBuilder().select();
3914
+ const result = await this._queryStatement(sql);
3915
+ return Number(this._resultHandler(result.reduce((prev, cur) => prev + Number(cur?.aggregate ?? 0), 0) ||
3916
+ 0));
3917
+ }
3918
+ /**
3919
+ *
3920
+ * @override
3921
+ * @param {string=} column [column=id]
3922
+ * @returns {promise<number>}
3923
+ */
3924
+ async max(c) {
3925
+ await this._prepareQueryPipeline();
3926
+ const distinct = this.$state.get("DISTINCT");
3927
+ let column = c == null ? this.$state.get('PRIMARY_KEY') : String(c);
3928
+ column = distinct
3929
+ ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3930
+ : `${this.bindColumn(column)}`;
3931
+ this.selectRaw(`${this.$constants("MAX")}(${column}) ${this.$constants("AS")} \`aggregate\``);
3932
+ const sql = this._queryBuilder().select();
3933
+ const result = await this._queryStatement(sql);
3934
+ return Number(this._resultHandler(result.sort((a, b) => b?.aggregate - a?.aggregate)[0]?.aggregate || 0));
3935
+ }
3936
+ /**
3937
+ * @override
3938
+ * @param {string} c
3939
+ * @returns {promise<number>}
3940
+ */
3941
+ async min(c) {
3942
+ await this._prepareQueryPipeline();
3943
+ const distinct = this.$state.get("DISTINCT");
3944
+ let column = c == null ? "id" : String(c);
3945
+ column = distinct
3946
+ ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3947
+ : `${this.bindColumn(column)}`;
3948
+ this.selectRaw(`${this.$constants("MIN")}(${column}) ${this.$constants("AS")} \`aggregate\``);
3949
+ const sql = this._queryBuilder().select();
3950
+ const result = await this._queryStatement(sql);
3951
+ return Number(this._resultHandler(result.sort((a, b) => a?.aggregate - b?.aggregate)[0]?.aggregate || 0));
3952
+ }
3565
3953
  /**
3566
3954
  * @override
3567
3955
  * @returns {promise<boolean>} promise boolean
@@ -3572,36 +3960,27 @@ class Model extends AbstractModel_1.AbstractModel {
3572
3960
  if (this.$state.get("SOFT_DELETE")) {
3573
3961
  const deletedAt = this._valuePattern(this.$state.get("SOFT_DELETE_FORMAT"));
3574
3962
  await this._runBefore("update");
3575
- const result = await new Model()
3963
+ const sql = new Model()
3576
3964
  .copyModel(this, { where: true, limit: true, orderBy: true })
3577
3965
  .update({
3578
3966
  [deletedAt]: this.$utils.timestamp(),
3579
3967
  })
3580
- .disableSoftDelete()
3581
3968
  .bind(this.$pool.get())
3582
3969
  .debug(this.$state.get("DEBUG"))
3583
- .save();
3970
+ .toString();
3971
+ const r = await this._actionStatement(sql);
3972
+ const result = Boolean(this._resultHandler(r?.$meta?.affected || false));
3584
3973
  await this._observer(result, "updated");
3585
3974
  await this._runAfter("update", result);
3586
3975
  return Boolean(this._resultHandler(result));
3587
3976
  }
3588
- const PK = this.$state.get("PRIMARY_KEY");
3589
- const TEMP = "TEMP";
3590
- const from = new Model()
3591
- .copyModel(this, { where: true, limit: true, orderBy: true })
3592
- .selectRaw(PK);
3593
- this
3594
- .unset({ where: true, limit: true })
3595
- .select(PK)
3596
- .whereSubQuery(PK, new Model().from(DB_1.DB.raw(`
3597
- (${from}) ${this.$constants("AS")} ${TEMP}`)).selectRaw(PK));
3598
3977
  this.$state.set("DELETE", true);
3599
3978
  await this._runBefore("remove");
3600
- const result = await this._actionStatement(this._queryBuilder().remove());
3601
- const r = Boolean(this._resultHandler(result?.$meta?.affected || false));
3602
- await this._observer(r, "deleted");
3603
- await this._runAfter("remove", r);
3604
- return r;
3979
+ const r = await this._actionStatement(this._queryBuilder().remove());
3980
+ const result = Boolean(this._resultHandler(r?.$meta?.affected || false));
3981
+ await this._observer(result, "deleted");
3982
+ await this._runAfter("remove", result);
3983
+ return result;
3605
3984
  }
3606
3985
  /**
3607
3986
  * @override
@@ -3612,36 +3991,27 @@ class Model extends AbstractModel_1.AbstractModel {
3612
3991
  if (this.$state.get("SOFT_DELETE")) {
3613
3992
  const deletedAt = this._valuePattern(this.$state.get("SOFT_DELETE_FORMAT"));
3614
3993
  await this._runBefore("update");
3615
- const result = await new Model()
3616
- .copyModel(this, { where: true, limit: true })
3994
+ const sql = new Model()
3995
+ .copyModel(this, { where: true, orderBy: true })
3617
3996
  .updateMany({
3618
3997
  [deletedAt]: this.$utils.timestamp(),
3619
3998
  })
3620
- .disableSoftDelete()
3621
- .debug(this.$state.get("DEBUG"))
3622
3999
  .bind(this.$pool.get())
3623
- .save();
4000
+ .debug(this.$state.get("DEBUG"))
4001
+ .toString();
4002
+ const r = await this._actionStatement(sql);
4003
+ const result = Boolean(this._resultHandler(r?.$meta?.affected || false));
3624
4004
  await this._observer(result, "updated");
3625
4005
  await this._runAfter("update", result);
3626
4006
  return Boolean(this._resultHandler(result));
3627
4007
  }
3628
- const PK = this.$state.get("PRIMARY_KEY");
3629
- const TEMP = "TEMP";
3630
- const from = new Model()
3631
- .copyModel(this, { where: true, limit: true, orderBy: true })
3632
- .selectRaw(PK);
3633
- this
3634
- .unset({ where: true, limit: true })
3635
- .select(PK)
3636
- .whereSubQuery(PK, new Model().from(DB_1.DB.raw(`
3637
- (${from}) ${this.$constants("AS")} ${TEMP}`)).selectRaw(PK));
3638
4008
  this.$state.set("DELETE", true);
3639
4009
  await this._runBefore("remove");
3640
- const result = await this._actionStatement(this._queryBuilder().remove());
3641
- const r = Boolean(this._resultHandler(result?.$meta?.affected || false));
3642
- await this._observer(r, "deleted");
3643
- await this._runAfter("remove", r);
3644
- return r;
4010
+ const r = await this._actionStatement(this._queryBuilder().remove());
4011
+ const result = Boolean(this._resultHandler(r?.$meta?.affected || false));
4012
+ await this._observer(result, "deleted");
4013
+ await this._runAfter("remove", result);
4014
+ return result;
3645
4015
  }
3646
4016
  /**
3647
4017
  *
@@ -3654,16 +4024,18 @@ class Model extends AbstractModel_1.AbstractModel {
3654
4024
  */
3655
4025
  async forceDelete() {
3656
4026
  this.disableSoftDelete();
3657
- const PK = this.$state.get('PRIMARY_KEY');
3658
- const TEMP = 'TEMP';
4027
+ const PK = this.$state.get("PRIMARY_KEY");
4028
+ const TEMP = "TEMP";
3659
4029
  const from = new Model()
3660
4030
  .copyModel(this, { where: true, limit: true, orderBy: true })
3661
4031
  .selectRaw(PK);
3662
- this
3663
- .unset({ where: true, limit: true })
4032
+ this.unset({ where: true, limit: true })
3664
4033
  .select(PK)
3665
- .whereSubQuery(PK, new Model().from(DB_1.DB.raw(`
3666
- (${from}) AS ${TEMP}`)).selectRaw(PK).toString());
4034
+ .whereSubQuery(PK, new Model()
4035
+ .from(DB_1.DB.raw(`
4036
+ (${from}) AS ${TEMP}`))
4037
+ .selectRaw(PK)
4038
+ .toString());
3667
4039
  this.$state.set("DELETE", true);
3668
4040
  const result = await this._actionStatement(this._queryBuilder().remove());
3669
4041
  const r = Boolean(this._resultHandler(result?.$meta?.affected || false));
@@ -3745,6 +4117,7 @@ class Model extends AbstractModel_1.AbstractModel {
3745
4117
  return this._resultHandler(undefined);
3746
4118
  await this._prepareQueryPipeline();
3747
4119
  this.limit(1);
4120
+ this._ensureRelationOwnerKeysSelected();
3748
4121
  let sql = this._queryBuilder().select();
3749
4122
  if (this.$state.get("RELATIONS_EXISTS"))
3750
4123
  sql = String(this.$relation.loadExists());
@@ -3768,6 +4141,15 @@ class Model extends AbstractModel_1.AbstractModel {
3768
4141
  async findOne(cb) {
3769
4142
  return await this.first(cb);
3770
4143
  }
4144
+ /**
4145
+ * @override
4146
+ * @param {number} id callback function return query sql
4147
+ * @returns {promise<Record<string,any> | null>} Record | null
4148
+ */
4149
+ async find(primaryKey) {
4150
+ this.where(this.$state.get("PRIMARY_KEY"), primaryKey);
4151
+ return await this.first();
4152
+ }
3771
4153
  /**
3772
4154
  * @override
3773
4155
  * @returns {promise<object | Error>} Record | throw error
@@ -3777,6 +4159,7 @@ class Model extends AbstractModel_1.AbstractModel {
3777
4159
  return this._resultHandler(undefined);
3778
4160
  await this._prepareQueryPipeline();
3779
4161
  this.limit(1);
4162
+ this._ensureRelationOwnerKeysSelected();
3780
4163
  let sql = this._queryBuilder().select();
3781
4164
  if (this.$state.get("RELATIONS_EXISTS"))
3782
4165
  sql = String(this.$relation.loadExists());
@@ -3805,6 +4188,7 @@ class Model extends AbstractModel_1.AbstractModel {
3805
4188
  if (this.$state.get("VOID"))
3806
4189
  return [];
3807
4190
  await this._prepareQueryPipeline();
4191
+ this._ensureRelationOwnerKeysSelected();
3808
4192
  let sql = this._queryBuilder().select();
3809
4193
  if (this.$state.get("RELATIONS_EXISTS"))
3810
4194
  sql = String(this.$relation.loadExists());
@@ -3848,6 +4232,7 @@ class Model extends AbstractModel_1.AbstractModel {
3848
4232
  this.$state.set("PAGE", page);
3849
4233
  this.limit(limit);
3850
4234
  this.offset(offset);
4235
+ this._ensureRelationOwnerKeysSelected();
3851
4236
  let sql = this._queryBuilder().select();
3852
4237
  if (this.$state.get("RELATIONS_EXISTS"))
3853
4238
  sql = String(this.$relation.loadExists());
@@ -3943,8 +4328,8 @@ class Model extends AbstractModel_1.AbstractModel {
3943
4328
  if (!Object.keys(data).length) {
3944
4329
  throw this._assertError("This method must require at least 1 argument.");
3945
4330
  }
3946
- this.$state.set("DATA", data);
3947
- if (this.$state.get('TRANSFORMS') == null) {
4331
+ this.$state.set("DATA", this._formatedInputData(data));
4332
+ if (this.$state.get("TRANSFORMS") == null) {
3948
4333
  this._queryInsertModel();
3949
4334
  }
3950
4335
  this.$state.set("SAVE", "INSERT");
@@ -3956,7 +4341,6 @@ class Model extends AbstractModel_1.AbstractModel {
3956
4341
  * @returns {this} this
3957
4342
  */
3958
4343
  create(data) {
3959
- //@ts-ignore
3960
4344
  return this.insert(data);
3961
4345
  }
3962
4346
  /**
@@ -3984,9 +4368,9 @@ class Model extends AbstractModel_1.AbstractModel {
3984
4368
  }
3985
4369
  }
3986
4370
  }
3987
- this.$state.set("DATA", data);
4371
+ this.$state.set("DATA", this._formatedInputData(data));
3988
4372
  this.limit(1);
3989
- if (this.$state.get('TRANSFORMS') == null) {
4373
+ if (this.$state.get("TRANSFORMS") == null) {
3990
4374
  this._queryUpdateModel();
3991
4375
  }
3992
4376
  this.$state.set("SAVE", "UPDATE");
@@ -4017,25 +4401,25 @@ class Model extends AbstractModel_1.AbstractModel {
4017
4401
  }
4018
4402
  }
4019
4403
  }
4020
- this.$state.set("DATA", data);
4021
- if (this.$state.get('TRANSFORMS') == null) {
4404
+ this.$state.set("DATA", this._formatedInputData(data));
4405
+ if (this.$state.get("TRANSFORMS") == null) {
4022
4406
  this._queryUpdateModel();
4023
4407
  }
4024
4408
  this.$state.set("SAVE", "UPDATE");
4025
4409
  return this;
4026
4410
  }
4027
4411
  /**
4028
- *
4029
- * @override
4030
- * @param {Array<{when: Record<string, string | number | boolean | null | undefined>, columns: Record<string, string | number | boolean | null | undefined>}>>} cases
4031
- * An array of update cases.
4032
- * - `when` is an object specifying the conditions to match records.
4033
- * - `columns` is an object specifying the new values to set for the matched records.
4034
- *
4035
- * @property {Record<string,string | number | boolean | null | undefined>} cases.when
4036
- * @property {Record<string,string | number | boolean | null | undefined>} cases.columns
4037
- * @returns {this} this
4038
- */
4412
+ *
4413
+ * @override
4414
+ * @param {Array<{when: Record<string, string | number | boolean | null | undefined>, columns: Record<string, string | number | boolean | null | undefined>}>>} cases
4415
+ * An array of update cases.
4416
+ * - `when` is an object specifying the conditions to match records.
4417
+ * - `columns` is an object specifying the new values to set for the matched records.
4418
+ *
4419
+ * @property {Record<string,string | number | boolean | null | undefined>} cases.when
4420
+ * @property {Record<string,string | number | boolean | null | undefined>} cases.columns
4421
+ * @returns {this} this
4422
+ */
4039
4423
  updateCases(cases) {
4040
4424
  if (!cases.length) {
4041
4425
  throw this._assertError("This method must require a non-empty array.");
@@ -4122,7 +4506,7 @@ class Model extends AbstractModel_1.AbstractModel {
4122
4506
  ? this.$constants("NULL")
4123
4507
  : this.$utils.transfromValueHasRaw(value)}`;
4124
4508
  });
4125
- this.$state.set("DATA", columns);
4509
+ this.$state.set("DATA", this._formatedInputData(columns));
4126
4510
  this.$state.set("UPDATE", keyValue);
4127
4511
  this.whereRaw("1");
4128
4512
  this.void();
@@ -4149,8 +4533,8 @@ class Model extends AbstractModel_1.AbstractModel {
4149
4533
  [column]: this._updateHandler(column, value),
4150
4534
  };
4151
4535
  }
4152
- this.$state.set("DATA", data);
4153
- if (this.$state.get('TRANSFORMS') == null) {
4536
+ this.$state.set("DATA", this._formatedInputData(data));
4537
+ if (this.$state.get("TRANSFORMS") == null) {
4154
4538
  this._queryUpdateModel();
4155
4539
  }
4156
4540
  this.$state.set("SAVE", "UPDATE");
@@ -4166,8 +4550,8 @@ class Model extends AbstractModel_1.AbstractModel {
4166
4550
  if (!Object.keys(data).length) {
4167
4551
  throw this._assertError("This method must require at least 1 argument.");
4168
4552
  }
4169
- this.$state.set("DATA", data);
4170
- if (this.$state.get('TRANSFORMS') == null) {
4553
+ this.$state.set("DATA", this._formatedInputData(data));
4554
+ if (this.$state.get("TRANSFORMS") == null) {
4171
4555
  this._queryUpdateModel();
4172
4556
  this._queryInsertModel();
4173
4557
  }
@@ -4207,8 +4591,8 @@ class Model extends AbstractModel_1.AbstractModel {
4207
4591
  if (!Object.keys(data).length) {
4208
4592
  throw this._assertError("This method must require at least 1 argument.");
4209
4593
  }
4210
- this.$state.set("DATA", data);
4211
- if (this.$state.get('TRANSFORMS') == null) {
4594
+ this.$state.set("DATA", this._formatedInputData(data));
4595
+ if (this.$state.get("TRANSFORMS") == null) {
4212
4596
  this._queryInsertModel();
4213
4597
  }
4214
4598
  this.$state.set("SAVE", "INSERT_OR_SELECT");
@@ -4232,8 +4616,8 @@ class Model extends AbstractModel_1.AbstractModel {
4232
4616
  if (!Object.keys(data).length) {
4233
4617
  throw this._assertError("This method must require at least 1 argument.");
4234
4618
  }
4235
- this.$state.set("DATA", data);
4236
- if (this.$state.get('TRANSFORMS') == null) {
4619
+ this.$state.set("DATA", this._formatedInputData(data));
4620
+ if (this.$state.get("TRANSFORMS") == null) {
4237
4621
  this._queryInsertModel();
4238
4622
  }
4239
4623
  this.$state.set("SAVE", "INSERT_NOT_EXISTS");
@@ -4257,8 +4641,8 @@ class Model extends AbstractModel_1.AbstractModel {
4257
4641
  if (!Array.isArray(data) || !data.length) {
4258
4642
  throw this._assertError("This method must require a non-empty array.");
4259
4643
  }
4260
- this.$state.set("DATA", data);
4261
- if (this.$state.get('TRANSFORMS') == null) {
4644
+ this.$state.set("DATA", this._formatedInputData(data));
4645
+ if (this.$state.get("TRANSFORMS") == null) {
4262
4646
  this._queryInsertMultipleModel();
4263
4647
  }
4264
4648
  this.$state.set("SAVE", "INSERT_MULTIPLE");
@@ -4271,7 +4655,6 @@ class Model extends AbstractModel_1.AbstractModel {
4271
4655
  * @returns {this} this
4272
4656
  */
4273
4657
  createMany(data) {
4274
- //@ts-ignore
4275
4658
  return this.createMultiple(data);
4276
4659
  }
4277
4660
  /**
@@ -4281,7 +4664,6 @@ class Model extends AbstractModel_1.AbstractModel {
4281
4664
  * @returns {this} this
4282
4665
  */
4283
4666
  insertMultiple(data) {
4284
- //@ts-ignore
4285
4667
  return this.createMultiple(data);
4286
4668
  }
4287
4669
  /**
@@ -4291,7 +4673,6 @@ class Model extends AbstractModel_1.AbstractModel {
4291
4673
  * @returns {this} this
4292
4674
  */
4293
4675
  insertMany(data) {
4294
- //@ts-ignore
4295
4676
  return this.createMultiple(data);
4296
4677
  }
4297
4678
  /**
@@ -4385,7 +4766,9 @@ class Model extends AbstractModel_1.AbstractModel {
4385
4766
  for (const { Field: field, Type: type } of fields) {
4386
4767
  if (passed(field))
4387
4768
  continue;
4388
- const blueprint = this._getBlueprintByColumn(field, { schema: schemaModel });
4769
+ const blueprint = this._getBlueprintByColumn(field, {
4770
+ schema: schemaModel,
4771
+ });
4389
4772
  if (blueprint?.isVirtual)
4390
4773
  continue;
4391
4774
  const value = field === uuid
@@ -4409,9 +4792,7 @@ class Model extends AbstractModel_1.AbstractModel {
4409
4792
  const debug = this.$state.get("DEBUG");
4410
4793
  const queue = [...chunkedData];
4411
4794
  const runNext = async () => {
4412
- const batch = Array
4413
- .from({ length: 3 }, () => queue.shift())
4414
- .filter(Boolean);
4795
+ const batch = Array.from({ length: 3 }, () => queue.shift()).filter(Boolean);
4415
4796
  if (!batch.length)
4416
4797
  return;
4417
4798
  await Promise.all(batch.map((data) => {
@@ -4425,7 +4806,7 @@ class Model extends AbstractModel_1.AbstractModel {
4425
4806
  await runNext();
4426
4807
  };
4427
4808
  const promises = Array.from({ length: 5 }, () => () => runNext());
4428
- await Promise.all(promises.map(v => v()));
4809
+ await Promise.all(promises.map((v) => v()));
4429
4810
  return;
4430
4811
  }
4431
4812
  /**
@@ -4826,7 +5207,7 @@ class Model extends AbstractModel_1.AbstractModel {
4826
5207
  case this.$constants("PATTERN").default: {
4827
5208
  return column;
4828
5209
  }
4829
- case this.$constants("PATTERN").snakeCase: {
5210
+ case this.$constants("PATTERN").snake_case: {
4830
5211
  return column.replace(/([A-Z])/g, (str) => `_${str.toLowerCase()}`);
4831
5212
  }
4832
5213
  case this.$constants("PATTERN").camelCase: {
@@ -4861,7 +5242,7 @@ class Model extends AbstractModel_1.AbstractModel {
4861
5242
  this.bindColumn(`${this.getTableName()}.${deletedAt}`),
4862
5243
  this.$constants("IS_NULL"),
4863
5244
  ].join(" ");
4864
- if (!wheres.some((where) => where.includes(softDeleteIsNull))) {
5245
+ if (!wheres.some((v) => v.column?.includes(softDeleteIsNull))) {
4865
5246
  this.whereNull(deletedAt);
4866
5247
  return this;
4867
5248
  }
@@ -4873,9 +5254,23 @@ class Model extends AbstractModel_1.AbstractModel {
4873
5254
  if (this.$state.get("EXCEPTS")?.length) {
4874
5255
  pipeline.push(async () => this.select(...(await this.exceptColumns())));
4875
5256
  }
4876
- await Promise.all(pipeline.map(fn => fn())).catch((err) => console.log(err));
5257
+ await Promise.all(pipeline.map((fn) => fn())).catch((err) => console.log(err));
4877
5258
  return;
4878
5259
  }
5260
+ _ensureRelationOwnerKeysSelected() {
5261
+ const relations = this.$state.get("RELATIONS");
5262
+ const relationship = this.$constants("RELATIONSHIP");
5263
+ const ownerKeyRelations = relations.filter((r) => {
5264
+ return (r.relation === relationship.hasMany ||
5265
+ r.relation === relationship.hasOne);
5266
+ });
5267
+ if (!ownerKeyRelations.length)
5268
+ return;
5269
+ const ownerKeys = new Set(ownerKeyRelations.map((r) => {
5270
+ return r.localKey ?? this.$state.get("PRIMARY_KEY");
5271
+ }));
5272
+ this.addSelect(...ownerKeys);
5273
+ }
4879
5274
  _handleGlobalScope() {
4880
5275
  if (!this.$state.get("GLOBAL_SCOPE"))
4881
5276
  return this;
@@ -4918,7 +5313,7 @@ class Model extends AbstractModel_1.AbstractModel {
4918
5313
  const sql = schemaColumn.sql.select;
4919
5314
  if (sql == null)
4920
5315
  continue;
4921
- if (sql.toLowerCase().includes(" as ")) {
5316
+ if (sql.toLowerCase().includes(` ${this.$constants("AS")} `)) {
4922
5317
  columns.push(sql);
4923
5318
  continue;
4924
5319
  }
@@ -4945,9 +5340,7 @@ class Model extends AbstractModel_1.AbstractModel {
4945
5340
  * generate sql statements
4946
5341
  * @override
4947
5342
  */
4948
- _queryBuilder({ onFormat = false } = {}) {
4949
- if (onFormat)
4950
- return this._buildQueryStatement();
5343
+ _queryBuilder() {
4951
5344
  this._handleSelect();
4952
5345
  this._handleSoftDelete();
4953
5346
  return this._buildQueryStatement();
@@ -4968,7 +5361,7 @@ class Model extends AbstractModel_1.AbstractModel {
4968
5361
  data = callback;
4969
5362
  }
4970
5363
  }
4971
- this.$state.set("DATA", data);
5364
+ this.$state.set("DATA", this._formatedInputData(data));
4972
5365
  return;
4973
5366
  }
4974
5367
  async _runAfter(action, data) {
@@ -5090,7 +5483,7 @@ class Model extends AbstractModel_1.AbstractModel {
5090
5483
  if (findCache == null)
5091
5484
  return;
5092
5485
  if (this.$state.get("DEBUG")) {
5093
- this.$utils.consoleCache(JSON.stringify({
5486
+ this.$utils.consoleCache({
5094
5487
  driver: this.$cache.provider(),
5095
5488
  key: cache.key,
5096
5489
  expires: cache.expires,
@@ -5099,7 +5492,7 @@ class Model extends AbstractModel_1.AbstractModel {
5099
5492
  this.$utils.typeOf(findCache) === "string"
5100
5493
  ? findCache.length
5101
5494
  : undefined,
5102
- }));
5495
+ });
5103
5496
  const endTime = +new Date();
5104
5497
  this.$utils.consoleExec(startTime, endTime);
5105
5498
  }
@@ -5136,8 +5529,8 @@ class Model extends AbstractModel_1.AbstractModel {
5136
5529
  this._returnEmpty(type, result, message, options));
5137
5530
  }
5138
5531
  async _pagination(data) {
5139
- const currentPage = +this.$state.get("PAGE");
5140
- const limit = Number(this.$state.get("LIMIT"));
5532
+ const currentPage = this.$state.get("PAGE") ?? 0;
5533
+ const limit = Number(this.$state.get("LIMIT") ?? 0);
5141
5534
  if (limit < 1) {
5142
5535
  throw this._assertError("This pagination needed limit minimun less 1 for limit");
5143
5536
  }
@@ -5160,15 +5553,21 @@ class Model extends AbstractModel_1.AbstractModel {
5160
5553
  last_page: lastPage,
5161
5554
  next_page: nextPage,
5162
5555
  prev_page: prevPage,
5556
+ page: {
5557
+ prev: prevPage,
5558
+ next: nextPage,
5559
+ current: currentPage,
5560
+ last: lastPage,
5561
+ },
5163
5562
  };
5164
5563
  const pattern = this.$state.get("PATTERN");
5165
- if (pattern === 'snake_case') {
5564
+ if (pattern === this.$constants("PATTERN").snake_case) {
5166
5565
  return this.$utils.snakeCase(this._resultHandler({
5167
5566
  meta,
5168
5567
  data,
5169
5568
  }));
5170
5569
  }
5171
- if (pattern === 'camelCase') {
5570
+ if (pattern === this.$constants("PATTERN").camelCase) {
5172
5571
  return this.$utils.camelCase(this._resultHandler({
5173
5572
  meta,
5174
5573
  data,
@@ -5215,6 +5614,12 @@ class Model extends AbstractModel_1.AbstractModel {
5215
5614
  last_page: 0,
5216
5615
  next_page: 0,
5217
5616
  prev_page: 0,
5617
+ page: {
5618
+ prev: 0,
5619
+ next: 0,
5620
+ current: Number(this.$state.get("PAGE")),
5621
+ last: 0,
5622
+ },
5218
5623
  },
5219
5624
  data: [],
5220
5625
  };
@@ -5223,14 +5628,14 @@ class Model extends AbstractModel_1.AbstractModel {
5223
5628
  default:
5224
5629
  throw this._assertError("Missing method first get or pagination");
5225
5630
  }
5226
- if (this.$state.get('PATTERN') === 'snake_case') {
5631
+ if (this.$state.get("PATTERN") === this.$constants("PATTERN").snake_case) {
5227
5632
  const empty = this.$utils.snakeCase(this._resultHandler(emptyData));
5228
5633
  await this.$utils.hookHandle(this.$state.get("HOOKS"), empty);
5229
5634
  await this._observer(empty, "selected");
5230
5635
  return empty;
5231
5636
  }
5232
- if (this.$state.get('PATTERN') === 'camelCase') {
5233
- const empty = this.$utils.snakeCase(this._resultHandler(emptyData));
5637
+ if (this.$state.get("PATTERN") === this.$constants("PATTERN").camelCase) {
5638
+ const empty = this.$utils.camelCase(this._resultHandler(emptyData));
5234
5639
  await this.$utils.hookHandle(this.$state.get("HOOKS"), empty);
5235
5640
  await this._observer(empty, "selected");
5236
5641
  return empty;
@@ -5266,11 +5671,11 @@ class Model extends AbstractModel_1.AbstractModel {
5266
5671
  throw this._assertError("Missing method first get or pagination");
5267
5672
  }
5268
5673
  }
5269
- if (this.$state.get('TRANSFORMS') != null) {
5674
+ if (this.$state.get("TRANSFORMS") != null) {
5270
5675
  await this.$utils.applyTransforms({
5271
5676
  result,
5272
- transforms: this.$state.get('TRANSFORMS'),
5273
- action: 'from'
5677
+ transforms: this.$state.get("TRANSFORMS"),
5678
+ action: "from",
5274
5679
  });
5275
5680
  }
5276
5681
  await this.$utils.hookHandle(this.$state.get("HOOKS"), result);
@@ -5290,11 +5695,11 @@ class Model extends AbstractModel_1.AbstractModel {
5290
5695
  : this.$utils.transfromDateToDateString(objects[updatedAt]),
5291
5696
  };
5292
5697
  }
5293
- if (this.$state.get('TRANSFORMS') != null) {
5698
+ if (this.$state.get("TRANSFORMS") != null) {
5294
5699
  await this.$utils.applyTransforms({
5295
5700
  result: objects,
5296
- transforms: this.$state.get('TRANSFORMS'),
5297
- action: 'to'
5701
+ transforms: this.$state.get("TRANSFORMS"),
5702
+ action: "to",
5298
5703
  });
5299
5704
  }
5300
5705
  const keyValue = Object.entries(objects).map(([column, value]) => {
@@ -5327,11 +5732,11 @@ class Model extends AbstractModel_1.AbstractModel {
5327
5732
  : this.$utils.transfromDateToDateString(data[updatedAt]),
5328
5733
  };
5329
5734
  }
5330
- if (this.$state.get('TRANSFORMS') != null) {
5735
+ if (this.$state.get("TRANSFORMS") != null) {
5331
5736
  await this.$utils.applyTransforms({
5332
5737
  result: data,
5333
- transforms: this.$state.get('TRANSFORMS'),
5334
- action: 'to'
5738
+ transforms: this.$state.get("TRANSFORMS"),
5739
+ action: "to",
5335
5740
  });
5336
5741
  }
5337
5742
  const hasUUID = data.hasOwnProperty(this.$state.get("UUID_FORMAT"));
@@ -5358,7 +5763,7 @@ class Model extends AbstractModel_1.AbstractModel {
5358
5763
  });
5359
5764
  this.$state.set("INSERT", {
5360
5765
  columns,
5361
- values: [values.join(', ')]
5766
+ values: [values.join(", ")],
5362
5767
  });
5363
5768
  return;
5364
5769
  }
@@ -5385,11 +5790,11 @@ class Model extends AbstractModel_1.AbstractModel {
5385
5790
  };
5386
5791
  columns = [...columns, `\`${createdAt}\``, `\`${updatedAt}\``];
5387
5792
  }
5388
- if (this.$state.get('TRANSFORMS') != null) {
5793
+ if (this.$state.get("TRANSFORMS") != null) {
5389
5794
  await this.$utils.applyTransforms({
5390
5795
  result: objects,
5391
- transforms: this.$state.get('TRANSFORMS'),
5392
- action: 'to'
5796
+ transforms: this.$state.get("TRANSFORMS"),
5797
+ action: "to",
5393
5798
  });
5394
5799
  }
5395
5800
  const hasUUID = objects.hasOwnProperty(this.$state.get("UUID_FORMAT"));
@@ -5417,13 +5822,13 @@ class Model extends AbstractModel_1.AbstractModel {
5417
5822
  values = [...values, `${v.join(",")}`];
5418
5823
  newData.push(objects);
5419
5824
  }
5420
- this.$state.set("DATA", newData);
5825
+ this.$state.set("DATA", this._formatedInputData(newData));
5421
5826
  columns = [
5422
5827
  ...new Set(columns.map((c) => `\`${this._valuePattern(c).replace(/\`/g, "")}\``)),
5423
5828
  ];
5424
5829
  this.$state.set("INSERT", {
5425
5830
  columns,
5426
- values
5831
+ values,
5427
5832
  });
5428
5833
  return;
5429
5834
  }
@@ -5442,7 +5847,7 @@ class Model extends AbstractModel_1.AbstractModel {
5442
5847
  if (check)
5443
5848
  return this._resultHandler(null);
5444
5849
  await this._runBefore("insert");
5445
- if (this.$state.get('TRANSFORMS') != null) {
5850
+ if (this.$state.get("TRANSFORMS") != null) {
5446
5851
  await this._queryInsertModel();
5447
5852
  }
5448
5853
  await this._validateSchema(this.$state.get("DATA"), "insert");
@@ -5452,7 +5857,7 @@ class Model extends AbstractModel_1.AbstractModel {
5452
5857
  await this.$utils.wait(this.$state.get("AFTER_SAVE"));
5453
5858
  let resultData = await new Model()
5454
5859
  .copyModel(this, { select: true, relations: true })
5455
- .whereIn("id", result.$meta.insertIds)
5860
+ .whereIn(this.$state.get('PRIMARY_KEY'), result.$meta.insertIds)
5456
5861
  .bind(this.$pool.get())
5457
5862
  .debug(this.$state.get("DEBUG"))
5458
5863
  .first();
@@ -5460,7 +5865,7 @@ class Model extends AbstractModel_1.AbstractModel {
5460
5865
  await this.$utils.wait(500);
5461
5866
  resultData = await new Model()
5462
5867
  .copyModel(this, { select: true, relations: true })
5463
- .whereIn("id", result.$meta.insertIds)
5868
+ .whereIn(this.$state.get('PRIMARY_KEY'), result.$meta.insertIds)
5464
5869
  .bind(this.$pool.get())
5465
5870
  .debug(this.$state.get("DEBUG"))
5466
5871
  .first();
@@ -5469,7 +5874,7 @@ class Model extends AbstractModel_1.AbstractModel {
5469
5874
  }
5470
5875
  async _insertModel() {
5471
5876
  await this._runBefore("insert");
5472
- if (this.$state.get('TRANSFORMS') != null) {
5877
+ if (this.$state.get("TRANSFORMS") != null) {
5473
5878
  await this._queryInsertModel();
5474
5879
  }
5475
5880
  await this._validateSchema(this.$state.get("DATA"), "insert");
@@ -5481,7 +5886,7 @@ class Model extends AbstractModel_1.AbstractModel {
5481
5886
  await this.$utils.wait(this.$state.get("AFTER_SAVE"));
5482
5887
  let resultData = await new Model()
5483
5888
  .copyModel(this, { select: true, relations: true })
5484
- .whereIn("id", result.$meta.insertIds)
5889
+ .whereIn(this.$state.get('PRIMARY_KEY'), result.$meta.insertIds)
5485
5890
  .bind(this.$pool.get())
5486
5891
  .debug(this.$state.get("DEBUG"))
5487
5892
  .first();
@@ -5489,7 +5894,7 @@ class Model extends AbstractModel_1.AbstractModel {
5489
5894
  await this.$utils.wait(1000);
5490
5895
  resultData = await new Model()
5491
5896
  .copyModel(this, { select: true, relations: true })
5492
- .whereIn("id", result.$meta.insertIds)
5897
+ .whereIn(this.$state.get('PRIMARY_KEY'), result.$meta.insertIds)
5493
5898
  .bind(this.$pool.get())
5494
5899
  .debug(this.$state.get("DEBUG"))
5495
5900
  .first();
@@ -5501,7 +5906,7 @@ class Model extends AbstractModel_1.AbstractModel {
5501
5906
  async _insertMultipleModel() {
5502
5907
  const data = this.$state.get("DATA") ?? [];
5503
5908
  await this._runBefore("insert");
5504
- if (this.$state.get('TRANSFORMS') != null) {
5909
+ if (this.$state.get("TRANSFORMS") != null) {
5505
5910
  await this._queryInsertMultipleModel();
5506
5911
  }
5507
5912
  for (const v of data) {
@@ -5542,7 +5947,7 @@ class Model extends AbstractModel_1.AbstractModel {
5542
5947
  switch (check) {
5543
5948
  case false: {
5544
5949
  await this._runBefore("insert");
5545
- if (this.$state.get('TRANSFORMS') != null) {
5950
+ if (this.$state.get("TRANSFORMS") != null) {
5546
5951
  await this._queryInsertModel();
5547
5952
  }
5548
5953
  await this._validateSchema(this.$state.get("DATA"), "insert");
@@ -5553,7 +5958,7 @@ class Model extends AbstractModel_1.AbstractModel {
5553
5958
  let data = await new Model()
5554
5959
  .copyModel(this, { select: true })
5555
5960
  .bind(this.$pool.get())
5556
- .whereIn("id", result.$meta.insertIds)
5961
+ .whereIn(this.$state.get('PRIMARY_KEY'), result.$meta.insertIds)
5557
5962
  .debug(this.$state.get("DEBUG"))
5558
5963
  .first();
5559
5964
  if (data == null) {
@@ -5561,7 +5966,7 @@ class Model extends AbstractModel_1.AbstractModel {
5561
5966
  data = await new Model()
5562
5967
  .copyModel(this, { select: true })
5563
5968
  .bind(this.$pool.get())
5564
- .whereIn("id", result.$meta.insertIds)
5969
+ .whereIn(this.$state.get('PRIMARY_KEY'), result.$meta.insertIds)
5565
5970
  .debug(this.$state.get("DEBUG"))
5566
5971
  .first();
5567
5972
  }
@@ -5573,7 +5978,7 @@ class Model extends AbstractModel_1.AbstractModel {
5573
5978
  }
5574
5979
  case true: {
5575
5980
  await this._runBefore("update");
5576
- if (this.$state.get('TRANSFORMS') != null) {
5981
+ if (this.$state.get("TRANSFORMS") != null) {
5577
5982
  await this._queryUpdateModel();
5578
5983
  }
5579
5984
  await this._validateSchema(this.$state.get("DATA"), "update");
@@ -5612,7 +6017,7 @@ class Model extends AbstractModel_1.AbstractModel {
5612
6017
  switch (check) {
5613
6018
  case false: {
5614
6019
  await this._runBefore("insert");
5615
- if (this.$state.get('TRANSFORMS') != null) {
6020
+ if (this.$state.get("TRANSFORMS") != null) {
5616
6021
  await this._queryInsertModel();
5617
6022
  }
5618
6023
  await this._validateSchema(this.$state.get("DATA"), "insert");
@@ -5623,7 +6028,7 @@ class Model extends AbstractModel_1.AbstractModel {
5623
6028
  let data = await new Model()
5624
6029
  .copyModel(this, { select: true })
5625
6030
  .bind(this.$pool.get())
5626
- .whereIn("id", result.$meta.insertIds)
6031
+ .whereIn(this.$state.get('PRIMARY_KEY'), result.$meta.insertIds)
5627
6032
  .debug(this.$state.get("DEBUG"))
5628
6033
  .first();
5629
6034
  if (data == null) {
@@ -5631,7 +6036,7 @@ class Model extends AbstractModel_1.AbstractModel {
5631
6036
  data = await new Model()
5632
6037
  .copyModel(this, { select: true })
5633
6038
  .bind(this.$pool.get())
5634
- .whereIn("id", result.$meta.insertIds)
6039
+ .whereIn(this.$state.get('PRIMARY_KEY'), result.$meta.insertIds)
5635
6040
  .debug(this.$state.get("DEBUG"))
5636
6041
  .first();
5637
6042
  }
@@ -5670,7 +6075,7 @@ class Model extends AbstractModel_1.AbstractModel {
5670
6075
  async _updateModel() {
5671
6076
  this._guardWhereCondition();
5672
6077
  await this._runBefore("update");
5673
- if (this.$state.get('TRANSFORMS') != null) {
6078
+ if (this.$state.get("TRANSFORMS") != null) {
5674
6079
  await this._queryUpdateModel();
5675
6080
  }
5676
6081
  await this._validateSchema(this.$state.get("DATA"), "update");
@@ -5709,6 +6114,10 @@ class Model extends AbstractModel_1.AbstractModel {
5709
6114
  throw new Error(message);
5710
6115
  return;
5711
6116
  }
6117
+ disabledRetry() {
6118
+ this.$state.set("RETRY", 3);
6119
+ return this;
6120
+ }
5712
6121
  async _checkSchemaOrNextError(e, retry = 1, originError) {
5713
6122
  const throwError = originError == null ? e : originError;
5714
6123
  try {
@@ -5719,12 +6128,19 @@ class Model extends AbstractModel_1.AbstractModel {
5719
6128
  return this._stoppedRetry(throwError);
5720
6129
  if (!(e instanceof Error))
5721
6130
  return this._stoppedRetry(throwError);
5722
- await this.sync({ force: true });
6131
+ await new Promise((r) => setTimeout(r, 1000));
6132
+ await new Model()
6133
+ .copyModel(this)
6134
+ .disabledRetry()
6135
+ .debug(this.$state.get('DEBUG'))
6136
+ .sync({ force: true }).catch(() => null);
6137
+ this.$state.set("RETRY", retry + 1);
5723
6138
  }
5724
6139
  catch (e) {
5725
6140
  if (retry >= 3) {
5726
6141
  throw throwError;
5727
6142
  }
6143
+ this.$state.set("RETRY", retry + 1);
5728
6144
  await this._checkSchemaOrNextError(e, retry + 1, originError);
5729
6145
  }
5730
6146
  }
@@ -5749,20 +6165,26 @@ class Model extends AbstractModel_1.AbstractModel {
5749
6165
  const uuidIsEnabled = Reflect.getMetadata(Decorator_1.REFLECT_META.UUID.enabled, this.constructor) || null;
5750
6166
  if (uuidIsEnabled) {
5751
6167
  this.$uuid = true;
5752
- this.$uuidColumn = Reflect.getMetadata(Decorator_1.REFLECT_META.UUID.column, this.constructor) || null;
6168
+ this.$uuidColumn =
6169
+ Reflect.getMetadata(Decorator_1.REFLECT_META.UUID.column, this.constructor) || null;
5753
6170
  }
5754
- const timestamp = Reflect.getMetadata(Decorator_1.REFLECT_META.TIMESTAMP.enabled, this.constructor) || null;
6171
+ const timestamp = Reflect.getMetadata(Decorator_1.REFLECT_META.TIMESTAMP.enabled, this.constructor) ||
6172
+ null;
5755
6173
  if (timestamp) {
5756
6174
  this.$timestamp = true;
5757
- this.$timestampColumns = Reflect.getMetadata(Decorator_1.REFLECT_META.TIMESTAMP.columns, this.constructor) || null;
6175
+ this.$timestampColumns =
6176
+ Reflect.getMetadata(Decorator_1.REFLECT_META.TIMESTAMP.columns, this.constructor) ||
6177
+ null;
5758
6178
  }
5759
6179
  const pattern = Reflect.getMetadata(Decorator_1.REFLECT_META.PATTERN, this.constructor) || null;
5760
6180
  if (pattern)
5761
6181
  this.$pattern = pattern;
5762
- const softDelete = Reflect.getMetadata(Decorator_1.REFLECT_META.SOFT_DELETE.enabled, this.constructor) || null;
6182
+ const softDelete = Reflect.getMetadata(Decorator_1.REFLECT_META.SOFT_DELETE.enabled, this.constructor) ||
6183
+ null;
5763
6184
  if (softDelete) {
5764
6185
  this.$softDelete = true;
5765
- this.$softDeleteColumn = Reflect.getMetadata(Decorator_1.REFLECT_META.SOFT_DELETE.columns, this.constructor) || null;
6186
+ this.$softDeleteColumn =
6187
+ Reflect.getMetadata(Decorator_1.REFLECT_META.SOFT_DELETE.columns, this.constructor) || null;
5766
6188
  }
5767
6189
  const schema = Reflect.getMetadata(Decorator_1.REFLECT_META.SCHEMA, this) || null;
5768
6190
  if (schema)
@@ -5834,27 +6256,27 @@ class Model extends AbstractModel_1.AbstractModel {
5834
6256
  this.useHooks(hooks);
5835
6257
  const beforeInserts = Reflect.getMetadata(Decorator_1.REFLECT_META.BEFORE.INSERT, this) || [];
5836
6258
  if (beforeInserts.length) {
5837
- this.useLifecycle('beforeInsert', beforeInserts);
6259
+ this.useLifecycle("beforeInsert", beforeInserts);
5838
6260
  }
5839
6261
  const afterInserts = Reflect.getMetadata(Decorator_1.REFLECT_META.AFTER.INSERT, this) || [];
5840
6262
  if (afterInserts.length) {
5841
- this.useLifecycle('afterInsert', afterInserts);
6263
+ this.useLifecycle("afterInsert", afterInserts);
5842
6264
  }
5843
6265
  const beforeUpdates = Reflect.getMetadata(Decorator_1.REFLECT_META.BEFORE.UPDATE, this) || [];
5844
6266
  if (beforeUpdates.length) {
5845
- this.useLifecycle('beforeUpdate', beforeUpdates);
6267
+ this.useLifecycle("beforeUpdate", beforeUpdates);
5846
6268
  }
5847
6269
  const afterUpdates = Reflect.getMetadata(Decorator_1.REFLECT_META.AFTER.UPDATE, this) || [];
5848
6270
  if (afterUpdates.length) {
5849
- this.useLifecycle('afterUpdate', afterUpdates);
6271
+ this.useLifecycle("afterUpdate", afterUpdates);
5850
6272
  }
5851
6273
  const beforeRemoves = Reflect.getMetadata(Decorator_1.REFLECT_META.BEFORE.REMOVE, this) || [];
5852
6274
  if (beforeRemoves.length) {
5853
- this.useLifecycle('beforeRemove', beforeRemoves);
6275
+ this.useLifecycle("beforeRemove", beforeRemoves);
5854
6276
  }
5855
6277
  const afterRemoves = Reflect.getMetadata(Decorator_1.REFLECT_META.AFTER.REMOVE, this) || [];
5856
6278
  if (afterRemoves.length) {
5857
- this.useLifecycle('afterRemove', afterRemoves);
6279
+ this.useLifecycle("afterRemove", afterRemoves);
5858
6280
  }
5859
6281
  return this;
5860
6282
  }
@@ -5869,7 +6291,7 @@ class Model extends AbstractModel_1.AbstractModel {
5869
6291
  this.bindColumn(`${this.getTableName()}.${deletedAt}`),
5870
6292
  this.$constants("IS_NULL"),
5871
6293
  ].join(" ");
5872
- if (wheres.some((where) => where.includes(softDeleteIsNull))) {
6294
+ if (wheres.some((v) => v.column?.includes(softDeleteIsNull))) {
5873
6295
  throw this._assertError(`The statement is not allowed to use the '${deletedAt}' column as a condition for any action`);
5874
6296
  }
5875
6297
  }
@@ -5883,7 +6305,7 @@ class Model extends AbstractModel_1.AbstractModel {
5883
6305
  return false;
5884
6306
  }
5885
6307
  }
5886
- _getBlueprintByColumn(column, { schema } = {}) {
6308
+ _getBlueprintByColumn(column, { schema, } = {}) {
5887
6309
  schema = schema ?? this.getSchemaModel();
5888
6310
  if (!schema)
5889
6311
  return null;
@@ -5942,6 +6364,28 @@ class Model extends AbstractModel_1.AbstractModel {
5942
6364
  foreignKey,
5943
6365
  };
5944
6366
  }
6367
+ _formatedInputData(data) {
6368
+ const schema = this.getSchemaModel();
6369
+ if (!schema)
6370
+ return data;
6371
+ if (data == null)
6372
+ return data;
6373
+ const formatObject = (obj) => {
6374
+ if (obj === null || typeof obj !== 'object')
6375
+ return obj;
6376
+ const result = {};
6377
+ for (const key of Object.keys(schema)) {
6378
+ if (key in obj) {
6379
+ result[key] = obj[key];
6380
+ }
6381
+ }
6382
+ return result;
6383
+ };
6384
+ if (Array.isArray(data)) {
6385
+ return data.map(item => formatObject(item));
6386
+ }
6387
+ return formatObject(data);
6388
+ }
5945
6389
  _initialModel() {
5946
6390
  this.$cache = Cache_1.Cache;
5947
6391
  this.$state = new StateManager_1.StateManager("model");