[英]How to return tokio_postgres ToSql type from closure in Rust?
我如何通過將ToSql
數據作為閉包傳遞來避免重復自己,告訴 tokio-postgres 哪些數據列,從我的各種結構模型到COPY
/ SELECT
/etc?
例如,理想情況下,我可以傳遞各種表/列參數,例如:
// see MRE, "copy_in" performs boilerplate to copy binary format in postgres table
copy_in(
&mut client, // the postgres client setup in tokio
"table_name", // meta info about what table/columns to insert
&["col1", "col2", "col3", "col4"],
&vec![Type::INT4, Type::VARCHAR, Type::INT4, Type::INT4],
&rows_of_struct_data, // the vec of data I plan to insert
// then here's the hard part: which fields to extract from each row... (not works)
|m| &[&[&m.id], &[&m.name], &[&m.range_begin, &m.range_end]] as &[&[&(dyn ToSql + Sync)]]
);
tokio_postgres
需要一種用於在復制期間寫入二進制數據的類型Vec<&(dyn ToSql + Sync)>
,雖然硬編碼什么被push
ed 到 Vec 是有效的,但我很困惑如何傳遞一個動態決定要push
什么的參數它。
我對此有兩個想法,但推薦的方法是什么?
預期
&dyn ToSql + Sync
,找到 trait 對象dyn ToSql
Vec
傳遞給我的閉包,以便它為每一行推送列數據,但這有幾個生命周期問題,例如:對
row
的引用在此處轉義異步閉包主體
我不知道如何返回 tokio_postgres &dyn ToSql + Sync 類型。 但是我在下面通過這種方式解決了這個問題。 我正在使用 postgres 的二進制副本插入數據。
桌子:
CREATE TABLE IF NOT EXISTS test (
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL
)
為了填充表格,我使用:
use tokio_postgres::types::{Type, ToSql};
use tokio_postgres::binary_copy::BinaryCopyInWriter;
use tokio_postgres::{NoTls, Error};
use futures::{pin_mut};
async fn main() -> Result<(), Error> {
//...
let config = format!("host={} user={} password='{}' dbname={} port={} connect_timeout=10",host, user, passwd, dbname, port);
let (client, connection) = tokio_postgres::connect(&config, NoTls).await?;
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("Connection error: {}", e);
}
});
let data: Vec<(i32,&str)> = vec![(1i32,"hello,"),
(2i32,"world!"),
(3i32,"how"),
(4i32,"are"),
(5i32,"you"),
(6i32,"today?")];
let sink = client
.copy_in("COPY test (id, name) FROM STDIN BINARY")
.await
.unwrap();
let writer = BinaryCopyInWriter::new(sink, &[Type::INT4, Type::VARCHAR]);
pin_mut!(writer);
for i in 0..data.len() {
let (id, name) = data[i];
writer.as_mut().write(&[&id, &name]).await.unwrap();
}
writer.finish().await?;
Ok(())
}
我使用元組來存儲數據,然后我解包元組以將數據插入數據庫。 依賴項是 tokio-postgres = "0.7.6", tokio = { version = "1.20.0", features = ["full"] } 和 futures = "0.3"。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.