polycule-connect/polyculeconnect/cmd/db/connect.go
Melora Hugues 344589829b
Some checks failed
/ docker-build-only (push) Successful in 1m58s
/ docker-build-push (push) Failing after 9s
/ go-test (push) Successful in 1m8s
Chore: remove generated cobra comments and improve help messages
2024-08-10 16:41:55 +02:00

55 lines
1.3 KiB
Go

package db
import (
"errors"
"fmt"
"os/exec"
"syscall"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
"github.com/spf13/cobra"
)
// connectCmd represents the db connect command
var connectCmd = &cobra.Command{
Use: "connect",
Short: "Connect to the database",
Long: `Connect to the database.`,
Run: func(cmd *cobra.Command, args []string) {
conf := utils.InitConfig("")
if err := connectToDB(conf); err != nil {
utils.Failf("Failed to connect to DB: %s", err.Error())
}
},
}
func connectSQLite(conf *config.StorageConfig) error {
path, err := exec.LookPath("sqlite3")
if err != nil {
if errors.Is(err, exec.ErrNotFound) {
return errors.New("sqlite3 not installed")
}
return fmt.Errorf("failed to find sqlite3 executable: %w", err)
}
if err := syscall.Exec(path, []string{path, conf.File}, nil); err != nil {
return fmt.Errorf("failed to run sqlite3 command: %w", err)
}
return nil
}
func connectToDB(conf *config.AppConfig) error {
switch conf.StorageType {
case string(config.Memory):
return errors.New("no DB associated with memory storage")
case string(config.SQLite):
return connectSQLite(conf.StorageConfig)
default:
return fmt.Errorf("unsupported storage type %q", conf.StorageType)
}
}
func init() {
dbCmd.AddCommand(connectCmd)
}