polycule-connect/polyculeconnect/cmd/db/destroy.go
Melora Hugues 94a5fbfc51
All checks were successful
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/push/deploy Pipeline was successful
Feat #45: Add CLI commands to manage the DB
2024-08-10 15:24:31 +02:00

60 lines
1.6 KiB
Go

package db
import (
"errors"
"fmt"
"os"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/cmd/utils"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/config"
"github.com/spf13/cobra"
)
// destroyCmd represents the db destroy command
var destroyCmd = &cobra.Command{
Use: "destroy",
Short: "Completely delete the current database",
Long: `Delete the current database.`,
Run: func(cmd *cobra.Command, args []string) {
conf := utils.InitConfig("")
if err := deleteDB(conf); err != nil {
utils.Failf("Failed to connect to DB: %s", err.Error())
}
fmt.Println("DB deleted")
},
}
func deleteSqliteDB(path string) error {
if err := os.Remove(path); err != nil {
if errors.Is(err, os.ErrNotExist) { // if the file has already been deleted we don't want to fail here
return nil
}
return fmt.Errorf("failed to delete SQLite file: %w", err)
}
return nil
}
func deleteDB(conf *config.AppConfig) error {
switch conf.StorageType {
case string(config.Memory):
return errors.New("no DB to delete in memory mode")
case string(config.SQLite):
return deleteSqliteDB(conf.StorageConfig.File)
default:
return fmt.Errorf("unsupported storage type %q", conf.StorageType)
}
}
func init() {
dbCmd.AddCommand(destroyCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// dbCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// dbCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}