Habib Ali Machpud
← Architecture decisions

Architecture decision

ADR-005: sqlc with explicit SQL

Generate typed Go queries while keeping schema and transaction behavior visible in SQL.

Context

Ask Habib needs a small Go data access layer that will grow into content indexing and retrieval. Query structure, PostgreSQL constraints, and transaction boundaries are important parts of the design.

Decision

Use sqlc to generate Go query methods from reviewed SQL, with pgx/v5 connection pooling. Commit generated code and check regeneration in CI with a pinned sqlc version. Goose manages explicit, embedded SQL migrations through a separate deployment job. API startup never changes the schema.

The first generated query checks that the API can access all three required content tables. The query resolves schema and privileges without scanning stored content. Its caller owns a short timeout and exposes a generic readiness response. Phase 4 is deployed in production. Acceptance covered the explicit migration job, API readiness, restricted roles, and recovery from an encrypted backup.

Alternatives considered

An ORM could reduce mapping work and provide a broad persistence abstraction. For this small PostgreSQL service, that would add another query model to understand while advanced retrieval still needs PostgreSQL-specific SQL.

Handwritten pgx calls avoid generation but require repeated row mapping and offer less compile-time help when query result shapes change. They remain useful for administrator setup and database integration checks.

Consequences

SQL stays explicit and generated types catch many mapping mistakes at build time. They do not prove query performance, correct authorization, or safe migrations. Real PostgreSQL tests cover role privileges, constraints, failed migration transactions, repeat execution, and restoration.

The generator becomes a development dependency. Changing its version requires a review of generated changes. Runtime code does not invoke sqlc or need the generator installed on the VPS. Future vector queries will use the configured Go vector type override and connection type registration.

Revisit the choice if mapping complexity becomes a demonstrated maintenance problem that another approach solves without obscuring SQL behavior.

References: sqlc with pgx, Goose provider.