| 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 | use 5.00503; # Universal Consensus 1998 for primetools | ||
| 35 | # Perl 5.005_03 compatibility for historical toolchains | ||
| 36 | # use 5.008001; # Lancaster Consensus 2013 for toolchains | ||
| 37 | |||
| 38 | use strict; | ||
| 39 | BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } } | ||
| 40 | use warnings; local $^W = 1; | ||
| 41 | BEGIN { pop @INC if $INC[-1] eq '.' } | ||
| 42 | use Fcntl qw(:flock); | ||
| 43 | use File::Path (); | ||
| 44 | use File::Spec; | ||
| 45 | use POSIX (); | ||
| 46 | |||
| 47 | use vars qw($VERSION $errstr); | ||
| 48 | $VERSION = '1.09'; | ||
| 49 | $VERSION = $VERSION; | ||
| 50 | $errstr = ''; | ||
| 51 | |||
| 52 | ############################################################################### | ||
| 53 | # Constants | ||
| 54 | ############################################################################### | ||
| 55 | use constant RECORD_ACTIVE => "\x01"; | ||
| 56 | use constant RECORD_DELETED => "\x00"; | ||
| 57 | use constant MAX_VARCHAR => 255; | ||
| 58 | use constant INT_MAX => 2147483647; | ||
| 59 | use constant INT_MIN => -2147483648; | ||
| 60 | use constant IDX_MAGIC => "SDBIDX1\n"; | ||
| 61 | use constant IDX_MAGIC_LEN => 8; | ||
| 62 | use constant REC_NO_SIZE => 4; | ||
| 63 | |||
| 64 | my %TYPE_SIZE = ( | ||
| 65 | INT => 4, | ||
| 66 | FLOAT => 8, | ||
| 67 | CHAR => undef, | ||
| 68 | VARCHAR => undef, | ||
| 69 | DATE => 10, | ||
| 70 | ); | ||
| 71 | |||
| 72 | ############################################################################### | ||
| 73 | # Constructor | ||
| 74 | ############################################################################### | ||
| 75 | sub new { | ||
| 76 | my($class, %args) = @_; | ||
| 77 | my $self = { | ||
| 78 | base_dir => ($args{base_dir} || 'simpledbms_data'), | ||
| 79 | db_name => ($args{db_name} || ''), | ||
| 80 | _tables => {}, | ||
| 81 | _locks => {}, | ||
| 82 | }; | ||
| 83 | bless $self, $class; | ||
| 84 | if (($self->{db_name} ne '') && !_valid_name($self->{db_name})) { | ||
| 85 | my $bad = _shown_name($self->{db_name}); | ||
| 86 | $errstr = "Invalid database name '$bad'"; | ||
| 87 | return undef; | ||
| 88 | } | ||
| 89 | unless (-d $self->{base_dir}) { | ||
| 90 | eval { | ||
| 91 | File::Path::mkpath($self->{base_dir}); | ||
| 92 | }; | ||
| 93 | if ($@) { | ||
| 94 | $errstr = "Cannot create base_dir: $@"; | ||
| 95 | return undef; | ||
| 96 | } | ||
| 97 | } | ||
| 98 | return $self; | ||
| 99 | } | ||
| 100 | |||
| 101 | ############################################################################### | ||
| 102 | # Database-level | ||
| 103 | ############################################################################### | ||
| 104 | sub create_database { | ||
| 105 | my($self, $db_name) = @_; | ||
| 106 | unless (_valid_name($db_name)) { | ||
| 107 | my $bad = _shown_name($db_name); | ||
| 108 | $errstr = "Invalid database name '$bad'"; | ||
| 109 | return 0; | ||
| 110 | } | ||
| 111 | my $path = $self->_db_path($db_name); | ||
| 112 | if (-d $path) { | ||
| 113 | $errstr = "Database '$db_name' already exists"; | ||
| 114 | return 0; | ||
| 115 | } | ||
| 116 | eval { | ||
| 117 | File::Path::mkpath($path); | ||
| 118 | }; | ||
| 119 | if ($@) { | ||
| 120 | $errstr = "Cannot create database '$db_name': $@"; | ||
| 121 | return 0; | ||
| 122 | } | ||
| 123 | return 1; | ||
| 124 | } | ||
| 125 | |||
| 126 | sub use_database { | ||
| 127 | my($self, $db_name) = @_; | ||
| 128 | unless (_valid_name($db_name)) { | ||
| 129 | my $bad = _shown_name($db_name); | ||
| 130 | $errstr = "Invalid database name '$bad'"; | ||
| 131 | return 0; | ||
| 132 | } | ||
| 133 | my $path = $self->_db_path($db_name); | ||
| 134 | unless (-d $path) { | ||
| 135 | $errstr = "Database '$db_name' does not exist"; | ||
| 136 | return 0; | ||
| 137 | } | ||
| 138 | $self->{db_name} = $db_name; | ||
| 139 | $self->{_tables} = {}; | ||
| 140 | return 1; | ||
| 141 | } | ||
| 142 | |||
| 143 | sub drop_database { | ||
| 144 | my($self, $db_name) = @_; | ||
| 145 | unless (_valid_name($db_name)) { | ||
| 146 | my $bad = _shown_name($db_name); | ||
| 147 | $errstr = "Invalid database name '$bad'"; | ||
| 148 | return 0; | ||
| 149 | } | ||
| 150 | my $path = $self->_db_path($db_name); | ||
| 151 | unless (-d $path) { | ||
| 152 | $errstr = "Database '$db_name' does not exist"; | ||
| 153 | return 0; | ||
| 154 | } | ||
| 155 | eval { | ||
| 156 | File::Path::rmtree($path); | ||
| 157 | }; | ||
| 158 | if ($@) { | ||
| 159 | $errstr = "Cannot drop database '$db_name': $@"; | ||
| 160 | return 0; | ||
| 161 | } | ||
| 162 | $self->{db_name} = '' if $self->{db_name} eq $db_name; | ||
| 163 | return 1; | ||
| 164 | } | ||
| 165 | |||
| 166 | sub list_databases { | ||
| 167 | my($self) = @_; | ||
| 168 | my $base = $self->{base_dir}; | ||
| 169 | local *DH; | ||
| 170 | opendir(DH, $base) or do { $errstr = "Cannot open base_dir: $!"; return (); }; | ||
| 171 | my @dbs = grep { !/^\./ && -d File::Spec->catdir($base, $_) } readdir(DH); | ||
| 172 | closedir DH; | ||
| 173 | return sort @dbs; | ||
| 174 | } | ||
| 175 | |||
| 176 | ############################################################################### | ||
| 177 | # Table-level | ||
| 178 | ############################################################################### | ||
| 179 | sub create_table { | ||
| 180 | my($self, $table, $columns) = @_; | ||
| 181 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 182 | return $self->_err("Invalid table name '" . _shown_name($table) . "'") | ||
| 183 | unless _valid_name($table); | ||
| 184 | my $sch_file = $self->_file($table, 'sch'); | ||
| 185 | return $self->_err("Table '$table' already exists") if -f $sch_file; | ||
| 186 | |||
| 187 | my @cols; | ||
| 188 | my $rec_size = 1; | ||
| 189 | for my $col (@$columns) { | ||
| 190 | my($name, $type, $size) = @$col; | ||
| 191 | $type = uc($type); | ||
| 192 | return $self->_err("Unknown type '$type'") unless exists $TYPE_SIZE{$type}; | ||
| 193 | my $store; | ||
| 194 | if ($type eq 'CHAR') { | ||
| 195 | return $self->_err("CHAR requires a size") unless $size && ($size > 0); | ||
| 196 | $store = int($size); | ||
| 197 | } | ||
| 198 | elsif ($type eq 'VARCHAR') { | ||
| 199 | $store = MAX_VARCHAR; | ||
| 200 | } | ||
| 201 | else { | ||
| 202 | $store = $TYPE_SIZE{$type}; | ||
| 203 | } | ||
| 204 | $rec_size += $store; | ||
| 205 | # decl is the declared size (from CREATE TABLE); for VARCHAR it may | ||
| 206 | # differ from the physical storage size (MAX_VARCHAR). | ||
| 207 | my $decl = (defined $size && $size > 0) ? int($size) : $store; | ||
| 208 | push @cols, { name=>$name, type=>$type, size=>$store, decl=>$decl }; | ||
| 209 | } | ||
| 210 | |||
| 211 | local *FH; | ||
| 212 | open(FH, "> $sch_file") or return $self->_err("Cannot write schema: $!"); | ||
| 213 | my $ok = print FH "VERSION=1\n"; | ||
| 214 | $ok &&= print FH "RECSIZE=$rec_size\n"; | ||
| 215 | for my $c (@cols) { | ||
| 216 | $ok &&= print FH "COL=$c->{name}:$c->{type}:$c->{size}:$c->{decl}\n"; | ||
| 217 | } | ||
| 218 | my $err = $!; | ||
| 219 | unless ($ok && close(FH)) { | ||
| 220 | $err = $! if $ok; | ||
| 221 | close FH if $ok; | ||
| 222 | unlink $sch_file; | ||
| 223 | return $self->_err("Cannot write schema: $err"); | ||
| 224 | } | ||
| 225 | |||
| 226 | local *FH; | ||
| 227 | my $dat_file = $self->_file($table, 'dat'); | ||
| 228 | open(FH, "> $dat_file") or return $self->_err("Cannot create dat: $!"); | ||
| 229 | binmode FH; | ||
| 230 | unless (close FH) { | ||
| 231 | my $e = $!; | ||
| 232 | unlink $sch_file; | ||
| 233 | return $self->_err("Cannot create dat: $e"); | ||
| 234 | } | ||
| 235 | return 1; | ||
| 236 | } | ||
| 237 | |||
| 238 | sub drop_table { | ||
| 239 | my($self, $table) = @_; | ||
| 240 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 241 | return $self->_err("Invalid table name '" . _shown_name($table) . "'") | ||
| 242 | unless _valid_name($table); | ||
| 243 | my $sch = $self->_load_schema($table); | ||
| 244 | if ($sch && $sch->{indexes}) { | ||
| 245 | for my $ix (values %{$sch->{indexes}}) { | ||
| 246 | my $f = $self->_idx_file($table, $ix->{name}); | ||
| 247 | unlink $f if -f $f; | ||
| 248 | } | ||
| 249 | } | ||
| 250 | for my $ext (qw(sch dat lck)) { | ||
| 251 | my $f = $self->_file($table, $ext); | ||
| 252 | unlink $f if -f $f; | ||
| 253 | } | ||
| 254 | my $dir = $self->_db_path($self->{db_name}); | ||
| 255 | local *DH; | ||
| 256 | if (opendir DH, $dir) { | ||
| 257 | for my $f (readdir DH) { | ||
| 258 | unlink File::Spec->catfile($dir, $f) if $f =~ /^\Q${table}\E\.[^.]+\.idx$/; | ||
| 259 | } | ||
| 260 | closedir DH; | ||
| 261 | } | ||
| 262 | delete $self->{_tables}{$table}; | ||
| 263 | return 1; | ||
| 264 | } | ||
| 265 | |||
| 266 | sub list_tables { | ||
| 267 | my($self) = @_; | ||
| 268 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 269 | my $dir = $self->_db_path($self->{db_name}); | ||
| 270 | local *DH; | ||
| 271 | opendir(DH, $dir) or return (); | ||
| 272 | my @tbls = map { /^(.+)\.sch$/ ? $1 : () } readdir DH; | ||
| 273 | closedir DH; | ||
| 274 | return sort @tbls; | ||
| 275 | } | ||
| 276 | |||
| 277 | sub describe_table { | ||
| 278 | my($self, $table) = @_; | ||
| 279 | my $sch = $self->_load_schema($table) or return undef; | ||
| 280 | return $sch->{cols}; | ||
| 281 | } | ||
| 282 | |||
| 283 | ############################################################################### | ||
| 284 | # INDEX DDL | ||
| 285 | ############################################################################### | ||
| 286 | sub create_index { | ||
| 287 | my($self, $idxname, $table, $colname, $unique) = @_; | ||
| 288 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 289 | return $self->_err("Invalid index name '" . _shown_name($idxname) . "'") | ||
| 290 | unless _valid_name($idxname); | ||
| 291 | my $sch = $self->_load_schema($table) or return undef; | ||
| 292 | |||
| 293 | my($col_def) = grep { $_->{name} eq $colname } @{$sch->{cols}}; | ||
| 294 | return $self->_err("Column '$colname' not found in '$table'") unless $col_def; | ||
| 295 | return $self->_err("Index '$idxname' already exists on '$table'") if $sch->{indexes}{$idxname}; | ||
| 296 | |||
| 297 | $unique = $unique ? 1 : 0; | ||
| 298 | |||
| 299 | my $sch_file = $self->_file($table, 'sch'); | ||
| 300 | local *FH; | ||
| 301 | open(FH, ">> $sch_file") or return $self->_err("Cannot update schema: $!"); | ||
| 302 | my $ok = print FH "IDX=$idxname:$colname:$unique\n"; | ||
| 303 | my $err = $!; | ||
| 304 | unless ($ok && close(FH)) { | ||
| 305 | $err = $! if $ok; | ||
| 306 | close FH if $ok; | ||
| 307 | return $self->_err("Cannot update schema: $err"); | ||
| 308 | } | ||
| 309 | |||
| 310 | $sch->{indexes}{$idxname} = { | ||
| 311 | name => $idxname, | ||
| 312 | col => $colname, | ||
| 313 | unique => $unique, | ||
| 314 | keysize => $col_def->{size}, | ||
| 315 | coltype => $col_def->{type}, | ||
| 316 | }; | ||
| 317 | |||
| 318 | return $self->_rebuild_index($table, $idxname); | ||
| 319 | } | ||
| 320 | |||
| 321 | sub drop_index { | ||
| 322 | my($self, $idxname, $table) = @_; | ||
| 323 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 324 | return $self->_err("Invalid index name '" . _shown_name($idxname) . "'") | ||
| 325 | unless _valid_name($idxname); | ||
| 326 | my $sch = $self->_load_schema($table) or return undef; | ||
| 327 | return $self->_err("Index '$idxname' does not exist on '$table'") unless $sch->{indexes}{$idxname}; | ||
| 328 | |||
| 329 | unlink $self->_idx_file($table, $idxname); | ||
| 330 | delete $sch->{indexes}{$idxname}; | ||
| 331 | return $self->_rewrite_schema($table, $sch); | ||
| 332 | } | ||
| 333 | |||
| 334 | sub list_indexes { | ||
| 335 | my($self, $table) = @_; | ||
| 336 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 337 | my $sch = $self->_load_schema($table) or return undef; | ||
| 338 | return [ values %{$sch->{indexes}} ]; | ||
| 339 | } | ||
| 340 | |||
| 341 | ############################################################################### | ||
| 342 | # DML: INSERT | ||
| 343 | ############################################################################### | ||
| 344 | sub insert { | ||
| 345 | my($self, $table, $row) = @_; | ||
| 346 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 347 | my $sch = $self->_load_schema($table) or return undef; | ||
| 348 | |||
| 349 | for my $col (@{$sch->{cols}}) { | ||
| 350 | my $cn = $col->{name}; | ||
| 351 | if ((!defined($row->{$cn}) || ($row->{$cn} eq '')) && defined $sch->{defaults}{$cn}) { | ||
| 352 | $row->{$cn} = $sch->{defaults}{$cn}; | ||
| 353 | } | ||
| 354 | } | ||
| 355 | |||
| 356 | # UNIQUE check. It runs after DEFAULT has been applied, so that the | ||
| 357 | # value actually stored is the one compared. NULL is the empty string | ||
| 358 | # here and SQL-92 lets a UNIQUE column hold any number of NULLs, so an | ||
| 359 | # absent value is not compared at all. | ||
| 360 | for my $ix (values %{$sch->{indexes}}) { | ||
| 361 | next unless $ix->{unique}; | ||
| 362 | my $val = $row->{$ix->{col}}; | ||
| 363 | next unless defined($val) && ($val ne ''); | ||
| 364 | if ($self->_idx_lookup_exact($table, $ix, $val) >= 0) { | ||
| 365 | return $self->_err("UNIQUE constraint violated on '$ix->{name}' (col '$ix->{col}', value '$val')"); | ||
| 366 | } | ||
| 367 | } | ||
| 368 | |||
| 369 | for my $cn (keys %{$sch->{notnull} || {}}) { | ||
| 370 | return $self->_err("NOT NULL constraint violated on column '$cn'") unless defined($row->{$cn}) && ($row->{$cn} ne ''); | ||
| 371 | } | ||
| 372 | for my $cn (keys %{$sch->{checks} || {}}) { | ||
| 373 | next unless defined($row->{$cn}) && ($row->{$cn} ne ''); | ||
| 374 | return $self->_err("CHECK constraint failed on column '$cn'") unless eval_bool($sch->{checks}{$cn}, $row); | ||
| 375 | } | ||
| 376 | # VARCHAR / CHAR length check: reject values longer than the declared size. | ||
| 377 | for my $col (@{$sch->{cols}}) { | ||
| 378 | my $cn = $col->{name}; | ||
| 379 | next unless ($col->{type} eq 'VARCHAR' || $col->{type} eq 'CHAR'); | ||
| 380 | my $decl = defined($col->{decl}) ? $col->{decl} : $col->{size}; | ||
| 381 | next unless defined($decl) && ($decl < MAX_VARCHAR); | ||
| 382 | next unless defined($row->{$cn}) && ($row->{$cn} ne ''); | ||
| 383 | if (length($row->{$cn}) > $decl) { | ||
| 384 | return $self->_err( | ||
| 385 | "Value too long for column '$cn': " | ||
| 386 | . "declared $col->{type}($decl), got " | ||
| 387 | . length($row->{$cn}) . " bytes" | ||
| 388 | ); | ||
| 389 | } | ||
| 390 | } | ||
| 391 | # Type check: INT range and DATE validity. | ||
| 392 | for my $col (@{$sch->{cols}}) { | ||
| 393 | my $msg = _type_error($col, $row->{$col->{name}}); | ||
| 394 | return $self->_err($msg) if defined $msg; | ||
| 395 | } | ||
| 396 | my $packed = $self->_pack_record($sch, $row) or return undef; | ||
| 397 | my $dat = $self->_file($table, 'dat'); | ||
| 398 | local *FH; | ||
| 399 | open(FH, ">> $dat") or return $self->_err("Cannot open dat for append: $!"); | ||
| 400 | binmode FH; | ||
| 401 | _autoflush(\*FH); | ||
| 402 | _lock_ex(\*FH); | ||
| 403 | my $file_size = (stat FH)[7]; | ||
| 404 | my $rec_no = int($file_size / $sch->{recsize}); | ||
| 405 | unless (print FH $packed) { | ||
| 406 | my $e = $!; | ||
| 407 | _unlock(\*FH); | ||
| 408 | close FH; | ||
| 409 | return $self->_err("Cannot write record: $e"); | ||
| 410 | } | ||
| 411 | |||
| 412 | # The .dat lock is held until every index is updated, so that another | ||
| 413 | # process never sees the new record without its index entries. | ||
| 414 | for my $ix (values %{$sch->{indexes}}) { | ||
| 415 | $self->_idx_insert($table, $ix, $row->{$ix->{col}}, $rec_no); | ||
| 416 | } | ||
| 417 | _unlock(\*FH); | ||
| 418 | unless (close FH) { | ||
| 419 | return $self->_err("Cannot flush record: $!"); | ||
| 420 | } | ||
| 421 | return 1; | ||
| 422 | } | ||
| 423 | |||
| 424 | sub delete_rows { | ||
| 425 | my($self, $table, $where_info) = @_; | ||
| 426 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 427 | my $sch = $self->_load_schema($table) or return undef; | ||
| 428 | my $where_sub = _to_where_sub($where_info); | ||
| 429 | my $dat = $self->_file($table, 'dat'); | ||
| 430 | my $recsize = $sch->{recsize}; | ||
| 431 | my $count = 0; | ||
| 432 | |||
| 433 | local *FH; | ||
| 434 | open(FH, "+< $dat") or return $self->_err("Cannot open dat for delete: $!"); | ||
| 435 | binmode FH; | ||
| 436 | _autoflush(\*FH); | ||
| 437 | _lock_ex(\*FH); | ||
| 438 | |||
| 439 | seek(FH, 0, 0); | ||
| 440 | my($pos, $rec_no) = (0, 0); | ||
| 441 | while (1) { | ||
| 442 | seek(FH, $pos, 0); | ||
| 443 | my $raw = ''; | ||
| 444 | my $n = read(FH, $raw, $recsize); | ||
| 445 | last unless defined($n) && ($n == $recsize); | ||
| 446 | if (substr($raw, 0, 1) ne RECORD_DELETED) { | ||
| 447 | my $row = $self->_unpack_record($sch, $raw); | ||
| 448 | if (!$where_sub || $where_sub->($row)) { | ||
| 449 | seek(FH, $pos, 0); | ||
| 450 | unless (print FH RECORD_DELETED) { | ||
| 451 | my $e = $!; | ||
| 452 | _unlock(\*FH); | ||
| 453 | close FH; | ||
| 454 | return $self->_err("Cannot mark record deleted: $e"); | ||
| 455 | } | ||
| 456 | $count++; | ||
| 457 | for my $ix (values %{$sch->{indexes}}) { | ||
| 458 | $self->_idx_delete($table, $ix, $row->{$ix->{col}}, $rec_no); | ||
| 459 | } | ||
| 460 | } | ||
| 461 | } | ||
| 462 | $pos += $recsize; | ||
| 463 | $rec_no++; | ||
| 464 | } | ||
| 465 | _unlock(\*FH); | ||
| 466 | unless (close FH) { | ||
| 467 | return $self->_err("Cannot flush dat: $!"); | ||
| 468 | } | ||
| 469 | return $count; | ||
| 470 | } | ||
| 471 | |||
| 472 | ############################################################################### | ||
| 473 | # VACUUM | ||
| 474 | ############################################################################### | ||
| 475 | sub vacuum { | ||
| 476 | my($self, $table) = @_; | ||
| 477 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 478 | my $sch = $self->_load_schema($table) or return undef; | ||
| 479 | my $dat = $self->_file($table, 'dat'); | ||
| 480 | my $tmp = $dat . '.tmp'; | ||
| 481 | my $recsize = $sch->{recsize}; | ||
| 482 | |||
| 483 | local *IN_FH; | ||
| 484 | open(IN_FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 485 | local *OUT_FH; | ||
| 486 | open(OUT_FH, "> $tmp") or do { close IN_FH; return $self->_err("Cannot open tmp: $!"); }; | ||
| 487 | binmode IN_FH; | ||
| 488 | binmode OUT_FH; | ||
| 489 | _lock_ex(\*IN_FH); | ||
| 490 | |||
| 491 | my $kept = 0; | ||
| 492 | while (1) { | ||
| 493 | my $raw = ''; | ||
| 494 | my $n = read(IN_FH, $raw, $recsize); | ||
| 495 | last unless defined($n) && ($n == $recsize); | ||
| 496 | if (substr($raw, 0, 1) ne RECORD_DELETED) { | ||
| 497 | unless (print OUT_FH $raw) { | ||
| 498 | my $e = $!; | ||
| 499 | close OUT_FH; | ||
| 500 | _unlock(\*IN_FH); | ||
| 501 | close IN_FH; | ||
| 502 | unlink $tmp; | ||
| 503 | return $self->_err("Cannot write tmp: $e"); | ||
| 504 | } | ||
| 505 | $kept++; | ||
| 506 | } | ||
| 507 | } | ||
| 508 | # close() flushes, so the replacement file is complete on disk before | ||
| 509 | # the exclusive lock on the original is released. | ||
| 510 | my $out_ok = close(OUT_FH); | ||
| 511 | my $out_err = $!; | ||
| 512 | _unlock(\*IN_FH); | ||
| 513 | close IN_FH; | ||
| 514 | unless ($out_ok) { | ||
| 515 | unlink $tmp; | ||
| 516 | return $self->_err("Cannot flush tmp: $out_err"); | ||
| 517 | } | ||
| 518 | rename($tmp, $dat) or do { | ||
| 519 | my $e = $!; | ||
| 520 | unlink $tmp; | ||
| 521 | return $self->_err("Cannot replace dat: $e"); | ||
| 522 | }; | ||
| 523 | |||
| 524 | for my $ix (values %{$sch->{indexes}}) { | ||
| 525 | $self->_rebuild_index($table, $ix->{name}) or return undef; | ||
| 526 | } | ||
| 527 | return $kept; | ||
| 528 | } | ||
| 529 | |||
| 530 | ############################################################################### | ||
| 531 | # execute() | ||
| 532 | ############################################################################### | ||
| 533 | sub execute { | ||
| 534 | my($self, $sql) = @_; | ||
| 535 | $sql = _strip_sql_comments($sql); | ||
| 536 | $sql =~ s/^\s+|\s+$//g; | ||
| 537 | $sql = _normalize_sql_space($sql); | ||
| 538 | |||
| 539 | # Detect subqueries: any SELECT that contains a nested (SELECT ...) | ||
| 540 | # Route through the subquery engine, but guard against infinite recursion | ||
| 541 | # by only routing non-trivial top-level statements (not pure SELECT). | ||
| 542 | if ($sql =~ /\(\s*SELECT\b/i) { | ||
| 543 | |||
| 544 | # Only intercept DML/DDL statements and complex SELECTs here; | ||
| 545 | # pure inner SELECTs (called recursively) pass through normally. | ||
| 546 | # Top-level statements that may contain subqueries: | ||
| 547 | if ($sql =~ /^(?:SELECT|INSERT|UPDATE|DELETE)\b/i) { | ||
| 548 | return $self->execute_with_subquery($sql); | ||
| 549 | } | ||
| 550 | } | ||
| 551 | |||
| 552 | if ($sql =~ /^CREATE\s+DATABASE\s+(\w+)$/i) { | ||
| 553 | return $self->create_database($1) | ||
| 554 | ? { type=>'ok', message=>"Database '$1' created" } | ||
| 555 | : { type=>'error', message=>$errstr }; | ||
| 556 | } | ||
| 557 | if ($sql =~ /^USE\s+(\w+)$/i) { | ||
| 558 | return $self->use_database($1) | ||
| 559 | ? { type=>'ok', message=>"Using database '$1'" } | ||
| 560 | : { type=>'error', message=>$errstr }; | ||
| 561 | } | ||
| 562 | if ($sql =~ /^DROP\s+DATABASE\s+(\w+)$/i) { | ||
| 563 | return $self->drop_database($1) | ||
| 564 | ? { type=>'ok', message=>"Database '$1' dropped" } | ||
| 565 | : { type=>'error', message=>$errstr }; | ||
| 566 | } | ||
| 567 | if ($sql =~ /^SHOW\s+DATABASES$/i) { | ||
| 568 | return { type=>'list', data=>[ $self->list_databases() ] }; | ||
| 569 | } | ||
| 570 | if ($sql =~ /^SHOW\s+TABLES$/i) { | ||
| 571 | return { type=>'list', data=>[ $self->list_tables() ] }; | ||
| 572 | } | ||
| 573 | if ($sql =~ /^SHOW\s+(?:INDEXES|INDICES|INDEX)\s+(?:ON|FROM)\s+(\w+)$/i) { | ||
| 574 | my $ixs = $self->list_indexes($1); | ||
| 575 | return defined($ixs) | ||
| 576 | ? { type=>'indexes', table=>$1, data=>$ixs } | ||
| 577 | : { type=>'error', message=>$errstr }; | ||
| 578 | } | ||
| 579 | if ($sql =~ /^DESCRIBE\s+(\w+)$/i) { | ||
| 580 | my $cols = $self->describe_table($1); | ||
| 581 | return $cols | ||
| 582 | ? { type=>'describe', data=>$cols } | ||
| 583 | : { type=>'error', message=>$errstr }; | ||
| 584 | } | ||
| 585 | if ($sql =~ /^CREATE\s+TABLE\s+(\w+)\s*\((.+)\)$/si) { | ||
| 586 | my($tbl, $col_str) = ($1, $2); | ||
| 587 | my @col_defs = _split_col_defs($col_str); | ||
| 588 | my(@cols, %nn, %defs, %chks, %uniq, $pk); | ||
| 589 | for my $cd (@col_defs) { | ||
| 590 | $cd =~ s/^\s+|\s+$//g; | ||
| 591 | if ($cd =~ /^PRIMARY\s+KEY\s*\(\s*(\w+)\s*\)$/si) { | ||
| 592 | $pk = $1; | ||
| 593 | next; | ||
| 594 | } | ||
| 595 | # Table-level UNIQUE (col): enforced through a unique index, | ||
| 596 | # exactly like the column-level UNIQUE modifier below. | ||
| 597 | if ($cd =~ /^UNIQUE\s*\(\s*(\w+)\s*\)$/si) { | ||
| 598 | $uniq{$1} = 1; | ||
| 599 | next; | ||
| 600 | } | ||
| 601 | # FOREIGN KEY (...) REFERENCES ...: table-level constraint. | ||
| 602 | # Accepted silently (constraint is not enforced). | ||
| 603 | if ($cd =~ /^FOREIGN\s+KEY\b/si) { | ||
| 604 | next; | ||
| 605 | } | ||
| 606 | my($cn, $ct, $cs, $rest); | ||
| 607 | if ($cd =~ /^(\w+)\s+(CHAR|VARCHAR)\s*\(\s*(\d+)\s*\)(.*)/si) { | ||
| 608 | ($cn, $ct, $cs, $rest) = ($1, uc($2), $3, $4); | ||
| 609 | } | ||
| 610 | elsif ($cd =~ /^(\w+)\s+(\w+)(.*)/si) { | ||
| 611 | ($cn, $ct, $rest) = ($1, uc($2), $3); | ||
| 612 | $cs = undef; | ||
| 613 | } | ||
| 614 | else { | ||
| 615 | return { type=>'error', message=>"Cannot parse column def: $cd" }; | ||
| 616 | } | ||
| 617 | push @cols, [ $cn, $ct, $cs ]; | ||
| 618 | $rest = '' unless defined $rest; | ||
| 619 | $pk = $cn if $rest =~ /\bPRIMARY\s+KEY\b/si; | ||
| 620 | $nn{$cn} = 1 if $rest =~ /\b(?:NOT\s+NULL|PRIMARY\s+KEY)\b/si; | ||
| 621 | $defs{$cn} = (defined($1) ? $1 : $2) if $rest =~ /\bDEFAULT\s+(?:'([^']*)'|(-?\d+\.?\d*))/si; | ||
| 622 | $chks{$cn} = $1 if $rest =~ /\bCHECK\s*\((.+)\)/si; | ||
| 623 | # UNIQUE is looked for with the CHECK expression removed, so | ||
| 624 | # that a CHECK body that happens to mention the word cannot | ||
| 625 | # produce a false hit. | ||
| 626 | my $ukw = $rest; | ||
| 627 | $ukw =~ s/\bCHECK\s*\(.+\)//si; | ||
| 628 | $uniq{$cn} = 1 if $ukw =~ /\bUNIQUE\b/si; | ||
| 629 | } | ||
| 630 | $nn{$pk} = 1 if defined $pk; | ||
| 631 | $self->create_table($tbl, [ @cols ]) or return { type=>'error', message=>$errstr }; | ||
| 632 | if (%nn || %defs || %chks || defined $pk) { | ||
| 633 | my $sch = $self->_load_schema($tbl) or return { type=>'error', message=>$errstr }; | ||
| 634 | $sch->{notnull} = { %nn }; | ||
| 635 | $sch->{defaults} = { %defs }; | ||
| 636 | $sch->{checks} = { %chks }; | ||
| 637 | $sch->{pk} = $pk if defined $pk; | ||
| 638 | $self->_rewrite_schema($tbl, $sch); | ||
| 639 | } | ||
| 640 | |||
| 641 | # PRIMARY KEY and UNIQUE are enforced by insert() and update() | ||
| 642 | # through a unique index, so one has to be created here. Without | ||
| 643 | # it both constraints were silently accepted and never checked. | ||
| 644 | # A column that is both PRIMARY KEY and UNIQUE gets a single index. | ||
| 645 | my(@auto_idx, %seen_idx); | ||
| 646 | if (defined $pk) { | ||
| 647 | push @auto_idx, [ $pk, $pk . '_pk' ]; | ||
| 648 | $seen_idx{$pk} = 1; | ||
| 649 | } | ||
| 650 | for my $c (@cols) { | ||
| 651 | my $cn = $c->[0]; | ||
| 652 | next unless $uniq{$cn}; | ||
| 653 | next if $seen_idx{$cn}++; | ||
| 654 | push @auto_idx, [ $cn, $cn . '_unique' ]; | ||
| 655 | } | ||
| 656 | for my $ai (@auto_idx) { | ||
| 657 | next if $self->create_index($ai->[1], $tbl, $ai->[0], 1); | ||
| 658 | my $msg = $errstr; | ||
| 659 | $self->drop_table($tbl); | ||
| 660 | return { type=>'error', message=>$msg }; | ||
| 661 | } | ||
| 662 | |||
| 663 | my $fk_note = ($col_str =~ /\bREFERENCES\b/si | ||
| 664 | || $col_str =~ /\bFOREIGN\s+KEY\b/si) | ||
| 665 | ? " (NOTE: FOREIGN KEY constraints are not enforced)" | ||
| 666 | : ""; | ||
| 667 | return { type=>'ok', message=>"Table '$tbl' created$fk_note" }; | ||
| 668 | } | ||
| 669 | if ($sql =~ /^DROP\s+TABLE\s+(\w+)$/i) { | ||
| 670 | return $self->drop_table($1) | ||
| 671 | ? { type=>'ok', message=>"Table '$1' dropped" } | ||
| 672 | : { type=>'error', message=>$errstr }; | ||
| 673 | } | ||
| 674 | if ($sql =~ /^CREATE\s+(UNIQUE\s+)?INDEX\s+(\w+)\s+ON\s+(\w+)\s*\(\s*(\w+)\s*\)$/i) { | ||
| 675 | my($uniq, $idxname, $tbl, $col) = ($1, $2, $3, $4); | ||
| 676 | return $self->create_index($idxname, $tbl, $col, $uniq ? 1 : 0) | ||
| 677 | ? { type=>'ok', message=>"Index '$idxname' created on '$tbl'('$col')" } | ||
| 678 | : { type=>'error', message=>$errstr }; | ||
| 679 | } | ||
| 680 | if ($sql =~ /^DROP\s+INDEX\s+(\w+)\s+ON\s+(\w+)$/i) { | ||
| 681 | return $self->drop_index($1, $2) | ||
| 682 | ? { type=>'ok', message=>"Index '$1' dropped" } | ||
| 683 | : { type=>'error', message=>$errstr }; | ||
| 684 | } | ||
| 685 | if ($sql =~ /^VACUUM\s+(\w+)$/i) { | ||
| 686 | my $n = $self->vacuum($1); | ||
| 687 | return defined($n) | ||
| 688 | ? { type=>'ok', message=>"Vacuum done, $n records kept" } | ||
| 689 | : { type=>'error', message=>$errstr }; | ||
| 690 | } | ||
| 691 | # INSERT INTO table VALUES (...) -- no column list: use schema order | ||
| 692 | if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s+VALUES\s*\((.+)\)$/si) { | ||
| 693 | my($tbl, $val_str) = ($1, $2); | ||
| 694 | my $sch = $self->_load_schema($tbl) | ||
| 695 | or return { type=>'error', message=>"Table '$tbl' does not exist" }; | ||
| 696 | my @cols = map { $_->{name} } @{$sch->{cols}}; | ||
| 697 | my @v = _parse_values($val_str); | ||
| 698 | if (@v != @cols) { | ||
| 699 | return { type=>'error', | ||
| 700 | message=>"INSERT: " . scalar(@v) . " value(s) for " | ||
| 701 | . scalar(@cols) . " column(s) in table '$tbl'" }; | ||
| 702 | } | ||
| 703 | my %row; | ||
| 704 | @row{@cols} = @v; | ||
| 705 | return $self->insert($tbl, { %row }) | ||
| 706 | ? { type=>'ok', message=>"1 row inserted" } | ||
| 707 | : { type=>'error', message=>$errstr }; | ||
| 708 | } | ||
| 709 | if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s*\(([^)]+)\)\s*VALUES\s*\((.+)\)$/si) { | ||
| 710 | my($tbl, $col_str, $val_str) = ($1, $2, $3); | ||
| 711 | my @c = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $col_str; | ||
| 712 | my @v = _parse_values($val_str); | ||
| 713 | my %row; | ||
| 714 | @row{@c} = @v; | ||
| 715 | return $self->insert($tbl, { %row }) | ||
| 716 | ? { type=>'ok', message=>"1 row inserted" } | ||
| 717 | : { type=>'error', message=>$errstr }; | ||
| 718 | } | ||
| 719 | if ($sql =~ /^INSERT\s+INTO\s+(\w+)\s*\(([^)]+)\)\s+(SELECT\b.+)$/si) { | ||
| 720 | my($tbl, $cs, $sel) = ($1, $2, $3); | ||
| 721 | my @dst_cols = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $cs; | ||
| 722 | |||
| 723 | # Extract SELECT column list in declaration order. | ||
| 724 | # The engine stores rows as hashes (alphabetical key order), so we | ||
| 725 | # must parse the SELECT list to know the intended positional mapping. | ||
| 726 | my @src_cols; | ||
| 727 | if ($sel =~ /^SELECT\s+(.*?)\s+FROM\s+/si) { | ||
| 728 | @src_cols = map { my $c = $_; $c =~ s/^\s+|\s+$//g; $c =~ s/\s+AS\s+\w+$//si; $c } split /,/, $1; | ||
| 729 | } | ||
| 730 | my $res = $self->execute($sel); | ||
| 731 | return { type=>'error', message=>$res->{message} } if $res->{type} eq 'error'; | ||
| 732 | my $n = 0; | ||
| 733 | for my $r (@{$res->{data}}) { | ||
| 734 | |||
| 735 | # Map SELECT result columns to INSERT destination columns. | ||
| 736 | # | ||
| 737 | # Name-based mapping (preferred): when every dst column name | ||
| 738 | # exists as a key in the result row, map by name regardless of | ||
| 739 | # position. This handles INSERT INTO dst(a,b) SELECT b,a FROM src | ||
| 740 | # correctly and is insensitive to SELECT column order. | ||
| 741 | # | ||
| 742 | # Position-based fallback: used when dst and src columns differ | ||
| 743 | # (e.g. INSERT INTO dst(x,y) SELECT a,b FROM src) or when src | ||
| 744 | # columns could not be parsed (SELECT *). | ||
| 745 | my %row; | ||
| 746 | my %rkeys = map { $_ => 1 } keys %$r; | ||
| 747 | my $name_based = @dst_cols | ||
| 748 | && !grep { !$rkeys{$_} } @dst_cols; | ||
| 749 | if ($name_based) { | ||
| 750 | for my $col (@dst_cols) { | ||
| 751 | $row{$col} = $r->{$col}; | ||
| 752 | } | ||
| 753 | } | ||
| 754 | else { | ||
| 755 | my @src_keys = @src_cols ? @src_cols : sort keys %$r; | ||
| 756 | for my $i (0 .. $#dst_cols) { | ||
| 757 | $row{$dst_cols[$i]} = defined($src_keys[$i]) | ||
| 758 | ? $r->{$src_keys[$i]} : undef; | ||
| 759 | } | ||
| 760 | } | ||
| 761 | $self->insert($tbl, { %row }) and $n++; | ||
| 762 | } | ||
| 763 | return { type=>'ok', message=>"$n row(s) inserted" }; | ||
| 764 | } | ||
| 765 | if ($sql =~ /^SELECT\b/i) { | ||
| 766 | my $sel_res = $self->select($sql); | ||
| 767 | return $sel_res if defined $sel_res; | ||
| 768 | return { type=>'error', message=>$errstr }; | ||
| 769 | } | ||
| 770 | if ($sql =~ /^UPDATE\s+(\w+)\s+SET\s+(.+?)(\s+WHERE\s+.+)?$/si) { | ||
| 771 | my($tbl, $set_str, $wc) = ($1, $2, (defined($3) ? $3 : '')); | ||
| 772 | my %se = parse_set_exprs($set_str); | ||
| 773 | my $ws; | ||
| 774 | if ($wc =~ /\bWHERE\s+(.+)/si) { | ||
| 775 | (my $e = $1) =~ s/^\s+|\s+$//g; | ||
| 776 | $ws = where_sub($e); | ||
| 777 | } | ||
| 778 | my $n = $self->update($tbl, { %se }, $ws); | ||
| 779 | return defined($n) | ||
| 780 | ? { type=>'ok', message=>"$n row(s) updated" } | ||
| 781 | : { type=>'error', message=>$errstr }; | ||
| 782 | } | ||
| 783 | if ($sql =~ /^DELETE\s+FROM\s+(\w+)(.*)?$/si) { | ||
| 784 | my($tbl, $rest) = ($1, (defined($2) ? $2 : '')); | ||
| 785 | my $ws; | ||
| 786 | if ($rest =~ /\bWHERE\s+(.+)/si) { | ||
| 787 | (my $e = $1) =~ s/^\s+|\s+$//g; | ||
| 788 | $ws = where_sub($e); | ||
| 789 | } | ||
| 790 | my $n = $self->delete_rows($tbl, $ws); | ||
| 791 | return defined($n) | ||
| 792 | ? { type=>'ok', message=>"$n row(s) deleted" } | ||
| 793 | : { type=>'error', message=>$errstr }; | ||
| 794 | } | ||
| 795 | return { type=>'error', message=>"Unsupported SQL: $sql" }; | ||
| 796 | } | ||
| 797 | |||
| 798 | ############################################################################### | ||
| 799 | # SUBQUERY ENGINE | ||
| 800 | # | ||
| 801 | # Supported subquery positions: | ||
| 802 | # | ||
| 803 | # 1. WHERE col IN (SELECT single_col FROM ...) | ||
| 804 | # 2. WHERE col NOT IN (SELECT single_col FROM ...) | ||
| 805 | # 3. WHERE col OP (SELECT single_col FROM ...) OP = = != < > <= >= | ||
| 806 | # 4. WHERE EXISTS (SELECT ... FROM ...) | ||
| 807 | # 5. WHERE NOT EXISTS (SELECT ... FROM ...) | ||
| 808 | # 6. FROM (SELECT ...) AS alias -- derived table / inline view | ||
| 809 | # 7. SELECT (SELECT single_col ...) AS alias -- scalar subquery in SELECT list | ||
| 810 | # | ||
| 811 | # Nesting: subqueries may themselves contain subqueries (recursive expansion). | ||
| 812 | # Correlated subqueries: outer row values injected via _subq_context hashref. | ||
| 813 | ############################################################################### | ||
| 814 | |||
| 815 | # --------------------------------------------------------------------------- | ||
| 816 | # Public wrapper: expand all subqueries in a SQL string, then execute. | ||
| 817 | # Called by execute() when a subquery token is detected. | ||
| 818 | # --------------------------------------------------------------------------- | ||
| 819 | sub execute_with_subquery { | ||
| 820 | my($self, $sql) = @_; | ||
| 821 | |||
| 822 | # Handle derived table in FROM: FROM (SELECT ...) AS alias | ||
| 823 | if ($sql =~ /\bFROM\s*\(/i) { | ||
| 824 | return $self->_exec_derived_table($sql); | ||
| 825 | } | ||
| 826 | |||
| 827 | # Handle scalar subqueries in SELECT list: SELECT (SELECT ...) AS alias | ||
| 828 | if ($sql =~ /^SELECT\s*\(/i) { | ||
| 829 | return $self->_exec_scalar_select_subquery($sql); | ||
| 830 | } | ||
| 831 | |||
| 832 | # Expand WHERE-clause subqueries iteratively (innermost first) | ||
| 833 | my $expanded = $self->_expand_where_subqueries($sql, {}); | ||
| 834 | return $expanded if ref($expanded) eq 'HASH'; # error hash | ||
| 835 | |||
| 836 | # If correlated subqueries remain (still contain (SELECT), use row-level evaluator | ||
| 837 | if ($expanded =~ /\(\s*SELECT\b/i) { | ||
| 838 | return $self->_exec_correlated_select($expanded); | ||
| 839 | } | ||
| 840 | |||
| 841 | return $self->execute($expanded); | ||
| 842 | } | ||
| 843 | |||
| 844 | # --------------------------------------------------------------------------- | ||
| 845 | # Execute a SELECT with correlated subqueries in the WHERE clause. | ||
| 846 | # Scans each row, evaluates the subquery with the row as outer context. | ||
| 847 | # --------------------------------------------------------------------------- | ||
| 848 | sub _exec_correlated_select { | ||
| 849 | my($self, $sql) = @_; | ||
| 850 | |||
| 851 | # Must be a plain SELECT (no JOIN, no derived table) | ||
| 852 | unless ($sql =~ /^SELECT\s+(.+?)\s+FROM\s+(\w+)(.*)?$/i) { | ||
| 853 | return { type=>'error', message=>"Cannot execute correlated query: $sql" }; | ||
| 854 | } | ||
| 855 | my($col_str, $tbl, $rest) = ($1, $2, (defined($3) ? $3 : '')); | ||
| 856 | |||
| 857 | my $sch = $self->_load_schema($tbl) or return { type=>'error', message=>$errstr }; | ||
| 858 | |||
| 859 | # Parse col list | ||
| 860 | my @sel_cols; | ||
| 861 | unless ($col_str =~ /^\*$/) { | ||
| 862 | @sel_cols = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $col_str; | ||
| 863 | } | ||
| 864 | |||
| 865 | # Strip ORDER BY / LIMIT / OFFSET | ||
| 866 | my %opts; | ||
| 867 | if ($rest =~ s/\bLIMIT\s+(\d+)//i) { | ||
| 868 | $opts{limit} = $1; | ||
| 869 | } | ||
| 870 | if ($rest =~ s/\bOFFSET\s+(\d+)//i) { | ||
| 871 | $opts{offset} = $1; | ||
| 872 | } | ||
| 873 | if ($rest =~ s/\bORDER\s+BY\s+(\w+)(?:\s+(ASC|DESC))?//i) { | ||
| 874 | $opts{order_by} = $1; | ||
| 875 | $opts{order_dir} = defined($2) ? $2 : 'ASC'; | ||
| 876 | my @onames = @sel_cols | ||
| 877 | ? map { _order_name_of($_) } @sel_cols | ||
| 878 | : map { $_->{name} } @{$sch->{cols}}; | ||
| 879 | my($obe, $obk) = _resolve_order_ordinal_scalar($opts{order_by}, [ @onames ]); | ||
| 880 | return { type=>'error', message=>$obe } if $obe ne ''; | ||
| 881 | $opts{order_by} = $obk; | ||
| 882 | } | ||
| 883 | |||
| 884 | # Extract WHERE expression | ||
| 885 | my $where_expr = ''; | ||
| 886 | if ($rest =~ /\bWHERE\s+(.+)/i) { | ||
| 887 | $where_expr = $1; | ||
| 888 | $where_expr =~ s/^\s+|\s+$//g; | ||
| 889 | } | ||
| 890 | |||
| 891 | # Parse conditions (may include subquery conditions) | ||
| 892 | my $conds = $self->_parse_conditions_with_subq($where_expr); | ||
| 893 | my $filter = $self->_compile_where_with_subq($conds); | ||
| 894 | |||
| 895 | # Full scan with per-row subquery evaluation | ||
| 896 | my $dat = $self->_file($tbl, 'dat'); | ||
| 897 | my $recsize = $sch->{recsize}; | ||
| 898 | my @results; | ||
| 899 | |||
| 900 | local *FH; | ||
| 901 | open(FH, "< $dat") or return { type=>'error', message=>"Cannot open dat: $!" }; | ||
| 902 | binmode FH; | ||
| 903 | _lock_sh(\*FH); | ||
| 904 | my $rec_no = 0; | ||
| 905 | while (1) { | ||
| 906 | my $raw = ''; | ||
| 907 | my $n = read(FH, $raw, $recsize); | ||
| 908 | last unless defined($n) && ($n == $recsize); | ||
| 909 | if (substr($raw, 0, 1) ne RECORD_DELETED) { | ||
| 910 | my $row = $self->_unpack_record($sch, $raw); | ||
| 911 | |||
| 912 | # Make row available under both bare and table-qualified names | ||
| 913 | my %qrow = %$row; | ||
| 914 | for my $c (@{$sch->{cols}}) { | ||
| 915 | $qrow{"$tbl.$c->{name}"} = $row->{$c->{name}}; | ||
| 916 | } | ||
| 917 | push @results, { %qrow } if $filter->({ %qrow }); | ||
| 918 | } | ||
| 919 | $rec_no++; | ||
| 920 | } | ||
| 921 | _unlock(\*FH); | ||
| 922 | close FH; | ||
| 923 | |||
| 924 | # ORDER BY | ||
| 925 | if (my $ob = $opts{order_by}) { | ||
| 926 | my $dir = lc(defined($opts{order_dir}) ? $opts{order_dir} : 'asc'); | ||
| 927 | @results = sort { | ||
| 928 | my($va, $vb) = ($a->{$ob}, $b->{$ob}); | ||
| 929 | my $cmp = (defined($va) && ($va =~ /^-?\d+\.?\d*$/) && | ||
| 930 | defined($vb) && ($vb =~ /^-?\d+\.?\d*$/)) | ||
| 931 | ? ($va <=> $vb) | ||
| 932 | : ((defined($va) ? $va : '') cmp (defined($vb) ? $vb : '')); | ||
| 933 | ($dir eq 'desc') ? -$cmp : $cmp; | ||
| 934 | } @results; | ||
| 935 | } | ||
| 936 | |||
| 937 | # OFFSET / LIMIT | ||
| 938 | my $off = defined($opts{offset}) ? $opts{offset} : 0; | ||
| 939 | @results = splice(@results, $off) if $off; | ||
| 940 | if (defined $opts{limit}) { | ||
| 941 | my $last = $opts{limit} - 1; | ||
| 942 | $last = $#results if $last > $#results; | ||
| 943 | @results = @results[0..$last]; | ||
| 944 | } | ||
| 945 | |||
| 946 | # Column projection (remove table-qualified duplicates) | ||
| 947 | my @proj; | ||
| 948 | for my $r (@results) { | ||
| 949 | my %p; | ||
| 950 | if (@sel_cols) { | ||
| 951 | for my $c (@sel_cols) { | ||
| 952 | $p{$c} = $r->{$c}; | ||
| 953 | } | ||
| 954 | } | ||
| 955 | else { | ||
| 956 | |||
| 957 | # All bare columns | ||
| 958 | for my $c (@{$sch->{cols}}) { | ||
| 959 | $p{$c->{name}} = $r->{$c->{name}}; | ||
| 960 | } | ||
| 961 | } | ||
| 962 | push @proj, { %p }; | ||
| 963 | } | ||
| 964 | |||
| 965 | return { type=>'rows', data=>[ @proj ] }; | ||
| 966 | } | ||
| 967 | |||
| 968 | # --------------------------------------------------------------------------- | ||
| 969 | # _expand_where_subqueries($sql, \%outer_row) | ||
| 970 | # | ||
| 971 | # Finds the innermost (SELECT ...) in a WHERE clause and replaces it with | ||
| 972 | # its evaluated result (a literal list or scalar). Repeats until no | ||
| 973 | # subqueries remain. Returns the rewritten SQL string, or error hashref. | ||
| 974 | # --------------------------------------------------------------------------- | ||
| 975 | sub _expand_where_subqueries { | ||
| 976 | my($self, $sql, $outer_row) = @_; | ||
| 977 | $outer_row ||= {}; | ||
| 978 | |||
| 979 | my $max_depth = 32; | ||
| 980 | my $iter = 0; | ||
| 981 | |||
| 982 | while (($sql =~ /\(\s*SELECT\b/i) && ($iter++ < $max_depth)) { | ||
| 983 | |||
| 984 | # Find the innermost (SELECT ...) -- i.e. the one with no nested (SELECT | ||
| 985 | my $pos = _find_innermost_subquery($sql); | ||
| 986 | last unless defined $pos; | ||
| 987 | |||
| 988 | my($start, $end) = @$pos; | ||
| 989 | my $inner_sql = substr($sql, $start + 1, $end - $start - 1); | ||
| 990 | $inner_sql =~ s/^\s+|\s+$//g; | ||
| 991 | |||
| 992 | # Determine context: what precedes the opening paren | ||
| 993 | my $prefix = substr($sql, 0, $start); | ||
| 994 | |||
| 995 | # Detect correlated subquery: inner SQL contains tablename.colname | ||
| 996 | # references that are NOT from the inner query's own tables. | ||
| 997 | # Heuristic: if inner_sql has \w+\.\w+ patterns, check if those | ||
| 998 | # table-names appear in the inner FROM clause. | ||
| 999 | if (_subquery_is_correlated($inner_sql)) { | ||
| 1000 | |||
| 1001 | # Cannot pre-evaluate; will be handled per-row in _compile_where_with_subq. | ||
| 1002 | # Mark as a correlated subquery placeholder and stop expanding here. | ||
| 1003 | last; | ||
| 1004 | } | ||
| 1005 | |||
| 1006 | # Inject outer row values for correlated references | ||
| 1007 | my $resolved = $self->_resolve_correlated($inner_sql, $outer_row); | ||
| 1008 | |||
| 1009 | # Execute the inner query | ||
| 1010 | my $inner_res = $self->execute($resolved); | ||
| 1011 | if (!$inner_res || ($inner_res->{type} eq 'error')) { | ||
| 1012 | my $msg = $inner_res ? $inner_res->{message} : $errstr; | ||
| 1013 | return { type=>'error', message=>"Subquery error: $msg" }; | ||
| 1014 | } | ||
| 1015 | |||
| 1016 | my @inner_rows = @{ $inner_res->{data} || [] }; | ||
| 1017 | |||
| 1018 | # Determine what kind of subquery this is based on prefix context | ||
| 1019 | my $replacement; | ||
| 1020 | if (($prefix =~ /\bIN\s*$/i) || ($prefix =~ /\bNOT\s+IN\s*$/i)) { | ||
| 1021 | |||
| 1022 | # IN / NOT IN: build a parenthesised list of literal values | ||
| 1023 | my @vals; | ||
| 1024 | for my $r (@inner_rows) { | ||
| 1025 | my @rv = values %$r; | ||
| 1026 | my $v = defined($rv[0]) ? $rv[0] : 'NULL'; | ||
| 1027 | if ($v =~ /^-?\d+\.?\d*$/) { | ||
| 1028 | push @vals, $v; | ||
| 1029 | } | ||
| 1030 | else { | ||
| 1031 | push @vals, "'$v'"; | ||
| 1032 | } | ||
| 1033 | } | ||
| 1034 | if (@vals) { | ||
| 1035 | $replacement = '(' . join(',', @vals) . ')'; | ||
| 1036 | } | ||
| 1037 | else { | ||
| 1038 | |||
| 1039 | # Empty set semantics: | ||
| 1040 | # col IN (empty) -> always false -> use (NULL) | ||
| 1041 | # col NOT IN (empty) -> always true -> use a value that | ||
| 1042 | # never matches col, so NOT IN evaluates to true for | ||
| 1043 | # every row. We inject the sentinel '__EMPTY_SET__' | ||
| 1044 | # (not a valid column value) which will not match. | ||
| 1045 | if ($prefix =~ /\bNOT\s+IN\s*$/i) { | ||
| 1046 | $replacement = "('__EMPTY_SET__')"; | ||
| 1047 | } | ||
| 1048 | else { | ||
| 1049 | $replacement = '(NULL)'; | ||
| 1050 | } | ||
| 1051 | } | ||
| 1052 | } | ||
| 1053 | elsif ($prefix =~ /\b(?:EXISTS|NOT\s+EXISTS)\s*$/i) { | ||
| 1054 | |||
| 1055 | # EXISTS / NOT EXISTS: replace the paren content with 1 or 0 | ||
| 1056 | # The EXISTS keyword stays; we replace just the (SELECT ...) with (1) or (0) | ||
| 1057 | $replacement = @inner_rows ? '(1)' : '(0)'; | ||
| 1058 | } | ||
| 1059 | else { | ||
| 1060 | |||
| 1061 | # Scalar subquery (=, !=, <, >, <=, >=, or bare use) | ||
| 1062 | if (@inner_rows > 1) { | ||
| 1063 | return { type=>'error', message=>"Subquery returns more than one row" }; | ||
| 1064 | } | ||
| 1065 | if (@inner_rows == 0) { | ||
| 1066 | $replacement = 'NULL'; | ||
| 1067 | } | ||
| 1068 | else { | ||
| 1069 | my @rv = values %{ $inner_rows[0] }; | ||
| 1070 | my $v = defined($rv[0]) ? $rv[0] : 'NULL'; | ||
| 1071 | $replacement = ($v =~ /^-?\d+\.?\d*$/) ? $v : "'$v'"; | ||
| 1072 | } | ||
| 1073 | } | ||
| 1074 | |||
| 1075 | # Splice the replacement into the SQL | ||
| 1076 | substr($sql, $start, $end - $start + 1) = $replacement; | ||
| 1077 | } | ||
| 1078 | |||
| 1079 | return $sql; | ||
| 1080 | } | ||
| 1081 | |||
| 1082 | # --------------------------------------------------------------------------- | ||
| 1083 | # Detect whether a subquery SQL string contains correlated outer references. | ||
| 1084 | # A subquery is correlated if it contains alias.colname where the alias | ||
| 1085 | # is NOT one of the tables listed in its own FROM clause. | ||
| 1086 | # --------------------------------------------------------------------------- | ||
| 1087 | sub _subquery_is_correlated { | ||
| 1088 | my($inner_sql) = @_; | ||
| 1089 | |||
| 1090 | # Find tables in the inner FROM clause | ||
| 1091 | my %inner_tables; | ||
| 1092 | |||
| 1093 | # FROM t1 [AS a1] [JOIN t2 AS a2 ON ...]* | ||
| 1094 | if ($inner_sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/i) { | ||
| 1095 | $inner_tables{ lc(defined($2) ? $2 : $1) } = 1; | ||
| 1096 | $inner_tables{ lc($1) } = 1; | ||
| 1097 | } | ||
| 1098 | while ($inner_sql =~ /\bJOIN\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/gi) { | ||
| 1099 | $inner_tables{ lc(defined($2) ? $2 : $1) } = 1; | ||
| 1100 | $inner_tables{ lc($1) } = 1; | ||
| 1101 | } | ||
| 1102 | |||
| 1103 | # Look for alias.col references in WHERE clause | ||
| 1104 | while ($inner_sql =~ /\b(\w+)\.(\w+)\b/g) { | ||
| 1105 | my($tbl, $col) = (lc($1), $2); | ||
| 1106 | return 1 unless $inner_tables{$tbl}; | ||
| 1107 | } | ||
| 1108 | return 0; | ||
| 1109 | } | ||
| 1110 | |||
| 1111 | # --------------------------------------------------------------------------- | ||
| 1112 | # Find the innermost (SELECT ...) -- the one whose content has no nested | ||
| 1113 | # (SELECT. Returns [$start_pos, $end_pos] of the outer parens, or undef. | ||
| 1114 | # --------------------------------------------------------------------------- | ||
| 1115 | sub _find_innermost_subquery { | ||
| 1116 | my($sql) = @_; | ||
| 1117 | my $len = length($sql); | ||
| 1118 | my $best_start; | ||
| 1119 | my $best_end; | ||
| 1120 | |||
| 1121 | my $i = 0; | ||
| 1122 | while ($i < $len) { | ||
| 1123 | |||
| 1124 | # Look for ( followed (possibly with spaces) by SELECT | ||
| 1125 | if (substr($sql, $i, 1) eq '(' ) { | ||
| 1126 | |||
| 1127 | # Check if this opens a SELECT | ||
| 1128 | my $peek = substr($sql, $i+1); | ||
| 1129 | $peek =~ s/^\s+//; | ||
| 1130 | if ($peek =~ /^SELECT\b/i) { | ||
| 1131 | |||
| 1132 | # Walk to matching close paren, check for no nested SELECT | ||
| 1133 | my $depth = 1; | ||
| 1134 | my $j = $i + 1; | ||
| 1135 | my $has_nested = 0; | ||
| 1136 | my $in_str = 0; | ||
| 1137 | while (($j < $len) && ($depth > 0)) { | ||
| 1138 | my $ch = substr($sql, $j, 1); | ||
| 1139 | if ($ch eq "'") { | ||
| 1140 | |||
| 1141 | # Toggle string mode | ||
| 1142 | $in_str = !$in_str; | ||
| 1143 | } | ||
| 1144 | elsif (!$in_str) { | ||
| 1145 | if ($ch eq '(') { | ||
| 1146 | $depth++; | ||
| 1147 | |||
| 1148 | # check for nested SELECT | ||
| 1149 | my $p2 = substr($sql, $j+1); | ||
| 1150 | $p2 =~ s/^\s+//; | ||
| 1151 | $has_nested = 1 if ($depth > 1) && ($p2 =~ /^SELECT\b/i); | ||
| 1152 | } | ||
| 1153 | elsif ($ch eq ')') { | ||
| 1154 | $depth--; | ||
| 1155 | } | ||
| 1156 | } | ||
| 1157 | $j++; | ||
| 1158 | } | ||
| 1159 | if (($depth == 0) && !$has_nested) { | ||
| 1160 | |||
| 1161 | # This is an innermost SELECT subquery | ||
| 1162 | $best_start = $i; | ||
| 1163 | $best_end = $j - 1; | ||
| 1164 | |||
| 1165 | # Don't break -- we want the last (innermost) one found | ||
| 1166 | } | ||
| 1167 | } | ||
| 1168 | } | ||
| 1169 | $i++; | ||
| 1170 | } | ||
| 1171 | |||
| 1172 | return defined($best_start) ? [ $best_start, $best_end ] : undef; | ||
| 1173 | } | ||
| 1174 | |||
| 1175 | # --------------------------------------------------------------------------- | ||
| 1176 | # _resolve_correlated($inner_sql, \%outer_row) | ||
| 1177 | # | ||
| 1178 | # Replace references to outer-row columns in a correlated subquery. | ||
| 1179 | # Outer references appear as outer.colname or are matched when the column | ||
| 1180 | # name exists in %outer_row but NOT in the inner query's table. | ||
| 1181 | # Simple heuristic: replace outer.col tokens with the literal value. | ||
| 1182 | # --------------------------------------------------------------------------- | ||
| 1183 | sub _resolve_correlated { | ||
| 1184 | my($self, $sql, $outer_row) = @_; | ||
| 1185 | return $sql unless %$outer_row; | ||
| 1186 | |||
| 1187 | # Build sorted list: longer (qualified) keys first so alias.col | ||
| 1188 | # is replaced before bare col to avoid double-substitution. | ||
| 1189 | my @keys = sort { length($b) <=> length($a) } keys %$outer_row; | ||
| 1190 | |||
| 1191 | for my $qkey (@keys) { | ||
| 1192 | my $val = defined($outer_row->{$qkey}) ? $outer_row->{$qkey} : 'NULL'; | ||
| 1193 | my $lit = ($val =~ /^-?\d+\.?\d*$/) ? $val : "'$val'"; | ||
| 1194 | |||
| 1195 | if (index($qkey, '.') >= 0) { | ||
| 1196 | |||
| 1197 | # Qualified key: e.g. "employees.id" | ||
| 1198 | # Build regex that matches the full qualified token | ||
| 1199 | (my $pat = $qkey) =~ s/\./\\./g; | ||
| 1200 | $sql =~ s/(?<![.\w])$pat(?!\w)/$lit/g; | ||
| 1201 | } | ||
| 1202 | else { | ||
| 1203 | |||
| 1204 | # Bare key: only replace if NOT preceded by a dot | ||
| 1205 | # (avoids replacing "id" inside "employees.id" already handled above) | ||
| 1206 | $sql =~ s/(?<![.\w])$qkey(?!\w)/$lit/g; | ||
| 1207 | } | ||
| 1208 | } | ||
| 1209 | return $sql; | ||
| 1210 | } | ||
| 1211 | |||
| 1212 | # --------------------------------------------------------------------------- | ||
| 1213 | # EXISTS / NOT EXISTS correlated subquery evaluation at runtime | ||
| 1214 | # | ||
| 1215 | # These must be evaluated per-outer-row, so they cannot be pre-expanded. | ||
| 1216 | # We detect them in _parse_conditions and defer evaluation. | ||
| 1217 | # --------------------------------------------------------------------------- | ||
| 1218 | |||
| 1219 | # Enhanced _parse_conditions that understands subquery conditions. | ||
| 1220 | # Returns arrayref of condition hashrefs; subquery conditions have: | ||
| 1221 | # { type => 'subquery', | ||
| 1222 | # op => 'IN'|'NOT_IN'|'EXISTS'|'NOT_EXISTS'|'CMP', | ||
| 1223 | # col => colname, # for IN/NOT_IN/CMP | ||
| 1224 | # cmp_op => '='|..., # for CMP | ||
| 1225 | # subql => 'SELECT ...', | ||
| 1226 | # } | ||
| 1227 | sub _parse_conditions_with_subq { | ||
| 1228 | my($self, $expr) = @_; | ||
| 1229 | my @conds; | ||
| 1230 | |||
| 1231 | # Split on AND (but not inside parens/strings) | ||
| 1232 | my @parts = _split_and_clauses($expr); | ||
| 1233 | |||
| 1234 | for my $part (@parts) { | ||
| 1235 | $part =~ s/^\s+|\s+$//g; | ||
| 1236 | |||
| 1237 | # EXISTS (SELECT ...) | ||
| 1238 | if ($part =~ /^(NOT\s+)?EXISTS\s*\((.+)\)\s*$/si) { | ||
| 1239 | my($neg, $subql) = ($1, $2); | ||
| 1240 | $subql =~ s/^\s+|\s+$//g; | ||
| 1241 | push @conds, { | ||
| 1242 | type => 'subquery', | ||
| 1243 | op => ($neg ? 'NOT_EXISTS' : 'EXISTS'), | ||
| 1244 | subql => $subql, | ||
| 1245 | }; | ||
| 1246 | next; | ||
| 1247 | } | ||
| 1248 | |||
| 1249 | # col [NOT] IN (SELECT ...) | ||
| 1250 | if ($part =~ /^([\w.]+)\s+(NOT\s+)?IN\s*\((\s*SELECT\b.+)\)\s*$/si) { | ||
| 1251 | my($col, $neg, $subql) = ($1, $2, $3); | ||
| 1252 | $subql =~ s/^\s+|\s+$//g; | ||
| 1253 | push @conds, { | ||
| 1254 | type => 'subquery', | ||
| 1255 | op => $neg ? 'NOT_IN' : 'IN', | ||
| 1256 | col => $col, | ||
| 1257 | subql => $subql, | ||
| 1258 | }; | ||
| 1259 | next; | ||
| 1260 | } | ||
| 1261 | |||
| 1262 | # col OP (SELECT ...) | ||
| 1263 | if ($part =~ /^([\w.]+)\s*(=|!=|<>|<=|>=|<|>)\s*\((\s*SELECT\b.+)\)\s*$/si) { | ||
| 1264 | my($col, $op, $subql) = ($1, uc($2), $3); | ||
| 1265 | $subql =~ s/^\s+|\s+$//g; | ||
| 1266 | push @conds, { | ||
| 1267 | type => 'subquery', | ||
| 1268 | op => 'CMP', | ||
| 1269 | cmp_op => $op, | ||
| 1270 | col => $col, | ||
| 1271 | subql => $subql, | ||
| 1272 | }; | ||
| 1273 | next; | ||
| 1274 | } | ||
| 1275 | |||
| 1276 | # Normal condition | ||
| 1277 | if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) { | ||
| 1278 | my($col, $op, $sv, $nv) = ($1, $2, $3, $4); | ||
| 1279 | push @conds, { col=>$col, op=>uc($op), val=>defined($sv) ? $sv : $nv }; | ||
| 1280 | } | ||
| 1281 | } | ||
| 1282 | return [ @conds ]; | ||
| 1283 | } | ||
| 1284 | |||
| 1285 | # Split WHERE expression on top-level AND (not inside parens or strings) | ||
| 1286 | sub _split_and_clauses { | ||
| 1287 | my($expr) = @_; | ||
| 1288 | my @parts; | ||
| 1289 | my $cur = ''; | ||
| 1290 | my $depth = 0; | ||
| 1291 | my $in_str = 0; | ||
| 1292 | my $i = 0; | ||
| 1293 | my $len = length($expr); | ||
| 1294 | |||
| 1295 | while ($i < $len) { | ||
| 1296 | my $ch = substr($expr, $i, 1); | ||
| 1297 | if (($ch eq "'") && !$in_str) { | ||
| 1298 | $in_str = 1; | ||
| 1299 | $cur .= $ch; | ||
| 1300 | } | ||
| 1301 | elsif (($ch eq "'") && $in_str) { | ||
| 1302 | $in_str = 0; | ||
| 1303 | $cur .= $ch; | ||
| 1304 | } | ||
| 1305 | elsif ($in_str) { | ||
| 1306 | $cur .= $ch; | ||
| 1307 | } | ||
| 1308 | elsif ($ch eq '(') { | ||
| 1309 | $depth++; | ||
| 1310 | $cur .= $ch; | ||
| 1311 | } | ||
| 1312 | elsif ($ch eq ')') { | ||
| 1313 | $depth--; | ||
| 1314 | $cur .= $ch; | ||
| 1315 | } | ||
| 1316 | elsif (($depth == 0) && (substr($expr, $i, 5) =~ /^AND\s/i)) { | ||
| 1317 | push @parts, $cur; | ||
| 1318 | $cur = ''; | ||
| 1319 | $i += 4; # skip "AND " | ||
| 1320 | next; | ||
| 1321 | } | ||
| 1322 | else { | ||
| 1323 | $cur .= $ch; | ||
| 1324 | } | ||
| 1325 | $i++; | ||
| 1326 | } | ||
| 1327 | push @parts, $cur if $cur =~ /\S/; | ||
| 1328 | return @parts; | ||
| 1329 | } | ||
| 1330 | |||
| 1331 | # --------------------------------------------------------------------------- | ||
| 1332 | # Build a where-filter sub that handles subquery conditions (evaluated | ||
| 1333 | # at filter time with the candidate row as outer context). | ||
| 1334 | # --------------------------------------------------------------------------- | ||
| 1335 | sub _compile_where_with_subq { | ||
| 1336 | my($self, $conds) = @_; | ||
| 1337 | return sub { 1 } unless $conds && @$conds; | ||
| 1338 | |||
| 1339 | my @plain; | ||
| 1340 | my @subq; | ||
| 1341 | for my $c (@$conds) { | ||
| 1342 | if (($c->{type} || '') eq 'subquery') { | ||
| 1343 | push @subq, $c; | ||
| 1344 | } | ||
| 1345 | else { | ||
| 1346 | push @plain, $c; | ||
| 1347 | } | ||
| 1348 | } | ||
| 1349 | |||
| 1350 | my $plain_sub = _compile_where_from_conds([ @plain ]); | ||
| 1351 | |||
| 1352 | return sub { | ||
| 1353 | my($row) = @_; | ||
| 1354 | |||
| 1355 | # Plain conditions first (fast path) | ||
| 1356 | return 0 if $plain_sub && !$plain_sub->($row); | ||
| 1357 | |||
| 1358 | # Subquery conditions (evaluated per row) | ||
| 1359 | for my $c (@subq) { | ||
| 1360 | my $op = $c->{op}; | ||
| 1361 | my $subql = $self->_resolve_correlated($c->{subql}, $row); | ||
| 1362 | my $res = $self->execute($subql); | ||
| 1363 | my @rows = ($res && $res->{type} eq 'rows') ? @{$res->{data}} : (); | ||
| 1364 | |||
| 1365 | if ($op eq 'EXISTS') { | ||
| 1366 | return 0 unless @rows; | ||
| 1367 | } | ||
| 1368 | elsif ($op eq 'NOT_EXISTS') { | ||
| 1369 | return 0 if @rows; | ||
| 1370 | } | ||
| 1371 | elsif (($op eq 'IN') || ($op eq 'NOT_IN')) { | ||
| 1372 | my $col_val = defined($row->{$c->{col}}) ? $row->{$c->{col}} : ''; | ||
| 1373 | my $found = 0; | ||
| 1374 | my $has_null = 0; | ||
| 1375 | for my $r (@rows) { | ||
| 1376 | my @rv = values %$r; | ||
| 1377 | unless (defined $rv[0]) { $has_null = 1; next } | ||
| 1378 | my $rv = $rv[0]; | ||
| 1379 | my $num = (($col_val =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/)); | ||
| 1380 | if ($num ? ($col_val == $rv) : ($col_val eq $rv)) { | ||
| 1381 | $found = 1; | ||
| 1382 | last; | ||
| 1383 | } | ||
| 1384 | } | ||
| 1385 | return 0 if $found && ($op eq 'NOT_IN'); | ||
| 1386 | return 0 if !$found && ($op eq 'IN'); | ||
| 1387 | # SQL NULL semantics: NOT IN with NULL in subquery is UNKNOWN | ||
| 1388 | return 0 if $has_null && !$found && ($op eq 'NOT_IN'); | ||
| 1389 | } | ||
| 1390 | elsif ($op eq 'CMP') { | ||
| 1391 | return 0 if @rows > 1; | ||
| 1392 | my $rhs; | ||
| 1393 | if (@rows == 0) { | ||
| 1394 | $rhs = undef; | ||
| 1395 | } | ||
| 1396 | else { | ||
| 1397 | my @rv = values %{ $rows[0] }; | ||
| 1398 | $rhs = $rv[0]; | ||
| 1399 | } | ||
| 1400 | return 0 unless defined $rhs; | ||
| 1401 | my $lhs = defined($row->{$c->{col}}) ? $row->{$c->{col}} : ''; | ||
| 1402 | my $cop = $c->{cmp_op}; | ||
| 1403 | my $num = (($lhs =~ /^-?\d+\.?\d*$/) && ($rhs =~ /^-?\d+\.?\d*$/)); | ||
| 1404 | if ($cop eq '=') { | ||
| 1405 | return 0 unless $num ? ($lhs == $rhs) : ($lhs eq $rhs); | ||
| 1406 | } | ||
| 1407 | elsif (($cop eq '!=') || ($cop eq '<>')) { | ||
| 1408 | return 0 unless $num ? ($lhs != $rhs) : ($lhs ne $rhs); | ||
| 1409 | } | ||
| 1410 | elsif ($cop eq '<') { | ||
| 1411 | return 0 unless $num ? ($lhs < $rhs) : ($lhs lt $rhs); | ||
| 1412 | } | ||
| 1413 | elsif ($cop eq '>') { | ||
| 1414 | return 0 unless $num ? ($lhs > $rhs) : ($lhs gt $rhs); | ||
| 1415 | } | ||
| 1416 | elsif ($cop eq '<=') { | ||
| 1417 | return 0 unless $num ? ($lhs <= $rhs) : ($lhs le $rhs); | ||
| 1418 | } | ||
| 1419 | elsif ($cop eq '>=') { | ||
| 1420 | return 0 unless $num ? ($lhs >= $rhs) : ($lhs ge $rhs); | ||
| 1421 | } | ||
| 1422 | } | ||
| 1423 | } | ||
| 1424 | return 1; | ||
| 1425 | }; | ||
| 1426 | } | ||
| 1427 | |||
| 1428 | # --------------------------------------------------------------------------- | ||
| 1429 | # Derived table: FROM (SELECT ...) AS alias [WHERE ...] [ORDER BY ...] | ||
| 1430 | # | ||
| 1431 | # Evaluates the inner SELECT, materialises the result as an in-memory | ||
| 1432 | # virtual table, then applies the outer WHERE/ORDER BY/LIMIT/OFFSET. | ||
| 1433 | # --------------------------------------------------------------------------- | ||
| 1434 | sub _exec_derived_table { | ||
| 1435 | my($self, $sql) = @_; | ||
| 1436 | |||
| 1437 | # Parse: SELECT outer_cols FROM (inner_sql) AS alias [WHERE ...] [ORDER BY ...] [LIMIT] [OFFSET] | ||
| 1438 | # Step 1: find the outer SELECT list | ||
| 1439 | unless ($sql =~ /^SELECT\s+(.+?)\s+FROM\s*\(/si) { | ||
| 1440 | return { type=>'error', message=>"Cannot parse derived table query" }; | ||
| 1441 | } | ||
| 1442 | my $outer_cols_str = $1; | ||
| 1443 | |||
| 1444 | # Step 2: extract the (inner_sql) AS alias part using paren matching | ||
| 1445 | my $from_pos = index(lc($sql), 'from'); | ||
| 1446 | my $paren_start = index($sql, '(', $from_pos); | ||
| 1447 | unless ($paren_start >= 0) { | ||
| 1448 | return { type=>'error', message=>"Cannot find subquery in FROM clause" }; | ||
| 1449 | } | ||
| 1450 | |||
| 1451 | my($inner_sql, $close_pos) = _extract_paren_content($sql, $paren_start); | ||
| 1452 | unless (defined $inner_sql) { | ||
| 1453 | return { type=>'error', message=>"Unmatched parentheses in FROM clause" }; | ||
| 1454 | } | ||
| 1455 | $inner_sql =~ s/^\s+|\s+$//g; | ||
| 1456 | |||
| 1457 | # Step 3: parse alias and trailing clauses after the closing paren | ||
| 1458 | my $after = substr($sql, $close_pos + 1); | ||
| 1459 | $after =~ s/^\s+//; | ||
| 1460 | |||
| 1461 | my $alias; | ||
| 1462 | if ($after =~ s/^(?:AS\s+)?(\w+)\s*//i) { | ||
| 1463 | $alias = $1; | ||
| 1464 | } | ||
| 1465 | else { | ||
| 1466 | $alias = 'subq'; | ||
| 1467 | } | ||
| 1468 | |||
| 1469 | # Step 4: parse outer WHERE / ORDER BY / LIMIT / OFFSET | ||
| 1470 | my %outer_opts; | ||
| 1471 | if ($after =~ s/\bLIMIT\s+(\d+)//i) { | ||
| 1472 | $outer_opts{limit} = $1; | ||
| 1473 | } | ||
| 1474 | if ($after =~ s/\bOFFSET\s+(\d+)//i) { | ||
| 1475 | $outer_opts{offset} = $1; | ||
| 1476 | } | ||
| 1477 | if ($after =~ s/\bORDER\s+BY\s+([\w.]+)(?:\s+(ASC|DESC))?//i) { | ||
| 1478 | $outer_opts{order_by} = $1; | ||
| 1479 | $outer_opts{order_dir} = ($2 || 'ASC'); | ||
| 1480 | my @onames; | ||
| 1481 | unless ($outer_cols_str =~ /^\s*(?:\w+\.)?\*\s*$/) { | ||
| 1482 | @onames = map { _order_name_of($_) } split(/\s*,\s*/, $outer_cols_str); | ||
| 1483 | } | ||
| 1484 | my($obe, $obk) = _resolve_order_ordinal_scalar($outer_opts{order_by}, [ @onames ]); | ||
| 1485 | return { type=>'error', message=>$obe } if $obe ne ''; | ||
| 1486 | $outer_opts{order_by} = $obk; | ||
| 1487 | } | ||
| 1488 | my $outer_having = ''; | ||
| 1489 | if ($after =~ s/\bHAVING\s+(.+?)(?=\s*$)//si) { | ||
| 1490 | $outer_having = $1; | ||
| 1491 | $outer_having =~ s/^\s+|\s+$//g; | ||
| 1492 | } | ||
| 1493 | my @outer_gb; | ||
| 1494 | if ($after =~ s/\bGROUP\s+BY\s+([\w.,\s]+?)(?=\s*$)//si) { | ||
| 1495 | @outer_gb = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $1; | ||
| 1496 | } | ||
| 1497 | |||
| 1498 | my $outer_where_str = ''; | ||
| 1499 | if ($after =~ /\bWHERE\s+(.+)/si) { | ||
| 1500 | $outer_where_str = $1; | ||
| 1501 | $outer_where_str =~ s/^\s+|\s+$//g; | ||
| 1502 | } | ||
| 1503 | |||
| 1504 | # Step 5: execute the inner query (recursing through execute_with_subquery) | ||
| 1505 | my $inner_res = $self->execute_with_subquery($inner_sql); | ||
| 1506 | if (!$inner_res || ($inner_res->{type} eq 'error')) { | ||
| 1507 | my $msg = $inner_res ? $inner_res->{message} : $errstr; | ||
| 1508 | return { type=>'error', message=>"Derived table subquery error: $msg" }; | ||
| 1509 | } | ||
| 1510 | |||
| 1511 | my @inner_rows = @{ $inner_res->{data} || [] }; | ||
| 1512 | |||
| 1513 | # Step 6: qualify column names with alias (for outer WHERE resolution) | ||
| 1514 | my @qualified_rows; | ||
| 1515 | for my $r (@inner_rows) { | ||
| 1516 | my %qr; | ||
| 1517 | for my $k (keys %$r) { | ||
| 1518 | |||
| 1519 | # Strip existing alias prefix if any, re-prefix with outer alias | ||
| 1520 | my $bare = ($k =~ /\.(\w+)$/) ? $1 : $k; | ||
| 1521 | $qr{"$alias.$bare"} = $r->{$k}; | ||
| 1522 | $qr{$bare} = $r->{$k}; # also keep bare for convenience | ||
| 1523 | } | ||
| 1524 | push @qualified_rows, { %qr }; | ||
| 1525 | } | ||
| 1526 | |||
| 1527 | # Step 7: apply outer WHERE | ||
| 1528 | if ($outer_where_str =~ /\S/) { | ||
| 1529 | my $conds = $self->_parse_conditions_with_subq($outer_where_str); | ||
| 1530 | my $filter = $self->_compile_where_with_subq($conds); | ||
| 1531 | @qualified_rows = grep { $filter->($_) } @qualified_rows; | ||
| 1532 | } | ||
| 1533 | |||
| 1534 | # An aggregate or a GROUP BY in the outer SELECT list consumes the | ||
| 1535 | # materialised rows, so ORDER BY / LIMIT / OFFSET have to be applied to | ||
| 1536 | # the aggregated result instead of to the input. | ||
| 1537 | my $outer_agg = (@outer_gb || ($outer_having ne '') | ||
| 1538 | || ($outer_cols_str =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i)) ? 1 : 0; | ||
| 1539 | |||
| 1540 | # Step 8: ORDER BY | ||
| 1541 | if ((my $ob = $outer_opts{order_by}) && !$outer_agg) { | ||
| 1542 | my $dir = lc($outer_opts{order_dir} || 'asc'); | ||
| 1543 | # Rows are keyed "alias.col"; fall back to the bare column name so | ||
| 1544 | # that an unqualified sort key still resolves. The fallback key is | ||
| 1545 | # computed once here: deriving it inside the comparator produced an | ||
| 1546 | # undefined hash subscript whenever the key had no alias prefix. | ||
| 1547 | my $obb = ($ob =~ /\.(\w+)$/) ? $1 : $ob; | ||
| 1548 | @qualified_rows = sort { | ||
| 1549 | my $va = defined($a->{$ob}) ? $a->{$ob} : $a->{$obb}; | ||
| 1550 | my $vb = defined($b->{$ob}) ? $b->{$ob} : $b->{$obb}; | ||
| 1551 | my $cmp = (defined($va) && ($va =~ /^-?\d+\.?\d*$/) && | ||
| 1552 | defined($vb) && ($vb =~ /^-?\d+\.?\d*$/)) | ||
| 1553 | ? ($va <=> $vb) | ||
| 1554 | : (($va || '') cmp ($vb || '')); | ||
| 1555 | ($dir eq 'desc') ? -$cmp : $cmp; | ||
| 1556 | } @qualified_rows; | ||
| 1557 | } | ||
| 1558 | |||
| 1559 | # Step 9: OFFSET / LIMIT | ||
| 1560 | unless ($outer_agg) { | ||
| 1561 | my $off = ($outer_opts{offset} || 0); | ||
| 1562 | @qualified_rows = splice(@qualified_rows, $off) if $off; | ||
| 1563 | if (defined $outer_opts{limit}) { | ||
| 1564 | my $last = $outer_opts{limit} - 1; | ||
| 1565 | $last = $#qualified_rows if $last > $#qualified_rows; | ||
| 1566 | @qualified_rows = @qualified_rows[0..$last]; | ||
| 1567 | } | ||
| 1568 | } | ||
| 1569 | |||
| 1570 | # Step 10: outer column projection | ||
| 1571 | my @proj_rows; | ||
| 1572 | if ($outer_agg) { | ||
| 1573 | my @specs = parse_col_list($outer_cols_str); | ||
| 1574 | @proj_rows = group_and_aggregate([ @qualified_rows ], [ @specs ], | ||
| 1575 | [ @outer_gb ], $outer_having); | ||
| 1576 | if (my $ob = $outer_opts{order_by}) { | ||
| 1577 | my $dir = lc($outer_opts{order_dir} || 'asc'); | ||
| 1578 | @proj_rows = sort { | ||
| 1579 | my $va = defined($a->{$ob}) ? $a->{$ob} : ''; | ||
| 1580 | my $vb = defined($b->{$ob}) ? $b->{$ob} : ''; | ||
| 1581 | my $cmp = (($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/)) | ||
| 1582 | ? ($va <=> $vb) : ($va cmp $vb); | ||
| 1583 | ($dir eq 'desc') ? -$cmp : $cmp; | ||
| 1584 | } @proj_rows; | ||
| 1585 | } | ||
| 1586 | my $off = ($outer_opts{offset} || 0); | ||
| 1587 | @proj_rows = splice(@proj_rows, $off) if $off; | ||
| 1588 | if (defined $outer_opts{limit}) { | ||
| 1589 | my $last = $outer_opts{limit} - 1; | ||
| 1590 | $last = $#proj_rows if $last > $#proj_rows; | ||
| 1591 | @proj_rows = @proj_rows[0..$last]; | ||
| 1592 | } | ||
| 1593 | } | ||
| 1594 | elsif ($outer_cols_str =~ /^\s*\*\s*$/) { | ||
| 1595 | @proj_rows = @qualified_rows; | ||
| 1596 | } | ||
| 1597 | else { | ||
| 1598 | my @want = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /,/, $outer_cols_str; | ||
| 1599 | for my $r (@qualified_rows) { | ||
| 1600 | my %p; | ||
| 1601 | for my $w (@want) { | ||
| 1602 | if (exists $r->{$w}) { | ||
| 1603 | $p{$w} = $r->{$w}; | ||
| 1604 | } | ||
| 1605 | elsif ($w =~ /^$alias\.(\w+)$/ && exists $r->{$1}) { | ||
| 1606 | $p{$w} = $r->{$1}; | ||
| 1607 | } | ||
| 1608 | else { | ||
| 1609 | |||
| 1610 | # bare name search | ||
| 1611 | for my $k (keys %$r) { | ||
| 1612 | if (($k =~ /\.\Q$w\E$/) || ($k eq $w)) { | ||
| 1613 | $p{$w} = $r->{$k}; | ||
| 1614 | last; | ||
| 1615 | } | ||
| 1616 | } | ||
| 1617 | } | ||
| 1618 | } | ||
| 1619 | push @proj_rows, { %p }; | ||
| 1620 | } | ||
| 1621 | } | ||
| 1622 | |||
| 1623 | return { type=>'rows', data=>[ @proj_rows ] }; | ||
| 1624 | } | ||
| 1625 | |||
| 1626 | # --------------------------------------------------------------------------- | ||
| 1627 | # Scalar subquery in SELECT list | ||
| 1628 | # SELECT (SELECT agg_col FROM t WHERE ...) AS label, other_col FROM main_tbl ... | ||
| 1629 | # --------------------------------------------------------------------------- | ||
| 1630 | sub _exec_scalar_select_subquery { | ||
| 1631 | my($self, $sql) = @_; | ||
| 1632 | |||
| 1633 | # Strategy: collect all scalar subqueries in the SELECT list, | ||
| 1634 | # evaluate each, replace with the literal value, then execute the rest. | ||
| 1635 | |||
| 1636 | # Find all top-level (SELECT ...) AS alias in the SELECT list | ||
| 1637 | # For simplicity: expand iteratively like WHERE subqueries | ||
| 1638 | my $expanded = $self->_expand_where_subqueries($sql, {}); | ||
| 1639 | return $expanded if ref($expanded) eq 'HASH'; | ||
| 1640 | return $self->execute($expanded); | ||
| 1641 | } | ||
| 1642 | |||
| 1643 | # --------------------------------------------------------------------------- | ||
| 1644 | # Extract content between matching parens starting at $start_pos. | ||
| 1645 | # Returns ($content_without_outer_parens, $close_paren_pos). | ||
| 1646 | # --------------------------------------------------------------------------- | ||
| 1647 | sub _extract_paren_content { | ||
| 1648 | my($sql, $start_pos) = @_; | ||
| 1649 | my $len = length($sql); | ||
| 1650 | my $depth = 0; | ||
| 1651 | my $in_str = 0; | ||
| 1652 | for my $i ($start_pos .. $len-1) { | ||
| 1653 | my $ch = substr($sql, $i, 1); | ||
| 1654 | if (($ch eq "'") && !$in_str) { | ||
| 1655 | $in_str = 1; | ||
| 1656 | } | ||
| 1657 | elsif (($ch eq "'") && $in_str) { | ||
| 1658 | $in_str = 0; | ||
| 1659 | } | ||
| 1660 | elsif (!$in_str) { | ||
| 1661 | if ($ch eq '(') { | ||
| 1662 | $depth++; | ||
| 1663 | } | ||
| 1664 | elsif ($ch eq ')') { | ||
| 1665 | $depth--; | ||
| 1666 | if ($depth == 0) { | ||
| 1667 | return (substr($sql, $start_pos+1, $i-$start_pos-1), $i); | ||
| 1668 | } | ||
| 1669 | } | ||
| 1670 | } | ||
| 1671 | } | ||
| 1672 | return (undef, undef); | ||
| 1673 | } | ||
| 1674 | |||
| 1675 | ############################################################################### | ||
| 1676 | # Index internals | ||
| 1677 | ############################################################################### | ||
| 1678 | |||
| 1679 | sub _idx_file { | ||
| 1680 | my($self, $table, $idxname) = @_; | ||
| 1681 | File::Spec->catfile($self->{base_dir}, $self->{db_name}, "$table.$idxname.idx"); | ||
| 1682 | } | ||
| 1683 | |||
| 1684 | sub _encode_key { | ||
| 1685 | my($type, $keysize, $val) = @_; | ||
| 1686 | $val = '' unless defined $val; | ||
| 1687 | if ($type eq 'INT') { | ||
| 1688 | my $iv = _looks_numeric($val) ? int($val) : 0; | ||
| 1689 | $iv = INT_MAX if $iv > INT_MAX; | ||
| 1690 | $iv = INT_MIN if $iv < INT_MIN; | ||
| 1691 | return pack('N', ($iv & 0xFFFFFFFF) ^ 0x80000000); | ||
| 1692 | } | ||
| 1693 | elsif ($type eq 'FLOAT') { | ||
| 1694 | |||
| 1695 | # A value that is not numeric encodes as 0, exactly as it is | ||
| 1696 | # stored by _pack_record. The test is made here rather than left | ||
| 1697 | # to pack() so that -w stays quiet: an index on a FLOAT column | ||
| 1698 | # used to make a single INSERT emit two "isn't numeric" warnings. | ||
| 1699 | # my $packed = pack('d>', $val+0); | ||
| 1700 | my $packed = pack('d', _looks_numeric($val) ? $val+0 : 0); | ||
| 1701 | $packed = reverse($packed) if unpack("C", pack("S", 1)); | ||
| 1702 | |||
| 1703 | my @b = unpack('C8', $packed); | ||
| 1704 | if ($b[0] & 0x80) { | ||
| 1705 | @b = map { $_ ^ 0xFF } @b; | ||
| 1706 | } | ||
| 1707 | else { | ||
| 1708 | $b[0] ^= 0x80; | ||
| 1709 | } | ||
| 1710 | return pack('C8', @b); | ||
| 1711 | } | ||
| 1712 | else { | ||
| 1713 | my $sv = substr($val, 0, $keysize); | ||
| 1714 | $sv .= "\x00" x ($keysize - length($sv)); | ||
| 1715 | return $sv; | ||
| 1716 | } | ||
| 1717 | } | ||
| 1718 | |||
| 1719 | |||
| 1720 | sub _idx_entry_size { | ||
| 1721 | $_[0]->{keysize} + REC_NO_SIZE; | ||
| 1722 | } | ||
| 1723 | |||
| 1724 | sub _idx_read_all { | ||
| 1725 | my($self, $table, $ix) = @_; | ||
| 1726 | my $idx_file = $self->_idx_file($table, $ix->{name}); | ||
| 1727 | my $entry_size = _idx_entry_size($ix); | ||
| 1728 | my @entries; | ||
| 1729 | return [ @entries ] unless -f $idx_file; | ||
| 1730 | local *FH; | ||
| 1731 | open(FH, "< $idx_file") or return [ @entries ]; | ||
| 1732 | binmode FH; | ||
| 1733 | _lock_sh(\*FH); | ||
| 1734 | my $magic = ''; | ||
| 1735 | read(FH, $magic, IDX_MAGIC_LEN); | ||
| 1736 | unless ($magic eq IDX_MAGIC) { | ||
| 1737 | _unlock(\*FH); | ||
| 1738 | close FH; | ||
| 1739 | return [ @entries ]; | ||
| 1740 | } | ||
| 1741 | while (1) { | ||
| 1742 | my $entry = ''; | ||
| 1743 | my $n = read(FH, $entry, $entry_size); | ||
| 1744 | last unless defined($n) && ($n == $entry_size); | ||
| 1745 | push @entries, [ substr($entry, 0, $ix->{keysize}), unpack('N', substr($entry, $ix->{keysize}, REC_NO_SIZE)) ]; | ||
| 1746 | } | ||
| 1747 | _unlock(\*FH); | ||
| 1748 | close FH; | ||
| 1749 | return [ @entries ]; | ||
| 1750 | } | ||
| 1751 | |||
| 1752 | sub _idx_write_all { | ||
| 1753 | my($self, $table, $ix, $entries) = @_; | ||
| 1754 | my $idx_file = $self->_idx_file($table, $ix->{name}); | ||
| 1755 | local *FH; | ||
| 1756 | unless (-f $idx_file) { | ||
| 1757 | open(FH, "> $idx_file") or return $self->_err("Cannot create index: $!"); | ||
| 1758 | close FH; | ||
| 1759 | } | ||
| 1760 | # Open without truncating, so that the file is emptied only after the | ||
| 1761 | # exclusive lock is held. Opening with '>' truncates at open() time, | ||
| 1762 | # which destroys a concurrent writer's data while we wait for the lock. | ||
| 1763 | open(FH, "+< $idx_file") or return $self->_err("Cannot write index: $!"); | ||
| 1764 | binmode FH; | ||
| 1765 | _autoflush(\*FH); | ||
| 1766 | _lock_ex(\*FH); | ||
| 1767 | truncate(FH, 0); | ||
| 1768 | seek(FH, 0, 0); | ||
| 1769 | # The whole image is assembled first and written with a single print, | ||
| 1770 | # so autoflush costs one write() per rebuild rather than one per entry. | ||
| 1771 | my $image = IDX_MAGIC; | ||
| 1772 | for my $e (@$entries) { | ||
| 1773 | $image .= $e->[0] . pack('N', $e->[1]); | ||
| 1774 | } | ||
| 1775 | my $ok = print FH $image; | ||
| 1776 | unless ($ok) { | ||
| 1777 | my $e = $!; | ||
| 1778 | _unlock(\*FH); | ||
| 1779 | close FH; | ||
| 1780 | return $self->_err("Cannot write index: $e"); | ||
| 1781 | } | ||
| 1782 | _unlock(\*FH); | ||
| 1783 | unless (close FH) { | ||
| 1784 | return $self->_err("Cannot flush index: $!"); | ||
| 1785 | } | ||
| 1786 | return 1; | ||
| 1787 | } | ||
| 1788 | |||
| 1789 | sub _idx_bisect { | ||
| 1790 | my($entries, $key_bytes) = @_; | ||
| 1791 | my($lo, $hi) = (0, scalar @$entries); | ||
| 1792 | while ($lo < $hi) { | ||
| 1793 | my $mid = int(($lo + $hi) / 2); | ||
| 1794 | if ($entries->[$mid][0] lt $key_bytes) { | ||
| 1795 | $lo = $mid + 1; | ||
| 1796 | } | ||
| 1797 | else { | ||
| 1798 | $hi = $mid; | ||
| 1799 | } | ||
| 1800 | } | ||
| 1801 | return $lo; | ||
| 1802 | } | ||
| 1803 | |||
| 1804 | sub _idx_lookup_exact { | ||
| 1805 | my($self, $table, $ix, $val) = @_; | ||
| 1806 | my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val); | ||
| 1807 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 1808 | my $pos = _idx_bisect($entries, $key_bytes); | ||
| 1809 | while (($pos < @$entries) && ($entries->[$pos][0] eq $key_bytes)) { | ||
| 1810 | return $pos; | ||
| 1811 | } | ||
| 1812 | return -1; | ||
| 1813 | } | ||
| 1814 | |||
| 1815 | sub _idx_insert { | ||
| 1816 | my($self, $table, $ix, $val, $rec_no) = @_; | ||
| 1817 | my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val); | ||
| 1818 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 1819 | my $pos = _idx_bisect($entries, $key_bytes); | ||
| 1820 | splice(@$entries, $pos, 0, [$key_bytes, $rec_no]); | ||
| 1821 | return $self->_idx_write_all($table, $ix, $entries); | ||
| 1822 | } | ||
| 1823 | |||
| 1824 | sub _idx_delete { | ||
| 1825 | my($self, $table, $ix, $val, $rec_no) = @_; | ||
| 1826 | my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $val); | ||
| 1827 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 1828 | my $pos = _idx_bisect($entries, $key_bytes); | ||
| 1829 | my $deleted = 0; | ||
| 1830 | while (($pos < @$entries) && ($entries->[$pos][0] eq $key_bytes)) { | ||
| 1831 | if ($entries->[$pos][1] == $rec_no) { | ||
| 1832 | splice(@$entries, $pos, 1); | ||
| 1833 | $deleted++; | ||
| 1834 | last; | ||
| 1835 | } | ||
| 1836 | $pos++; | ||
| 1837 | } | ||
| 1838 | return $self->_idx_write_all($table, $ix, $entries) if $deleted; | ||
| 1839 | return 1; | ||
| 1840 | } | ||
| 1841 | |||
| 1842 | sub _idx_range { | ||
| 1843 | my($self, $table, $ix, $lo_val, $lo_inc, $hi_val, $hi_inc) = @_; | ||
| 1844 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 1845 | return [] unless @$entries; | ||
| 1846 | |||
| 1847 | my $lo_pos = 0; | ||
| 1848 | if (defined $lo_val) { | ||
| 1849 | my $lo_key = _encode_key($ix->{coltype}, $ix->{keysize}, $lo_val); | ||
| 1850 | $lo_pos = _idx_bisect($entries, $lo_key); | ||
| 1851 | $lo_pos++ while !$lo_inc && ($lo_pos < @$entries) && ($entries->[$lo_pos][0] eq $lo_key); | ||
| 1852 | } | ||
| 1853 | my $hi_pos = scalar @$entries; | ||
| 1854 | if (defined $hi_val) { | ||
| 1855 | my $hi_key = _encode_key($ix->{coltype}, $ix->{keysize}, $hi_val); | ||
| 1856 | my $p = _idx_bisect($entries, $hi_key); | ||
| 1857 | $p++ while $hi_inc && ($p < @$entries) && ($entries->[$p][0] eq $hi_key); | ||
| 1858 | $hi_pos = $p; | ||
| 1859 | } | ||
| 1860 | return [ map { $entries->[$_][1] } $lo_pos .. $hi_pos-1 ]; | ||
| 1861 | } | ||
| 1862 | |||
| 1863 | sub _rebuild_index { | ||
| 1864 | my($self, $table, $idxname) = @_; | ||
| 1865 | my $sch = $self->_load_schema($table) or return undef; | ||
| 1866 | my $ix = $sch->{indexes}{$idxname}; | ||
| 1867 | return $self->_err("Index '$idxname' not found") unless $ix; | ||
| 1868 | my $dat = $self->_file($table, 'dat'); | ||
| 1869 | my $recsize = $sch->{recsize}; | ||
| 1870 | my @entries; | ||
| 1871 | if (-f $dat) { | ||
| 1872 | local *FH; | ||
| 1873 | open(FH, "< $dat") or return $self->_err("Cannot read dat: $!"); | ||
| 1874 | binmode FH; | ||
| 1875 | _lock_sh(\*FH); | ||
| 1876 | my $rec_no = 0; | ||
| 1877 | while (1) { | ||
| 1878 | my $raw = ''; | ||
| 1879 | my $n = read(FH, $raw, $recsize); | ||
| 1880 | last unless defined($n) && ($n == $recsize); | ||
| 1881 | if (substr($raw, 0, 1) ne RECORD_DELETED) { | ||
| 1882 | my $row = $self->_unpack_record($sch, $raw); | ||
| 1883 | push @entries, [ _encode_key($ix->{coltype}, $ix->{keysize}, $row->{$ix->{col}}), $rec_no ]; | ||
| 1884 | } | ||
| 1885 | $rec_no++; | ||
| 1886 | } | ||
| 1887 | _unlock(\*FH); | ||
| 1888 | close FH; | ||
| 1889 | } | ||
| 1890 | @entries = sort { $a->[0] cmp $b->[0] } @entries; | ||
| 1891 | return $self->_idx_write_all($table, $ix, [ @entries ]); | ||
| 1892 | } | ||
| 1893 | |||
| 1894 | sub _find_index_for_conds { | ||
| 1895 | my($self, $table, $sch, $conds) = @_; | ||
| 1896 | return undef unless $conds && @$conds; | ||
| 1897 | return undef unless %{$sch->{indexes}}; | ||
| 1898 | my %col2ix; | ||
| 1899 | for my $ix (values %{$sch->{indexes}}) { | ||
| 1900 | $col2ix{$ix->{col}} = $ix; | ||
| 1901 | } | ||
| 1902 | for my $c (@$conds) { | ||
| 1903 | my $ix = $col2ix{$c->{col}} or next; | ||
| 1904 | my $op = $c->{op}; | ||
| 1905 | if ($op eq '=') { | ||
| 1906 | my $key_bytes = _encode_key($ix->{coltype}, $ix->{keysize}, $c->{val}); | ||
| 1907 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 1908 | my $pos = _idx_bisect($entries, $key_bytes); | ||
| 1909 | my @rec_nos; | ||
| 1910 | while (($pos < @$entries) && ($entries->[$pos][0] eq $key_bytes)) { | ||
| 1911 | push @rec_nos, $entries->[$pos][1]; | ||
| 1912 | $pos++; | ||
| 1913 | } | ||
| 1914 | return [ @rec_nos ]; | ||
| 1915 | } | ||
| 1916 | elsif ($op eq '<') { | ||
| 1917 | return $self->_idx_range($table, $ix, undef, 0, $c->{val}, 0); | ||
| 1918 | } | ||
| 1919 | elsif ($op eq '<=') { | ||
| 1920 | return $self->_idx_range($table, $ix, undef, 0, $c->{val}, 1); | ||
| 1921 | } | ||
| 1922 | elsif ($op eq '>') { | ||
| 1923 | return $self->_idx_range($table, $ix, $c->{val}, 0, undef, 0); | ||
| 1924 | } | ||
| 1925 | elsif ($op eq '>=') { | ||
| 1926 | return $self->_idx_range($table, $ix, $c->{val}, 1, undef, 0); | ||
| 1927 | } | ||
| 1928 | } | ||
| 1929 | return undef; | ||
| 1930 | } | ||
| 1931 | |||
| 1932 | # _try_index_and_range($table, $sch, $where_expr) | ||
| 1933 | # | ||
| 1934 | # Attempt to satisfy a two-sided range or BETWEEN predicate using an index. | ||
| 1935 | # Recognises these WHERE patterns (same column, values numeric or quoted): | ||
| 1936 | # col OP1 val1 AND col OP2 val2 (e.g. id > 5 AND id < 10) | ||
| 1937 | # col BETWEEN val1 AND val2 | ||
| 1938 | # Returns an arrayref of matching record numbers, or undef if no index | ||
| 1939 | # can be applied (caller falls through to a full table scan). | ||
| 1940 | # | ||
| 1941 | sub _try_index_and_range { | ||
| 1942 | my($self, $table, $sch, $where_expr) = @_; | ||
| 1943 | return undef unless %{$sch->{indexes}}; | ||
| 1944 | my %col2ix; | ||
| 1945 | for my $ix (values %{$sch->{indexes}}) { | ||
| 1946 | $col2ix{$ix->{col}} = $ix; | ||
| 1947 | } | ||
| 1948 | my $VAL = qr/(?:'([^']*)'|(-?\d+\.?\d*))/; | ||
| 1949 | my $OP = qr/(<=|>=|<|>)/; | ||
| 1950 | # BETWEEN col BETWEEN val1 AND val2 | ||
| 1951 | if ($where_expr =~ /^(\w+)\s+BETWEEN\s+$VAL\s+AND\s+$VAL\s*$/i) { | ||
| 1952 | my($col, $lo_s, $lo_n, $hi_s, $hi_n) = ($1, $2, $3, $4, $5); | ||
| 1953 | my $lo = defined($lo_s) ? $lo_s : $lo_n; | ||
| 1954 | my $hi = defined($hi_s) ? $hi_s : $hi_n; | ||
| 1955 | my $ix = $col2ix{$col} or return undef; | ||
| 1956 | return $self->_idx_range($table, $ix, $lo, 1, $hi, 1); | ||
| 1957 | } | ||
| 1958 | # AND: col OP val AND col OP val (same column) | ||
| 1959 | if ($where_expr =~ /^(\w+)\s+$OP\s+$VAL\s+AND\s+\1\s+$OP\s+$VAL\s*$/i) { | ||
| 1960 | my($col, $op1, $v1s, $v1n, $op2, $v2s, $v2n) = ($1, $2, $3, $4, $5, $6, $7); | ||
| 1961 | my $v1 = defined($v1s) ? $v1s : $v1n; | ||
| 1962 | my $v2 = defined($v2s) ? $v2s : $v2n; | ||
| 1963 | my $ix = $col2ix{$col} or return undef; | ||
| 1964 | # Determine lo (lower bound) and hi (upper bound) | ||
| 1965 | my($lo, $lo_inc, $hi, $hi_inc); | ||
| 1966 | if ($op1 eq '>' || $op1 eq '>=') { | ||
| 1967 | ($lo, $lo_inc) = ($v1, $op1 eq '>='); | ||
| 1968 | ($hi, $hi_inc) = ($v2, $op2 eq '<='); | ||
| 1969 | } | ||
| 1970 | else { | ||
| 1971 | ($lo, $lo_inc) = ($v2, $op2 eq '>='); | ||
| 1972 | ($hi, $hi_inc) = ($v1, $op1 eq '<='); | ||
| 1973 | } | ||
| 1974 | return $self->_idx_range($table, $ix, $lo, $lo_inc, $hi, $hi_inc); | ||
| 1975 | } | ||
| 1976 | return undef; | ||
| 1977 | } | ||
| 1978 | |||
| 1979 | # _try_index_partial_and($table, $sch, $where_expr) | ||
| 1980 | # | ||
| 1981 | # For AND expressions involving multiple columns, pick the single indexed | ||
| 1982 | # column that yields the smallest candidate set and return its record | ||
| 1983 | # numbers. The caller applies the full WHERE predicate as a post-filter, | ||
| 1984 | # so correctness is guaranteed regardless of which index is chosen. | ||
| 1985 | # | ||
| 1986 | # Recognises AND-connected atoms of the form: | ||
| 1987 | # col = val col > val col >= val col < val col <= val | ||
| 1988 | # (quoted or numeric values; no subexpressions, BETWEEN, IN, OR, NOT) | ||
| 1989 | # | ||
| 1990 | # Returns an arrayref of candidate record numbers, or undef when no | ||
| 1991 | # usable index is found (caller falls through to a full table scan). | ||
| 1992 | # | ||
| 1993 | sub _try_index_partial_and { | ||
| 1994 | my($self, $table, $sch, $where_expr) = @_; | ||
| 1995 | return undef unless %{$sch->{indexes}}; | ||
| 1996 | # Only handle pure AND expressions (no OR/NOT/BETWEEN/IN/subqueries) | ||
| 1997 | return undef if $where_expr =~ /\b(?:OR|NOT|BETWEEN|IN)\b/i; | ||
| 1998 | return undef if $where_expr =~ /\(\s*SELECT\b/i; | ||
| 1999 | # Split on AND and collect simple col OP val atoms | ||
| 2000 | my @atoms; | ||
| 2001 | my $VAL = qr/(?:'[^']*'|-?\d+\.?\d*)/; | ||
| 2002 | my $OP = qr/(?:<=|>=|!=|<>|<|>|=)/; | ||
| 2003 | for my $part (split /\bAND\b/i, $where_expr) { | ||
| 2004 | $part =~ s/^\s+|\s+$//g; | ||
| 2005 | if ($part =~ /^(\w+)\s*($OP)\s*($VAL)$/ | ||
| 2006 | || $part =~ /^($VAL)\s*($OP)\s*(\w+)$/) { | ||
| 2007 | # Normalise so col is always on the left | ||
| 2008 | my($col, $op, $val); | ||
| 2009 | if ($part =~ /^(\w+)\s*($OP)\s*($VAL)$/) { | ||
| 2010 | ($col, $op, $val) = ($1, uc($2), $3); | ||
| 2011 | } | ||
| 2012 | else { | ||
| 2013 | # val OP col -- reverse the operator | ||
| 2014 | $part =~ /^($VAL)\s*($OP)\s*(\w+)$/; | ||
| 2015 | my %rev = ('>' => '<', '<' => '>', '>=' => '<=', | ||
| 2016 | '<=' => '>=', '=' => '=', '!=' => '!=', | ||
| 2017 | '<>' => '<>'); | ||
| 2018 | ($col, $op, $val) = ($3, $rev{uc($2)} || uc($2), $1); | ||
| 2019 | } | ||
| 2020 | $val =~ s/^'|'$//g; # strip surrounding quotes | ||
| 2021 | push @atoms, { col => $col, op => $op, val => $val }; | ||
| 2022 | } | ||
| 2023 | else { | ||
| 2024 | return undef; # complex atom -- cannot use index safely | ||
| 2025 | } | ||
| 2026 | } | ||
| 2027 | return undef unless @atoms >= 2; # single atom handled by Case 1/2 | ||
| 2028 | # Build column -> index map | ||
| 2029 | my %col2ix; | ||
| 2030 | for my $ix (values %{$sch->{indexes}}) { | ||
| 2031 | $col2ix{$ix->{col}} = $ix; | ||
| 2032 | } | ||
| 2033 | # Try each atom in turn; return the first index hit | ||
| 2034 | # (equality index preferred over range for a smaller candidate set) | ||
| 2035 | my $best_eq = undef; # record list from an equality match | ||
| 2036 | my $best_rng = undef; # record list from a range match | ||
| 2037 | for my $a (@atoms) { | ||
| 2038 | my $ix = $col2ix{$a->{col}} or next; | ||
| 2039 | my $op = $a->{op}; | ||
| 2040 | next if $op eq '!=' || $op eq '<>'; # inequality gives no benefit | ||
| 2041 | my $recs; | ||
| 2042 | if ($op eq '=') { | ||
| 2043 | my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $a->{val}); | ||
| 2044 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 2045 | my $pos = _idx_bisect($entries, $key); | ||
| 2046 | my @r; | ||
| 2047 | while (($pos < @$entries) && ($entries->[$pos][0] eq $key)) { | ||
| 2048 | push @r, $entries->[$pos][1]; | ||
| 2049 | $pos++; | ||
| 2050 | } | ||
| 2051 | $recs = [ @r ]; | ||
| 2052 | # Equality index: take first found and stop | ||
| 2053 | $best_eq = $recs and last; | ||
| 2054 | } | ||
| 2055 | elsif ($op eq '<') { | ||
| 2056 | $recs = $self->_idx_range($table, $ix, undef, 0, $a->{val}, 0); | ||
| 2057 | } | ||
| 2058 | elsif ($op eq '<=') { | ||
| 2059 | $recs = $self->_idx_range($table, $ix, undef, 0, $a->{val}, 1); | ||
| 2060 | } | ||
| 2061 | elsif ($op eq '>') { | ||
| 2062 | $recs = $self->_idx_range($table, $ix, $a->{val}, 0, undef, 0); | ||
| 2063 | } | ||
| 2064 | elsif ($op eq '>=') { | ||
| 2065 | $recs = $self->_idx_range($table, $ix, $a->{val}, 1, undef, 0); | ||
| 2066 | } | ||
| 2067 | $best_rng = $recs if defined $recs && !defined $best_rng; | ||
| 2068 | } | ||
| 2069 | return $best_eq if defined $best_eq; | ||
| 2070 | return $best_rng; | ||
| 2071 | } | ||
| 2072 | |||
| 2073 | # _try_index_in($table, $sch, $where_expr) | ||
| 2074 | # | ||
| 2075 | # Attempt to satisfy a col IN (v1, v2, ...) or col NOT IN (v1, v2, ...) | ||
| 2076 | # predicate using an index. For IN, performs one equality lookup per value | ||
| 2077 | # and returns the union of matching record numbers. NOT IN is not optimised | ||
| 2078 | # (returns undef so the caller falls through to a full table scan). | ||
| 2079 | # | ||
| 2080 | # The WHERE expression must consist of exactly one IN predicate with a | ||
| 2081 | # literal value list (no sub-selects, no OR/AND, no NOT IN). | ||
| 2082 | # | ||
| 2083 | # Returns an arrayref of candidate record numbers, or undef when no index | ||
| 2084 | # can be applied. | ||
| 2085 | # | ||
| 2086 | sub _try_index_in { | ||
| 2087 | my($self, $table, $sch, $where_expr) = @_; | ||
| 2088 | return undef unless %{$sch->{indexes}}; | ||
| 2089 | # Match: col IN (literal-list) no NOT IN, no sub-select | ||
| 2090 | return undef unless $where_expr =~ /^\s*(\w+)\s+IN\s*\(([^)]*)\)\s*$/si; | ||
| 2091 | my($col, $list_str) = ($1, $2); | ||
| 2092 | # Find index for this column | ||
| 2093 | my $ix; | ||
| 2094 | for my $candidate (values %{$sch->{indexes}}) { | ||
| 2095 | if ($candidate->{col} eq $col) { | ||
| 2096 | $ix = $candidate; | ||
| 2097 | last; | ||
| 2098 | } | ||
| 2099 | } | ||
| 2100 | return undef unless defined $ix; | ||
| 2101 | # Parse the value list | ||
| 2102 | my @vals; | ||
| 2103 | my $ls = $list_str; | ||
| 2104 | while ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) { | ||
| 2105 | my($sv, $nv, $nl) = ($1, $2, $3); | ||
| 2106 | if (defined $nl) { | ||
| 2107 | # NULL in IN list: no index lookup possible for NULL | ||
| 2108 | return undef; | ||
| 2109 | } | ||
| 2110 | elsif (defined $sv) { | ||
| 2111 | (my $x = $sv) =~ s/''/'/g; | ||
| 2112 | push @vals, $x; | ||
| 2113 | } | ||
| 2114 | else { | ||
| 2115 | push @vals, $nv; | ||
| 2116 | } | ||
| 2117 | } | ||
| 2118 | return undef unless @vals; # empty IN list: caller handles | ||
| 2119 | # Perform one equality index lookup per value, union the results | ||
| 2120 | my %seen; | ||
| 2121 | my @rec_nos; | ||
| 2122 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 2123 | for my $val (@vals) { | ||
| 2124 | my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val); | ||
| 2125 | my $pos = _idx_bisect($entries, $key); | ||
| 2126 | while (($pos < @$entries) && ($entries->[$pos][0] eq $key)) { | ||
| 2127 | my $rn = $entries->[$pos][1]; | ||
| 2128 | push @rec_nos, $rn unless $seen{$rn}++; | ||
| 2129 | $pos++; | ||
| 2130 | } | ||
| 2131 | } | ||
| 2132 | return [ @rec_nos ]; | ||
| 2133 | } | ||
| 2134 | |||
| 2135 | # _try_index_or($table, $sch, $where_expr) | ||
| 2136 | # | ||
| 2137 | # Attempt to satisfy a pure OR expression using indexes. | ||
| 2138 | # | ||
| 2139 | # Every atom in the OR chain must be a simple condition that can be served | ||
| 2140 | # by an index on the relevant column. If any atom has no usable index the | ||
| 2141 | # function returns undef and the caller falls through to a full table scan. | ||
| 2142 | # | ||
| 2143 | # Recognised atom forms (same column or different columns): | ||
| 2144 | # col = val col != val (not optimised -- returns undef) | ||
| 2145 | # col OP val (OP: <, <=, >, >=) | ||
| 2146 | # col BETWEEN lo AND hi | ||
| 2147 | # col IN (v1, v2, ...) | ||
| 2148 | # | ||
| 2149 | # Returns an arrayref of deduplicated record numbers, or undef. | ||
| 2150 | # | ||
| 2151 | sub _try_index_or { | ||
| 2152 | my($self, $table, $sch, $where_expr) = @_; | ||
| 2153 | return undef unless %{$sch->{indexes}}; | ||
| 2154 | # Must be a pure OR expression -- no AND, no NOT, no subqueries | ||
| 2155 | return undef if $where_expr =~ /\b(?:AND|NOT)\b/i; | ||
| 2156 | return undef if $where_expr =~ /\(\s*SELECT\b/i; | ||
| 2157 | # Split on OR | ||
| 2158 | my @atoms = DB::Handy::bool_split($where_expr, 'OR'); | ||
| 2159 | return undef unless @atoms >= 2; | ||
| 2160 | # Build column -> index map | ||
| 2161 | my %col2ix; | ||
| 2162 | for my $ix (values %{$sch->{indexes}}) { | ||
| 2163 | $col2ix{$ix->{col}} = $ix; | ||
| 2164 | } | ||
| 2165 | my $VAL = qr/(?:'(?:[^']|'')*'|-?\d+\.?\d*)/; | ||
| 2166 | my $OP = qr/(?:<=|>=|<|>|=)/; | ||
| 2167 | # Collect record numbers for each atom | ||
| 2168 | my %seen; | ||
| 2169 | my @all_recs; | ||
| 2170 | for my $atom (@atoms) { | ||
| 2171 | $atom =~ s/^\s+|\s+$//g; | ||
| 2172 | my $recs; | ||
| 2173 | # col BETWEEN lo AND hi | ||
| 2174 | if ($atom =~ /^(\w+)\s+BETWEEN\s+($VAL)\s+AND\s+($VAL)\s*$/i) { | ||
| 2175 | my($col, $lo, $hi) = ($1, $2, $3); | ||
| 2176 | my $ix = $col2ix{$col} or return undef; | ||
| 2177 | $lo =~ s/^'(.*)'$/$1/s; $hi =~ s/^'(.*)'$/$1/s; | ||
| 2178 | $recs = $self->_idx_range($table, $ix, $lo, 1, $hi, 1); | ||
| 2179 | } | ||
| 2180 | # col IN (val, ...) | ||
| 2181 | elsif ($atom =~ /^(\w+)\s+IN\s*\(([^)]*)\)\s*$/i) { | ||
| 2182 | my($col, $list) = ($1, $2); | ||
| 2183 | my $ix = $col2ix{$col} or return undef; | ||
| 2184 | $recs = $self->_try_index_in($table, $sch, $atom); | ||
| 2185 | return undef unless defined $recs; | ||
| 2186 | } | ||
| 2187 | # col OP val (equality or range, not !=/<>) | ||
| 2188 | elsif ($atom =~ /^(\w+)\s*($OP)\s*($VAL)$/) { | ||
| 2189 | my($col, $op, $val) = ($1, uc($2), $3); | ||
| 2190 | return undef if $op eq '!=' || $op eq '<>'; | ||
| 2191 | my $ix = $col2ix{$col} or return undef; | ||
| 2192 | $val =~ s/^'(.*)'$/$1/s; | ||
| 2193 | if ($op eq '=') { | ||
| 2194 | my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val); | ||
| 2195 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 2196 | my $pos = _idx_bisect($entries, $key); | ||
| 2197 | my @r; | ||
| 2198 | while (($pos < @$entries) && ($entries->[$pos][0] eq $key)) { | ||
| 2199 | push @r, $entries->[$pos][1]; | ||
| 2200 | $pos++; | ||
| 2201 | } | ||
| 2202 | $recs = [ @r ]; | ||
| 2203 | } | ||
| 2204 | elsif ($op eq '<') { $recs = $self->_idx_range($table, $ix, undef, 0, $val, 0) } | ||
| 2205 | elsif ($op eq '<=') { $recs = $self->_idx_range($table, $ix, undef, 0, $val, 1) } | ||
| 2206 | elsif ($op eq '>') { $recs = $self->_idx_range($table, $ix, $val, 0, undef, 0) } | ||
| 2207 | elsif ($op eq '>=') { $recs = $self->_idx_range($table, $ix, $val, 1, undef, 0) } | ||
| 2208 | } | ||
| 2209 | else { | ||
| 2210 | return undef; # complex atom: cannot use index | ||
| 2211 | } | ||
| 2212 | return undef unless defined $recs; | ||
| 2213 | for my $rn (@$recs) { | ||
| 2214 | push @all_recs, $rn unless $seen{$rn}++; | ||
| 2215 | } | ||
| 2216 | } | ||
| 2217 | return [ @all_recs ]; | ||
| 2218 | } | ||
| 2219 | |||
| 2220 | # _try_index_not_in($table, $sch, $where_expr) | ||
| 2221 | # | ||
| 2222 | # Attempt to satisfy a col NOT IN (v1, v2, ...) predicate using an index. | ||
| 2223 | # Collects the record numbers that match the IN list (via index), then | ||
| 2224 | # returns all record numbers in the index that are NOT in that set. | ||
| 2225 | # Efficient when the exclusion list is small relative to total row count. | ||
| 2226 | # | ||
| 2227 | # NULL in the value list causes a fallback to a full table scan (SQL | ||
| 2228 | # semantics: NOT IN with NULL never matches any row). | ||
| 2229 | # | ||
| 2230 | # Returns an arrayref of candidate record numbers, or undef when no index | ||
| 2231 | # can be applied. | ||
| 2232 | # | ||
| 2233 | sub _try_index_not_in { | ||
| 2234 | my($self, $table, $sch, $where_expr) = @_; | ||
| 2235 | return undef unless %{$sch->{indexes}}; | ||
| 2236 | # Match: col NOT IN (literal-list) no sub-select | ||
| 2237 | return undef unless $where_expr =~ /^\s*(\w+)\s+NOT\s+IN\s*\(([^)]*)\)\s*$/si; | ||
| 2238 | my($col, $list_str) = ($1, $2); | ||
| 2239 | # Find index for this column | ||
| 2240 | my $ix; | ||
| 2241 | for my $candidate (values %{$sch->{indexes}}) { | ||
| 2242 | if ($candidate->{col} eq $col) { | ||
| 2243 | $ix = $candidate; | ||
| 2244 | last; | ||
| 2245 | } | ||
| 2246 | } | ||
| 2247 | return undef unless defined $ix; | ||
| 2248 | # Parse the NOT IN value list | ||
| 2249 | my @vals; | ||
| 2250 | my $ls = $list_str; | ||
| 2251 | while ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) { | ||
| 2252 | my($sv, $nv, $nl) = ($1, $2, $3); | ||
| 2253 | if (defined $nl) { return undef } # NULL: fall back to full scan | ||
| 2254 | elsif (defined $sv) { (my $x = $sv) =~ s/''/'/g; push @vals, $x } | ||
| 2255 | else { push @vals, $nv } | ||
| 2256 | } | ||
| 2257 | return undef unless @vals; | ||
| 2258 | # Build set of record numbers to EXCLUDE (those matching the IN list) | ||
| 2259 | my %exclude; | ||
| 2260 | my $entries = $self->_idx_read_all($table, $ix); | ||
| 2261 | for my $val (@vals) { | ||
| 2262 | my $key = _encode_key($ix->{coltype}, $ix->{keysize}, $val); | ||
| 2263 | my $pos = _idx_bisect($entries, $key); | ||
| 2264 | while (($pos < @$entries) && ($entries->[$pos][0] eq $key)) { | ||
| 2265 | $exclude{$entries->[$pos][1]} = 1; | ||
| 2266 | $pos++; | ||
| 2267 | } | ||
| 2268 | } | ||
| 2269 | # Return all record numbers in the index that are NOT excluded | ||
| 2270 | my %seen; | ||
| 2271 | my @rec_nos; | ||
| 2272 | for my $entry (@$entries) { | ||
| 2273 | my $rn = $entry->[1]; | ||
| 2274 | push @rec_nos, $rn unless $exclude{$rn} || $seen{$rn}++; | ||
| 2275 | } | ||
| 2276 | return [ @rec_nos ]; | ||
| 2277 | } | ||
| 2278 | |||
| 2279 | ############################################################################### | ||
| 2280 | # JOIN -- Public entry point | ||
| 2281 | ############################################################################### | ||
| 2282 | # join_select(\@join_specs, \@col_specs, \@where_conds, \%opts) | ||
| 2283 | # | ||
| 2284 | # join_specs : arrayref of hashrefs, in left-to-right order | ||
| 2285 | # { table => 'employees', # physical table name | ||
| 2286 | # alias => 'e', # alias (or same as table) | ||
| 2287 | # type => 'INNER'|'LEFT'|'RIGHT'|'CROSS', | ||
| 2288 | # on_left => 'e.dept_id', # undef for first/CROSS | ||
| 2289 | # on_right => 'd.id', # undef for first/CROSS | ||
| 2290 | # } | ||
| 2291 | # | ||
| 2292 | # col_specs : arrayref of 'alias.col' or 'alias.*' or '*' | ||
| 2293 | # undef = all columns (alias-qualified) | ||
| 2294 | # | ||
| 2295 | # where_conds : arrayref of condition hashrefs (from _parse_join_conditions) | ||
| 2296 | # { lhs_alias, lhs_col, op, rhs_alias, rhs_col, val } | ||
| 2297 | # | ||
| 2298 | # opts : { order_by=>'alias.col'|'col', order_dir=>'ASC', limit=>N, offset=>M } | ||
| 2299 | # | ||
| 2300 | sub join_select { | ||
| 2301 | my($self, $join_specs, $col_specs, $where_conds, $opts) = @_; | ||
| 2302 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 2303 | $opts ||= {}; | ||
| 2304 | $where_conds ||= []; | ||
| 2305 | |||
| 2306 | # ------------------------------------------------------------------ | ||
| 2307 | # Step 1: load schemas; build alias -> { table, schema } map | ||
| 2308 | # ------------------------------------------------------------------ | ||
| 2309 | my %alias_info; # alias => { table, sch, rows(lazy) } | ||
| 2310 | for my $js (@$join_specs) { | ||
| 2311 | my $sch = $self->_load_schema($js->{table}) or return undef; | ||
| 2312 | $alias_info{ $js->{alias} } = { | ||
| 2313 | table => $js->{table}, | ||
| 2314 | sch => $sch, | ||
| 2315 | }; | ||
| 2316 | } | ||
| 2317 | |||
| 2318 | # ------------------------------------------------------------------ | ||
| 2319 | # Step 2: load the leftmost (driving) table fully into memory | ||
| 2320 | # ------------------------------------------------------------------ | ||
| 2321 | my $first = $join_specs->[0]; | ||
| 2322 | my @cur_rows = @{ $self->_scan_table_all($first->{table}, $first->{alias}) }; | ||
| 2323 | return undef unless defined($cur_rows[0]) || !$self->{_last_err}; | ||
| 2324 | |||
| 2325 | # ------------------------------------------------------------------ | ||
| 2326 | # Step 3: for each subsequent table, apply the JOIN | ||
| 2327 | # ------------------------------------------------------------------ | ||
| 2328 | for my $i (1 .. $#$join_specs) { | ||
| 2329 | my $js = $join_specs->[$i]; | ||
| 2330 | my $join_type = uc($js->{type} || 'INNER'); | ||
| 2331 | |||
| 2332 | # Parse ON alias1.col1 = alias2.col2 | ||
| 2333 | # A CROSS JOIN is unconditional, so an ON written on one is accepted | ||
| 2334 | # and ignored rather than checked. | ||
| 2335 | my($on_l_alias, $on_l_col, $on_r_alias, $on_r_col); | ||
| 2336 | if (($join_type ne 'CROSS') && $js->{on_left} && $js->{on_right}) { | ||
| 2337 | ($on_l_alias, $on_l_col) = _split_qualified($js->{on_left}); | ||
| 2338 | ($on_r_alias, $on_r_col) = _split_qualified($js->{on_right}); | ||
| 2339 | |||
| 2340 | # An equality is symmetric, but the code below is not: the left | ||
| 2341 | # operand has to name the accumulated left-hand side and the right | ||
| 2342 | # operand the table being joined in. "ON b.k = a.x" is as valid | ||
| 2343 | # as "ON a.x = b.k", and before 1.09 it produced a silent cross | ||
| 2344 | # join, so the operands are swapped here when they are the other | ||
| 2345 | # way round. | ||
| 2346 | if (defined($on_l_alias) && defined($on_r_alias) | ||
| 2347 | && ($on_l_alias eq $js->{alias}) && ($on_r_alias ne $js->{alias})) { | ||
| 2348 | ($on_l_alias, $on_l_col, $on_r_alias, $on_r_col) = | ||
| 2349 | ($on_r_alias, $on_r_col, $on_l_alias, $on_l_col); | ||
| 2350 | } | ||
| 2351 | |||
| 2352 | # Both operands have to be table-qualified. An unqualified name | ||
| 2353 | # cannot be looked up in a result row, whose keys are all | ||
| 2354 | # "alias.col", so before 1.09 "ON x = k" fell through to the | ||
| 2355 | # Cartesian-product branch without a word. | ||
| 2356 | unless (defined($on_l_alias) && defined($on_r_alias)) { | ||
| 2357 | return $self->_err( | ||
| 2358 | "Unqualified column in the ON clause of JOIN " | ||
| 2359 | . "$js->{table}; write ON <table>.<col> = <table>.<col>"); | ||
| 2360 | } | ||
| 2361 | |||
| 2362 | # A qualified operand has to name a table in this query. | ||
| 2363 | for my $qa ($on_l_alias, $on_r_alias) { | ||
| 2364 | next if $alias_info{$qa}; | ||
| 2365 | return $self->_err( | ||
| 2366 | "Unknown table or alias '$qa' in the ON clause of " | ||
| 2367 | . "JOIN $js->{table}"); | ||
| 2368 | } | ||
| 2369 | if ($on_r_alias ne $js->{alias}) { | ||
| 2370 | return $self->_err( | ||
| 2371 | "The ON clause of JOIN $js->{table} does not reference " | ||
| 2372 | . "'$js->{alias}'; a join condition has to compare a " | ||
| 2373 | . "column of '$js->{alias}' with a column of a table " | ||
| 2374 | . "already joined"); | ||
| 2375 | } | ||
| 2376 | } | ||
| 2377 | |||
| 2378 | # Load the right-side table | ||
| 2379 | my @right_rows = @{ $self->_scan_table_all($js->{table}, $js->{alias}) }; | ||
| 2380 | |||
| 2381 | # Build hash on right side if possible (index-nested-loop join) | ||
| 2382 | my %right_hash; | ||
| 2383 | my $use_hash = 0; | ||
| 2384 | if (defined($on_r_alias) && defined($on_r_col)) { | ||
| 2385 | for my $rr (@right_rows) { | ||
| 2386 | my $rkey = defined($rr->{"$on_r_alias.$on_r_col"}) | ||
| 2387 | ? $rr->{"$on_r_alias.$on_r_col"} | ||
| 2388 | : ''; | ||
| 2389 | push @{ $right_hash{$rkey} }, $rr; | ||
| 2390 | } | ||
| 2391 | $use_hash = 1; | ||
| 2392 | } | ||
| 2393 | |||
| 2394 | my @next_rows; | ||
| 2395 | |||
| 2396 | if (($join_type eq 'CROSS') || (!defined $on_l_alias)) { | ||
| 2397 | |||
| 2398 | # Cartesian product | ||
| 2399 | for my $lr (@cur_rows) { | ||
| 2400 | for my $rr (@right_rows) { | ||
| 2401 | push @next_rows, { %$lr, %$rr }; | ||
| 2402 | } | ||
| 2403 | } | ||
| 2404 | } | ||
| 2405 | elsif ($join_type eq 'INNER') { | ||
| 2406 | for my $lr (@cur_rows) { | ||
| 2407 | my $lkey = defined($lr->{"$on_l_alias.$on_l_col"}) | ||
| 2408 | ? $lr->{"$on_l_alias.$on_l_col"} | ||
| 2409 | : ''; | ||
| 2410 | my $matches = $use_hash ? ($right_hash{$lkey} || []) : [ @right_rows ]; | ||
| 2411 | for my $rr (@$matches) { | ||
| 2412 | next if ($use_hash == 0) && !_join_row_matches($lr, $rr, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col); | ||
| 2413 | push @next_rows, { %$lr, %$rr }; | ||
| 2414 | } | ||
| 2415 | } | ||
| 2416 | } | ||
| 2417 | elsif ($join_type eq 'LEFT') { | ||
| 2418 | for my $lr (@cur_rows) { | ||
| 2419 | my $lkey = defined($lr->{"$on_l_alias.$on_l_col"}) | ||
| 2420 | ? $lr->{"$on_l_alias.$on_l_col"} | ||
| 2421 | : ''; | ||
| 2422 | my $matches = $use_hash ? ($right_hash{$lkey} || []) | ||
| 2423 | : [ grep { _join_row_matches($lr, $_, $on_l_alias, $on_l_col, $on_r_alias, $on_r_col) } | ||
| 2424 | @right_rows | ||
| 2425 | ]; | ||
| 2426 | if (@$matches) { | ||
| 2427 | for my $rr (@$matches) { | ||
| 2428 | push @next_rows, { %$lr, %$rr }; | ||
| 2429 | } | ||
| 2430 | } | ||
| 2431 | else { | ||
| 2432 | |||
| 2433 | # NULL-fill right side | ||
| 2434 | my %null_right = _make_null_row($js->{alias}, $alias_info{$js->{alias}}{sch}); | ||
| 2435 | push @next_rows, { %$lr, %null_right }; | ||
| 2436 | } | ||
| 2437 | } | ||
| 2438 | } | ||
| 2439 | elsif ($join_type eq 'RIGHT') { | ||
| 2440 | |||
| 2441 | # RIGHT JOIN: swap sides, do LEFT, then results are correct | ||
| 2442 | for my $rr (@right_rows) { | ||
| 2443 | my $rkey = defined($rr->{"$on_r_alias.$on_r_col"}) ? $rr->{"$on_r_alias.$on_r_col"} : ''; | ||
| 2444 | my $l_alias_key = "$on_l_alias.$on_l_col"; | ||
| 2445 | my @matched_lefts; | ||
| 2446 | for my $lr (@cur_rows) { | ||
| 2447 | my $lkey = defined($lr->{$l_alias_key}) ? $lr->{$l_alias_key} : ''; | ||
| 2448 | push @matched_lefts, $lr if $lkey eq $rkey; | ||
| 2449 | } | ||
| 2450 | if (@matched_lefts) { | ||
| 2451 | for my $lr (@matched_lefts) { | ||
| 2452 | push @next_rows, { %$lr, %$rr }; | ||
| 2453 | } | ||
| 2454 | } | ||
| 2455 | else { | ||
| 2456 | |||
| 2457 | # NULL-fill all left-side aliases seen so far | ||
| 2458 | my %null_left; | ||
| 2459 | for my $prev_js (@{$join_specs}[0..$i-1]) { | ||
| 2460 | my %nr = _make_null_row($prev_js->{alias}, $alias_info{$prev_js->{alias}}{sch}); | ||
| 2461 | %null_left = (%null_left, %nr); | ||
| 2462 | } | ||
| 2463 | push @next_rows, { %null_left, %$rr }; | ||
| 2464 | } | ||
| 2465 | } | ||
| 2466 | } | ||
| 2467 | |||
| 2468 | @cur_rows = @next_rows; | ||
| 2469 | } | ||
| 2470 | |||
| 2471 | # ------------------------------------------------------------------ | ||
| 2472 | # Step 4: apply WHERE (post-join filter) | ||
| 2473 | # ------------------------------------------------------------------ | ||
| 2474 | if (@$where_conds) { | ||
| 2475 | my $wsub = _compile_join_where($where_conds); | ||
| 2476 | @cur_rows = grep { $wsub->($_) } @cur_rows; | ||
| 2477 | } | ||
| 2478 | |||
| 2479 | # ------------------------------------------------------------------ | ||
| 2480 | # Step 5: ORDER BY | ||
| 2481 | # ------------------------------------------------------------------ | ||
| 2482 | # order_keys holds every ORDER BY key as [ name, ASC|DESC ]; order_by and | ||
| 2483 | # order_dir carry the first key so that older callers keep working. | ||
| 2484 | my @ob_keys; | ||
| 2485 | if ($opts->{order_keys} && @{$opts->{order_keys}}) { | ||
| 2486 | @ob_keys = @{$opts->{order_keys}}; | ||
| 2487 | } | ||
| 2488 | elsif ($opts->{order_by}) { | ||
| 2489 | @ob_keys = ([ $opts->{order_by}, ($opts->{order_dir} || 'ASC') ]); | ||
| 2490 | } | ||
| 2491 | if (@ob_keys) { | ||
| 2492 | |||
| 2493 | # A result row is keyed "alias.col", so a bare ORDER BY name has to be | ||
| 2494 | # resolved to the alias that owns it. An unresolvable key used to | ||
| 2495 | # leave the rows in scan order without a word. | ||
| 2496 | my(%qual, %bare); | ||
| 2497 | for my $js (@$join_specs) { | ||
| 2498 | my $a = $js->{alias}; | ||
| 2499 | for my $c (@{$alias_info{$a}{sch}{cols}}) { | ||
| 2500 | $qual{"$a.$c->{name}"} = 1; | ||
| 2501 | $bare{$c->{name}} = "$a.$c->{name}" | ||
| 2502 | unless exists $bare{$c->{name}}; | ||
| 2503 | } | ||
| 2504 | } | ||
| 2505 | for my $k (@ob_keys) { | ||
| 2506 | next if $qual{$k->[0]}; | ||
| 2507 | if ($bare{$k->[0]}) { | ||
| 2508 | $k->[0] = $bare{$k->[0]}; | ||
| 2509 | next; | ||
| 2510 | } | ||
| 2511 | return $self->_err( | ||
| 2512 | "Unknown ORDER BY column '$k->[0]' in a JOIN query"); | ||
| 2513 | } | ||
| 2514 | |||
| 2515 | @cur_rows = sort { | ||
| 2516 | my $cmp = 0; | ||
| 2517 | for my $k (@ob_keys) { | ||
| 2518 | my($key, $dir) = @$k; | ||
| 2519 | my $va = $a->{$key}; | ||
| 2520 | my $vb = $b->{$key}; | ||
| 2521 | my $c = (defined($va) && ($va =~ /^-?\d+\.?\d*$/) && | ||
| 2522 | defined($vb) && ($vb =~ /^-?\d+\.?\d*$/)) | ||
| 2523 | ? ($va <=> $vb) | ||
| 2524 | : ((defined($va) ? $va : '') cmp (defined($vb) ? $vb : '')); | ||
| 2525 | $c = -$c if lc($dir) eq 'desc'; | ||
| 2526 | if ($c != 0) { | ||
| 2527 | $cmp = $c; | ||
| 2528 | last; | ||
| 2529 | } | ||
| 2530 | } | ||
| 2531 | $cmp; | ||
| 2532 | } @cur_rows; | ||
| 2533 | } | ||
| 2534 | |||
| 2535 | # ------------------------------------------------------------------ | ||
| 2536 | # Step 6: expand the select list and check every item | ||
| 2537 | # ------------------------------------------------------------------ | ||
| 2538 | my @expanded; | ||
| 2539 | if ($col_specs && @$col_specs) { | ||
| 2540 | |||
| 2541 | # Expand wildcards: 'alias.*' or '*' | ||
| 2542 | for my $cs (@$col_specs) { | ||
| 2543 | if ($cs eq '*') { | ||
| 2544 | |||
| 2545 | # all columns from all aliases | ||
| 2546 | for my $js (@$join_specs) { | ||
| 2547 | my $a = $js->{alias}; | ||
| 2548 | my $sch = $alias_info{$a}{sch}; | ||
| 2549 | for my $c (@{$sch->{cols}}) { | ||
| 2550 | push @expanded, "$a.$c->{name}"; | ||
| 2551 | } | ||
| 2552 | } | ||
| 2553 | } | ||
| 2554 | elsif ($cs =~ /^(\w+)\.\*$/) { | ||
| 2555 | my $a = $1; | ||
| 2556 | my $sch = $alias_info{$a} ? $alias_info{$a}{sch} : undef; | ||
| 2557 | unless ($sch) { | ||
| 2558 | return $self->_err("Unknown table or alias '$a' in '$cs'"); | ||
| 2559 | } | ||
| 2560 | for my $c (@{$sch->{cols}}) { | ||
| 2561 | push @expanded, "$a.$c->{name}"; | ||
| 2562 | } | ||
| 2563 | } | ||
| 2564 | else { | ||
| 2565 | push @expanded, $cs; | ||
| 2566 | } | ||
| 2567 | } | ||
| 2568 | |||
| 2569 | # Every item has to name a column of one of the joined tables. A | ||
| 2570 | # JOIN select list cannot evaluate an expression or an AS alias, and | ||
| 2571 | # until 1.09 such an item silently produced a row with no values in | ||
| 2572 | # it at all: "SELECT a.y AS nm ... JOIN", "SELECT a.x + 1 ... JOIN" | ||
| 2573 | # and "SELECT DISTINCT a.x ... JOIN" all returned empty rows. | ||
| 2574 | my %valid_col; | ||
| 2575 | for my $js (@$join_specs) { | ||
| 2576 | my $a = $js->{alias}; | ||
| 2577 | for my $c (@{$alias_info{$a}{sch}{cols}}) { | ||
| 2578 | $valid_col{"$a.$c->{name}"} = 1; | ||
| 2579 | $valid_col{$c->{name}} = 1; | ||
| 2580 | } | ||
| 2581 | } | ||
| 2582 | for my $ck (@expanded) { | ||
| 2583 | next if $valid_col{$ck}; | ||
| 2584 | return $self->_err( | ||
| 2585 | "Unsupported select item '$ck' in a JOIN query; a JOIN " | ||
| 2586 | . "select list accepts column names, '*' and '<table>.*' " | ||
| 2587 | . "only (no expressions and no AS aliases)"); | ||
| 2588 | } | ||
| 2589 | } | ||
| 2590 | |||
| 2591 | # ------------------------------------------------------------------ | ||
| 2592 | # Step 7: DISTINCT. Applied before OFFSET/LIMIT, as SQL requires, and | ||
| 2593 | # keyed on the select-list values only. | ||
| 2594 | # ------------------------------------------------------------------ | ||
| 2595 | if ($opts->{distinct}) { | ||
| 2596 | my @dkeys = @expanded ? @expanded : sort keys %{ $cur_rows[0] || {} }; | ||
| 2597 | my(%seen, @uniq); | ||
| 2598 | for my $r (@cur_rows) { | ||
| 2599 | my $k = join("\x00", map { | ||
| 2600 | defined($r->{$_}) ? $r->{$_} : "\x01" | ||
| 2601 | } @dkeys); | ||
| 2602 | push @uniq, $r unless $seen{$k}++; | ||
| 2603 | } | ||
| 2604 | @cur_rows = @uniq; | ||
| 2605 | } | ||
| 2606 | |||
| 2607 | # ------------------------------------------------------------------ | ||
| 2608 | # Step 8: OFFSET / LIMIT | ||
| 2609 | # ------------------------------------------------------------------ | ||
| 2610 | my $offset = ($opts->{offset} || 0); | ||
| 2611 | @cur_rows = splice(@cur_rows, $offset) if $offset; | ||
| 2612 | if (defined $opts->{limit}) { | ||
| 2613 | my $last = $opts->{limit} - 1; | ||
| 2614 | $last = $#cur_rows if $last > $#cur_rows; | ||
| 2615 | @cur_rows = @cur_rows[0..$last]; | ||
| 2616 | } | ||
| 2617 | |||
| 2618 | # ------------------------------------------------------------------ | ||
| 2619 | # Step 9: column projection | ||
| 2620 | # ------------------------------------------------------------------ | ||
| 2621 | if (@expanded) { | ||
| 2622 | my @proj_rows; | ||
| 2623 | for my $r (@cur_rows) { | ||
| 2624 | my %p; | ||
| 2625 | for my $ck (@expanded) { | ||
| 2626 | |||
| 2627 | # Try qualified name first, then bare name | ||
| 2628 | if (exists $r->{$ck}) { | ||
| 2629 | $p{$ck} = $r->{$ck}; | ||
| 2630 | } | ||
| 2631 | else { | ||
| 2632 | |||
| 2633 | # bare name: find first matching qualified key | ||
| 2634 | for my $k (keys %$r) { | ||
| 2635 | if (($k =~ /\.\Q$ck\E$/) || ($k eq $ck)) { | ||
| 2636 | $p{$ck} = $r->{$k}; | ||
| 2637 | last; | ||
| 2638 | } | ||
| 2639 | } | ||
| 2640 | } | ||
| 2641 | } | ||
| 2642 | push @proj_rows, { %p }; | ||
| 2643 | } | ||
| 2644 | return [ @proj_rows ]; | ||
| 2645 | } | ||
| 2646 | |||
| 2647 | return [ @cur_rows ]; | ||
| 2648 | } | ||
| 2649 | |||
| 2650 | # Load all active rows from a table, qualifying each column as "alias.col" | ||
| 2651 | sub _scan_table_all { | ||
| 2652 | my($self, $table, $alias) = @_; | ||
| 2653 | my $sch = $self->_load_schema($table) or return []; | ||
| 2654 | my $dat = $self->_file($table, 'dat'); | ||
| 2655 | my $recsize = $sch->{recsize}; | ||
| 2656 | my @rows; | ||
| 2657 | |||
| 2658 | local *FH; | ||
| 2659 | open(FH, "< $dat") or do { $errstr = "Cannot open dat '$dat': $!"; return []; }; | ||
| 2660 | binmode FH; | ||
| 2661 | _lock_sh(\*FH); | ||
| 2662 | while (1) { | ||
| 2663 | my $raw = ''; | ||
| 2664 | my $n = read(FH, $raw, $recsize); | ||
| 2665 | last unless defined($n) && ($n == $recsize); | ||
| 2666 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 2667 | my $raw_row = $self->_unpack_record($sch, $raw); | ||
| 2668 | |||
| 2669 | # Qualify column names with alias | ||
| 2670 | my %qrow; | ||
| 2671 | for my $col (@{$sch->{cols}}) { | ||
| 2672 | $qrow{"$alias.$col->{name}"} = $raw_row->{$col->{name}}; | ||
| 2673 | } | ||
| 2674 | push @rows, { %qrow }; | ||
| 2675 | } | ||
| 2676 | _unlock(\*FH); | ||
| 2677 | close FH; | ||
| 2678 | return [ @rows ]; | ||
| 2679 | } | ||
| 2680 | |||
| 2681 | # Build a row of NULLs for the given alias (for outer joins) | ||
| 2682 | sub _make_null_row { | ||
| 2683 | my($alias, $sch) = @_; | ||
| 2684 | my %row; | ||
| 2685 | for my $col (@{$sch->{cols}}) { | ||
| 2686 | $row{"$alias.$col->{name}"} = undef; | ||
| 2687 | } | ||
| 2688 | return %row; | ||
| 2689 | } | ||
| 2690 | |||
| 2691 | # Split "alias.col" into (alias, col); if no dot, return (undef, col) | ||
| 2692 | sub _split_qualified { | ||
| 2693 | my($qname) = @_; | ||
| 2694 | if ($qname =~ /^(\w+)\.(\w+)$/) { | ||
| 2695 | return ($1, $2); | ||
| 2696 | } | ||
| 2697 | return (undef, $qname); | ||
| 2698 | } | ||
| 2699 | |||
| 2700 | # Check if a pair of rows satisfies the ON equality condition | ||
| 2701 | sub _join_row_matches { | ||
| 2702 | my($lr, $rr, $la, $lc, $ra, $rc) = @_; | ||
| 2703 | my $lv = defined($la) ? $lr->{"$la.$lc"} : $lr->{$lc}; | ||
| 2704 | my $rv = defined($ra) ? $rr->{"$ra.$rc"} : $rr->{$rc}; | ||
| 2705 | return 0 unless defined($lv) && defined($rv); | ||
| 2706 | |||
| 2707 | # numeric compare if both look numeric | ||
| 2708 | if (($lv =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/)) { | ||
| 2709 | return (($lv == $rv) ? 1 : 0); | ||
| 2710 | } | ||
| 2711 | return (($lv eq $rv) ? 1 : 0); | ||
| 2712 | } | ||
| 2713 | |||
| 2714 | ############################################################################### | ||
| 2715 | # JOIN WHERE compiler | ||
| 2716 | # Conditions from the WHERE clause after a JOIN may reference qualified | ||
| 2717 | # columns (alias.col) or bare column names. | ||
| 2718 | # Condition hashref keys: | ||
| 2719 | # lhs_alias, lhs_col -- left-hand side | ||
| 2720 | # op -- = != <> < > <= >= LIKE | ||
| 2721 | # rhs_alias, rhs_col -- right-hand side (column comparison) OR | ||
| 2722 | # val -- literal value | ||
| 2723 | ############################################################################### | ||
| 2724 | sub _compile_join_where { | ||
| 2725 | my($conds) = @_; | ||
| 2726 | return sub { 1 } unless $conds && @$conds; | ||
| 2727 | return sub { | ||
| 2728 | my($row) = @_; | ||
| 2729 | for my $c (@$conds) { | ||
| 2730 | |||
| 2731 | # Resolve left-hand value | ||
| 2732 | my $lv; | ||
| 2733 | if (defined $c->{lhs_alias}) { | ||
| 2734 | $lv = $row->{"$c->{lhs_alias}.$c->{lhs_col}"}; | ||
| 2735 | } | ||
| 2736 | else { | ||
| 2737 | |||
| 2738 | # bare name: search qualified keys | ||
| 2739 | for my $k (keys %$row) { | ||
| 2740 | if (($k =~ /\.\Q$c->{lhs_col}\E$/) || ($k eq $c->{lhs_col})) { | ||
| 2741 | $lv = $row->{$k}; | ||
| 2742 | last; | ||
| 2743 | } | ||
| 2744 | } | ||
| 2745 | } | ||
| 2746 | # IS [NOT] NULL is decided before the coercion below, and uses | ||
| 2747 | # the same rule as the single-table engine: a NULL is either an | ||
| 2748 | # undefined value (a NULL-filled outer-join row) or the empty | ||
| 2749 | # string (the on-disk representation). | ||
| 2750 | if ($c->{op} eq 'IS_NULL') { | ||
| 2751 | return 0 if defined($lv) && ($lv ne ''); | ||
| 2752 | next; | ||
| 2753 | } | ||
| 2754 | if ($c->{op} eq 'IS_NOT_NULL') { | ||
| 2755 | return 0 unless defined($lv) && ($lv ne ''); | ||
| 2756 | next; | ||
| 2757 | } | ||
| 2758 | |||
| 2759 | $lv = '' unless defined $lv; | ||
| 2760 | |||
| 2761 | # Resolve right-hand value (literal or column) | ||
| 2762 | my $rv; | ||
| 2763 | if (defined $c->{rhs_col}) { | ||
| 2764 | if (defined $c->{rhs_alias}) { | ||
| 2765 | $rv = $row->{"$c->{rhs_alias}.$c->{rhs_col}"}; | ||
| 2766 | } | ||
| 2767 | else { | ||
| 2768 | for my $k (keys %$row) { | ||
| 2769 | if (($k =~ /\.\Q$c->{rhs_col}\E$/) || ($k eq $c->{rhs_col})) { | ||
| 2770 | $rv = $row->{$k}; | ||
| 2771 | last; | ||
| 2772 | } | ||
| 2773 | } | ||
| 2774 | } | ||
| 2775 | } | ||
| 2776 | else { | ||
| 2777 | $rv = $c->{val}; | ||
| 2778 | } | ||
| 2779 | $rv = '' unless defined $rv; | ||
| 2780 | |||
| 2781 | my $op = $c->{op}; | ||
| 2782 | |||
| 2783 | # IN / NOT IN | ||
| 2784 | if (($op eq 'IN') || ($op eq 'NOT_IN')) { | ||
| 2785 | my $lhs_val = $lv; | ||
| 2786 | my $found = 0; | ||
| 2787 | my $has_null = 0; | ||
| 2788 | for my $cv (@{$c->{vals}}) { | ||
| 2789 | unless (defined $cv) { $has_null = 1; next } | ||
| 2790 | my $num2 = (($lhs_val =~ /^-?\d+\.?\d*$/) && ($cv =~ /^-?\d+\.?\d*$/)); | ||
| 2791 | if ($num2 ? ($lhs_val == $cv) : ($lhs_val eq $cv)) { | ||
| 2792 | $found = 1; | ||
| 2793 | last; | ||
| 2794 | } | ||
| 2795 | } | ||
| 2796 | return 0 if $found && ($op eq 'NOT_IN'); | ||
| 2797 | return 0 if !$found && ($op eq 'IN'); | ||
| 2798 | # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN | ||
| 2799 | # when the row value was not found in the non-NULL values. | ||
| 2800 | return 0 if $has_null && !$found && ($op eq 'NOT_IN'); | ||
| 2801 | next; | ||
| 2802 | } | ||
| 2803 | |||
| 2804 | my $num = (($lv =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/)); | ||
| 2805 | |||
| 2806 | if ($op eq '=') { | ||
| 2807 | return 0 unless $num ? ($lv == $rv) : ($lv eq $rv); | ||
| 2808 | } | ||
| 2809 | elsif (($op eq '!=') || ($op eq '<>')) { | ||
| 2810 | return 0 unless $num ? ($lv != $rv) : ($lv ne $rv); | ||
| 2811 | } | ||
| 2812 | elsif ($op eq '<') { | ||
| 2813 | return 0 unless $num ? ($lv < $rv) : ($lv lt $rv); | ||
| 2814 | } | ||
| 2815 | elsif ($op eq '>') { | ||
| 2816 | return 0 unless $num ? ($lv > $rv) : ($lv gt $rv); | ||
| 2817 | } | ||
| 2818 | elsif ($op eq '<=') { | ||
| 2819 | return 0 unless $num ? ($lv <= $rv) : ($lv le $rv); | ||
| 2820 | } | ||
| 2821 | elsif ($op eq '>=') { | ||
| 2822 | return 0 unless $num ? ($lv >= $rv) : ($lv ge $rv); | ||
| 2823 | } | ||
| 2824 | elsif ($op eq 'LIKE') { | ||
| 2825 | my $p = _like_to_re($rv); | ||
| 2826 | return 0 unless $lv =~ /^$p$/i; | ||
| 2827 | } | ||
| 2828 | } | ||
| 2829 | return 1; | ||
| 2830 | }; | ||
| 2831 | } | ||
| 2832 | |||
| 2833 | ############################################################################### | ||
| 2834 | # JOIN SQL parser | ||
| 2835 | # Handles: | ||
| 2836 | # SELECT col_list | ||
| 2837 | # FROM t1 [AS a1] | ||
| 2838 | # [INNER|LEFT [OUTER]|RIGHT [OUTER]|CROSS] JOIN t2 [AS a2] ON a1.c = a2.c | ||
| 2839 | # [ JOIN t3 [AS a3] ON ... ] | ||
| 2840 | # [WHERE ...] | ||
| 2841 | # [ORDER BY alias.col [ASC|DESC]] | ||
| 2842 | # [LIMIT n] [OFFSET m] | ||
| 2843 | ############################################################################### | ||
| 2844 | # A table alias in a FROM clause is optional, so the token that follows a | ||
| 2845 | # table name has to be checked before it is accepted as one. Without this | ||
| 2846 | # guard "FROM a LEFT JOIN b ON a.id = b.bid" read LEFT as the alias of a, | ||
| 2847 | # which turned the LEFT JOIN into a plain JOIN and left every "a.col" | ||
| 2848 | # reference unresolvable, and "JOIN b ON ..." read ON as the alias of b, | ||
| 2849 | # which dropped the join condition and produced a silent cross join. | ||
| 2850 | sub _is_join_keyword { | ||
| 2851 | my($word) = @_; | ||
| 2852 | return 0 unless defined $word; | ||
| 2853 | return $word =~ /^(?:INNER|LEFT|RIGHT|FULL|OUTER|CROSS|NATURAL|JOIN|ON|USING|WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|UNION)$/i ? 1 : 0; | ||
| 2854 | } | ||
| 2855 | |||
| 2856 | sub _parse_join_sql { | ||
| 2857 | my($sql) = @_; | ||
| 2858 | # sql has been normalised: single spaces, trimmed | ||
| 2859 | |||
| 2860 | # --------------------------------------------------------------- | ||
| 2861 | # 1. Extract SELECT column list and the FROM...rest portion | ||
| 2862 | # --------------------------------------------------------------- | ||
| 2863 | return undef unless $sql =~ /^SELECT\s+(.+?)\s+FROM\s+(.+)$/si; | ||
| 2864 | my($sel_str, $from_rest) = ($1, $2); | ||
| 2865 | |||
| 2866 | # --------------------------------------------------------------- | ||
| 2867 | # 2. Strip trailing ORDER BY / LIMIT / OFFSET | ||
| 2868 | # (strip right-to-left to avoid greedy issues) | ||
| 2869 | # --------------------------------------------------------------- | ||
| 2870 | my %opts; | ||
| 2871 | |||
| 2872 | # Strip suffixes right-to-left: OFFSET, LIMIT, ORDER BY | ||
| 2873 | # (ORDER BY may precede LIMIT/OFFSET, so strip LIMIT+OFFSET first) | ||
| 2874 | if ($from_rest =~ s/\s+OFFSET\s+(\d+)\s*$//i) { | ||
| 2875 | $opts{offset} = $1; | ||
| 2876 | } | ||
| 2877 | if ($from_rest =~ s/\s+LIMIT\s+(\d+)\s*$//i) { | ||
| 2878 | $opts{limit} = $1; | ||
| 2879 | } | ||
| 2880 | # ORDER BY accepts a comma-separated key list. Before 1.09 only a single | ||
| 2881 | # key was matched here, so "ORDER BY a.y, a.x DESC" failed to match, was | ||
| 2882 | # swallowed by the WHERE strip below and then dropped by the condition | ||
| 2883 | # parser -- the rows came back in scan order with no error. | ||
| 2884 | if ($from_rest =~ s/\s+ORDER\s+BY\s+([\w.]+(?:\s+(?:ASC|DESC))?(?:\s*,\s*[\w.]+(?:\s+(?:ASC|DESC))?)*)\s*$//i) { | ||
| 2885 | my $ob_str = $1; | ||
| 2886 | my @ob_keys; | ||
| 2887 | for my $k (split(/\s*,\s*/, $ob_str)) { | ||
| 2888 | $k =~ s/^\s+|\s+$//g; | ||
| 2889 | my $dir = 'ASC'; | ||
| 2890 | $dir = uc($1) if $k =~ s/\s+(ASC|DESC)\s*$//i; | ||
| 2891 | push @ob_keys, [ $k, $dir ]; | ||
| 2892 | } | ||
| 2893 | if (@ob_keys) { | ||
| 2894 | $opts{order_keys} = [ @ob_keys ]; | ||
| 2895 | $opts{order_by} = $ob_keys[0][0]; | ||
| 2896 | $opts{order_dir} = $ob_keys[0][1]; | ||
| 2897 | } | ||
| 2898 | } | ||
| 2899 | |||
| 2900 | # --------------------------------------------------------------- | ||
| 2901 | # 3. Extract WHERE clause (everything after WHERE keyword, | ||
| 2902 | # which must come after all JOIN...ON clauses) | ||
| 2903 | # --------------------------------------------------------------- | ||
| 2904 | my $where_str = ''; | ||
| 2905 | |||
| 2906 | # WHERE must appear after the last ON clause; we find the last WHERE | ||
| 2907 | if ($from_rest =~ s/\s+WHERE\s+(.+)$//i) { | ||
| 2908 | $where_str = $1; | ||
| 2909 | $where_str =~ s/^\s+|\s+$//g; | ||
| 2910 | } | ||
| 2911 | |||
| 2912 | # --------------------------------------------------------------- | ||
| 2913 | # 4. Parse the FROM clause using iterative regex matching | ||
| 2914 | # Grammar: table [AS alias] | ||
| 2915 | # { join_type JOIN table [AS alias] ON qcol = qcol }* | ||
| 2916 | # --------------------------------------------------------------- | ||
| 2917 | my @join_specs; | ||
| 2918 | |||
| 2919 | # Parse the driving (first) table | ||
| 2920 | my $fr = $from_rest; | ||
| 2921 | $fr =~ s/^\s+//; | ||
| 2922 | unless ($fr =~ s/^(\w+)//) { | ||
| 2923 | return undef; | ||
| 2924 | } | ||
| 2925 | my $first_tbl = $1; | ||
| 2926 | my $first_alias = $first_tbl; | ||
| 2927 | if ($fr =~ /^\s+(?:AS\s+)?(\w+)/i) { | ||
| 2928 | my $cand = $1; | ||
| 2929 | unless (_is_join_keyword($cand)) { | ||
| 2930 | $fr =~ s/^\s+(?:AS\s+)?\w+//i; | ||
| 2931 | $first_alias = $cand; | ||
| 2932 | } | ||
| 2933 | } | ||
| 2934 | push @join_specs, { table => $first_tbl, alias => $first_alias, type => 'FIRST' }; | ||
| 2935 | |||
| 2936 | # Iteratively match JOIN clauses. | ||
| 2937 | # | ||
| 2938 | # The join-type words, the table and its alias are matched first; the ON | ||
| 2939 | # expression is then taken as everything up to the start of the next JOIN | ||
| 2940 | # clause (or the end of the FROM text) and checked separately. Until 1.09 | ||
| 2941 | # the ON clause was part of this pattern as an *optional* group matching | ||
| 2942 | # only "col = col", so every ON the pattern could not read simply failed | ||
| 2943 | # to participate: on_left and on_right stayed undef and join_select fell | ||
| 2944 | # through to its Cartesian-product branch. "ON a.x = b.k AND a.id < b.id", | ||
| 2945 | # "ON a.x < b.k", "ON b.k = a.x" (operands the other way round), USING, | ||
| 2946 | # NATURAL and FULL OUTER all returned a silent cross join instead of an | ||
| 2947 | # error. Anything not executable is now collected in $err. | ||
| 2948 | my $err = ''; | ||
| 2949 | 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) { | ||
| 2950 | my($type_kw, $tbl, $alias) = ($1, $2, $3); | ||
| 2951 | $type_kw = '' unless defined $type_kw; | ||
| 2952 | $type_kw =~ s/\s+$//; | ||
| 2953 | my $type = 'INNER'; | ||
| 2954 | if ($type_kw =~ /NATURAL/i) { | ||
| 2955 | $err = "NATURAL JOIN is not supported; name the join columns " | ||
| 2956 | . "with ON <left>.<col> = <right>.<col>" | ||
| 2957 | unless $err ne ''; | ||
| 2958 | } | ||
| 2959 | elsif ($type_kw =~ /FULL/i) { | ||
| 2960 | $err = "FULL OUTER JOIN is not supported; use LEFT JOIN or " | ||
| 2961 | . "RIGHT JOIN, or combine the two with UNION" | ||
| 2962 | unless $err ne ''; | ||
| 2963 | } | ||
| 2964 | elsif ($type_kw =~ /CROSS/i) { | ||
| 2965 | $type = 'CROSS'; | ||
| 2966 | } | ||
| 2967 | elsif ($type_kw =~ /LEFT/i) { | ||
| 2968 | $type = 'LEFT'; | ||
| 2969 | } | ||
| 2970 | elsif ($type_kw =~ /RIGHT/i) { | ||
| 2971 | $type = 'RIGHT'; | ||
| 2972 | } | ||
| 2973 | $alias = $tbl unless defined $alias; | ||
| 2974 | |||
| 2975 | # USING (col, ...) -- recognised only so that it can be rejected. | ||
| 2976 | if ($fr =~ s/^\s+USING\s*\(([^)]*)\)//i) { | ||
| 2977 | $err = "JOIN ... USING is not supported; use " | ||
| 2978 | . "ON <left>.<col> = <right>.<col>" | ||
| 2979 | unless $err ne ''; | ||
| 2980 | } | ||
| 2981 | |||
| 2982 | # ON <expr>, up to the next JOIN clause or the end of the FROM text. | ||
| 2983 | my($on_left, $on_right); | ||
| 2984 | if ($fr =~ s/^\s+ON\s+(.*?)(?=\s+(?:(?:INNER|LEFT|RIGHT|FULL|CROSS|NATURAL|OUTER)\s+)*JOIN\b|$)//is) { | ||
| 2985 | my $on_expr = $1; | ||
| 2986 | $on_expr =~ s/^\s+|\s+$//g; | ||
| 2987 | if ($on_expr =~ /^([\w.]+)\s*=\s*([\w.]+)$/) { | ||
| 2988 | ($on_left, $on_right) = ($1, $2); | ||
| 2989 | } | ||
| 2990 | else { | ||
| 2991 | $err = "Unsupported JOIN condition 'ON $on_expr'; a JOIN " | ||
| 2992 | . "accepts a single equality between two columns, as in " | ||
| 2993 | . "ON <left>.<col> = <right>.<col>. Move any further " | ||
| 2994 | . "restriction into the WHERE clause" | ||
| 2995 | unless $err ne ''; | ||
| 2996 | } | ||
| 2997 | } | ||
| 2998 | elsif ($type ne 'CROSS') { | ||
| 2999 | $err = "JOIN $tbl has no ON clause; add " | ||
| 3000 | . "ON <left>.<col> = <right>.<col>, or write CROSS JOIN for " | ||
| 3001 | . "a deliberate Cartesian product" | ||
| 3002 | unless $err ne ''; | ||
| 3003 | } | ||
| 3004 | |||
| 3005 | push @join_specs, { | ||
| 3006 | table => $tbl, | ||
| 3007 | alias => $alias, | ||
| 3008 | type => $type, | ||
| 3009 | on_left => $on_left, | ||
| 3010 | on_right => $on_right, | ||
| 3011 | }; | ||
| 3012 | } | ||
| 3013 | |||
| 3014 | # Must have at least 2 tables to be a JOIN. A JOIN that appears only | ||
| 3015 | # inside a subquery lands here too, so this returns undef without an | ||
| 3016 | # error and lets the ordinary SELECT parser take over. | ||
| 3017 | return undef if @join_specs < 2; | ||
| 3018 | |||
| 3019 | # Text left over in the FROM chain used to be discarded without a word. | ||
| 3020 | if (($err eq '') && ($fr =~ /\S/)) { | ||
| 3021 | my $left = $fr; | ||
| 3022 | $left =~ s/^\s+|\s+$//g; | ||
| 3023 | $err = "Unsupported text in FROM clause: '$left'"; | ||
| 3024 | } | ||
| 3025 | |||
| 3026 | return [ undef, undef, undef, undef, $err ] if $err ne ''; | ||
| 3027 | |||
| 3028 | # --------------------------------------------------------------- | ||
| 3029 | # 5. Parse SELECT column list | ||
| 3030 | # --------------------------------------------------------------- | ||
| 3031 | my @col_specs; | ||
| 3032 | |||
| 3033 | # DISTINCT used to be left glued to the first select item, which made the | ||
| 3034 | # item unresolvable: every row came back empty and nothing was deduplicated. | ||
| 3035 | if ($sel_str =~ s/^\s*DISTINCT\s+//i) { | ||
| 3036 | $opts{distinct} = 1; | ||
| 3037 | } | ||
| 3038 | if ($sel_str =~ /^\s*\*\s*$/) { | ||
| 3039 | @col_specs = (); # empty = all columns (expanded later) | ||
| 3040 | } | ||
| 3041 | else { | ||
| 3042 | for my $cs (split /\s*,\s*/, $sel_str) { | ||
| 3043 | $cs =~ s/^\s+|\s+$//g; | ||
| 3044 | push @col_specs, $cs; | ||
| 3045 | } | ||
| 3046 | } | ||
| 3047 | |||
| 3048 | # --------------------------------------------------------------- | ||
| 3049 | # 6. Parse WHERE conditions | ||
| 3050 | # --------------------------------------------------------------- | ||
| 3051 | my @where_conds; | ||
| 3052 | if ($where_str =~ /\S/) { | ||
| 3053 | my($wc, $werr) = _parse_join_conditions($where_str); | ||
| 3054 | return [ undef, undef, undef, undef, $werr ] if $werr ne ''; | ||
| 3055 | @where_conds = @$wc; | ||
| 3056 | } | ||
| 3057 | |||
| 3058 | return [ [ @join_specs ], [ @col_specs ], [ @where_conds ], { %opts }, '' ]; | ||
| 3059 | } | ||
| 3060 | |||
| 3061 | # Parse WHERE expression containing possibly qualified column names | ||
| 3062 | # Returns arrayref of condition hashrefs | ||
| 3063 | sub _parse_join_conditions { | ||
| 3064 | my($expr) = @_; | ||
| 3065 | return ([], '') unless defined($expr) && ($expr =~ /\S/); | ||
| 3066 | my @conds; | ||
| 3067 | |||
| 3068 | # Split on AND. BETWEEN carries an AND of its own that is not a | ||
| 3069 | # conjunction, so a part that opened a BETWEEN is glued back together | ||
| 3070 | # with the part that follows it. | ||
| 3071 | my @raw = split(/\s+AND\s+/i, $expr); | ||
| 3072 | my @parts; | ||
| 3073 | while (@raw) { | ||
| 3074 | my $p = shift @raw; | ||
| 3075 | if (($p =~ /\bBETWEEN\b/i) && ($p !~ /\bBETWEEN\b.*\bAND\b/i) && @raw) { | ||
| 3076 | $p .= ' AND ' . shift(@raw); | ||
| 3077 | } | ||
| 3078 | push @parts, $p; | ||
| 3079 | } | ||
| 3080 | |||
| 3081 | for my $part (@parts) { | ||
| 3082 | $part =~ s/^\s+|\s+$//g; | ||
| 3083 | next unless $part =~ /\S/; | ||
| 3084 | |||
| 3085 | # col IS [NOT] NULL. Without this a LEFT JOIN anti-join | ||
| 3086 | # ("WHERE right.col IS NULL") matched no pattern at all and was | ||
| 3087 | # dropped, so every joined row came back unfiltered. | ||
| 3088 | if ($part =~ /^((?:\w+\.)?\w+)\s+IS\s+(NOT\s+)?NULL$/i) { | ||
| 3089 | my($lhs, $neg) = ($1, $2); | ||
| 3090 | my($la, $lc) = _split_qualified($lhs); | ||
| 3091 | push @conds, { | ||
| 3092 | lhs_alias => $la, | ||
| 3093 | lhs_col => $lc, | ||
| 3094 | op => ($neg ? 'IS_NOT_NULL' : 'IS_NULL'), | ||
| 3095 | }; | ||
| 3096 | next; | ||
| 3097 | } | ||
| 3098 | |||
| 3099 | # col BETWEEN lo AND hi -> col >= lo, col <= hi | ||
| 3100 | if ($part =~ /^((?:\w+\.)?\w+)\s+BETWEEN\s+(?:'([^']*)'|(-?\d+\.?\d*))\s+AND\s+(?:'([^']*)'|(-?\d+\.?\d*))$/i) { | ||
| 3101 | my($lhs, $lo_s, $lo_n, $hi_s, $hi_n) = ($1, $2, $3, $4, $5); | ||
| 3102 | my($la, $lc) = _split_qualified($lhs); | ||
| 3103 | my $lo = defined($lo_s) ? $lo_s : $lo_n; | ||
| 3104 | my $hi = defined($hi_s) ? $hi_s : $hi_n; | ||
| 3105 | push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>'>=', val=>$lo }; | ||
| 3106 | push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>'<=', val=>$hi }; | ||
| 3107 | next; | ||
| 3108 | } | ||
| 3109 | |||
| 3110 | # col-vs-col: alias1.col1 OP alias2.col2 | ||
| 3111 | if (($part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>)\s*((?:\w+\.)?\w+)$/i) && ($part !~ /'/)) { | ||
| 3112 | my($lhs, $op, $rhs) = ($1, uc($2), $3); | ||
| 3113 | |||
| 3114 | # Heuristic: if rhs looks like a number, treat as literal | ||
| 3115 | if ($rhs =~ /^-?\d+\.?\d*$/) { | ||
| 3116 | my($la, $lc) = _split_qualified($lhs); | ||
| 3117 | push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>$op, val=>$rhs }; | ||
| 3118 | } | ||
| 3119 | else { | ||
| 3120 | my($la, $lc) = _split_qualified($lhs); | ||
| 3121 | my($ra, $rc) = _split_qualified($rhs); | ||
| 3122 | push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>$op, rhs_alias=>$ra, rhs_col=>$rc }; | ||
| 3123 | } | ||
| 3124 | # col [NOT] IN (val, val, ...) | ||
| 3125 | } | ||
| 3126 | elsif ($part =~ /^((?:\w+\.)?\w+)\s+(NOT\s+)?IN\s*\(([^)]*)\)\s*$/i) { | ||
| 3127 | my($lhs, $neg, $list_str) = ($1, $2, $3); | ||
| 3128 | my($la, $lc) = _split_qualified($lhs); | ||
| 3129 | my @vals; | ||
| 3130 | my $ls = $list_str; | ||
| 3131 | while ($ls =~ s/^\s*(?:'([^']*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) { | ||
| 3132 | my($sv, $nv, $nl) = ($1, $2, $3); | ||
| 3133 | push @vals, defined($nl) ? undef : (defined($sv) ? $sv : $nv); | ||
| 3134 | } | ||
| 3135 | push @conds, { | ||
| 3136 | lhs_alias => $la, | ||
| 3137 | lhs_col => $lc, | ||
| 3138 | op => ($neg ? 'NOT_IN' : 'IN'), | ||
| 3139 | vals => [ @vals ], | ||
| 3140 | }; | ||
| 3141 | # col-vs-literal | ||
| 3142 | } | ||
| 3143 | elsif ($part =~ /^((?:\w+\.)?\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) { | ||
| 3144 | my($lhs, $op, $sv, $nv) = ($1, uc($2), $3, $4); | ||
| 3145 | my($la, $lc) = _split_qualified($lhs); | ||
| 3146 | push @conds, { lhs_alias=>$la, lhs_col=>$lc, op=>$op, val=>defined($sv) ? $sv : $nv }; | ||
| 3147 | } | ||
| 3148 | else { | ||
| 3149 | |||
| 3150 | # Until 1.09 a part that matched none of the patterns above was | ||
| 3151 | # dropped in silence, so "WHERE a.x = 1 OR a.x = 2", "WHERE NOT | ||
| 3152 | # a.x = 1" and "WHERE (a.x = 1)" returned the whole join result | ||
| 3153 | # as though no WHERE had been written at all. | ||
| 3154 | return ([], "Unsupported WHERE condition in a JOIN query: " | ||
| 3155 | . "'$part'. A JOIN accepts AND-separated comparisons " | ||
| 3156 | . "between a column and a column or literal, IN, " | ||
| 3157 | . "NOT IN, LIKE, BETWEEN and IS [NOT] NULL; OR, NOT " | ||
| 3158 | . "and parentheses are not supported here"); | ||
| 3159 | } | ||
| 3160 | } | ||
| 3161 | return ([ @conds ], ''); | ||
| 3162 | } | ||
| 3163 | |||
| 3164 | ############################################################################### | ||
| 3165 | # General helpers | ||
| 3166 | ############################################################################### | ||
| 3167 | sub _err { | ||
| 3168 | my($self, $msg) = @_; | ||
| 3169 | $errstr = $msg; | ||
| 3170 | return undef; | ||
| 3171 | } | ||
| 3172 | |||
| 3173 | # Identifier validation. | ||
| 3174 | # | ||
| 3175 | # Database, table and index names are used directly as path components by | ||
| 3176 | # _db_path(), _file() and _idx_file(). Without a check, a caller of the | ||
| 3177 | # low-level API could escape base_dir entirely -- drop_database('../x') | ||
| 3178 | # would hand '../x' to File::Path::rmtree() and delete a directory tree | ||
| 3179 | # outside the database. The SQL layer already restricts every identifier | ||
| 3180 | # to \w+, so this only holds the documented Perl-level methods to the | ||
| 3181 | # same rule; no name that SQL can produce is rejected here. | ||
| 3182 | sub _valid_name { | ||
| 3183 | my($name) = @_; | ||
| 3184 | return 0 unless defined $name; | ||
| 3185 | return 0 unless $name =~ /^\w+\z/; | ||
| 3186 | return 1; | ||
| 3187 | } | ||
| 3188 | |||
| 3189 | # Render a name for an error message without interpolating undef. | ||
| 3190 | sub _shown_name { | ||
| 3191 | my($name) = @_; | ||
| 3192 | return defined($name) ? $name : ''; | ||
| 3193 | } | ||
| 3194 | |||
| 3195 | sub _db_path { | ||
| 3196 | my($self, $db) = @_; | ||
| 3197 | File::Spec->catdir($self->{base_dir}, $db); | ||
| 3198 | } | ||
| 3199 | |||
| 3200 | sub _file { | ||
| 3201 | my($self, $table, $ext) = @_; | ||
| 3202 | File::Spec->catfile($self->{base_dir}, $self->{db_name}, "$table.$ext"); | ||
| 3203 | } | ||
| 3204 | |||
| 3205 | sub _load_schema { | ||
| 3206 | my($self, $table) = @_; | ||
| 3207 | unless (_valid_name($table)) { | ||
| 3208 | my $bad = _shown_name($table); | ||
| 3209 | $errstr = "Invalid table name '$bad'"; | ||
| 3210 | return undef; | ||
| 3211 | } | ||
| 3212 | return $self->{_tables}{$table} if $self->{_tables}{$table}; | ||
| 3213 | my $sch_file = $self->_file($table, 'sch'); | ||
| 3214 | unless (-f $sch_file) { | ||
| 3215 | $errstr = "Table '$table' does not exist"; | ||
| 3216 | return undef; | ||
| 3217 | } | ||
| 3218 | local *FH; | ||
| 3219 | open(FH, "< $sch_file") or do { $errstr = "Cannot read schema: $!"; return undef; }; | ||
| 3220 | my($sch, @cols, %indexes); | ||
| 3221 | $sch = {}; | ||
| 3222 | $sch->{notnull} = {}; | ||
| 3223 | $sch->{defaults} = {}; | ||
| 3224 | $sch->{checks} = {}; | ||
| 3225 | $sch->{pk} = undef; | ||
| 3226 | local $_; | ||
| 3227 | while (<FH>) { | ||
| 3228 | chomp; | ||
| 3229 | if (/^RECSIZE=(\d+)/) { | ||
| 3230 | $sch->{recsize} = $1; | ||
| 3231 | } | ||
| 3232 | elsif (/^COL=(\w+):(\w+):(\d+)(?::(\d+))?/) { | ||
| 3233 | # 4th field is decl (declared size); absent in old schema files | ||
| 3234 | push @cols, { name=>$1, type=>$2, size=>$3, | ||
| 3235 | decl=>(defined($4) ? $4+0 : $3+0) }; | ||
| 3236 | } | ||
| 3237 | elsif (/^NOTNULL=(\w+)/) { | ||
| 3238 | $sch->{notnull}{$1} = 1; | ||
| 3239 | } | ||
| 3240 | elsif (/^DEFAULT=(\w+):(.+)/) { | ||
| 3241 | $sch->{defaults}{$1} = $2; | ||
| 3242 | } | ||
| 3243 | elsif (/^CHECK=(\w+):(.+)/) { | ||
| 3244 | $sch->{checks}{$1} = $2; | ||
| 3245 | } | ||
| 3246 | elsif (/^PK=(\w+)/) { | ||
| 3247 | $sch->{pk} = $1; | ||
| 3248 | $sch->{notnull}{$1} = 1; | ||
| 3249 | } | ||
| 3250 | elsif (/^IDX=(\w+):(\w+):([01])/) { | ||
| 3251 | my($iname, $icol, $iuniq) = ($1, $2, $3); | ||
| 3252 | my($cdef) = grep { $_->{name} eq $icol } @cols; | ||
| 3253 | $indexes{$iname} = { | ||
| 3254 | name => $iname, | ||
| 3255 | col => $icol, | ||
| 3256 | unique => $iuniq+0, | ||
| 3257 | keysize => ($cdef ? $cdef->{size} : 0), | ||
| 3258 | coltype => ($cdef ? $cdef->{type} : 'VARCHAR'), | ||
| 3259 | }; | ||
| 3260 | } | ||
| 3261 | } | ||
| 3262 | close FH; | ||
| 3263 | $sch->{cols} = [ @cols ]; | ||
| 3264 | $sch->{indexes} = { %indexes }; | ||
| 3265 | $self->{_tables}{$table} = $sch; | ||
| 3266 | return $sch; | ||
| 3267 | } | ||
| 3268 | |||
| 3269 | sub _rewrite_schema { | ||
| 3270 | my($self, $table, $sch) = @_; | ||
| 3271 | my $sch_file = $self->_file($table, 'sch'); | ||
| 3272 | local *FH; | ||
| 3273 | open(FH, "> $sch_file") or return $self->_err("Cannot rewrite schema: $!"); | ||
| 3274 | my $ok = print FH "VERSION=1\n"; | ||
| 3275 | $ok &&= print FH "RECSIZE=$sch->{recsize}\n"; | ||
| 3276 | for my $c (@{$sch->{cols}}) { | ||
| 3277 | $ok &&= print FH "COL=$c->{name}:$c->{type}:$c->{size}:" | ||
| 3278 | . (defined($c->{decl}) ? $c->{decl} : $c->{size}) . "\n"; | ||
| 3279 | } | ||
| 3280 | for my $ix (values %{$sch->{indexes}}) { | ||
| 3281 | $ok &&= print FH "IDX=$ix->{name}:$ix->{col}:$ix->{unique}\n"; | ||
| 3282 | } | ||
| 3283 | for my $c (sort keys %{$sch->{notnull} || {}}) { | ||
| 3284 | $ok &&= print FH "NOTNULL=$c\n"; | ||
| 3285 | } | ||
| 3286 | for my $c (sort keys %{$sch->{defaults} || {}}) { | ||
| 3287 | $ok &&= print FH "DEFAULT=$c:$sch->{defaults}{$c}\n"; | ||
| 3288 | } | ||
| 3289 | for my $c (sort keys %{$sch->{checks} || {}}) { | ||
| 3290 | $ok &&= print FH "CHECK=$c:$sch->{checks}{$c}\n"; | ||
| 3291 | } | ||
| 3292 | $ok &&= print FH "PK=$sch->{pk}\n" if $sch->{pk}; | ||
| 3293 | my $err = $!; | ||
| 3294 | unless ($ok && close(FH)) { | ||
| 3295 | $err = $! if $ok; | ||
| 3296 | close FH if $ok; | ||
| 3297 | return $self->_err("Cannot rewrite schema: $err"); | ||
| 3298 | } | ||
| 3299 | return 1; | ||
| 3300 | } | ||
| 3301 | |||
| 3302 | # Does $v look like a number that Perl can use in arithmetic without | ||
| 3303 | # complaining under -w? Leading and trailing whitespace is allowed, an | ||
| 3304 | # optional sign, a decimal part and an exponent; everything else -- the | ||
| 3305 | # empty string, 'abc', '12abc', '0x10', 'Inf', 'NaN' -- is not numeric. | ||
| 3306 | # | ||
| 3307 | # The same test used to be written out three times (index key encoding, | ||
| 3308 | # type validation and record packing) and the FLOAT paths had no test at | ||
| 3309 | # all, which is how "isn't numeric" warnings escaped from inside this | ||
| 3310 | # module. Keep it in one place so the three callers cannot drift apart. | ||
| 3311 | sub _looks_numeric { | ||
| 3312 | my($v) = @_; | ||
| 3313 | return 0 unless defined $v; | ||
| 3314 | return $v =~ /^\s*[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?\s*$/ ? 1 : 0; | ||
| 3315 | } | ||
| 3316 | |||
| 3317 | # Is $v a well-formed calendar date in YYYY-MM-DD form? | ||
| 3318 | sub _valid_date { | ||
| 3319 | my($v) = @_; | ||
| 3320 | return 0 unless $v =~ /^(\d\d\d\d)-(\d\d)-(\d\d)$/; | ||
| 3321 | my($y, $m, $d) = ($1, $2, $3); | ||
| 3322 | return 0 if ($m < 1) || ($m > 12); | ||
| 3323 | return 0 if $d < 1; | ||
| 3324 | my @mdays = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); | ||
| 3325 | my $max = $mdays[$m-1]; | ||
| 3326 | if ($m == 2) { | ||
| 3327 | $max = 29 if ((($y % 4) == 0) && (($y % 100) != 0)) || (($y % 400) == 0); | ||
| 3328 | } | ||
| 3329 | return 0 if $d > $max; | ||
| 3330 | return 1; | ||
| 3331 | } | ||
| 3332 | |||
| 3333 | # Return an error message when $v cannot be stored in column $col, or undef | ||
| 3334 | # when it can. NULL (undef or the empty string) is always storable. | ||
| 3335 | sub _type_error { | ||
| 3336 | my($col, $v) = @_; | ||
| 3337 | return undef unless defined($v) && ($v ne ''); | ||
| 3338 | my $cn = $col->{name}; | ||
| 3339 | if ($col->{type} eq 'INT') { | ||
| 3340 | # A value that is not numeric at all keeps its historical | ||
| 3341 | # behaviour and is stored as 0. Only a numeric value too large | ||
| 3342 | # for the 4-byte field is rejected, because that used to be | ||
| 3343 | # silently clamped to the nearest limit. | ||
| 3344 | return undef unless _looks_numeric($v); | ||
| 3345 | return undef if ($v >= INT_MIN) && ($v <= INT_MAX); | ||
| 3346 | return "Integer out of range for column '$cn': '$v' " | ||
| 3347 | . '(INT holds ' . INT_MIN . ' .. ' . INT_MAX . ')'; | ||
| 3348 | } | ||
| 3349 | if ($col->{type} eq 'DATE') { | ||
| 3350 | return undef if _valid_date($v); | ||
| 3351 | return "Invalid DATE for column '$cn': '$v' (expected YYYY-MM-DD)"; | ||
| 3352 | } | ||
| 3353 | return undef; | ||
| 3354 | } | ||
| 3355 | |||
| 3356 | sub _pack_record { | ||
| 3357 | my($self, $sch, $row) = @_; | ||
| 3358 | my $data = RECORD_ACTIVE; | ||
| 3359 | for my $col (@{$sch->{cols}}) { | ||
| 3360 | my $v = defined($row->{$col->{name}}) ? $row->{$col->{name}} : ''; | ||
| 3361 | my $t = $col->{type}; | ||
| 3362 | my $s = $col->{size}; | ||
| 3363 | if ($t eq 'INT') { | ||
| 3364 | # A value that is not numeric is stored as 0. It is tested | ||
| 3365 | # here rather than left to int() so that -w stays quiet. | ||
| 3366 | my $iv = _looks_numeric($v) ? int($v) : 0; | ||
| 3367 | $iv = INT_MAX if $iv > INT_MAX; | ||
| 3368 | $iv = INT_MIN if $iv < INT_MIN; | ||
| 3369 | $data .= pack('N', $iv&0xFFFFFFFF); | ||
| 3370 | } | ||
| 3371 | elsif ($t eq 'FLOAT') { | ||
| 3372 | # Same rule as INT, and for the same reason: a value that is | ||
| 3373 | # not numeric is stored as 0 without a warning. Up to 1.08 | ||
| 3374 | # this branch handed the raw value to pack() and any string | ||
| 3375 | # that was not a number leaked an "isn't numeric" warning out | ||
| 3376 | # of the module, whatever the caller's warning settings were. | ||
| 3377 | $data .= pack('d', _looks_numeric($v) ? $v+0 : 0); | ||
| 3378 | } | ||
| 3379 | else { | ||
| 3380 | my $sv = substr($v, 0, $s); | ||
| 3381 | $sv .= "\x00" x ($s-length($sv)); | ||
| 3382 | $data .= $sv; | ||
| 3383 | } | ||
| 3384 | } | ||
| 3385 | return $data; | ||
| 3386 | } | ||
| 3387 | |||
| 3388 | sub _unpack_record { | ||
| 3389 | my($self, $sch, $raw) = @_; | ||
| 3390 | my %row; | ||
| 3391 | my $offset = 1; | ||
| 3392 | for my $col (@{$sch->{cols}}) { | ||
| 3393 | my $t = $col->{type}; | ||
| 3394 | my $s = $col->{size}; | ||
| 3395 | my $chunk = substr($raw, $offset, $s); | ||
| 3396 | if ($t eq 'INT') { | ||
| 3397 | my $uv = unpack('N', $chunk); | ||
| 3398 | $uv -= 4294967296 if $uv > 2147483647; | ||
| 3399 | $row{$col->{name}} = $uv; | ||
| 3400 | } | ||
| 3401 | elsif ($t eq 'FLOAT') { | ||
| 3402 | $row{$col->{name}} = unpack('d', $chunk); | ||
| 3403 | } | ||
| 3404 | else { | ||
| 3405 | (my $sv = $chunk) =~ s/\x00+$//; | ||
| 3406 | $row{$col->{name}} = $sv; | ||
| 3407 | } | ||
| 3408 | $offset += $s; | ||
| 3409 | } | ||
| 3410 | return { %row }; | ||
| 3411 | } | ||
| 3412 | |||
| 3413 | sub _lock_ex { flock($_[0], LOCK_EX) } | ||
| 3414 | sub _lock_sh { flock($_[0], LOCK_SH) } | ||
| 3415 | sub _unlock { flock($_[0], LOCK_UN) } | ||
| 3416 | |||
| 3417 | # Put a write handle into autoflush mode. | ||
| 3418 | # | ||
| 3419 | # print() buffers, and the buffer is written out by close(), which runs | ||
| 3420 | # after _unlock(). Without this the data would reach the file only after | ||
| 3421 | # the exclusive lock had already been handed to another process. With | ||
| 3422 | # autoflush on, every print() reaches the file while the lock is still | ||
| 3423 | # held. IO::Handle->autoflush is avoided on purpose: the select() idiom | ||
| 3424 | # needs no module and works on every Perl from 5.005_03 onwards. | ||
| 3425 | sub _autoflush { | ||
| 3426 | my $old = select($_[0]); | ||
| 3427 | $| = 1; | ||
| 3428 | select($old); | ||
| 3429 | } | ||
| 3430 | |||
| 3431 | sub _to_where_sub { | ||
| 3432 | my($wi) = @_; | ||
| 3433 | return undef unless defined $wi; | ||
| 3434 | return $wi if ref($wi) eq 'CODE'; | ||
| 3435 | return _compile_where_from_conds($wi) if ref($wi) eq 'ARRAY'; | ||
| 3436 | return undef; | ||
| 3437 | } | ||
| 3438 | |||
| 3439 | sub _split_col_defs { | ||
| 3440 | my($str) = @_; | ||
| 3441 | my @parts; | ||
| 3442 | my $cur = ''; | ||
| 3443 | my $depth = 0; | ||
| 3444 | for my $ch (split //, $str) { | ||
| 3445 | if ($ch eq '(') { | ||
| 3446 | $depth++; | ||
| 3447 | $cur .= $ch; | ||
| 3448 | } | ||
| 3449 | elsif ($ch eq ')') { | ||
| 3450 | $depth--; | ||
| 3451 | $cur .= $ch; | ||
| 3452 | } | ||
| 3453 | elsif (($ch eq ',') && ($depth == 0)) { | ||
| 3454 | push @parts, $cur; | ||
| 3455 | $cur = ''; | ||
| 3456 | } | ||
| 3457 | else { | ||
| 3458 | $cur .= $ch; | ||
| 3459 | } | ||
| 3460 | } | ||
| 3461 | push @parts, $cur if $cur =~ /\S/; | ||
| 3462 | return @parts; | ||
| 3463 | } | ||
| 3464 | |||
| 3465 | sub _parse_values { | ||
| 3466 | my($str) = @_; | ||
| 3467 | my @vals; | ||
| 3468 | while (length $str) { | ||
| 3469 | $str =~ s/^\s+//; | ||
| 3470 | last unless length $str; | ||
| 3471 | if ($str =~ s/^'((?:[^']|'')*)'(?:\s*,\s*|\s*$)//) { | ||
| 3472 | my $s = $1; | ||
| 3473 | $s =~ s/''/'/g; | ||
| 3474 | push @vals, $s; | ||
| 3475 | } | ||
| 3476 | elsif ($str =~ s/^(NULL)(?:\s*,\s*|\s*$)//i) { | ||
| 3477 | push @vals, undef; | ||
| 3478 | } | ||
| 3479 | elsif ($str =~ s/^(-?\d+\.?\d*)(?:\s*,\s*|\s*$)//) { | ||
| 3480 | push @vals, $1; | ||
| 3481 | } | ||
| 3482 | else { | ||
| 3483 | last; | ||
| 3484 | } | ||
| 3485 | } | ||
| 3486 | return @vals; | ||
| 3487 | } | ||
| 3488 | |||
| 3489 | sub _parse_conditions { | ||
| 3490 | my($expr) = @_; | ||
| 3491 | my @conds; | ||
| 3492 | |||
| 3493 | # Use paren-aware AND splitter | ||
| 3494 | my @parts = _split_and_clauses($expr); | ||
| 3495 | for my $part (@parts) { | ||
| 3496 | $part =~ s/^\s+|\s+$//g; | ||
| 3497 | |||
| 3498 | # col [NOT] IN (val, val, ...) -- expanded from subquery or literal list | ||
| 3499 | if ($part =~ /^(\w+)\s+(NOT\s+)?IN\s*\(([^)]*)\)\s*$/i) { | ||
| 3500 | my($col, $neg, $list_str) = ($1, $2, $3); | ||
| 3501 | my @vals; | ||
| 3502 | |||
| 3503 | # parse list: numbers or quoted strings or NULL | ||
| 3504 | my $ls = $list_str; | ||
| 3505 | while ($ls =~ s/^\s*(?:'([^']*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) { | ||
| 3506 | my($sv, $nv, $nl) = ($1, $2, $3); | ||
| 3507 | push @vals, defined($nl) ? undef : (defined($sv) ? $sv : $nv); | ||
| 3508 | } | ||
| 3509 | push @conds, { | ||
| 3510 | col => $col, | ||
| 3511 | op => $neg ? 'NOT_IN' : 'IN', | ||
| 3512 | vals => [ @vals ], | ||
| 3513 | }; | ||
| 3514 | next; | ||
| 3515 | } | ||
| 3516 | |||
| 3517 | # EXISTS (1) or EXISTS (0) -- already evaluated by subquery expander | ||
| 3518 | if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) { | ||
| 3519 | my($neg, $val) = ($1, $2); | ||
| 3520 | my $truth = $val ? 1 : 0; | ||
| 3521 | $truth = 1 - $truth if $neg; | ||
| 3522 | push @conds, { op => 'CONST', val => $truth }; | ||
| 3523 | next; | ||
| 3524 | } | ||
| 3525 | |||
| 3526 | # EXISTS (1) or NOT EXISTS (0) without outer parens (legacy) | ||
| 3527 | if ($part =~ /^(NOT\s+)?EXISTS\s+(\d+)$/i) { | ||
| 3528 | my($neg, $val) = ($1, $2); | ||
| 3529 | my $truth = $val ? 1 : 0; | ||
| 3530 | $truth = 1 - $truth if $neg; | ||
| 3531 | push @conds, { op => 'CONST', val => $truth }; | ||
| 3532 | next; | ||
| 3533 | } | ||
| 3534 | |||
| 3535 | # col OP NULL -- SQL NULL semantics: comparison with NULL is always false | ||
| 3536 | if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*NULL$/i) { | ||
| 3537 | push @conds, { op => 'CONST', val => 0 }; | ||
| 3538 | next; | ||
| 3539 | } | ||
| 3540 | |||
| 3541 | # IS [NOT] NULL | ||
| 3542 | if ($part =~ /^(\w+)\s+IS\s+(NOT\s+)?NULL$/i) { | ||
| 3543 | my($col, $neg) = ($1, $2); | ||
| 3544 | push @conds, { col=>$col, op=>$neg ? 'IS_NOT_NULL' : 'IS_NULL' }; | ||
| 3545 | next; | ||
| 3546 | } | ||
| 3547 | |||
| 3548 | # Normal col OP literal | ||
| 3549 | if ($part =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>|LIKE)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/i) { | ||
| 3550 | my($col, $op, $sv, $nv) = ($1, $2, $3, $4); | ||
| 3551 | push @conds, { col=>$col, op=>uc($op), val=>(defined($sv) ? $sv : $nv) }; | ||
| 3552 | } | ||
| 3553 | } | ||
| 3554 | return [ @conds ]; | ||
| 3555 | } | ||
| 3556 | |||
| 3557 | sub _compile_where_from_conds { | ||
| 3558 | my($conds) = @_; | ||
| 3559 | return undef unless $conds && @$conds; | ||
| 3560 | return sub { | ||
| 3561 | my($row) = @_; | ||
| 3562 | for my $c (@$conds) { | ||
| 3563 | my $op = $c->{op}; | ||
| 3564 | |||
| 3565 | # Constant (pre-evaluated EXISTS/NOT EXISTS) | ||
| 3566 | if ($op eq 'CONST') { | ||
| 3567 | return 0 unless $c->{val}; | ||
| 3568 | # IN / NOT IN with value list | ||
| 3569 | } | ||
| 3570 | elsif (($op eq 'IN') || ($op eq 'NOT_IN')) { | ||
| 3571 | my $rv = defined($row->{$c->{col}}) ? $row->{$c->{col}} : ''; | ||
| 3572 | my $found = 0; | ||
| 3573 | my $has_null = 0; | ||
| 3574 | for my $cv (@{$c->{vals}}) { | ||
| 3575 | unless (defined $cv) { $has_null = 1; next } | ||
| 3576 | my $num = (($rv =~ /^-?\d+\.?\d*$/) && ($cv =~ /^-?\d+\.?\d*$/)); | ||
| 3577 | if ($num ? ($rv == $cv) : ($rv eq $cv)) { | ||
| 3578 | $found = 1; | ||
| 3579 | last; | ||
| 3580 | } | ||
| 3581 | } | ||
| 3582 | return 0 if $found && ($op eq 'NOT_IN'); | ||
| 3583 | return 0 if !$found && ($op eq 'IN'); | ||
| 3584 | # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN | ||
| 3585 | # when the row value was not found in the non-NULL values. | ||
| 3586 | return 0 if $has_null && !$found && ($op eq 'NOT_IN'); | ||
| 3587 | # IS NULL / IS NOT NULL | ||
| 3588 | } | ||
| 3589 | elsif ($op eq 'IS_NULL') { | ||
| 3590 | return 0 unless !defined($row->{$c->{col}}) || ($row->{$c->{col}} eq ''); | ||
| 3591 | } | ||
| 3592 | elsif ($op eq 'IS_NOT_NULL') { | ||
| 3593 | return 0 unless defined($row->{$c->{col}}) && ($row->{$c->{col}} ne ''); | ||
| 3594 | # Standard comparison | ||
| 3595 | } | ||
| 3596 | else { | ||
| 3597 | my $rv = defined($row->{$c->{col}}) ? $row->{$c->{col}} : ''; | ||
| 3598 | my $cv = $c->{val}; | ||
| 3599 | my $num = (($rv =~ /^-?\d+\.?\d*$/) && defined($cv) && ($cv =~ /^-?\d+\.?\d*$/)); | ||
| 3600 | if ($op eq '=') { | ||
| 3601 | return 0 unless $num ? ($rv == $cv) : ($rv eq $cv); | ||
| 3602 | } | ||
| 3603 | elsif (($op eq '!=') || ($op eq '<>')) { | ||
| 3604 | return 0 unless $num ? ($rv != $cv) : ($rv ne $cv); | ||
| 3605 | } | ||
| 3606 | elsif ($op eq '<') { | ||
| 3607 | return 0 unless $num ? ($rv < $cv) : ($rv lt $cv); | ||
| 3608 | } | ||
| 3609 | elsif ($op eq '>') { | ||
| 3610 | return 0 unless $num ? ($rv > $cv) : ($rv gt $cv); | ||
| 3611 | } | ||
| 3612 | elsif ($op eq '<=') { | ||
| 3613 | return 0 unless $num ? ($rv <= $cv) : ($rv le $cv); | ||
| 3614 | } | ||
| 3615 | elsif ($op eq '>=') { | ||
| 3616 | return 0 unless $num ? ($rv >= $cv) : ($rv ge $cv); | ||
| 3617 | } | ||
| 3618 | elsif ($op eq 'LIKE') { | ||
| 3619 | my $p = _like_to_re($cv); | ||
| 3620 | return 0 unless $rv =~ /^$p$/i; | ||
| 3621 | } | ||
| 3622 | } | ||
| 3623 | } | ||
| 3624 | return 1; | ||
| 3625 | }; | ||
| 3626 | } | ||
| 3627 | |||
| 3628 | ############################################################################### | ||
| 3629 | # SQL-92 Engine | ||
| 3630 | ############################################################################### | ||
| 3631 | |||
| 3632 | # ============================================================================= | ||
| 3633 | # Expression evaluator eval_expr($expr, \%row) -> scalar | ||
| 3634 | # ============================================================================= | ||
| 3635 | sub eval_expr { | ||
| 3636 | my($expr, $row) = @_; | ||
| 3637 | return undef unless defined $expr; | ||
| 3638 | $expr =~ s/^\s+|\s+$//g; | ||
| 3639 | return undef unless length($expr); | ||
| 3640 | return undef if $expr =~ /^NULL$/i; | ||
| 3641 | return $expr + 0 if $expr =~ /^-?\d+\.?\d*$/; | ||
| 3642 | if ($expr =~ /^'((?:[^']|'')*)'$/) { | ||
| 3643 | (my $s = $1) =~ s/''/'/g; | ||
| 3644 | return $s; | ||
| 3645 | } | ||
| 3646 | if (($expr =~ /^\((.+)\)$/s) && ($1 !~ /^\s*SELECT\b/i)) { | ||
| 3647 | return eval_expr($1, $row); | ||
| 3648 | } | ||
| 3649 | if ($expr =~ /^CASE\b(.*)\bEND$/si) { | ||
| 3650 | return eval_case($1, $row); | ||
| 3651 | } | ||
| 3652 | if ($expr =~ /^COALESCE\s*\((.+)\)$/si) { | ||
| 3653 | for my $a (args($1)) { | ||
| 3654 | my $v = eval_expr($a, $row); | ||
| 3655 | return $v if defined($v) && ($v ne ''); | ||
| 3656 | } | ||
| 3657 | return undef; | ||
| 3658 | } | ||
| 3659 | if ($expr =~ /^NULLIF\s*\((.+)\)$/si) { | ||
| 3660 | my @a = args($1); | ||
| 3661 | return undef unless @a == 2; | ||
| 3662 | my($va, $vb) = (eval_expr($a[0], $row), eval_expr($a[1], $row)); | ||
| 3663 | if (defined($va) && defined($vb)) { | ||
| 3664 | return undef if ((($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/)) ? ($va == $vb) : ($va eq $vb)); | ||
| 3665 | } | ||
| 3666 | return $va; | ||
| 3667 | } | ||
| 3668 | if ($expr =~ /^CAST\s*\(\s*(.+?)\s+AS\s+(\w+(?:\s*\(\s*\d+\s*\))?)\s*\)$/si) { | ||
| 3669 | my($ie, $t) = ($1, uc($2)); | ||
| 3670 | my $v = eval_expr($ie, $row); | ||
| 3671 | return undef unless defined $v; | ||
| 3672 | return int($v) if $t =~ /^INT/i; | ||
| 3673 | return $v + 0 if $t =~ /^(FLOAT|REAL|DOUBLE|NUMERIC|DECIMAL)/i; | ||
| 3674 | return "$v"; | ||
| 3675 | } | ||
| 3676 | if ($expr =~ /^(UPPER|LOWER|LENGTH|ABS|SIGN|TRIM|LTRIM|RTRIM)\s*\((.+)\)$/si) { | ||
| 3677 | my($fn, $arg) = (uc($1), $2); | ||
| 3678 | my $v = eval_expr($arg, $row); | ||
| 3679 | return undef unless defined $v; | ||
| 3680 | return uc($v) if $fn eq 'UPPER'; | ||
| 3681 | return lc($v) if $fn eq 'LOWER'; | ||
| 3682 | return length($v) if $fn eq 'LENGTH'; | ||
| 3683 | return abs($v + 0) if $fn eq 'ABS'; | ||
| 3684 | return (($v > 0) ? 1 : ($v < 0) ? -1 : 0) if $fn eq 'SIGN'; | ||
| 3685 | if ($fn eq 'TRIM') { | ||
| 3686 | (my $s = $v) =~ s/^\s+|\s+$//g; | ||
| 3687 | return $s; | ||
| 3688 | } | ||
| 3689 | if ($fn eq 'LTRIM') { | ||
| 3690 | (my $s = $v) =~ s/^\s+//; | ||
| 3691 | return $s; | ||
| 3692 | } | ||
| 3693 | if ($fn eq 'RTRIM') { | ||
| 3694 | (my $s = $v) =~ s/\s+$//; | ||
| 3695 | return $s; | ||
| 3696 | } | ||
| 3697 | } | ||
| 3698 | if ($expr =~ /^ROUND\s*\((.+)\)$/si) { | ||
| 3699 | my @a = args($1); | ||
| 3700 | my $v = eval_expr($a[0], $row); | ||
| 3701 | return undef unless defined $v; | ||
| 3702 | my $d = (@a > 1) ? int(eval_expr($a[1], $row) || 0) : 0; | ||
| 3703 | return sprintf("%.${d}f", $v+0) + 0; | ||
| 3704 | } | ||
| 3705 | if ($expr =~ /^(FLOOR|CEIL(?:ING)?)\s*\((.+)\)$/si) { | ||
| 3706 | my($fn, $arg) = (uc($1), $2); | ||
| 3707 | my $v = eval_expr($arg, $row); | ||
| 3708 | return undef unless defined $v; | ||
| 3709 | return $fn eq 'FLOOR' ? POSIX::floor($v+0) : POSIX::ceil($v+0); | ||
| 3710 | } | ||
| 3711 | if ($expr =~ /^MOD\s*\((.+)\)$/si) { | ||
| 3712 | my @a = args($1); | ||
| 3713 | return undef unless @a == 2; | ||
| 3714 | my($a, $b) = (eval_expr($a[0], $row)+0, eval_expr($a[1], $row)+0); | ||
| 3715 | return undef if $b == 0; | ||
| 3716 | return $a % $b; | ||
| 3717 | } | ||
| 3718 | if ($expr =~ /^(?:SUBSTR|SUBSTRING)\s*\((.+)\)$/si) { | ||
| 3719 | my $inner = $1; | ||
| 3720 | my($se, $ste, $le); | ||
| 3721 | if ($inner =~ /^(.+?)\s+FROM\s+(\S+)(?:\s+FOR\s+(.+))?$/si) { | ||
| 3722 | ($se, $ste, $le) = ($1, $2, $3); | ||
| 3723 | } | ||
| 3724 | else { | ||
| 3725 | ($se, $ste, $le) = args($inner); | ||
| 3726 | } | ||
| 3727 | my $s = eval_expr($se, $row); | ||
| 3728 | return undef unless defined $s; | ||
| 3729 | my $st = int(eval_expr($ste, $row) || 1); | ||
| 3730 | $st = 1 if $st < 1; | ||
| 3731 | return defined($le) | ||
| 3732 | ? substr($s, $st-1, int(eval_expr($le, $row) || 0)) | ||
| 3733 | : substr($s, $st-1); | ||
| 3734 | } | ||
| 3735 | if ($expr =~ /^CONCAT\s*\((.+)\)$/si) { | ||
| 3736 | my @args = args($1); | ||
| 3737 | my $r = ''; | ||
| 3738 | for (@args) { | ||
| 3739 | my $v = eval_expr($_, $row); | ||
| 3740 | $r .= defined($v) ? $v : ''; | ||
| 3741 | } | ||
| 3742 | return $r; | ||
| 3743 | } | ||
| 3744 | |||
| 3745 | # Binary operator: find rightmost at depth 0 (precedence low->high: || then +/- then */%) | ||
| 3746 | for my $op ('\\|\\|', '[+\\-]', '[*/%]') { | ||
| 3747 | my $p = find_binop($expr, $op); | ||
| 3748 | if (defined $p) { | ||
| 3749 | my $opsym = substr($expr, $p->{s}, $p->{l}); | ||
| 3750 | my $lv = eval_expr(substr($expr, 0, $p->{s}), $row); | ||
| 3751 | my $rv = eval_expr(substr($expr, $p->{s}+$p->{l}), $row); | ||
| 3752 | if ($opsym eq '||') { | ||
| 3753 | return (defined($lv) ? $lv : '').(defined($rv) ? $rv : ''); | ||
| 3754 | } | ||
| 3755 | return undef unless defined($lv) && defined($rv); | ||
| 3756 | my($l, $r) = ($lv + 0, $rv + 0); | ||
| 3757 | return $l + $r if $opsym eq '+'; | ||
| 3758 | return $l - $r if $opsym eq '-'; | ||
| 3759 | return $l * $r if $opsym eq '*'; | ||
| 3760 | return undef if (($opsym eq '/') || ($opsym eq '%')) && ($r == 0); | ||
| 3761 | return $l / $r if $opsym eq '/'; | ||
| 3762 | return $l % $r if $opsym eq '%'; | ||
| 3763 | } | ||
| 3764 | } | ||
| 3765 | if ($expr =~ /^-([\w('.].*)$/s) { | ||
| 3766 | my $v = eval_expr($1, $row); | ||
| 3767 | return undef unless defined $v; | ||
| 3768 | return - ($v + 0); | ||
| 3769 | } | ||
| 3770 | if ($expr =~ /^(\w+)\.(\w+)$/) { | ||
| 3771 | my($a, $c) = ($1, $2); | ||
| 3772 | return exists($row->{"$a.$c"}) ? $row->{"$a.$c"} : $row->{$c}; | ||
| 3773 | } | ||
| 3774 | return $row->{$expr} if $expr =~ /^\w+$/; | ||
| 3775 | return undef; | ||
| 3776 | } | ||
| 3777 | |||
| 3778 | sub eval_case { | ||
| 3779 | my($body, $row) = @_; | ||
| 3780 | $body =~ s/^\s+|\s+$//g; | ||
| 3781 | my $base; | ||
| 3782 | unless ($body =~ /^\s*WHEN\b/i) { | ||
| 3783 | $body =~ s/^(.+?)\s+(?=WHEN\b)//si and $base = $1; | ||
| 3784 | } | ||
| 3785 | my $else; | ||
| 3786 | $body =~ s/\s*\bELSE\b\s+(.+?)\s*$//si and $else = $1; | ||
| 3787 | while ($body =~ s/^\s*WHEN\s+(.+?)\s+THEN\s+(.+?)(?=\s+WHEN\b|\s*$)//si) { | ||
| 3788 | my($we, $te) = ($1, $2); | ||
| 3789 | my $m; | ||
| 3790 | if (defined $base) { | ||
| 3791 | my($bv, $wv) = (eval_expr($base, $row), eval_expr($we, $row)); | ||
| 3792 | $m = defined($bv) && defined($wv) && ((($bv =~ /^-?\d+\.?\d*$/) && ($wv =~ /^-?\d+\.?\d*$/)) ? ($bv == $wv) : ($bv eq $wv)); | ||
| 3793 | } | ||
| 3794 | else { | ||
| 3795 | $m = eval_bool($we, $row); | ||
| 3796 | } | ||
| 3797 | return eval_expr($te, $row) if $m; | ||
| 3798 | } | ||
| 3799 | return defined($else) ? eval_expr($else, $row) : undef; | ||
| 3800 | } | ||
| 3801 | |||
| 3802 | sub eval_bool { | ||
| 3803 | my($expr, $row) = @_; | ||
| 3804 | $expr =~ s/^\s+|\s+$//g; | ||
| 3805 | if ($expr =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) { | ||
| 3806 | my($l, $op, $r) = ($1, uc($2), $3); | ||
| 3807 | my($lv, $rv) = (eval_expr($l, $row), eval_expr($r, $row)); | ||
| 3808 | return 0 unless defined($lv) && defined($rv); | ||
| 3809 | my $n = (($lv =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/)); | ||
| 3810 | return $n ? ($lv == $rv) : ($lv eq $rv) if $op eq '='; | ||
| 3811 | return $n ? ($lv != $rv) : ($lv ne $rv) if $op =~ /^(!|<>)/; | ||
| 3812 | return $n ? ($lv < $rv) : ($lv lt $rv) if $op eq '<'; | ||
| 3813 | return $n ? ($lv > $rv) : ($lv gt $rv) if $op eq '>'; | ||
| 3814 | return $n ? ($lv <= $rv) : ($lv le $rv) if $op eq '<='; | ||
| 3815 | return $n ? ($lv >= $rv) : ($lv ge $rv) if $op eq '>='; | ||
| 3816 | } | ||
| 3817 | if ($expr =~ /^(.+)\s+IS\s+(NOT\s+)?NULL$/si) { | ||
| 3818 | my $v = eval_expr($1, $row); | ||
| 3819 | return $2 ? (defined($v) && ($v ne '')) : (!defined($v) || ($v eq '')); | ||
| 3820 | } | ||
| 3821 | return 0; | ||
| 3822 | } | ||
| 3823 | |||
| 3824 | # Argument splitter (handles parentheses and string literals) | ||
| 3825 | sub args { | ||
| 3826 | my($str) = @_; | ||
| 3827 | my @parts; | ||
| 3828 | my $cur = ''; | ||
| 3829 | my $d = 0; | ||
| 3830 | my $in_q = 0; | ||
| 3831 | for my $ch (split //, $str) { | ||
| 3832 | if (($ch eq "'") && !$in_q) { | ||
| 3833 | $in_q = 1; | ||
| 3834 | $cur .= $ch; | ||
| 3835 | } | ||
| 3836 | elsif (($ch eq "'") && $in_q) { | ||
| 3837 | $in_q = 0; | ||
| 3838 | $cur .= $ch; | ||
| 3839 | } | ||
| 3840 | elsif ($in_q) { | ||
| 3841 | $cur .= $ch; | ||
| 3842 | } | ||
| 3843 | elsif ($ch eq '(') { | ||
| 3844 | $d++; | ||
| 3845 | $cur .= $ch; | ||
| 3846 | } | ||
| 3847 | elsif ($ch eq ')') { | ||
| 3848 | $d--; | ||
| 3849 | $cur .= $ch; | ||
| 3850 | } | ||
| 3851 | elsif (($ch eq ',') && ($d == 0)) { | ||
| 3852 | push @parts, $cur; | ||
| 3853 | $cur = ''; | ||
| 3854 | } | ||
| 3855 | else { | ||
| 3856 | $cur .= $ch; | ||
| 3857 | } | ||
| 3858 | } | ||
| 3859 | push @parts, $cur if $cur =~ /\S/; | ||
| 3860 | return @parts; | ||
| 3861 | } | ||
| 3862 | |||
| 3863 | # Find rightmost binary operator at depth 0 | ||
| 3864 | sub find_binop { | ||
| 3865 | my($expr, $op_pat) = @_; | ||
| 3866 | my $d = 0; | ||
| 3867 | my $in_q = 0; | ||
| 3868 | my $best = undef; | ||
| 3869 | for my $i (0 .. length($expr)-1) { | ||
| 3870 | my $ch = substr($expr, $i, 1); | ||
| 3871 | if (($ch eq "'") && !$in_q) { | ||
| 3872 | $in_q = 1; | ||
| 3873 | } | ||
| 3874 | elsif (($ch eq "'") && $in_q) { | ||
| 3875 | $in_q = 0; | ||
| 3876 | } | ||
| 3877 | elsif (!$in_q && ($ch eq '(')) { | ||
| 3878 | $d++; | ||
| 3879 | } | ||
| 3880 | elsif (!$in_q && ($ch eq ')')) { | ||
| 3881 | $d--; | ||
| 3882 | } | ||
| 3883 | elsif (!$in_q && ($d == 0) && ($i > 0)) { | ||
| 3884 | if (substr($expr, $i) =~ /^($op_pat)/) { | ||
| 3885 | $best = { s=>$i, l=>length($1) }; | ||
| 3886 | } | ||
| 3887 | } | ||
| 3888 | } | ||
| 3889 | return $best; | ||
| 3890 | } | ||
| 3891 | |||
| 3892 | # ============================================================================= | ||
| 3893 | # WHERE engine where_sub($expr) -> coderef | ||
| 3894 | # ============================================================================= | ||
| 3895 | sub where_sub { | ||
| 3896 | my($expr) = @_; | ||
| 3897 | return sub{1} unless defined($expr) && ($expr =~ /\S/); | ||
| 3898 | return compile_tree(parse_bool($expr)); | ||
| 3899 | } | ||
| 3900 | |||
| 3901 | sub parse_bool { | ||
| 3902 | my($expr) = @_; | ||
| 3903 | $expr =~ s/^\s+|\s+$//g; | ||
| 3904 | my @or = bool_split($expr, 'OR'); | ||
| 3905 | return { op=>'OR', kids=>[map{parse_bool($_)}@or] } if @or > 1; | ||
| 3906 | my @and = bool_split($expr, 'AND'); | ||
| 3907 | return { op=>'AND', kids=>[map{parse_bool($_)}@and] } if @and > 1; | ||
| 3908 | return { op=>'NOT', kids=>[parse_bool($1)] } if $expr =~ /^NOT\s+(.+)$/si; | ||
| 3909 | if (($expr =~ /^\((.+)\)$/s) && ($1 !~ /^\s*SELECT\b/i)) { | ||
| 3910 | return parse_bool($1); | ||
| 3911 | } | ||
| 3912 | return { op=>'LEAF', cond=>parse_leaf($expr) }; | ||
| 3913 | } | ||
| 3914 | |||
| 3915 | sub bool_split { | ||
| 3916 | my($expr, $kw) = @_; | ||
| 3917 | my $kl = length($kw); | ||
| 3918 | my @parts; | ||
| 3919 | my $cur = ''; | ||
| 3920 | my $d = 0; | ||
| 3921 | my $in_q = 0; | ||
| 3922 | my $i = 0; | ||
| 3923 | my $len = length($expr); | ||
| 3924 | while ($i < $len) { | ||
| 3925 | my $ch = substr($expr, $i, 1); | ||
| 3926 | if (($ch eq "'") && !$in_q) { | ||
| 3927 | $in_q = 1; | ||
| 3928 | $cur .= $ch; | ||
| 3929 | } | ||
| 3930 | elsif (($ch eq "'") && $in_q) { | ||
| 3931 | $in_q = 0; | ||
| 3932 | $cur .= $ch; | ||
| 3933 | } | ||
| 3934 | elsif ($in_q) { | ||
| 3935 | $cur .= $ch; | ||
| 3936 | } | ||
| 3937 | elsif ($ch eq '(') { | ||
| 3938 | $d++; | ||
| 3939 | $cur .= $ch; | ||
| 3940 | } | ||
| 3941 | elsif ($ch eq ')') { | ||
| 3942 | $d--; | ||
| 3943 | $cur .= $ch; | ||
| 3944 | } | ||
| 3945 | elsif (($d == 0) | ||
| 3946 | && !$in_q | ||
| 3947 | && (uc(substr($expr, $i, $kl)) eq $kw) | ||
| 3948 | && (($i == 0) || (substr($expr, $i-1, 1) =~ /\s/)) | ||
| 3949 | && (($i+$kl) < $len) | ||
| 3950 | && (substr($expr, $i+$kl, 1) =~ /\s/) | ||
| 3951 | ) { | ||
| 3952 | |||
| 3953 | # For AND: do not split the AND inside BETWEEN x AND y | ||
| 3954 | if ($kw eq 'AND') { | ||
| 3955 | my $before = $cur; | ||
| 3956 | $before =~ s/^\s+|\s+$//g; | ||
| 3957 | if ($before =~ /\bBETWEEN\s+\S+\s*$/i) { | ||
| 3958 | $cur .= $ch; | ||
| 3959 | $i++; | ||
| 3960 | next; | ||
| 3961 | } | ||
| 3962 | } | ||
| 3963 | push @parts, $cur; | ||
| 3964 | $cur = ''; | ||
| 3965 | $i += $kl; | ||
| 3966 | next; | ||
| 3967 | } | ||
| 3968 | else { | ||
| 3969 | $cur .= $ch; | ||
| 3970 | } | ||
| 3971 | $i++; | ||
| 3972 | } | ||
| 3973 | push @parts, $cur; | ||
| 3974 | @parts = grep {/\S/} @parts; | ||
| 3975 | return @parts > 1 ? @parts : ($expr); | ||
| 3976 | } | ||
| 3977 | |||
| 3978 | # Split $sql into alternating chunks of [ is_literal, text ] so that a | ||
| 3979 | # placeholder inside a quoted string is never mistaken for a bind marker. | ||
| 3980 | sub _split_sql_literals { | ||
| 3981 | my($sql) = @_; | ||
| 3982 | my @parts; | ||
| 3983 | my $len = length $sql; | ||
| 3984 | my $i = 0; | ||
| 3985 | my $cur = ''; | ||
| 3986 | while ($i < $len) { | ||
| 3987 | if (substr($sql, $i, 1) eq "'") { | ||
| 3988 | push @parts, [ 0, $cur ] if length $cur; | ||
| 3989 | $cur = ''; | ||
| 3990 | my $j = $i + 1; | ||
| 3991 | while ($j < $len) { | ||
| 3992 | if (substr($sql, $j, 1) ne "'") { $j++; next } | ||
| 3993 | last unless substr($sql, $j+1, 1) eq "'"; | ||
| 3994 | $j += 2; | ||
| 3995 | } | ||
| 3996 | $j = $len if $j > $len; | ||
| 3997 | push @parts, [ 1, substr($sql, $i, $j-$i+1) ]; | ||
| 3998 | $i = $j + 1; | ||
| 3999 | next; | ||
| 4000 | } | ||
| 4001 | $cur .= substr($sql, $i, 1); | ||
| 4002 | $i++; | ||
| 4003 | } | ||
| 4004 | push @parts, [ 0, $cur ] if length $cur; | ||
| 4005 | return @parts; | ||
| 4006 | } | ||
| 4007 | |||
| 4008 | # Collapse each run of whitespace to a single space, but leave string | ||
| 4009 | # literals byte for byte alone: a newline or a tab inside a literal is | ||
| 4010 | # part of the value, not statement layout. | ||
| 4011 | sub _normalize_sql_space { | ||
| 4012 | my($sql) = @_; | ||
| 4013 | my $out = ''; | ||
| 4014 | for my $part (_split_sql_literals($sql)) { | ||
| 4015 | if ($part->[0]) { $out .= $part->[1]; next } | ||
| 4016 | my $chunk = $part->[1]; | ||
| 4017 | $chunk =~ s/\s+/ /g; | ||
| 4018 | $out .= $chunk; | ||
| 4019 | } | ||
| 4020 | return $out; | ||
| 4021 | } | ||
| 4022 | |||
| 4023 | sub _strip_sql_comments { | ||
| 4024 | my($sql) = @_; | ||
| 4025 | my $out = ''; | ||
| 4026 | my $len = length($sql); | ||
| 4027 | my $i = 0; | ||
| 4028 | while ($i < $len) { | ||
| 4029 | my $ch = substr($sql, $i, 1); | ||
| 4030 | if ($ch eq "'") { | ||
| 4031 | my $j = $i + 1; | ||
| 4032 | while ($j < $len) { | ||
| 4033 | if (substr($sql, $j, 1) ne "'") { $j++; next } | ||
| 4034 | last unless substr($sql, $j+1, 1) eq "'"; | ||
| 4035 | $j += 2; | ||
| 4036 | } | ||
| 4037 | $j = $len if $j > $len; | ||
| 4038 | $out .= substr($sql, $i, $j-$i+1); | ||
| 4039 | $i = $j + 1; | ||
| 4040 | next; | ||
| 4041 | } | ||
| 4042 | if (substr($sql, $i, 2) eq '--') { | ||
| 4043 | $i += 2; | ||
| 4044 | $i++ while ($i < $len) && (substr($sql, $i, 1) ne "\n"); | ||
| 4045 | $out .= ' '; | ||
| 4046 | next; | ||
| 4047 | } | ||
| 4048 | if (substr($sql, $i, 2) eq '/*') { | ||
| 4049 | $i += 2; | ||
| 4050 | $i++ while ($i < $len) && (substr($sql, $i, 2) ne '*/'); | ||
| 4051 | $i += 2; | ||
| 4052 | $out .= ' '; | ||
| 4053 | next; | ||
| 4054 | } | ||
| 4055 | $out .= $ch; | ||
| 4056 | $i++; | ||
| 4057 | } | ||
| 4058 | $out =~ s/^\s+|\s+$//g; | ||
| 4059 | return $out; | ||
| 4060 | } | ||
| 4061 | |||
| 4062 | sub _like_to_re { | ||
| 4063 | my($pat) = @_; | ||
| 4064 | my $re = ''; | ||
| 4065 | for my $i (0 .. length($pat)-1) { | ||
| 4066 | my $ch = substr($pat, $i, 1); | ||
| 4067 | if ($ch eq '%') { $re .= '.*' } | ||
| 4068 | elsif ($ch eq '_') { $re .= '.' } | ||
| 4069 | else { $re .= quotemeta($ch) } | ||
| 4070 | } | ||
| 4071 | return $re; | ||
| 4072 | } | ||
| 4073 | |||
| 4074 | sub parse_leaf { | ||
| 4075 | my($part) = @_; | ||
| 4076 | $part =~ s/^\s+|\s+$//g; | ||
| 4077 | if ($part =~ /^(NOT\s+)?EXISTS\s*\((\d+)\)$/i) { | ||
| 4078 | my($neg, $v) = ($1, $2); | ||
| 4079 | my $t = $v ? 1 : 0; | ||
| 4080 | $t = 1 - $t if $neg; | ||
| 4081 | return { op=>'CONST', val=>$t }; | ||
| 4082 | } | ||
| 4083 | if ($part =~ /^([\w.]+)\s+(NOT\s+)?IN\s*\(([^)]*)\)$/si) { | ||
| 4084 | my($col, $neg, $ls) = ($1, $2, $3); | ||
| 4085 | my @vals; | ||
| 4086 | while ($ls =~ s/^\s*(?:'((?:[^']|'')*)'|(-?\d+\.?\d*)|(NULL))\s*(?:,|$)//i) { | ||
| 4087 | my($sv, $nv, $nl) = ($1, $2, $3); | ||
| 4088 | if (defined $nl) { | ||
| 4089 | push @vals, undef; | ||
| 4090 | } | ||
| 4091 | elsif (defined $sv) { | ||
| 4092 | (my $x = $sv) =~ s/''/'/g; | ||
| 4093 | push @vals, $x; | ||
| 4094 | } | ||
| 4095 | else { | ||
| 4096 | push @vals, $nv; | ||
| 4097 | } | ||
| 4098 | } | ||
| 4099 | return { op=>($neg ? 'NOT_IN' : 'IN'), col=>$col, vals=>[ @vals ] }; | ||
| 4100 | } | ||
| 4101 | return { op=>'CONST', val=>0 } if $part =~ /^[\w.]+\s*(?:=|!=|<>|<=|>=|<|>)\s*NULL$/si; | ||
| 4102 | if ($part =~ /^([\w.]+)\s+IS\s+(NOT\s+)?NULL$/si) { | ||
| 4103 | return { op=>($2 ? 'IS_NOT_NULL' : 'IS_NULL'), col=>$1 }; | ||
| 4104 | } | ||
| 4105 | if ($part =~ /^([\w.]+)\s+(NOT\s+)?BETWEEN\s+(.+?)\s+AND\s+(.+)$/si) { | ||
| 4106 | my($col, $neg, $lo, $hi) = ($1, $2, $3, $4); | ||
| 4107 | $lo =~ s/^'(.*)'$/$1/s; | ||
| 4108 | $hi =~ s/^'(.*)'$/$1/s; | ||
| 4109 | return { op=>($neg ? 'NOT_BETWEEN' : 'BETWEEN'), col=>$col, lo=>$lo, hi=>$hi }; | ||
| 4110 | } | ||
| 4111 | if ($part =~ /^(.+?)\s+(NOT\s+)?LIKE\s+('(?:[^']|'')*'|\S+)$/si) { | ||
| 4112 | my($lhs, $neg, $pat) = ($1, $2, $3); | ||
| 4113 | $pat =~ s/^'(.*)'$/$1/s; | ||
| 4114 | $pat =~ s/''/'/g; | ||
| 4115 | my $re = _like_to_re($pat); | ||
| 4116 | return { op=>($neg ? 'NOT_LIKE' : 'LIKE'), lhs=>$lhs, re=>$re }; | ||
| 4117 | } | ||
| 4118 | if ($part =~ /^(.+?)\s*(=|!=|<>|<=|>=|<|>)\s*(.+)$/s) { | ||
| 4119 | my($lhs, $op, $rhs) = ($1, uc($2), $3); | ||
| 4120 | $lhs =~ s/^\s+|\s+$//g; | ||
| 4121 | $rhs =~ s/^\s+|\s+$//g; | ||
| 4122 | my $rv; | ||
| 4123 | if ($rhs =~ /^'((?:[^']|'')*)'$/) { | ||
| 4124 | ($rv = $1) =~ s/''/'/g; | ||
| 4125 | } | ||
| 4126 | else { | ||
| 4127 | $rv = $rhs; | ||
| 4128 | } | ||
| 4129 | return{ op=>$op, lhs=>$lhs, rhs_expr=>$rhs, rhs_val=>$rv }; | ||
| 4130 | } | ||
| 4131 | return{ op=>'CONST', val=>0 }; | ||
| 4132 | } | ||
| 4133 | |||
| 4134 | sub compile_tree { | ||
| 4135 | my($tree) = @_; | ||
| 4136 | my $op = $tree->{op}; | ||
| 4137 | if ($op eq 'AND') { | ||
| 4138 | my @s = map {compile_tree($_)} @{$tree->{kids}}; | ||
| 4139 | return sub { for my $s(@s) { return 0 unless $s->($_[0]) } 1 }; | ||
| 4140 | } | ||
| 4141 | if ($op eq 'OR') { | ||
| 4142 | my @s = map { compile_tree($_) } @{$tree->{kids}}; | ||
| 4143 | return sub { for my $s(@s) { return 1 if $s->($_[0]) } 0 }; | ||
| 4144 | } | ||
| 4145 | if ($op eq 'NOT') { | ||
| 4146 | my $s = compile_tree($tree->{kids}[0]); | ||
| 4147 | return sub{ $s->($_[0]) ? 0 : 1 }; | ||
| 4148 | } | ||
| 4149 | return compile_leaf($tree->{cond}); | ||
| 4150 | } | ||
| 4151 | |||
| 4152 | sub compile_leaf { | ||
| 4153 | my($c) = @_; | ||
| 4154 | my $op = defined($c->{op}) ? $c->{op} : ''; | ||
| 4155 | return sub { $c->{val} ? 1 : 0 } if $op eq 'CONST'; | ||
| 4156 | if ($op eq 'IS_NULL') { | ||
| 4157 | my $col = $c->{col}; | ||
| 4158 | return sub { my $v = $_[0]{$col}; !defined($v) || ($v eq '') }; | ||
| 4159 | } | ||
| 4160 | if ($op eq 'IS_NOT_NULL') { | ||
| 4161 | my $col = $c->{col}; | ||
| 4162 | return sub { my $v = $_[0]{$col}; defined($v) && ($v ne '') }; | ||
| 4163 | } | ||
| 4164 | if (($op eq 'BETWEEN') || ($op eq 'NOT_BETWEEN')) { | ||
| 4165 | my($col, $lo, $hi, $neg) = ($c->{col}, $c->{lo}, $c->{hi}, $op eq 'NOT_BETWEEN'); | ||
| 4166 | return sub { | ||
| 4167 | my $v = $_[0]{$col}; | ||
| 4168 | return 0 unless defined $v; | ||
| 4169 | my $n = (($v =~ /^-?\d+\.?\d*$/) && ($lo =~ /^-?\d+\.?\d*$/) && ($hi =~ /^-?\d+\.?\d*$/)); | ||
| 4170 | my $in_q = $n ? (($v>=$lo) && ($v<=$hi)) : (($v ge $lo) && ($v le $hi)); | ||
| 4171 | $neg ? !$in_q : $in_q; | ||
| 4172 | }; | ||
| 4173 | } | ||
| 4174 | if (($op eq 'IN') || ($op eq 'NOT_IN')) { | ||
| 4175 | my($col, $vals, $neg) = ($c->{col}, $c->{vals}, $op eq 'NOT_IN'); | ||
| 4176 | return sub { | ||
| 4177 | my $rv = defined($_[0]{$col}) ? $_[0]{$col} : ''; | ||
| 4178 | my $f = 0; | ||
| 4179 | my $has_null = 0; | ||
| 4180 | for my $cv (@$vals) { | ||
| 4181 | unless (defined $cv) { $has_null = 1; next } | ||
| 4182 | my $n = (($rv =~ /^-?\d+\.?\d*$/) && ($cv =~ /^-?\d+\.?\d*$/)); | ||
| 4183 | if ($n ? ($rv == $cv) : ($rv eq $cv)) { | ||
| 4184 | $f = 1; | ||
| 4185 | last; | ||
| 4186 | } | ||
| 4187 | } | ||
| 4188 | # SQL NULL semantics: NOT IN with NULL in list is UNKNOWN | ||
| 4189 | # when value not found -> treat as false (exclude the row). | ||
| 4190 | return 0 if $neg && $has_null && !$f; | ||
| 4191 | $neg ? !$f : $f; | ||
| 4192 | }; | ||
| 4193 | } | ||
| 4194 | if (($op eq 'LIKE') || ($op eq 'NOT_LIKE')) { | ||
| 4195 | my($lhs, $re, $neg) = ($c->{lhs}, $c->{re}, $op eq 'NOT_LIKE'); | ||
| 4196 | return sub { | ||
| 4197 | my $v = eval_expr($lhs, $_[0]); | ||
| 4198 | $v = '' unless defined $v; | ||
| 4199 | my $m = ($v =~ /^$re$/si) ? 1 : 0; | ||
| 4200 | $neg ? !$m : $m; | ||
| 4201 | }; | ||
| 4202 | } | ||
| 4203 | my($lhs, $op2, $rv_lit, $rhs_expr) = @{$c}{qw(lhs op rhs_val rhs_expr)}; | ||
| 4204 | return sub { | ||
| 4205 | my $row = $_[0]; | ||
| 4206 | my $lv = eval_expr($lhs, $row); | ||
| 4207 | return 0 unless defined $lv; | ||
| 4208 | my $rv = (($rhs_expr =~ /^[\w.]+$/) && ($rhs_expr !~ /^-?\d+\.?\d*$/)) ? eval_expr($rhs_expr, $row) : $rv_lit; | ||
| 4209 | $rv = '' unless defined $rv; | ||
| 4210 | my $n = (($lv =~ /^-?\d+\.?\d*$/) && ($rv =~ /^-?\d+\.?\d*$/)); | ||
| 4211 | return $n ? ($lv == $rv) : ($lv eq $rv) if $op2 eq '='; | ||
| 4212 | return $n ? ($lv != $rv) : ($lv ne $rv) if $op2 =~ /^(!|<>)/; | ||
| 4213 | return $n ? ($lv < $rv) : ($lv lt $rv) if $op2 eq '<'; | ||
| 4214 | return $n ? ($lv > $rv) : ($lv gt $rv) if $op2 eq '>'; | ||
| 4215 | return $n ? ($lv <= $rv) : ($lv le $rv) if $op2 eq '<='; | ||
| 4216 | return $n ? ($lv >= $rv) : ($lv ge $rv) if $op2 eq '>='; | ||
| 4217 | return 0; | ||
| 4218 | }; | ||
| 4219 | } | ||
| 4220 | |||
| 4221 | # ============================================================================= | ||
| 4222 | # SELECT dispatcher | ||
| 4223 | # ============================================================================= | ||
| 4224 | sub select { | ||
| 4225 | my($self, $sql) = @_; | ||
| 4226 | # Window functions are not supported; detect and reject early. | ||
| 4227 | # Strip string literals before checking to avoid false positives. | ||
| 4228 | my $sql_nostr = $sql; | ||
| 4229 | $sql_nostr =~ s/'(?:[^']|'')*'/''/g; | ||
| 4230 | if ($sql_nostr =~ /\bOVER\s*\(/i) { | ||
| 4231 | return $self->_err( | ||
| 4232 | "Window functions (OVER clause) are not supported. " | ||
| 4233 | . "Use GROUP BY with aggregate functions instead." | ||
| 4234 | ); | ||
| 4235 | } | ||
| 4236 | my @up = split_union($sql); | ||
| 4237 | return $self->exec_union([ @up ]) if @up > 1; | ||
| 4238 | if ($sql =~ /\bJOIN\b/i) { | ||
| 4239 | |||
| 4240 | # Parse GROUP BY / HAVING from the SQL before handing off to _parse_join_sql | ||
| 4241 | my $join_sql = $sql; | ||
| 4242 | my(@gb_join, $having_join); | ||
| 4243 | $having_join = ''; | ||
| 4244 | if ($join_sql =~ s/\bHAVING\s+(.+?)(?=\s*(?:ORDER\s+BY|LIMIT|OFFSET|$))//si) { | ||
| 4245 | $having_join = $1; | ||
| 4246 | $having_join =~ s/^\s+|\s+$//g; | ||
| 4247 | } | ||
| 4248 | if ($join_sql =~ s/\bGROUP\s+BY\s+(.+?)(?=\s*(?:HAVING|ORDER\s+BY|LIMIT|OFFSET|$))//si) { | ||
| 4249 | my $gbs = $1; | ||
| 4250 | $gbs =~ s/^\s+|\s+$//g; | ||
| 4251 | @gb_join = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $gbs; | ||
| 4252 | } | ||
| 4253 | my $has_agg = ($sql =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/si); | ||
| 4254 | my $needs_groupby = (@gb_join || ($having_join ne '') || $has_agg); | ||
| 4255 | |||
| 4256 | my $parsed = _parse_join_sql($join_sql); | ||
| 4257 | |||
| 4258 | # A JOIN construct the parser cannot execute is reported here rather | ||
| 4259 | # than left to fall through to the single-table parser, which used to | ||
| 4260 | # accept it and return rows that answered a different question. | ||
| 4261 | if ($parsed && ($parsed->[4] ne '')) { | ||
| 4262 | return { type=>'error', message=>$parsed->[4] }; | ||
| 4263 | } | ||
| 4264 | if ($parsed && $parsed->[0]) { | ||
| 4265 | my($js, $cs, $wc, $opts) = @$parsed; | ||
| 4266 | |||
| 4267 | # ORDER BY <position>: resolve against the select list. In the | ||
| 4268 | # aggregate branch the sort runs on projected rows keyed by | ||
| 4269 | # alias, in the plain branch on raw rows keyed by expression. | ||
| 4270 | my @sel_names = | ||
| 4271 | map { $needs_groupby ? _order_alias_of($_) : _order_name_of($_) } @$cs; | ||
| 4272 | my @ob_keys = $opts->{order_keys} ? @{$opts->{order_keys}} : (); | ||
| 4273 | for my $k (@ob_keys) { | ||
| 4274 | my($obe, $obk) = _resolve_order_ordinal_scalar($k->[0], [ @sel_names ]); | ||
| 4275 | return { type=>'error', message=>$obe } if $obe ne ''; | ||
| 4276 | $k->[0] = $obk if defined $obk; | ||
| 4277 | } | ||
| 4278 | if (@ob_keys) { | ||
| 4279 | $opts->{order_keys} = [ @ob_keys ]; | ||
| 4280 | $opts->{order_by} = $ob_keys[0][0]; | ||
| 4281 | $opts->{order_dir} = $ob_keys[0][1]; | ||
| 4282 | } | ||
| 4283 | |||
| 4284 | # If GROUP BY / HAVING / aggregate: fetch raw rows with SELECT * | ||
| 4285 | my $rows; | ||
| 4286 | if ($needs_groupby) { | ||
| 4287 | |||
| 4288 | # Fetch all columns as raw data for aggregation | ||
| 4289 | my $raw_opts = {%$opts}; | ||
| 4290 | delete $raw_opts->{order_by}; | ||
| 4291 | delete $raw_opts->{order_dir}; | ||
| 4292 | delete $raw_opts->{order_keys}; | ||
| 4293 | delete $raw_opts->{limit}; | ||
| 4294 | delete $raw_opts->{offset}; | ||
| 4295 | delete $raw_opts->{distinct}; | ||
| 4296 | $rows = $self->join_select($js, [], $wc, $raw_opts); | ||
| 4297 | } | ||
| 4298 | else { | ||
| 4299 | $rows = $self->join_select($js, $cs, $wc, $opts); | ||
| 4300 | } | ||
| 4301 | return{ type=>'error', message=>$errstr } unless $rows; | ||
| 4302 | |||
| 4303 | if ($needs_groupby) { | ||
| 4304 | |||
| 4305 | # Parse col_specs from the original SQL for aggregate evaluation | ||
| 4306 | my @col_specs_raw; | ||
| 4307 | if ($sql =~ /^SELECT\s+(.+?)\s+FROM\b/si) { | ||
| 4308 | my $cs_str = $1; | ||
| 4309 | for my $c (split /\s*,\s*/, $cs_str) { | ||
| 4310 | $c =~ s/^\s+|\s+$//g; | ||
| 4311 | if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/si) { | ||
| 4312 | push @col_specs_raw, [ $1, $2 ]; | ||
| 4313 | } | ||
| 4314 | else { | ||
| 4315 | my $alias = ($c =~ /^(\w+)\.(\w+)$/) ? $2 : $c; | ||
| 4316 | push @col_specs_raw, [ $c, $alias ]; | ||
| 4317 | } | ||
| 4318 | } | ||
| 4319 | } | ||
| 4320 | |||
| 4321 | # Group rows | ||
| 4322 | my(%gr, @go); | ||
| 4323 | if (@gb_join) { | ||
| 4324 | for my $row (@$rows) { | ||
| 4325 | |||
| 4326 | # resolve GROUP BY key: try qualified then unqualified | ||
| 4327 | my $k = join("\x00", map { | ||
| 4328 | my $col = $_; | ||
| 4329 | my $v = defined($row->{$col}) | ||
| 4330 | ? $row->{$col} | ||
| 4331 | : (($col =~ /^(\w+)\.(\w+)$/) && defined $row->{$2}) | ||
| 4332 | ? $row->{$2} | ||
| 4333 | : ''; | ||
| 4334 | defined($v) ? $v : ''; | ||
| 4335 | } @gb_join); | ||
| 4336 | push @go, $k unless exists $gr{$k}; | ||
| 4337 | push @{$gr{$k}}, $row; | ||
| 4338 | } | ||
| 4339 | } | ||
| 4340 | else { | ||
| 4341 | @go = ('__all__'); | ||
| 4342 | $gr{__all__} = $rows; | ||
| 4343 | } | ||
| 4344 | |||
| 4345 | my @results; | ||
| 4346 | for my $gk (@go) { | ||
| 4347 | my $grp = $gr{$gk}; | ||
| 4348 | my $rep = $grp->[0]; | ||
| 4349 | my %out; | ||
| 4350 | for my $spec (@col_specs_raw) { | ||
| 4351 | my($expr, $alias) = @$spec; | ||
| 4352 | $out{$alias} = eval_agg($expr, $grp, $rep); | ||
| 4353 | } | ||
| 4354 | if ($having_join ne '') { | ||
| 4355 | my $h = $having_join; | ||
| 4356 | my $cnt = scalar @$grp; | ||
| 4357 | $h =~ s/COUNT\s*\(\s*\*\s*\)/$cnt/gsi; | ||
| 4358 | $h =~ s/\b(SUM|AVG|MIN|MAX|COUNT)\s*\(([^)]+)\)/eval_agg("$1($2)", $grp, $rep)/geis; | ||
| 4359 | next unless where_sub($h)->({ %out }); | ||
| 4360 | } | ||
| 4361 | push @results, { %out }; | ||
| 4362 | } | ||
| 4363 | |||
| 4364 | # ORDER BY from opts (every key, in order) | ||
| 4365 | my @gob = $opts->{order_keys} ? @{$opts->{order_keys}} | ||
| 4366 | : (defined($opts->{order_by}) | ||
| 4367 | ? ([ $opts->{order_by}, ($opts->{order_dir} || 'ASC') ]) | ||
| 4368 | : ()); | ||
| 4369 | if (@gob && @results) { | ||
| 4370 | |||
| 4371 | # An aggregate result row is keyed by the select-list | ||
| 4372 | # alias, so "ORDER BY a.y" over "SELECT a.y, COUNT(*)" | ||
| 4373 | # has to resolve to the key 'y'. Before 1.09 it resolved | ||
| 4374 | # to nothing and the sort quietly did not happen. | ||
| 4375 | for my $k (@gob) { | ||
| 4376 | next if exists $results[0]{$k->[0]}; | ||
| 4377 | if (($k->[0] =~ /^\w+\.(\w+)$/) && exists($results[0]{$1})) { | ||
| 4378 | $k->[0] = $1; | ||
| 4379 | next; | ||
| 4380 | } | ||
| 4381 | return { type=>'error', message=> | ||
| 4382 | "ORDER BY column '$k->[0]' is not in the select " | ||
| 4383 | . "list of this aggregate query" }; | ||
| 4384 | } | ||
| 4385 | } | ||
| 4386 | if (@gob) { | ||
| 4387 | @results = sort { | ||
| 4388 | my $cmp = 0; | ||
| 4389 | for my $k (@gob) { | ||
| 4390 | my($key, $dir) = @$k; | ||
| 4391 | my $va = defined($a->{$key}) ? $a->{$key} : ''; | ||
| 4392 | my $vb = defined($b->{$key}) ? $b->{$key} : ''; | ||
| 4393 | my $c = (($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/)) | ||
| 4394 | ? ($va <=> $vb) | ||
| 4395 | : ($va cmp $vb); | ||
| 4396 | $c = -$c if lc($dir) eq 'desc'; | ||
| 4397 | if ($c != 0) { | ||
| 4398 | $cmp = $c; | ||
| 4399 | last; | ||
| 4400 | } | ||
| 4401 | } | ||
| 4402 | $cmp; | ||
| 4403 | } @results; | ||
| 4404 | } | ||
| 4405 | if (defined($opts->{offset}) && ($opts->{offset} > 0)) { | ||
| 4406 | @results = splice(@results, $opts->{offset}); | ||
| 4407 | } | ||
| 4408 | if (defined $opts->{limit}) { | ||
| 4409 | my $l = $opts->{limit} - 1; | ||
| 4410 | $l = $#results if $l > $#results; | ||
| 4411 | @results = @results[0 .. $l]; | ||
| 4412 | } | ||
| 4413 | return { type=>'rows', data=>[ @results ] }; | ||
| 4414 | } | ||
| 4415 | return { type=>'rows', data=>$rows }; | ||
| 4416 | } | ||
| 4417 | } | ||
| 4418 | my $p = $self->parse_select($sql) or return { type=>'error', message=>"Cannot parse SELECT: $sql" }; | ||
| 4419 | my($distinct, $col_specs, $tbl, $where_expr, $gb, $having, $ob, $limit, $offset) = @$p; | ||
| 4420 | my $needs_agg = (@$gb || ($having ne '') || grep { $_->[0] =~ /\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/si } @$col_specs); | ||
| 4421 | return $self->exec_groupby($tbl, $col_specs, $where_expr, $gb, $having, $ob, $limit, $offset) if $needs_agg; | ||
| 4422 | my $sch = $self->_load_schema($tbl) or return { type=>'error', message=>$errstr }; | ||
| 4423 | my $obe = _resolve_order_ordinals($ob, $col_specs, $sch); | ||
| 4424 | return { type=>'error', message=>$obe } if $obe ne ''; | ||
| 4425 | my $dat = $self->_file($tbl, 'dat'); | ||
| 4426 | my $ws; | ||
| 4427 | if ($where_expr ne '') { | ||
| 4428 | # Case 1: single condition col OP val (no AND/OR/NOT/BETWEEN/IN) | ||
| 4429 | if (($where_expr =~ /^(\w+)\s*(=|!=|<>|<=|>=|<|>)\s*(?:'([^']*)'|(-?\d+\.?\d*))$/) | ||
| 4430 | && ($where_expr !~ /\b(?:OR|AND|NOT|BETWEEN|IN)\b/i) | ||
| 4431 | ) { | ||
| 4432 | my($col, $op, $sv, $nv) = ($1, $2, $3, $4); | ||
| 4433 | my $cond = [{ col=>$col, op=>uc($op), val=>defined($sv) ? $sv : $nv }]; | ||
| 4434 | my $idx = $self->_find_index_for_conds($tbl, $sch, $cond); | ||
| 4435 | if (defined $idx) { | ||
| 4436 | my $wsub = where_sub($where_expr); | ||
| 4437 | my @rows; | ||
| 4438 | local *FH; | ||
| 4439 | open(FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 4440 | binmode FH; | ||
| 4441 | _lock_sh(\*FH); | ||
| 4442 | my $rs = $sch->{recsize}; | ||
| 4443 | for my $rn (sort { $a <=> $b } @$idx) { | ||
| 4444 | seek(FH, $rn*$rs, 0); | ||
| 4445 | my $raw = ''; | ||
| 4446 | my $n = read(FH, $raw, $rs); | ||
| 4447 | next unless defined($n) && ($n == $rs); | ||
| 4448 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 4449 | my $row = $self->_unpack_record($sch, $raw); | ||
| 4450 | push @rows, $row if !$wsub || $wsub->($row); | ||
| 4451 | } | ||
| 4452 | _unlock(\*FH); | ||
| 4453 | close FH; | ||
| 4454 | return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] }; | ||
| 4455 | } | ||
| 4456 | } | ||
| 4457 | # Case 2: AND of two range conditions on the same indexed column | ||
| 4458 | # col OP1 val1 AND col OP2 val2 (e.g. id > 5 AND id < 10) | ||
| 4459 | # also: col BETWEEN val1 AND val2 | ||
| 4460 | my $idx_range = $self->_try_index_and_range($tbl, $sch, $where_expr); | ||
| 4461 | if (defined $idx_range) { | ||
| 4462 | my $wsub = where_sub($where_expr); | ||
| 4463 | my @rows; | ||
| 4464 | local *FH; | ||
| 4465 | open(FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 4466 | binmode FH; | ||
| 4467 | _lock_sh(\*FH); | ||
| 4468 | my $rs = $sch->{recsize}; | ||
| 4469 | for my $rn (sort { $a <=> $b } @$idx_range) { | ||
| 4470 | seek(FH, $rn*$rs, 0); | ||
| 4471 | my $raw = ''; | ||
| 4472 | my $n = read(FH, $raw, $rs); | ||
| 4473 | next unless defined($n) && ($n == $rs); | ||
| 4474 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 4475 | my $row = $self->_unpack_record($sch, $raw); | ||
| 4476 | push @rows, $row if !$wsub || $wsub->($row); | ||
| 4477 | } | ||
| 4478 | _unlock(\*FH); | ||
| 4479 | close FH; | ||
| 4480 | return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] }; | ||
| 4481 | } | ||
| 4482 | # Case 3: AND across different indexed columns. | ||
| 4483 | # Use the best available single-column index to narrow the candidate | ||
| 4484 | # record set, then apply the full WHERE predicate as a post-filter. | ||
| 4485 | # Example: WHERE dept = 'Eng' AND salary > 70000 | ||
| 4486 | my $idx_partial = $self->_try_index_partial_and($tbl, $sch, $where_expr); | ||
| 4487 | if (defined $idx_partial) { | ||
| 4488 | my $wsub = where_sub($where_expr); | ||
| 4489 | my @rows; | ||
| 4490 | local *FH; | ||
| 4491 | open(FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 4492 | binmode FH; | ||
| 4493 | _lock_sh(\*FH); | ||
| 4494 | my $rs = $sch->{recsize}; | ||
| 4495 | for my $rn (sort { $a <=> $b } @$idx_partial) { | ||
| 4496 | seek(FH, $rn*$rs, 0); | ||
| 4497 | my $raw = ''; | ||
| 4498 | my $n = read(FH, $raw, $rs); | ||
| 4499 | next unless defined($n) && ($n == $rs); | ||
| 4500 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 4501 | my $row = $self->_unpack_record($sch, $raw); | ||
| 4502 | push @rows, $row if !$wsub || $wsub->($row); | ||
| 4503 | } | ||
| 4504 | _unlock(\*FH); | ||
| 4505 | close FH; | ||
| 4506 | return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] }; | ||
| 4507 | } | ||
| 4508 | # Case 4: col IN (v1, v2, ...) -- equality index per value, union. | ||
| 4509 | my $idx_in = $self->_try_index_in($tbl, $sch, $where_expr); | ||
| 4510 | if (defined $idx_in) { | ||
| 4511 | my $wsub = where_sub($where_expr); | ||
| 4512 | my @rows; | ||
| 4513 | local *FH; | ||
| 4514 | open(FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 4515 | binmode FH; | ||
| 4516 | _lock_sh(\*FH); | ||
| 4517 | my $rs = $sch->{recsize}; | ||
| 4518 | for my $rn (sort { $a <=> $b } @$idx_in) { | ||
| 4519 | seek(FH, $rn*$rs, 0); | ||
| 4520 | my $raw = ''; | ||
| 4521 | my $n = read(FH, $raw, $rs); | ||
| 4522 | next unless defined($n) && ($n == $rs); | ||
| 4523 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 4524 | my $row = $self->_unpack_record($sch, $raw); | ||
| 4525 | push @rows, $row if !$wsub || $wsub->($row); | ||
| 4526 | } | ||
| 4527 | _unlock(\*FH); | ||
| 4528 | close FH; | ||
| 4529 | return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] }; | ||
| 4530 | } | ||
| 4531 | # Case 5: pure OR of simple indexed conditions. | ||
| 4532 | # Every atom must have an index; returns union of all matching records. | ||
| 4533 | my $idx_or = $self->_try_index_or($tbl, $sch, $where_expr); | ||
| 4534 | if (defined $idx_or) { | ||
| 4535 | my $wsub = where_sub($where_expr); | ||
| 4536 | my @rows; | ||
| 4537 | local *FH; | ||
| 4538 | open(FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 4539 | binmode FH; | ||
| 4540 | _lock_sh(\*FH); | ||
| 4541 | my $rs = $sch->{recsize}; | ||
| 4542 | for my $rn (sort { $a <=> $b } @$idx_or) { | ||
| 4543 | seek(FH, $rn*$rs, 0); | ||
| 4544 | my $raw = ''; | ||
| 4545 | my $n = read(FH, $raw, $rs); | ||
| 4546 | next unless defined($n) && ($n == $rs); | ||
| 4547 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 4548 | my $row = $self->_unpack_record($sch, $raw); | ||
| 4549 | push @rows, $row if !$wsub || $wsub->($row); | ||
| 4550 | } | ||
| 4551 | _unlock(\*FH); | ||
| 4552 | close FH; | ||
| 4553 | return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] }; | ||
| 4554 | } | ||
| 4555 | # Case 6: col NOT IN (v1, v2, ...) -- index complement. | ||
| 4556 | my $idx_not_in = $self->_try_index_not_in($tbl, $sch, $where_expr); | ||
| 4557 | if (defined $idx_not_in) { | ||
| 4558 | my $wsub = where_sub($where_expr); | ||
| 4559 | my @rows; | ||
| 4560 | local *FH; | ||
| 4561 | open(FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 4562 | binmode FH; | ||
| 4563 | _lock_sh(\*FH); | ||
| 4564 | my $rs = $sch->{recsize}; | ||
| 4565 | for my $rn (sort { $a <=> $b } @$idx_not_in) { | ||
| 4566 | seek(FH, $rn*$rs, 0); | ||
| 4567 | my $raw = ''; | ||
| 4568 | my $n = read(FH, $raw, $rs); | ||
| 4569 | next unless defined($n) && ($n == $rs); | ||
| 4570 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 4571 | my $row = $self->_unpack_record($sch, $raw); | ||
| 4572 | push @rows, $row if !$wsub || $wsub->($row); | ||
| 4573 | } | ||
| 4574 | _unlock(\*FH); | ||
| 4575 | close FH; | ||
| 4576 | return{ type=>'rows', data=>[$self->project([ @rows ], $col_specs, $distinct, $ob, $limit, $offset)] }; | ||
| 4577 | } | ||
| 4578 | $ws = where_sub($where_expr); | ||
| 4579 | } | ||
| 4580 | my @raw; | ||
| 4581 | local *FH; | ||
| 4582 | open(FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 4583 | binmode FH; | ||
| 4584 | _lock_sh(\*FH); | ||
| 4585 | my $rs = $sch->{recsize}; | ||
| 4586 | while (1) { | ||
| 4587 | my $raw = ''; | ||
| 4588 | my $n = read(FH, $raw, $rs); | ||
| 4589 | last unless defined($n) && ($n == $rs); | ||
| 4590 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 4591 | my $row = $self->_unpack_record($sch, $raw); | ||
| 4592 | push @raw, $row if !$ws || $ws->($row); | ||
| 4593 | } | ||
| 4594 | _unlock(\*FH); | ||
| 4595 | close FH; | ||
| 4596 | return{ type=>'rows', data=>[ $self->project([ @raw ], $col_specs, $distinct, $ob, $limit, $offset) ] }; | ||
| 4597 | } | ||
| 4598 | |||
| 4599 | sub parse_select { | ||
| 4600 | my($self, $sql) = @_; | ||
| 4601 | $sql =~ s/^\s+|\s+$//g; | ||
| 4602 | $sql =~ s/^SELECT\s+//si or return undef; | ||
| 4603 | my $distinct = 0; | ||
| 4604 | $distinct = 1 if $sql =~ s/^DISTINCT\s+//si; | ||
| 4605 | my($col_str, $rest) = split_at_from($sql); | ||
| 4606 | return undef unless defined($col_str) && defined($rest); | ||
| 4607 | $rest =~ s/^\s*FROM\s+//si; | ||
| 4608 | my $tbl; | ||
| 4609 | ($rest =~ s/^(\w+)//) and ($tbl = $1); | ||
| 4610 | |||
| 4611 | # Optional alias (consumed only when token is not a SQL keyword) | ||
| 4612 | if (($rest =~ /^\s+(\w+)/) && ($1 !~ /^(?:WHERE|GROUP|ORDER|HAVING|LIMIT|OFFSET|INNER|LEFT|RIGHT|JOIN|ON|UNION)$/i)) { | ||
| 4613 | $rest =~ s/^\s+(?:AS\s+)?\w+//si; | ||
| 4614 | } | ||
| 4615 | $rest =~ s/^\s+//; | ||
| 4616 | return undef unless $tbl; | ||
| 4617 | my($limit, $offset) = (undef, undef); | ||
| 4618 | $rest =~ s/(?:^|\s+)OFFSET\s+(\d+)\s*$//si and $offset = $1; | ||
| 4619 | $rest =~ s/(?:^|\s+)LIMIT\s+(\d+)\s*$//si and $limit = $1; | ||
| 4620 | my @ob; | ||
| 4621 | if ($rest =~ s/(?:^|\s+)ORDER\s+BY\s+(.+?)(?=\s*(?:LIMIT|OFFSET|$))//si) { | ||
| 4622 | my $s = $1; | ||
| 4623 | $s =~ s/^\s+|\s+$//g; | ||
| 4624 | for my $item (split /\s*,\s*/, $s) { | ||
| 4625 | $item =~ s/^\s+|\s+$//g; | ||
| 4626 | my $dir = 'ASC'; | ||
| 4627 | $item =~ s/\s+(ASC|DESC)\s*$//si and $dir = uc($1); | ||
| 4628 | push @ob, [ $item, $dir ]; | ||
| 4629 | } | ||
| 4630 | } | ||
| 4631 | my $having = ''; | ||
| 4632 | $rest =~ s/(?:^|\s+)HAVING\s+(.+?)(?=\s*(?:ORDER|LIMIT|OFFSET|$))//si and $having = $1; | ||
| 4633 | $having =~ s/^\s+|\s+$//g; | ||
| 4634 | my @gb; | ||
| 4635 | if ($rest =~ s/(?:^|\s+)GROUP\s+BY\s+(.+?)(?=\s*(?:HAVING|ORDER|LIMIT|OFFSET|$))//si) { | ||
| 4636 | @gb = map { my $x = $_; $x =~ s/^\s+|\s+$//g; $x } split /\s*,\s*/, $1; | ||
| 4637 | } | ||
| 4638 | my $where = ''; | ||
| 4639 | $rest =~ /(?:^|\s*)WHERE\s+(.+)/si and ($where = $1) =~ s/^\s+|\s+$//g; | ||
| 4640 | my @cs = parse_col_list($col_str); | ||
| 4641 | return [ $distinct, [ @cs ], $tbl, $where, [ @gb ], $having, [ @ob ], $limit, $offset ]; | ||
| 4642 | } | ||
| 4643 | |||
| 4644 | sub split_at_from { | ||
| 4645 | my($str) = @_; | ||
| 4646 | my $d = 0; | ||
| 4647 | my $in_q = 0; | ||
| 4648 | my $len = length($str); | ||
| 4649 | for my $i (0 .. $len-1) { | ||
| 4650 | my $ch = substr($str, $i, 1); | ||
| 4651 | if (($ch eq "'") && !$in_q) { | ||
| 4652 | $in_q = 1; | ||
| 4653 | } | ||
| 4654 | elsif (($ch eq "'") && $in_q) { | ||
| 4655 | $in_q = 0; | ||
| 4656 | } | ||
| 4657 | elsif (!$in_q && ($ch eq '(')) { | ||
| 4658 | $d++; | ||
| 4659 | } | ||
| 4660 | elsif (!$in_q && ($ch eq ')')) { | ||
| 4661 | $d--; | ||
| 4662 | } | ||
| 4663 | elsif (!$in_q | ||
| 4664 | && ($d == 0) | ||
| 4665 | && (uc(substr($str, $i, 4)) eq 'FROM') | ||
| 4666 | && (($i == 0) || (substr($str, $i-1, 1) =~ /\s/)) | ||
| 4667 | && (($i+4 >= $len) || (substr($str, $i+4, 1) =~ /\s/)) | ||
| 4668 | ) { | ||
| 4669 | return (substr($str, 0, $i), substr($str, $i)); | ||
| 4670 | } | ||
| 4671 | } | ||
| 4672 | return (undef, undef); | ||
| 4673 | } | ||
| 4674 | |||
| 4675 | sub parse_col_list { | ||
| 4676 | my($cs) = @_; | ||
| 4677 | $cs =~ s/^\s+|\s+$//g; | ||
| 4678 | return([ '*', '*' ]) if $cs eq '*'; | ||
| 4679 | my @specs; | ||
| 4680 | for my $c (args($cs)) { | ||
| 4681 | $c =~ s/^\s+|\s+$//g; | ||
| 4682 | my($expr, $alias); | ||
| 4683 | if ($c =~ /^(.+?)\s+AS\s+(\w+)\s*$/si) { | ||
| 4684 | ($expr, $alias) = ($1, $2); | ||
| 4685 | $expr =~ s/^\s+|\s+$//g; | ||
| 4686 | } | ||
| 4687 | else { | ||
| 4688 | $expr = $c; | ||
| 4689 | $alias = ($expr =~ /^(\w+)\.(\w+)$/?$2:$expr); | ||
| 4690 | } | ||
| 4691 | push @specs, [$expr, $alias]; | ||
| 4692 | } | ||
| 4693 | return @specs; | ||
| 4694 | } | ||
| 4695 | |||
| 4696 | # SQL-92 lets an ORDER BY key be written as a select-list position instead | ||
| 4697 | # of a column name ("ORDER BY 2 DESC"). Rewrite every such item into the | ||
| 4698 | # name of the column it refers to, so that the comparators further down see | ||
| 4699 | # a name. Left alone, a bare number was compared as a constant and the | ||
| 4700 | # result came back unsorted with no error at all. | ||
| 4701 | # @$col_specs is the parsed select list; $sch is the table schema, needed | ||
| 4702 | # to resolve a position when the select list is "*". | ||
| 4703 | # Returns '' on success, or an error message for an out-of-range position. | ||
| 4704 | sub _resolve_order_ordinals { | ||
| 4705 | my($ob, $col_specs, $sch) = @_; | ||
| 4706 | return '' unless (ref($ob) eq 'ARRAY') && @$ob; | ||
| 4707 | my $wanted = 0; | ||
| 4708 | for my $o (@$ob) { | ||
| 4709 | $wanted = 1 if (ref($o) eq 'ARRAY') && defined($o->[0]) && ($o->[0] =~ /^\d+$/); | ||
| 4710 | } | ||
| 4711 | return '' unless $wanted; | ||
| 4712 | |||
| 4713 | my @names; | ||
| 4714 | if (ref($col_specs) eq 'ARRAY') { | ||
| 4715 | if ((@$col_specs == 1) && (ref($col_specs->[0]) eq 'ARRAY') | ||
| 4716 | && ($col_specs->[0][0] eq '*')) { | ||
| 4717 | @names = map { $_->{name} } @{$sch->{cols}} if ref($sch) eq 'HASH'; | ||
| 4718 | } | ||
| 4719 | else { | ||
| 4720 | @names = map { ref($_) eq 'ARRAY' ? $_->[1] : $_ } @$col_specs; | ||
| 4721 | } | ||
| 4722 | } | ||
| 4723 | for my $o (@$ob) { | ||
| 4724 | next unless (ref($o) eq 'ARRAY') && defined($o->[0]); | ||
| 4725 | next unless $o->[0] =~ /^\d+$/; | ||
| 4726 | my $n = $o->[0] + 0; | ||
| 4727 | unless (@names && ($n >= 1) && ($n <= scalar @names)) { | ||
| 4728 | return "ORDER BY position $o->[0] is not in the select list"; | ||
| 4729 | } | ||
| 4730 | $o->[0] = $names[$n - 1]; | ||
| 4731 | } | ||
| 4732 | return ''; | ||
| 4733 | } | ||
| 4734 | |||
| 4735 | # Scalar counterpart of _resolve_order_ordinals, for the JOIN, derived | ||
| 4736 | # table and correlated subquery paths. Those carry a single ORDER BY key | ||
| 4737 | # rather than a list of them. @$names is the output column list in SELECT | ||
| 4738 | # order; when it is empty the position cannot be resolved (a "*" select | ||
| 4739 | # list whose expansion is not known at this point) and the position is | ||
| 4740 | # reported rather than quietly ignored. | ||
| 4741 | # Returns (error_message, key); error_message is '' on success, and key is | ||
| 4742 | # the original one when it was not a position. | ||
| 4743 | sub _resolve_order_ordinal_scalar { | ||
| 4744 | my($ob, $names) = @_; | ||
| 4745 | return ('', $ob) unless defined($ob) && ($ob =~ /^\d+$/); | ||
| 4746 | my $n = $ob + 0; | ||
| 4747 | unless ((ref($names) eq 'ARRAY') && @$names && ($n >= 1) && ($n <= scalar @$names)) { | ||
| 4748 | return ("ORDER BY position $ob is not in the select list", $ob); | ||
| 4749 | } | ||
| 4750 | return ('', $names->[$n - 1]); | ||
| 4751 | } | ||
| 4752 | |||
| 4753 | # Select-list item as the sort comparators see it before projection: the | ||
| 4754 | # expression with any trailing "AS alias" removed. | ||
| 4755 | sub _order_name_of { | ||
| 4756 | my($item) = @_; | ||
| 4757 | return '' unless defined $item; | ||
| 4758 | $item =~ s/^\s+|\s+$//g; | ||
| 4759 | $item =~ s/\s+AS\s+\w+\s*$//si; | ||
| 4760 | return $item; | ||
| 4761 | } | ||
| 4762 | |||
| 4763 | # Select-list item as it is keyed after projection: the explicit alias, | ||
| 4764 | # the bare column of a qualified name, or the expression itself. | ||
| 4765 | sub _order_alias_of { | ||
| 4766 | my($item) = @_; | ||
| 4767 | return '' unless defined $item; | ||
| 4768 | $item =~ s/^\s+|\s+$//g; | ||
| 4769 | return $1 if $item =~ /\s+AS\s+(\w+)\s*$/si; | ||
| 4770 | return $2 if $item =~ /^(\w+)\.(\w+)$/; | ||
| 4771 | return $item; | ||
| 4772 | } | ||
| 4773 | |||
| 4774 | sub project { | ||
| 4775 | my($self, $rows, $col_specs, $distinct, $ob, $limit, $offset) = @_; my $star = ((@$col_specs == 1) && ($col_specs->[0][0] eq '*')); | ||
| 4776 | |||
| 4777 | # ORDER BY must be evaluated against the original (unprojected) rows so that | ||
| 4778 | # columns not listed in SELECT (e.g. "SELECT name ... ORDER BY score") are | ||
| 4779 | # still accessible for sorting. | ||
| 4780 | my @sorted = @$rows; | ||
| 4781 | if (@$ob) { | ||
| 4782 | @sorted = sort { | ||
| 4783 | my($ra, $rb) = ($a, $b); | ||
| 4784 | for my $o (@$ob) { | ||
| 4785 | my($e, $dir) = @$o; | ||
| 4786 | my $va = do { my $vv = eval_expr($e, $ra); defined($vv) ? $vv : (defined($ra->{$e}) ? $ra->{$e} : '') }; | ||
| 4787 | my $vb = do { my $vv = eval_expr($e, $rb); defined($vv) ? $vv : (defined($rb->{$e}) ? $rb->{$e} : '') }; | ||
| 4788 | my $c = (($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/)) ? ($va <=> $vb) : ($va cmp $vb); | ||
| 4789 | $c = -$c if lc($dir) eq 'desc'; | ||
| 4790 | return $c if $c; | ||
| 4791 | } | ||
| 4792 | 0 | ||
| 4793 | } @sorted; | ||
| 4794 | } | ||
| 4795 | |||
| 4796 | # Apply OFFSET / LIMIT on sorted raw rows before projection | ||
| 4797 | $offset = 0 unless defined $offset; | ||
| 4798 | @sorted = splice(@sorted, $offset) if $offset; | ||
| 4799 | if (defined $limit) { | ||
| 4800 | my $l = $limit-1; | ||
| 4801 | $l = $#sorted if $l>$#sorted; | ||
| 4802 | @sorted = @sorted[0 .. $l]; | ||
| 4803 | } | ||
| 4804 | |||
| 4805 | # Project to requested columns | ||
| 4806 | my @out; | ||
| 4807 | for my $row (@sorted) { | ||
| 4808 | if ($star) { | ||
| 4809 | push @out, { %$row }; | ||
| 4810 | } | ||
| 4811 | else { | ||
| 4812 | my %p; | ||
| 4813 | $p{$_->[1]} = eval_expr($_->[0], $row) for @$col_specs; | ||
| 4814 | push @out, { %p }; | ||
| 4815 | } | ||
| 4816 | } | ||
| 4817 | |||
| 4818 | # DISTINCT (applied after projection so aliases are visible) | ||
| 4819 | if ($distinct) { | ||
| 4820 | my %s; | ||
| 4821 | my @d; | ||
| 4822 | for my $r (@out) { | ||
| 4823 | my $k = join("\x00", map{ defined($r->{$_}) ? $r->{$_} : "\x01" } sort keys %$r); | ||
| 4824 | push @d, $r unless $s{$k}++; | ||
| 4825 | } | ||
| 4826 | @out = @d; | ||
| 4827 | } | ||
| 4828 | return @out; | ||
| 4829 | } | ||
| 4830 | |||
| 4831 | # ============================================================================= | ||
| 4832 | # GROUP BY / HAVING / aggregate functions | ||
| 4833 | # ============================================================================= | ||
| 4834 | sub exec_groupby { | ||
| 4835 | my($self, $tbl, $col_specs, $where_expr, $gb, $having, $ob, $limit, $offset) = @_; | ||
| 4836 | my $sch = $self->_load_schema($tbl) or return{ type=>'error', message=>$errstr }; | ||
| 4837 | my $obe = _resolve_order_ordinals($ob, $col_specs, $sch); | ||
| 4838 | return { type=>'error', message=>$obe } if $obe ne ''; | ||
| 4839 | my $dat = $self->_file($tbl, 'dat'); | ||
| 4840 | my $ws = ($where_expr ne '') ? where_sub($where_expr) : undef; | ||
| 4841 | my @raw; | ||
| 4842 | local *FH; | ||
| 4843 | open(FH, "< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 4844 | binmode FH; | ||
| 4845 | _lock_sh(\*FH); | ||
| 4846 | my $rs = $sch->{recsize}; | ||
| 4847 | while (1) { | ||
| 4848 | my $raw = ''; | ||
| 4849 | my $n = read(FH, $raw, $rs); | ||
| 4850 | last unless defined($n) && ($n == $rs); | ||
| 4851 | next if substr($raw, 0, 1) eq RECORD_DELETED; | ||
| 4852 | my $row = $self->_unpack_record($sch, $raw); | ||
| 4853 | push @raw, $row if !$ws || $ws->($row); | ||
| 4854 | } | ||
| 4855 | _unlock(\*FH); | ||
| 4856 | close FH; | ||
| 4857 | my @results = group_and_aggregate([ @raw ], $col_specs, $gb, $having); | ||
| 4858 | if (@$ob) { | ||
| 4859 | @results = sort { | ||
| 4860 | my($ra, $rb) = ($a, $b); | ||
| 4861 | for my $o (@$ob) { | ||
| 4862 | my($e, $dir) = @$o; | ||
| 4863 | my $va = do { my $vv = eval_expr($e, $ra); defined($vv) ? $vv : (defined($ra->{$e}) ? $ra->{$e} : '') }; | ||
| 4864 | my $vb = do { my $vv = eval_expr($e, $rb); defined($vv) ? $vv : (defined($rb->{$e}) ? $rb->{$e} : '') }; | ||
| 4865 | my $c = (($va =~ /^-?\d+\.?\d*$/) && ($vb =~ /^-?\d+\.?\d*$/)) ? ($va <=> $vb) : ($va cmp $vb); | ||
| 4866 | $c = -$c if lc($dir) eq 'desc'; | ||
| 4867 | return $c if $c; | ||
| 4868 | } | ||
| 4869 | 0 | ||
| 4870 | } @results | ||
| 4871 | } | ||
| 4872 | $offset = 0 unless defined $offset; | ||
| 4873 | @results = splice(@results, $offset) if $offset; | ||
| 4874 | if (defined $limit) { | ||
| 4875 | my $l = $limit - 1; | ||
| 4876 | $l = $#results if $l>$#results; | ||
| 4877 | @results = @results[0..$l]; | ||
| 4878 | } | ||
| 4879 | return{ type=>'rows', data=>[ @results ] }; | ||
| 4880 | } | ||
| 4881 | |||
| 4882 | # Group @$rows by the expressions in @$gb (an empty list means one group | ||
| 4883 | # holding every row), evaluate @$col_specs for each group and drop the | ||
| 4884 | # groups rejected by $having. Returns the result rows. The table-backed | ||
| 4885 | # SELECT path and the derived-table path share this, which is why it takes | ||
| 4886 | # rows rather than reading them itself. | ||
| 4887 | sub group_and_aggregate { | ||
| 4888 | my($rows, $col_specs, $gb, $having) = @_; | ||
| 4889 | $gb = [] unless defined $gb; | ||
| 4890 | $having = '' unless defined $having; | ||
| 4891 | my %gr; | ||
| 4892 | my @go; | ||
| 4893 | if (@$gb) { | ||
| 4894 | for my $row (@$rows) { | ||
| 4895 | my $k = join("\x00", map { my $v = eval_expr($_, $row); defined($v) ? $v : '' } @$gb); | ||
| 4896 | push @go, $k unless exists $gr{$k}; | ||
| 4897 | push @{$gr{$k}}, $row; | ||
| 4898 | } | ||
| 4899 | } | ||
| 4900 | else { | ||
| 4901 | @go = ('__all__'); | ||
| 4902 | $gr{__all__} = [ @$rows ]; | ||
| 4903 | } | ||
| 4904 | my @results; | ||
| 4905 | for my $gk (@go) { | ||
| 4906 | my $grp = $gr{$gk}; | ||
| 4907 | my $rep = defined($grp->[0]) ? $grp->[0] : {}; | ||
| 4908 | my %out; | ||
| 4909 | $out{$_->[1]} = eval_agg($_->[0], $grp, $rep) for @$col_specs; | ||
| 4910 | if ($having ne '') { | ||
| 4911 | my $h = $having; | ||
| 4912 | my $cnt = scalar @$grp; | ||
| 4913 | $h =~ s/COUNT\s*\(\s*\*\s*\)/$cnt/gsi; | ||
| 4914 | $h =~ s/\b(SUM|AVG|MIN|MAX|COUNT)\s*\(([^)]+)\)/eval_agg("$1($2)", $grp, $rep)/geis; | ||
| 4915 | next unless where_sub($h)->({ %out }); | ||
| 4916 | } | ||
| 4917 | push @results, { %out }; | ||
| 4918 | } | ||
| 4919 | return @results; | ||
| 4920 | } | ||
| 4921 | |||
| 4922 | sub eval_agg { | ||
| 4923 | my($expr, $grp, $rep) = @_; | ||
| 4924 | return scalar @$grp if $expr =~ /^COUNT\s*\(\s*\*\s*\)$/si; | ||
| 4925 | if ($expr =~ /^COUNT\s*\(\s*DISTINCT\s+(.+)\s*\)$/si) { | ||
| 4926 | my $e = $1; | ||
| 4927 | my %s; | ||
| 4928 | for my $r (@$grp) { | ||
| 4929 | my $vv = eval_expr($e, $r); | ||
| 4930 | next unless defined($vv) && ($vv ne ''); | ||
| 4931 | $s{$vv}++; | ||
| 4932 | } | ||
| 4933 | return scalar keys %s; | ||
| 4934 | } | ||
| 4935 | if ($expr =~ /^(COUNT|SUM|AVG|MIN|MAX)\s*\((.+)\)$/si) { | ||
| 4936 | my($fn, $inner) = (uc($1), $2); | ||
| 4937 | $inner =~ s/^\s+|\s+$//g; | ||
| 4938 | my @vals = grep { defined($_) && ($_ ne '') } map { eval_expr($inner, $_) } @$grp; | ||
| 4939 | return 0 unless @vals; | ||
| 4940 | return scalar @vals if $fn eq 'COUNT'; | ||
| 4941 | if ($fn eq 'SUM') { | ||
| 4942 | my $s = 0; | ||
| 4943 | $s += $_ for @vals; | ||
| 4944 | return $s; | ||
| 4945 | } | ||
| 4946 | if ($fn eq 'AVG') { | ||
| 4947 | my $s = 0; | ||
| 4948 | $s += $_ for @vals; | ||
| 4949 | return $s / @vals; | ||
| 4950 | } | ||
| 4951 | if ($fn eq 'MIN') { | ||
| 4952 | return (sort { (($a =~ /^-?\d+\.?\d*$/) && ($b =~ /^-?\d+\.?\d*$/)) ? ($a<=>$b) : ($a cmp $b) } @vals)[0]; | ||
| 4953 | } | ||
| 4954 | if ($fn eq 'MAX') { | ||
| 4955 | return (sort { (($a =~ /^-?\d+\.?\d*$/) && ($b =~ /^-?\d+\.?\d*$/)) ? ($b<=>$a) : ($b cmp $a) } @vals)[0]; | ||
| 4956 | } | ||
| 4957 | } | ||
| 4958 | return eval_expr($expr, $rep); | ||
| 4959 | } | ||
| 4960 | |||
| 4961 | # ============================================================================= | ||
| 4962 | # UNION / UNION ALL | ||
| 4963 | # ============================================================================= | ||
| 4964 | sub split_union { | ||
| 4965 | my($sql) = @_; | ||
| 4966 | my @parts; | ||
| 4967 | my $cur = ''; | ||
| 4968 | my $d = 0; | ||
| 4969 | my $in_q = 0; | ||
| 4970 | my $i = 0; | ||
| 4971 | my $len = length($sql); | ||
| 4972 | while ($i < $len) { | ||
| 4973 | my $ch = substr($sql, $i, 1); | ||
| 4974 | if (($ch eq "'") && !$in_q) { | ||
| 4975 | $in_q = 1; | ||
| 4976 | $cur .= $ch; | ||
| 4977 | } | ||
| 4978 | elsif (($ch eq "'") && $in_q) { | ||
| 4979 | $in_q = 0; | ||
| 4980 | $cur .= $ch; | ||
| 4981 | } | ||
| 4982 | elsif ($in_q) { | ||
| 4983 | $cur .= $ch; | ||
| 4984 | } | ||
| 4985 | elsif ($ch eq '(') { | ||
| 4986 | $d++; | ||
| 4987 | $cur .= $ch; | ||
| 4988 | } | ||
| 4989 | elsif ($ch eq ')') { | ||
| 4990 | $d--; | ||
| 4991 | $cur .= $ch; | ||
| 4992 | } | ||
| 4993 | elsif ($d == 0 && !$in_q | ||
| 4994 | && (($i == 0) || (substr($sql, $i-1, 1) =~ /\s/))) { | ||
| 4995 | # Detect UNION / INTERSECT / EXCEPT set operators | ||
| 4996 | my $kw = ''; | ||
| 4997 | my $klen = 0; | ||
| 4998 | if ((uc(substr($sql, $i, 5)) eq 'UNION') | ||
| 4999 | && ($i+5 < $len) && (substr($sql, $i+5, 1) =~ /[\s(]/)) { | ||
| 5000 | $kw = 'UNION'; $klen = 5; | ||
| 5001 | } | ||
| 5002 | elsif ((uc(substr($sql, $i, 9)) eq 'INTERSECT') | ||
| 5003 | && ($i+9 < $len) && (substr($sql, $i+9, 1) =~ /[\s(]/)) { | ||
| 5004 | $kw = 'INTERSECT'; $klen = 9; | ||
| 5005 | } | ||
| 5006 | elsif ((uc(substr($sql, $i, 6)) eq 'EXCEPT') | ||
| 5007 | && ($i+6 < $len) && (substr($sql, $i+6, 1) =~ /[\s(]/)) { | ||
| 5008 | $kw = 'EXCEPT'; $klen = 6; | ||
| 5009 | } | ||
| 5010 | if ($klen) { | ||
| 5011 | push @parts, $cur; | ||
| 5012 | $cur = ''; | ||
| 5013 | $i += $klen; | ||
| 5014 | while (($i < $len) && (substr($sql, $i, 1) =~ /\s/)) { $i++ } | ||
| 5015 | # UNION ALL / INTERSECT ALL / EXCEPT ALL | ||
| 5016 | if (($kw eq 'UNION') | ||
| 5017 | && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL') | ||
| 5018 | && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) { | ||
| 5019 | push @parts, 'UNION_ALL'; | ||
| 5020 | $i += 3; | ||
| 5021 | while (($i < $len) && (substr($sql, $i, 1) =~ /\s/)) { $i++ } | ||
| 5022 | } | ||
| 5023 | elsif (($kw eq 'INTERSECT') | ||
| 5024 | && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL') | ||
| 5025 | && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) { | ||
| 5026 | push @parts, 'INTERSECT_ALL'; | ||
| 5027 | $i += 3; | ||
| 5028 | while (($i < $len) && (substr($sql, $i, 1) =~ /\s/)) { $i++ } | ||
| 5029 | } | ||
| 5030 | elsif (($kw eq 'EXCEPT') | ||
| 5031 | && ($i+3 <= $len) && (uc(substr($sql, $i, 3)) eq 'ALL') | ||
| 5032 | && (($i+3 >= $len) || (substr($sql, $i+3, 1) =~ /\s/))) { | ||
| 5033 | push @parts, 'EXCEPT_ALL'; | ||
| 5034 | $i += 3; | ||
| 5035 | while (($i < $len) && (substr($sql, $i, 1) =~ /\s/)) { $i++ } | ||
| 5036 | } | ||
| 5037 | else { | ||
| 5038 | push @parts, $kw; # bare UNION / INTERSECT / EXCEPT | ||
| 5039 | } | ||
| 5040 | next; | ||
| 5041 | } | ||
| 5042 | else { | ||
| 5043 | $cur .= $ch; | ||
| 5044 | } | ||
| 5045 | } | ||
| 5046 | else { | ||
| 5047 | $cur .= $ch; | ||
| 5048 | } | ||
| 5049 | $i++; | ||
| 5050 | } | ||
| 5051 | push @parts, $cur if $cur =~ /\S/; | ||
| 5052 | return @parts; | ||
| 5053 | } | ||
| 5054 | |||
| 5055 | # Column order of one branch of a set operation, as a list of result-row | ||
| 5056 | # hash keys in select-list order. | ||
| 5057 | sub _branch_col_order { | ||
| 5058 | my($self, $sql, $data) = @_; | ||
| 5059 | return [ DB::Handy::Statement::_col_order_from_sql(undef, $sql, $data, $self) ]; | ||
| 5060 | } | ||
| 5061 | |||
| 5062 | sub exec_union { | ||
| 5063 | my($self, $parts) = @_; | ||
| 5064 | my @p = @$parts; | ||
| 5065 | my $first = shift @p; | ||
| 5066 | my $r0 = $self->execute($first); | ||
| 5067 | return $r0 if $r0->{type} eq 'error'; | ||
| 5068 | my @rows = @{$r0->{data}}; | ||
| 5069 | |||
| 5070 | # A result row is a hash keyed by column name, and SQL lines the branches | ||
| 5071 | # of a set operation up by *position*, taking the result column names from | ||
| 5072 | # the first branch. Until 1.09 the branches were merged as they came, so | ||
| 5073 | # "SELECT x FROM a UNION ALL SELECT p FROM b" produced rows keyed 'p' for | ||
| 5074 | # the second branch; every value read under the name 'x' was then NULL. | ||
| 5075 | # The column order of each later branch is therefore mapped onto the | ||
| 5076 | # first branch's names before the rows are combined. | ||
| 5077 | my $base = $self->_branch_col_order($first, \@rows); | ||
| 5078 | |||
| 5079 | while (@p >= 2) { | ||
| 5080 | my $sep = shift @p; | ||
| 5081 | my $q = shift @p; | ||
| 5082 | my $r = $self->execute($q); | ||
| 5083 | return $r if $r->{type} eq 'error'; | ||
| 5084 | my @rhs = @{$r->{data}}; | ||
| 5085 | my $rord = $self->_branch_col_order($q, \@rhs); | ||
| 5086 | if (@$base && @$rord) { | ||
| 5087 | if (@$base != @$rord) { | ||
| 5088 | return { type=>'error', message=> | ||
| 5089 | "Each SELECT of a set operation must return the same " | ||
| 5090 | . "number of columns (" . scalar(@$base) . " and " | ||
| 5091 | . scalar(@$rord) . ")" }; | ||
| 5092 | } | ||
| 5093 | if (join("\x00", @$base) ne join("\x00", @$rord)) { | ||
| 5094 | my @mapped; | ||
| 5095 | for my $row (@rhs) { | ||
| 5096 | my %n; | ||
| 5097 | for my $i (0 .. $#$base) { | ||
| 5098 | $n{ $base->[$i] } = $row->{ $rord->[$i] }; | ||
| 5099 | } | ||
| 5100 | push @mapped, { %n }; | ||
| 5101 | } | ||
| 5102 | @rhs = @mapped; | ||
| 5103 | } | ||
| 5104 | } | ||
| 5105 | # Build a key string for each row for set operations | ||
| 5106 | my $_key = sub { | ||
| 5107 | my($row) = @_; | ||
| 5108 | join("\x00", map { defined($row->{$_}) ? $row->{$_} : "\x01" } sort keys %$row); | ||
| 5109 | }; | ||
| 5110 | if ($sep eq 'UNION' || $sep eq '') { | ||
| 5111 | # UNION: combine then deduplicate | ||
| 5112 | push @rows, @rhs; | ||
| 5113 | my %s; my @d; | ||
| 5114 | for my $row (@rows) { | ||
| 5115 | push @d, $row unless $s{$_key->($row)}++; | ||
| 5116 | } | ||
| 5117 | @rows = @d; | ||
| 5118 | } | ||
| 5119 | elsif ($sep eq 'UNION_ALL') { | ||
| 5120 | # UNION ALL: combine without deduplication | ||
| 5121 | push @rows, @rhs; | ||
| 5122 | } | ||
| 5123 | elsif ($sep eq 'INTERSECT') { | ||
| 5124 | # INTERSECT: keep only rows present in both (deduplicated) | ||
| 5125 | my %in_rhs; | ||
| 5126 | for my $row (@rhs) { $in_rhs{$_key->($row)} = 1 } | ||
| 5127 | my %seen; my @d; | ||
| 5128 | for my $row (@rows) { | ||
| 5129 | my $k = $_key->($row); | ||
| 5130 | push @d, $row if $in_rhs{$k} && !$seen{$k}++; | ||
| 5131 | } | ||
| 5132 | @rows = @d; | ||
| 5133 | } | ||
| 5134 | elsif ($sep eq 'INTERSECT_ALL') { | ||
| 5135 | # INTERSECT ALL: keep rows present in both (with multiplicity) | ||
| 5136 | my %rhs_cnt; | ||
| 5137 | for my $row (@rhs) { $rhs_cnt{$_key->($row)}++ } | ||
| 5138 | my %used; my @d; | ||
| 5139 | for my $row (@rows) { | ||
| 5140 | my $k = $_key->($row); | ||
| 5141 | if (($rhs_cnt{$k} || 0) > ($used{$k} || 0)) { | ||
| 5142 | push @d, $row; | ||
| 5143 | $used{$k}++; | ||
| 5144 | } | ||
| 5145 | } | ||
| 5146 | @rows = @d; | ||
| 5147 | } | ||
| 5148 | elsif ($sep eq 'EXCEPT') { | ||
| 5149 | # EXCEPT: remove rows that appear in rhs (deduplicated) | ||
| 5150 | my %in_rhs; | ||
| 5151 | for my $row (@rhs) { $in_rhs{$_key->($row)} = 1 } | ||
| 5152 | my %seen; my @d; | ||
| 5153 | for my $row (@rows) { | ||
| 5154 | my $k = $_key->($row); | ||
| 5155 | push @d, $row if !$in_rhs{$k} && !$seen{$k}++; | ||
| 5156 | } | ||
| 5157 | @rows = @d; | ||
| 5158 | } | ||
| 5159 | elsif ($sep eq 'EXCEPT_ALL') { | ||
| 5160 | # EXCEPT ALL: remove rows with multiplicity | ||
| 5161 | my %rhs_cnt; | ||
| 5162 | for my $row (@rhs) { $rhs_cnt{$_key->($row)}++ } | ||
| 5163 | my %removed; my @d; | ||
| 5164 | for my $row (@rows) { | ||
| 5165 | my $k = $_key->($row); | ||
| 5166 | if (($rhs_cnt{$k} || 0) > ($removed{$k} || 0)) { | ||
| 5167 | $removed{$k}++; | ||
| 5168 | } | ||
| 5169 | else { | ||
| 5170 | push @d, $row; | ||
| 5171 | } | ||
| 5172 | } | ||
| 5173 | @rows = @d; | ||
| 5174 | } | ||
| 5175 | } | ||
| 5176 | return { type=>'rows', data=>[ @rows ] }; | ||
| 5177 | } | ||
| 5178 | |||
| 5179 | # ============================================================================= | ||
| 5180 | # UPDATE with expression SET | ||
| 5181 | # ============================================================================= | ||
| 5182 | sub parse_set_exprs { | ||
| 5183 | my($str) = @_; | ||
| 5184 | my %set; | ||
| 5185 | for my $part (args($str)) { | ||
| 5186 | $part =~ s/^\s+|\s+$//g; | ||
| 5187 | $set{$1} = $2 if $part =~ /^(\w+)\s*=\s*(.+)$/s; | ||
| 5188 | } | ||
| 5189 | return %set; | ||
| 5190 | } | ||
| 5191 | |||
| 5192 | sub update { | ||
| 5193 | my($self, $table, $set_exprs, $ws) = @_; | ||
| 5194 | return $self->_err("No database selected") unless $self->{db_name}; | ||
| 5195 | my $sch = $self->_load_schema($table) or return undef; | ||
| 5196 | my $dat = $self->_file($table, 'dat'); | ||
| 5197 | my $rs = $sch->{recsize}; | ||
| 5198 | my $n = 0; | ||
| 5199 | local *FH; | ||
| 5200 | open(FH, "+< $dat") or return $self->_err("Cannot open dat: $!"); | ||
| 5201 | binmode FH; | ||
| 5202 | _autoflush(\*FH); | ||
| 5203 | _lock_ex(\*FH); | ||
| 5204 | seek(FH, 0, 0); | ||
| 5205 | my $pos = 0; | ||
| 5206 | my $rno = 0; | ||
| 5207 | while (1) { | ||
| 5208 | seek(FH, $pos, 0); | ||
| 5209 | my $raw = ''; | ||
| 5210 | my $x = read(FH, $raw, $rs); | ||
| 5211 | last unless defined($x) && ($x == $rs); | ||
| 5212 | if (substr($raw, 0, 1) ne RECORD_DELETED) { | ||
| 5213 | my $row = $self->_unpack_record($sch, $raw); | ||
| 5214 | if (!$ws || $ws->($row)) { | ||
| 5215 | my %old; | ||
| 5216 | for my $ix (values %{$sch->{indexes}}) { | ||
| 5217 | $old{$ix->{name}} = $row->{$ix->{col}} | ||
| 5218 | } | ||
| 5219 | my %orig = %$row; | ||
| 5220 | $row->{$_} = eval_expr($set_exprs->{$_}, { %orig }) for keys %$set_exprs; | ||
| 5221 | for my $ix (values %{$sch->{indexes}}) { | ||
| 5222 | next unless $ix->{unique} && exists $set_exprs->{$ix->{col}}; | ||
| 5223 | my $nv = $row->{$ix->{col}}; | ||
| 5224 | next unless defined($nv) && ($nv ne ''); | ||
| 5225 | my $ep = $self->_idx_lookup_exact($table, $ix, $nv); | ||
| 5226 | if ($ep >= 0) { | ||
| 5227 | my $ef = $self->_idx_file($table, $ix->{name}); | ||
| 5228 | my $es = $ix->{keysize} + REC_NO_SIZE; | ||
| 5229 | local *IF_FH; | ||
| 5230 | open(IF_FH, "< $ef") or next; | ||
| 5231 | binmode IF_FH; | ||
| 5232 | seek(IF_FH, IDX_MAGIC_LEN + $ep * $es + $ix->{keysize}, 0); | ||
| 5233 | my $rn = ''; | ||
| 5234 | read(IF_FH, $rn, REC_NO_SIZE); | ||
| 5235 | close IF_FH; | ||
| 5236 | if (unpack('N', $rn) != $rno) { | ||
| 5237 | _unlock(\*FH); | ||
| 5238 | close FH; | ||
| 5239 | return $self->_err("UNIQUE constraint violated on '$ix->{name}'"); | ||
| 5240 | } | ||
| 5241 | } | ||
| 5242 | } | ||
| 5243 | |||
| 5244 | # NOT NULL constraint check on UPDATE | ||
| 5245 | for my $cn (keys %{$sch->{notnull} || {}}) { | ||
| 5246 | next unless exists $set_exprs->{$cn}; | ||
| 5247 | unless (defined($row->{$cn}) && ($row->{$cn} ne '')) { | ||
| 5248 | _unlock(\*FH); | ||
| 5249 | close FH; | ||
| 5250 | return $self->_err("NOT NULL constraint violated on column '$cn'"); | ||
| 5251 | } | ||
| 5252 | } | ||
| 5253 | # CHECK constraint check on UPDATE | ||
| 5254 | for my $cn (keys %{$sch->{checks} || {}}) { | ||
| 5255 | next unless exists $set_exprs->{$cn}; | ||
| 5256 | next unless defined($row->{$cn}) && ($row->{$cn} ne ''); | ||
| 5257 | unless (eval_bool($sch->{checks}{$cn}, $row)) { | ||
| 5258 | _unlock(\*FH); | ||
| 5259 | close FH; | ||
| 5260 | return $self->_err("CHECK constraint failed on column '$cn'"); | ||
| 5261 | } | ||
| 5262 | } | ||
| 5263 | # VARCHAR / CHAR length check on UPDATE | ||
| 5264 | for my $col (@{$sch->{cols}}) { | ||
| 5265 | my $cn = $col->{name}; | ||
| 5266 | next unless ($col->{type} eq 'VARCHAR' || $col->{type} eq 'CHAR'); | ||
| 5267 | next unless exists $set_exprs->{$cn}; | ||
| 5268 | my $decl = defined($col->{decl}) ? $col->{decl} : $col->{size}; | ||
| 5269 | next unless defined($decl) && ($decl < MAX_VARCHAR); | ||
| 5270 | next unless defined($row->{$cn}) && ($row->{$cn} ne ''); | ||
| 5271 | if (length($row->{$cn}) > $decl) { | ||
| 5272 | _unlock(\*FH); | ||
| 5273 | close FH; | ||
| 5274 | return $self->_err( | ||
| 5275 | "Value too long for column '$cn': " | ||
| 5276 | . "declared $col->{type}($decl), got " | ||
| 5277 | . length($row->{$cn}) . " bytes" | ||
| 5278 | ); | ||
| 5279 | } | ||
| 5280 | } | ||
| 5281 | # Type check on UPDATE: INT range and DATE validity. | ||
| 5282 | for my $col (@{$sch->{cols}}) { | ||
| 5283 | next unless exists $set_exprs->{$col->{name}}; | ||
| 5284 | my $msg = _type_error($col, $row->{$col->{name}}); | ||
| 5285 | next unless defined $msg; | ||
| 5286 | _unlock(\*FH); | ||
| 5287 | close FH; | ||
| 5288 | return $self->_err($msg); | ||
| 5289 | } | ||
| 5290 | my $p = $self->_pack_record($sch, $row); | ||
| 5291 | seek(FH, $pos, 0); | ||
| 5292 | unless (print FH $p) { | ||
| 5293 | my $e = $!; | ||
| 5294 | _unlock(\*FH); | ||
| 5295 | close FH; | ||
| 5296 | return $self->_err("Cannot write record: $e"); | ||
| 5297 | } | ||
| 5298 | $n++; | ||
| 5299 | for my $ix (values %{$sch->{indexes}}) { | ||
| 5300 | next unless exists $set_exprs->{$ix->{col}}; | ||
| 5301 | $self->_idx_delete($table, $ix, $old{$ix->{name}}, $rno); | ||
| 5302 | $self->_idx_insert($table, $ix, $row->{$ix->{col}}, $rno); | ||
| 5303 | } | ||
| 5304 | } | ||
| 5305 | } | ||
| 5306 | $pos += $rs; | ||
| 5307 | $rno++; | ||
| 5308 | } | ||
| 5309 | _unlock(\*FH); | ||
| 5310 | unless (close FH) { | ||
| 5311 | return $self->_err("Cannot flush dat: $!"); | ||
| 5312 | } | ||
| 5313 | return $n; | ||
| 5314 | } | ||
| 5315 | |||
| 5316 | ############################################################################### | ||
| 5317 | # DBI-like API -- DB::Handy::Connection / DB::Handy::Statement | ||
| 5318 | # | ||
| 5319 | # A standalone implementation with a DBI-inspired interface. | ||
| 5320 | # | ||
| 5321 | # Usage: | ||
| 5322 | # my $dbh = DB::Handy->connect("./data", "mydb"); | ||
| 5323 | # my $sth = $dbh->prepare("SELECT * FROM emp WHERE id = ?"); | ||
| 5324 | # $sth->execute(1); | ||
| 5325 | # while (my $row = $sth->fetchrow_hashref) { ... } | ||
| 5326 | # $sth->finish; | ||
| 5327 | # $dbh->disconnect; | ||
| 5328 | ############################################################################### | ||
| 5329 | |||
| 5330 | ############################################################################### | ||
| 5331 | # DB::Handy::Connection -- database connection handle (like $dbh) | ||
| 5332 | ############################################################################### | ||
| 5333 | package DB::Handy::Connection; | ||
| 5334 | use vars qw($VERSION); | ||
| 5335 | $VERSION = '1.09'; # keep in step with $DB::Handy::VERSION (literal so | ||
| 5336 | $VERSION = $VERSION; # that PAUSE and Module::Metadata can parse it) | ||
| 5337 | |||
| 5338 | use vars qw($errstr); | ||
| 5339 | $errstr = ''; | ||
| 5340 | |||
| 5341 | # new($base_dir, $database, \%opts) | ||
| 5342 | sub new { | ||
| 5343 | my($class, $base_dir, $database, $opts) = @_; | ||
| 5344 | $opts = {} unless ref($opts) eq 'HASH'; | ||
| 5345 | |||
| 5346 | # DBI code often opens a transaction by connecting with AutoCommit => 0. | ||
| 5347 | # There are no transactions here, so accepting that silently would leave | ||
| 5348 | # the caller believing its writes were being batched. | ||
| 5349 | if (exists($opts->{AutoCommit}) && !$opts->{AutoCommit}) { | ||
| 5350 | $errstr = "AutoCommit cannot be turned off: DB::Handy has no transactions"; | ||
| 5351 | if ($opts->{RaiseError}) { | ||
| 5352 | die "DB::Handy connect failed: $errstr\n"; | ||
| 5353 | } | ||
| 5354 | warn "DB::Handy: $errstr\n" if $opts->{PrintError}; | ||
| 5355 | return undef; | ||
| 5356 | } | ||
| 5357 | my $engine = DB::Handy->new(base_dir => $base_dir); | ||
| 5358 | unless (defined $engine) { | ||
| 5359 | $errstr = $DB::Handy::errstr; | ||
| 5360 | if ($opts->{RaiseError}) { | ||
| 5361 | die "DB::Handy connect failed: $errstr\n"; | ||
| 5362 | } | ||
| 5363 | return undef; | ||
| 5364 | } | ||
| 5365 | my $self = { | ||
| 5366 | _engine => $engine, | ||
| 5367 | _database => $database || '', | ||
| 5368 | AutoCommit => 1, | ||
| 5369 | RaiseError => $opts->{RaiseError} || 0, | ||
| 5370 | PrintError => (defined($opts->{PrintError}) ? $opts->{PrintError} : 0), | ||
| 5371 | errstr => '', | ||
| 5372 | err => 0, | ||
| 5373 | }; | ||
| 5374 | bless $self, $class; | ||
| 5375 | if ($database && (!defined($opts->{AutoUse}) || $opts->{AutoUse})) { | ||
| 5376 | my $res = $engine->execute("USE $database"); | ||
| 5377 | if ($res->{type} eq 'error') { | ||
| 5378 | $engine->execute("CREATE DATABASE $database"); | ||
| 5379 | $res = $engine->execute("USE $database"); | ||
| 5380 | } | ||
| 5381 | if ($res->{type} eq 'error') { | ||
| 5382 | $self->_set_err($DB::Handy::errstr || $res->{message}); | ||
| 5383 | return undef; | ||
| 5384 | } | ||
| 5385 | } | ||
| 5386 | return $self; | ||
| 5387 | } | ||
| 5388 | |||
| 5389 | # connect($dsn_or_dir, $database, \%opts) | ||
| 5390 | # Also accepts DSN string: "base_dir=./data;database=mydb" | ||
| 5391 | sub connect { | ||
| 5392 | my($class, $dsn, $database, $opts) = @_; | ||
| 5393 | my $base_dir; | ||
| 5394 | if (defined($dsn)) { | ||
| 5395 | # Strip optional dbi:Handy: prefix for DBI-style DSN | ||
| 5396 | $dsn =~ s/^dbi\s*:\s*Handy\s*:\s*//i; | ||
| 5397 | } | ||
| 5398 | if (defined($dsn) && ($dsn =~ /[=;]/)) { | ||
| 5399 | my %p = map { split /=/, $_, 2 } split /;/, $dsn; | ||
| 5400 | $base_dir = $p{base_dir} || $p{dir} || '.'; | ||
| 5401 | $database = $p{database} || $p{db} || $database; | ||
| 5402 | } | ||
| 5403 | else { | ||
| 5404 | $base_dir = defined($dsn) ? $dsn : '.'; | ||
| 5405 | } | ||
| 5406 | $opts = {} unless ref($opts) eq 'HASH'; | ||
| 5407 | return DB::Handy::Connection->new($base_dir, $database, $opts); | ||
| 5408 | } | ||
| 5409 | |||
| 5410 | # do($sql, @bind) -- shortcut for prepare+execute (useful for DDL/DML) | ||
| 5411 | sub do { | ||
| 5412 | my($self, $sql, @bind) = @_; | ||
| 5413 | my $sth = $self->prepare($sql) or return undef; | ||
| 5414 | return $sth->execute(@bind); | ||
| 5415 | } | ||
| 5416 | |||
| 5417 | # prepare($sql) -- returns a statement handle | ||
| 5418 | sub prepare { | ||
| 5419 | my($self, $sql) = @_; | ||
| 5420 | $self->_clear_err; | ||
| 5421 | unless (defined($sql) && ($sql =~ /\S/)) { | ||
| 5422 | $self->_set_err("prepare: empty SQL"); | ||
| 5423 | return undef; | ||
| 5424 | } | ||
| 5425 | return DB::Handy::Statement->new($self, $sql); | ||
| 5426 | } | ||
| 5427 | |||
| 5428 | # selectall_arrayref($sql, \%attr, @bind) | ||
| 5429 | # attr: Slice=>{} for array of hashrefs, Slice=>[] (default) for array of arrayrefs | ||
| 5430 | sub selectall_arrayref { | ||
| 5431 | my($self, $sql, $attr, @bind) = @_; | ||
| 5432 | $attr = {} unless ref($attr) eq 'HASH'; | ||
| 5433 | my $sth = $self->prepare($sql) or return undef; | ||
| 5434 | $sth->execute(@bind) or return undef; | ||
| 5435 | return $sth->fetchall_arrayref($attr->{Slice}); | ||
| 5436 | } | ||
| 5437 | |||
| 5438 | # selectall_hashref($sql, $key_col, \%attr, @bind) | ||
| 5439 | sub selectall_hashref { | ||
| 5440 | my($self, $sql, $key_col, $attr, @bind) = @_; | ||
| 5441 | my $rows = $self->selectall_arrayref($sql, {Slice=>{}}, @bind) or return undef; | ||
| 5442 | my %h; | ||
| 5443 | for my $row (@$rows) { | ||
| 5444 | $h{$row->{$key_col}} = $row; | ||
| 5445 | } | ||
| 5446 | return { %h }; | ||
| 5447 | } | ||
| 5448 | |||
| 5449 | # selectrow_hashref($sql, \%attr, @bind) | ||
| 5450 | sub selectrow_hashref { | ||
| 5451 | my($self, $sql, $attr, @bind) = @_; | ||
| 5452 | my $sth = $self->prepare($sql) or return undef; | ||
| 5453 | $sth->execute(@bind) or return undef; | ||
| 5454 | my $row = $sth->fetchrow_hashref; | ||
| 5455 | $sth->finish; | ||
| 5456 | return $row; | ||
| 5457 | } | ||
| 5458 | |||
| 5459 | # selectrow_arrayref($sql, \%attr, @bind) | ||
| 5460 | sub selectrow_arrayref { | ||
| 5461 | my($self, $sql, $attr, @bind) = @_; | ||
| 5462 | my $sth = $self->prepare($sql) or return undef; | ||
| 5463 | $sth->execute(@bind) or return undef; | ||
| 5464 | my $row = $sth->fetchrow_arrayref; | ||
| 5465 | $sth->finish; | ||
| 5466 | return $row; | ||
| 5467 | } | ||
| 5468 | |||
| 5469 | # quote($val) -- escape a value as a SQL single-quoted literal | ||
| 5470 | sub quote { | ||
| 5471 | my($self, $val) = @_; | ||
| 5472 | return 'NULL' unless defined $val; | ||
| 5473 | $val =~ s/'/''/g; | ||
| 5474 | return "'$val'"; | ||
| 5475 | } | ||
| 5476 | |||
| 5477 | # last_insert_id() -- row count recorded by the most recent INSERT | ||
| 5478 | # last_insert_id($catalog, $schema, $table, $field) | ||
| 5479 | # Arguments are accepted for DBI compatibility but ignored. | ||
| 5480 | sub last_insert_id { return $_[0]->{_last_insert_id} } | ||
| 5481 | |||
| 5482 | # table_info() -- list of tables [{TABLE_NAME=>...}, ...] | ||
| 5483 | sub table_info { | ||
| 5484 | my($self) = @_; | ||
| 5485 | my @tables = $self->{_engine}->list_tables(); | ||
| 5486 | return [ map { {TABLE_NAME=>$_, TABLE_TYPE=>'TABLE'} } @tables ]; | ||
| 5487 | } | ||
| 5488 | |||
| 5489 | # column_info($table) -- column metadata [{COLUMN_NAME=>..., DATA_TYPE=>...}, ...] | ||
| 5490 | sub column_info { | ||
| 5491 | my($self, $table) = @_; | ||
| 5492 | my $cols = $self->{_engine}->describe_table($table) or return undef; | ||
| 5493 | my $i = 0; | ||
| 5494 | return [ map { { | ||
| 5495 | COLUMN_NAME => $_->{name}, | ||
| 5496 | DATA_TYPE => $_->{type}, | ||
| 5497 | ORDINAL_POSITION => ++$i, | ||
| 5498 | IS_NULLABLE => ($_->{not_null} ? 'NO' : 'YES'), | ||
| 5499 | COLUMN_DEF => $_->{default}, | ||
| 5500 | } } @$cols ]; | ||
| 5501 | } | ||
| 5502 | |||
| 5503 | # disconnect() | ||
| 5504 | sub disconnect { | ||
| 5505 | my($self) = @_; | ||
| 5506 | $self->{_disconnected} = 1; | ||
| 5507 | return 1; | ||
| 5508 | } | ||
| 5509 | |||
| 5510 | # ping() -- returns 1 if connection is active | ||
| 5511 | sub ping { return $_[0]->{_disconnected} ? 0 : 1 } | ||
| 5512 | |||
| 5513 | # AutoCommit -- always on; transactions are not supported | ||
| 5514 | sub AutoCommit { return 1 } | ||
| 5515 | |||
| 5516 | # begin_work / commit / rollback | ||
| 5517 | # Transactions are not supported. These methods set errstr and return | ||
| 5518 | # undef rather than crashing, consistent with DBI error-handling style. | ||
| 5519 | sub begin_work { | ||
| 5520 | my($self) = @_; | ||
| 5521 | $self->_set_err( | ||
| 5522 | "Transactions are not supported: DB::Handy always operates in " | ||
| 5523 | . "AutoCommit mode. begin_work/commit/rollback are not available." | ||
| 5524 | ); | ||
| 5525 | return undef; | ||
| 5526 | } | ||
| 5527 | sub commit { | ||
| 5528 | my($self) = @_; | ||
| 5529 | $self->_set_err( | ||
| 5530 | "Transactions are not supported: DB::Handy always operates in " | ||
| 5531 | . "AutoCommit mode. begin_work/commit/rollback are not available." | ||
| 5532 | ); | ||
| 5533 | return undef; | ||
| 5534 | } | ||
| 5535 | sub rollback { | ||
| 5536 | my($self) = @_; | ||
| 5537 | $self->_set_err( | ||
| 5538 | "Transactions are not supported: DB::Handy always operates in " | ||
| 5539 | . "AutoCommit mode. begin_work/commit/rollback are not available." | ||
| 5540 | ); | ||
| 5541 | return undef; | ||
| 5542 | } | ||
| 5543 | |||
| 5544 | # errstr / err accessors | ||
| 5545 | sub errstr { return $_[0]->{errstr} } | ||
| 5546 | sub err { return $_[0]->{err} } | ||
| 5547 | |||
| 5548 | # _clear_err() -- DBI resets err/errstr at the start of every method that | ||
| 5549 | # talks to the database, so that a stale message from an earlier failure | ||
| 5550 | # is never mistaken for the outcome of the call that just succeeded. | ||
| 5551 | sub _clear_err { | ||
| 5552 | my($self) = @_; | ||
| 5553 | $self->{errstr} = ''; | ||
| 5554 | $self->{err} = 0; | ||
| 5555 | return; | ||
| 5556 | } | ||
| 5557 | |||
| 5558 | sub _set_err { | ||
| 5559 | my($self, $msg, $code) = @_; | ||
| 5560 | $code = 1 unless defined $code; | ||
| 5561 | $self->{errstr} = $msg; | ||
| 5562 | $self->{err} = $code; | ||
| 5563 | $errstr = $msg; | ||
| 5564 | if ($self->{PrintError}) { | ||
| 5565 | warn "DB::Handy: $msg\n"; | ||
| 5566 | } | ||
| 5567 | if ($self->{RaiseError}) { | ||
| 5568 | die "DB::Handy: $msg\n"; | ||
| 5569 | } | ||
| 5570 | } | ||
| 5571 | |||
| 5572 | ############################################################################### | ||
| 5573 | # DB::Handy::Statement -- statement handle (like $sth) | ||
| 5574 | ############################################################################### | ||
| 5575 | package DB::Handy::Statement; | ||
| 5576 | use vars qw($VERSION); | ||
| 5577 | $VERSION = '1.09'; # keep in step with $DB::Handy::VERSION (literal so | ||
| 5578 | $VERSION = $VERSION; # that PAUSE and Module::Metadata can parse it) | ||
| 5579 | |||
| 5580 | use vars qw($errstr); | ||
| 5581 | $errstr = ''; | ||
| 5582 | |||
| 5583 | sub new { | ||
| 5584 | my($class, $dbh, $sql) = @_; | ||
| 5585 | my $self = { | ||
| 5586 | _dbh => $dbh, | ||
| 5587 | _sql => $sql, | ||
| 5588 | _rows => undef, | ||
| 5589 | _cursor => 0, | ||
| 5590 | _executed => 0, | ||
| 5591 | _bind_params => [], | ||
| 5592 | rows => 0, | ||
| 5593 | errstr => '', | ||
| 5594 | err => 0, | ||
| 5595 | NAME => [], | ||
| 5596 | NAME_lc => [], | ||
| 5597 | NAME_uc => [], | ||
| 5598 | NUM_OF_FIELDS => 0, | ||
| 5599 | NUM_OF_PARAMS => _count_placeholders($sql), | ||
| 5600 | Statement => $sql, | ||
| 5601 | }; | ||
| 5602 | bless $self, $class; | ||
| 5603 | return $self; | ||
| 5604 | } | ||
| 5605 | |||
| 5606 | # Number of ? placeholders, ignoring any that sit inside a string literal | ||
| 5607 | # or a comment. This is the same count execute() will consume. | ||
| 5608 | sub _count_placeholders { | ||
| 5609 | my($sql) = @_; | ||
| 5610 | my $n = 0; | ||
| 5611 | for my $part (DB::Handy::_split_sql_literals(DB::Handy::_strip_sql_comments($sql))) { | ||
| 5612 | next if $part->[0]; | ||
| 5613 | $n += ($part->[1] =~ tr/?//); | ||
| 5614 | } | ||
| 5615 | return $n; | ||
| 5616 | } | ||
| 5617 | |||
| 5618 | # execute(@bind_values) -- substitute ? placeholders and run the statement | ||
| 5619 | sub execute { | ||
| 5620 | my($self, @bind) = @_; | ||
| 5621 | $self->_clear_err; | ||
| 5622 | |||
| 5623 | # merge values pre-set via bind_param() | ||
| 5624 | if (!@bind && @{$self->{_bind_params}}) { | ||
| 5625 | @bind = @{$self->{_bind_params}}; | ||
| 5626 | } | ||
| 5627 | |||
| 5628 | # DBI refuses a bind list whose length does not match the number of | ||
| 5629 | # placeholders. Without this check a missing value left a bare "?" | ||
| 5630 | # in the statement -- which then matched nothing -- and a surplus | ||
| 5631 | # value was dropped, so either mistake produced a silently wrong | ||
| 5632 | # result instead of an error. | ||
| 5633 | my $got = scalar @bind; | ||
| 5634 | my $need = $self->{NUM_OF_PARAMS}; | ||
| 5635 | if ($got != $need) { | ||
| 5636 | $self->_set_err( | ||
| 5637 | "called with $got bind variable" . (($got == 1) ? '' : 's') | ||
| 5638 | . " when $need " . (($need == 1) ? 'is' : 'are') | ||
| 5639 | . " needed" | ||
| 5640 | ); | ||
| 5641 | return undef; | ||
| 5642 | } | ||
| 5643 | |||
| 5644 | # Comments are removed first so that a ? inside one is not mistaken | ||
| 5645 | # for a placeholder; a ? inside a string literal is left alone too. | ||
| 5646 | my $sql = DB::Handy::_strip_sql_comments($self->{_sql}); | ||
| 5647 | |||
| 5648 | # substitute ? placeholders with actual values | ||
| 5649 | if (@bind) { | ||
| 5650 | my @params = @bind; | ||
| 5651 | my $out = ''; | ||
| 5652 | for my $part (DB::Handy::_split_sql_literals($sql)) { | ||
| 5653 | if ($part->[0]) { $out .= $part->[1]; next } | ||
| 5654 | my $chunk = $part->[1]; | ||
| 5655 | $chunk =~ s/\?/_dbi_quote(shift @params)/ge; | ||
| 5656 | $out .= $chunk; | ||
| 5657 | } | ||
| 5658 | $sql = $out; | ||
| 5659 | } | ||
| 5660 | |||
| 5661 | my $engine = $self->{_dbh}{_engine}; | ||
| 5662 | my $res = $engine->execute($sql); | ||
| 5663 | |||
| 5664 | $self->{_result} = $res; | ||
| 5665 | $self->{_executed} = 1; | ||
| 5666 | |||
| 5667 | if ($res->{type} eq 'error') { | ||
| 5668 | $self->_set_err($res->{message}); | ||
| 5669 | return undef; | ||
| 5670 | } | ||
| 5671 | |||
| 5672 | if ($res->{type} eq 'rows') { | ||
| 5673 | my $data = $res->{data}; | ||
| 5674 | $self->{_rows} = $data; | ||
| 5675 | $self->{_cursor} = 0; | ||
| 5676 | my $n = scalar @$data; | ||
| 5677 | $self->{rows} = $n; | ||
| 5678 | # Determine column order: prefer SELECT list order; for SELECT * | ||
| 5679 | # use schema declaration order; fall back to alphabetical. | ||
| 5680 | my @name_order = $self->_col_order_from_sql($sql, $data, $engine); | ||
| 5681 | $self->{NAME} = [ @name_order ]; | ||
| 5682 | $self->{NAME_lc} = [ map { lc $_ } @name_order ]; | ||
| 5683 | $self->{NAME_uc} = [ map { uc $_ } @name_order ]; | ||
| 5684 | $self->{NUM_OF_FIELDS} = scalar @name_order; | ||
| 5685 | return $n || '0E0'; | ||
| 5686 | } | ||
| 5687 | |||
| 5688 | # INSERT / UPDATE / DELETE / DDL | ||
| 5689 | if ($res->{type} eq 'ok') { | ||
| 5690 | my $affected = 0; | ||
| 5691 | if (defined($res->{message}) && ($res->{message} =~ /(\d+)\s+row/)) { | ||
| 5692 | $affected = $1 + 0; | ||
| 5693 | } | ||
| 5694 | $self->{rows} = $affected; | ||
| 5695 | $self->{_rows} = undef; | ||
| 5696 | $self->{NAME} = []; | ||
| 5697 | $self->{NAME_lc} = []; | ||
| 5698 | $self->{NAME_uc} = []; | ||
| 5699 | $self->{NUM_OF_FIELDS} = 0; | ||
| 5700 | if ($sql =~ /^\s*INSERT\b/i) { | ||
| 5701 | $self->{_dbh}{_last_insert_id} = $affected; | ||
| 5702 | } | ||
| 5703 | return $affected || '0E0'; | ||
| 5704 | } | ||
| 5705 | |||
| 5706 | # SHOW / DESCRIBE and other statement types | ||
| 5707 | if (ref($res->{data}) eq 'ARRAY') { | ||
| 5708 | $self->{_rows} = $res->{data}; | ||
| 5709 | $self->{_cursor} = 0; | ||
| 5710 | $self->{rows} = scalar @{$res->{data}}; | ||
| 5711 | } | ||
| 5712 | return '0E0'; | ||
| 5713 | } | ||
| 5714 | |||
| 5715 | # _col_order_from_sql($sql, $data, $engine) | ||
| 5716 | # | ||
| 5717 | # Return column names in the order they should be presented to the caller. | ||
| 5718 | # | ||
| 5719 | # For named SELECT lists (SELECT a, b, c) the order follows the SELECT list, | ||
| 5720 | # including AS aliases (already handled since 1.01). | ||
| 5721 | # | ||
| 5722 | # For SELECT * on a single table the order follows the CREATE TABLE column | ||
| 5723 | # declaration order, obtained from the schema. | ||
| 5724 | # | ||
| 5725 | # For SELECT * on a JOIN the order follows the table appearance order in | ||
| 5726 | # the FROM/JOIN clause, each table's columns in declaration order, returned | ||
| 5727 | # as 'alias.col' qualified names matching the result-row hash keys. | ||
| 5728 | # | ||
| 5729 | # Falls back to alphabetical (sorted keys of the first data row) when the | ||
| 5730 | # schema cannot be resolved or the SQL cannot be parsed. | ||
| 5731 | # | ||
| 5732 | sub _col_order_from_sql { | ||
| 5733 | my($self, $sql, $data, $engine) = @_; | ||
| 5734 | # Fallback: alphabetical from first row (or empty) | ||
| 5735 | my @fallback = ($data && @$data) ? sort keys %{$data->[0]} : (); | ||
| 5736 | return @fallback unless defined $sql; | ||
| 5737 | # Strip leading SELECT keyword | ||
| 5738 | my $col_str; | ||
| 5739 | if ($sql =~ /^SELECT\s+(.*?)\s+FROM\b/si) { | ||
| 5740 | $col_str = $1; | ||
| 5741 | } | ||
| 5742 | else { | ||
| 5743 | return @fallback; | ||
| 5744 | } | ||
| 5745 | $col_str =~ s/^DISTINCT\s+//si; | ||
| 5746 | # SELECT * (or alias.*): try to use schema declaration order | ||
| 5747 | if ($col_str =~ /^\*$/ || $col_str =~ /^\w+\.\*$/) { | ||
| 5748 | return @fallback unless defined $engine; | ||
| 5749 | # Parse FROM clause to get table name and optional alias | ||
| 5750 | if ($sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?\s*(?:WHERE|ORDER|GROUP|LIMIT|OFFSET|$)/si | ||
| 5751 | && $sql !~ /\bJOIN\b/i) { | ||
| 5752 | my($tbl, $alias) = ($1, $2); | ||
| 5753 | my $sch = $engine->_load_schema($tbl); | ||
| 5754 | return @fallback unless $sch; | ||
| 5755 | my @names = map { $_->{name} } @{$sch->{cols}}; | ||
| 5756 | # Verify names match result keys | ||
| 5757 | if (@$data) { | ||
| 5758 | my %keys = map { $_ => 1 } keys %{$data->[0]}; | ||
| 5759 | return @fallback if grep { !$keys{$_} } @names; | ||
| 5760 | } | ||
| 5761 | return @names; | ||
| 5762 | } | ||
| 5763 | # JOIN: collect tables in FROM/JOIN order, build alias.col names | ||
| 5764 | if ($sql =~ /\bJOIN\b/i) { | ||
| 5765 | return @fallback unless defined $engine; | ||
| 5766 | my @table_aliases; | ||
| 5767 | # Extract first table from FROM | ||
| 5768 | if ($sql =~ /\bFROM\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/si) { | ||
| 5769 | push @table_aliases, [ $1, (defined $2 ? $2 : $1) ]; | ||
| 5770 | } | ||
| 5771 | # Extract subsequent JOIN tables | ||
| 5772 | my $rest = $sql; | ||
| 5773 | while ($rest =~ /\bJOIN\s+(\w+)(?:\s+(?:AS\s+)?(\w+))?/gsi) { | ||
| 5774 | push @table_aliases, [ $1, (defined $2 ? $2 : $1) ]; | ||
| 5775 | } | ||
| 5776 | my @names; | ||
| 5777 | for my $ta (@table_aliases) { | ||
| 5778 | my($tbl, $alias) = @$ta; | ||
| 5779 | my $sch = $engine->_load_schema($tbl); | ||
| 5780 | next unless $sch; | ||
| 5781 | for my $col (@{$sch->{cols}}) { | ||
| 5782 | push @names, "$alias.$col->{name}"; | ||
| 5783 | } | ||
| 5784 | } | ||
| 5785 | if (@names) { | ||
| 5786 | # Verify names match result keys | ||
| 5787 | if (@$data) { | ||
| 5788 | my %keys = map { $_ => 1 } keys %{$data->[0]}; | ||
| 5789 | return @fallback if grep { !$keys{$_} } @names; | ||
| 5790 | } | ||
| 5791 | return @names; | ||
| 5792 | } | ||
| 5793 | return @fallback; | ||
| 5794 | } | ||
| 5795 | return @fallback; | ||
| 5796 | } | ||
| 5797 | # Split on commas (not inside parentheses) | ||
| 5798 | my @parts; | ||
| 5799 | my($cur, $depth) = ('', 0); | ||
| 5800 | for my $ch (split //, $col_str) { | ||
| 5801 | if ($ch eq '(') { $depth++; $cur .= $ch } | ||
| 5802 | elsif ($ch eq ')') { $depth--; $cur .= $ch } | ||
| 5803 | elsif ($ch eq ',' && $depth == 0) { push @parts, $cur; $cur = '' } | ||
| 5804 | else { $cur .= $ch } | ||
| 5805 | } | ||
| 5806 | push @parts, $cur if length $cur; | ||
| 5807 | my(@names, @alt); | ||
| 5808 | for my $part (@parts) { | ||
| 5809 | $part =~ s/^\s+|\s+$//g; | ||
| 5810 | # explicit alias: expr AS alias | ||
| 5811 | if ($part =~ /\bAS\s+(\w+)\s*$/si) { | ||
| 5812 | push @names, $1; | ||
| 5813 | push @alt, undef; | ||
| 5814 | } | ||
| 5815 | # qualified alias.col -> keep as 'alias.col' (JOIN result key format) | ||
| 5816 | elsif ($part =~ /^(\w+)\.(\w+)$/) { | ||
| 5817 | push @names, "$1.$2"; | ||
| 5818 | |||
| 5819 | # An aggregate query over a JOIN keys its output rows by the bare | ||
| 5820 | # column name, so 'a.y' has to be able to resolve to 'y'. Without | ||
| 5821 | # this the whole list was rejected below and the alphabetical | ||
| 5822 | # fallback took over, which put the columns of | ||
| 5823 | # "SELECT a.y, COUNT(*) ... GROUP BY a.y" in the order | ||
| 5824 | # COUNT(*), y. | ||
| 5825 | push @alt, $2; | ||
| 5826 | } | ||
| 5827 | # bare column name | ||
| 5828 | elsif ($part =~ /^(\w+)$/) { | ||
| 5829 | push @names, $1; | ||
| 5830 | push @alt, undef; | ||
| 5831 | } | ||
| 5832 | # complex expression without alias -> use the expression text as key | ||
| 5833 | else { | ||
| 5834 | push @names, $part; | ||
| 5835 | push @alt, undef; | ||
| 5836 | } | ||
| 5837 | } | ||
| 5838 | # Verify that every parsed name exists as a key in the result | ||
| 5839 | # (guards against mis-parses; also handles 0-row results) | ||
| 5840 | if (@$data) { | ||
| 5841 | my %keys = map { $_ => 1 } keys %{$data->[0]}; | ||
| 5842 | for my $i (0 .. $#names) { | ||
| 5843 | next if $keys{$names[$i]}; | ||
| 5844 | if (defined($alt[$i]) && $keys{$alt[$i]}) { | ||
| 5845 | $names[$i] = $alt[$i]; | ||
| 5846 | next; | ||
| 5847 | } | ||
| 5848 | return @fallback; | ||
| 5849 | } | ||
| 5850 | } | ||
| 5851 | return @names; | ||
| 5852 | } | ||
| 5853 | |||
| 5854 | # fetchrow_hashref -- return next row as hashref (undef at EOF) | ||
| 5855 | sub fetchrow_hashref { | ||
| 5856 | my($self) = @_; | ||
| 5857 | return undef unless defined $self->{_rows}; | ||
| 5858 | return undef if $self->{_cursor} >= scalar @{$self->{_rows}}; | ||
| 5859 | my $row = $self->{_rows}[ $self->{_cursor}++ ]; | ||
| 5860 | return { %$row }; | ||
| 5861 | } | ||
| 5862 | |||
| 5863 | # fetchrow_arrayref -- return next row as arrayref (columns in NAME order) | ||
| 5864 | sub fetchrow_arrayref { | ||
| 5865 | my($self) = @_; | ||
| 5866 | my $href = $self->fetchrow_hashref or return undef; | ||
| 5867 | my @cols = @{$self->{NAME}} ? @{$self->{NAME}} : sort keys %$href; | ||
| 5868 | return [ map { $href->{$_} } @cols ]; | ||
| 5869 | } | ||
| 5870 | |||
| 5871 | # fetchrow_array -- return next row as a list | ||
| 5872 | sub fetchrow_array { | ||
| 5873 | my($self) = @_; | ||
| 5874 | my $aref = $self->fetchrow_arrayref or return (); | ||
| 5875 | return @$aref; | ||
| 5876 | } | ||
| 5877 | |||
| 5878 | # fetch -- alias for fetchrow_arrayref | ||
| 5879 | sub fetch { return $_[0]->fetchrow_arrayref } | ||
| 5880 | |||
| 5881 | # fetchall_arrayref([$slice]) | ||
| 5882 | # $slice = {} -> [{col=>val,...}, ...] | ||
| 5883 | # $slice = [] -> [[val,...], ...] (default) | ||
| 5884 | sub fetchall_arrayref { | ||
| 5885 | my($self, $slice) = @_; | ||
| 5886 | return undef unless defined $self->{_rows}; | ||
| 5887 | my @all; | ||
| 5888 | if (ref($slice) eq 'HASH') { | ||
| 5889 | while (my $row = $self->fetchrow_hashref) { | ||
| 5890 | push @all, $row; | ||
| 5891 | } | ||
| 5892 | } | ||
| 5893 | else { | ||
| 5894 | while (my $row = $self->fetchrow_arrayref) { | ||
| 5895 | push @all, $row; | ||
| 5896 | } | ||
| 5897 | } | ||
| 5898 | return [ @all ]; | ||
| 5899 | } | ||
| 5900 | |||
| 5901 | # fetchall_hashref($key_col) -- return rows as a hashref keyed by $key_col | ||
| 5902 | sub fetchall_hashref { | ||
| 5903 | my($self, $key_col) = @_; | ||
| 5904 | my %h; | ||
| 5905 | while (my $row = $self->fetchrow_hashref) { | ||
| 5906 | $h{$row->{$key_col}} = $row; | ||
| 5907 | } | ||
| 5908 | return { %h }; | ||
| 5909 | } | ||
| 5910 | |||
| 5911 | # bind_param($pos, $val [, $attr]) -- pre-bind a placeholder by position | ||
| 5912 | sub bind_param { | ||
| 5913 | my($self, $pos, $val, $attr) = @_; | ||
| 5914 | $self->{_bind_params}[$pos - 1] = $val; | ||
| 5915 | return 1; | ||
| 5916 | } | ||
| 5917 | |||
| 5918 | # finish -- reset cursor and release resources | ||
| 5919 | sub finish { | ||
| 5920 | my($self) = @_; | ||
| 5921 | $self->{_rows} = undef; | ||
| 5922 | $self->{_cursor} = 0; | ||
| 5923 | $self->{_bind_params} = []; | ||
| 5924 | return 1; | ||
| 5925 | } | ||
| 5926 | |||
| 5927 | # rows -- number of rows affected or fetched by the last execute | ||
| 5928 | sub rows { return $_[0]->{rows} } | ||
| 5929 | |||
| 5930 | # errstr / err accessors | ||
| 5931 | sub errstr { return $_[0]->{errstr} } | ||
| 5932 | sub err { return $_[0]->{err} } | ||
| 5933 | |||
| 5934 | sub _clear_err { | ||
| 5935 | my($self) = @_; | ||
| 5936 | $self->{errstr} = ''; | ||
| 5937 | $self->{err} = 0; | ||
| 5938 | my $dbh = $self->{_dbh}; | ||
| 5939 | $dbh->_clear_err if ref($dbh); | ||
| 5940 | return; | ||
| 5941 | } | ||
| 5942 | |||
| 5943 | sub _set_err { | ||
| 5944 | my($self, $msg, $code) = @_; | ||
| 5945 | $code = 1 unless defined $code; | ||
| 5946 | $self->{errstr} = $msg; | ||
| 5947 | $self->{err} = $code; | ||
| 5948 | $errstr = $msg; | ||
| 5949 | my $dbh = $self->{_dbh}; | ||
| 5950 | $dbh->_set_err($msg, $code) if ref($dbh); | ||
| 5951 | } | ||
| 5952 | |||
| 5953 | # _dbi_quote($val) -- internal helper for ? placeholder substitution | ||
| 5954 | sub _dbi_quote { | ||
| 5955 | my($val) = @_; | ||
| 5956 | return 'NULL' unless defined $val; | ||
| 5957 | return $val if $val =~ /^-?\d+\.?\d*$/; # numeric: pass through as-is | ||
| 5958 | $val =~ s/'/''/g; | ||
| 5959 | return "'$val'"; | ||
| 5960 | } | ||
| 5961 | |||
| 5962 | ############################################################################### | ||
| 5963 | # Add connect() class method to DB::Handy | ||
| 5964 | ############################################################################### | ||
| 5965 | package DB::Handy; | ||
| 5966 | |||
| 5967 | sub connect { | ||
| 5968 | my($class, $dsn, $database, $opts) = @_; | ||
| 5969 | return DB::Handy::Connection->connect($dsn, $database, $opts); | ||
| 5970 | } | ||
| 5971 | |||
| 5972 | 1; | ||
| 5973 | |||
| 5974 | __END__ |