Deleting questions and adding tests for deleteing

This commit is contained in:
2025-11-12 19:29:13 -05:00
parent 65c5b9611c
commit ab48a68fab
2 changed files with 88 additions and 2 deletions

View File

@@ -12,6 +12,7 @@ import (
var ErrQuestionAlreadyExists = errors.New("Question already exists")
var ErrQuestionDoesntExist = errors.New("Question does not exist yet")
var ErrVoterAlreadyVoted = errors.New("Voter already voted")
var ErrPollNotFound = errors.New("Poll not found")
func CreatePoll(poll *models.Poll) (*models.Poll, error) {
new_poll := models.Poll{}
@@ -100,7 +101,7 @@ func GetPollByQuestion(question string) (*models.Poll, error) {
)
if err == sql.ErrNoRows {
return nil, ErrQuestionDoesntExist
return nil, ErrPollNotFound
} else if err != nil {
return nil, err
}
@@ -132,7 +133,7 @@ func GetPollByQuestion(question string) (*models.Poll, error) {
func GetAndCreatePollByQuestion(question string) (*models.Poll, error) {
new_poll, err := GetPollByQuestion(question)
if err == ErrQuestionDoesntExist {
if err == ErrPollNotFound {
create_poll := &models.Poll{
Question: question,
ExpiresAt: time.Now().Add(time.Hour * 10).Format("2006-01-02 15:04:05"),
@@ -233,5 +234,54 @@ func SetVote(vote *models.Vote) error {
return err
}
return nil
}
// Delete a poll by name
func DeletePollByQuestion(question string) error {
db_conn, err := db.Connect()
if err != nil {
return err
}
defer db.Close()
delete_votes_stmt, err := db_conn.Prepare(`
DELETE FROM voters
WHERE poll_id IN (
SELECT id
FROM polls
WHERE question == $1
)
`)
if err != nil {
return err
}
defer delete_votes_stmt.Close()
_, err = delete_votes_stmt.Exec(question)
if err != nil {
return err
}
delete_poll_stmt, err := db_conn.Prepare(`
DELETE FROM polls
WHERE question == $1
`)
if err != nil {
return err
}
defer delete_poll_stmt.Close()
res, err := delete_poll_stmt.Exec(question)
if err != nil {
return err
}
if num, err := res.RowsAffected(); num != 1 {
return errors.New("Failed to delete poll")
} else if err != nil {
return err
}
return nil
}