3

Go's zero value for a bool type is false. Postgres supports an undefined BOOL type, represented as NULL. This leads to problems when trying to fetch a BOOL value from Postgres in Go:

rows,err := db.Query("SELECT UNNEST('{TRUE,FALSE,NULL}'::BOOL[])");
if err != nil {
    log.Fatal(err)
}
for rows.Next() {
    var value bool
    if err := rows.Scan(&value); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Value: %t\n",value);
}

Output:

Value: true  
Value: false  
2014/11/17 09:34:26 sql: Scan error on column index 0: sql/driver: couldn't convert <nil> (<nil>) into type bool

What's the most idiomatic way around this problem? The two solutions I have imagined are neither very attractive:

  1. Don't use Go's bool type. Instead I would probably use a string, and do my own conversion which accounts for nil
  2. Always make sure BOOLs are either TRUE or FALSE in Postgres by using COALESCE() or some other means.

3 Answers 3

8

See http://golang.org/pkg/database/sql/#NullBool in the standard library.

NullBool represents a bool that may be null. NullBool implements the Scanner interface so it can be used as a scan destination, similar to NullString.

Sign up to request clarification or add additional context in comments.

Comments

5

My preference is using a pointer:

for rows.Next() {
    var value *bool

    if err := rows.Scan(&value); err != nil {
        log.Fatal(err)
    }

    if value == nil {
        // Handle nil
    }

    fmt.Printf("Value: %t\n", *value);
}

Comments

0

In case of using SQL + graphQL (gqlgen) my preference is using pointers as well.

Why?

Because when I generate a schema it will have pointers on the output and this is much easy to connect with a relevant struct which contains pointers (which handle DB operations).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.