Files
mtusi2026lab7/internal/storage/postgres/migrations/00004_attachments.sql
T
Vladislav Kunetskiy 1b6e96ccc0
Application / Go invariants and static checks (pull_request) Canceled after 0s
Application / Lab7 verified TLS and retained features (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
2026-11-10 14:39:57 +03:00

56 lines
2.5 KiB
SQL

-- +goose Up
-- Attachment metadata lives in PostgreSQL; the original bytes live only in S3.
CREATE TABLE attachments (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
object_key text NOT NULL,
filename text NOT NULL,
content_type text NOT NULL,
size_bytes bigint NOT NULL,
sha256 text NOT NULL,
status text NOT NULL,
error_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT attachments_object_key_key UNIQUE (object_key),
CONSTRAINT attachments_status_check CHECK (status IN ('pending', 'ready', 'failed')),
CONSTRAINT attachments_content_type_check CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_filename_length CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_size_check CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha256_check CHECK (sha256 ~ '^[0-9a-f]{64}$'),
CONSTRAINT attachments_error_consistency CHECK (
(status = 'ready' AND error_code IS NULL) OR
(status = 'failed' AND error_code IS NOT NULL) OR
status = 'pending'
)
);
CREATE INDEX attachments_chat_id_created_at_id_idx ON attachments (chat_id, created_at, id);
CREATE INDEX attachments_status_created_at_idx ON attachments (status, created_at);
CREATE TABLE message_attachments (
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT,
position smallint NOT NULL,
PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position_check CHECK (position BETWEEN 0 AND 9),
CONSTRAINT message_attachments_position_key UNIQUE (message_id, position)
);
CREATE INDEX message_attachments_attachment_id_idx ON message_attachments (attachment_id);
-- Lab1-3 messages must stay valid. Attachment-only messages use text = '';
-- the "text OR attachment" rule is enforced by the service and ogen.
ALTER TABLE messages DROP CONSTRAINT messages_text_not_blank;
-- +goose Down
-- WARNING: fails if attachment-only messages already exist. Roll back such
-- rows or the constraint cannot be restored.
ALTER TABLE messages ADD CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> '');
DROP TABLE message_attachments;
DROP TABLE attachments;