Skip to main content

pgdo/
runtime.rs

1//! Discover and use PostgreSQL installations.
2//!
3//! You may have many versions of PostgreSQL installed on a system. For example,
4//! on an Ubuntu system, they may be in `/usr/lib/postgresql/*`. On macOS using
5//! Homebrew, you may find them in `/usr/local/Cellar/postgresql@*`. [`Runtime`]
6//! represents one such runtime; and the [`strategy`] module has tools for
7//! finding and selecting runtimes.
8
9mod cache;
10pub mod constraint;
11mod error;
12pub mod strategy;
13
14use std::env;
15use std::ffi::OsStr;
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use crate::util;
20use crate::version;
21pub use error::RuntimeError;
22
23/// The oldest version of PostgreSQL that pgdo supports.
24///
25/// The rule: this is the oldest major version still supported by the
26/// PostgreSQL project, or 15, whichever is greater. Bump it in the first
27/// release after a major version reaches end-of-life; see the [PostgreSQL
28/// "Versioning Policy" page][versioning] for dates.
29///
30/// [versioning]: https://www.postgresql.org/support/versioning/
31pub const MINIMUM_VERSION: version::Version = version::Version::Post10(15, 0);
32
33/// Does pgdo support the given version of PostgreSQL?
34///
35/// This is pgdo's policy, separate from the [`version`] module, which can parse
36/// and represent any version of PostgreSQL. See [`MINIMUM_VERSION`].
37///
38/// Note that [`version::Version`] orders all pre-10 versions before 10 and
39/// later, so a plain comparison works across both versioning schemes.
40pub fn is_supported<V: Into<version::Version>>(version: V) -> bool {
41    version.into() >= MINIMUM_VERSION
42}
43
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct Runtime {
46    /// Path to the directory containing the `pg_ctl` executable and other
47    /// PostgreSQL binaries.
48    pub bindir: PathBuf,
49
50    /// Version of this runtime.
51    pub version: version::Version,
52}
53
54impl Runtime {
55    pub fn new<P: AsRef<Path>>(bindir: P) -> Result<Self, RuntimeError> {
56        let version = cache::version(bindir.as_ref().join("pg_ctl"))?;
57        Ok(Self { bindir: bindir.as_ref().to_owned(), version })
58    }
59
60    /// Does pgdo support this runtime? See [`is_supported`].
61    pub fn is_supported(&self) -> bool {
62        is_supported(self.version)
63    }
64
65    /// Return a [`Command`] prepped to run the given `program` in this
66    /// PostgreSQL runtime.
67    ///
68    /// ```rust
69    /// # use pgdo::runtime::{RuntimeError, strategy::{Strategy, StrategyLike}};
70    /// # let runtime = Strategy::default().fallback().unwrap();
71    /// let version = runtime.execute("pg_ctl").arg("--version").output()?;
72    /// # Ok::<(), RuntimeError>(())
73    /// ```
74    ///
75    /// # Panics
76    ///
77    /// Panics if it's not possible to calculate `PATH`; see
78    /// [`env::join_paths`].
79    pub fn execute<T: AsRef<OsStr>>(&self, program: T) -> Command {
80        let mut command = Command::new(self.bindir.join(program.as_ref()));
81        command.env(
82            "PATH",
83            util::prepend_to_path(&self.bindir, env::var_os("PATH")).unwrap(),
84        );
85        command
86    }
87
88    /// Return a [`Command`] prepped to run the given `program` with this
89    /// PostgreSQL runtime at the front of `PATH`. This is very similar to
90    /// [`Self::execute`] except it does not qualify the given program name with
91    /// [`Self::bindir`].
92    ///
93    /// ```rust
94    /// # use pgdo::runtime::{RuntimeError, strategy::{Strategy, StrategyLike}};
95    /// # let runtime = Strategy::default().fallback().unwrap();
96    /// let hello = runtime.command("bash").arg("-c").arg("echo hello").output()?;
97    /// # Ok::<(), RuntimeError>(())
98    /// ```
99    ///
100    /// # Panics
101    ///
102    /// Panics if it's not possible to calculate `PATH`; see
103    /// [`env::join_paths`].
104    pub fn command<T: AsRef<OsStr>>(&self, program: T) -> Command {
105        let mut command = Command::new(program);
106        command.env(
107            "PATH",
108            util::prepend_to_path(&self.bindir, env::var_os("PATH")).unwrap(),
109        );
110        command
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::{is_supported, Runtime, RuntimeError, MINIMUM_VERSION};
117    use crate::version::{PartialVersion, Version};
118
119    use std::env;
120    use std::path::PathBuf;
121
122    type TestResult = Result<(), RuntimeError>;
123
124    fn find_bindir() -> PathBuf {
125        env::split_paths(&env::var_os("PATH").expect("PATH not set"))
126            .find(|path| path.join("pg_ctl").exists())
127            .expect("pg_ctl not on PATH")
128    }
129
130    #[test]
131    fn runtime_new() -> TestResult {
132        let bindir = find_bindir();
133        let pg = Runtime::new(&bindir)?;
134        assert_eq!(bindir, pg.bindir);
135        Ok(())
136    }
137
138    #[test]
139    fn supports_versions_from_minimum_version() {
140        let Version::Post10(major, minor) = MINIMUM_VERSION else {
141            panic!("expected minimum version to be 10 or later");
142        };
143        assert!(is_supported(MINIMUM_VERSION));
144        assert!(is_supported(Version::Post10(major, minor + 1)));
145        assert!(is_supported(Version::Post10(major + 1, 0)));
146        assert!(is_supported(PartialVersion::Post10m(major)));
147    }
148
149    #[test]
150    fn does_not_support_versions_before_minimum_version() {
151        let Version::Post10(major, _) = MINIMUM_VERSION else {
152            panic!("expected minimum version to be 10 or later");
153        };
154        assert!(!is_supported(Version::Post10(major - 1, 99)));
155        assert!(!is_supported(PartialVersion::Post10m(major - 1)));
156        assert!(!is_supported(Version::Pre10(9, 6, 24)));
157        assert!(!is_supported(PartialVersion::Pre10m(9, 6)));
158    }
159}