2016-10-17 07:14:01 +03:00
|
|
|
package ast
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
|
2023-04-02 22:49:45 +03:00
|
|
|
"github.com/neilotoole/slogt"
|
|
|
|
"golang.org/x/exp/slog"
|
2020-08-06 20:58:47 +03:00
|
|
|
|
2023-04-02 22:49:45 +03:00
|
|
|
"github.com/stretchr/testify/assert"
|
2016-10-17 07:14:01 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestWalker(t *testing.T) {
|
2023-04-02 22:49:45 +03:00
|
|
|
log := slogt.New(t)
|
2016-10-17 07:14:01 +03:00
|
|
|
|
|
|
|
// `@mydb1 | .user, .address | join(.uid == .uid) | .uid, .username, .country`
|
2020-08-06 20:58:47 +03:00
|
|
|
p := getSLQParser(fixtJoinQuery1)
|
2016-10-17 07:14:01 +03:00
|
|
|
query := p.Query()
|
2020-08-06 20:58:47 +03:00
|
|
|
ast, err := buildAST(log, query)
|
2016-10-17 07:14:01 +03:00
|
|
|
|
|
|
|
assert.Nil(t, err)
|
|
|
|
assert.NotNil(t, ast)
|
|
|
|
|
2020-08-06 20:58:47 +03:00
|
|
|
walker := NewWalker(log, ast)
|
2016-10-17 07:14:01 +03:00
|
|
|
count := 0
|
|
|
|
|
2023-04-02 22:49:45 +03:00
|
|
|
visitor := func(log *slog.Logger, w *Walker, node Node) error {
|
2016-10-17 07:14:01 +03:00
|
|
|
count++
|
|
|
|
return w.visitChildren(node)
|
|
|
|
}
|
|
|
|
|
2023-03-22 09:17:34 +03:00
|
|
|
walker.AddVisitor(typeJoinNode, visitor)
|
2016-10-17 07:14:01 +03:00
|
|
|
err = walker.Walk()
|
|
|
|
assert.Nil(t, err)
|
|
|
|
assert.Equal(t, 1, count)
|
|
|
|
|
|
|
|
// test multiple visitors on the same node type
|
2020-08-06 20:58:47 +03:00
|
|
|
walker = NewWalker(log, ast)
|
2016-10-17 07:14:01 +03:00
|
|
|
countA := 0
|
2023-04-02 22:49:45 +03:00
|
|
|
visitorA := func(log *slog.Logger, w *Walker, node Node) error {
|
2016-10-17 07:14:01 +03:00
|
|
|
countA++
|
|
|
|
return w.visitChildren(node)
|
|
|
|
}
|
|
|
|
countB := 0
|
2023-04-02 22:49:45 +03:00
|
|
|
visitorB := func(log *slog.Logger, w *Walker, node Node) error {
|
2016-10-17 07:14:01 +03:00
|
|
|
countB++
|
|
|
|
return w.visitChildren(node)
|
|
|
|
}
|
|
|
|
|
2023-03-22 09:17:34 +03:00
|
|
|
walker.AddVisitor(typeTblSelectorNode, visitorA)
|
|
|
|
walker.AddVisitor(typeColSelectorNode, visitorB)
|
2016-10-17 07:14:01 +03:00
|
|
|
err = walker.Walk()
|
|
|
|
assert.Nil(t, err)
|
|
|
|
assert.Equal(t, 2, countA)
|
2023-03-22 09:17:34 +03:00
|
|
|
assert.Equal(t, 3, countB)
|
2016-10-17 07:14:01 +03:00
|
|
|
}
|