ferroquent 0.0.1

A faithful port of Laravel's Eloquent ORM to Rust (facade crate)
Documentation
//! Dot-nested eager loading (`with("posts.comments")`) against live MySQL/MariaDB.

use ferroquent::prelude::*;
use ferroquent_model::{BelongsTo, HasMany};

#[derive(Model, Clone, Debug, Default)]
struct User {
    id: u64,
    #[ferroquent(fillable)]
    name: String,
    posts: HasMany<Post>,
    state: ModelState<User>,
}

#[derive(Model, Clone, Debug, Default)]
struct Post {
    id: u64,
    #[ferroquent(fillable)]
    user_id: u64,
    #[ferroquent(fillable)]
    title: String,
    comments: HasMany<Comment>,
    #[ferroquent(foreign_key = "user_id")]
    author: BelongsTo<User>,
    state: ModelState<Post>,
}

#[derive(Model, Clone, Debug, Default)]
struct Comment {
    id: u64,
    #[ferroquent(fillable)]
    post_id: u64,
    #[ferroquent(fillable)]
    body: String,
    state: ModelState<Comment>,
}

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) {
            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
}

#[tokio::test]
async fn nested_eager_loading() {
    let conns = each_conn().await;
    if conns.is_empty() {
        eprintln!("SKIP: no DSN configured");
        return;
    }
    for conn in conns {
        let db = conn.as_ref();
        for stmt in [
            "drop table if exists `comments`",
            "drop table if exists `posts`",
            "drop table if exists `users`",
            "create table `users` (id bigint unsigned not null auto_increment primary key, name varchar(255) not null)",
            "create table `posts` (id bigint unsigned not null auto_increment primary key, user_id bigint unsigned not null, title varchar(255) not null)",
            "create table `comments` (id bigint unsigned not null auto_increment primary key, post_id bigint unsigned not null, body varchar(255) not null)",
        ] {
            db.statement(stmt, &[]).await.unwrap();
        }

        let taylor = User::create(db, record([("name", Value::Str("Taylor".into()))]))
            .await
            .unwrap();
        let p1 = Post::create(
            db,
            record([
                ("user_id", Value::UInt(taylor.id)),
                ("title", Value::Str("First".into())),
            ]),
        )
        .await
        .unwrap();
        let p2 = Post::create(
            db,
            record([
                ("user_id", Value::UInt(taylor.id)),
                ("title", Value::Str("Second".into())),
            ]),
        )
        .await
        .unwrap();
        for (pid, body) in [(p1.id, "c1a"), (p1.id, "c1b"), (p2.id, "c2a")] {
            Comment::create(
                db,
                record([
                    ("post_id", Value::UInt(pid)),
                    ("body", Value::Str(body.into())),
                ]),
            )
            .await
            .unwrap();
        }

        // Nested: load users → their posts → each post's comments (users→posts→comments = 3 queries).
        let mut q = User::query();
        q.with(["posts.comments"]).order_by("id");
        let users = q.get(db).await.unwrap();
        assert_eq!(users.len(), 1);
        let posts = users[0].posts.get().unwrap();
        assert_eq!(posts.len(), 2);
        // Nested comments are attached to the loaded posts.
        assert!(posts[0].comments.is_loaded());
        let total_comments: usize = posts.iter().map(|p| p.comments.get().unwrap().len()).sum();
        assert_eq!(total_comments, 3);
        assert_eq!(posts[0].comments.get().unwrap().len(), 2); // First
        assert_eq!(posts[1].comments.get().unwrap().len(), 1); // Second

        for stmt in [
            "drop table if exists `comments`",
            "drop table if exists `posts`",
            "drop table if exists `users`",
        ] {
            db.statement(stmt, &[]).await.unwrap();
        }
    }
}