Skip to content

πŸ”§ [P0] Refactor tag storage: JSON-in-TEXT β†’ junction tableΒ #120

Closed

Description

@ajianaz

Problem

Tags are stored as JSON strings (["tag1","tag2"]) in a SQLite TEXT column and queried with LIKE '%"tagname"%'. This is:

  • Fragile β€” tag names containing quotes (") break matching
  • O(n) full-scan β€” no index utilization despite JSON data
  • Incorrect β€” searching for literal % or _ wildcards returns everything
  • Untenable β€” N+1 query pattern in tags_with_counts() (one SQL query per unique tag)

Affected Code

  • crates/uteke-core/src/memory/store.rs:192-205 β€” tag storage/insert
  • crates/uteke-core/src/memory/store.rs:493-504 β€” tag search via LIKE
  • crates/uteke-core/src/memory/store.rs:516-527 β€” tag filtering
  • crates/uteke-core/src/memory/store.rs:556-591 β€” tag rename
  • crates/uteke-core/src/memory/store.rs:476-490 β€” N+1 count_tag() calls

Proposed Solution

Option A: Junction table (recommended)

CREATE TABLE memory_tags (
  memory_id TEXT NOT NULL REFERENCES memories(id) ON DELETE CASCADE,
  tag TEXT NOT NULL,
  PRIMARY KEY (memory_id, tag)
);
CREATE INDEX idx_memory_tags_tag ON memory_tags(tag);

Option B: SQLite JSON1 extension β€” Use json_each() for proper JSON querying. Simpler but slightly slower than junction table.

Option A recommended because:

  • Proper foreign key constraints + CASCADE delete
  • Direct index on tag column
  • Standard SQL patterns
  • Better query planner visibility

Migration Strategy

  1. Create memory_tags table
  2. Migrate existing JSON tags β†’ rows (handle corrupted JSON gracefully)
  3. Add version column to track schema version (currently ad-hoc, no version tracking)
  4. Update all tag operations to use junction table
  5. Drop old tags TEXT column (or keep as cached view for backward compat)

Acceptance Criteria

  • Tag storage uses junction table or json_each()
  • All tag operations (add, remove, rename, delete, filter, count) work correctly
  • tags_with_counts() uses single GROUP BY query
  • Migration runs cleanly on existing databases (zero data loss)
  • Tags containing quotes, %, _ characters work correctly
  • All existing tests pass + new tests for edge cases
  • No performance regression (benchmark with 1000+ memories, 50+ tags)

Breaking Change

⚠️ Yes β€” database schema change. Migration must handle existing data.

Metadata

Metadata

Assignees

No one assigned

    Labels

    scope:core

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions