Phase 0: backend + frontend scaffold, single-binary build
Implements the Pansy v1 scaffold (epic #20, phase 0). #1 Backend: Go module (pure-Go, builds with CGO_ENABLED=0), env config, gin server with slog + recovery + /api/v1/healthz, modernc SQLite store with WAL/busy_timeout/foreign_keys pragmas, embedded numbered-migration runner, full initial schema (users, sessions, gardens, garden_shares, garden_objects, plants, plantings), domain structs + sentinel errors, graceful shutdown. #2 Frontend: Vite + React 19 + TS (strict) + Tailwind 4 + TanStack Router/Query, typed /api/v1 fetch wrapper (ApiError carries status + body so later issues can read 409 conflict rows), dev proxy /api -> :8080, responsive app shell with stub pages for all five routes. #3 Single binary: //go:embed of the web build with a committed placeholder, SPA fallback (deep links, immutable asset caching, JSON 404 for unmatched /api and missing assets), Makefile (web/build/dev/test), README quickstart + env var table. Verified: go build/vet/test clean (CGO off); binary migrates idempotently and serves healthz; web tsc + build clean; integrated binary serves the SPA, deep links, and correct cache headers; app mounts and navigates all five routes at desktop and 375px widths. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
// Package api wires pansy's HTTP surface: a gin engine with structured logging
|
||||
// and panic recovery, the versioned JSON API under /api/v1, and (via spa.go) the
|
||||
// embedded single-page-app fallback. Handlers stay thin — decode, call the
|
||||
// service layer, encode — so all business logic and permission checks live in
|
||||
// internal/service (added by later issues).
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
sloggin "github.com/samber/slog-gin"
|
||||
|
||||
"gitea.stevedudenhoeffer.com/steve/pansy/internal/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// Quiet gin's default debug output; we log via slog-gin instead.
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
// New builds the gin engine with the standard middleware stack and registers the
|
||||
// API routes. The embedded SPA fallback is registered separately by the caller
|
||||
// via RegisterSPA (see spa.go) so the API can be built and tested without a web
|
||||
// build present.
|
||||
func New(cfg *config.Config) *gin.Engine {
|
||||
r := gin.New()
|
||||
r.Use(sloggin.New(slog.Default()), gin.Recovery())
|
||||
|
||||
if err := r.SetTrustedProxies(cfg.TrustedProxies); err != nil {
|
||||
slog.Warn("api: failed to set trusted proxies", "error", err)
|
||||
}
|
||||
|
||||
v1 := r.Group("/api/v1")
|
||||
v1.GET("/healthz", healthz)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// healthz is a liveness probe: always returns {"ok": true} when the server is up.
|
||||
func healthz(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// RegisterSPA serves the embedded single-page app for every route gin didn't
|
||||
// otherwise match. A request whose path maps to a real file (e.g. a hashed asset
|
||||
// bundle) is served directly; any other non-API path falls back to index.html so
|
||||
// client-side deep links like /gardens/42 load the app. Unmatched /api paths
|
||||
// return a JSON 404 rather than HTML.
|
||||
func RegisterSPA(r *gin.Engine, dist fs.FS) {
|
||||
fileServer := http.FileServer(http.FS(dist))
|
||||
|
||||
r.NoRoute(func(c *gin.Context) {
|
||||
reqPath := c.Request.URL.Path
|
||||
|
||||
if strings.HasPrefix(reqPath, "/api/") {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{
|
||||
"code": "NOT_FOUND", "message": "no such endpoint",
|
||||
}})
|
||||
return
|
||||
}
|
||||
|
||||
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
|
||||
c.JSON(http.StatusMethodNotAllowed, gin.H{"error": gin.H{
|
||||
"code": "METHOD_NOT_ALLOWED", "message": "method not allowed",
|
||||
}})
|
||||
return
|
||||
}
|
||||
|
||||
name := strings.TrimPrefix(path.Clean(reqPath), "/")
|
||||
if name == "" {
|
||||
name = "index.html"
|
||||
}
|
||||
|
||||
if f, err := dist.Open(name); err == nil {
|
||||
f.Close()
|
||||
// Vite emits content-hashed filenames under assets/, so those are safe
|
||||
// to cache forever; index.html must always revalidate to pick up new builds.
|
||||
if strings.HasPrefix(name, "assets/") {
|
||||
c.Header("Cache-Control", "public, max-age=31536000, immutable")
|
||||
} else {
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
}
|
||||
fileServer.ServeHTTP(c.Writer, c.Request)
|
||||
return
|
||||
}
|
||||
|
||||
// A missing file under assets/ is a genuine 404, not a client route:
|
||||
// falling back to index.html would return HTML with a 200 for a .js/.css
|
||||
// request, which the browser rejects with a confusing MIME-type error.
|
||||
if strings.HasPrefix(name, "assets/") {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{
|
||||
"code": "NOT_FOUND", "message": "asset not found",
|
||||
}})
|
||||
return
|
||||
}
|
||||
|
||||
serveIndex(c, dist)
|
||||
})
|
||||
}
|
||||
|
||||
// serveIndex writes index.html as the SPA fallback for an unmatched client route.
|
||||
func serveIndex(c *gin.Context, dist fs.FS) {
|
||||
data, err := fs.ReadFile(dist, "index.html")
|
||||
if err != nil {
|
||||
c.String(http.StatusInternalServerError, "index.html missing from build")
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
c.Data(http.StatusOK, "text/html; charset=utf-8", data)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func testEngine() *gin.Engine {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
// A real API route so unmatched /api/* paths reach NoRoute (as in production).
|
||||
r.GET("/api/v1/healthz", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) })
|
||||
|
||||
dist := fstest.MapFS{
|
||||
"index.html": &fstest.MapFile{Data: []byte(`<!doctype html><div id="root"></div>`)},
|
||||
"assets/app-abc123.js": &fstest.MapFile{Data: []byte(`console.log(1)`)},
|
||||
}
|
||||
RegisterSPA(r, dist)
|
||||
return r
|
||||
}
|
||||
|
||||
func do(t *testing.T, r *gin.Engine, method, path string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(method, path, nil))
|
||||
return w
|
||||
}
|
||||
|
||||
func TestSPAServesHashedAssetImmutable(t *testing.T) {
|
||||
w := do(t, testEngine(), http.MethodGet, "/assets/app-abc123.js")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", w.Code)
|
||||
}
|
||||
if cc := w.Header().Get("Cache-Control"); !strings.Contains(cc, "immutable") {
|
||||
t.Errorf("Cache-Control = %q, want immutable", cc)
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "javascript") {
|
||||
t.Errorf("Content-Type = %q, want javascript", ct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPAServesIndexNoCache(t *testing.T) {
|
||||
w := do(t, testEngine(), http.MethodGet, "/")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", w.Code)
|
||||
}
|
||||
if cc := w.Header().Get("Cache-Control"); cc != "no-cache" {
|
||||
t.Errorf("Cache-Control = %q, want no-cache", cc)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPAFallbackForClientRoute(t *testing.T) {
|
||||
// A deep link with no matching file returns index.html so client routing works.
|
||||
w := do(t, testEngine(), http.MethodGet, "/gardens/42")
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", w.Code)
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), `id="root"`) {
|
||||
t.Errorf("expected index.html body, got %q", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPAMissingAssetIs404(t *testing.T) {
|
||||
// A missing asset must NOT fall back to index.html (which would be a 200 of
|
||||
// HTML for a .js request — a MIME-type error in the browser).
|
||||
w := do(t, testEngine(), http.MethodGet, "/assets/missing-xyz.js")
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404", w.Code)
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "json") {
|
||||
t.Errorf("Content-Type = %q, want json", ct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPAUnmatchedAPIIs404JSON(t *testing.T) {
|
||||
w := do(t, testEngine(), http.MethodGet, "/api/v1/nope")
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404", w.Code)
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "json") {
|
||||
t.Errorf("Content-Type = %q, want json (not the SPA HTML)", ct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPARejectsNonGET(t *testing.T) {
|
||||
w := do(t, testEngine(), http.MethodPost, "/gardens")
|
||||
if w.Code != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("status = %d, want 405", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// Package config loads pansy's runtime configuration from the environment.
|
||||
//
|
||||
// Every value has a sensible default so `pansy` runs with zero configuration
|
||||
// for local use; production deployments override via PANSY_* env vars. Auth
|
||||
// values (local + OIDC) are plumbed here now and consumed by the auth issues
|
||||
// (#4 local, #5 OIDC).
|
||||
package config
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Registration gates local self-service signup.
|
||||
const (
|
||||
RegistrationOpen = "open"
|
||||
RegistrationClosed = "closed"
|
||||
)
|
||||
|
||||
// Config is the fully-resolved runtime configuration.
|
||||
type Config struct {
|
||||
// Port is the TCP port the HTTP server listens on (PANSY_PORT, default 8080).
|
||||
Port int
|
||||
// DBPath is the SQLite database file path (PANSY_DB, default ./pansy.db).
|
||||
DBPath string
|
||||
// BaseURL is the externally-visible base URL, used to derive the OIDC
|
||||
// redirect URI and absolute links (PANSY_BASE_URL). Empty in bare local dev.
|
||||
BaseURL string
|
||||
// Registration is "open" or "closed"; gates POST /auth/register for local
|
||||
// accounts (PANSY_REGISTRATION, default open). OIDC JIT provisioning ignores
|
||||
// this — the IdP gates access.
|
||||
Registration string
|
||||
// LocalAuth enables argon2id username/password auth (PANSY_LOCAL_AUTH,
|
||||
// default true). Set false for pure-Authentik deployments.
|
||||
LocalAuth bool
|
||||
// OIDC holds the optional OpenID Connect provider settings.
|
||||
OIDC OIDCConfig
|
||||
// TrustedProxies is the set of proxy CIDRs/IPs gin trusts for client IP
|
||||
// resolution (PANSY_TRUSTED_PROXIES, comma-separated). Empty trusts none.
|
||||
TrustedProxies []string
|
||||
}
|
||||
|
||||
// OIDCConfig holds the OpenID Connect provider settings (Authentik is the
|
||||
// primary IdP). Consumed by #5.
|
||||
type OIDCConfig struct {
|
||||
Issuer string // PANSY_OIDC_ISSUER — discovery base URL
|
||||
ClientID string // PANSY_OIDC_CLIENT_ID
|
||||
ClientSecret string // PANSY_OIDC_CLIENT_SECRET
|
||||
ButtonLabel string // PANSY_OIDC_BUTTON_LABEL — login-page button text
|
||||
}
|
||||
|
||||
// Enabled reports whether enough OIDC config is present to attempt discovery.
|
||||
func (o OIDCConfig) Enabled() bool {
|
||||
return o.Issuer != "" && o.ClientID != ""
|
||||
}
|
||||
|
||||
// RegistrationOpen reports whether local self-service signup is allowed.
|
||||
func (c *Config) RegistrationOpen() bool {
|
||||
return c.Registration == RegistrationOpen
|
||||
}
|
||||
|
||||
// Load reads configuration from the environment, applying defaults. It never
|
||||
// fails: invalid numeric/boolean values fall back to the default and are logged.
|
||||
func Load() *Config {
|
||||
cfg := &Config{
|
||||
Port: envInt("PANSY_PORT", 8080),
|
||||
DBPath: envStr("PANSY_DB", "./pansy.db"),
|
||||
BaseURL: strings.TrimRight(envStr("PANSY_BASE_URL", ""), "/"),
|
||||
Registration: envStr("PANSY_REGISTRATION", RegistrationOpen),
|
||||
LocalAuth: envBool("PANSY_LOCAL_AUTH", true),
|
||||
OIDC: OIDCConfig{
|
||||
Issuer: envStr("PANSY_OIDC_ISSUER", ""),
|
||||
ClientID: envStr("PANSY_OIDC_CLIENT_ID", ""),
|
||||
ClientSecret: envStr("PANSY_OIDC_CLIENT_SECRET", ""),
|
||||
ButtonLabel: envStr("PANSY_OIDC_BUTTON_LABEL", "Sign in with SSO"),
|
||||
},
|
||||
TrustedProxies: envList("PANSY_TRUSTED_PROXIES"),
|
||||
}
|
||||
|
||||
if cfg.Registration != RegistrationOpen && cfg.Registration != RegistrationClosed {
|
||||
slog.Warn("config: invalid PANSY_REGISTRATION, defaulting to open", "value", cfg.Registration)
|
||||
cfg.Registration = RegistrationOpen
|
||||
}
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func envStr(key, def string) string {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func envInt(key string, def int) int {
|
||||
v, ok := os.LookupEnv(key)
|
||||
if !ok || v == "" {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
slog.Warn("config: invalid int env, using default", "key", key, "value", v, "default", def)
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func envBool(key string, def bool) bool {
|
||||
v, ok := os.LookupEnv(key)
|
||||
if !ok || v == "" {
|
||||
return def
|
||||
}
|
||||
b, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
slog.Warn("config: invalid bool env, using default", "key", key, "value", v, "default", def)
|
||||
return def
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func envList(key string) []string {
|
||||
v, ok := os.LookupEnv(key)
|
||||
if !ok || v == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(v, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// Package domain holds pansy's core types: plain structs mirroring the database
|
||||
// schema and the sentinel errors the service layer returns. It has no
|
||||
// dependencies on store, api, or any framework — every other package depends on
|
||||
// it, not the other way around.
|
||||
package domain
|
||||
|
||||
import "errors"
|
||||
|
||||
// Sentinel errors returned by the service layer and mapped to HTTP status codes
|
||||
// by the API layer (404, 403, 409 respectively).
|
||||
var (
|
||||
// ErrNotFound means the requested entity does not exist (or is invisible to
|
||||
// the actor, when we deliberately mask existence).
|
||||
ErrNotFound = errors.New("not found")
|
||||
// ErrForbidden means the actor is known but lacks permission for the action.
|
||||
ErrForbidden = errors.New("forbidden")
|
||||
// ErrVersionConflict means the row's version did not match the one supplied
|
||||
// with a PATCH/DELETE; the caller should refetch and retry.
|
||||
ErrVersionConflict = errors.New("version conflict")
|
||||
)
|
||||
|
||||
// Enumerated string values mirrored from the schema CHECK constraints.
|
||||
const (
|
||||
UnitMetric = "metric"
|
||||
UnitImperial = "imperial"
|
||||
|
||||
RoleViewer = "viewer"
|
||||
RoleEditor = "editor"
|
||||
|
||||
KindBed = "bed"
|
||||
KindGrowBag = "grow_bag"
|
||||
KindContainer = "container"
|
||||
KindInGround = "in_ground"
|
||||
KindTree = "tree"
|
||||
KindPath = "path"
|
||||
KindStructure = "structure"
|
||||
|
||||
ShapeRect = "rect"
|
||||
ShapeCircle = "circle"
|
||||
ShapePolygon = "polygon" // reserved for post-v1
|
||||
|
||||
CategoryVegetable = "vegetable"
|
||||
CategoryHerb = "herb"
|
||||
CategoryFlower = "flower"
|
||||
CategoryFruit = "fruit"
|
||||
CategoryTreeShrub = "tree_shrub"
|
||||
CategoryCover = "cover"
|
||||
)
|
||||
|
||||
// User is a pansy account. It may have a local password, OIDC identity, or both.
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
PasswordHash *string `json:"-"` // never serialized
|
||||
OIDCIssuer *string `json:"-"`
|
||||
OIDCSubject *string `json:"-"`
|
||||
IsAdmin bool `json:"isAdmin"`
|
||||
Version int64 `json:"version"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// Session is a server-side session record. The raw token is never stored; only
|
||||
// its sha256 hash (the primary key) is.
|
||||
type Session struct {
|
||||
TokenHash string `json:"-"`
|
||||
UserID int64 `json:"userId"`
|
||||
ExpiresAt string `json:"expiresAt"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
}
|
||||
|
||||
// Garden is a planning surface owned by one user, at real-world scale (cm).
|
||||
type Garden struct {
|
||||
ID int64 `json:"id"`
|
||||
OwnerID int64 `json:"ownerId"`
|
||||
Name string `json:"name"`
|
||||
WidthCM float64 `json:"widthCm"`
|
||||
HeightCM float64 `json:"heightCm"`
|
||||
UnitPref string `json:"unitPref"`
|
||||
Notes string `json:"notes"`
|
||||
Version int64 `json:"version"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// GardenShare grants a non-owner user viewer or editor access to a garden.
|
||||
type GardenShare struct {
|
||||
ID int64 `json:"id"`
|
||||
GardenID int64 `json:"gardenId"`
|
||||
UserID int64 `json:"userId"`
|
||||
Role string `json:"role"`
|
||||
CreatedBy int64 `json:"createdBy"`
|
||||
Version int64 `json:"version"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// GardenObject is any placeable object in a garden (bed, container, tree, path…).
|
||||
// Positioned by center point + rotation about center, in garden space.
|
||||
type GardenObject struct {
|
||||
ID int64 `json:"id"`
|
||||
GardenID int64 `json:"gardenId"`
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
Shape string `json:"shape"`
|
||||
Points *string `json:"points,omitempty"` // reserved: JSON for polygons
|
||||
XCM float64 `json:"xCm"`
|
||||
YCM float64 `json:"yCm"`
|
||||
WidthCM float64 `json:"widthCm"`
|
||||
HeightCM float64 `json:"heightCm"`
|
||||
RotationDeg float64 `json:"rotationDeg"`
|
||||
ZIndex int `json:"zIndex"`
|
||||
Plantable bool `json:"plantable"`
|
||||
Color *string `json:"color,omitempty"`
|
||||
Props *string `json:"props,omitempty"` // kind-specific JSON
|
||||
Notes string `json:"notes"`
|
||||
Version int64 `json:"version"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// Plant is a catalog entry. OwnerID nil means a read-only seeded built-in.
|
||||
type Plant struct {
|
||||
ID int64 `json:"id"`
|
||||
OwnerID *int64 `json:"ownerId,omitempty"` // nil = built-in
|
||||
Name string `json:"name"`
|
||||
Category string `json:"category"`
|
||||
SpacingCM float64 `json:"spacingCm"`
|
||||
Color string `json:"color"`
|
||||
Icon string `json:"icon"`
|
||||
DaysToMaturity *int `json:"daysToMaturity,omitempty"`
|
||||
Notes string `json:"notes"`
|
||||
Version int64 `json:"version"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// Planting ("plop") is a circular patch of one plant, positioned in its parent
|
||||
// object's local frame. Count nil means it is derived from area / spacing².
|
||||
type Planting struct {
|
||||
ID int64 `json:"id"`
|
||||
ObjectID int64 `json:"objectId"`
|
||||
PlantID int64 `json:"plantId"`
|
||||
XCM float64 `json:"xCm"`
|
||||
YCM float64 `json:"yCm"`
|
||||
RadiusCM float64 `json:"radiusCm"`
|
||||
Count *int `json:"count,omitempty"` // nil = derived
|
||||
Label *string `json:"label,omitempty"`
|
||||
PlantedAt *string `json:"plantedAt,omitempty"`
|
||||
RemovedAt *string `json:"removedAt,omitempty"`
|
||||
Version int64 `json:"version"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
UpdatedAt string `json:"updatedAt"`
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed migrations/*.sql
|
||||
var migrationsFS embed.FS
|
||||
|
||||
// migration is one numbered SQL file: version parsed from the filename prefix.
|
||||
type migration struct {
|
||||
version int
|
||||
name string
|
||||
sql string
|
||||
}
|
||||
|
||||
// Migrate applies every embedded migration whose version has not yet been
|
||||
// recorded, in ascending order, each in its own transaction. It is idempotent:
|
||||
// a second run with no new files is a no-op. Migration files are named
|
||||
// NNNN_description.sql (e.g. 0001_init.sql); NNNN is the version.
|
||||
func (d *DB) Migrate(ctx context.Context) error {
|
||||
if _, err := d.sql.ExecContext(ctx,
|
||||
`CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY)`,
|
||||
); err != nil {
|
||||
return fmt.Errorf("store: create schema_migrations: %w", err)
|
||||
}
|
||||
|
||||
applied, err := d.appliedVersions(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, m := range migrations {
|
||||
if applied[m.version] {
|
||||
continue
|
||||
}
|
||||
if err := d.applyMigration(ctx, m); err != nil {
|
||||
return err
|
||||
}
|
||||
slog.Info("store: applied migration", "version", m.version, "name", m.name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) appliedVersions(ctx context.Context) (map[int]bool, error) {
|
||||
rows, err := d.sql.QueryContext(ctx, `SELECT version FROM schema_migrations`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: read schema_migrations: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
applied := map[int]bool{}
|
||||
for rows.Next() {
|
||||
var v int
|
||||
if err := rows.Scan(&v); err != nil {
|
||||
return nil, fmt.Errorf("store: scan schema_migrations: %w", err)
|
||||
}
|
||||
applied[v] = true
|
||||
}
|
||||
return applied, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) applyMigration(ctx context.Context, m migration) error {
|
||||
tx, err := d.sql.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("store: begin migration %d: %w", m.version, err)
|
||||
}
|
||||
defer tx.Rollback() //nolint:errcheck // no-op after a successful commit
|
||||
|
||||
if _, err := tx.ExecContext(ctx, m.sql); err != nil {
|
||||
return fmt.Errorf("store: apply migration %d (%s): %w", m.version, m.name, err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO schema_migrations (version) VALUES (?)`, m.version,
|
||||
); err != nil {
|
||||
return fmt.Errorf("store: record migration %d: %w", m.version, err)
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// loadMigrations reads and parses every embedded migration file, sorted by
|
||||
// version ascending.
|
||||
func loadMigrations() ([]migration, error) {
|
||||
entries, err := fs.ReadDir(migrationsFS, "migrations")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: read migrations dir: %w", err)
|
||||
}
|
||||
|
||||
var migrations []migration
|
||||
for _, e := range entries {
|
||||
if e.IsDir() || !strings.HasSuffix(e.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
version, err := parseVersion(e.Name())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, err := fs.ReadFile(migrationsFS, "migrations/"+e.Name())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: read migration %s: %w", e.Name(), err)
|
||||
}
|
||||
migrations = append(migrations, migration{version: version, name: e.Name(), sql: string(body)})
|
||||
}
|
||||
|
||||
sort.Slice(migrations, func(i, j int) bool {
|
||||
return migrations[i].version < migrations[j].version
|
||||
})
|
||||
return migrations, nil
|
||||
}
|
||||
|
||||
// parseVersion extracts the leading integer from a migration filename such as
|
||||
// "0001_init.sql".
|
||||
func parseVersion(name string) (int, error) {
|
||||
prefix, _, ok := strings.Cut(name, "_")
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("store: migration %q missing NNNN_ prefix", name)
|
||||
}
|
||||
v, err := strconv.Atoi(prefix)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("store: migration %q has non-numeric version: %w", name, err)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
-- 0001_init.sql — pansy initial schema.
|
||||
--
|
||||
-- Conventions (see DESIGN.md § Domain model):
|
||||
-- * All measurements are centimeters (REAL); imperial is a display concern.
|
||||
-- * `version INTEGER NOT NULL DEFAULT 1` on every user-mutable row; PATCH/DELETE
|
||||
-- carry it and the service layer increments on write for 409 conflict detection.
|
||||
-- * Enumerations are enforced with CHECK constraints.
|
||||
-- * Timestamps are ISO-8601 TEXT (UTC); dates are 'YYYY-MM-DD' TEXT.
|
||||
-- * Foreign keys cascade on owner/parent deletion; enforcement is on (PRAGMA foreign_keys).
|
||||
|
||||
-- users -----------------------------------------------------------------------
|
||||
-- A user may authenticate locally (password_hash), via OIDC (oidc_issuer+subject),
|
||||
-- or both (linked by email on first OIDC login). First registered user is admin.
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY,
|
||||
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT, -- argon2id; NULL for OIDC-only users
|
||||
oidc_issuer TEXT, -- NULL for local-only users
|
||||
oidc_subject TEXT,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)),
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||||
);
|
||||
-- NULLs compare distinct in SQLite, so this only constrains real (issuer, subject) pairs.
|
||||
CREATE UNIQUE INDEX idx_users_oidc ON users (oidc_issuer, oidc_subject);
|
||||
|
||||
-- sessions --------------------------------------------------------------------
|
||||
-- Opaque bearer token stored only as a sha256 hash; the raw token lives in the
|
||||
-- HttpOnly cookie. 30-day sliding expiry (expires_at bumped on use).
|
||||
CREATE TABLE sessions (
|
||||
token_hash TEXT PRIMARY KEY, -- sha256 of the 32-byte random token
|
||||
user_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
expires_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||||
);
|
||||
CREATE INDEX idx_sessions_user ON sessions (user_id);
|
||||
|
||||
-- gardens ---------------------------------------------------------------------
|
||||
CREATE TABLE gardens (
|
||||
id INTEGER PRIMARY KEY,
|
||||
owner_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
width_cm REAL NOT NULL,
|
||||
height_cm REAL NOT NULL,
|
||||
unit_pref TEXT NOT NULL DEFAULT 'metric' CHECK (unit_pref IN ('metric', 'imperial')),
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||||
);
|
||||
CREATE INDEX idx_gardens_owner ON gardens (owner_id);
|
||||
|
||||
-- garden_shares ---------------------------------------------------------------
|
||||
-- The owner is implicit via gardens.owner_id and never has a share row.
|
||||
CREATE TABLE garden_shares (
|
||||
id INTEGER PRIMARY KEY,
|
||||
garden_id INTEGER NOT NULL REFERENCES gardens (id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL CHECK (role IN ('viewer', 'editor')),
|
||||
created_by INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
UNIQUE (garden_id, user_id)
|
||||
);
|
||||
CREATE INDEX idx_garden_shares_garden ON garden_shares (garden_id);
|
||||
CREATE INDEX idx_garden_shares_user ON garden_shares (user_id);
|
||||
|
||||
-- garden_objects --------------------------------------------------------------
|
||||
-- One polymorphic table for every placeable object. Positioned by CENTER point +
|
||||
-- rotation about center, in garden space (origin top-left, x→right, y→down).
|
||||
-- shape='polygon' and the points JSON column are reserved for post-v1; the v1
|
||||
-- editor emits only 'rect' and 'circle' (circle: width_cm = diameter).
|
||||
CREATE TABLE garden_objects (
|
||||
id INTEGER PRIMARY KEY,
|
||||
garden_id INTEGER NOT NULL REFERENCES gardens (id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL CHECK (kind IN ('bed', 'grow_bag', 'container', 'in_ground', 'tree', 'path', 'structure')),
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
shape TEXT NOT NULL DEFAULT 'rect' CHECK (shape IN ('rect', 'circle', 'polygon')),
|
||||
points TEXT, -- reserved: JSON [[x,y],...] for shape='polygon'
|
||||
x_cm REAL NOT NULL, -- center in garden space
|
||||
y_cm REAL NOT NULL,
|
||||
width_cm REAL NOT NULL,
|
||||
height_cm REAL NOT NULL,
|
||||
rotation_deg REAL NOT NULL DEFAULT 0, -- clockwise about center
|
||||
z_index INTEGER NOT NULL DEFAULT 0,
|
||||
plantable INTEGER NOT NULL DEFAULT 0 CHECK (plantable IN (0, 1)),
|
||||
color TEXT, -- optional hex override
|
||||
props TEXT, -- kind-specific extras (JSON)
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||||
);
|
||||
CREATE INDEX idx_garden_objects_garden ON garden_objects (garden_id);
|
||||
|
||||
-- plants ----------------------------------------------------------------------
|
||||
-- Catalog. owner_id NULL = built-in (seeded, read-only; clone to customize).
|
||||
-- Users see built-ins plus their own.
|
||||
CREATE TABLE plants (
|
||||
id INTEGER PRIMARY KEY,
|
||||
owner_id INTEGER REFERENCES users (id) ON DELETE CASCADE, -- NULL = built-in
|
||||
name TEXT NOT NULL,
|
||||
category TEXT NOT NULL CHECK (category IN ('vegetable', 'herb', 'flower', 'fruit', 'tree_shrub', 'cover')),
|
||||
spacing_cm REAL NOT NULL, -- mature spacing
|
||||
color TEXT NOT NULL, -- hex
|
||||
icon TEXT NOT NULL DEFAULT '', -- emoji (zero image assets in v1)
|
||||
days_to_maturity INTEGER,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||||
);
|
||||
CREATE INDEX idx_plants_owner ON plants (owner_id);
|
||||
|
||||
-- plantings ("plops") ---------------------------------------------------------
|
||||
-- A circular patch of one plant, positioned in the PARENT OBJECT's local frame
|
||||
-- (origin at object center, unrotated axes) so moving/rotating the bed moves its
|
||||
-- plants for free. count NULL = derived max(1, round(pi*r^2 / spacing_cm^2)).
|
||||
-- "Clear bed" sets removed_at; v1 lists rows where removed_at IS NULL.
|
||||
CREATE TABLE plantings (
|
||||
id INTEGER PRIMARY KEY,
|
||||
object_id INTEGER NOT NULL REFERENCES garden_objects (id) ON DELETE CASCADE,
|
||||
plant_id INTEGER NOT NULL REFERENCES plants (id) ON DELETE RESTRICT,
|
||||
x_cm REAL NOT NULL, -- center in object-local frame
|
||||
y_cm REAL NOT NULL,
|
||||
radius_cm REAL NOT NULL,
|
||||
count INTEGER, -- NULL = derived from area / spacing^2
|
||||
label TEXT,
|
||||
planted_at TEXT, -- 'YYYY-MM-DD'
|
||||
removed_at TEXT, -- 'YYYY-MM-DD'; NULL = currently planted
|
||||
version INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
|
||||
);
|
||||
CREATE INDEX idx_plantings_object ON plantings (object_id);
|
||||
CREATE INDEX idx_plantings_plant ON plantings (plant_id);
|
||||
@@ -0,0 +1,68 @@
|
||||
// Package store provides pansy's durable persistence layer: a pure-Go SQLite
|
||||
// database (modernc.org/sqlite — no cgo, so the binary stays static) with a
|
||||
// tiny embedded migration runner. Entity query methods are added per feature
|
||||
// issue; this file only handles opening and the connection pragmas.
|
||||
package store
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
_ "modernc.org/sqlite" // pure-Go driver, registered as "sqlite"
|
||||
)
|
||||
|
||||
// DB is a handle to the SQLite database backing pansy. Safe for concurrent use:
|
||||
// WAL mode allows many readers with one writer, and busy_timeout makes a
|
||||
// contended writer wait rather than fail with SQLITE_BUSY.
|
||||
type DB struct {
|
||||
sql *sql.DB
|
||||
}
|
||||
|
||||
// Open opens (creating if absent) the SQLite database at path and returns a DB.
|
||||
// The pragmas — busy_timeout, WAL journal, and foreign-key enforcement — are
|
||||
// applied per connection via the DSN so every pooled connection inherits them.
|
||||
// A path of ":memory:" yields an ephemeral in-memory database (useful in tests);
|
||||
// the pool is pinned to a single connection so all queries see the same DB.
|
||||
// The caller owns the returned DB and must Close it.
|
||||
func Open(path string) (*DB, error) {
|
||||
dsn, memory := buildDSN(path)
|
||||
sqldb, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: open %q: %w", path, err)
|
||||
}
|
||||
if memory {
|
||||
// Each new connection to a bare ":memory:" DSN gets its OWN empty database,
|
||||
// so a pooled second connection wouldn't see the migrated schema. Pin the
|
||||
// pool to one connection to keep an in-memory DB coherent.
|
||||
sqldb.SetMaxOpenConns(1)
|
||||
}
|
||||
if err := sqldb.Ping(); err != nil {
|
||||
sqldb.Close()
|
||||
return nil, fmt.Errorf("store: ping %q: %w", path, err)
|
||||
}
|
||||
return &DB{sql: sqldb}, nil
|
||||
}
|
||||
|
||||
// buildDSN turns a filesystem path (or ":memory:") into a modernc DSN carrying
|
||||
// the pragmas we want on every connection, and reports whether it is in-memory.
|
||||
// A path that already looks like a DSN (has a scheme or query) is passed through
|
||||
// untouched.
|
||||
func buildDSN(path string) (dsn string, memory bool) {
|
||||
memory = path == ":memory:" || strings.Contains(path, ":memory:") || strings.Contains(path, "mode=memory")
|
||||
if strings.HasPrefix(path, "file:") || strings.Contains(path, "?") {
|
||||
return path, memory
|
||||
}
|
||||
pragmas := url.Values{}
|
||||
pragmas.Add("_pragma", "busy_timeout(5000)")
|
||||
pragmas.Add("_pragma", "journal_mode(WAL)")
|
||||
pragmas.Add("_pragma", "foreign_keys(1)")
|
||||
return "file:" + path + "?" + pragmas.Encode(), memory
|
||||
}
|
||||
|
||||
// Close closes the underlying database.
|
||||
func (d *DB) Close() error { return d.sql.Close() }
|
||||
|
||||
// SQL exposes the underlying *sql.DB for the per-entity query files.
|
||||
func (d *DB) SQL() *sql.DB { return d.sql }
|
||||
@@ -0,0 +1,122 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// openTestDB opens a fresh file-backed DB in a temp dir and migrates it.
|
||||
func openTestDB(t *testing.T) *DB {
|
||||
t.Helper()
|
||||
db, err := Open(filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { db.Close() })
|
||||
if err := db.Migrate(context.Background()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func TestMigrateCreatesSchema(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
want := []string{
|
||||
"users", "sessions", "gardens", "garden_shares",
|
||||
"garden_objects", "plants", "plantings", "schema_migrations",
|
||||
}
|
||||
for _, table := range want {
|
||||
var name string
|
||||
err := db.SQL().QueryRow(
|
||||
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`, table,
|
||||
).Scan(&name)
|
||||
if err != nil {
|
||||
t.Errorf("expected table %q to exist: %v", table, err)
|
||||
}
|
||||
}
|
||||
|
||||
var version int
|
||||
if err := db.SQL().QueryRow(`SELECT max(version) FROM schema_migrations`).Scan(&version); err != nil {
|
||||
t.Fatalf("read schema_migrations: %v", err)
|
||||
}
|
||||
if version != 1 {
|
||||
t.Errorf("schema version = %d, want 1", version)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateIsIdempotent(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
// A second Migrate must be a no-op and leave exactly one recorded version.
|
||||
if err := db.Migrate(context.Background()); err != nil {
|
||||
t.Fatalf("second Migrate: %v", err)
|
||||
}
|
||||
var count int
|
||||
if err := db.SQL().QueryRow(`SELECT count(*) FROM schema_migrations`).Scan(&count); err != nil {
|
||||
t.Fatalf("count schema_migrations: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("schema_migrations rows = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestForeignKeysEnforced(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
// The DSN sets foreign_keys(1) per connection; a planting referencing a
|
||||
// nonexistent object must be rejected. This guards the pragma actually
|
||||
// reaching the app's pooled connections, not just the sqlite3 CLI.
|
||||
_, err := db.SQL().Exec(
|
||||
`INSERT INTO plantings (object_id, plant_id, x_cm, y_cm, radius_cm) VALUES (999, 999, 0, 0, 10)`,
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected foreign-key violation, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckConstraintRejectsBadEnum(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
// Seed a user + garden so the FK is satisfied and only the CHECK can fail.
|
||||
res, err := db.SQL().Exec(
|
||||
`INSERT INTO users (email, display_name) VALUES ('[email protected]', 'A')`)
|
||||
if err != nil {
|
||||
t.Fatalf("insert user: %v", err)
|
||||
}
|
||||
uid, _ := res.LastInsertId()
|
||||
res, err = db.SQL().Exec(
|
||||
`INSERT INTO gardens (owner_id, name, width_cm, height_cm) VALUES (?, 'G', 100, 100)`, uid)
|
||||
if err != nil {
|
||||
t.Fatalf("insert garden: %v", err)
|
||||
}
|
||||
gid, _ := res.LastInsertId()
|
||||
|
||||
// kind='invalid' violates the CHECK constraint.
|
||||
_, err = db.SQL().Exec(
|
||||
`INSERT INTO garden_objects (garden_id, kind, x_cm, y_cm, width_cm, height_cm)
|
||||
VALUES (?, 'invalid', 0, 0, 10, 10)`, gid)
|
||||
if err == nil {
|
||||
t.Fatal("expected CHECK constraint violation for bad kind, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInMemoryDBIsCoherentAcrossQueries(t *testing.T) {
|
||||
// A bare ":memory:" DSN gives each connection its own DB; Open must pin the
|
||||
// pool so the migrated schema is visible to subsequent queries.
|
||||
db, err := Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("Open(:memory:): %v", err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err := db.Migrate(context.Background()); err != nil {
|
||||
t.Fatalf("Migrate: %v", err)
|
||||
}
|
||||
var name string
|
||||
if err := db.SQL().QueryRow(
|
||||
`SELECT name FROM sqlite_master WHERE type='table' AND name='gardens'`,
|
||||
).Scan(&name); err != nil {
|
||||
t.Fatalf("in-memory schema not visible: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Package webdist embeds the production web build so pansy ships as one static
|
||||
// binary. The Makefile syncs web/dist into this package's dist/ directory before
|
||||
// `go build`; a minimal placeholder dist/index.html is committed so the module
|
||||
// builds without a web build present (the Makefile overwrites it).
|
||||
package webdist
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
//go:embed all:dist
|
||||
var embedded embed.FS
|
||||
|
||||
// Dist returns the embedded web build rooted at its top level (index.html,
|
||||
// assets/…), ready to hand to api.RegisterSPA.
|
||||
func Dist() fs.FS {
|
||||
sub, err := fs.Sub(embedded, "dist")
|
||||
if err != nil {
|
||||
// Only possible if the embed directive and this path disagree — a build-time bug.
|
||||
panic("webdist: dist subtree missing: " + err.Error())
|
||||
}
|
||||
return sub
|
||||
}
|
||||
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>pansy</title>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Placeholder shell. `make web` replaces this directory with the real Vite
|
||||
build (web/dist). Serving this file means the binary was built without a
|
||||
web build; run `make build` for the full app. -->
|
||||
<main style="font-family: system-ui, sans-serif; max-width: 40rem; margin: 4rem auto; padding: 0 1rem;">
|
||||
<h1>pansy</h1>
|
||||
<p>The web build is not embedded in this binary. Run <code>make build</code> to bundle the frontend.</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user