mysql-orm-lite 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -872,6 +872,400 @@ if (db.transactionManager.hasActiveTransaction()) {
872
872
 
873
873
  ---
874
874
 
875
+ ### Schema Introspection
876
+
877
+ Query your database structure programmatically to inspect tables, columns, and indexes.
878
+
879
+ #### `schema.tables(dbConfig?)`
880
+
881
+ Get a list of all tables in the database.
882
+
883
+ ```javascript
884
+ const tables = await db.schema.tables();
885
+ console.log(tables); // ['users', 'orders', 'products', ...]
886
+ ```
887
+
888
+ #### `schema.columns(tableName, dbConfig?)`
889
+
890
+ Get detailed column information for a specific table.
891
+
892
+ ```javascript
893
+ const columns = await db.schema.columns('users');
894
+ console.log(columns);
895
+ /*
896
+ [
897
+ {
898
+ name: 'id',
899
+ type: 'int(11)',
900
+ nullable: false,
901
+ key: 'PRI',
902
+ default: null,
903
+ extra: 'auto_increment'
904
+ },
905
+ {
906
+ name: 'email',
907
+ type: 'varchar(255)',
908
+ nullable: false,
909
+ key: 'UNI',
910
+ default: null,
911
+ extra: ''
912
+ },
913
+ ...
914
+ ]
915
+ */
916
+ ```
917
+
918
+ #### `schema.indexes(tableName, dbConfig?)`
919
+
920
+ Get index information for a specific table.
921
+
922
+ ```javascript
923
+ const indexes = await db.schema.indexes('users');
924
+ console.log(indexes);
925
+ /*
926
+ [
927
+ {
928
+ name: 'PRIMARY',
929
+ column: 'id',
930
+ unique: true,
931
+ type: 'BTREE'
932
+ },
933
+ {
934
+ name: 'email_idx',
935
+ column: 'email',
936
+ unique: true,
937
+ type: 'BTREE'
938
+ },
939
+ ...
940
+ ]
941
+ */
942
+ ```
943
+
944
+ #### Practical Use Cases
945
+
946
+ **Dynamic Form Generation:**
947
+ ```javascript
948
+ const columns = await db.schema.columns('products');
949
+ const formFields = columns
950
+ .filter(col => !['id', 'created_at', 'updated_at'].includes(col.name))
951
+ .map(col => ({
952
+ name: col.name,
953
+ type: col.type.includes('int') ? 'number' : 'text',
954
+ required: !col.nullable
955
+ }));
956
+ ```
957
+
958
+ **Schema Validation:**
959
+ ```javascript
960
+ const tables = await db.schema.tables();
961
+ const requiredTables = ['users', 'orders', 'products'];
962
+ const missingTables = requiredTables.filter(t => !tables.includes(t));
963
+
964
+ if (missingTables.length > 0) {
965
+ console.error('Missing tables:', missingTables);
966
+ }
967
+ ```
968
+
969
+ #### `schema.foreignKeys(tableName?, dbConfig?)`
970
+
971
+ Get foreign key relationships for a specific table or all tables.
972
+
973
+ ```javascript
974
+ // Get all foreign keys in the database
975
+ const allForeignKeys = await db.schema.foreignKeys();
976
+ console.log(allForeignKeys);
977
+ /*
978
+ [
979
+ {
980
+ childTable: 'orders',
981
+ parentTable: 'users',
982
+ constraintName: 'orders_ibfk_1',
983
+ columnName: 'user_id',
984
+ referencedColumnName: 'id'
985
+ },
986
+ {
987
+ childTable: 'order_items',
988
+ parentTable: 'orders',
989
+ constraintName: 'order_items_ibfk_1',
990
+ columnName: 'order_id',
991
+ referencedColumnName: 'id'
992
+ },
993
+ ...
994
+ ]
995
+ */
996
+
997
+ // Get foreign keys for a specific table
998
+ const orderForeignKeys = await db.schema.foreignKeys('orders');
999
+ console.log(orderForeignKeys); // Shows both incoming and outgoing foreign keys
1000
+ ```
1001
+
1002
+ #### `schema.deleteOrder(dbConfig?)`
1003
+
1004
+ Get the correct order to delete/truncate tables based on foreign key dependencies. Uses topological sort to ensure child tables are deleted before parent tables, preventing foreign key constraint violations.
1005
+
1006
+ ```javascript
1007
+ const deleteOrder = await db.schema.deleteOrder();
1008
+ console.log(deleteOrder);
1009
+ // ['order_items', 'orders', 'users', 'products', ...]
1010
+ // Child tables come first, so you can safely delete in this order
1011
+
1012
+ // Practical use: Truncate all tables in the correct order
1013
+ for (const table of deleteOrder) {
1014
+ await db.find(`TRUNCATE TABLE ${table}`);
1015
+ console.log(`Truncated ${table}`);
1016
+ }
1017
+ ```
1018
+
1019
+ **Use Cases:**
1020
+ - **Database Cleanup**: Safely truncate all tables for testing without foreign key errors
1021
+ - **Data Migration**: Understand table dependencies before moving data
1022
+ - **Schema Visualization**: Generate dependency graphs for documentation```
1023
+
1024
+ ---
1025
+
1026
+ ```
1027
+
1028
+ ---
1029
+
1030
+ ### Bulk Operations
1031
+
1032
+ Optimized methods for handling large datasets efficiently.
1033
+
1034
+ #### `bulkInsert(table, records, options?)`
1035
+
1036
+ Insert multiple records in a single query (batching handled automatically).
1037
+
1038
+ ```javascript
1039
+ const users = [
1040
+ { name: 'User 1', email: 'user1@test.com' },
1041
+ { name: 'User 2', email: 'user2@test.com' },
1042
+ // ... 1000s of other users
1043
+ ];
1044
+
1045
+ // Automatically splits into batches (default 1000 per batch)
1046
+ const result = await db.bulkInsert('users', users);
1047
+
1048
+ console.log(`Inserted ${result.totalInserted} users in ${result.batches} batches`);
1049
+ console.log(`First ID: ${result.firstInsertId}, Last ID: ${result.lastInsertId}`);
1050
+
1051
+ // Custom batch size
1052
+ await db.bulkInsert('users', users, { batchSize: 500 });
1053
+
1054
+ // Use INSERT IGNORE to skip duplicates
1055
+ await db.bulkInsert('users', users, { ignore: true });
1056
+ ```
1057
+
1058
+ #### `upsert(table, data, options)`
1059
+
1060
+ Insert a record, or update specific fields if a duplicate key constraint occurs.
1061
+
1062
+ ```javascript
1063
+ // Updates 'stock' if product with id 101 already exists
1064
+ const result = await db.upsert('products', {
1065
+ id: 101,
1066
+ name: 'Laptop',
1067
+ stock: 50
1068
+ }, {
1069
+ conflictKey: 'id', // Column(s) that define uniqueness
1070
+ updateFields: ['stock'] // Only update 'stock' on conflict, keep 'name' as is
1071
+ // If updateFields is omitted, ALL fields except conflictKey are updated
1072
+ });
1073
+
1074
+ if (result.action === 'inserted') {
1075
+ console.log('New product created');
1076
+ } else {
1077
+ console.log('Product stock updated');
1078
+ }
1079
+ ```
1080
+
1081
+ #### `bulkUpsert(table, records, options)`
1082
+
1083
+ Perform upsert operations on a large array of records efficiently.
1084
+
1085
+ ```javascript
1086
+ const products = [
1087
+ { id: 101, stock: 50 },
1088
+ { id: 102, stock: 20 },
1089
+ // ...
1090
+ ];
1091
+
1092
+ const result = await db.bulkUpsert('products', products, {
1093
+ conflictKey: 'id',
1094
+ updateFields: ['stock']
1095
+ });
1096
+
1097
+ console.log(`Updated stock for ${result.totalAffected} products`);
1098
+ ```
1099
+
1100
+ ---
1101
+
1102
+ ### Performance Monitoring
1103
+
1104
+
1105
+ Track query execution metrics, identify slow queries, and monitor database performance in real-time.
1106
+
1107
+ #### Enable/Disable Monitoring
1108
+
1109
+ ```javascript
1110
+ // Enable performance monitoring
1111
+ db.performanceMonitor.enable();
1112
+
1113
+ // Your database operations...
1114
+ await db.select({ table: 'users', where: { active: true } });
1115
+
1116
+ // Disable monitoring
1117
+ db.performanceMonitor.disable();
1118
+ ```
1119
+
1120
+ > [!NOTE]
1121
+ > Performance monitoring is **disabled by default** to avoid overhead. Enable it only when needed.
1122
+
1123
+ #### Get Performance Statistics
1124
+
1125
+ ```javascript
1126
+ db.performanceMonitor.enable();
1127
+
1128
+ // Execute some queries...
1129
+ await db.select({ table: 'users' });
1130
+ await db.insert('logs', { message: 'test' });
1131
+ await db.updateWhere({ table: 'users', data: { status: 'active' }, where: { id: 1 } });
1132
+
1133
+ // Get comprehensive stats
1134
+ const stats = db.performanceMonitor.getStats();
1135
+ console.log(stats);
1136
+ /*
1137
+ {
1138
+ enabled: true,
1139
+ totalQueries: 3,
1140
+ averageQueryTime: 12.5,
1141
+ slowestQueries: [
1142
+ {
1143
+ query: 'SELECT * FROM users',
1144
+ duration: 25,
1145
+ timestamp: 1234567890,
1146
+ type: 'SELECT',
1147
+ params: []
1148
+ },
1149
+ ...
1150
+ ],
1151
+ queryCountByType: {
1152
+ SELECT: 1,
1153
+ INSERT: 1,
1154
+ UPDATE: 1,
1155
+ DELETE: 0,
1156
+ OTHER: 0
1157
+ },
1158
+ startTime: 1234567800,
1159
+ uptime: 90000
1160
+ }
1161
+ */
1162
+ ```
1163
+
1164
+ #### Get Slow Queries
1165
+
1166
+ ```javascript
1167
+ // Get top 10 slowest queries
1168
+ const slowQueries = db.performanceMonitor.getSlowQueries(10);
1169
+ console.log(slowQueries);
1170
+
1171
+ // Each entry contains:
1172
+ // - query: SQL query string
1173
+ // - duration: Execution time in milliseconds
1174
+ // - timestamp: When the query was executed
1175
+ // - type: Query type (SELECT, INSERT, UPDATE, DELETE, OTHER)
1176
+ // - params: Query parameters (if any)
1177
+ ```
1178
+
1179
+ #### Get Recent Queries
1180
+
1181
+ ```javascript
1182
+ // Get queries from the last 60 seconds (default)
1183
+ const recentQueries = db.performanceMonitor.getRecentQueries();
1184
+
1185
+ // Get queries from the last 5 minutes
1186
+ const last5Min = db.performanceMonitor.getRecentQueries(5 * 60 * 1000);
1187
+ ```
1188
+
1189
+ #### Get Queries Per Second
1190
+
1191
+ ```javascript
1192
+ const qps = db.performanceMonitor.getQueriesPerSecond();
1193
+ console.log(`Current QPS: ${qps.toFixed(2)}`);
1194
+ ```
1195
+
1196
+ #### Reset Metrics
1197
+
1198
+ ```javascript
1199
+ // Clear all collected metrics and restart the timer
1200
+ db.performanceMonitor.reset();
1201
+ ```
1202
+
1203
+ #### Connection Pool Statistics
1204
+
1205
+ ```javascript
1206
+ // Get current connection pool stats
1207
+ const poolStats = await db.connectionManager.getPoolStats();
1208
+ console.log(poolStats);
1209
+ /*
1210
+ {
1211
+ activeConnections: 2,
1212
+ idleConnections: 8,
1213
+ totalConnections: 10,
1214
+ waitingRequests: 0
1215
+ }
1216
+ */
1217
+ ```
1218
+
1219
+ #### Practical Use Cases
1220
+
1221
+ **1. Identify Performance Bottlenecks:**
1222
+ ```javascript
1223
+ db.performanceMonitor.enable();
1224
+
1225
+ // Run your application...
1226
+ await runApplicationLogic();
1227
+
1228
+ // After some time, check stats
1229
+ const slowQueries = db.performanceMonitor.getSlowQueries(5);
1230
+ slowQueries.forEach(q => {
1231
+ console.log(`Slow query (${q.duration}ms): ${q.query}`);
1232
+ });
1233
+ ```
1234
+
1235
+ **2. Monitor Production Performance:**
1236
+ ```javascript
1237
+ // Enable in production with periodic reporting
1238
+ db.performanceMonitor.enable();
1239
+
1240
+ setInterval(() => {
1241
+ const stats = db.performanceMonitor.getStats();
1242
+ console.log(`QPS: ${db.performanceMonitor.getQueriesPerSecond().toFixed(2)}`);
1243
+ console.log(`Avg Query Time: ${stats.averageQueryTime}ms`);
1244
+
1245
+ // Alert if queries are too slow
1246
+ if (stats.averageQueryTime > 100) {
1247
+ console.warn('ALERT: Average query time exceeds 100ms!');
1248
+ }
1249
+ }, 60000); // Every minute
1250
+ ```
1251
+
1252
+ **3. Load Testing Analysis:**
1253
+ ```javascript
1254
+ db.performanceMonitor.enable();
1255
+ db.performanceMonitor.reset();
1256
+
1257
+ // Run load test...
1258
+ await runLoadTest();
1259
+
1260
+ // Analyze results
1261
+ const stats = db.performanceMonitor.getStats();
1262
+ console.log(`Total Queries: ${stats.totalQueries}`);
1263
+ console.log(`Average Time: ${stats.averageQueryTime}ms`);
1264
+ console.log(`QPS: ${db.performanceMonitor.getQueriesPerSecond()}`);
1265
+ ```
1266
+
1267
+ ---
1268
+
875
1269
  ## Advanced Usage
876
1270
 
877
1271
  ### Multiple Database Connections
package/dist/index.d.ts CHANGED
@@ -1,13 +1,40 @@
1
1
  import connectionManager from './lib/connectionManager';
2
2
  import TransactionCRUD from './lib/TransactionCRUD';
3
3
  import transactionManager from './lib/transactionManager';
4
- export { connectionManager, transactionManager, TransactionCRUD };
4
+ import schema from './lib/schema';
5
+ import performanceMonitor from './lib/performanceMonitor';
6
+ export { connectionManager, transactionManager, TransactionCRUD, schema, performanceMonitor };
5
7
  export declare const find: (query: string, params?: any[], dbConfig?: import("./types").DbConfig) => Promise<any[]>;
6
8
  export declare const findCount: (query: string, params?: any[], dbConfig?: import("./types").DbConfig) => Promise<number>;
7
9
  export declare const insert: (table: string, data: Record<string, any>, dbConfig?: import("./types").DbConfig, debug?: boolean, isIgnore?: boolean) => Promise<any>;
8
10
  export declare const update: (table: string, data: Record<string, any>, query: string, dbConfig?: import("./types").DbConfig, debug?: boolean) => Promise<number>;
9
11
  export declare const _delete: (query: string, table?: string, dbConfig?: import("./types").DbConfig) => Promise<number>;
10
12
  export { _delete as delete };
13
+ export declare const bulkInsert: (table: string, records: Record<string, any>[], options?: {
14
+ batchSize?: number;
15
+ ignore?: boolean;
16
+ }, dbConfig?: import("./types").DbConfig) => Promise<{
17
+ totalInserted: number;
18
+ batches: number;
19
+ firstInsertId?: number;
20
+ lastInsertId?: number;
21
+ }>;
22
+ export declare const upsert: (table: string, data: Record<string, any>, options: {
23
+ conflictKey: string | string[];
24
+ updateFields?: string[];
25
+ }, dbConfig?: import("./types").DbConfig) => Promise<{
26
+ action: "inserted" | "updated";
27
+ affectedRows: number;
28
+ insertId?: number;
29
+ }>;
30
+ export declare const bulkUpsert: (table: string, records: Record<string, any>[], options: {
31
+ conflictKey: string | string[];
32
+ updateFields?: string[];
33
+ batchSize?: number;
34
+ }, dbConfig?: import("./types").DbConfig) => Promise<{
35
+ totalAffected: number;
36
+ batches: number;
37
+ }>;
11
38
  export declare const buildAndExecuteSelectQuery: (options: import("./types").SelectOptions, dbConfig?: import("./types").DbConfig) => Promise<any[]>;
12
39
  export declare const buildAndExecuteUpdateQuery: (options: import("./types").UpdateOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
13
40
  export declare const buildAndExecuteDeleteQuery: (options: import("./types").DeleteOptions, dbConfig?: import("./types").DbConfig) => Promise<number>;
@@ -58,6 +85,12 @@ declare const _default: {
58
85
  closePool: (config: import("./types").DbConfig) => Promise<void>;
59
86
  closeAllPools: () => Promise<void>;
60
87
  getLogger: () => import("./types").Logger;
88
+ getPoolStats: (dbConfig?: import("./types").DbConfig) => Promise<{
89
+ activeConnections: any;
90
+ idleConnections: any;
91
+ totalConnections: any;
92
+ waitingRequests: any;
93
+ }>;
61
94
  };
62
95
  transactionManager: {
63
96
  setInstance: (instance: TransactionCRUD) => void;
@@ -66,6 +99,14 @@ declare const _default: {
66
99
  hasActiveTransaction: () => boolean;
67
100
  };
68
101
  TransactionCRUD: typeof TransactionCRUD;
102
+ schema: {
103
+ tables(dbConfig?: import("./types").DbConfig): Promise<string[]>;
104
+ columns(tableName: string, dbConfig?: import("./types").DbConfig): Promise<import("./types").ColumnInfo[]>;
105
+ indexes(tableName: string, dbConfig?: import("./types").DbConfig): Promise<import("./types").IndexInfo[]>;
106
+ foreignKeys(tableName?: string, dbConfig?: import("./types").DbConfig): Promise<import("./types").ForeignKeyInfo[]>;
107
+ deleteOrder(dbConfig?: import("./types").DbConfig): Promise<string[]>;
108
+ };
109
+ performanceMonitor: import("./lib/performanceMonitor").PerformanceMonitor;
69
110
  find: (query: string, params?: any[], dbConfig?: import("./types").DbConfig) => Promise<any[]>;
70
111
  findCount: (query: string, params?: any[], dbConfig?: import("./types").DbConfig) => Promise<number>;
71
112
  insert: (table: string, data: Record<string, any>, dbConfig?: import("./types").DbConfig, debug?: boolean, isIgnore?: boolean) => Promise<any>;
@@ -113,5 +154,30 @@ declare const _default: {
113
154
  };
114
155
  };
115
156
  createTransaction: () => TransactionCRUD;
157
+ bulkInsert: (table: string, records: Record<string, any>[], options?: {
158
+ batchSize?: number;
159
+ ignore?: boolean;
160
+ }, dbConfig?: import("./types").DbConfig) => Promise<{
161
+ totalInserted: number;
162
+ batches: number;
163
+ firstInsertId?: number;
164
+ lastInsertId?: number;
165
+ }>;
166
+ upsert: (table: string, data: Record<string, any>, options: {
167
+ conflictKey: string | string[];
168
+ updateFields?: string[];
169
+ }, dbConfig?: import("./types").DbConfig) => Promise<{
170
+ action: "inserted" | "updated";
171
+ affectedRows: number;
172
+ insertId?: number;
173
+ }>;
174
+ bulkUpsert: (table: string, records: Record<string, any>[], options: {
175
+ conflictKey: string | string[];
176
+ updateFields?: string[];
177
+ batchSize?: number;
178
+ }, dbConfig?: import("./types").DbConfig) => Promise<{
179
+ totalAffected: number;
180
+ batches: number;
181
+ }>;
116
182
  };
117
183
  export default _default;
package/dist/index.js CHANGED
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
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;
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.bulkUpsert = exports.upsert = exports.bulkInsert = exports.delete = exports._delete = exports.update = exports.insert = exports.findCount = exports.find = exports.performanceMonitor = exports.schema = exports.TransactionCRUD = exports.transactionManager = exports.connectionManager = void 0;
40
40
  const connectionManager_1 = __importDefault(require("./lib/connectionManager"));
41
41
  exports.connectionManager = connectionManager_1.default;
42
42
  const crud = __importStar(require("./lib/crud"));
@@ -44,6 +44,10 @@ const TransactionCRUD_1 = __importDefault(require("./lib/TransactionCRUD"));
44
44
  exports.TransactionCRUD = TransactionCRUD_1.default;
45
45
  const transactionManager_1 = __importDefault(require("./lib/transactionManager"));
46
46
  exports.transactionManager = transactionManager_1.default;
47
+ const schema_1 = __importDefault(require("./lib/schema"));
48
+ exports.schema = schema_1.default;
49
+ const performanceMonitor_1 = __importDefault(require("./lib/performanceMonitor"));
50
+ exports.performanceMonitor = performanceMonitor_1.default;
47
51
  // CRUD Operations (Non-transactional)
48
52
  exports.find = crud.find;
49
53
  exports.findCount = crud.findCount;
@@ -51,6 +55,10 @@ exports.insert = crud.insert;
51
55
  exports.update = crud.update;
52
56
  exports._delete = crud.delete;
53
57
  exports.delete = exports._delete;
58
+ // Bulk Operations
59
+ exports.bulkInsert = crud.bulkInsert;
60
+ exports.upsert = crud.upsert;
61
+ exports.bulkUpsert = crud.bulkUpsert;
54
62
  // Query Builder - Full names
55
63
  exports.buildAndExecuteSelectQuery = crud.buildAndExecuteSelectQuery;
56
64
  exports.buildAndExecuteUpdateQuery = crud.buildAndExecuteUpdateQuery;
@@ -73,6 +81,8 @@ exports.default = {
73
81
  connectionManager: connectionManager_1.default,
74
82
  transactionManager: transactionManager_1.default,
75
83
  TransactionCRUD: TransactionCRUD_1.default,
84
+ schema: schema_1.default,
85
+ performanceMonitor: performanceMonitor_1.default,
76
86
  find: exports.find,
77
87
  findCount: exports.findCount,
78
88
  insert: exports.insert,
@@ -89,5 +99,8 @@ exports.default = {
89
99
  deleteWhere: exports.deleteWhere,
90
100
  remove: exports.remove,
91
101
  utils: exports.utils,
92
- createTransaction: exports.createTransaction
102
+ createTransaction: exports.createTransaction,
103
+ bulkInsert: exports.bulkInsert,
104
+ upsert: exports.upsert,
105
+ bulkUpsert: exports.bulkUpsert
93
106
  };
@@ -31,6 +31,17 @@ declare const connectionManager: {
31
31
  * Get logger instance
32
32
  */
33
33
  getLogger: () => Logger;
34
+ /**
35
+ * Get connection pool statistics
36
+ * @param dbConfig - Optional database configuration
37
+ * @returns Connection pool stats
38
+ */
39
+ getPoolStats: (dbConfig?: DbConfig) => Promise<{
40
+ activeConnections: any;
41
+ idleConnections: any;
42
+ totalConnections: any;
43
+ waitingRequests: any;
44
+ }>;
34
45
  };
35
46
  export default connectionManager;
36
47
  export { connectionManager };
@@ -137,7 +137,36 @@ const connectionManager = {
137
137
  /**
138
138
  * Get logger instance
139
139
  */
140
- getLogger: () => logger
140
+ getLogger: () => logger,
141
+ /**
142
+ * Get connection pool statistics
143
+ * @param dbConfig - Optional database configuration
144
+ * @returns Connection pool stats
145
+ */
146
+ getPoolStats: async (dbConfig) => {
147
+ const conf = dbConfig || defaultConfig;
148
+ if (!conf || !conf.database) {
149
+ throw new Error('Database configuration missing');
150
+ }
151
+ const key = getPoolKey(conf);
152
+ const pool = pools.get(key);
153
+ if (!pool) {
154
+ return {
155
+ activeConnections: 0,
156
+ idleConnections: 0,
157
+ totalConnections: 0,
158
+ waitingRequests: 0
159
+ };
160
+ }
161
+ // Access pool internals (mysql2 specific)
162
+ const poolInfo = pool.pool;
163
+ return {
164
+ activeConnections: poolInfo?._acquiringConnections?.length || 0,
165
+ idleConnections: poolInfo?._freeConnections?.length || 0,
166
+ totalConnections: poolInfo?._allConnections?.length || 0,
167
+ waitingRequests: poolInfo?._connectionQueue?.length || 0
168
+ };
169
+ }
141
170
  };
142
171
  exports.connectionManager = connectionManager;
143
172
  exports.default = connectionManager;
@@ -36,6 +36,31 @@ export declare const insert: (table: string, data: Record<string, any>, dbConfig
36
36
  export declare const update: (table: string, data: Record<string, any>, query: string, dbConfig?: DbConfig, debug?: boolean) => Promise<number>;
37
37
  export declare const _delete: (query: string, table?: string, dbConfig?: DbConfig) => Promise<number>;
38
38
  export { _delete as delete };
39
+ export declare const bulkInsert: (table: string, records: Record<string, any>[], options?: {
40
+ batchSize?: number;
41
+ ignore?: boolean;
42
+ }, dbConfig?: DbConfig) => Promise<{
43
+ totalInserted: number;
44
+ batches: number;
45
+ firstInsertId?: number;
46
+ lastInsertId?: number;
47
+ }>;
48
+ export declare const upsert: (table: string, data: Record<string, any>, options: {
49
+ conflictKey: string | string[];
50
+ updateFields?: string[];
51
+ }, dbConfig?: DbConfig) => Promise<{
52
+ action: "inserted" | "updated";
53
+ affectedRows: number;
54
+ insertId?: number;
55
+ }>;
56
+ export declare const bulkUpsert: (table: string, records: Record<string, any>[], options: {
57
+ conflictKey: string | string[];
58
+ updateFields?: string[];
59
+ batchSize?: number;
60
+ }, dbConfig?: DbConfig) => Promise<{
61
+ totalAffected: number;
62
+ batches: number;
63
+ }>;
39
64
  export declare const buildAndExecuteSelectQuery: (options: SelectOptions, dbConfig?: DbConfig) => Promise<any[]>;
40
65
  export declare const buildAndExecuteUpdateQuery: (options: UpdateOptions, dbConfig?: DbConfig) => Promise<number>;
41
66
  export declare const buildAndExecuteDeleteQuery: (options: DeleteOptions, dbConfig?: DbConfig) => Promise<number>;