forked from mtusi2026/mtusi2026lab4
lab4
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
filename varchar(255) NOT NULL,
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 char(64) NOT NULL,
|
||||
object_key text NOT NULL UNIQUE,
|
||||
status text NOT NULL CHECK (status IN ('uploading', 'ready', 'missing')),
|
||||
lease_until timestamptz NOT NULL,
|
||||
error_code text,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE INDEX attachments_chat_idx ON attachments(chat_id, created_at, id);
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
|
||||
PRIMARY KEY (message_id, position),
|
||||
UNIQUE (message_id, attachment_id)
|
||||
);
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
|
||||
CREATE FUNCTION check_message_content() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF length(btrim(NEW.text))=0 AND NOT EXISTS (
|
||||
SELECT 1 FROM message_attachments WHERE message_id=NEW.id
|
||||
) THEN
|
||||
RAISE EXCEPTION 'message needs text or attachment' USING ERRCODE='23514';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
-- Проверяем в конце транзакции, когда связи вложений уже вставлены.
|
||||
CREATE CONSTRAINT TRIGGER message_content
|
||||
AFTER INSERT OR UPDATE ON messages DEFERRABLE INITIALLY DEFERRED
|
||||
FOR EACH ROW EXECUTE FUNCTION check_message_content();
|
||||
-- Прежние текстовые повторы остаются совместимыми с расширенной схемой Message.
|
||||
UPDATE message_requests SET response=response || '{"attachment_ids": []}'::jsonb
|
||||
WHERE NOT response ? 'attachment_ids';
|
||||
Reference in New Issue
Block a user