Skip to content

Standardize database schema to snake_case - fix serialization inconsistency #611

Closed

Description

@malibio

Problem

The database schema uses mixed casing conventions AND queries are using incorrect field names:

  • Hub table (node): Uses camelCase (nodeType, createdAt, modifiedAt)
  • Spoke tables (task, date, schema): Uses snake_case (due_date, is_holiday, is_core)
  • Queries: Using wrong field names like type instead of nodeType or node_type

Standard SQL/database convention is snake_case, but our current schema is inconsistent.

Critical Bug: query_nodes() Uses Wrong Field Name

Location: packages/core/src/db/surreal_store.rs:1843

// ❌ CURRENT (BROKEN) - queries for field "type" which doesn't exist
if query.node_type.is_some() {
    conditions.push("type = $node_type".to_string());
}

Impact: This causes query_nodes() to return 0 results, breaking:

  • 35+ tests including test_query_nodes_by_type
  • All node type filtering functionality
  • Container task filters
  • Mention system queries

Root Cause: The database schema has nodeType (camelCase due to Rust serde), but the query uses bare type.

Current State

packages/core/src/db/schema.surql:

-- Hub table uses camelCase ❌
DEFINE FIELD IF NOT EXISTS nodeType ON TABLE node TYPE string ASSERT $value != NONE;
DEFINE FIELD IF NOT EXISTS createdAt ON TABLE node TYPE datetime DEFAULT time::now();
DEFINE FIELD IF NOT EXISTS modifiedAt ON TABLE node TYPE datetime DEFAULT time::now();

-- Spoke tables use snake_case ✅
DEFINE FIELD IF NOT EXISTS due_date ON TABLE task TYPE option<datetime>;
DEFINE FIELD IF NOT EXISTS is_holiday ON TABLE date TYPE bool DEFAULT false;
DEFINE FIELD IF NOT EXISTS is_core ON TABLE schema TYPE bool DEFAULT false;

Root Cause: Serialization Misconfiguration

The issue stems from how the Rust Node struct is serialized:

packages/core/src/models/node.rs (line 117):

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]  // ← Applied to BOTH DB and Frontend
pub struct Node {
    pub node_type: String,  // Rust field: snake_case
    pub created_at: String,
    pub modified_at: String,
}

The Problem:

  • #[serde(rename_all = "camelCase")] is applied globally
  • This converts node_type → nodeType for both database writes AND frontend responses
  • The database schema was created with camelCase fields because of this serialization
  • But queries are inconsistently using type, nodeType, or node_type

Current Flow:

Rust Code           Serde Serialization      Database Schema
─────────           ───────────────────      ───────────────
node_type      →    nodeType (camelCase) →   nodeType ❌
created_at     →    createdAt            →   createdAt ❌

Database Query      Field Reference          Result
──────────────      ───────────────          ──────
WHERE type = ?      "type" (doesn't exist)   0 results ❌

What it should be:

Rust Code           DB Serialization         Database Schema
─────────           ────────────────         ───────────────
node_type      →    node_type           →    node_type ✅
created_at     →    created_at          →    created_at ✅

                    Frontend Serialization   TypeScript
                    ──────────────────────   ──────────
node_type      →    nodeType            →    nodeType ✅

Database Query      Field Reference          Result
──────────────      ───────────────          ──────
WHERE node_type = ? "node_type" (exists)     Correct ✅

Proposed Solution

Phase 1: Immediate Bug Fix (Query Field Names)

Fix the broken query in query_nodes():

// packages/core/src/db/surreal_store.rs:1843
if query.node_type.is_some() {
    conditions.push("nodeType = $node_type".to_string());  // Match current schema
}

Impact: Fixes 35+ failing tests immediately without schema migration.

Phase 2: Long-term Solution (Database Schema Migration)

1. Update Database Schema to snake_case

packages/core/src/db/schema.surql:

-- Hub table: Change to snake_case
DEFINE FIELD IF NOT EXISTS node_type ON TABLE node TYPE string ASSERT $value != NONE;
DEFINE FIELD IF NOT EXISTS created_at ON TABLE node TYPE datetime DEFAULT time::now();
DEFINE FIELD IF NOT EXISTS modified_at ON TABLE node TYPE datetime DEFAULT time::now();
DEFINE FIELD IF NOT EXISTS data ON TABLE node TYPE option<record>;

-- Update indexes
DEFINE INDEX IF NOT EXISTS idx_node_type ON TABLE node COLUMNS node_type;
DEFINE INDEX IF NOT EXISTS idx_node_modified ON TABLE node COLUMNS modified_at;

2. Fix Rust Serialization (Two Options)

Option A: Separate serialization for DB vs Frontend

Use different serde attributes for database vs frontend boundaries:

// For database operations - use snake_case as-is
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Node {
    pub node_type: String,      // Serializes as "node_type" to DB
    pub created_at: String,
    pub modified_at: String,
}

// For Tauri commands - add camelCase conversion layer
// (in src-tauri/src/commands/models.rs or similar)
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NodeResponse {
    pub node_type: String,  // Serializes as "nodeType" to frontend
    pub created_at: String, // Serializes as "createdAt" to frontend
    pub modified_at: String,
}

Option B: Keep current struct, use explicit DB serialization

// Keep current struct for frontend compatibility
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Node {
    #[serde(alias = "node_type")]  // Allow DB snake_case on read
    pub node_type: String,
}

// Add custom DB serialization logic in surreal_store.rs
// to convert camelCase → snake_case before writing

3. Database Migration

Create migration to rename existing fields:

-- Migration script (executed once)
UPDATE node SET node_type = nodeType;
UPDATE node SET created_at = createdAt;
UPDATE node SET modified_at = modifiedAt;

-- Remove old fields
REMOVE FIELD nodeType ON TABLE node;
REMOVE FIELD createdAt ON TABLE node;
REMOVE FIELD modifiedAt ON TABLE node;

Note: There may be existing migration/schema sync infrastructure from previous work on "SchemaNode <-> SurrealDB Schema" that handles this pattern.

Benefits

  1. Consistency - All database fields use standard snake_case convention
  2. Clear Boundaries - Database uses snake_case, frontend receives camelCase
  3. Standards Compliance - Follows SQL/database naming conventions (per identifier-naming-conventions.md)
  4. Maintainability - Separate concerns: DB format vs API format
  5. Bug Prevention - Eliminates confusion about which field name to use in queries

Related Documentation

  • docs/architecture/development/standards/identifier-naming-conventions.md - Establishes the standard:
    • Line 263-292: "Always use nodeType (full qualifier)"
    • Line 438: Database fields should be node_type (snake_case)
    • Line 166-180: "Database Field Names... ✅ Correct - snake_case"

Acceptance Criteria

Phase 1: Quick Fix (Immediate)

  • Update query_nodes() to use nodeType field name (matches current schema)
  • Update any other queries using incorrect field names
  • All 35+ failing tests now pass
  • Document this as temporary fix pending Phase 2

Phase 2: Schema Migration (Long-term)

  • All hub table fields use snake_case in schema.surql
  • Database migration successfully renames existing fields
  • Rust serialization properly separates DB vs Frontend boundaries
  • All database queries use snake_case field names
  • Frontend still receives camelCase via Tauri commands
  • All tests passing (especially database integration tests)
  • No breaking changes to frontend TypeScript types

Scope

In Scope:

  • Hub table field naming (node_type, created_at, modified_at)
  • Query field reference consistency
  • Database schema migration
  • Rust serialization layer separation

Out of Scope:

  • Spoke table changes (already use snake_case correctly)
  • Frontend TypeScript changes (continues to use camelCase)
  • MCP protocol changes (frontend API unchanged)

Related Issues

Activity

  1. malibio commented on Nov 22, 2025

    @malibio
    CollaboratorAuthor

    Test Baseline (before implementation)

    Rust Tests: 502 passed, 35 failed, 14 ignored

    The 35 failing tests confirm the query field name issue described in the issue. These tests are expected to pass after Phase 1 fix.

    Frontend Tests: All passing (728+ tests in ~12 seconds)

    Starting implementation on feature branch.

  2. self-assigned this
    on Nov 22, 2025
  3. malibio commented on Nov 22, 2025

    @malibio
    CollaboratorAuthor

    Phase 1 Fix Validation Complete

    After investigation, confirmed that:

    ✅ Phase 1 Fix is CORRECT and WORKING

    • test_query_nodes_by_type now PASSES (was failing in baseline)
    • All 4 query field name changes are correct: type → nodeType
    • Changes match the current database schema

    ⚠️ Schema Test Failures are PRE-EXISTING

    • Schema test failures (14 tests) are NOT caused by Phase 1 changes
    • Tests fail identically on main branch without modifications
    • These failures are unrelated to the database field name issue
    • Appears to be a separate pre-existing bug in schema node creation

    Next Steps:

    • Phase 1 fix is ready to commit
    • Phase 2 (schema migration to snake_case) can proceed independently
    • Schema test failures should be addressed in separate issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions