Skip to content

Commit 5515308

Browse files
committed
Add types.MakeBool with variadic transformer functions
This is analogous to the `MakeInt` and `MakeString` functions but for Bool.
1 parent 435b8c6 commit 5515308

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

types/bool.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,28 @@ type Bool struct {
2222
Valid bool // Valid is true if Bool is not NULL
2323
}
2424

25+
// TransformZeroBoolToNull is a transformer function that sets the Valid field to false if the Bool is zero.
26+
// This is useful when you want to convert a zero value to a NULL value in a database context.
27+
func TransformZeroBoolToNull(b *Bool) {
28+
if b.Valid && !b.Bool {
29+
b.Valid = false
30+
}
31+
}
32+
33+
// MakeBool constructs a new Bool.
34+
//
35+
// Multiple transformer functions can be given, each transforming the generated Bool to whatever is needed.
36+
// If no transformers are given, the Bool will be valid and set to the given value.
37+
func MakeBool(bi bool, transformers ...func(*Bool)) Bool {
38+
b := Bool{Bool: bi, Valid: true}
39+
40+
for _, transformer := range transformers {
41+
transformer(&b)
42+
}
43+
44+
return b
45+
}
46+
2547
// IsZero implements the json.isZeroer interface.
2648
// A Bool is considered zero if its Valid field is false regardless of its actual Bool value.
2749
func (b Bool) IsZero() bool { return !b.Valid }

types/bool_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,46 @@ import (
77
"unicode/utf8"
88
)
99

10+
func TestMakeBool(t *testing.T) {
11+
t.Parallel()
12+
13+
subtests := []struct {
14+
name string
15+
input bool
16+
transformers []func(*Bool)
17+
output Bool
18+
}{
19+
{
20+
name: "false",
21+
input: false,
22+
output: Bool{Bool: false, Valid: true},
23+
},
24+
{
25+
name: "true",
26+
input: true,
27+
output: Bool{Bool: true, Valid: true},
28+
},
29+
{
30+
name: "false-transform-zero-to-null",
31+
input: false,
32+
transformers: []func(*Bool){TransformZeroBoolToNull},
33+
output: Bool{Valid: false},
34+
},
35+
{
36+
name: "true-transform-zero-to-null",
37+
input: true,
38+
transformers: []func(*Bool){TransformZeroBoolToNull},
39+
output: Bool{Bool: true, Valid: true},
40+
},
41+
}
42+
43+
for _, st := range subtests {
44+
t.Run(st.name, func(t *testing.T) {
45+
require.Equal(t, st.output, MakeBool(st.input, st.transformers...))
46+
})
47+
}
48+
}
49+
1050
func TestBool_MarshalJSON(t *testing.T) {
1151
subtests := []struct {
1252
input Bool

0 commit comments

Comments
 (0)