Skip to content

Commit

Permalink
Assign a name to columns with binary expressions in them
Browse files Browse the repository at this point in the history
The name of the column will be every measurement located inside of the
math expression in the order they are encountered in within the
expression.

Fixes #5730.
  • Loading branch information
jsternberg committed Feb 18, 2016
1 parent 7e64e77 commit 7948379
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
23 changes: 23 additions & 0 deletions influxql/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -1055,6 +1055,8 @@ func (s *SelectStatement) ColumnNames() []string {
continue
}
columnNames = append(columnNames, field.Name())
case *BinaryExpr:
columnNames = append(columnNames, BinaryExprName(f))
default:
// time is always first, and we already added it, so ignore it if they asked for it anywhere else.
if field.Name() != "time" {
Expand Down Expand Up @@ -2919,6 +2921,27 @@ func (e *BinaryExpr) String() string {
return fmt.Sprintf("%s %s %s", e.LHS.String(), e.Op.String(), e.RHS.String())
}

func BinaryExprName(expr *BinaryExpr) string {
v := binaryExprNameVisitor{}
Walk(&v, expr)
return strings.Join(v.names, "_")
}

type binaryExprNameVisitor struct {
names []string
}

func (v *binaryExprNameVisitor) Visit(n Node) Visitor {
switch n := n.(type) {
case *VarRef:
v.names = append(v.names, n.Val)
case *Call:
v.names = append(v.names, n.Name)
return nil
}
return v
}

// ParenExpr represents a parenthesized expression.
type ParenExpr struct {
Expr Expr
Expand Down
23 changes: 23 additions & 0 deletions influxql/ast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,29 @@ func TestSelectStatement_HasCountDistinct(t *testing.T) {
}
}

// Ensure binary expression names can be evaluated.
func TestBinaryExprName(t *testing.T) {
for i, tt := range []struct {
expr string
name string
}{
{expr: `value + 1`, name: `value`},
{expr: `"user" / total`, name: `user_total`},
{expr: `("user" + total) / total`, name: `user_total_total`},
} {
expr := influxql.MustParseExpr(tt.expr)
switch expr := expr.(type) {
case *influxql.BinaryExpr:
name := influxql.BinaryExprName(expr)
if name != tt.name {
t.Errorf("%d. unexpected name %s, got %s", i, name, tt.name)
}
default:
t.Errorf("%d. unexpected expr type: %T", i, expr)
}
}
}

// Ensure the time range of an expression can be extracted.
func TestTimeRange(t *testing.T) {
for i, tt := range []struct {
Expand Down

0 comments on commit 7948379

Please sign in to comment.