Skip to content

Commit

Permalink
dat.Null* helpers. Fixes #12
Browse files Browse the repository at this point in the history
  • Loading branch information
GeorgeErickson committed Jun 22, 2015
1 parent df370a0 commit 0873c59
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
25 changes: 25 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,31 @@ type NullBool struct {
sql.NullBool
}

// NullStringFrom creates a valid NullString
func NullStringFrom(v string) NullString {
return NullString{sql.NullString{v, true}}
}

// NullFloat64From creates a valid NullFloat64
func NullFloat64From(v float64) NullFloat64 {
return NullFloat64{sql.NullFloat64{v, true}}
}

// NullInt64From creates a valid NullInt64
func NullInt64From(v int64) NullInt64 {
return NullInt64{sql.NullInt64{v, true}}
}

// NullTimeFrom creates a valid NullTime
func NullTimeFrom(v time.Time) NullTime {
return NullTime{pq.NullTime{v, true}}
}

// NullBoolFrom creates a valid NullBool
func NullBoolFrom(v bool) NullBool {
return NullBool{sql.NullBool{v, true}}
}

var nullString = []byte("null")

// MarshalJSON correctly serializes a NullString to JSON
Expand Down
48 changes: 48 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package dat

import (
"testing"
"time"

"gopkg.in/stretchr/testify.v1/assert"
)

func TestNullStringFrom(t *testing.T) {
v := "foo"
n := NullStringFrom(v)

assert.True(t, n.Valid)
assert.Equal(t, n.String, v)
}

func TestNullFloat64From(t *testing.T) {
v := 42.2
n := NullFloat64From(v)

assert.True(t, n.Valid)
assert.Equal(t, n.Float64, v)
}

func TestNullInt64From(t *testing.T) {
v := int64(400)
n := NullInt64From(v)

assert.True(t, n.Valid)
assert.Equal(t, n.Int64, v)
}

func TestNullTimeFrom(t *testing.T) {
v := time.Now()
n := NullTimeFrom(v)

assert.True(t, n.Valid)
assert.Equal(t, n.Time, v)
}

func TestNullBoolFrom(t *testing.T) {
v := false
n := NullBoolFrom(v)

assert.True(t, n.Valid)
assert.Equal(t, n.Bool, v)
}

0 comments on commit 0873c59

Please sign in to comment.