Skip to content

Commit 8e414c7

Browse files
authored
feat: NullIfEmptySlice transform (#470)
1 parent 0766a9d commit 8e414c7

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

plugin/transform/primitives.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import (
1717
"github.com/turbot/go-kit/types"
1818
)
1919

20-
///////////////////////
20+
// /////////////////////
2121
// Transform primitives
2222
// predefined transform functions that may be chained together
2323

@@ -208,6 +208,19 @@ func NullIfZeroValue(_ context.Context, d *TransformData) (interface{}, error) {
208208
return d.Value, nil
209209
}
210210

211+
// NullIfEmptySliceValue returns nil if the input Value is an empty slice/array
212+
func NullIfEmptySliceValue(_ context.Context, d *TransformData) (interface{}, error) {
213+
if d.Value == nil {
214+
return nil, nil
215+
}
216+
v := helpers.DereferencePointer(d.Value)
217+
b, l := reflect.TypeOf(v).Kind() == reflect.Slice, reflect.ValueOf(v).Len()
218+
if b && l == 0 {
219+
return nil, nil
220+
}
221+
return d.Value, nil
222+
}
223+
211224
// UnmarshalYAML parse the yaml-encoded data and return the result
212225
func UnmarshalYAML(_ context.Context, d *TransformData) (interface{}, error) {
213226
if d.Value == nil {

plugin/transform/primitives_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,20 @@ Statement:
793793
function: StringArrayToMap,
794794
expected: "ERROR",
795795
},
796+
"NullIfEmptySlice array": {
797+
d: &TransformData{
798+
Value: []testStruct{{a: "A", b: "B"}, {a: "1", b: "2"}},
799+
},
800+
function: NullIfEmptySliceValue,
801+
expected: []testStruct{{a: "A", b: "B"}, {a: "1", b: "2"}},
802+
},
803+
"NullIfEmptySlice nil": {
804+
d: &TransformData{
805+
Value: []testStruct{},
806+
},
807+
function: NullIfEmptySliceValue,
808+
expected: nil,
809+
},
796810
}
797811

798812
func TestTransformFunctions(t *testing.T) {

plugin/transform/transform.go

+6
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,9 @@ func (t *ColumnTransforms) NullIfZero() *ColumnTransforms {
9595
t.Transforms = append(t.Transforms, &TransformCall{Transform: NullIfZeroValue})
9696
return t
9797
}
98+
99+
// NullIfEmptySlice returns nil if the input value is an empty slice/array
100+
func (t *ColumnTransforms) NullIfEmptySlice() *ColumnTransforms {
101+
t.Transforms = append(t.Transforms, &TransformCall{Transform: NullIfEmptySliceValue})
102+
return t
103+
}

0 commit comments

Comments
 (0)