Matthias Andreas Benkard | 832a54e | 2019-01-29 09:27:38 +0100 | [diff] [blame^] | 1 | // Copyright 2015 Google Inc. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package uuid |
| 6 | |
| 7 | import ( |
| 8 | "database/sql/driver" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | ) |
| 12 | |
| 13 | // Scan implements sql.Scanner so UUIDs can be read from databases transparently |
| 14 | // Currently, database types that map to string and []byte are supported. Please |
| 15 | // consult database-specific driver documentation for matching types. |
| 16 | func (uuid *UUID) Scan(src interface{}) error { |
| 17 | switch src.(type) { |
| 18 | case string: |
| 19 | // if an empty UUID comes from a table, we return a null UUID |
| 20 | if src.(string) == "" { |
| 21 | return nil |
| 22 | } |
| 23 | |
| 24 | // see uuid.Parse for required string format |
| 25 | parsed := Parse(src.(string)) |
| 26 | |
| 27 | if parsed == nil { |
| 28 | return errors.New("Scan: invalid UUID format") |
| 29 | } |
| 30 | |
| 31 | *uuid = parsed |
| 32 | case []byte: |
| 33 | b := src.([]byte) |
| 34 | |
| 35 | // if an empty UUID comes from a table, we return a null UUID |
| 36 | if len(b) == 0 { |
| 37 | return nil |
| 38 | } |
| 39 | |
| 40 | // assumes a simple slice of bytes if 16 bytes |
| 41 | // otherwise attempts to parse |
| 42 | if len(b) == 16 { |
| 43 | *uuid = UUID(b) |
| 44 | } else { |
| 45 | u := Parse(string(b)) |
| 46 | |
| 47 | if u == nil { |
| 48 | return errors.New("Scan: invalid UUID format") |
| 49 | } |
| 50 | |
| 51 | *uuid = u |
| 52 | } |
| 53 | |
| 54 | default: |
| 55 | return fmt.Errorf("Scan: unable to scan type %T into UUID", src) |
| 56 | } |
| 57 | |
| 58 | return nil |
| 59 | } |
| 60 | |
| 61 | // Value implements sql.Valuer so that UUIDs can be written to databases |
| 62 | // transparently. Currently, UUIDs map to strings. Please consult |
| 63 | // database-specific driver documentation for matching types. |
| 64 | func (uuid UUID) Value() (driver.Value, error) { |
| 65 | return uuid.String(), nil |
| 66 | } |