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