From c6bb9e1d94a82e71dfd7ff279aa6cea7c52779bb Mon Sep 17 00:00:00 2001 From: Peter Bourgon Date: Tue, 22 Sep 2020 23:13:54 +0200 Subject: [PATCH] Update Value docs re: zero-value behavior (#60) --- ulid.go | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/ulid.go b/ulid.go index adc8713..9ae2293 100644 --- a/ulid.go +++ b/ulid.go @@ -469,19 +469,38 @@ func (id *ULID) Scan(src interface{}) error { return ErrScanValue } -// Value implements the sql/driver.Valuer interface. This returns the value -// represented as a byte slice. If instead a string is desirable, a wrapper -// type can be created that calls String(). +// Value implements the sql/driver.Valuer interface, returning the ULID as a +// slice of bytes, by invoking MarshalBinary. If your use case requires a string +// representation instead, you can create a wrapper type that calls String() +// instead. // -// // stringValuer wraps a ULID as a string-based driver.Valuer. -// type stringValuer ULID +// type stringValuer ulid.ULID // -// func (id stringValuer) Value() (driver.Value, error) { -// return ULID(id).String(), nil -// } +// func (v stringValuer) Value() (driver.Value, error) { +// return ulid.ULID(v).String(), nil +// } +// +// // Example usage. +// db.Exec("...", stringValuer(id)) +// +// All valid ULIDs, including zero-value ULIDs, return a valid Value with a nil +// error. If your use case requires zero-value ULIDs to return a non-nil error, +// you can create a wrapper type that special-cases this behavior. +// +// var zeroValueULID ulid.ULID +// +// type invalidZeroValuer ulid.ULID +// +// func (v invalidZeroValuer) Value() (driver.Value, error) { +// if ulid.ULID(v).Compare(zeroValueULID) == 0 { +// return nil, fmt.Errorf("zero value") +// } +// return ulid.ULID(v).Value() +// } +// +// // Example usage. +// db.Exec("...", invalidZeroValuer(id)) // -// // Example usage. -// db.Exec("...", stringValuer(id)) func (id ULID) Value() (driver.Value, error) { return id.MarshalBinary() }