Repository navigation
Description
Overview
Update database schema to use SCHEMAFULL for core tables with hub-and-spoke architecture using bidirectional Record Links. The node table serves as the universal hub, while spoke tables (task, date, schema) store type-specific data with efficient indexing.
Self-Contained Scope
- Define
nodetable (hub) as SCHEMAFULL withdataRecord Link to spokes - Define spoke tables (
task,date,schema) as SCHEMAFULL + FLEXIBLE withnodereverse link - Define
has_childrelation as SCHEMAFULL with fractionalorderfield - Define
mentionsrelation as SCHEMAFULL for bidirectional references - Update seeding scripts to create bidirectional links atomically
- Document hub-and-spoke pattern with Record Links (not RELATE for composition)
Implementation Approach
- Define hub table with
data: recordfield pointing to spokes - Define spoke tables with
node: record(node)reverse link for efficient queries - Define graph relations (
has_child,mentions) as SCHEMAFULL TYPE RELATION - Update creation logic to establish bidirectional links in transactions
- Test both query directions (hub→spoke, spoke→hub)
Acceptance Criteria
-
nodetable defined as SCHEMAFULL withdataRecord Link field - Spoke tables (
task,date,schema) defined as SCHEMAFULL + FLEXIBLE withnodereverse link -
has_childrelation defined as SCHEMAFULL withorder: floatfield -
mentionsrelation defined as SCHEMAFULL with required fields - Creation uses atomic transactions to establish bidirectional links
- Both query patterns work:
node.data.statusandtask.node.content - Indexes support efficient spoke queries (e.g.,
WHERE priority = 'high') - Documentation explains hub-and-spoke with Record Links pattern
- Tests verify bidirectional access and query performance
Technical Implementation Notes
Architecture: Hub-and-Spoke with Bidirectional Record Links
NodeSpace uses a hub-and-spoke architecture where:
- Hub (
nodetable): Universal metadata for ALL node types - Spokes (
task,date,schematables): Type-specific queryable data - Record Links (not RELATE): Bidirectional pointers for 1-to-1 composition
- Graph Edges:
has_childandmentionsfor node-to-node relationships
Why Record Links instead of RELATE for hub-and-spoke:
- ✅ Faster performance (no graph traversal overhead for composition)
- ✅ Cleaner syntax (
node.data.statusvs->is_a->task.status) - ✅ Better for 1-to-1 relationships (node "contains" task data)
- ✅ Direct field access for UI bindings
Why Bidirectional Links:
- ✅ Efficient spoke queries with indexes (
SELECT * FROM task WHERE priority = 'high') - ✅ Access hub context from spoke (
task.node.content,task.node.createdAt) - ✅ No subqueries needed for joined data
See SurrealDB Record Links Video for detailed explanation.
Core Schema Definitions
File: packages/core/src/db/schema.surql
-- ============================================================================
-- HUB TABLE (SCHEMAFULL - Universal metadata)
-- ============================================================================
-- Node table: Universal metadata for ALL node types
DEFINE TABLE node SCHEMAFULL;
-- Required universal fields
DEFINE FIELD id ON TABLE node TYPE string ASSERT $value != NONE;
DEFINE FIELD content ON TABLE node TYPE string DEFAULT "";
DEFINE FIELD nodeType ON TABLE node TYPE string ASSERT $value != NONE;
DEFINE FIELD data ON TABLE node TYPE option<record>; -- Record Link to spoke (task, date, schema, or NULL)
DEFINE FIELD version ON TABLE node TYPE int DEFAULT 1 ASSERT $value >= 1;
DEFINE FIELD createdAt ON TABLE node TYPE datetime DEFAULT time::now();
DEFINE FIELD modifiedAt ON TABLE node TYPE datetime DEFAULT time::now();
-- Indexes for performance
DEFINE INDEX idx_node_type ON TABLE node COLUMNS nodeType;
DEFINE INDEX idx_node_modified ON TABLE node COLUMNS modifiedAt;
-- NO beforeSiblingId - structure lives in has_child edges!
-- NO parentId - hierarchy lives in has_child edges!
-- ============================================================================
-- SPOKE TABLES (SCHEMAFULL + FLEXIBLE - Type-specific queryable data)
-- ============================================================================
-- Task spoke: Status, priority, due dates with efficient indexing
DEFINE TABLE task SCHEMAFULL;
DEFINE FIELD id ON TABLE task TYPE record ASSERT $value != NONE;
DEFINE FIELD node ON TABLE task TYPE record(node) ASSERT $value != NONE; -- Reverse link to hub
-- Core task fields (indexed for queries)
DEFINE FIELD status ON TABLE task TYPE string DEFAULT 'todo';
DEFINE FIELD priority ON TABLE task TYPE option<string>;
DEFINE FIELD due_date ON TABLE task TYPE option<datetime>;
DEFINE FIELD assignee ON TABLE task TYPE option<record>;
-- Indexes for efficient spoke queries
DEFINE INDEX idx_task_status ON TABLE task COLUMNS status;
DEFINE INDEX idx_task_priority ON TABLE task COLUMNS priority;
DEFINE INDEX idx_task_due_date ON TABLE task COLUMNS due_date;
-- User extensions allowed
DEFINE FIELD * ON TABLE task FLEXIBLE;
-- ============================================================================
-- Date spoke: Timezone, holiday tracking
DEFINE TABLE date SCHEMAFULL;
DEFINE FIELD id ON TABLE date TYPE record ASSERT $value != NONE;
DEFINE FIELD node ON TABLE date TYPE record(node) ASSERT $value != NONE; -- Reverse link to hub
-- Core date fields
DEFINE FIELD timezone ON TABLE date TYPE string DEFAULT 'UTC';
DEFINE FIELD is_holiday ON TABLE date TYPE bool DEFAULT false;
-- User extensions allowed
DEFINE FIELD * ON TABLE date FLEXIBLE;
-- ============================================================================
-- Schema spoke: Type definitions
DEFINE TABLE schema SCHEMAFULL;
DEFINE FIELD id ON TABLE schema TYPE record ASSERT $value != NONE;
DEFINE FIELD node ON TABLE schema TYPE record(node) ASSERT $value != NONE; -- Reverse link to hub
-- Core schema fields
DEFINE FIELD is_core ON TABLE schema TYPE bool DEFAULT false;
DEFINE FIELD version ON TABLE schema TYPE int DEFAULT 1;
DEFINE FIELD fields ON TABLE schema TYPE array DEFAULT [];
-- User extensions allowed
DEFINE FIELD * ON TABLE schema FLEXIBLE;
-- ============================================================================
-- GRAPH RELATIONS (SCHEMAFULL - Node-to-node relationships)
-- ============================================================================
-- Has_child relation: Hierarchical relationships with fractional ordering
DEFINE TABLE has_child SCHEMAFULL TYPE RELATION IN node OUT node;
-- Required fields for hierarchy
DEFINE FIELD order ON TABLE has_child TYPE float ASSERT $value != NONE;
DEFINE FIELD createdAt ON TABLE has_child TYPE datetime DEFAULT time::now();
DEFINE FIELD version ON TABLE has_child TYPE int DEFAULT 1; -- OCC for concurrent edits
-- Index for efficient ordering queries
DEFINE INDEX idx_child_order ON TABLE has_child COLUMNS in, order;
-- Ensure unique parent-child relationships
DEFINE INDEX idx_unique_child ON TABLE has_child COLUMNS in, out UNIQUE;
-- ============================================================================
-- Mentions relation: Bidirectional references between nodes
DEFINE TABLE mentions SCHEMAFULL TYPE RELATION IN node OUT node;
-- Required base fields
DEFINE FIELD createdAt ON TABLE mentions TYPE datetime DEFAULT time::now();
DEFINE FIELD context ON TABLE mentions TYPE string DEFAULT "";
DEFINE FIELD offset ON TABLE mentions TYPE int DEFAULT 0;
-- Indexes for efficient queries
DEFINE INDEX idx_mentions_in ON TABLE mentions COLUMNS in;
DEFINE INDEX idx_mentions_out ON TABLE mentions COLUMNS out;
-- Prevent duplicate mentions
DEFINE INDEX idx_unique_mention ON TABLE mentions COLUMNS in, out UNIQUE;Creation Pattern (Atomic Bidirectional Links)
File: packages/core/src/db/surreal_store.rs
/// Create task with bidirectional hub-spoke links
pub async fn create_task(
&self,
content: &str,
status: &str,
priority: Option<&str>,
) -> Result<String> {
let uuid = Uuid::new_v4().to_string();
// Single atomic transaction ensures both links are created
self.db.query(r#"
BEGIN TRANSACTION;
-- Step 1: Create spoke (type-specific data)
CREATE task:$uuid CONTENT {
id: type::thing('task', $uuid),
node: type::thing('node', $uuid), -- Reverse link to hub
status: $status,
priority: $priority
};
-- Step 2: Create hub (universal metadata)
CREATE node:$uuid CONTENT {
id: type::thing('node', $uuid),
nodeType: 'task',
content: $content,
data: type::thing('task', $uuid), -- Forward link to spoke
version: 1,
createdAt: time::now(),
modifiedAt: time::now()
};
COMMIT TRANSACTION;
"#)
.bind(("uuid", &uuid))
.bind(("content", content))
.bind(("status", status))
.bind(("priority", priority))
.await?;
Ok(format!("node:{}", uuid))
}
/// Create simple text node (no spoke)
pub async fn create_text_node(&self, content: &str) -> Result<String> {
let uuid = Uuid::new_v4().to_string();
// Text nodes don't need spoke table - just hub
self.db.query(r#"
CREATE node:$uuid CONTENT {
id: type::thing('node', $uuid),
nodeType: 'text',
content: $content,
data: NONE, -- No spoke for text nodes
version: 1,
createdAt: time::now(),
modifiedAt: time::now()
}
"#)
.bind(("uuid", &uuid))
.await?;
Ok(format!("node:{}", uuid))
}Query Patterns (Both Directions)
-- Pattern 1: Hub → Spoke (via data Record Link)
SELECT
id,
content,
data.status, -- Dereference to spoke
data.priority
FROM node:abc
WHERE nodeType = 'task';
-- Returns:
-- { id: 'node:abc', content: '...', status: 'in_progress', priority: 'high' }
-- Pattern 2: Spoke → Hub (via node reverse link)
SELECT
*,
node.content AS title, -- Access hub fields
node.createdAt,
node->has_child->node AS children -- Access hub structure
FROM task
WHERE priority = 'high';
-- Returns:
-- [{ id: 'task:abc', status: 'in_progress', priority: 'high', title: '...', createdAt: '...', children: [...] }]
-- Pattern 3: Mixed nodes with spoke data (generic query)
SELECT
id,
nodeType,
content,
data.* -- Automatically dereferences to spoke fields (or NULL)
FROM node
WHERE id IN $nodeIds;
-- Returns mixed types:
-- [
-- { id: 'node:abc', nodeType: 'task', content: '...', status: 'in_progress', priority: 'high' },
-- { id: 'node:def', nodeType: 'text', content: '...', data: null },
-- { id: 'node:ghi', nodeType: 'task', content: '...', status: 'done', priority: 'low' }
-- ]
-- Pattern 4: Efficient spoke query with index
SELECT
*,
node.content AS title,
node.createdAt
FROM task
WHERE status = 'in_progress' -- Uses idx_task_status for fast lookup
ORDER BY priority DESC;
-- Pattern 5: Recursive tree with spoke data
SELECT
id,
content,
data.*,
->has_child->(node ORDER BY ->has_child.order).{..}.{
id,
content,
data.*,
children: ->has_child->(node ORDER BY ->has_child.order).@
} AS children
FROM node:root;Frontend Access Patterns
// Pattern 1: Generic node context (mixed types)
const nodes = await nodeService.getChildren(parentId);
nodes.forEach(node => {
if (node.nodeType === 'task') {
console.log(node.data.status); // Via Record Link
console.log(node.data.priority);
}
});
// Pattern 2: Type-specific query (direct spoke access)
const tasks = await db.query('SELECT * FROM task WHERE status = "in_progress"');
// Grid binding - direct field access
<DataGrid
data={tasks}
columns={[
{ field: 'status', header: 'Status' }, // task.status
{ field: 'priority', header: 'Priority' }, // task.priority
{ field: 'node.content', header: 'Title' }, // Via reverse link
]}
/>
// Pattern 3: Spoke query with hub context
const tasksWithContext = await db.query(`
SELECT
*,
node.content AS title,
node.createdAt,
node->has_child->node AS children
FROM task
WHERE status = 'in_progress'
`);Why This Architecture?
Hub-and-Spoke Benefits:
- Fast Type-Specific Queries - Index spoke fields (status, priority) for O(log n) lookups
- Clean Separation - Universal metadata (hub) vs type-specific data (spoke)
- Flexible Schema - Add new spokes without modifying hub
- Efficient Storage - Simple nodes (text, header) don't need spokes
Bidirectional Links Benefits:
- No Subqueries - Access hub from spoke via direct field (
task.node.content) - Performance - Indexed spoke queries with hub context in single query
- Simplicity - Clear access pattern from either direction
Record Link vs RELATE:
- Use Record Link for composition (node "contains" task data)
- Use RELATE for relationships (node→node connections like
has_child,mentions)
Spoke Tables Strategy
Create spoke tables ONLY for types with structured, queryable data:
✅ Need Spokes:
task- Has status, priority, due_date (indexed fields)date- Has timezone, is_holiday (structured data)schema- Has is_core, version, fields (metadata)
❌ Don't Need Spokes:
text- Just content (no type-specific fields)header- Level derived from markdown#code-block- Language derived from markdown```rustquote-block- Just contentordered-list- Just content
For simple types, data = null and all info lives in node.content.
Migration Script
File: packages/core/src/db/migrations/001_hub_spoke_schema.sql
Since NodeSpace has zero users and no production data, this is a direct implementation:
-- Drop and recreate with proper schema (development only)
REMOVE TABLE IF EXISTS node;
REMOVE TABLE IF EXISTS task;
REMOVE TABLE IF EXISTS date;
REMOVE TABLE IF EXISTS schema;
REMOVE TABLE IF EXISTS has_child;
REMOVE TABLE IF EXISTS mentions;
-- Create hub table
-- [Insert node schema from above]
-- Create spoke tables with reverse links
-- [Insert task, date, schema schemas from above]
-- Create graph relations
-- [Insert has_child, mentions schemas from above]Validation Tests
File: packages/core/src/tests/hub-spoke-schema.test.ts
import { describe, it, expect } from 'vitest';
import { testDb } from '../test-utils';
describe('Hub-and-Spoke Schema', () => {
describe('Hub table validation', () => {
it('should enforce required fields on node table', async () => {
await expect(
testDb.create('node', {
content: 'Test' // Missing nodeType
})
).rejects.toThrow(/required field/);
});
it('should allow NULL data for simple nodes', async () => {
const node = await testDb.create('node', {
id: 'node:abc',
nodeType: 'text',
content: 'Simple text',
data: null,
version: 1
});
expect(node.data).toBeNull();
});
});
describe('Bidirectional links', () => {
it('should create bidirectional links atomically', async () => {
const uuid = crypto.randomUUID();
await testDb.query(`
BEGIN TRANSACTION;
CREATE task:${uuid} CONTENT {
id: type::thing('task', '${uuid}'),
node: type::thing('node', '${uuid}'),
status: 'in_progress'
};
CREATE node:${uuid} CONTENT {
id: type::thing('node', '${uuid}'),
nodeType: 'task',
content: 'Test task',
data: type::thing('task', '${uuid}'),
version: 1
};
COMMIT TRANSACTION;
`);
// Verify hub → spoke
const node = await testDb.select(`node:${uuid}`);
expect(node.data.status).toBe('in_progress');
// Verify spoke → hub
const task = await testDb.select(`task:${uuid}`);
expect(task.node.content).toBe('Test task');
});
});
describe('Query patterns', () => {
it('should efficiently query spokes with indexes', async () => {
const tasks = await testDb.query(`
SELECT
*,
node.content AS title
FROM task
WHERE status = 'in_progress'
`);
tasks.forEach(task => {
expect(task).toHaveProperty('status');
expect(task).toHaveProperty('title');
});
});
it('should handle mixed node types with NULL data', async () => {
const nodes = await testDb.query(`
SELECT
id,
nodeType,
content,
data.*
FROM node
`);
const textNode = nodes.find(n => n.nodeType === 'text');
expect(textNode.data).toBeNull();
const taskNode = nodes.find(n => n.nodeType === 'task');
expect(taskNode.data).toHaveProperty('status');
});
});
describe('Graph relations', () => {
it('should enforce fractional ordering on has_child', async () => {
await expect(
testDb.query(`
RELATE node:parent->has_child->node:child
`)
).rejects.toThrow(/required field.*order/);
});
it('should accept has_child with fractional order', async () => {
const edge = await testDb.query(`
RELATE node:parent->has_child->node:child CONTENT {
order: 1.5,
createdAt: time::now(),
version: 1
}
`);
expect(edge[0].order).toBe(1.5);
});
});
});Resources & References
- SurrealDB Record Links: https://surrealdb.com/docs/surrealql/datamodel/ids
- SurrealDB Schema: https://surrealdb.com/docs/surrealql/statements/define/table
- SurrealDB Video - Record Links vs RELATE: Simplify graph edges with record references
- Current Schema:
packages/core/src/db/init.sql - Seeding Logic:
packages/core/src/db/seed.ts
Dependencies
- Migrate database schema to use fractional ordering instead of beforeSiblingId linked-list #550 (fractional ordering implementation)
- Implement SurrealDB LIVE SELECT for real-time node and edge updates #551 (LIVE SELECT for reactivity)
Related Issues
- Implement atomic moveNode operation with fractional ordering #552 (atomic moveNode operations)
- Create ReactiveStructureTree store with LIVE SELECT integration #553 (ReactiveStructureTree expects this schema)
- Create ReactiveNodeData store with debounced content updates #554 (ReactiveNodeData stores for hub and spoke)
Definition of Done
- Hub table (
node) defined as SCHEMAFULL withdata: recordfield - Spoke tables (
task,date,schema) defined withnode: record(node)reverse link -
has_childandmentionsrelations defined as SCHEMAFULL - Creation logic uses atomic transactions for bidirectional links
- Both query patterns work: hub→spoke and spoke→hub
- Indexes support efficient spoke queries
- Simple nodes (text, header, etc.) work with
data = null - Documentation explains hub-and-spoke pattern
- Tests verify bidirectional access and atomic creation
- No RELATE edges used for hub-spoke composition
Activity
WIP: Implement SCHEMAFULL schema with hub-and-spoke architecture (Issue
malibio commentedon Nov 20, 2025
WIP Progress Update
Pushed WIP commit implementing the core schema changes for SCHEMAFULL hub-and-spoke architecture.
Completed ✅
packages/core/src/db/schema.surqlwith SCHEMAFULL definitionsnode) withdata: option<record>for Record Linkstask,date,schema) withnode: recordreverse linkshas_child,mentions) with required fields and indexesSurrealStore::initialize_schema()to load from schema filesurreal_store.rshub_spoke_schema_test.rs) with 8 tests (1/8 passing)Remaining Work 🔧
Current Status
The schema file loads without errors and defines the proper hub-and-spoke structure. The test framework is in place and demonstrates the query patterns, just needs syntax fixes to validate functionality.
Branch:
feature/issue-560-hub-spoke-schemafullCommit: b25fe78
Fix UUID syntax and Record Link deserialization (Issue #560)
WIP: Fix UUID syntax and Record Link deserialization (Issue #560)
malibio commentedon Nov 20, 2025
Progress Update - WIP Commit c705a39
✅ Major Breakthroughs
UUID Syntax Fixed: UUIDs with hyphens require backticks in SurrealDB
CREATE node:`550e8400-e29b-41d4-a716-446655440000` CONTENT {...};Record Link Solution: Use
surrealdb::sql::Thinginstead ofserde_json::ValueSDK Upgraded: SurrealDB 2.2 → 2.3.10 (latest stable)
📊 Current Status
🎯 Next Steps
The core architecture is validated and working - remaining work is applying the same patterns to complete test coverage.
Branch:
feature/issue-560-hub-spoke-schemafullLatest Commit: c705a39
Complete hub-spoke SCHEMAFULL schema with all tests passing (Issue #560)
WIP: Implement SCHEMAFULL schema with hub-and-spoke architecture (Issue
WIP: Fix UUID syntax and Record Link deserialization (Issue #560)
Complete hub-spoke SCHEMAFULL schema with all tests passing (Issue #560)
Define core tables as SCHEMAFULL with strict validation (#563)
Define core tables as SCHEMAFULL with strict validation (#563)
Define core tables as SCHEMAFULL with strict validation (#563)
Define core tables as SCHEMAFULL with strict validation (#563)