AgentSkillsCN

Database

为本地与云端模式分别配置SQLite数据库,包括数据库架构、模块与各项设置。

SKILL.md
--- frontmatter
name: Database
description: SQLite database setup, schema, modules, and configuration for local and cloud modes.

Database

Brain uses SQLite for all data storage, via better-sqlite3 (local file).

Environment Variables

VariableDefaultDescription
DATABASE_URLfile:./brain.dbPath for local database file
TEST_MODESet to true or 1 to use the test database
TEST_DB_PATHbrain.test.dbPath to the test database file

Local Mode

The default for development. Uses better-sqlite3 with a single file (brain.db) in the project root. No configuration needed — the database file and schema are created automatically on first run.

SQLite pragmas enabled:

  • journal_mode = WAL — Write-Ahead Logging for better concurrency
  • foreign_keys = ON — Enforce foreign key constraints

The sqlite-vec extension is loaded when available for vector search support.

Testing

Tests use a separate database (brain.test.db) so they don't touch production data. Both variables are set in .env.test:

env
TEST_MODE=true
TEST_DB_PATH=brain.test.db

Schema

Schema is defined in src/lib/db/db-schema.ts and initialized automatically via initializeSchema() on first access. Uses CREATE TABLE IF NOT EXISTS for safe initialization.

Migrations are handled inline in the same file using ALTER TABLE statements with try/catch (no separate migration system).

Tables

TableDescription
usersUser accounts (email, password)
foldersOrganization folders for conversations and documents
conversationsChat conversations with settings (AI provider, grounding, response mode)
messagesChat messages with thinking/thoughts support
documentsUser documents
document_snapshotsVersion history for documents
conversation_documentsMany-to-many: conversations ↔ documents
file_attachmentsFiles attached to messages
eventsCalendar events with recurrence
events_ftsFull-text search virtual table for events
user_memoryUser memory/notes
user_kv_storeKey-value store for user preferences
shared_linksShared links for conversations, documents, snapshots
jobsBackground job tracking
job_eventsStreaming events for jobs
job_queueJob queue with priority and claiming
factsKnowledge facts with categories
fact_extractionsMany-to-many: facts ↔ conversations
fact_sheetsAggregated fact sheets with dedup log
fact_vecVector embeddings for semantic search (sqlite-vec virtual table)

Architecture

DbWrapper

Both local and cloud modules export a dbWrapper conforming to the DbWrapper interface (src/lib/db/db-types.ts). This provides a common async API:

  • prepare(sql) → returns { all(), get(), run() } (all async)
  • exec(sql) — execute raw SQL
  • transaction(fn) — wrap operations in a transaction

Note: better-sqlite3 is synchronous under the hood. The async wrapper provides API consistency.

Module Organization

All database operations live in src/lib/db/ and are re-exported through src/lib/db.ts as the public facade. Each module receives dbWrapper and ensureInitialized as parameters.

ModuleDomain
db-schema.tsSchema creation and migrations
db-types.tsTypeScript interfaces
db-users.tsUser CRUD
db-conversations.tsConversations, messages, sidebar
db-folders.tsFolder management
db-documents.tsDocument management
db-events.tsCalendar events
db-attachments.tsFile attachments
db-snapshots.tsDocument snapshots
db-shared-links.tsShared links
db-memory.tsUser memory
db-facts.tsFact storage and extraction
db-fact-sheets.tsFact sheet aggregation
db-jobs.tsJob system operations
db-embeddings.tsVector embeddings (sqlite-vec)
db-kv.tsKey-value store

Adding a New Table

  1. Add CREATE TABLE IF NOT EXISTS in src/lib/db/db-schema.ts
  2. Create a new src/lib/db/db-<name>.ts module with operations
  3. Import and re-export functions from src/lib/db.ts
  4. Add TypeScript types to src/lib/db/db-types.ts if needed

Key Files

  • src/lib/db.ts — Main facade, re-exports all operations
  • src/lib/db-local.ts — SQLite connection (better-sqlite3)
  • src/lib/db/db-schema.ts — Schema definitions and inline migrations
  • src/lib/db/db-types.ts — TypeScript interfaces (DbWrapper, row types)

Backup

bash
sqlite3 brain.db ".backup backup.db"