From a7e8750d5b83f390afec2333350a7293917dee12 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Mon, 13 Apr 2026 03:12:16 +0700 Subject: lib/uuid: return nil if ID is zero Per RFC 9562 Section 5.9, A Nil UUID value can be useful to communicate the absence of any other UUID value in situations that otherwise require or use a 128-bit UUID. A Nil UUID can express the concept "no such value here". Thus, it is reserved for such use as needed for implementation-specific situations. In case of SQL, the Value method should return nil if ID is zero. --- lib/uuidv7/uuid.go | 12 ++++++++++++ lib/uuidv7/uuid_test.go | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/uuidv7/uuid.go b/lib/uuidv7/uuid.go index b1a1165a..65479e24 100644 --- a/lib/uuidv7/uuid.go +++ b/lib/uuidv7/uuid.go @@ -112,13 +112,21 @@ func (id UUID) IsZero() bool { } // MarshalBinary encodes the id to binary for [encoding/gob]. +// It will return nil if id is zero. func (id UUID) MarshalBinary() (data []byte, err error) { + if id.IsZero() { + return nil, nil + } data = id.Bytes() return data, nil } // MarshalText encodes the id to JSON for [encoding/json]. +// It will return nil if id is zero. func (id UUID) MarshalText() (data []byte, err error) { + if id.IsZero() { + return nil, nil + } v := id.String() return []byte(v), nil } @@ -234,7 +242,11 @@ func (id *UUID) Time() time.Time { // Value returns the value for sending it to the database. // This method implements the [driver.Valuer] interface. +// It will return nil if id is zero, per RFC 9562 section 5.9. func (id UUID) Value() (v driver.Value, err error) { + if id.IsZero() { + return nil, nil + } v = id.String() return v, nil } diff --git a/lib/uuidv7/uuid_test.go b/lib/uuidv7/uuid_test.go index 4972a70c..c47806d8 100644 --- a/lib/uuidv7/uuid_test.go +++ b/lib/uuidv7/uuid_test.go @@ -156,7 +156,7 @@ func TestUUID_Value(t *testing.T) { if err != nil { t.Fatal(err) } - test.Assert(t, `ValueZero`, v.(string), `00000000-0000-0000-0000-000000000000`) + test.Assert(t, `ValueZero`, nil, v) err = id.Scan([]byte(`019CD2F8-1AE3-774E-BFFF-FFFFFFFFFFFF`)) if err != nil { -- cgit v1.3