Path: blob/main/vendor/github.com/google/uuid/null.go
2875 views
// Copyright 2021 Google Inc. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34package uuid56import (7"bytes"8"database/sql/driver"9"encoding/json"10"fmt"11)1213var jsonNull = []byte("null")1415// NullUUID represents a UUID that may be null.16// NullUUID implements the SQL driver.Scanner interface so17// it can be used as a scan destination:18//19// var u uuid.NullUUID20// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u)21// ...22// if u.Valid {23// // use u.UUID24// } else {25// // NULL value26// }27//28type NullUUID struct {29UUID UUID30Valid bool // Valid is true if UUID is not NULL31}3233// Scan implements the SQL driver.Scanner interface.34func (nu *NullUUID) Scan(value interface{}) error {35if value == nil {36nu.UUID, nu.Valid = Nil, false37return nil38}3940err := nu.UUID.Scan(value)41if err != nil {42nu.Valid = false43return err44}4546nu.Valid = true47return nil48}4950// Value implements the driver Valuer interface.51func (nu NullUUID) Value() (driver.Value, error) {52if !nu.Valid {53return nil, nil54}55// Delegate to UUID Value function56return nu.UUID.Value()57}5859// MarshalBinary implements encoding.BinaryMarshaler.60func (nu NullUUID) MarshalBinary() ([]byte, error) {61if nu.Valid {62return nu.UUID[:], nil63}6465return []byte(nil), nil66}6768// UnmarshalBinary implements encoding.BinaryUnmarshaler.69func (nu *NullUUID) UnmarshalBinary(data []byte) error {70if len(data) != 16 {71return fmt.Errorf("invalid UUID (got %d bytes)", len(data))72}73copy(nu.UUID[:], data)74nu.Valid = true75return nil76}7778// MarshalText implements encoding.TextMarshaler.79func (nu NullUUID) MarshalText() ([]byte, error) {80if nu.Valid {81return nu.UUID.MarshalText()82}8384return jsonNull, nil85}8687// UnmarshalText implements encoding.TextUnmarshaler.88func (nu *NullUUID) UnmarshalText(data []byte) error {89id, err := ParseBytes(data)90if err != nil {91nu.Valid = false92return err93}94nu.UUID = id95nu.Valid = true96return nil97}9899// MarshalJSON implements json.Marshaler.100func (nu NullUUID) MarshalJSON() ([]byte, error) {101if nu.Valid {102return json.Marshal(nu.UUID)103}104105return jsonNull, nil106}107108// UnmarshalJSON implements json.Unmarshaler.109func (nu *NullUUID) UnmarshalJSON(data []byte) error {110if bytes.Equal(data, jsonNull) {111*nu = NullUUID{}112return nil // valid null UUID113}114err := json.Unmarshal(data, &nu.UUID)115nu.Valid = err == nil116return err117}118119120