tspace-mysql 1.9.4 → 1.9.5

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 (121) hide show
  1. package/README.md +376 -72
  2. package/dist/cli/dump/db.js +3 -15
  3. package/dist/cli/dump/db.js.map +1 -1
  4. package/dist/cli/index.js +0 -3
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/cli/migrations/make-db.js +1 -1
  7. package/dist/cli/migrations/make-db.js.map +1 -1
  8. package/dist/cli/migrations/make-model.js +1 -6
  9. package/dist/cli/migrations/make-model.js.map +1 -1
  10. package/dist/lib/config/index.d.ts +6 -5
  11. package/dist/lib/config/index.js +18 -8
  12. package/dist/lib/config/index.js.map +1 -1
  13. package/dist/lib/constants/index.d.ts +1 -1
  14. package/dist/lib/constants/index.js +1 -1
  15. package/dist/lib/constants/index.js.map +1 -1
  16. package/dist/lib/core/Abstracts/AbstractBuilder.d.ts +2 -1
  17. package/dist/lib/core/Abstracts/AbstractDB.d.ts +5 -3
  18. package/dist/lib/core/Abstracts/AbstractDB.js.map +1 -1
  19. package/dist/lib/core/Abstracts/AbstractModel.d.ts +1 -2
  20. package/dist/lib/core/Abstracts/AbstractModel.js +0 -1
  21. package/dist/lib/core/Abstracts/AbstractModel.js.map +1 -1
  22. package/dist/lib/core/Abstracts/AbstractView.d.ts +2 -1
  23. package/dist/lib/core/Abstracts/AbstractView.js.map +1 -1
  24. package/dist/lib/core/Blueprint.d.ts +13 -3
  25. package/dist/lib/core/Blueprint.js +16 -1
  26. package/dist/lib/core/Blueprint.js.map +1 -1
  27. package/dist/lib/core/Builder.d.ts +172 -19
  28. package/dist/lib/core/Builder.js +564 -197
  29. package/dist/lib/core/Builder.js.map +1 -1
  30. package/dist/lib/core/Cache/DBCache.js +6 -5
  31. package/dist/lib/core/Cache/DBCache.js.map +1 -1
  32. package/dist/lib/core/Cache/index.js +1 -1
  33. package/dist/lib/core/Cache/index.js.map +1 -1
  34. package/dist/lib/core/Contracts/Audit.d.ts +5 -3
  35. package/dist/lib/core/Contracts/Audit.js +18 -2
  36. package/dist/lib/core/Contracts/Audit.js.map +1 -1
  37. package/dist/lib/core/DB.d.ts +148 -190
  38. package/dist/lib/core/DB.js +459 -525
  39. package/dist/lib/core/DB.js.map +1 -1
  40. package/dist/lib/core/Driver/index.d.ts +40 -15
  41. package/dist/lib/core/Driver/index.js +3 -0
  42. package/dist/lib/core/Driver/index.js.map +1 -1
  43. package/dist/lib/core/Driver/mariadb/MariadbDriver.d.ts +3 -2
  44. package/dist/lib/core/Driver/mariadb/MariadbDriver.js +7 -5
  45. package/dist/lib/core/Driver/mariadb/MariadbDriver.js.map +1 -1
  46. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.d.ts +42 -17
  47. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js +281 -154
  48. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js.map +1 -1
  49. package/dist/lib/core/Driver/mongodb/MongodbDriver.d.ts +4 -3
  50. package/dist/lib/core/Driver/mongodb/MongodbDriver.js +7 -5
  51. package/dist/lib/core/Driver/mongodb/MongodbDriver.js.map +1 -1
  52. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.d.ts +40 -15
  53. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js +205 -157
  54. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js.map +1 -1
  55. package/dist/lib/core/Driver/mysql/MysqlDriver.d.ts +3 -2
  56. package/dist/lib/core/Driver/mysql/MysqlDriver.js +6 -14
  57. package/dist/lib/core/Driver/mysql/MysqlDriver.js.map +1 -1
  58. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.d.ts +42 -17
  59. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js +251 -144
  60. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js.map +1 -1
  61. package/dist/lib/core/Driver/postgres/PostgresDriver.d.ts +3 -2
  62. package/dist/lib/core/Driver/postgres/PostgresDriver.js +7 -5
  63. package/dist/lib/core/Driver/postgres/PostgresDriver.js.map +1 -1
  64. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.d.ts +45 -19
  65. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js +471 -287
  66. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js.map +1 -1
  67. package/dist/lib/core/Driver/sqlite/SqliteDriver.d.ts +3 -2
  68. package/dist/lib/core/Driver/sqlite/SqliteDriver.js +8 -6
  69. package/dist/lib/core/Driver/sqlite/SqliteDriver.js.map +1 -1
  70. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.d.ts +47 -19
  71. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js +331 -203
  72. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js.map +1 -1
  73. package/dist/lib/core/Model.d.ts +255 -52
  74. package/dist/lib/core/Model.js +459 -117
  75. package/dist/lib/core/Model.js.map +1 -1
  76. package/dist/lib/core/Package.d.ts +5 -0
  77. package/dist/lib/core/Package.js +7 -2
  78. package/dist/lib/core/Package.js.map +1 -1
  79. package/dist/lib/core/Pool.d.ts +1 -1
  80. package/dist/lib/core/Pool.js +53 -75
  81. package/dist/lib/core/Pool.js.map +1 -1
  82. package/dist/lib/core/Queue/index.d.ts +2 -11
  83. package/dist/lib/core/Queue/index.js +3 -3
  84. package/dist/lib/core/Queue/index.js.map +1 -1
  85. package/dist/lib/core/Queue/types.d.ts +32 -3
  86. package/dist/lib/core/Queue/worker-lock.d.ts +17 -0
  87. package/dist/lib/core/Queue/worker-lock.js +28 -0
  88. package/dist/lib/core/Queue/worker-lock.js.map +1 -0
  89. package/dist/lib/core/Queue/worker.d.ts +37 -23
  90. package/dist/lib/core/Queue/worker.js +385 -171
  91. package/dist/lib/core/Queue/worker.js.map +1 -1
  92. package/dist/lib/core/RelationManager.js +1 -1
  93. package/dist/lib/core/RelationManager.js.map +1 -1
  94. package/dist/lib/core/Repository.d.ts +164 -29
  95. package/dist/lib/core/Repository.js +181 -40
  96. package/dist/lib/core/Repository.js.map +1 -1
  97. package/dist/lib/core/Schema.d.ts +11 -7
  98. package/dist/lib/core/Schema.js +249 -80
  99. package/dist/lib/core/Schema.js.map +1 -1
  100. package/dist/lib/core/SqlLike.js +4 -4
  101. package/dist/lib/core/SqlLike.js.map +1 -1
  102. package/dist/lib/core/StateManager.d.ts +19 -0
  103. package/dist/lib/core/StateManager.js +9 -4
  104. package/dist/lib/core/StateManager.js.map +1 -1
  105. package/dist/lib/core/UtilityTypes.d.ts +17 -3
  106. package/dist/lib/core/UtilityTypes.js.map +1 -1
  107. package/dist/lib/core/View.d.ts +3 -1
  108. package/dist/lib/core/View.js +18 -25
  109. package/dist/lib/core/View.js.map +1 -1
  110. package/dist/lib/core/index.d.ts +2 -0
  111. package/dist/lib/core/index.js +3 -1
  112. package/dist/lib/core/index.js.map +1 -1
  113. package/dist/lib/types/index.d.ts +77 -90
  114. package/dist/lib/types/repository/index.d.ts +18 -26
  115. package/dist/lib/utils/index.d.ts +7 -3
  116. package/dist/lib/utils/index.js +99 -37
  117. package/dist/lib/utils/index.js.map +1 -1
  118. package/package.json +1 -2
  119. package/dist/cli/dump/table.d.ts +0 -4
  120. package/dist/cli/dump/table.js +0 -41
  121. package/dist/cli/dump/table.js.map +0 -1
@@ -7,12 +7,11 @@ const DB_1 = require("./DB");
7
7
  const StateManager_1 = require("./StateManager");
8
8
  const Join_1 = require("./Join");
9
9
  const constants_1 = require("../constants");
10
- const config_1 = require("../config");
11
10
  const Pool_1 = require("./Pool");
12
11
  class Builder extends AbstractBuilder_1.AbstractBuilder {
13
12
  constructor() {
14
13
  super();
15
- this._initialConnection();
14
+ this._initBuilder();
16
15
  }
17
16
  /**
18
17
  * The 'instance' method is used get instance.
@@ -44,6 +43,16 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
44
43
  database() {
45
44
  return this.$database;
46
45
  }
46
+ useNode(type, options = {}) {
47
+ if (!this.$cluster) {
48
+ throw new Error('.useNode() is only available in cluster mode');
49
+ }
50
+ if (type === 'primary' && options.node !== undefined) {
51
+ throw new Error('The primary node cannot be specified');
52
+ }
53
+ this.$state.set('NODE', { type, node: options.node });
54
+ return this;
55
+ }
47
56
  /**
48
57
  * The 'rowLock' method is used to row level locks (`FOR UPDATE` or `FOR SHARE`) to the query.
49
58
  *
@@ -422,7 +431,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
422
431
  sleep(second) {
423
432
  this.CTEs('sleep', (query) => {
424
433
  return query
425
- .selectRaw(`${this._queryBuilder().sleep(second)} ${this.$constants("AS")} delay`)
434
+ .selectRaw(`${this.getQueryBuilder().sleep(second)} ${this.$constants("AS")} delay`)
426
435
  .from(null);
427
436
  });
428
437
  this.from(this.$state.get("TABLE_NAME"), {
@@ -719,10 +728,12 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
719
728
  * @returns {this}
720
729
  */
721
730
  whereJSON(column, { key, value, operator }) {
731
+ const qb = this.getQueryBuilder();
732
+ const json = qb.whereJson(this.bindColumn(String(column)), key);
722
733
  this.$state.set("WHERE", [
723
734
  ...this.$state.get("WHERE"),
724
735
  {
725
- column: `${this.bindColumn(String(column))}->>'$.${key}'`,
736
+ column: json,
726
737
  operator: `${operator == null ? "=" : operator.toLocaleUpperCase()}`,
727
738
  value: `${this.$utils.formatQueryValue(value)}`
728
739
  }
@@ -1667,7 +1678,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
1667
1678
  random() {
1668
1679
  this.$state.set("ORDER_BY", [
1669
1680
  ...this.$state.get("ORDER_BY"),
1670
- `${this.$constants("RAND")}`,
1681
+ `${this.getQueryBuilder().random()}`,
1671
1682
  ]);
1672
1683
  return this;
1673
1684
  }
@@ -2242,7 +2253,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2242
2253
  * @returns {string} return sql query
2243
2254
  */
2244
2255
  toString() {
2245
- const sql = this._queryBuilder().any();
2256
+ const sql = this.getQueryBuilder().any();
2246
2257
  return this._resultHandler(sql);
2247
2258
  }
2248
2259
  /**
@@ -2302,43 +2313,15 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2302
2313
  * @returns {Promise<Array>}
2303
2314
  */
2304
2315
  async showSchema(table = String(this.$state.get("TABLE_NAME")), options = {}) {
2305
- const sql = this._queryBuilder().getSchema({
2316
+ const qb = this.getQueryBuilder();
2317
+ const sql = qb.getSchema({
2306
2318
  database: this.$database,
2307
- table,
2319
+ table: this.$utils.escape(table),
2308
2320
  });
2309
- const raws = await this._queryStatement(sql);
2321
+ const raws = await this.rawQuery(sql);
2310
2322
  if (options.raw)
2311
2323
  return raws;
2312
- const schema = raws.map((r) => {
2313
- const schema = [];
2314
- schema.push(`\`${r.Field}\``);
2315
- schema.push(`${r.Type}`);
2316
- if (r.Nullable === "YES") {
2317
- schema.push(`NULL`);
2318
- }
2319
- if (r.Nullable === "NO") {
2320
- schema.push(`NOT NULL`);
2321
- }
2322
- if (r.Key === "PRI") {
2323
- schema.push(`PRIMARY KEY`);
2324
- }
2325
- if (r.Key === "UNI") {
2326
- schema.push(`UNIQUE`);
2327
- }
2328
- if (r.Default) {
2329
- if (r.Default.includes("IS_CONST:")) {
2330
- schema.push(`DEFAULT ${String(r.Default).replace("IS_CONST:", "")}`);
2331
- }
2332
- else {
2333
- schema.push(`DEFAULT '${r.Default}'`);
2334
- }
2335
- }
2336
- if (r.Extra) {
2337
- schema.push(`${r.Extra.toUpperCase()}`);
2338
- }
2339
- return schema.join(" ");
2340
- });
2341
- return schema;
2324
+ return qb.mapSchema(raws);
2342
2325
  }
2343
2326
  /**
2344
2327
  * The `getSchema` method is used to retrieve the column schema for the database
@@ -2356,11 +2339,15 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2356
2339
  *
2357
2340
  */
2358
2341
  async getSchema() {
2359
- const tableName = this.$state.get("TABLE_NAME");
2360
- if (tableName == null) {
2342
+ const table = this.$state.get("TABLE_NAME");
2343
+ if (table == null) {
2361
2344
  throw new Error('Unknown table name');
2362
2345
  }
2363
- return await this.showSchema(tableName, { raw: true });
2346
+ const sql = this.getQueryBuilder().getSchema({
2347
+ database: this.$database,
2348
+ table,
2349
+ });
2350
+ return await this.rawQuery(sql);
2364
2351
  }
2365
2352
  /**
2366
2353
  * The 'getFKs' method is used to get foreign key constraints for the database or a specific table.
@@ -2376,7 +2363,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2376
2363
  *
2377
2364
  */
2378
2365
  async getFKs(table) {
2379
- const fks = await this.rawQuery(this._queryBuilder().getFKs({
2366
+ const fks = await this.rawQuery(this.getQueryBuilder().getFKs({
2380
2367
  database: this.$database,
2381
2368
  table: table ?? String(this.$state.get("TABLE_NAME")),
2382
2369
  }));
@@ -2393,7 +2380,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2393
2380
  *
2394
2381
  */
2395
2382
  async hasFK({ constraint, table }) {
2396
- const result = await this.rawQuery(this._queryBuilder().hasFK({
2383
+ const result = await this.rawQuery(this.getQueryBuilder().hasFK({
2397
2384
  database: this.$database,
2398
2385
  table: table ?? String(this.$state.get("TABLE_NAME")),
2399
2386
  constraint
@@ -2416,7 +2403,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2416
2403
  *
2417
2404
  */
2418
2405
  async getChildFKs(table) {
2419
- const childFks = await this.rawQuery(this._queryBuilder().getChildFKs({
2406
+ const childFks = await this.rawQuery(this.getQueryBuilder().getChildFKs({
2420
2407
  database: this.$database,
2421
2408
  table: table ?? String(this.$state.get("TABLE_NAME")),
2422
2409
  }));
@@ -2450,7 +2437,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2450
2437
  if (exists) {
2451
2438
  throw new Error('The specified foreign key constraint already exists.');
2452
2439
  }
2453
- await this.rawQuery(this._queryBuilder()
2440
+ await this.rawQuery(this.getQueryBuilder()
2454
2441
  .addFK({
2455
2442
  table: table ?? this.getTableName(),
2456
2443
  tableRef,
@@ -2475,7 +2462,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2475
2462
  if (!exists) {
2476
2463
  throw new Error('The specified foreign key constraint was not found.');
2477
2464
  }
2478
- await this.rawQuery(this._queryBuilder()
2465
+ await this.rawQuery(this.getQueryBuilder()
2479
2466
  .dropFK({
2480
2467
  table: table ?? this.getTableName(),
2481
2468
  constraint
@@ -2498,7 +2485,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2498
2485
  *
2499
2486
  */
2500
2487
  async getIndexes(table) {
2501
- const indexes = await this.rawQuery(this._queryBuilder().getIndexes({
2488
+ const indexes = await this.rawQuery(this.getQueryBuilder().getIndexes({
2502
2489
  database: this.$database,
2503
2490
  table: table ?? this.getTableName()
2504
2491
  }));
@@ -2515,7 +2502,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2515
2502
  *
2516
2503
  */
2517
2504
  async hasIndex({ name, table }) {
2518
- const result = await this.rawQuery(this._queryBuilder().hasIndex({
2505
+ const result = await this.rawQuery(this.getQueryBuilder().hasIndex({
2519
2506
  database: this.$database,
2520
2507
  table: table ?? this.getTableName(),
2521
2508
  name
@@ -2545,7 +2532,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2545
2532
  if (exists) {
2546
2533
  throw new Error('The specified index already exists.');
2547
2534
  }
2548
- await this.rawQuery(this._queryBuilder().addIndex({
2535
+ await this.rawQuery(this.getQueryBuilder().addIndex({
2549
2536
  table: table ?? this.getTableName(),
2550
2537
  name,
2551
2538
  columns
@@ -2574,7 +2561,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2574
2561
  if (!exists) {
2575
2562
  throw new Error('The specified index was not found');
2576
2563
  }
2577
- await this.rawQuery(this._queryBuilder().dropIndex({
2564
+ await this.rawQuery(this.getQueryBuilder().dropIndex({
2578
2565
  table: table ?? this.getTableName(),
2579
2566
  name,
2580
2567
  }));
@@ -2595,7 +2582,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2595
2582
  * @returns {Promise<boolean>} Returns `true` if the unique constraint exists, otherwise `false`.
2596
2583
  */
2597
2584
  async hasUnique({ name, table }) {
2598
- const result = await this.rawQuery(this._queryBuilder().hasUnique({
2585
+ const result = await this.rawQuery(this.getQueryBuilder().hasUnique({
2599
2586
  database: this.$database,
2600
2587
  table: table ?? this.getTableName(),
2601
2588
  name
@@ -2625,7 +2612,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2625
2612
  if (exists) {
2626
2613
  throw new Error('The specified unique constraint already exists.');
2627
2614
  }
2628
- await this.rawQuery(this._queryBuilder().addUnique({
2615
+ await this.rawQuery(this.getQueryBuilder().addUnique({
2629
2616
  table: table ?? this.getTableName(),
2630
2617
  name,
2631
2618
  columns
@@ -2654,7 +2641,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2654
2641
  if (!exists) {
2655
2642
  throw new Error('The specified unique constraint was not found.');
2656
2643
  }
2657
- await this.rawQuery(this._queryBuilder().dropUnique({
2644
+ await this.rawQuery(this.getQueryBuilder().dropUnique({
2658
2645
  table: table ?? this.getTableName(),
2659
2646
  name,
2660
2647
  }));
@@ -2675,7 +2662,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2675
2662
  * otherwise `false`.
2676
2663
  */
2677
2664
  async hasPrimaryKey({ table } = {}) {
2678
- const result = await this.rawQuery(this._queryBuilder().hasPrimaryKey({
2665
+ const result = await this.rawQuery(this.getQueryBuilder().hasPrimaryKey({
2679
2666
  database: this.$database,
2680
2667
  table: table ?? this.getTableName()
2681
2668
  }));
@@ -2703,7 +2690,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2703
2690
  if (exists) {
2704
2691
  throw new Error('The specified primary constraint already exists.');
2705
2692
  }
2706
- await this.rawQuery(this._queryBuilder().addPrimaryKey({
2693
+ await this.rawQuery(this.getQueryBuilder().addPrimaryKey({
2707
2694
  table: table ?? String(this.getTableName()),
2708
2695
  columns
2709
2696
  }));
@@ -2729,7 +2716,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2729
2716
  if (!exists) {
2730
2717
  throw new Error('The specified primary constraint was not found.');
2731
2718
  }
2732
- await this.rawQuery(this._queryBuilder().dropPrimaryKey({
2719
+ await this.rawQuery(this.getQueryBuilder().dropPrimaryKey({
2733
2720
  table: table ?? String(this.getTableName())
2734
2721
  }));
2735
2722
  return;
@@ -2822,6 +2809,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2822
2809
  password,
2823
2810
  ...others,
2824
2811
  });
2812
+ this.$state.set('BIND', true);
2825
2813
  this.$pool.set(pool.connect());
2826
2814
  return this;
2827
2815
  }
@@ -2858,7 +2846,16 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2858
2846
  * @returns {this} this
2859
2847
  */
2860
2848
  bind(connection) {
2849
+ this.$state.set('BIND', true);
2861
2850
  this.$pool.set(connection);
2851
+ if (Object.hasOwn(connection, 'primary')) {
2852
+ const cluster = connection;
2853
+ this.$database = cluster.primary?.database();
2854
+ this.$driver = cluster.primary?.driver();
2855
+ return this;
2856
+ }
2857
+ this.$database = connection.database();
2858
+ this.$driver = connection.driver();
2862
2859
  return this;
2863
2860
  }
2864
2861
  /**
@@ -2908,7 +2905,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2908
2905
  */
2909
2906
  async increment(column = "id", value = 1) {
2910
2907
  this.$state.set("UPDATE", [
2911
- `${column} = ${column} + ${value}`
2908
+ `${column} = ${column} + ${this.$utils.escape(value)}`
2912
2909
  ]);
2913
2910
  return await this._update(true);
2914
2911
  }
@@ -2921,13 +2918,14 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2921
2918
  */
2922
2919
  async decrement(column = "id", value = 1) {
2923
2920
  this.$state.set("UPDATE", [
2924
- `${column} = ${column} - ${value}`,
2921
+ `${column} = ${column} - ${this.$utils.escape(value)}`,
2925
2922
  ]);
2926
2923
  return await this._update(true);
2927
2924
  }
2928
2925
  async version() {
2929
- const result = await this._queryStatement(`${this.$constants("SELECT")} VERSION() as version`);
2930
- return result[0].version;
2926
+ const qb = this.getQueryBuilder();
2927
+ const result = await this.rawQuery(qb.version());
2928
+ return result[0]?.version ?? 'unknown';
2931
2929
  }
2932
2930
  /**
2933
2931
  * The 'all' method is used to retrieve all records from a database table associated.
@@ -2965,24 +2963,20 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
2965
2963
  * @property {boolean?} opts.distinct
2966
2964
  * @returns {promise<Pagination>}
2967
2965
  */
2968
- async pagination(opts) {
2969
- let limit = 15;
2970
- let page = 1;
2966
+ async pagination(opts = {}) {
2967
+ const limit = this.$utils.softNumber(opts.limit ?? 15);
2968
+ const page = this.$utils.softNumber(opts.page ?? 1);
2971
2969
  if (opts?.distinct) {
2972
2970
  this.distinct();
2973
2971
  }
2974
- if (opts != null) {
2975
- limit = opts?.limit || limit;
2976
- page = opts?.page || page;
2977
- }
2978
2972
  const currentPage = page;
2979
2973
  const nextPage = currentPage + 1;
2980
2974
  const prevPage = currentPage - 1 === 0 ? 1 : currentPage - 1;
2981
2975
  const offset = (page - 1) * limit;
2982
- this.limit(limit);
2983
- this.offset(offset);
2984
- let sql = this._queryBuilder().select();
2985
- const result = await this._queryStatement(sql);
2976
+ const result = await this
2977
+ .limit(limit)
2978
+ .offset(offset)
2979
+ .get();
2986
2980
  if (!result.length)
2987
2981
  return {
2988
2982
  meta: {
@@ -3040,9 +3034,82 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3040
3034
  * @property {boolean?} opts.distinct
3041
3035
  * @returns {promise<Pagination>}
3042
3036
  */
3043
- async paginate(opts) {
3037
+ async paginate(opts = {}) {
3044
3038
  return await this.pagination(opts);
3045
3039
  }
3040
+ /**
3041
+ * The 'cursorPagination' method is used to perform cursor-based pagination
3042
+ * on a set of database query results obtained through the Query Builder.
3043
+ *
3044
+ * It uses cursor-based pagination instead of offset pagination, making it
3045
+ * more efficient when navigating through large datasets.
3046
+ *
3047
+ * @param {Object?} opts query opts
3048
+ * @param {number?} opts.limit number of records per page, default is 15
3049
+ * @param {string?} opts.cursor cursor used to retrieve the next page
3050
+ * @param {boolean?} opts.distinct whether to retrieve distinct records
3051
+ * @returns {Promise<TCursorPagination>}
3052
+ */
3053
+ async cursorPagination(opts = {}) {
3054
+ const limit = this.$utils.softNumber(opts.limit ?? 15);
3055
+ if (opts.distinct) {
3056
+ this.distinct();
3057
+ }
3058
+ let cursor = null;
3059
+ if (opts.cursor) {
3060
+ try {
3061
+ cursor = JSON.parse(Buffer.from(opts.cursor, 'base64').toString('utf8'));
3062
+ }
3063
+ catch {
3064
+ throw new Error('Invalid cursor');
3065
+ }
3066
+ }
3067
+ ;
3068
+ const primaryKey = this.$state.get('PRIMARY_KEY');
3069
+ const results = await this
3070
+ .when(cursor != null, q => q.where(primaryKey, '>', cursor[primaryKey]))
3071
+ .orderBy(primaryKey, 'ASC')
3072
+ .limit(limit + 1)
3073
+ .get();
3074
+ const hasNextPage = results.length > limit;
3075
+ if (hasNextPage) {
3076
+ results.pop();
3077
+ }
3078
+ const lastResult = results[results.length - 1];
3079
+ const nextCursor = hasNextPage && lastResult
3080
+ ? Buffer.from(JSON.stringify({
3081
+ [primaryKey]: lastResult[primaryKey],
3082
+ timestamp: +new Date()
3083
+ })).toString('base64')
3084
+ : null;
3085
+ return {
3086
+ meta: {
3087
+ limit: limit,
3088
+ count: results.length,
3089
+ next: {
3090
+ cursor: nextCursor,
3091
+ has: hasNextPage,
3092
+ }
3093
+ },
3094
+ data: results,
3095
+ };
3096
+ }
3097
+ /**
3098
+ * The 'cursorPaginate' method is used to perform cursor-based pagination
3099
+ * on a set of database query results obtained through the Query Builder.
3100
+ *
3101
+ * It uses cursor-based pagination instead of offset pagination, making it
3102
+ * more efficient when navigating through large datasets.
3103
+ *
3104
+ * @param {Object?} opts query opts
3105
+ * @param {number?} opts.limit number of records per page, default is 15
3106
+ * @param {string?} opts.cursor cursor used to retrieve the next page
3107
+ * @param {boolean?} opts.distinct whether to retrieve distinct records
3108
+ * @returns {Promise<TCursorPagination>}
3109
+ */
3110
+ async cursorPaginate(opts = {}) {
3111
+ return await this.cursorPagination(opts);
3112
+ }
3046
3113
  /**
3047
3114
  *
3048
3115
  * The 'first' method is used to retrieve the first record that matches the query conditions.
@@ -3055,7 +3122,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3055
3122
  if (this.$state.get("EXCEPTS")?.length)
3056
3123
  this.select(...(await this.exceptColumns()));
3057
3124
  this.limit(1);
3058
- let sql = this._queryBuilder().select();
3125
+ let sql = this.getQueryBuilder().select();
3059
3126
  if (cb) {
3060
3127
  const callbackSql = cb(sql);
3061
3128
  if (callbackSql == null || callbackSql === "")
@@ -3092,7 +3159,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3092
3159
  if (this.$state.get("EXCEPTS")?.length)
3093
3160
  this.select(...(await this.exceptColumns()));
3094
3161
  this.limit(1);
3095
- let sql = this._queryBuilder().select();
3162
+ let sql = this.getQueryBuilder().select();
3096
3163
  const result = await this._queryStatement(sql);
3097
3164
  const data = result?.shift() || null;
3098
3165
  if (data == null) {
@@ -3129,7 +3196,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3129
3196
  if (this.$state.get("EXCEPTS")?.length) {
3130
3197
  this.select(...(await this.exceptColumns()));
3131
3198
  }
3132
- let sql = this._queryBuilder().select();
3199
+ let sql = this.getQueryBuilder().select();
3133
3200
  if (cb) {
3134
3201
  const callbackSql = cb(sql);
3135
3202
  if (callbackSql == null || callbackSql === "") {
@@ -3152,19 +3219,222 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3152
3219
  return await this.get(cb);
3153
3220
  }
3154
3221
  /**
3155
- * The 'toAsyncIterable' method is used to execute a database query and return the result set as an asynchronous iterable.
3222
+ * The 'explain' method is used to analyze the query execution plan
3223
+ * without executing the query itself.
3156
3224
  *
3157
- * It retrieves multiple records from a database table based on the criteria specified in the query.
3158
- * The optional callback function can be used to modify the generated SQL query before execution.
3225
+ * It retrieves the execution plan from the database and analyzes it
3226
+ * for potential performance issues such as full table scans, filesorts,
3227
+ * and temporary tables.
3228
+ * @param {string?} sql query for explain
3229
+ * @returns {Promise<TExplain>} query execution plan and analysis
3230
+ */
3231
+ async explain(sql) {
3232
+ if (!sql) {
3233
+ sql = this.toSQL();
3234
+ }
3235
+ const LARGE_SCAN_ROWS = 10_000;
3236
+ const qb = this.getQueryBuilder();
3237
+ const plan = await this.rawQuery(qb.explain(sql)).catch(() => []);
3238
+ const issues = [];
3239
+ const recommendations = [];
3240
+ for (const row of plan) {
3241
+ const text = JSON.stringify(row).toLowerCase();
3242
+ const textRow = Object.values(row)
3243
+ .filter(value => typeof value === 'string')
3244
+ .join(' ');
3245
+ const type = String(row.type ?? '').toLowerCase();
3246
+ const possibleKeys = row.possible_keys;
3247
+ const key = row.key;
3248
+ const rows = /^\d+(?:\.\d+)?$/.test(String(row.rows))
3249
+ ? Number(row.rows)
3250
+ : Number(textRow.match(/\brows=(\d+(?:\.\d+)?)/i)?.[1] ?? 0);
3251
+ const hasPossibleIndex = possibleKeys != null &&
3252
+ String(possibleKeys).trim() !== '';
3253
+ const hasUsedIndex = key != null &&
3254
+ String(key).trim() !== '';
3255
+ const hasFullScan = type === 'all' &&
3256
+ !hasPossibleIndex;
3257
+ if (hasFullScan) {
3258
+ issues.push({
3259
+ type: 'FULL_SCAN',
3260
+ severity: rows > LARGE_SCAN_ROWS ? 'warning' : 'info',
3261
+ message: `A full table scan was detected (${rows.toLocaleString()} rows).`,
3262
+ });
3263
+ recommendations.push('Consider adding an appropriate index for the query conditions.');
3264
+ }
3265
+ if (Number.isFinite(rows) && rows >= LARGE_SCAN_ROWS) {
3266
+ issues.push({
3267
+ type: 'LARGE_SCAN',
3268
+ severity: 'warning',
3269
+ message: `The query is estimated to scan ${rows} rows.`,
3270
+ });
3271
+ recommendations.push('Consider optimizing the query or adding an appropriate index.');
3272
+ }
3273
+ if (text.includes('filesort') ||
3274
+ text.includes('sort')) {
3275
+ issues.push({
3276
+ type: 'FILE_SORT',
3277
+ severity: 'warning',
3278
+ message: 'A sort operation was detected.',
3279
+ });
3280
+ recommendations.push('Consider an index that supports the WHERE and ORDER BY conditions.');
3281
+ }
3282
+ if (text.includes('temporary') ||
3283
+ text.includes('temp table')) {
3284
+ issues.push({
3285
+ type: 'TEMPORARY_TABLE',
3286
+ severity: 'warning',
3287
+ message: 'A temporary table was used.',
3288
+ });
3289
+ recommendations.push('Review GROUP BY, ORDER BY, DISTINCT, and JOIN conditions.');
3290
+ }
3291
+ const hasNoIndex = type === 'all' &&
3292
+ !hasPossibleIndex &&
3293
+ !hasUsedIndex;
3294
+ if (hasNoIndex) {
3295
+ issues.push({
3296
+ type: 'NO_INDEX',
3297
+ severity: 'warning',
3298
+ message: 'No index was used for this operation.',
3299
+ });
3300
+ recommendations.push('Consider adding an index for the query conditions.');
3301
+ }
3302
+ if (hasFullScan &&
3303
+ (text.includes('filter:') ||
3304
+ text.includes('using where'))) {
3305
+ issues.push({
3306
+ type: 'FILTER_AFTER_SCAN',
3307
+ severity: 'warning',
3308
+ message: 'Rows are filtered after scanning the table.',
3309
+ });
3310
+ recommendations.push('Consider an index that can apply the filter earlier.');
3311
+ }
3312
+ }
3313
+ const status = issues.some(issue => issue.severity === 'critical')
3314
+ ? 'critical'
3315
+ : issues.some(issue => issue.severity === 'warning')
3316
+ ? 'warning'
3317
+ : 'ok';
3318
+ return {
3319
+ sql,
3320
+ plan,
3321
+ analysis: {
3322
+ status,
3323
+ issues,
3324
+ recommendations: [...new Set(recommendations)],
3325
+ },
3326
+ };
3327
+ }
3328
+ /**
3329
+ * The 'lazy' method is used to retrieve and process records incrementally
3330
+ * without loading the entire result set into memory at once.
3159
3331
  *
3160
- * @param {Function?} cb callback function return query sql
3161
- * @returns {AsyncIterable<any>}
3332
+ * It retrieves records in batches based on the specified limit and invokes
3333
+ * the callback for each record. The process continues until all records
3334
+ * have been retrieved and processed.
3335
+ *
3336
+ * The optional delayMs can be used to add a delay between each batch query,
3337
+ * which can help reduce database load when processing a large number of records.
3338
+ *
3339
+ * @param {Function} callback callback function that receives each retrieved record
3340
+ * @param {Object?} opts query opts
3341
+ * @param {number?} opts.limit number of records to retrieve per query
3342
+ * @param {number?} opts.offset number of records to skip before processing
3343
+ * @param {number?} opts.delayMs delay in milliseconds between each batch
3344
+ * @returns {Promise<void>}
3162
3345
  */
3163
- async *toAsyncIterable(cb) {
3164
- if (this.$state.get("VOID"))
3346
+ async lazy(callback, opts = {}) {
3347
+ const limit = opts.limit ?? 100;
3348
+ const delayMs = opts.delayMs ?? 0;
3349
+ let offset = opts.offset ?? 0;
3350
+ while (true) {
3351
+ const results = await this
3352
+ .limit(limit)
3353
+ .offset(offset)
3354
+ .get();
3355
+ if (results.length === 0) {
3356
+ break;
3357
+ }
3358
+ for (const result of results) {
3359
+ await callback(result);
3360
+ }
3361
+ if (results.length < limit) {
3362
+ break;
3363
+ }
3364
+ offset += results.length;
3365
+ if (delayMs > 0) {
3366
+ await new Promise(resolve => setTimeout(resolve, delayMs));
3367
+ }
3368
+ }
3369
+ }
3370
+ /**
3371
+ * The 'chunk' method is used to retrieve records from the database in chunks
3372
+ * and process each chunk through a callback function.
3373
+ *
3374
+ * It retrieves records in batches based on the specified limit and invokes
3375
+ * the callback with each batch of records. The process continues until all
3376
+ * records have been retrieved and processed.
3377
+ *
3378
+ * The optional delayMs can be used to add a delay between each batch query,
3379
+ * which can help reduce database load when processing a large number of records.
3380
+ *
3381
+ * @param {Function} callback callback function that receives the retrieved records
3382
+ * @param {Object?} opts query opts
3383
+ * @param {number?} opts.limit number of records to retrieve per chunk
3384
+ * @param {number?} opts.offset number of records to skip before processing
3385
+ * @param {number?} opts.delayMs delay in milliseconds between each batch
3386
+ * @returns {Promise<void>}
3387
+ */
3388
+ async chunk(callback, opts = {}) {
3389
+ const limit = opts.limit ?? 100;
3390
+ const delayMs = opts.delayMs ?? 0;
3391
+ let offset = opts.offset ?? 0;
3392
+ while (true) {
3393
+ const results = await this
3394
+ .limit(limit)
3395
+ .offset(offset)
3396
+ .get();
3397
+ if (results.length === 0) {
3398
+ break;
3399
+ }
3400
+ await callback(results);
3401
+ if (results.length < limit) {
3402
+ break;
3403
+ }
3404
+ offset += results.length;
3405
+ if (delayMs > 0) {
3406
+ await new Promise(resolve => setTimeout(resolve, delayMs));
3407
+ }
3408
+ }
3409
+ }
3410
+ /**
3411
+ * The 'stream' method is used to executes a SQL statement and asynchronously yields result rows.
3412
+ *
3413
+ * @returns {AsyncGenerator<T>} An async generator that yields result rows.
3414
+ *
3415
+ * @example
3416
+ * ```ts
3417
+ * import { DB } from "tspace-mysql";
3418
+ *
3419
+ * for await (const row of new DB('users').stream()) {
3420
+ * console.log(row);
3421
+ * }
3422
+ * ```
3423
+ */
3424
+ async *stream() {
3425
+ if (this.$state.get('VOID')) {
3165
3426
  return yield* [];
3166
- const results = await this.get(cb);
3167
- return yield* results;
3427
+ }
3428
+ const sql = this.toString();
3429
+ if (this.$state.get("DEBUG")) {
3430
+ const startTime = +new Date();
3431
+ const results = await this.$pool.stream(sql);
3432
+ const endTime = +new Date();
3433
+ this.$utils.consoleDebug(sql, false, this.$state.get("NODE"));
3434
+ this.$utils.consoleExec(startTime, endTime);
3435
+ return yield* results;
3436
+ }
3437
+ return yield* await this.$pool.stream(sql);
3168
3438
  }
3169
3439
  /**
3170
3440
  * The 'toArray' method is used to execute a database query and retrieve the result set that matches the query conditions.
@@ -3177,7 +3447,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3177
3447
  */
3178
3448
  async toArray(column = "id") {
3179
3449
  this.selectRaw(`${this.bindColumn(column)}`);
3180
- const sql = this._queryBuilder().select();
3450
+ const sql = this.getQueryBuilder().select();
3181
3451
  const result = await this._queryStatement(sql);
3182
3452
  const toArray = result.map((data) => data[column]);
3183
3453
  return this._resultHandler(toArray);
@@ -3218,7 +3488,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3218
3488
  ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3219
3489
  : `${this.bindColumn(column)}`;
3220
3490
  this.selectRaw(`${this.$constants("COUNT")}(${column}) ${this.$constants(`${this.$constants("AS")}`)} \`aggregate\``);
3221
- const sql = this._queryBuilder().select();
3491
+ const sql = this.getQueryBuilder().select();
3222
3492
  const result = await this._queryStatement(sql);
3223
3493
  return Number(this._resultHandler(result.reduce((prev, cur) => prev + Number(cur?.aggregate ?? 0), 0) || 0));
3224
3494
  }
@@ -3235,7 +3505,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3235
3505
  ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3236
3506
  : `${this.bindColumn(column)}`;
3237
3507
  this.selectRaw(`${this.$constants("AVG")}(${column}) ${this.$constants("AS")} \`aggregate\``);
3238
- const sql = this._queryBuilder().select();
3508
+ const sql = this.getQueryBuilder().select();
3239
3509
  const result = await this._queryStatement(sql);
3240
3510
  return Number(this._resultHandler((result.reduce((prev, cur) => prev + Number(cur?.aggregate ?? 0), 0) ||
3241
3511
  0) / result.length));
@@ -3253,7 +3523,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3253
3523
  ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3254
3524
  : `${this.bindColumn(column)}`;
3255
3525
  this.selectRaw(`${this.$constants("SUM")}(${column}) ${this.$constants("AS")} \`aggregate\``);
3256
- const sql = this._queryBuilder().select();
3526
+ const sql = this.getQueryBuilder().select();
3257
3527
  const result = await this._queryStatement(sql);
3258
3528
  return Number(this._resultHandler(result.reduce((prev, cur) => prev + Number(cur?.aggregate ?? 0), 0) || 0));
3259
3529
  }
@@ -3270,7 +3540,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3270
3540
  ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3271
3541
  : `${this.bindColumn(column)}`;
3272
3542
  this.selectRaw(`${this.$constants("MAX")}(${column}) ${this.$constants("AS")} \`aggregate\``);
3273
- const sql = this._queryBuilder().select();
3543
+ const sql = this.getQueryBuilder().select();
3274
3544
  const result = await this._queryStatement(sql);
3275
3545
  return Number(this._resultHandler(result.sort((a, b) => b?.aggregate - a?.aggregate)[0]?.aggregate || 0));
3276
3546
  }
@@ -3287,7 +3557,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3287
3557
  ? `${this.$constants("DISTINCT")} ${this.bindColumn(column)}`
3288
3558
  : `${this.bindColumn(column)}`;
3289
3559
  this.selectRaw(`${this.$constants("MIN")}(${column}) ${this.$constants("AS")} \`aggregate\``);
3290
- const sql = this._queryBuilder().select();
3560
+ const sql = this.getQueryBuilder().select();
3291
3561
  const result = await this._queryStatement(sql);
3292
3562
  return Number(this._resultHandler(result.sort((a, b) => a?.aggregate - b?.aggregate)[0]?.aggregate || 0));
3293
3563
  }
@@ -3303,7 +3573,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3303
3573
  }
3304
3574
  this.limit(1);
3305
3575
  this.$state.set("DELETE", true);
3306
- const result = await this._actionStatement(this._queryBuilder().remove());
3576
+ const result = await this._actionStatement(this.getQueryBuilder().remove());
3307
3577
  return Boolean(this._resultHandler(result?.$meta?.affected ?? false));
3308
3578
  }
3309
3579
  /**
@@ -3317,7 +3587,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3317
3587
  throw new Error("can't delete without where condition");
3318
3588
  }
3319
3589
  this.$state.set("DELETE", true);
3320
- const result = await this._actionStatement(this._queryBuilder().remove());
3590
+ const result = await this._actionStatement(this.getQueryBuilder().remove());
3321
3591
  return Boolean(this._resultHandler(result?.$meta?.affected ?? false));
3322
3592
  }
3323
3593
  /**
@@ -3331,7 +3601,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3331
3601
  */
3332
3602
  async forceDelete() {
3333
3603
  this.$state.set("DELETE", true);
3334
- const result = await this._actionStatement(this._queryBuilder().remove());
3604
+ const result = await this._actionStatement(this.getQueryBuilder().remove());
3335
3605
  return Boolean(this._resultHandler(result?.$meta?.affected ?? false));
3336
3606
  }
3337
3607
  /**
@@ -3534,7 +3804,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3534
3804
  * @async
3535
3805
  */
3536
3806
  async getTables() {
3537
- const results = await this._queryStatement(this._queryBuilder().getTables(this.database()));
3807
+ const results = await this._queryStatement(this.getQueryBuilder().getTables(this.database()));
3538
3808
  return results
3539
3809
  .map((table) => String(Object.values(table)[0]))
3540
3810
  .filter((d) => d != null || d !== "");
@@ -3548,7 +3818,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3548
3818
  * @async
3549
3819
  */
3550
3820
  async hasTable(table) {
3551
- const result = await this._queryStatement(this._queryBuilder().hasTable({ database: this.database(), table }));
3821
+ const result = await this._queryStatement(this.getQueryBuilder().hasTable({ database: this.database(), table }));
3552
3822
  return Boolean(result[0]?.IS_EXISTS ?? false);
3553
3823
  }
3554
3824
  /**
@@ -3559,7 +3829,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3559
3829
  * @returns {Promise<Array>}
3560
3830
  */
3561
3831
  async showColumns(table = String(this.$state.get("TABLE_NAME")), options = {}) {
3562
- const sql = this._queryBuilder().getColumns({
3832
+ const sql = this.getQueryBuilder().getColumns({
3563
3833
  table,
3564
3834
  database: this.$database,
3565
3835
  });
@@ -3675,7 +3945,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3675
3945
  ].join('\n'));
3676
3946
  return false;
3677
3947
  }
3678
- const sql = this._queryBuilder().truncate(this.getTableName());
3948
+ const sql = this.getQueryBuilder().truncate(this.getTableName());
3679
3949
  if (!force) {
3680
3950
  console.log([
3681
3951
  `\x1b[33m`,
@@ -3727,10 +3997,10 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3727
3997
  }
3728
3998
  const sql = [
3729
3999
  db
3730
- ? this._queryBuilder().dropDatabase(table)
4000
+ ? this.getQueryBuilder().dropDatabase(table)
3731
4001
  : view
3732
- ? this._queryBuilder().dropView(table)
3733
- : this._queryBuilder().dropTable(table),
4002
+ ? this.getQueryBuilder().dropView(table)
4003
+ : this.getQueryBuilder().dropTable(table),
3734
4004
  ].join(" ");
3735
4005
  if (!force) {
3736
4006
  console.log([
@@ -3821,7 +4091,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3821
4091
  newInstance.$state.set("HAVING", null);
3822
4092
  return newInstance;
3823
4093
  }
3824
- _queryBuilder() {
4094
+ getQueryBuilder() {
3825
4095
  return this._buildQueryStatement();
3826
4096
  }
3827
4097
  _buildQueryStatement() {
@@ -3842,14 +4112,14 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3842
4112
  const result = await this.$pool.query(sql);
3843
4113
  const endTime = +new Date();
3844
4114
  if (this.$state.get("DEBUG")) {
3845
- this.$utils.consoleDebug(sql);
4115
+ this.$utils.consoleDebug(sql, false, this.$state.get("NODE"));
3846
4116
  this.$utils.consoleExec(startTime, endTime);
3847
4117
  }
3848
4118
  return result;
3849
4119
  }
3850
4120
  catch (err) {
3851
4121
  if (this.$state.get("DEBUG"))
3852
- this.$utils.consoleDebug(sql);
4122
+ this.$utils.consoleDebug(sql, false, this.$state.get("NODE"));
3853
4123
  throw err;
3854
4124
  }
3855
4125
  }
@@ -3859,14 +4129,14 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3859
4129
  const result = await this.$pool.query(sql);
3860
4130
  const endTime = +new Date();
3861
4131
  if (this.$state.get("DEBUG")) {
3862
- this.$utils.consoleDebug(sql);
4132
+ this.$utils.consoleDebug(sql, false, this.$state.get("NODE"));
3863
4133
  this.$utils.consoleExec(startTime, endTime);
3864
4134
  }
3865
4135
  return result;
3866
4136
  }
3867
4137
  catch (err) {
3868
4138
  if (this.$state.get("DEBUG"))
3869
- this.$utils.consoleDebug(sql);
4139
+ this.$utils.consoleDebug(sql, false, this.$state.get("NODE"));
3870
4140
  throw err;
3871
4141
  }
3872
4142
  }
@@ -3885,7 +4155,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3885
4155
  .exists();
3886
4156
  switch (check) {
3887
4157
  case false: {
3888
- const result = await this._actionStatement(this._queryBuilder().insert());
4158
+ const result = await this._actionStatement(this.getQueryBuilder().insert());
3889
4159
  if (this.$state.get("VOID") || !result) {
3890
4160
  return this._resultHandler(undefined);
3891
4161
  }
@@ -3903,7 +4173,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3903
4173
  }
3904
4174
  }
3905
4175
  async _insert() {
3906
- const result = await this._actionStatement(this._queryBuilder().insert());
4176
+ const result = await this._actionStatement(this.getQueryBuilder().insert());
3907
4177
  if (this.$state.get("VOID") || !result)
3908
4178
  return this._resultHandler(undefined);
3909
4179
  await this.$utils.wait(this.$state.get("AFTER_SAVE"));
@@ -3916,7 +4186,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3916
4186
  return this._resultHandler(results);
3917
4187
  }
3918
4188
  async _insertMultiple() {
3919
- const result = await this._actionStatement(this._queryBuilder().insert());
4189
+ const result = await this._actionStatement(this.getQueryBuilder().insert());
3920
4190
  if (this.$state.get("VOID") || !result)
3921
4191
  return this._resultHandler(undefined);
3922
4192
  await this.$utils.wait(this.$state.get("AFTER_SAVE"));
@@ -3943,7 +4213,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3943
4213
  .exists();
3944
4214
  switch (check) {
3945
4215
  case false: {
3946
- const result = await this._actionStatement(this._queryBuilder().insert());
4216
+ const result = await this._actionStatement(this.getQueryBuilder().insert());
3947
4217
  if (this.$state.get("VOID") || !result)
3948
4218
  return this._resultHandler(undefined);
3949
4219
  await this.$utils.wait(this.$state.get("AFTER_SAVE"));
@@ -3990,7 +4260,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
3990
4260
  .exists();
3991
4261
  switch (check) {
3992
4262
  case false: {
3993
- const result = await this._actionStatement(this._queryBuilder().insert());
4263
+ const result = await this._actionStatement(this.getQueryBuilder().insert());
3994
4264
  if (this.$state.get("VOID") || !result)
3995
4265
  return this._resultHandler(undefined);
3996
4266
  await this.$utils.wait(this.$state.get("AFTER_SAVE"));
@@ -4004,7 +4274,7 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
4004
4274
  return this._resultHandler(resultData);
4005
4275
  }
4006
4276
  case true: {
4007
- const result = await this._actionStatement(this._queryBuilder().update());
4277
+ const result = await this._actionStatement(this.getQueryBuilder().update());
4008
4278
  if (this.$state.get("VOID") || !result)
4009
4279
  return this._resultHandler(null);
4010
4280
  await this.$utils.wait(this.$state.get("AFTER_SAVE"));
@@ -4029,11 +4299,11 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
4029
4299
  async _update(ignoreWhere = false) {
4030
4300
  if (!this.$state.get("WHERE").length && !ignoreWhere)
4031
4301
  throw new Error("can't update without where condition");
4032
- const result = await this._actionStatement(this._queryBuilder().update());
4302
+ const result = await this._actionStatement(this.getQueryBuilder().update());
4033
4303
  if (this.$state.get("VOID") || !result)
4034
4304
  return this._resultHandler(undefined);
4035
4305
  await this.$utils.wait(this.$state.get("AFTER_SAVE"));
4036
- const sql = this._queryBuilder().select();
4306
+ const sql = this.getQueryBuilder().select();
4037
4307
  const data = await this._queryStatement(sql);
4038
4308
  if (data?.length > 1)
4039
4309
  return this._resultHandler(data || []);
@@ -4130,98 +4400,195 @@ class Builder extends AbstractBuilder_1.AbstractBuilder {
4130
4400
  ]);
4131
4401
  return this;
4132
4402
  }
4133
- _initialConnection() {
4134
- this.$utils = utils_1.utils;
4135
- this.$pool = (() => {
4136
- if (config_1.Config.CLUSTER) {
4137
- let poolCluster = Pool_1.Pool.clusterConnect();
4138
- if (poolCluster == null) {
4139
- throw new Error("Cluster connection has not been initialized. Please verify your confings");
4403
+ _initClusterPool() {
4404
+ let poolCluster = Pool_1.Pool.clusterConnect();
4405
+ if (poolCluster == null) {
4406
+ throw new Error("Cluster connection has not been initialized. Please verify your confings");
4407
+ }
4408
+ return {
4409
+ query: async (sql) => {
4410
+ // The .bind the cluster context to the query method,
4411
+ // Overriding only the local pool reference.
4412
+ if (poolCluster.primary == null) {
4413
+ const pool = poolCluster;
4414
+ // Reset the node state when the primary node is unavailable,
4415
+ // since it may have been set by the client.
4416
+ this.$state.set('NODE', null);
4417
+ return pool.query(sql);
4140
4418
  }
4141
- return {
4142
- query: async (sql) => {
4143
- const first = sql.trim().split(/\s+/)[0].toUpperCase();
4144
- const isReaded = [
4145
- this.$constants("SELECT"),
4146
- this.$constants("SHOW"),
4147
- this.$constants("DESCRIBE")
4148
- ].includes(first) &&
4149
- (!sql
4150
- .toUpperCase()
4151
- .includes(this.$constants("ROW_LEVEL_LOCK").update) ||
4152
- !sql
4153
- .toUpperCase()
4154
- .includes(this.$constants("ROW_LEVEL_LOCK").share));
4155
- if (isReaded) {
4156
- const length = poolCluster?.slaves?.length ?? 0;
4157
- const random = Math.floor(Math.random() * length);
4158
- return poolCluster?.query != null
4159
- ? poolCluster.query(sql)
4160
- : poolCluster?.slaves[random].query(sql);
4161
- }
4162
- const length = poolCluster?.masters?.length ?? 0;
4163
- const random = Math.floor(Math.random() * length);
4164
- return poolCluster.query != null
4165
- ? poolCluster.query(sql)
4166
- : poolCluster?.masters[random].query(sql);
4167
- },
4168
- get: () => poolCluster,
4169
- set: (conn) => {
4170
- if (conn.database != null) {
4171
- this.$database = conn.database();
4172
- }
4173
- poolCluster = conn;
4174
- return;
4175
- },
4176
- queryBuilder: () => {
4177
- /**
4178
- *
4179
- * queryBuilder can use every nodes
4180
- */
4181
- return poolCluster?.masters == null
4182
- ? poolCluster?.queryBuilder
4183
- : poolCluster?.masters[0]?.queryBuilder;
4184
- },
4185
- transaction: async () => {
4186
- return await poolCluster.masters[0].connection();
4187
- },
4188
- stream: async (sql) => {
4189
- return await poolCluster.masters[0].stream(sql);
4190
- },
4191
- };
4192
- }
4193
- let pool = Pool_1.Pool.connect();
4194
- return {
4195
- stream: async (sql) => {
4196
- return await pool.stream(sql);
4197
- },
4198
- transaction: async () => {
4199
- return await pool.connection();
4200
- },
4201
- query: async (sql) => {
4419
+ const node = this.$state.get('NODE');
4420
+ if (node?.type === 'primary') {
4421
+ this.useNode('primary');
4422
+ return poolCluster.primary.query(sql);
4423
+ }
4424
+ if (node?.type === 'replica') {
4425
+ const length = poolCluster.replicas.length;
4426
+ const nodeIndex = node.node
4427
+ ? node.node - 1
4428
+ : Math.floor(Math.random() * length);
4429
+ const pool = poolCluster
4430
+ .replicas[nodeIndex];
4431
+ if (pool == null) {
4432
+ throw new Error(`Replica node '${nodeIndex + 1}' not found`);
4433
+ }
4434
+ this.useNode('replica', { node: nodeIndex + 1 });
4202
4435
  return pool.query(sql);
4203
- },
4204
- get: () => pool,
4205
- set: (conn) => {
4206
- if (conn.database != null) {
4207
- this.$database = conn.database();
4436
+ }
4437
+ const first = sql
4438
+ .trim()
4439
+ .split(/\s+/)[0].toUpperCase();
4440
+ const isRowLock = Object.values(this.$constants("ROW_LEVEL_LOCK")).some(lock => sql.toUpperCase().includes(lock));
4441
+ // Row-level locked SELECTs (e.g. FOR UPDATE, FOR SHARE) acquire database locks,
4442
+ // so they are not considered read-only queries and should be handled as write/locking operations.
4443
+ const isReaded = [
4444
+ this.$constants("SELECT"),
4445
+ this.$constants("SHOW"),
4446
+ this.$constants("DESCRIBE")
4447
+ ].includes(first);
4448
+ if (isReaded && !isRowLock) {
4449
+ const length = poolCluster.replicas.length ?? 0;
4450
+ const nodeIndex = Math.floor(Math.random() * length);
4451
+ this.useNode('replica', { node: nodeIndex + 1 });
4452
+ return poolCluster.replicas[nodeIndex].query(sql);
4453
+ }
4454
+ this.useNode('primary');
4455
+ return poolCluster.primary.query(sql);
4456
+ },
4457
+ get: () => poolCluster,
4458
+ set: (conn) => {
4459
+ if (conn.database != null) {
4460
+ this.$database = conn.database();
4461
+ }
4462
+ poolCluster = conn;
4463
+ return;
4464
+ },
4465
+ queryBuilder: () => {
4466
+ // The .bind the cluster context to the query method,
4467
+ // Overriding only the local pool reference.
4468
+ if (poolCluster.primary == null) {
4469
+ const pool = poolCluster;
4470
+ return pool.queryBuilder;
4471
+ }
4472
+ return poolCluster.primary.queryBuilder;
4473
+ },
4474
+ transaction: async () => {
4475
+ // The .bind the cluster context to the query method,
4476
+ // Overriding only the local pool reference.
4477
+ if (poolCluster.primary == null) {
4478
+ const pool = poolCluster;
4479
+ // Reset the node state when the primary node is unavailable,
4480
+ // since it may have been set by the client.
4481
+ this.$state.set('NODE', null);
4482
+ return await pool.connection();
4483
+ }
4484
+ const node = this.$state.get('NODE');
4485
+ if (node?.type === 'primary') {
4486
+ return await poolCluster.primary.connection();
4487
+ }
4488
+ if (node?.type === 'replica') {
4489
+ const length = poolCluster.replicas.length;
4490
+ const nodeIndex = node.node
4491
+ ? node.node - 1
4492
+ : Math.floor(Math.random() * length);
4493
+ const pool = poolCluster
4494
+ .replicas[nodeIndex];
4495
+ if (pool == null) {
4496
+ throw new Error(`Replica node '${nodeIndex + 1}' not found`);
4208
4497
  }
4209
- pool = conn;
4210
- return;
4211
- },
4212
- queryBuilder: () => pool.queryBuilder,
4213
- };
4214
- })();
4215
- this.$state = new StateManager_1.StateManager("default");
4216
- this.$constants = ((name) => {
4217
- if (name == null)
4498
+ return await pool.connection();
4499
+ }
4500
+ return await poolCluster.primary.connection();
4501
+ },
4502
+ stream: async (sql) => {
4503
+ // The .bind the cluster context to the query method,
4504
+ // Overriding only the local pool reference.
4505
+ if (poolCluster.primary == null) {
4506
+ const pool = poolCluster;
4507
+ return pool.stream(sql);
4508
+ }
4509
+ const node = this.$state.get('NODE');
4510
+ if (node?.type === 'primary') {
4511
+ return poolCluster.primary.stream(sql);
4512
+ }
4513
+ if (node?.type === 'replica') {
4514
+ const length = poolCluster.replicas.length;
4515
+ const nodeIndex = node.node
4516
+ ? node.node - 1
4517
+ : Math.floor(Math.random() * length);
4518
+ const pool = poolCluster
4519
+ .replicas[nodeIndex];
4520
+ if (pool == null) {
4521
+ throw new Error(`Replica node '${nodeIndex + 1}' not found`);
4522
+ }
4523
+ return pool.stream(sql);
4524
+ }
4525
+ const first = sql
4526
+ .trim()
4527
+ .split(/\s+/)[0].toUpperCase();
4528
+ const isRowLock = Object.values(this.$constants("ROW_LEVEL_LOCK")).some(lock => sql.toUpperCase().includes(lock));
4529
+ // Row-level locked SELECTs (e.g. FOR UPDATE, FOR SHARE) acquire database locks,
4530
+ // so they are not considered read-only queries and should be handled as write/locking operations.
4531
+ const isReaded = [
4532
+ this.$constants("SELECT"),
4533
+ this.$constants("SHOW"),
4534
+ this.$constants("DESCRIBE")
4535
+ ].includes(first) && !isRowLock;
4536
+ if (isReaded) {
4537
+ const length = poolCluster.replicas.length ?? 0;
4538
+ const nodeIndex = Math.floor(Math.random() * length);
4539
+ this.useNode('replica', { node: nodeIndex + 1 });
4540
+ return poolCluster.replicas[nodeIndex].stream(sql);
4541
+ }
4542
+ this.useNode('primary');
4543
+ return poolCluster.primary.stream(sql);
4544
+ },
4545
+ };
4546
+ }
4547
+ _initSinglePool() {
4548
+ let pool = Pool_1.Pool.connect();
4549
+ return {
4550
+ transaction: async () => {
4551
+ return await pool.connection();
4552
+ },
4553
+ query: async (sql) => {
4554
+ return pool.query(sql);
4555
+ },
4556
+ get: () => pool,
4557
+ set: (conn) => {
4558
+ if (conn.database != null) {
4559
+ this.$database = conn.database();
4560
+ }
4561
+ pool = conn;
4562
+ return;
4563
+ },
4564
+ queryBuilder: () => pool.queryBuilder,
4565
+ stream: async (sql) => {
4566
+ return await pool.stream(sql);
4567
+ },
4568
+ };
4569
+ }
4570
+ _initPool() {
4571
+ return this.$cluster
4572
+ ? this._initClusterPool()
4573
+ : this._initSinglePool();
4574
+ }
4575
+ _initConstants() {
4576
+ return ((name) => {
4577
+ if (name == null) {
4218
4578
  return constants_1.CONSTANTS;
4579
+ }
4219
4580
  if (!Object.prototype.hasOwnProperty.call(constants_1.CONSTANTS, name)) {
4220
- throw new Error(`Not found that constant : '${String(name)}'`);
4581
+ throw new Error(`Constant not found: '${String(name)}'`);
4221
4582
  }
4222
4583
  return constants_1.CONSTANTS[name];
4223
4584
  });
4224
4585
  }
4586
+ _initBuilder() {
4587
+ this.$utils = utils_1.utils;
4588
+ this.$pool = this._initPool();
4589
+ this.$state = new StateManager_1.StateManager("default");
4590
+ this.$constants = this._initConstants();
4591
+ }
4225
4592
  }
4226
4593
  exports.Builder = Builder;
4227
4594
  exports.default = Builder;