fix: allow API to access conversations created before upgrade to 1.10.0 (#28462)

Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com>
This commit is contained in:
张哲芳 2025-11-21 10:34:55 +08:00 committed by GitHub
parent cad2991946
commit c2043d0f6d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 24 additions and 2 deletions

View File

@ -1,11 +1,15 @@
import logging
from collections.abc import Mapping
from sqlalchemy import case
from sqlalchemy.orm import Session
from core.app.entities.app_invoke_entities import InvokeFrom
from extensions.ext_database import db
from models.model import App, DefaultEndUserSessionID, EndUser
logger = logging.getLogger(__name__)
class EndUserService:
"""
@ -32,18 +36,36 @@ class EndUserService:
user_id = DefaultEndUserSessionID.DEFAULT_SESSION_ID
with Session(db.engine, expire_on_commit=False) as session:
# Query with ORDER BY to prioritize exact type matches while maintaining backward compatibility
# This single query approach is more efficient than separate queries
end_user = (
session.query(EndUser)
.where(
EndUser.tenant_id == tenant_id,
EndUser.app_id == app_id,
EndUser.session_id == user_id,
EndUser.type == type,
)
.order_by(
# Prioritize records with matching type (0 = match, 1 = no match)
case((EndUser.type == type, 0), else_=1)
)
.first()
)
if end_user is None:
if end_user:
# If found a legacy end user with different type, update it for future consistency
if end_user.type != type:
logger.info(
"Upgrading legacy EndUser %s from type=%s to %s for session_id=%s",
end_user.id,
end_user.type,
type,
user_id,
)
end_user.type = type
session.commit()
else:
# Create new end user if none exists
end_user = EndUser(
tenant_id=tenant_id,
app_id=app_id,