bug fix for 다중 쿼리

This commit is contained in:
bluebamus committed 2025-12-30 00:01:20 +09:00
1 parent 5c99610e00
commit 8671a45d96
3 files changed
+1434 -445

No files matched your search

+38 -29
View File
@@ -99,17 +99,18 @@ async def generate_video(
) -> GenerateVideoResponse:
"""Creatomate API를 통해 영상을 생성합니다.
1. task_id로 Project, Lyric, Song, Image 병렬 조회
1. task_id로 Project, Lyric, Song, Image 순차 조회
2. Video 테이블에 초기 데이터 저장 (status: processing)
3. Creatomate API 호출 (orientation에 따른 템플릿 자동 선택)
4. creatomate_render_id 업데이트 후 응답 반환
Note: 이 함수는 Depends(get_session)을 사용하지 않고 명시적으로 세션을 관리합니다.
외부 API 호출 중 DB 커넥션이 유지되지 않도록 하여 커넥션 타임아웃 문제를 방지합니다.
DB 쿼리는 asyncio.gather()를 사용하여 병렬로 실행됩니다.
"""
import asyncio
중요: SQLAlchemy AsyncSession은 단일 세션에서 동시에 여러 쿼리를 실행하는 것을
지원하지 않습니다. asyncio.gather()로 병렬 쿼리를 실행하면 세션 상태 충돌이 발생합니다.
따라서 쿼리는 순차적으로 실행합니다.
"""
from app.database.session import AsyncSessionLocal
print(f"[generate_video] START - task_id: {task_id}, orientation: {orientation}")
@@ -130,33 +131,41 @@ async def generate_video(
try:
# 세션을 명시적으로 열고 DB 작업 후 바로 닫음
async with AsyncSessionLocal() as session:
# ===== 병렬 쿼리 실행: Project, Lyric, Song, Image 동시 조회 =====
project_query = select(Project).where(
Project.task_id == task_id
).order_by(Project.created_at.desc()).limit(1)
# ===== 순차 쿼리 실행: Project, Lyric, Song, Image =====
# Note: AsyncSession은 동일 세션에서 병렬 쿼리를 지원하지 않음
lyric_query = select(Lyric).where(
Lyric.task_id == task_id
).order_by(Lyric.created_at.desc()).limit(1)
song_query = select(Song).where(
Song.task_id == task_id
).order_by(Song.created_at.desc()).limit(1)
image_query = select(Image).where(
Image.task_id == task_id
).order_by(Image.img_order.asc())
# 4개 쿼리를 병렬로 실행
project_result, lyric_result, song_result, image_result = (
await asyncio.gather(
session.execute(project_query),
session.execute(lyric_query),
session.execute(song_query),
session.execute(image_query),
)
# Project 조회
project_result = await session.execute(
select(Project)
.where(Project.task_id == task_id)
.order_by(Project.created_at.desc())
.limit(1)
)
print(f"[generate_video] Parallel queries completed - task_id: {task_id}")
# Lyric 조회
lyric_result = await session.execute(
select(Lyric)
.where(Lyric.task_id == task_id)
.order_by(Lyric.created_at.desc())
.limit(1)
)
# Song 조회
song_result = await session.execute(
select(Song)
.where(Song.task_id == task_id)
.order_by(Song.created_at.desc())
.limit(1)
)
# Image 조회
image_result = await session.execute(
select(Image)
.where(Image.task_id == task_id)
.order_by(Image.img_order.asc())
)
print(f"[generate_video] Queries completed - task_id: {task_id}")
# ===== 결과 처리: Project =====
project = project_result.scalar_one_or_none()