if rw.Lock then no need for nested rw.RLock

main
Bel LaPointe 2024-12-15 00:45:27 -07:00
parent 78511f25f3
commit 58904c8619
2 changed files with 17 additions and 6 deletions

View File

@ -14,16 +14,19 @@ type DB struct {
scheme string
conn string
rw *sync.RWMutex
locked *bool
}
func NewDB(ctx context.Context, scheme, conn string) (DB, error) {
ctx, can := context.WithTimeout(ctx, time.Second*10)
defer can()
locked := false
db := DB{
scheme: scheme,
conn: conn,
rw: &sync.RWMutex{},
locked: &locked,
}
sql, err := db.dial(ctx)
@ -38,12 +41,18 @@ func NewDB(ctx context.Context, scheme, conn string) (DB, error) {
func (db DB) WithLock(cb func() error) error {
db.rw.Lock()
defer db.rw.Unlock()
*db.locked = true
defer func() {
*db.locked = false
}()
return cb()
}
func (db DB) Exec(ctx context.Context, q string, args ...any) error {
if !*db.locked {
db.rw.RLock()
defer db.rw.RUnlock()
}
return db.exec(ctx, q, args...)
}
@ -59,8 +68,10 @@ func (db DB) exec(ctx context.Context, q string, args ...any) error {
}
func (db DB) Query(ctx context.Context, cb func(*sql.Rows) error, q string, args ...any) error {
if !*db.locked {
db.rw.RLock()
defer db.rw.RUnlock()
}
return db.query(ctx, cb, q, args...)
}