Skip to main content

capy_db/
seeds.rs

1use capy_core::{AppConfig, AppContext, AppError, Result};
2use sea_orm::{DatabaseTransaction, TransactionTrait};
3use std::{future::Future, pin::Pin, sync::Arc};
4
5/// Database transaction and typed settings for explicit application-owned development data.
6pub struct SeedContext<'a> {
7    /// Use this transaction for every seed write; do not acquire another connection.
8    pub transaction: &'a DatabaseTransaction,
9    /// Resolved application settings; only development and test may execute seeds.
10    pub config: &'a AppConfig,
11}
12
13/// A seed future borrowing the transaction for the duration of the callback.
14pub type SeedFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
15
16/// An explicit application-owned seed callback. All writes share one transaction.
17#[derive(Clone)]
18pub struct Seeds(Arc<dyn for<'a> Fn(SeedContext<'a>) -> SeedFuture<'a> + Send + Sync>);
19
20impl Seeds {
21    /// Register ordinary Rust seeding code. Make repeated calls idempotent using stable keys.
22    pub fn new(
23        seed: impl for<'a> Fn(SeedContext<'a>) -> SeedFuture<'a> + Send + Sync + 'static,
24    ) -> Self {
25        Self(Arc::new(seed))
26    }
27
28    /// Reject production/unknown environments before executing application code.
29    pub fn validate_environment(config: &AppConfig) -> Result<()> {
30        if !matches!(config.app.environment.as_str(), "development" | "test") {
31            return Err(AppError::Configuration("Development seeds are disabled outside development/test. Use an explicit reviewed application migration or administration command for production data.".into()));
32        }
33        Ok(())
34    }
35
36    /// Run atomically; failure or cancellation rolls back transaction-owned writes.
37    /// External side effects cannot be rolled back: use transactional job dispatch instead.
38    pub async fn run(&self, context: &AppContext) -> Result<()> {
39        Self::validate_environment(&context.config)?;
40        let transaction = context.db.begin().await?;
41        (self.0)(SeedContext {
42            transaction: &transaction,
43            config: &context.config,
44        })
45        .await?;
46        transaction.commit().await?;
47        Ok(())
48    }
49}