@@ -116,6 +116,21 @@ impl Cluster {
116116        self . datadir . is_dir ( )  && self . datadir . join ( "PG_VERSION" ) . is_file ( ) 
117117    } 
118118
119+     /// Returns the PostgreSQL version in use by a cluster. 
120+      /// 
121+      /// This returns the version from the file named `PG_VERSION` in the data 
122+      /// directory if it exists, otherwise this returns `None`. For PostgreSQL 
123+      /// versions before 10 this is typically (maybe always) the major and minor 
124+      /// version, e.g. 9.4 rather than 9.4.26. For version 10 and above it 
125+      /// appears to be just the major number, e.g. 14 rather than 14.2. 
126+      pub  fn  version ( & self )  -> Option < String >  { 
127+         let  version_file = self . datadir . join ( "PG_VERSION" ) ; 
128+         match  std:: fs:: read_to_string ( version_file)  { 
129+             Ok ( version)  => Some ( version. trim ( ) . to_owned ( ) ) , 
130+             Err ( _)  => None , 
131+         } 
132+     } 
133+ 
119134    /// Check if this cluster is running. 
120135     /// 
121136     /// Tries to distinguish carefully between "definitely running", "definitely 
@@ -455,6 +470,27 @@ mod tests {
455470        } 
456471    } 
457472
473+     #[ test]  
474+     fn  cluster_has_no_version_when_it_does_not_exist ( )  { 
475+         for  runtime in  Runtime :: find_on_path ( )  { 
476+             println ! ( "{:?}" ,  runtime) ; 
477+             let  cluster = Cluster :: new ( "some/path" ,  runtime) ; 
478+             assert_eq ! ( cluster. version( ) ,  None ) ; 
479+         } 
480+     } 
481+ 
482+     #[ test]  
483+     fn  cluster_has_version_when_it_does_exists ( )  { 
484+         let  data_dir = tempdir:: TempDir :: new ( "data" ) . unwrap ( ) ; 
485+         let  version_file = data_dir. path ( ) . join ( "PG_VERSION" ) ; 
486+         File :: create ( & version_file) . unwrap ( ) ; 
487+         for  runtime in  Runtime :: find_on_path ( )  { 
488+             println ! ( "{:?}" ,  runtime) ; 
489+             let  cluster = Cluster :: new ( & data_dir,  runtime) ; 
490+             assert ! ( matches!( cluster. version( ) ,  Some ( _) ) ) ; 
491+         } 
492+     } 
493+ 
458494    #[ test]  
459495    fn  cluster_has_pid_file ( )  { 
460496        let  data_dir = PathBuf :: from ( "/some/where" ) ; 
0 commit comments