Adopt sqlc for typed Postgres queries behind store entities.
This commit is contained in:
+12
-6
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
"plumber/internal/store/sqlc"
|
||||
)
|
||||
|
||||
// Vote toggles or sets a user's vote on a question (value must be 1 or -1).
|
||||
@@ -16,16 +18,20 @@ func Vote(ctx context.Context, db *sql.DB, userID, questionID string, value int)
|
||||
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(¤t)
|
||||
|
||||
q := sqlc.New(tx)
|
||||
current, err := q.GetVote(ctx, sqlc.GetVoteParams{UserID: userID, QuestionID: questionID})
|
||||
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)
|
||||
if err == nil && int(current) == value {
|
||||
err = q.DeleteVote(ctx, sqlc.DeleteVoteParams{UserID: userID, QuestionID: 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)
|
||||
err = q.UpsertVote(ctx, sqlc.UpsertVoteParams{
|
||||
UserID: userID,
|
||||
QuestionID: questionID,
|
||||
Value: int32(value),
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
Reference in New Issue
Block a user