Skip to content

Commit

Permalink
move options after set (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
OrCh3n committed Jun 20, 2024
1 parent 2249818 commit 84efdbc
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
6 changes: 3 additions & 3 deletions insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
12 changes: 9 additions & 3 deletions update.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
11 changes: 10 additions & 1 deletion update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 84efdbc

Please sign in to comment.