@areumtecnologia/mysql-db-handler 1.0.14 → 2.0.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.
@@ -1,7 +1,9 @@
1
+ const stream = require('node:stream');
2
+
1
3
  const ALLOWED_OPERATORS = new Set([
2
4
  '=', '!=', '<>', '>', '>=', '<', '<=',
3
5
  'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
4
- 'REGEXP', 'NOT REGEXP', 'IS', 'IS NOT', 'BETWEEN'
6
+ 'REGEXP', 'NOT REGEXP', 'IS', 'IS NOT', 'BETWEEN', 'NOT BETWEEN'
5
7
  ]);
6
8
 
7
9
  function sanitizeOperator(op, defaultOp = '=') {
@@ -12,48 +14,217 @@ function sanitizeOperator(op, defaultOp = '=') {
12
14
 
13
15
  function sanitizeIdentifier(name) {
14
16
  if (!name || typeof name !== 'string') return '';
15
- return name.replace(/`/g, '');
17
+ return name.replace(/`/g, '').trim();
16
18
  }
17
19
 
18
20
  function safeTable(tableName) {
19
21
  if (!tableName || typeof tableName !== 'string') return '';
20
- // Se contiver '.', protege cada segmento (ex: `meubanco`.`minhatabela`)
21
22
  return tableName.split('.').map(part => `\`${sanitizeIdentifier(part)}\``).join('.');
22
23
  }
23
24
 
25
+ function safeTableWithAlias(tableName) {
26
+ if (!tableName || typeof tableName !== 'string') return '';
27
+ const parts = tableName.trim().split(/\s+(?:AS\s+)?/i);
28
+ if (parts.length === 2) {
29
+ return `${safeTable(parts[0])} AS \`${sanitizeIdentifier(parts[1])}\``;
30
+ }
31
+ return safeTable(tableName);
32
+ }
33
+
24
34
  function safeColumn(columnName) {
25
35
  if (!columnName || typeof columnName !== 'string') return '';
26
- // Se contiver '.', protege cada segmento (ex: `minhatabela`.`minhacoluna`)
27
- return columnName.split('.').map(part => `\`${sanitizeIdentifier(part)}\``).join('.');
36
+ const trimmed = columnName.trim();
37
+ if (trimmed === '*') return '*';
38
+ return trimmed.split('.').map(part => part === '*' ? '*' : `\`${sanitizeIdentifier(part)}\``).join('.');
39
+ }
40
+
41
+ /**
42
+ * Sanitiza listas de colunas para GROUP BY ou ORDER BY (suportando direção ASC/DESC em ORDER BY).
43
+ */
44
+ function sanitizeClauseList(clause, allowDirection = false) {
45
+ if (!clause) return '';
46
+ const items = Array.isArray(clause) ? clause : String(clause).split(',');
47
+ const sanitized = [];
48
+
49
+ for (const rawItem of items) {
50
+ const item = String(rawItem).trim();
51
+ if (!item) continue;
52
+
53
+ if (allowDirection) {
54
+ const parts = item.split(/\s+/);
55
+ const col = safeColumn(parts[0]);
56
+ const dir = parts[1] && ['ASC', 'DESC'].includes(parts[1].toUpperCase()) ? ` ${parts[1].toUpperCase()}` : '';
57
+ if (col) sanitized.push(`${col}${dir}`);
58
+ } else {
59
+ const col = safeColumn(item);
60
+ if (col) sanitized.push(col);
61
+ }
62
+ }
63
+ return sanitized.join(', ');
64
+ }
65
+
66
+ /**
67
+ * Permite expressões SQL seguras quando encapsuladas explicitamente.
68
+ */
69
+ function raw(sql) {
70
+ return { __isRawSql: true, sql: String(sql) };
28
71
  }
29
72
 
30
73
  class DatabaseHandler {
31
- constructor(database, table, expression = '') {
74
+ constructor(database, table, expressionOrOptions = '') {
32
75
  this.db = database;
33
76
  this.table = table;
34
77
  this.debug = false;
35
- this.expression = expression;
36
78
  this.onError = null;
79
+
80
+ if (typeof expressionOrOptions === 'string') {
81
+ this.expression = expressionOrOptions;
82
+ this.options = {};
83
+ } else if (expressionOrOptions && typeof expressionOrOptions === 'object') {
84
+ this.expression = expressionOrOptions.expression || '';
85
+ this.options = { ...expressionOrOptions };
86
+ } else {
87
+ this.expression = '';
88
+ this.options = {};
89
+ }
90
+
91
+ this.softDelete = this.options.softDelete || false;
92
+ this.timestamps = this.options.timestamps || false;
93
+ this.hiddenFields = Array.isArray(this.options.hiddenFields) ? [...this.options.hiddenFields] : [];
94
+ this.autoStripUnknown = Boolean(this.options.autoStripUnknown);
95
+
96
+ this._hooks = {
97
+ beforeInsert: [],
98
+ afterInsert: [],
99
+ beforeUpdate: [],
100
+ afterUpdate: [],
101
+ beforeDelete: [],
102
+ afterDelete: []
103
+ };
104
+
105
+ // Estado interno para o Query Builder Fluente
106
+ this._resetBuilder();
107
+ }
108
+
109
+ static raw(sql) {
110
+ return raw(sql);
111
+ }
112
+
113
+ static hasMany(handler, foreignKey, localKey = 'id') {
114
+ return { type: 'hasMany', handler, foreignKey, localKey };
115
+ }
116
+
117
+ static belongsTo(handler, foreignKey, localKey = 'id') {
118
+ return { type: 'belongsTo', handler, foreignKey, localKey };
119
+ }
120
+
121
+ static hasOne(handler, foreignKey, localKey = 'id') {
122
+ return { type: 'hasOne', handler, foreignKey, localKey };
123
+ }
124
+
125
+ _resetBuilder() {
126
+ this._qb = {
127
+ fields: [],
128
+ joins: [],
129
+ where: [],
130
+ groupBy: [],
131
+ having: null,
132
+ orderBy: [],
133
+ limit: undefined,
134
+ offset: undefined,
135
+ relations: [],
136
+ withTrashed: false,
137
+ onlyTrashed: false
138
+ };
139
+ }
140
+
141
+ _cloneWithBuilder(modifierFn) {
142
+ const clone = new DatabaseHandler(this.db, this.table, {
143
+ expression: this.expression,
144
+ softDelete: this.softDelete,
145
+ timestamps: this.timestamps,
146
+ hiddenFields: this.hiddenFields,
147
+ autoStripUnknown: this.autoStripUnknown
148
+ });
149
+ clone.debug = this.debug;
150
+ clone.onError = this.onError;
151
+ clone._hooks = {
152
+ beforeInsert: [...this._hooks.beforeInsert],
153
+ afterInsert: [...this._hooks.afterInsert],
154
+ beforeUpdate: [...this._hooks.beforeUpdate],
155
+ afterUpdate: [...this._hooks.afterUpdate],
156
+ beforeDelete: [...this._hooks.beforeDelete],
157
+ afterDelete: [...this._hooks.afterDelete]
158
+ };
159
+ clone._qb = {
160
+ fields: [...this._qb.fields],
161
+ joins: [...this._qb.joins],
162
+ where: [...this._qb.where],
163
+ groupBy: [...this._qb.groupBy],
164
+ having: this._qb.having ? { ...this._qb.having } : null,
165
+ orderBy: [...this._qb.orderBy],
166
+ limit: this._qb.limit,
167
+ offset: this._qb.offset,
168
+ relations: [...this._qb.relations],
169
+ withTrashed: this._qb.withTrashed,
170
+ onlyTrashed: this._qb.onlyTrashed
171
+ };
172
+ if (typeof modifierFn === 'function') {
173
+ modifierFn(clone._qb);
174
+ }
175
+ return clone;
37
176
  }
38
177
 
39
178
  _safeTable() {
40
179
  return safeTable(this.table);
41
180
  }
42
181
 
43
- async executeQuery(sql, params, isWrite = false) {
44
- const rows = await this.db.query(sql, params, isWrite);
45
- return rows;
182
+ _formatExpression() {
183
+ if (!this.expression || typeof this.expression !== 'string') return '';
184
+ const cleaned = this.expression.trim().replace(/^,\s*/, '');
185
+ return cleaned ? `, ${cleaned}` : '';
186
+ }
187
+
188
+ _buildSelectColumns(customFields = []) {
189
+ const expr = this._formatExpression();
190
+ if (!customFields || customFields.length === 0) {
191
+ return `*${expr}`;
192
+ }
193
+
194
+ const formatted = customFields.map(field => {
195
+ if (field && typeof field === 'object') {
196
+ if (field.__isRawSql) return field.sql;
197
+ if (field.raw) return String(field.raw);
198
+ if (field.column && field.as) {
199
+ return `${safeColumn(field.column)} AS \`${sanitizeIdentifier(field.as)}\``;
200
+ }
201
+ }
202
+ return safeColumn(String(field));
203
+ }).filter(Boolean);
204
+
205
+ const base = formatted.length > 0 ? formatted.join(', ') : '*';
206
+ return `${base}${expr}`;
207
+ }
208
+
209
+ async executeQuery(sql, params, isWrite = false, options = {}) {
210
+ if (this.debug) {
211
+ console.debug('[SQL Debug]:', sql, params);
212
+ }
213
+ return await this.db.query(sql, params, isWrite, { ...options, table: this.table });
46
214
  }
47
215
 
48
- /**
49
- * Clones this handler bound to a specific transaction or database executor.
50
- * @param {Object} txOrDb - Transaction context or database instance.
51
- * @returns {DatabaseHandler} A new handler instance.
52
- */
53
216
  withTransaction(txOrDb) {
54
- const handler = new DatabaseHandler(txOrDb, this.table, this.expression);
217
+ const executor = (txOrDb && txOrDb.db) ? txOrDb.db : txOrDb;
218
+ const handler = new DatabaseHandler(executor, this.table, {
219
+ expression: this.expression,
220
+ softDelete: this.softDelete,
221
+ timestamps: this.timestamps,
222
+ hiddenFields: this.hiddenFields,
223
+ autoStripUnknown: this.autoStripUnknown
224
+ });
55
225
  handler.debug = this.debug;
56
226
  handler.onError = this.onError;
227
+ handler._hooks = { ...this._hooks };
57
228
  return handler;
58
229
  }
59
230
 
@@ -61,158 +232,709 @@ class DatabaseHandler {
61
232
  return await this.db.getTableSchema(this.table);
62
233
  }
63
234
 
64
- /**
65
- * @private
66
- * Converte um objeto "achatado" (form-urlencoded) em um objeto aninhado (JSON).
67
- * Ex: { 'columns[0][data]': 'id' } => { columns: [{ data: 'id' }] }
68
- * Protegido contra Prototype Pollution (CWE-1321).
69
- */
235
+ // =========================================================================
236
+ // HOOKS DE CICLO DE VIDA (Life-cycle Hooks)
237
+ // =========================================================================
238
+
239
+ beforeInsert(fn) {
240
+ if (typeof fn === 'function') this._hooks.beforeInsert.push(fn);
241
+ return this;
242
+ }
243
+
244
+ afterInsert(fn) {
245
+ if (typeof fn === 'function') this._hooks.afterInsert.push(fn);
246
+ return this;
247
+ }
248
+
249
+ beforeUpdate(fn) {
250
+ if (typeof fn === 'function') this._hooks.beforeUpdate.push(fn);
251
+ return this;
252
+ }
253
+
254
+ afterUpdate(fn) {
255
+ if (typeof fn === 'function') this._hooks.afterUpdate.push(fn);
256
+ return this;
257
+ }
258
+
259
+ beforeDelete(fn) {
260
+ if (typeof fn === 'function') this._hooks.beforeDelete.push(fn);
261
+ return this;
262
+ }
263
+
264
+ afterDelete(fn) {
265
+ if (typeof fn === 'function') this._hooks.afterDelete.push(fn);
266
+ return this;
267
+ }
268
+
269
+ // =========================================================================
270
+ // SOFT DELETES & ESCOPO TRASHED
271
+ // =========================================================================
272
+
273
+ _getSoftDeleteColumn() {
274
+ if (!this.softDelete) return null;
275
+ return typeof this.softDelete === 'string' ? this.softDelete : 'deletado_em';
276
+ }
277
+
278
+ withTrashed() {
279
+ return this._cloneWithBuilder(qb => {
280
+ qb.withTrashed = true;
281
+ qb.onlyTrashed = false;
282
+ });
283
+ }
284
+
285
+ onlyTrashed() {
286
+ return this._cloneWithBuilder(qb => {
287
+ qb.withTrashed = false;
288
+ qb.onlyTrashed = true;
289
+ });
290
+ }
291
+
292
+ // =========================================================================
293
+ // QUERY BUILDER FLUENTE (Imutável por encadeamento)
294
+ // =========================================================================
295
+
296
+ selectFields(fields) {
297
+ const list = Array.isArray(fields) ? fields : [fields];
298
+ return this._cloneWithBuilder(qb => {
299
+ qb.fields.push(...list);
300
+ });
301
+ }
302
+
303
+ // Joins Fluentes
304
+ join(table, first, operator, second) {
305
+ return this._cloneWithBuilder(qb => {
306
+ qb.joins.push({ type: 'INNER JOIN', table, first, operator, second });
307
+ });
308
+ }
309
+
310
+ innerJoin(table, first, operator, second) {
311
+ return this.join(table, first, operator, second);
312
+ }
313
+
314
+ leftJoin(table, first, operator, second) {
315
+ return this._cloneWithBuilder(qb => {
316
+ qb.joins.push({ type: 'LEFT JOIN', table, first, operator, second });
317
+ });
318
+ }
319
+
320
+ rightJoin(table, first, operator, second) {
321
+ return this._cloneWithBuilder(qb => {
322
+ qb.joins.push({ type: 'RIGHT JOIN', table, first, operator, second });
323
+ });
324
+ }
325
+
326
+ _buildJoinClauses(joins) {
327
+ if (!Array.isArray(joins) || joins.length === 0) return '';
328
+ const clauses = joins.map(j => {
329
+ const tableSql = safeTableWithAlias(j.table);
330
+ const firstCol = safeColumn(j.first);
331
+ const op = sanitizeOperator(j.operator, '=');
332
+ const secondCol = safeColumn(j.second);
333
+ return `${j.type} ${tableSql} ON ${firstCol} ${op} ${secondCol}`;
334
+ });
335
+ return ` ${clauses.join(' ')}`;
336
+ }
337
+
338
+ // Eager Loading (.with)
339
+ with(relationName, relationOrHandler) {
340
+ return this._cloneWithBuilder(qb => {
341
+ let config;
342
+ if (relationOrHandler instanceof DatabaseHandler) {
343
+ config = {
344
+ name: relationName,
345
+ type: 'hasMany',
346
+ handler: relationOrHandler,
347
+ foreignKey: `${this.table.replace(/s$/, '')}_id`,
348
+ localKey: 'id'
349
+ };
350
+ } else if (typeof relationOrHandler === 'object' && relationOrHandler !== null) {
351
+ config = {
352
+ name: relationName,
353
+ type: relationOrHandler.type || relationOrHandler.relationType || 'hasMany',
354
+ handler: relationOrHandler.handler,
355
+ foreignKey: relationOrHandler.foreignKey,
356
+ localKey: relationOrHandler.localKey || 'id',
357
+ query: relationOrHandler.query
358
+ };
359
+ } else {
360
+ throw new Error(`Definição de relação inválida para "${relationName}"`);
361
+ }
362
+ qb.relations.push(config);
363
+ });
364
+ }
365
+
366
+ async _applyEagerLoading(rows, relations) {
367
+ if (!Array.isArray(rows) || rows.length === 0 || !Array.isArray(relations) || relations.length === 0) {
368
+ return rows;
369
+ }
370
+
371
+ for (const rel of relations) {
372
+ const { name, type, handler, foreignKey, localKey, query } = rel;
373
+ if (!handler || !foreignKey || !localKey) continue;
374
+
375
+ if (type === 'hasMany' || type === 'hasOne') {
376
+ const parentKeys = [...new Set(rows.map(r => r[localKey]).filter(k => k !== undefined && k !== null))];
377
+ if (parentKeys.length === 0) {
378
+ rows.forEach(r => {
379
+ r[name] = type === 'hasMany' ? [] : null;
380
+ });
381
+ continue;
382
+ }
383
+
384
+ let q = handler.where({ [foreignKey]: parentKeys });
385
+ if (typeof query === 'function') {
386
+ q = query(q) || q;
387
+ }
388
+ const childRecords = await q.get();
389
+ const safeChildren = Array.isArray(childRecords) ? childRecords : [];
390
+
391
+ const grouped = new Map();
392
+ for (const child of safeChildren) {
393
+ const fkVal = child[foreignKey];
394
+ if (!grouped.has(fkVal)) {
395
+ grouped.set(fkVal, []);
396
+ }
397
+ grouped.get(fkVal).push(child);
398
+ }
399
+
400
+ for (const row of rows) {
401
+ const lkVal = row[localKey];
402
+ const matched = grouped.get(lkVal) || [];
403
+ row[name] = type === 'hasMany' ? matched : (matched[0] || null);
404
+ }
405
+ } else if (type === 'belongsTo') {
406
+ const fkValues = [...new Set(rows.map(r => r[foreignKey]).filter(k => k !== undefined && k !== null))];
407
+ if (fkValues.length === 0) {
408
+ rows.forEach(r => {
409
+ r[name] = null;
410
+ });
411
+ continue;
412
+ }
413
+
414
+ let q = handler.where({ [localKey]: fkValues });
415
+ if (typeof query === 'function') {
416
+ q = query(q) || q;
417
+ }
418
+ const targetRecords = await q.get();
419
+ const safeTargets = Array.isArray(targetRecords) ? targetRecords : [];
420
+
421
+ const map = new Map();
422
+ for (const target of safeTargets) {
423
+ map.set(target[localKey], target);
424
+ }
425
+
426
+ for (const row of rows) {
427
+ const fkVal = row[foreignKey];
428
+ row[name] = map.get(fkVal) || null;
429
+ }
430
+ }
431
+ }
432
+
433
+ return rows;
434
+ }
435
+
436
+ where(condition, operatorOrValue, maybeValue) {
437
+ return this._cloneWithBuilder(qb => {
438
+ if (qb.where.length > 0) {
439
+ qb.where.push('AND');
440
+ }
441
+ if (typeof condition === 'string') {
442
+ if (arguments.length === 2) {
443
+ qb.where.push({ [condition]: operatorOrValue, operator: '=' });
444
+ } else {
445
+ qb.where.push({ [condition]: maybeValue, operator: operatorOrValue });
446
+ }
447
+ } else if (Array.isArray(condition)) {
448
+ qb.where.push(...condition);
449
+ } else if (typeof condition === 'object' && condition !== null) {
450
+ for (const [k, v] of Object.entries(condition)) {
451
+ if (qb.where.length > 0 && qb.where[qb.where.length - 1] !== 'AND' && qb.where[qb.where.length - 1] !== 'OR') {
452
+ qb.where.push('AND');
453
+ }
454
+ qb.where.push({ [k]: v, operator: '=' });
455
+ }
456
+ }
457
+ });
458
+ }
459
+
460
+ orWhere(condition, operatorOrValue, maybeValue) {
461
+ return this._cloneWithBuilder(qb => {
462
+ if (qb.where.length > 0) {
463
+ qb.where.push('OR');
464
+ }
465
+ if (typeof condition === 'string') {
466
+ if (arguments.length === 2) {
467
+ qb.where.push({ [condition]: operatorOrValue, operator: '=' });
468
+ } else {
469
+ qb.where.push({ [condition]: maybeValue, operator: operatorOrValue });
470
+ }
471
+ } else if (typeof condition === 'object' && condition !== null) {
472
+ qb.where.push(condition);
473
+ }
474
+ });
475
+ }
476
+
477
+ groupBy(cols) {
478
+ const list = Array.isArray(cols) ? cols : [cols];
479
+ return this._cloneWithBuilder(qb => qb.groupBy.push(...list));
480
+ }
481
+
482
+ having(sql, bindings = []) {
483
+ return this._cloneWithBuilder(qb => {
484
+ qb.having = { sql, bindings: Array.isArray(bindings) ? bindings : [bindings] };
485
+ });
486
+ }
487
+
488
+ orderBy(column, dir = 'ASC') {
489
+ return this._cloneWithBuilder(qb => {
490
+ const safeDir = String(dir).toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
491
+ qb.orderBy.push(`${column} ${safeDir}`);
492
+ });
493
+ }
494
+
495
+ limit(count) {
496
+ return this._cloneWithBuilder(qb => {
497
+ qb.limit = parseInt(count, 10);
498
+ });
499
+ }
500
+
501
+ offset(count) {
502
+ return this._cloneWithBuilder(qb => {
503
+ qb.offset = parseInt(count, 10);
504
+ });
505
+ }
506
+
507
+ async get() {
508
+ const rows = await this.select(this._qb.where, {
509
+ FIELDS: this._qb.fields,
510
+ JOINS: this._qb.joins,
511
+ GROUPBY: this._qb.groupBy.length ? this._qb.groupBy : undefined,
512
+ HAVING: this._qb.having || undefined,
513
+ ORDERBY: this._qb.orderBy.length ? this._qb.orderBy : undefined,
514
+ LIMIT: this._qb.limit,
515
+ OFFSET: this._qb.offset,
516
+ WITH_TRASHED: this._qb.withTrashed,
517
+ ONLY_TRASHED: this._qb.onlyTrashed
518
+ });
519
+ if (rows && rows.error) return rows;
520
+ if (Array.isArray(rows) && this._qb.relations.length > 0) {
521
+ await this._applyEagerLoading(rows, this._qb.relations);
522
+ }
523
+ return this._maskHiddenFields(rows);
524
+ }
525
+
526
+ async first() {
527
+ const rows = await this.limit(1).get();
528
+ if (rows && rows.error) return rows;
529
+ return Array.isArray(rows) ? (rows[0] || null) : null;
530
+ }
531
+
532
+ async count(column = '*') {
533
+ const softCol = this._getSoftDeleteColumn();
534
+ const whereConditions = [...this._qb.where];
535
+ if (softCol && !this._qb.withTrashed) {
536
+ if (whereConditions.length > 0) whereConditions.push('AND');
537
+ if (this._qb.onlyTrashed) {
538
+ whereConditions.push({ [softCol]: null, operator: 'IS NOT' });
539
+ } else {
540
+ whereConditions.push({ [softCol]: null, operator: 'IS' });
541
+ }
542
+ }
543
+
544
+ const { sql: whereSql, bindings } = this._buildWhereClause(whereConditions);
545
+ const whereClause = whereSql ? ` WHERE ${whereSql}` : '';
546
+ const joinClause = this._buildJoinClauses(this._qb.joins);
547
+ const colSql = column === '*' ? '*' : safeColumn(column);
548
+ const sql = `SELECT COUNT(${colSql}) AS total FROM ${this._safeTable()}${joinClause}${whereClause}`;
549
+ const result = await this.executeQuery(sql, bindings);
550
+ if (result && result.error) return result;
551
+ return Number(result?.[0]?.total || 0);
552
+ }
553
+
554
+ // Keyset Pagination (.cursorPaginate)
555
+ async cursorPaginate(options = {}) {
556
+ const cursorCol = options.cursorColumn || 'id';
557
+ const limit = Math.max(1, parseInt(options.limit, 10) || 20);
558
+ const direction = String(options.direction || 'ASC').toUpperCase() === 'DESC' ? 'DESC' : 'ASC';
559
+ const after = options.after !== undefined ? options.after : null;
560
+ const before = options.before !== undefined ? options.before : null;
561
+
562
+ let qb = this._cloneWithBuilder();
563
+ if (after !== null) {
564
+ const op = direction === 'ASC' ? '>' : '<';
565
+ qb = qb.where(cursorCol, op, after);
566
+ } else if (before !== null) {
567
+ const op = direction === 'ASC' ? '<' : '>';
568
+ qb = qb.where(cursorCol, op, before);
569
+ }
570
+
571
+ qb = qb.orderBy(cursorCol, direction).limit(limit + 1);
572
+ const rows = await qb.get();
573
+
574
+ if (rows && rows.error) return rows;
575
+
576
+ const safeRows = Array.isArray(rows) ? rows : [];
577
+ const hasMore = safeRows.length > limit;
578
+ if (hasMore) {
579
+ safeRows.pop();
580
+ }
581
+
582
+ const nextCursor = safeRows.length > 0 ? safeRows[safeRows.length - 1][cursorCol] : null;
583
+ const prevCursor = safeRows.length > 0 ? safeRows[0][cursorCol] : null;
584
+
585
+ return {
586
+ data: safeRows,
587
+ nextCursor,
588
+ prevCursor,
589
+ hasMore,
590
+ limit
591
+ };
592
+ }
593
+
594
+ // Streaming & Async Generator (.cursor & .stream)
595
+ async *cursor({ batchSize = 1000, cursorColumn = 'id' } = {}) {
596
+ let lastId = null;
597
+ const batch = Math.max(1, parseInt(batchSize, 10) || 1000);
598
+
599
+ while (true) {
600
+ let q = this._cloneWithBuilder();
601
+ if (lastId !== null) {
602
+ q = q.where(cursorColumn, '>', lastId);
603
+ }
604
+ q = q.orderBy(cursorColumn, 'ASC').limit(batch);
605
+ const rows = await q.get();
606
+
607
+ if (!Array.isArray(rows) || rows.length === 0) {
608
+ break;
609
+ }
610
+
611
+ for (const row of rows) {
612
+ yield row;
613
+ lastId = row[cursorColumn];
614
+ }
615
+
616
+ if (rows.length < batch) {
617
+ break;
618
+ }
619
+ }
620
+ }
621
+
622
+ stream(options = {}) {
623
+ return stream.Readable.from(this.cursor(options));
624
+ }
625
+
626
+ // =========================================================================
627
+ // MÉTODOS CORE E UTILITÁRIOS INTERNOS
628
+ // =========================================================================
629
+
70
630
  _hydrateObject(flatObject) {
631
+ if (!flatObject || typeof flatObject !== 'object') return {};
71
632
  const result = {};
72
- for (const key in flatObject) {
73
- if (!Object.prototype.hasOwnProperty.call(flatObject, key)) continue;
74
- const keys = key.match(/[^[\]']+/g); // Extrai chaves como ['columns', '0', 'data']
75
- if (!keys) continue;
76
633
 
77
- // Bloqueia poluição de protótipo
78
- if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
634
+ for (const key of Object.keys(flatObject)) {
635
+ if (!key.includes('[')) {
636
+ if (key !== '__proto__' && key !== 'constructor' && key !== 'prototype') {
637
+ result[key] = flatObject[key];
638
+ }
639
+ continue;
640
+ }
641
+
642
+ const keys = key.match(/[^[\]']+/g);
643
+ if (!keys || keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
79
644
  continue;
80
645
  }
81
646
 
82
647
  let current = result;
83
- while (keys.length > 1) {
84
- const k = keys.shift();
85
- current[k] = current[k] || (isNaN(keys[0]) ? {} : []);
648
+ for (let i = 0; i < keys.length - 1; i++) {
649
+ const k = keys[i];
650
+ const nextKey = keys[i + 1];
651
+ if (current[k] === undefined) {
652
+ current[k] = !isNaN(nextKey) ? [] : {};
653
+ }
86
654
  current = current[k];
87
655
  }
88
- current[keys[0]] = flatObject[key];
656
+ current[keys[keys.length - 1]] = flatObject[key];
89
657
  }
90
658
  return result;
91
659
  }
92
660
 
93
- _parseStrictCondition(strictCondition) {
94
- if (!strictCondition || !Array.isArray(strictCondition) || strictCondition.length === 0) {
95
- return { sql: '', bindings: [] };
661
+ _maskHiddenFields(rows) {
662
+ if (!this.hiddenFields || this.hiddenFields.length === 0 || !rows) {
663
+ return rows;
96
664
  }
97
- const clauses = [];
98
- const bindings = [];
99
- for (const item of strictCondition) {
100
- if (typeof item === 'string') {
101
- const upper = item.toUpperCase().trim();
102
- // Operadores lógicos (AND / OR) válidos são inseridos como-is
103
- if (upper === 'AND' || upper === 'OR') {
104
- clauses.push(upper);
105
- }
106
- } else if (typeof item === 'object' && item !== null) {
107
- const key = Object.keys(item).find(k => k.toLowerCase() !== 'operator');
108
- if (!key) continue;
109
- const cleanKey = sanitizeIdentifier(key);
110
- const value = item[key];
111
- let operator = sanitizeOperator(item.operator, '=');
112
-
113
- // Suporte a arrays => IN / NOT IN (consistente com _buildWhereClause)
114
- if (Array.isArray(value) && operator === '=') {
115
- operator = 'IN';
116
- }
117
665
 
118
- if (Array.isArray(value) && (operator === 'IN' || operator === 'NOT IN')) {
119
- if (value.length === 0) {
120
- clauses.push(operator === 'IN' ? '1 = 0' : '1 = 1');
121
- } else {
122
- const placeholders = value.map(() => '?').join(', ');
123
- clauses.push(`\`${cleanKey}\` ${operator} (${placeholders})`);
124
- bindings.push(...value);
125
- }
126
- } else {
127
- clauses.push(`\`${cleanKey}\` ${operator} ?`);
128
- bindings.push(value);
129
- }
666
+ const hiddenSet = new Set(this.hiddenFields);
667
+ const maskRow = (row) => {
668
+ if (!row || typeof row !== 'object') return row;
669
+ for (const h of hiddenSet) {
670
+ delete row[h];
130
671
  }
672
+ return row;
673
+ };
674
+
675
+ if (Array.isArray(rows)) {
676
+ rows.forEach(maskRow);
677
+ return rows;
131
678
  }
132
- // Junta com espaço para preservar operadores AND/OR intercalados.
133
- return { sql: `(${clauses.join(' ')})`, bindings };
679
+ return maskRow(rows);
134
680
  }
135
681
 
136
- /**
137
- * @private
138
- * Constrói a cláusula WHERE (sem a palavra-chave WHERE) e seus bindings associados.
139
- * @param {Object|Array} where - Condições do where.
140
- * @param {boolean} useRegex - Se deve usar REGEXP por padrão (para compatibilidade com update).
141
- * @returns {{ sql: string, bindings: Array }}
142
- */
143
- _buildWhereClause(where, useRegex = false) {
682
+ async _stripUnknownFields(data) {
683
+ if (!this.autoStripUnknown || !data || typeof data !== 'object') {
684
+ return data;
685
+ }
686
+
687
+ const schema = await this.getSchema();
688
+ if (!Array.isArray(schema) || schema.length === 0) {
689
+ return data;
690
+ }
691
+
692
+ const validCols = new Set(
693
+ schema.map(col => (col.COLUMN_NAME || col.column_name || '').toLowerCase()).filter(Boolean)
694
+ );
695
+
696
+ if (validCols.size === 0) return data;
697
+
698
+ if (Array.isArray(data)) {
699
+ return data.map(item => this._stripSingleObject(item, validCols));
700
+ }
701
+ return this._stripSingleObject(data, validCols);
702
+ }
703
+
704
+ _stripSingleObject(obj, validCols) {
705
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return obj;
706
+ const cleaned = {};
707
+ for (const [key, val] of Object.entries(obj)) {
708
+ if (validCols.has(key.toLowerCase())) {
709
+ cleaned[key] = val;
710
+ }
711
+ }
712
+ return cleaned;
713
+ }
714
+
715
+ _applyTimestampsOnInsert(data) {
716
+ if (!this.timestamps || !data || typeof data !== 'object') return data;
717
+ const now = new Date();
718
+ const createdCol = typeof this.timestamps === 'object' && this.timestamps.createdAt ? this.timestamps.createdAt : 'criado_em';
719
+ const updatedCol = typeof this.timestamps === 'object' && this.timestamps.updatedAt ? this.timestamps.updatedAt : 'atualizado_em';
720
+
721
+ if (Array.isArray(data)) {
722
+ data.forEach(item => {
723
+ if (item && typeof item === 'object') {
724
+ if (item[createdCol] === undefined) item[createdCol] = now;
725
+ if (item[updatedCol] === undefined) item[updatedCol] = now;
726
+ }
727
+ });
728
+ return data;
729
+ }
730
+
731
+ if (data[createdCol] === undefined) data[createdCol] = now;
732
+ if (data[updatedCol] === undefined) data[updatedCol] = now;
733
+ return data;
734
+ }
735
+
736
+ _applyTimestampsOnUpdate(setData) {
737
+ if (!this.timestamps || !setData || typeof setData !== 'object') return setData;
738
+ const now = new Date();
739
+ const updatedCol = typeof this.timestamps === 'object' && this.timestamps.updatedAt ? this.timestamps.updatedAt : 'atualizado_em';
740
+ if (setData[updatedCol] === undefined) {
741
+ setData[updatedCol] = now;
742
+ }
743
+ return setData;
744
+ }
745
+
746
+ _buildWhereClause(where, useRegex = false, wrapInParens = false) {
144
747
  if (!where) {
145
748
  return { sql: '', bindings: [] };
146
749
  }
147
750
 
148
751
  const conditions = [];
149
752
  const bindings = [];
753
+ const defaultOp = useRegex ? 'REGEXP' : '=';
150
754
 
151
755
  if (Array.isArray(where)) {
152
- where.forEach((param) => {
153
- if (typeof param === 'object' && param !== null && !Array.isArray(param)) {
756
+ if (where.length === 0) return { sql: '', bindings: [] };
757
+
758
+ for (const param of where) {
759
+ if (typeof param === 'string') {
760
+ const upper = param.toUpperCase().trim();
761
+ if (upper === 'AND' || upper === 'OR') {
762
+ conditions.push(upper);
763
+ }
764
+ } else if (typeof param === 'object' && param !== null && !Array.isArray(param)) {
154
765
  const keys = Object.keys(param);
155
766
  const colKey = keys.find(k => k.toLowerCase() !== 'operator');
156
- if (!colKey) return;
767
+ if (!colKey) continue;
157
768
 
158
- const cleanKey = sanitizeIdentifier(colKey);
769
+ const colSql = safeColumn(colKey);
159
770
  const value = param[colKey];
160
771
  const opKey = keys.find(k => k.toLowerCase() === 'operator');
161
- const opValue = opKey ? param[opKey] : undefined;
772
+ let op = sanitizeOperator(opKey ? param[opKey] : undefined, defaultOp);
162
773
 
163
- let op = sanitizeOperator(opValue, useRegex ? 'REGEXP' : '=');
774
+ if (value === null) {
775
+ if (op === '=' || op === 'IS') {
776
+ conditions.push(`${colSql} IS NULL`);
777
+ } else {
778
+ conditions.push(`${colSql} IS NOT NULL`);
779
+ }
780
+ continue;
781
+ }
164
782
 
165
- if (Array.isArray(value) && op === '=') {
166
- op = 'IN';
783
+ if ((op === 'BETWEEN' || op === 'NOT BETWEEN') && Array.isArray(value) && value.length === 2) {
784
+ conditions.push(`${colSql} ${op} ? AND ?`);
785
+ bindings.push(value[0], value[1]);
786
+ continue;
167
787
  }
168
788
 
169
- if (Array.isArray(value) && (op === 'IN' || op === 'NOT IN')) {
170
- if (value.length === 0) {
171
- conditions.push(op === 'IN' ? '1 = 0' : '1 = 1');
172
- } else {
173
- const placeholders = value.map(() => '?').join(', ');
174
- conditions.push(`\`${cleanKey}\` ${op} (${placeholders})`);
175
- bindings.push(...value);
789
+ if (Array.isArray(value)) {
790
+ if (op === '=') op = 'IN';
791
+ else if (op === '!=' || op === '<>') op = 'NOT IN';
792
+
793
+ if (op === 'IN' || op === 'NOT IN') {
794
+ if (value.length === 0) {
795
+ conditions.push(op === 'IN' ? '1 = 0' : '1 = 1');
796
+ } else {
797
+ const placeholders = value.map(() => '?').join(', ');
798
+ conditions.push(`${colSql} ${op} (${placeholders})`);
799
+ bindings.push(...value);
800
+ }
801
+ continue;
176
802
  }
177
- } else {
178
- const condition = `\`${cleanKey}\` ${op} ?`;
179
- conditions.push(condition);
180
- bindings.push(value);
181
803
  }
182
- } else if (typeof param === 'string') {
183
- const upper = param.toUpperCase().trim();
184
- if (upper === 'AND' || upper === 'OR') {
185
- conditions.push(upper);
804
+
805
+ conditions.push(`${colSql} ${op} ?`);
806
+ bindings.push(value);
807
+ }
808
+ }
809
+
810
+ if (conditions.length === 0) return { sql: '', bindings: [] };
811
+ const joined = conditions.join(' ');
812
+ return { sql: wrapInParens ? `(${joined})` : joined, bindings };
813
+
814
+ } else if (typeof where === 'object') {
815
+ for (const [key, value] of Object.entries(where)) {
816
+ const colSql = safeColumn(key);
817
+ if (value === null) {
818
+ conditions.push(`${colSql} IS NULL`);
819
+ } else if (Array.isArray(value)) {
820
+ if (value.length === 0) {
821
+ conditions.push('1 = 0');
822
+ } else {
823
+ const placeholders = value.map(() => '?').join(', ');
824
+ conditions.push(`${colSql} IN (${placeholders})`);
825
+ bindings.push(...value);
186
826
  }
827
+ } else {
828
+ conditions.push(`${colSql} ${defaultOp} ?`);
829
+ bindings.push(value);
187
830
  }
188
- });
189
- return { sql: conditions.join(' '), bindings };
190
- } else if (typeof where === 'object' && where !== null) {
191
- const operator = useRegex ? 'REGEXP' : '=';
192
- const keys = Object.keys(where);
193
- const sql = keys.map(key => `\`${sanitizeIdentifier(key)}\` ${operator} ?`).join(' AND ');
194
- const bindings = Object.values(where);
195
- return { sql, bindings };
831
+ }
832
+ const joined = conditions.join(' AND ');
833
+ return { sql: wrapInParens && joined ? `(${joined})` : joined, bindings };
196
834
  }
197
835
 
198
836
  return { sql: '', bindings: [] };
199
837
  }
200
838
 
839
+ _parseStrictCondition(strictCondition) {
840
+ return this._buildWhereClause(strictCondition, false, true);
841
+ }
842
+
843
+ async paginate(options = {}) {
844
+ const page = Math.max(1, parseInt(options.page, 10) || 1);
845
+ const limit = Math.max(1, parseInt(options.limit, 10) || 20);
846
+ const offset = (page - 1) * limit;
847
+
848
+ const targetWhere = options.where !== undefined ? options.where : this._qb.where;
849
+ const softCol = this._getSoftDeleteColumn();
850
+ const whereConditions = Array.isArray(targetWhere) ? [...targetWhere] : (typeof targetWhere === 'object' && targetWhere !== null ? [targetWhere] : []);
851
+
852
+ if (softCol && !this._qb.withTrashed) {
853
+ if (whereConditions.length > 0) whereConditions.push('AND');
854
+ if (this._qb.onlyTrashed) {
855
+ whereConditions.push({ [softCol]: null, operator: 'IS NOT' });
856
+ } else {
857
+ whereConditions.push({ [softCol]: null, operator: 'IS' });
858
+ }
859
+ }
860
+
861
+ const { sql: whereSql, bindings } = this._buildWhereClause(whereConditions);
862
+ const whereClause = whereSql ? ` WHERE ${whereSql}` : '';
863
+ const joinClause = this._buildJoinClauses(this._qb.joins);
864
+ const table = this._safeTable();
865
+
866
+ const countSql = `SELECT COUNT(*) AS total FROM ${table}${joinClause}${whereClause}`;
867
+ const selectClauses = {
868
+ FIELDS: options.fields || this._qb.fields,
869
+ JOINS: this._qb.joins,
870
+ GROUPBY: options.groupBy || (this._qb.groupBy.length ? this._qb.groupBy : undefined),
871
+ HAVING: options.having || this._qb.having || undefined,
872
+ ORDERBY: options.orderBy || (this._qb.orderBy.length ? this._qb.orderBy : undefined),
873
+ DESC: options.desc,
874
+ WITH_TRASHED: true, // Já aplicado em whereConditions
875
+ ...options.clauses,
876
+ LIMIT: limit,
877
+ OFFSET: offset
878
+ };
879
+
880
+ const inTx = typeof this.db.hasActiveTransaction === 'function' && this.db.hasActiveTransaction();
881
+ let countRes, dataRes;
882
+
883
+ if (!inTx) {
884
+ [countRes, dataRes] = await Promise.all([
885
+ this.executeQuery(countSql, bindings),
886
+ this.select(whereConditions, selectClauses)
887
+ ]);
888
+ } else {
889
+ countRes = await this.executeQuery(countSql, bindings);
890
+ dataRes = await this.select(whereConditions, selectClauses);
891
+ }
892
+
893
+ if (countRes && countRes.error) return countRes;
894
+ if (dataRes && dataRes.error) return dataRes;
895
+
896
+ const total = Number(countRes?.[0]?.total || 0);
897
+ const totalPages = Math.ceil(total / limit) || 1;
898
+ let data = Array.isArray(dataRes) ? dataRes : [];
899
+
900
+ if (data.length > 0 && this._qb.relations.length > 0) {
901
+ await this._applyEagerLoading(data, this._qb.relations);
902
+ }
903
+
904
+ return {
905
+ data: this._maskHiddenFields(data),
906
+ total,
907
+ page,
908
+ limit,
909
+ totalPages
910
+ };
911
+ }
912
+
201
913
  async selectToDatatable(rawDtQuery, strictCondition = []) {
202
914
  const isTrue = (val) => val === true || val === 'true';
203
- // Hidrata o objeto da requisição para o formato aninhado correto de forma segura
204
- const dtQuery = this._hydrateObject(rawDtQuery) || {};
915
+ const dtQuery = this._hydrateObject(rawDtQuery);
205
916
  const { draw, start, length, search, order, columns } = dtQuery;
206
917
  const table = this._safeTable();
918
+ const parsedDraw = parseInt(draw, 10) || 0;
207
919
 
208
920
  try {
209
- const baseWhere = this._parseStrictCondition(strictCondition);
921
+ const finalStrict = Array.isArray(strictCondition) ? [...strictCondition] : [strictCondition];
922
+ const softCol = this._getSoftDeleteColumn();
923
+ if (softCol && !this._qb.withTrashed) {
924
+ if (finalStrict.length > 0) finalStrict.push('AND');
925
+ if (this._qb.onlyTrashed) {
926
+ finalStrict.push({ [softCol]: null, operator: 'IS NOT' });
927
+ } else {
928
+ finalStrict.push({ [softCol]: null, operator: 'IS' });
929
+ }
930
+ }
931
+
932
+ const baseWhere = this._parseStrictCondition(finalStrict);
210
933
  const finalBindings = [...baseWhere.bindings];
211
934
  const finalWhereClauses = baseWhere.sql ? [baseWhere.sql] : [];
212
935
 
213
936
  const dtSearchClauses = [];
214
- if (columns && Array.isArray(columns)) {
215
- // 1. Busca Global
937
+ if (Array.isArray(columns)) {
216
938
  if (search && search.value !== '' && search.value !== undefined && search.value !== null) {
217
939
  const searchableCols = columns.filter(c => c && c.data && isTrue(c.searchable));
218
940
  if (searchableCols.length > 0) {
@@ -228,7 +950,6 @@ class DatabaseHandler {
228
950
  }
229
951
  }
230
952
 
231
- // 2. Busca por Coluna Específica
232
953
  for (const col of columns) {
233
954
  if (col && col.data && isTrue(col.searchable) && col.search && col.search.value !== '' && col.search.value !== undefined && col.search.value !== null) {
234
955
  const isRegex = isTrue(col.search.regex);
@@ -248,20 +969,18 @@ class DatabaseHandler {
248
969
  const hasDtSearch = dtSearchClauses.length > 0;
249
970
  const whereSql = finalWhereClauses.length > 0 ? `WHERE ${finalWhereClauses.join(' AND ')}` : '';
250
971
  const baseWhereSql = baseWhere.sql ? `WHERE ${baseWhere.sql}` : '';
972
+ const joinClause = this._buildJoinClauses(this._qb.joins);
251
973
 
252
- // 3. Ordenação com suporte a múltiplas colunas
253
974
  let orderSql = '';
254
- if (order && columns) {
255
- const orderArray = Array.isArray(order) ? order : [order];
975
+ if (order && Array.isArray(columns)) {
976
+ const orderArray = Array.isArray(order) ? order : Object.values(order);
256
977
  const orderParts = [];
257
978
  for (const ord of orderArray) {
258
979
  if (!ord || ord.column === undefined) continue;
259
- const orderColumnIndex = parseInt(ord.column, 10);
260
- const colDef = columns[orderColumnIndex];
980
+ const colDef = columns[parseInt(ord.column, 10)];
261
981
  if (colDef && isTrue(colDef.orderable) && colDef.data) {
262
- const orderColumnName = safeColumn(colDef.data);
263
- const orderDir = ord.dir && ord.dir.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
264
- orderParts.push(`${orderColumnName} ${orderDir}`);
982
+ const orderDir = ord.dir && String(ord.dir).toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
983
+ orderParts.push(`${safeColumn(colDef.data)} ${orderDir}`);
265
984
  }
266
985
  }
267
986
  if (orderParts.length > 0) {
@@ -269,85 +988,63 @@ class DatabaseHandler {
269
988
  }
270
989
  }
271
990
 
272
- // 4. Paginação segura (valores negativos ou inválidos não quebram a query)
273
991
  const safeStart = Math.max(0, parseInt(start, 10) || 0);
274
992
  const parsedLength = parseInt(length, 10);
275
- let limitSql = '';
276
- if (!isNaN(parsedLength) && parsedLength > 0) {
277
- limitSql = `LIMIT ${safeStart}, ${parsedLength}`;
278
- }
993
+ const limitSql = (!isNaN(parsedLength) && parsedLength > 0) ? `LIMIT ${safeStart}, ${parsedLength}` : '';
279
994
 
280
- // --- 5. Execução Otimizada das Queries ---
995
+ const totalCountSql = `SELECT COUNT(*) as total FROM ${table}${joinClause} ${baseWhereSql}`.trim();
996
+ const inTx = typeof this.db.hasActiveTransaction === 'function' && this.db.hasActiveTransaction();
281
997
 
282
- // Query 1: Total Geral (baseado em strictCondition)
283
- const totalCountSql = `SELECT COUNT(*) as total FROM ${table} ${baseWhereSql}`.trim();
284
- const totalResult = await this.executeQuery(totalCountSql, baseWhere.bindings);
285
- // Contrato: executeQuery propaga { error } em caso de falha (não lança).
286
- if (totalResult && totalResult.error) {
287
- return {
288
- draw: parseInt(draw, 10) || 0,
289
- recordsTotal: 0,
290
- recordsFiltered: 0,
291
- data: [],
292
- error: totalResult.error.message
293
- };
294
- }
295
- const recordsTotal = Number((totalResult && totalResult[0] && totalResult[0].total) || 0);
998
+ let totalResult;
999
+ let filteredResult = null;
296
1000
 
297
- // Query 2: Total Filtrado
298
- // OTIMIZAÇÃO: se não há filtro extra do DataTables, recordsFiltered é igual a recordsTotal.
299
- // Elimina uma query COUNT(*) idêntica e pesada.
300
- let recordsFiltered = recordsTotal;
301
1001
  if (hasDtSearch) {
302
- const filteredCountSql = `SELECT COUNT(*) as total FROM ${table} ${whereSql}`.trim();
303
- const filteredResult = await this.executeQuery(filteredCountSql, finalBindings);
304
- if (filteredResult && filteredResult.error) {
305
- return {
306
- draw: parseInt(draw, 10) || 0,
307
- recordsTotal,
308
- recordsFiltered: 0,
309
- data: [],
310
- error: filteredResult.error.message
311
- };
1002
+ const filteredCountSql = `SELECT COUNT(*) as total FROM ${table}${joinClause} ${whereSql}`.trim();
1003
+ if (!inTx) {
1004
+ [totalResult, filteredResult] = await Promise.all([
1005
+ this.executeQuery(totalCountSql, baseWhere.bindings),
1006
+ this.executeQuery(filteredCountSql, finalBindings)
1007
+ ]);
1008
+ } else {
1009
+ totalResult = await this.executeQuery(totalCountSql, baseWhere.bindings);
1010
+ filteredResult = await this.executeQuery(filteredCountSql, finalBindings);
312
1011
  }
313
- recordsFiltered = Number((filteredResult && filteredResult[0] && filteredResult[0].total) || 0);
1012
+ } else {
1013
+ totalResult = await this.executeQuery(totalCountSql, baseWhere.bindings);
1014
+ }
1015
+
1016
+ if (totalResult && totalResult.error) {
1017
+ return { draw: parsedDraw, recordsTotal: 0, recordsFiltered: 0, data: [], error: totalResult.error.message };
1018
+ }
1019
+ const recordsTotal = Number(totalResult?.[0]?.total || 0);
1020
+
1021
+ if (filteredResult && filteredResult.error) {
1022
+ return { draw: parsedDraw, recordsTotal, recordsFiltered: 0, data: [], error: filteredResult.error.message };
314
1023
  }
1024
+ const recordsFiltered = hasDtSearch ? Number(filteredResult?.[0]?.total || 0) : recordsTotal;
315
1025
 
316
- // Query 3: Dados da Página
317
- // OTIMIZAÇÃO SHORT-CIRCUIT: se recordsFiltered for 0, não há registros para retornar.
318
1026
  let data = [];
319
- if (recordsFiltered > 0) {
320
- const selectFields = ['*'];
321
- if (this.expression && this.expression.trim() !== '') {
322
- // Remove vírgula do início da expressão, se houver, para evitar duplicação
323
- selectFields.push(this.expression.trim().replace(/^,/, '').trim());
324
- }
325
- const dataSql = `SELECT ${selectFields.join(', ')} FROM ${table} ${whereSql ? ` ${whereSql}` : ''}${orderSql ? ` ${orderSql}` : ''}${limitSql ? ` ${limitSql}` : ''}`.trim();
1027
+ if (recordsFiltered > 0 && parsedLength !== 0) {
1028
+ const selectCols = this._buildSelectColumns(this._qb.fields);
1029
+ const dataSql = `SELECT ${selectCols} FROM ${table}${joinClause}${whereSql ? ` ${whereSql}` : ''}${orderSql ? ` ${orderSql}` : ''}${limitSql ? ` ${limitSql}` : ''}`.trim();
326
1030
  const dataResult = await this.executeQuery(dataSql, finalBindings);
327
1031
  if (dataResult && dataResult.error) {
328
- return {
329
- draw: parseInt(draw, 10) || 0,
330
- recordsTotal,
331
- recordsFiltered,
332
- data: [],
333
- error: dataResult.error.message
334
- };
1032
+ return { draw: parsedDraw, recordsTotal, recordsFiltered, data: [], error: dataResult.error.message };
335
1033
  }
336
1034
  data = Array.isArray(dataResult) ? dataResult : [];
337
1035
  }
338
1036
 
339
1037
  return {
340
- draw: parseInt(draw, 10) || 0,
1038
+ draw: parsedDraw,
341
1039
  recordsTotal,
342
1040
  recordsFiltered,
343
- data,
1041
+ data: this._maskHiddenFields(data),
344
1042
  };
345
-
346
1043
  } catch (e) {
347
- console.error("Erro em selectToDatatable:", e);
1044
+ console.error('Erro em selectToDatatable:', e);
348
1045
  if (this.onError) this.onError(e);
349
1046
  return {
350
- draw: parseInt(dtQuery?.draw, 10) || 0,
1047
+ draw: parsedDraw,
351
1048
  recordsTotal: 0,
352
1049
  recordsFiltered: 0,
353
1050
  data: [],
@@ -357,87 +1054,184 @@ class DatabaseHandler {
357
1054
  }
358
1055
 
359
1056
  async selectBy(params) {
360
- const table = this._safeTable();
361
- if (params) {
362
- const sql = `SELECT *${this.expression ? this.expression : ''} FROM ${table} WHERE ?`;
363
- const rows = await this.executeQuery(sql, params);
364
- return rows; // retorna um array, mesmo que vazio
1057
+ const softCol = this._getSoftDeleteColumn();
1058
+ const whereConditions = [];
1059
+
1060
+ if (params && typeof params === 'object') {
1061
+ for (const [k, v] of Object.entries(params)) {
1062
+ if (whereConditions.length > 0) whereConditions.push('AND');
1063
+ whereConditions.push({ [k]: v, operator: '=' });
1064
+ }
365
1065
  }
366
- else {
367
- const sql = `SELECT *${this.expression ? this.expression : ''} FROM ${table}`;
368
- return this.executeQuery(sql);
1066
+
1067
+ if (softCol && !this._qb.withTrashed) {
1068
+ if (whereConditions.length > 0) whereConditions.push('AND');
1069
+ if (this._qb.onlyTrashed) {
1070
+ whereConditions.push({ [softCol]: null, operator: 'IS NOT' });
1071
+ } else {
1072
+ whereConditions.push({ [softCol]: null, operator: 'IS' });
1073
+ }
369
1074
  }
1075
+
1076
+ return await this.select(whereConditions, { FIELDS: this._qb.fields, JOINS: this._qb.joins, WITH_TRASHED: true });
370
1077
  }
371
1078
 
372
1079
  /**
373
1080
  * @deprecated Use select() instead.
374
1081
  */
375
1082
  async selectOld(params, clauses = {}) {
1083
+ return this.select(params, clauses);
1084
+ }
1085
+
1086
+ async select(params, clauses = {}, _objectWhereOverride = null) {
376
1087
  if (params != null && !Array.isArray(params)) {
377
1088
  return new Error('O parâmetro "params" deve ser um array');
378
1089
  }
379
1090
 
380
- const conditions = [];
381
- const values = [];
382
-
383
- if (params && params.length) {
384
- params.map((param) => {
385
- if (typeof param === 'object' && !Array.isArray(param)) {
386
- const entries = Object.entries(param);
387
- const [key, value] = entries[0];
388
- const [operator, opValue] = entries[1] || [];
389
-
390
- const cleanKey = sanitizeIdentifier(key);
391
- const condition = `\`${cleanKey}\` ${opValue ?? '='} ?`;
392
- conditions.push(condition);
393
- values.push(value);
394
- } else if (typeof param === 'string') {
395
- conditions.push(param.toUpperCase());
1091
+ const whereTarget = _objectWhereOverride || (Array.isArray(params) ? [...params] : []);
1092
+ const softCol = this._getSoftDeleteColumn();
1093
+ const withTrashed = clauses.WITH_TRASHED !== undefined ? clauses.WITH_TRASHED : this._qb.withTrashed;
1094
+ const onlyTrashed = clauses.ONLY_TRASHED !== undefined ? clauses.ONLY_TRASHED : this._qb.onlyTrashed;
1095
+
1096
+ if (softCol) {
1097
+ if (onlyTrashed) {
1098
+ if (Array.isArray(whereTarget)) {
1099
+ if (whereTarget.length > 0) whereTarget.push('AND');
1100
+ whereTarget.push({ [softCol]: null, operator: 'IS NOT' });
1101
+ } else if (typeof whereTarget === 'object' && whereTarget !== null) {
1102
+ whereTarget[softCol] = { operator: 'IS NOT', value: null };
396
1103
  }
397
- });
1104
+ } else if (!withTrashed) {
1105
+ if (Array.isArray(whereTarget)) {
1106
+ if (whereTarget.length > 0) whereTarget.push('AND');
1107
+ whereTarget.push({ [softCol]: null, operator: 'IS' });
1108
+ } else if (typeof whereTarget === 'object' && whereTarget !== null) {
1109
+ whereTarget[softCol] = null;
1110
+ }
1111
+ }
398
1112
  }
399
1113
 
400
- const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' ')}` : '';
1114
+ const { sql: whereSql, bindings: values } = this._buildWhereClause(whereTarget);
1115
+ const whereClause = whereSql ? ` WHERE ${whereSql}` : '';
401
1116
 
402
- // Cláusulas adicionais
403
- const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
404
- const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
405
- const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
406
- const descClause = clauses['DESC'] ? ` DESC ` : '';
407
- const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
408
- const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
1117
+ const joins = clauses.JOINS || this._qb.joins;
1118
+ const joinClause = this._buildJoinClauses(joins);
409
1119
 
410
- const sql = `SELECT *${this.expression ?? ''} FROM ${this._safeTable()}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
1120
+ const selectCols = this._buildSelectColumns(clauses.FIELDS || this._qb.fields);
411
1121
 
412
- const rows = await this.executeQuery(sql, values);
413
- return rows;
414
- }
1122
+ // Sanitização estrita de GROUP BY e ORDER BY
1123
+ const safeGroup = clauses.GROUPBY ? sanitizeClauseList(clauses.GROUPBY, false) : '';
1124
+ const groupByClause = safeGroup ? ` GROUP BY ${safeGroup}` : '';
415
1125
 
416
- async select(params, clauses = {}) {
417
- if (params != null && !Array.isArray(params)) {
418
- return new Error('O parâmetro "params" deve ser um array');
1126
+ let havingClause = '';
1127
+ if (clauses.HAVING) {
1128
+ if (typeof clauses.HAVING === 'object' && clauses.HAVING.sql) {
1129
+ havingClause = ` HAVING ${clauses.HAVING.sql}`;
1130
+ if (Array.isArray(clauses.HAVING.bindings)) {
1131
+ values.push(...clauses.HAVING.bindings);
1132
+ }
1133
+ } else {
1134
+ havingClause = ` HAVING ${clauses.HAVING}`;
1135
+ }
419
1136
  }
420
1137
 
421
- const { sql: whereSql, bindings: values } = this._buildWhereClause(params);
422
- const whereClause = whereSql ? ` WHERE ${whereSql}` : '';
1138
+ const safeOrder = clauses.ORDERBY ? sanitizeClauseList(clauses.ORDERBY, true) : '';
1139
+ const orderClause = safeOrder ? ` ORDER BY ${safeOrder}` : '';
1140
+ const descClause = (clauses.DESC && safeOrder && !/\b(ASC|DESC)$/i.test(safeOrder)) ? ` DESC` : '';
1141
+
1142
+ const parsedLimit = clauses.LIMIT !== undefined ? parseInt(clauses.LIMIT, 10) : NaN;
1143
+ const limitClause = !isNaN(parsedLimit) && parsedLimit >= 0 ? ` LIMIT ${parsedLimit}` : '';
423
1144
 
424
- // Cláusulas adicionais
425
- const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
426
- const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
427
- const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
428
- const descClause = clauses['DESC'] ? ` DESC ` : '';
429
- const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
430
- const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
1145
+ const parsedOffset = clauses.OFFSET !== undefined ? parseInt(clauses.OFFSET, 10) : NaN;
1146
+ const offsetClause = !isNaN(parsedOffset) && parsedOffset >= 0 ? ` OFFSET ${parsedOffset}` : '';
431
1147
 
432
- const sql = `SELECT *${this.expression ?? ''} FROM ${this._safeTable()}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
1148
+ const sql = `SELECT ${selectCols} FROM ${this._safeTable()}${joinClause}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
433
1149
 
434
1150
  const rows = await this.executeQuery(sql, values);
435
- return rows;
1151
+ return this._maskHiddenFields(rows);
436
1152
  }
437
1153
 
438
1154
  async insert(params) {
1155
+ for (const hook of this._hooks.beforeInsert) {
1156
+ await hook(params);
1157
+ }
1158
+
1159
+ const stripped = await this._stripUnknownFields(params);
1160
+ const data = this._applyTimestampsOnInsert(stripped);
1161
+
439
1162
  const sql = `INSERT INTO ${this._safeTable()} SET ?`;
440
- const result = await this.executeQuery(sql, params, true);
1163
+ const result = await this.executeQuery(sql, data, true);
1164
+
1165
+ for (const hook of this._hooks.afterInsert) {
1166
+ await hook(result, data);
1167
+ }
1168
+
1169
+ return result;
1170
+ }
1171
+
1172
+ async insertMany(rowsArray) {
1173
+ if (!Array.isArray(rowsArray) || rowsArray.length === 0) {
1174
+ throw new Error('insertMany requer um array não vazio de objetos.');
1175
+ }
1176
+
1177
+ for (const hook of this._hooks.beforeInsert) {
1178
+ for (const row of rowsArray) {
1179
+ await hook(row);
1180
+ }
1181
+ }
1182
+
1183
+ const stripped = await this._stripUnknownFields(rowsArray);
1184
+ const dataRows = this._applyTimestampsOnInsert(stripped);
1185
+
1186
+ const columns = Object.keys(dataRows[0]);
1187
+ if (columns.length === 0) {
1188
+ throw new Error('Os objetos em insertMany devem conter ao menos uma coluna.');
1189
+ }
1190
+
1191
+ const safeCols = columns.map(c => safeColumn(c)).join(', ');
1192
+ const valuesMatrix = dataRows.map(row => columns.map(col => (row[col] !== undefined ? row[col] : null)));
1193
+
1194
+ const sql = `INSERT INTO ${this._safeTable()} (${safeCols}) VALUES ?`;
1195
+ const result = await this.executeQuery(sql, [valuesMatrix], true, { prepare: false });
1196
+
1197
+ for (const hook of this._hooks.afterInsert) {
1198
+ await hook(result, dataRows);
1199
+ }
1200
+
1201
+ return result;
1202
+ }
1203
+
1204
+ async upsert(data, updateColumns = null) {
1205
+ if (!data || typeof data !== 'object' || Object.keys(data).length === 0) {
1206
+ throw new Error('A operação de upsert requer um objeto de dados válido.');
1207
+ }
1208
+
1209
+ for (const hook of this._hooks.beforeInsert) {
1210
+ await hook(data);
1211
+ }
1212
+
1213
+ const stripped = await this._stripUnknownFields(data);
1214
+ const preparedData = this._applyTimestampsOnInsert(stripped);
1215
+
1216
+ const dataKeys = Object.keys(preparedData);
1217
+ const colsToUpdate = Array.isArray(updateColumns) && updateColumns.length > 0 ? updateColumns : dataKeys;
1218
+
1219
+ const insertCols = dataKeys.map(k => safeColumn(k)).join(', ');
1220
+ const insertPlaceholders = dataKeys.map(() => '?').join(', ');
1221
+ const updateClause = colsToUpdate.map(k => {
1222
+ const col = safeColumn(k);
1223
+ return `${col} = VALUES(${col})`;
1224
+ }).join(', ');
1225
+
1226
+ const bindings = dataKeys.map(k => preparedData[k]);
1227
+ const sql = `INSERT INTO ${this._safeTable()} (${insertCols}) VALUES (${insertPlaceholders}) ON DUPLICATE KEY UPDATE ${updateClause}`;
1228
+
1229
+ const result = await this.executeQuery(sql, bindings, true);
1230
+
1231
+ for (const hook of this._hooks.afterInsert) {
1232
+ await hook(result, preparedData);
1233
+ }
1234
+
441
1235
  return result;
442
1236
  }
443
1237
 
@@ -446,23 +1240,31 @@ class DatabaseHandler {
446
1240
  throw new Error('A operação de update requer um objeto "set" com ao menos um campo.');
447
1241
  }
448
1242
 
449
- // Inicializa a string SQL para a cláusula SET
450
- let setClause = Object.keys(params.set).map(key => `\`${sanitizeIdentifier(key)}\` = ?`).join(', ');
451
- let setValues = Object.values(params.set);
1243
+ for (const hook of this._hooks.beforeUpdate) {
1244
+ await hook(params.set, params.where);
1245
+ }
1246
+
1247
+ const strippedSet = await this._stripUnknownFields(params.set);
1248
+ const finalSet = this._applyTimestampsOnUpdate(strippedSet);
1249
+
1250
+ const setKeys = Object.keys(finalSet);
1251
+ const setClause = setKeys.map(key => `${safeColumn(key)} = ?`).join(', ');
1252
+ const setValues = setKeys.map(key => finalSet[key]);
452
1253
 
453
- // Inicializa a string SQL para a cláusula WHERE
454
1254
  const { sql: whereClause, bindings: whereValues } = this._buildWhereClause(params.where, !!options.useRegex);
455
1255
  if (!whereClause || whereClause.trim() === '') {
456
1256
  throw new Error('A operação de update requer uma cláusula "where" não vazia para prevenir alterações em toda a tabela.');
457
1257
  }
458
1258
 
459
- // Constrói a consulta SQL completa
460
1259
  const sql = `UPDATE ${this._safeTable()} SET ${setClause} WHERE ${whereClause}`;
461
- // Combina os valores SET e WHERE em um único array
462
1260
  const values = [...setValues, ...whereValues];
463
- // Executa a consulta sinalizando mutação de escrita
1261
+
464
1262
  const result = await this.executeQuery(sql, values, true);
465
1263
 
1264
+ for (const hook of this._hooks.afterUpdate) {
1265
+ await hook(result, finalSet, params.where);
1266
+ }
1267
+
466
1268
  return result;
467
1269
  }
468
1270
 
@@ -470,18 +1272,75 @@ class DatabaseHandler {
470
1272
  if (!conditions || typeof conditions !== 'object') {
471
1273
  return;
472
1274
  }
473
- const conditionKeys = Object.keys(conditions);
474
- if (conditionKeys.length === 0) {
475
- // Se o objeto conditions estiver vazio, não faz nada para evitar truncar a tabela
1275
+
1276
+ for (const hook of this._hooks.beforeDelete) {
1277
+ await hook(conditions);
1278
+ }
1279
+
1280
+ const softCol = this._getSoftDeleteColumn();
1281
+ if (softCol) {
1282
+ // Soft delete ativo: realiza UPDATE na coluna de timestamp
1283
+ const result = await this.update({
1284
+ set: { [softCol]: new Date() },
1285
+ where: conditions
1286
+ });
1287
+
1288
+ for (const hook of this._hooks.afterDelete) {
1289
+ await hook(result, conditions);
1290
+ }
1291
+ return result;
1292
+ }
1293
+
1294
+ const { sql: whereClause, bindings } = this._buildWhereClause(conditions);
1295
+ if (!whereClause) {
1296
+ return;
1297
+ }
1298
+
1299
+ const sql = `DELETE FROM ${this._safeTable()} WHERE ${whereClause}`;
1300
+ const result = await this.executeQuery(sql, bindings, true);
1301
+
1302
+ for (const hook of this._hooks.afterDelete) {
1303
+ await hook(result, conditions);
1304
+ }
1305
+
1306
+ return result;
1307
+ }
1308
+
1309
+ async forceDelete(conditions) {
1310
+ if (!conditions || typeof conditions !== 'object') {
1311
+ return;
1312
+ }
1313
+
1314
+ for (const hook of this._hooks.beforeDelete) {
1315
+ await hook(conditions);
1316
+ }
1317
+
1318
+ const { sql: whereClause, bindings } = this._buildWhereClause(conditions);
1319
+ if (!whereClause) {
476
1320
  return;
477
1321
  }
478
1322
 
479
- const whereConditions = conditionKeys.map((key) => `\`${sanitizeIdentifier(key)}\` = ?`).join(' AND ');
480
- const sql = `DELETE FROM ${this._safeTable()} WHERE ${whereConditions}`;
481
- const params = conditionKeys.map((key) => conditions[key]);
482
- const result = await this.executeQuery(sql, params, true);
1323
+ const sql = `DELETE FROM ${this._safeTable()} WHERE ${whereClause}`;
1324
+ const result = await this.executeQuery(sql, bindings, true);
1325
+
1326
+ for (const hook of this._hooks.afterDelete) {
1327
+ await hook(result, conditions);
1328
+ }
1329
+
483
1330
  return result;
484
1331
  }
1332
+
1333
+ async restore(conditions) {
1334
+ const softCol = this._getSoftDeleteColumn();
1335
+ if (!softCol) {
1336
+ throw new Error('O método restore() só pode ser usado quando o Soft Delete estiver ativo.');
1337
+ }
1338
+
1339
+ return await this.update({
1340
+ set: { [softCol]: null },
1341
+ where: conditions
1342
+ });
1343
+ }
485
1344
  }
486
1345
 
487
- module.exports = DatabaseHandler;
1346
+ module.exports = DatabaseHandler;