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
//! Admin executor for administrative commands
//!
//! This module provides the AdminExecutor which handles MongoDB administrative operations:
//! - Database management: show databases, use database
//! - Collection management: show collections
//! - Server commands and diagnostics
use futures::stream::TryStreamExt;
use mongodb::bson::{self, Document};
use tracing::info;
use crate::error::{ExecutionError, MongoshError, Result};
use crate::parser::AdminCommand;
use super::confirmation::confirm_admin_operation;
use super::context::ExecutionContext;
use super::result::{ExecutionResult, ExecutionStats, ResultData};
/// Executor for administrative commands
pub struct AdminExecutor {
/// Execution context
context: ExecutionContext,
}
impl AdminExecutor {
/// Create a new admin executor
///
/// # Arguments
/// * `context` - Execution context
///
/// # Returns
/// * `Result<Self>` - New executor or error
pub async fn new(context: ExecutionContext) -> Result<Self> {
Ok(Self { context })
}
/// Execute an administrative command
///
/// # Arguments
/// * `cmd` - Admin command to execute
///
/// # Returns
/// * `Result<ExecutionResult>` - Execution result or error
pub async fn execute(&self, cmd: AdminCommand) -> Result<ExecutionResult> {
// Check if operation requires confirmation
if !confirm_admin_operation(&cmd)? {
return Ok(ExecutionResult {
success: true,
data: ResultData::Message("Operation cancelled by user".to_string()),
stats: ExecutionStats::default(),
error: None,
});
}
match cmd {
AdminCommand::ShowDatabases => self.show_databases().await,
AdminCommand::ShowCollections => self.show_collections().await,
AdminCommand::UseDatabase(name) => self.use_database(name).await,
AdminCommand::ListIndexes(collection) => self.list_indexes(collection).await,
AdminCommand::CreateIndex {
collection,
keys,
options,
} => self.create_index(collection, keys, options).await,
AdminCommand::CreateIndexes {
collection,
indexes,
} => self.create_indexes(collection, indexes).await,
AdminCommand::DropIndex { collection, index } => {
self.drop_index(collection, index).await
}
AdminCommand::DropIndexes {
collection,
indexes,
} => self.drop_indexes(collection, indexes).await,
AdminCommand::DropCollection(collection) => self.drop_collection(collection).await,
AdminCommand::RenameCollection {
collection,
target,
drop_target,
} => self.rename_collection(collection, target, drop_target).await,
AdminCommand::CollectionStats { collection, scale } => {
self.collection_stats(collection, scale).await
}
_ => Err(MongoshError::NotImplemented(
"Admin command not yet implemented".to_string(),
)),
}
}
/// Show all databases
///
/// # Returns
/// * `Result<ExecutionResult>` - List of database names
async fn show_databases(&self) -> Result<ExecutionResult> {
info!("Listing databases");
let client = self.context.get_client().await?;
let db_names = client
.list_database_names()
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
info!("Found {} databases", db_names.len());
Ok(ExecutionResult {
success: true,
data: ResultData::List(db_names),
stats: ExecutionStats {
execution_time_ms: 0,
documents_returned: 0,
documents_affected: None,
},
error: None,
})
}
/// Show collections in current database
///
/// # Returns
/// * `Result<ExecutionResult>` - List of collection names
async fn show_collections(&self) -> Result<ExecutionResult> {
let db_name = self.context.get_current_database().await;
info!("Listing collections in database '{}'", db_name);
let db = self.context.get_database().await?;
let collection_names = db
.list_collection_names()
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
info!("Found {} collections", collection_names.len());
Ok(ExecutionResult {
success: true,
data: ResultData::List(collection_names),
stats: ExecutionStats {
execution_time_ms: 0,
documents_returned: 0,
documents_affected: None,
},
error: None,
})
}
/// Switch to a different database
///
/// # Arguments
/// * `name` - Database name
///
/// # Returns
/// * `Result<ExecutionResult>` - Success message
async fn use_database(&self, name: String) -> Result<ExecutionResult> {
info!("Switching to database '{}'", name);
self.context.set_current_database(name.clone()).await;
Ok(ExecutionResult {
success: true,
data: ResultData::Message(format!("switched to db {}", name)),
stats: ExecutionStats::default(),
error: None,
})
}
/// List indexes on a collection
///
/// # Arguments
/// * `collection` - Collection name
///
/// # Returns
/// * `Result<ExecutionResult>` - List of indexes
async fn list_indexes(&self, collection: String) -> Result<ExecutionResult> {
let db_name = self.context.get_current_database().await;
info!(
"Listing indexes for collection '{}' in database '{}'",
collection, db_name
);
let db = self.context.get_database().await?;
let coll: mongodb::Collection<Document> = db.collection(&collection);
// Get cursor for indexes
let mut cursor = coll
.list_indexes()
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
// Collect all indexes into a vector
let mut indexes = Vec::new();
while let Some(index) = cursor
.try_next()
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?
{
// Convert IndexModel to Document
let index_doc = bson::to_document(&index).map_err(|e| {
ExecutionError::QueryFailed(format!("Failed to convert index to document: {}", e))
})?;
indexes.push(index_doc);
}
let count = indexes.len();
info!("Found {} indexes", count);
Ok(ExecutionResult {
success: true,
data: ResultData::Documents(indexes),
stats: ExecutionStats {
execution_time_ms: 0,
documents_returned: count,
documents_affected: None,
},
error: None,
})
}
/// Parse index options from a document
///
/// # Arguments
/// * `options_doc` - Options document to parse
///
/// # Returns
/// * `Result<Option<mongodb::options::IndexOptions>>` - Parsed options or error
fn parse_index_options(
options_doc: Option<Document>,
) -> Result<Option<mongodb::options::IndexOptions>> {
match options_doc {
Some(opts) => {
let index_opts = bson::from_document(opts).map_err(|e| {
ExecutionError::InvalidParameters(format!("Invalid index options: {}", e))
})?;
Ok(Some(index_opts))
}
None => Ok(None),
}
}
/// Create an index on a collection
///
/// # Arguments
/// * `collection` - Collection name
/// * `keys` - Index keys document
/// * `options` - Optional index options
///
/// # Returns
/// * `Result<ExecutionResult>` - Index creation result
async fn create_index(
&self,
collection: String,
keys: Document,
options: Option<Document>,
) -> Result<ExecutionResult> {
use tracing::debug;
debug!(
"Creating index on collection '{}' with keys: {:?}",
collection, keys
);
let db = self.context.get_database().await?;
let coll: mongodb::Collection<Document> = db.collection(&collection);
// Parse and validate index options
let index_options = Self::parse_index_options(options)?;
// Create index model
let index_model = mongodb::IndexModel::builder()
.keys(keys)
.options(index_options)
.build();
// Create the index
let result = coll
.create_index(index_model)
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
debug!("Created index with name: {}", result.index_name);
Ok(ExecutionResult {
success: true,
data: ResultData::Message(format!("Created index: {}", result.index_name)),
stats: ExecutionStats::default(),
error: None,
})
}
/// Create multiple indexes on a collection
///
/// # Arguments
/// * `collection` - Collection name
/// * `indexes` - Vector of index specifications
///
/// # Returns
/// * `Result<ExecutionResult>` - Index creation result
async fn create_indexes(
&self,
collection: String,
indexes: Vec<Document>,
) -> Result<ExecutionResult> {
use tracing::debug;
debug!(
"Creating {} indexes on collection '{}'",
indexes.len(),
collection
);
let db = self.context.get_database().await?;
let coll: mongodb::Collection<Document> = db.collection(&collection);
// Create index models from documents
let mut index_models = Vec::new();
for (idx, index_doc) in indexes.into_iter().enumerate() {
// Extract keys - MongoDB requires "key" field (not "keys")
// Spec format: { key: { name: 1 }, name: "idx_name", unique: true, ... }
let keys = index_doc
.get_document("key")
.or_else(|_| index_doc.get_document("keys"))
.map_err(|_| {
ExecutionError::InvalidParameters(format!(
"Index specification at position {} must contain 'key' or 'keys' field",
idx
))
})?
.clone();
// Extract options - separate from keys
let options_doc = if let Ok(opts_doc) = index_doc.get_document("options") {
// Explicit options field
Some(opts_doc.clone())
} else {
// Extract root-level option fields
let mut opts = Document::new();
let option_fields = [
"name",
"unique",
"background",
"sparse",
"expireAfterSeconds",
"partialFilterExpression",
"collation",
"weights",
"default_language",
"language_override",
"textIndexVersion",
"2dsphereIndexVersion",
"bits",
"min",
"max",
"bucketSize",
"storageEngine",
"wildcardProjection",
"hidden",
];
for field in &option_fields {
if let Some(value) = index_doc.get(*field) {
opts.insert(*field, value.clone());
}
}
if !opts.is_empty() { Some(opts) } else { None }
};
// Parse options with proper error handling
let index_options = Self::parse_index_options(options_doc).map_err(|e| {
ExecutionError::InvalidParameters(format!(
"Invalid options for index at position {}: {}",
idx, e
))
})?;
let index_model = mongodb::IndexModel::builder()
.keys(keys)
.options(index_options)
.build();
index_models.push(index_model);
}
// Create the indexes
let result = coll
.create_indexes(index_models)
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
let index_names = result.index_names.join(", ");
debug!(
"Created {} indexes: {}",
result.index_names.len(),
index_names
);
Ok(ExecutionResult {
success: true,
data: ResultData::Message(format!("Created indexes: {}", index_names)),
stats: ExecutionStats::default(),
error: None,
})
}
/// Drop a single index from a collection
///
/// # Arguments
/// * `collection` - Collection name
/// * `index` - Index name to drop
///
/// # Returns
/// * `Result<ExecutionResult>` - Index drop result
async fn drop_index(&self, collection: String, index: String) -> Result<ExecutionResult> {
use tracing::debug;
debug!(
"Dropping index '{}' from collection '{}'",
index, collection
);
let db = self.context.get_database().await?;
let coll: mongodb::Collection<Document> = db.collection(&collection);
// Drop the index
coll.drop_index(index.clone())
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
debug!("Dropped index '{}'", index);
Ok(ExecutionResult {
success: true,
data: ResultData::Message(format!("Dropped index: {}", index)),
stats: ExecutionStats::default(),
error: None,
})
}
/// Drop multiple indexes from a collection
///
/// # Arguments
/// * `collection` - Collection name
/// * `indexes` - Optional list of index names to drop (None = drop all)
///
/// # Returns
/// * `Result<ExecutionResult>` - Index drop result
async fn drop_indexes(
&self,
collection: String,
indexes: Option<Vec<String>>,
) -> Result<ExecutionResult> {
use tracing::debug;
let db = self.context.get_database().await?;
let coll: mongodb::Collection<Document> = db.collection(&collection);
match indexes {
None => {
// Drop all indexes except _id_
debug!("Dropping all indexes from collection '{}'", collection);
coll.drop_indexes()
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
debug!("Dropped all indexes from collection '{}'", collection);
Ok(ExecutionResult {
success: true,
data: ResultData::Message(format!(
"Dropped all indexes from collection '{}'",
collection
)),
stats: ExecutionStats::default(),
error: None,
})
}
Some(index_names) => {
// Drop specific indexes
debug!(
"Dropping {} indexes from collection '{}'",
index_names.len(),
collection
);
for index_name in &index_names {
coll.drop_index(index_name.clone())
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
}
let names = index_names.join(", ");
debug!("Dropped indexes: {}", names);
Ok(ExecutionResult {
success: true,
data: ResultData::Message(format!("Dropped indexes: {}", names)),
stats: ExecutionStats::default(),
error: None,
})
}
}
}
/// Drop a collection
///
/// # Arguments
/// * `collection` - Collection name to drop
///
/// # Returns
/// * `Result<ExecutionResult>` - Collection drop result
async fn drop_collection(&self, collection: String) -> Result<ExecutionResult> {
use tracing::debug;
debug!("Dropping collection '{}'", collection);
let db = self.context.get_database().await?;
let coll: mongodb::Collection<Document> = db.collection(&collection);
// Drop the collection
coll.drop()
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
debug!("Dropped collection '{}'", collection);
Ok(ExecutionResult {
success: true,
data: ResultData::Message(format!("Dropped collection: {}", collection)),
stats: ExecutionStats::default(),
error: None,
})
}
/// Rename a collection
///
/// # Arguments
/// * `collection` - Name of the collection to rename
/// * `target` - New name for the collection
/// * `drop_target` - Whether to drop the target collection if it exists
///
/// # Returns
/// * `Result<ExecutionResult>` - Collection rename result
async fn rename_collection(
&self,
collection: String,
target: String,
drop_target: bool,
) -> Result<ExecutionResult> {
use mongodb::bson::doc;
use tracing::debug;
debug!(
"Renaming collection '{}' to '{}' (dropTarget: {})",
collection, target, drop_target
);
let db = self.context.get_database().await?;
let db_name = db.name();
// Build the renameCollection command
// The command must be run on the admin database
let command = doc! {
"renameCollection": format!("{}.{}", db_name, collection),
"to": format!("{}.{}", db_name, target),
"dropTarget": drop_target,
};
// Execute the command on the admin database
let client = self.context.get_client().await?;
let admin_db = client.database("admin");
admin_db
.run_command(command)
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
debug!("Renamed collection '{}' to '{}'", collection, target);
Ok(ExecutionResult {
success: true,
data: ResultData::Message(format!(
"Renamed collection '{}' to '{}'",
collection, target
)),
stats: ExecutionStats::default(),
error: None,
})
}
/// Get collection statistics
///
/// # Arguments
/// * `collection` - Name of the collection
/// * `scale` - Optional scale factor for size values
///
/// # Returns
/// * `Result<ExecutionResult>` - Collection statistics
async fn collection_stats(
&self,
collection: String,
scale: Option<i32>,
) -> Result<ExecutionResult> {
use mongodb::bson::doc;
use tracing::debug;
debug!(
"Getting stats for collection '{}' with scale: {:?}",
collection, scale
);
let db = self.context.get_database().await?;
// Build the collStats command
let mut command = doc! {
"collStats": &collection,
};
if let Some(scale_value) = scale {
command.insert("scale", scale_value);
}
// Execute the command
let result = db
.run_command(command)
.await
.map_err(|e| ExecutionError::QueryFailed(e.to_string()))?;
debug!("Retrieved stats for collection '{}'", collection);
Ok(ExecutionResult {
success: true,
data: ResultData::Document(result),
stats: ExecutionStats::default(),
error: None,
})
}
}
#[cfg(test)]
mod tests {
#[tokio::test]
async fn test_admin_executor_creation() {
// This is a placeholder test - would need proper setup with ConnectionManager
// and SharedState to fully test
}
}