diff --git a/qb/select.go b/qb/select.go index 73fed17..8c7e0b2 100644 --- a/qb/select.go +++ b/qb/select.go @@ -22,6 +22,13 @@ const ( DESC = false ) +func (o Order) String() string { + if o { + return "ASC" + } + return "DESC" +} + // SelectBuilder builds CQL SELECT statements. type SelectBuilder struct { table string @@ -29,8 +36,7 @@ type SelectBuilder struct { distinct columns where where groupBy columns - orderBy string - order Order + orderBy columns limit uint limitPerPartition uint allowFiltering bool @@ -75,14 +81,10 @@ func (b *SelectBuilder) ToCql() (stmt string, names []string) { cql.WriteByte(' ') } - if b.orderBy != "" { + if len(b.orderBy) > 0 { cql.WriteString("ORDER BY ") - cql.WriteString(b.orderBy) - if b.order { - cql.WriteString(" ASC ") - } else { - cql.WriteString(" DESC ") - } + b.orderBy.writeCql(&cql) + cql.WriteByte(' ') } if b.limit != 0 { @@ -144,7 +146,7 @@ func (b *SelectBuilder) GroupBy(columns ...string) *SelectBuilder { // OrderBy sets ORDER BY clause on the query. func (b *SelectBuilder) OrderBy(column string, o Order) *SelectBuilder { - b.orderBy, b.order = column, o + b.orderBy = append(b.orderBy, column+" "+o.String()) return b } diff --git a/qb/select_test.go b/qb/select_test.go index cd68a62..7ed3ca5 100644 --- a/qb/select_test.go +++ b/qb/select_test.go @@ -59,12 +59,23 @@ func TestSelectBuilder(t *testing.T) { B: Select("cycling.cyclist_name").GroupBy("id"), S: "SELECT id FROM cycling.cyclist_name GROUP BY id ", }, + // Add GROUP BY two columns + { + B: Select("cycling.cyclist_name").GroupBy("id", "user_uuid"), + S: "SELECT id,user_uuid FROM cycling.cyclist_name GROUP BY id,user_uuid ", + }, // Add ORDER BY { B: Select("cycling.cyclist_name").Where(w).OrderBy("firstname", ASC), S: "SELECT * FROM cycling.cyclist_name WHERE id=? ORDER BY firstname ASC ", N: []string{"expr"}, }, + // Add ORDER BY two columns + { + B: Select("cycling.cyclist_name").Where(w).OrderBy("firstname", ASC).OrderBy("lastname", DESC), + S: "SELECT * FROM cycling.cyclist_name WHERE id=? ORDER BY firstname ASC,lastname DESC ", + N: []string{"expr"}, + }, // Add LIMIT { B: Select("cycling.cyclist_name").Where(w).Limit(10),