Skip to content

Commit

Permalink
feat(chsql): add PREWHERE
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Jun 20, 2024
1 parent 3fcc6d7 commit 3473bf0
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 1 deletion.
1 change: 1 addition & 0 deletions internal/chstorage/chsql/_golden/Test8.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SELECT body FROM logs PREWHERE (hasToken(body, 'Error'))
5 changes: 5 additions & 0 deletions internal/chstorage/chsql/chsql.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,11 @@ func (p *Printer) From() {
p.Ident("FROM")
}

// Prewhere writes `PREWHERE` ident.
func (p *Printer) Prewhere() {
p.Ident("PREWHERE")
}

// Where writes `WHERE` ident.
func (p *Printer) Where() {
p.Ident("WHERE")
Expand Down
23 changes: 22 additions & 1 deletion internal/chstorage/chsql/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ type SelectQuery struct {
distinct bool
columns []ResultColumn

// prewhere is a set of expression joined by AND
prewhere []Expr
// where is a set of expression joined by AND
where []Expr
order []orderExpr
Expand Down Expand Up @@ -54,6 +56,12 @@ func (q *SelectQuery) Distinct(b bool) *SelectQuery {
return q
}

// Prewhere adds filters to query.
func (q *SelectQuery) Prewhere(filters ...Expr) *SelectQuery {
q.prewhere = append(q.prewhere, filters...)
return q
}

// Where adds filters to query.
func (q *SelectQuery) Where(filters ...Expr) *SelectQuery {
q.where = append(q.where, filters...)
Expand Down Expand Up @@ -145,6 +153,19 @@ func (q *SelectQuery) WriteSQL(p *Printer) error {
default:
return errors.New("either table or sub-query must be present")
}
if len(q.prewhere) > 0 {
p.Prewhere()
for i, filter := range q.prewhere {
if i != 0 {
p.And()
}
p.OpenParen()
if err := p.WriteExpr(filter); err != nil {
return errors.Wrapf(err, "prewhere %d", i)
}
p.CloseParen()
}
}
if len(q.where) > 0 {
p.Where()
for i, filter := range q.where {
Expand All @@ -153,7 +174,7 @@ func (q *SelectQuery) WriteSQL(p *Printer) error {
}
p.OpenParen()
if err := p.WriteExpr(filter); err != nil {
return errors.Wrapf(err, "filter %d", i)
return errors.Wrapf(err, "where %d", i)
}
p.CloseParen()
}
Expand Down
14 changes: 14 additions & 0 deletions internal/chstorage/chsql/select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,20 @@ func TestSelect(t *testing.T) {
false,
},

// Test PREWHERE.
{
func() *SelectQuery {
return Select(
"logs",
Column("body", nil),
).
Prewhere(
HasToken(Ident("body"), "Error"),
)
},
false,
},

// No columns.
{
func() *SelectQuery { return Select("logs") },
Expand Down

0 comments on commit 3473bf0

Please sign in to comment.