From 45e1c35124b26712ba684508cbbaf5503e147e25 Mon Sep 17 00:00:00 2001 From: Ning Sun Date: Wed, 11 Sep 2024 17:30:45 -0700 Subject: [PATCH] fix: array type serialization --- src/types/mod.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/types/mod.rs b/src/types/mod.rs index 2b65a4e..b007b7f 100644 --- a/src/types/mod.rs +++ b/src/types/mod.rs @@ -4,7 +4,7 @@ use std::{error::Error, fmt}; use bytes::{BufMut, BytesMut}; use chrono::offset::Utc; use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, TimeZone}; -use postgres_types::{IsNull, Type, WrongType}; +use postgres_types::{IsNull, Kind, Type, WrongType}; use rust_decimal::Decimal; pub trait ToSqlText: fmt::Debug { @@ -246,6 +246,11 @@ impl ToSqlText for &[T] { ty: &Type, out: &mut BytesMut, ) -> Result> { + let ty = match ty.kind() { + Kind::Array(inner_ty) => inner_ty, + _ => ty, + }; + out.put_slice(b"{"); for (i, val) in self.iter().enumerate() { if i > 0 { @@ -325,4 +330,18 @@ mod test { no.to_sql_text(&Type::BOOL, &mut buf).unwrap(); assert_eq!("f", String::from_utf8_lossy(buf.freeze().as_ref())); } + + #[test] + fn test_array() { + let date = &[ + NaiveDate::from_ymd_opt(2023, 3, 5).unwrap(), + NaiveDate::from_ymd_opt(2023, 3, 6).unwrap(), + ]; + let mut buf = BytesMut::new(); + date.to_sql_text(&Type::DATE_ARRAY, &mut buf).unwrap(); + assert_eq!( + "{2023-03-05,2023-03-06}", + String::from_utf8_lossy(buf.freeze().as_ref()) + ); + } }