musq 0.0.4

Musq is an asynchronous SQLite toolkit for Rust.
Documentation
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use std::result::Result as StdResult;

pub use time::{Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset};
use time::{
    format_description::{FormatItem, well_known::Rfc3339},
    macros::format_description as fd,
};

use crate::{
    Value,
    decode::Decode,
    encode::Encode,
    error::{DecodeError, EncodeError},
    sqlite::SqliteDataType,
};

impl Encode for OffsetDateTime {
    fn encode(&self) -> Result<Value, EncodeError> {
        let formatted = self.format(&Rfc3339).map_err(|e| {
            EncodeError::Conversion(format!("failed to format OffsetDateTime: {e}"))
        })?;
        Ok(Value::Text {
            value: formatted.into(),
            type_info: None,
        })
    }
}

impl Encode for PrimitiveDateTime {
    fn encode(&self) -> Result<Value, EncodeError> {
        let format = fd!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]");
        let formatted = self.format(&format).map_err(|e| {
            EncodeError::Conversion(format!("failed to format PrimitiveDateTime: {e}"))
        })?;
        Ok(Value::Text {
            value: formatted.into(),
            type_info: None,
        })
    }
}

impl Encode for Date {
    fn encode(&self) -> Result<Value, EncodeError> {
        let format = fd!("[year]-[month]-[day]");
        let formatted = self
            .format(&format)
            .map_err(|e| EncodeError::Conversion(format!("failed to format Date: {e}")))?;
        Ok(Value::Text {
            value: formatted.into(),
            type_info: None,
        })
    }
}

impl Encode for Time {
    fn encode(&self) -> Result<Value, EncodeError> {
        let format = fd!("[hour]:[minute]:[second].[subsecond]");
        let formatted = self
            .format(&format)
            .map_err(|e| EncodeError::Conversion(format!("failed to format Time: {e}")))?;
        Ok(Value::Text {
            value: formatted.into(),
            type_info: None,
        })
    }
}

impl<'r> Decode<'r> for OffsetDateTime {
    fn decode(value: &'r Value) -> StdResult<Self, DecodeError> {
        decode_offset_datetime(value)
    }
}

impl<'r> Decode<'r> for PrimitiveDateTime {
    fn decode(value: &'r Value) -> StdResult<Self, DecodeError> {
        decode_datetime(value)
    }
}

impl<'r> Decode<'r> for Date {
    fn decode(value: &'r Value) -> StdResult<Self, DecodeError> {
        Self::parse(value.text()?, &fd!("[year]-[month]-[day]"))
            .map_err(|e| DecodeError::Conversion(e.to_string()))
    }
}

impl<'r> Decode<'r> for Time {
    fn decode(value: &'r Value) -> StdResult<Self, DecodeError> {
        let value = value.text()?;

        let sqlite_time_formats = &[
            fd!("[hour]:[minute]:[second].[subsecond]"),
            fd!("[hour]:[minute]:[second]"),
            fd!("[hour]:[minute]"),
        ];

        for format in sqlite_time_formats {
            if let Ok(dt) = Self::parse(value, &format) {
                return Ok(dt);
            }
        }

        Err(format!("invalid time: {value}").into())
    }
}

/// Decode an offset datetime from a SQLite value.
fn decode_offset_datetime(value: &Value) -> StdResult<OffsetDateTime, DecodeError> {
    compatible!(
        value,
        SqliteDataType::Text
            | SqliteDataType::Int64
            | SqliteDataType::Int
            | SqliteDataType::Datetime
    );
    let dt = match value.type_info() {
        SqliteDataType::Text | SqliteDataType::Datetime => {
            decode_offset_datetime_from_text(value.text()?)
        }
        SqliteDataType::Int | SqliteDataType::Int64 => Some(
            OffsetDateTime::from_unix_timestamp(value.int64()?)
                .map_err(|e| DecodeError::Conversion(e.to_string()))?,
        ),

        _ => None,
    };

    if let Some(dt) = dt {
        Ok(dt)
    } else {
        Err(format!("invalid offset datetime: {}", value.text()?).into())
    }
}

/// Try parsing an offset datetime from text.
fn decode_offset_datetime_from_text(value: &str) -> Option<OffsetDateTime> {
    if let Ok(dt) = OffsetDateTime::parse(value, &Rfc3339) {
        return Some(dt);
    }

    if let Ok(dt) = OffsetDateTime::parse(value, formats::OFFSET_DATE_TIME) {
        return Some(dt);
    }

    if let Some(dt) = decode_datetime_from_text(value) {
        return Some(dt.assume_utc());
    }

    None
}

/// Decode a primitive datetime from a SQLite value.
fn decode_datetime(value: &Value) -> StdResult<PrimitiveDateTime, DecodeError> {
    compatible!(
        value,
        SqliteDataType::Text
            | SqliteDataType::Int64
            | SqliteDataType::Int
            | SqliteDataType::Datetime
    );
    let dt = match value.type_info() {
        SqliteDataType::Text | SqliteDataType::Datetime => decode_datetime_from_text(value.text()?),
        SqliteDataType::Int | SqliteDataType::Int64 => {
            let parsed = OffsetDateTime::from_unix_timestamp(value.int64()?)
                .map_err(|e| DecodeError::Conversion(e.to_string()))?;
            Some(PrimitiveDateTime::new(parsed.date(), parsed.time()))
        }
        _ => None,
    };

    if let Some(dt) = dt {
        Ok(dt)
    } else {
        Err(format!("invalid datetime: {}", value.text()?).into())
    }
}

/// Try parsing a primitive datetime from text.
fn decode_datetime_from_text(value: &str) -> Option<PrimitiveDateTime> {
    let default_format = fd!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]");
    if let Ok(dt) = PrimitiveDateTime::parse(value, &default_format) {
        return Some(dt);
    }

    let formats = [
        FormatItem::Compound(formats::PRIMITIVE_DATE_TIME_SPACE_SEPARATED),
        FormatItem::Compound(formats::PRIMITIVE_DATE_TIME_T_SEPARATED),
    ];

    if let Ok(dt) = PrimitiveDateTime::parse(value, &FormatItem::First(&formats)) {
        return Some(dt);
    }

    None
}

#[cfg(test)]
mod tests {
    use time::macros::{date, datetime, time};

    use super::*;
    use crate::{Value, sqlite::SqliteDataType};

    #[test]
    fn test_offset_datetime_encode_decode() {
        let dt = datetime!(2023-12-25 15:30:45.123456789 UTC);
        let encoded = dt.encode().unwrap();
        let decoded: OffsetDateTime = Decode::decode(&encoded).unwrap();
        assert_eq!(dt, decoded);
    }

    #[test]
    fn test_offset_datetime_encode_decode_with_offset() {
        let dt = datetime!(2023-12-25 15:30:45.123456789 +05:30);
        let encoded = dt.encode().unwrap();
        let decoded: OffsetDateTime = Decode::decode(&encoded).unwrap();
        assert_eq!(dt, decoded);
    }

    #[test]
    fn test_offset_datetime_decode_from_unix_timestamp() {
        let timestamp = 1703516445i64; // 2023-12-25 15:00:45 UTC
        let value = Value::Integer {
            value: timestamp,
            type_info: Some(SqliteDataType::Int64),
        };
        let decoded: OffsetDateTime = Decode::decode(&value).unwrap();
        let expected = OffsetDateTime::from_unix_timestamp(timestamp).unwrap();
        assert_eq!(decoded, expected);
    }

    #[test]
    fn test_offset_datetime_decode_various_text_formats() {
        // Test RFC3339 format
        let value = Value::Text {
            value: "2023-12-25T15:30:45.123Z".to_string().into(),
            type_info: Some(SqliteDataType::Text),
        };
        let decoded: OffsetDateTime = Decode::decode(&value).unwrap();
        let expected = datetime!(2023-12-25 15:30:45.123 UTC);
        assert_eq!(decoded, expected);

        // Test with timezone offset
        let value = Value::Text {
            value: "2023-12-25T15:30:45.123+05:30".to_string().into(),
            type_info: Some(SqliteDataType::Text),
        };
        let decoded: OffsetDateTime = Decode::decode(&value).unwrap();
        let expected = datetime!(2023-12-25 15:30:45.123 +05:30);
        assert_eq!(decoded, expected);

        // Test space-separated format
        let value = Value::Text {
            value: "2023-12-25 15:30:45.123".to_string().into(),
            type_info: Some(SqliteDataType::Text),
        };
        let decoded: OffsetDateTime = Decode::decode(&value).unwrap();
        let expected = datetime!(2023-12-25 15:30:45.123 UTC);
        assert_eq!(decoded, expected);
    }

    #[test]
    fn test_offset_datetime_decode_edge_cases() {
        // Test format with space and offset (this might reveal the bug)
        let value = Value::Text {
            value: "2023-12-25 15:30:45+05:30".to_string().into(),
            type_info: Some(SqliteDataType::Text),
        };
        let result: Result<OffsetDateTime, _> = Decode::decode(&value);
        // This should work but might fail due to the bug
        match result {
            Ok(dt) => {
                let expected = datetime!(2023-12-25 15:30:45 +05:30);
                assert_eq!(dt, expected);
            }
            Err(e) => {
                println!("Failed to parse '2023-12-25 15:30:45+05:30': {e}");
                // This reveals the bug
            }
        }
    }

    #[test]
    fn test_offset_datetime_format_bug_fixed() {
        // Test that the bug fix works correctly

        // This should now FAIL to parse (which is correct)
        let value = Value::Text {
            value: "2023-12-2515:30:45+05:30".to_string().into(), // No separator between date and time
            type_info: Some(SqliteDataType::Text),
        };
        let result: Result<OffsetDateTime, _> = Decode::decode(&value);

        match result {
            Ok(_) => panic!("Bug still exists: invalid format was parsed"),
            Err(_) => println!("✓ Bug fixed: invalid format correctly rejected"),
        }

        // These should still work correctly
        let valid_formats = vec![
            "2023-12-25 15:30:45+05:30", // Space separator
            "2023-12-25T15:30:45+05:30", // T separator
        ];

        for format_str in valid_formats {
            let value = Value::Text {
                value: format_str.to_string().into(),
                type_info: Some(SqliteDataType::Text),
            };
            let result: Result<OffsetDateTime, _> = Decode::decode(&value);

            match result {
                Ok(_) => println!("✓ Valid format correctly parsed: {format_str}"),
                Err(e) => panic!("Valid format failed to parse {format_str}: {e}"),
            }
        }
    }

    #[test]
    fn test_specific_rfc3339_failure() {
        // Test the exact failing format from the error message
        let problematic_format = "2025-07-22T06:20:47.847729Z";

        let value = Value::Text {
            value: problematic_format.to_string().into(),
            type_info: Some(SqliteDataType::Datetime),
        };
        let result: Result<OffsetDateTime, _> = Decode::decode(&value);

        match result {
            Ok(dt) => {
                // Verify it parsed correctly
                assert_eq!(dt.year(), 2025);
                assert_eq!(dt.month() as u8, 7);
                assert_eq!(dt.day(), 22);
                assert_eq!(dt.hour(), 6);
                assert_eq!(dt.minute(), 20);
                assert_eq!(dt.second(), 47);
                assert_eq!(dt.offset(), time::UtcOffset::UTC);
            }
            Err(e) => {
                panic!("Failed to parse valid RFC3339 format '{problematic_format}': {e}");
            }
        }

        // Test similar formats that might also fail
        let similar_formats = vec![
            "2025-07-22T06:20:47Z",        // No microseconds
            "2025-07-22T06:20:47.123456Z", // 6 digit microseconds
            "2025-07-22T06:20:47.1Z",      // Single digit subseconds
            "2025-07-22T06:20:47.123Z",    // 3 digit subseconds
        ];

        for format_str in similar_formats {
            let value = Value::Text {
                value: format_str.to_string().into(),
                type_info: Some(SqliteDataType::Datetime),
            };
            let result: Result<OffsetDateTime, _> = Decode::decode(&value);

            match result {
                Ok(_) => {} // Success is expected
                Err(e) => panic!("Failed to parse valid format '{format_str}': {e}"),
            }
        }
    }

    #[test]
    fn test_primitive_datetime_encode_decode() {
        let dt = datetime!(2023-12-25 15:30:45.123456789);
        let encoded = dt.encode().unwrap();
        let decoded: PrimitiveDateTime = Decode::decode(&encoded).unwrap();
        assert_eq!(dt, decoded);
    }

    #[test]
    fn test_primitive_datetime_decode_from_unix_timestamp() {
        let timestamp = 1703516445i64;
        let value = Value::Integer {
            value: timestamp,
            type_info: Some(SqliteDataType::Int64),
        };
        let decoded: PrimitiveDateTime = Decode::decode(&value).unwrap();
        let expected_dt = OffsetDateTime::from_unix_timestamp(timestamp).unwrap();
        let expected = PrimitiveDateTime::new(expected_dt.date(), expected_dt.time());
        assert_eq!(decoded, expected);
    }

    #[test]
    fn test_date_encode_decode() {
        let d = date!(2023 - 12 - 25);
        let encoded = d.encode().unwrap();
        let decoded: Date = Decode::decode(&encoded).unwrap();
        assert_eq!(d, decoded);
    }

    #[test]
    fn test_time_encode_decode() {
        let t = time!(15:30:45.123456789);
        let encoded = t.encode().unwrap();
        let decoded: Time = Decode::decode(&encoded).unwrap();
        assert_eq!(t, decoded);
    }

    #[test]
    fn test_time_decode_various_formats() {
        // Test with subseconds
        let value = Value::Text {
            value: "15:30:45.123".to_string().into(),
            type_info: Some(SqliteDataType::Text),
        };
        let decoded: Time = Decode::decode(&value).unwrap();
        let expected = time!(15:30:45.123);
        assert_eq!(decoded, expected);

        // Test without subseconds
        let value = Value::Text {
            value: "15:30:45".to_string().into(),
            type_info: Some(SqliteDataType::Text),
        };
        let decoded: Time = Decode::decode(&value).unwrap();
        let expected = time!(15:30:45);
        assert_eq!(decoded, expected);

        // Test without seconds
        let value = Value::Text {
            value: "15:30".to_string().into(),
            type_info: Some(SqliteDataType::Text),
        };
        let decoded: Time = Decode::decode(&value).unwrap();
        let expected = time!(15:30);
        assert_eq!(decoded, expected);
    }
}

/// Precomputed format descriptions for time parsing.
mod formats {
    use time::format_description::{
        BorrowedFormatItem as FormatItem, BorrowedFormatItem::*, Component::*, modifier,
    };

    /// Format item for year.
    const YEAR: FormatItem<'_> = Component(CalendarYearFullExtendedRange(
        modifier::CalendarYearFullExtendedRange::default(),
    ));

    /// Format item for month.
    const MONTH: FormatItem<'_> = Component(MonthNumerical(modifier::MonthNumerical::default()));

    /// Format item for day.
    const DAY: FormatItem<'_> = Component(Day({
        let mut value = modifier::Day::default();
        value.padding = modifier::Padding::Zero;
        value
    }));

    /// Format item for hour.
    const HOUR: FormatItem<'_> = Component(Hour24(modifier::Hour24::default()));

    /// Format item for minute.
    const MINUTE: FormatItem<'_> = Component(Minute({
        let mut value = modifier::Minute::default();
        value.padding = modifier::Padding::Zero;
        value
    }));

    /// Format item for second.
    const SECOND: FormatItem<'_> = Component(Second({
        let mut value = modifier::Second::default();
        value.padding = modifier::Padding::Zero;
        value
    }));

    /// Format item for subsecond.
    const SUBSECOND: FormatItem<'_> = Component(Subsecond({
        let mut value = modifier::Subsecond::default();
        value.digits = modifier::SubsecondDigits::OneOrMore;
        value
    }));

    /// Format item for offset hour.
    const OFFSET_HOUR: FormatItem<'_> = Component(OffsetHour({
        let mut value = modifier::OffsetHour::default();
        value.sign_is_mandatory = true;
        value.padding = modifier::Padding::Zero;
        value
    }));

    /// Format item for offset minute.
    const OFFSET_MINUTE: FormatItem<'_> = Component(OffsetMinute({
        let mut value = modifier::OffsetMinute::default();
        value.padding = modifier::Padding::Zero;
        value
    }));

    /// Formats for parsing offset datetime strings.
    pub(super) const OFFSET_DATE_TIME: &[FormatItem<'_>] = {
        &[
            YEAR,
            StringLiteral("-"),
            MONTH,
            StringLiteral("-"),
            DAY,
            First(&[StringLiteral(" "), StringLiteral("T")]),
            HOUR,
            StringLiteral(":"),
            MINUTE,
            Optional(&StringLiteral(":")),
            Optional(&SECOND),
            Optional(&StringLiteral(".")),
            Optional(&SUBSECOND),
            Optional(&OFFSET_HOUR),
            Optional(&StringLiteral(":")),
            Optional(&OFFSET_MINUTE),
        ]
    };

    /// Formats for parsing space-separated primitive datetimes.
    pub(super) const PRIMITIVE_DATE_TIME_SPACE_SEPARATED: &[FormatItem<'_>] = {
        &[
            YEAR,
            StringLiteral("-"),
            MONTH,
            StringLiteral("-"),
            DAY,
            StringLiteral(" "),
            HOUR,
            StringLiteral(":"),
            MINUTE,
            Optional(&StringLiteral(":")),
            Optional(&SECOND),
            Optional(&StringLiteral(".")),
            Optional(&SUBSECOND),
            Optional(&StringLiteral("Z")),
        ]
    };

    /// Formats for parsing T-separated primitive datetimes.
    pub(super) const PRIMITIVE_DATE_TIME_T_SEPARATED: &[FormatItem<'_>] = {
        &[
            YEAR,
            StringLiteral("-"),
            MONTH,
            StringLiteral("-"),
            DAY,
            StringLiteral("T"),
            HOUR,
            StringLiteral(":"),
            MINUTE,
            Optional(&StringLiteral(":")),
            Optional(&SECOND),
            Optional(&StringLiteral(".")),
            Optional(&SUBSECOND),
            Optional(&StringLiteral("Z")),
        ]
    };
}