Adopt sqlc for typed Postgres queries behind store entities.
This commit is contained in:
+19
-13
@@ -6,6 +6,8 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"plumber/internal/store/sqlc"
|
||||
)
|
||||
|
||||
// Answer is an admin reply to a question.
|
||||
@@ -35,23 +37,27 @@ func (a *Answer) Upsert(ctx context.Context) error {
|
||||
a.CreatedAt = now
|
||||
}
|
||||
a.UpdatedAt = now
|
||||
_, err := a.db.ExecContext(ctx, `
|
||||
INSERT INTO answers (question_id, author_id, body, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (question_id) DO UPDATE SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at`,
|
||||
a.QuestionID, a.AuthorID, a.Body, a.CreatedAt, a.UpdatedAt)
|
||||
return err
|
||||
return sqlc.New(a.db).UpsertAnswer(ctx, sqlc.UpsertAnswerParams{
|
||||
QuestionID: a.QuestionID,
|
||||
AuthorID: a.AuthorID,
|
||||
Body: a.Body,
|
||||
CreatedAt: a.CreatedAt,
|
||||
UpdatedAt: a.UpdatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
func GetAnswer(ctx context.Context, db *sql.DB, questionID string) (*Answer, error) {
|
||||
var a Answer
|
||||
err := db.QueryRowContext(ctx, `
|
||||
SELECT a.question_id, a.author_id, u.name, a.body, a.created_at, a.updated_at
|
||||
FROM answers a
|
||||
JOIN users u ON u.id = a.author_id
|
||||
WHERE a.question_id = $1`, questionID).Scan(&a.QuestionID, &a.AuthorID, &a.AuthorName, &a.Body, &a.CreatedAt, &a.UpdatedAt)
|
||||
r, err := sqlc.New(db).GetAnswer(ctx, questionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.db = db
|
||||
return &a, nil
|
||||
return &Answer{
|
||||
QuestionID: r.QuestionID,
|
||||
AuthorID: r.AuthorID,
|
||||
AuthorName: r.AuthorName,
|
||||
Body: r.Body,
|
||||
CreatedAt: r.CreatedAt,
|
||||
UpdatedAt: r.UpdatedAt,
|
||||
db: db,
|
||||
}, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user