tspace-mysql 1.9.4 → 1.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +282 -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 +252 -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 +472 -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 +332 -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
@@ -34,7 +34,6 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.DB = void 0;
37
- const sql_formatter_1 = require("sql-formatter");
38
37
  const AbstractDB_1 = require("./Abstracts/AbstractDB");
39
38
  const StateManager_1 = require("./StateManager");
40
39
  const Package_1 = require("../core/Package");
@@ -238,45 +237,9 @@ class DB extends AbstractDB_1.AbstractDB {
238
237
  return await new this().query(sql, parameters);
239
238
  }
240
239
  /**
241
- * The 'stream' method is used to executes a SQL statement and asynchronously yields result rows.
242
- *
243
- * @param {string} sql - The SQL statement to execute.
244
- * @returns {AsyncGenerator<T>} An async generator that yields result rows.
245
- *
246
- * @example
247
- * ```ts
248
- * import { DB } from "tspace-mysql";
249
- *
250
- * for await (const row of DB.stream('SELECT * FROM users')) {
251
- * console.log(row);
252
- * }
253
- * ```
254
- */
255
- async *stream(sql, parameters = {}) {
256
- const boundSql = this.$utils
257
- .bindingParameters(sql, parameters, { raw: false });
258
- yield* await this.$pool.stream(boundSql);
259
- }
260
- /**
261
- * The 'stream' method is used to executes a SQL statement and asynchronously yields result rows.
240
+ * The 'from' method is used to define the from table name.
262
241
  *
263
242
  * @static
264
- * @param {string} sql - The SQL statement to execute.
265
- * @returns {AsyncGenerator<T>} An async generator that yields result rows.
266
- *
267
- * @example
268
- * ```ts
269
- * import { DB } from "tspace-mysql";
270
- *
271
- * for await (const row of DB.stream('SELECT * FROM users')) {
272
- * console.log(row);
273
- * }
274
- */
275
- static async *stream(sql, parameters = {}) {
276
- yield* new this().stream(sql, parameters);
277
- }
278
- /**
279
- * The 'from' method is used to define the from table name.
280
243
  * @param {string} table table name
281
244
  * @returns {this} this
282
245
  */
@@ -285,6 +248,8 @@ class DB extends AbstractDB_1.AbstractDB {
285
248
  }
286
249
  /**
287
250
  * The 'table' method is used to define the table name.
251
+ *
252
+ * @static
288
253
  * @param {string} table table name
289
254
  * @returns {DB} DB
290
255
  */
@@ -294,6 +259,7 @@ class DB extends AbstractDB_1.AbstractDB {
294
259
  /**
295
260
  * The 'alias' method is used to set the table name.
296
261
  *
262
+ * @static
297
263
  * @param {string} sql raw sql from make a new alias for this table
298
264
  * @param {string} alias alias name
299
265
  * @returns {DB} DB
@@ -301,6 +267,15 @@ class DB extends AbstractDB_1.AbstractDB {
301
267
  static alias(sql, alias) {
302
268
  return new this().alias(sql, alias);
303
269
  }
270
+ /**
271
+ *
272
+ * @static
273
+ * @override
274
+ * @returns {this} this
275
+ */
276
+ static dd(debug = true) {
277
+ return new this().dd(debug);
278
+ }
304
279
  /**
305
280
  * The 'jsonObject' method is used to specify select data to JSON objects.
306
281
  * @param {string} object table name
@@ -327,6 +302,7 @@ class DB extends AbstractDB_1.AbstractDB {
327
302
  }
328
303
  /**
329
304
  * The 'jsonObject' method is used to specify select data to JSON objects.
305
+ *
330
306
  * @static
331
307
  * @param {string} object table name
332
308
  * @param {string} alias
@@ -337,6 +313,7 @@ class DB extends AbstractDB_1.AbstractDB {
337
313
  }
338
314
  /**
339
315
  * The 'JSONObject' method is used to specify select data to JSON objects.
316
+ *
340
317
  * @param {string} object table name
341
318
  * @param {string} alias
342
319
  * @returns {string} string
@@ -346,6 +323,7 @@ class DB extends AbstractDB_1.AbstractDB {
346
323
  }
347
324
  /**
348
325
  * The 'JSONObject' method is used to specify select data to JSON objects.
326
+ *
349
327
  * @static
350
328
  * @param {string} object table name
351
329
  * @param {string} alias
@@ -364,6 +342,7 @@ class DB extends AbstractDB_1.AbstractDB {
364
342
  }
365
343
  /**
366
344
  * The 'constants' method is used to return constants with key or none in 'DB' or 'Model'.
345
+ *
367
346
  * @static
368
347
  * @param {string} key
369
348
  * @returns {string | object} string || object
@@ -401,6 +380,7 @@ class DB extends AbstractDB_1.AbstractDB {
401
380
  }
402
381
  /**
403
382
  * select by cases
383
+ *
404
384
  * @static
405
385
  * @param {arrayObject} cases array object {when , then }
406
386
  * @param {string?} final else condition
@@ -410,19 +390,25 @@ class DB extends AbstractDB_1.AbstractDB {
410
390
  return new this().caseUpdate(cases, final);
411
391
  }
412
392
  /**
413
- * The 'generateUUID' methid is used to generate a universal unique identifier.
393
+ * The 'generateUUID' methid is used to generate a universal unique identifier (UUID).
394
+ *
395
+ * @param options - Options for UUID generation.
396
+ * @param options.v - UUID version to generate: 4 (random) or 7 (time-ordered). Defaults to 7.
414
397
  * @returns {string} string
415
398
  */
416
- generateUUID() {
417
- return this.$utils.generateUUID();
399
+ generateUUID({ v } = {}) {
400
+ return this.$utils.generateUUID(v);
418
401
  }
419
402
  /**
420
- * The 'generateUUID' methid is used to generate a universal unique identifier.
403
+ * The 'generateUUID' methid is used to generate a universal unique identifier (UUID).
404
+ *
405
+ * @param options - Options for UUID generation.
406
+ * @param options.v - UUID version to generate: 4 (random) or 7 (time-ordered). Defaults to 7.
421
407
  * @static
422
408
  * @returns {string} string
423
409
  */
424
- static generateUUID() {
425
- return new this().generateUUID();
410
+ static generateUUID({ v } = {}) {
411
+ return new this().generateUUID({ v });
426
412
  }
427
413
  /**
428
414
  * The 'snakeCase' methid is used to covert value to snakeCase pattern.
@@ -461,6 +447,8 @@ class DB extends AbstractDB_1.AbstractDB {
461
447
  }
462
448
  /**
463
449
  * The 'escape' methid is used to escaping SQL injections.
450
+ *
451
+ * @static
464
452
  * @returns {string} string
465
453
  */
466
454
  static escape(value) {
@@ -475,6 +463,8 @@ class DB extends AbstractDB_1.AbstractDB {
475
463
  }
476
464
  /**
477
465
  * The 'escapeXSS' methid is used to escaping XSS characters.
466
+ *
467
+ * @static
478
468
  * @returns {string} string
479
469
  */
480
470
  static escapeXSS(value) {
@@ -598,9 +588,8 @@ class DB extends AbstractDB_1.AbstractDB {
598
588
  *
599
589
  * Transactions are typically used when you want to ensure that a series of database operations either all succeed or all fail together,
600
590
  * ensuring data integrity.
601
- * @param {object} options
602
- * @property {number | undefined} options.primaryId
603
- * @property {number | undefined} options.nodeId
591
+ *
592
+ * @param {TPoolConnected} pool
604
593
  * @returns {ConnectionTransaction} object - Connection for the transaction
605
594
  * @type {object} connection
606
595
  * @property {function} connection.query - execute query sql then release connection to pool
@@ -608,29 +597,9 @@ class DB extends AbstractDB_1.AbstractDB {
608
597
  * @property {function} connection.commit - commit transaction of query
609
598
  * @property {function} connection.rollback - rollback transaction of query
610
599
  */
611
- async beginTransaction(options) {
612
- if (this.$cluster) {
613
- const cluster = new Pool_1.PoolConnection().clusterConnect();
614
- const masters = cluster.masters;
615
- if (!masters.length) {
616
- throw new Error("No Master available in cluster");
617
- }
618
- const length = masters.length;
619
- let selectedIndex = 0;
620
- if (options?.nodeId != null) {
621
- if (options.nodeId > length) {
622
- throw new Error(`Invalid nodeId ${options.nodeId}. Cluster has only ${length} master node(s).`);
623
- }
624
- selectedIndex = options.nodeId - 1;
625
- }
626
- else if (options?.primaryId != null) {
627
- selectedIndex = Math.round(options.primaryId % length);
628
- }
629
- const writer = masters[selectedIndex];
630
- if (writer == null) {
631
- throw new Error("No Master available in cluster");
632
- }
633
- return await writer.connection();
600
+ async beginTransaction(pool) {
601
+ if (pool) {
602
+ return await pool.connection();
634
603
  }
635
604
  return await this.$pool.transaction();
636
605
  }
@@ -641,10 +610,9 @@ class DB extends AbstractDB_1.AbstractDB {
641
610
  *
642
611
  * Transactions are typically used when you want to ensure that a series of database operations either all succeed or all fail together,
643
612
  * ensuring data integrity.
644
- * @param {object} options
645
- * @property {number | undefined} options.primaryId
646
- * @property {number | undefined} options.nodeId
647
613
  * @static
614
+ *
615
+ * @param {TPoolConnected} pool
648
616
  * @returns {ConnectionTransaction} object - Connection for the transaction
649
617
  * @type {object} connection
650
618
  * @property {function} connection.query - execute query sql then release connection to pool
@@ -652,11 +620,11 @@ class DB extends AbstractDB_1.AbstractDB {
652
620
  * @property {function} connection.commit - commit transaction of query
653
621
  * @property {function} connection.rollback - rollback transaction of query
654
622
  */
655
- static async beginTransaction(options) {
656
- return await new this().beginTransaction(options);
623
+ static async beginTransaction(pool) {
624
+ return await new this().beginTransaction(pool);
657
625
  }
658
626
  /**
659
- * Execute a database transaction.
627
+ * The 'transaction' is a method used to Execute a database transaction.
660
628
  *
661
629
  * This method will:
662
630
  * - Acquire a connection from the pool
@@ -672,8 +640,8 @@ class DB extends AbstractDB_1.AbstractDB {
672
640
  * @returns {Promise<T>} The result returned from the handler.
673
641
  *
674
642
  */
675
- async transaction(handler) {
676
- const trx = await this.$pool.transaction();
643
+ async transaction(handler, { pool } = {}) {
644
+ const trx = await this.beginTransaction(pool);
677
645
  try {
678
646
  await trx.startTransaction();
679
647
  const results = await handler(trx);
@@ -684,9 +652,12 @@ class DB extends AbstractDB_1.AbstractDB {
684
652
  await trx.rollback();
685
653
  throw err;
686
654
  }
655
+ finally {
656
+ await trx.end();
657
+ }
687
658
  }
688
659
  /**
689
- * Execute a database transaction.
660
+ * The 'transaction' is a method used to Execute a database transaction.
690
661
  *
691
662
  * This method will:
692
663
  * - Acquire a connection from the pool
@@ -695,6 +666,7 @@ class DB extends AbstractDB_1.AbstractDB {
695
666
  * - Commit if successful
696
667
  * - Rollback if any error occurs
697
668
  *
669
+ * @static
698
670
  * @template T
699
671
  * @param {(conn: TConnection) => Promise<T>} handler - Async function that receives the transaction connection.
700
672
  * All queries inside this handler MUST use the provided `conn` instance.
@@ -702,8 +674,8 @@ class DB extends AbstractDB_1.AbstractDB {
702
674
  * @returns {Promise<T>} The result returned from the handler.
703
675
  *
704
676
  */
705
- static async transaction(handler) {
706
- return await new this().transaction(handler);
677
+ static async transaction(handler, { pool } = {}) {
678
+ return await new this().transaction(handler, { pool });
707
679
  }
708
680
  /**
709
681
  * The 'getActiveConnections' method is used to return active connections
@@ -712,12 +684,13 @@ class DB extends AbstractDB_1.AbstractDB {
712
684
  */
713
685
  async getActiveConnections() {
714
686
  const current = await new DB()
715
- .query(this._queryBuilder().getActiveConnections());
687
+ .query(this.getQueryBuilder().getActiveConnections());
716
688
  return Number(current[0]?.Connections || 0);
717
689
  }
718
690
  /**
719
691
  * The 'getActiveConnections' method is used to return active connections
720
692
  *
693
+ * @static
721
694
  * @returns {Promise<number>} this
722
695
  */
723
696
  static async getActiveConnections() {
@@ -730,512 +703,473 @@ class DB extends AbstractDB_1.AbstractDB {
730
703
  */
731
704
  async getMaxConnections() {
732
705
  const current = await new DB()
733
- .query(this._queryBuilder().getMaxConnections());
706
+ .query(this.getQueryBuilder().getMaxConnections());
734
707
  return Number(current[0]?.MaxConnections || 0);
735
708
  }
736
709
  /**
737
710
  * The 'getMaxConnections' method is used to return max connections
738
711
  *
712
+ * @static
739
713
  * @returns {Promise<number>} this
740
714
  */
741
715
  static async getMaxConnections() {
742
716
  return await new this().getMaxConnections();
743
717
  }
744
718
  /**
745
- * The 'removeProperties' method is used to removed some properties.
719
+ * This'clone' method is used to clone the current database into a new database
720
+ * on the same server or another server.
746
721
  *
747
- * @param {Array | Record} data
748
- * @param {string[]} propertiesToRemoves
749
- * @returns {Array | Record} this
722
+ * @property {string} database - Target database name.
723
+ * @property {string[]} excludes - Tables to exclude from the clone.
724
+ * @property {object} to - Target server connection.
725
+ * @property {string} to.host - Target server host.
726
+ * @property {number} to.port - Target server port.
727
+ * @property {string} to.username - Target server username.
728
+ * @property {string} to.password - Target server password.
729
+ * @returns {Promise<void>}
750
730
  */
751
- removeProperties(data, propertiesToRemoves) {
752
- const setNestedProperty = (obj, path, value) => {
753
- const segments = path.split(".");
754
- let currentObj = obj;
755
- for (let i = 0; i < segments.length - 1; i++) {
756
- const segment = segments[i];
757
- if (!currentObj.hasOwnProperty(segment)) {
758
- currentObj[segment] = {};
759
- }
760
- currentObj = currentObj[segment];
761
- }
762
- const lastSegment = segments[segments.length - 1];
763
- currentObj[lastSegment] = value;
764
- };
765
- const remove = (obj, propertiesToRemoves) => {
766
- const temp = JSON.parse(JSON.stringify(obj));
767
- for (const property of propertiesToRemoves) {
768
- if (property == null)
769
- continue;
770
- const properties = property.split(".");
771
- let current = temp;
772
- let afterProp = "";
773
- const props = [];
774
- for (let i = 0; i < properties.length - 1; i++) {
775
- const prop = properties[i];
776
- if (current[prop] == null)
777
- continue;
778
- props.push(prop);
779
- if (typeof current[prop] === "object" && current[prop] != null) {
780
- current = current[prop];
781
- afterProp = prop;
782
- continue;
731
+ async clone({ database, excludes, only, value, to }) {
732
+ const qb = this.getQueryBuilder();
733
+ const db = await new DB()
734
+ .debug(this.$state.get("DEBUG"))
735
+ .query(qb.getDatabase(database));
736
+ if (Object.values(db[0] ?? []).length) {
737
+ throw new Error(`This database : '${database}' is already exists`);
738
+ }
739
+ const raws = only
740
+ ? only
741
+ : await new DB()
742
+ .debug(this.$state.get("DEBUG"))
743
+ .getTables();
744
+ const tables = raws.filter(r => !excludes?.includes(r));
745
+ await new DB()
746
+ .debug(this.$state.get("DEBUG"))
747
+ .query(qb.createDatabase(database));
748
+ const connTarget = new DB().getConnection({
749
+ ...(to ?? this.$credentials),
750
+ database,
751
+ });
752
+ const createFks = [];
753
+ const createIndexs = [];
754
+ for (const table of tables) {
755
+ const schema = await new DB()
756
+ .debug(this.$state.get("DEBUG"))
757
+ .showSchema(table);
758
+ await new DB()
759
+ .debug(this.$state.get("DEBUG"))
760
+ .bind(connTarget)
761
+ .query(qb.createTable({
762
+ database,
763
+ table,
764
+ schema,
765
+ }));
766
+ const fks = await new DB()
767
+ .debug(this.$state.get("DEBUG"))
768
+ .getFKs(table);
769
+ for (const fk of fks) {
770
+ createFks.push(qb.addFK({
771
+ table: table,
772
+ tableRef: fk.RefTable,
773
+ constraint: fk.Constraint,
774
+ key: fk.Column,
775
+ foreign: {
776
+ references: fk.RefColumn,
777
+ onDelete: fk.OnDelete,
778
+ onUpdate: fk.OnUpdate,
783
779
  }
784
- delete current[prop];
785
- afterProp = prop;
780
+ }));
781
+ }
782
+ const indexs = await new DB()
783
+ .debug(this.$state.get("DEBUG"))
784
+ .getIndexes(table);
785
+ for (const index of indexs) {
786
+ createIndexs.push(qb.addIndex({
787
+ table: table,
788
+ name: index.IndexName,
789
+ columns: [index.Column]
790
+ }));
791
+ }
792
+ if (!value)
793
+ continue;
794
+ const pageSize = 100;
795
+ let offset = 0;
796
+ while (true) {
797
+ const values = await new DB(table)
798
+ .debug(this.$state.get("DEBUG"))
799
+ .limit(pageSize)
800
+ .offset(offset)
801
+ .get();
802
+ if (!values.length) {
803
+ break;
786
804
  }
787
- const lastProp = properties[properties.length - 1];
788
- if (Array.isArray(current)) {
789
- setNestedProperty(temp, props.join("."), this.removeProperties(current, [afterProp, lastProp]));
790
- continue;
805
+ await new DB(table)
806
+ .debug(this.$state.get("DEBUG"))
807
+ .createMultiple([...values])
808
+ .bind(connTarget)
809
+ .void()
810
+ .save();
811
+ offset += values.length;
812
+ if (values.length < pageSize) {
813
+ break;
791
814
  }
792
- if (current[lastProp] == null)
793
- continue;
794
- delete current[lastProp];
795
815
  }
796
- return temp;
797
- };
798
- if (Array.isArray(data)) {
799
- return data.map((obj) => remove(obj, propertiesToRemoves));
800
816
  }
801
- return remove(data, propertiesToRemoves);
802
- }
803
- /**
804
- * The 'removeProperties' method is used to removed some properties.
805
- *
806
- * @param {Array | Record} data
807
- * @param {string[]} propertiesToRemoves
808
- * @returns {Array | Record} this
809
- */
810
- static removeProperties(data, propertiesToRemoves) {
811
- return new this().removeProperties(data, propertiesToRemoves);
812
- }
813
- /**
814
- *
815
- * This 'backup' method is used to backup database intro new database same server or to another server
816
- * @type {Object} backup
817
- * @property {string} backup.database clone current 'db' in connection to this database
818
- * @type {object?} backup.to
819
- * @property {string} backup.to.host
820
- * @property {number} backup.to.port
821
- * @property {string} backup.to.username
822
- * @property {string} backup.to.password
823
- * @returns {Promise<void>}
824
- */
825
- async backup({ database, to }) {
826
- const tables = await this.getTables();
827
- const backup = await this._backup({ tables, database, to });
828
- const creating = async ({ table, values, }) => {
829
- try {
830
- await table();
831
- await values();
817
+ if (createFks.length) {
818
+ for (const createFk of createFks) {
819
+ await new DB()
820
+ .debug(this.$state.get("DEBUG"))
821
+ .bind(connTarget)
822
+ .query(createFk);
832
823
  }
833
- catch (e) { }
834
- };
835
- await Promise.all(backup.map((b) => creating({ table: b.table, values: b.values })));
824
+ }
825
+ if (createIndexs.length) {
826
+ for (const createIndex of createIndexs) {
827
+ await new DB()
828
+ .debug(this.$state.get("DEBUG"))
829
+ .bind(connTarget)
830
+ .query(createIndex);
831
+ }
832
+ }
836
833
  return;
837
834
  }
838
835
  /**
839
- *
840
- * This 'backup' method is used to backup database intro new database same server or to another server
841
- * @type {Object} backup
842
- * @property {string} backup.database clone current 'db' in connection to this database
843
- * @type {object?} backup.to
844
- * @property {string} backup.to.host
845
- * @property {number} backup.to.port
846
- * @property {string} backup.to.username
847
- * @property {string} backup.to.password
848
- * @returns {Promise<void>}
849
- */
850
- static async backup({ database, to }) {
851
- return new this().backup({ database, to });
836
+ * This'clone' method is used to clone the current database into a new database
837
+ * on the same server or another server.
838
+ *
839
+ * @static
840
+ * @property {string} database - Target database name.
841
+ * @property {string[]} excludes - Tables to exclude from the clone.
842
+ * @property {object} to - Target server connection.
843
+ * @property {string} to.host - Target server host.
844
+ * @property {number} to.port - Target server port.
845
+ * @property {string} to.username - Target server username.
846
+ * @property {string} to.password - Target server password.
847
+ * @returns {Promise<void>}
848
+ */
849
+ static async clone({ database, only, excludes, value, to }) {
850
+ if (excludes) {
851
+ return new this().clone({ database, excludes, value, to });
852
+ }
853
+ ;
854
+ return new this().clone({ database, only, value, to });
852
855
  }
853
856
  /**
854
857
  *
855
- * This 'backupToFile' method is used to backup database intro new ${file}.sql
856
- * @type {Object} backup
857
- * @property {string} backup.database
858
- * @property {string} backup.filePath
859
- * @type {object?} backup.connection
860
- * @property {string} backup.connection.host
861
- * @property {number} backup.connection.port
862
- * @property {number} backup.connection.database
863
- * @property {string} backup.connection.username
864
- * @property {string} backup.connection.password
858
+ * This 'dump' method is used to Dumps a database into a SQL file
859
+ * @type {Object} opt
860
+ * @property {string?} opt.database
861
+ * @property {string} opt.filePath
862
+ * @property {string[]} opt.excludes
863
+ * @property {boolean?} opt.value
865
864
  * @returns {Promise<void>}
866
865
  */
867
- async backupToFile({ filePath, database = `dump_${+new Date()}`, connection, }) {
868
- await this.$utils.wait(1000 * 5);
869
- const tables = await this.getTables();
870
- const sqlFormatted = (sql) => {
871
- const statements = sql
872
- .split(";")
873
- .map((s) => s.trim())
874
- .filter(Boolean);
875
- const formattedStatements = statements.map((stmt) => {
876
- if (stmt.includes("(")) {
877
- const firstParen = stmt.indexOf("(");
878
- const lastParen = stmt.lastIndexOf(")");
879
- if (firstParen === -1 || lastParen === -1)
880
- return stmt + ";";
881
- const prefix = stmt.slice(0, firstParen).trim();
882
- let columnsPart = stmt.slice(firstParen + 1, lastParen).trim();
883
- const colArray = [];
884
- let parenCount = 0;
885
- let start = 0;
886
- for (let i = 0; i < columnsPart.length; i++) {
887
- const char = columnsPart[i];
888
- if (char === "(")
889
- parenCount++;
890
- if (char === ")")
891
- parenCount--;
892
- if (char === "," && parenCount === 0) {
893
- colArray.push(columnsPart.slice(start, i).trim());
894
- start = i + 1;
895
- }
896
- }
897
- colArray.push(columnsPart.slice(start).trim());
898
- const seen = new Set();
899
- const uniqueColumns = colArray.filter((col) => {
900
- const colNameMatch = col.match(/"([\w]+)"/) || col.match(/([\w]+)/);
901
- const colName = colNameMatch ? colNameMatch[1] : col;
902
- if (seen.has(colName))
903
- return false;
904
- seen.add(colName);
905
- return true;
906
- });
907
- const formattedColumns = uniqueColumns
908
- .map((c) => " " + c)
909
- .join(",\n");
910
- return `${prefix} (\n${formattedColumns}\n)`;
911
- }
912
- else {
913
- return stmt;
914
- }
915
- });
916
- return formattedStatements.join(";\n\n");
917
- };
918
- const backup = (await this._backupToString({ tables, database })).map((b) => {
919
- return {
920
- table: [
921
- `\n--`,
922
- `-- Table structure for table '${b.name}'`,
923
- `--\n`,
924
- `${sqlFormatted(b.table())}`,
925
- ].join("\n") + ";",
926
- values: b.values().length
927
- ? [
928
- `\n--`,
929
- `-- Dumping data for table '${b.name}'`,
930
- `--\n`,
931
- `${b
932
- .values()
933
- .map((v) => `${v}`)
934
- .join(",\n")}`,
935
- ].join("\n")
936
- : "",
937
- };
938
- });
939
- if (connection != null && Object.keys(connection)?.length)
940
- this.connection(connection);
941
- let sql = [
866
+ async dump({ filePath, excludes, only, database = `dump_${+new Date()}`, value = false }) {
867
+ if (!filePath.toLowerCase().endsWith(".sql")) {
868
+ filePath += ".sql";
869
+ }
870
+ await Package_1.Package.fs.promises.mkdir(Package_1.Package.path.dirname(filePath), { recursive: true });
871
+ const raws = only ? only : await this.getTables();
872
+ const tables = raws.filter(r => !excludes?.includes(r));
873
+ const qb = this.getQueryBuilder();
874
+ const headers = [
942
875
  `--`,
943
876
  `-- tspace-mysql SQL Dump`,
944
877
  `-- https://www.npmjs.com/package/tspace-mysql`,
945
878
  `--`,
946
- `-- Host: mysql-db`,
879
+ `-- Driver: '${this.$driver}'`,
947
880
  `-- Generation Time: ${new Date()}\n`,
948
- `SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";`,
949
- `START TRANSACTION;`,
950
881
  `--`,
951
882
  `-- Database: '${database}'`,
952
883
  `--\n`,
953
- `${this.$constants("CREATE_DATABASE_NOT_EXISTS")} ${database};`,
954
- `USE ${database};`,
884
+ `${qb.createDatabase(database)};`,
885
+ `${qb.useDatabase(database)};`,
886
+ `--\n`,
955
887
  `-- --------------------------------------------------------`,
956
- ];
957
- for (const b of backup) {
958
- sql = [...sql, b.table];
959
- if (b.values) {
960
- sql = [...sql, b.values];
888
+ ].map(v => qb.format(v)).join('\n');
889
+ const stream = Package_1.Package.fs.createWriteStream(filePath, {
890
+ encoding: "utf8",
891
+ });
892
+ const write = async (data) => {
893
+ if (stream.write(data)) {
894
+ return;
895
+ }
896
+ await new Promise((resolve) => {
897
+ stream.once("drain", resolve);
898
+ });
899
+ };
900
+ const formatCreateTable = (table, createTable) => {
901
+ return [
902
+ `\n--`,
903
+ `-- Table structure for table '${table}'`,
904
+ `--`,
905
+ `${this.$utils.sqlFormatted(createTable)}`,
906
+ ].join("\n") + ";";
907
+ };
908
+ const formatInsertValues = (value, maxChunkSize = 1024 * 1024) => {
909
+ if (!value.length)
910
+ return "";
911
+ const result = [];
912
+ let buffer = "";
913
+ const line = String(value) + "\n";
914
+ if (buffer.length + line.length > maxChunkSize) {
915
+ if (buffer) {
916
+ result.push(buffer);
917
+ buffer = "";
918
+ }
919
+ }
920
+ buffer += line;
921
+ if (buffer) {
922
+ result.push(buffer);
923
+ }
924
+ return result.join("");
925
+ };
926
+ try {
927
+ stream.write(headers);
928
+ stream.write("\n");
929
+ const createFks = [];
930
+ const createIndexs = [];
931
+ const startTime = Date.now();
932
+ let totalRows = 0;
933
+ for (let i = 0; i < tables.length; i++) {
934
+ const qb = this.getQueryBuilder();
935
+ const table = tables[i];
936
+ const tableStartTime = Date.now();
937
+ const fks = await this.getFKs(table).catch(_ => []);
938
+ for (const fk of fks) {
939
+ createFks.push(qb.addFK({
940
+ table: table,
941
+ tableRef: fk.RefTable,
942
+ constraint: fk.Constraint,
943
+ key: fk.Column,
944
+ foreign: {
945
+ references: fk.RefColumn,
946
+ onDelete: fk.OnDelete,
947
+ onUpdate: fk.OnUpdate,
948
+ }
949
+ }));
950
+ }
951
+ const indexs = await this.getIndexes(table).catch(_ => []);
952
+ for (const index of indexs) {
953
+ createIndexs.push(qb.addIndex({
954
+ table: table,
955
+ name: index.IndexName,
956
+ columns: index.Column.split(',')
957
+ }));
958
+ }
959
+ const progress = Math.round(((i + 1) / tables.length) * 100);
960
+ console.log(`\n[${String(progress).padStart(3, " ")}%] ` +
961
+ `[${i + 1}/${tables.length}] ${table}`);
962
+ const schema = await this.showSchema(table);
963
+ const createTable = qb.createTable({
964
+ database,
965
+ table,
966
+ schema
967
+ });
968
+ await write(formatCreateTable(table, createTable));
969
+ await write("\n");
970
+ console.log(` ├─ schema ✓`);
971
+ if (!value) {
972
+ console.log(` └─ done in ${((Date.now() - tableStartTime) / 1000).toFixed(2)}s`);
973
+ continue;
974
+ }
975
+ const pageSize = 100;
976
+ let offset = 0;
977
+ let page = 0;
978
+ let tableRows = 0;
979
+ let wasWritten = false;
980
+ while (true) {
981
+ const values = await this.table(table)
982
+ .limit(pageSize)
983
+ .offset(offset)
984
+ .get();
985
+ if (!values.length) {
986
+ break;
987
+ }
988
+ if (!wasWritten) {
989
+ const hearder = `\n--\n` +
990
+ `-- Dumping data for table '${table}'\n` +
991
+ `--\n`;
992
+ await write(hearder);
993
+ wasWritten = true;
994
+ }
995
+ const sql = this.table(table)
996
+ .createMultiple([...values])
997
+ .toString();
998
+ await write(formatInsertValues(sql + ";"));
999
+ tableRows += values.length;
1000
+ totalRows += values.length;
1001
+ offset += pageSize;
1002
+ page++;
1003
+ if (values.length < pageSize) {
1004
+ break;
1005
+ }
1006
+ console.log(` ├─ page ${page} | rows: ${tableRows.toLocaleString()}`);
1007
+ }
1008
+ await write("\n");
1009
+ const elapsed = ((Date.now() - tableStartTime) / 1000).toFixed(2);
1010
+ console.log(` ├─ rows: ${tableRows.toLocaleString()}`);
1011
+ console.log(` ├─ pages: ${page}`);
1012
+ console.log(` └─ done in ${elapsed}s`);
1013
+ }
1014
+ if (createFks.length) {
1015
+ const header = `\n--\n` +
1016
+ `-- Foreign key constraints\n` +
1017
+ `--\n`;
1018
+ await write(header);
1019
+ for (const createFk of createFks) {
1020
+ await write(createFk + ";\n");
1021
+ }
961
1022
  }
1023
+ if (createIndexs.length) {
1024
+ const header = `\n--\n` +
1025
+ `-- Index key constraints\n` +
1026
+ `--\n`;
1027
+ await write(header);
1028
+ for (const createIndex of createIndexs) {
1029
+ await write(createIndex + ";\n");
1030
+ }
1031
+ }
1032
+ const tail = [
1033
+ `--`,
1034
+ `--`,
1035
+ `-- --------------------------------------------------------`,
1036
+ ].join('\n');
1037
+ await write("\n" + tail);
1038
+ const totalTime = ((Date.now() - startTime) / 1000).toFixed(2);
1039
+ console.log(`\n[DONE] Dump completed: ${tables.length} tables, ` +
1040
+ `${totalRows.toLocaleString()} rows, ${totalTime}s`);
1041
+ stream.end();
1042
+ await new Promise((resolve) => {
1043
+ stream.once("finish", resolve);
1044
+ });
1045
+ }
1046
+ catch (error) {
1047
+ stream.destroy();
1048
+ throw error;
962
1049
  }
963
- Package_1.Package.fs.writeFileSync(filePath, [...sql, "COMMIT;"].join("\n"));
964
1050
  return;
965
1051
  }
966
1052
  /**
1053
+ * This 'dump' method is used to Dumps a database into a SQL file
967
1054
  *
968
- * This 'backupToFile' method is used to backup database intro new ${file}.sql
969
- * @type {Object} backup
970
- * @property {string} backup.database
971
- * @property {string} backup.filePath
972
- * @type {object?} backup.connection
973
- * @property {string} backup.connection.host
974
- * @property {number} backup.connection.port
975
- * @property {number} backup.connection.database
976
- * @property {string} backup.connection.username
977
- * @property {string} backup.connection.password
1055
+ * @static
1056
+ * @type {Object} opt
1057
+ * @property {string?} opt.database
1058
+ * @property {string} opt.filePath
1059
+ * @property {string[]} opt.excludes
1060
+ * @property {boolean?} opt.value
978
1061
  * @returns {Promise<void>}
979
1062
  */
980
- static async backupToFile({ filePath, database, connection, }) {
981
- return new this().backupToFile({ filePath, database, connection });
1063
+ static async dump({ filePath, database, excludes, only, value, }) {
1064
+ if (excludes) {
1065
+ return new this().dump({ filePath, database, excludes, value });
1066
+ }
1067
+ ;
1068
+ return new this().dump({ filePath, database, only, value });
982
1069
  }
983
1070
  /**
1071
+ * This 'session' method is used to manage database session variables.
984
1072
  *
985
- * This 'backupSchemaToFile' method is used to backup database intro new ${file}.sql
986
- * @type {Object} backup
987
- * @property {string} backup.database
988
- * @property {string} backup.filePath
989
- * @type {object?} backup.connection
990
- * @property {string} backup.connection.host
991
- * @property {number} backup.connection.port
992
- * @property {number} backup.connection.database
993
- * @property {string} backup.connection.username
994
- * @property {string} backup.connection.password
995
- * @returns {Promise<void>}
996
- */
997
- async backupSchemaToFile({ filePath, database = `dump_${+new Date()}`, connection, }) {
998
- if (connection != null && Object.keys(connection)?.length)
999
- this.connection(connection);
1000
- await this.$utils.wait(1000 * 3);
1001
- const tables = await this.getTables();
1002
- const backup = (await this._backupToString({ tables, database })).map((b) => {
1003
- return {
1004
- table: (0, sql_formatter_1.format)(b.table(), {
1005
- language: "spark",
1006
- tabWidth: 2,
1007
- linesBetweenQueries: 1,
1008
- }) + "\n",
1009
- };
1010
- });
1011
- let sql = [
1012
- `SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";`,
1013
- `START TRANSACTION;`,
1014
- `SET time_zone = "+00:00";`,
1015
- `${this.$constants("CREATE_DATABASE_NOT_EXISTS")} \`${database}\`;`,
1016
- `USE \`${database}\`;`,
1017
- ];
1018
- for (const b of backup)
1019
- sql = [...sql, b.table];
1020
- Package_1.Package.fs.writeFileSync(filePath, [...sql, "COMMIT;"].join("\n"));
1021
- return;
1022
- }
1023
- /**
1073
+ * Provides methods to get and set session variables for the current
1074
+ * database connection.
1024
1075
  *
1025
- * This 'backupSchemaToFile' method is used to backup database intro new ${file}.sql
1026
- *
1027
- * @type {Object} backup
1028
- * @property {string} backup.database
1029
- * @property {string} backup.filePath
1030
- * @type {object?} backup.connection
1031
- * @property {string} backup.connection.host
1032
- * @property {number} backup.connection.port
1033
- * @property {number} backup.connection.database
1034
- * @property {string} backup.connection.username
1035
- * @property {string} backup.connection.password
1036
- * @returns {Promise<void>}
1037
- */
1038
- static async backupSchemaToFile({ filePath, database, connection, }) {
1039
- return new this().backupSchemaToFile({ filePath, database, connection });
1040
- }
1041
- /**
1076
+ * Supported drivers:
1077
+ * - MySQL
1078
+ * - MariaDB
1079
+ * - PostgreSQL
1080
+ * - SQLite
1042
1081
  *
1043
- * This 'backupTableToFile' method is used to backup database intro new ${file}.sql
1044
- *
1045
- * @type {Object} backup
1046
- * @property {string} backup.database
1047
- * @property {string} backup.filePath
1048
- * @type {object?} backup.connection
1049
- * @property {string} backup.connection.host
1050
- * @property {number} backup.connection.port
1051
- * @property {number} backup.connection.database
1052
- * @property {string} backup.connection.username
1053
- * @property {string} backup.connection.password
1054
- * @returns {Promise<void>}
1082
+ * MongoDB is not supported.
1083
+ *
1084
+ * @example
1085
+ * ```ts
1086
+ * await DB.session().set('db', 'primary');
1087
+ *
1088
+ * const value = await db.session().get('db');
1089
+ * console.log(value) // primary
1090
+ *
1091
+ * ```
1055
1092
  */
1056
- async backupTableToFile({ filePath, table, connection, }) {
1057
- if (connection != null && Object.keys(connection)?.length)
1058
- this.connection(connection);
1059
- /**
1060
- *
1061
- * wait for the connection to new db connected
1062
- */
1063
- await this.$utils.wait(1000 * 5);
1064
- const schemas = await this.showSchema(table);
1065
- const createTableSQL = [
1066
- `${this.$constants("CREATE_TABLE_NOT_EXISTS")}`,
1067
- `\`${table}\``,
1068
- `(${schemas.join(",")})`,
1069
- `${this.$constants("ENGINE")};`,
1070
- ];
1071
- const values = await this.showValues(table);
1072
- let valueSQL = [];
1073
- if (values.length) {
1074
- const columns = await this.showColumns(table);
1075
- valueSQL = [
1076
- `${this.$constants("INSERT")}`,
1077
- `\`${table}\``,
1078
- `(${columns.map((column) => `\`${column}\``).join(",")})`,
1079
- `${this.$constants("VALUES")} ${values.join(",")};`,
1080
- ];
1093
+ session() {
1094
+ if (this.driver() === 'mongodb') {
1095
+ throw new Error('Session is not supported for MongoDB. Use a different driver or disable sessions features.');
1081
1096
  }
1082
- const sql = [
1083
- (0, sql_formatter_1.format)(createTableSQL.join(" "), {
1084
- language: "mysql",
1085
- tabWidth: 2,
1086
- linesBetweenQueries: 1,
1087
- }) + "\n",
1088
- valueSQL.join(" "),
1089
- ];
1090
- Package_1.Package.fs.writeFileSync(filePath, [...sql, "COMMIT;"].join("\n"));
1091
- return;
1097
+ const self = this;
1098
+ const qb = this.getQueryBuilder();
1099
+ return {
1100
+ async get(name) {
1101
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
1102
+ throw new Error(`Invalid session variable name: ${name}`);
1103
+ }
1104
+ const raw = await self.query(qb.getSession(self.escape(name)));
1105
+ if (!Array.isArray(raw) || !raw[0]) {
1106
+ return null;
1107
+ }
1108
+ const session = (raw[0][name] ?? null);
1109
+ return session === '' ? null : session;
1110
+ },
1111
+ async set(name, value) {
1112
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
1113
+ throw new Error(`Invalid session variable name: ${name}`);
1114
+ }
1115
+ await self.query(qb.setSession(self.escape(name), self.escape(value)));
1116
+ return;
1117
+ },
1118
+ async delete(name) {
1119
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
1120
+ throw new Error(`Invalid session variable name: ${name}`);
1121
+ }
1122
+ await self.query(qb.deleteSession(self.escape(name)));
1123
+ return;
1124
+ },
1125
+ };
1092
1126
  }
1093
1127
  /**
1128
+ * This 'session' method is used to manage database session variables.
1094
1129
  *
1095
- * This 'backupTableSchemaToFile' method is used to backup database intro new ${file}.sql
1096
- * @type {Object} backup
1097
- * @property {string} backup.table
1098
- * @property {string} backup.filePath
1099
- * @type {object?} backup.connection
1100
- * @property {string} backup.connection.host
1101
- * @property {number} backup.connection.port
1102
- * @property {number} backup.connection.database
1103
- * @property {string} backup.connection.username
1104
- * @property {string} backup.connection.password
1105
- * @returns {Promise<void>}
1130
+ * Provides methods to get and set session variables for the current
1131
+ * database connection.
1132
+ *
1133
+ * Supported drivers:
1134
+ * - MySQL
1135
+ * - MariaDB
1136
+ * - PostgreSQL
1137
+ * - SQLite
1138
+ *
1139
+ * MongoDB is not supported.
1140
+ *
1141
+ * @static
1142
+ *
1143
+ * @example
1144
+ * ```ts
1145
+ * await DB.session().set('db', 'primary');
1146
+ *
1147
+ * const value = await db.session().get('db');
1148
+ * console.log(value) // primary
1149
+ *
1150
+ * ```
1106
1151
  */
1107
- static async backupTableToFile({ filePath, table, connection, }) {
1108
- return new this().backupTableToFile({ filePath, table, connection });
1152
+ static session() {
1153
+ return new this().session();
1109
1154
  }
1110
1155
  /**
1156
+ * This 'timestamp' method is used to convert a date into a timestamp.
1111
1157
  *
1112
- * This 'backupTableSchemaToFile' method is used to backup database intro new ${file}.sql
1113
- * @type {Object} backup
1114
- * @property {string} backup.database
1115
- * @property {string} backup.filePath
1116
- * @type {object?} backup.connection
1117
- * @property {string} backup.connection.host
1118
- * @property {number} backup.connection.port
1119
- * @property {number} backup.connection.database
1120
- * @property {string} backup.connection.username
1121
- * @property {string} backup.connection.password
1122
- * @returns {Promise<void>}
1158
+ * @type {string | Date} dateString
1159
+ * @returns {T.DateTime}
1123
1160
  */
1124
- async backupTableSchemaToFile({ filePath, table, connection, }) {
1125
- const schemas = await this.showSchema(table);
1126
- const createTableSQL = [
1127
- `${this.$constants("CREATE_TABLE_NOT_EXISTS")}`,
1128
- `\`${table}\``,
1129
- `(${schemas.join(",")})`,
1130
- `${this.$constants("ENGINE")};`,
1131
- ];
1132
- const sql = [createTableSQL.join(" ")];
1133
- if (connection != null && Object.keys(connection)?.length)
1134
- this.connection(connection);
1135
- await this.$utils.wait(1000 * 5);
1136
- Package_1.Package.fs.writeFileSync(filePath, (0, sql_formatter_1.format)(sql.join("\n"), {
1137
- language: "spark",
1138
- tabWidth: 2,
1139
- linesBetweenQueries: 1,
1140
- }));
1141
- return;
1161
+ timestamp(dateString) {
1162
+ return this.$utils.timestamp(dateString);
1142
1163
  }
1143
1164
  /**
1165
+ * This 'timestamp' method is used to convert a date into a timestamp.
1144
1166
  *
1145
- * This 'backupTableSchemaToFile' method is used to backup database intro new ${file}.sql
1146
- * @type {Object} backup
1147
- * @property {string} backup.table
1148
- * @property {string} backup.filePath
1149
- * @type {object?} backup.connection
1150
- * @property {string} backup.connection.host
1151
- * @property {number} backup.connection.port
1152
- * @property {number} backup.connection.database
1153
- * @property {string} backup.connection.username
1154
- * @property {string} backup.connection.password
1155
- * @returns {Promise<void>}
1167
+ * @static
1168
+ * @type {string | Date} dateString
1169
+ * @returns {T.DateTime}
1156
1170
  */
1157
- static async backupTableSchemaToFile({ filePath, table, connection, }) {
1158
- return new this().backupTableSchemaToFile({ filePath, table, connection });
1159
- }
1160
- async _backup({ tables, database, to, }) {
1161
- const backup = [];
1162
- const conn = await new DB().getConnection({ ...(to ?? this.$credentials) });
1163
- const db = await new DB()
1164
- .bind(conn)
1165
- .query(this._queryBuilder().getDatabase(database));
1166
- if (Object.values(db[0] ?? []).length) {
1167
- throw new Error(`This database : '${database}' is already exists`);
1168
- }
1169
- await new DB()
1170
- .bind(conn)
1171
- .query(`${this.$constants("CREATE_DATABASE")} \`${database}\``);
1172
- const connWithDatabase = await new DB().getConnection({
1173
- ...(to ?? this.$credentials),
1174
- database,
1175
- });
1176
- for (const table of tables) {
1177
- const schema = await new DB()
1178
- .debug(this.$state.get("DEBUG"))
1179
- .showSchema(table);
1180
- const values = await new DB(table).debug(this.$state.get("DEBUG")).get();
1181
- backup.push({
1182
- name: table == null ? "" : table,
1183
- table: async () => {
1184
- await new DB()
1185
- .debug(this.$state.get("DEBUG"))
1186
- .bind(connWithDatabase)
1187
- .query(this._queryBuilder().createTable({ database, table, schema }));
1188
- return;
1189
- },
1190
- values: async () => {
1191
- if (!values.length)
1192
- return;
1193
- const chunked = this.$utils.chunkArray([...values], 1000);
1194
- const promises = [];
1195
- for (const data of chunked) {
1196
- promises.push(() => {
1197
- return new DB(table)
1198
- .debug(this.$state.get("DEBUG"))
1199
- .createMultiple([...data])
1200
- .bind(connWithDatabase)
1201
- .void()
1202
- .save();
1203
- });
1204
- }
1205
- await Promise.all(promises.map((v) => v()));
1206
- return;
1207
- },
1208
- });
1209
- }
1210
- return backup;
1211
- }
1212
- async _backupToString({ tables, database, }) {
1213
- const backup = [];
1214
- for (const table of tables) {
1215
- const schema = await this.showSchema(table);
1216
- const values = await this.table(table).get();
1217
- // const values :any[] = []
1218
- backup.push({
1219
- name: table == null ? "" : table,
1220
- table: () => {
1221
- return this._queryBuilder().createTable({ database, table, schema });
1222
- },
1223
- values: () => {
1224
- if (!values.length)
1225
- return [];
1226
- const chunked = this.$utils.chunkArray([...values], values.length > 500 ? 500 : 10);
1227
- const str = [];
1228
- for (const data of chunked) {
1229
- const sql = this.table(table)
1230
- .createMultiple([...data])
1231
- .toString();
1232
- str.push(sql);
1233
- }
1234
- return str;
1235
- },
1236
- });
1237
- }
1238
- return backup;
1171
+ static timestamp(dateString) {
1172
+ return new this().timestamp(dateString);
1239
1173
  }
1240
1174
  _initialDB() {
1241
1175
  this.$state = new StateManager_1.StateManager("db");