let ids: Vec<i32> = get_ids(); //get_ids impl elsewhere
let stmt = db_conn.prepare(
"SELECT id, name, created FROM person
WHERE id = ANY( $1 )").unwrap();
let mut iter = stmt.query(
[&ids]).unwrap();
This results in the error:
error: failed to find an implementation of trait postgres::types::ToSql for collections::vec::Vec<i32>
According to the documentation , this means that I need to convert it to types::array::ArrayBase<Option<i32>>
.
How do I do this?
My best attempt so far is:
let idOptions: Vec<Option<i32>> = ids.iter().map( |i| Some(i) ).collect();
let idsForDb: postgres::types::array::ArrayBase<Option<i32>> =
postgres::types::array::ArrayBase::from_vec(idOptions, 0);
let mut iter = stmt.query(
[&idsForDb]).unwrap();
Which results in:
error: expected core::iter::FromIterator<core::option::Option<&i32>>, but found core::iter::FromIterator<core::option::Option<i32>> (expected i32 but found &-ptr) [E0095]
The trick lied in dereferencing the pointer within the closure function in map |i| Some(*i)
|i| Some(*i)
:
let idOptions: Vec<Option<i32>> = ids.iter().map( |i| Some(*i) ).collect();
let idsForDb: postgres::types::array::ArrayBase<Option<i32>> =
postgres::types::array::ArrayBase::from_vec(idOptions, 0);
let mut iter = stmt.query(
[&idsForDb]).unwrap();
I'll award the answer to someone who can find a more elegant/ idiomatic way of doing this.
Try with either ArrayBase::from_raw
or ArrayBase::from_vec
. They are documented - you can either read the source code or build the docs with rustdoc.
https://github.com/sfackler/rust-postgres/blob/master/src/types/array.rs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.