Database Schema
PostgreSQL — центр истины платформы
67
Таблиц
205+
Миграций
66
Views
100+
Индексов
20+
Functions
Схемы базы данных
clowbotОсновная схема с бизнес-данными
Таблиц: 67
martАналитические views и marts
Views: 66
publicPostgreSQL extensions
Таблиц: 0
Доменная структура
Core Domain
Пользователи, чаты, сообщения, сессии
users
chats
groups
messages
sessions
settings
Process Domain
Процессы, запуски, шаги, артефакты
processes
process_runs
process_run_steps
process_artifacts
process_templates
Agent Domain
Агенты, методы, выбор, эффективность
agent_profile
agent_methods
agent_sub_agents
agent_selection_policy
agent_effectiveness
Policy Domain
Runtime политики, RBAC, провайдеры
runtime_policy
rbac_policies
llm_providers
hardware_profiles
timeout_profiles
Operator Domain
Задачи, события, напоминания
tasks
task_events
task_links
operator_runs
reminders
recurring_tasks
Content Domain
Контент, документы, аналитика
content_subjects
channel_registry
content_analytics
table_document
document_attribution
Ключевые связи (ER)
| From | → | To | Type | FK |
|---|---|---|---|---|
users | → | chats | 1:N | owner_id |
chats | → | messages | 1:N | chat_id |
processes | → | process_runs | 1:N | process_id |
process_runs | → | process_run_steps | 1:N | run_id |
process_run_steps | → | llm_calls | 1:N | step_id |
users | → | tasks | 1:N | owner_id |
tasks | → | task_events | 1:N | task_id |
agent_profile | → | agent_methods | 1:N | agent_code |
users | → | reminders | 1:N | user_id |
Ядерные таблицы (Top 15)
| Таблица | Описание | Ключевые поля | Rows |
|---|---|---|---|
users | Пользователи Telegram | telegram_user_id, username, tier | ~1000 |
chats | Чаты | telegram_chat_id, chat_type | ~500 |
messages | Сообщения | chat_id, role, content | ~100K |
processes | Шаблоны процессов | code, name, contract | ~50 |
process_runs | Запуски процессов | process_id, status, current_step | ~10K |
agent_profile | Профили агентов | agent_code, goal, allowed_tools | ~10 |
tasks | Задачи оператора | task_type, status, priority | ~5K |
runtime_policy | Runtime политики | key, value, namespace | ~10 |
reminders | Напоминания | user_id, due_at, status | ~500 |
llm_calls | Логи LLM-вызовов | model, prompt_tokens, completion_tokens | ~50K |
automation_events | События автоматизации | event_type, payload | ~20K |
workflow_registry | Реестр workflow-ов | workflow_id, name, active | ~20 |
table_document | Документы пользователей | user_id, doc_type, content | ~2K |
billing_events | Биллинг | user_id, amount, status | ~100 |
teams | Команды | name, owner_id | ~10 |
Ключевые индексы
| Table | Index Name | Columns |
|---|---|---|
messages | idx_messages_chat_created | chat_id, created_at DESC |
process_runs | idx_process_runs_status | status, created_at |
llm_calls | idx_llm_calls_created | created_at DESC |
tasks | idx_tasks_owner_status | owner_id, status |
reminders | idx_reminders_due | due_at, status |
Performance tip: Все частые запросы должны использовать индексы. Проверяй через EXPLAIN ANALYZE.
Миграции
Расположение
db/init/Нумерация
NNN_description.sqlПорядок
Alphabetical (001 → 400)Скрипт
scripts/apply_migrations_docker.shПРИМЕР МИГРАЦИИ
-- 359_agent_profiles.sql
CREATE TABLE IF NOT EXISTS clowbot.agent_profile (
agent_code text PRIMARY KEY,
goal text NOT NULL DEFAULT '',
allowed_tools text[] NOT NULL DEFAULT '{}',
preferred_models text[] NOT NULL DEFAULT '{}',
is_active boolean NOT NULL DEFAULT true,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_agent_profile_code
ON clowbot.agent_profile (agent_code);Марты и Views
Аналитические представления в схеме mart.*
mart.vw_tasksЗадачи с JOIN пользователей и чатов
mart.vw_task_treeРекурсивное дерево задач
mart.vw_process_test_gateQuality gate для процессов
mart.vw_llm_usageСтатистика использования LLM
mart.vw_agent_performanceЭффективность агентов
mart.vw_reminder_statsСтатистика напоминаний
Полезные запросы
Размер таблиц:
SELECT
schemaname || '.' || tablename as table,
pg_size_pretty(pg_total_relation_size(schemaname || '.' || tablename)) as size
FROM pg_tables
WHERE schemaname IN ('clowbot', 'mart')
ORDER BY pg_total_relation_size(schemaname || '.' || tablename) DESC
LIMIT 20;Список всех таблиц:
SELECT tablename FROM pg_tables WHERE schemaname = 'clowbot' ORDER BY tablename;
Структура таблицы:
\d clowbot.agent_profile -- Или SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'clowbot' AND table_name = 'agent_profile';
← Architecture
Core Tables
Runtime Policy