Skip to main content

sqlite_graphrag/commands/
link.rs

1//! Handler for the `link` CLI subcommand.
2
3use crate::constants::DEFAULT_RELATION_WEIGHT;
4use crate::entity_type::EntityType;
5use crate::errors::AppError;
6use crate::i18n::{errors_msg, validation};
7use crate::output::{self, OutputFormat};
8use crate::paths::AppPaths;
9use crate::storage::connection::open_rw;
10use crate::storage::entities;
11use crate::storage::entities::NewEntity;
12use rusqlite::params;
13use serde::Serialize;
14
15#[derive(clap::Args)]
16#[command(after_long_help = "EXAMPLES:\n  \
17    # Link two existing graph entities (extracted by GLiNER NER during `remember`)\n  \
18    sqlite-graphrag link --from oauth-flow --to refresh-tokens --relation related\n\n  \
19    # Auto-create entities that don't exist yet\n  \
20    sqlite-graphrag link --from concept-a --to concept-b --relation depends-on --create-missing\n\n  \
21    # Specify entity type for auto-created entities\n  \
22    sqlite-graphrag link --from alice --to acme-corp --relation related --create-missing --entity-type person\n\n  \
23    # Use a custom (non-canonical) relation type\n  \
24    sqlite-graphrag link --from module-a --to module-b --relation implements --create-missing\n\n  \
25    # If the entity does not exist and --create-missing is not set, the command fails with exit 4.\n  \
26    # To list current entity names:\n  \
27    sqlite-graphrag graph entities | jaq '.entities[].name'\n\n  \
28NOTE:\n  \
29    --from and --to expect ENTITY names (graph nodes), not memory names.\n  \
30    Memory names are managed via remember/read/edit/forget; entities are auto-extracted\n  \
31    by GLiNER NER from memory bodies or auto-created via --create-missing.")]
32pub struct LinkArgs {
33    /// Source ENTITY name (graph node, not memory). Entities are extracted by GLiNER NER during
34    /// `remember` or auto-created via `--create-missing`. Use `graph entities` to list
35    /// available entity names. Also accepts the alias `--name`.
36    #[arg(long, alias = "name")]
37    pub from: String,
38    /// Target ENTITY name (graph node, not memory). See `--from` for sourcing entity names.
39    #[arg(long)]
40    pub to: String,
41    /// Relation type between entities. Canonical values: applies-to, uses,
42    /// depends-on, causes, fixes, contradicts, supports, follows, related,
43    /// mentions, replaces, tracked-in. Any kebab-case or snake_case string
44    /// is also accepted as a custom relation.
45    #[arg(long, value_parser = crate::parsers::parse_relation, value_name = "RELATION")]
46    pub relation: String,
47    #[arg(long)]
48    pub weight: Option<f64>,
49    #[arg(long)]
50    pub namespace: Option<String>,
51    #[arg(long, value_enum, default_value = "json")]
52    pub format: OutputFormat,
53    #[arg(long, hide = true, help = "No-op; JSON is always emitted on stdout")]
54    pub json: bool,
55    #[arg(long, env = "SQLITE_GRAPHRAG_DB_PATH")]
56    pub db: Option<String>,
57    /// Auto-create entities when they do not exist. Created entities default to
58    /// type `concept` unless `--entity-type` specifies a different type.
59    #[arg(long, default_value_t = false)]
60    pub create_missing: bool,
61    /// Entity type assigned to auto-created entities (only effective with `--create-missing`).
62    #[arg(long, value_enum, default_value = "concept")]
63    pub entity_type: EntityType,
64    /// Reject non-canonical relation types with exit 1.
65    ///
66    /// When set, any relation not in the canonical list causes an immediate error.
67    /// Canonical values: applies-to, uses, depends-on, causes, fixes, contradicts,
68    /// supports, follows, related, mentions, replaces, tracked-in.
69    #[arg(
70        long,
71        default_value_t = false,
72        help = "Reject non-canonical relation types with exit 1"
73    )]
74    pub strict_relations: bool,
75    /// Emit a warning (but do not reject) when creating an edge would push either endpoint
76    /// entity above this degree. Default 50. Set 0 to disable the check.
77    #[arg(long, default_value_t = 50, value_name = "N")]
78    pub max_entity_degree: u32,
79}
80
81#[derive(Serialize)]
82struct LinkResponse {
83    action: String,
84    from: String,
85    to: String,
86    relation: String,
87    weight: f64,
88    namespace: String,
89    /// Total execution time in milliseconds from handler start to serialisation.
90    elapsed_ms: u64,
91    /// Entity names that were auto-created by `--create-missing`.
92    #[serde(skip_serializing_if = "Vec::is_empty")]
93    created_entities: Vec<String>,
94    /// Non-fatal warnings (e.g. non-canonical relation type).
95    #[serde(skip_serializing_if = "Vec::is_empty")]
96    warnings: Vec<String>,
97}
98
99pub fn run(args: LinkArgs) -> Result<(), AppError> {
100    let inicio = std::time::Instant::now();
101    tracing::debug!(target: "link", from = %args.from, to = %args.to, relation = %args.relation, "creating relationship");
102    let namespace = crate::namespace::resolve_namespace(args.namespace.as_deref())?;
103    let paths = AppPaths::resolve(args.db.as_deref())?;
104
105    let norm_from = crate::parsers::normalize_entity_name(&args.from);
106    let norm_to = crate::parsers::normalize_entity_name(&args.to);
107
108    if norm_from == norm_to {
109        return Err(AppError::Validation(validation::self_referential_link()));
110    }
111
112    let weight = args.weight.unwrap_or(DEFAULT_RELATION_WEIGHT);
113    if !(0.0..=1.0).contains(&weight) {
114        return Err(AppError::Validation(validation::invalid_link_weight(
115            weight,
116        )));
117    }
118    if weight >= 0.95 {
119        tracing::warn!(target: "link",
120            weight = weight,
121            "weight >= 0.95 compresses the scoring range; consider using a value below 0.95"
122        );
123    }
124    if weight <= 0.05 {
125        tracing::warn!(target: "link",
126            weight = weight,
127            "weight <= 0.05 may be too weak to influence traversal; consider using a value above 0.05"
128        );
129    }
130
131    crate::storage::connection::ensure_db_ready(&paths)?;
132
133    let mut warnings: Vec<String> = Vec::with_capacity(2);
134    let is_canonical = crate::parsers::is_canonical_relation(&args.relation);
135    if !is_canonical {
136        if args.strict_relations {
137            return Err(AppError::Validation(format!(
138                "non-canonical relation '{}': use --strict-relations=false or choose from: {}",
139                args.relation,
140                crate::parsers::CANONICAL_RELATIONS.join(", ")
141            )));
142        }
143        warnings.push(format!("non-canonical relation '{}'", args.relation));
144        tracing::warn!(target: "link",
145            relation = %args.relation,
146            "non-canonical relation accepted; consider using a well-known value"
147        );
148    }
149    let relation_str = &args.relation;
150
151    let mut conn = open_rw(&paths.db)?;
152    let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
153
154    let mut created_entities: Vec<String> = Vec::with_capacity(2);
155
156    if args.entity_type.as_str() == "memory" {
157        tracing::warn!(target: "link",
158            entity_type = "memory",
159            "entity_type 'memory' may conflict with memory table semantics; consider using 'concept' or another type"
160        );
161    }
162
163    let source_id = match entities::find_entity_id(&tx, &namespace, &norm_from)? {
164        Some(id) => id,
165        None if args.create_missing => {
166            let new_entity = NewEntity {
167                name: norm_from.clone(),
168                entity_type: args.entity_type,
169                description: None,
170            };
171            created_entities.push(norm_from.clone());
172            entities::upsert_entity(&tx, &namespace, &new_entity)?
173        }
174        None => {
175            return Err(AppError::NotFound(errors_msg::entity_not_found(
176                &norm_from, &namespace,
177            )));
178        }
179    };
180
181    let target_id = match entities::find_entity_id(&tx, &namespace, &norm_to)? {
182        Some(id) => id,
183        None if args.create_missing => {
184            let new_entity = NewEntity {
185                name: norm_to.clone(),
186                entity_type: args.entity_type,
187                description: None,
188            };
189            created_entities.push(norm_to.clone());
190            entities::upsert_entity(&tx, &namespace, &new_entity)?
191        }
192        None => {
193            return Err(AppError::NotFound(errors_msg::entity_not_found(
194                &norm_to, &namespace,
195            )));
196        }
197    };
198
199    let (rel_id, was_created) = entities::create_or_fetch_relationship(
200        &tx,
201        &namespace,
202        source_id,
203        target_id,
204        relation_str,
205        weight,
206        None,
207    )?;
208
209    let actual_weight: f64 = tx.query_row(
210        "SELECT weight FROM relationships WHERE id = ?1",
211        params![rel_id],
212        |r| r.get(0),
213    )?;
214
215    if was_created {
216        entities::recalculate_degree(&tx, source_id)?;
217        entities::recalculate_degree(&tx, target_id)?;
218
219        if args.max_entity_degree > 0 {
220            let cap = args.max_entity_degree as i64;
221            for (entity_id, entity_name) in [(source_id, &norm_from), (target_id, &norm_to)] {
222                let degree: i64 = tx.query_row(
223                    "SELECT degree FROM entities WHERE id = ?1",
224                    params![entity_id],
225                    |r| r.get(0),
226                )?;
227                if degree > cap {
228                    output::emit_progress(&format!(
229                        "WARNING: entity '{entity_name}' degree {degree} exceeds cap {cap}"
230                    ));
231                }
232            }
233        }
234    }
235    tx.commit()?;
236
237    conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")?;
238
239    let action = if was_created {
240        "created".to_string()
241    } else {
242        "already_exists".to_string()
243    };
244
245    let response = LinkResponse {
246        action: action.clone(),
247        from: norm_from.clone(),
248        to: norm_to.clone(),
249        relation: relation_str.to_string(),
250        weight: actual_weight,
251        namespace: namespace.clone(),
252        elapsed_ms: inicio.elapsed().as_millis() as u64,
253        created_entities,
254        warnings,
255    };
256
257    match args.format {
258        OutputFormat::Json => output::emit_json(&response)?,
259        OutputFormat::Text | OutputFormat::Markdown => {
260            output::emit_text(&format!(
261                "{}: {} --[{}]--> {} [{}]",
262                action, response.from, response.relation, response.to, response.namespace
263            ));
264        }
265    }
266
267    Ok(())
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn link_response_without_redundant_aliases() {
276        // P1-O: source/target fields were removed from the JSON response.
277        let resp = LinkResponse {
278            action: "created".to_string(),
279            from: "entity-a".to_string(),
280            to: "entity-b".to_string(),
281            relation: "uses".to_string(),
282            weight: 1.0,
283            namespace: "default".to_string(),
284            elapsed_ms: 0,
285            created_entities: vec![],
286            warnings: vec![],
287        };
288        let json = serde_json::to_value(&resp).expect("serialization must work");
289        assert_eq!(json["from"], "entity-a");
290        assert_eq!(json["to"], "entity-b");
291        assert!(
292            json.get("source").is_none(),
293            "field 'source' was removed in P1-O"
294        );
295        assert!(
296            json.get("target").is_none(),
297            "field 'target' was removed in P1-O"
298        );
299    }
300
301    #[test]
302    fn link_response_serializes_all_fields() {
303        let resp = LinkResponse {
304            action: "already_exists".to_string(),
305            from: "origin".to_string(),
306            to: "destination".to_string(),
307            relation: "mentions".to_string(),
308            weight: 0.8,
309            namespace: "test".to_string(),
310            elapsed_ms: 5,
311            created_entities: vec![],
312            warnings: vec![],
313        };
314        let json = serde_json::to_value(&resp).expect("serialization must work");
315        assert!(json.get("action").is_some());
316        assert!(json.get("from").is_some());
317        assert!(json.get("to").is_some());
318        assert!(json.get("relation").is_some());
319        assert!(json.get("weight").is_some());
320        assert!(json.get("namespace").is_some());
321        assert!(json.get("elapsed_ms").is_some());
322    }
323
324    #[test]
325    fn link_response_omits_created_entities_when_empty() {
326        let resp = LinkResponse {
327            action: "created".to_string(),
328            from: "a".to_string(),
329            to: "b".to_string(),
330            relation: "uses".to_string(),
331            weight: 1.0,
332            namespace: "global".to_string(),
333            elapsed_ms: 0,
334            created_entities: vec![],
335            warnings: vec![],
336        };
337        let json = serde_json::to_value(&resp).expect("serialization");
338        assert!(
339            json.get("created_entities").is_none(),
340            "empty vec must be omitted"
341        );
342    }
343
344    #[test]
345    fn link_response_includes_created_entities_when_present() {
346        let resp = LinkResponse {
347            action: "created".to_string(),
348            from: "new-a".to_string(),
349            to: "new-b".to_string(),
350            relation: "depends-on".to_string(),
351            weight: 0.5,
352            namespace: "test".to_string(),
353            elapsed_ms: 1,
354            created_entities: vec!["new-a".to_string(), "new-b".to_string()],
355            warnings: vec![],
356        };
357        let json = serde_json::to_value(&resp).expect("serialization");
358        let created = json["created_entities"].as_array().expect("must be array");
359        assert_eq!(created.len(), 2);
360        assert_eq!(created[0], "new-a");
361        assert_eq!(created[1], "new-b");
362    }
363
364    #[test]
365    fn link_response_includes_warnings_when_non_canonical() {
366        let resp = LinkResponse {
367            action: "created".to_string(),
368            from: "a".to_string(),
369            to: "b".to_string(),
370            relation: "implements".to_string(),
371            weight: 0.5,
372            namespace: "global".to_string(),
373            elapsed_ms: 0,
374            created_entities: vec![],
375            warnings: vec!["non-canonical relation 'implements'".to_string()],
376        };
377        let json = serde_json::to_value(&resp).expect("serialization");
378        let w = json["warnings"]
379            .as_array()
380            .expect("warnings must be present");
381        assert_eq!(w.len(), 1);
382        assert!(w[0].as_str().unwrap().contains("implements"));
383    }
384
385    #[test]
386    fn link_response_omits_warnings_when_empty() {
387        let resp = LinkResponse {
388            action: "created".to_string(),
389            from: "a".to_string(),
390            to: "b".to_string(),
391            relation: "uses".to_string(),
392            weight: 0.5,
393            namespace: "global".to_string(),
394            elapsed_ms: 0,
395            created_entities: vec![],
396            warnings: vec![],
397        };
398        let json = serde_json::to_value(&resp).expect("serialization");
399        assert!(
400            json.get("warnings").is_none(),
401            "empty warnings must be omitted"
402        );
403    }
404}