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
65
66
67
68
69
70
71
use crate::errors::PuffResult;
pub use bb8_postgres;
use bb8_postgres::bb8::Pool;
use bb8_postgres::PostgresConnectionManager;
use std::time::Duration;
use crate::context::with_puff_context;
use crate::types::{Puff, Text};
pub use bb8_redis::redis::Cmd;
use clap::{Arg, Command};
use tokio_postgres::tls::NoTls;
use tracing::info;
#[derive(Clone)]
pub struct PostgresClient {
client: Pool<PostgresConnectionManager<NoTls>>,
}
impl Puff for PostgresClient {}
impl PostgresClient {
pub fn pool(&self) -> Pool<PostgresConnectionManager<NoTls>> {
return self.client.clone();
}
}
pub async fn new_postgres_async<T: Into<Text>>(
config: T,
check: bool,
pool_size: u32,
) -> PuffResult<PostgresClient> {
let manager = PostgresConnectionManager::new_from_stringlike(config.into(), NoTls)?;
let pool = Pool::builder().max_size(pool_size).build(manager).await?;
let local_pool = pool.clone();
if check {
info!("Checking Postgres connectivity...");
let check_fut = async {
let mut conn = local_pool.get().await?;
let my_conn = &mut *conn;
let _r = my_conn.query_one("SELECT 1", &[]).await?;
PuffResult::Ok(())
};
tokio::time::timeout(Duration::from_secs(5), check_fut).await??;
info!("Postgres looks good.");
}
Ok(PostgresClient { client: pool })
}
pub fn with_postgres<F: FnOnce(PostgresClient) -> T, T>(f: F) -> T {
with_puff_context(move |d| f(d.postgres()))
}
pub(crate) fn add_postgres_command_arguments(name: &str, command: Command) -> Command {
let name_lower = name.to_lowercase();
let name_upper = name.to_uppercase();
command.arg(
Arg::new(format!("{}_postgres_url", name_lower))
.long(format!("{}-postgres-url", name_lower))
.num_args(1)
.value_name(format!("{}_POSTGRES_URL", name_upper))
.env(format!("PUFF_{}_POSTGRES_URL", name_upper))
.default_value("postgres://postgres:password@localhost:5432/postgres")
.help(format!("Postgres pool configuration for '{}'.", name)),
)
}