1use std::collections::BTreeMap;
5
6use serde::{Deserialize, Serialize};
7
8pub mod field {
9 pub const ID: &str = "id";
10 pub const CREATED_AT: &str = "createdAt";
11 pub const UPDATED_AT: &str = "updatedAt";
12 pub const DELETED_AT: &str = "deletedAt";
13}
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16pub enum FieldValue {
17 Text(String),
18 I64(i64),
19 F64(f64),
20 Date(i64),
22 Bytes(Vec<u8>),
24 Strings(Vec<String>),
28}
29
30impl FieldValue {
31 pub fn as_str(&self) -> Option<&str> {
32 match self {
33 Self::Text(s) => Some(s),
34 _ => None,
35 }
36 }
37 pub fn as_date_ms(&self) -> Option<i64> {
38 match self {
39 Self::Date(ms) => Some(*ms),
40 _ => None,
41 }
42 }
43 pub fn as_strings(&self) -> Option<&[String]> {
44 match self {
45 Self::Strings(v) => Some(v),
46 _ => None,
47 }
48 }
49 pub fn as_f64(&self) -> Option<f64> {
50 match self {
51 Self::F64(v) => Some(*v),
52 Self::I64(v) => Some(*v as f64),
53 _ => None,
54 }
55 }
56 pub fn as_text_or_bytes(&self) -> Option<String> {
58 match self {
59 Self::Text(s) => Some(s.clone()),
60 Self::Bytes(b) => String::from_utf8(b.clone()).ok(),
61 _ => None,
62 }
63 }
64}
65
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct RawRecord {
68 pub record_type: String,
69 pub record_name: String,
70 pub fields: BTreeMap<String, FieldValue>,
71 pub modified_ms: Option<i64>,
73 pub created_ms: Option<i64>,
75 pub change_tag: Option<String>,
78}
79
80impl RawRecord {
81 pub fn new(record_type: &str, record_name: &str) -> Self {
82 Self {
83 record_type: record_type.to_string(),
84 record_name: record_name.to_string(),
85 fields: BTreeMap::new(),
86 modified_ms: None,
87 created_ms: None,
88 change_tag: None,
89 }
90 }
91 pub fn get(&self, key: &str) -> Option<&FieldValue> {
92 self.fields.get(key)
93 }
94 pub fn text(&self, key: &str) -> Option<String> {
95 self.fields.get(key)?.as_str().map(str::to_string)
96 }
97 pub fn date_ms(&self, key: &str) -> Option<i64> {
98 self.fields.get(key)?.as_date_ms()
99 }
100 pub fn set(&mut self, key: &str, value: FieldValue) {
101 self.fields.insert(key.to_string(), value);
102 }
103 pub fn set_opt(&mut self, key: &str, value: Option<FieldValue>) {
105 match value {
106 Some(v) => self.set(key, v),
107 None => {
108 self.fields.remove(key);
109 }
110 }
111 }
112}
113
114pub fn write_tombstone(record: &mut RawRecord, id: &str, deleted_at_ms: i64, keep: &[&str]) {
118 record.fields.retain(|k, _| keep.contains(&k.as_str()));
119 record.set(field::ID, FieldValue::Text(id.to_string()));
120 record.set(field::UPDATED_AT, FieldValue::Date(deleted_at_ms));
121 record.set(field::DELETED_AT, FieldValue::Date(deleted_at_ms));
122}
123
124pub fn read_tombstone(record: &RawRecord) -> Option<(String, i64)> {
127 let deleted_at = record.date_ms(field::DELETED_AT)?;
128 let id = record
129 .text(field::ID)
130 .unwrap_or_else(|| record.record_name.clone());
131 Some((id, deleted_at))
132}