Files
mtusi2026lab6/backend/migrations/0003_attachments.sql
T

73 lines
2.5 KiB
SQL

-- +goose Up
-- +goose StatementBegin
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,
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes BIGINT NOT NULL,
sha256 BYTEA NOT NULL,
object_key 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_filename_len
CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_filename_no_slash
CHECK (filename !~ '[/\\]'),
CONSTRAINT attachments_filename_no_ctrl
CHECK (filename !~ '[[:cntrl:]]'),
CONSTRAINT attachments_content_type_chk
CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_size_chk
CHECK (size_bytes > 0 AND size_bytes <= 10485760),
CONSTRAINT attachments_sha256_len
CHECK (octet_length(sha256) = 32),
CONSTRAINT attachments_object_key_len
CHECK (char_length(object_key) BETWEEN 1 AND 1024),
CONSTRAINT attachments_status_chk
CHECK (status IN ('ready', 'pending', 'failed')),
CONSTRAINT attachments_error_code_consistency
CHECK (
(status IN ('ready', 'pending') AND error_code IS NULL) OR
(status = 'failed' AND error_code IS NOT NULL)
)
);
CREATE UNIQUE INDEX attachments_object_key_uniq
ON attachments (object_key);
CREATE INDEX attachments_chat_idx
ON attachments (chat_id, created_at, id);
CREATE INDEX attachments_pending_idx
ON attachments (created_at)
WHERE status = 'pending';
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,
CONSTRAINT message_attachments_pkey
PRIMARY KEY (message_id, attachment_id),
CONSTRAINT message_attachments_position_range
CHECK (position >= 0 AND position < 10),
CONSTRAINT message_attachments_position_uniq
UNIQUE (message_id, position)
);
CREATE INDEX message_attachments_attachment_idx
ON message_attachments (attachment_id);
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS message_attachments;
DROP TABLE IF EXISTS attachments;
-- +goose StatementEnd