tspace-mysql 1.9.4-beta.2 → 1.9.4-beta.4

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 (82) hide show
  1. package/README.md +310 -52
  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 +2 -2
  11. package/dist/lib/config/index.js +14 -5
  12. package/dist/lib/config/index.js.map +1 -1
  13. package/dist/lib/constants/index.d.ts +1 -0
  14. package/dist/lib/constants/index.js +1 -0
  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/Blueprint.d.ts +10 -0
  20. package/dist/lib/core/Blueprint.js +15 -0
  21. package/dist/lib/core/Blueprint.js.map +1 -1
  22. package/dist/lib/core/Builder.d.ts +145 -10
  23. package/dist/lib/core/Builder.js +499 -143
  24. package/dist/lib/core/Builder.js.map +1 -1
  25. package/dist/lib/core/DB.d.ts +130 -196
  26. package/dist/lib/core/DB.js +434 -529
  27. package/dist/lib/core/DB.js.map +1 -1
  28. package/dist/lib/core/Driver/index.d.ts +15 -1
  29. package/dist/lib/core/Driver/index.js +3 -0
  30. package/dist/lib/core/Driver/index.js.map +1 -1
  31. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.d.ts +14 -0
  32. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js +135 -33
  33. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js.map +1 -1
  34. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.d.ts +14 -0
  35. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js +28 -0
  36. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js.map +1 -1
  37. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.d.ts +14 -0
  38. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js +105 -23
  39. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js.map +1 -1
  40. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.d.ts +16 -1
  41. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js +238 -79
  42. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js.map +1 -1
  43. package/dist/lib/core/Driver/sqlite/SqliteDriver.js +1 -1
  44. package/dist/lib/core/Driver/sqlite/SqliteDriver.js.map +1 -1
  45. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.d.ts +17 -0
  46. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js +148 -28
  47. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js.map +1 -1
  48. package/dist/lib/core/Model.d.ts +243 -33
  49. package/dist/lib/core/Model.js +354 -56
  50. package/dist/lib/core/Model.js.map +1 -1
  51. package/dist/lib/core/Package.d.ts +5 -0
  52. package/dist/lib/core/Package.js +7 -2
  53. package/dist/lib/core/Package.js.map +1 -1
  54. package/dist/lib/core/Pool.js +44 -62
  55. package/dist/lib/core/Pool.js.map +1 -1
  56. package/dist/lib/core/Queue/types.d.ts +1 -0
  57. package/dist/lib/core/Queue/worker-lock.d.ts +17 -0
  58. package/dist/lib/core/Queue/worker-lock.js +30 -0
  59. package/dist/lib/core/Queue/worker-lock.js.map +1 -0
  60. package/dist/lib/core/Queue/worker.d.ts +6 -3
  61. package/dist/lib/core/Queue/worker.js +126 -46
  62. package/dist/lib/core/Queue/worker.js.map +1 -1
  63. package/dist/lib/core/Repository.d.ts +164 -29
  64. package/dist/lib/core/Repository.js +180 -40
  65. package/dist/lib/core/Repository.js.map +1 -1
  66. package/dist/lib/core/Schema.d.ts +5 -2
  67. package/dist/lib/core/Schema.js +111 -3
  68. package/dist/lib/core/Schema.js.map +1 -1
  69. package/dist/lib/core/StateManager.d.ts +17 -0
  70. package/dist/lib/core/StateManager.js +5 -1
  71. package/dist/lib/core/StateManager.js.map +1 -1
  72. package/dist/lib/core/UtilityTypes.d.ts +5 -1
  73. package/dist/lib/core/UtilityTypes.js.map +1 -1
  74. package/dist/lib/types/index.d.ts +56 -24
  75. package/dist/lib/types/repository/index.d.ts +10 -18
  76. package/dist/lib/utils/index.d.ts +6 -2
  77. package/dist/lib/utils/index.js +85 -15
  78. package/dist/lib/utils/index.js.map +1 -1
  79. package/package.json +1 -2
  80. package/dist/cli/dump/table.d.ts +0 -4
  81. package/dist/cli/dump/table.js +0 -41
  82. 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() {
277
+ return new this().dd();
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,6 @@ 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
604
591
  * @returns {ConnectionTransaction} object - Connection for the transaction
605
592
  * @type {object} connection
606
593
  * @property {function} connection.query - execute query sql then release connection to pool
@@ -608,30 +595,7 @@ class DB extends AbstractDB_1.AbstractDB {
608
595
  * @property {function} connection.commit - commit transaction of query
609
596
  * @property {function} connection.rollback - rollback transaction of query
610
597
  */
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();
634
- }
598
+ async beginTransaction() {
635
599
  return await this.$pool.transaction();
636
600
  }
637
601
  /**
@@ -641,9 +605,6 @@ class DB extends AbstractDB_1.AbstractDB {
641
605
  *
642
606
  * Transactions are typically used when you want to ensure that a series of database operations either all succeed or all fail together,
643
607
  * ensuring data integrity.
644
- * @param {object} options
645
- * @property {number | undefined} options.primaryId
646
- * @property {number | undefined} options.nodeId
647
608
  * @static
648
609
  * @returns {ConnectionTransaction} object - Connection for the transaction
649
610
  * @type {object} connection
@@ -652,11 +613,11 @@ class DB extends AbstractDB_1.AbstractDB {
652
613
  * @property {function} connection.commit - commit transaction of query
653
614
  * @property {function} connection.rollback - rollback transaction of query
654
615
  */
655
- static async beginTransaction(options) {
656
- return await new this().beginTransaction(options);
616
+ static async beginTransaction() {
617
+ return await new this().beginTransaction();
657
618
  }
658
619
  /**
659
- * Execute a database transaction.
620
+ * The 'transaction' is a method used to Execute a database transaction.
660
621
  *
661
622
  * This method will:
662
623
  * - Acquire a connection from the pool
@@ -666,14 +627,14 @@ class DB extends AbstractDB_1.AbstractDB {
666
627
  * - Rollback if any error occurs
667
628
  *
668
629
  * @template T
669
- * @param {(conn: TConnection) => Promise<T>} handler - Async function that receives the transaction connection.
630
+ * @param {(conn: TConnectionTransaction) => Promise<T>} handler - Async function that receives the transaction connection.
670
631
  * All queries inside this handler MUST use the provided `conn` instance.
671
632
  *
672
633
  * @returns {Promise<T>} The result returned from the handler.
673
634
  *
674
635
  */
675
636
  async transaction(handler) {
676
- const trx = await this.$pool.transaction();
637
+ const trx = await this.beginTransaction();
677
638
  try {
678
639
  await trx.startTransaction();
679
640
  const results = await handler(trx);
@@ -686,7 +647,7 @@ class DB extends AbstractDB_1.AbstractDB {
686
647
  }
687
648
  }
688
649
  /**
689
- * Execute a database transaction.
650
+ * The 'transaction' is a method used to Execute a database transaction.
690
651
  *
691
652
  * This method will:
692
653
  * - Acquire a connection from the pool
@@ -695,8 +656,9 @@ class DB extends AbstractDB_1.AbstractDB {
695
656
  * - Commit if successful
696
657
  * - Rollback if any error occurs
697
658
  *
659
+ * @static
698
660
  * @template T
699
- * @param {(conn: TConnection) => Promise<T>} handler - Async function that receives the transaction connection.
661
+ * @param {(conn: TConnectionTransaction) => Promise<T>} handler - Async function that receives the transaction connection.
700
662
  * All queries inside this handler MUST use the provided `conn` instance.
701
663
  *
702
664
  * @returns {Promise<T>} The result returned from the handler.
@@ -718,6 +680,7 @@ class DB extends AbstractDB_1.AbstractDB {
718
680
  /**
719
681
  * The 'getActiveConnections' method is used to return active connections
720
682
  *
683
+ * @static
721
684
  * @returns {Promise<number>} this
722
685
  */
723
686
  static async getActiveConnections() {
@@ -736,506 +699,448 @@ class DB extends AbstractDB_1.AbstractDB {
736
699
  /**
737
700
  * The 'getMaxConnections' method is used to return max connections
738
701
  *
702
+ * @static
739
703
  * @returns {Promise<number>} this
740
704
  */
741
705
  static async getMaxConnections() {
742
706
  return await new this().getMaxConnections();
743
707
  }
744
708
  /**
745
- * The 'removeProperties' method is used to removed some properties.
709
+ * This'clone' method is used to clone the current database into a new database
710
+ * on the same server or another server.
746
711
  *
747
- * @param {Array | Record} data
748
- * @param {string[]} propertiesToRemoves
749
- * @returns {Array | Record} this
712
+ * @property {string} database - Target database name.
713
+ * @property {string[]} excludes - Tables to exclude from the clone.
714
+ * @property {object} to - Target server connection.
715
+ * @property {string} to.host - Target server host.
716
+ * @property {number} to.port - Target server port.
717
+ * @property {string} to.username - Target server username.
718
+ * @property {string} to.password - Target server password.
719
+ * @returns {Promise<void>}
750
720
  */
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;
721
+ async clone({ database, excludes, only, value, to }) {
722
+ const qb = this._queryBuilder();
723
+ const db = await new DB()
724
+ .debug(this.$state.get("DEBUG"))
725
+ .query(qb.getDatabase(database));
726
+ if (Object.values(db[0] ?? []).length) {
727
+ throw new Error(`This database : '${database}' is already exists`);
728
+ }
729
+ const raws = only
730
+ ? only
731
+ : await new DB()
732
+ .debug(this.$state.get("DEBUG"))
733
+ .getTables();
734
+ const tables = raws.filter(r => !excludes?.includes(r));
735
+ await new DB()
736
+ .debug(this.$state.get("DEBUG"))
737
+ .query(qb.createDatabase(database));
738
+ const connTarget = new DB().getConnection({
739
+ ...(to ?? this.$credentials),
740
+ database,
741
+ });
742
+ const createFks = [];
743
+ const createIndexs = [];
744
+ for (const table of tables) {
745
+ const schema = await new DB()
746
+ .debug(this.$state.get("DEBUG"))
747
+ .showSchema(table);
748
+ await new DB()
749
+ .debug(this.$state.get("DEBUG"))
750
+ .bind(connTarget)
751
+ .query(qb.createTable({
752
+ database,
753
+ table,
754
+ schema,
755
+ }));
756
+ const fks = await new DB()
757
+ .debug(this.$state.get("DEBUG"))
758
+ .getFKs(table);
759
+ for (const fk of fks) {
760
+ createFks.push(qb.addFK({
761
+ table: table,
762
+ tableRef: fk.RefTable,
763
+ constraint: fk.Constraint,
764
+ key: fk.Column,
765
+ foreign: {
766
+ references: fk.RefColumn,
767
+ onDelete: fk.OnDelete,
768
+ onUpdate: fk.OnUpdate,
783
769
  }
784
- delete current[prop];
785
- afterProp = prop;
770
+ }));
771
+ }
772
+ const indexs = await new DB()
773
+ .debug(this.$state.get("DEBUG"))
774
+ .getIndexes(table);
775
+ for (const index of indexs) {
776
+ createIndexs.push(qb.addIndex({
777
+ table: table,
778
+ name: index.IndexName,
779
+ columns: [index.Column]
780
+ }));
781
+ }
782
+ if (!value)
783
+ continue;
784
+ const pageSize = 100;
785
+ let offset = 0;
786
+ while (true) {
787
+ const values = await new DB(table)
788
+ .debug(this.$state.get("DEBUG"))
789
+ .limit(pageSize)
790
+ .offset(offset)
791
+ .get();
792
+ if (!values.length) {
793
+ break;
786
794
  }
787
- const lastProp = properties[properties.length - 1];
788
- if (Array.isArray(current)) {
789
- setNestedProperty(temp, props.join("."), this.removeProperties(current, [afterProp, lastProp]));
790
- continue;
795
+ await new DB(table)
796
+ .debug(this.$state.get("DEBUG"))
797
+ .createMultiple([...values])
798
+ .bind(connTarget)
799
+ .void()
800
+ .save();
801
+ offset += values.length;
802
+ if (values.length < pageSize) {
803
+ break;
791
804
  }
792
- if (current[lastProp] == null)
793
- continue;
794
- delete current[lastProp];
795
805
  }
796
- return temp;
797
- };
798
- if (Array.isArray(data)) {
799
- return data.map((obj) => remove(obj, propertiesToRemoves));
800
806
  }
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();
807
+ if (createFks.length) {
808
+ for (const createFk of createFks) {
809
+ await new DB()
810
+ .debug(this.$state.get("DEBUG"))
811
+ .bind(connTarget)
812
+ .query(createFk);
832
813
  }
833
- catch (e) { }
834
- };
835
- await Promise.all(backup.map((b) => creating({ table: b.table, values: b.values })));
814
+ }
815
+ if (createIndexs.length) {
816
+ for (const createIndex of createIndexs) {
817
+ await new DB()
818
+ .debug(this.$state.get("DEBUG"))
819
+ .bind(connTarget)
820
+ .query(createIndex);
821
+ }
822
+ }
836
823
  return;
837
824
  }
838
825
  /**
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 });
826
+ * This'clone' method is used to clone the current database into a new database
827
+ * on the same server or another server.
828
+ *
829
+ * @static
830
+ * @property {string} database - Target database name.
831
+ * @property {string[]} excludes - Tables to exclude from the clone.
832
+ * @property {object} to - Target server connection.
833
+ * @property {string} to.host - Target server host.
834
+ * @property {number} to.port - Target server port.
835
+ * @property {string} to.username - Target server username.
836
+ * @property {string} to.password - Target server password.
837
+ * @returns {Promise<void>}
838
+ */
839
+ static async clone({ database, only, excludes, value, to }) {
840
+ if (excludes) {
841
+ return new this().clone({ database, excludes, value, to });
842
+ }
843
+ ;
844
+ return new this().clone({ database, only, value, to });
852
845
  }
853
846
  /**
854
847
  *
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
848
+ * This 'dump' method is used to Dumps a database into a SQL file
849
+ * @type {Object} opt
850
+ * @property {string?} opt.database
851
+ * @property {string} opt.filePath
852
+ * @property {string[]} opt.excludes
853
+ * @property {boolean?} opt.value
865
854
  * @returns {Promise<void>}
866
855
  */
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 = [
856
+ async dump({ filePath, excludes, only, database = `dump_${+new Date()}`, value = false }) {
857
+ if (!filePath.toLowerCase().endsWith(".sql")) {
858
+ filePath += ".sql";
859
+ }
860
+ await Package_1.Package.fs.promises.mkdir(Package_1.Package.path.dirname(filePath), { recursive: true });
861
+ const raws = only ? only : await this.getTables();
862
+ const tables = raws.filter(r => !excludes?.includes(r));
863
+ const qb = this._queryBuilder();
864
+ const headers = [
942
865
  `--`,
943
866
  `-- tspace-mysql SQL Dump`,
944
867
  `-- https://www.npmjs.com/package/tspace-mysql`,
945
868
  `--`,
946
- `-- Host: mysql-db`,
869
+ `-- Driver: '${this.$driver}'`,
947
870
  `-- Generation Time: ${new Date()}\n`,
948
- `SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";`,
949
- `START TRANSACTION;`,
950
871
  `--`,
951
872
  `-- Database: '${database}'`,
952
873
  `--\n`,
953
- `${this.$constants("CREATE_DATABASE_NOT_EXISTS")} ${database};`,
954
- `USE ${database};`,
874
+ `${qb.createDatabase(database)};`,
875
+ `${qb.useDatabase(database)};`,
876
+ `--\n`,
955
877
  `-- --------------------------------------------------------`,
956
- ];
957
- for (const b of backup) {
958
- sql = [...sql, b.table];
959
- if (b.values) {
960
- sql = [...sql, b.values];
878
+ ].map(v => qb.format(v)).join('\n');
879
+ const stream = Package_1.Package.fs.createWriteStream(filePath, {
880
+ encoding: "utf8",
881
+ });
882
+ const write = async (data) => {
883
+ if (stream.write(data)) {
884
+ return;
885
+ }
886
+ await new Promise((resolve) => {
887
+ stream.once("drain", resolve);
888
+ });
889
+ };
890
+ const formatCreateTable = (table, createTable) => {
891
+ return [
892
+ `\n--`,
893
+ `-- Table structure for table '${table}'`,
894
+ `--`,
895
+ `${this.$utils.sqlFormatted(createTable)}`,
896
+ ].join("\n") + ";";
897
+ };
898
+ const formatInsertValues = (value, maxChunkSize = 1024 * 1024) => {
899
+ if (!value.length)
900
+ return "";
901
+ const result = [];
902
+ let buffer = "";
903
+ const line = String(value) + "\n";
904
+ if (buffer.length + line.length > maxChunkSize) {
905
+ if (buffer) {
906
+ result.push(buffer);
907
+ buffer = "";
908
+ }
961
909
  }
910
+ buffer += line;
911
+ if (buffer) {
912
+ result.push(buffer);
913
+ }
914
+ return result.join("");
915
+ };
916
+ try {
917
+ stream.write(headers);
918
+ stream.write("\n");
919
+ const createFks = [];
920
+ const createIndexs = [];
921
+ const startTime = Date.now();
922
+ let totalRows = 0;
923
+ for (let i = 0; i < tables.length; i++) {
924
+ const qb = this._queryBuilder();
925
+ const table = tables[i];
926
+ const tableStartTime = Date.now();
927
+ const fks = await this.getFKs(table).catch(_ => []);
928
+ for (const fk of fks) {
929
+ createFks.push(qb.addFK({
930
+ table: table,
931
+ tableRef: fk.RefTable,
932
+ constraint: fk.Constraint,
933
+ key: fk.Column,
934
+ foreign: {
935
+ references: fk.RefColumn,
936
+ onDelete: fk.OnDelete,
937
+ onUpdate: fk.OnUpdate,
938
+ }
939
+ }));
940
+ }
941
+ const indexs = await this.getIndexes(table).catch(_ => []);
942
+ for (const index of indexs) {
943
+ createIndexs.push(qb.addIndex({
944
+ table: table,
945
+ name: index.IndexName,
946
+ columns: index.Column.split(',')
947
+ }));
948
+ }
949
+ const progress = Math.round(((i + 1) / tables.length) * 100);
950
+ console.log(`\n[${String(progress).padStart(3, " ")}%] ` +
951
+ `[${i + 1}/${tables.length}] ${table}`);
952
+ const schema = await this.showSchema(table);
953
+ const createTable = qb.createTable({
954
+ database,
955
+ table,
956
+ schema
957
+ });
958
+ await write(formatCreateTable(table, createTable));
959
+ await write("\n");
960
+ console.log(` ├─ schema ✓`);
961
+ if (!value) {
962
+ console.log(` └─ done in ${((Date.now() - tableStartTime) / 1000).toFixed(2)}s`);
963
+ continue;
964
+ }
965
+ const pageSize = 100;
966
+ let offset = 0;
967
+ let page = 0;
968
+ let tableRows = 0;
969
+ let wasWritten = false;
970
+ while (true) {
971
+ const values = await this.table(table)
972
+ .limit(pageSize)
973
+ .offset(offset)
974
+ .get();
975
+ if (!values.length) {
976
+ break;
977
+ }
978
+ if (!wasWritten) {
979
+ const hearder = `\n--\n` +
980
+ `-- Dumping data for table '${table}'\n` +
981
+ `--\n`;
982
+ await write(hearder);
983
+ wasWritten = true;
984
+ }
985
+ const sql = this.table(table)
986
+ .createMultiple([...values])
987
+ .toString();
988
+ await write(formatInsertValues(sql + ";"));
989
+ tableRows += values.length;
990
+ totalRows += values.length;
991
+ offset += pageSize;
992
+ page++;
993
+ if (values.length < pageSize) {
994
+ break;
995
+ }
996
+ console.log(` ├─ page ${page} | rows: ${tableRows.toLocaleString()}`);
997
+ }
998
+ await write("\n");
999
+ const elapsed = ((Date.now() - tableStartTime) / 1000).toFixed(2);
1000
+ console.log(` ├─ rows: ${tableRows.toLocaleString()}`);
1001
+ console.log(` ├─ pages: ${page}`);
1002
+ console.log(` └─ done in ${elapsed}s`);
1003
+ }
1004
+ if (createFks.length) {
1005
+ const header = `\n--\n` +
1006
+ `-- Foreign key constraints\n` +
1007
+ `--\n`;
1008
+ await write(header);
1009
+ for (const createFk of createFks) {
1010
+ await write(createFk + ";\n");
1011
+ }
1012
+ }
1013
+ if (createIndexs.length) {
1014
+ const header = `\n--\n` +
1015
+ `-- Index key constraints\n` +
1016
+ `--\n`;
1017
+ await write(header);
1018
+ for (const createIndex of createIndexs) {
1019
+ await write(createIndex + ";\n");
1020
+ }
1021
+ }
1022
+ const tail = [
1023
+ `--`,
1024
+ `--`,
1025
+ `-- --------------------------------------------------------`,
1026
+ ].join('\n');
1027
+ await write("\n" + tail);
1028
+ const totalTime = ((Date.now() - startTime) / 1000).toFixed(2);
1029
+ console.log(`\n[DONE] Dump completed: ${tables.length} tables, ` +
1030
+ `${totalRows.toLocaleString()} rows, ${totalTime}s`);
1031
+ stream.end();
1032
+ await new Promise((resolve) => {
1033
+ stream.once("finish", resolve);
1034
+ });
1035
+ }
1036
+ catch (error) {
1037
+ stream.destroy();
1038
+ throw error;
962
1039
  }
963
- Package_1.Package.fs.writeFileSync(filePath, [...sql, "COMMIT;"].join("\n"));
964
1040
  return;
965
1041
  }
966
1042
  /**
1043
+ * This 'dump' method is used to Dumps a database into a SQL file
967
1044
  *
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
1045
+ * @static
1046
+ * @type {Object} opt
1047
+ * @property {string?} opt.database
1048
+ * @property {string} opt.filePath
1049
+ * @property {string[]} opt.excludes
1050
+ * @property {boolean?} opt.value
978
1051
  * @returns {Promise<void>}
979
1052
  */
980
- static async backupToFile({ filePath, database, connection, }) {
981
- return new this().backupToFile({ filePath, database, connection });
1053
+ static async dump({ filePath, database, excludes, only, value, }) {
1054
+ if (excludes) {
1055
+ return new this().dump({ filePath, database, excludes, value });
1056
+ }
1057
+ ;
1058
+ return new this().dump({ filePath, database, only, value });
982
1059
  }
983
1060
  /**
1061
+ * This 'session' method is used to manage database session variables.
984
1062
  *
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
- /**
1063
+ * Provides methods to get and set session variables for the current
1064
+ * database connection.
1024
1065
  *
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
- /**
1066
+ * Supported drivers:
1067
+ * - MySQL
1068
+ * - MariaDB
1069
+ * - PostgreSQL
1070
+ * - SQLite
1042
1071
  *
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>}
1072
+ * MongoDB is not supported.
1073
+ *
1074
+ * @example
1075
+ * ```ts
1076
+ * await DB.session().set('db', 'primary');
1077
+ *
1078
+ * const value = await db.session().get('db');
1079
+ * console.log(value) // primary
1080
+ *
1081
+ * ```
1055
1082
  */
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
- ];
1083
+ session() {
1084
+ if (this.driver() === 'mongodb') {
1085
+ throw new Error('Session is not supported for MongoDB. Use a different driver or disable sessions features.');
1081
1086
  }
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;
1087
+ const self = this;
1088
+ const qb = this._queryBuilder();
1089
+ return {
1090
+ async get(name) {
1091
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
1092
+ throw new Error(`Invalid session variable name: ${name}`);
1093
+ }
1094
+ const raw = await self.query(qb.getSession(self.escape(name)));
1095
+ if (!Array.isArray(raw) || !raw[0]) {
1096
+ return null;
1097
+ }
1098
+ const session = (raw[0][name] ?? null);
1099
+ return session === '' ? null : session;
1100
+ },
1101
+ async set(name, value) {
1102
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
1103
+ throw new Error(`Invalid session variable name: ${name}`);
1104
+ }
1105
+ await self.query(qb.setSession(self.escape(name), self.escape(value)));
1106
+ return;
1107
+ },
1108
+ async delete(name) {
1109
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
1110
+ throw new Error(`Invalid session variable name: ${name}`);
1111
+ }
1112
+ await self.query(qb.deleteSession(self.escape(name)));
1113
+ return;
1114
+ },
1115
+ };
1092
1116
  }
1093
1117
  /**
1118
+ * This 'session' method is used to manage database session variables.
1094
1119
  *
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>}
1106
- */
1107
- static async backupTableToFile({ filePath, table, connection, }) {
1108
- return new this().backupTableToFile({ filePath, table, connection });
1109
- }
1110
- /**
1120
+ * Provides methods to get and set session variables for the current
1121
+ * database connection.
1111
1122
  *
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>}
1123
- */
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;
1142
- }
1143
- /**
1123
+ * Supported drivers:
1124
+ * - MySQL
1125
+ * - MariaDB
1126
+ * - PostgreSQL
1127
+ * - SQLite
1144
1128
  *
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>}
1129
+ * MongoDB is not supported.
1130
+ *
1131
+ * @static
1132
+ *
1133
+ * @example
1134
+ * ```ts
1135
+ * await DB.session().set('db', 'primary');
1136
+ *
1137
+ * const value = await db.session().get('db');
1138
+ * console.log(value) // primary
1139
+ *
1140
+ * ```
1156
1141
  */
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;
1142
+ static session() {
1143
+ return new this().session();
1239
1144
  }
1240
1145
  _initialDB() {
1241
1146
  this.$state = new StateManager_1.StateManager("db");