From b5e278742021a3b149c3c4a6c20831809180b065 Mon Sep 17 00:00:00 2001 From: ditatompel Date: Sat, 18 May 2024 19:39:27 +0700 Subject: [PATCH] Ability to delete prober by ID from CLI #2 --- cmd/server/admin.go | 1 + cmd/server/probers.go | 32 ++++++++++++++++++++++++++++++-- internal/repo/prober.go | 12 +++++++++++- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/cmd/server/admin.go b/cmd/server/admin.go index 3d70144..a0c41eb 100644 --- a/cmd/server/admin.go +++ b/cmd/server/admin.go @@ -44,6 +44,7 @@ func init() { cmd.Root.AddCommand(probersCmd) probersCmd.AddCommand(listProbersCmd) probersCmd.AddCommand(addProbersCmd) + probersCmd.AddCommand(deleteProbersCmd) listProbersCmd.Flags().StringP("sort-by", "s", "last_submit_ts", "Sort by column name, can be id or last_submit_ts") listProbersCmd.Flags().StringP("sort-dir", "d", "desc", "Sort direction, can be asc or desc") } diff --git a/cmd/server/probers.go b/cmd/server/probers.go index 35fe16a..7ccea05 100644 --- a/cmd/server/probers.go +++ b/cmd/server/probers.go @@ -3,6 +3,7 @@ package server import ( "fmt" "os" + "strconv" "strings" "text/tabwriter" "time" @@ -76,9 +77,10 @@ var addProbersCmd = &cobra.Command{ Long: `Create new prober identified by [name] (if provided) along with an API key. This command will display the prober name and API key when successfully executed.`, - Run: func(cmd *cobra.Command, args []string) { + Run: func(_ *cobra.Command, args []string) { if err := database.ConnectDB(); err != nil { - panic(err) + fmt.Println(err) + return } proberName := "" @@ -98,3 +100,29 @@ This command will display the prober name and API key when successfully executed fmt.Printf("Name: %s\nAPI Key: %s\n", prober.Name, prober.ApiKey) }, } + +var deleteProbersCmd = &cobra.Command{ + Use: "delete", + Short: "Delete prober", + Long: `Delete prober identified by id.`, + Run: func(_ *cobra.Command, _ []string) { + if err := database.ConnectDB(); err != nil { + fmt.Println(err) + return + } + proberId, err := strconv.Atoi(stringPrompt("Prober ID:")) + if err != nil { + fmt.Println("Invalid ID:", err) + return + } + + proberRepo := repo.NewProberRepo(database.GetDB()) + err = proberRepo.Delete(proberId) + if err != nil { + fmt.Println("Failed to delete prober:", err) + return + } + + fmt.Printf("Prober ID %d deleted\n", proberId) + }, +} diff --git a/internal/repo/prober.go b/internal/repo/prober.go index 65992d5..898bde1 100644 --- a/internal/repo/prober.go +++ b/internal/repo/prober.go @@ -50,7 +50,17 @@ func (repo *ProberRepo) Update(id int, name string) error { func (repo *ProberRepo) Delete(id int) error { query := `DELETE FROM tbl_prober WHERE id = ?` - _, err := repo.db.Exec(query, id) + res, err := repo.db.Exec(query, id) + if err != nil { + return err + } + row, err := res.RowsAffected() + if err != nil { + return err + } + if row == 0 { + return fmt.Errorf("no rows affected") + } return err }