@areumtecnologia/mysql-db-handler 1.0.9 → 1.0.11
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/index.js +3 -1
- package/lib/database-cache.js +49 -45
- package/lib/database.js +289 -16
- package/lib/databaseHandler.js +74 -15
- package/package.json +4 -3
- package/lib/database-singleton.js +0 -19
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/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
+
const DataBaseCache = require('./lib/database-cache');
|
|
2
3
|
const DataBase = require('./lib/database');
|
|
3
4
|
const DataBaseHandler = require('./lib/databaseHandler');
|
|
4
5
|
// We do not export the singleton by default in a library usually,
|
|
@@ -6,5 +7,6 @@ const DataBaseHandler = require('./lib/databaseHandler');
|
|
|
6
7
|
|
|
7
8
|
module.exports = {
|
|
8
9
|
DataBase,
|
|
9
|
-
DataBaseHandler
|
|
10
|
+
DataBaseHandler,
|
|
11
|
+
DataBaseCache
|
|
10
12
|
};
|
package/lib/database-cache.js
CHANGED
|
@@ -1,77 +1,81 @@
|
|
|
1
1
|
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
-
const
|
|
3
|
-
|
|
2
|
+
const DataBase = require('./database');
|
|
3
|
+
let NodeCache;
|
|
4
|
+
try {
|
|
5
|
+
NodeCache = require('node-cache');
|
|
6
|
+
} catch (e) {
|
|
7
|
+
// Fallback in-memory caso node-cache não esteja instalado
|
|
8
|
+
NodeCache = class FallbackCache {
|
|
9
|
+
constructor() {
|
|
10
|
+
this.map = new Map();
|
|
11
|
+
}
|
|
12
|
+
get(key) {
|
|
13
|
+
return this.map.get(key);
|
|
14
|
+
}
|
|
15
|
+
set(key, val) {
|
|
16
|
+
this.map.set(key, val);
|
|
17
|
+
}
|
|
18
|
+
flushAll() {
|
|
19
|
+
this.map.clear();
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
}
|
|
4
23
|
|
|
5
|
-
class DataBase {
|
|
6
|
-
constructor(config = {}) {
|
|
7
|
-
|
|
8
|
-
this.
|
|
9
|
-
this.cache = new NodeCache({ stdTTL: 100, checkperiod: 120 }); // Cache instance with a default TTL and check period.
|
|
24
|
+
class DataBaseCache extends DataBase {
|
|
25
|
+
constructor(config = {}, cacheOptions = { stdTTL: 100, checkperiod: 120 }) {
|
|
26
|
+
super(config);
|
|
27
|
+
this.cache = new NodeCache(cacheOptions);
|
|
10
28
|
}
|
|
11
29
|
|
|
12
|
-
//
|
|
30
|
+
// Mantido por compatibilidade
|
|
13
31
|
createPool() {
|
|
14
|
-
if (!this.pool) {
|
|
15
|
-
this.pool = mysql.createPool(this.config);
|
|
16
|
-
}
|
|
17
32
|
return this.pool;
|
|
18
33
|
}
|
|
19
34
|
|
|
20
|
-
async
|
|
21
|
-
|
|
22
|
-
|
|
35
|
+
async query(sql, params, isWrite = false) {
|
|
36
|
+
const inTransaction = !!this.getCurrentTransaction();
|
|
37
|
+
|
|
38
|
+
// Se estiver em transação ou for escrita, bypassa o cache completamente
|
|
39
|
+
if (inTransaction || isWrite) {
|
|
40
|
+
return await super.query(sql, params, isWrite);
|
|
23
41
|
}
|
|
24
|
-
return this.pool.getConnection();
|
|
25
|
-
}
|
|
26
42
|
|
|
27
|
-
|
|
28
|
-
const key = `query_${sql}_${JSON.stringify(params)}`;
|
|
43
|
+
const key = `query_${sql}_${JSON.stringify(params || [])}`;
|
|
29
44
|
const cachedResult = this.cache.get(key);
|
|
30
45
|
|
|
31
46
|
if (cachedResult) {
|
|
32
47
|
return cachedResult;
|
|
33
48
|
}
|
|
34
49
|
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
this.cache.set(key, rows); // Save the result in the cache.
|
|
39
|
-
return rows;
|
|
40
|
-
} catch (error) {
|
|
41
|
-
return { error };
|
|
42
|
-
} finally {
|
|
43
|
-
connection.release();
|
|
50
|
+
const rows = await super.query(sql, params, isWrite);
|
|
51
|
+
if (rows && !rows.error) {
|
|
52
|
+
this.cache.set(key, rows);
|
|
44
53
|
}
|
|
54
|
+
return rows;
|
|
45
55
|
}
|
|
46
56
|
|
|
47
|
-
// This method now uses placeholders to prevent SQL injection.
|
|
48
57
|
async getTableSchema(table) {
|
|
58
|
+
const inTransaction = !!this.getCurrentTransaction();
|
|
49
59
|
const key = `schema_${table}`;
|
|
50
|
-
const cachedResult = this.cache.get(key);
|
|
51
60
|
|
|
52
|
-
if (
|
|
53
|
-
|
|
61
|
+
if (!inTransaction) {
|
|
62
|
+
const cachedResult = this.cache.get(key);
|
|
63
|
+
if (cachedResult) {
|
|
64
|
+
return cachedResult;
|
|
65
|
+
}
|
|
54
66
|
}
|
|
55
67
|
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const connection = await this.getConnection();
|
|
60
|
-
try {
|
|
61
|
-
const [rows] = await connection.execute(sql, params); // Use execute with placeholders
|
|
62
|
-
this.cache.set(key, rows); // Save the result in the cache.
|
|
63
|
-
return rows;
|
|
64
|
-
} catch (error) {
|
|
65
|
-
return { error };
|
|
66
|
-
} finally {
|
|
67
|
-
connection.release();
|
|
68
|
+
const rows = await super.getTableSchema(table);
|
|
69
|
+
if (!inTransaction && rows && !rows.error) {
|
|
70
|
+
this.cache.set(key, rows);
|
|
68
71
|
}
|
|
72
|
+
return rows;
|
|
69
73
|
}
|
|
70
74
|
|
|
71
|
-
// Optional: A method to clear the cache if needed.
|
|
72
75
|
clearCache() {
|
|
73
76
|
this.cache.flushAll();
|
|
74
77
|
}
|
|
75
78
|
}
|
|
76
79
|
|
|
77
|
-
module.exports =
|
|
80
|
+
module.exports = DataBaseCache;
|
|
81
|
+
|
package/lib/database.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
const mysql = require('mysql2/promise');
|
|
2
|
+
const { AsyncLocalStorage } = require('node:async_hooks');
|
|
2
3
|
|
|
3
4
|
class DataBase {
|
|
4
5
|
/**
|
|
5
|
-
* Creates a database instance with a connection pool.
|
|
6
|
+
* Creates a database instance with a connection pool and async transaction context.
|
|
6
7
|
* @param {Object} [config] - Configuration object for the database connection.
|
|
7
8
|
*/
|
|
8
9
|
constructor(config) {
|
|
9
10
|
this.id = Date.now();
|
|
10
11
|
this.config = config;
|
|
11
12
|
this.pool = mysql.createPool(config);
|
|
13
|
+
this.als = new AsyncLocalStorage();
|
|
12
14
|
}
|
|
13
15
|
|
|
14
16
|
/**
|
|
15
17
|
* Retrieves the connection pool.
|
|
16
|
-
* @returns {
|
|
18
|
+
* @returns {mysql.Pool} The connection pool.
|
|
17
19
|
*/
|
|
18
20
|
getPool() {
|
|
19
21
|
return this.pool;
|
|
@@ -28,38 +30,307 @@ class DataBase {
|
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
/**
|
|
31
|
-
*
|
|
33
|
+
* Retrieves the active transaction context from AsyncLocalStorage, if any.
|
|
34
|
+
* @returns {Object|null} The current transaction context.
|
|
35
|
+
*/
|
|
36
|
+
getCurrentTransaction() {
|
|
37
|
+
return this.als.getStore() || null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Registers a callback to be executed immediately after the current transaction commits successfully.
|
|
42
|
+
* If called outside a transaction, the callback is executed asynchronously right away.
|
|
43
|
+
* @param {Function} callback - Callback function to run on commit.
|
|
44
|
+
*/
|
|
45
|
+
onCommit(callback) {
|
|
46
|
+
if (typeof callback !== 'function') {
|
|
47
|
+
throw new TypeError('O callback de onCommit deve ser uma função.');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const store = this.als.getStore();
|
|
51
|
+
if (store && store.onCommitHooks) {
|
|
52
|
+
store.onCommitHooks.push(callback);
|
|
53
|
+
} else {
|
|
54
|
+
// Se não estiver em transação, executa imediatamente sem bloquear
|
|
55
|
+
Promise.resolve().then(callback).catch(err => {
|
|
56
|
+
console.error('Erro ao executar callback de onCommit fora de transação:', err);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Executes a callback within a managed transaction.
|
|
63
|
+
* Handles BEGIN, COMMIT, ROLLBACK, connection release, and Savepoints automatically.
|
|
64
|
+
*
|
|
65
|
+
* @param {Function} callback - Async function (tx) => Promise<any>
|
|
66
|
+
* @param {Object} [options] - Transaction options.
|
|
67
|
+
* @param {string} [options.isolationLevel] - e.g. 'READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'
|
|
68
|
+
* @returns {Promise<any>} Result of the callback.
|
|
69
|
+
*/
|
|
70
|
+
async transaction(callback, options = {}) {
|
|
71
|
+
if (typeof callback !== 'function') {
|
|
72
|
+
throw new TypeError('O parâmetro callback deve ser uma função.');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const activeStore = this.als.getStore();
|
|
76
|
+
|
|
77
|
+
// Se já houver uma transação ativa com conexão, cria um Savepoint (transação aninhada)
|
|
78
|
+
if (activeStore && activeStore.transactionStarted && activeStore.connection) {
|
|
79
|
+
activeStore.depth = (activeStore.depth || 1) + 1;
|
|
80
|
+
activeStore.savepointCounter = (activeStore.savepointCounter || 0) + 1;
|
|
81
|
+
const spName = `sp_${activeStore.savepointCounter}`;
|
|
82
|
+
|
|
83
|
+
await activeStore.connection.query(`SAVEPOINT ${spName}`);
|
|
84
|
+
try {
|
|
85
|
+
const result = await callback(activeStore);
|
|
86
|
+
await activeStore.connection.query(`RELEASE SAVEPOINT ${spName}`);
|
|
87
|
+
return result;
|
|
88
|
+
} catch (error) {
|
|
89
|
+
await activeStore.connection.query(`ROLLBACK TO SAVEPOINT ${spName}`);
|
|
90
|
+
throw error;
|
|
91
|
+
} finally {
|
|
92
|
+
activeStore.depth--;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Transação Raiz
|
|
97
|
+
let connection = null;
|
|
98
|
+
const onCommitHooks = [];
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
connection = await this.getConnection();
|
|
102
|
+
|
|
103
|
+
if (options.isolationLevel) {
|
|
104
|
+
await connection.query(`SET TRANSACTION ISOLATION LEVEL ${options.isolationLevel}`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
await connection.beginTransaction();
|
|
108
|
+
|
|
109
|
+
const txContext = {
|
|
110
|
+
id: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
111
|
+
connection,
|
|
112
|
+
depth: 1,
|
|
113
|
+
savepointCounter: 0,
|
|
114
|
+
onCommitHooks,
|
|
115
|
+
transactionStarted: true,
|
|
116
|
+
isLazy: false
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const result = await this.als.run(txContext, async () => {
|
|
120
|
+
return await callback(txContext);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
await connection.commit();
|
|
124
|
+
|
|
125
|
+
// Executa hooks de pós-commit com segurança
|
|
126
|
+
for (const hook of onCommitHooks) {
|
|
127
|
+
try {
|
|
128
|
+
await hook();
|
|
129
|
+
} catch (hookErr) {
|
|
130
|
+
console.error('Erro ao executar hook de onCommit:', hookErr);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return result;
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (connection) {
|
|
137
|
+
try {
|
|
138
|
+
await connection.rollback();
|
|
139
|
+
} catch (rbErr) {
|
|
140
|
+
console.error('Erro durante rollback da transação:', rbErr);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
throw error;
|
|
144
|
+
} finally {
|
|
145
|
+
if (connection) {
|
|
146
|
+
connection.release();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Route wrapper or higher-order function to execute an async handler inside a transaction.
|
|
153
|
+
* @param {Function} fn - Async handler function.
|
|
154
|
+
* @param {Object} [options] - Options for dbi.transaction.
|
|
155
|
+
* @returns {Function} Wrapped handler.
|
|
156
|
+
*/
|
|
157
|
+
transactional(fn, options = {}) {
|
|
158
|
+
return (...args) => {
|
|
159
|
+
return this.transaction(() => fn(...args), options);
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Express middleware for automatic, transparent transaction management.
|
|
165
|
+
* Uses a lazy approach by default: only allocates a connection and begins a transaction
|
|
166
|
+
* if a write operation (insert/update/delete) is performed during the request.
|
|
167
|
+
*
|
|
168
|
+
* @param {Object} [options] - Configuration options.
|
|
169
|
+
* @param {Array<string>} [options.methods] - HTTP methods to auto-transact (default: ['POST', 'PUT', 'DELETE', 'PATCH']).
|
|
170
|
+
* @param {boolean} [options.lazy=true] - Whether to delay transaction creation until first write.
|
|
171
|
+
* @param {string} [options.isolationLevel] - Isolation level if transaction is created.
|
|
172
|
+
* @returns {Function} Express middleware.
|
|
173
|
+
*/
|
|
174
|
+
autoTransaction(options = {}) {
|
|
175
|
+
const {
|
|
176
|
+
methods = ['POST', 'PUT', 'DELETE', 'PATCH'],
|
|
177
|
+
lazy = true,
|
|
178
|
+
isolationLevel = null
|
|
179
|
+
} = options;
|
|
180
|
+
|
|
181
|
+
return (req, res, next) => {
|
|
182
|
+
const method = req.method ? req.method.toUpperCase() : 'GET';
|
|
183
|
+
const isTargetMethod = methods.includes(method);
|
|
184
|
+
|
|
185
|
+
if (!isTargetMethod && !lazy) {
|
|
186
|
+
return next();
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const onCommitHooks = [];
|
|
190
|
+
let connection = null;
|
|
191
|
+
let finalized = false;
|
|
192
|
+
|
|
193
|
+
const txContext = {
|
|
194
|
+
id: `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
195
|
+
connection: null,
|
|
196
|
+
depth: 1,
|
|
197
|
+
savepointCounter: 0,
|
|
198
|
+
onCommitHooks,
|
|
199
|
+
isLazy: lazy,
|
|
200
|
+
transactionStarted: false,
|
|
201
|
+
ensureConnection: async () => {
|
|
202
|
+
if (!connection) {
|
|
203
|
+
connection = await this.getConnection();
|
|
204
|
+
if (isolationLevel) {
|
|
205
|
+
await connection.query(`SET TRANSACTION ISOLATION LEVEL ${isolationLevel}`);
|
|
206
|
+
}
|
|
207
|
+
await connection.beginTransaction();
|
|
208
|
+
txContext.connection = connection;
|
|
209
|
+
txContext.transactionStarted = true;
|
|
210
|
+
}
|
|
211
|
+
return connection;
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
const cleanup = async (shouldCommit) => {
|
|
216
|
+
if (finalized) return;
|
|
217
|
+
finalized = true;
|
|
218
|
+
|
|
219
|
+
if (connection && txContext.transactionStarted) {
|
|
220
|
+
try {
|
|
221
|
+
if (shouldCommit) {
|
|
222
|
+
await connection.commit();
|
|
223
|
+
for (const hook of onCommitHooks) {
|
|
224
|
+
try {
|
|
225
|
+
await hook();
|
|
226
|
+
} catch (hookErr) {
|
|
227
|
+
console.error('Erro ao executar hook de onCommit no middleware:', hookErr);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} else {
|
|
231
|
+
await connection.rollback();
|
|
232
|
+
}
|
|
233
|
+
} catch (err) {
|
|
234
|
+
console.error('Erro finalizando transação no autoTransaction middleware:', err);
|
|
235
|
+
} finally {
|
|
236
|
+
connection.release();
|
|
237
|
+
txContext.connection = null;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
// Intercepta a finalização da resposta
|
|
243
|
+
const originalEnd = res.end.bind(res);
|
|
244
|
+
let finishHandled = false;
|
|
245
|
+
|
|
246
|
+
const handleFinish = async (isError) => {
|
|
247
|
+
if (finishHandled) return;
|
|
248
|
+
finishHandled = true;
|
|
249
|
+
const status = res.statusCode || 200;
|
|
250
|
+
const shouldCommit = !isError && status < 400;
|
|
251
|
+
await cleanup(shouldCommit);
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
res.end = function (...args) {
|
|
255
|
+
handleFinish(false).then(() => {
|
|
256
|
+
originalEnd(...args);
|
|
257
|
+
}).catch(err => {
|
|
258
|
+
console.error('Erro ao finalizar resposta em autoTransaction:', err);
|
|
259
|
+
originalEnd(...args);
|
|
260
|
+
});
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
res.on('close', () => {
|
|
264
|
+
if (!finishHandled) {
|
|
265
|
+
handleFinish(true);
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
this.als.run(txContext, () => {
|
|
270
|
+
try {
|
|
271
|
+
next();
|
|
272
|
+
} catch (err) {
|
|
273
|
+
handleFinish(true).then(() => next(err));
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Executes a SQL query using either the active transaction connection (if inside a transaction)
|
|
281
|
+
* or a pooled connection.
|
|
282
|
+
*
|
|
32
283
|
* @param {string} sql - The SQL query to execute.
|
|
33
284
|
* @param {Array} [params] - The parameters for the SQL query.
|
|
34
|
-
* @
|
|
35
|
-
* @
|
|
285
|
+
* @param {boolean} [isWrite=false] - Indicates whether the query is a write/mutation operation.
|
|
286
|
+
* @returns {Promise<Array|{error: Error}>} The result set, or an object with error outside of transactions.
|
|
287
|
+
* @throws {Error} Inside transactions, errors are thrown to guarantee automatic rollback.
|
|
36
288
|
*/
|
|
37
|
-
async query(sql, params) {
|
|
38
|
-
|
|
289
|
+
async query(sql, params, isWrite = false) {
|
|
290
|
+
const store = this.als.getStore();
|
|
291
|
+
|
|
292
|
+
if (store) {
|
|
293
|
+
let connection = store.connection;
|
|
294
|
+
|
|
295
|
+
// Se for lazy e ainda não tiver iniciado a transação, inicia caso seja escrita ou lazy=false
|
|
296
|
+
if (!connection && store.ensureConnection) {
|
|
297
|
+
if (isWrite || !store.isLazy) {
|
|
298
|
+
connection = await store.ensureConnection();
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
if (connection) {
|
|
303
|
+
try {
|
|
304
|
+
const [rows] = await connection.query(sql, params);
|
|
305
|
+
return rows;
|
|
306
|
+
} catch (error) {
|
|
307
|
+
console.error('Erro na execução da query transacional:', error);
|
|
308
|
+
// DENTRO DE TRANSAÇÃO: DEVE LANÇAR ERRO para abortar o fluxo e causar rollback
|
|
309
|
+
throw error;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Fluxo padrão fora de transações (mantém contrato e compatibilidade total)
|
|
315
|
+
let connection;
|
|
39
316
|
try {
|
|
40
|
-
// Passo 1: Obter uma conexão do pool
|
|
41
317
|
connection = await this.getConnection();
|
|
42
|
-
|
|
43
|
-
// Passo 2: Executar a query
|
|
44
318
|
const [rows] = await connection.query(sql, params);
|
|
45
319
|
return rows;
|
|
46
320
|
} catch (error) {
|
|
47
|
-
// Passo 3: Se a query falhar, logar e retornar o erro no formato desejado
|
|
48
321
|
console.error('Erro na execução da query:', error);
|
|
49
|
-
return { error };
|
|
322
|
+
return { error };
|
|
50
323
|
} finally {
|
|
51
|
-
// Passo 4: Este bloco SEMPRE será executado, independentemente de sucesso ou falha no 'try'
|
|
52
324
|
if (connection) {
|
|
53
|
-
connection.release();
|
|
325
|
+
connection.release();
|
|
54
326
|
}
|
|
55
327
|
}
|
|
56
328
|
}
|
|
57
329
|
|
|
58
330
|
/**
|
|
59
|
-
* Retrieves the schema of a given table using prepared statements
|
|
331
|
+
* Retrieves the schema of a given table using prepared statements.
|
|
60
332
|
* @param {string} table - The name of the table.
|
|
61
333
|
* @returns {Promise<Array>} The schema of the table.
|
|
62
|
-
* @throws {Error} Throws an error if the query fails.
|
|
63
334
|
*/
|
|
64
335
|
async getTableSchema(table) {
|
|
65
336
|
const sql = `SELECT column_name
|
|
@@ -78,4 +349,6 @@ class DataBase {
|
|
|
78
349
|
}
|
|
79
350
|
}
|
|
80
351
|
}
|
|
352
|
+
|
|
81
353
|
module.exports = DataBase;
|
|
354
|
+
|
package/lib/databaseHandler.js
CHANGED
|
@@ -8,13 +8,23 @@ class DatabaseHandler {
|
|
|
8
8
|
this.onError;
|
|
9
9
|
}
|
|
10
10
|
|
|
11
|
-
async executeQuery(sql, params) {
|
|
12
|
-
|
|
13
|
-
// const rows = await connection.query(sql, params);
|
|
14
|
-
const rows = await this.db.query(sql, params);
|
|
11
|
+
async executeQuery(sql, params, isWrite = false) {
|
|
12
|
+
const rows = await this.db.query(sql, params, isWrite);
|
|
15
13
|
return rows;
|
|
16
14
|
}
|
|
17
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Clones this handler bound to a specific transaction or database executor.
|
|
18
|
+
* @param {Object} txOrDb - Transaction context or database instance.
|
|
19
|
+
* @returns {DatabaseHandler} A new handler instance.
|
|
20
|
+
*/
|
|
21
|
+
withTransaction(txOrDb) {
|
|
22
|
+
const handler = new DatabaseHandler(txOrDb, this.table, this.expression);
|
|
23
|
+
handler.debug = this.debug;
|
|
24
|
+
handler.onError = this.onError;
|
|
25
|
+
return handler;
|
|
26
|
+
}
|
|
27
|
+
|
|
18
28
|
async getSchema() {
|
|
19
29
|
return await this.db.getTableSchema(this.table)
|
|
20
30
|
}
|
|
@@ -49,16 +59,37 @@ class DatabaseHandler {
|
|
|
49
59
|
const bindings = [];
|
|
50
60
|
for (const item of strictCondition) {
|
|
51
61
|
if (typeof item === 'string') {
|
|
62
|
+
// Operadores lógicos (AND / OR) são inseridos como-is, sem parênteses.
|
|
52
63
|
clauses.push(item.toUpperCase());
|
|
53
64
|
} else if (typeof item === 'object' && item !== null) {
|
|
54
65
|
const key = Object.keys(item).find(k => k !== 'operator');
|
|
55
66
|
if (!key) continue;
|
|
56
67
|
const value = item[key];
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
68
|
+
let operator = item.operator || '=';
|
|
69
|
+
let upperOp = String(operator).toUpperCase();
|
|
70
|
+
|
|
71
|
+
// Suporte a arrays => IN / NOT IN (consistente com _buildWhereClause)
|
|
72
|
+
if (Array.isArray(value) && upperOp === '=') {
|
|
73
|
+
operator = 'IN';
|
|
74
|
+
upperOp = 'IN';
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (Array.isArray(value) && (upperOp === 'IN' || upperOp === 'NOT IN')) {
|
|
78
|
+
if (value.length === 0) {
|
|
79
|
+
clauses.push(upperOp === 'IN' ? '1 = 0' : '1 = 1');
|
|
80
|
+
} else {
|
|
81
|
+
const placeholders = value.map(() => '?').join(', ');
|
|
82
|
+
clauses.push(`\`${key}\` ${operator} (${placeholders})`);
|
|
83
|
+
bindings.push(...value);
|
|
84
|
+
}
|
|
85
|
+
} else {
|
|
86
|
+
clauses.push(`\`${key}\` ${operator} ?`);
|
|
87
|
+
bindings.push(value);
|
|
88
|
+
}
|
|
60
89
|
}
|
|
61
90
|
}
|
|
91
|
+
// Junta com espaço para preservar operadores AND/OR intercalados.
|
|
92
|
+
// Ex: "(a = ? AND b = ?)" em vez de "(a = ? b = ?)" que era inválido.
|
|
62
93
|
return { sql: `(${clauses.join(' ')})`, bindings };
|
|
63
94
|
}
|
|
64
95
|
|
|
@@ -182,12 +213,31 @@ class DatabaseHandler {
|
|
|
182
213
|
// --- Queries ---
|
|
183
214
|
const baseWhereSql = baseWhere.sql ? `WHERE ${baseWhere.sql}` : '';
|
|
184
215
|
const totalCountSql = `SELECT COUNT(*) as total FROM ${this.table} ${baseWhereSql}`;
|
|
185
|
-
const
|
|
186
|
-
|
|
216
|
+
const totalResult = await this.executeQuery(totalCountSql, baseWhere.bindings);
|
|
217
|
+
// Contrato: executeQuery propaga { error } em caso de falha (não lança).
|
|
218
|
+
if (totalResult && totalResult.error) {
|
|
219
|
+
return {
|
|
220
|
+
draw: parseInt(draw || 0),
|
|
221
|
+
recordsTotal: 0,
|
|
222
|
+
recordsFiltered: 0,
|
|
223
|
+
data: [],
|
|
224
|
+
error: totalResult.error.message
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
const recordsTotal = (totalResult && totalResult[0] && totalResult[0].total) || 0;
|
|
187
228
|
|
|
188
229
|
const filteredCountSql = `SELECT COUNT(*) as total FROM ${this.table} ${whereSql}`;
|
|
189
|
-
const
|
|
190
|
-
|
|
230
|
+
const filteredResult = await this.executeQuery(filteredCountSql, finalBindings);
|
|
231
|
+
if (filteredResult && filteredResult.error) {
|
|
232
|
+
return {
|
|
233
|
+
draw: parseInt(draw || 0),
|
|
234
|
+
recordsTotal: parseInt(recordsTotal),
|
|
235
|
+
recordsFiltered: 0,
|
|
236
|
+
data: [],
|
|
237
|
+
error: filteredResult.error.message
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
const recordsFiltered = (filteredResult && filteredResult[0] && filteredResult[0].total) || 0;
|
|
191
241
|
|
|
192
242
|
// CORREÇÃO: Construção segura da cláusula SELECT para evitar vírgulas duplas.
|
|
193
243
|
const selectFields = ['*'];
|
|
@@ -197,6 +247,15 @@ class DatabaseHandler {
|
|
|
197
247
|
}
|
|
198
248
|
const dataSql = `SELECT ${selectFields.join(', ')} FROM ${this.table} ${whereSql} ${orderSql} ${limitSql}`;
|
|
199
249
|
const data = await this.executeQuery(dataSql, finalBindings);
|
|
250
|
+
if (data && data.error) {
|
|
251
|
+
return {
|
|
252
|
+
draw: parseInt(draw || 0),
|
|
253
|
+
recordsTotal: parseInt(recordsTotal),
|
|
254
|
+
recordsFiltered: parseInt(recordsFiltered),
|
|
255
|
+
data: [],
|
|
256
|
+
error: data.error.message
|
|
257
|
+
};
|
|
258
|
+
}
|
|
200
259
|
|
|
201
260
|
return {
|
|
202
261
|
draw: parseInt(draw || 0),
|
|
@@ -294,7 +353,7 @@ class DatabaseHandler {
|
|
|
294
353
|
|
|
295
354
|
async insert(params) {
|
|
296
355
|
const sql = `INSERT INTO ${this.table} SET ?`;
|
|
297
|
-
const result = await this.executeQuery(sql, params);
|
|
356
|
+
const result = await this.executeQuery(sql, params, true);
|
|
298
357
|
return result;
|
|
299
358
|
}
|
|
300
359
|
|
|
@@ -310,8 +369,8 @@ class DatabaseHandler {
|
|
|
310
369
|
const sql = `UPDATE ${this.table} SET ${setClause} WHERE ${whereClause}`;
|
|
311
370
|
// Combina os valores SET e WHERE em um único array
|
|
312
371
|
const values = [...setValues, ...whereValues];
|
|
313
|
-
// Executa a consulta
|
|
314
|
-
const result = await this.executeQuery(sql, values);
|
|
372
|
+
// Executa a consulta sinalizando mutação de escrita
|
|
373
|
+
const result = await this.executeQuery(sql, values, true);
|
|
315
374
|
|
|
316
375
|
return result;
|
|
317
376
|
}
|
|
@@ -326,7 +385,7 @@ class DatabaseHandler {
|
|
|
326
385
|
const whereConditions = conditionKeys.map((key) => `${key} = ?`).join(' AND ');
|
|
327
386
|
const sql = `DELETE FROM ${this.table} WHERE ${whereConditions}`;
|
|
328
387
|
const params = conditionKeys.map((key) => conditions[key]);
|
|
329
|
-
const result = await this.executeQuery(sql, params);
|
|
388
|
+
const result = await this.executeQuery(sql, params, true);
|
|
330
389
|
return result;
|
|
331
390
|
}
|
|
332
391
|
|
package/package.json
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@areumtecnologia/mysql-db-handler",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.11",
|
|
4
4
|
"description": "A powerful MySQL wrapper with connection pooling, singleton support, and advanced query handling for Node.js.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
7
|
-
"test": "
|
|
7
|
+
"test": "node tests/update_operators.test.js && node tests/selectToDatatable.test.js && node tests/transactions.test.js && node tests/customersSales.test.js"
|
|
8
8
|
},
|
|
9
9
|
"author": "Renan Moreira / Áreum Tecnologia",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"mysql2": "^3.
|
|
12
|
+
"mysql2": "^3.24.4",
|
|
13
|
+
"node-cache": "^5.1.2"
|
|
13
14
|
}
|
|
14
15
|
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
-
// src/database/database-singleton.js
|
|
3
|
-
// Exemplo Singleton para a conexão com o banco de dados
|
|
4
|
-
const { DB_HOST, DB_USER, DB_PASS } = require('../constants');
|
|
5
|
-
const DataBase = require("./database");
|
|
6
|
-
|
|
7
|
-
const dbi = new DataBase({
|
|
8
|
-
host: DB_HOST,
|
|
9
|
-
user: DB_USER,
|
|
10
|
-
password: DB_PASS,
|
|
11
|
-
database: '',
|
|
12
|
-
charset: "utf8mb4",
|
|
13
|
-
timezone: "-03:00",
|
|
14
|
-
connectionLimit: 1, // Ajustado para um limite de conexão mais comum
|
|
15
|
-
waitForConnections: true,
|
|
16
|
-
queueLimit: 0
|
|
17
|
-
});
|
|
18
|
-
// console.log("DATABASE SINGLETON CREATED", dbi.id);
|
|
19
|
-
module.exports = dbi;
|