Documentation
¶
Overview ¶
Lesson 09: sqlc, compile-time checked SQL.
sqlc flips the usual ORM idea: YOU write plain SQL in query.sql, and sqlc GENERATES the Go code (structs, params, methods) by reading your schema and queries.
sqlc.yaml + ../sql/schema.sql + query.sql -> `go tool sqlc generate` -> db/*.go
What you get:
- Compile-time safety: a wrong column or table name fails at GENERATE time, and a changed column type breaks the Go build instead of production.
- No hand-written Scan code, no reflection at runtime, and no performance cost over database/sql: the generated methods call database/sql directly.
- Query annotations choose the Go signature: :one -> (T, error) :many -> ([]T, error) :exec -> error :execrows -> (int64, error)
- sqlc.narg('x') makes a parameter nullable so you can write optional filters.
- db.New(sqlDB) works with *sql.DB or *sql.Tx (anything implementing DBTX), and q.WithTx(tx) rebinds the same Queries to a transaction.
Workflow:
- edit schema.sql (or migrations) and query.sql
- run `make sqlc` (this repo pins sqlc as a Go tool: `go tool sqlc generate -f ...`)
- COMMIT the generated db/ folder: builds should not need sqlc installed, and diffs show exactly how a query change altered the code.
Gotchas:
- Never edit generated files; change the SQL and regenerate.
- SQLite is loosely typed, so sqlc maps every INTEGER to int64 and nullable columns to sql.NullString / sql.NullInt64. PostgreSQL gives richer types (and pgx integration).
- Dynamic queries (optional filters, variable column lists) are sqlc's weak spot. The sqlc.narg pattern below covers filters; for truly dynamic SQL use a query builder.
In industry: sqlc is very popular for Go services that want raw-SQL control with type safety. Typical layout: one sqlc.yaml per service, queries grouped by table in several .sql files, generated package named `db` or `sqlcgen`, wrapped by a thin repository/store layer.