github.com/searKing/golang/go@v1.2.117/database/sql/null_duration.go (about)

     1  // Copyright 2020 The searKing Author. 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 sql
     6  
     7  import (
     8  	"database/sql"
     9  	"database/sql/driver"
    10  	"fmt"
    11  	"time"
    12  )
    13  
    14  func _() {
    15  	// An "cannot convert NullDuration literal (type NullDuration) to type atomic.Value" compiler error signifies that the base type have changed.
    16  	// Re-run the go-nulljson command to generate them again.
    17  	_ = (sql.Scanner)(&NullDuration{})
    18  	_ = (driver.Valuer)(&NullDuration{})
    19  }
    20  
    21  var nilTimeDurationValue = func() (val time.Duration) { return }()
    22  
    23  // NullDuration represents an interface that may be null.
    24  // NullDuration implements the Scanner interface so it can be used as a scan destination, similar to sql.NullString.
    25  type NullDuration struct {
    26  	Data time.Duration
    27  
    28  	Valid bool // Valid is true if Data is not NULL
    29  }
    30  
    31  // Scan implements the sql.Scanner interface.
    32  func (nj *NullDuration) Scan(src any) error {
    33  	if src == nil {
    34  		nj.Data, nj.Valid = nilTimeDurationValue, false
    35  		return nil
    36  	}
    37  	nj.Valid = true
    38  
    39  	var err error
    40  	switch src := src.(type) {
    41  	case string:
    42  		nj.Data, err = time.ParseDuration(src)
    43  	case []byte:
    44  		nj.Data, err = time.ParseDuration(string(src))
    45  	case time.Duration:
    46  		nj.Data, err = time.ParseDuration(src.String())
    47  	case nil:
    48  		nj.Data = nilTimeDurationValue
    49  		err = nil
    50  	default:
    51  		nj.Data, err = time.ParseDuration(fmt.Sprintf("%s", src))
    52  	}
    53  	if err == nil {
    54  		return nil
    55  	}
    56  
    57  	return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type %T : %w", src, nj.Data, err)
    58  }
    59  
    60  // Value implements the driver.Valuer interface.
    61  func (nj NullDuration) Value() (driver.Value, error) {
    62  	if !nj.Valid {
    63  		return nil, nil
    64  	}
    65  	return nj.Data.String(), nil
    66  }