@areumtecnologia/mysql-db-handler 1.0.10 → 1.0.12
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 +146 -2
- package/lib/database-cache.js +102 -77
- package/lib/database.js +316 -21
- package/lib/databaseHandler.js +449 -384
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -26,6 +26,13 @@ A powerful, robust, and production-ready MySQL wrapper for Node.js. It features
|
|
|
26
26
|
* [Updating Records (`update`)](#updating-records-update)
|
|
27
27
|
* [Deleting Records (`delete`)](#deleting-records-delete)
|
|
28
28
|
* [jQuery DataTables Server-Side Support](#jquery-datatables-server-side-support)
|
|
29
|
+
* [Transaction Support (ACID & Transparent)](#transaction-support-acid--transparent)
|
|
30
|
+
* [1. Explicit Block (`db.transaction`)](#1-explicit-block-dbtransaction)
|
|
31
|
+
* [2. Singleton Compatibility with `AsyncLocalStorage`](#2-singleton-compatibility-with-asynclocalstorage)
|
|
32
|
+
* [3. Post-Commit Hook (`db.onCommit`)](#3-post-commit-hook-dboncommit)
|
|
33
|
+
* [4. Route Wrapper (`db.transactional`)](#4-route-wrapper-dbtransactional)
|
|
34
|
+
* [5. Express Lazy Middleware (`db.autoTransaction`)](#5-express-lazy-middleware-dbautotransaction)
|
|
35
|
+
* [6. Nested Transactions & Savepoints](#6-nested-transactions--savepoints)
|
|
29
36
|
* [Database Singleton Pattern](#database-singleton-pattern)
|
|
30
37
|
* [Error Handling Strategy](#error-handling-strategy)
|
|
31
38
|
* [Contributing](#contributing)
|
|
@@ -36,11 +43,16 @@ A powerful, robust, and production-ready MySQL wrapper for Node.js. It features
|
|
|
36
43
|
## Features
|
|
37
44
|
|
|
38
45
|
* **Connection Pooling:** Efficiently manages and recycles database connections using `mysql2/promise`.
|
|
46
|
+
* **ACID Transactions:** Comprehensive transaction management with automatic `BEGIN`, `COMMIT`, `ROLLBACK`, and safe connection release.
|
|
47
|
+
* **Transparent Singleton Support:** Powered by native Node.js `AsyncLocalStorage`. Shared table singletons automatically adopt the current transaction without passing `tx` around.
|
|
48
|
+
* **Post-Commit Hooks (`onCommit`):** Execute external tasks (banking APIs, emails, webhooks) strictly after database transactions successfully commit.
|
|
49
|
+
* **Express Lazy Middleware:** Zero-code change transactions via `db.autoTransaction()`. Reads remain non-blocking on the pool, while write operations seamlessly open and commit transactions on demand.
|
|
50
|
+
* **Savepoints (Nested Transactions):** Safely run sub-transactions with partial rollback support without aborting outer transactions.
|
|
39
51
|
* **Flexible Query Builder:** Run complex operations without writing manual SQL strings.
|
|
40
52
|
* **Automatic `IN` Handling:** Smart processing of arrays for SQL `IN` and `NOT IN` operations (including prevention of empty array query crashes).
|
|
41
|
-
* **Optional Caching Wrapper:** Native support for query and schema caching using `node-cache`
|
|
53
|
+
* **Optional Caching Wrapper:** Native support for query and schema caching using `node-cache` (automatically bypassed during active transactions).
|
|
42
54
|
* **Server-Side DataTables Integration:** Effortless integration with jQuery DataTables server-side requests, handling filters, sorting, search (global and column-based), regex, and count totals automatically.
|
|
43
|
-
* **Robust Error Handling:** Intercepts and wraps database errors in predictable objects to
|
|
55
|
+
* **Robust Error Handling:** Intercepts and wraps database errors in predictable objects outside transactions, while throwing inside transactions to ensure immediate rollback.
|
|
44
56
|
|
|
45
57
|
---
|
|
46
58
|
|
|
@@ -328,6 +340,138 @@ app.post('/api/users/dt', async (req, res) => {
|
|
|
328
340
|
});
|
|
329
341
|
```
|
|
330
342
|
|
|
343
|
+
|
|
344
|
+
---
|
|
345
|
+
|
|
346
|
+
## Transaction Support (ACID & Transparent)
|
|
347
|
+
|
|
348
|
+
The library provides first-class transaction support built on top of Node.js native `AsyncLocalStorage`. Transactions can be used explicitly or completely transparently across shared Singletons without manual connection passing.
|
|
349
|
+
|
|
350
|
+
### 1. Explicit Block (`db.transaction`)
|
|
351
|
+
|
|
352
|
+
Wrap operations in `db.transaction(callback)`. If the callback resolves, `COMMIT` is executed automatically. If an error is thrown or unhandled, `ROLLBACK` is performed automatically and the connection is safely released back to the pool.
|
|
353
|
+
|
|
354
|
+
```javascript
|
|
355
|
+
await db.transaction(async () => {
|
|
356
|
+
await usersHandler.insert({ name: 'Alice', balance: 500 });
|
|
357
|
+
await auditHandler.insert({ action: 'USER_CREATED', user: 'Alice' });
|
|
358
|
+
// If any error occurs, all operations in this block are rolled back!
|
|
359
|
+
});
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
### 2. Singleton Compatibility with `AsyncLocalStorage`
|
|
363
|
+
|
|
364
|
+
When running inside `db.transaction()`, **you do not need to pass transaction instances to your handlers**. Globally shared table handlers (Singletons) automatically bind to the active transaction of the current asynchronous execution context:
|
|
365
|
+
|
|
366
|
+
```javascript
|
|
367
|
+
// databaseController.js - Exporting global singletons
|
|
368
|
+
const db = require('./db-singleton');
|
|
369
|
+
const { DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
|
|
370
|
+
|
|
371
|
+
const customersSales = new DataBaseHandler(db, 'customers_sales');
|
|
372
|
+
const customersProducts = new DataBaseHandler(db, 'customers_products');
|
|
373
|
+
|
|
374
|
+
module.exports = { db, customersSales, customersProducts };
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
```javascript
|
|
378
|
+
// salesRouter.js - In your route handler
|
|
379
|
+
const { db, customersSales, customersProducts } = require('./databaseController');
|
|
380
|
+
|
|
381
|
+
router.post('/sales', async (req, res) => {
|
|
382
|
+
try {
|
|
383
|
+
let saleResult;
|
|
384
|
+
await db.transaction(async () => {
|
|
385
|
+
saleResult = await customersSales.insert(req.body.sale);
|
|
386
|
+
|
|
387
|
+
// Check stock and update
|
|
388
|
+
const product = (await customersProducts.select([{ id: req.body.productId }]))[0];
|
|
389
|
+
if (!product || product.stock < req.body.amount) {
|
|
390
|
+
// Throwing an error here triggers automatic ROLLBACK for both tables!
|
|
391
|
+
throw new Error('Insufficient product stock');
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
await customersProducts.update({
|
|
395
|
+
set: { stock: product.stock - req.body.amount },
|
|
396
|
+
where: { id: req.body.productId }
|
|
397
|
+
});
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
res.json(saleResult);
|
|
401
|
+
} catch (err) {
|
|
402
|
+
res.status(500).json({ error: err.message });
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
### 3. Post-Commit Hook (`db.onCommit`)
|
|
408
|
+
|
|
409
|
+
When integrating with external third-party APIs (e.g., banking APIs, payment gateways, invoice generators, SMS, emails), **never perform slow external network calls while holding database locks**.
|
|
410
|
+
|
|
411
|
+
`db.onCommit(callback)` queues actions that will run **only after the database transaction successfully commits**:
|
|
412
|
+
|
|
413
|
+
```javascript
|
|
414
|
+
await db.transaction(async () => {
|
|
415
|
+
const sale = await customersSales.insert(payload);
|
|
416
|
+
|
|
417
|
+
// Schedule bank invoice creation: only runs if DB transaction commits!
|
|
418
|
+
db.onCommit(async () => {
|
|
419
|
+
await bankApiClient.registerInvoice(sale.insertId, invoiceData);
|
|
420
|
+
});
|
|
421
|
+
});
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
### 4. Route Wrapper (`db.transactional`)
|
|
425
|
+
|
|
426
|
+
Easily wrap asynchronous route handlers or service functions to run within a transaction without nesting `try/catch` or `db.transaction` boilerplate:
|
|
427
|
+
|
|
428
|
+
```javascript
|
|
429
|
+
router.post('/orders', db.transactional(async (req, res) => {
|
|
430
|
+
const order = await ordersHandler.insert(req.body);
|
|
431
|
+
await itemsHandler.insert({ orderId: order.insertId, items: req.body.items });
|
|
432
|
+
res.json(order);
|
|
433
|
+
}));
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
### 5. Express Lazy Middleware (`db.autoTransaction`)
|
|
437
|
+
|
|
438
|
+
For maximum transparency with **zero lines changed** in your route handlers, enable the `autoTransaction` middleware in your Express app:
|
|
439
|
+
|
|
440
|
+
```javascript
|
|
441
|
+
// server.js / app.js
|
|
442
|
+
app.use(db.autoTransaction({
|
|
443
|
+
methods: ['POST', 'PUT', 'DELETE', 'PATCH'], // HTTP methods to protect
|
|
444
|
+
lazy: true // Only opens a transaction when a write operation occurs
|
|
445
|
+
}));
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
* **Lazy Allocation:** `GET` requests or routes that only execute `select` queries will not open a transaction or hold connections.
|
|
449
|
+
* **On-Demand Write:** As soon as an `insert`, `update`, or `delete` is called on any handler during the request, a dedicated transaction starts automatically.
|
|
450
|
+
* **Automatic Completion:** When `res.send()` or `res.json()` completes with HTTP status `< 400`, the transaction automatically commits. If status is `>= 400` or an exception is thrown, it rolls back automatically.
|
|
451
|
+
|
|
452
|
+
### 6. Nested Transactions & Savepoints
|
|
453
|
+
|
|
454
|
+
The library natively supports nested transactions using MySQL `SAVEPOINT`s. Calling `db.transaction()` inside an existing transaction creates a savepoint instead of a new connection:
|
|
455
|
+
|
|
456
|
+
```javascript
|
|
457
|
+
await db.transaction(async () => {
|
|
458
|
+
await mainHandler.insert({ status: 'started' });
|
|
459
|
+
|
|
460
|
+
try {
|
|
461
|
+
// Nested block runs under a SAVEPOINT
|
|
462
|
+
await db.transaction(async () => {
|
|
463
|
+
await subHandler.insert({ data: 'optional_task' });
|
|
464
|
+
throw new Error('Non-critical sub-task failed');
|
|
465
|
+
});
|
|
466
|
+
} catch (e) {
|
|
467
|
+
// Sub-task is rolled back to SAVEPOINT, but the main transaction can still commit!
|
|
468
|
+
console.warn('Sub-task skipped:', e.message);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
await mainHandler.insert({ status: 'completed' });
|
|
472
|
+
});
|
|
473
|
+
```
|
|
474
|
+
|
|
331
475
|
---
|
|
332
476
|
|
|
333
477
|
## Database Singleton Pattern
|
package/lib/database-cache.js
CHANGED
|
@@ -1,77 +1,102 @@
|
|
|
1
|
-
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
-
const
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
return
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
|
|
1
|
+
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
+
const DataBase = require('./database');
|
|
3
|
+
let NodeCache;
|
|
4
|
+
try {
|
|
5
|
+
NodeCache = require('node-cache');
|
|
6
|
+
} catch (e) {
|
|
7
|
+
// Fallback in-memory com TTL básico caso node-cache não esteja instalado
|
|
8
|
+
NodeCache = class FallbackCache {
|
|
9
|
+
constructor(options = {}) {
|
|
10
|
+
this.map = new Map();
|
|
11
|
+
this.defaultTTL = (options.stdTTL || 100) * 1000;
|
|
12
|
+
}
|
|
13
|
+
get(key) {
|
|
14
|
+
const entry = this.map.get(key);
|
|
15
|
+
if (!entry) return undefined;
|
|
16
|
+
if (entry.expiry && Date.now() > entry.expiry) {
|
|
17
|
+
this.map.delete(key);
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
return entry.val;
|
|
21
|
+
}
|
|
22
|
+
set(key, val, ttlSeconds) {
|
|
23
|
+
const ttlMs = (ttlSeconds !== undefined ? ttlSeconds * 1000 : this.defaultTTL);
|
|
24
|
+
const expiry = ttlMs > 0 ? Date.now() + ttlMs : null;
|
|
25
|
+
this.map.set(key, { val, expiry });
|
|
26
|
+
}
|
|
27
|
+
flushAll() {
|
|
28
|
+
this.map.clear();
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function safeStringify(data) {
|
|
34
|
+
try {
|
|
35
|
+
return JSON.stringify(data || [], (_, value) => {
|
|
36
|
+
if (typeof value === 'bigint') {
|
|
37
|
+
return value.toString();
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
});
|
|
41
|
+
} catch {
|
|
42
|
+
return String(data);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
class DataBaseCache extends DataBase {
|
|
47
|
+
constructor(config = {}, cacheOptions = { stdTTL: 100, checkperiod: 120 }) {
|
|
48
|
+
super(config);
|
|
49
|
+
this.cache = new NodeCache(cacheOptions);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Mantido por compatibilidade
|
|
53
|
+
createPool() {
|
|
54
|
+
return this.pool;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async query(sql, params, isWrite = false) {
|
|
58
|
+
const inTransaction = !!this.getCurrentTransaction();
|
|
59
|
+
|
|
60
|
+
// Se estiver em transação ou for escrita, bypassa o cache completamente
|
|
61
|
+
if (inTransaction || isWrite) {
|
|
62
|
+
return await super.query(sql, params, isWrite);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const key = `query_${sql}_${safeStringify(params)}`;
|
|
66
|
+
const cachedResult = this.cache.get(key);
|
|
67
|
+
|
|
68
|
+
if (cachedResult) {
|
|
69
|
+
return cachedResult;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const rows = await super.query(sql, params, isWrite);
|
|
73
|
+
if (rows && !rows.error) {
|
|
74
|
+
this.cache.set(key, rows);
|
|
75
|
+
}
|
|
76
|
+
return rows;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async getTableSchema(table) {
|
|
80
|
+
const inTransaction = !!this.getCurrentTransaction();
|
|
81
|
+
const key = `schema_${table}`;
|
|
82
|
+
|
|
83
|
+
if (!inTransaction) {
|
|
84
|
+
const cachedResult = this.cache.get(key);
|
|
85
|
+
if (cachedResult) {
|
|
86
|
+
return cachedResult;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const rows = await super.getTableSchema(table);
|
|
91
|
+
if (!inTransaction && rows && !rows.error) {
|
|
92
|
+
this.cache.set(key, rows);
|
|
93
|
+
}
|
|
94
|
+
return rows;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
clearCache() {
|
|
98
|
+
this.cache.flushAll();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = DataBaseCache;
|