1#![allow(
11 clippy::unnecessary_literal_bound,
12 clippy::too_many_lines,
13 clippy::cast_possible_truncation,
14 clippy::cast_possible_wrap,
15 clippy::cast_sign_loss,
16 clippy::cast_precision_loss,
17 clippy::items_after_statements,
18 clippy::match_same_arms,
19 clippy::float_cmp,
20 clippy::suboptimal_flops,
21 clippy::manual_let_else,
22 clippy::single_match_else,
23 clippy::unnecessary_wraps,
24 clippy::cognitive_complexity,
25 clippy::similar_names,
26 clippy::many_single_char_names,
27 clippy::unreadable_literal,
28 clippy::manual_range_contains,
29 clippy::range_plus_one,
30 clippy::format_push_string,
31 clippy::redundant_else
32)]
33
34use std::{
35 borrow::Cow,
36 fmt::{Arguments, Write as _},
37};
38
39use fsqlite_error::Result;
40use fsqlite_types::SqliteValue;
41
42use crate::{FunctionRegistry, ScalarFunction};
43
44#[cfg(not(target_arch = "wasm32"))]
57fn utc_offset_for_local_datetime(y: i32, mo: u32, d: u32, h: u32, mi: u32, s: u32) -> i64 {
58 use chrono::{Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone};
59 let date = NaiveDate::from_ymd_opt(y, mo, d).unwrap_or_default();
60 let time = NaiveTime::from_hms_opt(h, mi, s).unwrap_or_default();
61 let naive = NaiveDateTime::new(date, time);
62 match Local.from_local_datetime(&naive).earliest() {
63 Some(dt) => dt.offset().local_minus_utc() as i64,
64 None => 0, }
66}
67
68#[cfg(target_arch = "wasm32")]
69fn utc_offset_for_local_datetime(_y: i32, _mo: u32, _d: u32, _h: u32, _mi: u32, _s: u32) -> i64 {
70 0
71}
72
73#[cfg(not(target_arch = "wasm32"))]
80fn utc_offset_for_utc_datetime(y: i32, mo: u32, d: u32, h: u32, mi: u32, s: u32) -> i64 {
81 use chrono::{Local, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};
82 let date = NaiveDate::from_ymd_opt(y, mo, d).unwrap_or_default();
83 let time = NaiveTime::from_hms_opt(h, mi, s).unwrap_or_default();
84 let naive = NaiveDateTime::new(date, time);
85 let utc_dt = Utc.from_utc_datetime(&naive);
86 let local_dt = utc_dt.with_timezone(&Local);
87 local_dt.offset().local_minus_utc() as i64
88}
89
90#[cfg(target_arch = "wasm32")]
91fn utc_offset_for_utc_datetime(_y: i32, _mo: u32, _d: u32, _h: u32, _mi: u32, _s: u32) -> i64 {
92 0
93}
94
95fn utc_offset_for_utc_jdn(jdn: f64) -> i64 {
97 let (y, mo, d) = jdn_to_ymd(jdn);
98 let (h, mi, s, _frac) = jdn_to_hms(jdn);
99 utc_offset_for_utc_datetime(y as i32, mo as u32, d as u32, h as u32, mi as u32, s as u32)
100}
101
102fn utc_offset_for_local_jdn(jdn: f64) -> i64 {
104 let (y, mo, d) = jdn_to_ymd(jdn);
105 let (h, mi, s, _frac) = jdn_to_hms(jdn);
106 utc_offset_for_local_datetime(y as i32, mo as u32, d as u32, h as u32, mi as u32, s as u32)
107}
108
109fn ymd_to_jdn(y: i64, m: i64, d: i64) -> f64 {
115 let (y, m) = if m <= 2 {
116 (y.saturating_sub(1), m.saturating_add(12))
117 } else {
118 (y, m)
119 };
120 let a = y / 100;
121 let b = 2_i64.saturating_sub(a).saturating_add(a / 4);
122 (365.25 * y.saturating_add(4716) as f64).floor()
123 + (30.6001 * m.saturating_add(1) as f64).floor()
124 + d as f64
125 + b as f64
126 - 1524.5
127}
128
129fn jdn_to_ymd(jdn: f64) -> (i64, i64, i64) {
136 let z = (jdn + 0.5).floor() as i64;
142 let alpha = ((z as f64 - 1_867_216.25) / 36524.25) as i64;
143 let a = z
144 .saturating_add(1)
145 .saturating_add(alpha)
146 .saturating_sub(alpha / 4);
147 let b = a.saturating_add(1524);
148 let c = ((b as f64 - 122.1) / 365.25) as i64;
149 let d = (365.25 * c as f64) as i64;
150 let e = ((b.saturating_sub(d)) as f64 / 30.6001) as i64;
151
152 let day = b
153 .saturating_sub(d)
154 .saturating_sub((30.6001 * e as f64) as i64);
155 let month = if e < 14 {
156 e.saturating_sub(1)
157 } else {
158 e.saturating_sub(13)
159 };
160 let year = if month > 2 {
161 c.saturating_sub(4716)
162 } else {
163 c.saturating_sub(4715)
164 };
165 (year, month, day)
166}
167
168fn jdn_to_hms(jdn: f64) -> (i64, i64, i64, f64) {
170 let frac = jdn + 0.5 - (jdn + 0.5).floor();
171 let total_ms = (frac * 86_400_000.0).round() as i64;
173 let h = total_ms / 3_600_000;
174 let rem = total_ms % 3_600_000;
175 let m = rem / 60_000;
176 let rem = rem % 60_000;
177 let s = rem / 1000;
178 let ms_frac = (rem % 1000) as f64 / 1000.0;
179 (h, m, s, ms_frac)
180}
181
182fn ymdhms_to_jdn(y: i64, mo: i64, d: i64, h: i64, mi: i64, s: i64, frac: f64) -> f64 {
184 ymd_to_jdn(y, mo, d) + (h as f64 * 3600.0 + mi as f64 * 60.0 + s as f64 + frac) / 86400.0
185}
186
187const UNIX_EPOCH_JDN: f64 = 2_440_587.5;
189const AUTO_JDN_MAX: f64 = 5_373_484.499_999;
191const AUTO_UNIX_MIN: f64 = -210_866_760_000.0;
193const AUTO_UNIX_MAX: f64 = 253_402_300_799.0;
194
195fn jdn_to_unix(jdn: f64) -> i64 {
196 ((jdn - UNIX_EPOCH_JDN) * 86400.0).round() as i64
197}
198
199fn unix_to_jdn(ts: f64) -> f64 {
200 ts / 86400.0 + UNIX_EPOCH_JDN
201}
202
203fn is_leap_year(y: i64) -> bool {
204 (y % 4 == 0 && y % 100 != 0) || y % 400 == 0
205}
206
207fn days_in_month(y: i64, m: i64) -> i64 {
208 match m {
209 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
210 4 | 6 | 9 | 11 => 30,
211 2 => {
212 if is_leap_year(y) {
213 29
214 } else {
215 28
216 }
217 }
218 _ => 30,
219 }
220}
221
222fn day_of_year(y: i64, m: i64, d: i64) -> i64 {
223 let mut doy = d;
224 for mo in 1..m {
225 doy = doy.saturating_add(days_in_month(y, mo));
226 }
227 doy
228}
229
230fn parse_timestring(s: &str) -> Option<f64> {
234 let s = s.trim();
235
236 if s.eq_ignore_ascii_case("now") {
242 use std::time::{SystemTime, UNIX_EPOCH};
243 let secs = SystemTime::now()
244 .duration_since(UNIX_EPOCH)
245 .unwrap_or_default()
246 .as_secs_f64();
247 return Some(2_440_587.5 + secs / 86_400.0);
249 }
250
251 if let Ok(jdn) = s.parse::<f64>() {
254 if jdn >= 0.0 && jdn.is_finite() {
255 return Some(jdn);
256 }
257 }
258
259 parse_iso8601(s)
261}
262
263fn parse_iso8601(s: &str) -> Option<f64> {
264 let bytes = s.as_bytes();
272 let len = bytes.len();
273
274 if len >= 10 && bytes[4] == b'-' && bytes[7] == b'-' {
276 let y = s[0..4].parse::<i64>().ok()?;
277 let m = s[5..7].parse::<i64>().ok()?;
278 let d = s[8..10].parse::<i64>().ok()?;
279
280 if m < 1 || m > 12 || d < 1 || d > 31 {
281 return None;
282 }
283
284 if len == 10 {
285 return Some(ymd_to_jdn(y, m, d));
286 }
287
288 if len > 10 && (bytes[10] == b' ' || bytes[10] == b'T') {
290 let time_part = &s[11..];
291 let (h, mi, sec, frac, tz_offset_min) = parse_time_part_with_tz(time_part)?;
292 let jdn = ymdhms_to_jdn(y, m, d, h, mi, sec, frac);
293 return Some(jdn - (tz_offset_min as f64) / 1440.0);
296 }
297 return None;
298 }
299
300 if len >= 5 && bytes[2] == b':' {
302 let (h, mi, sec, frac, tz_offset_min) = parse_time_part_with_tz(s)?;
303 let jdn = ymdhms_to_jdn(2000, 1, 1, h, mi, sec, frac);
304 return Some(jdn - (tz_offset_min as f64) / 1440.0);
305 }
306
307 None
308}
309
310fn split_tz_suffix(s: &str) -> Option<(&str, i64)> {
318 if let Some(stripped) = s.strip_suffix('Z').or_else(|| s.strip_suffix('z')) {
320 return Some((stripped, 0));
321 }
322
323 let bytes = s.as_bytes();
332 for width in [6usize, 5, 3] {
334 if bytes.len() < width + 1 {
335 continue;
336 }
337 let split_at = bytes.len() - width;
338 let sign_byte = bytes[split_at];
339 if sign_byte != b'+' && sign_byte != b'-' {
340 continue;
341 }
342 let tz_part = &s[split_at..];
343 if let Some(offset) = parse_tz_offset(tz_part) {
344 return Some((&s[..split_at], offset));
345 }
346 }
347
348 Some((s, 0))
350}
351
352fn parse_tz_offset(tz: &str) -> Option<i64> {
355 let bytes = tz.as_bytes();
356 if bytes.is_empty() {
357 return None;
358 }
359 let sign: i64 = match bytes[0] {
360 b'+' => 1,
361 b'-' => -1,
362 _ => return None,
363 };
364 let rest = &tz[1..];
365 let (hours, minutes) = match rest.len() {
366 5 if rest.as_bytes()[2] == b':' => (
368 rest[0..2].parse::<i64>().ok()?,
369 rest[3..5].parse::<i64>().ok()?,
370 ),
371 4 => (
373 rest[0..2].parse::<i64>().ok()?,
374 rest[2..4].parse::<i64>().ok()?,
375 ),
376 2 => (rest.parse::<i64>().ok()?, 0),
378 _ => return None,
379 };
380 if !(0..=23).contains(&hours) || !(0..=59).contains(&minutes) {
381 return None;
382 }
383 Some(sign * (hours * 60 + minutes))
384}
385
386fn parse_time_part_with_tz(s: &str) -> Option<(i64, i64, i64, f64, i64)> {
389 let (time_only, tz_offset_min) = split_tz_suffix(s)?;
390 let (h, mi, sec, frac) = parse_time_part(time_only)?;
391 Some((h, mi, sec, frac, tz_offset_min))
392}
393
394fn parse_time_part(s: &str) -> Option<(i64, i64, i64, f64)> {
396 let [h_tens, h_ones, b':', mi_tens, mi_ones, rest @ ..] = s.as_bytes() else {
397 return None;
398 };
399 let h = parse_two_ascii_digits(*h_tens, *h_ones)?;
404 let mi = parse_two_ascii_digits(*mi_tens, *mi_ones)?;
405 if !(0..=23).contains(&h) || !(0..=59).contains(&mi) {
406 return None;
407 }
408
409 match rest {
414 [] => Some((h, mi, 0, 0.0)),
415 [b':', sec_tens, sec_ones] => {
416 let sec = parse_two_ascii_digits(*sec_tens, *sec_ones)?;
417 if !(0..=59).contains(&sec) {
418 return None;
419 }
420 Some((h, mi, sec, 0.0))
421 }
422 [b':', sec_tens, sec_ones, b'.', ..] => {
423 let sec = parse_two_ascii_digits(*sec_tens, *sec_ones)?;
424 if !(0..=59).contains(&sec) {
425 return None;
426 }
427 let frac = s.get(8..)?.parse::<f64>().ok()?;
428 Some((h, mi, sec, frac))
429 }
430 _ => None,
431 }
432}
433
434#[inline]
435fn parse_two_ascii_digits(tens: u8, ones: u8) -> Option<i64> {
436 if tens.is_ascii_digit() && ones.is_ascii_digit() {
437 Some(i64::from((tens - b'0') * 10 + (ones - b'0')))
438 } else {
439 None
440 }
441}
442
443fn apply_modifier(jdn: f64, modifier: &str) -> Option<f64> {
447 let m = modifier.trim().to_ascii_lowercase();
448
449 if m == "start of month" {
451 let (y, mo, _d) = jdn_to_ymd(jdn);
452 return Some(ymd_to_jdn(y, mo, 1));
453 }
454 if m == "start of year" {
455 let (y, _mo, _d) = jdn_to_ymd(jdn);
456 return Some(ymd_to_jdn(y, 1, 1));
457 }
458 if m == "start of day" {
459 let (y, mo, d) = jdn_to_ymd(jdn);
460 return Some(ymd_to_jdn(y, mo, d));
461 }
462
463 if m == "unixepoch" {
465 return Some(unix_to_jdn(jdn));
466 }
467
468 if m == "julianday" {
471 return Some(jdn);
472 }
473
474 if m == "auto" {
479 if (0.0..=AUTO_JDN_MAX).contains(&jdn) {
480 return Some(jdn);
481 }
482 if (AUTO_UNIX_MIN..=AUTO_UNIX_MAX).contains(&jdn) {
483 return Some(unix_to_jdn(jdn));
484 }
485 return None;
486 }
487
488 if m == "localtime" {
491 let offset = utc_offset_for_utc_jdn(jdn);
492 return Some(jdn + offset as f64 / 86400.0);
493 }
494 if m == "utc" {
497 let offset = utc_offset_for_local_jdn(jdn);
498 return Some(jdn - offset as f64 / 86400.0);
499 }
500
501 if m == "subsec" || m == "subsecond" {
504 return Some(jdn);
505 }
506
507 if let Some(rest) = m.strip_prefix("weekday ") {
509 let wd = rest.trim().parse::<i64>().ok()?;
510 if !(0..=6).contains(&wd) {
511 return None;
512 }
513 let current_jdn_int = (jdn + 0.5).floor() as i64;
515 let current_wd = (current_jdn_int + 1) % 7; let mut diff = wd - current_wd;
517 if diff < 0 {
518 diff += 7;
519 }
520 return Some(jdn + diff as f64);
522 }
523
524 parse_arithmetic_modifier(&m).map(|delta| jdn + delta)
526}
527
528fn parse_arithmetic_modifier(m: &str) -> Option<f64> {
530 let (sign, rest) = if let Some(r) = m.strip_prefix('+') {
531 (1.0, r.trim())
532 } else {
533 let r = m.strip_prefix('-')?;
534 (-1.0, r.trim())
535 };
536
537 let mut parts = rest.splitn(2, ' ');
538 let num_str = parts.next()?;
539 let unit = parts.next()?.trim();
540
541 let num = num_str.parse::<f64>().ok().filter(|f| f.is_finite())?;
543 let delta = num * sign;
544
545 match unit.trim_end_matches('s') {
546 "day" => Some(delta),
547 "hour" => Some(delta / 24.0),
548 "minute" => Some(delta / 1440.0),
549 "second" => Some(delta / 86400.0),
550 "month" => Some(apply_month_delta(delta)),
551 "year" => Some(apply_month_delta(delta * 12.0)),
552 _ => None,
553 }
554}
555
556fn apply_month_delta(months: f64) -> f64 {
561 months * 30.436875
563}
564
565fn compute_floor(y: i64, m: i64, d: i64) -> i64 {
569 if d <= 28 {
570 0
571 } else if ((1_i64 << m) & 0x15aa) != 0 {
572 0
574 } else if m != 2 {
575 i64::from(d == 31)
577 } else if y % 4 != 0 || (y % 100 == 0 && y % 400 != 0) {
578 d - 28 } else {
580 d - 29 }
582}
583
584fn apply_modifiers(jdn: f64, modifiers: &[String]) -> Option<(f64, bool)> {
586 let mut j = jdn;
587 let mut subsec = false;
588 let mut n_floor: i64 = 0;
591 for m in modifiers {
592 let m_lower = m.trim().to_ascii_lowercase();
593 if m_lower == "subsec" || m_lower == "subsecond" {
594 subsec = true;
595 continue;
596 }
597 if m_lower == "ceiling" {
602 n_floor = 0;
603 continue;
604 }
605 if m_lower == "floor" {
606 j -= n_floor as f64;
607 n_floor = 0;
608 continue;
609 }
610 if is_month_year_modifier(&m_lower) {
616 match apply_month_year_exact(j, &m_lower) {
617 Ok(Some((new_jdn, nf))) => {
618 j = new_jdn;
619 n_floor = nf;
620 continue;
621 }
622 Ok(None) => return None,
623 Err(()) => {
624 }
626 }
627 }
628 n_floor = 0;
630 j = apply_modifier(j, m)?;
631 }
632 Some((j, subsec))
633}
634
635fn is_month_year_modifier(m: &str) -> bool {
636 (m.contains("month") || m.contains("year")) && (m.starts_with('+') || m.starts_with('-'))
637}
638
639fn apply_month_year_exact(jdn: f64, m: &str) -> std::result::Result<Option<(f64, i64)>, ()> {
645 let (sign, rest) = if let Some(r) = m.strip_prefix('+') {
646 (1_i64, r.trim())
647 } else if let Some(r) = m.strip_prefix('-') {
648 (-1_i64, r.trim())
649 } else {
650 return Err(());
651 };
652
653 let mut parts = rest.splitn(2, ' ');
654 let num_str = parts.next().ok_or(())?;
655 let unit = parts.next().ok_or(())?.trim();
656
657 let num = if let Ok(n) = num_str.parse::<i64>() {
659 n
660 } else if let Ok(f) = num_str.parse::<f64>() {
661 if f.fract() == 0.0 && f >= i64::MIN as f64 && f <= i64::MAX as f64 {
662 f as i64
663 } else {
664 return Err(());
665 }
666 } else {
667 return Err(());
668 };
669
670 let (y, mo, d) = jdn_to_ymd(jdn);
671 let (h, mi, s, frac) = jdn_to_hms(jdn);
672
673 let total_months = match unit.trim_end_matches('s') {
674 "month" => {
675 if let Some(val) = num.checked_mul(sign) {
676 val
677 } else {
678 return Ok(None);
679 }
680 }
681 "year" => {
682 if let Some(val) = num.checked_mul(sign).and_then(|v| v.checked_mul(12)) {
683 val
684 } else {
685 return Ok(None);
686 }
687 }
688 _ => return Err(()),
689 };
690
691 let current_months = if let Some(val) = y.checked_mul(12).and_then(|v| v.checked_add(mo - 1)) {
693 val
694 } else {
695 return Ok(None);
696 };
697 let new_total = if let Some(val) = current_months.checked_add(total_months) {
698 val
699 } else {
700 return Ok(None);
701 };
702
703 let new_y = new_total.div_euclid(12);
704 let new_mo = new_total.rem_euclid(12) + 1;
705 let n_floor = compute_floor(new_y, new_mo, d);
710 Ok(Some((
711 ymdhms_to_jdn(new_y, new_mo, d, h, mi, s, frac),
712 n_floor,
713 )))
714}
715
716fn format_date(jdn: f64) -> String {
719 let (y, m, d) = jdn_to_ymd(jdn);
720 format!("{y:04}-{m:02}-{d:02}")
721}
722
723fn format_time(jdn: f64, subsec: bool) -> String {
724 let (h, m, s, frac) = jdn_to_hms(jdn);
725 if subsec && frac > 1e-9 {
726 format!("{h:02}:{m:02}:{s:02}.{:03}", (frac * 1000.0).round() as i64)
727 } else {
728 format!("{h:02}:{m:02}:{s:02}")
729 }
730}
731
732fn format_datetime(jdn: f64, subsec: bool) -> String {
733 format!("{} {}", format_date(jdn), format_time(jdn, subsec))
734}
735
736#[inline]
737fn push_format(result: &mut String, args: Arguments<'_>) {
738 let _ = result.write_fmt(args);
739}
740
741#[inline]
742fn push_zero_padded_2(result: &mut String, value: i64) {
743 if (0..=99).contains(&value) {
744 let value = value as u8;
745 result.push(char::from(b'0' + value / 10));
746 result.push(char::from(b'0' + value % 10));
747 } else {
748 push_format(result, format_args!("{value:02}"));
749 }
750}
751
752#[inline]
753fn push_space_padded_2(result: &mut String, value: i64) {
754 if (0..=99).contains(&value) {
755 let value = value as u8;
756 if value >= 10 {
757 result.push(char::from(b'0' + value / 10));
758 } else {
759 result.push(' ');
760 }
761 result.push(char::from(b'0' + value % 10));
762 } else {
763 push_format(result, format_args!("{value:>2}"));
764 }
765}
766
767#[inline]
768fn push_zero_padded_3(result: &mut String, value: i64) {
769 if (0..=999).contains(&value) {
770 let value = value as u16;
771 result.push(char::from(b'0' + (value / 100) as u8));
772 result.push(char::from(b'0' + ((value / 10) % 10) as u8));
773 result.push(char::from(b'0' + (value % 10) as u8));
774 } else {
775 push_format(result, format_args!("{value:03}"));
776 }
777}
778
779#[inline]
780fn push_zero_padded_4(result: &mut String, value: i64) {
781 if (0..=9999).contains(&value) {
782 let value = value as u16;
783 result.push(char::from(b'0' + (value / 1000) as u8));
784 result.push(char::from(b'0' + ((value / 100) % 10) as u8));
785 result.push(char::from(b'0' + ((value / 10) % 10) as u8));
786 result.push(char::from(b'0' + (value % 10) as u8));
787 } else {
788 push_format(result, format_args!("{value:04}"));
789 }
790}
791
792fn format_strftime(fmt: &str, jdn: f64) -> String {
794 let (y, mo, d) = jdn_to_ymd(jdn);
795 let (h, mi, s, frac) = jdn_to_hms(jdn);
796 let doy = day_of_year(y, mo, d);
797 let jdn_int = (jdn + 0.5).floor() as i64;
799 let dow = (jdn_int + 1) % 7; let mut result = String::with_capacity(fmt.len().saturating_add(8));
802 let bytes = fmt.as_bytes();
803 let mut i = 0;
804 let mut literal_start = 0;
805
806 while i < bytes.len() {
807 if bytes[i] != b'%' || i + 1 >= bytes.len() {
808 i += 1;
809 continue;
810 }
811
812 result.push_str(&fmt[literal_start..i]);
813
814 let spec_suffix = &fmt[i + 1..];
815 let Some(spec) = spec_suffix.chars().next() else {
816 break;
817 };
818 i += 1 + spec.len_utf8();
819 literal_start = i;
820
821 match spec {
822 'd' => push_zero_padded_2(&mut result, d),
823 'e' => push_space_padded_2(&mut result, d),
824 'F' => {
825 push_zero_padded_4(&mut result, y);
827 result.push('-');
828 push_zero_padded_2(&mut result, mo);
829 result.push('-');
830 push_zero_padded_2(&mut result, d);
831 }
832 'f' => {
833 let total = s as f64 + frac;
835 push_format(&mut result, format_args!("{total:06.3}"));
836 }
837 'H' => push_zero_padded_2(&mut result, h),
838 'I' => {
839 let h12 = if h == 0 {
841 12
842 } else if h > 12 {
843 h - 12
844 } else {
845 h
846 };
847 push_zero_padded_2(&mut result, h12);
848 }
849 'j' => push_zero_padded_3(&mut result, doy),
850 'J' => {
851 push_format(&mut result, format_args!("{jdn:.15}"));
853 while result.as_bytes().last() == Some(&b'0') {
854 result.pop();
855 }
856 if result.as_bytes().last() == Some(&b'.') {
857 result.pop();
858 }
859 }
860 'k' => {
861 push_space_padded_2(&mut result, h);
863 }
864 'l' => {
865 let h12 = if h == 0 {
867 12
868 } else if h > 12 {
869 h - 12
870 } else {
871 h
872 };
873 push_space_padded_2(&mut result, h12);
874 }
875 'm' => push_zero_padded_2(&mut result, mo),
876 'M' => push_zero_padded_2(&mut result, mi),
877 'p' => {
878 result.push_str(if h < 12 { "AM" } else { "PM" });
879 }
880 'P' => {
881 result.push_str(if h < 12 { "am" } else { "pm" });
882 }
883 'R' => {
884 push_zero_padded_2(&mut result, h);
885 result.push(':');
886 push_zero_padded_2(&mut result, mi);
887 }
888 's' => {
889 let unix = jdn_to_unix(jdn);
890 push_format(&mut result, format_args!("{unix}"));
891 }
892 'S' => push_zero_padded_2(&mut result, s),
893 'T' => {
894 push_zero_padded_2(&mut result, h);
895 result.push(':');
896 push_zero_padded_2(&mut result, mi);
897 result.push(':');
898 push_zero_padded_2(&mut result, s);
899 }
900 'u' => {
901 let u = if dow == 0 { 7 } else { dow };
903 push_format(&mut result, format_args!("{u}"));
904 }
905 'w' => push_format(&mut result, format_args!("{dow}")),
906 'W' => {
907 let w = (doy + 6 - ((dow + 6) % 7)) / 7;
909 push_zero_padded_2(&mut result, w);
910 }
911 'Y' => push_zero_padded_4(&mut result, y),
912 'G' | 'g' | 'V' => {
913 let (iso_y, iso_w) = iso_week(y, mo, d);
915 match spec {
916 'G' => push_zero_padded_4(&mut result, iso_y),
917 'g' => push_zero_padded_2(&mut result, iso_y % 100),
918 'V' => push_zero_padded_2(&mut result, iso_w),
919 _ => unreachable!(),
920 }
921 }
922 '%' => result.push('%'),
923 other => {
924 result.push('%');
925 result.push(other);
926 }
927 }
928 }
929
930 if literal_start < fmt.len() {
931 result.push_str(&fmt[literal_start..]);
932 }
933
934 result
935}
936
937fn iso_week(y: i64, m: i64, d: i64) -> (i64, i64) {
939 let jdn = ymd_to_jdn(y, m, d);
940 let jdn_int = (jdn + 0.5).floor() as i64;
941 let dow = (jdn_int + 1) % 7;
943 let iso_dow = if dow == 0 { 7 } else { dow };
944
945 let thu_jdn = jdn_int + (4 - iso_dow);
947 let (thu_y, _, _) = jdn_to_ymd(thu_jdn as f64);
948
949 let jan4_jdn = (ymd_to_jdn(thu_y, 1, 4) + 0.5).floor() as i64;
951 let jan4_dow = (jan4_jdn + 1) % 7;
952 let jan4_iso_dow = if jan4_dow == 0 { 7 } else { jan4_dow };
953 let week1_start = jan4_jdn - (jan4_iso_dow - 1);
954
955 let week = (thu_jdn - week1_start) / 7 + 1;
956 (thu_y, week)
957}
958
959fn timediff_impl(jdn1: f64, jdn2: f64) -> String {
962 let (sign, start_jdn, end_jdn) = if jdn1 >= jdn2 {
963 ('+', jdn2, jdn1)
964 } else {
965 ('-', jdn1, jdn2)
966 };
967
968 let (start_y, start_mo, start_d) = jdn_to_ymd(start_jdn);
969 let (start_h, start_mi, mut start_s, start_frac) = jdn_to_hms(start_jdn);
970 let mut start_ms = (start_frac * 1000.0).round() as i64;
971 if start_ms >= 1000 {
972 start_ms = 0;
973 start_s += 1;
974 }
975
976 let (end_y, end_mo, end_d) = jdn_to_ymd(end_jdn);
977 let (end_h, end_mi, mut end_s, end_frac) = jdn_to_hms(end_jdn);
978 let mut end_ms = (end_frac * 1000.0).round() as i64;
979 if end_ms >= 1000 {
980 end_ms = 0;
981 end_s += 1;
982 }
983
984 let mut years = end_y - start_y;
985 let mut months = end_mo - start_mo;
986 let mut days = end_d - start_d;
987 let mut hours = end_h - start_h;
988 let mut minutes = end_mi - start_mi;
989 let mut seconds = end_s - start_s;
990 let mut millis = end_ms - start_ms;
991
992 if millis < 0 {
993 millis += 1000;
994 seconds -= 1;
995 }
996 if seconds < 0 {
997 seconds += 60;
998 minutes -= 1;
999 }
1000 if minutes < 0 {
1001 minutes += 60;
1002 hours -= 1;
1003 }
1004 if hours < 0 {
1005 hours += 24;
1006 days -= 1;
1007 }
1008 if days < 0 {
1009 months -= 1;
1010 let (borrow_y, borrow_mo) = if end_mo == 1 {
1011 (end_y - 1, 12)
1012 } else {
1013 (end_y, end_mo - 1)
1014 };
1015 days += days_in_month(borrow_y, borrow_mo);
1016 }
1017 if months < 0 {
1018 months += 12;
1019 years -= 1;
1020 }
1021
1022 format!(
1023 "{sign}{years:04}-{months:02}-{days:02} {hours:02}:{minutes:02}:{seconds:02}.{millis:03}"
1024 )
1025}
1026
1027fn parse_args(args: &[SqliteValue]) -> Option<(f64, bool)> {
1031 if args.is_empty() || args[0].is_null() {
1032 return None;
1033 }
1034
1035 let numeric_input = matches!(&args[0], SqliteValue::Integer(_) | SqliteValue::Float(_));
1036 let input = match &args[0] {
1037 SqliteValue::Text(s) => parse_timestring(s)?,
1038 SqliteValue::Integer(i) => *i as f64,
1039 SqliteValue::Float(f) => *f,
1040 _ => return None,
1041 };
1042
1043 if args[1..].iter().any(SqliteValue::is_null) {
1046 return None;
1047 }
1048 let modifiers: Vec<String> = args[1..].iter().map(SqliteValue::to_text).collect();
1049
1050 if numeric_input {
1055 let first = modifiers
1056 .first()
1057 .map(|modifier| modifier.trim().to_ascii_lowercase());
1058 let reinterprets_raw = matches!(first.as_deref(), Some("unixepoch" | "julianday" | "auto"));
1059 if !reinterprets_raw && !(0.0..=AUTO_JDN_MAX).contains(&input) {
1060 return None;
1061 }
1062 }
1063
1064 apply_modifiers(input, &modifiers)
1065}
1066
1067pub struct DateFunc;
1070
1071impl ScalarFunction for DateFunc {
1072 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1073 match parse_args(args) {
1074 Some((jdn, _)) => Ok(SqliteValue::Text(format_date(jdn).into())),
1075 None => Ok(SqliteValue::Null),
1076 }
1077 }
1078
1079 fn num_args(&self) -> i32 {
1080 -1
1081 }
1082
1083 fn name(&self) -> &str {
1084 "date"
1085 }
1086}
1087
1088pub struct TimeFunc;
1091
1092impl ScalarFunction for TimeFunc {
1093 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1094 match parse_args(args) {
1095 Some((jdn, subsec)) => Ok(SqliteValue::Text(format_time(jdn, subsec).into())),
1096 None => Ok(SqliteValue::Null),
1097 }
1098 }
1099
1100 fn num_args(&self) -> i32 {
1101 -1
1102 }
1103
1104 fn name(&self) -> &str {
1105 "time"
1106 }
1107}
1108
1109pub struct DateTimeFunc;
1112
1113impl ScalarFunction for DateTimeFunc {
1114 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1115 match parse_args(args) {
1116 Some((jdn, subsec)) => Ok(SqliteValue::Text(format_datetime(jdn, subsec).into())),
1117 None => Ok(SqliteValue::Null),
1118 }
1119 }
1120
1121 fn num_args(&self) -> i32 {
1122 -1
1123 }
1124
1125 fn name(&self) -> &str {
1126 "datetime"
1127 }
1128}
1129
1130pub struct JuliandayFunc;
1133
1134impl ScalarFunction for JuliandayFunc {
1135 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1136 match parse_args(args) {
1137 Some((jdn, _)) => Ok(SqliteValue::Float(jdn)),
1138 None => Ok(SqliteValue::Null),
1139 }
1140 }
1141
1142 fn num_args(&self) -> i32 {
1143 -1
1144 }
1145
1146 fn name(&self) -> &str {
1147 "julianday"
1148 }
1149}
1150
1151pub struct UnixepochFunc;
1154
1155impl ScalarFunction for UnixepochFunc {
1156 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1157 match parse_args(args) {
1158 Some((jdn, true)) => {
1161 let secs = (jdn - UNIX_EPOCH_JDN) * 86400.0;
1162 let rounded = (secs * 1000.0).round() / 1000.0;
1163 Ok(SqliteValue::Float(rounded))
1164 }
1165 Some((jdn, false)) => Ok(SqliteValue::Integer(jdn_to_unix(jdn))),
1166 None => Ok(SqliteValue::Null),
1167 }
1168 }
1169
1170 fn num_args(&self) -> i32 {
1171 -1
1172 }
1173
1174 fn name(&self) -> &str {
1175 "unixepoch"
1176 }
1177}
1178
1179pub struct StrftimeFunc;
1182
1183impl ScalarFunction for StrftimeFunc {
1184 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1185 if args.len() < 2 || args[0].is_null() || args[1].is_null() {
1186 return Ok(SqliteValue::Null);
1187 }
1188 let rest = &args[1..];
1189 match parse_args(rest) {
1190 Some((jdn, _)) => {
1191 let fmt = match args[0].as_text_str() {
1192 Some(text) => Cow::Borrowed(text),
1193 None => Cow::Owned(args[0].to_text()),
1194 };
1195 Ok(SqliteValue::Text(format_strftime(fmt.as_ref(), jdn).into()))
1196 }
1197 None => Ok(SqliteValue::Null),
1198 }
1199 }
1200
1201 fn num_args(&self) -> i32 {
1202 -1
1203 }
1204
1205 fn name(&self) -> &str {
1206 "strftime"
1207 }
1208}
1209
1210pub struct TimediffFunc;
1213
1214impl ScalarFunction for TimediffFunc {
1215 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1216 if args.len() < 2 || args[0].is_null() || args[1].is_null() {
1217 return Ok(SqliteValue::Null);
1218 }
1219
1220 let jdn1 = match &args[0] {
1221 SqliteValue::Text(s) => parse_timestring(s),
1222 SqliteValue::Integer(i) => Some(*i as f64),
1223 SqliteValue::Float(f) => Some(*f),
1224 _ => None,
1225 };
1226 let jdn2 = match &args[1] {
1227 SqliteValue::Text(s) => parse_timestring(s),
1228 SqliteValue::Integer(i) => Some(*i as f64),
1229 SqliteValue::Float(f) => Some(*f),
1230 _ => None,
1231 };
1232
1233 match (jdn1, jdn2) {
1234 (Some(j1), Some(j2)) => Ok(SqliteValue::Text(timediff_impl(j1, j2).into())),
1235 _ => Ok(SqliteValue::Null),
1236 }
1237 }
1238
1239 fn num_args(&self) -> i32 {
1240 2
1241 }
1242
1243 fn name(&self) -> &str {
1244 "timediff"
1245 }
1246}
1247
1248pub fn register_datetime_builtins(registry: &mut FunctionRegistry) {
1252 registry.register_scalar(DateFunc);
1253 registry.register_scalar(TimeFunc);
1254 registry.register_scalar(DateTimeFunc);
1255 registry.register_scalar(JuliandayFunc);
1256 registry.register_scalar(UnixepochFunc);
1257 registry.register_scalar(StrftimeFunc);
1258 registry.register_scalar(TimediffFunc);
1259}
1260
1261#[cfg(test)]
1264mod tests {
1265 use super::*;
1266
1267 fn text(s: &str) -> SqliteValue {
1268 SqliteValue::Text(s.into())
1269 }
1270
1271 fn int(v: i64) -> SqliteValue {
1272 SqliteValue::Integer(v)
1273 }
1274
1275 fn float(v: f64) -> SqliteValue {
1276 SqliteValue::Float(v)
1277 }
1278
1279 fn null() -> SqliteValue {
1280 SqliteValue::Null
1281 }
1282
1283 fn assert_text(result: &SqliteValue, expected: &str) {
1284 match result {
1285 SqliteValue::Text(s) => assert_eq!(s.as_ref(), expected, "text mismatch"),
1286 other => panic!("expected Text(\"{expected}\"), got {other:?}"),
1287 }
1288 }
1289
1290 #[test]
1293 fn test_date_basic() {
1294 let r = DateFunc.invoke(&[text("2024-03-15 14:30:00")]).unwrap();
1295 assert_text(&r, "2024-03-15");
1296 }
1297
1298 #[test]
1299 fn test_time_basic() {
1300 let r = TimeFunc.invoke(&[text("2024-03-15 14:30:45")]).unwrap();
1301 assert_text(&r, "14:30:45");
1302 }
1303
1304 #[test]
1305 fn test_datetime_basic() {
1306 let r = DateTimeFunc.invoke(&[text("2024-03-15 14:30:00")]).unwrap();
1307 assert_text(&r, "2024-03-15 14:30:00");
1308 }
1309
1310 #[test]
1311 fn test_julianday_basic() {
1312 let r = JuliandayFunc.invoke(&[text("2024-03-15")]).unwrap();
1313 match r {
1314 SqliteValue::Float(jdn) => {
1315 assert!((jdn - 2_460_384.5).abs() < 0.01, "unexpected JDN: {jdn}");
1317 }
1318 other => panic!("expected Float, got {other:?}"),
1319 }
1320 }
1321
1322 fn julianday_float(input: &str) -> f64 {
1330 match JuliandayFunc.invoke(&[text(input)]).unwrap() {
1331 SqliteValue::Float(v) => v,
1332 other => panic!("expected Float, got {other:?} for input {input:?}"),
1333 }
1334 }
1335
1336 fn assert_jdn_close(actual: f64, expected: f64, ctx: &str) {
1337 assert!(
1339 (actual - expected).abs() < 1e-6,
1340 "JDN mismatch for {ctx}: got {actual}, expected {expected}"
1341 );
1342 }
1343
1344 #[test]
1345 fn test_julianday_rfc3339_z_suffix() {
1346 let naive = julianday_float("2026-04-07 16:00:00");
1348 assert_jdn_close(julianday_float("2026-04-07T16:00:00Z"), naive, "T...Z");
1349 assert_jdn_close(
1350 julianday_float("2026-04-07T16:00:00z"),
1351 naive,
1352 "lowercase z",
1353 );
1354 }
1355
1356 #[test]
1357 fn test_julianday_rfc3339_zero_offset() {
1358 let naive = julianday_float("2026-04-07 16:00:00");
1359 assert_jdn_close(
1360 julianday_float("2026-04-07T16:00:00+00:00"),
1361 naive,
1362 "+00:00",
1363 );
1364 assert_jdn_close(
1365 julianday_float("2026-04-07T16:00:00-00:00"),
1366 naive,
1367 "-00:00",
1368 );
1369 }
1370
1371 #[test]
1372 fn test_julianday_rfc3339_positive_offset() {
1373 let base = julianday_float("2026-04-07 16:00:00");
1375 let expected = base - 1.0 / 24.0;
1376 assert_jdn_close(
1377 julianday_float("2026-04-07T16:00:00+01:00"),
1378 expected,
1379 "+01:00",
1380 );
1381 }
1382
1383 #[test]
1384 fn test_julianday_rfc3339_negative_offset() {
1385 let base = julianday_float("2026-04-07 16:00:00");
1387 let expected = base + 5.0 / 24.0;
1388 assert_jdn_close(
1389 julianday_float("2026-04-07T16:00:00-05:00"),
1390 expected,
1391 "-05:00",
1392 );
1393 }
1394
1395 #[test]
1396 fn test_julianday_rfc3339_half_hour_offset() {
1397 let base = julianday_float("2026-04-07 16:00:00");
1399 let expected = base - 5.5 / 24.0;
1400 assert_jdn_close(
1401 julianday_float("2026-04-07T16:00:00+05:30"),
1402 expected,
1403 "+05:30",
1404 );
1405 }
1406
1407 #[test]
1408 fn test_julianday_rfc3339_compact_offsets() {
1409 let base = julianday_float("2026-04-07 16:00:00");
1411 assert_jdn_close(
1412 julianday_float("2026-04-07T16:00:00+0100"),
1413 base - 1.0 / 24.0,
1414 "+0100",
1415 );
1416 assert_jdn_close(
1417 julianday_float("2026-04-07T16:00:00-0530"),
1418 base + 5.5 / 24.0,
1419 "-0530",
1420 );
1421 assert_jdn_close(
1422 julianday_float("2026-04-07T16:00:00+09"),
1423 base - 9.0 / 24.0,
1424 "+09",
1425 );
1426 }
1427
1428 #[test]
1429 fn test_julianday_rfc3339_fractional_seconds_with_tz() {
1430 let base = julianday_float("2026-04-07 16:00:00.500");
1432 assert_jdn_close(
1433 julianday_float("2026-04-07T16:00:00.500Z"),
1434 base,
1435 "fractional + Z",
1436 );
1437 assert_jdn_close(
1438 julianday_float("2026-04-07T16:00:00.500+01:00"),
1439 base - 1.0 / 24.0,
1440 "fractional + +01:00",
1441 );
1442 }
1443
1444 #[test]
1445 fn test_date_and_time_rfc3339_round_trip() {
1446 assert_text(
1449 &DateFunc
1450 .invoke(&[text("2026-04-07T16:00:00+05:00")])
1451 .unwrap(),
1452 "2026-04-07",
1454 );
1455 assert_text(
1456 &TimeFunc
1457 .invoke(&[text("2026-04-07T16:00:00+05:00")])
1458 .unwrap(),
1459 "11:00:00",
1460 );
1461 assert_text(
1462 &DateTimeFunc
1463 .invoke(&[text("2026-04-07T16:00:00+05:00")])
1464 .unwrap(),
1465 "2026-04-07 11:00:00",
1466 );
1467 }
1468
1469 #[test]
1470 fn test_julianday_rfc3339_invalid_offsets_return_null() {
1471 for bad in &[
1473 "2026-04-07T16:00:00+25:00", "2026-04-07T16:00:00+01:99", "2026-04-07T16:00:00+1", "2026-04-07T16:00:00+123", ] {
1478 let result = JuliandayFunc.invoke(&[text(bad)]).unwrap();
1479 assert_eq!(
1480 result,
1481 SqliteValue::Null,
1482 "expected NULL for malformed offset {bad:?}, got {result:?}"
1483 );
1484 }
1485 }
1486
1487 #[test]
1488 fn test_julianday_rejects_malformed_time_fields() {
1489 for bad in &[
1493 "+01:00", "-05:30", "+12:30:00", "12:+30:00", "12:30:+45", "12:30:+45.123", "0:00:00", "12:0:00", "12:30:0", "123:00:00", "12:345:00", ] {
1505 let result = JuliandayFunc.invoke(&[text(bad)]).unwrap();
1506 assert_eq!(
1507 result,
1508 SqliteValue::Null,
1509 "expected NULL for signed time field {bad:?}, got {result:?}"
1510 );
1511 }
1512 }
1513
1514 #[test]
1515 fn test_unixepoch_basic() {
1516 let r = UnixepochFunc
1517 .invoke(&[text("1970-01-01 00:00:00")])
1518 .unwrap();
1519 assert_eq!(r, int(0));
1520 }
1521
1522 #[test]
1523 fn test_unixepoch_known_date() {
1524 let r = UnixepochFunc
1525 .invoke(&[text("2024-01-01 00:00:00")])
1526 .unwrap();
1527 assert_eq!(r, int(1_704_067_200));
1529 }
1530
1531 #[test]
1534 fn test_modifier_days() {
1535 let r = DateFunc
1536 .invoke(&[text("2024-01-15"), text("+10 days")])
1537 .unwrap();
1538 assert_text(&r, "2024-01-25");
1539 }
1540
1541 #[test]
1542 fn test_modifier_months() {
1543 let r = DateFunc
1546 .invoke(&[text("2024-01-31"), text("+1 months")])
1547 .unwrap();
1548 assert_text(&r, "2024-03-02");
1549 }
1550
1551 #[test]
1552 fn test_modifier_years() {
1553 let r = DateFunc
1556 .invoke(&[text("2024-02-29"), text("+1 years")])
1557 .unwrap();
1558 assert_text(&r, "2025-03-01");
1559 }
1560
1561 #[test]
1562 fn test_modifier_hours() {
1563 let r = DateTimeFunc
1564 .invoke(&[text("2024-01-01 23:00:00"), text("+2 hours")])
1565 .unwrap();
1566 assert_text(&r, "2024-01-02 01:00:00");
1567 }
1568
1569 #[test]
1570 fn test_modifier_start_of_month() {
1571 let r = DateFunc
1572 .invoke(&[text("2024-03-15"), text("start of month")])
1573 .unwrap();
1574 assert_text(&r, "2024-03-01");
1575 }
1576
1577 #[test]
1578 fn test_modifier_start_of_year() {
1579 let r = DateFunc
1580 .invoke(&[text("2024-06-15"), text("start of year")])
1581 .unwrap();
1582 assert_text(&r, "2024-01-01");
1583 }
1584
1585 #[test]
1586 fn test_modifier_start_of_day() {
1587 let r = DateTimeFunc
1588 .invoke(&[text("2024-03-15 14:30:00"), text("start of day")])
1589 .unwrap();
1590 assert_text(&r, "2024-03-15 00:00:00");
1591 }
1592
1593 #[test]
1594 fn test_modifier_unixepoch() {
1595 let r = DateTimeFunc.invoke(&[int(0), text("unixepoch")]).unwrap();
1596 assert_text(&r, "1970-01-01 00:00:00");
1597 }
1598
1599 #[test]
1600 fn test_modifier_weekday() {
1601 let r = DateFunc
1603 .invoke(&[text("2024-03-15"), text("weekday 0")])
1604 .unwrap();
1605 assert_text(&r, "2024-03-17");
1606 }
1607
1608 #[test]
1609 fn test_modifier_auto_unixepoch() {
1610 let ts = int(1_710_531_045);
1611 let r = DateTimeFunc.invoke(&[ts.clone(), text("auto")]).unwrap();
1612 let expected = DateTimeFunc.invoke(&[ts, text("unixepoch")]).unwrap();
1613 assert_eq!(
1614 r, expected,
1615 "auto and unixepoch should agree for unix-like values"
1616 );
1617 }
1618
1619 #[test]
1620 fn test_modifier_auto_julian_day() {
1621 let r = DateFunc
1622 .invoke(&[float(2_460_384.5), text("auto")])
1623 .unwrap();
1624 assert_text(&r, "2024-03-15");
1625 }
1626
1627 #[test]
1628 fn test_modifier_localtime_utc_roundtrip() {
1629 let r = DateTimeFunc
1631 .invoke(&[text("2024-03-15 14:30:45"), text("localtime"), text("utc")])
1632 .unwrap();
1633 assert_text(&r, "2024-03-15 14:30:45");
1634 }
1635
1636 #[test]
1637 fn test_modifier_localtime_shifts_value() {
1638 let offset = utc_offset_for_utc_jdn(ymdhms_to_jdn(2024, 3, 15, 12, 0, 0, 0.0));
1640 if offset != 0 {
1641 let r = DateTimeFunc
1642 .invoke(&[text("2024-03-15 12:00:00"), text("localtime")])
1643 .unwrap();
1644 let shifted = match &r {
1646 SqliteValue::Text(s) => s.clone(),
1647 _ => panic!("expected text"),
1648 };
1649 assert_ne!(&*shifted, "2024-03-15 12:00:00");
1650 }
1651 }
1652
1653 #[test]
1654 fn test_modifier_auto_out_of_range_returns_null() {
1655 let r = DateTimeFunc.invoke(&[float(1.0e20), text("auto")]).unwrap();
1656 assert_eq!(r, SqliteValue::Null);
1657 }
1658
1659 #[test]
1660 fn test_modifier_order_matters() {
1661 let r1 = DateFunc
1663 .invoke(&[text("2024-03-15"), text("start of month"), text("+1 days")])
1664 .unwrap();
1665 assert_text(&r1, "2024-03-02");
1666
1667 let r2 = DateFunc
1669 .invoke(&[text("2024-03-15"), text("+1 days"), text("start of month")])
1670 .unwrap();
1671 assert_text(&r2, "2024-03-01");
1672 }
1673
1674 #[test]
1675 fn test_modifier_weekday_same_day_is_noop() {
1676 let r = DateFunc
1678 .invoke(&[text("2024-03-17"), text("weekday 0")])
1679 .unwrap();
1680 assert_text(&r, "2024-03-17");
1681 }
1682
1683 #[test]
1686 fn test_bare_time_defaults() {
1687 let r = DateFunc.invoke(&[text("12:30:00")]).unwrap();
1688 assert_text(&r, "2000-01-01");
1689 }
1690
1691 #[test]
1692 fn test_t_separator() {
1693 let r = DateTimeFunc.invoke(&[text("2024-03-15T14:30:00")]).unwrap();
1694 assert_text(&r, "2024-03-15 14:30:00");
1695 }
1696
1697 #[test]
1698 fn test_julian_day_input() {
1699 let r = DateFunc.invoke(&[float(2_460_384.5)]).unwrap();
1701 assert_text(&r, "2024-03-15");
1702 }
1703
1704 #[test]
1705 fn test_null_input() {
1706 assert_eq!(DateFunc.invoke(&[null()]).unwrap(), SqliteValue::Null);
1707 }
1708
1709 #[test]
1710 fn test_invalid_input() {
1711 assert_eq!(
1712 DateFunc.invoke(&[text("not-a-date")]).unwrap(),
1713 SqliteValue::Null
1714 );
1715 }
1716
1717 #[test]
1718 fn test_negative_time_component_invalid() {
1719 let r = TimeFunc.invoke(&[text("-01:00")]).unwrap();
1720 assert_eq!(r, SqliteValue::Null);
1721 }
1722
1723 #[test]
1726 fn test_leap_year() {
1727 let r = DateFunc
1728 .invoke(&[text("2024-02-28"), text("+1 days")])
1729 .unwrap();
1730 assert_text(&r, "2024-02-29");
1731 }
1732
1733 #[test]
1734 fn test_non_leap_year() {
1735 let r = DateFunc
1736 .invoke(&[text("2023-02-28"), text("+1 days")])
1737 .unwrap();
1738 assert_text(&r, "2023-03-01");
1739 }
1740
1741 #[test]
1744 fn test_strftime_basic() {
1745 let r = StrftimeFunc
1746 .invoke(&[text("%Y-%m-%d"), text("2024-03-15")])
1747 .unwrap();
1748 assert_text(&r, "2024-03-15");
1749 }
1750
1751 #[test]
1752 fn test_strftime_time_specifiers() {
1753 let r = StrftimeFunc
1754 .invoke(&[text("%H:%M:%S"), text("2024-03-15 14:30:45")])
1755 .unwrap();
1756 assert_text(&r, "14:30:45");
1757 }
1758
1759 #[test]
1760 fn test_strftime_unix_seconds() {
1761 let r = StrftimeFunc
1762 .invoke(&[text("%s"), text("1970-01-01 00:00:00")])
1763 .unwrap();
1764 assert_text(&r, "0");
1765 }
1766
1767 #[test]
1768 fn test_strftime_day_of_year() {
1769 let r = StrftimeFunc
1770 .invoke(&[text("%j"), text("2024-03-15")])
1771 .unwrap();
1772 assert_text(&r, "075");
1774 }
1775
1776 #[test]
1777 fn test_strftime_day_of_week() {
1778 let r = StrftimeFunc
1780 .invoke(&[text("%w"), text("2024-03-15")])
1781 .unwrap();
1782 assert_text(&r, "5");
1783
1784 let r = StrftimeFunc
1785 .invoke(&[text("%u"), text("2024-03-15")])
1786 .unwrap();
1787 assert_text(&r, "5");
1788 }
1789
1790 #[test]
1791 fn test_strftime_12hour() {
1792 let r = StrftimeFunc
1793 .invoke(&[text("%I %p"), text("2024-03-15 14:30:00")])
1794 .unwrap();
1795 assert_text(&r, "02 PM");
1796
1797 let r = StrftimeFunc
1798 .invoke(&[text("%I %P"), text("2024-03-15 09:30:00")])
1799 .unwrap();
1800 assert_text(&r, "09 am");
1801 }
1802
1803 #[test]
1804 fn test_strftime_all_specifiers_presence() {
1805 let fmt = "%d|%e|%f|%H|%I|%j|%J|%k|%l|%m|%M|%p|%P|%R|%s|%S|%T|%u|%w|%W|%G|%g|%V|%Y|%%";
1806 let r = StrftimeFunc
1807 .invoke(&[text(fmt), text("2024-03-15 14:30:45.123")])
1808 .unwrap();
1809
1810 let s = match r {
1811 SqliteValue::Text(v) => v,
1812 other => panic!("expected Text, got {other:?}"),
1813 };
1814 let parts: Vec<&str> = s.split('|').collect();
1815 assert_eq!(parts.len(), 25, "unexpected specifier output: {s}");
1816 assert_eq!(parts[0], "15"); assert_eq!(parts[1], "15"); assert_eq!(parts[2], "45.123"); assert_eq!(parts[3], "14"); assert_eq!(parts[4], "02"); assert_eq!(parts[5], "075"); assert!(
1823 parts[6].parse::<f64>().is_ok(),
1824 "expected numeric %J output, got {}",
1825 parts[6]
1826 );
1827 assert_eq!(parts[7], "14"); assert_eq!(parts[8], " 2"); assert_eq!(parts[9], "03"); assert_eq!(parts[10], "30"); assert_eq!(parts[11], "PM"); assert_eq!(parts[12], "pm"); assert_eq!(parts[13], "14:30"); assert!(
1835 parts[14].parse::<i64>().is_ok(),
1836 "expected numeric %s output, got {}",
1837 parts[14]
1838 );
1839 assert_eq!(parts[15], "45"); assert_eq!(parts[16], "14:30:45"); assert_eq!(parts[17], "5"); assert_eq!(parts[18], "5"); assert_eq!(parts[19], "11"); assert_eq!(parts[20], "2024"); assert_eq!(parts[21], "24"); assert_eq!(parts[22], "11"); assert_eq!(parts[23], "2024"); assert_eq!(parts[24], "%"); }
1850
1851 #[test]
1852 fn test_strftime_null() {
1853 assert_eq!(
1854 StrftimeFunc.invoke(&[null(), text("2024-01-01")]).unwrap(),
1855 SqliteValue::Null
1856 );
1857 assert_eq!(
1858 StrftimeFunc.invoke(&[text("%Y"), null()]).unwrap(),
1859 SqliteValue::Null
1860 );
1861 }
1862
1863 #[test]
1864 #[ignore = "perf-only benchmark"]
1865 fn perf_strftime_timestamp_rows() {
1866 use std::hint::black_box;
1867 use std::time::Instant;
1868
1869 const ROWS: usize = 200_000;
1870 const REPEATS: usize = 5;
1871 const FORMAT: &str = "%Y-%m-%d %H:%M:%S";
1872 const INPUT: &str = "2024-03-15 14:30:45";
1873
1874 let func = StrftimeFunc;
1875 let fmt = text(FORMAT);
1876 let input = text(INPUT);
1877 let mut best_ns = u128::MAX;
1878 let mut output_len = 0usize;
1879
1880 for _ in 0..REPEATS {
1881 let started = Instant::now();
1882 for _ in 0..ROWS {
1883 let result = black_box(
1884 func.invoke(black_box(&[fmt.clone(), input.clone()]))
1885 .expect("strftime benchmark invocation must succeed"),
1886 );
1887 output_len = match result {
1888 SqliteValue::Text(text) => text.len(),
1889 SqliteValue::Null
1890 | SqliteValue::Integer(_)
1891 | SqliteValue::Float(_)
1892 | SqliteValue::Blob(_) => 0,
1893 };
1894 }
1895 let elapsed_ns = started.elapsed().as_nanos();
1896 if elapsed_ns < best_ns {
1897 best_ns = elapsed_ns;
1898 }
1899 }
1900
1901 println!(
1902 "strftime_timestamp_rows rows={ROWS} repeats={REPEATS} best_ns={best_ns} output_len={output_len}"
1903 );
1904 }
1905
1906 #[test]
1909 fn test_timediff_basic() {
1910 let r = TimediffFunc
1911 .invoke(&[text("2024-03-15"), text("2024-03-10")])
1912 .unwrap();
1913 assert_text(&r, "+0000-00-05 00:00:00.000");
1914 }
1915
1916 #[test]
1917 fn test_timediff_negative() {
1918 let r = TimediffFunc
1919 .invoke(&[text("2024-03-10"), text("2024-03-15")])
1920 .unwrap();
1921 assert_text(&r, "-0000-00-05 00:00:00.000");
1922 }
1923
1924 #[test]
1925 fn test_timediff_year_boundary() {
1926 let r = TimediffFunc
1927 .invoke(&[text("2024-01-01 01:00:00"), text("2023-12-31 23:00:00")])
1928 .unwrap();
1929 assert_text(&r, "+0000-00-00 02:00:00.000");
1930 }
1931
1932 #[test]
1935 fn test_modifier_subsec() {
1936 let r = TimeFunc
1937 .invoke(&[text("2024-01-01 12:00:00.123"), text("subsec")])
1938 .unwrap();
1939 match &r {
1940 SqliteValue::Text(s) => assert!(
1941 s.contains('.'),
1942 "expected fractional seconds with subsec: {s}"
1943 ),
1944 other => panic!("expected Text, got {other:?}"),
1945 }
1946 }
1947
1948 #[test]
1951 fn test_register_datetime_builtins_all_present() {
1952 let mut reg = FunctionRegistry::new();
1953 register_datetime_builtins(&mut reg);
1954
1955 let expected = [
1956 "date",
1957 "time",
1958 "datetime",
1959 "julianday",
1960 "unixepoch",
1961 "strftime",
1962 "timediff",
1963 ];
1964
1965 for name in expected {
1966 assert!(
1967 reg.find_scalar(name, 1).is_some() || reg.find_scalar(name, 2).is_some(),
1968 "datetime function '{name}' not registered"
1969 );
1970 }
1971 }
1972
1973 #[test]
1976 fn test_modifier_year_overflow() {
1977 let huge = i64::MAX;
1980 let modifier = format!("+{huge} years");
1981 let r = DateFunc.invoke(&[text("2000-01-01"), text(&modifier)]);
1982 assert_eq!(r.unwrap(), SqliteValue::Null);
1985 }
1986
1987 #[test]
1988 fn test_jdn_roundtrip() {
1989 let dates = [
1991 (2024, 3, 15),
1992 (2000, 1, 1),
1993 (1970, 1, 1),
1994 (2024, 2, 29),
1995 (1900, 1, 1),
1996 (2099, 12, 31),
1997 ];
1998 for (y, m, d) in dates {
1999 let jdn = ymd_to_jdn(y, m, d);
2000 let (y2, m2, d2) = jdn_to_ymd(jdn);
2001 assert_eq!(
2002 (y, m, d),
2003 (y2, m2, d2),
2004 "roundtrip failed for {y}-{m}-{d} (JDN={jdn})"
2005 );
2006 }
2007 }
2008
2009 #[test]
2010 fn test_unix_epoch_roundtrip() {
2011 let jdn = ymd_to_jdn(1970, 1, 1);
2012 let unix = jdn_to_unix(jdn);
2013 assert_eq!(unix, 0, "Unix epoch should be 0");
2014
2015 let jdn2 = unix_to_jdn(0.0);
2016 assert!((jdn2 - UNIX_EPOCH_JDN).abs() < 1e-10, "roundtrip failed");
2017 }
2018}