#sqlx #crud #sql #orm #primary-key

macro anorm-macros

Implement Create, Read, Update, and Delete (CRUD) methods for sqlx

5 releases

0.1.6 May 17, 2024
0.1.5 Mar 18, 2024
0.1.3 Nov 13, 2023
0.1.2 Oct 31, 2023
0.1.1 Oct 29, 2023

#23 in #primary-key

Used in anorm


497 lines

Implement Create, Read, Update, and Delete (CRUD) methods for sqlx.


add the following to your project's Cargo.toml:

anorm = { virsion = "0.1", features = ["mysql"] }
sqlx = { version = "0.7", features = ["mysql","runtime-tokio-native-tls"] }

  • features: mysql, postgres, sqlite, mssql


#[derive(Debug, Crud, sqlx::FromRow)]
#[anorm(rename = "users")] // rename table name
struct User {
    // anorm(id) // default first field is primary key
    #[anorm(seq)] // sequence field, insert will ignore this field
    pub id: u64,
    #[anorm(rename = "name")] // rename field name
    #[anorm(by)] // generate query_by_field,update_by_field,delete_by_field
    pub name: String,
    #[anorm(update)] // generate method update_xxx. 
    pub password: String,
    #[anorm(skip)] // ignore field
    pub addr: Option<String>,
    // #[sqlx(skip)]
    // pub age: i32,

pub async fn get_pool() -> Result<MySqlPool> {

async fn test_query() {
    let pool=get_pool().await.unwrap();
    let u = User::get(&pool, 1).await;
    println!("get {:?}", u);
    let u = User::get_by(&pool, "where id=?", args!(1)).await;
    println!("get_by {:?}", u);
    let u = User::query_by_name(&pool, "plucky".into()).await;
    println!("query_by_name {:?}", u);
    let u =User::query(&pool).await;
    println!("list {:?}",u);

    // u.update(&pool).await;
    // u.insert(&pool).await;
    // u.delete(&pool).await

    // let list = vec![User::new(0, "lusy3", "123456"),User::new(0, "lusy5", "123456")];
    // let r =User::insert_all(&pool, list).await;
    // println!("list: {:?}",r);


generate method: get, get_by, query, query_by, update, delete, insert, insert_all.



default first field is primary key or set.


sequence field, auto increment. insert will skip this field.


rename table name or field name. default table name by struct name to_table_case: UserDetail => user_detail. default field name by field name to_snake_case: UserDetail => user_detail.


ignore field. using sqlx::FromRow, skip need #[anorm(skip)] and #[sqlx(skip)]


generate method update_xxx.


generate qet_by_field, query_by_field, update_by_field, delete_by_field.


generate impl sqlx::FromRow for struct. or use #[derive(sqlx::FromRow)]. if using sqlx::FromRow, if need skip field, both #[anorm(skip)] add #[sqlx(skip)] .



 let args = args!(&name, age);


query!("insert into users (name, password) values (?,?)", name, password).execute(&pool).await


query_as!(User, "select * from users where name = ?", name).fetch_one(&pool).await


~19K SLoC