@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.
@@ -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
- 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);
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 === '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);
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 && 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}`;
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
- const limitSql = (!isNaN(parsedLength) && parsedLength !== -1) ? `LIMIT ${safeStart}, ${parsedLength}` : '';
275
+ let limitSql = '';
276
+ if (!isNaN(parsedLength) && parsedLength > 0) {
277
+ limitSql = `LIMIT ${safeStart}, ${parsedLength}`;
278
+ }
253
279
 
254
- // --- Queries ---
255
- const baseWhereSql = baseWhere.sql ? `WHERE ${baseWhere.sql}` : '';
256
- const totalCountSql = `SELECT COUNT(*) as total FROM ${table} ${baseWhereSql}`;
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
- 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
- };
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
- // 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
- };
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: parseInt(recordsTotal),
304
- recordsFiltered: parseInt(recordsFiltered),
305
- data: 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.draw || 0),
350
+ draw: parseInt(dtQuery?.draw, 10) || 0,
313
351
  recordsTotal: 0,
314
352
  recordsFiltered: 0,
315
353
  data: [],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@areumtecnologia/mysql-db-handler",
3
- "version": "1.0.12",
3
+ "version": "1.0.13",
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": {