csql package provides a thin, productive layer over database/sql. Queries are parameterized and scanned into plain structs, so there is no ORM to learn and no query language beyond SQL itself.
The Queries Struct
Each package that talks to the database keeps its queries in aQueries struct. You may scaffold one using the CLI:
pkg/rockets/queries.go and adds it to the package’s wire module:
pkg/rockets/queries.go
Models
Rows are scanned into plain structs whosedb: tags map columns to fields. The examples on this page use the following model; to learn more about defining models, tag rules, and custom column types, see Models:
pkg/rockets/models.go
Reading Rows
TheGet method scans a single row into a struct, while Select scans multiple rows into a slice. Rather than writing SELECT * or a hand-maintained column list, render the columns from the model’s db: tags with qb.Columns:
You should always write
? placeholders, regardless of your database. Copper will automatically rebind them to your dialect’s native style, such as $1 for Postgres, before executing the query.Writing Rows
Exec runs INSERT, UPDATE, and DELETE statements:
Handling Missing Rows
Get returns sql.ErrNoRows when nothing matches. It is common to alias it as a package sentinel so that callers do not need to import database/sql:
pkg/rockets/models.go
IN Queries
To pass a slice into anIN (?) clause, use WithIn():
? into one placeholder per element of the slice.
Connections and Drivers
Copper opens the connection from your config and closes it on shutdown:config/dev.toml
copper create sets this up for you in cmd/app/wire.go:
max_open_connections, max_idle_connections, and conn_max_lifetime_mins under [csql]. All of the available keys are listed in the Configuration Reference.