@areumtecnologia/mysql-db-handler 1.0.14 → 2.0.1
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 +291 -10
- package/idex.d.ts +137 -0
- package/index.d.ts +204 -0
- package/lib/database-cache.js +118 -30
- package/lib/database.js +230 -157
- package/lib/databaseHandler.js +1104 -245
- package/package.json +15 -14
package/lib/database.js
CHANGED
|
@@ -8,6 +8,12 @@ const ALLOWED_ISOLATION_LEVELS = new Set([
|
|
|
8
8
|
'SERIALIZABLE'
|
|
9
9
|
]);
|
|
10
10
|
|
|
11
|
+
// Códigos de erro transientes do MySQL passíveis de retry automático
|
|
12
|
+
const RETRYABLE_ERROR_CODES = new Set([
|
|
13
|
+
'ER_LOCK_DEADLOCK', // errno 1213
|
|
14
|
+
'ER_LOCK_WAIT_TIMEOUT' // errno 1205
|
|
15
|
+
]);
|
|
16
|
+
|
|
11
17
|
function validateIsolationLevel(level) {
|
|
12
18
|
if (!level) return null;
|
|
13
19
|
const normalized = String(level).toUpperCase().trim();
|
|
@@ -17,71 +23,102 @@ function validateIsolationLevel(level) {
|
|
|
17
23
|
return normalized;
|
|
18
24
|
}
|
|
19
25
|
|
|
26
|
+
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
27
|
+
|
|
20
28
|
class DataBase {
|
|
21
29
|
/**
|
|
22
|
-
*
|
|
23
|
-
* @param {
|
|
30
|
+
* @param {Object} [config] - Configuração do MySQL2 + opções estendidas:
|
|
31
|
+
* @param {boolean} [config.throwOnError=false] - Lança erros fora de transações.
|
|
32
|
+
* @param {boolean} [config.usePreparedStatements=false] - Usa .execute() por defeito em vez de .query().
|
|
33
|
+
* @param {number} [config.slowQueryThreshold=0] - Limite em ms para emitir alerta de query lenta (0 = desativado).
|
|
34
|
+
* @param {Function} [config.onSlowQuery] - Callback ({ sql, params, durationMs }) chamado em queries lentas.
|
|
35
|
+
* @param {Object} [config.logger=console] - Logger customizado (Pino, Winston, console).
|
|
36
|
+
* @param {number} [config.maxRetries=3] - Número máximo de tentativas em caso de Deadlock em transações.
|
|
37
|
+
* @param {number} [config.retryDelayMs=50] - Atraso base (ms) para backoff exponencial em Deadlocks.
|
|
24
38
|
*/
|
|
25
|
-
constructor(config) {
|
|
39
|
+
constructor(config = {}) {
|
|
26
40
|
this.id = Date.now();
|
|
27
41
|
this.config = config;
|
|
28
|
-
this.
|
|
42
|
+
this.logger = config.logger || console;
|
|
43
|
+
this.slowQueryThreshold = Number(config.slowQueryThreshold) || 0;
|
|
44
|
+
this.onSlowQuery = typeof config.onSlowQuery === 'function' ? config.onSlowQuery : null;
|
|
45
|
+
this.usePreparedStatements = Boolean(config.usePreparedStatements);
|
|
46
|
+
this.maxRetries = config.maxRetries !== undefined ? Number(config.maxRetries) : 3;
|
|
47
|
+
this.retryDelayMs = config.retryDelayMs !== undefined ? Number(config.retryDelayMs) : 50;
|
|
48
|
+
|
|
49
|
+
// Extrai apenas opções válidas do mysql2 para evitar avisos de configuração desconhecida
|
|
50
|
+
const {
|
|
51
|
+
throwOnError,
|
|
52
|
+
usePreparedStatements,
|
|
53
|
+
slowQueryThreshold,
|
|
54
|
+
onSlowQuery,
|
|
55
|
+
logger,
|
|
56
|
+
maxRetries,
|
|
57
|
+
retryDelayMs,
|
|
58
|
+
replicas,
|
|
59
|
+
readReplicas,
|
|
60
|
+
read,
|
|
61
|
+
...mysqlConfig
|
|
62
|
+
} = config;
|
|
63
|
+
|
|
64
|
+
this.pool = mysql.createPool(mysqlConfig);
|
|
29
65
|
this.als = new AsyncLocalStorage();
|
|
66
|
+
|
|
67
|
+
// Replicação de Leitura/Escrita (Read/Write Splitting)
|
|
68
|
+
const replicaList = replicas || readReplicas || (Array.isArray(read) ? read : null);
|
|
69
|
+
this.replicaPools = [];
|
|
70
|
+
this._replicaIndex = 0;
|
|
71
|
+
|
|
72
|
+
if (Array.isArray(replicaList) && replicaList.length > 0) {
|
|
73
|
+
this.replicaPools = replicaList.map(repConfig => {
|
|
74
|
+
return mysql.createPool({ ...mysqlConfig, ...repConfig });
|
|
75
|
+
});
|
|
76
|
+
}
|
|
30
77
|
}
|
|
31
78
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
79
|
+
_selectPool(isWrite = false) {
|
|
80
|
+
if (isWrite || this.hasActiveTransaction() || this.replicaPools.length === 0) {
|
|
81
|
+
return this.pool;
|
|
82
|
+
}
|
|
83
|
+
const pool = this.replicaPools[this._replicaIndex % this.replicaPools.length];
|
|
84
|
+
this._replicaIndex = (this._replicaIndex + 1) % this.replicaPools.length;
|
|
85
|
+
return pool;
|
|
38
86
|
}
|
|
39
87
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
async getConnection() {
|
|
45
|
-
return this.
|
|
88
|
+
getPool(isWrite = false) {
|
|
89
|
+
return this._selectPool(isWrite);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async getConnection(isWrite = false) {
|
|
93
|
+
return this._selectPool(isWrite).getConnection();
|
|
46
94
|
}
|
|
47
95
|
|
|
48
|
-
/**
|
|
49
|
-
* Retrieves the active transaction context from AsyncLocalStorage, if any.
|
|
50
|
-
* @returns {Object|null} The current transaction context.
|
|
51
|
-
*/
|
|
52
96
|
getCurrentTransaction() {
|
|
53
97
|
return this.als.getStore() || null;
|
|
54
98
|
}
|
|
55
99
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
100
|
+
hasActiveTransaction() {
|
|
101
|
+
const store = this.als.getStore();
|
|
102
|
+
return !!(store && store.transactionStarted);
|
|
103
|
+
}
|
|
104
|
+
|
|
61
105
|
onCommit(callback) {
|
|
62
106
|
if (typeof callback !== 'function') {
|
|
63
107
|
throw new TypeError('O callback de onCommit deve ser uma função.');
|
|
64
108
|
}
|
|
65
109
|
|
|
66
110
|
const store = this.als.getStore();
|
|
67
|
-
if (store && store.onCommitHooks) {
|
|
111
|
+
if (store && store.transactionStarted && store.onCommitHooks) {
|
|
68
112
|
store.onCommitHooks.push(callback);
|
|
69
113
|
} else {
|
|
70
|
-
// Se não estiver em transação, executa imediatamente sem bloquear
|
|
71
114
|
Promise.resolve().then(callback).catch(err => {
|
|
72
|
-
|
|
115
|
+
this.logger.error('Erro ao executar callback de onCommit fora de transação:', err);
|
|
73
116
|
});
|
|
74
117
|
}
|
|
75
118
|
}
|
|
76
119
|
|
|
77
120
|
/**
|
|
78
|
-
*
|
|
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.
|
|
121
|
+
* Executa um callback dentro de uma transação gerida com suporte a Savepoints e Auto-Retry de Deadlocks.
|
|
85
122
|
*/
|
|
86
123
|
async transaction(callback, options = {}) {
|
|
87
124
|
if (typeof callback !== 'function') {
|
|
@@ -90,12 +127,17 @@ class DataBase {
|
|
|
90
127
|
|
|
91
128
|
const activeStore = this.als.getStore();
|
|
92
129
|
|
|
93
|
-
// Se
|
|
130
|
+
// Se estiver num contexto lazy (autoTransaction), garante a inicialização da conexão antes de prosseguir
|
|
131
|
+
if (activeStore && !activeStore.transactionStarted && typeof activeStore.ensureConnection === 'function') {
|
|
132
|
+
await activeStore.ensureConnection();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Transação Aninhada (Savepoint)
|
|
94
136
|
if (activeStore && activeStore.transactionStarted && activeStore.connection) {
|
|
95
137
|
activeStore.depth = (activeStore.depth || 1) + 1;
|
|
96
138
|
activeStore.savepointCounter = (activeStore.savepointCounter || 0) + 1;
|
|
97
139
|
const spName = `sp_${activeStore.savepointCounter}`;
|
|
98
|
-
const hooksLengthBefore =
|
|
140
|
+
const hooksLengthBefore = activeStore.onCommitHooks ? activeStore.onCommitHooks.length : 0;
|
|
99
141
|
|
|
100
142
|
await activeStore.connection.query(`SAVEPOINT ${spName}`);
|
|
101
143
|
try {
|
|
@@ -113,85 +155,84 @@ class DataBase {
|
|
|
113
155
|
}
|
|
114
156
|
}
|
|
115
157
|
|
|
116
|
-
// Transação Raiz
|
|
117
|
-
|
|
118
|
-
const
|
|
158
|
+
// Transação Raiz com suporte a Retry em Deadlocks
|
|
159
|
+
const retries = options.retries !== undefined ? Number(options.retries) : this.maxRetries;
|
|
160
|
+
const baseDelay = options.retryDelayMs !== undefined ? Number(options.retryDelayMs) : this.retryDelayMs;
|
|
161
|
+
const validIsoLevel = options.isolationLevel ? validateIsolationLevel(options.isolationLevel) : null;
|
|
119
162
|
|
|
120
|
-
|
|
121
|
-
|
|
163
|
+
let attempt = 0;
|
|
164
|
+
while (true) {
|
|
165
|
+
let connection = null;
|
|
166
|
+
const onCommitHooks = [];
|
|
122
167
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
await connection.query(`SET TRANSACTION ISOLATION LEVEL ${validIsoLevel}`);
|
|
126
|
-
}
|
|
168
|
+
try {
|
|
169
|
+
connection = await this.getConnection(true);
|
|
127
170
|
|
|
128
|
-
|
|
171
|
+
if (validIsoLevel) {
|
|
172
|
+
await connection.query(`SET TRANSACTION ISOLATION LEVEL ${validIsoLevel}`);
|
|
173
|
+
}
|
|
129
174
|
|
|
130
|
-
|
|
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
|
-
};
|
|
175
|
+
await connection.beginTransaction();
|
|
139
176
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
177
|
+
const txContext = {
|
|
178
|
+
id: `${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
179
|
+
db: this,
|
|
180
|
+
connection,
|
|
181
|
+
depth: 1,
|
|
182
|
+
savepointCounter: 0,
|
|
183
|
+
onCommitHooks,
|
|
184
|
+
transactionStarted: true,
|
|
185
|
+
isLazy: false,
|
|
186
|
+
attempt,
|
|
187
|
+
query: (sql, params, isWrite, queryOpts) => this.query(sql, params, isWrite, queryOpts),
|
|
188
|
+
getTableSchema: (table) => this.getTableSchema(table)
|
|
189
|
+
};
|
|
143
190
|
|
|
144
|
-
|
|
191
|
+
const result = await this.als.run(txContext, () => callback(txContext));
|
|
145
192
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
193
|
+
await connection.commit();
|
|
194
|
+
|
|
195
|
+
for (const hook of onCommitHooks) {
|
|
196
|
+
try {
|
|
197
|
+
await hook();
|
|
198
|
+
} catch (hookErr) {
|
|
199
|
+
this.logger.error('Erro ao executar hook de onCommit:', hookErr);
|
|
200
|
+
}
|
|
152
201
|
}
|
|
153
|
-
}
|
|
154
202
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
203
|
+
return result;
|
|
204
|
+
} catch (error) {
|
|
205
|
+
if (connection) {
|
|
206
|
+
try {
|
|
207
|
+
await connection.rollback();
|
|
208
|
+
} catch (rbErr) {
|
|
209
|
+
this.logger.error('Erro durante rollback da transação:', rbErr);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const isRetryable = error && (RETRYABLE_ERROR_CODES.has(error.code) || error.errno === 1213 || error.errno === 1205);
|
|
214
|
+
if (isRetryable && attempt < retries) {
|
|
215
|
+
attempt++;
|
|
216
|
+
// Backoff exponencial com jitter aleatório
|
|
217
|
+
const delay = baseDelay * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 25);
|
|
218
|
+
this.logger.warn(`Deadlock/Lock timeout detetado (${error.code}). Tentativa ${attempt}/${retries} em ${delay}ms...`);
|
|
219
|
+
await sleep(delay);
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
throw error;
|
|
224
|
+
} finally {
|
|
225
|
+
if (connection) {
|
|
226
|
+
connection.release();
|
|
162
227
|
}
|
|
163
|
-
}
|
|
164
|
-
throw error;
|
|
165
|
-
} finally {
|
|
166
|
-
if (connection) {
|
|
167
|
-
connection.release();
|
|
168
228
|
}
|
|
169
229
|
}
|
|
170
230
|
}
|
|
171
231
|
|
|
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
232
|
transactional(fn, options = {}) {
|
|
179
|
-
return (...args) =>
|
|
180
|
-
return this.transaction(() => fn(...args), options);
|
|
181
|
-
};
|
|
233
|
+
return (...args) => this.transaction(() => fn(...args), options);
|
|
182
234
|
}
|
|
183
235
|
|
|
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
236
|
autoTransaction(options = {}) {
|
|
196
237
|
const {
|
|
197
238
|
methods = ['POST', 'PUT', 'DELETE', 'PATCH'],
|
|
@@ -199,6 +240,8 @@ class DataBase {
|
|
|
199
240
|
isolationLevel = null
|
|
200
241
|
} = options;
|
|
201
242
|
|
|
243
|
+
const validIsoLevel = isolationLevel ? validateIsolationLevel(isolationLevel) : null;
|
|
244
|
+
|
|
202
245
|
return (req, res, next) => {
|
|
203
246
|
const method = req.method ? req.method.toUpperCase() : 'GET';
|
|
204
247
|
const isTargetMethod = methods.includes(method);
|
|
@@ -209,28 +252,42 @@ class DataBase {
|
|
|
209
252
|
|
|
210
253
|
const onCommitHooks = [];
|
|
211
254
|
let connection = null;
|
|
255
|
+
let connectionPromise = null;
|
|
212
256
|
let finalized = false;
|
|
213
257
|
|
|
214
258
|
const txContext = {
|
|
215
259
|
id: `req_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
|
|
260
|
+
db: this,
|
|
216
261
|
connection: null,
|
|
217
262
|
depth: 1,
|
|
218
263
|
savepointCounter: 0,
|
|
219
264
|
onCommitHooks,
|
|
220
265
|
isLazy: lazy,
|
|
221
266
|
transactionStarted: false,
|
|
267
|
+
query: (sql, params, isWrite, queryOpts) => this.query(sql, params, isWrite, queryOpts),
|
|
268
|
+
getTableSchema: (table) => this.getTableSchema(table),
|
|
222
269
|
ensureConnection: async () => {
|
|
223
|
-
if (
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
const
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
270
|
+
if (connection) return connection;
|
|
271
|
+
if (!connectionPromise) {
|
|
272
|
+
connectionPromise = (async () => {
|
|
273
|
+
const conn = await this.getConnection(true);
|
|
274
|
+
try {
|
|
275
|
+
if (validIsoLevel) {
|
|
276
|
+
await conn.query(`SET TRANSACTION ISOLATION LEVEL ${validIsoLevel}`);
|
|
277
|
+
}
|
|
278
|
+
await conn.beginTransaction();
|
|
279
|
+
connection = conn;
|
|
280
|
+
txContext.connection = conn;
|
|
281
|
+
txContext.transactionStarted = true;
|
|
282
|
+
return conn;
|
|
283
|
+
} catch (err) {
|
|
284
|
+
conn.release();
|
|
285
|
+
connectionPromise = null;
|
|
286
|
+
throw err;
|
|
287
|
+
}
|
|
288
|
+
})();
|
|
232
289
|
}
|
|
233
|
-
return
|
|
290
|
+
return connectionPromise;
|
|
234
291
|
}
|
|
235
292
|
};
|
|
236
293
|
|
|
@@ -238,6 +295,14 @@ class DataBase {
|
|
|
238
295
|
if (finalized) return;
|
|
239
296
|
finalized = true;
|
|
240
297
|
|
|
298
|
+
if (connectionPromise) {
|
|
299
|
+
try {
|
|
300
|
+
await connectionPromise;
|
|
301
|
+
} catch {
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
241
306
|
if (connection && txContext.transactionStarted) {
|
|
242
307
|
try {
|
|
243
308
|
if (shouldCommit) {
|
|
@@ -246,23 +311,23 @@ class DataBase {
|
|
|
246
311
|
try {
|
|
247
312
|
await hook();
|
|
248
313
|
} catch (hookErr) {
|
|
249
|
-
|
|
314
|
+
this.logger.error('Erro ao executar hook de onCommit no middleware:', hookErr);
|
|
250
315
|
}
|
|
251
316
|
}
|
|
252
317
|
} else {
|
|
253
318
|
await connection.rollback();
|
|
254
319
|
}
|
|
255
320
|
} catch (err) {
|
|
256
|
-
|
|
321
|
+
this.logger.error('Erro finalizando transação no autoTransaction middleware:', err);
|
|
257
322
|
} finally {
|
|
258
323
|
connection.release();
|
|
259
324
|
txContext.connection = null;
|
|
325
|
+
txContext.transactionStarted = false;
|
|
260
326
|
}
|
|
261
327
|
}
|
|
262
328
|
};
|
|
263
329
|
|
|
264
|
-
|
|
265
|
-
const originalEnd = res.end.bind(res);
|
|
330
|
+
const originalEnd = res.end;
|
|
266
331
|
let finishHandled = false;
|
|
267
332
|
|
|
268
333
|
const handleFinish = async (isError) => {
|
|
@@ -274,17 +339,14 @@ class DataBase {
|
|
|
274
339
|
};
|
|
275
340
|
|
|
276
341
|
res.end = function (...args) {
|
|
277
|
-
handleFinish(false)
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
console.error('Erro ao finalizar resposta em autoTransaction:', err);
|
|
281
|
-
originalEnd(...args);
|
|
282
|
-
});
|
|
342
|
+
handleFinish(false)
|
|
343
|
+
.catch(err => console.error('Erro ao finalizar resposta em autoTransaction:', err))
|
|
344
|
+
.finally(() => originalEnd.apply(this, args));
|
|
283
345
|
};
|
|
284
346
|
|
|
285
347
|
res.on('close', () => {
|
|
286
348
|
if (!finishHandled) {
|
|
287
|
-
handleFinish(true);
|
|
349
|
+
handleFinish(true).catch(err => this.logger.error('Erro no evento close:', err));
|
|
288
350
|
}
|
|
289
351
|
});
|
|
290
352
|
|
|
@@ -292,89 +354,100 @@ class DataBase {
|
|
|
292
354
|
try {
|
|
293
355
|
next();
|
|
294
356
|
} catch (err) {
|
|
295
|
-
handleFinish(true).
|
|
357
|
+
handleFinish(true).finally(() => next(err));
|
|
296
358
|
}
|
|
297
359
|
});
|
|
298
360
|
};
|
|
299
361
|
}
|
|
300
362
|
|
|
363
|
+
_recordSlowQuery(sql, params, startTime) {
|
|
364
|
+
if (this.slowQueryThreshold <= 0 && !this.onSlowQuery) return;
|
|
365
|
+
const durationMs = Number(process.hrtime.bigint() - startTime) / 1e6;
|
|
366
|
+
if (this.slowQueryThreshold > 0 && durationMs >= this.slowQueryThreshold) {
|
|
367
|
+
this.logger.warn(`[Slow Query: ${durationMs.toFixed(2)}ms] ${sql}`);
|
|
368
|
+
if (this.onSlowQuery) {
|
|
369
|
+
try {
|
|
370
|
+
this.onSlowQuery({ sql, params, durationMs });
|
|
371
|
+
} catch (err) {
|
|
372
|
+
this.logger.error('Erro no callback onSlowQuery:', err);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
301
378
|
/**
|
|
302
|
-
*
|
|
303
|
-
*
|
|
304
|
-
*
|
|
305
|
-
* @param {
|
|
306
|
-
* @param {
|
|
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.
|
|
379
|
+
* Executa uma query SQL com suporte a transações, telemetria e prepared statements.
|
|
380
|
+
* @param {string} sql - Query SQL.
|
|
381
|
+
* @param {Array|Object} [params] - Parâmetros da query.
|
|
382
|
+
* @param {boolean} [isWrite=false] - Indica se é escrita.
|
|
383
|
+
* @param {Object} [options] - Opções adicionais ({ prepare: boolean, table: string }).
|
|
310
384
|
*/
|
|
311
|
-
async query(sql, params, isWrite = false) {
|
|
385
|
+
async query(sql, params, isWrite = false, options = {}) {
|
|
312
386
|
const store = this.als.getStore();
|
|
387
|
+
const usePrepare = options.prepare !== undefined ? options.prepare : this.usePreparedStatements;
|
|
388
|
+
// Prepared statements binários (.execute) do mysql2 não suportam objetos literais para "SET ?" ou arrays aninhados de bulk insert
|
|
389
|
+
const canUseExecute = usePrepare && (params === undefined || (Array.isArray(params) && !params.some(Array.isArray)));
|
|
390
|
+
const method = canUseExecute ? 'execute' : 'query';
|
|
391
|
+
const trackTime = this.slowQueryThreshold > 0 || Boolean(this.onSlowQuery);
|
|
392
|
+
const startTime = trackTime ? process.hrtime.bigint() : 0n;
|
|
313
393
|
|
|
314
394
|
if (store) {
|
|
315
395
|
let connection = store.connection;
|
|
316
396
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
if (isWrite || !store.isLazy) {
|
|
320
|
-
connection = await store.ensureConnection();
|
|
321
|
-
}
|
|
397
|
+
if (!connection && store.ensureConnection && (isWrite || !store.isLazy)) {
|
|
398
|
+
connection = await store.ensureConnection();
|
|
322
399
|
}
|
|
323
400
|
|
|
324
401
|
if (connection) {
|
|
325
402
|
try {
|
|
326
|
-
const [rows] = await connection
|
|
403
|
+
const [rows] = await connection[method](sql, params);
|
|
404
|
+
if (trackTime) this._recordSlowQuery(sql, params, startTime);
|
|
327
405
|
return rows;
|
|
328
406
|
} catch (error) {
|
|
329
|
-
|
|
330
|
-
// DENTRO DE TRANSAÇÃO: DEVE LANÇAR ERRO para abortar o fluxo e causar rollback
|
|
407
|
+
this.logger.error('Erro na execução da query transacional:', error);
|
|
331
408
|
throw error;
|
|
332
409
|
}
|
|
333
410
|
}
|
|
334
411
|
}
|
|
335
412
|
|
|
336
|
-
// Fluxo padrão fora de transações (mantém contrato e compatibilidade total)
|
|
337
|
-
let connection;
|
|
338
413
|
try {
|
|
339
|
-
|
|
340
|
-
const [rows] = await
|
|
414
|
+
const targetPool = this._selectPool(isWrite);
|
|
415
|
+
const [rows] = await targetPool[method](sql, params);
|
|
416
|
+
if (trackTime) this._recordSlowQuery(sql, params, startTime);
|
|
341
417
|
return rows;
|
|
342
418
|
} catch (error) {
|
|
343
|
-
|
|
419
|
+
this.logger.error('Erro na execução da query:', error);
|
|
344
420
|
if (this.config && this.config.throwOnError) {
|
|
345
421
|
throw error;
|
|
346
422
|
}
|
|
347
423
|
return { error };
|
|
348
|
-
} finally {
|
|
349
|
-
if (connection) {
|
|
350
|
-
connection.release();
|
|
351
|
-
}
|
|
352
424
|
}
|
|
353
425
|
}
|
|
354
426
|
|
|
355
427
|
/**
|
|
356
|
-
*
|
|
357
|
-
* @param {string} table - The name of the table.
|
|
358
|
-
* @returns {Promise<Array>} The schema of the table.
|
|
428
|
+
* Atalho explícito para Prepared Statements binários no servidor MySQL.
|
|
359
429
|
*/
|
|
430
|
+
async execute(sql, params = [], isWrite = false, options = {}) {
|
|
431
|
+
return this.query(sql, params, isWrite, { ...options, prepare: true });
|
|
432
|
+
}
|
|
433
|
+
|
|
360
434
|
async getTableSchema(table) {
|
|
361
435
|
const sql = `SELECT column_name
|
|
362
436
|
FROM information_schema.columns
|
|
363
437
|
WHERE table_schema = COALESCE(?, DATABASE()) AND table_name = ?`;
|
|
364
438
|
const dbName = (this.config && this.config.database) ? this.config.database : null;
|
|
365
|
-
return await this.query(sql, [dbName, table]);
|
|
439
|
+
return await this.query(sql, [dbName, table], false, { table });
|
|
366
440
|
}
|
|
367
441
|
|
|
368
|
-
/**
|
|
369
|
-
* Closes the connection pool.
|
|
370
|
-
*/
|
|
371
442
|
async close() {
|
|
372
443
|
if (this.pool) {
|
|
373
444
|
await this.pool.end();
|
|
374
|
-
console.log(new Date().toLocaleString('pt-br'), 'POOL', 'Database connection pool closed.');
|
|
375
445
|
}
|
|
446
|
+
if (Array.isArray(this.replicaPools) && this.replicaPools.length > 0) {
|
|
447
|
+
await Promise.all(this.replicaPools.map(p => p.end()));
|
|
448
|
+
}
|
|
449
|
+
this.logger.log(new Date().toLocaleString('pt-BR'), 'POOL', 'Database connection pools closed.');
|
|
376
450
|
}
|
|
377
451
|
}
|
|
378
452
|
|
|
379
|
-
module.exports = DataBase;
|
|
380
|
-
|
|
453
|
+
module.exports = DataBase;
|