Debian Codegraph @

src/types/time.rs

raw symbols SCIP
1 use byteorder::{ByteOrder, LittleEndian};
2 use bytes::Buf;
3 use sqlx_core::database::Database;
4 use time::macros::format_description;
5 use time::{Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset};
6
7 use crate::decode::Decode;
8 use crate::encode::{Encode, IsNull};
9 use crate::error::{BoxDynError, UnexpectedNullError};
10 use crate::protocol::text::ColumnType;
11 use crate::type_info::MySqlTypeInfo;
12 use crate::types::{MySqlTime, MySqlTimeSign, Type};
13 use crate::{MySql, MySqlValueFormat, MySqlValueRef};
14
15 impl Type<MySql> for OffsetDateTime {
16 fn type_info() -> MySqlTypeInfo {
17 MySqlTypeInfo::binary(ColumnType::Timestamp)
18 }
19
20 fn compatible(ty: &MySqlTypeInfo) -> bool {
21 matches!(ty.r#type, ColumnType::Datetime | ColumnType::Timestamp)
22 }
23 }
24
25 impl Encode<'_, MySql> for OffsetDateTime {
26 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
27 let utc_dt = self.to_offset(UtcOffset::UTC);
28 let primitive_dt = PrimitiveDateTime::new(utc_dt.date(), utc_dt.time());
29
30 Encode::<MySql>::encode(primitive_dt, buf)
31 }
32 }
33
34 impl<'r> Decode<'r, MySql> for OffsetDateTime {
35 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
36 let primitive: PrimitiveDateTime = Decode::<MySql>::decode(value)?;
37
38 Ok(primitive.assume_utc())
39 }
40 }
41
42 impl Type<MySql> for Time {
43 fn type_info() -> MySqlTypeInfo {
44 MySqlTypeInfo::binary(ColumnType::Time)
45 }
46 }
47
48 impl Encode<'_, MySql> for Time {
49 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
50 let len = time_encoded_len(self);
51 buf.push(len);
52
53 // sign byte: Time is never negative
54 buf.push(0);
55
56 // Number of days in the interval; always 0 for time-of-day values.
57 // https://mariadb.com/kb/en/resultset-row/#teimstamp-binary-encoding
58 buf.extend_from_slice(&[0_u8; 4]);
59
60 encode_time(self, len > 8, buf);
61
62 Ok(IsNull::No)
63 }
64
65 fn size_hint(&self) -> usize {
66 time_encoded_len(self) as usize + 1 // plus length byte
67 }
68 }
69
70 impl<'r> Decode<'r, MySql> for Time {
71 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
72 match value.format() {
73 MySqlValueFormat::Binary => {
74 // Should never panic.
75 MySqlTime::decode(value)?.try_into()
76 }
77
78 // Retaining this parsing for now as it allows us to cross-check our impl.
79 MySqlValueFormat::Text => Time::parse(
80 value.as_str()?,
81 &format_description!("[hour]:[minute]:[second].[subsecond]"),
82 )
83 .map_err(Into::into),
84 }
85 }
86 }
87
88 impl TryFrom<MySqlTime> for Time {
89 type Error = BoxDynError;
90
91 fn try_from(time: MySqlTime) -> Result<Self, Self::Error> {
92 if !time.is_valid_time_of_day() {
93 return Err(format!("MySqlTime value out of range for `time::Time`: {time}").into());
94 }
95
96 #[allow(clippy::cast_possible_truncation)]
97 Ok(Time::from_hms_micro(
98 // `is_valid_time_of_day()` ensures this won't overflow
99 time.hours() as u8,
100 time.minutes(),
101 time.seconds(),
102 time.microseconds(),
103 )?)
104 }
105 }
106
107 impl From<MySqlTime> for time::Duration {
108 fn from(time: MySqlTime) -> Self {
109 // `subsec_nanos()` is guaranteed to be between 0 and 10^9
110 #[allow(clippy::cast_possible_wrap)]
111 time::Duration::new(time.whole_seconds_signed(), time.subsec_nanos() as i32)
112 }
113 }
114
115 impl TryFrom<time::Duration> for MySqlTime {
116 type Error = BoxDynError;
117
118 fn try_from(value: time::Duration) -> Result<Self, Self::Error> {
119 let sign = if value.is_negative() {
120 MySqlTimeSign::Negative
121 } else {
122 MySqlTimeSign::Positive
123 };
124
125 // Similar to `TryFrom<chrono::TimeDelta>`, use `std::time::Duration` as an intermediate.
126 Ok(MySqlTime::try_from(std::time::Duration::try_from(value.abs())?)?.with_sign(sign))
127 }
128 }
129
130 impl Type<MySql> for time::Duration {
131 fn type_info() -> MySqlTypeInfo {
132 MySqlTime::type_info()
133 }
134 }
135
136 impl<'r> Decode<'r, MySql> for time::Duration {
137 fn decode(value: <MySql as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
138 Ok(MySqlTime::decode(value)?.into())
139 }
140 }
141
142 impl Type<MySql> for Date {
143 fn type_info() -> MySqlTypeInfo {
144 MySqlTypeInfo::binary(ColumnType::Date)
145 }
146 }
147
148 impl Encode<'_, MySql> for Date {
149 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
150 buf.push(4);
151
152 encode_date(self, buf)?;
153
154 Ok(IsNull::No)
155 }
156
157 fn size_hint(&self) -> usize {
158 5
159 }
160 }
161
162 impl<'r> Decode<'r, MySql> for Date {
163 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
164 match value.format() {
165 MySqlValueFormat::Binary => {
166 let buf = value.as_bytes()?;
167
168 // Row decoding should leave the length byte on the front.
169 if buf.is_empty() {
170 return Err("empty buffer".into());
171 }
172
173 Ok(decode_date(&buf[1..])?.ok_or(UnexpectedNullError)?)
174 }
175 MySqlValueFormat::Text => {
176 let s = value.as_str()?;
177 Date::parse(s, &format_description!("[year]-[month]-[day]")).map_err(Into::into)
178 }
179 }
180 }
181 }
182
183 impl Type<MySql> for PrimitiveDateTime {
184 fn type_info() -> MySqlTypeInfo {
185 MySqlTypeInfo::binary(ColumnType::Datetime)
186 }
187 }
188
189 impl Encode<'_, MySql> for PrimitiveDateTime {
190 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
191 let len = primitive_dt_encoded_len(self);
192 buf.push(len);
193
194 encode_date(&self.date(), buf)?;
195
196 if len > 4 {
197 encode_time(&self.time(), len > 7, buf);
198 }
199
200 Ok(IsNull::No)
201 }
202
203 fn size_hint(&self) -> usize {
204 primitive_dt_encoded_len(self) as usize + 1 // plus length byte
205 }
206 }
207
208 impl<'r> Decode<'r, MySql> for PrimitiveDateTime {
209 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
210 match value.format() {
211 MySqlValueFormat::Binary => {
212 let mut buf = value.as_bytes()?;
213
214 if buf.is_empty() {
215 return Err("empty buffer".into());
216 }
217
218 let len = buf.get_u8();
219
220 let date = decode_date(buf)?.ok_or(UnexpectedNullError)?;
221
222 let dt = if len > 4 {
223 date.with_time(decode_time(&buf[4..])?)
224 } else {
225 date.midnight()
226 };
227
228 Ok(dt)
229 }
230
231 MySqlValueFormat::Text => {
232 let s = value.as_str()?;
233
234 // If there are no nanoseconds parse without them
235 if s.contains('.') {
236 PrimitiveDateTime::parse(
237 s,
238 &format_description!(
239 "[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"
240 ),
241 )
242 .map_err(Into::into)
243 } else {
244 PrimitiveDateTime::parse(
245 s,
246 &format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"),
247 )
248 .map_err(Into::into)
249 }
250 }
251 }
252 }
253 }
254
255 fn encode_date(date: &Date, buf: &mut Vec<u8>) -> Result<(), BoxDynError> {
256 // MySQL supports years from 1000 - 9999
257 let year =
258 u16::try_from(date.year()).map_err(|_| format!("Date out of range for Mysql: {date}"))?;
259
260 buf.extend_from_slice(&year.to_le_bytes());
261 buf.push(date.month().into());
262 buf.push(date.day());
263
264 Ok(())
265 }
266
267 fn decode_date(buf: &[u8]) -> Result<Option<Date>, BoxDynError> {
268 if buf.is_empty() {
269 // zero buffer means a zero date (null)
270 return Ok(None);
271 }
272
273 Date::from_calendar_date(
274 LittleEndian::read_u16(buf) as i32,
275 time::Month::try_from(buf[2])?,
276 buf[3],
277 )
278 .map_err(Into::into)
279 .map(Some)
280 }
281
282 fn encode_time(time: &Time, include_micros: bool, buf: &mut Vec<u8>) {
283 buf.push(time.hour());
284 buf.push(time.minute());
285 buf.push(time.second());
286
287 if include_micros {
288 buf.extend(&(time.nanosecond() / 1000).to_le_bytes());
289 }
290 }
291
292 fn decode_time(mut buf: &[u8]) -> Result<Time, BoxDynError> {
293 let hour = buf.get_u8();
294 let minute = buf.get_u8();
295 let seconds = buf.get_u8();
296
297 let micros = if !buf.is_empty() {
298 // microseconds : int<EOF>
299 buf.get_uint_le(buf.len())
300 } else {
301 0
302 };
303
304 let micros = u32::try_from(micros)
305 .map_err(|_| format!("MySQL returned microseconds out of range: {micros}"))?;
306
307 Time::from_hms_micro(hour, minute, seconds, micros)
308 .map_err(|e| format!("Time out of range for MySQL: {e}").into())
309 }
310
311 #[inline(always)]
312 fn primitive_dt_encoded_len(time: &PrimitiveDateTime) -> u8 {
313 // to save space the packet can be compressed:
314 match (time.hour(), time.minute(), time.second(), time.nanosecond()) {
315 // if hour, minutes, seconds and micro_seconds are all 0,
316 // length is 4 and no other field is sent
317 (0, 0, 0, 0) => 4,
318
319 // if micro_seconds is 0, length is 7
320 // and micro_seconds is not sent
321 (_, _, _, 0) => 7,
322
323 // otherwise length is 11
324 (_, _, _, _) => 11,
325 }
326 }
327
328 #[inline(always)]
329 fn time_encoded_len(time: &Time) -> u8 {
330 if time.nanosecond() == 0 {
331 // if micro_seconds is 0, length is 8 and micro_seconds is not sent
332 8
333 } else {
334 // otherwise length is 12
335 12
336 }
337 }