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