@areumtecnologia/mysql-db-handler 2.0.3 → 2.1.1

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
@@ -1,1200 +1,1381 @@
1
- # @areumtecnologia/mysql-db-handler
2
-
3
- A powerful, robust, and production-ready MySQL wrapper for Node.js. It features connection pooling, query caching (optional), jQuery DataTables server-side processing integration, safe error handling, and a flexible abstraction layer for CRUD operations.
4
-
5
- ## Table of Contents
6
-
7
- * [Features](#features)
8
- * [Installation](#installation)
9
- * [Core Classes](#core-classes)
10
- * [DataBase (Standard Connection)](#1-database-standard-connection)
11
- * [DataBase (With Query & Schema Caching)](#2-database-with-query--schema-caching)
12
- * [DataBaseHandler (CRUD Abstraction)](#3-databasehandler-crud-abstraction)
13
- * [Basic Usage](#basic-usage)
14
- * [1. Initializing Connection](#1-initializing-connection)
15
- * [2. Executing Raw SQL](#2-executing-raw-sql)
16
- * [3. Using the DataBaseHandler](#3-using-the-databasehandler)
17
- * [Advanced Querying (`select` method)](#advanced-querying-select-method)
18
- * [Basic Selection](#basic-selection)
19
- * [Working with the `IN` and `NOT IN` Operators](#working-with-the-in-and-not-in-operators)
20
- * [Automatic `IN` Detection](#automatic-in-detection)
21
- * [Explicit `IN` / `NOT IN` Operator](#explicit-in--not-in-operator)
22
- * [Empty Array Safety (`IN ()` Protection)](#empty-array-safety-in-protection)
23
- * [Combining Multiple Conditions (AND / OR)](#combining-multiple-conditions-and--or)
24
- * [CRUD Operations](#crud-operations)
25
- * [Inserting Records (`insert`)](#inserting-records-insert)
26
- * [Bulk Insert (`insertMany`)](#bulk-insert-insertmany)
27
- * [Upsert with Smart Timestamps (`upsert`)](#upsert-with-smart-timestamps-upsert)
28
- * [Updating Records (`update`)](#updating-records-update)
29
- * [Deleting Records (`delete`)](#deleting-records-delete)
30
- * [Fluent Mutations (`.where().update()` / `.delete()`)](#fluent-mutations-whereupdate--wheredelete)
31
- * [jQuery DataTables Server-Side Support (`selectToDatatable`)](#jquery-datatables-server-side-support-selecttodatatable)
32
- * [Key Features & Performance](#key-features--performance-optimizations)
33
- * [Method Signature](#method-signature)
34
- * [Basic Express.js Example](#basic-expressjs-example)
35
- * [Enforcing Backend Security (`strictCondition`)](#enforcing-backend-security-strictcondition)
36
- * [Using JOINs and Custom Expressions](#using-joins-and-custom-expressions)
37
- * [Frontend jQuery DataTables Setup](#frontend-jquery-datatables-setup)
38
- * [Response Structure & Error Handling](#response-structure--error-handling)
39
- * [Transaction Support (ACID & Transparent)](#transaction-support-acid--transparent)
40
- * [1. Explicit Block (`db.transaction`)](#1-explicit-block-dbtransaction)
41
- * [2. Singleton Compatibility with `AsyncLocalStorage`](#2-singleton-compatibility-with-asynclocalstorage)
42
- * [3. Post-Commit Hook (`db.onCommit`)](#3-post-commit-hook-dboncommit)
43
- * [4. Route Wrapper (`db.transactional`)](#4-route-wrapper-dbtransactional)
44
- * [5. Express Lazy Middleware (`db.autoTransaction`)](#5-express-lazy-middleware-dbautotransaction)
45
- * [6. Nested Transactions & Savepoints](#6-nested-transactions--savepoints)
46
- * [Database Singleton Pattern](#database-singleton-pattern)
47
- * [Error Handling Strategy](#error-handling-strategy)
48
- * [High-Scale Enterprise Micro-ORM (v2.0.0)](#high-scale-enterprise-micro-orm-v200)
49
- * [1. Fluent Query Builder & Aggregations (`.first`, `.count`, `.paginate`, `raw`)](#1-fluent-query-builder--aggregations-first-count-paginate-raw)
50
- * [2. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)](#2-fluent-joins--eager-loading-eliminating-the-n1-problem)
51
- * [3. Read/Write Splitting (Master + Read Replicas)](#3-readwrite-splitting-master--read-replicas)
52
- * [4. Keyset Pagination & Memory-Safe Streaming](#4-keyset-pagination--memory-safe-streaming)
53
- * [5. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks](#5-native-business-rules-soft-deletes-timestamps--lifecycle-hooks)
54
- * [6. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking](#6-runtime-schema-validation-auto-strip--sensitive-field-masking)
55
- * [Contributing](#contributing)
56
- * [License](#license)
57
-
58
- ---
59
-
60
- ## Features
61
-
62
- * **Connection Pooling:** Efficiently manages and recycles database connections using `mysql2/promise`.
63
- * **ACID Transactions:** Comprehensive transaction management with automatic `BEGIN`, `COMMIT`, `ROLLBACK`, and safe connection release.
64
- * **Transparent Singleton Support:** Powered by native Node.js `AsyncLocalStorage`. Shared table singletons automatically adopt the current transaction without passing `tx` around.
65
- * **Post-Commit Hooks (`onCommit`):** Execute external tasks (banking APIs, emails, webhooks) strictly after database transactions successfully commit.
66
- * **Express Lazy Middleware:** Zero-code change transactions via `db.autoTransaction()`. Reads remain non-blocking on the pool, while write operations seamlessly open and commit transactions on demand.
67
- * **Savepoints (Nested Transactions):** Safely run sub-transactions with partial rollback support without aborting outer transactions.
68
- * **Flexible Query Builder:** Run complex operations without writing manual SQL strings.
69
- * **Automatic `IN` Handling:** Smart processing of arrays for SQL `IN` and `NOT IN` operations (including prevention of empty array query crashes).
70
- * **Optional Caching Wrapper:** Native support for query and schema caching using `node-cache` (automatically bypassed during active transactions).
71
- * **Server-Side DataTables Integration:** Effortless integration with jQuery DataTables server-side requests, handling filters, sorting, search (global and column-based), regex, and count totals automatically.
72
- * **Robust Error Handling:** Intercepts and wraps database errors in predictable objects outside transactions, while throwing inside transactions to ensure immediate rollback.
73
-
74
- ---
75
-
76
- ## Installation
77
-
78
- ```bash
79
- npm install @areumtecnologia/mysql-db-handler
80
- ```
81
-
82
- If you wish to use the caching features, ensure `node-cache` is installed:
83
- ```bash
84
- npm install node-cache
85
- ```
86
-
87
- ---
88
-
89
- ## Core Classes
90
-
91
- The package exports the following primary components:
92
-
93
- ### 1. `DataBase` (Standard Connection)
94
- Located in `lib/database.js`. Manages standard pooled connections, schema discovery, and query execution.
95
-
96
- ### 2. `DataBase` (With Query & Schema Caching)
97
- Located in `lib/database-cache.js`. Overrides the standard `DataBase` implementation to provide in-memory query and table schema caching. It is ideal for read-heavy environments.
98
-
99
- ### 3. `DataBaseHandler` (CRUD Abstraction)
100
- Located in `lib/databaseHandler.js`. Bind this class to a specific table to perform database actions through utility methods (`select`, `selectBy`, `insert`, `update`, `delete`, `selectToDatatable`).
101
-
102
- > [!NOTE]
103
- > **Convenção de Nomenclatura & Aliases:**
104
- > O pacote exporta tanto os identificadores em PascalCase com `B` maiúsculo (`DataBase`, `DataBaseHandler`, `DataBaseCache`) quanto aliases com `b` minúsculo (`Database`, `DatabaseHandler`, `DatabaseCache`), permitindo compatibilidade total com qualquer estilo de importação:
105
- > ```javascript
106
- > const { DataBase, DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
107
- > // ou:
108
- > const { Database, DatabaseHandler } = require('@areumtecnologia/mysql-db-handler');
109
- > ```
110
-
111
- ---
112
-
113
- ## Basic Usage
114
-
115
- ### 1. Initializing Connection
116
-
117
- ```javascript
118
- const { DataBase } = require('@areumtecnologia/mysql-db-handler');
119
-
120
- // Configuration matches mysql2 connection configuration
121
- const db = new DataBase({
122
- host: 'localhost',
123
- user: 'root',
124
- password: 'password',
125
- database: 'my_app_db',
126
- port: 3306,
127
- connectionLimit: 10,
128
- waitForConnections: true,
129
- queueLimit: 0
130
- });
131
- ```
132
-
133
- ### 2. Executing Raw SQL
134
-
135
- Raw queries are executed through connection pooling. The library handles obtaining and releasing the connection automatically.
136
-
137
- ```javascript
138
- try {
139
- const rows = await db.query('SELECT * FROM users WHERE active = ? AND role = ?', [1, 'editor']);
140
- console.log('Active editors:', rows);
141
- } catch (error) {
142
- console.error('Database query failed:', error);
143
- }
144
- ```
145
-
146
- ### 3. Using the DataBaseHandler
147
-
148
- Wrap a table with a handler to abstract SQL construction.
149
-
150
- ```javascript
151
- const { DataBase, DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
152
-
153
- const db = new DataBase({ /* config */ });
154
- const usersHandler = new DataBaseHandler(db, 'users');
155
- ```
156
-
157
- ---
158
-
159
- ## Advanced Querying (`select` method)
160
-
161
- The `select(params, clauses)` method builds complex SQL `WHERE` clauses from arrays of condition objects.
162
-
163
- ### Basic Selection
164
-
165
- You can pass condition objects where the key is the column name and the value is the target value.
166
-
167
- ```javascript
168
- // Simple equals comparison (=)
169
- const users = await usersHandler.select([
170
- { role: 'admin' }
171
- ]);
172
- // Executes: SELECT * FROM users WHERE `role` = ?
173
- ```
174
-
175
- ### Working with the `IN` and `NOT IN` Operators
176
-
177
- The library provides special support for SQL `IN` operations by mapping JavaScript arrays to queries.
178
-
179
- #### Automatic `IN` Detection
180
- If a condition's value is an array, and no operator is explicitly set, the query builder automatically treats it as an `IN` statement:
181
-
182
- ```javascript
183
- const activeUsers = await usersHandler.select([
184
- { status: ['active', 'pending'] }
185
- ]);
186
- // Executes: SELECT * FROM users WHERE `status` IN (?, ?)
187
- // Bindings: ['active', 'pending']
188
- ```
189
-
190
- #### Explicit `IN` / `NOT IN` Operator
191
- You can explicitly define the `operator` as `'IN'` or `'NOT IN'`:
192
-
193
- ```javascript
194
- // Using NOT IN explicitly
195
- const nonAdminUsers = await usersHandler.select([
196
- { role: ['admin', 'superadmin'], operator: 'NOT IN' }
197
- ]);
198
- // Executes: SELECT * FROM users WHERE `role` NOT IN (?, ?)
199
- // Bindings: ['admin', 'superadmin']
200
- ```
201
-
202
- #### Empty Array Safety (`IN ()` Protection)
203
- In standard SQL, executing a query with an empty array in the `IN` clause (e.g., `WHERE status IN ()`) yields a syntax error and crashes the execution. The library automatically mitigates this:
204
-
205
- * **Empty `IN`**: Evaluates to `1 = 0` (always false). No records match this sub-clause, ensuring safe execution.
206
- * **Empty `NOT IN`**: Evaluates to `1 = 1` (always true). All records match this sub-clause, returning all values since nothing is excluded.
207
-
208
- ```javascript
209
- // Safe empty array handling
210
- const results = await usersHandler.select([
211
- { id: [], operator: 'IN' }
212
- ]);
213
- // Executes: SELECT * FROM users WHERE 1 = 0
214
-
215
- const allResults = await usersHandler.select([
216
- { id: [], operator: 'NOT IN' }
217
- ]);
218
- // Executes: SELECT * FROM users WHERE 1 = 1
219
- ```
220
-
221
- ### Combining Multiple Conditions (AND / OR)
222
-
223
- Interleave condition objects with string elements representing logical operators:
224
-
225
- ```javascript
226
- const filteredProducts = await productsHandler.select(
227
- [
228
- { category: 'electronics' },
229
- 'AND',
230
- { price: 500, operator: '>' },
231
- 'AND',
232
- { brand: ['Sony', 'LG'] } // Automatically mapped to IN
233
- ],
234
- {
235
- 'ORDERBY': 'price',
236
- 'DESC': true,
237
- 'LIMIT': 20
238
- }
239
- );
240
- // Executes:
241
- // SELECT * FROM products WHERE `category` = ? AND `price` > ? AND `brand` IN (?, ?) ORDER BY price DESC LIMIT 20
242
- ```
243
-
244
- ---
245
-
246
- ## CRUD Operations
247
-
248
- ### Inserting Records (`insert`)
249
-
250
- Adds a new row to the associated table using key-value properties.
251
-
252
- ```javascript
253
- const result = await usersHandler.insert({
254
- name: 'John Doe',
255
- email: 'john.doe@example.com',
256
- role: 'member',
257
- created_at: new Date()
258
- });
259
-
260
- console.log('Inserted ID:', result.insertId);
261
- ```
262
-
263
- ### Bulk Insert (`insertMany`)
264
-
265
- Insere múltiplos registros em uma única instrução SQL (`INSERT INTO table (...) VALUES ?`), oferecendo máxima performance para cargas em lote. O método aplica sanitização de schema (`autoStripUnknown`), preenche timestamps automáticos (`criado_em` / `atualizado_em`) e dispara os hooks de ciclo de vida (`beforeInsert` / `afterInsert`) para cada registro:
266
-
267
- ```javascript
268
- const novosUsuarios = [
269
- { name: 'Alice Silva', email: 'alice@empresa.com', role: 'developer' },
270
- { name: 'Bob Souza', email: 'bob@empresa.com', role: 'designer' },
271
- { name: 'Carlos Lima', email: 'carlos@empresa.com', role: 'manager' }
272
- ];
273
-
274
- const result = await usersHandler.insertMany(novosUsuarios);
275
- console.log('Linhas inseridas:', result.affectedRows);
276
- ```
277
-
278
- ### Upsert with Smart Timestamps (`upsert`)
279
-
280
- Executa uma operação atômica de inserção ou atualização (`INSERT INTO ... ON DUPLICATE KEY UPDATE`). Se o registro for novo, ele é inserido com os timestamps de criação e atualização. Se a chave primária ou índice único já existir, apenas os campos selecionados são atualizados, **preservando intacta a data de criação original (`criado_em` / `createdAt`)**:
281
-
282
- ```javascript
283
- // Exemplo: Insere o produto ou atualiza apenas preco e estoque se codigo_barras já existir
284
- const result = await produtosHandler.upsert({
285
- codigo_barras: '7891234567890',
286
- nome: 'Mouse sem Fio',
287
- preco: 149.90,
288
- estoque: 80
289
- }, ['preco', 'estoque']); // 2º argumento opcional: colunas a atualizar no conflito
290
-
291
- // Se omitir o 2º argumento, atualiza todos os campos fornecidos exceto criado_em:
292
- await produtosHandler.upsert({
293
- codigo_barras: '7891234567890',
294
- nome: 'Mouse sem Fio Pro',
295
- preco: 179.90
296
- });
297
- ```
298
-
299
- ### Updating Records (`update`)
300
-
301
- Performs selective updates by specifying both a `set` payload and a `where` filter. The `where` filter supports both standard flat objects (where conditions are implicitly joined by `AND` using `=` or `REGEXP`) and complex array configurations (with operators, `AND`, and `OR`), sharing the same advanced querying capabilities as the `select` method.
302
-
303
- #### 1. Simple Object Syntax (Implicit AND, = operator)
304
-
305
- ```javascript
306
- const result = await usersHandler.update({
307
- set: {
308
- status: 'suspended',
309
- notes: 'Violated terms of service'
310
- },
311
- where: {
312
- id: 42,
313
- status: 'active'
314
- }
315
- });
316
-
317
- console.log('Affected rows:', result.affectedRows);
318
- // Executes: UPDATE users SET `status` = ?, `notes` = ? WHERE `id` = ? AND `status` = ?
319
- ```
320
-
321
- #### 2. Advanced Array Syntax (with operators, AND/OR, and IN)
322
-
323
- You can pass an array of condition objects interleaved with `AND` or `OR` string elements to construct complex queries:
324
-
325
- ```javascript
326
- // Example updating records based on numeric thresholds and logical operators
327
- const result = await usersHandler.update({
328
- set: {
329
- status: 'inactive'
330
- },
331
- where: [
332
- { age: 18, operator: '<' },
333
- 'AND',
334
- { status: 'active' }
335
- ]
336
- });
337
- // Executes: UPDATE users SET `status` = ? WHERE `age` < ? AND `status` = ?
338
-
339
- // Example updating records using automatic IN operator detection
340
- const result = await usersHandler.update({
341
- set: {
342
- role: 'archived'
343
- },
344
- where: [
345
- { id: [10, 20, 30] } // Automatically builds: WHERE `id` IN (?, ?, ?)
346
- ]
347
- });
348
- // Executes: UPDATE users SET `role` = ? WHERE `id` IN (?, ?, ?)
349
-
350
- // Example combining complex logic (AND/OR)
351
- const result = await usersHandler.update({
352
- set: {
353
- category: 'Premium'
354
- },
355
- where: [
356
- { total_purchases: 1000, operator: '>' },
357
- 'AND',
358
- { status: 'active' },
359
- 'OR',
360
- { is_vip: 1 }
361
- ]
362
- });
363
- // Executes: UPDATE users SET `category` = ? WHERE `total_purchases` > ? AND `status` = ? OR `is_vip` = ?
364
- ```
365
-
366
- ### Deleting Records (`delete`)
367
-
368
- Deletes rows matching the conditions object (joined by implicit `AND` operators).
369
-
370
- ```javascript
371
- const result = await usersHandler.delete({
372
- status: 'temporary',
373
- is_expired: 1
374
- });
375
-
376
- console.log('Deleted rows:', result.affectedRows);
377
- ```
378
-
379
- ### Fluent Mutations (`.where().update()` / `.delete()`)
380
-
381
- Você pode encadear as mutações de escrita diretamente a partir do Query Builder Fluente, garantindo expressividade e legibilidade de alto nível:
382
-
383
- ```javascript
384
- // Soft Delete (ou hard delete) diretamente com filtros encadeados:
385
- await pedidosHandler
386
- .where('status', 'CANCELADO')
387
- .where('criado_em', '<', dataLimite)
388
- .delete();
389
-
390
- // Update com filtros fluentes encadeados:
391
- await clientesHandler
392
- .where('id', 10)
393
- .update({
394
- set: { status: 'ATIVO', tentativas_login: 0 }
395
- });
396
-
397
- // Restauração de itens da lixeira via Query Builder:
398
- await produtosHandler
399
- .where('categoria_id', 5)
400
- .restore();
401
-
402
- // Exclusão física definitiva (Hard Delete) via Query Builder:
403
- await logsHandler
404
- .where('criado_em', '<', dataExpiracao)
405
- .forceDelete();
406
- ```
407
-
408
- ---
409
-
410
- ## jQuery DataTables Server-Side Support (`selectToDatatable`)
411
-
412
- The `selectToDatatable` method provides seamless, enterprise-grade, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It eliminates manual SQL pagination boilerplate, automatically handling pagination, search (global and column-specific), multi-column ordering, regex filters, dual-count latency optimizations, backend security constraints, Soft Deletes, and sensitive field masking.
413
-
414
- ---
415
-
416
- ### Step-by-Step Execution Lifecycle (Under the Hood)
417
-
418
- Whenever `selectToDatatable(rawDtQuery, strictCondition)` is invoked, it executes the following optimized workflow:
419
-
420
- ```
421
- [Incoming Request] (req.body or req.query)
422
- │
423
- ▼
424
- 1. Hydration & Security Filter
425
- • Flattens or parses bracketed keys (e.g. columns[0][data] -> { columns: [{ data: ... }] })
426
- • Prototype Pollution Guard: Sanitizes __proto__, constructor, and prototype (CWE-1321)
427
- • Sanitizes integers (draw, start, length) preventing NaN injections
428
- │
429
- ▼
430
- 2. Backend Security & Tenant Scoping (strictCondition)
431
- • Injects non-bypassable backend filters (tenant_id, account_id, branch, etc.)
432
- • [v2.0.0] Injects Soft Delete filter (deletado_em IS NULL) automatically unless withTrashed() is active
433
- │
434
- ▼
435
- 3. Search Clause Generation
436
- • Global Search (search.value): Checks all columns where searchable == true -> (col1 LIKE ? OR col2 LIKE ?)
437
- • Column-Specific Search (columns[i].search.value): Checks individual columns -> AND colN LIKE ?
438
- • Regex Toggle: If regex == true, switches operator from LIKE %term% to REGEXP term
439
- • Parameterized bindings: All terms use prepared statement placeholders (?) to block SQL injection
440
- │
441
- ▼
442
- 4. Dual-COUNT Latency Optimization
443
- • No Active Search Filter: Only 1 COUNT(*) query is executed. recordsFiltered is instantly set to recordsTotal (up to 50% database I/O reduction).
444
- • Active Search Filter: Executes total COUNT(*) and filtered COUNT(*) concurrently via Promise.all().
445
- │
446
- ▼
447
- 5. Short-Circuit Check
448
- • If recordsFiltered === 0: The data SELECT query is skipped entirely. Returns data: [] immediately, avoiding expensive filesort and buffer allocations.
449
- │
450
- ▼
451
- 6. Multi-Column Ordering & Keyset Limitation
452
- • Parses all order directives (order[0], order[1], etc.)
453
- • Maps column index to sanitized column name (e.g. `col1` ASC, `col2` DESC)
454
- • Generates LIMIT start, length safely
455
- │
456
- ▼
457
- 7. Data Retrieval & Sensitive Field Masking
458
- • Executes SELECT <columns> FROM <table> [JOINS] [WHERE] [ORDER BY] [LIMIT]
459
- • [v2.0.0] Strips any fields declared in hiddenFields (e.g. senha_hash, token) before output
460
- │
461
- ▼
462
- [Standard JSON Response to DataTables]
463
- ```
464
-
465
- ---
466
-
467
- ### Key Features & Performance Optimizations
468
-
469
- * **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state during initial page load, sorting, and standard 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%**.
470
- * **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.
471
- * **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]`).
472
- * **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`.
473
- * **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.
474
- * **Prototype Pollution Protection (CWE-1321):** Deeply sanitizes incoming request keys, blocking injections targeting `__proto__`, `constructor`, or `prototype`.
475
- * **[v2.0.0] Soft Delete & Hidden Fields Aware:** Automatically excludes soft-deleted records (`deletado_em IS NULL`) and strips sensitive columns (`hiddenFields`) from the returned JSON.
476
-
477
- ---
478
-
479
- ### Method Signature
480
-
481
- ```javascript
482
- await handler.selectToDatatable(rawDtQuery, strictCondition = [])
483
- ```
484
-
485
- #### Parameters
486
-
487
- | Parameter | Type | Required | Description |
488
- | :--- | :--- | :---: | :--- |
489
- | `rawDtQuery` | `Object` | **Yes** | The request payload sent by jQuery DataTables (`req.body` in POST or `req.query` in GET). Supports both bracket-flattened keys and nested JSON. |
490
- | `strictCondition` | `Array` \| `Object` | No | Backend constraints that the client cannot view or modify (e.g. multi-tenant isolation, user scoping, active-only filters). |
491
-
492
- #### DataTables Payload Schema (`rawDtQuery`)
493
-
494
- | Field | Type | Description |
495
- | :--- | :--- | :--- |
496
- | `draw` | `number` \| `string` | Draw counter echoed back to the client to ensure response synchronization. |
497
- | `start` | `number` \| `string` | Zero-based paging first record indicator (`OFFSET`). Defaults to `0`. |
498
- | `length` | `number` \| `string` | Number of records to return (`LIMIT`). |
499
- | `search.value` | `string` | Global search value applied across all columns with `searchable: true`. |
500
- | `search.regex` | `boolean` \| `string` | If `true` or `'true'`, uses MySQL `REGEXP` instead of `LIKE %value%`. |
501
- | `order` | `Array<Object>` | Array of order objects: `{ column: 0, dir: 'asc' \| 'desc' }`. |
502
- | `columns` | `Array<Object>` | Array of column definitions: `{ data: 'col_name', searchable: true, orderable: true, search: { value: '', regex: false } }`. |
503
-
504
- ---
505
-
506
- ### Basic Express.js Example
507
-
508
- ```javascript
509
- const express = require('express');
510
- const { db, usersHandler } = require('./databaseController');
511
-
512
- const app = express();
513
- app.use(express.json());
514
- app.use(express.urlencoded({ extended: true }));
515
-
516
- app.post('/api/users/datatable', async (req, res) => {
517
- // req.body contains: { draw, start, length, search, order, columns }
518
- const result = await usersHandler.selectToDatatable(req.body);
519
- res.json(result);
520
- });
521
- ```
522
-
523
- ---
524
-
525
- ### Enforcing Backend Security (`strictCondition`)
526
-
527
- Never rely on the client frontend to enforce data 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:
528
-
529
- ```javascript
530
- app.post('/api/orders/datatable', async (req, res) => {
531
- // Client-side parameters cannot bypass these conditions:
532
- const strictConditions = [
533
- { tenant_id: req.user.tenantId },
534
- 'AND',
535
- { status: 'deleted', operator: '!=' },
536
- 'AND',
537
- { store_id: [101, 102, 105] } // Automatically mapped to: `store_id` IN (?, ?, ?)
538
- ];
539
-
540
- const result = await ordersHandler.selectToDatatable(req.body, strictConditions);
541
- res.json(result);
542
- });
543
- ```
544
-
545
- > [!IMPORTANT]
546
- > **Regra Obrigatória para Múltiplas Condições em `strictCondition`:**
547
- > Sempre forneça `strictCondition` no formato de **Array de Objetos** com conectivos explícitos (`'AND'` / `'OR'`). Se for passado um objeto único contendo múltiplas propriedades (como `{ tenant_id: 1, status: 'active' }`), o parser interno processará **apenas a primeira chave** e descartará as demais silenciosamente:
548
- > ```javascript
549
- > // Correto:
550
- > strictCondition: [
551
- > { 'pedidos.empresa_id': req.user.empresaId },
552
- > 'AND',
553
- > { 'pedidos.ativo': 1 }
554
- > ]
555
- > ```
556
-
557
- ---
558
-
559
- ### Using JOINs with DataTables
560
-
561
- #### Option A: Modern Fluent Query Builder Joins (Recommended in v2.0.0)
562
- Chain `.selectFields()` and `.leftJoin()` / `.join()` directly with `.selectToDatatable()`:
563
-
564
- ```javascript
565
- app.post('/api/pedidos/datatable', async (req, res) => {
566
- const result = await pedidosHandler
567
- .selectFields([
568
- 'pedidos.id',
569
- 'pedidos.valor',
570
- 'pedidos.criado_em',
571
- { column: 'c.nome', as: 'cliente_nome' },
572
- { column: 'v.nome', as: 'vendedor_nome' }
573
- ])
574
- .leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
575
- .leftJoin('vendedores v', 'pedidos.vendedor_id', '=', 'v.id')
576
- .selectToDatatable(req.body, [
577
- { 'pedidos.empresa_id': req.user.empresaId }
578
- ]);
579
-
580
- res.json(result);
581
- });
582
- ```
583
-
584
- #### Option B: Legacy Expression Parameter
585
- You can also initialize the handler with a SQL expression containing the JOINs and selected columns:
586
-
587
- ```javascript
588
- // Table: 'sales s'
589
- // Expression: JOIN with customers and users, selecting extra fields
590
- const salesHandler = new DataBaseHandler(
591
- db,
592
- 'customers_sales s',
593
- ', c.name AS customer_name, u.name AS user_name ' +
594
- 'LEFT JOIN customers c ON c.id = s.customer ' +
595
- 'LEFT JOIN users u ON u.id = s.user'
596
- );
597
-
598
- app.post('/api/sales/datatable', async (req, res) => {
599
- // DataTables columns can search and sort by qualified identifiers (e.g. 'c.name')
600
- const result = await salesHandler.selectToDatatable(req.body, [
601
- { 's.deleted_at': null, operator: 'IS' }
602
- ]);
603
- res.json(result);
604
- });
605
- ```
606
-
607
- ---
608
-
609
- ### Soft Deletes & Sensitive Fields in DataTables (v2.0.0)
610
-
611
- When configuring business rules on the handler, `selectToDatatable` automatically complies without requiring manual filters:
612
-
613
- ```javascript
614
- const clientesHandler = new DataBaseHandler(db, 'clientes', {
615
- softDelete: 'deletado_em', // Injeta 'AND deletado_em IS NULL' automaticamente
616
- hiddenFields: ['senha_hash', 'token_recuperacao'] // Remove do retorno mesmo se 'SELECT *' for usado
617
- });
618
-
619
- // A consulta abaixo já ignora excluídos e nunca expõe senha_hash
620
- app.post('/api/clientes/datatable', async (req, res) => {
621
- const result = await clientesHandler.selectToDatatable(req.body);
622
- res.json(result);
623
- });
624
-
625
- // Para consultar registos da lixeira (soft-deleted):
626
- app.post('/api/clientes/trash/datatable', async (req, res) => {
627
- const result = await clientesHandler.onlyTrashed().selectToDatatable(req.body);
628
- res.json(result);
629
- });
630
- ```
631
-
632
- ---
633
-
634
- ### Frontend jQuery DataTables Setup
635
-
636
- Configure your frontend DataTables instance with `serverSide: true`:
637
-
638
- ```javascript
639
- $('#usersTable').DataTable({
640
- processing: true,
641
- serverSide: true,
642
- ajax: {
643
- url: '/api/users/datatable',
644
- type: 'POST',
645
- contentType: 'application/json',
646
- data: function (d) {
647
- return JSON.stringify(d);
648
- }
649
- },
650
- columns: [
651
- { data: 'id', name: 'id' },
652
- { data: 'name', name: 'name' },
653
- { data: 'email', name: 'email' },
654
- { data: 'role', name: 'role' },
655
- {
656
- data: null,
657
- orderable: false,
658
- searchable: false,
659
- render: function (data, type, row) {
660
- return `<button onclick="editUser(${row.id})">Edit</button>`;
661
- }
662
- }
663
- ],
664
- order: [[0, 'desc']]
665
- });
666
- ```
667
-
668
- ---
669
-
670
- ### Response Structure & Error Handling
671
-
672
- The method always returns the standard JSON response expected by DataTables:
673
-
674
- #### Success Response
675
- ```json
676
- {
677
- "draw": 1,
678
- "recordsTotal": 1250,
679
- "recordsFiltered": 45,
680
- "data": [
681
- { "id": 42, "name": "John Doe", "email": "john@example.com", "role": "admin" },
682
- { "id": 43, "name": "Jane Smith", "email": "jane@example.com", "role": "editor" }
683
- ]
684
- }
685
- ```
686
-
687
- #### Safe Error Handling
688
- 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:
689
-
690
- ```json
691
- {
692
- "draw": 1,
693
- "recordsTotal": 0,
694
- "recordsFiltered": 0,
695
- "data": [],
696
- "error": "ER_NO_SUCH_TABLE: Table 'my_app_db.invalid_table' doesn't exist"
697
- }
698
- ```
699
-
700
-
701
- ---
702
-
703
- ## Transaction Support (ACID & Transparent)
704
-
705
- The library provides first-class transaction support built on top of Node.js native `AsyncLocalStorage`. Transactions can be used explicitly or completely transparently across shared Singletons without manual connection passing.
706
-
707
- ### 1. Explicit Block (`db.transaction`)
708
-
709
- Wrap operations in `db.transaction(callback)`. If the callback resolves, `COMMIT` is executed automatically. If an error is thrown or unhandled, `ROLLBACK` is performed automatically and the connection is safely released back to the pool.
710
-
711
- ```javascript
712
- await db.transaction(async () => {
713
- await usersHandler.insert({ name: 'Alice', balance: 500 });
714
- await auditHandler.insert({ action: 'USER_CREATED', user: 'Alice' });
715
- // If any error occurs, all operations in this block are rolled back!
716
- });
717
- ```
718
-
719
- ### 2. Singleton Compatibility with `AsyncLocalStorage`
720
-
721
- When running inside `db.transaction()`, **you do not need to pass transaction instances to your handlers**. Globally shared table handlers (Singletons) automatically bind to the active transaction of the current asynchronous execution context:
722
-
723
- ```javascript
724
- // databaseController.js - Exporting global singletons
725
- const db = require('./db-singleton');
726
- const { DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
727
-
728
- const customersSales = new DataBaseHandler(db, 'customers_sales');
729
- const customersProducts = new DataBaseHandler(db, 'customers_products');
730
-
731
- module.exports = { db, customersSales, customersProducts };
732
- ```
733
-
734
- ```javascript
735
- // salesRouter.js - In your route handler
736
- const { db, customersSales, customersProducts } = require('./databaseController');
737
-
738
- router.post('/sales', async (req, res) => {
739
- try {
740
- let saleResult;
741
- await db.transaction(async () => {
742
- saleResult = await customersSales.insert(req.body.sale);
743
-
744
- // Check stock and update
745
- const product = (await customersProducts.select([{ id: req.body.productId }]))[0];
746
- if (!product || product.stock < req.body.amount) {
747
- // Throwing an error here triggers automatic ROLLBACK for both tables!
748
- throw new Error('Insufficient product stock');
749
- }
750
-
751
- await customersProducts.update({
752
- set: { stock: product.stock - req.body.amount },
753
- where: { id: req.body.productId }
754
- });
755
- });
756
-
757
- res.json(saleResult);
758
- } catch (err) {
759
- res.status(500).json({ error: err.message });
760
- }
761
- });
762
- ```
763
-
764
- ### 3. Post-Commit Hook (`db.onCommit`)
765
-
766
- When integrating with external third-party APIs (e.g., banking APIs, payment gateways, invoice generators, SMS, emails), **never perform slow external network calls while holding database locks**.
767
-
768
- `db.onCommit(callback)` queues actions that will run **only after the database transaction successfully commits**:
769
-
770
- ```javascript
771
- await db.transaction(async () => {
772
- const sale = await customersSales.insert(payload);
773
-
774
- // Schedule bank invoice creation: only runs if DB transaction commits!
775
- db.onCommit(async () => {
776
- await bankApiClient.registerInvoice(sale.insertId, invoiceData);
777
- });
778
- });
779
- ```
780
-
781
- ### 4. Route Wrapper (`db.transactional`)
782
-
783
- Easily wrap asynchronous route handlers or service functions to run within a transaction without nesting `try/catch` or `db.transaction` boilerplate:
784
-
785
- ```javascript
786
- router.post('/orders', db.transactional(async (req, res) => {
787
- const order = await ordersHandler.insert(req.body);
788
- await itemsHandler.insert({ orderId: order.insertId, items: req.body.items });
789
- res.json(order);
790
- }));
791
- ```
792
-
793
- ### 5. Express Lazy Middleware (`db.autoTransaction`)
794
-
795
- For maximum transparency with **zero lines changed** in your route handlers, enable the `autoTransaction` middleware in your Express app:
796
-
797
- ```javascript
798
- // server.js / app.js
799
- app.use(db.autoTransaction({
800
- methods: ['POST', 'PUT', 'DELETE', 'PATCH'], // HTTP methods to protect
801
- lazy: true // Only opens a transaction when a write operation occurs
802
- }));
803
- ```
804
-
805
- * **Lazy Allocation:** `GET` requests or routes that only execute `select` queries will not open a transaction or hold connections.
806
- * **On-Demand Write:** As soon as an `insert`, `update`, or `delete` is called on any handler during the request, a dedicated transaction starts automatically.
807
- * **Automatic Completion:** When `res.send()` or `res.json()` completes with HTTP status `< 400`, the transaction automatically commits. If status is `>= 400` or an exception is thrown, it rolls back automatically.
808
-
809
- ### 6. Nested Transactions & Savepoints
810
-
811
- The library natively supports nested transactions using MySQL `SAVEPOINT`s. Calling `db.transaction()` inside an existing transaction creates a savepoint instead of a new connection:
812
-
813
- ```javascript
814
- await db.transaction(async () => {
815
- await mainHandler.insert({ status: 'started' });
816
-
817
- try {
818
- // Nested block runs under a SAVEPOINT
819
- await db.transaction(async () => {
820
- await subHandler.insert({ data: 'optional_task' });
821
- throw new Error('Non-critical sub-task failed');
822
- });
823
- } catch (e) {
824
- // Sub-task is rolled back to SAVEPOINT, but the main transaction can still commit!
825
- console.warn('Sub-task skipped:', e.message);
826
- }
827
-
828
- await mainHandler.insert({ status: 'completed' });
829
- });
830
- ```
831
-
832
- ---
833
-
834
- ## Database Singleton Pattern
835
-
836
- To prevent initializing redundant pool connections across various modules in a Node.js project, it is highly recommended to configure a single shared instance (Singleton).
837
-
838
- Create a `db.js` file:
839
- ```javascript
840
- // db.js
841
- const { DataBase } = require('@areumtecnologia/mysql-db-handler');
842
-
843
- const dbInstance = new DataBase({
844
- host: process.env.DB_HOST || 'localhost',
845
- user: process.env.DB_USER || 'root',
846
- password: process.env.DB_PASSWORD,
847
- database: process.env.DB_NAME,
848
- connectionLimit: parseInt(process.env.DB_POOL_LIMIT) || 10
849
- });
850
-
851
- module.exports = dbInstance;
852
- ```
853
-
854
- Import it in your business controllers/repositories:
855
- ```javascript
856
- // usersRepository.js
857
- const db = require('./db');
858
- const { DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
859
-
860
- const usersHandler = new DataBaseHandler(db, 'users');
861
-
862
- module.exports = {
863
- getUserById: (id) => usersHandler.selectBy({ id })
864
- };
865
- ```
866
-
867
- ---
868
-
869
- ## Error Handling Strategy
870
-
871
- Database exceptions generated during execution are caught internally by the `DataBase` instance. This means that instead of raising unhandled exceptions that could crash your Node.js application, the library wraps the error.
872
-
873
- Specifically, the following methods from **`DataBase`** and **`DataBaseHandler`** return an object with an `error` property when an execution error occurs:
874
- * `DataBase.query()`
875
- * `DataBaseHandler.select()` / `selectBy()`
876
- * `DataBaseHandler.insert()`
877
- * `DataBaseHandler.update()`
878
- * `DataBaseHandler.delete()`
879
- * `DataBaseHandler.selectToDatatable()`
880
-
881
- ### Example: Checking for errors in queries
882
-
883
- ```javascript
884
- // Example with Select if column doesn't exist (triggers database error)
885
- const users = await usersHandler.select([{ non_existent_column: 'admin' }]);
886
- if (users.error) {
887
- console.error('Failed to select users:', users.error.message);
888
- }
889
-
890
- // Example with Insert
891
- const insertResult = await usersHandler.insert({ name: 'John Doe' });
892
- if (insertResult.error) {
893
- console.error('Failed to insert user:', insertResult.error.message);
894
- }
895
-
896
- // Example with Update
897
- const updateResult = await usersHandler.update({
898
- set: { status: 'active' },
899
- where: { id: 999 }
900
- });
901
- if (updateResult.error) {
902
- console.error('Failed to update user:', updateResult.error.message);
903
- }
904
-
905
- // Example with Delete
906
- const deleteResult = await usersHandler.delete({ id: 999 });
907
- if (deleteResult.error) {
908
- console.error('Failed to delete user:', deleteResult.error.message);
909
- }
910
- ```
911
-
912
- > [!NOTE]
913
- > If you execute a `select` using valid columns but search for values that do not exist in the table (e.g. `await usersHandler.select([{ role: 'non_existent_role' }])`), this is **not** considered a database error. The query will execute successfully and return an empty array `[]` (without any `error` property). An error is only returned for actual database execution failures (such as syntax errors, missing columns, database connection drops, etc.).
914
-
915
- ---
916
-
917
- ## High-Scale Enterprise Micro-ORM (v2.0.0)
918
-
919
- With **v2.0.0**, `@areumtecnologia/mysql-db-handler` evolves from a single-table CRUD helper into a full-fledged enterprise Data Mapper and Micro-ORM designed for high-throughput, mission-critical systems.
920
-
921
- ### 1. Fluent Query Builder & Aggregations (`.first`, `.count`, `.paginate`, `raw`)
922
-
923
- O Query Builder Fluente oferece encadeamento imutável, tipagem limpa e sanitização de identificadores para construir consultas SQL expressivas sem strings manuais vulneráveis:
924
-
925
- #### Obter um Único Registro (`.first()`)
926
- Executa `LIMIT 1` e já desempacota o primeiro objeto ou retorna `null` caso nenhum registro atenda aos critérios:
927
- ```javascript
928
- const usuario = await usuariosHandler
929
- .where('email', 'admin@empresa.com')
930
- .first();
931
-
932
- if (!usuario) {
933
- console.log('Usuário não encontrado');
934
- }
935
- ```
936
-
937
- #### Contagem Direta de Registros (`.count()`)
938
- Retorna diretamente o valor numérico de linhas encontradas:
939
- ```javascript
940
- const totalAtivos = await usuariosHandler
941
- .where('status', 'ATIVO')
942
- .count(); // Retorna: 42
943
- ```
944
-
945
- #### Expressões SQL Brutas Seguras (`raw`)
946
- Utilize a função `raw` para incorporar cálculos e funções do MySQL em `selectFields`:
947
- ```javascript
948
- const { raw } = require('@areumtecnologia/mysql-db-handler');
949
-
950
- const resumo = await pedidosHandler
951
- .selectFields([
952
- 'status',
953
- raw('COUNT(*) AS total_pedidos'),
954
- raw('SUM(valor) AS montante_total'),
955
- raw('AVG(valor) AS ticket_medio')
956
- ])
957
- .where('criado_em', '>=', '2026-01-01')
958
- .groupBy('status')
959
- .having('montante_total > ?', [10000])
960
- .orderBy('montante_total', 'DESC')
961
- .get();
962
- ```
963
-
964
- #### Paginação Tradicional com Metadados (`.paginate()`)
965
- Para telas administrativas convencionais com barra de navegação paginada (Página 1 de 10):
966
- ```javascript
967
- const resultado = await pedidosHandler.paginate({
968
- page: 2,
969
- limit: 15,
970
- where: [{ status: 'PAGO' }],
971
- orderBy: 'id DESC'
972
- });
973
-
974
- // resultado:
975
- // {
976
- // data: [...], // Array de 15 pedidos da página 2
977
- // total: 150, // Total de pedidos no banco
978
- // page: 2, // Página atual
979
- // limit: 15, // Limite por página
980
- // totalPages: 10 // Total de páginas disponíveis
981
- // }
982
- ```
983
-
984
- > [!TIP]
985
- > **Quando usar `paginate` vs `cursorPaginate`:**
986
- > * Use `.paginate()` para telas administrativas com paginação numerada tradicional em tabelas pequenas e médias (< 100.000 linhas).
987
- > * Use `.cursorPaginate()` (Keyset Pagination) para feeds infinitos, exportações e tabelas de alta escala com milhões de linhas, onde o custo de `OFFSET` seria proibitivo.
988
-
989
- ---
990
-
991
- ### 2. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)
992
-
993
- #### Fluent Joins with Automatic Identifier Sanitization
994
- Chain `.join()`, `.leftJoin()`, `.rightJoin()`, or `.innerJoin()` directly on the query builder with support for table aliases:
995
-
996
- ```javascript
997
- const pedidos = await pedidosHandler
998
- .selectFields(['pedidos.id', 'pedidos.valor', { column: 'c.nome', as: 'cliente_nome' }])
999
- .leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
1000
- .where('pedidos.status', 'PAGO')
1001
- .get();
1002
- ```
1003
-
1004
- #### Eager Loading (`.with()`)
1005
- Prevent the dreaded N+1 query problem without creating massive, memory-heavy Cartesian joins in MySQL. Child entities are loaded in a single batched `WHERE foreign_key IN (...)` query and hydrated directly onto parents in memory:
1006
-
1007
- ```javascript
1008
- const pedidosComItens = await pedidosHandler
1009
- .where('status', 'PAGO')
1010
- .with('itens', {
1011
- type: 'hasMany',
1012
- handler: itensHandler,
1013
- foreignKey: 'pedido_id',
1014
- localKey: 'id',
1015
- query: (qb) => qb.where('ativo', 1).orderBy('sequencia', 'ASC') // Filtro e ordenação customizados
1016
- })
1017
- .with('cliente', DataBaseHandler.belongsTo(clientesHandler, 'cliente_id', 'id'))
1018
- .get();
1019
-
1020
- // pedidosComItens[0].itens -> Array de itens ativos do pedido 1
1021
- // pedidosComItens[0].cliente -> Objeto do cliente associado
1022
- ```
1023
-
1024
- ---
1025
-
1026
- ### 3. Read/Write Splitting (Master + Read Replicas)
1027
-
1028
- Scale read traffic horizontally across multiple cloud replicas (e.g. AWS Aurora, GCP Cloud SQL, Azure Database for MySQL) with automatic Round-Robin load balancing and strict transactional sticky sessions:
1029
-
1030
- ```javascript
1031
- const db = new DataBase({
1032
- host: 'primary-master.internal', // Pool de Escrita (Master)
1033
- user: 'app_user',
1034
- password: 'secret_password',
1035
- database: 'meu_banco',
1036
- replicas: [
1037
- { host: 'read-replica-1.internal' },
1038
- { host: 'read-replica-2.internal' }
1039
- ]
1040
- });
1041
-
1042
- // Queries simples de leitura são distribuídas via Round-Robin nas réplicas
1043
- const users = await db.query('SELECT * FROM users WHERE status = ?', ['active']);
1044
-
1045
- // Operações de mutação (INSERT, UPDATE, DELETE) vão obrigatoriamente para o Master
1046
- await db.query('INSERT INTO users SET ?', [{ name: 'Novo Usuário' }], true);
1047
-
1048
- // Dentro de transações, TODAS as leituras e escritas utilizam a conexão Master (evitando replication lag)
1049
- await db.transaction(async () => {
1050
- const user = await db.query('SELECT saldo FROM contas WHERE id = ?', [1]);
1051
- await db.query('UPDATE contas SET saldo = saldo - 50 WHERE id = ?', [1], true);
1052
- });
1053
- ```
1054
-
1055
- > [!WARNING]
1056
- > **Atenção em Queries SQL Manuais (`db.query`):**
1057
- > Ao executar mutações brutas sem o `DataBaseHandler` (`INSERT`, `UPDATE`, `DELETE`), o 3º argumento booleano `isWrite = true` é **obrigatório**:
1058
- > ```javascript
1059
- > // Se omitir o 3º argumento, um INSERT manual pode cair em uma réplica read-only!
1060
- > await db.query('INSERT INTO logs SET ?', [data], true);
1061
- > ```
1062
- > No `DataBaseHandler`, todas as operações de escrita (`insert`, `insertMany`, `upsert`, `update`, `delete`) já encaminham automaticamente para o Master (`isWrite = true`).
1063
-
1064
- ---
1065
-
1066
- ### 4. Keyset Pagination & Memory-Safe Streaming
1067
-
1068
- #### Keyset / Cursor Pagination (`.cursorPaginate()`)
1069
- Traditional `OFFSET` pagination degrades significantly on large tables because MySQL must scan and discard all rows before the offset. Keyset pagination uses constant-time index seeks (`WHERE id > ? ORDER BY id ASC LIMIT ?`):
1070
-
1071
- ```javascript
1072
- // Primeira página
1073
- const page1 = await produtosHandler.cursorPaginate({ limit: 20 });
1074
- // page1: { data: [...], nextCursor: 20, prevCursor: 1, hasMore: true, limit: 20 }
1075
-
1076
- // Próxima página (tempo constante de 1ms, mesmo após 500.000 registos)
1077
- const page2 = await produtosHandler.cursorPaginate({
1078
- limit: 20,
1079
- after: page1.nextCursor
1080
- });
1081
- ```
1082
-
1083
- > [!TIP]
1084
- > **Customização da Chave Primária (`cursorColumn`):**
1085
- > O método `.cursorPaginate()` assume por padrão a coluna `'id'`. Se a tabela utilizar outra chave de ordenação ou chave primária (`uuid`, `codigo`, `cod_produto`), declare-a explicitamente:
1086
- > ```javascript
1087
- > const page = await produtosHandler.cursorPaginate({
1088
- > cursorColumn: 'codigo',
1089
- > limit: 20,
1090
- > after: lastCode
1091
- > });
1092
- > ```
1093
-
1094
- #### Streaming & Async Iterator (`for await ... of`)
1095
- Export millions of rows to CSV or feed an ETL pipeline without triggering Node.js Heap Out of Memory errors:
1096
-
1097
- ```javascript
1098
- // Iteração sob demanda com consumo constante de memória (< 30 MB)
1099
- for await (const row of relatorioHandler.cursor({ batchSize: 1000 })) {
1100
- processRow(row);
1101
- }
1102
-
1103
- // Node.js Readable Stream nativo para pipes HTTP ou arquivos
1104
- relatorioHandler.stream({ batchSize: 500 })
1105
- .pipe(csvTransformStream)
1106
- .pipe(res);
1107
- ```
1108
-
1109
- ---
1110
-
1111
- ### 5. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks
1112
-
1113
- ```javascript
1114
- const clientesHandler = new DataBaseHandler(db, 'clientes', {
1115
- softDelete: 'deletado_em', // ou boolean true (padrão 'deletado_em')
1116
- timestamps: true // injeta criado_em e atualizado_em automaticamente
1117
- });
1118
- ```
1119
-
1120
- > [!TIP]
1121
- > **Tabelas com Nomenclatura em Inglês (`deleted_at`, `created_at`, `updated_at`):**
1122
- > Por padrão, a biblioteca assume as colunas em português (`deletado_em`, `criado_em`, `atualizado_em`). Se suas tabelas utilizam nomenclaturas em inglês, configure o objeto explicitamente:
1123
- > ```javascript
1124
- > const clientesHandler = new DataBaseHandler(db, 'customers_leads', {
1125
- > softDelete: 'deleted_at',
1126
- > timestamps: {
1127
- > createdAt: 'created_at',
1128
- > updatedAt: 'updated_at'
1129
- > }
1130
- > });
1131
- > ```
1132
-
1133
- #### Soft Deletes
1134
- * `.delete(where)`: Automaticamente executa `UPDATE clientes SET deletado_em = NOW() WHERE ...`.
1135
- * Consultas padrão (`select`, `get`, `first`, `paginate`, `selectToDatatable`) injetam automaticamente `AND deletado_em IS NULL`.
1136
- * `.withTrashed()`: Desativa o filtro para retornar registos ativos e deletados.
1137
- * `.onlyTrashed()`: Retorna exclusivamente registos na lixeira (`deletado_em IS NOT NULL`).
1138
- * `.restore(where)`: Restaura registos setando `deletado_em = NULL`.
1139
- * `.forceDelete(where)`: Executa `DELETE FROM` físico no MySQL.
1140
-
1141
- #### Lifecycle Hooks
1142
- Intercepte mutações antes ou depois de sua persistência:
1143
-
1144
- ```javascript
1145
- clientesHandler
1146
- .beforeInsert(async (data) => {
1147
- data.slug = slugify(data.nome);
1148
- })
1149
- .afterInsert(async (result, data) => {
1150
- await logAudit('CLIENT_CREATED', result.insertId);
1151
- })
1152
- .beforeUpdate(async (set, where) => {
1153
- validateBusinessRules(set);
1154
- })
1155
- .afterDelete(async (result, where) => {
1156
- await notifyService(where);
1157
- });
1158
- ```
1159
-
1160
- ---
1161
-
1162
- ### 6. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking
1163
-
1164
- ```javascript
1165
- const usuariosHandler = new DataBaseHandler(db, 'usuarios', {
1166
- autoStripUnknown: true, // Remove propriedades desconhecidas do payload
1167
- hiddenFields: ['senha_hash', 'token_recuperacao'] // Oculta campos confidenciais das consultas
1168
- });
1169
-
1170
- // Prevenção de Mass Assignment e ER_BAD_FIELD_ERROR vindo de requisições web:
1171
- await usuariosHandler.insert({
1172
- nome: 'Carlos',
1173
- email: 'carlos@empresa.com',
1174
- senha_hash: 'hash_seguro',
1175
- isAdminFake: true, // Ignorado silenciosamente pois não existe no schema
1176
- payload_sujo: 'qualquer_coisa' // Ignorado silenciosamente
1177
- });
1178
-
1179
- // Consultas nunca retornam senha_hash ou token_recuperacao acidentalmente:
1180
- const usuario = await usuariosHandler.where('id', 1).first();
1181
- console.log(usuario.senha_hash); // undefined
1182
- ```
1183
-
1184
- ---
1185
-
1186
- ## Contributing
1187
-
1188
- Contributions are welcome! Please open an issue or submit a pull request.
1189
-
1190
- 1. Fork the repository
1191
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
1192
- 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
1193
- 4. Push to the branch (`git push origin feature/amazing-feature`)
1194
- 5. Open a Pull Request
1195
-
1196
- ---
1197
-
1198
- ## License
1199
-
1200
- MIT
1
+ # @areumtecnologia/mysql-db-handler
2
+
3
+ A powerful, robust, and production-ready MySQL wrapper for Node.js. It features connection pooling, query caching (optional), jQuery DataTables server-side processing integration, safe error handling, and a flexible abstraction layer for CRUD operations.
4
+
5
+ ## Table of Contents
6
+
7
+ * [Features](#features)
8
+ * [Installation](#installation)
9
+ * [Core Classes](#core-classes)
10
+ * [DataBase (Standard Connection)](#1-database-standard-connection)
11
+ * [DataBase (With Query & Schema Caching)](#2-database-with-query--schema-caching)
12
+ * [DataBaseHandler (CRUD Abstraction)](#3-databasehandler-crud-abstraction)
13
+ * [Basic Usage](#basic-usage)
14
+ * [1. Initializing Connection](#1-initializing-connection)
15
+ * [2. Executing Raw SQL](#2-executing-raw-sql)
16
+ * [3. Using the DataBaseHandler](#3-using-the-databasehandler)
17
+ * [Categorized Static Enumerators (No Magic Strings)](#categorized-static-enumerators-no-magic-strings)
18
+ * [1. Arithmetic Operators (`ArithmeticOperator`)](#1-operadores-aritméticos-arithmeticoperator--operatorsarithmetic)
19
+ * [2. Comparison Operators (`ComparisonOperator`)](#2-operadores-de-comparação-relacionais-comparisonoperator--operatorscomparison)
20
+ * [3. Logical Operators (`LogicalOperator`)](#3-operadores-lógicos-logicaloperator--operatorslogical)
21
+ * [4. Bitwise Operators (`BitwiseOperator`)](#4-operadores-bit-a-bit-bitwiseoperator--operatorsbitwise)
22
+ * [Usage Examples](#practical-usage-examples)
23
+ * [Advanced Querying (`select` method)](#advanced-querying-select-method)
24
+ * [Basic Selection](#basic-selection)
25
+ * [Working with the `IN` and `NOT IN` Operators](#working-with-the-in-and-not-in-operators)
26
+ * [Automatic `IN` Detection](#automatic-in-detection)
27
+ * [Explicit `IN` / `NOT IN` Operator](#explicit-in--not-in-operator)
28
+ * [Empty Array Safety (`IN ()` Protection)](#empty-array-safety-in-protection)
29
+ * [Combining Multiple Conditions (AND / OR)](#combining-multiple-conditions-and--or)
30
+ * [CRUD Operations](#crud-operations)
31
+ * [Inserting Records (`insert`)](#inserting-records-insert)
32
+ * [Bulk Insert (`insertMany`)](#bulk-insert-insertmany)
33
+ * [Upsert with Smart Timestamps (`upsert`)](#upsert-with-smart-timestamps-upsert)
34
+ * [Updating Records (`update`)](#updating-records-update)
35
+ * [Deleting Records (`delete`)](#deleting-records-delete)
36
+ * [Fluent Mutations (`.where().update()` / `.delete()`)](#fluent-mutations-whereupdate--wheredelete)
37
+ * [jQuery DataTables Server-Side Support (`selectToDatatable`)](#jquery-datatables-server-side-support-selecttodatatable)
38
+ * [Key Features & Performance](#key-features--performance-optimizations)
39
+ * [Method Signature](#method-signature)
40
+ * [Basic Express.js Example](#basic-expressjs-example)
41
+ * [Enforcing Backend Security (`strictCondition`)](#enforcing-backend-security-strictcondition)
42
+ * [Using JOINs and Custom Expressions](#using-joins-and-custom-expressions)
43
+ * [Frontend jQuery DataTables Setup](#frontend-jquery-datatables-setup)
44
+ * [Response Structure & Error Handling](#response-structure--error-handling)
45
+ * [Transaction Support (ACID & Transparent)](#transaction-support-acid--transparent)
46
+ * [1. Explicit Block (`db.transaction`)](#1-explicit-block-dbtransaction)
47
+ * [2. Singleton Compatibility with `AsyncLocalStorage`](#2-singleton-compatibility-with-asynclocalstorage)
48
+ * [3. Post-Commit Hook (`db.onCommit`)](#3-post-commit-hook-dboncommit)
49
+ * [4. Route Wrapper (`db.transactional`)](#4-route-wrapper-dbtransactional)
50
+ * [5. Express Lazy Middleware (`db.autoTransaction`)](#5-express-lazy-middleware-dbautotransaction)
51
+ * [6. Nested Transactions & Savepoints](#6-nested-transactions--savepoints)
52
+ * [Database Singleton Pattern](#database-singleton-pattern)
53
+ * [Error Handling Strategy](#error-handling-strategy)
54
+ * [High-Scale Enterprise Micro-ORM (v2.0.0)](#high-scale-enterprise-micro-orm-v200)
55
+ * [1. Fluent Query Builder & Aggregations (`.first`, `.count`, `.paginate`, `raw`)](#1-fluent-query-builder--aggregations-first-count-paginate-raw)
56
+ * [2. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)](#2-fluent-joins--eager-loading-eliminating-the-n1-problem)
57
+ * [3. Read/Write Splitting (Master + Read Replicas)](#3-readwrite-splitting-master--read-replicas)
58
+ * [4. Keyset Pagination & Memory-Safe Streaming](#4-keyset-pagination--memory-safe-streaming)
59
+ * [5. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks](#5-native-business-rules-soft-deletes-timestamps--lifecycle-hooks)
60
+ * [6. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking](#6-runtime-schema-validation-auto-strip--sensitive-field-masking)
61
+ * [Contributing](#contributing)
62
+ * [License](#license)
63
+
64
+ ---
65
+
66
+ ## Features
67
+
68
+ * **Connection Pooling:** Efficiently manages and recycles database connections using `mysql2/promise`.
69
+ * **ACID Transactions:** Comprehensive transaction management with automatic `BEGIN`, `COMMIT`, `ROLLBACK`, and safe connection release.
70
+ * **Transparent Singleton Support:** Powered by native Node.js `AsyncLocalStorage`. Shared table singletons automatically adopt the current transaction without passing `tx` around.
71
+ * **Post-Commit Hooks (`onCommit`):** Execute external tasks (banking APIs, emails, webhooks) strictly after database transactions successfully commit.
72
+ * **Express Lazy Middleware:** Zero-code change transactions via `db.autoTransaction()`. Reads remain non-blocking on the pool, while write operations seamlessly open and commit transactions on demand.
73
+ * **Savepoints (Nested Transactions):** Safely run sub-transactions with partial rollback support without aborting outer transactions.
74
+ * **Categorized Static Enumerators:** Immutable (`Object.freeze`) enumerators (`ArithmeticOperator`, `ComparisonOperator`, `LogicalOperator`, `BitwiseOperator`) to completely eliminate magic strings and typo risks.
75
+ * **Flexible Query Builder:** Run complex operations without writing manual SQL strings.
76
+ * **Automatic `IN` Handling:** Smart processing of arrays for SQL `IN` and `NOT IN` operations (including prevention of empty array query crashes).
77
+ * **Optional Caching Wrapper:** Native support for query and schema caching using `node-cache` (automatically bypassed during active transactions).
78
+ * **Server-Side DataTables Integration:** Effortless integration with jQuery DataTables server-side requests, handling filters, sorting, search (global and column-based), regex, and count totals automatically.
79
+ * **Robust Error Handling:** Intercepts and wraps database errors in predictable objects outside transactions, while throwing inside transactions to ensure immediate rollback.
80
+
81
+ ---
82
+
83
+ ## Installation
84
+
85
+ ```bash
86
+ npm install @areumtecnologia/mysql-db-handler
87
+ ```
88
+
89
+ If you wish to use the caching features, ensure `node-cache` is installed:
90
+ ```bash
91
+ npm install node-cache
92
+ ```
93
+
94
+ ---
95
+
96
+ ## Core Classes
97
+
98
+ The package exports the following primary components:
99
+
100
+ ### 1. `DataBase` (Standard Connection)
101
+ Located in `lib/database.js`. Manages standard pooled connections, schema discovery, and query execution.
102
+
103
+ ### 2. `DataBase` (With Query & Schema Caching)
104
+ Located in `lib/database-cache.js`. Overrides the standard `DataBase` implementation to provide in-memory query and table schema caching. It is ideal for read-heavy environments.
105
+
106
+ ### 3. `DataBaseHandler` (CRUD Abstraction)
107
+ Located in `lib/databaseHandler.js`. Bind this class to a specific table to perform database actions through utility methods (`select`, `selectBy`, `insert`, `update`, `delete`, `selectToDatatable`).
108
+
109
+ > [!NOTE]
110
+ > **Convenção de Nomenclatura & Aliases:**
111
+ > O pacote exporta tanto os identificadores em PascalCase com `B` maiúsculo (`DataBase`, `DataBaseHandler`, `DataBaseCache`) quanto aliases com `b` minúsculo (`Database`, `DatabaseHandler`, `DatabaseCache`), permitindo compatibilidade total com qualquer estilo de importação:
112
+ > ```javascript
113
+ > const { DataBase, DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
114
+ > // ou:
115
+ > const { Database, DatabaseHandler } = require('@areumtecnologia/mysql-db-handler');
116
+ > ```
117
+
118
+ ---
119
+
120
+ ## Basic Usage
121
+
122
+ ### 1. Initializing Connection
123
+
124
+ ```javascript
125
+ const { DataBase } = require('@areumtecnologia/mysql-db-handler');
126
+
127
+ // Configuration matches mysql2 connection configuration
128
+ const db = new DataBase({
129
+ host: 'localhost',
130
+ user: 'root',
131
+ password: 'password',
132
+ database: 'my_app_db',
133
+ port: 3306,
134
+ connectionLimit: 10,
135
+ waitForConnections: true,
136
+ queueLimit: 0
137
+ });
138
+ ```
139
+
140
+ ### 2. Executing Raw SQL
141
+
142
+ Raw queries are executed through connection pooling. The library handles obtaining and releasing the connection automatically.
143
+
144
+ ```javascript
145
+ try {
146
+ const rows = await db.query('SELECT * FROM users WHERE active = ? AND role = ?', [1, 'editor']);
147
+ console.log('Active editors:', rows);
148
+ } catch (error) {
149
+ console.error('Database query failed:', error);
150
+ }
151
+ ```
152
+
153
+ ### 3. Using the DataBaseHandler
154
+
155
+ Wrap a table with a handler to abstract SQL construction.
156
+
157
+ ```javascript
158
+ const { DataBase, DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
159
+
160
+ const db = new DataBase({ /* config */ });
161
+ const usersHandler = new DataBaseHandler(db, 'users');
162
+ ```
163
+
164
+ ---
165
+
166
+ ## Categorized Static Enumerators (No Magic Strings)
167
+
168
+ Para evitar erros de digitação ("strings mágicas"), garantir compatibilidade total com autocomplete de IDEs e elevar a segurança de tipos em JavaScript e TypeScript, a biblioteca disponibiliza **Enumeradores Estáticos Categorizados** imutáveis (`Object.freeze`).
169
+
170
+ Os enumeradores podem ser importados diretamente da raiz do pacote ou acessados estaticamente através de `DataBaseHandler` / `DatabaseHandler`.
171
+
172
+ ```javascript
173
+ const {
174
+ DataBaseHandler,
175
+ Operators,
176
+ ArithmeticOperator,
177
+ ComparisonOperator,
178
+ LogicalOperator,
179
+ BitwiseOperator
180
+ } = require('@areumtecnologia/mysql-db-handler');
181
+
182
+ // Também acessíveis diretamente na classe:
183
+ // DataBaseHandler.ArithmeticOperator
184
+ // DataBaseHandler.ComparisonOperator
185
+ // DataBaseHandler.LogicalOperator
186
+ // DataBaseHandler.BitwiseOperator
187
+ // DataBaseHandler.Operators
188
+ ```
189
+
190
+ ---
191
+
192
+ ### 1. Operadores Aritméticos (`ArithmeticOperator` / `Operators.Arithmetic`)
193
+
194
+ Usados para realizar cálculos matemáticos com dados numéricos:
195
+
196
+ | Chave / Propriedade | Valor SQL | Descrição |
197
+ | :--- | :--- | :--- |
198
+ | `ArithmeticOperator.ADD` / `PLUS` | `+` | Adição (Soma) |
199
+ | `ArithmeticOperator.SUBTRACT` / `MINUS` | `-` | Subtração |
200
+ | `ArithmeticOperator.MULTIPLY` | `*` | Multiplicação |
201
+ | `ArithmeticOperator.DIVIDE` | `/` | Divisão |
202
+ | `ArithmeticOperator.MODULO` / `MOD` | `%` ou `MOD` | Módulo (resto da divisão inteira) |
203
+ | `ArithmeticOperator.DIV` / `INTEGER_DIVIDE` | `DIV` | Divisão inteira (descarta a parte decimal) |
204
+
205
+ *Alias alternativo:* `Operators.Aritmeticos`
206
+
207
+ ---
208
+
209
+ ### 2. Operadores de Comparação (Relacionais) (`ComparisonOperator` / `Operators.Comparison`)
210
+
211
+ Usados para comparar dois valores e retornar verdadeiro (1), falso (0) ou `NULL`:
212
+
213
+ | Chave / Propriedade | Valor SQL | Descrição |
214
+ | :--- | :--- | :--- |
215
+ | `ComparisonOperator.EQUALS` / `EQUAL` / `EQ` | `=` | Igual a |
216
+ | `ComparisonOperator.NOT_EQUALS` / `NOT_EQUAL` / `NEQ` | `!=` | Diferente de |
217
+ | `ComparisonOperator.NOT_EQUALS_ALT` / `DIFFERENT` | `<>` | Diferente de (sintaxe alternativa SQL) |
218
+ | `ComparisonOperator.GREATER_THAN` / `GT` | `>` | Maior que |
219
+ | `ComparisonOperator.LESS_THAN` / `LT` | `<` | Menor que |
220
+ | `ComparisonOperator.GREATER_THAN_OR_EQUAL` / `GTE` | `>=` | Maior ou igual a |
221
+ | `ComparisonOperator.LESS_THAN_OR_EQUAL` / `LTE` | `<=` | Menor ou igual a |
222
+ | `ComparisonOperator.BETWEEN` / `NOT_BETWEEN` | `BETWEEN` / `NOT BETWEEN` | Verifica se o valor está dentro de um intervalo |
223
+ | `ComparisonOperator.IN` / `NOT_IN` | `IN` / `NOT IN` | Verifica se o valor corresponde a qualquer elemento de uma lista |
224
+ | `ComparisonOperator.LIKE` / `NOT_LIKE` | `LIKE` / `NOT LIKE` | Compara padrões de texto (usado com coringas `%` e `_`) |
225
+ | `ComparisonOperator.IS_NULL` | `IS NULL` | Testa se um valor é nulo |
226
+ | `ComparisonOperator.IS_NOT_NULL` | `IS NOT NULL` | Testa se um valor não é nulo |
227
+ | `ComparisonOperator.IS` / `IS_NOT` | `IS` / `IS NOT` | Avaliação de predicados de identidade/nulidade |
228
+ | `ComparisonOperator.REGEXP` / `NOT_REGEXP` | `REGEXP` / `NOT REGEXP` | Validação por expressão regular |
229
+
230
+ *Alias alternativo:* `Operators.Comparacao`
231
+
232
+ ---
233
+
234
+ ### 3. Operadores Lógicos (`LogicalOperator` / `Operators.Logical`)
235
+
236
+ Usados para combinar múltiplas condições em uma consulta:
237
+
238
+ | Chave / Propriedade | Valor SQL | Descrição |
239
+ | :--- | :--- | :--- |
240
+ | `LogicalOperator.AND` | `AND` | Retorna verdadeiro se todas as condições forem verdadeiras |
241
+ | `LogicalOperator.OR` | `OR` | Retorna verdadeiro se pelo menos uma das condições for verdadeira |
242
+ | `LogicalOperator.NOT` / `BANG` / `NOT_ALT` | `NOT` ou `!` | Inverte o valor lógico (transforma verdadeiro em falso e vice-versa) |
243
+
244
+ *Alias alternativo:* `Operators.Logicos`
245
+
246
+ ---
247
+
248
+ ### 4. Operadores Bit a Bit (`BitwiseOperator` / `Operators.Bitwise`)
249
+
250
+ Realizam operações em nível de bits:
251
+
252
+ | Chave / Propriedade | Valor SQL | Descrição |
253
+ | :--- | :--- | :--- |
254
+ | `BitwiseOperator.AND` / `BITWISE_AND` | `&` | E bit a bit (AND) |
255
+ | `BitwiseOperator.OR` / `BITWISE_OR` | `\|` | OU bit a bit (OR) |
256
+ | `BitwiseOperator.XOR` / `BITWISE_XOR` | `^` | OU exclusivo bit a bit (XOR) |
257
+ | `BitwiseOperator.RIGHT_SHIFT` / `SHR` | `>>` | Deslocamento à direita (Right shift) |
258
+ | `BitwiseOperator.LEFT_SHIFT` / `SHL` | `<<` | Deslocamento à esquerda (Left shift) |
259
+
260
+ *Alias alternativo:* `Operators.BitwisePT`
261
+
262
+ ---
263
+
264
+ ### Practical Usage Examples
265
+
266
+ #### 1. Encadeamento Fluente (`where` e `orWhere`)
267
+ ```javascript
268
+ const { DataBaseHandler, ComparisonOperator } = require('@areumtecnologia/mysql-db-handler');
269
+
270
+ // Consultas sem nenhuma string mágica
271
+ const produtos = await produtosHandler
272
+ .where('preco', ComparisonOperator.GREATER_THAN_OR_EQUAL, 150)
273
+ .where('categoria', ComparisonOperator.EQUALS, 'informatica')
274
+ .orWhere('em_promocao', ComparisonOperator.EQUALS, 1)
275
+ .get();
276
+
277
+ // Verificação de Nulos elegante com 2 argumentos
278
+ const ativos = await produtosHandler
279
+ .where('deletado_em', ComparisonOperator.IS_NULL)
280
+ .where('publicado_em', ComparisonOperator.IS_NOT_NULL)
281
+ .get();
282
+
283
+ // Intervalos e Listas
284
+ const resultado = await produtosHandler
285
+ .where('data_criacao', ComparisonOperator.BETWEEN, ['2026-01-01', '2026-12-31'])
286
+ .where('nome', ComparisonOperator.LIKE, 'Notebook%')
287
+ .where('status', ComparisonOperator.IN, ['estoque', 'encomenda'])
288
+ .get();
289
+ ```
290
+
291
+ #### 2. Joins Fluentes
292
+ ```javascript
293
+ const pedidos = await pedidosHandler
294
+ .selectFields(['pedidos.id', 'pedidos.total', 'clientes.nome'])
295
+ .join('clientes', 'pedidos.cliente_id', ComparisonOperator.EQUALS, 'clientes.id')
296
+ .where('pedidos.status', ComparisonOperator.NOT_EQUALS, 'cancelado')
297
+ .get();
298
+ ```
299
+
300
+ #### 3. Mutações e Condições em Array (`update` e `delete`)
301
+ ```javascript
302
+ const { LogicalOperator, ComparisonOperator } = require('@areumtecnologia/mysql-db-handler');
303
+
304
+ await produtosHandler.update({
305
+ set: { status: 'arquivado' },
306
+ where: [
307
+ { estoque: 0, operator: ComparisonOperator.EQUALS },
308
+ LogicalOperator.OR,
309
+ { descontinuado: 1, operator: ComparisonOperator.EQUALS }
310
+ ]
311
+ });
312
+ ```
313
+
314
+ ---
315
+
316
+ ## Advanced Querying (`select` method)
317
+
318
+ The `select(params, clauses)` method builds complex SQL `WHERE` clauses from arrays of condition objects.
319
+
320
+ ### Basic Selection
321
+
322
+ You can pass condition objects where the key is the column name and the value is the target value.
323
+
324
+ ```javascript
325
+ // Simple equals comparison (=)
326
+ const users = await usersHandler.select([
327
+ { role: 'admin' }
328
+ ]);
329
+ // Executes: SELECT * FROM users WHERE `role` = ?
330
+ ```
331
+
332
+ ### Working with the `IN` and `NOT IN` Operators
333
+
334
+ The library provides special support for SQL `IN` operations by mapping JavaScript arrays to queries.
335
+
336
+ #### Automatic `IN` Detection
337
+ If a condition's value is an array, and no operator is explicitly set, the query builder automatically treats it as an `IN` statement:
338
+
339
+ ```javascript
340
+ const activeUsers = await usersHandler.select([
341
+ { status: ['active', 'pending'] }
342
+ ]);
343
+ // Executes: SELECT * FROM users WHERE `status` IN (?, ?)
344
+ // Bindings: ['active', 'pending']
345
+ ```
346
+
347
+ #### Explicit `IN` / `NOT IN` Operator
348
+ You can explicitly define the `operator` as `'IN'` or `'NOT IN'` (or using `ComparisonOperator.IN` / `ComparisonOperator.NOT_IN` to eliminate magic strings):
349
+
350
+ ```javascript
351
+ // Using ComparisonOperator.NOT_IN explicitly
352
+ const nonAdminUsers = await usersHandler.select([
353
+ { role: ['admin', 'superadmin'], operator: ComparisonOperator.NOT_IN }
354
+ ]);
355
+ // Executes: SELECT * FROM users WHERE `role` NOT IN (?, ?)
356
+ // Bindings: ['admin', 'superadmin']
357
+ ```
358
+
359
+ #### Empty Array Safety (`IN ()` Protection)
360
+ In standard SQL, executing a query with an empty array in the `IN` clause (e.g., `WHERE status IN ()`) yields a syntax error and crashes the execution. The library automatically mitigates this:
361
+
362
+ * **Empty `IN`**: Evaluates to `1 = 0` (always false). No records match this sub-clause, ensuring safe execution.
363
+ * **Empty `NOT IN`**: Evaluates to `1 = 1` (always true). All records match this sub-clause, returning all values since nothing is excluded.
364
+
365
+ ```javascript
366
+ // Safe empty array handling
367
+ const results = await usersHandler.select([
368
+ { id: [], operator: 'IN' }
369
+ ]);
370
+ // Executes: SELECT * FROM users WHERE 1 = 0
371
+
372
+ const allResults = await usersHandler.select([
373
+ { id: [], operator: 'NOT IN' }
374
+ ]);
375
+ // Executes: SELECT * FROM users WHERE 1 = 1
376
+ ```
377
+
378
+ ### Combining Multiple Conditions (AND / OR)
379
+
380
+ Interleave condition objects with string elements representing logical operators:
381
+
382
+ ```javascript
383
+ const filteredProducts = await productsHandler.select(
384
+ [
385
+ { category: 'electronics' },
386
+ 'AND',
387
+ { price: 500, operator: '>' },
388
+ 'AND',
389
+ { brand: ['Sony', 'LG'] } // Automatically mapped to IN
390
+ ],
391
+ {
392
+ 'ORDERBY': 'price',
393
+ 'DESC': true,
394
+ 'LIMIT': 20
395
+ }
396
+ );
397
+ // Executes:
398
+ // SELECT * FROM products WHERE `category` = ? AND `price` > ? AND `brand` IN (?, ?) ORDER BY price DESC LIMIT 20
399
+ ```
400
+
401
+ ---
402
+
403
+ ## CRUD Operations
404
+
405
+ ### Inserting Records (`insert`)
406
+
407
+ Adds a new row to the associated table using key-value properties.
408
+
409
+ ```javascript
410
+ const result = await usersHandler.insert({
411
+ name: 'John Doe',
412
+ email: 'john.doe@example.com',
413
+ role: 'member',
414
+ created_at: new Date()
415
+ });
416
+
417
+ console.log('Inserted ID:', result.insertId);
418
+ ```
419
+
420
+ ### Bulk Insert (`insertMany`)
421
+
422
+ Insere múltiplos registros em uma única instrução SQL (`INSERT INTO table (...) VALUES ?`), oferecendo máxima performance para cargas em lote. O método aplica sanitização de schema (`autoStripUnknown`), preenche timestamps automáticos (`criado_em` / `atualizado_em`) e dispara os hooks de ciclo de vida (`beforeInsert` / `afterInsert`) para cada registro:
423
+
424
+ ```javascript
425
+ const novosUsuarios = [
426
+ { name: 'Alice Silva', email: 'alice@empresa.com', role: 'developer' },
427
+ { name: 'Bob Souza', email: 'bob@empresa.com', role: 'designer' },
428
+ { name: 'Carlos Lima', email: 'carlos@empresa.com', role: 'manager' }
429
+ ];
430
+
431
+ const result = await usersHandler.insertMany(novosUsuarios);
432
+ console.log('Linhas inseridas:', result.affectedRows);
433
+ ```
434
+
435
+ ### Upsert with Smart Timestamps (`upsert`)
436
+
437
+ Executa uma operação atômica de inserção ou atualização (`INSERT INTO ... ON DUPLICATE KEY UPDATE`). Se o registro for novo, ele é inserido com os timestamps de criação e atualização. Se a chave primária ou índice único já existir, apenas os campos selecionados são atualizados, **preservando intacta a data de criação original (`criado_em` / `createdAt`)**:
438
+
439
+ ```javascript
440
+ // Exemplo: Insere o produto ou atualiza apenas preco e estoque se codigo_barras já existir
441
+ const result = await produtosHandler.upsert({
442
+ codigo_barras: '7891234567890',
443
+ nome: 'Mouse sem Fio',
444
+ preco: 149.90,
445
+ estoque: 80
446
+ }, ['preco', 'estoque']); // 2º argumento opcional: colunas a atualizar no conflito
447
+
448
+ // Se omitir o 2º argumento, atualiza todos os campos fornecidos exceto criado_em:
449
+ await produtosHandler.upsert({
450
+ codigo_barras: '7891234567890',
451
+ nome: 'Mouse sem Fio Pro',
452
+ preco: 179.90
453
+ });
454
+ ```
455
+
456
+ ### Updating Records (`update`)
457
+
458
+ Performs selective updates by specifying both a `set` payload and a `where` filter. The `where` filter supports both standard flat objects (where conditions are implicitly joined by `AND` using `=` or `REGEXP`) and complex array configurations (with operators, `AND`, and `OR`), sharing the same advanced querying capabilities as the `select` method.
459
+
460
+ #### 1. Simple Object Syntax (Implicit AND, = operator)
461
+
462
+ ```javascript
463
+ const result = await usersHandler.update({
464
+ set: {
465
+ status: 'suspended',
466
+ notes: 'Violated terms of service'
467
+ },
468
+ where: {
469
+ id: 42,
470
+ status: 'active'
471
+ }
472
+ });
473
+
474
+ console.log('Affected rows:', result.affectedRows);
475
+ // Executes: UPDATE users SET `status` = ?, `notes` = ? WHERE `id` = ? AND `status` = ?
476
+ ```
477
+
478
+ #### 2. Advanced Array Syntax (with operators, AND/OR, and IN)
479
+
480
+ You can pass an array of condition objects interleaved with `AND` or `OR` string elements to construct complex queries:
481
+
482
+ ```javascript
483
+ // Example updating records based on numeric thresholds and logical operators
484
+ const result = await usersHandler.update({
485
+ set: {
486
+ status: 'inactive'
487
+ },
488
+ where: [
489
+ { age: 18, operator: '<' },
490
+ 'AND',
491
+ { status: 'active' }
492
+ ]
493
+ });
494
+ // Executes: UPDATE users SET `status` = ? WHERE `age` < ? AND `status` = ?
495
+
496
+ // Example updating records using automatic IN operator detection
497
+ const result = await usersHandler.update({
498
+ set: {
499
+ role: 'archived'
500
+ },
501
+ where: [
502
+ { id: [10, 20, 30] } // Automatically builds: WHERE `id` IN (?, ?, ?)
503
+ ]
504
+ });
505
+ // Executes: UPDATE users SET `role` = ? WHERE `id` IN (?, ?, ?)
506
+
507
+ // Example combining complex logic (AND/OR)
508
+ const result = await usersHandler.update({
509
+ set: {
510
+ category: 'Premium'
511
+ },
512
+ where: [
513
+ { total_purchases: 1000, operator: '>' },
514
+ 'AND',
515
+ { status: 'active' },
516
+ 'OR',
517
+ { is_vip: 1 }
518
+ ]
519
+ });
520
+ // Executes: UPDATE users SET `category` = ? WHERE `total_purchases` > ? AND `status` = ? OR `is_vip` = ?
521
+ ```
522
+
523
+ ### Deleting Records (`delete`)
524
+
525
+ Deletes rows matching the conditions object (joined by implicit `AND` operators).
526
+
527
+ ```javascript
528
+ const result = await usersHandler.delete({
529
+ status: 'temporary',
530
+ is_expired: 1
531
+ });
532
+
533
+ console.log('Deleted rows:', result.affectedRows);
534
+ ```
535
+
536
+ ### Fluent Mutations (`.where().update()` / `.delete()`)
537
+
538
+ Você pode encadear as mutações de escrita diretamente a partir do Query Builder Fluente, garantindo expressividade e legibilidade de alto nível:
539
+
540
+ ```javascript
541
+ // Soft Delete (ou hard delete) diretamente com filtros encadeados:
542
+ await pedidosHandler
543
+ .where('status', 'CANCELADO')
544
+ .where('criado_em', '<', dataLimite)
545
+ .delete();
546
+
547
+ // Update com filtros fluentes encadeados:
548
+ await clientesHandler
549
+ .where('id', 10)
550
+ .update({
551
+ set: { status: 'ATIVO', tentativas_login: 0 }
552
+ });
553
+
554
+ // Restauração de itens da lixeira via Query Builder:
555
+ await produtosHandler
556
+ .where('categoria_id', 5)
557
+ .restore();
558
+
559
+ // Exclusão física definitiva (Hard Delete) via Query Builder:
560
+ await logsHandler
561
+ .where('criado_em', '<', dataExpiracao)
562
+ .forceDelete();
563
+ ```
564
+
565
+ ---
566
+
567
+ ## jQuery DataTables Server-Side Support (`selectToDatatable`)
568
+
569
+ The `selectToDatatable` method provides seamless, enterprise-grade, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It eliminates manual SQL pagination boilerplate, automatically handling pagination, search (global and column-specific), multi-column ordering, regex filters, dual-count latency optimizations, backend security constraints, Soft Deletes, and sensitive field masking.
570
+
571
+ ---
572
+
573
+ ### Step-by-Step Execution Lifecycle (Under the Hood)
574
+
575
+ Whenever `selectToDatatable(rawDtQuery, strictCondition)` is invoked, it executes the following optimized workflow:
576
+
577
+ ```
578
+ [Incoming Request] (req.body or req.query)
579
+ │
580
+ ▼
581
+ 1. Hydration & Security Filter
582
+ • Flattens or parses bracketed keys (e.g. columns[0][data] -> { columns: [{ data: ... }] })
583
+ • Prototype Pollution Guard: Sanitizes __proto__, constructor, and prototype (CWE-1321)
584
+ • Sanitizes integers (draw, start, length) preventing NaN injections
585
+ │
586
+ ▼
587
+ 2. Backend Security & Tenant Scoping (strictCondition)
588
+ • Injects non-bypassable backend filters (tenant_id, account_id, branch, etc.)
589
+ • [v2.0.0] Injects Soft Delete filter (deletado_em IS NULL) automatically unless withTrashed() is active
590
+ │
591
+ ▼
592
+ 3. Search Clause Generation
593
+ • Global Search (search.value): Checks all columns where searchable == true -> (col1 LIKE ? OR col2 LIKE ?)
594
+ • Column-Specific Search (columns[i].search.value): Checks individual columns -> AND colN LIKE ?
595
+ • Regex Toggle: If regex == true, switches operator from LIKE %term% to REGEXP term
596
+ • Parameterized bindings: All terms use prepared statement placeholders (?) to block SQL injection
597
+ │
598
+ ▼
599
+ 4. Dual-COUNT Latency Optimization
600
+ • No Active Search Filter: Only 1 COUNT(*) query is executed. recordsFiltered is instantly set to recordsTotal (up to 50% database I/O reduction).
601
+ • Active Search Filter: Executes total COUNT(*) and filtered COUNT(*) concurrently via Promise.all().
602
+ │
603
+ ▼
604
+ 5. Short-Circuit Check
605
+ • If recordsFiltered === 0: The data SELECT query is skipped entirely. Returns data: [] immediately, avoiding expensive filesort and buffer allocations.
606
+ │
607
+ ▼
608
+ 6. Multi-Column Ordering & Keyset Limitation
609
+ • Parses all order directives (order[0], order[1], etc.)
610
+ • Maps column index to sanitized column name (e.g. `col1` ASC, `col2` DESC)
611
+ • Generates LIMIT start, length safely
612
+ │
613
+ ▼
614
+ 7. Data Retrieval & Sensitive Field Masking
615
+ • Executes SELECT <columns> FROM <table> [JOINS] [WHERE] [ORDER BY] [LIMIT]
616
+ • [v2.0.0] Strips any fields declared in hiddenFields (e.g. senha_hash, token) before output
617
+ │
618
+ ▼
619
+ [Standard JSON Response to DataTables]
620
+ ```
621
+
622
+ ---
623
+
624
+ ### Key Features & Performance Optimizations
625
+
626
+ * **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state during initial page load, sorting, and standard 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%**.
627
+ * **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.
628
+ * **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]`).
629
+ * **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`.
630
+ * **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.
631
+ * **Prototype Pollution Protection (CWE-1321):** Deeply sanitizes incoming request keys, blocking injections targeting `__proto__`, `constructor`, or `prototype`.
632
+ * **[v2.0.0] Soft Delete & Hidden Fields Aware:** Automatically excludes soft-deleted records (`deletado_em IS NULL`) and strips sensitive columns (`hiddenFields`) from the returned JSON.
633
+
634
+ ---
635
+
636
+ ### Method Signature
637
+
638
+ ```javascript
639
+ await handler.selectToDatatable(rawDtQuery, strictCondition = [])
640
+ ```
641
+
642
+ #### Parameters
643
+
644
+ | Parameter | Type | Required | Description |
645
+ | :--- | :--- | :---: | :--- |
646
+ | `rawDtQuery` | `Object` | **Yes** | The request payload sent by jQuery DataTables (`req.body` in POST or `req.query` in GET). Supports both bracket-flattened keys and nested JSON. |
647
+ | `strictCondition` | `Array` \| `Object` | No | Backend constraints that the client cannot view or modify (e.g. multi-tenant isolation, user scoping, active-only filters). |
648
+
649
+ #### DataTables Payload Schema (`rawDtQuery`)
650
+
651
+ | Field | Type | Description |
652
+ | :--- | :--- | :--- |
653
+ | `draw` | `number` \| `string` | Draw counter echoed back to the client to ensure response synchronization. |
654
+ | `start` | `number` \| `string` | Zero-based paging first record indicator (`OFFSET`). Defaults to `0`. |
655
+ | `length` | `number` \| `string` | Number of records to return (`LIMIT`). |
656
+ | `search.value` | `string` | Global search value applied across all columns with `searchable: true`. |
657
+ | `search.regex` | `boolean` \| `string` | If `true` or `'true'`, uses MySQL `REGEXP` instead of `LIKE %value%`. |
658
+ | `order` | `Array<Object>` | Array of order objects: `{ column: 0, dir: 'asc' \| 'desc' }`. |
659
+ | `columns` | `Array<Object>` | Array of column definitions: `{ data: 'col_name', searchable: true, orderable: true, search: { value: '', regex: false } }`. |
660
+
661
+ ---
662
+
663
+ ### Basic Express.js Example
664
+
665
+ ```javascript
666
+ const express = require('express');
667
+ const { db, usersHandler } = require('./databaseController');
668
+
669
+ const app = express();
670
+ app.use(express.json());
671
+ app.use(express.urlencoded({ extended: true }));
672
+
673
+ app.post('/api/users/datatable', async (req, res) => {
674
+ // req.body contains: { draw, start, length, search, order, columns }
675
+ const result = await usersHandler.selectToDatatable(req.body);
676
+ res.json(result);
677
+ });
678
+ ```
679
+
680
+ ---
681
+
682
+ ### Enforcing Backend Security & Custom Filters (`strictCondition`)
683
+
684
+ Never rely solely on client frontend parameters to enforce data boundaries or custom business filters. Pass `strictCondition` to apply non-bypassable constraints.
685
+
686
+ `strictCondition` supports both **Array syntax** (with custom operators, arrays mapped to `IN`, and explicit `'AND'`/`'OR'`) and **Plain Object syntax** (multiple properties are automatically combined with `AND`):
687
+
688
+ ```javascript
689
+ app.post('/api/orders/datatable', async (req, res) => {
690
+ // Client-side parameters cannot bypass these conditions:
691
+ const strictConditions = [
692
+ { tenant_id: req.user.tenantId },
693
+ 'AND',
694
+ { status: 'deleted', operator: '!=' },
695
+ 'AND',
696
+ { store_id: [101, 102, 105] } // Automatically mapped to: `store_id` IN (?, ?, ?)
697
+ ];
698
+
699
+ const result = await ordersHandler.selectToDatatable(req.body, strictConditions);
700
+ res.json(result);
701
+ });
702
+ ```
703
+
704
+ ---
705
+
706
+ ### Handling Custom Frontend Filters (e.g., Status, Dates, Categories)
707
+
708
+ When users apply custom UI filters (dropdowns, datepickers, checkboxes) alongside DataTables, capture them in your controller and pass them into `strictCondition`:
709
+
710
+ ```javascript
711
+ app.post('/api/clientes/datatable', async (req, res) => {
712
+ const filters = [];
713
+
714
+ // Map UI filter (e.g. 'HABILITADO') to database column ('active' = 1 / 0)
715
+ if (req.body.status) {
716
+ filters.push({ active: req.body.status === 'HABILITADO' ? 1 : 0 });
717
+ }
718
+
719
+ if (req.body.created_after) {
720
+ if (filters.length > 0) filters.push('AND');
721
+ filters.push({ created_at: req.body.created_after, operator: '>=' });
722
+ }
723
+
724
+ // Pass request body + backend-mapped filters
725
+ const result = await clientesHandler.selectToDatatable(req.body, filters);
726
+ res.json(result);
727
+ });
728
+ ```
729
+
730
+ > [!TIP]
731
+ > **DataTables Modern Protocol Support (v1.10, v2.x, v3.x):**
732
+ > `selectToDatatable` automatically normalizes:
733
+ > - **Search**: supports standard `{ value: '...', regex: false }`, direct strings (`search: '...'`), and query fallbacks (`q`).
734
+ > - **Columns**: accepts both standard `Array` and index-keyed objects (`{ '0': {...}, '1': {...} }`).
735
+ > - **Ordering**: supports ordering by column index (`order: [{ column: 0, dir: 'asc' }]`) and by column name (`order: [{ name: 'col_name', dir: 'desc' }]`).
736
+ > - **Payload collision**: prevents bracketed keys (`search[value]`) from being corrupted by flat parameters.
737
+
738
+ ---
739
+
740
+ ### Using JOINs with DataTables
741
+
742
+ #### Option A: Modern Fluent Query Builder Joins (Recommended in v2.0.0)
743
+ Chain `.selectFields()` and `.leftJoin()` / `.join()` directly with `.selectToDatatable()`:
744
+
745
+ ```javascript
746
+ app.post('/api/pedidos/datatable', async (req, res) => {
747
+ const result = await pedidosHandler
748
+ .selectFields([
749
+ 'pedidos.id',
750
+ 'pedidos.valor',
751
+ 'pedidos.criado_em',
752
+ { column: 'c.nome', as: 'cliente_nome' },
753
+ { column: 'v.nome', as: 'vendedor_nome' }
754
+ ])
755
+ .leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
756
+ .leftJoin('vendedores v', 'pedidos.vendedor_id', '=', 'v.id')
757
+ .selectToDatatable(req.body, [
758
+ { 'pedidos.empresa_id': req.user.empresaId }
759
+ ]);
760
+
761
+ res.json(result);
762
+ });
763
+ ```
764
+
765
+ #### Option B: Legacy Expression Parameter
766
+ You can also initialize the handler with a SQL expression containing the JOINs and selected columns:
767
+
768
+ ```javascript
769
+ // Table: 'sales s'
770
+ // Expression: JOIN with customers and users, selecting extra fields
771
+ const salesHandler = new DataBaseHandler(
772
+ db,
773
+ 'customers_sales s',
774
+ ', c.name AS customer_name, u.name AS user_name ' +
775
+ 'LEFT JOIN customers c ON c.id = s.customer ' +
776
+ 'LEFT JOIN users u ON u.id = s.user'
777
+ );
778
+
779
+ app.post('/api/sales/datatable', async (req, res) => {
780
+ // DataTables columns can search and sort by qualified identifiers (e.g. 'c.name')
781
+ const result = await salesHandler.selectToDatatable(req.body, [
782
+ { 's.deleted_at': null, operator: 'IS' }
783
+ ]);
784
+ res.json(result);
785
+ });
786
+ ```
787
+
788
+ ---
789
+
790
+ ### Soft Deletes & Sensitive Fields in DataTables (v2.0.0)
791
+
792
+ When configuring business rules on the handler, `selectToDatatable` automatically complies without requiring manual filters:
793
+
794
+ ```javascript
795
+ const clientesHandler = new DataBaseHandler(db, 'clientes', {
796
+ softDelete: 'deletado_em', // Injeta 'AND deletado_em IS NULL' automaticamente
797
+ hiddenFields: ['senha_hash', 'token_recuperacao'] // Remove do retorno mesmo se 'SELECT *' for usado
798
+ });
799
+
800
+ // A consulta abaixo já ignora excluídos e nunca expõe senha_hash
801
+ app.post('/api/clientes/datatable', async (req, res) => {
802
+ const result = await clientesHandler.selectToDatatable(req.body);
803
+ res.json(result);
804
+ });
805
+
806
+ // Para consultar registos da lixeira (soft-deleted):
807
+ app.post('/api/clientes/trash/datatable', async (req, res) => {
808
+ const result = await clientesHandler.onlyTrashed().selectToDatatable(req.body);
809
+ res.json(result);
810
+ });
811
+ ```
812
+
813
+ ---
814
+
815
+ ### Frontend jQuery DataTables Setup
816
+
817
+ Configure your frontend DataTables instance with `serverSide: true`:
818
+
819
+ ```javascript
820
+ $('#usersTable').DataTable({
821
+ processing: true,
822
+ serverSide: true,
823
+ ajax: {
824
+ url: '/api/users/datatable',
825
+ type: 'POST',
826
+ contentType: 'application/json',
827
+ data: function (d) {
828
+ return JSON.stringify(d);
829
+ }
830
+ },
831
+ columns: [
832
+ { data: 'id', name: 'id' },
833
+ { data: 'name', name: 'name' },
834
+ { data: 'email', name: 'email' },
835
+ { data: 'role', name: 'role' },
836
+ {
837
+ data: null,
838
+ orderable: false,
839
+ searchable: false,
840
+ render: function (data, type, row) {
841
+ return `<button onclick="editUser(${row.id})">Edit</button>`;
842
+ }
843
+ }
844
+ ],
845
+ order: [[0, 'desc']]
846
+ });
847
+ ```
848
+
849
+ ---
850
+
851
+ ### Response Structure & Error Handling
852
+
853
+ The method always returns the standard JSON response expected by DataTables:
854
+
855
+ #### Success Response
856
+ ```json
857
+ {
858
+ "draw": 1,
859
+ "recordsTotal": 1250,
860
+ "recordsFiltered": 45,
861
+ "data": [
862
+ { "id": 42, "name": "John Doe", "email": "john@example.com", "role": "admin" },
863
+ { "id": 43, "name": "Jane Smith", "email": "jane@example.com", "role": "editor" }
864
+ ]
865
+ }
866
+ ```
867
+
868
+ #### Safe Error Handling
869
+ 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:
870
+
871
+ ```json
872
+ {
873
+ "draw": 1,
874
+ "recordsTotal": 0,
875
+ "recordsFiltered": 0,
876
+ "data": [],
877
+ "error": "ER_NO_SUCH_TABLE: Table 'my_app_db.invalid_table' doesn't exist"
878
+ }
879
+ ```
880
+
881
+
882
+ ---
883
+
884
+ ## Transaction Support (ACID & Transparent)
885
+
886
+ The library provides first-class transaction support built on top of Node.js native `AsyncLocalStorage`. Transactions can be used explicitly or completely transparently across shared Singletons without manual connection passing.
887
+
888
+ ### 1. Explicit Block (`db.transaction`)
889
+
890
+ Wrap operations in `db.transaction(callback)`. If the callback resolves, `COMMIT` is executed automatically. If an error is thrown or unhandled, `ROLLBACK` is performed automatically and the connection is safely released back to the pool.
891
+
892
+ ```javascript
893
+ await db.transaction(async () => {
894
+ await usersHandler.insert({ name: 'Alice', balance: 500 });
895
+ await auditHandler.insert({ action: 'USER_CREATED', user: 'Alice' });
896
+ // If any error occurs, all operations in this block are rolled back!
897
+ });
898
+ ```
899
+
900
+ ### 2. Singleton Compatibility with `AsyncLocalStorage`
901
+
902
+ When running inside `db.transaction()`, **you do not need to pass transaction instances to your handlers**. Globally shared table handlers (Singletons) automatically bind to the active transaction of the current asynchronous execution context:
903
+
904
+ ```javascript
905
+ // databaseController.js - Exporting global singletons
906
+ const db = require('./db-singleton');
907
+ const { DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
908
+
909
+ const customersSales = new DataBaseHandler(db, 'customers_sales');
910
+ const customersProducts = new DataBaseHandler(db, 'customers_products');
911
+
912
+ module.exports = { db, customersSales, customersProducts };
913
+ ```
914
+
915
+ ```javascript
916
+ // salesRouter.js - In your route handler
917
+ const { db, customersSales, customersProducts } = require('./databaseController');
918
+
919
+ router.post('/sales', async (req, res) => {
920
+ try {
921
+ let saleResult;
922
+ await db.transaction(async () => {
923
+ saleResult = await customersSales.insert(req.body.sale);
924
+
925
+ // Check stock and update
926
+ const product = (await customersProducts.select([{ id: req.body.productId }]))[0];
927
+ if (!product || product.stock < req.body.amount) {
928
+ // Throwing an error here triggers automatic ROLLBACK for both tables!
929
+ throw new Error('Insufficient product stock');
930
+ }
931
+
932
+ await customersProducts.update({
933
+ set: { stock: product.stock - req.body.amount },
934
+ where: { id: req.body.productId }
935
+ });
936
+ });
937
+
938
+ res.json(saleResult);
939
+ } catch (err) {
940
+ res.status(500).json({ error: err.message });
941
+ }
942
+ });
943
+ ```
944
+
945
+ ### 3. Post-Commit Hook (`db.onCommit`)
946
+
947
+ When integrating with external third-party APIs (e.g., banking APIs, payment gateways, invoice generators, SMS, emails), **never perform slow external network calls while holding database locks**.
948
+
949
+ `db.onCommit(callback)` queues actions that will run **only after the database transaction successfully commits**:
950
+
951
+ ```javascript
952
+ await db.transaction(async () => {
953
+ const sale = await customersSales.insert(payload);
954
+
955
+ // Schedule bank invoice creation: only runs if DB transaction commits!
956
+ db.onCommit(async () => {
957
+ await bankApiClient.registerInvoice(sale.insertId, invoiceData);
958
+ });
959
+ });
960
+ ```
961
+
962
+ ### 4. Route Wrapper (`db.transactional`)
963
+
964
+ Easily wrap asynchronous route handlers or service functions to run within a transaction without nesting `try/catch` or `db.transaction` boilerplate:
965
+
966
+ ```javascript
967
+ router.post('/orders', db.transactional(async (req, res) => {
968
+ const order = await ordersHandler.insert(req.body);
969
+ await itemsHandler.insert({ orderId: order.insertId, items: req.body.items });
970
+ res.json(order);
971
+ }));
972
+ ```
973
+
974
+ ### 5. Express Lazy Middleware (`db.autoTransaction`)
975
+
976
+ For maximum transparency with **zero lines changed** in your route handlers, enable the `autoTransaction` middleware in your Express app:
977
+
978
+ ```javascript
979
+ // server.js / app.js
980
+ app.use(db.autoTransaction({
981
+ methods: ['POST', 'PUT', 'DELETE', 'PATCH'], // HTTP methods to protect
982
+ lazy: true // Only opens a transaction when a write operation occurs
983
+ }));
984
+ ```
985
+
986
+ * **Lazy Allocation:** `GET` requests or routes that only execute `select` queries will not open a transaction or hold connections.
987
+ * **On-Demand Write:** As soon as an `insert`, `update`, or `delete` is called on any handler during the request, a dedicated transaction starts automatically.
988
+ * **Automatic Completion:** When `res.send()` or `res.json()` completes with HTTP status `< 400`, the transaction automatically commits. If status is `>= 400` or an exception is thrown, it rolls back automatically.
989
+
990
+ ### 6. Nested Transactions & Savepoints
991
+
992
+ The library natively supports nested transactions using MySQL `SAVEPOINT`s. Calling `db.transaction()` inside an existing transaction creates a savepoint instead of a new connection:
993
+
994
+ ```javascript
995
+ await db.transaction(async () => {
996
+ await mainHandler.insert({ status: 'started' });
997
+
998
+ try {
999
+ // Nested block runs under a SAVEPOINT
1000
+ await db.transaction(async () => {
1001
+ await subHandler.insert({ data: 'optional_task' });
1002
+ throw new Error('Non-critical sub-task failed');
1003
+ });
1004
+ } catch (e) {
1005
+ // Sub-task is rolled back to SAVEPOINT, but the main transaction can still commit!
1006
+ console.warn('Sub-task skipped:', e.message);
1007
+ }
1008
+
1009
+ await mainHandler.insert({ status: 'completed' });
1010
+ });
1011
+ ```
1012
+
1013
+ ---
1014
+
1015
+ ## Database Singleton Pattern
1016
+
1017
+ To prevent initializing redundant pool connections across various modules in a Node.js project, it is highly recommended to configure a single shared instance (Singleton).
1018
+
1019
+ Create a `db.js` file:
1020
+ ```javascript
1021
+ // db.js
1022
+ const { DataBase } = require('@areumtecnologia/mysql-db-handler');
1023
+
1024
+ const dbInstance = new DataBase({
1025
+ host: process.env.DB_HOST || 'localhost',
1026
+ user: process.env.DB_USER || 'root',
1027
+ password: process.env.DB_PASSWORD,
1028
+ database: process.env.DB_NAME,
1029
+ connectionLimit: parseInt(process.env.DB_POOL_LIMIT) || 10
1030
+ });
1031
+
1032
+ module.exports = dbInstance;
1033
+ ```
1034
+
1035
+ Import it in your business controllers/repositories:
1036
+ ```javascript
1037
+ // usersRepository.js
1038
+ const db = require('./db');
1039
+ const { DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
1040
+
1041
+ const usersHandler = new DataBaseHandler(db, 'users');
1042
+
1043
+ module.exports = {
1044
+ getUserById: (id) => usersHandler.selectBy({ id })
1045
+ };
1046
+ ```
1047
+
1048
+ ---
1049
+
1050
+ ## Error Handling Strategy
1051
+
1052
+ Database exceptions generated during execution are caught internally by the `DataBase` instance. This means that instead of raising unhandled exceptions that could crash your Node.js application, the library wraps the error.
1053
+
1054
+ Specifically, the following methods from **`DataBase`** and **`DataBaseHandler`** return an object with an `error` property when an execution error occurs:
1055
+ * `DataBase.query()`
1056
+ * `DataBaseHandler.select()` / `selectBy()`
1057
+ * `DataBaseHandler.insert()`
1058
+ * `DataBaseHandler.update()`
1059
+ * `DataBaseHandler.delete()`
1060
+ * `DataBaseHandler.selectToDatatable()`
1061
+
1062
+ ### Example: Checking for errors in queries
1063
+
1064
+ ```javascript
1065
+ // Example with Select if column doesn't exist (triggers database error)
1066
+ const users = await usersHandler.select([{ non_existent_column: 'admin' }]);
1067
+ if (users.error) {
1068
+ console.error('Failed to select users:', users.error.message);
1069
+ }
1070
+
1071
+ // Example with Insert
1072
+ const insertResult = await usersHandler.insert({ name: 'John Doe' });
1073
+ if (insertResult.error) {
1074
+ console.error('Failed to insert user:', insertResult.error.message);
1075
+ }
1076
+
1077
+ // Example with Update
1078
+ const updateResult = await usersHandler.update({
1079
+ set: { status: 'active' },
1080
+ where: { id: 999 }
1081
+ });
1082
+ if (updateResult.error) {
1083
+ console.error('Failed to update user:', updateResult.error.message);
1084
+ }
1085
+
1086
+ // Example with Delete
1087
+ const deleteResult = await usersHandler.delete({ id: 999 });
1088
+ if (deleteResult.error) {
1089
+ console.error('Failed to delete user:', deleteResult.error.message);
1090
+ }
1091
+ ```
1092
+
1093
+ > [!NOTE]
1094
+ > If you execute a `select` using valid columns but search for values that do not exist in the table (e.g. `await usersHandler.select([{ role: 'non_existent_role' }])`), this is **not** considered a database error. The query will execute successfully and return an empty array `[]` (without any `error` property). An error is only returned for actual database execution failures (such as syntax errors, missing columns, database connection drops, etc.).
1095
+
1096
+ ---
1097
+
1098
+ ## High-Scale Enterprise Micro-ORM (v2.0.0)
1099
+
1100
+ With **v2.0.0**, `@areumtecnologia/mysql-db-handler` evolves from a single-table CRUD helper into a full-fledged enterprise Data Mapper and Micro-ORM designed for high-throughput, mission-critical systems.
1101
+
1102
+ ### 1. Fluent Query Builder & Aggregations (`.first`, `.count`, `.paginate`, `raw`)
1103
+
1104
+ O Query Builder Fluente oferece encadeamento imutável, tipagem limpa e sanitização de identificadores para construir consultas SQL expressivas sem strings manuais vulneráveis:
1105
+
1106
+ #### Obter um Único Registro (`.first()`)
1107
+ Executa `LIMIT 1` e já desempacota o primeiro objeto ou retorna `null` caso nenhum registro atenda aos critérios:
1108
+ ```javascript
1109
+ const usuario = await usuariosHandler
1110
+ .where('email', 'admin@empresa.com')
1111
+ .first();
1112
+
1113
+ if (!usuario) {
1114
+ console.log('Usuário não encontrado');
1115
+ }
1116
+ ```
1117
+
1118
+ #### Contagem Direta de Registros (`.count()`)
1119
+ Retorna diretamente o valor numérico de linhas encontradas:
1120
+ ```javascript
1121
+ const totalAtivos = await usuariosHandler
1122
+ .where('status', 'ATIVO')
1123
+ .count(); // Retorna: 42
1124
+ ```
1125
+
1126
+ #### Expressões SQL Brutas Seguras (`raw`)
1127
+ Utilize a função `raw` para incorporar cálculos e funções do MySQL em `selectFields`:
1128
+ ```javascript
1129
+ const { raw } = require('@areumtecnologia/mysql-db-handler');
1130
+
1131
+ const resumo = await pedidosHandler
1132
+ .selectFields([
1133
+ 'status',
1134
+ raw('COUNT(*) AS total_pedidos'),
1135
+ raw('SUM(valor) AS montante_total'),
1136
+ raw('AVG(valor) AS ticket_medio')
1137
+ ])
1138
+ .where('criado_em', '>=', '2026-01-01')
1139
+ .groupBy('status')
1140
+ .having('montante_total > ?', [10000])
1141
+ .orderBy('montante_total', 'DESC')
1142
+ .get();
1143
+ ```
1144
+
1145
+ #### Paginação Tradicional com Metadados (`.paginate()`)
1146
+ Para telas administrativas convencionais com barra de navegação paginada (Página 1 de 10):
1147
+ ```javascript
1148
+ const resultado = await pedidosHandler.paginate({
1149
+ page: 2,
1150
+ limit: 15,
1151
+ where: [{ status: 'PAGO' }],
1152
+ orderBy: 'id DESC'
1153
+ });
1154
+
1155
+ // resultado:
1156
+ // {
1157
+ // data: [...], // Array de 15 pedidos da página 2
1158
+ // total: 150, // Total de pedidos no banco
1159
+ // page: 2, // Página atual
1160
+ // limit: 15, // Limite por página
1161
+ // totalPages: 10 // Total de páginas disponíveis
1162
+ // }
1163
+ ```
1164
+
1165
+ > [!TIP]
1166
+ > **Quando usar `paginate` vs `cursorPaginate`:**
1167
+ > * Use `.paginate()` para telas administrativas com paginação numerada tradicional em tabelas pequenas e médias (< 100.000 linhas).
1168
+ > * Use `.cursorPaginate()` (Keyset Pagination) para feeds infinitos, exportações e tabelas de alta escala com milhões de linhas, onde o custo de `OFFSET` seria proibitivo.
1169
+
1170
+ ---
1171
+
1172
+ ### 2. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)
1173
+
1174
+ #### Fluent Joins with Automatic Identifier Sanitization
1175
+ Chain `.join()`, `.leftJoin()`, `.rightJoin()`, or `.innerJoin()` directly on the query builder with support for table aliases:
1176
+
1177
+ ```javascript
1178
+ const pedidos = await pedidosHandler
1179
+ .selectFields(['pedidos.id', 'pedidos.valor', { column: 'c.nome', as: 'cliente_nome' }])
1180
+ .leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
1181
+ .where('pedidos.status', 'PAGO')
1182
+ .get();
1183
+ ```
1184
+
1185
+ #### Eager Loading (`.with()`)
1186
+ Prevent the dreaded N+1 query problem without creating massive, memory-heavy Cartesian joins in MySQL. Child entities are loaded in a single batched `WHERE foreign_key IN (...)` query and hydrated directly onto parents in memory:
1187
+
1188
+ ```javascript
1189
+ const pedidosComItens = await pedidosHandler
1190
+ .where('status', 'PAGO')
1191
+ .with('itens', {
1192
+ type: 'hasMany',
1193
+ handler: itensHandler,
1194
+ foreignKey: 'pedido_id',
1195
+ localKey: 'id',
1196
+ query: (qb) => qb.where('ativo', 1).orderBy('sequencia', 'ASC') // Filtro e ordenação customizados
1197
+ })
1198
+ .with('cliente', DataBaseHandler.belongsTo(clientesHandler, 'cliente_id', 'id'))
1199
+ .get();
1200
+
1201
+ // pedidosComItens[0].itens -> Array de itens ativos do pedido 1
1202
+ // pedidosComItens[0].cliente -> Objeto do cliente associado
1203
+ ```
1204
+
1205
+ ---
1206
+
1207
+ ### 3. Read/Write Splitting (Master + Read Replicas)
1208
+
1209
+ Scale read traffic horizontally across multiple cloud replicas (e.g. AWS Aurora, GCP Cloud SQL, Azure Database for MySQL) with automatic Round-Robin load balancing and strict transactional sticky sessions:
1210
+
1211
+ ```javascript
1212
+ const db = new DataBase({
1213
+ host: 'primary-master.internal', // Pool de Escrita (Master)
1214
+ user: 'app_user',
1215
+ password: 'secret_password',
1216
+ database: 'meu_banco',
1217
+ replicas: [
1218
+ { host: 'read-replica-1.internal' },
1219
+ { host: 'read-replica-2.internal' }
1220
+ ]
1221
+ });
1222
+
1223
+ // Queries simples de leitura são distribuídas via Round-Robin nas réplicas
1224
+ const users = await db.query('SELECT * FROM users WHERE status = ?', ['active']);
1225
+
1226
+ // Operações de mutação (INSERT, UPDATE, DELETE) vão obrigatoriamente para o Master
1227
+ await db.query('INSERT INTO users SET ?', [{ name: 'Novo Usuário' }], true);
1228
+
1229
+ // Dentro de transações, TODAS as leituras e escritas utilizam a conexão Master (evitando replication lag)
1230
+ await db.transaction(async () => {
1231
+ const user = await db.query('SELECT saldo FROM contas WHERE id = ?', [1]);
1232
+ await db.query('UPDATE contas SET saldo = saldo - 50 WHERE id = ?', [1], true);
1233
+ });
1234
+ ```
1235
+
1236
+ > [!WARNING]
1237
+ > **Atenção em Queries SQL Manuais (`db.query`):**
1238
+ > Ao executar mutações brutas sem o `DataBaseHandler` (`INSERT`, `UPDATE`, `DELETE`), o 3º argumento booleano `isWrite = true` é **obrigatório**:
1239
+ > ```javascript
1240
+ > // Se omitir o 3º argumento, um INSERT manual pode cair em uma réplica read-only!
1241
+ > await db.query('INSERT INTO logs SET ?', [data], true);
1242
+ > ```
1243
+ > No `DataBaseHandler`, todas as operações de escrita (`insert`, `insertMany`, `upsert`, `update`, `delete`) já encaminham automaticamente para o Master (`isWrite = true`).
1244
+
1245
+ ---
1246
+
1247
+ ### 4. Keyset Pagination & Memory-Safe Streaming
1248
+
1249
+ #### Keyset / Cursor Pagination (`.cursorPaginate()`)
1250
+ Traditional `OFFSET` pagination degrades significantly on large tables because MySQL must scan and discard all rows before the offset. Keyset pagination uses constant-time index seeks (`WHERE id > ? ORDER BY id ASC LIMIT ?`):
1251
+
1252
+ ```javascript
1253
+ // Primeira página
1254
+ const page1 = await produtosHandler.cursorPaginate({ limit: 20 });
1255
+ // page1: { data: [...], nextCursor: 20, prevCursor: 1, hasMore: true, limit: 20 }
1256
+
1257
+ // Próxima página (tempo constante de 1ms, mesmo após 500.000 registos)
1258
+ const page2 = await produtosHandler.cursorPaginate({
1259
+ limit: 20,
1260
+ after: page1.nextCursor
1261
+ });
1262
+ ```
1263
+
1264
+ > [!TIP]
1265
+ > **Customização da Chave Primária (`cursorColumn`):**
1266
+ > O método `.cursorPaginate()` assume por padrão a coluna `'id'`. Se a tabela utilizar outra chave de ordenação ou chave primária (`uuid`, `codigo`, `cod_produto`), declare-a explicitamente:
1267
+ > ```javascript
1268
+ > const page = await produtosHandler.cursorPaginate({
1269
+ > cursorColumn: 'codigo',
1270
+ > limit: 20,
1271
+ > after: lastCode
1272
+ > });
1273
+ > ```
1274
+
1275
+ #### Streaming & Async Iterator (`for await ... of`)
1276
+ Export millions of rows to CSV or feed an ETL pipeline without triggering Node.js Heap Out of Memory errors:
1277
+
1278
+ ```javascript
1279
+ // Iteração sob demanda com consumo constante de memória (< 30 MB)
1280
+ for await (const row of relatorioHandler.cursor({ batchSize: 1000 })) {
1281
+ processRow(row);
1282
+ }
1283
+
1284
+ // Node.js Readable Stream nativo para pipes HTTP ou arquivos
1285
+ relatorioHandler.stream({ batchSize: 500 })
1286
+ .pipe(csvTransformStream)
1287
+ .pipe(res);
1288
+ ```
1289
+
1290
+ ---
1291
+
1292
+ ### 5. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks
1293
+
1294
+ ```javascript
1295
+ const clientesHandler = new DataBaseHandler(db, 'clientes', {
1296
+ softDelete: 'deletado_em', // ou boolean true (padrão 'deletado_em')
1297
+ timestamps: true // injeta criado_em e atualizado_em automaticamente
1298
+ });
1299
+ ```
1300
+
1301
+ > [!TIP]
1302
+ > **Tabelas com Nomenclatura em Inglês (`deleted_at`, `created_at`, `updated_at`):**
1303
+ > Por padrão, a biblioteca assume as colunas em português (`deletado_em`, `criado_em`, `atualizado_em`). Se suas tabelas utilizam nomenclaturas em inglês, configure o objeto explicitamente:
1304
+ > ```javascript
1305
+ > const clientesHandler = new DataBaseHandler(db, 'customers_leads', {
1306
+ > softDelete: 'deleted_at',
1307
+ > timestamps: {
1308
+ > createdAt: 'created_at',
1309
+ > updatedAt: 'updated_at'
1310
+ > }
1311
+ > });
1312
+ > ```
1313
+
1314
+ #### Soft Deletes
1315
+ * `.delete(where)`: Automaticamente executa `UPDATE clientes SET deletado_em = NOW() WHERE ...`.
1316
+ * Consultas padrão (`select`, `get`, `first`, `paginate`, `selectToDatatable`) injetam automaticamente `AND deletado_em IS NULL`.
1317
+ * `.withTrashed()`: Desativa o filtro para retornar registos ativos e deletados.
1318
+ * `.onlyTrashed()`: Retorna exclusivamente registos na lixeira (`deletado_em IS NOT NULL`).
1319
+ * `.restore(where)`: Restaura registos setando `deletado_em = NULL`.
1320
+ * `.forceDelete(where)`: Executa `DELETE FROM` físico no MySQL.
1321
+
1322
+ #### Lifecycle Hooks
1323
+ Intercepte mutações antes ou depois de sua persistência:
1324
+
1325
+ ```javascript
1326
+ clientesHandler
1327
+ .beforeInsert(async (data) => {
1328
+ data.slug = slugify(data.nome);
1329
+ })
1330
+ .afterInsert(async (result, data) => {
1331
+ await logAudit('CLIENT_CREATED', result.insertId);
1332
+ })
1333
+ .beforeUpdate(async (set, where) => {
1334
+ validateBusinessRules(set);
1335
+ })
1336
+ .afterDelete(async (result, where) => {
1337
+ await notifyService(where);
1338
+ });
1339
+ ```
1340
+
1341
+ ---
1342
+
1343
+ ### 6. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking
1344
+
1345
+ ```javascript
1346
+ const usuariosHandler = new DataBaseHandler(db, 'usuarios', {
1347
+ autoStripUnknown: true, // Remove propriedades desconhecidas do payload
1348
+ hiddenFields: ['senha_hash', 'token_recuperacao'] // Oculta campos confidenciais das consultas
1349
+ });
1350
+
1351
+ // Prevenção de Mass Assignment e ER_BAD_FIELD_ERROR vindo de requisições web:
1352
+ await usuariosHandler.insert({
1353
+ nome: 'Carlos',
1354
+ email: 'carlos@empresa.com',
1355
+ senha_hash: 'hash_seguro',
1356
+ isAdminFake: true, // Ignorado silenciosamente pois não existe no schema
1357
+ payload_sujo: 'qualquer_coisa' // Ignorado silenciosamente
1358
+ });
1359
+
1360
+ // Consultas nunca retornam senha_hash ou token_recuperacao acidentalmente:
1361
+ const usuario = await usuariosHandler.where('id', 1).first();
1362
+ console.log(usuario.senha_hash); // undefined
1363
+ ```
1364
+
1365
+ ---
1366
+
1367
+ ## Contributing
1368
+
1369
+ Contributions are welcome! Please open an issue or submit a pull request.
1370
+
1371
+ 1. Fork the repository
1372
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
1373
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
1374
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
1375
+ 5. Open a Pull Request
1376
+
1377
+ ---
1378
+
1379
+ ## License
1380
+
1381
+ MIT