#查询构建器 #SQL查询 #SQL数据库 #组件 #复杂 #ORM #eloquent

eloquent_core

Eloquent 的核心查询构建器组件

6 个版本 (1 个稳定版)

1.0.0 2024年2月14日
0.2.0 2023年4月20日
0.1.4 2023年3月24日
0.1.3 2023年1月25日

#55#查询构建器

每月40次下载
eloquent 中使用

MIT 许可证

41KB
683

Eloquent

[!警告]

此包是为学习目的开发的,不适用于生产使用。

Eloquent 是一个SQL查询构建器,用于在Rust中轻松构建复杂SQL查询。它受到Laravel的查询构建器的启发,旨在简单易用。这与Laravel的Eloquent ORM不同。此库设计用于与任何SQL数据库一起使用,并且没有特定的数据库功能。

查询构建器支持 selectinsertupdatedeletewherejoingroup_byhavingorder_bylimitoffsetto_sql 方法,并支持where子句闭包。

有关更多详细信息,请参阅可用方法

用法

[dependencies]
eloquent = "1.0"
use eloquent_core::{Eloquent, Operator, Variable};

fn example_query() {
    let query = Eloquent::table("orders")
        .select("orders.customer_id")
        .select_as("customers.name", "customer_name")
        .select_count("orders.id", "total_orders")
        .join("customers", "orders.customer_id", "customers.id")
        .r#where(
            "orders.order_date",
            Operator::GreaterThanOrEqual,
            Variable::String("2024-01-01".to_string()),
        )
        .r#where(
            "customers.country_id",
            Operator::In,
            Variable::Array(vec![
                ArrayVariable::String("NL".to_string()),
                ArrayVariable::String("DE".to_string()),
            ]),
        )
        .where_not_null("shipped_at")
        .group_by(vec!["orders.customer_id", "customers.name"])
        .having("total_orders", Operator::GreaterThan, Variable::Int(5))
        .order_by("total_orders", Direction::Desc)
        .order_by("customer_name", Direction::Asc)
        .limit(10)
        .offset(0)
        .to_sql();

    assert_eq!(
        query,
        "SELECT orders.customer_id, customers.name AS customer_name, COUNT(orders.id) AS total_orders FROM orders JOIN customers ON orders.customer_id = customers.id WHERE orders.order_date >= `2024-01-01` AND customers.country_id IN (`NL`, `DE`) AND shipped_at IS NOT NULL GROUP BY orders.customer_id, customers.name HAVING total_orders > 5 ORDER BY total_orders DESC, customer_name ASC LIMIT 10 OFFSET 0"
    );
}
use eloquent_core::{Eloquent, Operator, Variable};

fn example_query() {
    let query = Eloquent::table("users")
        .where_closure(|closure| {
            closure
                .r#where("age", Operator::GreaterThanOrEqual, Variable::Int(18))
                .r#where("age", Operator::LessThan, Variable::Int(25));
        })
        .or_where_closure(|closure| {
            closure
                .r#where("age", Operator::GreaterThanOrEqual, Variable::Int(30))
                .r#where("age", Operator::LessThan, Variable::Int(35));
        })
        .to_sql();
    assert_eq!(
        query,
        "SELECT * FROM users WHERE (age >= 18 AND age < 25) OR (age >= 30 AND age < 35)"
    );
}

lib.rs:

Eloquent Core

Eloquent Core 是 Eloquent 库的核心库。它提供构建SQL查询的核心功能。

无运行时依赖