On Sat, Jan 10, 2004 at 10:27:44PM +0000, Tim Bunce wrote:
> On Fri, Jan 09, 2004 at 01:07:18PM -0600, Daniel S. Lewart wrote:
> > DBI Developers,
> > 
> > > Speak before you patch
> > 
> > I would like to extend DBI's fetchall_hashref and selectall_hashref
> > methods to handle multiple keys.  Being new to DBI, I miss Michael Peppler's
> > Sybperl::Simple's useful HashOfHashOfHash method.  The following are
> > my proposed new syntaxes:
> > 
> >   $sth->fetchall_hashref(@key_field);
> >   $dbh->selectall_hashref($statement, [EMAIL PROTECTED] [, \%attr[, 
> > @bind_values]]);
> 
> I'd accept a patch that allows the $key_field parameter of fetchall_hashref()
> (and thus selectall_hashref) to be either a string, as now, or an array ref.
> 
> The patch should:
>   - only affect fetchall_hashref()
>   - do my @key_fields = (ref $key_field) ? @$key_field : ($key_field);
>   - work for _any_ number of elements in key_fields

Just to fill that requirement out some more... here's some untested code
that I think will get you most of the way there:

        my $hash_key_name = $sth->{FetchHashKeyName} || 'NAME';
        my $names_hash = $sth->FETCH("${hash_key_name}_hash");

        my @key_fields = (ref $key_field) ? @$key_field : ($key_field);
        my @key_values;
        foreach (@key_fields) {

            my $index = $names_hash->{$_};  # perl index not column 
            ++$index if defined $index;     # convert to column number
            $index ||= $key_field if DBI::looks_like_number($key_field) && 
$key_field>=1;

            push @key_values, undef;
            $sth->bind_col($index, \$key_value[-1]) or return;
        }

        my $rows = {};
        my $NAME = $sth->{$hash_key_name};
        while (my $row = $sth->fetchrow_arrayref($hash_key_name)) {
            my $ref = $rows;
            $ref = $ref->{$_} ||= {} for @key_values;
            @[EMAIL PROTECTED] = @$row;
        }
        return \%rows;

Tim.

Reply via email to