Expand file tree Collapse file tree 2 files changed +17
-14
lines changed Original file line number Diff line number Diff line change @@ -149,18 +149,23 @@ export async function getLastMessageId(
149
149
150
150
/** Updates lastMsgId for a chat by selecting the highest messageId */
151
151
async function refreshLastMessageId ( chatId : number ) {
152
- let [ chat ] = await db . select ( ) . from ( chats ) . where ( eq ( chats . id , chatId ) )
153
- if ( ! chat ) {
154
- throw ModelError . ChatInvalid
155
- }
152
+ // Use a transaction with FOR UPDATE to lock the row while we're working with it
153
+ return await db . transaction ( async ( tx ) => {
154
+ let [ chat ] = await tx . select ( ) . from ( chats ) . where ( eq ( chats . id , chatId ) ) . for ( "update" )
155
+ if ( ! chat ) {
156
+ throw ModelError . ChatInvalid
157
+ }
158
+
159
+ let [ message ] = await tx
160
+ . select ( )
161
+ . from ( messages )
162
+ . where ( eq ( messages . chatId , chatId ) )
163
+ . orderBy ( desc ( messages . messageId ) )
164
+ . limit ( 1 )
156
165
157
- let [ message ] = await db
158
- . select ( )
159
- . from ( messages )
160
- . where ( eq ( messages . chatId , chatId ) )
161
- . orderBy ( desc ( messages . messageId ) )
162
- . limit ( 1 )
166
+ const newLastMsgId = message ?. messageId ?? null
167
+ await tx . update ( chats ) . set ( { lastMsgId : newLastMsgId } ) . where ( eq ( chats . id , chatId ) )
163
168
164
- const newLastMsgId = message ?. messageId ?? null
165
- await db . update ( chats ) . set ( { lastMsgId : newLastMsgId } ) . where ( eq ( chats . id , chatId ) )
169
+ return newLastMsgId
170
+ } )
166
171
}
Original file line number Diff line number Diff line change @@ -202,8 +202,6 @@ async function deleteMessages(messageIds: bigint[], chatId: number) {
202
202
)
203
203
. returning ( )
204
204
205
- console . log ( "deleted" , deleted )
206
-
207
205
if ( deleted . length === 0 ) {
208
206
log . trace ( "messages not found" , { messageIds, chatId } )
209
207
throw ModelError . MessageInvalid
0 commit comments