Repository navigation
Expand file tree
/
Copy pathmongodb.ts
More file actions
1056 lines (916 loc) · 36.7 KB
/
Copy pathmongodb.ts
File metadata and controls
1056 lines (916 loc) · 36.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* MongoDB Database Provider
* Document database support using official MongoDB driver
*/
import { MongoClient, ObjectId, Binary, Decimal128, type Db, type Document, type MongoClientOptions } from "mongodb";
import { BaseDatabaseProvider } from "../../base-provider";
import {
type DatabaseConnection,
type TableSchema,
type ColumnSchema,
type QueryResult,
type HealthInfo,
type MaintenanceType,
type MaintenanceResult,
type ProviderOptions,
type ProviderCapabilities,
type ProviderLabels,
type PreparedQuery,
type QueryPrepareOptions,
type SlowQuery,
type ActiveSession,
type DatabaseOverview,
type PerformanceMetrics,
type SlowQueryStats,
type ActiveSessionDetails,
type TableStats,
type IndexStats,
type StorageStats,
} from "../../types";
import { DatabaseConfigError, ConnectionError, QueryError, mapDatabaseError } from "../../errors";
import { formatBytes } from "../../utils/pool-manager";
// ============================================================================
// Types
// ============================================================================
interface MongoQuery {
collection: string;
operation:
| "find"
| "findOne"
| "aggregate"
| "count"
| "distinct"
| "insertOne"
| "insertMany"
| "updateOne"
| "updateMany"
| "deleteOne"
| "deleteMany";
filter?: Document;
pipeline?: Document[];
update?: Document;
documents?: Document[];
options?: {
limit?: number;
skip?: number;
sort?: Document;
projection?: Document;
};
}
// Operations query() accepts. parseQuery() casts unvalidated JSON, so the
// operation value is re-checked against this set at runtime before dispatch.
const SUPPORTED_OPERATIONS: ReadonlySet<MongoQuery["operation"]> = new Set([
"find",
"findOne",
"aggregate",
"count",
"distinct",
"insertOne",
"insertMany",
"updateOne",
"updateMany",
"deleteOne",
"deleteMany",
]);
// Maintenance operations runMaintenance() accepts; validated the same way.
const SUPPORTED_MAINTENANCE_TYPES: ReadonlySet<MaintenanceType> = new Set([
"analyze",
"reindex",
"vacuum",
"optimize",
"check",
"kill",
]);
// ============================================================================
// MongoDB Provider
// ============================================================================
export class MongoDBProvider extends BaseDatabaseProvider {
private client: MongoClient | null = null;
private db: Db | null = null;
constructor(config: DatabaseConnection, options: ProviderOptions = {}) {
super(config, options);
this.validate();
}
// ============================================================================
// Provider Metadata
// ============================================================================
public override getCapabilities(): ProviderCapabilities {
return {
queryLanguage: "json",
supportsExplain: false,
supportsExternalQueryLimiting: false,
supportsCreateTable: false,
// The query language is JSON commands, not SQL, so the inline row editor's
// `UPDATE ... SET` has nothing here to run against (issue #269).
supportsInlineRowEdit: false,
// MongoDB has no foreign key constraint at all, so `getSchema()`'s empty
// `foreignKeys` is the engine's model rather than this database's shape. A
// reader told only "none were found" would hedge over causes that do not apply
// here (#414).
declaresForeignKeys: false,
supportsMaintenance: true,
maintenanceOperations: ["vacuum", "analyze", "check"],
supportsConnectionString: true,
defaultPort: 27017,
schemaRefreshPattern: '"operation"\\s*:\\s*"(insert|delete|update)',
};
}
public override getLabels(): ProviderLabels {
return {
entityName: "Collection",
entityNamePlural: "Collections",
rowName: "document",
rowNamePlural: "documents",
selectAction: "Find Documents",
generateAction: "Generate Find",
analyzeAction: "Validate Collection",
vacuumAction: "Compact Collection",
searchPlaceholder: "Search collections or fields...",
analyzeGlobalLabel: "Run Validate",
analyzeGlobalTitle: "Validate Collections",
analyzeGlobalDesc: "Checks collection structure and indexes integrity for all collections.",
vacuumGlobalLabel: "Run Compact",
vacuumGlobalTitle: "Compact Storage",
vacuumGlobalDesc: "Defragments and compacts collection storage to reclaim disk space.",
};
}
public override prepareQuery(query: string, options: QueryPrepareOptions = {}): PreparedQuery {
return { query, wasLimited: false, limit: options.limit || 100, offset: 0 };
}
// ============================================================================
// Validation
// ============================================================================
public validate(): void {
super.validate();
if (!this.config.connectionString) {
if (!this.config.host) {
throw new DatabaseConfigError("Host or connection string is required for MongoDB", "mongodb");
}
if (!this.config.database) {
throw new DatabaseConfigError("Database name is required for MongoDB", "mongodb");
}
}
}
// ============================================================================
// Connection Management
// ============================================================================
public async connect(): Promise<void> {
if (this.client && this.db) {
return;
}
try {
const connectionString = this.buildConnectionString();
const options: MongoClientOptions = {
maxPoolSize: this.poolConfig.max,
minPoolSize: this.poolConfig.min,
maxIdleTimeMS: this.poolConfig.idleTimeout,
connectTimeoutMS: this.poolConfig.acquireTimeout,
serverSelectionTimeoutMS: this.poolConfig.acquireTimeout,
};
this.client = new MongoClient(connectionString, options);
await this.client.connect();
// Get database name from connection string or config
const dbName = this.getDatabaseName();
this.db = this.client.db(dbName);
// Test connection
await this.db.command({ ping: 1 });
this.setConnected(true);
} catch (error) {
this.setError(error instanceof Error ? error : new Error(String(error)));
throw new ConnectionError(
`Failed to connect to MongoDB: ${error instanceof Error ? error.message : error}`,
"mongodb",
this.config.host,
this.config.port,
);
}
}
public async disconnect(): Promise<void> {
if (this.client) {
try {
await this.client.close();
} finally {
this.client = null;
this.db = null;
this.setConnected(false);
}
}
}
private buildConnectionString(): string {
if (this.config.connectionString) {
return this.config.connectionString;
}
const auth =
this.config.user && this.config.password
? `${encodeURIComponent(this.config.user)}:${encodeURIComponent(this.config.password)}@`
: "";
const host = this.config.host || "localhost";
const port = this.config.port || 27017;
const database = this.config.database || "test";
return `mongodb://${auth}${host}:${port}/${database}`;
}
private getDatabaseName(): string {
if (this.config.database) {
return this.config.database;
}
// Extract from connection string
if (this.config.connectionString) {
const match = this.config.connectionString.match(/\/([^/?]+)(\?|$)/);
if (match) {
return match[1];
}
}
return "test";
}
// ============================================================================
// Query Execution
// ============================================================================
/**
* Execute a MongoDB query
* Accepts JSON-formatted MQL queries
*
* @example
* // Find documents
* {"collection": "users", "operation": "find", "filter": {"age": {"$gt": 18}}, "options": {"limit": 10}}
*
* // Aggregate
* {"collection": "orders", "operation": "aggregate", "pipeline": [{"$group": {"_id": "$status", "count": {"$sum": 1}}}]}
*
* // Insert
* {"collection": "users", "operation": "insertOne", "documents": [{"name": "John", "email": "john@example.com"}]}
*/
public async query(queryStr: string): Promise<QueryResult> {
this.ensureConnected();
return this.trackQuery(async () => {
const { result, executionTime } = await this.measureExecution(async () => {
try {
const query = this.parseQuery(queryStr);
const collection = this.db!.collection(query.collection);
if (!SUPPORTED_OPERATIONS.has(query.operation)) {
throw new QueryError(`Unsupported operation: ${query.operation}`, "mongodb");
}
let rows: Document[] = [];
let affectedCount = 0;
switch (query.operation) {
case "find": {
const cursor = collection.find(query.filter || {});
if (query.options?.projection) cursor.project(query.options.projection);
if (query.options?.sort) cursor.sort(query.options.sort);
if (query.options?.skip) cursor.skip(query.options.skip);
if (query.options?.limit) cursor.limit(query.options.limit);
else cursor.limit(100); // Default limit
try {
rows = await cursor.toArray();
} finally {
await cursor.close();
}
break;
}
case "findOne": {
const doc = await collection.findOne(query.filter || {}, {
projection: query.options?.projection,
});
rows = doc ? [doc] : [];
break;
}
case "aggregate":
rows = await collection.aggregate(query.pipeline || []).toArray();
break;
case "count":
const count = await collection.countDocuments(query.filter || {});
rows = [{ count }];
break;
case "distinct":
const field = query.options?.projection ? Object.keys(query.options.projection)[0] : "_id";
const values = await collection.distinct(field, query.filter || {});
rows = values.map((v) => ({ [field]: v }));
break;
case "insertOne":
if (!query.documents || query.documents.length === 0) {
throw new QueryError("Document is required for insertOne", "mongodb");
}
const insertOneResult = await collection.insertOne(query.documents[0]);
rows = [{ insertedId: insertOneResult.insertedId, acknowledged: insertOneResult.acknowledged }];
affectedCount = insertOneResult.acknowledged ? 1 : 0;
break;
case "insertMany":
if (!query.documents || query.documents.length === 0) {
throw new QueryError("Documents are required for insertMany", "mongodb");
}
const insertManyResult = await collection.insertMany(query.documents);
rows = [{ insertedCount: insertManyResult.insertedCount, insertedIds: insertManyResult.insertedIds }];
affectedCount = insertManyResult.insertedCount;
break;
case "updateOne":
if (!query.update) {
throw new QueryError("Update document is required for updateOne", "mongodb");
}
const updateOneResult = await collection.updateOne(query.filter || {}, query.update);
rows = [{ matchedCount: updateOneResult.matchedCount, modifiedCount: updateOneResult.modifiedCount }];
affectedCount = updateOneResult.modifiedCount;
break;
case "updateMany":
if (!query.update) {
throw new QueryError("Update document is required for updateMany", "mongodb");
}
const updateManyResult = await collection.updateMany(query.filter || {}, query.update);
rows = [{ matchedCount: updateManyResult.matchedCount, modifiedCount: updateManyResult.modifiedCount }];
affectedCount = updateManyResult.modifiedCount;
break;
case "deleteOne":
const deleteOneResult = await collection.deleteOne(query.filter || {});
rows = [{ deletedCount: deleteOneResult.deletedCount }];
affectedCount = deleteOneResult.deletedCount;
break;
case "deleteMany":
const deleteManyResult = await collection.deleteMany(query.filter || {});
rows = [{ deletedCount: deleteManyResult.deletedCount }];
affectedCount = deleteManyResult.deletedCount;
break;
}
// Convert ObjectId to string for display
const serializedRows = rows.map((row) => this.serializeDocument(row));
return {
rows: serializedRows,
fields: serializedRows.length > 0 ? Object.keys(serializedRows[0]) : [],
affectedCount,
};
} catch (error) {
if (error instanceof QueryError) throw error;
throw mapDatabaseError(error, "mongodb", queryStr);
}
});
return {
rows: result.rows,
fields: result.fields,
rowCount: result.rows.length || result.affectedCount,
executionTime,
};
});
}
private parseQuery(queryStr: string): MongoQuery {
try {
// Try to parse as JSON
const parsed = JSON.parse(queryStr.trim());
if (!parsed.collection) {
throw new QueryError("Collection name is required in query", "mongodb");
}
if (!parsed.operation) {
throw new QueryError("Operation is required in query (find, findOne, aggregate, etc.)", "mongodb");
}
return parsed as MongoQuery;
} catch (error) {
if (error instanceof QueryError) throw error;
throw new QueryError(
`Invalid MongoDB query format. Expected JSON with "collection" and "operation" fields. Example: {"collection": "users", "operation": "find", "filter": {}}`,
"mongodb",
);
}
}
private serializeDocument(doc: Document): Record<string, unknown> {
const serialized: Record<string, unknown> = {};
for (const [key, value] of Object.entries(doc)) {
if (value === null || value === undefined) {
serialized[key] = value;
} else if (typeof value === "object") {
if (value instanceof ObjectId) {
serialized[key] = value.toString();
} else if (value instanceof Binary) {
serialized[key] = `<Binary: ${value.length()} bytes>`;
} else if (value instanceof Decimal128) {
serialized[key] = value.toString();
} else if (value instanceof Date) {
serialized[key] = value.toISOString();
} else if (Array.isArray(value)) {
serialized[key] = value.map((v) => (typeof v === "object" && v !== null ? this.serializeDocument(v) : v));
} else {
serialized[key] = this.serializeDocument(value as Document);
}
} else {
serialized[key] = value;
}
}
return serialized;
}
// ============================================================================
// Schema Operations
// ============================================================================
/**
* Get schema by listing collections and sampling documents to infer field types
*
* A VIEW is listed like any other object, with the three questions a view cannot
* answer simply not asked of it. `listCollections()` returns views, and MongoDB
* rejects `count`, `listIndexes` and `collStats` on one with
* `CommandNotSupportedOnView` (code 166) — so before #414 a single view in the
* database threw out of this loop and the user lost the WHOLE schema read, not just
* the view.
*
* Filtering views out of the listing was the alternative and it loses more than it
* fixes: a view is an object the user created, they see it in this product's own
* sidebar, and its fields are readable by exactly the document sample taken below.
* Hiding it would answer "your view does not exist" to keep three commands quiet.
*
* The guard reads `collInfo.type`, which the server has already told us, rather than
* wrapping the calls in `try/catch`. A catch cannot tell code 166 from a genuine
* failure without inspecting the error anyway, and the honest fallback for a caught
* count is not `0` — a view is not empty, its row count is unknown. Reading the type
* also spends no round trip on a command known to be refused.
*/
public async getSchema(): Promise<TableSchema[]> {
this.ensureConnected();
const allCollections = await this.db!.listCollections().toArray();
// Skip system collections and limit to 200 collections for performance
const collections = allCollections.filter((c) => !c.name.startsWith("system.")).slice(0, 200);
const schemas: TableSchema[] = [];
for (const collInfo of collections) {
const collName = collInfo.name;
const collection = this.db!.collection(collName);
const isView = collInfo.type === "view";
// Get document count. Left ABSENT on a view rather than reported as 0: a view
// holds no documents of its own, and a zero would read as "this view is empty".
const rowCount = isView ? undefined : await collection.estimatedDocumentCount();
// Get collection stats for size. A view stores nothing, so it has no size to
// state; the try/catch stays for a collection whose stats are unavailable.
let sizeBytes: number | undefined;
if (!isView) {
// Unchanged for a collection, including its long-standing fallback: a
// collection whose stats this role cannot read still reports 0 B.
sizeBytes = 0;
try {
const stats = await this.db!.command({ collStats: collName });
sizeBytes = stats.size || 0;
} catch {
// Stats might not be available
}
}
// Sample documents to infer schema. This works on a view exactly as it works on
// a collection, which is why a view is worth listing at all.
const sampleDocs = await collection.find({}).limit(100).toArray();
const columns = this.inferSchemaFromDocuments(sampleDocs);
// Get indexes. A view has none of its own — the indexes its query uses belong to
// the collection underneath it, and claiming them here would misattribute them.
const indexList = isView ? [] : await collection.indexes();
const indexes = indexList.map((idx) => ({
name: idx.name || "unknown",
columns: Object.keys(idx.key || {}),
unique: idx.unique || false,
}));
schemas.push({
name: collName,
...(rowCount === undefined ? {} : { rowCount }),
...(sizeBytes === undefined ? {} : { size: formatBytes(sizeBytes) }),
columns,
indexes,
foreignKeys: [], // MongoDB doesn't have foreign keys
});
}
return schemas;
}
private inferSchemaFromDocuments(docs: Document[]): ColumnSchema[] {
const fieldTypes = new Map<string, Set<string>>();
for (const doc of docs) {
this.extractFieldTypes(doc, "", fieldTypes);
}
const columns: ColumnSchema[] = [];
for (const [fieldName, types] of fieldTypes) {
const typeArray = Array.from(types);
const type = typeArray.length === 1 ? typeArray[0] : `mixed(${typeArray.join("|")})`;
columns.push({
name: fieldName,
type,
nullable: types.has("null") || types.has("undefined"),
isPrimary: fieldName === "_id",
defaultValue: undefined,
});
}
// Sort: _id first, then alphabetically
columns.sort((a, b) => {
if (a.name === "_id") return -1;
if (b.name === "_id") return 1;
return a.name.localeCompare(b.name);
});
return columns;
}
private extractFieldTypes(doc: Document, prefix: string, fieldTypes: Map<string, Set<string>>): void {
for (const [key, value] of Object.entries(doc)) {
const fieldName = prefix ? `${prefix}.${key}` : key;
if (!fieldTypes.has(fieldName)) {
fieldTypes.set(fieldName, new Set());
}
const type = this.getMongoType(value);
fieldTypes.get(fieldName)!.add(type);
// Don't recurse into nested objects for now (keep it flat)
// Uncomment below to include nested fields
// if (type === 'object' && value !== null && !Array.isArray(value)) {
// this.extractFieldTypes(value as Document, fieldName, fieldTypes);
// }
}
}
private getMongoType(value: unknown): string {
if (value === null) return "null";
if (value === undefined) return "undefined";
if (Array.isArray(value)) return "array";
if (value instanceof Date) return "date";
if (value instanceof ObjectId) return "objectId";
if (value instanceof Binary) return "binary";
if (value instanceof Decimal128) return "decimal";
if (typeof value === "object") return "object";
return typeof value;
}
// ============================================================================
// Health & Monitoring
// ============================================================================
public async getHealth(): Promise<HealthInfo> {
this.ensureConnected();
try {
const serverStatus = await this.db!.admin().serverStatus();
const dbStats = await this.db!.stats();
// Get current operations
const currentOps = await this.db!.admin().command({ currentOp: 1 });
const activeSessions: ActiveSession[] = (currentOps.inprog || [])
.slice(0, 10)
.map((op: Record<string, unknown>) => ({
pid: op.opid || "N/A",
user: op.client || "N/A",
database: op.ns || this.getDatabaseName(),
state: op.active ? "active" : "idle",
query: JSON.stringify(op.command || {}).substring(0, 100),
duration:
typeof op.microsecs_running === "number" && op.microsecs_running > 0
? `${(op.microsecs_running / 1000000).toFixed(2)}s`
: "N/A",
}));
const slowQueries: SlowQuery[] = [];
// Try to get slow query info from profiler
try {
const profilerDocs = await this.db!.collection("system.profile").find({}).sort({ ts: -1 }).limit(5).toArray();
for (const doc of profilerDocs) {
slowQueries.push({
query: JSON.stringify(doc.command || doc.query || {}).substring(0, 100),
calls: 1,
avgTime: `${doc.millis || 0}ms`,
});
}
} catch {
slowQueries.push({
query: "Profiler not enabled. Run db.setProfilingLevel(1) to enable.",
calls: 0,
avgTime: "N/A",
});
}
return {
activeConnections: serverStatus.connections?.current || 0,
databaseSize: formatBytes(dbStats.dataSize || 0),
cacheHitRatio: serverStatus.wiredTiger?.cache
? `${(
(1 -
(serverStatus.wiredTiger.cache["pages read into cache"] || 0) /
Math.max(1, serverStatus.wiredTiger.cache["pages requested from the cache"] || 1)) *
100
).toFixed(1)}%`
: "N/A",
slowQueries,
activeSessions,
};
} catch (error) {
this.logError("getHealth", error);
return {
activeConnections: 0,
databaseSize: "N/A",
cacheHitRatio: "N/A",
slowQueries: [{ query: "Error fetching health info", calls: 0, avgTime: "N/A" }],
activeSessions: [],
};
}
}
// ============================================================================
// Maintenance Operations
// ============================================================================
public async runMaintenance(type: MaintenanceType, target?: string): Promise<MaintenanceResult> {
this.ensureConnected();
const { result, executionTime } = await this.measureExecution(async () => {
try {
// Callers pass unvalidated JSON, so the type is re-checked before dispatch
// (same pattern as SUPPORTED_OPERATIONS in query()).
if (!SUPPORTED_MAINTENANCE_TYPES.has(type)) {
throw new QueryError(`Unsupported maintenance type for MongoDB: ${type}`, "mongodb");
}
switch (type) {
case "analyze":
// Validate collection
if (target) {
await this.db!.command({ validate: target });
return { success: true, message: `Validated collection: ${target}` };
} else {
const collections = await this.db!.listCollections().toArray();
for (const coll of collections) {
await this.db!.command({ validate: coll.name });
}
return { success: true, message: `Validated ${collections.length} collections` };
}
case "reindex":
// reIndex was removed in MongoDB 6.0+
return {
success: false,
message: "Reindex is not supported in MongoDB 6.0+. Use compact instead to defragment collections.",
};
case "vacuum":
case "optimize":
// Compact collection (similar to vacuum)
if (target) {
await this.db!.command({ compact: target });
return { success: true, message: `Compacted collection: ${target}` };
} else {
const collections = await this.db!.listCollections().toArray();
for (const coll of collections) {
try {
await this.db!.command({ compact: coll.name });
} catch {
// Some collections might not be compactable
}
}
return { success: true, message: `Compacted collections` };
}
case "check": {
// Run dbCheck — requires a collection name as target
if (!target) {
throw new QueryError("Collection name is required for dbCheck operation", "mongodb");
}
const checkResult = await this.db!.command({ dbCheck: target });
return {
success: true,
message: `Database check completed for ${target}: ${JSON.stringify(checkResult)}`,
};
}
case "kill":
if (!target) {
throw new QueryError("Operation ID is required for kill operation", "mongodb");
}
await this.db!.admin().command({ killOp: 1, op: parseInt(target, 10) });
return { success: true, message: `Killed operation: ${target}` };
}
} catch (error) {
if (error instanceof QueryError) throw error;
throw mapDatabaseError(error, "mongodb");
}
});
return {
success: result.success,
executionTime,
message: result.message,
};
}
// ============================================================================
// Monitoring Operations
// ============================================================================
public async getOverview(): Promise<DatabaseOverview> {
this.ensureConnected();
try {
const serverStatus = await this.db!.admin().serverStatus();
const dbStats = await this.db!.stats();
const serverInfo = await this.db!.admin().command({ buildInfo: 1 });
// Calculate uptime
const uptimeSeconds = serverStatus.uptime || 0;
const uptime = this.formatUptimeString(uptimeSeconds);
// Get collection count
const collections = await this.db!.listCollections().toArray();
// Get index count
let indexCount = 0;
for (const coll of collections) {
try {
const indexes = await this.db!.collection(coll.name).indexes();
indexCount += indexes.length;
} catch {
// Skip if can't get indexes
}
}
return {
version: `MongoDB ${serverInfo.version || "Unknown"}`,
uptime,
startTime: new Date(Date.now() - uptimeSeconds * 1000),
activeConnections: serverStatus.connections?.current || 0,
maxConnections: serverStatus.connections?.available
? serverStatus.connections.current + serverStatus.connections.available
: 100,
databaseSize: formatBytes(dbStats.dataSize || 0),
databaseSizeBytes: dbStats.dataSize || 0,
tableCount: collections.length,
indexCount,
};
} catch (error) {
this.logError("getOverview", error);
return {
version: "MongoDB Unknown",
uptime: "N/A",
activeConnections: 0,
maxConnections: 100,
databaseSize: "N/A",
databaseSizeBytes: 0,
tableCount: 0,
indexCount: 0,
};
}
}
public async getPerformanceMetrics(): Promise<PerformanceMetrics> {
this.ensureConnected();
try {
const serverStatus = await this.db!.admin().serverStatus();
// Calculate cache hit ratio from WiredTiger
let cacheHitRatio = 99;
if (serverStatus.wiredTiger?.cache) {
const pagesRead = serverStatus.wiredTiger.cache["pages read into cache"] || 0;
const pagesRequested = serverStatus.wiredTiger.cache["pages requested from the cache"] || 1;
cacheHitRatio = Math.max(0, Math.min(100, (1 - pagesRead / Math.max(1, pagesRequested)) * 100));
}
// Calculate queries per second from opcounters
const opcounters = serverStatus.opcounters || {};
const uptimeSeconds = serverStatus.uptime || 1;
const totalOps =
(opcounters.query || 0) + (opcounters.insert || 0) + (opcounters.update || 0) + (opcounters.delete || 0);
const queriesPerSecond = totalOps / uptimeSeconds;
// Get buffer pool usage (WiredTiger cache usage)
let bufferPoolUsage = 0;
if (serverStatus.wiredTiger?.cache) {
const bytesInCache = serverStatus.wiredTiger.cache["bytes currently in the cache"] || 0;
const maxCacheBytes = serverStatus.wiredTiger.cache["maximum bytes configured"] || 1;
bufferPoolUsage = (bytesInCache / maxCacheBytes) * 100;
}
return {
cacheHitRatio: Math.round(cacheHitRatio * 100) / 100,
queriesPerSecond: Math.round(queriesPerSecond * 100) / 100,
bufferPoolUsage: Math.round(bufferPoolUsage * 100) / 100,
deadlocks: 0, // MongoDB doesn't have traditional deadlocks
};
} catch (error) {
this.logError("getPerformanceMetrics", error);
return {
cacheHitRatio: 99,
queriesPerSecond: 0,
bufferPoolUsage: 0,
deadlocks: 0,
};
}
}
public async getSlowQueries(options?: { limit?: number }): Promise<SlowQueryStats[]> {
this.ensureConnected();
const limit = options?.limit ?? 10;
try {
// Try to get slow queries from system.profile
const profilerDocs = await this.db!.collection("system.profile")
.find({})
.sort({ millis: -1 })
.limit(limit)
.toArray();
return profilerDocs.map((doc) => ({
query: JSON.stringify(doc.command || doc.query || {}).substring(0, 500),
calls: 1,
totalTime: doc.millis || 0,
avgTime: doc.millis || 0,
rows: doc.nreturned || 0,
}));
} catch {
// Profiler not enabled or system.profile doesn't exist
return [];
}
}
public async getActiveSessions(options?: { limit?: number }): Promise<ActiveSessionDetails[]> {
this.ensureConnected();
const limit = options?.limit ?? 50;
try {
const currentOps = await this.db!.admin().command({ currentOp: 1, $all: true });
return (currentOps.inprog || []).slice(0, limit).map((op: Document) => {
const microseconds = op.microsecs_running || 0;
const durationMs = microseconds / 1000;
return {
pid: op.opid || "N/A",
user: op.client || "N/A",
database: op.ns?.split(".")[0] || this.getDatabaseName(),
applicationName: op.appName || undefined,
clientAddr: op.client?.split(":")[0] || undefined,
state: op.active ? "active" : "idle",
query: JSON.stringify(op.command || {}).substring(0, 500),
duration: this.formatDurationString(durationMs),
durationMs,
waitEventType: op.waitingForLock ? "Lock" : undefined,
waitEvent: op.lockStats ? "Acquiring lock" : undefined,
};
});
} catch (error) {
this.logError("getActiveSessions", error);
return [];
}
}
public async getTableStats(): Promise<TableStats[]> {
this.ensureConnected();
const collections = await this.db!.listCollections().toArray();
const stats: TableStats[] = [];
for (const collInfo of collections) {
const collName = collInfo.name;
try {
const collStats = await this.db!.command({ collStats: collName });
stats.push({
schemaName: this.getDatabaseName(),
tableName: collName,
rowCount: collStats.count || 0,
tableSize: formatBytes(collStats.size || 0),
tableSizeBytes: collStats.size || 0,
indexSize: formatBytes(collStats.totalIndexSize || 0),
totalSize: formatBytes((collStats.size || 0) + (collStats.totalIndexSize || 0)),
totalSizeBytes: (collStats.size || 0) + (collStats.totalIndexSize || 0),
});
} catch {
// Skip if can't get stats for this collection
}
}
// Sort by total size descending
return stats.sort((a, b) => b.totalSizeBytes - a.totalSizeBytes);
}
public async getIndexStats(): Promise<IndexStats[]> {
this.ensureConnected();
const collections = await this.db!.listCollections().toArray();
const stats: IndexStats[] = [];
for (const collInfo of collections) {
const collName = collInfo.name;
const collection = this.db!.collection(collName);
try {
// Get index stats using aggregation
const indexStatsDocs = await collection.aggregate([{ $indexStats: {} }]).toArray();
// Get index definitions
const indexes = await collection.indexes();
for (const idx of indexes) {
const indexStats = indexStatsDocs.find((s) => s.name === idx.name);
stats.push({
schemaName: this.getDatabaseName(),
tableName: collName,
indexName: idx.name || "unknown",
indexType: idx.key ? (Object.values(idx.key).includes("text") ? "text" : "btree") : "btree",
columns: Object.keys(idx.key || {}),
isUnique: idx.unique || false,
isPrimary: idx.name === "_id_",
indexSize: "N/A",
indexSizeBytes: 0,
scans: indexStats?.accesses?.ops || 0,
});
}
} catch {
// Skip if can't get index stats for this collection
}
}
return stats;
}
public async getStorageStats(): Promise<StorageStats[]> {
this.ensureConnected();
const stats: StorageStats[] = [];
try {
const dbStats = await this.db!.stats();
const serverStatus = await this.db!.admin().serverStatus();
// Database data size
stats.push({