feat(mongodb): rename collections from sidebar

This commit is contained in:
onenewcode authored and GitHub committed 2026-07-21 17:08:27 +08:00
1 parent 809500fd52
commit 9a83b46f00
26 files changed
+1105 -93

No files matched your search

+123
View File
@@ -203,6 +203,54 @@ pub async fn list_databases(client: &Client) -> Result<Vec<String>, String> {
client.list_database_names().await.map_err(|e| e.to_string())
}
/// MongoDB collection kind from `listCollections` (not GridFS buckets).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MongoCollectionKind {
Collection,
View,
Timeseries,
}
impl MongoCollectionKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Collection => "collection",
Self::View => "view",
Self::Timeseries => "timeseries",
}
}
pub fn from_driver_type(collection_type: &mongodb::results::CollectionType) -> Self {
match collection_type {
mongodb::results::CollectionType::View => Self::View,
mongodb::results::CollectionType::Timeseries => Self::Timeseries,
// Collection and any future non_exhaustive variants default to a renamable collection.
_ => Self::Collection,
}
}
}
/// Name + kind for a MongoDB collection/view/timeseries returned by full `listCollections`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MongoCollectionSpec {
pub name: String,
pub kind: MongoCollectionKind,
}
/// Full `listCollections` with type metadata (for sidebar rename gating, etc.).
pub async fn list_collection_specs(client: &Client, database: &str) -> Result<Vec<MongoCollectionSpec>, String> {
let mut cursor = client.database(database).list_collections().await.map_err(|e| e.to_string())?;
let mut specs = Vec::new();
while let Some(spec) = cursor.try_next().await.map_err(|e| e.to_string())? {
specs.push(MongoCollectionSpec {
name: spec.name,
kind: MongoCollectionKind::from_driver_type(&spec.collection_type),
});
}
Ok(specs)
}
/// Name-only listing (schema, GridFS helpers, and other callers that do not need type).
pub async fn list_collections(client: &Client, database: &str) -> Result<Vec<String>, String> {
client.database(database).list_collection_names().await.map_err(|e| e.to_string())
}
@@ -505,6 +553,39 @@ pub async fn drop_collection(client: &Client, database: &str, collection: &str)
client.database(database).collection::<Document>(collection).drop().await.map_err(|e| e.to_string())
}
/// Build the admin `renameCollection` command document for a same-database rename.
///
/// Collection (and database) names are identifiers and must be passed exactly as provided —
/// do not trim or otherwise normalize them before building the namespace.
pub fn rename_collection_command_document(database: &str, old_name: &str, new_name: &str) -> Result<Document, String> {
if database.is_empty() {
return Err("Database name is required".to_string());
}
if old_name.is_empty() {
return Err("Collection name is required".to_string());
}
if new_name.is_empty() {
return Err("New collection name is required".to_string());
}
if old_name == new_name {
return Err("New collection name must differ from the current name".to_string());
}
// MongoDB reserves system.* namespaces; reject them before exposing a rename that the server cannot perform.
if old_name.starts_with("system.") || new_name.starts_with("system.") {
return Err("System collections cannot be renamed".to_string());
}
Ok(doc! {
"renameCollection": format!("{database}.{old_name}"),
"to": format!("{database}.{new_name}"),
})
}
pub async fn rename_collection(client: &Client, database: &str, old_name: &str, new_name: &str) -> Result<(), String> {
let command = rename_collection_command_document(database, old_name, new_name)?;
client.database("admin").run_command(command).await.map_err(|e| e.to_string())?;
Ok(())
}
pub async fn list_indexes(client: &Client, database: &str, collection: &str) -> Result<Vec<IndexInfo>, String> {
let col = client.database(database).collection::<Document>(collection);
let mut cursor = col.list_indexes().await.map_err(|e| e.to_string())?;
@@ -1953,6 +2034,48 @@ mod tests {
assert!(error.contains("unknown field `upsert`"));
}
#[test]
fn rename_collection_command_uses_fully_qualified_names() {
let command = rename_collection_command_document("app", "users", "accounts").unwrap();
assert_eq!(command.get_str("renameCollection").unwrap(), "app.users");
assert_eq!(command.get_str("to").unwrap(), "app.accounts");
}
#[test]
fn rename_collection_command_rejects_invalid_names() {
assert!(rename_collection_command_document("", "users", "accounts").unwrap_err().contains("Database"));
assert!(rename_collection_command_document("app", "", "accounts").unwrap_err().contains("Collection"));
assert!(rename_collection_command_document("app", "users", "").unwrap_err().contains("New collection"));
assert!(rename_collection_command_document("app", "users", "users").unwrap_err().contains("differ"));
assert!(rename_collection_command_document("app", "system.views", "views_backup")
.unwrap_err()
.contains("System collections"));
assert!(rename_collection_command_document("app", "users", "system.users")
.unwrap_err()
.contains("System collections"));
}
#[test]
fn rename_collection_command_preserves_identifier_whitespace() {
let command = rename_collection_command_document("app", " users ", " renamed ").unwrap();
assert_eq!(command.get_str("renameCollection").unwrap(), "app. users ");
assert_eq!(command.get_str("to").unwrap(), "app. renamed ");
}
#[test]
fn rename_collection_command_does_not_drop_existing_target() {
// Existing target names must fail at the server instead of being overwritten.
let command = rename_collection_command_document("app", "users", "accounts").unwrap();
assert!(!command.contains_key("dropTarget"));
}
#[test]
fn mongo_collection_kind_as_str_is_stable_wire_value() {
assert_eq!(MongoCollectionKind::Collection.as_str(), "collection");
assert_eq!(MongoCollectionKind::View.as_str(), "view");
assert_eq!(MongoCollectionKind::Timeseries.as_str(), "timeseries");
}
#[test]
fn multi_seed_uri_removes_direct_connection_true_before_driver_parse() {
let uri =
+25 -10
View File
@@ -27,12 +27,14 @@ pub struct MongoGridFsBucketInfo {
pub total_bytes: i64,
}
fn cmp_names(left: &str, right: &str) -> std::cmp::Ordering {
let left_lower = left.to_lowercase();
let right_lower = right.to_lowercase();
left_lower.cmp(&right_lower).then_with(|| left.cmp(right))
}
fn sort_names(mut names: Vec<String>) -> Vec<String> {
names.sort_by(|left, right| {
let left_lower = left.to_lowercase();
let right_lower = right.to_lowercase();
left_lower.cmp(&right_lower).then_with(|| left.cmp(right))
});
names.sort_by(|left, right| cmp_names(left, right));
names
}
@@ -84,16 +86,23 @@ fn mongo_list_databases_unauthorized(error: &str) -> bool {
lower.contains("not authorized") && lower.contains("listdatabases")
}
fn mongo_collection_info(name: String) -> CollectionInfo {
fn mongo_collection_info(name: String, kind: mongo_driver::MongoCollectionKind) -> CollectionInfo {
CollectionInfo {
name: name.clone(),
id: name,
dimension: None,
kind: Some("collection".to_string()),
kind: Some(kind.as_str().to_string()),
bucket_name: None,
}
}
fn sort_mongo_collection_specs(
mut specs: Vec<mongo_driver::MongoCollectionSpec>,
) -> Vec<mongo_driver::MongoCollectionSpec> {
specs.sort_by(|left, right| cmp_names(&left.name, &right.name));
specs
}
pub(crate) fn mongo_gridfs_bucket_names(names: &[String]) -> Vec<String> {
use std::collections::BTreeSet;
@@ -204,9 +213,10 @@ pub async fn list_collections_core(
let connections = state.connections.read().await;
match connections.get(connection_id).ok_or("Not found")? {
PoolKind::MongoDb(client) => {
let names = sort_names(mongo_driver::list_collections(client, database).await?);
let specs = sort_mongo_collection_specs(mongo_driver::list_collection_specs(client, database).await?);
let names: Vec<String> = specs.iter().map(|spec| spec.name.clone()).collect();
let mut infos = mongo_bucket_infos(&names);
infos.extend(names.into_iter().map(mongo_collection_info));
infos.extend(specs.into_iter().map(|spec| mongo_collection_info(spec.name, spec.kind)));
Ok(infos)
}
PoolKind::Elasticsearch(client) => {
@@ -221,7 +231,12 @@ pub async fn list_collections_core(
let mut client = client.lock().await;
let names = sort_names(client.mongo_list_collections(database).await?);
let mut infos = mongo_bucket_infos(&names);
infos.extend(names.into_iter().map(mongo_collection_info));
// Legacy agent returns names only; treat every entry as a plain collection.
infos.extend(
names
.into_iter()
.map(|name| mongo_collection_info(name, mongo_driver::MongoCollectionKind::Collection)),
);
Ok(infos)
}
_ => Err("Not a MongoDB/Elasticsearch/vector connection".to_string()),
+16
View File
@@ -62,6 +62,22 @@ pub async fn mongo_drop_collection_core(
}
}
pub async fn mongo_rename_collection_core(
state: &AppState,
connection_id: &str,
database: &str,
collection: &str,
new_name: &str,
) -> Result<(), String> {
ensure_document_pool(state, connection_id).await?;
let connections = state.connections.read().await;
match connections.get(connection_id).ok_or("Not found")? {
PoolKind::MongoDb(client) => mongo_driver::rename_collection(client, database, collection, new_name).await,
PoolKind::Agent(_) => Err("MongoDB legacy agent does not support rename collection".to_string()),
_ => Err("Not a MongoDB connection".to_string()),
}
}
pub async fn mongo_server_version_core(
state: &AppState,
connection_id: &str,