Files
orbits/internal/server/database/database.go
T

65 lines
1.5 KiB
Go

package database
import (
"orbits-server/internal/server/bootstrap"
"orbits-server/internal/shared/utility"
"path/filepath"
"time"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
//var watchdogStop = make(chan struct{})
func KickoffDatabase(workDir string) (*gorm.DB, error) {
dbLoc := filepath.Join(workDir, "station.db")
db, err := gorm.Open(sqlite.Open(dbLoc), &gorm.Config{
Logger: logger.Discard, // disable gorm logging since its not slog (yet)
TranslateError: true,
})
if err != nil {
return nil, err
}
// try to use GORM automigrate if the schema changes
if err := db.AutoMigrate(
&Command{}, // app state and command status
&File{}, // files database for keeping track
&Tenant{}, // table for tenants and its data
&Group{}, // group table for privileges
&Device{}, // devices table
); err != nil {
return nil, err
}
// create the first row if it does not exist yet
if err := db.FirstOrCreate(&Command{}, Command{
ID: 0,
State: "idle",
MediaType: utility.Unspecified,
}).Error; err != nil {
return nil, err
}
return db, nil
}
func KickoffDatabaseWatchdog(env bootstrap.Environment, db *gorm.DB) {
timeInterval := time.Second * time.Duration(env.WatchdogInterval)
ticker := time.NewTicker(timeInterval)
go func() {
defer ticker.Stop()
// run the watchdog function once to see if all is well.
watchdog(env, db)
// then defer to a decoupled/disowned golang goroutine
for range ticker.C {
watchdog(env, db)
}
}()
}