Created
January 12, 2023 06:17
-
-
Save C-Pro/2c0044d0d73d6f553a5cd8afc42ade06 to your computer and use it in GitHub Desktop.
Custom sql valuer that insert null to database if zero value is passed to it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://go.dev/play/p/gTzl_yht11I | |
package main | |
import ( | |
"database/sql/driver" | |
"fmt" | |
) | |
type valuer[T comparable] struct { | |
value *T | |
zero T | |
} | |
func (v *valuer[T]) Value() (driver.Value, error) { | |
return v.value, nil | |
} | |
func ZeroIsNull[T comparable](src T) driver.Valuer { | |
v := &valuer[T]{} | |
v.value = &src | |
if src == v.zero { | |
v.value = (*T)(nil) | |
} | |
return v | |
} | |
func main() { | |
v, _ := ZeroIsNull[string]("").Value() | |
fmt.Printf("%#v\n", v) | |
v, _ = ZeroIsNull[string]("test").Value() | |
fmt.Printf("%#v\n", *v.(*string)) | |
v, _ = ZeroIsNull[uint64](uint64(0)).Value() | |
fmt.Printf("%#v\n", v) | |
v, _ = ZeroIsNull[uint64](uint64(42)).Value() | |
fmt.Printf("%#v\n", *v.(*uint64)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment