Skip to content

Commit

Permalink
genesis
Browse files Browse the repository at this point in the history
  • Loading branch information
LukaGiorgadze committed Apr 30, 2023
1 parent 4e13905 commit c79c322
Show file tree
Hide file tree
Showing 5 changed files with 212 additions and 2 deletions.
47 changes: 45 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,45 @@
# gonull
Go package simplifies nullable fields handling.
# Go Nullable

## Go package simplifies nullable fields handling.

This package provides a generic nullable type implementation for use with Go's `database/sql` package.
It simplifies handling nullable fields in SQL databases by wrapping any data type with the `Nullable` type.
The Nullable type works with both basic and custom data types and implements the `sql.Scanner` and `driver.Valuer` interfaces, making it easy to use with the `database/sql` package.

## Use case
In a web application, you may have a user profile with optional fields like name, age, or whatever. These fields can be left empty by the user, and your database stores them as `NULL` values. Using the `Nullable` type from this library, you can easily handle these optional fields when scanning data from the database or inserting new records. By wrapping the data types of these fields with the `Nullable` type, you can handle `NULL` values without additional logic, making your code cleaner and more maintainable.


## Usage

```bash
go get https://github.com/lomsa-dev/gonull
```

```go
type User struct {
ID int
Name null.Nullable[string]
Age null.Nullable[int]
}

func main() {
// ...
rows, err := db.Query("SELECT id, name, age FROM users")
if err != nil {
log.Fatal(err)
}
defer rows.Close()

for rows.Next() {
var user User
err := rows.Scan(&user.ID, &user.Name, &user.Age)
if err != nil {
log.Fatal(err)
}
fmt.Printf("ID: %d, Name: %v, Age: %v\n", user.ID, user.Name.Val, user.Age.Val)
}
// ...
}

```
11 changes: 11 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/lomsa-dev/gonull

go 1.20

require github.com/stretchr/testify v1.8.2

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
17 changes: 17 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
50 changes: 50 additions & 0 deletions gonull.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package gonull

import (
"database/sql/driver"
"errors"
)

// Nullable wraps a generic nullable type that can be used with Go's database/sql package.
type Nullable[T any] struct {
Val T
IsSet bool
}

// NewNullable returns a new Nullable with the given value set and Valid set to true.
func NewNullable[T any](value T) Nullable[T] {
return Nullable[T]{Val: value, IsSet: true}
}

// Scan implements the sql.Scanner interface.
func (n *Nullable[T]) Scan(value interface{}) error {
if value == nil {
n.IsSet = false
return nil
}

var err error
n.Val, err = convertToType[T](value)
if err == nil {
n.IsSet = true
}
return err
}

// Value implements the driver.Valuer interface.
func (n Nullable[T]) Value() (driver.Value, error) {
if !n.IsSet {
return nil, nil
}
return n.Val, nil
}

func convertToType[T any](value interface{}) (T, error) {
switch v := value.(type) {
case T:
return v, nil
default:
var zero T
return zero, errors.New("unsupported type conversion")
}
}
89 changes: 89 additions & 0 deletions gonull_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package gonull

import (
"database/sql/driver"
"testing"

"github.com/stretchr/testify/assert"
)

func TestNewNullable(t *testing.T) {
value := "test"
n := NewNullable(value)

assert.True(t, n.IsSet)
assert.Equal(t, value, n.Val)
}

func TestNullableScan(t *testing.T) {
tests := []struct {
name string
value interface{}
isSet bool
wantErr bool
}{
{
name: "nil value",
value: nil,
isSet: false,
},
{
name: "string value",
value: "test",
isSet: true,
},
{
name: "unsupported type",
value: []byte{1, 2, 3},
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var n Nullable[string]
err := n.Scan(tt.value)

if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.isSet, n.IsSet)
if tt.isSet {
assert.Equal(t, tt.value, n.Val)
}
}
})
}
}

func TestNullableValue(t *testing.T) {
tests := []struct {
name string
nullable Nullable[string]
wantValue driver.Value
wantErr error
}{
{
name: "valid value",
nullable: NewNullable("test"),
wantValue: "test",
wantErr: nil,
},
{
name: "unset value",
nullable: Nullable[string]{IsSet: false},
wantValue: nil,
wantErr: nil,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
value, err := tt.nullable.Value()

assert.Equal(t, tt.wantErr, err)
assert.Equal(t, tt.wantValue, value)
})
}
}

0 comments on commit c79c322

Please sign in to comment.