noormme 1.0.0 → 1.0.2

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.
Files changed (137) hide show
  1. package/LICENSE +89 -21
  2. package/README.md +195 -578
  3. package/dist/cjs/cli/commands/analyze.js +4 -1
  4. package/dist/cjs/cli/commands/generate.js +48 -8
  5. package/dist/cjs/cli/commands/init.js +54 -14
  6. package/dist/cjs/cli/commands/inspect.js +10 -3
  7. package/dist/cjs/cli/commands/migrate.js +38 -2
  8. package/dist/cjs/cli/commands/optimize.js +4 -1
  9. package/dist/cjs/cli/commands/status.js +41 -5
  10. package/dist/cjs/cli/commands/watch.js +4 -1
  11. package/dist/cjs/cli/index.js +4 -1
  12. package/dist/cjs/dialect/database-introspector.js +16 -21
  13. package/dist/cjs/dialect/sqlite/sqlite-introspector.js +13 -24
  14. package/dist/cjs/dynamic/dynamic.d.ts +20 -0
  15. package/dist/cjs/dynamic/dynamic.js +25 -0
  16. package/dist/cjs/edge-runtime/edge-config.d.ts +125 -0
  17. package/dist/cjs/edge-runtime/edge-config.js +323 -0
  18. package/dist/cjs/errors/NoormError.d.ts +27 -4
  19. package/dist/cjs/errors/NoormError.js +142 -21
  20. package/dist/cjs/logging/logger.d.ts +7 -2
  21. package/dist/cjs/logging/logger.js +21 -7
  22. package/dist/cjs/noormme.d.ts +12 -8
  23. package/dist/cjs/noormme.js +133 -61
  24. package/dist/cjs/operation-node/column-node.js +4 -0
  25. package/dist/cjs/operation-node/identifier-node.js +4 -0
  26. package/dist/cjs/operation-node/table-node.js +7 -0
  27. package/dist/cjs/parser/reference-parser.js +5 -0
  28. package/dist/cjs/parser/table-parser.js +2 -0
  29. package/dist/cjs/performance/index.d.ts +44 -0
  30. package/dist/cjs/performance/index.js +64 -0
  31. package/dist/cjs/performance/query-optimizer.d.ts +134 -0
  32. package/dist/cjs/performance/query-optimizer.js +391 -0
  33. package/dist/cjs/performance/services/cache-service.d.ts +177 -0
  34. package/dist/cjs/performance/services/cache-service.js +415 -0
  35. package/dist/cjs/performance/services/connection-factory.d.ts +198 -0
  36. package/dist/cjs/performance/services/connection-factory.js +498 -0
  37. package/dist/cjs/performance/services/metrics-collector.d.ts +162 -0
  38. package/dist/cjs/performance/services/metrics-collector.js +406 -0
  39. package/dist/cjs/performance/utils/query-parser.d.ts +123 -0
  40. package/dist/cjs/performance/utils/query-parser.js +295 -0
  41. package/dist/cjs/raw-builder/sql.d.ts +73 -26
  42. package/dist/cjs/raw-builder/sql.js +9 -0
  43. package/dist/cjs/repository/repository-factory.d.ts +10 -42
  44. package/dist/cjs/repository/repository-factory.js +276 -394
  45. package/dist/cjs/schema/core/coordinators/schema-discovery.coordinator.js +6 -4
  46. package/dist/cjs/schema/core/factories/discovery-factory.js +5 -5
  47. package/dist/cjs/schema/core/utils/name-generator.js +34 -2
  48. package/dist/cjs/schema/core/utils/type-mapper.d.ts +19 -14
  49. package/dist/cjs/schema/core/utils/type-mapper.js +4 -7
  50. package/dist/cjs/schema/dialects/sqlite/discovery/sqlite-constraint-discovery.js +3 -2
  51. package/dist/cjs/schema/dialects/sqlite/sqlite-discovery.coordinator.d.ts +2 -0
  52. package/dist/cjs/schema/dialects/sqlite/sqlite-discovery.coordinator.js +19 -5
  53. package/dist/cjs/schema/test/dialect-capabilities.test.js +6 -0
  54. package/dist/cjs/schema/test/error-handling.test.js +52 -33
  55. package/dist/cjs/schema/test/integration.test.js +51 -5
  56. package/dist/cjs/schema/test/sqlite-discovery-coordinator.test.js +8 -4
  57. package/dist/cjs/sqlite-migration/index.js +35 -2
  58. package/dist/cjs/testing/test-utils.d.ts +5 -0
  59. package/dist/cjs/testing/test-utils.js +66 -6
  60. package/dist/cjs/types/index.d.ts +78 -13
  61. package/dist/cjs/types/index.js +23 -0
  62. package/dist/cjs/types/type-generator.d.ts +8 -0
  63. package/dist/cjs/types/type-generator.js +86 -17
  64. package/dist/cjs/util/safe-sql-helpers.d.ts +124 -0
  65. package/dist/cjs/util/safe-sql-helpers.js +221 -0
  66. package/dist/cjs/util/security-validator.d.ts +44 -0
  67. package/dist/cjs/util/security-validator.js +256 -0
  68. package/dist/cjs/util/security.d.ts +60 -0
  69. package/dist/cjs/util/security.js +137 -0
  70. package/dist/cjs/watch/schema-watcher.js +26 -7
  71. package/dist/esm/cli/commands/generate.js +10 -6
  72. package/dist/esm/cli/commands/init.js +15 -11
  73. package/dist/esm/cli/commands/inspect.js +6 -2
  74. package/dist/esm/cli/commands/status.js +3 -3
  75. package/dist/esm/dialect/database-introspector.js +16 -21
  76. package/dist/esm/dialect/sqlite/sqlite-introspector.js +13 -24
  77. package/dist/esm/dynamic/dynamic.d.ts +20 -0
  78. package/dist/esm/dynamic/dynamic.js +25 -0
  79. package/dist/esm/edge-runtime/edge-config.d.ts +125 -0
  80. package/dist/esm/edge-runtime/edge-config.js +281 -0
  81. package/dist/esm/errors/NoormError.d.ts +27 -4
  82. package/dist/esm/errors/NoormError.js +134 -18
  83. package/dist/esm/logging/logger.d.ts +7 -2
  84. package/dist/esm/logging/logger.js +21 -7
  85. package/dist/esm/noormme.d.ts +12 -8
  86. package/dist/esm/noormme.js +130 -61
  87. package/dist/esm/operation-node/column-node.js +4 -0
  88. package/dist/esm/operation-node/identifier-node.js +4 -0
  89. package/dist/esm/operation-node/table-node.js +7 -0
  90. package/dist/esm/parser/reference-parser.js +5 -0
  91. package/dist/esm/parser/table-parser.js +2 -0
  92. package/dist/esm/performance/index.d.ts +44 -0
  93. package/dist/esm/performance/index.js +48 -0
  94. package/dist/esm/performance/query-optimizer.d.ts +134 -0
  95. package/dist/esm/performance/query-optimizer.js +387 -0
  96. package/dist/esm/performance/services/cache-service.d.ts +177 -0
  97. package/dist/esm/performance/services/cache-service.js +410 -0
  98. package/dist/esm/performance/services/connection-factory.d.ts +198 -0
  99. package/dist/esm/performance/services/connection-factory.js +493 -0
  100. package/dist/esm/performance/services/metrics-collector.d.ts +162 -0
  101. package/dist/esm/performance/services/metrics-collector.js +402 -0
  102. package/dist/esm/performance/utils/query-parser.d.ts +123 -0
  103. package/dist/esm/performance/utils/query-parser.js +292 -0
  104. package/dist/esm/raw-builder/sql.d.ts +73 -26
  105. package/dist/esm/raw-builder/sql.js +9 -0
  106. package/dist/esm/repository/repository-factory.d.ts +10 -42
  107. package/dist/esm/repository/repository-factory.js +277 -395
  108. package/dist/esm/schema/core/coordinators/schema-discovery.coordinator.js +6 -4
  109. package/dist/esm/schema/core/factories/discovery-factory.js +5 -5
  110. package/dist/esm/schema/core/utils/name-generator.js +34 -2
  111. package/dist/esm/schema/core/utils/type-mapper.d.ts +19 -14
  112. package/dist/esm/schema/core/utils/type-mapper.js +4 -7
  113. package/dist/esm/schema/dialects/sqlite/discovery/sqlite-constraint-discovery.js +3 -2
  114. package/dist/esm/schema/dialects/sqlite/sqlite-discovery.coordinator.d.ts +2 -0
  115. package/dist/esm/schema/dialects/sqlite/sqlite-discovery.coordinator.js +19 -5
  116. package/dist/esm/schema/test/dialect-capabilities.test.js +6 -0
  117. package/dist/esm/schema/test/error-handling.test.js +52 -33
  118. package/dist/esm/schema/test/integration.test.js +18 -5
  119. package/dist/esm/schema/test/sqlite-discovery-coordinator.test.js +8 -4
  120. package/dist/esm/testing/test-utils.d.ts +5 -0
  121. package/dist/esm/testing/test-utils.js +66 -6
  122. package/dist/esm/types/index.d.ts +78 -13
  123. package/dist/esm/types/index.js +22 -1
  124. package/dist/esm/types/type-generator.d.ts +8 -0
  125. package/dist/esm/types/type-generator.js +86 -17
  126. package/dist/esm/util/safe-sql-helpers.d.ts +124 -0
  127. package/dist/esm/util/safe-sql-helpers.js +209 -0
  128. package/dist/esm/util/security-validator.d.ts +44 -0
  129. package/dist/esm/util/security-validator.js +246 -0
  130. package/dist/esm/util/security.d.ts +60 -0
  131. package/dist/esm/util/security.js +114 -0
  132. package/dist/esm/watch/schema-watcher.js +26 -7
  133. package/package.json +1 -1
  134. package/dist/cjs/performance/query-analyzer.d.ts +0 -89
  135. package/dist/cjs/performance/query-analyzer.js +0 -263
  136. package/dist/esm/performance/query-analyzer.d.ts +0 -89
  137. package/dist/esm/performance/query-analyzer.js +0 -260
@@ -0,0 +1,415 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryCacheService = exports.CacheService = void 0;
4
+ exports.createCacheService = createCacheService;
5
+ const logger_js_1 = require("../../logging/logger.js");
6
+ /**
7
+ * Generic cache service with TTL, size limits, and metrics
8
+ */
9
+ class CacheService {
10
+ cache = new Map();
11
+ config;
12
+ stats;
13
+ metrics;
14
+ cleanupTimer;
15
+ logger;
16
+ constructor(config = {}, logger) {
17
+ this.logger = logger || new logger_js_1.Logger('CacheService');
18
+ this.config = {
19
+ maxSize: 1000,
20
+ defaultTtl: 300000, // 5 minutes
21
+ cleanupInterval: 60000, // 1 minute
22
+ enableCompression: false,
23
+ enableMetrics: true,
24
+ ...config
25
+ };
26
+ this.stats = {
27
+ size: 0,
28
+ maxSize: this.config.maxSize,
29
+ hitCount: 0,
30
+ missCount: 0,
31
+ hitRate: 0,
32
+ totalSize: 0,
33
+ evictions: 0,
34
+ lastCleanup: new Date()
35
+ };
36
+ this.metrics = {
37
+ operations: {
38
+ get: 0,
39
+ set: 0,
40
+ delete: 0,
41
+ clear: 0
42
+ },
43
+ performance: {
44
+ averageGetTime: 0,
45
+ averageSetTime: 0,
46
+ slowestOperation: 0
47
+ },
48
+ memory: {
49
+ totalSize: 0,
50
+ averageEntrySize: 0,
51
+ largestEntry: 0
52
+ }
53
+ };
54
+ this.startCleanupTimer();
55
+ }
56
+ /**
57
+ * Get a value from cache
58
+ */
59
+ get(key) {
60
+ const startTime = performance.now();
61
+ try {
62
+ this.metrics.operations.get++;
63
+ const entry = this.cache.get(key);
64
+ if (!entry) {
65
+ this.stats.missCount++;
66
+ this.updateHitRate();
67
+ return null;
68
+ }
69
+ // Check if entry has expired
70
+ if (this.isExpired(entry)) {
71
+ this.cache.delete(key);
72
+ this.stats.missCount++;
73
+ this.updateHitRate();
74
+ this.updateStats();
75
+ return null;
76
+ }
77
+ // Update hit count and last access
78
+ entry.hitCount++;
79
+ this.stats.hitCount++;
80
+ this.updateHitRate();
81
+ const duration = performance.now() - startTime;
82
+ this.updatePerformanceMetrics('get', duration);
83
+ return entry.value;
84
+ }
85
+ catch (error) {
86
+ this.logger.error(`Cache get error for key ${key}:`, error);
87
+ return null;
88
+ }
89
+ }
90
+ /**
91
+ * Set a value in cache
92
+ */
93
+ set(key, value, ttl) {
94
+ const startTime = performance.now();
95
+ try {
96
+ this.metrics.operations.set++;
97
+ const entrySize = this.calculateSize(value);
98
+ const entryTtl = ttl || this.config.defaultTtl;
99
+ // Check if we need to evict entries
100
+ if (this.cache.size >= this.config.maxSize) {
101
+ this.evictEntries();
102
+ }
103
+ const entry = {
104
+ key,
105
+ value,
106
+ timestamp: Date.now(),
107
+ ttl: entryTtl,
108
+ hitCount: 0,
109
+ size: entrySize
110
+ };
111
+ this.cache.set(key, entry);
112
+ this.updateStats();
113
+ const duration = performance.now() - startTime;
114
+ this.updatePerformanceMetrics('set', duration);
115
+ return true;
116
+ }
117
+ catch (error) {
118
+ this.logger.error(`Cache set error for key ${key}:`, error);
119
+ return false;
120
+ }
121
+ }
122
+ /**
123
+ * Delete a value from cache
124
+ */
125
+ delete(key) {
126
+ try {
127
+ this.metrics.operations.delete++;
128
+ const deleted = this.cache.delete(key);
129
+ if (deleted) {
130
+ this.updateStats();
131
+ }
132
+ return deleted;
133
+ }
134
+ catch (error) {
135
+ this.logger.error(`Cache delete error for key ${key}:`, error);
136
+ return false;
137
+ }
138
+ }
139
+ /**
140
+ * Check if key exists in cache
141
+ */
142
+ has(key) {
143
+ const entry = this.cache.get(key);
144
+ if (!entry)
145
+ return false;
146
+ if (this.isExpired(entry)) {
147
+ this.cache.delete(key);
148
+ this.updateStats();
149
+ return false;
150
+ }
151
+ return true;
152
+ }
153
+ /**
154
+ * Clear all entries from cache
155
+ */
156
+ clear() {
157
+ try {
158
+ this.metrics.operations.clear++;
159
+ this.cache.clear();
160
+ this.updateStats();
161
+ this.logger.info('Cache cleared');
162
+ }
163
+ catch (error) {
164
+ this.logger.error('Cache clear error:', error);
165
+ }
166
+ }
167
+ /**
168
+ * Get cache statistics
169
+ */
170
+ getStats() {
171
+ return { ...this.stats };
172
+ }
173
+ /**
174
+ * Get detailed metrics
175
+ */
176
+ getMetrics() {
177
+ return { ...this.metrics };
178
+ }
179
+ /**
180
+ * Get cache size
181
+ */
182
+ size() {
183
+ return this.cache.size;
184
+ }
185
+ /**
186
+ * Get all cache keys
187
+ */
188
+ keys() {
189
+ return Array.from(this.cache.keys());
190
+ }
191
+ /**
192
+ * Get cache entries (for debugging)
193
+ */
194
+ entries() {
195
+ return Array.from(this.cache.entries()).map(([key, entry]) => ({ key, entry }));
196
+ }
197
+ /**
198
+ * Warm cache with multiple entries
199
+ */
200
+ warm(entries) {
201
+ let warmed = 0;
202
+ for (const { key, value, ttl } of entries) {
203
+ if (this.set(key, value, ttl)) {
204
+ warmed++;
205
+ }
206
+ }
207
+ this.logger.info(`Warmed cache with ${warmed}/${entries.length} entries`);
208
+ return warmed;
209
+ }
210
+ /**
211
+ * Get cache health status
212
+ */
213
+ getHealth() {
214
+ const issues = [];
215
+ const recommendations = [];
216
+ // Check hit rate
217
+ if (this.stats.hitRate < 0.5) {
218
+ issues.push(`Low hit rate: ${(this.stats.hitRate * 100).toFixed(1)}%`);
219
+ recommendations.push('Consider increasing TTL or cache size');
220
+ }
221
+ // Check memory usage
222
+ if (this.stats.totalSize > 100 * 1024 * 1024) { // 100MB
223
+ issues.push(`High memory usage: ${(this.stats.totalSize / 1024 / 1024).toFixed(1)}MB`);
224
+ recommendations.push('Consider reducing cache size or enabling compression');
225
+ }
226
+ // Check eviction rate
227
+ const evictionRate = this.stats.evictions / Math.max(this.stats.hitCount + this.stats.missCount, 1);
228
+ if (evictionRate > 0.1) {
229
+ issues.push(`High eviction rate: ${(evictionRate * 100).toFixed(1)}%`);
230
+ recommendations.push('Consider increasing cache size');
231
+ }
232
+ let status = 'healthy';
233
+ if (issues.length > 0) {
234
+ status = issues.some(issue => issue.includes('critical')) ? 'critical' : 'warning';
235
+ }
236
+ return { status, issues, recommendations };
237
+ }
238
+ /**
239
+ * Shutdown cache service
240
+ */
241
+ shutdown() {
242
+ if (this.cleanupTimer) {
243
+ clearInterval(this.cleanupTimer);
244
+ }
245
+ this.clear();
246
+ this.logger.info('Cache service shutdown');
247
+ }
248
+ /**
249
+ * Check if cache entry is expired
250
+ */
251
+ isExpired(entry) {
252
+ return Date.now() - entry.timestamp > entry.ttl;
253
+ }
254
+ /**
255
+ * Calculate size of a value (rough estimation)
256
+ */
257
+ calculateSize(value) {
258
+ try {
259
+ return JSON.stringify(value).length * 2; // Rough estimate in bytes
260
+ }
261
+ catch {
262
+ return 1024; // Default size if serialization fails
263
+ }
264
+ }
265
+ /**
266
+ * Evict entries when cache is full
267
+ */
268
+ evictEntries() {
269
+ const entries = Array.from(this.cache.entries());
270
+ // Sort by hit count and timestamp (LRU with hit count consideration)
271
+ entries.sort((a, b) => {
272
+ const [, entryA] = a;
273
+ const [, entryB] = b;
274
+ // Prefer entries with fewer hits
275
+ if (entryA.hitCount !== entryB.hitCount) {
276
+ return entryA.hitCount - entryB.hitCount;
277
+ }
278
+ // If hit counts are equal, prefer older entries
279
+ return entryA.timestamp - entryB.timestamp;
280
+ });
281
+ // Remove oldest/lowest hit count entries
282
+ const toRemove = Math.ceil(entries.length * 0.1); // Remove 10% of entries
283
+ for (let i = 0; i < toRemove && i < entries.length; i++) {
284
+ const [key] = entries[i];
285
+ this.cache.delete(key);
286
+ this.stats.evictions++;
287
+ }
288
+ }
289
+ /**
290
+ * Update cache statistics
291
+ */
292
+ updateStats() {
293
+ this.stats.size = this.cache.size;
294
+ let totalSize = 0;
295
+ let largestEntry = 0;
296
+ for (const entry of this.cache.values()) {
297
+ totalSize += entry.size;
298
+ largestEntry = Math.max(largestEntry, entry.size);
299
+ }
300
+ this.stats.totalSize = totalSize;
301
+ this.metrics.memory.totalSize = totalSize;
302
+ this.metrics.memory.largestEntry = largestEntry;
303
+ this.metrics.memory.averageEntrySize = this.cache.size > 0 ? totalSize / this.cache.size : 0;
304
+ }
305
+ /**
306
+ * Update hit rate
307
+ */
308
+ updateHitRate() {
309
+ const total = this.stats.hitCount + this.stats.missCount;
310
+ this.stats.hitRate = total > 0 ? this.stats.hitCount / total : 0;
311
+ }
312
+ /**
313
+ * Update performance metrics
314
+ */
315
+ updatePerformanceMetrics(operation, duration) {
316
+ if (!this.config.enableMetrics)
317
+ return;
318
+ this.metrics.performance.slowestOperation = Math.max(this.metrics.performance.slowestOperation, duration);
319
+ if (operation === 'get') {
320
+ const totalGets = this.metrics.operations.get;
321
+ this.metrics.performance.averageGetTime =
322
+ (this.metrics.performance.averageGetTime * (totalGets - 1) + duration) / totalGets;
323
+ }
324
+ else if (operation === 'set') {
325
+ const totalSets = this.metrics.operations.set;
326
+ this.metrics.performance.averageSetTime =
327
+ (this.metrics.performance.averageSetTime * (totalSets - 1) + duration) / totalSets;
328
+ }
329
+ }
330
+ /**
331
+ * Start cleanup timer
332
+ */
333
+ startCleanupTimer() {
334
+ this.cleanupTimer = setInterval(() => {
335
+ this.cleanup();
336
+ }, this.config.cleanupInterval);
337
+ }
338
+ /**
339
+ * Cleanup expired entries
340
+ */
341
+ cleanup() {
342
+ const now = Date.now();
343
+ let cleaned = 0;
344
+ for (const [key, entry] of this.cache.entries()) {
345
+ if (now - entry.timestamp > entry.ttl) {
346
+ this.cache.delete(key);
347
+ cleaned++;
348
+ }
349
+ }
350
+ if (cleaned > 0) {
351
+ this.stats.lastCleanup = new Date();
352
+ this.updateStats();
353
+ this.logger.debug(`Cleaned up ${cleaned} expired cache entries`);
354
+ }
355
+ }
356
+ }
357
+ exports.CacheService = CacheService;
358
+ /**
359
+ * Factory function to create cache service
360
+ */
361
+ function createCacheService(config, logger) {
362
+ return new CacheService(config, logger);
363
+ }
364
+ /**
365
+ * Specialized query cache service
366
+ */
367
+ class QueryCacheService extends CacheService {
368
+ constructor(config, logger) {
369
+ super({
370
+ maxSize: 1000,
371
+ defaultTtl: 300000, // 5 minutes
372
+ cleanupInterval: 60000, // 1 minute
373
+ enableMetrics: true,
374
+ ...config
375
+ }, logger);
376
+ }
377
+ /**
378
+ * Cache query result with automatic key generation
379
+ */
380
+ cacheQuery(query, params, result, ttl) {
381
+ const key = this.generateQueryKey(query, params);
382
+ return this.set(key, result, ttl);
383
+ }
384
+ /**
385
+ * Get cached query result
386
+ */
387
+ getCachedQuery(query, params) {
388
+ const key = this.generateQueryKey(query, params);
389
+ return this.get(key);
390
+ }
391
+ /**
392
+ * Generate cache key for query
393
+ */
394
+ generateQueryKey(query, params) {
395
+ const normalizedQuery = query.replace(/\s+/g, ' ').trim();
396
+ const paramsKey = params.map(p => String(p)).join('|');
397
+ return `query:${normalizedQuery}:${paramsKey}`;
398
+ }
399
+ /**
400
+ * Invalidate cache entries for a specific table
401
+ */
402
+ invalidateTable(table) {
403
+ let invalidated = 0;
404
+ for (const key of this.keys()) {
405
+ if (key.includes(`FROM ${table}`) || key.includes(`JOIN ${table}`)) {
406
+ if (this.delete(key)) {
407
+ invalidated++;
408
+ }
409
+ }
410
+ }
411
+ this.logger?.info(`Invalidated ${invalidated} cache entries for table ${table}`);
412
+ return invalidated;
413
+ }
414
+ }
415
+ exports.QueryCacheService = QueryCacheService;
@@ -0,0 +1,198 @@
1
+ import { NOORMME } from '../../noormme';
2
+ import { NOORMConfig } from '../../types';
3
+ import { Logger } from '../../logging/logger.js';
4
+ export interface ConnectionConfig extends NOORMConfig {
5
+ id?: string;
6
+ maxRetries?: number;
7
+ retryDelay?: number;
8
+ validationTimeout?: number;
9
+ }
10
+ export interface PooledConnection {
11
+ id: string;
12
+ db: NOORMME;
13
+ createdAt: Date;
14
+ lastUsed: Date;
15
+ isActive: boolean;
16
+ inUse: boolean;
17
+ config: ConnectionConfig;
18
+ }
19
+ export interface ConnectionValidationResult {
20
+ isValid: boolean;
21
+ error?: string;
22
+ responseTime?: number;
23
+ }
24
+ export interface ConnectionStats {
25
+ totalCreated: number;
26
+ totalDestroyed: number;
27
+ activeConnections: number;
28
+ failedCreations: number;
29
+ averageCreationTime: number;
30
+ averageValidationTime: number;
31
+ }
32
+ /**
33
+ * Factory for creating and managing database connections
34
+ */
35
+ export declare class ConnectionFactory {
36
+ private connections;
37
+ private stats;
38
+ private logger;
39
+ constructor(logger?: Logger);
40
+ /**
41
+ * Create a new database connection
42
+ */
43
+ createConnection(config: ConnectionConfig): Promise<PooledConnection>;
44
+ /**
45
+ * Validate a connection
46
+ */
47
+ validateConnection(connection: PooledConnection): Promise<ConnectionValidationResult>;
48
+ /**
49
+ * Get connection by ID
50
+ */
51
+ getConnection(id: string): PooledConnection | null;
52
+ /**
53
+ * Get all connections
54
+ */
55
+ getAllConnections(): PooledConnection[];
56
+ /**
57
+ * Get active connections
58
+ */
59
+ getActiveConnections(): PooledConnection[];
60
+ /**
61
+ * Get idle connections
62
+ */
63
+ getIdleConnections(): PooledConnection[];
64
+ /**
65
+ * Mark connection as in use
66
+ */
67
+ markInUse(connection: PooledConnection): void;
68
+ /**
69
+ * Mark connection as idle
70
+ */
71
+ markIdle(connection: PooledConnection): void;
72
+ /**
73
+ * Destroy a connection
74
+ */
75
+ destroyConnection(id: string): Promise<boolean>;
76
+ /**
77
+ * Destroy all connections
78
+ */
79
+ destroyAllConnections(): Promise<void>;
80
+ /**
81
+ * Cleanup inactive connections
82
+ */
83
+ cleanupInactiveConnections(maxAge?: number): Promise<number>;
84
+ /**
85
+ * Validate all connections
86
+ */
87
+ validateAllConnections(): Promise<Array<{
88
+ id: string;
89
+ isValid: boolean;
90
+ error?: string;
91
+ responseTime?: number;
92
+ }>>;
93
+ /**
94
+ * Get connection statistics
95
+ */
96
+ getStats(): ConnectionStats;
97
+ /**
98
+ * Get connection health status
99
+ */
100
+ getHealthStatus(): Promise<{
101
+ status: 'healthy' | 'warning' | 'critical';
102
+ issues: string[];
103
+ connections: {
104
+ total: number;
105
+ active: number;
106
+ idle: number;
107
+ inUse: number;
108
+ };
109
+ }>;
110
+ /**
111
+ * Generate unique connection ID
112
+ */
113
+ private generateConnectionId;
114
+ /**
115
+ * Update statistics
116
+ */
117
+ private updateStats;
118
+ /**
119
+ * Update average time for operations
120
+ */
121
+ private updateAverageTime;
122
+ }
123
+ /**
124
+ * Connection pool manager using the factory
125
+ */
126
+ export declare class ConnectionPoolManager {
127
+ private factory;
128
+ private config;
129
+ private poolConfig;
130
+ private waitingQueue;
131
+ private validationTimer?;
132
+ private isShuttingDown;
133
+ private logger;
134
+ constructor(config: ConnectionConfig, poolConfig?: Partial<ConnectionPoolManager['poolConfig']>, logger?: Logger);
135
+ /**
136
+ * Initialize the connection pool
137
+ */
138
+ initialize(): Promise<void>;
139
+ /**
140
+ * Acquire a connection from the pool
141
+ */
142
+ acquire(): Promise<PooledConnection>;
143
+ /**
144
+ * Release a connection back to the pool
145
+ */
146
+ release(connection: PooledConnection): Promise<void>;
147
+ /**
148
+ * Execute a function with a pooled connection
149
+ */
150
+ withConnection<T>(fn: (db: NOORMME) => Promise<T>): Promise<T>;
151
+ /**
152
+ * Get pool statistics
153
+ */
154
+ getStats(): {
155
+ poolSize: number;
156
+ idleConnections: number;
157
+ inUseConnections: number;
158
+ waitingQueue: number;
159
+ totalCreated: number;
160
+ totalDestroyed: number;
161
+ activeConnections: number;
162
+ failedCreations: number;
163
+ averageCreationTime: number;
164
+ averageValidationTime: number;
165
+ };
166
+ /**
167
+ * Shutdown the connection pool
168
+ */
169
+ shutdown(): Promise<void>;
170
+ /**
171
+ * Get idle connection from pool
172
+ */
173
+ private getIdleConnection;
174
+ /**
175
+ * Wait for a connection to become available
176
+ */
177
+ private waitForConnection;
178
+ /**
179
+ * Process waiting queue when connections become available
180
+ */
181
+ private processWaitingQueue;
182
+ /**
183
+ * Start validation timer
184
+ */
185
+ private startValidationTimer;
186
+ /**
187
+ * Validate all connections in the pool
188
+ */
189
+ private validateConnections;
190
+ /**
191
+ * Cleanup idle connections that exceed the idle timeout
192
+ */
193
+ private cleanupIdleConnections;
194
+ }
195
+ /**
196
+ * Factory function to create connection pool manager
197
+ */
198
+ export declare function createConnectionPool(config: ConnectionConfig, poolConfig?: Partial<ConnectionPoolManager['poolConfig']>, logger?: Logger): ConnectionPoolManager;