Files
plumber/internal/store/vote.go
T

35 lines
1.0 KiB
Go

package store
import (
"context"
"database/sql"
"fmt"
)
// Vote toggles or sets a user's vote on a question (value must be 1 or -1).
func Vote(ctx context.Context, db *sql.DB, userID, questionID string, value int) error {
if value != 1 && value != -1 {
return fmt.Errorf("invalid vote")
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var current sql.NullInt64
err = tx.QueryRowContext(ctx, `SELECT value FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID).Scan(&current)
if err != nil && err != sql.ErrNoRows {
return err
}
if err == nil && current.Valid && int(current.Int64) == value {
_, err = tx.ExecContext(ctx, `DELETE FROM votes WHERE user_id = $1 AND question_id = $2`, userID, questionID)
} else {
_, err = tx.ExecContext(ctx, `INSERT INTO votes (user_id, question_id, value) VALUES ($1, $2, $3)
ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`, userID, questionID, value)
}
if err != nil {
return err
}
return tx.Commit()
}