From 84efdbca18706c7285c868b7b57aef6cf26a7a1f Mon Sep 17 00:00:00 2001 From: Or Chen <125185199+OrCh3n@users.noreply.github.com> Date: Thu, 20 Jun 2024 16:03:12 +0300 Subject: [PATCH] move options after set (#20) --- insert.go | 6 +++--- update.go | 12 +++++++++--- update_test.go | 11 ++++++++++- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/insert.go b/insert.go index 74a1b5f..5089402 100644 --- a/insert.go +++ b/insert.go @@ -38,12 +38,12 @@ func WithInsertNotPrepared() InsertOption { func BuildInsert(tableName string, values []any, options ...InsertOption) (string, []any, error) { table := goqu.T(tableName) q := goqu.Insert(table).WithDialect(defaultDialect) - for _, o := range options { - q = o(table, q) - } encodedValues := make([]map[string]SQLValuer, len(values)) for i, value := range values { encodedValues[i] = encodeValues(value, skipInsert, false) } + for _, o := range options { + q = o(table, q) + } return q.Rows(encodedValues).ToSQL() } diff --git a/update.go b/update.go index 56a1527..abca5ac 100644 --- a/update.go +++ b/update.go @@ -27,16 +27,22 @@ func WithUpdateReturningAll() UpdateOption { } } +func WithUpdateSet(value any) UpdateOption { + return func(table exp.IdentifierExpression, s *goqu.UpdateDataset) *goqu.UpdateDataset { + return s.Set(value) + } +} + func BuildUpdate(tableName string, value any, options ...UpdateOption) (string, []any, error) { table := goqu.T(tableName) q := goqu.Update(table).WithDialect(defaultDialect) - for _, o := range options { - q = o(table, q) - } values := encodeValues(value, skipUpdate, true) if len(values) == 0 { return "", nil, errors.New("no values to update") } q = q.Set(values) + for _, o := range options { + q = o(table, q) + } return q.ToSQL() } diff --git a/update_test.go b/update_test.go index 477a347..307b20a 100644 --- a/update_test.go +++ b/update_test.go @@ -4,8 +4,10 @@ import ( "errors" "testing" - "github.com/roneli/goqux" + "github.com/doug-martin/goqu/v9" "github.com/stretchr/testify/assert" + + "github.com/roneli/goqux" ) type updateModel struct { @@ -67,6 +69,13 @@ func TestBuildUpdate(t *testing.T) { expectedArgs: []interface{}{false, int64(5)}, expectedQuery: `UPDATE "update_models" SET "bool_field"=$1,"int_field"=$2`, }, + { + name: "update_omit_empty_with_custom_set", + dst: updateModel{IntField: 1}, + options: []goqux.UpdateOption{goqux.WithUpdateSet(goqu.Record{"another_col_name_omit": "expected"})}, + expectedArgs: []interface{}{"expected"}, + expectedQuery: `UPDATE "update_models" SET "another_col_name_omit"=$1`, + }, } for _, tt := range tableTests { t.Run(tt.name, func(t *testing.T) {