Skip to content

Commit

Permalink
Implement ApplyIf for UpdateBuilder
Browse files Browse the repository at this point in the history
Fixes #6
  • Loading branch information
hlubek committed Jun 26, 2024
1 parent eceea49 commit d949945
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions builder/update_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,13 @@ func (b UpdateBuilder) innerWriteSQL(sb *SQLBuilder) {
b.returningItems.WriteSQL(sb)
}
}

// ApplyIf applies the given function to the builder if the condition is true.
// It returns the builder itself if the condition is false, otherwise it returns the result of the function.
// It's especially helpful for building a query conditionally.
func (b UpdateBuilder) ApplyIf(cond bool, apply func(q UpdateBuilder) UpdateBuilder) UpdateBuilder {
if cond && apply != nil {
return apply(b)
}
return b
}
20 changes: 20 additions & 0 deletions update_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"

"github.com/networkteam/qrb"
"github.com/networkteam/qrb/builder"
"github.com/networkteam/qrb/internal/testhelper"
)

Expand Down Expand Up @@ -133,4 +134,23 @@ func TestUpdateBuilder(t *testing.T) {
q,
)
})

t.Run("apply if", func(t *testing.T) {
q := qrb.
Update(qrb.N("films")).
Set("kind", qrb.String("Dramatic")).
Where(qrb.N("kind").Eq(qrb.String("Drama"))).
ApplyIf(true, func(q builder.UpdateBuilder) builder.UpdateBuilder {
return q.Where(qrb.N("archived").Eq(qrb.Bool(false)))
})

testhelper.AssertSQLWriterEquals(
t,
`
UPDATE films SET kind = 'Dramatic' WHERE kind = 'Drama' AND archived = false
`,
nil,
q,
)
})
}

0 comments on commit d949945

Please sign in to comment.