From 3794df20d464b5366f5ed86c40b8d5e319607ea7 Mon Sep 17 00:00:00 2001 From: Artyom Date: Wed, 28 Oct 2026 20:25:35 +0300 Subject: [PATCH] Add the attachments schema as an additive migration Migration 0003 creates attachments with a pending or ready status, a server-assigned object key in byte order collation and a partial index for pending rows, and message_attachments that keeps the order of the attachments of a message. Foreign keys hold the links between zones: an attachment belongs to a member of its chat, and a message may only reference an attachment of its own chat, with RESTRICT so a referenced attachment can never be deleted. The text check is relaxed to at most 4000 code points because an empty text is legal next to an attachment; an empty message without attachments is still refused by the domain. The migration test covers the new version, a rerun without changes and both foreign keys. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../add-lab4-image-attachments/tasks.md | 4 +- src/messenger/migrations/0003_attachments.sql | 37 +++++++++ student-tests/api/test_migrations.py | 78 ++++++++++++++++++- 3 files changed, 115 insertions(+), 4 deletions(-) create mode 100644 src/messenger/migrations/0003_attachments.sql diff --git a/openspec/changes/add-lab4-image-attachments/tasks.md b/openspec/changes/add-lab4-image-attachments/tasks.md index 88d0d938..0d1a054a 100644 --- a/openspec/changes/add-lab4-image-attachments/tasks.md +++ b/openspec/changes/add-lab4-image-attachments/tasks.md @@ -1,7 +1,7 @@ ## 1. Схема -- [ ] 1.1 Миграция `0003_attachments.sql`: `attachments` (статус `pending`/`ready`, `object_key COLLATE "C"`, `UNIQUE (id, chat_id)`, FK на `chat_members`, частичный индекс `pending`), `message_attachments` (FK на `attachments (id, chat_id)` `ON DELETE RESTRICT`, индекс по `attachment_id`), ослабленный `messages_text_check` -- [ ] 1.2 Проверка группы: тест миграций — версия `0003`, повтор без изменений, вложение не участника и ссылка на вложение другого чата отклоняются внешними ключами, пустой текст принимается схемой +- [x] 1.1 Миграция `0003_attachments.sql`: `attachments` (статус `pending`/`ready`, `object_key COLLATE "C"`, `UNIQUE (id, chat_id)`, FK на `chat_members`, частичный индекс `pending`), `message_attachments` (FK на `attachments (id, chat_id)` `ON DELETE RESTRICT`, индекс по `attachment_id`), ослабленный `messages_text_check` +- [x] 1.2 Проверка группы: тест миграций — версия `0003`, повтор без изменений, вложение не участника и ссылка на вложение другого чата отклоняются внешними ключами, пустой текст принимается схемой ## 2. Зона `attachments`: домен и приложение diff --git a/src/messenger/migrations/0003_attachments.sql b/src/messenger/migrations/0003_attachments.sql new file mode 100644 index 00000000..91259da9 --- /dev/null +++ b/src/messenger/migrations/0003_attachments.sql @@ -0,0 +1,37 @@ +ALTER TABLE messages + DROP CONSTRAINT messages_text_check, + ADD CONSTRAINT messages_text_check CHECK (char_length(text) <= 4000); + +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + owner_id uuid NOT NULL, + filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255), + content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), + size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), + sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), + width integer NOT NULL CHECK (width > 0), + height integer NOT NULL CHECK (height > 0), + object_key text COLLATE "C" NOT NULL CONSTRAINT attachments_object_key_key UNIQUE, + status text NOT NULL CHECK (status IN ('pending', 'ready')), + created_at timestamptz NOT NULL, + updated_at timestamptz NOT NULL, + CONSTRAINT attachments_chat_key UNIQUE (id, chat_id), + CONSTRAINT attachments_owner_fkey FOREIGN KEY (chat_id, owner_id) + REFERENCES chat_members (chat_id, user_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, + position smallint NOT NULL CHECK (position BETWEEN 0 AND 9), + chat_id uuid NOT NULL, + attachment_id uuid NOT NULL, + PRIMARY KEY (message_id, position), + UNIQUE (message_id, attachment_id), + CONSTRAINT message_attachments_attachment_fkey FOREIGN KEY (attachment_id, chat_id) + REFERENCES attachments (id, chat_id) ON DELETE RESTRICT +); + +CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id); diff --git a/student-tests/api/test_migrations.py b/student-tests/api/test_migrations.py index 12d9a351..9fa6e7ef 100644 --- a/student-tests/api/test_migrations.py +++ b/student-tests/api/test_migrations.py @@ -1,3 +1,5 @@ +from uuid import uuid4 + import asyncpg import pytest @@ -7,7 +9,8 @@ from messenger.migrate import MigrationChangedError, migrate, migrations COUNTS = """ SELECT (SELECT count(*) FROM users), (SELECT count(*) FROM sessions), (SELECT count(*) FROM chats), (SELECT count(*) FROM chat_members), - (SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys) + (SELECT count(*) FROM messages), (SELECT count(*) FROM idempotency_keys), + (SELECT count(*) FROM attachments), (SELECT count(*) FROM message_attachments) """ @@ -22,7 +25,7 @@ async def counts() -> list[int]: async def test_migrations_are_ordered_and_versioned() -> None: versions = [version for version, _ in migrations()] assert versions == sorted(versions) - assert versions[:2] == ["0001_init", "0002_idempotency_keys"] + assert versions[:3] == ["0001_init", "0002_idempotency_keys", "0003_attachments"] applied = await scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations") assert applied == versions @@ -75,3 +78,74 @@ async def test_key_needs_a_member_and_a_message() -> None: ) finally: await connection.close() + + +async def test_attachment_owner_must_be_member() -> None: + connection = await asyncpg.connect(DATABASE["url"]) + try: + with pytest.raises(asyncpg.ForeignKeyViolationError, match="attachments_owner_fkey"): + await connection.execute( + "INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, " + "size_bytes, sha256, width, height, object_key, status, created_at, updated_at) " + "VALUES (gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), 'a.png', " + "'image/png', 1, repeat('0', 64), 1, 1, 'attachments/x', 'pending', now(), now())" + ) + finally: + await connection.close() + + +async def test_message_links_only_attachments_of_its_chat() -> None: + user, chat_a, chat_b, attachment, message = (uuid4() for _ in range(5)) + seed = [ + ( + "INSERT INTO users (id, username, display_name, password_hash, created_at) " + "VALUES ($1, $2, 'A', '$argon2id$x', now())", + user, + f"u_{user.hex[:12]}", + ), + ("INSERT INTO chats (id, title, created_at) VALUES ($1, 'A', now())", chat_a), + ("INSERT INTO chats (id, title, created_at) VALUES ($1, 'B', now())", chat_b), + ( + "INSERT INTO chat_members (chat_id, user_id, position, chat_created_at) " + "VALUES ($1, $3, 1, now()), ($2, $3, 1, now())", + chat_a, + chat_b, + user, + ), + ( + "INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, " + "sha256, width, height, object_key, status, created_at, updated_at) VALUES ($1, $2, " + "$3, 'a.png', 'image/png', 1, repeat('0', 64), 1, 1, $4, 'ready', now(), now())", + attachment, + chat_a, + user, + f"attachments/{attachment}", + ), + ( + "INSERT INTO messages (id, chat_id, sender_id, text, created_at) " + "VALUES ($1, $2, $3, '', now())", + message, + chat_b, + user, + ), + ] + connection = await asyncpg.connect(DATABASE["url"]) + transaction = connection.transaction() + await transaction.start() + try: + for sql, *arguments in seed: + await connection.execute(sql, *arguments) + assert await connection.fetchval("SELECT text FROM messages WHERE id = $1", message) == "" + with pytest.raises( + asyncpg.ForeignKeyViolationError, match="message_attachments_attachment_fkey" + ): + await connection.execute( + "INSERT INTO message_attachments (message_id, position, chat_id, attachment_id) " + "VALUES ($1, 0, $2, $3)", + message, + chat_b, + attachment, + ) + finally: + await transaction.rollback() + await connection.close()