Looking for a fancy regex to split partial SQL where statement. Legacy app is quite old and records below are manually entered, which allows for a lot of mistakes. Given below where code I need to split it by brackets. I also need to record logical operator so after processing each statement I could construct it back.
SQL where scenarios:
my $view2 = "test1=1 AND ( test2=2 ) AND (test3=4 OR test3=9 OR test3=3 OR test3=5)"
EXPECTED array:
1: "test1=1"
2: "test2=2"
3: "test3=4 OR test3=9 OR test3=3 OR test3=5"
my $view2 = "( test1=2 AND test2=1 ) OR ( test1=2 AND test2=6 ) OR ( test1=2 AND test2=8 ) OR ( test1=2 AND test2=10 )"
EXPECTED array:
1: "test1=2 AND test2=1"
2: "test1=2 AND test2=6"
3: "test1=2 AND test2=8"
4: "test1=2 AND test2=10"
my $view3 = "test1 = '1' AND test3 = '3'"
EXPECTED array:
1: "test1 = '1' AND test3 = '3'"
I've tried splitting each statement and logic separately, one array with sql code, another array with logic operators. I also tried one array with sql code and logical operators. If code is wrapped properly in brackets, all is working ($view2) but if its not then that part is omitted ($view1 and $view3).
This is what I have so far
my $view1 = "test1=1 AND ( test2=2 ) AND (test3=4 OR test3=9 OR test3=3 OR test3=5)";
my $view2 = "( test1=2 AND test2=1 ) OR ( test1=2 AND test2=6 ) OR ( test1=2 AND test2=8 ) OR ( test1=2 AND test2=10 )";
my $view3 = "test1 = '1' AND test3 = '3'";
# stmt and logic separated
my @arr = ( $view1 =~ /\([^)]*\)/g );
my @logic= ( $view1 =~ /\)[^)]*\(/g );
# stmt and logic in one array
my @arrOne = $view =~ /\([^)]*[^(]*\)|\w+/g;
my $counter = 1;
foreach my $record (@arr) {
$record =~ s/\( | \)//g;
print "\n" . $counter . ":";
print $record;
$counter += 1;
}
my $counter_logic = 1;
foreach my $record (@logic) {
$record =~ s/\) | \(//g;
print "\n";
print $record;
}
How can I add part of sql code without brackets to regex pattern? Not sure if it's even doable? Any idea how to achieve it?
So after multiple failures I decided to use ChatGPT and believe it or not code seems to be working.
First I needed to clean string from single quotes and whitespaces and then following pattern did the trick