ferroquent 0.0.1

A faithful port of Laravel's Eloquent ORM to Rust (facade crate)
Documentation
//! # Ferroquent
//!
//! A faithful port of Laravel's Eloquent ORM to Rust. This facade crate re-exports the public API
//! from the workspace crates, hosts the prelude, and provides [`Ferroquent`] - the global
//! bootstrap that mirrors Laravel's `Capsule` (`setAsGlobal` + `bootEloquent`).
//!
//! See the workspace `README.md` for an overview and `docs/DEVIATIONS.md` for where Ferroquent
//! intentionally diverges from Eloquent.

use std::sync::OnceLock;

pub use ferroquent_core as core;
use ferroquent_core::error::{Error, Result};
use ferroquent_core::manager::{ConnectionHandle, DatabaseManager};
pub use ferroquent_model as model;

/// `#[derive(Model)]` - see [`ferroquent_model::Model`].
pub use ferroquent_macros::Model;
/// `#[derive(MorphTarget)]` - a closed enum backing a `MorphTo` relation.
pub use ferroquent_macros::MorphTarget;

#[cfg(feature = "cli")]
pub use ferroquent_cli as cli;
#[cfg(feature = "migrations")]
pub use ferroquent_migrations as migrations;
#[cfg(feature = "mysql")]
pub use ferroquent_mysql as mysql;
#[cfg(feature = "schema")]
pub use ferroquent_schema as schema;

/// A synchronous facade over the async API for scripts and CLIs - the reqwest pattern. Runs futures
/// to completion on an internal shared runtime, so callers never touch tokio directly.
///
/// ```no_run
/// # #[cfg(feature = "blocking")] {
/// # async fn work() -> ferroquent::core::error::Result<()> { Ok(()) }
/// let result = ferroquent::blocking::block_on(work());
/// # }
/// ```
///
/// Do not call from inside an existing tokio runtime (it would panic); use the async API there.
#[cfg(feature = "blocking")]
pub mod blocking {
    use std::future::Future;
    use std::sync::OnceLock;

    fn runtime() -> &'static tokio::runtime::Runtime {
        static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
        RT.get_or_init(|| {
            tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()
                .expect("failed to build Ferroquent blocking runtime")
        })
    }

    /// Run an async future to completion on Ferroquent's internal runtime.
    pub fn block_on<F: Future>(future: F) -> F::Output {
        runtime().block_on(future)
    }
}

/// The global connection manager (Laravel's `Capsule`). Set up with [`Ferroquent::boot`].
static MANAGER: OnceLock<DatabaseManager> = OnceLock::new();

/// The global bootstrap. Register drivers and connections once at startup, then resolve
/// connections anywhere via [`Ferroquent::connection`].
pub struct Ferroquent;

impl Ferroquent {
    /// Boot with a single default connection from a [`ConnectionConfig`](core::ConnectionConfig),
    /// registering the built-in drivers first. Idempotent for the built-in driver registration; the
    /// manager itself is set once.
    pub fn boot(config: core::ConnectionConfig) -> Result<()> {
        Self::register_builtin_drivers();
        let manager = DatabaseManager::new();
        manager.add_connection("default", config);
        MANAGER
            .set(manager)
            .map_err(|_| Error::config("Ferroquent::boot called more than once"))
    }

    /// Boot with a manager the caller has already populated (multiple named connections, extensions).
    pub fn boot_with(manager: DatabaseManager) -> Result<()> {
        Self::register_builtin_drivers();
        MANAGER
            .set(manager)
            .map_err(|_| Error::config("Ferroquent::boot called more than once"))
    }

    /// The global manager, or an error if [`boot`](Ferroquent::boot) has not been called.
    pub fn manager() -> Result<&'static DatabaseManager> {
        MANAGER
            .get()
            .ok_or_else(|| Error::config("Ferroquent is not booted; call Ferroquent::boot first"))
    }

    /// Resolve a connection by name (or the default when `None`).
    pub async fn connection(name: Option<&str>) -> Result<ConnectionHandle> {
        Self::manager()?.connection(name).await
    }

    fn register_builtin_drivers() {
        #[cfg(feature = "mysql")]
        ferroquent_mysql::register();
    }
}

/// The common imports for day-to-day use. Grows as milestones land.
pub mod prelude {
    pub use crate::MorphTarget;
    pub use crate::{Ferroquent, Model};
    pub use ferroquent_core::connection::{Connection, Executor, Transaction, transaction};
    pub use ferroquent_core::query::{QueryBuilder, record};
    pub use ferroquent_core::{
        BindingBucket, Bindings, Column, ConnectionConfig, DatabaseManager, Error, Expression,
        IntoColumn, IntoOperand, IntoValue, Operand, Result, Row, Value,
    };
    pub use ferroquent_model::{
        Builder, Cast, Event, Factory, FieldDef, FieldFlags, ModelExt, ModelPersist, ModelQuery,
        ModelState, Observer, Seeder, add_global_scope, model::Model as ModelTrait, observe, seed,
    };
}