1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
#![cfg(feature = "time03")]
use std::{convert::TryFrom, str::from_utf8};
use time03::{
error::{Parse, TryFromParsed},
format_description::{modifier, Component, FormatItem},
Date, PrimitiveDateTime, Time,
};
use crate::value::Value;
use super::{parse_mysql_time_string, ConvIr, FromValueError, ParseIr};
lazy_static::lazy_static! {
static ref FULL_YEAR: modifier::Year = {
let mut year_modifier = modifier::Year::default();
year_modifier.padding = modifier::Padding::Zero;
year_modifier.repr = modifier::YearRepr::Full;
year_modifier.iso_week_based = false;
year_modifier.sign_is_mandatory = false;
year_modifier
};
static ref ZERO_PADDED_MONTH: modifier::Month = {
let mut month_modifier = modifier::Month::default();
month_modifier.padding = modifier::Padding::Zero;
month_modifier.repr = modifier::MonthRepr::Numerical;
month_modifier.case_sensitive = true;
month_modifier
};
static ref ZERO_PADDED_DAY: modifier::Day = {
let mut day_modifier = modifier::Day::default();
day_modifier.padding = modifier::Padding::Zero;
day_modifier
};
static ref ZERO_PADDED_HOUR: modifier::Hour = {
let mut hour_modifier = modifier::Hour::default();
hour_modifier.padding = modifier::Padding::Zero;
hour_modifier.is_12_hour_clock = false;
hour_modifier
};
static ref ZERO_PADDED_MINUTE: modifier::Minute = {
let mut minute_modifier = modifier::Minute::default();
minute_modifier.padding = modifier::Padding::Zero;
minute_modifier
};
static ref ZERO_PADDED_SECOND: modifier::Second = {
let mut second_modifier = modifier::Second::default();
second_modifier.padding = modifier::Padding::Zero;
second_modifier
};
static ref DATE_FORMAT: Vec<FormatItem<'static>> = {
vec![
FormatItem::Component(Component::Year(*FULL_YEAR)),
FormatItem::Literal(b"-"),
FormatItem::Component(Component::Month(*ZERO_PADDED_MONTH)),
FormatItem::Literal(b"-"),
FormatItem::Component(Component::Day(*ZERO_PADDED_DAY)),
]
};
static ref TIME_FORMAT: Vec<FormatItem<'static>> = {
vec![
FormatItem::Component(Component::Hour(*ZERO_PADDED_HOUR)),
FormatItem::Literal(b":"),
FormatItem::Component(Component::Minute(*ZERO_PADDED_MINUTE)),
FormatItem::Literal(b":"),
FormatItem::Component(Component::Second(*ZERO_PADDED_SECOND)),
]
};
static ref DATE_TIME_FORMAT: Vec<FormatItem<'static>> = {
let mut format = DATE_FORMAT.clone();
format.push(FormatItem::Literal(b" "));
format.extend_from_slice(&*TIME_FORMAT);
format
};
}
impl ConvIr<PrimitiveDateTime> for ParseIr<PrimitiveDateTime> {
fn new(value: Value) -> Result<ParseIr<PrimitiveDateTime>, FromValueError> {
match value {
Value::Date(year, month, day, hour, minute, second, micros) => Ok(ParseIr {
value: Value::Date(year, month, day, hour, minute, second, micros),
output: match create_primitive_date_time(
year, month, day, hour, minute, second, micros,
) {
Some(datetime) => datetime,
None => return Err(FromValueError(value)),
},
}),
Value::Bytes(bytes) => match parse_mysql_datetime_string_with_time(&*bytes) {
Ok(output) => Ok(ParseIr {
value: Value::Bytes(bytes),
output,
}),
Err(_) => Err(FromValueError(Value::Bytes(bytes))),
},
v => Err(FromValueError(v)),
}
}
fn commit(self) -> PrimitiveDateTime {
self.output
}
fn rollback(self) -> Value {
self.value
}
}
impl ConvIr<Date> for ParseIr<Date> {
fn new(value: Value) -> Result<ParseIr<Date>, FromValueError> {
match value {
Value::Date(year, month, day, hour, minute, second, micros) => {
let mon = match time03::Month::try_from(month) {
Ok(month) => month,
Err(_) => return Err(FromValueError(value)),
};
Ok(ParseIr {
value: Value::Date(year, month, day, hour, minute, second, micros),
output: match Date::from_calendar_date(year as i32, mon, day) {
Ok(date) => date,
Err(_) => return Err(FromValueError(value)),
},
})
}
Value::Bytes(bytes) => {
match from_utf8(&*bytes)
.ok()
.and_then(|s| Date::parse(s, &*DATE_FORMAT).ok())
{
Some(output) => Ok(ParseIr {
value: Value::Bytes(bytes),
output,
}),
None => Err(FromValueError(Value::Bytes(bytes))),
}
}
v => Err(FromValueError(v)),
}
}
fn commit(self) -> Date {
self.output
}
fn rollback(self) -> Value {
self.value
}
}
impl ConvIr<Time> for ParseIr<Time> {
fn new(value: Value) -> Result<ParseIr<Time>, FromValueError> {
match value {
Value::Time(false, 0, h, m, s, u) => Ok(ParseIr {
value: Value::Time(false, 0, h, m, s, u),
output: match Time::from_hms_micro(h, m, s, u) {
Ok(time) => time,
Err(_) => return Err(FromValueError(value)),
},
}),
Value::Bytes(bytes) => match parse_mysql_time_string_with_time(&*bytes) {
Ok(output) => Ok(ParseIr {
value: Value::Bytes(bytes),
output,
}),
Err(_) => Err(FromValueError(Value::Bytes(bytes))),
},
v => Err(FromValueError(v)),
}
}
fn commit(self) -> Time {
self.output
}
fn rollback(self) -> Value {
self.value
}
}
fn create_primitive_date_time(
year: u16,
month: u8,
day: u8,
hour: u8,
minute: u8,
second: u8,
micros: u32,
) -> Option<PrimitiveDateTime> {
let mon = time03::Month::try_from(month).ok()?;
if let Ok(date) = Date::from_calendar_date(year as i32, mon, day) {
if let Ok(time) = Time::from_hms_micro(hour, minute, second, micros) {
return Some(PrimitiveDateTime::new(date, time));
}
}
None
}
pub(crate) fn parse_mysql_datetime_string_with_time(
bytes: &[u8],
) -> Result<PrimitiveDateTime, Parse> {
from_utf8(&*bytes)
.map_err(|_| Parse::TryFromParsed(TryFromParsed::InsufficientInformation))
.and_then(|s| {
if s.len() >= 19 {
PrimitiveDateTime::parse(&s[..19], &*DATE_TIME_FORMAT)
} else if s.len() >= 10 {
PrimitiveDateTime::parse(s, &*DATE_FORMAT)
} else {
Err(Parse::TryFromParsed(TryFromParsed::InsufficientInformation))
}
})
}
fn parse_mysql_time_string_with_time(bytes: &[u8]) -> Result<Time, Parse> {
from_utf8(&*bytes)
.map_err(|_| Parse::TryFromParsed(TryFromParsed::InsufficientInformation))
.and_then(|s| Time::parse(s, &*TIME_FORMAT))
}
impl ConvIr<time03::Duration> for ParseIr<time03::Duration> {
fn new(v: Value) -> Result<ParseIr<time03::Duration>, FromValueError> {
match v {
Value::Time(is_neg, days, hours, minutes, seconds, microseconds) => {
let duration = time03::Duration::days(days.into())
+ time03::Duration::hours(hours.into())
+ time03::Duration::minutes(minutes.into())
+ time03::Duration::seconds(seconds.into())
+ time03::Duration::microseconds(microseconds.into());
Ok(ParseIr {
value: Value::Time(is_neg, days, hours, minutes, seconds, microseconds),
output: if is_neg { -duration } else { duration },
})
}
Value::Bytes(val_bytes) => {
let duration = match parse_mysql_time_string(&*val_bytes) {
Some((is_neg, hours, minutes, seconds, microseconds)) => {
let duration = time03::Duration::hours(hours.into())
+ time03::Duration::minutes(minutes.into())
+ time03::Duration::seconds(seconds.into())
+ time03::Duration::microseconds(microseconds.into());
if is_neg {
-duration
} else {
duration
}
}
_ => return Err(FromValueError(Value::Bytes(val_bytes))),
};
Ok(ParseIr {
value: Value::Bytes(val_bytes),
output: duration,
})
}
v => Err(FromValueError(v)),
}
}
fn commit(self) -> time03::Duration {
self.output
}
fn rollback(self) -> Value {
self.value
}
}
impl From<PrimitiveDateTime> for Value {
fn from(x: PrimitiveDateTime) -> Value {
Value::Date(
x.year() as u16,
x.month() as u8,
x.day(),
x.hour(),
x.minute(),
x.second(),
x.microsecond(),
)
}
}
impl From<Date> for Value {
fn from(x: Date) -> Value {
Value::Date(x.year() as u16, x.month() as u8, x.day(), 0, 0, 0, 0)
}
}
impl From<Time> for Value {
fn from(x: Time) -> Value {
Value::Time(
false,
0,
x.hour() as u8,
x.minute() as u8,
x.second() as u8,
x.microsecond(),
)
}
}
impl From<time03::Duration> for Value {
fn from(mut x: time03::Duration) -> Value {
let negative = x < time03::Duration::ZERO;
if negative {
x = -x;
}
let days = x.whole_days() as u32;
x = x - time03::Duration::days(x.whole_days());
let hours = x.whole_hours() as u8;
x = x - time03::Duration::hours(x.whole_hours());
let minutes = x.whole_minutes() as u8;
x = x - time03::Duration::minutes(x.whole_minutes());
let seconds = x.whole_seconds() as u8;
x = x - time03::Duration::seconds(x.whole_seconds());
let microseconds = x.whole_microseconds() as u32;
Value::Time(negative, days, hours, minutes, seconds, microseconds)
}
}
impl_from_value!(PrimitiveDateTime, ParseIr<PrimitiveDateTime>);
impl_from_value!(Date, ParseIr<Date>);
impl_from_value!(Time, ParseIr<Time>);
impl_from_value!(time03::Duration, ParseIr<time03::Duration>);
#[cfg(test)]
mod tests {
use time03::error::ParseFromDescription;
use super::*;
use proptest::prelude::*;
proptest! {
#[test]
fn parse_mysql_time_string_doesnt_crash(s in r"\PC*") {
parse_mysql_time_string(s.as_bytes());
let _ = parse_mysql_time_string_with_time(s.as_bytes());
}
#[test]
fn parse_mysql_datetime_string_parses_correctly(
y in 0u32..10000,
m in 0u32..12,
d in 1u32..32,
h in 0u32..60,
i in 0u32..60,
s in 0u32..60,
have_us in 0..2,
us in 0u32..1000000,
) {
let time_string = format!(
"{:04}-{:02}-{:02} {:02}:{:02}:{:02}{}",
y, m, d, h, i, s,
if have_us == 1 {
format!(".{:06}", us)
} else {
"".into()
}
);
match parse_mysql_datetime_string_with_time(time_string.as_bytes()) {
Ok(datetime) => {
assert_eq!(
(
datetime.year() as u32,
datetime.month() as u32,
datetime.day() as u32,
datetime.hour() as u32,
datetime.minute() as u32,
datetime.second() as u32,
0,
),
(y, m, d, h, i, s, 0));
},
Err(err) => {
match err {
Parse::ParseFromDescription(ParseFromDescription::InvalidComponent("second")) => assert!(s > 59),
Parse::ParseFromDescription(ParseFromDescription::InvalidComponent("minute")) => assert!(i > 59),
Parse::ParseFromDescription(ParseFromDescription::InvalidComponent("hour")) => assert!(h > 23),
Parse::ParseFromDescription(ParseFromDescription::InvalidComponent("dayofmonth")) => assert!(!(1..=31).contains(&d)),
Parse::ParseFromDescription(ParseFromDescription::InvalidComponent("month")) => assert!(m < 1000 || m <= 12),
Parse::ParseFromDescription(ParseFromDescription::InvalidComponent("year")) => assert!(y != 0 && !(1000..=9999).contains(&y)),
Parse::TryFromParsed(TryFromParsed::ComponentRange(_)) |
Parse::TryFromParsed(TryFromParsed::InsufficientInformation) => {
if Date::from_calendar_date(y as i32, time03::Month::January, 1).is_err() {
assert!(y != 0 && !(1000..=9999).contains(&y));
} else if time03::Month::try_from(m as u8).is_err() {
assert!(m < 1000 || m <= 12);
} else if Date::from_calendar_date(0, time03::Month::January, d as u8).is_err() {
assert!(!(1..=31).contains(&d));
} else if Time::from_hms_micro(h as u8, 0, 0, 0).is_err() {
assert!(h > 23);
} else if Time::from_hms_micro(0, i as u8, 0, 0).is_err() {
assert!(i > 59);
} else if Time::from_hms_micro(0, 0, s as u8, 0).is_err() {
assert!(i > 59);
}
},
err => {
panic!("Failed to parse time `{}` due to an unknown reason. {}", time_string, err);
}
}
}
}
}
}
}