Bug: Profile updates do not persist successfully in database

未关闭
#304 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

@nevil06 已经在做这个了。

开始于 2026年9月19日。

  • #306 来自 @nevil06 —— 未关闭

评估

难度
3/5
预计耗时
1-2 天
新手友好度
68/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
冷清
技术栈
fastapi, python, sqlalchemy
领域
api, backend, database

调研方向

首先定位更新 UserProfile 模型的 FastAPI 后端服务方法,并检查其 SQLAlchemy Session 的使用方式。复现 profile 编辑流程,然后验证更新后的显示名称、简介和外部链接在刷新 profile 后仍然保留;完成内容包括对成功的更改执行 commit 和 refresh,并在出现 SQLAlchemy 错误时执行 rollback。

由索引模型根据 Issue 内容生成。

描述

Describe the bug

Users attempting to update their profiles (via the profile edit form) observe that their submitted changes do not persist. Specifically, fields such as display name, biography (bio), and external links (such as social profile links) fail to be saved to the database. When the user refreshes their profile page or re-fetches their profile details, the values revert to their previous states.

Root Cause Analysis

Upon reviewing the backend services, the FastAPI endpoints and corresponding service layers that process user profile modifications receive the validated schema fields from the request payload and apply them to the ORM model instances. However, the database transaction is never finalized.

Specifically, the SQLAlchemy database session (e.g., db: Session) is not committed after the attributes are updated on the model instance. Because there is no explicit call to db.commit(), the changes reside only in-memory during the lifetime of the request session and are automatically rolled back or discarded when the session is closed/teared down at the end of the request lifecycle.

Steps to Reproduce
  1. Log in to the application and navigate to the Edit Profile page.
  2. Modify the display name, bio, or add/edit external links.
  3. Click the Save Profile or Update button.
  4. Observe a successful response status (e.g., HTTP 200 OK returning the in-memory updated object).
  5. Navigate away or refresh the page.
  6. Observe that all modified fields have reverted to their original database state.
Proposed Solution & Backend Patch

To ensure that updates cleanly and safely persist to the profile database, we need to modify the backend FastAPI service method responsible for updating the user profile.

The service must:

  1. Fetch the existing database model instance.
  2. Dynamically apply the updated fields to the instance.
  3. Explicitly add/merge the instance to the SQLAlchemy session context.
  4. Perform a transaction commit (db.commit()).
  5. Refresh the instance (db.refresh()) to load any database-generated fields or triggers.
  6. Robustly handle any database integrity or connection exceptions by performing a session rollback (db.rollback()) and re-raising or logging the error.

Here is an outline of the proposed backend service patch:

from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from app.models import UserProfile  # Or appropriate SQLAlchemy model
from app.schemas import ProfileUpdateSchema
import logging

logger = logging.getLogger(__name__)

async def patch_user_profile(db: Session, user_id: str, profile_update: ProfileUpdateSchema) -> UserProfile:
    # 1. Retrieve the existing profile
    profile = db.query(UserProfile).filter(UserProfile.user_id == user_id).first()
    if not profile:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User profile not found."
        )

    # 2. Update model fields dynamically based on input schema
    update_data = profile_update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(profile, field, value)

    try:
        # 3. Add to session and commit transaction
        db.add(profile)
        db.commit()
        
        # 4. Refresh to load any database-computed fields
        db.refresh(profile)
        logger.info(f"Successfully committed profile updates for user {user_id} to database.")
        return profile
    except SQLAlchemyError as e:
        # 5. Rollback on failure to prevent stale/corrupt transaction state
        db.rollback()
        logger.error(f"Failed to persist profile updates for user {user_id}: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Database error occurred while saving profile updates."
        )

By wrapping the transaction with a standard try/except/rollback block, we guarantee database consistency while resolving the persistence failure.

主要语言
Python
星标
103
派生
143
PR 合并指标
30 天内没有已合并 PR

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 有 Pull Request 模板
  • 没有贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

AOSSIE-Org/Devr.AI 的其他 Issue

查看 AOSSIE-Org/Devr.AI 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。