Fix annoying warnings on innocent looking MSSQL code
[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);
e48635f7 9use IO::Handle ();
bbf6a9a5 10use DBIx::Class::_Util 'scope_guard';
e952df76 11use DBICTest::Util::LeakTracer qw(populate_weakregistry assert_empty_weakregistry);
439a7283 12use DBICTest::Util qw( local_umask tmpdir await_flock dbg DEBUG_TEST_CONCURRENCY_LOCKS );
e952df76 13use namespace::clean;
14
ddcc02d1 15if( $ENV{DBICTEST_ASSERT_NO_SPURIOUS_EXCEPTION_ACTION} ) {
5c33c8be 16 my $ea = __PACKAGE__->exception_action( sub {
ddcc02d1 17
18 my ( $fr_num, $disarmed, $throw_exception_fr_num );
19 while( ! $disarmed and my @fr = caller(++$fr_num) ) {
20
21 $throw_exception_fr_num ||= (
22 $fr[3] eq 'DBIx::Class::ResultSource::throw_exception'
23 and
24 $fr_num
25 );
26
27 $disarmed = !! (
28 $fr[1] =~ / \A (?: \. [\/\\] )? x?t [\/\\] .+ \.t \z /x
29 and
30 (
31 $fr[3] =~ /\A (?:
32 Test::Exception::throws_ok
33 |
34 Test::Exception::dies_ok
35 |
36 Try::Tiny::try
37 |
38 \Q(eval)\E
39 ) \z /x
40 or
41 (
42 $fr[3] eq 'Test::Exception::lives_ok'
43 and
44 ( $::TODO or Test::Builder->new->in_todo )
45 )
46 )
47 );
48 }
49
50 Test::Builder->new->ok(0, join "\n",
51 'Unexpected &exception_action invocation',
52 '',
53 ' You almost certainly used eval/try instead of dbic_internal_try()',
54 " Adjust *one* of the eval-ish constructs in the callstack starting" . DBICTest::Util::stacktrace($throw_exception_fr_num||())
55 ) unless $disarmed;
56
57 DBIx::Class::Exception->throw( $_[0] );
5c33c8be 58 });
59
60 my $interesting_ns_rx = qr/^ (?: main$ | DBIx::Class:: | DBICTest:: ) /x;
61
62 # hard-set $SIG{__DIE__} to the class-wide exception_action
63 # with a little escape preceeding it
64 $SIG{__DIE__} = sub {
65
66 # without this there would be false positives everywhere :(
67 die @_ if (
68 (caller(0))[0] !~ $interesting_ns_rx
69 or
70 (
71 caller(0) eq 'main'
72 and
73 (caller(1))[0] !~ $interesting_ns_rx
74 )
75 );
76
77 &$ea;
78 };
ddcc02d1 79}
80
2cfc22dd 81sub capture_executed_sql_bind {
82 my ($self, $cref) = @_;
83
84 $self->throw_exception("Expecting a coderef to run") unless ref $cref eq 'CODE';
85
4faaf174 86 require DBICTest::SQLTracerObj;
87
2cfc22dd 88 # hack around stupid, stupid API
89 no warnings 'redefine';
90 local *DBIx::Class::Storage::DBI::_format_for_trace = sub { $_[1] };
91 Class::C3->reinitialize if DBIx::Class::_ENV_::OLD_MRO;
92
b74b15b0 93 # can not use local() due to an unknown number of storages
94 # (think replicated)
95 my $orig_states = { map
96 { $_ => $self->storage->$_ }
97 qw(debugcb debugobj debug)
98 };
4faaf174 99
bbf6a9a5 100 my $sg = scope_guard {
b74b15b0 101 $self->storage->$_ ( $orig_states->{$_} ) for keys %$orig_states;
bbf6a9a5 102 };
b74b15b0 103
104 $self->storage->debugcb(undef);
105 $self->storage->debugobj( my $tracer_obj = DBICTest::SQLTracerObj->new );
106 $self->storage->debug(1);
2cfc22dd 107
49eeb48d 108 local $Test::Builder::Level = $Test::Builder::Level + 2;
2cfc22dd 109 $cref->();
110
111 return $tracer_obj->{sqlbinds} || [];
112}
113
49eeb48d 114sub is_executed_querycount {
115 my ($self, $cref, $exp_counts, $msg) = @_;
116
117 local $Test::Builder::Level = $Test::Builder::Level + 1;
118
119 $self->throw_exception("Expecting an hashref of counts or an integer representing total query count")
120 unless ref $exp_counts eq 'HASH' or (defined $exp_counts and ! ref $exp_counts);
121
122 my @got = map { $_->[0] } @{ $self->capture_executed_sql_bind($cref) };
123
124 return Test::More::is( @got, $exp_counts, $msg )
125 unless ref $exp_counts;
126
127 my $got_counts = { map { $_ => 0 } keys %$exp_counts };
128 $got_counts->{$_}++ for @got;
129
130 return Test::More::is_deeply(
131 $got_counts,
132 $exp_counts,
133 $msg,
134 );
135}
136
2cfc22dd 137sub is_executed_sql_bind {
138 my ($self, $cref, $sqlbinds, $msg) = @_;
139
140 local $Test::Builder::Level = $Test::Builder::Level + 1;
141
142 $self->throw_exception("Expecting an arrayref of SQL/Bind pairs") unless ref $sqlbinds eq 'ARRAY';
143
144 my @expected = @$sqlbinds;
145
146 my @got = map { $_->[1] } @{ $self->capture_executed_sql_bind($cref) };
147
148
149 return Test::Builder->new->ok(1, $msg || "No queries executed while running $cref")
150 if !@got and !@expected;
151
152 require SQL::Abstract::Test;
153 my $ret = 1;
154 while (@expected or @got) {
155 my $left = shift @got;
156 my $right = shift @expected;
157
158 # allow the right side to "simplify" the entire shebang
159 if ($left and $right) {
160 $left = [ @$left ];
161 for my $i (1..$#$right) {
162 if (
163 ! ref $right->[$i]
164 and
165 ref $left->[$i] eq 'ARRAY'
166 and
167 @{$left->[$i]} == 2
168 ) {
169 $left->[$i] = $left->[$i][1]
170 }
171 }
172 }
173
174 $ret &= SQL::Abstract::Test::is_same_sql_bind(
175 \( $left || [] ),
176 \( $right || [] ),
177 $msg,
178 );
179 }
180
181 return $ret;
182}
183
e952df76 184our $locker;
185END {
186 # we need the $locker to be referenced here for delayed destruction
187 if ($locker->{lock_name} and ($ENV{DBICTEST_LOCK_HOLDER}||0) == $$) {
69016f65 188 DEBUG_TEST_CONCURRENCY_LOCKS
189 and dbg "$locker->{type} LOCK RELEASED (END): $locker->{lock_name}";
e952df76 190 }
191}
192
193my $weak_registry = {};
194
195sub connection {
196 my $self = shift->next::method(@_);
197
198# MASSIVE FIXME
199# we can't really lock based on DSN, as we do not yet have a way to tell that e.g.
200# DBICTEST_MSSQL_DSN=dbi:Sybase:server=192.168.0.11:1433;database=dbtst
201# and
202# DBICTEST_MSSQL_ODBC_DSN=dbi:ODBC:server=192.168.0.11;port=1433;database=dbtst;driver=FreeTDS;tds_version=8.0
203# are the same server
204# hence we lock everything based on sqlt_type or just globally if not available
205# just pretend we are python you know? :)
206
207
208 # when we get a proper DSN resolution sanitize to produce a portable lockfile name
209 # this may look weird and unnecessary, but consider running tests from
210 # windows over a samba share >.>
211 #utf8::encode($dsn);
212 #$dsn =~ s/([^A-Za-z0-9_\-\.\=])/ sprintf '~%02X', ord($1) /ge;
213 #$dsn =~ s/^dbi/dbi/i;
214
215 # provide locking for physical (non-memory) DSNs, so that tests can
216 # safely run in parallel. While the harness (make -jN test) does set
217 # an envvar, we can not detect when a user invokes prove -jN. Hence
218 # perform the locking at all times, it shouldn't hurt.
219 # the lock fh *should* inherit across forks/subprocesses
e952df76 220 if (
221 ! $DBICTest::global_exclusive_lock
222 and
223 ( ! $ENV{DBICTEST_LOCK_HOLDER} or $ENV{DBICTEST_LOCK_HOLDER} == $$ )
224 and
225 ref($_[0]) ne 'CODE'
226 and
227 ($_[0]||'') !~ /^ (?i:dbi) \: SQLite \: (?: dbname\= )? (?: \:memory\: | t [\/\\] var [\/\\] DBIxClass\-) /x
228 ) {
229
0f6d86e4 230 my $locktype;
231
232 {
e952df76 233 # guard against infinite recursion
234 local $ENV{DBICTEST_LOCK_HOLDER} = -1;
235
0f6d86e4 236 # we need to work with a forced fresh clone so that we do not upset any state
e952df76 237 # of the main $schema (some tests examine it quite closely)
238 local $SIG{__WARN__} = sub {};
5c33c8be 239 local $SIG{__DIE__};
e952df76 240 local $@;
0f6d86e4 241
242 # this will either give us an undef $locktype or will determine things
243 # properly with a default ( possibly connecting in the process )
244 eval {
245 my $s = ref($self)->connect(@{$self->storage->connect_info})->storage;
246
247 $locktype = $s->sqlt_type || 'generic';
248
249 # in case sqlt_type did connect, doesn't matter if it fails or something
250 $s->disconnect;
e952df76 251 };
0f6d86e4 252 }
e952df76 253
254 # Never hold more than one lock. This solves the "lock in order" issues
255 # unrelated tests may have
256 # Also if there is no connection - there is no lock to be had
257 if ($locktype and (!$locker or $locker->{type} ne $locktype)) {
258
259 # this will release whatever lock we may currently be holding
260 # which is fine since the type does not match as checked above
69016f65 261 DEBUG_TEST_CONCURRENCY_LOCKS
262 and $locker
263 and dbg "$locker->{type} LOCK RELEASED (UNDEF): $locker->{lock_name}";
264
e952df76 265 undef $locker;
266
439a7283 267 my $lockpath = tmpdir . "_dbictest_$locktype.lock";
e952df76 268
69016f65 269 DEBUG_TEST_CONCURRENCY_LOCKS
270 and dbg "Waiting for $locktype LOCK: $lockpath...";
271
e952df76 272 my $lock_fh;
273 {
274 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
275 sysopen ($lock_fh, $lockpath, O_RDWR|O_CREAT) or die "Unable to open $lockpath: $!";
276 }
69016f65 277
630e2ea8 278 await_flock ($lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
69016f65 279
280 DEBUG_TEST_CONCURRENCY_LOCKS
281 and dbg "Got $locktype LOCK: $lockpath";
e952df76 282
283 # see if anyone was holding a lock before us, and wait up to 5 seconds for them to terminate
284 # if we do not do this we may end up trampling over some long-running END or somesuch
285 seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
286 my $old_pid;
287 if (
288 read ($lock_fh, $old_pid, 100)
289 and
290 ($old_pid) = $old_pid =~ /^(\d+)$/
291 ) {
69016f65 292 DEBUG_TEST_CONCURRENCY_LOCKS
293 and dbg "Post-grab WAIT for $old_pid START: $lockpath";
294
e952df76 295 for (1..50) {
296 kill (0, $old_pid) or last;
5a8d5308 297 select( undef, undef, undef, 0.1 );
e952df76 298 }
69016f65 299
300 DEBUG_TEST_CONCURRENCY_LOCKS
301 and dbg "Post-grab WAIT for $old_pid FINISHED: $lockpath";
e952df76 302 }
e952df76 303
304 truncate $lock_fh, 0;
305 seek ($lock_fh, 0, SEEK_SET) or die "seek failed $!";
306 $lock_fh->autoflush(1);
307 print $lock_fh $$;
308
309 $ENV{DBICTEST_LOCK_HOLDER} ||= $$;
310
311 $locker = {
312 type => $locktype,
313 fh => $lock_fh,
314 lock_name => "$lockpath",
315 };
316 }
317 }
318
319 if ($INC{'Test/Builder.pm'}) {
320 populate_weakregistry ( $weak_registry, $self->storage );
321
322 my $cur_connect_call = $self->storage->on_connect_call;
323
324 $self->storage->on_connect_call([
325 (ref $cur_connect_call eq 'ARRAY'
326 ? @$cur_connect_call
327 : ($cur_connect_call || ())
328 ),
329 [sub {
330 populate_weakregistry( $weak_registry, shift->_dbh )
331 }],
332 ]);
333 }
334
335 return $self;
336}
337
338sub clone {
339 my $self = shift->next::method(@_);
340 populate_weakregistry ( $weak_registry, $self )
341 if $INC{'Test/Builder.pm'};
342 $self;
343}
344
345END {
961d79db 346 # Make sure we run after any cleanup in other END blocks
961d79db 347 push @{ B::end_av()->object_2svref }, sub {
348 assert_empty_weakregistry($weak_registry, 'quiet');
349 };
e952df76 350}
27a701f9 351
3521;