4.1 KiB
Implementation Report — DOC-B1-document-artifacts
Status
DONE
Изменения
| Файл | Что |
|---|---|
app/models/document_artifact.py |
модель DocumentArtifact |
app/config.py |
DOCUMENT_STORAGE_ROOT / document_storage_root() |
app/database/migrations.py |
миграция 20260928_document_artifacts |
app/main.py |
регистрация модели |
tests/test_doc_b1_document_artifacts.py |
13 тестов |
Модель
app/models/document_artifact.py → таблица document_artifacts.
Поля: id, project_id (FK→projects), document_type, document_id, format, storage_key, template_type, template_version, content_hash VARCHAR(64), input_hash VARCHAR(64), is_current BOOLEAN default true, generated_at, created_at, updated_at.
Связь с KS-2/KS-3 полиморфная (document_type + document_id), FK на ks2/ks3 отсутствует. project_id — обычный FK.
Migration
DOCUMENT_ARTIFACTS_MIGRATION = "20260928_document_artifacts" в app/database/migrations.py (существующий механизм проекта):
CREATE TABLE document_artifacts(полный набор колонок);- индексы:
ix_document_artifacts_id,ix_document_artifacts_project_id,ix_document_artifacts_type_doc,ix_document_artifacts_current; - partial unique index
uq_document_artifact_current; - downgrade: drop таблицы + индексов + версии в
schema_migrations.
Индексы
(document_type, document_id)(project_id)(document_type, document_id, is_current)
Partial unique index
Реализован, т.к. SQLite поддерживает:
CREATE UNIQUE INDEX uq_document_artifact_current
ON document_artifacts (document_type, document_id, format)
WHERE is_current = 1
В SQLAlchemy — Index(..., unique=True, sqlite_where=text("is_current = 1")).
Исторические записи (is_current = 0) могут повторяться свободно.
Storage root config
app/config.py:
- env
DOCUMENT_STORAGE_ROOT(override); - default =
<app>/../storage, anchored черезPath(__file__).resolve(), не зависит от cwd; - не создаёт каталоги — только возвращает
Path.
Тесты
tests/test_doc_b1_document_artifacts.py (13):
- создание
DocumentArtifact; - обязательные поля (NOT NULL);
is_current=Trueпо умолчанию;- FK на Project;
- несколько historical artifacts допускаются;
- два current одного
(type, id, format)→ IntegrityError; - current для разных format разрешены;
- migration upgrade создаёт таблицу + индексы + версию;
- downgrade удаляет таблицу;
- существующие данные не повреждены;
- default storage root не зависит от cwd;
- custom
DOCUMENT_STORAGE_ROOTиз env; - config не создаёт каталог при импорте/вызове.
Результат pytest -q:
335 passed, 284 warnings in 26.20s
(322 существующих + 13 новых.)
Результат git diff --check:
(без ошибок)
Запуск приложения: app.ok Work Volume Tracker — модель зарегистрирована, миграция проходит.
Deviations
None.
Follow-up для DOC-B2
- Реализовать
document_artifact_service: persist / resolve / invalidate / hash (content_hash, input_hash). - Создание каталогов
storage/projects/<project_id>/documents/...при записи artifact. - Canonical DTO hash (Decimal→str, date→ISO, sort_keys).
- Правило «не более одного current» дополнительно обеспечить в сервисе (partial index — защитный уровень).
- Не добавлять
document_artifactsвdatabase_reset.DELETE_ORDERдо DOC-B8 (безопасное удаление файлов).