Files
pansy/internal/store/gardens.go
T
steve 78a04672b5
Build image / build-and-push (push) Successful in 8s
Seed provenance + inventory: source links and seed lots (#50) (#64)
Co-authored-by: Steve Dudenhoeffer <[email protected]>
2026-07-21 05:39:24 +00:00

312 lines
11 KiB
Go

package store
import (
"context"
"database/sql"
"errors"
"fmt"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/domain"
)
// gardenColumns lists the gardens columns in the fixed order scanGarden expects.
const gardenColumns = `id, owner_id, name, width_cm, height_cm, unit_pref, notes, grid_size_cm, snap_to_grid, version, created_at, updated_at`
func scanGarden(s scanner) (*domain.Garden, error) {
var (
g domain.Garden
snap int64
)
if err := s.Scan(
&g.ID, &g.OwnerID, &g.Name, &g.WidthCM, &g.HeightCM,
&g.UnitPref, &g.Notes, &g.GridSizeCM, &snap, &g.Version, &g.CreatedAt, &g.UpdatedAt,
); err != nil {
return nil, err
}
g.SnapToGrid = snap != 0
return &g, nil
}
// scanGardenWithRole reads a garden row plus a trailing my_role column into the
// computed Garden.MyRole field (used by the actor-scoped list).
func scanGardenWithRole(s scanner) (*domain.Garden, error) {
var (
g domain.Garden
snap int64
)
if err := s.Scan(
&g.ID, &g.OwnerID, &g.Name, &g.WidthCM, &g.HeightCM,
&g.UnitPref, &g.Notes, &g.GridSizeCM, &snap, &g.Version, &g.CreatedAt, &g.UpdatedAt, &g.MyRole,
); err != nil {
return nil, err
}
g.SnapToGrid = snap != 0
return &g, nil
}
// maxGardensListed caps the gardens list as a defensive backstop against a
// pathologically large result. At household scale a user has a handful of
// gardens, so this is never hit; genuine pagination is post-v1 if ever needed.
const maxGardensListed = 1000
// CreateGarden inserts a garden (owner_id, name, dimensions, unit, notes already
// set and validated by the service) and returns the stored row.
func (d *DB) CreateGarden(ctx context.Context, g *domain.Garden) (*domain.Garden, error) {
created, err := scanGarden(d.sql.QueryRowContext(ctx,
`INSERT INTO gardens (owner_id, name, width_cm, height_cm, unit_pref, notes, grid_size_cm, snap_to_grid)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
RETURNING `+gardenColumns,
g.OwnerID, g.Name, g.WidthCM, g.HeightCM, g.UnitPref, g.Notes, g.GridSizeCM, boolToInt(g.SnapToGrid),
))
if err != nil {
return nil, fmt.Errorf("store: insert garden: %w", err)
}
return created, nil
}
// GetGarden returns the garden with the given id, or domain.ErrNotFound.
func (d *DB) GetGarden(ctx context.Context, id int64) (*domain.Garden, error) {
g, err := scanGarden(d.sql.QueryRowContext(ctx,
`SELECT `+gardenColumns+` FROM gardens WHERE id = ?`, id))
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("store: get garden: %w", err)
}
return g, nil
}
// ListGardensForActor returns the gardens an actor can see — those they own
// (my_role "owner") plus those shared with them (my_role = the share's role) —
// newest first. Always a non-nil slice.
func (d *DB) ListGardensForActor(ctx context.Context, actorID int64) ([]domain.Garden, error) {
rows, err := d.sql.QueryContext(ctx,
`SELECT `+gardenColumns+`, my_role FROM (
SELECT `+gardenColumns+`, 'owner' AS my_role FROM gardens WHERE owner_id = ?
UNION ALL
SELECT `+qualifyColumns("g", gardenColumns)+`, s.role AS my_role
FROM gardens g JOIN garden_shares s ON s.garden_id = g.id
WHERE s.user_id = ?
)
ORDER BY created_at DESC, id DESC
LIMIT ?`,
actorID, actorID, maxGardensListed,
)
if err != nil {
return nil, fmt.Errorf("store: list gardens: %w", err)
}
defer rows.Close()
gardens := []domain.Garden{}
for rows.Next() {
g, err := scanGardenWithRole(rows)
if err != nil {
return nil, fmt.Errorf("store: scan garden: %w", err)
}
gardens = append(gardens, *g)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("store: iterate gardens: %w", err)
}
return gardens, nil
}
// UpdateGarden applies a version-guarded update (optimistic concurrency): the row
// is written only if its stored version matches g.Version, and version is
// incremented on success. It returns:
// - the updated row, on success;
// - (current row, domain.ErrVersionConflict) when the version didn't match, so
// the caller can hand the fresh row back to the client to rebase;
// - (nil, domain.ErrNotFound) if the row no longer exists.
//
// This is the sync contract every mutable resource in pansy follows.
func (d *DB) UpdateGarden(ctx context.Context, g *domain.Garden) (*domain.Garden, error) {
updated, err := scanGarden(d.sql.QueryRowContext(ctx,
`UPDATE gardens
SET name = ?, width_cm = ?, height_cm = ?, unit_pref = ?, notes = ?,
grid_size_cm = ?, snap_to_grid = ?,
version = version + 1,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = ? AND version = ?
RETURNING `+gardenColumns,
g.Name, g.WidthCM, g.HeightCM, g.UnitPref, g.Notes, g.GridSizeCM, boolToInt(g.SnapToGrid), g.ID, g.Version,
))
if errors.Is(err, sql.ErrNoRows) {
// No row matched: distinguish "gone" from "stale version".
current, gerr := d.GetGarden(ctx, g.ID)
if gerr != nil {
return nil, gerr // ErrNotFound (or a real error)
}
return current, domain.ErrVersionConflict
}
if err != nil {
return nil, fmt.Errorf("store: update garden: %w", err)
}
return updated, nil
}
// DeleteGarden removes a garden (and, via ON DELETE CASCADE, its objects/shares).
// Returns domain.ErrNotFound if no row was deleted.
func (d *DB) DeleteGarden(ctx context.Context, id int64) error {
res, err := d.sql.ExecContext(ctx, `DELETE FROM gardens WHERE id = ?`, id)
if err != nil {
return fmt.Errorf("store: delete garden: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("store: garden delete rows: %w", err)
}
if n == 0 {
return domain.ErrNotFound
}
return nil
}
// CopyGarden deep-copies garden srcID into a new garden owned by ownerID and
// named name, returning the new row. Objects are copied with their geometry,
// grid settings and z-order, and each object's ACTIVE plantings (removed_at IS
// NULL) are re-parented onto the copied object.
//
// Deliberately not copied:
// - public_token — the share link is a capability granted to the original, so a
// copy must not silently inherit a live public URL;
// - garden_shares — a copy is private to whoever made it;
// - removed plantings — the copy is a fresh layout, not the original's history.
//
// The whole copy runs in one transaction, so a failure part-way leaves no
// half-populated garden behind. Returns domain.ErrNotFound if srcID is gone.
func (d *DB) CopyGarden(ctx context.Context, srcID, ownerID int64, name string) (*domain.Garden, error) {
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("store: begin copy garden tx: %w", err)
}
defer tx.Rollback() //nolint:errcheck // no-op after a successful commit
// INSERT ... SELECT copies the source's own columns; owner and name are
// supplied. If the source is gone the SELECT is empty, nothing is inserted,
// and RETURNING yields no rows.
created, err := scanGarden(tx.QueryRowContext(ctx,
`INSERT INTO gardens (owner_id, name, width_cm, height_cm, unit_pref, notes, grid_size_cm, snap_to_grid)
SELECT ?, ?, width_cm, height_cm, unit_pref, notes, grid_size_cm, snap_to_grid
FROM gardens WHERE id = ?
RETURNING `+gardenColumns,
ownerID, name, srcID,
))
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("store: copy garden: %w", err)
}
// Read the source's objects fully before inserting: SQLite can't have an open
// cursor and a write on the same connection, and the pool is pinned to one
// connection for in-memory DBs.
srcObjects, err := queryObjects(ctx, tx,
`SELECT `+objectColumns+` FROM garden_objects WHERE garden_id = ? ORDER BY id`, srcID)
if err != nil {
return nil, err
}
// objectIDs maps a source object id to its copy, so plantings can be
// re-parented onto the right new object.
objectIDs := make(map[int64]int64, len(srcObjects))
for _, o := range srcObjects {
copied, err := scanObject(tx.QueryRowContext(ctx, objectInsert, objectInsertArgs(created.ID, &o)...))
if err != nil {
return nil, fmt.Errorf("store: copy object: %w", err)
}
objectIDs[o.ID] = copied.ID
}
srcPlantings, err := queryPlantings(ctx, tx,
`SELECT `+qualifyColumns("pl", plantingColumns)+` FROM plantings pl
JOIN garden_objects o ON o.id = pl.object_id
WHERE o.garden_id = ? AND pl.removed_at IS NULL
ORDER BY pl.id`, srcID)
if err != nil {
return nil, err
}
for _, p := range srcPlantings {
objectID, ok := objectIDs[p.ObjectID]
if !ok {
// Unreachable: every active planting joins an object we just copied.
return nil, fmt.Errorf("store: copy planting %d: source object %d not copied", p.ID, p.ObjectID)
}
// A copy must not inherit the source's seed-lot attribution. The copied
// plops are a plan, not a second planting out of the same packet, and
// carrying the link would double-count that lot's usage — and quietly
// attach a private lot to a garden that may later be shared.
p.SeedLotID = nil
if _, err := scanPlanting(tx.QueryRowContext(ctx, plantingInsert, plantingInsertArgs(objectID, &p)...)); err != nil {
return nil, fmt.Errorf("store: copy planting: %w", err)
}
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("store: commit garden copy: %w", err)
}
return created, nil
}
// GetGardenByPublicToken returns the garden whose public_token matches, or
// domain.ErrNotFound. Possession of the token is the capability, so there is no
// owner/actor check here — the service exposes this only for the unauthenticated
// public-read path. public_token itself is never selected into the row (it stays
// out of gardenColumns), so it can't leak through the returned garden.
func (d *DB) GetGardenByPublicToken(ctx context.Context, token string) (*domain.Garden, error) {
g, err := scanGarden(d.sql.QueryRowContext(ctx,
`SELECT `+gardenColumns+` FROM gardens WHERE public_token = ?`, token))
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("store: get garden by public token: %w", err)
}
return g, nil
}
// GetGardenPublicToken returns the garden's current public token (nil when the
// public link is disabled), or domain.ErrNotFound if the garden is gone.
func (d *DB) GetGardenPublicToken(ctx context.Context, gardenID int64) (*string, error) {
var tok sql.NullString
err := d.sql.QueryRowContext(ctx, `SELECT public_token FROM gardens WHERE id = ?`, gardenID).Scan(&tok)
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("store: get garden public token: %w", err)
}
if !tok.Valid {
return nil, nil
}
return &tok.String, nil
}
// SetGardenPublicToken sets the garden's public token (enabling/rotating the
// link) or clears it with a nil token (disabling the link). It does not bump the
// garden version — the public link is out-of-band from garden edits, so toggling
// it must not spuriously conflict a concurrent editor. Returns domain.ErrNotFound
// if the garden is gone.
func (d *DB) SetGardenPublicToken(ctx context.Context, gardenID int64, token *string) error {
var val any
if token != nil {
val = *token
}
res, err := d.sql.ExecContext(ctx,
`UPDATE gardens SET public_token = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = ?`,
val, gardenID)
if err != nil {
return fmt.Errorf("store: set garden public token: %w", err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("store: set garden public token rows: %w", err)
}
if n == 0 {
return domain.ErrNotFound
}
return nil
}