files/perl/DBIx-FetchAll.pm

Plain text | Download

  1. package DBIx::FetchAll;
  2.  
  3. =head1 NAME
  4.  
  5. DBIx::FetchAll - provides sugar for DBI $sth
  6.  
  7. =cut
  8.  
  9. use warnings;
  10. use strict;
  11.  
  12. =head1 METHODS
  13.  
  14. =head2 fetchall_hash
  15.  
  16.  %table     = $sth->fetchall_hash;
  17.  $table_ref = $sth->fetchall_hash;
  18.  
  19. C<%table> looks like this:
  20.  
  21.  (
  22.    colA => [ $row1_colA, $row2_colA, ... ],
  23.    colB => [ $row1_colB, $row2_colB, ... ],
  24.    colC => [ $row1_colC, $row2_colC, ... ],
  25.    ...
  26.  )
  27.  
  28. =cut
  29.  
  30. sub DBI::st::fetchall_hash {
  31.     my $sth   = shift;
  32.     my @cols  = @{$sth->{'NAME'}};
  33.     my %table = map { $_ => [] } @cols;
  34.     
  35.     while(my @row = $sth->fetchrow_array) {
  36.         push @{$table{$_}}, shift @row for(@cols);
  37.     }
  38.     
  39.     wantarray ? %table : \%table;
  40. }
  41.  
  42. =head1 AUTHOR
  43.  
  44. Jan Henning Thorsen
  45.  
  46. =cut
  47.  
  48. 1;