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((ymdhms_to_jdn(new_y, new_mo, d, h, mi, s, frac), n_floor)))
711}
712
713fn format_date(jdn: f64) -> String {
716 let (y, m, d) = jdn_to_ymd(jdn);
717 format!("{y:04}-{m:02}-{d:02}")
718}
719
720fn format_time(jdn: f64, subsec: bool) -> String {
721 let (h, m, s, frac) = jdn_to_hms(jdn);
722 if subsec && frac > 1e-9 {
723 format!("{h:02}:{m:02}:{s:02}.{:03}", (frac * 1000.0).round() as i64)
724 } else {
725 format!("{h:02}:{m:02}:{s:02}")
726 }
727}
728
729fn format_datetime(jdn: f64, subsec: bool) -> String {
730 format!("{} {}", format_date(jdn), format_time(jdn, subsec))
731}
732
733#[inline]
734fn push_format(result: &mut String, args: Arguments<'_>) {
735 let _ = result.write_fmt(args);
736}
737
738#[inline]
739fn push_zero_padded_2(result: &mut String, value: i64) {
740 if (0..=99).contains(&value) {
741 let value = value as u8;
742 result.push(char::from(b'0' + value / 10));
743 result.push(char::from(b'0' + value % 10));
744 } else {
745 push_format(result, format_args!("{value:02}"));
746 }
747}
748
749#[inline]
750fn push_space_padded_2(result: &mut String, value: i64) {
751 if (0..=99).contains(&value) {
752 let value = value as u8;
753 if value >= 10 {
754 result.push(char::from(b'0' + value / 10));
755 } else {
756 result.push(' ');
757 }
758 result.push(char::from(b'0' + value % 10));
759 } else {
760 push_format(result, format_args!("{value:>2}"));
761 }
762}
763
764#[inline]
765fn push_zero_padded_3(result: &mut String, value: i64) {
766 if (0..=999).contains(&value) {
767 let value = value as u16;
768 result.push(char::from(b'0' + (value / 100) as u8));
769 result.push(char::from(b'0' + ((value / 10) % 10) as u8));
770 result.push(char::from(b'0' + (value % 10) as u8));
771 } else {
772 push_format(result, format_args!("{value:03}"));
773 }
774}
775
776#[inline]
777fn push_zero_padded_4(result: &mut String, value: i64) {
778 if (0..=9999).contains(&value) {
779 let value = value as u16;
780 result.push(char::from(b'0' + (value / 1000) as u8));
781 result.push(char::from(b'0' + ((value / 100) % 10) as u8));
782 result.push(char::from(b'0' + ((value / 10) % 10) as u8));
783 result.push(char::from(b'0' + (value % 10) as u8));
784 } else {
785 push_format(result, format_args!("{value:04}"));
786 }
787}
788
789fn format_strftime(fmt: &str, jdn: f64) -> String {
791 let (y, mo, d) = jdn_to_ymd(jdn);
792 let (h, mi, s, frac) = jdn_to_hms(jdn);
793 let doy = day_of_year(y, mo, d);
794 let jdn_int = (jdn + 0.5).floor() as i64;
796 let dow = (jdn_int + 1) % 7; let mut result = String::with_capacity(fmt.len().saturating_add(8));
799 let bytes = fmt.as_bytes();
800 let mut i = 0;
801 let mut literal_start = 0;
802
803 while i < bytes.len() {
804 if bytes[i] != b'%' || i + 1 >= bytes.len() {
805 i += 1;
806 continue;
807 }
808
809 result.push_str(&fmt[literal_start..i]);
810
811 let spec_suffix = &fmt[i + 1..];
812 let Some(spec) = spec_suffix.chars().next() else {
813 break;
814 };
815 i += 1 + spec.len_utf8();
816 literal_start = i;
817
818 match spec {
819 'd' => push_zero_padded_2(&mut result, d),
820 'e' => push_space_padded_2(&mut result, d),
821 'F' => {
822 push_zero_padded_4(&mut result, y);
824 result.push('-');
825 push_zero_padded_2(&mut result, mo);
826 result.push('-');
827 push_zero_padded_2(&mut result, d);
828 }
829 'f' => {
830 let total = s as f64 + frac;
832 push_format(&mut result, format_args!("{total:06.3}"));
833 }
834 'H' => push_zero_padded_2(&mut result, h),
835 'I' => {
836 let h12 = if h == 0 {
838 12
839 } else if h > 12 {
840 h - 12
841 } else {
842 h
843 };
844 push_zero_padded_2(&mut result, h12);
845 }
846 'j' => push_zero_padded_3(&mut result, doy),
847 'J' => {
848 push_format(&mut result, format_args!("{jdn:.15}"));
850 while result.as_bytes().last() == Some(&b'0') {
851 result.pop();
852 }
853 if result.as_bytes().last() == Some(&b'.') {
854 result.pop();
855 }
856 }
857 'k' => {
858 push_space_padded_2(&mut result, h);
860 }
861 'l' => {
862 let h12 = if h == 0 {
864 12
865 } else if h > 12 {
866 h - 12
867 } else {
868 h
869 };
870 push_space_padded_2(&mut result, h12);
871 }
872 'm' => push_zero_padded_2(&mut result, mo),
873 'M' => push_zero_padded_2(&mut result, mi),
874 'p' => {
875 result.push_str(if h < 12 { "AM" } else { "PM" });
876 }
877 'P' => {
878 result.push_str(if h < 12 { "am" } else { "pm" });
879 }
880 'R' => {
881 push_zero_padded_2(&mut result, h);
882 result.push(':');
883 push_zero_padded_2(&mut result, mi);
884 }
885 's' => {
886 let unix = jdn_to_unix(jdn);
887 push_format(&mut result, format_args!("{unix}"));
888 }
889 'S' => push_zero_padded_2(&mut result, s),
890 'T' => {
891 push_zero_padded_2(&mut result, h);
892 result.push(':');
893 push_zero_padded_2(&mut result, mi);
894 result.push(':');
895 push_zero_padded_2(&mut result, s);
896 }
897 'u' => {
898 let u = if dow == 0 { 7 } else { dow };
900 push_format(&mut result, format_args!("{u}"));
901 }
902 'w' => push_format(&mut result, format_args!("{dow}")),
903 'W' => {
904 let w = (doy + 6 - ((dow + 6) % 7)) / 7;
906 push_zero_padded_2(&mut result, w);
907 }
908 'Y' => push_zero_padded_4(&mut result, y),
909 'G' | 'g' | 'V' => {
910 let (iso_y, iso_w) = iso_week(y, mo, d);
912 match spec {
913 'G' => push_zero_padded_4(&mut result, iso_y),
914 'g' => push_zero_padded_2(&mut result, iso_y % 100),
915 'V' => push_zero_padded_2(&mut result, iso_w),
916 _ => unreachable!(),
917 }
918 }
919 '%' => result.push('%'),
920 other => {
921 result.push('%');
922 result.push(other);
923 }
924 }
925 }
926
927 if literal_start < fmt.len() {
928 result.push_str(&fmt[literal_start..]);
929 }
930
931 result
932}
933
934fn iso_week(y: i64, m: i64, d: i64) -> (i64, i64) {
936 let jdn = ymd_to_jdn(y, m, d);
937 let jdn_int = (jdn + 0.5).floor() as i64;
938 let dow = (jdn_int + 1) % 7;
940 let iso_dow = if dow == 0 { 7 } else { dow };
941
942 let thu_jdn = jdn_int + (4 - iso_dow);
944 let (thu_y, _, _) = jdn_to_ymd(thu_jdn as f64);
945
946 let jan4_jdn = (ymd_to_jdn(thu_y, 1, 4) + 0.5).floor() as i64;
948 let jan4_dow = (jan4_jdn + 1) % 7;
949 let jan4_iso_dow = if jan4_dow == 0 { 7 } else { jan4_dow };
950 let week1_start = jan4_jdn - (jan4_iso_dow - 1);
951
952 let week = (thu_jdn - week1_start) / 7 + 1;
953 (thu_y, week)
954}
955
956fn timediff_impl(jdn1: f64, jdn2: f64) -> String {
959 let (sign, start_jdn, end_jdn) = if jdn1 >= jdn2 {
960 ('+', jdn2, jdn1)
961 } else {
962 ('-', jdn1, jdn2)
963 };
964
965 let (start_y, start_mo, start_d) = jdn_to_ymd(start_jdn);
966 let (start_h, start_mi, mut start_s, start_frac) = jdn_to_hms(start_jdn);
967 let mut start_ms = (start_frac * 1000.0).round() as i64;
968 if start_ms >= 1000 {
969 start_ms = 0;
970 start_s += 1;
971 }
972
973 let (end_y, end_mo, end_d) = jdn_to_ymd(end_jdn);
974 let (end_h, end_mi, mut end_s, end_frac) = jdn_to_hms(end_jdn);
975 let mut end_ms = (end_frac * 1000.0).round() as i64;
976 if end_ms >= 1000 {
977 end_ms = 0;
978 end_s += 1;
979 }
980
981 let mut years = end_y - start_y;
982 let mut months = end_mo - start_mo;
983 let mut days = end_d - start_d;
984 let mut hours = end_h - start_h;
985 let mut minutes = end_mi - start_mi;
986 let mut seconds = end_s - start_s;
987 let mut millis = end_ms - start_ms;
988
989 if millis < 0 {
990 millis += 1000;
991 seconds -= 1;
992 }
993 if seconds < 0 {
994 seconds += 60;
995 minutes -= 1;
996 }
997 if minutes < 0 {
998 minutes += 60;
999 hours -= 1;
1000 }
1001 if hours < 0 {
1002 hours += 24;
1003 days -= 1;
1004 }
1005 if days < 0 {
1006 months -= 1;
1007 let (borrow_y, borrow_mo) = if end_mo == 1 {
1008 (end_y - 1, 12)
1009 } else {
1010 (end_y, end_mo - 1)
1011 };
1012 days += days_in_month(borrow_y, borrow_mo);
1013 }
1014 if months < 0 {
1015 months += 12;
1016 years -= 1;
1017 }
1018
1019 format!(
1020 "{sign}{years:04}-{months:02}-{days:02} {hours:02}:{minutes:02}:{seconds:02}.{millis:03}"
1021 )
1022}
1023
1024fn parse_args(args: &[SqliteValue]) -> Option<(f64, bool)> {
1028 if args.is_empty() || args[0].is_null() {
1029 return None;
1030 }
1031
1032 let input = match &args[0] {
1033 SqliteValue::Text(s) => parse_timestring(s)?,
1034 SqliteValue::Integer(i) => *i as f64,
1035 SqliteValue::Float(f) => *f,
1036 _ => return None,
1037 };
1038
1039 if args[1..].iter().any(SqliteValue::is_null) {
1042 return None;
1043 }
1044 let modifiers: Vec<String> = args[1..].iter().map(SqliteValue::to_text).collect();
1045
1046 apply_modifiers(input, &modifiers)
1047}
1048
1049pub struct DateFunc;
1052
1053impl ScalarFunction for DateFunc {
1054 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1055 match parse_args(args) {
1056 Some((jdn, _)) => Ok(SqliteValue::Text(format_date(jdn).into())),
1057 None => Ok(SqliteValue::Null),
1058 }
1059 }
1060
1061 fn num_args(&self) -> i32 {
1062 -1
1063 }
1064
1065 fn name(&self) -> &str {
1066 "date"
1067 }
1068}
1069
1070pub struct TimeFunc;
1073
1074impl ScalarFunction for TimeFunc {
1075 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1076 match parse_args(args) {
1077 Some((jdn, subsec)) => Ok(SqliteValue::Text(format_time(jdn, subsec).into())),
1078 None => Ok(SqliteValue::Null),
1079 }
1080 }
1081
1082 fn num_args(&self) -> i32 {
1083 -1
1084 }
1085
1086 fn name(&self) -> &str {
1087 "time"
1088 }
1089}
1090
1091pub struct DateTimeFunc;
1094
1095impl ScalarFunction for DateTimeFunc {
1096 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1097 match parse_args(args) {
1098 Some((jdn, subsec)) => Ok(SqliteValue::Text(format_datetime(jdn, subsec).into())),
1099 None => Ok(SqliteValue::Null),
1100 }
1101 }
1102
1103 fn num_args(&self) -> i32 {
1104 -1
1105 }
1106
1107 fn name(&self) -> &str {
1108 "datetime"
1109 }
1110}
1111
1112pub struct JuliandayFunc;
1115
1116impl ScalarFunction for JuliandayFunc {
1117 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1118 match parse_args(args) {
1119 Some((jdn, _)) => Ok(SqliteValue::Float(jdn)),
1120 None => Ok(SqliteValue::Null),
1121 }
1122 }
1123
1124 fn num_args(&self) -> i32 {
1125 -1
1126 }
1127
1128 fn name(&self) -> &str {
1129 "julianday"
1130 }
1131}
1132
1133pub struct UnixepochFunc;
1136
1137impl ScalarFunction for UnixepochFunc {
1138 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1139 match parse_args(args) {
1140 Some((jdn, true)) => {
1143 let secs = (jdn - UNIX_EPOCH_JDN) * 86400.0;
1144 let rounded = (secs * 1000.0).round() / 1000.0;
1145 Ok(SqliteValue::Float(rounded))
1146 }
1147 Some((jdn, false)) => Ok(SqliteValue::Integer(jdn_to_unix(jdn))),
1148 None => Ok(SqliteValue::Null),
1149 }
1150 }
1151
1152 fn num_args(&self) -> i32 {
1153 -1
1154 }
1155
1156 fn name(&self) -> &str {
1157 "unixepoch"
1158 }
1159}
1160
1161pub struct StrftimeFunc;
1164
1165impl ScalarFunction for StrftimeFunc {
1166 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1167 if args.len() < 2 || args[0].is_null() || args[1].is_null() {
1168 return Ok(SqliteValue::Null);
1169 }
1170 let rest = &args[1..];
1171 match parse_args(rest) {
1172 Some((jdn, _)) => {
1173 let fmt = match args[0].as_text_str() {
1174 Some(text) => Cow::Borrowed(text),
1175 None => Cow::Owned(args[0].to_text()),
1176 };
1177 Ok(SqliteValue::Text(format_strftime(fmt.as_ref(), jdn).into()))
1178 }
1179 None => Ok(SqliteValue::Null),
1180 }
1181 }
1182
1183 fn num_args(&self) -> i32 {
1184 -1
1185 }
1186
1187 fn name(&self) -> &str {
1188 "strftime"
1189 }
1190}
1191
1192pub struct TimediffFunc;
1195
1196impl ScalarFunction for TimediffFunc {
1197 fn invoke(&self, args: &[SqliteValue]) -> Result<SqliteValue> {
1198 if args.len() < 2 || args[0].is_null() || args[1].is_null() {
1199 return Ok(SqliteValue::Null);
1200 }
1201
1202 let jdn1 = match &args[0] {
1203 SqliteValue::Text(s) => parse_timestring(s),
1204 SqliteValue::Integer(i) => Some(*i as f64),
1205 SqliteValue::Float(f) => Some(*f),
1206 _ => None,
1207 };
1208 let jdn2 = match &args[1] {
1209 SqliteValue::Text(s) => parse_timestring(s),
1210 SqliteValue::Integer(i) => Some(*i as f64),
1211 SqliteValue::Float(f) => Some(*f),
1212 _ => None,
1213 };
1214
1215 match (jdn1, jdn2) {
1216 (Some(j1), Some(j2)) => Ok(SqliteValue::Text(timediff_impl(j1, j2).into())),
1217 _ => Ok(SqliteValue::Null),
1218 }
1219 }
1220
1221 fn num_args(&self) -> i32 {
1222 2
1223 }
1224
1225 fn name(&self) -> &str {
1226 "timediff"
1227 }
1228}
1229
1230pub fn register_datetime_builtins(registry: &mut FunctionRegistry) {
1234 registry.register_scalar(DateFunc);
1235 registry.register_scalar(TimeFunc);
1236 registry.register_scalar(DateTimeFunc);
1237 registry.register_scalar(JuliandayFunc);
1238 registry.register_scalar(UnixepochFunc);
1239 registry.register_scalar(StrftimeFunc);
1240 registry.register_scalar(TimediffFunc);
1241}
1242
1243#[cfg(test)]
1246mod tests {
1247 use super::*;
1248
1249 fn text(s: &str) -> SqliteValue {
1250 SqliteValue::Text(s.into())
1251 }
1252
1253 fn int(v: i64) -> SqliteValue {
1254 SqliteValue::Integer(v)
1255 }
1256
1257 fn float(v: f64) -> SqliteValue {
1258 SqliteValue::Float(v)
1259 }
1260
1261 fn null() -> SqliteValue {
1262 SqliteValue::Null
1263 }
1264
1265 fn assert_text(result: &SqliteValue, expected: &str) {
1266 match result {
1267 SqliteValue::Text(s) => assert_eq!(s.as_ref(), expected, "text mismatch"),
1268 other => panic!("expected Text(\"{expected}\"), got {other:?}"),
1269 }
1270 }
1271
1272 #[test]
1275 fn test_date_basic() {
1276 let r = DateFunc.invoke(&[text("2024-03-15 14:30:00")]).unwrap();
1277 assert_text(&r, "2024-03-15");
1278 }
1279
1280 #[test]
1281 fn test_time_basic() {
1282 let r = TimeFunc.invoke(&[text("2024-03-15 14:30:45")]).unwrap();
1283 assert_text(&r, "14:30:45");
1284 }
1285
1286 #[test]
1287 fn test_datetime_basic() {
1288 let r = DateTimeFunc.invoke(&[text("2024-03-15 14:30:00")]).unwrap();
1289 assert_text(&r, "2024-03-15 14:30:00");
1290 }
1291
1292 #[test]
1293 fn test_julianday_basic() {
1294 let r = JuliandayFunc.invoke(&[text("2024-03-15")]).unwrap();
1295 match r {
1296 SqliteValue::Float(jdn) => {
1297 assert!((jdn - 2_460_384.5).abs() < 0.01, "unexpected JDN: {jdn}");
1299 }
1300 other => panic!("expected Float, got {other:?}"),
1301 }
1302 }
1303
1304 fn julianday_float(input: &str) -> f64 {
1312 match JuliandayFunc.invoke(&[text(input)]).unwrap() {
1313 SqliteValue::Float(v) => v,
1314 other => panic!("expected Float, got {other:?} for input {input:?}"),
1315 }
1316 }
1317
1318 fn assert_jdn_close(actual: f64, expected: f64, ctx: &str) {
1319 assert!(
1321 (actual - expected).abs() < 1e-6,
1322 "JDN mismatch for {ctx}: got {actual}, expected {expected}"
1323 );
1324 }
1325
1326 #[test]
1327 fn test_julianday_rfc3339_z_suffix() {
1328 let naive = julianday_float("2026-04-07 16:00:00");
1330 assert_jdn_close(julianday_float("2026-04-07T16:00:00Z"), naive, "T...Z");
1331 assert_jdn_close(
1332 julianday_float("2026-04-07T16:00:00z"),
1333 naive,
1334 "lowercase z",
1335 );
1336 }
1337
1338 #[test]
1339 fn test_julianday_rfc3339_zero_offset() {
1340 let naive = julianday_float("2026-04-07 16:00:00");
1341 assert_jdn_close(
1342 julianday_float("2026-04-07T16:00:00+00:00"),
1343 naive,
1344 "+00:00",
1345 );
1346 assert_jdn_close(
1347 julianday_float("2026-04-07T16:00:00-00:00"),
1348 naive,
1349 "-00:00",
1350 );
1351 }
1352
1353 #[test]
1354 fn test_julianday_rfc3339_positive_offset() {
1355 let base = julianday_float("2026-04-07 16:00:00");
1357 let expected = base - 1.0 / 24.0;
1358 assert_jdn_close(
1359 julianday_float("2026-04-07T16:00:00+01:00"),
1360 expected,
1361 "+01:00",
1362 );
1363 }
1364
1365 #[test]
1366 fn test_julianday_rfc3339_negative_offset() {
1367 let base = julianday_float("2026-04-07 16:00:00");
1369 let expected = base + 5.0 / 24.0;
1370 assert_jdn_close(
1371 julianday_float("2026-04-07T16:00:00-05:00"),
1372 expected,
1373 "-05:00",
1374 );
1375 }
1376
1377 #[test]
1378 fn test_julianday_rfc3339_half_hour_offset() {
1379 let base = julianday_float("2026-04-07 16:00:00");
1381 let expected = base - 5.5 / 24.0;
1382 assert_jdn_close(
1383 julianday_float("2026-04-07T16:00:00+05:30"),
1384 expected,
1385 "+05:30",
1386 );
1387 }
1388
1389 #[test]
1390 fn test_julianday_rfc3339_compact_offsets() {
1391 let base = julianday_float("2026-04-07 16:00:00");
1393 assert_jdn_close(
1394 julianday_float("2026-04-07T16:00:00+0100"),
1395 base - 1.0 / 24.0,
1396 "+0100",
1397 );
1398 assert_jdn_close(
1399 julianday_float("2026-04-07T16:00:00-0530"),
1400 base + 5.5 / 24.0,
1401 "-0530",
1402 );
1403 assert_jdn_close(
1404 julianday_float("2026-04-07T16:00:00+09"),
1405 base - 9.0 / 24.0,
1406 "+09",
1407 );
1408 }
1409
1410 #[test]
1411 fn test_julianday_rfc3339_fractional_seconds_with_tz() {
1412 let base = julianday_float("2026-04-07 16:00:00.500");
1414 assert_jdn_close(
1415 julianday_float("2026-04-07T16:00:00.500Z"),
1416 base,
1417 "fractional + Z",
1418 );
1419 assert_jdn_close(
1420 julianday_float("2026-04-07T16:00:00.500+01:00"),
1421 base - 1.0 / 24.0,
1422 "fractional + +01:00",
1423 );
1424 }
1425
1426 #[test]
1427 fn test_date_and_time_rfc3339_round_trip() {
1428 assert_text(
1431 &DateFunc
1432 .invoke(&[text("2026-04-07T16:00:00+05:00")])
1433 .unwrap(),
1434 "2026-04-07",
1436 );
1437 assert_text(
1438 &TimeFunc
1439 .invoke(&[text("2026-04-07T16:00:00+05:00")])
1440 .unwrap(),
1441 "11:00:00",
1442 );
1443 assert_text(
1444 &DateTimeFunc
1445 .invoke(&[text("2026-04-07T16:00:00+05:00")])
1446 .unwrap(),
1447 "2026-04-07 11:00:00",
1448 );
1449 }
1450
1451 #[test]
1452 fn test_julianday_rfc3339_invalid_offsets_return_null() {
1453 for bad in &[
1455 "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", ] {
1460 let result = JuliandayFunc.invoke(&[text(bad)]).unwrap();
1461 assert_eq!(
1462 result,
1463 SqliteValue::Null,
1464 "expected NULL for malformed offset {bad:?}, got {result:?}"
1465 );
1466 }
1467 }
1468
1469 #[test]
1470 fn test_julianday_rejects_malformed_time_fields() {
1471 for bad in &[
1475 "+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", ] {
1487 let result = JuliandayFunc.invoke(&[text(bad)]).unwrap();
1488 assert_eq!(
1489 result,
1490 SqliteValue::Null,
1491 "expected NULL for signed time field {bad:?}, got {result:?}"
1492 );
1493 }
1494 }
1495
1496 #[test]
1497 fn test_unixepoch_basic() {
1498 let r = UnixepochFunc
1499 .invoke(&[text("1970-01-01 00:00:00")])
1500 .unwrap();
1501 assert_eq!(r, int(0));
1502 }
1503
1504 #[test]
1505 fn test_unixepoch_known_date() {
1506 let r = UnixepochFunc
1507 .invoke(&[text("2024-01-01 00:00:00")])
1508 .unwrap();
1509 assert_eq!(r, int(1_704_067_200));
1511 }
1512
1513 #[test]
1516 fn test_modifier_days() {
1517 let r = DateFunc
1518 .invoke(&[text("2024-01-15"), text("+10 days")])
1519 .unwrap();
1520 assert_text(&r, "2024-01-25");
1521 }
1522
1523 #[test]
1524 fn test_modifier_months() {
1525 let r = DateFunc
1528 .invoke(&[text("2024-01-31"), text("+1 months")])
1529 .unwrap();
1530 assert_text(&r, "2024-03-02");
1531 }
1532
1533 #[test]
1534 fn test_modifier_years() {
1535 let r = DateFunc
1538 .invoke(&[text("2024-02-29"), text("+1 years")])
1539 .unwrap();
1540 assert_text(&r, "2025-03-01");
1541 }
1542
1543 #[test]
1544 fn test_modifier_hours() {
1545 let r = DateTimeFunc
1546 .invoke(&[text("2024-01-01 23:00:00"), text("+2 hours")])
1547 .unwrap();
1548 assert_text(&r, "2024-01-02 01:00:00");
1549 }
1550
1551 #[test]
1552 fn test_modifier_start_of_month() {
1553 let r = DateFunc
1554 .invoke(&[text("2024-03-15"), text("start of month")])
1555 .unwrap();
1556 assert_text(&r, "2024-03-01");
1557 }
1558
1559 #[test]
1560 fn test_modifier_start_of_year() {
1561 let r = DateFunc
1562 .invoke(&[text("2024-06-15"), text("start of year")])
1563 .unwrap();
1564 assert_text(&r, "2024-01-01");
1565 }
1566
1567 #[test]
1568 fn test_modifier_start_of_day() {
1569 let r = DateTimeFunc
1570 .invoke(&[text("2024-03-15 14:30:00"), text("start of day")])
1571 .unwrap();
1572 assert_text(&r, "2024-03-15 00:00:00");
1573 }
1574
1575 #[test]
1576 fn test_modifier_unixepoch() {
1577 let r = DateTimeFunc.invoke(&[int(0), text("unixepoch")]).unwrap();
1578 assert_text(&r, "1970-01-01 00:00:00");
1579 }
1580
1581 #[test]
1582 fn test_modifier_weekday() {
1583 let r = DateFunc
1585 .invoke(&[text("2024-03-15"), text("weekday 0")])
1586 .unwrap();
1587 assert_text(&r, "2024-03-17");
1588 }
1589
1590 #[test]
1591 fn test_modifier_auto_unixepoch() {
1592 let ts = int(1_710_531_045);
1593 let r = DateTimeFunc.invoke(&[ts.clone(), text("auto")]).unwrap();
1594 let expected = DateTimeFunc.invoke(&[ts, text("unixepoch")]).unwrap();
1595 assert_eq!(
1596 r, expected,
1597 "auto and unixepoch should agree for unix-like values"
1598 );
1599 }
1600
1601 #[test]
1602 fn test_modifier_auto_julian_day() {
1603 let r = DateFunc
1604 .invoke(&[float(2_460_384.5), text("auto")])
1605 .unwrap();
1606 assert_text(&r, "2024-03-15");
1607 }
1608
1609 #[test]
1610 fn test_modifier_localtime_utc_roundtrip() {
1611 let r = DateTimeFunc
1613 .invoke(&[text("2024-03-15 14:30:45"), text("localtime"), text("utc")])
1614 .unwrap();
1615 assert_text(&r, "2024-03-15 14:30:45");
1616 }
1617
1618 #[test]
1619 fn test_modifier_localtime_shifts_value() {
1620 let offset = utc_offset_for_utc_jdn(ymdhms_to_jdn(2024, 3, 15, 12, 0, 0, 0.0));
1622 if offset != 0 {
1623 let r = DateTimeFunc
1624 .invoke(&[text("2024-03-15 12:00:00"), text("localtime")])
1625 .unwrap();
1626 let shifted = match &r {
1628 SqliteValue::Text(s) => s.clone(),
1629 _ => panic!("expected text"),
1630 };
1631 assert_ne!(&*shifted, "2024-03-15 12:00:00");
1632 }
1633 }
1634
1635 #[test]
1636 fn test_modifier_auto_out_of_range_returns_null() {
1637 let r = DateTimeFunc.invoke(&[float(1.0e20), text("auto")]).unwrap();
1638 assert_eq!(r, SqliteValue::Null);
1639 }
1640
1641 #[test]
1642 fn test_modifier_order_matters() {
1643 let r1 = DateFunc
1645 .invoke(&[text("2024-03-15"), text("start of month"), text("+1 days")])
1646 .unwrap();
1647 assert_text(&r1, "2024-03-02");
1648
1649 let r2 = DateFunc
1651 .invoke(&[text("2024-03-15"), text("+1 days"), text("start of month")])
1652 .unwrap();
1653 assert_text(&r2, "2024-03-01");
1654 }
1655
1656 #[test]
1657 fn test_modifier_weekday_same_day_is_noop() {
1658 let r = DateFunc
1660 .invoke(&[text("2024-03-17"), text("weekday 0")])
1661 .unwrap();
1662 assert_text(&r, "2024-03-17");
1663 }
1664
1665 #[test]
1668 fn test_bare_time_defaults() {
1669 let r = DateFunc.invoke(&[text("12:30:00")]).unwrap();
1670 assert_text(&r, "2000-01-01");
1671 }
1672
1673 #[test]
1674 fn test_t_separator() {
1675 let r = DateTimeFunc.invoke(&[text("2024-03-15T14:30:00")]).unwrap();
1676 assert_text(&r, "2024-03-15 14:30:00");
1677 }
1678
1679 #[test]
1680 fn test_julian_day_input() {
1681 let r = DateFunc.invoke(&[float(2_460_384.5)]).unwrap();
1683 assert_text(&r, "2024-03-15");
1684 }
1685
1686 #[test]
1687 fn test_null_input() {
1688 assert_eq!(DateFunc.invoke(&[null()]).unwrap(), SqliteValue::Null);
1689 }
1690
1691 #[test]
1692 fn test_invalid_input() {
1693 assert_eq!(
1694 DateFunc.invoke(&[text("not-a-date")]).unwrap(),
1695 SqliteValue::Null
1696 );
1697 }
1698
1699 #[test]
1700 fn test_negative_time_component_invalid() {
1701 let r = TimeFunc.invoke(&[text("-01:00")]).unwrap();
1702 assert_eq!(r, SqliteValue::Null);
1703 }
1704
1705 #[test]
1708 fn test_leap_year() {
1709 let r = DateFunc
1710 .invoke(&[text("2024-02-28"), text("+1 days")])
1711 .unwrap();
1712 assert_text(&r, "2024-02-29");
1713 }
1714
1715 #[test]
1716 fn test_non_leap_year() {
1717 let r = DateFunc
1718 .invoke(&[text("2023-02-28"), text("+1 days")])
1719 .unwrap();
1720 assert_text(&r, "2023-03-01");
1721 }
1722
1723 #[test]
1726 fn test_strftime_basic() {
1727 let r = StrftimeFunc
1728 .invoke(&[text("%Y-%m-%d"), text("2024-03-15")])
1729 .unwrap();
1730 assert_text(&r, "2024-03-15");
1731 }
1732
1733 #[test]
1734 fn test_strftime_time_specifiers() {
1735 let r = StrftimeFunc
1736 .invoke(&[text("%H:%M:%S"), text("2024-03-15 14:30:45")])
1737 .unwrap();
1738 assert_text(&r, "14:30:45");
1739 }
1740
1741 #[test]
1742 fn test_strftime_unix_seconds() {
1743 let r = StrftimeFunc
1744 .invoke(&[text("%s"), text("1970-01-01 00:00:00")])
1745 .unwrap();
1746 assert_text(&r, "0");
1747 }
1748
1749 #[test]
1750 fn test_strftime_day_of_year() {
1751 let r = StrftimeFunc
1752 .invoke(&[text("%j"), text("2024-03-15")])
1753 .unwrap();
1754 assert_text(&r, "075");
1756 }
1757
1758 #[test]
1759 fn test_strftime_day_of_week() {
1760 let r = StrftimeFunc
1762 .invoke(&[text("%w"), text("2024-03-15")])
1763 .unwrap();
1764 assert_text(&r, "5");
1765
1766 let r = StrftimeFunc
1767 .invoke(&[text("%u"), text("2024-03-15")])
1768 .unwrap();
1769 assert_text(&r, "5");
1770 }
1771
1772 #[test]
1773 fn test_strftime_12hour() {
1774 let r = StrftimeFunc
1775 .invoke(&[text("%I %p"), text("2024-03-15 14:30:00")])
1776 .unwrap();
1777 assert_text(&r, "02 PM");
1778
1779 let r = StrftimeFunc
1780 .invoke(&[text("%I %P"), text("2024-03-15 09:30:00")])
1781 .unwrap();
1782 assert_text(&r, "09 am");
1783 }
1784
1785 #[test]
1786 fn test_strftime_all_specifiers_presence() {
1787 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|%%";
1788 let r = StrftimeFunc
1789 .invoke(&[text(fmt), text("2024-03-15 14:30:45.123")])
1790 .unwrap();
1791
1792 let s = match r {
1793 SqliteValue::Text(v) => v,
1794 other => panic!("expected Text, got {other:?}"),
1795 };
1796 let parts: Vec<&str> = s.split('|').collect();
1797 assert_eq!(parts.len(), 25, "unexpected specifier output: {s}");
1798 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!(
1805 parts[6].parse::<f64>().is_ok(),
1806 "expected numeric %J output, got {}",
1807 parts[6]
1808 );
1809 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!(
1817 parts[14].parse::<i64>().is_ok(),
1818 "expected numeric %s output, got {}",
1819 parts[14]
1820 );
1821 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], "%"); }
1832
1833 #[test]
1834 fn test_strftime_null() {
1835 assert_eq!(
1836 StrftimeFunc.invoke(&[null(), text("2024-01-01")]).unwrap(),
1837 SqliteValue::Null
1838 );
1839 assert_eq!(
1840 StrftimeFunc.invoke(&[text("%Y"), null()]).unwrap(),
1841 SqliteValue::Null
1842 );
1843 }
1844
1845 #[test]
1846 #[ignore = "perf-only benchmark"]
1847 fn perf_strftime_timestamp_rows() {
1848 use std::hint::black_box;
1849 use std::time::Instant;
1850
1851 const ROWS: usize = 200_000;
1852 const REPEATS: usize = 5;
1853 const FORMAT: &str = "%Y-%m-%d %H:%M:%S";
1854 const INPUT: &str = "2024-03-15 14:30:45";
1855
1856 let func = StrftimeFunc;
1857 let fmt = text(FORMAT);
1858 let input = text(INPUT);
1859 let mut best_ns = u128::MAX;
1860 let mut output_len = 0usize;
1861
1862 for _ in 0..REPEATS {
1863 let started = Instant::now();
1864 for _ in 0..ROWS {
1865 let result = black_box(
1866 func.invoke(black_box(&[fmt.clone(), input.clone()]))
1867 .expect("strftime benchmark invocation must succeed"),
1868 );
1869 output_len = match result {
1870 SqliteValue::Text(text) => text.len(),
1871 SqliteValue::Null
1872 | SqliteValue::Integer(_)
1873 | SqliteValue::Float(_)
1874 | SqliteValue::Blob(_) => 0,
1875 };
1876 }
1877 let elapsed_ns = started.elapsed().as_nanos();
1878 if elapsed_ns < best_ns {
1879 best_ns = elapsed_ns;
1880 }
1881 }
1882
1883 println!(
1884 "strftime_timestamp_rows rows={ROWS} repeats={REPEATS} best_ns={best_ns} output_len={output_len}"
1885 );
1886 }
1887
1888 #[test]
1891 fn test_timediff_basic() {
1892 let r = TimediffFunc
1893 .invoke(&[text("2024-03-15"), text("2024-03-10")])
1894 .unwrap();
1895 assert_text(&r, "+0000-00-05 00:00:00.000");
1896 }
1897
1898 #[test]
1899 fn test_timediff_negative() {
1900 let r = TimediffFunc
1901 .invoke(&[text("2024-03-10"), text("2024-03-15")])
1902 .unwrap();
1903 assert_text(&r, "-0000-00-05 00:00:00.000");
1904 }
1905
1906 #[test]
1907 fn test_timediff_year_boundary() {
1908 let r = TimediffFunc
1909 .invoke(&[text("2024-01-01 01:00:00"), text("2023-12-31 23:00:00")])
1910 .unwrap();
1911 assert_text(&r, "+0000-00-00 02:00:00.000");
1912 }
1913
1914 #[test]
1917 fn test_modifier_subsec() {
1918 let r = TimeFunc
1919 .invoke(&[text("2024-01-01 12:00:00.123"), text("subsec")])
1920 .unwrap();
1921 match &r {
1922 SqliteValue::Text(s) => assert!(
1923 s.contains('.'),
1924 "expected fractional seconds with subsec: {s}"
1925 ),
1926 other => panic!("expected Text, got {other:?}"),
1927 }
1928 }
1929
1930 #[test]
1933 fn test_register_datetime_builtins_all_present() {
1934 let mut reg = FunctionRegistry::new();
1935 register_datetime_builtins(&mut reg);
1936
1937 let expected = [
1938 "date",
1939 "time",
1940 "datetime",
1941 "julianday",
1942 "unixepoch",
1943 "strftime",
1944 "timediff",
1945 ];
1946
1947 for name in expected {
1948 assert!(
1949 reg.find_scalar(name, 1).is_some() || reg.find_scalar(name, 2).is_some(),
1950 "datetime function '{name}' not registered"
1951 );
1952 }
1953 }
1954
1955 #[test]
1958 fn test_modifier_year_overflow() {
1959 let huge = i64::MAX;
1962 let modifier = format!("+{huge} years");
1963 let r = DateFunc.invoke(&[text("2000-01-01"), text(&modifier)]);
1964 assert_eq!(r.unwrap(), SqliteValue::Null);
1967 }
1968
1969 #[test]
1970 fn test_jdn_roundtrip() {
1971 let dates = [
1973 (2024, 3, 15),
1974 (2000, 1, 1),
1975 (1970, 1, 1),
1976 (2024, 2, 29),
1977 (1900, 1, 1),
1978 (2099, 12, 31),
1979 ];
1980 for (y, m, d) in dates {
1981 let jdn = ymd_to_jdn(y, m, d);
1982 let (y2, m2, d2) = jdn_to_ymd(jdn);
1983 assert_eq!(
1984 (y, m, d),
1985 (y2, m2, d2),
1986 "roundtrip failed for {y}-{m}-{d} (JDN={jdn})"
1987 );
1988 }
1989 }
1990
1991 #[test]
1992 fn test_unix_epoch_roundtrip() {
1993 let jdn = ymd_to_jdn(1970, 1, 1);
1994 let unix = jdn_to_unix(jdn);
1995 assert_eq!(unix, 0, "Unix epoch should be 0");
1996
1997 let jdn2 = unix_to_jdn(0.0);
1998 assert!((jdn2 - UNIX_EPOCH_JDN).abs() < 1e-10, "roundtrip failed");
1999 }
2000}