[Dbix-class] Re: How to grep field types?

A. Pagaltzis pagaltzis at gmx.de
Fri May 11 14:01:49 GMT 2007


* RA Jones <ra.jones at dpw.clara.co.uk> [2007-05-11 14:15]:
> because this controller method is generating an sql 'where'
> from two schemas, I have to do this:
> 
> foreach( qw/Schema::Foo Schema::Bar/ ) {
>  my $schema = $_;

  foreach my $schema ( qw/Schema::Foo Schema::Bar/ ) {

>  my $src = $c->model($schema)->result_source;
>       
>  push @date_fields, grep { $src->column_info($_)->{data_type} eq 'DATE' } $src->columns;
> }

I’d write that as a map.

    @date_fields = map {
        my $src = $c->model($_)->result_source;
        grep { $src->column_info($_)->{data_type} eq 'DATE' } $src->columns;
    } qw( Schema::Foo Schema::Bar );

That’s really too much work for a map block, though…

I’ll be naughty and monkey-patch DBIx::ResultSource:

    sub DBIx::ResultSource::all_columns_info {
        my $self = shift;
        map +{
            column_name => $_,
            %{ $self->column_info($_) }
        }, $self->columns;
    }

Then the actual code can be much more readable:

    @date_fields = (
        map  { $_->{column_name} }
        grep { $_->{data_type} eq 'DATE' }
        map  { $c->model($_)->result_source->all_columns_info }
        qw( Schema::Foo Schema::Bar )
    };

However, I wrote it this way only because that is the cleanest
cut for monkey-patching ::ResultSource for our purposes.

Ideally, the hash returned by `column_info` would already include
a `column_name` key and `column_info` would accept a list of
column names to return information about, not only a single one.

This could be implemented in DBIx::Class with only a tiny patch.

The code would then become this:

    @date_fields = (
        map  { $_->{column_name} }
        grep { $_->{data_type} eq 'DATE' }
        map  { $_->column_info( $_->columns ) }
        map  { $c->model($_)->result_source }
        qw( Schema::Foo Schema::Bar )
    );

Regards,
-- 
Aristotle Pagaltzis // <http://plasmasturm.org/>



More information about the Dbix-class mailing list