Skip to content

Commit

Permalink
Refactor chat_list to handle message_history table existence
Browse files Browse the repository at this point in the history
  • Loading branch information
baptiste-pasquier committed Mar 25, 2024
1 parent b8f2f63 commit e55138e
Showing 1 changed file with 23 additions and 18 deletions.
41 changes: 23 additions & 18 deletions backend/api_plugins/sessions/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,30 @@ async def chat_list(
user_email = current_user.email if current_user else "unauthenticated"
chats = []
with Database() as connection:
# Join session with message_history and get the first message
result = connection.execute(
"SELECT s.id, s.timestamp, mh.message FROM session s LEFT JOIN (SELECT"
" *, ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY timestamp ASC)"
" as rn FROM message_history) mh ON s.id = mh.session_id AND mh.rn = 1"
" WHERE s.user_id = ? ORDER BY s.timestamp DESC",
(user_email,),
)
for row in result:
# Extract the first message content if available
first_message_content = (
json.loads(row[2])["data"]["content"] if row[2] else ""
# Check if message_history table exists
message_history_exists = connection.execute(
"SELECT name FROM sqlite_schema WHERE type='table' AND name='message_history'"
).fetchone()
if message_history_exists:
# Join session with message_history and get the first message
result = connection.execute(
"SELECT s.id, s.timestamp, mh.message FROM session s LEFT JOIN (SELECT"
" *, ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY timestamp ASC)"
" as rn FROM message_history) mh ON s.id = mh.session_id AND mh.rn = 1"
" WHERE s.user_id = ? ORDER BY s.timestamp DESC",
(user_email,),
)
chat = {
"id": row[0],
"timestamp": row[1],
"first_message": first_message_content,
}
chats.append(chat)
for row in result:
# Extract the first message content if available
first_message_content = (
json.loads(row[2])["data"]["content"] if row[2] else ""
)
chat = {
"id": row[0],
"timestamp": row[1],
"first_message": first_message_content,
}
chats.append(chat)
return chats

@app.get("/session/{session_id}")
Expand Down

0 comments on commit e55138e

Please sign in to comment.