09sqlc

command
v0.0.0-...-610d9af Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: GPL-3.0 Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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:

  1. edit schema.sql (or migrations) and query.sql
  2. run `make sqlc` (this repo pins sqlc as a Go tool: `go tool sqlc generate -f ...`)
  3. 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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL