locking
parent
e85ce38e50
commit
81af991c58
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"io"
|
"io"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
_ "github.com/glebarez/sqlite"
|
_ "github.com/glebarez/sqlite"
|
||||||
|
|
@ -12,6 +13,7 @@ import (
|
||||||
type DB struct {
|
type DB struct {
|
||||||
scheme string
|
scheme string
|
||||||
conn string
|
conn string
|
||||||
|
rw *sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDB(ctx context.Context, scheme, conn string) (DB, error) {
|
func NewDB(ctx context.Context, scheme, conn string) (DB, error) {
|
||||||
|
|
@ -21,6 +23,7 @@ func NewDB(ctx context.Context, scheme, conn string) (DB, error) {
|
||||||
db := DB{
|
db := DB{
|
||||||
scheme: scheme,
|
scheme: scheme,
|
||||||
conn: conn,
|
conn: conn,
|
||||||
|
rw: &sync.RWMutex{},
|
||||||
}
|
}
|
||||||
|
|
||||||
sql, err := db.dial(ctx)
|
sql, err := db.dial(ctx)
|
||||||
|
|
@ -53,7 +56,19 @@ func NewDB(ctx context.Context, scheme, conn string) (DB, error) {
|
||||||
return db, err
|
return db, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (db DB) WithLock(cb func() error) error {
|
||||||
|
db.rw.Lock()
|
||||||
|
defer db.rw.Unlock()
|
||||||
|
return cb()
|
||||||
|
}
|
||||||
|
|
||||||
func (db DB) Exec(ctx context.Context, q string, args ...any) error {
|
func (db DB) Exec(ctx context.Context, q string, args ...any) error {
|
||||||
|
db.rw.RLock()
|
||||||
|
defer db.rw.RUnlock()
|
||||||
|
return db.exec(ctx, q, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db DB) exec(ctx context.Context, q string, args ...any) error {
|
||||||
c, err := db.dial(ctx)
|
c, err := db.dial(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
@ -65,6 +80,12 @@ 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 {
|
func (db DB) Query(ctx context.Context, cb func(*sql.Rows) error, q string, args ...any) error {
|
||||||
|
db.rw.RLock()
|
||||||
|
defer db.rw.RUnlock()
|
||||||
|
return db.query(ctx, cb, q, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db DB) query(ctx context.Context, cb func(*sql.Rows) error, q string, args ...any) error {
|
||||||
c, err := db.dial(ctx)
|
c, err := db.dial(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue