CREATE TABLE public.bot_api_updates ( id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, bot_user_id bigint NOT NULL, update_kind varchar(32) NOT NULL, peer_type varchar(16) NOT NULL, peer_id bigint NOT NULL, message_id integer NOT NULL, source_pts integer NOT NULL DEFAULT 0, date integer NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now(), CONSTRAINT bot_api_updates_kind_check CHECK ((update_kind)::text = ANY (ARRAY['message'::text, 'edited_message'::text])), CONSTRAINT bot_api_updates_peer_type_check CHECK ((peer_type)::text = ANY (ARRAY['user'::text, 'channel'::text])), CONSTRAINT bot_api_updates_peer_id_check CHECK (peer_id > 0), CONSTRAINT bot_api_updates_message_id_check CHECK (message_id > 0), CONSTRAINT bot_api_updates_source_pts_check CHECK (source_pts >= 0), CONSTRAINT bot_api_updates_source_unique UNIQUE (bot_user_id, update_kind, peer_type, peer_id, message_id, source_pts), CONSTRAINT bot_api_updates_bot_user_id_fkey FOREIGN KEY (bot_user_id) REFERENCES public.bots(bot_user_id) ON DELETE CASCADE ); CREATE INDEX bot_api_updates_bot_scan_idx ON public.bot_api_updates (bot_user_id, id); CREATE INDEX bot_api_updates_retention_idx ON public.bot_api_updates (date, id); CREATE TABLE public.bot_api_update_states ( bot_user_id bigint PRIMARY KEY, confirmed_update_id bigint NOT NULL DEFAULT 0, updated_at timestamptz NOT NULL DEFAULT now(), CONSTRAINT bot_api_update_states_confirmed_check CHECK (confirmed_update_id >= 0), CONSTRAINT bot_api_update_states_bot_user_id_fkey FOREIGN KEY (bot_user_id) REFERENCES public.bots(bot_user_id) ON DELETE CASCADE );