mysql-orm-lite 1.0.1 → 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.
@@ -0,0 +1,117 @@
1
+ import connectionManager from './lib/connectionManager';
2
+ import TransactionCRUD from './lib/TransactionCRUD';
3
+ import transactionManager from './lib/transactionManager';
4
+ export { connectionManager, transactionManager, TransactionCRUD };
5
+ export declare const find: (query: string, params?: any[], dbConfig?: import("./types").DbConfig) => Promise<any[]>;
6
+ export declare const findCount: (query: string, params?: any[], dbConfig?: import("./types").DbConfig) => Promise<number>;
7
+ export declare const insert: (table: string, data: Record<string, any>, dbConfig?: import("./types").DbConfig, debug?: boolean, isIgnore?: boolean) => Promise<any>;
8
+ export declare const update: (table: string, data: Record<string, any>, query: string, dbConfig?: import("./types").DbConfig, debug?: boolean) => Promise<number>;
9
+ export declare const _delete: (query: string, table?: string, dbConfig?: import("./types").DbConfig) => Promise<number>;
10
+ export { _delete as delete };
11
+ export declare const buildAndExecuteSelectQuery: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
12
+ export declare const buildAndExecuteUpdateQuery: (options: import("./types").UpdateOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
13
+ export declare const buildAndExecuteDeleteQuery: (options: import("./types").DeleteOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
14
+ export declare const select: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
15
+ export declare const findWhere: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
16
+ export declare const query: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
17
+ export declare const updateWhere: (options: import("./types").UpdateOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
18
+ export declare const updateQuery: (options: import("./types").UpdateOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
19
+ export declare const deleteWhere: (options: import("./types").DeleteOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
20
+ export declare const remove: (options: import("./types").DeleteOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
21
+ export declare const utils: {
22
+ handleConnectionError(err: any): Error;
23
+ logQueryPerformance(query: string, startTime: number, params?: any[]): number;
24
+ executeQuery({ query, params, dbConfig, operation }: {
25
+ query: string;
26
+ params?: any[];
27
+ dbConfig?: import("./types").DbConfig;
28
+ operation?: string;
29
+ }): Promise<any>;
30
+ validateUpdateParams(table: string, data: Record<string, any>, query: string): string[];
31
+ prepareUpdateParams(data: Record<string, any>): {
32
+ setFields: string[];
33
+ params: any[];
34
+ };
35
+ _buildWhereClause(conditions: import("./types").WhereConditions): {
36
+ clause: string;
37
+ params: any[];
38
+ };
39
+ _buildSelectQuery(options: import("./types").SelectOptions): {
40
+ query: string;
41
+ params: any[];
42
+ };
43
+ _buildUpdateQuery(options: import("./types").UpdateOptions): {
44
+ query: string;
45
+ params: any[];
46
+ };
47
+ _buildDeleteQuery(options: import("./types").DeleteOptions): {
48
+ query: string;
49
+ params: any[];
50
+ };
51
+ };
52
+ export declare const createTransaction: () => TransactionCRUD;
53
+ declare const _default: {
54
+ connectionManager: {
55
+ init: (config: import("./types").DbConfig, customLogger?: import("./types").Logger) => void;
56
+ setLogger: (customLogger: import("./types").Logger) => void;
57
+ getPool: (dbConfig?: import("./types").DbConfig) => Promise<import("mysql2/promise").Pool>;
58
+ closePool: (config: import("./types").DbConfig) => Promise<void>;
59
+ closeAllPools: () => Promise<void>;
60
+ getLogger: () => import("./types").Logger;
61
+ };
62
+ transactionManager: {
63
+ setInstance: (instance: TransactionCRUD) => void;
64
+ getInstance: () => TransactionCRUD | null;
65
+ clearInstance: () => void;
66
+ hasActiveTransaction: () => boolean;
67
+ };
68
+ TransactionCRUD: typeof TransactionCRUD;
69
+ find: (query: string, params?: any[], dbConfig?: import("./types").DbConfig) => Promise<any[]>;
70
+ findCount: (query: string, params?: any[], dbConfig?: import("./types").DbConfig) => Promise<number>;
71
+ insert: (table: string, data: Record<string, any>, dbConfig?: import("./types").DbConfig, debug?: boolean, isIgnore?: boolean) => Promise<any>;
72
+ update: (table: string, data: Record<string, any>, query: string, dbConfig?: import("./types").DbConfig, debug?: boolean) => Promise<number>;
73
+ delete: (query: string, table?: string, dbConfig?: import("./types").DbConfig) => Promise<number>;
74
+ buildAndExecuteSelectQuery: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
75
+ buildAndExecuteUpdateQuery: (options: import("./types").UpdateOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
76
+ buildAndExecuteDeleteQuery: (options: import("./types").DeleteOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
77
+ select: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
78
+ findWhere: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
79
+ query: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
80
+ updateWhere: (options: import("./types").UpdateOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
81
+ updateQuery: (options: import("./types").UpdateOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
82
+ deleteWhere: (options: import("./types").DeleteOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
83
+ remove: (options: import("./types").DeleteOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
84
+ utils: {
85
+ handleConnectionError(err: any): Error;
86
+ logQueryPerformance(query: string, startTime: number, params?: any[]): number;
87
+ executeQuery({ query, params, dbConfig, operation }: {
88
+ query: string;
89
+ params?: any[];
90
+ dbConfig?: import("./types").DbConfig;
91
+ operation?: string;
92
+ }): Promise<any>;
93
+ validateUpdateParams(table: string, data: Record<string, any>, query: string): string[];
94
+ prepareUpdateParams(data: Record<string, any>): {
95
+ setFields: string[];
96
+ params: any[];
97
+ };
98
+ _buildWhereClause(conditions: import("./types").WhereConditions): {
99
+ clause: string;
100
+ params: any[];
101
+ };
102
+ _buildSelectQuery(options: import("./types").SelectOptions): {
103
+ query: string;
104
+ params: any[];
105
+ };
106
+ _buildUpdateQuery(options: import("./types").UpdateOptions): {
107
+ query: string;
108
+ params: any[];
109
+ };
110
+ _buildDeleteQuery(options: import("./types").DeleteOptions): {
111
+ query: string;
112
+ params: any[];
113
+ };
114
+ };
115
+ createTransaction: () => TransactionCRUD;
116
+ };
117
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.createTransaction = exports.utils = exports.remove = exports.deleteWhere = exports.updateQuery = exports.updateWhere = exports.query = exports.findWhere = exports.select = exports.buildAndExecuteDeleteQuery = exports.buildAndExecuteUpdateQuery = exports.buildAndExecuteSelectQuery = exports.delete = exports._delete = exports.update = exports.insert = exports.findCount = exports.find = exports.TransactionCRUD = exports.transactionManager = exports.connectionManager = void 0;
40
+ const connectionManager_1 = __importDefault(require("./lib/connectionManager"));
41
+ exports.connectionManager = connectionManager_1.default;
42
+ const crud = __importStar(require("./lib/crud"));
43
+ const TransactionCRUD_1 = __importDefault(require("./lib/TransactionCRUD"));
44
+ exports.TransactionCRUD = TransactionCRUD_1.default;
45
+ const transactionManager_1 = __importDefault(require("./lib/transactionManager"));
46
+ exports.transactionManager = transactionManager_1.default;
47
+ // CRUD Operations (Non-transactional)
48
+ exports.find = crud.find;
49
+ exports.findCount = crud.findCount;
50
+ exports.insert = crud.insert;
51
+ exports.update = crud.update;
52
+ exports._delete = crud.delete;
53
+ exports.delete = exports._delete;
54
+ // Query Builder - Full names
55
+ exports.buildAndExecuteSelectQuery = crud.buildAndExecuteSelectQuery;
56
+ exports.buildAndExecuteUpdateQuery = crud.buildAndExecuteUpdateQuery;
57
+ exports.buildAndExecuteDeleteQuery = crud.buildAndExecuteDeleteQuery;
58
+ // Query Builder - Alternative shorter names
59
+ exports.select = crud.select;
60
+ exports.findWhere = crud.findWhere;
61
+ exports.query = crud.query;
62
+ exports.updateWhere = crud.updateWhere;
63
+ exports.updateQuery = crud.updateQuery;
64
+ exports.deleteWhere = crud.deleteWhere;
65
+ exports.remove = crud.remove;
66
+ // Utility exports
67
+ exports.utils = crud.utils;
68
+ // Convenience method to create transaction
69
+ const createTransaction = () => new TransactionCRUD_1.default();
70
+ exports.createTransaction = createTransaction;
71
+ // Default export for CJS compatibility and convenience
72
+ exports.default = {
73
+ connectionManager: connectionManager_1.default,
74
+ transactionManager: transactionManager_1.default,
75
+ TransactionCRUD: TransactionCRUD_1.default,
76
+ find: exports.find,
77
+ findCount: exports.findCount,
78
+ insert: exports.insert,
79
+ update: exports.update,
80
+ delete: exports._delete,
81
+ buildAndExecuteSelectQuery: exports.buildAndExecuteSelectQuery,
82
+ buildAndExecuteUpdateQuery: exports.buildAndExecuteUpdateQuery,
83
+ buildAndExecuteDeleteQuery: exports.buildAndExecuteDeleteQuery,
84
+ select: exports.select,
85
+ findWhere: exports.findWhere,
86
+ query: exports.query,
87
+ updateWhere: exports.updateWhere,
88
+ updateQuery: exports.updateQuery,
89
+ deleteWhere: exports.deleteWhere,
90
+ remove: exports.remove,
91
+ utils: exports.utils,
92
+ createTransaction: exports.createTransaction
93
+ };
@@ -0,0 +1,42 @@
1
+ import { DbConfig, SelectOptions, UpdateOptions, DeleteOptions } from '../types';
2
+ declare class TransactionCRUD {
3
+ private connection;
4
+ private transactionActive;
5
+ debug: boolean;
6
+ constructor();
7
+ /**
8
+ * Initialize a transaction
9
+ * @param dbConfig - Database configuration (optional)
10
+ */
11
+ init(dbConfig?: DbConfig): Promise<any>;
12
+ /**
13
+ * Execute a query within the transaction
14
+ */
15
+ executeQuery(query: string, params?: any[], operation?: string): Promise<any>;
16
+ /**
17
+ * Commit the transaction
18
+ */
19
+ commit(): Promise<void>;
20
+ /**
21
+ * Rollback the transaction
22
+ */
23
+ rollback(): Promise<void>;
24
+ private _cleanup;
25
+ find(query: string, params?: any[]): Promise<any[]>;
26
+ insert(table: string, data: Record<string, any>): Promise<any>;
27
+ update(table: string, data: Record<string, any>, query: string): Promise<number>;
28
+ delete(query: string, table?: string): Promise<number>;
29
+ buildAndExecuteSelectQuery(options: SelectOptions): Promise<any[]>;
30
+ buildAndExecuteUpdateQuery(options: UpdateOptions): Promise<number>;
31
+ buildAndExecuteDeleteQuery(options: DeleteOptions): Promise<number>;
32
+ select(options: SelectOptions): Promise<any[]>;
33
+ findWhere(options: SelectOptions): Promise<any[]>;
34
+ findForUpdate(options: SelectOptions): Promise<any[]>;
35
+ query(options: SelectOptions): Promise<any[]>;
36
+ updateWhere(options: UpdateOptions): Promise<number>;
37
+ updateQuery(options: UpdateOptions): Promise<number>;
38
+ deleteWhere(options: DeleteOptions): Promise<number>;
39
+ remove(options: DeleteOptions): Promise<number>;
40
+ }
41
+ export default TransactionCRUD;
42
+ export { TransactionCRUD };
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TransactionCRUD = void 0;
7
+ const connectionManager_1 = __importDefault(require("./connectionManager"));
8
+ const crud_1 = require("./crud");
9
+ class TransactionCRUD {
10
+ connection = null;
11
+ transactionActive = false;
12
+ debug = false;
13
+ constructor() {
14
+ this.connection = null;
15
+ this.transactionActive = false;
16
+ this.debug = false;
17
+ }
18
+ /**
19
+ * Initialize a transaction
20
+ * @param dbConfig - Database configuration (optional)
21
+ */
22
+ async init(dbConfig) {
23
+ const logger = connectionManager_1.default.getLogger();
24
+ try {
25
+ const pool = await connectionManager_1.default.getPool(dbConfig);
26
+ this.connection = await pool.getConnection();
27
+ await this.connection.beginTransaction();
28
+ this.transactionActive = true;
29
+ logger.info('Transaction initialized successfully');
30
+ return this.connection;
31
+ }
32
+ catch (error) {
33
+ logger.error('Failed to initialize transaction:', error);
34
+ if (this.connection) {
35
+ this.connection.release();
36
+ this.connection = null;
37
+ }
38
+ throw error;
39
+ }
40
+ }
41
+ /**
42
+ * Execute a query within the transaction
43
+ */
44
+ async executeQuery(query, params = [], operation = 'TRANS_QUERY') {
45
+ if (!this.connection || !this.transactionActive) {
46
+ throw new Error('No active transaction. Call init() first.');
47
+ }
48
+ const logger = connectionManager_1.default.getLogger();
49
+ const startTime = Date.now();
50
+ try {
51
+ const [results] = await this.connection.query(query, params);
52
+ const duration = Date.now() - startTime;
53
+ if (duration > 1000) {
54
+ logger.warn(`[TRANS] Slow Query (${duration}ms): ${query}`);
55
+ }
56
+ return results;
57
+ }
58
+ catch (error) {
59
+ logger.error(`${operation} Failed: ${error.message}`);
60
+ logger.error(`Query: ${query}`);
61
+ throw error;
62
+ }
63
+ }
64
+ /**
65
+ * Commit the transaction
66
+ */
67
+ async commit() {
68
+ if (!this.connection || !this.transactionActive) {
69
+ throw new Error('No active transaction to commit');
70
+ }
71
+ const logger = connectionManager_1.default.getLogger();
72
+ try {
73
+ await this.connection.commit();
74
+ logger.info('Transaction committed');
75
+ }
76
+ catch (error) {
77
+ logger.error('Commit failed, rolling back...', error);
78
+ await this.rollback();
79
+ throw error;
80
+ }
81
+ finally {
82
+ this._cleanup();
83
+ }
84
+ }
85
+ /**
86
+ * Rollback the transaction
87
+ */
88
+ async rollback() {
89
+ if (!this.connection)
90
+ return;
91
+ const logger = connectionManager_1.default.getLogger();
92
+ try {
93
+ await this.connection.rollback();
94
+ logger.info('Transaction rolled back');
95
+ }
96
+ catch (error) {
97
+ logger.error('Rollback failed:', error);
98
+ }
99
+ finally {
100
+ this._cleanup();
101
+ }
102
+ }
103
+ _cleanup() {
104
+ if (this.connection) {
105
+ this.connection.release();
106
+ this.connection = null;
107
+ }
108
+ this.transactionActive = false;
109
+ }
110
+ // CRUD Methods
111
+ async find(query, params = []) {
112
+ return await this.executeQuery(query, params, 'TRANS_FIND');
113
+ }
114
+ async insert(table, data) {
115
+ if (!table || !data)
116
+ throw new Error('Invalid table or data');
117
+ const fields = Object.keys(data);
118
+ const values = Object.values(data);
119
+ const placeholders = fields.map(() => '?').join(', ');
120
+ const sql = `INSERT INTO ${table} (${fields.join(', ')}) VALUES (${placeholders})`;
121
+ const result = await this.executeQuery(sql, values, 'TRANS_INSERT');
122
+ return result.insertId;
123
+ }
124
+ async update(table, data, query) {
125
+ if (!query || !query.toLowerCase().includes('where'))
126
+ throw new Error('Update requires WHERE');
127
+ const { setFields, params } = crud_1.utils.prepareUpdateParams(data);
128
+ const sql = `UPDATE ${table} SET ${setFields.join(', ')} ${query}`;
129
+ const result = await this.executeQuery(sql, params, 'TRANS_UPDATE');
130
+ return result.affectedRows;
131
+ }
132
+ async delete(query, table) {
133
+ if (!query || !query.toLowerCase().includes('where'))
134
+ throw new Error('Delete requires WHERE');
135
+ const sql = table ? `DELETE FROM ${table} ${query}` : query;
136
+ const result = await this.executeQuery(sql, [], 'TRANS_DELETE');
137
+ return result.affectedRows;
138
+ }
139
+ async buildAndExecuteSelectQuery(options) {
140
+ const logger = connectionManager_1.default.getLogger();
141
+ try {
142
+ const { query, params } = crud_1.utils._buildSelectQuery(options);
143
+ return await this.executeQuery(query, params, 'TRANS_BUILD_SELECT');
144
+ }
145
+ catch (err) {
146
+ logger.error('buildAndExecuteSelectQuery failed:', err);
147
+ throw err;
148
+ }
149
+ }
150
+ async buildAndExecuteUpdateQuery(options) {
151
+ const logger = connectionManager_1.default.getLogger();
152
+ try {
153
+ const { query, params } = crud_1.utils._buildUpdateQuery(options);
154
+ const result = await this.executeQuery(query, params, 'TRANS_BUILD_UPDATE');
155
+ return result.affectedRows;
156
+ }
157
+ catch (err) {
158
+ logger.error('buildAndExecuteUpdateQuery failed:', err);
159
+ throw err;
160
+ }
161
+ }
162
+ async buildAndExecuteDeleteQuery(options) {
163
+ const logger = connectionManager_1.default.getLogger();
164
+ try {
165
+ const { query, params } = crud_1.utils._buildDeleteQuery(options);
166
+ const result = await this.executeQuery(query, params, 'TRANS_BUILD_DELETE');
167
+ return result.affectedRows;
168
+ }
169
+ catch (err) {
170
+ logger.error('buildAndExecuteDeleteQuery failed:', err);
171
+ throw err;
172
+ }
173
+ }
174
+ // Alternative shorter method names (aliases)
175
+ async select(options) {
176
+ return this.buildAndExecuteSelectQuery(options);
177
+ }
178
+ async findWhere(options) {
179
+ return this.buildAndExecuteSelectQuery(options);
180
+ }
181
+ async findForUpdate(options) {
182
+ options.forUpdate = true;
183
+ return this.buildAndExecuteSelectQuery(options);
184
+ }
185
+ async query(options) {
186
+ return this.buildAndExecuteSelectQuery(options);
187
+ }
188
+ async updateWhere(options) {
189
+ return this.buildAndExecuteUpdateQuery(options);
190
+ }
191
+ async updateQuery(options) {
192
+ return this.buildAndExecuteUpdateQuery(options);
193
+ }
194
+ async deleteWhere(options) {
195
+ return this.buildAndExecuteDeleteQuery(options);
196
+ }
197
+ async remove(options) {
198
+ return this.buildAndExecuteDeleteQuery(options);
199
+ }
200
+ }
201
+ exports.TransactionCRUD = TransactionCRUD;
202
+ exports.default = TransactionCRUD;
@@ -0,0 +1,36 @@
1
+ import * as mysql from 'mysql2/promise';
2
+ import { DbConfig, Logger } from '../types';
3
+ declare const connectionManager: {
4
+ /**
5
+ * Initialize with default config and optional logger
6
+ * @param config - Database configuration
7
+ * @param customLogger - Custom logger (optional)
8
+ */
9
+ init: (config: DbConfig, customLogger?: Logger) => void;
10
+ /**
11
+ * Set custom logger
12
+ * @param customLogger - Logger with info, error, warn methods
13
+ */
14
+ setLogger: (customLogger: Logger) => void;
15
+ /**
16
+ * Get or create a connection pool
17
+ * @param dbConfig - Database configuration (optional)
18
+ * @returns MySQL connection pool
19
+ */
20
+ getPool: (dbConfig?: DbConfig) => Promise<mysql.Pool>;
21
+ /**
22
+ * Close a specific pool
23
+ * @param config - Database configuration
24
+ */
25
+ closePool: (config: DbConfig) => Promise<void>;
26
+ /**
27
+ * Close all pools (call on application shutdown)
28
+ */
29
+ closeAllPools: () => Promise<void>;
30
+ /**
31
+ * Get logger instance
32
+ */
33
+ getLogger: () => Logger;
34
+ };
35
+ export default connectionManager;
36
+ export { connectionManager };
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.connectionManager = void 0;
37
+ const mysql = __importStar(require("mysql2/promise"));
38
+ // Default logger
39
+ const defaultLogger = {
40
+ info: (...args) => console.log('[INFO]', ...args),
41
+ error: (...args) => console.error('[ERROR]', ...args),
42
+ warn: (...args) => console.warn('[WARN]', ...args)
43
+ };
44
+ const pools = new Map();
45
+ let logger = defaultLogger;
46
+ let defaultConfig = null;
47
+ const getPoolKey = (config) => {
48
+ return `${config.host}:${config.port || 3306}:${config.user}:${config.database}`;
49
+ };
50
+ const connectionManager = {
51
+ /**
52
+ * Initialize with default config and optional logger
53
+ * @param config - Database configuration
54
+ * @param customLogger - Custom logger (optional)
55
+ */
56
+ init: (config, customLogger) => {
57
+ if (!config || !config.database) {
58
+ throw new Error('Valid database configuration required');
59
+ }
60
+ defaultConfig = config;
61
+ if (customLogger) {
62
+ logger = customLogger;
63
+ }
64
+ logger.info('Connection manager initialized');
65
+ },
66
+ /**
67
+ * Set custom logger
68
+ * @param customLogger - Logger with info, error, warn methods
69
+ */
70
+ setLogger: (customLogger) => {
71
+ logger = customLogger;
72
+ },
73
+ /**
74
+ * Get or create a connection pool
75
+ * @param dbConfig - Database configuration (optional)
76
+ * @returns MySQL connection pool
77
+ */
78
+ getPool: async (dbConfig) => {
79
+ const conf = dbConfig || defaultConfig;
80
+ if (!conf || !conf.database) {
81
+ throw new Error('Database configuration missing. Call connectionManager.init() first or provide dbConfig');
82
+ }
83
+ const key = getPoolKey(conf);
84
+ if (pools.has(key)) {
85
+ return pools.get(key);
86
+ }
87
+ try {
88
+ logger.info(`Creating new connection pool for ${key}`);
89
+ const pool = mysql.createPool({
90
+ host: conf.host,
91
+ user: conf.user,
92
+ password: conf.password,
93
+ database: conf.database,
94
+ port: conf.port || 3306,
95
+ waitForConnections: true,
96
+ connectionLimit: conf.connectionLimit || 10,
97
+ queueLimit: 0,
98
+ enableKeepAlive: true,
99
+ keepAliveInitialDelay: 0
100
+ });
101
+ pools.set(key, pool);
102
+ return pool;
103
+ }
104
+ catch (error) {
105
+ logger.error('Failed to create connection pool:', error);
106
+ throw error;
107
+ }
108
+ },
109
+ /**
110
+ * Close a specific pool
111
+ * @param config - Database configuration
112
+ */
113
+ closePool: async (config) => {
114
+ const key = getPoolKey(config);
115
+ if (pools.has(key)) {
116
+ const pool = pools.get(key);
117
+ await pool.end();
118
+ pools.delete(key);
119
+ logger.info(`Closed connection pool for ${key}`);
120
+ }
121
+ },
122
+ /**
123
+ * Close all pools (call on application shutdown)
124
+ */
125
+ closeAllPools: async () => {
126
+ for (const [key, pool] of pools.entries()) {
127
+ try {
128
+ await pool.end();
129
+ logger.info(`Closed connection pool for ${key}`);
130
+ }
131
+ catch (error) {
132
+ logger.error(`Error closing pool ${key}:`, error);
133
+ }
134
+ }
135
+ pools.clear();
136
+ },
137
+ /**
138
+ * Get logger instance
139
+ */
140
+ getLogger: () => logger
141
+ };
142
+ exports.connectionManager = connectionManager;
143
+ exports.default = connectionManager;