1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
use crate::{
    core::{
        entities::LayerIds,
        storage::timeindex::TimeIndexEntry,
        utils::errors::{
            GraphError,
            GraphError::{EdgeExistsError, NodeExistsError},
        },
        OptionAsStr,
    },
    db::{
        api::{
            mutation::internal::{
                InternalAdditionOps, InternalDeletionOps, InternalPropertyAdditionOps,
            },
            view::{internal::InternalMaterialize, IntoDynamic, StaticGraphViewOps},
        },
        graph::{edge::EdgeView, node::NodeView},
    },
    prelude::{AdditionOps, EdgeViewOps, NodeViewOps},
};

pub trait ImportOps:
    StaticGraphViewOps
    + InternalAdditionOps
    + InternalDeletionOps
    + InternalPropertyAdditionOps
    + InternalMaterialize
{
    /// Imports a single node into the graph.
    ///
    /// This function takes a reference to a node and an optional boolean flag `force`.
    /// If `force` is `Some(false)` or `None`, the function will return an error if the node already exists in the graph.
    /// If `force` is `Some(true)`, the function will overwrite the existing node in the graph.
    ///
    /// # Arguments
    ///
    /// * `node` - A reference to the node to be imported.
    /// * `force` - An optional boolean flag. If `Some(true)`, the function will overwrite the existing node.
    ///
    /// # Returns
    ///
    /// A `Result` which is `Ok` if the node was successfully imported, and `Err` otherwise.
    fn import_node<GHH: StaticGraphViewOps + IntoDynamic, GH: StaticGraphViewOps + IntoDynamic>(
        &self,
        node: &NodeView<GHH, GH>,
        force: bool,
    ) -> Result<NodeView<Self, Self>, GraphError>;

    /// Imports multiple nodes into the graph.
    ///
    /// This function takes a vector of references to nodes and an optional boolean flag `force`.
    /// If `force` is `Some(false)` or `None`, the function will return an error if any of the nodes already exist in the graph.
    /// If `force` is `Some(true)`, the function will overwrite the existing nodes in the graph.
    ///
    /// # Arguments
    ///
    /// * `nodes` - A vector of references to the nodes to be imported.
    /// * `force` - An optional boolean flag. If `Some(true)`, the function will overwrite the existing nodes.
    ///
    /// # Returns
    ///
    /// A `Result` which is `Ok` if the nodes were successfully imported, and `Err` otherwise.
    fn import_nodes<GHH: StaticGraphViewOps + IntoDynamic, GH: StaticGraphViewOps + IntoDynamic>(
        &self,
        node: Vec<&NodeView<GHH, GH>>,
        force: bool,
    ) -> Result<Vec<NodeView<Self, Self>>, GraphError>;

    /// Imports a single edge into the graph.
    ///
    /// This function takes a reference to an edge and an optional boolean flag `force`.
    /// If `force` is `Some(false)` or `None`, the function will return an error if the edge already exists in the graph.
    /// If `force` is `Some(true)`, the function will overwrite the existing edge in the graph.
    ///
    /// # Arguments
    ///
    /// * `edge` - A reference to the edge to be imported.
    /// * `force` - An optional boolean flag. If `Some(true)`, the function will overwrite the existing edge.
    ///
    /// # Returns
    ///
    /// A `Result` which is `Ok` if the edge was successfully imported, and `Err` otherwise.
    fn import_edge<GHH: StaticGraphViewOps + IntoDynamic, GH: StaticGraphViewOps + IntoDynamic>(
        &self,
        edge: &EdgeView<GHH, GH>,
        force: bool,
    ) -> Result<EdgeView<Self, Self>, GraphError>;

    /// Imports multiple edges into the graph.
    ///
    /// This function takes a vector of references to edges and an optional boolean flag `force`.
    /// If `force` is `Some(false)` or `None`, the function will return an error if any of the edges already exist in the graph.
    /// If `force` is `Some(true)`, the function will overwrite the existing edges in the graph.
    ///
    /// # Arguments
    ///
    /// * `edges` - A vector of references to the edges to be imported.
    /// * `force` - An optional boolean flag. If `Some(true)`, the function will overwrite the existing edges.
    ///
    /// # Returns
    ///
    /// A `Result` which is `Ok` if the edges were successfully imported, and `Err` otherwise.
    fn import_edges<GHH: StaticGraphViewOps + IntoDynamic, GH: StaticGraphViewOps + IntoDynamic>(
        &self,
        edges: Vec<&EdgeView<GHH, GH>>,
        force: bool,
    ) -> Result<Vec<EdgeView<Self, Self>>, GraphError>;
}

impl<
        G: StaticGraphViewOps
            + InternalAdditionOps
            + InternalDeletionOps
            + InternalPropertyAdditionOps
            + InternalMaterialize,
    > ImportOps for G
{
    fn import_node<GHH: StaticGraphViewOps + IntoDynamic, GH: StaticGraphViewOps + IntoDynamic>(
        &self,
        node: &NodeView<GHH, GH>,
        force: bool,
    ) -> Result<NodeView<G, G>, GraphError> {
        if !force && self.node(node.id()).is_some() {
            return Err(NodeExistsError(node.id()));
        }

        let node_internal =
            self.resolve_node(node.id(), node.graph.core_node_arc(node.node).name.as_str());
        let node_internal_type_id = self
            .resolve_node_type(node_internal, node.node_type().as_str())
            .unwrap_or(0usize);

        for h in node.history() {
            let t = TimeIndexEntry::from_input(self, h)?;
            self.internal_add_node(t, node_internal, vec![], node_internal_type_id)?;
        }
        for (name, prop_view) in node.properties().temporal().iter() {
            let old_prop_id = node
                .graph
                .node_meta()
                .temporal_prop_meta()
                .get_id(&name)
                .unwrap();
            let dtype = node
                .graph
                .node_meta()
                .temporal_prop_meta()
                .get_dtype(old_prop_id)
                .unwrap();
            let new_prop_id = self.resolve_node_property(&name, dtype, false)?;
            for (h, prop) in prop_view.iter() {
                let new_prop = self.process_prop_value(prop);
                let t = TimeIndexEntry::from_input(self, h)?;
                self.internal_add_node(
                    t,
                    node_internal,
                    vec![(new_prop_id, new_prop)],
                    node_internal_type_id,
                )?;
            }
        }
        self.node(node.id())
            .expect("node added")
            .add_constant_properties(node.properties().constant())?;

        Ok(self.node(node.id()).unwrap())
    }

    fn import_nodes<GHH: StaticGraphViewOps + IntoDynamic, GH: StaticGraphViewOps + IntoDynamic>(
        &self,
        nodes: Vec<&NodeView<GHH, GH>>,
        force: bool,
    ) -> Result<Vec<NodeView<G, G>>, GraphError> {
        let mut added_nodes = vec![];
        for node in nodes {
            let res = self.import_node(node, force);
            added_nodes.push(res.unwrap())
        }
        Ok(added_nodes)
    }

    fn import_edge<GHH: StaticGraphViewOps + IntoDynamic, GH: StaticGraphViewOps + IntoDynamic>(
        &self,
        edge: &EdgeView<GHH, GH>,
        force: bool,
    ) -> Result<EdgeView<Self, Self>, GraphError> {
        // make sure we preserve all layers even if they are empty
        // skip default layer
        for layer in edge.graph.unique_layers().skip(1) {
            self.resolve_layer(Some(&layer));
        }
        if !force && self.has_edge(edge.src().name(), edge.dst().name()) {
            return Err(EdgeExistsError(edge.src().id(), edge.dst().id()));
        }
        // Add edges first so we definitely have all associated nodes (important in case of persistent edges)
        // FIXME: this needs to be verified
        for ee in edge.explode_layers() {
            let layer_id = *ee.edge.layer().expect("exploded layers");
            let layer_ids = LayerIds::One(layer_id);
            let layer_name = self.get_layer_name(layer_id);
            let layer_name: Option<&str> = if layer_id == 0 {
                None
            } else {
                Some(&layer_name)
            };
            for ee in ee.explode() {
                self.add_edge(
                    ee.time().expect("exploded edge"),
                    ee.src().name(),
                    ee.dst().name(),
                    ee.properties().temporal().collect_properties(),
                    layer_name,
                )?;
            }

            if self.include_deletions() {
                for t in edge.graph.edge_deletion_history(edge.edge, &layer_ids) {
                    let ti = TimeIndexEntry::from_input(self, t)?;
                    let src_id = self.resolve_node(edge.src().id(), Some(&edge.src().name()));
                    let dst_id = self.resolve_node(edge.dst().id(), Some(&edge.dst().name()));
                    let layer = self.resolve_layer(layer_name);
                    self.internal_delete_edge(ti, src_id, dst_id, layer)?;
                }
            }

            self.edge(ee.src().id(), ee.dst().id())
                .expect("edge added")
                .add_constant_properties(ee.properties().constant(), layer_name)?;
        }
        Ok(self.edge(edge.src().name(), edge.dst().name()).unwrap())
    }

    fn import_edges<GHH: StaticGraphViewOps + IntoDynamic, GH: StaticGraphViewOps + IntoDynamic>(
        &self,
        edges: Vec<&EdgeView<GHH, GH>>,
        force: bool,
    ) -> Result<Vec<EdgeView<Self, Self>>, GraphError> {
        let mut added_edges = vec![];
        for edge in edges {
            let res = self.import_edge(edge, force);
            added_edges.push(res.unwrap())
        }
        Ok(added_edges)
    }
}