cypher_dto/
node.rs

1use crate::{FieldSet, StampMode};
2use neo4rs::{Node, Query};
3
4/// A node [Entity].
5pub trait NodeEntity: FieldSet + TryFrom<Node> {
6    type Id: NodeId<T = Self>;
7
8    /// Get the [NodeId] for this entity.
9    ///
10    /// This is less efficient than using self.into(), but is useful when you
11    /// don't want to consume the entity.
12    ///
13    /// The implementation in derive will clone the individual ID fields as
14    /// necessary.
15    fn identifier(&self) -> Self::Id;
16
17    /// Convenience method for `self.into()`.
18    fn into_identifier(self) -> Self::Id {
19        self.into()
20    }
21
22    fn create(&self) -> Query {
23        let q = Query::new(format!(
24            "CREATE (n:{})",
25            Self::to_query_obj(None, StampMode::Create),
26        ));
27        self.add_values_to_params(q, None, StampMode::Create)
28    }
29
30    /// Treats the current values as the desired values and does a merge update (`SET n += ...`).
31    ///
32    /// NOTE: Does not support changing the identifier fields.
33    fn update(&self) -> Query {
34        let q = Query::new(format!(
35            "MATCH (n:{}) SET n += {{ {} }}",
36            Self::Id::to_query_obj(None, StampMode::Read),
37            Self::to_query_fields(None, StampMode::Update),
38        ));
39        self.add_values_to_params(q, None, StampMode::Update)
40    }
41}
42
43/// The identifying fields of a [NodeEntity].
44pub trait NodeId: FieldSet + From<Self::T> + TryFrom<Node> {
45    type T: NodeEntity<Id = Self>;
46
47    /// Read a [NodeEntity] by its id, using "n" as the variable for the node.
48    fn read(&self) -> Query {
49        let q = Query::new(format!(
50            "MATCH (n:{}) RETURN n",
51            Self::to_query_obj(None, StampMode::Read)
52        ));
53        self.add_values_to_params(q, None, StampMode::Read)
54    }
55
56    /// Delete a [NodeEntity] by its id, using "n" as the variable for the node.
57    fn delete(&self) -> Query {
58        let q = Query::new(format!(
59            "MATCH (n:{}) DETACH DELETE n",
60            Self::to_query_obj(None, StampMode::Read)
61        ));
62        self.add_values_to_params(q, None, StampMode::Read)
63    }
64}