Skip to content

Commit

Permalink
fix #61, introduce the new expression api for generating queries
Browse files Browse the repository at this point in the history
  • Loading branch information
aacanakin committed Jun 19, 2016
1 parent 62df29a commit cc06dc9
Show file tree
Hide file tree
Showing 52 changed files with 2,573 additions and 1,582 deletions.
49 changes: 49 additions & 0 deletions aggregate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package qb

import (
"fmt"
)

// Avg function generates "avg(%s)" statement for column
func Avg(column ColumnElem) AggregateClause {
return Aggregate("AVG", column)
}

// Count function generates "count(%s)" statement for column
func Count(column ColumnElem) AggregateClause {
return Aggregate("COUNT", column)
}

// Sum function generates "sum(%s)" statement for column
func Sum(column ColumnElem) AggregateClause {
return Aggregate("SUM", column)
}

// Min function generates "min(%s)" statement for column
func Min(column ColumnElem) AggregateClause {
return Aggregate("MIN", column)
}

// Max function generates "max(%s)" statement for column
func Max(column ColumnElem) AggregateClause {
return Aggregate("MAX", column)
}

// Aggregate generates a new aggregate clause given function & column
func Aggregate(fn string, column ColumnElem) AggregateClause {
return AggregateClause{fn, column}
}

// AggregateClause is the base struct for building aggregate functions
type AggregateClause struct {
fn string
column ColumnElem
}

// Build compiles the aggregate clause and returns the sql and bindings
func (c AggregateClause) Build(dialect Dialect) (string, []interface{}) {
bindings := []interface{}{}
sql := fmt.Sprintf("%s(%s)", c.fn, dialect.Escape(c.column.Name))
return sql, bindings
}

15 changes: 15 additions & 0 deletions aggregate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package qb

import (
"testing"
"github.com/stretchr/testify/assert"
)

func TestAggregates(t *testing.T) {
col := Column("id", Varchar().Size(36))
assert.Equal(t, Avg(col), Aggregate("AVG", col))
assert.Equal(t, Count(col), Aggregate("COUNT", col))
assert.Equal(t, Sum(col), Aggregate("SUM", col))
assert.Equal(t, Min(col), Aggregate("MIN", col))
assert.Equal(t, Max(col), Aggregate("MAX", col))
}
Loading

0 comments on commit cc06dc9

Please sign in to comment.