Skip to content

Commit

Permalink
qb: insert support order by multiple columns (#79)
Browse files Browse the repository at this point in the history
Fixes #78
  • Loading branch information
mmatczuk authored Nov 15, 2018
1 parent 8083fa2 commit b7e4f7e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
22 changes: 12 additions & 10 deletions qb/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,21 @@ const (
DESC = false
)

func (o Order) String() string {
if o {
return "ASC"
}
return "DESC"
}

// SelectBuilder builds CQL SELECT statements.
type SelectBuilder struct {
table string
columns columns
distinct columns
where where
groupBy columns
orderBy string
order Order
orderBy columns
limit uint
limitPerPartition uint
allowFiltering bool
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}

Expand Down
11 changes: 11 additions & 0 deletions qb/select_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit b7e4f7e

Please sign in to comment.