By convention, all database queries are wrapped in a Queries layer that can be generated using the Copper CLI -
copperscaffold:queriesrockets
pkg/rockets/queries.go
funcNewQueries(queriercsql.Querier)*Queries{return&Queries{querier:querier,}}typeQueriesstruct{queriercsql.Querier}// Add methods on the Queries struct that query the database
Querier
The auto-generated Queries struct has a dependency on csql.Querier. Querier allows you to run queries safely on your database and scan results into Go structs and slices with very little boilerplate.
The example below queries the rockets table and scans the results into the rockets slice -
func(q *Queries)ListRockets(ctxcontext.Context)([]Rocket,error){constquery="SELECT * FROM rockets ORDER BY launch_date DESC"var(rockets[]Rocketerr=q.querier.Select(ctx,&rockets,query))returnrockets,err}
Similarly, the example below scans the result into a single Go struct -
Finally, if you want to execute SQL statements (such as DELETE), use the Querier.Exec method -
Transaction Middleware
The csql.TxMiddleware can be used to wrap every HTTP request in a database transaction. The transaction is automatically committed if the response code from the handler is success-like (i.e. 100-399) or rolled back for any other status code or even panics.
The middleware is added as a global middleware by default in pkg/app/handler.go.