Skip to content

Commit

Permalink
Update Cherry to support ConnectionOptions so that logging can be con…
Browse files Browse the repository at this point in the history
…trolled
  • Loading branch information
Ryan Miller committed Nov 29, 2022
1 parent 63300df commit 5c8b378
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 13 deletions.
2 changes: 1 addition & 1 deletion cherry-macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cherry-macros"
version = "0.8.5"
version = "0.8.6"
authors = ["moritz"]
edition = "2021"
description = "lightweight procedural macros bringing orm-like features to sqlx"
Expand Down
4 changes: 2 additions & 2 deletions cherry/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "cherry"
version = "0.8.5"
version = "0.8.6"
authors = ["bugslabx <bugslabx@gmail.com>"]
edition = "2021"
license = "MIT OR Apache-2.0"
Expand Down Expand Up @@ -63,7 +63,7 @@ serde = { version = "1.0.123", optional = true }
serde_derive = { version = "1.0.123", optional = true }

[dependencies.cherry-macros]
version = "0.8.5"
version = "0.8.6"
path = "../cherry-macros"

[dev-dependencies]
Expand Down
55 changes: 46 additions & 9 deletions cherry/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ use std::time::Duration;
use anyhow::anyhow;
use once_cell::sync::OnceCell;
use sqlx::pool::PoolOptions;
use crate::ConnectOptions;
use crate::sqlx::Database;

use crate::types::{Pool, Result};
use crate::types::{Pool, Result, };

static POOLS: OnceCell<BTreeMap<TypeId, Pool>> = OnceCell::new();

Expand All @@ -32,6 +34,28 @@ pub async fn setup_pools<T>(config: T) -> Result<()>
Ok(())
}

pub async fn setup_pools_with<T>(config: T) -> Result<()>
where T: IntoIterator<Item = (TypeId, PoolConfig,crate::ConnectOptions)>
{
if POOLS.get().is_none()
{
let mut pools = BTreeMap::new();
for (key, v,o) in config {
pools.insert(key, v.to_pool_with(o).await?);
}

POOLS.set(pools).map_err(|_| anyhow!("Failed to set pools."))?;
} else {
if cfg!(any(test, feature = "test")) {
return Ok(());
} else {
Err(anyhow!("Failed to set pools."))?;
}
}

Ok(())
}

pub fn get(type_id: TypeId) -> Result<&'static Pool> {
let value = POOLS.get()
.ok_or_else(|| anyhow!("Pools is empty."))?
Expand Down Expand Up @@ -64,6 +88,9 @@ pub struct PoolConfig {
pub connect_timeout: Option<u64>,
pub max_lifetime: Option<u64>,
pub idle_timeout: Option<u64>,
pub log_statements_level: Option<String>,
pub log_slow_queries_level: Option<String>,
pub log_slow_queries_duration: Option<Duration>,
// after_connect: None,
// before_acquire: None,
// after_release: None,
Expand All @@ -72,27 +99,37 @@ pub struct PoolConfig {

impl PoolConfig {

pub(crate) async fn to_pool_with(&self,options: ConnectOptions) -> Result<Pool> {
let pool_opts = self.pool_options();
Ok( pool_opts.connect_with(options).await?)
}

pub(crate) async fn to_pool(&self) -> Result<Pool> {
let mut opts = PoolOptions::new();
let pool_opts = self.pool_options();
Ok(pool_opts.connect(self.url.as_str() ).await?)
}

fn pool_options<D:Database>(&self) -> PoolOptions<D> {
let mut pool_opts = PoolOptions::new();
if let Some(v) = self.test_before_acquire {
opts = opts.test_before_acquire(v);
pool_opts = pool_opts.test_before_acquire(v);
}
if let Some(v) = self.max_connections {
opts = opts.max_connections(v);
pool_opts = pool_opts.max_connections(v);
}
if let Some(v) = self.min_connections {
opts = opts.min_connections(v);
pool_opts = pool_opts.min_connections(v);
}
if let Some(v) = self.connect_timeout {
opts = opts.connect_timeout(Duration::from_secs(v));
pool_opts = pool_opts.connect_timeout(Duration::from_secs(v));
}
if let Some(v) = self.max_lifetime {
opts = opts.max_lifetime(Duration::from_secs(v));
pool_opts = pool_opts.max_lifetime(Duration::from_secs(v));
}
if let Some(v) = self.idle_timeout {
opts = opts.idle_timeout(Duration::from_secs(v));
pool_opts = pool_opts.idle_timeout(Duration::from_secs(v));
}

Ok( opts.connect(self.url.as_str()).await? )
pool_opts
}
}
2 changes: 1 addition & 1 deletion cherry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub use cherry_macros::*;
pub use {
schema::Schema,
datasource::DataSource,
table::{Table,Insert,Patch,Db},
table::{Table,Insert,Patch,Db,ConnectOptions},
query::select::Select,
};

Expand Down
8 changes: 8 additions & 0 deletions cherry/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ pub type Db = sqlx::Postgres;
#[cfg(feature = "sqlite")]
pub type Db = sqlx::Sqlite;


#[cfg(feature = "mysql")]
pub type ConnectOptions = sqlx::mysql::MySqlConnectOptions;
#[cfg(feature = "postgres")]
pub type ConnectOptions = sqlx::postgres::PgConnectOptions;
#[cfg(feature = "sqlite")]
pub type ConnectOptions = sqlx::sqlite::SqliteConnectOptions;

/// A database table in which each row is identified by a unique ID.
#[async_trait]
pub trait Table : Schema
Expand Down

0 comments on commit 5c8b378

Please sign in to comment.