Skip to content

Commit

Permalink
feat(opts): Adding a generic WithFilter option that takes a joiner …
Browse files Browse the repository at this point in the history
…or wherer (#103)

* Adding filter opt for generic passing

* join first
  • Loading branch information
Jacobbrewer1 authored Jan 31, 2025
1 parent e7eede8 commit c9b9315
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
13 changes: 13 additions & 0 deletions patch_opts.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,19 @@ func WithTable(table string) PatchOpt {
}
}

// WithFilter takes in either a Wherer or a Joiner to set the filter to use in the SQL statement
func WithFilter(filter any) PatchOpt {
return func(s *SQLPatch) {
if join, ok := filter.(Joiner); ok {
WithJoin(join)(s)
}

if where, ok := filter.(Wherer); ok {
WithWhere(where)(s)
}
}
}

// WithWhere sets the where clause to use in the SQL statement
func WithWhere(where Wherer) PatchOpt {
return func(s *SQLPatch) {
Expand Down
30 changes: 30 additions & 0 deletions sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,36 @@ func (s *generateSQLSuite) TestGenerateSQL_Success() {
mw.AssertExpectations(s.T())
}

type testFilter struct{}

func (f *testFilter) Where() (string, []any) {
return "age = ?", []any{18}
}

func (f *testFilter) Join() (string, []any) {
return "JOIN table2 ON table1.id = table2.id", nil
}

func (s *generateSQLSuite) TestGenerateSQL_Success_WhereAndJoin() {
type testObj struct {
Id *int `db:"id"`
Name *string `db:"name"`
}

obj := testObj{
Id: ptr(1),
Name: ptr("test"),
}

sqlStr, args, err := GenerateSQL(obj,
WithTable("test_table"),
WithFilter(new(testFilter)),
)
s.NoError(err)
s.Equal("UPDATE test_table\nJOIN table2 ON table1.id = table2.id\nSET id = ?, name = ?\nWHERE (1=1)\nAND (\nage = ?\n)", sqlStr)
s.Equal([]any{int64(1), "test", 18}, args)
}

func (s *generateSQLSuite) TestGenerateSQL_Success_WhereString() {
type testObj struct {
Id *int `db:"id"`
Expand Down

0 comments on commit c9b9315

Please sign in to comment.