user10714010
user10714010

Reputation: 935

Is there something like sql.NullJson akin to sql.NullString in golang?

I am querying from postgres using golang, one of the field contains json that can sometimes be NULL

Like this

row := db.QueryRow(
    "select my_string, my_json from my_table where my_string = $1",
   my_id)


var my_string sql.NullString
var myjson MyJsonStruct
err := row.Scan(&my_string2, &myjson)

But I am getting

sql: Scan error on column index 2, name "my_json": unsupported Scan, storing driver.Value type <nil> into type *main.MyJsonStruct

I checked https://godoc.org/database/sql but didn't find sql.NullJson What is a go way of dealing with this situation?

Upvotes: 1

Views: 322

Answers (1)

yogy fresta rahmawan
yogy fresta rahmawan

Reputation: 227

No, there is no sql.json. I think the best way to dealing with json column in db is to implement valuer and scanner. so something like this :

// Scan implements database/sql.Scanner interface
func (m *MyJsonStruct) Scan(src interface{}) error {
    if src == nil {
        return nil
    }
    data, ok := src.([]byte)
    if !ok {
        return errors.New("type assertion to []byte failed")
    }
    var myJsonStruct MyJsonStruct
    if err := json.Unmarshal(data, &myJsonStruct); err != nil {
        return fmt.Errorf("unmarshal myJsonStruct: %w", err)
    }
    *m = myJsonStruct
    return nil
}

// Value implements database/sql/driver.Valuer interface
func (m MyJsonStruct) Value() (driver.Value, error) {
    data, err := json.Marshal(m)
    if err != nil {
        return nil, fmt.Errorf("marshal myJsonStruct: %w", err)
    }
    return data, nil
}

Upvotes: 3

Related Questions