Files
mtusi2026lab5/migrations/003_attachments.sql
T
dawudukandCursor 9046d5206d Перенести рабочую базу lab4 в skeleton лабораторной 5.
Исходники, миграции, Dockerfile и стенд lab4 нужны как основа асинхронной обработки вложений.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-09 00:48:22 +03:00

51 lines
2.2 KiB
SQL

-- Attachment metadata stays in Postgres. Bytes stay in the private bucket.
-- A blob_writes row is inserted before the S3 PUT and marked committed in the
-- same transaction as the attachment row. If that transaction rolls back, the
-- API deletes the object. Rows still uncommitted after ORPHAN_GRACE_SECONDS
-- are removed by the sweeper, so a crash between PUT and COMMIT cannot leave
-- a permanent untracked object. Fresh in-flight uploads are inside the grace
-- window and are not deleted.
ALTER TABLE messages DROP CONSTRAINT messages_text_len;
ALTER TABLE messages
ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 0 AND 4000);
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),
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes INTEGER NOT NULL,
sha256 TEXT NOT NULL,
object_key TEXT NOT NULL UNIQUE,
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_size CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachments_type CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_status CHECK (status = 'ready'),
CONSTRAINT attachments_ready_error CHECK (status <> 'ready' OR error_code IS NULL)
);
CREATE INDEX attachments_chat_idx ON attachments (chat_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 INTEGER NOT NULL CHECK (position >= 0 AND position < 10),
PRIMARY KEY (message_id, attachment_id),
UNIQUE (message_id, position)
);
CREATE TABLE blob_writes (
object_key TEXT PRIMARY KEY,
committed BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX blob_writes_pending_idx ON blob_writes (created_at) WHERE NOT committed;