ferroquent 0.0.1

A faithful port of Laravel's Eloquent ORM to Rust (facade crate)
Documentation
//! Full model lifecycle against live MySQL/MariaDB: create, hydrate, dirty-gated save, find,
//! query, timestamps, mass assignment, delete. Skipped when no DSN env var is set.

use ferroquent::prelude::*;

#[derive(Model, Clone, Debug, Default)]
struct User {
    id: u64,
    #[ferroquent(fillable)]
    name: String,
    #[ferroquent(fillable)]
    email: String,
    #[ferroquent(fillable)]
    votes: i32,
    created_at: Option<chrono::NaiveDateTime>,
    updated_at: Option<chrono::NaiveDateTime>,
    state: ModelState<User>,
}

async fn each_conn() -> Vec<std::sync::Arc<dyn Connection>> {
    let mut out = Vec::new();
    for var in ["FERROQUENT_TEST_MYSQL_DSN", "FERROQUENT_TEST_MARIADB_DSN"] {
        if let Ok(dsn) = std::env::var(var) {
            ferroquent::mysql::register();
            let config = ConnectionConfig::from_url(&dsn).unwrap();
            let pool = ferroquent::mysql::connector::connect(&config)
                .await
                .unwrap();
            let flavor = ferroquent::mysql::connector::detect_flavor(&config, &pool).await;
            out.push(std::sync::Arc::new(ferroquent::mysql::MySqlConnection::new(
                "test", flavor, pool,
            )) as std::sync::Arc<dyn Connection>);
        }
    }
    out
}

async fn setup(conn: &dyn Connection) {
    conn.statement("drop table if exists `users`", &[])
        .await
        .unwrap();
    conn.statement(
        "create table `users` (
            id bigint unsigned not null auto_increment primary key,
            name varchar(255) not null,
            email varchar(255) not null unique,
            votes int not null default 0,
            created_at datetime null,
            updated_at datetime null
        )",
        &[],
    )
    .await
    .unwrap();
}

#[tokio::test]
async fn model_lifecycle() {
    let conns = each_conn().await;
    if conns.is_empty() {
        eprintln!("SKIP: no DSN configured");
        return;
    }

    for conn in conns {
        let ex = conn.as_ref();
        setup(ex).await;

        // create() - mass-assign, insert, set the auto id, fill timestamps.
        let mut user = User::create(
            ex,
            [
                ("name".to_string(), Value::Str("Taylor".into())),
                ("email".to_string(), Value::Str("taylor@x.co".into())),
                ("votes".to_string(), Value::Int(10)),
            ],
        )
        .await
        .unwrap();
        assert!(user.id > 0);
        assert!(user.state().exists);
        assert!(user.state().was_recently_created);
        assert!(user.created_at.is_some(), "created_at timestamp set");
        assert!(user.is_clean(), "freshly saved model is clean");

        // Dirty-gated update: only the changed column is written.
        user.votes = 25;
        assert!(user.is_dirty());
        user.save(ex).await.unwrap();
        assert!(user.is_clean());

        // find() hydrates a fresh instance with the persisted values.
        let found = User::find(ex, user.id).await.unwrap().unwrap();
        assert_eq!(found.name, "Taylor");
        assert_eq!(found.votes, 25);
        assert!(found.state().exists);

        // A no-op save (nothing dirty) must not error and must not touch the row.
        let mut again = found.clone();
        again.save(ex).await.unwrap();

        // Query builder over the model.
        User::create(
            ex,
            [
                ("name".to_string(), Value::Str("Abigail".into())),
                ("email".to_string(), Value::Str("abi@x.co".into())),
                ("votes".to_string(), Value::Int(5)),
            ],
        )
        .await
        .unwrap();

        let mut q = User::query();
        q.where_("votes", ">", 8).order_by_desc("votes");
        let high = q.get(ex).await.unwrap();
        assert_eq!(high.len(), 1);
        assert_eq!(high[0].name, "Taylor");

        assert_eq!(User::query().count(ex).await.unwrap(), 2);

        // delete()
        let mut to_delete = User::find(ex, user.id).await.unwrap().unwrap();
        assert!(to_delete.delete(ex).await.unwrap());
        assert!(!to_delete.state().exists);
        assert_eq!(User::query().count(ex).await.unwrap(), 1);

        conn.statement("drop table if exists `users`", &[])
            .await
            .unwrap();
    }
}