Skip to main content

cozo/runtime/db/
named_rows.rs

1/*
2 * Copyright 2022, The Cozo Project Authors.
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
5 * If a copy of the MPL was not distributed with this file,
6 * You can obtain one at https://mozilla.org/MPL/2.0/.
7 */
8
9use std::collections::BTreeMap;
10
11use itertools::Itertools;
12use miette::{miette, Result};
13use serde_json::json;
14
15use crate::data::json::JsonValue;
16use crate::data::tuple::Tuple;
17use crate::data::value::DataValue;
18
19#[derive(serde_derive::Serialize, serde_derive::Deserialize, Debug, Clone, Default)]
20/// Rows in a relation, together with headers for the fields.
21pub struct NamedRows {
22    /// The headers
23    pub headers: Vec<String>,
24    /// The rows
25    pub rows: Vec<Tuple>,
26    /// Contains the next named rows, if exists
27    pub next: Option<Box<NamedRows>>,
28}
29
30impl IntoIterator for NamedRows {
31    type Item = Tuple;
32    type IntoIter = std::vec::IntoIter<Self::Item>;
33
34    fn into_iter(self) -> Self::IntoIter {
35        self.rows.into_iter()
36    }
37}
38
39impl NamedRows {
40    /// create a named rows with the given headers and rows
41    pub fn new(headers: Vec<String>, rows: Vec<Tuple>) -> Self {
42        Self {
43            headers,
44            rows,
45            next: None,
46        }
47    }
48
49    /// If there are more named rows after the current one
50    pub fn has_more(&self) -> bool {
51        self.next.is_some()
52    }
53
54    /// convert a chain of named rows to individual named rows
55    pub fn flatten(self) -> Vec<Self> {
56        let mut collected = vec![];
57        let mut current = self;
58        loop {
59            let nxt = current.next.take();
60            collected.push(current);
61            if let Some(n) = nxt {
62                current = *n;
63            } else {
64                break;
65            }
66        }
67        collected
68    }
69
70    /// Convert to a JSON object
71    pub fn into_json(self) -> JsonValue {
72        let nxt = match self.next {
73            None => json!(null),
74            Some(more) => more.into_json(),
75        };
76        let rows = self
77            .rows
78            .into_iter()
79            .map(|row| row.into_iter().map(JsonValue::from).collect::<JsonValue>())
80            .collect::<JsonValue>();
81        json!({
82            "headers": self.headers,
83            "rows": rows,
84            "next": nxt,
85        })
86    }
87    /// Make named rows from JSON
88    pub fn from_json(value: &JsonValue) -> Result<Self> {
89        let headers = value
90            .get("headers")
91            .ok_or_else(|| miette!("NamedRows requires 'headers' field"))?;
92        let headers = headers
93            .as_array()
94            .ok_or_else(|| miette!("'headers' field must be an array"))?;
95        let headers = headers
96            .iter()
97            .map(|h| -> Result<String> {
98                let h = h
99                    .as_str()
100                    .ok_or_else(|| miette!("'headers' field must be an array of strings"))?;
101                Ok(h.to_string())
102            })
103            .try_collect()?;
104        let rows = value
105            .get("rows")
106            .ok_or_else(|| miette!("NamedRows requires 'rows' field"))?;
107        let rows = rows
108            .as_array()
109            .ok_or_else(|| miette!("'rows' field must be an array"))?;
110        let rows = rows
111            .iter()
112            .map(|row| -> Result<Vec<DataValue>> {
113                let row = row
114                    .as_array()
115                    .ok_or_else(|| miette!("'rows' field must be an array of arrays"))?;
116                Ok(row.iter().map(DataValue::from).collect_vec())
117            })
118            .try_collect()?;
119        Ok(Self {
120            headers,
121            rows,
122            next: None,
123        })
124    }
125
126    /// Create a query and parameters to apply an operation (insert, put, delete, rm) to a stored
127    /// relation with the named rows.
128    pub fn into_payload(self, relation: &str, op: &str) -> Payload {
129        let cols_str = self.headers.join(", ");
130        let query = format!("?[{cols_str}] <- $data :{op} {relation} {{ {cols_str} }}");
131        let data = DataValue::List(self.rows.into_iter().map(|r| DataValue::List(r)).collect());
132        (query, [("data".to_string(), data)].into())
133    }
134}
135
136/// The query and parameters.
137pub type Payload = (String, BTreeMap<String, DataValue>);
138
139/// Commands to be sent to a multi-transaction
140#[derive(Eq, PartialEq, Debug)]
141pub enum TransactionPayload {
142    /// Commit the current transaction
143    Commit,
144    /// Abort the current transaction
145    Abort,
146    /// Run a query inside the transaction
147    Query(Payload),
148}