-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmk-visual-explain
3097 lines (2579 loc) · 95.9 KB
/
mk-visual-explain
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
#!/usr/bin/env perl
# This is mk-visual-explain, a program to transform MySQL's EXPLAIN output
# into a query execution plan formatted as a tree.
#
# This program is copyright 2007-2011 Baron Schwartz.
# Feedback and improvements are welcome.
#
# THIS PROGRAM IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, version 2; OR the Perl Artistic License. On UNIX and similar
# systems, you can issue `man perlgpl' or `man perlartistic' to read these
# licenses.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA.
use strict;
use warnings FATAL => 'all';
our $VERSION = '1.0.22';
our $DISTRIB = '7540';
our $SVN_REV = sprintf("%d", (q$Revision: 7477 $ =~ m/(\d+)/g, 0));
# ###########################################################################
# Converts text (e.g. saved output) to a "recordset" -- an array of hashrefs
# -- just like EXPLAIN does for selectall_arrayref({}).
# ###########################################################################
package ExplainParser;
use strict;
use warnings FATAL => 'all';
sub new {
bless {}, shift;
}
sub parse_tabular {
my ( $text, @cols ) = @_;
my %row;
my @vals = $text =~ m/\| +([^\|]*?)(?= +\|)/msg;
return (undef, \@vals) unless @cols;
@row{@cols} = @vals;
return (\%row, undef);
}
sub parse_tab_sep {
my ( $text, @cols ) = @_;
my %row;
my @vals = split(/\t/, $text);
return (undef, \@vals) unless @cols;
@row{@cols} = @vals;
return (\%row, undef);
}
sub parse_vertical {
my ( $text, @cols ) = @_;
my %row = $text =~ m/^ *(\w+): ([^\n]*) *$/msg;
return (\%row, undef);
}
sub parse {
my ($self, $text) = @_;
my $started = 0;
my $lines = 0;
my @cols = ();
my @result = ();
# Detect which kind of input it is
my ( $line_re, $vals_sub );
if ( $text =~ m/^\+---/m ) { # standard "tabular" output
$line_re = qr/^(\| .*)[\r\n]+/m;
$vals_sub = \&parse_tabular;
}
elsif ( $text =~ m/^id\tselect_type\t/m ) { # tab-separated
$line_re = qr/^(.*?\t.*)[\r\n]+/m;
$vals_sub = \&parse_tab_sep;
}
elsif ( $text =~ m/\*\*\* 1. row/ ) { # "vertical" output
$line_re = qr/^( *.*?^ *Extra:[^\n]*$)/ms;
$vals_sub = \&parse_vertical;
}
if ( $line_re ) {
# Pull it apart into lines and parse them.
LINE:
foreach my $line ( $text =~ m/$line_re/g ) {
my ($row, $cols) = $vals_sub->($line, @cols);
if ( $row ) {
foreach my $key ( keys %$row ) {
if ( !$row->{$key} || $row->{$key} eq 'NULL' ) {
$row->{$key} = undef;
}
}
push @result, $row;
}
else {
@cols = @$cols;
}
}
}
return \@result;
}
# ###########################################################################
# Converts output of EXPLAIN into a human-readable tree.
# ###########################################################################
package ExplainTree;
use List::Util qw(max);
use Data::Dumper;
sub new {
my ( $class, $options ) = @_;
my $self = bless {}, $class;
$self->load_options($options);
return $self;
}
sub load_options {
my ( $self, $options ) = @_;
if ( $options && ref $options eq 'HASH' ) {
@{$self}{keys %$options} = values %$options;
}
else {
delete @{$self}{keys %$self};
}
}
sub parse {
my ( $self, $text, $options ) = @_;
return $self->process(ExplainParser->new->parse($text), $options);
}
# The main method that turns a result set into a tree. Accepts an arrayref of
# hashrefs which correspond to the rows in EXPLAIN. See the ALGORITHM in the
# documentation for a small novel about this process.
sub process {
my ( $self, $rows, $options ) = @_;
$self->load_options($options);
return unless ref $rows eq 'ARRAY' && @$rows;
# Pre-process and sanity check the rows.
my @rows = @$rows;
foreach my $i ( 0 .. $#rows ) {
my $row = $rows[$i];
$row->{rowid} = $i;
$row->{Extra} ||= '';
# The source code says if there are too many tables unioned together, the
# table column will get truncated, like "<union1,2,3,4...>". If this
# happens, I've got to bail out. I'm not going to check all the source
# code for all versions, but in 5.0 it looks like I can get this to happen
# around table 20.
die "UNION has too many tables: $row->{table}"
if $row->{table} && $row->{table} =~ m/\./;
if ( !defined $row->{id} ) {
if ( $row->{table} && (my ($id) = $row->{table} =~ m/^<union(\d+)/) ) {
$row->{id} = $id;
}
else {
die "Unexpected NULL in id column, please report as a bug";
}
}
}
# Re-order the rows so all references are forward.
my %union_for
= map { $_->{id} => $_ }
grep { $_->{select_type} eq 'UNION RESULT' }
@rows;
my $last_id = 0;
my @reordered;
foreach my $row ( grep { $_->{select_type} ne 'UNION RESULT' } @rows ) {
if ( $last_id != $row->{id} && $union_for{$row->{id}} ) {
push @reordered, $union_for{$row->{id}};
}
push @reordered, $row;
$last_id = $row->{id};
}
# Process the rows recursively.
my $tree = $self->build_query_plan(@reordered);
return $tree;
}
sub build_query_plan {
my ( $self, @rows ) = @_;
if ( !@rows ) {
die "I got no rows";
}
# Is it a UNION RESULT? Split it up into sub-scopes and recurse.
if ( $rows[0]->{select_type} eq 'UNION RESULT' ) {
my $row = shift @rows;
my @kids;
my @ids = $row->{table} =~ m/(\d+)/g;
my $enclosing_scope;
if ( $rows[0]->{select_type} =~ m/SUBQUERY/ ) {
$enclosing_scope = $rows[0];
}
foreach my $i ( 0 .. $#ids ) {
my $start = $self->index_of($ids[$i], @rows);
my $end = $i < $#ids ? $self->index_of($ids[$i + 1], @rows) : @rows;
push @kids, $self->build_query_plan(splice(@rows, $start, $end - $start));
}
$row->{children} = [ @kids ];
$row->{table} = "union("
. join(',', map { $self->recursive_table_name($_) || '<none>' } @kids)
. ")";
my $tree = $self->transform($row);
if ( $enclosing_scope ) {
my $node = $self->transform($enclosing_scope);
$node->{children} = [ $tree ];
$tree = $node;
}
return $tree;
}
# Are there DERIVED tables? If so, find its children and pull them out of the
# list under it.
while ( my ($der) = grep { $_->{table} && $_->{table} =~ m/^<derived\d+>$/ } @rows ) {
# Figure out the start and end of the derived scope.
my ($der_id) = $der->{table} =~ m/^<derived(\d+)>$/;
my $start = $self->index_of($der_id, @rows);
my $end = $start;
while ( $end < @rows && $rows[$end]->{id} >= $der_id ) {
$end++;
}
# Get the rows that belong to this scope and recurse.
my @enclosed_scope = splice(@rows, $start, $end - $start);
my $kids = $self->build_query_plan(@enclosed_scope);
$der->{children} = [$kids];
$der->{table} = "derived(" . ($self->recursive_table_name($kids) || '<none>') . ")";
}
# Handle the "normal case." For each node, if the id is the same as the last
# one, JOIN and continue. If the id is greater, it's a subquery, so should
# be recursed.
# But, filesort/temporary have to be handled specially, because they appear
# in the first row, even if they are done later. Here are the cases,
# according to http://s.petrunia.net/blog/?p=24:
# ... MySQL has three ways to run a join and produce ordered output:
# Method EXPLAIN output
# ################################## ####################################
# Use index-based access method that no mention of filesort
# produces ordered output
# ---------------------------------- ------------------------------------
# Use filesort() on 1st non-constant "Using filesort" in the first row
# table
# ---------------------------------- ------------------------------------
# Put join result into a temporary "Using temporary; Using filesort" in
# table and use filesort() on it the first row
# ---------------------------------- ------------------------------------
my $first = shift(@rows);
# This is "case three" above.
my $is_temp_filesort;
if ( $first->{Extra} =~ m/Using temporary; Using filesort/ ) {
# The entire join is being placed into a temporary table and filesorted,
# so I'll make a note of that and apply it afterwards. In the meantime I
# must remove mention of it from the node so the node doesn't get extra
# transformations in transform().
$is_temp_filesort = 1;
$first->{Extra} =~ s/Using temporary; Using filesort(?:; )?//;
}
# This is "case two" above. Must find first non-constant table and move
# the filesort() there.
elsif ( $first->{Extra} =~ m/Using filesort/ && $first->{type} =~ m/^(?:system|const)$/ ) {
my ( $first_non_const ) = grep { $_->{type} !~ m/^(?:system|const)$/ } @rows;
if ( $first_non_const ) {
$first->{Extra} =~ s/Using filesort(?:; )?//;
$first_non_const->{Extra} .= '; Using filesort';
}
}
my $scope = $first->{id};
my $tree = $self->transform($first);
my $i = 0;
while ( $i < @rows ) {
my $row = $rows[$i];
if ( $row->{id} == $scope ) {
$tree = {
type => 'JOIN',
children => [ $tree, $self->transform($row) ],
};
$i++;
}
else {
# It's another kind of "join". Find the enclosing scope boundaries and
# recurse. The scope starts at $i.
my $end = $i;
while ( $end < @rows && $rows[$end]->{id} >= $row->{id} ) {
$end++;
}
my @enclosed_scope = splice(@rows, $i, $end - $i);
$tree = {
type => $row->{select_type},
children => [ $tree, $self->build_query_plan(@enclosed_scope) ],
};
# Don't increment the pointer because I just removed rows from @rows.
# $i++
}
}
if ( $is_temp_filesort ) {
$tree = $self->filesort(
$self->temporary($tree, $self->recursive_table_name($tree)));
}
return $tree;
}
sub transform {
my ( $self, $row ) = @_;
my $sub = $row->{type};
# ##################################################################
# Dispatch to a class method to generate the tree.
# ##################################################################
my $no_matching_row = join('|',
"Impossible (?:WHERE|HAVING)(?: noticed after reading const tables)?",
'No matching.*row',
'(?:unique|const) row not found',
);
my $node
= $sub
? $self->$sub($row)
: $row->{Extra} =~ m/No tables/
? { type => ( $row->{select_type} !~ m/^(?:PRIMARY|SIMPLE)$/
? $row->{select_type}
: 'DUAL') }
: $row->{Extra} =~ m/(?:$no_matching_row)/i
? { type => 'IMPOSSIBLE' }
: $row->{Extra} =~ m/optimized away/
? { type => 'CONSTANT' }
: die "Can't handle " . Dumper($row);
my ($warn) = $row->{Extra} =~ m/($no_matching_row)/;
if ( $warn ) {
$node->{warning} = $warn;
}
# ##################################################################
# Apply other tree transformations.
# ##################################################################
if ( $row->{Extra} =~ m/Using where/ ) {
$node = {
type => 'Filter with WHERE',
children => [$node],
};
}
if ( $row->{Extra} =~ m/Using join buffer/ ) {
$node = {
type => 'Join buffer',
children => [$node],
};
}
if ( $row->{Extra} =~ m/Distinct|Not exists/ ) {
$node = {
type => 'Distinct/Not-Exists',
children => [$node],
};
}
if ( $row->{Extra} =~ m/Range checked for each record \(\w+ map: ([^\)]+)\)/ ) {
# (index map: N) is a bitmap of which indexes are used. For example:
# 0x5 base 16 (or base 10)
# 0101 base 2
# 4321 position of bits
# 3 1 indexes used
my $bitmap = eval "int($1)"; # Hex to decimal if it begins with '0x'
$bitmap = unpack("B32", pack("N", $bitmap)); # Convert into binary string of 1/0
$bitmap =~ s/^0+//; # Remove leading zeros
$bitmap = reverse $bitmap; # Iterate from left-to-right
my $possible_keys = join(',',
grep { substr($bitmap, $_ - 1, 1) }
( 1 .. length($bitmap) ));
$node = {
type => 'Re-evaluate indexes each row',
possible_keys => $possible_keys,
children => [$node],
};
}
if ( $row->{Extra} =~ m/Using filesort/ ) {
$node = $self->filesort($node);
}
if ( $row->{Extra} =~ m/Using temporary/ ) {
$node = $self->temporary($node, $row->{table}, 1);
}
# Add some data that will help me keep track of nodes as I manipulate
# them later
$node->{id} = $row->{id};
$node->{rowid} = $row->{rowid};
return $node;
}
sub index_of {
my ( $self, $id, @rows ) = @_;
my $i = 0;
foreach my $row ( @rows ) {
if ( $row->{id} && $row->{id} == $id ) {
return $i;
}
$i++;
}
die "Can't find row $id in "
. join(',', map { $_->{id} || '' } @rows);
}
sub pretty_print {
my ( $self, $node, $prefix ) = @_;
$prefix ||= '';
my $branch = $prefix ? substr($prefix, 0, length($prefix) -3) . '+- ' : '';
my $output = $branch . $node->{type} . "\n";
my @kids;
if ( $node->{children} ) {
@kids = reverse @{$node->{children}};
}
my $suffix = (@kids > 1) ? '| ' : ' ';
foreach my $thing ( qw(table key partitions possible_keys method key_len ref rows warning) ) {
if ( defined $node->{$thing} ) {
$output .= $prefix . sprintf('%-14s %s', $thing, $node->{$thing}) . "\n";
}
}
my $last_child = pop @kids;
foreach my $child ( @kids ) {
$output .= $self->pretty_print($child, $prefix . $suffix);
}
if ( $last_child ) {
$output .= $self->pretty_print($last_child, $prefix . ' ');
}
return $output;
}
#############################################################################
# Each method in this section corresponds to a value you will find in the 'type'
# column in EXPLAIN.
#############################################################################
sub ALL {
my ( $self, $row ) = @_;
return {
type => 'Table scan',
rows => $row->{rows},
children => [$self->table($row)],
};
}
sub fulltext {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Fulltext scan');
}
sub range {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Index range scan');
}
sub index {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Index scan');
}
sub eq_ref {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Unique index lookup');
}
sub ref {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Index lookup');
}
sub ref_or_null {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Index lookup with extra null lookup');
}
sub const {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Constant index lookup');
}
sub system {
my ( $self, $row ) = @_;
return {
type => 'Constant table access',
rows => $row->{rows},
children => [$self->table($row)],
};
}
sub unique_subquery {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Unique subquery');
}
sub index_subquery {
my ( $self, $row ) = @_;
return $self->index_access($row, 'Index subquery');
}
# From the manual: "The Index Merge method is used to retrieve rows with
# several range scans and to merge their results into one." Therefore each
# index access should be shown as an index range scan. The unions and
# intersections can be recursive, as in
# union(intersect(key1,key2),intersect(key3,key4))
sub index_merge {
my ( $self, $row ) = @_;
my ( $merge_spec )
= $row->{Extra} =~ m/Using ((?:intersect|union|sort_union)\(.*?\))(?=;|$)/;
my ($merge, $num) = $self->recurse_index_merge($row, $merge_spec, 0);
# index_merge_bookmark_lookup note:
# From the manual, "If the used indexes don't cover all columns used in the
# query, full rows are retrieved only when the range conditions for all
# used keys are satisfied." So a bookmark lookup shouldn't be shown for
# all indexes; it should be shown from the merge results.
return $self->bookmark_lookup($merge, $row);
}
# ###########################################################################
# Helper subroutines.
# ###########################################################################
sub recursive_table_name {
my ( $self, $node ) = @_;
if ( $node->{table} ) {
return $node->{table};
}
if ( $node->{key} ) {
my ( $table ) = $node->{key} =~ m/(.*?)->/;
return $table;
}
if ( $node->{type} eq 'Bookmark lookup' ) {
return $node->{children}->[1]->{table};
}
if ( $node->{type} eq 'IMPOSSIBLE' ) {
return '<none>';
}
if ( $node->{children} ) {
return join(',',
grep { $_ }
map { $self->recursive_table_name($_) }
@{$node->{children}});
}
}
# $num is the number of nodes to the left of this node in a depth-first
# traversal. It lets me figure out which value goes in key_len.
my $bal; # Workaround for issue 90 (Variable "$bal" will not stay shared).
sub recurse_index_merge {
my ( $self, $row, $spec, $num ) = @_;
my ($type, $args) = $spec =~ m/(intersect|union|sort_union)\((.*)\)$/;
my @children;
# See 'man perlre' and search for 'matches a parenthesized group'.
$bal = qr/
\(
(?:
(?> [^()]+ ) # Non-parens without backtracking
|
(??{ $bal }) # Group with matching parens
)*
\)
/x;
# Extract a thing, followed by balanced parentheses.
foreach my $child ( $args =~ m/(\w+$bal)/g ) {
my ( $subtree, $num ) = $self->recurse_index_merge($row, $child, $num);
push @children, $subtree;
}
if ( !@children ) { # Recursion base case; $args is an index list
foreach my $idx ( split(/,/, $args) ) {
my $index_scan = $self->index_access($row, 'Index range scan', $idx);
$index_scan->{key_len} = ($row->{key_len} =~ m/(\d+)/g)[$num++];
push @children, $index_scan;
}
}
return (
{
type => 'Index merge',
method => $type,
rows => $row->{rows},
children => \@children,
},
$num
);
}
sub table {
my ( $self, $row ) = @_;
my $node = {
type => ($row->{table} && $row->{table} =~ m/^(derived|union)\(/)
? uc $1
: 'Table',
table => $row->{table},
possible_keys => $row->{possible_keys},
partitions => $row->{partitions},
};
if ( $row->{children} ) {
$node->{children} = $row->{children};
}
return $node;
}
sub bookmark_lookup {
my ( $self, $node, $row ) = @_;
if ( $row->{Extra} =~ m/Using index/
|| ( $self->{clustered} && $row->{key} && $row->{key} eq 'PRIMARY' ))
{
return $node;
}
return {
type => 'Bookmark lookup',
children => [ $node, $self->table($row) ],
};
}
sub filesort {
my ( $self, $node ) = @_;
return {
type => 'Filesort',
children => [$node],
};
}
sub temporary {
my ( $self, $node, $table_name, $is_scan ) = @_;
$node = {
type => 'TEMPORARY',
table => "temporary($table_name)",
possible_keys => undef,
partitions => undef,
children => [$node],
};
if ( $is_scan ) {
$node = {
type => 'Table scan',
rows => undef,
children => [ $node ],
};
}
return $node;
}
sub index_access {
my ( $self, $row, $type, $key ) = @_;
my $node = {
type => $type,
key => $row->{table} . '->' . ( $key || $row->{key} ),
possible_keys => $row->{possible_keys},
partitions => $row->{partitions},
key_len => $row->{key_len},
'ref' => $row->{ref},
rows => $row->{rows},
};
if ( $row->{Extra} =~ m/Full scan on NULL key/ ) {
$node->{warning} = 'Full scan on NULL key';
}
if ( $row->{Extra} =~ m/Using index for group-by/ ) {
$node->{type} = 'Loose index scan';
}
# See index_merge_bookmark_lookup note above.
if ( $row->{type} ne 'index_merge' ) {
$node = $self->bookmark_lookup($node, $row);
}
return $node;
}
# ###########################################################################
# OptionParser package 7102
# This package is a copy without comments from the original. The original
# with comments and its test file can be found in the SVN repository at,
# trunk/common/OptionParser.pm
# trunk/common/t/OptionParser.t
# See http://code.google.com/p/maatkit/wiki/Developers for more information.
# ###########################################################################
package OptionParser;
use strict;
use warnings FATAL => 'all';
use List::Util qw(max);
use English qw(-no_match_vars);
use constant MKDEBUG => $ENV{MKDEBUG} || 0;
use Getopt::Long;
my $POD_link_re = '[LC]<"?([^">]+)"?>';
sub new {
my ( $class, %args ) = @_;
my @required_args = qw();
foreach my $arg ( @required_args ) {
die "I need a $arg argument" unless $args{$arg};
}
my ($program_name) = $PROGRAM_NAME =~ m/([.A-Za-z-]+)$/;
$program_name ||= $PROGRAM_NAME;
my $home = $ENV{HOME} || $ENV{HOMEPATH} || $ENV{USERPROFILE} || '.';
my %attributes = (
'type' => 1,
'short form' => 1,
'group' => 1,
'default' => 1,
'cumulative' => 1,
'negatable' => 1,
);
my $self = {
head1 => 'OPTIONS', # These args are used internally
skip_rules => 0, # to instantiate another Option-
item => '--(.*)', # Parser obj that parses the
attributes => \%attributes, # DSN OPTIONS section. Tools
parse_attributes => \&_parse_attribs, # don't tinker with these args.
%args,
strict => 1, # disabled by a special rule
program_name => $program_name,
opts => {},
got_opts => 0,
short_opts => {},
defaults => {},
groups => {},
allowed_groups => {},
errors => [],
rules => [], # desc of rules for --help
mutex => [], # rule: opts are mutually exclusive
atleast1 => [], # rule: at least one opt is required
disables => {}, # rule: opt disables other opts
defaults_to => {}, # rule: opt defaults to value of other opt
DSNParser => undef,
default_files => [
"/etc/maatkit/maatkit.conf",
"/etc/maatkit/$program_name.conf",
"$home/.maatkit.conf",
"$home/.$program_name.conf",
],
types => {
string => 's', # standard Getopt type
int => 'i', # standard Getopt type
float => 'f', # standard Getopt type
Hash => 'H', # hash, formed from a comma-separated list
hash => 'h', # hash as above, but only if a value is given
Array => 'A', # array, similar to Hash
array => 'a', # array, similar to hash
DSN => 'd', # DSN
size => 'z', # size with kMG suffix (powers of 2^10)
time => 'm', # time, with an optional suffix of s/h/m/d
},
};
return bless $self, $class;
}
sub get_specs {
my ( $self, $file ) = @_;
$file ||= $self->{file} || __FILE__;
my @specs = $self->_pod_to_specs($file);
$self->_parse_specs(@specs);
open my $fh, "<", $file or die "Cannot open $file: $OS_ERROR";
my $contents = do { local $/ = undef; <$fh> };
close $fh;
if ( $contents =~ m/^=head1 DSN OPTIONS/m ) {
MKDEBUG && _d('Parsing DSN OPTIONS');
my $dsn_attribs = {
dsn => 1,
copy => 1,
};
my $parse_dsn_attribs = sub {
my ( $self, $option, $attribs ) = @_;
map {
my $val = $attribs->{$_};
if ( $val ) {
$val = $val eq 'yes' ? 1
: $val eq 'no' ? 0
: $val;
$attribs->{$_} = $val;
}
} keys %$attribs;
return {
key => $option,
%$attribs,
};
};
my $dsn_o = new OptionParser(
description => 'DSN OPTIONS',
head1 => 'DSN OPTIONS',
dsn => 0, # XXX don't infinitely recurse!
item => '\* (.)', # key opts are a single character
skip_rules => 1, # no rules before opts
attributes => $dsn_attribs,
parse_attributes => $parse_dsn_attribs,
);
my @dsn_opts = map {
my $opts = {
key => $_->{spec}->{key},
dsn => $_->{spec}->{dsn},
copy => $_->{spec}->{copy},
desc => $_->{desc},
};
$opts;
} $dsn_o->_pod_to_specs($file);
$self->{DSNParser} = DSNParser->new(opts => \@dsn_opts);
}
return;
}
sub DSNParser {
my ( $self ) = @_;
return $self->{DSNParser};
};
sub get_defaults_files {
my ( $self ) = @_;
return @{$self->{default_files}};
}
sub _pod_to_specs {
my ( $self, $file ) = @_;
$file ||= $self->{file} || __FILE__;
open my $fh, '<', $file or die "Cannot open $file: $OS_ERROR";
my @specs = ();
my @rules = ();
my $para;
local $INPUT_RECORD_SEPARATOR = '';
while ( $para = <$fh> ) {
next unless $para =~ m/^=head1 $self->{head1}/;
last;
}
while ( $para = <$fh> ) {
last if $para =~ m/^=over/;
next if $self->{skip_rules};
chomp $para;
$para =~ s/\s+/ /g;
$para =~ s/$POD_link_re/$1/go;
MKDEBUG && _d('Option rule:', $para);
push @rules, $para;
}
die "POD has no $self->{head1} section" unless $para;
do {
if ( my ($option) = $para =~ m/^=item $self->{item}/ ) {
chomp $para;
MKDEBUG && _d($para);
my %attribs;
$para = <$fh>; # read next paragraph, possibly attributes
if ( $para =~ m/: / ) { # attributes
$para =~ s/\s+\Z//g;
%attribs = map {
my ( $attrib, $val) = split(/: /, $_);
die "Unrecognized attribute for --$option: $attrib"
unless $self->{attributes}->{$attrib};
($attrib, $val);
} split(/; /, $para);
if ( $attribs{'short form'} ) {
$attribs{'short form'} =~ s/-//;
}
$para = <$fh>; # read next paragraph, probably short help desc
}
else {
MKDEBUG && _d('Option has no attributes');
}
$para =~ s/\s+\Z//g;
$para =~ s/\s+/ /g;
$para =~ s/$POD_link_re/$1/go;
$para =~ s/\.(?:\n.*| [A-Z].*|\Z)//s;
MKDEBUG && _d('Short help:', $para);
die "No description after option spec $option" if $para =~ m/^=item/;
if ( my ($base_option) = $option =~ m/^\[no\](.*)/ ) {
$option = $base_option;
$attribs{'negatable'} = 1;
}
push @specs, {
spec => $self->{parse_attributes}->($self, $option, \%attribs),
desc => $para
. (defined $attribs{default} ? " (default $attribs{default})" : ''),
group => ($attribs{'group'} ? $attribs{'group'} : 'default'),
};
}
while ( $para = <$fh> ) {
last unless $para;
if ( $para =~ m/^=head1/ ) {
$para = undef; # Can't 'last' out of a do {} block.
last;
}
last if $para =~ m/^=item /;
}
} while ( $para );
die "No valid specs in $self->{head1}" unless @specs;
close $fh;
return @specs, @rules;
}
sub _parse_specs {
my ( $self, @specs ) = @_;
my %disables; # special rule that requires deferred checking
foreach my $opt ( @specs ) {
if ( ref $opt ) { # It's an option spec, not a rule.
MKDEBUG && _d('Parsing opt spec:',
map { ($_, '=>', $opt->{$_}) } keys %$opt);
my ( $long, $short ) = $opt->{spec} =~ m/^([\w-]+)(?:\|([^!+=]*))?/;
if ( !$long ) {
die "Cannot parse long option from spec $opt->{spec}";
}
$opt->{long} = $long;
die "Duplicate long option --$long" if exists $self->{opts}->{$long};
$self->{opts}->{$long} = $opt;
if ( length $long == 1 ) {
MKDEBUG && _d('Long opt', $long, 'looks like short opt');
$self->{short_opts}->{$long} = $long;
}
if ( $short ) {
die "Duplicate short option -$short"
if exists $self->{short_opts}->{$short};
$self->{short_opts}->{$short} = $long;
$opt->{short} = $short;
}
else {
$opt->{short} = undef;
}
$opt->{is_negatable} = $opt->{spec} =~ m/!/ ? 1 : 0;
$opt->{is_cumulative} = $opt->{spec} =~ m/\+/ ? 1 : 0;
$opt->{is_required} = $opt->{desc} =~ m/required/ ? 1 : 0;
$opt->{group} ||= 'default';
$self->{groups}->{ $opt->{group} }->{$long} = 1;
$opt->{value} = undef;
$opt->{got} = 0;
my ( $type ) = $opt->{spec} =~ m/=(.)/;
$opt->{type} = $type;
MKDEBUG && _d($long, 'type:', $type);
$opt->{spec} =~ s/=./=s/ if ( $type && $type =~ m/[HhAadzm]/ );
if ( (my ($def) = $opt->{desc} =~ m/default\b(?: ([^)]+))?/) ) {
$self->{defaults}->{$long} = defined $def ? $def : 1;
MKDEBUG && _d($long, 'default:', $def);
}
if ( $long eq 'config' ) {
$self->{defaults}->{$long} = join(',', $self->get_defaults_files());
}