Skip to content

Commit

Permalink
add a NullSnowflake implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Kelwing committed Nov 25, 2022
1 parent 1b2a537 commit 5c7bd36
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions null_snowflake.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package snowflake

import (
"bytes"
"database/sql/driver"
"encoding/json"
)

var nullBytes = []byte("null")

// NullSnowflake is a nullable Snowflake
type NullSnowflake struct {
Snowflake Snowflake
Valid bool
}

// NewNullSnowflake creates a new NullSnowflake
func NewNullSnowflake(s Snowflake, valid bool) NullSnowflake {
return NullSnowflake{
Snowflake: s,
Valid: valid,
}
}

// Scan implements sql.Scanner interface
func (s *NullSnowflake) Scan(value any) error {
if value == nil {
s.Snowflake, s.Valid = Snowflake(0), false
return nil
}
s.Valid = true
return (&s.Snowflake).Scan(value)
}

// Value implements driver.Valuer interface
func (s NullSnowflake) Value() (driver.Value, error) {
if !s.Valid {
return nil, nil
}
return s.Snowflake.Value()
}

// ValueOrZero returns the inner value if valid, otherwise zero.
func (s NullSnowflake) ValueOrZero() Snowflake {
if !s.Valid {
return Snowflake(0)
}
return s.Snowflake
}

// UnmarshalJSON implements json.Unmarshaler.
func (s *NullSnowflake) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, nullBytes) {
s.Valid = false
return nil
}

if err := json.Unmarshal(data, &s.Snowflake); err != nil {
return err
}

s.Valid = true

return nil
}

// MarshalJSON implements json.Marshaler.
func (s NullSnowflake) MarshalJSON() ([]byte, error) {
if !s.Valid {
return nullBytes, nil
}

return s.Snowflake.MarshalJSON()
}

0 comments on commit 5c7bd36

Please sign in to comment.