File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed
Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change @@ -107,3 +107,28 @@ func (j *JSONText) Unmarshal(v interface{}) error {
107107func (j JSONText ) String () string {
108108 return string (j )
109109}
110+
111+ // BitBool is an implementation of a bool for the MySQL type BIT(1).
112+ // This type allows you to avoid wasting an entire byte for MySQL's boolean type TINYINT.
113+ type BitBool bool
114+
115+ // Value implements the driver.Valuer interface,
116+ // and turns the BitBool into a bitfield (BIT(1)) for MySQL storage.
117+ func (b BitBool ) Value () (driver.Value , error ) {
118+ if b {
119+ return []byte {1 }, nil
120+ } else {
121+ return []byte {0 }, nil
122+ }
123+ }
124+
125+ // Scan implements the sql.Scanner interface,
126+ // and turns the bitfield incoming from MySQL into a BitBool
127+ func (b * BitBool ) Scan (src interface {}) error {
128+ v , ok := src .([]byte )
129+ if ! ok {
130+ return errors .New ("bad []byte type assertion" )
131+ }
132+ * b = v [0 ] == 1
133+ return nil
134+ }
Original file line number Diff line number Diff line change @@ -40,3 +40,35 @@ func TestJSONText(t *testing.T) {
4040 t .Errorf ("Was expecting invalid json to fail!" )
4141 }
4242}
43+
44+ func TestBitBool (t * testing.T ) {
45+ // Test true value
46+ var b BitBool = true
47+
48+ v , err := b .Value ()
49+ if err != nil {
50+ t .Errorf ("Cannot return error" )
51+ }
52+ err = (& b ).Scan (v )
53+ if err != nil {
54+ t .Errorf ("Was not expecting an error" )
55+ }
56+ if ! b {
57+ t .Errorf ("Was expecting the bool we sent in (true), got %b" , b )
58+ }
59+
60+ // Test false value
61+ b = false
62+
63+ v , err = b .Value ()
64+ if err != nil {
65+ t .Errorf ("Cannot return error" )
66+ }
67+ err = (& b ).Scan (v )
68+ if err != nil {
69+ t .Errorf ("Was not expecting an error" )
70+ }
71+ if b {
72+ t .Errorf ("Was expecting the bool we sent in (false), got %b" , b )
73+ }
74+ }
You can’t perform that action at this time.
0 commit comments