|
| 1 | +# Query Annotations |
| 2 | + |
| 3 | +sqlc requires each query to have a small comment indicating the name and |
| 4 | +command. The format of this comment is as follows: |
| 5 | + |
| 6 | +```sql |
| 7 | +-- name: <name> <command> |
| 8 | +``` |
| 9 | + |
| 10 | +## Commands |
| 11 | + |
| 12 | +sqlc supports four types of query commands. |
| 13 | + |
| 14 | +### `:many` |
| 15 | + |
| 16 | +The generated method will return a slice of records via |
| 17 | +[QueryContext](https://golang.org/pkg/database/sql/#DB.QueryContext). |
| 18 | + |
| 19 | +```sql |
| 20 | +-- name: ListAuthors :many |
| 21 | +SELECT * FROM authors |
| 22 | +ORDER BY name; |
| 23 | +``` |
| 24 | + |
| 25 | +```go |
| 26 | +func (q *Queries) ListAuthors(ctx context.Context) ([]Author, error) { |
| 27 | + rows, err := q.db.QueryContext(ctx, listAuthors) |
| 28 | + // ... |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +### `:one` |
| 33 | + |
| 34 | +The generated method will return a single record via |
| 35 | +[QueryRowContext](https://golang.org/pkg/database/sql/#DB.QueryRowContext). |
| 36 | + |
| 37 | +```sql |
| 38 | +-- name: GetAuthor :one |
| 39 | +SELECT * FROM authors |
| 40 | +WHERE id = $1 LIMIT 1; |
| 41 | +``` |
| 42 | + |
| 43 | +```go |
| 44 | +func (q *Queries) GetAuthor(ctx context.Context, id int64) (Author, error) { |
| 45 | + row := q.db.QueryRowContext(ctx, getAuthor, id) |
| 46 | + // ... |
| 47 | +} |
| 48 | +``` |
| 49 | + |
| 50 | +### `:exec` |
| 51 | + |
| 52 | +The generated method will return the error from |
| 53 | +[ExecContext](https://golang.org/pkg/database/sql/#DB.ExecContext). |
| 54 | + |
| 55 | +```sql |
| 56 | +-- name: DeleteAuthor :exec |
| 57 | +DELETE FROM authors |
| 58 | +WHERE id = $1; |
| 59 | +``` |
| 60 | + |
| 61 | +```go |
| 62 | +func (q *Queries) DeleteAuthor(ctx context.Context, id int64) error { |
| 63 | + _, err := q.db.ExecContext(ctx, deleteAuthor, id) |
| 64 | + return err |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +### `:execrows` |
| 69 | + |
| 70 | +The generated method will return the number of affected rows from the |
| 71 | +[result](https://golang.org/pkg/database/sql/#Result) returned by |
| 72 | +[ExecContext](https://golang.org/pkg/database/sql/#DB.ExecContext). |
| 73 | + |
| 74 | +```sql |
| 75 | +-- name: DeleteAllAuthors :execrows |
| 76 | +DELETE FROM authors; |
| 77 | +``` |
| 78 | + |
| 79 | +```go |
| 80 | +func (q *Queries) DeleteAllAuthors(ctx context.Context) (int64, error) { |
| 81 | + _, err := q.db.ExecContext(ctx, deleteAllAuthors) |
| 82 | + // ... |
| 83 | +} |
| 84 | +``` |
0 commit comments