lib/DB/Handy.pm

filter: Statementstmt 89.9% 3167 / 3522 Branchbran 70.5% 1750 / 2482 Conditioncond 58.1% 570 / 980 MC/DCmcdc 37.1% 216 / 582 Subroutinesub 96.2% 180 / 187 Podpod 42.8% 18 / 42 totaltotal 75.7% 5901 / 7795 SCAR 103.7
CC
1746
Cov
79%
__ANON__
1199.9
__ANON__
645.8
eval_expr
441.4
CRAP 31768.1
« blib/lib/DB/Handy.pm ↑ Summary
1 package DB::Handy;
2 ######################################################################
3 #
4 # DB::Handy - Pure-Perl flat-file relational database with DBI-like interface
5 #
6 # https://metacpan.org/dist/DB-Handy
7 #
8 # Copyright (c) 2026 INABA Hitoshi <ina.cpan@gmail.com>
9 ######################################################################
10 #
11 # Compatible : Perl 5.005_03 and later
12 # Platform : Windows and UNIX/Linux
13 #
14 # FILE LAYOUT:
15 # <base_dir>/<database>/
16 # <table>.sch schema (text, key=value lines)
17 # <table>.dat records (fixed-length binary; 1st byte is active/deleted flag)
18 # <table>.<idxname>.idx sorted index (binary)
19 #
20 # INDEX FILE FORMAT (each entry is fixed-size):
21 # Header : "SDBIDX1\n" (8 bytes)
22 # Entries (sorted ascending by key_bytes):
23 # [key_bytes : keysize bytes][rec_no : 4 bytes big-endian uint32]
24 #
25 # Key encoding (byte order == value order):
26 # INT : sign-bit-flipped big-endian uint32
27 # FLOAT : IEEE 754 order-preserving 8-byte encoding
28 # other : NUL-padded fixed-width string
29 #
30 # SCHEMA FILE format for indexes:
31 # IDX=<idxname>:<colname>:<unique 0|1>
32 ######################################################################
33  
34 24 ▶use 5.00503; # Universal Consensus 1998 for primetools
Subroutine BEGIN: called CC=1 SCAR=0.0
35 # Perl 5.005_03 compatibility for historical toolchains
36 # use 5.008001; # Lancaster Consensus 2013 for toolchains
37  
38 24 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 24 ▶BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } }
Subroutine BEGIN: called CC=3 SCAR=16.5
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.006" and not defined &warnings::import) 0 24 24
Condition33%1/3
$] < "5.006" and not defined &warnings::import
!ll&&!rl&&r
2400
MC/DC0%0/2
$] < "5.006" and not defined &warnings::import
$] < "5.006" not defined &warnings::import
Truth table33%1/3
A and not(B)
A= $] < "5.006"B= not defined &warnings::import
ABresult
0X0
100
111
40 24 ▶use warnings; local $^W = 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 24 ▶BEGIN { pop @INC if $INC[-1] eq '.' }
Subroutine BEGIN: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $INC[-1] eq "." 0 24 24
42 24 ▶use Fcntl qw(:flock);
Subroutine BEGIN: called CC=1 SCAR=0.0
43 24 ▶use File::Path ();
Subroutine BEGIN: called CC=1 SCAR=0.0
44 24 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 24 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
46  
47 24 ▶use vars qw($VERSION $errstr);
Subroutine BEGIN: called CC=1 SCAR=0.0
48 24 $VERSION = '1.09';
49 24 $VERSION = $VERSION;
50 24 $errstr = '';
51  
52 ###############################################################################
53 # Constants
54 ###############################################################################
55 24 ▶use constant RECORD_ACTIVE => "\x01";
Subroutine BEGIN: called CC=1 SCAR=0.0
56 24 ▶use constant RECORD_DELETED => "\x00";
Subroutine BEGIN: called CC=1 SCAR=0.0
57 24 ▶use constant MAX_VARCHAR => 255;
Subroutine BEGIN: called CC=1 SCAR=0.0
58 24 ▶use constant INT_MAX => 2147483647;
Subroutine BEGIN: called CC=1 SCAR=0.0
59 24 ▶use constant INT_MIN => -2147483648;
Subroutine BEGIN: called CC=1 SCAR=0.0
60 24 ▶use constant IDX_MAGIC => "SDBIDX1\n";
Subroutine BEGIN: called CC=1 SCAR=0.0
61 24 ▶use constant IDX_MAGIC_LEN => 8;
Subroutine BEGIN: called CC=1 SCAR=0.0
62 24 ▶use constant REC_NO_SIZE => 4;
Subroutine BEGIN: called CC=1 SCAR=0.0
63  
64 24 my %TYPE_SIZE = (
65 INT => 4,
66 FLOAT => 8,
67 CHAR => undef,
68 VARCHAR => undef,
69 DATE => 10,
70 );
71  
72 ###############################################################################
73 # Constructor
74 ###############################################################################
75 sub new {
76 66 ▶ my($class, %args) = @_;
Subroutine new: called CC=7 SCAR=19.9
Pod documented
77 my $self = {
78 base_dir => ($args{base_dir} || 'simpledbms_data'),
79 66 ▶ db_name => ($args{db_name} || ''),
Condition75%3/4
$args{'base_dir'} || 'simpledbms_data'
l!l
660
$args{'db_name'} || ''
l!l
165
MC/DC0%0/1
$args{'base_dir'} || 'simpledbms_data'
$args{'base_dir'}
MC/DC100%1/1
$args{'db_name'} || ''
$args{'db_name'}
Truth table50%1/2
A
A= $args{'base_dir'}
Aresult
11
00
Truth table100%2/2
A
A= $args{'db_name'}
Aresult
11
00
80 _tables => {},
81 _locks => {},
82 };
83 66 bless $self, $class;
84 66 ▶ if (($self->{db_name} ne '') && !_valid_name($self->{db_name})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"db_name"} ne "" and not _valid_name($self->{"db_name"})) 1 65 66
Condition66%2/3
$self->{"db_name"} ne "" and not _valid_name($self->{"db_name"})
!ll&&!rl&&r
6501
MC/DC50%1/2
$self->{"db_name"} ne "" and not _valid_name($self->{"db_name"})
$self->{"db_name"} ne "" not _valid_name($self->{"db_name"})
Truth table66%2/3
A and not(B)
A= $self->{"db_name"} ne ""B= not _valid_name($self->{"db_name"})
ABresult
0X0
100
111
85 1 my $bad = _shown_name($self->{db_name});
86 1 $errstr = "Invalid database name '$bad'";
87 1 return undef;
88 }
89 65 ▶ unless (-d $self->{base_dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $self->{"base_dir"}) 20 45 65
90 20 eval {
91 20 File::Path::mkpath($self->{base_dir});
92 };
93 20 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 20 20
94 0 $errstr = "Cannot create base_dir: $@";
95 0 return undef;
96 }
97 }
98 65 return $self;
99 }
100  
101 ###############################################################################
102 # Database-level
103 ###############################################################################
104 sub create_database {
105 34 ▶ my($self, $db_name) = @_;
Subroutine create_database: called CC=4 SCAR=14.0
Pod documented
106 34 ▶ unless (_valid_name($db_name)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_valid_name($db_name)) 9 25 34
107 9 my $bad = _shown_name($db_name);
108 9 $errstr = "Invalid database name '$bad'";
109 9 return 0;
110 }
111 25 my $path = $self->_db_path($db_name);
112 25 ▶ if (-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $path) 1 24 25
113 1 $errstr = "Database '$db_name' already exists";
114 1 return 0;
115 }
116 24 eval {
117 24 File::Path::mkpath($path);
118 };
119 24 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 24 24
120 0 $errstr = "Cannot create database '$db_name': $@";
121 0 return 0;
122 }
123 24 return 1;
124 }
125  
126 sub use_database {
127 83 ▶ my($self, $db_name) = @_;
Subroutine use_database: called CC=3 SCAR=11.0
Pod documented
128 83 ▶ unless (_valid_name($db_name)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_valid_name($db_name)) 9 74 83
129 9 my $bad = _shown_name($db_name);
130 9 $errstr = "Invalid database name '$bad'";
131 9 return 0;
132 }
133 74 my $path = $self->_db_path($db_name);
134 74 ▶ unless (-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $path) 8 66 74
135 8 $errstr = "Database '$db_name' does not exist";
136 8 return 0;
137 }
138 66 $self->{db_name} = $db_name;
139 66 $self->{_tables} = {};
140 66 return 1;
141 }
142  
143 sub drop_database {
144 3 ▶ my($self, $db_name) = @_;
Subroutine drop_database: called CC=5 SCAR=17.3
Pod documented
145 3 ▶ unless (_valid_name($db_name)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_valid_name($db_name)) 1 2 3
146 1 my $bad = _shown_name($db_name);
147 1 $errstr = "Invalid database name '$bad'";
148 1 return 0;
149 }
150 2 my $path = $self->_db_path($db_name);
151 2 ▶ unless (-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $path) 0 2 2
152 0 $errstr = "Database '$db_name' does not exist";
153 0 return 0;
154 }
155 2 eval {
156 2 File::Path::rmtree($path);
157 };
158 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
159 0 $errstr = "Cannot drop database '$db_name': $@";
160 0 return 0;
161 }
162 2 ▶ $self->{db_name} = '' if $self->{db_name} eq $db_name;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"db_name"} eq $db_name 2 0 2
163 2 return 1;
164 }
165  
166 sub list_databases {
167 4 ▶ my($self) = @_;
Subroutine list_databases: called CC=3 SCAR=11.3
Pod documented
168 4 my $base = $self->{base_dir};
169 4 local *DH;
170 4 ▶ opendir(DH, $base) or do { $errstr = "Cannot open base_dir: $!"; return (); };
Branch: 1 branch
BranchTrueFalseTotal
opendir DH, $base or do { $DB::Handy::errstr = "Cannot open base_dir: $!"; return () } 0 4 4
171 4 ▶ my @dbs = grep { !/^\./ && -d File::Spec->catdir($base, $_) } readdir(DH);
Branch: 1 branch
BranchTrueFalseTotal
not /^\./ and -d "File::Spec"->catdir($base, $_) 4 8 12
172 4 closedir DH;
173 4 return sort @dbs;
174 }
175  
176 ###############################################################################
177 # Table-level
178 ###############################################################################
179 sub create_table {
180 167 ▶ my($self, $table, $columns) = @_;
Subroutine create_table: called CC=22 SCAR=35.9
Pod documented
181 167 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 1 166 167
182 166 ▶ return $self->_err("Invalid table name '" . _shown_name($table) . "'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_name($table) 9 157 166
183 unless _valid_name($table);
184 157 my $sch_file = $self->_file($table, 'sch');
185 157 ▶ return $self->_err("Table '$table' already exists") if -f $sch_file;
Branch: 1 branch
BranchTrueFalseTotal
if -f $sch_file 0 157 157
186  
187 157 my @cols;
188 157 my $rec_size = 1;
189 157 for my $col (@$columns) {
190 353 my($name, $type, $size) = @$col;
191 353 $type = uc($type);
192 353 ▶ return $self->_err("Unknown type '$type'") unless exists $TYPE_SIZE{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $TYPE_SIZE{$type} 2 351 353
193 351 my $store;
194 351 ▶ if ($type eq 'CHAR') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'CHAR') { } 10 341 351
elsif ($type eq 'VARCHAR') { } 116 225 341
195 10 ▶ return $self->_err("CHAR requires a size") unless $size && ($size > 0);
Branch: 1 branch
BranchTrueFalseTotal
unless $size and $size > 0 0 10 10
Condition33%1/3
$size and $size > 0
!ll&&!rl&&r
0010
MC/DC0%0/2
$size and $size > 0
$size $size > 0
Truth table33%1/3
A and B
A= $sizeB= $size > 0
ABresult
0X0
100
111
196 10 $store = int($size);
197 }
198 elsif ($type eq 'VARCHAR') {
199 116 $store = MAX_VARCHAR;
200 }
201 else {
202 225 $store = $TYPE_SIZE{$type};
203 }
204 351 $rec_size += $store;
205 # decl is the declared size (from CREATE TABLE); for VARCHAR it may
206 # differ from the physical storage size (MAX_VARCHAR).
207 351 ▶ my $decl = (defined $size && $size > 0) ? int($size) : $store;
Branch: 1 branch
BranchTrueFalseTotal
defined $size && $size > 0 ? : 125 226 351
Condition66%2/3
defined $size and $size > 0
!ll&&!rl&&r
2260125
MC/DC50%1/2
defined $size and $size > 0
defined $size $size > 0
Truth table66%2/3
A and B
A= defined $sizeB= $size > 0
ABresult
0X0
100
111
208 351 push @cols, { name=>$name, type=>$type, size=>$store, decl=>$decl };
209 }
210  
211 155 local *FH;
212 155 ▶ open(FH, "> $sch_file") or return $self->_err("Cannot write schema: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "> $sch_file" or return $self->_err("Cannot write schema: $!") 0 155 155
213 155 my $ok = print FH "VERSION=1\n";
214 155 ▶ $ok &&= print FH "RECSIZE=$rec_size\n";
Condition33%1/3
$ok &&= print(FH "RECSIZE=$rec_size\n")
!ll&&!rl&&r
00155
MC/DC0%0/2
$ok &&= print(FH "RECSIZE=$rec_size\n")
$ok print(FH "RECSIZE=$rec_size\n")
Truth table33%1/3
A &&= B
A= $okB= print(FH "RECSIZE=$rec_size\n")
ABresult
0X0
100
111
215 155 for my $c (@cols) {
216 349 ▶ $ok &&= print FH "COL=$c->{name}:$c->{type}:$c->{size}:$c->{decl}\n";
Condition33%1/3
$ok &&= print(FH qq[COL=$c->{"name"}:$c->{"type"}:$c->{"size"}:$c->{"decl"}\n])
!ll&&!rl&&r
00349
MC/DC0%0/2
$ok &&= print(FH qq[COL=$c->{"name"}:$c->{"type"}:$c->{"size"}:$c->{"decl"}\n])
$ok print(FH qq[COL=$c->{"name"}:$c->{"type"}:$c->{"size"}:$c->{"decl"}\n])
Truth table33%1/3
A &&= B
A= $okB= print(FH qq[COL=$c->{"name"}:$c->{"type"}:$c->{"size"}:$c->{"decl"}\n])
ABresult
0X0
100
111
217 }
218 155 my $err = $!;
219 155 ▶ unless ($ok && close(FH)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok and close FH) 0 155 155
Condition33%1/3
$ok and close FH
!ll&&!rl&&r
00155
MC/DC0%0/2
$ok and close FH
$ok close FH
Truth table33%1/3
A and B
A= $okB= close FH
ABresult
0X0
100
111
220 0 ▶ $err = $! if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
221 0 ▶ close FH if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
222 0 unlink $sch_file;
223 0 return $self->_err("Cannot write schema: $err");
224 }
225  
226 155 local *FH;
227 155 my $dat_file = $self->_file($table, 'dat');
228 155 ▶ open(FH, "> $dat_file") or return $self->_err("Cannot create dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "> $dat_file" or return $self->_err("Cannot create dat: $!") 0 155 155
229 155 binmode FH;
230 155 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 155 155
231 0 my $e = $!;
232 0 unlink $sch_file;
233 0 return $self->_err("Cannot create dat: $e");
234 }
235 155 return 1;
236 }
237  
238 sub drop_table {
239 13 ▶ my($self, $table) = @_;
Subroutine drop_table: called CC=12 SCAR=25.6
Pod documented
240 13 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 13 13
241 13 ▶ return $self->_err("Invalid table name '" . _shown_name($table) . "'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_name($table) 9 4 13
242 unless _valid_name($table);
243 4 my $sch = $self->_load_schema($table);
244 4 ▶ if ($sch && $sch->{indexes}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sch and $sch->{"indexes"}) 4 0 4
Condition33%1/3
$sch and $sch->{"indexes"}
!ll&&!rl&&r
004
MC/DC0%0/2
$sch and $sch->{"indexes"}
$sch $sch->{"indexes"}
Truth table33%1/3
A and B
A= $schB= $sch->{"indexes"}
ABresult
0X0
100
111
245 4 for my $ix (values %{$sch->{indexes}}) {
246 1 my $f = $self->_idx_file($table, $ix->{name});
247 1 ▶ unlink $f if -f $f;
Branch: 1 branch
BranchTrueFalseTotal
if -f $f 1 0 1
248 }
249 }
250 4 for my $ext (qw(sch dat lck)) {
251 12 my $f = $self->_file($table, $ext);
252 12 ▶ unlink $f if -f $f;
Branch: 1 branch
BranchTrueFalseTotal
if -f $f 8 4 12
253 }
254 4 my $dir = $self->_db_path($self->{db_name});
255 4 local *DH;
256 4 ▶ if (opendir DH, $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (opendir DH, $dir) 4 0 4
257 4 for my $f (readdir DH) {
258 28 ▶ unlink File::Spec->catfile($dir, $f) if $f =~ /^\Q${table}\E\.[^.]+\.idx$/;
Branch: 1 branch
BranchTrueFalseTotal
if $f =~ /^\Q$table\E\.[^.]+\.idx$/ 0 28 28
259 }
260 4 closedir DH;
261 }
262 4 delete $self->{_tables}{$table};
263 4 return 1;
264 }
265  
266 sub list_tables {
267 6 ▶ my($self) = @_;
Subroutine list_tables: called CC=4 SCAR=14.0
Pod documented
268 6 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 6 6
269 6 my $dir = $self->_db_path($self->{db_name});
270 6 local *DH;
271 6 ▶ opendir(DH, $dir) or return ();
Branch: 1 branch
BranchTrueFalseTotal
opendir DH, $dir or return () 0 6 6
272 6 ▶ my @tbls = map { /^(.+)\.sch$/ ? $1 : () } readdir DH;
Branch: 1 branch
BranchTrueFalseTotal
/^(.+)\.sch$/ ? : 22 37 59
273 6 closedir DH;
274 6 return sort @tbls;
275 }
276  
277 sub describe_table {
278 6 ▶ my($self, $table) = @_;
Subroutine describe_table: called CC=2 SCAR=6.9
Pod documented
279 6 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 1 5 6
280 5 return $sch->{cols};
281 }
282  
283 ###############################################################################
284 # INDEX DDL
285 ###############################################################################
286 sub create_index {
287 64 ▶ my($self, $idxname, $table, $colname, $unique) = @_;
Subroutine create_index: called CC=12 SCAR=28.7
Pod documented
288 64 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 64 64
289 64 ▶ return $self->_err("Invalid index name '" . _shown_name($idxname) . "'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_name($idxname) 9 55 64
290 unless _valid_name($idxname);
291 55 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 0 55 55
292  
293 55 my($col_def) = grep { $_->{name} eq $colname } @{$sch->{cols}};
294 55 ▶ return $self->_err("Column '$colname' not found in '$table'") unless $col_def;
Branch: 1 branch
BranchTrueFalseTotal
unless $col_def 0 55 55
295 55 ▶ return $self->_err("Index '$idxname' already exists on '$table'") if $sch->{indexes}{$idxname};
Branch: 1 branch
BranchTrueFalseTotal
if $sch->{"indexes"}{$idxname} 0 55 55
296  
297 55 ▶ $unique = $unique ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$unique ? : 22 33 55
298  
299 55 my $sch_file = $self->_file($table, 'sch');
300 55 local *FH;
301 55 ▶ open(FH, ">> $sch_file") or return $self->_err("Cannot update schema: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, ">> $sch_file" or return $self->_err("Cannot update schema: $!") 0 55 55
302 55 my $ok = print FH "IDX=$idxname:$colname:$unique\n";
303 55 my $err = $!;
304 55 ▶ unless ($ok && close(FH)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok and close FH) 0 55 55
Condition33%1/3
$ok and close FH
!ll&&!rl&&r
0055
MC/DC0%0/2
$ok and close FH
$ok close FH
Truth table33%1/3
A and B
A= $okB= close FH
ABresult
0X0
100
111
305 0 ▶ $err = $! if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
306 0 ▶ close FH if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
307 0 return $self->_err("Cannot update schema: $err");
308 }
309  
310 $sch->{indexes}{$idxname} = {
311 name => $idxname,
312 col => $colname,
313 unique => $unique,
314 keysize => $col_def->{size},
315 coltype => $col_def->{type},
316 55 };
317  
318 55 return $self->_rebuild_index($table, $idxname);
319 }
320  
321 sub drop_index {
322 11 ▶ my($self, $idxname, $table) = @_;
Subroutine drop_index: called CC=5 SCAR=16.4
Pod documented
323 11 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 11 11
324 11 ▶ return $self->_err("Invalid index name '" . _shown_name($idxname) . "'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_name($idxname) 9 2 11
325 unless _valid_name($idxname);
326 2 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 0 2 2
327 2 ▶ return $self->_err("Index '$idxname' does not exist on '$table'") unless $sch->{indexes}{$idxname};
Branch: 1 branch
BranchTrueFalseTotal
unless $sch->{"indexes"}{$idxname} 0 2 2
328  
329 2 unlink $self->_idx_file($table, $idxname);
330 2 delete $sch->{indexes}{$idxname};
331 2 return $self->_rewrite_schema($table, $sch);
332 }
333  
334 sub list_indexes {
335 8 ▶ my($self, $table) = @_;
Subroutine list_indexes: called CC=3 SCAR=11.0
Pod documented
336 8 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 8 8
337 8 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 1 7 8
338 7 return [ values %{$sch->{indexes}} ];
339 }
340  
341 ###############################################################################
342 # DML: INSERT
343 ###############################################################################
344 sub insert {
345 2014 ▶ my($self, $table, $row) = @_;
Subroutine insert: called CC=37 SCAR=36.8
Pod documented
346 2014 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 2014 2014
347 2014 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 2 2012 2014
348  
349 2012 for my $col (@{$sch->{cols}}) {
350 3520 my $cn = $col->{name};
351 3520 ▶ if ((!defined($row->{$cn}) || ($row->{$cn} eq '')) && defined $sch->{defaults}{$cn}) {
Branch: 1 branch
BranchTrueFalseTotal
if (!defined($row->{$cn}) || $row->{$cn} eq "" and defined $sch->{"defaults"}{$cn}) 16 3504 3520
Condition100%6/6
!defined($row->{$cn}) || $row->{$cn} eq "" and defined $sch->{"defaults"}{$cn}
!ll&&!rl&&r
34327216
not defined $row->{$cn} or $row->{$cn} eq ""
l!l&&r!l&&!r
8443432
MC/DC66%2/3
!defined($row->{$cn}) || $row->{$cn} eq "" and defined $sch->{"defaults"}{$cn}
not defined $row->{$cn} $row->{$cn} eq "" defined $sch->{"defaults"}{$cn}
Truth table80%4/5
not(A) or B and C
A= not defined $row->{$cn}B= $row->{$cn} eq ""C= defined $sch->{"defaults"}{$cn}
ABCresult
00X0
1X00
0100
1X11
0111
352 16 $row->{$cn} = $sch->{defaults}{$cn};
353 }
354 }
355  
356 # UNIQUE check. It runs after DEFAULT has been applied, so that the
357 # value actually stored is the one compared. NULL is the empty string
358 # here and SQL-92 lets a UNIQUE column hold any number of NULLs, so an
359 # absent value is not compared at all.
360 2012 for my $ix (values %{$sch->{indexes}}) {
361 1959 ▶ next unless $ix->{unique};
Branch: 1 branch
BranchTrueFalseTotal
unless $ix->{"unique"} 1891 68 1959
362 68 my $val = $row->{$ix->{col}};
363 68 ▶ next unless defined($val) && ($val ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and $val ne "" 4 64 68
Condition66%2/3
defined $val and $val ne ""
!ll&&!rl&&r
4064
MC/DC50%1/2
defined $val and $val ne ""
defined $val $val ne ""
Truth table66%2/3
A and B
A= defined $valB= $val ne ""
ABresult
0X0
100
111
364 64 ▶ if ($self->_idx_lookup_exact($table, $ix, $val) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_idx_lookup_exact($table, $ix, $val) >= 0) 9 55 64
365 9 return $self->_err("UNIQUE constraint violated on '$ix->{name}' (col '$ix->{col}', value '$val')");
366 }
367 }
368  
369 2003 ▶ for my $cn (keys %{$sch->{notnull} || {}}) {
Branch: 1 branch
BranchTrueFalseTotal
$sch->{"notnull"} or {} 0 2003 2003
370 48 ▶ return $self->_err("NOT NULL constraint violated on column '$cn'") unless defined($row->{$cn}) && ($row->{$cn} ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row->{$cn} and $row->{$cn} ne "" 8 40 48
Condition100%3/3
defined $row->{$cn} and $row->{$cn} ne ""
!ll&&!rl&&r
7140
MC/DC100%2/2
defined $row->{$cn} and $row->{$cn} ne ""
defined $row->{$cn} $row->{$cn} ne ""
Truth table100%3/3
A and B
A= defined $row->{$cn}B= $row->{$cn} ne ""
ABresult
0X0
100
111
371 }
372 1995 ▶ for my $cn (keys %{$sch->{checks} || {}}) {
Branch: 1 branch
BranchTrueFalseTotal
$sch->{"checks"} or {} 0 1995 1995
373 16 ▶ next unless defined($row->{$cn}) && ($row->{$cn} ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row->{$cn} and $row->{$cn} ne "" 2 14 16
Condition66%2/3
defined $row->{$cn} and $row->{$cn} ne ""
!ll&&!rl&&r
2014
MC/DC50%1/2
defined $row->{$cn} and $row->{$cn} ne ""
defined $row->{$cn} $row->{$cn} ne ""
Truth table66%2/3
A and B
A= defined $row->{$cn}B= $row->{$cn} ne ""
ABresult
0X0
100
111
374 14 ▶ return $self->_err("CHECK constraint failed on column '$cn'") unless eval_bool($sch->{checks}{$cn}, $row);
Branch: 1 branch
BranchTrueFalseTotal
unless eval_bool($sch->{"checks"}{$cn}, $row) 5 9 14
375 }
376 # VARCHAR / CHAR length check: reject values longer than the declared size.
377 1990 for my $col (@{$sch->{cols}}) {
378 3461 my $cn = $col->{name};
379 3461 ▶ next unless ($col->{type} eq 'VARCHAR' || $col->{type} eq 'CHAR');
Branch: 1 branch
BranchTrueFalseTotal
unless $col->{"type"} eq "VARCHAR" or $col->{"type"} eq "CHAR" 2405 1056 3461
Condition100%3/3
$col->{"type"} eq "VARCHAR" or $col->{"type"} eq "CHAR"
l!l&&r!l&&!r
1005512405
MC/DC100%2/2
$col->{"type"} eq "VARCHAR" or $col->{"type"} eq "CHAR"
$col->{"type"} eq "VARCHAR" $col->{"type"} eq "CHAR"
Truth table100%3/3
A or B
A= $col->{"type"} eq "VARCHAR"B= $col->{"type"} eq "CHAR"
ABresult
1X1
011
000
380 1056 ▶ my $decl = defined($col->{decl}) ? $col->{decl} : $col->{size};
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'decl'} ? : 1056 0 1056
381 1056 ▶ next unless defined($decl) && ($decl < MAX_VARCHAR);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decl and $decl < 255 2 1054 1056
Condition66%2/3
defined $decl and $decl < 255
!ll&&!rl&&r
021054
MC/DC50%1/2
defined $decl and $decl < 255
defined $decl $decl < 255
Truth table66%2/3
A and B
A= defined $declB= $decl < 255
ABresult
0X0
100
111
382 1054 ▶ next unless defined($row->{$cn}) && ($row->{$cn} ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row->{$cn} and $row->{$cn} ne "" 28 1026 1054
Condition100%3/3
defined $row->{$cn} and $row->{$cn} ne ""
!ll&&!rl&&r
2621026
MC/DC100%2/2
defined $row->{$cn} and $row->{$cn} ne ""
defined $row->{$cn} $row->{$cn} ne ""
Truth table100%3/3
A and B
A= defined $row->{$cn}B= $row->{$cn} ne ""
ABresult
0X0
100
111
383 1026 ▶ if (length($row->{$cn}) > $decl) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $row->{$cn} > $decl) 3 1023 1026
384 return $self->_err(
385 "Value too long for column '$cn': "
386 . "declared $col->{type}($decl), got "
387 3 . length($row->{$cn}) . " bytes"
388 );
389 }
390 }
391 # Type check: INT range and DATE validity.
392 1987 for my $col (@{$sch->{cols}}) {
393 3440 my $msg = _type_error($col, $row->{$col->{name}});
394 3440 ▶ return $self->_err($msg) if defined $msg;
Branch: 1 branch
BranchTrueFalseTotal
if defined $msg 11 3429 3440
395 }
396 1976 ▶ my $packed = $self->_pack_record($sch, $row) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $packed = $self->_pack_record($sch, $row) or return undef 0 1976 1976
397 1976 my $dat = $self->_file($table, 'dat');
398 1976 local *FH;
399 1976 ▶ open(FH, ">> $dat") or return $self->_err("Cannot open dat for append: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, ">> $dat" or return $self->_err("Cannot open dat for append: $!") 2 1974 1976
400 1974 binmode FH;
401 1974 _autoflush(\*FH);
402 1974 _lock_ex(\*FH);
403 1974 my $file_size = (stat FH)[7];
404 1974 my $rec_no = int($file_size / $sch->{recsize});
405 1974 ▶ unless (print FH $packed) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print FH $packed) 0 1974 1974
406 0 my $e = $!;
407 0 _unlock(\*FH);
408 0 close FH;
409 0 return $self->_err("Cannot write record: $e");
410 }
411  
412 # The .dat lock is held until every index is updated, so that another
413 # process never sees the new record without its index entries.
414 1974 for my $ix (values %{$sch->{indexes}}) {
415 1943 $self->_idx_insert($table, $ix, $row->{$ix->{col}}, $rec_no);
416 }
417 1974 _unlock(\*FH);
418 1974 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 1974 1974
419 0 return $self->_err("Cannot flush record: $!");
420 }
421 1974 return 1;
422 }
423  
424 sub delete_rows {
425 13 ▶ my($self, $table, $where_info) = @_;
Subroutine delete_rows: called CC=12 SCAR=25.6
Pod documented
426 13 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 13 13
427 13 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 1 12 13
428 12 my $where_sub = _to_where_sub($where_info);
429 12 my $dat = $self->_file($table, 'dat');
430 12 my $recsize = $sch->{recsize};
431 12 my $count = 0;
432  
433 12 local *FH;
434 12 ▶ open(FH, "+< $dat") or return $self->_err("Cannot open dat for delete: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "+< $dat" or return $self->_err("Cannot open dat for delete: $!") 0 12 12
435 12 binmode FH;
436 12 _autoflush(\*FH);
437 12 _lock_ex(\*FH);
438  
439 12 seek(FH, 0, 0);
440 12 my($pos, $rec_no) = (0, 0);
441 12 while (1) {
442 93 seek(FH, $pos, 0);
443 93 my $raw = '';
444 93 my $n = read(FH, $raw, $recsize);
445 93 ▶ last unless defined($n) && ($n == $recsize);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $recsize 12 81 93
Condition66%2/3
defined $n and $n == $recsize
!ll&&!rl&&r
01281
MC/DC50%1/2
defined $n and $n == $recsize
defined $n $n == $recsize
Truth table66%2/3
A and B
A= defined $nB= $n == $recsize
ABresult
0X0
100
111
446 81 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 76 5 81
447 76 my $row = $self->_unpack_record($sch, $raw);
448 76 ▶ if (!$where_sub || $where_sub->($row)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $where_sub or &$where_sub($row)) 14 62 76
Condition66%2/3
not $where_sub or &$where_sub($row)
l!l&&r!l&&!r
01462
MC/DC50%1/2
not $where_sub or &$where_sub($row)
not $where_sub &$where_sub($row)
Truth table66%2/3
not(A) or B
A= not $where_subB= &$where_sub($row)
ABresult
1X1
011
000
449 14 seek(FH, $pos, 0);
450 14 ▶ unless (print FH RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print FH "\0") 0 14 14
451 0 my $e = $!;
452 0 _unlock(\*FH);
453 0 close FH;
454 0 return $self->_err("Cannot mark record deleted: $e");
455 }
456 14 $count++;
457 14 for my $ix (values %{$sch->{indexes}}) {
458 10 $self->_idx_delete($table, $ix, $row->{$ix->{col}}, $rec_no);
459 }
460 }
461 }
462 81 $pos += $recsize;
463 81 $rec_no++;
464 }
465 12 _unlock(\*FH);
466 12 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 12 12
467 0 return $self->_err("Cannot flush dat: $!");
468 }
469 12 return $count;
470 }
471  
472 ###############################################################################
473 # VACUUM
474 ###############################################################################
475 sub vacuum {
476 4 ▶ my($self, $table) = @_;
Subroutine vacuum: called CC=13 SCAR=29.0
Pod documented
477 4 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 4 4
478 4 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 1 3 4
479 3 my $dat = $self->_file($table, 'dat');
480 3 my $tmp = $dat . '.tmp';
481 3 my $recsize = $sch->{recsize};
482  
483 3 local *IN_FH;
484 3 ▶ open(IN_FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open IN_FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 3 3
485 3 local *OUT_FH;
486 3 ▶ open(OUT_FH, "> $tmp") or do { close IN_FH; return $self->_err("Cannot open tmp: $!"); };
Branch: 1 branch
BranchTrueFalseTotal
open OUT_FH, "> $tmp" or do { close IN_FH; return $self->_err("Cannot open tmp: $!") } 0 3 3
487 3 binmode IN_FH;
488 3 binmode OUT_FH;
489 3 _lock_ex(\*IN_FH);
490  
491 3 my $kept = 0;
492 3 while (1) {
493 26 my $raw = '';
494 26 my $n = read(IN_FH, $raw, $recsize);
495 26 ▶ last unless defined($n) && ($n == $recsize);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $recsize 3 23 26
Condition66%2/3
defined $n and $n == $recsize
!ll&&!rl&&r
0323
MC/DC50%1/2
defined $n and $n == $recsize
defined $n $n == $recsize
Truth table66%2/3
A and B
A= defined $nB= $n == $recsize
ABresult
0X0
100
111
496 23 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 18 5 23
497 18 ▶ unless (print OUT_FH $raw) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print OUT_FH $raw) 0 18 18
498 0 my $e = $!;
499 0 close OUT_FH;
500 0 _unlock(\*IN_FH);
501 0 close IN_FH;
502 0 unlink $tmp;
503 0 return $self->_err("Cannot write tmp: $e");
504 }
505 18 $kept++;
506 }
507 }
508 # close() flushes, so the replacement file is complete on disk before
509 # the exclusive lock on the original is released.
510 3 my $out_ok = close(OUT_FH);
511 3 my $out_err = $!;
512 3 _unlock(\*IN_FH);
513 3 close IN_FH;
514 3 ▶ unless ($out_ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($out_ok) 0 3 3
515 0 unlink $tmp;
516 0 return $self->_err("Cannot flush tmp: $out_err");
517 }
518 3 ▶ rename($tmp, $dat) or do {
Branch: 1 branch
BranchTrueFalseTotal
rename $tmp, $dat or do { my $e = $!; unlink $tmp; return $self->_err("Cannot replace dat: $e") } 0 3 3
519 0 my $e = $!;
520 0 unlink $tmp;
521 0 return $self->_err("Cannot replace dat: $e");
522 };
523  
524 3 for my $ix (values %{$sch->{indexes}}) {
525 4 ▶ $self->_rebuild_index($table, $ix->{name}) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->_rebuild_index($table, $ix->{"name"}) or return undef 0 4 4
526 }
527 3 return $kept;
528 }
529  
530 ###############################################################################
531 # execute()
532 ###############################################################################
533 sub execute {
534 3111 ▶ my($self, $sql) = @_;
Subroutine execute: called CC=81 SCAR=45.0
Pod documented
535 3111 $sql = _strip_sql_comments($sql);
536 3111 $sql =~ s/^\s+|\s+$//g;
537 3111 $sql = _normalize_sql_space($sql);
538  
539 # Detect subqueries: any SELECT that contains a nested (SELECT ...)
540 # Route through the subquery engine, but guard against infinite recursion
541 # by only routing non-trivial top-level statements (not pure SELECT).
542 3111 ▶ if ($sql =~ /\(\s*SELECT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\(\s*SELECT\b/i) 44 3067 3111
543  
544 # Only intercept DML/DDL statements and complex SELECTs here;
545 # pure inner SELECTs (called recursively) pass through normally.
546 # Top-level statements that may contain subqueries:
547 44 ▶ if ($sql =~ /^(?:SELECT|INSERT|UPDATE|DELETE)\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^(?:SELECT|INSERT|UPDATE|DELETE)\b/i) 44 0 44
548 44 return $self->execute_with_subquery($sql);
549 }
550 }
551  
552 3067 ▶ if ($sql =~ /^CREATE\s+DATABASE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^CREATE\s+DATABASE\s+(\w+)$/i) 9 3058 3067
553 9 ▶ return $self->create_database($1)
Branch: 1 branch
BranchTrueFalseTotal
$self->create_database($1) ? : 9 0 9
554 ? { type=>'ok', message=>"Database '$1' created" }
555 : { type=>'error', message=>$errstr };
556 }
557 3058 ▶ if ($sql =~ /^USE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^USE\s+(\w+)$/i) 54 3004 3058
558 54 ▶ return $self->use_database($1)
Branch: 1 branch
BranchTrueFalseTotal
$self->use_database($1) ? : 47 7 54
559 ? { type=>'ok', message=>"Using database '$1'" }
560 : { type=>'error', message=>$errstr };
561 }
562 3004 ▶ if ($sql =~ /^DROP\s+DATABASE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DROP\s+DATABASE\s+(\w+)$/i) 0 3004 3004
563 0 ▶ return $self->drop_database($1)
Branch: 1 branch
BranchTrueFalseTotal
$self->drop_database($1) ? : 0 0 0
564 ? { type=>'ok', message=>"Database '$1' dropped" }
565 : { type=>'error', message=>$errstr };
566 }
567 3004 ▶ if ($sql =~ /^SHOW\s+DATABASES$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SHOW\s+DATABASES$/i) 1 3003 3004
568 1 return { type=>'list', data=>[ $self->list_databases() ] };
569 }
570 3003 ▶ if ($sql =~ /^SHOW\s+TABLES$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SHOW\s+TABLES$/i) 1 3002 3003
571 1 return { type=>'list', data=>[ $self->list_tables() ] };
572 }
573 3002 ▶ if ($sql =~ /^SHOW\s+(?:INDEXES|INDICES|INDEX)\s+(?:ON|FROM)\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SHOW\s+(?:INDEXES|INDICES|INDEX)\s+(?:ON|FROM)\s+(\w+)$/i) 1 3001 3002
574 1 my $ixs = $self->list_indexes($1);
575 1 ▶ return defined($ixs)
Branch: 1 branch
BranchTrueFalseTotal
defined $ixs ? : 1 0 1
576 ? { type=>'indexes', table=>$1, data=>$ixs }
577 : { type=>'error', message=>$errstr };
578 }
579 3001 ▶ if ($sql =~ /^DESCRIBE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DESCRIBE\s+(\w+)$/i) 2 2999 3001
580 2 my $cols = $self->describe_table($1);
581 2 ▶ return $cols
Branch: 1 branch
BranchTrueFalseTotal
$cols ? : 2 0 2
582 ? { type=>'describe', data=>$cols }
583 : { type=>'error', message=>$errstr };
584 }
585 2999 ▶ if ($sql =~ /^CREATE\s+TABLE\s+(\w+)\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^CREATE\s+TABLE\s+(\w+)\s*\((.+)\)$/is) 156 2843 2999
586 156 my($tbl, $col_str) = ($1, $2);
587 156 my @col_defs = _split_col_defs($col_str);
588 156 my(@cols, %nn, %defs, %chks, %uniq, $pk);
589 156 for my $cd (@col_defs) {
590 353 $cd =~ s/^\s+|\s+$//g;
591 353 ▶ if ($cd =~ /^PRIMARY\s+KEY\s*\(\s*(\w+)\s*\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cd =~ /^PRIMARY\s+KEY\s*\(\s*(\w+)\s*\)$/is) 0 353 353
592 0 $pk = $1;
593 0 next;
594 }
595 # Table-level UNIQUE (col): enforced through a unique index,
596 # exactly like the column-level UNIQUE modifier below.
597 353 ▶ if ($cd =~ /^UNIQUE\s*\(\s*(\w+)\s*\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cd =~ /^UNIQUE\s*\(\s*(\w+)\s*\)$/is) 1 352 353
598 1 $uniq{$1} = 1;
599 1 next;
600 }
601 # FOREIGN KEY (...) REFERENCES ...: table-level constraint.
602 # Accepted silently (constraint is not enforced).
603 352 ▶ if ($cd =~ /^FOREIGN\s+KEY\b/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cd =~ /^FOREIGN\s+KEY\b/is) 1 351 352
604 1 next;
605 }
606 351 my($cn, $ct, $cs, $rest);
607 351 ▶ if ($cd =~ /^(\w+)\s+(CHAR|VARCHAR)\s*\(\s*(\d+)\s*\)(.*)/si) {
Branch: 2 branches
BranchTrueFalseTotal
if ($cd =~ /^(\w+)\s+(CHAR|VARCHAR)\s*\(\s*(\d+)\s*\)(.*)/is) { } 124 227 351
elsif ($cd =~ /^(\w+)\s+(\w+)(.*)/is) { } 227 0 227
608 124 ($cn, $ct, $cs, $rest) = ($1, uc($2), $3, $4);
609 }
610 elsif ($cd =~ /^(\w+)\s+(\w+)(.*)/si) {
611 227 ($cn, $ct, $rest) = ($1, uc($2), $3);
612 227 $cs = undef;
613 }
614 else {
615 0 return { type=>'error', message=>"Cannot parse column def: $cd" };
616 }
617 351 push @cols, [ $cn, $ct, $cs ];
618 351 ▶ $rest = '' unless defined $rest;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rest 0 351 351
619 351 ▶ $pk = $cn if $rest =~ /\bPRIMARY\s+KEY\b/si;
Branch: 1 branch
BranchTrueFalseTotal
if $rest =~ /\bPRIMARY\s+KEY\b/is 7 344 351
620 351 ▶ $nn{$cn} = 1 if $rest =~ /\b(?:NOT\s+NULL|PRIMARY\s+KEY)\b/si;
Branch: 1 branch
BranchTrueFalseTotal
if $rest =~ /\b(?:NOT\s+NULL|PRIMARY\s+KEY)\b/is 21 330 351
621 351 ▶ $defs{$cn} = (defined($1) ? $1 : $2) if $rest =~ /\bDEFAULT\s+(?:'([^']*)'|(-?\d+\.?\d*))/si;
Branch: 2 branches
BranchTrueFalseTotal
if $rest =~ /\bDEFAULT\s+(?:'([^']*)'|(-?\d+\.?\d*))/is 7 344 351
defined $1 ? : 3 4 7
622 351 ▶ $chks{$cn} = $1 if $rest =~ /\bCHECK\s*\((.+)\)/si;
Branch: 1 branch
BranchTrueFalseTotal
if $rest =~ /\bCHECK\s*\((.+)\)/is 8 343 351
623 # UNIQUE is looked for with the CHECK expression removed, so
624 # that a CHECK body that happens to mention the word cannot
625 # produce a false hit.
626 351 my $ukw = $rest;
627 351 $ukw =~ s/\bCHECK\s*\(.+\)//si;
628 351 ▶ $uniq{$cn} = 1 if $ukw =~ /\bUNIQUE\b/si;
Branch: 1 branch
BranchTrueFalseTotal
if $ukw =~ /\bUNIQUE\b/is 3 348 351
629 }
630 156 ▶ $nn{$pk} = 1 if defined $pk;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pk 7 149 156
631 156 ▶ $self->create_table($tbl, [ @cols ]) or return { type=>'error', message=>$errstr };
Branch: 1 branch
BranchTrueFalseTotal
$self->create_table($tbl, [@cols]) or return {"type", "error", "message", $DB::Handy::errstr} 3 153 156
632 153 ▶ if (%nn || %defs || %chks || defined $pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (%nn or %defs or %chks or defined $pk) 2 134 136
Condition88%8/9
%nn or %defs or %chks or defined $pk
l!l&&r!l&&!r
190134
%nn or %defs or %chks
l!l&&r!l&&!r
172134
%nn or %defs
l!l&&r!l&&!r
161136
MC/DC75%3/4
%nn or %defs or %chks or defined $pk
%nn %defs %chks defined $pk
Truth table80%4/5
A or B or C or D
A= %nnB= %defsC= %chksD= defined $pk
ABCDresult
1XXX1
01XX1
001X1
00011
00000
633 19 ▶ my $sch = $self->_load_schema($tbl) or return { type=>'error', message=>$errstr };
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($tbl) or return {"type", "error", "message", $DB::Handy::errstr} 0 19 19
634 19 $sch->{notnull} = { %nn };
635 19 $sch->{defaults} = { %defs };
636 19 $sch->{checks} = { %chks };
637 19 ▶ $sch->{pk} = $pk if defined $pk;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pk 7 12 19
638 19 $self->_rewrite_schema($tbl, $sch);
639 }
640  
641 # PRIMARY KEY and UNIQUE are enforced by insert() and update()
642 # through a unique index, so one has to be created here. Without
643 # it both constraints were silently accepted and never checked.
644 # A column that is both PRIMARY KEY and UNIQUE gets a single index.
645 153 my(@auto_idx, %seen_idx);
646 153 ▶ if (defined $pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pk) 7 146 153
647 7 push @auto_idx, [ $pk, $pk . '_pk' ];
648 7 $seen_idx{$pk} = 1;
649 }
650 153 for my $c (@cols) {
651 346 my $cn = $c->[0];
652 346 ▶ next unless $uniq{$cn};
Branch: 1 branch
BranchTrueFalseTotal
unless $uniq{$cn} 342 4 346
653 4 ▶ next if $seen_idx{$cn}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_idx{$cn}++ 1 3 4
654 3 push @auto_idx, [ $cn, $cn . '_unique' ];
655 }
656 153 for my $ai (@auto_idx) {
657 10 ▶ next if $self->create_index($ai->[1], $tbl, $ai->[0], 1);
Branch: 1 branch
BranchTrueFalseTotal
if $self->create_index($ai->[1], $tbl, $ai->[0], 1) 10 0 10
658 0 my $msg = $errstr;
659 0 $self->drop_table($tbl);
660 0 return { type=>'error', message=>$msg };
661 }
662  
663 153 ▶ my $fk_note = ($col_str =~ /\bREFERENCES\b/si
Branch: 1 branch
BranchTrueFalseTotal
$col_str =~ /\bREFERENCES\b/is || $col_str =~ /\bFOREIGN\s+KEY\b/is ? : 3 150 153
Condition66%2/3
$col_str =~ /\bREFERENCES\b/is or $col_str =~ /\bFOREIGN\s+KEY\b/is
l!l&&r!l&&!r
30150
MC/DC50%1/2
$col_str =~ /\bREFERENCES\b/is or $col_str =~ /\bFOREIGN\s+KEY\b/is
$col_str =~ /\bREFERENCES\b/is $col_str =~ /\bFOREIGN\s+KEY\b/is
Truth table66%2/3
A or B
A= $col_str =~ /\bREFERENCES\b/isB= $col_str =~ /\bFOREIGN\s+KEY\b/is
ABresult
1X1
011
000
664 || $col_str =~ /\bFOREIGN\s+KEY\b/si)
665 ? " (NOTE: FOREIGN KEY constraints are not enforced)"
666 : "";
667 153 return { type=>'ok', message=>"Table '$tbl' created$fk_note" };
668 }
669 2843 ▶ if ($sql =~ /^DROP\s+TABLE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DROP\s+TABLE\s+(\w+)$/i) 3 2840 2843
670 3 ▶ return $self->drop_table($1)
Branch: 1 branch
BranchTrueFalseTotal
$self->drop_table($1) ? : 3 0 3
671 ? { type=>'ok', message=>"Table '$1' dropped" }
672 : { type=>'error', message=>$errstr };
673 }
674 2840 ▶ if ($sql =~ /^CREATE\s+(UNIQUE\s+)?INDEX\s+(\w+)\s+ON\s+(\w+)\s*\(\s*(\w+)\s*\)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^CREATE\s+(UNIQUE\s+)?INDEX\s+(\w+)\s+ON\s+(\w+)\s*\(\s*(\w+)\s*\)$/i) 44 2796 2840
675 44 my($uniq, $idxname, $tbl, $col) = ($1, $2, $3, $4);
676 44 ▶ return $self->create_index($idxname, $tbl, $col, $uniq ? 1 : 0)
Branch: 2 branches
BranchTrueFalseTotal
$self->create_index($idxname, $tbl, $col, $uniq ? 1 : 0) ? : 44 0 44
$uniq ? : 11 33 44
677 ? { type=>'ok', message=>"Index '$idxname' created on '$tbl'('$col')" }
678 : { type=>'error', message=>$errstr };
679 }
680 2796 ▶ if ($sql =~ /^DROP\s+INDEX\s+(\w+)\s+ON\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DROP\s+INDEX\s+(\w+)\s+ON\s+(\w+)$/i) 1 2795 2796
681 1 ▶ return $self->drop_index($1, $2)
Branch: 1 branch
BranchTrueFalseTotal
$self->drop_index($1, $2) ? : 1 0 1
682 ? { type=>'ok', message=>"Index '$1' dropped" }
683 : { type=>'error', message=>$errstr };
684 }
685 2795 ▶ if ($sql =~ /^VACUUM\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^VACUUM\s+(\w+)$/i) 2 2793 2795
686 2 my $n = $self->vacuum($1);
687 2 ▶ return defined($n)
Branch: 1 branch
BranchTrueFalseTotal
defined $n ? : 2 0 2
688 ? { type=>'ok', message=>"Vacuum done, $n records kept" }
689 : { type=>'error', message=>$errstr };
690 }
691 # INSERT INTO table VALUES (...) -- no column list: use schema order
692 2793 ▶ if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s+VALUES\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s+VALUES\s*\((.+)\)$/is) 11 2782 2793
693 11 my($tbl, $val_str) = ($1, $2);
694 11 ▶ my $sch = $self->_load_schema($tbl)
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($tbl) or return {"type", "error", "message", "Table '${tbl}' does not exist"} 1 10 11
695 or return { type=>'error', message=>"Table '$tbl' does not exist" };
696 10 my @cols = map { $_->{name} } @{$sch->{cols}};
697 10 my @v = _parse_values($val_str);
698 10 ▶ if (@v != @cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@v != @cols) 2 8 10
699 2 return { type=>'error',
700 message=>"INSERT: " . scalar(@v) . " value(s) for "
701 . scalar(@cols) . " column(s) in table '$tbl'" };
702 }
703 8 my %row;
704 8 @row{@cols} = @v;
705 8 ▶ return $self->insert($tbl, { %row })
Branch: 1 branch
BranchTrueFalseTotal
$self->insert($tbl, {%row}) ? : 8 0 8
706 ? { type=>'ok', message=>"1 row inserted" }
707 : { type=>'error', message=>$errstr };
708 }
709 2782 ▶ if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s*\(([^)]+)\)\s*VALUES\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s*\(([^)]+)\)\s*VALUES\s*\((.+)\)$/is) 1971 811 2782
710 1971 my($tbl, $col_str, $val_str) = ($1, $2, $3);
711 1971 my @c = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $col_str;
712 1971 my @v = _parse_values($val_str);
713 1971 my %row;
714 1971 @row{@c} = @v;
715 1971 ▶ return $self->insert($tbl, { %row })
Branch: 1 branch
BranchTrueFalseTotal
$self->insert($tbl, {%row}) ? : 1932 39 1971
716 ? { type=>'ok', message=>"1 row inserted" }
717 : { type=>'error', message=>$errstr };
718 }
719 811 ▶ if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s*\(([^)]+)\)\s+(SELECT\b.+)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s*\(([^)]+)\)\s+(SELECT\b.+)$/is) 12 799 811
720 12 my($tbl, $cs, $sel) = ($1, $2, $3);
721 12 my @dst_cols = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $cs;
722  
723 # Extract SELECT column list in declaration order.
724 # The engine stores rows as hashes (alphabetical key order), so we
725 # must parse the SELECT list to know the intended positional mapping.
726 12 my @src_cols;
727 12 ▶ if ($sel =~ /^SELECT\s+(.*?)\s+FROM\s+/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel =~ /^SELECT\s+(.*?)\s+FROM\s+/is) 12 0 12
728 12 @src_cols = map { my $c = $_; $c =~ s/^\s+|\s+$//g; $c =~ s/\s+AS\s+\w+$//si; $c } split /,/, $1;
729 }
730 12 my $res = $self->execute($sel);
731 12 ▶ return { type=>'error', message=>$res->{message} } if $res->{type} eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $res->{"type"} eq "error" 0 12 12
732 12 my $n = 0;
733 12 for my $r (@{$res->{data}}) {
734  
735 # Map SELECT result columns to INSERT destination columns.
736 #
737 # Name-based mapping (preferred): when every dst column name
738 # exists as a key in the result row, map by name regardless of
739 # position. This handles INSERT INTO dst(a,b) SELECT b,a FROM src
740 # correctly and is insensitive to SELECT column order.
741 #
742 # Position-based fallback: used when dst and src columns differ
743 # (e.g. INSERT INTO dst(x,y) SELECT a,b FROM src) or when src
744 # columns could not be parsed (SELECT *).
745 32 my %row;
746 32 my %rkeys = map { $_ => 1 } keys %$r;
747 my $name_based = @dst_cols
748 32 ▶ && !grep { !$rkeys{$_} } @dst_cols;
Condition66%2/3
@dst_cols && !grep({not $rkeys{$_};} @dst_cols)
!ll&&!rl&&r
0527
MC/DC50%1/2
@dst_cols && !grep({not $rkeys{$_};} @dst_cols)
@dst_cols !grep({not $rkeys{$_};} @dst_cols)
Truth table66%2/3
A && not(B)
A= @dst_colsB= !grep({not $rkeys{$_};} @dst_cols)
ABresult
0X0
100
111
749 32 ▶ if ($name_based) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name_based) { } 27 5 32
750 27 for my $col (@dst_cols) {
751 50 $row{$col} = $r->{$col};
752 }
753 }
754 else {
755 5 ▶ my @src_keys = @src_cols ? @src_cols : sort keys %$r;
Branch: 1 branch
BranchTrueFalseTotal
@src_cols ? : 5 0 5
756 5 for my $i (0 .. $#dst_cols) {
757 $row{$dst_cols[$i]} = defined($src_keys[$i])
758 12 ▶ ? $r->{$src_keys[$i]} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $src_keys[$i] ? : 12 0 12
759 }
760 }
761 32 ▶ $self->insert($tbl, { %row }) and $n++;
Branch: 1 branch
BranchTrueFalseTotal
$self->insert($tbl, {%row}) and ++$n 32 0 32
762 }
763 12 return { type=>'ok', message=>"$n row(s) inserted" };
764 }
765 799 ▶ if ($sql =~ /^SELECT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SELECT\b/i) 739 60 799
766 739 my $sel_res = $self->select($sql);
767 739 ▶ return $sel_res if defined $sel_res;
Branch: 1 branch
BranchTrueFalseTotal
if defined $sel_res 732 7 739
768 7 return { type=>'error', message=>$errstr };
769 }
770 60 ▶ if ($sql =~ /^UPDATE\s+(\w+)\s+SET\s+(.+?)(\s+WHERE\s+.+)?$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^UPDATE\s+(\w+)\s+SET\s+(.+?)(\s+WHERE\s+.+)?$/is) 41 19 60
771 41 ▶ my($tbl, $set_str, $wc) = ($1, $2, (defined($3) ? $3 : ''));
Branch: 1 branch
BranchTrueFalseTotal
defined $3 ? : 40 1 41
772 41 my %se = parse_set_exprs($set_str);
773 41 my $ws;
774 41 ▶ if ($wc =~ /\bWHERE\s+(.+)/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wc =~ /\bWHERE\s+(.+)/is) 40 1 41
775 40 (my $e = $1) =~ s/^\s+|\s+$//g;
776 40 $ws = where_sub($e);
777 }
778 41 my $n = $self->update($tbl, { %se }, $ws);
779 41 ▶ return defined($n)
Branch: 1 branch
BranchTrueFalseTotal
defined $n ? : 28 13 41
780 ? { type=>'ok', message=>"$n row(s) updated" }
781 : { type=>'error', message=>$errstr };
782 }
783 19 ▶ if ($sql =~ /^DELETE\s+FROM\s+(\w+)(.*)?$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DELETE\s+FROM\s+(\w+)(.*)?$/is) 12 7 19
784 12 ▶ my($tbl, $rest) = ($1, (defined($2) ? $2 : ''));
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 12 0 12
785 12 my $ws;
786 12 ▶ if ($rest =~ /\bWHERE\s+(.+)/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ /\bWHERE\s+(.+)/is) 12 0 12
787 12 (my $e = $1) =~ s/^\s+|\s+$//g;
788 12 $ws = where_sub($e);
789 }
790 12 my $n = $self->delete_rows($tbl, $ws);
791 12 ▶ return defined($n)
Branch: 1 branch
BranchTrueFalseTotal
defined $n ? : 12 0 12
792 ? { type=>'ok', message=>"$n row(s) deleted" }
793 : { type=>'error', message=>$errstr };
794 }
795 7 return { type=>'error', message=>"Unsupported SQL: $sql" };
796 }
797  
798 ###############################################################################
799 # SUBQUERY ENGINE
800 #
801 # Supported subquery positions:
802 #
803 # 1. WHERE col IN (SELECT single_col FROM ...)
804 # 2. WHERE col NOT IN (SELECT single_col FROM ...)
805 # 3. WHERE col OP (SELECT single_col FROM ...) OP = = != < > <= >=
806 # 4. WHERE EXISTS (SELECT ... FROM ...)
807 # 5. WHERE NOT EXISTS (SELECT ... FROM ...)
808 # 6. FROM (SELECT ...) AS alias -- derived table / inline view
809 # 7. SELECT (SELECT single_col ...) AS alias -- scalar subquery in SELECT list
810 #
811 # Nesting: subqueries may themselves contain subqueries (recursive expansion).
812 # Correlated subqueries: outer row values injected via _subq_context hashref.
813 ###############################################################################
814  
815 # ---------------------------------------------------------------------------
816 # Public wrapper: expand all subqueries in a SQL string, then execute.
817 # Called by execute() when a subquery token is detected.
818 # ---------------------------------------------------------------------------
819 sub execute_with_subquery {
820 63 ▶ my($self, $sql) = @_;
Subroutine execute_with_subquery: called CC=5 SCAR=16.3
Pod undocumented
821  
822 # Handle derived table in FROM: FROM (SELECT ...) AS alias
823 63 ▶ if ($sql =~ /\bFROM\s*\(/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\bFROM\s*\(/i) 19 44 63
824 19 return $self->_exec_derived_table($sql);
825 }
826  
827 # Handle scalar subqueries in SELECT list: SELECT (SELECT ...) AS alias
828 44 ▶ if ($sql =~ /^SELECT\s*\(/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SELECT\s*\(/i) 0 44 44
829 0 return $self->_exec_scalar_select_subquery($sql);
830 }
831  
832 # Expand WHERE-clause subqueries iteratively (innermost first)
833 44 my $expanded = $self->_expand_where_subqueries($sql, {});
834 44 ▶ return $expanded if ref($expanded) eq 'HASH'; # error hash
Branch: 1 branch
BranchTrueFalseTotal
if ref $expanded eq "HASH" 0 44 44
835  
836 # If correlated subqueries remain (still contain (SELECT), use row-level evaluator
837 44 ▶ if ($expanded =~ /\(\s*SELECT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded =~ /\(\s*SELECT\b/i) 4 40 44
838 4 return $self->_exec_correlated_select($expanded);
839 }
840  
841 40 return $self->execute($expanded);
842 }
843  
844 # ---------------------------------------------------------------------------
845 # Execute a SELECT with correlated subqueries in the WHERE clause.
846 # Scans each row, evaluates the subquery with the row as outer context.
847 # ---------------------------------------------------------------------------
848 sub _exec_correlated_select {
849 4 ▶ my($self, $sql) = @_;
Subroutine _exec_correlated_select: called CC=35 SCAR=41.8
850  
851 # Must be a plain SELECT (no JOIN, no derived table)
852 4 ▶ unless ($sql =~ /^SELECT\s+(.+?)\s+FROM\s+(\w+)(.*)?$/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sql =~ /^SELECT\s+(.+?)\s+FROM\s+(\w+)(.*)?$/i) 0 4 4
853 0 return { type=>'error', message=>"Cannot execute correlated query: $sql" };
854 }
855 4 ▶ my($col_str, $tbl, $rest) = ($1, $2, (defined($3) ? $3 : ''));
Branch: 1 branch
BranchTrueFalseTotal
defined $3 ? : 4 0 4
856  
857 4 ▶ my $sch = $self->_load_schema($tbl) or return { type=>'error', message=>$errstr };
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($tbl) or return {"type", "error", "message", $DB::Handy::errstr} 0 4 4
858  
859 # Parse col list
860 4 my @sel_cols;
861 4 ▶ unless ($col_str =~ /^\*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($col_str =~ /^\*$/) 4 0 4
862 4 @sel_cols = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $col_str;
863 }
864  
865 # Strip ORDER BY / LIMIT / OFFSET
866 4 my %opts;
867 4 ▶ if ($rest =~ s/\bLIMIT\s+(\d+)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ s/\bLIMIT\s+(\d+)//i) 0 4 4
868 0 $opts{limit} = $1;
869 }
870 4 ▶ if ($rest =~ s/\bOFFSET\s+(\d+)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ s/\bOFFSET\s+(\d+)//i) 0 4 4
871 0 $opts{offset} = $1;
872 }
873 4 ▶ if ($rest =~ s/\bORDER\s+BY\s+(\w+)(?:\s+(ASC|DESC))?//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ s/\bORDER\s+BY\s+(\w+)(?:\s+(ASC|DESC))?//i) 1 3 4
874 1 $opts{order_by} = $1;
875 1 ▶ $opts{order_dir} = defined($2) ? $2 : 'ASC';
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 0 1 1
876 my @onames = @sel_cols
877 1 ? map { _order_name_of($_) } @sel_cols
878 1 ▶ : map { $_->{name} } @{$sch->{cols}};
Branch: 1 branch
BranchTrueFalseTotal
@sel_cols ? : 1 0 1
879 1 my($obe, $obk) = _resolve_order_ordinal_scalar($opts{order_by}, [ @onames ]);
880 1 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 0 1 1
881 1 $opts{order_by} = $obk;
882 }
883  
884 # Extract WHERE expression
885 4 my $where_expr = '';
886 4 ▶ if ($rest =~ /\bWHERE\s+(.+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ /\bWHERE\s+(.+)/i) 4 0 4
887 4 $where_expr = $1;
888 4 $where_expr =~ s/^\s+|\s+$//g;
889 }
890  
891 # Parse conditions (may include subquery conditions)
892 4 my $conds = $self->_parse_conditions_with_subq($where_expr);
893 4 my $filter = $self->_compile_where_with_subq($conds);
894  
895 # Full scan with per-row subquery evaluation
896 4 my $dat = $self->_file($tbl, 'dat');
897 4 my $recsize = $sch->{recsize};
898 4 my @results;
899  
900 4 local *FH;
901 4 ▶ open(FH, "< $dat") or return { type=>'error', message=>"Cannot open dat: $!" };
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return {"type", "error", "message", "Cannot open dat: $!"} 0 4 4
902 4 binmode FH;
903 4 _lock_sh(\*FH);
904 4 my $rec_no = 0;
905 4 while (1) {
906 32 my $raw = '';
907 32 my $n = read(FH, $raw, $recsize);
908 32 ▶ last unless defined($n) && ($n == $recsize);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $recsize 4 28 32
Condition66%2/3
defined $n and $n == $recsize
!ll&&!rl&&r
0428
MC/DC50%1/2
defined $n and $n == $recsize
defined $n $n == $recsize
Truth table66%2/3
A and B
A= defined $nB= $n == $recsize
ABresult
0X0
100
111
909 28 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 28 0 28
910 28 my $row = $self->_unpack_record($sch, $raw);
911  
912 # Make row available under both bare and table-qualified names
913 28 my %qrow = %$row;
914 28 for my $c (@{$sch->{cols}}) {
915 132 $qrow{"$tbl.$c->{name}"} = $row->{$c->{name}};
916 }
917 28 ▶ push @results, { %qrow } if $filter->({ %qrow });
Branch: 1 branch
BranchTrueFalseTotal
if &$filter({%qrow}) 15 13 28
918 }
919 28 $rec_no++;
920 }
921 4 _unlock(\*FH);
922 4 close FH;
923  
924 # ORDER BY
925 4 ▶ if (my $ob = $opts{order_by}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ob = $opts{"order_by"}) 1 3 4
926 1 ▶ my $dir = lc(defined($opts{order_dir}) ? $opts{order_dir} : 'asc');
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'order_dir'} ? : 1 0 1
927 @results = sort {
928 1 my($va, $vb) = ($a->{$ob}, $b->{$ob});
929 3 ▶ my $cmp = (defined($va) && ($va =~ /^-?\d+\.?\d*$/) &&
Branch: 3 branches
BranchTrueFalseTotal
defined $va && $va =~ /^-?\d+\.?\d*$/ && defined $vb && $vb =~ /^-?\d+\.?\d*$/ ? : 0 3 3
defined $va ? : 3 0 3
defined $vb ? : 3 0 3
Condition33%3/9
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb and $vb =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
300
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb
!ll&&!rl&&r
300
defined $va and $va =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
030
MC/DC0%0/4
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb and $vb =~ /^-?\d+\.?\d*$/
defined $va $va =~ /^-?\d+\.?\d*$/ defined $vb $vb =~ /^-?\d+\.?\d*$/
Truth table20%1/5
A and B and C and D
A= defined $vaB= $va =~ /^-?\d+\.?\d*$/C= defined $vbD= $vb =~ /^-?\d+\.?\d*$/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
930 defined($vb) && ($vb =~ /^-?\d+\.?\d*$/))
931 ? ($va <=> $vb)
932 : ((defined($va) ? $va : '') cmp (defined($vb) ? $vb : ''));
933 3 ▶ ($dir eq 'desc') ? -$cmp : $cmp;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'desc' ? : 0 3 3
934 } @results;
935 }
936  
937 # OFFSET / LIMIT
938 4 ▶ my $off = defined($opts{offset}) ? $opts{offset} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'offset'} ? : 0 4 4
939 4 ▶ @results = splice(@results, $off) if $off;
Branch: 1 branch
BranchTrueFalseTotal
if $off 0 4 4
940 4 ▶ if (defined $opts{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"limit"}) 0 4 4
941 0 my $last = $opts{limit} - 1;
942 0 ▶ $last = $#results if $last > $#results;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $#results 0 0 0
943 0 @results = @results[0..$last];
944 }
945  
946 # Column projection (remove table-qualified duplicates)
947 4 my @proj;
948 4 for my $r (@results) {
949 15 my %p;
950 15 ▶ if (@sel_cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sel_cols) { } 15 0 15
951 15 for my $c (@sel_cols) {
952 15 $p{$c} = $r->{$c};
953 }
954 }
955 else {
956  
957 # All bare columns
958 0 for my $c (@{$sch->{cols}}) {
959 0 $p{$c->{name}} = $r->{$c->{name}};
960 }
961 }
962 15 push @proj, { %p };
963 }
964  
965 4 return { type=>'rows', data=>[ @proj ] };
966 }
967  
968 # ---------------------------------------------------------------------------
969 # _expand_where_subqueries($sql, \%outer_row)
970 #
971 # Finds the innermost (SELECT ...) in a WHERE clause and replaces it with
972 # its evaluated result (a literal list or scalar). Repeats until no
973 # subqueries remain. Returns the rewritten SQL string, or error hashref.
974 # ---------------------------------------------------------------------------
975 sub _expand_where_subqueries {
976 44 ▶ my($self, $sql, $outer_row) = @_;
Subroutine _expand_where_subqueries: called CC=23 SCAR=32.8
977 44 ▶ $outer_row ||= {};
Condition50%1/2
$outer_row ||= {}
l!l
440
MC/DC0%0/1
$outer_row ||= {}
$outer_row
Truth table50%1/2
A
A= $outer_row
Aresult
11
00
978  
979 44 my $max_depth = 32;
980 44 my $iter = 0;
981  
982 44 ▶ while (($sql =~ /\(\s*SELECT\b/i) && ($iter++ < $max_depth)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\(\s*SELECT\b/i and $iter++ < $max_depth) 27 40 67
Condition66%2/3
$sql =~ /\(\s*SELECT\b/i and $iter++ < $max_depth
!ll&&!rl&&r
40027
MC/DC50%1/2
$sql =~ /\(\s*SELECT\b/i and $iter++ < $max_depth
$sql =~ /\(\s*SELECT\b/i $iter++ < $max_depth
Truth table66%2/3
A and B
A= $sql =~ /\(\s*SELECT\b/iB= $iter++ < $max_depth
ABresult
0X0
100
111
983  
984 # Find the innermost (SELECT ...) -- i.e. the one with no nested (SELECT
985 27 my $pos = _find_innermost_subquery($sql);
986 27 ▶ last unless defined $pos;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pos 0 27 27
987  
988 27 my($start, $end) = @$pos;
989 27 my $inner_sql = substr($sql, $start + 1, $end - $start - 1);
990 27 $inner_sql =~ s/^\s+|\s+$//g;
991  
992 # Determine context: what precedes the opening paren
993 27 my $prefix = substr($sql, 0, $start);
994  
995 # Detect correlated subquery: inner SQL contains tablename.colname
996 # references that are NOT from the inner query's own tables.
997 # Heuristic: if inner_sql has \w+\.\w+ patterns, check if those
998 # table-names appear in the inner FROM clause.
999 27 ▶ if (_subquery_is_correlated($inner_sql)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_subquery_is_correlated($inner_sql)) 4 23 27
1000  
1001 # Cannot pre-evaluate; will be handled per-row in _compile_where_with_subq.
1002 # Mark as a correlated subquery placeholder and stop expanding here.
1003 4 last;
1004 }
1005  
1006 # Inject outer row values for correlated references
1007 23 my $resolved = $self->_resolve_correlated($inner_sql, $outer_row);
1008  
1009 # Execute the inner query
1010 23 my $inner_res = $self->execute($resolved);
1011 23 ▶ if (!$inner_res || ($inner_res->{type} eq 'error')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $inner_res or $inner_res->{"type"} eq "error") 0 23 23
Condition33%1/3
not $inner_res or $inner_res->{"type"} eq "error"
l!l&&r!l&&!r
0023
MC/DC0%0/2
not $inner_res or $inner_res->{"type"} eq "error"
not $inner_res $inner_res->{"type"} eq "error"
Truth table33%1/3
not(A) or B
A= not $inner_resB= $inner_res->{"type"} eq "error"
ABresult
1X1
011
000
1012 0 ▶ my $msg = $inner_res ? $inner_res->{message} : $errstr;
Branch: 1 branch
BranchTrueFalseTotal
$inner_res ? : 0 0 0
1013 0 return { type=>'error', message=>"Subquery error: $msg" };
1014 }
1015  
1016 23 ▶ my @inner_rows = @{ $inner_res->{data} || [] };
Branch: 1 branch
BranchTrueFalseTotal
$inner_res->{"data"} or [] 0 23 23
1017  
1018 # Determine what kind of subquery this is based on prefix context
1019 23 my $replacement;
1020 23 ▶ if (($prefix =~ /\bIN\s*$/i) || ($prefix =~ /\bNOT\s+IN\s*$/i)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($prefix =~ /\bIN\s*$/i or $prefix =~ /\bNOT\s+IN\s*$/i) { } 12 11 23
elsif ($prefix =~ /\b(?:EXISTS|NOT\s+EXISTS)\s*$/i) { } 3 8 11
Condition66%2/3
$prefix =~ /\bIN\s*$/i or $prefix =~ /\bNOT\s+IN\s*$/i
l!l&&r!l&&!r
12011
MC/DC50%1/2
$prefix =~ /\bIN\s*$/i or $prefix =~ /\bNOT\s+IN\s*$/i
$prefix =~ /\bIN\s*$/i $prefix =~ /\bNOT\s+IN\s*$/i
Truth table66%2/3
A or B
A= $prefix =~ /\bIN\s*$/iB= $prefix =~ /\bNOT\s+IN\s*$/i
ABresult
1X1
011
000
1021  
1022 # IN / NOT IN: build a parenthesised list of literal values
1023 12 my @vals;
1024 12 for my $r (@inner_rows) {
1025 17 my @rv = values %$r;
1026 17 ▶ my $v = defined($rv[0]) ? $rv[0] : 'NULL';
Branch: 1 branch
BranchTrueFalseTotal
defined $rv[0] ? : 17 0 17
1027 17 ▶ if ($v =~ /^-?\d+\.?\d*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /^-?\d+\.?\d*$/) { } 15 2 17
1028 15 push @vals, $v;
1029 }
1030 else {
1031 2 push @vals, "'$v'";
1032 }
1033 }
1034 12 ▶ if (@vals) {
Branch: 1 branch
BranchTrueFalseTotal
if (@vals) { } 10 2 12
1035 10 $replacement = '(' . join(',', @vals) . ')';
1036 }
1037 else {
1038  
1039 # Empty set semantics:
1040 # col IN (empty) -> always false -> use (NULL)
1041 # col NOT IN (empty) -> always true -> use a value that
1042 # never matches col, so NOT IN evaluates to true for
1043 # every row. We inject the sentinel '__EMPTY_SET__'
1044 # (not a valid column value) which will not match.
1045 2 ▶ if ($prefix =~ /\bNOT\s+IN\s*$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prefix =~ /\bNOT\s+IN\s*$/i) { } 1 1 2
1046 1 $replacement = "('__EMPTY_SET__')";
1047 }
1048 else {
1049 1 $replacement = '(NULL)';
1050 }
1051 }
1052 }
1053 elsif ($prefix =~ /\b(?:EXISTS|NOT\s+EXISTS)\s*$/i) {
1054  
1055 # EXISTS / NOT EXISTS: replace the paren content with 1 or 0
1056 # The EXISTS keyword stays; we replace just the (SELECT ...) with (1) or (0)
1057 3 ▶ $replacement = @inner_rows ? '(1)' : '(0)';
Branch: 1 branch
BranchTrueFalseTotal
@inner_rows ? : 1 2 3
1058 }
1059 else {
1060  
1061 # Scalar subquery (=, !=, <, >, <=, >=, or bare use)
1062 8 ▶ if (@inner_rows > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@inner_rows > 1) 0 8 8
1063 0 return { type=>'error', message=>"Subquery returns more than one row" };
1064 }
1065 8 ▶ if (@inner_rows == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@inner_rows == 0) { } 1 7 8
1066 1 $replacement = 'NULL';
1067 }
1068 else {
1069 7 my @rv = values %{ $inner_rows[0] };
1070 7 ▶ my $v = defined($rv[0]) ? $rv[0] : 'NULL';
Branch: 1 branch
BranchTrueFalseTotal
defined $rv[0] ? : 7 0 7
1071 7 ▶ $replacement = ($v =~ /^-?\d+\.?\d*$/) ? $v : "'$v'";
Branch: 1 branch
BranchTrueFalseTotal
$v =~ /^-?\d+\.?\d*$/ ? : 7 0 7
1072 }
1073 }
1074  
1075 # Splice the replacement into the SQL
1076 23 substr($sql, $start, $end - $start + 1) = $replacement;
1077 }
1078  
1079 44 return $sql;
1080 }
1081  
1082 # ---------------------------------------------------------------------------
1083 # Detect whether a subquery SQL string contains correlated outer references.
1084 # A subquery is correlated if it contains alias.colname where the alias
1085 # is NOT one of the tables listed in its own FROM clause.
1086 # ---------------------------------------------------------------------------
1087 sub _subquery_is_correlated {
1088 27 ▶ my($inner_sql) = @_;
Subroutine _subquery_is_correlated: called CC=7 SCAR=20.5
1089  
1090 # Find tables in the inner FROM clause
1091 27 my %inner_tables;
1092  
1093 # FROM t1 [AS a1] [JOIN t2 AS a2 ON ...]*
1094 27 ▶ if ($inner_sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inner_sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/i) 27 0 27
1095 27 ▶ $inner_tables{ lc(defined($2) ? $2 : $1) } = 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 24 3 27
1096 27 $inner_tables{ lc($1) } = 1;
1097 }
1098 27 ▶ while ($inner_sql =~ /\bJOIN\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/gi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inner_sql =~ /\bJOIN\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/gi) 0 27 27
1099 0 ▶ $inner_tables{ lc(defined($2) ? $2 : $1) } = 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 0 0 0
1100 0 $inner_tables{ lc($1) } = 1;
1101 }
1102  
1103 # Look for alias.col references in WHERE clause
1104 27 ▶ while ($inner_sql =~ /\b(\w+)\.(\w+)\b/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inner_sql =~ /\b(\w+)\.(\w+)\b/g) 5 23 28
1105 5 my($tbl, $col) = (lc($1), $2);
1106 5 ▶ return 1 unless $inner_tables{$tbl};
Branch: 1 branch
BranchTrueFalseTotal
unless $inner_tables{$tbl} 4 1 5
1107 }
1108 23 return 0;
1109 }
1110  
1111 # ---------------------------------------------------------------------------
1112 # Find the innermost (SELECT ...) -- the one whose content has no nested
1113 # (SELECT. Returns [$start_pos, $end_pos] of the outer parens, or undef.
1114 # ---------------------------------------------------------------------------
1115 sub _find_innermost_subquery {
1116 27 ▶ my($sql) = @_;
Subroutine _find_innermost_subquery: called CC=15 SCAR=27.1
1117 27 my $len = length($sql);
1118 27 my $best_start;
1119 my $best_end;
1120  
1121 27 my $i = 0;
1122 27 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 2665 27 2692
1123  
1124 # Look for ( followed (possibly with spaces) by SELECT
1125 2665 ▶ if (substr($sql, $i, 1) eq '(' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $i, 1) eq "(") 30 2635 2665
1126  
1127 # Check if this opens a SELECT
1128 30 my $peek = substr($sql, $i+1);
1129 30 $peek =~ s/^\s+//;
1130 30 ▶ if ($peek =~ /^SELECT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($peek =~ /^SELECT\b/i) 29 1 30
1131  
1132 # Walk to matching close paren, check for no nested SELECT
1133 29 my $depth = 1;
1134 29 my $j = $i + 1;
1135 29 my $has_nested = 0;
1136 29 my $in_str = 0;
1137 29 ▶ while (($j < $len) && ($depth > 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $len and $depth > 0) 1486 29 1515
Condition100%3/3
$j < $len and $depth > 0
!ll&&!rl&&r
2541486
MC/DC100%2/2
$j < $len and $depth > 0
$j < $len $depth > 0
Truth table100%3/3
A and B
A= $j < $lenB= $depth > 0
ABresult
0X0
100
111
1138 1486 my $ch = substr($sql, $j, 1);
1139 1486 ▶ if ($ch eq "'") {
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq q[']) { } 16 1470 1486
elsif (not $in_str) { } 1430 40 1470
1140  
1141 # Toggle string mode
1142 16 $in_str = !$in_str;
1143 }
1144 elsif (!$in_str) {
1145 1430 ▶ if ($ch eq '(') {
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq '(') { } 3 1427 1430
elsif ($ch eq ')') { } 32 1395 1427
1146 3 $depth++;
1147  
1148 # check for nested SELECT
1149 3 my $p2 = substr($sql, $j+1);
1150 3 $p2 =~ s/^\s+//;
1151 3 ▶ $has_nested = 1 if ($depth > 1) && ($p2 =~ /^SELECT\b/i);
Branch: 1 branch
BranchTrueFalseTotal
if $depth > 1 and $p2 =~ /^SELECT\b/i 2 1 3
Condition66%2/3
$depth > 1 and $p2 =~ /^SELECT\b/i
!ll&&!rl&&r
012
MC/DC50%1/2
$depth > 1 and $p2 =~ /^SELECT\b/i
$depth > 1 $p2 =~ /^SELECT\b/i
Truth table66%2/3
A and B
A= $depth > 1B= $p2 =~ /^SELECT\b/i
ABresult
0X0
100
111
1152 }
1153 elsif ($ch eq ')') {
1154 32 $depth--;
1155 }
1156 }
1157 1486 $j++;
1158 }
1159 29 ▶ if (($depth == 0) && !$has_nested) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth == 0 and not $has_nested) 27 2 29
Condition66%2/3
$depth == 0 and not $has_nested
!ll&&!rl&&r
0227
MC/DC50%1/2
$depth == 0 and not $has_nested
$depth == 0 not $has_nested
Truth table66%2/3
A and not(B)
A= $depth == 0B= not $has_nested
ABresult
0X0
100
111
1160  
1161 # This is an innermost SELECT subquery
1162 27 $best_start = $i;
1163 27 $best_end = $j - 1;
1164  
1165 # Don't break -- we want the last (innermost) one found
1166 }
1167 }
1168 }
1169 2665 $i++;
1170 }
1171  
1172 27 ▶ return defined($best_start) ? [ $best_start, $best_end ] : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $best_start ? : 27 0 27
1173 }
1174  
1175 # ---------------------------------------------------------------------------
1176 # _resolve_correlated($inner_sql, \%outer_row)
1177 #
1178 # Replace references to outer-row columns in a correlated subquery.
1179 # Outer references appear as outer.colname or are matched when the column
1180 # name exists in %outer_row but NOT in the inner query's table.
1181 # Simple heuristic: replace outer.col tokens with the literal value.
1182 # ---------------------------------------------------------------------------
1183 sub _resolve_correlated {
1184 51 ▶ my($self, $sql, $outer_row) = @_;
Subroutine _resolve_correlated: called CC=6 SCAR=17.9
1185 51 ▶ return $sql unless %$outer_row;
Branch: 1 branch
BranchTrueFalseTotal
unless %$outer_row 23 28 51
1186  
1187 # Build sorted list: longer (qualified) keys first so alias.col
1188 # is replaced before bare col to avoid double-substitution.
1189 28 my @keys = sort { length($b) <=> length($a) } keys %$outer_row;
1190  
1191 28 for my $qkey (@keys) {
1192 264 ▶ my $val = defined($outer_row->{$qkey}) ? $outer_row->{$qkey} : 'NULL';
Branch: 1 branch
BranchTrueFalseTotal
defined $outer_row->{$qkey} ? : 264 0 264
1193 264 ▶ my $lit = ($val =~ /^-?\d+\.?\d*$/) ? $val : "'$val'";
Branch: 1 branch
BranchTrueFalseTotal
$val =~ /^-?\d+\.?\d*$/ ? : 200 64 264
1194  
1195 264 ▶ if (index($qkey, '.') >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($qkey, '.') != -1) { } 132 132 264
1196  
1197 # Qualified key: e.g. "employees.id"
1198 # Build regex that matches the full qualified token
1199 132 (my $pat = $qkey) =~ s/\./\\./g;
1200 132 $sql =~ s/(?<![.\w])$pat(?!\w)/$lit/g;
1201 }
1202 else {
1203  
1204 # Bare key: only replace if NOT preceded by a dot
1205 # (avoids replacing "id" inside "employees.id" already handled above)
1206 132 $sql =~ s/(?<![.\w])$qkey(?!\w)/$lit/g;
1207 }
1208 }
1209 28 return $sql;
1210 }
1211  
1212 # ---------------------------------------------------------------------------
1213 # EXISTS / NOT EXISTS correlated subquery evaluation at runtime
1214 #
1215 # These must be evaluated per-outer-row, so they cannot be pre-expanded.
1216 # We detect them in _parse_conditions and defer evaluation.
1217 # ---------------------------------------------------------------------------
1218  
1219 # Enhanced _parse_conditions that understands subquery conditions.
1220 # Returns arrayref of condition hashrefs; subquery conditions have:
1221 # { type => 'subquery',
1222 # op => 'IN'|'NOT_IN'|'EXISTS'|'NOT_EXISTS'|'CMP',
1223 # col => colname, # for IN/NOT_IN/CMP
1224 # cmp_op => '='|..., # for CMP
1225 # subql => 'SELECT ...',
1226 # }
1227 sub _parse_conditions_with_subq {
1228 6 ▶ my($self, $expr) = @_;
Subroutine _parse_conditions_with_subq: called CC=9 SCAR=23.1
1229 6 my @conds;
1230  
1231 # Split on AND (but not inside parens/strings)
1232 6 my @parts = _split_and_clauses($expr);
1233  
1234 6 for my $part (@parts) {
1235 6 $part =~ s/^\s+|\s+$//g;
1236  
1237 # EXISTS (SELECT ...)
1238 6 ▶ if ($part =~ /^(NOT\s+)?EXISTS\s*\((.+)\)\s*$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(NOT\s+)?EXISTS\s*\((.+)\)\s*$/is) 3 3 6
1239 3 my($neg, $subql) = ($1, $2);
1240 3 $subql =~ s/^\s+|\s+$//g;
1241 3 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 1 2 3
1242 type => 'subquery',
1243 op => ($neg ? 'NOT_EXISTS' : 'EXISTS'),
1244 subql => $subql,
1245 };
1246 3 next;
1247 }
1248  
1249 # col [NOT] IN (SELECT ...)
1250 3 ▶ if ($part =~ /^([\w.]+)\s+(NOT\s+)?IN\s*\((\s*SELECT\b.+)\)\s*$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^([\w.]+)\s+(NOT\s+)?IN\s*\((\s*SELECT\b.+)\)\s*$/is) 0 3 3
1251 0 my($col, $neg, $subql) = ($1, $2, $3);
1252 0 $subql =~ s/^\s+|\s+$//g;
1253 0 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 0 0 0
1254 type => 'subquery',
1255 op => $neg ? 'NOT_IN' : 'IN',
1256 col => $col,
1257 subql => $subql,
1258 };
1259 0 next;
1260 }
1261  
1262 # col OP (SELECT ...)
1263 3 ▶ if ($part =~ /^([\w.]+)\s*(=|!=|<>|<=|>=|<|>)\s*\((\s*SELECT\b.+)\)\s*$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^([\w.]+)\s*(=|!=|<>|<=|>=|<|>)\s*\((\s*SELECT\b.+)\)\s*$/is) 1 2 3
1264 1 my($col, $op, $subql) = ($1, uc($2), $3);
1265 1 $subql =~ s/^\s+|\s+$//g;
1266 1 push @conds, {
1267 type => 'subquery',
1268 op => 'CMP',
1269 cmp_op => $op,
1270 col => $col,
1271 subql => $subql,
1272 };
1273 1 next;
1274 }
1275  
1276 # Normal condition
1277 2 ▶ if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) 2 0 2
1278 2 my($col, $op, $sv, $nv) = ($1, $2, $3, $4);
1279 2 ▶ push @conds, { col=>$col, op=>uc($op), val=>defined($sv) ? $sv : $nv };
Branch: 1 branch
BranchTrueFalseTotal
defined $sv ? : 0 2 2
1280 }
1281 }
1282 6 return [ @conds ];
1283 }
1284  
1285 # Split WHERE expression on top-level AND (not inside parens or strings)
1286 sub _split_and_clauses {
1287 6 ▶ my($expr) = @_;
Subroutine _split_and_clauses: called CC=12 SCAR=29.5
1288 6 my @parts;
1289 6 my $cur = '';
1290 6 my $depth = 0;
1291 6 my $in_str = 0;
1292 6 my $i = 0;
1293 6 my $len = length($expr);
1294  
1295 6 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 334 6 340
1296 334 my $ch = substr($expr, $i, 1);
1297 334 ▶ if (($ch eq "'") && !$in_str) {
Branch: 6 branches
BranchTrueFalseTotal
if ($ch eq q['] and not $in_str) { } 0 334 334
elsif ($ch eq q['] and $in_str) { } 0 334 334
elsif ($in_str) { } 0 334 334
elsif ($ch eq '(') { } 4 330 334
elsif ($ch eq ')') { } 4 326 330
elsif ($depth == 0 and substr($expr, $i, 5) =~ /^AND\s/i) { } 0 326 326
Condition33%1/3
$ch eq "'" and not $in_str
!ll&&!rl&&r
33400
MC/DC0%0/2
$ch eq "'" and not $in_str
$ch eq "'" not $in_str
Truth table33%1/3
A and not(B)
A= $ch eq "'"B= not $in_str
ABresult
0X0
100
111
1298 0 $in_str = 1;
1299 0 $cur .= $ch;
1300 }
1301 ▶ elsif (($ch eq "'") && $in_str) {
Condition33%1/3
$ch eq "'" and $in_str
!ll&&!rl&&r
33400
MC/DC0%0/2
$ch eq "'" and $in_str
$ch eq "'" $in_str
Truth table33%1/3
A and B
A= $ch eq "'"B= $in_str
ABresult
0X0
100
111
1302 0 $in_str = 0;
1303 0 $cur .= $ch;
1304 }
1305 elsif ($in_str) {
1306 0 $cur .= $ch;
1307 }
1308 elsif ($ch eq '(') {
1309 4 $depth++;
1310 4 $cur .= $ch;
1311 }
1312 elsif ($ch eq ')') {
1313 4 $depth--;
1314 4 $cur .= $ch;
1315 }
1316 ▶ elsif (($depth == 0) && (substr($expr, $i, 5) =~ /^AND\s/i)) {
Condition66%2/3
$depth == 0 and substr($expr, $i, 5) =~ /^AND\s/i
!ll&&!rl&&r
266600
MC/DC0%0/2
$depth == 0 and substr($expr, $i, 5) =~ /^AND\s/i
$depth == 0 substr($expr, $i, 5) =~ /^AND\s/i
Truth table66%2/3
A and B
A= $depth == 0B= substr($expr, $i, 5) =~ /^AND\s/i
ABresult
0X0
100
111
1317 0 push @parts, $cur;
1318 0 $cur = '';
1319 0 $i += 4; # skip "AND "
1320 0 next;
1321 }
1322 else {
1323 326 $cur .= $ch;
1324 }
1325 334 $i++;
1326 }
1327 6 ▶ push @parts, $cur if $cur =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $cur =~ /\S/ 6 0 6
1328 6 return @parts;
1329 }
1330  
1331 # ---------------------------------------------------------------------------
1332 # Build a where-filter sub that handles subquery conditions (evaluated
1333 # at filter time with the candidate row as outer context).
1334 # ---------------------------------------------------------------------------
1335 sub _compile_where_with_subq {
1336 6 ▶ my($self, $conds) = @_;
Subroutine _compile_where_with_subq: called CC=6 SCAR=25.5
1337 6 ▶ return sub { 1 } unless $conds && @$conds;
Subroutine __ANON__: not called CC=1 SCAR=1.7
Branch: 1 branch
BranchTrueFalseTotal
unless $conds and @$conds 0 6 6
Condition33%1/3
$conds and @$conds
!ll&&!rl&&r
006
MC/DC0%0/2
$conds and @$conds
$conds @$conds
Truth table33%1/3
A and B
A= $condsB= @$conds
ABresult
0X0
100
111
1338  
1339 6 my @plain;
1340 my @subq;
1341 6 for my $c (@$conds) {
1342 6 ▶ if (($c->{type} || '') eq 'subquery') {
Branch: 1 branch
BranchTrueFalseTotal
if (($c->{'type'} || '') eq 'subquery') { } 4 2 6
Condition100%2/2
$c->{'type'} || ''
l!l
42
MC/DC100%1/1
$c->{'type'} || ''
$c->{'type'}
Truth table100%2/2
A
A= $c->{'type'}
Aresult
11
00
1343 4 push @subq, $c;
1344 }
1345 else {
1346 2 push @plain, $c;
1347 }
1348 }
1349  
1350 6 my $plain_sub = _compile_where_from_conds([ @plain ]);
1351  
1352 return sub {
1353 36 ▶ my($row) = @_;
Subroutine __ANON__: called CC=50 SCAR=64.7
1354  
1355 # Plain conditions first (fast path)
1356 36 ▶ return 0 if $plain_sub && !$plain_sub->($row);
Branch: 1 branch
BranchTrueFalseTotal
if $plain_sub and not &$plain_sub($row) 2 34 36
Condition100%3/3
$plain_sub and not &$plain_sub($row)
!ll&&!rl&&r
2862
MC/DC100%2/2
$plain_sub and not &$plain_sub($row)
$plain_sub not &$plain_sub($row)
Truth table100%3/3
A and not(B)
A= $plain_subB= not &$plain_sub($row)
ABresult
0X0
100
111
1357  
1358 # Subquery conditions (evaluated per row)
1359 34 for my $c (@subq) {
1360 28 my $op = $c->{op};
1361 28 my $subql = $self->_resolve_correlated($c->{subql}, $row);
1362 28 my $res = $self->execute($subql);
1363 28 ▶ my @rows = ($res && $res->{type} eq 'rows') ? @{$res->{data}} : ();
Branch: 1 branch
BranchTrueFalseTotal
$res && $res->{'type'} eq 'rows' ? : 28 0 28
Condition33%1/3
$res and $res->{"type"} eq "rows"
!ll&&!rl&&r
0028
MC/DC0%0/2
$res and $res->{"type"} eq "rows"
$res $res->{"type"} eq "rows"
Truth table33%1/3
A and B
A= $resB= $res->{"type"} eq "rows"
ABresult
0X0
100
111
1364  
1365 28 ▶ if ($op eq 'EXISTS') {
Branch: 4 branches
BranchTrueFalseTotal
if ($op eq 'EXISTS') { } 12 16 28
elsif ($op eq 'NOT_EXISTS') { } 8 8 16
elsif ($op eq 'IN' or $op eq 'NOT_IN') { } 0 8 8
elsif ($op eq 'CMP') { } 8 0 8
1366 12 ▶ return 0 unless @rows;
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 5 7 12
1367 }
1368 elsif ($op eq 'NOT_EXISTS') {
1369 8 ▶ return 0 if @rows;
Branch: 1 branch
BranchTrueFalseTotal
if @rows 4 4 8
1370 }
1371 ▶ elsif (($op eq 'IN') || ($op eq 'NOT_IN')) {
Condition33%1/3
$op eq "IN" or $op eq "NOT_IN"
l!l&&r!l&&!r
008
MC/DC0%0/2
$op eq "IN" or $op eq "NOT_IN"
$op eq "IN" $op eq "NOT_IN"
Truth table33%1/3
A or B
A= $op eq "IN"B= $op eq "NOT_IN"
ABresult
1X1
011
000
1372 0 ▶ my $col_val = defined($row->{$c->{col}}) ? $row->{$c->{col}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$c->{'col'}} ? : 0 0 0
1373 0 my $found = 0;
1374 0 my $has_null = 0;
1375 0 for my $r (@rows) {
1376 0 my @rv = values %$r;
1377 0 ▶ unless (defined $rv[0]) { $has_null = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rv[0]) 0 0 0
1378 0 my $rv = $rv[0];
1379 0 ▶ my $num = (($col_val =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/));
Condition0%0/3
$col_val =~ /^-?\d+\.?\d*$/ && $rv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
000
MC/DC0%0/2
$col_val =~ /^-?\d+\.?\d*$/ && $rv =~ /^-?\d+\.?\d*$/
$col_val =~ /^-?\d+\.?\d*$/ $rv =~ /^-?\d+\.?\d*$/
Truth table0%0/3
A && B
A= $col_val =~ /^-?\d+\.?\d*$/B= $rv =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
1380 0 ▶ if ($num ? ($col_val == $rv) : ($col_val eq $rv)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($num ? $col_val == $rv : $col_val eq $rv) 0 0 0
$num ? : 0 0 0
1381 0 $found = 1;
1382 0 last;
1383 }
1384 }
1385 0 ▶ return 0 if $found && ($op eq 'NOT_IN');
Branch: 1 branch
BranchTrueFalseTotal
if $found and $op eq "NOT_IN" 0 0 0
Condition0%0/3
$found and $op eq "NOT_IN"
!ll&&!rl&&r
000
MC/DC0%0/2
$found and $op eq "NOT_IN"
$found $op eq "NOT_IN"
Truth table0%0/3
A and B
A= $foundB= $op eq "NOT_IN"
ABresult
0X0
100
111
1386 0 ▶ return 0 if !$found && ($op eq 'IN');
Branch: 1 branch
BranchTrueFalseTotal
if not $found and $op eq "IN" 0 0 0
Condition0%0/3
not $found and $op eq "IN"
!ll&&!rl&&r
000
MC/DC0%0/2
not $found and $op eq "IN"
not $found $op eq "IN"
Truth table0%0/3
not(A) and B
A= not $foundB= $op eq "IN"
ABresult
0X0
100
111
1387 # SQL NULL semantics: NOT IN with NULL in subquery is UNKNOWN
1388 0 ▶ return 0 if $has_null && !$found && ($op eq 'NOT_IN');
Branch: 1 branch
BranchTrueFalseTotal
if $has_null and not $found and $op eq "NOT_IN" 0 0 0
Condition0%0/6
$has_null and not $found and $op eq "NOT_IN"
!ll&&!rl&&r
000
$has_null and not $found
!ll&&!rl&&r
000
MC/DC0%0/3
$has_null and not $found and $op eq "NOT_IN"
$has_null not $found $op eq "NOT_IN"
Truth table0%0/4
A and not(B) and C
A= $has_nullB= not $foundC= $op eq "NOT_IN"
ABCresult
0XX0
10X0
1100
1111
1389 }
1390 elsif ($op eq 'CMP') {
1391 8 ▶ return 0 if @rows > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @rows > 1 0 8 8
1392 8 my $rhs;
1393 8 ▶ if (@rows == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rows == 0) { } 4 4 8
1394 4 $rhs = undef;
1395 }
1396 else {
1397 4 my @rv = values %{ $rows[0] };
1398 4 $rhs = $rv[0];
1399 }
1400 8 ▶ return 0 unless defined $rhs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rhs 4 4 8
1401 4 ▶ my $lhs = defined($row->{$c->{col}}) ? $row->{$c->{col}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$c->{'col'}} ? : 4 0 4
1402 4 my $cop = $c->{cmp_op};
1403 4 ▶ my $num = (($lhs =~ /^-?\d+\.?\d*$/) && ($rhs =~ /^-?\d+\.?\d*$/));
Condition33%1/3
$lhs =~ /^-?\d+\.?\d*$/ && $rhs =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
004
MC/DC0%0/2
$lhs =~ /^-?\d+\.?\d*$/ && $rhs =~ /^-?\d+\.?\d*$/
$lhs =~ /^-?\d+\.?\d*$/ $rhs =~ /^-?\d+\.?\d*$/
Truth table33%1/3
A && B
A= $lhs =~ /^-?\d+\.?\d*$/B= $rhs =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
1404 4 ▶ if ($cop eq '=') {
Branch: 6 branches
BranchTrueFalseTotal
if ($cop eq '=') { } 0 4 4
elsif ($cop eq '!=' or $cop eq '<>') { } 0 4 4
elsif ($cop eq '<') { } 0 4 4
elsif ($cop eq '>') { } 4 0 4
elsif ($cop eq '<=') { } 0 0 0
elsif ($cop eq '>=') { } 0 0 0
1405 0 ▶ return 0 unless $num ? ($lhs == $rhs) : ($lhs eq $rhs);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lhs == $rhs : $lhs eq $rhs 0 0 0
$num ? : 0 0 0
1406 }
1407 ▶ elsif (($cop eq '!=') || ($cop eq '<>')) {
Condition33%1/3
$cop eq "!=" or $cop eq "<>"
l!l&&r!l&&!r
004
MC/DC0%0/2
$cop eq "!=" or $cop eq "<>"
$cop eq "!=" $cop eq "<>"
Truth table33%1/3
A or B
A= $cop eq "!="B= $cop eq "<>"
ABresult
1X1
011
000
1408 0 ▶ return 0 unless $num ? ($lhs != $rhs) : ($lhs ne $rhs);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lhs != $rhs : $lhs ne $rhs 0 0 0
$num ? : 0 0 0
1409 }
1410 elsif ($cop eq '<') {
1411 0 ▶ return 0 unless $num ? ($lhs < $rhs) : ($lhs lt $rhs);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lhs < $rhs : $lhs lt $rhs 0 0 0
$num ? : 0 0 0
1412 }
1413 elsif ($cop eq '>') {
1414 4 ▶ return 0 unless $num ? ($lhs > $rhs) : ($lhs gt $rhs);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lhs > $rhs : $lhs gt $rhs 0 4 4
$num ? : 4 0 4
1415 }
1416 elsif ($cop eq '<=') {
1417 0 ▶ return 0 unless $num ? ($lhs <= $rhs) : ($lhs le $rhs);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lhs <= $rhs : $lhs le $rhs 0 0 0
$num ? : 0 0 0
1418 }
1419 elsif ($cop eq '>=') {
1420 0 ▶ return 0 unless $num ? ($lhs >= $rhs) : ($lhs ge $rhs);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lhs >= $rhs : $lhs ge $rhs 0 0 0
$num ? : 0 0 0
1421 }
1422 }
1423 }
1424 21 return 1;
1425 6 };
1426 }
1427  
1428 # ---------------------------------------------------------------------------
1429 # Derived table: FROM (SELECT ...) AS alias [WHERE ...] [ORDER BY ...]
1430 #
1431 # Evaluates the inner SELECT, materialises the result as an in-memory
1432 # virtual table, then applies the outer WHERE/ORDER BY/LIMIT/OFFSET.
1433 # ---------------------------------------------------------------------------
1434 sub _exec_derived_table {
1435 19 ▶ my($self, $sql) = @_;
Subroutine _exec_derived_table: called CC=64 SCAR=49.9
1436  
1437 # Parse: SELECT outer_cols FROM (inner_sql) AS alias [WHERE ...] [ORDER BY ...] [LIMIT] [OFFSET]
1438 # Step 1: find the outer SELECT list
1439 19 ▶ unless ($sql =~ /^SELECT\s+(.+?)\s+FROM\s*\(/si) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sql =~ /^SELECT\s+(.+?)\s+FROM\s*\(/is) 0 19 19
1440 0 return { type=>'error', message=>"Cannot parse derived table query" };
1441 }
1442 19 my $outer_cols_str = $1;
1443  
1444 # Step 2: extract the (inner_sql) AS alias part using paren matching
1445 19 my $from_pos = index(lc($sql), 'from');
1446 19 my $paren_start = index($sql, '(', $from_pos);
1447 19 ▶ unless ($paren_start >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($paren_start >= 0) 0 19 19
1448 0 return { type=>'error', message=>"Cannot find subquery in FROM clause" };
1449 }
1450  
1451 19 my($inner_sql, $close_pos) = _extract_paren_content($sql, $paren_start);
1452 19 ▶ unless (defined $inner_sql) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $inner_sql) 0 19 19
1453 0 return { type=>'error', message=>"Unmatched parentheses in FROM clause" };
1454 }
1455 19 $inner_sql =~ s/^\s+|\s+$//g;
1456  
1457 # Step 3: parse alias and trailing clauses after the closing paren
1458 19 my $after = substr($sql, $close_pos + 1);
1459 19 $after =~ s/^\s+//;
1460  
1461 19 my $alias;
1462 19 ▶ if ($after =~ s/^(?:AS\s+)?(\w+)\s*//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/^(?:AS\s+)?(\w+)\s*//i) { } 19 0 19
1463 19 $alias = $1;
1464 }
1465 else {
1466 0 $alias = 'subq';
1467 }
1468  
1469 # Step 4: parse outer WHERE / ORDER BY / LIMIT / OFFSET
1470 19 my %outer_opts;
1471 19 ▶ if ($after =~ s/\bLIMIT\s+(\d+)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/\bLIMIT\s+(\d+)//i) 4 15 19
1472 4 $outer_opts{limit} = $1;
1473 }
1474 19 ▶ if ($after =~ s/\bOFFSET\s+(\d+)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/\bOFFSET\s+(\d+)//i) 0 19 19
1475 0 $outer_opts{offset} = $1;
1476 }
1477 19 ▶ if ($after =~ s/\bORDER\s+BY\s+([\w.]+)(?:\s+(ASC|DESC))?//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/\bORDER\s+BY\s+([\w.]+)(?:\s+(ASC|DESC))?//i) 5 14 19
1478 5 $outer_opts{order_by} = $1;
1479 5 ▶ $outer_opts{order_dir} = ($2 || 'ASC');
Condition100%2/2
$2 || 'ASC'
l!l
23
MC/DC100%1/1
$2 || 'ASC'
$2
Truth table100%2/2
A
A= $2
Aresult
11
00
1480 5 my @onames;
1481 5 ▶ unless ($outer_cols_str =~ /^\s*(?:\w+\.)?\*\s*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($outer_cols_str =~ /^\s*(?:\w+\.)?\*\s*$/) 5 0 5
1482 5 @onames = map { _order_name_of($_) } split(/\s*,\s*/, $outer_cols_str);
1483 }
1484 5 my($obe, $obk) = _resolve_order_ordinal_scalar($outer_opts{order_by}, [ @onames ]);
1485 5 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 0 5 5
1486 5 $outer_opts{order_by} = $obk;
1487 }
1488 19 my $outer_having = '';
1489 19 ▶ if ($after =~ s/\bHAVING\s+(.+?)(?=\s*$)//si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/\bHAVING\s+(.+?)(?=\s*$)//is) 1 18 19
1490 1 $outer_having = $1;
1491 1 $outer_having =~ s/^\s+|\s+$//g;
1492 }
1493 19 my @outer_gb;
1494 19 ▶ if ($after =~ s/\bGROUP\s+BY\s+([\w.,\s]+?)(?=\s*$)//si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/\bGROUP\s+BY\s+([\w.,\s]+?)(?=\s*$)//is) 4 15 19
1495 4 @outer_gb = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $1;
1496 }
1497  
1498 19 my $outer_where_str = '';
1499 19 ▶ if ($after =~ /\bWHERE\s+(.+)/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ /\bWHERE\s+(.+)/is) 2 17 19
1500 2 $outer_where_str = $1;
1501 2 $outer_where_str =~ s/^\s+|\s+$//g;
1502 }
1503  
1504 # Step 5: execute the inner query (recursing through execute_with_subquery)
1505 19 my $inner_res = $self->execute_with_subquery($inner_sql);
1506 19 ▶ if (!$inner_res || ($inner_res->{type} eq 'error')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $inner_res or $inner_res->{"type"} eq "error") 0 19 19
Condition33%1/3
not $inner_res or $inner_res->{"type"} eq "error"
l!l&&r!l&&!r
0019
MC/DC0%0/2
not $inner_res or $inner_res->{"type"} eq "error"
not $inner_res $inner_res->{"type"} eq "error"
Truth table33%1/3
not(A) or B
A= not $inner_resB= $inner_res->{"type"} eq "error"
ABresult
1X1
011
000
1507 0 ▶ my $msg = $inner_res ? $inner_res->{message} : $errstr;
Branch: 1 branch
BranchTrueFalseTotal
$inner_res ? : 0 0 0
1508 0 return { type=>'error', message=>"Derived table subquery error: $msg" };
1509 }
1510  
1511 19 ▶ my @inner_rows = @{ $inner_res->{data} || [] };
Branch: 1 branch
BranchTrueFalseTotal
$inner_res->{"data"} or [] 0 19 19
1512  
1513 # Step 6: qualify column names with alias (for outer WHERE resolution)
1514 19 my @qualified_rows;
1515 19 for my $r (@inner_rows) {
1516 74 my %qr;
1517 74 for my $k (keys %$r) {
1518  
1519 # Strip existing alias prefix if any, re-prefix with outer alias
1520 102 ▶ my $bare = ($k =~ /\.(\w+)$/) ? $1 : $k;
Branch: 1 branch
BranchTrueFalseTotal
$k =~ /\.(\w+)$/ ? : 0 102 102
1521 102 $qr{"$alias.$bare"} = $r->{$k};
1522 102 $qr{$bare} = $r->{$k}; # also keep bare for convenience
1523 }
1524 74 push @qualified_rows, { %qr };
1525 }
1526  
1527 # Step 7: apply outer WHERE
1528 19 ▶ if ($outer_where_str =~ /\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($outer_where_str =~ /\S/) 2 17 19
1529 2 my $conds = $self->_parse_conditions_with_subq($outer_where_str);
1530 2 my $filter = $self->_compile_where_with_subq($conds);
1531 2 @qualified_rows = grep { $filter->($_) } @qualified_rows;
1532 }
1533  
1534 # An aggregate or a GROUP BY in the outer SELECT list consumes the
1535 # materialised rows, so ORDER BY / LIMIT / OFFSET have to be applied to
1536 # the aggregated result instead of to the input.
1537 19 ▶ my $outer_agg = (@outer_gb || ($outer_having ne '')
Branch: 1 branch
BranchTrueFalseTotal
@outer_gb || $outer_having ne '' || $outer_cols_str =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i ? : 12 7 19
Condition83%5/6
@outer_gb or $outer_having ne "" or $outer_cols_str =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i
l!l&&r!l&&!r
487
@outer_gb or $outer_having ne ""
l!l&&r!l&&!r
4015
MC/DC66%2/3
@outer_gb or $outer_having ne "" or $outer_cols_str =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i
@outer_gb $outer_having ne "" $outer_cols_str =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i
Truth table75%3/4
A or B or C
A= @outer_gbB= $outer_having ne ""C= $outer_cols_str =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i
ABCresult
1XX1
01X1
0011
0000
1538 || ($outer_cols_str =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i)) ? 1 : 0;
1539  
1540 # Step 8: ORDER BY
1541 19 ▶ if ((my $ob = $outer_opts{order_by}) && !$outer_agg) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ob = $outer_opts{"order_by"} and not $outer_agg) 2 17 19
Condition100%3/3
my $ob = $outer_opts{"order_by"} and not $outer_agg
!ll&&!rl&&r
1432
MC/DC100%2/2
my $ob = $outer_opts{"order_by"} and not $outer_agg
my $ob = $outer_opts{"order_by"} not $outer_agg
Truth table100%3/3
A and not(B)
A= my $ob = $outer_opts{"order_by"}B= not $outer_agg
ABresult
0X0
100
111
1542 2 ▶ my $dir = lc($outer_opts{order_dir} || 'asc');
Condition50%1/2
$outer_opts{'order_dir'} || 'asc'
l!l
20
MC/DC0%0/1
$outer_opts{'order_dir'} || 'asc'
$outer_opts{'order_dir'}
Truth table50%1/2
A
A= $outer_opts{'order_dir'}
Aresult
11
00
1543 # Rows are keyed "alias.col"; fall back to the bare column name so
1544 # that an unqualified sort key still resolves. The fallback key is
1545 # computed once here: deriving it inside the comparator produced an
1546 # undefined hash subscript whenever the key had no alias prefix.
1547 2 ▶ my $obb = ($ob =~ /\.(\w+)$/) ? $1 : $ob;
Branch: 1 branch
BranchTrueFalseTotal
$ob =~ /\.(\w+)$/ ? : 1 1 2
1548 @qualified_rows = sort {
1549 2 ▶ my $va = defined($a->{$ob}) ? $a->{$ob} : $a->{$obb};
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::a->{$ob} ? : 22 0 22
1550 22 ▶ my $vb = defined($b->{$ob}) ? $b->{$ob} : $b->{$obb};
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::b->{$ob} ? : 22 0 22
1551 22 ▶ my $cmp = (defined($va) && ($va =~ /^-?\d+\.?\d*$/) &&
Branch: 1 branch
BranchTrueFalseTotal
defined $va && $va =~ /^-?\d+\.?\d*$/ && defined $vb && $vb =~ /^-?\d+\.?\d*$/ ? : 22 0 22
Condition23%3/13
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb and $vb =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
0022
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb
!ll&&!rl&&r
0022
defined $va and $va =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
0022
$va || ''
l!l
00
$vb || ''
l!l
00
MC/DC0%0/4
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb and $vb =~ /^-?\d+\.?\d*$/
defined $va $va =~ /^-?\d+\.?\d*$/ defined $vb $vb =~ /^-?\d+\.?\d*$/
MC/DC0%0/1
$va || ''
$va
MC/DC0%0/1
$vb || ''
$vb
Truth table20%1/5
A and B and C and D
A= defined $vaB= $va =~ /^-?\d+\.?\d*$/C= defined $vbD= $vb =~ /^-?\d+\.?\d*$/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
Truth table0%0/2
A
A= $va
Aresult
11
00
Truth table0%0/2
A
A= $vb
Aresult
11
00
1552 defined($vb) && ($vb =~ /^-?\d+\.?\d*$/))
1553 ? ($va <=> $vb)
1554 : (($va || '') cmp ($vb || ''));
1555 22 ▶ ($dir eq 'desc') ? -$cmp : $cmp;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'desc' ? : 5 17 22
1556 } @qualified_rows;
1557 }
1558  
1559 # Step 9: OFFSET / LIMIT
1560 19 ▶ unless ($outer_agg) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($outer_agg) 7 12 19
1561 7 ▶ my $off = ($outer_opts{offset} || 0);
Condition50%1/2
$outer_opts{'offset'} || 0
l!l
07
MC/DC0%0/1
$outer_opts{'offset'} || 0
$outer_opts{'offset'}
Truth table50%1/2
A
A= $outer_opts{'offset'}
Aresult
11
00
1562 7 ▶ @qualified_rows = splice(@qualified_rows, $off) if $off;
Branch: 1 branch
BranchTrueFalseTotal
if $off 0 7 7
1563 7 ▶ if (defined $outer_opts{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $outer_opts{"limit"}) 2 5 7
1564 2 my $last = $outer_opts{limit} - 1;
1565 2 ▶ $last = $#qualified_rows if $last > $#qualified_rows;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $#qualified_rows 0 2 2
1566 2 @qualified_rows = @qualified_rows[0..$last];
1567 }
1568 }
1569  
1570 # Step 10: outer column projection
1571 19 my @proj_rows;
1572 19 ▶ if ($outer_agg) {
Branch: 2 branches
BranchTrueFalseTotal
if ($outer_agg) { } 12 7 19
elsif ($outer_cols_str =~ /^\s*\*\s*$/) { } 0 7 7
1573 12 my @specs = parse_col_list($outer_cols_str);
1574 12 @proj_rows = group_and_aggregate([ @qualified_rows ], [ @specs ],
1575 [ @outer_gb ], $outer_having);
1576 12 ▶ if (my $ob = $outer_opts{order_by}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ob = $outer_opts{"order_by"}) 3 9 12
1577 3 ▶ my $dir = lc($outer_opts{order_dir} || 'asc');
Condition50%1/2
$outer_opts{'order_dir'} || 'asc'
l!l
30
MC/DC0%0/1
$outer_opts{'order_dir'} || 'asc'
$outer_opts{'order_dir'}
Truth table50%1/2
A
A= $outer_opts{'order_dir'}
Aresult
11
00
1578 @proj_rows = sort {
1579 3 ▶ my $va = defined($a->{$ob}) ? $a->{$ob} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::a->{$ob} ? : 2 0 2
1580 2 ▶ my $vb = defined($b->{$ob}) ? $b->{$ob} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::b->{$ob} ? : 2 0 2
1581 2 ▶ my $cmp = (($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/))
Branch: 1 branch
BranchTrueFalseTotal
$va =~ /^-?\d+\.?\d*$/ && $vb =~ /^-?\d+\.?\d*$/ ? : 0 2 2
Condition33%1/3
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
200
MC/DC0%0/2
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
$va =~ /^-?\d+\.?\d*$/ $vb =~ /^-?\d+\.?\d*$/
Truth table33%1/3
A and B
A= $va =~ /^-?\d+\.?\d*$/B= $vb =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
1582 ? ($va <=> $vb) : ($va cmp $vb);
1583 2 ▶ ($dir eq 'desc') ? -$cmp : $cmp;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'desc' ? : 1 1 2
1584 } @proj_rows;
1585 }
1586 12 ▶ my $off = ($outer_opts{offset} || 0);
Condition50%1/2
$outer_opts{'offset'} || 0
l!l
012
MC/DC0%0/1
$outer_opts{'offset'} || 0
$outer_opts{'offset'}
Truth table50%1/2
A
A= $outer_opts{'offset'}
Aresult
11
00
1587 12 ▶ @proj_rows = splice(@proj_rows, $off) if $off;
Branch: 1 branch
BranchTrueFalseTotal
if $off 0 12 12
1588 12 ▶ if (defined $outer_opts{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $outer_opts{"limit"}) 2 10 12
1589 2 my $last = $outer_opts{limit} - 1;
1590 2 ▶ $last = $#proj_rows if $last > $#proj_rows;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $#proj_rows 0 2 2
1591 2 @proj_rows = @proj_rows[0..$last];
1592 }
1593 }
1594 elsif ($outer_cols_str =~ /^\s*\*\s*$/) {
1595 0 @proj_rows = @qualified_rows;
1596 }
1597 else {
1598 7 my @want = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $outer_cols_str;
1599 7 for my $r (@qualified_rows) {
1600 22 my %p;
1601 22 for my $w (@want) {
1602 26 ▶ if (exists $r->{$w}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $r->{$w}) { } 26 0 26
elsif ($w =~ /^$alias\.(\w+)$/ and exists $r->{$1}) { } 0 0 0
1603 26 $p{$w} = $r->{$w};
1604 }
1605 ▶ elsif ($w =~ /^$alias\.(\w+)$/ && exists $r->{$1}) {
Condition0%0/3
$w =~ /^$alias\.(\w+)$/ and exists $r->{$1}
!ll&&!rl&&r
000
MC/DC0%0/2
$w =~ /^$alias\.(\w+)$/ and exists $r->{$1}
$w =~ /^$alias\.(\w+)$/ exists $r->{$1}
Truth table0%0/3
A and B
A= $w =~ /^$alias\.(\w+)$/B= exists $r->{$1}
ABresult
0X0
100
111
1606 0 $p{$w} = $r->{$1};
1607 }
1608 else {
1609  
1610 # bare name search
1611 0 for my $k (keys %$r) {
1612 0 ▶ if (($k =~ /\.\Q$w\E$/) || ($k eq $w)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /\.\Q$w\E$/ or $k eq $w) 0 0 0
Condition0%0/3
$k =~ /\.\Q$w\E$/ or $k eq $w
l!l&&r!l&&!r
000
MC/DC0%0/2
$k =~ /\.\Q$w\E$/ or $k eq $w
$k =~ /\.\Q$w\E$/ $k eq $w
Truth table0%0/3
A or B
A= $k =~ /\.\Q$w\E$/B= $k eq $w
ABresult
1X1
011
000
1613 0 $p{$w} = $r->{$k};
1614 0 last;
1615 }
1616 }
1617 }
1618 }
1619 22 push @proj_rows, { %p };
1620 }
1621 }
1622  
1623 19 return { type=>'rows', data=>[ @proj_rows ] };
1624 }
1625  
1626 # ---------------------------------------------------------------------------
1627 # Scalar subquery in SELECT list
1628 # SELECT (SELECT agg_col FROM t WHERE ...) AS label, other_col FROM main_tbl ...
1629 # ---------------------------------------------------------------------------
1630 sub _exec_scalar_select_subquery {
1631 0 ▶ my($self, $sql) = @_;
Subroutine _exec_scalar_select_subquery: not called CC=2 SCAR=17.9
1632  
1633 # Strategy: collect all scalar subqueries in the SELECT list,
1634 # evaluate each, replace with the literal value, then execute the rest.
1635  
1636 # Find all top-level (SELECT ...) AS alias in the SELECT list
1637 # For simplicity: expand iteratively like WHERE subqueries
1638 0 my $expanded = $self->_expand_where_subqueries($sql, {});
1639 0 ▶ return $expanded if ref($expanded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $expanded eq "HASH" 0 0 0
1640 0 return $self->execute($expanded);
1641 }
1642  
1643 # ---------------------------------------------------------------------------
1644 # Extract content between matching parens starting at $start_pos.
1645 # Returns ($content_without_outer_parens, $close_paren_pos).
1646 # ---------------------------------------------------------------------------
1647 sub _extract_paren_content {
1648 19 ▶ my($sql, $start_pos) = @_;
Subroutine _extract_paren_content: called CC=10 SCAR=25.5
1649 19 my $len = length($sql);
1650 19 my $depth = 0;
1651 19 my $in_str = 0;
1652 19 for my $i ($start_pos .. $len-1) {
1653 548 my $ch = substr($sql, $i, 1);
1654 548 ▶ if (($ch eq "'") && !$in_str) {
Branch: 3 branches
BranchTrueFalseTotal
if ($ch eq q['] and not $in_str) { } 0 548 548
elsif ($ch eq q['] and $in_str) { } 0 548 548
elsif (not $in_str) { } 548 0 548
Condition33%1/3
$ch eq "'" and not $in_str
!ll&&!rl&&r
54800
MC/DC0%0/2
$ch eq "'" and not $in_str
$ch eq "'" not $in_str
Truth table33%1/3
A and not(B)
A= $ch eq "'"B= not $in_str
ABresult
0X0
100
111
1655 0 $in_str = 1;
1656 }
1657 ▶ elsif (($ch eq "'") && $in_str) {
Condition33%1/3
$ch eq "'" and $in_str
!ll&&!rl&&r
54800
MC/DC0%0/2
$ch eq "'" and $in_str
$ch eq "'" $in_str
Truth table33%1/3
A and B
A= $ch eq "'"B= $in_str
ABresult
0X0
100
111
1658 0 $in_str = 0;
1659 }
1660 elsif (!$in_str) {
1661 548 ▶ if ($ch eq '(') {
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq '(') { } 19 529 548
elsif ($ch eq ')') { } 19 510 529
1662 19 $depth++;
1663 }
1664 elsif ($ch eq ')') {
1665 19 $depth--;
1666 19 ▶ if ($depth == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth == 0) 19 0 19
1667 19 return (substr($sql, $start_pos+1, $i-$start_pos-1), $i);
1668 }
1669 }
1670 }
1671 }
1672 19 return (undef, undef);
1673 }
1674  
1675 ###############################################################################
1676 # Index internals
1677 ###############################################################################
1678  
1679 sub _idx_file {
1680 4253 ▶ my($self, $table, $idxname) = @_;
Subroutine _idx_file: called CC=1 SCAR=0.0
1681 4253 File::Spec->catfile($self->{base_dir}, $self->{db_name}, "$table.$idxname.idx");
1682 }
1683  
1684 sub _encode_key {
1685 2525 ▶ my($type, $keysize, $val) = @_;
Subroutine _encode_key: called CC=10 SCAR=23.2
1686 2525 ▶ $val = '' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 6 2519 2525
1687 2525 ▶ if ($type eq 'INT') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'INT') { } 1728 797 2525
elsif ($type eq 'FLOAT') { } 137 660 797
1688 1728 ▶ my $iv = _looks_numeric($val) ? int($val) : 0;
Branch: 1 branch
BranchTrueFalseTotal
_looks_numeric($val) ? : 1728 0 1728
1689 1728 ▶ $iv = INT_MAX if $iv > INT_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if $iv > 2147483647 0 1728 1728
1690 1728 ▶ $iv = INT_MIN if $iv < INT_MIN;
Branch: 1 branch
BranchTrueFalseTotal
if $iv < '-2147483648' 0 1728 1728
1691 1728 return pack('N', ($iv & 0xFFFFFFFF) ^ 0x80000000);
1692 }
1693 elsif ($type eq 'FLOAT') {
1694  
1695 # A value that is not numeric encodes as 0, exactly as it is
1696 # stored by _pack_record. The test is made here rather than left
1697 # to pack() so that -w stays quiet: an index on a FLOAT column
1698 # used to make a single INSERT emit two "isn't numeric" warnings.
1699 # my $packed = pack('d>', $val+0);
1700 137 ▶ my $packed = pack('d', _looks_numeric($val) ? $val+0 : 0);
Branch: 1 branch
BranchTrueFalseTotal
_looks_numeric($val) ? : 129 8 137
1701 137 ▶ $packed = reverse($packed) if unpack("C", pack("S", 1));
Branch: 1 branch
BranchTrueFalseTotal
if unpack "C", "\1\0" 137 0 137
1702  
1703 137 my @b = unpack('C8', $packed);
1704 137 ▶ if ($b[0] & 0x80) {
Branch: 1 branch
BranchTrueFalseTotal
if ($b[0] & 128) { } 4 133 137
1705 4 @b = map { $_ ^ 0xFF } @b;
1706 }
1707 else {
1708 133 $b[0] ^= 0x80;
1709 }
1710 137 return pack('C8', @b);
1711 }
1712 else {
1713 660 my $sv = substr($val, 0, $keysize);
1714 660 $sv .= "\x00" x ($keysize - length($sv));
1715 660 return $sv;
1716 }
1717 }
1718  
1719  
1720 sub _idx_entry_size {
1721 2223 ▶ $_[0]->{keysize} + REC_NO_SIZE;
Subroutine _idx_entry_size: called CC=1 SCAR=0.0
1722 }
1723  
1724 sub _idx_read_all {
1725 2223 ▶ my($self, $table, $ix) = @_;
Subroutine _idx_read_all: called CC=6 SCAR=18.4
1726 2223 my $idx_file = $self->_idx_file($table, $ix->{name});
1727 2223 my $entry_size = _idx_entry_size($ix);
1728 2223 my @entries;
1729 2223 ▶ return [ @entries ] unless -f $idx_file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $idx_file 0 2223 2223
1730 2223 local *FH;
1731 2223 ▶ open(FH, "< $idx_file") or return [ @entries ];
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $idx_file" or return [@entries] 0 2223 2223
1732 2223 binmode FH;
1733 2223 _lock_sh(\*FH);
1734 2223 my $magic = '';
1735 2223 read(FH, $magic, IDX_MAGIC_LEN);
1736 2223 ▶ unless ($magic eq IDX_MAGIC) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($magic eq "SDBIDX1\n") 0 2223 2223
1737 0 _unlock(\*FH);
1738 0 close FH;
1739 0 return [ @entries ];
1740 }
1741 2223 while (1) {
1742 319794 my $entry = '';
1743 319794 my $n = read(FH, $entry, $entry_size);
1744 319794 ▶ last unless defined($n) && ($n == $entry_size);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $entry_size 2223 317571 319794
Condition66%2/3
defined $n and $n == $entry_size
!ll&&!rl&&r
02223317571
MC/DC50%1/2
defined $n and $n == $entry_size
defined $n $n == $entry_size
Truth table66%2/3
A and B
A= defined $nB= $n == $entry_size
ABresult
0X0
100
111
1745 317571 push @entries, [ substr($entry, 0, $ix->{keysize}), unpack('N', substr($entry, $ix->{keysize}, REC_NO_SIZE)) ];
1746 }
1747 2223 _unlock(\*FH);
1748 2223 close FH;
1749 2223 return [ @entries ];
1750 }
1751  
1752 sub _idx_write_all {
1753 2022 ▶ my($self, $table, $ix, $entries) = @_;
Subroutine _idx_write_all: called CC=7 SCAR=20.6
1754 2022 my $idx_file = $self->_idx_file($table, $ix->{name});
1755 2022 local *FH;
1756 2022 ▶ unless (-f $idx_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $idx_file) 55 1967 2022
1757 55 ▶ open(FH, "> $idx_file") or return $self->_err("Cannot create index: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "> $idx_file" or return $self->_err("Cannot create index: $!") 0 55 55
1758 55 close FH;
1759 }
1760 # Open without truncating, so that the file is emptied only after the
1761 # exclusive lock is held. Opening with '>' truncates at open() time,
1762 # which destroys a concurrent writer's data while we wait for the lock.
1763 2022 ▶ open(FH, "+< $idx_file") or return $self->_err("Cannot write index: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "+< $idx_file" or return $self->_err("Cannot write index: $!") 0 2022 2022
1764 2022 binmode FH;
1765 2022 _autoflush(\*FH);
1766 2022 _lock_ex(\*FH);
1767 2022 truncate(FH, 0);
1768 2022 seek(FH, 0, 0);
1769 # The whole image is assembled first and written with a single print,
1770 # so autoflush costs one write() per rebuild rather than one per entry.
1771 2022 my $image = IDX_MAGIC;
1772 2022 for my $e (@$entries) {
1773 315025 $image .= $e->[0] . pack('N', $e->[1]);
1774 }
1775 2022 my $ok = print FH $image;
1776 2022 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 2022 2022
1777 0 my $e = $!;
1778 0 _unlock(\*FH);
1779 0 close FH;
1780 0 return $self->_err("Cannot write index: $e");
1781 }
1782 2022 _unlock(\*FH);
1783 2022 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 2022 2022
1784 0 return $self->_err("Cannot flush index: $!");
1785 }
1786 2022 return 1;
1787 }
1788  
1789 sub _idx_bisect {
1790 2430 ▶ my($entries, $key_bytes) = @_;
Subroutine _idx_bisect: called CC=3 SCAR=11.0
1791 2430 my($lo, $hi) = (0, scalar @$entries);
1792 2430 ▶ while ($lo < $hi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo < $hi) 13740 2430 16170
1793 13740 my $mid = int(($lo + $hi) / 2);
1794 13740 ▶ if ($entries->[$mid][0] lt $key_bytes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entries->[$mid][0] lt $key_bytes) { } 9657 4083 13740
1795 9657 $lo = $mid + 1;
1796 }
1797 else {
1798 4083 $hi = $mid;
1799 }
1800 }
1801 2430 return $lo;
1802 }
1803  
1804 sub _idx_lookup_exact {
1805 69 ▶ my($self, $table, $ix, $val) = @_;
Subroutine _idx_lookup_exact: called CC=3 SCAR=11.0
1806 69 my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
1807 69 my $entries = $self->_idx_read_all($table, $ix);
1808 69 my $pos = _idx_bisect($entries, $key_bytes);
1809 69 ▶ while (($pos < @$entries) && ($entries->[$pos][0] eq $key_bytes)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < @$entries and $entries->[$pos][0] eq $key_bytes) 14 55 69
Condition66%2/3
$pos < @$entries and $entries->[$pos][0] eq $key_bytes
!ll&&!rl&&r
55014
MC/DC50%1/2
$pos < @$entries and $entries->[$pos][0] eq $key_bytes
$pos < @$entries $entries->[$pos][0] eq $key_bytes
Truth table66%2/3
A and B
A= $pos < @$entriesB= $entries->[$pos][0] eq $key_bytes
ABresult
0X0
100
111
1810 14 return $pos;
1811 }
1812 55 return -1;
1813 }
1814  
1815 sub _idx_insert {
1816 1948 ▶ my($self, $table, $ix, $val, $rec_no) = @_;
Subroutine _idx_insert: called CC=1 SCAR=0.0
1817 1948 my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
1818 1948 my $entries = $self->_idx_read_all($table, $ix);
1819 1948 my $pos = _idx_bisect($entries, $key_bytes);
1820 1948 splice(@$entries, $pos, 0, [$key_bytes, $rec_no]);
1821 1948 return $self->_idx_write_all($table, $ix, $entries);
1822 }
1823  
1824 sub _idx_delete {
1825 15 ▶ my($self, $table, $ix, $val, $rec_no) = @_;
Subroutine _idx_delete: called CC=5 SCAR=16.7
1826 15 my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
1827 15 my $entries = $self->_idx_read_all($table, $ix);
1828 15 my $pos = _idx_bisect($entries, $key_bytes);
1829 15 my $deleted = 0;
1830 15 ▶ while (($pos < @$entries) && ($entries->[$pos][0] eq $key_bytes)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < @$entries and $entries->[$pos][0] eq $key_bytes) 21 0 21
Condition33%1/3
$pos < @$entries and $entries->[$pos][0] eq $key_bytes
!ll&&!rl&&r
0021
MC/DC0%0/2
$pos < @$entries and $entries->[$pos][0] eq $key_bytes
$pos < @$entries $entries->[$pos][0] eq $key_bytes
Truth table33%1/3
A and B
A= $pos < @$entriesB= $entries->[$pos][0] eq $key_bytes
ABresult
0X0
100
111
1831 21 ▶ if ($entries->[$pos][1] == $rec_no) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entries->[$pos][1] == $rec_no) 15 6 21
1832 15 splice(@$entries, $pos, 1);
1833 15 $deleted++;
1834 15 last;
1835 }
1836 6 $pos++;
1837 }
1838 15 ▶ return $self->_idx_write_all($table, $ix, $entries) if $deleted;
Branch: 1 branch
BranchTrueFalseTotal
if $deleted 15 0 15
1839 0 return 1;
1840 }
1841  
1842 sub _idx_range {
1843 39 ▶ my($self, $table, $ix, $lo_val, $lo_inc, $hi_val, $hi_inc) = @_;
Subroutine _idx_range: called CC=10 SCAR=23.0
1844 39 my $entries = $self->_idx_read_all($table, $ix);
1845 39 ▶ return [] unless @$entries;
Branch: 1 branch
BranchTrueFalseTotal
unless @$entries 0 39 39
1846  
1847 39 my $lo_pos = 0;
1848 39 ▶ if (defined $lo_val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lo_val) 32 7 39
1849 32 my $lo_key = _encode_key($ix->{coltype}, $ix->{keysize}, $lo_val);
1850 32 $lo_pos = _idx_bisect($entries, $lo_key);
1851 32 ▶ $lo_pos++ while !$lo_inc && ($lo_pos < @$entries) && ($entries->[$lo_pos][0] eq $lo_key);
Branch: 1 branch
BranchTrueFalseTotal
not $lo_inc and $lo_pos < @$entries and $entries->[$lo_pos][0] eq $lo_key and do { ++$lo_pos } 9 32 41
Condition83%5/6
not $lo_inc and $lo_pos < @$entries and $entries->[$lo_pos][0] eq $lo_key
!ll&&!rl&&r
21119
not $lo_inc and $lo_pos < @$entries
!ll&&!rl&&r
21020
MC/DC66%2/3
not $lo_inc and $lo_pos < @$entries and $entries->[$lo_pos][0] eq $lo_key
not $lo_inc $lo_pos < @$entries $entries->[$lo_pos][0] eq $lo_key
Truth table75%3/4
not(A) and B and C
A= not $lo_incB= $lo_pos < @$entriesC= $entries->[$lo_pos][0] eq $lo_key
ABCresult
0XX0
10X0
1100
1111
1852 }
1853 39 my $hi_pos = scalar @$entries;
1854 39 ▶ if (defined $hi_val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hi_val) 23 16 39
1855 23 my $hi_key = _encode_key($ix->{coltype}, $ix->{keysize}, $hi_val);
1856 23 my $p = _idx_bisect($entries, $hi_key);
1857 23 ▶ $p++ while $hi_inc && ($p < @$entries) && ($entries->[$p][0] eq $hi_key);
Branch: 1 branch
BranchTrueFalseTotal
$hi_inc and $p < @$entries and $entries->[$p][0] eq $hi_key and do { ++$p } 18 23 41
Condition100%6/6
$hi_inc and $p < @$entries and $entries->[$p][0] eq $hi_key
!ll&&!rl&&r
51818
$hi_inc and $p < @$entries
!ll&&!rl&&r
4136
MC/DC100%3/3
$hi_inc and $p < @$entries and $entries->[$p][0] eq $hi_key
$hi_inc $p < @$entries $entries->[$p][0] eq $hi_key
Truth table100%4/4
A and B and C
A= $hi_incB= $p < @$entriesC= $entries->[$p][0] eq $hi_key
ABCresult
0XX0
10X0
1100
1111
1858 23 $hi_pos = $p;
1859 }
1860 39 return [ map { $entries->[$_][1] } $lo_pos .. $hi_pos-1 ];
1861 }
1862  
1863 sub _rebuild_index {
1864 59 ▶ my($self, $table, $idxname) = @_;
Subroutine _rebuild_index: called CC=8 SCAR=20.9
1865 59 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 0 59 59
1866 59 my $ix = $sch->{indexes}{$idxname};
1867 59 ▶ return $self->_err("Index '$idxname' not found") unless $ix;
Branch: 1 branch
BranchTrueFalseTotal
unless $ix 0 59 59
1868 59 my $dat = $self->_file($table, 'dat');
1869 59 my $recsize = $sch->{recsize};
1870 59 my @entries;
1871 59 ▶ if (-f $dat) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $dat) 59 0 59
1872 59 local *FH;
1873 59 ▶ open(FH, "< $dat") or return $self->_err("Cannot read dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot read dat: $!") 0 59 59
1874 59 binmode FH;
1875 59 _lock_sh(\*FH);
1876 59 my $rec_no = 0;
1877 59 while (1) {
1878 155 my $raw = '';
1879 155 my $n = read(FH, $raw, $recsize);
1880 155 ▶ last unless defined($n) && ($n == $recsize);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $recsize 59 96 155
Condition66%2/3
defined $n and $n == $recsize
!ll&&!rl&&r
05996
MC/DC50%1/2
defined $n and $n == $recsize
defined $n $n == $recsize
Truth table66%2/3
A and B
A= defined $nB= $n == $recsize
ABresult
0X0
100
111
1881 96 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 95 1 96
1882 95 my $row = $self->_unpack_record($sch, $raw);
1883 95 push @entries, [ _encode_key($ix->{coltype}, $ix->{keysize}, $row->{$ix->{col}}), $rec_no ];
1884 }
1885 96 $rec_no++;
1886 }
1887 59 _unlock(\*FH);
1888 59 close FH;
1889 }
1890 59 @entries = sort { $a->[0] cmp $b->[0] } @entries;
1891 59 return $self->_idx_write_all($table, $ix, [ @entries ]);
1892 }
1893  
1894 sub _find_index_for_conds {
1895 235 ▶ my($self, $table, $sch, $conds) = @_;
Subroutine _find_index_for_conds: called CC=14 SCAR=26.4
1896 235 ▶ return undef unless $conds && @$conds;
Branch: 1 branch
BranchTrueFalseTotal
unless $conds and @$conds 0 235 235
Condition33%1/3
$conds and @$conds
!ll&&!rl&&r
00235
MC/DC0%0/2
$conds and @$conds
$conds @$conds
Truth table33%1/3
A and B
A= $condsB= @$conds
ABresult
0X0
100
111
1897 235 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 177 58 235
1898 58 my %col2ix;
1899 58 for my $ix (values %{$sch->{indexes}}) {
1900 97 $col2ix{$ix->{col}} = $ix;
1901 }
1902 58 for my $c (@$conds) {
1903 58 ▶ my $ix = $col2ix{$c->{col}} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$c->{"col"}} or next 10 48 58
1904 48 my $op = $c->{op};
1905 48 ▶ if ($op eq '=') {
Branch: 5 branches
BranchTrueFalseTotal
if ($op eq '=') { } 31 17 48
elsif ($op eq '<') { } 2 15 17
elsif ($op eq '<=') { } 3 12 15
elsif ($op eq '>') { } 5 7 12
elsif ($op eq '>=') { } 6 1 7
1906 31 my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $c->{val});
1907 31 my $entries = $self->_idx_read_all($table, $ix);
1908 31 my $pos = _idx_bisect($entries, $key_bytes);
1909 31 my @rec_nos;
1910 31 ▶ while (($pos < @$entries) && ($entries->[$pos][0] eq $key_bytes)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < @$entries and $entries->[$pos][0] eq $key_bytes) 42 31 73
Condition100%3/3
$pos < @$entries and $entries->[$pos][0] eq $key_bytes
!ll&&!rl&&r
92242
MC/DC100%2/2
$pos < @$entries and $entries->[$pos][0] eq $key_bytes
$pos < @$entries $entries->[$pos][0] eq $key_bytes
Truth table100%3/3
A and B
A= $pos < @$entriesB= $entries->[$pos][0] eq $key_bytes
ABresult
0X0
100
111
1911 42 push @rec_nos, $entries->[$pos][1];
1912 42 $pos++;
1913 }
1914 31 return [ @rec_nos ];
1915 }
1916 elsif ($op eq '<') {
1917 2 return $self->_idx_range($table, $ix, undef, 0, $c->{val}, 0);
1918 }
1919 elsif ($op eq '<=') {
1920 3 return $self->_idx_range($table, $ix, undef, 0, $c->{val}, 1);
1921 }
1922 elsif ($op eq '>') {
1923 5 return $self->_idx_range($table, $ix, $c->{val}, 0, undef, 0);
1924 }
1925 elsif ($op eq '>=') {
1926 6 return $self->_idx_range($table, $ix, $c->{val}, 1, undef, 0);
1927 }
1928 }
1929 11 return undef;
1930 }
1931  
1932 # _try_index_and_range($table, $sch, $where_expr)
1933 #
1934 # Attempt to satisfy a two-sided range or BETWEEN predicate using an index.
1935 # Recognises these WHERE patterns (same column, values numeric or quoted):
1936 # col OP1 val1 AND col OP2 val2 (e.g. id > 5 AND id < 10)
1937 # col BETWEEN val1 AND val2
1938 # Returns an arrayref of matching record numbers, or undef if no index
1939 # can be applied (caller falls through to a full table scan).
1940 #
1941 sub _try_index_and_range {
1942 367 ▶ my($self, $table, $sch, $where_expr) = @_;
Subroutine _try_index_and_range: called CC=13 SCAR=25.9
1943 367 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 129 367
1944 129 my %col2ix;
1945 129 for my $ix (values %{$sch->{indexes}}) {
1946 235 $col2ix{$ix->{col}} = $ix;
1947 }
1948 129 my $VAL = qr/(?:'([^']*)'|(-?\d+\.?\d*))/;
1949 129 my $OP = qr/(<=|>=|<|>)/;
1950 # BETWEEN col BETWEEN val1 AND val2
1951 129 ▶ if ($where_expr =~ /^(\w+)\s+BETWEEN\s+$VAL\s+AND\s+$VAL\s*$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($where_expr =~ /^(\w+)\s+BETWEEN\s+$VAL\s+AND\s+$VAL\s*$/i) 6 123 129
1952 6 my($col, $lo_s, $lo_n, $hi_s, $hi_n) = ($1, $2, $3, $4, $5);
1953 6 ▶ my $lo = defined($lo_s) ? $lo_s : $lo_n;
Branch: 1 branch
BranchTrueFalseTotal
defined $lo_s ? : 0 6 6
1954 6 ▶ my $hi = defined($hi_s) ? $hi_s : $hi_n;
Branch: 1 branch
BranchTrueFalseTotal
defined $hi_s ? : 0 6 6
1955 6 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 0 6 6
1956 6 return $self->_idx_range($table, $ix, $lo, 1, $hi, 1);
1957 }
1958 # AND: col OP val AND col OP val (same column)
1959 123 ▶ if ($where_expr =~ /^(\w+)\s+$OP\s+$VAL\s+AND\s+\1\s+$OP\s+$VAL\s*$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($where_expr =~ /^(\w+)\s+$OP\s+$VAL\s+AND\s+\1\s+$OP\s+$VAL\s*$/i) 10 113 123
1960 10 my($col, $op1, $v1s, $v1n, $op2, $v2s, $v2n) = ($1, $2, $3, $4, $5, $6, $7);
1961 10 ▶ my $v1 = defined($v1s) ? $v1s : $v1n;
Branch: 1 branch
BranchTrueFalseTotal
defined $v1s ? : 0 10 10
1962 10 ▶ my $v2 = defined($v2s) ? $v2s : $v2n;
Branch: 1 branch
BranchTrueFalseTotal
defined $v2s ? : 0 10 10
1963 10 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 0 10 10
1964 # Determine lo (lower bound) and hi (upper bound)
1965 10 my($lo, $lo_inc, $hi, $hi_inc);
1966 10 ▶ if ($op1 eq '>' || $op1 eq '>=') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op1 eq '>' or $op1 eq '>=') { } 9 1 10
Condition100%3/3
$op1 eq ">" or $op1 eq ">="
l!l&&r!l&&!r
271
MC/DC100%2/2
$op1 eq ">" or $op1 eq ">="
$op1 eq ">" $op1 eq ">="
Truth table100%3/3
A or B
A= $op1 eq ">"B= $op1 eq ">="
ABresult
1X1
011
000
1967 9 ($lo, $lo_inc) = ($v1, $op1 eq '>=');
1968 9 ($hi, $hi_inc) = ($v2, $op2 eq '<=');
1969 }
1970 else {
1971 1 ($lo, $lo_inc) = ($v2, $op2 eq '>=');
1972 1 ($hi, $hi_inc) = ($v1, $op1 eq '<=');
1973 }
1974 10 return $self->_idx_range($table, $ix, $lo, $lo_inc, $hi, $hi_inc);
1975 }
1976 113 return undef;
1977 }
1978  
1979 # _try_index_partial_and($table, $sch, $where_expr)
1980 #
1981 # For AND expressions involving multiple columns, pick the single indexed
1982 # column that yields the smallest candidate set and return its record
1983 # numbers. The caller applies the full WHERE predicate as a post-filter,
1984 # so correctness is guaranteed regardless of which index is chosen.
1985 #
1986 # Recognises AND-connected atoms of the form:
1987 # col = val col > val col >= val col < val col <= val
1988 # (quoted or numeric values; no subexpressions, BETWEEN, IN, OR, NOT)
1989 #
1990 # Returns an arrayref of candidate record numbers, or undef when no
1991 # usable index is found (caller falls through to a full table scan).
1992 #
1993 sub _try_index_partial_and {
1994 351 ▶ my($self, $table, $sch, $where_expr) = @_;
Subroutine _try_index_partial_and: called CC=26 SCAR=35.8
1995 351 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 113 351
1996 # Only handle pure AND expressions (no OR/NOT/BETWEEN/IN/subqueries)
1997 113 ▶ return undef if $where_expr =~ /\b(?:OR|NOT|BETWEEN|IN)\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $where_expr =~ /\b(?:OR|NOT|BETWEEN|IN)\b/i 88 25 113
1998 25 ▶ return undef if $where_expr =~ /\(\s*SELECT\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $where_expr =~ /\(\s*SELECT\b/i 0 25 25
1999 # Split on AND and collect simple col OP val atoms
2000 25 my @atoms;
2001 25 my $VAL = qr/(?:'[^']*'|-?\d+\.?\d*)/;
2002 25 my $OP = qr/(?:<=|>=|!=|<>|<|>|=)/;
2003 25 for my $part (split /\bAND\b/i, $where_expr) {
2004 39 $part =~ s/^\s+|\s+$//g;
2005 39 ▶ if ($part =~ /^(\w+)\s*($OP)\s*($VAL)$/
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s*($OP)\s*($VAL)$/ or $part =~ /^($VAL)\s*($OP)\s*(\w+)$/) { } 38 1 39
Condition66%2/3
$part =~ /^(\w+)\s*($OP)\s*($VAL)$/ or $part =~ /^($VAL)\s*($OP)\s*(\w+)$/
l!l&&r!l&&!r
3801
MC/DC50%1/2
$part =~ /^(\w+)\s*($OP)\s*($VAL)$/ or $part =~ /^($VAL)\s*($OP)\s*(\w+)$/
$part =~ /^(\w+)\s*($OP)\s*($VAL)$/ $part =~ /^($VAL)\s*($OP)\s*(\w+)$/
Truth table66%2/3
A or B
A= $part =~ /^(\w+)\s*($OP)\s*($VAL)$/B= $part =~ /^($VAL)\s*($OP)\s*(\w+)$/
ABresult
1X1
011
000
2006 || $part =~ /^($VAL)\s*($OP)\s*(\w+)$/) {
2007 # Normalise so col is always on the left
2008 38 my($col, $op, $val);
2009 38 ▶ if ($part =~ /^(\w+)\s*($OP)\s*($VAL)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s*($OP)\s*($VAL)$/) { } 38 0 38
2010 38 ($col, $op, $val) = ($1, uc($2), $3);
2011 }
2012 else {
2013 # val OP col -- reverse the operator
2014 0 $part =~ /^($VAL)\s*($OP)\s*(\w+)$/;
2015 0 my %rev = ('>' => '<', '<' => '>', '>=' => '<=',
2016 '<=' => '>=', '=' => '=', '!=' => '!=',
2017 '<>' => '<>');
2018 0 ▶ ($col, $op, $val) = ($3, $rev{uc($2)} || uc($2), $1);
Condition0%0/3
$rev{uc $2} || uc $2
l!l&&r!l&&!r
000
MC/DC0%0/2
$rev{uc $2} || uc $2
$rev{uc $2} uc $2
Truth table0%0/3
A || B
A= $rev{uc $2}B= uc $2
ABresult
1X1
011
000
2019 }
2020 38 $val =~ s/^'|'$//g; # strip surrounding quotes
2021 38 push @atoms, { col => $col, op => $op, val => $val };
2022 }
2023 else {
2024 1 return undef; # complex atom -- cannot use index safely
2025 }
2026 }
2027 24 ▶ return undef unless @atoms >= 2; # single atom handled by Case 1/2
Branch: 1 branch
BranchTrueFalseTotal
unless @atoms >= 2 11 13 24
2028 # Build column -> index map
2029 13 my %col2ix;
2030 13 for my $ix (values %{$sch->{indexes}}) {
2031 26 $col2ix{$ix->{col}} = $ix;
2032 }
2033 # Try each atom in turn; return the first index hit
2034 # (equality index preferred over range for a smaller candidate set)
2035 13 my $best_eq = undef; # record list from an equality match
2036 13 my $best_rng = undef; # record list from a range match
2037 13 for my $a (@atoms) {
2038 17 ▶ my $ix = $col2ix{$a->{col}} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$a->{"col"}} or next 4 13 17
2039 13 my $op = $a->{op};
2040 13 ▶ next if $op eq '!=' || $op eq '<>'; # inequality gives no benefit
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "!=" or $op eq "<>" 0 13 13
Condition33%1/3
$op eq "!=" or $op eq "<>"
l!l&&r!l&&!r
0013
MC/DC0%0/2
$op eq "!=" or $op eq "<>"
$op eq "!=" $op eq "<>"
Truth table33%1/3
A or B
A= $op eq "!="B= $op eq "<>"
ABresult
1X1
011
000
2041 13 my $recs;
2042 13 ▶ if ($op eq '=') {
Branch: 5 branches
BranchTrueFalseTotal
if ($op eq '=') { } 10 3 13
elsif ($op eq '<') { } 0 3 3
elsif ($op eq '<=') { } 0 3 3
elsif ($op eq '>') { } 3 0 3
elsif ($op eq '>=') { } 0 0 0
2043 10 my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $a->{val});
2044 10 my $entries = $self->_idx_read_all($table, $ix);
2045 10 my $pos = _idx_bisect($entries, $key);
2046 10 my @r;
2047 10 ▶ while (($pos < @$entries) && ($entries->[$pos][0] eq $key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < @$entries and $entries->[$pos][0] eq $key) 34 10 44
Condition100%3/3
$pos < @$entries and $entries->[$pos][0] eq $key
!ll&&!rl&&r
2834
MC/DC100%2/2
$pos < @$entries and $entries->[$pos][0] eq $key
$pos < @$entries $entries->[$pos][0] eq $key
Truth table100%3/3
A and B
A= $pos < @$entriesB= $entries->[$pos][0] eq $key
ABresult
0X0
100
111
2048 34 push @r, $entries->[$pos][1];
2049 34 $pos++;
2050 }
2051 10 $recs = [ @r ];
2052 # Equality index: take first found and stop
2053 10 ▶ $best_eq = $recs and last;
Branch: 1 branch
BranchTrueFalseTotal
$best_eq = $recs and last 10 0 10
2054 }
2055 elsif ($op eq '<') {
2056 0 $recs = $self->_idx_range($table, $ix, undef, 0, $a->{val}, 0);
2057 }
2058 elsif ($op eq '<=') {
2059 0 $recs = $self->_idx_range($table, $ix, undef, 0, $a->{val}, 1);
2060 }
2061 elsif ($op eq '>') {
2062 3 $recs = $self->_idx_range($table, $ix, $a->{val}, 0, undef, 0);
2063 }
2064 elsif ($op eq '>=') {
2065 0 $recs = $self->_idx_range($table, $ix, $a->{val}, 1, undef, 0);
2066 }
2067 3 ▶ $best_rng = $recs if defined $recs && !defined $best_rng;
Branch: 1 branch
BranchTrueFalseTotal
if defined $recs and not defined $best_rng 3 0 3
Condition33%1/3
defined $recs and not defined $best_rng
!ll&&!rl&&r
003
MC/DC0%0/2
defined $recs and not defined $best_rng
defined $recs not defined $best_rng
Truth table33%1/3
A and not(B)
A= defined $recsB= not defined $best_rng
ABresult
0X0
100
111
2068 }
2069 13 ▶ return $best_eq if defined $best_eq;
Branch: 1 branch
BranchTrueFalseTotal
if defined $best_eq 10 3 13
2070 3 return $best_rng;
2071 }
2072  
2073 # _try_index_in($table, $sch, $where_expr)
2074 #
2075 # Attempt to satisfy a col IN (v1, v2, ...) or col NOT IN (v1, v2, ...)
2076 # predicate using an index. For IN, performs one equality lookup per value
2077 # and returns the union of matching record numbers. NOT IN is not optimised
2078 # (returns undef so the caller falls through to a full table scan).
2079 #
2080 # The WHERE expression must consist of exactly one IN predicate with a
2081 # literal value list (no sub-selects, no OR/AND, no NOT IN).
2082 #
2083 # Returns an arrayref of candidate record numbers, or undef when no index
2084 # can be applied.
2085 #
2086 sub _try_index_in {
2087 342 ▶ my($self, $table, $sch, $where_expr) = @_;
Subroutine _try_index_in: called CC=14 SCAR=26.4
2088 342 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 104 342
2089 # Match: col IN (literal-list) no NOT IN, no sub-select
2090 104 ▶ return undef unless $where_expr =~ /^\s*(\w+)\s+IN\s*\(([^)]*)\)\s*$/si;
Branch: 1 branch
BranchTrueFalseTotal
unless $where_expr =~ /^\s*(\w+)\s+IN\s*\(([^)]*)\)\s*$/is 70 34 104
2091 34 my($col, $list_str) = ($1, $2);
2092 # Find index for this column
2093 34 my $ix;
2094 34 for my $candidate (values %{$sch->{indexes}}) {
2095 44 ▶ if ($candidate->{col} eq $col) {
Branch: 1 branch
BranchTrueFalseTotal
if ($candidate->{"col"} eq $col) 33 11 44
2096 33 $ix = $candidate;
2097 33 last;
2098 }
2099 }
2100 34 ▶ return undef unless defined $ix;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ix 1 33 34
2101 # Parse the value list
2102 33 my @vals;
2103 33 my $ls = $list_str;
2104 33 ▶ while ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) 93 32 125
2105 93 my($sv, $nv, $nl) = ($1, $2, $3);
2106 93 ▶ if (defined $nl) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $nl) { } 1 92 93
elsif (defined $sv) { } 11 81 92
2107 # NULL in IN list: no index lookup possible for NULL
2108 1 return undef;
2109 }
2110 elsif (defined $sv) {
2111 11 (my $x = $sv) =~ s/''/'/g;
2112 11 push @vals, $x;
2113 }
2114 else {
2115 81 push @vals, $nv;
2116 }
2117 }
2118 32 ▶ return undef unless @vals; # empty IN list: caller handles
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 0 32 32
2119 # Perform one equality index lookup per value, union the results
2120 32 my %seen;
2121 my @rec_nos;
2122 32 my $entries = $self->_idx_read_all($table, $ix);
2123 32 for my $val (@vals) {
2124 91 my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
2125 91 my $pos = _idx_bisect($entries, $key);
2126 91 ▶ while (($pos < @$entries) && ($entries->[$pos][0] eq $key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < @$entries and $entries->[$pos][0] eq $key) 110 91 201
Condition100%3/3
$pos < @$entries and $entries->[$pos][0] eq $key
!ll&&!rl&&r
1081110
MC/DC100%2/2
$pos < @$entries and $entries->[$pos][0] eq $key
$pos < @$entries $entries->[$pos][0] eq $key
Truth table100%3/3
A and B
A= $pos < @$entriesB= $entries->[$pos][0] eq $key
ABresult
0X0
100
111
2127 110 my $rn = $entries->[$pos][1];
2128 110 ▶ push @rec_nos, $rn unless $seen{$rn}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$rn}++ 108 2 110
2129 110 $pos++;
2130 }
2131 }
2132 32 return [ @rec_nos ];
2133 }
2134  
2135 # _try_index_or($table, $sch, $where_expr)
2136 #
2137 # Attempt to satisfy a pure OR expression using indexes.
2138 #
2139 # Every atom in the OR chain must be a simple condition that can be served
2140 # by an index on the relevant column. If any atom has no usable index the
2141 # function returns undef and the caller falls through to a full table scan.
2142 #
2143 # Recognised atom forms (same column or different columns):
2144 # col = val col != val (not optimised -- returns undef)
2145 # col OP val (OP: <, <=, >, >=)
2146 # col BETWEEN lo AND hi
2147 # col IN (v1, v2, ...)
2148 #
2149 # Returns an arrayref of deduplicated record numbers, or undef.
2150 #
2151 sub _try_index_or {
2152 310 ▶ my($self, $table, $sch, $where_expr) = @_;
Subroutine _try_index_or: called CC=26 SCAR=35.4
2153 310 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 72 310
2154 # Must be a pure OR expression -- no AND, no NOT, no subqueries
2155 72 ▶ return undef if $where_expr =~ /\b(?:AND|NOT)\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $where_expr =~ /\b(?:AND|NOT)\b/i 27 45 72
2156 45 ▶ return undef if $where_expr =~ /\(\s*SELECT\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $where_expr =~ /\(\s*SELECT\b/i 0 45 45
2157 # Split on OR
2158 45 my @atoms = DB::Handy::bool_split($where_expr, 'OR');
2159 45 ▶ return undef unless @atoms >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @atoms >= 2 14 31 45
2160 # Build column -> index map
2161 31 my %col2ix;
2162 31 for my $ix (values %{$sch->{indexes}}) {
2163 61 $col2ix{$ix->{col}} = $ix;
2164 }
2165 31 my $VAL = qr/(?:'(?:[^']|'')*'|-?\d+\.?\d*)/;
2166 31 my $OP = qr/(?:<=|>=|<|>|=)/;
2167 # Collect record numbers for each atom
2168 31 my %seen;
2169 my @all_recs;
2170 31 for my $atom (@atoms) {
2171 66 $atom =~ s/^\s+|\s+$//g;
2172 66 my $recs;
2173 # col BETWEEN lo AND hi
2174 66 ▶ if ($atom =~ /^(\w+)\s+BETWEEN\s+($VAL)\s+AND\s+($VAL)\s*$/i) {
Branch: 3 branches
BranchTrueFalseTotal
if ($atom =~ /^(\w+)\s+BETWEEN\s+($VAL)\s+AND\s+($VAL)\s*$/i) { } 0 66 66
elsif ($atom =~ /^(\w+)\s+IN\s*\(([^)]*)\)\s*$/i) { } 3 63 66
elsif ($atom =~ /^(\w+)\s*($OP)\s*($VAL)$/) { } 63 0 63
2175 0 my($col, $lo, $hi) = ($1, $2, $3);
2176 0 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 0 0 0
2177 0 $lo =~ s/^'(.*)'$/$1/s; $hi =~ s/^'(.*)'$/$1/s;
2178 0 $recs = $self->_idx_range($table, $ix, $lo, 1, $hi, 1);
2179 }
2180 # col IN (val, ...)
2181 elsif ($atom =~ /^(\w+)\s+IN\s*\(([^)]*)\)\s*$/i) {
2182 3 my($col, $list) = ($1, $2);
2183 3 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 0 3 3
2184 3 $recs = $self->_try_index_in($table, $sch, $atom);
2185 3 ▶ return undef unless defined $recs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $recs 0 3 3
2186 }
2187 # col OP val (equality or range, not !=/<>)
2188 elsif ($atom =~ /^(\w+)\s*($OP)\s*($VAL)$/) {
2189 63 my($col, $op, $val) = ($1, uc($2), $3);
2190 63 ▶ return undef if $op eq '!=' || $op eq '<>';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "!=" or $op eq "<>" 0 63 63
Condition33%1/3
$op eq "!=" or $op eq "<>"
l!l&&r!l&&!r
0063
MC/DC0%0/2
$op eq "!=" or $op eq "<>"
$op eq "!=" $op eq "<>"
Truth table33%1/3
A or B
A= $op eq "!="B= $op eq "<>"
ABresult
1X1
011
000
2191 63 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 1 62 63
2192 62 $val =~ s/^'(.*)'$/$1/s;
2193 62 ▶ if ($op eq '=') {
Branch: 5 branches
BranchTrueFalseTotal
if ($op eq '=') { } 58 4 62
elsif ($op eq '<') { } 0 4 4
elsif ($op eq '<=') { } 2 2 4
elsif ($op eq '>') { } 0 2 2
elsif ($op eq '>=') { } 2 0 2
2194 58 my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
2195 58 my $entries = $self->_idx_read_all($table, $ix);
2196 58 my $pos = _idx_bisect($entries, $key);
2197 58 my @r;
2198 58 ▶ while (($pos < @$entries) && ($entries->[$pos][0] eq $key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < @$entries and $entries->[$pos][0] eq $key) 414 58 472
Condition100%3/3
$pos < @$entries and $entries->[$pos][0] eq $key
!ll&&!rl&&r
1147414
MC/DC100%2/2
$pos < @$entries and $entries->[$pos][0] eq $key
$pos < @$entries $entries->[$pos][0] eq $key
Truth table100%3/3
A and B
A= $pos < @$entriesB= $entries->[$pos][0] eq $key
ABresult
0X0
100
111
2199 414 push @r, $entries->[$pos][1];
2200 414 $pos++;
2201 }
2202 58 $recs = [ @r ];
2203 }
2204 0 elsif ($op eq '<') { $recs = $self->_idx_range($table, $ix, undef, 0, $val, 0) }
2205 2 elsif ($op eq '<=') { $recs = $self->_idx_range($table, $ix, undef, 0, $val, 1) }
2206 0 elsif ($op eq '>') { $recs = $self->_idx_range($table, $ix, $val, 0, undef, 0) }
2207 2 elsif ($op eq '>=') { $recs = $self->_idx_range($table, $ix, $val, 1, undef, 0) }
2208 }
2209 else {
2210 0 return undef; # complex atom: cannot use index
2211 }
2212 65 ▶ return undef unless defined $recs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $recs 0 65 65
2213 65 for my $rn (@$recs) {
2214 431 ▶ push @all_recs, $rn unless $seen{$rn}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$rn}++ 427 4 431
2215 }
2216 }
2217 30 return [ @all_recs ];
2218 }
2219  
2220 # _try_index_not_in($table, $sch, $where_expr)
2221 #
2222 # Attempt to satisfy a col NOT IN (v1, v2, ...) predicate using an index.
2223 # Collects the record numbers that match the IN list (via index), then
2224 # returns all record numbers in the index that are NOT in that set.
2225 # Efficient when the exclusion list is small relative to total row count.
2226 #
2227 # NULL in the value list causes a fallback to a full table scan (SQL
2228 # semantics: NOT IN with NULL never matches any row).
2229 #
2230 # Returns an arrayref of candidate record numbers, or undef when no index
2231 # can be applied.
2232 #
2233 sub _try_index_not_in {
2234 280 ▶ my($self, $table, $sch, $where_expr) = @_;
Subroutine _try_index_not_in: called CC=16 SCAR=27.7
2235 280 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 42 280
2236 # Match: col NOT IN (literal-list) no sub-select
2237 42 ▶ return undef unless $where_expr =~ /^\s*(\w+)\s+NOT\s+IN\s*\(([^)]*)\)\s*$/si;
Branch: 1 branch
BranchTrueFalseTotal
unless $where_expr =~ /^\s*(\w+)\s+NOT\s+IN\s*\(([^)]*)\)\s*$/is 19 23 42
2238 23 my($col, $list_str) = ($1, $2);
2239 # Find index for this column
2240 23 my $ix;
2241 23 for my $candidate (values %{$sch->{indexes}}) {
2242 30 ▶ if ($candidate->{col} eq $col) {
Branch: 1 branch
BranchTrueFalseTotal
if ($candidate->{"col"} eq $col) 22 8 30
2243 22 $ix = $candidate;
2244 22 last;
2245 }
2246 }
2247 23 ▶ return undef unless defined $ix;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ix 1 22 23
2248 # Parse the NOT IN value list
2249 22 my @vals;
2250 22 my $ls = $list_str;
2251 22 ▶ while ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) 155 21 176
2252 155 my($sv, $nv, $nl) = ($1, $2, $3);
2253 155 ▶ if (defined $nl) { return undef } # NULL: fall back to full scan
Branch: 2 branches
BranchTrueFalseTotal
if (defined $nl) { } 1 154 155
elsif (defined $sv) { } 7 147 154
2254 7 elsif (defined $sv) { (my $x = $sv) =~ s/''/'/g; push @vals, $x }
2255 147 else { push @vals, $nv }
2256 }
2257 21 ▶ return undef unless @vals;
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 0 21 21
2258 # Build set of record numbers to EXCLUDE (those matching the IN list)
2259 21 my %exclude;
2260 21 my $entries = $self->_idx_read_all($table, $ix);
2261 21 for my $val (@vals) {
2262 153 my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
2263 153 my $pos = _idx_bisect($entries, $key);
2264 153 ▶ while (($pos < @$entries) && ($entries->[$pos][0] eq $key)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < @$entries and $entries->[$pos][0] eq $key) 161 153 314
Condition100%3/3
$pos < @$entries and $entries->[$pos][0] eq $key
!ll&&!rl&&r
8145161
MC/DC100%2/2
$pos < @$entries and $entries->[$pos][0] eq $key
$pos < @$entries $entries->[$pos][0] eq $key
Truth table100%3/3
A and B
A= $pos < @$entriesB= $entries->[$pos][0] eq $key
ABresult
0X0
100
111
2265 161 $exclude{$entries->[$pos][1]} = 1;
2266 161 $pos++;
2267 }
2268 }
2269 # Return all record numbers in the index that are NOT excluded
2270 21 my %seen;
2271 my @rec_nos;
2272 21 for my $entry (@$entries) {
2273 357 my $rn = $entry->[1];
2274 357 ▶ push @rec_nos, $rn unless $exclude{$rn} || $seen{$rn}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $exclude{$rn} or $seen{$rn}++ 196 161 357
Condition66%2/3
$exclude{$rn} or $seen{$rn}++
l!l&&r!l&&!r
1610196
MC/DC50%1/2
$exclude{$rn} or $seen{$rn}++
$exclude{$rn} $seen{$rn}++
Truth table66%2/3
A or B
A= $exclude{$rn}B= $seen{$rn}++
ABresult
1X1
011
000
2275 }
2276 21 return [ @rec_nos ];
2277 }
2278  
2279 ###############################################################################
2280 # JOIN -- Public entry point
2281 ###############################################################################
2282 # join_select(\@join_specs, \@col_specs, \@where_conds, \%opts)
2283 #
2284 # join_specs : arrayref of hashrefs, in left-to-right order
2285 # { table => 'employees', # physical table name
2286 # alias => 'e', # alias (or same as table)
2287 # type => 'INNER'|'LEFT'|'RIGHT'|'CROSS',
2288 # on_left => 'e.dept_id', # undef for first/CROSS
2289 # on_right => 'd.id', # undef for first/CROSS
2290 # }
2291 #
2292 # col_specs : arrayref of 'alias.col' or 'alias.*' or '*'
2293 # undef = all columns (alias-qualified)
2294 #
2295 # where_conds : arrayref of condition hashrefs (from _parse_join_conditions)
2296 # { lhs_alias, lhs_col, op, rhs_alias, rhs_col, val }
2297 #
2298 # opts : { order_by=>'alias.col'|'col', order_dir=>'ASC', limit=>N, offset=>M }
2299 #
2300 sub join_select {
2301 73 ▶ my($self, $join_specs, $col_specs, $where_conds, $opts) = @_;
Subroutine join_select: called CC=106 SCAR=52.4
Pod undocumented
2302 73 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 73 73
2303 73 ▶ $opts ||= {};
Condition50%1/2
$opts ||= {}
l!l
730
MC/DC0%0/1
$opts ||= {}
$opts
Truth table50%1/2
A
A= $opts
Aresult
11
00
2304 73 ▶ $where_conds ||= [];
Condition50%1/2
$where_conds ||= []
l!l
730
MC/DC0%0/1
$where_conds ||= []
$where_conds
Truth table50%1/2
A
A= $where_conds
Aresult
11
00
2305  
2306 # ------------------------------------------------------------------
2307 # Step 1: load schemas; build alias -> { table, schema } map
2308 # ------------------------------------------------------------------
2309 73 my %alias_info; # alias => { table, sch, rows(lazy) }
2310 73 for my $js (@$join_specs) {
2311 148 ▶ my $sch = $self->_load_schema($js->{table}) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($js->{"table"}) or return undef 0 148 148
2312 $alias_info{ $js->{alias} } = {
2313 table => $js->{table},
2314 148 sch => $sch,
2315 };
2316 }
2317  
2318 # ------------------------------------------------------------------
2319 # Step 2: load the leftmost (driving) table fully into memory
2320 # ------------------------------------------------------------------
2321 73 my $first = $join_specs->[0];
2322 73 my @cur_rows = @{ $self->_scan_table_all($first->{table}, $first->{alias}) };
2323 73 ▶ return undef unless defined($cur_rows[0]) || !$self->{_last_err};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $cur_rows[0] or not $self->{"_last_err"} 0 73 73
Condition33%1/3
defined $cur_rows[0] or not $self->{"_last_err"}
l!l&&r!l&&!r
7300
MC/DC0%0/2
defined $cur_rows[0] or not $self->{"_last_err"}
defined $cur_rows[0] not $self->{"_last_err"}
Truth table33%1/3
A or not(B)
A= defined $cur_rows[0]B= not $self->{"_last_err"}
ABresult
1X1
011
000
2324  
2325 # ------------------------------------------------------------------
2326 # Step 3: for each subsequent table, apply the JOIN
2327 # ------------------------------------------------------------------
2328 73 for my $i (1 .. $#$join_specs) {
2329 75 my $js = $join_specs->[$i];
2330 75 ▶ my $join_type = uc($js->{type} || 'INNER');
Condition50%1/2
$js->{'type'} || 'INNER'
l!l
750
MC/DC0%0/1
$js->{'type'} || 'INNER'
$js->{'type'}
Truth table50%1/2
A
A= $js->{'type'}
Aresult
11
00
2331  
2332 # Parse ON alias1.col1 = alias2.col2
2333 # A CROSS JOIN is unconditional, so an ON written on one is accepted
2334 # and ignored rather than checked.
2335 75 my($on_l_alias, $on_l_col, $on_r_alias, $on_r_col);
2336 75 ▶ if (($join_type ne 'CROSS') && $js->{on_left} && $js->{on_right}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($join_type ne "CROSS" and $js->{"on_left"} and $js->{"on_right"}) 73 2 75
Condition66%4/6
$join_type ne "CROSS" and $js->{"on_left"} and $js->{"on_right"}
!ll&&!rl&&r
2073
$join_type ne "CROSS" and $js->{"on_left"}
!ll&&!rl&&r
2073
MC/DC33%1/3
$join_type ne "CROSS" and $js->{"on_left"} and $js->{"on_right"}
$join_type ne "CROSS" $js->{"on_left"} $js->{"on_right"}
Truth table50%2/4
A and B and C
A= $join_type ne "CROSS"B= $js->{"on_left"}C= $js->{"on_right"}
ABCresult
0XX0
10X0
1100
1111
2337 73 ($on_l_alias, $on_l_col) = _split_qualified($js->{on_left});
2338 73 ($on_r_alias, $on_r_col) = _split_qualified($js->{on_right});
2339  
2340 # An equality is symmetric, but the code below is not: the left
2341 # operand has to name the accumulated left-hand side and the right
2342 # operand the table being joined in. "ON b.k = a.x" is as valid
2343 # as "ON a.x = b.k", and before 1.09 it produced a silent cross
2344 # join, so the operands are swapped here when they are the other
2345 # way round.
2346 73 ▶ if (defined($on_l_alias) && defined($on_r_alias)
Branch: 1 branch
BranchTrueFalseTotal
if (defined $on_l_alias and defined $on_r_alias and $on_l_alias eq $js->{"alias"} and $on_r_alias ne $js->{"alias"}) 2 71 73
Condition88%8/9
defined $on_l_alias and defined $on_r_alias and $on_l_alias eq $js->{"alias"} and $on_r_alias ne $js->{"alias"}
!ll&&!rl&&r
7102
defined $on_l_alias and defined $on_r_alias and $on_l_alias eq $js->{"alias"}
!ll&&!rl&&r
2692
defined $on_l_alias and defined $on_r_alias
!ll&&!rl&&r
1171
MC/DC75%3/4
defined $on_l_alias and defined $on_r_alias and $on_l_alias eq $js->{"alias"} and $on_r_alias ne $js->{"alias"}
defined $on_l_alias defined $on_r_alias $on_l_alias eq $js->{"alias"} $on_r_alias ne $js->{"alias"}
Truth table80%4/5
A and B and C and D
A= defined $on_l_aliasB= defined $on_r_aliasC= $on_l_alias eq $js->{"alias"}D= $on_r_alias ne $js->{"alias"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2347 && ($on_l_alias eq $js->{alias}) && ($on_r_alias ne $js->{alias})) {
2348 2 ($on_l_alias, $on_l_col, $on_r_alias, $on_r_col) =
2349 ($on_r_alias, $on_r_col, $on_l_alias, $on_l_col);
2350 }
2351  
2352 # Both operands have to be table-qualified. An unqualified name
2353 # cannot be looked up in a result row, whose keys are all
2354 # "alias.col", so before 1.09 "ON x = k" fell through to the
2355 # Cartesian-product branch without a word.
2356 73 ▶ unless (defined($on_l_alias) && defined($on_r_alias)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $on_l_alias and defined $on_r_alias) 2 71 73
Condition100%3/3
defined $on_l_alias and defined $on_r_alias
!ll&&!rl&&r
1171
MC/DC100%2/2
defined $on_l_alias and defined $on_r_alias
defined $on_l_alias defined $on_r_alias
Truth table100%3/3
A and B
A= defined $on_l_aliasB= defined $on_r_alias
ABresult
0X0
100
111
2357 2 return $self->_err(
2358 "Unqualified column in the ON clause of JOIN "
2359 . "$js->{table}; write ON <table>.<col> = <table>.<col>");
2360 }
2361  
2362 # A qualified operand has to name a table in this query.
2363 71 for my $qa ($on_l_alias, $on_r_alias) {
2364 142 ▶ next if $alias_info{$qa};
Branch: 1 branch
BranchTrueFalseTotal
if $alias_info{$qa} 141 1 142
2365 1 return $self->_err(
2366 "Unknown table or alias '$qa' in the ON clause of "
2367 . "JOIN $js->{table}");
2368 }
2369 70 ▶ if ($on_r_alias ne $js->{alias}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($on_r_alias ne $js->{"alias"}) 1 69 70
2370 1 return $self->_err(
2371 "The ON clause of JOIN $js->{table} does not reference "
2372 . "'$js->{alias}'; a join condition has to compare a "
2373 . "column of '$js->{alias}' with a column of a table "
2374 . "already joined");
2375 }
2376 }
2377  
2378 # Load the right-side table
2379 71 my @right_rows = @{ $self->_scan_table_all($js->{table}, $js->{alias}) };
2380  
2381 # Build hash on right side if possible (index-nested-loop join)
2382 71 my %right_hash;
2383 71 my $use_hash = 0;
2384 71 ▶ if (defined($on_r_alias) && defined($on_r_col)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $on_r_alias and defined $on_r_col) 69 2 71
Condition66%2/3
defined $on_r_alias and defined $on_r_col
!ll&&!rl&&r
2069
MC/DC50%1/2
defined $on_r_alias and defined $on_r_col
defined $on_r_alias defined $on_r_col
Truth table66%2/3
A and B
A= defined $on_r_aliasB= defined $on_r_col
ABresult
0X0
100
111
2385 69 for my $rr (@right_rows) {
2386 my $rkey = defined($rr->{"$on_r_alias.$on_r_col"})
2387 247 ▶ ? $rr->{"$on_r_alias.$on_r_col"}
Branch: 1 branch
BranchTrueFalseTotal
defined $$rr{"$on_r_alias.$on_r_col"} ? : 247 0 247
2388 : '';
2389 247 push @{ $right_hash{$rkey} }, $rr;
2390 }
2391 69 $use_hash = 1;
2392 }
2393  
2394 71 my @next_rows;
2395  
2396 71 ▶ if (($join_type eq 'CROSS') || (!defined $on_l_alias)) {
Branch: 4 branches
BranchTrueFalseTotal
if ($join_type eq 'CROSS' or not defined $on_l_alias) { } 2 69 71
elsif ($join_type eq 'INNER') { } 57 12 69
elsif ($join_type eq 'LEFT') { } 11 1 12
elsif ($join_type eq 'RIGHT') { } 1 0 1
Condition66%2/3
$join_type eq "CROSS" or not defined $on_l_alias
l!l&&r!l&&!r
2069
MC/DC50%1/2
$join_type eq "CROSS" or not defined $on_l_alias
$join_type eq "CROSS" not defined $on_l_alias
Truth table66%2/3
A or not(B)
A= $join_type eq "CROSS"B= not defined $on_l_alias
ABresult
1X1
011
000
2397  
2398 # Cartesian product
2399 2 for my $lr (@cur_rows) {
2400 5 for my $rr (@right_rows) {
2401 15 push @next_rows, { %$lr, %$rr };
2402 }
2403 }
2404 }
2405 elsif ($join_type eq 'INNER') {
2406 57 for my $lr (@cur_rows) {
2407 my $lkey = defined($lr->{"$on_l_alias.$on_l_col"})
2408 256 ▶ ? $lr->{"$on_l_alias.$on_l_col"}
Branch: 1 branch
BranchTrueFalseTotal
defined $$lr{"$on_l_alias.$on_l_col"} ? : 256 0 256
2409 : '';
2410 256 ▶ my $matches = $use_hash ? ($right_hash{$lkey} || []) : [ @right_rows ];
Branch: 1 branch
BranchTrueFalseTotal
$use_hash ? : 256 0 256
Condition100%2/2
$right_hash{$lkey} or []
l!l
19759
MC/DC100%1/1
$right_hash{$lkey} or []
$right_hash{$lkey}
Truth table100%2/2
A
A= $right_hash{$lkey}
Aresult
11
00
2411 256 for my $rr (@$matches) {
2412 230 ▶ next if ($use_hash == 0) && !_join_row_matches($lr, $rr, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col);
Branch: 1 branch
BranchTrueFalseTotal
if $use_hash == 0 and not _join_row_matches($lr, $rr, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col) 0 230 230
Condition33%1/3
$use_hash == 0 and not _join_row_matches($lr, $rr, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col)
!ll&&!rl&&r
23000
MC/DC0%0/2
$use_hash == 0 and not _join_row_matches($lr, $rr, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col)
$use_hash == 0 not _join_row_matches($lr, $rr, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col)
Truth table33%1/3
A and not(B)
A= $use_hash == 0B= not _join_row_matches($lr, $rr, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col)
ABresult
0X0
100
111
2413 230 push @next_rows, { %$lr, %$rr };
2414 }
2415 }
2416 }
2417 elsif ($join_type eq 'LEFT') {
2418 11 for my $lr (@cur_rows) {
2419 my $lkey = defined($lr->{"$on_l_alias.$on_l_col"})
2420 52 ▶ ? $lr->{"$on_l_alias.$on_l_col"}
Branch: 1 branch
BranchTrueFalseTotal
defined $$lr{"$on_l_alias.$on_l_col"} ? : 52 0 52
2421 : '';
2422 my $matches = $use_hash ? ($right_hash{$lkey} || [])
2423 52 ▶ : [ grep { _join_row_matches($lr, $_, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col) }
Branch: 1 branch
BranchTrueFalseTotal
$use_hash ? : 52 0 52
Condition100%2/2
$right_hash{$lkey} or []
l!l
4111
MC/DC100%1/1
$right_hash{$lkey} or []
$right_hash{$lkey}
Truth table100%2/2
A
A= $right_hash{$lkey}
Aresult
11
00
2424 @right_rows
2425 ];
2426 52 ▶ if (@$matches) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$matches) { } 41 11 52
2427 41 for my $rr (@$matches) {
2428 47 push @next_rows, { %$lr, %$rr };
2429 }
2430 }
2431 else {
2432  
2433 # NULL-fill right side
2434 11 my %null_right = _make_null_row($js->{alias}, $alias_info{$js->{alias}}{sch});
2435 11 push @next_rows, { %$lr, %null_right };
2436 }
2437 }
2438 }
2439 elsif ($join_type eq 'RIGHT') {
2440  
2441 # RIGHT JOIN: swap sides, do LEFT, then results are correct
2442 1 for my $rr (@right_rows) {
2443 5 ▶ my $rkey = defined($rr->{"$on_r_alias.$on_r_col"}) ? $rr->{"$on_r_alias.$on_r_col"} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$rr{"$on_r_alias.$on_r_col"} ? : 5 0 5
2444 5 my $l_alias_key = "$on_l_alias.$on_l_col";
2445 5 my @matched_lefts;
2446 5 for my $lr (@cur_rows) {
2447 35 ▶ my $lkey = defined($lr->{$l_alias_key}) ? $lr->{$l_alias_key} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $lr->{$l_alias_key} ? : 35 0 35
2448 35 ▶ push @matched_lefts, $lr if $lkey eq $rkey;
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq $rkey 6 29 35
2449 }
2450 5 ▶ if (@matched_lefts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@matched_lefts) { } 3 2 5
2451 3 for my $lr (@matched_lefts) {
2452 6 push @next_rows, { %$lr, %$rr };
2453 }
2454 }
2455 else {
2456  
2457 # NULL-fill all left-side aliases seen so far
2458 2 my %null_left;
2459 2 for my $prev_js (@{$join_specs}[0..$i-1]) {
2460 2 my %nr = _make_null_row($prev_js->{alias}, $alias_info{$prev_js->{alias}}{sch});
2461 2 %null_left = (%null_left, %nr);
2462 }
2463 2 push @next_rows, { %null_left, %$rr };
2464 }
2465 }
2466 }
2467  
2468 71 @cur_rows = @next_rows;
2469 }
2470  
2471 # ------------------------------------------------------------------
2472 # Step 4: apply WHERE (post-join filter)
2473 # ------------------------------------------------------------------
2474 69 ▶ if (@$where_conds) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$where_conds) 23 46 69
2475 23 my $wsub = _compile_join_where($where_conds);
2476 23 @cur_rows = grep { $wsub->($_) } @cur_rows;
2477 }
2478  
2479 # ------------------------------------------------------------------
2480 # Step 5: ORDER BY
2481 # ------------------------------------------------------------------
2482 # order_keys holds every ORDER BY key as [ name, ASC|DESC ]; order_by and
2483 # order_dir carry the first key so that older callers keep working.
2484 69 my @ob_keys;
2485 69 ▶ if ($opts->{order_keys} && @{$opts->{order_keys}}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($opts->{'order_keys'} and @{$opts->{'order_keys'};}) { } 28 41 69
elsif ($opts->{'order_by'}) { } 0 41 41
Condition66%2/3
$opts->{"order_keys"} and @{$opts->{"order_keys"};}
!ll&&!rl&&r
41028
MC/DC50%1/2
$opts->{"order_keys"} and @{$opts->{"order_keys"};}
$opts->{"order_keys"} @{$opts->{"order_keys"};}
Truth table66%2/3
A and B
A= $opts->{"order_keys"}B= @{$opts->{"order_keys"};}
ABresult
0X0
100
111
2486 28 @ob_keys = @{$opts->{order_keys}};
2487 }
2488 elsif ($opts->{order_by}) {
2489 0 ▶ @ob_keys = ([ $opts->{order_by}, ($opts->{order_dir} || 'ASC') ]);
Condition0%0/2
$opts->{'order_dir'} || 'ASC'
l!l
00
MC/DC0%0/1
$opts->{'order_dir'} || 'ASC'
$opts->{'order_dir'}
Truth table0%0/2
A
A= $opts->{'order_dir'}
Aresult
11
00
2490 }
2491 69 ▶ if (@ob_keys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ob_keys) 28 41 69
2492  
2493 # A result row is keyed "alias.col", so a bare ORDER BY name has to be
2494 # resolved to the alias that owns it. An unresolvable key used to
2495 # leave the rows in scan order without a word.
2496 28 my(%qual, %bare);
2497 28 for my $js (@$join_specs) {
2498 56 my $a = $js->{alias};
2499 56 for my $c (@{$alias_info{$a}{sch}{cols}}) {
2500 146 $qual{"$a.$c->{name}"} = 1;
2501 $bare{$c->{name}} = "$a.$c->{name}"
2502 146 ▶ unless exists $bare{$c->{name}};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $bare{$c->{"name"}} 141 5 146
2503 }
2504 }
2505 28 for my $k (@ob_keys) {
2506 31 ▶ next if $qual{$k->[0]};
Branch: 1 branch
BranchTrueFalseTotal
if $qual{$k->[0]} 30 1 31
2507 1 ▶ if ($bare{$k->[0]}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bare{$k->[0]}) 0 1 1
2508 0 $k->[0] = $bare{$k->[0]};
2509 0 next;
2510 }
2511 1 return $self->_err(
2512 "Unknown ORDER BY column '$k->[0]' in a JOIN query");
2513 }
2514  
2515 @cur_rows = sort {
2516 27 my $cmp = 0;
2517 133 for my $k (@ob_keys) {
2518 146 my($key, $dir) = @$k;
2519 146 my $va = $a->{$key};
2520 146 my $vb = $b->{$key};
2521 146 ▶ my $c = (defined($va) && ($va =~ /^-?\d+\.?\d*$/) &&
Branch: 3 branches
BranchTrueFalseTotal
defined $va && $va =~ /^-?\d+\.?\d*$/ && defined $vb && $vb =~ /^-?\d+\.?\d*$/ ? : 115 31 146
defined $va ? : 31 0 31
defined $vb ? : 31 0 31
Condition66%6/9
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb and $vb =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
310115
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb
!ll&&!rl&&r
310115
defined $va and $va =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
031115
MC/DC25%1/4
defined $va and $va =~ /^-?\d+\.?\d*$/ and defined $vb and $vb =~ /^-?\d+\.?\d*$/
defined $va $va =~ /^-?\d+\.?\d*$/ defined $vb $vb =~ /^-?\d+\.?\d*$/
Truth table40%2/5
A and B and C and D
A= defined $vaB= $va =~ /^-?\d+\.?\d*$/C= defined $vbD= $vb =~ /^-?\d+\.?\d*$/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
2522 defined($vb) && ($vb =~ /^-?\d+\.?\d*$/))
2523 ? ($va <=> $vb)
2524 : ((defined($va) ? $va : '') cmp (defined($vb) ? $vb : ''));
2525 146 ▶ $c = -$c if lc($dir) eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if lc $dir eq "desc" 20 126 146
2526 146 ▶ if ($c != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c != 0) 116 30 146
2527 116 $cmp = $c;
2528 116 last;
2529 }
2530 }
2531 $cmp;
2532 } @cur_rows;
2533 }
2534  
2535 # ------------------------------------------------------------------
2536 # Step 6: expand the select list and check every item
2537 # ------------------------------------------------------------------
2538 68 my @expanded;
2539 68 ▶ if ($col_specs && @$col_specs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($col_specs and @$col_specs) 58 10 68
Condition66%2/3
$col_specs and @$col_specs
!ll&&!rl&&r
01058
MC/DC50%1/2
$col_specs and @$col_specs
$col_specs @$col_specs
Truth table66%2/3
A and B
A= $col_specsB= @$col_specs
ABresult
0X0
100
111
2540  
2541 # Expand wildcards: 'alias.*' or '*'
2542 58 for my $cs (@$col_specs) {
2543 101 ▶ if ($cs eq '*') {
Branch: 2 branches
BranchTrueFalseTotal
if ($cs eq '*') { } 0 101 101
elsif ($cs =~ /^(\w+)\.\*$/) { } 2 99 101
2544  
2545 # all columns from all aliases
2546 0 for my $js (@$join_specs) {
2547 0 my $a = $js->{alias};
2548 0 my $sch = $alias_info{$a}{sch};
2549 0 for my $c (@{$sch->{cols}}) {
2550 0 push @expanded, "$a.$c->{name}";
2551 }
2552 }
2553 }
2554 elsif ($cs =~ /^(\w+)\.\*$/) {
2555 2 my $a = $1;
2556 2 ▶ my $sch = $alias_info{$a} ? $alias_info{$a}{sch} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$alias_info{$a} ? : 2 0 2
2557 2 ▶ unless ($sch) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sch) 0 2 2
2558 0 return $self->_err("Unknown table or alias '$a' in '$cs'");
2559 }
2560 2 for my $c (@{$sch->{cols}}) {
2561 6 push @expanded, "$a.$c->{name}";
2562 }
2563 }
2564 else {
2565 99 push @expanded, $cs;
2566 }
2567 }
2568  
2569 # Every item has to name a column of one of the joined tables. A
2570 # JOIN select list cannot evaluate an expression or an AS alias, and
2571 # until 1.09 such an item silently produced a row with no values in
2572 # it at all: "SELECT a.y AS nm ... JOIN", "SELECT a.x + 1 ... JOIN"
2573 # and "SELECT DISTINCT a.x ... JOIN" all returned empty rows.
2574 58 my %valid_col;
2575 58 for my $js (@$join_specs) {
2576 118 my $a = $js->{alias};
2577 118 for my $c (@{$alias_info{$a}{sch}{cols}}) {
2578 328 $valid_col{"$a.$c->{name}"} = 1;
2579 328 $valid_col{$c->{name}} = 1;
2580 }
2581 }
2582 58 for my $ck (@expanded) {
2583 105 ▶ next if $valid_col{$ck};
Branch: 1 branch
BranchTrueFalseTotal
if $valid_col{$ck} 102 3 105
2584 3 return $self->_err(
2585 "Unsupported select item '$ck' in a JOIN query; a JOIN "
2586 . "select list accepts column names, '*' and '<table>.*' "
2587 . "only (no expressions and no AS aliases)");
2588 }
2589 }
2590  
2591 # ------------------------------------------------------------------
2592 # Step 7: DISTINCT. Applied before OFFSET/LIMIT, as SQL requires, and
2593 # keyed on the select-list values only.
2594 # ------------------------------------------------------------------
2595 65 ▶ if ($opts->{distinct}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"distinct"}) 4 61 65
2596 4 ▶ my @dkeys = @expanded ? @expanded : sort keys %{ $cur_rows[0] || {} };
Branch: 2 branches
BranchTrueFalseTotal
@expanded ? : 4 0 4
$cur_rows[0] or {} 0 0 0
2597 4 my(%seen, @uniq);
2598 4 for my $r (@cur_rows) {
2599 my $k = join("\x00", map {
2600 12 ▶ defined($r->{$_}) ? $r->{$_} : "\x01"
Branch: 1 branch
BranchTrueFalseTotal
defined $r->{$_} ? : 15 0 15
2601 } @dkeys);
2602 12 ▶ push @uniq, $r unless $seen{$k}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$k}++ 7 5 12
2603 }
2604 4 @cur_rows = @uniq;
2605 }
2606  
2607 # ------------------------------------------------------------------
2608 # Step 8: OFFSET / LIMIT
2609 # ------------------------------------------------------------------
2610 65 ▶ my $offset = ($opts->{offset} || 0);
Condition100%2/2
$opts->{'offset'} || 0
l!l
164
MC/DC100%1/1
$opts->{'offset'} || 0
$opts->{'offset'}
Truth table100%2/2
A
A= $opts->{'offset'}
Aresult
11
00
2611 65 ▶ @cur_rows = splice(@cur_rows, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 1 64 65
2612 65 ▶ if (defined $opts->{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts->{"limit"}) 3 62 65
2613 3 my $last = $opts->{limit} - 1;
2614 3 ▶ $last = $#cur_rows if $last > $#cur_rows;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $#cur_rows 0 3 3
2615 3 @cur_rows = @cur_rows[0..$last];
2616 }
2617  
2618 # ------------------------------------------------------------------
2619 # Step 9: column projection
2620 # ------------------------------------------------------------------
2621 65 ▶ if (@expanded) {
Branch: 1 branch
BranchTrueFalseTotal
if (@expanded) 55 10 65
2622 55 my @proj_rows;
2623 55 for my $r (@cur_rows) {
2624 165 my %p;
2625 165 for my $ck (@expanded) {
2626  
2627 # Try qualified name first, then bare name
2628 312 ▶ if (exists $r->{$ck}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $r->{$ck}) { } 312 0 312
2629 312 $p{$ck} = $r->{$ck};
2630 }
2631 else {
2632  
2633 # bare name: find first matching qualified key
2634 0 for my $k (keys %$r) {
2635 0 ▶ if (($k =~ /\.\Q$ck\E$/) || ($k eq $ck)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /\.\Q$ck\E$/ or $k eq $ck) 0 0 0
Condition0%0/3
$k =~ /\.\Q$ck\E$/ or $k eq $ck
l!l&&r!l&&!r
000
MC/DC0%0/2
$k =~ /\.\Q$ck\E$/ or $k eq $ck
$k =~ /\.\Q$ck\E$/ $k eq $ck
Truth table0%0/3
A or B
A= $k =~ /\.\Q$ck\E$/B= $k eq $ck
ABresult
1X1
011
000
2636 0 $p{$ck} = $r->{$k};
2637 0 last;
2638 }
2639 }
2640 }
2641 }
2642 165 push @proj_rows, { %p };
2643 }
2644 55 return [ @proj_rows ];
2645 }
2646  
2647 10 return [ @cur_rows ];
2648 }
2649  
2650 # Load all active rows from a table, qualifying each column as "alias.col"
2651 sub _scan_table_all {
2652 144 ▶ my($self, $table, $alias) = @_;
Subroutine _scan_table_all: called CC=7 SCAR=19.8
2653 144 ▶ my $sch = $self->_load_schema($table) or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return [] 0 144 144
2654 144 my $dat = $self->_file($table, 'dat');
2655 144 my $recsize = $sch->{recsize};
2656 144 my @rows;
2657  
2658 144 local *FH;
2659 144 ▶ open(FH, "< $dat") or do { $errstr = "Cannot open dat '$dat': $!"; return []; };
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or do { $DB::Handy::errstr = "Cannot open dat '${dat}': $!"; return [] } 0 144 144
2660 144 binmode FH;
2661 144 _lock_sh(\*FH);
2662 144 while (1) {
2663 716 my $raw = '';
2664 716 my $n = read(FH, $raw, $recsize);
2665 716 ▶ last unless defined($n) && ($n == $recsize);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $recsize 144 572 716
Condition66%2/3
defined $n and $n == $recsize
!ll&&!rl&&r
0144572
MC/DC50%1/2
defined $n and $n == $recsize
defined $n $n == $recsize
Truth table66%2/3
A and B
A= defined $nB= $n == $recsize
ABresult
0X0
100
111
2666 572 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 572 572
2667 572 my $raw_row = $self->_unpack_record($sch, $raw);
2668  
2669 # Qualify column names with alias
2670 572 my %qrow;
2671 572 for my $col (@{$sch->{cols}}) {
2672 1725 $qrow{"$alias.$col->{name}"} = $raw_row->{$col->{name}};
2673 }
2674 572 push @rows, { %qrow };
2675 }
2676 144 _unlock(\*FH);
2677 144 close FH;
2678 144 return [ @rows ];
2679 }
2680  
2681 # Build a row of NULLs for the given alias (for outer joins)
2682 sub _make_null_row {
2683 13 ▶ my($alias, $sch) = @_;
Subroutine _make_null_row: called CC=2 SCAR=6.9
2684 13 my %row;
2685 13 for my $col (@{$sch->{cols}}) {
2686 37 $row{"$alias.$col->{name}"} = undef;
2687 }
2688 13 return %row;
2689 }
2690  
2691 # Split "alias.col" into (alias, col); if no dot, return (undef, col)
2692 sub _split_qualified {
2693 173 ▶ my($qname) = @_;
Subroutine _split_qualified: called CC=2 SCAR=6.9
2694 173 ▶ if ($qname =~ /^(\w+)\.(\w+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($qname =~ /^(\w+)\.(\w+)$/) 170 3 173
2695 170 return ($1, $2);
2696 }
2697 3 return (undef, $qname);
2698 }
2699  
2700 # Check if a pair of rows satisfies the ON equality condition
2701 sub _join_row_matches {
2702 0 ▶ my($lr, $rr, $la, $lc, $ra, $rc) = @_;
Subroutine _join_row_matches: not called CC=9 SCAR=45.0
2703 0 ▶ my $lv = defined($la) ? $lr->{"$la.$lc"} : $lr->{$lc};
Branch: 1 branch
BranchTrueFalseTotal
defined $la ? : 0 0 0
2704 0 ▶ my $rv = defined($ra) ? $rr->{"$ra.$rc"} : $rr->{$rc};
Branch: 1 branch
BranchTrueFalseTotal
defined $ra ? : 0 0 0
2705 0 ▶ return 0 unless defined($lv) && defined($rv);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv and defined $rv 0 0 0
Condition0%0/3
defined $lv and defined $rv
!ll&&!rl&&r
000
MC/DC0%0/2
defined $lv and defined $rv
defined $lv defined $rv
Truth table0%0/3
A and B
A= defined $lvB= defined $rv
ABresult
0X0
100
111
2706  
2707 # numeric compare if both look numeric
2708 0 ▶ if (($lv =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lv =~ /^-?\d+\.?\d*$/ and $rv =~ /^-?\d+\.?\d*$/) 0 0 0
Condition0%0/3
$lv =~ /^-?\d+\.?\d*$/ and $rv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
000
MC/DC0%0/2
$lv =~ /^-?\d+\.?\d*$/ and $rv =~ /^-?\d+\.?\d*$/
$lv =~ /^-?\d+\.?\d*$/ $rv =~ /^-?\d+\.?\d*$/
Truth table0%0/3
A and B
A= $lv =~ /^-?\d+\.?\d*$/B= $rv =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
2709 0 ▶ return (($lv == $rv) ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$lv == $rv ? : 0 0 0
2710 }
2711 0 ▶ return (($lv eq $rv) ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$lv eq $rv ? : 0 0 0
2712 }
2713  
2714 ###############################################################################
2715 # JOIN WHERE compiler
2716 # Conditions from the WHERE clause after a JOIN may reference qualified
2717 # columns (alias.col) or bare column names.
2718 # Condition hashref keys:
2719 # lhs_alias, lhs_col -- left-hand side
2720 # op -- = != <> < > <= >= LIKE
2721 # rhs_alias, rhs_col -- right-hand side (column comparison) OR
2722 # val -- literal value
2723 ###############################################################################
2724 sub _compile_join_where {
2725 23 ▶ my($conds) = @_;
Subroutine _compile_join_where: called CC=3 SCAR=12.4
2726 23 ▶ return sub { 1 } unless $conds && @$conds;
Subroutine __ANON__: not called CC=1 SCAR=1.7
Branch: 1 branch
BranchTrueFalseTotal
unless $conds and @$conds 0 23 23
Condition33%1/3
$conds and @$conds
!ll&&!rl&&r
0023
MC/DC0%0/2
$conds and @$conds
$conds @$conds
Truth table33%1/3
A and B
A= $condsB= @$conds
ABresult
0X0
100
111
2727 return sub {
2728 115 ▶ my($row) = @_;
Subroutine __ANON__: called CC=55 SCAR=53.1
2729 115 for my $c (@$conds) {
2730  
2731 # Resolve left-hand value
2732 131 my $lv;
2733 131 ▶ if (defined $c->{lhs_alias}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $c->{'lhs_alias'}) { } 131 0 131
2734 131 $lv = $row->{"$c->{lhs_alias}.$c->{lhs_col}"};
2735 }
2736 else {
2737  
2738 # bare name: search qualified keys
2739 0 for my $k (keys %$row) {
2740 0 ▶ if (($k =~ /\.\Q$c->{lhs_col}\E$/) || ($k eq $c->{lhs_col})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /\.\Q$c->{"lhs_col"}\E$/ or $k eq $c->{"lhs_col"}) 0 0 0
Condition0%0/3
$k =~ /\.\Q$c->{"lhs_col"}\E$/ or $k eq $c->{"lhs_col"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$k =~ /\.\Q$c->{"lhs_col"}\E$/ or $k eq $c->{"lhs_col"}
$k =~ /\.\Q$c->{"lhs_col"}\E$/ $k eq $c->{"lhs_col"}
Truth table0%0/3
A or B
A= $k =~ /\.\Q$c->{"lhs_col"}\E$/B= $k eq $c->{"lhs_col"}
ABresult
1X1
011
000
2741 0 $lv = $row->{$k};
2742 0 last;
2743 }
2744 }
2745 }
2746 # IS [NOT] NULL is decided before the coercion below, and uses
2747 # the same rule as the single-table engine: a NULL is either an
2748 # undefined value (a NULL-filled outer-join row) or the empty
2749 # string (the on-disk representation).
2750 131 ▶ if ($c->{op} eq 'IS_NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->{"op"} eq "IS_NULL") 4 127 131
2751 4 ▶ return 0 if defined($lv) && ($lv ne '');
Branch: 1 branch
BranchTrueFalseTotal
if defined $lv and $lv ne "" 3 1 4
Condition66%2/3
defined $lv and $lv ne ""
!ll&&!rl&&r
103
MC/DC50%1/2
defined $lv and $lv ne ""
defined $lv $lv ne ""
Truth table66%2/3
A and B
A= defined $lvB= $lv ne ""
ABresult
0X0
100
111
2752 1 next;
2753 }
2754 127 ▶ if ($c->{op} eq 'IS_NOT_NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->{"op"} eq "IS_NOT_NULL") 4 123 127
2755 4 ▶ return 0 unless defined($lv) && ($lv ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv and $lv ne "" 1 3 4
Condition66%2/3
defined $lv and $lv ne ""
!ll&&!rl&&r
103
MC/DC50%1/2
defined $lv and $lv ne ""
defined $lv $lv ne ""
Truth table66%2/3
A and B
A= defined $lvB= $lv ne ""
ABresult
0X0
100
111
2756 3 next;
2757 }
2758  
2759 123 ▶ $lv = '' unless defined $lv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv 1 122 123
2760  
2761 # Resolve right-hand value (literal or column)
2762 123 my $rv;
2763 123 ▶ if (defined $c->{rhs_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $c->{'rhs_col'}) { } 0 123 123
2764 0 ▶ if (defined $c->{rhs_alias}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $c->{'rhs_alias'}) { } 0 0 0
2765 0 $rv = $row->{"$c->{rhs_alias}.$c->{rhs_col}"};
2766 }
2767 else {
2768 0 for my $k (keys %$row) {
2769 0 ▶ if (($k =~ /\.\Q$c->{rhs_col}\E$/) || ($k eq $c->{rhs_col})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k =~ /\.\Q$c->{"rhs_col"}\E$/ or $k eq $c->{"rhs_col"}) 0 0 0
Condition0%0/3
$k =~ /\.\Q$c->{"rhs_col"}\E$/ or $k eq $c->{"rhs_col"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$k =~ /\.\Q$c->{"rhs_col"}\E$/ or $k eq $c->{"rhs_col"}
$k =~ /\.\Q$c->{"rhs_col"}\E$/ $k eq $c->{"rhs_col"}
Truth table0%0/3
A or B
A= $k =~ /\.\Q$c->{"rhs_col"}\E$/B= $k eq $c->{"rhs_col"}
ABresult
1X1
011
000
2770 0 $rv = $row->{$k};
2771 0 last;
2772 }
2773 }
2774 }
2775 }
2776 else {
2777 123 $rv = $c->{val};
2778 }
2779 123 ▶ $rv = '' unless defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 8 115 123
2780  
2781 123 my $op = $c->{op};
2782  
2783 # IN / NOT IN
2784 123 ▶ if (($op eq 'IN') || ($op eq 'NOT_IN')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IN" or $op eq "NOT_IN") 8 115 123
Condition66%2/3
$op eq "IN" or $op eq "NOT_IN"
l!l&&r!l&&!r
80115
MC/DC50%1/2
$op eq "IN" or $op eq "NOT_IN"
$op eq "IN" $op eq "NOT_IN"
Truth table66%2/3
A or B
A= $op eq "IN"B= $op eq "NOT_IN"
ABresult
1X1
011
000
2785 8 my $lhs_val = $lv;
2786 8 my $found = 0;
2787 8 my $has_null = 0;
2788 8 for my $cv (@{$c->{vals}}) {
2789 8 ▶ unless (defined $cv) { $has_null = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cv) 0 8 8
2790 8 ▶ my $num2 = (($lhs_val =~ /^-?\d+\.?\d*$/) && ($cv =~ /^-?\d+\.?\d*$/));
Condition33%1/3
$lhs_val =~ /^-?\d+\.?\d*$/ && $cv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
008
MC/DC0%0/2
$lhs_val =~ /^-?\d+\.?\d*$/ && $cv =~ /^-?\d+\.?\d*$/
$lhs_val =~ /^-?\d+\.?\d*$/ $cv =~ /^-?\d+\.?\d*$/
Truth table33%1/3
A && B
A= $lhs_val =~ /^-?\d+\.?\d*$/B= $cv =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
2791 8 ▶ if ($num2 ? ($lhs_val == $cv) : ($lhs_val eq $cv)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($num2 ? $lhs_val == $cv : $lhs_val eq $cv) 4 4 8
$num2 ? : 8 0 8
2792 4 $found = 1;
2793 4 last;
2794 }
2795 }
2796 8 ▶ return 0 if $found && ($op eq 'NOT_IN');
Branch: 1 branch
BranchTrueFalseTotal
if $found and $op eq "NOT_IN" 0 8 8
Condition66%2/3
$found and $op eq "NOT_IN"
!ll&&!rl&&r
440
MC/DC0%0/2
$found and $op eq "NOT_IN"
$found $op eq "NOT_IN"
Truth table66%2/3
A and B
A= $foundB= $op eq "NOT_IN"
ABresult
0X0
100
111
2797 8 ▶ return 0 if !$found && ($op eq 'IN');
Branch: 1 branch
BranchTrueFalseTotal
if not $found and $op eq "IN" 4 4 8
Condition66%2/3
not $found and $op eq "IN"
!ll&&!rl&&r
404
MC/DC50%1/2
not $found and $op eq "IN"
not $found $op eq "IN"
Truth table66%2/3
not(A) and B
A= not $foundB= $op eq "IN"
ABresult
0X0
100
111
2798 # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN
2799 # when the row value was not found in the non-NULL values.
2800 4 ▶ return 0 if $has_null && !$found && ($op eq 'NOT_IN');
Branch: 1 branch
BranchTrueFalseTotal
if $has_null and not $found and $op eq "NOT_IN" 0 4 4
Condition33%2/6
$has_null and not $found and $op eq "NOT_IN"
!ll&&!rl&&r
400
$has_null and not $found
!ll&&!rl&&r
400
MC/DC0%0/3
$has_null and not $found and $op eq "NOT_IN"
$has_null not $found $op eq "NOT_IN"
Truth table25%1/4
A and not(B) and C
A= $has_nullB= not $foundC= $op eq "NOT_IN"
ABCresult
0XX0
10X0
1100
1111
2801 4 next;
2802 }
2803  
2804 115 ▶ my $num = (($lv =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/));
Condition66%2/3
$lv =~ /^-?\d+\.?\d*$/ && $rv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
44071
MC/DC50%1/2
$lv =~ /^-?\d+\.?\d*$/ && $rv =~ /^-?\d+\.?\d*$/
$lv =~ /^-?\d+\.?\d*$/ $rv =~ /^-?\d+\.?\d*$/
Truth table66%2/3
A && B
A= $lv =~ /^-?\d+\.?\d*$/B= $rv =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
2805  
2806 115 ▶ if ($op eq '=') {
Branch: 7 branches
BranchTrueFalseTotal
if ($op eq '=') { } 87 28 115
elsif ($op eq '!=' or $op eq '<>') { } 0 28 28
elsif ($op eq '<') { } 0 28 28
elsif ($op eq '>') { } 12 16 28
elsif ($op eq '<=') { } 4 12 16
elsif ($op eq '>=') { } 9 3 12
elsif ($op eq 'LIKE') { } 3 0 3
2807 87 ▶ return 0 unless $num ? ($lv == $rv) : ($lv eq $rv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lv == $rv : $lv eq $rv 64 23 87
$num ? : 46 41 87
2808 }
2809 ▶ elsif (($op eq '!=') || ($op eq '<>')) {
Condition33%1/3
$op eq "!=" or $op eq "<>"
l!l&&r!l&&!r
0028
MC/DC0%0/2
$op eq "!=" or $op eq "<>"
$op eq "!=" $op eq "<>"
Truth table33%1/3
A or B
A= $op eq "!="B= $op eq "<>"
ABresult
1X1
011
000
2810 0 ▶ return 0 unless $num ? ($lv != $rv) : ($lv ne $rv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lv != $rv : $lv ne $rv 0 0 0
$num ? : 0 0 0
2811 }
2812 elsif ($op eq '<') {
2813 0 ▶ return 0 unless $num ? ($lv < $rv) : ($lv lt $rv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lv < $rv : $lv lt $rv 0 0 0
$num ? : 0 0 0
2814 }
2815 elsif ($op eq '>') {
2816 12 ▶ return 0 unless $num ? ($lv > $rv) : ($lv gt $rv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lv > $rv : $lv gt $rv 4 8 12
$num ? : 12 0 12
2817 }
2818 elsif ($op eq '<=') {
2819 4 ▶ return 0 unless $num ? ($lv <= $rv) : ($lv le $rv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lv <= $rv : $lv le $rv 0 4 4
$num ? : 4 0 4
2820 }
2821 elsif ($op eq '>=') {
2822 9 ▶ return 0 unless $num ? ($lv >= $rv) : ($lv ge $rv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $lv >= $rv : $lv ge $rv 3 6 9
$num ? : 9 0 9
2823 }
2824 elsif ($op eq 'LIKE') {
2825 3 my $p = _like_to_re($rv);
2826 3 ▶ return 0 unless $lv =~ /^$p$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $lv =~ /^$p$/i 1 2 3
2827 }
2828 }
2829 35 return 1;
2830 23 };
2831 }
2832  
2833 ###############################################################################
2834 # JOIN SQL parser
2835 # Handles:
2836 # SELECT col_list
2837 # FROM t1 [AS a1]
2838 # [INNER|LEFT [OUTER]|RIGHT [OUTER]|CROSS] JOIN t2 [AS a2] ON a1.c = a2.c
2839 # [ JOIN t3 [AS a3] ON ... ]
2840 # [WHERE ...]
2841 # [ORDER BY alias.col [ASC|DESC]]
2842 # [LIMIT n] [OFFSET m]
2843 ###############################################################################
2844 # A table alias in a FROM clause is optional, so the token that follows a
2845 # table name has to be checked before it is accepted as one. Without this
2846 # guard "FROM a LEFT JOIN b ON a.id = b.bid" read LEFT as the alias of a,
2847 # which turned the LEFT JOIN into a plain JOIN and left every "a.col"
2848 # reference unresolvable, and "JOIN b ON ..." read ON as the alias of b,
2849 # which dropped the join condition and produced a silent cross join.
2850 sub _is_join_keyword {
2851 89 ▶ my($word) = @_;
Subroutine _is_join_keyword: called CC=3 SCAR=11.1
2852 89 ▶ return 0 unless defined $word;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $word 0 89 89
2853 89 ▶ return $word =~ /^(?:INNER|LEFT|RIGHT|FULL|OUTER|CROSS|NATURAL|JOIN|ON|USING|WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|UNION)$/i ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$word =~ /^(?:INNER|LEFT|RIGHT|FULL|OUTER|CROSS|NATURAL|JOIN|ON|USING|WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|UNION)$/i ? : 56 33 89
2854 }
2855  
2856 sub _parse_join_sql {
2857 89 ▶ my($sql) = @_;
Subroutine _parse_join_sql: called CC=38 SCAR=36.8
2858 # sql has been normalised: single spaces, trimmed
2859  
2860 # ---------------------------------------------------------------
2861 # 1. Extract SELECT column list and the FROM...rest portion
2862 # ---------------------------------------------------------------
2863 89 ▶ return undef unless $sql =~ /^SELECT\s+(.+?)\s+FROM\s+(.+)$/si;
Branch: 1 branch
BranchTrueFalseTotal
unless $sql =~ /^SELECT\s+(.+?)\s+FROM\s+(.+)$/is 0 89 89
2864 89 my($sel_str, $from_rest) = ($1, $2);
2865  
2866 # ---------------------------------------------------------------
2867 # 2. Strip trailing ORDER BY / LIMIT / OFFSET
2868 # (strip right-to-left to avoid greedy issues)
2869 # ---------------------------------------------------------------
2870 89 my %opts;
2871  
2872 # Strip suffixes right-to-left: OFFSET, LIMIT, ORDER BY
2873 # (ORDER BY may precede LIMIT/OFFSET, so strip LIMIT+OFFSET first)
2874 89 ▶ if ($from_rest =~ s/\s+OFFSET\s+(\d+)\s*$//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from_rest =~ s/\s+OFFSET\s+(\d+)\s*$//i) 1 88 89
2875 1 $opts{offset} = $1;
2876 }
2877 89 ▶ if ($from_rest =~ s/\s+LIMIT\s+(\d+)\s*$//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from_rest =~ s/\s+LIMIT\s+(\d+)\s*$//i) 3 86 89
2878 3 $opts{limit} = $1;
2879 }
2880 # ORDER BY accepts a comma-separated key list. Before 1.09 only a single
2881 # key was matched here, so "ORDER BY a.y, a.x DESC" failed to match, was
2882 # swallowed by the WHERE strip below and then dropped by the condition
2883 # parser -- the rows came back in scan order with no error.
2884 89 ▶ if ($from_rest =~ s/\s+ORDER\s+BY\s+([\w.]+(?:\s+(?:ASC|DESC))?(?:\s*,\s*[\w.]+(?:\s+(?:ASC|DESC))?)*)\s*$//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from_rest =~ s/\s+ORDER\s+BY\s+([\w.]+(?:\s+(?:ASC|DESC))?(?:\s*,\s*[\w.]+(?:\s+(?:ASC|DESC))?)*)\s*$//i) 31 58 89
2885 31 my $ob_str = $1;
2886 31 my @ob_keys;
2887 31 for my $k (split(/\s*,\s*/, $ob_str)) {
2888 34 $k =~ s/^\s+|\s+$//g;
2889 34 my $dir = 'ASC';
2890 34 ▶ $dir = uc($1) if $k =~ s/\s+(ASC|DESC)\s*$//i;
Branch: 1 branch
BranchTrueFalseTotal
if $k =~ s/\s+(ASC|DESC)\s*$//i 9 25 34
2891 34 push @ob_keys, [ $k, $dir ];
2892 }
2893 31 ▶ if (@ob_keys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ob_keys) 31 0 31
2894 31 $opts{order_keys} = [ @ob_keys ];
2895 31 $opts{order_by} = $ob_keys[0][0];
2896 31 $opts{order_dir} = $ob_keys[0][1];
2897 }
2898 }
2899  
2900 # ---------------------------------------------------------------
2901 # 3. Extract WHERE clause (everything after WHERE keyword,
2902 # which must come after all JOIN...ON clauses)
2903 # ---------------------------------------------------------------
2904 89 my $where_str = '';
2905  
2906 # WHERE must appear after the last ON clause; we find the last WHERE
2907 89 ▶ if ($from_rest =~ s/\s+WHERE\s+(.+)$//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from_rest =~ s/\s+WHERE\s+(.+)$//i) 26 63 89
2908 26 $where_str = $1;
2909 26 $where_str =~ s/^\s+|\s+$//g;
2910 }
2911  
2912 # ---------------------------------------------------------------
2913 # 4. Parse the FROM clause using iterative regex matching
2914 # Grammar: table [AS alias]
2915 # { join_type JOIN table [AS alias] ON qcol = qcol }*
2916 # ---------------------------------------------------------------
2917 89 my @join_specs;
2918  
2919 # Parse the driving (first) table
2920 89 my $fr = $from_rest;
2921 89 $fr =~ s/^\s+//;
2922 89 ▶ unless ($fr =~ s/^(\w+)//) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fr =~ s/^(\w+)//) 0 89 89
2923 0 return undef;
2924 }
2925 89 my $first_tbl = $1;
2926 89 my $first_alias = $first_tbl;
2927 89 ▶ if ($fr =~ /^\s+(?:AS\s+)?(\w+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fr =~ /^\s+(?:AS\s+)?(\w+)/i) 89 0 89
2928 89 my $cand = $1;
2929 89 ▶ unless (_is_join_keyword($cand)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_is_join_keyword($cand)) 33 56 89
2930 33 $fr =~ s/^\s+(?:AS\s+)?\w+//i;
2931 33 $first_alias = $cand;
2932 }
2933 }
2934 89 push @join_specs, { table => $first_tbl, alias => $first_alias, type => 'FIRST' };
2935  
2936 # Iteratively match JOIN clauses.
2937 #
2938 # The join-type words, the table and its alias are matched first; the ON
2939 # expression is then taken as everything up to the start of the next JOIN
2940 # clause (or the end of the FROM text) and checked separately. Until 1.09
2941 # the ON clause was part of this pattern as an *optional* group matching
2942 # only "col = col", so every ON the pattern could not read simply failed
2943 # to participate: on_left and on_right stayed undef and join_select fell
2944 # through to its Cartesian-product branch. "ON a.x = b.k AND a.id < b.id",
2945 # "ON a.x < b.k", "ON b.k = a.x" (operands the other way round), USING,
2946 # NATURAL and FULL OUTER all returned a silent cross join instead of an
2947 # error. Anything not executable is now collected in $err.
2948 89 my $err = '';
2949 89 ▶ while ($fr =~ s/^\s+((?:(?:INNER|LEFT|RIGHT|FULL|CROSS|NATURAL|OUTER)\s+)*)JOIN\s+(\w+)(?:\s+(?:AS\s+)?((?!(?:INNER|LEFT|RIGHT|FULL|OUTER|CROSS|NATURAL|JOIN|ON|USING|WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|UNION)\b)\w+))?//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fr =~ s/^\s+((?:(?:INNER|LEFT|RIGHT|FULL|CROSS|NATURAL|OUTER)\s+)*)JOIN\s+(\w+)(?:\s+(?:AS\s+)?((?!(?:INNER|LEFT|RIGHT|FULL|OUTER|CROSS|NATURAL|JOIN|ON|USING|WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|UNION)\b)\w+))?//i) 91 89 180
2950 91 my($type_kw, $tbl, $alias) = ($1, $2, $3);
2951 91 ▶ $type_kw = '' unless defined $type_kw;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type_kw 0 91 91
2952 91 $type_kw =~ s/\s+$//;
2953 91 my $type = 'INNER';
2954 91 ▶ if ($type_kw =~ /NATURAL/i) {
Branch: 5 branches
BranchTrueFalseTotal
if ($type_kw =~ /NATURAL/i) { } 5 86 91
elsif ($type_kw =~ /FULL/i) { } 2 84 86
elsif ($type_kw =~ /CROSS/i) { } 2 82 84
elsif ($type_kw =~ /LEFT/i) { } 12 70 82
elsif ($type_kw =~ /RIGHT/i) { } 1 69 70
2955 5 ▶ $err = "NATURAL JOIN is not supported; name the join columns "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 5 0 5
2956 . "with ON <left>.<col> = <right>.<col>"
2957 unless $err ne '';
2958 }
2959 elsif ($type_kw =~ /FULL/i) {
2960 2 ▶ $err = "FULL OUTER JOIN is not supported; use LEFT JOIN or "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 2 0 2
2961 . "RIGHT JOIN, or combine the two with UNION"
2962 unless $err ne '';
2963 }
2964 elsif ($type_kw =~ /CROSS/i) {
2965 2 $type = 'CROSS';
2966 }
2967 elsif ($type_kw =~ /LEFT/i) {
2968 12 $type = 'LEFT';
2969 }
2970 elsif ($type_kw =~ /RIGHT/i) {
2971 1 $type = 'RIGHT';
2972 }
2973 91 ▶ $alias = $tbl unless defined $alias;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $alias 56 35 91
2974  
2975 # USING (col, ...) -- recognised only so that it can be rejected.
2976 91 ▶ if ($fr =~ s/^\s+USING\s*\(([^)]*)\)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fr =~ s/^\s+USING\s*\(([^)]*)\)//i) 1 90 91
2977 1 ▶ $err = "JOIN ... USING is not supported; use "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 1 0 1
2978 . "ON <left>.<col> = <right>.<col>"
2979 unless $err ne '';
2980 }
2981  
2982 # ON <expr>, up to the next JOIN clause or the end of the FROM text.
2983 91 my($on_left, $on_right);
2984 91 ▶ if ($fr =~ s/^\s+ON\s+(.*?)(?=\s+(?:(?:INNER|LEFT|RIGHT|FULL|CROSS|NATURAL|OUTER)\s+)*JOIN\b|$)//is) {
Branch: 2 branches
BranchTrueFalseTotal
if ($fr =~ s/^\s+ON\s+(.*?)(?=\s+(?:(?:INNER|LEFT|RIGHT|FULL|CROSS|NATURAL|OUTER)\s+)*JOIN\b|$)//is) { } 82 9 91
elsif ($type ne 'CROSS') { } 8 1 9
2985 82 my $on_expr = $1;
2986 82 $on_expr =~ s/^\s+|\s+$//g;
2987 82 ▶ if ($on_expr =~ /^([\w.]+)\s*=\s*([\w.]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($on_expr =~ /^([\w.]+)\s*=\s*([\w.]+)$/) { } 79 3 82
2988 79 ($on_left, $on_right) = ($1, $2);
2989 }
2990 else {
2991 3 ▶ $err = "Unsupported JOIN condition 'ON $on_expr'; a JOIN "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 3 0 3
2992 . "accepts a single equality between two columns, as in "
2993 . "ON <left>.<col> = <right>.<col>. Move any further "
2994 . "restriction into the WHERE clause"
2995 unless $err ne '';
2996 }
2997 }
2998 elsif ($type ne 'CROSS') {
2999 8 ▶ $err = "JOIN $tbl has no ON clause; add "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 2 6 8
3000 . "ON <left>.<col> = <right>.<col>, or write CROSS JOIN for "
3001 . "a deliberate Cartesian product"
3002 unless $err ne '';
3003 }
3004  
3005 91 push @join_specs, {
3006 table => $tbl,
3007 alias => $alias,
3008 type => $type,
3009 on_left => $on_left,
3010 on_right => $on_right,
3011 };
3012 }
3013  
3014 # Must have at least 2 tables to be a JOIN. A JOIN that appears only
3015 # inside a subquery lands here too, so this returns undef without an
3016 # error and lets the ordinary SELECT parser take over.
3017 89 ▶ return undef if @join_specs < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @join_specs < 2 0 89 89
3018  
3019 # Text left over in the FROM chain used to be discarded without a word.
3020 89 ▶ if (($err eq '') && ($fr =~ /\S/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err eq "" and $fr =~ /\S/) 0 89 89
Condition66%2/3
$err eq "" and $fr =~ /\S/
!ll&&!rl&&r
13760
MC/DC0%0/2
$err eq "" and $fr =~ /\S/
$err eq "" $fr =~ /\S/
Truth table66%2/3
A and B
A= $err eq ""B= $fr =~ /\S/
ABresult
0X0
100
111
3021 0 my $left = $fr;
3022 0 $left =~ s/^\s+|\s+$//g;
3023 0 $err = "Unsupported text in FROM clause: '$left'";
3024 }
3025  
3026 89 ▶ return [ undef, undef, undef, undef, $err ] if $err ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $err ne "" 13 76 89
3027  
3028 # ---------------------------------------------------------------
3029 # 5. Parse SELECT column list
3030 # ---------------------------------------------------------------
3031 76 my @col_specs;
3032  
3033 # DISTINCT used to be left glued to the first select item, which made the
3034 # item unresolvable: every row came back empty and nothing was deduplicated.
3035 76 ▶ if ($sel_str =~ s/^\s*DISTINCT\s+//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel_str =~ s/^\s*DISTINCT\s+//i) 4 72 76
3036 4 $opts{distinct} = 1;
3037 }
3038 76 ▶ if ($sel_str =~ /^\s*\*\s*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel_str =~ /^\s*\*\s*$/) { } 4 72 76
3039 4 @col_specs = (); # empty = all columns (expanded later)
3040 }
3041 else {
3042 72 for my $cs (split /\s*,\s*/, $sel_str) {
3043 122 $cs =~ s/^\s+|\s+$//g;
3044 122 push @col_specs, $cs;
3045 }
3046 }
3047  
3048 # ---------------------------------------------------------------
3049 # 6. Parse WHERE conditions
3050 # ---------------------------------------------------------------
3051 76 my @where_conds;
3052 76 ▶ if ($where_str =~ /\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($where_str =~ /\S/) 26 50 76
3053 26 my($wc, $werr) = _parse_join_conditions($where_str);
3054 26 ▶ return [ undef, undef, undef, undef, $werr ] if $werr ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $werr ne "" 3 23 26
3055 23 @where_conds = @$wc;
3056 }
3057  
3058 73 return [ [ @join_specs ], [ @col_specs ], [ @where_conds ], { %opts }, '' ];
3059 }
3060  
3061 # Parse WHERE expression containing possibly qualified column names
3062 # Returns arrayref of condition hashrefs
3063 sub _parse_join_conditions {
3064 26 ▶ my($expr) = @_;
Subroutine _parse_join_conditions: called CC=24 SCAR=33.1
3065 26 ▶ return ([], '') unless defined($expr) && ($expr =~ /\S/);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expr and $expr =~ /\S/ 0 26 26
Condition33%1/3
defined $expr and $expr =~ /\S/
!ll&&!rl&&r
0026
MC/DC0%0/2
defined $expr and $expr =~ /\S/
defined $expr $expr =~ /\S/
Truth table33%1/3
A and B
A= defined $exprB= $expr =~ /\S/
ABresult
0X0
100
111
3066 26 my @conds;
3067  
3068 # Split on AND. BETWEEN carries an AND of its own that is not a
3069 # conjunction, so a part that opened a BETWEEN is glued back together
3070 # with the part that follows it.
3071 26 my @raw = split(/\s+AND\s+/i, $expr);
3072 26 my @parts;
3073 26 ▶ while (@raw) {
Branch: 1 branch
BranchTrueFalseTotal
if (@raw) 30 26 56
3074 30 my $p = shift @raw;
3075 30 ▶ if (($p =~ /\bBETWEEN\b/i) && ($p !~ /\bBETWEEN\b.*\bAND\b/i) && @raw) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p =~ /\bBETWEEN\b/i and not $p =~ /\bBETWEEN\b.*\bAND\b/i and @raw) 2 28 30
Condition66%4/6
$p =~ /\bBETWEEN\b/i and not $p =~ /\bBETWEEN\b.*\bAND\b/i and @raw
!ll&&!rl&&r
2802
$p =~ /\bBETWEEN\b/i and not $p =~ /\bBETWEEN\b.*\bAND\b/i
!ll&&!rl&&r
2802
MC/DC33%1/3
$p =~ /\bBETWEEN\b/i and not $p =~ /\bBETWEEN\b.*\bAND\b/i and @raw
$p =~ /\bBETWEEN\b/i not $p =~ /\bBETWEEN\b.*\bAND\b/i @raw
Truth table50%2/4
A and not(B) and C
A= $p =~ /\bBETWEEN\b/iB= not $p =~ /\bBETWEEN\b.*\bAND\b/iC= @raw
ABCresult
0XX0
10X0
1100
1111
3076 2 $p .= ' AND ' . shift(@raw);
3077 }
3078 30 push @parts, $p;
3079 }
3080  
3081 26 for my $part (@parts) {
3082 30 $part =~ s/^\s+|\s+$//g;
3083 30 ▶ next unless $part =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $part =~ /\S/ 0 30 30
3084  
3085 # col IS [NOT] NULL. Without this a LEFT JOIN anti-join
3086 # ("WHERE right.col IS NULL") matched no pattern at all and was
3087 # dropped, so every joined row came back unfiltered.
3088 30 ▶ if ($part =~ /^((?:\w+\.)?\w+)\s+IS\s+(NOT\s+)?NULL$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^((?:\w+\.)?\w+)\s+IS\s+(NOT\s+)?NULL$/i) 2 28 30
3089 2 my($lhs, $neg) = ($1, $2);
3090 2 my($la, $lc) = _split_qualified($lhs);
3091 2 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 1 1 2
3092 lhs_alias => $la,
3093 lhs_col => $lc,
3094 op => ($neg ? 'IS_NOT_NULL' : 'IS_NULL'),
3095 };
3096 2 next;
3097 }
3098  
3099 # col BETWEEN lo AND hi -> col >= lo, col <= hi
3100 28 ▶ if ($part =~ /^((?:\w+\.)?\w+)\s+BETWEEN\s+(?:'([^']*)'|(-?\d+\.?\d*))\s+AND\s+(?:'([^']*)'|(-?\d+\.?\d*))$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^((?:\w+\.)?\w+)\s+BETWEEN\s+(?:'([^']*)'|(-?\d+\.?\d*))\s+AND\s+(?:'([^']*)'|(-?\d+\.?\d*))$/i) 2 26 28
3101 2 my($lhs, $lo_s, $lo_n, $hi_s, $hi_n) = ($1, $2, $3, $4, $5);
3102 2 my($la, $lc) = _split_qualified($lhs);
3103 2 ▶ my $lo = defined($lo_s) ? $lo_s : $lo_n;
Branch: 1 branch
BranchTrueFalseTotal
defined $lo_s ? : 0 2 2
3104 2 ▶ my $hi = defined($hi_s) ? $hi_s : $hi_n;
Branch: 1 branch
BranchTrueFalseTotal
defined $hi_s ? : 0 2 2
3105 2 push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>'>=', val=>$lo };
3106 2 push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>'<=', val=>$hi };
3107 2 next;
3108 }
3109  
3110 # col-vs-col: alias1.col1 OP alias2.col2
3111 26 ▶ if (($part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>)\s*((?:\w+\.)?\w+)$/i) && ($part !~ /'/)) {
Branch: 3 branches
BranchTrueFalseTotal
if ($part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>)\s*((?:\w+\.)?\w+)$/i and not $part =~ /'/) { } 14 12 26
elsif ($part =~ /^((?:\w+\.)?\w+)\s+(NOT\s+)?IN\s*\(([^)]*)\)\s*$/i) { } 1 11 12
elsif ($part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) { } 8 3 11
Condition66%2/3
$part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>)\s*((?:\w+\.)?\w+)$/i and not $part =~ /'/
!ll&&!rl&&r
12014
MC/DC50%1/2
$part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>)\s*((?:\w+\.)?\w+)$/i and not $part =~ /'/
$part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>)\s*((?:\w+\.)?\w+)$/i not $part =~ /'/
Truth table66%2/3
A and not(B)
A= $part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>)\s*((?:\w+\.)?\w+)$/iB= not $part =~ /'/
ABresult
0X0
100
111
3112 14 my($lhs, $op, $rhs) = ($1, uc($2), $3);
3113  
3114 # Heuristic: if rhs looks like a number, treat as literal
3115 14 ▶ if ($rhs =~ /^-?\d+\.?\d*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rhs =~ /^-?\d+\.?\d*$/) { } 14 0 14
3116 14 my($la, $lc) = _split_qualified($lhs);
3117 14 push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>$op, val=>$rhs };
3118 }
3119 else {
3120 0 my($la, $lc) = _split_qualified($lhs);
3121 0 my($ra, $rc) = _split_qualified($rhs);
3122 0 push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>$op, rhs_alias=>$ra, rhs_col=>$rc };
3123 }
3124 # col [NOT] IN (val, val, ...)
3125 }
3126 elsif ($part =~ /^((?:\w+\.)?\w+)\s+(NOT\s+)?IN\s*\(([^)]*)\)\s*$/i) {
3127 1 my($lhs, $neg, $list_str) = ($1, $2, $3);
3128 1 my($la, $lc) = _split_qualified($lhs);
3129 1 my @vals;
3130 1 my $ls = $list_str;
3131 1 ▶ while ($ls =~ s/^\s*(?:'([^']*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ls =~ s/^\s*(?:'([^']*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) 1 1 2
3132 1 my($sv, $nv, $nl) = ($1, $2, $3);
3133 1 ▶ push @vals, defined($nl) ? undef : (defined($sv) ? $sv : $nv);
Branch: 2 branches
BranchTrueFalseTotal
defined $nl ? : 0 1 1
defined $sv ? : 0 1 1
3134 }
3135 1 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 0 1 1
3136 lhs_alias => $la,
3137 lhs_col => $lc,
3138 op => ($neg ? 'NOT_IN' : 'IN'),
3139 vals => [ @vals ],
3140 };
3141 # col-vs-literal
3142 }
3143 elsif ($part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) {
3144 8 my($lhs, $op, $sv, $nv) = ($1, uc($2), $3, $4);
3145 8 my($la, $lc) = _split_qualified($lhs);
3146 8 ▶ push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>$op, val=>defined($sv) ? $sv : $nv };
Branch: 1 branch
BranchTrueFalseTotal
defined $sv ? : 8 0 8
3147 }
3148 else {
3149  
3150 # Until 1.09 a part that matched none of the patterns above was
3151 # dropped in silence, so "WHERE a.x = 1 OR a.x = 2", "WHERE NOT
3152 # a.x = 1" and "WHERE (a.x = 1)" returned the whole join result
3153 # as though no WHERE had been written at all.
3154 3 return ([], "Unsupported WHERE condition in a JOIN query: "
3155 . "'$part'. A JOIN accepts AND-separated comparisons "
3156 . "between a column and a column or literal, IN, "
3157 . "NOT IN, LIKE, BETWEEN and IS [NOT] NULL; OR, NOT "
3158 . "and parentheses are not supported here");
3159 }
3160 }
3161 23 return ([ @conds ], '');
3162 }
3163  
3164 ###############################################################################
3165 # General helpers
3166 ###############################################################################
3167 sub _err {
3168 105 ▶ my($self, $msg) = @_;
Subroutine _err: called CC=1 SCAR=0.0
3169 105 $errstr = $msg;
3170 105 return undef;
3171 }
3172  
3173 # Identifier validation.
3174 #
3175 # Database, table and index names are used directly as path components by
3176 # _db_path(), _file() and _idx_file(). Without a check, a caller of the
3177 # low-level API could escape base_dir entirely -- drop_database('../x')
3178 # would hand '../x' to File::Path::rmtree() and delete a directory tree
3179 # outside the database. The SQL layer already restricts every identifier
3180 # to \w+, so this only holds the documented Perl-level methods to the
3181 # same rule; no name that SQL can produce is rejected here.
3182 sub _valid_name {
3183 3532 ▶ my($name) = @_;
Subroutine _valid_name: called CC=3 SCAR=11.0
3184 3532 ▶ return 0 unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 3532 3532
3185 3532 ▶ return 0 unless $name =~ /^\w+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /^\w+\z/ 61 3471 3532
3186 3471 return 1;
3187 }
3188  
3189 # Render a name for an error message without interpolating undef.
3190 sub _shown_name {
3191 61 ▶ my($name) = @_;
Subroutine _shown_name: called CC=2 SCAR=7.2
3192 61 ▶ return defined($name) ? $name : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 61 0 61
3193 }
3194  
3195 sub _db_path {
3196 111 ▶ my($self, $db) = @_;
Subroutine _db_path: called CC=1 SCAR=0.0
3197 111 File::Spec->catdir($self->{base_dir}, $db);
3198 }
3199  
3200 sub _file {
3201 3419 ▶ my($self, $table, $ext) = @_;
Subroutine _file: called CC=1 SCAR=0.0
3202 3419 File::Spec->catfile($self->{base_dir}, $self->{db_name}, "$table.$ext");
3203 }
3204  
3205 sub _load_schema {
3206 3157 ▶ my($self, $table) = @_;
Subroutine _load_schema: called CC=16 SCAR=28.3
3207 3157 ▶ unless (_valid_name($table)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_valid_name($table)) 5 3152 3157
3208 5 my $bad = _shown_name($table);
3209 5 $errstr = "Invalid table name '$bad'";
3210 5 return undef;
3211 }
3212 3152 ▶ return $self->{_tables}{$table} if $self->{_tables}{$table};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_tables"}{$table} 2967 185 3152
3213 185 my $sch_file = $self->_file($table, 'sch');
3214 185 ▶ unless (-f $sch_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $sch_file) 9 176 185
3215 9 $errstr = "Table '$table' does not exist";
3216 9 return undef;
3217 }
3218 176 local *FH;
3219 176 ▶ open(FH, "< $sch_file") or do { $errstr = "Cannot read schema: $!"; return undef; };
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $sch_file" or do { $DB::Handy::errstr = "Cannot read schema: $!"; return undef } 0 176 176
3220 176 my($sch, @cols, %indexes);
3221 176 $sch = {};
3222 176 $sch->{notnull} = {};
3223 176 $sch->{defaults} = {};
3224 176 $sch->{checks} = {};
3225 176 $sch->{pk} = undef;
3226 176 local $_;
3227 176 ▶ while (<FH>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline FH)) 773 176 949
3228 773 chomp;
3229 773 ▶ if (/^RECSIZE=(\d+)/) {
Branch: 7 branches
BranchTrueFalseTotal
if (/^RECSIZE=(\d+)/) { } 176 597 773
elsif (/^COL=(\w+):(\w+):(\d+)(?::(\d+))?/) { } 406 191 597
elsif (/^NOTNULL=(\w+)/) { } 1 190 191
elsif (/^DEFAULT=(\w+):(.+)/) { } 0 190 190
elsif (/^CHECK=(\w+):(.+)/) { } 1 189 190
elsif (/^PK=(\w+)/) { } 0 189 189
elsif (/^IDX=(\w+):(\w+):([01])/) { } 13 176 189
3230 176 $sch->{recsize} = $1;
3231 }
3232 elsif (/^COL=(\w+):(\w+):(\d+)(?::(\d+))?/) {
3233 # 4th field is decl (declared size); absent in old schema files
3234 406 ▶ push @cols, { name=>$1, type=>$2, size=>$3,
Branch: 1 branch
BranchTrueFalseTotal
defined $4 ? : 406 0 406
3235 decl=>(defined($4) ? $4+0 : $3+0) };
3236 }
3237 elsif (/^NOTNULL=(\w+)/) {
3238 1 $sch->{notnull}{$1} = 1;
3239 }
3240 elsif (/^DEFAULT=(\w+):(.+)/) {
3241 0 $sch->{defaults}{$1} = $2;
3242 }
3243 elsif (/^CHECK=(\w+):(.+)/) {
3244 1 $sch->{checks}{$1} = $2;
3245 }
3246 elsif (/^PK=(\w+)/) {
3247 0 $sch->{pk} = $1;
3248 0 $sch->{notnull}{$1} = 1;
3249 }
3250 elsif (/^IDX=(\w+):(\w+):([01])/) {
3251 13 my($iname, $icol, $iuniq) = ($1, $2, $3);
3252 13 my($cdef) = grep { $_->{name} eq $icol } @cols;
3253 $indexes{$iname} = {
3254 name => $iname,
3255 col => $icol,
3256 unique => $iuniq+0,
3257 keysize => ($cdef ? $cdef->{size} : 0),
3258 13 ▶ coltype => ($cdef ? $cdef->{type} : 'VARCHAR'),
Branch: 2 branches
BranchTrueFalseTotal
$cdef ? : 13 0 13
$cdef ? : 13 0 13
3259 };
3260 }
3261 }
3262 176 close FH;
3263 176 $sch->{cols} = [ @cols ];
3264 176 $sch->{indexes} = { %indexes };
3265 176 $self->{_tables}{$table} = $sch;
3266 176 return $sch;
3267 }
3268  
3269 sub _rewrite_schema {
3270 21 ▶ my($self, $table, $sch) = @_;
Subroutine _rewrite_schema: called CC=23 SCAR=41.0
3271 21 my $sch_file = $self->_file($table, 'sch');
3272 21 local *FH;
3273 21 ▶ open(FH, "> $sch_file") or return $self->_err("Cannot rewrite schema: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "> $sch_file" or return $self->_err("Cannot rewrite schema: $!") 0 21 21
3274 21 my $ok = print FH "VERSION=1\n";
3275 21 ▶ $ok &&= print FH "RECSIZE=$sch->{recsize}\n";
Condition33%1/3
$ok &&= print(FH qq[RECSIZE=$sch->{"recsize"}\n])
!ll&&!rl&&r
0021
MC/DC0%0/2
$ok &&= print(FH qq[RECSIZE=$sch->{"recsize"}\n])
$ok print(FH qq[RECSIZE=$sch->{"recsize"}\n])
Truth table33%1/3
A &&= B
A= $okB= print(FH qq[RECSIZE=$sch->{"recsize"}\n])
ABresult
0X0
100
111
3276 21 for my $c (@{$sch->{cols}}) {
3277 $ok &&= print FH "COL=$c->{name}:$c->{type}:$c->{size}:"
3278 56 ▶ . (defined($c->{decl}) ? $c->{decl} : $c->{size}) . "\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $c->{'decl'} ? : 56 0 56
Condition33%1/3
$ok &&= print(FH qq[COL=$c->{"name"}:$c->{"type"}:$c->{"size"}:] . (defined $c->{"decl"} ? $c->{"decl"} : $c->{"size"}) . "\n")
!ll&&!rl&&r
0056
MC/DC0%0/2
$ok &&= print(FH qq[COL=$c->{"name"}:$c->{"type"}:$c->{"size"}:] . (defined $c->{"decl"} ? $c->{"decl"} : $c->{"size"}) . "\n")
$ok print(FH qq[COL=$c->{"name"}:$c->{"type"}:$c->{"size"}:] . (defined $c->{"decl"} ? $c->{"decl"} : $c->{"size"}) . "\n")
Truth table33%1/3
A &&= B
A= $okB= print(FH qq[COL=$c->{"name"}:$c->{"type"}:$c->{"size"}:] . (defined $c->{"decl"} ? $c->{"decl"} : $c->{"size"}) . "\n")
ABresult
0X0
100
111
3279 }
3280 21 for my $ix (values %{$sch->{indexes}}) {
3281 2 ▶ $ok &&= print FH "IDX=$ix->{name}:$ix->{col}:$ix->{unique}\n";
Condition33%1/3
$ok &&= print(FH qq[IDX=$ix->{"name"}:$ix->{"col"}:$ix->{"unique"}\n])
!ll&&!rl&&r
002
MC/DC0%0/2
$ok &&= print(FH qq[IDX=$ix->{"name"}:$ix->{"col"}:$ix->{"unique"}\n])
$ok print(FH qq[IDX=$ix->{"name"}:$ix->{"col"}:$ix->{"unique"}\n])
Truth table33%1/3
A &&= B
A= $okB= print(FH qq[IDX=$ix->{"name"}:$ix->{"col"}:$ix->{"unique"}\n])
ABresult
0X0
100
111
3282 }
3283 21 ▶ for my $c (sort keys %{$sch->{notnull} || {}}) {
Branch: 1 branch
BranchTrueFalseTotal
$sch->{"notnull"} or {} 0 21 21
3284 21 ▶ $ok &&= print FH "NOTNULL=$c\n";
Condition33%1/3
$ok &&= print(FH "NOTNULL=$c\n")
!ll&&!rl&&r
0021
MC/DC0%0/2
$ok &&= print(FH "NOTNULL=$c\n")
$ok print(FH "NOTNULL=$c\n")
Truth table33%1/3
A &&= B
A= $okB= print(FH "NOTNULL=$c\n")
ABresult
0X0
100
111
3285 }
3286 21 ▶ for my $c (sort keys %{$sch->{defaults} || {}}) {
Branch: 1 branch
BranchTrueFalseTotal
$sch->{"defaults"} or {} 0 21 21
3287 7 ▶ $ok &&= print FH "DEFAULT=$c:$sch->{defaults}{$c}\n";
Condition33%1/3
$ok &&= print(FH qq[DEFAULT=${c}:$sch->{"defaults"}{$c}\n])
!ll&&!rl&&r
007
MC/DC0%0/2
$ok &&= print(FH qq[DEFAULT=${c}:$sch->{"defaults"}{$c}\n])
$ok print(FH qq[DEFAULT=${c}:$sch->{"defaults"}{$c}\n])
Truth table33%1/3
A &&= B
A= $okB= print(FH qq[DEFAULT=${c}:$sch->{"defaults"}{$c}\n])
ABresult
0X0
100
111
3288 }
3289 21 ▶ for my $c (sort keys %{$sch->{checks} || {}}) {
Branch: 1 branch
BranchTrueFalseTotal
$sch->{"checks"} or {} 0 21 21
3290 8 ▶ $ok &&= print FH "CHECK=$c:$sch->{checks}{$c}\n";
Condition33%1/3
$ok &&= print(FH qq[CHECK=${c}:$sch->{"checks"}{$c}\n])
!ll&&!rl&&r
008
MC/DC0%0/2
$ok &&= print(FH qq[CHECK=${c}:$sch->{"checks"}{$c}\n])
$ok print(FH qq[CHECK=${c}:$sch->{"checks"}{$c}\n])
Truth table33%1/3
A &&= B
A= $okB= print(FH qq[CHECK=${c}:$sch->{"checks"}{$c}\n])
ABresult
0X0
100
111
3291 }
3292 21 ▶ $ok &&= print FH "PK=$sch->{pk}\n" if $sch->{pk};
Branch: 1 branch
BranchTrueFalseTotal
if $sch->{"pk"} 7 14 21
Condition33%1/3
$ok &&= print(FH qq[PK=$sch->{"pk"}\n])
!ll&&!rl&&r
007
MC/DC0%0/2
$ok &&= print(FH qq[PK=$sch->{"pk"}\n])
$ok print(FH qq[PK=$sch->{"pk"}\n])
Truth table33%1/3
A &&= B
A= $okB= print(FH qq[PK=$sch->{"pk"}\n])
ABresult
0X0
100
111
3293 21 my $err = $!;
3294 21 ▶ unless ($ok && close(FH)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok and close FH) 0 21 21
Condition33%1/3
$ok and close FH
!ll&&!rl&&r
0021
MC/DC0%0/2
$ok and close FH
$ok close FH
Truth table33%1/3
A and B
A= $okB= close FH
ABresult
0X0
100
111
3295 0 ▶ $err = $! if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
3296 0 ▶ close FH if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
3297 0 return $self->_err("Cannot rewrite schema: $err");
3298 }
3299 21 return 1;
3300 }
3301  
3302 # Does $v look like a number that Perl can use in arithmetic without
3303 # complaining under -w? Leading and trailing whitespace is allowed, an
3304 # optional sign, a decimal part and an exponent; everything else -- the
3305 # empty string, 'abc', '12abc', '0x10', 'Inf', 'NaN' -- is not numeric.
3306 #
3307 # The same test used to be written out three times (index key encoding,
3308 # type validation and record packing) and the FLOAT paths had no test at
3309 # all, which is how "isn't numeric" warnings escaped from inside this
3310 # module. Keep it in one place so the three callers cannot drift apart.
3311 sub _looks_numeric {
3312 6551 ▶ my($v) = @_;
Subroutine _looks_numeric: called CC=3 SCAR=11.1
3313 6551 ▶ return 0 unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 6551 6551
3314 6551 ▶ return $v =~ /^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?\s*$/ ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$v =~ /^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?\s*$/ ? : 6514 37 6551
3315 }
3316  
3317 # Is $v a well-formed calendar date in YYYY-MM-DD form?
3318 sub _valid_date {
3319 20 ▶ my($v) = @_;
Subroutine _valid_date: called CC=10 SCAR=23.0
3320 20 ▶ return 0 unless $v =~ /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $v =~ /^(\d\d\d\d)-(\d\d)-(\d\d)$/ 2 18 20
3321 18 my($y, $m, $d) = ($1, $2, $3);
3322 18 ▶ return 0 if ($m < 1) || ($m > 12);
Branch: 1 branch
BranchTrueFalseTotal
if $m < 1 or $m > 12 3 15 18
Condition100%3/3
$m < 1 or $m > 12
l!l&&r!l&&!r
1215
MC/DC100%2/2
$m < 1 or $m > 12
$m < 1 $m > 12
Truth table100%3/3
A or B
A= $m < 1B= $m > 12
ABresult
1X1
011
000
3323 15 ▶ return 0 if $d < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $d < 1 0 15 15
3324 15 my @mdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
3325 15 my $max = $mdays[$m-1];
3326 15 ▶ if ($m == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m == 2) 6 9 15
3327 6 ▶ $max = 29 if ((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0);
Branch: 1 branch
BranchTrueFalseTotal
if $y % 4 == 0 and $y % 100 != 0 or $y % 400 == 0 4 2 6
Condition100%6/6
$y % 4 == 0 and $y % 100 != 0 or $y % 400 == 0
l!l&&r!l&&!r
312
$y % 4 == 0 and $y % 100 != 0
!ll&&!rl&&r
123
MC/DC100%3/3
$y % 4 == 0 and $y % 100 != 0 or $y % 400 == 0
$y % 4 == 0 $y % 100 != 0 $y % 400 == 0
Truth table80%4/5
A and B or C
A= $y % 4 == 0B= $y % 100 != 0C= $y % 400 == 0
ABCresult
11X1
0X11
1011
0X00
1000
3328 }
3329 15 ▶ return 0 if $d > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $d > $max 4 11 15
3330 11 return 1;
3331 }
3332  
3333 # Return an error message when $v cannot be stored in column $col, or undef
3334 # when it can. NULL (undef or the empty string) is always storable.
3335 sub _type_error {
3336 3482 ▶ my($col, $v) = @_;
Subroutine _type_error: called CC=9 SCAR=22.0
3337 3482 ▶ return undef unless defined($v) && ($v ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v and $v ne "" 50 3432 3482
Condition100%3/3
defined $v and $v ne ""
!ll&&!rl&&r
4733432
MC/DC100%2/2
defined $v and $v ne ""
defined $v $v ne ""
Truth table100%3/3
A and B
A= defined $vB= $v ne ""
ABresult
0X0
100
111
3338 3432 my $cn = $col->{name};
3339 3432 ▶ if ($col->{type} eq 'INT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($col->{"type"} eq "INT") 2261 1171 3432
3340 # A value that is not numeric at all keeps its historical
3341 # behaviour and is stored as 0. Only a numeric value too large
3342 # for the 4-byte field is rejected, because that used to be
3343 # silently clamped to the nearest limit.
3344 2261 ▶ return undef unless _looks_numeric($v);
Branch: 1 branch
BranchTrueFalseTotal
unless _looks_numeric($v) 2 2259 2261
3345 2259 ▶ return undef if ($v >= INT_MIN) && ($v <= INT_MAX);
Branch: 1 branch
BranchTrueFalseTotal
if $v >= '-2147483648' and $v <= 2147483647 2255 4 2259
Condition100%3/3
$v >= '-2147483648' and $v <= 2147483647
!ll&&!rl&&r
132255
MC/DC100%2/2
$v >= '-2147483648' and $v <= 2147483647
$v >= '-2147483648' $v <= 2147483647
Truth table100%3/3
A and B
A= $v >= '-2147483648'B= $v <= 2147483647
ABresult
0X0
100
111
3346 4 return "Integer out of range for column '$cn': '$v' "
3347 . '(INT holds ' . INT_MIN . ' .. ' . INT_MAX . ')';
3348 }
3349 1171 ▶ if ($col->{type} eq 'DATE') {
Branch: 1 branch
BranchTrueFalseTotal
if ($col->{"type"} eq "DATE") 20 1151 1171
3350 20 ▶ return undef if _valid_date($v);
Branch: 1 branch
BranchTrueFalseTotal
if _valid_date($v) 11 9 20
3351 9 return "Invalid DATE for column '$cn': '$v' (expected YYYY-MM-DD)";
3352 }
3353 1151 return undef;
3354 }
3355  
3356 sub _pack_record {
3357 2014 ▶ my($self, $sch, $row) = @_;
Subroutine _pack_record: called CC=9 SCAR=22.0
3358 2014 my $data = RECORD_ACTIVE;
3359 2014 for my $col (@{$sch->{cols}}) {
3360 3523 ▶ my $v = defined($row->{$col->{name}}) ? $row->{$col->{name}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$col->{'name'}} ? : 3484 39 3523
3361 3523 my $t = $col->{type};
3362 3523 my $s = $col->{size};
3363 3523 ▶ if ($t eq 'INT') {
Branch: 2 branches
BranchTrueFalseTotal
if ($t eq 'INT') { } 2300 1223 3523
elsif ($t eq 'FLOAT') { } 125 1098 1223
3364 # A value that is not numeric is stored as 0. It is tested
3365 # here rather than left to int() so that -w stays quiet.
3366 2300 ▶ my $iv = _looks_numeric($v) ? int($v) : 0;
Branch: 1 branch
BranchTrueFalseTotal
_looks_numeric($v) ? : 2288 12 2300
3367 2300 ▶ $iv = INT_MAX if $iv > INT_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if $iv > 2147483647 0 2300 2300
3368 2300 ▶ $iv = INT_MIN if $iv < INT_MIN;
Branch: 1 branch
BranchTrueFalseTotal
if $iv < '-2147483648' 0 2300 2300
3369 2300 $data .= pack('N', $iv&0xFFFFFFFF);
3370 }
3371 elsif ($t eq 'FLOAT') {
3372 # Same rule as INT, and for the same reason: a value that is
3373 # not numeric is stored as 0 without a warning. Up to 1.08
3374 # this branch handed the raw value to pack() and any string
3375 # that was not a number leaked an "isn't numeric" warning out
3376 # of the module, whatever the caller's warning settings were.
3377 125 ▶ $data .= pack('d', _looks_numeric($v) ? $v+0 : 0);
Branch: 1 branch
BranchTrueFalseTotal
_looks_numeric($v) ? : 110 15 125
3378 }
3379 else {
3380 1098 my $sv = substr($v, 0, $s);
3381 1098 $sv .= "\x00" x ($s-length($sv));
3382 1098 $data .= $sv;
3383 }
3384 }
3385 2014 return $data;
3386 }
3387  
3388 sub _unpack_record {
3389 4074 ▶ my($self, $sch, $raw) = @_;
Subroutine _unpack_record: called CC=5 SCAR=16.1
3390 4074 my %row;
3391 4074 my $offset = 1;
3392 4074 for my $col (@{$sch->{cols}}) {
3393 12102 my $t = $col->{type};
3394 12102 my $s = $col->{size};
3395 12102 my $chunk = substr($raw, $offset, $s);
3396 12102 ▶ if ($t eq 'INT') {
Branch: 2 branches
BranchTrueFalseTotal
if ($t eq 'INT') { } 7128 4974 12102
elsif ($t eq 'FLOAT') { } 391 4583 4974
3397 7128 my $uv = unpack('N', $chunk);
3398 7128 ▶ $uv -= 4294967296 if $uv > 2147483647;
Branch: 1 branch
BranchTrueFalseTotal
if $uv > 2147483647 14 7114 7128
3399 7128 $row{$col->{name}} = $uv;
3400 }
3401 elsif ($t eq 'FLOAT') {
3402 391 $row{$col->{name}} = unpack('d', $chunk);
3403 }
3404 else {
3405 4583 (my $sv = $chunk) =~ s/\x00+$//;
3406 4583 $row{$col->{name}} = $sv;
3407 }
3408 12102 $offset += $s;
3409 }
3410 4074 return { %row };
3411 }
3412  
3413 4052 ▶sub _lock_ex { flock($_[0], LOCK_EX) }
Subroutine _lock_ex: called CC=1 SCAR=0.0
3414 3025 ▶sub _lock_sh { flock($_[0], LOCK_SH) }
Subroutine _lock_sh: called CC=1 SCAR=0.0
3415 7077 ▶sub _unlock { flock($_[0], LOCK_UN) }
Subroutine _unlock: called CC=1 SCAR=0.0
3416  
3417 # Put a write handle into autoflush mode.
3418 #
3419 # print() buffers, and the buffer is written out by close(), which runs
3420 # after _unlock(). Without this the data would reach the file only after
3421 # the exclusive lock had already been handed to another process. With
3422 # autoflush on, every print() reaches the file while the lock is still
3423 # held. IO::Handle->autoflush is avoided on purpose: the select() idiom
3424 # needs no module and works on every Perl from 5.005_03 onwards.
3425 sub _autoflush {
3426 4049 ▶ my $old = select($_[0]);
Subroutine _autoflush: called CC=1 SCAR=0.0
3427 4049 $| = 1;
3428 4049 select($old);
3429 }
3430  
3431 sub _to_where_sub {
3432 12 ▶ my($wi) = @_;
Subroutine _to_where_sub: called CC=4 SCAR=18.9
3433 12 ▶ return undef unless defined $wi;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $wi 0 12 12
3434 12 ▶ return $wi if ref($wi) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $wi eq "CODE" 12 0 12
3435 0 ▶ return _compile_where_from_conds($wi) if ref($wi) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $wi eq "ARRAY" 0 0 0
3436 0 return undef;
3437 }
3438  
3439 sub _split_col_defs {
3440 156 ▶ my($str) = @_;
Subroutine _split_col_defs: called CC=7 SCAR=19.5
3441 156 my @parts;
3442 156 my $cur = '';
3443 156 my $depth = 0;
3444 156 for my $ch (split //, $str) {
3445 4364 ▶ if ($ch eq '(') {
Branch: 3 branches
BranchTrueFalseTotal
if ($ch eq '(') { } 137 4227 4364
elsif ($ch eq ')') { } 137 4090 4227
elsif ($ch eq ',' and $depth == 0) { } 197 3893 4090
3446 137 $depth++;
3447 137 $cur .= $ch;
3448 }
3449 elsif ($ch eq ')') {
3450 137 $depth--;
3451 137 $cur .= $ch;
3452 }
3453 ▶ elsif (($ch eq ',') && ($depth == 0)) {
Condition66%2/3
$ch eq "," and $depth == 0
!ll&&!rl&&r
38930197
MC/DC50%1/2
$ch eq "," and $depth == 0
$ch eq "," $depth == 0
Truth table66%2/3
A and B
A= $ch eq ","B= $depth == 0
ABresult
0X0
100
111
3454 197 push @parts, $cur;
3455 197 $cur = '';
3456 }
3457 else {
3458 3893 $cur .= $ch;
3459 }
3460 }
3461 156 ▶ push @parts, $cur if $cur =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $cur =~ /\S/ 156 0 156
3462 156 return @parts;
3463 }
3464  
3465 sub _parse_values {
3466 1981 ▶ my($str) = @_;
Subroutine _parse_values: called CC=6 SCAR=18.0
3467 1981 my @vals;
3468 1981 ▶ while (length $str) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $str) 3385 1981 5366
3469 3385 $str =~ s/^\s+//;
3470 3385 ▶ last unless length $str;
Branch: 1 branch
BranchTrueFalseTotal
unless length $str 0 3385 3385
3471 3385 ▶ if ($str =~ s/^'((?:[^']|'')*)'(?:\s*,\s*|\s*$)//) {
Branch: 3 branches
BranchTrueFalseTotal
if ($str =~ s/^'((?:[^']|'')*)'(?:\s*,\s*|\s*$)//) { } 1055 2330 3385
elsif ($str =~ s/^(NULL)(?:\s*,\s*|\s*$)//i) { } 7 2323 2330
elsif ($str =~ s/^(-?\d+\.?\d*)(?:\s*,\s*|\s*$)//) { } 2323 0 2323
3472 1055 my $s = $1;
3473 1055 $s =~ s/''/'/g;
3474 1055 push @vals, $s;
3475 }
3476 elsif ($str =~ s/^(NULL)(?:\s*,\s*|\s*$)//i) {
3477 7 push @vals, undef;
3478 }
3479 elsif ($str =~ s/^(-?\d+\.?\d*)(?:\s*,\s*|\s*$)//) {
3480 2323 push @vals, $1;
3481 }
3482 else {
3483 0 last;
3484 }
3485 }
3486 1981 return @vals;
3487 }
3488  
3489 sub _parse_conditions {
3490 0 ▶ my($expr) = @_;
Subroutine _parse_conditions: not called CC=18 SCAR=58.3
3491 0 my @conds;
3492  
3493 # Use paren-aware AND splitter
3494 0 my @parts = _split_and_clauses($expr);
3495 0 for my $part (@parts) {
3496 0 $part =~ s/^\s+|\s+$//g;
3497  
3498 # col [NOT] IN (val, val, ...) -- expanded from subquery or literal list
3499 0 ▶ if ($part =~ /^(\w+)\s+(NOT\s+)?IN\s*\(([^)]*)\)\s*$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s+(NOT\s+)?IN\s*\(([^)]*)\)\s*$/i) 0 0 0
3500 0 my($col, $neg, $list_str) = ($1, $2, $3);
3501 0 my @vals;
3502  
3503 # parse list: numbers or quoted strings or NULL
3504 0 my $ls = $list_str;
3505 0 ▶ while ($ls =~ s/^\s*(?:'([^']*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ls =~ s/^\s*(?:'([^']*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) 0 0 0
3506 0 my($sv, $nv, $nl) = ($1, $2, $3);
3507 0 ▶ push @vals, defined($nl) ? undef : (defined($sv) ? $sv : $nv);
Branch: 2 branches
BranchTrueFalseTotal
defined $nl ? : 0 0 0
defined $sv ? : 0 0 0
3508 }
3509 0 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 0 0 0
3510 col => $col,
3511 op => $neg ? 'NOT_IN' : 'IN',
3512 vals => [ @vals ],
3513 };
3514 0 next;
3515 }
3516  
3517 # EXISTS (1) or EXISTS (0) -- already evaluated by subquery expander
3518 0 ▶ if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) 0 0 0
3519 0 my($neg, $val) = ($1, $2);
3520 0 ▶ my $truth = $val ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$val ? : 0 0 0
3521 0 ▶ $truth = 1 - $truth if $neg;
Branch: 1 branch
BranchTrueFalseTotal
if $neg 0 0 0
3522 0 push @conds, { op => 'CONST', val => $truth };
3523 0 next;
3524 }
3525  
3526 # EXISTS (1) or NOT EXISTS (0) without outer parens (legacy)
3527 0 ▶ if ($part =~ /^(NOT\s+)?EXISTS\s+(\d+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(NOT\s+)?EXISTS\s+(\d+)$/i) 0 0 0
3528 0 my($neg, $val) = ($1, $2);
3529 0 ▶ my $truth = $val ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$val ? : 0 0 0
3530 0 ▶ $truth = 1 - $truth if $neg;
Branch: 1 branch
BranchTrueFalseTotal
if $neg 0 0 0
3531 0 push @conds, { op => 'CONST', val => $truth };
3532 0 next;
3533 }
3534  
3535 # col OP NULL -- SQL NULL semantics: comparison with NULL is always false
3536 0 ▶ if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*NULL$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*NULL$/i) 0 0 0
3537 0 push @conds, { op => 'CONST', val => 0 };
3538 0 next;
3539 }
3540  
3541 # IS [NOT] NULL
3542 0 ▶ if ($part =~ /^(\w+)\s+IS\s+(NOT\s+)?NULL$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s+IS\s+(NOT\s+)?NULL$/i) 0 0 0
3543 0 my($col, $neg) = ($1, $2);
3544 0 ▶ push @conds, { col=>$col, op=>$neg ? 'IS_NOT_NULL' : 'IS_NULL' };
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 0 0 0
3545 0 next;
3546 }
3547  
3548 # Normal col OP literal
3549 0 ▶ if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) 0 0 0
3550 0 my($col, $op, $sv, $nv) = ($1, $2, $3, $4);
3551 0 ▶ push @conds, { col=>$col, op=>uc($op), val=>(defined($sv) ? $sv : $nv) };
Branch: 1 branch
BranchTrueFalseTotal
defined $sv ? : 0 0 0
3552 }
3553 }
3554 0 return [ @conds ];
3555 }
3556  
3557 sub _compile_where_from_conds {
3558 6 ▶ my($conds) = @_;
Subroutine _compile_where_from_conds: called CC=3 SCAR=19.1
3559 6 ▶ return undef unless $conds && @$conds;
Branch: 1 branch
BranchTrueFalseTotal
unless $conds and @$conds 4 2 6
Condition66%2/3
$conds and @$conds
!ll&&!rl&&r
042
MC/DC50%1/2
$conds and @$conds
$conds @$conds
Truth table66%2/3
A and B
A= $condsB= @$conds
ABresult
0X0
100
111
3560 return sub {
3561 8 ▶ my($row) = @_;
Subroutine __ANON__: called CC=49 SCAR=70.9
3562 8 for my $c (@$conds) {
3563 8 my $op = $c->{op};
3564  
3565 # Constant (pre-evaluated EXISTS/NOT EXISTS)
3566 8 ▶ if ($op eq 'CONST') {
Branch: 4 branches
BranchTrueFalseTotal
if ($op eq 'CONST') { } 0 8 8
elsif ($op eq 'IN' or $op eq 'NOT_IN') { } 0 8 8
elsif ($op eq 'IS_NULL') { } 0 8 8
elsif ($op eq 'IS_NOT_NULL') { } 0 8 8
3567 0 ▶ return 0 unless $c->{val};
Branch: 1 branch
BranchTrueFalseTotal
unless $c->{"val"} 0 0 0
3568 # IN / NOT IN with value list
3569 }
3570 ▶ elsif (($op eq 'IN') || ($op eq 'NOT_IN')) {
Condition33%1/3
$op eq "IN" or $op eq "NOT_IN"
l!l&&r!l&&!r
008
MC/DC0%0/2
$op eq "IN" or $op eq "NOT_IN"
$op eq "IN" $op eq "NOT_IN"
Truth table33%1/3
A or B
A= $op eq "IN"B= $op eq "NOT_IN"
ABresult
1X1
011
000
3571 0 ▶ my $rv = defined($row->{$c->{col}}) ? $row->{$c->{col}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$c->{'col'}} ? : 0 0 0
3572 0 my $found = 0;
3573 0 my $has_null = 0;
3574 0 for my $cv (@{$c->{vals}}) {
3575 0 ▶ unless (defined $cv) { $has_null = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cv) 0 0 0
3576 0 ▶ my $num = (($rv =~ /^-?\d+\.?\d*$/) && ($cv =~ /^-?\d+\.?\d*$/));
Condition0%0/3
$rv =~ /^-?\d+\.?\d*$/ && $cv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
000
MC/DC0%0/2
$rv =~ /^-?\d+\.?\d*$/ && $cv =~ /^-?\d+\.?\d*$/
$rv =~ /^-?\d+\.?\d*$/ $cv =~ /^-?\d+\.?\d*$/
Truth table0%0/3
A && B
A= $rv =~ /^-?\d+\.?\d*$/B= $cv =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
3577 0 ▶ if ($num ? ($rv == $cv) : ($rv eq $cv)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($num ? $rv == $cv : $rv eq $cv) 0 0 0
$num ? : 0 0 0
3578 0 $found = 1;
3579 0 last;
3580 }
3581 }
3582 0 ▶ return 0 if $found && ($op eq 'NOT_IN');
Branch: 1 branch
BranchTrueFalseTotal
if $found and $op eq "NOT_IN" 0 0 0
Condition0%0/3
$found and $op eq "NOT_IN"
!ll&&!rl&&r
000
MC/DC0%0/2
$found and $op eq "NOT_IN"
$found $op eq "NOT_IN"
Truth table0%0/3
A and B
A= $foundB= $op eq "NOT_IN"
ABresult
0X0
100
111
3583 0 ▶ return 0 if !$found && ($op eq 'IN');
Branch: 1 branch
BranchTrueFalseTotal
if not $found and $op eq "IN" 0 0 0
Condition0%0/3
not $found and $op eq "IN"
!ll&&!rl&&r
000
MC/DC0%0/2
not $found and $op eq "IN"
not $found $op eq "IN"
Truth table0%0/3
not(A) and B
A= not $foundB= $op eq "IN"
ABresult
0X0
100
111
3584 # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN
3585 # when the row value was not found in the non-NULL values.
3586 0 ▶ return 0 if $has_null && !$found && ($op eq 'NOT_IN');
Branch: 1 branch
BranchTrueFalseTotal
if $has_null and not $found and $op eq "NOT_IN" 0 0 0
Condition0%0/6
$has_null and not $found and $op eq "NOT_IN"
!ll&&!rl&&r
000
$has_null and not $found
!ll&&!rl&&r
000
MC/DC0%0/3
$has_null and not $found and $op eq "NOT_IN"
$has_null not $found $op eq "NOT_IN"
Truth table0%0/4
A and not(B) and C
A= $has_nullB= not $foundC= $op eq "NOT_IN"
ABCresult
0XX0
10X0
1100
1111
3587 # IS NULL / IS NOT NULL
3588 }
3589 elsif ($op eq 'IS_NULL') {
3590 0 ▶ return 0 unless !defined($row->{$c->{col}}) || ($row->{$c->{col}} eq '');
Branch: 1 branch
BranchTrueFalseTotal
unless not defined $$row{$c->{"col"}} or $$row{$c->{"col"}} eq "" 0 0 0
Condition0%0/3
not defined $$row{$c->{"col"}} or $$row{$c->{"col"}} eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $$row{$c->{"col"}} or $$row{$c->{"col"}} eq ""
not defined $$row{$c->{"col"}} $$row{$c->{"col"}} eq ""
Truth table0%0/3
not(A) or B
A= not defined $$row{$c->{"col"}}B= $$row{$c->{"col"}} eq ""
ABresult
1X1
011
000
3591 }
3592 elsif ($op eq 'IS_NOT_NULL') {
3593 0 ▶ return 0 unless defined($row->{$c->{col}}) && ($row->{$c->{col}} ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$row{$c->{"col"}} and $$row{$c->{"col"}} ne "" 0 0 0
Condition0%0/3
defined $$row{$c->{"col"}} and $$row{$c->{"col"}} ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $$row{$c->{"col"}} and $$row{$c->{"col"}} ne ""
defined $$row{$c->{"col"}} $$row{$c->{"col"}} ne ""
Truth table0%0/3
A and B
A= defined $$row{$c->{"col"}}B= $$row{$c->{"col"}} ne ""
ABresult
0X0
100
111
3594 # Standard comparison
3595 }
3596 else {
3597 8 ▶ my $rv = defined($row->{$c->{col}}) ? $row->{$c->{col}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$c->{'col'}} ? : 8 0 8
3598 8 my $cv = $c->{val};
3599 8 ▶ my $num = (($rv =~ /^-?\d+\.?\d*$/) && defined($cv) && ($cv =~ /^-?\d+\.?\d*$/));
Condition33%2/6
$rv =~ /^-?\d+\.?\d*$/ && defined $cv && $cv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
008
$rv =~ /^-?\d+\.?\d*$/ and defined $cv
!ll&&!rl&&r
008
MC/DC0%0/3
$rv =~ /^-?\d+\.?\d*$/ && defined $cv && $cv =~ /^-?\d+\.?\d*$/
$rv =~ /^-?\d+\.?\d*$/ defined $cv $cv =~ /^-?\d+\.?\d*$/
Truth table25%1/4
A and B && C
A= $rv =~ /^-?\d+\.?\d*$/B= defined $cvC= $cv =~ /^-?\d+\.?\d*$/
ABCresult
0XX0
10X0
1100
1111
3600 8 ▶ if ($op eq '=') {
Branch: 7 branches
BranchTrueFalseTotal
if ($op eq '=') { } 4 4 8
elsif ($op eq '!=' or $op eq '<>') { } 0 4 4
elsif ($op eq '<') { } 0 4 4
elsif ($op eq '>') { } 4 0 4
elsif ($op eq '<=') { } 0 0 0
elsif ($op eq '>=') { } 0 0 0
elsif ($op eq 'LIKE') { } 0 0 0
3601 4 ▶ return 0 unless $num ? ($rv == $cv) : ($rv eq $cv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $rv == $cv : $rv eq $cv 0 4 4
$num ? : 4 0 4
3602 }
3603 ▶ elsif (($op eq '!=') || ($op eq '<>')) {
Condition33%1/3
$op eq "!=" or $op eq "<>"
l!l&&r!l&&!r
004
MC/DC0%0/2
$op eq "!=" or $op eq "<>"
$op eq "!=" $op eq "<>"
Truth table33%1/3
A or B
A= $op eq "!="B= $op eq "<>"
ABresult
1X1
011
000
3604 0 ▶ return 0 unless $num ? ($rv != $cv) : ($rv ne $cv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $rv != $cv : $rv ne $cv 0 0 0
$num ? : 0 0 0
3605 }
3606 elsif ($op eq '<') {
3607 0 ▶ return 0 unless $num ? ($rv < $cv) : ($rv lt $cv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $rv < $cv : $rv lt $cv 0 0 0
$num ? : 0 0 0
3608 }
3609 elsif ($op eq '>') {
3610 4 ▶ return 0 unless $num ? ($rv > $cv) : ($rv gt $cv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $rv > $cv : $rv gt $cv 2 2 4
$num ? : 4 0 4
3611 }
3612 elsif ($op eq '<=') {
3613 0 ▶ return 0 unless $num ? ($rv <= $cv) : ($rv le $cv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $rv <= $cv : $rv le $cv 0 0 0
$num ? : 0 0 0
3614 }
3615 elsif ($op eq '>=') {
3616 0 ▶ return 0 unless $num ? ($rv >= $cv) : ($rv ge $cv);
Branch: 2 branches
BranchTrueFalseTotal
unless $num ? $rv >= $cv : $rv ge $cv 0 0 0
$num ? : 0 0 0
3617 }
3618 elsif ($op eq 'LIKE') {
3619 0 my $p = _like_to_re($cv);
3620 0 ▶ return 0 unless $rv =~ /^$p$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $rv =~ /^$p$/i 0 0 0
3621 }
3622 }
3623 }
3624 6 return 1;
3625 2 };
3626 }
3627  
3628 ###############################################################################
3629 # SQL-92 Engine
3630 ###############################################################################
3631  
3632 # =============================================================================
3633 # Expression evaluator eval_expr($expr, \%row) -> scalar
3634 # =============================================================================
3635 sub eval_expr {
3636 5753 ▶ my($expr, $row) = @_;
Subroutine eval_expr: called CC=76 SCAR=60.9
Pod undocumented
3637 5753 ▶ return undef unless defined $expr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expr 0 5753 5753
3638 5753 $expr =~ s/^\s+|\s+$//g;
3639 5753 ▶ return undef unless length($expr);
Branch: 1 branch
BranchTrueFalseTotal
unless length $expr 0 5753 5753
3640 5753 ▶ return undef if $expr =~ /^NULL$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^NULL$/i 0 5753 5753
3641 5753 ▶ return $expr + 0 if $expr =~ /^-?\d+\.?\d*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^-?\d+\.?\d*$/ 117 5636 5753
3642 5636 ▶ if ($expr =~ /^'((?:[^']|'')*)'$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^'((?:[^']|'')*)'$/) 30 5606 5636
3643 30 (my $s = $1) =~ s/''/'/g;
3644 30 return $s;
3645 }
3646 5606 ▶ if (($expr =~ /^\((.+)\)$/s) && ($1 !~ /^\s*SELECT\b/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^\((.+)\)$/s and not $1 =~ /^\s*SELECT\b/i) 0 5606 5606
Condition33%1/3
$expr =~ /^\((.+)\)$/s and not $1 =~ /^\s*SELECT\b/i
!ll&&!rl&&r
560600
MC/DC0%0/2
$expr =~ /^\((.+)\)$/s and not $1 =~ /^\s*SELECT\b/i
$expr =~ /^\((.+)\)$/s not $1 =~ /^\s*SELECT\b/i
Truth table33%1/3
A and not(B)
A= $expr =~ /^\((.+)\)$/sB= not $1 =~ /^\s*SELECT\b/i
ABresult
0X0
100
111
3647 0 return eval_expr($1, $row);
3648 }
3649 5606 ▶ if ($expr =~ /^CASE\b(.*)\bEND$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^CASE\b(.*)\bEND$/is) 9 5597 5606
3650 9 return eval_case($1, $row);
3651 }
3652 5597 ▶ if ($expr =~ /^COALESCE\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^COALESCE\s*\((.+)\)$/is) 4 5593 5597
3653 4 for my $a (args($1)) {
3654 6 my $v = eval_expr($a, $row);
3655 6 ▶ return $v if defined($v) && ($v ne '');
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and $v ne "" 4 2 6
Condition66%2/3
defined $v and $v ne ""
!ll&&!rl&&r
024
MC/DC50%1/2
defined $v and $v ne ""
defined $v $v ne ""
Truth table66%2/3
A and B
A= defined $vB= $v ne ""
ABresult
0X0
100
111
3656 }
3657 0 return undef;
3658 }
3659 5593 ▶ if ($expr =~ /^NULLIF\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^NULLIF\s*\((.+)\)$/is) 2 5591 5593
3660 2 my @a = args($1);
3661 2 ▶ return undef unless @a == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @a == 2 0 2 2
3662 2 my($va, $vb) = (eval_expr($a[0], $row), eval_expr($a[1], $row));
3663 2 ▶ if (defined($va) && defined($vb)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $va and defined $vb) 2 0 2
Condition33%1/3
defined $va and defined $vb
!ll&&!rl&&r
002
MC/DC0%0/2
defined $va and defined $vb
defined $va defined $vb
Truth table33%1/3
A and B
A= defined $vaB= defined $vb
ABresult
0X0
100
111
3664 2 ▶ return undef if ((($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/)) ? ($va == $vb) : ($va eq $vb));
Branch: 2 branches
BranchTrueFalseTotal
if $va =~ /^-?\d+\.?\d*$/ && $vb =~ /^-?\d+\.?\d*$/ ? $va == $vb : $va eq $vb 1 1 2
$va =~ /^-?\d+\.?\d*$/ && $vb =~ /^-?\d+\.?\d*$/ ? : 2 0 2
Condition33%1/3
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
002
MC/DC0%0/2
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
$va =~ /^-?\d+\.?\d*$/ $vb =~ /^-?\d+\.?\d*$/
Truth table33%1/3
A and B
A= $va =~ /^-?\d+\.?\d*$/B= $vb =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
3665 }
3666 1 return $va;
3667 }
3668 5591 ▶ if ($expr =~ /^CAST\s*\(\s*(.+?)\s+AS\s+(\w+(?:\s*\(\s*\d+\s*\))?)\s*\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^CAST\s*\(\s*(.+?)\s+AS\s+(\w+(?:\s*\(\s*\d+\s*\))?)\s*\)$/is) 2 5589 5591
3669 2 my($ie, $t) = ($1, uc($2));
3670 2 my $v = eval_expr($ie, $row);
3671 2 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 2 2
3672 2 ▶ return int($v) if $t =~ /^INT/i;
Branch: 1 branch
BranchTrueFalseTotal
if $t =~ /^INT/i 1 1 2
3673 1 ▶ return $v + 0 if $t =~ /^(FLOAT|REAL|DOUBLE|NUMERIC|DECIMAL)/i;
Branch: 1 branch
BranchTrueFalseTotal
if $t =~ /^(FLOAT|REAL|DOUBLE|NUMERIC|DECIMAL)/i 0 1 1
3674 1 return "$v";
3675 }
3676 5589 ▶ if ($expr =~ /^(UPPER|LOWER|LENGTH|ABS|SIGN|TRIM|LTRIM|RTRIM)\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(UPPER|LOWER|LENGTH|ABS|SIGN|TRIM|LTRIM|RTRIM)\s*\((.+)\)$/is) 9 5580 5589
3677 9 my($fn, $arg) = (uc($1), $2);
3678 9 my $v = eval_expr($arg, $row);
3679 9 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 9 9
3680 9 ▶ return uc($v) if $fn eq 'UPPER';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "UPPER" 2 7 9
3681 7 ▶ return lc($v) if $fn eq 'LOWER';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "LOWER" 3 4 7
3682 4 ▶ return length($v) if $fn eq 'LENGTH';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "LENGTH" 2 2 4
3683 2 ▶ return abs($v + 0) if $fn eq 'ABS';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "ABS" 0 2 2
3684 2 ▶ return (($v > 0) ? 1 : ($v < 0) ? -1 : 0) if $fn eq 'SIGN';
Branch: 3 branches
BranchTrueFalseTotal
if $fn eq "SIGN" 0 2 2
$v > 0 ? : 0 0 0
$v < 0 ? : 0 0 0
3685 2 ▶ if ($fn eq 'TRIM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "TRIM") 2 0 2
3686 2 (my $s = $v) =~ s/^\s+|\s+$//g;
3687 2 return $s;
3688 }
3689 0 ▶ if ($fn eq 'LTRIM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "LTRIM") 0 0 0
3690 0 (my $s = $v) =~ s/^\s+//;
3691 0 return $s;
3692 }
3693 0 ▶ if ($fn eq 'RTRIM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "RTRIM") 0 0 0
3694 0 (my $s = $v) =~ s/\s+$//;
3695 0 return $s;
3696 }
3697 }
3698 5580 ▶ if ($expr =~ /^ROUND\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^ROUND\s*\((.+)\)$/is) 0 5580 5580
3699 0 my @a = args($1);
3700 0 my $v = eval_expr($a[0], $row);
3701 0 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
3702 0 ▶ my $d = (@a > 1) ? int(eval_expr($a[1], $row) || 0) : 0;
Branch: 1 branch
BranchTrueFalseTotal
@a > 1 ? : 0 0 0
Condition0%0/2
eval_expr($a[1], $row) || 0
l!l
00
MC/DC0%0/1
eval_expr($a[1], $row) || 0
eval_expr($a[1], $row)
Truth table0%0/2
A
A= eval_expr($a[1], $row)
Aresult
11
00
3703 0 return sprintf("%.${d}f", $v+0) + 0;
3704 }
3705 5580 ▶ if ($expr =~ /^(FLOOR|CEIL(?:ING)?)\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(FLOOR|CEIL(?:ING)?)\s*\((.+)\)$/is) 0 5580 5580
3706 0 my($fn, $arg) = (uc($1), $2);
3707 0 my $v = eval_expr($arg, $row);
3708 0 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
3709 0 ▶ return $fn eq 'FLOOR' ? POSIX::floor($v+0) : POSIX::ceil($v+0);
Branch: 1 branch
BranchTrueFalseTotal
$fn eq 'FLOOR' ? : 0 0 0
3710 }
3711 5580 ▶ if ($expr =~ /^MOD\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^MOD\s*\((.+)\)$/is) 0 5580 5580
3712 0 my @a = args($1);
3713 0 ▶ return undef unless @a == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @a == 2 0 0 0
3714 0 my($a, $b) = (eval_expr($a[0], $row)+0, eval_expr($a[1], $row)+0);
3715 0 ▶ return undef if $b == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $b == 0 0 0 0
3716 0 return $a % $b;
3717 }
3718 5580 ▶ if ($expr =~ /^(?:SUBSTR|SUBSTRING)\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(?:SUBSTR|SUBSTRING)\s*\((.+)\)$/is) 1 5579 5580
3719 1 my $inner = $1;
3720 1 my($se, $ste, $le);
3721 1 ▶ if ($inner =~ /^(.+?)\s+FROM\s+(\S+)(?:\s+FOR\s+(.+))?$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inner =~ /^(.+?)\s+FROM\s+(\S+)(?:\s+FOR\s+(.+))?$/is) { } 0 1 1
3722 0 ($se, $ste, $le) = ($1, $2, $3);
3723 }
3724 else {
3725 1 ($se, $ste, $le) = args($inner);
3726 }
3727 1 my $s = eval_expr($se, $row);
3728 1 ▶ return undef unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 1 1
3729 1 ▶ my $st = int(eval_expr($ste, $row) || 1);
Condition50%1/2
eval_expr($ste, $row) || 1
l!l
10
MC/DC0%0/1
eval_expr($ste, $row) || 1
eval_expr($ste, $row)
Truth table50%1/2
A
A= eval_expr($ste, $row)
Aresult
11
00
3730 1 ▶ $st = 1 if $st < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $st < 1 0 1 1
3731 1 ▶ return defined($le)
Branch: 1 branch
BranchTrueFalseTotal
defined $le ? : 1 0 1
Condition50%1/2
eval_expr($le, $row) || 0
l!l
10
MC/DC0%0/1
eval_expr($le, $row) || 0
eval_expr($le, $row)
Truth table50%1/2
A
A= eval_expr($le, $row)
Aresult
11
00
3732 ? substr($s, $st-1, int(eval_expr($le, $row) || 0))
3733 : substr($s, $st-1);
3734 }
3735 5579 ▶ if ($expr =~ /^CONCAT\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^CONCAT\s*\((.+)\)$/is) 0 5579 5579
3736 0 my @args = args($1);
3737 0 my $r = '';
3738 0 for (@args) {
3739 0 my $v = eval_expr($_, $row);
3740 0 ▶ $r .= defined($v) ? $v : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 0 0 0
3741 }
3742 0 return $r;
3743 }
3744  
3745 # Binary operator: find rightmost at depth 0 (precedence low->high: || then +/- then */%)
3746 5579 for my $op ('\\|\\|', '[+\\-]', '[*/%]') {
3747 16707 my $p = find_binop($expr, $op);
3748 16707 ▶ if (defined $p) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p) 36 16671 16707
3749 36 my $opsym = substr($expr, $p->{s}, $p->{l});
3750 36 my $lv = eval_expr(substr($expr, 0, $p->{s}), $row);
3751 36 my $rv = eval_expr(substr($expr, $p->{s}+$p->{l}), $row);
3752 36 ▶ if ($opsym eq '||') {
Branch: 1 branch
BranchTrueFalseTotal
if ($opsym eq "||") 6 30 36
3753 6 ▶ return (defined($lv) ? $lv : '').(defined($rv) ? $rv : '');
Branch: 2 branches
BranchTrueFalseTotal
defined $lv ? : 6 0 6
defined $rv ? : 6 0 6
3754 }
3755 30 ▶ return undef unless defined($lv) && defined($rv);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv and defined $rv 0 30 30
Condition33%1/3
defined $lv and defined $rv
!ll&&!rl&&r
0030
MC/DC0%0/2
defined $lv and defined $rv
defined $lv defined $rv
Truth table33%1/3
A and B
A= defined $lvB= defined $rv
ABresult
0X0
100
111
3756 30 my($l, $r) = ($lv + 0, $rv + 0);
3757 30 ▶ return $l + $r if $opsym eq '+';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "+" 18 12 30
3758 12 ▶ return $l - $r if $opsym eq '-';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "-" 0 12 12
3759 12 ▶ return $l * $r if $opsym eq '*';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "*" 6 6 12
3760 6 ▶ return undef if (($opsym eq '/') || ($opsym eq '%')) && ($r == 0);
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "/" || $opsym eq "%" and $r == 0 0 6 6
Condition33%2/6
$opsym eq "/" || $opsym eq "%" and $r == 0
!ll&&!rl&&r
060
$opsym eq "/" or $opsym eq "%"
l!l&&r!l&&!r
060
MC/DC0%0/3
$opsym eq "/" || $opsym eq "%" and $r == 0
$opsym eq "/" $opsym eq "%" $r == 0
Truth table20%1/5
A or B and C
A= $opsym eq "/"B= $opsym eq "%"C= $r == 0
ABCresult
00X0
1X00
0100
1X11
0111
3761 6 ▶ return $l / $r if $opsym eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "/" 0 6 6
3762 6 ▶ return $l % $r if $opsym eq '%';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "%" 6 0 6
3763 }
3764 }
3765 5543 ▶ if ($expr =~ /^-([\w('.].*)$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^-([\w('.].*)$/s) 0 5543 5543
3766 0 my $v = eval_expr($1, $row);
3767 0 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
3768 0 return - ($v + 0);
3769 }
3770 5543 ▶ if ($expr =~ /^(\w+)\.(\w+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(\w+)\.(\w+)$/) 46 5497 5543
3771 46 my($a, $c) = ($1, $2);
3772 46 ▶ return exists($row->{"$a.$c"}) ? $row->{"$a.$c"} : $row->{$c};
Branch: 1 branch
BranchTrueFalseTotal
exists $$row{"$a.$c"} ? : 16 30 46
3773 }
3774 5497 ▶ return $row->{$expr} if $expr =~ /^\w+$/;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^\w+$/ 5497 0 5497
3775 0 return undef;
3776 }
3777  
3778 sub eval_case {
3779 9 ▶ my($body, $row) = @_;
Subroutine eval_case: called CC=12 SCAR=33.6
Pod undocumented
3780 9 $body =~ s/^\s+|\s+$//g;
3781 9 my $base;
3782 9 ▶ unless ($body =~ /^\s*WHEN\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($body =~ /^\s*WHEN\b/i) 0 9 9
3783 0 ▶ $body =~ s/^(.+?)\s+(?=WHEN\b)//si and $base = $1;
Branch: 1 branch
BranchTrueFalseTotal
$body =~ s/^(.+?)\s+(?=WHEN\b)//is and $base = $1 0 0 0
3784 }
3785 9 my $else;
3786 9 ▶ $body =~ s/\s*\bELSE\b\s+(.+?)\s*$//si and $else = $1;
Branch: 1 branch
BranchTrueFalseTotal
$body =~ s/\s*\bELSE\b\s+(.+?)\s*$//is and $else = $1 9 0 9
3787 9 ▶ while ($body =~ s/^\s*WHEN\s+(.+?)\s+THEN\s+(.+?)(?=\s+WHEN\b|\s*$)//si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ s/^\s*WHEN\s+(.+?)\s+THEN\s+(.+?)(?=\s+WHEN\b|\s*$)//is) 15 3 18
3788 15 my($we, $te) = ($1, $2);
3789 15 my $m;
3790 15 ▶ if (defined $base) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $base) { } 0 15 15
3791 0 my($bv, $wv) = (eval_expr($base, $row), eval_expr($we, $row));
3792 0 ▶ $m = defined($bv) && defined($wv) && ((($bv =~ /^-?\d+\.?\d*$/) && ($wv =~ /^-?\d+\.?\d*$/)) ? ($bv == $wv) : ($bv eq $wv));
Branch: 1 branch
BranchTrueFalseTotal
$bv =~ /^-?\d+\.?\d*$/ && $wv =~ /^-?\d+\.?\d*$/ ? : 0 0 0
Condition0%0/9
defined $bv && defined $wv && ($bv =~ /^-?\d+\.?\d*$/ && $wv =~ /^-?\d+\.?\d*$/ ? $bv == $wv : $bv eq $wv)
!ll&&!rl&&r
000
defined $bv and defined $wv
!ll&&!rl&&r
000
$bv =~ /^-?\d+\.?\d*$/ and $wv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
000
MC/DC0%0/4
defined $bv && defined $wv && ($bv =~ /^-?\d+\.?\d*$/ && $wv =~ /^-?\d+\.?\d*$/ ? $bv == $wv : $bv eq $wv)
defined $bv defined $wv $bv =~ /^-?\d+\.?\d*$/ $wv =~ /^-?\d+\.?\d*$/
Truth table0%0/5
A and B && C and D
A= defined $bvB= defined $wvC= $bv =~ /^-?\d+\.?\d*$/D= $wv =~ /^-?\d+\.?\d*$/
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3793 }
3794 else {
3795 15 $m = eval_bool($we, $row);
3796 }
3797 15 ▶ return eval_expr($te, $row) if $m;
Branch: 1 branch
BranchTrueFalseTotal
if $m 6 9 15
3798 }
3799 3 ▶ return defined($else) ? eval_expr($else, $row) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $else ? : 3 0 3
3800 }
3801  
3802 sub eval_bool {
3803 40 ▶ my($expr, $row) = @_;
Subroutine eval_bool: called CC=21 SCAR=42.3
Pod undocumented
3804 40 $expr =~ s/^\s+|\s+$//g;
3805 40 ▶ if ($expr =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) 40 0 40
3806 40 my($l, $op, $r) = ($1, uc($2), $3);
3807 40 my($lv, $rv) = (eval_expr($l, $row), eval_expr($r, $row));
3808 40 ▶ return 0 unless defined($lv) && defined($rv);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv and defined $rv 0 40 40
Condition33%1/3
defined $lv and defined $rv
!ll&&!rl&&r
0040
MC/DC0%0/2
defined $lv and defined $rv
defined $lv defined $rv
Truth table33%1/3
A and B
A= defined $lvB= defined $rv
ABresult
0X0
100
111
3809 40 ▶ my $n = (($lv =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/));
Condition33%1/3
$lv =~ /^-?\d+\.?\d*$/ && $rv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
0040
MC/DC0%0/2
$lv =~ /^-?\d+\.?\d*$/ && $rv =~ /^-?\d+\.?\d*$/
$lv =~ /^-?\d+\.?\d*$/ $rv =~ /^-?\d+\.?\d*$/
Truth table33%1/3
A && B
A= $lv =~ /^-?\d+\.?\d*$/B= $rv =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
3810 40 ▶ return $n ? ($lv == $rv) : ($lv eq $rv) if $op eq '=';
Branch: 2 branches
BranchTrueFalseTotal
if $op eq "=" 5 35 40
$n ? : 5 0 5
3811 35 ▶ return $n ? ($lv != $rv) : ($lv ne $rv) if $op =~ /^(!|<>)/;
Branch: 2 branches
BranchTrueFalseTotal
if $op =~ /^(!|<>)/ 0 35 35
$n ? : 0 0 0
3812 35 ▶ return $n ? ($lv < $rv) : ($lv lt $rv) if $op eq '<';
Branch: 2 branches
BranchTrueFalseTotal
if $op eq "<" 10 25 35
$n ? : 10 0 10
3813 25 ▶ return $n ? ($lv > $rv) : ($lv gt $rv) if $op eq '>';
Branch: 2 branches
BranchTrueFalseTotal
if $op eq ">" 1 24 25
$n ? : 1 0 1
3814 24 ▶ return $n ? ($lv <= $rv) : ($lv le $rv) if $op eq '<=';
Branch: 2 branches
BranchTrueFalseTotal
if $op eq "<=" 5 19 24
$n ? : 5 0 5
3815 19 ▶ return $n ? ($lv >= $rv) : ($lv ge $rv) if $op eq '>=';
Branch: 2 branches
BranchTrueFalseTotal
if $op eq ">=" 19 0 19
$n ? : 19 0 19
3816 }
3817 0 ▶ if ($expr =~ /^(.+)\s+IS\s+(NOT\s+)?NULL$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(.+)\s+IS\s+(NOT\s+)?NULL$/is) 0 0 0
3818 0 my $v = eval_expr($1, $row);
3819 0 ▶ return $2 ? (defined($v) && ($v ne '')) : (!defined($v) || ($v eq ''));
Branch: 1 branch
BranchTrueFalseTotal
$2 ? : 0 0 0
Condition0%0/6
defined $v and $v ne ""
!ll&&!rl&&r
000
not defined $v or $v eq ""
l!l&&r!l&&!r
000
MC/DC0%0/2
defined $v and $v ne ""
defined $v $v ne ""
MC/DC0%0/2
not defined $v or $v eq ""
not defined $v $v eq ""
Truth table0%0/3
A and B
A= defined $vB= $v ne ""
ABresult
0X0
100
111
Truth table0%0/3
not(A) or B
A= not defined $vB= $v eq ""
ABresult
1X1
011
000
3820 }
3821 0 return 0;
3822 }
3823  
3824 # Argument splitter (handles parentheses and string literals)
3825 sub args {
3826 607 ▶ my($str) = @_;
Subroutine args: called CC=12 SCAR=24.9
Pod undocumented
3827 607 my @parts;
3828 607 my $cur = '';
3829 607 my $d = 0;
3830 607 my $in_q = 0;
3831 607 for my $ch (split //, $str) {
3832 3699 ▶ if (($ch eq "'") && !$in_q) {
Branch: 6 branches
BranchTrueFalseTotal
if ($ch eq q['] and not $in_q) { } 29 3670 3699
elsif ($ch eq q['] and $in_q) { } 29 3641 3670
elsif ($in_q) { } 139 3502 3641
elsif ($ch eq '(') { } 70 3432 3502
elsif ($ch eq ')') { } 70 3362 3432
elsif ($ch eq ',' and $d == 0) { } 155 3207 3362
Condition100%3/3
$ch eq "'" and not $in_q
!ll&&!rl&&r
36412929
MC/DC100%2/2
$ch eq "'" and not $in_q
$ch eq "'" not $in_q
Truth table100%3/3
A and not(B)
A= $ch eq "'"B= not $in_q
ABresult
0X0
100
111
3833 29 $in_q = 1;
3834 29 $cur .= $ch;
3835 }
3836 ▶ elsif (($ch eq "'") && $in_q) {
Condition66%2/3
$ch eq "'" and $in_q
!ll&&!rl&&r
3641029
MC/DC50%1/2
$ch eq "'" and $in_q
$ch eq "'" $in_q
Truth table66%2/3
A and B
A= $ch eq "'"B= $in_q
ABresult
0X0
100
111
3837 29 $in_q = 0;
3838 29 $cur .= $ch;
3839 }
3840 elsif ($in_q) {
3841 139 $cur .= $ch;
3842 }
3843 elsif ($ch eq '(') {
3844 70 $d++;
3845 70 $cur .= $ch;
3846 }
3847 elsif ($ch eq ')') {
3848 70 $d--;
3849 70 $cur .= $ch;
3850 }
3851 ▶ elsif (($ch eq ',') && ($d == 0)) {
Condition100%3/3
$ch eq "," and $d == 0
!ll&&!rl&&r
32016155
MC/DC100%2/2
$ch eq "," and $d == 0
$ch eq "," $d == 0
Truth table100%3/3
A and B
A= $ch eq ","B= $d == 0
ABresult
0X0
100
111
3852 155 push @parts, $cur;
3853 155 $cur = '';
3854 }
3855 else {
3856 3207 $cur .= $ch;
3857 }
3858 }
3859 607 ▶ push @parts, $cur if $cur =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $cur =~ /\S/ 607 0 607
3860 607 return @parts;
3861 }
3862  
3863 # Find rightmost binary operator at depth 0
3864 sub find_binop {
3865 16707 ▶ my($expr, $op_pat) = @_;
Subroutine find_binop: called CC=14 SCAR=27.2
Pod undocumented
3866 16707 my $d = 0;
3867 16707 my $in_q = 0;
3868 16707 my $best = undef;
3869 16707 for my $i (0 .. length($expr)-1) {
3870 47624 my $ch = substr($expr, $i, 1);
3871 47624 ▶ if (($ch eq "'") && !$in_q) {
Branch: 5 branches
BranchTrueFalseTotal
if ($ch eq q['] and not $in_q) { } 2 47622 47624
elsif ($ch eq q['] and $in_q) { } 2 47620 47622
elsif (not $in_q and $ch eq '(') { } 0 47620 47620
elsif (not $in_q and $ch eq ')') { } 0 47620 47620
elsif (not $in_q and $d == 0 and $i > 0) { } 30911 16711 47622
Condition100%3/3
$ch eq "'" and not $in_q
!ll&&!rl&&r
4762022
MC/DC100%2/2
$ch eq "'" and not $in_q
$ch eq "'" not $in_q
Truth table100%3/3
A and not(B)
A= $ch eq "'"B= not $in_q
ABresult
0X0
100
111
3872 2 $in_q = 1;
3873 }
3874 ▶ elsif (($ch eq "'") && $in_q) {
Condition66%2/3
$ch eq "'" and $in_q
!ll&&!rl&&r
4762002
MC/DC50%1/2
$ch eq "'" and $in_q
$ch eq "'" $in_q
Truth table66%2/3
A and B
A= $ch eq "'"B= $in_q
ABresult
0X0
100
111
3875 2 $in_q = 0;
3876 }
3877 ▶ elsif (!$in_q && ($ch eq '(')) {
Condition66%2/3
not $in_q and $ch eq "("
!ll&&!rl&&r
2476180
MC/DC0%0/2
not $in_q and $ch eq "("
not $in_q $ch eq "("
Truth table66%2/3
not(A) and B
A= not $in_qB= $ch eq "("
ABresult
0X0
100
111
3878 0 $d++;
3879 }
3880 ▶ elsif (!$in_q && ($ch eq ')')) {
Condition66%2/3
not $in_q and $ch eq ")"
!ll&&!rl&&r
2476180
MC/DC0%0/2
not $in_q and $ch eq ")"
not $in_q $ch eq ")"
Truth table66%2/3
not(A) and B
A= not $in_qB= $ch eq ")"
ABresult
0X0
100
111
3881 0 $d--;
3882 }
3883 ▶ elsif (!$in_q && ($d == 0) && ($i > 0)) {
Condition83%5/6
not $in_q and $d == 0 and $i > 0
!ll&&!rl&&r
21670730911
not $in_q and $d == 0
!ll&&!rl&&r
2047618
MC/DC66%2/3
not $in_q and $d == 0 and $i > 0
not $in_q $d == 0 $i > 0
Truth table75%3/4
not(A) and B and C
A= not $in_qB= $d == 0C= $i > 0
ABCresult
0XX0
10X0
1100
1111
3884 30911 ▶ if (substr($expr, $i) =~ /^($op_pat)/) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($expr, $i) =~ /^($op_pat)/) 37 30874 30911
3885 37 $best = { s=>$i, l=>length($1) };
3886 }
3887 }
3888 }
3889 16707 return $best;
3890 }
3891  
3892 # =============================================================================
3893 # WHERE engine where_sub($expr) -> coderef
3894 # =============================================================================
3895 sub where_sub {
3896 479 ▶ my($expr) = @_;
Subroutine where_sub: called CC=3 SCAR=13.3
Pod undocumented
3897 479 ▶ return sub{1} unless defined($expr) && ($expr =~ /\S/);
Subroutine __ANON__: not called CC=1 SCAR=1.7
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expr and $expr =~ /\S/ 0 479 479
Condition33%1/3
defined $expr and $expr =~ /\S/
!ll&&!rl&&r
00479
MC/DC0%0/2
defined $expr and $expr =~ /\S/
defined $expr $expr =~ /\S/
Truth table33%1/3
A and B
A= defined $exprB= $expr =~ /\S/
ABresult
0X0
100
111
3898 479 return compile_tree(parse_bool($expr));
3899 }
3900  
3901 sub parse_bool {
3902 655 ▶ my($expr) = @_;
Subroutine parse_bool: called CC=6 SCAR=17.9
Pod undocumented
3903 655 $expr =~ s/^\s+|\s+$//g;
3904 655 my @or = bool_split($expr, 'OR');
3905 655 ▶ return { op=>'OR', kids=>[map{parse_bool($_)}@or] } if @or > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @or > 1 38 617 655
3906 617 my @and = bool_split($expr, 'AND');
3907 617 ▶ return { op=>'AND', kids=>[map{parse_bool($_)}@and] } if @and > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @and > 1 45 572 617
3908 572 ▶ return { op=>'NOT', kids=>[parse_bool($1)] } if $expr =~ /^NOT\s+(.+)$/si;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^NOT\s+(.+)$/is 2 570 572
3909 570 ▶ if (($expr =~ /^\((.+)\)$/s) && ($1 !~ /^\s*SELECT\b/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^\((.+)\)$/s and not $1 =~ /^\s*SELECT\b/i) 2 568 570
Condition66%2/3
$expr =~ /^\((.+)\)$/s and not $1 =~ /^\s*SELECT\b/i
!ll&&!rl&&r
56802
MC/DC50%1/2
$expr =~ /^\((.+)\)$/s and not $1 =~ /^\s*SELECT\b/i
$expr =~ /^\((.+)\)$/s not $1 =~ /^\s*SELECT\b/i
Truth table66%2/3
A and not(B)
A= $expr =~ /^\((.+)\)$/sB= not $1 =~ /^\s*SELECT\b/i
ABresult
0X0
100
111
3910 2 return parse_bool($1);
3911 }
3912 568 return { op=>'LEAF', cond=>parse_leaf($expr) };
3913 }
3914  
3915 sub bool_split {
3916 1317 ▶ my($expr, $kw) = @_;
Subroutine bool_split: called CC=19 SCAR=29.5
Pod undocumented
3917 1317 my $kl = length($kw);
3918 1317 my @parts;
3919 1317 my $cur = '';
3920 1317 my $d = 0;
3921 1317 my $in_q = 0;
3922 1317 my $i = 0;
3923 1317 my $len = length($expr);
3924 1317 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 15590 1317 16907
3925 15590 my $ch = substr($expr, $i, 1);
3926 15590 ▶ if (($ch eq "'") && !$in_q) {
Branch: 6 branches
BranchTrueFalseTotal
if ($ch eq q['] and not $in_q) { } 326 15264 15590
elsif ($ch eq q['] and $in_q) { } 326 14938 15264
elsif ($in_q) { } 1070 13868 14938
elsif ($ch eq '(') { } 168 13700 13868
elsif ($ch eq ')') { } 168 13532 13700
elsif ($d == 0 and not $in_q and uc substr($expr, $i, $kl) eq $kw and $i == 0 || substr($expr, $i - 1, 1) =~ /\s/ and $i + $kl < $len and substr($expr, $i + $kl, 1) =~ /\s/) { } 135 13397 13532
Condition100%3/3
$ch eq "'" and not $in_q
!ll&&!rl&&r
14938326326
MC/DC100%2/2
$ch eq "'" and not $in_q
$ch eq "'" not $in_q
Truth table100%3/3
A and not(B)
A= $ch eq "'"B= not $in_q
ABresult
0X0
100
111
3927 326 $in_q = 1;
3928 326 $cur .= $ch;
3929 }
3930 ▶ elsif (($ch eq "'") && $in_q) {
Condition66%2/3
$ch eq "'" and $in_q
!ll&&!rl&&r
149380326
MC/DC50%1/2
$ch eq "'" and $in_q
$ch eq "'" $in_q
Truth table66%2/3
A and B
A= $ch eq "'"B= $in_q
ABresult
0X0
100
111
3931 326 $in_q = 0;
3932 326 $cur .= $ch;
3933 }
3934 elsif ($in_q) {
3935 1070 $cur .= $ch;
3936 }
3937 elsif ($ch eq '(') {
3938 168 $d++;
3939 168 $cur .= $ch;
3940 }
3941 elsif ($ch eq ')') {
3942 168 $d--;
3943 168 $cur .= $ch;
3944 }
3945 ▶ elsif (($d == 0)
Condition88%16/18
$d == 0 and not $in_q and uc substr($expr, $i, $kl) eq $kw and $i == 0 || substr($expr, $i - 1, 1) =~ /\s/ and $i + $kl < $len and substr($expr, $i + $kl, 1) =~ /\s/
!ll&&!rl&&r
1338116135
$d == 0 and not $in_q and uc substr($expr, $i, $kl) eq $kw and $i == 0 || substr($expr, $i - 1, 1) =~ /\s/ and $i + $kl < $len
!ll&&!rl&&r
133810151
$d == 0 and not $in_q and uc substr($expr, $i, $kl) eq $kw and $i == 0 || substr($expr, $i - 1, 1) =~ /\s/
!ll&&!rl&&r
133756151
$d == 0 and not $in_q and uc substr($expr, $i, $kl) eq $kw
!ll&&!rl&&r
154311832157
$d == 0 and not $in_q
!ll&&!rl&&r
1543011989
$i == 0 or substr($expr, $i - 1, 1) =~ /\s/
l!l&&r!l&&!r
121396
MC/DC57%4/7
$d == 0 and not $in_q and uc substr($expr, $i, $kl) eq $kw and $i == 0 || substr($expr, $i - 1, 1) =~ /\s/ and $i + $kl < $len and substr($expr, $i + $kl, 1) =~ /\s/
$d == 0 not $in_q uc substr($expr, $i, $kl) eq $kw $i == 0 substr($expr, $i - 1, 1) =~ /\s/ $i + $kl < $len substr($expr, $i + $kl, 1) =~ /\s/
Truth table60%6/10
A and not(B) and C and D or E and F and G
A= $d == 0B= not $in_qC= uc substr($expr, $i, $kl) eq $kwD= $i == 0E= substr($expr, $i - 1, 1) =~ /\s/F= $i + $kl < $lenG= substr($expr, $i + $kl, 1) =~ /\s/
ABCDEFGresult
0XXXXXX0
10XXXXX0
110XXXX0
11100XX0
1111X0X0
111010X0
1111X100
11101100
1111X111
11101111
3946 && !$in_q
3947 && (uc(substr($expr, $i, $kl)) eq $kw)
3948 && (($i == 0) || (substr($expr, $i-1, 1) =~ /\s/))
3949 && (($i+$kl) < $len)
3950 && (substr($expr, $i+$kl, 1) =~ /\s/)
3951 ) {
3952  
3953 # For AND: do not split the AND inside BETWEEN x AND y
3954 135 ▶ if ($kw eq 'AND') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kw eq "AND") 56 79 135
3955 56 my $before = $cur;
3956 56 $before =~ s/^\s+|\s+$//g;
3957 56 ▶ if ($before =~ /\bBETWEEN\s+\S+\s*$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($before =~ /\bBETWEEN\s+\S+\s*$/i) 10 46 56
3958 10 $cur .= $ch;
3959 10 $i++;
3960 10 next;
3961 }
3962 }
3963 125 push @parts, $cur;
3964 125 $cur = '';
3965 125 $i += $kl;
3966 125 next;
3967 }
3968 else {
3969 13397 $cur .= $ch;
3970 }
3971 15455 $i++;
3972 }
3973 1317 push @parts, $cur;
3974 1317 @parts = grep {/\S/} @parts;
3975 1317 ▶ return @parts > 1 ? @parts : ($expr);
Branch: 1 branch
BranchTrueFalseTotal
@parts > 1 ? : 114 1203 1317
3976 }
3977  
3978 # Split $sql into alternating chunks of [ is_literal, text ] so that a
3979 # placeholder inside a quoted string is never mistaken for a bind marker.
3980 sub _split_sql_literals {
3981 3629 ▶ my($sql) = @_;
Subroutine _split_sql_literals: called CC=9 SCAR=22.0
3982 3629 my @parts;
3983 3629 my $len = length $sql;
3984 3629 my $i = 0;
3985 3629 my $cur = '';
3986 3629 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 142418 3629 146047
3987 142418 ▶ if (substr($sql, $i, 1) eq "'") {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $i, 1) eq "'") 1333 141085 142418
3988 1333 ▶ push @parts, [ 0, $cur ] if length $cur;
Branch: 1 branch
BranchTrueFalseTotal
if length $cur 1333 0 1333
3989 1333 $cur = '';
3990 1333 my $j = $i + 1;
3991 1333 ▶ while ($j < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $len) 5389 0 5389
3992 5389 ▶ if (substr($sql, $j, 1) ne "'") { $j++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $j, 1) ne "'") 4049 1340 5389
3993 1340 ▶ last unless substr($sql, $j+1, 1) eq "'";
Branch: 1 branch
BranchTrueFalseTotal
unless substr($sql, $j + 1, 1) eq "'" 1333 7 1340
3994 7 $j += 2;
3995 }
3996 1333 ▶ $j = $len if $j > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $j > $len 0 1333 1333
3997 1333 push @parts, [ 1, substr($sql, $i, $j-$i+1) ];
3998 1333 $i = $j + 1;
3999 1333 next;
4000 }
4001 141085 $cur .= substr($sql, $i, 1);
4002 141085 $i++;
4003 }
4004 3629 ▶ push @parts, [ 0, $cur ] if length $cur;
Branch: 1 branch
BranchTrueFalseTotal
if length $cur 3550 79 3629
4005 3629 return @parts;
4006 }
4007  
4008 # Collapse each run of whitespace to a single space, but leave string
4009 # literals byte for byte alone: a newline or a tab inside a literal is
4010 # part of the value, not statement layout.
4011 sub _normalize_sql_space {
4012 3111 ▶ my($sql) = @_;
Subroutine _normalize_sql_space: called CC=3 SCAR=11.0
4013 3111 my $out = '';
4014 3111 for my $part (_split_sql_literals($sql)) {
4015 5481 ▶ if ($part->[0]) { $out .= $part->[1]; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($part->[0]) 1221 4260 5481
4016 4260 my $chunk = $part->[1];
4017 4260 $chunk =~ s/\s+/ /g;
4018 4260 $out .= $chunk;
4019 }
4020 3111 return $out;
4021 }
4022  
4023 sub _strip_sql_comments {
4024 4029 ▶ my($sql) = @_;
Subroutine _strip_sql_comments: called CC=13 SCAR=25.7
4025 4029 my $out = '';
4026 4029 my $len = length($sql);
4027 4029 my $i = 0;
4028 4029 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 159122 4029 163151
4029 159122 my $ch = substr($sql, $i, 1);
4030 159122 ▶ if ($ch eq "'") {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "'") 1440 157682 159122
4031 1440 my $j = $i + 1;
4032 1440 ▶ while ($j < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $len) 5944 0 5944
4033 5944 ▶ if (substr($sql, $j, 1) ne "'") { $j++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $j, 1) ne "'") 4495 1449 5944
4034 1449 ▶ last unless substr($sql, $j+1, 1) eq "'";
Branch: 1 branch
BranchTrueFalseTotal
unless substr($sql, $j + 1, 1) eq "'" 1440 9 1449
4035 9 $j += 2;
4036 }
4037 1440 ▶ $j = $len if $j > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $j > $len 0 1440 1440
4038 1440 $out .= substr($sql, $i, $j-$i+1);
4039 1440 $i = $j + 1;
4040 1440 next;
4041 }
4042 157682 ▶ if (substr($sql, $i, 2) eq '--') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $i, 2) eq "--") 9 157673 157682
4043 9 $i += 2;
4044 9 ▶ $i++ while ($i < $len) && (substr($sql, $i, 1) ne "\n");
Branch: 1 branch
BranchTrueFalseTotal
$i < $len and substr($sql, $i, 1) ne "\n" and do { ++$i } 76 9 85
Condition66%2/3
$i < $len and substr($sql, $i, 1) ne "\n"
!ll&&!rl&&r
9076
MC/DC50%1/2
$i < $len and substr($sql, $i, 1) ne "\n"
$i < $len substr($sql, $i, 1) ne "\n"
Truth table66%2/3
A and B
A= $i < $lenB= substr($sql, $i, 1) ne "\n"
ABresult
0X0
100
111
4045 9 $out .= ' ';
4046 9 next;
4047 }
4048 157673 ▶ if (substr($sql, $i, 2) eq '/*') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $i, 2) eq "/*") 8 157665 157673
4049 8 $i += 2;
4050 8 ▶ $i++ while ($i < $len) && (substr($sql, $i, 2) ne '*/');
Branch: 1 branch
BranchTrueFalseTotal
$i < $len and substr($sql, $i, 2) ne "*/" and do { ++$i } 48 8 56
Condition100%3/3
$i < $len and substr($sql, $i, 2) ne "*/"
!ll&&!rl&&r
2648
MC/DC100%2/2
$i < $len and substr($sql, $i, 2) ne "*/"
$i < $len substr($sql, $i, 2) ne "*/"
Truth table100%3/3
A and B
A= $i < $lenB= substr($sql, $i, 2) ne "*/"
ABresult
0X0
100
111
4051 8 $i += 2;
4052 8 $out .= ' ';
4053 8 next;
4054 }
4055 157665 $out .= $ch;
4056 157665 $i++;
4057 }
4058 4029 $out =~ s/^\s+|\s+$//g;
4059 4029 return $out;
4060 }
4061  
4062 sub _like_to_re {
4063 16 ▶ my($pat) = @_;
Subroutine _like_to_re: called CC=4 SCAR=13.9
4064 16 my $re = '';
4065 16 for my $i (0 .. length($pat)-1) {
4066 59 my $ch = substr($pat, $i, 1);
4067 59 ▶ if ($ch eq '%') { $re .= '.*' }
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq '%') { } 14 45 59
elsif ($ch eq '_') { } 1 44 45
4068 1 elsif ($ch eq '_') { $re .= '.' }
4069 44 else { $re .= quotemeta($ch) }
4070 }
4071 16 return $re;
4072 }
4073  
4074 sub parse_leaf {
4075 568 ▶ my($part) = @_;
Subroutine parse_leaf: called CC=18 SCAR=28.9
Pod undocumented
4076 568 $part =~ s/^\s+|\s+$//g;
4077 568 ▶ if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) 3 565 568
4078 3 my($neg, $v) = ($1, $2);
4079 3 ▶ my $t = $v ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$v ? : 1 2 3
4080 3 ▶ $t = 1 - $t if $neg;
Branch: 1 branch
BranchTrueFalseTotal
if $neg 0 3 3
4081 3 return { op=>'CONST', val=>$t };
4082 }
4083 565 ▶ if ($part =~ /^([\w.]+)\s+(NOT\s+)?IN\s*\(([^)]*)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^([\w.]+)\s+(NOT\s+)?IN\s*\(([^)]*)\)$/is) 71 494 565
4084 71 my($col, $neg, $ls) = ($1, $2, $3);
4085 71 my @vals;
4086 71 ▶ while ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) 285 71 356
4087 285 my($sv, $nv, $nl) = ($1, $2, $3);
4088 285 ▶ if (defined $nl) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $nl) { } 3 282 285
elsif (defined $sv) { } 19 263 282
4089 3 push @vals, undef;
4090 }
4091 elsif (defined $sv) {
4092 19 (my $x = $sv) =~ s/''/'/g;
4093 19 push @vals, $x;
4094 }
4095 else {
4096 263 push @vals, $nv;
4097 }
4098 }
4099 71 ▶ return { op=>($neg ? 'NOT_IN' : 'IN'), col=>$col, vals=>[ @vals ] };
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 27 44 71
4100 }
4101 494 ▶ return { op=>'CONST', val=>0 } if $part =~ /^[\w.]+\s*(?:=|!=|<>|<=|>=|<|>)\s*NULL$/si;
Branch: 1 branch
BranchTrueFalseTotal
if $part =~ /^[\w.]+\s*(?:=|!=|<>|<=|>=|<|>)\s*NULL$/is 1 493 494
4102 493 ▶ if ($part =~ /^([\w.]+)\s+IS\s+(NOT\s+)?NULL$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^([\w.]+)\s+IS\s+(NOT\s+)?NULL$/is) 3 490 493
4103 3 ▶ return { op=>($2 ? 'IS_NOT_NULL' : 'IS_NULL'), col=>$1 };
Branch: 1 branch
BranchTrueFalseTotal
$2 ? : 2 1 3
4104 }
4105 490 ▶ if ($part =~ /^([\w.]+)\s+(NOT\s+)?BETWEEN\s+(.+?)\s+AND\s+(.+)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^([\w.]+)\s+(NOT\s+)?BETWEEN\s+(.+?)\s+AND\s+(.+)$/is) 10 480 490
4106 10 my($col, $neg, $lo, $hi) = ($1, $2, $3, $4);
4107 10 $lo =~ s/^'(.*)'$/$1/s;
4108 10 $hi =~ s/^'(.*)'$/$1/s;
4109 10 ▶ return { op=>($neg ? 'NOT_BETWEEN' : 'BETWEEN'), col=>$col, lo=>$lo, hi=>$hi };
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 1 9 10
4110 }
4111 480 ▶ if ($part =~ /^(.+?)\s+(NOT\s+)?LIKE\s+('(?:[^']|'')*'|\S+)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(.+?)\s+(NOT\s+)?LIKE\s+('(?:[^']|'')*'|\S+)$/is) 13 467 480
4112 13 my($lhs, $neg, $pat) = ($1, $2, $3);
4113 13 $pat =~ s/^'(.*)'$/$1/s;
4114 13 $pat =~ s/''/'/g;
4115 13 my $re = _like_to_re($pat);
4116 13 ▶ return { op=>($neg ? 'NOT_LIKE' : 'LIKE'), lhs=>$lhs, re=>$re };
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 2 11 13
4117 }
4118 467 ▶ if ($part =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) 467 0 467
4119 467 my($lhs, $op, $rhs) = ($1, uc($2), $3);
4120 467 $lhs =~ s/^\s+|\s+$//g;
4121 467 $rhs =~ s/^\s+|\s+$//g;
4122 467 my $rv;
4123 467 ▶ if ($rhs =~ /^'((?:[^']|'')*)'$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rhs =~ /^'((?:[^']|'')*)'$/) { } 83 384 467
4124 83 ($rv = $1) =~ s/''/'/g;
4125 }
4126 else {
4127 384 $rv = $rhs;
4128 }
4129 467 return{ op=>$op, lhs=>$lhs, rhs_expr=>$rhs, rhs_val=>$rv };
4130 }
4131 0 return{ op=>'CONST', val=>0 };
4132 }
4133  
4134 sub compile_tree {
4135 653 ▶ my($tree) = @_;
Subroutine compile_tree: called CC=4 SCAR=13.9
Pod undocumented
4136 653 my $op = $tree->{op};
4137 653 ▶ if ($op eq 'AND') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "AND") 45 608 653
4138 45 my @s = map {compile_tree($_)} @{$tree->{kids}};
4139 45 ▶ return sub { for my $s(@s) { return 0 unless $s->($_[0]) } 1 };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
unless &$s($_[0]) 292 335 627
4140 }
4141 608 ▶ if ($op eq 'OR') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "OR") 38 570 608
4142 38 my @s = map { compile_tree($_) } @{$tree->{kids}};
4143 38 ▶ return sub { for my $s(@s) { return 1 if $s->($_[0]) } 0 };
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
if &$s($_[0]) 452 465 917
4144 }
4145 570 ▶ if ($op eq 'NOT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "NOT") 2 568 570
4146 2 my $s = compile_tree($tree->{kids}[0]);
4147 2 ▶ return sub{ $s->($_[0]) ? 0 : 1 };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
&$s($_[0]) ? : 1 11 12
4148 }
4149 568 return compile_leaf($tree->{cond});
4150 }
4151  
4152 sub compile_leaf {
4153 568 ▶ my($c) = @_;
Subroutine compile_leaf: called CC=11 SCAR=24.3
Pod undocumented
4154 568 ▶ my $op = defined($c->{op}) ? $c->{op} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $c->{'op'} ? : 568 0 568
4155 568 ▶ return sub { $c->{val} ? 1 : 0 } if $op eq 'CONST';
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 2 branches
BranchTrueFalseTotal
if $op eq "CONST" 4 564 568
$c->{'val'} ? : 8 24 32
4156 564 ▶ if ($op eq 'IS_NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IS_NULL") 1 563 564
4157 1 my $col = $c->{col};
4158 1 ▶ return sub { my $v = $_[0]{$col}; !defined($v) || ($v eq '') };
Subroutine __ANON__: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
not defined $v or $v eq "" 3 0 3
4159 }
4160 563 ▶ if ($op eq 'IS_NOT_NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IS_NOT_NULL") 2 561 563
4161 2 my $col = $c->{col};
4162 2 ▶ return sub { my $v = $_[0]{$col}; defined($v) && ($v ne '') };
Subroutine __ANON__: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
defined $v and $v ne "" 6 0 6
4163 }
4164 561 ▶ if (($op eq 'BETWEEN') || ($op eq 'NOT_BETWEEN')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "BETWEEN" or $op eq "NOT_BETWEEN") 10 551 561
Condition100%3/3
$op eq "BETWEEN" or $op eq "NOT_BETWEEN"
l!l&&r!l&&!r
91551
MC/DC100%2/2
$op eq "BETWEEN" or $op eq "NOT_BETWEEN"
$op eq "BETWEEN" $op eq "NOT_BETWEEN"
Truth table100%3/3
A or B
A= $op eq "BETWEEN"B= $op eq "NOT_BETWEEN"
ABresult
1X1
011
000
4165 10 my($col, $lo, $hi, $neg) = ($c->{col}, $c->{lo}, $c->{hi}, $op eq 'NOT_BETWEEN');
4166 return sub {
4167 50 ▶ my $v = $_[0]{$col};
Subroutine __ANON__: called CC=8 SCAR=24.7
4168 50 ▶ return 0 unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 50 50
4169 50 ▶ my $n = (($v =~ /^-?\d+\.?\d*$/) && ($lo =~ /^-?\d+\.?\d*$/) && ($hi =~ /^-?\d+\.?\d*$/));
Condition33%2/6
$v =~ /^-?\d+\.?\d*$/ && $lo =~ /^-?\d+\.?\d*$/ && $hi =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
0050
$v =~ /^-?\d+\.?\d*$/ and $lo =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
0050
MC/DC0%0/3
$v =~ /^-?\d+\.?\d*$/ && $lo =~ /^-?\d+\.?\d*$/ && $hi =~ /^-?\d+\.?\d*$/
$v =~ /^-?\d+\.?\d*$/ $lo =~ /^-?\d+\.?\d*$/ $hi =~ /^-?\d+\.?\d*$/
Truth table25%1/4
A and B && C
A= $v =~ /^-?\d+\.?\d*$/B= $lo =~ /^-?\d+\.?\d*$/C= $hi =~ /^-?\d+\.?\d*$/
ABCresult
0XX0
10X0
1100
1111
4170 50 ▶ my $in_q = $n ? (($v>=$lo) && ($v<=$hi)) : (($v ge $lo) && ($v le $hi));
Branch: 1 branch
BranchTrueFalseTotal
$n ? : 50 0 50
Condition50%3/6
$v >= $lo and $v <= $hi
!ll&&!rl&&r
6836
$v ge $lo and $v le $hi
!ll&&!rl&&r
000
MC/DC100%2/2
$v >= $lo and $v <= $hi
$v >= $lo $v <= $hi
MC/DC0%0/2
$v ge $lo and $v le $hi
$v ge $lo $v le $hi
Truth table100%3/3
A and B
A= $v >= $loB= $v <= $hi
ABresult
0X0
100
111
Truth table0%0/3
A and B
A= $v ge $loB= $v le $hi
ABresult
0X0
100
111
4171 50 ▶ $neg ? !$in_q : $in_q;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 4 46 50
4172 10 };
4173 }
4174 551 ▶ if (($op eq 'IN') || ($op eq 'NOT_IN')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IN" or $op eq "NOT_IN") 71 480 551
Condition100%3/3
$op eq "IN" or $op eq "NOT_IN"
l!l&&r!l&&!r
4427480
MC/DC100%2/2
$op eq "IN" or $op eq "NOT_IN"
$op eq "IN" $op eq "NOT_IN"
Truth table100%3/3
A or B
A= $op eq "IN"B= $op eq "NOT_IN"
ABresult
1X1
011
000
4175 71 my($col, $vals, $neg) = ($c->{col}, $c->{vals}, $op eq 'NOT_IN');
4176 return sub {
4177 791 ▶ my $rv = defined($_[0]{$col}) ? $_[0]{$col} : '';
Subroutine __ANON__: called CC=11 SCAR=24.0
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0]{$col} ? : 791 0 791
4178 791 my $f = 0;
4179 791 my $has_null = 0;
4180 791 for my $cv (@$vals) {
4181 11824 ▶ unless (defined $cv) { $has_null = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cv) 22 11802 11824
4182 11802 ▶ my $n = (($rv =~ /^-?\d+\.?\d*$/) && ($cv =~ /^-?\d+\.?\d*$/));
Condition100%3/3
$rv =~ /^-?\d+\.?\d*$/ && $cv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
67811727
MC/DC100%2/2
$rv =~ /^-?\d+\.?\d*$/ && $cv =~ /^-?\d+\.?\d*$/
$rv =~ /^-?\d+\.?\d*$/ $cv =~ /^-?\d+\.?\d*$/
Truth table100%3/3
A && B
A= $rv =~ /^-?\d+\.?\d*$/B= $cv =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
4183 11802 ▶ if ($n ? ($rv == $cv) : ($rv eq $cv)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($n ? $rv == $cv : $rv eq $cv) 161 11641 11802
$n ? : 11727 75 11802
4184 161 $f = 1;
4185 161 last;
4186 }
4187 }
4188 # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN
4189 # when value not found -> treat as false (exclude the row).
4190 791 ▶ return 0 if $neg && $has_null && !$f;
Branch: 1 branch
BranchTrueFalseTotal
if $neg and $has_null and not $f 6 785 791
Condition100%6/6
$neg and $has_null and not $f
!ll&&!rl&&r
78416
$neg and $has_null
!ll&&!rl&&r
5502347
MC/DC100%3/3
$neg and $has_null and not $f
$neg $has_null not $f
Truth table100%4/4
A and B and not(C)
A= $negB= $has_nullC= not $f
ABCresult
0XX0
10X0
1100
1111
4191 785 ▶ $neg ? !$f : $f;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 235 550 785
4192 71 };
4193 }
4194 480 ▶ if (($op eq 'LIKE') || ($op eq 'NOT_LIKE')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "LIKE" or $op eq "NOT_LIKE") 13 467 480
Condition100%3/3
$op eq "LIKE" or $op eq "NOT_LIKE"
l!l&&r!l&&!r
112467
MC/DC100%2/2
$op eq "LIKE" or $op eq "NOT_LIKE"
$op eq "LIKE" $op eq "NOT_LIKE"
Truth table100%3/3
A or B
A= $op eq "LIKE"B= $op eq "NOT_LIKE"
ABresult
1X1
011
000
4195 13 my($lhs, $re, $neg) = ($c->{lhs}, $c->{re}, $op eq 'NOT_LIKE');
4196 return sub {
4197 69 ▶ my $v = eval_expr($lhs, $_[0]);
Subroutine __ANON__: called CC=4 SCAR=13.9
4198 69 ▶ $v = '' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 69 69
4199 69 ▶ my $m = ($v =~ /^$re$/si) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$v =~ /^$re$/is ? : 19 50 69
4200 69 ▶ $neg ? !$m : $m;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 9 60 69
4201 13 };
4202 }
4203 467 my($lhs, $op2, $rv_lit, $rhs_expr) = @{$c}{qw(lhs op rhs_val rhs_expr)};
4204 return sub {
4205 2319 ▶ my $row = $_[0];
Subroutine __ANON__: called CC=18 SCAR=30.3
4206 2319 my $lv = eval_expr($lhs, $row);
4207 2319 ▶ return 0 unless defined $lv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv 0 2319 2319
4208 2319 ▶ my $rv = (($rhs_expr =~ /^[\w.]+$/) && ($rhs_expr !~ /^-?\d+\.?\d*$/)) ? eval_expr($rhs_expr, $row) : $rv_lit;
Branch: 1 branch
BranchTrueFalseTotal
$rhs_expr =~ /^[\w.]+$/ && !($rhs_expr =~ /^-?\d+\.?\d*$/) ? : 0 2319 2319
Condition66%2/3
$rhs_expr =~ /^[\w.]+$/ and not $rhs_expr =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
66816510
MC/DC0%0/2
$rhs_expr =~ /^[\w.]+$/ and not $rhs_expr =~ /^-?\d+\.?\d*$/
$rhs_expr =~ /^[\w.]+$/ not $rhs_expr =~ /^-?\d+\.?\d*$/
Truth table66%2/3
A and not(B)
A= $rhs_expr =~ /^[\w.]+$/B= not $rhs_expr =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
4209 2319 ▶ $rv = '' unless defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 0 2319 2319
4210 2319 ▶ my $n = (($lv =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/));
Condition100%3/3
$lv =~ /^-?\d+\.?\d*$/ && $rv =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
65151663
MC/DC100%2/2
$lv =~ /^-?\d+\.?\d*$/ && $rv =~ /^-?\d+\.?\d*$/
$lv =~ /^-?\d+\.?\d*$/ $rv =~ /^-?\d+\.?\d*$/
Truth table100%3/3
A && B
A= $lv =~ /^-?\d+\.?\d*$/B= $rv =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
4211 2319 ▶ return $n ? ($lv == $rv) : ($lv eq $rv) if $op2 eq '=';
Branch: 2 branches
BranchTrueFalseTotal
if $op2 eq "=" 1559 760 2319
$n ? : 913 646 1559
4212 760 ▶ return $n ? ($lv != $rv) : ($lv ne $rv) if $op2 =~ /^(!|<>)/;
Branch: 2 branches
BranchTrueFalseTotal
if $op2 =~ /^(!|<>)/ 18 742 760
$n ? : 8 10 18
4213 742 ▶ return $n ? ($lv < $rv) : ($lv lt $rv) if $op2 eq '<';
Branch: 2 branches
BranchTrueFalseTotal
if $op2 eq "<" 73 669 742
$n ? : 73 0 73
4214 669 ▶ return $n ? ($lv > $rv) : ($lv gt $rv) if $op2 eq '>';
Branch: 2 branches
BranchTrueFalseTotal
if $op2 eq ">" 415 254 669
$n ? : 415 0 415
4215 254 ▶ return $n ? ($lv <= $rv) : ($lv le $rv) if $op2 eq '<=';
Branch: 2 branches
BranchTrueFalseTotal
if $op2 eq "<=" 123 131 254
$n ? : 123 0 123
4216 131 ▶ return $n ? ($lv >= $rv) : ($lv ge $rv) if $op2 eq '>=';
Branch: 2 branches
BranchTrueFalseTotal
if $op2 eq ">=" 131 0 131
$n ? : 131 0 131
4217 0 return 0;
4218 467 };
4219 }
4220  
4221 # =============================================================================
4222 # SELECT dispatcher
4223 # =============================================================================
4224 sub select {
4225 739 ▶ my($self, $sql) = @_;
Subroutine select: called CC=121 SCAR=54.3
Pod documented
4226 # Window functions are not supported; detect and reject early.
4227 # Strip string literals before checking to avoid false positives.
4228 739 my $sql_nostr = $sql;
4229 739 $sql_nostr =~ s/'(?:[^']|'')*'/''/g;
4230 739 ▶ if ($sql_nostr =~ /\bOVER\s*\(/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql_nostr =~ /\bOVER\s*\(/i) 7 732 739
4231 7 return $self->_err(
4232 "Window functions (OVER clause) are not supported. "
4233 . "Use GROUP BY with aggregate functions instead."
4234 );
4235 }
4236 732 my @up = split_union($sql);
4237 732 ▶ return $self->exec_union([ @up ]) if @up > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @up > 1 38 694 732
4238 694 ▶ if ($sql =~ /\bJOIN\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\bJOIN\b/i) 89 605 694
4239  
4240 # Parse GROUP BY / HAVING from the SQL before handing off to _parse_join_sql
4241 89 my $join_sql = $sql;
4242 89 my(@gb_join, $having_join);
4243 89 $having_join = '';
4244 89 ▶ if ($join_sql =~ s/\bHAVING\s+(.+?)(?=\s*(?:ORDER\s+BY|LIMIT|OFFSET|$))//si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($join_sql =~ s/\bHAVING\s+(.+?)(?=\s*(?:ORDER\s+BY|LIMIT|OFFSET|$))//is) 0 89 89
4245 0 $having_join = $1;
4246 0 $having_join =~ s/^\s+|\s+$//g;
4247 }
4248 89 ▶ if ($join_sql =~ s/\bGROUP\s+BY\s+(.+?)(?=\s*(?:HAVING|ORDER\s+BY|LIMIT|OFFSET|$))//si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($join_sql =~ s/\bGROUP\s+BY\s+(.+?)(?=\s*(?:HAVING|ORDER\s+BY|LIMIT|OFFSET|$))//is) 6 83 89
4249 6 my $gbs = $1;
4250 6 $gbs =~ s/^\s+|\s+$//g;
4251 6 @gb_join = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $gbs;
4252 }
4253 89 my $has_agg = ($sql =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/si);
4254 89 ▶ my $needs_groupby = (@gb_join || ($having_join ne '') || $has_agg);
Condition66%4/6
@gb_join || $having_join ne '' || $has_agg
l!l&&r!l&&!r
6083
@gb_join or $having_join ne ""
l!l&&r!l&&!r
6083
MC/DC33%1/3
@gb_join || $having_join ne '' || $has_agg
@gb_join $having_join ne "" $has_agg
Truth table50%2/4
A or B || C
A= @gb_joinB= $having_join ne ""C= $has_agg
ABCresult
1XX1
01X1
0011
0000
4255  
4256 89 my $parsed = _parse_join_sql($join_sql);
4257  
4258 # A JOIN construct the parser cannot execute is reported here rather
4259 # than left to fall through to the single-table parser, which used to
4260 # accept it and return rows that answered a different question.
4261 89 ▶ if ($parsed && ($parsed->[4] ne '')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsed and $parsed->[4] ne "") 16 73 89
Condition66%2/3
$parsed and $parsed->[4] ne ""
!ll&&!rl&&r
07316
MC/DC50%1/2
$parsed and $parsed->[4] ne ""
$parsed $parsed->[4] ne ""
Truth table66%2/3
A and B
A= $parsedB= $parsed->[4] ne ""
ABresult
0X0
100
111
4262 16 return { type=>'error', message=>$parsed->[4] };
4263 }
4264 73 ▶ if ($parsed && $parsed->[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if ($parsed and $parsed->[0]) 73 0 73
Condition33%1/3
$parsed and $parsed->[0]
!ll&&!rl&&r
0073
MC/DC0%0/2
$parsed and $parsed->[0]
$parsed $parsed->[0]
Truth table33%1/3
A and B
A= $parsedB= $parsed->[0]
ABresult
0X0
100
111
4265 73 my($js, $cs, $wc, $opts) = @$parsed;
4266  
4267 # ORDER BY <position>: resolve against the select list. In the
4268 # aggregate branch the sort runs on projected rows keyed by
4269 # alias, in the plain branch on raw rows keyed by expression.
4270 my @sel_names =
4271 73 ▶ map { $needs_groupby ? _order_alias_of($_) : _order_name_of($_) } @$cs;
Branch: 1 branch
BranchTrueFalseTotal
$needs_groupby ? : 13 106 119
4272 73 ▶ my @ob_keys = $opts->{order_keys} ? @{$opts->{order_keys}} : ();
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'order_keys'} ? : 31 42 73
4273 73 for my $k (@ob_keys) {
4274 34 my($obe, $obk) = _resolve_order_ordinal_scalar($k->[0], [ @sel_names ]);
4275 34 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 0 34 34
4276 34 ▶ $k->[0] = $obk if defined $obk;
Branch: 1 branch
BranchTrueFalseTotal
if defined $obk 34 0 34
4277 }
4278 73 ▶ if (@ob_keys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ob_keys) 31 42 73
4279 31 $opts->{order_keys} = [ @ob_keys ];
4280 31 $opts->{order_by} = $ob_keys[0][0];
4281 31 $opts->{order_dir} = $ob_keys[0][1];
4282 }
4283  
4284 # If GROUP BY / HAVING / aggregate: fetch raw rows with SELECT *
4285 73 my $rows;
4286 73 ▶ if ($needs_groupby) {
Branch: 1 branch
BranchTrueFalseTotal
if ($needs_groupby) { } 6 67 73
4287  
4288 # Fetch all columns as raw data for aggregation
4289 6 my $raw_opts = {%$opts};
4290 6 delete $raw_opts->{order_by};
4291 6 delete $raw_opts->{order_dir};
4292 6 delete $raw_opts->{order_keys};
4293 6 delete $raw_opts->{limit};
4294 6 delete $raw_opts->{offset};
4295 6 delete $raw_opts->{distinct};
4296 6 $rows = $self->join_select($js, [], $wc, $raw_opts);
4297 }
4298 else {
4299 67 $rows = $self->join_select($js, $cs, $wc, $opts);
4300 }
4301 73 ▶ return{ type=>'error', message=>$errstr } unless $rows;
Branch: 1 branch
BranchTrueFalseTotal
unless $rows 8 65 73
4302  
4303 65 ▶ if ($needs_groupby) {
Branch: 1 branch
BranchTrueFalseTotal
if ($needs_groupby) 6 59 65
4304  
4305 # Parse col_specs from the original SQL for aggregate evaluation
4306 6 my @col_specs_raw;
4307 6 ▶ if ($sql =~ /^SELECT\s+(.+?)\s+FROM\b/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SELECT\s+(.+?)\s+FROM\b/is) 6 0 6
4308 6 my $cs_str = $1;
4309 6 for my $c (split /\s*,\s*/, $cs_str) {
4310 13 $c =~ s/^\s+|\s+$//g;
4311 13 ▶ if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/is) { } 4 9 13
4312 4 push @col_specs_raw, [ $1, $2 ];
4313 }
4314 else {
4315 9 ▶ my $alias = ($c =~ /^(\w+)\.(\w+)$/) ? $2 : $c;
Branch: 1 branch
BranchTrueFalseTotal
$c =~ /^(\w+)\.(\w+)$/ ? : 5 4 9
4316 9 push @col_specs_raw, [ $c, $alias ];
4317 }
4318 }
4319 }
4320  
4321 # Group rows
4322 6 my(%gr, @go);
4323 6 ▶ if (@gb_join) {
Branch: 1 branch
BranchTrueFalseTotal
if (@gb_join) { } 6 0 6
4324 6 for my $row (@$rows) {
4325  
4326 # resolve GROUP BY key: try qualified then unqualified
4327 my $k = join("\x00", map {
4328 21 my $col = $_;
4329 my $v = defined($row->{$col})
4330 ? $row->{$col}
4331 : (($col =~ /^(\w+)\.(\w+)$/) && defined $row->{$2})
4332 21 ▶ ? $row->{$2}
Branch: 2 branches
BranchTrueFalseTotal
defined $row->{$col} ? : 21 0 21
$col =~ /^(\w+)\.(\w+)$/ && defined $row->{$2} ? : 0 0 0
Condition0%0/3
$col =~ /^(\w+)\.(\w+)$/ and defined $row->{$2}
!ll&&!rl&&r
000
MC/DC0%0/2
$col =~ /^(\w+)\.(\w+)$/ and defined $row->{$2}
$col =~ /^(\w+)\.(\w+)$/ defined $row->{$2}
Truth table0%0/3
A and B
A= $col =~ /^(\w+)\.(\w+)$/B= defined $row->{$2}
ABresult
0X0
100
111
4333 : '';
4334 21 ▶ defined($v) ? $v : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 21 0 21
4335 } @gb_join);
4336 21 ▶ push @go, $k unless exists $gr{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $gr{$k} 10 11 21
4337 21 push @{$gr{$k}}, $row;
4338 }
4339 }
4340 else {
4341 0 @go = ('__all__');
4342 0 $gr{__all__} = $rows;
4343 }
4344  
4345 6 my @results;
4346 6 for my $gk (@go) {
4347 10 my $grp = $gr{$gk};
4348 10 my $rep = $grp->[0];
4349 10 my %out;
4350 10 for my $spec (@col_specs_raw) {
4351 23 my($expr, $alias) = @$spec;
4352 23 $out{$alias} = eval_agg($expr, $grp, $rep);
4353 }
4354 10 ▶ if ($having_join ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($having_join ne "") 0 10 10
4355 0 my $h = $having_join;
4356 0 my $cnt = scalar @$grp;
4357 0 $h =~ s/COUNT\s*\(\s*\*\s*\)/$cnt/gsi;
4358 0 $h =~ s/\b(SUM|AVG|MIN|MAX|COUNT)\s*\(([^)]+)\)/eval_agg("$1($2)", $grp, $rep)/geis;
4359 0 ▶ next unless where_sub($h)->({ %out });
Branch: 1 branch
BranchTrueFalseTotal
unless where_sub($h)->({%out}) 0 0 0
4360 }
4361 10 push @results, { %out };
4362 }
4363  
4364 # ORDER BY from opts (every key, in order)
4365 3 ▶ my @gob = $opts->{order_keys} ? @{$opts->{order_keys}}
Branch: 1 branch
BranchTrueFalseTotal
defined $opts->{'order_by'} ? : 0 3 3
Condition0%0/2
$opts->{'order_dir'} || 'ASC'
l!l
00
MC/DC0%0/1
$opts->{'order_dir'} || 'ASC'
$opts->{'order_dir'}
Truth table0%0/2
A
A= $opts->{'order_dir'}
Aresult
11
00
4366 : (defined($opts->{order_by})
4367 6 ▶ ? ([ $opts->{order_by}, ($opts->{order_dir} || 'ASC') ])
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'order_keys'} ? : 3 3 6
4368 : ());
4369 6 ▶ if (@gob && @results) {
Branch: 1 branch
BranchTrueFalseTotal
if (@gob and @results) 3 3 6
Condition66%2/3
@gob and @results
!ll&&!rl&&r
303
MC/DC50%1/2
@gob and @results
@gob @results
Truth table66%2/3
A and B
A= @gobB= @results
ABresult
0X0
100
111
4370  
4371 # An aggregate result row is keyed by the select-list
4372 # alias, so "ORDER BY a.y" over "SELECT a.y, COUNT(*)"
4373 # has to resolve to the key 'y'. Before 1.09 it resolved
4374 # to nothing and the sort quietly did not happen.
4375 3 for my $k (@gob) {
4376 3 ▶ next if exists $results[0]{$k->[0]};
Branch: 1 branch
BranchTrueFalseTotal
if exists $results[0]{$k->[0]} 0 3 3
4377 3 ▶ if (($k->[0] =~ /^\w+\.(\w+)$/) && exists($results[0]{$1})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k->[0] =~ /^\w+\.(\w+)$/ and exists $results[0]{$1}) 2 1 3
Condition66%2/3
$k->[0] =~ /^\w+\.(\w+)$/ and exists $results[0]{$1}
!ll&&!rl&&r
012
MC/DC50%1/2
$k->[0] =~ /^\w+\.(\w+)$/ and exists $results[0]{$1}
$k->[0] =~ /^\w+\.(\w+)$/ exists $results[0]{$1}
Truth table66%2/3
A and B
A= $k->[0] =~ /^\w+\.(\w+)$/B= exists $results[0]{$1}
ABresult
0X0
100
111
4378 2 $k->[0] = $1;
4379 2 next;
4380 }
4381 1 return { type=>'error', message=>
4382 "ORDER BY column '$k->[0]' is not in the select "
4383 . "list of this aggregate query" };
4384 }
4385 }
4386 5 ▶ if (@gob) {
Branch: 1 branch
BranchTrueFalseTotal
if (@gob) 2 3 5
4387 @results = sort {
4388 2 my $cmp = 0;
4389 4 for my $k (@gob) {
4390 4 my($key, $dir) = @$k;
4391 4 ▶ my $va = defined($a->{$key}) ? $a->{$key} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::a->{$key} ? : 4 0 4
4392 4 ▶ my $vb = defined($b->{$key}) ? $b->{$key} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::b->{$key} ? : 4 0 4
4393 4 ▶ my $c = (($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/))
Branch: 1 branch
BranchTrueFalseTotal
$va =~ /^-?\d+\.?\d*$/ && $vb =~ /^-?\d+\.?\d*$/ ? : 1 3 4
Condition66%2/3
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
301
MC/DC50%1/2
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
$va =~ /^-?\d+\.?\d*$/ $vb =~ /^-?\d+\.?\d*$/
Truth table66%2/3
A and B
A= $va =~ /^-?\d+\.?\d*$/B= $vb =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
4394 ? ($va <=> $vb)
4395 : ($va cmp $vb);
4396 4 ▶ $c = -$c if lc($dir) eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if lc $dir eq "desc" 1 3 4
4397 4 ▶ if ($c != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c != 0) 4 0 4
4398 4 $cmp = $c;
4399 4 last;
4400 }
4401 }
4402 $cmp;
4403 } @results;
4404 }
4405 5 ▶ if (defined($opts->{offset}) && ($opts->{offset} > 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts->{"offset"} and $opts->{"offset"} > 0) 0 5 5
Condition33%1/3
defined $opts->{"offset"} and $opts->{"offset"} > 0
!ll&&!rl&&r
500
MC/DC0%0/2
defined $opts->{"offset"} and $opts->{"offset"} > 0
defined $opts->{"offset"} $opts->{"offset"} > 0
Truth table33%1/3
A and B
A= defined $opts->{"offset"}B= $opts->{"offset"} > 0
ABresult
0X0
100
111
4406 0 @results = splice(@results, $opts->{offset});
4407 }
4408 5 ▶ if (defined $opts->{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts->{"limit"}) 0 5 5
4409 0 my $l = $opts->{limit} - 1;
4410 0 ▶ $l = $#results if $l > $#results;
Branch: 1 branch
BranchTrueFalseTotal
if $l > $#results 0 0 0
4411 0 @results = @results[0 .. $l];
4412 }
4413 5 return { type=>'rows', data=>[ @results ] };
4414 }
4415 59 return { type=>'rows', data=>$rows };
4416 }
4417 }
4418 605 ▶ my $p = $self->parse_select($sql) or return { type=>'error', message=>"Cannot parse SELECT: $sql" };
Branch: 1 branch
BranchTrueFalseTotal
my $p = $self->parse_select($sql) or return {"type", "error", "message", "Cannot parse SELECT: $sql"} 0 605 605
4419 605 my($distinct, $col_specs, $tbl, $where_expr, $gb, $having, $ob, $limit, $offset) = @$p;
4420 605 ▶ my $needs_agg = (@$gb || ($having ne '') || grep { $_->[0] =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/si } @$col_specs);
Condition83%5/6
@$gb || $having ne '' || grep({$_->[0] =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/is;} @$col_specs)
l!l&&r!l&&!r
1223570
@$gb or $having ne ""
l!l&&r!l&&!r
120593
MC/DC66%2/3
@$gb || $having ne '' || grep({$_->[0] =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/is;} @$col_specs)
@$gb $having ne "" grep({$_->[0] =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/is;} @$col_specs)
Truth table75%3/4
A or B || C
A= @$gbB= $having ne ""C= grep({$_->[0] =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/is;} @$col_specs)
ABCresult
1XX1
01X1
0011
0000
4421 605 ▶ return $self->exec_groupby($tbl, $col_specs, $where_expr, $gb, $having, $ob, $limit, $offset) if $needs_agg;
Branch: 1 branch
BranchTrueFalseTotal
if $needs_agg 35 570 605
4422 570 ▶ my $sch = $self->_load_schema($tbl) or return { type=>'error', message=>$errstr };
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($tbl) or return {"type", "error", "message", $DB::Handy::errstr} 7 563 570
4423 563 my $obe = _resolve_order_ordinals($ob, $col_specs, $sch);
4424 563 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 3 560 563
4425 560 my $dat = $self->_file($tbl, 'dat');
4426 560 my $ws;
4427 560 ▶ if ($where_expr ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($where_expr ne "") 414 146 560
4428 # Case 1: single condition col OP val (no AND/OR/NOT/BETWEEN/IN)
4429 414 ▶ if (($where_expr =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/)
Branch: 1 branch
BranchTrueFalseTotal
if ($where_expr =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/ and not $where_expr =~ /\b(?:OR|AND|NOT|BETWEEN|IN)\b/i) 235 179 414
Condition66%2/3
$where_expr =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/ and not $where_expr =~ /\b(?:OR|AND|NOT|BETWEEN|IN)\b/i
!ll&&!rl&&r
1790235
MC/DC50%1/2
$where_expr =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/ and not $where_expr =~ /\b(?:OR|AND|NOT|BETWEEN|IN)\b/i
$where_expr =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/ not $where_expr =~ /\b(?:OR|AND|NOT|BETWEEN|IN)\b/i
Truth table66%2/3
A and not(B)
A= $where_expr =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/B= not $where_expr =~ /\b(?:OR|AND|NOT|BETWEEN|IN)\b/i
ABresult
0X0
100
111
4430 && ($where_expr !~ /\b(?:OR|AND|NOT|BETWEEN|IN)\b/i)
4431 ) {
4432 235 my($col, $op, $sv, $nv) = ($1, $2, $3, $4);
4433 235 ▶ my $cond = [{ col=>$col, op=>uc($op), val=>defined($sv) ? $sv : $nv }];
Branch: 1 branch
BranchTrueFalseTotal
defined $sv ? : 30 205 235
4434 235 my $idx = $self->_find_index_for_conds($tbl, $sch, $cond);
4435 235 ▶ if (defined $idx) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx) 47 188 235
4436 47 my $wsub = where_sub($where_expr);
4437 47 my @rows;
4438 47 local *FH;
4439 47 ▶ open(FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 47 47
4440 47 binmode FH;
4441 47 _lock_sh(\*FH);
4442 47 my $rs = $sch->{recsize};
4443 47 for my $rn (sort { $a <=> $b } @$idx) {
4444 105 seek(FH, $rn*$rs, 0);
4445 105 my $raw = '';
4446 105 my $n = read(FH, $raw, $rs);
4447 105 ▶ next unless defined($n) && ($n == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $rs 0 105 105
Condition33%1/3
defined $n and $n == $rs
!ll&&!rl&&r
00105
MC/DC0%0/2
defined $n and $n == $rs
defined $n $n == $rs
Truth table33%1/3
A and B
A= defined $nB= $n == $rs
ABresult
0X0
100
111
4448 105 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 105 105
4449 105 my $row = $self->_unpack_record($sch, $raw);
4450 105 ▶ push @rows, $row if !$wsub || $wsub->($row);
Branch: 1 branch
BranchTrueFalseTotal
if not $wsub or &$wsub($row) 100 5 105
Condition66%2/3
not $wsub or &$wsub($row)
l!l&&r!l&&!r
01005
MC/DC50%1/2
not $wsub or &$wsub($row)
not $wsub &$wsub($row)
Truth table66%2/3
not(A) or B
A= not $wsubB= &$wsub($row)
ABresult
1X1
011
000
4451 }
4452 47 _unlock(\*FH);
4453 47 close FH;
4454 47 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4455 }
4456 }
4457 # Case 2: AND of two range conditions on the same indexed column
4458 # col OP1 val1 AND col OP2 val2 (e.g. id > 5 AND id < 10)
4459 # also: col BETWEEN val1 AND val2
4460 367 my $idx_range = $self->_try_index_and_range($tbl, $sch, $where_expr);
4461 367 ▶ if (defined $idx_range) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_range) 16 351 367
4462 16 my $wsub = where_sub($where_expr);
4463 16 my @rows;
4464 16 local *FH;
4465 16 ▶ open(FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 16 16
4466 16 binmode FH;
4467 16 _lock_sh(\*FH);
4468 16 my $rs = $sch->{recsize};
4469 16 for my $rn (sort { $a <=> $b } @$idx_range) {
4470 95 seek(FH, $rn*$rs, 0);
4471 95 my $raw = '';
4472 95 my $n = read(FH, $raw, $rs);
4473 95 ▶ next unless defined($n) && ($n == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $rs 0 95 95
Condition33%1/3
defined $n and $n == $rs
!ll&&!rl&&r
0095
MC/DC0%0/2
defined $n and $n == $rs
defined $n $n == $rs
Truth table33%1/3
A and B
A= defined $nB= $n == $rs
ABresult
0X0
100
111
4474 95 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 95 95
4475 95 my $row = $self->_unpack_record($sch, $raw);
4476 95 ▶ push @rows, $row if !$wsub || $wsub->($row);
Branch: 1 branch
BranchTrueFalseTotal
if not $wsub or &$wsub($row) 95 0 95
Condition33%1/3
not $wsub or &$wsub($row)
l!l&&r!l&&!r
0950
MC/DC0%0/2
not $wsub or &$wsub($row)
not $wsub &$wsub($row)
Truth table33%1/3
not(A) or B
A= not $wsubB= &$wsub($row)
ABresult
1X1
011
000
4477 }
4478 16 _unlock(\*FH);
4479 16 close FH;
4480 16 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4481 }
4482 # Case 3: AND across different indexed columns.
4483 # Use the best available single-column index to narrow the candidate
4484 # record set, then apply the full WHERE predicate as a post-filter.
4485 # Example: WHERE dept = 'Eng' AND salary > 70000
4486 351 my $idx_partial = $self->_try_index_partial_and($tbl, $sch, $where_expr);
4487 351 ▶ if (defined $idx_partial) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_partial) 12 339 351
4488 12 my $wsub = where_sub($where_expr);
4489 12 my @rows;
4490 12 local *FH;
4491 12 ▶ open(FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 12 12
4492 12 binmode FH;
4493 12 _lock_sh(\*FH);
4494 12 my $rs = $sch->{recsize};
4495 12 for my $rn (sort { $a <=> $b } @$idx_partial) {
4496 40 seek(FH, $rn*$rs, 0);
4497 40 my $raw = '';
4498 40 my $n = read(FH, $raw, $rs);
4499 40 ▶ next unless defined($n) && ($n == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $rs 0 40 40
Condition33%1/3
defined $n and $n == $rs
!ll&&!rl&&r
0040
MC/DC0%0/2
defined $n and $n == $rs
defined $n $n == $rs
Truth table33%1/3
A and B
A= defined $nB= $n == $rs
ABresult
0X0
100
111
4500 40 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 40 40
4501 40 my $row = $self->_unpack_record($sch, $raw);
4502 40 ▶ push @rows, $row if !$wsub || $wsub->($row);
Branch: 1 branch
BranchTrueFalseTotal
if not $wsub or &$wsub($row) 25 15 40
Condition66%2/3
not $wsub or &$wsub($row)
l!l&&r!l&&!r
02515
MC/DC50%1/2
not $wsub or &$wsub($row)
not $wsub &$wsub($row)
Truth table66%2/3
not(A) or B
A= not $wsubB= &$wsub($row)
ABresult
1X1
011
000
4503 }
4504 12 _unlock(\*FH);
4505 12 close FH;
4506 12 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4507 }
4508 # Case 4: col IN (v1, v2, ...) -- equality index per value, union.
4509 339 my $idx_in = $self->_try_index_in($tbl, $sch, $where_expr);
4510 339 ▶ if (defined $idx_in) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_in) 29 310 339
4511 29 my $wsub = where_sub($where_expr);
4512 29 my @rows;
4513 29 local *FH;
4514 29 ▶ open(FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 29 29
4515 29 binmode FH;
4516 29 _lock_sh(\*FH);
4517 29 my $rs = $sch->{recsize};
4518 29 for my $rn (sort { $a <=> $b } @$idx_in) {
4519 100 seek(FH, $rn*$rs, 0);
4520 100 my $raw = '';
4521 100 my $n = read(FH, $raw, $rs);
4522 100 ▶ next unless defined($n) && ($n == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $rs 0 100 100
Condition33%1/3
defined $n and $n == $rs
!ll&&!rl&&r
00100
MC/DC0%0/2
defined $n and $n == $rs
defined $n $n == $rs
Truth table33%1/3
A and B
A= defined $nB= $n == $rs
ABresult
0X0
100
111
4523 100 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 100 100
4524 100 my $row = $self->_unpack_record($sch, $raw);
4525 100 ▶ push @rows, $row if !$wsub || $wsub->($row);
Branch: 1 branch
BranchTrueFalseTotal
if not $wsub or &$wsub($row) 100 0 100
Condition33%1/3
not $wsub or &$wsub($row)
l!l&&r!l&&!r
01000
MC/DC0%0/2
not $wsub or &$wsub($row)
not $wsub &$wsub($row)
Truth table33%1/3
not(A) or B
A= not $wsubB= &$wsub($row)
ABresult
1X1
011
000
4526 }
4527 29 _unlock(\*FH);
4528 29 close FH;
4529 29 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4530 }
4531 # Case 5: pure OR of simple indexed conditions.
4532 # Every atom must have an index; returns union of all matching records.
4533 310 my $idx_or = $self->_try_index_or($tbl, $sch, $where_expr);
4534 310 ▶ if (defined $idx_or) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_or) 30 280 310
4535 30 my $wsub = where_sub($where_expr);
4536 30 my @rows;
4537 30 local *FH;
4538 30 ▶ open(FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 30 30
4539 30 binmode FH;
4540 30 _lock_sh(\*FH);
4541 30 my $rs = $sch->{recsize};
4542 30 for my $rn (sort { $a <=> $b } @$idx_or) {
4543 427 seek(FH, $rn*$rs, 0);
4544 427 my $raw = '';
4545 427 my $n = read(FH, $raw, $rs);
4546 427 ▶ next unless defined($n) && ($n == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $rs 0 427 427
Condition33%1/3
defined $n and $n == $rs
!ll&&!rl&&r
00427
MC/DC0%0/2
defined $n and $n == $rs
defined $n $n == $rs
Truth table33%1/3
A and B
A= defined $nB= $n == $rs
ABresult
0X0
100
111
4547 427 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 427 427
4548 427 my $row = $self->_unpack_record($sch, $raw);
4549 427 ▶ push @rows, $row if !$wsub || $wsub->($row);
Branch: 1 branch
BranchTrueFalseTotal
if not $wsub or &$wsub($row) 427 0 427
Condition33%1/3
not $wsub or &$wsub($row)
l!l&&r!l&&!r
04270
MC/DC0%0/2
not $wsub or &$wsub($row)
not $wsub &$wsub($row)
Truth table33%1/3
not(A) or B
A= not $wsubB= &$wsub($row)
ABresult
1X1
011
000
4550 }
4551 30 _unlock(\*FH);
4552 30 close FH;
4553 30 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4554 }
4555 # Case 6: col NOT IN (v1, v2, ...) -- index complement.
4556 280 my $idx_not_in = $self->_try_index_not_in($tbl, $sch, $where_expr);
4557 280 ▶ if (defined $idx_not_in) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_not_in) 21 259 280
4558 21 my $wsub = where_sub($where_expr);
4559 21 my @rows;
4560 21 local *FH;
4561 21 ▶ open(FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 21 21
4562 21 binmode FH;
4563 21 _lock_sh(\*FH);
4564 21 my $rs = $sch->{recsize};
4565 21 for my $rn (sort { $a <=> $b } @$idx_not_in) {
4566 196 seek(FH, $rn*$rs, 0);
4567 196 my $raw = '';
4568 196 my $n = read(FH, $raw, $rs);
4569 196 ▶ next unless defined($n) && ($n == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $rs 0 196 196
Condition33%1/3
defined $n and $n == $rs
!ll&&!rl&&r
00196
MC/DC0%0/2
defined $n and $n == $rs
defined $n $n == $rs
Truth table33%1/3
A and B
A= defined $nB= $n == $rs
ABresult
0X0
100
111
4570 196 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 196 196
4571 196 my $row = $self->_unpack_record($sch, $raw);
4572 196 ▶ push @rows, $row if !$wsub || $wsub->($row);
Branch: 1 branch
BranchTrueFalseTotal
if not $wsub or &$wsub($row) 196 0 196
Condition33%1/3
not $wsub or &$wsub($row)
l!l&&r!l&&!r
01960
MC/DC0%0/2
not $wsub or &$wsub($row)
not $wsub &$wsub($row)
Truth table33%1/3
not(A) or B
A= not $wsubB= &$wsub($row)
ABresult
1X1
011
000
4573 }
4574 21 _unlock(\*FH);
4575 21 close FH;
4576 21 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4577 }
4578 259 $ws = where_sub($where_expr);
4579 }
4580 405 my @raw;
4581 405 local *FH;
4582 405 ▶ open(FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 405 405
4583 405 binmode FH;
4584 405 _lock_sh(\*FH);
4585 405 my $rs = $sch->{recsize};
4586 405 while (1) {
4587 2441 my $raw = '';
4588 2441 my $n = read(FH, $raw, $rs);
4589 2441 ▶ last unless defined($n) && ($n == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $rs 405 2036 2441
Condition66%2/3
defined $n and $n == $rs
!ll&&!rl&&r
04052036
MC/DC50%1/2
defined $n and $n == $rs
defined $n $n == $rs
Truth table66%2/3
A and B
A= defined $nB= $n == $rs
ABresult
0X0
100
111
4590 2036 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 14 2022 2036
4591 2022 my $row = $self->_unpack_record($sch, $raw);
4592 2022 ▶ push @raw, $row if !$ws || $ws->($row);
Branch: 1 branch
BranchTrueFalseTotal
if not $ws or &$ws($row) 990 1032 2022
Condition100%3/3
not $ws or &$ws($row)
l!l&&r!l&&!r
5754151032
MC/DC100%2/2
not $ws or &$ws($row)
not $ws &$ws($row)
Truth table100%3/3
not(A) or B
A= not $wsB= &$ws($row)
ABresult
1X1
011
000
4593 }
4594 405 _unlock(\*FH);
4595 405 close FH;
4596 405 return{ type=>'rows', data=>[ $self->project([ @raw ], $col_specs, $distinct, $ob, $limit, $offset) ] };
4597 }
4598  
4599 sub parse_select {
4600 605 ▶ my($self, $sql) = @_;
Subroutine parse_select: called CC=17 SCAR=28.7
Pod undocumented
4601 605 $sql =~ s/^\s+|\s+$//g;
4602 605 ▶ $sql =~ s/^SELECT\s+//si or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sql =~ s/^SELECT\s+//is or return undef 0 605 605
4603 605 my $distinct = 0;
4604 605 ▶ $distinct = 1 if $sql =~ s/^DISTINCT\s+//si;
Branch: 1 branch
BranchTrueFalseTotal
if $sql =~ s/^DISTINCT\s+//is 4 601 605
4605 605 my($col_str, $rest) = split_at_from($sql);
4606 605 ▶ return undef unless defined($col_str) && defined($rest);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $col_str and defined $rest 0 605 605
Condition33%1/3
defined $col_str and defined $rest
!ll&&!rl&&r
00605
MC/DC0%0/2
defined $col_str and defined $rest
defined $col_str defined $rest
Truth table33%1/3
A and B
A= defined $col_strB= defined $rest
ABresult
0X0
100
111
4607 605 $rest =~ s/^\s*FROM\s+//si;
4608 605 my $tbl;
4609 605 ▶ ($rest =~ s/^(\w+)//) and ($tbl = $1);
Branch: 1 branch
BranchTrueFalseTotal
$rest =~ s/^(\w+)// and $tbl = $1 605 0 605
4610  
4611 # Optional alias (consumed only when token is not a SQL keyword)
4612 605 ▶ if (($rest =~ /^\s+(\w+)/) && ($1 !~ /^(?:WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|INNER|LEFT|RIGHT|JOIN|ON|UNION)$/i)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ /^\s+(\w+)/ and not $1 =~ /^(?:WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|INNER|LEFT|RIGHT|JOIN|ON|UNION)$/i) 0 605 605
Condition66%2/3
$rest =~ /^\s+(\w+)/ and not $1 =~ /^(?:WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|INNER|LEFT|RIGHT|JOIN|ON|UNION)$/i
!ll&&!rl&&r
1264790
MC/DC0%0/2
$rest =~ /^\s+(\w+)/ and not $1 =~ /^(?:WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|INNER|LEFT|RIGHT|JOIN|ON|UNION)$/i
$rest =~ /^\s+(\w+)/ not $1 =~ /^(?:WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|INNER|LEFT|RIGHT|JOIN|ON|UNION)$/i
Truth table66%2/3
A and not(B)
A= $rest =~ /^\s+(\w+)/B= not $1 =~ /^(?:WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|INNER|LEFT|RIGHT|JOIN|ON|UNION)$/i
ABresult
0X0
100
111
4613 0 $rest =~ s/^\s+(?:AS\s+)?\w+//si;
4614 }
4615 605 $rest =~ s/^\s+//;
4616 605 ▶ return undef unless $tbl;
Branch: 1 branch
BranchTrueFalseTotal
unless $tbl 0 605 605
4617 605 my($limit, $offset) = (undef, undef);
4618 605 ▶ $rest =~ s/(?:^|\s+)OFFSET\s+(\d+)\s*$//si and $offset = $1;
Branch: 1 branch
BranchTrueFalseTotal
$rest =~ s/(?:^|\s+)OFFSET\s+(\d+)\s*$//is and $offset = $1 6 599 605
4619 605 ▶ $rest =~ s/(?:^|\s+)LIMIT\s+(\d+)\s*$//si and $limit = $1;
Branch: 1 branch
BranchTrueFalseTotal
$rest =~ s/(?:^|\s+)LIMIT\s+(\d+)\s*$//is and $limit = $1 17 588 605
4620 605 my @ob;
4621 605 ▶ if ($rest =~ s/(?:^|\s+)ORDER\s+BY\s+(.+?)(?=\s*(?:LIMIT|OFFSET|$))//si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ s/(?:^|\s+)ORDER\s+BY\s+(.+?)(?=\s*(?:LIMIT|OFFSET|$))//is) 85 520 605
4622 85 my $s = $1;
4623 85 $s =~ s/^\s+|\s+$//g;
4624 85 for my $item (split /\s*,\s*/, $s) {
4625 88 $item =~ s/^\s+|\s+$//g;
4626 88 my $dir = 'ASC';
4627 88 ▶ $item =~ s/\s+(ASC|DESC)\s*$//si and $dir = uc($1);
Branch: 1 branch
BranchTrueFalseTotal
$item =~ s/\s+(ASC|DESC)\s*$//is and $dir = uc $1 14 74 88
4628 88 push @ob, [ $item, $dir ];
4629 }
4630 }
4631 605 my $having = '';
4632 605 ▶ $rest =~ s/(?:^|\s+)HAVING\s+(.+?)(?=\s*(?:ORDER|LIMIT|OFFSET|$))//si and $having = $1;
Branch: 1 branch
BranchTrueFalseTotal
$rest =~ s/(?:^|\s+)HAVING\s+(.+?)(?=\s*(?:ORDER|LIMIT|OFFSET|$))//is and $having = $1 3 602 605
4633 605 $having =~ s/^\s+|\s+$//g;
4634 605 my @gb;
4635 605 ▶ if ($rest =~ s/(?:^|\s+)GROUP\s+BY\s+(.+?)(?=\s*(?:HAVING|ORDER|LIMIT|OFFSET|$))//si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ s/(?:^|\s+)GROUP\s+BY\s+(.+?)(?=\s*(?:HAVING|ORDER|LIMIT|OFFSET|$))//is) 12 593 605
4636 12 @gb = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $1;
4637 }
4638 605 my $where = '';
4639 605 ▶ $rest =~ /(?:^|\s*)WHERE\s+(.+)/si and ($where = $1) =~ s/^\s+|\s+$//g;
Branch: 1 branch
BranchTrueFalseTotal
$rest =~ /(?:^|\s*)WHERE\s+(.+)/is and ($where = $1) =~ s/^\s+|\s+$//g 418 187 605
4640 605 my @cs = parse_col_list($col_str);
4641 605 return [ $distinct, [ @cs ], $tbl, $where, [ @gb ], $having, [ @ob ], $limit, $offset ];
4642 }
4643  
4644 sub split_at_from {
4645 605 ▶ my($str) = @_;
Subroutine split_at_from: called CC=17 SCAR=28.9
Pod undocumented
4646 605 my $d = 0;
4647 605 my $in_q = 0;
4648 605 my $len = length($str);
4649 605 for my $i (0 .. $len-1) {
4650 4375 my $ch = substr($str, $i, 1);
4651 4375 ▶ if (($ch eq "'") && !$in_q) {
Branch: 5 branches
BranchTrueFalseTotal
if ($ch eq q['] and not $in_q) { } 8 4367 4375
elsif ($ch eq q['] and $in_q) { } 8 4359 4367
elsif (not $in_q and $ch eq '(') { } 59 4300 4359
elsif (not $in_q and $ch eq ')') { } 59 4241 4300
elsif (not $in_q and $d == 0 and uc substr($str, $i, 4) eq 'FROM' and $i == 0 || substr($str, $i - 1, 1) =~ /\s/ and $i + 4 >= $len || substr($str, $i + 4, 1) =~ /\s/) { } 605 7272 7877
Condition100%3/3
$ch eq "'" and not $in_q
!ll&&!rl&&r
435988
MC/DC100%2/2
$ch eq "'" and not $in_q
$ch eq "'" not $in_q
Truth table100%3/3
A and not(B)
A= $ch eq "'"B= not $in_q
ABresult
0X0
100
111
4652 8 $in_q = 1;
4653 }
4654 ▶ elsif (($ch eq "'") && $in_q) {
Condition66%2/3
$ch eq "'" and $in_q
!ll&&!rl&&r
435908
MC/DC50%1/2
$ch eq "'" and $in_q
$ch eq "'" $in_q
Truth table66%2/3
A and B
A= $ch eq "'"B= $in_q
ABresult
0X0
100
111
4655 8 $in_q = 0;
4656 }
4657 ▶ elsif (!$in_q && ($ch eq '(')) {
Condition100%3/3
not $in_q and $ch eq "("
!ll&&!rl&&r
27427359
MC/DC100%2/2
not $in_q and $ch eq "("
not $in_q $ch eq "("
Truth table100%3/3
not(A) and B
A= not $in_qB= $ch eq "("
ABresult
0X0
100
111
4658 59 $d++;
4659 }
4660 ▶ elsif (!$in_q && ($ch eq ')')) {
Condition100%3/3
not $in_q and $ch eq ")"
!ll&&!rl&&r
27421459
MC/DC100%2/2
not $in_q and $ch eq ")"
not $in_q $ch eq ")"
Truth table100%3/3
not(A) and B
A= not $in_qB= $ch eq ")"
ABresult
0X0
100
111
4661 59 $d--;
4662 }
4663 ▶ elsif (!$in_q
Condition66%12/18
not $in_q and $d == 0 and uc substr($str, $i, 4) eq "FROM" and $i == 0 || substr($str, $i - 1, 1) =~ /\s/ and $i + 4 >= $len || substr($str, $i + 4, 1) =~ /\s/
!ll&&!rl&&r
36360605
not $in_q and $d == 0 and uc substr($str, $i, 4) eq "FROM" and $i == 0 || substr($str, $i - 1, 1) =~ /\s/
!ll&&!rl&&r
36360605
not $in_q and $d == 0 and uc substr($str, $i, 4) eq "FROM"
!ll&&!rl&&r
2103426605
not $in_q and $d == 0
!ll&&!rl&&r
271834031
$i == 0 or substr($str, $i - 1, 1) =~ /\s/
l!l&&r!l&&!r
06050
$i + 4 >= $len or substr($str, $i + 4, 1) =~ /\s/
l!l&&r!l&&!r
06050
MC/DC42%3/7
not $in_q and $d == 0 and uc substr($str, $i, 4) eq "FROM" and $i == 0 || substr($str, $i - 1, 1) =~ /\s/ and $i + 4 >= $len || substr($str, $i + 4, 1) =~ /\s/
not $in_q $d == 0 uc substr($str, $i, 4) eq "FROM" $i == 0 substr($str, $i - 1, 1) =~ /\s/ $i + 4 >= $len substr($str, $i + 4, 1) =~ /\s/
Truth table40%4/10
not(A) and B and C and D or E and F or G
A= not $in_qB= $d == 0C= uc substr($str, $i, 4) eq "FROM"D= $i == 0E= substr($str, $i - 1, 1) =~ /\s/F= $i + 4 >= $lenG= substr($str, $i + 4, 1) =~ /\s/
ABCDEFGresult
0XXXXXX0
10XXXXX0
110XXXX0
11100XX0
1111X000
11101000
1111X1X1
1111X011
111011X1
11101011
4664 && ($d == 0)
4665 && (uc(substr($str, $i, 4)) eq 'FROM')
4666 && (($i == 0) || (substr($str, $i-1, 1) =~ /\s/))
4667 && (($i+4 >= $len) || (substr($str, $i+4, 1) =~ /\s/))
4668 ) {
4669 605 return (substr($str, 0, $i), substr($str, $i));
4670 }
4671 }
4672 0 return (undef, undef);
4673 }
4674  
4675 sub parse_col_list {
4676 617 ▶ my($cs) = @_;
Subroutine parse_col_list: called CC=5 SCAR=16.1
Pod undocumented
4677 617 $cs =~ s/^\s+|\s+$//g;
4678 617 ▶ return([ '*', '*' ]) if $cs eq '*';
Branch: 1 branch
BranchTrueFalseTotal
if $cs eq "*" 58 559 617
4679 559 my @specs;
4680 559 for my $c (args($cs)) {
4681 704 $c =~ s/^\s+|\s+$//g;
4682 704 my($expr, $alias);
4683 704 ▶ if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/is) { } 63 641 704
4684 63 ($expr, $alias) = ($1, $2);
4685 63 $expr =~ s/^\s+|\s+$//g;
4686 }
4687 else {
4688 641 $expr = $c;
4689 641 ▶ $alias = ($expr =~ /^(\w+)\.(\w+)$/?$2:$expr);
Branch: 1 branch
BranchTrueFalseTotal
$expr =~ /^(\w+)\.(\w+)$/ ? : 0 641 641
4690 }
4691 704 push @specs, [$expr, $alias];
4692 }
4693 559 return @specs;
4694 }
4695  
4696 # SQL-92 lets an ORDER BY key be written as a select-list position instead
4697 # of a column name ("ORDER BY 2 DESC"). Rewrite every such item into the
4698 # name of the column it refers to, so that the comparators further down see
4699 # a name. Left alone, a bare number was compared as a constant and the
4700 # result came back unsorted with no error at all.
4701 # @$col_specs is the parsed select list; $sch is the table schema, needed
4702 # to resolve a position when the select list is "*".
4703 # Returns '' on success, or an error message for an out-of-range position.
4704 sub _resolve_order_ordinals {
4705 598 ▶ my($ob, $col_specs, $sch) = @_;
Subroutine _resolve_order_ordinals: called CC=21 SCAR=32.3
4706 598 ▶ return '' unless (ref($ob) eq 'ARRAY') && @$ob;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ob eq "ARRAY" and @$ob 513 85 598
Condition66%2/3
ref $ob eq "ARRAY" and @$ob
!ll&&!rl&&r
051385
MC/DC50%1/2
ref $ob eq "ARRAY" and @$ob
ref $ob eq "ARRAY" @$ob
Truth table66%2/3
A and B
A= ref $ob eq "ARRAY"B= @$ob
ABresult
0X0
100
111
4707 85 my $wanted = 0;
4708 85 for my $o (@$ob) {
4709 88 ▶ $wanted = 1 if (ref($o) eq 'ARRAY') && defined($o->[0]) && ($o->[0] =~ /^\d+$/);
Branch: 1 branch
BranchTrueFalseTotal
if ref $o eq "ARRAY" and defined $o->[0] and $o->[0] =~ /^\d+$/ 10 78 88
Condition50%3/6
ref $o eq "ARRAY" and defined $o->[0] and $o->[0] =~ /^\d+$/
!ll&&!rl&&r
07810
ref $o eq "ARRAY" and defined $o->[0]
!ll&&!rl&&r
0088
MC/DC33%1/3
ref $o eq "ARRAY" and defined $o->[0] and $o->[0] =~ /^\d+$/
ref $o eq "ARRAY" defined $o->[0] $o->[0] =~ /^\d+$/
Truth table50%2/4
A and B and C
A= ref $o eq "ARRAY"B= defined $o->[0]C= $o->[0] =~ /^\d+$/
ABCresult
0XX0
10X0
1100
1111
4710 }
4711 85 ▶ return '' unless $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless $wanted 76 9 85
4712  
4713 9 my @names;
4714 9 ▶ if (ref($col_specs) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $col_specs eq "ARRAY") 9 0 9
4715 9 ▶ if ((@$col_specs == 1) && (ref($col_specs->[0]) eq 'ARRAY')
Branch: 1 branch
BranchTrueFalseTotal
if (@$col_specs == 1 and ref $col_specs->[0] eq 'ARRAY' and $col_specs->[0][0] eq '*') { } 1 8 9
Condition66%4/6
@$col_specs == 1 and ref $col_specs->[0] eq "ARRAY" and $col_specs->[0][0] eq "*"
!ll&&!rl&&r
801
@$col_specs == 1 and ref $col_specs->[0] eq "ARRAY"
!ll&&!rl&&r
801
MC/DC33%1/3
@$col_specs == 1 and ref $col_specs->[0] eq "ARRAY" and $col_specs->[0][0] eq "*"
@$col_specs == 1 ref $col_specs->[0] eq "ARRAY" $col_specs->[0][0] eq "*"
Truth table50%2/4
A and B and C
A= @$col_specs == 1B= ref $col_specs->[0] eq "ARRAY"C= $col_specs->[0][0] eq "*"
ABCresult
0XX0
10X0
1100
1111
4716 && ($col_specs->[0][0] eq '*')) {
4717 1 ▶ @names = map { $_->{name} } @{$sch->{cols}} if ref($sch) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $sch eq "HASH" 1 0 1
4718 }
4719 else {
4720 8 ▶ @names = map { ref($_) eq 'ARRAY' ? $_->[1] : $_ } @$col_specs;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 17 0 17
4721 }
4722 }
4723 9 for my $o (@$ob) {
4724 10 ▶ next unless (ref($o) eq 'ARRAY') && defined($o->[0]);
Branch: 1 branch
BranchTrueFalseTotal
unless ref $o eq "ARRAY" and defined $o->[0] 0 10 10
Condition33%1/3
ref $o eq "ARRAY" and defined $o->[0]
!ll&&!rl&&r
0010
MC/DC0%0/2
ref $o eq "ARRAY" and defined $o->[0]
ref $o eq "ARRAY" defined $o->[0]
Truth table33%1/3
A and B
A= ref $o eq "ARRAY"B= defined $o->[0]
ABresult
0X0
100
111
4725 10 ▶ next unless $o->[0] =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $o->[0] =~ /^\d+$/ 0 10 10
4726 10 my $n = $o->[0] + 0;
4727 10 ▶ unless (@names && ($n >= 1) && ($n <= scalar @names)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@names and $n >= 1 and $n <= scalar @names) 3 7 10
Condition83%5/6
@names and $n >= 1 and $n <= scalar @names
!ll&&!rl&&r
127
@names and $n >= 1
!ll&&!rl&&r
019
MC/DC66%2/3
@names and $n >= 1 and $n <= scalar @names
@names $n >= 1 $n <= scalar @names
Truth table75%3/4
A and B and C
A= @namesB= $n >= 1C= $n <= scalar @names
ABCresult
0XX0
10X0
1100
1111
4728 3 return "ORDER BY position $o->[0] is not in the select list";
4729 }
4730 7 $o->[0] = $names[$n - 1];
4731 }
4732 6 return '';
4733 }
4734  
4735 # Scalar counterpart of _resolve_order_ordinals, for the JOIN, derived
4736 # table and correlated subquery paths. Those carry a single ORDER BY key
4737 # rather than a list of them. @$names is the output column list in SELECT
4738 # order; when it is empty the position cannot be resolved (a "*" select
4739 # list whose expansion is not known at this point) and the position is
4740 # reported rather than quietly ignored.
4741 # Returns (error_message, key); error_message is '' on success, and key is
4742 # the original one when it was not a position.
4743 sub _resolve_order_ordinal_scalar {
4744 40 ▶ my($ob, $names) = @_;
Subroutine _resolve_order_ordinal_scalar: called CC=7 SCAR=23.4
4745 40 ▶ return ('', $ob) unless defined($ob) && ($ob =~ /^\d+$/);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ob and $ob =~ /^\d+$/ 37 3 40
Condition66%2/3
defined $ob and $ob =~ /^\d+$/
!ll&&!rl&&r
0373
MC/DC50%1/2
defined $ob and $ob =~ /^\d+$/
defined $ob $ob =~ /^\d+$/
Truth table66%2/3
A and B
A= defined $obB= $ob =~ /^\d+$/
ABresult
0X0
100
111
4746 3 my $n = $ob + 0;
4747 3 ▶ unless ((ref($names) eq 'ARRAY') && @$names && ($n >= 1) && ($n <= scalar @$names)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $names eq "ARRAY" and @$names and $n >= 1 and $n <= scalar @$names) 0 3 3
Condition33%3/9
ref $names eq "ARRAY" and @$names and $n >= 1 and $n <= scalar @$names
!ll&&!rl&&r
003
ref $names eq "ARRAY" and @$names and $n >= 1
!ll&&!rl&&r
003
ref $names eq "ARRAY" and @$names
!ll&&!rl&&r
003
MC/DC0%0/4
ref $names eq "ARRAY" and @$names and $n >= 1 and $n <= scalar @$names
ref $names eq "ARRAY" @$names $n >= 1 $n <= scalar @$names
Truth table20%1/5
A and B and C and D
A= ref $names eq "ARRAY"B= @$namesC= $n >= 1D= $n <= scalar @$names
ABCDresult
0XXX0
10XX0
110X0
11100
11111
4748 0 return ("ORDER BY position $ob is not in the select list", $ob);
4749 }
4750 3 return ('', $names->[$n - 1]);
4751 }
4752  
4753 # Select-list item as the sort comparators see it before projection: the
4754 # expression with any trailing "AS alias" removed.
4755 sub _order_name_of {
4756 115 ▶ my($item) = @_;
Subroutine _order_name_of: called CC=2 SCAR=7.0
4757 115 ▶ return '' unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 115 115
4758 115 $item =~ s/^\s+|\s+$//g;
4759 115 $item =~ s/\s+AS\s+\w+\s*$//si;
4760 115 return $item;
4761 }
4762  
4763 # Select-list item as it is keyed after projection: the explicit alias,
4764 # the bare column of a qualified name, or the expression itself.
4765 sub _order_alias_of {
4766 13 ▶ my($item) = @_;
Subroutine _order_alias_of: called CC=4 SCAR=13.9
4767 13 ▶ return '' unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 13 13
4768 13 $item =~ s/^\s+|\s+$//g;
4769 13 ▶ return $1 if $item =~ /\s+AS\s+(\w+)\s*$/si;
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /\s+AS\s+(\w+)\s*$/is 4 9 13
4770 9 ▶ return $2 if $item =~ /^(\w+)\.(\w+)$/;
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /^(\w+)\.(\w+)$/ 5 4 9
4771 4 return $item;
4772 }
4773  
4774 sub project {
4775 560 ▶ my($self, $rows, $col_specs, $distinct, $ob, $limit, $offset) = @_; my $star = ((@$col_specs == 1) && ($col_specs->[0][0] eq '*'));
Subroutine project: called CC=23 SCAR=31.7
Pod undocumented
Condition100%3/3
@$col_specs == 1 && $col_specs->[0][0] eq '*'
!ll&&!rl&&r
9241751
MC/DC100%2/2
@$col_specs == 1 && $col_specs->[0][0] eq '*'
@$col_specs == 1 $col_specs->[0][0] eq '*'
Truth table100%3/3
A && B
A= @$col_specs == 1B= $col_specs->[0][0] eq '*'
ABresult
0X0
100
111
4776  
4777 # ORDER BY must be evaluated against the original (unprojected) rows so that
4778 # columns not listed in SELECT (e.g. "SELECT name ... ORDER BY score") are
4779 # still accessible for sorting.
4780 560 my @sorted = @$rows;
4781 560 ▶ if (@$ob) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$ob) 72 488 560
4782 @sorted = sort {
4783 72 my($ra, $rb) = ($a, $b);
4784 379 for my $o (@$ob) {
4785 393 my($e, $dir) = @$o;
4786 393 ▶ my $va = do { my $vv = eval_expr($e, $ra); defined($vv) ? $vv : (defined($ra->{$e}) ? $ra->{$e} : '') };
Branch: 2 branches
BranchTrueFalseTotal
defined $vv ? : 393 0 393
defined $ra->{$e} ? : 0 0 0
4787 393 ▶ my $vb = do { my $vv = eval_expr($e, $rb); defined($vv) ? $vv : (defined($rb->{$e}) ? $rb->{$e} : '') };
Branch: 2 branches
BranchTrueFalseTotal
defined $vv ? : 393 0 393
defined $rb->{$e} ? : 0 0 0
4788 393 ▶ my $c = (($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/)) ? ($va <=> $vb) : ($va cmp $vb);
Branch: 1 branch
BranchTrueFalseTotal
$va =~ /^-?\d+\.?\d*$/ && $vb =~ /^-?\d+\.?\d*$/ ? : 328 65 393
Condition66%2/3
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
650328
MC/DC50%1/2
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
$va =~ /^-?\d+\.?\d*$/ $vb =~ /^-?\d+\.?\d*$/
Truth table66%2/3
A and B
A= $va =~ /^-?\d+\.?\d*$/B= $vb =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
4789 393 ▶ $c = -$c if lc($dir) eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if lc $dir eq "desc" 63 330 393
4790 393 ▶ return $c if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 353 40 393
4791 }
4792 0
4793 } @sorted;
4794 }
4795  
4796 # Apply OFFSET / LIMIT on sorted raw rows before projection
4797 560 ▶ $offset = 0 unless defined $offset;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $offset 554 6 560
4798 560 ▶ @sorted = splice(@sorted, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 5 555 560
4799 560 ▶ if (defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 17 543 560
4800 17 my $l = $limit-1;
4801 17 ▶ $l = $#sorted if $l>$#sorted;
Branch: 1 branch
BranchTrueFalseTotal
if $l > $#sorted 0 17 17
4802 17 @sorted = @sorted[0 .. $l];
4803 }
4804  
4805 # Project to requested columns
4806 560 my @out;
4807 560 for my $row (@sorted) {
4808 1872 ▶ if ($star) {
Branch: 1 branch
BranchTrueFalseTotal
if ($star) { } 125 1747 1872
4809 125 push @out, { %$row };
4810 }
4811 else {
4812 1747 my %p;
4813 1747 $p{$_->[1]} = eval_expr($_->[0], $row) for @$col_specs;
4814 1747 push @out, { %p };
4815 }
4816 }
4817  
4818 # DISTINCT (applied after projection so aliases are visible)
4819 560 ▶ if ($distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct) 4 556 560
4820 4 my %s;
4821 my @d;
4822 4 for my $r (@out) {
4823 22 ▶ my $k = join("\x00", map{ defined($r->{$_}) ? $r->{$_} : "\x01" } sort keys %$r);
Branch: 1 branch
BranchTrueFalseTotal
defined $r->{$_} ? : 22 0 22
4824 22 ▶ push @d, $r unless $s{$k}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $s{$k}++ 10 12 22
4825 }
4826 4 @out = @d;
4827 }
4828 560 return @out;
4829 }
4830  
4831 # =============================================================================
4832 # GROUP BY / HAVING / aggregate functions
4833 # =============================================================================
4834 sub exec_groupby {
4835 35 ▶ my($self, $tbl, $col_specs, $where_expr, $gb, $having, $ob, $limit, $offset) = @_;
Subroutine exec_groupby: called CC=24 SCAR=34.4
Pod undocumented
4836 35 ▶ my $sch = $self->_load_schema($tbl) or return{ type=>'error', message=>$errstr };
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($tbl) or return {"type", "error", "message", $DB::Handy::errstr} 0 35 35
4837 35 my $obe = _resolve_order_ordinals($ob, $col_specs, $sch);
4838 35 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 0 35 35
4839 35 my $dat = $self->_file($tbl, 'dat');
4840 35 ▶ my $ws = ($where_expr ne '') ? where_sub($where_expr) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$where_expr ne '' ? : 4 31 35
4841 35 my @raw;
4842 35 local *FH;
4843 35 ▶ open(FH, "< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $dat" or return $self->_err("Cannot open dat: $!") 0 35 35
4844 35 binmode FH;
4845 35 _lock_sh(\*FH);
4846 35 my $rs = $sch->{recsize};
4847 35 while (1) {
4848 223 my $raw = '';
4849 223 my $n = read(FH, $raw, $rs);
4850 223 ▶ last unless defined($n) && ($n == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n and $n == $rs 35 188 223
Condition66%2/3
defined $n and $n == $rs
!ll&&!rl&&r
035188
MC/DC50%1/2
defined $n and $n == $rs
defined $n $n == $rs
Truth table66%2/3
A and B
A= defined $nB= $n == $rs
ABresult
0X0
100
111
4851 188 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 9 179 188
4852 179 my $row = $self->_unpack_record($sch, $raw);
4853 179 ▶ push @raw, $row if !$ws || $ws->($row);
Branch: 1 branch
BranchTrueFalseTotal
if not $ws or &$ws($row) 164 15 179
Condition100%3/3
not $ws or &$ws($row)
l!l&&r!l&&!r
1541015
MC/DC100%2/2
not $ws or &$ws($row)
not $ws &$ws($row)
Truth table100%3/3
not(A) or B
A= not $wsB= &$ws($row)
ABresult
1X1
011
000
4854 }
4855 35 _unlock(\*FH);
4856 35 close FH;
4857 35 my @results = group_and_aggregate([ @raw ], $col_specs, $gb, $having);
4858 35 ▶ if (@$ob) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$ob) 10 25 35
4859 @results = sort {
4860 10 my($ra, $rb) = ($a, $b);
4861 25 for my $o (@$ob) {
4862 25 my($e, $dir) = @$o;
4863 25 ▶ my $va = do { my $vv = eval_expr($e, $ra); defined($vv) ? $vv : (defined($ra->{$e}) ? $ra->{$e} : '') };
Branch: 2 branches
BranchTrueFalseTotal
defined $vv ? : 25 0 25
defined $ra->{$e} ? : 0 0 0
4864 25 ▶ my $vb = do { my $vv = eval_expr($e, $rb); defined($vv) ? $vv : (defined($rb->{$e}) ? $rb->{$e} : '') };
Branch: 2 branches
BranchTrueFalseTotal
defined $vv ? : 25 0 25
defined $rb->{$e} ? : 0 0 0
4865 25 ▶ my $c = (($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/)) ? ($va <=> $vb) : ($va cmp $vb);
Branch: 1 branch
BranchTrueFalseTotal
$va =~ /^-?\d+\.?\d*$/ && $vb =~ /^-?\d+\.?\d*$/ ? : 11 14 25
Condition66%2/3
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
14011
MC/DC50%1/2
$va =~ /^-?\d+\.?\d*$/ and $vb =~ /^-?\d+\.?\d*$/
$va =~ /^-?\d+\.?\d*$/ $vb =~ /^-?\d+\.?\d*$/
Truth table66%2/3
A and B
A= $va =~ /^-?\d+\.?\d*$/B= $vb =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
4866 25 ▶ $c = -$c if lc($dir) eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if lc $dir eq "desc" 0 25 25
4867 25 ▶ return $c if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 25 0 25
4868 }
4869 0
4870 } @results
4871 }
4872 35 ▶ $offset = 0 unless defined $offset;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $offset 35 0 35
4873 35 ▶ @results = splice(@results, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 35 35
4874 35 ▶ if (defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 0 35 35
4875 0 my $l = $limit - 1;
4876 0 ▶ $l = $#results if $l>$#results;
Branch: 1 branch
BranchTrueFalseTotal
if $l > $#results 0 0 0
4877 0 @results = @results[0..$l];
4878 }
4879 35 return{ type=>'rows', data=>[ @results ] };
4880 }
4881  
4882 # Group @$rows by the expressions in @$gb (an empty list means one group
4883 # holding every row), evaluate @$col_specs for each group and drop the
4884 # groups rejected by $having. Returns the result rows. The table-backed
4885 # SELECT path and the derived-table path share this, which is why it takes
4886 # rows rather than reading them itself.
4887 sub group_and_aggregate {
4888 47 ▶ my($rows, $col_specs, $gb, $having) = @_;
Subroutine group_and_aggregate: called CC=12 SCAR=24.9
Pod undocumented
4889 47 ▶ $gb = [] unless defined $gb;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gb 0 47 47
4890 47 ▶ $having = '' unless defined $having;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $having 0 47 47
4891 47 my %gr;
4892 my @go;
4893 47 ▶ if (@$gb) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$gb) { } 16 31 47
4894 16 for my $row (@$rows) {
4895 91 ▶ my $k = join("\x00", map { my $v = eval_expr($_, $row); defined($v) ? $v : '' } @$gb);
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 91 0 91
4896 91 ▶ push @go, $k unless exists $gr{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $gr{$k} 40 51 91
4897 91 push @{$gr{$k}}, $row;
4898 }
4899 }
4900 else {
4901 31 @go = ('__all__');
4902 31 $gr{__all__} = [ @$rows ];
4903 }
4904 47 my @results;
4905 47 for my $gk (@go) {
4906 71 my $grp = $gr{$gk};
4907 71 ▶ my $rep = defined($grp->[0]) ? $grp->[0] : {};
Branch: 1 branch
BranchTrueFalseTotal
defined $grp->[0] ? : 69 2 71
4908 71 my %out;
4909 71 $out{$_->[1]} = eval_agg($_->[0], $grp, $rep) for @$col_specs;
4910 71 ▶ if ($having ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($having ne "") 9 62 71
4911 9 my $h = $having;
4912 9 my $cnt = scalar @$grp;
4913 9 $h =~ s/COUNT\s*\(\s*\*\s*\)/$cnt/gsi;
4914 9 $h =~ s/\b(SUM|AVG|MIN|MAX|COUNT)\s*\(([^)]+)\)/eval_agg("$1($2)", $grp, $rep)/geis;
4915 9 ▶ next unless where_sub($h)->({ %out });
Branch: 1 branch
BranchTrueFalseTotal
unless where_sub($h)->({%out}) 3 6 9
4916 }
4917 68 push @results, { %out };
4918 }
4919 47 return @results;
4920 }
4921  
4922 sub eval_agg {
4923 152 ▶ my($expr, $grp, $rep) = @_;
Subroutine eval_agg: called CC=20 SCAR=30.6
Pod undocumented
4924 152 ▶ return scalar @$grp if $expr =~ /^COUNT\s*\(\s*\*\s*\)$/si;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^COUNT\s*\(\s*\*\s*\)$/is 57 95 152
4925 95 ▶ if ($expr =~ /^COUNT\s*\(\s*DISTINCT\s+(.+)\s*\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^COUNT\s*\(\s*DISTINCT\s+(.+)\s*\)$/is) 2 93 95
4926 2 my $e = $1;
4927 2 my %s;
4928 2 for my $r (@$grp) {
4929 9 my $vv = eval_expr($e, $r);
4930 9 ▶ next unless defined($vv) && ($vv ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $vv and $vv ne "" 1 8 9
Condition66%2/3
defined $vv and $vv ne ""
!ll&&!rl&&r
018
MC/DC50%1/2
defined $vv and $vv ne ""
defined $vv $vv ne ""
Truth table66%2/3
A and B
A= defined $vvB= $vv ne ""
ABresult
0X0
100
111
4931 8 $s{$vv}++;
4932 }
4933 2 return scalar keys %s;
4934 }
4935 93 ▶ if ($expr =~ /^(COUNT|SUM|AVG|MIN|MAX)\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(COUNT|SUM|AVG|MIN|MAX)\s*\((.+)\)$/is) 43 50 93
4936 43 my($fn, $inner) = (uc($1), $2);
4937 43 $inner =~ s/^\s+|\s+$//g;
4938 43 ▶ my @vals = grep { defined($_) && ($_ ne '') } map { eval_expr($inner, $_) } @$grp;
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and $_ ne "" 123 0 123
4939 43 ▶ return 0 unless @vals;
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 0 43 43
4940 43 ▶ return scalar @vals if $fn eq 'COUNT';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "COUNT" 1 42 43
4941 42 ▶ if ($fn eq 'SUM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "SUM") 19 23 42
4942 19 my $s = 0;
4943 19 $s += $_ for @vals;
4944 19 return $s;
4945 }
4946 23 ▶ if ($fn eq 'AVG') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "AVG") 9 14 23
4947 9 my $s = 0;
4948 9 $s += $_ for @vals;
4949 9 return $s / @vals;
4950 }
4951 14 ▶ if ($fn eq 'MIN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "MIN") 5 9 14
4952 5 ▶ return (sort { (($a =~ /^-?\d+\.?\d*$/) && ($b =~ /^-?\d+\.?\d*$/)) ? ($a<=>$b) : ($a cmp $b) } @vals)[0];
Branch: 1 branch
BranchTrueFalseTotal
$a =~ /^-?\d+\.?\d*$/ && $b =~ /^-?\d+\.?\d*$/ ? : 17 0 17
Condition33%1/3
$a =~ /^-?\d+\.?\d*$/ and $b =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
0017
MC/DC0%0/2
$a =~ /^-?\d+\.?\d*$/ and $b =~ /^-?\d+\.?\d*$/
$a =~ /^-?\d+\.?\d*$/ $b =~ /^-?\d+\.?\d*$/
Truth table33%1/3
A and B
A= $a =~ /^-?\d+\.?\d*$/B= $b =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
4953 }
4954 9 ▶ if ($fn eq 'MAX') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "MAX") 9 0 9
4955 9 ▶ return (sort { (($a =~ /^-?\d+\.?\d*$/) && ($b =~ /^-?\d+\.?\d*$/)) ? ($b<=>$a) : ($b cmp $a) } @vals)[0];
Branch: 1 branch
BranchTrueFalseTotal
$a =~ /^-?\d+\.?\d*$/ && $b =~ /^-?\d+\.?\d*$/ ? : 20 0 20
Condition33%1/3
$a =~ /^-?\d+\.?\d*$/ and $b =~ /^-?\d+\.?\d*$/
!ll&&!rl&&r
0020
MC/DC0%0/2
$a =~ /^-?\d+\.?\d*$/ and $b =~ /^-?\d+\.?\d*$/
$a =~ /^-?\d+\.?\d*$/ $b =~ /^-?\d+\.?\d*$/
Truth table33%1/3
A and B
A= $a =~ /^-?\d+\.?\d*$/B= $b =~ /^-?\d+\.?\d*$/
ABresult
0X0
100
111
4956 }
4957 }
4958 50 return eval_expr($expr, $rep);
4959 }
4960  
4961 # =============================================================================
4962 # UNION / UNION ALL
4963 # =============================================================================
4964 sub split_union {
4965 732 ▶ my($sql) = @_;
Subroutine split_union: called CC=47 SCAR=39.8
Pod undocumented
4966 732 my @parts;
4967 732 my $cur = '';
4968 732 my $d = 0;
4969 732 my $in_q = 0;
4970 732 my $i = 0;
4971 732 my $len = length($sql);
4972 732 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 31880 732 32612
4973 31880 my $ch = substr($sql, $i, 1);
4974 31880 ▶ if (($ch eq "'") && !$in_q) {
Branch: 6 branches
BranchTrueFalseTotal
if ($ch eq q['] and not $in_q) { } 134 31746 31880
elsif ($ch eq q['] and $in_q) { } 134 31612 31746
elsif ($in_q) { } 468 31144 31612
elsif ($ch eq '(') { } 152 30992 31144
elsif ($ch eq ')') { } 152 30840 30992
elsif ($d == 0 and not $in_q and $i == 0 || substr($sql, $i - 1, 1) =~ /\s/) { } 6469 24371 30840
Condition100%3/3
$ch eq "'" and not $in_q
!ll&&!rl&&r
31612134134
MC/DC100%2/2
$ch eq "'" and not $in_q
$ch eq "'" not $in_q
Truth table100%3/3
A and not(B)
A= $ch eq "'"B= not $in_q
ABresult
0X0
100
111
4975 134 $in_q = 1;
4976 134 $cur .= $ch;
4977 }
4978 ▶ elsif (($ch eq "'") && $in_q) {
Condition66%2/3
$ch eq "'" and $in_q
!ll&&!rl&&r
316120134
MC/DC50%1/2
$ch eq "'" and $in_q
$ch eq "'" $in_q
Truth table66%2/3
A and B
A= $ch eq "'"B= $in_q
ABresult
0X0
100
111
4979 134 $in_q = 0;
4980 134 $cur .= $ch;
4981 }
4982 elsif ($in_q) {
4983 468 $cur .= $ch;
4984 }
4985 elsif ($ch eq '(') {
4986 152 $d++;
4987 152 $cur .= $ch;
4988 }
4989 elsif ($ch eq ')') {
4990 152 $d--;
4991 152 $cur .= $ch;
4992 }
4993 ▶ elsif ($d == 0 && !$in_q
Condition88%8/9
$d == 0 and not $in_q and $i == 0 || substr($sql, $i - 1, 1) =~ /\s/
!ll&&!rl&&r
927234446469
$d == 0 and not $in_q
!ll&&!rl&&r
927029913
$i == 0 or substr($sql, $i - 1, 1) =~ /\s/
l!l&&r!l&&!r
732573723444
MC/DC75%3/4
$d == 0 and not $in_q and $i == 0 || substr($sql, $i - 1, 1) =~ /\s/
$d == 0 not $in_q $i == 0 substr($sql, $i - 1, 1) =~ /\s/
Truth table80%4/5
A and not(B) and C or D
A= $d == 0B= not $in_qC= $i == 0D= substr($sql, $i - 1, 1) =~ /\s/
ABCDresult
0XXX0
10XX0
11000
111X1
11011
4994 && (($i == 0) || (substr($sql, $i-1, 1) =~ /\s/))) {
4995 # Detect UNION / INTERSECT / EXCEPT set operators
4996 6469 my $kw = '';
4997 6469 my $klen = 0;
4998 6469 ▶ if ((uc(substr($sql, $i, 5)) eq 'UNION')
Branch: 3 branches
BranchTrueFalseTotal
if (uc substr($sql, $i, 5) eq 'UNION' and $i + 5 < $len and substr($sql, $i + 5, 1) =~ /[\s(]/) { } 8 6461 6469
elsif (uc substr($sql, $i, 9) eq 'INTERSECT' and $i + 9 < $len and substr($sql, $i + 9, 1) =~ /[\s(]/) { } 18 6443 6461
elsif (uc substr($sql, $i, 6) eq 'EXCEPT' and $i + 6 < $len and substr($sql, $i + 6, 1) =~ /[\s(]/) { } 13 12860 12873
Condition66%4/6
uc substr($sql, $i, 5) eq "UNION" and $i + 5 < $len and substr($sql, $i + 5, 1) =~ /[\s(]/
!ll&&!rl&&r
646108
uc substr($sql, $i, 5) eq "UNION" and $i + 5 < $len
!ll&&!rl&&r
646108
MC/DC33%1/3
uc substr($sql, $i, 5) eq "UNION" and $i + 5 < $len and substr($sql, $i + 5, 1) =~ /[\s(]/
uc substr($sql, $i, 5) eq "UNION" $i + 5 < $len substr($sql, $i + 5, 1) =~ /[\s(]/
Truth table50%2/4
A and B and C
A= uc substr($sql, $i, 5) eq "UNION"B= $i + 5 < $lenC= substr($sql, $i + 5, 1) =~ /[\s(]/
ABCresult
0XX0
10X0
1100
1111
4999 && ($i+5 < $len) && (substr($sql, $i+5, 1) =~ /[\s(]/)) {
5000 8 $kw = 'UNION'; $klen = 5;
5001 }
5002 ▶ elsif ((uc(substr($sql, $i, 9)) eq 'INTERSECT')
Condition66%4/6
uc substr($sql, $i, 9) eq "INTERSECT" and $i + 9 < $len and substr($sql, $i + 9, 1) =~ /[\s(]/
!ll&&!rl&&r
6443018
uc substr($sql, $i, 9) eq "INTERSECT" and $i + 9 < $len
!ll&&!rl&&r
6443018
MC/DC33%1/3
uc substr($sql, $i, 9) eq "INTERSECT" and $i + 9 < $len and substr($sql, $i + 9, 1) =~ /[\s(]/
uc substr($sql, $i, 9) eq "INTERSECT" $i + 9 < $len substr($sql, $i + 9, 1) =~ /[\s(]/
Truth table50%2/4
A and B and C
A= uc substr($sql, $i, 9) eq "INTERSECT"B= $i + 9 < $lenC= substr($sql, $i + 9, 1) =~ /[\s(]/
ABCresult
0XX0
10X0
1100
1111
5003 && ($i+9 < $len) && (substr($sql, $i+9, 1) =~ /[\s(]/)) {
5004 18 $kw = 'INTERSECT'; $klen = 9;
5005 }
5006 ▶ elsif ((uc(substr($sql, $i, 6)) eq 'EXCEPT')
Condition66%4/6
uc substr($sql, $i, 6) eq "EXCEPT" and $i + 6 < $len and substr($sql, $i + 6, 1) =~ /[\s(]/
!ll&&!rl&&r
6430013
uc substr($sql, $i, 6) eq "EXCEPT" and $i + 6 < $len
!ll&&!rl&&r
6430013
MC/DC33%1/3
uc substr($sql, $i, 6) eq "EXCEPT" and $i + 6 < $len and substr($sql, $i + 6, 1) =~ /[\s(]/
uc substr($sql, $i, 6) eq "EXCEPT" $i + 6 < $len substr($sql, $i + 6, 1) =~ /[\s(]/
Truth table50%2/4
A and B and C
A= uc substr($sql, $i, 6) eq "EXCEPT"B= $i + 6 < $lenC= substr($sql, $i + 6, 1) =~ /[\s(]/
ABCresult
0XX0
10X0
1100
1111
5007 && ($i+6 < $len) && (substr($sql, $i+6, 1) =~ /[\s(]/)) {
5008 13 $kw = 'EXCEPT'; $klen = 6;
5009 }
5010 6469 ▶ if ($klen) {
Branch: 1 branch
BranchTrueFalseTotal
if ($klen) { } 39 6430 6469
5011 39 push @parts, $cur;
5012 39 $cur = '';
5013 39 $i += $klen;
5014 39 ▶ while (($i < $len) && (substr($sql, $i, 1) =~ /\s/)) { $i++ }
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len and substr($sql, $i, 1) =~ /\s/) 39 39 78
Condition66%2/3
$i < $len and substr($sql, $i, 1) =~ /\s/
!ll&&!rl&&r
03939
MC/DC50%1/2
$i < $len and substr($sql, $i, 1) =~ /\s/
$i < $len substr($sql, $i, 1) =~ /\s/
Truth table66%2/3
A and B
A= $i < $lenB= substr($sql, $i, 1) =~ /\s/
ABresult
0X0
100
111
5015 # UNION ALL / INTERSECT ALL / EXCEPT ALL
5016 39 ▶ if (($kw eq 'UNION')
Branch: 3 branches
BranchTrueFalseTotal
if ($kw eq 'UNION' and $i + 3 <= $len and uc substr($sql, $i, 3) eq 'ALL' and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/) { } 4 35 39
elsif ($kw eq 'INTERSECT' and $i + 3 <= $len and uc substr($sql, $i, 3) eq 'ALL' and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/) { } 2 33 35
elsif ($kw eq 'EXCEPT' and $i + 3 <= $len and uc substr($sql, $i, 3) eq 'ALL' and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/) { } 3 30 33
Condition66%8/12
$kw eq "UNION" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL" and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/
!ll&&!rl&&r
3504
$kw eq "UNION" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL"
!ll&&!rl&&r
3144
$kw eq "UNION" and $i + 3 <= $len
!ll&&!rl&&r
3108
$i + 3 >= $len or substr($sql, $i + 3, 1) =~ /\s/
l!l&&r!l&&!r
040
MC/DC40%2/5
$kw eq "UNION" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL" and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/
$kw eq "UNION" $i + 3 <= $len uc substr($sql, $i, 3) eq "ALL" $i + 3 >= $len substr($sql, $i + 3, 1) =~ /\s/
Truth table50%3/6
A and B and C and D or E
A= $kw eq "UNION"B= $i + 3 <= $lenC= uc substr($sql, $i, 3) eq "ALL"D= $i + 3 >= $lenE= substr($sql, $i + 3, 1) =~ /\s/
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
5017 && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL')
5018 && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) {
5019 4 push @parts, 'UNION_ALL';
5020 4 $i += 3;
5021 4 ▶ while (($i < $len) && (substr($sql, $i, 1) =~ /\s/)) { $i++ }
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len and substr($sql, $i, 1) =~ /\s/) 4 4 8
Condition66%2/3
$i < $len and substr($sql, $i, 1) =~ /\s/
!ll&&!rl&&r
044
MC/DC50%1/2
$i < $len and substr($sql, $i, 1) =~ /\s/
$i < $len substr($sql, $i, 1) =~ /\s/
Truth table66%2/3
A and B
A= $i < $lenB= substr($sql, $i, 1) =~ /\s/
ABresult
0X0
100
111
5022 }
5023 ▶ elsif (($kw eq 'INTERSECT')
Condition66%8/12
$kw eq "INTERSECT" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL" and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/
!ll&&!rl&&r
3302
$kw eq "INTERSECT" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL"
!ll&&!rl&&r
17162
$kw eq "INTERSECT" and $i + 3 <= $len
!ll&&!rl&&r
17018
$i + 3 >= $len or substr($sql, $i + 3, 1) =~ /\s/
l!l&&r!l&&!r
020
MC/DC40%2/5
$kw eq "INTERSECT" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL" and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/
$kw eq "INTERSECT" $i + 3 <= $len uc substr($sql, $i, 3) eq "ALL" $i + 3 >= $len substr($sql, $i + 3, 1) =~ /\s/
Truth table50%3/6
A and B and C and D or E
A= $kw eq "INTERSECT"B= $i + 3 <= $lenC= uc substr($sql, $i, 3) eq "ALL"D= $i + 3 >= $lenE= substr($sql, $i + 3, 1) =~ /\s/
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
5024 && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL')
5025 && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) {
5026 2 push @parts, 'INTERSECT_ALL';
5027 2 $i += 3;
5028 2 ▶ while (($i < $len) && (substr($sql, $i, 1) =~ /\s/)) { $i++ }
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len and substr($sql, $i, 1) =~ /\s/) 2 2 4
Condition66%2/3
$i < $len and substr($sql, $i, 1) =~ /\s/
!ll&&!rl&&r
022
MC/DC50%1/2
$i < $len and substr($sql, $i, 1) =~ /\s/
$i < $len substr($sql, $i, 1) =~ /\s/
Truth table66%2/3
A and B
A= $i < $lenB= substr($sql, $i, 1) =~ /\s/
ABresult
0X0
100
111
5029 }
5030 ▶ elsif (($kw eq 'EXCEPT')
Condition66%8/12
$kw eq "EXCEPT" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL" and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/
!ll&&!rl&&r
3003
$kw eq "EXCEPT" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL"
!ll&&!rl&&r
20103
$kw eq "EXCEPT" and $i + 3 <= $len
!ll&&!rl&&r
20013
$i + 3 >= $len or substr($sql, $i + 3, 1) =~ /\s/
l!l&&r!l&&!r
030
MC/DC40%2/5
$kw eq "EXCEPT" and $i + 3 <= $len and uc substr($sql, $i, 3) eq "ALL" and $i + 3 >= $len || substr($sql, $i + 3, 1) =~ /\s/
$kw eq "EXCEPT" $i + 3 <= $len uc substr($sql, $i, 3) eq "ALL" $i + 3 >= $len substr($sql, $i + 3, 1) =~ /\s/
Truth table50%3/6
A and B and C and D or E
A= $kw eq "EXCEPT"B= $i + 3 <= $lenC= uc substr($sql, $i, 3) eq "ALL"D= $i + 3 >= $lenE= substr($sql, $i + 3, 1) =~ /\s/
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
5031 && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL')
5032 && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) {
5033 3 push @parts, 'EXCEPT_ALL';
5034 3 $i += 3;
5035 3 ▶ while (($i < $len) && (substr($sql, $i, 1) =~ /\s/)) { $i++ }
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len and substr($sql, $i, 1) =~ /\s/) 3 3 6
Condition66%2/3
$i < $len and substr($sql, $i, 1) =~ /\s/
!ll&&!rl&&r
033
MC/DC50%1/2
$i < $len and substr($sql, $i, 1) =~ /\s/
$i < $len substr($sql, $i, 1) =~ /\s/
Truth table66%2/3
A and B
A= $i < $lenB= substr($sql, $i, 1) =~ /\s/
ABresult
0X0
100
111
5036 }
5037 else {
5038 30 push @parts, $kw; # bare UNION / INTERSECT / EXCEPT
5039 }
5040 39 next;
5041 }
5042 else {
5043 6430 $cur .= $ch;
5044 }
5045 }
5046 else {
5047 24371 $cur .= $ch;
5048 }
5049 31841 $i++;
5050 }
5051 732 ▶ push @parts, $cur if $cur =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $cur =~ /\S/ 732 0 732
5052 732 return @parts;
5053 }
5054  
5055 # Column order of one branch of a set operation, as a list of result-row
5056 # hash keys in select-list order.
5057 sub _branch_col_order {
5058 77 ▶ my($self, $sql, $data) = @_;
Subroutine _branch_col_order: called CC=1 SCAR=0.0
5059 77 return [ DB::Handy::Statement::_col_order_from_sql(undef, $sql, $data, $self) ];
5060 }
5061  
5062 sub exec_union {
5063 38 ▶ my($self, $parts) = @_;
Subroutine exec_union: called CC=37 SCAR=36.2
Pod undocumented
5064 38 my @p = @$parts;
5065 38 my $first = shift @p;
5066 38 my $r0 = $self->execute($first);
5067 38 ▶ return $r0 if $r0->{type} eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $r0->{"type"} eq "error" 0 38 38
5068 38 my @rows = @{$r0->{data}};
5069  
5070 # A result row is a hash keyed by column name, and SQL lines the branches
5071 # of a set operation up by *position*, taking the result column names from
5072 # the first branch. Until 1.09 the branches were merged as they came, so
5073 # "SELECT x FROM a UNION ALL SELECT p FROM b" produced rows keyed 'p' for
5074 # the second branch; every value read under the name 'x' was then NULL.
5075 # The column order of each later branch is therefore mapped onto the
5076 # first branch's names before the rows are combined.
5077 38 my $base = $self->_branch_col_order($first, \@rows);
5078  
5079 38 ▶ while (@p >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@p >= 2) 39 37 76
5080 39 my $sep = shift @p;
5081 39 my $q = shift @p;
5082 39 my $r = $self->execute($q);
5083 39 ▶ return $r if $r->{type} eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"type"} eq "error" 0 39 39
5084 39 my @rhs = @{$r->{data}};
5085 39 my $rord = $self->_branch_col_order($q, \@rhs);
5086 39 ▶ if (@$base && @$rord) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$base and @$rord) 39 0 39
Condition33%1/3
@$base and @$rord
!ll&&!rl&&r
0039
MC/DC0%0/2
@$base and @$rord
@$base @$rord
Truth table33%1/3
A and B
A= @$baseB= @$rord
ABresult
0X0
100
111
5087 39 ▶ if (@$base != @$rord) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$base != @$rord) 1 38 39
5088 1 return { type=>'error', message=>
5089 "Each SELECT of a set operation must return the same "
5090 . "number of columns (" . scalar(@$base) . " and "
5091 . scalar(@$rord) . ")" };
5092 }
5093 38 ▶ if (join("\x00", @$base) ne join("\x00", @$rord)) {
Branch: 1 branch
BranchTrueFalseTotal
if (join("\0", @$base) ne join("\0", @$rord)) 5 33 38
5094 5 my @mapped;
5095 5 for my $row (@rhs) {
5096 15 my %n;
5097 15 for my $i (0 .. $#$base) {
5098 18 $n{ $base->[$i] } = $row->{ $rord->[$i] };
5099 }
5100 15 push @mapped, { %n };
5101 }
5102 5 @rhs = @mapped;
5103 }
5104 }
5105 # Build a key string for each row for set operations
5106 my $_key = sub {
5107 270 ▶ my($row) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
5108 270 ▶ join("\x00", map { defined($row->{$_}) ? $row->{$_} : "\x01" } sort keys %$row);
Branch: 1 branch
BranchTrueFalseTotal
defined $row->{$_} ? : 276 0 276
5109 38 };
5110 38 ▶ if ($sep eq 'UNION' || $sep eq '') {
Branch: 6 branches
BranchTrueFalseTotal
if ($sep eq 'UNION' or $sep eq '') { } 3 35 38
elsif ($sep eq 'UNION_ALL') { } 4 31 35
elsif ($sep eq 'INTERSECT') { } 16 15 31
elsif ($sep eq 'INTERSECT_ALL') { } 2 13 15
elsif ($sep eq 'EXCEPT') { } 10 3 13
elsif ($sep eq 'EXCEPT_ALL') { } 3 0 3
Condition66%2/3
$sep eq "UNION" or $sep eq ""
l!l&&r!l&&!r
3035
MC/DC50%1/2
$sep eq "UNION" or $sep eq ""
$sep eq "UNION" $sep eq ""
Truth table66%2/3
A or B
A= $sep eq "UNION"B= $sep eq ""
ABresult
1X1
011
000
5111 # UNION: combine then deduplicate
5112 3 push @rows, @rhs;
5113 3 my %s; my @d;
5114 3 for my $row (@rows) {
5115 20 ▶ push @d, $row unless $s{$_key->($row)}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $s{&$_key($row)}++ 15 5 20
5116 }
5117 3 @rows = @d;
5118 }
5119 elsif ($sep eq 'UNION_ALL') {
5120 # UNION ALL: combine without deduplication
5121 4 push @rows, @rhs;
5122 }
5123 elsif ($sep eq 'INTERSECT') {
5124 # INTERSECT: keep only rows present in both (deduplicated)
5125 16 my %in_rhs;
5126 16 for my $row (@rhs) { $in_rhs{$_key->($row)} = 1 }
5127 16 my %seen; my @d;
5128 16 for my $row (@rows) {
5129 65 my $k = $_key->($row);
5130 65 ▶ push @d, $row if $in_rhs{$k} && !$seen{$k}++;
Branch: 1 branch
BranchTrueFalseTotal
if $in_rhs{$k} and not $seen{$k}++ 40 25 65
Condition100%3/3
$in_rhs{$k} and not $seen{$k}++
!ll&&!rl&&r
23240
MC/DC100%2/2
$in_rhs{$k} and not $seen{$k}++
$in_rhs{$k} not $seen{$k}++
Truth table100%3/3
A and not(B)
A= $in_rhs{$k}B= not $seen{$k}++
ABresult
0X0
100
111
5131 }
5132 16 @rows = @d;
5133 }
5134 elsif ($sep eq 'INTERSECT_ALL') {
5135 # INTERSECT ALL: keep rows present in both (with multiplicity)
5136 2 my %rhs_cnt;
5137 2 for my $row (@rhs) { $rhs_cnt{$_key->($row)}++ }
5138 2 my %used; my @d;
5139 2 for my $row (@rows) {
5140 8 my $k = $_key->($row);
5141 8 ▶ if (($rhs_cnt{$k} || 0) > ($used{$k} || 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (($rhs_cnt{$k} || 0) > ($used{$k} || 0)) 3 5 8
Condition100%4/4
$rhs_cnt{$k} || 0
l!l
53
$used{$k} || 0
l!l
35
MC/DC100%1/1
$rhs_cnt{$k} || 0
$rhs_cnt{$k}
MC/DC100%1/1
$used{$k} || 0
$used{$k}
Truth table100%2/2
A
A= $rhs_cnt{$k}
Aresult
11
00
Truth table100%2/2
A
A= $used{$k}
Aresult
11
00
5142 3 push @d, $row;
5143 3 $used{$k}++;
5144 }
5145 }
5146 2 @rows = @d;
5147 }
5148 elsif ($sep eq 'EXCEPT') {
5149 # EXCEPT: remove rows that appear in rhs (deduplicated)
5150 10 my %in_rhs;
5151 10 for my $row (@rhs) { $in_rhs{$_key->($row)} = 1 }
5152 10 my %seen; my @d;
5153 10 for my $row (@rows) {
5154 37 my $k = $_key->($row);
5155 37 ▶ push @d, $row if !$in_rhs{$k} && !$seen{$k}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $in_rhs{$k} or $seen{$k}++ 16 21 37
Condition100%3/3
$in_rhs{$k} or $seen{$k}++
l!l&&r!l&&!r
19216
MC/DC100%2/2
$in_rhs{$k} or $seen{$k}++
$in_rhs{$k} $seen{$k}++
Truth table100%3/3
A or B
A= $in_rhs{$k}B= $seen{$k}++
ABresult
1X1
011
000
5156 }
5157 10 @rows = @d;
5158 }
5159 elsif ($sep eq 'EXCEPT_ALL') {
5160 # EXCEPT ALL: remove rows with multiplicity
5161 3 my %rhs_cnt;
5162 3 for my $row (@rhs) { $rhs_cnt{$_key->($row)}++ }
5163 3 my %removed; my @d;
5164 3 for my $row (@rows) {
5165 14 my $k = $_key->($row);
5166 14 ▶ if (($rhs_cnt{$k} || 0) > ($removed{$k} || 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (($rhs_cnt{$k} || 0) > ($removed{$k} || 0)) { } 6 8 14
Condition100%4/4
$rhs_cnt{$k} || 0
l!l
104
$removed{$k} || 0
l!l
68
MC/DC100%1/1
$rhs_cnt{$k} || 0
$rhs_cnt{$k}
MC/DC100%1/1
$removed{$k} || 0
$removed{$k}
Truth table100%2/2
A
A= $rhs_cnt{$k}
Aresult
11
00
Truth table100%2/2
A
A= $removed{$k}
Aresult
11
00
5167 6 $removed{$k}++;
5168 }
5169 else {
5170 8 push @d, $row;
5171 }
5172 }
5173 3 @rows = @d;
5174 }
5175 }
5176 37 return { type=>'rows', data=>[ @rows ] };
5177 }
5178  
5179 # =============================================================================
5180 # UPDATE with expression SET
5181 # =============================================================================
5182 sub parse_set_exprs {
5183 41 ▶ my($str) = @_;
Subroutine parse_set_exprs: called CC=3 SCAR=11.0
Pod undocumented
5184 41 my %set;
5185 41 for my $part (args($str)) {
5186 43 $part =~ s/^\s+|\s+$//g;
5187 43 ▶ $set{$1} = $2 if $part =~ /^(\w+)\s*=\s*(.+)$/s;
Branch: 1 branch
BranchTrueFalseTotal
if $part =~ /^(\w+)\s*=\s*(.+)$/s 43 0 43
5188 }
5189 41 return %set;
5190 }
5191  
5192 sub update {
5193 41 ▶ my($self, $table, $set_exprs, $ws) = @_;
Subroutine update: called CC=47 SCAR=40.4
Pod undocumented
5194 41 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 41 41
5195 41 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 0 41 41
5196 41 my $dat = $self->_file($table, 'dat');
5197 41 my $rs = $sch->{recsize};
5198 41 my $n = 0;
5199 41 local *FH;
5200 41 ▶ open(FH, "+< $dat") or return $self->_err("Cannot open dat: $!");
Branch: 1 branch
BranchTrueFalseTotal
open FH, "+< $dat" or return $self->_err("Cannot open dat: $!") 0 41 41
5201 41 binmode FH;
5202 41 _autoflush(\*FH);
5203 41 _lock_ex(\*FH);
5204 41 seek(FH, 0, 0);
5205 41 my $pos = 0;
5206 41 my $rno = 0;
5207 41 while (1) {
5208 168 seek(FH, $pos, 0);
5209 168 my $raw = '';
5210 168 my $x = read(FH, $raw, $rs);
5211 168 ▶ last unless defined($x) && ($x == $rs);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x and $x == $rs 28 140 168
Condition66%2/3
defined $x and $x == $rs
!ll&&!rl&&r
028140
MC/DC50%1/2
defined $x and $x == $rs
defined $x $x == $rs
Truth table66%2/3
A and B
A= defined $xB= $x == $rs
ABresult
0X0
100
111
5212 140 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 139 1 140
5213 139 my $row = $self->_unpack_record($sch, $raw);
5214 139 ▶ if (!$ws || $ws->($row)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ws or &$ws($row)) 51 88 139
Condition100%3/3
not $ws or &$ws($row)
l!l&&r!l&&!r
44788
MC/DC100%2/2
not $ws or &$ws($row)
not $ws &$ws($row)
Truth table100%3/3
not(A) or B
A= not $wsB= &$ws($row)
ABresult
1X1
011
000
5215 51 my %old;
5216 51 for my $ix (values %{$sch->{indexes}}) {
5217 $old{$ix->{name}} = $row->{$ix->{col}}
5218 14 }
5219 51 my %orig = %$row;
5220 51 $row->{$_} = eval_expr($set_exprs->{$_}, { %orig }) for keys %$set_exprs;
5221 51 for my $ix (values %{$sch->{indexes}}) {
5222 14 ▶ next unless $ix->{unique} && exists $set_exprs->{$ix->{col}};
Branch: 1 branch
BranchTrueFalseTotal
unless $ix->{"unique"} and exists $$set_exprs{$ix->{"col"}} 9 5 14
Condition100%3/3
$ix->{"unique"} and exists $$set_exprs{$ix->{"col"}}
!ll&&!rl&&r
815
MC/DC100%2/2
$ix->{"unique"} and exists $$set_exprs{$ix->{"col"}}
$ix->{"unique"} exists $$set_exprs{$ix->{"col"}}
Truth table100%3/3
A and B
A= $ix->{"unique"}B= exists $$set_exprs{$ix->{"col"}}
ABresult
0X0
100
111
5223 5 my $nv = $row->{$ix->{col}};
5224 5 ▶ next unless defined($nv) && ($nv ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $nv and $nv ne "" 0 5 5
Condition33%1/3
defined $nv and $nv ne ""
!ll&&!rl&&r
005
MC/DC0%0/2
defined $nv and $nv ne ""
defined $nv $nv ne ""
Truth table33%1/3
A and B
A= defined $nvB= $nv ne ""
ABresult
0X0
100
111
5225 5 my $ep = $self->_idx_lookup_exact($table, $ix, $nv);
5226 5 ▶ if ($ep >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ep >= 0) 5 0 5
5227 5 my $ef = $self->_idx_file($table, $ix->{name});
5228 5 my $es = $ix->{keysize} + REC_NO_SIZE;
5229 5 local *IF_FH;
5230 5 ▶ open(IF_FH, "< $ef") or next;
Branch: 1 branch
BranchTrueFalseTotal
open IF_FH, "< $ef" or next 0 5 5
5231 5 binmode IF_FH;
5232 5 seek(IF_FH, IDX_MAGIC_LEN + $ep * $es + $ix->{keysize}, 0);
5233 5 my $rn = '';
5234 5 read(IF_FH, $rn, REC_NO_SIZE);
5235 5 close IF_FH;
5236 5 ▶ if (unpack('N', $rn) != $rno) {
Branch: 1 branch
BranchTrueFalseTotal
if (unpack("N", $rn) != $rno) 3 2 5
5237 3 _unlock(\*FH);
5238 3 close FH;
5239 3 return $self->_err("UNIQUE constraint violated on '$ix->{name}'");
5240 }
5241 }
5242 }
5243  
5244 # NOT NULL constraint check on UPDATE
5245 48 ▶ for my $cn (keys %{$sch->{notnull} || {}}) {
Branch: 1 branch
BranchTrueFalseTotal
$sch->{"notnull"} or {} 0 48 48
5246 12 ▶ next unless exists $set_exprs->{$cn};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $set_exprs->{$cn} 11 1 12
5247 1 ▶ unless (defined($row->{$cn}) && ($row->{$cn} ne '')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $row->{$cn} and $row->{$cn} ne "") 1 0 1
Condition33%1/3
defined $row->{$cn} and $row->{$cn} ne ""
!ll&&!rl&&r
010
MC/DC0%0/2
defined $row->{$cn} and $row->{$cn} ne ""
defined $row->{$cn} $row->{$cn} ne ""
Truth table33%1/3
A and B
A= defined $row->{$cn}B= $row->{$cn} ne ""
ABresult
0X0
100
111
5248 1 _unlock(\*FH);
5249 1 close FH;
5250 1 return $self->_err("NOT NULL constraint violated on column '$cn'");
5251 }
5252 }
5253 # CHECK constraint check on UPDATE
5254 47 ▶ for my $cn (keys %{$sch->{checks} || {}}) {
Branch: 1 branch
BranchTrueFalseTotal
$sch->{"checks"} or {} 0 47 47
5255 17 ▶ next unless exists $set_exprs->{$cn};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $set_exprs->{$cn} 6 11 17
5256 11 ▶ next unless defined($row->{$cn}) && ($row->{$cn} ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row->{$cn} and $row->{$cn} ne "" 0 11 11
Condition33%1/3
defined $row->{$cn} and $row->{$cn} ne ""
!ll&&!rl&&r
0011
MC/DC0%0/2
defined $row->{$cn} and $row->{$cn} ne ""
defined $row->{$cn} $row->{$cn} ne ""
Truth table33%1/3
A and B
A= defined $row->{$cn}B= $row->{$cn} ne ""
ABresult
0X0
100
111
5257 11 ▶ unless (eval_bool($sch->{checks}{$cn}, $row)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval_bool($sch->{"checks"}{$cn}, $row)) 6 5 11
5258 6 _unlock(\*FH);
5259 6 close FH;
5260 6 return $self->_err("CHECK constraint failed on column '$cn'");
5261 }
5262 }
5263 # VARCHAR / CHAR length check on UPDATE
5264 41 for my $col (@{$sch->{cols}}) {
5265 123 my $cn = $col->{name};
5266 123 ▶ next unless ($col->{type} eq 'VARCHAR' || $col->{type} eq 'CHAR');
Branch: 1 branch
BranchTrueFalseTotal
unless $col->{"type"} eq "VARCHAR" or $col->{"type"} eq "CHAR" 83 40 123
Condition100%3/3
$col->{"type"} eq "VARCHAR" or $col->{"type"} eq "CHAR"
l!l&&r!l&&!r
36483
MC/DC100%2/2
$col->{"type"} eq "VARCHAR" or $col->{"type"} eq "CHAR"
$col->{"type"} eq "VARCHAR" $col->{"type"} eq "CHAR"
Truth table100%3/3
A or B
A= $col->{"type"} eq "VARCHAR"B= $col->{"type"} eq "CHAR"
ABresult
1X1
011
000
5267 40 ▶ next unless exists $set_exprs->{$cn};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $set_exprs->{$cn} 28 12 40
5268 12 ▶ my $decl = defined($col->{decl}) ? $col->{decl} : $col->{size};
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'decl'} ? : 12 0 12
5269 12 ▶ next unless defined($decl) && ($decl < MAX_VARCHAR);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decl and $decl < 255 0 12 12
Condition33%1/3
defined $decl and $decl < 255
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $decl and $decl < 255
defined $decl $decl < 255
Truth table33%1/3
A and B
A= defined $declB= $decl < 255
ABresult
0X0
100
111
5270 12 ▶ next unless defined($row->{$cn}) && ($row->{$cn} ne '');
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row->{$cn} and $row->{$cn} ne "" 0 12 12
Condition33%1/3
defined $row->{$cn} and $row->{$cn} ne ""
!ll&&!rl&&r
0012
MC/DC0%0/2
defined $row->{$cn} and $row->{$cn} ne ""
defined $row->{$cn} $row->{$cn} ne ""
Truth table33%1/3
A and B
A= defined $row->{$cn}B= $row->{$cn} ne ""
ABresult
0X0
100
111
5271 12 ▶ if (length($row->{$cn}) > $decl) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $row->{$cn} > $decl) 1 11 12
5272 1 _unlock(\*FH);
5273 1 close FH;
5274 return $self->_err(
5275 "Value too long for column '$cn': "
5276 . "declared $col->{type}($decl), got "
5277 1 . length($row->{$cn}) . " bytes"
5278 );
5279 }
5280 }
5281 # Type check on UPDATE: INT range and DATE validity.
5282 40 for my $col (@{$sch->{cols}}) {
5283 118 ▶ next unless exists $set_exprs->{$col->{name}};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$set_exprs{$col->{"name"}} 76 42 118
5284 42 my $msg = _type_error($col, $row->{$col->{name}});
5285 42 ▶ next unless defined $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $msg 40 2 42
5286 2 _unlock(\*FH);
5287 2 close FH;
5288 2 return $self->_err($msg);
5289 }
5290 38 my $p = $self->_pack_record($sch, $row);
5291 38 seek(FH, $pos, 0);
5292 38 ▶ unless (print FH $p) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print FH $p) 0 38 38
5293 0 my $e = $!;
5294 0 _unlock(\*FH);
5295 0 close FH;
5296 0 return $self->_err("Cannot write record: $e");
5297 }
5298 38 $n++;
5299 38 for my $ix (values %{$sch->{indexes}}) {
5300 9 ▶ next unless exists $set_exprs->{$ix->{col}};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$set_exprs{$ix->{"col"}} 4 5 9
5301 5 $self->_idx_delete($table, $ix, $old{$ix->{name}}, $rno);
5302 5 $self->_idx_insert($table, $ix, $row->{$ix->{col}}, $rno);
5303 }
5304 }
5305 }
5306 127 $pos += $rs;
5307 127 $rno++;
5308 }
5309 28 _unlock(\*FH);
5310 28 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 28 28
5311 0 return $self->_err("Cannot flush dat: $!");
5312 }
5313 28 return $n;
5314 }
5315  
5316 ###############################################################################
5317 # DBI-like API -- DB::Handy::Connection / DB::Handy::Statement
5318 #
5319 # A standalone implementation with a DBI-inspired interface.
5320 #
5321 # Usage:
5322 # my $dbh = DB::Handy->connect("./data", "mydb");
5323 # my $sth = $dbh->prepare("SELECT * FROM emp WHERE id = ?");
5324 # $sth->execute(1);
5325 # while (my $row = $sth->fetchrow_hashref) { ... }
5326 # $sth->finish;
5327 # $dbh->disconnect;
5328 ###############################################################################
5329  
5330 ###############################################################################
5331 # DB::Handy::Connection -- database connection handle (like $dbh)
5332 ###############################################################################
5333 package DB::Handy::Connection;
5334 24 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
5335 24 $VERSION = '1.09'; # keep in step with $DB::Handy::VERSION (literal so
5336 24 $VERSION = $VERSION; # that PAUSE and Module::Metadata can parse it)
5337  
5338 24 ▶use vars qw($errstr);
Subroutine BEGIN: called CC=1 SCAR=0.0
5339 24 $errstr = '';
5340  
5341 # new($base_dir, $database, \%opts)
5342 sub new {
5343 48 ▶ my($class, $base_dir, $database, $opts) = @_;
Subroutine new: called CC=17 SCAR=33.6
5344 48 ▶ $opts = {} unless ref($opts) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $opts eq "HASH" 0 48 48
5345  
5346 # DBI code often opens a transaction by connecting with AutoCommit => 0.
5347 # There are no transactions here, so accepting that silently would leave
5348 # the caller believing its writes were being batched.
5349 48 ▶ if (exists($opts->{AutoCommit}) && !$opts->{AutoCommit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts->{"AutoCommit"} and not $opts->{"AutoCommit"}) 2 46 48
Condition100%3/3
exists $opts->{"AutoCommit"} and not $opts->{"AutoCommit"}
!ll&&!rl&&r
4512
MC/DC100%2/2
exists $opts->{"AutoCommit"} and not $opts->{"AutoCommit"}
exists $opts->{"AutoCommit"} not $opts->{"AutoCommit"}
Truth table100%3/3
A and not(B)
A= exists $opts->{"AutoCommit"}B= not $opts->{"AutoCommit"}
ABresult
0X0
100
111
5350 2 $errstr = "AutoCommit cannot be turned off: DB::Handy has no transactions";
5351 2 ▶ if ($opts->{RaiseError}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"RaiseError"}) 0 2 2
5352 0 die "DB::Handy connect failed: $errstr\n";
5353 }
5354 2 ▶ warn "DB::Handy: $errstr\n" if $opts->{PrintError};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"PrintError"} 0 2 2
5355 2 return undef;
5356 }
5357 46 my $engine = DB::Handy->new(base_dir => $base_dir);
5358 46 ▶ unless (defined $engine) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $engine) 0 46 46
5359 0 $errstr = $DB::Handy::errstr;
5360 0 ▶ if ($opts->{RaiseError}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"RaiseError"}) 0 0 0
5361 0 die "DB::Handy connect failed: $errstr\n";
5362 }
5363 0 return undef;
5364 }
5365 my $self = {
5366 _engine => $engine,
5367 _database => $database || '',
5368 AutoCommit => 1,
5369 RaiseError => $opts->{RaiseError} || 0,
5370 46 ▶ PrintError => (defined($opts->{PrintError}) ? $opts->{PrintError} : 0),
Branch: 1 branch
BranchTrueFalseTotal
defined $opts->{'PrintError'} ? : 4 42 46
Condition75%3/4
$database || ''
l!l
460
$opts->{'RaiseError'} || 0
l!l
244
MC/DC0%0/1
$database || ''
$database
MC/DC100%1/1
$opts->{'RaiseError'} || 0
$opts->{'RaiseError'}
Truth table50%1/2
A
A= $database
Aresult
11
00
Truth table100%2/2
A
A= $opts->{'RaiseError'}
Aresult
11
00
5371 errstr => '',
5372 err => 0,
5373 };
5374 46 bless $self, $class;
5375 46 ▶ if ($database && (!defined($opts->{AutoUse}) || $opts->{AutoUse})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($database and !defined($opts->{"AutoUse"}) || $opts->{"AutoUse"}) 45 1 46
Condition50%3/6
$database and !defined($opts->{"AutoUse"}) || $opts->{"AutoUse"}
!ll&&!rl&&r
0460
not defined $opts->{"AutoUse"} or $opts->{"AutoUse"}
l!l&&r!l&&!r
4501
MC/DC0%0/3
$database and !defined($opts->{"AutoUse"}) || $opts->{"AutoUse"}
$database not defined $opts->{"AutoUse"} $opts->{"AutoUse"}
Truth table25%1/4
A and not(B) or C
A= $databaseB= not defined $opts->{"AutoUse"}C= $opts->{"AutoUse"}
ABCresult
0XX0
1000
11X1
1011
5376 45 my $res = $engine->execute("USE $database");
5377 45 ▶ if ($res->{type} eq 'error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "error") 7 38 45
5378 7 $engine->execute("CREATE DATABASE $database");
5379 7 $res = $engine->execute("USE $database");
5380 }
5381 45 ▶ if ($res->{type} eq 'error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "error") 0 45 45
5382 0 ▶ $self->_set_err($DB::Handy::errstr || $res->{message});
Condition0%0/3
$DB::Handy::errstr || $res->{'message'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$DB::Handy::errstr || $res->{'message'}
$DB::Handy::errstr $res->{'message'}
Truth table0%0/3
A || B
A= $DB::Handy::errstrB= $res->{'message'}
ABresult
1X1
011
000
5383 0 return undef;
5384 }
5385 }
5386 46 return $self;
5387 }
5388  
5389 # connect($dsn_or_dir, $database, \%opts)
5390 # Also accepts DSN string: "base_dir=./data;database=mydb"
5391 sub connect {
5392 48 ▶ my($class, $dsn, $database, $opts) = @_;
Subroutine connect: called CC=10 SCAR=24.3
5393 48 my $base_dir;
5394 48 ▶ if (defined($dsn)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dsn) 48 0 48
5395 # Strip optional dbi:Handy: prefix for DBI-style DSN
5396 48 $dsn =~ s/^dbi\s*:\s*Handy\s*:\s*//i;
5397 }
5398 48 ▶ if (defined($dsn) && ($dsn =~ /[=;]/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dsn and $dsn =~ /[=;]/) { } 7 41 48
Condition66%2/3
defined $dsn and $dsn =~ /[=;]/
!ll&&!rl&&r
0417
MC/DC50%1/2
defined $dsn and $dsn =~ /[=;]/
defined $dsn $dsn =~ /[=;]/
Truth table66%2/3
A and B
A= defined $dsnB= $dsn =~ /[=;]/
ABresult
0X0
100
111
5399 7 my %p = map { split /=/, $_, 2 } split /;/, $dsn;
5400 7 ▶ $base_dir = $p{base_dir} || $p{dir} || '.';
Condition60%3/5
$p{'base_dir'} || $p{'dir'} || '.'
l!l
70
$p{"base_dir"} or $p{"dir"}
l!l&&r!l&&!r
250
MC/DC0%0/2
$p{'base_dir'} || $p{'dir'} || '.'
$p{"base_dir"} $p{"dir"}
Truth table66%2/3
A or B
A= $p{"base_dir"}B= $p{"dir"}
ABresult
1X1
011
000
5401 7 ▶ $database = $p{database} || $p{db} || $database;
Condition50%3/6
$p{'database'} || $p{'db'} || $database
l!l&&r!l&&!r
700
$p{"database"} or $p{"db"}
l!l&&r!l&&!r
250
MC/DC0%0/3
$p{'database'} || $p{'db'} || $database
$p{"database"} $p{"db"} $database
Truth table50%2/4
A or B || C
A= $p{"database"}B= $p{"db"}C= $database
ABCresult
1XX1
01X1
0011
0000
5402 }
5403 else {
5404 41 ▶ $base_dir = defined($dsn) ? $dsn : '.';
Branch: 1 branch
BranchTrueFalseTotal
defined $dsn ? : 41 0 41
5405 }
5406 48 ▶ $opts = {} unless ref($opts) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $opts eq "HASH" 40 8 48
5407 48 return DB::Handy::Connection->new($base_dir, $database, $opts);
5408 }
5409  
5410 # do($sql, @bind) -- shortcut for prepare+execute (useful for DDL/DML)
5411 sub do {
5412 198 ▶ my($self, $sql, @bind) = @_;
Subroutine do: called CC=2 SCAR=7.1
5413 198 ▶ my $sth = $self->prepare($sql) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->prepare($sql) or return undef 0 198 198
5414 198 return $sth->execute(@bind);
5415 }
5416  
5417 # prepare($sql) -- returns a statement handle
5418 sub prepare {
5419 461 ▶ my($self, $sql) = @_;
Subroutine prepare: called CC=3 SCAR=13.5
5420 461 $self->_clear_err;
5421 461 ▶ unless (defined($sql) && ($sql =~ /\S/)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $sql and $sql =~ /\S/) 0 461 461
Condition33%1/3
defined $sql and $sql =~ /\S/
!ll&&!rl&&r
00461
MC/DC0%0/2
defined $sql and $sql =~ /\S/
defined $sql $sql =~ /\S/
Truth table33%1/3
A and B
A= defined $sqlB= $sql =~ /\S/
ABresult
0X0
100
111
5422 0 $self->_set_err("prepare: empty SQL");
5423 0 return undef;
5424 }
5425 461 return DB::Handy::Statement->new($self, $sql);
5426 }
5427  
5428 # selectall_arrayref($sql, \%attr, @bind)
5429 # attr: Slice=>{} for array of hashrefs, Slice=>[] (default) for array of arrayrefs
5430 sub selectall_arrayref {
5431 163 ▶ my($self, $sql, $attr, @bind) = @_;
Subroutine selectall_arrayref: called CC=4 SCAR=13.9
5432 163 ▶ $attr = {} unless ref($attr) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $attr eq "HASH" 96 67 163
5433 163 ▶ my $sth = $self->prepare($sql) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->prepare($sql) or return undef 0 163 163
5434 163 ▶ $sth->execute(@bind) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@bind) or return undef 29 133 162
5435 133 return $sth->fetchall_arrayref($attr->{Slice});
5436 }
5437  
5438 # selectall_hashref($sql, $key_col, \%attr, @bind)
5439 sub selectall_hashref {
5440 2 ▶ my($self, $sql, $key_col, $attr, @bind) = @_;
Subroutine selectall_hashref: called CC=3 SCAR=11.0
5441 2 ▶ my $rows = $self->selectall_arrayref($sql, {Slice=>{}}, @bind) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $rows = $self->selectall_arrayref($sql, {"Slice", {}}, @bind) or return undef 0 2 2
5442 2 my %h;
5443 2 for my $row (@$rows) {
5444 7 $h{$row->{$key_col}} = $row;
5445 }
5446 2 return { %h };
5447 }
5448  
5449 # selectrow_hashref($sql, \%attr, @bind)
5450 sub selectrow_hashref {
5451 19 ▶ my($self, $sql, $attr, @bind) = @_;
Subroutine selectrow_hashref: called CC=3 SCAR=11.2
5452 19 ▶ my $sth = $self->prepare($sql) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->prepare($sql) or return undef 0 19 19
5453 19 ▶ $sth->execute(@bind) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@bind) or return undef 0 19 19
5454 19 my $row = $sth->fetchrow_hashref;
5455 19 $sth->finish;
5456 19 return $row;
5457 }
5458  
5459 # selectrow_arrayref($sql, \%attr, @bind)
5460 sub selectrow_arrayref {
5461 4 ▶ my($self, $sql, $attr, @bind) = @_;
Subroutine selectrow_arrayref: called CC=3 SCAR=11.2
5462 4 ▶ my $sth = $self->prepare($sql) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->prepare($sql) or return undef 0 4 4
5463 4 ▶ $sth->execute(@bind) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@bind) or return undef 0 4 4
5464 4 my $row = $sth->fetchrow_arrayref;
5465 4 $sth->finish;
5466 4 return $row;
5467 }
5468  
5469 # quote($val) -- escape a value as a SQL single-quoted literal
5470 sub quote {
5471 9 ▶ my($self, $val) = @_;
Subroutine quote: called CC=2 SCAR=6.9
5472 9 ▶ return 'NULL' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 2 7 9
5473 7 $val =~ s/'/''/g;
5474 7 return "'$val'";
5475 }
5476  
5477 # last_insert_id() -- row count recorded by the most recent INSERT
5478 # last_insert_id($catalog, $schema, $table, $field)
5479 # Arguments are accepted for DBI compatibility but ignored.
5480 7 ▶sub last_insert_id { return $_[0]->{_last_insert_id} }
Subroutine last_insert_id: called CC=1 SCAR=0.0
5481  
5482 # table_info() -- list of tables [{TABLE_NAME=>...}, ...]
5483 sub table_info {
5484 1 ▶ my($self) = @_;
Subroutine table_info: called CC=1 SCAR=0.0
5485 1 my @tables = $self->{_engine}->list_tables();
5486 1 return [ map { {TABLE_NAME=>$_, TABLE_TYPE=>'TABLE'} } @tables ];
5487 }
5488  
5489 # column_info($table) -- column metadata [{COLUMN_NAME=>..., DATA_TYPE=>...}, ...]
5490 sub column_info {
5491 1 ▶ my($self, $table) = @_;
Subroutine column_info: called CC=3 SCAR=11.3
5492 1 ▶ my $cols = $self->{_engine}->describe_table($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $cols = $self->{"_engine"}->describe_table($table) or return undef 0 1 1
5493 1 my $i = 0;
5494 1 return [ map { {
5495 COLUMN_NAME => $_->{name},
5496 DATA_TYPE => $_->{type},
5497 ORDINAL_POSITION => ++$i,
5498 IS_NULLABLE => ($_->{not_null} ? 'NO' : 'YES'),
5499 COLUMN_DEF => $_->{default},
5500 4 ▶ } } @$cols ];
Branch: 1 branch
BranchTrueFalseTotal
$_->{'not_null'} ? : 0 4 4
5501 }
5502  
5503 # disconnect()
5504 sub disconnect {
5505 43 ▶ my($self) = @_;
Subroutine disconnect: called CC=1 SCAR=0.0
5506 43 $self->{_disconnected} = 1;
5507 43 return 1;
5508 }
5509  
5510 # ping() -- returns 1 if connection is active
5511 3 ▶sub ping { return $_[0]->{_disconnected} ? 0 : 1 }
Subroutine ping: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'_disconnected'} ? : 1 2 3
5512  
5513 # AutoCommit -- always on; transactions are not supported
5514 3 ▶sub AutoCommit { return 1 }
Subroutine AutoCommit: called CC=1 SCAR=0.0
5515  
5516 # begin_work / commit / rollback
5517 # Transactions are not supported. These methods set errstr and return
5518 # undef rather than crashing, consistent with DBI error-handling style.
5519 sub begin_work {
5520 1 ▶ my($self) = @_;
Subroutine begin_work: called CC=1 SCAR=0.0
5521 1 $self->_set_err(
5522 "Transactions are not supported: DB::Handy always operates in "
5523 . "AutoCommit mode. begin_work/commit/rollback are not available."
5524 );
5525 1 return undef;
5526 }
5527 sub commit {
5528 1 ▶ my($self) = @_;
Subroutine commit: called CC=1 SCAR=0.0
5529 1 $self->_set_err(
5530 "Transactions are not supported: DB::Handy always operates in "
5531 . "AutoCommit mode. begin_work/commit/rollback are not available."
5532 );
5533 1 return undef;
5534 }
5535 sub rollback {
5536 1 ▶ my($self) = @_;
Subroutine rollback: called CC=1 SCAR=0.0
5537 1 $self->_set_err(
5538 "Transactions are not supported: DB::Handy always operates in "
5539 . "AutoCommit mode. begin_work/commit/rollback are not available."
5540 );
5541 1 return undef;
5542 }
5543  
5544 # errstr / err accessors
5545 34 ▶sub errstr { return $_[0]->{errstr} }
Subroutine errstr: called CC=1 SCAR=0.0
5546 7 ▶sub err { return $_[0]->{err} }
Subroutine err: called CC=1 SCAR=0.0
5547  
5548 # _clear_err() -- DBI resets err/errstr at the start of every method that
5549 # talks to the database, so that a stale message from an earlier failure
5550 # is never mistaken for the outcome of the call that just succeeded.
5551 sub _clear_err {
5552 921 ▶ my($self) = @_;
Subroutine _clear_err: called CC=1 SCAR=0.0
5553 921 $self->{errstr} = '';
5554 921 $self->{err} = 0;
5555 921 return;
5556 }
5557  
5558 sub _set_err {
5559 70 ▶ my($self, $msg, $code) = @_;
Subroutine _set_err: called CC=4 SCAR=13.9
5560 70 ▶ $code = 1 unless defined $code;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code 3 67 70
5561 70 $self->{errstr} = $msg;
5562 70 $self->{err} = $code;
5563 70 $errstr = $msg;
5564 70 ▶ if ($self->{PrintError}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"PrintError"}) 1 69 70
5565 1 warn "DB::Handy: $msg\n";
5566 }
5567 70 ▶ if ($self->{RaiseError}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"RaiseError"}) 3 67 70
5568 3 die "DB::Handy: $msg\n";
5569 }
5570 }
5571  
5572 ###############################################################################
5573 # DB::Handy::Statement -- statement handle (like $sth)
5574 ###############################################################################
5575 package DB::Handy::Statement;
5576 24 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
5577 24 $VERSION = '1.09'; # keep in step with $DB::Handy::VERSION (literal so
5578 24 $VERSION = $VERSION; # that PAUSE and Module::Metadata can parse it)
5579  
5580 24 ▶use vars qw($errstr);
Subroutine BEGIN: called CC=1 SCAR=0.0
5581 24 $errstr = '';
5582  
5583 sub new {
5584 461 ▶ my($class, $dbh, $sql) = @_;
Subroutine new: called CC=1 SCAR=0.0
5585 461 my $self = {
5586 _dbh => $dbh,
5587 _sql => $sql,
5588 _rows => undef,
5589 _cursor => 0,
5590 _executed => 0,
5591 _bind_params => [],
5592 rows => 0,
5593 errstr => '',
5594 err => 0,
5595 NAME => [],
5596 NAME_lc => [],
5597 NAME_uc => [],
5598 NUM_OF_FIELDS => 0,
5599 NUM_OF_PARAMS => _count_placeholders($sql),
5600 Statement => $sql,
5601 };
5602 461 bless $self, $class;
5603 461 return $self;
5604 }
5605  
5606 # Number of ? placeholders, ignoring any that sit inside a string literal
5607 # or a comment. This is the same count execute() will consume.
5608 sub _count_placeholders {
5609 461 ▶ my($sql) = @_;
Subroutine _count_placeholders: called CC=3 SCAR=11.0
5610 461 my $n = 0;
5611 461 for my $part (DB::Handy::_split_sql_literals(DB::Handy::_strip_sql_comments($sql))) {
5612 674 ▶ next if $part->[0];
Branch: 1 branch
BranchTrueFalseTotal
if $part->[0] 110 564 674
5613 564 $n += ($part->[1] =~ tr/?//);
5614 }
5615 461 return $n;
5616 }
5617  
5618 # execute(@bind_values) -- substitute ? placeholders and run the statement
5619 sub execute {
5620 460 ▶ my($self, @bind) = @_;
Subroutine execute: called CC=18 SCAR=29.1
5621 460 $self->_clear_err;
5622  
5623 # merge values pre-set via bind_param()
5624 460 ▶ if (!@bind && @{$self->{_bind_params}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @bind and @{$self->{"_bind_params"};}) 2 458 460
Condition100%3/3
not @bind and @{$self->{"_bind_params"};}
!ll&&!rl&&r
584002
MC/DC100%2/2
not @bind and @{$self->{"_bind_params"};}
not @bind @{$self->{"_bind_params"};}
Truth table100%3/3
not(A) and B
A= not @bindB= @{$self->{"_bind_params"};}
ABresult
0X0
100
111
5625 2 @bind = @{$self->{_bind_params}};
5626 }
5627  
5628 # DBI refuses a bind list whose length does not match the number of
5629 # placeholders. Without this check a missing value left a bare "?"
5630 # in the statement -- which then matched nothing -- and a surplus
5631 # value was dropped, so either mistake produced a silently wrong
5632 # result instead of an error.
5633 460 my $got = scalar @bind;
5634 460 my $need = $self->{NUM_OF_PARAMS};
5635 460 ▶ if ($got != $need) {
Branch: 1 branch
BranchTrueFalseTotal
if ($got != $need) 3 457 460
5636 3 ▶ $self->_set_err(
Branch: 2 branches
BranchTrueFalseTotal
$got == 1 ? : 1 2 3
$need == 1 ? : 2 1 3
5637 "called with $got bind variable" . (($got == 1) ? '' : 's')
5638 . " when $need " . (($need == 1) ? 'is' : 'are')
5639 . " needed"
5640 );
5641 3 return undef;
5642 }
5643  
5644 # Comments are removed first so that a ? inside one is not mistaken
5645 # for a placeholder; a ? inside a string literal is left alone too.
5646 457 my $sql = DB::Handy::_strip_sql_comments($self->{_sql});
5647  
5648 # substitute ? placeholders with actual values
5649 457 ▶ if (@bind) {
Branch: 1 branch
BranchTrueFalseTotal
if (@bind) 57 400 457
5650 57 my @params = @bind;
5651 57 my $out = '';
5652 57 for my $part (DB::Handy::_split_sql_literals($sql)) {
5653 61 ▶ if ($part->[0]) { $out .= $part->[1]; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($part->[0]) 2 59 61
5654 59 my $chunk = $part->[1];
5655 59 $chunk =~ s/\?/_dbi_quote(shift @params)/ge;
5656 59 $out .= $chunk;
5657 }
5658 57 $sql = $out;
5659 }
5660  
5661 457 my $engine = $self->{_dbh}{_engine};
5662 457 my $res = $engine->execute($sql);
5663  
5664 457 $self->{_result} = $res;
5665 457 $self->{_executed} = 1;
5666  
5667 457 ▶ if ($res->{type} eq 'error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "error") 64 393 457
5668 64 $self->_set_err($res->{message});
5669 61 return undef;
5670 }
5671  
5672 393 ▶ if ($res->{type} eq 'rows') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "rows") 222 171 393
5673 222 my $data = $res->{data};
5674 222 $self->{_rows} = $data;
5675 222 $self->{_cursor} = 0;
5676 222 my $n = scalar @$data;
5677 222 $self->{rows} = $n;
5678 # Determine column order: prefer SELECT list order; for SELECT *
5679 # use schema declaration order; fall back to alphabetical.
5680 222 my @name_order = $self->_col_order_from_sql($sql, $data, $engine);
5681 222 $self->{NAME} = [ @name_order ];
5682 222 $self->{NAME_lc} = [ map { lc $_ } @name_order ];
5683 222 $self->{NAME_uc} = [ map { uc $_ } @name_order ];
5684 222 $self->{NUM_OF_FIELDS} = scalar @name_order;
5685 222 ▶ return $n || '0E0';
Condition100%2/2
$n || '0E0'
l!l
2157
MC/DC100%1/1
$n || '0E0'
$n
Truth table100%2/2
A
A= $n
Aresult
11
00
5686 }
5687  
5688 # INSERT / UPDATE / DELETE / DDL
5689 171 ▶ if ($res->{type} eq 'ok') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "ok") 171 0 171
5690 171 my $affected = 0;
5691 171 ▶ if (defined($res->{message}) && ($res->{message} =~ /(\d+)\s+row/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $res->{"message"} and $res->{"message"} =~ /(\d+)\s+row/) 132 39 171
Condition66%2/3
defined $res->{"message"} and $res->{"message"} =~ /(\d+)\s+row/
!ll&&!rl&&r
039132
MC/DC50%1/2
defined $res->{"message"} and $res->{"message"} =~ /(\d+)\s+row/
defined $res->{"message"} $res->{"message"} =~ /(\d+)\s+row/
Truth table66%2/3
A and B
A= defined $res->{"message"}B= $res->{"message"} =~ /(\d+)\s+row/
ABresult
0X0
100
111
5692 132 $affected = $1 + 0;
5693 }
5694 171 $self->{rows} = $affected;
5695 171 $self->{_rows} = undef;
5696 171 $self->{NAME} = [];
5697 171 $self->{NAME_lc} = [];
5698 171 $self->{NAME_uc} = [];
5699 171 $self->{NUM_OF_FIELDS} = 0;
5700 171 ▶ if ($sql =~ /^\s*INSERT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^\s*INSERT\b/i) 117 54 171
5701 117 $self->{_dbh}{_last_insert_id} = $affected;
5702 }
5703 171 ▶ return $affected || '0E0';
Condition100%2/2
$affected || '0E0'
l!l
13239
MC/DC100%1/1
$affected || '0E0'
$affected
Truth table100%2/2
A
A= $affected
Aresult
11
00
5704 }
5705  
5706 # SHOW / DESCRIBE and other statement types
5707 0 ▶ if (ref($res->{data}) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $res->{"data"} eq "ARRAY") 0 0 0
5708 0 $self->{_rows} = $res->{data};
5709 0 $self->{_cursor} = 0;
5710 0 $self->{rows} = scalar @{$res->{data}};
5711 }
5712 0 return '0E0';
5713 }
5714  
5715 # _col_order_from_sql($sql, $data, $engine)
5716 #
5717 # Return column names in the order they should be presented to the caller.
5718 #
5719 # For named SELECT lists (SELECT a, b, c) the order follows the SELECT list,
5720 # including AS aliases (already handled since 1.01).
5721 #
5722 # For SELECT * on a single table the order follows the CREATE TABLE column
5723 # declaration order, obtained from the schema.
5724 #
5725 # For SELECT * on a JOIN the order follows the table appearance order in
5726 # the FROM/JOIN clause, each table's columns in declaration order, returned
5727 # as 'alias.col' qualified names matching the result-row hash keys.
5728 #
5729 # Falls back to alphabetical (sorted keys of the first data row) when the
5730 # schema cannot be resolved or the SQL cannot be parsed.
5731 #
5732 sub _col_order_from_sql {
5733 299 ▶ my($self, $sql, $data, $engine) = @_;
Subroutine _col_order_from_sql: called CC=40 SCAR=38.0
5734 # Fallback: alphabetical from first row (or empty)
5735 299 ▶ my @fallback = ($data && @$data) ? sort keys %{$data->[0]} : ();
Branch: 1 branch
BranchTrueFalseTotal
$data && @$data ? : 290 9 299
Condition66%2/3
$data and @$data
!ll&&!rl&&r
09290
MC/DC50%1/2
$data and @$data
$data @$data
Truth table66%2/3
A and B
A= $dataB= @$data
ABresult
0X0
100
111
5736 299 ▶ return @fallback unless defined $sql;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sql 0 299 299
5737 # Strip leading SELECT keyword
5738 299 my $col_str;
5739 299 ▶ if ($sql =~ /^SELECT\s+(.*?)\s+FROM\b/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SELECT\s+(.*?)\s+FROM\b/is) { } 299 0 299
5740 299 $col_str = $1;
5741 }
5742 else {
5743 0 return @fallback;
5744 }
5745 299 $col_str =~ s/^DISTINCT\s+//si;
5746 # SELECT * (or alias.*): try to use schema declaration order
5747 299 ▶ if ($col_str =~ /^\*$/ || $col_str =~ /^\w+\.\*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($col_str =~ /^\*$/ or $col_str =~ /^\w+\.\*$/) 16 283 299
Condition100%3/3
$col_str =~ /^\*$/ or $col_str =~ /^\w+\.\*$/
l!l&&r!l&&!r
151283
MC/DC100%2/2
$col_str =~ /^\*$/ or $col_str =~ /^\w+\.\*$/
$col_str =~ /^\*$/ $col_str =~ /^\w+\.\*$/
Truth table100%3/3
A or B
A= $col_str =~ /^\*$/B= $col_str =~ /^\w+\.\*$/
ABresult
1X1
011
000
5748 16 ▶ return @fallback unless defined $engine;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $engine 0 16 16
5749 # Parse FROM clause to get table name and optional alias
5750 16 ▶ if ($sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?\s*(?:WHERE|ORDER|GROUP|LIMIT|OFFSET|$)/si
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?\s*(?:WHERE|ORDER|GROUP|LIMIT|OFFSET|$)/is and not $sql =~ /\bJOIN\b/i) 12 4 16
Condition66%2/3
$sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?\s*(?:WHERE|ORDER|GROUP|LIMIT|OFFSET|$)/is and not $sql =~ /\bJOIN\b/i
!ll&&!rl&&r
4012
MC/DC50%1/2
$sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?\s*(?:WHERE|ORDER|GROUP|LIMIT|OFFSET|$)/is and not $sql =~ /\bJOIN\b/i
$sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?\s*(?:WHERE|ORDER|GROUP|LIMIT|OFFSET|$)/is not $sql =~ /\bJOIN\b/i
Truth table66%2/3
A and not(B)
A= $sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?\s*(?:WHERE|ORDER|GROUP|LIMIT|OFFSET|$)/isB= not $sql =~ /\bJOIN\b/i
ABresult
0X0
100
111
5751 && $sql !~ /\bJOIN\b/i) {
5752 12 my($tbl, $alias) = ($1, $2);
5753 12 my $sch = $engine->_load_schema($tbl);
5754 12 ▶ return @fallback unless $sch;
Branch: 1 branch
BranchTrueFalseTotal
unless $sch 0 12 12
5755 12 my @names = map { $_->{name} } @{$sch->{cols}};
5756 # Verify names match result keys
5757 12 ▶ if (@$data) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$data) 11 1 12
5758 11 my %keys = map { $_ => 1 } keys %{$data->[0]};
5759 11 ▶ return @fallback if grep { !$keys{$_} } @names;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not $keys{$_};} @names 0 11 11
5760 }
5761 12 return @names;
5762 }
5763 # JOIN: collect tables in FROM/JOIN order, build alias.col names
5764 4 ▶ if ($sql =~ /\bJOIN\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\bJOIN\b/i) 4 0 4
5765 4 ▶ return @fallback unless defined $engine;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $engine 0 4 4
5766 4 my @table_aliases;
5767 # Extract first table from FROM
5768 4 ▶ if ($sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/is) 4 0 4
5769 4 ▶ push @table_aliases, [ $1, (defined $2 ? $2 : $1) ];
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 4 0 4
5770 }
5771 # Extract subsequent JOIN tables
5772 4 my $rest = $sql;
5773 4 ▶ while ($rest =~ /\bJOIN\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/gsi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ /\bJOIN\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/sig) 4 4 8
5774 4 ▶ push @table_aliases, [ $1, (defined $2 ? $2 : $1) ];
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 4 0 4
5775 }
5776 4 my @names;
5777 4 for my $ta (@table_aliases) {
5778 8 my($tbl, $alias) = @$ta;
5779 8 my $sch = $engine->_load_schema($tbl);
5780 8 ▶ next unless $sch;
Branch: 1 branch
BranchTrueFalseTotal
unless $sch 0 8 8
5781 8 for my $col (@{$sch->{cols}}) {
5782 22 push @names, "$alias.$col->{name}";
5783 }
5784 }
5785 4 ▶ if (@names) {
Branch: 1 branch
BranchTrueFalseTotal
if (@names) 4 0 4
5786 # Verify names match result keys
5787 4 ▶ if (@$data) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$data) 4 0 4
5788 4 my %keys = map { $_ => 1 } keys %{$data->[0]};
5789 4 ▶ return @fallback if grep { !$keys{$_} } @names;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not $keys{$_};} @names 2 2 4
5790 }
5791 2 return @names;
5792 }
5793 0 return @fallback;
5794 }
5795 0 return @fallback;
5796 }
5797 # Split on commas (not inside parentheses)
5798 283 my @parts;
5799 283 my($cur, $depth) = ('', 0);
5800 283 for my $ch (split //, $col_str) {
5801 1603 ▶ if ($ch eq '(') { $depth++; $cur .= $ch }
Branch: 3 branches
BranchTrueFalseTotal
if ($ch eq '(') { } 40 1563 1603
elsif ($ch eq ')') { } 40 1523 1563
elsif ($ch eq ',' and $depth == 0) { } 93 1430 1523
5802 40 elsif ($ch eq ')') { $depth--; $cur .= $ch }
5803 93 ▶ elsif ($ch eq ',' && $depth == 0) { push @parts, $cur; $cur = '' }
Condition100%3/3
$ch eq "," and $depth == 0
!ll&&!rl&&r
1428293
MC/DC100%2/2
$ch eq "," and $depth == 0
$ch eq "," $depth == 0
Truth table100%3/3
A and B
A= $ch eq ","B= $depth == 0
ABresult
0X0
100
111
5804 1430 else { $cur .= $ch }
5805 }
5806 283 ▶ push @parts, $cur if length $cur;
Branch: 1 branch
BranchTrueFalseTotal
if length $cur 283 0 283
5807 283 my(@names, @alt);
5808 283 for my $part (@parts) {
5809 376 $part =~ s/^\s+|\s+$//g;
5810 # explicit alias: expr AS alias
5811 376 ▶ if ($part =~ /\bAS\s+(\w+)\s*$/si) {
Branch: 3 branches
BranchTrueFalseTotal
if ($part =~ /\bAS\s+(\w+)\s*$/is) { } 25 351 376
elsif ($part =~ /^(\w+)\.(\w+)$/) { } 50 301 351
elsif ($part =~ /^(\w+)$/) { } 280 21 301
5812 25 push @names, $1;
5813 25 push @alt, undef;
5814 }
5815 # qualified alias.col -> keep as 'alias.col' (JOIN result key format)
5816 elsif ($part =~ /^(\w+)\.(\w+)$/) {
5817 50 push @names, "$1.$2";
5818  
5819 # An aggregate query over a JOIN keys its output rows by the bare
5820 # column name, so 'a.y' has to be able to resolve to 'y'. Without
5821 # this the whole list was rejected below and the alphabetical
5822 # fallback took over, which put the columns of
5823 # "SELECT a.y, COUNT(*) ... GROUP BY a.y" in the order
5824 # COUNT(*), y.
5825 50 push @alt, $2;
5826 }
5827 # bare column name
5828 elsif ($part =~ /^(\w+)$/) {
5829 280 push @names, $1;
5830 280 push @alt, undef;
5831 }
5832 # complex expression without alias -> use the expression text as key
5833 else {
5834 21 push @names, $part;
5835 21 push @alt, undef;
5836 }
5837 }
5838 # Verify that every parsed name exists as a key in the result
5839 # (guards against mis-parses; also handles 0-row results)
5840 283 ▶ if (@$data) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$data) 275 8 283
5841 275 my %keys = map { $_ => 1 } keys %{$data->[0]};
5842 275 for my $i (0 .. $#names) {
5843 367 ▶ next if $keys{$names[$i]};
Branch: 1 branch
BranchTrueFalseTotal
if $keys{$names[$i]} 364 3 367
5844 3 ▶ if (defined($alt[$i]) && $keys{$alt[$i]}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $alt[$i] and $keys{$alt[$i]}) 3 0 3
Condition33%1/3
defined $alt[$i] and $keys{$alt[$i]}
!ll&&!rl&&r
003
MC/DC0%0/2
defined $alt[$i] and $keys{$alt[$i]}
defined $alt[$i] $keys{$alt[$i]}
Truth table33%1/3
A and B
A= defined $alt[$i]B= $keys{$alt[$i]}
ABresult
0X0
100
111
5845 3 $names[$i] = $alt[$i];
5846 3 next;
5847 }
5848 0 return @fallback;
5849 }
5850 }
5851 283 return @names;
5852 }
5853  
5854 # fetchrow_hashref -- return next row as hashref (undef at EOF)
5855 sub fetchrow_hashref {
5856 540 ▶ my($self) = @_;
Subroutine fetchrow_hashref: called CC=3 SCAR=11.0
5857 540 ▶ return undef unless defined $self->{_rows};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_rows"} 1 539 540
5858 539 ▶ return undef if $self->{_cursor} >= scalar @{$self->{_rows}};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_cursor"} >= scalar @{$self->{"_rows"};} 155 384 539
5859 384 my $row = $self->{_rows}[ $self->{_cursor}++ ];
5860 384 return { %$row };
5861 }
5862  
5863 # fetchrow_arrayref -- return next row as arrayref (columns in NAME order)
5864 sub fetchrow_arrayref {
5865 395 ▶ my($self) = @_;
Subroutine fetchrow_arrayref: called CC=3 SCAR=11.0
5866 395 ▶ my $href = $self->fetchrow_hashref or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $href = $self->fetchrow_hashref or return undef 126 269 395
5867 269 ▶ my @cols = @{$self->{NAME}} ? @{$self->{NAME}} : sort keys %$href;
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{'NAME'};} ? : 269 0 269
5868 269 return [ map { $href->{$_} } @cols ];
5869 }
5870  
5871 # fetchrow_array -- return next row as a list
5872 sub fetchrow_array {
5873 13 ▶ my($self) = @_;
Subroutine fetchrow_array: called CC=2 SCAR=6.9
5874 13 ▶ my $aref = $self->fetchrow_arrayref or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $aref = $self->fetchrow_arrayref or return () 2 11 13
5875 11 return @$aref;
5876 }
5877  
5878 # fetch -- alias for fetchrow_arrayref
5879 0 ▶sub fetch { return $_[0]->fetchrow_arrayref }
Subroutine fetch: not called CC=1 SCAR=6.9
5880  
5881 # fetchall_arrayref([$slice])
5882 # $slice = {} -> [{col=>val,...}, ...]
5883 # $slice = [] -> [[val,...], ...] (default)
5884 sub fetchall_arrayref {
5885 138 ▶ my($self, $slice) = @_;
Subroutine fetchall_arrayref: called CC=5 SCAR=16.1
5886 138 ▶ return undef unless defined $self->{_rows};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_rows"} 0 138 138
5887 138 my @all;
5888 138 ▶ if (ref($slice) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $slice eq 'HASH') { } 18 120 138
5889 18 ▶ while (my $row = $self->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $self->fetchrow_hashref) 47 18 65
5890 47 push @all, $row;
5891 }
5892 }
5893 else {
5894 120 ▶ while (my $row = $self->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $self->fetchrow_arrayref) 233 120 353
5895 233 push @all, $row;
5896 }
5897 }
5898 138 return [ @all ];
5899 }
5900  
5901 # fetchall_hashref($key_col) -- return rows as a hashref keyed by $key_col
5902 sub fetchall_hashref {
5903 2 ▶ my($self, $key_col) = @_;
Subroutine fetchall_hashref: called CC=2 SCAR=6.9
5904 2 my %h;
5905 2 ▶ while (my $row = $self->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $self->fetchrow_hashref) 7 2 9
5906 7 $h{$row->{$key_col}} = $row;
5907 }
5908 2 return { %h };
5909 }
5910  
5911 # bind_param($pos, $val [, $attr]) -- pre-bind a placeholder by position
5912 sub bind_param {
5913 2 ▶ my($self, $pos, $val, $attr) = @_;
Subroutine bind_param: called CC=1 SCAR=0.0
5914 2 $self->{_bind_params}[$pos - 1] = $val;
5915 2 return 1;
5916 }
5917  
5918 # finish -- reset cursor and release resources
5919 sub finish {
5920 73 ▶ my($self) = @_;
Subroutine finish: called CC=1 SCAR=0.0
5921 73 $self->{_rows} = undef;
5922 73 $self->{_cursor} = 0;
5923 73 $self->{_bind_params} = [];
5924 73 return 1;
5925 }
5926  
5927 # rows -- number of rows affected or fetched by the last execute
5928 5 ▶sub rows { return $_[0]->{rows} }
Subroutine rows: called CC=1 SCAR=0.0
5929  
5930 # errstr / err accessors
5931 5 ▶sub errstr { return $_[0]->{errstr} }
Subroutine errstr: called CC=1 SCAR=0.0
5932 2 ▶sub err { return $_[0]->{err} }
Subroutine err: called CC=1 SCAR=0.0
5933  
5934 sub _clear_err {
5935 460 ▶ my($self) = @_;
Subroutine _clear_err: called CC=2 SCAR=7.0
5936 460 $self->{errstr} = '';
5937 460 $self->{err} = 0;
5938 460 my $dbh = $self->{_dbh};
5939 460 ▶ $dbh->_clear_err if ref($dbh);
Branch: 1 branch
BranchTrueFalseTotal
if ref $dbh 460 0 460
5940 460 return;
5941 }
5942  
5943 sub _set_err {
5944 67 ▶ my($self, $msg, $code) = @_;
Subroutine _set_err: called CC=3 SCAR=11.2
5945 67 ▶ $code = 1 unless defined $code;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code 67 0 67
5946 67 $self->{errstr} = $msg;
5947 67 $self->{err} = $code;
5948 67 $errstr = $msg;
5949 67 my $dbh = $self->{_dbh};
5950 67 ▶ $dbh->_set_err($msg, $code) if ref($dbh);
Branch: 1 branch
BranchTrueFalseTotal
if ref $dbh 67 0 67
5951 }
5952  
5953 # _dbi_quote($val) -- internal helper for ? placeholder substitution
5954 sub _dbi_quote {
5955 100 ▶ my($val) = @_;
Subroutine _dbi_quote: called CC=3 SCAR=11.0
5956 100 ▶ return 'NULL' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 100 100
5957 100 ▶ return $val if $val =~ /^-?\d+\.?\d*$/; # numeric: pass through as-is
Branch: 1 branch
BranchTrueFalseTotal
if $val =~ /^-?\d+\.?\d*$/ 59 41 100
5958 41 $val =~ s/'/''/g;
5959 41 return "'$val'";
5960 }
5961  
5962 ###############################################################################
5963 # Add connect() class method to DB::Handy
5964 ###############################################################################
5965 package DB::Handy;
5966  
5967 sub connect {
5968 48 ▶ my($class, $dsn, $database, $opts) = @_;
Subroutine connect: called CC=1 SCAR=0.0
Pod documented
5969 48 return DB::Handy::Connection->connect($dsn, $database, $opts);
5970 }
5971  
5972 24 1;
5973  
5974 __END__
« blib/lib/DB/Handy.pm ↑ Summary