use std::time::Duration;
use crate::error::TenancyError;
use crate::tenant::Tenant;
#[cfg(feature = "postgres")]
pub mod postgres;
#[cfg(feature = "postgres")]
pub use self::pg::{SeedFn, TenantDatabase};
#[cfg(feature = "postgres")]
pub use postgres::PostgresTenantDatabase;
#[cfg(feature = "postgres")]
mod pg {
use std::future::Future;
use std::pin::Pin;
use async_trait::async_trait;
use sqlx::migrate::Migrator;
use sqlx::PgPool;
use crate::error::TenancyError;
use crate::tenant::Tenant;
pub type SeedFn = dyn for<'a> Fn(
&'a Tenant,
&'a PgPool,
) -> Pin<Box<dyn Future<Output = Result<(), TenancyError>> + Send + 'a>>
+ Send
+ Sync;
#[async_trait]
pub trait TenantDatabase: Send + Sync {
async fn connect(&self, tenant: &Tenant) -> Result<PgPool, TenancyError>;
async fn create(&self, tenant: &Tenant) -> Result<(), TenancyError>;
async fn drop_database(&self, tenant: &Tenant) -> Result<(), TenancyError>;
async fn migrate(&self, tenant: &Tenant, migrator: &Migrator) -> Result<(), TenancyError>;
async fn seed(&self, tenant: &Tenant, seed: &SeedFn) -> Result<(), TenancyError>;
}
}
pub struct DatabaseConfig {
pub url_template: String,
pub admin_url: String,
pub database_prefix: String,
pub pool_max_connections: u32,
pub idle_timeout: Duration,
}
impl DatabaseConfig {
pub fn database_name(&self, tenant: &Tenant) -> String {
tenant.database_name(&self.database_prefix)
}
pub fn tenant_url(&self, tenant: &Tenant) -> Result<String, TenancyError> {
if !self.url_template.contains("{database}") {
return Err(TenancyError::Config(
"url_template must contain the {database} placeholder".to_string(),
));
}
Ok(self
.url_template
.replace("{database}", &self.database_name(tenant)))
}
}