Rust中如何将chrono::DateTime<Utc>数组传入PostgreSQL存储过程?
解决Rust中chrono DateTime数组传入PostgreSQL存储过程的类型不匹配问题
错误提示显示PostgreSQL期望TimestampArray类型,但你传入的是Rust的&[chrono::datetime::DateTime<chrono::offset::utc::Utc>],这是因为postgres crate默认没实现该数组类型的ToSql转换,下面给两种解决办法:
方法一:用postgres-types的Array包装器
- 先在
Cargo.toml里补全依赖,启用chrono相关特性:
[dependencies] postgres = { version = "0.19", features = ["with-chrono"] } postgres-types = { version = "0.2", features = ["chrono"] }
- 把你的DateTime数组包装成
postgres_types::Array再传入:
use postgres_types::Array; // 假设array是你的&[DateTime<Utc>]数组 let pg_compatible_array = Array::from(array); let stmt = connection.prepare_cached("call proc($1)").await.unwrap(); if let Ok(_) = connection.execute(&stmt, &[&pg_compatible_array]).await { info!("worked"); } else { error!("error"); }
方法二:手动转换为PostgreSQL原生Timestamp数组
如果不想加额外依赖,可以把每个DateTime<Utc>转成postgres crate提供的Timestamp类型:
use postgres::types::Timestamp; // 逐个转换DateTime到Timestamp let timestamp_array: Vec<Timestamp> = array.iter() .map(|utc_dt| Timestamp::from(utc_dt.naive_utc())) .collect(); let stmt = connection.prepare_cached("call proc($1)").await.unwrap(); if let Ok(_) = connection.execute(&stmt, &[×tamp_array]).await { info!("worked"); } else { error!("error"); }
原理很简单:PostgreSQL的timestamp[]类型需要Rust侧提供能被识别的数组包装类型,直接传&[DateTime<Utc>]无法被自动转换,通过上面两种方式处理后,就能满足ToSql的类型要求,顺利传入存储过程。
内容的提问来源于stack exchange,提问作者ferd tomale
相关产品推荐
相关产品推荐

