use std::sync::Arc;
use littlegraph_core::{
NodeValue, PathValue, QueryResult as CoreQueryResult, RelationshipValue, Value,
};
use pyo3::exceptions::{PyIndexError, PyKeyError, PyTypeError};
use pyo3::prelude::*;
use pyo3::types::{PyAny, PyBool, PyDict, PyFloat, PyInt, PyList, PyString, PyTuple};
use crate::error::BindingError;
#[pyclass(frozen, module = "littlegraph._littlegraph")]
pub(crate) struct QueryResult {
columns: Arc<Vec<String>>,
rows: Vec<Py<Record>>,
}
#[pyclass(frozen, module = "littlegraph._littlegraph")]
pub(crate) struct Record {
columns: Arc<Vec<String>>,
values: Vec<Py<PyAny>>,
}
#[pyclass(frozen, module = "littlegraph._littlegraph")]
pub(crate) struct Node {
#[pyo3(get)]
element_id: String,
#[pyo3(get)]
record_id: Option<u64>,
labels: Vec<String>,
properties: Py<PyAny>,
}
#[pyclass(frozen, module = "littlegraph._littlegraph")]
pub(crate) struct Relationship {
#[pyo3(get)]
element_id: String,
#[pyo3(get)]
record_id: Option<u64>,
#[pyo3(get)]
start_node_element_id: String,
#[pyo3(get)]
end_node_element_id: String,
#[pyo3(get)]
start_node_record_id: Option<u64>,
#[pyo3(get)]
end_node_record_id: Option<u64>,
#[pyo3(get)]
r#type: String,
properties: Py<PyAny>,
}
#[pyclass(frozen, module = "littlegraph._littlegraph")]
pub(crate) struct Path {
nodes: Vec<Py<Node>>,
relationships: Vec<Py<Relationship>>,
}
pub(crate) fn result_to_python(
py: Python<'_>,
result: CoreQueryResult,
) -> PyResult<Py<QueryResult>> {
let columns = Arc::new(result.columns);
let mut rows = Vec::with_capacity(result.rows.len());
for row in result.rows {
let mut values = Vec::with_capacity(row.values.len());
for value in row.values {
values.push(value_to_python(py, value)?);
}
rows.push(Py::new(
py,
Record {
columns: columns.clone(),
values,
},
)?);
}
Py::new(py, QueryResult { columns, rows })
}
#[pymethods]
impl QueryResult {
#[getter]
fn columns(&self, py: Python<'_>) -> PyResult<Py<PyTuple>> {
Ok(PyTuple::new(py, &*self.columns)?.unbind())
}
fn __len__(&self) -> usize {
self.rows.len()
}
fn __getitem__(&self, index: isize, py: Python<'_>) -> PyResult<Py<Record>> {
let index = normalize_index(index, self.rows.len())?;
Ok(self.rows[index].clone_ref(py))
}
fn __iter__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
let rows = self
.rows
.iter()
.map(|row| row.clone_ref(py))
.collect::<Vec<_>>();
Ok(PyTuple::new(py, rows)?.call_method0("__iter__")?.unbind())
}
fn __repr__(&self) -> String {
format!(
"QueryResult(columns={:?}, rows={})",
self.columns,
self.rows.len()
)
}
}
#[pymethods]
impl Record {
fn __len__(&self) -> usize {
self.values.len()
}
fn __getitem__(&self, key: &Bound<'_, PyAny>, py: Python<'_>) -> PyResult<Py<PyAny>> {
if key.is_instance_of::<PyInt>() && !key.is_instance_of::<PyBool>() {
let index = key.extract::<isize>().map_err(|_| {
PyIndexError::new_err("record index is outside the supported range")
})?;
let index = normalize_index(index, self.values.len())?;
return Ok(self.values[index].clone_ref(py));
}
if key.is_instance_of::<PyString>() {
let key = key.extract::<String>()?;
let index = self
.columns
.iter()
.position(|column| column == &key)
.ok_or_else(|| PyKeyError::new_err(key))?;
return Ok(self.values[index].clone_ref(py));
}
Err(PyTypeError::new_err(
"record indices must be integers or column names",
))
}
fn keys(&self, py: Python<'_>) -> PyResult<Py<PyTuple>> {
Ok(PyTuple::new(py, &*self.columns)?.unbind())
}
fn values(&self, py: Python<'_>) -> PyResult<Py<PyTuple>> {
let values = self
.values
.iter()
.map(|value| value.clone_ref(py))
.collect::<Vec<_>>();
Ok(PyTuple::new(py, values)?.unbind())
}
fn items(&self, py: Python<'_>) -> PyResult<Py<PyTuple>> {
let items = self
.columns
.iter()
.zip(&self.values)
.map(|(column, value)| (column, value.clone_ref(py)))
.collect::<Vec<_>>();
Ok(PyTuple::new(py, items)?.unbind())
}
fn data(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
let data = PyDict::new(py);
for (column, value) in self.columns.iter().zip(&self.values) {
data.set_item(column, value)?;
}
Ok(data.unbind())
}
fn __iter__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
Ok(self.values(py)?.bind(py).call_method0("__iter__")?.unbind())
}
fn __repr__(&self) -> String {
format!("Record(columns={:?})", self.columns)
}
}
#[pymethods]
impl Node {
#[getter]
fn labels(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
Ok(py
.get_type::<pyo3::types::PyFrozenSet>()
.call1((PyTuple::new(py, &self.labels)?,))?
.unbind())
}
#[getter]
fn properties(&self, py: Python<'_>) -> Py<PyAny> {
self.properties.clone_ref(py)
}
fn __getitem__(&self, key: &str, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_item(&self.properties, key, py)
}
fn keys(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_method(&self.properties, "keys", py)
}
fn values(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_method(&self.properties, "values", py)
}
fn items(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_method(&self.properties, "items", py)
}
#[pyo3(signature = (key, default=None))]
fn get(
&self,
key: &str,
default: Option<&Bound<'_, PyAny>>,
py: Python<'_>,
) -> PyResult<Py<PyAny>> {
property_get(&self.properties, key, default, py)
}
fn __len__(&self, py: Python<'_>) -> PyResult<usize> {
self.properties.bind(py).len()
}
fn __iter__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_method(&self.properties, "__iter__", py)
}
fn __repr__(&self) -> String {
format!(
"Node(element_id={:?}, labels={:?})",
self.element_id, self.labels
)
}
}
#[pymethods]
impl Relationship {
#[getter]
fn properties(&self, py: Python<'_>) -> Py<PyAny> {
self.properties.clone_ref(py)
}
fn __getitem__(&self, key: &str, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_item(&self.properties, key, py)
}
fn keys(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_method(&self.properties, "keys", py)
}
fn values(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_method(&self.properties, "values", py)
}
fn items(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_method(&self.properties, "items", py)
}
#[pyo3(signature = (key, default=None))]
fn get(
&self,
key: &str,
default: Option<&Bound<'_, PyAny>>,
py: Python<'_>,
) -> PyResult<Py<PyAny>> {
property_get(&self.properties, key, default, py)
}
fn __len__(&self, py: Python<'_>) -> PyResult<usize> {
self.properties.bind(py).len()
}
fn __iter__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
property_method(&self.properties, "__iter__", py)
}
fn __repr__(&self) -> String {
format!(
"Relationship(element_id={:?}, type={:?})",
self.element_id, self.r#type
)
}
}
fn property_item(properties: &Py<PyAny>, key: &str, py: Python<'_>) -> PyResult<Py<PyAny>> {
Ok(properties.bind(py).get_item(key)?.unbind())
}
fn property_method(properties: &Py<PyAny>, method: &str, py: Python<'_>) -> PyResult<Py<PyAny>> {
Ok(properties.bind(py).call_method0(method)?.unbind())
}
fn property_get(
properties: &Py<PyAny>,
key: &str,
default: Option<&Bound<'_, PyAny>>,
py: Python<'_>,
) -> PyResult<Py<PyAny>> {
let default = default
.map(|value| value.clone().unbind())
.unwrap_or_else(|| py.None());
Ok(properties
.bind(py)
.call_method1("get", (key, default))?
.unbind())
}
#[pymethods]
impl Path {
#[getter]
fn nodes(&self, py: Python<'_>) -> PyResult<Py<PyTuple>> {
let nodes = self
.nodes
.iter()
.map(|node| node.clone_ref(py))
.collect::<Vec<_>>();
Ok(PyTuple::new(py, nodes)?.unbind())
}
#[getter]
fn relationships(&self, py: Python<'_>) -> PyResult<Py<PyTuple>> {
let relationships = self
.relationships
.iter()
.map(|relationship| relationship.clone_ref(py))
.collect::<Vec<_>>();
Ok(PyTuple::new(py, relationships)?.unbind())
}
fn __repr__(&self) -> String {
format!(
"Path(nodes={}, relationships={})",
self.nodes.len(),
self.relationships.len()
)
}
}
fn value_to_python(py: Python<'_>, value: Value) -> PyResult<Py<PyAny>> {
match value {
Value::Null => Ok(py.None()),
Value::Boolean(value) => Ok(PyBool::new(py, value).to_owned().unbind().into_any()),
Value::Integer(value) => Ok(PyInt::new(py, value).unbind().into_any()),
Value::Float(value) => Ok(PyFloat::new(py, value).unbind().into_any()),
Value::String(value) => Ok(PyString::new(py, &value).unbind().into_any()),
Value::List(values) => {
let values = values
.into_iter()
.map(|value| value_to_python(py, value))
.collect::<PyResult<Vec<_>>>()?;
Ok(PyList::new(py, values)?.unbind().into_any())
}
Value::Map(values) => Ok(properties_to_python(py, values)?.unbind().into_any()),
Value::Node(node) => Ok(node_to_python(py, node)?.into_any()),
Value::Relationship(relationship) => {
Ok(relationship_to_python(py, relationship)?.into_any())
}
Value::Path(path) => Ok(path_to_python(py, path)?.into_any()),
_ => Err(BindingError::unsupported_value(
"query result contains a value unsupported by this binding",
)
.into_pyerr(py)),
}
}
fn node_to_python(py: Python<'_>, node: NodeValue) -> PyResult<Py<Node>> {
Py::new(
py,
Node {
element_id: node.id,
record_id: node.record_id,
labels: node.labels,
properties: readonly_properties(py, node.properties)?,
},
)
}
fn relationship_to_python(
py: Python<'_>,
relationship: RelationshipValue,
) -> PyResult<Py<Relationship>> {
Py::new(
py,
Relationship {
element_id: relationship.id,
record_id: relationship.record_id,
start_node_element_id: relationship.start,
end_node_element_id: relationship.end,
start_node_record_id: relationship.start_record_id,
end_node_record_id: relationship.end_record_id,
r#type: relationship.r#type,
properties: readonly_properties(py, relationship.properties)?,
},
)
}
fn path_to_python(py: Python<'_>, path: PathValue) -> PyResult<Py<Path>> {
let nodes = path
.nodes
.into_iter()
.map(|node| node_to_python(py, node))
.collect::<PyResult<Vec<_>>>()?;
let relationships = path
.relationships
.into_iter()
.map(|relationship| relationship_to_python(py, relationship))
.collect::<PyResult<Vec<_>>>()?;
Py::new(
py,
Path {
nodes,
relationships,
},
)
}
fn properties_to_python(
py: Python<'_>,
properties: std::collections::BTreeMap<String, Value>,
) -> PyResult<Bound<'_, PyDict>> {
let dictionary = PyDict::new(py);
for (key, value) in properties {
dictionary.set_item(key, value_to_python(py, value)?)?;
}
Ok(dictionary)
}
fn readonly_properties(
py: Python<'_>,
properties: std::collections::BTreeMap<String, Value>,
) -> PyResult<Py<PyAny>> {
let dictionary = properties_to_python(py, properties)?;
Ok(py
.import("types")?
.getattr("MappingProxyType")?
.call1((dictionary,))?
.unbind())
}
fn normalize_index(index: isize, length: usize) -> PyResult<usize> {
let length =
isize::try_from(length).map_err(|_| PyIndexError::new_err("index out of range"))?;
let index = if index < 0 { length + index } else { index };
if !(0..length).contains(&index) {
return Err(PyIndexError::new_err("index out of range"));
}
Ok(index as usize)
}
#[cfg(test)]
mod tests {
use littlegraph_core::{NodeValue, PathValue, Record as CoreRecord, RelationshipValue};
use super::*;
#[test]
#[allow(deprecated)]
fn converts_every_current_core_value_variant() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let node = NodeValue::new(
"node-1".to_owned(),
vec!["Person".to_owned()],
Default::default(),
);
let relationship = RelationshipValue::new(
"relationship-1".to_owned(),
"node-1".to_owned(),
"node-2".to_owned(),
"KNOWS".to_owned(),
Default::default(),
);
let result = CoreQueryResult {
columns: vec![
"null",
"boolean",
"integer",
"float",
"string",
"list",
"map",
"node",
"relationship",
"path",
]
.into_iter()
.map(str::to_owned)
.collect(),
rows: vec![CoreRecord {
values: vec![
Value::Null,
Value::Boolean(true),
Value::Integer(42),
Value::Float(1.5),
Value::String("value".to_owned()),
Value::List(vec![Value::Integer(1)]),
Value::Map(std::collections::BTreeMap::from([(
"key".to_owned(),
Value::String("value".to_owned()),
)])),
Value::Node(node.clone()),
Value::Relationship(relationship.clone()),
Value::Path(PathValue {
nodes: vec![node],
relationships: vec![relationship],
}),
],
}],
};
let converted = result_to_python(py, result).unwrap();
let converted = converted.borrow(py);
let record = converted.rows[0].borrow(py);
assert_eq!(record.values[2].extract::<i64>(py).unwrap(), 42);
let path = record.values[9].extract::<PyRef<'_, Path>>(py).unwrap();
assert_eq!(path.nodes.len(), 1);
assert_eq!(path.relationships.len(), 1);
});
}
}