2010-10-27 34 views
5

我想漂亮地打印DBIx ::類:: ResultSet的結果是這樣的:我該如何漂亮地打印DBIx :: Class結果?

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

我發現DBIx :: SQLCrosstab ::格式類,但它似乎只與自己的查詢工作。

回答

4

我不知道任何DBIC 漂亮的打印模塊,但它很容易從任何無數的文本,HTML或其他類型的CPAN表格輸出模塊實現。

下面是一個使用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; 
} 

這與輸出我的測試數據下面我快速的工作例如:

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

/I3az/

1

如果您正在尋找真正的漂亮輸出,使用上面的draegtun的例子。但是,如果您真的只想使用Data :: Dumper在沒有所有源數據的情況下吐出一個DBIx :: Class :: Row對象,則可以將此鉤子添加到結果類中(或者更好地添加到基本結果中類的所有架構結果)

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