Skip to content

Commit

Permalink
Resolve a suspicious race condition when doing Unmarshal on the Query…
Browse files Browse the repository at this point in the history
… struct
  • Loading branch information
ktsivkov committed Mar 21, 2024
1 parent 1b3e58f commit b327816
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,32 @@ package caches

import (
"encoding/json"
"sync"

"gorm.io/gorm"
)

type Query[T any] struct {
Dest T
RowsAffected int64
mu sync.RWMutex
}

func (q *Query[T]) Marshal() ([]byte, error) {
q.mu.RUnlock()
defer q.mu.RUnlock()
return json.Marshal(q)
}

func (q *Query[T]) Unmarshal(bytes []byte) error {
q.mu.Lock()
defer q.mu.Unlock()
return json.Unmarshal(bytes, q)
}

func (q *Query[T]) replaceOn(db *gorm.DB) {
q.mu.Lock()
defer q.mu.Unlock()
SetPointedValue(db.Statement.Dest, q.Dest)
SetPointedValue(&db.Statement.RowsAffected, &q.RowsAffected)
}

0 comments on commit b327816

Please sign in to comment.