@areumtecnologia/mysql-db-handler 2.0.2 → 2.0.3
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 +212 -12
- package/index.d.ts +9 -1
- package/index.js +5 -1
- package/lib/databaseHandler.js +90 -23
- package/package.json +1 -1
- package/idex.d.ts +0 -137
package/README.md
CHANGED
|
@@ -23,8 +23,11 @@ A powerful, robust, and production-ready MySQL wrapper for Node.js. It features
|
|
|
23
23
|
* [Combining Multiple Conditions (AND / OR)](#combining-multiple-conditions-and--or)
|
|
24
24
|
* [CRUD Operations](#crud-operations)
|
|
25
25
|
* [Inserting Records (`insert`)](#inserting-records-insert)
|
|
26
|
+
* [Bulk Insert (`insertMany`)](#bulk-insert-insertmany)
|
|
27
|
+
* [Upsert with Smart Timestamps (`upsert`)](#upsert-with-smart-timestamps-upsert)
|
|
26
28
|
* [Updating Records (`update`)](#updating-records-update)
|
|
27
29
|
* [Deleting Records (`delete`)](#deleting-records-delete)
|
|
30
|
+
* [Fluent Mutations (`.where().update()` / `.delete()`)](#fluent-mutations-whereupdate--wheredelete)
|
|
28
31
|
* [jQuery DataTables Server-Side Support (`selectToDatatable`)](#jquery-datatables-server-side-support-selecttodatatable)
|
|
29
32
|
* [Key Features & Performance](#key-features--performance-optimizations)
|
|
30
33
|
* [Method Signature](#method-signature)
|
|
@@ -42,6 +45,13 @@ A powerful, robust, and production-ready MySQL wrapper for Node.js. It features
|
|
|
42
45
|
* [6. Nested Transactions & Savepoints](#6-nested-transactions--savepoints)
|
|
43
46
|
* [Database Singleton Pattern](#database-singleton-pattern)
|
|
44
47
|
* [Error Handling Strategy](#error-handling-strategy)
|
|
48
|
+
* [High-Scale Enterprise Micro-ORM (v2.0.0)](#high-scale-enterprise-micro-orm-v200)
|
|
49
|
+
* [1. Fluent Query Builder & Aggregations (`.first`, `.count`, `.paginate`, `raw`)](#1-fluent-query-builder--aggregations-first-count-paginate-raw)
|
|
50
|
+
* [2. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)](#2-fluent-joins--eager-loading-eliminating-the-n1-problem)
|
|
51
|
+
* [3. Read/Write Splitting (Master + Read Replicas)](#3-readwrite-splitting-master--read-replicas)
|
|
52
|
+
* [4. Keyset Pagination & Memory-Safe Streaming](#4-keyset-pagination--memory-safe-streaming)
|
|
53
|
+
* [5. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks](#5-native-business-rules-soft-deletes-timestamps--lifecycle-hooks)
|
|
54
|
+
* [6. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking](#6-runtime-schema-validation-auto-strip--sensitive-field-masking)
|
|
45
55
|
* [Contributing](#contributing)
|
|
46
56
|
* [License](#license)
|
|
47
57
|
|
|
@@ -87,7 +97,16 @@ Located in `lib/database.js`. Manages standard pooled connections, schema discov
|
|
|
87
97
|
Located in `lib/database-cache.js`. Overrides the standard `DataBase` implementation to provide in-memory query and table schema caching. It is ideal for read-heavy environments.
|
|
88
98
|
|
|
89
99
|
### 3. `DataBaseHandler` (CRUD Abstraction)
|
|
90
|
-
Located in `lib/
|
|
100
|
+
Located in `lib/databaseHandler.js`. Bind this class to a specific table to perform database actions through utility methods (`select`, `selectBy`, `insert`, `update`, `delete`, `selectToDatatable`).
|
|
101
|
+
|
|
102
|
+
> [!NOTE]
|
|
103
|
+
> **Convenção de Nomenclatura & Aliases:**
|
|
104
|
+
> O pacote exporta tanto os identificadores em PascalCase com `B` maiúsculo (`DataBase`, `DataBaseHandler`, `DataBaseCache`) quanto aliases com `b` minúsculo (`Database`, `DatabaseHandler`, `DatabaseCache`), permitindo compatibilidade total com qualquer estilo de importação:
|
|
105
|
+
> ```javascript
|
|
106
|
+
> const { DataBase, DataBaseHandler } = require('@areumtecnologia/mysql-db-handler');
|
|
107
|
+
> // ou:
|
|
108
|
+
> const { Database, DatabaseHandler } = require('@areumtecnologia/mysql-db-handler');
|
|
109
|
+
> ```
|
|
91
110
|
|
|
92
111
|
---
|
|
93
112
|
|
|
@@ -241,6 +260,42 @@ const result = await usersHandler.insert({
|
|
|
241
260
|
console.log('Inserted ID:', result.insertId);
|
|
242
261
|
```
|
|
243
262
|
|
|
263
|
+
### Bulk Insert (`insertMany`)
|
|
264
|
+
|
|
265
|
+
Insere múltiplos registros em uma única instrução SQL (`INSERT INTO table (...) VALUES ?`), oferecendo máxima performance para cargas em lote. O método aplica sanitização de schema (`autoStripUnknown`), preenche timestamps automáticos (`criado_em` / `atualizado_em`) e dispara os hooks de ciclo de vida (`beforeInsert` / `afterInsert`) para cada registro:
|
|
266
|
+
|
|
267
|
+
```javascript
|
|
268
|
+
const novosUsuarios = [
|
|
269
|
+
{ name: 'Alice Silva', email: 'alice@empresa.com', role: 'developer' },
|
|
270
|
+
{ name: 'Bob Souza', email: 'bob@empresa.com', role: 'designer' },
|
|
271
|
+
{ name: 'Carlos Lima', email: 'carlos@empresa.com', role: 'manager' }
|
|
272
|
+
];
|
|
273
|
+
|
|
274
|
+
const result = await usersHandler.insertMany(novosUsuarios);
|
|
275
|
+
console.log('Linhas inseridas:', result.affectedRows);
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
### Upsert with Smart Timestamps (`upsert`)
|
|
279
|
+
|
|
280
|
+
Executa uma operação atômica de inserção ou atualização (`INSERT INTO ... ON DUPLICATE KEY UPDATE`). Se o registro for novo, ele é inserido com os timestamps de criação e atualização. Se a chave primária ou índice único já existir, apenas os campos selecionados são atualizados, **preservando intacta a data de criação original (`criado_em` / `createdAt`)**:
|
|
281
|
+
|
|
282
|
+
```javascript
|
|
283
|
+
// Exemplo: Insere o produto ou atualiza apenas preco e estoque se codigo_barras já existir
|
|
284
|
+
const result = await produtosHandler.upsert({
|
|
285
|
+
codigo_barras: '7891234567890',
|
|
286
|
+
nome: 'Mouse sem Fio',
|
|
287
|
+
preco: 149.90,
|
|
288
|
+
estoque: 80
|
|
289
|
+
}, ['preco', 'estoque']); // 2º argumento opcional: colunas a atualizar no conflito
|
|
290
|
+
|
|
291
|
+
// Se omitir o 2º argumento, atualiza todos os campos fornecidos exceto criado_em:
|
|
292
|
+
await produtosHandler.upsert({
|
|
293
|
+
codigo_barras: '7891234567890',
|
|
294
|
+
nome: 'Mouse sem Fio Pro',
|
|
295
|
+
preco: 179.90
|
|
296
|
+
});
|
|
297
|
+
```
|
|
298
|
+
|
|
244
299
|
### Updating Records (`update`)
|
|
245
300
|
|
|
246
301
|
Performs selective updates by specifying both a `set` payload and a `where` filter. The `where` filter supports both standard flat objects (where conditions are implicitly joined by `AND` using `=` or `REGEXP`) and complex array configurations (with operators, `AND`, and `OR`), sharing the same advanced querying capabilities as the `select` method.
|
|
@@ -321,6 +376,35 @@ const result = await usersHandler.delete({
|
|
|
321
376
|
console.log('Deleted rows:', result.affectedRows);
|
|
322
377
|
```
|
|
323
378
|
|
|
379
|
+
### Fluent Mutations (`.where().update()` / `.delete()`)
|
|
380
|
+
|
|
381
|
+
Você pode encadear as mutações de escrita diretamente a partir do Query Builder Fluente, garantindo expressividade e legibilidade de alto nível:
|
|
382
|
+
|
|
383
|
+
```javascript
|
|
384
|
+
// Soft Delete (ou hard delete) diretamente com filtros encadeados:
|
|
385
|
+
await pedidosHandler
|
|
386
|
+
.where('status', 'CANCELADO')
|
|
387
|
+
.where('criado_em', '<', dataLimite)
|
|
388
|
+
.delete();
|
|
389
|
+
|
|
390
|
+
// Update com filtros fluentes encadeados:
|
|
391
|
+
await clientesHandler
|
|
392
|
+
.where('id', 10)
|
|
393
|
+
.update({
|
|
394
|
+
set: { status: 'ATIVO', tentativas_login: 0 }
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
// Restauração de itens da lixeira via Query Builder:
|
|
398
|
+
await produtosHandler
|
|
399
|
+
.where('categoria_id', 5)
|
|
400
|
+
.restore();
|
|
401
|
+
|
|
402
|
+
// Exclusão física definitiva (Hard Delete) via Query Builder:
|
|
403
|
+
await logsHandler
|
|
404
|
+
.where('criado_em', '<', dataExpiracao)
|
|
405
|
+
.forceDelete();
|
|
406
|
+
```
|
|
407
|
+
|
|
324
408
|
---
|
|
325
409
|
|
|
326
410
|
## jQuery DataTables Server-Side Support (`selectToDatatable`)
|
|
@@ -458,6 +542,18 @@ app.post('/api/orders/datatable', async (req, res) => {
|
|
|
458
542
|
});
|
|
459
543
|
```
|
|
460
544
|
|
|
545
|
+
> [!IMPORTANT]
|
|
546
|
+
> **Regra Obrigatória para Múltiplas Condições em `strictCondition`:**
|
|
547
|
+
> Sempre forneça `strictCondition` no formato de **Array de Objetos** com conectivos explícitos (`'AND'` / `'OR'`). Se for passado um objeto único contendo múltiplas propriedades (como `{ tenant_id: 1, status: 'active' }`), o parser interno processará **apenas a primeira chave** e descartará as demais silenciosamente:
|
|
548
|
+
> ```javascript
|
|
549
|
+
> // Correto:
|
|
550
|
+
> strictCondition: [
|
|
551
|
+
> { 'pedidos.empresa_id': req.user.empresaId },
|
|
552
|
+
> 'AND',
|
|
553
|
+
> { 'pedidos.ativo': 1 }
|
|
554
|
+
> ]
|
|
555
|
+
> ```
|
|
556
|
+
|
|
461
557
|
---
|
|
462
558
|
|
|
463
559
|
### Using JOINs with DataTables
|
|
@@ -515,7 +611,7 @@ app.post('/api/sales/datatable', async (req, res) => {
|
|
|
515
611
|
When configuring business rules on the handler, `selectToDatatable` automatically complies without requiring manual filters:
|
|
516
612
|
|
|
517
613
|
```javascript
|
|
518
|
-
const clientesHandler = new
|
|
614
|
+
const clientesHandler = new DataBaseHandler(db, 'clientes', {
|
|
519
615
|
softDelete: 'deletado_em', // Injeta 'AND deletado_em IS NULL' automaticamente
|
|
520
616
|
hiddenFields: ['senha_hash', 'token_recuperacao'] // Remove do retorno mesmo se 'SELECT *' for usado
|
|
521
617
|
});
|
|
@@ -822,7 +918,77 @@ if (deleteResult.error) {
|
|
|
822
918
|
|
|
823
919
|
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
920
|
|
|
825
|
-
### 1. Fluent
|
|
921
|
+
### 1. Fluent Query Builder & Aggregations (`.first`, `.count`, `.paginate`, `raw`)
|
|
922
|
+
|
|
923
|
+
O Query Builder Fluente oferece encadeamento imutável, tipagem limpa e sanitização de identificadores para construir consultas SQL expressivas sem strings manuais vulneráveis:
|
|
924
|
+
|
|
925
|
+
#### Obter um Único Registro (`.first()`)
|
|
926
|
+
Executa `LIMIT 1` e já desempacota o primeiro objeto ou retorna `null` caso nenhum registro atenda aos critérios:
|
|
927
|
+
```javascript
|
|
928
|
+
const usuario = await usuariosHandler
|
|
929
|
+
.where('email', 'admin@empresa.com')
|
|
930
|
+
.first();
|
|
931
|
+
|
|
932
|
+
if (!usuario) {
|
|
933
|
+
console.log('Usuário não encontrado');
|
|
934
|
+
}
|
|
935
|
+
```
|
|
936
|
+
|
|
937
|
+
#### Contagem Direta de Registros (`.count()`)
|
|
938
|
+
Retorna diretamente o valor numérico de linhas encontradas:
|
|
939
|
+
```javascript
|
|
940
|
+
const totalAtivos = await usuariosHandler
|
|
941
|
+
.where('status', 'ATIVO')
|
|
942
|
+
.count(); // Retorna: 42
|
|
943
|
+
```
|
|
944
|
+
|
|
945
|
+
#### Expressões SQL Brutas Seguras (`raw`)
|
|
946
|
+
Utilize a função `raw` para incorporar cálculos e funções do MySQL em `selectFields`:
|
|
947
|
+
```javascript
|
|
948
|
+
const { raw } = require('@areumtecnologia/mysql-db-handler');
|
|
949
|
+
|
|
950
|
+
const resumo = await pedidosHandler
|
|
951
|
+
.selectFields([
|
|
952
|
+
'status',
|
|
953
|
+
raw('COUNT(*) AS total_pedidos'),
|
|
954
|
+
raw('SUM(valor) AS montante_total'),
|
|
955
|
+
raw('AVG(valor) AS ticket_medio')
|
|
956
|
+
])
|
|
957
|
+
.where('criado_em', '>=', '2026-01-01')
|
|
958
|
+
.groupBy('status')
|
|
959
|
+
.having('montante_total > ?', [10000])
|
|
960
|
+
.orderBy('montante_total', 'DESC')
|
|
961
|
+
.get();
|
|
962
|
+
```
|
|
963
|
+
|
|
964
|
+
#### Paginação Tradicional com Metadados (`.paginate()`)
|
|
965
|
+
Para telas administrativas convencionais com barra de navegação paginada (Página 1 de 10):
|
|
966
|
+
```javascript
|
|
967
|
+
const resultado = await pedidosHandler.paginate({
|
|
968
|
+
page: 2,
|
|
969
|
+
limit: 15,
|
|
970
|
+
where: [{ status: 'PAGO' }],
|
|
971
|
+
orderBy: 'id DESC'
|
|
972
|
+
});
|
|
973
|
+
|
|
974
|
+
// resultado:
|
|
975
|
+
// {
|
|
976
|
+
// data: [...], // Array de 15 pedidos da página 2
|
|
977
|
+
// total: 150, // Total de pedidos no banco
|
|
978
|
+
// page: 2, // Página atual
|
|
979
|
+
// limit: 15, // Limite por página
|
|
980
|
+
// totalPages: 10 // Total de páginas disponíveis
|
|
981
|
+
// }
|
|
982
|
+
```
|
|
983
|
+
|
|
984
|
+
> [!TIP]
|
|
985
|
+
> **Quando usar `paginate` vs `cursorPaginate`:**
|
|
986
|
+
> * Use `.paginate()` para telas administrativas com paginação numerada tradicional em tabelas pequenas e médias (< 100.000 linhas).
|
|
987
|
+
> * Use `.cursorPaginate()` (Keyset Pagination) para feeds infinitos, exportações e tabelas de alta escala com milhões de linhas, onde o custo de `OFFSET` seria proibitivo.
|
|
988
|
+
|
|
989
|
+
---
|
|
990
|
+
|
|
991
|
+
### 2. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)
|
|
826
992
|
|
|
827
993
|
#### Fluent Joins with Automatic Identifier Sanitization
|
|
828
994
|
Chain `.join()`, `.leftJoin()`, `.rightJoin()`, or `.innerJoin()` directly on the query builder with support for table aliases:
|
|
@@ -845,18 +1011,19 @@ const pedidosComItens = await pedidosHandler
|
|
|
845
1011
|
type: 'hasMany',
|
|
846
1012
|
handler: itensHandler,
|
|
847
1013
|
foreignKey: 'pedido_id',
|
|
848
|
-
localKey: 'id'
|
|
1014
|
+
localKey: 'id',
|
|
1015
|
+
query: (qb) => qb.where('ativo', 1).orderBy('sequencia', 'ASC') // Filtro e ordenação customizados
|
|
849
1016
|
})
|
|
850
|
-
.with('cliente',
|
|
1017
|
+
.with('cliente', DataBaseHandler.belongsTo(clientesHandler, 'cliente_id', 'id'))
|
|
851
1018
|
.get();
|
|
852
1019
|
|
|
853
|
-
// pedidosComItens[0].itens -> Array de itens do pedido 1
|
|
1020
|
+
// pedidosComItens[0].itens -> Array de itens ativos do pedido 1
|
|
854
1021
|
// pedidosComItens[0].cliente -> Objeto do cliente associado
|
|
855
1022
|
```
|
|
856
1023
|
|
|
857
1024
|
---
|
|
858
1025
|
|
|
859
|
-
###
|
|
1026
|
+
### 3. Read/Write Splitting (Master + Read Replicas)
|
|
860
1027
|
|
|
861
1028
|
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
1029
|
|
|
@@ -885,9 +1052,18 @@ await db.transaction(async () => {
|
|
|
885
1052
|
});
|
|
886
1053
|
```
|
|
887
1054
|
|
|
1055
|
+
> [!WARNING]
|
|
1056
|
+
> **Atenção em Queries SQL Manuais (`db.query`):**
|
|
1057
|
+
> Ao executar mutações brutas sem o `DataBaseHandler` (`INSERT`, `UPDATE`, `DELETE`), o 3º argumento booleano `isWrite = true` é **obrigatório**:
|
|
1058
|
+
> ```javascript
|
|
1059
|
+
> // Se omitir o 3º argumento, um INSERT manual pode cair em uma réplica read-only!
|
|
1060
|
+
> await db.query('INSERT INTO logs SET ?', [data], true);
|
|
1061
|
+
> ```
|
|
1062
|
+
> No `DataBaseHandler`, todas as operações de escrita (`insert`, `insertMany`, `upsert`, `update`, `delete`) já encaminham automaticamente para o Master (`isWrite = true`).
|
|
1063
|
+
|
|
888
1064
|
---
|
|
889
1065
|
|
|
890
|
-
###
|
|
1066
|
+
### 4. Keyset Pagination & Memory-Safe Streaming
|
|
891
1067
|
|
|
892
1068
|
#### Keyset / Cursor Pagination (`.cursorPaginate()`)
|
|
893
1069
|
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 ?`):
|
|
@@ -904,6 +1080,17 @@ const page2 = await produtosHandler.cursorPaginate({
|
|
|
904
1080
|
});
|
|
905
1081
|
```
|
|
906
1082
|
|
|
1083
|
+
> [!TIP]
|
|
1084
|
+
> **Customização da Chave Primária (`cursorColumn`):**
|
|
1085
|
+
> O método `.cursorPaginate()` assume por padrão a coluna `'id'`. Se a tabela utilizar outra chave de ordenação ou chave primária (`uuid`, `codigo`, `cod_produto`), declare-a explicitamente:
|
|
1086
|
+
> ```javascript
|
|
1087
|
+
> const page = await produtosHandler.cursorPaginate({
|
|
1088
|
+
> cursorColumn: 'codigo',
|
|
1089
|
+
> limit: 20,
|
|
1090
|
+
> after: lastCode
|
|
1091
|
+
> });
|
|
1092
|
+
> ```
|
|
1093
|
+
|
|
907
1094
|
#### Streaming & Async Iterator (`for await ... of`)
|
|
908
1095
|
Export millions of rows to CSV or feed an ETL pipeline without triggering Node.js Heap Out of Memory errors:
|
|
909
1096
|
|
|
@@ -921,15 +1108,28 @@ relatorioHandler.stream({ batchSize: 500 })
|
|
|
921
1108
|
|
|
922
1109
|
---
|
|
923
1110
|
|
|
924
|
-
###
|
|
1111
|
+
### 5. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks
|
|
925
1112
|
|
|
926
1113
|
```javascript
|
|
927
|
-
const clientesHandler = new
|
|
1114
|
+
const clientesHandler = new DataBaseHandler(db, 'clientes', {
|
|
928
1115
|
softDelete: 'deletado_em', // ou boolean true (padrão 'deletado_em')
|
|
929
1116
|
timestamps: true // injeta criado_em e atualizado_em automaticamente
|
|
930
1117
|
});
|
|
931
1118
|
```
|
|
932
1119
|
|
|
1120
|
+
> [!TIP]
|
|
1121
|
+
> **Tabelas com Nomenclatura em Inglês (`deleted_at`, `created_at`, `updated_at`):**
|
|
1122
|
+
> Por padrão, a biblioteca assume as colunas em português (`deletado_em`, `criado_em`, `atualizado_em`). Se suas tabelas utilizam nomenclaturas em inglês, configure o objeto explicitamente:
|
|
1123
|
+
> ```javascript
|
|
1124
|
+
> const clientesHandler = new DataBaseHandler(db, 'customers_leads', {
|
|
1125
|
+
> softDelete: 'deleted_at',
|
|
1126
|
+
> timestamps: {
|
|
1127
|
+
> createdAt: 'created_at',
|
|
1128
|
+
> updatedAt: 'updated_at'
|
|
1129
|
+
> }
|
|
1130
|
+
> });
|
|
1131
|
+
> ```
|
|
1132
|
+
|
|
933
1133
|
#### Soft Deletes
|
|
934
1134
|
* `.delete(where)`: Automaticamente executa `UPDATE clientes SET deletado_em = NOW() WHERE ...`.
|
|
935
1135
|
* Consultas padrão (`select`, `get`, `first`, `paginate`, `selectToDatatable`) injetam automaticamente `AND deletado_em IS NULL`.
|
|
@@ -959,10 +1159,10 @@ clientesHandler
|
|
|
959
1159
|
|
|
960
1160
|
---
|
|
961
1161
|
|
|
962
|
-
###
|
|
1162
|
+
### 6. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking
|
|
963
1163
|
|
|
964
1164
|
```javascript
|
|
965
|
-
const usuariosHandler = new
|
|
1165
|
+
const usuariosHandler = new DataBaseHandler(db, 'usuarios', {
|
|
966
1166
|
autoStripUnknown: true, // Remove propriedades desconhecidas do payload
|
|
967
1167
|
hiddenFields: ['senha_hash', 'token_recuperacao'] // Oculta campos confidenciais das consultas
|
|
968
1168
|
});
|
package/index.d.ts
CHANGED
|
@@ -79,10 +79,12 @@ export interface PaginatedResult<T = any> {
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
export interface RelationDefinition {
|
|
82
|
-
|
|
82
|
+
type?: 'hasMany' | 'hasOne' | 'belongsTo';
|
|
83
|
+
relationType?: 'hasMany' | 'hasOne' | 'belongsTo';
|
|
83
84
|
handler: DataBaseHandler<any>;
|
|
84
85
|
foreignKey: string;
|
|
85
86
|
localKey?: string;
|
|
87
|
+
query?: (qb: DataBaseHandler<any>) => DataBaseHandler<any>;
|
|
86
88
|
}
|
|
87
89
|
|
|
88
90
|
export interface DatabaseHandlerOptions {
|
|
@@ -130,6 +132,9 @@ export class DataBaseHandler<T = RowDataPacket> {
|
|
|
130
132
|
options: DatabaseHandlerOptions;
|
|
131
133
|
|
|
132
134
|
static raw(sql: string): { __isRawSql: true; sql: string };
|
|
135
|
+
static hasMany(handler: DataBaseHandler<any>, foreignKey: string, localKey?: string): RelationDefinition;
|
|
136
|
+
static belongsTo(handler: DataBaseHandler<any>, foreignKey: string, localKey?: string): RelationDefinition;
|
|
137
|
+
static hasOne(handler: DataBaseHandler<any>, foreignKey: string, localKey?: string): RelationDefinition;
|
|
133
138
|
|
|
134
139
|
constructor(database: DataBase, table: string, expressionOrOptions?: string | DatabaseHandlerOptions);
|
|
135
140
|
withTransaction(txOrDb: any): DataBaseHandler<T>;
|
|
@@ -202,3 +207,6 @@ export class DataBaseHandler<T = RowDataPacket> {
|
|
|
202
207
|
update(params: { set: Record<string, any>; where: any }, options?: { useRegex?: boolean }): Promise<ResultSetHeader>;
|
|
203
208
|
delete(conditions: Record<string, any> | any[]): Promise<ResultSetHeader | undefined>;
|
|
204
209
|
}
|
|
210
|
+
|
|
211
|
+
export function raw(sql: string): { __isRawSql: true; sql: string };
|
|
212
|
+
export { DataBaseHandler as DatabaseHandler, DataBase as Database, DataBaseCache as DatabaseCache };
|
package/index.js
CHANGED
|
@@ -7,6 +7,10 @@ const DataBaseHandler = require('./lib/databaseHandler');
|
|
|
7
7
|
|
|
8
8
|
module.exports = {
|
|
9
9
|
DataBase,
|
|
10
|
+
Database: DataBase,
|
|
10
11
|
DataBaseHandler,
|
|
11
|
-
|
|
12
|
+
DatabaseHandler: DataBaseHandler,
|
|
13
|
+
DataBaseCache,
|
|
14
|
+
DatabaseCache: DataBaseCache,
|
|
15
|
+
raw: DataBaseHandler.raw
|
|
12
16
|
};
|
package/lib/databaseHandler.js
CHANGED
|
@@ -381,7 +381,14 @@ class DatabaseHandler {
|
|
|
381
381
|
continue;
|
|
382
382
|
}
|
|
383
383
|
|
|
384
|
-
|
|
384
|
+
const hadHiddenFk = Array.isArray(handler.hiddenFields) && handler.hiddenFields.includes(foreignKey);
|
|
385
|
+
let effectiveHandler = handler;
|
|
386
|
+
if (hadHiddenFk) {
|
|
387
|
+
effectiveHandler = handler._cloneWithBuilder();
|
|
388
|
+
effectiveHandler.hiddenFields = handler.hiddenFields.filter(f => f !== foreignKey);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
let q = effectiveHandler.where({ [foreignKey]: parentKeys });
|
|
385
392
|
if (typeof query === 'function') {
|
|
386
393
|
q = query(q) || q;
|
|
387
394
|
}
|
|
@@ -402,6 +409,12 @@ class DatabaseHandler {
|
|
|
402
409
|
const matched = grouped.get(lkVal) || [];
|
|
403
410
|
row[name] = type === 'hasMany' ? matched : (matched[0] || null);
|
|
404
411
|
}
|
|
412
|
+
|
|
413
|
+
if (hadHiddenFk) {
|
|
414
|
+
for (const child of safeChildren) {
|
|
415
|
+
delete child[foreignKey];
|
|
416
|
+
}
|
|
417
|
+
}
|
|
405
418
|
} else if (type === 'belongsTo') {
|
|
406
419
|
const fkValues = [...new Set(rows.map(r => r[foreignKey]).filter(k => k !== undefined && k !== null))];
|
|
407
420
|
if (fkValues.length === 0) {
|
|
@@ -411,7 +424,14 @@ class DatabaseHandler {
|
|
|
411
424
|
continue;
|
|
412
425
|
}
|
|
413
426
|
|
|
414
|
-
|
|
427
|
+
const hadHiddenLk = Array.isArray(handler.hiddenFields) && handler.hiddenFields.includes(localKey);
|
|
428
|
+
let effectiveHandler = handler;
|
|
429
|
+
if (hadHiddenLk) {
|
|
430
|
+
effectiveHandler = handler._cloneWithBuilder();
|
|
431
|
+
effectiveHandler.hiddenFields = handler.hiddenFields.filter(f => f !== localKey);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
let q = effectiveHandler.where({ [localKey]: fkValues });
|
|
415
435
|
if (typeof query === 'function') {
|
|
416
436
|
q = query(q) || q;
|
|
417
437
|
}
|
|
@@ -427,6 +447,12 @@ class DatabaseHandler {
|
|
|
427
447
|
const fkVal = row[foreignKey];
|
|
428
448
|
row[name] = map.get(fkVal) || null;
|
|
429
449
|
}
|
|
450
|
+
|
|
451
|
+
if (hadHiddenLk) {
|
|
452
|
+
for (const target of safeTargets) {
|
|
453
|
+
delete target[localKey];
|
|
454
|
+
}
|
|
455
|
+
}
|
|
430
456
|
}
|
|
431
457
|
}
|
|
432
458
|
|
|
@@ -560,15 +586,21 @@ class DatabaseHandler {
|
|
|
560
586
|
const before = options.before !== undefined ? options.before : null;
|
|
561
587
|
|
|
562
588
|
let qb = this._cloneWithBuilder();
|
|
589
|
+
let isReverse = false;
|
|
590
|
+
|
|
563
591
|
if (after !== null) {
|
|
564
592
|
const op = direction === 'ASC' ? '>' : '<';
|
|
565
|
-
qb = qb.where(cursorCol, op, after);
|
|
593
|
+
qb = qb.where(cursorCol, op, after).orderBy(cursorCol, direction);
|
|
566
594
|
} else if (before !== null) {
|
|
595
|
+
isReverse = true;
|
|
567
596
|
const op = direction === 'ASC' ? '<' : '>';
|
|
568
|
-
|
|
597
|
+
const revDir = direction === 'ASC' ? 'DESC' : 'ASC';
|
|
598
|
+
qb = qb.where(cursorCol, op, before).orderBy(cursorCol, revDir);
|
|
599
|
+
} else {
|
|
600
|
+
qb = qb.orderBy(cursorCol, direction);
|
|
569
601
|
}
|
|
570
602
|
|
|
571
|
-
qb = qb.
|
|
603
|
+
qb = qb.limit(limit + 1);
|
|
572
604
|
const rows = await qb.get();
|
|
573
605
|
|
|
574
606
|
if (rows && rows.error) return rows;
|
|
@@ -579,6 +611,10 @@ class DatabaseHandler {
|
|
|
579
611
|
safeRows.pop();
|
|
580
612
|
}
|
|
581
613
|
|
|
614
|
+
if (isReverse) {
|
|
615
|
+
safeRows.reverse();
|
|
616
|
+
}
|
|
617
|
+
|
|
582
618
|
const nextCursor = safeRows.length > 0 ? safeRows[safeRows.length - 1][cursorCol] : null;
|
|
583
619
|
const prevCursor = safeRows.length > 0 ? safeRows[0][cursorCol] : null;
|
|
584
620
|
|
|
@@ -1085,7 +1121,11 @@ class DatabaseHandler {
|
|
|
1085
1121
|
|
|
1086
1122
|
async select(params, clauses = {}, _objectWhereOverride = null) {
|
|
1087
1123
|
if (params != null && !Array.isArray(params)) {
|
|
1088
|
-
|
|
1124
|
+
const err = new Error('O parâmetro "params" deve ser um array');
|
|
1125
|
+
if (this.db && this.db.config && this.db.config.throwOnError) {
|
|
1126
|
+
throw err;
|
|
1127
|
+
}
|
|
1128
|
+
return { error: err };
|
|
1089
1129
|
}
|
|
1090
1130
|
|
|
1091
1131
|
const whereTarget = _objectWhereOverride || (Array.isArray(params) ? [...params] : []);
|
|
@@ -1214,14 +1254,25 @@ class DatabaseHandler {
|
|
|
1214
1254
|
const preparedData = this._applyTimestampsOnInsert(stripped);
|
|
1215
1255
|
|
|
1216
1256
|
const dataKeys = Object.keys(preparedData);
|
|
1217
|
-
const
|
|
1257
|
+
const createdCol = typeof this.timestamps === 'object' && this.timestamps.createdAt ? this.timestamps.createdAt : 'criado_em';
|
|
1258
|
+
const updatedCol = typeof this.timestamps === 'object' && this.timestamps.updatedAt ? this.timestamps.updatedAt : 'atualizado_em';
|
|
1259
|
+
|
|
1260
|
+
// Previne a sobrescrita do timestamp de criação original em caso de update
|
|
1261
|
+
const defaultUpdateCols = this.timestamps ? dataKeys.filter(k => k !== createdCol) : dataKeys;
|
|
1262
|
+
const colsToUpdate = Array.isArray(updateColumns) && updateColumns.length > 0 ? updateColumns : defaultUpdateCols;
|
|
1218
1263
|
|
|
1219
1264
|
const insertCols = dataKeys.map(k => safeColumn(k)).join(', ');
|
|
1220
1265
|
const insertPlaceholders = dataKeys.map(() => '?').join(', ');
|
|
1221
|
-
const
|
|
1266
|
+
const updateParts = colsToUpdate.map(k => {
|
|
1222
1267
|
const col = safeColumn(k);
|
|
1223
1268
|
return `${col} = VALUES(${col})`;
|
|
1224
|
-
})
|
|
1269
|
+
});
|
|
1270
|
+
|
|
1271
|
+
if (this.timestamps && !colsToUpdate.includes(updatedCol) && dataKeys.includes(updatedCol)) {
|
|
1272
|
+
updateParts.push(`${safeColumn(updatedCol)} = VALUES(${safeColumn(updatedCol)})`);
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
const updateClause = updateParts.join(', ');
|
|
1225
1276
|
|
|
1226
1277
|
const bindings = dataKeys.map(k => preparedData[k]);
|
|
1227
1278
|
const sql = `INSERT INTO ${this._safeTable()} (${insertCols}) VALUES (${insertPlaceholders}) ON DUPLICATE KEY UPDATE ${updateClause}`;
|
|
@@ -1240,8 +1291,12 @@ class DatabaseHandler {
|
|
|
1240
1291
|
throw new Error('A operação de update requer um objeto "set" com ao menos um campo.');
|
|
1241
1292
|
}
|
|
1242
1293
|
|
|
1294
|
+
const effectiveWhere = params.where !== undefined
|
|
1295
|
+
? params.where
|
|
1296
|
+
: (this._qb.where.length > 0 ? this._qb.where : null);
|
|
1297
|
+
|
|
1243
1298
|
for (const hook of this._hooks.beforeUpdate) {
|
|
1244
|
-
await hook(params.set,
|
|
1299
|
+
await hook(params.set, effectiveWhere);
|
|
1245
1300
|
}
|
|
1246
1301
|
|
|
1247
1302
|
const strippedSet = await this._stripUnknownFields(params.set);
|
|
@@ -1251,7 +1306,7 @@ class DatabaseHandler {
|
|
|
1251
1306
|
const setClause = setKeys.map(key => `${safeColumn(key)} = ?`).join(', ');
|
|
1252
1307
|
const setValues = setKeys.map(key => finalSet[key]);
|
|
1253
1308
|
|
|
1254
|
-
const { sql: whereClause, bindings: whereValues } = this._buildWhereClause(
|
|
1309
|
+
const { sql: whereClause, bindings: whereValues } = this._buildWhereClause(effectiveWhere, !!options.useRegex);
|
|
1255
1310
|
if (!whereClause || whereClause.trim() === '') {
|
|
1256
1311
|
throw new Error('A operação de update requer uma cláusula "where" não vazia para prevenir alterações em toda a tabela.');
|
|
1257
1312
|
}
|
|
@@ -1262,19 +1317,23 @@ class DatabaseHandler {
|
|
|
1262
1317
|
const result = await this.executeQuery(sql, values, true);
|
|
1263
1318
|
|
|
1264
1319
|
for (const hook of this._hooks.afterUpdate) {
|
|
1265
|
-
await hook(result, finalSet,
|
|
1320
|
+
await hook(result, finalSet, effectiveWhere);
|
|
1266
1321
|
}
|
|
1267
1322
|
|
|
1268
1323
|
return result;
|
|
1269
1324
|
}
|
|
1270
1325
|
|
|
1271
1326
|
async delete(conditions) {
|
|
1272
|
-
|
|
1327
|
+
const targetConditions = conditions !== undefined
|
|
1328
|
+
? conditions
|
|
1329
|
+
: (this._qb.where.length > 0 ? this._qb.where : null);
|
|
1330
|
+
|
|
1331
|
+
if (!targetConditions || typeof targetConditions !== 'object') {
|
|
1273
1332
|
return;
|
|
1274
1333
|
}
|
|
1275
1334
|
|
|
1276
1335
|
for (const hook of this._hooks.beforeDelete) {
|
|
1277
|
-
await hook(
|
|
1336
|
+
await hook(targetConditions);
|
|
1278
1337
|
}
|
|
1279
1338
|
|
|
1280
1339
|
const softCol = this._getSoftDeleteColumn();
|
|
@@ -1282,16 +1341,16 @@ class DatabaseHandler {
|
|
|
1282
1341
|
// Soft delete ativo: realiza UPDATE na coluna de timestamp
|
|
1283
1342
|
const result = await this.update({
|
|
1284
1343
|
set: { [softCol]: new Date() },
|
|
1285
|
-
where:
|
|
1344
|
+
where: targetConditions
|
|
1286
1345
|
});
|
|
1287
1346
|
|
|
1288
1347
|
for (const hook of this._hooks.afterDelete) {
|
|
1289
|
-
await hook(result,
|
|
1348
|
+
await hook(result, targetConditions);
|
|
1290
1349
|
}
|
|
1291
1350
|
return result;
|
|
1292
1351
|
}
|
|
1293
1352
|
|
|
1294
|
-
const { sql: whereClause, bindings } = this._buildWhereClause(
|
|
1353
|
+
const { sql: whereClause, bindings } = this._buildWhereClause(targetConditions);
|
|
1295
1354
|
if (!whereClause) {
|
|
1296
1355
|
return;
|
|
1297
1356
|
}
|
|
@@ -1300,22 +1359,26 @@ class DatabaseHandler {
|
|
|
1300
1359
|
const result = await this.executeQuery(sql, bindings, true);
|
|
1301
1360
|
|
|
1302
1361
|
for (const hook of this._hooks.afterDelete) {
|
|
1303
|
-
await hook(result,
|
|
1362
|
+
await hook(result, targetConditions);
|
|
1304
1363
|
}
|
|
1305
1364
|
|
|
1306
1365
|
return result;
|
|
1307
1366
|
}
|
|
1308
1367
|
|
|
1309
1368
|
async forceDelete(conditions) {
|
|
1310
|
-
|
|
1369
|
+
const targetConditions = conditions !== undefined
|
|
1370
|
+
? conditions
|
|
1371
|
+
: (this._qb.where.length > 0 ? this._qb.where : null);
|
|
1372
|
+
|
|
1373
|
+
if (!targetConditions || typeof targetConditions !== 'object') {
|
|
1311
1374
|
return;
|
|
1312
1375
|
}
|
|
1313
1376
|
|
|
1314
1377
|
for (const hook of this._hooks.beforeDelete) {
|
|
1315
|
-
await hook(
|
|
1378
|
+
await hook(targetConditions);
|
|
1316
1379
|
}
|
|
1317
1380
|
|
|
1318
|
-
const { sql: whereClause, bindings } = this._buildWhereClause(
|
|
1381
|
+
const { sql: whereClause, bindings } = this._buildWhereClause(targetConditions);
|
|
1319
1382
|
if (!whereClause) {
|
|
1320
1383
|
return;
|
|
1321
1384
|
}
|
|
@@ -1324,13 +1387,17 @@ class DatabaseHandler {
|
|
|
1324
1387
|
const result = await this.executeQuery(sql, bindings, true);
|
|
1325
1388
|
|
|
1326
1389
|
for (const hook of this._hooks.afterDelete) {
|
|
1327
|
-
await hook(result,
|
|
1390
|
+
await hook(result, targetConditions);
|
|
1328
1391
|
}
|
|
1329
1392
|
|
|
1330
1393
|
return result;
|
|
1331
1394
|
}
|
|
1332
1395
|
|
|
1333
1396
|
async restore(conditions) {
|
|
1397
|
+
const targetConditions = conditions !== undefined
|
|
1398
|
+
? conditions
|
|
1399
|
+
: (this._qb.where.length > 0 ? this._qb.where : null);
|
|
1400
|
+
|
|
1334
1401
|
const softCol = this._getSoftDeleteColumn();
|
|
1335
1402
|
if (!softCol) {
|
|
1336
1403
|
throw new Error('O método restore() só pode ser usado quando o Soft Delete estiver ativo.');
|
|
@@ -1338,7 +1405,7 @@ class DatabaseHandler {
|
|
|
1338
1405
|
|
|
1339
1406
|
return await this.update({
|
|
1340
1407
|
set: { [softCol]: null },
|
|
1341
|
-
where:
|
|
1408
|
+
where: targetConditions
|
|
1342
1409
|
});
|
|
1343
1410
|
}
|
|
1344
1411
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@areumtecnologia/mysql-db-handler",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.3",
|
|
4
4
|
"description": "High-scale enterprise Micro-ORM and MySQL Data Mapper with connection pooling, read/write splitting, eager loading, keyset pagination, soft deletes, and fluent query builder for Node.js.",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"types": "index.d.ts",
|
package/idex.d.ts
DELETED
|
@@ -1,137 +0,0 @@
|
|
|
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
|
-
}
|