mongodb_gridfs/bucket/
drop.rs

1use crate::bucket::GridFSBucket;
2use bson::Document;
3use mongodb::error::Result;
4
5impl GridFSBucket {
6    /**
7    Drops the files and chunks collections associated with this
8    bucket.
9    [Spec](https://github.com/mongodb/specifications/blob/master/source/gridfs/gridfs-spec.rst#dropping-an-entire-gridfs-bucket)
10     */
11    pub async fn drop(&self) -> Result<()> {
12        let dboptions = self.options.clone().unwrap_or_default();
13        let bucket_name = dboptions.bucket_name;
14        let file_collection = bucket_name.clone() + ".files";
15        let files = self.db.collection::<Document>(&file_collection);
16
17        // let drop_options = DropCollectionOptions::builder()
18        //     .write_concern(dboptions.write_concern.clone())
19        //     .build();
20
21        // FIXME: MongoError(Error { kind: CommandError(CommandError { code: 14, code_name: "TypeMismatch", message: "\"writeConcern\" had the wrong type. Expected object, found null", labels: [] }), labels: [] })
22        files.drop(None).await?;
23
24        let chunk_collection = bucket_name + ".chunks";
25        let chunks = self.db.collection::<Document>(&chunk_collection);
26
27        //        let drop_options = DropCollectionOptions::default(); //  builder()
28        // .write_concern(dboptions.write_concern)
29        // .build();
30
31        chunks.drop(None).await?;
32
33        Ok(())
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::GridFSBucket;
40    use crate::{options::GridFSBucketOptions, GridFSError};
41
42    use mongodb::Client;
43    use mongodb::Database;
44    use uuid::Uuid;
45    fn db_name_new() -> String {
46        "test_".to_owned()
47            + Uuid::new_v4()
48                .hyphenated()
49                .encode_lower(&mut Uuid::encode_buffer())
50    }
51
52    #[tokio::test]
53    async fn drop_bucket() -> Result<(), GridFSError> {
54        let client = Client::with_uri_str(
55            &std::env::var("MONGO_URI").unwrap_or("mongodb://localhost:27017/".to_string()),
56        )
57        .await?;
58        let dbname = db_name_new();
59        let db: Database = client.database(&dbname);
60        let bucket = &GridFSBucket::new(db.clone(), Some(GridFSBucketOptions::default()));
61        bucket
62            .clone()
63            .upload_from_stream("test.txt", "test data".as_bytes(), None)
64            .await?;
65
66        let coll_list = db.list_collection_names(None).await?;
67        assert!(coll_list.contains(&"fs.files".to_string()));
68        assert!(coll_list.contains(&"fs.chunks".to_string()));
69
70        bucket.drop().await?;
71
72        let coll_list = db.list_collection_names(None).await?;
73        assert!(coll_list.is_empty());
74
75        db.drop(None).await?;
76        Ok(())
77    }
78}