@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/lib/database.js CHANGED
@@ -1,19 +1,37 @@
1
1
  const mysql = require('mysql2/promise');
2
+ const { AsyncLocalStorage } = require('node:async_hooks');
3
+
4
+ const ALLOWED_ISOLATION_LEVELS = new Set([
5
+ 'READ UNCOMMITTED',
6
+ 'READ COMMITTED',
7
+ 'REPEATABLE READ',
8
+ 'SERIALIZABLE'
9
+ ]);
10
+
11
+ function validateIsolationLevel(level) {
12
+ if (!level) return null;
13
+ const normalized = String(level).toUpperCase().trim();
14
+ if (!ALLOWED_ISOLATION_LEVELS.has(normalized)) {
15
+ throw new Error(`Nível de isolamento inválido: "${level}". Valores válidos: ${Array.from(ALLOWED_ISOLATION_LEVELS).join(', ')}`);
16
+ }
17
+ return normalized;
18
+ }
2
19
 
3
20
  class DataBase {
4
21
  /**
5
- * Creates a database instance with a connection pool.
22
+ * Creates a database instance with a connection pool and async transaction context.
6
23
  * @param {Object} [config] - Configuration object for the database connection.
7
24
  */
8
25
  constructor(config) {
9
26
  this.id = Date.now();
10
27
  this.config = config;
11
28
  this.pool = mysql.createPool(config);
29
+ this.als = new AsyncLocalStorage();
12
30
  }
13
31
 
14
32
  /**
15
33
  * Retrieves the connection pool.
16
- * @returns {Promise<mysql.Pool>} The connection pool.
34
+ * @returns {mysql.Pool} The connection pool.
17
35
  */
18
36
  getPool() {
19
37
  return this.pool;
@@ -28,48 +46,323 @@ class DataBase {
28
46
  }
29
47
 
30
48
  /**
31
- * Executes a SQL query using a pooled connection.
49
+ * Retrieves the active transaction context from AsyncLocalStorage, if any.
50
+ * @returns {Object|null} The current transaction context.
51
+ */
52
+ getCurrentTransaction() {
53
+ return this.als.getStore() || null;
54
+ }
55
+
56
+ /**
57
+ * Registers a callback to be executed immediately after the current transaction commits successfully.
58
+ * If called outside a transaction, the callback is executed asynchronously right away.
59
+ * @param {Function} callback - Callback function to run on commit.
60
+ */
61
+ onCommit(callback) {
62
+ if (typeof callback !== 'function') {
63
+ throw new TypeError('O callback de onCommit deve ser uma função.');
64
+ }
65
+
66
+ const store = this.als.getStore();
67
+ if (store && store.onCommitHooks) {
68
+ store.onCommitHooks.push(callback);
69
+ } else {
70
+ // Se não estiver em transação, executa imediatamente sem bloquear
71
+ Promise.resolve().then(callback).catch(err => {
72
+ console.error('Erro ao executar callback de onCommit fora de transação:', err);
73
+ });
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Executes a callback within a managed transaction.
79
+ * Handles BEGIN, COMMIT, ROLLBACK, connection release, and Savepoints automatically.
80
+ *
81
+ * @param {Function} callback - Async function (tx) => Promise<any>
82
+ * @param {Object} [options] - Transaction options.
83
+ * @param {string} [options.isolationLevel] - e.g. 'READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'
84
+ * @returns {Promise<any>} Result of the callback.
85
+ */
86
+ async transaction(callback, options = {}) {
87
+ if (typeof callback !== 'function') {
88
+ throw new TypeError('O parâmetro callback deve ser uma função.');
89
+ }
90
+
91
+ const activeStore = this.als.getStore();
92
+
93
+ // Se já houver uma transação ativa com conexão, cria um Savepoint (transação aninhada)
94
+ if (activeStore && activeStore.transactionStarted && activeStore.connection) {
95
+ activeStore.depth = (activeStore.depth || 1) + 1;
96
+ activeStore.savepointCounter = (activeStore.savepointCounter || 0) + 1;
97
+ const spName = `sp_${activeStore.savepointCounter}`;
98
+ const hooksLengthBefore = (activeStore.onCommitHooks && activeStore.onCommitHooks.length) || 0;
99
+
100
+ await activeStore.connection.query(`SAVEPOINT ${spName}`);
101
+ try {
102
+ const result = await callback(activeStore);
103
+ await activeStore.connection.query(`RELEASE SAVEPOINT ${spName}`);
104
+ return result;
105
+ } catch (error) {
106
+ if (activeStore.onCommitHooks) {
107
+ activeStore.onCommitHooks.length = hooksLengthBefore;
108
+ }
109
+ await activeStore.connection.query(`ROLLBACK TO SAVEPOINT ${spName}`);
110
+ throw error;
111
+ } finally {
112
+ activeStore.depth--;
113
+ }
114
+ }
115
+
116
+ // Transação Raiz
117
+ let connection = null;
118
+ const onCommitHooks = [];
119
+
120
+ try {
121
+ connection = await this.getConnection();
122
+
123
+ if (options.isolationLevel) {
124
+ const validIsoLevel = validateIsolationLevel(options.isolationLevel);
125
+ await connection.query(`SET TRANSACTION ISOLATION LEVEL ${validIsoLevel}`);
126
+ }
127
+
128
+ await connection.beginTransaction();
129
+
130
+ const txContext = {
131
+ id: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
132
+ connection,
133
+ depth: 1,
134
+ savepointCounter: 0,
135
+ onCommitHooks,
136
+ transactionStarted: true,
137
+ isLazy: false
138
+ };
139
+
140
+ const result = await this.als.run(txContext, async () => {
141
+ return await callback(txContext);
142
+ });
143
+
144
+ await connection.commit();
145
+
146
+ // Executa hooks de pós-commit com segurança
147
+ for (const hook of onCommitHooks) {
148
+ try {
149
+ await hook();
150
+ } catch (hookErr) {
151
+ console.error('Erro ao executar hook de onCommit:', hookErr);
152
+ }
153
+ }
154
+
155
+ return result;
156
+ } catch (error) {
157
+ if (connection) {
158
+ try {
159
+ await connection.rollback();
160
+ } catch (rbErr) {
161
+ console.error('Erro durante rollback da transação:', rbErr);
162
+ }
163
+ }
164
+ throw error;
165
+ } finally {
166
+ if (connection) {
167
+ connection.release();
168
+ }
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Route wrapper or higher-order function to execute an async handler inside a transaction.
174
+ * @param {Function} fn - Async handler function.
175
+ * @param {Object} [options] - Options for dbi.transaction.
176
+ * @returns {Function} Wrapped handler.
177
+ */
178
+ transactional(fn, options = {}) {
179
+ return (...args) => {
180
+ return this.transaction(() => fn(...args), options);
181
+ };
182
+ }
183
+
184
+ /**
185
+ * Express middleware for automatic, transparent transaction management.
186
+ * Uses a lazy approach by default: only allocates a connection and begins a transaction
187
+ * if a write operation (insert/update/delete) is performed during the request.
188
+ *
189
+ * @param {Object} [options] - Configuration options.
190
+ * @param {Array<string>} [options.methods] - HTTP methods to auto-transact (default: ['POST', 'PUT', 'DELETE', 'PATCH']).
191
+ * @param {boolean} [options.lazy=true] - Whether to delay transaction creation until first write.
192
+ * @param {string} [options.isolationLevel] - Isolation level if transaction is created.
193
+ * @returns {Function} Express middleware.
194
+ */
195
+ autoTransaction(options = {}) {
196
+ const {
197
+ methods = ['POST', 'PUT', 'DELETE', 'PATCH'],
198
+ lazy = true,
199
+ isolationLevel = null
200
+ } = options;
201
+
202
+ return (req, res, next) => {
203
+ const method = req.method ? req.method.toUpperCase() : 'GET';
204
+ const isTargetMethod = methods.includes(method);
205
+
206
+ if (!isTargetMethod && !lazy) {
207
+ return next();
208
+ }
209
+
210
+ const onCommitHooks = [];
211
+ let connection = null;
212
+ let finalized = false;
213
+
214
+ const txContext = {
215
+ id: `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
216
+ connection: null,
217
+ depth: 1,
218
+ savepointCounter: 0,
219
+ onCommitHooks,
220
+ isLazy: lazy,
221
+ transactionStarted: false,
222
+ ensureConnection: async () => {
223
+ if (!connection) {
224
+ connection = await this.getConnection();
225
+ if (isolationLevel) {
226
+ const validIsoLevel = validateIsolationLevel(isolationLevel);
227
+ await connection.query(`SET TRANSACTION ISOLATION LEVEL ${validIsoLevel}`);
228
+ }
229
+ await connection.beginTransaction();
230
+ txContext.connection = connection;
231
+ txContext.transactionStarted = true;
232
+ }
233
+ return connection;
234
+ }
235
+ };
236
+
237
+ const cleanup = async (shouldCommit) => {
238
+ if (finalized) return;
239
+ finalized = true;
240
+
241
+ if (connection && txContext.transactionStarted) {
242
+ try {
243
+ if (shouldCommit) {
244
+ await connection.commit();
245
+ for (const hook of onCommitHooks) {
246
+ try {
247
+ await hook();
248
+ } catch (hookErr) {
249
+ console.error('Erro ao executar hook de onCommit no middleware:', hookErr);
250
+ }
251
+ }
252
+ } else {
253
+ await connection.rollback();
254
+ }
255
+ } catch (err) {
256
+ console.error('Erro finalizando transação no autoTransaction middleware:', err);
257
+ } finally {
258
+ connection.release();
259
+ txContext.connection = null;
260
+ }
261
+ }
262
+ };
263
+
264
+ // Intercepta a finalização da resposta
265
+ const originalEnd = res.end.bind(res);
266
+ let finishHandled = false;
267
+
268
+ const handleFinish = async (isError) => {
269
+ if (finishHandled) return;
270
+ finishHandled = true;
271
+ const status = res.statusCode || 200;
272
+ const shouldCommit = !isError && status < 400;
273
+ await cleanup(shouldCommit);
274
+ };
275
+
276
+ res.end = function (...args) {
277
+ handleFinish(false).then(() => {
278
+ originalEnd(...args);
279
+ }).catch(err => {
280
+ console.error('Erro ao finalizar resposta em autoTransaction:', err);
281
+ originalEnd(...args);
282
+ });
283
+ };
284
+
285
+ res.on('close', () => {
286
+ if (!finishHandled) {
287
+ handleFinish(true);
288
+ }
289
+ });
290
+
291
+ this.als.run(txContext, () => {
292
+ try {
293
+ next();
294
+ } catch (err) {
295
+ handleFinish(true).then(() => next(err));
296
+ }
297
+ });
298
+ };
299
+ }
300
+
301
+ /**
302
+ * Executes a SQL query using either the active transaction connection (if inside a transaction)
303
+ * or a pooled connection.
304
+ *
32
305
  * @param {string} sql - The SQL query to execute.
33
306
  * @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.
307
+ * @param {boolean} [isWrite=false] - Indicates whether the query is a write/mutation operation.
308
+ * @returns {Promise<Array|{error: Error}>} The result set, or an object with error outside of transactions.
309
+ * @throws {Error} Inside transactions or if config.throwOnError is true, errors are thrown.
37
310
  */
38
- async query(sql, params) {
39
- let connection; // Mova a declaração da conexão para fora do bloco try
311
+ async query(sql, params, isWrite = false) {
312
+ const store = this.als.getStore();
313
+
314
+ if (store) {
315
+ let connection = store.connection;
316
+
317
+ // Se for lazy e ainda não tiver iniciado a transação, inicia caso seja escrita ou lazy=false
318
+ if (!connection && store.ensureConnection) {
319
+ if (isWrite || !store.isLazy) {
320
+ connection = await store.ensureConnection();
321
+ }
322
+ }
323
+
324
+ if (connection) {
325
+ try {
326
+ const [rows] = await connection.query(sql, params);
327
+ return rows;
328
+ } catch (error) {
329
+ console.error('Erro na execução da query transacional:', error);
330
+ // DENTRO DE TRANSAÇÃO: DEVE LANÇAR ERRO para abortar o fluxo e causar rollback
331
+ throw error;
332
+ }
333
+ }
334
+ }
335
+
336
+ // Fluxo padrão fora de transações (mantém contrato e compatibilidade total)
337
+ let connection;
40
338
  try {
41
- // Passo 1: Obter uma conexão do pool
42
339
  connection = await this.getConnection();
43
-
44
- // Passo 2: Executar a query
45
340
  const [rows] = await connection.query(sql, params);
46
341
  return rows;
47
342
  } catch (error) {
48
- // Passo 3: Logar o erro para diagnóstico
49
343
  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.
344
+ if (this.config && this.config.throwOnError) {
345
+ throw error;
346
+ }
53
347
  return { error };
54
348
  } finally {
55
- // Passo 4: Este bloco SEMPRE será executado, independentemente de sucesso ou falha no 'try'
56
349
  if (connection) {
57
- connection.release(); // Garante que a conexão seja devolvida ao pool
350
+ connection.release();
58
351
  }
59
352
  }
60
353
  }
61
354
 
62
355
  /**
63
- * Retrieves the schema of a given table using prepared statements to prevent SQL injection.
356
+ * Retrieves the schema of a given table using prepared statements.
64
357
  * @param {string} table - The name of the table.
65
358
  * @returns {Promise<Array>} The schema of the table.
66
- * @throws {Error} Throws an error if the query fails.
67
359
  */
68
360
  async getTableSchema(table) {
69
361
  const sql = `SELECT column_name
70
362
  FROM information_schema.columns
71
- WHERE table_schema = ? AND table_name = ?`;
72
- return await this.query(sql, [this.config.database, table]);
363
+ WHERE table_schema = COALESCE(?, DATABASE()) AND table_name = ?`;
364
+ const dbName = (this.config && this.config.database) ? this.config.database : null;
365
+ return await this.query(sql, [dbName, table]);
73
366
  }
74
367
 
75
368
  /**
@@ -82,4 +375,6 @@ class DataBase {
82
375
  }
83
376
  }
84
377
  }
378
+
85
379
  module.exports = DataBase;
380
+