github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/internal/db/base/types/types.go (about)

     1  package types
     2  
     3  import (
     4  	"database/sql"
     5  	"database/sql/driver"
     6  
     7  	"github.com/ShoshinNikita/budget-manager/internal/pkg/errors"
     8  )
     9  
    10  // Uint represents optional uint. It treats NULL as 0 and vice versa
    11  type Uint uint
    12  
    13  var (
    14  	_ sql.Scanner   = (*Uint)(nil)
    15  	_ driver.Valuer = (*Uint)(nil)
    16  )
    17  
    18  func (v *Uint) Scan(src interface{}) error {
    19  	if src == nil {
    20  		*v = 0
    21  		return nil
    22  	}
    23  
    24  	switch src := src.(type) {
    25  	case int64:
    26  		*v = Uint(src)
    27  	default:
    28  		return errors.Errorf("couldn't scan uint from %T", src)
    29  	}
    30  	return nil
    31  }
    32  
    33  func (v Uint) Value() (driver.Value, error) {
    34  	if v == 0 {
    35  		return nil, nil
    36  	}
    37  	return int64(v), nil
    38  }
    39  
    40  // String represents optional string. It treats NULL as empty string and vice versa
    41  type String string
    42  
    43  var _ sql.Scanner = (*String)(nil)
    44  
    45  func (v *String) Scan(src interface{}) error {
    46  	if src == nil {
    47  		*v = ""
    48  		return nil
    49  	}
    50  
    51  	switch src := src.(type) {
    52  	case string:
    53  		*v = String(src)
    54  	case []byte:
    55  		*v = String(src)
    56  	default:
    57  		return errors.Errorf("couldn't scan string from %T", src)
    58  	}
    59  	return nil
    60  }
    61  
    62  func (v String) Value() (driver.Value, error) {
    63  	if v == "" {
    64  		return nil, nil
    65  	}
    66  	return string(v), nil
    67  }