Retire DBIC::DebugObj, replace with $dbictest_schema->is_executed_sql_bind()
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest / BaseSchema.pm
1 package #hide from pause
2   DBICTest::BaseSchema;
3
4 use strict;
5 use warnings;
6 use base qw(DBICTest::Base DBIx::Class::Schema);
7
8 use Fcntl qw(:DEFAULT :seek :flock);
9 use Time::HiRes 'sleep';
10 use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry);
11 use DBICTest::Util 'local_umask';
12 use namespace::clean;
13
14 {
15   package # moar hide
16     DBICTest::SQLTracerObj;
17   use base 'DBIx::Class::Storage::Statistics';
18
19   sub query_start { push @{$_[0]{sqlbinds}}, [ ($_[1] =~ /^\s*(\S+)/)[0], [ $_[1], @{ $_[2]||[] } ] ] }
20
21   # who the hell came up with this API >:(
22   for my $txn (qw(begin rollback commit)) {
23     no strict 'refs';
24     *{"txn_$txn"} = sub { push @{$_[0]{sqlbinds}}, [ uc $txn => [ uc $txn ] ] };
25   }
26
27   sub svp_begin { push @{$_[0]{sqlbinds}}, [ SAVEPOINT => [ "SAVEPOINT $_[1]" ] ] }
28   sub svp_release { push @{$_[0]{sqlbinds}}, [ RELEASE_SAVEPOINT => [ "RELEASE $_[1]" ] ] }
29   sub svp_rollback { push @{$_[0]{sqlbinds}}, [ ROLLBACK_TO_SAVEPOINT => [ "ROLLBACK TO $_[1]" ] ] }
30
31 }
32
33 sub capture_executed_sql_bind {
34   my ($self, $cref) = @_;
35
36   $self->throw_exception("Expecting a coderef to run") unless ref $cref eq 'CODE';
37
38   # hack around stupid, stupid API
39   no warnings 'redefine';
40   local *DBIx::Class::Storage::DBI::_format_for_trace = sub { $_[1] };
41   Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
42
43   local $self->storage->{debugcb};
44   local $self->storage->{debugobj} = my $tracer_obj = DBICTest::SQLTracerObj->new;
45   local $self->storage->{debug} = 1;
46
47
48   $cref->();
49
50   return $tracer_obj->{sqlbinds} || [];
51 }
52
53 sub is_executed_sql_bind {
54   my ($self, $cref, $sqlbinds, $msg) = @_;
55
56   local $Test::Builder::Level = $Test::Builder::Level + 1;
57
58   $self->throw_exception("Expecting an arrayref of SQL/Bind pairs") unless ref $sqlbinds eq 'ARRAY';
59
60   my @expected = @$sqlbinds;
61
62   my @got = map { $_->[1] } @{ $self->capture_executed_sql_bind($cref) };
63
64
65   return Test::Builder->new->ok(1, $msg || "No queries executed while running $cref")
66     if !@got and !@expected;
67
68   require SQL::Abstract::Test;
69   my $ret = 1;
70   while (@expected or @got) {
71     my $left = shift @got;
72     my $right = shift @expected;
73
74     # allow the right side to "simplify" the entire shebang
75     if ($left and $right) {
76       $left = [ @$left ];
77       for my $i (1..$#$right) {
78         if (
79           ! ref $right->[$i]
80             and
81           ref $left->[$i] eq 'ARRAY'
82             and
83           @{$left->[$i]} == 2
84         ) {
85           $left->[$i] = $left->[$i][1]
86         }
87       }
88     }
89
90     $ret &= SQL::Abstract::Test::is_same_sql_bind(
91       \( $left || [] ),
92       \( $right || [] ),
93       $msg,
94     );
95   }
96
97   return $ret;
98 }
99
100 our $locker;
101 END {
102   # we need the $locker to be referenced here for delayed destruction
103   if ($locker->{lock_name} and ($ENV{DBICTEST_LOCK_HOLDER}||0) == $$) {
104     #warn "$$ $0 $locker->{type} LOCK RELEASED";
105   }
106 }
107
108 my $weak_registry = {};
109
110 sub connection {
111   my $self = shift->next::method(@_);
112
113 # MASSIVE FIXME
114 # we can't really lock based on DSN, as we do not yet have a way to tell that e.g.
115 # DBICTEST_MSSQL_DSN=dbi:Sybase:server=192.168.0.11:1433;database=dbtst
116 #  and
117 # DBICTEST_MSSQL_ODBC_DSN=dbi:ODBC:server=192.168.0.11;port=1433;database=dbtst;driver=FreeTDS;tds_version=8.0
118 # are the same server
119 # hence we lock everything based on sqlt_type or just globally if not available
120 # just pretend we are python you know? :)
121
122
123   # when we get a proper DSN resolution sanitize to produce a portable lockfile name
124   # this may look weird and unnecessary, but consider running tests from
125   # windows over a samba share >.>
126   #utf8::encode($dsn);
127   #$dsn =~ s/([^A-Za-z0-9_\-\.\=])/ sprintf '~%02X', ord($1) /ge;
128   #$dsn =~ s/^dbi/dbi/i;
129
130   # provide locking for physical (non-memory) DSNs, so that tests can
131   # safely run in parallel. While the harness (make -jN test) does set
132   # an envvar, we can not detect when a user invokes prove -jN. Hence
133   # perform the locking at all times, it shouldn't hurt.
134   # the lock fh *should* inherit across forks/subprocesses
135   #
136   # File locking is hard. Really hard. By far the best lock implementation
137   # I've seen is part of the guts of File::Temp. However it is sadly not
138   # reusable. Since I am not aware of folks doing NFS parallel testing,
139   # nor are we known to work on VMS, I am just going to punt this and
140   # use the portable-ish flock() provided by perl itself. If this does
141   # not work for you - patches more than welcome.
142   if (
143     ! $DBICTest::global_exclusive_lock
144       and
145     ( ! $ENV{DBICTEST_LOCK_HOLDER} or $ENV{DBICTEST_LOCK_HOLDER} == $$ )
146       and
147     ref($_[0]) ne 'CODE'
148       and
149     ($_[0]||'') !~ /^ (?i:dbi) \: SQLite \: (?: dbname\= )? (?: \:memory\: | t [\/\\] var [\/\\] DBIxClass\-) /x
150   ) {
151
152     my $locktype = do {
153       # guard against infinite recursion
154       local $ENV{DBICTEST_LOCK_HOLDER} = -1;
155
156       # we need to connect a forced fresh clone so that we do not upset any state
157       # of the main $schema (some tests examine it quite closely)
158       local $SIG{__WARN__} = sub {};
159       local $@;
160       my $storage = eval {
161         my $st = ref($self)->connect(@{$self->storage->connect_info})->storage;
162         $st->ensure_connected;  # do connect here, to catch a possible throw
163         $st;
164       };
165       $storage
166         ? do {
167           my $t = $storage->sqlt_type || 'generic';
168           eval { $storage->disconnect };
169           $t;
170         }
171         : undef
172       ;
173     };
174
175     # Never hold more than one lock. This solves the "lock in order" issues
176     # unrelated tests may have
177     # Also if there is no connection - there is no lock to be had
178     if ($locktype and (!$locker or $locker->{type} ne $locktype)) {
179
180       # this will release whatever lock we may currently be holding
181       # which is fine since the type does not match as checked above
182       undef $locker;
183
184       my $lockpath = DBICTest::RunMode->tmpdir->file("_dbictest_$locktype.lock");
185
186       #warn "$$ $0 $locktype GRABBING LOCK";
187       my $lock_fh;
188       {
189         my $u = local_umask(0); # so that the file opens as 666, and any user can lock
190         sysopen ($lock_fh, $lockpath, O_RDWR|O_CREAT) or die "Unable to open $lockpath: $!";
191       }
192       flock ($lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
193       #warn "$$ $0 $locktype LOCK GRABBED";
194
195       # see if anyone was holding a lock before us, and wait up to 5 seconds for them to terminate
196       # if we do not do this we may end up trampling over some long-running END or somesuch
197       seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
198       my $old_pid;
199       if (
200         read ($lock_fh, $old_pid, 100)
201           and
202         ($old_pid) = $old_pid =~ /^(\d+)$/
203       ) {
204         for (1..50) {
205           kill (0, $old_pid) or last;
206           sleep 0.1;
207         }
208       }
209       #warn "$$ $0 $locktype POST GRAB WAIT";
210
211       truncate $lock_fh, 0;
212       seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
213       $lock_fh->autoflush(1);
214       print $lock_fh $$;
215
216       $ENV{DBICTEST_LOCK_HOLDER} ||= $$;
217
218       $locker = {
219         type => $locktype,
220         fh => $lock_fh,
221         lock_name => "$lockpath",
222       };
223     }
224   }
225
226   if ($INC{'Test/Builder.pm'}) {
227     populate_weakregistry ( $weak_registry, $self->storage );
228
229     my $cur_connect_call = $self->storage->on_connect_call;
230
231     $self->storage->on_connect_call([
232       (ref $cur_connect_call eq 'ARRAY'
233         ? @$cur_connect_call
234         : ($cur_connect_call || ())
235       ),
236       [sub {
237         populate_weakregistry( $weak_registry, shift->_dbh )
238       }],
239     ]);
240   }
241
242   return $self;
243 }
244
245 sub clone {
246   my $self = shift->next::method(@_);
247   populate_weakregistry ( $weak_registry, $self )
248     if $INC{'Test/Builder.pm'};
249   $self;
250 }
251
252 END {
253   assert_empty_weakregistry($weak_registry, 'quiet');
254 }
255
256 1;