From c8301feed7310937900d03d6f9bd7649f625cc9e Mon Sep 17 00:00:00 2001 From: "Lei, HUANG" <6406592+v0y4g3r@users.noreply.github.com> Date: Thu, 4 May 2023 18:57:38 +0800 Subject: [PATCH] fix: respect MySQL timestamp format (#1510) --- src/common/time/src/timestamp.rs | 33 ++++++++++++++++++++++++++++---- src/servers/src/mysql/writer.rs | 2 +- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/common/time/src/timestamp.rs b/src/common/time/src/timestamp.rs index c231b052c4..8990b57eaf 100644 --- a/src/common/time/src/timestamp.rs +++ b/src/common/time/src/timestamp.rs @@ -164,12 +164,17 @@ impl Timestamp { /// Format timestamp to ISO8601 string. If the timestamp exceeds what chrono timestamp can /// represent, this function simply print the timestamp unit and value in plain string. pub fn to_iso8601_string(&self) -> String { + self.as_formatted_string("%Y-%m-%d %H:%M:%S%.f%z") + } + + pub fn to_local_string(&self) -> String { + self.as_formatted_string("%Y-%m-%d %H:%M:%S%.f") + } + + fn as_formatted_string(self, pattern: &str) -> String { if let Some(v) = self.to_chrono_datetime() { let local = Local {}; - format!( - "{}", - local.from_utc_datetime(&v).format("%Y-%m-%d %H:%M:%S%.f%z") - ) + format!("{}", local.from_utc_datetime(&v).format(pattern)) } else { format!("[Timestamp{}: {}]", self.unit, self.value) } @@ -889,4 +894,24 @@ mod tests { Timestamp::from_str("1970-01-01 08:00:00").unwrap() ); } + + #[test] + fn test_to_local_string() { + std::env::set_var("TZ", "Asia/Shanghai"); + + assert_eq!( + "1970-01-01 08:00:00.000000001", + Timestamp::new(1, TimeUnit::Nanosecond).to_local_string() + ); + + assert_eq!( + "1970-01-01 08:00:00.001", + Timestamp::new(1, TimeUnit::Millisecond).to_local_string() + ); + + assert_eq!( + "1970-01-01 08:00:01", + Timestamp::new(1, TimeUnit::Second).to_local_string() + ); + } } diff --git a/src/servers/src/mysql/writer.rs b/src/servers/src/mysql/writer.rs index 2093be65ab..a1109cc7f3 100644 --- a/src/servers/src/mysql/writer.rs +++ b/src/servers/src/mysql/writer.rs @@ -161,7 +161,7 @@ impl<'a, W: AsyncWrite + Unpin> MysqlResultWriter<'a, W> { Value::Binary(v) => row_writer.write_col(v.deref())?, Value::Date(v) => row_writer.write_col(v.val())?, Value::DateTime(v) => row_writer.write_col(v.val())?, - Value::Timestamp(v) => row_writer.write_col(v.to_iso8601_string())?, + Value::Timestamp(v) => row_writer.write_col(v.to_local_string())?, Value::List(_) => { return Err(Error::Internal { err_msg: format!(