PKGBUILD/cmd/db/db.go

107 lines
2.4 KiB
Go

package db
import (
"context"
"fmt"
"net/url"
"github.com/Masterminds/semver"
"github.com/go-flucky/flucky/cmd/internal"
"github.com/go-flucky/flucky/pkg/config"
"github.com/go-flucky/flucky/pkg/storage/db"
"github.com/go-flucky/flucky/pkg/types"
"github.com/spf13/cobra"
)
var (
semanticVersion *semver.Version
)
// InitCmd initialize all convert subcommands
func InitCmd(cmd *cobra.Command, semver *semver.Version) error {
semanticVersion = semver
databaseCmd := &cobra.Command{
Use: "db",
Short: "Interagte with the database configured as storage endpoint",
}
updateDatabaseCmd := &cobra.Command{
Use: "init",
Short: "Initialize the database scheme for the version of the flucky binary",
Args: cobra.NoArgs,
Example: "flucky db update",
RunE: initializeDatabase,
}
databaseCmd.AddCommand(updateDatabaseCmd)
cmd.AddCommand(databaseCmd)
return nil
}
func initializeDatabase(cmd *cobra.Command, args []string) error {
configFile, err := cmd.Flags().GetString("config")
if err != nil {
return fmt.Errorf("No config file defined")
}
cnf, err := config.Read(configFile)
if err != nil {
return err
}
storageEndpointURL, err := url.Parse(cnf.StorageEndpoint)
if err != nil {
return fmt.Errorf("Failed to parse storage endpoint: %v", err)
}
logLevel, err := cmd.Flags().GetString("loglevel")
if err != nil {
return fmt.Errorf("No loglevel defined: %v", err)
}
flogger := internal.InitializeLogger(logLevel)
database, err := db.New(storageEndpointURL)
if err != nil {
return err
}
defer database.Close()
ctx := context.Background()
flogger.Debug("Initialize database scheme")
err = database.Schema(ctx, semanticVersion)
if err != nil {
return err
}
_, err = database.SelectDeviceByID(ctx, cnf.Device.ID)
if err != nil {
flogger.Debug("Add device into database")
devices := []*types.Device{cnf.Device}
if err := database.InsertDevices(ctx, devices); err != nil {
return err
}
} else {
flogger.Debug("Device already availabe in the database")
}
for _, sensor := range cnf.Sensors {
_, err = database.SelectSensorByID(ctx, sensor.ID)
if err != nil {
flogger.Debug("Add sensor %v into the database", sensor.FullName())
sensors := []*types.Sensor{sensor}
if err := database.InsertSensors(ctx, sensors); err != nil {
return err
}
} else {
flogger.Debug("Sensor %v already available in the database", sensor.FullName())
}
}
return nil
}