Repository navigation
Closed
Description
Implement NodeStore Trait for SurrealDB Backend
Parent Epic: #461 (SurrealDB Migration)
Phase: 2 - SurrealDB Implementation
Estimated Time: 4-5 days
Depends On: #462 (NodeStore Trait), #463 (Turso Wrapper)
Objective
Implement the NodeStore trait for SurrealDB embedded backend, leveraging PoC code from Epic #460 and ensuring feature parity with Turso implementation.
Implementation
1. Production SurrealStore Implementation
File: packages/desktop-app/src-tauri/src/datastore/surreal/store.rs
use async_trait::async_trait;
use anyhow::Result;
use surrealdb::{Surreal, engine::local::{Db, RocksDb}};
use crate::datastore::NodeStore;
use crate::models::{Node, NodeFilter, NodeUpdate};
pub struct SurrealStore {
db: Surreal<Db>,
}
#[async_trait]
impl NodeStore for SurrealStore {
async fn create_node(&self, node: Node) -> Result<Node> {
// Use SCHEMALESS table: CREATE nodes CONTENT {...}
let created: Option<Node> = self.db
.create("nodes")
.content(node)
.await?;
created.ok_or_else(|| anyhow::anyhow!("Failed to create node"))
}
async fn get_node(&self, id: &str) -> Result<Option<Node>> {
// SELECT * FROM nodes WHERE id = $id
self.db.select(("nodes", id)).await.map_err(Into::into)
}
async fn update_node(&self, id: &str, update: NodeUpdate) -> Result<Node> {
// UPDATE nodes SET ... WHERE id = $id
let updated: Option<Node> = self.db
.update(("nodes", id))
.merge(update)
.await?;
updated.ok_or_else(|| anyhow::anyhow!("Node not found"))
}
async fn delete_node(&self, id: &str) -> Result<()> {
// DELETE nodes WHERE id = $id
self.db.delete(("nodes", id)).await.map(|_| ()).map_err(Into::into)
}
async fn query_nodes(&self, filter: NodeFilter) -> Result<Vec<Node>> {
// Build SurrealQL query from filter
// SELECT * FROM nodes WHERE properties.status = $status ...
let query = build_surrealql_query(&filter);
let mut response = self.db.query(query).await?;
response.take(0).map_err(Into::into)
}
async fn search_nodes(&self, query: &str) -> Result<Vec<Node>> {
// Full-text search using SurrealDB search capabilities
// SELECT * FROM nodes WHERE content @@ $query
let search_query = format!("SELECT * FROM nodes WHERE content @@ '{}'", query);
let mut response = self.db.query(search_query).await?;
response.take(0).map_err(Into::into)
}
async fn get_children(&self, parent_id: &str) -> Result<Vec<Node>> {
// SELECT * FROM nodes WHERE parent_id = $parent_id
let query = format!("SELECT * FROM nodes WHERE parent_id = '{}'", parent_id);
let mut response = self.db.query(query).await?;
response.take(0).map_err(Into::into)
}
async fn move_node(&self, id: &str, new_parent: Option<&str>) -> Result<()> {
// UPDATE nodes SET parent_id = $new_parent WHERE id = $id
let _: Option<Node> = self.db
.update(("nodes", id))
.merge(serde_json::json!({"parent_id": new_parent}))
.await?;
Ok(())
}
async fn set_property(&self, id: &str, key: &str, value: serde_json::Value) -> Result<()> {
// UPDATE nodes SET properties.$key = $value WHERE id = $id
// SCHEMALESS: properties can be arbitrary JSON
let query = format!("UPDATE nodes:{} SET properties.{} = $value", id, key);
self.db.query(query).bind(("value", value)).await?;
Ok(())
}
async fn get_property(&self, id: &str, key: &str) -> Result<Option<serde_json::Value>> {
// SELECT properties.$key FROM nodes WHERE id = $id
let query = format!("SELECT properties.{} AS value FROM nodes:{}", key, id);
let mut response = self.db.query(query).await?;
let result: Option<serde_json::Value> = response.take("value")?;
Ok(result)
}
async fn batch_create(&self, nodes: Vec<Node>) -> Result<Vec<Node>> {
// Use transaction for batch insert
let mut created = Vec::new();
for node in nodes {
let result = self.create_node(node).await?;
created.push(result);
}
Ok(created)
}
async fn transaction<F, T>(&self, f: F) -> Result<T>
where
F: FnOnce() -> Result<T> + Send,
{
// SurrealDB transaction support
// BEGIN TRANSACTION; ... COMMIT;
self.db.query("BEGIN TRANSACTION").await?;
match f() {
Ok(result) => {
self.db.query("COMMIT").await?;
Ok(result)
}
Err(e) => {
self.db.query("CANCEL TRANSACTION").await?;
Err(e)
}
}
}
}
impl SurrealStore {
pub async fn new(db_path: PathBuf) -> Result<Self> {
let db = Surreal::new::<RocksDb>(db_path).await?;
db.use_ns("nodespace").use_db("nodes").await?;
// Initialize SCHEMALESS table
db.query("DEFINE TABLE IF NOT EXISTS nodes SCHEMALESS").await?;
Ok(Self { db })
}
}
fn build_surrealql_query(filter: &NodeFilter) -> String {
// Convert NodeFilter to SurrealQL query
// Example: WHERE properties.status = 'done' AND properties.priority > 3
// Implementation details in this function
}2. Integration with Factory Pattern
File: packages/desktop-app/src-tauri/src/datastore/factory.rs
pub async fn create_store(config: &DatabaseConfig) -> Result<Arc<dyn NodeStore>> {
#[cfg(feature = "surrealdb")]
{
use crate::datastore::surreal::SurrealStore;
Ok(Arc::new(SurrealStore::new(config.path.clone()).await?))
}
#[cfg(feature = "turso")]
{
use crate::datastore::turso::TursoStore;
Ok(Arc::new(TursoStore::new(config.connection.clone()).await?))
}
}3. Leverage PoC Code
Reference: Epic #460 PoC implementation
- Reuse startup time tracking (if needed for monitoring)
- Reuse SCHEMALESS table initialization
- Reuse RocksDB embedded configuration
- Apply lessons learned from Phase 1 & 2 tests
Acceptance Criteria
- SurrealStore implements all NodeStore trait methods
- All PoC test cases pass with production implementation
- Performance meets/exceeds PoC benchmarks:
- Startup time <100ms
- 100K query <200ms
- Deep pagination <50ms
- Complex queries <300ms avg
- SCHEMALESS mode working with arbitrary properties
- Dot notation queries functional
- Feature flag "surrealdb" correctly enables backend
- Code compiles with clippy checks passing
- Comprehensive documentation added
Testing
Unit Tests
- Each NodeStore method tested individually
- SCHEMALESS property handling validated
- Transaction support verified
Integration Tests (from PoC)
- test_phase1_startup_time (production version)
- test_phase1_schemaless_arbitrary_properties
- test_phase1_schemaless_dot_notation_queries
- test_phase1_sparse_properties
- test_phase2_scale_100k_nodes
- test_phase2_deep_pagination
- test_phase2_complex_queries
Parity Tests
- Compare query results with Turso backend
- Verify identical behavior for CRUD operations
- Validate property setting/getting consistency
Performance Requirements
Must meet PoC benchmarks:
- Startup time: <100ms (PoC: 52ms)
- 100K nodes query: <200ms (PoC: 104ms)
- Deep pagination: <50ms (PoC: 8.3ms)
- Complex queries avg: <300ms (PoC: 211ms)
Dependencies
- Create NodeStore Trait Abstraction Layer #462: NodeStore Trait Abstraction Layer
- Implement NodeStore Trait for Turso Backend #463: Turso Backend Wrapper
- Epic SurrealDB Feasibility PoC - Quick Evaluation #460: SurrealDB PoC (reference implementation)
References
- Epic SurrealDB Migration - Hybrid Architecture (Desktop-Only) #461: SurrealDB Migration
- Epic SurrealDB Feasibility PoC - Quick Evaluation #460: SurrealDB Feasibility PoC
/packages/desktop-app/src-tauri/src/datastore/surreal/tests/(PoC tests)- Architect's migration plan (SurrealDB implementation section)
Activity
Complete SurrealDB Feasibility PoC - All GO Criteria Met (#460)
Add Epic #461 Phase 1 architectural planning documentation
SurrealDB Migration - Hybrid Architecture (Desktop-Only) (#467)
docs: Add phase markers and status tracking to SurrealDB migration docs
malibio commentedon Nov 12, 2025
Test Baseline (Starting Phase 2)
Date: 2025-11-12
Branch: feature/issue-461-surrealdb-hybrid-migration
Test Results Summary
Known Issues
Status
✅ All critical tests passing
✅ No new failures
✅ Ready to begin SurrealDB implementation
Next: Implement SurrealStore with NodeStore trait
malibio commentedon Nov 12, 2025
Phase 2 Implementation Complete ✅
Commit: 7c940e1
Summary
Successfully implemented complete SurrealStore with all 22 NodeStore trait methods, following the hybrid dual-table architecture design.
Completed Work
Architecture Implementation
nodes+ type-specific tablestable:uuidTesting Status
--features surrealdbFiles Modified
Cargo.toml: SurrealDB workspace dependencypackages/core/Cargo.toml: Feature flagspackages/core/src/db/surreal_store.rs: Complete implementation (NEW)packages/core/src/db/mod.rs: Conditional exportsKnown Limitations
Next Steps (Phase 3)
Ready for review ✓
Implement Phase 2: SurrealStore with NodeStore trait (#464)
Fix critical SurrealStore Phase 2 implementation issues (#464)
Implement A/B Testing Framework for Backend Comparison (#465)
SurrealDB Migration - Hybrid Architecture (Desktop-Only) (#467)
Implement Phase 2: SurrealStore with NodeStore trait (#464)
Fix critical SurrealStore Phase 2 implementation issues (#464)
Implement A/B Testing Framework for Backend Comparison (#465)
SurrealDB Migration - Hybrid Architecture (Desktop-Only) (#467)
Implement Phase 2: SurrealStore with NodeStore trait (#464)
Fix critical SurrealStore Phase 2 implementation issues (#464)
Implement A/B Testing Framework for Backend Comparison (#465)
Implement Phase 2: SurrealStore with NodeStore trait (#464)
Fix critical SurrealStore Phase 2 implementation issues (#464)
Implement A/B Testing Framework for Backend Comparison (#465)