2022-11-13 19:17:07 +01:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
2022-11-20 00:19:41 +01:00
|
|
|
"blackforestbytes.com/simplecloudnotifier/db/schema"
|
2022-11-13 22:31:28 +01:00
|
|
|
"context"
|
2022-11-13 19:17:07 +01:00
|
|
|
"database/sql"
|
2022-11-13 22:31:28 +01:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2022-11-13 19:17:07 +01:00
|
|
|
_ "github.com/mattn/go-sqlite3"
|
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 *sql.DB
|
|
|
|
}
|
|
|
|
|
2022-11-23 20:21:49 +01:00
|
|
|
func NewDatabase(filename string) (*Database, error) {
|
|
|
|
db, err := sql.Open("sqlite3", filename)
|
2022-11-13 22:31:28 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-11-18 21:25:40 +01:00
|
|
|
return &Database{db}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
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 {
|
2022-11-13 22:31:28 +01:00
|
|
|
|
2022-11-20 00:19:41 +01:00
|
|
|
_, err = db.db.ExecContext(ctx, schema.Schema3)
|
2022-11-13 22:31:28 +01:00
|
|
|
if err != nil {
|
2022-11-18 21:25:40 +01:00
|
|
|
return err
|
2022-11-13 22:31:28 +01:00
|
|
|
}
|
|
|
|
|
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-13 22:31:28 +01:00
|
|
|
|
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
|
2022-11-13 22:31:28 +01:00
|
|
|
} else {
|
2022-11-20 00:19:41 +01:00
|
|
|
return errors.New(fmt.Sprintf("Unknown DB schema: %d", currschema))
|
2022-11-13 22:31:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2022-11-18 21:25:40 +01:00
|
|
|
func (db *Database) Ping() error {
|
|
|
|
return db.db.Ping()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *Database) BeginTx(ctx context.Context) (*sql.Tx, error) {
|
2022-11-20 03:06:08 +01:00
|
|
|
return db.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelDefault})
|
2022-11-18 21:25:40 +01:00
|
|
|
}
|