Database Schema

PostgreSQL — центр истины платформы

67
Таблиц
205+
Миграций
66
Views
100+
Индексов
20+
Functions

Схемы базы данных

clowbot

Основная схема с бизнес-данными

Таблиц: 67
mart

Аналитические views и marts

Views: 66
public

PostgreSQL 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)

FromToTypeFK
userschats1:Nowner_id
chatsmessages1:Nchat_id
processesprocess_runs1:Nprocess_id
process_runsprocess_run_steps1:Nrun_id
process_run_stepsllm_calls1:Nstep_id
userstasks1:Nowner_id
taskstask_events1:Ntask_id
agent_profileagent_methods1:Nagent_code
usersreminders1:Nuser_id

Ядерные таблицы (Top 15)

ТаблицаОписаниеКлючевые поляRows
usersПользователи Telegramtelegram_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_policyRuntime политики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

Ключевые индексы

TableIndex NameColumns
messagesidx_messages_chat_createdchat_id, created_at DESC
process_runsidx_process_runs_statusstatus, created_at
llm_callsidx_llm_calls_createdcreated_at DESC
tasksidx_tasks_owner_statusowner_id, status
remindersidx_reminders_duedue_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_gate

Quality 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