Some checks failed
Linting and tests / Linting (push) Failing after 37s
119 lines
2.4 KiB
Go
119 lines
2.4 KiB
Go
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"io/fs"
|
|
"log/slog"
|
|
|
|
"bunker/client/internal/application"
|
|
"bunker/client/internal/services/core"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
// sqlite adapter.
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
var _ = core.Database(&database{})
|
|
|
|
type database struct {
|
|
mainWindow core.MainWindow
|
|
options core.Options
|
|
app *application.Application
|
|
db *sqlx.DB
|
|
logger *slog.Logger
|
|
migrations map[string]fs.FS
|
|
dbPath string
|
|
version int64
|
|
}
|
|
|
|
// Initialize initializes service.
|
|
func Initialize(app *application.Application) error {
|
|
db := &database{
|
|
app: app,
|
|
}
|
|
|
|
if err := app.RegisterService(db); err != nil {
|
|
return fmt.Errorf("%w: %w", core.ErrDatabase, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (d *database) Configure() error {
|
|
d.configureDBPath()
|
|
|
|
db, err := sqlx.Open("sqlite", d.dbPath)
|
|
if err != nil {
|
|
return fmt.Errorf("configure: open database: %w", err)
|
|
}
|
|
|
|
d.db = db
|
|
|
|
d.logger.Info("Database opened.", "path", d.dbPath)
|
|
|
|
if err := d.initializeSysInfoHandler(); err != nil {
|
|
return fmt.Errorf("configure: %w", err)
|
|
}
|
|
|
|
if err := d.initializeOptions(); err != nil {
|
|
return fmt.Errorf("configure: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (d *database) ConnectDependencies() error {
|
|
mainWindowRaw := d.app.Service(core.ServiceNameMainWindow)
|
|
if mainWindowRaw == nil {
|
|
return fmt.Errorf("connect dependencies: get main window: %w", application.ErrServiceNotFound)
|
|
}
|
|
|
|
mainWindow, valid := mainWindowRaw.(core.MainWindow)
|
|
if !valid {
|
|
return fmt.Errorf("connect dependencies: type assert main window: %w", core.ErrDatabaseIsInvalid)
|
|
}
|
|
|
|
d.mainWindow = mainWindow
|
|
|
|
optionsRaw := d.app.Service(core.ServiceNameOptions)
|
|
if optionsRaw == nil {
|
|
return fmt.Errorf("connect dependencies: get options: %w", application.ErrServiceNotFound)
|
|
}
|
|
|
|
options, valid := optionsRaw.(core.Options)
|
|
if !valid {
|
|
return fmt.Errorf("connect dependencies: type assert options: %w", core.ErrOptionsIsInvalid)
|
|
}
|
|
|
|
d.options = options
|
|
|
|
return nil
|
|
}
|
|
|
|
func (d *database) Initialize() error {
|
|
d.logger = d.app.NewLogger("service", core.ServiceNameDatabase)
|
|
|
|
d.logger.Info("Initializing...")
|
|
|
|
d.migrations = make(map[string]fs.FS, 0)
|
|
|
|
return nil
|
|
}
|
|
|
|
func (d *database) Name() string {
|
|
return core.ServiceNameDatabase
|
|
}
|
|
|
|
func (d *database) LaunchStartupTasks() error {
|
|
if err := d.applyMigrations(); err != nil {
|
|
return fmt.Errorf("launch startup tasks: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (d *database) Shutdown() error {
|
|
return nil
|
|
}
|