> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zeus.agentspro.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Database

> Zeus database architecture and Drizzle ORM

# Database Architecture

## Overview

Zeus uses a layered database architecture that separates database operations from business logic, achieving clear separation of concerns.

## Architecture Overview

```mermaid theme={null}
flowchart TD
    subgraph Routes["API Routes<br/>web/src/app/api/[resource]/route.ts"]
        R["HTTP request/response handling, parameter validation, permission checks"]
    end

    subgraph Service["Service Layer<br/>web/src/db/service/"]
        S["Business logic, transaction handling, cross-model coordination"]
    end

    subgraph Model["Model Layer<br/>web/src/db/model/"]
        M["Single-table CRUD operations, query building"]
    end

    subgraph SchemaLayer["Schema Layer<br/>web/src/db/schema/"]
        SC["Table structure definitions, relationship declarations, type generation"]
    end

    PostgreSQL[(PostgreSQL)]

    Routes --> Service
    Service --> Model
    Model --> SchemaLayer
    SchemaLayer --> PostgreSQL
```

## Layer Responsibilities

### 1. Schema Layer

Defines table structures and relationships using Drizzle ORM's declarative syntax for database tables, field types, constraints, and foreign key relationships.

### 2. Model Layer

Encapsulates single-table CRUD operations, providing standard methods like `findById`, `findByUserId`, `create`, `update`, and `delete`. Each Model corresponds to one database table.

### 3. Service Layer

Handles business logic, including cross-model transactions and coordinated operations. For example, creating a session while simultaneously adding the first message, or cascade-deleting all messages when a session is deleted.

### 4. API Route Layer

Handles HTTP requests, responsible for permission checks, parameter validation, calling the Service layer, and returning responses. API Routes do not directly operate on the database.

***

# Drizzle ORM

## Overview

Zeus uses Drizzle ORM for type-safe database operations with PostgreSQL.

## Database Tables

The system contains the following database tables (defined in `db/schema/`):

**Authentication & User:**

* `user` - User information (id, name, email, emailVerified, image, etc.)
* `session` - User sessions (linked to user, includes token and expiration time)
* `account` - OAuth accounts (linked to user, stores third-party login information)
* `user_settings` - User preference settings
* `invitation_code` - Invitation codes for registration

**Chat & Sessions:**

* `chat_session` - Chat sessions (linked to user and project)
* `message` - Message records (linked to chat\_session, includes role, content, and tool call information)
* `checkpoint` - Agent state checkpoints for session recovery

**Projects:**

* `project` - Project management (linked to user)
* `settings` - Project-level settings

**Knowledge Base:**

* `knowledge_base` - Knowledge base metadata (linked to user)
* `embedding` - Embedding configuration for vector search

**Tools & Skills:**

* `tools` - MCP server and tool configuration (linked to user, includes tools and prompts)
* `tool_allowlist` - Auto-run tool allowlist per user
* `skills` - Skill configuration and metadata

**AI & Agent:**

* `llm` - LLM model configuration per user
* `memory` - Long-term memory entries (linked to user)
* `sandbox` - Sandbox environment configuration
* `plan` - Agent plan records

**Automation & Credits:**

* `scheduled_task` - Scheduled task definitions
* `credits` - User credit balance and transaction records

**Showcase:**

* `showcase` - Published showcase entries

## Type Safety

Drizzle automatically generates TypeScript types from schema definitions via `InferSelectModel` and `InferInsertModel`, ensuring type safety for query and insert operations.

## Best Practices

### 1. Use Connection Pooling

Configure a database connection pool (recommended max: 20) with reasonable timeout parameters to optimize performance.

### 2. Add Indexes

Add indexes on frequently queried fields, such as foreign key fields like `userId` and `projectId`.

### 3. Use Transactions

For multi-step operations requiring atomicity, use `db.transaction()` to ensure data consistency.

### 4. Batch Operations

Prefer batch inserts and `IN` queries over individual operations in loops.
