Skip to content

Instantly share code, notes, and snippets.

@C-Pro
Created January 12, 2023 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save C-Pro/2c0044d0d73d6f553a5cd8afc42ade06 to your computer and use it in GitHub Desktop.
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.
// 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