@areumtecnologia/mysql-db-handler 1.0.14 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +165 -0
- 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
|
@@ -702,6 +702,171 @@ if (deleteResult.error) {
|
|
|
702
702
|
|
|
703
703
|
---
|
|
704
704
|
|
|
705
|
+
## High-Scale Enterprise Micro-ORM (v2.0.0)
|
|
706
|
+
|
|
707
|
+
With **v2.0.0**, `@areumtecnologia/mysql-db-handler` evolves from a single-table CRUD helper into a full-fledged enterprise Data Mapper and Micro-ORM designed for high-throughput, mission-critical systems.
|
|
708
|
+
|
|
709
|
+
### 1. Fluent Joins & Eager Loading (Eliminating the N+1 Problem)
|
|
710
|
+
|
|
711
|
+
#### Fluent Joins with Automatic Identifier Sanitization
|
|
712
|
+
Chain `.join()`, `.leftJoin()`, `.rightJoin()`, or `.innerJoin()` directly on the query builder with support for table aliases:
|
|
713
|
+
|
|
714
|
+
```javascript
|
|
715
|
+
const pedidos = await pedidosHandler
|
|
716
|
+
.selectFields(['pedidos.id', 'pedidos.valor', { column: 'c.nome', as: 'cliente_nome' }])
|
|
717
|
+
.leftJoin('clientes c', 'pedidos.cliente_id', '=', 'c.id')
|
|
718
|
+
.where('pedidos.status', 'PAGO')
|
|
719
|
+
.get();
|
|
720
|
+
```
|
|
721
|
+
|
|
722
|
+
#### Eager Loading (`.with()`)
|
|
723
|
+
Prevent the dreaded N+1 query problem without creating massive, memory-heavy Cartesian joins in MySQL. Child entities are loaded in a single batched `WHERE foreign_key IN (...)` query and hydrated directly onto parents in memory:
|
|
724
|
+
|
|
725
|
+
```javascript
|
|
726
|
+
const pedidosComItens = await pedidosHandler
|
|
727
|
+
.where('status', 'PAGO')
|
|
728
|
+
.with('itens', {
|
|
729
|
+
type: 'hasMany',
|
|
730
|
+
handler: itensHandler,
|
|
731
|
+
foreignKey: 'pedido_id',
|
|
732
|
+
localKey: 'id'
|
|
733
|
+
})
|
|
734
|
+
.with('cliente', DatabaseHandler.belongsTo(clientesHandler, 'cliente_id', 'id'))
|
|
735
|
+
.get();
|
|
736
|
+
|
|
737
|
+
// pedidosComItens[0].itens -> Array de itens do pedido 1
|
|
738
|
+
// pedidosComItens[0].cliente -> Objeto do cliente associado
|
|
739
|
+
```
|
|
740
|
+
|
|
741
|
+
---
|
|
742
|
+
|
|
743
|
+
### 2. Read/Write Splitting (Master + Read Replicas)
|
|
744
|
+
|
|
745
|
+
Scale read traffic horizontally across multiple cloud replicas (e.g. AWS Aurora, GCP Cloud SQL, Azure Database for MySQL) with automatic Round-Robin load balancing and strict transactional sticky sessions:
|
|
746
|
+
|
|
747
|
+
```javascript
|
|
748
|
+
const db = new DataBase({
|
|
749
|
+
host: 'primary-master.internal', // Pool de Escrita (Master)
|
|
750
|
+
user: 'app_user',
|
|
751
|
+
password: 'secret_password',
|
|
752
|
+
database: 'meu_banco',
|
|
753
|
+
replicas: [
|
|
754
|
+
{ host: 'read-replica-1.internal' },
|
|
755
|
+
{ host: 'read-replica-2.internal' }
|
|
756
|
+
]
|
|
757
|
+
});
|
|
758
|
+
|
|
759
|
+
// Queries simples de leitura são distribuídas via Round-Robin nas réplicas
|
|
760
|
+
const users = await db.query('SELECT * FROM users WHERE status = ?', ['active']);
|
|
761
|
+
|
|
762
|
+
// Operações de mutação (INSERT, UPDATE, DELETE) vão obrigatoriamente para o Master
|
|
763
|
+
await db.query('INSERT INTO users SET ?', [{ name: 'Novo Usuário' }], true);
|
|
764
|
+
|
|
765
|
+
// Dentro de transações, TODAS as leituras e escritas utilizam a conexão Master (evitando replication lag)
|
|
766
|
+
await db.transaction(async () => {
|
|
767
|
+
const user = await db.query('SELECT saldo FROM contas WHERE id = ?', [1]);
|
|
768
|
+
await db.query('UPDATE contas SET saldo = saldo - 50 WHERE id = ?', [1], true);
|
|
769
|
+
});
|
|
770
|
+
```
|
|
771
|
+
|
|
772
|
+
---
|
|
773
|
+
|
|
774
|
+
### 3. Keyset Pagination & Memory-Safe Streaming
|
|
775
|
+
|
|
776
|
+
#### Keyset / Cursor Pagination (`.cursorPaginate()`)
|
|
777
|
+
Traditional `OFFSET` pagination degrades significantly on large tables because MySQL must scan and discard all rows before the offset. Keyset pagination uses constant-time index seeks (`WHERE id > ? ORDER BY id ASC LIMIT ?`):
|
|
778
|
+
|
|
779
|
+
```javascript
|
|
780
|
+
// Primeira página
|
|
781
|
+
const page1 = await produtosHandler.cursorPaginate({ limit: 20 });
|
|
782
|
+
// page1: { data: [...], nextCursor: 20, prevCursor: 1, hasMore: true, limit: 20 }
|
|
783
|
+
|
|
784
|
+
// Próxima página (tempo constante de 1ms, mesmo após 500.000 registos)
|
|
785
|
+
const page2 = await produtosHandler.cursorPaginate({
|
|
786
|
+
limit: 20,
|
|
787
|
+
after: page1.nextCursor
|
|
788
|
+
});
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
#### Streaming & Async Iterator (`for await ... of`)
|
|
792
|
+
Export millions of rows to CSV or feed an ETL pipeline without triggering Node.js Heap Out of Memory errors:
|
|
793
|
+
|
|
794
|
+
```javascript
|
|
795
|
+
// Iteração sob demanda com consumo constante de memória (< 30 MB)
|
|
796
|
+
for await (const row of relatorioHandler.cursor({ batchSize: 1000 })) {
|
|
797
|
+
processRow(row);
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
// Node.js Readable Stream nativo para pipes HTTP ou arquivos
|
|
801
|
+
relatorioHandler.stream({ batchSize: 500 })
|
|
802
|
+
.pipe(csvTransformStream)
|
|
803
|
+
.pipe(res);
|
|
804
|
+
```
|
|
805
|
+
|
|
806
|
+
---
|
|
807
|
+
|
|
808
|
+
### 4. Native Business Rules: Soft Deletes, Timestamps & Lifecycle Hooks
|
|
809
|
+
|
|
810
|
+
```javascript
|
|
811
|
+
const clientesHandler = new DatabaseHandler(db, 'clientes', {
|
|
812
|
+
softDelete: 'deletado_em', // ou boolean true (padrão 'deletado_em')
|
|
813
|
+
timestamps: true // injeta criado_em e atualizado_em automaticamente
|
|
814
|
+
});
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
#### Soft Deletes
|
|
818
|
+
* `.delete(where)`: Automaticamente executa `UPDATE clientes SET deletado_em = NOW() WHERE ...`.
|
|
819
|
+
* Consultas padrão (`select`, `get`, `first`, `paginate`, `selectToDatatable`) injetam automaticamente `AND deletado_em IS NULL`.
|
|
820
|
+
* `.withTrashed()`: Desativa o filtro para retornar registos ativos e deletados.
|
|
821
|
+
* `.onlyTrashed()`: Retorna exclusivamente registos na lixeira (`deletado_em IS NOT NULL`).
|
|
822
|
+
* `.restore(where)`: Restaura registos setando `deletado_em = NULL`.
|
|
823
|
+
* `.forceDelete(where)`: Executa `DELETE FROM` físico no MySQL.
|
|
824
|
+
|
|
825
|
+
#### Lifecycle Hooks
|
|
826
|
+
Intercepte mutações antes ou depois de sua persistência:
|
|
827
|
+
|
|
828
|
+
```javascript
|
|
829
|
+
clientesHandler
|
|
830
|
+
.beforeInsert(async (data) => {
|
|
831
|
+
data.slug = slugify(data.nome);
|
|
832
|
+
})
|
|
833
|
+
.afterInsert(async (result, data) => {
|
|
834
|
+
await logAudit('CLIENT_CREATED', result.insertId);
|
|
835
|
+
})
|
|
836
|
+
.beforeUpdate(async (set, where) => {
|
|
837
|
+
validateBusinessRules(set);
|
|
838
|
+
})
|
|
839
|
+
.afterDelete(async (result, where) => {
|
|
840
|
+
await notifyService(where);
|
|
841
|
+
});
|
|
842
|
+
```
|
|
843
|
+
|
|
844
|
+
---
|
|
845
|
+
|
|
846
|
+
### 5. Runtime Schema Validation (Auto-Strip) & Sensitive Field Masking
|
|
847
|
+
|
|
848
|
+
```javascript
|
|
849
|
+
const usuariosHandler = new DatabaseHandler(db, 'usuarios', {
|
|
850
|
+
autoStripUnknown: true, // Remove propriedades desconhecidas do payload
|
|
851
|
+
hiddenFields: ['senha_hash', 'token_recuperacao'] // Oculta campos confidenciais das consultas
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
// Prevenção de Mass Assignment e ER_BAD_FIELD_ERROR vindo de requisições web:
|
|
855
|
+
await usuariosHandler.insert({
|
|
856
|
+
nome: 'Carlos',
|
|
857
|
+
email: 'carlos@empresa.com',
|
|
858
|
+
senha_hash: 'hash_seguro',
|
|
859
|
+
isAdminFake: true, // Ignorado silenciosamente pois não existe no schema
|
|
860
|
+
payload_sujo: 'qualquer_coisa' // Ignorado silenciosamente
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
// Consultas nunca retornam senha_hash ou token_recuperacao acidentalmente:
|
|
864
|
+
const usuario = await usuariosHandler.where('id', 1).first();
|
|
865
|
+
console.log(usuario.senha_hash); // undefined
|
|
866
|
+
```
|
|
867
|
+
|
|
868
|
+
---
|
|
869
|
+
|
|
705
870
|
## Contributing
|
|
706
871
|
|
|
707
872
|
Contributions are welcome! Please open an issue or submit a pull request.
|
package/idex.d.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { Pool, PoolConnection, PoolOptions, ResultSetHeader, RowDataPacket } from 'mysql2/promise';
|
|
2
|
+
|
|
3
|
+
export type IsolationLevel = 'READ UNCOMMITTED' | 'READ COMMITTED' | 'REPEATABLE READ' | 'SERIALIZABLE';
|
|
4
|
+
|
|
5
|
+
export interface ExtendedDatabaseConfig extends PoolOptions {
|
|
6
|
+
throwOnError?: boolean;
|
|
7
|
+
usePreparedStatements?: boolean;
|
|
8
|
+
slowQueryThreshold?: number;
|
|
9
|
+
onSlowQuery?: (info: { sql: string; params: any; durationMs: number }) => void;
|
|
10
|
+
logger?: Pick<Console, 'log' | 'warn' | 'error' | 'debug'>;
|
|
11
|
+
maxRetries?: number;
|
|
12
|
+
retryDelayMs?: number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface TransactionOptions {
|
|
16
|
+
isolationLevel?: IsolationLevel;
|
|
17
|
+
retries?: number;
|
|
18
|
+
retryDelayMs?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface AutoTransactionOptions {
|
|
22
|
+
methods?: string[];
|
|
23
|
+
lazy?: boolean;
|
|
24
|
+
isolationLevel?: IsolationLevel;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface CacheStoreAdapter {
|
|
28
|
+
get(key: string): any | Promise<any>;
|
|
29
|
+
set(key: string, val: any, ttl?: number): any | Promise<any>;
|
|
30
|
+
del?(keys: string | string[]): any | Promise<any>;
|
|
31
|
+
flushAll?(): any | Promise<any>;
|
|
32
|
+
close?(): any | Promise<any>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface CacheOptions {
|
|
36
|
+
stdTTL?: number;
|
|
37
|
+
checkperiod?: number;
|
|
38
|
+
store?: CacheStoreAdapter;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface PaginateOptions {
|
|
42
|
+
page?: number;
|
|
43
|
+
limit?: number;
|
|
44
|
+
where?: any;
|
|
45
|
+
fields?: Array<string | { column: string; as: string } | { raw: string }>;
|
|
46
|
+
orderBy?: string | string[];
|
|
47
|
+
groupBy?: string | string[];
|
|
48
|
+
having?: { sql: string; bindings?: any[] } | string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface PaginatedResult<T = any> {
|
|
52
|
+
data: T[];
|
|
53
|
+
total: number;
|
|
54
|
+
page: number;
|
|
55
|
+
limit: number;
|
|
56
|
+
totalPages: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class DataBase {
|
|
60
|
+
id: number;
|
|
61
|
+
config: ExtendedDatabaseConfig;
|
|
62
|
+
pool: Pool;
|
|
63
|
+
|
|
64
|
+
constructor(config?: ExtendedDatabaseConfig);
|
|
65
|
+
getPool(): Pool;
|
|
66
|
+
getConnection(): Promise<PoolConnection>;
|
|
67
|
+
getCurrentTransaction(): Record<string, any> | null;
|
|
68
|
+
hasActiveTransaction(): boolean;
|
|
69
|
+
onCommit(callback: () => any | Promise<any>): void;
|
|
70
|
+
transaction<T>(callback: (tx: any) => Promise<T>, options?: TransactionOptions): Promise<T>;
|
|
71
|
+
transactional<T extends (...args: any[]) => Promise<any>>(fn: T, options?: TransactionOptions): T;
|
|
72
|
+
autoTransaction(options?: AutoTransactionOptions): (req: any, res: any, next: any) => void;
|
|
73
|
+
query<T = any>(sql: string, params?: any, isWrite?: boolean, options?: { prepare?: boolean; table?: string; ttl?: number }): Promise<T>;
|
|
74
|
+
execute<T = any>(sql: string, params?: any[], isWrite?: boolean, options?: { table?: string }): Promise<T>;
|
|
75
|
+
getTableSchema(table: string): Promise<RowDataPacket[]>;
|
|
76
|
+
close(): Promise<void>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export class DataBaseCache extends DataBase {
|
|
80
|
+
constructor(config?: ExtendedDatabaseConfig, cacheOptions?: CacheOptions);
|
|
81
|
+
createPool(): Pool;
|
|
82
|
+
clearTableCache(table: string): Promise<void>;
|
|
83
|
+
clearCache(): Promise<void>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class DataBaseHandler<T = RowDataPacket> {
|
|
87
|
+
db: DataBase;
|
|
88
|
+
table: string;
|
|
89
|
+
debug: boolean;
|
|
90
|
+
expression: string;
|
|
91
|
+
onError: ((err: Error) => void) | null;
|
|
92
|
+
|
|
93
|
+
static raw(sql: string): { __isRawSql: true; sql: string };
|
|
94
|
+
|
|
95
|
+
constructor(database: DataBase, table: string, expression?: string);
|
|
96
|
+
withTransaction(txOrDb: any): DataBaseHandler<T>;
|
|
97
|
+
getSchema(): Promise<RowDataPacket[]>;
|
|
98
|
+
executeQuery(sql: string, params?: any, isWrite?: boolean, options?: Record<string, any>): Promise<any>;
|
|
99
|
+
|
|
100
|
+
// Fluent Query Builder
|
|
101
|
+
selectFields(fields: string | string[] | Array<string | { column: string; as: string } | { raw: string }>): DataBaseHandler<T>;
|
|
102
|
+
where(columnOrObject: string | Record<string, any> | any[], operatorOrValue?: any, value?: any): DataBaseHandler<T>;
|
|
103
|
+
orWhere(columnOrObject: string | Record<string, any>, operatorOrValue?: any, value?: any): DataBaseHandler<T>;
|
|
104
|
+
groupBy(cols: string | string[]): DataBaseHandler<T>;
|
|
105
|
+
having(sql: string, bindings?: any[]): DataBaseHandler<T>;
|
|
106
|
+
orderBy(column: string, dir?: 'ASC' | 'DESC'): DataBaseHandler<T>;
|
|
107
|
+
limit(count: number): DataBaseHandler<T>;
|
|
108
|
+
offset(count: number): DataBaseHandler<T>;
|
|
109
|
+
get(): Promise<T[]>;
|
|
110
|
+
first(): Promise<T | null>;
|
|
111
|
+
count(column?: string): Promise<number>;
|
|
112
|
+
|
|
113
|
+
// Core Operations
|
|
114
|
+
paginate(options?: PaginateOptions): Promise<PaginatedResult<T>>;
|
|
115
|
+
selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[]): Promise<{
|
|
116
|
+
draw: number;
|
|
117
|
+
recordsTotal: number;
|
|
118
|
+
recordsFiltered: number;
|
|
119
|
+
data: T[];
|
|
120
|
+
error?: string;
|
|
121
|
+
}>;
|
|
122
|
+
selectBy(params?: Record<string, any>): Promise<T[]>;
|
|
123
|
+
select(params?: any[], clauses?: {
|
|
124
|
+
FIELDS?: any[];
|
|
125
|
+
GROUPBY?: string | string[];
|
|
126
|
+
HAVING?: string | { sql: string; bindings?: any[] };
|
|
127
|
+
ORDERBY?: string | string[];
|
|
128
|
+
DESC?: boolean;
|
|
129
|
+
LIMIT?: number;
|
|
130
|
+
OFFSET?: number;
|
|
131
|
+
}): Promise<T[]>;
|
|
132
|
+
insert(params: Record<string, any>): Promise<ResultSetHeader>;
|
|
133
|
+
insertMany(rowsArray: Array<Record<string, any>>): Promise<ResultSetHeader>;
|
|
134
|
+
upsert(data: Record<string, any>, updateColumns?: string[]): Promise<ResultSetHeader>;
|
|
135
|
+
update(params: { set: Record<string, any>; where: any }, options?: { useRegex?: boolean }): Promise<ResultSetHeader>;
|
|
136
|
+
delete(conditions: Record<string, any> | any[]): Promise<ResultSetHeader | undefined>;
|
|
137
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
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
|
+
// v2.0.0 Read/Write Splitting
|
|
14
|
+
replicas?: Array<PoolOptions>;
|
|
15
|
+
readReplicas?: Array<PoolOptions>;
|
|
16
|
+
stickyWrites?: boolean;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface TransactionOptions {
|
|
20
|
+
isolationLevel?: IsolationLevel;
|
|
21
|
+
retries?: number;
|
|
22
|
+
retryDelayMs?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface AutoTransactionOptions {
|
|
26
|
+
methods?: string[];
|
|
27
|
+
lazy?: boolean;
|
|
28
|
+
isolationLevel?: IsolationLevel;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface CacheStoreAdapter {
|
|
32
|
+
get(key: string): any | Promise<any>;
|
|
33
|
+
set(key: string, val: any, ttl?: number): any | Promise<any>;
|
|
34
|
+
del?(keys: string | string[]): any | Promise<any>;
|
|
35
|
+
flushAll?(): any | Promise<any>;
|
|
36
|
+
close?(): any | Promise<any>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface CacheOptions {
|
|
40
|
+
stdTTL?: number;
|
|
41
|
+
checkperiod?: number;
|
|
42
|
+
store?: CacheStoreAdapter;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface PaginateOptions {
|
|
46
|
+
page?: number;
|
|
47
|
+
limit?: number;
|
|
48
|
+
where?: any;
|
|
49
|
+
fields?: Array<string | { column: string; as: string } | { raw: string }>;
|
|
50
|
+
orderBy?: string | string[];
|
|
51
|
+
groupBy?: string | string[];
|
|
52
|
+
having?: { sql: string; bindings?: any[] } | string;
|
|
53
|
+
clauses?: Record<string, any>;
|
|
54
|
+
desc?: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface CursorPaginateOptions {
|
|
58
|
+
cursorColumn?: string;
|
|
59
|
+
after?: string | number;
|
|
60
|
+
before?: string | number;
|
|
61
|
+
limit?: number;
|
|
62
|
+
direction?: 'ASC' | 'DESC';
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface CursorPaginatedResult<T = any> {
|
|
66
|
+
data: T[];
|
|
67
|
+
nextCursor: string | number | null;
|
|
68
|
+
prevCursor: string | number | null;
|
|
69
|
+
hasMore: boolean;
|
|
70
|
+
limit: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface PaginatedResult<T = any> {
|
|
74
|
+
data: T[];
|
|
75
|
+
total: number;
|
|
76
|
+
page: number;
|
|
77
|
+
limit: number;
|
|
78
|
+
totalPages: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export interface RelationDefinition {
|
|
82
|
+
relationType: 'hasMany' | 'hasOne' | 'belongsTo';
|
|
83
|
+
handler: DataBaseHandler<any>;
|
|
84
|
+
foreignKey: string;
|
|
85
|
+
localKey?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface DatabaseHandlerOptions {
|
|
89
|
+
expression?: string;
|
|
90
|
+
softDelete?: boolean | string;
|
|
91
|
+
timestamps?: boolean | { createdAt?: string; updatedAt?: string };
|
|
92
|
+
hiddenFields?: string[];
|
|
93
|
+
autoStripUnknown?: boolean;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export class DataBase {
|
|
97
|
+
id: number;
|
|
98
|
+
config: ExtendedDatabaseConfig;
|
|
99
|
+
pool: Pool;
|
|
100
|
+
replicaPools: Pool[];
|
|
101
|
+
|
|
102
|
+
constructor(config?: ExtendedDatabaseConfig);
|
|
103
|
+
getPool(isWrite?: boolean): Pool;
|
|
104
|
+
getConnection(isWrite?: boolean): Promise<PoolConnection>;
|
|
105
|
+
getCurrentTransaction(): Record<string, any> | null;
|
|
106
|
+
hasActiveTransaction(): boolean;
|
|
107
|
+
onCommit(callback: () => any | Promise<any>): void;
|
|
108
|
+
transaction<T>(callback: (tx: any) => Promise<T>, options?: TransactionOptions): Promise<T>;
|
|
109
|
+
transactional<T extends (...args: any[]) => Promise<any>>(fn: T, options?: TransactionOptions): T;
|
|
110
|
+
autoTransaction(options?: AutoTransactionOptions): (req: any, res: any, next: any) => void;
|
|
111
|
+
query<T = any>(sql: string, params?: any, isWrite?: boolean, options?: { prepare?: boolean; table?: string; ttl?: number }): Promise<T>;
|
|
112
|
+
execute<T = any>(sql: string, params?: any[], isWrite?: boolean, options?: { table?: string }): Promise<T>;
|
|
113
|
+
getTableSchema(table: string): Promise<RowDataPacket[]>;
|
|
114
|
+
close(): Promise<void>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export class DataBaseCache extends DataBase {
|
|
118
|
+
constructor(config?: ExtendedDatabaseConfig, cacheOptions?: CacheOptions);
|
|
119
|
+
createPool(): Pool;
|
|
120
|
+
clearTableCache(table: string): Promise<void>;
|
|
121
|
+
clearCache(): Promise<void>;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export class DataBaseHandler<T = RowDataPacket> {
|
|
125
|
+
db: DataBase;
|
|
126
|
+
table: string;
|
|
127
|
+
debug: boolean;
|
|
128
|
+
expression: string;
|
|
129
|
+
onError: ((err: Error) => void) | null;
|
|
130
|
+
options: DatabaseHandlerOptions;
|
|
131
|
+
|
|
132
|
+
static raw(sql: string): { __isRawSql: true; sql: string };
|
|
133
|
+
|
|
134
|
+
constructor(database: DataBase, table: string, expressionOrOptions?: string | DatabaseHandlerOptions);
|
|
135
|
+
withTransaction(txOrDb: any): DataBaseHandler<T>;
|
|
136
|
+
getSchema(): Promise<RowDataPacket[]>;
|
|
137
|
+
executeQuery(sql: string, params?: any, isWrite?: boolean, options?: Record<string, any>): Promise<any>;
|
|
138
|
+
|
|
139
|
+
// Fluent Joins
|
|
140
|
+
join(table: string, first: string, operator: string, second: string): DataBaseHandler<T>;
|
|
141
|
+
leftJoin(table: string, first: string, operator: string, second: string): DataBaseHandler<T>;
|
|
142
|
+
rightJoin(table: string, first: string, operator: string, second: string): DataBaseHandler<T>;
|
|
143
|
+
innerJoin(table: string, first: string, operator: string, second: string): DataBaseHandler<T>;
|
|
144
|
+
|
|
145
|
+
// Eager Loading (N+1 Elimination)
|
|
146
|
+
with(relationName: string, relationOrHandler: RelationDefinition | DataBaseHandler<any>): DataBaseHandler<T>;
|
|
147
|
+
|
|
148
|
+
// Soft Deletes & Trashed Scope
|
|
149
|
+
withTrashed(): DataBaseHandler<T>;
|
|
150
|
+
onlyTrashed(): DataBaseHandler<T>;
|
|
151
|
+
restore(conditions: Record<string, any> | any[]): Promise<ResultSetHeader>;
|
|
152
|
+
forceDelete(conditions: Record<string, any> | any[]): Promise<ResultSetHeader | undefined>;
|
|
153
|
+
|
|
154
|
+
// Lifecycle Hooks
|
|
155
|
+
beforeInsert(hook: (data: Record<string, any>) => any | Promise<any>): this;
|
|
156
|
+
afterInsert(hook: (result: any, data: Record<string, any>) => any | Promise<any>): this;
|
|
157
|
+
beforeUpdate(hook: (set: Record<string, any>, where: any) => any | Promise<any>): this;
|
|
158
|
+
afterUpdate(hook: (result: any, set: Record<string, any>, where: any) => any | Promise<any>): this;
|
|
159
|
+
beforeDelete(hook: (where: any) => any | Promise<any>): this;
|
|
160
|
+
afterDelete(hook: (result: any, where: any) => any | Promise<any>): this;
|
|
161
|
+
|
|
162
|
+
// Fluent Query Builder
|
|
163
|
+
selectFields(fields: string | string[] | Array<string | { column: string; as: string } | { raw: string }>): DataBaseHandler<T>;
|
|
164
|
+
where(columnOrObject: string | Record<string, any> | any[], operatorOrValue?: any, value?: any): DataBaseHandler<T>;
|
|
165
|
+
orWhere(columnOrObject: string | Record<string, any>, operatorOrValue?: any, value?: any): DataBaseHandler<T>;
|
|
166
|
+
groupBy(cols: string | string[]): DataBaseHandler<T>;
|
|
167
|
+
having(sql: string, bindings?: any[]): DataBaseHandler<T>;
|
|
168
|
+
orderBy(column: string, dir?: 'ASC' | 'DESC'): DataBaseHandler<T>;
|
|
169
|
+
limit(count: number): DataBaseHandler<T>;
|
|
170
|
+
offset(count: number): DataBaseHandler<T>;
|
|
171
|
+
get(): Promise<T[]>;
|
|
172
|
+
first(): Promise<T | null>;
|
|
173
|
+
count(column?: string): Promise<number>;
|
|
174
|
+
|
|
175
|
+
// Keyset Pagination & Streaming
|
|
176
|
+
cursorPaginate(options?: CursorPaginateOptions): Promise<CursorPaginatedResult<T>>;
|
|
177
|
+
cursor(options?: { batchSize?: number }): AsyncGenerator<T, void, unknown>;
|
|
178
|
+
stream(options?: Record<string, any>): any;
|
|
179
|
+
|
|
180
|
+
// Core Operations
|
|
181
|
+
paginate(options?: PaginateOptions): Promise<PaginatedResult<T>>;
|
|
182
|
+
selectToDatatable(rawDtQuery: Record<string, any>, strictCondition?: any[]): Promise<{
|
|
183
|
+
draw: number;
|
|
184
|
+
recordsTotal: number;
|
|
185
|
+
recordsFiltered: number;
|
|
186
|
+
data: T[];
|
|
187
|
+
error?: string;
|
|
188
|
+
}>;
|
|
189
|
+
selectBy(params?: Record<string, any>): Promise<T[]>;
|
|
190
|
+
select(params?: any[], clauses?: {
|
|
191
|
+
FIELDS?: any[];
|
|
192
|
+
GROUPBY?: string | string[];
|
|
193
|
+
HAVING?: string | { sql: string; bindings?: any[] };
|
|
194
|
+
ORDERBY?: string | string[];
|
|
195
|
+
DESC?: boolean;
|
|
196
|
+
LIMIT?: number;
|
|
197
|
+
OFFSET?: number;
|
|
198
|
+
}): Promise<T[]>;
|
|
199
|
+
insert(params: Record<string, any>): Promise<ResultSetHeader>;
|
|
200
|
+
insertMany(rowsArray: Array<Record<string, any>>): Promise<ResultSetHeader>;
|
|
201
|
+
upsert(data: Record<string, any>, updateColumns?: string[]): Promise<ResultSetHeader>;
|
|
202
|
+
update(params: { set: Record<string, any>; where: any }, options?: { useRegex?: boolean }): Promise<ResultSetHeader>;
|
|
203
|
+
delete(conditions: Record<string, any> | any[]): Promise<ResultSetHeader | undefined>;
|
|
204
|
+
}
|