@areumtecnologia/mysql-db-handler 1.0.12 → 1.0.14

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 CHANGED
@@ -25,7 +25,14 @@ A powerful, robust, and production-ready MySQL wrapper for Node.js. It features
25
25
  * [Inserting Records (`insert`)](#inserting-records-insert)
26
26
  * [Updating Records (`update`)](#updating-records-update)
27
27
  * [Deleting Records (`delete`)](#deleting-records-delete)
28
- * [jQuery DataTables Server-Side Support](#jquery-datatables-server-side-support)
28
+ * [jQuery DataTables Server-Side Support (`selectToDatatable`)](#jquery-datatables-server-side-support-selecttodatatable)
29
+ * [Key Features & Performance](#key-features--performance-optimizations)
30
+ * [Method Signature](#method-signature)
31
+ * [Basic Express.js Example](#basic-expressjs-example)
32
+ * [Enforcing Backend Security (`strictCondition`)](#enforcing-backend-security-strictcondition)
33
+ * [Using JOINs and Custom Expressions](#using-joins-and-custom-expressions)
34
+ * [Frontend jQuery DataTables Setup](#frontend-jquery-datatables-setup)
35
+ * [Response Structure & Error Handling](#response-structure--error-handling)
29
36
  * [Transaction Support (ACID & Transparent)](#transaction-support-acid--transparent)
30
37
  * [1. Explicit Block (`db.transaction`)](#1-explicit-block-dbtransaction)
31
38
  * [2. Singleton Compatibility with `AsyncLocalStorage`](#2-singleton-compatibility-with-asynclocalstorage)
@@ -316,30 +323,168 @@ console.log('Deleted rows:', result.affectedRows);
316
323
 
317
324
  ---
318
325
 
319
- ## jQuery DataTables Server-Side Support
326
+ ## jQuery DataTables Server-Side Support (`selectToDatatable`)
320
327
 
321
- The `selectToDatatable` method processes the complex nested payloads sent by jQuery DataTables server-side scripts and returns the required format.
328
+ The `selectToDatatable` method provides seamless, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It automatically handles pagination, search (global and column-based), multi-column ordering, regex filters, total/filtered counts, and backend security constraints.
329
+
330
+ ### Key Features & Performance Optimizations
331
+
332
+ * **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state in standard page loads and pagination), `recordsFiltered` is automatically set to `recordsTotal`. The method skips the redundant second `COUNT(*)` query, **reducing database count latency and I/O by up to 50%**.
333
+ * **Short-Circuit on Zero Results:** If search criteria yield zero records (`recordsFiltered === 0`), the data retrieval query (`SELECT ... LIMIT`) is skipped entirely, returning an empty array `data: []` instantly without triggering expensive `filesort` or index scans.
334
+ * **Format & Content-Type Agnostic:** Fully supports both `application/json` (with native JavaScript boolean values `true`/`false`) and `application/x-www-form-urlencoded` (nested or bracket-flattened parameters like `columns[0][data]`).
335
+ * **Multi-Column Sorting:** Seamlessly parses multiple order directives (e.g. holding Shift or configuring `order: [[0, 'asc'], [1, 'desc']]`), producing `ORDER BY \`col1\` ASC, \`col2\` DESC`.
336
+ * **Safe Qualified Column Identifiers:** Automatically splits table/alias qualified column names (e.g. `u.name`, `p.title`) and escapes each component separately (`` `u`.`name` ``), avoiding MySQL `ER_BAD_FIELD_ERROR` issues when using JOINs.
337
+ * **Prototype Pollution Protection (CWE-1321):** Deeply sanitizes incoming request keys, blocking injections targeting `__proto__`, `constructor`, or `prototype`.
338
+
339
+ ---
340
+
341
+ ### Method Signature
322
342
 
323
343
  ```javascript
324
- // Express.js Route Example
325
- app.post('/api/users/dt', async (req, res) => {
326
- // req.body contains the DataTables standard payload:
327
- // { draw: 1, start: 0, length: 10, search: { value: 'John', regex: false }, columns: [...] }
328
-
329
- // You can enforce strict conditions that the client cannot bypass (e.g., tenant containment)
344
+ await handler.selectToDatatable(rawDtQuery, strictCondition = [])
345
+ ```
346
+
347
+ | Parameter | Type | Description |
348
+ | :--- | :--- | :--- |
349
+ | `rawDtQuery` | `Object` | The request payload sent by jQuery DataTables (`req.body` or `req.query`). Supports both flat bracketed keys and nested objects. |
350
+ | `strictCondition` | `Array` *(Optional)* | Backend conditions that the client cannot view or modify (e.g. multi-tenant isolation, user scoping, active-only filters). |
351
+
352
+ ---
353
+
354
+ ### Basic Express.js Example
355
+
356
+ ```javascript
357
+ const express = require('express');
358
+ const { db, usersHandler } = require('./databaseController');
359
+
360
+ const app = express();
361
+ app.use(express.json());
362
+ app.use(express.urlencoded({ extended: true }));
363
+
364
+ app.post('/api/users/datatable', async (req, res) => {
365
+ // req.body contains: { draw, start, length, search, order, columns }
366
+ const result = await usersHandler.selectToDatatable(req.body);
367
+ res.json(result);
368
+ });
369
+ ```
370
+
371
+ ---
372
+
373
+ ### Enforcing Backend Security (`strictCondition`)
374
+
375
+ Never rely on the client to enforce data access boundaries. Pass a `strictCondition` array to apply non-bypassable constraints. It shares the same query-building syntax as `select()`, supporting custom operators, arrays (`IN`), and `AND`/`OR` conjunctions:
376
+
377
+ ```javascript
378
+ app.post('/api/orders/datatable', async (req, res) => {
379
+ // Client-side parameters cannot bypass these conditions:
330
380
  const strictConditions = [
331
381
  { tenant_id: req.user.tenantId },
332
382
  'AND',
333
- { status: 'deleted', operator: '!=' }
383
+ { status: 'deleted', operator: '!=' },
384
+ 'AND',
385
+ { store_id: [101, 102, 105] } // Automatically mapped to: `store_id` IN (?, ?, ?)
334
386
  ];
335
387
 
336
- const datatableResult = await usersHandler.selectToDatatable(req.body, strictConditions);
337
-
338
- // Returns: { draw: 1, recordsTotal: 100, recordsFiltered: 12, data: [...] }
339
- res.json(datatableResult);
388
+ const result = await ordersHandler.selectToDatatable(req.body, strictConditions);
389
+ res.json(result);
340
390
  });
341
391
  ```
342
392
 
393
+ ---
394
+
395
+ ### Using JOINs and Custom Expressions
396
+
397
+ If your table requires JOINs or computed fields, initialize the `DataBaseHandler` with an expression parameter:
398
+
399
+ ```javascript
400
+ // Table: 'sales s'
401
+ // Expression: JOIN with customers and users, selecting extra fields
402
+ const salesHandler = new DataBaseHandler(
403
+ db,
404
+ 'customers_sales s',
405
+ ', c.name AS customer_name, u.name AS user_name ' +
406
+ 'LEFT JOIN customers c ON c.id = s.customer ' +
407
+ 'LEFT JOIN users u ON u.id = s.user'
408
+ );
409
+
410
+ app.post('/api/sales/datatable', async (req, res) => {
411
+ // DataTables columns can now search and sort by qualified identifiers:
412
+ // e.g. columns: [{ data: 's.id' }, { data: 'c.name' }, { data: 's.amount' }]
413
+ const result = await salesHandler.selectToDatatable(req.body, [
414
+ { 's.deleted_at': null, operator: 'IS' }
415
+ ]);
416
+ res.json(result);
417
+ });
418
+ ```
419
+
420
+ ---
421
+
422
+ ### Frontend jQuery DataTables Setup
423
+
424
+ Configure your frontend DataTables instance with `serverSide: true`:
425
+
426
+ ```javascript
427
+ $('#usersTable').DataTable({
428
+ processing: true,
429
+ serverSide: true,
430
+ ajax: {
431
+ url: '/api/users/datatable',
432
+ type: 'POST',
433
+ contentType: 'application/json',
434
+ data: function (d) {
435
+ return JSON.stringify(d);
436
+ }
437
+ },
438
+ columns: [
439
+ { data: 'id', name: 'id' },
440
+ { data: 'name', name: 'name' },
441
+ { data: 'email', name: 'email' },
442
+ { data: 'role', name: 'role' },
443
+ {
444
+ data: null,
445
+ orderable: false,
446
+ searchable: false,
447
+ render: function (data, type, row) {
448
+ return `<button onclick="editUser(${row.id})">Edit</button>`;
449
+ }
450
+ }
451
+ ],
452
+ order: [[0, 'desc']]
453
+ });
454
+ ```
455
+
456
+ ---
457
+
458
+ ### Response Structure & Error Handling
459
+
460
+ The method always returns the standard JSON response expected by DataTables:
461
+
462
+ #### Success Response
463
+ ```json
464
+ {
465
+ "draw": 1,
466
+ "recordsTotal": 1250,
467
+ "recordsFiltered": 45,
468
+ "data": [
469
+ { "id": 42, "name": "John Doe", "email": "john@example.com", "role": "admin" },
470
+ { "id": 43, "name": "Jane Smith", "email": "jane@example.com", "role": "editor" }
471
+ ]
472
+ }
473
+ ```
474
+
475
+ #### Safe Error Handling
476
+ If an underlying database error occurs, `selectToDatatable` catches it safely, notifies your `onError` handler (if configured), and returns a structured response with the error message so the client table does not hang indefinitely:
477
+
478
+ ```json
479
+ {
480
+ "draw": 1,
481
+ "recordsTotal": 0,
482
+ "recordsFiltered": 0,
483
+ "data": [],
484
+ "error": "ER_NO_SUCH_TABLE: Table 'my_app_db.invalid_table' doesn't exist"
485
+ }
486
+ ```
487
+
343
488
 
344
489
  ---
345
490
 
@@ -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.14",
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": {