github.com/octohelm/storage@v0.0.0-20240516030302-1ac2cc1ea347/pkg/datatypes/json_scanner.go (about)

     1  package datatypes
     2  
     3  import (
     4  	"database/sql/driver"
     5  	"encoding/json"
     6  	"fmt"
     7  )
     8  
     9  func JSONScan(dbValue any, value any) error {
    10  	switch v := dbValue.(type) {
    11  	case []byte:
    12  		bytes := v
    13  		if len(bytes) > 0 {
    14  			return json.Unmarshal(bytes, value)
    15  		}
    16  		return nil
    17  	case string:
    18  		str := v
    19  		if str == "" {
    20  			return nil
    21  		}
    22  		return json.Unmarshal([]byte(str), value)
    23  	case nil:
    24  		return nil
    25  	default:
    26  		return fmt.Errorf("cannot sql.Scan() from: %#v", value)
    27  	}
    28  }
    29  
    30  func JSONValue(value any) (driver.Value, error) {
    31  	if zeroCheck, ok := value.(interface {
    32  		IsZero() bool
    33  	}); ok {
    34  		if zeroCheck.IsZero() {
    35  			return "", nil
    36  		}
    37  	}
    38  	bytes, err := json.Marshal(value)
    39  	if err != nil {
    40  		return "", err
    41  	}
    42  	str := string(bytes)
    43  	if str == "null" {
    44  		return "", nil
    45  	}
    46  	return str, nil
    47  }