@areumtecnologia/mysql-db-handler 1.0.3 → 1.0.5
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 +25 -10
- package/lib/databaseHandler.js +76 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# mysql-db-handler
|
|
1
|
+
# @areumtecnologia/mysql-db-handler
|
|
2
2
|
|
|
3
3
|
A powerful MySQL wrapper with connection pooling, singleton support, and advanced query handling for Node.js.
|
|
4
4
|
|
|
@@ -13,7 +13,7 @@ A powerful MySQL wrapper with connection pooling, singleton support, and advance
|
|
|
13
13
|
## Installation
|
|
14
14
|
|
|
15
15
|
```bash
|
|
16
|
-
npm install mysql-db-handler
|
|
16
|
+
npm install @areumtecnologia/mysql-db-handler
|
|
17
17
|
```
|
|
18
18
|
|
|
19
19
|
## Basic Usage
|
|
@@ -22,7 +22,7 @@ npm install mysql-db-handler
|
|
|
22
22
|
You can create a new instance of the database class directly.
|
|
23
23
|
|
|
24
24
|
```javascript
|
|
25
|
-
const { DataBase } = require('mysql-db-handler');
|
|
25
|
+
const { DataBase } = require('@areumtecnologia/mysql-db-handler');
|
|
26
26
|
|
|
27
27
|
const db = new DataBase({
|
|
28
28
|
host: 'localhost',
|
|
@@ -50,22 +50,37 @@ try {
|
|
|
50
50
|
The `DataBaseHandler` simplifies interactions with specific tables.
|
|
51
51
|
|
|
52
52
|
```javascript
|
|
53
|
-
const { DataBaseHandler } = require('mysql-db-handler');
|
|
53
|
+
const { DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
|
|
54
54
|
|
|
55
55
|
// Initialize handler for 'customers' table
|
|
56
56
|
const customers = new DataBaseHandler(db, 'customers');
|
|
57
|
-
|
|
58
|
-
// Select all
|
|
59
|
-
const allCustomers = await customers.select();
|
|
60
|
-
|
|
61
|
-
// Select with conditions
|
|
62
|
-
const activeCustomers = await customers.selectBy({ status: 1 });
|
|
63
57
|
```
|
|
64
58
|
|
|
65
59
|
---
|
|
66
60
|
|
|
67
61
|
## Advanced Usage & Examples
|
|
68
62
|
|
|
63
|
+
### Inserting Records (`insert`)
|
|
64
|
+
|
|
65
|
+
The `insert` method adds a new row to the table.
|
|
66
|
+
|
|
67
|
+
**Parameters:**
|
|
68
|
+
* `params` (Object): An object where keys match the column names and values are the data to insert.
|
|
69
|
+
|
|
70
|
+
**Example:**
|
|
71
|
+
|
|
72
|
+
```javascript
|
|
73
|
+
const logs = new DataBaseHandler(db, 'app_logs');
|
|
74
|
+
|
|
75
|
+
const result = await logs.insert({
|
|
76
|
+
level: 'info',
|
|
77
|
+
message: 'User logged in',
|
|
78
|
+
timestamp: new Date()
|
|
79
|
+
});
|
|
80
|
+
// Executes: INSERT INTO app_logs SET `level` = ?, `message` = ?, `timestamp` = ?
|
|
81
|
+
console.log(`Inserted Row ID: ${result.insertId}`);
|
|
82
|
+
```
|
|
83
|
+
|
|
69
84
|
### Flexible Selection (`select`)
|
|
70
85
|
|
|
71
86
|
The `select` method allows you to build complex queries using an array of parameters and a clauses object.
|
package/lib/databaseHandler.js
CHANGED
|
@@ -169,7 +169,7 @@ class DatabaseHandler {
|
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
-
async
|
|
172
|
+
async selectOld(params, clauses = {}) {
|
|
173
173
|
if (params != null && !Array.isArray(params)) {
|
|
174
174
|
return new Error('O parâmetro "params" deve ser um array');
|
|
175
175
|
}
|
|
@@ -209,6 +209,81 @@ class DatabaseHandler {
|
|
|
209
209
|
return rows;
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
+
async select(params, clauses = {}) {
|
|
213
|
+
if (params != null && !Array.isArray(params)) {
|
|
214
|
+
return new Error('O parâmetro "params" deve ser um array');
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const conditions = [];
|
|
218
|
+
const values = [];
|
|
219
|
+
|
|
220
|
+
if (params && params.length) {
|
|
221
|
+
// Dica: Troquei map por forEach. O map é para transformar arrays,
|
|
222
|
+
// como você só está preenchendo variáveis externas, forEach é semanticamente correto.
|
|
223
|
+
params.forEach((param) => {
|
|
224
|
+
if (typeof param === 'object' && !Array.isArray(param)) {
|
|
225
|
+
const entries = Object.entries(param);
|
|
226
|
+
const [key, value] = entries[0];
|
|
227
|
+
const [operatorKey, operatorValue] = entries[1] || [];
|
|
228
|
+
|
|
229
|
+
// --- INÍCIO DAS MODIFICAÇÕES PARA SUPORTE AO IN ---
|
|
230
|
+
|
|
231
|
+
// 1. Define o operador (padrão é '=')
|
|
232
|
+
let op = operatorValue ?? '=';
|
|
233
|
+
const upperOp = op.toUpperCase();
|
|
234
|
+
|
|
235
|
+
// 2. "Magia": Se o valor for um array e não tiver operador (ou for '='),
|
|
236
|
+
// converte automaticamente para 'IN' para facilitar sua vida.
|
|
237
|
+
if (Array.isArray(value) && upperOp === '=') {
|
|
238
|
+
op = 'IN';
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// 3. Lógica específica para IN e NOT IN
|
|
242
|
+
if (Array.isArray(value) && (upperOp === 'IN' || upperOp === 'NOT IN')) {
|
|
243
|
+
if (value.length === 0) {
|
|
244
|
+
// O SQL não permite "IN ()".
|
|
245
|
+
// Um IN vazio nunca encontra nada (falso), um NOT IN vazio encontra tudo (verdadeiro).
|
|
246
|
+
conditions.push(upperOp === 'IN' ? '1 = 0' : '1 = 1');
|
|
247
|
+
} else {
|
|
248
|
+
// Cria a string de placeholders: "?, ?, ?" baseada no tamanho do array
|
|
249
|
+
const placeholders = value.map(() => '?').join(', ');
|
|
250
|
+
conditions.push(`\`${key}\` ${op} (${placeholders})`);
|
|
251
|
+
|
|
252
|
+
// Espalha os valores do array individualmente no array de values
|
|
253
|
+
values.push(...value);
|
|
254
|
+
}
|
|
255
|
+
} else {
|
|
256
|
+
// 4. Lógica original para valores únicos (string, number, boolean, etc)
|
|
257
|
+
// ou outros operadores (LIKE, REGEXP, >, <, etc)
|
|
258
|
+
const condition = `\`${key}\` ${op} ?`;
|
|
259
|
+
conditions.push(condition);
|
|
260
|
+
values.push(value);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// --- FIM DAS MODIFICAÇÕES ---
|
|
264
|
+
|
|
265
|
+
} else if (typeof param === 'string') {
|
|
266
|
+
conditions.push(param.toUpperCase());
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' ')}` : '';
|
|
272
|
+
|
|
273
|
+
// Cláusulas adicionais
|
|
274
|
+
const groupByClause = clauses['GROUPBY'] ? ` GROUP BY ${clauses['GROUPBY']}` : '';
|
|
275
|
+
const havingClause = clauses['HAVING'] ? ` HAVING ${clauses['HAVING']}` : '';
|
|
276
|
+
const orderClause = clauses['ORDERBY'] ? ` ORDER BY ${clauses['ORDERBY']}` : '';
|
|
277
|
+
const descClause = clauses['DESC'] ? ` DESC ` : '';
|
|
278
|
+
const limitClause = clauses['LIMIT'] ? ` LIMIT ${clauses['LIMIT']}` : '';
|
|
279
|
+
const offsetClause = clauses['OFFSET'] ? ` OFFSET ${clauses['OFFSET']}` : '';
|
|
280
|
+
|
|
281
|
+
const sql = `SELECT *${this.expression ?? ''} FROM ${this.table}${whereClause}${groupByClause}${havingClause}${orderClause}${descClause}${limitClause}${offsetClause}`;
|
|
282
|
+
|
|
283
|
+
const rows = await this.executeQuery(sql, values);
|
|
284
|
+
return rows;
|
|
285
|
+
}
|
|
286
|
+
|
|
212
287
|
async insert(params) {
|
|
213
288
|
const sql = `INSERT INTO ${this.table} SET ?`;
|
|
214
289
|
const result = await this.executeQuery(sql, params);
|
package/package.json
CHANGED