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/README.md
CHANGED
|
@@ -95,7 +95,9 @@ npm install -D typescript@5.9.3
|
|
|
95
95
|
- [Query Builder](#query-builder)
|
|
96
96
|
- [Table Name & Alias Name](#table-name--alias-name)
|
|
97
97
|
- [Returning Results](#returning-results)
|
|
98
|
-
- [Query
|
|
98
|
+
- [Query Statements](#query-statements)
|
|
99
|
+
- [Stream Statements](#stream-statements)
|
|
100
|
+
- [Session Statements](#session-statements)
|
|
99
101
|
- [Select Statements](#select-statements)
|
|
100
102
|
- [Raw Expressions](#raw-expressions)
|
|
101
103
|
- [Ordering, Grouping, Limit and Offset](#ordering-grouping-limit-and-offset)
|
|
@@ -128,6 +130,7 @@ npm install -D typescript@5.9.3
|
|
|
128
130
|
- [Unset Statements](#unset-statements)
|
|
129
131
|
- [Common Table Expressions](#common-table-expressions)
|
|
130
132
|
- [Union](#union)
|
|
133
|
+
- [Explain](#explain)
|
|
131
134
|
- [More Methods](#more-methods)
|
|
132
135
|
- [Database Transactions](#database-transactions)
|
|
133
136
|
- [Race Condition](#race-condition)
|
|
@@ -190,6 +193,8 @@ npm install -D typescript@5.9.3
|
|
|
190
193
|
- [Repository Transactions](#repository-transactions)
|
|
191
194
|
- [Repository Relations](#repository-relations)
|
|
192
195
|
- [Queue](#queue)
|
|
196
|
+
- [Queue Events](#queue-events)
|
|
197
|
+
- [Queue Type-safe Events and Jobs](#queue-type-safe-events-and-jobs)
|
|
193
198
|
- [View](#view)
|
|
194
199
|
- [Stored Procedure](#stored-procedure)
|
|
195
200
|
- [Blueprint](#blueprint)
|
|
@@ -323,7 +328,7 @@ To connect your application to a Cluster database, use the following configurati
|
|
|
323
328
|
|
|
324
329
|
```js
|
|
325
330
|
// ----------------------------------------------------
|
|
326
|
-
//
|
|
331
|
+
// @Example MariaDB Galera Cluster
|
|
327
332
|
|
|
328
333
|
DB_DRIVER = mariadb
|
|
329
334
|
DB_HOST = host-load-balncer ❌
|
|
@@ -335,20 +340,156 @@ DB_DATABASE = database
|
|
|
335
340
|
|
|
336
341
|
```js
|
|
337
342
|
// ----------------------------------------------------
|
|
343
|
+
// Configure multiple database nodes using comma-separated connection values.
|
|
344
|
+
|
|
338
345
|
// MariaDB Galera Cluster
|
|
339
|
-
// host1
|
|
340
|
-
// host2
|
|
341
|
-
|
|
346
|
+
// host1 → Primary node
|
|
347
|
+
// host2 → Replica node 1
|
|
348
|
+
// host3 → Replica node 2
|
|
342
349
|
DB_DRIVER = mariadb
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
// master can be more than 1
|
|
346
|
-
// DB_HOST = master@host1,slave@host2,slave@host3
|
|
350
|
+
// Host 1 remains the primary; hosts 2 and 3 are replicas.
|
|
351
|
+
DB_HOST = host1,host2,host3
|
|
347
352
|
DB_PORT = 3306,3307,3308
|
|
348
353
|
DB_USERNAME = root1,root2,root3
|
|
349
354
|
DB_PASSWORD = password1,password2,password3
|
|
350
355
|
DB_DATABASE = database
|
|
351
356
|
```
|
|
357
|
+
Example Flow
|
|
358
|
+
|
|
359
|
+
```text
|
|
360
|
+
┌─────────────────┐
|
|
361
|
+
│ Application │
|
|
362
|
+
└────────┬────────┘
|
|
363
|
+
│
|
|
364
|
+
┌────────────┴────────────┐
|
|
365
|
+
│ │
|
|
366
|
+
WRITE → READ READ
|
|
367
|
+
│ │
|
|
368
|
+
▼ ▼
|
|
369
|
+
┌─────────────────┐ ┌─────────────────┐
|
|
370
|
+
│ host1 │ │ Random Replica │
|
|
371
|
+
│ PRIMARY │ │ │
|
|
372
|
+
└─────────────────┘ └────────┬────────┘
|
|
373
|
+
│
|
|
374
|
+
┌──────┴──────┐
|
|
375
|
+
▼ ▼
|
|
376
|
+
┌────────────┐ ┌────────────┐
|
|
377
|
+
│ host2 │ │ host3 │
|
|
378
|
+
│ REPLICA 1 │ │ REPLICA 2 │
|
|
379
|
+
└────────────┘ └────────────┘
|
|
380
|
+
```
|
|
381
|
+
Node Selection
|
|
382
|
+
|
|
383
|
+
When no node is explicitly selected, the database automatically routes
|
|
384
|
+
queries based on the action being performed.
|
|
385
|
+
|
|
386
|
+
Write / Action Queries
|
|
387
|
+
|
|
388
|
+
Queries that modify data are automatically sent to the primary node.
|
|
389
|
+
```js
|
|
390
|
+
await new DB('users')
|
|
391
|
+
.create({
|
|
392
|
+
name: 'John'
|
|
393
|
+
})
|
|
394
|
+
.save()
|
|
395
|
+
|
|
396
|
+
await new DB('users')
|
|
397
|
+
.update({
|
|
398
|
+
name: 'John Doe'
|
|
399
|
+
})
|
|
400
|
+
.save()
|
|
401
|
+
|
|
402
|
+
await new DB('users')
|
|
403
|
+
.delete()
|
|
404
|
+
|
|
405
|
+
```
|
|
406
|
+
Read / Select Queries
|
|
407
|
+
|
|
408
|
+
Queries that only read data are automatically sent to a random replica node.
|
|
409
|
+
```js
|
|
410
|
+
await new DB('users')
|
|
411
|
+
.findMany();
|
|
412
|
+
```
|
|
413
|
+
Use the primary node explicitly:
|
|
414
|
+
|
|
415
|
+
```js
|
|
416
|
+
await new DB('users')
|
|
417
|
+
.useNode('primary') // host1
|
|
418
|
+
.findMany();
|
|
419
|
+
|
|
420
|
+
```
|
|
421
|
+
|
|
422
|
+
Use a random replica node:
|
|
423
|
+
```js
|
|
424
|
+
await new DB('users')
|
|
425
|
+
.useNode('replica') // host2,host3
|
|
426
|
+
.findMany();
|
|
427
|
+
```
|
|
428
|
+
Use a specific replica node:
|
|
429
|
+
```js
|
|
430
|
+
await new DB('users')
|
|
431
|
+
.useNode('replica', { node: 1 }) // host2
|
|
432
|
+
.findMany()
|
|
433
|
+
|
|
434
|
+
await new DB('users')
|
|
435
|
+
.useNode('replica', { node: 2 }) // host3
|
|
436
|
+
.findMany()
|
|
437
|
+
```
|
|
438
|
+
Transactions are executed on the **primary node by default**, but you can use a replica node if needed.
|
|
439
|
+
|
|
440
|
+
Use `.bind(trx)` to ensure queries are executed within the same transaction.
|
|
441
|
+
```js
|
|
442
|
+
await new DB()
|
|
443
|
+
.useNode('primary') // Primary by default; replicas can also be selected.
|
|
444
|
+
.transaction(async (trx) => {
|
|
445
|
+
await new User()
|
|
446
|
+
.create({
|
|
447
|
+
name: `tspace`,
|
|
448
|
+
email: "tspace@example.com",
|
|
449
|
+
})
|
|
450
|
+
.bind(trx) // Don't forget to bind the transaction
|
|
451
|
+
.save();
|
|
452
|
+
});
|
|
453
|
+
```
|
|
454
|
+
⚠️ Why .bind(trx) is required
|
|
455
|
+
|
|
456
|
+
The transaction is associated with a specific database connection.
|
|
457
|
+
Calling .bind(trx) ensures that the query uses the same connection and transaction context.
|
|
458
|
+
|
|
459
|
+
Without .bind(trx), the query may use another connection and will not be part of the transaction.
|
|
460
|
+
```js
|
|
461
|
+
await new DB()
|
|
462
|
+
.useNode('primary')
|
|
463
|
+
.transaction(async (trx) => {
|
|
464
|
+
|
|
465
|
+
const user = await new User()
|
|
466
|
+
.create({
|
|
467
|
+
name: `tspace`,
|
|
468
|
+
email: "tspace@example.com",
|
|
469
|
+
})
|
|
470
|
+
.bind(trx)
|
|
471
|
+
.save();
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
// ⚠️ Read operations use a random replica by default.
|
|
475
|
+
const findUser = await new User().where('id',user.id).findOne()
|
|
476
|
+
// May not be found because the query can be routed to
|
|
477
|
+
// host2 or host3 before the replication has completed.
|
|
478
|
+
|
|
479
|
+
// How to Fix Read-After-Write
|
|
480
|
+
// If you need to read data immediately after a transaction,
|
|
481
|
+
// there are two ways to ensure the read sees the latest data.
|
|
482
|
+
const fixed1 = await new User()
|
|
483
|
+
.bind(trx) // Uses the same transaction connection.
|
|
484
|
+
.where('id',user.id)
|
|
485
|
+
.findOne()
|
|
486
|
+
|
|
487
|
+
const fixed2 = await new User()
|
|
488
|
+
.useNode('primary') // Uses the same primary node selected for the transaction.
|
|
489
|
+
.where('id',user.id)
|
|
490
|
+
.findOne()
|
|
491
|
+
|
|
492
|
+
```
|
|
352
493
|
|
|
353
494
|
## SQL Like
|
|
354
495
|
SQL (Structured Query Language) is used to manage data in relational databases.
|
|
@@ -508,6 +649,10 @@ const users = await new DB("users").toRawSQL(); // sql query string
|
|
|
508
649
|
|
|
509
650
|
const users = await new DB("users").pagination(); // Object of pagination
|
|
510
651
|
|
|
652
|
+
const users = await new DB("users").cursorPagination(); // object of cursor pagination
|
|
653
|
+
|
|
654
|
+
const users = await new DB("users").stream() // object AsyncGenerator
|
|
655
|
+
|
|
511
656
|
const users = await new DB("users").makeSelectStatement() // query string for select statement
|
|
512
657
|
|
|
513
658
|
const users = await new DB("users").makeInsertStatement() // query string for insert statement
|
|
@@ -530,6 +675,77 @@ const query = await DB.query(
|
|
|
530
675
|
username : ['name1','name2']
|
|
531
676
|
})
|
|
532
677
|
// SELECT * FROM users WHERE id = '1' AND email IS NULL AND username in ('name1','name2');
|
|
678
|
+
|
|
679
|
+
const query = await DB.query(
|
|
680
|
+
"SELECT * FROM users WHERE id = ? AND email IS ? AND name IN ?",
|
|
681
|
+
[1,null,['name1','name2']]
|
|
682
|
+
)
|
|
683
|
+
// SELECT * FROM users WHERE id = '1' AND email IS NULL AND username in ('name1','name2');
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
## Stream Statements
|
|
687
|
+
stream() returns an AsyncGenerator,
|
|
688
|
+
allowing records to be processed one at a time without loading the entire result set into memory.
|
|
689
|
+
|
|
690
|
+
Using `for await...of`:
|
|
691
|
+
```js
|
|
692
|
+
const stream = new DB('users').stream();
|
|
693
|
+
|
|
694
|
+
for await (const user of stream) {
|
|
695
|
+
console.log(user);
|
|
696
|
+
}
|
|
697
|
+
```
|
|
698
|
+
|
|
699
|
+
Using `.next()` for manual iteration:
|
|
700
|
+
```js
|
|
701
|
+
const stream = new DB('users').stream();
|
|
702
|
+
while (true) {
|
|
703
|
+
const result = await stream.next();
|
|
704
|
+
|
|
705
|
+
if (result.done) {
|
|
706
|
+
break;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
const user = result.value;
|
|
710
|
+
|
|
711
|
+
console.log(user);
|
|
712
|
+
}
|
|
713
|
+
```
|
|
714
|
+
## Session Statements
|
|
715
|
+
|
|
716
|
+
```js
|
|
717
|
+
await new DB()
|
|
718
|
+
.session()
|
|
719
|
+
.set('db1','session-1');
|
|
720
|
+
|
|
721
|
+
const get = await new DB()
|
|
722
|
+
.session()
|
|
723
|
+
.get('db1');
|
|
724
|
+
|
|
725
|
+
console.log(get) // session-1
|
|
726
|
+
|
|
727
|
+
await new DB()
|
|
728
|
+
.session()
|
|
729
|
+
.delete('db1');
|
|
730
|
+
|
|
731
|
+
// When using a cluster, session variables belong to the selected node.
|
|
732
|
+
await new DB()
|
|
733
|
+
.useNode('replica', { node : 1 }) // write to node1
|
|
734
|
+
.session()
|
|
735
|
+
.set('node1','session-node-1');
|
|
736
|
+
|
|
737
|
+
const getNode1 = await new DB()
|
|
738
|
+
.useNode('replica', { node : 1 })
|
|
739
|
+
.session()
|
|
740
|
+
.get('node1');
|
|
741
|
+
|
|
742
|
+
const getNode2 = await new DB()
|
|
743
|
+
.useNode('replica', { node : 2 })
|
|
744
|
+
.session()
|
|
745
|
+
.get('node1');
|
|
746
|
+
|
|
747
|
+
console.log(getNode1) // session-node-1
|
|
748
|
+
console.log(getNode2) // null
|
|
533
749
|
```
|
|
534
750
|
|
|
535
751
|
## Select Statements
|
|
@@ -950,12 +1166,13 @@ console.log(userHasPosts)
|
|
|
950
1166
|
|
|
951
1167
|
## Paginating
|
|
952
1168
|
|
|
1169
|
+
Using `Simple pagination`:
|
|
953
1170
|
```js
|
|
954
|
-
|
|
1171
|
+
await new DB("users").pagination();
|
|
955
1172
|
// SELECT * FROM `users` LIMIT 15 OFFSET 0;
|
|
956
1173
|
// SELECT COUNT(*) AS total FROM `users`;
|
|
957
1174
|
|
|
958
|
-
|
|
1175
|
+
await new DB("users").pagination({ page: 2, limit: 5 });
|
|
959
1176
|
|
|
960
1177
|
/*
|
|
961
1178
|
SELECT * FROM `users` LIMIT 5 OFFSET 5;
|
|
@@ -966,11 +1183,14 @@ const pageTwoUsers = await new DB("users").paginate({ page: 2, limit: 5 });
|
|
|
966
1183
|
meta: {
|
|
967
1184
|
total: n,
|
|
968
1185
|
limit: 5,
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
1186
|
+
page : {
|
|
1187
|
+
total: 5,
|
|
1188
|
+
current: 2,
|
|
1189
|
+
last: n,
|
|
1190
|
+
next: 3,
|
|
1191
|
+
prev: 1
|
|
1192
|
+
}
|
|
1193
|
+
|
|
974
1194
|
},
|
|
975
1195
|
data: [...your data here]
|
|
976
1196
|
}
|
|
@@ -978,6 +1198,32 @@ const pageTwoUsers = await new DB("users").paginate({ page: 2, limit: 5 });
|
|
|
978
1198
|
*/
|
|
979
1199
|
```
|
|
980
1200
|
|
|
1201
|
+
Using `Cursor pagination`:
|
|
1202
|
+
```js
|
|
1203
|
+
await new DB("users").cursorPagination();
|
|
1204
|
+
// SELECT * FROM `users` ORDER BY `users`.`id` ASC LIMIT 16;
|
|
1205
|
+
|
|
1206
|
+
await new DB("users").cursorPagination({ limit: 5 });
|
|
1207
|
+
// SELECT * FROM `users` ORDER BY `users`.`id` ASC LIMIT 6;
|
|
1208
|
+
|
|
1209
|
+
await new DB("users").cursorPagination({ limit: 5, cursor : "eyJp..." });
|
|
1210
|
+
// SELECT * FROM `users` WHERE `users`.`id` > 5 ORDER BY `users`.`id` ASC LIMIT 6;
|
|
1211
|
+
|
|
1212
|
+
/*
|
|
1213
|
+
the results are returned
|
|
1214
|
+
{
|
|
1215
|
+
meta: {
|
|
1216
|
+
limit: 5,
|
|
1217
|
+
count: 5,
|
|
1218
|
+
next: {
|
|
1219
|
+
cursor: 'eyJp...',
|
|
1220
|
+
has: true
|
|
1221
|
+
}
|
|
1222
|
+
},
|
|
1223
|
+
data: [...your data here]
|
|
1224
|
+
}
|
|
1225
|
+
```
|
|
1226
|
+
|
|
981
1227
|
## Insert Statements
|
|
982
1228
|
|
|
983
1229
|
```js
|
|
@@ -1307,6 +1553,54 @@ const users = await new DB('users')
|
|
|
1307
1553
|
|
|
1308
1554
|
```
|
|
1309
1555
|
|
|
1556
|
+
### Explain
|
|
1557
|
+
```js
|
|
1558
|
+
const { analysis } = await new DB('users')
|
|
1559
|
+
.select('*')
|
|
1560
|
+
.where('email','explain@gmail.com')
|
|
1561
|
+
.explain()
|
|
1562
|
+
|
|
1563
|
+
// EXPLAIN (SELECT * FROM `users` WHERE `users`.`email` = 'explain@gmail.com');
|
|
1564
|
+
// returned analysis
|
|
1565
|
+
{
|
|
1566
|
+
"status": "warning",
|
|
1567
|
+
"issues": [
|
|
1568
|
+
{
|
|
1569
|
+
"type": "FULL_SCAN",
|
|
1570
|
+
"severity": "warning",
|
|
1571
|
+
"message": "A full table scan was detected."
|
|
1572
|
+
},
|
|
1573
|
+
{
|
|
1574
|
+
"type": "NO_INDEX",
|
|
1575
|
+
"severity": "warning",
|
|
1576
|
+
"message": "No index was used for this operation."
|
|
1577
|
+
},
|
|
1578
|
+
{
|
|
1579
|
+
"type": "FILTER_AFTER_SCAN",
|
|
1580
|
+
"severity": "warning",
|
|
1581
|
+
"message": "Rows are filtered after scanning the table."
|
|
1582
|
+
}
|
|
1583
|
+
],
|
|
1584
|
+
"recommendations": [
|
|
1585
|
+
"Consider adding an appropriate index for the query conditions.",
|
|
1586
|
+
"Consider adding an index for the query conditions.",
|
|
1587
|
+
"Consider an index that can apply the filter earlier."
|
|
1588
|
+
]
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
// when you add index to email
|
|
1592
|
+
// returned analysis
|
|
1593
|
+
{
|
|
1594
|
+
"status": "ok",
|
|
1595
|
+
"issues": [],
|
|
1596
|
+
"recommendations": []
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
// send sql to analysis
|
|
1600
|
+
const { analysis } = await new DB()
|
|
1601
|
+
.explain("SELECT * FROM `users` WHERE `users`.`email` LIKE '%explain@gmail.com%'")
|
|
1602
|
+
|
|
1603
|
+
```
|
|
1310
1604
|
## More Methods
|
|
1311
1605
|
|
|
1312
1606
|
```js
|
|
@@ -1531,7 +1825,7 @@ try {
|
|
|
1531
1825
|
name: `tspace`,
|
|
1532
1826
|
email: "tspace@example.com",
|
|
1533
1827
|
})
|
|
1534
|
-
.bind(trx) //
|
|
1828
|
+
.bind(trx) // Don't forget to bind the transaction
|
|
1535
1829
|
.save();
|
|
1536
1830
|
|
|
1537
1831
|
const posts = await new Post()
|
|
@@ -1839,45 +2133,25 @@ const users = await new DB('users')
|
|
|
1839
2133
|
To backup a database, you can perform the following steps:
|
|
1840
2134
|
|
|
1841
2135
|
```js
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
database: 'try-to-backup', // clone current database to this database
|
|
1849
|
-
to ?: {
|
|
2136
|
+
await new DB().clone({
|
|
2137
|
+
database: 'try-to-backup', // clone current database to new database name
|
|
2138
|
+
// Options dump value
|
|
2139
|
+
value : true,
|
|
2140
|
+
// options Can you clone current database to other server with new database
|
|
2141
|
+
to : {
|
|
1850
2142
|
host: 'localhost',
|
|
1851
2143
|
port : 3306,
|
|
1852
2144
|
username: 'username',
|
|
1853
2145
|
password: 'password',
|
|
1854
2146
|
}
|
|
1855
2147
|
})
|
|
1856
|
-
/**
|
|
1857
|
-
*
|
|
1858
|
-
* @param {string} database Database selected
|
|
1859
|
-
* @param {string} filePath file path
|
|
1860
|
-
* @param {object | null} conection defalut current connection
|
|
1861
|
-
*/
|
|
1862
|
-
const backupToFile = await new DB().backupToFile({
|
|
1863
|
-
database: 'try-to-backup',
|
|
1864
|
-
filePath: 'backup.sql',
|
|
1865
|
-
connection ?: {
|
|
1866
|
-
host: 'localhost',
|
|
1867
|
-
port : 3306,
|
|
1868
|
-
database: 'database'
|
|
1869
|
-
username: 'username',
|
|
1870
|
-
password: 'password',
|
|
1871
|
-
}
|
|
1872
|
-
})
|
|
1873
|
-
// backupToFile => backup.sql
|
|
1874
|
-
|
|
1875
|
-
/**
|
|
1876
|
-
*
|
|
1877
|
-
* @param {string} database new db name
|
|
1878
|
-
*/
|
|
1879
|
-
await new DB().cloneDB('try-to-clone')
|
|
1880
2148
|
|
|
2149
|
+
await new DB().dump({
|
|
2150
|
+
database: 'try-to-dump',
|
|
2151
|
+
filePath: 'dump.sql',
|
|
2152
|
+
// Options dump value
|
|
2153
|
+
value : true
|
|
2154
|
+
})
|
|
1881
2155
|
```
|
|
1882
2156
|
|
|
1883
2157
|
## Injection
|
|
@@ -2513,6 +2787,23 @@ await new User()
|
|
|
2513
2787
|
* }
|
|
2514
2788
|
*/
|
|
2515
2789
|
|
|
2790
|
+
/**
|
|
2791
|
+
* Query users that have related posts matching a condition,
|
|
2792
|
+
* without loading the related posts (uses WHERE EXISTS)
|
|
2793
|
+
*/
|
|
2794
|
+
await new User()
|
|
2795
|
+
.whereHas("posts", (query) => query.where('title','LIKE',"%post%"))
|
|
2796
|
+
.findOne()
|
|
2797
|
+
/**
|
|
2798
|
+
SELECT * FROM `users`
|
|
2799
|
+
WHERE EXISTS (
|
|
2800
|
+
SELECT 1 FROM `posts`
|
|
2801
|
+
WHERE `posts`.`title` LIKE '%post%' AND `users`.`id` = `posts`.`user_id`
|
|
2802
|
+
)
|
|
2803
|
+
LIMIT 1
|
|
2804
|
+
*/
|
|
2805
|
+
|
|
2806
|
+
|
|
2516
2807
|
```
|
|
2517
2808
|
|
|
2518
2809
|
#### Deeply Nested Relations
|
|
@@ -2988,22 +3279,27 @@ import { PostUser } from './PostUser'
|
|
|
2988
3279
|
|
|
2989
3280
|
class UserObserve {
|
|
2990
3281
|
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
3282
|
+
public selected(results) {
|
|
3283
|
+
console.log({ results , selected : true })
|
|
3284
|
+
}
|
|
2994
3285
|
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
3286
|
+
public created(results) {
|
|
3287
|
+
console.log({ results , created : true })
|
|
3288
|
+
}
|
|
2998
3289
|
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3290
|
+
public updated(results) {
|
|
3291
|
+
console.log({ results , updated : true })
|
|
3292
|
+
}
|
|
3002
3293
|
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
}
|
|
3294
|
+
public deleted(results) {
|
|
3295
|
+
console.log({ results , deleted : true })
|
|
3006
3296
|
}
|
|
3297
|
+
}
|
|
3298
|
+
|
|
3299
|
+
enum UserRole {
|
|
3300
|
+
Admin = 'admin',
|
|
3301
|
+
User = 'user',
|
|
3302
|
+
}
|
|
3007
3303
|
|
|
3008
3304
|
@Pattern('camelCase')
|
|
3009
3305
|
@Observer(UserObserve)
|
|
@@ -3039,6 +3335,9 @@ class User extends Model {
|
|
|
3039
3335
|
@Column(() => Blueprint.varchar(50).null())
|
|
3040
3336
|
public password !: string
|
|
3041
3337
|
|
|
3338
|
+
@Column(() => Blueprint.enum(UserRole).default(UserRole.Admin))
|
|
3339
|
+
public role !: `${UserRole}`
|
|
3340
|
+
|
|
3042
3341
|
@Column(() => Blueprint.timestamp().null())
|
|
3043
3342
|
public createdAt!: Date
|
|
3044
3343
|
|
|
@@ -3266,10 +3565,11 @@ class Post extends Model {
|
|
|
3266
3565
|
id: Blueprint.int().notNull().primary().autoIncrement(),
|
|
3267
3566
|
uuid: Blueprint.varchar(50).null(),
|
|
3268
3567
|
user_id: Blueprint.int().notNull().foreign({
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
|
|
3568
|
+
on: () => User, // or "users"
|
|
3569
|
+
// Optionals
|
|
3570
|
+
references: "id", // default "id"
|
|
3571
|
+
onDelete: "CASCADE", // default "CASCADE"
|
|
3572
|
+
onUpdate: "CASCADE", // default "CASCADE"
|
|
3273
3573
|
}),
|
|
3274
3574
|
title: Blueprint.varchar(255).null(),
|
|
3275
3575
|
created_at: Blueprint.timestamp().null(),
|
|
@@ -4174,24 +4474,53 @@ retries, priorities, and job inspection.
|
|
|
4174
4474
|
- Idle / Wake Workers automatically go idle when no jobs are available, and wake up instantly when new jobs arrive.
|
|
4175
4475
|
|
|
4176
4476
|
```js
|
|
4177
|
-
import { Queue, Job } from 'tspace-mysql';
|
|
4477
|
+
import { Queue, Job, DB } from 'tspace-mysql';
|
|
4478
|
+
|
|
4479
|
+
// Start the Queue worker
|
|
4480
|
+
await Queue.start({
|
|
4481
|
+
inspect: true, // @default false - Enable queue workflow inspection
|
|
4482
|
+
flush: true, // @default false - Remove all existing jobs before starting
|
|
4483
|
+
|
|
4484
|
+
hostname: 'pod1', // @default env.hostname - Worker hostname
|
|
4485
|
+
|
|
4486
|
+
maxIdleRetries: 8, // @default 5 - Maximum retries when no jobs are available
|
|
4487
|
+
|
|
4488
|
+
poll: {
|
|
4489
|
+
enabled: true, // @default false - Enable periodic job polling
|
|
4490
|
+
interval: 10_000, // @default 60_000 - Polling interval in milliseconds
|
|
4491
|
+
},
|
|
4492
|
+
|
|
4493
|
+
cleanup: {
|
|
4494
|
+
enabled: true, // @default false - Enable automatic job cleanup
|
|
4495
|
+
interval: 10_000, // @default 60_000 - Cleanup interval in milliseconds
|
|
4496
|
+
statuses: ['completed', 'failed'], // @default ['completed'] - Job statuses to delete
|
|
4497
|
+
},
|
|
4178
4498
|
|
|
4499
|
+
// By default, Queue uses the same database connection as your application.
|
|
4500
|
+
// You can optionally provide a separate connection for Queue.
|
|
4501
|
+
|
|
4502
|
+
// Using a separate connection configuration:
|
|
4503
|
+
connection: {
|
|
4504
|
+
driver: 'sqlite',
|
|
4505
|
+
database: 'app.db',
|
|
4506
|
+
},
|
|
4507
|
+
|
|
4508
|
+
// Or reuse an existing database connection:
|
|
4509
|
+
// connection: DB.getConnection({
|
|
4510
|
+
// driver: 'sqlite',
|
|
4511
|
+
// database: 'app.db',
|
|
4512
|
+
// }),
|
|
4513
|
+
});
|
|
4514
|
+
|
|
4515
|
+
const worker = 20;
|
|
4516
|
+
|
|
4517
|
+
// register process send email 20
|
|
4179
4518
|
const fakeSendEmail = async (job: Job) => {
|
|
4180
4519
|
if(Math.random() < 0.5) throw new Error(`Failed job ${job.id}`)
|
|
4181
4520
|
await new Promise<void>((ok) => setTimeout(ok, 2000));
|
|
4182
4521
|
return `Send email Completed job ${job.id}`;
|
|
4183
4522
|
}
|
|
4184
4523
|
|
|
4185
|
-
// start the Queue
|
|
4186
|
-
await Queue.start({
|
|
4187
|
-
inspect : true,
|
|
4188
|
-
flush : false, // flush = true -> remove all jobs
|
|
4189
|
-
hostname: 'pod1'
|
|
4190
|
-
});
|
|
4191
|
-
|
|
4192
|
-
const worker = 20;
|
|
4193
|
-
|
|
4194
|
-
// register process send email 20
|
|
4195
4524
|
for(let i = 1; i <= worker; i++) {
|
|
4196
4525
|
|
|
4197
4526
|
Queue.process(`send-email-(${i})`, async(job) => {
|
|
@@ -4209,6 +4538,8 @@ for(let j = 1; j <= worker * 500; j++) {
|
|
|
4209
4538
|
email: `John-${i}@gmail.com`,
|
|
4210
4539
|
name: `John-${i}`
|
|
4211
4540
|
}, {
|
|
4541
|
+
// Prevent duplicate jobs when triggered by cron jobs.
|
|
4542
|
+
// uniqueKey : `uq:${i}`,
|
|
4212
4543
|
delayMs : 1000 * Math.random() * 10,
|
|
4213
4544
|
priority : i % 2 ? 9999 + Math.floor((Math.random() * 9999) + 1) : 0,
|
|
4214
4545
|
maxAttempts : 3,
|
|
@@ -4226,6 +4557,83 @@ for(let j = 1; j <= worker * 500; j++) {
|
|
|
4226
4557
|
// if you want to end the Queue
|
|
4227
4558
|
// await Queue.end()
|
|
4228
4559
|
|
|
4560
|
+
```
|
|
4561
|
+
### Queue Events
|
|
4562
|
+
|
|
4563
|
+
Queue also supports an event-based publish/subscribe pattern.
|
|
4564
|
+
|
|
4565
|
+
One event can have multiple subscribers.
|
|
4566
|
+
Use Queue.subscribe() to subscribe a job handler to an event
|
|
4567
|
+
```js
|
|
4568
|
+
// user.created
|
|
4569
|
+
// │
|
|
4570
|
+
// ├── email
|
|
4571
|
+
// ├── notify
|
|
4572
|
+
// └── analytics
|
|
4573
|
+
|
|
4574
|
+
Queue.subscribe(
|
|
4575
|
+
'user.created',
|
|
4576
|
+
'email',
|
|
4577
|
+
async (job) => {
|
|
4578
|
+
await new Promise(r => setTimeout(r, 1000));
|
|
4579
|
+
console.log('Send e-mail : ' + job.payload.email)
|
|
4580
|
+
return 'Done!';
|
|
4581
|
+
},
|
|
4582
|
+
{ concurrency: 2 }
|
|
4583
|
+
);
|
|
4584
|
+
|
|
4585
|
+
Queue.subscribe(
|
|
4586
|
+
'user.created',
|
|
4587
|
+
'notify',
|
|
4588
|
+
async (job) => {
|
|
4589
|
+
await new Promise(r => setTimeout(r, 1000));
|
|
4590
|
+
console.log('notify : ' + job.payload.email)
|
|
4591
|
+
return 'Done!';
|
|
4592
|
+
},
|
|
4593
|
+
{ concurrency: 3 }
|
|
4594
|
+
);
|
|
4595
|
+
```
|
|
4596
|
+
Use Queue.publish() to publish an event.
|
|
4597
|
+
```js
|
|
4598
|
+
for (let i = 1; i <= 5; i++) {
|
|
4599
|
+
// will send to jobs ['email','notify'];
|
|
4600
|
+
Queue.publish(
|
|
4601
|
+
'user.created',
|
|
4602
|
+
{ id : i , email : `user${i}@gmail.com` },
|
|
4603
|
+
{
|
|
4604
|
+
priority: i
|
|
4605
|
+
}
|
|
4606
|
+
);
|
|
4607
|
+
}
|
|
4608
|
+
|
|
4609
|
+
```
|
|
4610
|
+
### Queue Type-safe Events and Jobs
|
|
4611
|
+
Queue optionally supports type-safe event and job names through `QueueContract`.
|
|
4612
|
+
|
|
4613
|
+
The feature is optional.
|
|
4614
|
+
|
|
4615
|
+
If the application does not define a contract, the Queue API can continue to accept normal string names.
|
|
4616
|
+
|
|
4617
|
+
Create a `types.d.ts` file in your application:
|
|
4618
|
+
```js
|
|
4619
|
+
import { QueueContract } from 'tspace-mysql';
|
|
4620
|
+
|
|
4621
|
+
declare module 'tspace-mysql' {
|
|
4622
|
+
interface QueueContract {
|
|
4623
|
+
events: {
|
|
4624
|
+
'user.created': [
|
|
4625
|
+
'email',
|
|
4626
|
+
'notify',
|
|
4627
|
+
];
|
|
4628
|
+
};
|
|
4629
|
+
|
|
4630
|
+
jobs: [
|
|
4631
|
+
'resize-video',
|
|
4632
|
+
'cleanup',
|
|
4633
|
+
];
|
|
4634
|
+
}
|
|
4635
|
+
}
|
|
4636
|
+
|
|
4229
4637
|
```
|
|
4230
4638
|
|
|
4231
4639
|
## View
|
|
@@ -4415,7 +4823,13 @@ Blueprint is a tool used for defining database schemas programmatically.
|
|
|
4415
4823
|
It allows developers to describe the structure of their database tables using a simple and intuitive syntax rather than writing SQL queries directly., you may use the:
|
|
4416
4824
|
|
|
4417
4825
|
```js
|
|
4418
|
-
import { Schema , Blueprint , DB } from 'tspace-mysql'
|
|
4826
|
+
import { Schema , Blueprint , DB } from 'tspace-mysql';
|
|
4827
|
+
|
|
4828
|
+
enum UserRole {
|
|
4829
|
+
Admin = 'admin',
|
|
4830
|
+
User = 'user',
|
|
4831
|
+
}
|
|
4832
|
+
|
|
4419
4833
|
(async () => {
|
|
4420
4834
|
await new Schema().table('users', {
|
|
4421
4835
|
id : Blueprint.int().notNull().primary().autoIncrement(),
|
|
@@ -4426,6 +4840,7 @@ import { Schema , Blueprint , DB } from 'tspace-mysql'
|
|
|
4426
4840
|
email_verify : Blueprint.tinyInt(),
|
|
4427
4841
|
password : Blueprint.varchar(255),
|
|
4428
4842
|
json : Blueprint.json(),
|
|
4843
|
+
role : Blueprint.enum(UserRole).default(UserRole.Admin)
|
|
4429
4844
|
created_at : Blueprint.null().timestamp(),
|
|
4430
4845
|
updated_at : Blueprint.null().timestamp(),
|
|
4431
4846
|
deleted_at : Blueprint.null().timestamp()
|
|
@@ -4458,6 +4873,10 @@ enum(...n)
|
|
|
4458
4873
|
date()
|
|
4459
4874
|
dateTime()
|
|
4460
4875
|
timestamp ()
|
|
4876
|
+
raw({
|
|
4877
|
+
type : 'DECIMAL(10, 2)',
|
|
4878
|
+
attribute : 'DEFAULT(1)'
|
|
4879
|
+
})
|
|
4461
4880
|
|
|
4462
4881
|
/**
|
|
4463
4882
|
* To add attributes of the schema to the database
|
|
@@ -4593,9 +5012,7 @@ tspace-mysql query "SELECT * FROM users"
|
|
|
4593
5012
|
The command will dump the database or table into a file.
|
|
4594
5013
|
|
|
4595
5014
|
```sh
|
|
4596
|
-
tspace-mysql dump:db --dir=<folder for dump>
|
|
4597
|
-
|
|
4598
|
-
tspace-mysql dump:table "table_name" --dir=<folder for dump> --values // backup with values in the table
|
|
5015
|
+
tspace-mysql dump:db --dir=<folder for dump> // backup
|
|
4599
5016
|
|
|
4600
5017
|
```
|
|
4601
5018
|
|