Skip to main content
Copper’s 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 a Queries struct. You may scaffold one using the CLI:
This creates pkg/rockets/queries.go and adds it to the package’s wire module:
pkg/rockets/queries.go

Models

Rows are scanned into plain structs whose db: 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

The Get 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 an IN (?) clause, use WithIn():
Copper expands the single ? 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
The database driver is blank-imported by your application rather than by Copper. copper create sets this up for you in cmd/app/wire.go:
The pool defaults to 25 open connections, 25 idle connections, and a 5-minute connection lifetime. If you would like to tune these, set max_open_connections, max_idle_connections, and conn_max_lifetime_mins under [csql]. All of the available keys are listed in the Configuration Reference.

Next

Now that you can read and write rows, you may want to learn how Copper wraps mutating requests in automatic Transactions, or let Query Builder write your column lists for you.