lib/DB/Handy.pm

filter: Statementstmt 89.9% 3176 / 3532 Branchbran 70.7% 1740 / 2460 Conditioncond 58.0% 584 / 1006 MC/DCmcdc 36.7% 219 / 596 Subroutinesub 96.2% 180 / 187 Podpod 42.8% 18 / 42 totaltotal 75.6% 5917 / 7823 CC 1747 SCAR 48.1
CC
1747
Cov
79%
__ANON__
1199.9
__ANON__
645.8
eval_expr
441.4
CRAP 123.1
↑ 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 0 ▶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.10';
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 # Names that Windows resolves to a character device rather than to a file,
73 # whatever extension follows them: "nul.sch" is the bit bucket, "con.dat"
74 # is the console. A database, table or index so named would appear to be
75 # created, silently discard every write and read back as empty. They are
76 # refused on every platform, not only on MSWin32, so that a data directory
77 # built on one system stays usable on another.
78 24 my %DEVICE_NAME = ();
79 {
80 24 my $dev;
81 24 for $dev (qw(con prn aux nul)) {
82 96 $DEVICE_NAME{$dev} = 1;
83 }
84 24 my $n;
85 24 for $n (0 .. 9) {
86 240 $DEVICE_NAME{"com$n"} = 1;
87 240 $DEVICE_NAME{"lpt$n"} = 1;
88 }
89 }
90  
91 ###############################################################################
92 # Constructor
93 ###############################################################################
94 66 ▶sub new {
Subroutine new: called CC=7 SCAR=19.9
Pod documented
95 66 my($class, %args) = @_;
96 my $self = {
97 base_dir => ($args{base_dir} || 'simpledbms_data'),
98 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
99 _tables => {},
100 _locks => {},
101 };
102 66 bless $self, $class;
103 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
104 1 my $bad = _shown_name($self->{db_name});
105 1 $errstr = "Invalid database name '$bad'";
106 1 return undef;
107 }
108 65 ▶ unless (-d $self->{base_dir}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $self->{"base_dir"}) 20 45 65
109 20 eval {
110 20 File::Path::mkpath($self->{base_dir});
111 };
112 20 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 20 20
113 0 $errstr = "Cannot create base_dir: $@";
114 0 return undef;
115 }
116 }
117 65 return $self;
118 }
119  
120 ###############################################################################
121 # Database-level
122 ###############################################################################
123 35 ▶sub create_database {
Subroutine create_database: called CC=4 SCAR=14.0
Pod documented
124 35 my($self, $db_name) = @_;
125 35 ▶ unless (_valid_name($db_name)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_valid_name($db_name)) 10 25 35
126 10 my $bad = _shown_name($db_name);
127 10 $errstr = "Invalid database name '$bad'";
128 10 return 0;
129 }
130 25 my $path = $self->_db_path($db_name);
131 25 ▶ if (-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $path) 1 24 25
132 1 $errstr = "Database '$db_name' already exists";
133 1 return 0;
134 }
135 24 eval {
136 24 File::Path::mkpath($path);
137 };
138 24 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 24 24
139 0 $errstr = "Cannot create database '$db_name': $@";
140 0 return 0;
141 }
142 24 return 1;
143 }
144  
145 84 ▶sub use_database {
Subroutine use_database: called CC=3 SCAR=11.0
Pod documented
146 84 my($self, $db_name) = @_;
147 84 ▶ unless (_valid_name($db_name)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_valid_name($db_name)) 9 75 84
148 9 my $bad = _shown_name($db_name);
149 9 $errstr = "Invalid database name '$bad'";
150 9 return 0;
151 }
152 75 my $path = $self->_db_path($db_name);
153 75 ▶ unless (-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $path) 8 67 75
154 8 $errstr = "Database '$db_name' does not exist";
155 8 return 0;
156 }
157 67 $self->{db_name} = $db_name;
158 67 $self->{_tables} = {};
159 67 return 1;
160 }
161  
162 3 ▶sub drop_database {
Subroutine drop_database: called CC=5 SCAR=17.3
Pod documented
163 3 my($self, $db_name) = @_;
164 3 ▶ unless (_valid_name($db_name)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_valid_name($db_name)) 1 2 3
165 1 my $bad = _shown_name($db_name);
166 1 $errstr = "Invalid database name '$bad'";
167 1 return 0;
168 }
169 2 my $path = $self->_db_path($db_name);
170 2 ▶ unless (-d $path) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $path) 0 2 2
171 0 $errstr = "Database '$db_name' does not exist";
172 0 return 0;
173 }
174 2 eval {
175 2 File::Path::rmtree($path);
176 };
177 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
178 0 $errstr = "Cannot drop database '$db_name': $@";
179 0 return 0;
180 }
181 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
182 2 return 1;
183 }
184  
185 4 ▶sub list_databases {
Subroutine list_databases: called CC=3 SCAR=11.5
Pod documented
186 4 my($self) = @_;
187 4 my $base = $self->{base_dir};
188 4 local *DH;
189 0 ▶ 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 () } 4 0 4
190 4 ▶ my @dbs = grep { !/^\./ && -d File::Spec->catdir($base, $_) } readdir(DH);
Condition66%2/3
!/^\./ && -d 'File::Spec'->catdir($base, $_)
!ll&&!rl&&r
804
MC/DC50%1/2
!/^\./ && -d 'File::Spec'->catdir($base, $_)
!/^\./ -d 'File::Spec'->catdir($base, $_)
Truth table66%2/3
not(A) && B
A= !/^\./B= -d 'File::Spec'->catdir($base, $_)
ABresult
0X0
100
111
191 4 closedir DH;
192 4 return sort @dbs;
193 }
194  
195 ###############################################################################
196 # Table-level
197 ###############################################################################
198 178 ▶sub create_table {
Subroutine create_table: called CC=22 SCAR=35.9
Pod documented
199 178 my($self, $table, $columns) = @_;
200 178 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 1 177 178
201 177 ▶ return $self->_err("Invalid table name '" . _shown_name($table) . "'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_name($table) 19 158 177
202 unless _valid_name($table);
203 158 my $sch_file = $self->_file($table, 'sch');
204 158 ▶ return $self->_err("Table '$table' already exists") if -f $sch_file;
Branch: 1 branch
BranchTrueFalseTotal
if -f $sch_file 0 158 158
205  
206 158 my @cols;
207 158 my $rec_size = 1;
208 158 for my $col (@$columns) {
209 354 my($name, $type, $size) = @$col;
210 354 $type = uc($type);
211 354 ▶ return $self->_err("Unknown type '$type'") unless exists $TYPE_SIZE{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $TYPE_SIZE{$type} 2 352 354
212 352 my $store;
213 352 ▶ if ($type eq 'CHAR') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'CHAR') { } 10 342 352
elsif ($type eq 'VARCHAR') { } 116 226 342
214 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
215 10 $store = int($size);
216 }
217 elsif ($type eq 'VARCHAR') {
218 116 $store = MAX_VARCHAR;
219 }
220 else {
221 226 $store = $TYPE_SIZE{$type};
222 }
223 352 $rec_size += $store;
224 # decl is the declared size (from CREATE TABLE); for VARCHAR it may
225 # differ from the physical storage size (MAX_VARCHAR).
226 352 ▶ my $decl = (defined $size && $size > 0) ? int($size) : $store;
Branch: 1 branch
BranchTrueFalseTotal
defined $size && $size > 0 ? : 125 227 352
Condition66%2/3
defined $size and $size > 0
!ll&&!rl&&r
2270125
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
227 352 push @cols, { name=>$name, type=>$type, size=>$store, decl=>$decl };
228 }
229  
230 156 local *FH;
231 156 ▶ 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: $!") 156 0 156
232 156 my $ok = print FH "VERSION=1\n";
233 156 ▶ $ok &&= print FH "RECSIZE=$rec_size\n";
Condition33%1/3
$ok &&= print(FH "RECSIZE=$rec_size\n")
!ll&&!rl&&r
00156
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
234 156 for my $c (@cols) {
235 350 ▶ $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
00350
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
236 }
237 156 my $err = $!;
238 156 ▶ unless ($ok && close(FH)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok and close FH) 0 156 156
Condition33%1/3
$ok and close FH
!ll&&!rl&&r
00156
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
239 0 ▶ $err = $! if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
240 0 ▶ close FH if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
241 0 unlink $sch_file;
242 0 return $self->_err("Cannot write schema: $err");
243 }
244  
245 156 local *FH;
246 156 my $dat_file = $self->_file($table, 'dat');
247 156 ▶ 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: $!") 156 0 156
248 156 binmode FH;
249 156 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 156 156
250 0 my $e = $!;
251 0 unlink $sch_file;
252 0 return $self->_err("Cannot create dat: $e");
253 }
254 156 return 1;
255 }
256  
257 14 ▶sub drop_table {
Subroutine drop_table: called CC=12 SCAR=25.6
Pod documented
258 14 my($self, $table) = @_;
259 14 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 14 14
260 14 ▶ return $self->_err("Invalid table name '" . _shown_name($table) . "'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_name($table) 9 5 14
261 unless _valid_name($table);
262 5 my $sch = $self->_load_schema($table);
263 5 ▶ if ($sch && $sch->{indexes}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sch and $sch->{"indexes"}) 5 0 5
Condition33%1/3
$sch and $sch->{"indexes"}
!ll&&!rl&&r
005
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
264 5 for my $ix (values %{$sch->{indexes}}) {
265 1 my $f = $self->_idx_file($table, $ix->{name});
266 1 ▶ unlink $f if -f $f;
Branch: 1 branch
BranchTrueFalseTotal
if -f $f 1 0 1
267 }
268 }
269 5 for my $ext (qw(sch dat lck)) {
270 15 my $f = $self->_file($table, $ext);
271 15 ▶ unlink $f if -f $f;
Branch: 1 branch
BranchTrueFalseTotal
if -f $f 10 5 15
272 }
273 5 my $dir = $self->_db_path($self->{db_name});
274 5 local *DH;
275 5 ▶ if (opendir DH, $dir) {
Branch: 1 branch
BranchTrueFalseTotal
if (opendir DH, $dir) 5 0 5
276 5 for my $f (readdir DH) {
277 34 ▶ unlink File::Spec->catfile($dir, $f) if $f =~ /^\Q${table}\E\.[^.]+\.idx$/;
Branch: 1 branch
BranchTrueFalseTotal
if $f =~ /^\Q$table\E\.[^.]+\.idx$/ 0 34 34
278 }
279 5 closedir DH;
280 }
281 5 delete $self->{_tables}{$table};
282 5 return 1;
283 }
284  
285 6 ▶sub list_tables {
Subroutine list_tables: called CC=4 SCAR=14.0
Pod documented
286 6 my($self) = @_;
287 6 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 6 6
288 6 my $dir = $self->_db_path($self->{db_name});
289 6 local *DH;
290 6 ▶ opendir(DH, $dir) or return ();
Branch: 1 branch
BranchTrueFalseTotal
opendir DH, $dir or return () 6 0 6
291 6 ▶ my @tbls = map { /^(.+)\.sch$/ ? $1 : () } readdir DH;
Branch: 1 branch
BranchTrueFalseTotal
/^(.+)\.sch$/ ? : 22 37 59
292 6 closedir DH;
293 6 return sort @tbls;
294 }
295  
296 6 ▶sub describe_table {
Subroutine describe_table: called CC=2 SCAR=6.9
Pod documented
297 6 my($self, $table) = @_;
298 6 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 5 1 6
299 5 return $sch->{cols};
300 }
301  
302 ###############################################################################
303 # INDEX DDL
304 ###############################################################################
305 65 ▶sub create_index {
Subroutine create_index: called CC=12 SCAR=28.7
Pod documented
306 65 my($self, $idxname, $table, $colname, $unique) = @_;
307 65 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 65 65
308 65 ▶ return $self->_err("Invalid index name '" . _shown_name($idxname) . "'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_name($idxname) 10 55 65
309 unless _valid_name($idxname);
310 55 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 55 0 55
311  
312 55 my($col_def) = grep { $_->{name} eq $colname } @{$sch->{cols}};
313 55 ▶ return $self->_err("Column '$colname' not found in '$table'") unless $col_def;
Branch: 1 branch
BranchTrueFalseTotal
unless $col_def 0 55 55
314 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
315  
316 55 ▶ $unique = $unique ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$unique ? : 22 33 55
317  
318 55 my $sch_file = $self->_file($table, 'sch');
319 55 local *FH;
320 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: $!") 55 0 55
321 55 my $ok = print FH "IDX=$idxname:$colname:$unique\n";
322 55 my $err = $!;
323 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
324 0 ▶ $err = $! if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
325 0 ▶ close FH if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
326 0 return $self->_err("Cannot update schema: $err");
327 }
328  
329 $sch->{indexes}{$idxname} = {
330 name => $idxname,
331 col => $colname,
332 unique => $unique,
333 keysize => $col_def->{size},
334 coltype => $col_def->{type},
335 55 };
336  
337 55 return $self->_rebuild_index($table, $idxname);
338 }
339  
340 11 ▶sub drop_index {
Subroutine drop_index: called CC=5 SCAR=16.4
Pod documented
341 11 my($self, $idxname, $table) = @_;
342 11 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 11 11
343 11 ▶ return $self->_err("Invalid index name '" . _shown_name($idxname) . "'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_name($idxname) 9 2 11
344 unless _valid_name($idxname);
345 2 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 2 0 2
346 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
347  
348 2 unlink $self->_idx_file($table, $idxname);
349 2 delete $sch->{indexes}{$idxname};
350 2 return $self->_rewrite_schema($table, $sch);
351 }
352  
353 8 ▶sub list_indexes {
Subroutine list_indexes: called CC=3 SCAR=11.0
Pod documented
354 8 my($self, $table) = @_;
355 8 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 8 8
356 8 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 7 1 8
357 7 return [ values %{$sch->{indexes}} ];
358 }
359  
360 ###############################################################################
361 # DML: INSERT
362 ###############################################################################
363 2014 ▶sub insert {
Subroutine insert: called CC=37 SCAR=36.8
Pod documented
364 2014 my($self, $table, $row) = @_;
365 2014 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 2014 2014
366 2014 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 2012 2 2014
367  
368 2012 for my $col (@{$sch->{cols}}) {
369 3520 my $cn = $col->{name};
370 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
371 16 $row->{$cn} = $sch->{defaults}{$cn};
372 }
373 }
374  
375 # UNIQUE check. It runs after DEFAULT has been applied, so that the
376 # value actually stored is the one compared. NULL is the empty string
377 # here and SQL-92 lets a UNIQUE column hold any number of NULLs, so an
378 # absent value is not compared at all.
379 2012 for my $ix (values %{$sch->{indexes}}) {
380 1959 ▶ next unless $ix->{unique};
Branch: 1 branch
BranchTrueFalseTotal
unless $ix->{"unique"} 1891 68 1959
381 68 my $val = $row->{$ix->{col}};
382 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
383 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
384 9 return $self->_err("UNIQUE constraint violated on '$ix->{name}' (col '$ix->{col}', value '$val')");
385 }
386 }
387  
388 2003 ▶ for my $cn (keys %{$sch->{notnull} || {}}) {
Condition50%1/2
$sch->{'notnull'} || {}
l!l
20030
MC/DC0%0/1
$sch->{'notnull'} || {}
$sch->{'notnull'}
Truth table50%1/2
A
A= $sch->{'notnull'}
Aresult
11
00
389 47 ▶ 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 39 47
Condition100%3/3
defined $row->{$cn} and $row->{$cn} ne ""
!ll&&!rl&&r
7139
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
390 }
391 1995 ▶ for my $cn (keys %{$sch->{checks} || {}}) {
Condition50%1/2
$sch->{'checks'} || {}
l!l
19950
MC/DC0%0/1
$sch->{'checks'} || {}
$sch->{'checks'}
Truth table50%1/2
A
A= $sch->{'checks'}
Aresult
11
00
392 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
393 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
394 }
395 # VARCHAR / CHAR length check: reject values longer than the declared size.
396 1990 for my $col (@{$sch->{cols}}) {
397 3461 my $cn = $col->{name};
398 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
399 1056 ▶ my $decl = defined($col->{decl}) ? $col->{decl} : $col->{size};
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'decl'} ? : 1056 0 1056
400 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
401 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
402 1026 ▶ if (length($row->{$cn}) > $decl) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $row->{$cn} > $decl) 3 1023 1026
403 return $self->_err(
404 "Value too long for column '$cn': "
405 . "declared $col->{type}($decl), got "
406 3 . length($row->{$cn}) . " bytes"
407 );
408 }
409 }
410 # Type check: INT range and DATE validity.
411 1987 for my $col (@{$sch->{cols}}) {
412 3440 my $msg = _type_error($col, $row->{$col->{name}});
413 3440 ▶ return $self->_err($msg) if defined $msg;
Branch: 1 branch
BranchTrueFalseTotal
if defined $msg 11 3429 3440
414 }
415 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 1976 0 1976
416 1976 my $dat = $self->_file($table, 'dat');
417 1976 local *FH;
418 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: $!") 1974 2 1976
419 1974 binmode FH;
420 1974 _autoflush(\*FH);
421 1974 _lock_ex(\*FH);
422 1974 my $file_size = (stat FH)[7];
423 1974 my $rec_no = int($file_size / $sch->{recsize});
424 1974 ▶ unless (print FH $packed) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print FH $packed) 0 1974 1974
425 0 my $e = $!;
426 0 _unlock(\*FH);
427 0 close FH;
428 0 return $self->_err("Cannot write record: $e");
429 }
430  
431 # The .dat lock is held until every index is updated, so that another
432 # process never sees the new record without its index entries.
433 1974 for my $ix (values %{$sch->{indexes}}) {
434 1943 $self->_idx_insert($table, $ix, $row->{$ix->{col}}, $rec_no);
435 }
436 1974 _unlock(\*FH);
437 1974 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 1974 1974
438 0 return $self->_err("Cannot flush record: $!");
439 }
440 1974 return 1;
441 }
442  
443 13 ▶sub delete_rows {
Subroutine delete_rows: called CC=12 SCAR=25.6
Pod documented
444 13 my($self, $table, $where_info) = @_;
445 13 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 13 13
446 13 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 12 1 13
447 12 my $where_sub = _to_where_sub($where_info);
448 12 my $dat = $self->_file($table, 'dat');
449 12 my $recsize = $sch->{recsize};
450 12 my $count = 0;
451  
452 12 local *FH;
453 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: $!") 12 0 12
454 12 binmode FH;
455 12 _autoflush(\*FH);
456 12 _lock_ex(\*FH);
457  
458 12 seek(FH, 0, 0);
459 12 my($pos, $rec_no) = (0, 0);
460 12 while (1) {
461 93 seek(FH, $pos, 0);
462 93 my $raw = '';
463 93 my $n = read(FH, $raw, $recsize);
464 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
465 81 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 76 5 81
466 76 my $row = $self->_unpack_record($sch, $raw);
467 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
468 14 seek(FH, $pos, 0);
469 14 ▶ unless (print FH RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print FH "\0") 0 14 14
470 0 my $e = $!;
471 0 _unlock(\*FH);
472 0 close FH;
473 0 return $self->_err("Cannot mark record deleted: $e");
474 }
475 14 $count++;
476 14 for my $ix (values %{$sch->{indexes}}) {
477 10 $self->_idx_delete($table, $ix, $row->{$ix->{col}}, $rec_no);
478 }
479 }
480 }
481 81 $pos += $recsize;
482 81 $rec_no++;
483 }
484 12 _unlock(\*FH);
485 12 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 12 12
486 0 return $self->_err("Cannot flush dat: $!");
487 }
488 12 return $count;
489 }
490  
491 ###############################################################################
492 # VACUUM
493 ###############################################################################
494 4 ▶sub vacuum {
Subroutine vacuum: called CC=13 SCAR=29.0
Pod documented
495 4 my($self, $table) = @_;
496 4 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 4 4
497 4 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 3 1 4
498 3 my $dat = $self->_file($table, 'dat');
499 3 my $tmp = $dat . '.tmp';
500 3 my $recsize = $sch->{recsize};
501  
502 3 local *IN_FH;
503 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: $!") 3 0 3
504 3 local *OUT_FH;
505 0 ▶ 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: $!") } 3 0 3
506 3 binmode IN_FH;
507 3 binmode OUT_FH;
508 3 _lock_ex(\*IN_FH);
509  
510 3 my $kept = 0;
511 3 while (1) {
512 26 my $raw = '';
513 26 my $n = read(IN_FH, $raw, $recsize);
514 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
515 23 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 18 5 23
516 18 ▶ unless (print OUT_FH $raw) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print OUT_FH $raw) 0 18 18
517 0 my $e = $!;
518 0 close OUT_FH;
519 0 _unlock(\*IN_FH);
520 0 close IN_FH;
521 0 unlink $tmp;
522 0 return $self->_err("Cannot write tmp: $e");
523 }
524 18 $kept++;
525 }
526 }
527 # close() flushes, so the replacement file is complete on disk before
528 # the exclusive lock on the original is released.
529 3 my $out_ok = close(OUT_FH);
530 3 my $out_err = $!;
531 3 _unlock(\*IN_FH);
532 3 close IN_FH;
533 3 ▶ unless ($out_ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($out_ok) 0 3 3
534 0 unlink $tmp;
535 0 return $self->_err("Cannot flush tmp: $out_err");
536 }
537 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") } 3 0 3
538 0 my $e = $!;
539 0 unlink $tmp;
540 0 return $self->_err("Cannot replace dat: $e");
541 };
542  
543 3 for my $ix (values %{$sch->{indexes}}) {
544 4 ▶ $self->_rebuild_index($table, $ix->{name}) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->_rebuild_index($table, $ix->{"name"}) or return undef 4 0 4
545 }
546 3 return $kept;
547 }
548  
549 ###############################################################################
550 # execute()
551 ###############################################################################
552 3112 ▶sub execute {
Subroutine execute: called CC=81 SCAR=45.0
Pod documented
553 3112 my($self, $sql) = @_;
554 3112 $sql = _strip_sql_comments($sql);
555 3112 $sql =~ s/^\s+|\s+$//g;
556 3112 $sql = _normalize_sql_space($sql);
557  
558 # Detect subqueries: any SELECT that contains a nested (SELECT ...)
559 # Route through the subquery engine, but guard against infinite recursion
560 # by only routing non-trivial top-level statements (not pure SELECT).
561 3112 ▶ if ($sql =~ /\(\s*SELECT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\(\s*SELECT\b/i) 44 3068 3112
562  
563 # Only intercept DML/DDL statements and complex SELECTs here;
564 # pure inner SELECTs (called recursively) pass through normally.
565 # Top-level statements that may contain subqueries:
566 44 ▶ if ($sql =~ /^(?:SELECT|INSERT|UPDATE|DELETE)\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^(?:SELECT|INSERT|UPDATE|DELETE)\b/i) 44 0 44
567 44 return $self->execute_with_subquery($sql);
568 }
569 }
570  
571 3068 ▶ if ($sql =~ /^CREATE\s+DATABASE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^CREATE\s+DATABASE\s+(\w+)$/i) 9 3059 3068
572 9 ▶ return $self->create_database($1)
Branch: 1 branch
BranchTrueFalseTotal
$self->create_database($1) ? : 9 0 9
573 ? { type=>'ok', message=>"Database '$1' created" }
574 : { type=>'error', message=>$errstr };
575 }
576 3059 ▶ if ($sql =~ /^USE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^USE\s+(\w+)$/i) 54 3005 3059
577 54 ▶ return $self->use_database($1)
Branch: 1 branch
BranchTrueFalseTotal
$self->use_database($1) ? : 47 7 54
578 ? { type=>'ok', message=>"Using database '$1'" }
579 : { type=>'error', message=>$errstr };
580 }
581 3005 ▶ if ($sql =~ /^DROP\s+DATABASE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DROP\s+DATABASE\s+(\w+)$/i) 0 3005 3005
582 0 ▶ return $self->drop_database($1)
Branch: 1 branch
BranchTrueFalseTotal
$self->drop_database($1) ? : 0 0 0
583 ? { type=>'ok', message=>"Database '$1' dropped" }
584 : { type=>'error', message=>$errstr };
585 }
586 3005 ▶ if ($sql =~ /^SHOW\s+DATABASES$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SHOW\s+DATABASES$/i) 1 3004 3005
587 1 return { type=>'list', data=>[ $self->list_databases() ] };
588 }
589 3004 ▶ if ($sql =~ /^SHOW\s+TABLES$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SHOW\s+TABLES$/i) 1 3003 3004
590 1 return { type=>'list', data=>[ $self->list_tables() ] };
591 }
592 3003 ▶ 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 3002 3003
593 1 my $ixs = $self->list_indexes($1);
594 1 ▶ return defined($ixs)
Branch: 1 branch
BranchTrueFalseTotal
defined $ixs ? : 1 0 1
595 ? { type=>'indexes', table=>$1, data=>$ixs }
596 : { type=>'error', message=>$errstr };
597 }
598 3002 ▶ if ($sql =~ /^DESCRIBE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DESCRIBE\s+(\w+)$/i) 2 3000 3002
599 2 my $cols = $self->describe_table($1);
600 2 ▶ return $cols
Branch: 1 branch
BranchTrueFalseTotal
$cols ? : 2 0 2
601 ? { type=>'describe', data=>$cols }
602 : { type=>'error', message=>$errstr };
603 }
604 3000 ▶ if ($sql =~ /^CREATE\s+TABLE\s+(\w+)\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^CREATE\s+TABLE\s+(\w+)\s*\((.+)\)$/is) 157 2843 3000
605 157 my($tbl, $col_str) = ($1, $2);
606 157 my @col_defs = _split_col_defs($col_str);
607 157 my(@cols, %nn, %defs, %chks, %uniq, $pk);
608 157 for my $cd (@col_defs) {
609 354 $cd =~ s/^\s+|\s+$//g;
610 354 ▶ 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 354 354
611 0 $pk = $1;
612 0 next;
613 }
614 # Table-level UNIQUE (col): enforced through a unique index,
615 # exactly like the column-level UNIQUE modifier below.
616 354 ▶ if ($cd =~ /^UNIQUE\s*\(\s*(\w+)\s*\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cd =~ /^UNIQUE\s*\(\s*(\w+)\s*\)$/is) 1 353 354
617 1 $uniq{$1} = 1;
618 1 next;
619 }
620 # FOREIGN KEY (...) REFERENCES ...: table-level constraint.
621 # Accepted silently (constraint is not enforced).
622 353 ▶ if ($cd =~ /^FOREIGN\s+KEY\b/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cd =~ /^FOREIGN\s+KEY\b/is) 1 352 353
623 1 next;
624 }
625 352 my($cn, $ct, $cs, $rest);
626 352 ▶ 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 228 352
elsif ($cd =~ /^(\w+)\s+(\w+)(.*)/is) { } 228 0 228
627 124 ($cn, $ct, $cs, $rest) = ($1, uc($2), $3, $4);
628 }
629 elsif ($cd =~ /^(\w+)\s+(\w+)(.*)/si) {
630 228 ($cn, $ct, $rest) = ($1, uc($2), $3);
631 228 $cs = undef;
632 }
633 else {
634 0 return { type=>'error', message=>"Cannot parse column def: $cd" };
635 }
636 352 push @cols, [ $cn, $ct, $cs ];
637 352 ▶ $rest = '' unless defined $rest;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rest 0 352 352
638 352 ▶ $pk = $cn if $rest =~ /\bPRIMARY\s+KEY\b/si;
Branch: 1 branch
BranchTrueFalseTotal
if $rest =~ /\bPRIMARY\s+KEY\b/is 7 345 352
639 352 ▶ $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 331 352
640 352 ▶ $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 345 352
defined $1 ? : 3 4 7
641 352 ▶ $chks{$cn} = $1 if $rest =~ /\bCHECK\s*\((.+)\)/si;
Branch: 1 branch
BranchTrueFalseTotal
if $rest =~ /\bCHECK\s*\((.+)\)/is 8 344 352
642 # UNIQUE is looked for with the CHECK expression removed, so
643 # that a CHECK body that happens to mention the word cannot
644 # produce a false hit.
645 352 my $ukw = $rest;
646 352 $ukw =~ s/\bCHECK\s*\(.+\)//si;
647 352 ▶ $uniq{$cn} = 1 if $ukw =~ /\bUNIQUE\b/si;
Branch: 1 branch
BranchTrueFalseTotal
if $ukw =~ /\bUNIQUE\b/is 3 349 352
648 }
649 157 ▶ $nn{$pk} = 1 if defined $pk;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pk 7 150 157
650 157 ▶ $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} 153 4 157
651 153 ▶ if (%nn || %defs || %chks || defined $pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (%nn or %defs or %chks or defined $pk) 19 134 153
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
652 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} 19 0 19
653 19 $sch->{notnull} = { %nn };
654 19 $sch->{defaults} = { %defs };
655 19 $sch->{checks} = { %chks };
656 19 ▶ $sch->{pk} = $pk if defined $pk;
Branch: 1 branch
BranchTrueFalseTotal
if defined $pk 7 12 19
657 19 $self->_rewrite_schema($tbl, $sch);
658 }
659  
660 # PRIMARY KEY and UNIQUE are enforced by insert() and update()
661 # through a unique index, so one has to be created here. Without
662 # it both constraints were silently accepted and never checked.
663 # A column that is both PRIMARY KEY and UNIQUE gets a single index.
664 153 my(@auto_idx, %seen_idx);
665 153 ▶ if (defined $pk) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pk) 7 146 153
666 7 push @auto_idx, [ $pk, $pk . '_pk' ];
667 7 $seen_idx{$pk} = 1;
668 }
669 153 for my $c (@cols) {
670 346 my $cn = $c->[0];
671 346 ▶ next unless $uniq{$cn};
Branch: 1 branch
BranchTrueFalseTotal
unless $uniq{$cn} 342 4 346
672 4 ▶ next if $seen_idx{$cn}++;
Branch: 1 branch
BranchTrueFalseTotal
if $seen_idx{$cn}++ 1 3 4
673 3 push @auto_idx, [ $cn, $cn . '_unique' ];
674 }
675 153 for my $ai (@auto_idx) {
676 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
677 0 my $msg = $errstr;
678 0 $self->drop_table($tbl);
679 0 return { type=>'error', message=>$msg };
680 }
681  
682 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
683 || $col_str =~ /\bFOREIGN\s+KEY\b/si)
684 ? " (NOTE: FOREIGN KEY constraints are not enforced)"
685 : "";
686 153 return { type=>'ok', message=>"Table '$tbl' created$fk_note" };
687 }
688 2843 ▶ if ($sql =~ /^DROP\s+TABLE\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DROP\s+TABLE\s+(\w+)$/i) 3 2840 2843
689 3 ▶ return $self->drop_table($1)
Branch: 1 branch
BranchTrueFalseTotal
$self->drop_table($1) ? : 3 0 3
690 ? { type=>'ok', message=>"Table '$1' dropped" }
691 : { type=>'error', message=>$errstr };
692 }
693 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
694 44 my($uniq, $idxname, $tbl, $col) = ($1, $2, $3, $4);
695 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
696 ? { type=>'ok', message=>"Index '$idxname' created on '$tbl'('$col')" }
697 : { type=>'error', message=>$errstr };
698 }
699 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
700 1 ▶ return $self->drop_index($1, $2)
Branch: 1 branch
BranchTrueFalseTotal
$self->drop_index($1, $2) ? : 1 0 1
701 ? { type=>'ok', message=>"Index '$1' dropped" }
702 : { type=>'error', message=>$errstr };
703 }
704 2795 ▶ if ($sql =~ /^VACUUM\s+(\w+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^VACUUM\s+(\w+)$/i) 2 2793 2795
705 2 my $n = $self->vacuum($1);
706 2 ▶ return defined($n)
Branch: 1 branch
BranchTrueFalseTotal
defined $n ? : 2 0 2
707 ? { type=>'ok', message=>"Vacuum done, $n records kept" }
708 : { type=>'error', message=>$errstr };
709 }
710 # INSERT INTO table VALUES (...) -- no column list: use schema order
711 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
712 11 my($tbl, $val_str) = ($1, $2);
713 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"} 10 1 11
714 or return { type=>'error', message=>"Table '$tbl' does not exist" };
715 10 my @cols = map { $_->{name} } @{$sch->{cols}};
716 10 my @v = _parse_values($val_str);
717 10 ▶ if (@v != @cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@v != @cols) 2 8 10
718 2 return { type=>'error',
719 message=>"INSERT: " . scalar(@v) . " value(s) for "
720 . scalar(@cols) . " column(s) in table '$tbl'" };
721 }
722 8 my %row;
723 8 @row{@cols} = @v;
724 8 ▶ return $self->insert($tbl, { %row })
Branch: 1 branch
BranchTrueFalseTotal
$self->insert($tbl, {%row}) ? : 8 0 8
725 ? { type=>'ok', message=>"1 row inserted" }
726 : { type=>'error', message=>$errstr };
727 }
728 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
729 1971 my($tbl, $col_str, $val_str) = ($1, $2, $3);
730 1971 my @c = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $col_str;
731 1971 my @v = _parse_values($val_str);
732 1971 my %row;
733 1971 @row{@c} = @v;
734 1971 ▶ return $self->insert($tbl, { %row })
Branch: 1 branch
BranchTrueFalseTotal
$self->insert($tbl, {%row}) ? : 1932 39 1971
735 ? { type=>'ok', message=>"1 row inserted" }
736 : { type=>'error', message=>$errstr };
737 }
738 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
739 12 my($tbl, $cs, $sel) = ($1, $2, $3);
740 12 my @dst_cols = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $cs;
741  
742 # Extract SELECT column list in declaration order.
743 # The engine stores rows as hashes (alphabetical key order), so we
744 # must parse the SELECT list to know the intended positional mapping.
745 12 my @src_cols;
746 12 ▶ if ($sel =~ /^SELECT\s+(.*?)\s+FROM\s+/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel =~ /^SELECT\s+(.*?)\s+FROM\s+/is) 12 0 12
747 12 @src_cols = map { my $c = $_; $c =~ s/^\s+|\s+$//g; $c =~ s/\s+AS\s+\w+$//si; $c } split /,/, $1;
748 }
749 12 my $res = $self->execute($sel);
750 12 ▶ return { type=>'error', message=>$res->{message} } if $res->{type} eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $res->{"type"} eq "error" 0 12 12
751 12 my $n = 0;
752 12 for my $r (@{$res->{data}}) {
753  
754 # Map SELECT result columns to INSERT destination columns.
755 #
756 # Name-based mapping (preferred): when every dst column name
757 # exists as a key in the result row, map by name regardless of
758 # position. This handles INSERT INTO dst(a,b) SELECT b,a FROM src
759 # correctly and is insensitive to SELECT column order.
760 #
761 # Position-based fallback: used when dst and src columns differ
762 # (e.g. INSERT INTO dst(x,y) SELECT a,b FROM src) or when src
763 # columns could not be parsed (SELECT *).
764 32 my %row;
765 32 my %rkeys = map { $_ => 1 } keys %$r;
766 my $name_based = @dst_cols
767 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
768 32 ▶ if ($name_based) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name_based) { } 27 5 32
769 27 for my $col (@dst_cols) {
770 50 $row{$col} = $r->{$col};
771 }
772 }
773 else {
774 5 ▶ my @src_keys = @src_cols ? @src_cols : sort keys %$r;
Branch: 1 branch
BranchTrueFalseTotal
@src_cols ? : 5 0 5
775 5 for my $i (0 .. $#dst_cols) {
776 $row{$dst_cols[$i]} = defined($src_keys[$i])
777 12 ▶ ? $r->{$src_keys[$i]} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $src_keys[$i] ? : 12 0 12
778 }
779 }
780 32 ▶ $self->insert($tbl, { %row }) and $n++;
Branch: 1 branch
BranchTrueFalseTotal
$self->insert($tbl, {%row}) and ++$n 32 0 32
781 }
782 12 return { type=>'ok', message=>"$n row(s) inserted" };
783 }
784 799 ▶ if ($sql =~ /^SELECT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SELECT\b/i) 739 60 799
785 739 my $sel_res = $self->select($sql);
786 739 ▶ return $sel_res if defined $sel_res;
Branch: 1 branch
BranchTrueFalseTotal
if defined $sel_res 732 7 739
787 7 return { type=>'error', message=>$errstr };
788 }
789 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
790 41 ▶ my($tbl, $set_str, $wc) = ($1, $2, (defined($3) ? $3 : ''));
Branch: 1 branch
BranchTrueFalseTotal
defined $3 ? : 40 1 41
791 41 my %se = parse_set_exprs($set_str);
792 41 my $ws;
793 41 ▶ if ($wc =~ /\bWHERE\s+(.+)/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wc =~ /\bWHERE\s+(.+)/is) 40 1 41
794 40 (my $e = $1) =~ s/^\s+|\s+$//g;
795 40 $ws = where_sub($e);
796 }
797 41 my $n = $self->update($tbl, { %se }, $ws);
798 41 ▶ return defined($n)
Branch: 1 branch
BranchTrueFalseTotal
defined $n ? : 28 13 41
799 ? { type=>'ok', message=>"$n row(s) updated" }
800 : { type=>'error', message=>$errstr };
801 }
802 19 ▶ if ($sql =~ /^DELETE\s+FROM\s+(\w+)(.*)?$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^DELETE\s+FROM\s+(\w+)(.*)?$/is) 12 7 19
803 12 ▶ my($tbl, $rest) = ($1, (defined($2) ? $2 : ''));
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 12 0 12
804 12 my $ws;
805 12 ▶ if ($rest =~ /\bWHERE\s+(.+)/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ /\bWHERE\s+(.+)/is) 12 0 12
806 12 (my $e = $1) =~ s/^\s+|\s+$//g;
807 12 $ws = where_sub($e);
808 }
809 12 my $n = $self->delete_rows($tbl, $ws);
810 12 ▶ return defined($n)
Branch: 1 branch
BranchTrueFalseTotal
defined $n ? : 12 0 12
811 ? { type=>'ok', message=>"$n row(s) deleted" }
812 : { type=>'error', message=>$errstr };
813 }
814 7 return { type=>'error', message=>"Unsupported SQL: $sql" };
815 }
816  
817 ###############################################################################
818 # SUBQUERY ENGINE
819 #
820 # Supported subquery positions:
821 #
822 # 1. WHERE col IN (SELECT single_col FROM ...)
823 # 2. WHERE col NOT IN (SELECT single_col FROM ...)
824 # 3. WHERE col OP (SELECT single_col FROM ...) OP = = != < > <= >=
825 # 4. WHERE EXISTS (SELECT ... FROM ...)
826 # 5. WHERE NOT EXISTS (SELECT ... FROM ...)
827 # 6. FROM (SELECT ...) AS alias -- derived table / inline view
828 # 7. SELECT (SELECT single_col ...) AS alias -- scalar subquery in SELECT list
829 #
830 # Nesting: subqueries may themselves contain subqueries (recursive expansion).
831 # Correlated subqueries: outer row values injected via _subq_context hashref.
832 ###############################################################################
833  
834 # ---------------------------------------------------------------------------
835 # Public wrapper: expand all subqueries in a SQL string, then execute.
836 # Called by execute() when a subquery token is detected.
837 # ---------------------------------------------------------------------------
838 63 ▶sub execute_with_subquery {
Subroutine execute_with_subquery: called CC=5 SCAR=16.3
Pod undocumented
839 63 my($self, $sql) = @_;
840  
841 # Handle derived table in FROM: FROM (SELECT ...) AS alias
842 63 ▶ if ($sql =~ /\bFROM\s*\(/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\bFROM\s*\(/i) 19 44 63
843 19 return $self->_exec_derived_table($sql);
844 }
845  
846 # Handle scalar subqueries in SELECT list: SELECT (SELECT ...) AS alias
847 44 ▶ if ($sql =~ /^SELECT\s*\(/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SELECT\s*\(/i) 0 44 44
848 0 return $self->_exec_scalar_select_subquery($sql);
849 }
850  
851 # Expand WHERE-clause subqueries iteratively (innermost first)
852 44 my $expanded = $self->_expand_where_subqueries($sql, {});
853 44 ▶ return $expanded if ref($expanded) eq 'HASH'; # error hash
Branch: 1 branch
BranchTrueFalseTotal
if ref $expanded eq "HASH" 0 44 44
854  
855 # If correlated subqueries remain (still contain (SELECT), use row-level evaluator
856 44 ▶ if ($expanded =~ /\(\s*SELECT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expanded =~ /\(\s*SELECT\b/i) 4 40 44
857 4 return $self->_exec_correlated_select($expanded);
858 }
859  
860 40 return $self->execute($expanded);
861 }
862  
863 # ---------------------------------------------------------------------------
864 # Execute a SELECT with correlated subqueries in the WHERE clause.
865 # Scans each row, evaluates the subquery with the row as outer context.
866 # ---------------------------------------------------------------------------
867 4 ▶sub _exec_correlated_select {
Subroutine _exec_correlated_select: called CC=35 SCAR=41.8
868 4 my($self, $sql) = @_;
869  
870 # Must be a plain SELECT (no JOIN, no derived table)
871 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
872 0 return { type=>'error', message=>"Cannot execute correlated query: $sql" };
873 }
874 4 ▶ my($col_str, $tbl, $rest) = ($1, $2, (defined($3) ? $3 : ''));
Branch: 1 branch
BranchTrueFalseTotal
defined $3 ? : 4 0 4
875  
876 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} 4 0 4
877  
878 # Parse col list
879 4 my @sel_cols;
880 4 ▶ unless ($col_str =~ /^\*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($col_str =~ /^\*$/) 4 0 4
881 4 @sel_cols = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $col_str;
882 }
883  
884 # Strip ORDER BY / LIMIT / OFFSET
885 4 my %opts;
886 4 ▶ if ($rest =~ s/\bLIMIT\s+(\d+)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ s/\bLIMIT\s+(\d+)//i) 0 4 4
887 0 $opts{limit} = $1;
888 }
889 4 ▶ if ($rest =~ s/\bOFFSET\s+(\d+)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ s/\bOFFSET\s+(\d+)//i) 0 4 4
890 0 $opts{offset} = $1;
891 }
892 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
893 1 $opts{order_by} = $1;
894 1 ▶ $opts{order_dir} = defined($2) ? $2 : 'ASC';
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 0 1 1
895 my @onames = @sel_cols
896 1 ? map { _order_name_of($_) } @sel_cols
897 0 ▶ : map { $_->{name} } @{$sch->{cols}};
Branch: 1 branch
BranchTrueFalseTotal
@sel_cols ? : 1 0 1
898 1 my($obe, $obk) = _resolve_order_ordinal_scalar($opts{order_by}, [ @onames ]);
899 1 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 0 1 1
900 1 $opts{order_by} = $obk;
901 }
902  
903 # Extract WHERE expression
904 4 my $where_expr = '';
905 4 ▶ if ($rest =~ /\bWHERE\s+(.+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rest =~ /\bWHERE\s+(.+)/i) 4 0 4
906 4 $where_expr = $1;
907 4 $where_expr =~ s/^\s+|\s+$//g;
908 }
909  
910 # Parse conditions (may include subquery conditions)
911 4 my $conds = $self->_parse_conditions_with_subq($where_expr);
912 4 my $filter = $self->_compile_where_with_subq($conds);
913  
914 # Full scan with per-row subquery evaluation
915 4 my $dat = $self->_file($tbl, 'dat');
916 4 my $recsize = $sch->{recsize};
917 4 my @results;
918  
919 4 local *FH;
920 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: $!"} 4 0 4
921 4 binmode FH;
922 4 _lock_sh(\*FH);
923 4 my $rec_no = 0;
924 4 while (1) {
925 32 my $raw = '';
926 32 my $n = read(FH, $raw, $recsize);
927 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
928 28 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 28 0 28
929 28 my $row = $self->_unpack_record($sch, $raw);
930  
931 # Make row available under both bare and table-qualified names
932 28 my %qrow = %$row;
933 28 for my $c (@{$sch->{cols}}) {
934 132 $qrow{"$tbl.$c->{name}"} = $row->{$c->{name}};
935 }
936 28 ▶ push @results, { %qrow } if $filter->({ %qrow });
Branch: 1 branch
BranchTrueFalseTotal
if &$filter({%qrow}) 15 13 28
937 }
938 28 $rec_no++;
939 }
940 4 _unlock(\*FH);
941 4 close FH;
942  
943 # ORDER BY
944 4 ▶ if (my $ob = $opts{order_by}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ob = $opts{"order_by"}) 1 3 4
945 1 ▶ my $dir = lc(defined($opts{order_dir}) ? $opts{order_dir} : 'asc');
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'order_dir'} ? : 1 0 1
946 @results = sort {
947 1 my($va, $vb) = ($a->{$ob}, $b->{$ob});
948 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
949 defined($vb) && ($vb =~ /^-?\d+\.?\d*$/))
950 ? ($va <=> $vb)
951 : ((defined($va) ? $va : '') cmp (defined($vb) ? $vb : ''));
952 3 ▶ ($dir eq 'desc') ? -$cmp : $cmp;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'desc' ? : 0 3 3
953 } @results;
954 }
955  
956 # OFFSET / LIMIT
957 4 ▶ my $off = defined($opts{offset}) ? $opts{offset} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'offset'} ? : 0 4 4
958 4 ▶ @results = splice(@results, $off) if $off;
Branch: 1 branch
BranchTrueFalseTotal
if $off 0 4 4
959 4 ▶ if (defined $opts{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"limit"}) 0 4 4
960 0 my $last = $opts{limit} - 1;
961 0 ▶ $last = $#results if $last > $#results;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $#results 0 0 0
962 0 @results = @results[0..$last];
963 }
964  
965 # Column projection (remove table-qualified duplicates)
966 4 my @proj;
967 4 for my $r (@results) {
968 15 my %p;
969 15 ▶ if (@sel_cols) {
Branch: 1 branch
BranchTrueFalseTotal
if (@sel_cols) { } 15 0 15
970 15 for my $c (@sel_cols) {
971 15 $p{$c} = $r->{$c};
972 }
973 }
974 else {
975  
976 # All bare columns
977 0 for my $c (@{$sch->{cols}}) {
978 0 $p{$c->{name}} = $r->{$c->{name}};
979 }
980 }
981 15 push @proj, { %p };
982 }
983  
984 4 return { type=>'rows', data=>[ @proj ] };
985 }
986  
987 # ---------------------------------------------------------------------------
988 # _expand_where_subqueries($sql, \%outer_row)
989 #
990 # Finds the innermost (SELECT ...) in a WHERE clause and replaces it with
991 # its evaluated result (a literal list or scalar). Repeats until no
992 # subqueries remain. Returns the rewritten SQL string, or error hashref.
993 # ---------------------------------------------------------------------------
994 44 ▶sub _expand_where_subqueries {
Subroutine _expand_where_subqueries: called CC=23 SCAR=32.8
995 44 my($self, $sql, $outer_row) = @_;
996 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
997  
998 44 my $max_depth = 32;
999 44 my $iter = 0;
1000  
1001 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
1002  
1003 # Find the innermost (SELECT ...) -- i.e. the one with no nested (SELECT
1004 27 my $pos = _find_innermost_subquery($sql);
1005 27 ▶ last unless defined $pos;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pos 0 27 27
1006  
1007 27 my($start, $end) = @$pos;
1008 27 my $inner_sql = substr($sql, $start + 1, $end - $start - 1);
1009 27 $inner_sql =~ s/^\s+|\s+$//g;
1010  
1011 # Determine context: what precedes the opening paren
1012 27 my $prefix = substr($sql, 0, $start);
1013  
1014 # Detect correlated subquery: inner SQL contains tablename.colname
1015 # references that are NOT from the inner query's own tables.
1016 # Heuristic: if inner_sql has \w+\.\w+ patterns, check if those
1017 # table-names appear in the inner FROM clause.
1018 27 ▶ if (_subquery_is_correlated($inner_sql)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_subquery_is_correlated($inner_sql)) 4 23 27
1019  
1020 # Cannot pre-evaluate; will be handled per-row in _compile_where_with_subq.
1021 # Mark as a correlated subquery placeholder and stop expanding here.
1022 4 last;
1023 }
1024  
1025 # Inject outer row values for correlated references
1026 23 my $resolved = $self->_resolve_correlated($inner_sql, $outer_row);
1027  
1028 # Execute the inner query
1029 23 my $inner_res = $self->execute($resolved);
1030 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
1031 0 ▶ my $msg = $inner_res ? $inner_res->{message} : $errstr;
Branch: 1 branch
BranchTrueFalseTotal
$inner_res ? : 0 0 0
1032 0 return { type=>'error', message=>"Subquery error: $msg" };
1033 }
1034  
1035 23 ▶ my @inner_rows = @{ $inner_res->{data} || [] };
Condition50%1/2
$inner_res->{'data'} || []
l!l
230
MC/DC0%0/1
$inner_res->{'data'} || []
$inner_res->{'data'}
Truth table50%1/2
A
A= $inner_res->{'data'}
Aresult
11
00
1036  
1037 # Determine what kind of subquery this is based on prefix context
1038 23 my $replacement;
1039 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
1040  
1041 # IN / NOT IN: build a parenthesised list of literal values
1042 12 my @vals;
1043 12 for my $r (@inner_rows) {
1044 17 my @rv = values %$r;
1045 17 ▶ my $v = defined($rv[0]) ? $rv[0] : 'NULL';
Branch: 1 branch
BranchTrueFalseTotal
defined $rv[0] ? : 17 0 17
1046 17 ▶ if ($v =~ /^-?\d+\.?\d*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v =~ /^-?\d+\.?\d*$/) { } 15 2 17
1047 15 push @vals, $v;
1048 }
1049 else {
1050 2 push @vals, "'$v'";
1051 }
1052 }
1053 12 ▶ if (@vals) {
Branch: 1 branch
BranchTrueFalseTotal
if (@vals) { } 10 2 12
1054 10 $replacement = '(' . join(',', @vals) . ')';
1055 }
1056 else {
1057  
1058 # Empty set semantics:
1059 # col IN (empty) -> always false -> use (NULL)
1060 # col NOT IN (empty) -> always true -> use a value that
1061 # never matches col, so NOT IN evaluates to true for
1062 # every row. We inject the sentinel '__EMPTY_SET__'
1063 # (not a valid column value) which will not match.
1064 2 ▶ if ($prefix =~ /\bNOT\s+IN\s*$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prefix =~ /\bNOT\s+IN\s*$/i) { } 1 1 2
1065 1 $replacement = "('__EMPTY_SET__')";
1066 }
1067 else {
1068 1 $replacement = '(NULL)';
1069 }
1070 }
1071 }
1072 elsif ($prefix =~ /\b(?:EXISTS|NOT\s+EXISTS)\s*$/i) {
1073  
1074 # EXISTS / NOT EXISTS: replace the paren content with 1 or 0
1075 # The EXISTS keyword stays; we replace just the (SELECT ...) with (1) or (0)
1076 3 ▶ $replacement = @inner_rows ? '(1)' : '(0)';
Branch: 1 branch
BranchTrueFalseTotal
@inner_rows ? : 1 2 3
1077 }
1078 else {
1079  
1080 # Scalar subquery (=, !=, <, >, <=, >=, or bare use)
1081 8 ▶ if (@inner_rows > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@inner_rows > 1) 0 8 8
1082 0 return { type=>'error', message=>"Subquery returns more than one row" };
1083 }
1084 8 ▶ if (@inner_rows == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@inner_rows == 0) { } 1 7 8
1085 1 $replacement = 'NULL';
1086 }
1087 else {
1088 7 my @rv = values %{ $inner_rows[0] };
1089 7 ▶ my $v = defined($rv[0]) ? $rv[0] : 'NULL';
Branch: 1 branch
BranchTrueFalseTotal
defined $rv[0] ? : 7 0 7
1090 7 ▶ $replacement = ($v =~ /^-?\d+\.?\d*$/) ? $v : "'$v'";
Branch: 1 branch
BranchTrueFalseTotal
$v =~ /^-?\d+\.?\d*$/ ? : 7 0 7
1091 }
1092 }
1093  
1094 # Splice the replacement into the SQL
1095 23 substr($sql, $start, $end - $start + 1) = $replacement;
1096 }
1097  
1098 44 return $sql;
1099 }
1100  
1101 # ---------------------------------------------------------------------------
1102 # Detect whether a subquery SQL string contains correlated outer references.
1103 # A subquery is correlated if it contains alias.colname where the alias
1104 # is NOT one of the tables listed in its own FROM clause.
1105 # ---------------------------------------------------------------------------
1106 27 ▶sub _subquery_is_correlated {
Subroutine _subquery_is_correlated: called CC=7 SCAR=20.5
1107 27 my($inner_sql) = @_;
1108  
1109 # Find tables in the inner FROM clause
1110 27 my %inner_tables;
1111  
1112 # FROM t1 [AS a1] [JOIN t2 AS a2 ON ...]*
1113 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
1114 27 ▶ $inner_tables{ lc(defined($2) ? $2 : $1) } = 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 24 3 27
1115 27 $inner_tables{ lc($1) } = 1;
1116 }
1117 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
1118 0 ▶ $inner_tables{ lc(defined($2) ? $2 : $1) } = 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 0 0 0
1119 0 $inner_tables{ lc($1) } = 1;
1120 }
1121  
1122 # Look for alias.col references in WHERE clause
1123 27 ▶ while ($inner_sql =~ /\b(\w+)\.(\w+)\b/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inner_sql =~ /\b(\w+)\.(\w+)\b/g) 5 23 28
1124 5 my($tbl, $col) = (lc($1), $2);
1125 5 ▶ return 1 unless $inner_tables{$tbl};
Branch: 1 branch
BranchTrueFalseTotal
unless $inner_tables{$tbl} 4 1 5
1126 }
1127 23 return 0;
1128 }
1129  
1130 # ---------------------------------------------------------------------------
1131 # Find the innermost (SELECT ...) -- the one whose content has no nested
1132 # (SELECT. Returns [$start_pos, $end_pos] of the outer parens, or undef.
1133 # ---------------------------------------------------------------------------
1134 27 ▶sub _find_innermost_subquery {
Subroutine _find_innermost_subquery: called CC=15 SCAR=27.1
1135 27 my($sql) = @_;
1136 27 my $len = length($sql);
1137 27 my $best_start;
1138 my $best_end;
1139  
1140 27 my $i = 0;
1141 27 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 2665 27 2692
1142  
1143 # Look for ( followed (possibly with spaces) by SELECT
1144 2665 ▶ if (substr($sql, $i, 1) eq '(' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $i, 1) eq "(") 30 2635 2665
1145  
1146 # Check if this opens a SELECT
1147 30 my $peek = substr($sql, $i+1);
1148 30 $peek =~ s/^\s+//;
1149 30 ▶ if ($peek =~ /^SELECT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($peek =~ /^SELECT\b/i) 29 1 30
1150  
1151 # Walk to matching close paren, check for no nested SELECT
1152 29 my $depth = 1;
1153 29 my $j = $i + 1;
1154 29 my $has_nested = 0;
1155 29 my $in_str = 0;
1156 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
1157 1486 my $ch = substr($sql, $j, 1);
1158 1486 ▶ if ($ch eq "'") {
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq q[']) { } 16 1470 1486
elsif (not $in_str) { } 1430 40 1470
1159  
1160 # Toggle string mode
1161 16 $in_str = !$in_str;
1162 }
1163 elsif (!$in_str) {
1164 1430 ▶ if ($ch eq '(') {
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq '(') { } 3 1427 1430
elsif ($ch eq ')') { } 32 1395 1427
1165 3 $depth++;
1166  
1167 # check for nested SELECT
1168 3 my $p2 = substr($sql, $j+1);
1169 3 $p2 =~ s/^\s+//;
1170 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
1171 }
1172 elsif ($ch eq ')') {
1173 32 $depth--;
1174 }
1175 }
1176 1486 $j++;
1177 }
1178 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
1179  
1180 # This is an innermost SELECT subquery
1181 27 $best_start = $i;
1182 27 $best_end = $j - 1;
1183  
1184 # Don't break -- we want the last (innermost) one found
1185 }
1186 }
1187 }
1188 2665 $i++;
1189 }
1190  
1191 27 ▶ return defined($best_start) ? [ $best_start, $best_end ] : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $best_start ? : 27 0 27
1192 }
1193  
1194 # ---------------------------------------------------------------------------
1195 # _resolve_correlated($inner_sql, \%outer_row)
1196 #
1197 # Replace references to outer-row columns in a correlated subquery.
1198 # Outer references appear as outer.colname or are matched when the column
1199 # name exists in %outer_row but NOT in the inner query's table.
1200 # Simple heuristic: replace outer.col tokens with the literal value.
1201 # ---------------------------------------------------------------------------
1202 51 ▶sub _resolve_correlated {
Subroutine _resolve_correlated: called CC=6 SCAR=17.9
1203 51 my($self, $sql, $outer_row) = @_;
1204 51 ▶ return $sql unless %$outer_row;
Branch: 1 branch
BranchTrueFalseTotal
unless %$outer_row 23 28 51
1205  
1206 # Build sorted list: longer (qualified) keys first so alias.col
1207 # is replaced before bare col to avoid double-substitution.
1208 28 my @keys = sort { length($b) <=> length($a) } keys %$outer_row;
1209  
1210 28 for my $qkey (@keys) {
1211 264 ▶ my $val = defined($outer_row->{$qkey}) ? $outer_row->{$qkey} : 'NULL';
Branch: 1 branch
BranchTrueFalseTotal
defined $outer_row->{$qkey} ? : 264 0 264
1212 264 ▶ my $lit = ($val =~ /^-?\d+\.?\d*$/) ? $val : "'$val'";
Branch: 1 branch
BranchTrueFalseTotal
$val =~ /^-?\d+\.?\d*$/ ? : 200 64 264
1213  
1214 264 ▶ if (index($qkey, '.') >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($qkey, '.') != -1) { } 132 132 264
1215  
1216 # Qualified key: e.g. "employees.id"
1217 # Build regex that matches the full qualified token
1218 132 (my $pat = $qkey) =~ s/\./\\./g;
1219 132 $sql =~ s/(?<![.\w])$pat(?!\w)/$lit/g;
1220 }
1221 else {
1222  
1223 # Bare key: only replace if NOT preceded by a dot
1224 # (avoids replacing "id" inside "employees.id" already handled above)
1225 132 $sql =~ s/(?<![.\w])$qkey(?!\w)/$lit/g;
1226 }
1227 }
1228 28 return $sql;
1229 }
1230  
1231 # ---------------------------------------------------------------------------
1232 # EXISTS / NOT EXISTS correlated subquery evaluation at runtime
1233 #
1234 # These must be evaluated per-outer-row, so they cannot be pre-expanded.
1235 # We detect them in _parse_conditions and defer evaluation.
1236 # ---------------------------------------------------------------------------
1237  
1238 # Enhanced _parse_conditions that understands subquery conditions.
1239 # Returns arrayref of condition hashrefs; subquery conditions have:
1240 # { type => 'subquery',
1241 # op => 'IN'|'NOT_IN'|'EXISTS'|'NOT_EXISTS'|'CMP',
1242 # col => colname, # for IN/NOT_IN/CMP
1243 # cmp_op => '='|..., # for CMP
1244 # subql => 'SELECT ...',
1245 # }
1246 6 ▶sub _parse_conditions_with_subq {
Subroutine _parse_conditions_with_subq: called CC=9 SCAR=23.1
1247 6 my($self, $expr) = @_;
1248 6 my @conds;
1249  
1250 # Split on AND (but not inside parens/strings)
1251 6 my @parts = _split_and_clauses($expr);
1252  
1253 6 for my $part (@parts) {
1254 6 $part =~ s/^\s+|\s+$//g;
1255  
1256 # EXISTS (SELECT ...)
1257 6 ▶ if ($part =~ /^(NOT\s+)?EXISTS\s*\((.+)\)\s*$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(NOT\s+)?EXISTS\s*\((.+)\)\s*$/is) 3 3 6
1258 3 my($neg, $subql) = ($1, $2);
1259 3 $subql =~ s/^\s+|\s+$//g;
1260 3 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 1 2 3
1261 type => 'subquery',
1262 op => ($neg ? 'NOT_EXISTS' : 'EXISTS'),
1263 subql => $subql,
1264 };
1265 3 next;
1266 }
1267  
1268 # col [NOT] IN (SELECT ...)
1269 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
1270 0 my($col, $neg, $subql) = ($1, $2, $3);
1271 0 $subql =~ s/^\s+|\s+$//g;
1272 0 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 0 0 0
1273 type => 'subquery',
1274 op => $neg ? 'NOT_IN' : 'IN',
1275 col => $col,
1276 subql => $subql,
1277 };
1278 0 next;
1279 }
1280  
1281 # col OP (SELECT ...)
1282 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
1283 1 my($col, $op, $subql) = ($1, uc($2), $3);
1284 1 $subql =~ s/^\s+|\s+$//g;
1285 1 push @conds, {
1286 type => 'subquery',
1287 op => 'CMP',
1288 cmp_op => $op,
1289 col => $col,
1290 subql => $subql,
1291 };
1292 1 next;
1293 }
1294  
1295 # Normal condition
1296 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
1297 2 my($col, $op, $sv, $nv) = ($1, $2, $3, $4);
1298 2 ▶ push @conds, { col=>$col, op=>uc($op), val=>defined($sv) ? $sv : $nv };
Branch: 1 branch
BranchTrueFalseTotal
defined $sv ? : 0 2 2
1299 }
1300 }
1301 6 return [ @conds ];
1302 }
1303  
1304 # Split WHERE expression on top-level AND (not inside parens or strings)
1305 6 ▶sub _split_and_clauses {
Subroutine _split_and_clauses: called CC=12 SCAR=29.5
1306 6 my($expr) = @_;
1307 6 my @parts;
1308 6 my $cur = '';
1309 6 my $depth = 0;
1310 6 my $in_str = 0;
1311 6 my $i = 0;
1312 6 my $len = length($expr);
1313  
1314 6 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 334 6 340
1315 334 my $ch = substr($expr, $i, 1);
1316 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
1317 0 $in_str = 1;
1318 0 $cur .= $ch;
1319 }
1320 ▶ 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
1321 0 $in_str = 0;
1322 0 $cur .= $ch;
1323 }
1324 elsif ($in_str) {
1325 0 $cur .= $ch;
1326 }
1327 elsif ($ch eq '(') {
1328 4 $depth++;
1329 4 $cur .= $ch;
1330 }
1331 elsif ($ch eq ')') {
1332 4 $depth--;
1333 4 $cur .= $ch;
1334 }
1335 ▶ 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
1336 0 push @parts, $cur;
1337 0 $cur = '';
1338 0 $i += 4; # skip "AND "
1339 0 next;
1340 }
1341 else {
1342 326 $cur .= $ch;
1343 }
1344 334 $i++;
1345 }
1346 6 ▶ push @parts, $cur if $cur =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $cur =~ /\S/ 6 0 6
1347 6 return @parts;
1348 }
1349  
1350 # ---------------------------------------------------------------------------
1351 # Build a where-filter sub that handles subquery conditions (evaluated
1352 # at filter time with the candidate row as outer context).
1353 # ---------------------------------------------------------------------------
1354 6 ▶sub _compile_where_with_subq {
Subroutine _compile_where_with_subq: called CC=6 SCAR=25.5
1355 6 my($self, $conds) = @_;
1356 0 ▶ 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
1357  
1358 6 my @plain;
1359 my @subq;
1360 6 for my $c (@$conds) {
1361 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
1362 4 push @subq, $c;
1363 }
1364 else {
1365 2 push @plain, $c;
1366 }
1367 }
1368  
1369 6 my $plain_sub = _compile_where_from_conds([ @plain ]);
1370  
1371 36 ▶ return sub {
Subroutine __ANON__: called CC=50 SCAR=64.7
1372 36 my($row) = @_;
1373  
1374 # Plain conditions first (fast path)
1375 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
1376  
1377 # Subquery conditions (evaluated per row)
1378 34 for my $c (@subq) {
1379 28 my $op = $c->{op};
1380 28 my $subql = $self->_resolve_correlated($c->{subql}, $row);
1381 28 my $res = $self->execute($subql);
1382 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
1383  
1384 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
1385 12 ▶ return 0 unless @rows;
Branch: 1 branch
BranchTrueFalseTotal
unless @rows 5 7 12
1386 }
1387 elsif ($op eq 'NOT_EXISTS') {
1388 8 ▶ return 0 if @rows;
Branch: 1 branch
BranchTrueFalseTotal
if @rows 4 4 8
1389 }
1390 ▶ 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
1391 0 ▶ my $col_val = defined($row->{$c->{col}}) ? $row->{$c->{col}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$c->{'col'}} ? : 0 0 0
1392 0 my $found = 0;
1393 0 my $has_null = 0;
1394 0 for my $r (@rows) {
1395 0 my @rv = values %$r;
1396 0 ▶ unless (defined $rv[0]) { $has_null = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $rv[0]) 0 0 0
1397 0 my $rv = $rv[0];
1398 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
1399 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
1400 0 $found = 1;
1401 0 last;
1402 }
1403 }
1404 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
1405 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
1406 # SQL NULL semantics: NOT IN with NULL in subquery is UNKNOWN
1407 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
1408 }
1409 elsif ($op eq 'CMP') {
1410 8 ▶ return 0 if @rows > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @rows > 1 0 8 8
1411 8 my $rhs;
1412 8 ▶ if (@rows == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (@rows == 0) { } 4 4 8
1413 4 $rhs = undef;
1414 }
1415 else {
1416 4 my @rv = values %{ $rows[0] };
1417 4 $rhs = $rv[0];
1418 }
1419 8 ▶ return 0 unless defined $rhs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rhs 4 4 8
1420 4 ▶ my $lhs = defined($row->{$c->{col}}) ? $row->{$c->{col}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$c->{'col'}} ? : 4 0 4
1421 4 my $cop = $c->{cmp_op};
1422 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
1423 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
1424 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
1425 }
1426 ▶ 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
1427 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
1428 }
1429 elsif ($cop eq '<') {
1430 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
1431 }
1432 elsif ($cop eq '>') {
1433 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
1434 }
1435 elsif ($cop eq '<=') {
1436 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
1437 }
1438 elsif ($cop eq '>=') {
1439 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
1440 }
1441 }
1442 }
1443 21 return 1;
1444 6 };
1445 }
1446  
1447 # ---------------------------------------------------------------------------
1448 # Derived table: FROM (SELECT ...) AS alias [WHERE ...] [ORDER BY ...]
1449 #
1450 # Evaluates the inner SELECT, materialises the result as an in-memory
1451 # virtual table, then applies the outer WHERE/ORDER BY/LIMIT/OFFSET.
1452 # ---------------------------------------------------------------------------
1453 19 ▶sub _exec_derived_table {
Subroutine _exec_derived_table: called CC=64 SCAR=49.9
1454 19 my($self, $sql) = @_;
1455  
1456 # Parse: SELECT outer_cols FROM (inner_sql) AS alias [WHERE ...] [ORDER BY ...] [LIMIT] [OFFSET]
1457 # Step 1: find the outer SELECT list
1458 19 ▶ unless ($sql =~ /^SELECT\s+(.+?)\s+FROM\s*\(/si) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sql =~ /^SELECT\s+(.+?)\s+FROM\s*\(/is) 0 19 19
1459 0 return { type=>'error', message=>"Cannot parse derived table query" };
1460 }
1461 19 my $outer_cols_str = $1;
1462  
1463 # Step 2: extract the (inner_sql) AS alias part using paren matching
1464 19 my $from_pos = index(lc($sql), 'from');
1465 19 my $paren_start = index($sql, '(', $from_pos);
1466 19 ▶ unless ($paren_start >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($paren_start >= 0) 0 19 19
1467 0 return { type=>'error', message=>"Cannot find subquery in FROM clause" };
1468 }
1469  
1470 19 my($inner_sql, $close_pos) = _extract_paren_content($sql, $paren_start);
1471 19 ▶ unless (defined $inner_sql) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $inner_sql) 0 19 19
1472 0 return { type=>'error', message=>"Unmatched parentheses in FROM clause" };
1473 }
1474 19 $inner_sql =~ s/^\s+|\s+$//g;
1475  
1476 # Step 3: parse alias and trailing clauses after the closing paren
1477 19 my $after = substr($sql, $close_pos + 1);
1478 19 $after =~ s/^\s+//;
1479  
1480 19 my $alias;
1481 19 ▶ if ($after =~ s/^(?:AS\s+)?(\w+)\s*//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/^(?:AS\s+)?(\w+)\s*//i) { } 19 0 19
1482 19 $alias = $1;
1483 }
1484 else {
1485 0 $alias = 'subq';
1486 }
1487  
1488 # Step 4: parse outer WHERE / ORDER BY / LIMIT / OFFSET
1489 19 my %outer_opts;
1490 19 ▶ if ($after =~ s/\bLIMIT\s+(\d+)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/\bLIMIT\s+(\d+)//i) 4 15 19
1491 4 $outer_opts{limit} = $1;
1492 }
1493 19 ▶ if ($after =~ s/\bOFFSET\s+(\d+)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/\bOFFSET\s+(\d+)//i) 0 19 19
1494 0 $outer_opts{offset} = $1;
1495 }
1496 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
1497 5 $outer_opts{order_by} = $1;
1498 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
1499 5 my @onames;
1500 5 ▶ unless ($outer_cols_str =~ /^\s*(?:\w+\.)?\*\s*$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($outer_cols_str =~ /^\s*(?:\w+\.)?\*\s*$/) 5 0 5
1501 5 @onames = map { _order_name_of($_) } split(/\s*,\s*/, $outer_cols_str);
1502 }
1503 5 my($obe, $obk) = _resolve_order_ordinal_scalar($outer_opts{order_by}, [ @onames ]);
1504 5 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 0 5 5
1505 5 $outer_opts{order_by} = $obk;
1506 }
1507 19 my $outer_having = '';
1508 19 ▶ if ($after =~ s/\bHAVING\s+(.+?)(?=\s*$)//si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ s/\bHAVING\s+(.+?)(?=\s*$)//is) 1 18 19
1509 1 $outer_having = $1;
1510 1 $outer_having =~ s/^\s+|\s+$//g;
1511 }
1512 19 my @outer_gb;
1513 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
1514 4 @outer_gb = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $1;
1515 }
1516  
1517 19 my $outer_where_str = '';
1518 19 ▶ if ($after =~ /\bWHERE\s+(.+)/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($after =~ /\bWHERE\s+(.+)/is) 2 17 19
1519 2 $outer_where_str = $1;
1520 2 $outer_where_str =~ s/^\s+|\s+$//g;
1521 }
1522  
1523 # Step 5: execute the inner query (recursing through execute_with_subquery)
1524 19 my $inner_res = $self->execute_with_subquery($inner_sql);
1525 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
1526 0 ▶ my $msg = $inner_res ? $inner_res->{message} : $errstr;
Branch: 1 branch
BranchTrueFalseTotal
$inner_res ? : 0 0 0
1527 0 return { type=>'error', message=>"Derived table subquery error: $msg" };
1528 }
1529  
1530 19 ▶ my @inner_rows = @{ $inner_res->{data} || [] };
Condition50%1/2
$inner_res->{'data'} || []
l!l
190
MC/DC0%0/1
$inner_res->{'data'} || []
$inner_res->{'data'}
Truth table50%1/2
A
A= $inner_res->{'data'}
Aresult
11
00
1531  
1532 # Step 6: qualify column names with alias (for outer WHERE resolution)
1533 19 my @qualified_rows;
1534 19 for my $r (@inner_rows) {
1535 74 my %qr;
1536 74 for my $k (keys %$r) {
1537  
1538 # Strip existing alias prefix if any, re-prefix with outer alias
1539 102 ▶ my $bare = ($k =~ /\.(\w+)$/) ? $1 : $k;
Branch: 1 branch
BranchTrueFalseTotal
$k =~ /\.(\w+)$/ ? : 0 102 102
1540 102 $qr{"$alias.$bare"} = $r->{$k};
1541 102 $qr{$bare} = $r->{$k}; # also keep bare for convenience
1542 }
1543 74 push @qualified_rows, { %qr };
1544 }
1545  
1546 # Step 7: apply outer WHERE
1547 19 ▶ if ($outer_where_str =~ /\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($outer_where_str =~ /\S/) 2 17 19
1548 2 my $conds = $self->_parse_conditions_with_subq($outer_where_str);
1549 2 my $filter = $self->_compile_where_with_subq($conds);
1550 2 @qualified_rows = grep { $filter->($_) } @qualified_rows;
1551 }
1552  
1553 # An aggregate or a GROUP BY in the outer SELECT list consumes the
1554 # materialised rows, so ORDER BY / LIMIT / OFFSET have to be applied to
1555 # the aggregated result instead of to the input.
1556 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
1557 || ($outer_cols_str =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i)) ? 1 : 0;
1558  
1559 # Step 8: ORDER BY
1560 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
1561 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
1562 # Rows are keyed "alias.col"; fall back to the bare column name so
1563 # that an unqualified sort key still resolves. The fallback key is
1564 # computed once here: deriving it inside the comparator produced an
1565 # undefined hash subscript whenever the key had no alias prefix.
1566 2 ▶ my $obb = ($ob =~ /\.(\w+)$/) ? $1 : $ob;
Branch: 1 branch
BranchTrueFalseTotal
$ob =~ /\.(\w+)$/ ? : 1 1 2
1567 @qualified_rows = sort {
1568 2 ▶ my $va = defined($a->{$ob}) ? $a->{$ob} : $a->{$obb};
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::a->{$ob} ? : 22 0 22
1569 22 ▶ my $vb = defined($b->{$ob}) ? $b->{$ob} : $b->{$obb};
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::b->{$ob} ? : 22 0 22
1570 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
1571 defined($vb) && ($vb =~ /^-?\d+\.?\d*$/))
1572 ? ($va <=> $vb)
1573 : (($va || '') cmp ($vb || ''));
1574 22 ▶ ($dir eq 'desc') ? -$cmp : $cmp;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'desc' ? : 5 17 22
1575 } @qualified_rows;
1576 }
1577  
1578 # Step 9: OFFSET / LIMIT
1579 19 ▶ unless ($outer_agg) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($outer_agg) 7 12 19
1580 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
1581 7 ▶ @qualified_rows = splice(@qualified_rows, $off) if $off;
Branch: 1 branch
BranchTrueFalseTotal
if $off 0 7 7
1582 7 ▶ if (defined $outer_opts{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $outer_opts{"limit"}) 2 5 7
1583 2 my $last = $outer_opts{limit} - 1;
1584 2 ▶ $last = $#qualified_rows if $last > $#qualified_rows;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $#qualified_rows 0 2 2
1585 2 @qualified_rows = @qualified_rows[0..$last];
1586 }
1587 }
1588  
1589 # Step 10: outer column projection
1590 19 my @proj_rows;
1591 19 ▶ if ($outer_agg) {
Branch: 2 branches
BranchTrueFalseTotal
if ($outer_agg) { } 12 7 19
elsif ($outer_cols_str =~ /^\s*\*\s*$/) { } 0 7 7
1592 12 my @specs = parse_col_list($outer_cols_str);
1593 12 @proj_rows = group_and_aggregate([ @qualified_rows ], [ @specs ],
1594 [ @outer_gb ], $outer_having);
1595 12 ▶ if (my $ob = $outer_opts{order_by}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ob = $outer_opts{"order_by"}) 3 9 12
1596 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
1597 @proj_rows = sort {
1598 3 ▶ my $va = defined($a->{$ob}) ? $a->{$ob} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::a->{$ob} ? : 2 0 2
1599 2 ▶ my $vb = defined($b->{$ob}) ? $b->{$ob} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::b->{$ob} ? : 2 0 2
1600 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
1601 ? ($va <=> $vb) : ($va cmp $vb);
1602 2 ▶ ($dir eq 'desc') ? -$cmp : $cmp;
Branch: 1 branch
BranchTrueFalseTotal
$dir eq 'desc' ? : 1 1 2
1603 } @proj_rows;
1604 }
1605 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
1606 12 ▶ @proj_rows = splice(@proj_rows, $off) if $off;
Branch: 1 branch
BranchTrueFalseTotal
if $off 0 12 12
1607 12 ▶ if (defined $outer_opts{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $outer_opts{"limit"}) 2 10 12
1608 2 my $last = $outer_opts{limit} - 1;
1609 2 ▶ $last = $#proj_rows if $last > $#proj_rows;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $#proj_rows 0 2 2
1610 2 @proj_rows = @proj_rows[0..$last];
1611 }
1612 }
1613 elsif ($outer_cols_str =~ /^\s*\*\s*$/) {
1614 0 @proj_rows = @qualified_rows;
1615 }
1616 else {
1617 7 my @want = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $outer_cols_str;
1618 7 for my $r (@qualified_rows) {
1619 22 my %p;
1620 22 for my $w (@want) {
1621 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
1622 26 $p{$w} = $r->{$w};
1623 }
1624 ▶ 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
1625 0 $p{$w} = $r->{$1};
1626 }
1627 else {
1628  
1629 # bare name search
1630 0 for my $k (keys %$r) {
1631 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
1632 0 $p{$w} = $r->{$k};
1633 0 last;
1634 }
1635 }
1636 }
1637 }
1638 22 push @proj_rows, { %p };
1639 }
1640 }
1641  
1642 19 return { type=>'rows', data=>[ @proj_rows ] };
1643 }
1644  
1645 # ---------------------------------------------------------------------------
1646 # Scalar subquery in SELECT list
1647 # SELECT (SELECT agg_col FROM t WHERE ...) AS label, other_col FROM main_tbl ...
1648 # ---------------------------------------------------------------------------
1649 0 ▶sub _exec_scalar_select_subquery {
Subroutine _exec_scalar_select_subquery: not called CC=2 SCAR=17.9
1650 0 my($self, $sql) = @_;
1651  
1652 # Strategy: collect all scalar subqueries in the SELECT list,
1653 # evaluate each, replace with the literal value, then execute the rest.
1654  
1655 # Find all top-level (SELECT ...) AS alias in the SELECT list
1656 # For simplicity: expand iteratively like WHERE subqueries
1657 0 my $expanded = $self->_expand_where_subqueries($sql, {});
1658 0 ▶ return $expanded if ref($expanded) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $expanded eq "HASH" 0 0 0
1659 0 return $self->execute($expanded);
1660 }
1661  
1662 # ---------------------------------------------------------------------------
1663 # Extract content between matching parens starting at $start_pos.
1664 # Returns ($content_without_outer_parens, $close_paren_pos).
1665 # ---------------------------------------------------------------------------
1666 19 ▶sub _extract_paren_content {
Subroutine _extract_paren_content: called CC=10 SCAR=26.2
1667 19 my($sql, $start_pos) = @_;
1668 19 my $len = length($sql);
1669 19 my $depth = 0;
1670 19 my $in_str = 0;
1671 19 for my $i ($start_pos .. $len-1) {
1672 548 my $ch = substr($sql, $i, 1);
1673 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
1674 0 $in_str = 1;
1675 }
1676 ▶ 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
1677 0 $in_str = 0;
1678 }
1679 elsif (!$in_str) {
1680 548 ▶ if ($ch eq '(') {
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq '(') { } 19 529 548
elsif ($ch eq ')') { } 19 510 529
1681 19 $depth++;
1682 }
1683 elsif ($ch eq ')') {
1684 19 $depth--;
1685 19 ▶ if ($depth == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth == 0) 19 0 19
1686 19 return (substr($sql, $start_pos+1, $i-$start_pos-1), $i);
1687 }
1688 }
1689 }
1690 }
1691 0 return (undef, undef);
1692 }
1693  
1694 ###############################################################################
1695 # Index internals
1696 ###############################################################################
1697  
1698 4253 ▶sub _idx_file {
Subroutine _idx_file: called CC=1 SCAR=0.0
1699 4253 my($self, $table, $idxname) = @_;
1700 4253 File::Spec->catfile($self->{base_dir}, $self->{db_name}, "$table.$idxname.idx");
1701 }
1702  
1703 2525 ▶sub _encode_key {
Subroutine _encode_key: called CC=10 SCAR=23.2
1704 2525 my($type, $keysize, $val) = @_;
1705 2525 ▶ $val = '' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 6 2519 2525
1706 2525 ▶ if ($type eq 'INT') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'INT') { } 1728 797 2525
elsif ($type eq 'FLOAT') { } 137 660 797
1707 1728 ▶ my $iv = _looks_numeric($val) ? int($val) : 0;
Branch: 1 branch
BranchTrueFalseTotal
_looks_numeric($val) ? : 1728 0 1728
1708 1728 ▶ $iv = INT_MAX if $iv > INT_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if $iv > 2147483647 0 1728 1728
1709 1728 ▶ $iv = INT_MIN if $iv < INT_MIN;
Branch: 1 branch
BranchTrueFalseTotal
if $iv < '-2147483648' 0 1728 1728
1710 1728 return pack('N', ($iv & 0xFFFFFFFF) ^ 0x80000000);
1711 }
1712 elsif ($type eq 'FLOAT') {
1713  
1714 # A value that is not numeric encodes as 0, exactly as it is
1715 # stored by _pack_record. The test is made here rather than left
1716 # to pack() so that -w stays quiet: an index on a FLOAT column
1717 # used to make a single INSERT emit two "isn't numeric" warnings.
1718 # my $packed = pack('d>', $val+0);
1719 137 ▶ my $packed = pack('d', _looks_numeric($val) ? $val+0 : 0);
Branch: 1 branch
BranchTrueFalseTotal
_looks_numeric($val) ? : 129 8 137
1720 137 ▶ $packed = reverse($packed) if unpack("C", pack("S", 1));
Branch: 1 branch
BranchTrueFalseTotal
if unpack "C", "\1\0" 137 0 137
1721  
1722 137 my @b = unpack('C8', $packed);
1723 137 ▶ if ($b[0] & 0x80) {
Branch: 1 branch
BranchTrueFalseTotal
if ($b[0] & 128) { } 4 133 137
1724 4 @b = map { $_ ^ 0xFF } @b;
1725 }
1726 else {
1727 133 $b[0] ^= 0x80;
1728 }
1729 137 return pack('C8', @b);
1730 }
1731 else {
1732 660 my $sv = substr($val, 0, $keysize);
1733 660 $sv .= "\x00" x ($keysize - length($sv));
1734 660 return $sv;
1735 }
1736 }
1737  
1738  
1739 2223 ▶sub _idx_entry_size {
Subroutine _idx_entry_size: called CC=1 SCAR=0.0
1740 2223 $_[0]->{keysize} + REC_NO_SIZE;
1741 }
1742  
1743 2223 ▶sub _idx_read_all {
Subroutine _idx_read_all: called CC=6 SCAR=18.4
1744 2223 my($self, $table, $ix) = @_;
1745 2223 my $idx_file = $self->_idx_file($table, $ix->{name});
1746 2223 my $entry_size = _idx_entry_size($ix);
1747 2223 my @entries;
1748 2223 ▶ return [ @entries ] unless -f $idx_file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $idx_file 0 2223 2223
1749 2223 local *FH;
1750 2223 ▶ open(FH, "< $idx_file") or return [ @entries ];
Branch: 1 branch
BranchTrueFalseTotal
open FH, "< $idx_file" or return [@entries] 2223 0 2223
1751 2223 binmode FH;
1752 2223 _lock_sh(\*FH);
1753 2223 my $magic = '';
1754 2223 read(FH, $magic, IDX_MAGIC_LEN);
1755 2223 ▶ unless ($magic eq IDX_MAGIC) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($magic eq "SDBIDX1\n") 0 2223 2223
1756 0 _unlock(\*FH);
1757 0 close FH;
1758 0 return [ @entries ];
1759 }
1760 2223 while (1) {
1761 319794 my $entry = '';
1762 319794 my $n = read(FH, $entry, $entry_size);
1763 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
1764 317571 push @entries, [ substr($entry, 0, $ix->{keysize}), unpack('N', substr($entry, $ix->{keysize}, REC_NO_SIZE)) ];
1765 }
1766 2223 _unlock(\*FH);
1767 2223 close FH;
1768 2223 return [ @entries ];
1769 }
1770  
1771 2022 ▶sub _idx_write_all {
Subroutine _idx_write_all: called CC=7 SCAR=20.6
1772 2022 my($self, $table, $ix, $entries) = @_;
1773 2022 my $idx_file = $self->_idx_file($table, $ix->{name});
1774 2022 local *FH;
1775 2022 ▶ unless (-f $idx_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $idx_file) 55 1967 2022
1776 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: $!") 55 0 55
1777 55 close FH;
1778 }
1779 # Open without truncating, so that the file is emptied only after the
1780 # exclusive lock is held. Opening with '>' truncates at open() time,
1781 # which destroys a concurrent writer's data while we wait for the lock.
1782 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: $!") 2022 0 2022
1783 2022 binmode FH;
1784 2022 _autoflush(\*FH);
1785 2022 _lock_ex(\*FH);
1786 2022 truncate(FH, 0);
1787 2022 seek(FH, 0, 0);
1788 # The whole image is assembled first and written with a single print,
1789 # so autoflush costs one write() per rebuild rather than one per entry.
1790 2022 my $image = IDX_MAGIC;
1791 2022 for my $e (@$entries) {
1792 315025 $image .= $e->[0] . pack('N', $e->[1]);
1793 }
1794 2022 my $ok = print FH $image;
1795 2022 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 2022 2022
1796 0 my $e = $!;
1797 0 _unlock(\*FH);
1798 0 close FH;
1799 0 return $self->_err("Cannot write index: $e");
1800 }
1801 2022 _unlock(\*FH);
1802 2022 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 2022 2022
1803 0 return $self->_err("Cannot flush index: $!");
1804 }
1805 2022 return 1;
1806 }
1807  
1808 2430 ▶sub _idx_bisect {
Subroutine _idx_bisect: called CC=3 SCAR=11.0
1809 2430 my($entries, $key_bytes) = @_;
1810 2430 my($lo, $hi) = (0, scalar @$entries);
1811 2430 ▶ while ($lo < $hi) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo < $hi) 13740 2430 16170
1812 13740 my $mid = int(($lo + $hi) / 2);
1813 13740 ▶ if ($entries->[$mid][0] lt $key_bytes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entries->[$mid][0] lt $key_bytes) { } 9657 4083 13740
1814 9657 $lo = $mid + 1;
1815 }
1816 else {
1817 4083 $hi = $mid;
1818 }
1819 }
1820 2430 return $lo;
1821 }
1822  
1823 69 ▶sub _idx_lookup_exact {
Subroutine _idx_lookup_exact: called CC=3 SCAR=11.0
1824 69 my($self, $table, $ix, $val) = @_;
1825 69 my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
1826 69 my $entries = $self->_idx_read_all($table, $ix);
1827 69 my $pos = _idx_bisect($entries, $key_bytes);
1828 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
1829 14 return $pos;
1830 }
1831 55 return -1;
1832 }
1833  
1834 1948 ▶sub _idx_insert {
Subroutine _idx_insert: called CC=1 SCAR=0.0
1835 1948 my($self, $table, $ix, $val, $rec_no) = @_;
1836 1948 my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
1837 1948 my $entries = $self->_idx_read_all($table, $ix);
1838 1948 my $pos = _idx_bisect($entries, $key_bytes);
1839 1948 splice(@$entries, $pos, 0, [$key_bytes, $rec_no]);
1840 1948 return $self->_idx_write_all($table, $ix, $entries);
1841 }
1842  
1843 15 ▶sub _idx_delete {
Subroutine _idx_delete: called CC=5 SCAR=16.7
1844 15 my($self, $table, $ix, $val, $rec_no) = @_;
1845 15 my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
1846 15 my $entries = $self->_idx_read_all($table, $ix);
1847 15 my $pos = _idx_bisect($entries, $key_bytes);
1848 15 my $deleted = 0;
1849 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
1850 21 ▶ if ($entries->[$pos][1] == $rec_no) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entries->[$pos][1] == $rec_no) 15 6 21
1851 15 splice(@$entries, $pos, 1);
1852 15 $deleted++;
1853 15 last;
1854 }
1855 6 $pos++;
1856 }
1857 15 ▶ return $self->_idx_write_all($table, $ix, $entries) if $deleted;
Branch: 1 branch
BranchTrueFalseTotal
if $deleted 15 0 15
1858 0 return 1;
1859 }
1860  
1861 39 ▶sub _idx_range {
Subroutine _idx_range: called CC=10 SCAR=23.0
1862 39 my($self, $table, $ix, $lo_val, $lo_inc, $hi_val, $hi_inc) = @_;
1863 39 my $entries = $self->_idx_read_all($table, $ix);
1864 39 ▶ return [] unless @$entries;
Branch: 1 branch
BranchTrueFalseTotal
unless @$entries 0 39 39
1865  
1866 39 my $lo_pos = 0;
1867 39 ▶ if (defined $lo_val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $lo_val) 32 7 39
1868 32 my $lo_key = _encode_key($ix->{coltype}, $ix->{keysize}, $lo_val);
1869 32 $lo_pos = _idx_bisect($entries, $lo_key);
1870 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
1871 }
1872 39 my $hi_pos = scalar @$entries;
1873 39 ▶ if (defined $hi_val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $hi_val) 23 16 39
1874 23 my $hi_key = _encode_key($ix->{coltype}, $ix->{keysize}, $hi_val);
1875 23 my $p = _idx_bisect($entries, $hi_key);
1876 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
1877 23 $hi_pos = $p;
1878 }
1879 39 return [ map { $entries->[$_][1] } $lo_pos .. $hi_pos-1 ];
1880 }
1881  
1882 59 ▶sub _rebuild_index {
Subroutine _rebuild_index: called CC=8 SCAR=20.9
1883 59 my($self, $table, $idxname) = @_;
1884 59 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 59 0 59
1885 59 my $ix = $sch->{indexes}{$idxname};
1886 59 ▶ return $self->_err("Index '$idxname' not found") unless $ix;
Branch: 1 branch
BranchTrueFalseTotal
unless $ix 0 59 59
1887 59 my $dat = $self->_file($table, 'dat');
1888 59 my $recsize = $sch->{recsize};
1889 59 my @entries;
1890 59 ▶ if (-f $dat) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $dat) 59 0 59
1891 59 local *FH;
1892 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: $!") 59 0 59
1893 59 binmode FH;
1894 59 _lock_sh(\*FH);
1895 59 my $rec_no = 0;
1896 59 while (1) {
1897 155 my $raw = '';
1898 155 my $n = read(FH, $raw, $recsize);
1899 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
1900 96 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 95 1 96
1901 95 my $row = $self->_unpack_record($sch, $raw);
1902 95 push @entries, [ _encode_key($ix->{coltype}, $ix->{keysize}, $row->{$ix->{col}}), $rec_no ];
1903 }
1904 96 $rec_no++;
1905 }
1906 59 _unlock(\*FH);
1907 59 close FH;
1908 }
1909 59 @entries = sort { $a->[0] cmp $b->[0] } @entries;
1910 59 return $self->_idx_write_all($table, $ix, [ @entries ]);
1911 }
1912  
1913 235 ▶sub _find_index_for_conds {
Subroutine _find_index_for_conds: called CC=14 SCAR=26.4
1914 235 my($self, $table, $sch, $conds) = @_;
1915 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
1916 235 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 177 58 235
1917 58 my %col2ix;
1918 58 for my $ix (values %{$sch->{indexes}}) {
1919 97 $col2ix{$ix->{col}} = $ix;
1920 }
1921 58 for my $c (@$conds) {
1922 58 ▶ my $ix = $col2ix{$c->{col}} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$c->{"col"}} or next 48 10 58
1923 48 my $op = $c->{op};
1924 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
1925 31 my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $c->{val});
1926 31 my $entries = $self->_idx_read_all($table, $ix);
1927 31 my $pos = _idx_bisect($entries, $key_bytes);
1928 31 my @rec_nos;
1929 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
1930 42 push @rec_nos, $entries->[$pos][1];
1931 42 $pos++;
1932 }
1933 31 return [ @rec_nos ];
1934 }
1935 elsif ($op eq '<') {
1936 2 return $self->_idx_range($table, $ix, undef, 0, $c->{val}, 0);
1937 }
1938 elsif ($op eq '<=') {
1939 3 return $self->_idx_range($table, $ix, undef, 0, $c->{val}, 1);
1940 }
1941 elsif ($op eq '>') {
1942 5 return $self->_idx_range($table, $ix, $c->{val}, 0, undef, 0);
1943 }
1944 elsif ($op eq '>=') {
1945 6 return $self->_idx_range($table, $ix, $c->{val}, 1, undef, 0);
1946 }
1947 }
1948 11 return undef;
1949 }
1950  
1951 # _try_index_and_range($table, $sch, $where_expr)
1952 #
1953 # Attempt to satisfy a two-sided range or BETWEEN predicate using an index.
1954 # Recognises these WHERE patterns (same column, values numeric or quoted):
1955 # col OP1 val1 AND col OP2 val2 (e.g. id > 5 AND id < 10)
1956 # col BETWEEN val1 AND val2
1957 # Returns an arrayref of matching record numbers, or undef if no index
1958 # can be applied (caller falls through to a full table scan).
1959 #
1960 367 ▶sub _try_index_and_range {
Subroutine _try_index_and_range: called CC=13 SCAR=25.9
1961 367 my($self, $table, $sch, $where_expr) = @_;
1962 367 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 129 367
1963 129 my %col2ix;
1964 129 for my $ix (values %{$sch->{indexes}}) {
1965 235 $col2ix{$ix->{col}} = $ix;
1966 }
1967 129 my $VAL = qr/(?:'([^']*)'|(-?\d+\.?\d*))/;
1968 129 my $OP = qr/(<=|>=|<|>)/;
1969 # BETWEEN col BETWEEN val1 AND val2
1970 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
1971 6 my($col, $lo_s, $lo_n, $hi_s, $hi_n) = ($1, $2, $3, $4, $5);
1972 6 ▶ my $lo = defined($lo_s) ? $lo_s : $lo_n;
Branch: 1 branch
BranchTrueFalseTotal
defined $lo_s ? : 0 6 6
1973 6 ▶ my $hi = defined($hi_s) ? $hi_s : $hi_n;
Branch: 1 branch
BranchTrueFalseTotal
defined $hi_s ? : 0 6 6
1974 6 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 6 0 6
1975 6 return $self->_idx_range($table, $ix, $lo, 1, $hi, 1);
1976 }
1977 # AND: col OP val AND col OP val (same column)
1978 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
1979 10 my($col, $op1, $v1s, $v1n, $op2, $v2s, $v2n) = ($1, $2, $3, $4, $5, $6, $7);
1980 10 ▶ my $v1 = defined($v1s) ? $v1s : $v1n;
Branch: 1 branch
BranchTrueFalseTotal
defined $v1s ? : 0 10 10
1981 10 ▶ my $v2 = defined($v2s) ? $v2s : $v2n;
Branch: 1 branch
BranchTrueFalseTotal
defined $v2s ? : 0 10 10
1982 10 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 10 0 10
1983 # Determine lo (lower bound) and hi (upper bound)
1984 10 my($lo, $lo_inc, $hi, $hi_inc);
1985 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
1986 9 ($lo, $lo_inc) = ($v1, $op1 eq '>=');
1987 9 ($hi, $hi_inc) = ($v2, $op2 eq '<=');
1988 }
1989 else {
1990 1 ($lo, $lo_inc) = ($v2, $op2 eq '>=');
1991 1 ($hi, $hi_inc) = ($v1, $op1 eq '<=');
1992 }
1993 10 return $self->_idx_range($table, $ix, $lo, $lo_inc, $hi, $hi_inc);
1994 }
1995 113 return undef;
1996 }
1997  
1998 # _try_index_partial_and($table, $sch, $where_expr)
1999 #
2000 # For AND expressions involving multiple columns, pick the single indexed
2001 # column that yields the smallest candidate set and return its record
2002 # numbers. The caller applies the full WHERE predicate as a post-filter,
2003 # so correctness is guaranteed regardless of which index is chosen.
2004 #
2005 # Recognises AND-connected atoms of the form:
2006 # col = val col > val col >= val col < val col <= val
2007 # (quoted or numeric values; no subexpressions, BETWEEN, IN, OR, NOT)
2008 #
2009 # Returns an arrayref of candidate record numbers, or undef when no
2010 # usable index is found (caller falls through to a full table scan).
2011 #
2012 351 ▶sub _try_index_partial_and {
Subroutine _try_index_partial_and: called CC=26 SCAR=35.8
2013 351 my($self, $table, $sch, $where_expr) = @_;
2014 351 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 113 351
2015 # Only handle pure AND expressions (no OR/NOT/BETWEEN/IN/subqueries)
2016 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
2017 25 ▶ return undef if $where_expr =~ /\(\s*SELECT\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $where_expr =~ /\(\s*SELECT\b/i 0 25 25
2018 # Split on AND and collect simple col OP val atoms
2019 25 my @atoms;
2020 25 my $VAL = qr/(?:'[^']*'|-?\d+\.?\d*)/;
2021 25 my $OP = qr/(?:<=|>=|!=|<>|<|>|=)/;
2022 25 for my $part (split /\bAND\b/i, $where_expr) {
2023 39 $part =~ s/^\s+|\s+$//g;
2024 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
2025 || $part =~ /^($VAL)\s*($OP)\s*(\w+)$/) {
2026 # Normalise so col is always on the left
2027 38 my($col, $op, $val);
2028 38 ▶ if ($part =~ /^(\w+)\s*($OP)\s*($VAL)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s*($OP)\s*($VAL)$/) { } 38 0 38
2029 38 ($col, $op, $val) = ($1, uc($2), $3);
2030 }
2031 else {
2032 # val OP col -- reverse the operator
2033 0 $part =~ /^($VAL)\s*($OP)\s*(\w+)$/;
2034 0 my %rev = ('>' => '<', '<' => '>', '>=' => '<=',
2035 '<=' => '>=', '=' => '=', '!=' => '!=',
2036 '<>' => '<>');
2037 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
2038 }
2039 38 $val =~ s/^'|'$//g; # strip surrounding quotes
2040 38 push @atoms, { col => $col, op => $op, val => $val };
2041 }
2042 else {
2043 1 return undef; # complex atom -- cannot use index safely
2044 }
2045 }
2046 24 ▶ return undef unless @atoms >= 2; # single atom handled by Case 1/2
Branch: 1 branch
BranchTrueFalseTotal
unless @atoms >= 2 11 13 24
2047 # Build column -> index map
2048 13 my %col2ix;
2049 13 for my $ix (values %{$sch->{indexes}}) {
2050 26 $col2ix{$ix->{col}} = $ix;
2051 }
2052 # Try each atom in turn; return the first index hit
2053 # (equality index preferred over range for a smaller candidate set)
2054 13 my $best_eq = undef; # record list from an equality match
2055 13 my $best_rng = undef; # record list from a range match
2056 13 for my $a (@atoms) {
2057 17 ▶ my $ix = $col2ix{$a->{col}} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$a->{"col"}} or next 13 4 17
2058 13 my $op = $a->{op};
2059 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
2060 13 my $recs;
2061 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
2062 10 my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $a->{val});
2063 10 my $entries = $self->_idx_read_all($table, $ix);
2064 10 my $pos = _idx_bisect($entries, $key);
2065 10 my @r;
2066 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
2067 34 push @r, $entries->[$pos][1];
2068 34 $pos++;
2069 }
2070 10 $recs = [ @r ];
2071 # Equality index: take first found and stop
2072 10 ▶ $best_eq = $recs and last;
Branch: 1 branch
BranchTrueFalseTotal
$best_eq = $recs and last 10 0 10
2073 }
2074 elsif ($op eq '<') {
2075 0 $recs = $self->_idx_range($table, $ix, undef, 0, $a->{val}, 0);
2076 }
2077 elsif ($op eq '<=') {
2078 0 $recs = $self->_idx_range($table, $ix, undef, 0, $a->{val}, 1);
2079 }
2080 elsif ($op eq '>') {
2081 3 $recs = $self->_idx_range($table, $ix, $a->{val}, 0, undef, 0);
2082 }
2083 elsif ($op eq '>=') {
2084 0 $recs = $self->_idx_range($table, $ix, $a->{val}, 1, undef, 0);
2085 }
2086 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
2087 }
2088 13 ▶ return $best_eq if defined $best_eq;
Branch: 1 branch
BranchTrueFalseTotal
if defined $best_eq 10 3 13
2089 3 return $best_rng;
2090 }
2091  
2092 # _try_index_in($table, $sch, $where_expr)
2093 #
2094 # Attempt to satisfy a col IN (v1, v2, ...) or col NOT IN (v1, v2, ...)
2095 # predicate using an index. For IN, performs one equality lookup per value
2096 # and returns the union of matching record numbers. NOT IN is not optimised
2097 # (returns undef so the caller falls through to a full table scan).
2098 #
2099 # The WHERE expression must consist of exactly one IN predicate with a
2100 # literal value list (no sub-selects, no OR/AND, no NOT IN).
2101 #
2102 # Returns an arrayref of candidate record numbers, or undef when no index
2103 # can be applied.
2104 #
2105 342 ▶sub _try_index_in {
Subroutine _try_index_in: called CC=14 SCAR=26.4
2106 342 my($self, $table, $sch, $where_expr) = @_;
2107 342 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 104 342
2108 # Match: col IN (literal-list) no NOT IN, no sub-select
2109 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
2110 34 my($col, $list_str) = ($1, $2);
2111 # Find index for this column
2112 34 my $ix;
2113 34 for my $candidate (values %{$sch->{indexes}}) {
2114 53 ▶ if ($candidate->{col} eq $col) {
Branch: 1 branch
BranchTrueFalseTotal
if ($candidate->{"col"} eq $col) 33 20 53
2115 33 $ix = $candidate;
2116 33 last;
2117 }
2118 }
2119 34 ▶ return undef unless defined $ix;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ix 1 33 34
2120 # Parse the value list
2121 33 my @vals;
2122 33 my $ls = $list_str;
2123 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
2124 93 my($sv, $nv, $nl) = ($1, $2, $3);
2125 93 ▶ if (defined $nl) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $nl) { } 1 92 93
elsif (defined $sv) { } 11 81 92
2126 # NULL in IN list: no index lookup possible for NULL
2127 1 return undef;
2128 }
2129 elsif (defined $sv) {
2130 11 (my $x = $sv) =~ s/''/'/g;
2131 11 push @vals, $x;
2132 }
2133 else {
2134 81 push @vals, $nv;
2135 }
2136 }
2137 32 ▶ return undef unless @vals; # empty IN list: caller handles
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 0 32 32
2138 # Perform one equality index lookup per value, union the results
2139 32 my %seen;
2140 my @rec_nos;
2141 32 my $entries = $self->_idx_read_all($table, $ix);
2142 32 for my $val (@vals) {
2143 91 my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
2144 91 my $pos = _idx_bisect($entries, $key);
2145 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
2146 110 my $rn = $entries->[$pos][1];
2147 110 ▶ push @rec_nos, $rn unless $seen{$rn}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$rn}++ 108 2 110
2148 110 $pos++;
2149 }
2150 }
2151 32 return [ @rec_nos ];
2152 }
2153  
2154 # _try_index_or($table, $sch, $where_expr)
2155 #
2156 # Attempt to satisfy a pure OR expression using indexes.
2157 #
2158 # Every atom in the OR chain must be a simple condition that can be served
2159 # by an index on the relevant column. If any atom has no usable index the
2160 # function returns undef and the caller falls through to a full table scan.
2161 #
2162 # Recognised atom forms (same column or different columns):
2163 # col = val col != val (not optimised -- returns undef)
2164 # col OP val (OP: <, <=, >, >=)
2165 # col BETWEEN lo AND hi
2166 # col IN (v1, v2, ...)
2167 #
2168 # Returns an arrayref of deduplicated record numbers, or undef.
2169 #
2170 310 ▶sub _try_index_or {
Subroutine _try_index_or: called CC=26 SCAR=35.4
2171 310 my($self, $table, $sch, $where_expr) = @_;
2172 310 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 72 310
2173 # Must be a pure OR expression -- no AND, no NOT, no subqueries
2174 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
2175 45 ▶ return undef if $where_expr =~ /\(\s*SELECT\b/i;
Branch: 1 branch
BranchTrueFalseTotal
if $where_expr =~ /\(\s*SELECT\b/i 0 45 45
2176 # Split on OR
2177 45 my @atoms = DB::Handy::bool_split($where_expr, 'OR');
2178 45 ▶ return undef unless @atoms >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @atoms >= 2 14 31 45
2179 # Build column -> index map
2180 31 my %col2ix;
2181 31 for my $ix (values %{$sch->{indexes}}) {
2182 61 $col2ix{$ix->{col}} = $ix;
2183 }
2184 31 my $VAL = qr/(?:'(?:[^']|'')*'|-?\d+\.?\d*)/;
2185 31 my $OP = qr/(?:<=|>=|<|>|=)/;
2186 # Collect record numbers for each atom
2187 31 my %seen;
2188 my @all_recs;
2189 31 for my $atom (@atoms) {
2190 66 $atom =~ s/^\s+|\s+$//g;
2191 66 my $recs;
2192 # col BETWEEN lo AND hi
2193 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
2194 0 my($col, $lo, $hi) = ($1, $2, $3);
2195 0 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 0 0 0
2196 0 $lo =~ s/^'(.*)'$/$1/s; $hi =~ s/^'(.*)'$/$1/s;
2197 0 $recs = $self->_idx_range($table, $ix, $lo, 1, $hi, 1);
2198 }
2199 # col IN (val, ...)
2200 elsif ($atom =~ /^(\w+)\s+IN\s*\(([^)]*)\)\s*$/i) {
2201 3 my($col, $list) = ($1, $2);
2202 3 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 3 0 3
2203 3 $recs = $self->_try_index_in($table, $sch, $atom);
2204 3 ▶ return undef unless defined $recs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $recs 0 3 3
2205 }
2206 # col OP val (equality or range, not !=/<>)
2207 elsif ($atom =~ /^(\w+)\s*($OP)\s*($VAL)$/) {
2208 63 my($col, $op, $val) = ($1, uc($2), $3);
2209 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
2210 63 ▶ my $ix = $col2ix{$col} or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $ix = $col2ix{$col} or return undef 62 1 63
2211 62 $val =~ s/^'(.*)'$/$1/s;
2212 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
2213 58 my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
2214 58 my $entries = $self->_idx_read_all($table, $ix);
2215 58 my $pos = _idx_bisect($entries, $key);
2216 58 my @r;
2217 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
2218 414 push @r, $entries->[$pos][1];
2219 414 $pos++;
2220 }
2221 58 $recs = [ @r ];
2222 }
2223 0 elsif ($op eq '<') { $recs = $self->_idx_range($table, $ix, undef, 0, $val, 0) }
2224 2 elsif ($op eq '<=') { $recs = $self->_idx_range($table, $ix, undef, 0, $val, 1) }
2225 0 elsif ($op eq '>') { $recs = $self->_idx_range($table, $ix, $val, 0, undef, 0) }
2226 2 elsif ($op eq '>=') { $recs = $self->_idx_range($table, $ix, $val, 1, undef, 0) }
2227 }
2228 else {
2229 0 return undef; # complex atom: cannot use index
2230 }
2231 65 ▶ return undef unless defined $recs;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $recs 0 65 65
2232 65 for my $rn (@$recs) {
2233 431 ▶ push @all_recs, $rn unless $seen{$rn}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$rn}++ 427 4 431
2234 }
2235 }
2236 30 return [ @all_recs ];
2237 }
2238  
2239 # _try_index_not_in($table, $sch, $where_expr)
2240 #
2241 # Attempt to satisfy a col NOT IN (v1, v2, ...) predicate using an index.
2242 # Collects the record numbers that match the IN list (via index), then
2243 # returns all record numbers in the index that are NOT in that set.
2244 # Efficient when the exclusion list is small relative to total row count.
2245 #
2246 # NULL in the value list causes a fallback to a full table scan (SQL
2247 # semantics: NOT IN with NULL never matches any row).
2248 #
2249 # Returns an arrayref of candidate record numbers, or undef when no index
2250 # can be applied.
2251 #
2252 280 ▶sub _try_index_not_in {
Subroutine _try_index_not_in: called CC=16 SCAR=27.7
2253 280 my($self, $table, $sch, $where_expr) = @_;
2254 280 ▶ return undef unless %{$sch->{indexes}};
Branch: 1 branch
BranchTrueFalseTotal
unless %{$sch->{"indexes"};} 238 42 280
2255 # Match: col NOT IN (literal-list) no sub-select
2256 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
2257 23 my($col, $list_str) = ($1, $2);
2258 # Find index for this column
2259 23 my $ix;
2260 23 for my $candidate (values %{$sch->{indexes}}) {
2261 32 ▶ if ($candidate->{col} eq $col) {
Branch: 1 branch
BranchTrueFalseTotal
if ($candidate->{"col"} eq $col) 22 10 32
2262 22 $ix = $candidate;
2263 22 last;
2264 }
2265 }
2266 23 ▶ return undef unless defined $ix;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ix 1 22 23
2267 # Parse the NOT IN value list
2268 22 my @vals;
2269 22 my $ls = $list_str;
2270 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
2271 155 my($sv, $nv, $nl) = ($1, $2, $3);
2272 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
2273 7 elsif (defined $sv) { (my $x = $sv) =~ s/''/'/g; push @vals, $x }
2274 147 else { push @vals, $nv }
2275 }
2276 21 ▶ return undef unless @vals;
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 0 21 21
2277 # Build set of record numbers to EXCLUDE (those matching the IN list)
2278 21 my %exclude;
2279 21 my $entries = $self->_idx_read_all($table, $ix);
2280 21 for my $val (@vals) {
2281 153 my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val);
2282 153 my $pos = _idx_bisect($entries, $key);
2283 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
2284 161 $exclude{$entries->[$pos][1]} = 1;
2285 161 $pos++;
2286 }
2287 }
2288 # Return all record numbers in the index that are NOT excluded
2289 21 my %seen;
2290 my @rec_nos;
2291 21 for my $entry (@$entries) {
2292 357 my $rn = $entry->[1];
2293 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
2294 }
2295 21 return [ @rec_nos ];
2296 }
2297  
2298 ###############################################################################
2299 # JOIN -- Public entry point
2300 ###############################################################################
2301 # join_select(\@join_specs, \@col_specs, \@where_conds, \%opts)
2302 #
2303 # join_specs : arrayref of hashrefs, in left-to-right order
2304 # { table => 'employees', # physical table name
2305 # alias => 'e', # alias (or same as table)
2306 # type => 'INNER'|'LEFT'|'RIGHT'|'CROSS',
2307 # on_left => 'e.dept_id', # undef for first/CROSS
2308 # on_right => 'd.id', # undef for first/CROSS
2309 # }
2310 #
2311 # col_specs : arrayref of 'alias.col' or 'alias.*' or '*'
2312 # undef = all columns (alias-qualified)
2313 #
2314 # where_conds : arrayref of condition hashrefs (from _parse_join_conditions)
2315 # { lhs_alias, lhs_col, op, rhs_alias, rhs_col, val }
2316 #
2317 # opts : { order_by=>'alias.col'|'col', order_dir=>'ASC', limit=>N, offset=>M }
2318 #
2319 73 ▶sub join_select {
Subroutine join_select: called CC=106 SCAR=52.4
Pod undocumented
2320 73 my($self, $join_specs, $col_specs, $where_conds, $opts) = @_;
2321 73 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 73 73
2322 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
2323 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
2324  
2325 # ------------------------------------------------------------------
2326 # Step 1: load schemas; build alias -> { table, schema } map
2327 # ------------------------------------------------------------------
2328 73 my %alias_info; # alias => { table, sch, rows(lazy) }
2329 73 for my $js (@$join_specs) {
2330 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 148 0 148
2331 $alias_info{ $js->{alias} } = {
2332 table => $js->{table},
2333 148 sch => $sch,
2334 };
2335 }
2336  
2337 # ------------------------------------------------------------------
2338 # Step 2: load the leftmost (driving) table fully into memory
2339 # ------------------------------------------------------------------
2340 73 my $first = $join_specs->[0];
2341 73 my @cur_rows = @{ $self->_scan_table_all($first->{table}, $first->{alias}) };
2342 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
2343  
2344 # ------------------------------------------------------------------
2345 # Step 3: for each subsequent table, apply the JOIN
2346 # ------------------------------------------------------------------
2347 73 for my $i (1 .. $#$join_specs) {
2348 75 my $js = $join_specs->[$i];
2349 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
2350  
2351 # Parse ON alias1.col1 = alias2.col2
2352 # A CROSS JOIN is unconditional, so an ON written on one is accepted
2353 # and ignored rather than checked.
2354 75 my($on_l_alias, $on_l_col, $on_r_alias, $on_r_col);
2355 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
2356 73 ($on_l_alias, $on_l_col) = _split_qualified($js->{on_left});
2357 73 ($on_r_alias, $on_r_col) = _split_qualified($js->{on_right});
2358  
2359 # An equality is symmetric, but the code below is not: the left
2360 # operand has to name the accumulated left-hand side and the right
2361 # operand the table being joined in. "ON b.k = a.x" is as valid
2362 # as "ON a.x = b.k", and before 1.09 it produced a silent cross
2363 # join, so the operands are swapped here when they are the other
2364 # way round.
2365 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
2366 && ($on_l_alias eq $js->{alias}) && ($on_r_alias ne $js->{alias})) {
2367 2 ($on_l_alias, $on_l_col, $on_r_alias, $on_r_col) =
2368 ($on_r_alias, $on_r_col, $on_l_alias, $on_l_col);
2369 }
2370  
2371 # Both operands have to be table-qualified. An unqualified name
2372 # cannot be looked up in a result row, whose keys are all
2373 # "alias.col", so before 1.09 "ON x = k" fell through to the
2374 # Cartesian-product branch without a word.
2375 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
2376 2 return $self->_err(
2377 "Unqualified column in the ON clause of JOIN "
2378 . "$js->{table}; write ON <table>.<col> = <table>.<col>");
2379 }
2380  
2381 # A qualified operand has to name a table in this query.
2382 71 for my $qa ($on_l_alias, $on_r_alias) {
2383 142 ▶ next if $alias_info{$qa};
Branch: 1 branch
BranchTrueFalseTotal
if $alias_info{$qa} 141 1 142
2384 1 return $self->_err(
2385 "Unknown table or alias '$qa' in the ON clause of "
2386 . "JOIN $js->{table}");
2387 }
2388 70 ▶ if ($on_r_alias ne $js->{alias}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($on_r_alias ne $js->{"alias"}) 1 69 70
2389 1 return $self->_err(
2390 "The ON clause of JOIN $js->{table} does not reference "
2391 . "'$js->{alias}'; a join condition has to compare a "
2392 . "column of '$js->{alias}' with a column of a table "
2393 . "already joined");
2394 }
2395 }
2396  
2397 # Load the right-side table
2398 71 my @right_rows = @{ $self->_scan_table_all($js->{table}, $js->{alias}) };
2399  
2400 # Build hash on right side if possible (index-nested-loop join)
2401 71 my %right_hash;
2402 71 my $use_hash = 0;
2403 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
2404 69 for my $rr (@right_rows) {
2405 my $rkey = defined($rr->{"$on_r_alias.$on_r_col"})
2406 247 ▶ ? $rr->{"$on_r_alias.$on_r_col"}
Branch: 1 branch
BranchTrueFalseTotal
defined $$rr{"$on_r_alias.$on_r_col"} ? : 247 0 247
2407 : '';
2408 247 push @{ $right_hash{$rkey} }, $rr;
2409 }
2410 69 $use_hash = 1;
2411 }
2412  
2413 71 my @next_rows;
2414  
2415 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
2416  
2417 # Cartesian product
2418 2 for my $lr (@cur_rows) {
2419 5 for my $rr (@right_rows) {
2420 15 push @next_rows, { %$lr, %$rr };
2421 }
2422 }
2423 }
2424 elsif ($join_type eq 'INNER') {
2425 57 for my $lr (@cur_rows) {
2426 my $lkey = defined($lr->{"$on_l_alias.$on_l_col"})
2427 256 ▶ ? $lr->{"$on_l_alias.$on_l_col"}
Branch: 1 branch
BranchTrueFalseTotal
defined $$lr{"$on_l_alias.$on_l_col"} ? : 256 0 256
2428 : '';
2429 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
2430 256 for my $rr (@$matches) {
2431 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
2432 230 push @next_rows, { %$lr, %$rr };
2433 }
2434 }
2435 }
2436 elsif ($join_type eq 'LEFT') {
2437 11 for my $lr (@cur_rows) {
2438 my $lkey = defined($lr->{"$on_l_alias.$on_l_col"})
2439 52 ▶ ? $lr->{"$on_l_alias.$on_l_col"}
Branch: 1 branch
BranchTrueFalseTotal
defined $$lr{"$on_l_alias.$on_l_col"} ? : 52 0 52
2440 : '';
2441 my $matches = $use_hash ? ($right_hash{$lkey} || [])
2442 0 ▶ : [ 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
2443 @right_rows
2444 ];
2445 52 ▶ if (@$matches) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$matches) { } 41 11 52
2446 41 for my $rr (@$matches) {
2447 47 push @next_rows, { %$lr, %$rr };
2448 }
2449 }
2450 else {
2451  
2452 # NULL-fill right side
2453 11 my %null_right = _make_null_row($js->{alias}, $alias_info{$js->{alias}}{sch});
2454 11 push @next_rows, { %$lr, %null_right };
2455 }
2456 }
2457 }
2458 elsif ($join_type eq 'RIGHT') {
2459  
2460 # RIGHT JOIN: swap sides, do LEFT, then results are correct
2461 1 for my $rr (@right_rows) {
2462 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
2463 5 my $l_alias_key = "$on_l_alias.$on_l_col";
2464 5 my @matched_lefts;
2465 5 for my $lr (@cur_rows) {
2466 35 ▶ my $lkey = defined($lr->{$l_alias_key}) ? $lr->{$l_alias_key} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $lr->{$l_alias_key} ? : 35 0 35
2467 35 ▶ push @matched_lefts, $lr if $lkey eq $rkey;
Branch: 1 branch
BranchTrueFalseTotal
if $lkey eq $rkey 6 29 35
2468 }
2469 5 ▶ if (@matched_lefts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@matched_lefts) { } 3 2 5
2470 3 for my $lr (@matched_lefts) {
2471 6 push @next_rows, { %$lr, %$rr };
2472 }
2473 }
2474 else {
2475  
2476 # NULL-fill all left-side aliases seen so far
2477 2 my %null_left;
2478 2 for my $prev_js (@{$join_specs}[0..$i-1]) {
2479 2 my %nr = _make_null_row($prev_js->{alias}, $alias_info{$prev_js->{alias}}{sch});
2480 2 %null_left = (%null_left, %nr);
2481 }
2482 2 push @next_rows, { %null_left, %$rr };
2483 }
2484 }
2485 }
2486  
2487 71 @cur_rows = @next_rows;
2488 }
2489  
2490 # ------------------------------------------------------------------
2491 # Step 4: apply WHERE (post-join filter)
2492 # ------------------------------------------------------------------
2493 69 ▶ if (@$where_conds) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$where_conds) 23 46 69
2494 23 my $wsub = _compile_join_where($where_conds);
2495 23 @cur_rows = grep { $wsub->($_) } @cur_rows;
2496 }
2497  
2498 # ------------------------------------------------------------------
2499 # Step 5: ORDER BY
2500 # ------------------------------------------------------------------
2501 # order_keys holds every ORDER BY key as [ name, ASC|DESC ]; order_by and
2502 # order_dir carry the first key so that older callers keep working.
2503 69 my @ob_keys;
2504 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
2505 28 @ob_keys = @{$opts->{order_keys}};
2506 }
2507 elsif ($opts->{order_by}) {
2508 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
2509 }
2510 69 ▶ if (@ob_keys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ob_keys) 28 41 69
2511  
2512 # A result row is keyed "alias.col", so a bare ORDER BY name has to be
2513 # resolved to the alias that owns it. An unresolvable key used to
2514 # leave the rows in scan order without a word.
2515 28 my(%qual, %bare);
2516 28 for my $js (@$join_specs) {
2517 56 my $a = $js->{alias};
2518 56 for my $c (@{$alias_info{$a}{sch}{cols}}) {
2519 146 $qual{"$a.$c->{name}"} = 1;
2520 $bare{$c->{name}} = "$a.$c->{name}"
2521 146 ▶ unless exists $bare{$c->{name}};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $bare{$c->{"name"}} 141 5 146
2522 }
2523 }
2524 28 for my $k (@ob_keys) {
2525 31 ▶ next if $qual{$k->[0]};
Branch: 1 branch
BranchTrueFalseTotal
if $qual{$k->[0]} 30 1 31
2526 1 ▶ if ($bare{$k->[0]}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bare{$k->[0]}) 0 1 1
2527 0 $k->[0] = $bare{$k->[0]};
2528 0 next;
2529 }
2530 1 return $self->_err(
2531 "Unknown ORDER BY column '$k->[0]' in a JOIN query");
2532 }
2533  
2534 @cur_rows = sort {
2535 27 my $cmp = 0;
2536 133 for my $k (@ob_keys) {
2537 146 my($key, $dir) = @$k;
2538 146 my $va = $a->{$key};
2539 146 my $vb = $b->{$key};
2540 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
2541 defined($vb) && ($vb =~ /^-?\d+\.?\d*$/))
2542 ? ($va <=> $vb)
2543 : ((defined($va) ? $va : '') cmp (defined($vb) ? $vb : ''));
2544 146 ▶ $c = -$c if lc($dir) eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if lc $dir eq "desc" 20 126 146
2545 146 ▶ if ($c != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c != 0) 116 30 146
2546 116 $cmp = $c;
2547 116 last;
2548 }
2549 }
2550 $cmp;
2551 } @cur_rows;
2552 }
2553  
2554 # ------------------------------------------------------------------
2555 # Step 6: expand the select list and check every item
2556 # ------------------------------------------------------------------
2557 68 my @expanded;
2558 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
2559  
2560 # Expand wildcards: 'alias.*' or '*'
2561 58 for my $cs (@$col_specs) {
2562 101 ▶ if ($cs eq '*') {
Branch: 2 branches
BranchTrueFalseTotal
if ($cs eq '*') { } 0 101 101
elsif ($cs =~ /^(\w+)\.\*$/) { } 2 99 101
2563  
2564 # all columns from all aliases
2565 0 for my $js (@$join_specs) {
2566 0 my $a = $js->{alias};
2567 0 my $sch = $alias_info{$a}{sch};
2568 0 for my $c (@{$sch->{cols}}) {
2569 0 push @expanded, "$a.$c->{name}";
2570 }
2571 }
2572 }
2573 elsif ($cs =~ /^(\w+)\.\*$/) {
2574 2 my $a = $1;
2575 2 ▶ my $sch = $alias_info{$a} ? $alias_info{$a}{sch} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$alias_info{$a} ? : 2 0 2
2576 2 ▶ unless ($sch) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sch) 0 2 2
2577 0 return $self->_err("Unknown table or alias '$a' in '$cs'");
2578 }
2579 2 for my $c (@{$sch->{cols}}) {
2580 6 push @expanded, "$a.$c->{name}";
2581 }
2582 }
2583 else {
2584 99 push @expanded, $cs;
2585 }
2586 }
2587  
2588 # Every item has to name a column of one of the joined tables. A
2589 # JOIN select list cannot evaluate an expression or an AS alias, and
2590 # until 1.09 such an item silently produced a row with no values in
2591 # it at all: "SELECT a.y AS nm ... JOIN", "SELECT a.x + 1 ... JOIN"
2592 # and "SELECT DISTINCT a.x ... JOIN" all returned empty rows.
2593 58 my %valid_col;
2594 58 for my $js (@$join_specs) {
2595 118 my $a = $js->{alias};
2596 118 for my $c (@{$alias_info{$a}{sch}{cols}}) {
2597 328 $valid_col{"$a.$c->{name}"} = 1;
2598 328 $valid_col{$c->{name}} = 1;
2599 }
2600 }
2601 58 for my $ck (@expanded) {
2602 105 ▶ next if $valid_col{$ck};
Branch: 1 branch
BranchTrueFalseTotal
if $valid_col{$ck} 102 3 105
2603 3 return $self->_err(
2604 "Unsupported select item '$ck' in a JOIN query; a JOIN "
2605 . "select list accepts column names, '*' and '<table>.*' "
2606 . "only (no expressions and no AS aliases)");
2607 }
2608 }
2609  
2610 # ------------------------------------------------------------------
2611 # Step 7: DISTINCT. Applied before OFFSET/LIMIT, as SQL requires, and
2612 # keyed on the select-list values only.
2613 # ------------------------------------------------------------------
2614 65 ▶ if ($opts->{distinct}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"distinct"}) 4 61 65
2615 0 ▶ my @dkeys = @expanded ? @expanded : sort keys %{ $cur_rows[0] || {} };
Branch: 1 branch
BranchTrueFalseTotal
@expanded ? : 4 0 4
Condition0%0/2
$cur_rows[0] || {}
l!l
00
MC/DC0%0/1
$cur_rows[0] || {}
$cur_rows[0]
Truth table0%0/2
A
A= $cur_rows[0]
Aresult
11
00
2616 4 my(%seen, @uniq);
2617 4 for my $r (@cur_rows) {
2618 my $k = join("\x00", map {
2619 12 ▶ defined($r->{$_}) ? $r->{$_} : "\x01"
Branch: 1 branch
BranchTrueFalseTotal
defined $r->{$_} ? : 15 0 15
2620 } @dkeys);
2621 12 ▶ push @uniq, $r unless $seen{$k}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $seen{$k}++ 7 5 12
2622 }
2623 4 @cur_rows = @uniq;
2624 }
2625  
2626 # ------------------------------------------------------------------
2627 # Step 8: OFFSET / LIMIT
2628 # ------------------------------------------------------------------
2629 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
2630 65 ▶ @cur_rows = splice(@cur_rows, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 1 64 65
2631 65 ▶ if (defined $opts->{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts->{"limit"}) 3 62 65
2632 3 my $last = $opts->{limit} - 1;
2633 3 ▶ $last = $#cur_rows if $last > $#cur_rows;
Branch: 1 branch
BranchTrueFalseTotal
if $last > $#cur_rows 0 3 3
2634 3 @cur_rows = @cur_rows[0..$last];
2635 }
2636  
2637 # ------------------------------------------------------------------
2638 # Step 9: column projection
2639 # ------------------------------------------------------------------
2640 65 ▶ if (@expanded) {
Branch: 1 branch
BranchTrueFalseTotal
if (@expanded) 55 10 65
2641 55 my @proj_rows;
2642 55 for my $r (@cur_rows) {
2643 165 my %p;
2644 165 for my $ck (@expanded) {
2645  
2646 # Try qualified name first, then bare name
2647 312 ▶ if (exists $r->{$ck}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $r->{$ck}) { } 312 0 312
2648 312 $p{$ck} = $r->{$ck};
2649 }
2650 else {
2651  
2652 # bare name: find first matching qualified key
2653 0 for my $k (keys %$r) {
2654 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
2655 0 $p{$ck} = $r->{$k};
2656 0 last;
2657 }
2658 }
2659 }
2660 }
2661 165 push @proj_rows, { %p };
2662 }
2663 55 return [ @proj_rows ];
2664 }
2665  
2666 10 return [ @cur_rows ];
2667 }
2668  
2669 # Load all active rows from a table, qualifying each column as "alias.col"
2670 144 ▶sub _scan_table_all {
Subroutine _scan_table_all: called CC=7 SCAR=19.8
2671 144 my($self, $table, $alias) = @_;
2672 144 ▶ my $sch = $self->_load_schema($table) or return [];
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return [] 144 0 144
2673 144 my $dat = $self->_file($table, 'dat');
2674 144 my $recsize = $sch->{recsize};
2675 144 my @rows;
2676  
2677 144 local *FH;
2678 0 ▶ 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 [] } 144 0 144
2679 144 binmode FH;
2680 144 _lock_sh(\*FH);
2681 144 while (1) {
2682 716 my $raw = '';
2683 716 my $n = read(FH, $raw, $recsize);
2684 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
2685 572 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 572 572
2686 572 my $raw_row = $self->_unpack_record($sch, $raw);
2687  
2688 # Qualify column names with alias
2689 572 my %qrow;
2690 572 for my $col (@{$sch->{cols}}) {
2691 1725 $qrow{"$alias.$col->{name}"} = $raw_row->{$col->{name}};
2692 }
2693 572 push @rows, { %qrow };
2694 }
2695 144 _unlock(\*FH);
2696 144 close FH;
2697 144 return [ @rows ];
2698 }
2699  
2700 # Build a row of NULLs for the given alias (for outer joins)
2701 13 ▶sub _make_null_row {
Subroutine _make_null_row: called CC=2 SCAR=6.9
2702 13 my($alias, $sch) = @_;
2703 13 my %row;
2704 13 for my $col (@{$sch->{cols}}) {
2705 37 $row{"$alias.$col->{name}"} = undef;
2706 }
2707 13 return %row;
2708 }
2709  
2710 # Split "alias.col" into (alias, col); if no dot, return (undef, col)
2711 173 ▶sub _split_qualified {
Subroutine _split_qualified: called CC=2 SCAR=6.9
2712 173 my($qname) = @_;
2713 173 ▶ if ($qname =~ /^(\w+)\.(\w+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($qname =~ /^(\w+)\.(\w+)$/) 170 3 173
2714 170 return ($1, $2);
2715 }
2716 3 return (undef, $qname);
2717 }
2718  
2719 # Check if a pair of rows satisfies the ON equality condition
2720 0 ▶sub _join_row_matches {
Subroutine _join_row_matches: not called CC=9 SCAR=45.0
2721 0 my($lr, $rr, $la, $lc, $ra, $rc) = @_;
2722 0 ▶ my $lv = defined($la) ? $lr->{"$la.$lc"} : $lr->{$lc};
Branch: 1 branch
BranchTrueFalseTotal
defined $la ? : 0 0 0
2723 0 ▶ my $rv = defined($ra) ? $rr->{"$ra.$rc"} : $rr->{$rc};
Branch: 1 branch
BranchTrueFalseTotal
defined $ra ? : 0 0 0
2724 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
2725  
2726 # numeric compare if both look numeric
2727 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
2728 0 ▶ return (($lv == $rv) ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$lv == $rv ? : 0 0 0
2729 }
2730 0 ▶ return (($lv eq $rv) ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
$lv eq $rv ? : 0 0 0
2731 }
2732  
2733 ###############################################################################
2734 # JOIN WHERE compiler
2735 # Conditions from the WHERE clause after a JOIN may reference qualified
2736 # columns (alias.col) or bare column names.
2737 # Condition hashref keys:
2738 # lhs_alias, lhs_col -- left-hand side
2739 # op -- = != <> < > <= >= LIKE
2740 # rhs_alias, rhs_col -- right-hand side (column comparison) OR
2741 # val -- literal value
2742 ###############################################################################
2743 23 ▶sub _compile_join_where {
Subroutine _compile_join_where: called CC=3 SCAR=12.4
2744 23 my($conds) = @_;
2745 0 ▶ 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
2746 115 ▶ return sub {
Subroutine __ANON__: called CC=55 SCAR=53.1
2747 115 my($row) = @_;
2748 115 for my $c (@$conds) {
2749  
2750 # Resolve left-hand value
2751 131 my $lv;
2752 131 ▶ if (defined $c->{lhs_alias}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $c->{'lhs_alias'}) { } 131 0 131
2753 131 $lv = $row->{"$c->{lhs_alias}.$c->{lhs_col}"};
2754 }
2755 else {
2756  
2757 # bare name: search qualified keys
2758 0 for my $k (keys %$row) {
2759 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
2760 0 $lv = $row->{$k};
2761 0 last;
2762 }
2763 }
2764 }
2765 # IS [NOT] NULL is decided before the coercion below, and uses
2766 # the same rule as the single-table engine: a NULL is either an
2767 # undefined value (a NULL-filled outer-join row) or the empty
2768 # string (the on-disk representation).
2769 131 ▶ if ($c->{op} eq 'IS_NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->{"op"} eq "IS_NULL") 4 127 131
2770 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
2771 1 next;
2772 }
2773 127 ▶ if ($c->{op} eq 'IS_NOT_NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->{"op"} eq "IS_NOT_NULL") 4 123 127
2774 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
2775 3 next;
2776 }
2777  
2778 123 ▶ $lv = '' unless defined $lv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv 1 122 123
2779  
2780 # Resolve right-hand value (literal or column)
2781 123 my $rv;
2782 123 ▶ if (defined $c->{rhs_col}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $c->{'rhs_col'}) { } 0 123 123
2783 0 ▶ if (defined $c->{rhs_alias}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $c->{'rhs_alias'}) { } 0 0 0
2784 0 $rv = $row->{"$c->{rhs_alias}.$c->{rhs_col}"};
2785 }
2786 else {
2787 0 for my $k (keys %$row) {
2788 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
2789 0 $rv = $row->{$k};
2790 0 last;
2791 }
2792 }
2793 }
2794 }
2795 else {
2796 123 $rv = $c->{val};
2797 }
2798 123 ▶ $rv = '' unless defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 8 115 123
2799  
2800 123 my $op = $c->{op};
2801  
2802 # IN / NOT IN
2803 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
2804 8 my $lhs_val = $lv;
2805 8 my $found = 0;
2806 8 my $has_null = 0;
2807 8 for my $cv (@{$c->{vals}}) {
2808 0 ▶ unless (defined $cv) { $has_null = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cv) 0 8 8
2809 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
2810 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
2811 4 $found = 1;
2812 4 last;
2813 }
2814 }
2815 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
2816 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
2817 # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN
2818 # when the row value was not found in the non-NULL values.
2819 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
2820 4 next;
2821 }
2822  
2823 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
2824  
2825 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
2826 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
2827 }
2828 ▶ 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
2829 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
2830 }
2831 elsif ($op eq '<') {
2832 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
2833 }
2834 elsif ($op eq '>') {
2835 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
2836 }
2837 elsif ($op eq '<=') {
2838 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
2839 }
2840 elsif ($op eq '>=') {
2841 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
2842 }
2843 elsif ($op eq 'LIKE') {
2844 3 my $p = _like_to_re($rv);
2845 3 ▶ return 0 unless $lv =~ /^$p$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $lv =~ /^$p$/i 1 2 3
2846 }
2847 }
2848 35 return 1;
2849 23 };
2850 }
2851  
2852 ###############################################################################
2853 # JOIN SQL parser
2854 # Handles:
2855 # SELECT col_list
2856 # FROM t1 [AS a1]
2857 # [INNER|LEFT [OUTER]|RIGHT [OUTER]|CROSS] JOIN t2 [AS a2] ON a1.c = a2.c
2858 # [ JOIN t3 [AS a3] ON ... ]
2859 # [WHERE ...]
2860 # [ORDER BY alias.col [ASC|DESC]]
2861 # [LIMIT n] [OFFSET m]
2862 ###############################################################################
2863 # A table alias in a FROM clause is optional, so the token that follows a
2864 # table name has to be checked before it is accepted as one. Without this
2865 # guard "FROM a LEFT JOIN b ON a.id = b.bid" read LEFT as the alias of a,
2866 # which turned the LEFT JOIN into a plain JOIN and left every "a.col"
2867 # reference unresolvable, and "JOIN b ON ..." read ON as the alias of b,
2868 # which dropped the join condition and produced a silent cross join.
2869 89 ▶sub _is_join_keyword {
Subroutine _is_join_keyword: called CC=3 SCAR=11.1
2870 89 my($word) = @_;
2871 89 ▶ return 0 unless defined $word;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $word 0 89 89
2872 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
2873 }
2874  
2875 89 ▶sub _parse_join_sql {
Subroutine _parse_join_sql: called CC=38 SCAR=36.8
2876 89 my($sql) = @_;
2877 # sql has been normalised: single spaces, trimmed
2878  
2879 # ---------------------------------------------------------------
2880 # 1. Extract SELECT column list and the FROM...rest portion
2881 # ---------------------------------------------------------------
2882 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
2883 89 my($sel_str, $from_rest) = ($1, $2);
2884  
2885 # ---------------------------------------------------------------
2886 # 2. Strip trailing ORDER BY / LIMIT / OFFSET
2887 # (strip right-to-left to avoid greedy issues)
2888 # ---------------------------------------------------------------
2889 89 my %opts;
2890  
2891 # Strip suffixes right-to-left: OFFSET, LIMIT, ORDER BY
2892 # (ORDER BY may precede LIMIT/OFFSET, so strip LIMIT+OFFSET first)
2893 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
2894 1 $opts{offset} = $1;
2895 }
2896 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
2897 3 $opts{limit} = $1;
2898 }
2899 # ORDER BY accepts a comma-separated key list. Before 1.09 only a single
2900 # key was matched here, so "ORDER BY a.y, a.x DESC" failed to match, was
2901 # swallowed by the WHERE strip below and then dropped by the condition
2902 # parser -- the rows came back in scan order with no error.
2903 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
2904 31 my $ob_str = $1;
2905 31 my @ob_keys;
2906 31 for my $k (split(/\s*,\s*/, $ob_str)) {
2907 34 $k =~ s/^\s+|\s+$//g;
2908 34 my $dir = 'ASC';
2909 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
2910 34 push @ob_keys, [ $k, $dir ];
2911 }
2912 31 ▶ if (@ob_keys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ob_keys) 31 0 31
2913 31 $opts{order_keys} = [ @ob_keys ];
2914 31 $opts{order_by} = $ob_keys[0][0];
2915 31 $opts{order_dir} = $ob_keys[0][1];
2916 }
2917 }
2918  
2919 # ---------------------------------------------------------------
2920 # 3. Extract WHERE clause (everything after WHERE keyword,
2921 # which must come after all JOIN...ON clauses)
2922 # ---------------------------------------------------------------
2923 89 my $where_str = '';
2924  
2925 # WHERE must appear after the last ON clause; we find the last WHERE
2926 89 ▶ if ($from_rest =~ s/\s+WHERE\s+(.+)$//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($from_rest =~ s/\s+WHERE\s+(.+)$//i) 26 63 89
2927 26 $where_str = $1;
2928 26 $where_str =~ s/^\s+|\s+$//g;
2929 }
2930  
2931 # ---------------------------------------------------------------
2932 # 4. Parse the FROM clause using iterative regex matching
2933 # Grammar: table [AS alias]
2934 # { join_type JOIN table [AS alias] ON qcol = qcol }*
2935 # ---------------------------------------------------------------
2936 89 my @join_specs;
2937  
2938 # Parse the driving (first) table
2939 89 my $fr = $from_rest;
2940 89 $fr =~ s/^\s+//;
2941 89 ▶ unless ($fr =~ s/^(\w+)//) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($fr =~ s/^(\w+)//) 0 89 89
2942 0 return undef;
2943 }
2944 89 my $first_tbl = $1;
2945 89 my $first_alias = $first_tbl;
2946 89 ▶ if ($fr =~ /^\s+(?:AS\s+)?(\w+)/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fr =~ /^\s+(?:AS\s+)?(\w+)/i) 89 0 89
2947 89 my $cand = $1;
2948 89 ▶ unless (_is_join_keyword($cand)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_is_join_keyword($cand)) 33 56 89
2949 33 $fr =~ s/^\s+(?:AS\s+)?\w+//i;
2950 33 $first_alias = $cand;
2951 }
2952 }
2953 89 push @join_specs, { table => $first_tbl, alias => $first_alias, type => 'FIRST' };
2954  
2955 # Iteratively match JOIN clauses.
2956 #
2957 # The join-type words, the table and its alias are matched first; the ON
2958 # expression is then taken as everything up to the start of the next JOIN
2959 # clause (or the end of the FROM text) and checked separately. Until 1.09
2960 # the ON clause was part of this pattern as an *optional* group matching
2961 # only "col = col", so every ON the pattern could not read simply failed
2962 # to participate: on_left and on_right stayed undef and join_select fell
2963 # through to its Cartesian-product branch. "ON a.x = b.k AND a.id < b.id",
2964 # "ON a.x < b.k", "ON b.k = a.x" (operands the other way round), USING,
2965 # NATURAL and FULL OUTER all returned a silent cross join instead of an
2966 # error. Anything not executable is now collected in $err.
2967 89 my $err = '';
2968 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
2969 91 my($type_kw, $tbl, $alias) = ($1, $2, $3);
2970 91 ▶ $type_kw = '' unless defined $type_kw;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type_kw 0 91 91
2971 91 $type_kw =~ s/\s+$//;
2972 91 my $type = 'INNER';
2973 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
2974 5 ▶ $err = "NATURAL JOIN is not supported; name the join columns "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 5 0 5
2975 . "with ON <left>.<col> = <right>.<col>"
2976 unless $err ne '';
2977 }
2978 elsif ($type_kw =~ /FULL/i) {
2979 2 ▶ $err = "FULL OUTER JOIN is not supported; use LEFT JOIN or "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 2 0 2
2980 . "RIGHT JOIN, or combine the two with UNION"
2981 unless $err ne '';
2982 }
2983 elsif ($type_kw =~ /CROSS/i) {
2984 2 $type = 'CROSS';
2985 }
2986 elsif ($type_kw =~ /LEFT/i) {
2987 12 $type = 'LEFT';
2988 }
2989 elsif ($type_kw =~ /RIGHT/i) {
2990 1 $type = 'RIGHT';
2991 }
2992 91 ▶ $alias = $tbl unless defined $alias;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $alias 56 35 91
2993  
2994 # USING (col, ...) -- recognised only so that it can be rejected.
2995 91 ▶ if ($fr =~ s/^\s+USING\s*\(([^)]*)\)//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($fr =~ s/^\s+USING\s*\(([^)]*)\)//i) 1 90 91
2996 1 ▶ $err = "JOIN ... USING is not supported; use "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 1 0 1
2997 . "ON <left>.<col> = <right>.<col>"
2998 unless $err ne '';
2999 }
3000  
3001 # ON <expr>, up to the next JOIN clause or the end of the FROM text.
3002 91 my($on_left, $on_right);
3003 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
3004 82 my $on_expr = $1;
3005 82 $on_expr =~ s/^\s+|\s+$//g;
3006 82 ▶ if ($on_expr =~ /^([\w.]+)\s*=\s*([\w.]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($on_expr =~ /^([\w.]+)\s*=\s*([\w.]+)$/) { } 79 3 82
3007 79 ($on_left, $on_right) = ($1, $2);
3008 }
3009 else {
3010 3 ▶ $err = "Unsupported JOIN condition 'ON $on_expr'; a JOIN "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 3 0 3
3011 . "accepts a single equality between two columns, as in "
3012 . "ON <left>.<col> = <right>.<col>. Move any further "
3013 . "restriction into the WHERE clause"
3014 unless $err ne '';
3015 }
3016 }
3017 elsif ($type ne 'CROSS') {
3018 8 ▶ $err = "JOIN $tbl has no ON clause; add "
Branch: 1 branch
BranchTrueFalseTotal
unless $err ne "" 2 6 8
3019 . "ON <left>.<col> = <right>.<col>, or write CROSS JOIN for "
3020 . "a deliberate Cartesian product"
3021 unless $err ne '';
3022 }
3023  
3024 91 push @join_specs, {
3025 table => $tbl,
3026 alias => $alias,
3027 type => $type,
3028 on_left => $on_left,
3029 on_right => $on_right,
3030 };
3031 }
3032  
3033 # Must have at least 2 tables to be a JOIN. A JOIN that appears only
3034 # inside a subquery lands here too, so this returns undef without an
3035 # error and lets the ordinary SELECT parser take over.
3036 89 ▶ return undef if @join_specs < 2;
Branch: 1 branch
BranchTrueFalseTotal
if @join_specs < 2 0 89 89
3037  
3038 # Text left over in the FROM chain used to be discarded without a word.
3039 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
3040 0 my $left = $fr;
3041 0 $left =~ s/^\s+|\s+$//g;
3042 0 $err = "Unsupported text in FROM clause: '$left'";
3043 }
3044  
3045 89 ▶ return [ undef, undef, undef, undef, $err ] if $err ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $err ne "" 13 76 89
3046  
3047 # ---------------------------------------------------------------
3048 # 5. Parse SELECT column list
3049 # ---------------------------------------------------------------
3050 76 my @col_specs;
3051  
3052 # DISTINCT used to be left glued to the first select item, which made the
3053 # item unresolvable: every row came back empty and nothing was deduplicated.
3054 76 ▶ if ($sel_str =~ s/^\s*DISTINCT\s+//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel_str =~ s/^\s*DISTINCT\s+//i) 4 72 76
3055 4 $opts{distinct} = 1;
3056 }
3057 76 ▶ if ($sel_str =~ /^\s*\*\s*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sel_str =~ /^\s*\*\s*$/) { } 4 72 76
3058 4 @col_specs = (); # empty = all columns (expanded later)
3059 }
3060 else {
3061 72 for my $cs (split /\s*,\s*/, $sel_str) {
3062 122 $cs =~ s/^\s+|\s+$//g;
3063 122 push @col_specs, $cs;
3064 }
3065 }
3066  
3067 # ---------------------------------------------------------------
3068 # 6. Parse WHERE conditions
3069 # ---------------------------------------------------------------
3070 76 my @where_conds;
3071 76 ▶ if ($where_str =~ /\S/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($where_str =~ /\S/) 26 50 76
3072 26 my($wc, $werr) = _parse_join_conditions($where_str);
3073 26 ▶ return [ undef, undef, undef, undef, $werr ] if $werr ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $werr ne "" 3 23 26
3074 23 @where_conds = @$wc;
3075 }
3076  
3077 73 return [ [ @join_specs ], [ @col_specs ], [ @where_conds ], { %opts }, '' ];
3078 }
3079  
3080 # Parse WHERE expression containing possibly qualified column names
3081 # Returns arrayref of condition hashrefs
3082 26 ▶sub _parse_join_conditions {
Subroutine _parse_join_conditions: called CC=24 SCAR=33.1
3083 26 my($expr) = @_;
3084 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
3085 26 my @conds;
3086  
3087 # Split on AND. BETWEEN carries an AND of its own that is not a
3088 # conjunction, so a part that opened a BETWEEN is glued back together
3089 # with the part that follows it.
3090 26 my @raw = split(/\s+AND\s+/i, $expr);
3091 26 my @parts;
3092 26 ▶ while (@raw) {
Branch: 1 branch
BranchTrueFalseTotal
if (@raw) 30 26 56
3093 30 my $p = shift @raw;
3094 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
3095 2 $p .= ' AND ' . shift(@raw);
3096 }
3097 30 push @parts, $p;
3098 }
3099  
3100 26 for my $part (@parts) {
3101 30 $part =~ s/^\s+|\s+$//g;
3102 30 ▶ next unless $part =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
unless $part =~ /\S/ 0 30 30
3103  
3104 # col IS [NOT] NULL. Without this a LEFT JOIN anti-join
3105 # ("WHERE right.col IS NULL") matched no pattern at all and was
3106 # dropped, so every joined row came back unfiltered.
3107 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
3108 2 my($lhs, $neg) = ($1, $2);
3109 2 my($la, $lc) = _split_qualified($lhs);
3110 2 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 1 1 2
3111 lhs_alias => $la,
3112 lhs_col => $lc,
3113 op => ($neg ? 'IS_NOT_NULL' : 'IS_NULL'),
3114 };
3115 2 next;
3116 }
3117  
3118 # col BETWEEN lo AND hi -> col >= lo, col <= hi
3119 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
3120 2 my($lhs, $lo_s, $lo_n, $hi_s, $hi_n) = ($1, $2, $3, $4, $5);
3121 2 my($la, $lc) = _split_qualified($lhs);
3122 2 ▶ my $lo = defined($lo_s) ? $lo_s : $lo_n;
Branch: 1 branch
BranchTrueFalseTotal
defined $lo_s ? : 0 2 2
3123 2 ▶ my $hi = defined($hi_s) ? $hi_s : $hi_n;
Branch: 1 branch
BranchTrueFalseTotal
defined $hi_s ? : 0 2 2
3124 2 push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>'>=', val=>$lo };
3125 2 push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>'<=', val=>$hi };
3126 2 next;
3127 }
3128  
3129 # col-vs-col: alias1.col1 OP alias2.col2
3130 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
3131 14 my($lhs, $op, $rhs) = ($1, uc($2), $3);
3132  
3133 # Heuristic: if rhs looks like a number, treat as literal
3134 14 ▶ if ($rhs =~ /^-?\d+\.?\d*$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rhs =~ /^-?\d+\.?\d*$/) { } 14 0 14
3135 14 my($la, $lc) = _split_qualified($lhs);
3136 14 push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>$op, val=>$rhs };
3137 }
3138 else {
3139 0 my($la, $lc) = _split_qualified($lhs);
3140 0 my($ra, $rc) = _split_qualified($rhs);
3141 0 push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>$op, rhs_alias=>$ra, rhs_col=>$rc };
3142 }
3143 # col [NOT] IN (val, val, ...)
3144 }
3145 elsif ($part =~ /^((?:\w+\.)?\w+)\s+(NOT\s+)?IN\s*\(([^)]*)\)\s*$/i) {
3146 1 my($lhs, $neg, $list_str) = ($1, $2, $3);
3147 1 my($la, $lc) = _split_qualified($lhs);
3148 1 my @vals;
3149 1 my $ls = $list_str;
3150 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
3151 1 my($sv, $nv, $nl) = ($1, $2, $3);
3152 1 ▶ push @vals, defined($nl) ? undef : (defined($sv) ? $sv : $nv);
Branch: 2 branches
BranchTrueFalseTotal
defined $nl ? : 0 1 1
defined $sv ? : 0 1 1
3153 }
3154 1 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 0 1 1
3155 lhs_alias => $la,
3156 lhs_col => $lc,
3157 op => ($neg ? 'NOT_IN' : 'IN'),
3158 vals => [ @vals ],
3159 };
3160 # col-vs-literal
3161 }
3162 elsif ($part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) {
3163 8 my($lhs, $op, $sv, $nv) = ($1, uc($2), $3, $4);
3164 8 my($la, $lc) = _split_qualified($lhs);
3165 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
3166 }
3167 else {
3168  
3169 # Until 1.09 a part that matched none of the patterns above was
3170 # dropped in silence, so "WHERE a.x = 1 OR a.x = 2", "WHERE NOT
3171 # a.x = 1" and "WHERE (a.x = 1)" returned the whole join result
3172 # as though no WHERE had been written at all.
3173 3 return ([], "Unsupported WHERE condition in a JOIN query: "
3174 . "'$part'. A JOIN accepts AND-separated comparisons "
3175 . "between a column and a column or literal, IN, "
3176 . "NOT IN, LIKE, BETWEEN and IS [NOT] NULL; OR, NOT "
3177 . "and parentheses are not supported here");
3178 }
3179 }
3180 23 return ([ @conds ], '');
3181 }
3182  
3183 ###############################################################################
3184 # General helpers
3185 ###############################################################################
3186 116 ▶sub _err {
Subroutine _err: called CC=1 SCAR=0.0
3187 116 my($self, $msg) = @_;
3188 116 $errstr = $msg;
3189 116 return undef;
3190 }
3191  
3192 # Identifier validation.
3193 #
3194 # Database, table and index names are used directly as path components by
3195 # _db_path(), _file() and _idx_file(). Without a check, a caller of the
3196 # low-level API could escape base_dir entirely -- drop_database('../x')
3197 # would hand '../x' to File::Path::rmtree() and delete a directory tree
3198 # outside the database. The SQL layer already restricts every identifier
3199 # to \w+, so this only holds the documented Perl-level methods to the
3200 # same rule; no name that SQL can produce is rejected here.
3201 3548 ▶sub _valid_name {
Subroutine _valid_name: called CC=4 SCAR=13.9
3202 3548 my($name) = @_;
3203 3548 ▶ return 0 unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 0 3548 3548
3204 3548 ▶ return 0 unless $name =~ /^\w+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /^\w+\z/ 61 3487 3548
3205 3487 ▶ return 0 if $DEVICE_NAME{lc($name)};
Branch: 1 branch
BranchTrueFalseTotal
if $DEVICE_NAME{lc $name} 12 3475 3487
3206 3475 return 1;
3207 }
3208  
3209 # Render a name for an error message without interpolating undef.
3210 73 ▶sub _shown_name {
Subroutine _shown_name: called CC=2 SCAR=7.2
3211 73 my($name) = @_;
3212 73 ▶ return defined($name) ? $name : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 73 0 73
3213 }
3214  
3215 113 ▶sub _db_path {
Subroutine _db_path: called CC=1 SCAR=0.0
3216 113 my($self, $db) = @_;
3217 113 File::Spec->catdir($self->{base_dir}, $db);
3218 }
3219  
3220 3425 ▶sub _file {
Subroutine _file: called CC=1 SCAR=0.0
3221 3425 my($self, $table, $ext) = @_;
3222 3425 File::Spec->catfile($self->{base_dir}, $self->{db_name}, "$table.$ext");
3223 }
3224  
3225 3158 ▶sub _load_schema {
Subroutine _load_schema: called CC=16 SCAR=28.3
3226 3158 my($self, $table) = @_;
3227 3158 ▶ unless (_valid_name($table)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_valid_name($table)) 5 3153 3158
3228 5 my $bad = _shown_name($table);
3229 5 $errstr = "Invalid table name '$bad'";
3230 5 return undef;
3231 }
3232 3153 ▶ return $self->{_tables}{$table} if $self->{_tables}{$table};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_tables"}{$table} 2967 186 3153
3233 186 my $sch_file = $self->_file($table, 'sch');
3234 186 ▶ unless (-f $sch_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $sch_file) 9 177 186
3235 9 $errstr = "Table '$table' does not exist";
3236 9 return undef;
3237 }
3238 177 local *FH;
3239 0 ▶ 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 } 177 0 177
3240 177 my($sch, @cols, %indexes);
3241 177 $sch = {};
3242 177 $sch->{notnull} = {};
3243 177 $sch->{defaults} = {};
3244 177 $sch->{checks} = {};
3245 177 $sch->{pk} = undef;
3246 177 local $_;
3247 177 ▶ while (<FH>) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline FH)) 776 177 953
3248 776 chomp;
3249 776 ▶ if (/^RECSIZE=(\d+)/) {
Branch: 7 branches
BranchTrueFalseTotal
if (/^RECSIZE=(\d+)/) { } 177 599 776
elsif (/^COL=(\w+):(\w+):(\d+)(?::(\d+))?/) { } 407 192 599
elsif (/^NOTNULL=(\w+)/) { } 1 191 192
elsif (/^DEFAULT=(\w+):(.+)/) { } 0 191 191
elsif (/^CHECK=(\w+):(.+)/) { } 1 190 191
elsif (/^PK=(\w+)/) { } 0 190 190
elsif (/^IDX=(\w+):(\w+):([01])/) { } 13 177 190
3250 177 $sch->{recsize} = $1;
3251 }
3252 elsif (/^COL=(\w+):(\w+):(\d+)(?::(\d+))?/) {
3253 # 4th field is decl (declared size); absent in old schema files
3254 407 ▶ push @cols, { name=>$1, type=>$2, size=>$3,
Branch: 1 branch
BranchTrueFalseTotal
defined $4 ? : 407 0 407
3255 decl=>(defined($4) ? $4+0 : $3+0) };
3256 }
3257 elsif (/^NOTNULL=(\w+)/) {
3258 1 $sch->{notnull}{$1} = 1;
3259 }
3260 elsif (/^DEFAULT=(\w+):(.+)/) {
3261 0 $sch->{defaults}{$1} = $2;
3262 }
3263 elsif (/^CHECK=(\w+):(.+)/) {
3264 1 $sch->{checks}{$1} = $2;
3265 }
3266 elsif (/^PK=(\w+)/) {
3267 0 $sch->{pk} = $1;
3268 0 $sch->{notnull}{$1} = 1;
3269 }
3270 elsif (/^IDX=(\w+):(\w+):([01])/) {
3271 13 my($iname, $icol, $iuniq) = ($1, $2, $3);
3272 13 my($cdef) = grep { $_->{name} eq $icol } @cols;
3273 $indexes{$iname} = {
3274 name => $iname,
3275 col => $icol,
3276 unique => $iuniq+0,
3277 keysize => ($cdef ? $cdef->{size} : 0),
3278 13 ▶ coltype => ($cdef ? $cdef->{type} : 'VARCHAR'),
Branch: 2 branches
BranchTrueFalseTotal
$cdef ? : 13 0 13
$cdef ? : 13 0 13
3279 };
3280 }
3281 }
3282 177 close FH;
3283 177 $sch->{cols} = [ @cols ];
3284 177 $sch->{indexes} = { %indexes };
3285 177 $self->{_tables}{$table} = $sch;
3286 177 return $sch;
3287 }
3288  
3289 21 ▶sub _rewrite_schema {
Subroutine _rewrite_schema: called CC=23 SCAR=41.0
3290 21 my($self, $table, $sch) = @_;
3291 21 my $sch_file = $self->_file($table, 'sch');
3292 21 local *FH;
3293 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: $!") 21 0 21
3294 21 my $ok = print FH "VERSION=1\n";
3295 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
3296 21 for my $c (@{$sch->{cols}}) {
3297 $ok &&= print FH "COL=$c->{name}:$c->{type}:$c->{size}:"
3298 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
3299 }
3300 21 for my $ix (values %{$sch->{indexes}}) {
3301 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
3302 }
3303 21 ▶ for my $c (sort keys %{$sch->{notnull} || {}}) {
Condition50%1/2
$sch->{'notnull'} || {}
l!l
210
MC/DC0%0/1
$sch->{'notnull'} || {}
$sch->{'notnull'}
Truth table50%1/2
A
A= $sch->{'notnull'}
Aresult
11
00
3304 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
3305 }
3306 21 ▶ for my $c (sort keys %{$sch->{defaults} || {}}) {
Condition50%1/2
$sch->{'defaults'} || {}
l!l
210
MC/DC0%0/1
$sch->{'defaults'} || {}
$sch->{'defaults'}
Truth table50%1/2
A
A= $sch->{'defaults'}
Aresult
11
00
3307 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
3308 }
3309 21 ▶ for my $c (sort keys %{$sch->{checks} || {}}) {
Condition50%1/2
$sch->{'checks'} || {}
l!l
210
MC/DC0%0/1
$sch->{'checks'} || {}
$sch->{'checks'}
Truth table50%1/2
A
A= $sch->{'checks'}
Aresult
11
00
3310 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
3311 }
3312 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
3313 21 my $err = $!;
3314 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
3315 0 ▶ $err = $! if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
3316 0 ▶ close FH if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
3317 0 return $self->_err("Cannot rewrite schema: $err");
3318 }
3319 21 return 1;
3320 }
3321  
3322 # Does $v look like a number that Perl can use in arithmetic without
3323 # complaining under -w? Leading and trailing whitespace is allowed, an
3324 # optional sign, a decimal part and an exponent; everything else -- the
3325 # empty string, 'abc', '12abc', '0x10', 'Inf', 'NaN' -- is not numeric.
3326 #
3327 # The same test used to be written out three times (index key encoding,
3328 # type validation and record packing) and the FLOAT paths had no test at
3329 # all, which is how "isn't numeric" warnings escaped from inside this
3330 # module. Keep it in one place so the three callers cannot drift apart.
3331 6551 ▶sub _looks_numeric {
Subroutine _looks_numeric: called CC=3 SCAR=11.1
3332 6551 my($v) = @_;
3333 6551 ▶ return 0 unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 6551 6551
3334 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
3335 }
3336  
3337 # Is $v a well-formed calendar date in YYYY-MM-DD form?
3338 20 ▶sub _valid_date {
Subroutine _valid_date: called CC=10 SCAR=23.0
3339 20 my($v) = @_;
3340 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
3341 18 my($y, $m, $d) = ($1, $2, $3);
3342 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
3343 15 ▶ return 0 if $d < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $d < 1 0 15 15
3344 15 my @mdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
3345 15 my $max = $mdays[$m-1];
3346 15 ▶ if ($m == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($m == 2) 6 9 15
3347 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
3348 }
3349 15 ▶ return 0 if $d > $max;
Branch: 1 branch
BranchTrueFalseTotal
if $d > $max 4 11 15
3350 11 return 1;
3351 }
3352  
3353 # Return an error message when $v cannot be stored in column $col, or undef
3354 # when it can. NULL (undef or the empty string) is always storable.
3355 3482 ▶sub _type_error {
Subroutine _type_error: called CC=9 SCAR=22.0
3356 3482 my($col, $v) = @_;
3357 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
3358 3432 my $cn = $col->{name};
3359 3432 ▶ if ($col->{type} eq 'INT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($col->{"type"} eq "INT") 2261 1171 3432
3360 # A value that is not numeric at all keeps its historical
3361 # behaviour and is stored as 0. Only a numeric value too large
3362 # for the 4-byte field is rejected, because that used to be
3363 # silently clamped to the nearest limit.
3364 2261 ▶ return undef unless _looks_numeric($v);
Branch: 1 branch
BranchTrueFalseTotal
unless _looks_numeric($v) 2 2259 2261
3365 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
3366 4 return "Integer out of range for column '$cn': '$v' "
3367 . '(INT holds ' . INT_MIN . ' .. ' . INT_MAX . ')';
3368 }
3369 1171 ▶ if ($col->{type} eq 'DATE') {
Branch: 1 branch
BranchTrueFalseTotal
if ($col->{"type"} eq "DATE") 20 1151 1171
3370 20 ▶ return undef if _valid_date($v);
Branch: 1 branch
BranchTrueFalseTotal
if _valid_date($v) 11 9 20
3371 9 return "Invalid DATE for column '$cn': '$v' (expected YYYY-MM-DD)";
3372 }
3373 1151 return undef;
3374 }
3375  
3376 2014 ▶sub _pack_record {
Subroutine _pack_record: called CC=9 SCAR=22.0
3377 2014 my($self, $sch, $row) = @_;
3378 2014 my $data = RECORD_ACTIVE;
3379 2014 for my $col (@{$sch->{cols}}) {
3380 3523 ▶ my $v = defined($row->{$col->{name}}) ? $row->{$col->{name}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$col->{'name'}} ? : 3484 39 3523
3381 3523 my $t = $col->{type};
3382 3523 my $s = $col->{size};
3383 3523 ▶ if ($t eq 'INT') {
Branch: 2 branches
BranchTrueFalseTotal
if ($t eq 'INT') { } 2300 1223 3523
elsif ($t eq 'FLOAT') { } 125 1098 1223
3384 # A value that is not numeric is stored as 0. It is tested
3385 # here rather than left to int() so that -w stays quiet.
3386 2300 ▶ my $iv = _looks_numeric($v) ? int($v) : 0;
Branch: 1 branch
BranchTrueFalseTotal
_looks_numeric($v) ? : 2288 12 2300
3387 2300 ▶ $iv = INT_MAX if $iv > INT_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if $iv > 2147483647 0 2300 2300
3388 2300 ▶ $iv = INT_MIN if $iv < INT_MIN;
Branch: 1 branch
BranchTrueFalseTotal
if $iv < '-2147483648' 0 2300 2300
3389 2300 $data .= pack('N', $iv&0xFFFFFFFF);
3390 }
3391 elsif ($t eq 'FLOAT') {
3392 # Same rule as INT, and for the same reason: a value that is
3393 # not numeric is stored as 0 without a warning. Up to 1.08
3394 # this branch handed the raw value to pack() and any string
3395 # that was not a number leaked an "isn't numeric" warning out
3396 # of the module, whatever the caller's warning settings were.
3397 125 ▶ $data .= pack('d', _looks_numeric($v) ? $v+0 : 0);
Branch: 1 branch
BranchTrueFalseTotal
_looks_numeric($v) ? : 110 15 125
3398 }
3399 else {
3400 1098 my $sv = substr($v, 0, $s);
3401 1098 $sv .= "\x00" x ($s-length($sv));
3402 1098 $data .= $sv;
3403 }
3404 }
3405 2014 return $data;
3406 }
3407  
3408 4074 ▶sub _unpack_record {
Subroutine _unpack_record: called CC=5 SCAR=16.1
3409 4074 my($self, $sch, $raw) = @_;
3410 4074 my %row;
3411 4074 my $offset = 1;
3412 4074 for my $col (@{$sch->{cols}}) {
3413 12102 my $t = $col->{type};
3414 12102 my $s = $col->{size};
3415 12102 my $chunk = substr($raw, $offset, $s);
3416 12102 ▶ if ($t eq 'INT') {
Branch: 2 branches
BranchTrueFalseTotal
if ($t eq 'INT') { } 7128 4974 12102
elsif ($t eq 'FLOAT') { } 391 4583 4974
3417 7128 my $uv = unpack('N', $chunk);
3418 7128 ▶ $uv -= 4294967296 if $uv > 2147483647;
Branch: 1 branch
BranchTrueFalseTotal
if $uv > 2147483647 14 7114 7128
3419 7128 $row{$col->{name}} = $uv;
3420 }
3421 elsif ($t eq 'FLOAT') {
3422 391 $row{$col->{name}} = unpack('d', $chunk);
3423 }
3424 else {
3425 4583 (my $sv = $chunk) =~ s/\x00+$//;
3426 4583 $row{$col->{name}} = $sv;
3427 }
3428 12102 $offset += $s;
3429 }
3430 4074 return { %row };
3431 }
3432  
3433 4052 ▶sub _lock_ex { flock($_[0], LOCK_EX) }
Subroutine _lock_ex: called CC=1 SCAR=0.0
3434 3025 ▶sub _lock_sh { flock($_[0], LOCK_SH) }
Subroutine _lock_sh: called CC=1 SCAR=0.0
3435 7077 ▶sub _unlock { flock($_[0], LOCK_UN) }
Subroutine _unlock: called CC=1 SCAR=0.0
3436  
3437 # Put a write handle into autoflush mode.
3438 #
3439 # print() buffers, and the buffer is written out by close(), which runs
3440 # after _unlock(). Without this the data would reach the file only after
3441 # the exclusive lock had already been handed to another process. With
3442 # autoflush on, every print() reaches the file while the lock is still
3443 # held. IO::Handle->autoflush is avoided on purpose: the select() idiom
3444 # needs no module and works on every Perl from 5.005_03 onwards.
3445 4049 ▶sub _autoflush {
Subroutine _autoflush: called CC=1 SCAR=0.0
3446 4049 my $old = select($_[0]);
3447 4049 $| = 1;
3448 4049 select($old);
3449 }
3450  
3451 12 ▶sub _to_where_sub {
Subroutine _to_where_sub: called CC=4 SCAR=18.9
3452 12 my($wi) = @_;
3453 12 ▶ return undef unless defined $wi;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $wi 0 12 12
3454 12 ▶ return $wi if ref($wi) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $wi eq "CODE" 12 0 12
3455 0 ▶ return _compile_where_from_conds($wi) if ref($wi) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $wi eq "ARRAY" 0 0 0
3456 0 return undef;
3457 }
3458  
3459 157 ▶sub _split_col_defs {
Subroutine _split_col_defs: called CC=7 SCAR=19.5
3460 157 my($str) = @_;
3461 157 my @parts;
3462 157 my $cur = '';
3463 157 my $depth = 0;
3464 157 for my $ch (split //, $str) {
3465 4370 ▶ if ($ch eq '(') {
Branch: 3 branches
BranchTrueFalseTotal
if ($ch eq '(') { } 137 4233 4370
elsif ($ch eq ')') { } 137 4096 4233
elsif ($ch eq ',' and $depth == 0) { } 197 3899 4096
3466 137 $depth++;
3467 137 $cur .= $ch;
3468 }
3469 elsif ($ch eq ')') {
3470 137 $depth--;
3471 137 $cur .= $ch;
3472 }
3473 ▶ elsif (($ch eq ',') && ($depth == 0)) {
Condition66%2/3
$ch eq "," and $depth == 0
!ll&&!rl&&r
38990197
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
3474 197 push @parts, $cur;
3475 197 $cur = '';
3476 }
3477 else {
3478 3899 $cur .= $ch;
3479 }
3480 }
3481 157 ▶ push @parts, $cur if $cur =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $cur =~ /\S/ 157 0 157
3482 157 return @parts;
3483 }
3484  
3485 1981 ▶sub _parse_values {
Subroutine _parse_values: called CC=6 SCAR=18.0
3486 1981 my($str) = @_;
3487 1981 my @vals;
3488 1981 ▶ while (length $str) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $str) 3385 1981 5366
3489 3385 $str =~ s/^\s+//;
3490 3385 ▶ last unless length $str;
Branch: 1 branch
BranchTrueFalseTotal
unless length $str 0 3385 3385
3491 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
3492 1055 my $s = $1;
3493 1055 $s =~ s/''/'/g;
3494 1055 push @vals, $s;
3495 }
3496 elsif ($str =~ s/^(NULL)(?:\s*,\s*|\s*$)//i) {
3497 7 push @vals, undef;
3498 }
3499 elsif ($str =~ s/^(-?\d+\.?\d*)(?:\s*,\s*|\s*$)//) {
3500 2323 push @vals, $1;
3501 }
3502 else {
3503 0 last;
3504 }
3505 }
3506 1981 return @vals;
3507 }
3508  
3509 0 ▶sub _parse_conditions {
Subroutine _parse_conditions: not called CC=18 SCAR=58.3
3510 0 my($expr) = @_;
3511 0 my @conds;
3512  
3513 # Use paren-aware AND splitter
3514 0 my @parts = _split_and_clauses($expr);
3515 0 for my $part (@parts) {
3516 0 $part =~ s/^\s+|\s+$//g;
3517  
3518 # col [NOT] IN (val, val, ...) -- expanded from subquery or literal list
3519 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
3520 0 my($col, $neg, $list_str) = ($1, $2, $3);
3521 0 my @vals;
3522  
3523 # parse list: numbers or quoted strings or NULL
3524 0 my $ls = $list_str;
3525 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
3526 0 my($sv, $nv, $nl) = ($1, $2, $3);
3527 0 ▶ push @vals, defined($nl) ? undef : (defined($sv) ? $sv : $nv);
Branch: 2 branches
BranchTrueFalseTotal
defined $nl ? : 0 0 0
defined $sv ? : 0 0 0
3528 }
3529 0 ▶ push @conds, {
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 0 0 0
3530 col => $col,
3531 op => $neg ? 'NOT_IN' : 'IN',
3532 vals => [ @vals ],
3533 };
3534 0 next;
3535 }
3536  
3537 # EXISTS (1) or EXISTS (0) -- already evaluated by subquery expander
3538 0 ▶ if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) 0 0 0
3539 0 my($neg, $val) = ($1, $2);
3540 0 ▶ my $truth = $val ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$val ? : 0 0 0
3541 0 ▶ $truth = 1 - $truth if $neg;
Branch: 1 branch
BranchTrueFalseTotal
if $neg 0 0 0
3542 0 push @conds, { op => 'CONST', val => $truth };
3543 0 next;
3544 }
3545  
3546 # EXISTS (1) or NOT EXISTS (0) without outer parens (legacy)
3547 0 ▶ if ($part =~ /^(NOT\s+)?EXISTS\s+(\d+)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(NOT\s+)?EXISTS\s+(\d+)$/i) 0 0 0
3548 0 my($neg, $val) = ($1, $2);
3549 0 ▶ my $truth = $val ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$val ? : 0 0 0
3550 0 ▶ $truth = 1 - $truth if $neg;
Branch: 1 branch
BranchTrueFalseTotal
if $neg 0 0 0
3551 0 push @conds, { op => 'CONST', val => $truth };
3552 0 next;
3553 }
3554  
3555 # col OP NULL -- SQL NULL semantics: comparison with NULL is always false
3556 0 ▶ if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*NULL$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*NULL$/i) 0 0 0
3557 0 push @conds, { op => 'CONST', val => 0 };
3558 0 next;
3559 }
3560  
3561 # IS [NOT] NULL
3562 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
3563 0 my($col, $neg) = ($1, $2);
3564 0 ▶ push @conds, { col=>$col, op=>$neg ? 'IS_NOT_NULL' : 'IS_NULL' };
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 0 0 0
3565 0 next;
3566 }
3567  
3568 # Normal col OP literal
3569 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
3570 0 my($col, $op, $sv, $nv) = ($1, $2, $3, $4);
3571 0 ▶ push @conds, { col=>$col, op=>uc($op), val=>(defined($sv) ? $sv : $nv) };
Branch: 1 branch
BranchTrueFalseTotal
defined $sv ? : 0 0 0
3572 }
3573 }
3574 0 return [ @conds ];
3575 }
3576  
3577 6 ▶sub _compile_where_from_conds {
Subroutine _compile_where_from_conds: called CC=3 SCAR=19.1
3578 6 my($conds) = @_;
3579 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
3580 8 ▶ return sub {
Subroutine __ANON__: called CC=49 SCAR=70.9
3581 8 my($row) = @_;
3582 8 for my $c (@$conds) {
3583 8 my $op = $c->{op};
3584  
3585 # Constant (pre-evaluated EXISTS/NOT EXISTS)
3586 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
3587 0 ▶ return 0 unless $c->{val};
Branch: 1 branch
BranchTrueFalseTotal
unless $c->{"val"} 0 0 0
3588 # IN / NOT IN with value list
3589 }
3590 ▶ 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
3591 0 ▶ my $rv = defined($row->{$c->{col}}) ? $row->{$c->{col}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$c->{'col'}} ? : 0 0 0
3592 0 my $found = 0;
3593 0 my $has_null = 0;
3594 0 for my $cv (@{$c->{vals}}) {
3595 0 ▶ unless (defined $cv) { $has_null = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cv) 0 0 0
3596 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
3597 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
3598 0 $found = 1;
3599 0 last;
3600 }
3601 }
3602 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
3603 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
3604 # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN
3605 # when the row value was not found in the non-NULL values.
3606 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
3607 # IS NULL / IS NOT NULL
3608 }
3609 elsif ($op eq 'IS_NULL') {
3610 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
3611 }
3612 elsif ($op eq 'IS_NOT_NULL') {
3613 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
3614 # Standard comparison
3615 }
3616 else {
3617 8 ▶ my $rv = defined($row->{$c->{col}}) ? $row->{$c->{col}} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $$row{$c->{'col'}} ? : 8 0 8
3618 8 my $cv = $c->{val};
3619 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
3620 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
3621 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
3622 }
3623 ▶ 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
3624 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
3625 }
3626 elsif ($op eq '<') {
3627 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
3628 }
3629 elsif ($op eq '>') {
3630 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
3631 }
3632 elsif ($op eq '<=') {
3633 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
3634 }
3635 elsif ($op eq '>=') {
3636 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
3637 }
3638 elsif ($op eq 'LIKE') {
3639 0 my $p = _like_to_re($cv);
3640 0 ▶ return 0 unless $rv =~ /^$p$/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $rv =~ /^$p$/i 0 0 0
3641 }
3642 }
3643 }
3644 6 return 1;
3645 2 };
3646 }
3647  
3648 ###############################################################################
3649 # SQL-92 Engine
3650 ###############################################################################
3651  
3652 # =============================================================================
3653 # Expression evaluator eval_expr($expr, \%row) -> scalar
3654 # =============================================================================
3655 5753 ▶sub eval_expr {
Subroutine eval_expr: called CC=76 SCAR=60.9
Pod undocumented
3656 5753 my($expr, $row) = @_;
3657 5753 ▶ return undef unless defined $expr;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expr 0 5753 5753
3658 5753 $expr =~ s/^\s+|\s+$//g;
3659 5753 ▶ return undef unless length($expr);
Branch: 1 branch
BranchTrueFalseTotal
unless length $expr 0 5753 5753
3660 5753 ▶ return undef if $expr =~ /^NULL$/i;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^NULL$/i 0 5753 5753
3661 5753 ▶ return $expr + 0 if $expr =~ /^-?\d+\.?\d*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^-?\d+\.?\d*$/ 117 5636 5753
3662 5636 ▶ if ($expr =~ /^'((?:[^']|'')*)'$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^'((?:[^']|'')*)'$/) 30 5606 5636
3663 30 (my $s = $1) =~ s/''/'/g;
3664 30 return $s;
3665 }
3666 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
3667 0 return eval_expr($1, $row);
3668 }
3669 5606 ▶ if ($expr =~ /^CASE\b(.*)\bEND$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^CASE\b(.*)\bEND$/is) 9 5597 5606
3670 9 return eval_case($1, $row);
3671 }
3672 5597 ▶ if ($expr =~ /^COALESCE\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^COALESCE\s*\((.+)\)$/is) 4 5593 5597
3673 4 for my $a (args($1)) {
3674 6 my $v = eval_expr($a, $row);
3675 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
3676 }
3677 0 return undef;
3678 }
3679 5593 ▶ if ($expr =~ /^NULLIF\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^NULLIF\s*\((.+)\)$/is) 2 5591 5593
3680 2 my @a = args($1);
3681 2 ▶ return undef unless @a == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @a == 2 0 2 2
3682 2 my($va, $vb) = (eval_expr($a[0], $row), eval_expr($a[1], $row));
3683 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
3684 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
3685 }
3686 1 return $va;
3687 }
3688 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
3689 2 my($ie, $t) = ($1, uc($2));
3690 2 my $v = eval_expr($ie, $row);
3691 2 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 2 2
3692 2 ▶ return int($v) if $t =~ /^INT/i;
Branch: 1 branch
BranchTrueFalseTotal
if $t =~ /^INT/i 1 1 2
3693 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
3694 1 return "$v";
3695 }
3696 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
3697 9 my($fn, $arg) = (uc($1), $2);
3698 9 my $v = eval_expr($arg, $row);
3699 9 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 9 9
3700 9 ▶ return uc($v) if $fn eq 'UPPER';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "UPPER" 2 7 9
3701 7 ▶ return lc($v) if $fn eq 'LOWER';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "LOWER" 3 4 7
3702 4 ▶ return length($v) if $fn eq 'LENGTH';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "LENGTH" 2 2 4
3703 2 ▶ return abs($v + 0) if $fn eq 'ABS';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "ABS" 0 2 2
3704 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
3705 2 ▶ if ($fn eq 'TRIM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "TRIM") 2 0 2
3706 2 (my $s = $v) =~ s/^\s+|\s+$//g;
3707 2 return $s;
3708 }
3709 0 ▶ if ($fn eq 'LTRIM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "LTRIM") 0 0 0
3710 0 (my $s = $v) =~ s/^\s+//;
3711 0 return $s;
3712 }
3713 0 ▶ if ($fn eq 'RTRIM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "RTRIM") 0 0 0
3714 0 (my $s = $v) =~ s/\s+$//;
3715 0 return $s;
3716 }
3717 }
3718 5580 ▶ if ($expr =~ /^ROUND\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^ROUND\s*\((.+)\)$/is) 0 5580 5580
3719 0 my @a = args($1);
3720 0 my $v = eval_expr($a[0], $row);
3721 0 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
3722 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
3723 0 return sprintf("%.${d}f", $v+0) + 0;
3724 }
3725 5580 ▶ if ($expr =~ /^(FLOOR|CEIL(?:ING)?)\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(FLOOR|CEIL(?:ING)?)\s*\((.+)\)$/is) 0 5580 5580
3726 0 my($fn, $arg) = (uc($1), $2);
3727 0 my $v = eval_expr($arg, $row);
3728 0 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
3729 0 ▶ return $fn eq 'FLOOR' ? POSIX::floor($v+0) : POSIX::ceil($v+0);
Branch: 1 branch
BranchTrueFalseTotal
$fn eq 'FLOOR' ? : 0 0 0
3730 }
3731 5580 ▶ if ($expr =~ /^MOD\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^MOD\s*\((.+)\)$/is) 0 5580 5580
3732 0 my @a = args($1);
3733 0 ▶ return undef unless @a == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @a == 2 0 0 0
3734 0 my($a, $b) = (eval_expr($a[0], $row)+0, eval_expr($a[1], $row)+0);
3735 0 ▶ return undef if $b == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $b == 0 0 0 0
3736 0 return $a % $b;
3737 }
3738 5580 ▶ if ($expr =~ /^(?:SUBSTR|SUBSTRING)\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(?:SUBSTR|SUBSTRING)\s*\((.+)\)$/is) 1 5579 5580
3739 1 my $inner = $1;
3740 1 my($se, $ste, $le);
3741 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
3742 0 ($se, $ste, $le) = ($1, $2, $3);
3743 }
3744 else {
3745 1 ($se, $ste, $le) = args($inner);
3746 }
3747 1 my $s = eval_expr($se, $row);
3748 1 ▶ return undef unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 0 1 1
3749 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
3750 1 ▶ $st = 1 if $st < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $st < 1 0 1 1
3751 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
3752 ? substr($s, $st-1, int(eval_expr($le, $row) || 0))
3753 : substr($s, $st-1);
3754 }
3755 5579 ▶ if ($expr =~ /^CONCAT\s*\((.+)\)$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^CONCAT\s*\((.+)\)$/is) 0 5579 5579
3756 0 my @args = args($1);
3757 0 my $r = '';
3758 0 for (@args) {
3759 0 my $v = eval_expr($_, $row);
3760 0 ▶ $r .= defined($v) ? $v : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 0 0 0
3761 }
3762 0 return $r;
3763 }
3764  
3765 # Binary operator: find rightmost at depth 0 (precedence low->high: || then +/- then */%)
3766 5579 for my $op ('\\|\\|', '[+\\-]', '[*/%]') {
3767 16707 my $p = find_binop($expr, $op);
3768 16707 ▶ if (defined $p) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $p) 36 16671 16707
3769 36 my $opsym = substr($expr, $p->{s}, $p->{l});
3770 36 my $lv = eval_expr(substr($expr, 0, $p->{s}), $row);
3771 36 my $rv = eval_expr(substr($expr, $p->{s}+$p->{l}), $row);
3772 36 ▶ if ($opsym eq '||') {
Branch: 1 branch
BranchTrueFalseTotal
if ($opsym eq "||") 6 30 36
3773 6 ▶ return (defined($lv) ? $lv : '').(defined($rv) ? $rv : '');
Branch: 2 branches
BranchTrueFalseTotal
defined $lv ? : 6 0 6
defined $rv ? : 6 0 6
3774 }
3775 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
3776 30 my($l, $r) = ($lv + 0, $rv + 0);
3777 30 ▶ return $l + $r if $opsym eq '+';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "+" 18 12 30
3778 12 ▶ return $l - $r if $opsym eq '-';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "-" 0 12 12
3779 12 ▶ return $l * $r if $opsym eq '*';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "*" 6 6 12
3780 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
3781 6 ▶ return $l / $r if $opsym eq '/';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "/" 0 6 6
3782 6 ▶ return $l % $r if $opsym eq '%';
Branch: 1 branch
BranchTrueFalseTotal
if $opsym eq "%" 6 0 6
3783 }
3784 }
3785 5543 ▶ if ($expr =~ /^-([\w('.].*)$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^-([\w('.].*)$/s) 0 5543 5543
3786 0 my $v = eval_expr($1, $row);
3787 0 ▶ return undef unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 0 0
3788 0 return - ($v + 0);
3789 }
3790 5543 ▶ if ($expr =~ /^(\w+)\.(\w+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(\w+)\.(\w+)$/) 46 5497 5543
3791 46 my($a, $c) = ($1, $2);
3792 46 ▶ return exists($row->{"$a.$c"}) ? $row->{"$a.$c"} : $row->{$c};
Branch: 1 branch
BranchTrueFalseTotal
exists $$row{"$a.$c"} ? : 16 30 46
3793 }
3794 5497 ▶ return $row->{$expr} if $expr =~ /^\w+$/;
Branch: 1 branch
BranchTrueFalseTotal
if $expr =~ /^\w+$/ 5497 0 5497
3795 0 return undef;
3796 }
3797  
3798 9 ▶sub eval_case {
Subroutine eval_case: called CC=12 SCAR=33.6
Pod undocumented
3799 9 my($body, $row) = @_;
3800 9 $body =~ s/^\s+|\s+$//g;
3801 9 my $base;
3802 9 ▶ unless ($body =~ /^\s*WHEN\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($body =~ /^\s*WHEN\b/i) 0 9 9
3803 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
3804 }
3805 9 my $else;
3806 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
3807 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
3808 15 my($we, $te) = ($1, $2);
3809 15 my $m;
3810 15 ▶ if (defined $base) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $base) { } 0 15 15
3811 0 my($bv, $wv) = (eval_expr($base, $row), eval_expr($we, $row));
3812 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
3813 }
3814 else {
3815 15 $m = eval_bool($we, $row);
3816 }
3817 15 ▶ return eval_expr($te, $row) if $m;
Branch: 1 branch
BranchTrueFalseTotal
if $m 6 9 15
3818 }
3819 3 ▶ return defined($else) ? eval_expr($else, $row) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $else ? : 3 0 3
3820 }
3821  
3822 40 ▶sub eval_bool {
Subroutine eval_bool: called CC=21 SCAR=42.3
Pod undocumented
3823 40 my($expr, $row) = @_;
3824 40 $expr =~ s/^\s+|\s+$//g;
3825 40 ▶ if ($expr =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expr =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) 40 0 40
3826 40 my($l, $op, $r) = ($1, uc($2), $3);
3827 40 my($lv, $rv) = (eval_expr($l, $row), eval_expr($r, $row));
3828 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
3829 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
3830 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
3831 35 ▶ return $n ? ($lv != $rv) : ($lv ne $rv) if $op =~ /^(!|<>)/;
Branch: 2 branches
BranchTrueFalseTotal
if $op =~ /^(!|<>)/ 0 35 35
$n ? : 0 0 0
3832 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
3833 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
3834 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
3835 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
3836 }
3837 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
3838 0 my $v = eval_expr($1, $row);
3839 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
3840 }
3841 0 return 0;
3842 }
3843  
3844 # Argument splitter (handles parentheses and string literals)
3845 607 ▶sub args {
Subroutine args: called CC=12 SCAR=24.9
Pod undocumented
3846 607 my($str) = @_;
3847 607 my @parts;
3848 607 my $cur = '';
3849 607 my $d = 0;
3850 607 my $in_q = 0;
3851 607 for my $ch (split //, $str) {
3852 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
3853 29 $in_q = 1;
3854 29 $cur .= $ch;
3855 }
3856 ▶ 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
3857 29 $in_q = 0;
3858 29 $cur .= $ch;
3859 }
3860 elsif ($in_q) {
3861 139 $cur .= $ch;
3862 }
3863 elsif ($ch eq '(') {
3864 70 $d++;
3865 70 $cur .= $ch;
3866 }
3867 elsif ($ch eq ')') {
3868 70 $d--;
3869 70 $cur .= $ch;
3870 }
3871 ▶ 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
3872 155 push @parts, $cur;
3873 155 $cur = '';
3874 }
3875 else {
3876 3207 $cur .= $ch;
3877 }
3878 }
3879 607 ▶ push @parts, $cur if $cur =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $cur =~ /\S/ 607 0 607
3880 607 return @parts;
3881 }
3882  
3883 # Find rightmost binary operator at depth 0
3884 16707 ▶sub find_binop {
Subroutine find_binop: called CC=14 SCAR=27.2
Pod undocumented
3885 16707 my($expr, $op_pat) = @_;
3886 16707 my $d = 0;
3887 16707 my $in_q = 0;
3888 16707 my $best = undef;
3889 16707 for my $i (0 .. length($expr)-1) {
3890 47624 my $ch = substr($expr, $i, 1);
3891 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
3892 2 $in_q = 1;
3893 }
3894 ▶ 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
3895 2 $in_q = 0;
3896 }
3897 ▶ 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
3898 0 $d++;
3899 }
3900 ▶ 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
3901 0 $d--;
3902 }
3903 ▶ 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
3904 30911 ▶ if (substr($expr, $i) =~ /^($op_pat)/) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($expr, $i) =~ /^($op_pat)/) 37 30874 30911
3905 37 $best = { s=>$i, l=>length($1) };
3906 }
3907 }
3908 }
3909 16707 return $best;
3910 }
3911  
3912 # =============================================================================
3913 # WHERE engine where_sub($expr) -> coderef
3914 # =============================================================================
3915 479 ▶sub where_sub {
Subroutine where_sub: called CC=3 SCAR=13.3
Pod undocumented
3916 479 my($expr) = @_;
3917 0 ▶ 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
3918 479 return compile_tree(parse_bool($expr));
3919 }
3920  
3921 655 ▶sub parse_bool {
Subroutine parse_bool: called CC=6 SCAR=17.9
Pod undocumented
3922 655 my($expr) = @_;
3923 655 $expr =~ s/^\s+|\s+$//g;
3924 655 my @or = bool_split($expr, 'OR');
3925 655 ▶ return { op=>'OR', kids=>[map{parse_bool($_)}@or] } if @or > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @or > 1 38 617 655
3926 617 my @and = bool_split($expr, 'AND');
3927 617 ▶ return { op=>'AND', kids=>[map{parse_bool($_)}@and] } if @and > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @and > 1 45 572 617
3928 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
3929 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
3930 2 return parse_bool($1);
3931 }
3932 568 return { op=>'LEAF', cond=>parse_leaf($expr) };
3933 }
3934  
3935 1317 ▶sub bool_split {
Subroutine bool_split: called CC=19 SCAR=29.5
Pod undocumented
3936 1317 my($expr, $kw) = @_;
3937 1317 my $kl = length($kw);
3938 1317 my @parts;
3939 1317 my $cur = '';
3940 1317 my $d = 0;
3941 1317 my $in_q = 0;
3942 1317 my $i = 0;
3943 1317 my $len = length($expr);
3944 1317 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 15590 1317 16907
3945 15590 my $ch = substr($expr, $i, 1);
3946 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
3947 326 $in_q = 1;
3948 326 $cur .= $ch;
3949 }
3950 ▶ 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
3951 326 $in_q = 0;
3952 326 $cur .= $ch;
3953 }
3954 elsif ($in_q) {
3955 1070 $cur .= $ch;
3956 }
3957 elsif ($ch eq '(') {
3958 168 $d++;
3959 168 $cur .= $ch;
3960 }
3961 elsif ($ch eq ')') {
3962 168 $d--;
3963 168 $cur .= $ch;
3964 }
3965 ▶ 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
3966 && !$in_q
3967 && (uc(substr($expr, $i, $kl)) eq $kw)
3968 && (($i == 0) || (substr($expr, $i-1, 1) =~ /\s/))
3969 && (($i+$kl) < $len)
3970 && (substr($expr, $i+$kl, 1) =~ /\s/)
3971 ) {
3972  
3973 # For AND: do not split the AND inside BETWEEN x AND y
3974 135 ▶ if ($kw eq 'AND') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kw eq "AND") 56 79 135
3975 56 my $before = $cur;
3976 56 $before =~ s/^\s+|\s+$//g;
3977 56 ▶ if ($before =~ /\bBETWEEN\s+\S+\s*$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($before =~ /\bBETWEEN\s+\S+\s*$/i) 10 46 56
3978 10 $cur .= $ch;
3979 10 $i++;
3980 10 next;
3981 }
3982 }
3983 125 push @parts, $cur;
3984 125 $cur = '';
3985 125 $i += $kl;
3986 125 next;
3987 }
3988 else {
3989 13397 $cur .= $ch;
3990 }
3991 15455 $i++;
3992 }
3993 1317 push @parts, $cur;
3994 1317 @parts = grep {/\S/} @parts;
3995 1317 ▶ return @parts > 1 ? @parts : ($expr);
Branch: 1 branch
BranchTrueFalseTotal
@parts > 1 ? : 114 1203 1317
3996 }
3997  
3998 # Split $sql into alternating chunks of [ is_literal, text ] so that a
3999 # placeholder inside a quoted string is never mistaken for a bind marker.
4000 3630 ▶sub _split_sql_literals {
Subroutine _split_sql_literals: called CC=9 SCAR=22.0
4001 3630 my($sql) = @_;
4002 3630 my @parts;
4003 3630 my $len = length $sql;
4004 3630 my $i = 0;
4005 3630 my $cur = '';
4006 3630 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 142443 3630 146073
4007 142443 ▶ if (substr($sql, $i, 1) eq "'") {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $i, 1) eq "'") 1333 141110 142443
4008 1333 ▶ push @parts, [ 0, $cur ] if length $cur;
Branch: 1 branch
BranchTrueFalseTotal
if length $cur 1333 0 1333
4009 1333 $cur = '';
4010 1333 my $j = $i + 1;
4011 1333 ▶ while ($j < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $len) 5389 0 5389
4012 5389 ▶ if (substr($sql, $j, 1) ne "'") { $j++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $j, 1) ne "'") 4049 1340 5389
4013 1340 ▶ last unless substr($sql, $j+1, 1) eq "'";
Branch: 1 branch
BranchTrueFalseTotal
unless substr($sql, $j + 1, 1) eq "'" 1333 7 1340
4014 7 $j += 2;
4015 }
4016 1333 ▶ $j = $len if $j > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $j > $len 0 1333 1333
4017 1333 push @parts, [ 1, substr($sql, $i, $j-$i+1) ];
4018 1333 $i = $j + 1;
4019 1333 next;
4020 }
4021 141110 $cur .= substr($sql, $i, 1);
4022 141110 $i++;
4023 }
4024 3630 ▶ push @parts, [ 0, $cur ] if length $cur;
Branch: 1 branch
BranchTrueFalseTotal
if length $cur 3551 79 3630
4025 3630 return @parts;
4026 }
4027  
4028 # Collapse each run of whitespace to a single space, but leave string
4029 # literals byte for byte alone: a newline or a tab inside a literal is
4030 # part of the value, not statement layout.
4031 3112 ▶sub _normalize_sql_space {
Subroutine _normalize_sql_space: called CC=3 SCAR=11.0
4032 3112 my($sql) = @_;
4033 3112 my $out = '';
4034 3112 for my $part (_split_sql_literals($sql)) {
4035 5482 ▶ if ($part->[0]) { $out .= $part->[1]; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($part->[0]) 1221 4261 5482
4036 4261 my $chunk = $part->[1];
4037 4261 $chunk =~ s/\s+/ /g;
4038 4261 $out .= $chunk;
4039 }
4040 3112 return $out;
4041 }
4042  
4043 4030 ▶sub _strip_sql_comments {
Subroutine _strip_sql_comments: called CC=13 SCAR=25.7
4044 4030 my($sql) = @_;
4045 4030 my $out = '';
4046 4030 my $len = length($sql);
4047 4030 my $i = 0;
4048 4030 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 159147 4030 163177
4049 159147 my $ch = substr($sql, $i, 1);
4050 159147 ▶ if ($ch eq "'") {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq "'") 1440 157707 159147
4051 1440 my $j = $i + 1;
4052 1440 ▶ while ($j < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $len) 5944 0 5944
4053 5944 ▶ if (substr($sql, $j, 1) ne "'") { $j++; next }
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $j, 1) ne "'") 4495 1449 5944
4054 1449 ▶ last unless substr($sql, $j+1, 1) eq "'";
Branch: 1 branch
BranchTrueFalseTotal
unless substr($sql, $j + 1, 1) eq "'" 1440 9 1449
4055 9 $j += 2;
4056 }
4057 1440 ▶ $j = $len if $j > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $j > $len 0 1440 1440
4058 1440 $out .= substr($sql, $i, $j-$i+1);
4059 1440 $i = $j + 1;
4060 1440 next;
4061 }
4062 157707 ▶ if (substr($sql, $i, 2) eq '--') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $i, 2) eq "--") 9 157698 157707
4063 9 $i += 2;
4064 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
4065 9 $out .= ' ';
4066 9 next;
4067 }
4068 157698 ▶ if (substr($sql, $i, 2) eq '/*') {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($sql, $i, 2) eq "/*") 8 157690 157698
4069 8 $i += 2;
4070 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
4071 8 $i += 2;
4072 8 $out .= ' ';
4073 8 next;
4074 }
4075 157690 $out .= $ch;
4076 157690 $i++;
4077 }
4078 4030 $out =~ s/^\s+|\s+$//g;
4079 4030 return $out;
4080 }
4081  
4082 16 ▶sub _like_to_re {
Subroutine _like_to_re: called CC=4 SCAR=13.9
4083 16 my($pat) = @_;
4084 16 my $re = '';
4085 16 for my $i (0 .. length($pat)-1) {
4086 59 my $ch = substr($pat, $i, 1);
4087 59 ▶ if ($ch eq '%') { $re .= '.*' }
Branch: 2 branches
BranchTrueFalseTotal
if ($ch eq '%') { } 14 45 59
elsif ($ch eq '_') { } 1 44 45
4088 1 elsif ($ch eq '_') { $re .= '.' }
4089 44 else { $re .= quotemeta($ch) }
4090 }
4091 16 return $re;
4092 }
4093  
4094 568 ▶sub parse_leaf {
Subroutine parse_leaf: called CC=18 SCAR=28.9
Pod undocumented
4095 568 my($part) = @_;
4096 568 $part =~ s/^\s+|\s+$//g;
4097 568 ▶ if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) 3 565 568
4098 3 my($neg, $v) = ($1, $2);
4099 3 ▶ my $t = $v ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$v ? : 1 2 3
4100 3 ▶ $t = 1 - $t if $neg;
Branch: 1 branch
BranchTrueFalseTotal
if $neg 0 3 3
4101 3 return { op=>'CONST', val=>$t };
4102 }
4103 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
4104 71 my($col, $neg, $ls) = ($1, $2, $3);
4105 71 my @vals;
4106 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
4107 285 my($sv, $nv, $nl) = ($1, $2, $3);
4108 285 ▶ if (defined $nl) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $nl) { } 3 282 285
elsif (defined $sv) { } 19 263 282
4109 3 push @vals, undef;
4110 }
4111 elsif (defined $sv) {
4112 19 (my $x = $sv) =~ s/''/'/g;
4113 19 push @vals, $x;
4114 }
4115 else {
4116 263 push @vals, $nv;
4117 }
4118 }
4119 71 ▶ return { op=>($neg ? 'NOT_IN' : 'IN'), col=>$col, vals=>[ @vals ] };
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 27 44 71
4120 }
4121 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
4122 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
4123 3 ▶ return { op=>($2 ? 'IS_NOT_NULL' : 'IS_NULL'), col=>$1 };
Branch: 1 branch
BranchTrueFalseTotal
$2 ? : 2 1 3
4124 }
4125 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
4126 10 my($col, $neg, $lo, $hi) = ($1, $2, $3, $4);
4127 10 $lo =~ s/^'(.*)'$/$1/s;
4128 10 $hi =~ s/^'(.*)'$/$1/s;
4129 10 ▶ return { op=>($neg ? 'NOT_BETWEEN' : 'BETWEEN'), col=>$col, lo=>$lo, hi=>$hi };
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 1 9 10
4130 }
4131 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
4132 13 my($lhs, $neg, $pat) = ($1, $2, $3);
4133 13 $pat =~ s/^'(.*)'$/$1/s;
4134 13 $pat =~ s/''/'/g;
4135 13 my $re = _like_to_re($pat);
4136 13 ▶ return { op=>($neg ? 'NOT_LIKE' : 'LIKE'), lhs=>$lhs, re=>$re };
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 2 11 13
4137 }
4138 467 ▶ if ($part =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) {
Branch: 1 branch
BranchTrueFalseTotal
if ($part =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) 467 0 467
4139 467 my($lhs, $op, $rhs) = ($1, uc($2), $3);
4140 467 $lhs =~ s/^\s+|\s+$//g;
4141 467 $rhs =~ s/^\s+|\s+$//g;
4142 467 my $rv;
4143 467 ▶ if ($rhs =~ /^'((?:[^']|'')*)'$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rhs =~ /^'((?:[^']|'')*)'$/) { } 83 384 467
4144 83 ($rv = $1) =~ s/''/'/g;
4145 }
4146 else {
4147 384 $rv = $rhs;
4148 }
4149 467 return{ op=>$op, lhs=>$lhs, rhs_expr=>$rhs, rhs_val=>$rv };
4150 }
4151 0 return{ op=>'CONST', val=>0 };
4152 }
4153  
4154 653 ▶sub compile_tree {
Subroutine compile_tree: called CC=4 SCAR=13.9
Pod undocumented
4155 653 my($tree) = @_;
4156 653 my $op = $tree->{op};
4157 653 ▶ if ($op eq 'AND') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "AND") 45 608 653
4158 45 my @s = map {compile_tree($_)} @{$tree->{kids}};
4159 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
4160 }
4161 608 ▶ if ($op eq 'OR') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "OR") 38 570 608
4162 38 my @s = map { compile_tree($_) } @{$tree->{kids}};
4163 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
4164 }
4165 570 ▶ if ($op eq 'NOT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "NOT") 2 568 570
4166 2 my $s = compile_tree($tree->{kids}[0]);
4167 2 ▶ return sub{ $s->($_[0]) ? 0 : 1 };
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
&$s($_[0]) ? : 1 11 12
4168 }
4169 568 return compile_leaf($tree->{cond});
4170 }
4171  
4172 568 ▶sub compile_leaf {
Subroutine compile_leaf: called CC=11 SCAR=24.3
Pod undocumented
4173 568 my($c) = @_;
4174 568 ▶ my $op = defined($c->{op}) ? $c->{op} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $c->{'op'} ? : 568 0 568
4175 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
4176 564 ▶ if ($op eq 'IS_NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IS_NULL") 1 563 564
4177 1 my $col = $c->{col};
4178 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 "" 0 3 3
4179 }
4180 563 ▶ if ($op eq 'IS_NOT_NULL') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "IS_NOT_NULL") 2 561 563
4181 2 my $col = $c->{col};
4182 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
4183 }
4184 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
4185 10 my($col, $lo, $hi, $neg) = ($c->{col}, $c->{lo}, $c->{hi}, $op eq 'NOT_BETWEEN');
4186 50 ▶ return sub {
Subroutine __ANON__: called CC=8 SCAR=24.7
4187 50 my $v = $_[0]{$col};
4188 50 ▶ return 0 unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 50 50
4189 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
4190 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
4191 50 ▶ $neg ? !$in_q : $in_q;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 4 46 50
4192 10 };
4193 }
4194 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
4195 71 my($col, $vals, $neg) = ($c->{col}, $c->{vals}, $op eq 'NOT_IN');
4196 791 ▶ return sub {
Subroutine __ANON__: called CC=11 SCAR=24.0
4197 791 ▶ my $rv = defined($_[0]{$col}) ? $_[0]{$col} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0]{$col} ? : 791 0 791
4198 791 my $f = 0;
4199 791 my $has_null = 0;
4200 791 for my $cv (@$vals) {
4201 11824 ▶ unless (defined $cv) { $has_null = 1; next }
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cv) 22 11802 11824
4202 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
4203 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
4204 161 $f = 1;
4205 161 last;
4206 }
4207 }
4208 # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN
4209 # when value not found -> treat as false (exclude the row).
4210 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
4211 785 ▶ $neg ? !$f : $f;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 235 550 785
4212 71 };
4213 }
4214 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
4215 13 my($lhs, $re, $neg) = ($c->{lhs}, $c->{re}, $op eq 'NOT_LIKE');
4216 69 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
4217 69 my $v = eval_expr($lhs, $_[0]);
4218 69 ▶ $v = '' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 69 69
4219 69 ▶ my $m = ($v =~ /^$re$/si) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$v =~ /^$re$/is ? : 19 50 69
4220 69 ▶ $neg ? !$m : $m;
Branch: 1 branch
BranchTrueFalseTotal
$neg ? : 9 60 69
4221 13 };
4222 }
4223 467 my($lhs, $op2, $rv_lit, $rhs_expr) = @{$c}{qw(lhs op rhs_val rhs_expr)};
4224 2319 ▶ return sub {
Subroutine __ANON__: called CC=18 SCAR=30.3
4225 2319 my $row = $_[0];
4226 2319 my $lv = eval_expr($lhs, $row);
4227 2319 ▶ return 0 unless defined $lv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $lv 0 2319 2319
4228 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
4229 2319 ▶ $rv = '' unless defined $rv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $rv 0 2319 2319
4230 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
4231 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
4232 760 ▶ return $n ? ($lv != $rv) : ($lv ne $rv) if $op2 =~ /^(!|<>)/;
Branch: 2 branches
BranchTrueFalseTotal
if $op2 =~ /^(!|<>)/ 18 742 760
$n ? : 8 10 18
4233 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
4234 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
4235 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
4236 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
4237 0 return 0;
4238 467 };
4239 }
4240  
4241 # =============================================================================
4242 # SELECT dispatcher
4243 # =============================================================================
4244 739 ▶sub select {
Subroutine select: called CC=121 SCAR=54.3
Pod documented
4245 739 my($self, $sql) = @_;
4246 # Window functions are not supported; detect and reject early.
4247 # Strip string literals before checking to avoid false positives.
4248 739 my $sql_nostr = $sql;
4249 739 $sql_nostr =~ s/'(?:[^']|'')*'/''/g;
4250 739 ▶ if ($sql_nostr =~ /\bOVER\s*\(/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql_nostr =~ /\bOVER\s*\(/i) 7 732 739
4251 7 return $self->_err(
4252 "Window functions (OVER clause) are not supported. "
4253 . "Use GROUP BY with aggregate functions instead."
4254 );
4255 }
4256 732 my @up = split_union($sql);
4257 732 ▶ return $self->exec_union([ @up ]) if @up > 1;
Branch: 1 branch
BranchTrueFalseTotal
if @up > 1 38 694 732
4258 694 ▶ if ($sql =~ /\bJOIN\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\bJOIN\b/i) 89 605 694
4259  
4260 # Parse GROUP BY / HAVING from the SQL before handing off to _parse_join_sql
4261 89 my $join_sql = $sql;
4262 89 my(@gb_join, $having_join);
4263 89 $having_join = '';
4264 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
4265 0 $having_join = $1;
4266 0 $having_join =~ s/^\s+|\s+$//g;
4267 }
4268 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
4269 6 my $gbs = $1;
4270 6 $gbs =~ s/^\s+|\s+$//g;
4271 6 @gb_join = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $gbs;
4272 }
4273 89 my $has_agg = ($sql =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/si);
4274 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
4275  
4276 89 my $parsed = _parse_join_sql($join_sql);
4277  
4278 # A JOIN construct the parser cannot execute is reported here rather
4279 # than left to fall through to the single-table parser, which used to
4280 # accept it and return rows that answered a different question.
4281 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
4282 16 return { type=>'error', message=>$parsed->[4] };
4283 }
4284 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
4285 73 my($js, $cs, $wc, $opts) = @$parsed;
4286  
4287 # ORDER BY <position>: resolve against the select list. In the
4288 # aggregate branch the sort runs on projected rows keyed by
4289 # alias, in the plain branch on raw rows keyed by expression.
4290 my @sel_names =
4291 73 ▶ map { $needs_groupby ? _order_alias_of($_) : _order_name_of($_) } @$cs;
Branch: 1 branch
BranchTrueFalseTotal
$needs_groupby ? : 13 106 119
4292 73 ▶ my @ob_keys = $opts->{order_keys} ? @{$opts->{order_keys}} : ();
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'order_keys'} ? : 31 42 73
4293 73 for my $k (@ob_keys) {
4294 34 my($obe, $obk) = _resolve_order_ordinal_scalar($k->[0], [ @sel_names ]);
4295 34 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 0 34 34
4296 34 ▶ $k->[0] = $obk if defined $obk;
Branch: 1 branch
BranchTrueFalseTotal
if defined $obk 34 0 34
4297 }
4298 73 ▶ if (@ob_keys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ob_keys) 31 42 73
4299 31 $opts->{order_keys} = [ @ob_keys ];
4300 31 $opts->{order_by} = $ob_keys[0][0];
4301 31 $opts->{order_dir} = $ob_keys[0][1];
4302 }
4303  
4304 # If GROUP BY / HAVING / aggregate: fetch raw rows with SELECT *
4305 73 my $rows;
4306 73 ▶ if ($needs_groupby) {
Branch: 1 branch
BranchTrueFalseTotal
if ($needs_groupby) { } 6 67 73
4307  
4308 # Fetch all columns as raw data for aggregation
4309 6 my $raw_opts = {%$opts};
4310 6 delete $raw_opts->{order_by};
4311 6 delete $raw_opts->{order_dir};
4312 6 delete $raw_opts->{order_keys};
4313 6 delete $raw_opts->{limit};
4314 6 delete $raw_opts->{offset};
4315 6 delete $raw_opts->{distinct};
4316 6 $rows = $self->join_select($js, [], $wc, $raw_opts);
4317 }
4318 else {
4319 67 $rows = $self->join_select($js, $cs, $wc, $opts);
4320 }
4321 73 ▶ return{ type=>'error', message=>$errstr } unless $rows;
Branch: 1 branch
BranchTrueFalseTotal
unless $rows 8 65 73
4322  
4323 65 ▶ if ($needs_groupby) {
Branch: 1 branch
BranchTrueFalseTotal
if ($needs_groupby) 6 59 65
4324  
4325 # Parse col_specs from the original SQL for aggregate evaluation
4326 6 my @col_specs_raw;
4327 6 ▶ if ($sql =~ /^SELECT\s+(.+?)\s+FROM\b/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SELECT\s+(.+?)\s+FROM\b/is) 6 0 6
4328 6 my $cs_str = $1;
4329 6 for my $c (split /\s*,\s*/, $cs_str) {
4330 13 $c =~ s/^\s+|\s+$//g;
4331 13 ▶ if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/is) { } 4 9 13
4332 4 push @col_specs_raw, [ $1, $2 ];
4333 }
4334 else {
4335 9 ▶ my $alias = ($c =~ /^(\w+)\.(\w+)$/) ? $2 : $c;
Branch: 1 branch
BranchTrueFalseTotal
$c =~ /^(\w+)\.(\w+)$/ ? : 5 4 9
4336 9 push @col_specs_raw, [ $c, $alias ];
4337 }
4338 }
4339 }
4340  
4341 # Group rows
4342 6 my(%gr, @go);
4343 6 ▶ if (@gb_join) {
Branch: 1 branch
BranchTrueFalseTotal
if (@gb_join) { } 6 0 6
4344 6 for my $row (@$rows) {
4345  
4346 # resolve GROUP BY key: try qualified then unqualified
4347 my $k = join("\x00", map {
4348 21 my $col = $_;
4349 my $v = defined($row->{$col})
4350 ? $row->{$col}
4351 : (($col =~ /^(\w+)\.(\w+)$/) && defined $row->{$2})
4352 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
4353 : '';
4354 21 ▶ defined($v) ? $v : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 21 0 21
4355 } @gb_join);
4356 21 ▶ push @go, $k unless exists $gr{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $gr{$k} 10 11 21
4357 21 push @{$gr{$k}}, $row;
4358 }
4359 }
4360 else {
4361 0 @go = ('__all__');
4362 0 $gr{__all__} = $rows;
4363 }
4364  
4365 6 my @results;
4366 6 for my $gk (@go) {
4367 10 my $grp = $gr{$gk};
4368 10 my $rep = $grp->[0];
4369 10 my %out;
4370 10 for my $spec (@col_specs_raw) {
4371 23 my($expr, $alias) = @$spec;
4372 23 $out{$alias} = eval_agg($expr, $grp, $rep);
4373 }
4374 10 ▶ if ($having_join ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($having_join ne "") 0 10 10
4375 0 my $h = $having_join;
4376 0 my $cnt = scalar @$grp;
4377 0 $h =~ s/COUNT\s*\(\s*\*\s*\)/$cnt/gsi;
4378 0 $h =~ s/\b(SUM|AVG|MIN|MAX|COUNT)\s*\(([^)]+)\)/eval_agg("$1($2)", $grp, $rep)/geis;
4379 0 ▶ next unless where_sub($h)->({ %out });
Branch: 1 branch
BranchTrueFalseTotal
unless where_sub($h)->({%out}) 0 0 0
4380 }
4381 10 push @results, { %out };
4382 }
4383  
4384 # ORDER BY from opts (every key, in order)
4385 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
4386 : (defined($opts->{order_by})
4387 6 ▶ ? ([ $opts->{order_by}, ($opts->{order_dir} || 'ASC') ])
Branch: 1 branch
BranchTrueFalseTotal
$opts->{'order_keys'} ? : 3 3 6
4388 : ());
4389 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
4390  
4391 # An aggregate result row is keyed by the select-list
4392 # alias, so "ORDER BY a.y" over "SELECT a.y, COUNT(*)"
4393 # has to resolve to the key 'y'. Before 1.09 it resolved
4394 # to nothing and the sort quietly did not happen.
4395 3 for my $k (@gob) {
4396 3 ▶ next if exists $results[0]{$k->[0]};
Branch: 1 branch
BranchTrueFalseTotal
if exists $results[0]{$k->[0]} 0 3 3
4397 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
4398 2 $k->[0] = $1;
4399 2 next;
4400 }
4401 1 return { type=>'error', message=>
4402 "ORDER BY column '$k->[0]' is not in the select "
4403 . "list of this aggregate query" };
4404 }
4405 }
4406 5 ▶ if (@gob) {
Branch: 1 branch
BranchTrueFalseTotal
if (@gob) 2 3 5
4407 @results = sort {
4408 2 my $cmp = 0;
4409 4 for my $k (@gob) {
4410 4 my($key, $dir) = @$k;
4411 4 ▶ my $va = defined($a->{$key}) ? $a->{$key} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::a->{$key} ? : 4 0 4
4412 4 ▶ my $vb = defined($b->{$key}) ? $b->{$key} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $DB::Handy::b->{$key} ? : 4 0 4
4413 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
4414 ? ($va <=> $vb)
4415 : ($va cmp $vb);
4416 4 ▶ $c = -$c if lc($dir) eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if lc $dir eq "desc" 1 3 4
4417 4 ▶ if ($c != 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c != 0) 4 0 4
4418 4 $cmp = $c;
4419 4 last;
4420 }
4421 }
4422 $cmp;
4423 } @results;
4424 }
4425 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
4426 0 @results = splice(@results, $opts->{offset});
4427 }
4428 5 ▶ if (defined $opts->{limit}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts->{"limit"}) 0 5 5
4429 0 my $l = $opts->{limit} - 1;
4430 0 ▶ $l = $#results if $l > $#results;
Branch: 1 branch
BranchTrueFalseTotal
if $l > $#results 0 0 0
4431 0 @results = @results[0 .. $l];
4432 }
4433 5 return { type=>'rows', data=>[ @results ] };
4434 }
4435 59 return { type=>'rows', data=>$rows };
4436 }
4437 }
4438 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"} 605 0 605
4439 605 my($distinct, $col_specs, $tbl, $where_expr, $gb, $having, $ob, $limit, $offset) = @$p;
4440 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
4441 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
4442 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} 563 7 570
4443 563 my $obe = _resolve_order_ordinals($ob, $col_specs, $sch);
4444 563 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 3 560 563
4445 560 my $dat = $self->_file($tbl, 'dat');
4446 560 my $ws;
4447 560 ▶ if ($where_expr ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($where_expr ne "") 414 146 560
4448 # Case 1: single condition col OP val (no AND/OR/NOT/BETWEEN/IN)
4449 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
4450 && ($where_expr !~ /\b(?:OR|AND|NOT|BETWEEN|IN)\b/i)
4451 ) {
4452 235 my($col, $op, $sv, $nv) = ($1, $2, $3, $4);
4453 235 ▶ my $cond = [{ col=>$col, op=>uc($op), val=>defined($sv) ? $sv : $nv }];
Branch: 1 branch
BranchTrueFalseTotal
defined $sv ? : 30 205 235
4454 235 my $idx = $self->_find_index_for_conds($tbl, $sch, $cond);
4455 235 ▶ if (defined $idx) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx) 47 188 235
4456 47 my $wsub = where_sub($where_expr);
4457 47 my @rows;
4458 47 local *FH;
4459 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: $!") 47 0 47
4460 47 binmode FH;
4461 47 _lock_sh(\*FH);
4462 47 my $rs = $sch->{recsize};
4463 47 for my $rn (sort { $a <=> $b } @$idx) {
4464 105 seek(FH, $rn*$rs, 0);
4465 105 my $raw = '';
4466 105 my $n = read(FH, $raw, $rs);
4467 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
4468 105 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 105 105
4469 105 my $row = $self->_unpack_record($sch, $raw);
4470 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
4471 }
4472 47 _unlock(\*FH);
4473 47 close FH;
4474 47 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4475 }
4476 }
4477 # Case 2: AND of two range conditions on the same indexed column
4478 # col OP1 val1 AND col OP2 val2 (e.g. id > 5 AND id < 10)
4479 # also: col BETWEEN val1 AND val2
4480 367 my $idx_range = $self->_try_index_and_range($tbl, $sch, $where_expr);
4481 367 ▶ if (defined $idx_range) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_range) 16 351 367
4482 16 my $wsub = where_sub($where_expr);
4483 16 my @rows;
4484 16 local *FH;
4485 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: $!") 16 0 16
4486 16 binmode FH;
4487 16 _lock_sh(\*FH);
4488 16 my $rs = $sch->{recsize};
4489 16 for my $rn (sort { $a <=> $b } @$idx_range) {
4490 95 seek(FH, $rn*$rs, 0);
4491 95 my $raw = '';
4492 95 my $n = read(FH, $raw, $rs);
4493 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
4494 95 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 95 95
4495 95 my $row = $self->_unpack_record($sch, $raw);
4496 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
4497 }
4498 16 _unlock(\*FH);
4499 16 close FH;
4500 16 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4501 }
4502 # Case 3: AND across different indexed columns.
4503 # Use the best available single-column index to narrow the candidate
4504 # record set, then apply the full WHERE predicate as a post-filter.
4505 # Example: WHERE dept = 'Eng' AND salary > 70000
4506 351 my $idx_partial = $self->_try_index_partial_and($tbl, $sch, $where_expr);
4507 351 ▶ if (defined $idx_partial) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_partial) 12 339 351
4508 12 my $wsub = where_sub($where_expr);
4509 12 my @rows;
4510 12 local *FH;
4511 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: $!") 12 0 12
4512 12 binmode FH;
4513 12 _lock_sh(\*FH);
4514 12 my $rs = $sch->{recsize};
4515 12 for my $rn (sort { $a <=> $b } @$idx_partial) {
4516 40 seek(FH, $rn*$rs, 0);
4517 40 my $raw = '';
4518 40 my $n = read(FH, $raw, $rs);
4519 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
4520 40 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 40 40
4521 40 my $row = $self->_unpack_record($sch, $raw);
4522 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
4523 }
4524 12 _unlock(\*FH);
4525 12 close FH;
4526 12 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4527 }
4528 # Case 4: col IN (v1, v2, ...) -- equality index per value, union.
4529 339 my $idx_in = $self->_try_index_in($tbl, $sch, $where_expr);
4530 339 ▶ if (defined $idx_in) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_in) 29 310 339
4531 29 my $wsub = where_sub($where_expr);
4532 29 my @rows;
4533 29 local *FH;
4534 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: $!") 29 0 29
4535 29 binmode FH;
4536 29 _lock_sh(\*FH);
4537 29 my $rs = $sch->{recsize};
4538 29 for my $rn (sort { $a <=> $b } @$idx_in) {
4539 100 seek(FH, $rn*$rs, 0);
4540 100 my $raw = '';
4541 100 my $n = read(FH, $raw, $rs);
4542 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
4543 100 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 100 100
4544 100 my $row = $self->_unpack_record($sch, $raw);
4545 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
4546 }
4547 29 _unlock(\*FH);
4548 29 close FH;
4549 29 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4550 }
4551 # Case 5: pure OR of simple indexed conditions.
4552 # Every atom must have an index; returns union of all matching records.
4553 310 my $idx_or = $self->_try_index_or($tbl, $sch, $where_expr);
4554 310 ▶ if (defined $idx_or) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_or) 30 280 310
4555 30 my $wsub = where_sub($where_expr);
4556 30 my @rows;
4557 30 local *FH;
4558 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: $!") 30 0 30
4559 30 binmode FH;
4560 30 _lock_sh(\*FH);
4561 30 my $rs = $sch->{recsize};
4562 30 for my $rn (sort { $a <=> $b } @$idx_or) {
4563 427 seek(FH, $rn*$rs, 0);
4564 427 my $raw = '';
4565 427 my $n = read(FH, $raw, $rs);
4566 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
4567 427 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 427 427
4568 427 my $row = $self->_unpack_record($sch, $raw);
4569 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
4570 }
4571 30 _unlock(\*FH);
4572 30 close FH;
4573 30 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4574 }
4575 # Case 6: col NOT IN (v1, v2, ...) -- index complement.
4576 280 my $idx_not_in = $self->_try_index_not_in($tbl, $sch, $where_expr);
4577 280 ▶ if (defined $idx_not_in) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $idx_not_in) 21 259 280
4578 21 my $wsub = where_sub($where_expr);
4579 21 my @rows;
4580 21 local *FH;
4581 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: $!") 21 0 21
4582 21 binmode FH;
4583 21 _lock_sh(\*FH);
4584 21 my $rs = $sch->{recsize};
4585 21 for my $rn (sort { $a <=> $b } @$idx_not_in) {
4586 196 seek(FH, $rn*$rs, 0);
4587 196 my $raw = '';
4588 196 my $n = read(FH, $raw, $rs);
4589 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
4590 196 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 0 196 196
4591 196 my $row = $self->_unpack_record($sch, $raw);
4592 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
4593 }
4594 21 _unlock(\*FH);
4595 21 close FH;
4596 21 return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] };
4597 }
4598 259 $ws = where_sub($where_expr);
4599 }
4600 405 my @raw;
4601 405 local *FH;
4602 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: $!") 405 0 405
4603 405 binmode FH;
4604 405 _lock_sh(\*FH);
4605 405 my $rs = $sch->{recsize};
4606 405 while (1) {
4607 2441 my $raw = '';
4608 2441 my $n = read(FH, $raw, $rs);
4609 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
4610 2036 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 14 2022 2036
4611 2022 my $row = $self->_unpack_record($sch, $raw);
4612 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
4613 }
4614 405 _unlock(\*FH);
4615 405 close FH;
4616 405 return{ type=>'rows', data=>[ $self->project([ @raw ], $col_specs, $distinct, $ob, $limit, $offset) ] };
4617 }
4618  
4619 605 ▶sub parse_select {
Subroutine parse_select: called CC=17 SCAR=28.7
Pod undocumented
4620 605 my($self, $sql) = @_;
4621 605 $sql =~ s/^\s+|\s+$//g;
4622 605 ▶ $sql =~ s/^SELECT\s+//si or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sql =~ s/^SELECT\s+//is or return undef 605 0 605
4623 605 my $distinct = 0;
4624 605 ▶ $distinct = 1 if $sql =~ s/^DISTINCT\s+//si;
Branch: 1 branch
BranchTrueFalseTotal
if $sql =~ s/^DISTINCT\s+//is 4 601 605
4625 605 my($col_str, $rest) = split_at_from($sql);
4626 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
4627 605 $rest =~ s/^\s*FROM\s+//si;
4628 605 my $tbl;
4629 605 ▶ ($rest =~ s/^(\w+)//) and ($tbl = $1);
Branch: 1 branch
BranchTrueFalseTotal
$rest =~ s/^(\w+)// and $tbl = $1 605 0 605
4630  
4631 # Optional alias (consumed only when token is not a SQL keyword)
4632 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
4633 0 $rest =~ s/^\s+(?:AS\s+)?\w+//si;
4634 }
4635 605 $rest =~ s/^\s+//;
4636 605 ▶ return undef unless $tbl;
Branch: 1 branch
BranchTrueFalseTotal
unless $tbl 0 605 605
4637 605 my($limit, $offset) = (undef, undef);
4638 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
4639 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
4640 605 my @ob;
4641 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
4642 85 my $s = $1;
4643 85 $s =~ s/^\s+|\s+$//g;
4644 85 for my $item (split /\s*,\s*/, $s) {
4645 88 $item =~ s/^\s+|\s+$//g;
4646 88 my $dir = 'ASC';
4647 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
4648 88 push @ob, [ $item, $dir ];
4649 }
4650 }
4651 605 my $having = '';
4652 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
4653 605 $having =~ s/^\s+|\s+$//g;
4654 605 my @gb;
4655 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
4656 12 @gb = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $1;
4657 }
4658 605 my $where = '';
4659 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
4660 605 my @cs = parse_col_list($col_str);
4661 605 return [ $distinct, [ @cs ], $tbl, $where, [ @gb ], $having, [ @ob ], $limit, $offset ];
4662 }
4663  
4664 605 ▶sub split_at_from {
Subroutine split_at_from: called CC=17 SCAR=28.9
Pod undocumented
4665 605 my($str) = @_;
4666 605 my $d = 0;
4667 605 my $in_q = 0;
4668 605 my $len = length($str);
4669 605 for my $i (0 .. $len-1) {
4670 4375 my $ch = substr($str, $i, 1);
4671 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
4672 8 $in_q = 1;
4673 }
4674 ▶ 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
4675 8 $in_q = 0;
4676 }
4677 ▶ 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
4678 59 $d++;
4679 }
4680 ▶ 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
4681 59 $d--;
4682 }
4683 ▶ 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
4684 && ($d == 0)
4685 && (uc(substr($str, $i, 4)) eq 'FROM')
4686 && (($i == 0) || (substr($str, $i-1, 1) =~ /\s/))
4687 && (($i+4 >= $len) || (substr($str, $i+4, 1) =~ /\s/))
4688 ) {
4689 605 return (substr($str, 0, $i), substr($str, $i));
4690 }
4691 }
4692 0 return (undef, undef);
4693 }
4694  
4695 617 ▶sub parse_col_list {
Subroutine parse_col_list: called CC=5 SCAR=16.1
Pod undocumented
4696 617 my($cs) = @_;
4697 617 $cs =~ s/^\s+|\s+$//g;
4698 617 ▶ return([ '*', '*' ]) if $cs eq '*';
Branch: 1 branch
BranchTrueFalseTotal
if $cs eq "*" 58 559 617
4699 559 my @specs;
4700 559 for my $c (args($cs)) {
4701 704 $c =~ s/^\s+|\s+$//g;
4702 704 my($expr, $alias);
4703 704 ▶ if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/is) { } 63 641 704
4704 63 ($expr, $alias) = ($1, $2);
4705 63 $expr =~ s/^\s+|\s+$//g;
4706 }
4707 else {
4708 641 $expr = $c;
4709 641 ▶ $alias = ($expr =~ /^(\w+)\.(\w+)$/?$2:$expr);
Branch: 1 branch
BranchTrueFalseTotal
$expr =~ /^(\w+)\.(\w+)$/ ? : 0 641 641
4710 }
4711 704 push @specs, [$expr, $alias];
4712 }
4713 559 return @specs;
4714 }
4715  
4716 # SQL-92 lets an ORDER BY key be written as a select-list position instead
4717 # of a column name ("ORDER BY 2 DESC"). Rewrite every such item into the
4718 # name of the column it refers to, so that the comparators further down see
4719 # a name. Left alone, a bare number was compared as a constant and the
4720 # result came back unsorted with no error at all.
4721 # @$col_specs is the parsed select list; $sch is the table schema, needed
4722 # to resolve a position when the select list is "*".
4723 # Returns '' on success, or an error message for an out-of-range position.
4724 598 ▶sub _resolve_order_ordinals {
Subroutine _resolve_order_ordinals: called CC=21 SCAR=32.3
4725 598 my($ob, $col_specs, $sch) = @_;
4726 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
4727 85 my $wanted = 0;
4728 85 for my $o (@$ob) {
4729 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
4730 }
4731 85 ▶ return '' unless $wanted;
Branch: 1 branch
BranchTrueFalseTotal
unless $wanted 76 9 85
4732  
4733 9 my @names;
4734 9 ▶ if (ref($col_specs) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $col_specs eq "ARRAY") 9 0 9
4735 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
4736 && ($col_specs->[0][0] eq '*')) {
4737 1 ▶ @names = map { $_->{name} } @{$sch->{cols}} if ref($sch) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $sch eq "HASH" 1 0 1
4738 }
4739 else {
4740 8 ▶ @names = map { ref($_) eq 'ARRAY' ? $_->[1] : $_ } @$col_specs;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ eq 'ARRAY' ? : 17 0 17
4741 }
4742 }
4743 9 for my $o (@$ob) {
4744 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
4745 10 ▶ next unless $o->[0] =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $o->[0] =~ /^\d+$/ 0 10 10
4746 10 my $n = $o->[0] + 0;
4747 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
4748 3 return "ORDER BY position $o->[0] is not in the select list";
4749 }
4750 7 $o->[0] = $names[$n - 1];
4751 }
4752 6 return '';
4753 }
4754  
4755 # Scalar counterpart of _resolve_order_ordinals, for the JOIN, derived
4756 # table and correlated subquery paths. Those carry a single ORDER BY key
4757 # rather than a list of them. @$names is the output column list in SELECT
4758 # order; when it is empty the position cannot be resolved (a "*" select
4759 # list whose expansion is not known at this point) and the position is
4760 # reported rather than quietly ignored.
4761 # Returns (error_message, key); error_message is '' on success, and key is
4762 # the original one when it was not a position.
4763 40 ▶sub _resolve_order_ordinal_scalar {
Subroutine _resolve_order_ordinal_scalar: called CC=7 SCAR=23.4
4764 40 my($ob, $names) = @_;
4765 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
4766 3 my $n = $ob + 0;
4767 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
4768 0 return ("ORDER BY position $ob is not in the select list", $ob);
4769 }
4770 3 return ('', $names->[$n - 1]);
4771 }
4772  
4773 # Select-list item as the sort comparators see it before projection: the
4774 # expression with any trailing "AS alias" removed.
4775 115 ▶sub _order_name_of {
Subroutine _order_name_of: called CC=2 SCAR=7.0
4776 115 my($item) = @_;
4777 115 ▶ return '' unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 115 115
4778 115 $item =~ s/^\s+|\s+$//g;
4779 115 $item =~ s/\s+AS\s+\w+\s*$//si;
4780 115 return $item;
4781 }
4782  
4783 # Select-list item as it is keyed after projection: the explicit alias,
4784 # the bare column of a qualified name, or the expression itself.
4785 13 ▶sub _order_alias_of {
Subroutine _order_alias_of: called CC=4 SCAR=13.9
4786 13 my($item) = @_;
4787 13 ▶ return '' unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 13 13
4788 13 $item =~ s/^\s+|\s+$//g;
4789 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
4790 9 ▶ return $2 if $item =~ /^(\w+)\.(\w+)$/;
Branch: 1 branch
BranchTrueFalseTotal
if $item =~ /^(\w+)\.(\w+)$/ 5 4 9
4791 4 return $item;
4792 }
4793  
4794 560 ▶sub project {
Subroutine project: called CC=23 SCAR=31.7
Pod undocumented
4795 560 ▶ my($self, $rows, $col_specs, $distinct, $ob, $limit, $offset) = @_; my $star = ((@$col_specs == 1) && ($col_specs->[0][0] eq '*'));
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
4796  
4797 # ORDER BY must be evaluated against the original (unprojected) rows so that
4798 # columns not listed in SELECT (e.g. "SELECT name ... ORDER BY score") are
4799 # still accessible for sorting.
4800 560 my @sorted = @$rows;
4801 560 ▶ if (@$ob) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$ob) 72 488 560
4802 @sorted = sort {
4803 72 my($ra, $rb) = ($a, $b);
4804 379 for my $o (@$ob) {
4805 393 my($e, $dir) = @$o;
4806 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
4807 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
4808 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
4809 393 ▶ $c = -$c if lc($dir) eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if lc $dir eq "desc" 63 330 393
4810 393 ▶ return $c if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 353 40 393
4811 }
4812 0
4813 } @sorted;
4814 }
4815  
4816 # Apply OFFSET / LIMIT on sorted raw rows before projection
4817 560 ▶ $offset = 0 unless defined $offset;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $offset 554 6 560
4818 560 ▶ @sorted = splice(@sorted, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 5 555 560
4819 560 ▶ if (defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 17 543 560
4820 17 my $l = $limit-1;
4821 17 ▶ $l = $#sorted if $l>$#sorted;
Branch: 1 branch
BranchTrueFalseTotal
if $l > $#sorted 0 17 17
4822 17 @sorted = @sorted[0 .. $l];
4823 }
4824  
4825 # Project to requested columns
4826 560 my @out;
4827 560 for my $row (@sorted) {
4828 1872 ▶ if ($star) {
Branch: 1 branch
BranchTrueFalseTotal
if ($star) { } 125 1747 1872
4829 125 push @out, { %$row };
4830 }
4831 else {
4832 1747 my %p;
4833 1747 $p{$_->[1]} = eval_expr($_->[0], $row) for @$col_specs;
4834 1747 push @out, { %p };
4835 }
4836 }
4837  
4838 # DISTINCT (applied after projection so aliases are visible)
4839 560 ▶ if ($distinct) {
Branch: 1 branch
BranchTrueFalseTotal
if ($distinct) 4 556 560
4840 4 my %s;
4841 my @d;
4842 4 for my $r (@out) {
4843 22 ▶ my $k = join("\x00", map{ defined($r->{$_}) ? $r->{$_} : "\x01" } sort keys %$r);
Branch: 1 branch
BranchTrueFalseTotal
defined $r->{$_} ? : 22 0 22
4844 22 ▶ push @d, $r unless $s{$k}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $s{$k}++ 10 12 22
4845 }
4846 4 @out = @d;
4847 }
4848 560 return @out;
4849 }
4850  
4851 # =============================================================================
4852 # GROUP BY / HAVING / aggregate functions
4853 # =============================================================================
4854 35 ▶sub exec_groupby {
Subroutine exec_groupby: called CC=24 SCAR=34.4
Pod undocumented
4855 35 my($self, $tbl, $col_specs, $where_expr, $gb, $having, $ob, $limit, $offset) = @_;
4856 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} 35 0 35
4857 35 my $obe = _resolve_order_ordinals($ob, $col_specs, $sch);
4858 35 ▶ return { type=>'error', message=>$obe } if $obe ne '';
Branch: 1 branch
BranchTrueFalseTotal
if $obe ne "" 0 35 35
4859 35 my $dat = $self->_file($tbl, 'dat');
4860 35 ▶ my $ws = ($where_expr ne '') ? where_sub($where_expr) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$where_expr ne '' ? : 4 31 35
4861 35 my @raw;
4862 35 local *FH;
4863 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: $!") 35 0 35
4864 35 binmode FH;
4865 35 _lock_sh(\*FH);
4866 35 my $rs = $sch->{recsize};
4867 35 while (1) {
4868 223 my $raw = '';
4869 223 my $n = read(FH, $raw, $rs);
4870 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
4871 188 ▶ next if substr($raw, 0, 1) eq RECORD_DELETED;
Branch: 1 branch
BranchTrueFalseTotal
if substr($raw, 0, 1) eq "\0" 9 179 188
4872 179 my $row = $self->_unpack_record($sch, $raw);
4873 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
4874 }
4875 35 _unlock(\*FH);
4876 35 close FH;
4877 35 my @results = group_and_aggregate([ @raw ], $col_specs, $gb, $having);
4878 35 ▶ if (@$ob) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$ob) 10 25 35
4879 @results = sort {
4880 10 my($ra, $rb) = ($a, $b);
4881 25 for my $o (@$ob) {
4882 25 my($e, $dir) = @$o;
4883 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
4884 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
4885 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
4886 25 ▶ $c = -$c if lc($dir) eq 'desc';
Branch: 1 branch
BranchTrueFalseTotal
if lc $dir eq "desc" 0 25 25
4887 25 ▶ return $c if $c;
Branch: 1 branch
BranchTrueFalseTotal
if $c 25 0 25
4888 }
4889 0
4890 } @results
4891 }
4892 35 ▶ $offset = 0 unless defined $offset;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $offset 35 0 35
4893 35 ▶ @results = splice(@results, $offset) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 0 35 35
4894 35 ▶ if (defined $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $limit) 0 35 35
4895 0 my $l = $limit - 1;
4896 0 ▶ $l = $#results if $l>$#results;
Branch: 1 branch
BranchTrueFalseTotal
if $l > $#results 0 0 0
4897 0 @results = @results[0..$l];
4898 }
4899 35 return{ type=>'rows', data=>[ @results ] };
4900 }
4901  
4902 # Group @$rows by the expressions in @$gb (an empty list means one group
4903 # holding every row), evaluate @$col_specs for each group and drop the
4904 # groups rejected by $having. Returns the result rows. The table-backed
4905 # SELECT path and the derived-table path share this, which is why it takes
4906 # rows rather than reading them itself.
4907 47 ▶sub group_and_aggregate {
Subroutine group_and_aggregate: called CC=12 SCAR=24.9
Pod undocumented
4908 47 my($rows, $col_specs, $gb, $having) = @_;
4909 47 ▶ $gb = [] unless defined $gb;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $gb 0 47 47
4910 47 ▶ $having = '' unless defined $having;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $having 0 47 47
4911 47 my %gr;
4912 my @go;
4913 47 ▶ if (@$gb) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$gb) { } 16 31 47
4914 16 for my $row (@$rows) {
4915 91 ▶ my $k = join("\x00", map { my $v = eval_expr($_, $row); defined($v) ? $v : '' } @$gb);
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 91 0 91
4916 91 ▶ push @go, $k unless exists $gr{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $gr{$k} 40 51 91
4917 91 push @{$gr{$k}}, $row;
4918 }
4919 }
4920 else {
4921 31 @go = ('__all__');
4922 31 $gr{__all__} = [ @$rows ];
4923 }
4924 47 my @results;
4925 47 for my $gk (@go) {
4926 71 my $grp = $gr{$gk};
4927 71 ▶ my $rep = defined($grp->[0]) ? $grp->[0] : {};
Branch: 1 branch
BranchTrueFalseTotal
defined $grp->[0] ? : 69 2 71
4928 71 my %out;
4929 71 $out{$_->[1]} = eval_agg($_->[0], $grp, $rep) for @$col_specs;
4930 71 ▶ if ($having ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($having ne "") 9 62 71
4931 9 my $h = $having;
4932 9 my $cnt = scalar @$grp;
4933 9 $h =~ s/COUNT\s*\(\s*\*\s*\)/$cnt/gsi;
4934 9 $h =~ s/\b(SUM|AVG|MIN|MAX|COUNT)\s*\(([^)]+)\)/eval_agg("$1($2)", $grp, $rep)/geis;
4935 9 ▶ next unless where_sub($h)->({ %out });
Branch: 1 branch
BranchTrueFalseTotal
unless where_sub($h)->({%out}) 3 6 9
4936 }
4937 68 push @results, { %out };
4938 }
4939 47 return @results;
4940 }
4941  
4942 152 ▶sub eval_agg {
Subroutine eval_agg: called CC=20 SCAR=30.5
Pod undocumented
4943 152 my($expr, $grp, $rep) = @_;
4944 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
4945 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
4946 2 my $e = $1;
4947 2 my %s;
4948 2 for my $r (@$grp) {
4949 9 my $vv = eval_expr($e, $r);
4950 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
4951 8 $s{$vv}++;
4952 }
4953 2 return scalar keys %s;
4954 }
4955 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
4956 43 my($fn, $inner) = (uc($1), $2);
4957 43 $inner =~ s/^\s+|\s+$//g;
4958 43 ▶ my @vals = grep { defined($_) && ($_ ne '') } map { eval_expr($inner, $_) } @$grp;
Condition66%2/3
defined $_ && $_ ne ''
!ll&&!rl&&r
01122
MC/DC50%1/2
defined $_ && $_ ne ''
defined $_ $_ ne ''
Truth table66%2/3
A && B
A= defined $_B= $_ ne ''
ABresult
0X0
100
111
4959 43 ▶ return 0 unless @vals;
Branch: 1 branch
BranchTrueFalseTotal
unless @vals 0 43 43
4960 43 ▶ return scalar @vals if $fn eq 'COUNT';
Branch: 1 branch
BranchTrueFalseTotal
if $fn eq "COUNT" 1 42 43
4961 42 ▶ if ($fn eq 'SUM') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "SUM") 19 23 42
4962 19 my $s = 0;
4963 19 $s += $_ for @vals;
4964 19 return $s;
4965 }
4966 23 ▶ if ($fn eq 'AVG') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "AVG") 9 14 23
4967 9 my $s = 0;
4968 9 $s += $_ for @vals;
4969 9 return $s / @vals;
4970 }
4971 14 ▶ if ($fn eq 'MIN') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "MIN") 5 9 14
4972 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
4973 }
4974 9 ▶ if ($fn eq 'MAX') {
Branch: 1 branch
BranchTrueFalseTotal
if ($fn eq "MAX") 9 0 9
4975 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
4976 }
4977 }
4978 50 return eval_expr($expr, $rep);
4979 }
4980  
4981 # =============================================================================
4982 # UNION / UNION ALL
4983 # =============================================================================
4984 732 ▶sub split_union {
Subroutine split_union: called CC=47 SCAR=39.8
Pod undocumented
4985 732 my($sql) = @_;
4986 732 my @parts;
4987 732 my $cur = '';
4988 732 my $d = 0;
4989 732 my $in_q = 0;
4990 732 my $i = 0;
4991 732 my $len = length($sql);
4992 732 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 31880 732 32612
4993 31880 my $ch = substr($sql, $i, 1);
4994 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
4995 134 $in_q = 1;
4996 134 $cur .= $ch;
4997 }
4998 ▶ 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
4999 134 $in_q = 0;
5000 134 $cur .= $ch;
5001 }
5002 elsif ($in_q) {
5003 468 $cur .= $ch;
5004 }
5005 elsif ($ch eq '(') {
5006 152 $d++;
5007 152 $cur .= $ch;
5008 }
5009 elsif ($ch eq ')') {
5010 152 $d--;
5011 152 $cur .= $ch;
5012 }
5013 ▶ 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
5014 && (($i == 0) || (substr($sql, $i-1, 1) =~ /\s/))) {
5015 # Detect UNION / INTERSECT / EXCEPT set operators
5016 6469 my $kw = '';
5017 6469 my $klen = 0;
5018 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
5019 && ($i+5 < $len) && (substr($sql, $i+5, 1) =~ /[\s(]/)) {
5020 8 $kw = 'UNION'; $klen = 5;
5021 }
5022 ▶ 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
5023 && ($i+9 < $len) && (substr($sql, $i+9, 1) =~ /[\s(]/)) {
5024 18 $kw = 'INTERSECT'; $klen = 9;
5025 }
5026 ▶ 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
5027 && ($i+6 < $len) && (substr($sql, $i+6, 1) =~ /[\s(]/)) {
5028 13 $kw = 'EXCEPT'; $klen = 6;
5029 }
5030 6469 ▶ if ($klen) {
Branch: 1 branch
BranchTrueFalseTotal
if ($klen) { } 39 6430 6469
5031 39 push @parts, $cur;
5032 39 $cur = '';
5033 39 $i += $klen;
5034 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
5035 # UNION ALL / INTERSECT ALL / EXCEPT ALL
5036 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
5037 && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL')
5038 && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) {
5039 4 push @parts, 'UNION_ALL';
5040 4 $i += 3;
5041 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
5042 }
5043 ▶ 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
5044 && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL')
5045 && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) {
5046 2 push @parts, 'INTERSECT_ALL';
5047 2 $i += 3;
5048 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
5049 }
5050 ▶ 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
5051 && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL')
5052 && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) {
5053 3 push @parts, 'EXCEPT_ALL';
5054 3 $i += 3;
5055 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
5056 }
5057 else {
5058 30 push @parts, $kw; # bare UNION / INTERSECT / EXCEPT
5059 }
5060 39 next;
5061 }
5062 else {
5063 6430 $cur .= $ch;
5064 }
5065 }
5066 else {
5067 24371 $cur .= $ch;
5068 }
5069 31841 $i++;
5070 }
5071 732 ▶ push @parts, $cur if $cur =~ /\S/;
Branch: 1 branch
BranchTrueFalseTotal
if $cur =~ /\S/ 732 0 732
5072 732 return @parts;
5073 }
5074  
5075 # Column order of one branch of a set operation, as a list of result-row
5076 # hash keys in select-list order.
5077 77 ▶sub _branch_col_order {
Subroutine _branch_col_order: called CC=1 SCAR=0.0
5078 77 my($self, $sql, $data) = @_;
5079 77 return [ DB::Handy::Statement::_col_order_from_sql(undef, $sql, $data, $self) ];
5080 }
5081  
5082 38 ▶sub exec_union {
Subroutine exec_union: called CC=37 SCAR=36.2
Pod undocumented
5083 38 my($self, $parts) = @_;
5084 38 my @p = @$parts;
5085 38 my $first = shift @p;
5086 38 my $r0 = $self->execute($first);
5087 38 ▶ return $r0 if $r0->{type} eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $r0->{"type"} eq "error" 0 38 38
5088 38 my @rows = @{$r0->{data}};
5089  
5090 # A result row is a hash keyed by column name, and SQL lines the branches
5091 # of a set operation up by *position*, taking the result column names from
5092 # the first branch. Until 1.09 the branches were merged as they came, so
5093 # "SELECT x FROM a UNION ALL SELECT p FROM b" produced rows keyed 'p' for
5094 # the second branch; every value read under the name 'x' was then NULL.
5095 # The column order of each later branch is therefore mapped onto the
5096 # first branch's names before the rows are combined.
5097 38 my $base = $self->_branch_col_order($first, \@rows);
5098  
5099 38 ▶ while (@p >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@p >= 2) 39 37 76
5100 39 my $sep = shift @p;
5101 39 my $q = shift @p;
5102 39 my $r = $self->execute($q);
5103 39 ▶ return $r if $r->{type} eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"type"} eq "error" 0 39 39
5104 39 my @rhs = @{$r->{data}};
5105 39 my $rord = $self->_branch_col_order($q, \@rhs);
5106 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
5107 39 ▶ if (@$base != @$rord) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$base != @$rord) 1 38 39
5108 1 return { type=>'error', message=>
5109 "Each SELECT of a set operation must return the same "
5110 . "number of columns (" . scalar(@$base) . " and "
5111 . scalar(@$rord) . ")" };
5112 }
5113 38 ▶ if (join("\x00", @$base) ne join("\x00", @$rord)) {
Branch: 1 branch
BranchTrueFalseTotal
if (join("\0", @$base) ne join("\0", @$rord)) 5 33 38
5114 5 my @mapped;
5115 5 for my $row (@rhs) {
5116 15 my %n;
5117 15 for my $i (0 .. $#$base) {
5118 18 $n{ $base->[$i] } = $row->{ $rord->[$i] };
5119 }
5120 15 push @mapped, { %n };
5121 }
5122 5 @rhs = @mapped;
5123 }
5124 }
5125 # Build a key string for each row for set operations
5126 270 ▶ my $_key = sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
5127 270 my($row) = @_;
5128 270 ▶ join("\x00", map { defined($row->{$_}) ? $row->{$_} : "\x01" } sort keys %$row);
Branch: 1 branch
BranchTrueFalseTotal
defined $row->{$_} ? : 276 0 276
5129 38 };
5130 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
5131 # UNION: combine then deduplicate
5132 3 push @rows, @rhs;
5133 3 my %s; my @d;
5134 3 for my $row (@rows) {
5135 20 ▶ push @d, $row unless $s{$_key->($row)}++;
Branch: 1 branch
BranchTrueFalseTotal
unless $s{&$_key($row)}++ 15 5 20
5136 }
5137 3 @rows = @d;
5138 }
5139 elsif ($sep eq 'UNION_ALL') {
5140 # UNION ALL: combine without deduplication
5141 4 push @rows, @rhs;
5142 }
5143 elsif ($sep eq 'INTERSECT') {
5144 # INTERSECT: keep only rows present in both (deduplicated)
5145 16 my %in_rhs;
5146 16 for my $row (@rhs) { $in_rhs{$_key->($row)} = 1 }
5147 16 my %seen; my @d;
5148 16 for my $row (@rows) {
5149 65 my $k = $_key->($row);
5150 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
5151 }
5152 16 @rows = @d;
5153 }
5154 elsif ($sep eq 'INTERSECT_ALL') {
5155 # INTERSECT ALL: keep rows present in both (with multiplicity)
5156 2 my %rhs_cnt;
5157 2 for my $row (@rhs) { $rhs_cnt{$_key->($row)}++ }
5158 2 my %used; my @d;
5159 2 for my $row (@rows) {
5160 8 my $k = $_key->($row);
5161 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
5162 3 push @d, $row;
5163 3 $used{$k}++;
5164 }
5165 }
5166 2 @rows = @d;
5167 }
5168 elsif ($sep eq 'EXCEPT') {
5169 # EXCEPT: remove rows that appear in rhs (deduplicated)
5170 10 my %in_rhs;
5171 10 for my $row (@rhs) { $in_rhs{$_key->($row)} = 1 }
5172 10 my %seen; my @d;
5173 10 for my $row (@rows) {
5174 37 my $k = $_key->($row);
5175 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
5176 }
5177 10 @rows = @d;
5178 }
5179 elsif ($sep eq 'EXCEPT_ALL') {
5180 # EXCEPT ALL: remove rows with multiplicity
5181 3 my %rhs_cnt;
5182 3 for my $row (@rhs) { $rhs_cnt{$_key->($row)}++ }
5183 3 my %removed; my @d;
5184 3 for my $row (@rows) {
5185 14 my $k = $_key->($row);
5186 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
5187 6 $removed{$k}++;
5188 }
5189 else {
5190 8 push @d, $row;
5191 }
5192 }
5193 3 @rows = @d;
5194 }
5195 }
5196 37 return { type=>'rows', data=>[ @rows ] };
5197 }
5198  
5199 # =============================================================================
5200 # UPDATE with expression SET
5201 # =============================================================================
5202 41 ▶sub parse_set_exprs {
Subroutine parse_set_exprs: called CC=3 SCAR=11.0
Pod undocumented
5203 41 my($str) = @_;
5204 41 my %set;
5205 41 for my $part (args($str)) {
5206 43 $part =~ s/^\s+|\s+$//g;
5207 43 ▶ $set{$1} = $2 if $part =~ /^(\w+)\s*=\s*(.+)$/s;
Branch: 1 branch
BranchTrueFalseTotal
if $part =~ /^(\w+)\s*=\s*(.+)$/s 43 0 43
5208 }
5209 41 return %set;
5210 }
5211  
5212 41 ▶sub update {
Subroutine update: called CC=47 SCAR=40.4
Pod undocumented
5213 41 my($self, $table, $set_exprs, $ws) = @_;
5214 41 ▶ return $self->_err("No database selected") unless $self->{db_name};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"db_name"} 0 41 41
5215 41 ▶ my $sch = $self->_load_schema($table) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sch = $self->_load_schema($table) or return undef 41 0 41
5216 41 my $dat = $self->_file($table, 'dat');
5217 41 my $rs = $sch->{recsize};
5218 41 my $n = 0;
5219 41 local *FH;
5220 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: $!") 41 0 41
5221 41 binmode FH;
5222 41 _autoflush(\*FH);
5223 41 _lock_ex(\*FH);
5224 41 seek(FH, 0, 0);
5225 41 my $pos = 0;
5226 41 my $rno = 0;
5227 41 while (1) {
5228 168 seek(FH, $pos, 0);
5229 168 my $raw = '';
5230 168 my $x = read(FH, $raw, $rs);
5231 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
5232 140 ▶ if (substr($raw, 0, 1) ne RECORD_DELETED) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($raw, 0, 1) ne "\0") 139 1 140
5233 139 my $row = $self->_unpack_record($sch, $raw);
5234 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
5235 51 my %old;
5236 51 for my $ix (values %{$sch->{indexes}}) {
5237 $old{$ix->{name}} = $row->{$ix->{col}}
5238 14 }
5239 51 my %orig = %$row;
5240 51 $row->{$_} = eval_expr($set_exprs->{$_}, { %orig }) for keys %$set_exprs;
5241 51 for my $ix (values %{$sch->{indexes}}) {
5242 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
5243 5 my $nv = $row->{$ix->{col}};
5244 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
5245 5 my $ep = $self->_idx_lookup_exact($table, $ix, $nv);
5246 5 ▶ if ($ep >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ep >= 0) 5 0 5
5247 5 my $ef = $self->_idx_file($table, $ix->{name});
5248 5 my $es = $ix->{keysize} + REC_NO_SIZE;
5249 5 local *IF_FH;
5250 5 ▶ open(IF_FH, "< $ef") or next;
Branch: 1 branch
BranchTrueFalseTotal
open IF_FH, "< $ef" or next 5 0 5
5251 5 binmode IF_FH;
5252 5 seek(IF_FH, IDX_MAGIC_LEN + $ep * $es + $ix->{keysize}, 0);
5253 5 my $rn = '';
5254 5 read(IF_FH, $rn, REC_NO_SIZE);
5255 5 close IF_FH;
5256 5 ▶ if (unpack('N', $rn) != $rno) {
Branch: 1 branch
BranchTrueFalseTotal
if (unpack("N", $rn) != $rno) 3 2 5
5257 3 _unlock(\*FH);
5258 3 close FH;
5259 3 return $self->_err("UNIQUE constraint violated on '$ix->{name}'");
5260 }
5261 }
5262 }
5263  
5264 # NOT NULL constraint check on UPDATE
5265 48 ▶ for my $cn (keys %{$sch->{notnull} || {}}) {
Condition50%1/2
$sch->{'notnull'} || {}
l!l
480
MC/DC0%0/1
$sch->{'notnull'} || {}
$sch->{'notnull'}
Truth table50%1/2
A
A= $sch->{'notnull'}
Aresult
11
00
5266 12 ▶ next unless exists $set_exprs->{$cn};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $set_exprs->{$cn} 11 1 12
5267 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
5268 1 _unlock(\*FH);
5269 1 close FH;
5270 1 return $self->_err("NOT NULL constraint violated on column '$cn'");
5271 }
5272 }
5273 # CHECK constraint check on UPDATE
5274 47 ▶ for my $cn (keys %{$sch->{checks} || {}}) {
Condition50%1/2
$sch->{'checks'} || {}
l!l
470
MC/DC0%0/1
$sch->{'checks'} || {}
$sch->{'checks'}
Truth table50%1/2
A
A= $sch->{'checks'}
Aresult
11
00
5275 17 ▶ next unless exists $set_exprs->{$cn};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $set_exprs->{$cn} 6 11 17
5276 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
5277 11 ▶ unless (eval_bool($sch->{checks}{$cn}, $row)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval_bool($sch->{"checks"}{$cn}, $row)) 6 5 11
5278 6 _unlock(\*FH);
5279 6 close FH;
5280 6 return $self->_err("CHECK constraint failed on column '$cn'");
5281 }
5282 }
5283 # VARCHAR / CHAR length check on UPDATE
5284 41 for my $col (@{$sch->{cols}}) {
5285 123 my $cn = $col->{name};
5286 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
5287 40 ▶ next unless exists $set_exprs->{$cn};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $set_exprs->{$cn} 28 12 40
5288 12 ▶ my $decl = defined($col->{decl}) ? $col->{decl} : $col->{size};
Branch: 1 branch
BranchTrueFalseTotal
defined $col->{'decl'} ? : 12 0 12
5289 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
5290 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
5291 12 ▶ if (length($row->{$cn}) > $decl) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $row->{$cn} > $decl) 1 11 12
5292 1 _unlock(\*FH);
5293 1 close FH;
5294 return $self->_err(
5295 "Value too long for column '$cn': "
5296 . "declared $col->{type}($decl), got "
5297 1 . length($row->{$cn}) . " bytes"
5298 );
5299 }
5300 }
5301 # Type check on UPDATE: INT range and DATE validity.
5302 40 for my $col (@{$sch->{cols}}) {
5303 118 ▶ next unless exists $set_exprs->{$col->{name}};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$set_exprs{$col->{"name"}} 76 42 118
5304 42 my $msg = _type_error($col, $row->{$col->{name}});
5305 42 ▶ next unless defined $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $msg 40 2 42
5306 2 _unlock(\*FH);
5307 2 close FH;
5308 2 return $self->_err($msg);
5309 }
5310 38 my $p = $self->_pack_record($sch, $row);
5311 38 seek(FH, $pos, 0);
5312 38 ▶ unless (print FH $p) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print FH $p) 0 38 38
5313 0 my $e = $!;
5314 0 _unlock(\*FH);
5315 0 close FH;
5316 0 return $self->_err("Cannot write record: $e");
5317 }
5318 38 $n++;
5319 38 for my $ix (values %{$sch->{indexes}}) {
5320 9 ▶ next unless exists $set_exprs->{$ix->{col}};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$set_exprs{$ix->{"col"}} 4 5 9
5321 5 $self->_idx_delete($table, $ix, $old{$ix->{name}}, $rno);
5322 5 $self->_idx_insert($table, $ix, $row->{$ix->{col}}, $rno);
5323 }
5324 }
5325 }
5326 127 $pos += $rs;
5327 127 $rno++;
5328 }
5329 28 _unlock(\*FH);
5330 28 ▶ unless (close FH) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close FH) 0 28 28
5331 0 return $self->_err("Cannot flush dat: $!");
5332 }
5333 28 return $n;
5334 }
5335  
5336 ###############################################################################
5337 # DBI-like API -- DB::Handy::Connection / DB::Handy::Statement
5338 #
5339 # A standalone implementation with a DBI-inspired interface.
5340 #
5341 # Usage:
5342 # my $dbh = DB::Handy->connect("./data", "mydb");
5343 # my $sth = $dbh->prepare("SELECT * FROM emp WHERE id = ?");
5344 # $sth->execute(1);
5345 # while (my $row = $sth->fetchrow_hashref) { ... }
5346 # $sth->finish;
5347 # $dbh->disconnect;
5348 ###############################################################################
5349  
5350 ###############################################################################
5351 # DB::Handy::Connection -- database connection handle (like $dbh)
5352 ###############################################################################
5353 package DB::Handy::Connection;
5354 24 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
5355 24 $VERSION = '1.10'; # keep in step with $DB::Handy::VERSION (literal so
5356 24 $VERSION = $VERSION; # that PAUSE and Module::Metadata can parse it)
5357  
5358 24 ▶use vars qw($errstr);
Subroutine BEGIN: called CC=1 SCAR=0.0
5359 24 $errstr = '';
5360  
5361 # new($base_dir, $database, \%opts)
5362 48 ▶sub new {
Subroutine new: called CC=17 SCAR=33.0
5363 48 my($class, $base_dir, $database, $opts) = @_;
5364 48 ▶ $opts = {} unless ref($opts) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $opts eq "HASH" 0 48 48
5365  
5366 # DBI code often opens a transaction by connecting with AutoCommit => 0.
5367 # There are no transactions here, so accepting that silently would leave
5368 # the caller believing its writes were being batched.
5369 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
5370 2 $errstr = "AutoCommit cannot be turned off: DB::Handy has no transactions";
5371 2 ▶ if ($opts->{RaiseError}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"RaiseError"}) 0 2 2
5372 0 die "DB::Handy connect failed: $errstr\n";
5373 }
5374 2 ▶ warn "DB::Handy: $errstr\n" if $opts->{PrintError};
Branch: 1 branch
BranchTrueFalseTotal
if $opts->{"PrintError"} 0 2 2
5375 2 return undef;
5376 }
5377 46 my $engine = DB::Handy->new(base_dir => $base_dir);
5378 46 ▶ unless (defined $engine) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $engine) 0 46 46
5379 0 $errstr = $DB::Handy::errstr;
5380 0 ▶ if ($opts->{RaiseError}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"RaiseError"}) 0 0 0
5381 0 die "DB::Handy connect failed: $errstr\n";
5382 }
5383 0 return undef;
5384 }
5385 my $self = {
5386 _engine => $engine,
5387 _database => $database || '',
5388 AutoCommit => 1,
5389 RaiseError => $opts->{RaiseError} || 0,
5390 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
5391 errstr => '',
5392 err => 0,
5393 };
5394 46 bless $self, $class;
5395 46 ▶ if ($database && (!defined($opts->{AutoUse}) || $opts->{AutoUse})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($database and !defined($opts->{"AutoUse"}) || $opts->{"AutoUse"}) 45 1 46
Condition66%4/6
$database and !defined($opts->{"AutoUse"}) || $opts->{"AutoUse"}
!ll&&!rl&&r
0145
not defined $opts->{"AutoUse"} or $opts->{"AutoUse"}
l!l&&r!l&&!r
4501
MC/DC33%1/3
$database and !defined($opts->{"AutoUse"}) || $opts->{"AutoUse"}
$database not defined $opts->{"AutoUse"} $opts->{"AutoUse"}
Truth table50%2/4
A and not(B) or C
A= $databaseB= not defined $opts->{"AutoUse"}C= $opts->{"AutoUse"}
ABCresult
0XX0
1000
11X1
1011
5396 45 my $res = $engine->execute("USE $database");
5397 45 ▶ if ($res->{type} eq 'error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "error") 7 38 45
5398 7 $engine->execute("CREATE DATABASE $database");
5399 7 $res = $engine->execute("USE $database");
5400 }
5401 45 ▶ if ($res->{type} eq 'error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "error") 0 45 45
5402 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
5403 0 return undef;
5404 }
5405 }
5406 46 return $self;
5407 }
5408  
5409 # connect($dsn_or_dir, $database, \%opts)
5410 # Also accepts DSN string: "base_dir=./data;database=mydb"
5411 48 ▶sub connect {
Subroutine connect: called CC=10 SCAR=24.3
5412 48 my($class, $dsn, $database, $opts) = @_;
5413 48 my $base_dir;
5414 48 ▶ if (defined($dsn)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dsn) 48 0 48
5415 # Strip optional dbi:Handy: prefix for DBI-style DSN
5416 48 $dsn =~ s/^dbi\s*:\s*Handy\s*:\s*//i;
5417 }
5418 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
5419 7 my %p = map { split /=/, $_, 2 } split /;/, $dsn;
5420 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
5421 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
5422 }
5423 else {
5424 41 ▶ $base_dir = defined($dsn) ? $dsn : '.';
Branch: 1 branch
BranchTrueFalseTotal
defined $dsn ? : 41 0 41
5425 }
5426 48 ▶ $opts = {} unless ref($opts) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $opts eq "HASH" 40 8 48
5427 48 return DB::Handy::Connection->new($base_dir, $database, $opts);
5428 }
5429  
5430 # do($sql, @bind) -- shortcut for prepare+execute (useful for DDL/DML)
5431 198 ▶sub do {
Subroutine do: called CC=2 SCAR=7.1
5432 198 my($self, $sql, @bind) = @_;
5433 198 ▶ my $sth = $self->prepare($sql) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->prepare($sql) or return undef 198 0 198
5434 198 return $sth->execute(@bind);
5435 }
5436  
5437 # prepare($sql) -- returns a statement handle
5438 461 ▶sub prepare {
Subroutine prepare: called CC=3 SCAR=13.5
5439 461 my($self, $sql) = @_;
5440 461 $self->_clear_err;
5441 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
5442 0 $self->_set_err("prepare: empty SQL");
5443 0 return undef;
5444 }
5445 461 return DB::Handy::Statement->new($self, $sql);
5446 }
5447  
5448 # selectall_arrayref($sql, \%attr, @bind)
5449 # attr: Slice=>{} for array of hashrefs, Slice=>[] (default) for array of arrayrefs
5450 163 ▶sub selectall_arrayref {
Subroutine selectall_arrayref: called CC=4 SCAR=13.9
5451 163 my($self, $sql, $attr, @bind) = @_;
5452 163 ▶ $attr = {} unless ref($attr) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $attr eq "HASH" 96 67 163
5453 163 ▶ my $sth = $self->prepare($sql) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->prepare($sql) or return undef 163 0 163
5454 163 ▶ $sth->execute(@bind) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@bind) or return undef 133 29 162
5455 133 return $sth->fetchall_arrayref($attr->{Slice});
5456 }
5457  
5458 # selectall_hashref($sql, $key_col, \%attr, @bind)
5459 2 ▶sub selectall_hashref {
Subroutine selectall_hashref: called CC=3 SCAR=11.0
5460 2 my($self, $sql, $key_col, $attr, @bind) = @_;
5461 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 2 0 2
5462 2 my %h;
5463 2 for my $row (@$rows) {
5464 7 $h{$row->{$key_col}} = $row;
5465 }
5466 2 return { %h };
5467 }
5468  
5469 # selectrow_hashref($sql, \%attr, @bind)
5470 19 ▶sub selectrow_hashref {
Subroutine selectrow_hashref: called CC=3 SCAR=11.2
5471 19 my($self, $sql, $attr, @bind) = @_;
5472 19 ▶ my $sth = $self->prepare($sql) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->prepare($sql) or return undef 19 0 19
5473 19 ▶ $sth->execute(@bind) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@bind) or return undef 19 0 19
5474 19 my $row = $sth->fetchrow_hashref;
5475 19 $sth->finish;
5476 19 return $row;
5477 }
5478  
5479 # selectrow_arrayref($sql, \%attr, @bind)
5480 4 ▶sub selectrow_arrayref {
Subroutine selectrow_arrayref: called CC=3 SCAR=11.2
5481 4 my($self, $sql, $attr, @bind) = @_;
5482 4 ▶ my $sth = $self->prepare($sql) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $sth = $self->prepare($sql) or return undef 4 0 4
5483 4 ▶ $sth->execute(@bind) or return undef;
Branch: 1 branch
BranchTrueFalseTotal
$sth->execute(@bind) or return undef 4 0 4
5484 4 my $row = $sth->fetchrow_arrayref;
5485 4 $sth->finish;
5486 4 return $row;
5487 }
5488  
5489 # quote($val) -- escape a value as a SQL single-quoted literal
5490 9 ▶sub quote {
Subroutine quote: called CC=2 SCAR=6.9
5491 9 my($self, $val) = @_;
5492 9 ▶ return 'NULL' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 2 7 9
5493 7 $val =~ s/'/''/g;
5494 7 return "'$val'";
5495 }
5496  
5497 # last_insert_id() -- row count recorded by the most recent INSERT
5498 # last_insert_id($catalog, $schema, $table, $field)
5499 # Arguments are accepted for DBI compatibility but ignored.
5500 7 ▶sub last_insert_id { return $_[0]->{_last_insert_id} }
Subroutine last_insert_id: called CC=1 SCAR=0.0
5501  
5502 # table_info() -- list of tables [{TABLE_NAME=>...}, ...]
5503 1 ▶sub table_info {
Subroutine table_info: called CC=1 SCAR=0.0
5504 1 my($self) = @_;
5505 1 my @tables = $self->{_engine}->list_tables();
5506 1 return [ map { {TABLE_NAME=>$_, TABLE_TYPE=>'TABLE'} } @tables ];
5507 }
5508  
5509 # column_info($table) -- column metadata [{COLUMN_NAME=>..., DATA_TYPE=>...}, ...]
5510 1 ▶sub column_info {
Subroutine column_info: called CC=3 SCAR=11.3
5511 1 my($self, $table) = @_;
5512 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 1 0 1
5513 1 my $i = 0;
5514 1 return [ map { {
5515 COLUMN_NAME => $_->{name},
5516 DATA_TYPE => $_->{type},
5517 ORDINAL_POSITION => ++$i,
5518 IS_NULLABLE => ($_->{not_null} ? 'NO' : 'YES'),
5519 COLUMN_DEF => $_->{default},
5520 4 ▶ } } @$cols ];
Branch: 1 branch
BranchTrueFalseTotal
$_->{'not_null'} ? : 0 4 4
5521 }
5522  
5523 # disconnect()
5524 43 ▶sub disconnect {
Subroutine disconnect: called CC=1 SCAR=0.0
5525 43 my($self) = @_;
5526 43 $self->{_disconnected} = 1;
5527 43 return 1;
5528 }
5529  
5530 # ping() -- returns 1 if connection is active
5531 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
5532  
5533 # AutoCommit -- always on; transactions are not supported
5534 3 ▶sub AutoCommit { return 1 }
Subroutine AutoCommit: called CC=1 SCAR=0.0
5535  
5536 # begin_work / commit / rollback
5537 # Transactions are not supported. These methods set errstr and return
5538 # undef rather than crashing, consistent with DBI error-handling style.
5539 1 ▶sub begin_work {
Subroutine begin_work: called CC=1 SCAR=0.0
5540 1 my($self) = @_;
5541 1 $self->_set_err(
5542 "Transactions are not supported: DB::Handy always operates in "
5543 . "AutoCommit mode. begin_work/commit/rollback are not available."
5544 );
5545 1 return undef;
5546 }
5547 1 ▶sub commit {
Subroutine commit: called CC=1 SCAR=0.0
5548 1 my($self) = @_;
5549 1 $self->_set_err(
5550 "Transactions are not supported: DB::Handy always operates in "
5551 . "AutoCommit mode. begin_work/commit/rollback are not available."
5552 );
5553 1 return undef;
5554 }
5555 1 ▶sub rollback {
Subroutine rollback: called CC=1 SCAR=0.0
5556 1 my($self) = @_;
5557 1 $self->_set_err(
5558 "Transactions are not supported: DB::Handy always operates in "
5559 . "AutoCommit mode. begin_work/commit/rollback are not available."
5560 );
5561 1 return undef;
5562 }
5563  
5564 # errstr / err accessors
5565 34 ▶sub errstr { return $_[0]->{errstr} }
Subroutine errstr: called CC=1 SCAR=0.0
5566 7 ▶sub err { return $_[0]->{err} }
Subroutine err: called CC=1 SCAR=0.0
5567  
5568 # _clear_err() -- DBI resets err/errstr at the start of every method that
5569 # talks to the database, so that a stale message from an earlier failure
5570 # is never mistaken for the outcome of the call that just succeeded.
5571 921 ▶sub _clear_err {
Subroutine _clear_err: called CC=1 SCAR=0.0
5572 921 my($self) = @_;
5573 921 $self->{errstr} = '';
5574 921 $self->{err} = 0;
5575 921 return;
5576 }
5577  
5578 70 ▶sub _set_err {
Subroutine _set_err: called CC=4 SCAR=13.9
5579 70 my($self, $msg, $code) = @_;
5580 70 ▶ $code = 1 unless defined $code;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code 3 67 70
5581 70 $self->{errstr} = $msg;
5582 70 $self->{err} = $code;
5583 70 $errstr = $msg;
5584 70 ▶ if ($self->{PrintError}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"PrintError"}) 1 69 70
5585 1 warn "DB::Handy: $msg\n";
5586 }
5587 70 ▶ if ($self->{RaiseError}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"RaiseError"}) 3 67 70
5588 3 die "DB::Handy: $msg\n";
5589 }
5590 }
5591  
5592 ###############################################################################
5593 # DB::Handy::Statement -- statement handle (like $sth)
5594 ###############################################################################
5595 package DB::Handy::Statement;
5596 24 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
5597 24 $VERSION = '1.10'; # keep in step with $DB::Handy::VERSION (literal so
5598 24 $VERSION = $VERSION; # that PAUSE and Module::Metadata can parse it)
5599  
5600 24 ▶use vars qw($errstr);
Subroutine BEGIN: called CC=1 SCAR=0.0
5601 24 $errstr = '';
5602  
5603 461 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
5604 461 my($class, $dbh, $sql) = @_;
5605 461 my $self = {
5606 _dbh => $dbh,
5607 _sql => $sql,
5608 _rows => undef,
5609 _cursor => 0,
5610 _executed => 0,
5611 _bind_params => [],
5612 rows => 0,
5613 errstr => '',
5614 err => 0,
5615 NAME => [],
5616 NAME_lc => [],
5617 NAME_uc => [],
5618 NUM_OF_FIELDS => 0,
5619 NUM_OF_PARAMS => _count_placeholders($sql),
5620 Statement => $sql,
5621 };
5622 461 bless $self, $class;
5623 461 return $self;
5624 }
5625  
5626 # Number of ? placeholders, ignoring any that sit inside a string literal
5627 # or a comment. This is the same count execute() will consume.
5628 461 ▶sub _count_placeholders {
Subroutine _count_placeholders: called CC=3 SCAR=11.0
5629 461 my($sql) = @_;
5630 461 my $n = 0;
5631 461 for my $part (DB::Handy::_split_sql_literals(DB::Handy::_strip_sql_comments($sql))) {
5632 674 ▶ next if $part->[0];
Branch: 1 branch
BranchTrueFalseTotal
if $part->[0] 110 564 674
5633 564 $n += ($part->[1] =~ tr/?//);
5634 }
5635 461 return $n;
5636 }
5637  
5638 # execute(@bind_values) -- substitute ? placeholders and run the statement
5639 460 ▶sub execute {
Subroutine execute: called CC=18 SCAR=29.1
5640 460 my($self, @bind) = @_;
5641 460 $self->_clear_err;
5642  
5643 # merge values pre-set via bind_param()
5644 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
5645 2 @bind = @{$self->{_bind_params}};
5646 }
5647  
5648 # DBI refuses a bind list whose length does not match the number of
5649 # placeholders. Without this check a missing value left a bare "?"
5650 # in the statement -- which then matched nothing -- and a surplus
5651 # value was dropped, so either mistake produced a silently wrong
5652 # result instead of an error.
5653 460 my $got = scalar @bind;
5654 460 my $need = $self->{NUM_OF_PARAMS};
5655 460 ▶ if ($got != $need) {
Branch: 1 branch
BranchTrueFalseTotal
if ($got != $need) 3 457 460
5656 3 ▶ $self->_set_err(
Branch: 2 branches
BranchTrueFalseTotal
$got == 1 ? : 1 2 3
$need == 1 ? : 2 1 3
5657 "called with $got bind variable" . (($got == 1) ? '' : 's')
5658 . " when $need " . (($need == 1) ? 'is' : 'are')
5659 . " needed"
5660 );
5661 3 return undef;
5662 }
5663  
5664 # Comments are removed first so that a ? inside one is not mistaken
5665 # for a placeholder; a ? inside a string literal is left alone too.
5666 457 my $sql = DB::Handy::_strip_sql_comments($self->{_sql});
5667  
5668 # substitute ? placeholders with actual values
5669 457 ▶ if (@bind) {
Branch: 1 branch
BranchTrueFalseTotal
if (@bind) 57 400 457
5670 57 my @params = @bind;
5671 57 my $out = '';
5672 57 for my $part (DB::Handy::_split_sql_literals($sql)) {
5673 61 ▶ if ($part->[0]) { $out .= $part->[1]; next }
Branch: 1 branch
BranchTrueFalseTotal
if ($part->[0]) 2 59 61
5674 59 my $chunk = $part->[1];
5675 59 $chunk =~ s/\?/_dbi_quote(shift @params)/ge;
5676 59 $out .= $chunk;
5677 }
5678 57 $sql = $out;
5679 }
5680  
5681 457 my $engine = $self->{_dbh}{_engine};
5682 457 my $res = $engine->execute($sql);
5683  
5684 457 $self->{_result} = $res;
5685 457 $self->{_executed} = 1;
5686  
5687 457 ▶ if ($res->{type} eq 'error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "error") 64 393 457
5688 64 $self->_set_err($res->{message});
5689 61 return undef;
5690 }
5691  
5692 393 ▶ if ($res->{type} eq 'rows') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "rows") 222 171 393
5693 222 my $data = $res->{data};
5694 222 $self->{_rows} = $data;
5695 222 $self->{_cursor} = 0;
5696 222 my $n = scalar @$data;
5697 222 $self->{rows} = $n;
5698 # Determine column order: prefer SELECT list order; for SELECT *
5699 # use schema declaration order; fall back to alphabetical.
5700 222 my @name_order = $self->_col_order_from_sql($sql, $data, $engine);
5701 222 $self->{NAME} = [ @name_order ];
5702 222 $self->{NAME_lc} = [ map { lc $_ } @name_order ];
5703 222 $self->{NAME_uc} = [ map { uc $_ } @name_order ];
5704 222 $self->{NUM_OF_FIELDS} = scalar @name_order;
5705 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
5706 }
5707  
5708 # INSERT / UPDATE / DELETE / DDL
5709 171 ▶ if ($res->{type} eq 'ok') {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->{"type"} eq "ok") 171 0 171
5710 171 my $affected = 0;
5711 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
5712 132 $affected = $1 + 0;
5713 }
5714 171 $self->{rows} = $affected;
5715 171 $self->{_rows} = undef;
5716 171 $self->{NAME} = [];
5717 171 $self->{NAME_lc} = [];
5718 171 $self->{NAME_uc} = [];
5719 171 $self->{NUM_OF_FIELDS} = 0;
5720 171 ▶ if ($sql =~ /^\s*INSERT\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^\s*INSERT\b/i) 117 54 171
5721 117 $self->{_dbh}{_last_insert_id} = $affected;
5722 }
5723 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
5724 }
5725  
5726 # SHOW / DESCRIBE and other statement types
5727 0 ▶ if (ref($res->{data}) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $res->{"data"} eq "ARRAY") 0 0 0
5728 0 $self->{_rows} = $res->{data};
5729 0 $self->{_cursor} = 0;
5730 0 $self->{rows} = scalar @{$res->{data}};
5731 }
5732 0 return '0E0';
5733 }
5734  
5735 # _col_order_from_sql($sql, $data, $engine)
5736 #
5737 # Return column names in the order they should be presented to the caller.
5738 #
5739 # For named SELECT lists (SELECT a, b, c) the order follows the SELECT list,
5740 # including AS aliases (already handled since 1.01).
5741 #
5742 # For SELECT * on a single table the order follows the CREATE TABLE column
5743 # declaration order, obtained from the schema.
5744 #
5745 # For SELECT * on a JOIN the order follows the table appearance order in
5746 # the FROM/JOIN clause, each table's columns in declaration order, returned
5747 # as 'alias.col' qualified names matching the result-row hash keys.
5748 #
5749 # Falls back to alphabetical (sorted keys of the first data row) when the
5750 # schema cannot be resolved or the SQL cannot be parsed.
5751 #
5752 299 ▶sub _col_order_from_sql {
Subroutine _col_order_from_sql: called CC=40 SCAR=38.0
5753 299 my($self, $sql, $data, $engine) = @_;
5754 # Fallback: alphabetical from first row (or empty)
5755 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
5756 299 ▶ return @fallback unless defined $sql;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sql 0 299 299
5757 # Strip leading SELECT keyword
5758 299 my $col_str;
5759 299 ▶ if ($sql =~ /^SELECT\s+(.*?)\s+FROM\b/si) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /^SELECT\s+(.*?)\s+FROM\b/is) { } 299 0 299
5760 299 $col_str = $1;
5761 }
5762 else {
5763 0 return @fallback;
5764 }
5765 299 $col_str =~ s/^DISTINCT\s+//si;
5766 # SELECT * (or alias.*): try to use schema declaration order
5767 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
5768 16 ▶ return @fallback unless defined $engine;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $engine 0 16 16
5769 # Parse FROM clause to get table name and optional alias
5770 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
5771 && $sql !~ /\bJOIN\b/i) {
5772 12 my($tbl, $alias) = ($1, $2);
5773 12 my $sch = $engine->_load_schema($tbl);
5774 12 ▶ return @fallback unless $sch;
Branch: 1 branch
BranchTrueFalseTotal
unless $sch 0 12 12
5775 12 my @names = map { $_->{name} } @{$sch->{cols}};
5776 # Verify names match result keys
5777 12 ▶ if (@$data) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$data) 11 1 12
5778 11 my %keys = map { $_ => 1 } keys %{$data->[0]};
5779 11 ▶ return @fallback if grep { !$keys{$_} } @names;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not $keys{$_};} @names 0 11 11
5780 }
5781 12 return @names;
5782 }
5783 # JOIN: collect tables in FROM/JOIN order, build alias.col names
5784 4 ▶ if ($sql =~ /\bJOIN\b/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sql =~ /\bJOIN\b/i) 4 0 4
5785 4 ▶ return @fallback unless defined $engine;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $engine 0 4 4
5786 4 my @table_aliases;
5787 # Extract first table from FROM
5788 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
5789 4 ▶ push @table_aliases, [ $1, (defined $2 ? $2 : $1) ];
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 4 0 4
5790 }
5791 # Extract subsequent JOIN tables
5792 4 my $rest = $sql;
5793 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
5794 4 ▶ push @table_aliases, [ $1, (defined $2 ? $2 : $1) ];
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 4 0 4
5795 }
5796 4 my @names;
5797 4 for my $ta (@table_aliases) {
5798 8 my($tbl, $alias) = @$ta;
5799 8 my $sch = $engine->_load_schema($tbl);
5800 8 ▶ next unless $sch;
Branch: 1 branch
BranchTrueFalseTotal
unless $sch 0 8 8
5801 8 for my $col (@{$sch->{cols}}) {
5802 22 push @names, "$alias.$col->{name}";
5803 }
5804 }
5805 4 ▶ if (@names) {
Branch: 1 branch
BranchTrueFalseTotal
if (@names) 4 0 4
5806 # Verify names match result keys
5807 4 ▶ if (@$data) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$data) 4 0 4
5808 4 my %keys = map { $_ => 1 } keys %{$data->[0]};
5809 4 ▶ return @fallback if grep { !$keys{$_} } @names;
Branch: 1 branch
BranchTrueFalseTotal
if grep {not $keys{$_};} @names 2 2 4
5810 }
5811 2 return @names;
5812 }
5813 0 return @fallback;
5814 }
5815 0 return @fallback;
5816 }
5817 # Split on commas (not inside parentheses)
5818 283 my @parts;
5819 283 my($cur, $depth) = ('', 0);
5820 283 for my $ch (split //, $col_str) {
5821 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
5822 40 elsif ($ch eq ')') { $depth--; $cur .= $ch }
5823 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
5824 1430 else { $cur .= $ch }
5825 }
5826 283 ▶ push @parts, $cur if length $cur;
Branch: 1 branch
BranchTrueFalseTotal
if length $cur 283 0 283
5827 283 my(@names, @alt);
5828 283 for my $part (@parts) {
5829 376 $part =~ s/^\s+|\s+$//g;
5830 # explicit alias: expr AS alias
5831 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
5832 25 push @names, $1;
5833 25 push @alt, undef;
5834 }
5835 # qualified alias.col -> keep as 'alias.col' (JOIN result key format)
5836 elsif ($part =~ /^(\w+)\.(\w+)$/) {
5837 50 push @names, "$1.$2";
5838  
5839 # An aggregate query over a JOIN keys its output rows by the bare
5840 # column name, so 'a.y' has to be able to resolve to 'y'. Without
5841 # this the whole list was rejected below and the alphabetical
5842 # fallback took over, which put the columns of
5843 # "SELECT a.y, COUNT(*) ... GROUP BY a.y" in the order
5844 # COUNT(*), y.
5845 50 push @alt, $2;
5846 }
5847 # bare column name
5848 elsif ($part =~ /^(\w+)$/) {
5849 280 push @names, $1;
5850 280 push @alt, undef;
5851 }
5852 # complex expression without alias -> use the expression text as key
5853 else {
5854 21 push @names, $part;
5855 21 push @alt, undef;
5856 }
5857 }
5858 # Verify that every parsed name exists as a key in the result
5859 # (guards against mis-parses; also handles 0-row results)
5860 283 ▶ if (@$data) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$data) 275 8 283
5861 275 my %keys = map { $_ => 1 } keys %{$data->[0]};
5862 275 for my $i (0 .. $#names) {
5863 367 ▶ next if $keys{$names[$i]};
Branch: 1 branch
BranchTrueFalseTotal
if $keys{$names[$i]} 364 3 367
5864 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
5865 3 $names[$i] = $alt[$i];
5866 3 next;
5867 }
5868 0 return @fallback;
5869 }
5870 }
5871 283 return @names;
5872 }
5873  
5874 # fetchrow_hashref -- return next row as hashref (undef at EOF)
5875 540 ▶sub fetchrow_hashref {
Subroutine fetchrow_hashref: called CC=3 SCAR=11.0
5876 540 my($self) = @_;
5877 540 ▶ return undef unless defined $self->{_rows};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_rows"} 1 539 540
5878 539 ▶ return undef if $self->{_cursor} >= scalar @{$self->{_rows}};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_cursor"} >= scalar @{$self->{"_rows"};} 155 384 539
5879 384 my $row = $self->{_rows}[ $self->{_cursor}++ ];
5880 384 return { %$row };
5881 }
5882  
5883 # fetchrow_arrayref -- return next row as arrayref (columns in NAME order)
5884 395 ▶sub fetchrow_arrayref {
Subroutine fetchrow_arrayref: called CC=3 SCAR=11.0
5885 395 my($self) = @_;
5886 395 ▶ my $href = $self->fetchrow_hashref or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $href = $self->fetchrow_hashref or return undef 269 126 395
5887 269 ▶ my @cols = @{$self->{NAME}} ? @{$self->{NAME}} : sort keys %$href;
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{'NAME'};} ? : 269 0 269
5888 269 return [ map { $href->{$_} } @cols ];
5889 }
5890  
5891 # fetchrow_array -- return next row as a list
5892 13 ▶sub fetchrow_array {
Subroutine fetchrow_array: called CC=2 SCAR=6.9
5893 13 my($self) = @_;
5894 13 ▶ my $aref = $self->fetchrow_arrayref or return ();
Branch: 1 branch
BranchTrueFalseTotal
my $aref = $self->fetchrow_arrayref or return () 11 2 13
5895 11 return @$aref;
5896 }
5897  
5898 # fetch -- alias for fetchrow_arrayref
5899 0 ▶sub fetch { return $_[0]->fetchrow_arrayref }
Subroutine fetch: not called CC=1 SCAR=6.9
5900  
5901 # fetchall_arrayref([$slice])
5902 # $slice = {} -> [{col=>val,...}, ...]
5903 # $slice = [] -> [[val,...], ...] (default)
5904 138 ▶sub fetchall_arrayref {
Subroutine fetchall_arrayref: called CC=5 SCAR=16.1
5905 138 my($self, $slice) = @_;
5906 138 ▶ return undef unless defined $self->{_rows};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $self->{"_rows"} 0 138 138
5907 138 my @all;
5908 138 ▶ if (ref($slice) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $slice eq 'HASH') { } 18 120 138
5909 18 ▶ while (my $row = $self->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $self->fetchrow_hashref) 47 18 65
5910 47 push @all, $row;
5911 }
5912 }
5913 else {
5914 120 ▶ while (my $row = $self->fetchrow_arrayref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $self->fetchrow_arrayref) 233 120 353
5915 233 push @all, $row;
5916 }
5917 }
5918 138 return [ @all ];
5919 }
5920  
5921 # fetchall_hashref($key_col) -- return rows as a hashref keyed by $key_col
5922 2 ▶sub fetchall_hashref {
Subroutine fetchall_hashref: called CC=2 SCAR=6.9
5923 2 my($self, $key_col) = @_;
5924 2 my %h;
5925 2 ▶ while (my $row = $self->fetchrow_hashref) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $row = $self->fetchrow_hashref) 7 2 9
5926 7 $h{$row->{$key_col}} = $row;
5927 }
5928 2 return { %h };
5929 }
5930  
5931 # bind_param($pos, $val [, $attr]) -- pre-bind a placeholder by position
5932 2 ▶sub bind_param {
Subroutine bind_param: called CC=1 SCAR=0.0
5933 2 my($self, $pos, $val, $attr) = @_;
5934 2 $self->{_bind_params}[$pos - 1] = $val;
5935 2 return 1;
5936 }
5937  
5938 # finish -- reset cursor and release resources
5939 73 ▶sub finish {
Subroutine finish: called CC=1 SCAR=0.0
5940 73 my($self) = @_;
5941 73 $self->{_rows} = undef;
5942 73 $self->{_cursor} = 0;
5943 73 $self->{_bind_params} = [];
5944 73 return 1;
5945 }
5946  
5947 # rows -- number of rows affected or fetched by the last execute
5948 5 ▶sub rows { return $_[0]->{rows} }
Subroutine rows: called CC=1 SCAR=0.0
5949  
5950 # errstr / err accessors
5951 5 ▶sub errstr { return $_[0]->{errstr} }
Subroutine errstr: called CC=1 SCAR=0.0
5952 2 ▶sub err { return $_[0]->{err} }
Subroutine err: called CC=1 SCAR=0.0
5953  
5954 460 ▶sub _clear_err {
Subroutine _clear_err: called CC=2 SCAR=7.0
5955 460 my($self) = @_;
5956 460 $self->{errstr} = '';
5957 460 $self->{err} = 0;
5958 460 my $dbh = $self->{_dbh};
5959 460 ▶ $dbh->_clear_err if ref($dbh);
Branch: 1 branch
BranchTrueFalseTotal
if ref $dbh 460 0 460
5960 460 return;
5961 }
5962  
5963 67 ▶sub _set_err {
Subroutine _set_err: called CC=3 SCAR=11.2
5964 67 my($self, $msg, $code) = @_;
5965 67 ▶ $code = 1 unless defined $code;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code 67 0 67
5966 67 $self->{errstr} = $msg;
5967 67 $self->{err} = $code;
5968 67 $errstr = $msg;
5969 67 my $dbh = $self->{_dbh};
5970 67 ▶ $dbh->_set_err($msg, $code) if ref($dbh);
Branch: 1 branch
BranchTrueFalseTotal
if ref $dbh 67 0 67
5971 }
5972  
5973 # _dbi_quote($val) -- internal helper for ? placeholder substitution
5974 100 ▶sub _dbi_quote {
Subroutine _dbi_quote: called CC=3 SCAR=11.0
5975 100 my($val) = @_;
5976 100 ▶ return 'NULL' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 100 100
5977 100 ▶ return $val if $val =~ /^-?\d+\.?\d*$/; # numeric: pass through as-is
Branch: 1 branch
BranchTrueFalseTotal
if $val =~ /^-?\d+\.?\d*$/ 59 41 100
5978 41 $val =~ s/'/''/g;
5979 41 return "'$val'";
5980 }
5981  
5982 ###############################################################################
5983 # Add connect() class method to DB::Handy
5984 ###############################################################################
5985 package DB::Handy;
5986  
5987 48 ▶sub connect {
Subroutine connect: called CC=1 SCAR=0.0
Pod documented
5988 48 my($class, $dsn, $database, $opts) = @_;
5989 48 return DB::Handy::Connection->connect($dsn, $database, $opts);
5990 }
5991  
5992 24 1;
5993  
5994 __END__
↑ Summary