[Dbix-class] get_columns and overloaded column accessors

Peter Rabbitson rabbit+dbic at rabbit.us
Wed Oct 20 12:57:38 GMT 2010


Francesc Romà i Frigolé wrote:
> Hello,
> 
> I'm using overloaded column accessors as described in the Cookbok 
> <http://search.cpan.org/%7Efrew/DBIx-Class-0.08123/lib/DBIx/Class/Manual/Cookbook.pod#OVERLOADING_METHODS>. 
> For a given row, I'd like to get a hash with all the column names/value 
> pairs like Row->get_columns returns. However, get_columns returns the 
> actual column values, not the ones created with the custom overloaded 
> accessors. get_inflated_columns behaves the same way.

I don't believe you. Here is the implementation of get_inflated_columns
from the current CPAN version:

sub get_inflated_columns {
   my $self = shift;

   my %loaded_colinfo = (map
     { $_ => $self->column_info($_) }
     (grep { $self->has_column_loaded($_) } $self->columns)
   );

   my %inflated;
   for my $col (keys %loaded_colinfo) {
     if (exists $loaded_colinfo{$col}{accessor}) {
       my $acc = $loaded_colinfo{$col}{accessor};
       $inflated{$col} = $self->$acc if defined $acc;
     }
     else {
       $inflated{$col} = $self->$col;
     }
   }

   # return all loaded columns with the inflations overlayed on top
   return ($self->get_columns, %inflated);
}

> 
> I could get the data I want with a loop but it's not very elegant:
> 
>       foreach my $col ( $row->columns ) {
>           $row_href->{$col} = $obj->$col;
>       }
> 

That's how the internals do it too.

> Is there a better way of doing this? The reason why I want the hash is 
> to pass the data to my view in a Catalyst application.

Use http://search.cpan.org/~frew/DBIx-Class-0.08123/lib/DBIx/Class/ResultClass/HashRefInflator.pm

> BTW, the documentation of Row->get_column says "Returns a raw column 
> value from the row object, if it has already been fetched from the 
> database or set by an accessor." Which made me think it would do what I 
> need, but it doesn't.

Yes, it returns the raw value, regardless of what transformations took
place, it reaches into the object itself. Please suggest better wording
for above piece of documentation (or just send a github pull req :)


> To illustrate my point, I took the code in DBIx::Class::Manual::Example, 
> and added the following accessor in the result Track:
> 
> ...
> 
> As you can see, the overloaded accessor works with the row object, but 
> is not used by get_columns.

Yes, expected and by design.



More information about the DBIx-Class mailing list