carbon_postgres_client/
lib.rs1use sqlx::{postgres::PgPoolOptions, Error, PgPool, Postgres};
2use sqlx_migrator::{
3 migrator::{Info, Migrate, Migrator},
4 Migration, Plan,
5};
6
7#[derive(Clone)]
8pub struct PgClient {
9 pub pool: PgPool,
10}
11
12impl juniper::Context for PgClient {}
13
14impl PgClient {
15 pub async fn new(url: &str, min_connections: u32, max_connections: u32) -> Result<Self, Error> {
16 let pool = PgPoolOptions::new()
17 .min_connections(min_connections)
18 .max_connections(max_connections)
19 .connect(url)
20 .await?;
21
22 Ok(Self { pool })
23 }
24
25 pub async fn migrate(
26 &self,
27 migrations: Vec<Box<dyn Migration<Postgres>>>,
28 ) -> Result<(), Error> {
29 let mut migrator = Migrator::<Postgres>::default();
30 migrator
31 .add_migrations(migrations)
32 .expect("Failed to add migrations");
33
34 let mut conn = self.pool.acquire().await?;
35 migrator
36 .run(&mut *conn, &Plan::apply_all())
37 .await
38 .expect("Failed to run migrations");
39
40 Ok(())
41 }
42}