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