Skip to main content

oxilite_cypher/
value.rs

1//! Cypher values and their mapping to RDF terms.
2//!
3// @lat: [[architecture#Property graph frontend#Mapping]]
4
5use crate::error::{CypherError, Result};
6
7use oxrdf::{Literal, NamedNode, NamedOrBlankNode, Term};
8use std::cmp::Ordering;
9use std::collections::BTreeMap;
10use std::fmt;
11
12/// `rdf:JSON`, the datatype of list and map property values.
13pub const RDF_JSON: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#JSON";
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub enum TemporalKind {
17    Date,
18    DateTime,
19    LocalDateTime,
20    Time,
21    LocalTime,
22    Duration,
23}
24
25impl TemporalKind {
26    pub fn datatype(self) -> &'static str {
27        match self {
28            Self::Date => "http://www.w3.org/2001/XMLSchema#date",
29            Self::DateTime | Self::LocalDateTime => "http://www.w3.org/2001/XMLSchema#dateTime",
30            Self::Time | Self::LocalTime => "http://www.w3.org/2001/XMLSchema#time",
31            Self::Duration => "http://www.w3.org/2001/XMLSchema#duration",
32        }
33    }
34}
35
36/// A node of the property graph.
37#[derive(Debug, Clone, PartialEq)]
38pub struct Node {
39    pub id: NamedOrBlankNode,
40    pub labels: Vec<String>,
41    pub properties: BTreeMap<String, Value>,
42}
43
44impl Node {
45    pub fn element_id(&self) -> String {
46        subject_str(&self.id)
47    }
48}
49
50/// A relationship: an asserted triple, identified by its reifier when it has one.
51#[derive(Debug, Clone, PartialEq)]
52pub struct Relationship {
53    pub start: NamedOrBlankNode,
54    pub predicate: NamedNode,
55    pub end: NamedOrBlankNode,
56    pub reifier: Option<NamedOrBlankNode>,
57    pub rel_type: String,
58    pub properties: BTreeMap<String, Value>,
59}
60
61impl Relationship {
62    pub fn element_id(&self) -> String {
63        match &self.reifier {
64            Some(r) => subject_str(r),
65            None => format!(
66                "<<( {} <{}> {} )>>",
67                subject_str(&self.start),
68                self.predicate.as_str(),
69                subject_str(&self.end)
70            ),
71        }
72    }
73
74    pub(crate) fn same(&self, other: &Self) -> bool {
75        self.start == other.start
76            && self.predicate == other.predicate
77            && self.end == other.end
78            && self.reifier == other.reifier
79    }
80}
81
82#[derive(Debug, Clone, PartialEq)]
83pub struct Path {
84    pub nodes: Vec<Node>,
85    pub relationships: Vec<Relationship>,
86}
87
88/// A Cypher value.
89#[derive(Debug, Clone, PartialEq)]
90pub enum Value {
91    Null,
92    Bool(bool),
93    Int(i64),
94    Float(f64),
95    String(String),
96    Temporal(TemporalKind, String),
97    List(Vec<Value>),
98    Map(BTreeMap<String, Value>),
99    Node(Node),
100    Relationship(Relationship),
101    Path(Path),
102}
103
104pub(crate) fn subject_str(s: &NamedOrBlankNode) -> String {
105    match s {
106        NamedOrBlankNode::NamedNode(n) => n.as_str().to_string(),
107        NamedOrBlankNode::BlankNode(b) => format!("_:{}", b.as_str()),
108    }
109}
110
111impl Value {
112    pub fn is_null(&self) -> bool {
113        matches!(self, Self::Null)
114    }
115
116    pub fn type_name(&self) -> &'static str {
117        match self {
118            Self::Null => "NULL",
119            Self::Bool(_) => "BOOLEAN",
120            Self::Int(_) => "INTEGER",
121            Self::Float(_) => "FLOAT",
122            Self::String(_) => "STRING",
123            Self::Temporal(k, _) => match k {
124                TemporalKind::Date => "DATE",
125                TemporalKind::DateTime => "DATETIME",
126                TemporalKind::LocalDateTime => "LOCALDATETIME",
127                TemporalKind::Time => "TIME",
128                TemporalKind::LocalTime => "LOCALTIME",
129                TemporalKind::Duration => "DURATION",
130            },
131            Self::List(_) => "LIST",
132            Self::Map(_) => "MAP",
133            Self::Node(_) => "NODE",
134            Self::Relationship(_) => "RELATIONSHIP",
135            Self::Path(_) => "PATH",
136        }
137    }
138
139    pub fn as_bool(&self) -> Option<bool> {
140        match self {
141            Self::Bool(b) => Some(*b),
142            _ => None,
143        }
144    }
145
146    pub fn as_f64(&self) -> Option<f64> {
147        match self {
148            Self::Int(i) => Some(*i as f64),
149            Self::Float(f) => Some(*f),
150            _ => None,
151        }
152    }
153
154    /// Converts a stored RDF literal to a Cypher value.
155    pub fn from_literal(l: &Literal) -> Self {
156        let dt = l.datatype().as_str();
157        let lex = l.value();
158        match dt {
159            "http://www.w3.org/2001/XMLSchema#string"
160            | "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"
161            | "http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString" => {
162                Self::String(lex.to_string())
163            }
164            "http://www.w3.org/2001/XMLSchema#boolean" => match lex {
165                "true" | "1" => Self::Bool(true),
166                "false" | "0" => Self::Bool(false),
167                _ => Self::String(lex.to_string()),
168            },
169            "http://www.w3.org/2001/XMLSchema#integer"
170            | "http://www.w3.org/2001/XMLSchema#long"
171            | "http://www.w3.org/2001/XMLSchema#int"
172            | "http://www.w3.org/2001/XMLSchema#short"
173            | "http://www.w3.org/2001/XMLSchema#byte"
174            | "http://www.w3.org/2001/XMLSchema#nonNegativeInteger"
175            | "http://www.w3.org/2001/XMLSchema#positiveInteger"
176            | "http://www.w3.org/2001/XMLSchema#nonPositiveInteger"
177            | "http://www.w3.org/2001/XMLSchema#negativeInteger"
178            | "http://www.w3.org/2001/XMLSchema#unsignedLong"
179            | "http://www.w3.org/2001/XMLSchema#unsignedInt"
180            | "http://www.w3.org/2001/XMLSchema#unsignedShort"
181            | "http://www.w3.org/2001/XMLSchema#unsignedByte" => match lex.trim().parse::<i64>() {
182                Ok(i) => Self::Int(i),
183                Err(_) => lex
184                    .trim()
185                    .parse::<f64>()
186                    .map_or_else(|_| Self::String(lex.to_string()), Self::Float),
187            },
188            "http://www.w3.org/2001/XMLSchema#decimal"
189            | "http://www.w3.org/2001/XMLSchema#double"
190            | "http://www.w3.org/2001/XMLSchema#float" => match lex.trim() {
191                "INF" => Self::Float(f64::INFINITY),
192                "-INF" => Self::Float(f64::NEG_INFINITY),
193                "NaN" => Self::Float(f64::NAN),
194                t => t
195                    .parse::<f64>()
196                    .map_or_else(|_| Self::String(lex.to_string()), Self::Float),
197            },
198            "http://www.w3.org/2001/XMLSchema#date"
199            | "http://www.w3.org/2001/XMLSchema#time"
200            | "http://www.w3.org/2001/XMLSchema#dateTime"
201            | "http://www.w3.org/2001/XMLSchema#dateTimeStamp"
202            | "http://www.w3.org/2001/XMLSchema#duration"
203            | "http://www.w3.org/2001/XMLSchema#dayTimeDuration"
204            | "http://www.w3.org/2001/XMLSchema#yearMonthDuration"
205            | crate::temporal::ZONED_DATETIME => crate::temporal::from_literal(dt, lex)
206                .unwrap_or_else(|| Self::String(lex.to_string())),
207            RDF_JSON => serde_json::from_str::<serde_json::Value>(lex)
208                .map_or_else(|_| Self::String(lex.to_string()), |j| Self::from_json(&j)),
209            _ => Self::String(lex.to_string()),
210        }
211    }
212
213    /// Converts a term returned by a SPARQL solution into a plain value (IRIs and blank nodes
214    /// become their string form).
215    pub fn from_term(t: &Term) -> Self {
216        match t {
217            Term::Literal(l) => Self::from_literal(l),
218            Term::NamedNode(n) => Self::String(n.as_str().to_string()),
219            Term::BlankNode(b) => Self::String(format!("_:{}", b.as_str())),
220            Term::Triple(t) => Self::String(t.to_string()),
221        }
222    }
223
224    /// The RDF literal storing this value as a property, or `None` for `null`.
225    pub fn to_literal(&self) -> Result<Option<Literal>> {
226        Ok(Some(match self {
227            Self::Null => return Ok(None),
228            Self::Bool(b) => Literal::from(*b),
229            Self::Int(i) => Literal::from(*i),
230            Self::Float(f) => Literal::from(*f),
231            Self::String(s) => Literal::new_simple_literal(s.clone()),
232            Self::Temporal(k, lex) => {
233                let (l, dt) = crate::temporal::T::parse(*k, lex)?.lexical();
234                Literal::new_typed_literal(l, NamedNode::new_unchecked(dt))
235            }
236            Self::List(items) if items.is_empty() => {
237                Literal::new_typed_literal("[]", NamedNode::new_unchecked(RDF_JSON))
238            }
239            Self::List(_) | Self::Map(_) => Literal::new_typed_literal(
240                self.to_json_storable()?.to_string(),
241                NamedNode::new_unchecked(RDF_JSON),
242            ),
243            Self::Node(_) | Self::Relationship(_) | Self::Path(_) => {
244                return Err(CypherError::runtime(format!(
245                    "a {} cannot be stored as a property value",
246                    self.type_name()
247                )))
248            }
249        }))
250    }
251
252    fn to_json_storable(&self) -> Result<serde_json::Value> {
253        Ok(match self {
254            Self::Null => serde_json::Value::Null,
255            Self::Bool(b) => (*b).into(),
256            Self::Int(i) => (*i).into(),
257            Self::Float(f) => serde_json::Number::from_f64(*f)
258                .map_or(serde_json::Value::Null, serde_json::Value::Number),
259            Self::String(s) | Self::Temporal(_, s) => s.clone().into(),
260            Self::List(items) => serde_json::Value::Array(
261                items
262                    .iter()
263                    .map(Self::to_json_storable)
264                    .collect::<Result<_>>()?,
265            ),
266            Self::Map(m) => serde_json::Value::Object(
267                m.iter()
268                    .map(|(k, v)| Ok((k.clone(), v.to_json_storable()?)))
269                    .collect::<Result<_>>()?,
270            ),
271            Self::Node(_) | Self::Relationship(_) | Self::Path(_) => {
272                return Err(CypherError::runtime(format!(
273                    "a {} cannot be stored in a property",
274                    self.type_name()
275                )))
276            }
277        })
278    }
279
280    pub fn from_json(j: &serde_json::Value) -> Self {
281        match j {
282            serde_json::Value::Null => Self::Null,
283            serde_json::Value::Bool(b) => Self::Bool(*b),
284            serde_json::Value::Number(n) => match n.as_i64() {
285                Some(i) => Self::Int(i),
286                None => Self::Float(n.as_f64().unwrap_or(f64::NAN)),
287            },
288            serde_json::Value::String(s) => Self::String(s.clone()),
289            serde_json::Value::Array(a) => Self::List(a.iter().map(Self::from_json).collect()),
290            serde_json::Value::Object(o) => Self::Map(
291                o.iter()
292                    .map(|(k, v)| (k.clone(), Self::from_json(v)))
293                    .collect(),
294            ),
295        }
296    }
297
298    /// JSON form for bindings and result serialization.
299    pub fn to_json(&self) -> serde_json::Value {
300        use serde_json::json;
301        let props = |p: &BTreeMap<String, Value>| {
302            serde_json::Value::Object(p.iter().map(|(k, v)| (k.clone(), v.to_json())).collect())
303        };
304        match self {
305            Self::Null => serde_json::Value::Null,
306            Self::Bool(b) => json!(b),
307            Self::Int(i) => json!(i),
308            Self::Float(f) => serde_json::Number::from_f64(*f)
309                .map_or_else(|| json!(f.to_string()), serde_json::Value::Number),
310            Self::String(s) => json!(s),
311            Self::Temporal(k, s) => {
312                json!({"type": self.type_name().to_lowercase(), "value": s, "kind": format!("{k:?}")})
313            }
314            Self::List(items) => {
315                serde_json::Value::Array(items.iter().map(Self::to_json).collect())
316            }
317            Self::Map(m) => props(m),
318            Self::Node(n) => json!({
319                "type": "node",
320                "id": n.element_id(),
321                "labels": n.labels,
322                "properties": props(&n.properties),
323            }),
324            Self::Relationship(r) => json!({
325                "type": "relationship",
326                "id": r.element_id(),
327                "relType": r.rel_type,
328                "start": subject_str(&r.start),
329                "end": subject_str(&r.end),
330                "properties": props(&r.properties),
331            }),
332            Self::Path(p) => json!({
333                "type": "path",
334                "nodes": p.nodes.iter().map(|n| Value::Node(n.clone()).to_json()).collect::<Vec<_>>(),
335                "relationships": p.relationships.iter().map(|r| Value::Relationship(r.clone()).to_json()).collect::<Vec<_>>(),
336            }),
337        }
338    }
339
340    /// Cypher `=`: `None` is `null`.
341    pub fn cypher_eq(&self, other: &Self) -> Option<bool> {
342        match (self, other) {
343            (Self::Null, _) | (_, Self::Null) => None,
344            (Self::Int(a), Self::Int(b)) => Some(a == b),
345            (Self::Int(_) | Self::Float(_), Self::Int(_) | Self::Float(_)) => {
346                Some(self.as_f64() == other.as_f64())
347            }
348            (Self::Bool(a), Self::Bool(b)) => Some(a == b),
349            (Self::String(a), Self::String(b)) => Some(a == b),
350            (Self::Temporal(k1, a), Self::Temporal(k2, b)) => {
351                match (
352                    crate::temporal::T::parse(*k1, a),
353                    crate::temporal::T::parse(*k2, b),
354                ) {
355                    (Ok(x), Ok(y)) => crate::temporal::equal(&x, &y),
356                    _ => Some(k1 == k2 && a == b),
357                }
358            }
359            (Self::List(a), Self::List(b)) => {
360                if a.len() != b.len() {
361                    return Some(false);
362                }
363                let mut unknown = false;
364                for (x, y) in a.iter().zip(b) {
365                    match x.cypher_eq(y) {
366                        Some(false) => return Some(false),
367                        None => unknown = true,
368                        Some(true) => {}
369                    }
370                }
371                if unknown {
372                    None
373                } else {
374                    Some(true)
375                }
376            }
377            (Self::Map(a), Self::Map(b)) => {
378                if a.len() != b.len() || a.keys().ne(b.keys()) {
379                    return Some(false);
380                }
381                let mut unknown = false;
382                for (x, y) in a.values().zip(b.values()) {
383                    match x.cypher_eq(y) {
384                        Some(false) => return Some(false),
385                        None => unknown = true,
386                        Some(true) => {}
387                    }
388                }
389                if unknown {
390                    None
391                } else {
392                    Some(true)
393                }
394            }
395            (Self::Node(a), Self::Node(b)) => Some(a.id == b.id),
396            (Self::Relationship(a), Self::Relationship(b)) => Some(a.same(b)),
397            (Self::Path(a), Self::Path(b)) => Some(
398                a.nodes.len() == b.nodes.len()
399                    && a.nodes.iter().zip(&b.nodes).all(|(x, y)| x.id == y.id)
400                    && a.relationships.len() == b.relationships.len()
401                    && a.relationships
402                        .iter()
403                        .zip(&b.relationships)
404                        .all(|(x, y)| x.same(y)),
405            ),
406            _ => Some(false),
407        }
408    }
409
410    /// Cypher `<` and friends: `None` when the values are not comparable.
411    pub fn cypher_cmp(&self, other: &Self) -> Option<Ordering> {
412        match (self, other) {
413            (Self::Int(a), Self::Int(b)) => Some(a.cmp(b)),
414            (Self::Int(_) | Self::Float(_), Self::Int(_) | Self::Float(_)) => {
415                self.as_f64()?.partial_cmp(&other.as_f64()?)
416            }
417            (Self::String(a), Self::String(b)) => Some(a.cmp(b)),
418            (Self::Bool(a), Self::Bool(b)) => Some(a.cmp(b)),
419            (Self::Temporal(k1, a), Self::Temporal(k2, b)) => {
420                let (x, y) = (
421                    crate::temporal::T::parse(*k1, a).ok()?,
422                    crate::temporal::T::parse(*k2, b).ok()?,
423                );
424                crate::temporal::compare(&x, &y)
425            }
426            (Self::List(a), Self::List(b)) => {
427                for (x, y) in a.iter().zip(b) {
428                    match x.cypher_cmp(y)? {
429                        Ordering::Equal => {}
430                        o => return Some(o),
431                    }
432                }
433                Some(a.len().cmp(&b.len()))
434            }
435            _ => None,
436        }
437    }
438
439    fn order_rank(&self) -> u8 {
440        match self {
441            Self::Map(_) => 0,
442            Self::Node(_) => 1,
443            Self::Relationship(_) => 2,
444            Self::List(_) => 3,
445            Self::Path(_) => 4,
446            Self::Temporal(..) => 5,
447            Self::String(_) => 6,
448            Self::Bool(_) => 7,
449            Self::Int(_) | Self::Float(_) => 8,
450            Self::Null => 9,
451        }
452    }
453
454    /// The total order of `ORDER BY` (nulls last when ascending).
455    pub fn order(&self, other: &Self) -> Ordering {
456        let (ra, rb) = (self.order_rank(), other.order_rank());
457        if ra != rb {
458            return ra.cmp(&rb);
459        }
460        match (self, other) {
461            (Self::Int(_) | Self::Float(_), Self::Int(_) | Self::Float(_)) => {
462                let (a, b) = (self.as_f64().unwrap_or(0.0), other.as_f64().unwrap_or(0.0));
463                match (a.is_nan(), b.is_nan()) {
464                    (true, true) => Ordering::Equal,
465                    (true, false) => Ordering::Greater,
466                    (false, true) => Ordering::Less,
467                    _ => a.partial_cmp(&b).unwrap_or(Ordering::Equal),
468                }
469            }
470            (Self::List(a), Self::List(b)) => {
471                for (x, y) in a.iter().zip(b) {
472                    match x.order(y) {
473                        Ordering::Equal => {}
474                        o => return o,
475                    }
476                }
477                a.len().cmp(&b.len())
478            }
479            (Self::Map(a), Self::Map(b)) => {
480                let ka: Vec<_> = a.iter().collect();
481                let kb: Vec<_> = b.iter().collect();
482                for ((k1, v1), (k2, v2)) in ka.iter().zip(&kb) {
483                    match k1.cmp(k2).then_with(|| v1.order(v2)) {
484                        Ordering::Equal => {}
485                        o => return o,
486                    }
487                }
488                ka.len().cmp(&kb.len())
489            }
490            (Self::Node(a), Self::Node(b)) => subject_str(&a.id).cmp(&subject_str(&b.id)),
491            (Self::Relationship(a), Self::Relationship(b)) => a.element_id().cmp(&b.element_id()),
492            (Self::Path(a), Self::Path(b)) => a.relationships.len().cmp(&b.relationships.len()),
493            _ => self.cypher_cmp(other).unwrap_or(Ordering::Equal),
494        }
495    }
496
497    /// A key for grouping and `DISTINCT` (Cypher equivalence: `null` equals `null`, `1`
498    /// equals `1.0`).
499    pub fn group_key(&self) -> GroupKey {
500        match self {
501            Self::Null => GroupKey::Null,
502            Self::Bool(b) => GroupKey::Bool(*b),
503            Self::Int(i) => GroupKey::Int(*i),
504            Self::Float(f) => {
505                if f.fract() == 0.0 && f.abs() < 9.0e15 {
506                    GroupKey::Int(*f as i64)
507                } else if f.is_nan() {
508                    GroupKey::NaN
509                } else {
510                    GroupKey::Float(f.to_bits())
511                }
512            }
513            Self::String(s) => GroupKey::Str(s.clone()),
514            Self::Temporal(k, s) => GroupKey::Temporal(*k, s.clone()),
515            Self::List(items) => GroupKey::List(items.iter().map(Self::group_key).collect()),
516            Self::Map(m) => {
517                GroupKey::Map(m.iter().map(|(k, v)| (k.clone(), v.group_key())).collect())
518            }
519            Self::Node(n) => GroupKey::Entity(subject_str(&n.id)),
520            Self::Relationship(r) => GroupKey::Entity(r.element_id()),
521            Self::Path(p) => GroupKey::List(
522                p.nodes
523                    .iter()
524                    .map(|n| GroupKey::Entity(subject_str(&n.id)))
525                    .chain(
526                        p.relationships
527                            .iter()
528                            .map(|r| GroupKey::Entity(r.element_id())),
529                    )
530                    .collect(),
531            ),
532        }
533    }
534}
535
536/// See [`Value::group_key`].
537#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
538pub enum GroupKey {
539    Null,
540    Bool(bool),
541    Int(i64),
542    Float(u64),
543    NaN,
544    Str(String),
545    Temporal(TemporalKind, String),
546    List(Vec<GroupKey>),
547    Map(Vec<(String, GroupKey)>),
548    Entity(String),
549}
550
551impl fmt::Display for Value {
552    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
553        match self {
554            Self::Null => write!(f, "null"),
555            Self::Bool(b) => write!(f, "{b}"),
556            Self::Int(i) => write!(f, "{i}"),
557            Self::Float(x) => {
558                if x.fract() == 0.0 && x.is_finite() {
559                    write!(f, "{x:.1}")
560                } else {
561                    write!(f, "{x}")
562                }
563            }
564            Self::String(s) => write!(f, "'{s}'"),
565            Self::Temporal(_, s) => write!(f, "'{s}'"),
566            Self::List(items) => {
567                write!(f, "[")?;
568                for (i, v) in items.iter().enumerate() {
569                    if i > 0 {
570                        write!(f, ", ")?;
571                    }
572                    write!(f, "{v}")?;
573                }
574                write!(f, "]")
575            }
576            Self::Map(m) => {
577                write!(f, "{{")?;
578                for (i, (k, v)) in m.iter().enumerate() {
579                    if i > 0 {
580                        write!(f, ", ")?;
581                    }
582                    write!(f, "{k}: {v}")?;
583                }
584                write!(f, "}}")
585            }
586            Self::Node(n) => {
587                write!(f, "(")?;
588                for l in &n.labels {
589                    write!(f, ":{l}")?;
590                }
591                if !n.properties.is_empty() {
592                    if !n.labels.is_empty() {
593                        write!(f, " ")?;
594                    }
595                    write!(f, "{}", Value::Map(n.properties.clone()))?;
596                }
597                write!(f, ")")
598            }
599            Self::Relationship(r) => {
600                write!(f, "[:{}", r.rel_type)?;
601                if !r.properties.is_empty() {
602                    write!(f, " {}", Value::Map(r.properties.clone()))?;
603                }
604                write!(f, "]")
605            }
606            Self::Path(p) => {
607                write!(f, "<")?;
608                for (i, n) in p.nodes.iter().enumerate() {
609                    if i > 0 {
610                        let r = &p.relationships[i - 1];
611                        if r.start == n.id {
612                            write!(f, "<-{}-", Value::Relationship(r.clone()))?;
613                        } else {
614                            write!(f, "-{}->", Value::Relationship(r.clone()))?;
615                        }
616                    }
617                    write!(f, "{}", Value::Node(n.clone()))?;
618                }
619                write!(f, ">")
620            }
621        }
622    }
623}
624
625/// Parameters of a query, by name.
626pub type Params = BTreeMap<String, Value>;
627
628pub const REIFIES: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies";