-
Notifications
You must be signed in to change notification settings - Fork 3
/
myway.pl
executable file
·6737 lines (5880 loc) · 228 KB
/
myway.pl
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
#!/bin/sh
exec perl -wx $0 "$@"
if 0;
#!perl -w
#line 6
###############################################################################
# HP Autonomy
###############################################################################
#
# myway.pl
#
# A perl re-implementation of flyway, maintaining 100% compatibility with
# flyway schema files and tables whilst providing enhanced automatic operation
# and resilience.
#
###############################################################################
# FIXME: # {{{
#
# * Need to pre-filter restoration data, to fix the MySQL bug if logging is
# enabled - see bugs.mysql.com/69970
#
# }}}
# TODO: # {{{
#
# * fork()/exec() pv when performing restorations, and check for failure. If
# so, show the last error from 'SHOW ENGINE INNODB STATUS';
#
# * Enhance Percona SQLParser code to handle more statement types;
#
# * Allow 'parse' dbdump option to tokenise backup?
#
# * Incorporate HPCS modules to allow backup directly to Object Store - this
# requires splitting data into small (10MB) chunks and passing an overall
# manifest on completion;
#
# * Make HPCS modules optional, so when not present myway.pl will still run,
# but without Object Store functionality;
#
# * Check entry -> tokens -> tables -> db, and confirm it exists (caching seen
# databases);
#
# * Add parser for GRANT, etc.;
#
# * Roll-back on failure - try to continue rather than dying?
#
# * Restore backups on failure;
#
# }}}
# Copyright 2014 Stuart Shelton, Autonomy Systems Ltd.
# Portions of this program are copyright 2010-2012 Percona Inc.
#
# 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
# MERCHANTIBILITY 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.
{
# Include Percona SQLParser # {{{
# ###########################################################################
# SQLParser package $Revision$
# ###########################################################################
# Package: SQLParser
# SQLParser parses common MySQL SQL statements into data structures.
# This parser is MySQL-specific and intentionally meant to handle only
# "common" cases. Although there are many limiations (like UNION, CASE,
# etc.), many complex cases are handled that no other free, Perl SQL
# parser at the time of writing can parse, notably subqueries in all their
# places and varieties.
#
# This package has not been profiled and since it relies heavily on
# mildly complex regex, so do not expect amazing performance.
#
# See SQLParser.t for examples of the various data structures. There are
# many and they vary a lot depending on the statment parsed, so documentation
# in this file is not exhaustive.
#
# This package differs from QueryParser because here we parse the entire SQL
# statement (thus giving access to all its parts), whereas QueryParser extracts
# just needed parts (and ignores all the rest).
package SQLParser;
use strict;
use warnings FATAL => 'all';
use English qw(-no_match_vars);
use constant MKDEBUG => $ENV{MKDEBUG} || 0;
use constant SQLDEBUG => $ENV{SQLDEBUG} || 0;
use constant DEFDELIM => ';';
# Used by improved parse_values
use Regexp::Common;
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
sub new( $% );
sub parse( $$;$ );
sub parse_alter( $$ );
sub parse_call( $$ );
sub parse_create( $$ );
sub parse_delete( $$ );
sub parse_drop( $$ );
#sub parse_grant( $$ );
sub parse_insert( $$ ); # Alias of parse_replace
sub parse_select( $$ );
sub parse_update( $$ );
sub parse_add( $$ );
sub parse_change( $$ );
sub parse_character_set( $$ );
sub parse_columns( $$ );
sub parse_from( $$ ); # Alias of parse_into, parse_tables
sub parse_group_by( $$ );
sub parse_having( $$ );
sub parse_identifier( $$$ );
sub parse_identifiers( $$ );
sub parse_limit( $$ );
sub parse_modify( $$ );
sub parse_order_by( $$ );
sub parse_set( $$ );
sub parse_table_reference( $$ );
sub parse_values( $$ );
sub parse_where( $$ );
sub clean_query( $$ );
sub is_identifier( $$ );
sub normalize_keyword_spaces( $$ );
sub remove_functions( $$ );
sub remove_subqueries( $$ );
sub remove_using_columns( $$ );
sub replace_function( $$ );
sub set_Schema( $$ );
sub split_unquote( $$$ );
sub _parse_clauses( $$ );
sub _parse_csv( $$$ );
sub _parse_query( $$$$$ );
sub _is_constant( $$ );
sub _d;
# Basic identifers for database, table, column and function names.
my $quoted_ident = qr/`[^`]+`/;
# '' is a valid constant...
#my $constant_ident = qr/'[^']+'/;
my $constant_ident = qr/'[^']*'/;
#my $unquoted_ident = qr/
# \@{0,2} # optional @ or @@ for variables
# \w+ # the ident name
# (?:\s*\([^\)]*\))? # optional function params
#/x;
my $unquoted_ident = qr/
\@{0,2} # optional @ or @@ for variables
\w+ # the ident name
(?:\s*$RE{ balanced }{ -parens => '()' })? # optional function params
/x;
my $ident_alias = qr/
\s+ # space before alias
(?:(AS)\s+)? # optional AS keyword
((?>$quoted_ident|$unquoted_ident)) # alais
/xi;
#my $function_ident = qr/
# \s*
# (
# (?:\b\w+|`\w+`)\s* # function name
# \( # opening parenthesis
# [^\)]* # function args, if any
# \) # closing parenthesis
# )
#/x;
my $function_ident = qr/
(
(?:\b\w+|`\w+`)\s* # function name
$RE{ balanced }{ -parens => '()' }
)
/x;
# A table is identified by 1 or 2 identifiers separated by a period
# and optionally followed by an alias. See parse_table_reference()
# for why an optional index hint is not included here.
my $table_ident = qr/(?:
((?:(?>$quoted_ident|$unquoted_ident)\.?){1,2}) # table
(?:$ident_alias)? # optional alias
)/xo;
# A column is identified by 1 to 3 identifiers separated by periods
# and optionally followed by an alias.
my $column_ident = qr/(?:
((?:(?>$quoted_ident|$constant_ident|$function_ident|$unquoted_ident|\*)\.?){1,3}) # column
(?:$ident_alias)? # optional alias
)/xo;
my %ignore_function = (
NOT => 1,
IN => 1,
INDEX => 1,
KEY => 1,
);
# Sub: new # {{{
# Create a SQLParser object.
#
# Parameters:
# %args - Arguments
#
# Optional Arguments:
# Schema - <Schema> object. Can be set later by calling <set_Schema()>.
#
# Returns:
# SQLParser object
sub new( $% ) {
my ( $class, %args ) = @_;
my $self = {
%args
, delimiter => DEFDELIM
};
return( bless( $self, $class ) );
} # new # }}}
# Sub: parse # {{{
# Parse a SQL statment. Only statements of $allowed_types are parsed.
# This sub recurses to parse subqueries.
#
# Parameters:
# $query - SQL statement
#
# Returns:
# A complex hashref of the parsed SQL statment. All keys and almost all
# values are lowercase for consistency. The struct is roughly:
# (start code)
# {
# type => '', # one of $allowed_types
# clauses => {}, # raw, unparsed text of clauses
# <clause> => struct # parsed clause struct, e.g. from => [<tables>]
# keywords => {}, # LOW_PRIORITY, DISTINCT, SQL_CACHE, etc.
# functions => {}, # MAX(), SUM(), NOW(), etc.
# select => {}, # SELECT struct for INSERT/REPLACE ... SELECT
# subqueries => [], # pointers to subquery structs
# }
# (end code)
# It varies, of course, depending on the query. If something is missing
# it means the query doesn't have that part. E.g. INSERT has an INTO clause
# but DELETE does not, and only DELETE and SELECT have FROM clauses. Each
# clause struct is different; see their respective parse_CLAUSE subs.
sub parse( $$;$ ) {
my ( $self, $query, $delim ) = @_;
return unless $query;
$delim = DEFDELIM unless( defined( $delim ) and length( $delim ) );
#MKDEBUG && _d('Query:', $query);
# Only these types of statements are parsed.
my $allowed_types = qr/(?:
ALTER
|CALL
|CREATE
|DELETE
|DELIMITER
|DROP
|INSERT
|REPLACE
|SELECT
|UPDATE
)/xi;
#|GRANT
# Flatten and clean query.
$query = $self->clean_query($query);
# Remove first word, should be the statement type. The parse_TYPE subs
# expect that this is already removed.
my $type;
if ( $query =~ s/^(\w+)\s+// ) {
$type = lc $1;
MKDEBUG && _d('Query type:', $type);
die "Cannot parse " . uc($type) . " queries"
unless $type =~ m/$allowed_types/i;
}
elsif( $query eq $delim ) {
# This is a bit of a hack to catch fragments after hints which
# may have been passed through this far...
return( undef );
}
else {
die "Query '$query' does not begin with a word"; # shouldn't happen
}
$query = $self->normalize_keyword_spaces($query);
MKDEBUG && _d('Normalised query:', $type, $query);
if ( 'delimiter' eq $type ) {
my @terms = split( /\s+/, $query );
$self->{delimiter} = shift( @terms );
my $struct;
$struct->{type} = $type;
$struct->{delimiter} = $self->{delimiter};
$struct->{unknown} = join( ' ', @terms );
return $struct;
}
# If query has any subqueries, remove/save them and replace them.
# They'll be parsed later, after the main outer query.
my @subqueries;
if ( $query =~ m/(\(\s*SELECT\s+)/i ) {
MKDEBUG && _d('Removing subqueries');
@subqueries = $self->remove_subqueries($query);
$query = shift @subqueries;
}
elsif ( $type eq 'create' && $query =~ m/\s+SELECT/ ) {
# XXX: create PROCEDURE may contain SELECT sub-queries, but
# it cannot be assumed that they will continue to the end
# of the line. Delimiter-parsing in this instance is not
# trivial, as the active delimiter may differ from ';',
# which may also appear (without delimiting) in a quoted
# string...
MKDEBUG && _d('CREATE..SELECT');
#($subqueries[0]->{query}) = $query =~ m/\s+(SELECT\s+.+)/;
#$query =~ s/\s+SELECT\s+.+//;
# XXX: Let's give is a try anyway...
($subqueries[0]->{query}) = $query =~ m/\s+(SELECT\s+[^;]+)/;
$query =~ s/\s+SELECT\s+[^;]+//;
}
# Parse raw text parts from query. The parse_TYPE subs only do half
# the work: parsing raw text parts of clauses, tables, functions, etc.
# Since these parts are invariant (e.g. a LIMIT clause is same for any
# type of SQL statement) they are parsed later via other parse_CLAUSE
# subs, instead of parsing them individually in each parse_TYPE sub.
my $parse_func = "parse_$type";
my $struct = $self->$parse_func($query);
if ( !$struct ) {
MKDEBUG && _d($parse_func, 'failed to parse query');
return;
}
$struct->{type} = $type;
$self->_parse_clauses($struct);
# TODO: parse functions
if ( @subqueries ) {
MKDEBUG && _d('Parsing subqueries');
foreach my $subquery ( @subqueries ) {
my $subquery_struct = $self->parse($subquery->{query});
@{$subquery_struct}{keys %$subquery} = values %$subquery;
push @{$struct->{subqueries}}, $subquery_struct;
}
}
MKDEBUG && _d('Query struct:', Dumper($struct));
return $struct;
} # parse # }}}
# Functions to handle top-level SQL elements
sub parse_alter( $$ ) { # {{{
my ( $self, $query ) = @_;
my $keywords = qr/(ONLINE|OFFLINE|IGNORE)/i;
my ( $type, @query ) = split( /\s+/, $query );
$query = join( ' ', @query );
if( $type =~ m/TABLE/i ) {
$query =~ s/^\s*TABLE\s+//i;
#my $clauses = qr/(ADD(?:\s+(?:COLUMN|INDEX|KEY|CONSTRAINT|(?:CONSTRAINT\s+)?(?:(?:PRIMARY|FOREIGN)\s+KEY|UNIQUE\s+(?:INDEX|KEY))|(?:FULLTEXT|SPATIAL)\s+(?:INDEX|KEY)))?|(?:ALTER|CHANGE|MODIFY)(?:\s+COLUMN)?|DROP(?:\s+(?:COLUMN|INDEX|(?:(?:PRIMARY|FOREIGN)\s+)?KEY))?|(?:DIS|EN)ABLE\s+KEYS|RENAME\s+(?:TO|AS)?|ORDER\s+BY|CONVERT\s+TO\s+CHARACTER\s+SET|(?:DEFAULT\s+)?CHARACTER\s+SET(?:\s+=)?|(?:DISCARD|IMPORT)\s+TABLESPACE|(?:ADD|DROP|COALESCE|REORGANISE|ANALYSE|CHECK|OPTIMIZE|REBUILD|REPAIR)\s+PARTITION|PARTITION\s+BY|REMOVE\s+PARTITIONING)/i;
my $clauses = qr/(ADD|(?:ALTER|CHANGE|MODIFY)|DROP|(?:DIS|EN)ABLE\s+KEYS|RENAME|ORDER\s+BY|CONVERT\s+TO\s+CHARACTER\s+SET|(?:DEFAULT\s+)?CHARACTER\s+SET|(?:DISCARD|IMPORT)\s+TABLESPACE|(?:ADD|DROP|COALESCE|REORGANISE|ANALYSE|CHECK|OPTIMIZE|REBUILD|REPAIR)\s+PARTITION|PARTITION\s+BY|REMOVE\s+PARTITIONING)/i;
return $self->_parse_query($query, $keywords, 'tables', $clauses);
}
} # parse_alter # }}}
sub parse_call( $$ ) { # {{{
my ($self, $query) = @_;
my ($name) = $query =~ m/
(\S+)(?:\s*\(.*\)\s*)?
/xi;
$name =~ s/['"]//g;
$name =~ s/\(\s*\)$//;
return {
object => 'procedure',
name => $name,
unknown => undef,
};
} # parse_call # }}}
sub parse_create( $$ ) { # {{{
my ($self, $query) = @_;
return unless $query;
# FIXME: This function will only really parse 'CREATE TABLE', and even
# then it doesn't give much information :(
my ($obj, $name) = $query =~ m/
(\S+)\s+
(?:IF\s+NOT\s+EXISTS\s+)?
(\S+)\s*.*$
/xi;
$name =~ s/['"]//g;
$name =~ s/\(\s*\)$//;
$name =~ s/[;(]$//;
my $struct = {
object => lc $obj,
name => $name,
unknown => undef,
};
if( lc( $obj ) eq 'procedure' ) {
$query =~ s/\sBEGIN\s/ BEGIN; /gi;
$query =~ s/\sEND( IF)\s/ END$1; /gi;
$query =~ s/\sTHEN\s/ THEN; /gi;
MKDEBUG && _d('Filtered query:', $query);
my @subqueries = split( /;/, DEFDELIM . $query . DEFDELIM );
for( my $n = 0 ; $n < scalar( @subqueries ) ; $n++ ) {
my $subquery = $subqueries[ $n ];
if( 0 == $n ) {
$subquery = '';
} elsif( 1 == $n ) {
$subquery =~ s/^.*?BEGIN//;
MKDEBUG && _d('Filtered initial sub-query:', $subquery);
} elsif( scalar( @subqueries ) - 1 == $n ) {
$subquery =~ s/END.*?$//;
MKDEBUG && _d('Filtered final sub-query:', $subquery);
}
$subquery =~ s/^\s+//;
$subquery =~ s/\s+$//;
if( length( $subquery ) ) {
MKDEBUG && _d('Parsing CREATE PROCEDURE sub-query:', $subquery);
my $subquery_struct;
eval {
$subquery_struct = $self->parse($subquery);
};
if( $@ ) {
$subquery_struct = { unknown => $subquery };
}
push @{$struct->{subqueries}}, $subquery_struct;
}
}
}
MKDEBUG && _d('Create struct:', Dumper($struct));
return $struct;
} # parse_create # }}}
sub parse_delete( $$ ) { # {{{
my ( $self, $query ) = @_;
if ( $query =~ s/FROM\s+//i ) {
my $keywords = qr/(LOW_PRIORITY|QUICK|IGNORE)/i;
my $clauses = qr/(FROM|WHERE|ORDER\s+BY|LIMIT(?:\s+\d+))/i;
return $self->_parse_query($query, $keywords, 'from', $clauses);
}
else {
die "DELETE without FROM: $query";
}
} # parse_delete # }}}
sub parse_drop( $$ ) { # {{{
my ($self, $query) = @_;
# Keywords are expected to be at the start of the query, so these
# that appear at the end are handled separately. Afaik, SELECT are
# the only statements with optional keywords at the end. These
# also appear to be the only keywords with spaces instead of _.
my @keywords;
my $final_keywords = qr/(RESTRICT|CASCADE)/i;
1 while $query =~ s/\s+$final_keywords/(push @keywords, $1), ''/gie;
my $struct;
my $delimiter = $self->{delimiter};
$delimiter = DEFDELIM unless( defined( $delimiter ) and length( $delimiter ) );
( my $terms = $query ) =~ s/\s*\Q$delimiter\E\s*$//;
#( my $terms = $query ) =~ s/\s*$delimiter\s*$//;
$terms =~ s/IF\s+EXISTS//;
my( $type, @objects ) = split( /\s+/, $terms );
if( $type =~ m/TEMPORARY/i ) {
if( not( shift( @objects ) =~ m/TABLE/i ) ) {
die "TEMPORARY without TABLE: $query";
} else {
$struct->{keywords}->{temporary} = 1;
$type = 'TABLE';
}
}
if( 'LOGFILE' eq uc( $type ) ) {
$type .= ' ' . shift( @objects );
if( not( 'LOGFILE GROUP' eq $type ) ) {
die "LOGFILE without GROUP: $query";
}
}
$struct->{object} = lc( $type );
if( uc( $type ) =~ m/DATABASE|EVENT|FUNCTION|PROCEDURE|SERVER|TRIGGER/ ) {
if( scalar( @objects ) > 1 ) {
die "DROP " . uc( $type ) . " supports only one parameter: $query";
}
$struct->{name} = shift( @objects );
} elsif( uc( $type ) eq 'INDEX' ) {
# Handle 'ON tbl_name' plus optional 'ALGORITHM [=] {DEFAULT|INPLACE|COPY} | LOCK [=] {DEFAULT|NONE|SHARED|EXCLUSIVE} ...'
my $name = shift( @objects );
# XXX: Statements of the form:
# ALTER TABLE `foo` DROP INDEX `bar`
# ... will now invoke this code-path, so DROP without ON
# is valid iff we're part of an ALTER query. Unfortunately
# there's no way to tell whether this is the case at this.
#
if( scalar( @objects ) and not( 'ON' eq shift( @objects ) ) ) {
die "DROP " . uc( $type ) . " without ON: $query";
}
my $tbl = shift( @objects );
$struct->{name} = $self->parse_identifier('column', $name);
$struct->{tbl} = $self->parse_identifier('table', $tbl) if( defined( $tbl ) );
while( scalar( @objects ) ) {
my $term = shift( @objects );
if( not( $term =~ m/ALGORITHM|LOCK/i ) ) {
die "DROP " . uc( $type ) . " unrecognised parameter $term: $query";
}
my $argument = shift( @objects );
if( defined( $argument ) and ( '=' eq $argument ) ) {
$argument = shift( @objects );
}
if( defined( $argument ) ) {
$struct->{keywords}->{ lc( $term ) } = $argument;
} else {
die "Parameter $term requires an argument: $query";
}
}
} elsif( uc( $type ) =~ m/LOGFILE GROUP|TABLESPACE/ ) {
# Handle optional 'ENGINE [=] engine_name'
$struct->{name} = shift( @objects );
while( scalar( @objects ) ) {
my $term = shift( @objects );
if( not( $term =~ m/ENGINE/i ) ) {
die "DROP " . uc( $type ) . " unrecognised parameter $term: $query";
}
my $argument = shift( @objects );
if( defined( $argument ) and ( '=' eq $argument ) ) {
$argument = shift( @objects );
}
if( defined( $argument ) ) {
$struct->{keywords}->{ lc( $term ) } = $argument;
} else {
die "Parameter $term requires an argument: $query";
}
}
} else {
if( 1 == scalar( @objects ) ) {
$struct->{name} = shift( @objects );
} else {
# TODO: Are commas in quoted object names valid?
my $names = split( /,\s+/, join( ' ', @objects ) );
$struct->{name} = $names;
}
}
$struct->{unknown} = undef;
# Add final keywords, if any.
map { s/ /_/g; $struct->{keywords}->{lc $_} = 1; } @keywords;
return $struct;
} # parse_drop # }}}
#sub parse_grant( $$ ) { # {{{
# my ($self, $query) = @_;
#
# my $keywords = qr/(
# ALL
# |ALL\s+PRIVILEGES
# |ALTER
# |ALTER\s+ROUTINE
# |CREATE
# |CREATE\s+ROUTINE
# |CREATE\s+TEMPORARY\s+TABLES
# |CREATE\s+USER
# |CREATE\s+VIEW
# |DELETE
# |DROP
# |EVENT
# |EXECUTE
# |FILE
# |GRANT\s+OPTION
# |INDEX
# |INSERT
# |LOCK\s+TABLES
# |PROCESS
# |REFERENCES
# |RELOAD
# |RECPLICATION\s+CLIENT
# |REPLICATION\s+SLAVE
# |SELECT
# |SHOW\s+DATABASES
# |SHOW\s+VIEW
# |SHUTDOWN
# |SUPER
# |TRIGGER
# |UPDATE
# |USAGE
# )/xi;
# my $clauses = qr/(ON|TO|REQUIRE|AND|WITH)/i;
#
# return $self->_parse_query($query, $keywords, 'grants', $clauses);
#} # parse_grant # }}}
sub parse_insert( $$ ) { # {{{
my ( $self, $query ) = @_;
return unless $query;
MKDEBUG && _d('Parsing INSERT/REPLACE', $query);
my $struct = {};
my $delimiter = $self->{delimiter};
$delimiter = DEFDELIM unless( defined( $delimiter ) and length( $delimiter ) );
$query =~ s/\s*\Q$delimiter\E\s*$//;
#$query =~ s/\s*$delimiter\s*$//;
# Save, remove keywords.
my $keywords = qr/(LOW_PRIORITY|DELAYED|HIGH_PRIORITY|IGNORE)/i;
1 while $query =~ s/$keywords\s+/$struct->{keywords}->{lc $1}=1, ''/gie;
if ( $query =~ m/ON DUPLICATE KEY UPDATE (.+)/i ) {
my $values = $1;
die "No values after ON DUPLICATE KEY UPDATE: $query" unless $values;
$struct->{clauses}->{on_duplicate} = $values;
MKDEBUG && _d('Clause: on duplicate key update', $values);
# This clause can be confused for JOIN ... ON in INSERT-SELECT queries,
# so we remove the ON DUPLICATE KEY UPDATE clause after extracting its
# values.
$query =~ s/\s+ON DUPLICATE KEY UPDATE.+//;
}
# Parse INTO clause. Literal "INTO" is optional.
# if ( my @into = ($query =~ m/
# (?:INTO\s+)? # INTO, optional
# (`[^`]+`|[^\s(]+?)\s* # table ref
# (\([^)]+\)\s+)? # column list, optional
# (VALUES?|SET|SELECT)\s* # start of next caluse
# /xgci)
# ) {
( my $string = $query ) =~ s/^\s*INTO\s+//;
my $tbl;
if( $string =~ m/^\s*`([^`]+)`/ and defined( $1 ) and length( $1 ) ) {
$tbl = $1;
MKDEBUG && _d('Found quoted table name', $tbl);
$string =~ s/^\s*`\Q$tbl\E`\s*//;
} elsif( $string =~ m/^\s*([^\s(]+?)[\s(]/ and defined( $1 ) and length( $1 ) ) {
$tbl = $1;
MKDEBUG && _d('Found table name', $tbl);
$string =~ s/^\s*\Q$tbl\E\s*//;
} else {
die "INSERT/REPLACE without table: $query";
}
$struct->{clauses}->{into} = $tbl;
MKDEBUG && _d('Clause: into', $tbl, ', string', $string);
if( $string =~ m/^\s*(\(.*\))\s+(?:VALUES?|SET|SELECT)\s*/ ) {
my @input = split( //, $1 );
my @output;
my $escaped = 0;
my $quoted = 0;
my $bra = 0;
my $ket = 0;
EXTRACT: foreach my $character ( @input ) {
push( @output, $character );
if( $character eq ')' and not( $quoted ) and ( $ket <= $bra ) ) {
last EXTRACT;
} else {
if( $character eq "'" ) {
if( not( $escaped ) ) {
$quoted = not( $quoted );
}
} elsif( $character eq '(' ) {
$bra++;
} elsif( $character eq ')' ) {
$ket++;
}
if( $character eq '\\' ) {
$escaped = 1;
} else {
$escaped = 0;
}
}
}
my $cols = join( '', @output );
$cols =~ s/^\(//;
$cols =~ s/\)$//;
if ( $cols ) {
$struct->{clauses}->{columns} = $cols;
MKDEBUG && _d('Clause: columns', $cols);
$string =~ s/^\s*\(\s*\Q$cols\E\s*\)\s*//;
#$string =~ s/^\s*\(\s*$cols\s*\)\s*//;
} else {
# Insert into no columns!?
# Can apparently be used to create a new ID in an
# auto-increment column of a table...
$string =~ s/^\s*\(\s*\)\s*//;
}
}
my @components = split( /\s+/, $string );
my $next_clause = lc( shift( @components ) ); # VALUES, SET or SELECT
die "INSERT/REPLACE without clause after table: $query"
unless $next_clause;
$next_clause = 'values' if $next_clause eq 'value';
my ($values) = ($string =~ m/^\s*\Q$next_clause\E\s*(.*)$/i);
#my ($values) = ($string =~ m/^\s*$next_clause\s*(.*)$/i);
die "INSERT/REPLACE without values: $query" unless $values;
$struct->{clauses}->{$next_clause} = $values;
MKDEBUG && _d('Clause:', $next_clause, $values);
# Save any leftovers. If there are any, parsing missed something.
($struct->{unknown}) = ($string =~ m/^\s*\Q$next_clause\E\s*\Q$values\E\s*(.*)$/i);
#($struct->{unknown}) = ($string =~ m/^\s*\Q$next_clause\E\s*$values\s*(.*)$/i);
#($struct->{unknown}) = ($string =~ m/^\s*$next_clause\s*$values\s*(.*)$/i);
# if ( my @into = ($query =~ m/
# (?:INTO\s+)? # INTO, optional
# (.+?)\s+ # table ref
# (\([^\)]+\)\s+)? # column list, optional
# (VALUE.?|SET|SELECT)\s+ # start of next caluse
# /xgci)
# ) {
# my $tbl = shift @into; # table ref
# $struct->{clauses}->{into} = $tbl;
# MKDEBUG && _d('Clause: into', $tbl);
#
# my $cols = shift @into; # columns, maybe
# if ( $cols ) {
# $cols =~ s/[\(\)]//g;
# $struct->{clauses}->{columns} = $cols;
# MKDEBUG && _d('Clause: columns', $cols);
# }
#
# my $next_clause = lc(shift @into); # VALUES, SET or SELECT
# die "INSERT/REPLACE without clause after table: $query"
# unless $next_clause;
# $next_clause = 'values' if $next_clause eq 'value';
# my ($values) = ($query =~ m/\G(.+)/gci);
# die "INSERT/REPLACE without values: $query" unless $values;
# $struct->{clauses}->{$next_clause} = $values;
# MKDEBUG && _d('Clause:', $next_clause, $values);
# }
#
# # Save any leftovers. If there are any, parsing missed something.
# ($struct->{unknown}) = ($query =~ m/\G(.+)/);
return $struct;
} # parse_insert
{
# Suppress warnings like "Name "SQLParser::parse_set" used only once:
# possible typo at SQLParser.pm line 480." caused by the fact that we
# don't call these aliases directly, they're called indirectly using
# $parse_func, hence Perl can't see their being called a compile time.
no warnings;
# INSERT and REPLACE are so similar that they are both parsed
# in parse_insert().
*parse_replace = \&parse_insert;
} # }}}
sub parse_select( $$ ) { # {{{
my ( $self, $query ) = @_;
# Keywords are expected to be at the start of the query, so these
# that appear at the end are handled separately. Afaik, SELECT are
# the only statements with optional keywords at the end. These
# also appear to be the only keywords with spaces instead of _.
my @keywords;
my $final_keywords = qr/(FOR\s+UPDATE|LOCK\s+IN\s+SHARE\s+MODE)/i;
1 while $query =~ s/\s+$final_keywords/(push @keywords, $1), ''/gie;
my $keywords = qr/(
ALL
|DISTINCT
|DISTINCTROW
|HIGH_PRIORITY
|STRAIGHT_JOIN
|SQL_SMALL_RESULT
|SQL_BIG_RESULT
|SQL_BUFFER_RESULT
|SQL_CACHE
|SQL_NO_CACHE
|SQL_CALC_FOUND_ROWS
)/xi;
my $clauses = qr/(
FROM
|WHERE
|GROUP\s+BY
|HAVING
|ORDER\s+BY
|LIMIT(?:\s+\d+)
|PROCEDURE
|INTO\s+OUTFILE
)/xi;
my $struct = $self->_parse_query($query, $keywords, 'columns', $clauses);
# Add final keywords, if any.
map { s/ /_/g; $struct->{keywords}->{lc $_} = 1; } @keywords;
return $struct;
} # parse_select # }}}
sub parse_update( $$ ) { # {{{
my ( $self, $query ) = @_;
my $keywords = qr/(LOW_PRIORITY|IGNORE)/i;
my $clauses = qr/(SET|WHERE|ORDER\s+BY|LIMIT(?:\s+\d+))/i;
return $self->_parse_query($query, $keywords, 'tables', $clauses);
} # parse_update # }}}
# Functions to handle SQL components
# Sub: parse_add # {{{
# GROUP BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]
sub parse_add( $$ ) {
my ( $self, $add ) = @_;
return unless $add;
MKDEBUG && _d('Parsing ADD', $add);
# Parse the identifers.
my $idents = $self->parse_identifiers( $self->_parse_csv($add) );
return $idents;
} # parse_add # }}}
sub parse_change( $$ ) { # {{{
my ( $self, $change ) = @_;
# TODO
return $change;
} # parse_change # }}}
sub parse_character_set( $$ ) { # {{{
my ( $self, $character_set ) = @_;
# TODO
return $character_set;
} # parse_character_set # }}}
sub parse_columns( $$ ) { # {{{
my ( $self, $cols ) = @_;
MKDEBUG && _d('Parsing columns list:', $cols);
my @cols;
pos $cols = 0;
while (pos $cols < length $cols) {
MKDEBUG && _d("At position '" . ( ( pos $cols ) or 0 ) . "' of ", length $cols);
if ($cols =~ m/\G\s*(__SQ\d+__)\s*(?>,|\Z)/gcxo) {
warn "SQL DEBUG: (4) " .
( defined( $1 ) ? "\$1(db_tbl_col) is '$1'" : '' ) .
( defined( $2 ) ? ", \$2(unused) is '$2'" : '' ) .
( defined( $3 ) ? ", \$3(unused) is '$3'" : '' ) .
( defined( $4 ) ? ", \$4(unused) is '$4'" : '' ) .
( defined( $5 ) ? ", \$4(unused) is '$5'" : '' ) .
"." if SQLDEBUG;
MKDEBUG && _d("Passing-through expression with compressed element \"$1\"");
my $col_struct = { expr => $1, (), () };
push @cols, $col_struct;
}
# XXX: Looking at it, the alias/col/tbl hash is lacking either
# the col(umn) or the alias name, because only three
# values are stored :(
# We see:
# jobs.id AS id -> { alias => 'AS', col => 'id', tbl => 'jobs' }
# ... so explicit_alias is missing, and $2 is in $3.
#
elsif ($cols =~ m/\G\s*($RE{ balanced }{ -parens => '()' })\s*(?>,|\Z)/gcxo) {
my ($select_expr) = $1;
warn "SQL DEBUG: (5) " .
( defined( $1 ) ? "\$1(db_tbl_col) is '$1'" : '' ) .
( defined( $2 ) ? ", \$2(unused) is '$2'" : '' ) .
( defined( $3 ) ? ", \$3(unused) is '$3'" : '' ) .
( defined( $4 ) ? ", \$4(unused) is '$4'" : '' ) .
( defined( $5 ) ? ", \$4(unused) is '$5'" : '' ) .
"." if SQLDEBUG;
# See comments for $function_ident(2) below
MKDEBUG && _d("Cannot fully parse expression \"$select_expr\"");
my $col_struct = { expr => $select_expr, (), () };
push @cols, $col_struct;
}
elsif ($cols =~ m/\G\s*$column_ident\s*(?>,|\Z)/gcxo) {
warn "SQL DEBUG: (1) " .
( defined( $1 ) ? "\$1(db_tbl_col) is '$1'" : '' ) .
( defined( $2 ) ? ", \$2(unused) is '$2'" : '' ) .
( defined( $3 ) ? ", \$3(as) is '$3'" : '' ) .
( defined( $4 ) ? ", \$4(alias) is '$4'" : '' ) .
( defined( $5 ) ? ", \$4(unused) is '$5'" : '' ) .
"." if SQLDEBUG;
#my ($db_tbl_col, $as, $alias) = ($1, $2, $3); # XXX
my ($db_tbl_col, $as, $alias) = ($1, $3, $4); # XXX
#MKDEBUG && _d("column identifier:", Dumper(\$db_tbl_col));
my $ident_struct = $self->parse_identifier('column', $db_tbl_col);
#MKDEBUG && _d("resulting column identifier struct:", Dumper(\$ident_struct));
if (defined $ident_struct) {
$alias =~ s/`//g if defined $alias and length $alias;
my $col_struct = {
%$ident_struct,
($as ? (explicit_alias => 1) : ()),
($alias ? (alias => $alias) : ()),
};
push @cols, $col_struct;
}
}
# Furthermore, if the LHS of a SELECT statement is actually a
# function-call rather than an alias at all, then we need to
# handle that differently (but only if the other approaches
# have failed to match)...
# Update: Moved to position 2
elsif ($cols =~ m/\G\s*$function_ident\s*(?>,|\Z)/gcxo) {
my ($select_expr) = $1;
warn "SQL DEBUG: (2) " .
( defined( $1 ) ? "\$1(db_tbl_col) is '$1'" : '' ) .
( defined( $2 ) ? ", \$2(as) is '$2'" : '' ) .
( defined( $3 ) ? ", \$3(alias) is '$3'" : '' ) .
( defined( $4 ) ? ", \$4(unused) is '$4'" : '' ) .
( defined( $5 ) ? ", \$4(unused) is '$5'" : '' ) .
"." if SQLDEBUG;
# There's no obvious way to represent this in the
# current structure, which is predecated upon having a
# concrete identifier as a root element. Having said
# this, the expression is still represented in
# { 'clauses' } -> { 'columns' } (although not as an
# alias/col/tbl hash) so perhaps this is okay...
MKDEBUG && _d("Cannot fully parse expression \"$select_expr\"");
my $col_struct = { expr => $select_expr, (), () };
push @cols, $col_struct;
}
# This can occur when, for example, the LHS of a SELECT
# statement's alias definition is an expression rather
# than a simple column-reference...
elsif ($cols =~ m/\G\s*(.+?)$ident_alias\s*(?>,|\Z)/gcxo) {
my ($select_expr, $as, $alias) = ($1, $2, $3); # XXX
warn "SQL DEBUG: (3) " .
( defined( $1 ) ? "\$1(db_tbl_col) is '$1'" : '' ) .
( defined( $2 ) ? ", \$2(as) is '$2'" : '' ) .
( defined( $3 ) ? ", \$3(alias) is '$3'" : '' ) .
( defined( $4 ) ? ", \$4(unused) is '$4'" : '' ) .
( defined( $5 ) ? ", \$4(unused) is '$5'" : '' ) .
"." if SQLDEBUG;
$alias =~ s/`//g if $alias;
# There's no obvious way to represent this in the
# current structure, which is predecated upon having a
# concrete identifier as a root element. Having said
# this, the expression is still represented in
# { 'clauses' } -> { 'columns' } (although not as an
# alias/col/tbl hash) so perhaps this is okay...
MKDEBUG && _d("Cannot fully parse expression \"" . $select_expr . ( defined( $as ) ? ' ' . $as . ' ' : ' ' ) . $alias . "\"");
my $col_struct = {
expr => $select_expr,
($as ? (explicit_alias => 1) : ()),
($alias ? (alias => $alias) : ()),
};
push @cols, $col_struct;
}
elsif ($cols =~ m/\G\s*(.+?)(.*)\s*(?>,|\Z)/gcxo) {
my ($select_expr) = $1;
MKDEBUG && _d("Cannot parse expression \"$select_expr\"");
my $col_struct = { expr => $select_expr, (), () };
push @cols, $col_struct;
}
else {
die "Column ident match on '$cols' failed"; # shouldn't happen
}
}