@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.
- package/README.md +291 -10
- 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
|
@@ -325,16 +325,70 @@ console.log('Deleted rows:', result.affectedRows);
|
|
|
325
325
|
|
|
326
326
|
## jQuery DataTables Server-Side Support (`selectToDatatable`)
|
|
327
327
|
|
|
328
|
-
The `selectToDatatable` method provides seamless, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It automatically
|
|
328
|
+
The `selectToDatatable` method provides seamless, enterprise-grade, high-performance integration with [jQuery DataTables](https://datatables.net/) server-side processing. It eliminates manual SQL pagination boilerplate, automatically handling pagination, search (global and column-specific), multi-column ordering, regex filters, dual-count latency optimizations, backend security constraints, Soft Deletes, and sensitive field masking.
|
|
329
|
+
|
|
330
|
+
---
|
|
331
|
+
|
|
332
|
+
### Step-by-Step Execution Lifecycle (Under the Hood)
|
|
333
|
+
|
|
334
|
+
Whenever `selectToDatatable(rawDtQuery, strictCondition)` is invoked, it executes the following optimized workflow:
|
|
335
|
+
|
|
336
|
+
```
|
|
337
|
+
[Incoming Request] (req.body or req.query)
|
|
338
|
+
│
|
|
339
|
+
▼
|
|
340
|
+
1. Hydration & Security Filter
|
|
341
|
+
• Flattens or parses bracketed keys (e.g. columns[0][data] -> { columns: [{ data: ... }] })
|
|
342
|
+
• Prototype Pollution Guard: Sanitizes __proto__, constructor, and prototype (CWE-1321)
|
|
343
|
+
• Sanitizes integers (draw, start, length) preventing NaN injections
|
|
344
|
+
│
|
|
345
|
+
▼
|
|
346
|
+
2. Backend Security & Tenant Scoping (strictCondition)
|
|
347
|
+
• Injects non-bypassable backend filters (tenant_id, account_id, branch, etc.)
|
|
348
|
+
• [v2.0.0] Injects Soft Delete filter (deletado_em IS NULL) automatically unless withTrashed() is active
|
|
349
|
+
│
|
|
350
|
+
▼
|
|
351
|
+
3. Search Clause Generation
|
|
352
|
+
• Global Search (search.value): Checks all columns where searchable == true -> (col1 LIKE ? OR col2 LIKE ?)
|
|
353
|
+
• Column-Specific Search (columns[i].search.value): Checks individual columns -> AND colN LIKE ?
|
|
354
|
+
• Regex Toggle: If regex == true, switches operator from LIKE %term% to REGEXP term
|
|
355
|
+
• Parameterized bindings: All terms use prepared statement placeholders (?) to block SQL injection
|
|
356
|
+
│
|
|
357
|
+
▼
|
|
358
|
+
4. Dual-COUNT Latency Optimization
|
|
359
|
+
• No Active Search Filter: Only 1 COUNT(*) query is executed. recordsFiltered is instantly set to recordsTotal (up to 50% database I/O reduction).
|
|
360
|
+
• Active Search Filter: Executes total COUNT(*) and filtered COUNT(*) concurrently via Promise.all().
|
|
361
|
+
│
|
|
362
|
+
▼
|
|
363
|
+
5. Short-Circuit Check
|
|
364
|
+
• If recordsFiltered === 0: The data SELECT query is skipped entirely. Returns data: [] immediately, avoiding expensive filesort and buffer allocations.
|
|
365
|
+
│
|
|
366
|
+
▼
|
|
367
|
+
6. Multi-Column Ordering & Keyset Limitation
|
|
368
|
+
• Parses all order directives (order[0], order[1], etc.)
|
|
369
|
+
• Maps column index to sanitized column name (e.g. `col1` ASC, `col2` DESC)
|
|
370
|
+
• Generates LIMIT start, length safely
|
|
371
|
+
│
|
|
372
|
+
▼
|
|
373
|
+
7. Data Retrieval & Sensitive Field Masking
|
|
374
|
+
• Executes SELECT <columns> FROM <table> [JOINS] [WHERE] [ORDER BY] [LIMIT]
|
|
375
|
+
• [v2.0.0] Strips any fields declared in hiddenFields (e.g. senha_hash, token) before output
|
|
376
|
+
│
|
|
377
|
+
▼
|
|
378
|
+
[Standard JSON Response to DataTables]
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
---
|
|
329
382
|
|
|
330
383
|
### Key Features & Performance Optimizations
|
|
331
384
|
|
|
332
|
-
* **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state
|
|
385
|
+
* **Smart Single `COUNT(*)`:** When no client-side search filter is active (the default state during initial page load, sorting, and standard pagination), `recordsFiltered` is automatically set to `recordsTotal`. The method skips the redundant second `COUNT(*)` query, **reducing database count latency and I/O by up to 50%**.
|
|
333
386
|
* **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
387
|
* **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
388
|
* **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
389
|
* **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
390
|
* **Prototype Pollution Protection (CWE-1321):** Deeply sanitizes incoming request keys, blocking injections targeting `__proto__`, `constructor`, or `prototype`.
|
|
391
|
+
* **[v2.0.0] Soft Delete & Hidden Fields Aware:** Automatically excludes soft-deleted records (`deletado_em IS NULL`) and strips sensitive columns (`hiddenFields`) from the returned JSON.
|
|
338
392
|
|
|
339
393
|
---
|
|
340
394
|
|
|
@@ -344,10 +398,24 @@ The `selectToDatatable` method provides seamless, high-performance integration w
|
|
|
344
398
|
await handler.selectToDatatable(rawDtQuery, strictCondition = [])
|
|
345
399
|
```
|
|
346
400
|
|
|
347
|
-
|
|
401
|
+
#### Parameters
|
|
402
|
+
|
|
403
|
+
| Parameter | Type | Required | Description |
|
|
404
|
+
| :--- | :--- | :---: | :--- |
|
|
405
|
+
| `rawDtQuery` | `Object` | **Yes** | The request payload sent by jQuery DataTables (`req.body` in POST or `req.query` in GET). Supports both bracket-flattened keys and nested JSON. |
|
|
406
|
+
| `strictCondition` | `Array` \| `Object` | No | Backend constraints that the client cannot view or modify (e.g. multi-tenant isolation, user scoping, active-only filters). |
|
|
407
|
+
|
|
408
|
+
#### DataTables Payload Schema (`rawDtQuery`)
|
|
409
|
+
|
|
410
|
+
| Field | Type | Description |
|
|
348
411
|
| :--- | :--- | :--- |
|
|
349
|
-
| `
|
|
350
|
-
| `
|
|
412
|
+
| `draw` | `number` \| `string` | Draw counter echoed back to the client to ensure response synchronization. |
|
|
413
|
+
| `start` | `number` \| `string` | Zero-based paging first record indicator (`OFFSET`). Defaults to `0`. |
|
|
414
|
+
| `length` | `number` \| `string` | Number of records to return (`LIMIT`). |
|
|
415
|
+
| `search.value` | `string` | Global search value applied across all columns with `searchable: true`. |
|
|
416
|
+
| `search.regex` | `boolean` \| `string` | If `true` or `'true'`, uses MySQL `REGEXP` instead of `LIKE %value%`. |
|
|
417
|
+
| `order` | `Array<Object>` | Array of order objects: `{ column: 0, dir: 'asc' \| 'desc' }`. |
|
|
418
|
+
| `columns` | `Array<Object>` | Array of column definitions: `{ data: 'col_name', searchable: true, orderable: true, search: { value: '', regex: false } }`. |
|
|
351
419
|
|
|
352
420
|
---
|
|
353
421
|
|
|
@@ -372,7 +440,7 @@ app.post('/api/users/datatable', async (req, res) => {
|
|
|
372
440
|
|
|
373
441
|
### Enforcing Backend Security (`strictCondition`)
|
|
374
442
|
|
|
375
|
-
Never rely on the client to enforce data
|
|
443
|
+
Never rely on the client frontend to enforce data 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
444
|
|
|
377
445
|
```javascript
|
|
378
446
|
app.post('/api/orders/datatable', async (req, res) => {
|
|
@@ -392,9 +460,33 @@ app.post('/api/orders/datatable', async (req, res) => {
|
|
|
392
460
|
|
|
393
461
|
---
|
|
394
462
|
|
|
395
|
-
### Using JOINs
|
|
463
|
+
### Using JOINs with DataTables
|
|
396
464
|
|
|
397
|
-
|
|
465
|
+
#### Option A: Modern Fluent Query Builder Joins (Recommended in v2.0.0)
|
|
466
|
+
Chain `.selectFields()` and `.leftJoin()` / `.join()` directly with `.selectToDatatable()`:
|
|
467
|
+
|
|
468
|
+
```javascript
|
|
469
|
+
app.post('/api/pedidos/datatable', async (req, res) => {
|
|
470
|
+
const result = await pedidosHandler
|
|
471
|
+
.selectFields([
|
|
472
|
+
'pedidos.id',
|
|
473
|
+
'pedidos.valor',
|
|
474
|
+
'pedidos.criado_em',
|
|
475
|
+
{ column: 'c.nome', as: 'cliente_nome' },
|
|
476
|
+
{ column: 'v.nome', as: 'vendedor_nome' }
|
|
477
|
+
])
|
|
478
|
+
.leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
|
|
479
|
+
.leftJoin('vendedores v', 'pedidos.vendedor_id', '=', 'v.id')
|
|
480
|
+
.selectToDatatable(req.body, [
|
|
481
|
+
{ 'pedidos.empresa_id': req.user.empresaId }
|
|
482
|
+
]);
|
|
483
|
+
|
|
484
|
+
res.json(result);
|
|
485
|
+
});
|
|
486
|
+
```
|
|
487
|
+
|
|
488
|
+
#### Option B: Legacy Expression Parameter
|
|
489
|
+
You can also initialize the handler with a SQL expression containing the JOINs and selected columns:
|
|
398
490
|
|
|
399
491
|
```javascript
|
|
400
492
|
// Table: 'sales s'
|
|
@@ -408,8 +500,7 @@ const salesHandler = new DataBaseHandler(
|
|
|
408
500
|
);
|
|
409
501
|
|
|
410
502
|
app.post('/api/sales/datatable', async (req, res) => {
|
|
411
|
-
// DataTables columns can
|
|
412
|
-
// e.g. columns: [{ data: 's.id' }, { data: 'c.name' }, { data: 's.amount' }]
|
|
503
|
+
// DataTables columns can search and sort by qualified identifiers (e.g. 'c.name')
|
|
413
504
|
const result = await salesHandler.selectToDatatable(req.body, [
|
|
414
505
|
{ 's.deleted_at': null, operator: 'IS' }
|
|
415
506
|
]);
|
|
@@ -419,6 +510,31 @@ app.post('/api/sales/datatable', async (req, res) => {
|
|
|
419
510
|
|
|
420
511
|
---
|
|
421
512
|
|
|
513
|
+
### Soft Deletes & Sensitive Fields in DataTables (v2.0.0)
|
|
514
|
+
|
|
515
|
+
When configuring business rules on the handler, `selectToDatatable` automatically complies without requiring manual filters:
|
|
516
|
+
|
|
517
|
+
```javascript
|
|
518
|
+
const clientesHandler = new DatabaseHandler(db, 'clientes', {
|
|
519
|
+
softDelete: 'deletado_em', // Injeta 'AND deletado_em IS NULL' automaticamente
|
|
520
|
+
hiddenFields: ['senha_hash', 'token_recuperacao'] // Remove do retorno mesmo se 'SELECT *' for usado
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
// A consulta abaixo já ignora excluídos e nunca expõe senha_hash
|
|
524
|
+
app.post('/api/clientes/datatable', async (req, res) => {
|
|
525
|
+
const result = await clientesHandler.selectToDatatable(req.body);
|
|
526
|
+
res.json(result);
|
|
527
|
+
});
|
|
528
|
+
|
|
529
|
+
// Para consultar registos da lixeira (soft-deleted):
|
|
530
|
+
app.post('/api/clientes/trash/datatable', async (req, res) => {
|
|
531
|
+
const result = await clientesHandler.onlyTrashed().selectToDatatable(req.body);
|
|
532
|
+
res.json(result);
|
|
533
|
+
});
|
|
534
|
+
```
|
|
535
|
+
|
|
536
|
+
---
|
|
537
|
+
|
|
422
538
|
### Frontend jQuery DataTables Setup
|
|
423
539
|
|
|
424
540
|
Configure your frontend DataTables instance with `serverSide: true`:
|
|
@@ -702,6 +818,171 @@ if (deleteResult.error) {
|
|
|
702
818
|
|
|
703
819
|
---
|
|
704
820
|
|
|
821
|
+
## High-Scale Enterprise Micro-ORM (v2.0.0)
|
|
822
|
+
|
|
823
|
+
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.
|
|
824
|
+
|
|
825
|
+
### 1. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)
|
|
826
|
+
|
|
827
|
+
#### Fluent Joins with Automatic Identifier Sanitization
|
|
828
|
+
Chain `.join()`, `.leftJoin()`, `.rightJoin()`, or `.innerJoin()` directly on the query builder with support for table aliases:
|
|
829
|
+
|
|
830
|
+
```javascript
|
|
831
|
+
const pedidos = await pedidosHandler
|
|
832
|
+
.selectFields(['pedidos.id', 'pedidos.valor', { column: 'c.nome', as: 'cliente_nome' }])
|
|
833
|
+
.leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
|
|
834
|
+
.where('pedidos.status', 'PAGO')
|
|
835
|
+
.get();
|
|
836
|
+
```
|
|
837
|
+
|
|
838
|
+
#### Eager Loading (`.with()`)
|
|
839
|
+
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:
|
|
840
|
+
|
|
841
|
+
```javascript
|
|
842
|
+
const pedidosComItens = await pedidosHandler
|
|
843
|
+
.where('status', 'PAGO')
|
|
844
|
+
.with('itens', {
|
|
845
|
+
type: 'hasMany',
|
|
846
|
+
handler: itensHandler,
|
|
847
|
+
foreignKey: 'pedido_id',
|
|
848
|
+
localKey: 'id'
|
|
849
|
+
})
|
|
850
|
+
.with('cliente', DatabaseHandler.belongsTo(clientesHandler, 'cliente_id', 'id'))
|
|
851
|
+
.get();
|
|
852
|
+
|
|
853
|
+
// pedidosComItens[0].itens -> Array de itens do pedido 1
|
|
854
|
+
// pedidosComItens[0].cliente -> Objeto do cliente associado
|
|
855
|
+
```
|
|
856
|
+
|
|
857
|
+
---
|
|
858
|
+
|
|
859
|
+
### 2. Read/Write Splitting (Master + Read Replicas)
|
|
860
|
+
|
|
861
|
+
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:
|
|
862
|
+
|
|
863
|
+
```javascript
|
|
864
|
+
const db = new DataBase({
|
|
865
|
+
host: 'primary-master.internal', // Pool de Escrita (Master)
|
|
866
|
+
user: 'app_user',
|
|
867
|
+
password: 'secret_password',
|
|
868
|
+
database: 'meu_banco',
|
|
869
|
+
replicas: [
|
|
870
|
+
{ host: 'read-replica-1.internal' },
|
|
871
|
+
{ host: 'read-replica-2.internal' }
|
|
872
|
+
]
|
|
873
|
+
});
|
|
874
|
+
|
|
875
|
+
// Queries simples de leitura são distribuídas via Round-Robin nas réplicas
|
|
876
|
+
const users = await db.query('SELECT * FROM users WHERE status = ?', ['active']);
|
|
877
|
+
|
|
878
|
+
// Operações de mutação (INSERT, UPDATE, DELETE) vão obrigatoriamente para o Master
|
|
879
|
+
await db.query('INSERT INTO users SET ?', [{ name: 'Novo Usuário' }], true);
|
|
880
|
+
|
|
881
|
+
// Dentro de transações, TODAS as leituras e escritas utilizam a conexão Master (evitando replication lag)
|
|
882
|
+
await db.transaction(async () => {
|
|
883
|
+
const user = await db.query('SELECT saldo FROM contas WHERE id = ?', [1]);
|
|
884
|
+
await db.query('UPDATE contas SET saldo = saldo - 50 WHERE id = ?', [1], true);
|
|
885
|
+
});
|
|
886
|
+
```
|
|
887
|
+
|
|
888
|
+
---
|
|
889
|
+
|
|
890
|
+
### 3. Keyset Pagination & Memory-Safe Streaming
|
|
891
|
+
|
|
892
|
+
#### Keyset / Cursor Pagination (`.cursorPaginate()`)
|
|
893
|
+
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 ?`):
|
|
894
|
+
|
|
895
|
+
```javascript
|
|
896
|
+
// Primeira página
|
|
897
|
+
const page1 = await produtosHandler.cursorPaginate({ limit: 20 });
|
|
898
|
+
// page1: { data: [...], nextCursor: 20, prevCursor: 1, hasMore: true, limit: 20 }
|
|
899
|
+
|
|
900
|
+
// Próxima página (tempo constante de 1ms, mesmo após 500.000 registos)
|
|
901
|
+
const page2 = await produtosHandler.cursorPaginate({
|
|
902
|
+
limit: 20,
|
|
903
|
+
after: page1.nextCursor
|
|
904
|
+
});
|
|
905
|
+
```
|
|
906
|
+
|
|
907
|
+
#### Streaming & Async Iterator (`for await ... of`)
|
|
908
|
+
Export millions of rows to CSV or feed an ETL pipeline without triggering Node.js Heap Out of Memory errors:
|
|
909
|
+
|
|
910
|
+
```javascript
|
|
911
|
+
// Iteração sob demanda com consumo constante de memória (< 30 MB)
|
|
912
|
+
for await (const row of relatorioHandler.cursor({ batchSize: 1000 })) {
|
|
913
|
+
processRow(row);
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
// Node.js Readable Stream nativo para pipes HTTP ou arquivos
|
|
917
|
+
relatorioHandler.stream({ batchSize: 500 })
|
|
918
|
+
.pipe(csvTransformStream)
|
|
919
|
+
.pipe(res);
|
|
920
|
+
```
|
|
921
|
+
|
|
922
|
+
---
|
|
923
|
+
|
|
924
|
+
### 4. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks
|
|
925
|
+
|
|
926
|
+
```javascript
|
|
927
|
+
const clientesHandler = new DatabaseHandler(db, 'clientes', {
|
|
928
|
+
softDelete: 'deletado_em', // ou boolean true (padrão 'deletado_em')
|
|
929
|
+
timestamps: true // injeta criado_em e atualizado_em automaticamente
|
|
930
|
+
});
|
|
931
|
+
```
|
|
932
|
+
|
|
933
|
+
#### Soft Deletes
|
|
934
|
+
* `.delete(where)`: Automaticamente executa `UPDATE clientes SET deletado_em = NOW() WHERE ...`.
|
|
935
|
+
* Consultas padrão (`select`, `get`, `first`, `paginate`, `selectToDatatable`) injetam automaticamente `AND deletado_em IS NULL`.
|
|
936
|
+
* `.withTrashed()`: Desativa o filtro para retornar registos ativos e deletados.
|
|
937
|
+
* `.onlyTrashed()`: Retorna exclusivamente registos na lixeira (`deletado_em IS NOT NULL`).
|
|
938
|
+
* `.restore(where)`: Restaura registos setando `deletado_em = NULL`.
|
|
939
|
+
* `.forceDelete(where)`: Executa `DELETE FROM` físico no MySQL.
|
|
940
|
+
|
|
941
|
+
#### Lifecycle Hooks
|
|
942
|
+
Intercepte mutações antes ou depois de sua persistência:
|
|
943
|
+
|
|
944
|
+
```javascript
|
|
945
|
+
clientesHandler
|
|
946
|
+
.beforeInsert(async (data) => {
|
|
947
|
+
data.slug = slugify(data.nome);
|
|
948
|
+
})
|
|
949
|
+
.afterInsert(async (result, data) => {
|
|
950
|
+
await logAudit('CLIENT_CREATED', result.insertId);
|
|
951
|
+
})
|
|
952
|
+
.beforeUpdate(async (set, where) => {
|
|
953
|
+
validateBusinessRules(set);
|
|
954
|
+
})
|
|
955
|
+
.afterDelete(async (result, where) => {
|
|
956
|
+
await notifyService(where);
|
|
957
|
+
});
|
|
958
|
+
```
|
|
959
|
+
|
|
960
|
+
---
|
|
961
|
+
|
|
962
|
+
### 5. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking
|
|
963
|
+
|
|
964
|
+
```javascript
|
|
965
|
+
const usuariosHandler = new DatabaseHandler(db, 'usuarios', {
|
|
966
|
+
autoStripUnknown: true, // Remove propriedades desconhecidas do payload
|
|
967
|
+
hiddenFields: ['senha_hash', 'token_recuperacao'] // Oculta campos confidenciais das consultas
|
|
968
|
+
});
|
|
969
|
+
|
|
970
|
+
// Prevenção de Mass Assignment e ER_BAD_FIELD_ERROR vindo de requisições web:
|
|
971
|
+
await usuariosHandler.insert({
|
|
972
|
+
nome: 'Carlos',
|
|
973
|
+
email: 'carlos@empresa.com',
|
|
974
|
+
senha_hash: 'hash_seguro',
|
|
975
|
+
isAdminFake: true, // Ignorado silenciosamente pois não existe no schema
|
|
976
|
+
payload_sujo: 'qualquer_coisa' // Ignorado silenciosamente
|
|
977
|
+
});
|
|
978
|
+
|
|
979
|
+
// Consultas nunca retornam senha_hash ou token_recuperacao acidentalmente:
|
|
980
|
+
const usuario = await usuariosHandler.where('id', 1).first();
|
|
981
|
+
console.log(usuario.senha_hash); // undefined
|
|
982
|
+
```
|
|
983
|
+
|
|
984
|
+
---
|
|
985
|
+
|
|
705
986
|
## Contributing
|
|
706
987
|
|
|
707
988
|
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
|
+
}
|