Files
plumber/internal/store/answer.go
T

58 lines
1.5 KiB
Go

package store
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
)
// Answer is an admin reply to a question.
type Answer struct {
QuestionID string
AuthorID string
AuthorName string
Body string
CreatedAt string
UpdatedAt string
db *sql.DB
}
// NewAnswer returns an Answer bound to db.
func NewAnswer(db *sql.DB) *Answer {
return &Answer{db: db}
}
// Upsert inserts or updates the answer for QuestionID.
func (a *Answer) Upsert(ctx context.Context) error {
if a == nil || a.db == nil {
return fmt.Errorf("answer: no database")
}
a.Body = strings.TrimSpace(a.Body)
now := time.Now().UTC().Format(time.RFC3339)
if a.CreatedAt == "" {
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
}
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)
if err != nil {
return nil, err
}
a.db = db
return &a, nil
}