Skip to main content

nexus_memory_storage/
lib.rs

1//! Nexus Storage - Database operations and storage layer
2//!
3//! This crate provides SQLite-based storage using SQLx.
4
5pub mod migrations;
6pub mod models;
7pub mod repository;
8
9pub use migrations::create_processed_files_table;
10pub use models::*;
11pub use repository::{
12    ListMemoryFilters, MemoryRelationRepository, MemoryRepository, MetricSample,
13    NamespaceRepository, ProcessedFileRepository, SemanticCandidateParams, StoreDigestParams,
14    StoreMemoryParams, StoreMemoryWithLineageParams, WorkingSetParams,
15};
16
17use sqlx::sqlite::SqliteConnectOptions;
18use sqlx::SqlitePool;
19
20/// Convert sqlx::Error to NexusError
21pub fn db_error(err: sqlx::Error) -> nexus_core::NexusError {
22    nexus_core::NexusError::Database(err.to_string())
23}
24
25/// Storage manager for database operations
26pub struct StorageManager {
27    pool: SqlitePool,
28    initialized: bool,
29}
30
31impl StorageManager {
32    /// Create a new storage manager
33    pub fn new(pool: SqlitePool) -> Self {
34        Self {
35            pool,
36            initialized: false,
37        }
38    }
39
40    /// Create a new storage manager from database URL
41    pub async fn from_url(url: &str) -> crate::Result<Self> {
42        let options = url
43            .parse::<SqliteConnectOptions>()
44            .map_err(|err| nexus_core::NexusError::Database(err.to_string()))?
45            .create_if_missing(true);
46        let pool = SqlitePool::connect_with(options).await.map_err(db_error)?;
47        Ok(Self::new(pool))
48    }
49
50    /// Initialize the database schema
51    pub async fn initialize(&mut self) -> crate::Result<()> {
52        if self.initialized {
53            return Ok(());
54        }
55
56        migrations::run_migrations(&self.pool).await?;
57        self.initialized = true;
58        Ok(())
59    }
60
61    /// Get a reference to the connection pool
62    pub fn pool(&self) -> &SqlitePool {
63        &self.pool
64    }
65
66    /// Check if initialized
67    pub fn is_initialized(&self) -> bool {
68        self.initialized
69    }
70}
71
72pub type Result<T> = std::result::Result<T, nexus_core::NexusError>;