🐛 fix(database): fix deleteMessagesBySession incorrectly deleting all messages (#10110)

This commit is contained in:
Arvin Xu
2025-11-08 23:40:02 +08:00
committed by GitHub
parent c48956e715
commit 1d7f67da56
2 changed files with 68 additions and 13 deletions
@@ -1922,6 +1922,63 @@ describe('MessageModel', () => {
expect(remainingMessages).toHaveLength(1);
expect(remainingMessages[0].id).toBe('2');
});
it('should delete only non-topic messages when topicId is null', async () => {
await serverDB.insert(sessions).values([{ id: 'session1', userId }]);
await serverDB.insert(topics).values([
{ id: 'topic1', sessionId: 'session1', userId },
{ id: 'topic2', sessionId: 'session1', userId },
]);
await serverDB.insert(messages).values([
{
id: '1',
userId,
sessionId: 'session1',
topicId: null,
role: 'user',
content: 'message without topic 1',
},
{
id: '2',
userId,
sessionId: 'session1',
topicId: null,
role: 'assistant',
content: 'message without topic 2',
},
{
id: '3',
userId,
sessionId: 'session1',
topicId: 'topic1',
role: 'user',
content: 'message in topic1',
},
{
id: '4',
userId,
sessionId: 'session1',
topicId: 'topic2',
role: 'assistant',
content: 'message in topic2',
},
]);
// Delete messages in session1 with null topicId
await messageModel.deleteMessagesBySession('session1', null);
const remainingMessages = await serverDB
.select()
.from(messages)
.where(eq(messages.userId, userId))
.orderBy(messages.id);
// Should only keep messages with topics
expect(remainingMessages).toHaveLength(2);
expect(remainingMessages[0].id).toBe('3');
expect(remainingMessages[1].id).toBe('4');
});
});
describe('genId', () => {
+11 -13
View File
@@ -768,19 +768,17 @@ export class MessageModel {
sessionId?: string | null,
topicId?: string | null,
groupId?: string | null,
) => {
const conditions = [eq(messages.userId, this.userId), this.matchSession(sessionId)];
// For deletion: only filter by topicId/groupId if explicitly provided
if (topicId !== undefined && topicId !== null) {
conditions.push(eq(messages.topicId, topicId));
}
if (groupId !== undefined && groupId !== null) {
conditions.push(eq(messages.groupId, groupId));
}
return this.db.delete(messages).where(and(...conditions));
};
) =>
this.db
.delete(messages)
.where(
and(
eq(messages.userId, this.userId),
this.matchSession(sessionId),
this.matchTopic(topicId),
this.matchGroup(groupId),
),
);
deleteAllMessages = async () => {
return this.db.delete(messages).where(eq(messages.userId, this.userId));