12 releases (breaking)

0.10.0 Jan 24, 2024
0.8.0 Dec 22, 2023
0.7.0 Jul 5, 2023
0.6.0 Jun 25, 2022
0.3.0-alpha.0 Nov 18, 2020

#1446 in Database interfaces

Download history 1/week @ 2023-12-18 32/week @ 2024-01-01 7/week @ 2024-01-08 17/week @ 2024-01-15 5/week @ 2024-01-22 16/week @ 2024-02-19 19/week @ 2024-02-26 22/week @ 2024-03-11 46/week @ 2024-03-18 69/week @ 2024-03-25

137 downloads per month

MIT license

14KB
210 lines

sqlxinsert

Warning: used in private projects

Derive macro for inserting struct into sql.

Instead of manually creating insert query and binding all attributes:

let query = r#"
insert into article 
    ( title, subtitle, url, text ) 
values 
    ( $1, $2, $3, $4 ) 
returning *
"#;

let result: Article = sqlx::query_as::<_, Article>(query)
    .bind(&article.title)
    .bind(&article.subtitle)
    .bind(&article.url)
    .bind(&article.text)
    .fetch_one(&mut conn)
    .await?;

Using derive macro if simplifies to this:

let res = car.insert::<Car>(&pool, "cars").await?
Example with different input and output structs.
#[derive(Default, Debug, std::cmp::PartialEq, sqlx::FromRow)]
struct Car {
    pub id: i32,
    pub name: String,
    pub color: Option<String>
}
#[derive(Default, Debug, sqlx::FromRow, sqlxinsert::PgInsert)]
struct CreateCar {
    pub name: String,
    pub color: Option<String>,
}
impl CreateCar {
    pub fn new<T: Into<String>>(name: T) -> Self {
        CreateCar {
            name: name.into(),
            color: None,
        }
    }
}

#[tokio::main]
async fn main() -> sqlx::Result<()>{
    let url = "postgres://user:pass@localhost:5432/test_db";
    let pool = sqlx::postgres::PgPoolOptions::new().connect(&url).await.unwrap();
    let car_skoda = CreateCar::new("Skoda");
    let res: Car = car_skoda.insert::<Car>(pool, "cars").await?;
    Ok(())
}

Build

make build

Test

Requirements: docker installed

make testall

Dependencies

~13–30MB
~480K SLoC