Skip to main content

graphd_engine/
values.rs

1use base64::Engine;
2use chrono::Datelike;
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6use crate::error::GraphdError;
7
8/// Internal ID for nodes and relationships in the graph database.
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
10pub struct InternalId {
11    pub table: u64,
12    pub offset: u64,
13}
14
15/// A value returned from a Cypher query, encoded as JSON per Neo4j HTTP API spec.
16#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
17#[serde(untagged)]
18pub enum GraphValue {
19    Null,
20    Bool(bool),
21    Int(i64),
22    Float(f64),
23    String(String),
24    Timestamp(chrono::DateTime<chrono::FixedOffset>),
25    Date(String),
26    Base64(String),
27    Duration(String),
28    List(Vec<GraphValue>),
29    Map(HashMap<String, GraphValue>),
30    Tagged(TaggedValue),
31}
32
33/// Graph-specific types that use a `$type` discriminator.
34#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
35#[serde(tag = "$type", rename_all = "lowercase")]
36pub enum TaggedValue {
37    Node {
38        id: InternalId,
39        label: String,
40        properties: HashMap<String, GraphValue>,
41    },
42    Rel {
43        id: InternalId,
44        label: String,
45        src: InternalId,
46        dst: InternalId,
47        properties: HashMap<String, GraphValue>,
48    },
49    Path {
50        nodes: Vec<GraphValue>,
51        rels: Vec<GraphValue>,
52    },
53    Union {
54        tag: String,
55        value: Box<GraphValue>,
56    },
57}
58
59/// Convert a LadybugDB Value into a GraphValue for JSON serialization.
60pub fn from_lbug_value(value: &lbug::Value) -> GraphValue {
61    match value {
62        lbug::Value::Null(_) => GraphValue::Null,
63        lbug::Value::Bool(b) => GraphValue::Bool(*b),
64        lbug::Value::Int8(n) => GraphValue::Int(*n as i64),
65        lbug::Value::Int16(n) => GraphValue::Int(*n as i64),
66        lbug::Value::Int32(n) => GraphValue::Int(*n as i64),
67        lbug::Value::Int64(n) => GraphValue::Int(*n),
68        lbug::Value::Int128(n) => GraphValue::String(n.to_string()),
69        lbug::Value::UInt8(n) => GraphValue::Int(*n as i64),
70        lbug::Value::UInt16(n) => GraphValue::Int(*n as i64),
71        lbug::Value::UInt32(n) => GraphValue::Int(*n as i64),
72        lbug::Value::UInt64(n) => {
73            if *n <= i64::MAX as u64 {
74                GraphValue::Int(*n as i64)
75            } else {
76                GraphValue::String(n.to_string())
77            }
78        }
79        lbug::Value::Float(f) => GraphValue::Float(*f as f64),
80        lbug::Value::Double(f) => GraphValue::Float(*f),
81        lbug::Value::Decimal(d) => GraphValue::String(d.to_string()),
82        lbug::Value::String(s) => GraphValue::String(s.clone()),
83        lbug::Value::Blob(b) => {
84            GraphValue::Base64(base64::engine::general_purpose::STANDARD.encode(b))
85        }
86        lbug::Value::UUID(u) => GraphValue::String(u.to_string()),
87        lbug::Value::Date(d) => GraphValue::Date(d.to_string()),
88        lbug::Value::Timestamp(t)
89        | lbug::Value::TimestampTz(t)
90        | lbug::Value::TimestampNs(t)
91        | lbug::Value::TimestampMs(t)
92        | lbug::Value::TimestampSec(t) => {
93            let offset_secs = t.offset().whole_seconds();
94            let fixed_offset =
95                chrono::FixedOffset::east_opt(offset_secs).expect("valid UTC offset");
96            #[allow(deprecated)]
97            let naive =
98                chrono::NaiveDateTime::from_timestamp_opt(t.unix_timestamp(), t.nanosecond())
99                    .expect("valid timestamp");
100            GraphValue::Timestamp(chrono::DateTime::from_naive_utc_and_offset(
101                naive,
102                fixed_offset,
103            ))
104        }
105        lbug::Value::Interval(d) => GraphValue::Duration(time_duration_to_iso8601(d)),
106        lbug::Value::List(_, items) | lbug::Value::Array(_, items) => {
107            GraphValue::List(items.iter().map(from_lbug_value).collect())
108        }
109        lbug::Value::Map(_, entries) => {
110            let mut map = HashMap::new();
111            for (k, v) in entries {
112                let key = match k {
113                    lbug::Value::String(s) => s.clone(),
114                    other => format!("{other:?}"),
115                };
116                map.insert(key, from_lbug_value(v));
117            }
118            GraphValue::Map(map)
119        }
120        lbug::Value::Struct(fields) => {
121            let mut map = HashMap::new();
122            for (key, val) in fields {
123                map.insert(key.clone(), from_lbug_value(val));
124            }
125            GraphValue::Map(map)
126        }
127        lbug::Value::Node(node) => {
128            let id = InternalId {
129                table: node.get_node_id().table_id,
130                offset: node.get_node_id().offset,
131            };
132            let mut properties = HashMap::new();
133            for (key, val) in node.get_properties() {
134                properties.insert(key.clone(), from_lbug_value(val));
135            }
136            GraphValue::Tagged(TaggedValue::Node {
137                id,
138                label: node.get_label_name().clone(),
139                properties,
140            })
141        }
142        lbug::Value::Rel(rel) => {
143            let src = InternalId {
144                table: rel.get_src_node().table_id,
145                offset: rel.get_src_node().offset,
146            };
147            let dst = InternalId {
148                table: rel.get_dst_node().table_id,
149                offset: rel.get_dst_node().offset,
150            };
151            let mut properties = HashMap::new();
152            for (key, val) in rel.get_properties() {
153                properties.insert(key.clone(), from_lbug_value(val));
154            }
155            GraphValue::Tagged(TaggedValue::Rel {
156                id: InternalId { table: 0, offset: 0 }, // RelVal doesn't expose its own ID
157                label: rel.get_label_name().clone(),
158                src,
159                dst,
160                properties,
161            })
162        }
163        lbug::Value::RecursiveRel { nodes, rels } => {
164            GraphValue::Tagged(TaggedValue::Path {
165                nodes: nodes.iter().map(|n| from_lbug_value(&lbug::Value::Node(n.clone()))).collect(),
166                rels: rels.iter().map(|r| from_lbug_value(&lbug::Value::Rel(r.clone()))).collect(),
167            })
168        }
169        lbug::Value::InternalID(id) => GraphValue::Map(HashMap::from([
170            ("table".to_string(), GraphValue::Int(id.table_id as i64)),
171            ("offset".to_string(), GraphValue::Int(id.offset as i64)),
172        ])),
173        lbug::Value::Union { value, .. } => from_lbug_value(value),
174    }
175}
176
177/// Infer the logical type from a lbug Value (for list element type).
178pub fn lbug_value_logical_type(v: &lbug::Value) -> lbug::LogicalType {
179    match v {
180        lbug::Value::Bool(_) => lbug::LogicalType::Bool,
181        lbug::Value::Int64(_) => lbug::LogicalType::Int64,
182        lbug::Value::UInt64(_) => lbug::LogicalType::UInt64,
183        lbug::Value::Double(_) => lbug::LogicalType::Double,
184        lbug::Value::Float(_) => lbug::LogicalType::Float,
185        lbug::Value::String(_) => lbug::LogicalType::String,
186        lbug::Value::Date(_) => lbug::LogicalType::Date,
187        lbug::Value::Blob(_) => lbug::LogicalType::Blob,
188        lbug::Value::Interval(_) => lbug::LogicalType::Interval,
189        _ => lbug::LogicalType::Any,
190    }
191}
192
193/// Convert a JSON value to a LadybugDB value for parameter binding.
194pub fn to_lbug_value(json: &serde_json::Value) -> Result<lbug::Value, GraphdError> {
195    match json {
196        serde_json::Value::Null => Ok(lbug::Value::Null(lbug::LogicalType::Any)),
197        serde_json::Value::Bool(b) => Ok(lbug::Value::Bool(*b)),
198        serde_json::Value::Number(n) => {
199            if let Some(i) = n.as_i64() {
200                Ok(lbug::Value::Int64(i))
201            } else if let Some(u) = n.as_u64() {
202                Ok(lbug::Value::UInt64(u))
203            } else if let Some(f) = n.as_f64() {
204                Ok(lbug::Value::Double(f))
205            } else {
206                Err(GraphdError::TypeError("Unsupported number type".into()))
207            }
208        }
209        serde_json::Value::String(s) => Ok(lbug::Value::String(s.clone())),
210        serde_json::Value::Array(arr) => {
211            let items: Result<Vec<lbug::Value>, GraphdError> =
212                arr.iter().map(to_lbug_value).collect();
213            let items = items?;
214            let elem_type = items
215                .first()
216                .map(lbug_value_logical_type)
217                .unwrap_or(lbug::LogicalType::Any);
218            Ok(lbug::Value::List(elem_type, items))
219        }
220        serde_json::Value::Object(obj) => match (obj.get("$type"), obj.get("_value")) {
221            (Some(serde_json::Value::String(ty)), Some(val)) => typed_json_to_lbug(ty, val),
222            _ => Err(GraphdError::TypeError(
223                "Object params require {\"$type\": ..., \"_value\": ...} typed JSON format".into(),
224            )),
225        },
226    }
227}
228
229/// Convert a JSON params object to a Vec of (name, lbug::Value) pairs.
230pub fn json_params_to_lbug(
231    params: &serde_json::Value,
232) -> Result<Vec<(String, lbug::Value)>, GraphdError> {
233    let obj = params
234        .as_object()
235        .ok_or_else(|| GraphdError::TypeError("params must be a JSON object".into()))?;
236    obj.iter()
237        .map(|(k, v)| Ok((k.clone(), to_lbug_value(v)?)))
238        .collect()
239}
240
241/// Convert a Neo4j Query API v2 typed JSON value to a lbug Value.
242///
243/// Typed JSON uses `{"$type": "TypeName", "_value": ...}` wrappers to encode
244/// types that plain JSON cannot represent (datetimes, dates, etc.).
245/// See: <https://neo4j.com/docs/query-api/current/typed-json/>
246fn typed_json_to_lbug(type_name: &str, value: &serde_json::Value) -> Result<lbug::Value, GraphdError> {
247    match type_name {
248        "Null" => Ok(lbug::Value::Null(lbug::LogicalType::Any)),
249        "Boolean" => value
250            .as_bool()
251            .map(lbug::Value::Bool)
252            .ok_or_else(|| GraphdError::TypeError("Boolean _value must be true/false".into())),
253        "Integer" => {
254            let s = value
255                .as_str()
256                .or_else(|| None)
257                .ok_or_else(|| GraphdError::TypeError("Integer _value must be a string".into()))?;
258            s.parse::<i64>()
259                .map(lbug::Value::Int64)
260                .map_err(|e| GraphdError::TypeError(format!("Invalid Integer: {e}")))
261        }
262        "Float" => {
263            let s = value
264                .as_str()
265                .ok_or_else(|| GraphdError::TypeError("Float _value must be a string".into()))?;
266            s.parse::<f64>()
267                .map(lbug::Value::Double)
268                .map_err(|e| GraphdError::TypeError(format!("Invalid Float: {e}")))
269        }
270        "String" => value
271            .as_str()
272            .map(|s| lbug::Value::String(s.to_string()))
273            .ok_or_else(|| GraphdError::TypeError("String _value must be a string".into())),
274        "OffsetDateTime" | "ZonedDateTime" => {
275            let s = value
276                .as_str()
277                .ok_or_else(|| GraphdError::TypeError("DateTime _value must be an ISO-8601 string".into()))?;
278            // Strip optional IANA zone suffix: "2024-01-15T10:30:00Z[Europe/London]" → "2024-01-15T10:30:00Z"
279            let iso = s.split('[').next().unwrap_or(s);
280            let dt = chrono::DateTime::parse_from_rfc3339(iso)
281                .map_err(|e| GraphdError::TypeError(format!("Invalid datetime: {e}")))?;
282            chrono_to_lbug_timestamp(&dt)
283        }
284        "LocalDateTime" => {
285            let s = value
286                .as_str()
287                .ok_or_else(|| GraphdError::TypeError("LocalDateTime _value must be an ISO-8601 string".into()))?;
288            // Parse as naive, assume UTC
289            let naive = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f")
290                .or_else(|_| chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S"))
291                .map_err(|e| GraphdError::TypeError(format!("Invalid LocalDateTime: {e}")))?;
292            let dt = chrono::DateTime::<chrono::FixedOffset>::from_naive_utc_and_offset(
293                naive,
294                chrono::FixedOffset::east_opt(0).expect("UTC offset"),
295            );
296            chrono_to_lbug_timestamp(&dt)
297        }
298        "Date" => {
299            let s = value
300                .as_str()
301                .ok_or_else(|| GraphdError::TypeError("Date _value must be a string".into()))?;
302            let d = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d")
303                .map_err(|e| GraphdError::TypeError(format!("Invalid Date: {e}")))?;
304            let date = time::Date::from_calendar_date(
305                d.year(),
306                time::Month::try_from(d.month() as u8)
307                    .map_err(|e| GraphdError::TypeError(format!("Invalid month: {e}")))?,
308                d.day() as u8,
309            )
310            .map_err(|e| GraphdError::TypeError(format!("Invalid Date: {e}")))?;
311            Ok(lbug::Value::Date(date))
312        }
313        "Duration" => {
314            let s = value
315                .as_str()
316                .ok_or_else(|| GraphdError::TypeError("Duration _value must be a string".into()))?;
317            let dur = parse_iso8601_duration(s)?;
318            Ok(lbug::Value::Interval(dur))
319        }
320        "Base64" => {
321            let s = value
322                .as_str()
323                .ok_or_else(|| GraphdError::TypeError("Base64 _value must be a string".into()))?;
324            let bytes = base64::engine::general_purpose::STANDARD
325                .decode(s)
326                .map_err(|e| GraphdError::TypeError(format!("Invalid Base64: {e}")))?;
327            Ok(lbug::Value::Blob(bytes))
328        }
329        "List" => {
330            let arr = value
331                .as_array()
332                .ok_or_else(|| GraphdError::TypeError("List _value must be an array".into()))?;
333            let items: Result<Vec<lbug::Value>, GraphdError> =
334                arr.iter().map(to_lbug_value).collect();
335            let items = items?;
336            let elem_type = items
337                .first()
338                .map(lbug_value_logical_type)
339                .unwrap_or(lbug::LogicalType::Any);
340            Ok(lbug::Value::List(elem_type, items))
341        }
342        "Map" => {
343            let obj = value
344                .as_object()
345                .ok_or_else(|| GraphdError::TypeError("Map _value must be an object".into()))?;
346            let entries: Result<Vec<(lbug::Value, lbug::Value)>, GraphdError> = obj
347                .iter()
348                .map(|(k, v)| {
349                    let key = lbug::Value::String(k.clone());
350                    let val = to_lbug_value(v)?;
351                    Ok((key, val))
352                })
353                .collect();
354            Ok(lbug::Value::Map(
355                (lbug::LogicalType::String, lbug::LogicalType::Any),
356                entries?,
357            ))
358        }
359        _ => Err(GraphdError::TypeError(format!(
360            "Unsupported typed JSON $type: {type_name}"
361        ))),
362    }
363}
364
365/// Convert a chrono DateTime to lbug::Value::Timestamp via time::OffsetDateTime.
366fn chrono_to_lbug_timestamp(
367    dt: &chrono::DateTime<chrono::FixedOffset>,
368) -> Result<lbug::Value, GraphdError> {
369    use chrono::Timelike;
370    let ts = time::OffsetDateTime::from_unix_timestamp(dt.timestamp())
371        .map_err(|e| GraphdError::TypeError(format!("{e}")))?
372        .replace_nanosecond(dt.nanosecond())
373        .map_err(|e| GraphdError::TypeError(format!("{e}")))?;
374    let offset = time::UtcOffset::from_whole_seconds(dt.offset().local_minus_utc())
375        .map_err(|e| GraphdError::TypeError(format!("{e}")))?;
376    Ok(lbug::Value::Timestamp(ts.to_offset(offset)))
377}
378
379/// Convert a time::Duration to an ISO 8601 duration string (e.g. "P14DT16H12M").
380fn time_duration_to_iso8601(d: &time::Duration) -> String {
381    let total_secs = d.whole_seconds().unsigned_abs();
382    let negative = d.whole_seconds() < 0;
383
384    let days = total_secs / 86400;
385    let remainder = total_secs % 86400;
386    let hours = remainder / 3600;
387    let remainder = remainder % 3600;
388    let minutes = remainder / 60;
389    let seconds = remainder % 60;
390    let nanos = d.subsec_nanoseconds().unsigned_abs() as u64;
391
392    let mut s = if negative {
393        "-P".to_string()
394    } else {
395        "P".to_string()
396    };
397    if days > 0 {
398        s.push_str(&format!("{days}D"));
399    }
400    if hours > 0 || minutes > 0 || seconds > 0 || nanos > 0 {
401        s.push('T');
402        if hours > 0 {
403            s.push_str(&format!("{hours}H"));
404        }
405        if minutes > 0 {
406            s.push_str(&format!("{minutes}M"));
407        }
408        if seconds > 0 || nanos > 0 {
409            if nanos > 0 {
410                let frac = nanos as f64 / 1_000_000_000.0;
411                let sec_f = seconds as f64 + frac;
412                s.push_str(&format!("{sec_f}S"));
413            } else {
414                s.push_str(&format!("{seconds}S"));
415            }
416        }
417    }
418    if s == "P" || s == "-P" {
419        s.push_str("T0S");
420    }
421    s
422}
423
424/// Parse an ISO 8601 duration string (e.g. "P14DT16H12M") into a time::Duration.
425/// Supports P[nD][T[nH][nM][n.nS]]. Does not support year/month components.
426fn parse_iso8601_duration(s: &str) -> Result<time::Duration, GraphdError> {
427    let input = s.trim();
428    let (negative, input) = if let Some(rest) = input.strip_prefix('-') {
429        (true, rest)
430    } else {
431        (false, input)
432    };
433    let input = input.strip_prefix('P').ok_or_else(|| {
434        GraphdError::TypeError(format!("Duration must start with 'P': {s}"))
435    })?;
436
437    let (date_part, time_part) = if let Some(t_idx) = input.find('T') {
438        (&input[..t_idx], Some(&input[t_idx + 1..]))
439    } else {
440        (input, None)
441    };
442
443    let mut total_secs: i64 = 0;
444    let mut nanos: i64 = 0;
445
446    // Parse date part (only D supported)
447    if !date_part.is_empty() {
448        if let Some(d) = date_part.strip_suffix('D') {
449            let days: i64 = d
450                .parse()
451                .map_err(|e| GraphdError::TypeError(format!("Invalid days in duration: {e}")))?;
452            total_secs += days * 86400;
453        } else {
454            return Err(GraphdError::TypeError(format!(
455                "Unsupported duration date component (only days supported): {s}"
456            )));
457        }
458    }
459
460    // Parse time part
461    if let Some(time_str) = time_part {
462        let mut rest = time_str;
463        if let Some(h_idx) = rest.find('H') {
464            let hours: i64 = rest[..h_idx]
465                .parse()
466                .map_err(|e| GraphdError::TypeError(format!("Invalid hours: {e}")))?;
467            total_secs += hours * 3600;
468            rest = &rest[h_idx + 1..];
469        }
470        if let Some(m_idx) = rest.find('M') {
471            let minutes: i64 = rest[..m_idx]
472                .parse()
473                .map_err(|e| GraphdError::TypeError(format!("Invalid minutes: {e}")))?;
474            total_secs += minutes * 60;
475            rest = &rest[m_idx + 1..];
476        }
477        if let Some(s_idx) = rest.find('S') {
478            let sec_str = &rest[..s_idx];
479            if let Some(dot_idx) = sec_str.find('.') {
480                let whole: i64 = sec_str[..dot_idx]
481                    .parse()
482                    .map_err(|e| GraphdError::TypeError(format!("Invalid seconds: {e}")))?;
483                total_secs += whole;
484                let frac_str = &sec_str[dot_idx + 1..];
485                let padded = format!("{:0<9}", frac_str);
486                nanos = padded[..9]
487                    .parse()
488                    .map_err(|e| GraphdError::TypeError(format!("Invalid fractional seconds: {e}")))?;
489            } else {
490                let secs: i64 = sec_str
491                    .parse()
492                    .map_err(|e| GraphdError::TypeError(format!("Invalid seconds: {e}")))?;
493                total_secs += secs;
494            }
495        }
496    }
497
498    let mut dur = time::Duration::new(total_secs, nanos as i32);
499    if negative {
500        dur = -dur;
501    }
502    Ok(dur)
503}
504
505/// Serialize a GraphValue to Neo4j Query API v2 typed JSON format.
506///
507/// Convert a GraphValue to plain JSON (no type wrappers).
508/// Scalars become native JSON types: Int->Number, String->String, Bool->Bool.
509/// Nodes/Rels/Paths keep structure but with plain property values.
510pub fn graph_value_to_plain_json(gv: &GraphValue) -> serde_json::Value {
511    match gv {
512        GraphValue::Null => serde_json::Value::Null,
513        GraphValue::Bool(b) => serde_json::json!(b),
514        GraphValue::Int(i) => serde_json::json!(i),
515        GraphValue::Float(f) => serde_json::json!(f),
516        GraphValue::String(s) => serde_json::json!(s),
517        GraphValue::Timestamp(dt) => serde_json::json!(dt.to_rfc3339()),
518        GraphValue::Date(s) => serde_json::json!(s),
519        GraphValue::Base64(s) => serde_json::json!(s),
520        GraphValue::Duration(s) => serde_json::json!(s),
521        GraphValue::List(items) => {
522            serde_json::Value::Array(items.iter().map(graph_value_to_plain_json).collect())
523        }
524        GraphValue::Map(m) => {
525            let obj: serde_json::Map<std::string::String, serde_json::Value> = m
526                .iter()
527                .map(|(k, v)| (k.clone(), graph_value_to_plain_json(v)))
528                .collect();
529            serde_json::Value::Object(obj)
530        }
531        GraphValue::Tagged(TaggedValue::Node {
532            id,
533            label,
534            properties,
535        }) => {
536            let props: serde_json::Map<std::string::String, serde_json::Value> = properties
537                .iter()
538                .map(|(k, v)| (k.clone(), graph_value_to_plain_json(v)))
539                .collect();
540            serde_json::json!({
541                "_element_id": format!("{}:{}", id.table, id.offset),
542                "_labels": [label],
543                "_properties": props
544            })
545        }
546        GraphValue::Tagged(TaggedValue::Rel {
547            id,
548            label,
549            src,
550            dst,
551            properties,
552        }) => {
553            let props: serde_json::Map<std::string::String, serde_json::Value> = properties
554                .iter()
555                .map(|(k, v)| (k.clone(), graph_value_to_plain_json(v)))
556                .collect();
557            serde_json::json!({
558                "_element_id": format!("{}:{}", id.table, id.offset),
559                "_start_node_element_id": format!("{}:{}", src.table, src.offset),
560                "_end_node_element_id": format!("{}:{}", dst.table, dst.offset),
561                "_type": label,
562                "_properties": props
563            })
564        }
565        GraphValue::Tagged(TaggedValue::Path { nodes, rels }) => {
566            let mut elements = Vec::new();
567            for (i, node) in nodes.iter().enumerate() {
568                elements.push(graph_value_to_plain_json(node));
569                if let Some(rel) = rels.get(i) {
570                    elements.push(graph_value_to_plain_json(rel));
571                }
572            }
573            serde_json::json!(elements)
574        }
575        GraphValue::Tagged(TaggedValue::Union { value, .. }) => graph_value_to_plain_json(value),
576    }
577}
578
579/// Every value gets a `{"$type": "TypeName", "_value": ...}` wrapper.
580/// See: <https://neo4j.com/docs/query-api/current/typed-json/>
581pub fn graph_value_to_typed_json(gv: &GraphValue) -> serde_json::Value {
582    match gv {
583        GraphValue::Null => serde_json::json!(null),
584        GraphValue::Bool(b) => serde_json::json!({"$type": "Boolean", "_value": b}),
585        GraphValue::Int(i) => serde_json::json!({"$type": "Integer", "_value": i.to_string()}),
586        GraphValue::Float(f) => serde_json::json!({"$type": "Float", "_value": f.to_string()}),
587        GraphValue::String(s) => serde_json::json!({"$type": "String", "_value": s}),
588        GraphValue::Timestamp(dt) => {
589            serde_json::json!({"$type": "OffsetDateTime", "_value": dt.to_rfc3339()})
590        }
591        GraphValue::Date(s) => serde_json::json!({"$type": "Date", "_value": s}),
592        GraphValue::Base64(s) => serde_json::json!({"$type": "Base64", "_value": s}),
593        GraphValue::Duration(s) => serde_json::json!({"$type": "Duration", "_value": s}),
594        GraphValue::List(items) => serde_json::json!({
595            "$type": "List",
596            "_value": items.iter().map(graph_value_to_typed_json).collect::<Vec<_>>()
597        }),
598        GraphValue::Map(m) => {
599            let obj: serde_json::Map<std::string::String, serde_json::Value> = m
600                .iter()
601                .map(|(k, v)| (k.clone(), graph_value_to_typed_json(v)))
602                .collect();
603            serde_json::json!({"$type": "Map", "_value": obj})
604        }
605        GraphValue::Tagged(TaggedValue::Node {
606            id,
607            label,
608            properties,
609        }) => {
610            let props: serde_json::Map<std::string::String, serde_json::Value> = properties
611                .iter()
612                .map(|(k, v)| (k.clone(), graph_value_to_typed_json(v)))
613                .collect();
614            serde_json::json!({
615                "$type": "Node",
616                "_value": {
617                    "_element_id": format!("{}:{}", id.table, id.offset),
618                    "_labels": [label],
619                    "_properties": props
620                }
621            })
622        }
623        GraphValue::Tagged(TaggedValue::Rel {
624            id,
625            label,
626            src,
627            dst,
628            properties,
629        }) => {
630            let props: serde_json::Map<std::string::String, serde_json::Value> = properties
631                .iter()
632                .map(|(k, v)| (k.clone(), graph_value_to_typed_json(v)))
633                .collect();
634            serde_json::json!({
635                "$type": "Relationship",
636                "_value": {
637                    "_element_id": format!("{}:{}", id.table, id.offset),
638                    "_start_node_element_id": format!("{}:{}", src.table, src.offset),
639                    "_end_node_element_id": format!("{}:{}", dst.table, dst.offset),
640                    "_type": label,
641                    "_properties": props
642                }
643            })
644        }
645        GraphValue::Tagged(TaggedValue::Path { nodes, rels }) => {
646            let mut elements = Vec::new();
647            for (i, node) in nodes.iter().enumerate() {
648                elements.push(graph_value_to_typed_json(node));
649                if let Some(rel) = rels.get(i) {
650                    elements.push(graph_value_to_typed_json(rel));
651                }
652            }
653            serde_json::json!({"$type": "Path", "_value": elements})
654        }
655        GraphValue::Tagged(TaggedValue::Union { value, .. }) => graph_value_to_typed_json(value),
656    }
657}
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662
663    #[test]
664    fn test_scalar_serialization() {
665        assert_eq!(serde_json::to_string(&GraphValue::Null).unwrap(), "null");
666        assert_eq!(serde_json::to_string(&GraphValue::Bool(true)).unwrap(), "true");
667        assert_eq!(serde_json::to_string(&GraphValue::Int(42)).unwrap(), "42");
668        assert_eq!(serde_json::to_string(&GraphValue::Float(3.14)).unwrap(), "3.14");
669        assert_eq!(
670            serde_json::to_string(&GraphValue::String("hello".into())).unwrap(),
671            "\"hello\""
672        );
673    }
674
675    #[test]
676    fn test_node_serialization() {
677        let node = GraphValue::Tagged(TaggedValue::Node {
678            id: InternalId { table: 0, offset: 5 },
679            label: "Person".into(),
680            properties: HashMap::from([
681                ("name".into(), GraphValue::String("Alice".into())),
682                ("age".into(), GraphValue::Int(30)),
683            ]),
684        });
685        let json: serde_json::Value = serde_json::to_value(&node).unwrap();
686        assert_eq!(json["$type"], "node");
687        assert_eq!(json["label"], "Person");
688        assert_eq!(json["id"]["table"], 0);
689        assert_eq!(json["id"]["offset"], 5);
690    }
691
692    #[test]
693    fn test_rel_serialization() {
694        let rel = GraphValue::Tagged(TaggedValue::Rel {
695            id: InternalId { table: 2, offset: 10 },
696            label: "KNOWS".into(),
697            src: InternalId { table: 0, offset: 5 },
698            dst: InternalId { table: 0, offset: 8 },
699            properties: HashMap::new(),
700        });
701        let json: serde_json::Value = serde_json::to_value(&rel).unwrap();
702        assert_eq!(json["$type"], "rel");
703        assert_eq!(json["label"], "KNOWS");
704        assert_eq!(json["src"]["offset"], 5);
705        assert_eq!(json["dst"]["offset"], 8);
706    }
707
708    #[test]
709    fn test_list_serialization() {
710        let list = GraphValue::List(vec![GraphValue::Int(1), GraphValue::Int(2)]);
711        assert_eq!(serde_json::to_string(&list).unwrap(), "[1,2]");
712    }
713
714    #[test]
715    fn test_to_lbug_null() {
716        let v = to_lbug_value(&serde_json::Value::Null).unwrap();
717        assert!(matches!(v, lbug::Value::Null(_)));
718    }
719
720    #[test]
721    fn test_to_lbug_bool() {
722        assert!(matches!(
723            to_lbug_value(&serde_json::json!(true)).unwrap(),
724            lbug::Value::Bool(true)
725        ));
726        assert!(matches!(
727            to_lbug_value(&serde_json::json!(false)).unwrap(),
728            lbug::Value::Bool(false)
729        ));
730    }
731
732    #[test]
733    fn test_to_lbug_int() {
734        match to_lbug_value(&serde_json::json!(42)).unwrap() {
735            lbug::Value::Int64(n) => assert_eq!(n, 42),
736            other => panic!("expected Int64, got {other:?}"),
737        }
738    }
739
740    #[test]
741    fn test_to_lbug_float() {
742        match to_lbug_value(&serde_json::json!(3.14)).unwrap() {
743            lbug::Value::Double(f) => assert!((f - 3.14).abs() < f64::EPSILON),
744            other => panic!("expected Double, got {other:?}"),
745        }
746    }
747
748    #[test]
749    fn test_to_lbug_string() {
750        match to_lbug_value(&serde_json::json!("hello")).unwrap() {
751            lbug::Value::String(s) => assert_eq!(s, "hello"),
752            other => panic!("expected String, got {other:?}"),
753        }
754    }
755
756    #[test]
757    fn test_to_lbug_array() {
758        match to_lbug_value(&serde_json::json!([1, 2, 3])).unwrap() {
759            lbug::Value::List(ty, items) => {
760                assert_eq!(ty, lbug::LogicalType::Int64);
761                assert_eq!(items.len(), 3);
762            }
763            other => panic!("expected List, got {other:?}"),
764        }
765    }
766
767    #[test]
768    fn test_to_lbug_float_array() {
769        match to_lbug_value(&serde_json::json!([0.1, 0.2, 0.3])).unwrap() {
770            lbug::Value::List(ty, items) => {
771                assert_eq!(ty, lbug::LogicalType::Double);
772                assert_eq!(items.len(), 3);
773            }
774            other => panic!("expected List, got {other:?}"),
775        }
776    }
777
778    #[test]
779    fn test_to_lbug_string_array() {
780        match to_lbug_value(&serde_json::json!(["a", "b"])).unwrap() {
781            lbug::Value::List(ty, items) => {
782                assert_eq!(ty, lbug::LogicalType::String);
783                assert_eq!(items.len(), 2);
784            }
785            other => panic!("expected List, got {other:?}"),
786        }
787    }
788
789    #[test]
790    fn test_to_lbug_empty_array() {
791        match to_lbug_value(&serde_json::json!([])).unwrap() {
792            lbug::Value::List(ty, items) => {
793                assert_eq!(ty, lbug::LogicalType::Any);
794                assert!(items.is_empty());
795            }
796            other => panic!("expected List, got {other:?}"),
797        }
798    }
799
800    #[test]
801    fn test_to_lbug_plain_object_error() {
802        assert!(to_lbug_value(&serde_json::json!({"a": 1})).is_err());
803    }
804
805    #[test]
806    fn test_typed_json_integer() {
807        match to_lbug_value(&serde_json::json!({"$type": "Integer", "_value": "42"})).unwrap() {
808            lbug::Value::Int64(n) => assert_eq!(n, 42),
809            other => panic!("expected Int64, got {other:?}"),
810        }
811    }
812
813    #[test]
814    fn test_typed_json_float() {
815        match to_lbug_value(&serde_json::json!({"$type": "Float", "_value": "3.14"})).unwrap() {
816            lbug::Value::Double(f) => assert!((f - 3.14).abs() < f64::EPSILON),
817            other => panic!("expected Double, got {other:?}"),
818        }
819    }
820
821    #[test]
822    fn test_typed_json_string() {
823        match to_lbug_value(&serde_json::json!({"$type": "String", "_value": "hello"})).unwrap() {
824            lbug::Value::String(s) => assert_eq!(s, "hello"),
825            other => panic!("expected String, got {other:?}"),
826        }
827    }
828
829    #[test]
830    fn test_typed_json_boolean() {
831        match to_lbug_value(&serde_json::json!({"$type": "Boolean", "_value": true})).unwrap() {
832            lbug::Value::Bool(b) => assert!(b),
833            other => panic!("expected Bool, got {other:?}"),
834        }
835    }
836
837    #[test]
838    fn test_typed_json_null() {
839        match to_lbug_value(&serde_json::json!({"$type": "Null", "_value": null})).unwrap() {
840            lbug::Value::Null(_) => {}
841            other => panic!("expected Null, got {other:?}"),
842        }
843    }
844
845    #[test]
846    fn test_typed_json_offset_datetime() {
847        let val = to_lbug_value(
848            &serde_json::json!({"$type": "OffsetDateTime", "_value": "2024-01-15T10:30:00Z"}),
849        )
850        .unwrap();
851        match val {
852            lbug::Value::Timestamp(ts) => {
853                assert_eq!(ts.year(), 2024);
854                assert_eq!(ts.month() as u8, 1);
855                assert_eq!(ts.day(), 15);
856                assert_eq!(ts.hour(), 10);
857                assert_eq!(ts.minute(), 30);
858            }
859            other => panic!("expected Timestamp, got {other:?}"),
860        }
861    }
862
863    #[test]
864    fn test_typed_json_date() {
865        let val =
866            to_lbug_value(&serde_json::json!({"$type": "Date", "_value": "2024-06-15"})).unwrap();
867        match val {
868            lbug::Value::Date(d) => {
869                assert_eq!(d.year(), 2024);
870                assert_eq!(d.month() as u8, 6);
871                assert_eq!(d.day(), 15);
872            }
873            other => panic!("expected Date, got {other:?}"),
874        }
875    }
876
877    #[test]
878    fn test_typed_json_unsupported_type() {
879        assert!(
880            to_lbug_value(&serde_json::json!({"$type": "Point", "_value": "SRID=7203;POINT(1 2)"}))
881                .is_err()
882        );
883    }
884
885    #[test]
886    fn test_json_params_to_lbug() {
887        let params = serde_json::json!({"name": "Alice", "age": 30});
888        let result = json_params_to_lbug(&params).unwrap();
889        assert_eq!(result.len(), 2);
890        // Check both params exist (order not guaranteed from JSON object)
891        let names: Vec<&str> = result.iter().map(|(k, _)| k.as_str()).collect();
892        assert!(names.contains(&"name"));
893        assert!(names.contains(&"age"));
894    }
895
896    #[test]
897    fn test_json_params_not_object() {
898        assert!(json_params_to_lbug(&serde_json::json!("not an object")).is_err());
899    }
900
901    #[test]
902    fn test_graph_value_to_typed_json_scalars() {
903        assert_eq!(graph_value_to_typed_json(&GraphValue::Null), serde_json::json!(null));
904        assert_eq!(
905            graph_value_to_typed_json(&GraphValue::Bool(true)),
906            serde_json::json!({"$type": "Boolean", "_value": true})
907        );
908        assert_eq!(
909            graph_value_to_typed_json(&GraphValue::Int(42)),
910            serde_json::json!({"$type": "Integer", "_value": "42"})
911        );
912        assert_eq!(
913            graph_value_to_typed_json(&GraphValue::String("hello".into())),
914            serde_json::json!({"$type": "String", "_value": "hello"})
915        );
916    }
917
918    #[test]
919    fn test_graph_value_to_typed_json_timestamp() {
920        let dt = chrono::DateTime::parse_from_rfc3339("2024-01-15T10:30:00Z").unwrap();
921        let json = graph_value_to_typed_json(&GraphValue::Timestamp(dt));
922        assert_eq!(json["$type"], "OffsetDateTime");
923        assert!(json["_value"].as_str().unwrap().contains("2024-01-15"));
924    }
925
926    #[test]
927    fn test_graph_value_to_typed_json_list() {
928        let list = GraphValue::List(vec![GraphValue::Int(1), GraphValue::Int(2)]);
929        let json = graph_value_to_typed_json(&list);
930        assert_eq!(json["$type"], "List");
931        assert_eq!(json["_value"].as_array().unwrap().len(), 2);
932    }
933
934    #[test]
935    fn test_graph_value_to_typed_json_node() {
936        let node = GraphValue::Tagged(TaggedValue::Node {
937            id: InternalId { table: 0, offset: 5 },
938            label: "Person".into(),
939            properties: HashMap::from([("name".into(), GraphValue::String("Alice".into()))]),
940        });
941        let json = graph_value_to_typed_json(&node);
942        assert_eq!(json["$type"], "Node");
943        assert_eq!(json["_value"]["_labels"][0], "Person");
944        assert_eq!(json["_value"]["_properties"]["name"]["_value"], "Alice");
945    }
946
947    #[test]
948    fn test_from_lbug_date_typed_json() {
949        let date = time::Date::from_calendar_date(2024, time::Month::June, 15).unwrap();
950        let gv = from_lbug_value(&lbug::Value::Date(date));
951        assert!(matches!(&gv, GraphValue::Date(s) if s == "2024-06-15"));
952        let json = graph_value_to_typed_json(&gv);
953        assert_eq!(json["$type"], "Date");
954        assert_eq!(json["_value"], "2024-06-15");
955    }
956
957    #[test]
958    fn test_from_lbug_blob_typed_json() {
959        let gv = from_lbug_value(&lbug::Value::Blob(vec![72, 101, 108, 108, 111]));
960        assert!(matches!(&gv, GraphValue::Base64(s) if s == "SGVsbG8="));
961        let json = graph_value_to_typed_json(&gv);
962        assert_eq!(json["$type"], "Base64");
963        assert_eq!(json["_value"], "SGVsbG8=");
964    }
965
966    #[test]
967    fn test_from_lbug_interval_typed_json() {
968        let d = time::Duration::new(14 * 86400 + 16 * 3600 + 12 * 60, 0);
969        let gv = from_lbug_value(&lbug::Value::Interval(d));
970        assert!(matches!(&gv, GraphValue::Duration(_)));
971        let json = graph_value_to_typed_json(&gv);
972        assert_eq!(json["$type"], "Duration");
973        assert_eq!(json["_value"], "P14DT16H12M");
974    }
975
976    #[test]
977    fn test_typed_json_duration() {
978        let val =
979            to_lbug_value(&serde_json::json!({"$type": "Duration", "_value": "P14DT16H12M"}))
980                .unwrap();
981        match val {
982            lbug::Value::Interval(d) => {
983                assert_eq!(d.whole_days(), 14);
984                assert_eq!(d.whole_hours() % 24, 16);
985                assert_eq!(d.whole_minutes() % 60, 12);
986            }
987            other => panic!("expected Interval, got {other:?}"),
988        }
989    }
990
991    #[test]
992    fn test_typed_json_base64() {
993        let val =
994            to_lbug_value(&serde_json::json!({"$type": "Base64", "_value": "SGVsbG8="})).unwrap();
995        match val {
996            lbug::Value::Blob(bytes) => assert_eq!(bytes, b"Hello"),
997            other => panic!("expected Blob, got {other:?}"),
998        }
999    }
1000
1001    #[test]
1002    fn test_typed_json_map() {
1003        let val = to_lbug_value(&serde_json::json!({
1004            "$type": "Map",
1005            "_value": {
1006                "name": {"$type": "String", "_value": "Alice"},
1007                "age": {"$type": "Integer", "_value": "30"}
1008            }
1009        }))
1010        .unwrap();
1011        match val {
1012            lbug::Value::Map(_, entries) => {
1013                assert_eq!(entries.len(), 2);
1014            }
1015            other => panic!("expected Map, got {other:?}"),
1016        }
1017    }
1018
1019    #[test]
1020    fn test_duration_parse_zero() {
1021        let val =
1022            to_lbug_value(&serde_json::json!({"$type": "Duration", "_value": "PT0S"})).unwrap();
1023        match val {
1024            lbug::Value::Interval(d) => assert_eq!(d.whole_seconds(), 0),
1025            other => panic!("expected Interval, got {other:?}"),
1026        }
1027    }
1028
1029    #[test]
1030    fn test_duration_parse_fractional_seconds() {
1031        let val =
1032            to_lbug_value(&serde_json::json!({"$type": "Duration", "_value": "PT1.5S"})).unwrap();
1033        match val {
1034            lbug::Value::Interval(d) => {
1035                assert_eq!(d.whole_seconds(), 1);
1036                assert_eq!(d.subsec_nanoseconds(), 500_000_000);
1037            }
1038            other => panic!("expected Interval, got {other:?}"),
1039        }
1040    }
1041
1042    #[test]
1043    fn test_duration_roundtrip() {
1044        let d = time::Duration::new(3 * 86400 + 2 * 3600 + 30 * 60 + 15, 0);
1045        let iso = time_duration_to_iso8601(&d);
1046        assert_eq!(iso, "P3DT2H30M15S");
1047        let parsed = parse_iso8601_duration(&iso).unwrap();
1048        assert_eq!(parsed, d);
1049    }
1050
1051    #[test]
1052    fn test_graph_value_to_typed_json_date() {
1053        let json = graph_value_to_typed_json(&GraphValue::Date("2024-06-15".into()));
1054        assert_eq!(json["$type"], "Date");
1055        assert_eq!(json["_value"], "2024-06-15");
1056    }
1057
1058    #[test]
1059    fn test_graph_value_to_typed_json_base64() {
1060        let json = graph_value_to_typed_json(&GraphValue::Base64("SGVsbG8=".into()));
1061        assert_eq!(json["$type"], "Base64");
1062        assert_eq!(json["_value"], "SGVsbG8=");
1063    }
1064
1065    #[test]
1066    fn test_graph_value_to_typed_json_duration() {
1067        let json = graph_value_to_typed_json(&GraphValue::Duration("P14DT16H12M".into()));
1068        assert_eq!(json["$type"], "Duration");
1069        assert_eq!(json["_value"], "P14DT16H12M");
1070    }
1071}