CREATE TYPE thread_type AS ENUM ( 'expenses', 'movies', 'schedule', 'recipes', 'custom' ); CREATE TABLE threads ( id BIGSERIAL PRIMARY KEY, family_id BIGINT NOT NULL REFERENCES families (id) ON DELETE CASCADE, type thread_type NOT NULL, title TEXT NOT NULL, telegram_topic_id BIGINT NOT NULL, is_system BOOLEAN NOT NULL DEFAULT FALSE, created_by BIGINT NOT NULL REFERENCES users (id), created_at TIMESTAMP NOT NULL DEFAULT NOW(), UNIQUE (family_id, telegram_topic_id) ); CREATE UNIQUE INDEX idx_unique_system_threads ON threads (family_id, type) WHERE is_system = TRUE; CREATE INDEX idx_threads_family_id ON threads (family_id); CREATE INDEX idx_threads_family_type ON threads(family_id, type);