59 lines
1.9 KiB
Python
59 lines
1.9 KiB
Python
"""Memoir repository — Book, Chapter, MemoirState data access."""
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy.orm import joinedload
|
|
|
|
from app.features.memoir.models import Book, Chapter, ChapterSection, MemoirState
|
|
|
|
|
|
async def get_current_book(user_id: str, db: AsyncSession) -> Book | None:
|
|
stmt = select(Book).where(Book.user_id == user_id).order_by(Book.updated_at.desc()).limit(1)
|
|
result = await db.execute(stmt)
|
|
return result.scalar_one_or_none()
|
|
|
|
|
|
async def get_chapters_with_sections(
|
|
user_id: str,
|
|
db: AsyncSession,
|
|
*,
|
|
active_only: bool = True,
|
|
is_new_only: bool | None = None,
|
|
) -> list[Chapter]:
|
|
stmt = (
|
|
select(Chapter)
|
|
.where(Chapter.user_id == user_id)
|
|
.options(
|
|
joinedload(Chapter.sections),
|
|
joinedload(Chapter.images),
|
|
joinedload(Chapter.sections).joinedload(ChapterSection.image_record),
|
|
)
|
|
.order_by(Chapter.order_index)
|
|
)
|
|
if active_only:
|
|
stmt = stmt.where(Chapter.is_active == True) # noqa: E712
|
|
if is_new_only is True:
|
|
stmt = stmt.where(Chapter.is_new == True) # noqa: E712
|
|
result = await db.execute(stmt)
|
|
return list(result.unique().scalars().all())
|
|
|
|
|
|
async def get_chapter_by_id(chapter_id: str, db: AsyncSession) -> Chapter | None:
|
|
stmt = (
|
|
select(Chapter)
|
|
.where(Chapter.id == chapter_id)
|
|
.options(
|
|
joinedload(Chapter.sections),
|
|
joinedload(Chapter.images),
|
|
joinedload(Chapter.sections).joinedload(ChapterSection.image_record),
|
|
)
|
|
)
|
|
result = await db.execute(stmt)
|
|
return result.unique().scalars().one_or_none()
|
|
|
|
|
|
async def get_memoir_state(user_id: str, db: AsyncSession) -> MemoirState | None:
|
|
stmt = select(MemoirState).where(MemoirState.user_id == user_id)
|
|
result = await db.execute(stmt)
|
|
return result.scalar_one_or_none()
|