...

Source file src/github.com/pborman/uuid/sql.go

Documentation: github.com/pborman/uuid

     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  			parsed := make([]byte, 16)
    44  			copy(parsed, b)
    45  			*uuid = UUID(parsed)
    46  		} else {
    47  			u := Parse(string(b))
    48  
    49  			if u == nil {
    50  				return errors.New("Scan: invalid UUID format")
    51  			}
    52  
    53  			*uuid = u
    54  		}
    55  
    56  	default:
    57  		return fmt.Errorf("Scan: unable to scan type %T into UUID", src)
    58  	}
    59  
    60  	return nil
    61  }
    62  
    63  // Value implements sql.Valuer so that UUIDs can be written to databases
    64  // transparently. Currently, UUIDs map to strings. Please consult
    65  // database-specific driver documentation for matching types.
    66  func (uuid UUID) Value() (driver.Value, error) {
    67  	return uuid.String(), nil
    68  }
    69  

View as plain text