@omnitron-dev/titan-database 0.1.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.
Files changed (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +27 -0
  3. package/dist/database.constants.d.ts +32 -0
  4. package/dist/database.constants.d.ts.map +1 -0
  5. package/dist/database.constants.js +37 -0
  6. package/dist/database.constants.js.map +1 -0
  7. package/dist/database.decorators.d.ts +86 -0
  8. package/dist/database.decorators.d.ts.map +1 -0
  9. package/dist/database.decorators.js +239 -0
  10. package/dist/database.decorators.js.map +1 -0
  11. package/dist/database.health.d.ts +22 -0
  12. package/dist/database.health.d.ts.map +1 -0
  13. package/dist/database.health.js +140 -0
  14. package/dist/database.health.js.map +1 -0
  15. package/dist/database.internal-types.d.ts +83 -0
  16. package/dist/database.internal-types.d.ts.map +1 -0
  17. package/dist/database.internal-types.js +38 -0
  18. package/dist/database.internal-types.js.map +1 -0
  19. package/dist/database.manager.d.ts +97 -0
  20. package/dist/database.manager.d.ts.map +1 -0
  21. package/dist/database.manager.js +833 -0
  22. package/dist/database.manager.js.map +1 -0
  23. package/dist/database.module.d.ts +15 -0
  24. package/dist/database.module.d.ts.map +1 -0
  25. package/dist/database.module.js +195 -0
  26. package/dist/database.module.js.map +1 -0
  27. package/dist/database.types.d.ts +326 -0
  28. package/dist/database.types.d.ts.map +1 -0
  29. package/dist/database.types.js +15 -0
  30. package/dist/database.types.js.map +1 -0
  31. package/dist/exports/dialects.d.ts +2 -0
  32. package/dist/exports/dialects.d.ts.map +1 -0
  33. package/dist/exports/dialects.js +2 -0
  34. package/dist/exports/dialects.js.map +1 -0
  35. package/dist/exports/kysera.d.ts +16 -0
  36. package/dist/exports/kysera.d.ts.map +1 -0
  37. package/dist/exports/kysera.js +9 -0
  38. package/dist/exports/kysera.js.map +1 -0
  39. package/dist/exports/migration.d.ts +4 -0
  40. package/dist/exports/migration.d.ts.map +1 -0
  41. package/dist/exports/migration.js +2 -0
  42. package/dist/exports/migration.js.map +1 -0
  43. package/dist/exports/plugins.d.ts +9 -0
  44. package/dist/exports/plugins.d.ts.map +1 -0
  45. package/dist/exports/plugins.js +5 -0
  46. package/dist/exports/plugins.js.map +1 -0
  47. package/dist/exports/repository.d.ts +3 -0
  48. package/dist/exports/repository.d.ts.map +1 -0
  49. package/dist/exports/repository.js +2 -0
  50. package/dist/exports/repository.js.map +1 -0
  51. package/dist/exports/rls.d.ts +10 -0
  52. package/dist/exports/rls.d.ts.map +1 -0
  53. package/dist/exports/rls.js +6 -0
  54. package/dist/exports/rls.js.map +1 -0
  55. package/dist/exports/transaction.d.ts +3 -0
  56. package/dist/exports/transaction.d.ts.map +1 -0
  57. package/dist/exports/transaction.js +2 -0
  58. package/dist/exports/transaction.js.map +1 -0
  59. package/dist/index.d.ts +41 -0
  60. package/dist/index.d.ts.map +1 -0
  61. package/dist/index.js +26 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/plugins/sqlite-date-serializer.plugin.d.ts +9 -0
  64. package/dist/plugins/sqlite-date-serializer.plugin.d.ts.map +1 -0
  65. package/dist/plugins/sqlite-date-serializer.plugin.js +61 -0
  66. package/dist/plugins/sqlite-date-serializer.plugin.js.map +1 -0
  67. package/dist/repository/transaction-aware.repository.d.ts +90 -0
  68. package/dist/repository/transaction-aware.repository.d.ts.map +1 -0
  69. package/dist/repository/transaction-aware.repository.js +210 -0
  70. package/dist/repository/transaction-aware.repository.js.map +1 -0
  71. package/dist/transaction/transaction.context.d.ts +31 -0
  72. package/dist/transaction/transaction.context.d.ts.map +1 -0
  73. package/dist/transaction/transaction.context.js +81 -0
  74. package/dist/transaction/transaction.context.js.map +1 -0
  75. package/dist/utils/type-guards.d.ts +29 -0
  76. package/dist/utils/type-guards.d.ts.map +1 -0
  77. package/dist/utils/type-guards.js +75 -0
  78. package/dist/utils/type-guards.js.map +1 -0
  79. package/dist/uuid-v7.d.ts +5 -0
  80. package/dist/uuid-v7.d.ts.map +1 -0
  81. package/dist/uuid-v7.js +22 -0
  82. package/dist/uuid-v7.js.map +1 -0
  83. package/package.json +92 -0
@@ -0,0 +1,833 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { Kysely, PostgresDialect, MysqlDialect, SqliteDialect, CamelCasePlugin, sql } from 'kysely';
11
+ import { Pool } from 'pg';
12
+ import * as mysql from 'mysql2';
13
+ import BetterSqlite3 from 'better-sqlite3';
14
+ import { sqliteDateSerializerPlugin } from './plugins/sqlite-date-serializer.plugin.js';
15
+ import { createExecutor, isKyseraExecutor, getPlugins, getRawDb, } from '@kysera/executor';
16
+ import { CircuitBreaker } from '@kysera/infra';
17
+ import { Injectable } from '@omnitron-dev/titan/decorators';
18
+ import { Errors, TitanError, ErrorCode } from '@omnitron-dev/titan/errors';
19
+ import { DATABASE_DEFAULT_CONNECTION, DEFAULT_POOL_CONFIG, DEFAULT_TIMEOUTS, } from './database.constants.js';
20
+ const ERROR_MESSAGES = {
21
+ CONNECTION_FAILED: (name, error) => `Failed to connect to database "${name}": ${error}`,
22
+ INVALID_DIALECT: (dialect) => `Invalid database dialect: ${dialect}`,
23
+ };
24
+ const DIALECT_SETTINGS = {
25
+ postgres: { defaultPort: 5432 },
26
+ mysql: { defaultPort: 3306 },
27
+ sqlite: { defaultPort: null },
28
+ mssql: { defaultPort: 1433 },
29
+ };
30
+ const DATABASE_EVENTS = {
31
+ CONNECTED: 'database.connected',
32
+ DISCONNECTED: 'database.disconnected',
33
+ ERROR: 'database.error',
34
+ };
35
+ import { EventEmitter } from '@omnitron-dev/eventemitter';
36
+ let DatabaseManager = class DatabaseManager {
37
+ constructor(options, logger) {
38
+ this.connections = new Map();
39
+ this.circuitBreakers = new Map();
40
+ this.connectionSchemas = new Map();
41
+ this.eventEmitter = new EventEmitter();
42
+ this.shutdownInProgress = false;
43
+ this.initialized = false;
44
+ this.defaultRetryConfig = {
45
+ maxRetries: 5,
46
+ baseDelayMs: 1000,
47
+ maxDelayMs: 16000,
48
+ timeoutMs: 30000,
49
+ };
50
+ this.healthCheckIntervalMs = 30000;
51
+ this.healthCheckFailures = new Map();
52
+ this.maxHealthCheckFailures = 3;
53
+ this.options = options || {};
54
+ this.logger = logger.child({ module: 'DatabaseManager' });
55
+ }
56
+ async init() {
57
+ if (this.initialized) {
58
+ this.logger.debug('Database manager already initialized, skipping');
59
+ return;
60
+ }
61
+ this.logger.info('Initializing database manager');
62
+ const connections = this.getConnectionConfigs();
63
+ for (const [name, config] of Object.entries(connections)) {
64
+ await this.createConnectionWithRetry(name, config);
65
+ }
66
+ this.initialized = true;
67
+ if (this.options.defaultSchema) {
68
+ for (const [name, info] of this.connections) {
69
+ if (info.config.dialect === 'postgres' && info.connected) {
70
+ try {
71
+ await this.setSchema(this.options.defaultSchema, name);
72
+ }
73
+ catch (error) {
74
+ this.logger.warn({ connection: name, schema: this.options.defaultSchema, error }, 'Failed to set default schema');
75
+ }
76
+ }
77
+ }
78
+ }
79
+ if (this.options.healthCheck !== false) {
80
+ this.startProactiveHealthChecks();
81
+ }
82
+ this.logger.info({ connectionCount: this.connections.size }, 'Database manager initialized');
83
+ }
84
+ startProactiveHealthChecks() {
85
+ if (this.healthCheckTimer) {
86
+ return;
87
+ }
88
+ this.logger.info({ intervalMs: this.healthCheckIntervalMs }, 'Starting proactive health checks');
89
+ this.healthCheckTimer = setInterval(async () => {
90
+ await this.runHealthChecks();
91
+ }, this.healthCheckIntervalMs);
92
+ if (this.healthCheckTimer.unref) {
93
+ this.healthCheckTimer.unref();
94
+ }
95
+ }
96
+ stopProactiveHealthChecks() {
97
+ if (this.healthCheckTimer) {
98
+ clearInterval(this.healthCheckTimer);
99
+ this.healthCheckTimer = undefined;
100
+ this.logger.debug('Proactive health checks stopped');
101
+ }
102
+ }
103
+ async runHealthChecks() {
104
+ const healthCheckPromises = [];
105
+ for (const [name, info] of this.connections) {
106
+ if (!info.connected) {
107
+ continue;
108
+ }
109
+ healthCheckPromises.push(this.runSingleHealthCheck(name, info));
110
+ }
111
+ await Promise.all(healthCheckPromises);
112
+ }
113
+ async runSingleHealthCheck(name, info) {
114
+ try {
115
+ const startTime = Date.now();
116
+ const isHealthy = await this.validateConnectionHealth(info.instance, info.config.dialect);
117
+ const latency = Date.now() - startTime;
118
+ if (isHealthy) {
119
+ this.healthCheckFailures.set(name, 0);
120
+ if (latency > 500) {
121
+ this.logger.warn({ connection: name, latency }, 'Connection health check passed but with high latency');
122
+ }
123
+ }
124
+ else {
125
+ await this.handleHealthCheckFailure(name, info, new Error('Health check returned false'));
126
+ }
127
+ }
128
+ catch (error) {
129
+ await this.handleHealthCheckFailure(name, info, error);
130
+ }
131
+ }
132
+ async handleHealthCheckFailure(name, info, error) {
133
+ const failures = (this.healthCheckFailures.get(name) || 0) + 1;
134
+ this.healthCheckFailures.set(name, failures);
135
+ this.logger.warn({ connection: name, failures, maxFailures: this.maxHealthCheckFailures, error: error.message }, 'Connection health check failed');
136
+ info.poolMetrics.errorCount++;
137
+ info.poolMetrics.lastError = error;
138
+ this.emitEvent({
139
+ type: DATABASE_EVENTS.ERROR,
140
+ connection: name,
141
+ timestamp: new Date(),
142
+ error,
143
+ });
144
+ if (failures >= this.maxHealthCheckFailures) {
145
+ this.logger.error({ connection: name, failures }, 'Connection failed health checks, attempting reconnection');
146
+ try {
147
+ info.connected = false;
148
+ await this.reconnect(name);
149
+ this.healthCheckFailures.set(name, 0);
150
+ this.logger.info({ connection: name }, 'Connection recovered after health check failures');
151
+ }
152
+ catch (reconnectError) {
153
+ this.logger.error({ connection: name, error: reconnectError.message }, 'Failed to recover connection');
154
+ }
155
+ }
156
+ }
157
+ async checkConnectionHealth(name = DATABASE_DEFAULT_CONNECTION) {
158
+ const info = this.connections.get(name);
159
+ if (!info) {
160
+ return { healthy: false, error: `Connection '${name}' not found` };
161
+ }
162
+ if (!info.connected) {
163
+ return { healthy: false, error: 'Connection not established' };
164
+ }
165
+ try {
166
+ const startTime = Date.now();
167
+ const isHealthy = await this.validateConnectionHealth(info.instance, info.config.dialect);
168
+ const latency = Date.now() - startTime;
169
+ return { healthy: isHealthy, latency };
170
+ }
171
+ catch (error) {
172
+ return { healthy: false, error: error.message };
173
+ }
174
+ }
175
+ getHealthStatus() {
176
+ const status = new Map();
177
+ for (const [name, info] of this.connections) {
178
+ status.set(name, {
179
+ connected: info.connected,
180
+ consecutiveFailures: this.healthCheckFailures.get(name) || 0,
181
+ lastError: info.lastError?.message,
182
+ poolMetrics: this.collectPoolMetrics(info),
183
+ });
184
+ }
185
+ return status;
186
+ }
187
+ getConnectionConfigs() {
188
+ const configs = {};
189
+ if (this.options.connection) {
190
+ configs[DATABASE_DEFAULT_CONNECTION] = {
191
+ ...this.options.connection,
192
+ name: DATABASE_DEFAULT_CONNECTION,
193
+ };
194
+ }
195
+ if (this.options.connections) {
196
+ for (const [name, config] of Object.entries(this.options.connections)) {
197
+ configs[name] = { ...config, name };
198
+ }
199
+ }
200
+ if (Object.keys(configs).length === 0) {
201
+ configs[DATABASE_DEFAULT_CONNECTION] = {
202
+ name: DATABASE_DEFAULT_CONNECTION,
203
+ dialect: 'sqlite',
204
+ connection: ':memory:',
205
+ };
206
+ }
207
+ return configs;
208
+ }
209
+ async createConnectionWithRetry(name, config) {
210
+ const retryConfig = this.defaultRetryConfig;
211
+ let lastError;
212
+ for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
213
+ try {
214
+ this.logger.debug({ name, attempt, maxRetries: retryConfig.maxRetries }, 'Attempting database connection');
215
+ const info = await this.createConnection(name, config);
216
+ if (attempt > 0) {
217
+ this.logger.info({ name, attempt, totalRetries: attempt }, 'Database connection established after retries');
218
+ }
219
+ return info;
220
+ }
221
+ catch (error) {
222
+ lastError = error;
223
+ const isLastAttempt = attempt === retryConfig.maxRetries;
224
+ if (isLastAttempt) {
225
+ this.logger.error({ name, attempt, error: lastError }, 'Database connection failed after all retries');
226
+ break;
227
+ }
228
+ const delayMs = Math.min(retryConfig.baseDelayMs * Math.pow(2, attempt), retryConfig.maxDelayMs);
229
+ this.logger.warn({ name, attempt, nextRetryIn: delayMs, error: lastError.message }, 'Database connection failed, retrying');
230
+ await this.sleep(delayMs);
231
+ }
232
+ }
233
+ throw new TitanError({
234
+ code: ErrorCode.SERVICE_UNAVAILABLE,
235
+ message: `Database connection ${name} failed after ${retryConfig.maxRetries} retries: ${lastError?.message}`,
236
+ details: { connection: name, error: lastError?.message, maxRetries: retryConfig.maxRetries },
237
+ });
238
+ }
239
+ async createConnection(name, config) {
240
+ this.logger.debug({ name, dialect: config.dialect }, 'Creating database connection');
241
+ const poolConfig = config.pool || {};
242
+ const info = {
243
+ name,
244
+ config,
245
+ instance: null,
246
+ pool: undefined,
247
+ connected: false,
248
+ connecting: true,
249
+ retryCount: 0,
250
+ metrics: {
251
+ queryCount: 0,
252
+ errorCount: 0,
253
+ totalQueryTime: 0,
254
+ },
255
+ poolMetrics: {
256
+ totalConnections: 0,
257
+ idleConnections: 0,
258
+ activeConnections: 0,
259
+ waitingClients: 0,
260
+ acquireCount: 0,
261
+ releaseCount: 0,
262
+ errorCount: 0,
263
+ averageAcquireTimeMs: 0,
264
+ totalAcquireTimeMs: 0,
265
+ poolSize: {
266
+ min: poolConfig.min ?? DEFAULT_POOL_CONFIG.min,
267
+ max: poolConfig.max ?? DEFAULT_POOL_CONFIG.max,
268
+ },
269
+ },
270
+ };
271
+ try {
272
+ const { instance, pool } = await this.createKyselyInstance(config);
273
+ info.instance = instance;
274
+ info.pool = pool;
275
+ await this.testConnection(instance, config.dialect);
276
+ const isHealthy = await this.validateConnectionHealth(instance, config.dialect);
277
+ if (!isHealthy) {
278
+ throw Errors.unavailable('Database', 'Connection health check failed');
279
+ }
280
+ info.connected = true;
281
+ info.connecting = false;
282
+ this.connections.set(name, info);
283
+ const cbOptions = this.options.circuitBreaker;
284
+ if (cbOptions?.enabled !== false) {
285
+ const breaker = new CircuitBreaker({
286
+ threshold: cbOptions?.threshold ?? 5,
287
+ resetTimeMs: cbOptions?.resetTimeMs ?? 60000,
288
+ onStateChange: (newState, previousState) => {
289
+ this.logger.warn({ connection: name, newState, previousState }, 'Circuit breaker state changed');
290
+ },
291
+ });
292
+ this.circuitBreakers.set(name, breaker);
293
+ }
294
+ this.emitEvent({
295
+ type: DATABASE_EVENTS.CONNECTED,
296
+ connection: name,
297
+ timestamp: new Date(),
298
+ });
299
+ this.logger.info({ name, dialect: config.dialect }, 'Database connection established');
300
+ return info;
301
+ }
302
+ catch (error) {
303
+ info.connecting = false;
304
+ info.lastError = error;
305
+ this.connections.set(name, info);
306
+ const errorMessage = ERROR_MESSAGES.CONNECTION_FAILED(name, error.message);
307
+ this.logger.error({ name, error }, errorMessage);
308
+ this.emitEvent({
309
+ type: DATABASE_EVENTS.ERROR,
310
+ connection: name,
311
+ timestamp: new Date(),
312
+ error: error,
313
+ });
314
+ throw new TitanError({
315
+ code: ErrorCode.SERVICE_UNAVAILABLE,
316
+ message: `Database connection ${name} is unavailable: ${errorMessage}`,
317
+ details: { connection: name, error: errorMessage },
318
+ });
319
+ }
320
+ }
321
+ async createKyselyInstance(config) {
322
+ const connectionConfig = this.parseConnectionConfig(config);
323
+ switch (config.dialect) {
324
+ case 'postgres': {
325
+ const pgConfig = { ...connectionConfig };
326
+ if (pgConfig['ssl'] === false) {
327
+ delete pgConfig['ssl'];
328
+ }
329
+ const pool = new Pool({
330
+ ...pgConfig,
331
+ ...DEFAULT_POOL_CONFIG,
332
+ ...config.pool,
333
+ });
334
+ pool.on('error', (err, client) => {
335
+ this.logger.error({ error: err, client: client ? 'present' : 'none' }, 'PostgreSQL pool error');
336
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
337
+ if (connInfo) {
338
+ connInfo.poolMetrics.errorCount++;
339
+ connInfo.poolMetrics.lastError = err;
340
+ }
341
+ this.emitEvent({
342
+ type: DATABASE_EVENTS.ERROR,
343
+ connection: config.name || DATABASE_DEFAULT_CONNECTION,
344
+ timestamp: new Date(),
345
+ error: err,
346
+ });
347
+ });
348
+ pool.on('connect', (_client) => {
349
+ this.logger.debug('PostgreSQL pool client connected');
350
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
351
+ if (connInfo) {
352
+ connInfo.poolMetrics.totalConnections++;
353
+ connInfo.poolMetrics.idleConnections++;
354
+ }
355
+ });
356
+ pool.on('acquire', (_client) => {
357
+ this.logger.debug('PostgreSQL pool client acquired');
358
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
359
+ if (connInfo) {
360
+ connInfo.poolMetrics.acquireCount++;
361
+ connInfo.poolMetrics.activeConnections++;
362
+ connInfo.poolMetrics.idleConnections = Math.max(0, connInfo.poolMetrics.idleConnections - 1);
363
+ connInfo.poolMetrics.lastAcquireAt = new Date();
364
+ }
365
+ });
366
+ pool.on('release', (_client) => {
367
+ this.logger.debug('PostgreSQL pool client released');
368
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
369
+ if (connInfo) {
370
+ connInfo.poolMetrics.releaseCount++;
371
+ connInfo.poolMetrics.activeConnections = Math.max(0, connInfo.poolMetrics.activeConnections - 1);
372
+ connInfo.poolMetrics.idleConnections++;
373
+ }
374
+ });
375
+ pool.on('remove', (_client) => {
376
+ this.logger.debug('PostgreSQL pool client removed');
377
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
378
+ if (connInfo) {
379
+ connInfo.poolMetrics.totalConnections = Math.max(0, connInfo.poolMetrics.totalConnections - 1);
380
+ connInfo.poolMetrics.idleConnections = Math.max(0, connInfo.poolMetrics.idleConnections - 1);
381
+ }
382
+ });
383
+ const dialect = new PostgresDialect({ pool });
384
+ const kyselyPlugins = this.options.camelCase ? [new CamelCasePlugin()] : [];
385
+ const instance = new Kysely({
386
+ dialect,
387
+ log: config.debug ? ['query', 'error'] : undefined,
388
+ plugins: kyselyPlugins,
389
+ });
390
+ return { instance, pool };
391
+ }
392
+ case 'mysql': {
393
+ const mysqlConfig = { ...connectionConfig };
394
+ if (mysqlConfig['ssl'] === false) {
395
+ delete mysqlConfig['ssl'];
396
+ }
397
+ const mysqlPoolConfig = {
398
+ connectionLimit: config.pool?.max || DEFAULT_POOL_CONFIG.max,
399
+ waitForConnections: true,
400
+ queueLimit: 0,
401
+ connectTimeout: DEFAULT_POOL_CONFIG.acquireTimeoutMillis,
402
+ };
403
+ const pool = mysql.createPool({
404
+ ...mysqlConfig,
405
+ ...mysqlPoolConfig,
406
+ });
407
+ pool.on('error', (err) => {
408
+ this.logger.error({ error: err }, 'MySQL pool error');
409
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
410
+ if (connInfo) {
411
+ connInfo.poolMetrics.errorCount++;
412
+ connInfo.poolMetrics.lastError = err;
413
+ }
414
+ this.emitEvent({
415
+ type: DATABASE_EVENTS.ERROR,
416
+ connection: config.name || DATABASE_DEFAULT_CONNECTION,
417
+ timestamp: new Date(),
418
+ error: err,
419
+ });
420
+ });
421
+ pool.on('connection', (_connection) => {
422
+ this.logger.debug('MySQL pool connection established');
423
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
424
+ if (connInfo) {
425
+ connInfo.poolMetrics.totalConnections++;
426
+ connInfo.poolMetrics.idleConnections++;
427
+ }
428
+ });
429
+ pool.on('acquire', (_connection) => {
430
+ this.logger.debug('MySQL pool connection acquired');
431
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
432
+ if (connInfo) {
433
+ connInfo.poolMetrics.acquireCount++;
434
+ connInfo.poolMetrics.activeConnections++;
435
+ connInfo.poolMetrics.idleConnections = Math.max(0, connInfo.poolMetrics.idleConnections - 1);
436
+ connInfo.poolMetrics.lastAcquireAt = new Date();
437
+ }
438
+ });
439
+ pool.on('release', (_connection) => {
440
+ this.logger.debug('MySQL pool connection released');
441
+ const connInfo = this.connections.get(config.name || DATABASE_DEFAULT_CONNECTION);
442
+ if (connInfo) {
443
+ connInfo.poolMetrics.releaseCount++;
444
+ connInfo.poolMetrics.activeConnections = Math.max(0, connInfo.poolMetrics.activeConnections - 1);
445
+ connInfo.poolMetrics.idleConnections++;
446
+ }
447
+ });
448
+ const dialect = new MysqlDialect({ pool });
449
+ const mysqlPlugins = this.options.camelCase ? [new CamelCasePlugin()] : [];
450
+ const instance = new Kysely({
451
+ dialect,
452
+ log: config.debug ? ['query', 'error'] : undefined,
453
+ plugins: mysqlPlugins,
454
+ });
455
+ return { instance, pool };
456
+ }
457
+ case 'sqlite': {
458
+ const database = new BetterSqlite3(connectionConfig.database || ':memory:', {
459
+ verbose: config.debug ? (msg) => this.logger.debug({ msg }, 'SQLite verbose') : undefined,
460
+ timeout: 5000,
461
+ });
462
+ const isInMemory = !connectionConfig.database ||
463
+ connectionConfig.database === ':memory:' ||
464
+ connectionConfig.database.includes('mode=memory') ||
465
+ connectionConfig.database.includes(':memory:');
466
+ if (!isInMemory) {
467
+ database.pragma('journal_mode = WAL');
468
+ }
469
+ database.pragma('busy_timeout = 5000');
470
+ const dialect = new SqliteDialect({ database });
471
+ const sqlitePlugins = [sqliteDateSerializerPlugin()];
472
+ if (this.options.camelCase) {
473
+ sqlitePlugins.push(new CamelCasePlugin());
474
+ }
475
+ const instance = new Kysely({
476
+ dialect,
477
+ log: config.debug ? ['query', 'error'] : undefined,
478
+ plugins: sqlitePlugins,
479
+ });
480
+ return { instance, pool: database };
481
+ }
482
+ default:
483
+ throw Errors.badRequest(ERROR_MESSAGES.INVALID_DIALECT(config.dialect));
484
+ }
485
+ }
486
+ parseConnectionConfig(config) {
487
+ if (!config) {
488
+ throw Errors.badRequest('Database connection configuration is required');
489
+ }
490
+ if (typeof config.connection === 'string') {
491
+ if (config.dialect === 'sqlite') {
492
+ return { database: config.connection };
493
+ }
494
+ const url = new URL(config.connection);
495
+ const sslParam = url.searchParams.get('ssl');
496
+ const result = {
497
+ host: url.hostname,
498
+ port: parseInt(url.port) || DIALECT_SETTINGS[config.dialect]?.defaultPort || undefined,
499
+ database: url.pathname.slice(1),
500
+ user: url.username,
501
+ password: url.password,
502
+ };
503
+ if (sslParam === 'true') {
504
+ result.ssl = true;
505
+ }
506
+ return result;
507
+ }
508
+ const connConfig = config.connection;
509
+ if (!connConfig) {
510
+ if (config.dialect === 'sqlite') {
511
+ return { database: ':memory:' };
512
+ }
513
+ const configKeys = Object.keys(config).join(', ');
514
+ throw Errors.badRequest(`Connection configuration is required for ${config.dialect || 'undefined'}. ` +
515
+ `Received config keys: [${configKeys}]. ` +
516
+ `Common mistake: Using {...context.connection} instead of {connection: context.connection} ` +
517
+ `in TitanDatabaseModule.forRoot()`);
518
+ }
519
+ return {
520
+ database: connConfig.database || (config.dialect === 'sqlite' ? ':memory:' : 'postgres'),
521
+ host: connConfig.host,
522
+ port: connConfig.port,
523
+ user: connConfig.user,
524
+ password: connConfig.password,
525
+ ssl: connConfig.ssl,
526
+ searchPath: connConfig.searchPath,
527
+ charset: connConfig.charset,
528
+ timezone: connConfig.timezone,
529
+ };
530
+ }
531
+ async testConnection(db, dialect) {
532
+ const timeout = this.options.queryTimeout || DEFAULT_TIMEOUTS.query;
533
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(Errors.timeout('database connection test', timeout)), timeout));
534
+ const testQuery = sql `SELECT 1`.execute(db);
535
+ await Promise.race([testQuery, timeoutPromise]);
536
+ }
537
+ async validateConnectionHealth(db, dialect) {
538
+ try {
539
+ const timeout = dialect === 'sqlite' ? 10000 : 5000;
540
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Health check timeout')), timeout));
541
+ const healthCheckPromise = (async () => {
542
+ const testQuery = dialect === 'sqlite' ? sql `SELECT 1 AS health_check`.execute(db) : sql `SELECT 1 AS health_check`.execute(db);
543
+ await testQuery;
544
+ return true;
545
+ })();
546
+ return await Promise.race([healthCheckPromise, timeoutPromise]);
547
+ }
548
+ catch (error) {
549
+ this.logger.error({ error }, 'Connection health check failed');
550
+ return false;
551
+ }
552
+ }
553
+ sleep(ms) {
554
+ return new Promise((resolve) => setTimeout(resolve, ms));
555
+ }
556
+ async getConnection(name = DATABASE_DEFAULT_CONNECTION) {
557
+ const info = this.connections.get(name);
558
+ if (!info) {
559
+ throw Errors.notFound('Database connection', name);
560
+ }
561
+ if (!info.connected && !info.connecting) {
562
+ await this.reconnect(name);
563
+ }
564
+ if (!info.connected) {
565
+ throw Errors.unavailable(name, info.lastError?.message || 'Unknown error');
566
+ }
567
+ return info.instance;
568
+ }
569
+ async getExecutor(name = DATABASE_DEFAULT_CONNECTION, plugins) {
570
+ const info = this.connections.get(name);
571
+ if (!info) {
572
+ throw Errors.notFound('Database connection', name);
573
+ }
574
+ if (!info.connected && !info.connecting) {
575
+ await this.reconnect(name);
576
+ }
577
+ if (!info.connected) {
578
+ throw Errors.unavailable(name, info.lastError?.message || 'Unknown error');
579
+ }
580
+ if (plugins && plugins.length > 0) {
581
+ this.logger.debug({ connection: name, plugins: plugins.map((p) => p.name) }, 'Creating executor with custom plugins');
582
+ return createExecutor(info.instance, plugins);
583
+ }
584
+ if (info.executor) {
585
+ return info.executor;
586
+ }
587
+ return createExecutor(info.instance, []);
588
+ }
589
+ async setConnectionPlugins(name = DATABASE_DEFAULT_CONNECTION, plugins) {
590
+ const info = this.connections.get(name);
591
+ if (!info) {
592
+ throw Errors.notFound('Database connection', name);
593
+ }
594
+ if (!info.connected) {
595
+ throw Errors.unavailable(name, 'Connection not established');
596
+ }
597
+ this.logger.info({ connection: name, plugins: plugins.map((p) => p.name) }, 'Setting connection plugins');
598
+ const executor = await createExecutor(info.instance, plugins);
599
+ info.executor = executor;
600
+ info.plugins = getPlugins(executor);
601
+ return executor;
602
+ }
603
+ getConnectionPlugins(name = DATABASE_DEFAULT_CONNECTION) {
604
+ const info = this.connections.get(name);
605
+ return info?.plugins || [];
606
+ }
607
+ isExecutor(value) {
608
+ return isKyseraExecutor(value);
609
+ }
610
+ getRawDb(executor) {
611
+ return getRawDb(executor);
612
+ }
613
+ getPool(name = DATABASE_DEFAULT_CONNECTION) {
614
+ const info = this.connections.get(name);
615
+ return info?.pool;
616
+ }
617
+ async reconnect(name) {
618
+ const info = this.connections.get(name);
619
+ if (!info) {
620
+ throw Errors.notFound('Database connection', name);
621
+ }
622
+ this.logger.info({ name }, 'Attempting to reconnect to database');
623
+ info.retryCount++;
624
+ await this.createConnectionWithRetry(name, info.config);
625
+ }
626
+ async close(name = DATABASE_DEFAULT_CONNECTION) {
627
+ const info = this.connections.get(name);
628
+ if (!info) {
629
+ return;
630
+ }
631
+ this.connections.delete(name);
632
+ this.logger.info({ name }, 'Closing database connection');
633
+ try {
634
+ if (info.executor && isKyseraExecutor(info.executor)) {
635
+ try {
636
+ const { destroyExecutor } = await import('@kysera/executor');
637
+ await destroyExecutor(info.executor);
638
+ }
639
+ catch {
640
+ this.logger.debug({ name }, 'Skipping executor cleanup - dynamic import unavailable');
641
+ }
642
+ }
643
+ await info.instance.destroy();
644
+ if (info.pool) {
645
+ if (info.config.dialect === 'postgres' && info.pool instanceof Pool) {
646
+ await info.pool.end();
647
+ }
648
+ else if (info.config.dialect === 'mysql' && 'end' in info.pool) {
649
+ await new Promise((resolve, reject) => {
650
+ info.pool.end((err) => (err ? reject(err) : resolve()));
651
+ });
652
+ }
653
+ else if (info.config.dialect === 'sqlite' && 'close' in info.pool) {
654
+ info.pool.close();
655
+ }
656
+ }
657
+ info.connected = false;
658
+ this.emitEvent({
659
+ type: DATABASE_EVENTS.DISCONNECTED,
660
+ connection: name,
661
+ timestamp: new Date(),
662
+ });
663
+ this.logger.info({ name }, 'Database connection closed');
664
+ }
665
+ catch (error) {
666
+ this.logger.error({ name, error }, 'Error closing database connection');
667
+ throw error;
668
+ }
669
+ }
670
+ async closeAll() {
671
+ this.stopProactiveHealthChecks();
672
+ if (this.connections.size === 0) {
673
+ return;
674
+ }
675
+ this.logger.info('Closing all database connections');
676
+ const connectionNames = Array.from(this.connections.keys());
677
+ const closePromises = connectionNames.map((name) => this.close(name).catch((error) => this.logger.error({ name, error }, 'Error closing connection')));
678
+ await Promise.all(closePromises);
679
+ this.logger.info('All database connections closed');
680
+ }
681
+ isConnected(name = DATABASE_DEFAULT_CONNECTION) {
682
+ const info = this.connections.get(name);
683
+ return info?.connected || false;
684
+ }
685
+ getConnectionNames() {
686
+ return Array.from(this.connections.keys());
687
+ }
688
+ getMetrics(name) {
689
+ if (name) {
690
+ const info = this.connections.get(name);
691
+ return info?.metrics || {};
692
+ }
693
+ const metrics = {};
694
+ for (const [connName, info] of this.connections) {
695
+ metrics[connName] = info.metrics;
696
+ }
697
+ return metrics;
698
+ }
699
+ getPoolMetrics(name) {
700
+ if (name) {
701
+ const info = this.connections.get(name);
702
+ if (!info) {
703
+ throw Errors.notFound('Connection', name);
704
+ }
705
+ return this.collectPoolMetrics(info);
706
+ }
707
+ const metrics = new Map();
708
+ for (const [connName, info] of this.connections) {
709
+ metrics.set(connName, this.collectPoolMetrics(info));
710
+ }
711
+ return metrics;
712
+ }
713
+ collectPoolMetrics(info) {
714
+ const baseMetrics = { ...info.poolMetrics };
715
+ if (info.pool) {
716
+ if (info.config.dialect === 'postgres' && info.pool instanceof Pool) {
717
+ const pgPool = info.pool;
718
+ baseMetrics.totalConnections = pgPool.totalCount;
719
+ baseMetrics.idleConnections = pgPool.idleCount;
720
+ baseMetrics.waitingClients = pgPool.waitingCount;
721
+ baseMetrics.activeConnections = pgPool.totalCount - pgPool.idleCount;
722
+ }
723
+ else if (info.config.dialect === 'mysql' && 'pool' in info.pool) {
724
+ }
725
+ }
726
+ if (baseMetrics.acquireCount > 0 && baseMetrics.totalAcquireTimeMs > 0) {
727
+ baseMetrics.averageAcquireTimeMs = baseMetrics.totalAcquireTimeMs / baseMetrics.acquireCount;
728
+ }
729
+ return baseMetrics;
730
+ }
731
+ resetPoolMetrics(name) {
732
+ const resetMetrics = (info) => {
733
+ info.poolMetrics.acquireCount = 0;
734
+ info.poolMetrics.releaseCount = 0;
735
+ info.poolMetrics.errorCount = 0;
736
+ info.poolMetrics.totalAcquireTimeMs = 0;
737
+ info.poolMetrics.averageAcquireTimeMs = 0;
738
+ info.poolMetrics.lastError = undefined;
739
+ info.poolMetrics.lastAcquireAt = undefined;
740
+ };
741
+ if (name) {
742
+ const info = this.connections.get(name);
743
+ if (info) {
744
+ resetMetrics(info);
745
+ }
746
+ }
747
+ else {
748
+ for (const info of this.connections.values()) {
749
+ resetMetrics(info);
750
+ }
751
+ }
752
+ }
753
+ registerShutdownHandlers() {
754
+ const shutdownHandler = async () => {
755
+ if (this.shutdownInProgress)
756
+ return;
757
+ this.shutdownInProgress = true;
758
+ this.logger.info('Database manager shutdown initiated');
759
+ const timeout = this.options.shutdownTimeout || DEFAULT_TIMEOUTS.shutdown;
760
+ const timeoutPromise = new Promise((resolve) => setTimeout(resolve, timeout));
761
+ await Promise.race([this.closeAll(), timeoutPromise]);
762
+ };
763
+ process.on('SIGINT', shutdownHandler);
764
+ process.on('SIGTERM', shutdownHandler);
765
+ }
766
+ emitEvent(event) {
767
+ this.eventEmitter.emit(event.type, event);
768
+ }
769
+ on(event, listener) {
770
+ this.eventEmitter.on(event, listener);
771
+ }
772
+ off(event, listener) {
773
+ this.eventEmitter.off(event, listener);
774
+ }
775
+ getConnectionConfig(name) {
776
+ const connectionName = name || DATABASE_DEFAULT_CONNECTION;
777
+ const info = this.connections.get(connectionName);
778
+ return info?.config;
779
+ }
780
+ getDialect(name = DATABASE_DEFAULT_CONNECTION) {
781
+ const info = this.connections.get(name);
782
+ return info?.config?.dialect;
783
+ }
784
+ getCircuitBreaker(name = DATABASE_DEFAULT_CONNECTION) {
785
+ return this.circuitBreakers.get(name);
786
+ }
787
+ async withCircuitBreaker(name = DATABASE_DEFAULT_CONNECTION, fn) {
788
+ const breaker = this.circuitBreakers.get(name);
789
+ const db = await this.getConnection(name);
790
+ if (breaker) {
791
+ return breaker.execute(() => fn(db));
792
+ }
793
+ return fn(db);
794
+ }
795
+ async setSchema(schema, name = DATABASE_DEFAULT_CONNECTION) {
796
+ const info = this.connections.get(name);
797
+ if (!info) {
798
+ throw Errors.notFound('Database connection', name);
799
+ }
800
+ if (info.config.dialect !== 'postgres') {
801
+ throw Errors.badRequest(`setSchema is only supported for PostgreSQL connections, got: ${info.config.dialect}`);
802
+ }
803
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(schema)) {
804
+ throw Errors.badRequest(`Invalid schema name: ${schema}`);
805
+ }
806
+ await sql `SET search_path TO ${sql.ref(schema)}, public`.execute(info.instance);
807
+ this.connectionSchemas.set(name, schema);
808
+ this.logger.debug({ connection: name, schema }, 'Schema set for connection');
809
+ }
810
+ getSchema(name = DATABASE_DEFAULT_CONNECTION) {
811
+ return this.connectionSchemas.get(name);
812
+ }
813
+ async withSchema(schema, fn, name = DATABASE_DEFAULT_CONNECTION) {
814
+ const previousSchema = this.connectionSchemas.get(name);
815
+ await this.setSchema(schema, name);
816
+ try {
817
+ const db = await this.getConnection(name);
818
+ return await fn(db);
819
+ }
820
+ finally {
821
+ await this.setSchema(previousSchema ?? 'public', name);
822
+ }
823
+ }
824
+ async onModuleDestroy() {
825
+ await this.closeAll();
826
+ }
827
+ };
828
+ DatabaseManager = __decorate([
829
+ Injectable(),
830
+ __metadata("design:paramtypes", [Object, Object])
831
+ ], DatabaseManager);
832
+ export { DatabaseManager };
833
+ //# sourceMappingURL=database.manager.js.map