use super::{PgConfig, PgError, PgPool, operation_metrics::Measurements};
use crate::setup::SetupContext;
use std::{collections::BTreeSet, future::Future, pin::Pin, sync::Arc};
pub type OperationFuture<'connection, T> =
Pin<Box<dyn Future<Output = Result<T, super::Error>> + Send + 'connection>>;
#[derive(Clone)]
pub struct PgOperations {
pool: PgPool,
operations: Vec<PgOperation>,
}
impl PgOperations {
pub fn pool(&self) -> &PgPool {
&self.pool
}
pub fn get(&self, name: &str) -> Option<PgOperation> {
self.operations
.iter()
.find(|operation| operation.name() == name)
.cloned()
}
}
#[derive(Clone)]
pub struct PgOperation {
pub(super) pool: PgPool,
pub(super) pool_name: Arc<str>,
pub(super) name: Arc<str>,
pub(super) metrics: Measurements,
}
impl PgOperation {
pub fn name(&self) -> &str {
&self.name
}
}
impl SetupContext {
pub async fn postgres_operations(
&mut self,
name: impl Into<String>,
config: PgConfig,
operations: &[&str],
) -> Result<PgOperations, PgError> {
validate_names(operations)?;
let name = name.into();
let pool = self.postgres(name.clone(), config).await?;
let measurements = super::operation_metrics::register(&self.metrics(), &name, operations)?;
let pool_name: Arc<str> = name.into();
let operations = operations
.iter()
.zip(measurements)
.map(|(name, metrics)| PgOperation {
pool: pool.clone(),
pool_name: pool_name.clone(),
name: (*name).into(),
metrics,
})
.collect();
Ok(PgOperations { pool, operations })
}
}
fn validate_names(names: &[&str]) -> Result<(), PgError> {
let mut unique = BTreeSet::new();
if names.is_empty() || names.len() > 32 {
return Err(PgError::Configuration);
}
for name in names {
if name.is_empty()
|| name.len() > 64
|| !unique.insert(name)
|| !name
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
{
return Err(PgError::Configuration);
}
}
Ok(())
}
#[cfg(test)]
#[path = "operations_test.rs"]
mod operations_test;