@areumtecnologia/mysql-db-handler 1.0.14 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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
+ }
@@ -3,12 +3,24 @@ const DataBase = require('./database');
3
3
  let NodeCache;
4
4
  try {
5
5
  NodeCache = require('node-cache');
6
- } catch (e) {
7
- // Fallback in-memory com TTL básico caso node-cache não esteja instalado
6
+ } catch {
8
7
  NodeCache = class FallbackCache {
9
8
  constructor(options = {}) {
10
9
  this.map = new Map();
11
10
  this.defaultTTL = (options.stdTTL || 100) * 1000;
11
+ const checkPeriod = (options.checkperiod || 120) * 1000;
12
+ if (checkPeriod > 0) {
13
+ this.timer = setInterval(() => this._evictExpired(), checkPeriod);
14
+ if (this.timer.unref) this.timer.unref();
15
+ }
16
+ }
17
+ _evictExpired() {
18
+ const now = Date.now();
19
+ for (const [k, entry] of this.map.entries()) {
20
+ if (entry.expiry && now > entry.expiry) {
21
+ this.map.delete(k);
22
+ }
23
+ }
12
24
  }
13
25
  get(key) {
14
26
  const entry = this.map.get(key);
@@ -24,79 +36,155 @@ try {
24
36
  const expiry = ttlMs > 0 ? Date.now() + ttlMs : null;
25
37
  this.map.set(key, { val, expiry });
26
38
  }
39
+ del(keys) {
40
+ const arr = Array.isArray(keys) ? keys : [keys];
41
+ for (const k of arr) this.map.delete(k);
42
+ }
27
43
  flushAll() {
28
44
  this.map.clear();
29
45
  }
46
+ close() {
47
+ if (this.timer) clearInterval(this.timer);
48
+ }
30
49
  };
31
50
  }
32
51
 
33
52
  function safeStringify(data) {
53
+ if (data === undefined || data === null) return '';
34
54
  try {
35
- return JSON.stringify(data || [], (_, value) => {
36
- if (typeof value === 'bigint') {
37
- return value.toString();
38
- }
39
- return value;
40
- });
55
+ return JSON.stringify(data, (_, value) =>
56
+ typeof value === 'bigint' ? value.toString() : value
57
+ );
41
58
  } catch {
42
59
  return String(data);
43
60
  }
44
61
  }
45
62
 
63
+ function extractTableFromSql(sql) {
64
+ if (!sql || typeof sql !== 'string') return 'global';
65
+ const match = sql.match(/(?:FROM|INTO|UPDATE)\s+`?([a-zA-Z0-9_.]+)`?/i);
66
+ return match ? match[1].replace(/`/g, '').toLowerCase() : 'global';
67
+ }
68
+
46
69
  class DataBaseCache extends DataBase {
70
+ /**
71
+ * @param {Object} [config] - Configuração da base de dados.
72
+ * @param {Object} [cacheOptions] - Opções do NodeCache ou store customizado ({ stdTTL, checkperiod, store }).
73
+ */
47
74
  constructor(config = {}, cacheOptions = { stdTTL: 100, checkperiod: 120 }) {
48
75
  super(config);
49
- this.cache = new NodeCache(cacheOptions);
76
+ this.stdTTL = cacheOptions.stdTTL || 100;
77
+ // Permite injetar um adaptador externo (ex.: Redis) ou usa NodeCache local
78
+ this.cache = cacheOptions.store || new NodeCache(cacheOptions);
79
+ // Índice de chaves por tabela para invalidação cirúrgica
80
+ this.tableIndex = new Map();
50
81
  }
51
82
 
52
- // Mantido por compatibilidade
53
83
  createPool() {
54
84
  return this.pool;
55
85
  }
56
86
 
57
- async query(sql, params, isWrite = false) {
58
- const inTransaction = !!this.getCurrentTransaction();
87
+ _registerTableKey(table, key) {
88
+ const normalizedTable = (table || 'global').toLowerCase();
89
+ if (!this.tableIndex.has(normalizedTable)) {
90
+ this.tableIndex.set(normalizedTable, new Set());
91
+ }
92
+ this.tableIndex.get(normalizedTable).add(key);
93
+ }
94
+
95
+ async query(sql, params, isWrite = false, options = {}) {
96
+ const inActiveTransaction = this.hasActiveTransaction();
97
+ const tableTag = (options.table || extractTableFromSql(sql)).toLowerCase();
59
98
 
60
- // Se estiver em transação ou for escrita, bypassa o cache completamente
61
- if (inTransaction || isWrite) {
62
- return await super.query(sql, params, isWrite);
99
+ if (isWrite) {
100
+ const result = await super.query(sql, params, true, options);
101
+ if (result && !result.error) {
102
+ if (inActiveTransaction) {
103
+ // Se estiver em transação, limpa o cache da tabela apenas quando o commit for confirmado
104
+ this.onCommit(() => this.clearTableCache(tableTag));
105
+ } else {
106
+ await this.clearTableCache(tableTag);
107
+ }
108
+ }
109
+ return result;
63
110
  }
64
111
 
65
- const key = `query_${sql}_${safeStringify(params)}`;
66
- const cachedResult = this.cache.get(key);
112
+ if (inActiveTransaction) {
113
+ return await super.query(sql, params, false, options);
114
+ }
115
+
116
+ const key = `query:${tableTag}:${sql}:${safeStringify(params)}`;
117
+ const cachedResult = await this.cache.get(key);
67
118
 
68
- if (cachedResult) {
119
+ if (cachedResult !== undefined && cachedResult !== null) {
69
120
  return cachedResult;
70
121
  }
71
122
 
72
- const rows = await super.query(sql, params, isWrite);
123
+ const rows = await super.query(sql, params, false, options);
73
124
  if (rows && !rows.error) {
74
- this.cache.set(key, rows);
125
+ const ttl = options.ttl !== undefined ? options.ttl : this.stdTTL;
126
+ await this.cache.set(key, rows, ttl);
127
+ this._registerTableKey(tableTag, key);
75
128
  }
76
129
  return rows;
77
130
  }
78
131
 
79
132
  async getTableSchema(table) {
80
- const inTransaction = !!this.getCurrentTransaction();
81
- const key = `schema_${table}`;
133
+ const inActiveTransaction = this.hasActiveTransaction();
134
+ const normalizedTable = String(table).toLowerCase();
135
+ const key = `schema:${normalizedTable}`;
82
136
 
83
- if (!inTransaction) {
84
- const cachedResult = this.cache.get(key);
85
- if (cachedResult) {
137
+ if (!inActiveTransaction) {
138
+ const cachedResult = await this.cache.get(key);
139
+ if (cachedResult !== undefined && cachedResult !== null) {
86
140
  return cachedResult;
87
141
  }
88
142
  }
89
143
 
90
144
  const rows = await super.getTableSchema(table);
91
- if (!inTransaction && rows && !rows.error) {
92
- this.cache.set(key, rows);
145
+ if (!inActiveTransaction && rows && !rows.error) {
146
+ await this.cache.set(key, rows, this.stdTTL);
147
+ this._registerTableKey(normalizedTable, key);
93
148
  }
94
149
  return rows;
95
150
  }
96
151
 
97
- clearCache() {
98
- this.cache.flushAll();
152
+ /**
153
+ * Invalida seletivamente apenas as queries associadas a uma tabela específica.
154
+ */
155
+ async clearTableCache(table) {
156
+ if (!table) return this.clearCache();
157
+ const normalizedTable = String(table).replace(/`/g, '').toLowerCase();
158
+ const keys = this.tableIndex.get(normalizedTable);
159
+
160
+ if (keys && keys.size > 0) {
161
+ const keyArray = Array.from(keys);
162
+ if (typeof this.cache.del === 'function') {
163
+ await this.cache.del(keyArray);
164
+ } else {
165
+ for (const k of keyArray) {
166
+ if (typeof this.cache.delete === 'function') await this.cache.delete(k);
167
+ }
168
+ }
169
+ this.tableIndex.delete(normalizedTable);
170
+ }
171
+ }
172
+
173
+ async clearCache() {
174
+ this.tableIndex.clear();
175
+ if (typeof this.cache.flushAll === 'function') {
176
+ await this.cache.flushAll();
177
+ } else if (typeof this.cache.clear === 'function') {
178
+ await this.cache.clear();
179
+ }
180
+ }
181
+
182
+ async close() {
183
+ if (this.cache && typeof this.cache.close === 'function') {
184
+ await this.cache.close();
185
+ }
186
+ await super.close();
99
187
  }
100
188
  }
101
189
 
102
- module.exports = DataBaseCache;
190
+ module.exports = DataBaseCache;