qail_pg/types/
temporal.rs

1//! Timestamp type conversions for PostgreSQL.
2//!
3//! PostgreSQL timestamps are stored as microseconds since 2000-01-01 00:00:00 UTC.
4
5use super::{FromPg, ToPg, TypeError};
6use crate::protocol::types::oid;
7
8/// PostgreSQL epoch: 2000-01-01 00:00:00 UTC
9/// Difference from Unix epoch (1970-01-01) in microseconds
10const PG_EPOCH_OFFSET_USEC: i64 = 946_684_800_000_000;
11
12/// Timestamp without timezone (microseconds since 2000-01-01)
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct Timestamp {
15    /// Microseconds since PostgreSQL epoch (2000-01-01 00:00:00)
16    pub usec: i64,
17}
18
19impl Timestamp {
20    /// Create from microseconds since PostgreSQL epoch
21    pub fn from_pg_usec(usec: i64) -> Self {
22        Self { usec }
23    }
24
25    /// Create from Unix timestamp (seconds since 1970-01-01)
26    pub fn from_unix_secs(secs: i64) -> Self {
27        Self {
28            usec: secs * 1_000_000 - PG_EPOCH_OFFSET_USEC,
29        }
30    }
31
32    /// Convert to Unix timestamp (seconds since 1970-01-01)
33    pub fn to_unix_secs(&self) -> i64 {
34        (self.usec + PG_EPOCH_OFFSET_USEC) / 1_000_000
35    }
36
37    /// Convert to Unix timestamp with microseconds
38    pub fn to_unix_usec(&self) -> i64 {
39        self.usec + PG_EPOCH_OFFSET_USEC
40    }
41}
42
43impl FromPg for Timestamp {
44    fn from_pg(bytes: &[u8], oid_val: u32, format: i16) -> Result<Self, TypeError> {
45        if oid_val != oid::TIMESTAMP && oid_val != oid::TIMESTAMPTZ {
46            return Err(TypeError::UnexpectedOid {
47                expected: "timestamp",
48                got: oid_val,
49            });
50        }
51
52        if format == 1 {
53            // Binary: 8 bytes, microseconds since 2000-01-01
54            if bytes.len() != 8 {
55                return Err(TypeError::InvalidData(
56                    "Expected 8 bytes for timestamp".to_string(),
57                ));
58            }
59            let usec = i64::from_be_bytes([
60                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
61            ]);
62            Ok(Timestamp::from_pg_usec(usec))
63        } else {
64            // Text format: parse ISO 8601
65            let s =
66                std::str::from_utf8(bytes).map_err(|e| TypeError::InvalidData(e.to_string()))?;
67            parse_timestamp_text(s)
68        }
69    }
70}
71
72impl ToPg for Timestamp {
73    fn to_pg(&self) -> (Vec<u8>, u32, i16) {
74        (self.usec.to_be_bytes().to_vec(), oid::TIMESTAMP, 1)
75    }
76}
77
78/// Parse PostgreSQL text timestamp format
79fn parse_timestamp_text(s: &str) -> Result<Timestamp, TypeError> {
80    // Format: "2024-12-25 17:30:00" or "2024-12-25 17:30:00.123456"
81    // This is a simplified parser - production would use chrono or time crate
82
83    let parts: Vec<&str> = s.split(&[' ', 'T'][..]).collect();
84    if parts.len() < 2 {
85        return Err(TypeError::InvalidData(format!("Invalid timestamp: {}", s)));
86    }
87
88    let date_parts: Vec<i32> = parts[0].split('-').filter_map(|p| p.parse().ok()).collect();
89
90    if date_parts.len() != 3 {
91        return Err(TypeError::InvalidData(format!(
92            "Invalid date: {}",
93            parts[0]
94        )));
95    }
96
97    let time_str =
98        parts[1].trim_end_matches(|c: char| c == '+' || c == '-' || c.is_ascii_digit() || c == ':');
99    let time_parts: Vec<&str> = time_str.split(':').collect();
100
101    let hour: i32 = time_parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
102    let minute: i32 = time_parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
103    let second_str = time_parts.get(2).unwrap_or(&"0");
104    let sec_parts: Vec<&str> = second_str.split('.').collect();
105    let second: i32 = sec_parts.first().and_then(|s| s.parse().ok()).unwrap_or(0);
106    let usec: i64 = sec_parts
107        .get(1)
108        .map(|s| {
109            let padded = format!("{:0<6}", s);
110            padded[..6].parse::<i64>().unwrap_or(0)
111        })
112        .unwrap_or(0);
113
114    // Calculate days since 2000-01-01
115    let year = date_parts[0];
116    let month = date_parts[1];
117    let day = date_parts[2];
118
119    // Simplified calculation (not accounting for all leap years correctly)
120    let days_since_epoch = days_from_ymd(year, month, day);
121
122    let total_usec = days_since_epoch as i64 * 86_400_000_000
123        + hour as i64 * 3_600_000_000
124        + minute as i64 * 60_000_000
125        + second as i64 * 1_000_000
126        + usec;
127
128    Ok(Timestamp::from_pg_usec(total_usec))
129}
130
131/// Calculate days since 2000-01-01
132fn days_from_ymd(year: i32, month: i32, day: i32) -> i32 {
133    // Days from 2000-01-01 to given date
134    let mut days = 0;
135
136    // Years
137    for y in 2000..year {
138        days += if is_leap_year(y) { 366 } else { 365 };
139    }
140    for y in year..2000 {
141        days -= if is_leap_year(y) { 366 } else { 365 };
142    }
143
144    // Months
145    let days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
146    for m in 1..month {
147        days += days_in_month[(m - 1) as usize];
148        if m == 2 && is_leap_year(year) {
149            days += 1;
150        }
151    }
152
153    // Days
154    days += day - 1;
155
156    days
157}
158
159fn is_leap_year(year: i32) -> bool {
160    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
161}
162
163/// Date type (days since 2000-01-01)
164#[derive(Debug, Clone, Copy, PartialEq, Eq)]
165pub struct Date {
166    pub days: i32,
167}
168
169impl FromPg for Date {
170    fn from_pg(bytes: &[u8], oid_val: u32, format: i16) -> Result<Self, TypeError> {
171        if oid_val != oid::DATE {
172            return Err(TypeError::UnexpectedOid {
173                expected: "date",
174                got: oid_val,
175            });
176        }
177
178        if format == 1 {
179            // Binary: 4 bytes, days since 2000-01-01
180            if bytes.len() != 4 {
181                return Err(TypeError::InvalidData(
182                    "Expected 4 bytes for date".to_string(),
183                ));
184            }
185            let days = i32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
186            Ok(Date { days })
187        } else {
188            // Text format: YYYY-MM-DD
189            let s =
190                std::str::from_utf8(bytes).map_err(|e| TypeError::InvalidData(e.to_string()))?;
191            let parts: Vec<i32> = s.split('-').filter_map(|p| p.parse().ok()).collect();
192            if parts.len() != 3 {
193                return Err(TypeError::InvalidData(format!("Invalid date: {}", s)));
194            }
195            Ok(Date {
196                days: days_from_ymd(parts[0], parts[1], parts[2]),
197            })
198        }
199    }
200}
201
202impl ToPg for Date {
203    fn to_pg(&self) -> (Vec<u8>, u32, i16) {
204        (self.days.to_be_bytes().to_vec(), oid::DATE, 1)
205    }
206}
207
208/// Time type (microseconds since midnight)
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210pub struct Time {
211    /// Microseconds since midnight
212    pub usec: i64,
213}
214
215impl Time {
216    /// Create from hours, minutes, seconds, microseconds
217    pub fn new(hour: u8, minute: u8, second: u8, usec: u32) -> Self {
218        Self {
219            usec: hour as i64 * 3_600_000_000
220                + minute as i64 * 60_000_000
221                + second as i64 * 1_000_000
222                + usec as i64,
223        }
224    }
225
226    /// Get hours component (0-23)
227    pub fn hour(&self) -> u8 {
228        ((self.usec / 3_600_000_000) % 24) as u8
229    }
230
231    /// Get minutes component (0-59)
232    pub fn minute(&self) -> u8 {
233        ((self.usec / 60_000_000) % 60) as u8
234    }
235
236    /// Get seconds component (0-59)
237    pub fn second(&self) -> u8 {
238        ((self.usec / 1_000_000) % 60) as u8
239    }
240
241    /// Get microseconds component (0-999999)
242    pub fn microsecond(&self) -> u32 {
243        (self.usec % 1_000_000) as u32
244    }
245}
246
247impl FromPg for Time {
248    fn from_pg(bytes: &[u8], oid_val: u32, format: i16) -> Result<Self, TypeError> {
249        if oid_val != oid::TIME {
250            return Err(TypeError::UnexpectedOid {
251                expected: "time",
252                got: oid_val,
253            });
254        }
255
256        if format == 1 {
257            // Binary: 8 bytes, microseconds since midnight
258            if bytes.len() != 8 {
259                return Err(TypeError::InvalidData(
260                    "Expected 8 bytes for time".to_string(),
261                ));
262            }
263            let usec = i64::from_be_bytes([
264                bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
265            ]);
266            Ok(Time { usec })
267        } else {
268            // Text format: HH:MM:SS or HH:MM:SS.ffffff
269            let s =
270                std::str::from_utf8(bytes).map_err(|e| TypeError::InvalidData(e.to_string()))?;
271            parse_time_text(s)
272        }
273    }
274}
275
276impl ToPg for Time {
277    fn to_pg(&self) -> (Vec<u8>, u32, i16) {
278        (self.usec.to_be_bytes().to_vec(), oid::TIME, 1)
279    }
280}
281
282/// Parse PostgreSQL text time format
283fn parse_time_text(s: &str) -> Result<Time, TypeError> {
284    let parts: Vec<&str> = s.split(':').collect();
285    if parts.len() < 2 {
286        return Err(TypeError::InvalidData(format!("Invalid time: {}", s)));
287    }
288
289    let hour: i64 = parts[0]
290        .parse()
291        .map_err(|_| TypeError::InvalidData("Invalid hour".to_string()))?;
292    let minute: i64 = parts[1]
293        .parse()
294        .map_err(|_| TypeError::InvalidData("Invalid minute".to_string()))?;
295
296    let (second, usec) = if parts.len() > 2 {
297        let sec_parts: Vec<&str> = parts[2].split('.').collect();
298        let sec: i64 = sec_parts[0].parse().unwrap_or(0);
299        let us: i64 = sec_parts
300            .get(1)
301            .map(|s| {
302                let padded = format!("{:0<6}", s);
303                padded[..6].parse::<i64>().unwrap_or(0)
304            })
305            .unwrap_or(0);
306        (sec, us)
307    } else {
308        (0, 0)
309    };
310
311    Ok(Time {
312        usec: hour * 3_600_000_000 + minute * 60_000_000 + second * 1_000_000 + usec,
313    })
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    #[test]
321    fn test_timestamp_unix_conversion() {
322        // 2024-01-01 00:00:00 UTC
323        let ts = Timestamp::from_unix_secs(1704067200);
324        let back = ts.to_unix_secs();
325        assert_eq!(back, 1704067200);
326    }
327
328    #[test]
329    fn test_timestamp_from_pg_binary() {
330        // Some arbitrary timestamp in binary
331        let usec: i64 = 789_012_345_678_900; // ~25 years after 2000
332        let bytes = usec.to_be_bytes();
333        let ts = Timestamp::from_pg(&bytes, oid::TIMESTAMP, 1).unwrap();
334        assert_eq!(ts.usec, usec);
335    }
336
337    #[test]
338    fn test_date_from_pg_binary() {
339        // 2024-01-01 = 8766 days since 2000-01-01
340        let days: i32 = 8766;
341        let bytes = days.to_be_bytes();
342        let date = Date::from_pg(&bytes, oid::DATE, 1).unwrap();
343        assert_eq!(date.days, days);
344    }
345
346    #[test]
347    fn test_time_from_pg_binary() {
348        // 12:30:45.123456 = 45045123456 microseconds
349        let usec: i64 = 12 * 3_600_000_000 + 30 * 60_000_000 + 45 * 1_000_000 + 123456;
350        let bytes = usec.to_be_bytes();
351        let time = Time::from_pg(&bytes, oid::TIME, 1).unwrap();
352        assert_eq!(time.hour(), 12);
353        assert_eq!(time.minute(), 30);
354        assert_eq!(time.second(), 45);
355        assert_eq!(time.microsecond(), 123456);
356    }
357
358    #[test]
359    fn test_time_from_pg_text() {
360        let time = parse_time_text("14:30:00").unwrap();
361        assert_eq!(time.hour(), 14);
362        assert_eq!(time.minute(), 30);
363        assert_eq!(time.second(), 0);
364    }
365}