1package DBIx::Perlish; 2 3use 5.014; 4use warnings; 5use strict; 6use Carp; 7 8use vars qw($VERSION @EXPORT @EXPORT_OK %EXPORT_TAGS $SQL @BIND_VALUES); 9require Exporter; 10use base 'Exporter'; 11use Keyword::Pluggable; 12 13$VERSION = '1.06'; 14@EXPORT = qw(sql); 15@EXPORT_OK = qw(union intersect except subselect); 16%EXPORT_TAGS = (all => [@EXPORT, @EXPORT_OK]); 17 18use DBIx::Perlish::Parse; 19 20sub union (&;$) {} 21sub intersect (&;$) {} 22sub except (&;$) {} 23sub subselect (&) {} 24 25my $default_object; 26my $non_object_quirks = {}; 27 28sub optree_version 29{ 30 return 1 if $^V lt 5.22.0; 31 return 2; 32} 33 34sub lexify 35{ 36 my ( $text, $insert ) = @_; 37 $insert .= 'sub ' if $$text =~ /^\s*\{/; 38 substr($$text, 0, 0, $insert); 39} 40 41sub import 42{ 43 my $pkg = caller; 44 local @EXPORT_OK = @EXPORT_OK; 45 local %EXPORT_TAGS = %EXPORT_TAGS; 46 if ($pkg && $pkg->can("except")) { 47 # XXX maybe check prototype here 48 pop @EXPORT_OK; 49 %EXPORT_TAGS = (all => [@EXPORT, @EXPORT_OK]); 50 } 51 my @shift; 52 @shift = (shift()) if @_ % 2; 53 my %p = @_; 54 if ($p{prefix} && $p{prefix} =~ /^[a-zA-Z_]\w*$/) { 55 no strict 'refs'; 56 if ( $p{dbh} && ref $p{dbh} && (ref $p{dbh} eq "SCALAR" || ref $p{dbh} eq "REF")) { 57 my $dbhref = $p{dbh}; 58 *{$pkg."::$p{prefix}_fetch"} = 59 *{$pkg."::$p{prefix}_select"} = 60 sub (&) { my $o = DBIx::Perlish->new(dbh => $$dbhref); $o->fetch(@_) }; 61 *{$pkg."::$p{prefix}_update"} = 62 sub (&) { my $o = DBIx::Perlish->new(dbh => $$dbhref); $o->update(@_) }; 63 *{$pkg."::$p{prefix}_delete"} = 64 sub (&) { my $o = DBIx::Perlish->new(dbh => $$dbhref); $o->delete(@_) }; 65 *{$pkg."::$p{prefix}_insert"} = 66 sub { my $o = DBIx::Perlish->new(dbh => $$dbhref); $o->insert(@_) }; 67 return; 68 } 69 } 70 71 my $prefix = delete($p{prefix}) // 'db'; 72 my $dbh = delete($p{dbh}) // '$dbh'; 73 my $iprefix = '__' . $dbh . '_execute_perlish'; 74 $iprefix =~ s/\W//g; 75 76 for ( 77 [fetch => " $dbh, q(fetch), "], 78 [select => " $dbh, q(fetch), "], 79 [update => " $dbh, q(update), "], 80 [delete => " $dbh, q(delete), "], 81 ) { 82 my ($name, $code) = @$_; 83 Keyword::Pluggable::define 84 keyword => $prefix . '_' . $name, 85 code => sub { lexify( $_[0], $iprefix.$code ) }, 86 expression => 1, 87 package => $pkg 88 ; 89 } 90 Keyword::Pluggable::define 91 keyword => $prefix . '_insert', 92 code => $iprefix . "_insert $dbh, ", 93 expression => 1, 94 package => $pkg 95 ; 96 97 { 98 no strict 'refs'; 99 *{$pkg."::${iprefix}"} = sub ($$&) { 100 my ( $dbh, $method, $sub ) = @_; 101 my $o = DBIx::Perlish->new(dbh => $dbh); 102 $o->$method($sub); 103 }; 104 *{$pkg."::${iprefix}_insert"} = sub { 105 my $o = DBIx::Perlish->new(dbh => shift); 106 $o->insert(@_) 107 }; 108 } 109 DBIx::Perlish->export_to_level(1, @shift, %p); 110} 111 112sub init { warn "DBIx::Perlish::init is deprecated" } 113 114sub new 115{ 116 my ($class, %p) = @_; 117 unless (UNIVERSAL::isa($p{dbh}, "DBI::db")) { # XXX maybe relax for other things? 118 die "Invalid database handle supplied in the \"dbh\" parameter.\n"; 119 } 120 my $me = bless { dbh => $p{dbh}, quirks => {} }, $class; 121 if ($p{quirks} && ref $p{quirks} eq "ARRAY") { 122 for my $q (@{$p{quirks}}) { 123 $me->quirk(@$q); 124 } 125 } 126 return $me; 127} 128 129sub quirk 130{ 131 my $flavor = shift; 132 my $quirks = $non_object_quirks; 133 if (ref $flavor) { 134 $quirks = $flavor->{quirks}; 135 $flavor = shift; 136 } 137 $flavor = lc $flavor; 138 if ($flavor eq "oracle") { 139 my $qtype = shift; 140 if ($qtype eq "table_func_cast") { 141 my ($func, $cast) = @_; 142 die "table_func_cast requires a function name and a type name" unless $cast; 143 $quirks->{oracle_table_func_cast}{$func} = $cast; 144 } else { 145 die "unknown quirk $qtype for $flavor"; 146 } 147 } else { 148 die "there are currently no quirks for $flavor"; 149 } 150} 151 152sub _get_flavor 153{ 154 my ($real_dbh) = @_; 155 my $dbh = tied(%$real_dbh) || $real_dbh; 156 return lc $dbh->{Driver}{Name}; 157} 158 159sub gen_sql_select 160{ 161 my ($moi, $sub) = @_; 162 my $me = ref $moi ? $moi : {}; 163 164 my $dbh = $me->{dbh}; 165 my @kf; 166 my $flavor = _get_flavor($dbh); 167 my $kf_convert = sub { return $_[0] }; 168 if ($flavor eq "pg" && $dbh->{FetchHashKeyName}) { 169 if ($dbh->{FetchHashKeyName} eq "NAME_uc") { 170 $kf_convert = sub { return uc $_[0] }; 171 } elsif ($dbh->{FetchHashKeyName} eq "NAME_lc") { 172 $kf_convert = sub { return lc $_[0] }; 173 } 174 } 175 my ($sql, $bind_values, $nret, %flags) = gen_sql($sub, "select", 176 flavor => $flavor, 177 dbh => $dbh, 178 quirks => $me->{quirks} || $non_object_quirks, 179 key_fields => \@kf, 180 kf_convert => $kf_convert, 181 ); 182 $flags{key_fields} = \@kf if @kf; 183 return $sql, $bind_values, $nret, %flags; 184} 185 186sub query 187{ 188 my ($moi, $sub) = @_; 189 my $me = ref $moi ? $moi : {}; 190 my ( $sql ) = $moi->gen_sql_select($sub); 191 return $sql; 192} 193 194sub fetch 195{ 196 my ($moi, $sub) = @_; 197 my $me = ref $moi ? $moi : {}; 198 199 my $nret; 200 my $dbh = $me->{dbh}; 201 my %flags; 202 203 ($me->{sql}, $me->{bind_values}, $nret, %flags) = $me->gen_sql_select($sub); 204 $SQL = $me->{sql}; @BIND_VALUES = @{$me->{bind_values}}; 205 206 if ($flags{key_fields}) { 207 my @kf = @{ $flags{key_fields} // [] }; 208 my $kf = @kf == 1 ? $kf[0] : [@kf]; 209 my $r = $dbh->selectall_hashref($me->{sql}, $kf, {}, @{$me->{bind_values}}) || {}; 210 my $postprocess; 211 if ($nret - @kf == 1) { 212 # Only one field returned apart from the key field, 213 # change hash reference to simple values. 214 $postprocess = sub { 215 my ($h, $level) = @_; 216 if ($level <= 1) { 217 delete @$_{@kf} for values %$h; 218 $_ = (values %$_)[0] for values %$h; 219 } else { 220 for my $nh (values %$h) { 221 $postprocess->($nh, $level-1); 222 } 223 } 224 }; 225 } else { 226 $postprocess = sub { 227 my ($h, $level) = @_; 228 if ($level <= 1) { 229 delete @$_{@kf} for values %$h; 230 } else { 231 for my $nh (values %$h) { 232 $postprocess->($nh, $level-1); 233 } 234 } 235 }; 236 } 237 $postprocess->($r, scalar @kf); 238 return wantarray ? %$r : $r; 239 } else { 240 if ($nret > 1) { 241 my $r = $dbh->selectall_arrayref($me->{sql}, {Slice=>{}}, @{$me->{bind_values}}) || []; 242 return wantarray ? @$r : $r->[0]; 243 } else { 244 my $r = $dbh->selectcol_arrayref($me->{sql}, {}, @{$me->{bind_values}}) || []; 245 return wantarray ? @$r : $r->[0]; 246 } 247 } 248} 249 250# XXX refactor update/delete into a single implemention if possible? 251sub update 252{ 253 my ($moi, $sub) = @_; 254 my $me = ref $moi ? $moi : {}; 255 256 my $dbh = $me->{dbh}; 257 ($me->{sql}, $me->{bind_values}) = gen_sql($sub, "update", 258 flavor => _get_flavor($dbh), 259 dbh => $dbh, 260 quirks => $me->{quirks} || $non_object_quirks, 261 ); 262 $SQL = $me->{sql}; @BIND_VALUES = @{$me->{bind_values}}; 263 $dbh->do($me->{sql}, {}, @{$me->{bind_values}}); 264} 265 266sub delete 267{ 268 my ($moi, $sub) = @_; 269 my $me = ref $moi ? $moi : {}; 270 271 my $dbh = $me->{dbh}; 272 ($me->{sql}, $me->{bind_values}) = gen_sql($sub, "delete", 273 flavor => _get_flavor($dbh), 274 dbh => $dbh, 275 quirks => $me->{quirks} || $non_object_quirks, 276 ); 277 $SQL = $me->{sql}; @BIND_VALUES = @{$me->{bind_values}}; 278 $dbh->do($me->{sql}, {}, @{$me->{bind_values}}); 279} 280 281sub insert 282{ 283 my ($moi, $table, @rows) = @_; 284 my $me = ref $moi ? $moi : {}; 285 286 my $dbh = $me->{dbh}; 287 my %sth; 288 for my $row (@rows) { 289 my @keys = sort keys %$row; 290 my $sql = "insert into $table ("; 291 $sql .= join ",", @keys; 292 $sql .= ") values ("; 293 my (@v, @b); 294 my $skip_prepare; 295 for my $v (@$row{@keys}) { 296 if (ref $v eq 'CODE') { 297 push @v, scalar $v->(); 298 $skip_prepare = 1; 299 } else { 300 push @v, "?"; 301 push @b, $v; 302 } 303 } 304 $sql .= join ",", @v; 305 $sql .= ")"; 306 if ($skip_prepare) { 307 return undef unless defined $dbh->do($sql, {}, @b); 308 } else { 309 my $k = join ";", @keys; 310 $sth{$k} ||= $dbh->prepare($sql); 311 return undef unless defined $sth{$k}->execute(@b); 312 } 313 } 314 return scalar @rows; 315} 316 317sub sql ($) { 318 my $self = shift; 319 if (ref $self && $self->isa("DBIx::Perlish")) { 320 $self->{sql}; 321 } else { 322 sub { $self } 323 } 324} 325sub bind_values { $_[0]->{bind_values} ? @{$_[0]->{bind_values}} : () } 326 327sub gen_sql 328{ 329 my ($sub, $operation, %args) = @_; 330 331 $args{quirks} = $non_object_quirks unless $args{quirks}; 332 $args{inline} //= 1; 333 334 my $S = DBIx::Perlish::Parse::init(%args, operation => $operation); 335 DBIx::Perlish::Parse::parse_sub($S, $sub); 336 my $sql = ""; 337 my $next_bit = ""; 338 my $nret = 9999; 339 my $no_aliases; 340 my $dangerous; 341 my %flags; 342 if ($operation eq "select") { 343 my $nkf = 0; 344 if ($S->{key_fields}) { 345 $nkf = @{$S->{key_fields}}; 346 push @{$args{key_fields}}, @{$S->{key_fields}} if $args{key_fields}; 347 } 348 $sql = "select "; 349 $sql .= "distinct " if $S->{distinct}; 350 if ($S->{returns}) { 351 $sql .= join ", ", @{$S->{returns}}; 352 $nret = @{$S->{returns}}; 353 for my $ret (@{$S->{returns}}) { 354 $nret = 9999 if $ret =~ /\*/; 355 } 356 $flags{returns_dont_care} = 1 if 357 1 == @{$S->{returns}} && 358 $S->{returns}->[0] =~ /^(.*)\.\*/ && 359 $S->{returns_dont_care}->{$1} 360 ; 361 } else { 362 $sql .= "*"; 363 } 364 $next_bit = " from "; 365 die "all returns are key fields, this is nonsensical\n" if $nkf == $nret; 366 } elsif ($operation eq "delete") { 367 $no_aliases = 1; 368 $dangerous = 1; 369 $next_bit = "delete from "; 370 } elsif ($operation eq "update") { 371 $no_aliases = 1; 372 $dangerous = 1; 373 $next_bit = "update "; 374 } else { 375 die "unsupported operation: $operation\n"; 376 } 377 my %tabs; 378 for my $var (keys %{$S->{vars}}) { 379 $tabs{$S->{var_alias}->{$var}} = 380 $no_aliases ? 381 "$S->{vars}->{$var}" : 382 "$S->{vars}->{$var} $S->{var_alias}->{$var}"; 383 } 384 for my $tab (keys %{$S->{tabs}}) { 385 $tabs{$S->{tab_alias}->{$tab}} = 386 $no_aliases ? 387 "$tab" : 388 "$tab $S->{tab_alias}->{$tab}"; 389 } 390 unless (keys %tabs) { 391 if ($operation eq "select" && $S->{returns}) { 392 if ($args{flavor} && $args{flavor} eq "oracle") { 393 $tabs{dual} = "dual"; 394 } else { 395 $next_bit = " "; 396 } 397 } else { 398 die "no tables specified in $operation\n"; 399 } 400 } 401 $sql .= $next_bit; 402 my %seentab; 403 my $joins = ""; 404 for my $j ( @{$S->{joins}} ) { 405 my ($join, $tab1, $tab2, $condition) = @$j; 406 $condition = ( defined $condition) ? " on $condition" : ''; 407 die "not sure what to do with repeated tables ($tabs{$tab1} and $tabs{$tab2}) in a join\n" 408 if $seentab{$tab1} && $seentab{$tab2}; 409 if ($seentab{$tab2}) { 410 ($tab1, $tab2) = ($tab2, $tab1); 411 if ($join eq "left outer") { 412 $join = "right outer"; 413 } elsif ($join eq "right outer") { 414 $join = "left outer"; 415 } 416 } 417 if ($seentab{$tab1}) { 418 $joins .= " " if $joins; 419 $joins .= "$join join $tabs{$tab2}$condition"; 420 } else { 421 $joins .= ", " if $joins; 422 $joins .= "$tabs{$tab1} $join join $tabs{$tab2}$condition"; 423 } 424 $seentab{$tab1}++; 425 $seentab{$tab2}++; 426 } 427 my @joins = $joins ? ($joins) : (); 428 $sql .= join ", ", @joins, map { $tabs{$_} } grep { !$seentab{$_} } sort keys %tabs; 429 430 my @sets = grep { $_ ne "" } @{$S->{sets}}; 431 my @where = grep { $_ ne "" } @{$S->{where}}; 432 my @having = grep { $_ ne "" } @{$S->{having}}; 433 my @group_by = grep { $_ ne "" } @{$S->{group_by}}; 434 my @order_by = grep { $_ ne "" } @{$S->{order_by}}; 435 436 if ($S->{autogroup_needed} && !$S->{no_autogroup} && 437 !@group_by && @{$S->{autogroup_by}}) 438 { 439 @group_by = grep { $_ ne "" } @{$S->{autogroup_by}}; 440 } 441 die "nothing to update\n" if $operation eq "update" && !@sets; 442 443 $sql .= " set " . join ", ", @sets if @sets; 444 $sql .= " where " . join " and ", @where if @where; 445 $sql .= " group by " . join ", ", @group_by if @group_by; 446 $sql .= " having " . join " and ", @having if @having; 447 $sql .= " order by " . join ", ", @order_by if @order_by; 448 449 if ($dangerous && !@where && !$S->{seen_exec}) { 450 die "unfiltered $operation is dangerous: use exec if you want it\n"; 451 } 452 453 my $use_rownum = $args{flavor} && $args{flavor} eq "oracle"; 454 455 unless ($use_rownum) { 456 if ($S->{limit}) { 457 $sql .= " limit $S->{limit}"; 458 } 459 if ($S->{offset}) { 460 $sql .= " offset $S->{offset}"; 461 } 462 } 463 my $v = $S->{set_values}; 464 push @$v, @{$S->{ret_values}}; 465 push @$v, @{$S->{join_values}}; 466 push @$v, @{$S->{values}}; 467 468 for my $add (@{$S->{additions}}) { 469 $sql .= " $add->{type} $add->{sql}"; 470 push @$v, @{$add->{vals}}; 471 } 472 $sql =~ s/\s+$//; 473 474 if ( $use_rownum && ( $S->{limit} || $S->{offset} )) { 475 my @p; 476 push @p, "ROWNUM > " . $S->{offset} if $S->{offset}; 477 push @p, "ROWNUM <= " . ($S->{limit} + ($S->{offset} // 0)) if $S->{limit}; 478 $sql = "select * from ($sql) where " . join(' and ', @p); 479 } 480 481 return ($sql, $v, $nret, %flags); 482} 483 484 4851; 486__END__ 487 488=head1 NAME 489 490DBIx::Perlish - a perlish interface to SQL databases 491 492=head1 VERSION 493 494This document describes DBIx::Perlish version 1.00 495 496 497=head1 SYNOPSIS 498 499 use DBI; 500 use DBIx::Perlish; 501 502 my $dbh = DBI->connect(...); 503 504 # selects: 505 my @rows = db_fetch { 506 my $x : users; 507 defined $x->id; 508 $x->name !~ /\@/; 509 }; 510 511 # sub-queries: 512 my @rows = db_fetch { 513 my $x : users; 514 $x->id <- subselect { 515 my $t2 : table1; 516 $t2->col == 2 || $t2->col == 3; 517 return $t2->user_id; 518 }; 519 $x->name !~ /\@/; 520 }; 521 522 # updates: 523 db_update { 524 data->num < 100; 525 data->mutable; 526 527 data->num = data->num + 1; 528 data->name = "xyz"; 529 }; 530 531 # more updates: 532 db_update { 533 my $d : data; 534 $d->num < 100, $d->mutable; 535 536 $d = { 537 num => $d->num + 1, 538 name => "xyz" 539 }; 540 }; 541 542 # deletes: 543 db_delete { 544 my $t : table1; 545 !defined $t->age or 546 $t->age < 18; 547 }; 548 549 # inserts: 550 my $id = 42; 551 db_insert 'users', { 552 id => $id, 553 name => "moi", 554 }; 555 556 557=head1 DESCRIPTION 558 559The C<DBIx::Perlish> module provides the ability to work with databases 560supported by the C<DBI> module using Perl's own syntax for four most 561common operations: SELECT, UPDATE, DELETE, and INSERT. 562 563By using C<DBIx::Perlish>, you can write most of your database 564queries using a domain-specific language with Perl syntax. 565Since a Perl programmer knows Perl by definition, 566and might not know SQL to the same degree, this approach 567generally leads to a more comprehensible and maintainable 568code. 569 570The module is not intended to replace 100% of SQL used in your program. 571There is a hope, however, that it can be used to replace 572a substantial portion of it. 573 574The C<DBIx::Perlish> module quite intentionally neither implements 575nor cares about database administration tasks like schema design 576and management. The plain C<DBI> interface is quite sufficient for 577that. Similarly, and for the same reason, it does not take care of 578establishing database connections or handling transactions. All this 579is outside the scope of this module. 580 581 582=head2 Ideology 583 584There are three sensible and semi-sensible ways of arranging code that 585works with SQL databases in Perl: 586 587=over 588 589=item SQL sprinkling approach 590 591One puts queries wherever one needs to do something with the database, 592so bits and pieces of SQL are intermixed with the program logic. 593This approach can easily become an incomprehensible mess that is difficult 594to read and maintain. 595 596=item Clean and tidy approach 597 598Everything database-related is put into a separate module, or into a 599collection of modules. Wherever database access is required, 600a corresponding sub or method from such a module is called from the 601main program. Whenever something is needed that the DB module does 602not already provide, a new sub or method is added into it. 603 604=item Object-relational mapping 605 606One carefully designs the database schema and an associated collection 607of classes, then formulates the design in terms of any of the existing 608object-relational mapper modules like C<Class::DBI>, C<DBIx::Class> 609or C<Tangram>, then uses objects which perform all necessary queries 610under the hood. This approach is even cleaner than "clean and tidy" 611above, but it has other issues. Some schemas do not map well into 612the OO space. Typically, the resulting performance is an issue 613as well. The performance issues can in some cases be alleviated 614by adding hand-crafted SQL in strategic places, so in this regard 615the object-relational mapping approach can resemble the "clean and tidy" 616approach. 617 618=back 619 620The C<DBIx::Perlish> module is meant to eliminate the majority 621of the "SQL sprinkling" style of database interaction. 622It is also fully compatible with the "clean and tidy" method. 623 624=head2 Procedural interface 625 626=head3 db_fetch {} 627 628The C<db_fetch {}> function queries and returns data from 629the database. 630 631The function parses the supplied query sub, 632converts it into the corresponding SQL SELECT statement, 633and executes it. 634 635What it returns depends on two things: the context and the 636return statement in the query sub, if any. 637 638If there is a return statement which specifies exactly one 639column, and C<db_fetch {}> is called in the scalar context, 640a single scalar representing the requested column is returned 641for the first row of selected data. Example: 642 643 my $somename = db_fetch { return user->name }; 644 645Borrowing DBI's terminology, this is analogous to 646 647 my $somename = 648 $dbh->selectrow_array("select name from user"); 649 650If there is a return statement which specifies exactly one 651column, and C<db_fetch {}> is called in the list context, 652an array containing the specified column for all selected 653rows is returned. Example: 654 655 my @allnames = db_fetch { return user->name }; 656 657This is analogous to 658 659 my @allnames = 660 @{$dbh->selectcol_arrayref("select name from user")}; 661 662When there is no return statement, or if 663the return statement specifies multiple columns, 664then an individual row is represented by a hash 665reference with column names as the keys. 666 667In the scalar context, a single hashref is returned, which 668corresponds to the first row of selected data. Example: 669 670 my $h = db_fetch { my $u : user }; 671 print "name: $h->{name}, id: $h->{id}\n"; 672 673In DBI parlance that would look like 674 675 my $h = $dbh->selectrow_hashref("select * from user"); 676 print "name: $h->{name}, id: $h->{id}\n"; 677 678In the list context, an array of hashrefs is returned, 679one element for one row of selected data: 680 681 my @users = db_fetch { my $u : user }; 682 print "name: $_->{name}, id: $_->{id}\n" for @users; 683 684Again, borrowing from DBI, this is analogous to 685 686 my @users = @{$dbh->selectall_arrayref("select * from user", 687 {Slice=>{}})}; 688 print "name: $_->{name}, id: $_->{id}\n" for @users; 689 690There is also a way to specify that one or several of 691the return values are the B<key fields>, to obtain a behavior 692similar to that of the DBI's C<selectall_hashref()> function. 693A return value is a B<key field> if it is prepended with B<-k>: 694 695 my %data = db_fetch { 696 my $u : users; 697 return -k $u->name, $u; 698 }; 699 700This is somewhat analogous to 701 702 my %data = %{$dbh->selectall_hashref( 703 "select name, * from users", "name")}; 704 705If the C<db_fetch {}> containing key fields is called in the 706scalar context, it returns a hash reference instead of a hash. 707In both cases the complete result set is returned. 708 709This is different from calling the C<db_fetch {}> without key fields 710in the scalar context, which always returns a single row (or a single 711value), as explained above. 712 713The individual results in such a result set will be hash references 714if the return statement specifies more than one column (not counting 715the key fields), or a simple value if the return statement specifies 716exactly one column in addition to the key fields. For example, 717 718 my %data = db_fetch { 719 my $u : user; 720 return -k $u->id, $u; 721 }; 722 print "The name of the user with ID 42 is $data{42}{name}\n"; 723 724but: 725 726 my %data = db_fetch { 727 my $u : user; 728 return -k $u->id, $u->name; 729 }; 730 print "The name of the user with ID 42 is $data{42}\n"; 731 732In any case, the key fields themselves are never present in the result, 733unless they were specified in the return statement independently. 734 735The C<db_fetch {}> function will throw an exception if it is unable to 736find a valid database handle to use, or if it is unable to convert its 737query sub to SQL. 738 739In addition, if the database handle is configured to throw exceptions, 740the function might throw any of the exceptions thrown by DBI. 741 742L</Subqueries> are permitted in db_fetch's query subs. 743 744Please see L</Query sub syntax> below for details of the 745syntax allowed in query subs. 746 747The C<db_fetch {}> function is exported by default. 748 749=head3 db_select {} 750 751The C<db_select {}> function is an alias to the C<db_fetch {}>. 752It is exported by default. 753 754=head3 db_update {} 755 756The C<db_update {}> function updates rows of a database table. 757 758The function parses the supplied query sub, 759converts it into the corresponding SQL UPDATE statement, 760and executes it. 761 762The function returns whatever DBI's C<do> method returns. 763 764The function will throw an exception if it is unable to find 765a valid database handle to use, or if it is unable to convert 766its query sub to SQL. 767 768In addition, if the database handle is configured to throw exceptions, 769the function might throw any of the exceptions thrown by DBI. 770 771A query sub of the C<db_update {}> function must refer 772to precisely one table (not counting tables referred to 773by subqueries). 774 775Neither C<return> statements nor C<last> statements are 776allowed in the C<db_update {}> function's query subs. 777 778An attempt to call the C<db_update {}> function with 779no filtering expressions in the query sub will throw 780an exception since such is very likely a dangerous mistake. 781To allow such an update to proceed, include an C<exec> 782call with no parameters anywhere in the query sub. 783 784L</Subqueries> are permitted in db_update's query subs. 785 786Please see L</Query sub syntax> below for details of the 787syntax allowed in query subs. 788 789Examples: 790 791 db_update { 792 tbl->id == 41; 793 tbl->id = tbl->id - 1; 794 tbl->name = "luff"; 795 }; 796 797 db_update { 798 tbl->id = 42; 799 exec; # without this an exception is thrown 800 }; 801 802 db_update { 803 my $t : tbl; 804 $t->id == 40; 805 $t = { 806 id => $t->id + 2, 807 name => "LIFF", 808 }; 809 }; 810 811 db_update { 812 tbl->id == 40; 813 tbl() = { 814 id => tbl->id + 2, 815 name => "LIFF", 816 }; 817 }; 818 819The C<db_update {}> function is exported by default. 820 821 822=head3 db_delete {} 823 824The C<db_delete {}> function deletes data from 825the database. 826 827The C<db_delete {}> function parses the supplied query sub, 828converts it into the corresponding SQL DELETE statement, 829and executes it. 830 831The function returns whatever DBI's C<do> method returns. 832 833The function will throw an exception if it is unable to find 834a valid database handle to use, or if it is unable to convert 835its query sub to SQL. 836 837In addition, if the database handle is configured to throw exceptions, 838the function might throw any of the exceptions thrown by DBI. 839 840A query sub of the C<db_delete {}> function must refer 841to precisely one table (not counting tables referred to 842by subqueries). 843 844Neither C<return> statements nor C<last> statements are 845allowed in the C<db_delete {}> function's query subs. 846 847An attempt to call the C<db_delete {}> function with 848no filtering expressions in the query sub will throw 849an exception since such is very likely a dangerous mistake. 850To allow such a delete to proceed, include an C<exec> 851call with no parameters anywhere in the query sub. 852 853L</Subqueries> are permitted in db_delete's query subs. 854 855Please see L</Query sub syntax> below for details of the 856syntax allowed in query subs. 857 858Examples: 859 860 db_delete { $x : users; exec; } # delete all users 861 862 # delete with a subquery 863 db_delete { 864 my $u : users; 865 $u->name <- subselect { 866 visitors->origin eq "Uranus"; 867 return visitors->name; 868 } 869 } 870 871The C<db_delete {}> function is exported by default. 872 873 874=head3 db_insert() 875 876The C<db_insert()> function inserts rows into a 877database table. 878 879This function is different from the rest 880because it does not take a query sub as the parameter. 881 882Instead, it takes a table name as its first parameter, 883and any number of hash references afterwards. 884 885For each specified hashref, a new row is inserted 886into the specified table. The resulting insert statement 887specifies hashref keys as the column names, with corresponding 888values taken from hashref values. Example: 889 890 db_insert 'users', { id => 1, name => "the.user" }; 891 892A value can be a call to the exported C<sql()> function, 893in which case it is inserted verbatim into the generated 894SQL, for example: 895 896 db_insert 'users', { 897 id => sql("some_seq.nextval"), 898 name => "the.user" 899 }; 900 901The function returns the number of insert operations performed. 902If any of the DBI insert operations fail, the function returns 903undef, and does not perform remaining inserts. 904 905The function will throw an exception if it is unable to find 906a valid database handle to use. 907 908In addition, if the database handle is configured to throw exceptions, 909the function might throw any of the exceptions thrown by DBI. 910 911The C<db_insert {}> function is exported by default. 912 913=head3 subselect {} 914 915This call, formerly known as as internal form of C<db_fetch>, 916is basically an SQL SELECT statement. See L</Subqueries>. 917 918=head3 union() 919 920This is a helper sub which is meant to be used inside 921query subs. Please see L</Compound queries' statements> 922for details. The C<union()> can be exported via C<:all> 923import declaration. 924 925=head3 intersect() 926 927This is a helper sub which is meant to be used inside 928query subs. Please see L</Compound queries' statements> 929for details. The C<intersect()> can be exported via C<:all> 930import declaration. 931 932=head3 except() 933 934This is a helper sub which is meant to be used inside 935query subs. Please see L</Compound queries' statements> 936for details. The C<except()> can be exported via C<:all> 937import declaration. 938 939=head3 quirk() 940 941Unfortunately it is not always possible to generate an 942SQL statement which is valid for different DBI drivers, 943even when the C<DBIx::Perlish> module has the knowledge 944about what driver is in use. 945 946The C<quirk()> sub exists to alleviate this problem in 947certain situations by registering "quirks". 948Please avoid using it if possible. 949 950It accepts at least two positional parameters. The 951first parameter is the DBI driver flavor. 952The second parameter identifies a particular quirk. 953The rest of parameters are quirk-dependent. 954 955It is a fatal error to attempt to register a quirk that 956is not recognized by the module. 957 958Currently only Oracle has any quirks, which are listed 959below: 960 961=over 962 963=item table_func_cast 964 965When table functions are used in Oracle, one sometimes 966gets an error 967"ORA-22905: cannot access rows from a non-nested table item". 968The solution recommended by Oracle is to do an explicit type 969cast to a correct type. Since the C<DBIx::Perlish> module 970has no way of knowing what the correct type is, it needs 971a little help. The C<table_func_cast> quirk requires two extra 972parameters, the name of a table function and the type to cast 973it to. 974 975=back 976 977 978=head3 $SQL and @BIND_VALUES 979 980The C<DBIx::Perlish> module provides two global variables 981(not exported) to aid in debugging. 982The C<$DBIx::Perlish::SQL> variable contains the text of 983the SQL which was generated during the most recent 984invocation of one of C<db_fetch {}>, C<db_update {}>, 985or C<db_delete {}>. 986The C<@DBIx::Perlish::BIND_VALUES> array contains the bind values 987to be used with the corresponding SQL code. 988 989 990=head2 Query sub syntax 991 992The important thing to remember is that although the query subs have Perl 993syntax, they do B<not> represent Perl, but a specialized "domain specific" 994database query language with Perl syntax. 995 996A query sub can consist of the following types of statements: 997 998=over 999 1000=item * 1001 1002table variables declarations; 1003 1004=item * 1005 1006query filter statements; 1007 1008=item * 1009 1010return statements; 1011 1012=item * 1013 1014assignments; 1015 1016=item * 1017 1018result limiting and ordering statements; 1019 1020=item * 1021 1022conditional statements; 1023 1024=item * 1025 1026statements with label syntax; 1027 1028=item * 1029 1030compound queries' statements. 1031 1032=back 1033 1034The order of the statements is generally not important, 1035except that table variables have to be declared before use. 1036 1037=head3 Table variables declarations 1038 1039Table variables declarations allow one to associate 1040lexical variables with database tables. They look 1041like this: 1042 1043 my $var : tablename; 1044 1045It is possible to associate several variables with the 1046same table; this is the preferable mechanism if self-joins 1047are desired. 1048 1049In case the table name is not known until runtime, it is also 1050possible to write for example 1051 1052 my $var : table = $data->{tablename}; 1053 1054In this case the attribute "table" must be specified verbatim, 1055and the name of the table is taken from the right-hand side of the 1056assignment. 1057 1058Database schemas ("schemaname.tablename") are supported in 1059several different ways: 1060 1061=over 1062 1063=item Using the runtime mechanism described above: 1064 1065 my $tabnam = "schemaname.tablename"; 1066 db_fetch { 1067 my $t : table = $tabnam; 1068 }; 1069 1070=item Using a similar verbatim "table" attribute with a string constant: 1071 1072 my $t : table = "schemaname.tablename"; 1073 1074=item Using attribute argument with the verbatim "table" attribute: 1075 1076 my $t : table(schemaname.tablename); 1077 1078=item Using schema name as the attribute and table name as its argument: 1079 1080 my $t : schemaname(tablename); 1081 1082=back 1083 1084Last, but not least, a combination of verbatim "table" attribute 1085with a nested L</subselect {}> can be used to implement I<inline views>: 1086 1087 my $var : table = subselect { ... }; 1088 1089In this case a B<select> statement corresponding to 1090the nested L</subselect {}> will represent the table. 1091Please note that not all database drivers support 1092this, although at present the C<DBIx::Perlish> module 1093does not care and will generate SQL which will subsequently 1094fail to execute. 1095 1096Another possibility for declaring table variables is 1097described in L</Statements with label syntax>. 1098 1099Please note that L</db_update {}> and L</db_delete {}> must 1100only refer to a single table. 1101 1102=head3 Query filter statements 1103 1104Query filter statements have a general form of Perl expressions. 1105Binary comparison operators, logical "or" (both high and lower 1106precedence form), matching operators =~ and !~, binary arithmetic 1107operators, string concatenation, defined(expr), 1108and unary ! are all valid in the filters. 1109There is also a special back-arrow, "comes from" C<E<lt>-> binary 1110operator used for matching a column to a set of values, and for 1111subqueries. 1112 1113Individual terms can refer to a table column using dereferencing 1114syntax 1115(one of C<tablename-E<gt>column>, 1116C<$tablevar-E<gt>column>, 1117C<tablename-E<gt>$varcolumn>, or 1118C<$tablevar-E<gt>$varcolumn>), 1119to an integer, floating point, or string constant, to a function 1120call, to C<next> statement with an argument, 1121or to a scalar value in the outer scope (simple scalars, 1122hash elements, or dereferenced hashref elements chained to 1123an arbitrary depth are supported). 1124 1125Inside constant strings, table column specifiers are interpolated; 1126the result of such interpolation is represented as a sequence 1127of explicit SQL concatenation operations. 1128The variable interpolation syntax is somewhat different from 1129normal Perl rules, which does not interpolate method calls. 1130So it is perfectly legal to write 1131 1132 return "abc $t->name xyz"; 1133 1134When it is impossible to distinguish between the column name 1135and the following characters, the hash element syntax must be 1136used instead: 1137 1138 return "abc$t->{name}xyz"; 1139 1140Of course, one may want to avoid the trouble altogether and use explicit Perl 1141concatenation in such cases: 1142 1143 return "abc" . $t->name . "xyz"; 1144 1145Please note that specifying column names as hash elements 1146is I<only> valid inside interpolated strings; this may change 1147in the future versions of the module. 1148 1149Please also note that column specifiers of 1150C<tablename-E<gt>column> form cannot be embedded into strings; 1151again, use explicit Perl concatenation in such cases. 1152 1153Function calls can take an arbitrary number of arguments. 1154Each argument to a function must currently be a term, 1155although it is expected that more general expressions will 1156be supported in the future. 1157The function call appear verbatim in the resulting SQL, 1158with the arguments translated from Perl syntax to SQL 1159syntax. For example: 1160 1161 lower($t1->name) eq lower($t2->lastname); 1162 1163Some of the functions are handled specially: 1164 1165=over 1166 1167=item C<lc> and C<uc> 1168 1169The Perl builtins C<lc> and C<uc> are translated into C<lower> and 1170C<upper>, respectively. 1171 1172=item C<extract> 1173 1174A two-argument form of the C<extract> function, where the first 1175argument is a constant string, will be converted into the form 1176understood by the SQL standard. For example, 1177 1178 extract(day => $t->field) 1179 1180will be converted into something like 1181 1182 EXTRACT(DAY FROM t01.field) 1183 1184as is required. 1185 1186=back 1187 1188Another special case is when C<sql()> function (with a single 1189parameter) is called. In this case the parameter of the 1190function call inserted verbatim into the generated SQL, 1191for example: 1192 1193 db_update { 1194 tab->state eq "new"; 1195 tab->id = sql "some_seq.nextval"; 1196 }; 1197 1198There is also a shortcut when one can use backquotes for 1199verbatim SQL pieces: 1200 1201 db_update { 1202 tab->state eq "new"; 1203 tab->id = `some_seq.nextval`; 1204 }; 1205 1206A C<next> statement with a (label) argument is interpreted as 1207an operator of getting the next value out of a sequence, 1208where the label name is the name of the sequence. 1209Syntax specific to the DBI driver will be used to represent 1210this operation. It is a fatal error to use such a statement 1211with DBI drivers which do not support sequences. For example, 1212the following is exactly equivalent to the example above, 1213except it is more portable: 1214 1215 db_update { 1216 tab->state eq "new"; 1217 tab->id = next some_seq; 1218 }; 1219 1220The "comes from" C<E<lt>-> binary operator can be used in the 1221following manner: 1222 1223 my @ary = (1,2,3); 1224 db_fetch { 1225 tab->id <- @ary; 1226 }; 1227 1228This is equivalent to SQL's C<IN I<list>> operator, where 1229the list comes from the C<@ary> array. An array reference 1230or an anonymous array can also be used in place of the C<@ary> 1231here. 1232 1233The C<E<lt>-> operator can also be used with L</Subqueries>, 1234below. 1235 1236 1237=head3 Return statements 1238 1239Return statements determine which columns are returned by 1240a query under what names. 1241Each element in the return statement can be either 1242a reference to the whole table, an expression involving 1243table columns, or a string constant, 1244in which case it is taken as an alias to 1245the next element in the return statement: 1246 1247 return ($table->col1, anothername => $table->col2); 1248 1249If an element is a reference to the whole table, 1250it is understood that all columns from this table 1251are returned: 1252 1253 return ($t1->col1, $t1->col2, $t2); 1254 1255Table references cannot be aliased by a name. 1256 1257One can also specify a "distinct" or "DISTINCT" 1258string constant in the beginning of the return list, 1259in which case duplicated rows will be eliminated 1260from the result set. 1261 1262It is also permissible to use a C<next> operator with a label 1263argument (see above) in return statements: 1264 1265 return next some_seq; 1266 1267Return statements are only valid in L</db_fetch {}>. 1268 1269Query subs representing subqueries using the reverse 1270arrow notation must have exactly one return statement 1271returning exactly one column (see L</Subqueries> below). 1272 1273 1274=head3 Assignments 1275 1276Assignments can take two form: individual column assignments 1277or bulk assignments. The former must have a reference to 1278a table column on the left-hand side, and an expression 1279like those accepted in filter statements on the right-hand 1280side: 1281 1282 table1->id = 42; 1283 $t->column = $t->column + 1; 1284 1285The bulk assignments must have a table specifier on the left-hand 1286side, and a hash reference on the right-hand side. 1287The keys of the hash represent column names, and the values 1288are expressions like those in the individual column 1289assignments: 1290 1291 $t = { 1292 id => 42, 1293 column => $t->column + 1 1294 }; 1295 1296or 1297 1298 tablename() = { 1299 id => 42, 1300 column => tablename->column + 1 1301 }; 1302 1303Please note a certain ugliness in C<tablename()> in the last example, 1304so it is probably better to either use table vars, or stick to the 1305single assignment syntax of the first example. 1306 1307It is possible to intermix hashes and hashrefs dereferencings with 1308verbatim key/value pairs in bulk assignments: 1309 1310 $t = { 1311 id => 42, 1312 column => $t->column + 1, 1313 %$hashref_from_outer_scope 1314 }; 1315 1316Please note that the right hand side of the bulk assignment must 1317be an anonymouse hash reference. Thus, the following is invalid: 1318 1319 $t = $hashref_from_outer_scope; 1320 1321Instead, write 1322 1323 $t = {%$hashref_from_outer_scope}; 1324 1325The latter emphasizes the fact that this is the bulk assignment, which 1326is not clear from the former statement. 1327 1328Assignment statements are only valid in L</db_update {}>. 1329 1330=head3 Result limiting and ordering statements 1331 1332The C<last> command can be used to limit the number of 1333results returned by a fetch operation. 1334 1335If it stands on its own anywhere in the query sub, it means "stop 1336after finding the first row that matches other filters", so it 1337is analogous to C<LIMIT 1> in many SQL dialects. 1338 1339It can also be used in conjunction with a range C<..> operator, 1340so that 1341 1342 last unless 5..20; 1343 1344is equivalent to 1345 1346 OFFSET 5 LIMIT 16 1347 1348 1349The C<sort> builtin can be used to specify the desired order 1350of the results: 1351 1352 sort $t->col1, $t->col2; 1353 1354is equivalent to 1355 1356 ORDER BY col1, col2 1357 1358In order to support the ordering direction, the sort expressions 1359can be preceded by a literal string which 1360must satisfy the pattern /^(asc)/i (for ascending order, 1361which is the default), or /^(desc)/i for descending order: 1362 1363 sort desc => $t->col1, asc => $t->col2; 1364 1365is equivalent to 1366 1367 ORDER BY col1 DESC, col2 1368 1369Result limiting and ordering statements are only valid in L</db_fetch {}>. 1370 1371 1372=head3 Conditional statements 1373 1374There is a limited support for parse-time conditional expressions. 1375 1376At the query sub parsing stage, if the conditional does not mention 1377any tables or columns, and refers exclusively to the values from the 1378outer scope, it is evaluated, and the corresponding filter (or any other 1379kind of statement) is only put into the generated SQL if the condition 1380is true. 1381 1382For example, 1383 1384 my $type = "ICBM"; 1385 db_fetch { 1386 my $p : products; 1387 $p->type eq $type if $type; 1388 }; 1389 1390will generate the equivalent to C<select * from products where type = 'ICBM'>, 1391while the same code would generate just C<select * from products> if C<$type> 1392were false. 1393 1394The same code could be written with a real C<if> statement as well: 1395 1396 my $type = "ICBM"; 1397 db_fetch { 1398 my $p : products; 1399 if ($type) { 1400 $p->type eq $type; 1401 } 1402 }; 1403 1404Similarly, 1405 1406 my $want_z = 1; 1407 db_fetch { 1408 my $p : products; 1409 return $p->x, $p->y unless $want_z; 1410 return $p->x, $p->y, $p->z if $want_z; 1411 }; 1412 1413will generate the equivalent of C<select x, y from products> when 1414C<$want_z> is false, and C<select x, y, z from products> when 1415C<$want_z> is true. 1416 1417 1418=head3 Statements with label syntax 1419 1420There is a number of special labels which query sub syntax allows. 1421 1422Specifying label C<distinct:> anywhere in the query sub leads to duplicated 1423rows being eliminated from the result set. 1424 1425Specifying label C<limit:> followed by a number (or a scalar variable 1426representing a number) limits the number of rows returned by the query. 1427 1428Specifying label C<offset:> followed by a number N (or a scalar variable 1429representing a number N) skips first N rows from the returned result 1430set. 1431 1432Specifying label C<order:>, C<orderby:>, C<order_by:>, 1433C<sort:>, C<sortby:>, or C<sort_by:>, followed by a list of 1434expressions will sort the result set according to the expressions. 1435For details about the sorting criteria see the documentation 1436for C<ORDER BY> clause in your SQL dialect reference manual. 1437Before a sorting expression in a list one may specify one of the 1438string constants "asc", "ascending", "desc", "descending" to 1439alter the sorting order, or even generic direction and column, for example: 1440 1441 db_fetch { 1442 my $t : tbl; 1443 order_by: asc => $t->name, desc => $t->age, $direction, $column; 1444 }; 1445 1446Specifying label C<group:>, C<groupby:>, or C<group_by:>, 1447followed by a list of column specifiers is equivalent to 1448the SQL clause C<GROUP BY col1, col2, ...>. 1449 1450The module implements an I<experimental> feature which 1451in some cases allows one to omit the explicit 1452C<group_by:> label. If there is an explicit C<return> statement 1453which mentions an aggregate function alongside "normal" 1454column specifiers, and that return statement does not 1455reference the whole table, and the explicit C<group_by:> label 1456is not present in the query, the 1457C<DBIx::Perlish> module will generate one automatically. 1458For example, the following query: 1459 1460 db_fetch { 1461 my $t : tab; 1462 return $t->name, $t->type, count($t->age); 1463 }; 1464 1465will execute the equivalent of the following SQL statement: 1466 1467 select name, type, count(age) from tab group by name, type 1468 1469The C<avg()>, C<count()>, C<max()>, C<min()>, and C<sum()> 1470functions are considered to be aggregate. 1471 1472Similarly, using an aggregate function in a filtering expression 1473will lead to automatic introduction of a HAVING clause: 1474 1475 db_fetch { 1476 my $w : weather; 1477 max($w->temp_lo) < 40; 1478 return $w->city; 1479 }; 1480 1481will translate into an equivalent of 1482 1483 select city from weather group by city having max(temp_lo) < 40 1484 1485Specifying label C<table:> followed by a lexical variable 1486declaration, followed by an assignment introduces an alternative 1487table declaration syntax. The value of the expression on the right 1488hand side of the assignment is taken to be the name of the table: 1489 1490 my $data = { table => "mytable" }; 1491 db_fetch { 1492 table: my $t = $data->{table}; 1493 }; 1494 1495This is useful if you don't know the names of your table until 1496runtime. 1497 1498All special labels are case insensitive. 1499 1500Special labels are only valid in L</db_fetch {}>. 1501 1502 1503=head3 Compound queries' statements 1504 1505The SQL compound queries UNION, INTERSECT, and EXCEPT are supported 1506using the following syntax: 1507 1508 db_fetch { 1509 { 1510 ... normal query statements ... 1511 } 1512 compound-query-keyword 1513 { 1514 ... normal query statements ... 1515 } 1516 }; 1517 1518Here I<compound-query-keyword> is one of C<union>, 1519C<intersect>, or C<except>. 1520 1521This feature will only work if the C<use> statement for 1522the C<DBIx::Perlish> module was written with C<:all> 1523export declaration, since C<union>, C<intersect>, and C<except> 1524are subs that are not exported by default by the module. 1525 1526It is the responsibility of the programmer to make sure 1527that results of the individual queries used in a compound 1528query are compatible with each other. 1529 1530 1531=head3 Subqueries 1532 1533It is possible to use subqueries in L</db_fetch {}>, L</db_update {}>, 1534and L</db_delete {}>. 1535 1536There are two variants of subqueries. The first one is a 1537call, as a complete statement, 1538to L</db_fetch {}> anywhere in the body of the query sub. 1539This variant corresponds to the C<EXISTS (SELECT ...)> SQL 1540construct, for example: 1541 1542 db_delete { 1543 my $t : table1; 1544 subselect { 1545 $t->id == table2->table1_id; 1546 }; 1547 }; 1548 1549Another variant corresponds to the C<column IN (SELECT ...)> SQL 1550construct. It uses a special syntax with back-arrow C<E<lt>-> 1551(read it as "comes from"), 1552which signifies that the column specifier on the left gets 1553its values from whatever is returned by a L</db_fetch {}> on 1554the right: 1555 1556 db_delete { 1557 my $t : table1; 1558 $t->id <- subselect { 1559 return table2->table1_id; 1560 }; 1561 }; 1562 1563This variant puts a limitation on the return statement in the sub-query 1564query sub. Namely, it must contain a return statement with exactly one 1565return value. 1566 1567If the right-hand side of the "comes from" operator is a function call, 1568the function is assumed to be a function potentially returning a set 1569of values, or a "table function", in Oracle terminology. 1570Such construct is converted into a driver-dependent subselect involving 1571the table function: 1572 1573 db_fetch { 1574 tbl->id <- tablefunc($id); 1575 }; 1576 1577Where result of a subquery comes from a function, the following syntax can be 1578also used: 1579 1580 db_fetch { 1581 my $t : table = tablefunc($id); 1582 return $t; 1583 }; 1584 1585This allows for SQL syntax like 1586 1587 SELECT t.* FROM tablefunc(?) t, other_table 1588 1589where joins of subselects are not enough. 1590 1591=head3 Joins 1592 1593Joins are implemented similar to subqueries, using embedded C<db_fetch> call to 1594specify a join condition. The join syntax is one of (the last two are 1595equivalent): 1596 1597 join $t1 BINARY_OP $t2; 1598 join $t1 BINARY_OP $t2 => subselect { CONDITION }; 1599 join $t1 BINARY_OP $t2 <= subselect { CONDITION }; 1600 1601where CONDITION is an arbitrary expression using fields from C<$t1> and C<$t2> 1602, and BINARY_OP is one of C<*>,C<+>,C<x>,C<&>,C<|>,C<< < >>,C<< > >> operators, 1603which correspond to the following standard join types: 1604 1605=over 1606 1607=item Inner join 1608 1609This corresponds to either of C<*>, C<&>, and C<x> operators. 1610The C<subselect {}> condition for inner join may be omitted, 1611in which case it degenerates into a I<cross join>. 1612 1613=item Full outer join 1614 1615It is specified with C<+> or C<|>. 1616The C<DBIx::Perlish> module does not care 1617that some database engines do not support full outer join, 1618nor does it try to work around this limitation. 1619 1620=item Left outer join 1621 1622C<< < >> 1623 1624=item Right outer join 1625 1626C<< > >> 1627 1628=back 1629 1630Example: 1631 1632 my $x : x; 1633 my $y : y; 1634 join $y * $x => subselect { $y-> id == $x-> id }; 1635 1636=head2 Object-oriented interface 1637 1638=head3 new() 1639 1640Constructs and returns a new DBIx::Perlish object. 1641 1642Takes named parameter. 1643 1644One parameter, C<dbh>, is required and 1645must be a valid DBI database handler. 1646 1647Another parameter which the C<new()> understands is C<quirks>, 1648which, if present, must be a reference to an array of anonymous 1649arrays, each corresponding to a single call to C<quirk()>. 1650Please see C<quirk()> for details. 1651 1652Can throw an exception if the supplied parameters 1653are incorrect. 1654 1655=head3 fetch() 1656 1657An object-oriented version of L</db_fetch {}>. 1658 1659=head3 update() 1660 1661An object-oriented version of L</db_update {}>. 1662 1663=head3 delete() 1664 1665An object-oriented version of L</db_delete {}>. 1666 1667=head3 insert() 1668 1669An object-oriented version of L</db_insert()>. 1670 1671Returns the SQL string, most recently generated by database 1672queries performed by the object. 1673Returns undef if there were no queries made thus far. 1674 1675Example: 1676 1677 $db->query(sub { $u : users }); 1678 print $db->sql, "\n"; 1679 1680=head3 query($sub) 1681 1682Returns converts C<$sub> into SQL text. 1683Useful for debugging and passing down prepared queries 1684 1685=head3 sql() 1686 1687Serves the purpose of injecting verbatim pieces of SQL into query subs (see 1688L</Query filter statements>) or into the values to be inserted via 1689L</db_insert()>. 1690 1691The C<sql()> function is exported by default. 1692 1693=head3 bind_values() 1694 1695Takes no parameters. 1696Returns an array of bind values that were used in the most recent 1697database query performed by the object. 1698Returns an empty array if there were not queries made thus far. 1699 1700Example: 1701 1702 $db->query(sub { users->name eq "john" }); 1703 print join(", ", $db->bind_values), "\n"; 1704 1705=head3 quirk() 1706 1707An object-oriented version of L</quirk()>. 1708 1709=head3 optree_version 1710 1711Returns 1 if perl version is prior 5.22, where there are no optimizations on the optree. 1712Returns 2 otherwise, when perl introduced changes to optree, that caused certain uncompatibilities. 1713See more in C<BACKWARD COMPATIBILITY> 1714 1715=head2 Working with multiple database handles 1716 1717There are several ways in which the C<DBIx::Perlish> module can be used 1718with several different database handles within the same program: 1719 1720=over 1721 1722=item Using object-oriented interface 1723 1724The advantage of this approach is that there is no confusion 1725about which database handle is in use, since a DBIx::Perlish object 1726is always created with an explicit database handle as a parameter 1727to L</new()>. 1728 1729The obvious disadvantage is that one has to explicitly use "sub" 1730when specifying a query sub, so the syntax is unwieldy. 1731 1732=item Using special import syntax 1733 1734It is possible to import differently named specialized versions 1735of the subs 1736normally exported by the C<DBIx::Perlish> module, which will 1737use specified database handle. The syntax is as follows: 1738 1739 use DBIx::Perlish; 1740 my $dbh = DBI->connect(...); 1741 1742 my $foo_dbh = DBI->connect(...); 1743 use DBIx::Perlish prefix => "foo", dbh => \$foo_dbh; 1744 1745 my $bar_dbh = DBI->connect(...); 1746 use DBIx::Perlish prefix => "bar", dbh => \$bar_dbh; 1747 1748 my @default = db_fetch { ... }; 1749 my @foo = foo_fetch { ... }; 1750 my @bar = bar_fetch { ... }; 1751 1752The syntax and semantics of such specialized versions is exactly 1753the same as with the normal L</db_fetch {}>, L</db_select {}>, 1754L</db_update {}>, L</db_delete {}>, and L</db_insert()>, 1755except that they use the database handle specified in the C<use> 1756statement for all operations. As can be seen from the example above, 1757the normal versions still work as intended, employing the usual mechanisms 1758for determining which handle to use. 1759 1760=back 1761 1762 1763=head2 Database driver specifics 1764 1765The generated SQL output can differ depending on 1766the particular database driver in use. 1767 1768=head3 MySQL 1769 1770Native MySQL regular expressions are used if possible and if 1771a simple C<LIKE> won't suffice. 1772 1773=head3 Oracle 1774 1775The function call C<sysdate()> is transformed into C<sysdate> 1776(without parentheses). 1777 1778Selects without table specification are assumed to be 1779selects from DUAL, for example: 1780 1781 my $newval = db_fetch { return `tab_id_seq.nextval` }; 1782 1783Table functions in Oracle are handled specially. 1784 1785There are quirks (see L</quirk()>) that can be registered 1786for Oracle driver. 1787 1788=head3 Postgresql 1789 1790Native Postgresql regular expressions are used if possible and if 1791a simple C<LIKE> won't suffice. 1792 1793The same applies to PgLite, which is a Postgresql-like wrapper around 1794SQLite. In this case, "native" PgLite regular expressions are actually 1795native Perl regular expressions, but the C<DBIx::Perlish> module 1796pretends it does not know about it. 1797 1798=head3 SQLite 1799 1800Native Perl regular expressions are used with SQLite even for 1801simple match cases, since SQLite does not know how to optimize 1802C<LIKE> applied to an indexed column with a constant prefix. 1803 1804=head2 Implementation details and more ideology 1805 1806To achieve its purpose, this module uses neither operator 1807overloading nor source filters. 1808 1809The operator overloading would only work if individual tables were 1810represented by Perl objects. This means that an object-relational 1811mapper like C<Tangram> can do it, but C<DBIx::Perlish> cannot. 1812 1813The source filters are limited in other ways: the modules using them 1814are often incompatible with other modules that also use source filtering, 1815and it is B<very> difficult to do source filtering when any degree of 1816flexibility is required. Only perl can parse Perl! 1817 1818The C<DBIx::Perlish> module, on the other hand, leverages perl's ability 1819to parse Perl and operates directly on the already compiled Perl code. 1820In other words, it parses the Perl op tree (syntax tree). 1821 1822The idea of this module came from Erlang. Erlang has a so called 1823I<list comprehension syntax>, which allows one to generate lists 1824using I<generator> expressions and to select the list elements using 1825I<filter> expressions. Furthermore, the authors of the Erlang database, 1826Mnesia, hijacked this syntax for the purpose of doing database queries 1827via a mechanism called I<parse transform>. 1828The end result was that the database queries in Erlang are expressed 1829by using Erlang's own syntax. 1830 1831I found this approach elegant, and thought "why something like this 1832cannot be done in Perl"? 1833 1834 1835=head1 CONFIGURATION AND ENVIRONMENT 1836 1837DBIx::Perlish requires no configuration files or environment variables. 1838 1839=head2 Running under L<Devel::Cover> 1840 1841When the C<DBIx::Perlish> module detects that the current program 1842is being run under L<Devel::Cover>, 1843it tries to cheat a little bit and feeds L<Devel::Cover> 1844with I<false> information to make those 1845query subs which were parsed by the module 1846to appear "covered". 1847 1848This is done because the query subs are B<never> executed, 1849and thus would normally be presented as "not covered" by 1850the L<Devel::Cover> reporter. 1851Although a developer has no trouble deciding to ignore 1852such "red islands", he has to perform this decision every 1853time he looks at the coverage data, which tends to become 1854annoying rather quickly. 1855 1856Currently, only statement and sub execution data are faked. 1857 1858=head1 DEPENDENCIES 1859 1860The C<DBIx::Perlish> module needs at least perl 5.14. 1861 1862This module requires C<DBI> to do anything useful. 1863 1864In order to support the special handling of the C<$dbh> variable, 1865C<Keyword::Pluggable> needs to be installed. C<Devel::Caller> is 1866needed for some magic, and C<Pod::Markdown> is a developer dependency 1867for auto-generating README.md. 1868 1869Other modules used used by C<DBIx::Perlish> are included 1870into the standard Perl distribution. 1871 1872=head1 INCOMPATIBILITIES 1873 1874Starting with version 0.54 the handling of key fields 1875(return -k $t->field) has incompatibly changed. 1876The previous behavior was to always return individual 1877results as hash references, even when only one 1878column (not counting the key fields) was specified 1879in the return statement. The current behavior is 1880to return simple values in this case. 1881 1882If you use C<DBIx::Perlish> together with L<HTML::Mason>, 1883you are likely to see warnings "Useless use of ... in void context" 1884that Mason helpfully converts into fatal errors. 1885 1886To fix this, edit your C<handler.pl> and add the following line: 1887 1888 $ah->interp->ignore_warnings_expr("(?i-xsm:Subroutine .* redefined|Useless use of .+ in void context)"); 1889 1890Here C<$ah> must refer to an instance of C<HTML::Mason::ApacheHandler> 1891class. 1892 1893Mason is to blame for this, since it disregards 1894warnings' handlers installed by other modules. 1895 1896=head1 BACKWARD COMPATIBILITY 1897 1898Perl 5.22 introduced certain changes to the way optree is constructed. 1899Some of these cannot be adequately treated, because whole constructs might be 1900simply optimized away before even they hit the parser (example: C<join(1,2)> gets translated into constant C<2>). 1901 1902Known cases are not documented so far, but look in the tests for I<optree_version> invocations 1903to see where these are found. 1904 1905=head1 BUGS AND LIMITATIONS 1906 1907No bugs have been reported. 1908 1909Please report any bugs or feature requests to 1910C<bug-dbix-perlish@rt.cpan.org>, or through the web interface at 1911L<http://rt.cpan.org>. 1912 1913A number of features found in many SQL dialects is not supported. 1914 1915The module cannot handle more than 100 tables in a single 1916query sub. 1917 1918Although variables closed over the query sub can be used 1919in it, only simple scalars, hash elements, and dereferenced 1920hasref elements are understood at the moment. 1921 1922If you would like to see something implemented, 1923or find a nice Perlish syntax for some SQL feature, 1924please let me know! 1925 1926=head1 AUTHOR 1927 1928Anton Berezin C<< <tobez@tobez.org> >> 1929 1930=head1 ACKNOWLEDGEMENTS 1931 1932Special thanks to Dmitry Karasik, 1933who contributed code and syntax ideas on several occasions, 1934and with whom I spent considerable time discussing 1935this module. 1936 1937I would also like to thank 1938Henrik Andersen, 1939Mathieu Arnold, 1940Phil Regnauld, 1941and Lars Thegler, 1942for discussions, suggestions, bug reports and code contributions. 1943 1944This work is in part sponsored by Telia Denmark. 1945 1946 1947=head1 SUPPORT 1948 1949There is also the project website at 1950 http://dbix-perlish.tobez.org/ 1951 1952 1953=head1 LICENSE AND COPYRIGHT 1954 1955Copyright (c) 2007-2013, Anton Berezin C<< <tobez@tobez.org> >>. All rights reserved. 1956 1957Redistribution and use in source and binary forms, with or without 1958modification, are permitted provided that the following conditions 1959are met: 1960 19611. Redistributions of source code must retain the above copyright 1962 notice, this list of conditions and the following disclaimer. 1963 19642. Redistributions in binary form must reproduce the above copyright 1965 notice, this list of conditions and the following disclaimer in the 1966 documentation and/or other materials provided with the distribution. 1967 1968THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND 1969ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 1970IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 1971ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE 1972FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 1973DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 1974OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 1975HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 1976LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 1977OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 1978SUCH DAMAGE. 1979