-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathoutput_test.go
235 lines (213 loc) · 7.24 KB
/
output_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Copyright 2020 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package explain_test
import (
"context"
"fmt"
"regexp"
"strings"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec/explain"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/datapathutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/encoding"
"github.com/cockroachdb/cockroach/pkg/util/grunning"
"github.com/cockroachdb/datadriven"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
yaml "gopkg.in/yaml.v2"
)
func TestOutputBuilder(t *testing.T) {
example := func(flags explain.Flags) *explain.OutputBuilder {
ob := explain.NewOutputBuilder(flags)
ob.AddField("distributed", "true")
ob.EnterMetaNode("meta")
{
ob.EnterNode(
"render",
colinfo.ResultColumns{{Name: "a", Typ: types.Int}, {Name: "b", Typ: types.String}},
colinfo.ColumnOrdering{
{ColIdx: 0, Direction: encoding.Ascending},
{ColIdx: 1, Direction: encoding.Descending},
},
)
ob.AddField("render 0", "foo")
ob.AddField("render 1", "bar")
{
ob.EnterNode("join", colinfo.ResultColumns{{Name: "x", Typ: types.Int}}, nil)
ob.AddField("type", "outer")
{
{
ob.EnterNode("scan", colinfo.ResultColumns{{Name: "x", Typ: types.Int}}, nil)
ob.AddField("table", "foo")
ob.LeaveNode()
}
{
ob.EnterNode("scan", nil, nil) // Columns should show up as "()".
ob.AddField("table", "bar")
ob.LeaveNode()
}
}
ob.LeaveNode()
}
ob.LeaveNode()
}
ob.LeaveNode()
return ob
}
datadriven.RunTest(t, datapathutils.TestDataPath(t, "output"), func(t *testing.T, d *datadriven.TestData) string {
var flags explain.Flags
for _, arg := range d.CmdArgs {
switch arg.Key {
case "verbose":
flags.Verbose = true
case "types":
flags.Verbose = true
flags.ShowTypes = true
default:
panic(fmt.Sprintf("unknown argument %s", arg.Key))
}
}
ob := example(flags)
switch d.Cmd {
case "string":
return ob.BuildString()
case "tree":
treeYaml, err := yaml.Marshal(ob.BuildProtoTree())
if err != nil {
panic(err)
}
return string(treeYaml)
default:
panic(fmt.Sprintf("unknown command %s", d.Cmd))
}
})
}
func TestEmptyOutputBuilder(t *testing.T) {
ob := explain.NewOutputBuilder(explain.Flags{Verbose: true})
if str := ob.BuildString(); str != "" {
t.Errorf("expected empty string, got '%s'", str)
}
if rows := ob.BuildStringRows(); len(rows) != 0 {
t.Errorf("expected no rows, got %v", rows)
}
}
func TestMaxDiskSpillUsage(t *testing.T) {
testClusterArgs := base.TestClusterArgs{
ReplicationMode: base.ReplicationAuto,
}
distSQLKnobs := &execinfra.TestingKnobs{}
distSQLKnobs.ForceDiskSpill = true
testClusterArgs.ServerArgs.Knobs.DistSQL = distSQLKnobs
testClusterArgs.ServerArgs.Insecure = true
serverutils.InitTestServerFactory(server.TestServerFactory)
tc := testcluster.StartTestCluster(t, 1, testClusterArgs)
ctx := context.Background()
defer tc.Stopper().Stop(ctx)
conn := tc.Conns[0]
_, err := conn.ExecContext(ctx, `
CREATE TABLE t (a PRIMARY KEY, b) AS SELECT i, i FROM generate_series(1, 10) AS g(i)
`)
assert.NoError(t, err)
maxDiskUsageRE := regexp.MustCompile(`max sql temp disk usage: (\d+)`)
queryMatchRE := func(query string, re *regexp.Regexp) bool {
rows, err := conn.QueryContext(ctx, query)
assert.NoError(t, err)
for rows.Next() {
var res string
assert.NoError(t, rows.Scan(&res))
var sb strings.Builder
sb.WriteString(res)
sb.WriteByte('\n')
if matches := re.FindStringSubmatch(res); len(matches) > 0 {
return true
}
}
return false
}
// We are expecting disk spilling to show up because we enabled ForceDiskSpill
// knob above.
assert.True(t, queryMatchRE(`EXPLAIN ANALYZE (VERBOSE, DISTSQL) select * from t join t AS x on t.b=x.a`, maxDiskUsageRE), "didn't find max sql temp disk usage: in explain")
assert.False(t, queryMatchRE(`EXPLAIN ANALYZE (VERBOSE, DISTSQL) select * from t `, maxDiskUsageRE), "found unexpected max sql temp disk usage: in explain")
}
func TestCPUTimeEndToEnd(t *testing.T) {
if !grunning.Supported() {
return
}
testClusterArgs := base.TestClusterArgs{
ReplicationMode: base.ReplicationAuto,
}
distSQLKnobs := &execinfra.TestingKnobs{}
distSQLKnobs.ForceDiskSpill = true
testClusterArgs.ServerArgs.Knobs.DistSQL = distSQLKnobs
testClusterArgs.ServerArgs.Insecure = true
const numNodes = 3
serverutils.InitTestServerFactory(server.TestServerFactory)
tc := testcluster.StartTestCluster(t, numNodes, testClusterArgs)
ctx := context.Background()
defer tc.Stopper().Stop(ctx)
db := sqlutils.MakeSQLRunner(tc.Conns[0])
runQuery := func(query string, hideCPU bool) {
rows := db.QueryStr(t, "EXPLAIN ANALYZE "+query)
var err error
var foundCPU bool
var cpuTime time.Duration
for _, row := range rows {
if len(row) != 1 {
t.Fatalf("expected one column")
}
if strings.Contains(row[0], "sql cpu time") {
foundCPU = true
cpuStr := strings.Split(row[0], " ")
require.Equal(t, len(cpuStr), 4)
cpuTime, err = time.ParseDuration(cpuStr[3])
require.NoError(t, err)
break
}
}
if hideCPU {
require.Falsef(t, foundCPU, "expected not to output CPU time for query: %s", query)
} else {
require.NotZerof(t, cpuTime, "expected nonzero CPU time for query: %s", query)
}
}
// Mutation queries shouldn't output CPU time.
runQuery("CREATE TABLE t (x INT PRIMARY KEY, y INT);", true /* hideCPU */)
runQuery("INSERT INTO t (SELECT t, t%127 FROM generate_series(1, 10000) g(t));", true /* hideCPU */)
// Split the table across the nodes in order to make the following test cases
// more interesting.
for _, stmt := range []string{
`ALTER TABLE t SPLIT AT VALUES (2500)`,
`ALTER TABLE t SPLIT AT VALUES (5000)`,
`ALTER TABLE t SPLIT AT VALUES (7500)`,
`ALTER TABLE t EXPERIMENTAL_RELOCATE VALUES (ARRAY[1], 2500)`,
`ALTER TABLE t EXPERIMENTAL_RELOCATE VALUES (ARRAY[2], 5000)`,
`ALTER TABLE t EXPERIMENTAL_RELOCATE VALUES (ARRAY[3], 7500)`,
} {
testutils.SucceedsSoon(t, func() error {
_, err := db.DB.ExecContext(ctx, stmt)
return err
})
}
runQuery("SELECT * FROM t;", false /* hideCPU */)
runQuery("SELECT count(*) FROM t;", false /* hideCPU */)
runQuery("SELECT * FROM (SELECT * FROM t WHERE x > 2000 AND x < 3000) s1 JOIN t ON s1.x = t.x", false /* hideCPU */)
runQuery("SELECT * FROM (VALUES (1), (2), (3)) v(a) INNER LOOKUP JOIN t ON a = x", false /* hideCPU */)
runQuery("SELECT count(*) FROM generate_series(1, 100000)", false /* hideCPU */)
}