1use crate::graph::{
2 Entity, KnowledgeGraph, ObservationDeletion, ObservationInput, ObservationResult, Relation,
3};
4use anyhow::{bail, Context, Result};
5use r2d2::Pool;
6use r2d2_sqlite::SqliteConnectionManager;
7use rusqlite::{params, Connection, OptionalExtension};
8use std::collections::HashSet;
9use std::path::Path;
10
11const MAX_NAME_LENGTH: usize = 256; const MAX_TYPE_LENGTH: usize = 128; const MAX_OBSERVATION_LENGTH: usize = 4096; #[derive(Debug)]
18struct SqliteCustomizer;
19
20impl r2d2::CustomizeConnection<Connection, rusqlite::Error> for SqliteCustomizer {
21 fn on_acquire(&self, conn: &mut Connection) -> std::result::Result<(), rusqlite::Error> {
22 conn.execute_batch("PRAGMA foreign_keys = ON;")?;
24 Ok(())
25 }
26}
27
28fn validate_name(name: &str, field: &str) -> Result<()> {
30 if name.is_empty() {
31 bail!("{} cannot be empty", field);
32 }
33 if name.len() > MAX_NAME_LENGTH {
34 bail!("{} too long (max {} chars)", field, MAX_NAME_LENGTH);
35 }
36 if name.chars().any(|c| c.is_control() || c == '\0') {
38 bail!("{} contains invalid characters", field);
39 }
40 Ok(())
41}
42
43fn validate_type(type_str: &str, field: &str) -> Result<()> {
45 if type_str.is_empty() {
46 bail!("{} cannot be empty", field);
47 }
48 if type_str.len() > MAX_TYPE_LENGTH {
49 bail!("{} too long (max {} chars)", field, MAX_TYPE_LENGTH);
50 }
51 if !type_str
53 .chars()
54 .all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == ':')
55 {
56 bail!(
57 "{} contains invalid characters (only alphanumeric, -, _, ., : allowed)",
58 field
59 );
60 }
61 Ok(())
62}
63
64fn validate_observation(obs: &str) -> Result<()> {
66 if obs.len() > MAX_OBSERVATION_LENGTH {
67 bail!(
68 "Observation too long (max {} chars)",
69 MAX_OBSERVATION_LENGTH
70 );
71 }
72 if obs.contains('\0') {
74 bail!("Observation contains null bytes");
75 }
76 Ok(())
77}
78
79fn build_placeholders(count: usize, offset: usize) -> String {
82 (offset..offset + count)
83 .map(|i| format!("?{}", i))
84 .collect::<Vec<_>>()
85 .join(", ")
86}
87
88fn sanitize_fts5_query(query: &str) -> String {
92 query
94 .split_whitespace()
95 .map(|term| {
96 let stripped = term.trim_matches('"');
98 let escaped = stripped.replace('"', "\"\"");
100 format!("\"{}\"", escaped)
101 })
102 .collect::<Vec<_>>()
103 .join(" ")
104}
105
106fn validate_db_path(path: &Path) -> Result<()> {
108 if let Some(ext) = path.extension() {
110 if ext != "db" {
111 bail!("Invalid database file extension (must be .db)");
112 }
113 } else {
114 bail!("Database path must have .db extension");
115 }
116 Ok(())
117}
118
119const SCHEMA: &str = r#"
120-- Entities table
121CREATE TABLE IF NOT EXISTS entities (
122 name TEXT PRIMARY KEY NOT NULL,
123 entity_type TEXT NOT NULL,
124 observations TEXT NOT NULL
125) STRICT;
126
127-- Relations table with FOREIGN KEY for cascade delete
128CREATE TABLE IF NOT EXISTS relations (
129 id INTEGER PRIMARY KEY AUTOINCREMENT,
130 from_entity TEXT NOT NULL,
131 to_entity TEXT NOT NULL,
132 relation_type TEXT NOT NULL,
133 UNIQUE(from_entity, to_entity, relation_type),
134 FOREIGN KEY(from_entity) REFERENCES entities(name) ON DELETE CASCADE,
135 FOREIGN KEY(to_entity) REFERENCES entities(name) ON DELETE CASCADE
136) STRICT;
137
138-- Indexes for performance
139CREATE INDEX IF NOT EXISTS idx_entity_type ON entities(entity_type);
140CREATE INDEX IF NOT EXISTS idx_from ON relations(from_entity);
141CREATE INDEX IF NOT EXISTS idx_to ON relations(to_entity);
142CREATE INDEX IF NOT EXISTS idx_relation_type ON relations(relation_type);
143
144-- Compound indexes for complex queries
145CREATE INDEX IF NOT EXISTS idx_relations_from_type ON relations(from_entity, relation_type);
146CREATE INDEX IF NOT EXISTS idx_relations_to_type ON relations(to_entity, relation_type);
147
148-- FTS5 virtual table for full-text search
149CREATE VIRTUAL TABLE IF NOT EXISTS entities_fts USING fts5(
150 name,
151 entity_type,
152 observations,
153 content='entities',
154 content_rowid='rowid'
155);
156
157-- Triggers to keep FTS5 in sync with entities table
158CREATE TRIGGER IF NOT EXISTS entities_ai AFTER INSERT ON entities BEGIN
159 INSERT INTO entities_fts(rowid, name, entity_type, observations)
160 VALUES (new.rowid, new.name, new.entity_type, new.observations);
161END;
162
163CREATE TRIGGER IF NOT EXISTS entities_ad AFTER DELETE ON entities BEGIN
164 INSERT INTO entities_fts(entities_fts, rowid, name, entity_type, observations)
165 VALUES ('delete', old.rowid, old.name, old.entity_type, old.observations);
166END;
167
168CREATE TRIGGER IF NOT EXISTS entities_au AFTER UPDATE ON entities BEGIN
169 INSERT INTO entities_fts(entities_fts, rowid, name, entity_type, observations)
170 VALUES ('delete', old.rowid, old.name, old.entity_type, old.observations);
171 INSERT INTO entities_fts(rowid, name, entity_type, observations)
172 VALUES (new.rowid, new.name, new.entity_type, new.observations);
173END;
174"#;
175
176pub struct Database {
177 pool: Pool<SqliteConnectionManager>,
178}
179
180impl Database {
181 pub fn open(path: &Path) -> Result<Self> {
183 validate_db_path(path)?;
185
186 if let Some(parent) = path.parent() {
188 std::fs::create_dir_all(parent)?;
189 }
190
191 let manager = SqliteConnectionManager::file(path);
192 let pool = Pool::builder()
193 .max_size(15) .connection_customizer(Box::new(SqliteCustomizer)) .build(manager)
196 .context("Failed to create connection pool")?;
197
198 {
200 let conn = pool.get().context("Failed to get connection from pool")?;
201
202 conn.execute_batch("PRAGMA journal_mode = WAL;")?;
204
205 conn.execute_batch(SCHEMA)?;
207 }
208
209 Ok(Self { pool })
210 }
211
212 pub fn create_entities(&self, entities: &[Entity]) -> Result<Vec<Entity>> {
216 if entities.is_empty() {
217 return Ok(Vec::new());
218 }
219
220 for entity in entities {
222 validate_name(&entity.name, "Entity name")?;
223 validate_type(&entity.entity_type, "Entity type")?;
224 for obs in &entity.observations {
225 validate_observation(obs)?;
226 }
227 }
228
229 let conn = self
230 .pool
231 .get()
232 .context("Failed to get database connection from pool")?;
233 let tx = conn
234 .unchecked_transaction()
235 .context("Failed to start transaction for creating entities")?;
236 let mut new_entities = Vec::new();
237
238 {
239 let mut stmt = tx.prepare_cached(
240 "INSERT OR IGNORE INTO entities (name, entity_type, observations) VALUES (?1, ?2, ?3)"
241 )
242 .context("Failed to prepare insert statement for entities")?;
243
244 for entity in entities {
246 let obs_json = serde_json::to_string(&entity.observations).context(format!(
247 "Failed to serialize observations for entity '{}'",
248 entity.name
249 ))?;
250 let rows_affected = stmt
251 .execute(params![&entity.name, &entity.entity_type, &obs_json,])
252 .with_context(|| format!("Failed to insert entity '{}'", entity.name))?;
253
254 if rows_affected > 0 {
256 new_entities.push(entity.clone());
257 }
258 }
259 }
260
261 tx.commit()
262 .context("Failed to commit transaction for creating entities")?;
263 Ok(new_entities)
264 }
265
266 pub fn create_relations(&self, relations: &[Relation]) -> Result<Vec<Relation>> {
270 if relations.is_empty() {
271 return Ok(Vec::new());
272 }
273
274 for rel in relations {
276 validate_name(&rel.from, "From entity")?;
277 validate_name(&rel.to, "To entity")?;
278 validate_type(&rel.relation_type, "Relation type")?;
279 }
280
281 let conn = self
282 .pool
283 .get()
284 .context("Failed to get database connection from pool")?;
285 let tx = conn
286 .unchecked_transaction()
287 .context("Failed to start transaction for creating relations")?;
288 let mut new_relations = Vec::new();
289
290 {
291 let mut stmt = tx.prepare_cached(
292 "INSERT OR IGNORE INTO relations (from_entity, to_entity, relation_type) VALUES (?1, ?2, ?3)"
293 )
294 .context("Failed to prepare insert statement for relations")?;
295
296 for rel in relations {
298 match stmt.execute(params![&rel.from, &rel.to, &rel.relation_type]) {
300 Ok(rows_affected) => {
301 if rows_affected > 0 {
303 new_relations.push(rel.clone());
304 }
305 }
306 Err(rusqlite::Error::SqliteFailure(err, _)) => {
307 if err.code == rusqlite::ErrorCode::ConstraintViolation {
308 anyhow::bail!(
309 "Cannot create relation '{}' -> '{}' (type: '{}'): one or both entities do not exist",
310 rel.from, rel.to, rel.relation_type
311 );
312 }
313 return Err(err).with_context(|| {
314 format!(
315 "Database error creating relation '{}' -> '{}'",
316 rel.from, rel.to
317 )
318 });
319 }
320 Err(e) => {
321 return Err(e).with_context(|| {
322 format!(
323 "Failed to insert relation '{}' -> '{}' (type: '{}')",
324 rel.from, rel.to, rel.relation_type
325 )
326 })
327 }
328 }
329 }
330 }
331
332 tx.commit()
333 .context("Failed to commit transaction for creating relations")?;
334 Ok(new_relations)
335 }
336
337 pub fn add_observations(&self, inputs: &[ObservationInput]) -> Result<Vec<ObservationResult>> {
340 for input in inputs {
342 validate_name(&input.entity_name, "Entity name")?;
343 for obs in &input.contents {
344 validate_observation(obs)?;
345 }
346 }
347
348 let conn = self
349 .pool
350 .get()
351 .context("Failed to get database connection from pool")?;
352 let tx = conn
353 .unchecked_transaction()
354 .context("Failed to start transaction for adding observations")?;
355 let mut results = Vec::new();
356
357 for input in inputs {
358 let current: Option<String> = tx
360 .query_row(
361 "SELECT observations FROM entities WHERE name = ?1",
362 params![&input.entity_name],
363 |row| row.get(0),
364 )
365 .optional()
366 .with_context(|| {
367 format!("Database error querying entity '{}'", input.entity_name)
368 })?;
369
370 let current = current.with_context(|| {
371 format!(
372 "Cannot add observations: entity '{}' does not exist",
373 input.entity_name
374 )
375 })?;
376
377 let mut observations: Vec<String> =
379 serde_json::from_str(¤t).with_context(|| {
380 format!(
381 "Corrupted observations data for entity '{}'",
382 input.entity_name
383 )
384 })?;
385
386 let mut added = Vec::new();
388 for obs in &input.contents {
389 if !observations.contains(obs) {
390 observations.push(obs.clone());
391 added.push(obs.clone());
392 }
393 }
394
395 if !added.is_empty() {
397 let obs_json = serde_json::to_string(&observations).with_context(|| {
398 format!(
399 "Failed to serialize observations for entity '{}'",
400 input.entity_name
401 )
402 })?;
403 tx.execute(
404 "UPDATE entities SET observations = ?1 WHERE name = ?2",
405 params![&obs_json, &input.entity_name],
406 )
407 .with_context(|| {
408 format!(
409 "Failed to update observations for entity '{}'",
410 input.entity_name
411 )
412 })?;
413 }
414
415 results.push(ObservationResult {
416 entity_name: input.entity_name.clone(),
417 added_observations: added,
418 });
419 }
420
421 tx.commit()
422 .context("Failed to commit transaction for adding observations")?;
423 Ok(results)
424 }
425
426 pub fn delete_entities(&self, names: &[String]) -> Result<usize> {
429 if names.is_empty() {
430 return Ok(0);
431 }
432
433 for name in names {
435 validate_name(name, "Entity name")?;
436 }
437
438 let conn = self
439 .pool
440 .get()
441 .context("Failed to get database connection from pool")?;
442
443 let tx = conn
444 .unchecked_transaction()
445 .context("Failed to start transaction for deleting entities")?;
446
447 let placeholders = build_placeholders(names.len(), 1);
448 let query = format!("DELETE FROM entities WHERE name IN ({})", placeholders);
449
450 let params: Vec<&dyn rusqlite::ToSql> =
451 names.iter().map(|s| s as &dyn rusqlite::ToSql).collect();
452
453 let count = tx
454 .execute(&query, params.as_slice())
455 .context(format!("Failed to delete {} entities", names.len()))?;
456
457 tx.commit()
460 .context("Failed to commit transaction for deleting entities")?;
461
462 Ok(count)
463 }
464
465 pub fn delete_observations(&self, deletions: &[ObservationDeletion]) -> Result<()> {
468 for deletion in deletions {
470 validate_name(&deletion.entity_name, "Entity name")?;
471 }
472
473 let conn = self
474 .pool
475 .get()
476 .context("Failed to get database connection from pool")?;
477 let tx = conn
478 .unchecked_transaction()
479 .context("Failed to start transaction for deleting observations")?;
480
481 for deletion in deletions {
482 let current: Option<String> = tx
483 .query_row(
484 "SELECT observations FROM entities WHERE name = ?1",
485 params![&deletion.entity_name],
486 |row| row.get(0),
487 )
488 .optional()
489 .with_context(|| {
490 format!("Database error querying entity '{}'", deletion.entity_name)
491 })?;
492
493 let current = current.with_context(|| {
494 format!(
495 "Cannot delete observations: entity '{}' does not exist",
496 deletion.entity_name
497 )
498 })?;
499
500 let mut observations: Vec<String> =
501 serde_json::from_str(¤t).with_context(|| {
502 format!(
503 "Corrupted observations data for entity '{}'",
504 deletion.entity_name
505 )
506 })?;
507 observations.retain(|obs| !deletion.observations.contains(obs));
508
509 let obs_json = serde_json::to_string(&observations).with_context(|| {
510 format!(
511 "Failed to serialize observations for entity '{}'",
512 deletion.entity_name
513 )
514 })?;
515 tx.execute(
516 "UPDATE entities SET observations = ?1 WHERE name = ?2",
517 params![&obs_json, &deletion.entity_name],
518 )
519 .with_context(|| {
520 format!(
521 "Failed to delete observations from entity '{}'",
522 deletion.entity_name
523 )
524 })?;
525 }
526
527 tx.commit()
528 .context("Failed to commit transaction for deleting observations")?;
529 Ok(())
530 }
531
532 pub fn delete_relations(&self, relations: &[Relation]) -> Result<usize> {
535 if relations.is_empty() {
536 return Ok(0);
537 }
538
539 for rel in relations {
541 validate_name(&rel.from, "From entity")?;
542 validate_name(&rel.to, "To entity")?;
543 validate_type(&rel.relation_type, "Relation type")?;
544 }
545
546 let conn = self
547 .pool
548 .get()
549 .context("Failed to get database connection from pool")?;
550 let tx = conn
551 .unchecked_transaction()
552 .context("Failed to start transaction for deleting relations")?;
553 let mut count = 0;
554
555 {
556 let mut stmt = tx.prepare_cached(
557 "DELETE FROM relations WHERE from_entity = ?1 AND to_entity = ?2 AND relation_type = ?3"
558 ).context("Failed to prepare delete statement for relations")?;
559
560 for rel in relations {
561 count += stmt
562 .execute(params![&rel.from, &rel.to, &rel.relation_type])
563 .with_context(|| {
564 format!(
565 "Failed to delete relation '{}' -> '{}' (type: '{}')",
566 rel.from, rel.to, rel.relation_type
567 )
568 })?;
569 }
570 }
571
572 tx.commit()
573 .context("Failed to commit transaction for deleting relations")?;
574 Ok(count)
575 }
576
577 pub fn read_graph(&self) -> Result<KnowledgeGraph> {
579 let conn = self
580 .pool
581 .get()
582 .context("Failed to get database connection from pool")?;
583
584 let entities = self
585 .read_all_entities(&conn)
586 .context("Failed to read entities")?;
587 let relations = self
588 .read_all_relations(&conn)
589 .context("Failed to read relations")?;
590
591 Ok(KnowledgeGraph {
592 entities,
593 relations,
594 })
595 }
596
597 fn read_all_entities(&self, conn: &Connection) -> Result<Vec<Entity>> {
599 let mut stmt = conn.prepare("SELECT name, entity_type, observations FROM entities")?;
600 let rows = stmt.query_map([], |row| {
601 Ok((
602 row.get::<_, String>(0)?,
603 row.get::<_, String>(1)?,
604 row.get::<_, String>(2)?,
605 ))
606 })?;
607
608 let mut entities = Vec::with_capacity(rows.size_hint().0);
610 for row in rows {
611 let (name, entity_type, obs_json) = row?;
612 let observations: Vec<String> = serde_json::from_str(&obs_json)
613 .with_context(|| format!("Corrupted observations for entity '{}'", name))?;
614 entities.push(Entity {
615 name,
616 entity_type,
617 observations,
618 });
619 }
620 Ok(entities)
621 }
622
623 fn read_all_relations(&self, conn: &Connection) -> Result<Vec<Relation>> {
625 let mut stmt =
626 conn.prepare("SELECT from_entity, to_entity, relation_type FROM relations")?;
627 let rows = stmt.query_map([], |row| {
628 Ok(Relation {
629 from: row.get(0)?,
630 to: row.get(1)?,
631 relation_type: row.get(2)?,
632 })
633 })?;
634
635 let mut relations = Vec::with_capacity(rows.size_hint().0);
637 for row in rows {
638 relations.push(row?);
639 }
640 Ok(relations)
641 }
642
643 pub fn search_nodes(&self, query: Option<&str>) -> Result<KnowledgeGraph> {
645 let trimmed = query.map(|q| q.trim()).unwrap_or("");
647 if trimmed.is_empty() {
648 return self.read_graph();
649 }
650
651 let conn = self
652 .pool
653 .get()
654 .context("Failed to get database connection from pool")?;
655
656 let safe_query = sanitize_fts5_query(trimmed);
658
659 let entities = self
661 .search_entities_fts(&conn, &safe_query)
662 .context("Failed to search entities")?;
663
664 let relations = self
666 .get_relations_between(&conn, &entities)
667 .context("Failed to get relations for search results")?;
668
669 Ok(KnowledgeGraph {
670 entities,
671 relations,
672 })
673 }
674
675 fn search_entities_fts(&self, conn: &Connection, fts_query: &str) -> Result<Vec<Entity>> {
677 let mut stmt = conn
678 .prepare(
679 "SELECT e.name, e.entity_type, e.observations
680 FROM entities e
681 INNER JOIN entities_fts fts ON e.rowid = fts.rowid
682 WHERE entities_fts MATCH ?1",
683 )
684 .context("Failed to prepare FTS5 search query")?;
685
686 let rows = stmt.query_map(params![fts_query], |row| {
687 Ok((
688 row.get::<_, String>(0)?,
689 row.get::<_, String>(1)?,
690 row.get::<_, String>(2)?,
691 ))
692 })?;
693
694 let mut entities = Vec::with_capacity(rows.size_hint().0);
696 for row in rows {
697 let (name, entity_type, obs_json) = row?;
698 let observations: Vec<String> = serde_json::from_str(&obs_json)
699 .with_context(|| format!("Corrupted observations for entity '{}'", name))?;
700 entities.push(Entity {
701 name,
702 entity_type,
703 observations,
704 });
705 }
706 Ok(entities)
707 }
708
709 fn get_relations_between(
711 &self,
712 conn: &Connection,
713 entities: &[Entity],
714 ) -> Result<Vec<Relation>> {
715 if entities.is_empty() {
716 return Ok(Vec::new());
717 }
718
719 let entity_names: HashSet<_> = entities.iter().map(|e| &e.name).collect();
720
721 let placeholders_from = build_placeholders(entity_names.len(), 1);
722 let placeholders_to = build_placeholders(entity_names.len(), entity_names.len() + 1);
723
724 let query = format!(
725 "SELECT from_entity, to_entity, relation_type FROM relations
726 WHERE from_entity IN ({}) AND to_entity IN ({})",
727 placeholders_from, placeholders_to
728 );
729
730 let mut params: Vec<&dyn rusqlite::ToSql> = Vec::with_capacity(entity_names.len() * 2);
732 for name in &entity_names {
733 params.push(*name);
734 }
735 for name in &entity_names {
736 params.push(*name);
737 }
738
739 let mut stmt = conn.prepare(&query)?;
740 let rows = stmt.query_map(params.as_slice(), |row| {
741 Ok(Relation {
742 from: row.get(0)?,
743 to: row.get(1)?,
744 relation_type: row.get(2)?,
745 })
746 })?;
747
748 let mut relations = Vec::with_capacity(rows.size_hint().0);
750 for row in rows {
751 relations.push(row?);
752 }
753 Ok(relations)
754 }
755
756 pub fn open_nodes(&self, names: &[String]) -> Result<KnowledgeGraph> {
758 if names.is_empty() {
759 return Ok(KnowledgeGraph::default());
760 }
761
762 for name in names {
764 validate_name(name, "Entity name")?;
765 }
766
767 let conn = self
768 .pool
769 .get()
770 .context("Failed to get database connection from pool")?;
771
772 let entities = self
774 .read_entities_by_names(&conn, names)
775 .context("Failed to read entities")?;
776
777 let relations = self
779 .get_relations_between(&conn, &entities)
780 .context("Failed to get relations")?;
781
782 Ok(KnowledgeGraph {
783 entities,
784 relations,
785 })
786 }
787
788 fn read_entities_by_names(
790 &self,
791 conn: &Connection,
792 names: &[String],
793 ) -> Result<Vec<Entity>> {
794 let placeholders = build_placeholders(names.len(), 1);
795 let query = format!(
796 "SELECT name, entity_type, observations FROM entities WHERE name IN ({})",
797 placeholders
798 );
799
800 let params: Vec<&dyn rusqlite::ToSql> =
801 names.iter().map(|s| s as &dyn rusqlite::ToSql).collect();
802
803 let mut stmt = conn.prepare(&query)?;
804 let rows = stmt.query_map(params.as_slice(), |row| {
805 Ok((
806 row.get::<_, String>(0)?,
807 row.get::<_, String>(1)?,
808 row.get::<_, String>(2)?,
809 ))
810 })?;
811
812 let mut entities = Vec::with_capacity(names.len());
813 for row in rows {
814 let (name, entity_type, obs_json) = row?;
815 let observations: Vec<String> = serde_json::from_str(&obs_json)
816 .with_context(|| format!("Corrupted observations for entity '{}'", name))?;
817 entities.push(Entity {
818 name,
819 entity_type,
820 observations,
821 });
822 }
823 Ok(entities)
824 }
825}