#orm #sqlx #mapping #primary-key #built #update #create

sorm

基于SQLx的简单ORM(对象关系映射)

2个版本

0.1.1 2024年7月5日
0.1.0 2024年6月24日

#10#primary-key

每月下载量 25次

MIT 许可证

56KB
1K SLoC

sorm

基于SQLx的简单ORM(对象关系映射)。

示例

use std::error::Error;
use std::time::{SystemTime, UNIX_EPOCH};

use serde_json::json;
use sorm::model::Model;
use sorm::{clause, sorm};
use sqlx::{Executor, SqlitePool};

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let db = SqlitePool::connect("sqlite://:memory:").await?;
    db.execute(
        r#"
CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    enable INTEGER NOT NULL,
    updated_at INTEGER NOT NULL,
    created_at INTEGER NOT NULL
)
"#,
    )
        .await?;

    // Create
    let mut user = User::new();
    user.set_name("foo".to_string());
    user.create(&db).await?;
    println!("{}", json!(user)); // => {"created_at":1719131281,"enable":1,"id":1,"name":"foo","updated_at":1719131281}

    // Update
    user.set_enable(0);
    user.update(&db).await?;
    println!("{}", json!(user)); // => {"created_at":1719131281,"enable":0,"id":1,"name":"foo","updated_at":1719131281}

    // Find by primary key
    let user = User::find(&db, &1).await?;
    println!("{}", json!(user)); // => {"created_at":1719131281,"enable":0,"id":1,"name":"foo","updated_at":1719131281}

    // Use query builder
    let name = "foo";
    let user = User::query()
        .select(&[User::ID, User::NAME])
        .r#where(clause!("name={&name}"))
        .find(&db)
        .await?;
    println!("{}", json!(user)); // => {"id":1,"name":"foo"}

    // Delete
    user.delete(&db).await?;
    User::destroy(&db, &1).await?;

    Ok(())
}

#[sorm(table = "users", serialize)]
struct User {
    #[sorm(primary_key(increment))]
    id: i64,

    name: String,

    #[sorm(default = "1")]
    enable: i8,

    #[sorm(update_time)]
    updated_at: i64,

    #[sorm(create_time)]
    created_at: i64,
}

fn current_timestamp() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64
}

安装

  • sqlite

    cargoadd sorm --功能sqlite

  • postgres

    cargoadd sorm --功能postgres

  • mysql

    cargoadd sorm --功能mysql

依赖项

~7–22MB
~337K SLoC