-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathexpr_format.go
1519 lines (1342 loc) · 44.3 KB
/
expr_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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 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 memo
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"unicode"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props"
"github.com/cockroachdb/cockroach/pkg/sql/opt/props/physical"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/treeprinter"
"github.com/cockroachdb/errors"
)
// ScalarFmtInterceptor is a callback that can be set to a custom formatting
// function. If the function returns a non-empty string, the normal formatting
// code is bypassed.
var ScalarFmtInterceptor func(f *ExprFmtCtx, expr opt.ScalarExpr) string
// ExprFmtFlags controls which properties of the expression are shown in
// formatted output.
type ExprFmtFlags int
const (
// ExprFmtShowAll shows all properties of the expression.
ExprFmtShowAll ExprFmtFlags = 0
// ExprFmtHideMiscProps does not show outer columns, row cardinality, provided
// orderings, side effects, or error text in the output.
ExprFmtHideMiscProps ExprFmtFlags = 1 << (iota - 1)
// ExprFmtHideConstraints does not show inferred constraints in the output.
ExprFmtHideConstraints
// ExprFmtHideFuncDeps does not show functional dependencies in the output.
ExprFmtHideFuncDeps
// ExprFmtHideRuleProps does not show rule-specific properties in the output.
ExprFmtHideRuleProps
// ExprFmtHideStats does not show statistics in the output.
ExprFmtHideStats
// ExprFmtHideCost does not show expression cost in the output.
ExprFmtHideCost
// ExprFmtHideQualifications removes the qualification from column labels
// (except when a shortened name would be ambiguous).
ExprFmtHideQualifications
// ExprFmtHideScalars removes subtrees that contain only scalars and replaces
// them with the SQL expression (if possible).
ExprFmtHideScalars
// ExprFmtHidePhysProps hides all required physical properties, except for
// Presentation (see ExprFmtHideColumns).
ExprFmtHidePhysProps
// ExprFmtHideTypes hides type information from columns and scalar
// expressions.
ExprFmtHideTypes
// ExprFmtHideNotNull hides the !null specifier from columns.
ExprFmtHideNotNull
// ExprFmtHideColumns removes column information.
ExprFmtHideColumns
// ExprFmtHideAll shows only the basic structure of the expression.
// Note: this flag should be used judiciously, as its meaning changes whenever
// we add more flags.
ExprFmtHideAll ExprFmtFlags = (1 << iota) - 1
)
// HasFlags tests whether the given flags are all set.
func (f ExprFmtFlags) HasFlags(subset ExprFmtFlags) bool {
return f&subset == subset
}
// FormatExpr returns a string representation of the given expression, formatted
// according to the specified flags.
func FormatExpr(e opt.Expr, flags ExprFmtFlags, mem *Memo, catalog cat.Catalog) string {
if catalog == nil {
// Automatically hide qualifications if we have no catalog.
flags |= ExprFmtHideQualifications
}
f := MakeExprFmtCtx(flags, mem, catalog)
f.FormatExpr(e)
return f.Buffer.String()
}
// ExprFmtCtx is passed as context to expression formatting functions, which
// need to know the formatting flags and memo in order to format. In addition,
// a reusable bytes buffer avoids unnecessary allocations.
type ExprFmtCtx struct {
Buffer *bytes.Buffer
// Flags controls how the expression is formatted.
Flags ExprFmtFlags
// Memo must contain any expression that is formatted.
Memo *Memo
// Catalog must be set unless the ExprFmtHideQualifications flag is set.
Catalog cat.Catalog
// nameGen is used to generate a unique name for each relational
// subexpression when Memo.saveTablesPrefix is non-empty. These names
// correspond to the tables that would be saved if the query were run
// with the session variable `save_tables_prefix` set to the same value.
nameGen *ExprNameGenerator
}
// MakeExprFmtCtx creates an expression formatting context from a new buffer.
func MakeExprFmtCtx(flags ExprFmtFlags, mem *Memo, catalog cat.Catalog) ExprFmtCtx {
return MakeExprFmtCtxBuffer(&bytes.Buffer{}, flags, mem, catalog)
}
// MakeExprFmtCtxBuffer creates an expression formatting context from an
// existing buffer.
func MakeExprFmtCtxBuffer(
buf *bytes.Buffer, flags ExprFmtFlags, mem *Memo, catalog cat.Catalog,
) ExprFmtCtx {
var nameGen *ExprNameGenerator
if mem != nil && mem.saveTablesPrefix != "" {
nameGen = NewExprNameGenerator(mem.saveTablesPrefix)
}
return ExprFmtCtx{Buffer: buf, Flags: flags, Memo: mem, Catalog: catalog, nameGen: nameGen}
}
// HasFlags tests whether the given flags are all set.
func (f *ExprFmtCtx) HasFlags(subset ExprFmtFlags) bool {
return f.Flags.HasFlags(subset)
}
// FormatExpr constructs a treeprinter view of the given expression for testing
// and debugging, according to the flags in this context.
func (f *ExprFmtCtx) FormatExpr(e opt.Expr) {
tp := treeprinter.New()
f.formatExpr(e, tp)
f.Buffer.Reset()
f.Buffer.WriteString(tp.String())
}
func (f *ExprFmtCtx) space() {
f.Buffer.WriteByte(' ')
}
func (f *ExprFmtCtx) formatExpr(e opt.Expr, tp treeprinter.Node) {
scalar, ok := e.(opt.ScalarExpr)
if ok {
f.formatScalar(scalar, tp)
} else {
f.formatRelational(e.(RelExpr), tp)
}
}
func (f *ExprFmtCtx) formatRelational(e RelExpr, tp treeprinter.Node) {
md := f.Memo.Metadata()
relational := e.Relational()
required := e.RequiredPhysical()
if required == nil {
// required can be nil before optimization has taken place.
required = physical.MinRequired
}
// Special cases for merge-join and lookup-join: we want the type of the join
// to show up first.
f.Buffer.Reset()
switch t := e.(type) {
case *MergeJoinExpr:
fmt.Fprintf(f.Buffer, "%v (merge)", t.JoinType)
case *LookupJoinExpr:
fmt.Fprintf(f.Buffer, "%v (lookup", t.JoinType)
FormatPrivate(f, e.Private(), required)
f.Buffer.WriteByte(')')
case *InvertedJoinExpr:
fmt.Fprintf(f.Buffer, "%v (inverted", t.JoinType)
FormatPrivate(f, e.Private(), required)
f.Buffer.WriteByte(')')
case *ZigzagJoinExpr:
fmt.Fprintf(f.Buffer, "%v (zigzag", opt.InnerJoinOp)
FormatPrivate(f, e.Private(), required)
f.Buffer.WriteByte(')')
case *ScanExpr, *PlaceholderScanExpr, *IndexJoinExpr, *ShowTraceForSessionExpr,
*InsertExpr, *UpdateExpr, *UpsertExpr, *DeleteExpr, *SequenceSelectExpr,
*WindowExpr, *OpaqueRelExpr, *OpaqueMutationExpr, *OpaqueDDLExpr,
*AlterTableSplitExpr, *AlterTableUnsplitExpr, *AlterTableUnsplitAllExpr,
*AlterTableRelocateExpr, *ControlJobsExpr, *CancelQueriesExpr,
*CancelSessionsExpr, *CreateViewExpr, *ExportExpr:
fmt.Fprintf(f.Buffer, "%v", e.Op())
FormatPrivate(f, e.Private(), required)
case *SortExpr:
if t.InputOrdering.Any() {
fmt.Fprintf(f.Buffer, "%v", e.Op())
} else {
fmt.Fprintf(f.Buffer, "%v (segmented)", e.Op())
}
case *WithExpr:
fmt.Fprintf(f.Buffer, "%v &%d", e.Op(), t.ID)
if t.Name != "" {
fmt.Fprintf(f.Buffer, " (%s)", t.Name)
}
case *WithScanExpr:
fmt.Fprintf(f.Buffer, "%v &%d", e.Op(), t.With)
if t.Name != "" {
fmt.Fprintf(f.Buffer, " (%s)", t.Name)
}
default:
fmt.Fprintf(f.Buffer, "%v", e.Op())
if opt.IsJoinNonApplyOp(t) {
// All join ops that weren't handled above execute as a hash join.
if leftEqCols, _ := ExtractJoinEqualityColumns(
e.Child(0).(RelExpr).Relational().OutputCols,
e.Child(1).(RelExpr).Relational().OutputCols,
*e.Child(2).(*FiltersExpr),
); len(leftEqCols) == 0 {
// The case where there are no equality columns is executed as a
// degenerate case of hash join; let's be explicit about that.
f.Buffer.WriteString(" (cross)")
} else {
f.Buffer.WriteString(" (hash)")
}
}
}
tp = tp.Child(f.Buffer.String())
if f.nameGen != nil {
name := f.nameGen.GenerateName(e.Op())
tp.Childf("save-table-name: %s", name)
}
var colList opt.ColList
// Special handling to improve the columns display for certain ops.
switch t := e.(type) {
case *ProjectExpr:
// We want the synthesized column IDs to map 1-to-1 to the projections,
// and the pass-through columns at the end.
// Get the list of columns from the ProjectionsOp, which has the natural
// order.
for i := range t.Projections {
colList = append(colList, t.Projections[i].Col)
}
// Add pass-through columns.
t.Passthrough.ForEach(func(i opt.ColumnID) {
colList = append(colList, i)
})
case *ValuesExpr:
colList = t.Cols
case *UnionExpr, *IntersectExpr, *ExceptExpr,
*UnionAllExpr, *IntersectAllExpr, *ExceptAllExpr, *LocalityOptimizedSearchExpr:
colList = e.Private().(*SetPrivate).OutCols
default:
// Fall back to writing output columns in column id order.
colList = e.Relational().OutputCols.ToList()
}
f.formatColumns(e, tp, colList, required.Presentation)
switch t := e.(type) {
// Special-case handling for GroupBy private; print grouping columns
// and internal ordering in addition to full set of columns.
case *GroupByExpr, *ScalarGroupByExpr, *DistinctOnExpr, *EnsureDistinctOnExpr,
*UpsertDistinctOnExpr, *EnsureUpsertDistinctOnExpr:
private := e.Private().(*GroupingPrivate)
if !f.HasFlags(ExprFmtHideColumns) && !private.GroupingCols.Empty() {
f.formatColList(e, tp, "grouping columns:", private.GroupingCols.ToList())
}
if !f.HasFlags(ExprFmtHidePhysProps) && !private.Ordering.Any() {
tp.Childf("internal-ordering: %s", private.Ordering)
}
if !f.HasFlags(ExprFmtHideMiscProps) && private.ErrorOnDup != "" {
tp.Childf("error: \"%s\"", private.ErrorOnDup)
}
case *LimitExpr:
if !f.HasFlags(ExprFmtHidePhysProps) && !t.Ordering.Any() {
tp.Childf("internal-ordering: %s", t.Ordering)
}
case *OffsetExpr:
if !f.HasFlags(ExprFmtHidePhysProps) && !t.Ordering.Any() {
tp.Childf("internal-ordering: %s", t.Ordering)
}
case *Max1RowExpr:
if !f.HasFlags(ExprFmtHideMiscProps) {
tp.Childf("error: \"%s\"", t.ErrorText)
}
// Special-case handling for set operators to show the left and right
// input columns that correspond to the output columns.
case *UnionExpr, *IntersectExpr, *ExceptExpr,
*UnionAllExpr, *IntersectAllExpr, *ExceptAllExpr, *LocalityOptimizedSearchExpr:
private := e.Private().(*SetPrivate)
if !f.HasFlags(ExprFmtHideColumns) {
f.formatColList(e, tp, "left columns:", private.LeftCols)
f.formatColList(e, tp, "right columns:", private.RightCols)
}
if !f.HasFlags(ExprFmtHidePhysProps) && !private.Ordering.Any() {
tp.Childf("internal-ordering: %s", private.Ordering)
}
case *ScanExpr, *PlaceholderScanExpr:
private := t.Private().(*ScanPrivate)
if t.Op() == opt.ScanOp && private.IsCanonical() {
// For the canonical scan, show the expressions attached to the TableMeta.
tab := md.TableMeta(private.Table)
if tab.Constraints != nil {
c := tp.Childf("check constraint expressions")
for i := 0; i < tab.Constraints.ChildCount(); i++ {
f.formatExpr(tab.Constraints.Child(i), c)
}
}
if len(tab.ComputedCols) > 0 {
c := tp.Childf("computed column expressions")
cols := make(opt.ColList, 0, len(tab.ComputedCols))
for col := range tab.ComputedCols {
cols = append(cols, col)
}
sort.Slice(cols, func(i, j int) bool {
return cols[i] < cols[j]
})
for _, col := range cols {
f.Buffer.Reset()
f.formatExpr(tab.ComputedCols[col], c.Child(f.ColumnString(col)))
}
}
partialIndexPredicates := tab.PartialIndexPredicatesUnsafe()
if partialIndexPredicates != nil {
c := tp.Child("partial index predicates")
indexOrds := make([]cat.IndexOrdinal, 0, len(partialIndexPredicates))
for ord := range partialIndexPredicates {
indexOrds = append(indexOrds, ord)
}
sort.Ints(indexOrds)
for _, ord := range indexOrds {
name := string(tab.Table.Index(ord).Name())
f.Buffer.Reset()
f.formatScalarWithLabel(name, partialIndexPredicates[ord], c)
}
}
}
if c := private.Constraint; c != nil {
if c.IsContradiction() {
tp.Childf("constraint: contradiction")
} else if c.Spans.Count() == 1 {
tp.Childf("constraint: %s: %s", c.Columns.String(), c.Spans.Get(0).String())
} else {
n := tp.Childf("constraint: %s", c.Columns.String())
for i := 0; i < c.Spans.Count(); i++ {
n.Child(c.Spans.Get(i).String())
}
}
}
if ic := private.InvertedConstraint; ic != nil {
idx := md.Table(private.Table).Index(private.Index)
var b strings.Builder
for i := idx.NonInvertedPrefixColumnCount(); i < idx.KeyColumnCount(); i++ {
b.WriteRune('/')
b.WriteString(fmt.Sprintf("%d", private.Table.ColumnID(idx.Column(i).Ordinal())))
}
n := tp.Childf("inverted constraint: %s", b.String())
ic.Format(n, "spans")
}
if private.HardLimit.IsSet() {
tp.Childf("limit: %s", private.HardLimit)
}
if !private.Flags.Empty() {
var b strings.Builder
if private.Flags.NoIndexJoin {
b.WriteString(" no-index-join")
} else if private.Flags.ForceIndex {
idx := md.Table(private.Table).Index(private.Flags.Index)
dir := ""
switch private.Flags.Direction {
case tree.DefaultDirection:
case tree.Ascending:
dir = ",fwd"
case tree.Descending:
dir = ",rev"
}
b.WriteString(fmt.Sprintf(" force-index=%s%s", idx.Name(), dir))
}
if private.Flags.NoZigzagJoin {
b.WriteString(" no-zigzag-join")
}
tp.Childf("flags:%s", b.String())
}
if private.Locking != nil {
strength := ""
switch private.Locking.Strength {
case tree.ForNone:
case tree.ForKeyShare:
strength = "for-key-share"
case tree.ForShare:
strength = "for-share"
case tree.ForNoKeyUpdate:
strength = "for-no-key-update"
case tree.ForUpdate:
strength = "for-update"
default:
panic(errors.AssertionFailedf("unexpected strength"))
}
wait := ""
switch private.Locking.WaitPolicy {
case tree.LockWaitBlock:
case tree.LockWaitSkip:
wait = ",skip-locked"
case tree.LockWaitError:
wait = ",nowait"
default:
panic(errors.AssertionFailedf("unexpected wait policy"))
}
tp.Childf("locking: %s%s", strength, wait)
}
case *InvertedFilterExpr:
var b strings.Builder
b.WriteRune('/')
b.WriteString(fmt.Sprintf("%d", t.InvertedColumn))
n := tp.Childf("inverted expression: %s", b.String())
t.InvertedExpression.Format(n, false /* includeSpansToRead */)
if t.PreFiltererState != nil {
n := tp.Childf("pre-filterer expression")
f.formatExpr(t.PreFiltererState.Expr, n)
}
case *LookupJoinExpr:
if !t.Flags.Empty() {
tp.Childf("flags: %s", t.Flags.String())
}
if !f.HasFlags(ExprFmtHideColumns) {
if len(t.KeyCols) > 0 {
idxCols := make(opt.ColList, len(t.KeyCols))
idx := md.Table(t.Table).Index(t.Index)
for i := range idxCols {
idxCols[i] = t.Table.ColumnID(idx.Column(i).Ordinal())
}
tp.Childf("key columns: %v = %v", t.KeyCols, idxCols)
}
if len(t.LookupExpr) > 0 {
n := tp.Childf("lookup expression")
f.formatExpr(&t.LookupExpr, n)
}
if len(t.RemoteLookupExpr) > 0 {
n := tp.Childf("remote lookup expression")
f.formatExpr(&t.RemoteLookupExpr, n)
}
}
if t.LookupColsAreTableKey {
tp.Childf("lookup columns are key")
}
if t.IsSecondJoinInPairedJoiner {
tp.Childf("second join in paired joiner")
}
case *InvertedJoinExpr:
if !t.Flags.Empty() {
tp.Childf("flags: %s", t.Flags.String())
}
if !f.HasFlags(ExprFmtHideColumns) && len(t.PrefixKeyCols) > 0 {
idxCols := make(opt.ColList, len(t.PrefixKeyCols))
idx := md.Table(t.Table).Index(t.Index)
for i := range idxCols {
idxCols[i] = t.Table.ColumnID(idx.Column(i).Ordinal())
}
tp.Childf("prefix key columns: %v = %v", t.PrefixKeyCols, idxCols)
}
if t.IsFirstJoinInPairedJoiner {
f.formatColList(e, tp, "first join in paired joiner; continuation column:", opt.ColList{t.ContinuationCol})
}
n := tp.Child("inverted-expr")
f.formatExpr(t.InvertedExpr, n)
case *ZigzagJoinExpr:
if !f.HasFlags(ExprFmtHideColumns) {
tp.Childf("eq columns: %v = %v", t.LeftEqCols, t.RightEqCols)
leftVals := make([]tree.Datum, len(t.LeftFixedCols))
rightVals := make([]tree.Datum, len(t.RightFixedCols))
// FixedVals is always going to be a ScalarListExpr, containing tuples,
// containing one ScalarListExpr, containing ConstExprs.
for i := range t.LeftFixedCols {
leftVals[i] = ExtractConstDatum(t.FixedVals[0].Child(0).Child(i))
}
for i := range t.RightFixedCols {
rightVals[i] = ExtractConstDatum(t.FixedVals[1].Child(0).Child(i))
}
tp.Childf("left fixed columns: %v = %v", t.LeftFixedCols, leftVals)
tp.Childf("right fixed columns: %v = %v", t.RightFixedCols, rightVals)
}
case *MergeJoinExpr:
if !t.Flags.Empty() {
tp.Childf("flags: %s", t.Flags.String())
}
if !f.HasFlags(ExprFmtHidePhysProps) {
tp.Childf("left ordering: %s", t.LeftEq)
tp.Childf("right ordering: %s", t.RightEq)
}
case *InsertExpr:
if !f.HasFlags(ExprFmtHideColumns) {
if len(colList) == 0 {
tp.Child("columns: <none>")
}
f.formatArbiterIndexes(tp, t.ArbiterIndexes, t.Table)
f.formatArbiterConstraints(tp, t.ArbiterConstraints, t.Table)
f.formatMutationCols(e, tp, "insert-mapping:", t.InsertCols, t.Table)
f.formatOptionalColList(e, tp, "check columns:", t.CheckCols)
f.formatOptionalColList(e, tp, "partial index put columns:", t.PartialIndexPutCols)
f.formatMutationCommon(tp, &t.MutationPrivate)
}
case *UpdateExpr:
if !f.HasFlags(ExprFmtHideColumns) {
if len(colList) == 0 {
tp.Child("columns: <none>")
}
f.formatOptionalColList(e, tp, "fetch columns:", t.FetchCols)
f.formatMutationCols(e, tp, "update-mapping:", t.UpdateCols, t.Table)
f.formatOptionalColList(e, tp, "check columns:", t.CheckCols)
f.formatOptionalColList(e, tp, "partial index put columns:", t.PartialIndexPutCols)
f.formatOptionalColList(e, tp, "partial index del columns:", t.PartialIndexDelCols)
f.formatMutationCommon(tp, &t.MutationPrivate)
}
case *UpsertExpr:
if !f.HasFlags(ExprFmtHideColumns) {
if len(colList) == 0 {
tp.Child("columns: <none>")
}
if t.CanaryCol != 0 {
f.formatArbiterIndexes(tp, t.ArbiterIndexes, t.Table)
f.formatArbiterConstraints(tp, t.ArbiterConstraints, t.Table)
f.formatColList(e, tp, "canary column:", opt.ColList{t.CanaryCol})
f.formatOptionalColList(e, tp, "fetch columns:", t.FetchCols)
f.formatMutationCols(e, tp, "insert-mapping:", t.InsertCols, t.Table)
f.formatMutationCols(e, tp, "update-mapping:", t.UpdateCols, t.Table)
f.formatMutationCols(e, tp, "return-mapping:", t.ReturnCols, t.Table)
} else {
f.formatMutationCols(e, tp, "upsert-mapping:", t.InsertCols, t.Table)
}
f.formatOptionalColList(e, tp, "check columns:", t.CheckCols)
f.formatOptionalColList(e, tp, "partial index put columns:", t.PartialIndexPutCols)
f.formatOptionalColList(e, tp, "partial index del columns:", t.PartialIndexDelCols)
f.formatMutationCommon(tp, &t.MutationPrivate)
}
case *DeleteExpr:
if !f.HasFlags(ExprFmtHideColumns) {
if len(colList) == 0 {
tp.Child("columns: <none>")
}
f.formatOptionalColList(e, tp, "fetch columns:", t.FetchCols)
f.formatOptionalColList(e, tp, "partial index del columns:", t.PartialIndexDelCols)
f.formatMutationCommon(tp, &t.MutationPrivate)
}
case *WithExpr:
if t.Mtr.Set {
if t.Mtr.Materialize {
tp.Child("materialized")
} else {
tp.Child("not-materialized")
}
}
case *WithScanExpr:
if !f.HasFlags(ExprFmtHideColumns) {
child := tp.Child("mapping:")
for i := range t.InCols {
f.Buffer.Reset()
f.space()
f.formatCol("" /* label */, t.InCols[i], opt.ColSet{} /* notNullCols */)
f.Buffer.WriteString(" => ")
f.formatCol("" /* label */, t.OutCols[i], opt.ColSet{} /* notNullCols */)
child.Child(f.Buffer.String())
}
}
case *CreateTableExpr:
tp.Child(t.Syntax.String())
case *CreateViewExpr:
tp.Child(t.ViewQuery)
f.Buffer.Reset()
f.Buffer.WriteString("columns:")
for _, col := range t.Columns {
f.space()
f.formatCol(col.Alias, col.ID, opt.ColSet{} /* notNullCols */)
}
tp.Child(f.Buffer.String())
n := tp.Child("dependencies")
for _, dep := range t.Deps {
f.Buffer.Reset()
name := dep.DataSource.Name()
f.Buffer.WriteString(name.String())
if dep.SpecificIndex {
fmt.Fprintf(f.Buffer, "@%s", dep.DataSource.(cat.Table).Index(dep.Index).Name())
}
colNames, isTable := dep.GetColumnNames()
if len(colNames) > 0 {
fmt.Fprintf(f.Buffer, " [columns:")
for _, colName := range colNames {
fmt.Fprintf(f.Buffer, " %s", colName)
}
fmt.Fprintf(f.Buffer, "]")
} else if isTable {
fmt.Fprintf(f.Buffer, " [no columns]")
}
n.Child(f.Buffer.String())
}
case *CreateStatisticsExpr:
tp.Child(t.Syntax.String())
case *ExportExpr:
tp.Childf("format: %s", t.FileFormat)
case *ExplainExpr:
// ExplainPlan is the default, don't show it.
m := ""
if t.Options.Mode != tree.ExplainPlan {
m = strings.ToLower(t.Options.Mode.String())
}
if t.Options.Flags[tree.ExplainFlagVerbose] {
if m != "" {
m += ", "
}
m += "verbose"
}
if m != "" {
tp.Childf("mode: %s", m)
}
case *RecursiveCTEExpr:
if !f.HasFlags(ExprFmtHideColumns) {
tp.Childf("working table binding: &%d", t.WithID)
f.formatColList(e, tp, "initial columns:", t.InitialCols)
f.formatColList(e, tp, "recursive columns:", t.RecursiveCols)
}
default:
if opt.IsJoinOp(t) {
p := t.Private().(*JoinPrivate)
if !p.Flags.Empty() {
tp.Childf("flags: %s", p.Flags.String())
}
}
}
if !f.HasFlags(ExprFmtHideMiscProps) {
if !relational.OuterCols.Empty() {
tp.Childf("outer: %s", relational.OuterCols.String())
}
if relational.Cardinality != props.AnyCardinality {
// Suppress cardinality for Scan ops if it's redundant with Limit field.
if scan, ok := e.(*ScanExpr); !ok || !scan.HardLimit.IsSet() {
tp.Childf("cardinality: %s", relational.Cardinality)
}
}
if join, ok := e.(joinWithMultiplicity); ok {
mult := join.getMultiplicity()
if s := mult.Format(e.Op()); s != "" {
tp.Childf("multiplicity: %s", s)
}
}
f.Buffer.Reset()
writeFlag := func(name string) {
if f.Buffer.Len() != 0 {
f.Buffer.WriteString(", ")
}
f.Buffer.WriteString(name)
}
if !relational.VolatilitySet.IsLeakProof() {
writeFlag(relational.VolatilitySet.String())
}
if relational.CanMutate {
writeFlag("mutations")
}
if relational.HasPlaceholder {
writeFlag("has-placeholder")
}
if f.Buffer.Len() != 0 {
tp.Child(f.Buffer.String())
}
}
if !f.HasFlags(ExprFmtHideStats) {
tp.Childf("stats: %s", &relational.Stats)
}
if !f.HasFlags(ExprFmtHideCost) {
cost := e.Cost()
if cost != 0 {
tp.Childf("cost: %.9g", cost)
}
}
// Format functional dependencies.
if !f.HasFlags(ExprFmtHideFuncDeps) {
// Show the key separately from the rest of the FDs.
if key, ok := relational.FuncDeps.StrictKey(); ok {
tp.Childf("key: %s", key)
} else if key, ok := relational.FuncDeps.LaxKey(); ok {
tp.Childf("lax-key: %s", key)
}
if fdStr := relational.FuncDeps.StringOnlyFDs(); fdStr != "" {
tp.Childf("fd: %s", fdStr)
}
}
if !f.HasFlags(ExprFmtHidePhysProps) {
if !required.Ordering.Any() {
if f.HasFlags(ExprFmtHideMiscProps) {
tp.Childf("ordering: %s", required.Ordering.String())
} else {
// Show the provided ordering as well, unless it's exactly the same.
provided := e.ProvidedPhysical().Ordering
reqStr := required.Ordering.String()
provStr := provided.String()
if provStr == reqStr {
tp.Childf("ordering: %s", reqStr)
} else {
tp.Childf("ordering: %s [actual: %s]", reqStr, provStr)
}
}
}
if required.LimitHint != 0 {
tp.Childf("limit hint: %.2f", required.LimitHint)
}
}
if !f.HasFlags(ExprFmtHideRuleProps) {
r := &relational.Rule
if !r.PruneCols.Empty() {
tp.Childf("prune: %s", r.PruneCols.String())
}
if !r.RejectNullCols.Empty() {
tp.Childf("reject-nulls: %s", r.RejectNullCols.String())
}
if len(r.InterestingOrderings) > 0 {
tp.Childf("interesting orderings: %s", r.InterestingOrderings.String())
}
if !r.UnfilteredCols.Empty() {
tp.Childf("unfiltered-cols: %s", r.UnfilteredCols.String())
}
if withUses := relational.Shared.Rule.WithUses; len(withUses) > 0 {
n := tp.Childf("cte-uses")
ids := make([]opt.WithID, 0, len(withUses))
for id := range withUses {
ids = append(ids, id)
}
sort.Slice(ids, func(i, j int) bool {
return ids[i] < ids[j]
})
for _, id := range ids {
info := withUses[id]
n.Childf("&%d: count=%d used-columns=%s", id, info.Count, info.UsedCols)
}
}
}
switch t := e.(type) {
case *CreateTableExpr:
// Do not print dummy input expression if there was no AS clause.
if !t.Syntax.As() {
return
}
case *PlaceholderScanExpr:
// Show the child scalar expressions under a "span" heading.
tp = tp.Childf("span")
}
for i, n := 0, e.ChildCount(); i < n; i++ {
f.formatExpr(e.Child(i), tp)
}
}
func (f *ExprFmtCtx) formatScalar(scalar opt.ScalarExpr, tp treeprinter.Node) {
f.formatScalarWithLabel("", scalar, tp)
}
func (f *ExprFmtCtx) formatScalarWithLabel(
label string, scalar opt.ScalarExpr, tp treeprinter.Node,
) {
f.Buffer.Reset()
if label != "" {
f.Buffer.WriteString(label)
f.Buffer.WriteString(": ")
}
switch scalar.Op() {
case opt.ProjectionsOp, opt.AggregationsOp, opt.UniqueChecksOp, opt.FKChecksOp, opt.KVOptionsOp:
// Omit empty lists (except filters).
if scalar.ChildCount() == 0 {
return
}
case opt.FiltersOp:
// Show empty Filters expression as "filters (true)".
if scalar.ChildCount() == 0 {
f.Buffer.WriteString("filters (true)")
tp.Child(f.Buffer.String())
return
}
case opt.IfErrOp:
fmt.Fprintf(f.Buffer, "%v", scalar.Op())
f.FormatScalarProps(scalar)
tp = tp.Child(f.Buffer.String())
f.formatExpr(scalar.Child(0), tp)
if scalar.Child(1).ChildCount() > 0 {
f.formatExpr(scalar.Child(1), tp.Child("else"))
}
if scalar.Child(2).ChildCount() > 0 {
f.formatExpr(scalar.Child(2), tp.Child("err-code"))
}
return
case opt.AggFilterOp:
fmt.Fprintf(f.Buffer, "%v", scalar.Op())
f.FormatScalarProps(scalar)
tp = tp.Child(f.Buffer.String())
f.formatExpr(scalar.Child(0), tp)
f.formatExpr(scalar.Child(1), tp.Child("filter"))
return
case opt.ScalarListOp:
// Don't show scalar-list as a separate node, as it's redundant with its
// parent.
for i, n := 0, scalar.ChildCount(); i < n; i++ {
f.formatExpr(scalar.Child(i), tp)
}
return
}
// Omit various list items from the output, but show some of their properties
// along with the properties of their child.
var scalarProps []string
switch scalar.Op() {
case opt.FiltersItemOp, opt.ProjectionsItemOp, opt.AggregationsItemOp,
opt.ZipItemOp, opt.WindowsItemOp:
emitProp := func(format string, args ...interface{}) {
scalarProps = append(scalarProps, fmt.Sprintf(format, args...))
}
switch item := scalar.(type) {
case *ProjectionsItem:
if !f.HasFlags(ExprFmtHideColumns) {
emitProp("as=%s", f.ColumnString(item.Col))
}
case *AggregationsItem:
if !f.HasFlags(ExprFmtHideColumns) {
emitProp("as=%s", f.ColumnString(item.Col))
}
case *ZipItem:
// TODO(radu): show the item.Cols
case *WindowsItem:
if !f.HasFlags(ExprFmtHideColumns) {
emitProp("as=%s", f.ColumnString(item.Col))
}
// Only show the frame if it differs from the default.
def := WindowFrame{
Mode: tree.RANGE,
StartBoundType: tree.UnboundedPreceding,
EndBoundType: tree.CurrentRow,
FrameExclusion: tree.NoExclusion,
}
if item.Frame != def {
emitProp("frame=%q", item.Frame.String())
}
}
scalarProps = append(scalarProps, f.scalarPropsStrings(scalar)...)
scalar = scalar.Child(0).(opt.ScalarExpr)
default:
scalarProps = f.scalarPropsStrings(scalar)
}
var intercepted bool
if f.HasFlags(ExprFmtHideScalars) && ScalarFmtInterceptor != nil {
if str := ScalarFmtInterceptor(f, scalar); str != "" {
f.Buffer.WriteString(str)
intercepted = true
}
}
if !intercepted {
fmt.Fprintf(f.Buffer, "%v", scalar.Op())
f.formatScalarPrivate(scalar)
}
if len(scalarProps) != 0 {
f.Buffer.WriteString(" [")
f.Buffer.WriteString(strings.Join(scalarProps, ", "))
f.Buffer.WriteByte(']')
}
tp = tp.Child(f.Buffer.String())
if !intercepted {
for i, n := 0, scalar.ChildCount(); i < n; i++ {
f.formatExpr(scalar.Child(i), tp)
}
}
}
// scalarPropsStrings returns a slice of strings, each describing a property;
// for example:
// {"type=bool", "outer=(1)", "constraints=(/1: [/1 - /1]; tight)"}
func (f *ExprFmtCtx) scalarPropsStrings(scalar opt.ScalarExpr) []string {
typ := scalar.DataType()
if typ == nil {
if scalar.Op() == opt.UniqueChecksItemOp || scalar.Op() == opt.FKChecksItemOp ||
scalar.Op() == opt.KVOptionsItemOp {
// These are not true scalars and have no properties.
return nil
}
// Don't panic if scalar properties don't yet exist when printing
// expression.
return []string{"type=undefined"}
}
var res []string
emitProp := func(format string, args ...interface{}) {
res = append(res, fmt.Sprintf(format, args...))
}
if !f.HasFlags(ExprFmtHideTypes) && typ.Family() != types.AnyFamily {
emitProp("type=%s", typ)
}
if propsExpr, ok := scalar.(ScalarPropsExpr); ok {
scalarProps := propsExpr.ScalarProps()
if !f.HasFlags(ExprFmtHideMiscProps) {
if !scalarProps.OuterCols.Empty() {
emitProp("outer=%s", scalarProps.OuterCols)
}
if !scalarProps.VolatilitySet.IsLeakProof() {
emitProp(scalarProps.VolatilitySet.String())
}
if scalarProps.HasCorrelatedSubquery {
emitProp("correlated-subquery")
} else if scalarProps.HasSubquery {
emitProp("subquery")
}
}
if !f.HasFlags(ExprFmtHideConstraints) {
if scalarProps.Constraints != nil && !scalarProps.Constraints.IsUnconstrained() {
var tight string
if scalarProps.TightConstraints {
tight = "; tight"
}
emitProp("constraints=(%s%s)", scalarProps.Constraints, tight)
}
}