@areumtecnologia/mysql-db-handler 2.1.0 → 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 +1381 -1224
- package/index.d.ts +93 -6
- package/index.js +29 -16
- package/lib/databaseHandler.js +47 -24
- package/lib/operators.js +146 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,1224 +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
|
-
* [
|
|
18
|
-
* [
|
|
19
|
-
* [
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
* [
|
|
25
|
-
* [
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
* [
|
|
30
|
-
|
|
31
|
-
* [
|
|
32
|
-
* [
|
|
33
|
-
* [
|
|
34
|
-
* [
|
|
35
|
-
* [
|
|
36
|
-
* [
|
|
37
|
-
|
|
38
|
-
* [
|
|
39
|
-
* [
|
|
40
|
-
* [
|
|
41
|
-
* [
|
|
42
|
-
* [
|
|
43
|
-
* [
|
|
44
|
-
* [
|
|
45
|
-
|
|
46
|
-
* [
|
|
47
|
-
* [
|
|
48
|
-
* [
|
|
49
|
-
* [
|
|
50
|
-
* [
|
|
51
|
-
* [
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
* [
|
|
56
|
-
* [
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
*
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
* **
|
|
69
|
-
* **
|
|
70
|
-
* **
|
|
71
|
-
* **
|
|
72
|
-
* **
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
```
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
>
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
//
|
|
187
|
-
//
|
|
188
|
-
```
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
*
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
###
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
```javascript
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
//
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
nome
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
const
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
//
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
```
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
{
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
});
|
|
786
|
-
```
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
```javascript
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
```
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
const
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
}
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
###
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
```javascript
|
|
952
|
-
|
|
953
|
-
.
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
});
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
//
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
//
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
---
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
```javascript
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
.
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
```
|
|
1047
|
-
|
|
1048
|
-
---
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
####
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
.
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
```javascript
|
|
1189
|
-
const
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
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
|