开发者

How can I pretty print DBIx::Class results?

开发者 https://www.devze.com 2023-01-22 10:18 出处:网络
I\'d like to pretty-print DBIx::Class::ResultSet results like this: my $schema = MyDatabase::Main->connect(\'dbi:SQLite:db/example.db\');

I'd like to pretty-print DBIx::Class::ResultSet results like this:

my $schema = MyDatabase::Main->connect('dbi:SQLite:db/example.db');
my $rs = $schema->resultset('Track')->all()
# then print $rs with all of those feilds

I found DBIx::SQLCrosst开发者_JS百科ab::Format class but it seems to work only with own queries.


I don't know of any DBIC pretty print modules but it is easy to implement from any of the myriad of text, html or other types of tabular output modules on CPAN.

Below is my quick working example using Text::Table

use 5.012;
use warnings;
use List::MoreUtils 'zip';
use Text::Table;

# my database with Album schema from DBIx::Class::Manual::Intro
use MySchema;
my $db     = MySchema->connect( "DBI:SQLite:myschema_db" );
my $album  = $db->resultset( 'Album' );

# get column names for the Album table
my @cols   = $album->result_source->columns;

# create header with these column names
my $table  = Text::Table->new( header( @cols ) );

# add each Album row to table output
while (my $cd = $album->next) {
    $table->add( map { $cd->get_column( $_ ) } @cols );
}

print $table;    # => tabular text output

# adds | separator between header labels
sub header {
    my @sep = (\' | ') x @_;
    zip @_, @sep;
}

This outputs the following with my test data:

albumid | artist      | title          | rank | 
1       | Lou Reed    | Transformer    |      | 
2       | Lou Reed    | Berlin         |      | 
3       | David Bowie | Ziggy Stardust |      | 
4       | Japan       | Tin Drum       |      |

/I3az/


If you're looking for truly pretty output, use draegtun's example above. However if you really just want to be able to use Data::Dumper to spit out a DBIx::Class::Row object without all of the source data you can add this hook to your result class (or better yet to a base result class for all of your schema results)

sub _dumper_hook {
  $_[0] = bless { %{ $_[0] }, _source_handle=>undef }, ref($_[0]); 
}
$Data::Dumper::Freezer = '_dumper_hook';
0

精彩评论

暂无评论...
验证码 换一张
取 消