allow disabling of show_progress; _ some accessors
[scpubgit/Q-Branch.git] / lib / DBIx / Class / Storage / Debug / PrettyPrint.pm
1 package DBIx::Class::Storage::Debug::PrettyPrint;
2
3 use strict;
4 use warnings;
5
6 use base 'DBIx::Class::Storage::Statistics';
7
8 use SQL::Abstract::Tree;
9
10 __PACKAGE__->mk_group_accessors( simple => '_sqlat' );
11 __PACKAGE__->mk_group_accessors( simple => '_clear_line_str' );
12 __PACKAGE__->mk_group_accessors( simple => '_executing_str' );
13 __PACKAGE__->mk_group_accessors( simple => '_show_progress' );
14
15 sub new {
16    my $class = shift;
17    my $args  = shift;
18
19    my $clear_line = $args->{clear_line} || "\r\e[J";
20    my $executing  = $args->{executing}  || eval { require Term::ANSIColor } ? do {
21        my $c = \&Term::ANSIColor::color;
22        $c->('blink white on_black') . 'EXECUTING...' . $c->('reset');;
23    } : 'EXECUTING...';
24    my $show_progress = defined $args->{show_progress} ? $args->{show_progress} : 1;
25
26    my $sqlat = SQL::Abstract::Tree->new($args);
27    my $self = $class->next::method(@_);
28    $self->_clear_line_str($clear_line);
29    $self->_executing_str($executing);
30    $self->_show_progress($show_progress);
31
32    $self->_sqlat($sqlat);
33
34    return $self
35 }
36
37 sub print {
38   my $self = shift;
39   my $string = shift;
40   my $bindargs = shift || [];
41
42   my ($lw, $lr);
43   ($lw, $string, $lr) = $string =~ /^(\s*)(.+?)(\s*)$/s;
44
45   return if defined $bindargs && defined $bindargs->[0] &&
46     $bindargs->[0] eq q('__BULK_INSERT__');
47
48   my $use_placeholders = !!$self->_sqlat->fill_in_placeholders;
49
50   # DBIC pre-quotes bindargs
51   $bindargs = [map { s/^'//; s/'$//; $_ } @{$bindargs}] if $use_placeholders;
52
53   my $formatted = $self->_sqlat->format($string, $bindargs);
54
55   $formatted = "$formatted: " . join ', ', @{$bindargs}
56      unless $use_placeholders;
57
58   $self->next::method("$lw$formatted$lr", @_);
59 }
60
61 sub query_start {
62   my ($self, $string, @bind) = @_;
63
64   if(defined $self->callback) {
65     $string =~ m/^(\w+)/;
66     $self->callback->($1, "$string: ".join(', ', @bind)."\n");
67     return;
68   }
69
70   $string =~ s/\s+$//;
71
72   $self->print("$string\n", \@bind);
73
74   $self->debugfh->print($self->_executing_str) if $self->_show_progress
75 }
76
77 sub query_end {
78   $_[0]->debugfh->print($_[0]->_clear_line_str) if $_[0]->_show_progress
79 }
80
81 1;
82
83 =pod
84
85 =head1 SYNOPSIS
86
87  package MyApp::Schema;
88
89  use parent 'DBIx::Class::Schema';
90
91  use DBIx::Class::Storage::Debug::PrettyPrint;
92
93  __PACKAGE__->load_namespaces;
94
95  my $pp = DBIx::Class::Storage::Debug::PrettyPrint->new({
96    profile => 'console',
97  });
98
99  sub connection {
100    my $self = shift;
101
102    my $ret = $self->next::method(@_);
103
104    $self->storage->debugobj($pp);
105
106    $ret
107  }
108