Go: database/sql: add NullInt16 support

Created on 7 Jul 2020  路  9Comments  路  Source: golang/go

Hey Go team!

I maintain a database code generator. I'm having trouble correctly supporting null smallint columns because the database/sql package does not have a NullInt16 type. It would look almost identical to Nullint32 and NullInt64.

// NullInt16 represents an int32 that may be null.
// NullInt16 implements the Scanner interface so
// it can be used as a scan destination, similar to NullString.
type NullInt16 struct {
    Int16 int16
    Valid bool // Valid is true if Int16 is not NULL
}

// Scan implements the Scanner interface.
func (n *NullInt16) Scan(value interface{}) error {
    if value == nil {
        n.Int16, n.Valid = 0, false
        return nil
    }
    n.Valid = true
    return convertAssign(&n.Int16, value)
}

// Value implements the driver Valuer interface.
func (n NullInt16) Value() (driver.Value, error) {
    if !n.Valid {
        return nil, nil
    }
    return int64(n.Int16), nil
}
Proposal Proposal-Accepted

Most helpful comment

Do we need NullByte for tinyint too?
(No luck for 24-bit mediumint)

All 9 comments

CC @kardianos

@kyleconroy This looks reasonable. Can you send a CL?

On a side note, these nullable wrappers would probably be a great use for generics...

Yeah, can do. A bit swamped right now, but should have it done by the end of the week

On a side note, these nullable wrappers would probably be a great use for generics...

I know! Here's a four-line replacement for the various sql.Null* types in the standard library.

    type Null(type T) struct {
        Val   T
        Valid bool // Valid is true if Val is not NULL
    }

Here's what it looks like in practice: https://go2goplay.golang.org/p/Qj8MqYWWAc3

Do we need NullByte for tinyint too?
(No luck for 24-bit mediumint)

NullByte and NullInt16 both sound good. Might as well complete the family.

Based on the discussion above, this seems like a likely accept.

No change in consensus, so accepted.

I have some spare time and like to contribute more to the Go project. May I volunteer for a CL @kyleconroy, or do you prefer to do it yourself?

Was this page helpful?
0 / 5 - 0 ratings