ferroquent 0.0.1

A faithful port of Laravel's Eloquent ORM to Rust (facade crate)
Documentation
//! Polymorphic (morph) relations against live MySQL/MariaDB: Post/Video morphMany Comment.

use ferroquent::prelude::*;
use ferroquent_model::MorphMany;

#[derive(Model, Clone, Debug, Default)]
struct Post {
    id: u64,
    #[ferroquent(fillable)]
    title: String,
    #[ferroquent(morph = "commentable")]
    comments: MorphMany<Comment>,
    state: ModelState<Post>,
}

#[derive(Model, Clone, Debug, Default)]
struct Video {
    id: u64,
    #[ferroquent(fillable)]
    url: String,
    #[ferroquent(morph = "commentable")]
    comments: MorphMany<Comment>,
    state: ModelState<Video>,
}

#[derive(Model, Clone, Debug, Default)]
struct Comment {
    id: u64,
    #[ferroquent(fillable)]
    commentable_id: u64,
    #[ferroquent(fillable)]
    commentable_type: String,
    #[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 morph_many() {
    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 `videos`",
            "drop table if exists `posts`",
            "create table `posts` (id bigint unsigned not null auto_increment primary key, title varchar(255) not null)",
            "create table `videos` (id bigint unsigned not null auto_increment primary key, url varchar(255) not null)",
            "create table `comments` (id bigint unsigned not null auto_increment primary key, commentable_id bigint unsigned not null, commentable_type varchar(255) not null, body varchar(255) not null)",
        ] {
            db.statement(stmt, &[]).await.unwrap();
        }

        let post = Post::create(db, record([("title", Value::Str("Hello".into()))]))
            .await
            .unwrap();
        let video = Video::create(db, record([("url", Value::Str("v.mp4".into()))]))
            .await
            .unwrap();
        // Post gets 2 comments (type "post"), video gets 1 (type "video"). Note the ids overlap (1,1)
        // - the type column disambiguates.
        for (cid, ctype, body) in [
            (post.id, "post", "on post a"),
            (post.id, "post", "on post b"),
            (video.id, "video", "on video"),
        ] {
            Comment::create(
                db,
                record([
                    ("commentable_id", Value::UInt(cid)),
                    ("commentable_type", Value::Str(ctype.into())),
                    ("body", Value::Str(body.into())),
                ]),
            )
            .await
            .unwrap();
        }

        // Lazy: post.comments() filters by type = "post" (its MORPH_ALIAS).
        let post_comments = post.comments().get(db).await.unwrap();
        assert_eq!(
            post_comments.len(),
            2,
            "post has 2 comments (type disambiguated)"
        );

        let video_comments = video.comments().get(db).await.unwrap();
        assert_eq!(video_comments.len(), 1);
        assert_eq!(video_comments[0].body, "on video");

        // Eager on posts: type-filtered + grouped.
        let mut q = Post::query();
        q.with(["comments"]);
        let posts = q.get(db).await.unwrap();
        assert_eq!(posts.len(), 1);
        assert!(posts[0].comments.is_loaded());
        assert_eq!(posts[0].comments.get().unwrap().len(), 2);

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