@areumtecnologia/mysql-db-handler 1.0.11 → 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-cache.js +102 -81
- package/lib/database.js +31 -5
- package/lib/databaseHandler.js +449 -394
- package/package.json +2 -2
package/lib/database-cache.js
CHANGED
|
@@ -1,81 +1,102 @@
|
|
|
1
|
-
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
-
const DataBase = require('./database');
|
|
3
|
-
let NodeCache;
|
|
4
|
-
try {
|
|
5
|
-
NodeCache = require('node-cache');
|
|
6
|
-
} catch (e) {
|
|
7
|
-
// Fallback in-memory caso node-cache não esteja instalado
|
|
8
|
-
NodeCache = class FallbackCache {
|
|
9
|
-
constructor() {
|
|
10
|
-
this.map = new Map();
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
return
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async
|
|
58
|
-
const inTransaction = !!this.getCurrentTransaction();
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
1
|
+
// Áreum Tecnologia - Renan Moreira - renan.moreira@areum.com.br
|
|
2
|
+
const DataBase = require('./database');
|
|
3
|
+
let NodeCache;
|
|
4
|
+
try {
|
|
5
|
+
NodeCache = require('node-cache');
|
|
6
|
+
} catch (e) {
|
|
7
|
+
// Fallback in-memory com TTL básico caso node-cache não esteja instalado
|
|
8
|
+
NodeCache = class FallbackCache {
|
|
9
|
+
constructor(options = {}) {
|
|
10
|
+
this.map = new Map();
|
|
11
|
+
this.defaultTTL = (options.stdTTL || 100) * 1000;
|
|
12
|
+
}
|
|
13
|
+
get(key) {
|
|
14
|
+
const entry = this.map.get(key);
|
|
15
|
+
if (!entry) return undefined;
|
|
16
|
+
if (entry.expiry && Date.now() > entry.expiry) {
|
|
17
|
+
this.map.delete(key);
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
return entry.val;
|
|
21
|
+
}
|
|
22
|
+
set(key, val, ttlSeconds) {
|
|
23
|
+
const ttlMs = (ttlSeconds !== undefined ? ttlSeconds * 1000 : this.defaultTTL);
|
|
24
|
+
const expiry = ttlMs > 0 ? Date.now() + ttlMs : null;
|
|
25
|
+
this.map.set(key, { val, expiry });
|
|
26
|
+
}
|
|
27
|
+
flushAll() {
|
|
28
|
+
this.map.clear();
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function safeStringify(data) {
|
|
34
|
+
try {
|
|
35
|
+
return JSON.stringify(data || [], (_, value) => {
|
|
36
|
+
if (typeof value === 'bigint') {
|
|
37
|
+
return value.toString();
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
});
|
|
41
|
+
} catch {
|
|
42
|
+
return String(data);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
class DataBaseCache extends DataBase {
|
|
47
|
+
constructor(config = {}, cacheOptions = { stdTTL: 100, checkperiod: 120 }) {
|
|
48
|
+
super(config);
|
|
49
|
+
this.cache = new NodeCache(cacheOptions);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Mantido por compatibilidade
|
|
53
|
+
createPool() {
|
|
54
|
+
return this.pool;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async query(sql, params, isWrite = false) {
|
|
58
|
+
const inTransaction = !!this.getCurrentTransaction();
|
|
59
|
+
|
|
60
|
+
// Se estiver em transação ou for escrita, bypassa o cache completamente
|
|
61
|
+
if (inTransaction || isWrite) {
|
|
62
|
+
return await super.query(sql, params, isWrite);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const key = `query_${sql}_${safeStringify(params)}`;
|
|
66
|
+
const cachedResult = this.cache.get(key);
|
|
67
|
+
|
|
68
|
+
if (cachedResult) {
|
|
69
|
+
return cachedResult;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const rows = await super.query(sql, params, isWrite);
|
|
73
|
+
if (rows && !rows.error) {
|
|
74
|
+
this.cache.set(key, rows);
|
|
75
|
+
}
|
|
76
|
+
return rows;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async getTableSchema(table) {
|
|
80
|
+
const inTransaction = !!this.getCurrentTransaction();
|
|
81
|
+
const key = `schema_${table}`;
|
|
82
|
+
|
|
83
|
+
if (!inTransaction) {
|
|
84
|
+
const cachedResult = this.cache.get(key);
|
|
85
|
+
if (cachedResult) {
|
|
86
|
+
return cachedResult;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const rows = await super.getTableSchema(table);
|
|
91
|
+
if (!inTransaction && rows && !rows.error) {
|
|
92
|
+
this.cache.set(key, rows);
|
|
93
|
+
}
|
|
94
|
+
return rows;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
clearCache() {
|
|
98
|
+
this.cache.flushAll();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
module.exports = DataBaseCache;
|
package/lib/database.js
CHANGED
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
const mysql = require('mysql2/promise');
|
|
2
2
|
const { AsyncLocalStorage } = require('node:async_hooks');
|
|
3
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
|
+
}
|
|
19
|
+
|
|
4
20
|
class DataBase {
|
|
5
21
|
/**
|
|
6
22
|
* Creates a database instance with a connection pool and async transaction context.
|
|
@@ -79,6 +95,7 @@ class DataBase {
|
|
|
79
95
|
activeStore.depth = (activeStore.depth || 1) + 1;
|
|
80
96
|
activeStore.savepointCounter = (activeStore.savepointCounter || 0) + 1;
|
|
81
97
|
const spName = `sp_${activeStore.savepointCounter}`;
|
|
98
|
+
const hooksLengthBefore = (activeStore.onCommitHooks && activeStore.onCommitHooks.length) || 0;
|
|
82
99
|
|
|
83
100
|
await activeStore.connection.query(`SAVEPOINT ${spName}`);
|
|
84
101
|
try {
|
|
@@ -86,6 +103,9 @@ class DataBase {
|
|
|
86
103
|
await activeStore.connection.query(`RELEASE SAVEPOINT ${spName}`);
|
|
87
104
|
return result;
|
|
88
105
|
} catch (error) {
|
|
106
|
+
if (activeStore.onCommitHooks) {
|
|
107
|
+
activeStore.onCommitHooks.length = hooksLengthBefore;
|
|
108
|
+
}
|
|
89
109
|
await activeStore.connection.query(`ROLLBACK TO SAVEPOINT ${spName}`);
|
|
90
110
|
throw error;
|
|
91
111
|
} finally {
|
|
@@ -101,7 +121,8 @@ class DataBase {
|
|
|
101
121
|
connection = await this.getConnection();
|
|
102
122
|
|
|
103
123
|
if (options.isolationLevel) {
|
|
104
|
-
|
|
124
|
+
const validIsoLevel = validateIsolationLevel(options.isolationLevel);
|
|
125
|
+
await connection.query(`SET TRANSACTION ISOLATION LEVEL ${validIsoLevel}`);
|
|
105
126
|
}
|
|
106
127
|
|
|
107
128
|
await connection.beginTransaction();
|
|
@@ -202,7 +223,8 @@ class DataBase {
|
|
|
202
223
|
if (!connection) {
|
|
203
224
|
connection = await this.getConnection();
|
|
204
225
|
if (isolationLevel) {
|
|
205
|
-
|
|
226
|
+
const validIsoLevel = validateIsolationLevel(isolationLevel);
|
|
227
|
+
await connection.query(`SET TRANSACTION ISOLATION LEVEL ${validIsoLevel}`);
|
|
206
228
|
}
|
|
207
229
|
await connection.beginTransaction();
|
|
208
230
|
txContext.connection = connection;
|
|
@@ -284,7 +306,7 @@ class DataBase {
|
|
|
284
306
|
* @param {Array} [params] - The parameters for the SQL query.
|
|
285
307
|
* @param {boolean} [isWrite=false] - Indicates whether the query is a write/mutation operation.
|
|
286
308
|
* @returns {Promise<Array|{error: Error}>} The result set, or an object with error outside of transactions.
|
|
287
|
-
* @throws {Error} Inside transactions, errors are thrown
|
|
309
|
+
* @throws {Error} Inside transactions or if config.throwOnError is true, errors are thrown.
|
|
288
310
|
*/
|
|
289
311
|
async query(sql, params, isWrite = false) {
|
|
290
312
|
const store = this.als.getStore();
|
|
@@ -319,6 +341,9 @@ class DataBase {
|
|
|
319
341
|
return rows;
|
|
320
342
|
} catch (error) {
|
|
321
343
|
console.error('Erro na execução da query:', error);
|
|
344
|
+
if (this.config && this.config.throwOnError) {
|
|
345
|
+
throw error;
|
|
346
|
+
}
|
|
322
347
|
return { error };
|
|
323
348
|
} finally {
|
|
324
349
|
if (connection) {
|
|
@@ -335,8 +360,9 @@ class DataBase {
|
|
|
335
360
|
async getTableSchema(table) {
|
|
336
361
|
const sql = `SELECT column_name
|
|
337
362
|
FROM information_schema.columns
|
|
338
|
-
WHERE table_schema =
|
|
339
|
-
|
|
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]);
|
|
340
366
|
}
|
|
341
367
|
|
|
342
368
|
/**
|
package/lib/databaseHandler.js
CHANGED
|
@@ -1,394 +1,449 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
return
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
const
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
return
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
async
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
const
|
|
388
|
-
const
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
|
|
1
|
+
const ALLOWED_OPERATORS = new Set([
|
|
2
|
+
'=', '!=', '<>', '>', '>=', '<', '<=',
|
|
3
|
+
'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
|
|
4
|
+
'REGEXP', 'NOT REGEXP', 'IS', 'IS NOT', 'BETWEEN'
|
|
5
|
+
]);
|
|
6
|
+
|
|
7
|
+
function sanitizeOperator(op, defaultOp = '=') {
|
|
8
|
+
if (!op) return defaultOp;
|
|
9
|
+
const upper = String(op).toUpperCase().trim();
|
|
10
|
+
return ALLOWED_OPERATORS.has(upper) ? upper : defaultOp;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function sanitizeIdentifier(name) {
|
|
14
|
+
if (!name || typeof name !== 'string') return '';
|
|
15
|
+
return name.replace(/`/g, '');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function safeTable(tableName) {
|
|
19
|
+
if (!tableName || typeof tableName !== 'string') return '';
|
|
20
|
+
// Se contiver '.', protege cada segmento (ex: `meubanco`.`minhatabela`)
|
|
21
|
+
return tableName.split('.').map(part => `\`${sanitizeIdentifier(part)}\``).join('.');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
class DatabaseHandler {
|
|
25
|
+
constructor(database, table, expression = '') {
|
|
26
|
+
this.db = database;
|
|
27
|
+
this.table = table;
|
|
28
|
+
this.debug = false;
|
|
29
|
+
this.expression = expression;
|
|
30
|
+
this.onError = null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
_safeTable() {
|
|
34
|
+
return safeTable(this.table);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async executeQuery(sql, params, isWrite = false) {
|
|
38
|
+
const rows = await this.db.query(sql, params, isWrite);
|
|
39
|
+
return rows;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Clones this handler bound to a specific transaction or database executor.
|
|
44
|
+
* @param {Object} txOrDb - Transaction context or database instance.
|
|
45
|
+
* @returns {DatabaseHandler} A new handler instance.
|
|
46
|
+
*/
|
|
47
|
+
withTransaction(txOrDb) {
|
|
48
|
+
const handler = new DatabaseHandler(txOrDb, this.table, this.expression);
|
|
49
|
+
handler.debug = this.debug;
|
|
50
|
+
handler.onError = this.onError;
|
|
51
|
+
return handler;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async getSchema() {
|
|
55
|
+
return await this.db.getTableSchema(this.table);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @private
|
|
60
|
+
* Converte um objeto "achatado" (form-urlencoded) em um objeto aninhado (JSON).
|
|
61
|
+
* Ex: { 'columns[0][data]': 'id' } => { columns: [{ data: 'id' }] }
|
|
62
|
+
* Protegido contra Prototype Pollution (CWE-1321).
|
|
63
|
+
*/
|
|
64
|
+
_hydrateObject(flatObject) {
|
|
65
|
+
const result = {};
|
|
66
|
+
for (const key in flatObject) {
|
|
67
|
+
if (!Object.prototype.hasOwnProperty.call(flatObject, key)) continue;
|
|
68
|
+
const keys = key.match(/[^[\]']+/g); // Extrai chaves como ['columns', '0', 'data']
|
|
69
|
+
if (!keys) continue;
|
|
70
|
+
|
|
71
|
+
// Bloqueia poluição de protótipo
|
|
72
|
+
if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let current = result;
|
|
77
|
+
while (keys.length > 1) {
|
|
78
|
+
const k = keys.shift();
|
|
79
|
+
current[k] = current[k] || (isNaN(keys[0]) ? {} : []);
|
|
80
|
+
current = current[k];
|
|
81
|
+
}
|
|
82
|
+
current[keys[0]] = flatObject[key];
|
|
83
|
+
}
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
_parseStrictCondition(strictCondition) {
|
|
88
|
+
if (!strictCondition || !Array.isArray(strictCondition) || strictCondition.length === 0) {
|
|
89
|
+
return { sql: '', bindings: [] };
|
|
90
|
+
}
|
|
91
|
+
const clauses = [];
|
|
92
|
+
const bindings = [];
|
|
93
|
+
for (const item of strictCondition) {
|
|
94
|
+
if (typeof item === 'string') {
|
|
95
|
+
const upper = item.toUpperCase().trim();
|
|
96
|
+
// Operadores lógicos (AND / OR) válidos são inseridos como-is
|
|
97
|
+
if (upper === 'AND' || upper === 'OR') {
|
|
98
|
+
clauses.push(upper);
|
|
99
|
+
}
|
|
100
|
+
} else if (typeof item === 'object' && item !== null) {
|
|
101
|
+
const key = Object.keys(item).find(k => k.toLowerCase() !== 'operator');
|
|
102
|
+
if (!key) continue;
|
|
103
|
+
const cleanKey = sanitizeIdentifier(key);
|
|
104
|
+
const value = item[key];
|
|
105
|
+
let operator = sanitizeOperator(item.operator, '=');
|
|
106
|
+
|
|
107
|
+
// Suporte a arrays => IN / NOT IN (consistente com _buildWhereClause)
|
|
108
|
+
if (Array.isArray(value) && operator === '=') {
|
|
109
|
+
operator = 'IN';
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (Array.isArray(value) && (operator === 'IN' || operator === 'NOT IN')) {
|
|
113
|
+
if (value.length === 0) {
|
|
114
|
+
clauses.push(operator === 'IN' ? '1 = 0' : '1 = 1');
|
|
115
|
+
} else {
|
|
116
|
+
const placeholders = value.map(() => '?').join(', ');
|
|
117
|
+
clauses.push(`\`${cleanKey}\` ${operator} (${placeholders})`);
|
|
118
|
+
bindings.push(...value);
|
|
119
|
+
}
|
|
120
|
+
} else {
|
|
121
|
+
clauses.push(`\`${cleanKey}\` ${operator} ?`);
|
|
122
|
+
bindings.push(value);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
// Junta com espaço para preservar operadores AND/OR intercalados.
|
|
127
|
+
return { sql: `(${clauses.join(' ')})`, bindings };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* @private
|
|
132
|
+
* Constrói a cláusula WHERE (sem a palavra-chave WHERE) e seus bindings associados.
|
|
133
|
+
* @param {Object|Array} where - Condições do where.
|
|
134
|
+
* @param {boolean} useRegex - Se deve usar REGEXP por padrão (para compatibilidade com update).
|
|
135
|
+
* @returns {{ sql: string, bindings: Array }}
|
|
136
|
+
*/
|
|
137
|
+
_buildWhereClause(where, useRegex = false) {
|
|
138
|
+
if (!where) {
|
|
139
|
+
return { sql: '', bindings: [] };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const conditions = [];
|
|
143
|
+
const bindings = [];
|
|
144
|
+
|
|
145
|
+
if (Array.isArray(where)) {
|
|
146
|
+
where.forEach((param) => {
|
|
147
|
+
if (typeof param === 'object' && param !== null && !Array.isArray(param)) {
|
|
148
|
+
const keys = Object.keys(param);
|
|
149
|
+
const colKey = keys.find(k => k.toLowerCase() !== 'operator');
|
|
150
|
+
if (!colKey) return;
|
|
151
|
+
|
|
152
|
+
const cleanKey = sanitizeIdentifier(colKey);
|
|
153
|
+
const value = param[colKey];
|
|
154
|
+
const opKey = keys.find(k => k.toLowerCase() === 'operator');
|
|
155
|
+
const opValue = opKey ? param[opKey] : undefined;
|
|
156
|
+
|
|
157
|
+
let op = sanitizeOperator(opValue, useRegex ? 'REGEXP' : '=');
|
|
158
|
+
|
|
159
|
+
if (Array.isArray(value) && op === '=') {
|
|
160
|
+
op = 'IN';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (Array.isArray(value) && (op === 'IN' || op === 'NOT IN')) {
|
|
164
|
+
if (value.length === 0) {
|
|
165
|
+
conditions.push(op === 'IN' ? '1 = 0' : '1 = 1');
|
|
166
|
+
} else {
|
|
167
|
+
const placeholders = value.map(() => '?').join(', ');
|
|
168
|
+
conditions.push(`\`${cleanKey}\` ${op} (${placeholders})`);
|
|
169
|
+
bindings.push(...value);
|
|
170
|
+
}
|
|
171
|
+
} else {
|
|
172
|
+
const condition = `\`${cleanKey}\` ${op} ?`;
|
|
173
|
+
conditions.push(condition);
|
|
174
|
+
bindings.push(value);
|
|
175
|
+
}
|
|
176
|
+
} else if (typeof param === 'string') {
|
|
177
|
+
const upper = param.toUpperCase().trim();
|
|
178
|
+
if (upper === 'AND' || upper === 'OR') {
|
|
179
|
+
conditions.push(upper);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
return { sql: conditions.join(' '), bindings };
|
|
184
|
+
} else if (typeof where === 'object' && where !== null) {
|
|
185
|
+
const operator = useRegex ? 'REGEXP' : '=';
|
|
186
|
+
const keys = Object.keys(where);
|
|
187
|
+
const sql = keys.map(key => `\`${sanitizeIdentifier(key)}\` ${operator} ?`).join(' AND ');
|
|
188
|
+
const bindings = Object.values(where);
|
|
189
|
+
return { sql, bindings };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return { sql: '', bindings: [] };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async selectToDatatable(rawDtQuery, strictCondition = []) {
|
|
196
|
+
// Hidrata o objeto da requisição para o formato aninhado correto de forma segura
|
|
197
|
+
const dtQuery = this._hydrateObject(rawDtQuery);
|
|
198
|
+
const { draw, start, length, search, order, columns } = dtQuery;
|
|
199
|
+
const table = this._safeTable();
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
const baseWhere = this._parseStrictCondition(strictCondition);
|
|
203
|
+
const finalBindings = [...baseWhere.bindings];
|
|
204
|
+
const finalWhereClauses = baseWhere.sql ? [baseWhere.sql] : [];
|
|
205
|
+
|
|
206
|
+
const dtSearchClauses = [];
|
|
207
|
+
if (columns) {
|
|
208
|
+
if (search && search.value !== '') {
|
|
209
|
+
const globalSearch = columns
|
|
210
|
+
.filter(c => c.data && c.searchable === 'true')
|
|
211
|
+
.map(c => `\`${sanitizeIdentifier(c.data)}\` LIKE ?`);
|
|
212
|
+
|
|
213
|
+
if (globalSearch.length > 0) {
|
|
214
|
+
const regexSearch = search.regex === 'true' ? `${search.value}` : `%${search.value}%`;
|
|
215
|
+
const operator = search.regex === 'true' ? 'REGEXP' : 'LIKE';
|
|
216
|
+
const clauses = globalSearch.map(c => c.replace('LIKE ?', `${operator} ?`));
|
|
217
|
+
|
|
218
|
+
dtSearchClauses.push(`(${clauses.join(' OR ')})`);
|
|
219
|
+
for (let i = 0; i < globalSearch.length; i++) {
|
|
220
|
+
finalBindings.push(regexSearch);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
for (const col of columns) {
|
|
225
|
+
if (col.data && col.searchable === 'true' && col.search && col.search.value !== '') {
|
|
226
|
+
const regexSearch = col.search.regex === 'true' ? `${col.search.value}` : `%${col.search.value}%`;
|
|
227
|
+
const operator = col.search.regex === 'true' ? 'REGEXP' : 'LIKE';
|
|
228
|
+
dtSearchClauses.push(`\`${sanitizeIdentifier(col.data)}\` ${operator} ?`);
|
|
229
|
+
finalBindings.push(regexSearch);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
if (dtSearchClauses.length > 0) {
|
|
235
|
+
finalWhereClauses.push(dtSearchClauses.join(' AND '));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const whereSql = finalWhereClauses.length > 0 ? `WHERE ${finalWhereClauses.join(' AND ')}` : '';
|
|
239
|
+
|
|
240
|
+
let orderSql = '';
|
|
241
|
+
if (order && order.length > 0 && columns) {
|
|
242
|
+
const orderColumnIndex = order[0].column;
|
|
243
|
+
if (columns[orderColumnIndex] && columns[orderColumnIndex].orderable === 'true' && columns[orderColumnIndex].data) {
|
|
244
|
+
const orderColumnName = sanitizeIdentifier(columns[orderColumnIndex].data);
|
|
245
|
+
const orderDir = order[0].dir && order[0].dir.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
|
246
|
+
orderSql = `ORDER BY \`${orderColumnName}\` ${orderDir}`;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const safeStart = Math.max(0, parseInt(start, 10) || 0);
|
|
251
|
+
const parsedLength = parseInt(length, 10);
|
|
252
|
+
const limitSql = (!isNaN(parsedLength) && parsedLength !== -1) ? `LIMIT ${safeStart}, ${parsedLength}` : '';
|
|
253
|
+
|
|
254
|
+
// --- Queries ---
|
|
255
|
+
const baseWhereSql = baseWhere.sql ? `WHERE ${baseWhere.sql}` : '';
|
|
256
|
+
const totalCountSql = `SELECT COUNT(*) as total FROM ${table} ${baseWhereSql}`;
|
|
257
|
+
const totalResult = await this.executeQuery(totalCountSql, baseWhere.bindings);
|
|
258
|
+
// Contrato: executeQuery propaga { error } em caso de falha (não lança).
|
|
259
|
+
if (totalResult && totalResult.error) {
|
|
260
|
+
return {
|
|
261
|
+
draw: parseInt(draw || 0),
|
|
262
|
+
recordsTotal: 0,
|
|
263
|
+
recordsFiltered: 0,
|
|
264
|
+
data: [],
|
|
265
|
+
error: totalResult.error.message
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
const recordsTotal = (totalResult && totalResult[0] && totalResult[0].total) || 0;
|
|
269
|
+
|
|
270
|
+
const filteredCountSql = `SELECT COUNT(*) as total FROM ${table} ${whereSql}`;
|
|
271
|
+
const filteredResult = await this.executeQuery(filteredCountSql, finalBindings);
|
|
272
|
+
if (filteredResult && filteredResult.error) {
|
|
273
|
+
return {
|
|
274
|
+
draw: parseInt(draw || 0),
|
|
275
|
+
recordsTotal: parseInt(recordsTotal),
|
|
276
|
+
recordsFiltered: 0,
|
|
277
|
+
data: [],
|
|
278
|
+
error: filteredResult.error.message
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
const recordsFiltered = (filteredResult && filteredResult[0] && filteredResult[0].total) || 0;
|
|
282
|
+
|
|
283
|
+
// Construção segura da cláusula SELECT para evitar vírgulas duplas.
|
|
284
|
+
const selectFields = ['*'];
|
|
285
|
+
if (this.expression && this.expression.trim() !== '') {
|
|
286
|
+
// Remove vírgula do início da expressão, se houver, para evitar duplicação
|
|
287
|
+
selectFields.push(this.expression.trim().replace(/^,/, '').trim());
|
|
288
|
+
}
|
|
289
|
+
const dataSql = `SELECT ${selectFields.join(', ')} FROM ${table} ${whereSql} ${orderSql} ${limitSql}`;
|
|
290
|
+
const data = await this.executeQuery(dataSql, finalBindings);
|
|
291
|
+
if (data && data.error) {
|
|
292
|
+
return {
|
|
293
|
+
draw: parseInt(draw || 0),
|
|
294
|
+
recordsTotal: parseInt(recordsTotal),
|
|
295
|
+
recordsFiltered: parseInt(recordsFiltered),
|
|
296
|
+
data: [],
|
|
297
|
+
error: data.error.message
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return {
|
|
302
|
+
draw: parseInt(draw || 0),
|
|
303
|
+
recordsTotal: parseInt(recordsTotal),
|
|
304
|
+
recordsFiltered: parseInt(recordsFiltered),
|
|
305
|
+
data: data,
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
} catch (e) {
|
|
309
|
+
console.error("Erro em selectToDatatable:", e);
|
|
310
|
+
if (this.onError) this.onError(e);
|
|
311
|
+
return {
|
|
312
|
+
draw: parseInt(dtQuery.draw || 0),
|
|
313
|
+
recordsTotal: 0,
|
|
314
|
+
recordsFiltered: 0,
|
|
315
|
+
data: [],
|
|
316
|
+
error: e.message
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async selectBy(params) {
|
|
322
|
+
const table = this._safeTable();
|
|
323
|
+
if (params) {
|
|
324
|
+
const sql = `SELECT *${this.expression ? this.expression : ''} FROM ${table} WHERE ?`;
|
|
325
|
+
const rows = await this.executeQuery(sql, params);
|
|
326
|
+
return rows; // retorna um array, mesmo que vazio
|
|
327
|
+
}
|
|
328
|
+
else {
|
|
329
|
+
const sql = `SELECT *${this.expression ? this.expression : ''} FROM ${table}`;
|
|
330
|
+
return this.executeQuery(sql);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* @deprecated Use select() instead.
|
|
336
|
+
*/
|
|
337
|
+
async selectOld(params, clauses = {}) {
|
|
338
|
+
if (params != null && !Array.isArray(params)) {
|
|
339
|
+
return new Error('O parâmetro "params" deve ser um array');
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const conditions = [];
|
|
343
|
+
const values = [];
|
|
344
|
+
|
|
345
|
+
if (params && params.length) {
|
|
346
|
+
params.map((param) => {
|
|
347
|
+
if (typeof param === 'object' && !Array.isArray(param)) {
|
|
348
|
+
const entries = Object.entries(param);
|
|
349
|
+
const [key, value] = entries[0];
|
|
350
|
+
const [operator, opValue] = entries[1] || [];
|
|
351
|
+
|
|
352
|
+
const cleanKey = sanitizeIdentifier(key);
|
|
353
|
+
const condition = `\`${cleanKey}\` ${opValue ?? '='} ?`;
|
|
354
|
+
conditions.push(condition);
|
|
355
|
+
values.push(value);
|
|
356
|
+
} else if (typeof param === 'string') {
|
|
357
|
+
conditions.push(param.toUpperCase());
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' ')}` : '';
|
|
363
|
+
|
|
364
|
+
// Cláusulas adicionais
|
|
365
|
+
const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
|
|
366
|
+
const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
|
|
367
|
+
const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
|
|
368
|
+
const descClause = clauses['DESC'] ? ` DESC ` : '';
|
|
369
|
+
const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
|
|
370
|
+
const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
|
|
371
|
+
|
|
372
|
+
const sql = `SELECT *${this.expression ?? ''} FROM ${this._safeTable()}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
|
|
373
|
+
|
|
374
|
+
const rows = await this.executeQuery(sql, values);
|
|
375
|
+
return rows;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async select(params, clauses = {}) {
|
|
379
|
+
if (params != null && !Array.isArray(params)) {
|
|
380
|
+
return new Error('O parâmetro "params" deve ser um array');
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const { sql: whereSql, bindings: values } = this._buildWhereClause(params);
|
|
384
|
+
const whereClause = whereSql ? ` WHERE ${whereSql}` : '';
|
|
385
|
+
|
|
386
|
+
// Cláusulas adicionais
|
|
387
|
+
const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
|
|
388
|
+
const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
|
|
389
|
+
const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
|
|
390
|
+
const descClause = clauses['DESC'] ? ` DESC ` : '';
|
|
391
|
+
const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
|
|
392
|
+
const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
|
|
393
|
+
|
|
394
|
+
const sql = `SELECT *${this.expression ?? ''} FROM ${this._safeTable()}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
|
|
395
|
+
|
|
396
|
+
const rows = await this.executeQuery(sql, values);
|
|
397
|
+
return rows;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async insert(params) {
|
|
401
|
+
const sql = `INSERT INTO ${this._safeTable()} SET ?`;
|
|
402
|
+
const result = await this.executeQuery(sql, params, true);
|
|
403
|
+
return result;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
async update(params, options = {}) {
|
|
407
|
+
if (!params || typeof params !== 'object' || !params.set || typeof params.set !== 'object' || Object.keys(params.set).length === 0) {
|
|
408
|
+
throw new Error('A operação de update requer um objeto "set" com ao menos um campo.');
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// Inicializa a string SQL para a cláusula SET
|
|
412
|
+
let setClause = Object.keys(params.set).map(key => `\`${sanitizeIdentifier(key)}\` = ?`).join(', ');
|
|
413
|
+
let setValues = Object.values(params.set);
|
|
414
|
+
|
|
415
|
+
// Inicializa a string SQL para a cláusula WHERE
|
|
416
|
+
const { sql: whereClause, bindings: whereValues } = this._buildWhereClause(params.where, !!options.useRegex);
|
|
417
|
+
if (!whereClause || whereClause.trim() === '') {
|
|
418
|
+
throw new Error('A operação de update requer uma cláusula "where" não vazia para prevenir alterações em toda a tabela.');
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Constrói a consulta SQL completa
|
|
422
|
+
const sql = `UPDATE ${this._safeTable()} SET ${setClause} WHERE ${whereClause}`;
|
|
423
|
+
// Combina os valores SET e WHERE em um único array
|
|
424
|
+
const values = [...setValues, ...whereValues];
|
|
425
|
+
// Executa a consulta sinalizando mutação de escrita
|
|
426
|
+
const result = await this.executeQuery(sql, values, true);
|
|
427
|
+
|
|
428
|
+
return result;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async delete(conditions) {
|
|
432
|
+
if (!conditions || typeof conditions !== 'object') {
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
const conditionKeys = Object.keys(conditions);
|
|
436
|
+
if (conditionKeys.length === 0) {
|
|
437
|
+
// Se o objeto conditions estiver vazio, não faz nada para evitar truncar a tabela
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const whereConditions = conditionKeys.map((key) => `\`${sanitizeIdentifier(key)}\` = ?`).join(' AND ');
|
|
442
|
+
const sql = `DELETE FROM ${this._safeTable()} WHERE ${whereConditions}`;
|
|
443
|
+
const params = conditionKeys.map((key) => conditions[key]);
|
|
444
|
+
const result = await this.executeQuery(sql, params, true);
|
|
445
|
+
return result;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
module.exports = DatabaseHandler;
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@areumtecnologia/mysql-db-handler",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
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 && node tests/transactions.test.js && node tests/customersSales.test.js"
|
|
7
|
+
"test": "node tests/security_and_robustness.test.js && 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",
|