@areumtecnologia/mysql-db-handler 1.0.12 → 1.0.13
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/databaseHandler.js +103 -65
- package/package.json +1 -1
package/lib/databaseHandler.js
CHANGED
|
@@ -21,6 +21,12 @@ function safeTable(tableName) {
|
|
|
21
21
|
return tableName.split('.').map(part => `\`${sanitizeIdentifier(part)}\``).join('.');
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
function safeColumn(columnName) {
|
|
25
|
+
if (!columnName || typeof columnName !== 'string') return '';
|
|
26
|
+
// Se contiver '.', protege cada segmento (ex: `minhatabela`.`minhacoluna`)
|
|
27
|
+
return columnName.split('.').map(part => `\`${sanitizeIdentifier(part)}\``).join('.');
|
|
28
|
+
}
|
|
29
|
+
|
|
24
30
|
class DatabaseHandler {
|
|
25
31
|
constructor(database, table, expression = '') {
|
|
26
32
|
this.db = database;
|
|
@@ -193,8 +199,9 @@ class DatabaseHandler {
|
|
|
193
199
|
}
|
|
194
200
|
|
|
195
201
|
async selectToDatatable(rawDtQuery, strictCondition = []) {
|
|
202
|
+
const isTrue = (val) => val === true || val === 'true';
|
|
196
203
|
// Hidrata o objeto da requisição para o formato aninhado correto de forma segura
|
|
197
|
-
const dtQuery = this._hydrateObject(rawDtQuery);
|
|
204
|
+
const dtQuery = this._hydrateObject(rawDtQuery) || {};
|
|
198
205
|
const { draw, start, length, search, order, columns } = dtQuery;
|
|
199
206
|
const table = this._safeTable();
|
|
200
207
|
|
|
@@ -204,29 +211,32 @@ class DatabaseHandler {
|
|
|
204
211
|
const finalWhereClauses = baseWhere.sql ? [baseWhere.sql] : [];
|
|
205
212
|
|
|
206
213
|
const dtSearchClauses = [];
|
|
207
|
-
if (columns) {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
const
|
|
215
|
-
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
finalBindings.push(regexSearch);
|
|
214
|
+
if (columns && Array.isArray(columns)) {
|
|
215
|
+
// 1. Busca Global
|
|
216
|
+
if (search && search.value !== '' && search.value !== undefined && search.value !== null) {
|
|
217
|
+
const searchableCols = columns.filter(c => c && c.data && isTrue(c.searchable));
|
|
218
|
+
if (searchableCols.length > 0) {
|
|
219
|
+
const isRegex = isTrue(search.regex);
|
|
220
|
+
const operator = isRegex ? 'REGEXP' : 'LIKE';
|
|
221
|
+
const term = isRegex ? `${search.value}` : `%${search.value}%`;
|
|
222
|
+
|
|
223
|
+
const orClauses = searchableCols.map(c => `${safeColumn(c.data)} ${operator} ?`);
|
|
224
|
+
dtSearchClauses.push(`(${orClauses.join(' OR ')})`);
|
|
225
|
+
for (let i = 0; i < searchableCols.length; i++) {
|
|
226
|
+
finalBindings.push(term);
|
|
221
227
|
}
|
|
222
228
|
}
|
|
223
229
|
}
|
|
230
|
+
|
|
231
|
+
// 2. Busca por Coluna Específica
|
|
224
232
|
for (const col of columns) {
|
|
225
|
-
if (col.data && col.searchable
|
|
226
|
-
const
|
|
227
|
-
const operator =
|
|
228
|
-
|
|
229
|
-
|
|
233
|
+
if (col && col.data && isTrue(col.searchable) && col.search && col.search.value !== '' && col.search.value !== undefined && col.search.value !== null) {
|
|
234
|
+
const isRegex = isTrue(col.search.regex);
|
|
235
|
+
const operator = isRegex ? 'REGEXP' : 'LIKE';
|
|
236
|
+
const term = isRegex ? `${col.search.value}` : `%${col.search.value}%`;
|
|
237
|
+
|
|
238
|
+
dtSearchClauses.push(`${safeColumn(col.data)} ${operator} ?`);
|
|
239
|
+
finalBindings.push(term);
|
|
230
240
|
}
|
|
231
241
|
}
|
|
232
242
|
}
|
|
@@ -235,81 +245,109 @@ class DatabaseHandler {
|
|
|
235
245
|
finalWhereClauses.push(dtSearchClauses.join(' AND '));
|
|
236
246
|
}
|
|
237
247
|
|
|
248
|
+
const hasDtSearch = dtSearchClauses.length > 0;
|
|
238
249
|
const whereSql = finalWhereClauses.length > 0 ? `WHERE ${finalWhereClauses.join(' AND ')}` : '';
|
|
250
|
+
const baseWhereSql = baseWhere.sql ? `WHERE ${baseWhere.sql}` : '';
|
|
239
251
|
|
|
252
|
+
// 3. Ordenação com suporte a múltiplas colunas
|
|
240
253
|
let orderSql = '';
|
|
241
|
-
if (order &&
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
254
|
+
if (order && columns) {
|
|
255
|
+
const orderArray = Array.isArray(order) ? order : [order];
|
|
256
|
+
const orderParts = [];
|
|
257
|
+
for (const ord of orderArray) {
|
|
258
|
+
if (!ord || ord.column === undefined) continue;
|
|
259
|
+
const orderColumnIndex = parseInt(ord.column, 10);
|
|
260
|
+
const colDef = columns[orderColumnIndex];
|
|
261
|
+
if (colDef && isTrue(colDef.orderable) && colDef.data) {
|
|
262
|
+
const orderColumnName = safeColumn(colDef.data);
|
|
263
|
+
const orderDir = ord.dir && ord.dir.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
|
264
|
+
orderParts.push(`${orderColumnName} ${orderDir}`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (orderParts.length > 0) {
|
|
268
|
+
orderSql = `ORDER BY ${orderParts.join(', ')}`;
|
|
247
269
|
}
|
|
248
270
|
}
|
|
249
271
|
|
|
272
|
+
// 4. Paginação segura (valores negativos ou inválidos não quebram a query)
|
|
250
273
|
const safeStart = Math.max(0, parseInt(start, 10) || 0);
|
|
251
274
|
const parsedLength = parseInt(length, 10);
|
|
252
|
-
|
|
275
|
+
let limitSql = '';
|
|
276
|
+
if (!isNaN(parsedLength) && parsedLength > 0) {
|
|
277
|
+
limitSql = `LIMIT ${safeStart}, ${parsedLength}`;
|
|
278
|
+
}
|
|
253
279
|
|
|
254
|
-
// --- Queries ---
|
|
255
|
-
|
|
256
|
-
|
|
280
|
+
// --- 5. Execução Otimizada das Queries ---
|
|
281
|
+
|
|
282
|
+
// Query 1: Total Geral (baseado em strictCondition)
|
|
283
|
+
const totalCountSql = `SELECT COUNT(*) as total FROM ${table} ${baseWhereSql}`.trim();
|
|
257
284
|
const totalResult = await this.executeQuery(totalCountSql, baseWhere.bindings);
|
|
258
285
|
// Contrato: executeQuery propaga { error } em caso de falha (não lança).
|
|
259
286
|
if (totalResult && totalResult.error) {
|
|
260
287
|
return {
|
|
261
|
-
draw: parseInt(draw || 0
|
|
288
|
+
draw: parseInt(draw, 10) || 0,
|
|
262
289
|
recordsTotal: 0,
|
|
263
290
|
recordsFiltered: 0,
|
|
264
291
|
data: [],
|
|
265
292
|
error: totalResult.error.message
|
|
266
293
|
};
|
|
267
294
|
}
|
|
268
|
-
const recordsTotal = (totalResult && totalResult[0] && totalResult[0].total) || 0;
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
295
|
+
const recordsTotal = Number((totalResult && totalResult[0] && totalResult[0].total) || 0);
|
|
296
|
+
|
|
297
|
+
// Query 2: Total Filtrado
|
|
298
|
+
// OTIMIZAÇÃO: se não há filtro extra do DataTables, recordsFiltered é igual a recordsTotal.
|
|
299
|
+
// Elimina uma query COUNT(*) idêntica e pesada.
|
|
300
|
+
let recordsFiltered = recordsTotal;
|
|
301
|
+
if (hasDtSearch) {
|
|
302
|
+
const filteredCountSql = `SELECT COUNT(*) as total FROM ${table} ${whereSql}`.trim();
|
|
303
|
+
const filteredResult = await this.executeQuery(filteredCountSql, finalBindings);
|
|
304
|
+
if (filteredResult && filteredResult.error) {
|
|
305
|
+
return {
|
|
306
|
+
draw: parseInt(draw, 10) || 0,
|
|
307
|
+
recordsTotal,
|
|
308
|
+
recordsFiltered: 0,
|
|
309
|
+
data: [],
|
|
310
|
+
error: filteredResult.error.message
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
recordsFiltered = Number((filteredResult && filteredResult[0] && filteredResult[0].total) || 0);
|
|
280
314
|
}
|
|
281
|
-
const recordsFiltered = (filteredResult && filteredResult[0] && filteredResult[0].total) || 0;
|
|
282
315
|
|
|
283
|
-
//
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
selectFields
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
316
|
+
// Query 3: Dados da Página
|
|
317
|
+
// OTIMIZAÇÃO SHORT-CIRCUIT: se recordsFiltered for 0, não há registros para retornar.
|
|
318
|
+
let data = [];
|
|
319
|
+
if (recordsFiltered > 0) {
|
|
320
|
+
const selectFields = ['*'];
|
|
321
|
+
if (this.expression && this.expression.trim() !== '') {
|
|
322
|
+
// Remove vírgula do início da expressão, se houver, para evitar duplicação
|
|
323
|
+
selectFields.push(this.expression.trim().replace(/^,/, '').trim());
|
|
324
|
+
}
|
|
325
|
+
const dataSql = `SELECT ${selectFields.join(', ')} FROM ${table} ${whereSql ? ` ${whereSql}` : ''}${orderSql ? ` ${orderSql}` : ''}${limitSql ? ` ${limitSql}` : ''}`.trim();
|
|
326
|
+
const dataResult = await this.executeQuery(dataSql, finalBindings);
|
|
327
|
+
if (dataResult && dataResult.error) {
|
|
328
|
+
return {
|
|
329
|
+
draw: parseInt(draw, 10) || 0,
|
|
330
|
+
recordsTotal,
|
|
331
|
+
recordsFiltered,
|
|
332
|
+
data: [],
|
|
333
|
+
error: dataResult.error.message
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
data = Array.isArray(dataResult) ? dataResult : [];
|
|
299
337
|
}
|
|
300
338
|
|
|
301
339
|
return {
|
|
302
|
-
draw: parseInt(draw || 0
|
|
303
|
-
recordsTotal
|
|
304
|
-
recordsFiltered
|
|
305
|
-
data
|
|
340
|
+
draw: parseInt(draw, 10) || 0,
|
|
341
|
+
recordsTotal,
|
|
342
|
+
recordsFiltered,
|
|
343
|
+
data,
|
|
306
344
|
};
|
|
307
345
|
|
|
308
346
|
} catch (e) {
|
|
309
347
|
console.error("Erro em selectToDatatable:", e);
|
|
310
348
|
if (this.onError) this.onError(e);
|
|
311
349
|
return {
|
|
312
|
-
draw: parseInt(dtQuery
|
|
350
|
+
draw: parseInt(dtQuery?.draw, 10) || 0,
|
|
313
351
|
recordsTotal: 0,
|
|
314
352
|
recordsFiltered: 0,
|
|
315
353
|
data: [],
|
package/package.json
CHANGED