Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Add more examples to updating rows #1499

Merged
merged 1 commit into from Mar 19, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
57 changes: 52 additions & 5 deletions docs/howto/update.md
Expand Up @@ -5,12 +5,53 @@ CREATE TABLE authors (
id SERIAL PRIMARY KEY,
bio text NOT NULL
);
```

-- name: UpdateAuthor :exec
UPDATE authors SET bio = $2
WHERE id = $1;
## Single parameter

If your query has a single parameter, your Go method will also have a single
parameter.

```sql
-- name: UpdateAuthorBios :exec
UPDATE authors SET bio = $1;
```

```go
package db

import (
"context"
"database/sql"
)

type DBTX interface {
ExecContext(context.Context, string, ...interface{}) error
}

func New(db DBTX) *Queries {
return &Queries{db: db}
}

type Queries struct {
db DBTX
}

const updateAuthorBios = `-- name: UpdateAuthorBios :exec
UPDATE authors SET bio = $1
`

func (q *Queries) UpdateAuthorBios(ctx context.Context, bio string) error {
_, err := q.db.ExecContext(ctx, updateAuthorBios, bio)
return err
}
```

## Multiple parameters

If your query has more than one parameter, your Go method will accept a
`Params` struct.

```go
package db

Expand All @@ -36,8 +77,14 @@ UPDATE authors SET bio = $2
WHERE id = $1
`

func (q *Queries) UpdateAuthor(ctx context.Context, id int, bio string) error {
_, err := q.db.ExecContext(ctx, updateAuthor, id, bio)
type UpdateAuthorParams struct {
ID int32
Bio string
}

func (q *Queries) UpdateAuthor(ctx context.Context, arg UpdateAuthorParams) error {
_, err := q.db.ExecContext(ctx, updateAuthor, arg.ID, arg.Bio)
return err
}
```