Repository navigation
Description
Overview
Implement core QueryService in Rust (packages/core) for executing queries using the hub-and-spoke SurrealDB architecture. This service translates QueryDefinition to SurrealQL, leverages record links and graph edges, and returns properly typed results.
Architecture References
- SurrealDB Schema Design:
docs/architecture/data/surrealdb-schema-design.md - Persistence Architecture:
docs/architecture/persistence-architecture.md - Hub-and-Spoke Pattern: See
packages/core/src/db/schema.surqlfor current schema
Problem Statement
QueryNode stores structured query definitions, but we need a service to execute these queries against the graph-native database and return matching nodes. The service must:
- Query the hub table (
node) with proper type filtering - Access type-specific properties via record links (
data.property) - Traverse graph edges for relationships (
->has_child->,->mentions->) - Handle complex filter combinations efficiently
Dependencies
- QueryNode Behavior and Core Type Definitions #439: QueryNode type definition (QueryDefinition types)
Current Database Context
Hub-and-Spoke Architecture
From schema.surql:
-- Hub table: Universal metadata for ALL node types
DEFINE TABLE IF NOT EXISTS node SCHEMAFULL;
DEFINE FIELD IF NOT EXISTS content ON TABLE node TYPE string DEFAULT "";
DEFINE FIELD IF NOT EXISTS node_type ON TABLE node TYPE string ASSERT $value != NONE;
DEFINE FIELD IF NOT EXISTS data ON TABLE node TYPE option<record>; -- Record Link to spoke
-- Graph edges for relationships
DEFINE TABLE IF NOT EXISTS has_child SCHEMAFULL TYPE RELATION IN node OUT node;
DEFINE TABLE IF NOT EXISTS mentions SCHEMAFULL TYPE RELATION IN node OUT node;Query Pattern Examples
Type filter: SELECT * FROM node WHERE node_type = 'task'
Property filter via spoke: SELECT * FROM node WHERE data.status = 'open' FETCH data
Graph traversal: SELECT ->has_child->node FROM node:⟨parent-id⟩
Proposed Solution
Phase 1: Core Service Structure
File: packages/core/src/services/query_service.rs
use anyhow::{Context, Result};
use crate::db::SurrealStore;
use crate::models::Node;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryDefinition {
pub target_type: String,
pub filters: Vec<QueryFilter>,
pub sorting: Option<Vec<SortConfig>>,
pub limit: Option<usize>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryFilter {
#[serde(rename = "type")]
pub filter_type: String,
pub operator: String,
pub property: Option<String>,
pub value: Option<serde_json::Value>,
pub case_sensitive: Option<bool>,
pub relationship_type: Option<String>,
pub node_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SortConfig {
pub field: String,
pub direction: String,
}
pub struct QueryService<C: surrealdb::Connection> {
store: Arc<SurrealStore<C>>,
}
impl<C: surrealdb::Connection> QueryService<C> {
pub fn new(store: Arc<SurrealStore<C>>) -> Self {
Self { store }
}
/// Execute a query and return matching nodes
pub async fn execute(&self, query: QueryDefinition) -> Result<Vec<Node>> {
let sql = self.build_query(&query)?;
self.store.execute_query(&sql).await
}
/// Translate QueryDefinition to SurrealQL
fn build_query(&self, query: &QueryDefinition) -> Result<String> {
let mut sql = String::from("SELECT * FROM node");
let mut conditions = Vec::new();
// Type filter (using node_type field)
if query.target_type != "*" {
conditions.push(format!("node_type = '{}'", query.target_type));
}
// Build filter conditions
for filter in &query.filters {
match filter.filter_type.as_str() {
"property" => conditions.push(self.build_property_filter(filter)?),
"content" => conditions.push(self.build_content_filter(filter)?),
"relationship" => conditions.push(self.build_relationship_filter(filter)?),
"metadata" => conditions.push(self.build_metadata_filter(filter)?),
_ => return Err(anyhow::anyhow!("Unknown filter type")),
}
}
// Apply WHERE clause
if !conditions.is_empty() {
sql.push_str(" WHERE ");
sql.push_str(&conditions.join(" AND "));
}
// Add sorting
if let Some(sorting) = &query.sorting {
sql.push_str(" ORDER BY ");
let clauses: Vec<String> = sorting.iter()
.map(|s| format!("{} {}",
self.resolve_field(&s.field),
s.direction.to_uppercase()))
.collect();
sql.push_str(&clauses.join(", "));
}
// Add limit
if let Some(limit) = query.limit {
sql.push_str(&format!(" LIMIT {}", limit));
}
// FETCH data to hydrate type-specific properties
sql.push_str(" FETCH data;");
Ok(sql)
}
fn resolve_field(&self, field: &str) -> String {
// Metadata fields are on hub table
if ["created_at", "modified_at", "content", "node_type"].contains(&field) {
field.to_string()
} else {
// Type-specific fields accessed via data link
format!("data.{}", field)
}
}
fn build_property_filter(&self, filter: &QueryFilter) -> Result<String> {
let property = filter.property.as_ref()
.ok_or_else(|| anyhow::anyhow!("Property filter missing 'property' field"))?;
let field = format!("data.{}", property);
match filter.operator.as_str() {
"equals" => {
let value = serde_json::to_string(&filter.value)?;
Ok(format!("{} = {}", field, value))
}
"contains" => {
let value = filter.value.as_ref()
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Contains requires string value"))?;
if filter.case_sensitive.unwrap_or(true) {
Ok(format!("{} CONTAINS '{}'", field, value))
} else {
Ok(format!("string::lowercase({}) CONTAINS string::lowercase('{}')", field, value))
}
}
"gt" | "lt" | "gte" | "lte" => {
let op = match filter.operator.as_str() {
"gt" => ">", "lt" => "<", "gte" => ">=", "lte" => "<=",
_ => unreachable!()
};
let value = serde_json::to_string(&filter.value)?;
Ok(format!("{} {} {}", field, op, value))
}
"in" => {
let values = filter.value.as_ref()
.and_then(|v| v.as_array())
.ok_or_else(|| anyhow::anyhow!("In requires array value"))?;
let list = values.iter()
.map(|v| serde_json::to_string(v))
.collect::<Result<Vec<_>, _>>()?
.join(", ");
Ok(format!("{} IN [{}]", field, list))
}
"exists" => Ok(format!("{} IS NOT NONE", field)),
_ => Err(anyhow::anyhow!("Unsupported operator: {}", filter.operator)),
}
}
fn build_content_filter(&self, filter: &QueryFilter) -> Result<String> {
let value = filter.value.as_ref()
.and_then(|v| v.as_str())
.ok_or_else(|| anyhow::anyhow!("Content filter requires string value"))?;
match filter.operator.as_str() {
"contains" => {
if filter.case_sensitive.unwrap_or(true) {
Ok(format!("content CONTAINS '{}'", value))
} else {
Ok(format!("string::lowercase(content) CONTAINS string::lowercase('{}')", value))
}
}
"equals" => Ok(format!("content = '{}'", value)),
_ => Err(anyhow::anyhow!("Unsupported content operator")),
}
}
fn build_relationship_filter(&self, filter: &QueryFilter) -> Result<String> {
let rel_type = filter.relationship_type.as_ref()
.ok_or_else(|| anyhow::anyhow!("Missing relationshipType"))?;
let node_id = filter.node_id.as_ref()
.ok_or_else(|| anyhow::anyhow!("Missing nodeId"))?;
match rel_type.as_str() {
"children" => Ok(format!(
"id IN (SELECT VALUE out FROM has_child WHERE in = node:⟨{}⟩)",
node_id
)),
"parent" => Ok(format!(
"id IN (SELECT VALUE in FROM has_child WHERE out = node:⟨{}⟩)",
node_id
)),
"mentions" => Ok(format!(
"id IN (SELECT VALUE out FROM mentions WHERE in = node:⟨{}⟩)",
node_id
)),
"mentioned_by" => Ok(format!(
"id IN (SELECT VALUE in FROM mentions WHERE out = node:⟨{}⟩)",
node_id
)),
_ => Err(anyhow::anyhow!("Unsupported relationship type")),
}
}
fn build_metadata_filter(&self, filter: &QueryFilter) -> Result<String> {
let property = filter.property.as_ref()
.ok_or_else(|| anyhow::anyhow!("Metadata filter missing property"))?;
if !["created_at", "modified_at", "node_type", "content"].contains(&property.as_str()) {
return Err(anyhow::anyhow!("Invalid metadata field: {}", property));
}
let value = serde_json::to_string(&filter.value)?;
let op = match filter.operator.as_str() {
"equals" => "=",
"gt" => ">", "lt" => "<", "gte" => ">=", "lte" => "<=",
_ => return Err(anyhow::anyhow!("Unsupported metadata operator")),
};
Ok(format!("{} {} {}", property, op, value))
}
}Query Pattern Examples
Example 1: Type Filter Only
{ targetType: 'task', filters: [] }SQL: SELECT * FROM node WHERE node_type = 'task' FETCH data;
Example 2: Property Filter (via spoke table)
{
targetType: 'task',
filters: [{ type: 'property', property: 'status', operator: 'equals', value: 'open' }]
}SQL: SELECT * FROM node WHERE node_type = 'task' AND data.status = 'open' FETCH data;
Example 3: Relationship Filter (graph edge)
{
targetType: '*',
filters: [{ type: 'relationship', relationshipType: 'children', nodeId: 'abc-123' }]
}SQL: SELECT * FROM node WHERE id IN (SELECT VALUE out FROM has_child WHERE in = node:⟨abc-123⟩) FETCH data;
Example 4: Combined Filters
{
targetType: 'task',
filters: [
{ type: 'property', property: 'status', operator: 'in', value: ['open', 'in_progress'] },
{ type: 'metadata', property: 'created_at', operator: 'gt', value: '2025-01-01' }
],
sorting: [{ field: 'due_date', direction: 'asc' }],
limit: 20
}Acceptance Criteria
- QueryService struct created in
packages/core/src/services/query_service.rs -
execute()translates QueryDefinition to SurrealQL and returnsVec<Node> - Property filters use record link pattern (
data.property) - Relationship filters use graph edge queries
- Content filters supported (full-text search with case-sensitivity)
- Metadata filters supported (created_at, modified_at, node_type)
- Sorting handles both metadata and type-specific fields
- All queries include
FETCH datafor property hydration - Comprehensive error handling for invalid queries
- Unit tests for SQL query building logic
- Integration tests with test database
- Tests pass (
bun run test:all) - Code passes
bun run quality:fix
Performance Targets
- Simple type query: <50ms
- Property filter query: <100ms
- Relationship query: <50ms
- Complex combined query: <300ms
Testing Requirements
Unit Tests
- Property filter building (all operators)
- Content filter building (case-sensitive/insensitive)
- Relationship filter building (children, parent, mentions, mentioned_by)
- Metadata filter building
- Sorting logic
- Error handling
Integration Tests
- Execute query with type filter
- Execute query with property filter
- Execute query with relationship filter
- Combined queries work correctly
- FETCH data hydrates properties
- Empty results handled gracefully
Non-Goals
- Query result caching (future enhancement)
- Query optimization/indexing (future enhancement)
- Real-time query updates (future enhancement)
Activity
malibio commentedon Dec 3, 2025
Frontend baseline: 728 tests passed, Rust baseline: 200 tests passed
Implement QueryService with SQL query execution (#440)
Convert QueryService to use enums and spoke-centric queries (#440)
malibio commentedon Dec 3, 2025
Implementation Complete ✅
Summary
Implemented QueryService with enum-based type safety and spoke-centric query architecture. All tests passing.
Key Changes
SELECT * FROM task) instead of hub table withFETCH datatarget_type = '*')Architecture Pivot
Original spec: Hub-centric queries with
FETCH dataImplemented: Spoke-centric queries with record links to hub
This is more efficient because:
status = 'open'vsdata.status = 'open'node.created_atTest Results
Performance
Spoke-centric queries are faster than hub-centric:
node_typeReady for review!
Fix sort order preservation in QueryService
QueryService with SQL Query Execution (#722)
QueryService with SQL Query Execution (#722)
QueryService with SQL Query Execution (#722)
QueryService with SQL Query Execution (#722)