2023-09-18 23:57:18 +00:00
|
|
|
package database
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
_ "embed"
|
2023-09-19 23:29:55 +00:00
|
|
|
"fmt"
|
2023-09-18 23:57:18 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2023-10-24 00:18:16 +00:00
|
|
|
_ "modernc.org/sqlite"
|
2023-10-05 23:56:19 +00:00
|
|
|
"path"
|
2023-09-18 23:57:18 +00:00
|
|
|
"reichard.io/bbank/config"
|
|
|
|
)
|
|
|
|
|
|
|
|
type DBManager struct {
|
|
|
|
DB *sql.DB
|
|
|
|
Ctx context.Context
|
|
|
|
Queries *Queries
|
|
|
|
}
|
|
|
|
|
|
|
|
//go:embed schema.sql
|
|
|
|
var ddl string
|
|
|
|
|
2023-10-03 20:47:38 +00:00
|
|
|
//go:embed update_temp_tables.sql
|
|
|
|
var tsql string
|
|
|
|
|
2023-09-18 23:57:18 +00:00
|
|
|
func NewMgr(c *config.Config) *DBManager {
|
|
|
|
// Create Manager
|
|
|
|
dbm := &DBManager{
|
|
|
|
Ctx: context.Background(),
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create Database
|
2023-10-24 00:18:16 +00:00
|
|
|
if c.DBType == "sqlite" || c.DBType == "memory" {
|
|
|
|
var dbLocation string = ":memory:"
|
|
|
|
if c.DBType == "sqlite" {
|
|
|
|
dbLocation = path.Join(c.ConfigPath, fmt.Sprintf("%s.db", c.DBName))
|
|
|
|
}
|
|
|
|
|
2023-09-18 23:57:18 +00:00
|
|
|
var err error
|
2023-10-05 23:56:19 +00:00
|
|
|
dbm.DB, err = sql.Open("sqlite", dbLocation)
|
2023-09-18 23:57:18 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2023-10-05 23:56:19 +00:00
|
|
|
|
|
|
|
// Single Open Connection
|
|
|
|
dbm.DB.SetMaxOpenConns(1)
|
|
|
|
if _, err := dbm.DB.Exec(ddl, nil); err != nil {
|
|
|
|
log.Info("Exec Error:", err)
|
|
|
|
}
|
2023-09-18 23:57:18 +00:00
|
|
|
} else {
|
|
|
|
log.Fatal("Unsupported Database")
|
|
|
|
}
|
|
|
|
|
|
|
|
dbm.Queries = New(dbm.DB)
|
|
|
|
|
|
|
|
return dbm
|
|
|
|
}
|
2023-09-19 23:29:55 +00:00
|
|
|
|
2023-11-03 23:38:31 +00:00
|
|
|
func (dbm *DBManager) Shutdown() error {
|
|
|
|
return dbm.DB.Close()
|
|
|
|
}
|
|
|
|
|
2023-10-03 20:47:38 +00:00
|
|
|
func (dbm *DBManager) CacheTempTables() error {
|
|
|
|
if _, err := dbm.DB.ExecContext(dbm.Ctx, tsql); err != nil {
|
2023-09-19 23:29:55 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|