Add EXECUTING for clarity of long running SQL
[dbsrgits/SQL-Abstract.git] / lib / DBIx / Class / Storage / Debug / PrettyPrint.pm
CommitLineData
0d5df7d6 1package DBIx::Class::Storage::Debug::PrettyPrint;
1dc93d17 2
84c65032 3use strict;
4use warnings;
5
1dc93d17 6use base 'DBIx::Class::Storage::Statistics';
7
8use SQL::Abstract::Tree;
9
10__PACKAGE__->mk_group_accessors( simple => '_sqlat' );
416cdb2e 11__PACKAGE__->mk_group_accessors( simple => 'clear_line_str' );
12__PACKAGE__->mk_group_accessors( simple => 'executing_str' );
1dc93d17 13
14sub new {
0d5df7d6 15 my $class = shift;
416cdb2e 16 my $args = shift;
1dc93d17 17
416cdb2e 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);
0d5df7d6 26 my $self = $class->next::method(@_);
416cdb2e 27 $self->clear_line_str($clear_line);
28 $self->executing_str($executing);
1dc93d17 29
0d5df7d6 30 $self->_sqlat($sqlat);
1dc93d17 31
0d5df7d6 32 return $self
1dc93d17 33}
34
31756ef2 35sub print {
1dc93d17 36 my $self = shift;
37 my $string = shift;
25d4d820 38 my $bindargs = shift || [];
84c65032 39
416cdb2e 40 my ($lw, $lr);
41 ($lw, $string, $lr) = $string =~ /^(\s*)(.+?)(\s*)$/s;
42
fab0bed9 43 return if defined $bindargs && defined $bindargs->[0] &&
44 $bindargs->[0] eq q('__BULK_INSERT__');
45
84c65032 46 my $use_placeholders = !!$self->_sqlat->fill_in_placeholders;
47
48 # DBIC pre-quotes bindargs
ec02b310 49 $bindargs = [map { s/^'//; s/'$//; $_ } @{$bindargs}] if $use_placeholders;
84c65032 50
416cdb2e 51 my $formatted = $self->_sqlat->format($string, $bindargs);
1dc93d17 52
84c65032 53 $formatted = "$formatted: " . join ', ', @{$bindargs}
54 unless $use_placeholders;
1dc93d17 55
416cdb2e 56 $self->next::method("$lw$formatted$lr", @_);
1dc93d17 57}
58
84c65032 59sub 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
416cdb2e 68 $string =~ s/\s+$//;
69
70 $self->print("$string\n", \@bind);
71
72 $self->debugfh->print($self->executing_str)
73}
74
75sub query_end {
76 $_[0]->debugfh->print($_[0]->clear_line_str);
84c65032 77}
78
1dc93d17 791;
6b1bf9f8 80
81=pod
82
83=head1 SYNOPSIS
84
85 package MyApp::Schema;
86
87 use parent 'DBIx::Class::Schema';
88
0d5df7d6 89 use DBIx::Class::Storage::Debug::PrettyPrint;
6b1bf9f8 90
91 __PACKAGE__->load_namespaces;
92
0d5df7d6 93 my $pp = DBIx::Class::Storage::Debug::PrettyPrint->new({
94 profile => 'console',
95 });
6b1bf9f8 96
97 sub connection {
0d5df7d6 98 my $self = shift;
6b1bf9f8 99
0d5df7d6 100 my $ret = $self->next::method(@_);
6b1bf9f8 101
0d5df7d6 102 $self->storage->debugobj($pp);
6b1bf9f8 103
0d5df7d6 104 $ret
6b1bf9f8 105 }
106