Use a RWMutex for DB

This commit is contained in:
Simon Ser 2020-03-04 20:15:38 +01:00
parent e25037f5a6
commit 660e4c035d
No known key found for this signature in database
GPG key ID: 0FDE7BE0E88F5E48

15
db.go
View file

@ -2,7 +2,6 @@ package jounce
import ( import (
"database/sql" "database/sql"
"errors"
"sync" "sync"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
@ -27,7 +26,7 @@ type Channel struct {
} }
type DB struct { type DB struct {
lock sync.Mutex lock sync.RWMutex
db *sql.DB db *sql.DB
} }
@ -46,8 +45,8 @@ func (db *DB) Close() error {
} }
func (db *DB) ListUsers() ([]User, error) { func (db *DB) ListUsers() ([]User, error) {
db.lock.Lock() db.lock.RLock()
defer db.lock.Unlock() defer db.lock.RUnlock()
rows, err := db.db.Query("SELECT username, password FROM User") rows, err := db.db.Query("SELECT username, password FROM User")
if err != nil { if err != nil {
@ -75,8 +74,8 @@ func (db *DB) ListUsers() ([]User, error) {
} }
func (db *DB) ListNetworks(username string) ([]Network, error) { func (db *DB) ListNetworks(username string) ([]Network, error) {
db.lock.Lock() db.lock.RLock()
defer db.lock.Unlock() defer db.lock.RUnlock()
rows, err := db.db.Query("SELECT id, addr, nick, username, realname FROM Network WHERE user = ?", username) rows, err := db.db.Query("SELECT id, addr, nick, username, realname FROM Network WHERE user = ?", username)
if err != nil { if err != nil {
@ -107,8 +106,8 @@ func (db *DB) ListNetworks(username string) ([]Network, error) {
} }
func (db *DB) ListChannels(networkID int64) ([]Channel, error) { func (db *DB) ListChannels(networkID int64) ([]Channel, error) {
db.lock.Lock() db.lock.RLock()
defer db.lock.Unlock() defer db.lock.RUnlock()
rows, err := db.db.Query("SELECT id, name FROM Channel WHERE network = ?", networkID) rows, err := db.db.Query("SELECT id, name FROM Channel WHERE network = ?", networkID)
if err != nil { if err != nil {