diff --git a/config/frontend.example.toml b/config/frontend.example.toml index 83da275afab1..6bb84e66d3ab 100644 --- a/config/frontend.example.toml +++ b/config/frontend.example.toml @@ -1,7 +1,7 @@ # Node running mode, see `standalone.example.toml`. mode = "distributed" -# The default time zone of the server -# default_time_zone = "UTC" +# The default timezone of the server +# default_timezone = "UTC" [heartbeat] # Interval for sending heartbeat task to the Metasrv, 5 seconds by default. diff --git a/config/standalone.example.toml b/config/standalone.example.toml index f153916495d9..b5b7e07ab132 100644 --- a/config/standalone.example.toml +++ b/config/standalone.example.toml @@ -2,8 +2,8 @@ mode = "standalone" # Whether to enable greptimedb telemetry, true by default. enable_telemetry = true -# The default time zone of the server -# default_time_zone = "UTC" +# The default timezone of the server +# default_timezone = "UTC" # HTTP server options. [http] diff --git a/src/cmd/src/error.rs b/src/cmd/src/error.rs index 2dd46ac48f9c..ec4e41a5dbe2 100644 --- a/src/cmd/src/error.rs +++ b/src/cmd/src/error.rs @@ -43,8 +43,8 @@ pub enum Error { source: common_meta::error::Error, }, - #[snafu(display("Failed to init default time zone"))] - InitTimeZone { + #[snafu(display("Failed to init default timezone"))] + InitTimezone { location: Location, source: common_time::error::Error, }, @@ -274,7 +274,7 @@ impl ErrorExt for Error { | Error::LoadLayeredConfig { .. } | Error::IllegalConfig { .. } | Error::InvalidReplCommand { .. } - | Error::InitTimeZone { .. } + | Error::InitTimezone { .. } | Error::ConnectEtcd { .. } | Error::NotDataFromOutput { .. } | Error::CreateDir { .. } diff --git a/src/cmd/src/frontend.rs b/src/cmd/src/frontend.rs index fa4eefe1515c..607c7f3d7bd1 100644 --- a/src/cmd/src/frontend.rs +++ b/src/cmd/src/frontend.rs @@ -22,7 +22,7 @@ use client::client_manager::DatanodeClients; use common_meta::heartbeat::handler::parse_mailbox_message::ParseMailboxMessageHandler; use common_meta::heartbeat::handler::HandlerGroupExecutor; use common_telemetry::logging; -use common_time::timezone::set_default_time_zone; +use common_time::timezone::set_default_timezone; use frontend::frontend::FrontendOptions; use frontend::heartbeat::handler::invalidate_table_cache::InvalidateTableCacheHandler; use frontend::heartbeat::HeartbeatTask; @@ -33,7 +33,7 @@ use servers::tls::{TlsMode, TlsOption}; use servers::Mode; use snafu::{OptionExt, ResultExt}; -use crate::error::{self, InitTimeZoneSnafu, MissingConfigSnafu, Result, StartFrontendSnafu}; +use crate::error::{self, InitTimezoneSnafu, MissingConfigSnafu, Result, StartFrontendSnafu}; use crate::options::{CliOptions, Options}; use crate::App; @@ -218,7 +218,7 @@ impl StartCommand { logging::info!("Frontend start command: {:#?}", self); logging::info!("Frontend options: {:#?}", opts); - set_default_time_zone(opts.default_time_zone.as_deref()).context(InitTimeZoneSnafu)?; + set_default_timezone(opts.default_timezone.as_deref()).context(InitTimezoneSnafu)?; let meta_client_options = opts.meta_client.as_ref().context(MissingConfigSnafu { msg: "'meta_client'", diff --git a/src/cmd/src/standalone.rs b/src/cmd/src/standalone.rs index 3255871a2f4b..b6947741bc49 100644 --- a/src/cmd/src/standalone.rs +++ b/src/cmd/src/standalone.rs @@ -31,7 +31,7 @@ use common_meta::wal::{WalOptionsAllocator, WalOptionsAllocatorRef}; use common_procedure::ProcedureManagerRef; use common_telemetry::info; use common_telemetry::logging::LoggingOptions; -use common_time::timezone::set_default_time_zone; +use common_time::timezone::set_default_timezone; use datanode::config::{DatanodeOptions, ProcedureConfig, RegionEngineConfig, StorageConfig}; use datanode::datanode::{Datanode, DatanodeBuilder}; use file_engine::config::EngineConfig as FileEngineConfig; @@ -51,7 +51,7 @@ use servers::Mode; use snafu::ResultExt; use crate::error::{ - CreateDirSnafu, IllegalConfigSnafu, InitDdlManagerSnafu, InitMetadataSnafu, InitTimeZoneSnafu, + CreateDirSnafu, IllegalConfigSnafu, InitDdlManagerSnafu, InitMetadataSnafu, InitTimezoneSnafu, Result, ShutdownDatanodeSnafu, ShutdownFrontendSnafu, StartDatanodeSnafu, StartFrontendSnafu, StartProcedureManagerSnafu, StartWalOptionsAllocatorSnafu, StopProcedureManagerSnafu, }; @@ -98,7 +98,7 @@ impl SubCommand { pub struct StandaloneOptions { pub mode: Mode, pub enable_telemetry: bool, - pub default_time_zone: Option, + pub default_timezone: Option, pub http: HttpOptions, pub grpc: GrpcOptions, pub mysql: MysqlOptions, @@ -122,7 +122,7 @@ impl Default for StandaloneOptions { Self { mode: Mode::Standalone, enable_telemetry: true, - default_time_zone: None, + default_timezone: None, http: HttpOptions::default(), grpc: GrpcOptions::default(), mysql: MysqlOptions::default(), @@ -149,7 +149,7 @@ impl StandaloneOptions { fn frontend_options(self) -> FrontendOptions { FrontendOptions { mode: self.mode, - default_time_zone: self.default_time_zone, + default_timezone: self.default_timezone, http: self.http, grpc: self.grpc, mysql: self.mysql, @@ -370,8 +370,8 @@ impl StartCommand { info!("Building standalone instance with {opts:#?}"); - set_default_time_zone(opts.frontend.default_time_zone.as_deref()) - .context(InitTimeZoneSnafu)?; + set_default_timezone(opts.frontend.default_timezone.as_deref()) + .context(InitTimezoneSnafu)?; // Ensure the data_home directory exists. fs::create_dir_all(path::Path::new(&opts.data_home)).context(CreateDirSnafu { diff --git a/src/common/time/src/datetime.rs b/src/common/time/src/datetime.rs index 1a5693ca9785..7dc872b8f2ac 100644 --- a/src/common/time/src/datetime.rs +++ b/src/common/time/src/datetime.rs @@ -20,7 +20,7 @@ use chrono::{Days, LocalResult, Months, NaiveDateTime, TimeZone as ChronoTimeZon use serde::{Deserialize, Serialize}; use crate::error::{Error, InvalidDateStrSnafu, Result}; -use crate::timezone::TimeZone; +use crate::timezone::Timezone; use crate::util::{format_utc_datetime, local_datetime_to_utc}; use crate::{Date, Interval}; @@ -110,11 +110,11 @@ impl DateTime { NaiveDateTime::from_timestamp_millis(self.0) } - pub fn to_chrono_datetime_with_timezone(&self, tz: Option) -> Option { + pub fn to_chrono_datetime_with_timezone(&self, tz: Option) -> Option { let datetime = self.to_chrono_datetime(); datetime.map(|v| match tz { - Some(TimeZone::Offset(offset)) => offset.from_utc_datetime(&v).naive_local(), - Some(TimeZone::Named(tz)) => tz.from_utc_datetime(&v).naive_local(), + Some(Timezone::Offset(offset)) => offset.from_utc_datetime(&v).naive_local(), + Some(Timezone::Named(tz)) => tz.from_utc_datetime(&v).naive_local(), None => Utc.from_utc_datetime(&v).naive_local(), }) } @@ -155,11 +155,11 @@ impl DateTime { #[cfg(test)] mod tests { use super::*; - use crate::timezone::set_default_time_zone; + use crate::timezone::set_default_timezone; #[test] pub fn test_new_date_time() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); assert_eq!("1970-01-01 08:00:00+0800", DateTime::new(0).to_string()); assert_eq!("1970-01-01 08:00:01+0800", DateTime::new(1000).to_string()); assert_eq!("1970-01-01 07:59:59+0800", DateTime::new(-1000).to_string()); @@ -167,7 +167,7 @@ mod tests { #[test] pub fn test_parse_from_string() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); let time = "1970-01-01 00:00:00+0800"; let dt = DateTime::from_str(time).unwrap(); assert_eq!(time, &dt.to_string()); @@ -195,7 +195,7 @@ mod tests { #[test] fn test_parse_local_date_time() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); assert_eq!( -28800000, DateTime::from_str("1970-01-01 00:00:00").unwrap().val() diff --git a/src/common/time/src/error.rs b/src/common/time/src/error.rs index 2cd4527d2d07..a1d225610531 100644 --- a/src/common/time/src/error.rs +++ b/src/common/time/src/error.rs @@ -51,8 +51,8 @@ pub enum Error { #[snafu(display("Timestamp arithmetic overflow, msg: {}", msg))] ArithmeticOverflow { msg: String, location: Location }, - #[snafu(display("Invalid time zone offset: {hours}:{minutes}"))] - InvalidTimeZoneOffset { + #[snafu(display("Invalid timezone offset: {hours}:{minutes}"))] + InvalidTimezoneOffset { hours: i32, minutes: u32, location: Location, @@ -66,8 +66,8 @@ pub enum Error { location: Location, }, - #[snafu(display("Invalid time zone string {raw}"))] - ParseTimeZoneName { raw: String, location: Location }, + #[snafu(display("Invalid timezone string {raw}"))] + ParseTimezoneName { raw: String, location: Location }, } impl ErrorExt for Error { @@ -75,9 +75,9 @@ impl ErrorExt for Error { match self { Error::ParseDateStr { .. } | Error::ParseTimestamp { .. } - | Error::InvalidTimeZoneOffset { .. } + | Error::InvalidTimezoneOffset { .. } | Error::ParseOffsetStr { .. } - | Error::ParseTimeZoneName { .. } => StatusCode::InvalidArguments, + | Error::ParseTimezoneName { .. } => StatusCode::InvalidArguments, Error::TimestampOverflow { .. } => StatusCode::Internal, Error::InvalidDateStr { .. } | Error::ArithmeticOverflow { .. } => { StatusCode::InvalidArguments @@ -96,9 +96,9 @@ impl ErrorExt for Error { | Error::TimestampOverflow { location, .. } | Error::ArithmeticOverflow { location, .. } => Some(*location), Error::ParseDateStr { .. } - | Error::InvalidTimeZoneOffset { .. } + | Error::InvalidTimezoneOffset { .. } | Error::ParseOffsetStr { .. } - | Error::ParseTimeZoneName { .. } => None, + | Error::ParseTimezoneName { .. } => None, Error::InvalidDateStr { location, .. } => Some(*location), Error::ParseInterval { location, .. } => Some(*location), } diff --git a/src/common/time/src/lib.rs b/src/common/time/src/lib.rs index 4a47c212dc11..770057394c2a 100644 --- a/src/common/time/src/lib.rs +++ b/src/common/time/src/lib.rs @@ -31,4 +31,4 @@ pub use interval::Interval; pub use range::RangeMillis; pub use timestamp::Timestamp; pub use timestamp_millis::TimestampMillis; -pub use timezone::TimeZone; +pub use timezone::Timezone; diff --git a/src/common/time/src/time.rs b/src/common/time/src/time.rs index aec8c125b55e..fdcc9ee32ec2 100644 --- a/src/common/time/src/time.rs +++ b/src/common/time/src/time.rs @@ -19,7 +19,7 @@ use chrono::{NaiveDateTime, NaiveTime, TimeZone as ChronoTimeZone, Utc}; use serde::{Deserialize, Serialize}; use crate::timestamp::TimeUnit; -use crate::timezone::{get_time_zone, TimeZone}; +use crate::timezone::{get_timezone, Timezone}; /// Time value, represents the elapsed time since midnight in the unit of `TimeUnit`. #[derive(Debug, Clone, Default, Copy, Serialize, Deserialize)] @@ -108,26 +108,26 @@ impl Time { self.as_formatted_string("%H:%M:%S%.f%z", None) } - /// Format Time for system time zone. + /// Format Time for system timeszone. pub fn to_system_tz_string(&self) -> String { self.as_formatted_string("%H:%M:%S%.f", None) } /// Format Time for given timezone. - /// When timezone is None, using system time zone by default. - pub fn to_timezone_aware_string(&self, tz: Option) -> String { + /// When timezone is None, using system timezone by default. + pub fn to_timezone_aware_string(&self, tz: Option) -> String { self.as_formatted_string("%H:%M:%S%.f", tz) } - fn as_formatted_string(self, pattern: &str, timezone: Option) -> String { + fn as_formatted_string(self, pattern: &str, timezone: Option) -> String { if let Some(time) = self.to_chrono_time() { let date = Utc::now().date_naive(); let datetime = NaiveDateTime::new(date, time); - match get_time_zone(timezone) { - TimeZone::Offset(offset) => { + match get_timezone(timezone) { + Timezone::Offset(offset) => { format!("{}", offset.from_utc_datetime(&datetime).format(pattern)) } - TimeZone::Named(tz) => { + Timezone::Named(tz) => { format!("{}", tz.from_utc_datetime(&datetime).format(pattern)) } } @@ -220,7 +220,7 @@ mod tests { use serde_json::Value; use super::*; - use crate::timezone::set_default_time_zone; + use crate::timezone::set_default_timezone; #[test] fn test_time() { @@ -310,7 +310,7 @@ mod tests { #[test] fn test_to_iso8601_string() { - set_default_time_zone(Some("+10:00")).unwrap(); + set_default_timezone(Some("+10:00")).unwrap(); let time_millis = 1000001; let ts = Time::new_millisecond(time_millis); assert_eq!("10:16:40.001+1000", ts.to_iso8601_string()); @@ -334,7 +334,7 @@ mod tests { #[test] fn test_serialize_to_json_value() { - set_default_time_zone(Some("+10:00")).unwrap(); + set_default_timezone(Some("+10:00")).unwrap(); assert_eq!( "10:00:01+1000", match serde_json::Value::from(Time::new(1, TimeUnit::Second)) { @@ -370,7 +370,7 @@ mod tests { #[test] fn test_to_timezone_aware_string() { - set_default_time_zone(Some("+10:00")).unwrap(); + set_default_timezone(Some("+10:00")).unwrap(); assert_eq!( "10:00:00.001", @@ -380,37 +380,37 @@ mod tests { assert_eq!( "08:00:00.001", Time::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("SYSTEM").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("SYSTEM").unwrap())) ); assert_eq!( "08:00:00.001", Time::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("+08:00").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("+08:00").unwrap())) ); assert_eq!( "07:00:00.001", Time::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("+07:00").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("+07:00").unwrap())) ); assert_eq!( "23:00:00.001", Time::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("-01:00").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("-01:00").unwrap())) ); assert_eq!( "08:00:00.001", Time::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("Asia/Shanghai").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("Asia/Shanghai").unwrap())) ); assert_eq!( "00:00:00.001", Time::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("UTC").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("UTC").unwrap())) ); assert_eq!( "03:00:00.001", Time::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("Europe/Moscow").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("Europe/Moscow").unwrap())) ); } } diff --git a/src/common/time/src/timestamp.rs b/src/common/time/src/timestamp.rs index 2932400b120b..d09890544bd3 100644 --- a/src/common/time/src/timestamp.rs +++ b/src/common/time/src/timestamp.rs @@ -27,12 +27,12 @@ use serde::{Deserialize, Serialize}; use snafu::{OptionExt, ResultExt}; use crate::error::{ArithmeticOverflowSnafu, Error, ParseTimestampSnafu, TimestampOverflowSnafu}; -use crate::timezone::{get_time_zone, TimeZone}; +use crate::timezone::{get_timezone, Timezone}; use crate::util::div_ceil; use crate::{error, Interval}; /// Timestamp represents the value of units(seconds/milliseconds/microseconds/nanoseconds) elapsed -/// since UNIX epoch. The valid value range of [Timestamp] depends on it's unit (all in UTC time zone): +/// since UNIX epoch. The valid value range of [Timestamp] depends on it's unit (all in UTC timezone): /// - for [TimeUnit::Second]: [-262144-01-01 00:00:00, +262143-12-31 23:59:59] /// - for [TimeUnit::Millisecond]: [-262144-01-01 00:00:00.000, +262143-12-31 23:59:59.999] /// - for [TimeUnit::Microsecond]: [-262144-01-01 00:00:00.000000, +262143-12-31 23:59:59.999999] @@ -293,24 +293,24 @@ impl Timestamp { self.as_formatted_string("%Y-%m-%d %H:%M:%S%.f%z", None) } - /// Format timestamp use **system time zone**. + /// Format timestamp use **system timezone**. pub fn to_local_string(&self) -> String { self.as_formatted_string("%Y-%m-%d %H:%M:%S%.f", None) } /// Format timestamp for given timezone. - /// If `tz==None`, the server default time zone will used. - pub fn to_timezone_aware_string(&self, tz: Option) -> String { + /// If `tz==None`, the server default timezone will used. + pub fn to_timezone_aware_string(&self, tz: Option) -> String { self.as_formatted_string("%Y-%m-%d %H:%M:%S%.f", tz) } - fn as_formatted_string(self, pattern: &str, timezone: Option) -> String { + fn as_formatted_string(self, pattern: &str, timezone: Option) -> String { if let Some(v) = self.to_chrono_datetime() { - match get_time_zone(timezone) { - TimeZone::Offset(offset) => { + match get_timezone(timezone) { + Timezone::Offset(offset) => { format!("{}", offset.from_utc_datetime(&v).format(pattern)) } - TimeZone::Named(tz) => { + Timezone::Named(tz) => { format!("{}", tz.from_utc_datetime(&v).format(pattern)) } } @@ -324,11 +324,11 @@ impl Timestamp { NaiveDateTime::from_timestamp_opt(sec, nsec) } - pub fn to_chrono_datetime_with_timezone(&self, tz: Option) -> Option { + pub fn to_chrono_datetime_with_timezone(&self, tz: Option) -> Option { let datetime = self.to_chrono_datetime(); datetime.map(|v| match tz { - Some(TimeZone::Offset(offset)) => offset.from_utc_datetime(&v).naive_local(), - Some(TimeZone::Named(tz)) => tz.from_utc_datetime(&v).naive_local(), + Some(Timezone::Offset(offset)) => offset.from_utc_datetime(&v).naive_local(), + Some(Timezone::Named(tz)) => tz.from_utc_datetime(&v).naive_local(), None => Utc.from_utc_datetime(&v).naive_local(), }) } @@ -560,7 +560,7 @@ mod tests { use serde_json::Value; use super::*; - use crate::timezone::set_default_time_zone; + use crate::timezone::set_default_timezone; #[test] pub fn test_time_unit() { @@ -790,7 +790,7 @@ mod tests { #[test] fn test_to_iso8601_string() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); let datetime_str = "2020-09-08 13:42:29.042+0000"; let ts = Timestamp::from_str(datetime_str).unwrap(); assert_eq!("2020-09-08 21:42:29.042+0800", ts.to_iso8601_string()); @@ -814,7 +814,7 @@ mod tests { #[test] fn test_serialize_to_json_value() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); assert_eq!( "1970-01-01 08:00:01+0800", match serde_json::Value::from(Timestamp::new(1, TimeUnit::Second)) { @@ -1055,7 +1055,7 @@ mod tests { // $TZ doesn't take effort. #[test] - fn test_parse_in_time_zone() { + fn test_parse_in_timezone() { std::env::set_var("TZ", "Asia/Shanghai"); assert_eq!( Timestamp::new(28800, TimeUnit::Second), @@ -1075,7 +1075,7 @@ mod tests { #[test] fn test_to_local_string() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); assert_eq!( "1970-01-01 08:00:00.000000001", @@ -1108,52 +1108,52 @@ mod tests { #[test] fn test_to_timezone_aware_string() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); std::env::set_var("TZ", "Asia/Shanghai"); assert_eq!( "1970-01-01 08:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("SYSTEM").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("SYSTEM").unwrap())) ); assert_eq!( "1970-01-01 08:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("SYSTEM").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("SYSTEM").unwrap())) ); assert_eq!( "1970-01-01 08:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("+08:00").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("+08:00").unwrap())) ); assert_eq!( "1970-01-01 07:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("+07:00").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("+07:00").unwrap())) ); assert_eq!( "1969-12-31 23:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("-01:00").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("-01:00").unwrap())) ); assert_eq!( "1970-01-01 08:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("Asia/Shanghai").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("Asia/Shanghai").unwrap())) ); assert_eq!( "1970-01-01 00:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("UTC").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("UTC").unwrap())) ); assert_eq!( "1970-01-01 01:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("Europe/Berlin").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("Europe/Berlin").unwrap())) ); assert_eq!( "1970-01-01 03:00:00.001", Timestamp::new(1, TimeUnit::Millisecond) - .to_timezone_aware_string(Some(TimeZone::from_tz_string("Europe/Moscow").unwrap())) + .to_timezone_aware_string(Some(Timezone::from_tz_string("Europe/Moscow").unwrap())) ); } diff --git a/src/common/time/src/timezone.rs b/src/common/time/src/timezone.rs index e8f4a11ce519..700e0db073d9 100644 --- a/src/common/time/src/timezone.rs +++ b/src/common/time/src/timezone.rs @@ -21,40 +21,44 @@ use once_cell::sync::OnceCell; use snafu::{OptionExt, ResultExt}; use crate::error::{ - InvalidTimeZoneOffsetSnafu, ParseOffsetStrSnafu, ParseTimeZoneNameSnafu, Result, + InvalidTimezoneOffsetSnafu, ParseOffsetStrSnafu, ParseTimezoneNameSnafu, Result, }; use crate::util::find_tz_from_env; -/// System time zone in `frontend`/`standalone`, -/// config by option `default_time_zone` in toml, -/// default value is `UTC` when `default_time_zone` is not set. -static DEFAULT_TIME_ZONE: OnceCell = OnceCell::new(); +/// System timezone in `frontend`/`standalone`, +/// config by option `default_timezone` in toml, +/// default value is `UTC` when `default_timezone` is not set. +static DEFAULT_TIMEZONE: OnceCell = OnceCell::new(); -// Set the System time zone by `tz_str` -pub fn set_default_time_zone(tz_str: Option<&str>) -> Result<()> { +// Set the System timezone by `tz_str` +pub fn set_default_timezone(tz_str: Option<&str>) -> Result<()> { let tz = match tz_str { - None | Some("") => TimeZone::Named(Tz::UTC), - Some(tz) => TimeZone::from_tz_string(tz)?, + None | Some("") => Timezone::Named(Tz::UTC), + Some(tz) => Timezone::from_tz_string(tz)?, }; - DEFAULT_TIME_ZONE.get_or_init(|| tz); + DEFAULT_TIMEZONE.get_or_init(|| tz); Ok(()) } #[inline(always)] -/// If the `tz=Some(time_zone)`, return `time_zone` directly, -/// or return current system time zone. -pub fn get_time_zone(tz: Option) -> TimeZone { - tz.or(DEFAULT_TIME_ZONE.get().cloned()) - .unwrap_or(TimeZone::Named(Tz::UTC)) +/// If the `tz=Some(timezone)`, return `timezone` directly, +/// or return current system timezone. +pub fn get_timezone(tz: Option) -> Timezone { + tz.unwrap_or_else(|| { + DEFAULT_TIMEZONE + .get() + .cloned() + .unwrap_or(Timezone::Named(Tz::UTC)) + }) } #[derive(Debug, Clone, PartialEq, Eq)] -pub enum TimeZone { +pub enum Timezone { Offset(FixedOffset), Named(Tz), } -impl TimeZone { +impl Timezone { /// Compute timezone from given offset hours and minutes /// Return `Err` if given offset exceeds scope pub fn hours_mins_opt(offset_hours: i32, offset_mins: u32) -> Result { @@ -66,7 +70,7 @@ impl TimeZone { FixedOffset::east_opt(offset_secs) .map(Self::Offset) - .context(InvalidTimeZoneOffsetSnafu { + .context(InvalidTimezoneOffsetSnafu { hours: offset_hours, minutes: offset_mins, }) @@ -84,7 +88,7 @@ impl TimeZone { pub fn from_tz_string(tz_string: &str) -> Result { // Use system timezone if tz_string.eq_ignore_ascii_case("SYSTEM") { - Ok(TimeZone::Named(find_tz_from_env().unwrap_or(Tz::UTC))) + Ok(Timezone::Named(find_tz_from_env().unwrap_or(Tz::UTC))) } else if let Some((hrs, mins)) = tz_string.split_once(':') { let hrs = hrs .parse::() @@ -96,12 +100,12 @@ impl TimeZone { } else if let Ok(tz) = Tz::from_str(tz_string) { Ok(Self::Named(tz)) } else { - ParseTimeZoneNameSnafu { raw: tz_string }.fail() + ParseTimezoneNameSnafu { raw: tz_string }.fail() } } } -impl Display for TimeZone { +impl Display for Timezone { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Named(tz) => write!(f, "{}", tz.name()), @@ -111,9 +115,9 @@ impl Display for TimeZone { } #[inline] -/// Return current system config time zone, default config is UTC -pub fn system_time_zone_name() -> String { - format!("{}", get_time_zone(None)) +/// Return current system config timezone, default config is UTC +pub fn system_timezone_name() -> String { + format!("{}", get_timezone(None)) } #[cfg(test)] @@ -123,55 +127,55 @@ mod tests { #[test] fn test_from_tz_string() { assert_eq!( - TimeZone::Named(Tz::UTC), - TimeZone::from_tz_string("SYSTEM").unwrap() + Timezone::Named(Tz::UTC), + Timezone::from_tz_string("SYSTEM").unwrap() ); - let utc_plus_8 = TimeZone::Offset(FixedOffset::east_opt(3600 * 8).unwrap()); - assert_eq!(utc_plus_8, TimeZone::from_tz_string("+8:00").unwrap()); - assert_eq!(utc_plus_8, TimeZone::from_tz_string("+08:00").unwrap()); - assert_eq!(utc_plus_8, TimeZone::from_tz_string("08:00").unwrap()); + let utc_plus_8 = Timezone::Offset(FixedOffset::east_opt(3600 * 8).unwrap()); + assert_eq!(utc_plus_8, Timezone::from_tz_string("+8:00").unwrap()); + assert_eq!(utc_plus_8, Timezone::from_tz_string("+08:00").unwrap()); + assert_eq!(utc_plus_8, Timezone::from_tz_string("08:00").unwrap()); - let utc_minus_8 = TimeZone::Offset(FixedOffset::west_opt(3600 * 8).unwrap()); - assert_eq!(utc_minus_8, TimeZone::from_tz_string("-08:00").unwrap()); - assert_eq!(utc_minus_8, TimeZone::from_tz_string("-8:00").unwrap()); + let utc_minus_8 = Timezone::Offset(FixedOffset::west_opt(3600 * 8).unwrap()); + assert_eq!(utc_minus_8, Timezone::from_tz_string("-08:00").unwrap()); + assert_eq!(utc_minus_8, Timezone::from_tz_string("-8:00").unwrap()); - let utc_minus_8_5 = TimeZone::Offset(FixedOffset::west_opt(3600 * 8 + 60 * 30).unwrap()); - assert_eq!(utc_minus_8_5, TimeZone::from_tz_string("-8:30").unwrap()); + let utc_minus_8_5 = Timezone::Offset(FixedOffset::west_opt(3600 * 8 + 60 * 30).unwrap()); + assert_eq!(utc_minus_8_5, Timezone::from_tz_string("-8:30").unwrap()); - let utc_plus_max = TimeZone::Offset(FixedOffset::east_opt(3600 * 14).unwrap()); - assert_eq!(utc_plus_max, TimeZone::from_tz_string("14:00").unwrap()); + let utc_plus_max = Timezone::Offset(FixedOffset::east_opt(3600 * 14).unwrap()); + assert_eq!(utc_plus_max, Timezone::from_tz_string("14:00").unwrap()); - let utc_minus_max = TimeZone::Offset(FixedOffset::west_opt(3600 * 13 + 60 * 59).unwrap()); - assert_eq!(utc_minus_max, TimeZone::from_tz_string("-13:59").unwrap()); + let utc_minus_max = Timezone::Offset(FixedOffset::west_opt(3600 * 13 + 60 * 59).unwrap()); + assert_eq!(utc_minus_max, Timezone::from_tz_string("-13:59").unwrap()); assert_eq!( - TimeZone::Named(Tz::Asia__Shanghai), - TimeZone::from_tz_string("Asia/Shanghai").unwrap() + Timezone::Named(Tz::Asia__Shanghai), + Timezone::from_tz_string("Asia/Shanghai").unwrap() ); assert_eq!( - TimeZone::Named(Tz::UTC), - TimeZone::from_tz_string("UTC").unwrap() + Timezone::Named(Tz::UTC), + Timezone::from_tz_string("UTC").unwrap() ); - assert!(TimeZone::from_tz_string("WORLD_PEACE").is_err()); - assert!(TimeZone::from_tz_string("A0:01").is_err()); - assert!(TimeZone::from_tz_string("20:0A").is_err()); - assert!(TimeZone::from_tz_string(":::::").is_err()); - assert!(TimeZone::from_tz_string("Asia/London").is_err()); - assert!(TimeZone::from_tz_string("Unknown").is_err()); + assert!(Timezone::from_tz_string("WORLD_PEACE").is_err()); + assert!(Timezone::from_tz_string("A0:01").is_err()); + assert!(Timezone::from_tz_string("20:0A").is_err()); + assert!(Timezone::from_tz_string(":::::").is_err()); + assert!(Timezone::from_tz_string("Asia/London").is_err()); + assert!(Timezone::from_tz_string("Unknown").is_err()); } #[test] fn test_timezone_to_string() { - assert_eq!("UTC", TimeZone::Named(Tz::UTC).to_string()); + assert_eq!("UTC", Timezone::Named(Tz::UTC).to_string()); assert_eq!( "+01:00", - TimeZone::from_tz_string("01:00").unwrap().to_string() + Timezone::from_tz_string("01:00").unwrap().to_string() ); assert_eq!( "Asia/Shanghai", - TimeZone::from_tz_string("Asia/Shanghai") + Timezone::from_tz_string("Asia/Shanghai") .unwrap() .to_string() ); diff --git a/src/common/time/src/util.rs b/src/common/time/src/util.rs index 10e7d6cc1383..1a890ec2092f 100644 --- a/src/common/time/src/util.rs +++ b/src/common/time/src/util.rs @@ -17,21 +17,21 @@ use std::str::FromStr; use chrono::{LocalResult, NaiveDateTime, TimeZone}; use chrono_tz::Tz; -use crate::timezone::get_time_zone; +use crate::timezone::get_timezone; pub fn format_utc_datetime(utc: &NaiveDateTime, pattern: &str) -> String { - match get_time_zone(None) { - crate::TimeZone::Offset(offset) => { + match get_timezone(None) { + crate::Timezone::Offset(offset) => { offset.from_utc_datetime(utc).format(pattern).to_string() } - crate::TimeZone::Named(tz) => tz.from_utc_datetime(utc).format(pattern).to_string(), + crate::Timezone::Named(tz) => tz.from_utc_datetime(utc).format(pattern).to_string(), } } pub fn local_datetime_to_utc(local: &NaiveDateTime) -> LocalResult { - match get_time_zone(None) { - crate::TimeZone::Offset(offset) => offset.from_local_datetime(local).map(|x| x.naive_utc()), - crate::TimeZone::Named(tz) => tz.from_local_datetime(local).map(|x| x.naive_utc()), + match get_timezone(None) { + crate::Timezone::Offset(offset) => offset.from_local_datetime(local).map(|x| x.naive_utc()), + crate::Timezone::Named(tz) => tz.from_local_datetime(local).map(|x| x.naive_utc()), } } diff --git a/src/datatypes/src/time.rs b/src/datatypes/src/time.rs index d10eb6e65481..845e1dd25c5a 100644 --- a/src/datatypes/src/time.rs +++ b/src/datatypes/src/time.rs @@ -120,13 +120,13 @@ define_time_with_unit!(Nanosecond, i64); #[cfg(test)] mod tests { - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use super::*; #[test] fn test_to_serde_json_value() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); let time = TimeSecond::new(123); let val = serde_json::Value::from(time); match val { diff --git a/src/datatypes/src/timestamp.rs b/src/datatypes/src/timestamp.rs index 5abf92361d75..f434d2e3766e 100644 --- a/src/datatypes/src/timestamp.rs +++ b/src/datatypes/src/timestamp.rs @@ -122,13 +122,13 @@ define_timestamp_with_unit!(Nanosecond); #[cfg(test)] mod tests { - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use super::*; #[test] fn test_to_serde_json_value() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); let ts = TimestampSecond::new(123); let val = serde_json::Value::from(ts); match val { diff --git a/src/datatypes/src/types/cast.rs b/src/datatypes/src/types/cast.rs index 979597897bcc..d92f5f9bbfbb 100644 --- a/src/datatypes/src/types/cast.rs +++ b/src/datatypes/src/types/cast.rs @@ -176,7 +176,7 @@ mod tests { use common_base::bytes::StringBytes; use common_time::time::Time; - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use common_time::{Date, DateTime, Timestamp}; use ordered_float::OrderedFloat; @@ -214,7 +214,7 @@ mod tests { #[test] fn test_cast_with_opt() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); // non-strict mode let cast_option = CastOption { strict: false }; let src_value = Value::Int8(-1); diff --git a/src/datatypes/src/types/date_type.rs b/src/datatypes/src/types/date_type.rs index 86c046a79e83..a0df0b5a2151 100644 --- a/src/datatypes/src/types/date_type.rs +++ b/src/datatypes/src/types/date_type.rs @@ -101,7 +101,7 @@ impl LogicalPrimitiveType for DateType { #[cfg(test)] mod tests { use common_base::bytes::StringBytes; - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use common_time::Timestamp; use super::*; @@ -109,7 +109,7 @@ mod tests { // $TZ doesn't take effort #[test] fn test_date_cast() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); // timestamp -> date let ts = Value::Timestamp(Timestamp::from_str("2000-01-01 08:00:01").unwrap()); let date = ConcreteDataType::date_datatype().try_cast(ts).unwrap(); diff --git a/src/datatypes/src/types/datetime_type.rs b/src/datatypes/src/types/datetime_type.rs index 88f0c6ac400d..4e23982a2e34 100644 --- a/src/datatypes/src/types/datetime_type.rs +++ b/src/datatypes/src/types/datetime_type.rs @@ -101,7 +101,7 @@ impl LogicalPrimitiveType for DateTimeType { #[cfg(test)] mod tests { - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use common_time::Timestamp; use super::*; @@ -114,7 +114,7 @@ mod tests { assert_eq!(dt, Value::DateTime(DateTime::from(1000))); // cast from String - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); let val = Value::String("1970-01-01 00:00:00+0800".into()); let dt = ConcreteDataType::datetime_datatype().try_cast(val).unwrap(); assert_eq!( diff --git a/src/datatypes/src/types/timestamp_type.rs b/src/datatypes/src/types/timestamp_type.rs index 19a4ede1e354..bca9d3e8e2e2 100644 --- a/src/datatypes/src/types/timestamp_type.rs +++ b/src/datatypes/src/types/timestamp_type.rs @@ -203,7 +203,7 @@ impl_data_type_for_timestamp!(Microsecond); #[cfg(test)] mod tests { - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use common_time::{Date, DateTime}; use super::*; @@ -231,7 +231,7 @@ mod tests { // $TZ doesn't take effort #[test] fn test_timestamp_cast() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); // String -> TimestampSecond let s = Value::String("2021-01-01 01:02:03".to_string().into()); let ts = ConcreteDataType::timestamp_second_datatype() diff --git a/src/datatypes/src/value.rs b/src/datatypes/src/value.rs index 791d6f028c7b..b53a96a2c434 100644 --- a/src/datatypes/src/value.rs +++ b/src/datatypes/src/value.rs @@ -1190,7 +1190,7 @@ impl<'a> ValueRef<'a> { #[cfg(test)] mod tests { use arrow::datatypes::DataType as ArrowDataType; - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use num_traits::Float; use super::*; @@ -1876,7 +1876,7 @@ mod tests { #[test] fn test_display() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); assert_eq!(Value::Null.to_string(), "Null"); assert_eq!(Value::UInt8(8).to_string(), "8"); assert_eq!(Value::UInt16(16).to_string(), "16"); diff --git a/src/datatypes/src/vectors/datetime.rs b/src/datatypes/src/vectors/datetime.rs index 99e2bdb7add5..8a29648e6e07 100644 --- a/src/datatypes/src/vectors/datetime.rs +++ b/src/datatypes/src/vectors/datetime.rs @@ -26,7 +26,7 @@ mod tests { use arrow::array::{Array, PrimitiveArray}; use arrow_array::ArrayRef; - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use common_time::DateTime; use super::*; @@ -38,7 +38,7 @@ mod tests { #[test] fn test_datetime_vector() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); let v = DateTimeVector::new(PrimitiveArray::from(vec![1000, 2000, 3000])); assert_eq!(ConcreteDataType::datetime_datatype(), v.data_type()); assert_eq!(3, v.len()); diff --git a/src/frontend/src/frontend.rs b/src/frontend/src/frontend.rs index 270b053d7ccf..18140e6566f8 100644 --- a/src/frontend/src/frontend.rs +++ b/src/frontend/src/frontend.rs @@ -32,7 +32,7 @@ use crate::service_config::{ pub struct FrontendOptions { pub mode: Mode, pub node_id: Option, - pub default_time_zone: Option, + pub default_timezone: Option, pub heartbeat: HeartbeatOptions, pub http: HttpOptions, pub grpc: GrpcOptions, @@ -54,7 +54,7 @@ impl Default for FrontendOptions { Self { mode: Mode::Standalone, node_id: None, - default_time_zone: None, + default_timezone: None, heartbeat: HeartbeatOptions::frontend_default(), http: HttpOptions::default(), grpc: GrpcOptions::default(), diff --git a/src/servers/src/mysql/federated.rs b/src/servers/src/mysql/federated.rs index 9600438817db..d59d97deb0ef 100644 --- a/src/servers/src/mysql/federated.rs +++ b/src/servers/src/mysql/federated.rs @@ -21,8 +21,8 @@ use std::sync::Arc; use common_query::Output; use common_recordbatch::RecordBatches; -use common_time::timezone::system_time_zone_name; -use common_time::TimeZone; +use common_time::timezone::system_timezone_name; +use common_time::Timezone; use datatypes::prelude::ConcreteDataType; use datatypes::schema::{ColumnSchema, Schema}; use datatypes::vectors::StringVector; @@ -55,7 +55,7 @@ static SELECT_TIME_DIFF_FUNC_PATTERN: Lazy = static SHOW_SQL_MODE_PATTERN: Lazy = Lazy::new(|| Regex::new("(?i)^(SHOW VARIABLES LIKE 'sql_mode'(.*))").unwrap()); -// Time zone settings +// Timezone settings static SET_TIME_ZONE_PATTERN: Lazy = Lazy::new(|| Regex::new(r"(?i)^SET TIME_ZONE\s*=\s*'(\S+)'").unwrap()); @@ -200,8 +200,8 @@ fn select_variable(query: &str, query_context: QueryContextRef) -> Option query_context.time_zone().to_string(), - "system_time_zone" => system_time_zone_name(), + "time_zone" => query_context.timezone().to_string(), + "system_time_zone" => system_timezone_name(), _ => VAR_VALUES .get(var_as[0]) .map(|v| v.to_string()) @@ -268,8 +268,8 @@ fn check_set_variables(query: &str, session: SessionRef) -> Option { if let Some(captures) = SET_TIME_ZONE_PATTERN.captures(query) { // get the capture let tz = captures.get(1).unwrap(); - if let Ok(timezone) = TimeZone::from_tz_string(tz.as_str()) { - session.set_time_zone(timezone); + if let Ok(timezone) = Timezone::from_tz_string(tz.as_str()) { + session.set_timezone(timezone); return Some(Output::AffectedRows(0)); } } @@ -328,7 +328,7 @@ fn get_version() -> String { #[cfg(test)] mod test { - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use session::context::{Channel, QueryContext}; use session::Session; @@ -389,7 +389,7 @@ mod test { test(query, expected); // set system timezone - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); // complex variables let query = "/* mysql-connector-java-8.0.17 (Revision: 16a712ddb3f826a1933ab42b0039f7fb9eebc6ec) */SELECT @@session.auto_increment_increment AS auto_increment_increment, @@character_set_client AS character_set_client, @@character_set_connection AS character_set_connection, @@character_set_results AS character_set_results, @@character_set_server AS character_set_server, @@collation_server AS collation_server, @@collation_connection AS collation_connection, @@init_connect AS init_connect, @@interactive_timeout AS interactive_timeout, @@license AS license, @@lower_case_table_names AS lower_case_table_names, @@max_allowed_packet AS max_allowed_packet, @@net_write_timeout AS net_write_timeout, @@performance_schema AS performance_schema, @@sql_mode AS sql_mode, @@system_time_zone AS system_time_zone, @@time_zone AS time_zone, @@transaction_isolation AS transaction_isolation, @@wait_timeout AS wait_timeout;"; let expected = "\ @@ -435,17 +435,17 @@ mod test { } #[test] - fn test_set_time_zone() { + fn test_set_timezone() { // test default is UTC when no config in greptimedb { let session = Arc::new(Session::new(None, Channel::Mysql)); let query_context = session.new_query_context(); - assert_eq!("UTC", query_context.time_zone().to_string()); + assert_eq!("UTC", query_context.timezone().to_string()); } - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); let session = Arc::new(Session::new(None, Channel::Mysql)); let query_context = session.new_query_context(); - assert_eq!("Asia/Shanghai", query_context.time_zone().to_string()); + assert_eq!("Asia/Shanghai", query_context.timezone().to_string()); let output = check( "set time_zone = 'UTC'", QueryContext::arc(), @@ -458,7 +458,7 @@ mod test { _ => unreachable!(), } let query_context = session.new_query_context(); - assert_eq!("UTC", query_context.time_zone().to_string()); + assert_eq!("UTC", query_context.timezone().to_string()); let output = check("select @@time_zone", query_context.clone(), session.clone()); match output.unwrap() { diff --git a/src/servers/src/mysql/writer.rs b/src/servers/src/mysql/writer.rs index c3461ab35ed5..00c6ee08e052 100644 --- a/src/servers/src/mysql/writer.rs +++ b/src/servers/src/mysql/writer.rs @@ -194,10 +194,10 @@ impl<'a, W: AsyncWrite + Unpin> MysqlResultWriter<'a, W> { Value::Date(v) => row_writer.write_col(v.to_chrono_date())?, // convert datetime and timestamp to timezone of current connection Value::DateTime(v) => row_writer.write_col( - v.to_chrono_datetime_with_timezone(Some(query_context.time_zone())), + v.to_chrono_datetime_with_timezone(Some(query_context.timezone())), )?, Value::Timestamp(v) => row_writer.write_col( - v.to_chrono_datetime_with_timezone(Some(query_context.time_zone())), + v.to_chrono_datetime_with_timezone(Some(query_context.timezone())), )?, Value::Interval(v) => row_writer.write_col(v.to_iso8601_string())?, Value::Duration(v) => row_writer.write_col(v.to_std_duration())?, @@ -210,7 +210,7 @@ impl<'a, W: AsyncWrite + Unpin> MysqlResultWriter<'a, W> { }) } Value::Time(v) => row_writer - .write_col(v.to_timezone_aware_string(Some(query_context.time_zone())))?, + .write_col(v.to_timezone_aware_string(Some(query_context.timezone())))?, Value::Decimal128(v) => row_writer.write_col(v.to_string())?, } } diff --git a/src/session/src/context.rs b/src/session/src/context.rs index 5b7ad7d219de..256217d78502 100644 --- a/src/session/src/context.rs +++ b/src/session/src/context.rs @@ -21,8 +21,8 @@ use arc_swap::ArcSwap; use auth::UserInfoRef; use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME}; use common_catalog::{build_db_string, parse_catalog_and_schema_from_db_string}; -use common_time::timezone::get_time_zone; -use common_time::TimeZone; +use common_time::timezone::get_timezone; +use common_time::Timezone; use derive_builder::Builder; use sql::dialect::{Dialect, GreptimeDbDialect, MySqlDialect, PostgreSqlDialect}; @@ -36,7 +36,7 @@ pub struct QueryContext { current_catalog: String, current_schema: String, current_user: ArcSwap>, - time_zone: TimeZone, + timezone: Timezone, sql_dialect: Box, } @@ -58,7 +58,7 @@ impl From<&RegionRequestHeader> for QueryContext { current_catalog: catalog.to_string(), current_schema: schema.to_string(), current_user: Default::default(), - time_zone: get_time_zone(None), + timezone: get_timezone(None), sql_dialect: Box::new(GreptimeDbDialect {}), } } @@ -116,8 +116,8 @@ impl QueryContext { } #[inline] - pub fn time_zone(&self) -> TimeZone { - self.time_zone.clone() + pub fn timezone(&self) -> Timezone { + self.timezone.clone() } #[inline] @@ -143,7 +143,7 @@ impl QueryContextBuilder { current_user: self .current_user .unwrap_or_else(|| ArcSwap::new(Arc::new(None))), - time_zone: self.time_zone.unwrap_or(get_time_zone(None)), + timezone: self.timezone.unwrap_or(get_timezone(None)), sql_dialect: self .sql_dialect .unwrap_or_else(|| Box::new(GreptimeDbDialect {})), diff --git a/src/session/src/lib.rs b/src/session/src/lib.rs index eeeb8551b1ac..49290826a069 100644 --- a/src/session/src/lib.rs +++ b/src/session/src/lib.rs @@ -21,8 +21,8 @@ use arc_swap::ArcSwap; use auth::UserInfoRef; use common_catalog::build_db_string; use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME}; -use common_time::timezone::get_time_zone; -use common_time::TimeZone; +use common_time::timezone::get_timezone; +use common_time::Timezone; use context::QueryContextBuilder; use crate::context::{Channel, ConnInfo, QueryContextRef}; @@ -34,7 +34,7 @@ pub struct Session { schema: ArcSwap, user_info: ArcSwap, conn_info: ConnInfo, - time_zone: ArcSwap, + timezone: ArcSwap, } pub type SessionRef = Arc; @@ -46,7 +46,7 @@ impl Session { schema: ArcSwap::new(Arc::new(DEFAULT_SCHEMA_NAME.into())), user_info: ArcSwap::new(Arc::new(auth::userinfo_by_name(None))), conn_info: ConnInfo::new(addr, channel), - time_zone: ArcSwap::new(Arc::new(get_time_zone(None))), + timezone: ArcSwap::new(Arc::new(get_timezone(None))), } } @@ -59,7 +59,7 @@ impl Session { .current_catalog(self.catalog.load().to_string()) .current_schema(self.schema.load().to_string()) .sql_dialect(self.conn_info.channel.dialect()) - .time_zone((**self.time_zone.load()).clone()) + .timezone((**self.timezone.load()).clone()) .build() } @@ -74,13 +74,13 @@ impl Session { } #[inline] - pub fn time_zone(&self) -> TimeZone { - self.time_zone.load().as_ref().clone() + pub fn timezone(&self) -> Timezone { + self.timezone.load().as_ref().clone() } #[inline] - pub fn set_time_zone(&self, tz: TimeZone) { - let _ = self.time_zone.swap(Arc::new(tz)); + pub fn set_timezone(&self, tz: Timezone) { + let _ = self.timezone.swap(Arc::new(tz)); } #[inline] diff --git a/src/sql/src/statements.rs b/src/sql/src/statements.rs index 3c42a0c81aef..ebc1c4d9f4fe 100644 --- a/src/sql/src/statements.rs +++ b/src/sql/src/statements.rs @@ -521,7 +521,7 @@ mod tests { use api::v1::ColumnDataType; use common_time::timestamp::TimeUnit; - use common_time::timezone::set_default_time_zone; + use common_time::timezone::set_default_timezone; use datatypes::types::BooleanType; use datatypes::value::OrderedFloat; @@ -697,7 +697,7 @@ mod tests { #[test] pub fn test_parse_datetime_literal() { - set_default_time_zone(Some("Asia/Shanghai")).unwrap(); + set_default_timezone(Some("Asia/Shanghai")).unwrap(); let value = sql_value_to_value( "datetime_col", &ConcreteDataType::datetime_datatype(), diff --git a/tests-integration/tests/sql.rs b/tests-integration/tests/sql.rs index 2b747a554a75..93566296fab0 100644 --- a/tests-integration/tests/sql.rs +++ b/tests-integration/tests/sql.rs @@ -219,8 +219,8 @@ pub async fn test_mysql_timezone(store_type: StorageType) { .unwrap(); let _ = conn.execute("SET time_zone = 'UTC'").await.unwrap(); - let time_zone = conn.fetch_all("SELECT @@time_zone").await.unwrap(); - assert_eq!(time_zone[0].get::(0), "UTC"); + let timezone = conn.fetch_all("SELECT @@time_zone").await.unwrap(); + assert_eq!(timezone[0].get::(0), "UTC"); // test data let _ = conn