blob: f326b54db37a664af48c29e9643d2080a5752615 [file] [log] [blame]
Takahiro Suzuki241c10e2020-12-17 20:17:57 +09001// Copyright 2016 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
5package uuid
6
7import (
8 "database/sql/driver"
9 "fmt"
10)
11
12// Scan implements sql.Scanner so UUIDs can be read from databases transparently
13// Currently, database types that map to string and []byte are supported. Please
14// consult database-specific driver documentation for matching types.
15func (uuid *UUID) Scan(src interface{}) error {
16 switch src := src.(type) {
17 case nil:
18 return nil
19
20 case string:
21 // if an empty UUID comes from a table, we return a null UUID
22 if src == "" {
23 return nil
24 }
25
26 // see Parse for required string format
27 u, err := Parse(src)
28 if err != nil {
29 return fmt.Errorf("Scan: %v", err)
30 }
31
32 *uuid = u
33
34 case []byte:
35 // if an empty UUID comes from a table, we return a null UUID
36 if len(src) == 0 {
37 return nil
38 }
39
40 // assumes a simple slice of bytes if 16 bytes
41 // otherwise attempts to parse
42 if len(src) != 16 {
43 return uuid.Scan(string(src))
44 }
45 copy((*uuid)[:], src)
46
47 default:
48 return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
49 }
50
51 return nil
52}
53
54// Value implements sql.Valuer so that UUIDs can be written to databases
55// transparently. Currently, UUIDs map to strings. Please consult
56// database-specific driver documentation for matching types.
57func (uuid UUID) Value() (driver.Value, error) {
58 return uuid.String(), nil
59}