postgres_util/
lib.rs

1use std::process::Command;
2use std::collections::HashMap;
3use regex::Regex;
4
5// extract numerical major and minor version from version string
6fn parse_version(s: &str) -> (String, String) {
7    let re_release = Regex::new(r"^PostgreSQL (\d+)\.(\d+).*$").unwrap();
8    let re_devel = Regex::new(r"^PostgreSQL (\d+)devel.*$").unwrap();
9    if let Some(caps) = re_release.captures(s) {
10        return (caps[1].to_string(), caps[2].to_string())
11    }
12    if let Some(caps) = re_devel.captures(s) {
13        return (caps[1].to_string(), String::from("devel"))
14    }
15    panic!("unable to parse version string");
16}
17
18// extract key and value from the form "KEY = VALUE"
19fn parse_line(s: &str) -> (&str, &str) {
20    let v: Vec<&str> = s.splitn(2, " = ").collect();
21
22    (v[0], v[1])
23}
24
25// parse "K = V" lines into HashMap
26fn parse_output(s: &str) -> HashMap<String, String> {
27    let mut map = HashMap::new();
28    for line in s.lines() {
29        let (k, v) = parse_line(line);
30        map.insert(k.to_string(), v.to_string());
31    }
32    map
33}
34
35// execute pg_config and return stdout as String
36fn pg_config() -> String {
37    let output = Command::new("pg_config")
38        .output()
39        .expect("failed to run pg_config");
40    assert!(output.status.success());
41
42    String::from_utf8(output.stdout).unwrap()
43}
44
45pub fn postgres() -> HashMap<String, String> {
46    let stdout = pg_config();
47    let mut map = parse_output(&stdout);
48
49    let (major, minor) = parse_version(&map["VERSION"]);
50    map.insert("VERSION_MAJOR".to_string(), major);
51    map.insert("VERSION_MINOR".to_string(), minor);
52    map
53}
54
55#[test]
56fn test1() {
57    dbg!(postgres());
58}