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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay