From 15803e386124e2545530d0d19fbd6e86b42c1903 Mon Sep 17 00:00:00 2001 From: lucklove Date: Mon, 23 Sep 2019 16:36:52 +0800 Subject: [PATCH] executor: fix unordered trace events in row format The trace statement can print out a trace tree, however, in row format, the tree is unordered, where earlier events may be placed behind. Signed-off-by: lucklove --- executor/trace.go | 13 +++++++++++++ executor/trace_test.go | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/executor/trace.go b/executor/trace.go index 91acb341928c5..41744820642b7 100644 --- a/executor/trace.go +++ b/executor/trace.go @@ -17,6 +17,7 @@ import ( "context" "encoding/json" "fmt" + "sort" "time" "github.com/opentracing/basictracer-go" @@ -199,6 +200,18 @@ func dfsTree(t *appdash.Trace, prefix string, isLast bool, chk *chunk.Chunk) { chk.AppendString(1, start.Format("15:04:05.000000")) chk.AppendString(2, duration.String()) + // Sort events by their start time + sort.Slice(t.Sub, func(i, j int) bool { + var istart, jstart time.Time + if ievent, err := t.Sub[i].TimespanEvent(); err == nil { + istart = ievent.Start() + } + if jevent, err := t.Sub[j].TimespanEvent(); err == nil { + jstart = jevent.Start() + } + return istart.Before(jstart) + }) + for i, sp := range t.Sub { dfsTree(sp, newPrefix, i == (len(t.Sub))-1 /*last element of array*/, chk) } diff --git a/executor/trace_test.go b/executor/trace_test.go index fb2edfa687958..70bdcc35aa056 100644 --- a/executor/trace_test.go +++ b/executor/trace_test.go @@ -40,11 +40,28 @@ func (s *testSuite1) TestTraceExec(c *C) { // +---------------------------+-----------------+------------+ rows = tk.MustQuery("trace format='row' select * from trace where id = 0;").Rows() c.Assert(len(rows) > 1, IsTrue) + c.Assert(rowsOrdered(rows), IsTrue) rows = tk.MustQuery("trace format='row' delete from trace where id = 0").Rows() c.Assert(len(rows) > 1, IsTrue) + c.Assert(rowsOrdered(rows), IsTrue) tk.MustExec("trace format='log' insert into trace (c1, c2, c3) values (1, 2, 3)") rows = tk.MustQuery("trace format='log' select * from trace where id = 0;").Rows() c.Assert(len(rows), GreaterEqual, 1) } + +func rowsOrdered(rows [][]interface{}) bool { + for idx := range rows { + if _, ok := rows[idx][1].(string); !ok { + return false + } + if idx == 0 { + continue + } + if rows[idx-1][1].(string) > rows[idx][1].(string) { + return false + } + } + return true +}