I recently started dusting off my Go skills. Coming from the Java world, where JPA and Hibernate are the norm, my first instinct was to reach for an ORM. My search led me to GORM first, which seemed like the obvious choice, but then I came across sqlc and it was exactly what I was looking for. sqlc generates type-safe Go code from plain SQL, so I keep full control over my queries without having to write and maintain all the boilerplate.
All the examples in this post come from a small recipes API I built to practice: recipes, ingredients, and a many-to-many table that links them, stored in PostgreSQL.
Installation
To install sqlc you can see all the steps here: installing sqlc
If you don’t want to install it globally, you can also run it with go run, pinning the version so everyone on the project generates the same code:
go run github.com/sqlc-dev/sqlc/cmd/sqlc@v1.31.1 generateGetting Started
sqlc needs three things:
- A schema: the
CREATE TABLEstatements of your database. - The queries: plain
.sqlfiles with the queries you want to run. - A config file (
sqlc.yml) that tells sqlc where to find them and where to write the generated Go code.
This is how the project is organized:
internal/store/pg/├── schema/schema.sql # CREATE TABLE statements├── queries/│ ├── recipes.sql│ └── ingredients.sql└── db/ # generated by sqlc, never edited by handThe schema is just regular SQL:
CREATE TABLE IF NOT EXISTS ingredients ( id UUID PRIMARY KEY, name TEXT NOT NULL UNIQUE CHECK (trim(name) <> ''));
CREATE TABLE IF NOT EXISTS recipes ( id UUID PRIMARY KEY, name TEXT NOT NULL CHECK (trim(name) <> ''), description TEXT NOT NULL DEFAULT '', created_at TIMESTAMPTZ NOT NULL);
CREATE TABLE IF NOT EXISTS recipe_ingredients ( recipe_id UUID NOT NULL REFERENCES recipes (id) ON DELETE CASCADE, ingredient_id UUID NOT NULL REFERENCES ingredients (id) ON DELETE RESTRICT,3 collapsed lines
quantity TEXT NOT NULL DEFAULT '', PRIMARY KEY (recipe_id, ingredient_id));And this is a minimal sqlc.yml in the root of the project:
version: "2"sql: - engine: "postgresql" schema: "internal/store/pg/schema/schema.sql" queries: "internal/store/pg/queries" gen: go: package: "db" out: "internal/store/pg/db" sql_package: "pgx/v5"engine: the database you use:postgresql,mysqlorsqlite.schema: a file or a directory with your schema (migrations work too).queries: a file or a directory with your queries.gen.go.package: the name of the generated Go package.gen.go.out: the directory where the code is written.gen.go.sql_package: the driver to generate code for. By default it isdatabase/sql; withpgx/v5you get code that uses pgx directly.
The full reference of the config file is here: sqlc configuration
Query Annotations
Each query in the .sql files starts with a comment that gives it a name (the name of the generated Go method) and an annotation that tells sqlc what the method should return:
-- name: GetRecipe :oneSELECT * FROM recipes WHERE id = $1;:one
Returns a single row. If no row matches, the error is the driver’s “no rows” error (pgx.ErrNoRows with pgx).
-- name: GetRecipe :oneSELECT * FROM recipes WHERE id = $1;func (q *Queries) GetRecipe(ctx context.Context, id uuid.UUID) (Recipe, error):many
Returns a slice with all the rows.
-- name: GetAllRecipes :manySELECT * FROM recipes ORDER BY created_at, id;func (q *Queries) GetAllRecipes(ctx context.Context) ([]Recipe, error):exec
Runs the query and only returns the error. When a query has more than one parameter, sqlc generates a Params struct for them.
-- name: CreateRecipe :execINSERT INTO recipes (id, name, description, created_at) VALUES ($1, $2, $3, $4);type CreateRecipeParams struct { ID uuid.UUID Name string Description string CreatedAt time.Time}
func (q *Queries) CreateRecipe(ctx context.Context, arg CreateRecipeParams) error:execrows
Like :exec, but it also returns the number of affected rows. This is very handy for updates and deletes, where 0 means the row didn’t exist:
-- name: DeleteRecipe :execrowsDELETE FROM recipes WHERE id = $1;func (q *Queries) DeleteRecipe(ctx context.Context, id uuid.UUID) (int64, error)n, err := r.q.DeleteRecipe(ctx, id)if err != nil { return err}if n == 0 { return domain.ErrNotFound}There are more annotations, like :execresult, :copyfrom or :batchexec, you can see all of them here: query annotations
Named Parameters and sqlc.embed
Two macros I found really useful:
sqlc.arg(name)gives a parameter a proper name instead of$1, so the generated method has a meaningful argument name.sqlc.embed(table)puts the whole row of a joined table inside the result as its own struct, instead of flattening all its columns.
-- name: SearchRecipesByName :manySELECT * FROM recipesWHERE name ILIKE '%' || sqlc.arg(query)::text || '%'ORDER BY created_at, id;
-- name: GetRecipeIngredientDetails :manySELECT sqlc.embed(ingredients), recipe_ingredients.quantityFROM recipe_ingredientsJOIN ingredients ON ingredients.id = recipe_ingredients.ingredient_idWHERE recipe_ingredients.recipe_id = $1;func (q *Queries) SearchRecipesByName(ctx context.Context, query string) ([]Recipe, error)
type GetRecipeIngredientDetailsRow struct { Ingredient Ingredient Quantity string}sqlc generate
Once the config and the queries are in place, run:
sqlc generateIf everything is fine, the command prints nothing. If a query references a column or a table that doesn’t exist, it fails and tells you where, so you catch the error at generation time instead of at runtime.
The output is three kinds of files in the out directory:
internal/store/pg/db/├── db.go # the Queries struct, the DBTX interface and New()├── models.go # one struct per table├── recipes.sql.go # one method per query in recipes.sql└── ingredients.sql.go # one method per query in ingredients.sqlmodels.go has a struct for each table:
// Code generated by sqlc. DO NOT EDIT.
type Recipe struct { ID uuid.UUID Name string Description string CreatedAt time.Time}And each query becomes a method with all the scanning code you would otherwise write by hand:
const getRecipe = `-- name: GetRecipe :oneSELECT id, name, description, created_at FROM recipes WHERE id = $1`
func (q *Queries) GetRecipe(ctx context.Context, id uuid.UUID) (Recipe, error) { row := q.db.QueryRow(ctx, getRecipe, id) var i Recipe err := row.Scan( &i.ID, &i.Name, &i.Description, &i.CreatedAt, ) return i, err}Notice that sqlc expands SELECT * into the explicit list of columns, so adding a column to the table later doesn’t silently break the scan.
To use it, you only need to pass a connection (or a pool) to db.New:
pool, err := pgxpool.New(ctx, url)if err != nil { return err}q := db.New(pool)
recipe, err := q.GetRecipe(ctx, id)Override Types
By default sqlc picks the Go type for each database type. With pgx/v5, a UUID column becomes pgtype.UUID and a TIMESTAMPTZ column becomes pgtype.Timestamptz, which are not the types I want to use in the rest of the application. With overrides you can tell sqlc which Go type to use:
gen: go: package: "db" out: "internal/store/pg/db" sql_package: "pgx/v5" overrides: - db_type: "timestamptz" go_type: "time.Time" - db_type: "uuid" go_type: import: "github.com/google/uuid" type: "UUID"Before and after:
// without overridestype Recipe struct { ID pgtype.UUID Name string Description string CreatedAt pgtype.Timestamptz}
// with overridestype Recipe struct { ID uuid.UUID Name string Description string CreatedAt time.Time}db_typeoverrides every column of that database type.columnoverrides a single column (table.column).go_typecan be a simple string for the standard library (time.Time) or an object withimportandtypefor external packages.
The column form is useful when the database doesn’t have a proper type. In SQLite the ids are TEXT, so I override each id column one by one:
overrides: - column: "recipes.id" go_type: { import: "github.com/google/uuid", type: "UUID" } - column: "recipe_ingredients.recipe_id" go_type: { import: "github.com/google/uuid", type: "UUID" }More details here: overriding types
Transactions
sqlc doesn’t start transactions for you, but it makes them easy. The generated Queries has a WithTx method that returns a copy of it bound to a transaction:
func (q *Queries) WithTx(tx pgx.Tx) *Queries { return &Queries{ db: tx, }}So the flow is: begin the transaction with the driver, run the queries through q.WithTx(tx), and commit or roll back. In the recipes API, creating a recipe means inserting the recipe and all its ingredients, so they must be saved together or not at all. I wrapped that in a small helper:
// inTx runs fn in a transaction so a recipe and its ingredient rows are saved together or not at all.func (r *RecipeRepository) inTx(ctx context.Context, fn func(q *db.Queries) error) error { tx, err := r.pool.Begin(ctx) if err != nil { return err } defer tx.Rollback(ctx) // no-op after Commit if err := fn(r.q.WithTx(tx)); err != nil { return err } return tx.Commit(ctx)}Beginstarts the transaction.defer tx.Rollbackmakes sure the transaction is rolled back if anything fails or panics. After a successfulCommitit does nothing.Commitsaves everything.
And using it:
func (r *RecipeRepository) Create(ctx context.Context, rec domain.Recipe) error { return r.inTx(ctx, func(q *db.Queries) error { err := q.CreateRecipe(ctx, db.CreateRecipeParams{ ID: rec.ID, Name: rec.Name, Description: rec.Description, CreatedAt: rec.CreatedAt, }) if err != nil { return err } for _, ri := range rec.Ingredients { err := q.AddRecipeIngredient(ctx, db.AddRecipeIngredientParams{ RecipeID: rec.ID, IngredientID: ri.IngredientID,9 collapsed lines
Quantity: ri.Quantity, }) if err != nil { return err // the recipe insert is rolled back too } } return nil })}More details here: using transactions
Rules
sqlc vet checks your queries against a set of rules, and fails if any query breaks one. It’s a nice way to catch problems in CI before they reach production. Rules are written in CEL (Common Expression Language): if the expression is true, the rule fails for that query.
You declare the rules at the top level of sqlc.yml and enable them per sql entry:
version: "2"sql: - engine: "postgresql" schema: "internal/store/pg/schema/schema.sql" queries: "internal/store/pg/queries" database: uri: "postgres://recipes:recipes@localhost:5432/recipes_vet?sslmode=disable" rules: - sqlc/db-prepare - postgresql-no-seq-scan gen: go: # ...
rules:5 collapsed lines
- name: postgresql-no-seq-scan message: "query plan reads the whole table (Seq Scan)" rule: | postgresql.explain.plan.node_type == 'Seq Scan' || postgresql.explain.plan.plans.exists(p, p.node_type == 'Seq Scan')Built-in Rules
sqlc/db-prepare: prepares every query against a real database, which catches errors that the static analysis can miss. It needs thedatabase.uri.
Custom Rules
Each rule receives information about the query (query.sql, query.name, query.cmd, query.params…) and you can write any expression over it. For example, a rule that doesn’t allow DELETE without a WHERE:
rules: - name: no-delete-without-where message: "don't delete all the rows" rule: | query.sql.startsWith("DELETE") && !query.sql.contains("WHERE")When the config has a database connection, sqlc can also run EXPLAIN on each query and expose the plan as postgresql.explain. That’s what postgresql-no-seq-scan uses: it fails when PostgreSQL has to read the whole table instead of using an index.
In the recipes API I have a query that breaks it on purpose. A pattern that starts with % can’t use an index:
-- name: SearchRecipesByName :manySELECT * FROM recipesWHERE name ILIKE '%' || sqlc.arg(query)::text || '%'ORDER BY created_at, id;$ sqlc vetinternal/store/pg/queries/recipes.sql: SearchRecipesByName: postgresql-no-seq-scan: query plan reads the whole table (Seq Scan)Disabling a Rule for a Query
Sometimes reading the whole table is exactly what you want, like listing every ingredient. You can disable a rule for a single query with a @sqlc-vet-disable comment:
-- name: GetAllIngredients :many-- Lists every row on purpose, so the Seq Scan is expected.-- @sqlc-vet-disable postgresql-no-seq-scanSELECT * FROM ingredients;More details here: linting queries
Conclusion
sqlc gives me the best of both worlds: I write the SQL I want, and I get type-safe Go code without writing a single Scan by hand. If you come from an ORM like I did, it takes a little time to get used to writing every query yourself, but in exchange you always know exactly what runs against your database.
You can find the full code of the examples here: recipes-api