@areumtecnologia/mysql-db-handler 1.0.10 → 1.0.12

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,384 +1,449 @@
1
- class DatabaseHandler {
2
- constructor(database, table, expression = '') {
3
- this.db = database;
4
- this.table = table;
5
- this.debug = false;
6
- this.expression = expression;
7
- this.debug = false;
8
- this.onError;
9
- }
10
-
11
- async executeQuery(sql, params) {
12
- // const connection = await this.db;
13
- // const rows = await connection.query(sql, params);
14
- const rows = await this.db.query(sql, params);
15
- return rows;
16
- }
17
-
18
- async getSchema() {
19
- return await this.db.getTableSchema(this.table)
20
- }
21
-
22
- /**
23
- * @private
24
- * Converte um objeto "achatado" (form-urlencoded) em um objeto aninhado (JSON).
25
- * Ex: { 'columns[0][data]': 'id' } => { columns: [{ data: 'id' }] }
26
- */
27
- _hydrateObject(flatObject) {
28
- const result = {};
29
- for (const key in flatObject) {
30
- const keys = key.match(/[^[\]']+/g); // Extrai chaves como ['columns', '0', 'data']
31
- if (!keys) continue;
32
-
33
- let current = result;
34
- while (keys.length > 1) {
35
- const k = keys.shift();
36
- current[k] = current[k] || (isNaN(keys[0]) ? {} : []);
37
- current = current[k];
38
- }
39
- current[keys[0]] = flatObject[key];
40
- }
41
- return result;
42
- }
43
-
44
- _parseStrictCondition(strictCondition) {
45
- if (!strictCondition || !Array.isArray(strictCondition) || strictCondition.length === 0) {
46
- return { sql: '', bindings: [] };
47
- }
48
- const clauses = [];
49
- const bindings = [];
50
- for (const item of strictCondition) {
51
- if (typeof item === 'string') {
52
- // Operadores lógicos (AND / OR) são inseridos como-is, sem parênteses.
53
- clauses.push(item.toUpperCase());
54
- } else if (typeof item === 'object' && item !== null) {
55
- const key = Object.keys(item).find(k => k !== 'operator');
56
- if (!key) continue;
57
- const value = item[key];
58
- let operator = item.operator || '=';
59
- let upperOp = String(operator).toUpperCase();
60
-
61
- // Suporte a arrays => IN / NOT IN (consistente com _buildWhereClause)
62
- if (Array.isArray(value) && upperOp === '=') {
63
- operator = 'IN';
64
- upperOp = 'IN';
65
- }
66
-
67
- if (Array.isArray(value) && (upperOp === 'IN' || upperOp === 'NOT IN')) {
68
- if (value.length === 0) {
69
- clauses.push(upperOp === 'IN' ? '1 = 0' : '1 = 1');
70
- } else {
71
- const placeholders = value.map(() => '?').join(', ');
72
- clauses.push(`\`${key}\` ${operator} (${placeholders})`);
73
- bindings.push(...value);
74
- }
75
- } else {
76
- clauses.push(`\`${key}\` ${operator} ?`);
77
- bindings.push(value);
78
- }
79
- }
80
- }
81
- // Junta com espaço para preservar operadores AND/OR intercalados.
82
- // Ex: "(a = ? AND b = ?)" em vez de "(a = ? b = ?)" que era inválido.
83
- return { sql: `(${clauses.join(' ')})`, bindings };
84
- }
85
-
86
- /**
87
- * @private
88
- * Constrói a cláusula WHERE (sem a palavra-chave WHERE) e seus bindings associados.
89
- * @param {Object|Array} where - Condições do where.
90
- * @param {boolean} useRegex - Se deve usar REGEXP por padrão (para compatibilidade com update).
91
- * @returns {{ sql: string, bindings: Array }}
92
- */
93
- _buildWhereClause(where, useRegex = false) {
94
- if (!where) {
95
- return { sql: '', bindings: [] };
96
- }
97
-
98
- const conditions = [];
99
- const bindings = [];
100
-
101
- if (Array.isArray(where)) {
102
- where.forEach((param) => {
103
- if (typeof param === 'object' && param !== null && !Array.isArray(param)) {
104
- const entries = Object.entries(param);
105
- if (entries.length === 0) return;
106
-
107
- const [key, value] = entries[0];
108
- const [operatorKey, operatorValue] = entries[1] || [];
109
-
110
- let op = operatorValue ?? (useRegex ? 'REGEXP' : '=');
111
- let upperOp = String(op).toUpperCase();
112
-
113
- if (Array.isArray(value) && upperOp === '=') {
114
- op = 'IN';
115
- upperOp = 'IN';
116
- }
117
-
118
- if (Array.isArray(value) && (upperOp === 'IN' || upperOp === 'NOT IN')) {
119
- if (value.length === 0) {
120
- conditions.push(upperOp === 'IN' ? '1 = 0' : '1 = 1');
121
- } else {
122
- const placeholders = value.map(() => '?').join(', ');
123
- conditions.push(`\`${key}\` ${op} (${placeholders})`);
124
- bindings.push(...value);
125
- }
126
- } else {
127
- const condition = `\`${key}\` ${op} ?`;
128
- conditions.push(condition);
129
- bindings.push(value);
130
- }
131
- } else if (typeof param === 'string') {
132
- conditions.push(param.toUpperCase());
133
- }
134
- });
135
- return { sql: conditions.join(' '), bindings };
136
- } else if (typeof where === 'object' && where !== null) {
137
- const operator = useRegex ? 'REGEXP' : '=';
138
- const keys = Object.keys(where);
139
- const sql = keys.map(key => `\`${key}\` ${operator} ?`).join(' AND ');
140
- const bindings = Object.values(where);
141
- return { sql, bindings };
142
- }
143
-
144
- return { sql: '', bindings: [] };
145
- }
146
-
147
- async selectToDatatable(rawDtQuery, strictCondition = []) {
148
- // NOVO: Hidrata o objeto da requisição para o formato aninhado correto.
149
- const dtQuery = this._hydrateObject(rawDtQuery);
150
- const { draw, start, length, search, order, columns } = dtQuery;
151
-
152
- try {
153
- const baseWhere = this._parseStrictCondition(strictCondition);
154
- const finalBindings = [...baseWhere.bindings];
155
- const finalWhereClauses = baseWhere.sql ? [baseWhere.sql] : [];
156
-
157
- const dtSearchClauses = [];
158
- if (columns) {
159
- if (search && search.value !== '') {
160
- const globalSearch = columns
161
- .filter(c => c.data && c.searchable === 'true')
162
- .map(c => `\`${c.data}\` LIKE ?`);
163
-
164
- if (globalSearch.length > 0) {
165
- const regexSearch = search.regex === 'true' ? `${search.value}` : `%${search.value}%`;
166
- const operator = search.regex === 'true' ? 'REGEXP' : 'LIKE';
167
- const clauses = globalSearch.map(c => c.replace('LIKE ?', `${operator} ?`));
168
-
169
- dtSearchClauses.push(`(${clauses.join(' OR ')})`);
170
- for (let i = 0; i < globalSearch.length; i++) {
171
- finalBindings.push(regexSearch);
172
- }
173
- }
174
- }
175
- for (const col of columns) {
176
- if (col.data && col.searchable === 'true' && col.search && col.search.value !== '') {
177
- const regexSearch = col.search.regex === 'true' ? `${col.search.value}` : `%${col.search.value}%`;
178
- const operator = col.search.regex === 'true' ? 'REGEXP' : 'LIKE';
179
- dtSearchClauses.push(`\`${col.data}\` ${operator} ?`);
180
- finalBindings.push(regexSearch);
181
- }
182
- }
183
- }
184
-
185
- if (dtSearchClauses.length > 0) {
186
- finalWhereClauses.push(dtSearchClauses.join(' AND '));
187
- }
188
-
189
- const whereSql = finalWhereClauses.length > 0 ? `WHERE ${finalWhereClauses.join(' AND ')}` : '';
190
-
191
- let orderSql = '';
192
- if (order && order.length > 0 && columns) {
193
- const orderColumnIndex = order[0].column;
194
- if (columns[orderColumnIndex] && columns[orderColumnIndex].orderable === 'true' && columns[orderColumnIndex].data) {
195
- const orderColumnName = columns[orderColumnIndex].data;
196
- const orderDir = order[0].dir.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
197
- orderSql = `ORDER BY \`${orderColumnName}\` ${orderDir}`;
198
- }
199
- }
200
-
201
- const limitSql = (length && length != '-1') ? `LIMIT ${parseInt(start, 10)}, ${parseInt(length, 10)}` : '';
202
-
203
- // --- Queries ---
204
- const baseWhereSql = baseWhere.sql ? `WHERE ${baseWhere.sql}` : '';
205
- const totalCountSql = `SELECT COUNT(*) as total FROM ${this.table} ${baseWhereSql}`;
206
- const totalResult = await this.executeQuery(totalCountSql, baseWhere.bindings);
207
- // Contrato: executeQuery propaga { error } em caso de falha (não lança).
208
- if (totalResult && totalResult.error) {
209
- return {
210
- draw: parseInt(draw || 0),
211
- recordsTotal: 0,
212
- recordsFiltered: 0,
213
- data: [],
214
- error: totalResult.error.message
215
- };
216
- }
217
- const recordsTotal = (totalResult && totalResult[0] && totalResult[0].total) || 0;
218
-
219
- const filteredCountSql = `SELECT COUNT(*) as total FROM ${this.table} ${whereSql}`;
220
- const filteredResult = await this.executeQuery(filteredCountSql, finalBindings);
221
- if (filteredResult && filteredResult.error) {
222
- return {
223
- draw: parseInt(draw || 0),
224
- recordsTotal: parseInt(recordsTotal),
225
- recordsFiltered: 0,
226
- data: [],
227
- error: filteredResult.error.message
228
- };
229
- }
230
- const recordsFiltered = (filteredResult && filteredResult[0] && filteredResult[0].total) || 0;
231
-
232
- // CORREÇÃO: Construção segura da cláusula SELECT para evitar vírgulas duplas.
233
- const selectFields = ['*'];
234
- if (this.expression && this.expression.trim() !== '') {
235
- // Remove vírgula do início da expressão, se houver, para evitar duplicação
236
- selectFields.push(this.expression.trim().replace(/^,/, '').trim());
237
- }
238
- const dataSql = `SELECT ${selectFields.join(', ')} FROM ${this.table} ${whereSql} ${orderSql} ${limitSql}`;
239
- const data = await this.executeQuery(dataSql, finalBindings);
240
- if (data && data.error) {
241
- return {
242
- draw: parseInt(draw || 0),
243
- recordsTotal: parseInt(recordsTotal),
244
- recordsFiltered: parseInt(recordsFiltered),
245
- data: [],
246
- error: data.error.message
247
- };
248
- }
249
-
250
- return {
251
- draw: parseInt(draw || 0),
252
- recordsTotal: parseInt(recordsTotal),
253
- recordsFiltered: parseInt(recordsFiltered),
254
- data: data,
255
- };
256
-
257
- } catch (e) {
258
- console.error("Erro em selectToDatatable:", e);
259
- if (this.onError) this.onError(e);
260
- return {
261
- draw: parseInt(dtQuery.draw || 0),
262
- recordsTotal: 0,
263
- recordsFiltered: 0,
264
- data: [],
265
- error: e.message
266
- };
267
- }
268
- }
269
-
270
- async selectBy(params) {
271
- if (params) {
272
- const sql = `SELECT *${this.expression ? this.expression : ''} FROM ${this.table} WHERE ?`;
273
- const rows = await this.executeQuery(sql, params);
274
- return rows;//retorna um array, mesmo que vazio
275
- }
276
- else {
277
- const sql = `SELECT *${this.expression ? this.expression : ''} FROM ${this.table}`;
278
- return this.executeQuery(sql);
279
- }
280
- }
281
-
282
- async selectOld(params, clauses = {}) {
283
- if (params != null && !Array.isArray(params)) {
284
- return new Error('O parâmetro "params" deve ser um array');
285
- }
286
-
287
- const conditions = [];
288
- const values = [];
289
-
290
- if (params && params.length) {
291
- params.map((param) => {
292
- if (typeof param === 'object' && !Array.isArray(param)) {
293
- const entries = Object.entries(param);
294
- const [key, value] = entries[0];
295
- const [operator, opValue] = entries[1] || [];
296
-
297
- const condition = `\`${key}\` ${opValue ?? '='} ?`;
298
- conditions.push(condition);
299
- values.push(value);
300
- } else if (typeof param === 'string') {
301
- conditions.push(param.toUpperCase());
302
- }
303
- });
304
- }
305
-
306
- const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' ')}` : '';
307
-
308
- // Cláusulas adicionais
309
- const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
310
- const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
311
- const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
312
- const descClause = clauses['DESC'] ? ` DESC ` : '';
313
- const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
314
- const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
315
-
316
- const sql = `SELECT *${this.expression ?? ''} FROM ${this.table}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
317
-
318
- const rows = await this.executeQuery(sql, values);
319
- return rows;
320
- }
321
-
322
- async select(params, clauses = {}) {
323
- if (params != null && !Array.isArray(params)) {
324
- return new Error('O parâmetro "params" deve ser um array');
325
- }
326
-
327
- const { sql: whereSql, bindings: values } = this._buildWhereClause(params);
328
- const whereClause = whereSql ? ` WHERE ${whereSql}` : '';
329
-
330
- // Cláusulas adicionais
331
- const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
332
- const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
333
- const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
334
- const descClause = clauses['DESC'] ? ` DESC ` : '';
335
- const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
336
- const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
337
-
338
- const sql = `SELECT *${this.expression ?? ''} FROM ${this.table}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
339
-
340
- const rows = await this.executeQuery(sql, values);
341
- return rows;
342
- }
343
-
344
- async insert(params) {
345
- const sql = `INSERT INTO ${this.table} SET ?`;
346
- const result = await this.executeQuery(sql, params);
347
- return result;
348
- }
349
-
350
- async update(params, options = {}) {
351
- // Inicializa a string SQL para a cláusula SET
352
- let setClause = Object.keys(params.set).map(key => `\`${key}\` = ?`).join(', ');
353
- let setValues = Object.values(params.set);
354
-
355
- // Inicializa a string SQL para a cláusula WHERE
356
- const { sql: whereClause, bindings: whereValues } = this._buildWhereClause(params.where, !!options.useRegex);
357
-
358
- // Constrói a consulta SQL completa
359
- const sql = `UPDATE ${this.table} SET ${setClause} WHERE ${whereClause}`;
360
- // Combina os valores SET e WHERE em um único array
361
- const values = [...setValues, ...whereValues];
362
- // Executa a consulta
363
- const result = await this.executeQuery(sql, values);
364
-
365
- return result;
366
- }
367
-
368
- async delete(conditions) {
369
- const conditionKeys = Object.keys(conditions);
370
- if (conditionKeys.length === 0) {
371
- // Se o objeto conditions estiver vazio, não faz nada
372
- return;
373
- }
374
-
375
- const whereConditions = conditionKeys.map((key) => `${key} = ?`).join(' AND ');
376
- const sql = `DELETE FROM ${this.table} WHERE ${whereConditions}`;
377
- const params = conditionKeys.map((key) => conditions[key]);
378
- const result = await this.executeQuery(sql, params);
379
- return result;
380
- }
381
-
382
- }
383
-
384
- module.exports = DatabaseHandler;
1
+ const ALLOWED_OPERATORS = new Set([
2
+ '=', '!=', '<>', '>', '>=', '<', '<=',
3
+ 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
4
+ 'REGEXP', 'NOT REGEXP', 'IS', 'IS NOT', 'BETWEEN'
5
+ ]);
6
+
7
+ function sanitizeOperator(op, defaultOp = '=') {
8
+ if (!op) return defaultOp;
9
+ const upper = String(op).toUpperCase().trim();
10
+ return ALLOWED_OPERATORS.has(upper) ? upper : defaultOp;
11
+ }
12
+
13
+ function sanitizeIdentifier(name) {
14
+ if (!name || typeof name !== 'string') return '';
15
+ return name.replace(/`/g, '');
16
+ }
17
+
18
+ function safeTable(tableName) {
19
+ if (!tableName || typeof tableName !== 'string') return '';
20
+ // Se contiver '.', protege cada segmento (ex: `meubanco`.`minhatabela`)
21
+ return tableName.split('.').map(part => `\`${sanitizeIdentifier(part)}\``).join('.');
22
+ }
23
+
24
+ class DatabaseHandler {
25
+ constructor(database, table, expression = '') {
26
+ this.db = database;
27
+ this.table = table;
28
+ this.debug = false;
29
+ this.expression = expression;
30
+ this.onError = null;
31
+ }
32
+
33
+ _safeTable() {
34
+ return safeTable(this.table);
35
+ }
36
+
37
+ async executeQuery(sql, params, isWrite = false) {
38
+ const rows = await this.db.query(sql, params, isWrite);
39
+ return rows;
40
+ }
41
+
42
+ /**
43
+ * Clones this handler bound to a specific transaction or database executor.
44
+ * @param {Object} txOrDb - Transaction context or database instance.
45
+ * @returns {DatabaseHandler} A new handler instance.
46
+ */
47
+ withTransaction(txOrDb) {
48
+ const handler = new DatabaseHandler(txOrDb, this.table, this.expression);
49
+ handler.debug = this.debug;
50
+ handler.onError = this.onError;
51
+ return handler;
52
+ }
53
+
54
+ async getSchema() {
55
+ return await this.db.getTableSchema(this.table);
56
+ }
57
+
58
+ /**
59
+ * @private
60
+ * Converte um objeto "achatado" (form-urlencoded) em um objeto aninhado (JSON).
61
+ * Ex: { 'columns[0][data]': 'id' } => { columns: [{ data: 'id' }] }
62
+ * Protegido contra Prototype Pollution (CWE-1321).
63
+ */
64
+ _hydrateObject(flatObject) {
65
+ const result = {};
66
+ for (const key in flatObject) {
67
+ if (!Object.prototype.hasOwnProperty.call(flatObject, key)) continue;
68
+ const keys = key.match(/[^[\]']+/g); // Extrai chaves como ['columns', '0', 'data']
69
+ if (!keys) continue;
70
+
71
+ // Bloqueia poluição de protótipo
72
+ if (keys.some(k => k === '__proto__' || k === 'constructor' || k === 'prototype')) {
73
+ continue;
74
+ }
75
+
76
+ let current = result;
77
+ while (keys.length > 1) {
78
+ const k = keys.shift();
79
+ current[k] = current[k] || (isNaN(keys[0]) ? {} : []);
80
+ current = current[k];
81
+ }
82
+ current[keys[0]] = flatObject[key];
83
+ }
84
+ return result;
85
+ }
86
+
87
+ _parseStrictCondition(strictCondition) {
88
+ if (!strictCondition || !Array.isArray(strictCondition) || strictCondition.length === 0) {
89
+ return { sql: '', bindings: [] };
90
+ }
91
+ const clauses = [];
92
+ const bindings = [];
93
+ for (const item of strictCondition) {
94
+ if (typeof item === 'string') {
95
+ const upper = item.toUpperCase().trim();
96
+ // Operadores lógicos (AND / OR) válidos são inseridos como-is
97
+ if (upper === 'AND' || upper === 'OR') {
98
+ clauses.push(upper);
99
+ }
100
+ } else if (typeof item === 'object' && item !== null) {
101
+ const key = Object.keys(item).find(k => k.toLowerCase() !== 'operator');
102
+ if (!key) continue;
103
+ const cleanKey = sanitizeIdentifier(key);
104
+ const value = item[key];
105
+ let operator = sanitizeOperator(item.operator, '=');
106
+
107
+ // Suporte a arrays => IN / NOT IN (consistente com _buildWhereClause)
108
+ if (Array.isArray(value) && operator === '=') {
109
+ operator = 'IN';
110
+ }
111
+
112
+ if (Array.isArray(value) && (operator === 'IN' || operator === 'NOT IN')) {
113
+ if (value.length === 0) {
114
+ clauses.push(operator === 'IN' ? '1 = 0' : '1 = 1');
115
+ } else {
116
+ const placeholders = value.map(() => '?').join(', ');
117
+ clauses.push(`\`${cleanKey}\` ${operator} (${placeholders})`);
118
+ bindings.push(...value);
119
+ }
120
+ } else {
121
+ clauses.push(`\`${cleanKey}\` ${operator} ?`);
122
+ bindings.push(value);
123
+ }
124
+ }
125
+ }
126
+ // Junta com espaço para preservar operadores AND/OR intercalados.
127
+ return { sql: `(${clauses.join(' ')})`, bindings };
128
+ }
129
+
130
+ /**
131
+ * @private
132
+ * Constrói a cláusula WHERE (sem a palavra-chave WHERE) e seus bindings associados.
133
+ * @param {Object|Array} where - Condições do where.
134
+ * @param {boolean} useRegex - Se deve usar REGEXP por padrão (para compatibilidade com update).
135
+ * @returns {{ sql: string, bindings: Array }}
136
+ */
137
+ _buildWhereClause(where, useRegex = false) {
138
+ if (!where) {
139
+ return { sql: '', bindings: [] };
140
+ }
141
+
142
+ const conditions = [];
143
+ const bindings = [];
144
+
145
+ if (Array.isArray(where)) {
146
+ where.forEach((param) => {
147
+ if (typeof param === 'object' && param !== null && !Array.isArray(param)) {
148
+ const keys = Object.keys(param);
149
+ const colKey = keys.find(k => k.toLowerCase() !== 'operator');
150
+ if (!colKey) return;
151
+
152
+ const cleanKey = sanitizeIdentifier(colKey);
153
+ const value = param[colKey];
154
+ const opKey = keys.find(k => k.toLowerCase() === 'operator');
155
+ const opValue = opKey ? param[opKey] : undefined;
156
+
157
+ let op = sanitizeOperator(opValue, useRegex ? 'REGEXP' : '=');
158
+
159
+ if (Array.isArray(value) && op === '=') {
160
+ op = 'IN';
161
+ }
162
+
163
+ if (Array.isArray(value) && (op === 'IN' || op === 'NOT IN')) {
164
+ if (value.length === 0) {
165
+ conditions.push(op === 'IN' ? '1 = 0' : '1 = 1');
166
+ } else {
167
+ const placeholders = value.map(() => '?').join(', ');
168
+ conditions.push(`\`${cleanKey}\` ${op} (${placeholders})`);
169
+ bindings.push(...value);
170
+ }
171
+ } else {
172
+ const condition = `\`${cleanKey}\` ${op} ?`;
173
+ conditions.push(condition);
174
+ bindings.push(value);
175
+ }
176
+ } else if (typeof param === 'string') {
177
+ const upper = param.toUpperCase().trim();
178
+ if (upper === 'AND' || upper === 'OR') {
179
+ conditions.push(upper);
180
+ }
181
+ }
182
+ });
183
+ return { sql: conditions.join(' '), bindings };
184
+ } else if (typeof where === 'object' && where !== null) {
185
+ const operator = useRegex ? 'REGEXP' : '=';
186
+ const keys = Object.keys(where);
187
+ const sql = keys.map(key => `\`${sanitizeIdentifier(key)}\` ${operator} ?`).join(' AND ');
188
+ const bindings = Object.values(where);
189
+ return { sql, bindings };
190
+ }
191
+
192
+ return { sql: '', bindings: [] };
193
+ }
194
+
195
+ async selectToDatatable(rawDtQuery, strictCondition = []) {
196
+ // Hidrata o objeto da requisição para o formato aninhado correto de forma segura
197
+ const dtQuery = this._hydrateObject(rawDtQuery);
198
+ const { draw, start, length, search, order, columns } = dtQuery;
199
+ const table = this._safeTable();
200
+
201
+ try {
202
+ const baseWhere = this._parseStrictCondition(strictCondition);
203
+ const finalBindings = [...baseWhere.bindings];
204
+ const finalWhereClauses = baseWhere.sql ? [baseWhere.sql] : [];
205
+
206
+ const dtSearchClauses = [];
207
+ if (columns) {
208
+ if (search && search.value !== '') {
209
+ const globalSearch = columns
210
+ .filter(c => c.data && c.searchable === 'true')
211
+ .map(c => `\`${sanitizeIdentifier(c.data)}\` LIKE ?`);
212
+
213
+ if (globalSearch.length > 0) {
214
+ const regexSearch = search.regex === 'true' ? `${search.value}` : `%${search.value}%`;
215
+ const operator = search.regex === 'true' ? 'REGEXP' : 'LIKE';
216
+ const clauses = globalSearch.map(c => c.replace('LIKE ?', `${operator} ?`));
217
+
218
+ dtSearchClauses.push(`(${clauses.join(' OR ')})`);
219
+ for (let i = 0; i < globalSearch.length; i++) {
220
+ finalBindings.push(regexSearch);
221
+ }
222
+ }
223
+ }
224
+ for (const col of columns) {
225
+ if (col.data && col.searchable === 'true' && col.search && col.search.value !== '') {
226
+ const regexSearch = col.search.regex === 'true' ? `${col.search.value}` : `%${col.search.value}%`;
227
+ const operator = col.search.regex === 'true' ? 'REGEXP' : 'LIKE';
228
+ dtSearchClauses.push(`\`${sanitizeIdentifier(col.data)}\` ${operator} ?`);
229
+ finalBindings.push(regexSearch);
230
+ }
231
+ }
232
+ }
233
+
234
+ if (dtSearchClauses.length > 0) {
235
+ finalWhereClauses.push(dtSearchClauses.join(' AND '));
236
+ }
237
+
238
+ const whereSql = finalWhereClauses.length > 0 ? `WHERE ${finalWhereClauses.join(' AND ')}` : '';
239
+
240
+ let orderSql = '';
241
+ if (order && order.length > 0 && columns) {
242
+ const orderColumnIndex = order[0].column;
243
+ if (columns[orderColumnIndex] && columns[orderColumnIndex].orderable === 'true' && columns[orderColumnIndex].data) {
244
+ const orderColumnName = sanitizeIdentifier(columns[orderColumnIndex].data);
245
+ const orderDir = order[0].dir && order[0].dir.toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
246
+ orderSql = `ORDER BY \`${orderColumnName}\` ${orderDir}`;
247
+ }
248
+ }
249
+
250
+ const safeStart = Math.max(0, parseInt(start, 10) || 0);
251
+ const parsedLength = parseInt(length, 10);
252
+ const limitSql = (!isNaN(parsedLength) && parsedLength !== -1) ? `LIMIT ${safeStart}, ${parsedLength}` : '';
253
+
254
+ // --- Queries ---
255
+ const baseWhereSql = baseWhere.sql ? `WHERE ${baseWhere.sql}` : '';
256
+ const totalCountSql = `SELECT COUNT(*) as total FROM ${table} ${baseWhereSql}`;
257
+ const totalResult = await this.executeQuery(totalCountSql, baseWhere.bindings);
258
+ // Contrato: executeQuery propaga { error } em caso de falha (não lança).
259
+ if (totalResult && totalResult.error) {
260
+ return {
261
+ draw: parseInt(draw || 0),
262
+ recordsTotal: 0,
263
+ recordsFiltered: 0,
264
+ data: [],
265
+ error: totalResult.error.message
266
+ };
267
+ }
268
+ const recordsTotal = (totalResult && totalResult[0] && totalResult[0].total) || 0;
269
+
270
+ const filteredCountSql = `SELECT COUNT(*) as total FROM ${table} ${whereSql}`;
271
+ const filteredResult = await this.executeQuery(filteredCountSql, finalBindings);
272
+ if (filteredResult && filteredResult.error) {
273
+ return {
274
+ draw: parseInt(draw || 0),
275
+ recordsTotal: parseInt(recordsTotal),
276
+ recordsFiltered: 0,
277
+ data: [],
278
+ error: filteredResult.error.message
279
+ };
280
+ }
281
+ const recordsFiltered = (filteredResult && filteredResult[0] && filteredResult[0].total) || 0;
282
+
283
+ // Construção segura da cláusula SELECT para evitar vírgulas duplas.
284
+ const selectFields = ['*'];
285
+ if (this.expression && this.expression.trim() !== '') {
286
+ // Remove vírgula do início da expressão, se houver, para evitar duplicação
287
+ selectFields.push(this.expression.trim().replace(/^,/, '').trim());
288
+ }
289
+ const dataSql = `SELECT ${selectFields.join(', ')} FROM ${table} ${whereSql} ${orderSql} ${limitSql}`;
290
+ const data = await this.executeQuery(dataSql, finalBindings);
291
+ if (data && data.error) {
292
+ return {
293
+ draw: parseInt(draw || 0),
294
+ recordsTotal: parseInt(recordsTotal),
295
+ recordsFiltered: parseInt(recordsFiltered),
296
+ data: [],
297
+ error: data.error.message
298
+ };
299
+ }
300
+
301
+ return {
302
+ draw: parseInt(draw || 0),
303
+ recordsTotal: parseInt(recordsTotal),
304
+ recordsFiltered: parseInt(recordsFiltered),
305
+ data: data,
306
+ };
307
+
308
+ } catch (e) {
309
+ console.error("Erro em selectToDatatable:", e);
310
+ if (this.onError) this.onError(e);
311
+ return {
312
+ draw: parseInt(dtQuery.draw || 0),
313
+ recordsTotal: 0,
314
+ recordsFiltered: 0,
315
+ data: [],
316
+ error: e.message
317
+ };
318
+ }
319
+ }
320
+
321
+ async selectBy(params) {
322
+ const table = this._safeTable();
323
+ if (params) {
324
+ const sql = `SELECT *${this.expression ? this.expression : ''} FROM ${table} WHERE ?`;
325
+ const rows = await this.executeQuery(sql, params);
326
+ return rows; // retorna um array, mesmo que vazio
327
+ }
328
+ else {
329
+ const sql = `SELECT *${this.expression ? this.expression : ''} FROM ${table}`;
330
+ return this.executeQuery(sql);
331
+ }
332
+ }
333
+
334
+ /**
335
+ * @deprecated Use select() instead.
336
+ */
337
+ async selectOld(params, clauses = {}) {
338
+ if (params != null && !Array.isArray(params)) {
339
+ return new Error('O parâmetro "params" deve ser um array');
340
+ }
341
+
342
+ const conditions = [];
343
+ const values = [];
344
+
345
+ if (params && params.length) {
346
+ params.map((param) => {
347
+ if (typeof param === 'object' && !Array.isArray(param)) {
348
+ const entries = Object.entries(param);
349
+ const [key, value] = entries[0];
350
+ const [operator, opValue] = entries[1] || [];
351
+
352
+ const cleanKey = sanitizeIdentifier(key);
353
+ const condition = `\`${cleanKey}\` ${opValue ?? '='} ?`;
354
+ conditions.push(condition);
355
+ values.push(value);
356
+ } else if (typeof param === 'string') {
357
+ conditions.push(param.toUpperCase());
358
+ }
359
+ });
360
+ }
361
+
362
+ const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' ')}` : '';
363
+
364
+ // Cláusulas adicionais
365
+ const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
366
+ const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
367
+ const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
368
+ const descClause = clauses['DESC'] ? ` DESC ` : '';
369
+ const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
370
+ const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
371
+
372
+ const sql = `SELECT *${this.expression ?? ''} FROM ${this._safeTable()}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
373
+
374
+ const rows = await this.executeQuery(sql, values);
375
+ return rows;
376
+ }
377
+
378
+ async select(params, clauses = {}) {
379
+ if (params != null && !Array.isArray(params)) {
380
+ return new Error('O parâmetro "params" deve ser um array');
381
+ }
382
+
383
+ const { sql: whereSql, bindings: values } = this._buildWhereClause(params);
384
+ const whereClause = whereSql ? ` WHERE ${whereSql}` : '';
385
+
386
+ // Cláusulas adicionais
387
+ const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
388
+ const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
389
+ const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
390
+ const descClause = clauses['DESC'] ? ` DESC ` : '';
391
+ const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
392
+ const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
393
+
394
+ const sql = `SELECT *${this.expression ?? ''} FROM ${this._safeTable()}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
395
+
396
+ const rows = await this.executeQuery(sql, values);
397
+ return rows;
398
+ }
399
+
400
+ async insert(params) {
401
+ const sql = `INSERT INTO ${this._safeTable()} SET ?`;
402
+ const result = await this.executeQuery(sql, params, true);
403
+ return result;
404
+ }
405
+
406
+ async update(params, options = {}) {
407
+ if (!params || typeof params !== 'object' || !params.set || typeof params.set !== 'object' || Object.keys(params.set).length === 0) {
408
+ throw new Error('A operação de update requer um objeto "set" com ao menos um campo.');
409
+ }
410
+
411
+ // Inicializa a string SQL para a cláusula SET
412
+ let setClause = Object.keys(params.set).map(key => `\`${sanitizeIdentifier(key)}\` = ?`).join(', ');
413
+ let setValues = Object.values(params.set);
414
+
415
+ // Inicializa a string SQL para a cláusula WHERE
416
+ const { sql: whereClause, bindings: whereValues } = this._buildWhereClause(params.where, !!options.useRegex);
417
+ if (!whereClause || whereClause.trim() === '') {
418
+ throw new Error('A operação de update requer uma cláusula "where" não vazia para prevenir alterações em toda a tabela.');
419
+ }
420
+
421
+ // Constrói a consulta SQL completa
422
+ const sql = `UPDATE ${this._safeTable()} SET ${setClause} WHERE ${whereClause}`;
423
+ // Combina os valores SET e WHERE em um único array
424
+ const values = [...setValues, ...whereValues];
425
+ // Executa a consulta sinalizando mutação de escrita
426
+ const result = await this.executeQuery(sql, values, true);
427
+
428
+ return result;
429
+ }
430
+
431
+ async delete(conditions) {
432
+ if (!conditions || typeof conditions !== 'object') {
433
+ return;
434
+ }
435
+ const conditionKeys = Object.keys(conditions);
436
+ if (conditionKeys.length === 0) {
437
+ // Se o objeto conditions estiver vazio, não faz nada para evitar truncar a tabela
438
+ return;
439
+ }
440
+
441
+ const whereConditions = conditionKeys.map((key) => `\`${sanitizeIdentifier(key)}\` = ?`).join(' AND ');
442
+ const sql = `DELETE FROM ${this._safeTable()} WHERE ${whereConditions}`;
443
+ const params = conditionKeys.map((key) => conditions[key]);
444
+ const result = await this.executeQuery(sql, params, true);
445
+ return result;
446
+ }
447
+ }
448
+
449
+ module.exports = DatabaseHandler;