Documentation
¶
Overview ¶
Lesson 08: sqlx, database/sql with the boilerplate removed.
github.com/jmoiron/sqlx wraps database/sql (sqlx.DB embeds *sql.DB, so everything from lesson 02 still works) and adds:
- struct scanning via `db:"column"` tags: Get (one row), Select (many rows), StructScan
- named parameters: NamedExec / NamedQuery with :field placeholders bound from a struct or map
- sqlx.In: expands a slice into IN (?, ?, ?) because database/sql cannot bind a slice
- Rebind: rewrites ? placeholders for the target driver ($1, $2 for PostgreSQL)
Compare with lesson 02: there we wrote Scan(&t.ID, &t.ProjectID, ...) and a for rows.Next() loop by hand, in the right column order, for every query. With sqlx, adding a column means adding a struct field.
Rules and gotchas:
- Column names must map to struct fields; an unmapped column is an error ("missing destination name"). Select only what the struct has, or add `db:"-"` / extra fields.
- Without tags sqlx lower-cases field names (AssigneeID -> assigneeid), so always tag.
- Select loads ALL rows into memory. For huge results iterate with Queryx + StructScan.
- sqlx is still runtime-checked: a typo in SQL or a tag is found when the query runs.
- sqlx.In returns a query with ? marks; call db.Rebind(query) before running it so it works on PostgreSQL too. An EMPTY slice makes sqlx.In return an error, so guard it.
In industry: sqlx is a very common middle ground. You still write plain SQL (full control, easy to optimise) but skip repetitive scanning code. Teams that want compile-time checked queries move on to sqlc (lesson 09).