From d94994521b230f7168d3ed32e05521094e36364b Mon Sep 17 00:00:00 2001 From: Christopher Hlubek Date: Wed, 26 Jun 2024 12:41:16 +0200 Subject: [PATCH] Implement ApplyIf for UpdateBuilder Fixes #6 --- builder/update_builder.go | 10 ++++++++++ update_builder_test.go | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/builder/update_builder.go b/builder/update_builder.go index 287adc2..a6bf30f 100644 --- a/builder/update_builder.go +++ b/builder/update_builder.go @@ -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 +} diff --git a/update_builder_test.go b/update_builder_test.go index 6610669..a4fe90a 100644 --- a/update_builder_test.go +++ b/update_builder_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/networkteam/qrb" + "github.com/networkteam/qrb/builder" "github.com/networkteam/qrb/internal/testhelper" ) @@ -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, + ) + }) }