514b43bd73649fced735887f0d433c5ce645a9d8
[dbsrgits/DBIx-Class.git] / t / storage / debug.t
1 use strict;
2 use warnings;
3 no warnings 'once';
4
5 use Test::More;
6 use Test::Exception;
7 use lib qw(t/lib);
8 use DBICTest;
9 use DBIC::SqlMakerTest;
10 use Path::Class qw/file/;
11
12 BEGIN { delete @ENV{qw(DBIC_TRACE DBIC_TRACE_PROFILE DBICTEST_SQLITE_USE_FILE)} }
13
14 my $schema = DBICTest->init_schema();
15
16 my $lfn = file("t/var/sql-$$.log");
17 unlink $lfn or die $!
18   if -e $lfn;
19
20 # make sure we are testing the vanilla debugger and not ::PrettyPrint
21 require DBIx::Class::Storage::Statistics;
22 $schema->storage->debugobj(DBIx::Class::Storage::Statistics->new);
23
24 ok ( $schema->storage->debug(1), 'debug' );
25 $schema->storage->debugfh($lfn->openw);
26 $schema->storage->debugfh->autoflush(1);
27 $schema->resultset('CD')->count;
28
29 my @loglines = $lfn->slurp;
30 is (@loglines, 1, 'one line of log');
31 like($loglines[0], qr/^SELECT COUNT/, 'File log via debugfh success');
32
33 $schema->storage->debugfh(undef);
34
35 {
36   local $ENV{DBIC_TRACE} = "=$lfn";
37   unlink $lfn;
38
39   $schema->resultset('CD')->count;
40
41   my $schema2 = DBICTest->init_schema(no_deploy => 1);
42   $schema2->storage->_do_query('SELECT 1'); # _do_query() logs via standard mechanisms
43
44   my @loglines = $lfn->slurp;
45   is(@loglines, 2, '2 lines of log');
46   like($loglines[0], qr/^SELECT COUNT/, 'Env log from schema1 success');
47   like($loglines[1], qr/^SELECT 1:/, 'Env log from schema2 success');
48
49   $schema->storage->debugobj->debugfh(undef)
50 }
51
52 END {
53   unlink $lfn;
54 }
55
56 open(STDERRCOPY, '>&STDERR');
57 close(STDERR);
58 dies_ok {
59   $schema->resultset('CD')->search({})->count;
60 } 'Died on closed FH';
61
62 open(STDERR, '>&STDERRCOPY');
63
64 # test debugcb and debugobj protocol
65 {
66   my $rs = $schema->resultset('CD')->search( {
67     artist => 1,
68     cdid => { -between => [ 1, 3 ] },
69     title => { '!=' => \[ '?', undef ] }
70   });
71
72   my $sql_trace = 'SELECT me.cdid, me.artist, me.title, me.year, me.genreid, me.single_track FROM cd me WHERE ( ( artist = ? AND ( cdid BETWEEN ? AND ? ) AND title != ? ) )';
73   my @bind_trace = qw( '1' '1' '3' NULL );  # quotes are in fact part of the trace </facepalm>
74
75
76   my @args;
77   $schema->storage->debugcb(sub { push @args, @_ } );
78
79   $rs->all;
80
81   is_deeply( \@args, [
82     "SELECT",
83     sprintf( "%s: %s\n", $sql_trace, join ', ', @bind_trace ),
84   ]);
85
86   {
87     package DBICTest::DebugObj;
88     our @ISA = 'DBIx::Class::Storage::Statistics';
89
90     sub query_start {
91       my $self = shift;
92       ( $self->{_traced_sql}, @{$self->{_traced_bind}} ) = @_;
93     }
94   }
95
96   my $do = $schema->storage->debugobj(DBICTest::DebugObj->new);
97
98   $rs->all;
99
100   is( $do->{_traced_sql}, $sql_trace );
101
102   is_deeply ( $do->{_traced_bind}, \@bind_trace );
103 }
104
105 done_testing;