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