CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
email text NOT NULL UNIQUE,
password_hash text NOT NULL,
last_model_id text NOT NULL DEFAULT 'chatgpt'
CHECK (last_model_id IN ('chatgpt', 'deepseek', 'qwen')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE conversations (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title text NOT NULL DEFAULT 'Новый чат',
model_id text NOT NULL DEFAULT 'chatgpt'
CHECK (model_id IN ('chatgpt', 'deepseek', 'qwen')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX conversations_user_updated_at_idx
ON conversations (user_id, updated_at DESC);
CREATE TABLE chat_messages (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
conversation_id uuid NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
role text NOT NULL CHECK (role IN ('user', 'assistant')),
content text NOT NULL DEFAULT '',
status text NOT NULL DEFAULT 'complete'
CHECK (status IN ('streaming', 'complete', 'error', 'stopped')),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX chat_messages_conversation_created_at_idx
ON chat_messages (conversation_id, created_at ASC);