# Go + PostgreSQL (pgx & sqlc) + React — AI Agent Guidelines & Architecture Rules

> High-throughput systems architecture rules for Go (Golang), pgxpool connection management, sqlc type-safe query generation, and React web dashboards.
> Technologies: Go, PostgreSQL, React, Docker, TypeScript

---

## AGENTS.md
```markdown
# Project Architecture & Guidelines (Go + PostgreSQL + React)

## 1. System Architecture
- **Backend Language**: Go (Golang 1.22+).
- **Database Driver**: `pgx/v5` with `pgxpool` connection pooling.
- **SQL Query Compilation**: `sqlc` for compile-time type-safe Go struct and query generation.
- **HTTP Framework**: Standard library `net/http` with `chi` or `echo` router.
- **Frontend Client**: React + TypeScript Single Page Application (SPA).

## 2. PostgreSQL Connection Pool Management (pgxpool)
- Configure `pgxpool.Config` during application startup:
  ```go
  config, err := pgxpool.ParseConfig(databaseURL)
  if err != nil {
      log.Fatalf("Unable to parse DB URL: %v", err)
  }

  config.MaxConns = 25
  config.MinConns = 5
  config.MaxConnLifetime = 1 * time.Hour
  config.MaxConnIdleTime = 15 * time.Minute
  config.HealthCheckPeriod = 1 * time.Minute

  pool, err := pgxpool.NewWithConfig(context.Background(), config)
  if err != nil {
      log.Fatalf("Unable to create connection pool: %v", err)
  }
  defer pool.Close()
  ```
- Always propagate `context.Context` (with timeouts/deadlines) into all database query calls (`pool.Query(ctx, ...)`).

## 3. SQL & Schema Rules (sqlc)
- Write plain SQL files in `sql/queries/` and DDL migrations in `sql/schema/`.
- Run `sqlc generate` to compile SQL into type-safe Go code. NEVER write manual string concatenation queries.
- Migrations: Manage database versions using `golang-migrate` or `goose`.

## 4. Layer Organization
- `cmd/server/main.go`: Application entrypoint, configuration parsing, dependency wiring, graceful shutdown.
- `internal/db/`: Generated sqlc models and database queries.
- `internal/api/`: HTTP route handlers, middleware, request decoding, response serialization.
- `internal/service/`: Business domain logic and transactional boundaries.
- `frontend/`: React SPA source code.

## 5. Common Pitfalls to Avoid
- ❌ Forgetting `rows.Close()` when iterating over raw query results.
- ❌ Ignoring context cancellation: If an HTTP client disconnects, pass `r.Context()` to cancel active database queries immediately.
- ❌ Global Database Handles: Inject `*pgxpool.Pool` or `*db.Queries` into handler structs via constructor functions.

## 6. Testing Conventions
- Use Go's built-in `testing` package with `testify/assert` for readable assertions; avoid heavier frameworks unless the team already standardizes on one.
- Spin up an ephemeral Postgres instance per test run with `testcontainers-go` rather than mocking `pgx` — sqlc-generated queries should be verified against a real schema.
- Table-driven tests (`[]struct{ name string; input ...; want ... }`) are the idiomatic Go pattern; use them for handler and service logic.
- Run `go test -race ./...` in CI to catch data races in goroutines handling concurrent requests.

## 7. Git Workflow & PR Conventions
- Conventional Commits (`feat:`, `fix:`, `refactor:`) scoped by package, e.g. `fix(internal/api): handle nil pointer on empty query result`.
- Regenerate and commit `sqlc generate` output in the same PR as any `sql/queries/` change — never let generated code drift from source SQL.
- Require `go vet ./...`, `go test -race ./...`, and `golangci-lint run` green before merge.
- Squash-merge; keep `main` bisectable for `go test` regression hunting.
```

---

## CLAUDE.md
```markdown
# CLAUDE.md — Go + PostgreSQL + React

Refer to @AGENTS.md for complete Go connection pooling and sqlc guidelines.

## Common Commands
- `go run ./cmd/server` - Run Go API server locally
- `go test -v ./...` - Run all Go test packages
- `sqlc generate` - Recompile SQL queries into Go code
- `migrate -path sql/schema -database "$DATABASE_URL" up` - Apply migrations

## Claude Specific Directives
- When writing Go code, always accept `context.Context` as the first parameter in database and service methods.
- Handle all Go errors explicitly with `if err != nil`.
```

---

## .cursor/rules/stack.mdc
```markdown
---
description: Go + PostgreSQL (pgx & sqlc) + React architecture rules
globs: ["**/*.go", "frontend/**/*.tsx"]
alwaysApply: true
---

# Go + PostgreSQL (pgx & sqlc) + React

- Go 1.22+, `pgx/v5` with `pgxpool`, `sqlc`-generated queries, React + TypeScript SPA frontend.
- `pgxpool.Config` with explicit `MaxConns`, `MinConns`, `MaxConnLifetime`, `HealthCheckPeriod` — never rely on defaults in production.
- Always propagate `context.Context` with timeouts into every database call; cancel on client disconnect via `r.Context()`.
- Write SQL in `sql/queries/`, run `sqlc generate` to compile typed Go code. Never hand-write string-concatenated queries.
- `internal/db/` (generated queries), `internal/api/` (HTTP layer), `internal/service/` (business logic) — keep layers separate.
- Always `defer rows.Close()` when iterating raw query results.
- Inject `*pgxpool.Pool`/`*db.Queries` via constructors — no global database handles.
- Explicit `if err != nil` on every fallible call; no swallowed errors.
```

---

## Architecture Overview & Best Practices
## Architecture Overview

Production conventions for high-throughput, low-latency concurrent systems with **Go (Golang)**, **pgxpool**, **sqlc**, and **React**.

### Verified Real-World Adoption

This exact architecture powers massive monitoring and messaging systems including **Grafana**, **Mattermost**, **Lago**, and **PocketBase**.

### Key Architectural Nuances

- **Compile-Time Type Safety**: `sqlc` validates SQL queries against actual PostgreSQL schema at build time.
- **Context-Aware Query Execution**: Automatically cancels long-running database queries if clients drop HTTP connections.