1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use std::str::FromStr;
use anyhow::{bail, Context};
use tokio::task::JoinHandle;
use tokio_postgres::config::Host;
use tokio_postgres::{Client, Config};
use url::Url;
use mz_ore::task;
use mz_postgres_util::make_tls;
pub fn config_url(config: &Config) -> Result<Url, anyhow::Error> {
let mut url = Url::parse("postgresql://").unwrap();
let host = match config.get_hosts() {
[] => "localhost".into(),
[Host::Tcp(host)] => host.clone(),
[Host::Unix(path)] => path.display().to_string(),
_ => bail!("Materialize URL cannot contain multiple hosts"),
};
url.set_host(Some(&host))
.context("parsing Materialize host")?;
url.set_port(Some(match config.get_ports() {
[] => 5432,
[port] => *port,
_ => bail!("Materialize URL cannot contain multiple ports"),
}))
.expect("known to be valid to set port");
if let Some(user) = config.get_user() {
url.set_username(user)
.expect("known to be valid to set username");
}
Ok(url)
}
pub async fn postgres_client(
url: &str,
) -> Result<(Client, JoinHandle<Result<(), tokio_postgres::Error>>), anyhow::Error> {
let tls = make_tls(&Config::from_str(url)?)?;
let (client, connection) = tokio_postgres::connect(url, tls)
.await
.context("connecting to postgres")?;
println!("Connecting to PostgreSQL server at {}...", url);
let handle = task::spawn(|| "postgres_client_task", connection);
Ok((client, handle))
}