Files
mtusi2026lab5/db/migrations/00003_attachments.sql
T
2026-11-13 15:52:39 +03:00

39 lines
1.6 KiB
SQL

-- +goose Up
CREATE TYPE attachment_content_type AS ENUM ('image/png', 'image/jpeg');
CREATE TYPE attachment_status AS ENUM ('queued', 'processing', 'ready', 'failed');
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,
s3_key text NOT NULL UNIQUE,
filename text NOT NULL,
content_type attachment_content_type NOT NULL,
size_bytes int NOT NULL CHECK (size_bytes > 0 AND size_bytes <= 10485760),
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
status attachment_status NOT NULL DEFAULT 'queued',
error_code text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX idx_attachments_chat_id ON attachments (chat_id, created_at);
CREATE INDEX idx_attachments_owner_id ON attachments (owner_id);
CREATE INDEX idx_attachments_queued_created_at ON attachments (created_at) WHERE status = 'queued';
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 int NOT NULL CHECK (position >= 0 AND position < 10),
PRIMARY KEY (message_id, attachment_id),
UNIQUE (message_id, position)
);
CREATE INDEX idx_message_attachments_attachment_id ON message_attachments (attachment_id);
-- +goose Down
DROP TABLE message_attachments;
DROP TABLE attachments;
DROP TYPE attachment_status;
DROP TYPE attachment_content_type;