You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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包装器

  1. 先在Cargo.toml里补全依赖,启用chrono相关特性:
[dependencies]
postgres = { version = "0.19", features = ["with-chrono"] }
postgres-types = { version = "0.2", features = ["chrono"] }
  1. 把你的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, &[&timestamp_array]).await {
    info!("worked");
} else {
    error!("error");
}

原理很简单:PostgreSQL的timestamp[]类型需要Rust侧提供能被识别的数组包装类型,直接传&[DateTime<Utc>]无法被自动转换,通过上面两种方式处理后,就能满足ToSql的类型要求,顺利传入存储过程。

内容的提问来源于stack exchange,提问作者ferd tomale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 06:04:59