AAnvio
Database

Relationships

Foreign keys, cascade rules, and join patterns across the 9-table Drizzle schema.

4 min read

Level 3+ only — see ERD for the full diagram and Tables for column-level detail. This page focuses on how the tables connect and what happens on delete.

Foreign key inventory

Every foreign key in packages/db/src/schema.ts, exactly as declared:

From tableColumnReferencesOn delete
sessionsuser_idusers.idCASCADE
sessionsagent_idagents.id(no action — default RESTRICT)
session_messagessession_idsessions.idCASCADE
memory_entriessession_idsessions.idSET NULL
memory_entriesuser_idusers.idCASCADE
tool_executionssession_idsessions.idCASCADE
agent_skillsagent_idagents.idCASCADE
agent_skillsskill_idskills.idCASCADE

personas has no foreign keys in or out.

Cascade behavior, explained

Deleting a user cascades hard

DELETE FROM users WHERE id = '...'

This cascades to:

  1. All of that user's sessions (via sessions.user_id ON DELETE CASCADE)
  2. Which cascades to all session_messages and tool_executions for those sessions
  3. All of that user's memory_entries directly (via memory_entries.user_id ON DELETE CASCADE)

Deleting a user is destructive and total — there's no soft-delete or archival step at the schema level. If you need to preserve conversation history after account deletion, add that logic in application code before the delete, not after.

Deleting a session is destructive to messages/tools, but not memory

DELETE FROM sessions WHERE id = '...'
  • session_messages for that session: deleted (CASCADE)
  • tool_executions for that session: deleted (CASCADE)
  • memory_entries that reference that session: kept, but session_id is set to NULL (SET NULL)

This is intentional: a memory entry (a fact learned, a summary stored) is meant to outlive the session that produced it. The transcript and tool audit log are considered session-scoped and disposable; memory is considered durable.

Deleting an agent does NOT cascade

sessions.agent_id REFERENCES agents.id has no onDelete clause, which means Postgres defaults to NO ACTION (effectively RESTRICT). Attempting to delete an agents row that has any sessions referencing it will fail with a foreign key violation. In practice, agents aren't expected to be deleted through this table at all — agent definitions are normally managed as files in workspace/agents/ (Level 1) and only mirrored into Postgres for Level 3 lookups.

Deleting a skill or agent cascades through the join table only

agent_skills cascades on both sides — deleting either an agent or a skill removes the corresponding join rows, but (per above) deleting an agent will itself be blocked first if sessions reference it.

Relationship cardinality summary

Rendering diagram…

Why no relation to the filesystem session model?

The Postgres sessions table and the runtime's StoredSession (used by SessionStore, ChannelSessionBridge, and the Channel Hub — see Channel Adapters) are related concepts but not the same object. At Level 1–2, sessions live as JSONL files or SQLite rows managed by @anvio/workspace, independent of this Drizzle schema. The Postgres schema is one possible persistence backend for Level 3, wired in by choosing storage.provider / memory.provider in workspace/anvio.yaml — it is not automatically the source of truth just because it exists in the monorepo.

Querying relationships with Drizzle

Example: fetch a session with its messages and the agent it ran as, using the relations declared above (via drizzle-orm's query builder — see packages/db/src/index.ts for the createDb() factory that wires schema into the client):

import { eq } from 'drizzle-orm';
import { createDb, sessions, sessionMessages, agents } from '@anvio/db';

const db = createDb(process.env.DATABASE_URL!);

const [session] = await db.select().from(sessions).where(eq(sessions.id, sessionId));
const messages = await db
  .select()
  .from(sessionMessages)
  .where(eq(sessionMessages.sessionId, sessionId));
const [agent] = await db.select().from(agents).where(eq(agents.id, session.agentId));

TODO: verify against packages/db/src — no Drizzle relations() helper calls were found in schema.ts (only raw pgTable + .references()). If you need db.query.sessions.findMany({ with: { messages: true } })-style relational queries, you'll need to add relations() definitions yourself; they don't exist yet.

Edit on GitHub

Last updated on

On this page