Skip to content

Commit

Permalink
transformer: add transformer for unsetting empty values
Browse files Browse the repository at this point in the history
  • Loading branch information
N1cOs committed Nov 23, 2021
1 parent 225d021 commit a42f7e7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
19 changes: 16 additions & 3 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,17 +107,30 @@ func basicCreateAndPopulateKeyspace(t *testing.T, session gocqlx.Session) {

// Insert song using query builder.
insertSong := qb.Insert("examples.songs").
Columns("id", "title", "album", "artist", "tags", "data").Query(session)
Columns("id", "title", "album", "artist", "tags", "data")

insertSong.BindStruct(Song{
insertQuery := insertSong.Query(session).BindStruct(Song{
ID: mustParseUUID("756716f7-2e54-4715-9f00-91dcbea6cf50"),
Title: "La Petite Tonkinoise",
Album: "Bye Bye Blackbird",
Artist: "Joséphine Baker",
Tags: []string{"jazz", "2013"},
Data: []byte("music"),
})
if err := insertSong.ExecRelease(); err != nil {
if err := insertQuery.ExecRelease(); err != nil {
t.Fatal("ExecRelease() failed:", err)
}

// Insert song with some empty fields using the same statement.
insertQuery = insertSong.Query(session).
WithBindTransformer(gocqlx.UnsetEmptyTransformer).
BindStruct(Song{
ID: mustParseUUID("94db5bd8-ca97-4d50-9832-14d583c832cd"),
Title: "Moulin Rouge",
Artist: "Joséphine Baker",
Data: []byte("music"),
})
if err := insertQuery.ExecRelease(); err != nil {
t.Fatal("ExecRelease() failed:", err)
}

Expand Down
17 changes: 17 additions & 0 deletions transformer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,27 @@

package gocqlx

import (
"reflect"

"github.com/gocql/gocql"
)

// Transformer transforms the value of the named parameter to another value.
type Transformer func(name string, val interface{}) interface{}

// DefaultBindTransformer just do nothing.
//
// A custom transformer can always be set per Query.
var DefaultBindTransformer Transformer

// UnsetEmptyTransformer unsets all empty parameters.
// It helps to avoid tombstones when using the same insert/update
// statement for filled and partially filled named parameters.
var UnsetEmptyTransformer = func(name string, val interface{}) interface{} {
v := reflect.ValueOf(val)
if v.IsZero() {
return gocql.UnsetValue
}
return val
}

0 comments on commit a42f7e7

Please # to comment.