SimpleCloudNotifier/scnserver/db/database.go

100 lines
2.2 KiB
Go
Raw Normal View History

2022-11-13 19:17:07 +01:00
package db
import (
server "blackforestbytes.com/simplecloudnotifier"
"blackforestbytes.com/simplecloudnotifier/db/dbtools"
2022-11-20 00:19:41 +01:00
"blackforestbytes.com/simplecloudnotifier/db/schema"
"context"
2022-11-13 19:17:07 +01:00
"database/sql"
"errors"
"fmt"
"github.com/jmoiron/sqlx"
2022-11-13 19:17:07 +01:00
_ "github.com/mattn/go-sqlite3"
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"gogs.mikescher.com/BlackForestBytes/goext/sq"
2022-11-18 21:25:40 +01:00
"time"
2022-11-13 19:17:07 +01:00
)
2022-11-18 21:25:40 +01:00
type Database struct {
db sq.DB
2022-11-18 21:25:40 +01:00
}
func NewDatabase(conf server.Config) (*Database, error) {
url := fmt.Sprintf("file:%s?_journal=%s&_timeout=%d&_fk=%s", conf.DBFile, conf.DBJournal, conf.DBTimeout.Milliseconds(), langext.FormatBool(conf.DBCheckForeignKeys, "true", "false"))
xdb, err := sqlx.Open("sqlite3", url)
if err != nil {
return nil, err
}
if conf.DBSingleConn {
xdb.SetMaxOpenConns(1)
} else {
xdb.SetMaxOpenConns(5)
xdb.SetMaxIdleConns(5)
xdb.SetConnMaxLifetime(60 * time.Minute)
xdb.SetConnMaxIdleTime(60 * time.Minute)
}
qqdb := sq.NewDB(xdb)
scndb := &Database{qqdb}
qqdb.AddListener(dbtools.DBLogger{})
qqdb.AddListener(dbtools.NewDBPreprocessor(scndb.db))
return scndb, nil
2022-11-18 21:25:40 +01:00
}
func (db *Database) Migrate(ctx context.Context) error {
ctx, cancel := context.WithTimeout(context.Background(), 24*time.Second)
defer cancel()
2022-11-20 00:19:41 +01:00
currschema, err := db.ReadSchema(ctx)
if currschema == 0 {
_, err = db.db.Exec(ctx, schema.Schema3, sq.PP{})
if err != nil {
2022-11-18 21:25:40 +01:00
return err
}
2022-11-24 12:53:27 +01:00
err = db.WriteMetaInt(ctx, "schema", 3)
if err != nil {
return err
}
2022-11-18 21:25:40 +01:00
return nil
2022-11-20 00:19:41 +01:00
} else if currschema == 1 {
2022-11-18 21:25:40 +01:00
return errors.New("cannot autom. upgrade schema 1")
2022-11-20 00:19:41 +01:00
} else if currschema == 2 {
2022-11-18 21:25:40 +01:00
return errors.New("cannot autom. upgrade schema 2") //TODO
2022-11-20 00:19:41 +01:00
} else if currschema == 3 {
2022-11-18 21:25:40 +01:00
return nil // current
} else {
2022-11-20 00:19:41 +01:00
return errors.New(fmt.Sprintf("Unknown DB schema: %d", currschema))
}
}
func (db *Database) Ping(ctx context.Context) error {
return db.db.Ping(ctx)
2022-11-18 21:25:40 +01:00
}
func (db *Database) BeginTx(ctx context.Context) (sq.Tx, error) {
return db.db.BeginTransaction(ctx, sql.LevelDefault)
2022-11-18 21:25:40 +01:00
}
2022-12-22 10:21:10 +01:00
func (db *Database) Stop(ctx context.Context) error {
_, err := db.db.Exec(ctx, "PRAGMA wal_checkpoint;", sq.PP{})
if err != nil {
return err
}
err = db.db.Exit()
if err != nil {
return err
}
return nil
}