Skip to content

Commit

Permalink
Merge pull request #2157 from cockroachdb/pmattis/sql-order-by
Browse files Browse the repository at this point in the history
Add semantic actions for ORDER BY.
  • Loading branch information
petermattis committed Aug 19, 2015
2 parents 2600a14 + 1b09030 commit 9e749f1
Show file tree
Hide file tree
Showing 4 changed files with 4,097 additions and 4,036 deletions.
7 changes: 4 additions & 3 deletions sql/parser/parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,10 @@ func TestParse(t *testing.T) {
{`SELECT FROM t WHERE a = COUNT(*)`},
{`SELECT (a.b) FROM t WHERE (b.c) = 2`},

{`SELECT FROM t ORDER BY a`},
{`SELECT FROM t ORDER BY a ASC`},
{`SELECT FROM t ORDER BY a DESC`},

{`SELECT FROM t HAVING a = b`},

{`SELECT FROM t UNION SELECT 1 FROM t`},
Expand Down Expand Up @@ -395,9 +399,6 @@ func TestParseSyntax(t *testing.T) {
{`SELECT e'\'\"\b\n\r\t\\' FROM t`},
{`SELECT '\x' FROM t`},
{`SELECT 1 FROM t GROUP BY a`},
{`SELECT 1 FROM t ORDER BY a`},
{`SELECT 1 FROM t ORDER BY a ASC`},
{`SELECT 1 FROM t ORDER BY a DESC`},
{`CREATE INDEX a ON b (c)`},
{`CREATE INDEX a ON b.c (d)`},
{`CREATE INDEX ON a (b)`},
Expand Down
36 changes: 28 additions & 8 deletions sql/parser/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,20 +284,40 @@ func (node OrderBy) String() string {
return buf.String()
}

// Direction for ordering results.
type Direction int

// Direction values.
const (
DefaultDirection Direction = iota
Ascending
Descending
)

var directionName = [...]string{
DefaultDirection: "",
Ascending: "ASC",
Descending: "DESC",
}

func (d Direction) String() string {
if d < 0 || d > Direction(len(directionName)-1) {
return fmt.Sprintf("Direction(%d)", d)
}
return directionName[d]
}

// Order represents an ordering expression.
type Order struct {
Expr Expr
Direction string
Direction Direction
}

// Order.Direction
const (
astAsc = " ASC"
astDesc = " DESC"
)

func (node *Order) String() string {
return fmt.Sprintf("%s%s", node.Expr, node.Direction)
if node.Direction == DefaultDirection {
return node.Expr.String()
}
return fmt.Sprintf("%s %s", node.Expr, node.Direction)
}

// Limit represents a LIMIT clause.
Expand Down
Loading

0 comments on commit 9e749f1

Please sign in to comment.