Files
pansy/internal/store/journal.go
T
steveandClaude Opus 4.8 6638696b00
Build image / build-and-push (push) Successful in 5s
Address Gadfly review on the grow journal
PATCH and DELETE /journal/:id were never registered. Both handlers existed, were
covered by service-level tests, and were completely unreachable — my edit to the
router anchored on a string that only exists on another branch, so it silently
did nothing. Registered, and covered by an API-level test that walks the whole
lifecycle through the router, because that is the only kind of test that could
have caught it. Anything addressed by its own id now has one.

An entry about a plop was invisible under its bed's filter. Naming only a
planting left object_id null, so "notes about this bed" silently excluded every
note written about something growing IN the bed — the two filters disagreed
about what an entry is about, which is precisely the question the reader is
asking. The parent object is now derived from the planting.

checkJournalTarget flattened every store error to ErrInvalidInput, so a real
database failure surfaced as a 400 telling the caller their request was bad, and
never reached the logs. Only "no such row" is a bad reference now; anything else
passes through.

ListJournalEntries repeated the column scan order inline, one column different
from scanJournalEntry — the classic way for a shared column list to drift out of
step with its readers. Both now build from journalScanTargets, with the list
appending the joined author name.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01H3zbym8Doka2d7D48maSgZ
2026-07-21 01:39:56 -04:00

169 lines
5.7 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
)
// journalColumns lists journal_entries columns in the order scanJournalEntry
// expects. Used unqualified for direct selects; the list read qualifies with j.
const journalColumns = `id, garden_id, object_id, planting_id, author_id, body,
observed_at, version, created_at, updated_at`
// journalScanTargets returns the scan destinations for journalColumns, in order.
// The list read appends one more for the joined author name, so the two readers
// share a single definition of the column order rather than each repeating it.
func journalScanTargets(e *domain.JournalEntry) []any {
return []any{
&e.ID, &e.GardenID, &e.ObjectID, &e.PlantingID, &e.AuthorID, &e.Body,
&e.ObservedAt, &e.Version, &e.CreatedAt, &e.UpdatedAt,
}
}
func scanJournalEntry(s scanner) (*domain.JournalEntry, error) {
var e domain.JournalEntry
if err := s.Scan(journalScanTargets(&e)...); err != nil {
return nil, err
}
return &e, nil
}
// JournalFilter narrows a garden's journal. A nil field means "don't filter on
// this". ObjectID/PlantingID select entries about one bed or one plop; the date
// range is inclusive and matches observed_at, not created_at.
type JournalFilter struct {
ObjectID *int64
PlantingID *int64
From *string
To *string
Limit int
Offset int
}
// CreateJournalEntry inserts an entry (fields already validated by the service).
func (d *DB) CreateJournalEntry(ctx context.Context, e *domain.JournalEntry) (*domain.JournalEntry, error) {
created, err := scanJournalEntry(d.sql.QueryRowContext(ctx,
`INSERT INTO journal_entries (garden_id, object_id, planting_id, author_id, body, observed_at)
VALUES (?, ?, ?, ?, ?, ?)
RETURNING `+journalColumns,
e.GardenID, e.ObjectID, e.PlantingID, e.AuthorID, e.Body, e.ObservedAt,
))
if err != nil {
return nil, fmt.Errorf("store: insert journal entry: %w", err)
}
return created, nil
}
// GetJournalEntry returns an entry by id, or domain.ErrNotFound. Permission is
// the service's business, via the entry's garden.
func (d *DB) GetJournalEntry(ctx context.Context, id int64) (*domain.JournalEntry, error) {
e, err := scanJournalEntry(d.sql.QueryRowContext(ctx,
`SELECT `+journalColumns+` FROM journal_entries WHERE id = ?`, id))
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("store: get journal entry: %w", err)
}
return e, nil
}
// ListJournalEntries returns a garden's entries, most recently OBSERVED first,
// narrowed by the filter. Each carries its author's display name, so the list
// renders without a lookup per row. Always a non-nil slice.
func (d *DB) ListJournalEntries(ctx context.Context, gardenID int64, f JournalFilter) ([]domain.JournalEntry, error) {
query := `SELECT ` + qualifyColumns("j", journalColumns) + `, u.display_name
FROM journal_entries j
JOIN users u ON u.id = j.author_id
WHERE j.garden_id = ?`
args := []any{gardenID}
if f.ObjectID != nil {
query += ` AND j.object_id = ?`
args = append(args, *f.ObjectID)
}
if f.PlantingID != nil {
query += ` AND j.planting_id = ?`
args = append(args, *f.PlantingID)
}
if f.From != nil {
query += ` AND j.observed_at >= ?`
args = append(args, *f.From)
}
if f.To != nil {
query += ` AND j.observed_at <= ?`
args = append(args, *f.To)
}
// id DESC breaks ties within a day, so several entries observed on the same
// date still read newest-first rather than in arbitrary order.
query += ` ORDER BY j.observed_at DESC, j.id DESC LIMIT ? OFFSET ?`
args = append(args, f.Limit, f.Offset)
rows, err := d.sql.QueryContext(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("store: list journal entries: %w", err)
}
defer rows.Close()
entries := []domain.JournalEntry{}
for rows.Next() {
var e domain.JournalEntry
if err := rows.Scan(append(journalScanTargets(&e), &e.AuthorName)...); err != nil {
return nil, fmt.Errorf("store: scan journal entry: %w", err)
}
entries = append(entries, e)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("store: iterate journal entries: %w", err)
}
return entries, nil
}
// UpdateJournalEntry applies a version-guarded update of the mutable columns.
// Same contract as every other mutable resource. The target (garden/object/
// planting) and the author are immutable: an entry is a record of an observation,
// so re-pointing it at a different bed would be rewriting the observation rather
// than correcting the text.
func (d *DB) UpdateJournalEntry(ctx context.Context, e *domain.JournalEntry) (*domain.JournalEntry, error) {
updated, err := scanJournalEntry(d.sql.QueryRowContext(ctx,
`UPDATE journal_entries
SET body = ?, observed_at = ?,
version = version + 1,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ? AND version = ?
RETURNING `+journalColumns,
e.Body, e.ObservedAt, e.ID, e.Version,
))
if errors.Is(err, sql.ErrNoRows) {
current, gerr := d.GetJournalEntry(ctx, e.ID)
if gerr != nil {
return nil, gerr
}
return current, domain.ErrVersionConflict
}
if err != nil {
return nil, fmt.Errorf("store: update journal entry: %w", err)
}
return updated, nil
}
// DeleteJournalEntry removes an entry. Returns domain.ErrNotFound if none was.
func (d *DB) DeleteJournalEntry(ctx context.Context, id int64) error {
res, err := d.sql.ExecContext(ctx, `DELETE FROM journal_entries WHERE id = ?`, id)
if err != nil {
return fmt.Errorf("store: delete journal entry: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("store: journal delete rows: %w", err)
}
if n == 0 {
return domain.ErrNotFound
}
return nil
}