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