DEV Community

Alexandru Bucur
Alexandru Bucur

Posted on • Originally published at alexandrubucur.com on

Simple UUID wrapper for MySQL in Go that covers UUID to BIN conversion

Here's a quick snippet you can use to create a custom type that maps an UUID to a Binary(16) representation in MySQL.

I assume this is not present in gofrs/uuid since it's database specific, but having NullUUID available is an easy 'inspiration' opportunity ;).

import (
    "database/sql/driver"

    "github.com/gofrs/uuid/v5"
)

type NullBinaryUUID struct {
    UUID  uuid.UUID
    Valid bool // Valid is true if UUID is not NULL
}

// Value implements the driver.Valuer interface.
func (u NullBinaryUUID) Value() (driver.Value, error) {
    if !u.Valid {
        return nil, nil
    }

    // Delegate to UUID Value function
    return u.UUID.Bytes(), nil
}

// Scan implements the sql.Scanner interface.
func (u *NullBinaryUUID) Scan(src interface{}) error {
    if src == nil {
        u.UUID, u.Valid = uuid.UUID{}, false
        return nil
    }

    // Delegate to UUID Scan function
    u.Valid = true
    return u.UUID.Scan(src)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)