@areumtecnologia/mysql-db-handler 2.0.2 → 2.1.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 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/databasehandler.js`. Bind this class to a specific table to perform database actions through utility methods (`select`, `selectBy`, `insert`, `update`, `delete`, `selectToDatatable`).
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`)
@@ -438,9 +522,11 @@ app.post('/api/users/datatable', async (req, res) => {
438
522
 
439
523
  ---
440
524
 
441
- ### Enforcing Backend Security (`strictCondition`)
525
+ ### Enforcing Backend Security & Custom Filters (`strictCondition`)
526
+
527
+ Never rely solely on client frontend parameters to enforce data boundaries or custom business filters. Pass `strictCondition` to apply non-bypassable constraints.
442
528
 
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:
529
+ `strictCondition` supports both **Array syntax** (with custom operators, arrays mapped to `IN`, and explicit `'AND'`/`'OR'`) and **Plain Object syntax** (multiple properties are automatically combined with `AND`):
444
530
 
445
531
  ```javascript
446
532
  app.post('/api/orders/datatable', async (req, res) => {
@@ -460,6 +546,40 @@ app.post('/api/orders/datatable', async (req, res) => {
460
546
 
461
547
  ---
462
548
 
549
+ ### Handling Custom Frontend Filters (e.g., Status, Dates, Categories)
550
+
551
+ When users apply custom UI filters (dropdowns, datepickers, checkboxes) alongside DataTables, capture them in your controller and pass them into `strictCondition`:
552
+
553
+ ```javascript
554
+ app.post('/api/clientes/datatable', async (req, res) => {
555
+ const filters = [];
556
+
557
+ // Map UI filter (e.g. 'HABILITADO') to database column ('active' = 1 / 0)
558
+ if (req.body.status) {
559
+ filters.push({ active: req.body.status === 'HABILITADO' ? 1 : 0 });
560
+ }
561
+
562
+ if (req.body.created_after) {
563
+ if (filters.length > 0) filters.push('AND');
564
+ filters.push({ created_at: req.body.created_after, operator: '>=' });
565
+ }
566
+
567
+ // Pass request body + backend-mapped filters
568
+ const result = await clientesHandler.selectToDatatable(req.body, filters);
569
+ res.json(result);
570
+ });
571
+ ```
572
+
573
+ > [!TIP]
574
+ > **DataTables Modern Protocol Support (v1.10, v2.x, v3.x):**
575
+ > `selectToDatatable` automatically normalizes:
576
+ > - **Search**: supports standard `{ value: '...', regex: false }`, direct strings (`search: '...'`), and query fallbacks (`q`).
577
+ > - **Columns**: accepts both standard `Array` and index-keyed objects (`{ '0': {...}, '1': {...} }`).
578
+ > - **Ordering**: supports ordering by column index (`order: [{ column: 0, dir: 'asc' }]`) and by column name (`order: [{ name: 'col_name', dir: 'desc' }]`).
579
+ > - **Payload collision**: prevents bracketed keys (`search[value]`) from being corrupted by flat parameters.
580
+
581
+ ---
582
+
463
583
  ### Using JOINs with DataTables
464
584
 
465
585
  #### Option A: Modern Fluent Query Builder Joins (Recommended in v2.0.0)
@@ -515,7 +635,7 @@ app.post('/api/sales/datatable', async (req, res) => {
515
635
  When configuring business rules on the handler, `selectToDatatable` automatically complies without requiring manual filters:
516
636
 
517
637
  ```javascript
518
- const clientesHandler = new DatabaseHandler(db, 'clientes', {
638
+ const clientesHandler = new DataBaseHandler(db, 'clientes', {
519
639
  softDelete: 'deletado_em', // Injeta 'AND deletado_em IS NULL' automaticamente
520
640
  hiddenFields: ['senha_hash', 'token_recuperacao'] // Remove do retorno mesmo se 'SELECT *' for usado
521
641
  });
@@ -822,7 +942,77 @@ if (deleteResult.error) {
822
942
 
823
943
  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
944
 
825
- ### 1. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)
945
+ ### 1. Fluent Query Builder & Aggregations (`.first`, `.count`, `.paginate`, `raw`)
946
+
947
+ 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:
948
+
949
+ #### Obter um Único Registro (`.first()`)
950
+ Executa `LIMIT 1` e já desempacota o primeiro objeto ou retorna `null` caso nenhum registro atenda aos critérios:
951
+ ```javascript
952
+ const usuario = await usuariosHandler
953
+ .where('email', 'admin@empresa.com')
954
+ .first();
955
+
956
+ if (!usuario) {
957
+ console.log('Usuário não encontrado');
958
+ }
959
+ ```
960
+
961
+ #### Contagem Direta de Registros (`.count()`)
962
+ Retorna diretamente o valor numérico de linhas encontradas:
963
+ ```javascript
964
+ const totalAtivos = await usuariosHandler
965
+ .where('status', 'ATIVO')
966
+ .count(); // Retorna: 42
967
+ ```
968
+
969
+ #### Expressões SQL Brutas Seguras (`raw`)
970
+ Utilize a função `raw` para incorporar cálculos e funções do MySQL em `selectFields`:
971
+ ```javascript
972
+ const { raw } = require('@areumtecnologia/mysql-db-handler');
973
+
974
+ const resumo = await pedidosHandler
975
+ .selectFields([
976
+ 'status',
977
+ raw('COUNT(*) AS total_pedidos'),
978
+ raw('SUM(valor) AS montante_total'),
979
+ raw('AVG(valor) AS ticket_medio')
980
+ ])
981
+ .where('criado_em', '>=', '2026-01-01')
982
+ .groupBy('status')
983
+ .having('montante_total > ?', [10000])
984
+ .orderBy('montante_total', 'DESC')
985
+ .get();
986
+ ```
987
+
988
+ #### Paginação Tradicional com Metadados (`.paginate()`)
989
+ Para telas administrativas convencionais com barra de navegação paginada (Página 1 de 10):
990
+ ```javascript
991
+ const resultado = await pedidosHandler.paginate({
992
+ page: 2,
993
+ limit: 15,
994
+ where: [{ status: 'PAGO' }],
995
+ orderBy: 'id DESC'
996
+ });
997
+
998
+ // resultado:
999
+ // {
1000
+ // data: [...], // Array de 15 pedidos da página 2
1001
+ // total: 150, // Total de pedidos no banco
1002
+ // page: 2, // Página atual
1003
+ // limit: 15, // Limite por página
1004
+ // totalPages: 10 // Total de páginas disponíveis
1005
+ // }
1006
+ ```
1007
+
1008
+ > [!TIP]
1009
+ > **Quando usar `paginate` vs `cursorPaginate`:**
1010
+ > * Use `.paginate()` para telas administrativas com paginação numerada tradicional em tabelas pequenas e médias (< 100.000 linhas).
1011
+ > * 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.
1012
+
1013
+ ---
1014
+
1015
+ ### 2. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)
826
1016
 
827
1017
  #### Fluent Joins with Automatic Identifier Sanitization
828
1018
  Chain `.join()`, `.leftJoin()`, `.rightJoin()`, or `.innerJoin()` directly on the query builder with support for table aliases:
@@ -845,18 +1035,19 @@ const pedidosComItens = await pedidosHandler
845
1035
  type: 'hasMany',
846
1036
  handler: itensHandler,
847
1037
  foreignKey: 'pedido_id',
848
- localKey: 'id'
1038
+ localKey: 'id',
1039
+ query: (qb) => qb.where('ativo', 1).orderBy('sequencia', 'ASC') // Filtro e ordenação customizados
849
1040
  })
850
- .with('cliente', DatabaseHandler.belongsTo(clientesHandler, 'cliente_id', 'id'))
1041
+ .with('cliente', DataBaseHandler.belongsTo(clientesHandler, 'cliente_id', 'id'))
851
1042
  .get();
852
1043
 
853
- // pedidosComItens[0].itens -> Array de itens do pedido 1
1044
+ // pedidosComItens[0].itens -> Array de itens ativos do pedido 1
854
1045
  // pedidosComItens[0].cliente -> Objeto do cliente associado
855
1046
  ```
856
1047
 
857
1048
  ---
858
1049
 
859
- ### 2. Read/Write Splitting (Master + Read Replicas)
1050
+ ### 3. Read/Write Splitting (Master + Read Replicas)
860
1051
 
861
1052
  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
1053
 
@@ -885,9 +1076,18 @@ await db.transaction(async () => {
885
1076
  });
886
1077
  ```
887
1078
 
1079
+ > [!WARNING]
1080
+ > **Atenção em Queries SQL Manuais (`db.query`):**
1081
+ > Ao executar mutações brutas sem o `DataBaseHandler` (`INSERT`, `UPDATE`, `DELETE`), o 3º argumento booleano `isWrite = true` é **obrigatório**:
1082
+ > ```javascript
1083
+ > // Se omitir o 3º argumento, um INSERT manual pode cair em uma réplica read-only!
1084
+ > await db.query('INSERT INTO logs SET ?', [data], true);
1085
+ > ```
1086
+ > No `DataBaseHandler`, todas as operações de escrita (`insert`, `insertMany`, `upsert`, `update`, `delete`) já encaminham automaticamente para o Master (`isWrite = true`).
1087
+
888
1088
  ---
889
1089
 
890
- ### 3. Keyset Pagination & Memory-Safe Streaming
1090
+ ### 4. Keyset Pagination & Memory-Safe Streaming
891
1091
 
892
1092
  #### Keyset / Cursor Pagination (`.cursorPaginate()`)
893
1093
  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 +1104,17 @@ const page2 = await produtosHandler.cursorPaginate({
904
1104
  });
905
1105
  ```
906
1106
 
1107
+ > [!TIP]
1108
+ > **Customização da Chave Primária (`cursorColumn`):**
1109
+ > 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:
1110
+ > ```javascript
1111
+ > const page = await produtosHandler.cursorPaginate({
1112
+ > cursorColumn: 'codigo',
1113
+ > limit: 20,
1114
+ > after: lastCode
1115
+ > });
1116
+ > ```
1117
+
907
1118
  #### Streaming & Async Iterator (`for await ... of`)
908
1119
  Export millions of rows to CSV or feed an ETL pipeline without triggering Node.js Heap Out of Memory errors:
909
1120
 
@@ -921,15 +1132,28 @@ relatorioHandler.stream({ batchSize: 500 })
921
1132
 
922
1133
  ---
923
1134
 
924
- ### 4. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks
1135
+ ### 5. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks
925
1136
 
926
1137
  ```javascript
927
- const clientesHandler = new DatabaseHandler(db, 'clientes', {
1138
+ const clientesHandler = new DataBaseHandler(db, 'clientes', {
928
1139
  softDelete: 'deletado_em', // ou boolean true (padrão 'deletado_em')
929
1140
  timestamps: true // injeta criado_em e atualizado_em automaticamente
930
1141
  });
931
1142
  ```
932
1143
 
1144
+ > [!TIP]
1145
+ > **Tabelas com Nomenclatura em Inglês (`deleted_at`, `created_at`, `updated_at`):**
1146
+ > 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:
1147
+ > ```javascript
1148
+ > const clientesHandler = new DataBaseHandler(db, 'customers_leads', {
1149
+ > softDelete: 'deleted_at',
1150
+ > timestamps: {
1151
+ > createdAt: 'created_at',
1152
+ > updatedAt: 'updated_at'
1153
+ > }
1154
+ > });
1155
+ > ```
1156
+
933
1157
  #### Soft Deletes
934
1158
  * `.delete(where)`: Automaticamente executa `UPDATE clientes SET deletado_em = NOW() WHERE ...`.
935
1159
  * Consultas padrão (`select`, `get`, `first`, `paginate`, `selectToDatatable`) injetam automaticamente `AND deletado_em IS NULL`.
@@ -959,10 +1183,10 @@ clientesHandler
959
1183
 
960
1184
  ---
961
1185
 
962
- ### 5. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking
1186
+ ### 6. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking
963
1187
 
964
1188
  ```javascript
965
- const usuariosHandler = new DatabaseHandler(db, 'usuarios', {
1189
+ const usuariosHandler = new DataBaseHandler(db, 'usuarios', {
966
1190
  autoStripUnknown: true, // Remove propriedades desconhecidas do payload
967
1191
  hiddenFields: ['senha_hash', 'token_recuperacao'] // Oculta campos confidenciais das consultas
968
1192
  });
package/index.d.ts CHANGED
@@ -79,10 +79,12 @@ export interface PaginatedResult<T = any> {
79
79
  }
80
80
 
81
81
  export interface RelationDefinition {
82
- relationType: 'hasMany' | 'hasOne' | 'belongsTo';
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>;
@@ -179,7 +184,7 @@ export class DataBaseHandler<T = RowDataPacket> {
179
184
 
180
185
  // Core Operations
181
186
  paginate(options?: PaginateOptions): Promise<PaginatedResult<T>>;
182
- selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[]): Promise<{
187
+ selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[] | Record<string, any>): Promise<{
183
188
  draw: number;
184
189
  recordsTotal: number;
185
190
  recordsFiltered: number;
@@ -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
- DataBaseCache
12
+ DatabaseHandler: DataBaseHandler,
13
+ DataBaseCache,
14
+ DatabaseCache: DataBaseCache,
15
+ raw: DataBaseHandler.raw
12
16
  };
@@ -381,7 +381,14 @@ class DatabaseHandler {
381
381
  continue;
382
382
  }
383
383
 
384
- let q = handler.where({ [foreignKey]: parentKeys });
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
- let q = handler.where({ [localKey]: fkValues });
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
- qb = qb.where(cursorCol, op, before);
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.orderBy(cursorCol, direction).limit(limit + 1);
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
 
@@ -634,7 +670,15 @@ class DatabaseHandler {
634
670
  for (const key of Object.keys(flatObject)) {
635
671
  if (!key.includes('[')) {
636
672
  if (key !== '__proto__' && key !== 'constructor' && key !== 'prototype') {
637
- result[key] = flatObject[key];
673
+ const existing = result[key];
674
+ const incoming = flatObject[key];
675
+ if (existing && typeof existing === 'object' && (!incoming || typeof incoming !== 'object')) {
676
+ // Não sobrescreve um objeto já estruturado (ex: search vindo de search[value]) com valor primitivo
677
+ } else if (existing && typeof existing === 'object' && incoming && typeof incoming === 'object') {
678
+ result[key] = { ...existing, ...incoming };
679
+ } else {
680
+ result[key] = incoming;
681
+ }
638
682
  }
639
683
  continue;
640
684
  }
@@ -648,7 +692,7 @@ class DatabaseHandler {
648
692
  for (let i = 0; i < keys.length - 1; i++) {
649
693
  const k = keys[i];
650
694
  const nextKey = keys[i + 1];
651
- if (current[k] === undefined) {
695
+ if (current[k] === undefined || current[k] === null || typeof current[k] !== 'object') {
652
696
  current[k] = !isNaN(nextKey) ? [] : {};
653
697
  }
654
698
  current = current[k];
@@ -918,7 +962,18 @@ class DatabaseHandler {
918
962
  const parsedDraw = parseInt(draw, 10) || 0;
919
963
 
920
964
  try {
921
- const finalStrict = Array.isArray(strictCondition) ? [...strictCondition] : [strictCondition];
965
+ let finalStrict = [];
966
+ if (Array.isArray(strictCondition)) {
967
+ finalStrict = [...strictCondition];
968
+ } else if (strictCondition && typeof strictCondition === 'object') {
969
+ const entries = Object.entries(strictCondition);
970
+ for (let i = 0; i < entries.length; i++) {
971
+ const [k, v] = entries[i];
972
+ if (i > 0) finalStrict.push('AND');
973
+ finalStrict.push({ [k]: v });
974
+ }
975
+ }
976
+
922
977
  const softCol = this._getSoftDeleteColumn();
923
978
  if (softCol && !this._qb.withTrashed) {
924
979
  if (finalStrict.length > 0) finalStrict.push('AND');
@@ -933,14 +988,25 @@ class DatabaseHandler {
933
988
  const finalBindings = [...baseWhere.bindings];
934
989
  const finalWhereClauses = baseWhere.sql ? [baseWhere.sql] : [];
935
990
 
991
+ // Normaliza columns para suportar tanto Array quanto Objeto indexado ({ '0': {...}, '1': {...} })
992
+ const colsArray = Array.isArray(columns)
993
+ ? columns
994
+ : (columns && typeof columns === 'object' ? Object.values(columns) : []);
995
+
936
996
  const dtSearchClauses = [];
937
- if (Array.isArray(columns)) {
938
- if (search && search.value !== '' && search.value !== undefined && search.value !== null) {
939
- const searchableCols = columns.filter(c => c && c.data && isTrue(c.searchable));
997
+ if (colsArray.length > 0) {
998
+ // Normaliza o termo de busca global (suporta search.value, string direta ou fallback q)
999
+ const rawSearchVal = typeof search === 'string'
1000
+ ? search
1001
+ : (search && search.value != null ? search.value : (dtQuery.q != null ? dtQuery.q : ''));
1002
+ const globalSearchTerm = String(rawSearchVal ?? '').trim();
1003
+
1004
+ if (globalSearchTerm !== '') {
1005
+ const searchableCols = colsArray.filter(c => c && c.data && isTrue(c.searchable));
940
1006
  if (searchableCols.length > 0) {
941
- const isRegex = isTrue(search.regex);
1007
+ const isRegex = (typeof search === 'object' && search !== null) ? isTrue(search.regex) : false;
942
1008
  const operator = isRegex ? 'REGEXP' : 'LIKE';
943
- const term = isRegex ? `${search.value}` : `%${search.value}%`;
1009
+ const term = isRegex ? globalSearchTerm : `%${globalSearchTerm}%`;
944
1010
 
945
1011
  const orClauses = searchableCols.map(c => `${safeColumn(c.data)} ${operator} ?`);
946
1012
  dtSearchClauses.push(`(${orClauses.join(' OR ')})`);
@@ -950,14 +1016,23 @@ class DatabaseHandler {
950
1016
  }
951
1017
  }
952
1018
 
953
- for (const col of columns) {
954
- if (col && col.data && isTrue(col.searchable) && col.search && col.search.value !== '' && col.search.value !== undefined && col.search.value !== null) {
955
- const isRegex = isTrue(col.search.regex);
956
- const operator = isRegex ? 'REGEXP' : 'LIKE';
957
- const term = isRegex ? `${col.search.value}` : `%${col.search.value}%`;
958
-
959
- dtSearchClauses.push(`${safeColumn(col.data)} ${operator} ?`);
960
- finalBindings.push(term);
1019
+ // Busca individual por coluna
1020
+ for (const col of colsArray) {
1021
+ if (col && col.data && isTrue(col.searchable)) {
1022
+ const colSearch = col.search;
1023
+ const colVal = typeof colSearch === 'string'
1024
+ ? colSearch
1025
+ : (colSearch && colSearch.value != null ? colSearch.value : '');
1026
+ const colSearchTerm = String(colVal ?? '').trim();
1027
+
1028
+ if (colSearchTerm !== '') {
1029
+ const isRegex = (typeof colSearch === 'object' && colSearch !== null) ? isTrue(colSearch.regex) : false;
1030
+ const operator = isRegex ? 'REGEXP' : 'LIKE';
1031
+ const term = isRegex ? colSearchTerm : `%${colSearchTerm}%`;
1032
+
1033
+ dtSearchClauses.push(`${safeColumn(col.data)} ${operator} ?`);
1034
+ finalBindings.push(term);
1035
+ }
961
1036
  }
962
1037
  }
963
1038
  }
@@ -972,12 +1047,18 @@ class DatabaseHandler {
972
1047
  const joinClause = this._buildJoinClauses(this._qb.joins);
973
1048
 
974
1049
  let orderSql = '';
975
- if (order && Array.isArray(columns)) {
1050
+ if (order && colsArray.length > 0) {
976
1051
  const orderArray = Array.isArray(order) ? order : Object.values(order);
977
1052
  const orderParts = [];
978
1053
  for (const ord of orderArray) {
979
- if (!ord || ord.column === undefined) continue;
980
- const colDef = columns[parseInt(ord.column, 10)];
1054
+ if (!ord) continue;
1055
+ let colDef = null;
1056
+ if (ord.column !== undefined && ord.column !== null && ord.column !== '') {
1057
+ colDef = colsArray[parseInt(ord.column, 10)];
1058
+ } else if (ord.name || ord.data) {
1059
+ const targetName = ord.name || ord.data;
1060
+ colDef = colsArray.find(c => c && (c.name === targetName || c.data === targetName));
1061
+ }
981
1062
  if (colDef && isTrue(colDef.orderable) && colDef.data) {
982
1063
  const orderDir = ord.dir && String(ord.dir).toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
983
1064
  orderParts.push(`${safeColumn(colDef.data)} ${orderDir}`);
@@ -1085,7 +1166,11 @@ class DatabaseHandler {
1085
1166
 
1086
1167
  async select(params, clauses = {}, _objectWhereOverride = null) {
1087
1168
  if (params != null && !Array.isArray(params)) {
1088
- return new Error('O parâmetro "params" deve ser um array');
1169
+ const err = new Error('O parâmetro "params" deve ser um array');
1170
+ if (this.db && this.db.config && this.db.config.throwOnError) {
1171
+ throw err;
1172
+ }
1173
+ return { error: err };
1089
1174
  }
1090
1175
 
1091
1176
  const whereTarget = _objectWhereOverride || (Array.isArray(params) ? [...params] : []);
@@ -1214,14 +1299,25 @@ class DatabaseHandler {
1214
1299
  const preparedData = this._applyTimestampsOnInsert(stripped);
1215
1300
 
1216
1301
  const dataKeys = Object.keys(preparedData);
1217
- const colsToUpdate = Array.isArray(updateColumns) && updateColumns.length > 0 ? updateColumns : dataKeys;
1302
+ const createdCol = typeof this.timestamps === 'object' && this.timestamps.createdAt ? this.timestamps.createdAt : 'criado_em';
1303
+ const updatedCol = typeof this.timestamps === 'object' && this.timestamps.updatedAt ? this.timestamps.updatedAt : 'atualizado_em';
1304
+
1305
+ // Previne a sobrescrita do timestamp de criação original em caso de update
1306
+ const defaultUpdateCols = this.timestamps ? dataKeys.filter(k => k !== createdCol) : dataKeys;
1307
+ const colsToUpdate = Array.isArray(updateColumns) && updateColumns.length > 0 ? updateColumns : defaultUpdateCols;
1218
1308
 
1219
1309
  const insertCols = dataKeys.map(k => safeColumn(k)).join(', ');
1220
1310
  const insertPlaceholders = dataKeys.map(() => '?').join(', ');
1221
- const updateClause = colsToUpdate.map(k => {
1311
+ const updateParts = colsToUpdate.map(k => {
1222
1312
  const col = safeColumn(k);
1223
1313
  return `${col} = VALUES(${col})`;
1224
- }).join(', ');
1314
+ });
1315
+
1316
+ if (this.timestamps && !colsToUpdate.includes(updatedCol) && dataKeys.includes(updatedCol)) {
1317
+ updateParts.push(`${safeColumn(updatedCol)} = VALUES(${safeColumn(updatedCol)})`);
1318
+ }
1319
+
1320
+ const updateClause = updateParts.join(', ');
1225
1321
 
1226
1322
  const bindings = dataKeys.map(k => preparedData[k]);
1227
1323
  const sql = `INSERT INTO ${this._safeTable()} (${insertCols}) VALUES (${insertPlaceholders}) ON DUPLICATE KEY UPDATE ${updateClause}`;
@@ -1240,8 +1336,12 @@ class DatabaseHandler {
1240
1336
  throw new Error('A operação de update requer um objeto "set" com ao menos um campo.');
1241
1337
  }
1242
1338
 
1339
+ const effectiveWhere = params.where !== undefined
1340
+ ? params.where
1341
+ : (this._qb.where.length > 0 ? this._qb.where : null);
1342
+
1243
1343
  for (const hook of this._hooks.beforeUpdate) {
1244
- await hook(params.set, params.where);
1344
+ await hook(params.set, effectiveWhere);
1245
1345
  }
1246
1346
 
1247
1347
  const strippedSet = await this._stripUnknownFields(params.set);
@@ -1251,7 +1351,7 @@ class DatabaseHandler {
1251
1351
  const setClause = setKeys.map(key => `${safeColumn(key)} = ?`).join(', ');
1252
1352
  const setValues = setKeys.map(key => finalSet[key]);
1253
1353
 
1254
- const { sql: whereClause, bindings: whereValues } = this._buildWhereClause(params.where, !!options.useRegex);
1354
+ const { sql: whereClause, bindings: whereValues } = this._buildWhereClause(effectiveWhere, !!options.useRegex);
1255
1355
  if (!whereClause || whereClause.trim() === '') {
1256
1356
  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
1357
  }
@@ -1262,19 +1362,23 @@ class DatabaseHandler {
1262
1362
  const result = await this.executeQuery(sql, values, true);
1263
1363
 
1264
1364
  for (const hook of this._hooks.afterUpdate) {
1265
- await hook(result, finalSet, params.where);
1365
+ await hook(result, finalSet, effectiveWhere);
1266
1366
  }
1267
1367
 
1268
1368
  return result;
1269
1369
  }
1270
1370
 
1271
1371
  async delete(conditions) {
1272
- if (!conditions || typeof conditions !== 'object') {
1372
+ const targetConditions = conditions !== undefined
1373
+ ? conditions
1374
+ : (this._qb.where.length > 0 ? this._qb.where : null);
1375
+
1376
+ if (!targetConditions || typeof targetConditions !== 'object') {
1273
1377
  return;
1274
1378
  }
1275
1379
 
1276
1380
  for (const hook of this._hooks.beforeDelete) {
1277
- await hook(conditions);
1381
+ await hook(targetConditions);
1278
1382
  }
1279
1383
 
1280
1384
  const softCol = this._getSoftDeleteColumn();
@@ -1282,16 +1386,16 @@ class DatabaseHandler {
1282
1386
  // Soft delete ativo: realiza UPDATE na coluna de timestamp
1283
1387
  const result = await this.update({
1284
1388
  set: { [softCol]: new Date() },
1285
- where: conditions
1389
+ where: targetConditions
1286
1390
  });
1287
1391
 
1288
1392
  for (const hook of this._hooks.afterDelete) {
1289
- await hook(result, conditions);
1393
+ await hook(result, targetConditions);
1290
1394
  }
1291
1395
  return result;
1292
1396
  }
1293
1397
 
1294
- const { sql: whereClause, bindings } = this._buildWhereClause(conditions);
1398
+ const { sql: whereClause, bindings } = this._buildWhereClause(targetConditions);
1295
1399
  if (!whereClause) {
1296
1400
  return;
1297
1401
  }
@@ -1300,22 +1404,26 @@ class DatabaseHandler {
1300
1404
  const result = await this.executeQuery(sql, bindings, true);
1301
1405
 
1302
1406
  for (const hook of this._hooks.afterDelete) {
1303
- await hook(result, conditions);
1407
+ await hook(result, targetConditions);
1304
1408
  }
1305
1409
 
1306
1410
  return result;
1307
1411
  }
1308
1412
 
1309
1413
  async forceDelete(conditions) {
1310
- if (!conditions || typeof conditions !== 'object') {
1414
+ const targetConditions = conditions !== undefined
1415
+ ? conditions
1416
+ : (this._qb.where.length > 0 ? this._qb.where : null);
1417
+
1418
+ if (!targetConditions || typeof targetConditions !== 'object') {
1311
1419
  return;
1312
1420
  }
1313
1421
 
1314
1422
  for (const hook of this._hooks.beforeDelete) {
1315
- await hook(conditions);
1423
+ await hook(targetConditions);
1316
1424
  }
1317
1425
 
1318
- const { sql: whereClause, bindings } = this._buildWhereClause(conditions);
1426
+ const { sql: whereClause, bindings } = this._buildWhereClause(targetConditions);
1319
1427
  if (!whereClause) {
1320
1428
  return;
1321
1429
  }
@@ -1324,13 +1432,17 @@ class DatabaseHandler {
1324
1432
  const result = await this.executeQuery(sql, bindings, true);
1325
1433
 
1326
1434
  for (const hook of this._hooks.afterDelete) {
1327
- await hook(result, conditions);
1435
+ await hook(result, targetConditions);
1328
1436
  }
1329
1437
 
1330
1438
  return result;
1331
1439
  }
1332
1440
 
1333
1441
  async restore(conditions) {
1442
+ const targetConditions = conditions !== undefined
1443
+ ? conditions
1444
+ : (this._qb.where.length > 0 ? this._qb.where : null);
1445
+
1334
1446
  const softCol = this._getSoftDeleteColumn();
1335
1447
  if (!softCol) {
1336
1448
  throw new Error('O método restore() só pode ser usado quando o Soft Delete estiver ativo.');
@@ -1338,7 +1450,7 @@ class DatabaseHandler {
1338
1450
 
1339
1451
  return await this.update({
1340
1452
  set: { [softCol]: null },
1341
- where: conditions
1453
+ where: targetConditions
1342
1454
  });
1343
1455
  }
1344
1456
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@areumtecnologia/mysql-db-handler",
3
- "version": "2.0.2",
3
+ "version": "2.1.0",
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
- }