Skip to content

Commit

Permalink
fix: array type serialization (#194)
Browse files Browse the repository at this point in the history
  • Loading branch information
sunng87 authored Sep 12, 2024
1 parent 321393a commit 7e8eca7
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -246,6 +246,11 @@ impl<T: ToSqlText> ToSqlText for &[T] {
ty: &Type,
out: &mut BytesMut,
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
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 {
Expand Down Expand Up @@ -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())
);
}
}

0 comments on commit 7e8eca7

Please sign in to comment.