evenframe_core 0.4.0

Core functionality for Evenframe - TypeScript type generation and database schema synchronization
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
use core::fmt;
#[cfg(feature = "surrealdb")]
use serde::de::MapAccess;
use serde::{
    Deserialize, Deserializer, Serialize,
    de::{self, Visitor},
};
use std::{marker::PhantomData, ops::Deref};

// === EvenframeRecordId: surrealdb-backed implementation ===

#[cfg(feature = "surrealdb")]
use surrealdb::types::{RecordId, ToSql};

#[cfg(feature = "surrealdb")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EvenframeRecordId(pub RecordId);

#[cfg(feature = "surrealdb")]
impl From<String> for EvenframeRecordId {
    fn from(value: String) -> Self {
        let mut parts = value.splitn(2, ':');
        let table = parts.next().unwrap_or("");
        let key = parts.next().unwrap_or("").replace(['', '', '`'], "");
        EvenframeRecordId(RecordId::new(table, key))
    }
}

#[cfg(feature = "surrealdb")]
impl Deref for EvenframeRecordId {
    type Target = RecordId;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[cfg(feature = "surrealdb")]
impl EvenframeRecordId {
    pub fn as_inner(&self) -> &RecordId {
        &self.0
    }

    pub fn into_inner(self) -> RecordId {
        self.0
    }
}

#[cfg(feature = "surrealdb")]
impl fmt::Display for EvenframeRecordId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.to_sql().replace(['', '', '`'], ""))
    }
}

#[cfg(feature = "surrealdb")]
impl serde::Serialize for EvenframeRecordId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.0.to_sql().replace(['', '', '`'], ""))
    }
}

#[cfg(feature = "surrealdb")]
impl<'de> Deserialize<'de> for EvenframeRecordId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct EvenframeRecordIdVisitor;

        impl<'de> Visitor<'de> for EvenframeRecordIdVisitor {
            type Value = EvenframeRecordId;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter
                    .write_str("a RecordId, a string that can be parsed into a RecordId, or null")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let mut parts = value.splitn(2, ':');
                let table = parts.next().unwrap_or("");
                let key = parts.next().unwrap_or("").replace(['', '', '`'], "");
                Ok(EvenframeRecordId(RecordId::new(table, key)))
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str(&value)
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                // SurrealQL FETCH returns partial records as `{ id: "table:key",
                // ...other selected fields }`. The standard `RecordId` map shape
                // is `{ table: "...", id: ... }` and rejects extra keys, so
                // before falling through to `RecordId::deserialize` we look for
                // a string `id` containing `:` and parse it directly. This
                // makes RecordLink<T> deserialization succeed for fetched
                // partials by collapsing the partial back to its Id form.
                let mut buffered: Vec<(String, serde_value::Value)> = Vec::new();
                let mut id_string: Option<String> = None;
                while let Some(key) = map.next_key::<String>()? {
                    if key == "id" && id_string.is_none() {
                        let raw = map.next_value::<serde_value::Value>()?;
                        match &raw {
                            serde_value::Value::String(s) if s.contains(':') => {
                                id_string = Some(s.clone());
                            }
                            _ => {
                                buffered.push((key, raw));
                            }
                        }
                    } else {
                        let raw = map.next_value::<serde_value::Value>()?;
                        buffered.push((key, raw));
                    }
                }
                if let Some(s) = id_string {
                    let mut parts = s.splitn(2, ':');
                    let table = parts.next().unwrap_or("");
                    let key = parts.next().unwrap_or("").replace(['', '', '`'], "");
                    return Ok(EvenframeRecordId(RecordId::new(table, key)));
                }
                // Fall back to RecordId::deserialize for the canonical
                // `{ table, id }` shape (or any other variant RecordId accepts).
                let buffered_map: std::collections::BTreeMap<
                    serde_value::Value,
                    serde_value::Value,
                > = buffered
                    .into_iter()
                    .map(|(k, v)| (serde_value::Value::String(k), v))
                    .collect();
                let record_id = RecordId::deserialize(serde_value::Value::Map(buffered_map))
                    .map_err(de::Error::custom)?;
                Ok(EvenframeRecordId(record_id))
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                // JSON `null` → treat as empty string
                self.visit_str("no:access")
            }
        }

        deserializer.deserialize_any(EvenframeRecordIdVisitor)
    }
}

// === EvenframeRecordId: string-based fallback when surrealdb is disabled ===

#[cfg(not(feature = "surrealdb"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EvenframeRecordId {
    pub table: String,
    pub key: String,
}

#[cfg(not(feature = "surrealdb"))]
impl From<String> for EvenframeRecordId {
    fn from(value: String) -> Self {
        let mut parts = value.splitn(2, ':');
        let table = parts.next().unwrap_or("").to_string();
        let key = parts
            .next()
            .unwrap_or("")
            .replace(['', '', '`'], "")
            .to_string();
        EvenframeRecordId { table, key }
    }
}

#[cfg(not(feature = "surrealdb"))]
impl fmt::Display for EvenframeRecordId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.table, self.key)
    }
}

#[cfg(not(feature = "surrealdb"))]
impl serde::Serialize for EvenframeRecordId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("{}:{}", self.table, self.key))
    }
}

#[cfg(not(feature = "surrealdb"))]
impl<'de> Deserialize<'de> for EvenframeRecordId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct EvenframeRecordIdVisitor;

        impl<'de> Visitor<'de> for EvenframeRecordIdVisitor {
            type Value = EvenframeRecordId;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a string in the format 'table:key', or null")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let mut parts = value.splitn(2, ':');
                let table = parts.next().unwrap_or("").to_string();
                let key = parts
                    .next()
                    .unwrap_or("")
                    .replace(['', '', '`'], "")
                    .to_string();
                Ok(EvenframeRecordId { table, key })
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str(&value)
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str("no:access")
            }
        }

        deserializer.deserialize_any(EvenframeRecordIdVisitor)
    }
}

// === EvenframePhantomData (always compiled) ===

#[derive(Debug, Default, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EvenframePhantomData<T>(pub PhantomData<T>);

impl<T> Deref for EvenframePhantomData<T> {
    type Target = PhantomData<T>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> EvenframePhantomData<T> {
    pub fn new() -> Self {
        EvenframePhantomData(PhantomData)
    }

    pub fn as_inner(&self) -> &PhantomData<T> {
        &self.0
    }

    pub fn into_inner(self) -> PhantomData<T> {
        self.0
    }
}

// === EvenframeValue (always compiled) ===

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EvenframeValue(pub serde_value::Value);

impl Deref for EvenframeValue {
    type Target = serde_value::Value;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl EvenframeValue {
    pub fn as_inner(&self) -> &serde_value::Value {
        &self.0
    }

    pub fn into_inner(self) -> serde_value::Value {
        self.0
    }
}

// === EvenframeDuration (always compiled) ===

// We remove `Serialize` from the derive macro to provide a custom implementation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EvenframeDuration(pub chrono::TimeDelta);

// Manually implement `Serialize` to control the output format.
impl Serialize for EvenframeDuration {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // Serialize as a tuple [seconds, nanos]
        use serde::ser::SerializeTuple;

        // Get the total seconds and the nanosecond part
        let total_seconds = self.0.num_seconds();
        let nanos = self.0.subsec_nanos();

        // Create a 2-element tuple
        let mut tuple = serializer.serialize_tuple(2)?;
        tuple.serialize_element(&total_seconds)?;
        tuple.serialize_element(&nanos)?;
        tuple.end()
    }
}

// Deserialize implementation that handles both formats:
// - i64: total nanoseconds (legacy format)
// - [i64, i32]: tuple of [seconds, nanos] (new format)
impl<'de> Deserialize<'de> for EvenframeDuration {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct DurationVisitor;

        impl<'de> Visitor<'de> for DurationVisitor {
            type Value = EvenframeDuration;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("either an i64 (nanoseconds) or a tuple [seconds, nanos]")
            }

            // Handle the legacy format: single i64 representing total nanoseconds
            fn visit_i64<E>(self, nanos: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let td = chrono::TimeDelta::nanoseconds(nanos);
                Ok(EvenframeDuration(td))
            }

            // Also handle u64 for large positive values
            fn visit_u64<E>(self, nanos: u64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let td = chrono::TimeDelta::nanoseconds(nanos as i64);
                Ok(EvenframeDuration(td))
            }

            // Handle i32
            fn visit_i32<E>(self, nanos: i32) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let td = chrono::TimeDelta::nanoseconds(nanos as i64);
                Ok(EvenframeDuration(td))
            }

            // Handle u32
            fn visit_u32<E>(self, nanos: u32) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let td = chrono::TimeDelta::nanoseconds(nanos as i64);
                Ok(EvenframeDuration(td))
            }

            // Handle the new format: tuple of [seconds, nanos]
            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: de::SeqAccess<'de>,
            {
                let seconds = seq
                    .next_element::<i64>()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                let nanos = seq
                    .next_element::<i32>()?
                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;

                // Ensure no extra elements
                if seq.next_element::<de::IgnoredAny>()?.is_some() {
                    return Err(de::Error::invalid_length(3, &self));
                }

                let td = chrono::TimeDelta::seconds(seconds)
                    + chrono::TimeDelta::nanoseconds(nanos as i64);
                Ok(EvenframeDuration(td))
            }
        }

        deserializer.deserialize_any(DurationVisitor)
    }
}