Fix: Performance issues and sqlite locking (#74)

* fix: performance issues and sqlite locking

* fix: dashboard release stats was reversed

* refactor: open and migrate db

* chore: cleanup
This commit is contained in:
Ludvig Lundgren 2022-01-11 19:35:27 +01:00 committed by GitHub
parent d8c37dde2f
commit f466657ed4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 362 additions and 658 deletions

View file

@ -0,0 +1,81 @@
package database
import (
"context"
"database/sql"
"fmt"
"sync"
_ "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog/log"
)
type SqliteDB struct {
lock sync.RWMutex
handler *sql.DB
ctx context.Context
cancel func()
DSN string
}
func NewSqliteDB(source string) *SqliteDB {
db := &SqliteDB{
DSN: dataSourceName(source, "autobrr.db"),
}
db.ctx, db.cancel = context.WithCancel(context.Background())
return db
}
func (db *SqliteDB) Open() error {
if db.DSN == "" {
return fmt.Errorf("DSN required")
}
var err error
// open database connection
if db.handler, err = sql.Open("sqlite3", db.DSN); err != nil {
log.Fatal().Err(err).Msg("could not open db connection")
return err
}
// Set busy timeout
if _, err = db.handler.Exec(`PRAGMA busy_timeout = 5000;`); err != nil {
return fmt.Errorf("busy timeout pragma")
}
// Enable WAL. SQLite performs better with the WAL because it allows
// multiple readers to operate while data is being written.
if _, err = db.handler.Exec(`PRAGMA journal_mode = wal;`); err != nil {
return fmt.Errorf("enable wal: %w", err)
}
// Enable foreign key checks. For historical reasons, SQLite does not check
// foreign key constraints by default. There's some overhead on inserts to
// verify foreign key integrity, but it's definitely worth it.
if _, err = db.handler.Exec(`PRAGMA foreign_keys = ON;`); err != nil {
return fmt.Errorf("foreign keys pragma: %w", err)
}
// migrate db
if err = db.migrate(); err != nil {
log.Fatal().Err(err).Msg("could not migrate db")
return err
}
return nil
}
func (db *SqliteDB) Close() error {
// cancel background context
db.cancel()
// close database
if db.handler != nil {
return db.handler.Close()
}
return nil
}