@areumtecnologia/mysql-db-handler 1.0.13 → 2.0.0
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 +324 -14
- package/idex.d.ts +137 -0
- package/index.d.ts +204 -0
- package/lib/database-cache.js +118 -30
- package/lib/database.js +230 -157
- package/lib/databaseHandler.js +1104 -245
- package/package.json +15 -14
package/README.md
CHANGED
|
@@ -25,7 +25,14 @@ A powerful, robust, and production-ready MySQL wrapper for Node.js. It features
|
|
|
25
25
|
* [Inserting Records (`insert`)](#inserting-records-insert)
|
|
26
26
|
* [Updating Records (`update`)](#updating-records-update)
|
|
27
27
|
* [Deleting Records (`delete`)](#deleting-records-delete)
|
|
28
|
-
* [jQuery DataTables Server-Side Support](#jquery-datatables-server-side-support)
|
|
28
|
+
* [jQuery DataTables Server-Side Support (`selectToDatatable`)](#jquery-datatables-server-side-support-selecttodatatable)
|
|
29
|
+
* [Key Features & Performance](#key-features--performance-optimizations)
|
|
30
|
+
* [Method Signature](#method-signature)
|
|
31
|
+
* [Basic Express.js Example](#basic-expressjs-example)
|
|
32
|
+
* [Enforcing Backend Security (`strictCondition`)](#enforcing-backend-security-strictcondition)
|
|
33
|
+
* [Using JOINs and Custom Expressions](#using-joins-and-custom-expressions)
|
|
34
|
+
* [Frontend jQuery DataTables Setup](#frontend-jquery-datatables-setup)
|
|
35
|
+
* [Response Structure & Error Handling](#response-structure--error-handling)
|
|
29
36
|
* [Transaction Support (ACID & Transparent)](#transaction-support-acid--transparent)
|
|
30
37
|
* [1. Explicit Block (`db.transaction`)](#1-explicit-block-dbtransaction)
|
|
31
38
|
* [2. Singleton Compatibility with `AsyncLocalStorage`](#2-singleton-compatibility-with-asynclocalstorage)
|
|
@@ -316,30 +323,168 @@ console.log('Deleted rows:', result.affectedRows);
|
|
|
316
323
|
|
|
317
324
|
---
|
|
318
325
|
|
|
319
|
-
## jQuery DataTables Server-Side Support
|
|
326
|
+
## jQuery DataTables Server-Side Support (`selectToDatatable`)
|
|
320
327
|
|
|
321
|
-
The `selectToDatatable` method
|
|
328
|
+
The `selectToDatatable` method provides seamless, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It automatically handles pagination, search (global and column-based), multi-column ordering, regex filters, total/filtered counts, and backend security constraints.
|
|
329
|
+
|
|
330
|
+
### Key Features & Performance Optimizations
|
|
331
|
+
|
|
332
|
+
* **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state in standard page loads and pagination), `recordsFiltered` is automatically set to `recordsTotal`. The method skips the redundant second `COUNT(*)` query, **reducing database count latency and I/O by up to 50%**.
|
|
333
|
+
* **Short-Circuit on Zero Results:** If search criteria yield zero records (`recordsFiltered === 0`), the data retrieval query (`SELECT ... LIMIT`) is skipped entirely, returning an empty array `data: []` instantly without triggering expensive `filesort` or index scans.
|
|
334
|
+
* **Format & Content-Type Agnostic:** Fully supports both `application/json` (with native JavaScript boolean values `true`/`false`) and `application/x-www-form-urlencoded` (nested or bracket-flattened parameters like `columns[0][data]`).
|
|
335
|
+
* **Multi-Column Sorting:** Seamlessly parses multiple order directives (e.g. holding Shift or configuring `order: [[0, 'asc'], [1, 'desc']]`), producing `ORDER BY \`col1\` ASC, \`col2\` DESC`.
|
|
336
|
+
* **Safe Qualified Column Identifiers:** Automatically splits table/alias qualified column names (e.g. `u.name`, `p.title`) and escapes each component separately (`` `u`.`name` ``), avoiding MySQL `ER_BAD_FIELD_ERROR` issues when using JOINs.
|
|
337
|
+
* **Prototype Pollution Protection (CWE-1321):** Deeply sanitizes incoming request keys, blocking injections targeting `__proto__`, `constructor`, or `prototype`.
|
|
338
|
+
|
|
339
|
+
---
|
|
340
|
+
|
|
341
|
+
### Method Signature
|
|
322
342
|
|
|
323
343
|
```javascript
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
344
|
+
await handler.selectToDatatable(rawDtQuery, strictCondition = [])
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
| Parameter | Type | Description |
|
|
348
|
+
| :--- | :--- | :--- |
|
|
349
|
+
| `rawDtQuery` | `Object` | The request payload sent by jQuery DataTables (`req.body` or `req.query`). Supports both flat bracketed keys and nested objects. |
|
|
350
|
+
| `strictCondition` | `Array` *(Optional)* | Backend conditions that the client cannot view or modify (e.g. multi-tenant isolation, user scoping, active-only filters). |
|
|
351
|
+
|
|
352
|
+
---
|
|
353
|
+
|
|
354
|
+
### Basic Express.js Example
|
|
355
|
+
|
|
356
|
+
```javascript
|
|
357
|
+
const express = require('express');
|
|
358
|
+
const { db, usersHandler } = require('./databaseController');
|
|
359
|
+
|
|
360
|
+
const app = express();
|
|
361
|
+
app.use(express.json());
|
|
362
|
+
app.use(express.urlencoded({ extended: true }));
|
|
363
|
+
|
|
364
|
+
app.post('/api/users/datatable', async (req, res) => {
|
|
365
|
+
// req.body contains: { draw, start, length, search, order, columns }
|
|
366
|
+
const result = await usersHandler.selectToDatatable(req.body);
|
|
367
|
+
res.json(result);
|
|
368
|
+
});
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
---
|
|
372
|
+
|
|
373
|
+
### Enforcing Backend Security (`strictCondition`)
|
|
374
|
+
|
|
375
|
+
Never rely on the client to enforce data access boundaries. Pass a `strictCondition` array to apply non-bypassable constraints. It shares the same query-building syntax as `select()`, supporting custom operators, arrays (`IN`), and `AND`/`OR` conjunctions:
|
|
376
|
+
|
|
377
|
+
```javascript
|
|
378
|
+
app.post('/api/orders/datatable', async (req, res) => {
|
|
379
|
+
// Client-side parameters cannot bypass these conditions:
|
|
330
380
|
const strictConditions = [
|
|
331
381
|
{ tenant_id: req.user.tenantId },
|
|
332
382
|
'AND',
|
|
333
|
-
{ status: 'deleted', operator: '!=' }
|
|
383
|
+
{ status: 'deleted', operator: '!=' },
|
|
384
|
+
'AND',
|
|
385
|
+
{ store_id: [101, 102, 105] } // Automatically mapped to: `store_id` IN (?, ?, ?)
|
|
334
386
|
];
|
|
335
387
|
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
// Returns: { draw: 1, recordsTotal: 100, recordsFiltered: 12, data: [...] }
|
|
339
|
-
res.json(datatableResult);
|
|
388
|
+
const result = await ordersHandler.selectToDatatable(req.body, strictConditions);
|
|
389
|
+
res.json(result);
|
|
340
390
|
});
|
|
341
391
|
```
|
|
342
392
|
|
|
393
|
+
---
|
|
394
|
+
|
|
395
|
+
### Using JOINs and Custom Expressions
|
|
396
|
+
|
|
397
|
+
If your table requires JOINs or computed fields, initialize the `DataBaseHandler` with an expression parameter:
|
|
398
|
+
|
|
399
|
+
```javascript
|
|
400
|
+
// Table: 'sales s'
|
|
401
|
+
// Expression: JOIN with customers and users, selecting extra fields
|
|
402
|
+
const salesHandler = new DataBaseHandler(
|
|
403
|
+
db,
|
|
404
|
+
'customers_sales s',
|
|
405
|
+
', c.name AS customer_name, u.name AS user_name ' +
|
|
406
|
+
'LEFT JOIN customers c ON c.id = s.customer ' +
|
|
407
|
+
'LEFT JOIN users u ON u.id = s.user'
|
|
408
|
+
);
|
|
409
|
+
|
|
410
|
+
app.post('/api/sales/datatable', async (req, res) => {
|
|
411
|
+
// DataTables columns can now search and sort by qualified identifiers:
|
|
412
|
+
// e.g. columns: [{ data: 's.id' }, { data: 'c.name' }, { data: 's.amount' }]
|
|
413
|
+
const result = await salesHandler.selectToDatatable(req.body, [
|
|
414
|
+
{ 's.deleted_at': null, operator: 'IS' }
|
|
415
|
+
]);
|
|
416
|
+
res.json(result);
|
|
417
|
+
});
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
422
|
+
### Frontend jQuery DataTables Setup
|
|
423
|
+
|
|
424
|
+
Configure your frontend DataTables instance with `serverSide: true`:
|
|
425
|
+
|
|
426
|
+
```javascript
|
|
427
|
+
$('#usersTable').DataTable({
|
|
428
|
+
processing: true,
|
|
429
|
+
serverSide: true,
|
|
430
|
+
ajax: {
|
|
431
|
+
url: '/api/users/datatable',
|
|
432
|
+
type: 'POST',
|
|
433
|
+
contentType: 'application/json',
|
|
434
|
+
data: function (d) {
|
|
435
|
+
return JSON.stringify(d);
|
|
436
|
+
}
|
|
437
|
+
},
|
|
438
|
+
columns: [
|
|
439
|
+
{ data: 'id', name: 'id' },
|
|
440
|
+
{ data: 'name', name: 'name' },
|
|
441
|
+
{ data: 'email', name: 'email' },
|
|
442
|
+
{ data: 'role', name: 'role' },
|
|
443
|
+
{
|
|
444
|
+
data: null,
|
|
445
|
+
orderable: false,
|
|
446
|
+
searchable: false,
|
|
447
|
+
render: function (data, type, row) {
|
|
448
|
+
return `<button onclick="editUser(${row.id})">Edit</button>`;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
],
|
|
452
|
+
order: [[0, 'desc']]
|
|
453
|
+
});
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
---
|
|
457
|
+
|
|
458
|
+
### Response Structure & Error Handling
|
|
459
|
+
|
|
460
|
+
The method always returns the standard JSON response expected by DataTables:
|
|
461
|
+
|
|
462
|
+
#### Success Response
|
|
463
|
+
```json
|
|
464
|
+
{
|
|
465
|
+
"draw": 1,
|
|
466
|
+
"recordsTotal": 1250,
|
|
467
|
+
"recordsFiltered": 45,
|
|
468
|
+
"data": [
|
|
469
|
+
{ "id": 42, "name": "John Doe", "email": "john@example.com", "role": "admin" },
|
|
470
|
+
{ "id": 43, "name": "Jane Smith", "email": "jane@example.com", "role": "editor" }
|
|
471
|
+
]
|
|
472
|
+
}
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
#### Safe Error Handling
|
|
476
|
+
If an underlying database error occurs, `selectToDatatable` catches it safely, notifies your `onError` handler (if configured), and returns a structured response with the error message so the client table does not hang indefinitely:
|
|
477
|
+
|
|
478
|
+
```json
|
|
479
|
+
{
|
|
480
|
+
"draw": 1,
|
|
481
|
+
"recordsTotal": 0,
|
|
482
|
+
"recordsFiltered": 0,
|
|
483
|
+
"data": [],
|
|
484
|
+
"error": "ER_NO_SUCH_TABLE: Table 'my_app_db.invalid_table' doesn't exist"
|
|
485
|
+
}
|
|
486
|
+
```
|
|
487
|
+
|
|
343
488
|
|
|
344
489
|
---
|
|
345
490
|
|
|
@@ -557,6 +702,171 @@ if (deleteResult.error) {
|
|
|
557
702
|
|
|
558
703
|
---
|
|
559
704
|
|
|
705
|
+
## High-Scale Enterprise Micro-ORM (v2.0.0)
|
|
706
|
+
|
|
707
|
+
With **v2.0.0**, `@areumtecnologia/mysql-db-handler` evolves from a single-table CRUD helper into a full-fledged enterprise Data Mapper and Micro-ORM designed for high-throughput, mission-critical systems.
|
|
708
|
+
|
|
709
|
+
### 1. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)
|
|
710
|
+
|
|
711
|
+
#### Fluent Joins with Automatic Identifier Sanitization
|
|
712
|
+
Chain `.join()`, `.leftJoin()`, `.rightJoin()`, or `.innerJoin()` directly on the query builder with support for table aliases:
|
|
713
|
+
|
|
714
|
+
```javascript
|
|
715
|
+
const pedidos = await pedidosHandler
|
|
716
|
+
.selectFields(['pedidos.id', 'pedidos.valor', { column: 'c.nome', as: 'cliente_nome' }])
|
|
717
|
+
.leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
|
|
718
|
+
.where('pedidos.status', 'PAGO')
|
|
719
|
+
.get();
|
|
720
|
+
```
|
|
721
|
+
|
|
722
|
+
#### Eager Loading (`.with()`)
|
|
723
|
+
Prevent the dreaded N+1 query problem without creating massive, memory-heavy Cartesian joins in MySQL. Child entities are loaded in a single batched `WHERE foreign_key IN (...)` query and hydrated directly onto parents in memory:
|
|
724
|
+
|
|
725
|
+
```javascript
|
|
726
|
+
const pedidosComItens = await pedidosHandler
|
|
727
|
+
.where('status', 'PAGO')
|
|
728
|
+
.with('itens', {
|
|
729
|
+
type: 'hasMany',
|
|
730
|
+
handler: itensHandler,
|
|
731
|
+
foreignKey: 'pedido_id',
|
|
732
|
+
localKey: 'id'
|
|
733
|
+
})
|
|
734
|
+
.with('cliente', DatabaseHandler.belongsTo(clientesHandler, 'cliente_id', 'id'))
|
|
735
|
+
.get();
|
|
736
|
+
|
|
737
|
+
// pedidosComItens[0].itens -> Array de itens do pedido 1
|
|
738
|
+
// pedidosComItens[0].cliente -> Objeto do cliente associado
|
|
739
|
+
```
|
|
740
|
+
|
|
741
|
+
---
|
|
742
|
+
|
|
743
|
+
### 2. Read/Write Splitting (Master + Read Replicas)
|
|
744
|
+
|
|
745
|
+
Scale read traffic horizontally across multiple cloud replicas (e.g. AWS Aurora, GCP Cloud SQL, Azure Database for MySQL) with automatic Round-Robin load balancing and strict transactional sticky sessions:
|
|
746
|
+
|
|
747
|
+
```javascript
|
|
748
|
+
const db = new DataBase({
|
|
749
|
+
host: 'primary-master.internal', // Pool de Escrita (Master)
|
|
750
|
+
user: 'app_user',
|
|
751
|
+
password: 'secret_password',
|
|
752
|
+
database: 'meu_banco',
|
|
753
|
+
replicas: [
|
|
754
|
+
{ host: 'read-replica-1.internal' },
|
|
755
|
+
{ host: 'read-replica-2.internal' }
|
|
756
|
+
]
|
|
757
|
+
});
|
|
758
|
+
|
|
759
|
+
// Queries simples de leitura são distribuídas via Round-Robin nas réplicas
|
|
760
|
+
const users = await db.query('SELECT * FROM users WHERE status = ?', ['active']);
|
|
761
|
+
|
|
762
|
+
// Operações de mutação (INSERT, UPDATE, DELETE) vão obrigatoriamente para o Master
|
|
763
|
+
await db.query('INSERT INTO users SET ?', [{ name: 'Novo Usuário' }], true);
|
|
764
|
+
|
|
765
|
+
// Dentro de transações, TODAS as leituras e escritas utilizam a conexão Master (evitando replication lag)
|
|
766
|
+
await db.transaction(async () => {
|
|
767
|
+
const user = await db.query('SELECT saldo FROM contas WHERE id = ?', [1]);
|
|
768
|
+
await db.query('UPDATE contas SET saldo = saldo - 50 WHERE id = ?', [1], true);
|
|
769
|
+
});
|
|
770
|
+
```
|
|
771
|
+
|
|
772
|
+
---
|
|
773
|
+
|
|
774
|
+
### 3. Keyset Pagination & Memory-Safe Streaming
|
|
775
|
+
|
|
776
|
+
#### Keyset / Cursor Pagination (`.cursorPaginate()`)
|
|
777
|
+
Traditional `OFFSET` pagination degrades significantly on large tables because MySQL must scan and discard all rows before the offset. Keyset pagination uses constant-time index seeks (`WHERE id > ? ORDER BY id ASC LIMIT ?`):
|
|
778
|
+
|
|
779
|
+
```javascript
|
|
780
|
+
// Primeira página
|
|
781
|
+
const page1 = await produtosHandler.cursorPaginate({ limit: 20 });
|
|
782
|
+
// page1: { data: [...], nextCursor: 20, prevCursor: 1, hasMore: true, limit: 20 }
|
|
783
|
+
|
|
784
|
+
// Próxima página (tempo constante de 1ms, mesmo após 500.000 registos)
|
|
785
|
+
const page2 = await produtosHandler.cursorPaginate({
|
|
786
|
+
limit: 20,
|
|
787
|
+
after: page1.nextCursor
|
|
788
|
+
});
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
#### Streaming & Async Iterator (`for await ... of`)
|
|
792
|
+
Export millions of rows to CSV or feed an ETL pipeline without triggering Node.js Heap Out of Memory errors:
|
|
793
|
+
|
|
794
|
+
```javascript
|
|
795
|
+
// Iteração sob demanda com consumo constante de memória (< 30 MB)
|
|
796
|
+
for await (const row of relatorioHandler.cursor({ batchSize: 1000 })) {
|
|
797
|
+
processRow(row);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// Node.js Readable Stream nativo para pipes HTTP ou arquivos
|
|
801
|
+
relatorioHandler.stream({ batchSize: 500 })
|
|
802
|
+
.pipe(csvTransformStream)
|
|
803
|
+
.pipe(res);
|
|
804
|
+
```
|
|
805
|
+
|
|
806
|
+
---
|
|
807
|
+
|
|
808
|
+
### 4. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks
|
|
809
|
+
|
|
810
|
+
```javascript
|
|
811
|
+
const clientesHandler = new DatabaseHandler(db, 'clientes', {
|
|
812
|
+
softDelete: 'deletado_em', // ou boolean true (padrão 'deletado_em')
|
|
813
|
+
timestamps: true // injeta criado_em e atualizado_em automaticamente
|
|
814
|
+
});
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
#### Soft Deletes
|
|
818
|
+
* `.delete(where)`: Automaticamente executa `UPDATE clientes SET deletado_em = NOW() WHERE ...`.
|
|
819
|
+
* Consultas padrão (`select`, `get`, `first`, `paginate`, `selectToDatatable`) injetam automaticamente `AND deletado_em IS NULL`.
|
|
820
|
+
* `.withTrashed()`: Desativa o filtro para retornar registos ativos e deletados.
|
|
821
|
+
* `.onlyTrashed()`: Retorna exclusivamente registos na lixeira (`deletado_em IS NOT NULL`).
|
|
822
|
+
* `.restore(where)`: Restaura registos setando `deletado_em = NULL`.
|
|
823
|
+
* `.forceDelete(where)`: Executa `DELETE FROM` físico no MySQL.
|
|
824
|
+
|
|
825
|
+
#### Lifecycle Hooks
|
|
826
|
+
Intercepte mutações antes ou depois de sua persistência:
|
|
827
|
+
|
|
828
|
+
```javascript
|
|
829
|
+
clientesHandler
|
|
830
|
+
.beforeInsert(async (data) => {
|
|
831
|
+
data.slug = slugify(data.nome);
|
|
832
|
+
})
|
|
833
|
+
.afterInsert(async (result, data) => {
|
|
834
|
+
await logAudit('CLIENT_CREATED', result.insertId);
|
|
835
|
+
})
|
|
836
|
+
.beforeUpdate(async (set, where) => {
|
|
837
|
+
validateBusinessRules(set);
|
|
838
|
+
})
|
|
839
|
+
.afterDelete(async (result, where) => {
|
|
840
|
+
await notifyService(where);
|
|
841
|
+
});
|
|
842
|
+
```
|
|
843
|
+
|
|
844
|
+
---
|
|
845
|
+
|
|
846
|
+
### 5. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking
|
|
847
|
+
|
|
848
|
+
```javascript
|
|
849
|
+
const usuariosHandler = new DatabaseHandler(db, 'usuarios', {
|
|
850
|
+
autoStripUnknown: true, // Remove propriedades desconhecidas do payload
|
|
851
|
+
hiddenFields: ['senha_hash', 'token_recuperacao'] // Oculta campos confidenciais das consultas
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
// Prevenção de Mass Assignment e ER_BAD_FIELD_ERROR vindo de requisições web:
|
|
855
|
+
await usuariosHandler.insert({
|
|
856
|
+
nome: 'Carlos',
|
|
857
|
+
email: 'carlos@empresa.com',
|
|
858
|
+
senha_hash: 'hash_seguro',
|
|
859
|
+
isAdminFake: true, // Ignorado silenciosamente pois não existe no schema
|
|
860
|
+
payload_sujo: 'qualquer_coisa' // Ignorado silenciosamente
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
// Consultas nunca retornam senha_hash ou token_recuperacao acidentalmente:
|
|
864
|
+
const usuario = await usuariosHandler.where('id', 1).first();
|
|
865
|
+
console.log(usuario.senha_hash); // undefined
|
|
866
|
+
```
|
|
867
|
+
|
|
868
|
+
---
|
|
869
|
+
|
|
560
870
|
## Contributing
|
|
561
871
|
|
|
562
872
|
Contributions are welcome! Please open an issue or submit a pull request.
|
package/idex.d.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Pool, PoolConnection, PoolOptions, ResultSetHeader, RowDataPacket } from 'mysql2/promise';
|
|
2
|
+
|
|
3
|
+
export type IsolationLevel = 'READ UNCOMMITTED' | 'READ COMMITTED' | 'REPEATABLE READ' | 'SERIALIZABLE';
|
|
4
|
+
|
|
5
|
+
export interface ExtendedDatabaseConfig extends PoolOptions {
|
|
6
|
+
throwOnError?: boolean;
|
|
7
|
+
usePreparedStatements?: boolean;
|
|
8
|
+
slowQueryThreshold?: number;
|
|
9
|
+
onSlowQuery?: (info: { sql: string; params: any; durationMs: number }) => void;
|
|
10
|
+
logger?: Pick<Console, 'log' | 'warn' | 'error' | 'debug'>;
|
|
11
|
+
maxRetries?: number;
|
|
12
|
+
retryDelayMs?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface TransactionOptions {
|
|
16
|
+
isolationLevel?: IsolationLevel;
|
|
17
|
+
retries?: number;
|
|
18
|
+
retryDelayMs?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface AutoTransactionOptions {
|
|
22
|
+
methods?: string[];
|
|
23
|
+
lazy?: boolean;
|
|
24
|
+
isolationLevel?: IsolationLevel;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CacheStoreAdapter {
|
|
28
|
+
get(key: string): any | Promise<any>;
|
|
29
|
+
set(key: string, val: any, ttl?: number): any | Promise<any>;
|
|
30
|
+
del?(keys: string | string[]): any | Promise<any>;
|
|
31
|
+
flushAll?(): any | Promise<any>;
|
|
32
|
+
close?(): any | Promise<any>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface CacheOptions {
|
|
36
|
+
stdTTL?: number;
|
|
37
|
+
checkperiod?: number;
|
|
38
|
+
store?: CacheStoreAdapter;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface PaginateOptions {
|
|
42
|
+
page?: number;
|
|
43
|
+
limit?: number;
|
|
44
|
+
where?: any;
|
|
45
|
+
fields?: Array<string | { column: string; as: string } | { raw: string }>;
|
|
46
|
+
orderBy?: string | string[];
|
|
47
|
+
groupBy?: string | string[];
|
|
48
|
+
having?: { sql: string; bindings?: any[] } | string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface PaginatedResult<T = any> {
|
|
52
|
+
data: T[];
|
|
53
|
+
total: number;
|
|
54
|
+
page: number;
|
|
55
|
+
limit: number;
|
|
56
|
+
totalPages: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class DataBase {
|
|
60
|
+
id: number;
|
|
61
|
+
config: ExtendedDatabaseConfig;
|
|
62
|
+
pool: Pool;
|
|
63
|
+
|
|
64
|
+
constructor(config?: ExtendedDatabaseConfig);
|
|
65
|
+
getPool(): Pool;
|
|
66
|
+
getConnection(): Promise<PoolConnection>;
|
|
67
|
+
getCurrentTransaction(): Record<string, any> | null;
|
|
68
|
+
hasActiveTransaction(): boolean;
|
|
69
|
+
onCommit(callback: () => any | Promise<any>): void;
|
|
70
|
+
transaction<T>(callback: (tx: any) => Promise<T>, options?: TransactionOptions): Promise<T>;
|
|
71
|
+
transactional<T extends (...args: any[]) => Promise<any>>(fn: T, options?: TransactionOptions): T;
|
|
72
|
+
autoTransaction(options?: AutoTransactionOptions): (req: any, res: any, next: any) => void;
|
|
73
|
+
query<T = any>(sql: string, params?: any, isWrite?: boolean, options?: { prepare?: boolean; table?: string; ttl?: number }): Promise<T>;
|
|
74
|
+
execute<T = any>(sql: string, params?: any[], isWrite?: boolean, options?: { table?: string }): Promise<T>;
|
|
75
|
+
getTableSchema(table: string): Promise<RowDataPacket[]>;
|
|
76
|
+
close(): Promise<void>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export class DataBaseCache extends DataBase {
|
|
80
|
+
constructor(config?: ExtendedDatabaseConfig, cacheOptions?: CacheOptions);
|
|
81
|
+
createPool(): Pool;
|
|
82
|
+
clearTableCache(table: string): Promise<void>;
|
|
83
|
+
clearCache(): Promise<void>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class DataBaseHandler<T = RowDataPacket> {
|
|
87
|
+
db: DataBase;
|
|
88
|
+
table: string;
|
|
89
|
+
debug: boolean;
|
|
90
|
+
expression: string;
|
|
91
|
+
onError: ((err: Error) => void) | null;
|
|
92
|
+
|
|
93
|
+
static raw(sql: string): { __isRawSql: true; sql: string };
|
|
94
|
+
|
|
95
|
+
constructor(database: DataBase, table: string, expression?: string);
|
|
96
|
+
withTransaction(txOrDb: any): DataBaseHandler<T>;
|
|
97
|
+
getSchema(): Promise<RowDataPacket[]>;
|
|
98
|
+
executeQuery(sql: string, params?: any, isWrite?: boolean, options?: Record<string, any>): Promise<any>;
|
|
99
|
+
|
|
100
|
+
// Fluent Query Builder
|
|
101
|
+
selectFields(fields: string | string[] | Array<string | { column: string; as: string } | { raw: string }>): DataBaseHandler<T>;
|
|
102
|
+
where(columnOrObject: string | Record<string, any> | any[], operatorOrValue?: any, value?: any): DataBaseHandler<T>;
|
|
103
|
+
orWhere(columnOrObject: string | Record<string, any>, operatorOrValue?: any, value?: any): DataBaseHandler<T>;
|
|
104
|
+
groupBy(cols: string | string[]): DataBaseHandler<T>;
|
|
105
|
+
having(sql: string, bindings?: any[]): DataBaseHandler<T>;
|
|
106
|
+
orderBy(column: string, dir?: 'ASC' | 'DESC'): DataBaseHandler<T>;
|
|
107
|
+
limit(count: number): DataBaseHandler<T>;
|
|
108
|
+
offset(count: number): DataBaseHandler<T>;
|
|
109
|
+
get(): Promise<T[]>;
|
|
110
|
+
first(): Promise<T | null>;
|
|
111
|
+
count(column?: string): Promise<number>;
|
|
112
|
+
|
|
113
|
+
// Core Operations
|
|
114
|
+
paginate(options?: PaginateOptions): Promise<PaginatedResult<T>>;
|
|
115
|
+
selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[]): Promise<{
|
|
116
|
+
draw: number;
|
|
117
|
+
recordsTotal: number;
|
|
118
|
+
recordsFiltered: number;
|
|
119
|
+
data: T[];
|
|
120
|
+
error?: string;
|
|
121
|
+
}>;
|
|
122
|
+
selectBy(params?: Record<string, any>): Promise<T[]>;
|
|
123
|
+
select(params?: any[], clauses?: {
|
|
124
|
+
FIELDS?: any[];
|
|
125
|
+
GROUPBY?: string | string[];
|
|
126
|
+
HAVING?: string | { sql: string; bindings?: any[] };
|
|
127
|
+
ORDERBY?: string | string[];
|
|
128
|
+
DESC?: boolean;
|
|
129
|
+
LIMIT?: number;
|
|
130
|
+
OFFSET?: number;
|
|
131
|
+
}): Promise<T[]>;
|
|
132
|
+
insert(params: Record<string, any>): Promise<ResultSetHeader>;
|
|
133
|
+
insertMany(rowsArray: Array<Record<string, any>>): Promise<ResultSetHeader>;
|
|
134
|
+
upsert(data: Record<string, any>, updateColumns?: string[]): Promise<ResultSetHeader>;
|
|
135
|
+
update(params: { set: Record<string, any>; where: any }, options?: { useRegex?: boolean }): Promise<ResultSetHeader>;
|
|
136
|
+
delete(conditions: Record<string, any> | any[]): Promise<ResultSetHeader | undefined>;
|
|
137
|
+
}
|