11use bson:: { doc, Bson } ;
22
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+ } ;
48
59impl GridFsBucket {
610 /// Renames the file with the given 'id' to the provided `new_filename`. This method returns an
@@ -14,6 +18,22 @@ impl GridFsBucket {
1418 new_filename : new_filename. into ( ) ,
1519 }
1620 }
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+ }
1737}
1838
1939#[ cfg( feature = "sync" ) ]
@@ -25,6 +45,18 @@ impl crate::sync::gridfs::GridFsBucket {
2545 pub fn rename ( & self , id : Bson , new_filename : impl Into < String > ) -> Rename {
2646 self . async_bucket . rename ( id, new_filename)
2747 }
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+ }
2860}
2961
3062/// Renames a file. Construct with [`GridFsBucket::rename`].
@@ -51,3 +83,36 @@ impl<'a> Action for Rename<'a> {
5183 Ok ( ( ) )
5284 }
5385}
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