Skip to content

Commit ee61cf1

Browse files
committed
docs: add documentation and examples for sqlc.narg
1 parent a22a7b7 commit ee61cf1

File tree

5 files changed

+87
-2
lines changed

5 files changed

+87
-2
lines changed

docs/howto/named_parameters.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,36 @@ SET
5656
END
5757
RETURNING *;
5858
```
59+
60+
## Nullable parameters
61+
62+
sqlc infers the nullability of any specified parameters, and often does exactly
63+
what you want. If you want finer control over the nullability of your
64+
parameters, you may use `sql.narg()` (**n**ullable arg) to override the default
65+
behavior. Using `sql.narg` tells sqlc to ignore whatever nullability it has
66+
inferred and generate a nullable parameter instead.
67+
68+
.. note::
69+
There is no nullable equivalent of the `@` syntax.
70+
71+
Here is an example that uses a single query to allow updating an author's
72+
name, bio or both.
73+
74+
```sql
75+
-- name: UpdateAuthor :one
76+
UPDATE author
77+
SET
78+
name = coalesce(sqlc.narg('name'), name),
79+
bio = coalesce(sqlc.narg('bio'), bio)
80+
WHERE id = sqlc.arg('id');
81+
```
82+
83+
The following code is generated:
84+
85+
```go
86+
type UpdateAuthorParams struct {
87+
Name sql.NullString
88+
Bio sql.NullString
89+
ID int64
90+
}
91+
```

examples/authors/mysql/query.sql

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,16 @@ ORDER BY name;
1010
INSERT INTO authors (
1111
name, bio
1212
) VALUES (
13-
?, ?
13+
?, ?
1414
);
1515

1616
/* name: DeleteAuthor :exec */
1717
DELETE FROM authors
1818
WHERE id = ?;
19+
20+
/* name: UpdateAuthor :exec */
21+
UPDATE authors
22+
SET
23+
name = coalesce(sqlc.narg('name'), name),
24+
bio = coalesce(sqlc.narg('bio'), bio)
25+
WHERE id = sqlc.arg('id');

examples/authors/mysql/query.sql.go

Lines changed: 20 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/authors/postgresql/query.sql

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,10 @@ RETURNING *;
1717
-- name: DeleteAuthor :exec
1818
DELETE FROM authors
1919
WHERE id = $1;
20+
21+
-- name: UpdateAuthor :exec
22+
UPDATE authors
23+
SET
24+
name = coalesce(sqlc.narg('name'), name),
25+
bio = coalesce(sqlc.narg('bio'), bio)
26+
WHERE id = sqlc.arg('id');

examples/authors/postgresql/query.sql.go

Lines changed: 19 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)