Adopt sqlc for typed Postgres queries behind store entities.

This commit is contained in:
2026-08-22 06:59:56 -07:00
parent c77298411e
commit b519cf6fe5
17 changed files with 1016 additions and 147 deletions
+12 -6
View File
@@ -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(&current)
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