@areumtecnologia/mysql-db-handler 1.0.10 → 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 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` to boost performance.
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 prevent application crashes.
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
@@ -1,77 +1,81 @@
1
1
  // Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
2
- const mysql = require('mysql2/promise');
3
- const NodeCache = require('node-cache');
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 DataBaseCache {
6
- constructor(config = {}) {
7
- this.config = config;
8
- this.pool = mysql.createPool(this.config); // The pool is created once when the instance is created.
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
- // The createPool method is preserved for compatibility but is not necessary as the pool is already created in the constructor.
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 getConnection() {
21
- if (!this.pool) {
22
- throw new Error('Pool de conexões não criado.');
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
- async query(sql, params) {
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 connection = await this.getConnection();
36
- try {
37
- const [rows] = await connection.query(sql, params);
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 (cachedResult) {
53
- return cachedResult;
61
+ if (!inTransaction) {
62
+ const cachedResult = this.cache.get(key);
63
+ if (cachedResult) {
64
+ return cachedResult;
65
+ }
54
66
  }
55
67
 
56
- const sql = `SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ?`;
57
- const params = [this.config.database, table];
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
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 {Promise<mysql.Pool>} The connection pool.
18
+ * @returns {mysql.Pool} The connection pool.
17
19
  */
18
20
  getPool() {
19
21
  return this.pool;
@@ -28,42 +30,307 @@ class DataBase {
28
30
  }
29
31
 
30
32
  /**
31
- * Executes a SQL query using a pooled connection.
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
- * @returns {Promise<Array|{error: Error}>} The result set from the query,
35
- * or an object with an `error` property if the query fails.
36
- * This prevents unhandled exceptions from crashing the application.
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.
37
288
  */
38
- async query(sql, params) {
39
- let connection; // Mova a declaração da conexão para fora do bloco try
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;
40
316
  try {
41
- // Passo 1: Obter uma conexão do pool
42
317
  connection = await this.getConnection();
43
-
44
- // Passo 2: Executar a query
45
318
  const [rows] = await connection.query(sql, params);
46
319
  return rows;
47
320
  } catch (error) {
48
- // Passo 3: Logar o erro para diagnóstico
49
321
  console.error('Erro na execução da query:', error);
50
-
51
- // Retorna o erro encapsulado em { error } para evitar crashes não tratados,
52
- // mantendo o contrato documentado no README.
53
322
  return { error };
54
323
  } finally {
55
- // Passo 4: Este bloco SEMPRE será executado, independentemente de sucesso ou falha no 'try'
56
324
  if (connection) {
57
- connection.release(); // Garante que a conexão seja devolvida ao pool
325
+ connection.release();
58
326
  }
59
327
  }
60
328
  }
61
329
 
62
330
  /**
63
- * Retrieves the schema of a given table using prepared statements to prevent SQL injection.
331
+ * Retrieves the schema of a given table using prepared statements.
64
332
  * @param {string} table - The name of the table.
65
333
  * @returns {Promise<Array>} The schema of the table.
66
- * @throws {Error} Throws an error if the query fails.
67
334
  */
68
335
  async getTableSchema(table) {
69
336
  const sql = `SELECT column_name
@@ -82,4 +349,6 @@ class DataBase {
82
349
  }
83
350
  }
84
351
  }
352
+
85
353
  module.exports = DataBase;
354
+
@@ -8,13 +8,23 @@ class DatabaseHandler {
8
8
  this.onError;
9
9
  }
10
10
 
11
- async executeQuery(sql, params) {
12
- // const connection = await this.db;
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
  }
@@ -343,7 +353,7 @@ class DatabaseHandler {
343
353
 
344
354
  async insert(params) {
345
355
  const sql = `INSERT INTO ${this.table} SET ?`;
346
- const result = await this.executeQuery(sql, params);
356
+ const result = await this.executeQuery(sql, params, true);
347
357
  return result;
348
358
  }
349
359
 
@@ -359,8 +369,8 @@ class DatabaseHandler {
359
369
  const sql = `UPDATE ${this.table} SET ${setClause} WHERE ${whereClause}`;
360
370
  // Combina os valores SET e WHERE em um único array
361
371
  const values = [...setValues, ...whereValues];
362
- // Executa a consulta
363
- 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);
364
374
 
365
375
  return result;
366
376
  }
@@ -375,7 +385,7 @@ class DatabaseHandler {
375
385
  const whereConditions = conditionKeys.map((key) => `${key} = ?`).join(' AND ');
376
386
  const sql = `DELETE FROM ${this.table} WHERE ${whereConditions}`;
377
387
  const params = conditionKeys.map((key) => conditions[key]);
378
- const result = await this.executeQuery(sql, params);
388
+ const result = await this.executeQuery(sql, params, true);
379
389
  return result;
380
390
  }
381
391
 
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@areumtecnologia/mysql-db-handler",
3
- "version": "1.0.10",
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": "node tests/update_operators.test.js && node tests/selectToDatatable.test.js"
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.23.1"
12
+ "mysql2": "^3.24.4",
13
+ "node-cache": "^5.1.2"
13
14
  }
14
15
  }