-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
opt_tester.go
2330 lines (2097 loc) · 70.2 KB
/
opt_tester.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 opttester
import (
"bytes"
"compress/zlib"
"context"
gosql "database/sql"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"math"
"net/url"
"os"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"testing"
"text/tabwriter"
"time"
"github.com/cockroachdb/cockroach/pkg/build/bazel"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemaexpr"
"github.com/cockroachdb/cockroach/pkg/sql/opt"
"github.com/cockroachdb/cockroach/pkg/sql/opt/cat"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec/execbuilder"
"github.com/cockroachdb/cockroach/pkg/sql/opt/indexrec"
"github.com/cockroachdb/cockroach/pkg/sql/opt/memo"
"github.com/cockroachdb/cockroach/pkg/sql/opt/norm"
"github.com/cockroachdb/cockroach/pkg/sql/opt/optbuilder"
"github.com/cockroachdb/cockroach/pkg/sql/opt/optgen/exprgen"
"github.com/cockroachdb/cockroach/pkg/sql/opt/ordering"
"github.com/cockroachdb/cockroach/pkg/sql/opt/testutils/testcat"
"github.com/cockroachdb/cockroach/pkg/sql/opt/xform"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/volatility"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/treeprinter"
"github.com/cockroachdb/datadriven"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/pmezard/go-difflib/difflib"
)
const rewriteActualFlag = "rewrite-actual-stats"
var (
rewriteActualStats = flag.Bool(
rewriteActualFlag, false,
"used to update the actual statistics for statistics quality tests. If true, the opttester "+
"will actually run the test queries to calculate actual statistics for comparison with the "+
"estimated stats.",
)
pgurl = flag.String(
"pgurl", "postgresql://localhost:26257/?sslmode=disable&user=root",
"the database url to connect to",
)
formatFlags = map[string]memo.ExprFmtFlags{
"miscprops": memo.ExprFmtHideMiscProps,
"constraints": memo.ExprFmtHideConstraints,
"funcdeps": memo.ExprFmtHideFuncDeps,
"ruleprops": memo.ExprFmtHideRuleProps,
"stats": memo.ExprFmtHideStats,
"hist": memo.ExprFmtHideHistograms,
"cost": memo.ExprFmtHideCost,
"qual": memo.ExprFmtHideQualifications,
"scalars": memo.ExprFmtHideScalars,
"physprops": memo.ExprFmtHidePhysProps,
"types": memo.ExprFmtHideTypes,
"notnull": memo.ExprFmtHideNotNull,
"columns": memo.ExprFmtHideColumns,
"all": memo.ExprFmtHideAll,
"notvisibleindex": memo.ExprFmtHideNotVisibleIndexInfo,
}
)
// RuleSet efficiently stores an unordered set of RuleNames.
type RuleSet = util.FastIntSet
// OptTester is a helper for testing the various optimizer components. It
// contains the boiler-plate code for the following useful tasks:
// - Build an unoptimized opt expression tree
// - Build an optimized opt expression tree
// - Format the optimizer memo structure
// - Create a diff showing the optimizer's work, step-by-step
// - Build the exec node tree
// - Execute the exec node tree
//
// The OptTester is used by tests in various sub-packages of the opt package.
type OptTester struct {
Flags Flags
catalog cat.Catalog
sql string
ctx context.Context
semaCtx tree.SemaContext
evalCtx eval.Context
appliedRules RuleSet
builder strings.Builder
}
// Flags are control knobs for tests. Note that specific testcases can
// override these defaults.
type Flags struct {
// ExprFormat controls the output detail of build / opt/ optsteps command
// directives.
ExprFormat memo.ExprFmtFlags
// MemoFormat controls the output detail of memo command directives.
MemoFormat xform.FmtFlags
// FullyQualifyNames if set: when building a query, the optbuilder fully
// qualifies all column names before adding them to the metadata. This flag
// allows us to test that name resolution works correctly, and avoids
// cluttering test output with schema and catalog names in the general case.
FullyQualifyNames bool
// Verbose indicates whether verbose test debugging information will be
// output to stdout when commands run. Only certain commands support this.
Verbose bool
// DisableRules is a set of rules that are not allowed to run.
DisableRules RuleSet
// ExploreTraceRule restricts the ExploreTrace output to only show the effects
// of a specific rule.
ExploreTraceRule opt.RuleName
// ExploreTraceSkipNoop hides the ExploreTrace output for instances of rules
// that fire but don't add any new expressions to the memo.
ExploreTraceSkipNoop bool
// ExpectedRules is a set of rules which must be exercised for the test to
// pass.
ExpectedRules RuleSet
// UnexpectedRules is a set of rules which must not be exercised for the test
// to pass.
UnexpectedRules RuleSet
// ColStats is a list of ColSets for which a column statistic is requested.
ColStats []opt.ColSet
// PerturbCost indicates how much to randomly perturb the cost. It is used
// to generate alternative plans for testing. For example, if PerturbCost is
// 0.5, and the estimated cost of an expression is c, the cost returned by
// the coster will be in the range [c - 0.5 * c, c + 0.5 * c).
PerturbCost float64
// JoinLimit is the default value for SessionData.ReorderJoinsLimit.
JoinLimit int
// PreferLookupJoinsForFK is the default value for
// SessionData.PreferLookupJoinsForFKs.
PreferLookupJoinsForFKs bool
// PropagateInputOrdering is the default value for
// SessionData.PropagateInputOrdering.
PropagateInputOrdering bool
// NullOrderedLast is the default value for
// SessionData.NullOrderedLast.
NullOrderedLast bool
// Locality specifies the location of the planning node as a set of user-
// defined key/value pairs, ordered from most inclusive to least inclusive.
// If there are no tiers, then the node's location is not known. Examples:
//
// [region=eu]
// [region=us,dc=east]
//
Locality roachpb.Locality
// Database specifies the current database to use for the query. This field
// is only used by the stats-quality command when rewriteActualFlag=true.
Database string
// Table specifies the current table to use for the command. This field is
// only used by the inject-stats commands.
Table string
// SaveTablesPrefix specifies the prefix of the table to create or print
// for each subexpression in the query.
SaveTablesPrefix string
// IgnoreTables specifies the subset of stats tables which should not be
// outputted by the stats-quality command.
IgnoreTables util.FastIntSet
// File specifies the name of the file to import. This field is only used by
// the import command.
File string
// CascadeLevels limits the depth of recursive cascades for build-cascades.
CascadeLevels int
// NoStableFolds controls whether constant folding for normalization includes
// stable operators.
NoStableFolds bool
// IndexVersion controls the version of the index descriptor created in the
// test catalog. This field is only used by the exec-ddl command for CREATE
// INDEX statements.
IndexVersion descpb.IndexDescriptorVersion
// OptStepsSplitDiff, if true, replaces the unified diff output of the
// optsteps command with a split diff where the before and after expressions
// are printed in their entirety. The default value is false.
OptStepsSplitDiff bool
// RuleApplicationLimit is used by the check-size command to check whether
// more than RuleApplicationLimit rules are applied during optimization.
RuleApplicationLimit int64
// MemoGroupLimit is used by the check-size command to check whether
// more than MemoGroupLimit memo groups are constructed during optimization.
MemoGroupLimit int64
// SuppressSizeCheckReport is used by the check-size command to disable
// printing of the number of rules applied or memo groups constructed so that
// it can be used as an upper-bound sanity check and not a requirement for an
// exact number of rules or memo groups.
SuppressSizeCheckReport bool
// QueryArgs are values for placeholders, used for assign-placeholders-*.
QueryArgs []string
// UseMultiColStats is the value for SessionData.OptimizerUseMultiColStats.
// It defaults to true in New.
UseMultiColStats bool
// SkipRace indicates that a test should be skipped if the race detector is
// enabled.
SkipRace bool
// ot is a reference to the OptTester owning Flags.
ot *OptTester
}
// New constructs a new instance of the OptTester for the given SQL statement.
// Metadata used by the SQL query is accessed via the catalog.
func New(catalog cat.Catalog, sql string) *OptTester {
ctx := context.Background()
ot := &OptTester{
Flags: Flags{JoinLimit: opt.DefaultJoinOrderLimit, UseMultiColStats: true},
catalog: catalog,
sql: sql,
ctx: ctx,
semaCtx: tree.MakeSemaContext(),
evalCtx: eval.MakeTestingEvalContext(cluster.MakeTestingClusterSettings()),
}
ot.Flags.ot = ot
ot.semaCtx.SearchPath = tree.EmptySearchPath
ot.semaCtx.FunctionResolver = ot.catalog
// To allow opttester tests to use now(), we hardcode a preset transaction
// time. May 10, 2017 is a historic day: the release date of CockroachDB 1.0.
ot.evalCtx.TxnTimestamp = time.Date(2017, 05, 10, 13, 0, 0, 0, time.UTC)
// Set any OptTester-wide session flags here.
ot.evalCtx.SessionData().UserProto = username.MakeSQLUsernameFromPreNormalizedString("opttester").EncodeProto()
ot.evalCtx.SessionData().Database = "defaultdb"
ot.evalCtx.SessionData().ZigzagJoinEnabled = true
ot.evalCtx.SessionData().OptimizerUseHistograms = true
ot.evalCtx.SessionData().LocalityOptimizedSearch = true
ot.evalCtx.SessionData().ReorderJoinsLimit = opt.DefaultJoinOrderLimit
ot.evalCtx.SessionData().InsertFastPath = true
return ot
}
// RunCommand implements commands that are used by most tests:
//
// - exec-ddl
//
// Runs a SQL DDL statement to build the test catalog. Only a small number
// of DDL statements are supported, and those not fully. This is only
// available when using a TestCatalog.
//
// - build [flags]
//
// Builds an expression tree from a SQL query and outputs it without any
// optimizations applied to it.
//
// - norm [flags]
//
// Builds an expression tree from a SQL query, applies normalization
// optimizations, and outputs it without any exploration optimizations
// applied to it.
//
// - opt [flags]
//
// Builds an expression tree from a SQL query, fully optimizes it using the
// memo, and then outputs the lowest cost tree.
//
// - assign-placeholders-build query-args=(...)
//
// Builds a query that has placeholders (with normalization disabled), then
// assigns placeholders to the given query arguments. Normalization rules are
// disabled when assigning placeholders.
//
// - assign-placeholders-norm query-args=(...)
//
// Builds a query that has placeholders (with normalization enabled), then
// assigns placeholders to the given query arguments. Normalization rules are
// enabled when assigning placeholders.
//
// - assign-placeholders-opt query-args=(...)
//
// Builds a query that has placeholders (with normalization enabled), then
// assigns placeholders to the given query arguments and fully optimizes it.
//
// - placeholder-fast-path [flags]
//
// Builds an expression tree from a SQL query which contains placeholders and
// attempts to use the placeholder fast path to obtain a fully optimized
// expression with placeholders.
//
// - build-cascades [flags]
//
// Builds a query and then recursively builds cascading queries. Outputs all
// unoptimized plans.
//
// - optsteps [flags]
//
// Outputs the lowest cost tree for each step in optimization using the
// standard unified diff format. Used for debugging the optimizer.
//
// - optstepsweb [flags]
//
// Similar to optsteps, but outputs a URL which displays the results.
//
// - exploretrace [flags]
//
// Outputs information about exploration rule application. Used for debugging
// the optimizer.
//
// - memo [flags]
//
// Builds an expression tree from a SQL query, fully optimizes it using the
// memo, and then outputs the memo containing the forest of trees.
//
// - rulestats [flags]
//
// Performs the optimization and outputs statistics about applied rules.
//
// - expr
//
// Builds an expression directly from an opt-gen-like string; see
// exprgen.Build.
//
// - exprnorm
//
// Builds an expression directly from an opt-gen-like string (see
// exprgen.Build), applies normalization optimizations, and outputs the tree
// without any exploration optimizations applied to it.
//
// - expropt
//
// Builds an expression directly from an opt-gen-like string (see
// exprgen.Optimize), applies normalization and exploration optimizations,
// and outputs the tree.
//
// - stats-quality [flags]
//
// Fully optimizes the given query and saves the subexpressions as tables
// in the test catalog with their estimated statistics injected.
// If rewriteActualFlag=true, also executes the given query against a
// running database and saves the intermediate results as tables.
// Compares estimated statistics for a relational expression with the actual
// statistics calculated by calling CREATE STATISTICS on the output of the
// expression. If rewriteActualFlag=false, stats-quality must have been run
// previously with rewriteActualFlag=true to save the statistics as tables.
//
// - reorderjoins [flags]
//
// Fully optimizes the given query and outputs information from
// joinOrderBuilder during join reordering. See the ReorderJoins comment in
// reorder_joins.go for information on the output format.
//
// - import file=...
//
// Imports a file containing exec-ddl commands in order to add tables and/or
// stats to the catalog. This allows commonly-used schemas such as TPC-C or
// TPC-H to be used by multiple test files without copying the schemas and
// stats multiple times. The file name must be provided with the file flag.
// The path of the file should be relative to
// testutils/opttester/testfixtures.
//
// - inject-stats file=... table=...
//
// Injects table statistics from a json file.
//
// - check-size [rule-limit=...] [group-limit=...] [suppress-report]
//
// Fully optimizes the given query and outputs the number of rules applied
// and memo groups created. If the rule-limit or group-limit flags are set,
// check-size will result in a test error if the rule application or memo
// group count exceeds the corresponding limit. If either the rule-limit or
// group-limit options are used the suppress-report option suppresses
// printing of the number of rules and groups explored.
//
// - index-candidates
//
// Walks through the SQL statement to determine candidates for index
// recommendation. See the indexrec package.
//
// - index-recommendations
//
// Walks through the SQL statement and recommends indexes to add in order to
// speed up its execution, if these indexes exist. See the indexrec package.
//
// Supported flags:
//
// - format: controls the formatting of expressions for build, opt, and
// optsteps commands. Format flags are of the form
// (show|hide)-(all|miscprops|constraints|scalars|types|...)
// See formatFlags for all flags. Multiple flags can be specified; each flag
// modifies the existing set of the flags.
//
// - no-stable-folds: disallows constant folding for stable operators; only
// used with "norm".
//
// - fully-qualify-names: fully qualify all column names in the test output.
//
// - expect: fail the test if the rules specified by name are not "applied".
// For normalization rules, "applied" means that the rule's pattern matched
// an expression. For exploration rules, "applied" means that the rule's
// pattern matched an expression and the rule generated one or more new
// expressions in the memo.
//
// - expect-not: fail the test if the rules specified by name are "applied".
//
// - disable: disables optimizer rules by name. Examples:
// opt disable=ConstrainScan
// norm disable=(NegateOr,NegateAnd)
//
// - rule: used with exploretrace; the value is the name of a rule. When
// specified, the exploretrace output is filtered to only show expression
// changes due to that specific rule.
//
// - skip-no-op: used with exploretrace; hide instances of rules that don't
// generate any new expressions.
//
// - colstat: requests the calculation of a column statistic on the top-level
// expression. The value is a column or a list of columns. The flag can
// be used multiple times to request different statistics.
//
// - perturb-cost: used to randomly perturb the estimated cost of each
// expression in the query tree for the purpose of creating alternate query
// plans in the optimizer.
//
// - locality: used to set the locality of the node that plans the query. This
// can affect costing when there are multiple possible indexes to choose
// from, each in different localities.
//
// - database: used to set the current database used by the query. This is
// used by the stats-quality command when rewriteActualFlag=true.
//
// - table: used to set the current table used by the command. This is used by
// the inject-stats command.
//
// - stats-quality-prefix: must be used with the stats-quality command. If
// rewriteActualFlag=true, indicates that a table should be created with the
// given prefix for the output of each subexpression in the query. Otherwise,
// outputs the name of the table that would be created for each
// subexpression.
//
// - ignore-tables: specifies the set of stats tables for which stats quality
// comparisons should not be outputted. Only used with the stats-quality
// command. Note that tables can always be added to the `ignore-tables` set
// without necessitating a run with `rewrite-actual-stats=true`, because the
// now-ignored stats outputs will simply be removed. However, the reverse is
// not possible. So, the best way to rewrite a stats quality test for which
// the plan has changed is to first remove the `ignore-tables` flag, then add
// it back and do a normal rewrite to remove the superfluous tables.
//
// - file: specifies a file, used for the following commands:
// - import: the file path is relative to opttester/testfixtures;
// - inject-stats: the file path is relative to the test file.
//
// - join-limit: sets the value for SessionData.ReorderJoinsLimit, which
// indicates the number of joins at which the optimizer should stop
// attempting to reorder.
//
// - prefer-lookup-joins-for-fks: sets SessionData.PreferLookupJoinsForFKs to
// true, causing foreign key operations to prefer lookup joins.
//
// - null-ordered-last: sets SessionData.NullOrderedLast to true, which orders
// NULL values last in ascending order.
//
// - cascade-levels: used to limit the depth of recursive cascades for
// build-cascades.
//
// - index-version: controls the version of the index descriptor created in
// the test catalog. This is used by the exec-ddl command for CREATE INDEX
// statements.
//
// - split-diff: replaces the unified diff output of the optsteps command with
// a split diff where the before and after expressions are printed in their
// entirety. This is only used by the optsteps command.
//
// - rule-limit: used with check-size to set a max limit on the number of rules
// that can be applied before a testing error is returned.
//
// - group-limit: used with check-size to set a max limit on the number of
// groups that can be added to the memo before a testing error is returned.
//
// - memo-cycles: used with memo to search the memo for cycles and output a
// path with a cycle if one is found.
//
// - use-multi-col-stats: sets the value for
// SessionData.OptimizerUseMultiColStats which indicates whether or not
// multi-column statistics are used for cardinality estimation in the
// optimizer. This option requires a single boolean argument.
//
// - skip-race: skips the test if the race detector is enabled.
//
func (ot *OptTester) RunCommand(tb testing.TB, d *datadriven.TestData) string {
// Allow testcases to override the flags.
for _, a := range d.CmdArgs {
if err := ot.Flags.Set(a); err != nil {
d.Fatalf(tb, "%+v", err)
}
}
ot.Flags.Verbose = datadriven.Verbose()
// Skip the test if the skip-race flag was provided and the race detector is
// enabled.
if ot.Flags.SkipRace && util.RaceEnabled {
return d.Expected
}
ot.semaCtx.Placeholders = tree.PlaceholderInfo{}
ot.evalCtx.SessionData().ReorderJoinsLimit = int64(ot.Flags.JoinLimit)
ot.evalCtx.SessionData().PreferLookupJoinsForFKs = ot.Flags.PreferLookupJoinsForFKs
ot.evalCtx.SessionData().PropagateInputOrdering = ot.Flags.PropagateInputOrdering
ot.evalCtx.SessionData().NullOrderedLast = ot.Flags.NullOrderedLast
ot.evalCtx.SessionData().OptimizerUseMultiColStats = ot.Flags.UseMultiColStats
ot.evalCtx.TestingKnobs.OptimizerCostPerturbation = ot.Flags.PerturbCost
ot.evalCtx.Locality = ot.Flags.Locality
ot.evalCtx.SessionData().SaveTablesPrefix = ot.Flags.SaveTablesPrefix
ot.evalCtx.Placeholders = nil
switch d.Cmd {
case "exec-ddl":
testCatalog, ok := ot.catalog.(*testcat.Catalog)
if !ok {
d.Fatalf(tb, "exec-ddl can only be used with TestCatalog")
}
var s string
var err error
if ot.Flags.IndexVersion != 0 {
s, err = testCatalog.ExecuteDDLWithIndexVersion(d.Input, ot.Flags.IndexVersion)
} else {
s, err = testCatalog.ExecuteDDL(d.Input)
}
if err != nil {
d.Fatalf(tb, "%v", err)
}
return s
case "build":
e, err := ot.OptBuild()
if err != nil {
if errors.HasAssertionFailure(err) {
d.Fatalf(tb, "%+v", err)
}
pgerr := pgerror.Flatten(err)
text := strings.TrimSpace(pgerr.Error())
if pgcode.MakeCode(pgerr.Code) != pgcode.Uncategorized {
// Output Postgres error code if it's available.
return fmt.Sprintf("error (%s): %s\n", pgerr.Code, text)
}
return fmt.Sprintf("error: %s\n", text)
}
ot.postProcess(tb, d, e)
return ot.FormatExpr(e)
case "norm":
e, err := ot.OptNorm()
if err != nil {
if errors.HasAssertionFailure(err) {
d.Fatalf(tb, "%+v", err)
}
pgerr := pgerror.Flatten(err)
text := strings.TrimSpace(pgerr.Error())
if pgcode.MakeCode(pgerr.Code) != pgcode.Uncategorized {
// Output Postgres error code if it's available.
return fmt.Sprintf("error (%s): %s\n", pgerr.Code, text)
}
return fmt.Sprintf("error: %s\n", text)
}
ot.postProcess(tb, d, e)
return ot.FormatExpr(e)
case "opt":
e, err := ot.Optimize()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
ot.postProcess(tb, d, e)
return ot.FormatExpr(e)
case "assign-placeholders-build", "assign-placeholders-norm", "assign-placeholders-opt":
explore := d.Cmd == "assign-placeholders-opt"
normalize := explore || d.Cmd == "assign-placeholders-norm"
e, err := ot.AssignPlaceholders(ot.Flags.QueryArgs, normalize, explore)
if err != nil {
d.Fatalf(tb, "%+v", err)
}
ot.postProcess(tb, d, e)
return ot.FormatExpr(e)
case "placeholder-fast-path":
e, ok, err := ot.PlaceholderFastPath()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
if !ok {
return "no fast path"
}
return ot.FormatExpr(e)
case "build-cascades":
o := ot.makeOptimizer()
o.DisableOptimizations()
if err := ot.buildExpr(o.Factory()); err != nil {
d.Fatalf(tb, "%+v", err)
}
e := o.Memo().RootExpr()
var buildCascades func(e opt.Expr, tp treeprinter.Node, level int)
buildCascades = func(e opt.Expr, tp treeprinter.Node, level int) {
if ot.Flags.CascadeLevels != 0 && level > ot.Flags.CascadeLevels {
return
}
if opt.IsMutationOp(e) {
p := e.Private().(*memo.MutationPrivate)
for _, c := range p.FKCascades {
// We use the same memo to build the cascade. This makes the entire
// tree easier to read (e.g. the column IDs won't overlap).
cascade, err := c.Builder.Build(
context.Background(),
&ot.semaCtx,
&ot.evalCtx,
ot.catalog,
o.Factory(),
c.WithID,
e.Child(0).(memo.RelExpr).Relational(),
c.OldValues,
c.NewValues,
)
if err != nil {
d.Fatalf(tb, "error building cascade: %+v", err)
}
n := tp.Child("cascade")
n.Child(strings.TrimRight(ot.FormatExpr(cascade), "\n"))
buildCascades(cascade, n, level+1)
}
}
for i := 0; i < e.ChildCount(); i++ {
buildCascades(e.Child(i), tp, level)
}
}
tp := treeprinter.New()
root := tp.Child("root")
root.Child(strings.TrimRight(ot.FormatExpr(e), "\n"))
buildCascades(e, root, 1)
return tp.String()
case "optsteps":
result, err := ot.OptSteps()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
case "optstepsweb":
result, err := ot.OptStepsWeb()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
case "exploretrace":
result, err := ot.ExploreTrace()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
case "rulestats":
result, err := ot.RuleStats()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
case "memo":
result, err := ot.Memo()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
ot.checkExpectedRules(tb, d)
return result
case "expr":
e, err := ot.Expr()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
ot.postProcess(tb, d, e)
return ot.FormatExpr(e)
case "exprnorm":
e, err := ot.ExprNorm()
if err != nil {
return fmt.Sprintf("error: %s\n", err)
}
ot.postProcess(tb, d, e)
return ot.FormatExpr(e)
case "expropt":
e, err := ot.ExprOpt()
if err != nil {
if len(errors.GetAllDetails(err)) > 0 {
return fmt.Sprintf("error: %s\ndetails:\n%s", err, errors.FlattenDetails(err))
}
return fmt.Sprintf("error: %s\n", err)
}
ot.postProcess(tb, d, e)
return ot.FormatExpr(e)
case "stats-quality":
result, err := ot.StatsQuality(tb, d)
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
case "import":
ot.Import(tb)
return ""
case "inject-stats":
ot.InjectStats(tb, d)
return ""
case "reorderjoins":
result, err := ot.ReorderJoins()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
case "check-size":
result, err := ot.CheckSize()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
case "index-candidates":
result, err := ot.IndexCandidates()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
case "index-recommendations":
result, err := ot.IndexRecommendations()
if err != nil {
d.Fatalf(tb, "%+v", err)
}
return result
default:
d.Fatalf(tb, "unsupported command: %s", d.Cmd)
return ""
}
}
// FormatExpr is a convenience wrapper for memo.FormatExpr.
func (ot *OptTester) FormatExpr(e opt.Expr) string {
var mem *memo.Memo
if rel, ok := e.(memo.RelExpr); ok {
mem = rel.Memo()
}
return memo.FormatExpr(e, ot.Flags.ExprFormat, mem, ot.catalog)
}
func formatRuleSet(r RuleSet) string {
var buf bytes.Buffer
comma := false
for i, ok := r.Next(0); ok; i, ok = r.Next(i + 1) {
if comma {
buf.WriteString(", ")
}
comma = true
fmt.Fprintf(&buf, "%v", opt.RuleName(i))
}
return buf.String()
}
func (ot *OptTester) checkExpectedRules(tb testing.TB, d *datadriven.TestData) {
if !ot.Flags.ExpectedRules.SubsetOf(ot.appliedRules) {
unseen := ot.Flags.ExpectedRules.Difference(ot.appliedRules)
d.Fatalf(tb, "expected to see %s, but was not triggered. Did see %s",
formatRuleSet(unseen), formatRuleSet(ot.appliedRules))
}
if ot.Flags.UnexpectedRules.Intersects(ot.appliedRules) {
seen := ot.Flags.UnexpectedRules.Intersection(ot.appliedRules)
d.Fatalf(tb, "expected not to see %s, but it was triggered", formatRuleSet(seen))
}
}
func (ot *OptTester) postProcess(tb testing.TB, d *datadriven.TestData, e opt.Expr) {
fillInLazyProps(e)
if rel, ok := e.(memo.RelExpr); ok {
for _, cols := range ot.Flags.ColStats {
memo.RequestColStat(&ot.evalCtx, rel, cols)
}
}
ot.checkExpectedRules(tb, d)
}
// Fills in lazily-derived properties (for display).
func fillInLazyProps(e opt.Expr) {
if rel, ok := e.(memo.RelExpr); ok {
// These properties are derived from the normalized expression.
rel = rel.FirstExpr()
// Derive columns that are candidates for pruning.
norm.DerivePruneCols(rel)
// Derive columns that are candidates for null rejection.
norm.DeriveRejectNullCols(rel)
// Make sure the interesting orderings are calculated.
ordering.DeriveInterestingOrderings(rel)
}
for i, n := 0, e.ChildCount(); i < n; i++ {
fillInLazyProps(e.Child(i))
}
}
func ruleNamesToRuleSet(args []string) (RuleSet, error) {
var result RuleSet
for _, r := range args {
rn, err := ruleFromString(r)
if err != nil {
return result, err
}
result.Add(int(rn))
}
return result, nil
}
// Set parses an argument that refers to a flag.
// See OptTester.RunCommand for supported flags.
func (f *Flags) Set(arg datadriven.CmdArg) error {
switch arg.Key {
case "set":
for _, val := range arg.Vals {
s := strings.Split(val, "=")
if len(s) != 2 {
return errors.Errorf("Expected both session variable name and value for set command")
}
err := sql.SetSessionVariable(f.ot.ctx, f.ot.evalCtx, s[0], s[1])
if err != nil {
return err
}
}
case "format":
if len(arg.Vals) == 0 {
return fmt.Errorf("format flag requires value(s)")
}
for _, v := range arg.Vals {
// Format values are of the form (hide|show)-(flag). These flags modify
// the default flags for the test and multiple flags are applied in order.
parts := strings.SplitN(v, "-", 2)
if len(parts) != 2 ||
(parts[0] != "show" && parts[0] != "hide") ||
formatFlags[parts[1]] == 0 {
return fmt.Errorf("unknown format value %s", v)
}
if parts[0] == "hide" {
f.ExprFormat |= formatFlags[parts[1]]
} else {
f.ExprFormat &= ^formatFlags[parts[1]]
}
}
case "fully-qualify-names":
f.FullyQualifyNames = true
// Hiding qualifications defeats the purpose.
f.ExprFormat &= ^memo.ExprFmtHideQualifications
case "no-stable-folds":
f.NoStableFolds = true
case "disable":
if len(arg.Vals) == 0 {
return fmt.Errorf("disable requires arguments")
}
for _, s := range arg.Vals {
r, err := ruleFromString(s)
if err != nil {
return err
}
f.DisableRules.Add(int(r))
}
case "join-limit":
if len(arg.Vals) != 1 {
return fmt.Errorf("join-limit requires a single argument")
}
limit, err := strconv.ParseInt(arg.Vals[0], 10, 64)
if err != nil {
return errors.Wrap(err, "join-limit")
}
f.JoinLimit = int(limit)
case "prefer-lookup-joins-for-fks":
if len(arg.Vals) > 0 {
return fmt.Errorf("unknown vals for prefer-lookup-joins-for-fks")
}
f.PreferLookupJoinsForFKs = true
case "null-ordered-last":
if len(arg.Vals) > 0 {
return fmt.Errorf("unknown vals for null-ordered-last")
}
f.NullOrderedLast = true
case "rule":
if len(arg.Vals) != 1 {
return fmt.Errorf("rule requires one argument")
}
var err error
f.ExploreTraceRule, err = ruleFromString(arg.Vals[0])
if err != nil {
return err
}
case "skip-no-op":
f.ExploreTraceSkipNoop = true
case "expect":
ruleset, err := ruleNamesToRuleSet(arg.Vals)
if err != nil {
return err
}
f.ExpectedRules.UnionWith(ruleset)
case "expect-not":
ruleset, err := ruleNamesToRuleSet(arg.Vals)