tspace-mysql 1.9.3 → 1.9.4-beta.10

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 (129) hide show
  1. package/README.md +497 -80
  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 +4 -4
  11. package/dist/lib/config/index.js +16 -7
  12. package/dist/lib/config/index.js.map +1 -1
  13. package/dist/lib/constants/index.d.ts +2 -2
  14. package/dist/lib/constants/index.js +9 -2
  15. package/dist/lib/constants/index.js.map +1 -1
  16. package/dist/lib/core/Abstracts/AbstractBuilder.d.ts +3 -2
  17. package/dist/lib/core/Abstracts/AbstractBuilder.js +1 -0
  18. package/dist/lib/core/Abstracts/AbstractBuilder.js.map +1 -1
  19. package/dist/lib/core/Abstracts/AbstractDB.d.ts +5 -3
  20. package/dist/lib/core/Abstracts/AbstractDB.js.map +1 -1
  21. package/dist/lib/core/Abstracts/AbstractModel.d.ts +1 -2
  22. package/dist/lib/core/Abstracts/AbstractModel.js +0 -1
  23. package/dist/lib/core/Abstracts/AbstractModel.js.map +1 -1
  24. package/dist/lib/core/Abstracts/AbstractView.d.ts +2 -1
  25. package/dist/lib/core/Abstracts/AbstractView.js.map +1 -1
  26. package/dist/lib/core/Blueprint.d.ts +56 -13
  27. package/dist/lib/core/Blueprint.js +58 -2
  28. package/dist/lib/core/Blueprint.js.map +1 -1
  29. package/dist/lib/core/Builder.d.ts +172 -19
  30. package/dist/lib/core/Builder.js +574 -210
  31. package/dist/lib/core/Builder.js.map +1 -1
  32. package/dist/lib/core/Cache/DBCache.js +6 -5
  33. package/dist/lib/core/Cache/DBCache.js.map +1 -1
  34. package/dist/lib/core/Cache/index.js +1 -1
  35. package/dist/lib/core/Cache/index.js.map +1 -1
  36. package/dist/lib/core/Contracts/Audit.d.ts +7 -5
  37. package/dist/lib/core/Contracts/Audit.js +18 -2
  38. package/dist/lib/core/Contracts/Audit.js.map +1 -1
  39. package/dist/lib/core/Contracts/Logger.d.ts +2 -2
  40. package/dist/lib/core/DB.d.ts +242 -169
  41. package/dist/lib/core/DB.js +559 -524
  42. package/dist/lib/core/DB.js.map +1 -1
  43. package/dist/lib/core/Driver/index.d.ts +41 -15
  44. package/dist/lib/core/Driver/index.js +14 -0
  45. package/dist/lib/core/Driver/index.js.map +1 -1
  46. package/dist/lib/core/Driver/mariadb/MariadbDriver.d.ts +6 -2
  47. package/dist/lib/core/Driver/mariadb/MariadbDriver.js +24 -7
  48. package/dist/lib/core/Driver/mariadb/MariadbDriver.js.map +1 -1
  49. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.d.ts +42 -17
  50. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js +281 -154
  51. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js.map +1 -1
  52. package/dist/lib/core/Driver/mongodb/MongodbDriver.d.ts +7 -3
  53. package/dist/lib/core/Driver/mongodb/MongodbDriver.js +11 -6
  54. package/dist/lib/core/Driver/mongodb/MongodbDriver.js.map +1 -1
  55. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.d.ts +40 -15
  56. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js +205 -157
  57. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js.map +1 -1
  58. package/dist/lib/core/Driver/mysql/MysqlDriver.d.ts +6 -2
  59. package/dist/lib/core/Driver/mysql/MysqlDriver.js +29 -7
  60. package/dist/lib/core/Driver/mysql/MysqlDriver.js.map +1 -1
  61. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.d.ts +42 -17
  62. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js +251 -144
  63. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js.map +1 -1
  64. package/dist/lib/core/Driver/postgres/PostgresDriver.d.ts +6 -2
  65. package/dist/lib/core/Driver/postgres/PostgresDriver.js +27 -8
  66. package/dist/lib/core/Driver/postgres/PostgresDriver.js.map +1 -1
  67. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.d.ts +45 -19
  68. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js +471 -287
  69. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js.map +1 -1
  70. package/dist/lib/core/Driver/sqlite/SqliteDriver.d.ts +6 -2
  71. package/dist/lib/core/Driver/sqlite/SqliteDriver.js +18 -7
  72. package/dist/lib/core/Driver/sqlite/SqliteDriver.js.map +1 -1
  73. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.d.ts +47 -19
  74. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js +331 -203
  75. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js.map +1 -1
  76. package/dist/lib/core/Model.d.ts +541 -36
  77. package/dist/lib/core/Model.js +726 -81
  78. package/dist/lib/core/Model.js.map +1 -1
  79. package/dist/lib/core/Package.d.ts +5 -0
  80. package/dist/lib/core/Package.js +7 -2
  81. package/dist/lib/core/Package.js.map +1 -1
  82. package/dist/lib/core/Pool.d.ts +1 -1
  83. package/dist/lib/core/Pool.js +57 -73
  84. package/dist/lib/core/Pool.js.map +1 -1
  85. package/dist/lib/core/{Queue.d.ts → Queue/index.d.ts} +112 -117
  86. package/dist/lib/core/Queue/index.js +283 -0
  87. package/dist/lib/core/Queue/index.js.map +1 -0
  88. package/dist/lib/core/Queue/types.d.ts +68 -0
  89. package/dist/lib/core/Queue/types.js +3 -0
  90. package/dist/lib/core/Queue/types.js.map +1 -0
  91. package/dist/lib/core/Queue/worker-lock.d.ts +17 -0
  92. package/dist/lib/core/Queue/worker-lock.js +28 -0
  93. package/dist/lib/core/Queue/worker-lock.js.map +1 -0
  94. package/dist/lib/core/Queue/worker.d.ts +113 -0
  95. package/dist/lib/core/Queue/worker.js +853 -0
  96. package/dist/lib/core/Queue/worker.js.map +1 -0
  97. package/dist/lib/core/RelationManager.js +1 -1
  98. package/dist/lib/core/RelationManager.js.map +1 -1
  99. package/dist/lib/core/Repository.d.ts +175 -20
  100. package/dist/lib/core/Repository.js +180 -18
  101. package/dist/lib/core/Repository.js.map +1 -1
  102. package/dist/lib/core/Schema.d.ts +11 -7
  103. package/dist/lib/core/Schema.js +249 -80
  104. package/dist/lib/core/Schema.js.map +1 -1
  105. package/dist/lib/core/SqlLike.js +4 -4
  106. package/dist/lib/core/SqlLike.js.map +1 -1
  107. package/dist/lib/core/StateManager.d.ts +19 -0
  108. package/dist/lib/core/StateManager.js +9 -4
  109. package/dist/lib/core/StateManager.js.map +1 -1
  110. package/dist/lib/core/UtilityTypes.d.ts +24 -6
  111. package/dist/lib/core/UtilityTypes.js.map +1 -1
  112. package/dist/lib/core/View.d.ts +3 -1
  113. package/dist/lib/core/View.js +18 -25
  114. package/dist/lib/core/View.js.map +1 -1
  115. package/dist/lib/core/index.d.ts +2 -0
  116. package/dist/lib/core/index.js +3 -1
  117. package/dist/lib/core/index.js.map +1 -1
  118. package/dist/lib/types/decorator/index.d.ts +3 -0
  119. package/dist/lib/types/index.d.ts +93 -105
  120. package/dist/lib/types/repository/index.d.ts +20 -28
  121. package/dist/lib/utils/index.d.ts +16 -7
  122. package/dist/lib/utils/index.js +127 -24
  123. package/dist/lib/utils/index.js.map +1 -1
  124. package/package.json +3 -6
  125. package/dist/cli/dump/table.d.ts +0 -4
  126. package/dist/cli/dump/table.js +0 -41
  127. package/dist/cli/dump/table.js.map +0 -1
  128. package/dist/lib/core/Queue.js +0 -726
  129. package/dist/lib/core/Queue.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");
@@ -68,7 +67,12 @@ class DB extends AbstractDB_1.AbstractDB {
68
67
  * @returns {promise<void>}
69
68
  */
70
69
  async initialize() {
71
- await this.query(`${this.$constants("SELECT")} 1`);
70
+ const sql = `${this.$constants("SELECT")} 1`;
71
+ await this.query(sql)
72
+ .catch(async () => {
73
+ await new Promise(r => setTimeout(r, 3000));
74
+ await this.query(sql);
75
+ });
72
76
  return;
73
77
  }
74
78
  /**
@@ -116,41 +120,126 @@ class DB extends AbstractDB_1.AbstractDB {
116
120
  *
117
121
  * @param {string} sql
118
122
  * @param {Record<string,any>} parameters
119
- * @returns {promise<any[]>}
123
+ * @returns {Promise<T>}
124
+ *
125
+ * @example
126
+ * Execute a query without parameters:
127
+ * ```ts
128
+ * const users = await db.query(
129
+ * 'SELECT * FROM users'
130
+ * );
131
+ * ```
132
+ *
133
+ * @example
134
+ * Execute a query with named parameters:
135
+ * ```ts
136
+ * const user = await db.query(
137
+ * 'SELECT * FROM users WHERE id = :id',
138
+ * { id: 1 }
139
+ * );
140
+ * ```
141
+ *
142
+ * @example
143
+ * Execute a query with multiple parameters:
144
+ * ```ts
145
+ * const users = await db.query(
146
+ * 'SELECT * FROM users WHERE status = :status AND age >= :age',
147
+ * {
148
+ * status: 'active',
149
+ * age: 18,
150
+ * }
151
+ * );
152
+ * ```
153
+ *
154
+ * @example
155
+ * Use an array parameter:
156
+ * ```ts
157
+ * const users = await db.query(
158
+ * 'SELECT * FROM users WHERE id IN :ids',
159
+ * {
160
+ * ids: [1, 2, 3],
161
+ * }
162
+ * );
163
+ * ```
164
+ *
165
+ * @example
166
+ * Positional parameters using `?` placeholders:
167
+ * ```ts
168
+ * const users = await db.query<User[]>(
169
+ * 'SELECT * FROM users WHERE id = ? AND status = ?',
170
+ * [1, 'active']
171
+ * );
172
+ * ```
120
173
  */
121
174
  async query(sql, parameters = {}) {
122
- if (!Object.keys(parameters).length) {
123
- return await this.rawQuery(sql);
124
- }
125
- let bindSql = sql;
126
- for (const key in parameters) {
127
- const parameter = parameters[key];
128
- if (parameter === null) {
129
- bindSql = bindSql.replace(`:${key}`, this.$constants("NULL"));
130
- continue;
131
- }
132
- if (parameter === true || parameter === false) {
133
- bindSql = bindSql.replace(`:${key}`, `'${parameter === true ? 1 : 0}'`);
134
- continue;
135
- }
136
- bindSql = bindSql.replace(`:${key}`, Array.isArray(parameter)
137
- ? `(${parameter.map((p) => `'${this.escape(p)}'`).join(",")})`
138
- : `'${this.escape(parameter)}'`);
139
- }
140
- return await this.rawQuery(bindSql);
175
+ const boundSql = this.$utils
176
+ .bindingParameters(sql, parameters, { raw: false });
177
+ return await this.rawQuery(boundSql);
141
178
  }
142
179
  /**
143
180
  * The 'query' method is used to execute sql statement
144
181
  *
182
+ * @static
145
183
  * @param {string} sql
146
184
  * @param {Record<string,any>} parameters
147
- * @returns {promise<any[]>}
185
+ * @returns {Promise<T>}
186
+ *
187
+ * @example
188
+ * Execute a query without parameters:
189
+ * ```ts
190
+ * const users = await db.query(
191
+ * 'SELECT * FROM users'
192
+ * );
193
+ * ```
194
+ *
195
+ * @example
196
+ * Execute a query with named parameters:
197
+ * ```ts
198
+ * const user = await db.query(
199
+ * 'SELECT * FROM users WHERE id = :id',
200
+ * { id: 1 }
201
+ * );
202
+ * ```
203
+ *
204
+ * @example
205
+ * Execute a query with multiple parameters:
206
+ * ```ts
207
+ * const users = await db.query(
208
+ * 'SELECT * FROM users WHERE status = :status AND age >= :age',
209
+ * {
210
+ * status: 'active',
211
+ * age: 18,
212
+ * }
213
+ * );
214
+ * ```
215
+ *
216
+ * @example
217
+ * Use an array parameter:
218
+ * ```ts
219
+ * const users = await db.query(
220
+ * 'SELECT * FROM users WHERE id IN :ids',
221
+ * {
222
+ * ids: [1, 2, 3],
223
+ * }
224
+ * );
225
+ * ```
226
+ *
227
+ * @example
228
+ * Positional parameters using `?` placeholders:
229
+ * ```ts
230
+ * const users = await db.query<User[]>(
231
+ * 'SELECT * FROM users WHERE id = ? AND status = ?',
232
+ * [1, 'active']
233
+ * );
234
+ * ```
148
235
  */
149
236
  static async query(sql, parameters = {}) {
150
237
  return await new this().query(sql, parameters);
151
238
  }
152
239
  /**
153
240
  * The 'from' method is used to define the from table name.
241
+ *
242
+ * @static
154
243
  * @param {string} table table name
155
244
  * @returns {this} this
156
245
  */
@@ -159,6 +248,8 @@ class DB extends AbstractDB_1.AbstractDB {
159
248
  }
160
249
  /**
161
250
  * The 'table' method is used to define the table name.
251
+ *
252
+ * @static
162
253
  * @param {string} table table name
163
254
  * @returns {DB} DB
164
255
  */
@@ -168,6 +259,7 @@ class DB extends AbstractDB_1.AbstractDB {
168
259
  /**
169
260
  * The 'alias' method is used to set the table name.
170
261
  *
262
+ * @static
171
263
  * @param {string} sql raw sql from make a new alias for this table
172
264
  * @param {string} alias alias name
173
265
  * @returns {DB} DB
@@ -175,6 +267,15 @@ class DB extends AbstractDB_1.AbstractDB {
175
267
  static alias(sql, alias) {
176
268
  return new this().alias(sql, alias);
177
269
  }
270
+ /**
271
+ *
272
+ * @static
273
+ * @override
274
+ * @returns {this} this
275
+ */
276
+ static dd(debug = true) {
277
+ return new this().dd(debug);
278
+ }
178
279
  /**
179
280
  * The 'jsonObject' method is used to specify select data to JSON objects.
180
281
  * @param {string} object table name
@@ -201,6 +302,7 @@ class DB extends AbstractDB_1.AbstractDB {
201
302
  }
202
303
  /**
203
304
  * The 'jsonObject' method is used to specify select data to JSON objects.
305
+ *
204
306
  * @static
205
307
  * @param {string} object table name
206
308
  * @param {string} alias
@@ -211,6 +313,7 @@ class DB extends AbstractDB_1.AbstractDB {
211
313
  }
212
314
  /**
213
315
  * The 'JSONObject' method is used to specify select data to JSON objects.
316
+ *
214
317
  * @param {string} object table name
215
318
  * @param {string} alias
216
319
  * @returns {string} string
@@ -220,6 +323,7 @@ class DB extends AbstractDB_1.AbstractDB {
220
323
  }
221
324
  /**
222
325
  * The 'JSONObject' method is used to specify select data to JSON objects.
326
+ *
223
327
  * @static
224
328
  * @param {string} object table name
225
329
  * @param {string} alias
@@ -238,6 +342,7 @@ class DB extends AbstractDB_1.AbstractDB {
238
342
  }
239
343
  /**
240
344
  * The 'constants' method is used to return constants with key or none in 'DB' or 'Model'.
345
+ *
241
346
  * @static
242
347
  * @param {string} key
243
348
  * @returns {string | object} string || object
@@ -275,6 +380,7 @@ class DB extends AbstractDB_1.AbstractDB {
275
380
  }
276
381
  /**
277
382
  * select by cases
383
+ *
278
384
  * @static
279
385
  * @param {arrayObject} cases array object {when , then }
280
386
  * @param {string?} final else condition
@@ -284,19 +390,25 @@ class DB extends AbstractDB_1.AbstractDB {
284
390
  return new this().caseUpdate(cases, final);
285
391
  }
286
392
  /**
287
- * 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.
288
397
  * @returns {string} string
289
398
  */
290
- generateUUID() {
291
- return this.$utils.generateUUID();
399
+ generateUUID({ v } = {}) {
400
+ return this.$utils.generateUUID(v);
292
401
  }
293
402
  /**
294
- * 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.
295
407
  * @static
296
408
  * @returns {string} string
297
409
  */
298
- static generateUUID() {
299
- return new this().generateUUID();
410
+ static generateUUID({ v } = {}) {
411
+ return new this().generateUUID({ v });
300
412
  }
301
413
  /**
302
414
  * The 'snakeCase' methid is used to covert value to snakeCase pattern.
@@ -331,10 +443,12 @@ class DB extends AbstractDB_1.AbstractDB {
331
443
  * @returns {string} string
332
444
  */
333
445
  escape(value) {
334
- return this.$utils.escape(value, true);
446
+ return this.$utils.escape(value, { hard: true });
335
447
  }
336
448
  /**
337
449
  * The 'escape' methid is used to escaping SQL injections.
450
+ *
451
+ * @static
338
452
  * @returns {string} string
339
453
  */
340
454
  static escape(value) {
@@ -349,6 +463,8 @@ class DB extends AbstractDB_1.AbstractDB {
349
463
  }
350
464
  /**
351
465
  * The 'escapeXSS' methid is used to escaping XSS characters.
466
+ *
467
+ * @static
352
468
  * @returns {string} string
353
469
  */
354
470
  static escapeXSS(value) {
@@ -375,12 +491,9 @@ class DB extends AbstractDB_1.AbstractDB {
375
491
  * )
376
492
  * .findOne();
377
493
  */
378
- raw(sql, parameters = []) {
379
- if (!parameters.length) {
380
- return `${this.$constants("RAW")}${sql}`;
381
- }
382
- sql = this.$utils.bindingParameters(sql, parameters);
383
- return `${this.$constants("RAW")}${sql}`;
494
+ raw(sql, parameters = {}) {
495
+ const boundSql = this.$utils.bindingParameters(sql, parameters);
496
+ return `${this.$constants("RAW")}${boundSql}`;
384
497
  }
385
498
  /**
386
499
  * The 'raw' methid is used to allow for raw sql queries to some method in 'DB' or 'Model'.
@@ -404,7 +517,7 @@ class DB extends AbstractDB_1.AbstractDB {
404
517
  * )
405
518
  * .findOne();
406
519
  */
407
- static raw(sql, parameters = []) {
520
+ static raw(sql, parameters = {}) {
408
521
  return `${new this().raw(sql, parameters)}`;
409
522
  }
410
523
  /**
@@ -475,9 +588,8 @@ class DB extends AbstractDB_1.AbstractDB {
475
588
  *
476
589
  * Transactions are typically used when you want to ensure that a series of database operations either all succeed or all fail together,
477
590
  * ensuring data integrity.
478
- * @param {object} options
479
- * @property {number | undefined} options.primaryId
480
- * @property {number | undefined} options.nodeId
591
+ *
592
+ * @param {TPoolConnected} pool
481
593
  * @returns {ConnectionTransaction} object - Connection for the transaction
482
594
  * @type {object} connection
483
595
  * @property {function} connection.query - execute query sql then release connection to pool
@@ -485,29 +597,9 @@ class DB extends AbstractDB_1.AbstractDB {
485
597
  * @property {function} connection.commit - commit transaction of query
486
598
  * @property {function} connection.rollback - rollback transaction of query
487
599
  */
488
- async beginTransaction(options) {
489
- if (this.$cluster) {
490
- const cluster = new Pool_1.PoolConnection().clusterConnect();
491
- const masters = cluster.masters;
492
- if (!masters.length) {
493
- throw new Error("No Master available in cluster");
494
- }
495
- const length = masters.length;
496
- let selectedIndex = 0;
497
- if (options?.nodeId != null) {
498
- if (options.nodeId > length) {
499
- throw new Error(`Invalid nodeId ${options.nodeId}. Cluster has only ${length} master node(s).`);
500
- }
501
- selectedIndex = options.nodeId - 1;
502
- }
503
- else if (options?.primaryId != null) {
504
- selectedIndex = Math.round(options.primaryId % length);
505
- }
506
- const writer = masters[selectedIndex];
507
- if (writer == null) {
508
- throw new Error("No Master available in cluster");
509
- }
510
- return await writer.connection();
600
+ async beginTransaction(pool) {
601
+ if (pool) {
602
+ return await pool.connection();
511
603
  }
512
604
  return await this.$pool.transaction();
513
605
  }
@@ -518,10 +610,9 @@ class DB extends AbstractDB_1.AbstractDB {
518
610
  *
519
611
  * Transactions are typically used when you want to ensure that a series of database operations either all succeed or all fail together,
520
612
  * ensuring data integrity.
521
- * @param {object} options
522
- * @property {number | undefined} options.primaryId
523
- * @property {number | undefined} options.nodeId
524
613
  * @static
614
+ *
615
+ * @param {TPoolConnected} pool
525
616
  * @returns {ConnectionTransaction} object - Connection for the transaction
526
617
  * @type {object} connection
527
618
  * @property {function} connection.query - execute query sql then release connection to pool
@@ -529,11 +620,11 @@ class DB extends AbstractDB_1.AbstractDB {
529
620
  * @property {function} connection.commit - commit transaction of query
530
621
  * @property {function} connection.rollback - rollback transaction of query
531
622
  */
532
- static async beginTransaction(options) {
533
- return await new this().beginTransaction(options);
623
+ static async beginTransaction(pool) {
624
+ return await new this().beginTransaction(pool);
534
625
  }
535
626
  /**
536
- * Execute a database transaction.
627
+ * The 'transaction' is a method used to Execute a database transaction.
537
628
  *
538
629
  * This method will:
539
630
  * - Acquire a connection from the pool
@@ -549,8 +640,8 @@ class DB extends AbstractDB_1.AbstractDB {
549
640
  * @returns {Promise<T>} The result returned from the handler.
550
641
  *
551
642
  */
552
- async transaction(handler) {
553
- const trx = await this.$pool.transaction();
643
+ async transaction(handler, { pool } = {}) {
644
+ const trx = await this.beginTransaction(pool);
554
645
  try {
555
646
  await trx.startTransaction();
556
647
  const results = await handler(trx);
@@ -563,7 +654,7 @@ class DB extends AbstractDB_1.AbstractDB {
563
654
  }
564
655
  }
565
656
  /**
566
- * Execute a database transaction.
657
+ * The 'transaction' is a method used to Execute a database transaction.
567
658
  *
568
659
  * This method will:
569
660
  * - Acquire a connection from the pool
@@ -572,6 +663,7 @@ class DB extends AbstractDB_1.AbstractDB {
572
663
  * - Commit if successful
573
664
  * - Rollback if any error occurs
574
665
  *
666
+ * @static
575
667
  * @template T
576
668
  * @param {(conn: TConnection) => Promise<T>} handler - Async function that receives the transaction connection.
577
669
  * All queries inside this handler MUST use the provided `conn` instance.
@@ -579,8 +671,8 @@ class DB extends AbstractDB_1.AbstractDB {
579
671
  * @returns {Promise<T>} The result returned from the handler.
580
672
  *
581
673
  */
582
- static async transaction(handler) {
583
- return await new this().transaction(handler);
674
+ static async transaction(handler, { pool } = {}) {
675
+ return await new this().transaction(handler, { pool });
584
676
  }
585
677
  /**
586
678
  * The 'getActiveConnections' method is used to return active connections
@@ -589,12 +681,13 @@ class DB extends AbstractDB_1.AbstractDB {
589
681
  */
590
682
  async getActiveConnections() {
591
683
  const current = await new DB()
592
- .query(this._queryBuilder().getActiveConnections());
684
+ .query(this.getQueryBuilder().getActiveConnections());
593
685
  return Number(current[0]?.Connections || 0);
594
686
  }
595
687
  /**
596
688
  * The 'getActiveConnections' method is used to return active connections
597
689
  *
690
+ * @static
598
691
  * @returns {Promise<number>} this
599
692
  */
600
693
  static async getActiveConnections() {
@@ -607,512 +700,454 @@ class DB extends AbstractDB_1.AbstractDB {
607
700
  */
608
701
  async getMaxConnections() {
609
702
  const current = await new DB()
610
- .query(this._queryBuilder().getMaxConnections());
703
+ .query(this.getQueryBuilder().getMaxConnections());
611
704
  return Number(current[0]?.MaxConnections || 0);
612
705
  }
613
706
  /**
614
707
  * The 'getMaxConnections' method is used to return max connections
615
708
  *
709
+ * @static
616
710
  * @returns {Promise<number>} this
617
711
  */
618
712
  static async getMaxConnections() {
619
713
  return await new this().getMaxConnections();
620
714
  }
621
715
  /**
622
- * The 'removeProperties' method is used to removed some properties.
716
+ * This'clone' method is used to clone the current database into a new database
717
+ * on the same server or another server.
623
718
  *
624
- * @param {Array | Record} data
625
- * @param {string[]} propertiesToRemoves
626
- * @returns {Array | Record} this
719
+ * @property {string} database - Target database name.
720
+ * @property {string[]} excludes - Tables to exclude from the clone.
721
+ * @property {object} to - Target server connection.
722
+ * @property {string} to.host - Target server host.
723
+ * @property {number} to.port - Target server port.
724
+ * @property {string} to.username - Target server username.
725
+ * @property {string} to.password - Target server password.
726
+ * @returns {Promise<void>}
627
727
  */
628
- removeProperties(data, propertiesToRemoves) {
629
- const setNestedProperty = (obj, path, value) => {
630
- const segments = path.split(".");
631
- let currentObj = obj;
632
- for (let i = 0; i < segments.length - 1; i++) {
633
- const segment = segments[i];
634
- if (!currentObj.hasOwnProperty(segment)) {
635
- currentObj[segment] = {};
636
- }
637
- currentObj = currentObj[segment];
638
- }
639
- const lastSegment = segments[segments.length - 1];
640
- currentObj[lastSegment] = value;
641
- };
642
- const remove = (obj, propertiesToRemoves) => {
643
- const temp = JSON.parse(JSON.stringify(obj));
644
- for (const property of propertiesToRemoves) {
645
- if (property == null)
646
- continue;
647
- const properties = property.split(".");
648
- let current = temp;
649
- let afterProp = "";
650
- const props = [];
651
- for (let i = 0; i < properties.length - 1; i++) {
652
- const prop = properties[i];
653
- if (current[prop] == null)
654
- continue;
655
- props.push(prop);
656
- if (typeof current[prop] === "object" && current[prop] != null) {
657
- current = current[prop];
658
- afterProp = prop;
659
- continue;
728
+ async clone({ database, excludes, only, value, to }) {
729
+ const qb = this.getQueryBuilder();
730
+ const db = await new DB()
731
+ .debug(this.$state.get("DEBUG"))
732
+ .query(qb.getDatabase(database));
733
+ if (Object.values(db[0] ?? []).length) {
734
+ throw new Error(`This database : '${database}' is already exists`);
735
+ }
736
+ const raws = only
737
+ ? only
738
+ : await new DB()
739
+ .debug(this.$state.get("DEBUG"))
740
+ .getTables();
741
+ const tables = raws.filter(r => !excludes?.includes(r));
742
+ await new DB()
743
+ .debug(this.$state.get("DEBUG"))
744
+ .query(qb.createDatabase(database));
745
+ const connTarget = new DB().getConnection({
746
+ ...(to ?? this.$credentials),
747
+ database,
748
+ });
749
+ const createFks = [];
750
+ const createIndexs = [];
751
+ for (const table of tables) {
752
+ const schema = await new DB()
753
+ .debug(this.$state.get("DEBUG"))
754
+ .showSchema(table);
755
+ await new DB()
756
+ .debug(this.$state.get("DEBUG"))
757
+ .bind(connTarget)
758
+ .query(qb.createTable({
759
+ database,
760
+ table,
761
+ schema,
762
+ }));
763
+ const fks = await new DB()
764
+ .debug(this.$state.get("DEBUG"))
765
+ .getFKs(table);
766
+ for (const fk of fks) {
767
+ createFks.push(qb.addFK({
768
+ table: table,
769
+ tableRef: fk.RefTable,
770
+ constraint: fk.Constraint,
771
+ key: fk.Column,
772
+ foreign: {
773
+ references: fk.RefColumn,
774
+ onDelete: fk.OnDelete,
775
+ onUpdate: fk.OnUpdate,
660
776
  }
661
- delete current[prop];
662
- afterProp = prop;
777
+ }));
778
+ }
779
+ const indexs = await new DB()
780
+ .debug(this.$state.get("DEBUG"))
781
+ .getIndexes(table);
782
+ for (const index of indexs) {
783
+ createIndexs.push(qb.addIndex({
784
+ table: table,
785
+ name: index.IndexName,
786
+ columns: [index.Column]
787
+ }));
788
+ }
789
+ if (!value)
790
+ continue;
791
+ const pageSize = 100;
792
+ let offset = 0;
793
+ while (true) {
794
+ const values = await new DB(table)
795
+ .debug(this.$state.get("DEBUG"))
796
+ .limit(pageSize)
797
+ .offset(offset)
798
+ .get();
799
+ if (!values.length) {
800
+ break;
663
801
  }
664
- const lastProp = properties[properties.length - 1];
665
- if (Array.isArray(current)) {
666
- setNestedProperty(temp, props.join("."), this.removeProperties(current, [afterProp, lastProp]));
667
- continue;
802
+ await new DB(table)
803
+ .debug(this.$state.get("DEBUG"))
804
+ .createMultiple([...values])
805
+ .bind(connTarget)
806
+ .void()
807
+ .save();
808
+ offset += values.length;
809
+ if (values.length < pageSize) {
810
+ break;
668
811
  }
669
- if (current[lastProp] == null)
670
- continue;
671
- delete current[lastProp];
672
812
  }
673
- return temp;
674
- };
675
- if (Array.isArray(data)) {
676
- return data.map((obj) => remove(obj, propertiesToRemoves));
677
813
  }
678
- return remove(data, propertiesToRemoves);
679
- }
680
- /**
681
- * The 'removeProperties' method is used to removed some properties.
682
- *
683
- * @param {Array | Record} data
684
- * @param {string[]} propertiesToRemoves
685
- * @returns {Array | Record} this
686
- */
687
- static removeProperties(data, propertiesToRemoves) {
688
- return new this().removeProperties(data, propertiesToRemoves);
689
- }
690
- /**
691
- *
692
- * This 'backup' method is used to backup database intro new database same server or to another server
693
- * @type {Object} backup
694
- * @property {string} backup.database clone current 'db' in connection to this database
695
- * @type {object?} backup.to
696
- * @property {string} backup.to.host
697
- * @property {number} backup.to.port
698
- * @property {string} backup.to.username
699
- * @property {string} backup.to.password
700
- * @returns {Promise<void>}
701
- */
702
- async backup({ database, to }) {
703
- const tables = await this.getTables();
704
- const backup = await this._backup({ tables, database, to });
705
- const creating = async ({ table, values, }) => {
706
- try {
707
- await table();
708
- await values();
814
+ if (createFks.length) {
815
+ for (const createFk of createFks) {
816
+ await new DB()
817
+ .debug(this.$state.get("DEBUG"))
818
+ .bind(connTarget)
819
+ .query(createFk);
709
820
  }
710
- catch (e) { }
711
- };
712
- await Promise.all(backup.map((b) => creating({ table: b.table, values: b.values })));
821
+ }
822
+ if (createIndexs.length) {
823
+ for (const createIndex of createIndexs) {
824
+ await new DB()
825
+ .debug(this.$state.get("DEBUG"))
826
+ .bind(connTarget)
827
+ .query(createIndex);
828
+ }
829
+ }
713
830
  return;
714
831
  }
715
832
  /**
716
- *
717
- * This 'backup' method is used to backup database intro new database same server or to another server
718
- * @type {Object} backup
719
- * @property {string} backup.database clone current 'db' in connection to this database
720
- * @type {object?} backup.to
721
- * @property {string} backup.to.host
722
- * @property {number} backup.to.port
723
- * @property {string} backup.to.username
724
- * @property {string} backup.to.password
725
- * @returns {Promise<void>}
726
- */
727
- static async backup({ database, to }) {
728
- return new this().backup({ database, to });
833
+ * This'clone' method is used to clone the current database into a new database
834
+ * on the same server or another server.
835
+ *
836
+ * @static
837
+ * @property {string} database - Target database name.
838
+ * @property {string[]} excludes - Tables to exclude from the clone.
839
+ * @property {object} to - Target server connection.
840
+ * @property {string} to.host - Target server host.
841
+ * @property {number} to.port - Target server port.
842
+ * @property {string} to.username - Target server username.
843
+ * @property {string} to.password - Target server password.
844
+ * @returns {Promise<void>}
845
+ */
846
+ static async clone({ database, only, excludes, value, to }) {
847
+ if (excludes) {
848
+ return new this().clone({ database, excludes, value, to });
849
+ }
850
+ ;
851
+ return new this().clone({ database, only, value, to });
729
852
  }
730
853
  /**
731
854
  *
732
- * This 'backupToFile' method is used to backup database intro new ${file}.sql
733
- * @type {Object} backup
734
- * @property {string} backup.database
735
- * @property {string} backup.filePath
736
- * @type {object?} backup.connection
737
- * @property {string} backup.connection.host
738
- * @property {number} backup.connection.port
739
- * @property {number} backup.connection.database
740
- * @property {string} backup.connection.username
741
- * @property {string} backup.connection.password
855
+ * This 'dump' method is used to Dumps a database into a SQL file
856
+ * @type {Object} opt
857
+ * @property {string?} opt.database
858
+ * @property {string} opt.filePath
859
+ * @property {string[]} opt.excludes
860
+ * @property {boolean?} opt.value
742
861
  * @returns {Promise<void>}
743
862
  */
744
- async backupToFile({ filePath, database = `dump_${+new Date()}`, connection, }) {
745
- await this.$utils.wait(1000 * 5);
746
- const tables = await this.getTables();
747
- const sqlFormatted = (sql) => {
748
- const statements = sql
749
- .split(";")
750
- .map((s) => s.trim())
751
- .filter(Boolean);
752
- const formattedStatements = statements.map((stmt) => {
753
- if (stmt.includes("(")) {
754
- const firstParen = stmt.indexOf("(");
755
- const lastParen = stmt.lastIndexOf(")");
756
- if (firstParen === -1 || lastParen === -1)
757
- return stmt + ";";
758
- const prefix = stmt.slice(0, firstParen).trim();
759
- let columnsPart = stmt.slice(firstParen + 1, lastParen).trim();
760
- const colArray = [];
761
- let parenCount = 0;
762
- let start = 0;
763
- for (let i = 0; i < columnsPart.length; i++) {
764
- const char = columnsPart[i];
765
- if (char === "(")
766
- parenCount++;
767
- if (char === ")")
768
- parenCount--;
769
- if (char === "," && parenCount === 0) {
770
- colArray.push(columnsPart.slice(start, i).trim());
771
- start = i + 1;
772
- }
773
- }
774
- colArray.push(columnsPart.slice(start).trim());
775
- const seen = new Set();
776
- const uniqueColumns = colArray.filter((col) => {
777
- const colNameMatch = col.match(/"([\w]+)"/) || col.match(/([\w]+)/);
778
- const colName = colNameMatch ? colNameMatch[1] : col;
779
- if (seen.has(colName))
780
- return false;
781
- seen.add(colName);
782
- return true;
783
- });
784
- const formattedColumns = uniqueColumns
785
- .map((c) => " " + c)
786
- .join(",\n");
787
- return `${prefix} (\n${formattedColumns}\n)`;
788
- }
789
- else {
790
- return stmt;
791
- }
792
- });
793
- return formattedStatements.join(";\n\n");
794
- };
795
- const backup = (await this._backupToString({ tables, database })).map((b) => {
796
- return {
797
- table: [
798
- `\n--`,
799
- `-- Table structure for table '${b.name}'`,
800
- `--\n`,
801
- `${sqlFormatted(b.table())}`,
802
- ].join("\n") + ";",
803
- values: b.values().length
804
- ? [
805
- `\n--`,
806
- `-- Dumping data for table '${b.name}'`,
807
- `--\n`,
808
- `${b
809
- .values()
810
- .map((v) => `${v}`)
811
- .join(",\n")}`,
812
- ].join("\n")
813
- : "",
814
- };
815
- });
816
- if (connection != null && Object.keys(connection)?.length)
817
- this.connection(connection);
818
- let sql = [
863
+ async dump({ filePath, excludes, only, database = `dump_${+new Date()}`, value = false }) {
864
+ if (!filePath.toLowerCase().endsWith(".sql")) {
865
+ filePath += ".sql";
866
+ }
867
+ await Package_1.Package.fs.promises.mkdir(Package_1.Package.path.dirname(filePath), { recursive: true });
868
+ const raws = only ? only : await this.getTables();
869
+ const tables = raws.filter(r => !excludes?.includes(r));
870
+ const qb = this.getQueryBuilder();
871
+ const headers = [
819
872
  `--`,
820
873
  `-- tspace-mysql SQL Dump`,
821
874
  `-- https://www.npmjs.com/package/tspace-mysql`,
822
875
  `--`,
823
- `-- Host: mysql-db`,
876
+ `-- Driver: '${this.$driver}'`,
824
877
  `-- Generation Time: ${new Date()}\n`,
825
- `SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";`,
826
- `START TRANSACTION;`,
827
878
  `--`,
828
879
  `-- Database: '${database}'`,
829
880
  `--\n`,
830
- `${this.$constants("CREATE_DATABASE_NOT_EXISTS")} ${database};`,
831
- `USE ${database};`,
881
+ `${qb.createDatabase(database)};`,
882
+ `${qb.useDatabase(database)};`,
883
+ `--\n`,
832
884
  `-- --------------------------------------------------------`,
833
- ];
834
- for (const b of backup) {
835
- sql = [...sql, b.table];
836
- if (b.values) {
837
- sql = [...sql, b.values];
885
+ ].map(v => qb.format(v)).join('\n');
886
+ const stream = Package_1.Package.fs.createWriteStream(filePath, {
887
+ encoding: "utf8",
888
+ });
889
+ const write = async (data) => {
890
+ if (stream.write(data)) {
891
+ return;
838
892
  }
893
+ await new Promise((resolve) => {
894
+ stream.once("drain", resolve);
895
+ });
896
+ };
897
+ const formatCreateTable = (table, createTable) => {
898
+ return [
899
+ `\n--`,
900
+ `-- Table structure for table '${table}'`,
901
+ `--`,
902
+ `${this.$utils.sqlFormatted(createTable)}`,
903
+ ].join("\n") + ";";
904
+ };
905
+ const formatInsertValues = (value, maxChunkSize = 1024 * 1024) => {
906
+ if (!value.length)
907
+ return "";
908
+ const result = [];
909
+ let buffer = "";
910
+ const line = String(value) + "\n";
911
+ if (buffer.length + line.length > maxChunkSize) {
912
+ if (buffer) {
913
+ result.push(buffer);
914
+ buffer = "";
915
+ }
916
+ }
917
+ buffer += line;
918
+ if (buffer) {
919
+ result.push(buffer);
920
+ }
921
+ return result.join("");
922
+ };
923
+ try {
924
+ stream.write(headers);
925
+ stream.write("\n");
926
+ const createFks = [];
927
+ const createIndexs = [];
928
+ const startTime = Date.now();
929
+ let totalRows = 0;
930
+ for (let i = 0; i < tables.length; i++) {
931
+ const qb = this.getQueryBuilder();
932
+ const table = tables[i];
933
+ const tableStartTime = Date.now();
934
+ const fks = await this.getFKs(table).catch(_ => []);
935
+ for (const fk of fks) {
936
+ createFks.push(qb.addFK({
937
+ table: table,
938
+ tableRef: fk.RefTable,
939
+ constraint: fk.Constraint,
940
+ key: fk.Column,
941
+ foreign: {
942
+ references: fk.RefColumn,
943
+ onDelete: fk.OnDelete,
944
+ onUpdate: fk.OnUpdate,
945
+ }
946
+ }));
947
+ }
948
+ const indexs = await this.getIndexes(table).catch(_ => []);
949
+ for (const index of indexs) {
950
+ createIndexs.push(qb.addIndex({
951
+ table: table,
952
+ name: index.IndexName,
953
+ columns: index.Column.split(',')
954
+ }));
955
+ }
956
+ const progress = Math.round(((i + 1) / tables.length) * 100);
957
+ console.log(`\n[${String(progress).padStart(3, " ")}%] ` +
958
+ `[${i + 1}/${tables.length}] ${table}`);
959
+ const schema = await this.showSchema(table);
960
+ const createTable = qb.createTable({
961
+ database,
962
+ table,
963
+ schema
964
+ });
965
+ await write(formatCreateTable(table, createTable));
966
+ await write("\n");
967
+ console.log(` ├─ schema ✓`);
968
+ if (!value) {
969
+ console.log(` └─ done in ${((Date.now() - tableStartTime) / 1000).toFixed(2)}s`);
970
+ continue;
971
+ }
972
+ const pageSize = 100;
973
+ let offset = 0;
974
+ let page = 0;
975
+ let tableRows = 0;
976
+ let wasWritten = false;
977
+ while (true) {
978
+ const values = await this.table(table)
979
+ .limit(pageSize)
980
+ .offset(offset)
981
+ .get();
982
+ if (!values.length) {
983
+ break;
984
+ }
985
+ if (!wasWritten) {
986
+ const hearder = `\n--\n` +
987
+ `-- Dumping data for table '${table}'\n` +
988
+ `--\n`;
989
+ await write(hearder);
990
+ wasWritten = true;
991
+ }
992
+ const sql = this.table(table)
993
+ .createMultiple([...values])
994
+ .toString();
995
+ await write(formatInsertValues(sql + ";"));
996
+ tableRows += values.length;
997
+ totalRows += values.length;
998
+ offset += pageSize;
999
+ page++;
1000
+ if (values.length < pageSize) {
1001
+ break;
1002
+ }
1003
+ console.log(` ├─ page ${page} | rows: ${tableRows.toLocaleString()}`);
1004
+ }
1005
+ await write("\n");
1006
+ const elapsed = ((Date.now() - tableStartTime) / 1000).toFixed(2);
1007
+ console.log(` ├─ rows: ${tableRows.toLocaleString()}`);
1008
+ console.log(` ├─ pages: ${page}`);
1009
+ console.log(` └─ done in ${elapsed}s`);
1010
+ }
1011
+ if (createFks.length) {
1012
+ const header = `\n--\n` +
1013
+ `-- Foreign key constraints\n` +
1014
+ `--\n`;
1015
+ await write(header);
1016
+ for (const createFk of createFks) {
1017
+ await write(createFk + ";\n");
1018
+ }
1019
+ }
1020
+ if (createIndexs.length) {
1021
+ const header = `\n--\n` +
1022
+ `-- Index key constraints\n` +
1023
+ `--\n`;
1024
+ await write(header);
1025
+ for (const createIndex of createIndexs) {
1026
+ await write(createIndex + ";\n");
1027
+ }
1028
+ }
1029
+ const tail = [
1030
+ `--`,
1031
+ `--`,
1032
+ `-- --------------------------------------------------------`,
1033
+ ].join('\n');
1034
+ await write("\n" + tail);
1035
+ const totalTime = ((Date.now() - startTime) / 1000).toFixed(2);
1036
+ console.log(`\n[DONE] Dump completed: ${tables.length} tables, ` +
1037
+ `${totalRows.toLocaleString()} rows, ${totalTime}s`);
1038
+ stream.end();
1039
+ await new Promise((resolve) => {
1040
+ stream.once("finish", resolve);
1041
+ });
1042
+ }
1043
+ catch (error) {
1044
+ stream.destroy();
1045
+ throw error;
839
1046
  }
840
- Package_1.Package.fs.writeFileSync(filePath, [...sql, "COMMIT;"].join("\n"));
841
1047
  return;
842
1048
  }
843
1049
  /**
1050
+ * This 'dump' method is used to Dumps a database into a SQL file
844
1051
  *
845
- * This 'backupToFile' method is used to backup database intro new ${file}.sql
846
- * @type {Object} backup
847
- * @property {string} backup.database
848
- * @property {string} backup.filePath
849
- * @type {object?} backup.connection
850
- * @property {string} backup.connection.host
851
- * @property {number} backup.connection.port
852
- * @property {number} backup.connection.database
853
- * @property {string} backup.connection.username
854
- * @property {string} backup.connection.password
1052
+ * @static
1053
+ * @type {Object} opt
1054
+ * @property {string?} opt.database
1055
+ * @property {string} opt.filePath
1056
+ * @property {string[]} opt.excludes
1057
+ * @property {boolean?} opt.value
855
1058
  * @returns {Promise<void>}
856
1059
  */
857
- static async backupToFile({ filePath, database, connection, }) {
858
- return new this().backupToFile({ filePath, database, connection });
1060
+ static async dump({ filePath, database, excludes, only, value, }) {
1061
+ if (excludes) {
1062
+ return new this().dump({ filePath, database, excludes, value });
1063
+ }
1064
+ ;
1065
+ return new this().dump({ filePath, database, only, value });
859
1066
  }
860
1067
  /**
1068
+ * This 'session' method is used to manage database session variables.
861
1069
  *
862
- * This 'backupSchemaToFile' method is used to backup database intro new ${file}.sql
863
- * @type {Object} backup
864
- * @property {string} backup.database
865
- * @property {string} backup.filePath
866
- * @type {object?} backup.connection
867
- * @property {string} backup.connection.host
868
- * @property {number} backup.connection.port
869
- * @property {number} backup.connection.database
870
- * @property {string} backup.connection.username
871
- * @property {string} backup.connection.password
872
- * @returns {Promise<void>}
873
- */
874
- async backupSchemaToFile({ filePath, database = `dump_${+new Date()}`, connection, }) {
875
- if (connection != null && Object.keys(connection)?.length)
876
- this.connection(connection);
877
- await this.$utils.wait(1000 * 3);
878
- const tables = await this.getTables();
879
- const backup = (await this._backupToString({ tables, database })).map((b) => {
880
- return {
881
- table: (0, sql_formatter_1.format)(b.table(), {
882
- language: "spark",
883
- tabWidth: 2,
884
- linesBetweenQueries: 1,
885
- }) + "\n",
886
- };
887
- });
888
- let sql = [
889
- `SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";`,
890
- `START TRANSACTION;`,
891
- `SET time_zone = "+00:00";`,
892
- `${this.$constants("CREATE_DATABASE_NOT_EXISTS")} \`${database}\`;`,
893
- `USE \`${database}\`;`,
894
- ];
895
- for (const b of backup)
896
- sql = [...sql, b.table];
897
- Package_1.Package.fs.writeFileSync(filePath, [...sql, "COMMIT;"].join("\n"));
898
- return;
899
- }
900
- /**
1070
+ * Provides methods to get and set session variables for the current
1071
+ * database connection.
901
1072
  *
902
- * This 'backupSchemaToFile' method is used to backup database intro new ${file}.sql
903
- *
904
- * @type {Object} backup
905
- * @property {string} backup.database
906
- * @property {string} backup.filePath
907
- * @type {object?} backup.connection
908
- * @property {string} backup.connection.host
909
- * @property {number} backup.connection.port
910
- * @property {number} backup.connection.database
911
- * @property {string} backup.connection.username
912
- * @property {string} backup.connection.password
913
- * @returns {Promise<void>}
914
- */
915
- static async backupSchemaToFile({ filePath, database, connection, }) {
916
- return new this().backupSchemaToFile({ filePath, database, connection });
917
- }
918
- /**
1073
+ * Supported drivers:
1074
+ * - MySQL
1075
+ * - MariaDB
1076
+ * - PostgreSQL
1077
+ * - SQLite
919
1078
  *
920
- * This 'backupTableToFile' method is used to backup database intro new ${file}.sql
921
- *
922
- * @type {Object} backup
923
- * @property {string} backup.database
924
- * @property {string} backup.filePath
925
- * @type {object?} backup.connection
926
- * @property {string} backup.connection.host
927
- * @property {number} backup.connection.port
928
- * @property {number} backup.connection.database
929
- * @property {string} backup.connection.username
930
- * @property {string} backup.connection.password
931
- * @returns {Promise<void>}
1079
+ * MongoDB is not supported.
1080
+ *
1081
+ * @example
1082
+ * ```ts
1083
+ * await DB.session().set('db', 'primary');
1084
+ *
1085
+ * const value = await db.session().get('db');
1086
+ * console.log(value) // primary
1087
+ *
1088
+ * ```
932
1089
  */
933
- async backupTableToFile({ filePath, table, connection, }) {
934
- if (connection != null && Object.keys(connection)?.length)
935
- this.connection(connection);
936
- /**
937
- *
938
- * wait for the connection to new db connected
939
- */
940
- await this.$utils.wait(1000 * 5);
941
- const schemas = await this.showSchema(table);
942
- const createTableSQL = [
943
- `${this.$constants("CREATE_TABLE_NOT_EXISTS")}`,
944
- `\`${table}\``,
945
- `(${schemas.join(",")})`,
946
- `${this.$constants("ENGINE")};`,
947
- ];
948
- const values = await this.showValues(table);
949
- let valueSQL = [];
950
- if (values.length) {
951
- const columns = await this.showColumns(table);
952
- valueSQL = [
953
- `${this.$constants("INSERT")}`,
954
- `\`${table}\``,
955
- `(${columns.map((column) => `\`${column}\``).join(",")})`,
956
- `${this.$constants("VALUES")} ${values.join(",")};`,
957
- ];
1090
+ session() {
1091
+ if (this.driver() === 'mongodb') {
1092
+ throw new Error('Session is not supported for MongoDB. Use a different driver or disable sessions features.');
958
1093
  }
959
- const sql = [
960
- (0, sql_formatter_1.format)(createTableSQL.join(" "), {
961
- language: "mysql",
962
- tabWidth: 2,
963
- linesBetweenQueries: 1,
964
- }) + "\n",
965
- valueSQL.join(" "),
966
- ];
967
- Package_1.Package.fs.writeFileSync(filePath, [...sql, "COMMIT;"].join("\n"));
968
- return;
1094
+ const self = this;
1095
+ const qb = this.getQueryBuilder();
1096
+ return {
1097
+ async get(name) {
1098
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
1099
+ throw new Error(`Invalid session variable name: ${name}`);
1100
+ }
1101
+ const raw = await self.query(qb.getSession(self.escape(name)));
1102
+ if (!Array.isArray(raw) || !raw[0]) {
1103
+ return null;
1104
+ }
1105
+ const session = (raw[0][name] ?? null);
1106
+ return session === '' ? null : session;
1107
+ },
1108
+ async set(name, value) {
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.setSession(self.escape(name), self.escape(value)));
1113
+ return;
1114
+ },
1115
+ async delete(name) {
1116
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
1117
+ throw new Error(`Invalid session variable name: ${name}`);
1118
+ }
1119
+ await self.query(qb.deleteSession(self.escape(name)));
1120
+ return;
1121
+ },
1122
+ };
969
1123
  }
970
1124
  /**
1125
+ * This 'session' method is used to manage database session variables.
971
1126
  *
972
- * This 'backupTableSchemaToFile' method is used to backup database intro new ${file}.sql
973
- * @type {Object} backup
974
- * @property {string} backup.table
975
- * @property {string} backup.filePath
976
- * @type {object?} backup.connection
977
- * @property {string} backup.connection.host
978
- * @property {number} backup.connection.port
979
- * @property {number} backup.connection.database
980
- * @property {string} backup.connection.username
981
- * @property {string} backup.connection.password
982
- * @returns {Promise<void>}
983
- */
984
- static async backupTableToFile({ filePath, table, connection, }) {
985
- return new this().backupTableToFile({ filePath, table, connection });
986
- }
987
- /**
1127
+ * Provides methods to get and set session variables for the current
1128
+ * database connection.
988
1129
  *
989
- * This 'backupTableSchemaToFile' method is used to backup database intro new ${file}.sql
990
- * @type {Object} backup
991
- * @property {string} backup.database
992
- * @property {string} backup.filePath
993
- * @type {object?} backup.connection
994
- * @property {string} backup.connection.host
995
- * @property {number} backup.connection.port
996
- * @property {number} backup.connection.database
997
- * @property {string} backup.connection.username
998
- * @property {string} backup.connection.password
999
- * @returns {Promise<void>}
1000
- */
1001
- async backupTableSchemaToFile({ filePath, table, connection, }) {
1002
- const schemas = await this.showSchema(table);
1003
- const createTableSQL = [
1004
- `${this.$constants("CREATE_TABLE_NOT_EXISTS")}`,
1005
- `\`${table}\``,
1006
- `(${schemas.join(",")})`,
1007
- `${this.$constants("ENGINE")};`,
1008
- ];
1009
- const sql = [createTableSQL.join(" ")];
1010
- if (connection != null && Object.keys(connection)?.length)
1011
- this.connection(connection);
1012
- await this.$utils.wait(1000 * 5);
1013
- Package_1.Package.fs.writeFileSync(filePath, (0, sql_formatter_1.format)(sql.join("\n"), {
1014
- language: "spark",
1015
- tabWidth: 2,
1016
- linesBetweenQueries: 1,
1017
- }));
1018
- return;
1019
- }
1020
- /**
1130
+ * Supported drivers:
1131
+ * - MySQL
1132
+ * - MariaDB
1133
+ * - PostgreSQL
1134
+ * - SQLite
1021
1135
  *
1022
- * This 'backupTableSchemaToFile' method is used to backup database intro new ${file}.sql
1023
- * @type {Object} backup
1024
- * @property {string} backup.table
1025
- * @property {string} backup.filePath
1026
- * @type {object?} backup.connection
1027
- * @property {string} backup.connection.host
1028
- * @property {number} backup.connection.port
1029
- * @property {number} backup.connection.database
1030
- * @property {string} backup.connection.username
1031
- * @property {string} backup.connection.password
1032
- * @returns {Promise<void>}
1136
+ * MongoDB is not supported.
1137
+ *
1138
+ * @static
1139
+ *
1140
+ * @example
1141
+ * ```ts
1142
+ * await DB.session().set('db', 'primary');
1143
+ *
1144
+ * const value = await db.session().get('db');
1145
+ * console.log(value) // primary
1146
+ *
1147
+ * ```
1033
1148
  */
1034
- static async backupTableSchemaToFile({ filePath, table, connection, }) {
1035
- return new this().backupTableSchemaToFile({ filePath, table, connection });
1036
- }
1037
- async _backup({ tables, database, to, }) {
1038
- const backup = [];
1039
- const conn = await new DB().getConnection({ ...(to ?? this.$credentials) });
1040
- const db = await new DB()
1041
- .bind(conn)
1042
- .query(this._queryBuilder().getDatabase(database));
1043
- if (Object.values(db[0] ?? []).length) {
1044
- throw new Error(`This database : '${database}' is already exists`);
1045
- }
1046
- await new DB()
1047
- .bind(conn)
1048
- .query(`${this.$constants("CREATE_DATABASE")} \`${database}\``);
1049
- const connWithDatabase = await new DB().getConnection({
1050
- ...(to ?? this.$credentials),
1051
- database,
1052
- });
1053
- for (const table of tables) {
1054
- const schema = await new DB()
1055
- .debug(this.$state.get("DEBUG"))
1056
- .showSchema(table);
1057
- const values = await new DB(table).debug(this.$state.get("DEBUG")).get();
1058
- backup.push({
1059
- name: table == null ? "" : table,
1060
- table: async () => {
1061
- await new DB()
1062
- .debug(this.$state.get("DEBUG"))
1063
- .bind(connWithDatabase)
1064
- .query(this._queryBuilder().createTable({ database, table, schema }));
1065
- return;
1066
- },
1067
- values: async () => {
1068
- if (!values.length)
1069
- return;
1070
- const chunked = this.$utils.chunkArray([...values], 1000);
1071
- const promises = [];
1072
- for (const data of chunked) {
1073
- promises.push(() => {
1074
- return new DB(table)
1075
- .debug(this.$state.get("DEBUG"))
1076
- .createMultiple([...data])
1077
- .bind(connWithDatabase)
1078
- .void()
1079
- .save();
1080
- });
1081
- }
1082
- await Promise.all(promises.map((v) => v()));
1083
- return;
1084
- },
1085
- });
1086
- }
1087
- return backup;
1088
- }
1089
- async _backupToString({ tables, database, }) {
1090
- const backup = [];
1091
- for (const table of tables) {
1092
- const schema = await this.showSchema(table);
1093
- const values = await this.table(table).get();
1094
- // const values :any[] = []
1095
- backup.push({
1096
- name: table == null ? "" : table,
1097
- table: () => {
1098
- return this._queryBuilder().createTable({ database, table, schema });
1099
- },
1100
- values: () => {
1101
- if (!values.length)
1102
- return [];
1103
- const chunked = this.$utils.chunkArray([...values], values.length > 500 ? 500 : 10);
1104
- const str = [];
1105
- for (const data of chunked) {
1106
- const sql = this.table(table)
1107
- .createMultiple([...data])
1108
- .toString();
1109
- str.push(sql);
1110
- }
1111
- return str;
1112
- },
1113
- });
1114
- }
1115
- return backup;
1149
+ static session() {
1150
+ return new this().session();
1116
1151
  }
1117
1152
  _initialDB() {
1118
1153
  this.$state = new StateManager_1.StateManager("db");