Skip to main content

sqlitegraph/graph/
edge_ops.rs

1//! Edge CRUD operations for SqliteGraph.
2
3use rusqlite::params;
4
5use crate::errors::SqliteGraphError;
6
7use super::{
8    SqliteGraph,
9    types::{GraphEdge, row_to_edge, validate_edge},
10};
11
12impl SqliteGraph {
13    pub fn insert_edge(&self, edge: &GraphEdge) -> Result<i64, SqliteGraphError> {
14        validate_edge(edge)?;
15        if !self.entity_exists(edge.from_id)? || !self.entity_exists(edge.to_id)? {
16            return Err(SqliteGraphError::invalid_input(
17                "edge endpoints must reference existing entities",
18            ));
19        }
20        let data = serde_json::to_string(&edge.data)
21            .map_err(|e| SqliteGraphError::invalid_input(e.to_string()))?;
22        self.connection()
23            .execute(
24                "INSERT INTO graph_edges(from_id, to_id, edge_type, data) VALUES(?1, ?2, ?3, ?4)",
25                params![edge.from_id, edge.to_id, edge.edge_type.as_str(), data],
26            )
27            .map_err(|e| SqliteGraphError::query(e.to_string()))?;
28        self.invalidate_caches();
29        Ok(self.connection().last_insert_rowid())
30    }
31
32    pub fn get_edge(&self, id: i64) -> Result<GraphEdge, SqliteGraphError> {
33        self.connection()
34            .query_row(
35                "SELECT id, from_id, to_id, edge_type, data FROM graph_edges WHERE id=?1",
36                params![id],
37                row_to_edge,
38            )
39            .map_err(|err| match err {
40                rusqlite::Error::QueryReturnedNoRows => {
41                    SqliteGraphError::not_found(format!("edge {id}"))
42                }
43                other => SqliteGraphError::query(other.to_string()),
44            })
45    }
46
47    pub fn delete_edge(&self, id: i64) -> Result<(), SqliteGraphError> {
48        let affected = self
49            .connection()
50            .execute("DELETE FROM graph_edges WHERE id=?1", params![id])
51            .map_err(|e| SqliteGraphError::query(e.to_string()))?;
52        if affected == 0 {
53            return Err(SqliteGraphError::not_found(format!("edge {id}")));
54        }
55        self.invalidate_caches();
56        Ok(())
57    }
58}