-- Ядро Buryan Hub: сущности, связи, события. create table if not exists entities ( id bigserial primary key, kind text not null, -- фильм, сериал, книга, фото, документ, закладка, устройство key text not null, -- tmdb:693134, calibre:88 title text not null, status text, -- последнее известное состояние external_ids jsonb not null default '{}'::jsonb, search_text text not null default '', updated_at timestamptz not null default now(), unique (kind, key) ); create index if not exists idx_entities_search on entities using gin (to_tsvector('simple', search_text)); create index if not exists idx_entities_kind on entities (kind); create table if not exists entity_links ( id bigserial primary key, from_id bigint not null references entities(id) on delete cascade, to_id bigint not null references entities(id) on delete cascade, relation text not null default 'related', created_at timestamptz not null default now(), unique (from_id, to_id, relation) ); create index if not exists idx_links_from on entity_links (from_id); create index if not exists idx_links_to on entity_links (to_id); create table if not exists events ( id bigserial primary key, at timestamptz not null default now(), source text not null, -- sonarr, radarr, seerr, jellyfin, immich, alertmanager type text not null, -- media.imported, service.down entity jsonb not null default '{}'::jsonb, payload jsonb not null default '{}'::jsonb, actor text not null default 'system', entity_id bigint references entities(id) on delete set null ); create index if not exists idx_events_at on events (at desc); create index if not exists idx_events_source on events (source); create table if not exists sync_state ( key text primary key, value jsonb not null default '{}'::jsonb, updated_at timestamptz not null default now() );