I am using the below code to insert to a Postgres DB using tokio-postgres, is there any better option :
let members = &[obj] //obj is a struct
let mut params = Vec::<&(dyn ToSql + Sync)>::new();
let mut i = 1;
let mut qry:String = "insert into tablename(id,userid,usertype) values".to_string();
for column in members{
if(i ==1){
qry = format!("{} (${},${},${})",qry,i,i+1,i+2);
}else{
qry = format!("{}, (${},${},${})",qry,i,i+1,i+2);
}
params.push(&column.id);
params.push(&column.userid);
params.push(&column.usertype);
i = i+3;
}
println!("qry : {}",qry);
let result = p.execute(&qry, ¶ms[..]).await; //p is the pool manager
No:
You can marginally improve it by using iterators:
use itertools::Itertools; // For tuples() and format_with()
let params: Vec<_> = members
.iter()
.flat_map(|row| [&row.id as &(dyn ToSql + Sync), &row.userid, &row.usertype])
.collect();
let query = format!(
"insert into tablename(id, userid, usertype) values {}",
(0..params.len())
.tuples()
.format_with(", ", |(i, j, k), f| {
f(&format_args!("(${i}, ${j}, ${k})"))
}),
);
However I don't really think that's better.