Crate dysql_macro
source · [−]Expand description
Do dynamic-sql query through proc-macro
It bases on [tokio-postgres] and [sqlx] crate (default feature), you can switch them by setting the features. It uses [Ramhorns] the high performance template engine implementation of [Mustache]
Example (Sqlx)
main.rs
ⓘ
//...
async fn main() -> dysql::DySqlResult<()> {
let conn = connect_postgres_db().await;
// fetch all
let dto = UserDto{ id: None, name: None, age: Some(15) };
let rst = fetch_all!(|dto, &conn| -> User {
r#"SELECT * FROM test_user
WHERE 1 = 1
{{#name}}AND name = :name{{/name}}
{{#age}}AND age > :age{{/age}}
ORDER BY id"#
});
assert_eq!(
vec![
User { id: 2, name: Some("zhanglan".to_owned()), age: Some(21) },
User { id: 3, name: Some("zhangsan".to_owned()), age: Some(35) }
],
rst
);
let rst = fetch_one!(...);
let rst = fetch_scalar!(...);
let affected_rows_num = execute!(...);
let insert_id = insert!(...);
}Example (tokio-postgres)
Full example please see: Dysql tokio-postgres example
Example (sqlx)
Full example please see: Dysql sqlx example
Macros
Execute query
fetch all datas that filtered by dto
fetch one data that filtered by dto
Fetch a scalar value from query
Insert data
Note: if you use this macro under postgres database, you should add “returning id” at the end of sql statement by yourself.