1
1
use bson:: { doc, Bson } ;
2
2
3
- use crate :: { action:: action_impl, error:: Result , gridfs:: GridFsBucket } ;
3
+ use crate :: {
4
+ action:: action_impl,
5
+ error:: { ErrorKind , GridFsErrorKind , GridFsFileIdentifier , Result } ,
6
+ gridfs:: GridFsBucket ,
7
+ } ;
4
8
5
9
impl GridFsBucket {
6
10
/// Renames the file with the given 'id' to the provided `new_filename`. This method returns an
@@ -14,6 +18,22 @@ impl GridFsBucket {
14
18
new_filename : new_filename. into ( ) ,
15
19
}
16
20
}
21
+
22
+ /// Renames all revisions of the file with the given name to the provided `new_filename`. This
23
+ /// method returns an error if the name does not match any files in the bucket.
24
+ ///
25
+ /// `await` will return [`Result<()>`].
26
+ pub fn rename_by_name (
27
+ & self ,
28
+ filename : impl Into < String > ,
29
+ new_filename : impl Into < String > ,
30
+ ) -> RenameByName {
31
+ RenameByName {
32
+ bucket : self ,
33
+ filename : filename. into ( ) ,
34
+ new_filename : new_filename. into ( ) ,
35
+ }
36
+ }
17
37
}
18
38
19
39
#[ cfg( feature = "sync" ) ]
@@ -25,6 +45,18 @@ impl crate::sync::gridfs::GridFsBucket {
25
45
pub fn rename ( & self , id : Bson , new_filename : impl Into < String > ) -> Rename {
26
46
self . async_bucket . rename ( id, new_filename)
27
47
}
48
+
49
+ /// Renames all revisions of the file with the given name to the provided `new_filename`. This
50
+ /// method returns an error if the name does not match any files in the bucket.
51
+ ///
52
+ /// [`run`](RenameByName::run) will return [`Result<()>`].
53
+ pub fn rename_by_name (
54
+ & self ,
55
+ filename : impl Into < String > ,
56
+ new_filename : impl Into < String > ,
57
+ ) -> RenameByName {
58
+ self . async_bucket . rename_by_name ( filename, new_filename)
59
+ }
28
60
}
29
61
30
62
/// Renames a file. Construct with [`GridFsBucket::rename`].
@@ -51,3 +83,36 @@ impl<'a> Action for Rename<'a> {
51
83
Ok ( ( ) )
52
84
}
53
85
}
86
+
87
+ /// Renames a file selected by name. Construct with [`GridFsBucket::rename_by_name`].
88
+ #[ must_use]
89
+ pub struct RenameByName < ' a > {
90
+ bucket : & ' a GridFsBucket ,
91
+ filename : String ,
92
+ new_filename : String ,
93
+ }
94
+
95
+ #[ action_impl]
96
+ impl < ' a > Action for RenameByName < ' a > {
97
+ type Future = RenameByNameFuture ;
98
+
99
+ async fn execute ( self ) -> Result < ( ) > {
100
+ let count = self
101
+ . bucket
102
+ . files ( )
103
+ . update_many (
104
+ doc ! { "filename" : self . filename. clone( ) } ,
105
+ doc ! { "$set" : { "filename" : self . new_filename } } ,
106
+ )
107
+ . await ?
108
+ . matched_count ;
109
+ if count == 0 {
110
+ return Err ( ErrorKind :: GridFs ( GridFsErrorKind :: FileNotFound {
111
+ identifier : GridFsFileIdentifier :: Filename ( self . filename ) ,
112
+ } )
113
+ . into ( ) ) ;
114
+ }
115
+
116
+ Ok ( ( ) )
117
+ }
118
+ }
0 commit comments