/
pdb-parted
executable file
·2035 lines (1717 loc) · 51.4 KB
/
pdb-parted
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
# pdb-parted
# Copyright (C) 2009-2013 PalominoDB, Inc.
# Copyright (C) 2016-2019 Rick Pizzi
#
# You may contact the current maintainer at pizzi@leopardus.com
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# Dec 02, 2016: Rick: patched to allow use of hourly partitions
# Jul 22, 2019: Rick: patched to use when no partitioning function defined (part col is integer)
# Oct 18, 2019: Rick: patched for MariaDB 10.3 which puts backticks around column names in I_S
#
# REQUIRES perl-DateTime-Format-Strptime and perl-DBD-MySQL package
#
use strict;
use warnings FATAL => 'all';
our $use_hours = 0;
our $no_part_func = 0;
# ###########################################################################
# ProcessLog package 876f85f39dfeb6100fbb852f82cbf61c1e4d739a
# ###########################################################################
package ProcessLog;
use strict;
use warnings FATAL => 'all';
my $mail_available = 1;
eval 'use Mail::Send';
if($@) {
$mail_available = 0;
}
use Sys::Hostname;
use Digest::MD5 qw(md5_hex);
use Time::HiRes qw(time);
use File::Spec;
use Fcntl qw(:seek);
use English qw(-no_match_vars);
use constant _PdbDEBUG => $ENV{Pdb_DEBUG} || 0;
use constant Level1 => 1;
use constant Level2 => 2;
use constant Level3 => 3;
sub new {
my $class = shift;
my ($script_name, $logpath, $email_to) = @_;
my $self = {};
$self->{run_id} = md5_hex(time . rand() . $script_name);
$self->{script_name} = $script_name;
$self->{log_path} = $logpath;
$self->{email_to} = $email_to;
$self->{stack_depth} = 10; # Show traces 10 levels deep.
$self->{logsub} = 0;
$self->{quiet} = 0;
bless $self,$class;
$self->logpath($logpath);
return $self;
}
sub DESTROY {
my ($self) = @_;
if(ref($$self{'LOG'}) and ref($$self{'LOG'}) eq 'GLOB') {
$$self{'LOG'}->flush();
}
}
sub null {
my $class = shift;
$class->new('', '/dev/null', undef);
}
sub name {
my $self = shift;
$self->{script_name};
}
sub runid {
my $self = shift;
$self->{run_id};
}
sub start {
my $self = shift;
$self->m("BEGIN $self->{run_id}");
}
sub end {
my $self = shift;
$self->m("END $self->{run_id}");
}
sub stack_depth {
my ($self, $opts) = @_;
my $old = $self->{stack_depth};
$self->{stack_depth} = $opts if( defined $opts );
$old;
}
sub quiet {
my ($self, $new) = @_;
my $old = $self->{quiet};
$self->{quiet} = $new if( defined $new );
$old;
}
sub logpath {
my ($self, $logpath) = @_;
my $script_name = $$self{script_name};
return $self->{log_path} if(not $logpath);
$self->{log_path} = $logpath;
if($logpath =~ /^syslog:(\w+)/) {
require Sys::Syslog;
Sys::Syslog::openlog($script_name, "", $1);
$self->{logsub} = sub {
my $self = shift;
$_[3] = '';
my $lvl = 'LOG_DEBUG';
$lvl = 'LOG_INFO' if($_[0] eq "msg");
$lvl = 'LOG_NOTICE' if($_[0] eq "ifo");
$lvl = 'LOG_ERR' if($_[0] eq "err");
Sys::Syslog::syslog($lvl, _p(@_));
print _p(@_) unless $self->{quiet};
};
}
elsif($logpath eq 'pdb-test-harness' or $logpath eq 'stderr') {
$self->{logsub} = sub {
my $self = shift;
my @args = @_;
$args[0] =~ s/^/# /;
print STDERR _p(@args);
}
}
else {
open $self->{LOG}, ">>$self->{log_path}" or die("Unable to open logfile: '$self->{log_path}'.\n");
binmode($self->{LOG});
$self->{logsub} = sub {
my $self = shift;
my $fh = $self->{LOG};
print $fh _p(@_);
print _p(@_) unless $self->{quiet};
};
}
return $self;
}
sub email_to {
my ($self, @emails) = @_;
my $old = $$self{email_to};
if(@emails) {
$$self{email_to} = [@emails];
}
return $old;
}
sub m {
my ($self,$m) = shift;
my $fh = $self->{LOG};
my $t = sprintf("%.3f", time());
$self->{logsub}->($self, 'msg', undef, undef, $t, @_);
}
sub ms {
my $self = shift;
$self->m(@_);
$self->m($self->stack());
}
sub p {
my ($self) = shift;
my $fh = \*STDIN;
my $regex = qr/.*/;
my $default = undef;
my @prompt = ();
if(ref($_[0]) eq 'GLOB') {
$fh = shift;
}
if(ref($_[-1]) eq 'Regexp') {
$regex = pop;
}
elsif(ref($_[-2]) eq 'Regexp') {
$default = pop;
$regex = pop;
}
@prompt = @_;
$self->m(@prompt);
chomp($_ = <$fh>);
if($default and $_ eq '') {
$self->m('Using default:', $default);
return $default;
}
while($_ !~ $regex) {
$self->d("Input doesn't match:", $regex);
$self->m(@prompt);
chomp($_ = <$fh>);
}
$self->m('Using input:', $_);
return $_;
}
sub e {
my ($self,$m) = shift;
my ($package, undef, $line) = caller 0;
my $fh = $self->{LOG};
my $t = sprintf("%.3f", time());
$self->{logsub}->($self, 'err', $package, $line, $t, @_);
}
sub ed {
my ($self) = shift;
$self->e(@_);
die(shift(@_) . "\n");
}
sub es {
my $self = shift;
$self->e(@_);
$self->e($self->stack());
}
sub i {
my $self = shift;
my $fh = $self->{LOG};
my $t = sprintf("%.3f", time());
$self->{logsub}->($self, 'ifo', undef, undef, $t, @_);
}
sub is {
my $self = shift;
$self->i(@_);
$self->i($self->stack());
}
sub d {
my $self = shift;
my ($package, undef, $line) = caller 0;
my $fh = $self->{LOG};
if(_PdbDEBUG) {
my $t = sprintf("%.3f", time());
$self->{logsub}->($self, 'dbg', $package, $line, $t, @_);
}
}
sub ds {
my $self = shift;
$self->d(@_);
$self->d($self->stack());
}
sub x {
my ($self, $subref, @args) = @_;
my $r = undef;
my $saved_fhs = undef;
my $proc_fh = undef;
eval {
$saved_fhs = $self->_save_stdfhs();
open($proc_fh, '+>', undef) or die("Unable to open anonymous tempfile");
open(STDOUT, '>&', $proc_fh) or die("Unable to dup anon fh to STDOUT");
open(STDERR, '>&', \*STDOUT) or die("Unable to dup STDOUT to STDERR");
$r = $subref->(@args);
};
$self->_restore_stdfhs($saved_fhs);
seek($proc_fh, 0, SEEK_SET);
return {rcode => $r, error => $EVAL_ERROR . $self->stack, fh => $proc_fh};
}
sub stack {
my ($self, $level, $top) = @_;
$level = $self->{stack_depth} ||= 10 unless($level);
$top = (defined $top ? $top : 2);
my $out = "";
my $i=0;
my ($package, $file, $line, $sub) = caller($i+$top); # +2 hides ProcessLog from the stack trace.
$i++;
if($package) {
$out .= "Stack trace:\n";
}
else {
$out .= "No stack data available.\n";
}
while($package and $i < $level) {
$out .= " "x$i . "$package $file:$line $sub\n";
($package, $file, $line, $sub) = caller($i+$top);
$i++;
}
chomp($out);
$out;
}
sub _p {
my $mode = shift;
my $package = shift;
my $line = shift;
my $time = shift;
my $prefix = "$mode";
$prefix .= " ${package}:${line}" if(defined $package and defined $line);
$prefix .= $time ? " $time: " : ": ";
@_ = map { (my $temp = $_) =~ s/\n/\n$prefix/g; $temp; }
map { defined $_ ? $_ : 'undef' } @_;
$prefix. join(' ',@_). "\n";
}
sub _flush {
my ($self) = @_;
unless($self->{log_path} =~ /^syslog:/) {
$self->{LOG}->flush;
}
1;
}
sub _save_stdfhs {
my ($self) = @_;
open my $stdout_save, ">&", \*STDOUT or die("Unable to dup stdout");
open my $stderr_save, ">&", \*STDERR or die("Unable to dup stderr");
return { o => $stdout_save, e => $stderr_save };
}
sub _restore_stdfhs {
my ($self, $fhs) = @_;
my $o = $fhs->{o};
my $e = $fhs->{e};
open STDOUT, ">&", $o;
open STDERR, ">&", $e;
return 1;
}
sub email_and_die {
my ($self, $extra) = @_;
$self->e("Mail sending not available. Install Mail::Send, or perl-MailTools on CentOS") and die("Cannot mail out") unless($mail_available);
$self->failure_email($extra);
die($extra);
}
sub failure_email {
my ($self,$extra) = @_;
$self->send_email("$self->{script_name} FAILED", $extra);
}
sub success_email {
my ($self, $extra) = @_;
$self->send_email("$self->{script_name} SUCCESS", $extra);
}
sub send_email {
my ($self, $subj, $body, @extra_to) = @_;
$body ||= "No additional message attached.";
my @to;
unless( $mail_available ) {
$self->e("Mail sending not available. Install Mail::Send, or perl-MailTools on CentOS");
return 0;
}
unless( defined $self->{email_to} || @extra_to ) {
$self->e("Cannot send email with no addresses.");
return 0;
}
@to = ( (ref($self->{email_to}) eq 'ARRAY' ? @{$self->{email_to}} : $self->{email_to}), @extra_to );
my $msg = Mail::Send->new(Subject => $subj);
$msg->to(@to);
my $fh = $msg->open;
print($fh "Message from ", $self->{script_name}, " on ", hostname(), "\n");
print($fh "RUN ID: ", $self->{run_id}, "\n");
print($fh "Logging to: ", ($self->{log_path} =~ /^syslog/ ?
$self->{log_path}
: File::Spec->rel2abs($self->{log_path})),
"\n\n");
print($fh $body);
print($fh "\n");
$fh->close;
}
{
no strict 'refs';
no warnings 'once';
*::PL = \(ProcessLog->new($0, '/dev/null'));
}
1;
# ###########################################################################
# End ProcessLog package
# ###########################################################################
# ###########################################################################
# DSN package 13f9a3c9df3506bad80034eedeb6ba834aa1444d
# ###########################################################################
package DSN;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use Storable;
sub _create {
my ($class, $keys) = @_;
my $self = {};
$self = _merge($self, $keys);
return bless $self, $class;
}
sub STORABLE_freeze {
my ($self, $cloning) = @_;
return if $cloning;
my $f = {};
_merge($f, $self);
return (
Storable::nfreeze($f)
);
}
sub STORABLE_thaw {
my ($self, $cloning, $serialized) = @_;
return if $cloning;
my $f = Storable::thaw($serialized);
return _merge($self, $f);
}
sub STORABLE_attach {
my ($class, $cloning, $serialized) = @_;
return if $cloning;
my $f = Storable::thaw($serialized);
return $class->_create($f);
}
sub DESTROY {}
sub get {
my ($self, $k) = @_;
return $self->{$k}->{'value'};
}
sub has {
my ($self, $k) = @_;
return exists $self->{$k}->{'value'};
}
sub str {
my ($self) = @_;
my $str = "";
for(sort keys %$self) {
$str .= "$_=". $self->get($_) ."," if($self->has($_));
}
chop($str);
return $str;
}
sub get_dbi_str {
my ($self, $extra_opts) = @_;
$extra_opts ||= {};
my %set_implied = ();
my %dsn_conv = (
'h' => 'host',
'P' => 'port',
'F' => 'mysql_read_default_file',
'G' => 'mysql_read_default_group',
'S' => 'mysql_socket',
'D' => 'database',
'SSL_key' => 'mysql_ssl_client_key',
'SSL_cert' => 'mysql_ssl_client_cert',
'SSL_CA' => 'mysql_ssl_ca_file',
'SSL_CA_path' => 'mysql_ssl_ca_path',
'SSL_cipher' => 'mysql_ssl_cipher'
);
my %opt_implied = (
'SSL_key' => 'mysql_ssl=1',
'SSL_cert' => 'mysql_ssl=1',
'SSL_CA' => 'mysql_ssl=1',
'SSL_CA_path' => 'mysql_ssl=1',
'SSL_cipher' => 'mysql_ssl=1'
);
my $dbh_str = 'DBI:mysql:';
for(sort keys(%$self)) {
if(exists($opt_implied{$_}) and $self->has($_) and !$set_implied{$opt_implied{$_}}) {
$dbh_str .= $opt_implied{$_} . ';';
$set_implied{$opt_implied{$_}} = 1;
}
$dbh_str .= $dsn_conv{$_} .'='. ($self->get($_) || '') .';'
if(exists($dsn_conv{$_}) and $self->has($_));
}
if(%$extra_opts) {
$dbh_str .= join(';',
map { "$_=". $$extra_opts{$_} } sort keys(%$extra_opts));
}
return $dbh_str;
}
sub get_dbh {
my ($self, $cached, $extra_opts, $extra_dbi_opts) = @_;
my $dbh_str = $self->get_dbi_str($extra_dbi_opts);
my $options = _merge({ 'AutoCommit' => 0, 'RaiseError' => 1,
'PrintError' => 0, 'ShowErrorStatement' => 1 }, ($extra_opts || {}));
my $dbh;
if($cached) {
$dbh = DBI->connect_cached($dbh_str, $self->get('u'), $self->get('p'),
$options);
}
else {
$dbh = DBI->connect($dbh_str, $self->get('u'), $self->get('p'),
$options);
}
if($self->has('N')) {
$dbh->do('SET NAMES '. $dbh->quote($self->get('N')));
}
if($self->has('vars')) {
my $vars = join(', ', map {
my ($k, $v) = split(/=/, $_, 2);
$_ = $k . ' = ' . ($v =~ /^\d+$/ ? $v : $dbh->quote($v, 1));
$_;
} split(/;/, $self->get('vars')));
$dbh->do('SET '. $vars);
}
return $dbh;
}
sub fill_in {
my ($self, $from) = @_;
$self = _merge($self, $from, 0);
return $self;
}
sub _merge {
my ($h1, $h2, $over, $p) = @_;
foreach my $k (keys %$h2) {
if(!ref($h2->{$k})) {
if($over and exists $h1->{$k}) {
$h1->{$k} = $h2->{$k};
}
elsif(!exists $h1->{$k}) {
$h1->{$k} = $h2->{$k};
}
}
elsif(ref($h2->{$k}) eq 'ARRAY') {
$h1->{$k} = [];
push @{$h1->{$k}}, $_ for(@{$h2->{$k}});
}
else {
$h1->{$k} ||= {};
_merge($h1->{$k}, $h2->{$k}, $over, $h1);
}
}
$h1;
}
1;
package DSNParser;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use Carp;
sub new {
my ($class, $keys) = @_;
croak('keys must be a hashref') unless(ref($keys));
my $self = {};
$self->{'keys'} = $keys;
$self->{'allow_unknown'} = 0;
return bless $self, $class;
}
sub add_key {
my ($self, $key, $params) = @_;
croak('params must be a hashref') unless(ref($params));
if(exists $self->{'keys'}->{$key}) {
croak("Key '$key' must not already exist");
}
$self->{'keys'}->{$key} = $params;
}
sub rem_key {
my ($self, $key) = @_;
unless(exists $self->{'keys'}->{$key}) {
croak("Key '$key' must already exist");
}
delete $self->{'keys'}->{$key};
}
sub mand_key {
my ($self, $key, $flag) = @_;
unless(exists $self->{'keys'}->{$key}) {
croak("Key '$key' must already exist");
}
$self->{'keys'}->{$key}->{'mandatory'} = $flag;
}
sub default {
my ($class) = @_;
my $default_keys = {
'h' => {
'desc' => 'Hostname',
'default' => '',
'mandatory' => 0
},
'u' => {
'desc' => 'Username',
'default' => '',
'mandatory' => 0
},
'p' => {
'desc' => 'Password',
'default' => '',
'mandatory' => 0
},
'P' => {
'desc' => 'Port',
'default' => 3306,
'mandatory' => 0
},
'F' => {
'desc' => 'Defaults File',
'default' => '',
'mandatory' => 0
},
'G' => {
'desc' => 'Defaults File Group',
'default' => 'client',
'mandatory' => 0
},
'D' => {
'desc' => 'Database name',
'default' => '',
'mandatory' => 0
},
't' => {
'desc' => 'Table name',
'default' => '',
'mandatory' => 0
},
'S' => {
'desc' => 'Socket path',
'default' => '',
'mandatory' => 0
},
'N' => {
'desc' => 'Client character set',
'default' => '',
'mandatory' => 0
},
'vars' => {
'desc' => 'Extra client variables',
'default' => '',
'mandatory' => 0
},
'sU' => {
'desc' => 'SSH User',
'default' => '',
'mandatory' => 0
},
'sK' => {
'desc' => 'SSH Key',
'default' => '',
'mandatory' => 0
},
'SSL_key' => {
'desc' => 'SSL client key',
'default' => '',
'mandatory' => 0
},
'SSL_cert' => {
'desc' => 'SSL client certificate',
'default' => '',
'mandatory' => 0
},
'SSL_CA' => {
'desc' => 'SSL client CA file',
'default' => '',
'mandatory' => 0
},
'SSL_CA_path' => {
'desc' => 'SSL client CA path',
'default' => '',
'mandatory' => 0
},
'SSL_cipher' => {
'desc' => 'SSL cipher',
'default' => '',
'mandatory' => 0
}
};
return $class->new($default_keys);
}
sub parse {
my ($self, $str) = @_;
use Data::Dumper;
$Data::Dumper::Indent = 0;
my $dsn = DSN->_create($self->{'keys'});
foreach my $kv ( split(/,/, $str) ) {
my ($key, $val) = split(/=/, $kv, 2);
croak('Unknown key: '. $key .' in dsn')
unless($self->{'allow_unknown'} or exists($self->{'keys'}->{$key}) );
$dsn->{$key}->{'value'} = $val;
}
foreach my $k ( keys %$dsn ) {
if($dsn->{$k}->{'mandatory'} and ! exists($dsn->{$k}->{'value'})) {
croak('Missing key: '. $k .' ['. ($self->{'keys'}->{$k}->{'desc'}||'no description') .'] in dsn');
}
}
return $dsn;
}
1;
# ###########################################################################
# End DSN package
# ###########################################################################
# ###########################################################################
# TablePartitions package bf38632f606e6c5d8d6c94691979a33e334690e2
# ###########################################################################
package TablePartitions;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use Data::Dumper;
use DBI;
sub new {
my ( $class, $pl, $dsn ) = @_;
my $self = ();
$self->{dbh} = $dsn->get_dbh(1);
$self->{pl} = $pl;
$self->{schema} = $dsn->get('D');
$self->{name} = $dsn->get('t');
bless $self, $class;
$self->_get_partitions();
if($self->{partition_method} ne 'RANGE') {
return undef;
}
else {
return $self;
}
}
sub _get_version {
my ($self) = @_;
my $dbh = $self->{dbh};
my ($version) = $dbh->selectrow_array('SELECT VERSION()');
my ($major, $minor, $micro, $dist) = $version =~ /^(\d+)\.(\d+)\.(\d+)-(.*)/;
unless($major) {
($major, $minor, $micro) = $version =~ /^(\d+)\.(\d+)\.(\d+)/;
$dist = '';
}
["$major.$minor", $major, $minor, $micro, $dist];
}
sub _get_partitions {
my ($self) = @_;
my $dbh = $self->{dbh};
my ($release, undef, undef, undef, undef) = $self->_get_version();
die("Server release not at least 5.1 ($release)") if ($release < 5.1);
if(1) {
$self->_get_partitions_by_IS();
}
}
sub _get_partitions_by_IS {
my ($self) = @_;
my $dbh = $self->{dbh};
my $qtd_schema = $dbh->quote($self->{schema});
my $qtd_table = $dbh->quote($self->{name});
my $sql = "SELECT * FROM `information_schema`.`PARTITIONS` WHERE TABLE_SCHEMA=$qtd_schema AND TABLE_NAME=$qtd_table";
$self->{pl}->d('SQL:', $sql);
my $rows = $dbh->selectall_arrayref($sql, { Slice => {} });
$self->{pl}->es("Table does not have any partitions, or does not exist.")
and die("Table does not have any partitions, or does not exist")
unless(scalar @$rows >= 1);
$self->{partitions} = [];
$self->{partition_method} = $rows->[0]->{PARTITION_METHOD};
$self->{partition_expression} = $rows->[0]->{PARTITION_EXPRESSION};
foreach my $r (@$rows) {
my $p = {
name => $r->{PARTITION_NAME},
sub_name => $r->{SUBPARTITION_NAME},
position => $r->{PARTITION_ORDINAL_POSITION},
description => $r->{PARTITION_DESCRIPTION},
sub_position => $r->{SUBPARTITION_ORDINAL_POSITION}
};
push @{$self->{partitions}}, $p;
}
}
sub partitions {
my ($self) = @_;
$self->{pl}->d(Dumper($self->{partitions}));
$self->{partitions}
}
sub first_partition {
my ($self) = @_;
$self->{partitions}->[0];
}
sub last_partition {
my ($self) = @_;
$self->{partitions}->[-1];
}
sub method {
my ($self) = @_;
$self->{partition_method};
}
sub expression {
my ($self) = @_;
$self->{partition_expression};
}
sub expression_column {
my ($self) = @_;
my ($col, $fn) = $self->expr_datelike;
return $col if(defined($col));
$self->{partition_expression} =~ /^\s*(A-Za-z\-_\$)\(([A-Za-z0-9\-_\$]+)\)/i;
return $2 if ($1 and $2);
return $self->{partition_expression};
}
sub expr_datelike {
my ($self) = @_;
my %datefuncs = ( 'to_days' => 'from_days', 'month' => 1, 'year' => 'rick_year', 'unix_timestamp' => 'from_unixtime', 'to_seconds' => 'rick_seconds' );
$self->{partition_expression} =~ /^\s*([A-Za-z\-_\$]+)\(([A-Za-z0-9\-_\$`]+)\)/i;
if(defined $1 and $datefuncs{lc($1)}) {
return ($2, $1, $datefuncs{lc($1)});
}
else {
if ($no_part_func) {
return ($2, '', '');
}
else {
return undef;
}
}
}
sub match_partitions {
my ($self, $reg) = @_;
my %res;
map { $res{$_->{name}} = {name => $_->{name}, position => $_->{position}, description => $_->{description} } if($_->{name} =~ $reg); } @{$self->{partitions}};
values %res;
}
sub has_maxvalue_data {
my ($self) = @_;
my $dbh = $self->{dbh};
my $explain_result = undef;
my $descr = undef;
my $col = $self->expression_column;
if ( $self->{partitions}->[-1]->{description} eq 'MAXVALUE' ) {
$descr = $self->{partitions}->[-2]->{description};
if($self->expr_datelike) {
my (undef, $fn, $cfn) = $self->expr_datelike;
if($fn) {
$descr = "$cfn($descr)";
}
}
}
else {
return 0; # Can't have maxvalue data since there isn't a partition for that.
}
my $sql =
qq|SELECT COUNT(*) AS cnt
FROM `$self->{schema}`.`$self->{name}`
WHERE $col > $descr
| ;
$self->{pl}->d('SQL:', $sql);
eval {
$explain_result = $dbh->selectrow_hashref($sql);
$self->{pl}->d(Dumper($explain_result));
};
if($EVAL_ERROR) {
$self->{pl}->es($EVAL_ERROR);
return undef;
}
return $explain_result->{cnt};
}
sub start_reorganization {
my ($self, $p) = @_;
die("Need partition name to re-organize") unless($p);
my $part = undef;
foreach my $par (@{$self->{partitions}}) {
$part = $par if($par->{name} eq $p);
}
return undef unless($part);
$self->{re_organizing} = [];
push @{$self->{re_organizing}},$part;
return 1;
}
sub add_reorganized_part {
my ($self, $name, $desc) = @_;
return undef unless($self->{re_organizing});
my ($col, $fn) = $self->expr_datelike;
push @{$self->{re_organizing}}, {name => $name, description => $desc};
return 1;
}
sub end_reorganization {
my ($self, $pretend) = @_;
return undef unless $self->{re_organizing};
my $sql = "ALTER TABLE `$self->{schema}`.`$self->{name}` REORGANIZE PARTITION";
my $orig_part = shift @{$self->{re_organizing}};
my (undef, $fn) = $self->expr_datelike;
$sql .= " $orig_part->{name} INTO (";
while($_ = shift @{$self->{re_organizing}}) {
$sql .= "\nPARTITION $_->{name} VALUES LESS THAN ";
if(uc($_->{description}) eq 'MAXVALUE') {
$sql .= 'MAXVALUE';
}
else {
if($fn) {
$sql .= "($fn(" . $self->{dbh}->quote($_->{description}) . '))';
}
else {
$sql .= "(" . $_->{description} . ')';
}
}
$sql .= ',';
}
chop($sql);
$sql .= "\n)";
$self->{pl}->d("SQL: $sql");
eval {
unless($pretend) {
$self->{dbh}->do($sql);
$self->_get_partitions();
}
};
if($EVAL_ERROR) {
$self->{pl}->e("Error reorganizing partition $orig_part->{name}: $@");
return undef;
}
$self->{re_organizing} = 0;
return 1;
}