-
Notifications
You must be signed in to change notification settings - Fork 153
/
format.go
98 lines (85 loc) · 2.34 KB
/
format.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
package plan
import (
"fmt"
"runtime/debug"
"strings"
)
type FormatOption func(*formatter)
// Formatted accepts a plan.Spec and options, and returns a Formatter
// that can be used with the standard fmt package, e.g.,
//
// fmt.Println(Formatted(plan, WithDetails())
func Formatted(p *Spec, opts ...FormatOption) fmt.Formatter {
f := formatter{
p: p,
}
for _, o := range opts {
o(&f)
}
return f
}
// WithDetails returns a FormatOption that can be used to provide extra details
// in a formatted plan.
func WithDetails() FormatOption {
return func(f *formatter) {
f.withDetails = true
}
}
// Detailer provides an optional interface that ProcedureSpecs can implement.
// Implementors of this interface will have their details appear in the
// formatted output for a plan if the WithDetails() option is set.
type Detailer interface {
PlanDetails() string
}
type formatter struct {
withDetails bool
p *Spec
}
func formatAsDOT(id NodeID) string {
// The DOT language does not allow "." or "/" in IDs
// so quote the node IDs.
return fmt.Sprintf("%q", id)
}
func (f formatter) Format(fs fmt.State, c rune) {
// Panicking while producing debug output is frustrating, so catch any panics and
// continue if that happens.
defer func() {
if e := recover(); e != nil {
_, _ = fmt.Fprintf(fs, "panic while formatting plan: %v\n", e)
_, _ = fmt.Fprintf(fs, "stack: %s\n", string(debug.Stack()))
}
}()
_, _ = fmt.Fprintf(fs, "digraph {\n")
var edges []string
_ = f.p.BottomUpWalk(func(pn Node) error {
_, _ = fmt.Fprintf(fs, " %v\n", formatAsDOT(pn.ID()))
if f.withDetails {
details := ""
if d, ok := pn.ProcedureSpec().(Detailer); ok {
details += d.PlanDetails() + "\n"
}
if ppn, ok := pn.(*PhysicalPlanNode); ok {
for _, attr := range ppn.outputAttrs() {
if d, ok := attr.(Detailer); ok {
details += d.PlanDetails() + "\n"
}
}
}
lines := strings.Split(strings.TrimSpace(details), "\n")
for _, line := range lines {
if len(line) > 0 {
_, _ = fmt.Fprintf(fs, " // %s\n", line)
}
}
}
for _, pred := range pn.Predecessors() {
edges = append(edges, fmt.Sprintf(" %v -> %v", formatAsDOT(pred.ID()), formatAsDOT(pn.ID())))
}
return nil
})
_, _ = fmt.Fprintf(fs, "\n")
for _, e := range edges {
_, _ = fmt.Fprintf(fs, "%v\n", e)
}
_, _ = fmt.Fprintf(fs, "}\n")
}