Debian Codegraph @

src/types/chrono.rs

raw symbols SCIP
1 use bytes::Buf;
2 use chrono::{
3 DateTime, Datelike, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Timelike, Utc,
4 };
5 use sqlx_core::database::Database;
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 DateTime<Utc> {
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 /// Note: assumes the connection's `time_zone` is set to `+00:00` (UTC).
26 impl Encode<'_, MySql> for DateTime<Utc> {
27 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
28 Encode::<MySql>::encode(self.naive_utc(), buf)
29 }
30 }
31
32 /// Note: assumes the connection's `time_zone` is set to `+00:00` (UTC).
33 impl<'r> Decode<'r, MySql> for DateTime<Utc> {
34 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
35 let naive: NaiveDateTime = Decode::<MySql>::decode(value)?;
36
37 Ok(Utc.from_utc_datetime(&naive))
38 }
39 }
40
41 impl Type<MySql> for DateTime<Local> {
42 fn type_info() -> MySqlTypeInfo {
43 MySqlTypeInfo::binary(ColumnType::Timestamp)
44 }
45
46 fn compatible(ty: &MySqlTypeInfo) -> bool {
47 matches!(ty.r#type, ColumnType::Datetime | ColumnType::Timestamp)
48 }
49 }
50
51 /// Note: assumes the connection's `time_zone` is set to `+00:00` (UTC).
52 impl Encode<'_, MySql> for DateTime<Local> {
53 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
54 Encode::<MySql>::encode(self.naive_utc(), buf)
55 }
56 }
57
58 /// Note: assumes the connection's `time_zone` is set to `+00:00` (UTC).
59 impl<'r> Decode<'r, MySql> for DateTime<Local> {
60 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
61 Ok(<DateTime<Utc> as Decode<'r, MySql>>::decode(value)?.with_timezone(&Local))
62 }
63 }
64
65 impl Type<MySql> for NaiveTime {
66 fn type_info() -> MySqlTypeInfo {
67 MySqlTime::type_info()
68 }
69 }
70
71 impl Encode<'_, MySql> for NaiveTime {
72 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
73 let len = naive_time_encoded_len(self);
74 buf.push(len);
75
76 // NaiveTime is not negative
77 buf.push(0);
78
79 // Number of days in the interval; always 0 for time-of-day values.
80 // https://mariadb.com/kb/en/resultset-row/#teimstamp-binary-encoding
81 buf.extend_from_slice(&[0_u8; 4]);
82
83 encode_time(self, len > 8, buf);
84
85 Ok(IsNull::No)
86 }
87
88 fn size_hint(&self) -> usize {
89 naive_time_encoded_len(self) as usize + 1 // plus length byte
90 }
91 }
92
93 /// Decode from a `TIME` value.
94 ///
95 /// ### Errors
96 /// Returns an error if the `TIME` value is negative or exceeds `23:59:59.999999`.
97 impl<'r> Decode<'r, MySql> for NaiveTime {
98 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
99 match value.format() {
100 MySqlValueFormat::Binary => {
101 // Covers most possible failure modes.
102 MySqlTime::decode(value)?.try_into()
103 }
104 // Retaining this parsing for now as it allows us to cross-check our impl.
105 MySqlValueFormat::Text => {
106 let s = value.as_str()?;
107 NaiveTime::parse_from_str(s, "%H:%M:%S%.f").map_err(Into::into)
108 }
109 }
110 }
111 }
112
113 impl TryFrom<MySqlTime> for NaiveTime {
114 type Error = BoxDynError;
115
116 fn try_from(time: MySqlTime) -> Result<Self, Self::Error> {
117 NaiveTime::from_hms_micro_opt(
118 time.hours(),
119 time.minutes() as u32,
120 time.seconds() as u32,
121 time.microseconds(),
122 )
123 .ok_or_else(|| format!("Cannot convert `MySqlTime` value to `NaiveTime`: {time}").into())
124 }
125 }
126
127 impl From<MySqlTime> for chrono::TimeDelta {
128 fn from(time: MySqlTime) -> Self {
129 chrono::TimeDelta::new(time.whole_seconds_signed(), time.subsec_nanos())
130 .expect("BUG: chrono::TimeDelta should have a greater range than MySqlTime")
131 }
132 }
133
134 impl TryFrom<chrono::TimeDelta> for MySqlTime {
135 type Error = BoxDynError;
136
137 fn try_from(value: chrono::TimeDelta) -> Result<Self, Self::Error> {
138 let sign = if value < chrono::TimeDelta::zero() {
139 MySqlTimeSign::Negative
140 } else {
141 MySqlTimeSign::Positive
142 };
143
144 Ok(
145 // `std::time::Duration` has a greater positive range than `TimeDelta`
146 // which makes it a great intermediate if you ignore the sign.
147 MySqlTime::try_from(value.abs().to_std()?)?.with_sign(sign),
148 )
149 }
150 }
151
152 impl Type<MySql> for chrono::TimeDelta {
153 fn type_info() -> MySqlTypeInfo {
154 MySqlTime::type_info()
155 }
156 }
157
158 impl<'r> Decode<'r, MySql> for chrono::TimeDelta {
159 fn decode(value: <MySql as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
160 Ok(MySqlTime::decode(value)?.into())
161 }
162 }
163
164 impl Type<MySql> for NaiveDate {
165 fn type_info() -> MySqlTypeInfo {
166 MySqlTypeInfo::binary(ColumnType::Date)
167 }
168 }
169
170 impl Encode<'_, MySql> for NaiveDate {
171 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
172 buf.push(4);
173
174 encode_date(self, buf)?;
175
176 Ok(IsNull::No)
177 }
178
179 fn size_hint(&self) -> usize {
180 5
181 }
182 }
183
184 impl<'r> Decode<'r, MySql> for NaiveDate {
185 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
186 match value.format() {
187 MySqlValueFormat::Binary => {
188 let buf = value.as_bytes()?;
189
190 // Row decoding should have left the length prefix.
191 if buf.is_empty() {
192 return Err("empty buffer".into());
193 }
194
195 decode_date(&buf[1..])?.ok_or_else(|| UnexpectedNullError.into())
196 }
197
198 MySqlValueFormat::Text => {
199 let s = value.as_str()?;
200 NaiveDate::parse_from_str(s, "%Y-%m-%d").map_err(Into::into)
201 }
202 }
203 }
204 }
205
206 impl Type<MySql> for NaiveDateTime {
207 fn type_info() -> MySqlTypeInfo {
208 MySqlTypeInfo::binary(ColumnType::Datetime)
209 }
210 }
211
212 impl Encode<'_, MySql> for NaiveDateTime {
213 fn encode_by_ref(&self, buf: &mut Vec<u8>) -> Result<IsNull, BoxDynError> {
214 let len = naive_dt_encoded_len(self);
215 buf.push(len);
216
217 encode_date(&self.date(), buf)?;
218
219 if len > 4 {
220 encode_time(&self.time(), len > 7, buf);
221 }
222
223 Ok(IsNull::No)
224 }
225
226 fn size_hint(&self) -> usize {
227 naive_dt_encoded_len(self) as usize + 1 // plus length byte
228 }
229 }
230
231 impl<'r> Decode<'r, MySql> for NaiveDateTime {
232 fn decode(value: MySqlValueRef<'r>) -> Result<Self, BoxDynError> {
233 match value.format() {
234 MySqlValueFormat::Binary => {
235 let buf = value.as_bytes()?;
236
237 if buf.is_empty() {
238 return Err("empty buffer".into());
239 }
240
241 let len = buf[0];
242 let date = decode_date(&buf[1..])?.ok_or(UnexpectedNullError)?;
243
244 let dt = if len > 4 {
245 date.and_time(decode_time(len - 4, &buf[5..])?)
246 } else {
247 date.and_hms_opt(0, 0, 0)
248 .expect("expected `NaiveDate::and_hms_opt(0, 0, 0)` to be valid")
249 };
250
251 Ok(dt)
252 }
253
254 MySqlValueFormat::Text => {
255 let s = value.as_str()?;
256 NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f").map_err(Into::into)
257 }
258 }
259 }
260 }
261
262 fn encode_date(date: &NaiveDate, buf: &mut Vec<u8>) -> Result<(), BoxDynError> {
263 // MySQL supports years 1000 - 9999
264 let year = u16::try_from(date.year())
265 .map_err(|_| format!("NaiveDateTime out of range for Mysql: {date}"))?;
266
267 buf.extend_from_slice(&year.to_le_bytes());
268
269 // `NaiveDate` guarantees the ranges of these values
270 #[allow(clippy::cast_possible_truncation)]
271 {
272 buf.push(date.month() as u8);
273 buf.push(date.day() as u8);
274 }
275
276 Ok(())
277 }
278
279 fn decode_date(mut buf: &[u8]) -> Result<Option<NaiveDate>, BoxDynError> {
280 match buf.len() {
281 // MySQL specifies that if there are no bytes, this is all zeros
282 0 => Ok(None),
283 4.. => {
284 let year = buf.get_u16_le() as i32;
285 let month = buf[0] as u32;
286 let day = buf[1] as u32;
287
288 let date = NaiveDate::from_ymd_opt(year, month, day)
289 .ok_or_else(|| format!("server returned invalid date: {year}/{month}/{day}"))?;
290
291 Ok(Some(date))
292 }
293 len => Err(format!("expected at least 4 bytes for date, got {len}").into()),
294 }
295 }
296
297 fn encode_time(time: &NaiveTime, include_micros: bool, buf: &mut Vec<u8>) {
298 // `NaiveTime` API guarantees the ranges of these values
299 #[allow(clippy::cast_possible_truncation)]
300 {
301 buf.push(time.hour() as u8);
302 buf.push(time.minute() as u8);
303 buf.push(time.second() as u8);
304 }
305
306 if include_micros {
307 buf.extend((time.nanosecond() / 1000).to_le_bytes());
308 }
309 }
310
311 fn decode_time(len: u8, mut buf: &[u8]) -> Result<NaiveTime, BoxDynError> {
312 let hour = buf.get_u8();
313 let minute = buf.get_u8();
314 let seconds = buf.get_u8();
315
316 let micros = if len > 3 {
317 // microseconds : int<EOF>
318 buf.get_uint_le(buf.len())
319 } else {
320 0
321 };
322
323 let micros = u32::try_from(micros)
324 .map_err(|_| format!("server returned microseconds out of range: {micros}"))?;
325
326 NaiveTime::from_hms_micro_opt(hour as u32, minute as u32, seconds as u32, micros)
327 .ok_or_else(|| format!("server returned invalid time: {hour:02}:{minute:02}:{seconds:02}; micros: {micros}").into())
328 }
329
330 #[inline(always)]
331 fn naive_dt_encoded_len(time: &NaiveDateTime) -> u8 {
332 // to save space the packet can be compressed:
333 match (
334 time.hour(),
335 time.minute(),
336 time.second(),
337 #[allow(deprecated)]
338 time.timestamp_subsec_nanos(),
339 ) {
340 // if hour, minutes, seconds and micro_seconds are all 0,
341 // length is 4 and no other field is sent
342 (0, 0, 0, 0) => 4,
343
344 // if micro_seconds is 0, length is 7
345 // and micro_seconds is not sent
346 (_, _, _, 0) => 7,
347
348 // otherwise length is 11
349 (_, _, _, _) => 11,
350 }
351 }
352
353 #[inline(always)]
354 fn naive_time_encoded_len(time: &NaiveTime) -> u8 {
355 if time.nanosecond() == 0 {
356 // if micro_seconds is 0, length is 8 and micro_seconds is not sent
357 8
358 } else {
359 // otherwise length is 12
360 12
361 }
362 }