drasi-source-postgres 0.1.12

PostgreSQL source plugin for Drasi
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
// Copyright 2025 The Drasi Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use anyhow::{anyhow, Result};
use byteorder::{BigEndian, ReadBytesExt};
use chrono::{DateTime, NaiveDateTime, Utc};
use log::{debug, warn};
use postgres_types::Oid;
use rust_decimal::Decimal;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::io::{Cursor, Read};
use std::sync::Arc;
use uuid::Uuid;

use super::types::{
    ColumnInfo, PostgresValue, RelationInfo, ReplicaIdentity, TransactionInfo, WalMessage,
};

#[allow(dead_code)]
const PGOUTPUT_VERSION: u32 = 1;

pub struct PgOutputDecoder {
    relations: HashMap<u32, RelationInfo>,
    current_transaction: Option<TransactionInfo>,
}

impl Default for PgOutputDecoder {
    fn default() -> Self {
        Self::new()
    }
}

impl PgOutputDecoder {
    pub fn new() -> Self {
        Self {
            relations: HashMap::new(),
            current_transaction: None,
        }
    }

    pub fn decode_message(&mut self, data: &[u8]) -> Result<Option<WalMessage>> {
        if data.is_empty() {
            return Ok(None);
        }

        let msg_type = data[0];
        let payload = &data[1..];

        match msg_type {
            b'B' => self.decode_begin(payload),
            b'C' => self.decode_commit(payload),
            b'O' => self.decode_origin(payload),
            b'R' => self.decode_relation(payload),
            b'Y' => self.decode_type(payload),
            b'I' => self.decode_insert(payload),
            b'U' => self.decode_update(payload),
            b'D' => self.decode_delete(payload),
            b'T' => self.decode_truncate(payload),
            b'M' => self.decode_message_logical(payload),
            _ => {
                warn!("Unknown pgoutput message type: 0x{msg_type:02x}");
                Ok(None)
            }
        }
    }

    fn decode_begin(&mut self, data: &[u8]) -> Result<Option<WalMessage>> {
        let mut cursor = Cursor::new(data);

        let final_lsn = cursor.read_u64::<BigEndian>()?;
        let commit_timestamp = cursor.read_i64::<BigEndian>()?;
        let xid = cursor.read_u32::<BigEndian>()?;

        // Convert PostgreSQL timestamp to DateTime
        let timestamp = postgres_epoch_to_datetime(commit_timestamp)?;

        let transaction = TransactionInfo {
            xid,
            commit_lsn: final_lsn,
            commit_timestamp: timestamp,
        };

        self.current_transaction = Some(transaction.clone());

        debug!("Begin transaction: xid={xid}, lsn={final_lsn:x}");
        Ok(Some(WalMessage::Begin(transaction)))
    }

    fn decode_commit(&mut self, data: &[u8]) -> Result<Option<WalMessage>> {
        let mut cursor = Cursor::new(data);

        let _flags = cursor.read_u8()?;
        let commit_lsn = cursor.read_u64::<BigEndian>()?;
        let _end_lsn = cursor.read_u64::<BigEndian>()?;
        let commit_timestamp = cursor.read_i64::<BigEndian>()?;

        let timestamp = postgres_epoch_to_datetime(commit_timestamp)?;

        let transaction = TransactionInfo {
            xid: self
                .current_transaction
                .as_ref()
                .map(|t| t.xid)
                .unwrap_or(0),
            commit_lsn,
            commit_timestamp: timestamp,
        };

        self.current_transaction = None;

        debug!("Commit transaction: lsn={commit_lsn:x}");
        Ok(Some(WalMessage::Commit(transaction)))
    }

    fn decode_origin(&mut self, _data: &[u8]) -> Result<Option<WalMessage>> {
        // Origin messages are informational, we can skip them for now
        Ok(None)
    }

    fn decode_relation(&mut self, data: &[u8]) -> Result<Option<WalMessage>> {
        let mut cursor = Cursor::new(data);

        let relation_id = cursor.read_u32::<BigEndian>()?;
        let namespace = read_cstring(&mut cursor)?;
        let name = read_cstring(&mut cursor)?;
        let replica_identity = match cursor.read_u8()? {
            b'd' => ReplicaIdentity::Default,
            b'n' => ReplicaIdentity::Nothing,
            b'f' => ReplicaIdentity::Full,
            b'i' => ReplicaIdentity::Index,
            other => {
                warn!("Unknown replica identity: {}", other as char);
                ReplicaIdentity::Default
            }
        };

        let column_count = cursor.read_u16::<BigEndian>()?;
        let mut columns = Vec::with_capacity(column_count as usize);

        for _ in 0..column_count {
            let flags = cursor.read_u8()?;
            let is_key = (flags & 1) != 0;
            let column_name = read_cstring(&mut cursor)?;
            let type_oid = cursor.read_u32::<BigEndian>()?;
            let type_modifier = cursor.read_i32::<BigEndian>()?;

            columns.push(ColumnInfo {
                name: column_name,
                type_oid: Oid::from(type_oid),
                type_modifier,
                is_key,
            });
        }

        let relation = RelationInfo {
            id: relation_id,
            namespace,
            name: name.clone(),
            replica_identity,
            columns,
        };

        debug!(
            "Relation: id={}, namespace={}, name={}, columns={}",
            relation_id,
            relation.namespace,
            name,
            relation.columns.len()
        );

        self.relations.insert(relation_id, relation.clone());
        Ok(Some(WalMessage::Relation(relation)))
    }

    fn decode_type(&mut self, _data: &[u8]) -> Result<Option<WalMessage>> {
        // Type messages describe custom types, we'll handle them later if needed
        Ok(None)
    }

    fn decode_insert(&mut self, data: &[u8]) -> Result<Option<WalMessage>> {
        debug!("Decoding insert message, data length: {}", data.len());
        let mut cursor = Cursor::new(data);

        let relation_id = cursor.read_u32::<BigEndian>()?;
        let tuple_type = cursor.read_u8()?;

        debug!(
            "Insert: relation_id={}, tuple_type={}",
            relation_id, tuple_type as char
        );

        if tuple_type != b'N' {
            return Err(anyhow!(
                "Expected 'N' tuple type for insert, got: {tuple_type}"
            ));
        }

        let relation = self
            .relations
            .get(&relation_id)
            .ok_or_else(|| anyhow!("Unknown relation ID: {relation_id}"))?;

        debug!(
            "Insert for table: {}, expected columns: {}",
            relation.name,
            relation.columns.len()
        );
        let tuple = self.decode_tuple_data(&mut cursor, &relation.columns)?;

        debug!(
            "Insert: relation={}, columns={}",
            relation.name,
            tuple.len()
        );
        Ok(Some(WalMessage::Insert { relation_id, tuple }))
    }

    fn decode_update(&mut self, data: &[u8]) -> Result<Option<WalMessage>> {
        let mut cursor = Cursor::new(data);

        let relation_id = cursor.read_u32::<BigEndian>()?;
        let tuple_type = cursor.read_u8()?;

        let relation = self
            .relations
            .get(&relation_id)
            .ok_or_else(|| anyhow!("Unknown relation ID: {relation_id}"))?;

        let mut old_tuple = None;
        let new_tuple;

        match tuple_type {
            b'K' | b'O' => {
                // Has old tuple (key or old)
                old_tuple = Some(self.decode_tuple_data(&mut cursor, &relation.columns)?);
                let next_type = cursor.read_u8()?;
                if next_type != b'N' {
                    return Err(anyhow!("Expected 'N' after old tuple, got: {next_type}"));
                }
                new_tuple = self.decode_tuple_data(&mut cursor, &relation.columns)?;
            }
            b'N' => {
                // Only new tuple
                new_tuple = self.decode_tuple_data(&mut cursor, &relation.columns)?;
            }
            _ => {
                return Err(anyhow!("Unknown tuple type for update: {tuple_type}"));
            }
        }

        debug!(
            "Update: relation={}, has_old={}",
            relation.name,
            old_tuple.is_some()
        );
        Ok(Some(WalMessage::Update {
            relation_id,
            old_tuple,
            new_tuple,
        }))
    }

    fn decode_delete(&mut self, data: &[u8]) -> Result<Option<WalMessage>> {
        let mut cursor = Cursor::new(data);

        let relation_id = cursor.read_u32::<BigEndian>()?;
        let tuple_type = cursor.read_u8()?;

        if tuple_type != b'K' && tuple_type != b'O' {
            return Err(anyhow!(
                "Expected 'K' or 'O' tuple type for delete, got: {tuple_type}"
            ));
        }

        let relation = self
            .relations
            .get(&relation_id)
            .ok_or_else(|| anyhow!("Unknown relation ID: {relation_id}"))?;

        let old_tuple = self.decode_tuple_data(&mut cursor, &relation.columns)?;

        debug!("Delete: relation={}", relation.name);
        Ok(Some(WalMessage::Delete {
            relation_id,
            old_tuple,
        }))
    }

    fn decode_truncate(&mut self, data: &[u8]) -> Result<Option<WalMessage>> {
        let mut cursor = Cursor::new(data);

        let relation_count = cursor.read_u32::<BigEndian>()?;
        let _options = cursor.read_u8()?;

        let mut relation_ids = Vec::with_capacity(relation_count as usize);
        for _ in 0..relation_count {
            relation_ids.push(cursor.read_u32::<BigEndian>()?);
        }

        debug!("Truncate: {relation_count} relations");
        Ok(Some(WalMessage::Truncate { relation_ids }))
    }

    fn decode_message_logical(&mut self, _data: &[u8]) -> Result<Option<WalMessage>> {
        // Logical messages are application-specific, skip for now
        Ok(None)
    }

    fn decode_tuple_data(
        &self,
        cursor: &mut Cursor<&[u8]>,
        columns: &[ColumnInfo],
    ) -> Result<Vec<PostgresValue>> {
        let start_pos = cursor.position();
        let total_len = cursor.get_ref().len();
        debug!("decode_tuple_data: start position={start_pos}, total buffer length={total_len}");

        let column_count = cursor.read_u16::<BigEndian>()? as usize;
        debug!("Decoding {column_count} columns");

        if column_count != columns.len() {
            warn!(
                "Column count mismatch: expected {}, got {}",
                columns.len(),
                column_count
            );
        }

        let mut values = Vec::with_capacity(column_count);

        for i in 0..column_count {
            let column = columns
                .get(i)
                .ok_or_else(|| anyhow!("Column index out of bounds: {i}"))?;

            let tuple_type = cursor.read_u8()?;
            debug!(
                "Column {}: type={} ({}), oid={}",
                i, tuple_type as char, tuple_type, column.type_oid
            );

            let value = match tuple_type {
                b'n' => PostgresValue::Null,
                b'u' => PostgresValue::Null, // Unchanged TOAST value
                b't' => {
                    let length = cursor.read_u32::<BigEndian>()? as usize;
                    // Ensure we have enough data to read
                    let pos = cursor.position() as usize;
                    let available = cursor.get_ref().len() - pos;
                    debug!(
                        "Column {i} text value: length={length}, pos={pos}, available={available}"
                    );
                    if available < length {
                        return Err(anyhow!("Not enough data for column {} ({}): need {} bytes, have {} bytes at position {}", 
                            i, column.name, length, available, pos));
                    }
                    let mut data = vec![0u8; length];
                    cursor.read_exact(&mut data).map_err(|e| {
                        anyhow!(
                            "Failed to read {} bytes for column {} ({}): {}",
                            length,
                            i,
                            column.name,
                            e
                        )
                    })?;
                    debug!(
                        "Successfully read {} bytes for column {}, decoding type OID {}",
                        length, i, column.type_oid
                    );
                    self.decode_column_value(&data, column.type_oid)?
                }
                _ => {
                    return Err(anyhow!(
                        "Unknown tuple data type: {} ({})",
                        tuple_type as char,
                        tuple_type
                    ));
                }
            };

            values.push(value);
        }

        Ok(values)
    }

    fn decode_column_value(&self, data: &[u8], type_oid: Oid) -> Result<PostgresValue> {
        // Map common PostgreSQL type OIDs to decoders
        let oid_value = type_oid;
        match oid_value {
            16 => {
                // bool
                Ok(PostgresValue::Bool(data[0] != 0))
            }
            21 => {
                // int2
                if data.len() == 2 {
                    // Binary format
                    let mut cursor = Cursor::new(data);
                    Ok(PostgresValue::Int2(cursor.read_i16::<BigEndian>()?))
                } else {
                    // Text format
                    let text = String::from_utf8_lossy(data);
                    let value = text
                        .trim()
                        .parse::<i16>()
                        .map_err(|e| anyhow!("Failed to parse int2 from '{text}': {e}"))?;
                    Ok(PostgresValue::Int2(value))
                }
            }
            23 => {
                // int4
                if data.len() == 4 {
                    // Binary format
                    let mut cursor = Cursor::new(data);
                    Ok(PostgresValue::Int4(cursor.read_i32::<BigEndian>()?))
                } else {
                    // Text format - parse as string
                    let text = String::from_utf8_lossy(data);
                    let value = text
                        .trim()
                        .parse::<i32>()
                        .map_err(|e| anyhow!("Failed to parse int4 from '{text}': {e}"))?;
                    Ok(PostgresValue::Int4(value))
                }
            }
            20 => {
                // int8
                if data.len() == 8 {
                    // Binary format
                    let mut cursor = Cursor::new(data);
                    Ok(PostgresValue::Int8(cursor.read_i64::<BigEndian>()?))
                } else {
                    // Text format
                    let text = String::from_utf8_lossy(data);
                    let value = text
                        .trim()
                        .parse::<i64>()
                        .map_err(|e| anyhow!("Failed to parse int8 from '{text}': {e}"))?;
                    Ok(PostgresValue::Int8(value))
                }
            }
            700 => {
                // float4
                if data.len() == 4 {
                    // Binary format
                    let mut cursor = Cursor::new(data);
                    Ok(PostgresValue::Float4(cursor.read_f32::<BigEndian>()?))
                } else {
                    // Text format
                    let text = String::from_utf8_lossy(data);
                    let value = text
                        .trim()
                        .parse::<f32>()
                        .map_err(|e| anyhow!("Failed to parse float4 from '{text}': {e}"))?;
                    Ok(PostgresValue::Float4(value))
                }
            }
            701 => {
                // float8
                if data.len() == 8 {
                    // Binary format
                    let mut cursor = Cursor::new(data);
                    Ok(PostgresValue::Float8(cursor.read_f64::<BigEndian>()?))
                } else {
                    // Text format
                    let text = String::from_utf8_lossy(data);
                    let value = text
                        .trim()
                        .parse::<f64>()
                        .map_err(|e| anyhow!("Failed to parse float8 from '{text}': {e}"))?;
                    Ok(PostgresValue::Float8(value))
                }
            }
            1700 => {
                // numeric
                // Check if it's text format (pgoutput default) or binary format
                if data.len() < 8
                    || (!data.is_empty() && data[0] >= b'0' && data[0] <= b'9')
                    || (!data.is_empty() && (data[0] == b'-' || data[0] == b'+' || data[0] == b'.'))
                {
                    // Text format - parse as string
                    let text = String::from_utf8_lossy(data);
                    let value = Decimal::from_str_exact(text.trim())
                        .map_err(|e| anyhow!("Failed to parse numeric from '{text}': {e}"))?;
                    Ok(PostgresValue::Numeric(value))
                } else {
                    // Binary format
                    Ok(PostgresValue::Numeric(decode_numeric(data)?))
                }
            }
            25 | 1043 | 19 => {
                // text, varchar, name
                Ok(PostgresValue::Text(
                    String::from_utf8_lossy(data).to_string(),
                ))
            }
            1042 => {
                // char/bpchar
                let s = String::from_utf8_lossy(data).trim_end().to_string();
                Ok(PostgresValue::Char(s))
            }
            2950 => {
                // uuid
                if data.len() != 16 {
                    return Err(anyhow!("Invalid UUID length: {}", data.len()));
                }
                let uuid = Uuid::from_slice(data)?;
                Ok(PostgresValue::Uuid(uuid))
            }
            1114 => {
                // timestamp
                if data.len() == 8 {
                    // Binary format
                    let mut cursor = Cursor::new(data);
                    let micros = cursor.read_i64::<BigEndian>()?;
                    let timestamp = postgres_epoch_to_naive_datetime(micros)?;
                    Ok(PostgresValue::Timestamp(timestamp))
                } else {
                    // Text format - parse PostgreSQL timestamp string
                    let text = String::from_utf8_lossy(data);
                    let timestamp =
                        NaiveDateTime::parse_from_str(text.trim(), "%Y-%m-%d %H:%M:%S%.f")
                            .or_else(|_| {
                                NaiveDateTime::parse_from_str(text.trim(), "%Y-%m-%d %H:%M:%S")
                            })
                            .map_err(|e| anyhow!("Failed to parse timestamp from '{text}': {e}"))?;
                    Ok(PostgresValue::Timestamp(timestamp))
                }
            }
            1184 => {
                // timestamptz
                if data.len() == 8 {
                    // Binary format
                    let mut cursor = Cursor::new(data);
                    let micros = cursor.read_i64::<BigEndian>()?;
                    let timestamp = postgres_epoch_to_datetime(micros)?;
                    Ok(PostgresValue::TimestampTz(timestamp))
                } else {
                    // Text format - parse PostgreSQL timestamptz string
                    let text = String::from_utf8_lossy(data);
                    // PostgreSQL sends timestamptz in ISO 8601 format
                    let timestamp = DateTime::parse_from_rfc3339(text.trim())
                        .or_else(|_| {
                            DateTime::parse_from_str(text.trim(), "%Y-%m-%d %H:%M:%S%.f%z")
                        })
                        .map_err(|e| anyhow!("Failed to parse timestamptz from '{text}': {e}"))?
                        .with_timezone(&Utc);
                    Ok(PostgresValue::TimestampTz(timestamp))
                }
            }
            1082 => {
                // date
                let mut cursor = Cursor::new(data);
                let days = cursor.read_i32::<BigEndian>()?;
                let date = postgres_epoch_to_date(days)?;
                Ok(PostgresValue::Date(date))
            }
            1083 => {
                // time
                let mut cursor = Cursor::new(data);
                let micros = cursor.read_i64::<BigEndian>()?;
                let time = postgres_time_to_naive_time(micros)?;
                Ok(PostgresValue::Time(time))
            }
            114 | 3802 => {
                // json, jsonb
                let json_str = if oid_value == 3802 {
                    // jsonb has a version byte
                    String::from_utf8_lossy(&data[1..]).to_string()
                } else {
                    String::from_utf8_lossy(data).to_string()
                };
                let value: JsonValue = serde_json::from_str(&json_str)?;
                Ok(PostgresValue::Json(value))
            }
            17 => {
                // bytea
                Ok(PostgresValue::Bytea(data.to_vec()))
            }
            _ => {
                // Default to text representation for unknown types
                warn!("Unknown type OID {oid_value}, treating as text");
                Ok(PostgresValue::Text(
                    String::from_utf8_lossy(data).to_string(),
                ))
            }
        }
    }

    pub fn get_relation(&self, relation_id: u32) -> Option<&RelationInfo> {
        self.relations.get(&relation_id)
    }
}

fn read_cstring(cursor: &mut Cursor<&[u8]>) -> Result<String> {
    let mut buffer = Vec::new();
    loop {
        let byte = cursor.read_u8()?;
        if byte == 0 {
            break;
        }
        buffer.push(byte);
    }
    Ok(String::from_utf8_lossy(&buffer).to_string())
}

fn postgres_epoch_to_datetime(micros: i64) -> Result<DateTime<Utc>> {
    // PostgreSQL epoch is 2000-01-01 00:00:00
    const POSTGRES_EPOCH: i64 = 946684800000000; // microseconds since Unix epoch
    let unix_micros = micros + POSTGRES_EPOCH;
    let secs = unix_micros / 1_000_000;
    let nanos = ((unix_micros % 1_000_000) * 1000) as u32;

    DateTime::from_timestamp(secs, nanos).ok_or_else(|| anyhow!("Invalid timestamp"))
}

fn postgres_epoch_to_naive_datetime(micros: i64) -> Result<NaiveDateTime> {
    let dt = postgres_epoch_to_datetime(micros)?;
    Ok(dt.naive_utc())
}

fn postgres_epoch_to_date(days: i32) -> Result<chrono::NaiveDate> {
    // PostgreSQL date epoch is 2000-01-01
    const POSTGRES_DATE_EPOCH: i32 = 10957; // days since Unix epoch (1970-01-01)
    let unix_days = days + POSTGRES_DATE_EPOCH;

    let epoch =
        chrono::NaiveDate::from_ymd_opt(1970, 1, 1).ok_or_else(|| anyhow!("Invalid epoch date"))?;

    Ok(epoch + chrono::Duration::days(unix_days as i64))
}

fn postgres_time_to_naive_time(micros: i64) -> Result<chrono::NaiveTime> {
    let total_secs = micros / 1_000_000;
    let hours = (total_secs / 3600) as u32;
    let minutes = ((total_secs % 3600) / 60) as u32;
    let seconds = (total_secs % 60) as u32;
    let nanos = ((micros % 1_000_000) * 1000) as u32;

    chrono::NaiveTime::from_hms_nano_opt(hours, minutes, seconds, nanos)
        .ok_or_else(|| anyhow!("Invalid time"))
}

/// Decode a column value from text format (used by bootstrap)
pub fn decode_column_value_text(
    text: &str,
    type_oid: i32,
) -> Result<drasi_core::models::ElementValue> {
    use drasi_core::models::ElementValue;

    match type_oid as u32 {
        16 => {
            // bool
            let value = text.parse::<bool>().or_else(|_| match text {
                "t" => Ok(true),
                "f" => Ok(false),
                _ => Err(anyhow!("Invalid boolean value")),
            })?;
            Ok(ElementValue::Bool(value))
        }
        21 => {
            // int2
            let value = text.parse::<i16>()?;
            Ok(ElementValue::Integer(value as i64))
        }
        23 => {
            // int4
            let value = text.parse::<i32>()?;
            Ok(ElementValue::Integer(value as i64))
        }
        20 => {
            // int8
            let value = text.parse::<i64>()?;
            Ok(ElementValue::Integer(value))
        }
        700 => {
            // float4
            let value = text.parse::<f32>()?;
            Ok(ElementValue::Float(ordered_float::OrderedFloat(
                value as f64,
            )))
        }
        701 => {
            // float8
            let value = text.parse::<f64>()?;
            Ok(ElementValue::Float(ordered_float::OrderedFloat(value)))
        }
        1700 => {
            // numeric/decimal
            let value = text.parse::<f64>()?;
            Ok(ElementValue::Float(ordered_float::OrderedFloat(value)))
        }
        25 | 1043 | 19 => {
            // text, varchar, name
            Ok(ElementValue::String(Arc::from(text)))
        }
        1114 | 1184 => {
            // timestamp, timestamptz
            Ok(ElementValue::String(Arc::from(text)))
        }
        1082 => {
            // date
            Ok(ElementValue::String(Arc::from(text)))
        }
        2950 => {
            // uuid
            Ok(ElementValue::String(Arc::from(text)))
        }
        _ => {
            // Default to string for unknown types
            Ok(ElementValue::String(Arc::from(text)))
        }
    }
}

fn decode_numeric(data: &[u8]) -> Result<Decimal> {
    if data.len() < 8 {
        return Err(anyhow!("Numeric data too short"));
    }

    let mut cursor = Cursor::new(data);
    let ndigits = cursor.read_u16::<BigEndian>()?;
    let weight = cursor.read_i16::<BigEndian>()?;
    let sign = cursor.read_u16::<BigEndian>()?;
    let dscale = cursor.read_u16::<BigEndian>()?;

    if sign == 0xC000 {
        // NaN
        return Ok(Decimal::ZERO);
    }

    let mut digits = Vec::with_capacity(ndigits as usize);
    for _ in 0..ndigits {
        digits.push(cursor.read_u16::<BigEndian>()?);
    }

    // Convert PostgreSQL numeric to Decimal
    // This is a simplified implementation
    let mut result = Decimal::ZERO;
    let base = Decimal::from(10000);

    for (i, &digit) in digits.iter().enumerate() {
        let power = weight as i32 - i as i32;
        let digit_value = Decimal::from(digit as i64);
        let multiplier = if power >= 0 {
            let mut result = Decimal::ONE;
            for _ in 0..power {
                result *= base;
            }
            result
        } else {
            let mut result = Decimal::ONE;
            for _ in 0..(-power) {
                result /= base;
            }
            result
        };
        result += digit_value * multiplier;
    }

    if sign == 0x4000 {
        result = -result;
    }

    // Apply scale
    if dscale > 0 {
        let mut scale_divisor = Decimal::ONE;
        for _ in 0..dscale {
            scale_divisor *= Decimal::from(10);
        }
        result /= scale_divisor;
    }

    Ok(result)
}