diff --git a/insert_test.go b/insert_test.go index 696e2ef..f52eea2 100644 --- a/insert_test.go +++ b/insert_test.go @@ -8,10 +8,11 @@ import ( ) type insertModel struct { - IntField int64 `db:"int_field"` - OtherValue string - SkipInsert bool `goqux:"skip_insert"` - DbTag string `db:"another_col_name"` + IntField int64 `db:"int_field"` + OtherValue string + SkipInsert bool `goqux:"skip_insert"` + DbTag string `db:"another_col_name"` + DbTagOmitEmpty string `db:"another_col_name_omit,omitempty"` } func TestBuildInsert(t *testing.T) { @@ -25,6 +26,13 @@ func TestBuildInsert(t *testing.T) { }{ { name: "simple_insert", + values: []any{insertModel{IntField: 5, DbTagOmitEmpty: "test"}}, + expectedQuery: `INSERT INTO "insert_models" ("another_col_name", "another_col_name_omit", "int_field", "other_value") VALUES ($1, $2, $3, $4)`, + expectedArgs: []interface{}{"", "test", int64(5), ""}, + expectedError: nil, + }, + { + name: "simple_insert_ompitempty", values: []any{insertModel{IntField: 5}}, expectedQuery: `INSERT INTO "insert_models" ("another_col_name", "int_field", "other_value") VALUES ($1, $2, $3)`, expectedArgs: []interface{}{"", int64(5), ""}, diff --git a/struct.go b/struct.go index 7a5a675..c552db0 100644 --- a/struct.go +++ b/struct.go @@ -24,6 +24,8 @@ const ( defaultNow = "now" // Same as default now but will inject time.Now().UTC() defaultNowUtc = "now_utc" + // omitempty will skip the field if it is zero value + omitEmpty = ",omitempty" ) func encodeValues(v any, skipType string, skipZeroValues bool) map[string]SQLValuer { @@ -42,6 +44,12 @@ func encodeValues(v any, skipType string, skipZeroValues bool) map[string]SQLVal columnName := strcase.ToSnake(f.Name) if dbTag := f.Tag.Get(tagNameDb); dbTag != "" { + if strings.Contains(dbTag, omitEmpty) { + if value.IsZero() { + continue + } + dbTag = strings.ReplaceAll(dbTag, omitEmpty, "") + } columnName = dbTag } diff --git a/update_test.go b/update_test.go index cca99d8..dac626f 100644 --- a/update_test.go +++ b/update_test.go @@ -9,8 +9,9 @@ import ( ) type updateModel struct { - IntField int - DbTag string `db:"another_col_name"` + IntField int + DbTag string `db:"another_col_name"` + DbTagOmitEmpty string `db:"another_col_name_omit,omitempty"` } func TestBuildUpdate(t *testing.T) { @@ -29,6 +30,13 @@ func TestBuildUpdate(t *testing.T) { expectedArgs: []interface{}{"test", int64(5)}, expectedError: nil, }, + { + name: "simple_update", + dst: updateModel{IntField: 5, DbTagOmitEmpty: "test"}, + expectedQuery: `UPDATE "update_models" SET "another_col_name_omit"=$1,"int_field"=$2`, + expectedArgs: []interface{}{"test", int64(5)}, + expectedError: nil, + }, { name: "update_with_filters", dst: updateModel{IntField: 5},