Skip to content

Commit

Permalink
Merge pull request #21 from twharmon/count-queries
Browse files Browse the repository at this point in the history
Add group by and having clauses to count queries
  • Loading branch information
twharmon authored Aug 26, 2020
2 parents 87d31ee + 0881091 commit f056b77
Showing 1 changed file with 49 additions and 6 deletions.
55 changes: 49 additions & 6 deletions count_query.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ import (

// CountQuery is a query for counting rows in a table.
type CountQuery struct {
db *DB
count string
table string
joins []string
wheres []*where
whereArgs []interface{}
db *DB
count string
table string
joins []string
wheres []*where
whereArgs []interface{}
havings []*having
havingArgs []interface{}
groupBy string
}

// Where specifies which rows will be returned.
Expand Down Expand Up @@ -71,5 +74,45 @@ func (cq *CountQuery) String() string {
}
q.WriteString(where.condition)
}
if cq.groupBy != "" {
q.WriteString(" group by ")
q.WriteString(cq.groupBy)
}
for i, having := range cq.havings {
if i == 0 {
q.WriteString(" having ")
} else {
q.WriteString(having.conjunction)
}
q.WriteString(having.condition)
}
return q.String()
}

// Having specifies which rows will be returned.
func (cq *CountQuery) Having(condition string, args ...interface{}) *CountQuery {
h := &having{
conjunction: " and ",
condition: condition,
}
cq.havings = append(cq.havings, h)
cq.havingArgs = append(cq.havingArgs, args...)
return cq
}

// OrHaving specifies which rows will be returned.
func (cq *CountQuery) OrHaving(condition string, args ...interface{}) *CountQuery {
h := &having{
conjunction: " or ",
condition: condition,
}
cq.havings = append(cq.havings, h)
cq.havingArgs = append(cq.havingArgs, args...)
return cq
}

// GroupBy specifies how to group the results.
func (cq *CountQuery) GroupBy(bys ...string) *CountQuery {
cq.groupBy = strings.Join(bys, ", ")
return cq
}

0 comments on commit f056b77

Please sign in to comment.