Skip to content

Database migration fails when upgrading from older versions - "no such column: sdk_session_id" #482

Description

@qiaoqinyu

● ## Bug: Database migration fails when upgrading from older versions - "no such column: sdk_session_id"

Description

When upgrading to claude-mem 8.2.7 from an older version, the /api/context/inject endpoint returns HTTP 500 with error:

{"error":"no such column: sdk_session_id"}

Root Cause

Migration 17 (renameSessionIdColumns) has a logic flaw. It checks only the sdk_sessions table to determine if migration should be skipped:

if(this.db.query("PRAGMA table_info(sdk_sessions)").all().some(r=>r.name==="content_session_id")){
  // Skip migration if sdk_sessions already has content_session_id
  return;
}

However, this doesn't account for databases from older versions where:
- sdk_sessions table may already have content_session_id (from a previous partial migration or different upgrade path)
- But observations and session_summaries tables never had the sdk_session_id column in the first place

The migration then tries to RENAME COLUMN sdk_session_id TO memory_session_id on tables where that column doesn't exist, causing subsequent queries to fail.

Steps to Reproduce

1. Have an older claude-mem database (pre-sdk_session_id column era)
2. Upgrade to version 8.2.7
3. Start the worker
4. Call /api/context/inject?project=test
5. Observe 500 error: no such column: sdk_session_id

Environment

- claude-mem version: 8.2.7
- OS: Ubuntu (WSL2)
- Node.js: v20.19.6

Workaround

Manually add the missing columns:

ALTER TABLE observations ADD COLUMN sdk_session_id INTEGER REFERENCES sdk_sessions(id);
ALTER TABLE session_summaries ADD COLUMN sdk_session_id INTEGER REFERENCES sdk_sessions(id);

Suggested Fix

The migration should check each table individually and handle the case where the column doesn't exist:

// For each table, check if column exists before renaming
const obsInfo = this.db.query("PRAGMA table_info(observations)").all();
if (obsInfo.some(col => col.name === 'sdk_session_id')) {
  this.db.run('ALTER TABLE observations RENAME COLUMN sdk_session_id TO memory_session_id');
} else if (!obsInfo.some(col => col.name === 'memory_session_id')) {
  // Column doesn't exist at all - add it
  this.db.run('ALTER TABLE observations ADD COLUMN memory_session_id INTEGER REFERENCES sdk_sessions(id)');
}
// Same pattern for session_summaries

Alternatively, the repairSessionIdColumnRename migration (version 19) could be enhanced to add missing columns instead of only handling renames.

---

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugConfirmed bug

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions