Skip to content

Commit

Permalink
Implement ANY/ALL
Browse files Browse the repository at this point in the history
Fixes #7
  • Loading branch information
hlubek committed Jun 26, 2024
1 parent d949945 commit 5c8935f
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
36 changes: 36 additions & 0 deletions builder/functions_subquery_comparison.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package builder

type subqueryExp struct {
op string
exp Exp
}

func (s subqueryExp) IsExp() {}

func (s subqueryExp) WriteSQL(sb *SQLBuilder) {
sb.WriteString(s.op)
sb.WriteRune(' ')

_, isSelect := s.exp.(SelectExp)
if !isSelect {
sb.WriteRune('(')
}
s.exp.WriteSQL(sb)
if !isSelect {
sb.WriteRune(')')
}
}

func Any(exp Exp) Exp {
return subqueryExp{
op: "ANY",
exp: exp,
}
}

func All(exp Exp) Exp {
return subqueryExp{
op: "ALL",
exp: exp,
}
}
10 changes: 10 additions & 0 deletions root.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,16 @@ func Exists(subquery builder.SelectExp) builder.Exp {
return builder.Exists(subquery)
}

// --- Row and Array Comparisons

func Any(exp builder.Exp) builder.Exp {
return builder.Any(exp)
}

func All(exp builder.Exp) builder.Exp {
return builder.All(exp)
}

// --- Commands

func InsertInto(tableName builder.Identer) builder.InsertBuilder {
Expand Down
34 changes: 34 additions & 0 deletions select_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,40 @@ func TestSelectBuilder_Where(t *testing.T) {
q,
)
})

t.Run("where all with subselect", func(t *testing.T) {
q := qrb.Select(qrb.N("*")).
From(qrb.N("employees")).
Where(qrb.N("salary").Gt(qrb.All(qrb.Select(qrb.N("salary")).From(qrb.N("managers")))))

testhelper.AssertSQLWriterEquals(
t,
`
SELECT *
FROM employees
WHERE salary > ALL (SELECT salary FROM managers)
`,
nil,
q,
)
})

t.Run("where any with array", func(t *testing.T) {
q := qrb.Select(qrb.N("*")).
From(qrb.N("table")).
Where(qrb.N("column").Eq(qrb.Any(qrb.Array(qrb.Int(1), qrb.Int(2), qrb.Int(3)))))

testhelper.AssertSQLWriterEquals(
t,
`
SELECT *
FROM table
WHERE column = ANY (ARRAY[1, 2, 3])
`,
nil,
q,
)
})
}

func TestSelectBuilder_GroupBy(t *testing.T) {
Expand Down

0 comments on commit 5c8935f

Please sign in to comment.