capy-db 0.10.0

SeaORM database connections and explicit migrations for Capy.
Documentation
use capy_core::{AppConfig, AppContext, AppError, Result};
use sea_orm::{DatabaseTransaction, TransactionTrait};
use std::{future::Future, pin::Pin, sync::Arc};

/// Database transaction and typed settings for explicit application-owned development data.
pub struct SeedContext<'a> {
    /// Use this transaction for every seed write; do not acquire another connection.
    pub transaction: &'a DatabaseTransaction,
    /// Resolved application settings; only development and test may execute seeds.
    pub config: &'a AppConfig,
}

/// A seed future borrowing the transaction for the duration of the callback.
pub type SeedFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;

/// An explicit application-owned seed callback. All writes share one transaction.
#[derive(Clone)]
pub struct Seeds(Arc<dyn for<'a> Fn(SeedContext<'a>) -> SeedFuture<'a> + Send + Sync>);

impl Seeds {
    /// Register ordinary Rust seeding code. Make repeated calls idempotent using stable keys.
    pub fn new(
        seed: impl for<'a> Fn(SeedContext<'a>) -> SeedFuture<'a> + Send + Sync + 'static,
    ) -> Self {
        Self(Arc::new(seed))
    }

    /// Reject production/unknown environments before executing application code.
    pub fn validate_environment(config: &AppConfig) -> Result<()> {
        if !matches!(config.app.environment.as_str(), "development" | "test") {
            return Err(AppError::Configuration("Development seeds are disabled outside development/test. Use an explicit reviewed application migration or administration command for production data.".into()));
        }
        Ok(())
    }

    /// Run atomically; failure or cancellation rolls back transaction-owned writes.
    /// External side effects cannot be rolled back: use transactional job dispatch instead.
    pub async fn run(&self, context: &AppContext) -> Result<()> {
        Self::validate_environment(&context.config)?;
        let transaction = context.db.begin().await?;
        (self.0)(SeedContext {
            transaction: &transaction,
            config: &context.config,
        })
        .await?;
        transaction.commit().await?;
        Ok(())
    }
}