@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/README.md +146 -2
- package/lib/database-cache.js +102 -77
- package/lib/database.js +316 -21
- package/lib/databaseHandler.js +449 -384
- package/package.json +4 -3
package/lib/databaseHandler.js
CHANGED
|
@@ -1,384 +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
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
if (
|
|
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
|
-
const
|
|
205
|
-
|
|
206
|
-
const
|
|
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
|
-
if (
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
const
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
}
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
};
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
if (
|
|
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
|
-
|
|
323
|
-
if (params
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
const
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
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;
|