Switch most remaining debug-hooks to $dbictest_schema->is_executed_querycount()
[dbsrgits/DBIx-Class-Historic.git] / t / lib / DBICTest.pm
CommitLineData
8273e845 1package # hide from PAUSE
c6d74d3e 2 DBICTest;
1c339d71 3
4use strict;
5use warnings;
39568b8a 6
7# this noop trick initializes the STDOUT, so that the TAP::Harness
8# issued IO::Select->can_read calls (which are blocking wtf wtf wtf)
9# keep spinning and scheduling jobs
10# This results in an overall much smoother job-queue drainage, since
11# the Harness blocks less
12# (ideally this needs to be addressed in T::H, but a quick patchjob
13# broke everything so tabling it for now)
14BEGIN {
15 if ($INC{'Test/Builder.pm'}) {
16 local $| = 1;
17 print "#\n";
18 }
19}
5e724964 20
21use Module::Runtime 'module_notional_filename';
22BEGIN {
23 for my $mod (qw( DBIC::SqlMakerTest SQL::Abstract )) {
24 if ( $INC{ module_notional_filename($mod) } ) {
25 # FIXME this does not seem to work in BEGIN - why?!
26 #require Carp;
27 #$Carp::Internal{ (__PACKAGE__) }++;
28 #Carp::croak( __PACKAGE__ . " must be loaded before $mod" );
29
30 my ($fr, @frame) = 1;
31 while (@frame = caller($fr++)) {
32 last if $frame[1] !~ m|^t/lib/DBICTest|;
33 }
34
35 die __PACKAGE__ . " must be loaded before $mod (or modules using $mod) at $frame[1] line $frame[2]\n";
36 }
37 }
38}
39568b8a 39
1c339d71 40use DBICTest::Schema;
218b7c12 41use DBICTest::Util::LeakTracer qw/populate_weakregistry assert_empty_weakregistry/;
42use DBICTest::Util 'local_umask';
a258bfc7 43use Carp;
de306d4b 44use Path::Class::File ();
8d6b1478 45use File::Spec;
027e3cc6 46use Fcntl qw/:DEFAULT :flock/;
2525160d 47use Config;
17e7d7f0 48
49=head1 NAME
50
51DBICTest - Library to be used by DBIx::Class test scripts.
52
53=head1 SYNOPSIS
54
55 use lib qw(t/lib);
56 use DBICTest;
57 use Test::More;
8273e845 58
17e7d7f0 59 my $schema = DBICTest->init_schema();
60
61=head1 DESCRIPTION
62
8273e845 63This module provides the basic utilities to write tests against
17e7d7f0 64DBIx::Class.
65
66=head1 METHODS
67
68=head2 init_schema
69
70 my $schema = DBICTest->init_schema(
71 no_deploy=>1,
72 no_populate=>1,
2bf79155 73 storage_type=>'::DBI::Replicated',
cb6ec758 74 storage_type_args=>{
d7a58a29 75 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
cb6ec758 76 },
17e7d7f0 77 );
78
8273e845 79This method removes the test SQLite database in t/var/DBIxClass.db
17e7d7f0 80and then creates a new, empty database.
81
8273e845 82This method will call deploy_schema() by default, unless the
17e7d7f0 83no_deploy flag is set.
84
8273e845 85Also, by default, this method will call populate_schema() by
17e7d7f0 86default, unless the no_deploy or no_populate flags are set.
87
88=cut
1c339d71 89
8d6b1478 90# some tests are very time sensitive and need to run on their own, without
91# being disturbed by anything else grabbing CPU or disk IO. Hence why everything
92# using DBICTest grabs a shared lock, and the few tests that request a :GlobalLock
93# will ask for an exclusive one and block until they can get it
94our ($global_lock_fh, $global_exclusive_lock);
95sub import {
96 my $self = shift;
97
0a03f539 98 my $lockpath = DBICTest::RunMode->tmpdir->file('_dbictest_global.lock');
8d6b1478 99
100 {
101 my $u = local_umask(0); # so that the file opens as 666, and any user can lock
fa19e5d6 102 sysopen ($global_lock_fh, $lockpath, O_RDWR|O_CREAT)
103 or die "Unable to open $lockpath: $!";
8d6b1478 104 }
105
106 for (@_) {
107 if ($_ eq ':GlobalLock') {
108 flock ($global_lock_fh, LOCK_EX) or die "Unable to lock $lockpath: $!";
109 $global_exclusive_lock = 1;
110 }
111 else {
112 croak "Unknown export $_ requested from $self";
113 }
114 }
115
116 unless ($global_exclusive_lock) {
117 flock ($global_lock_fh, LOCK_SH) or die "Unable to lock $lockpath: $!";
118 }
119}
120
121END {
122 if ($global_lock_fh) {
123 # delay destruction even more
124 }
857d66ca 125}
126
8d6b1478 127{
de306d4b 128 my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
129 $dir->mkpath unless -d "$dir";
8d6b1478 130 $dir = "$dir";
131
132 sub _sqlite_dbfilename {
133 my $holder = $ENV{DBICTEST_LOCK_HOLDER} || $$;
134 $holder = $$ if $holder == -1;
135
136 # useful for missing cleanup debugging
137 #if ( $holder == $$) {
138 # my $x = $0;
139 # $x =~ s/\//#/g;
140 # $holder .= "-$x";
141 #}
142
143 return "$dir/DBIxClass-$holder.db";
144 }
145
146 END {
147 _cleanup_dbfile();
148 }
149}
150
151$SIG{INT} = sub { _cleanup_dbfile(); exit 1 };
152
153sub _cleanup_dbfile {
154 # cleanup if this is us
155 if (
156 ! $ENV{DBICTEST_LOCK_HOLDER}
157 or
158 $ENV{DBICTEST_LOCK_HOLDER} == -1
159 or
160 $ENV{DBICTEST_LOCK_HOLDER} == $$
161 ) {
162 my $db_file = _sqlite_dbfilename();
163 unlink $_ for ($db_file, "${db_file}-journal");
164 }
165}
166
167sub has_custom_dsn {
168 return $ENV{"DBICTEST_DSN"} ? 1:0;
bcb3e850 169}
170
171sub _sqlite_dbname {
481df957 172 my $self = shift;
173 my %args = @_;
39b80a73 174 return $self->_sqlite_dbfilename if (
175 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
176 );
d7a58a29 177 return ":memory:";
857d66ca 178}
179
579ca3f7 180sub _database {
17e7d7f0 181 my $self = shift;
481df957 182 my %args = @_;
17e7d7f0 183
a258bfc7 184 if ($ENV{DBICTEST_DSN}) {
185 return (
186 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
187 { AutoCommit => 1, %args },
188 );
189 }
190 my $db_file = $self->_sqlite_dbname(%args);
17e7d7f0 191
a258bfc7 192 for ($db_file, "${db_file}-journal") {
193 next unless -e $_;
194 unlink ($_) or carp (
70c28808 195 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
a258bfc7 196 );
197 }
17e7d7f0 198
a258bfc7 199 return ("dbi:SQLite:${db_file}", '', '', {
200 AutoCommit => 1,
201
202 # this is executed on every connect, and thus installs a disconnect/DESTROY
203 # guard for every new $dbh
204 on_connect_do => sub {
9e75be92 205
a258bfc7 206 my $storage = shift;
207 my $dbh = $storage->_get_dbh;
208
209 # no fsync on commit
210 $dbh->do ('PRAGMA synchronous = OFF');
211
4f6eb3d8 212 if (
213 $ENV{DBICTEST_SQLITE_REVERSE_DEFAULT_ORDER}
214 and
215 # the pragma does not work correctly before libsqlite 3.7.9
216 $storage->_server_info->{normalized_dbms_version} >= 3.007009
217 ) {
4a24dba9 218 $dbh->do ('PRAGMA reverse_unordered_selects = ON');
219 }
fb88ca2c 220
a258bfc7 221 # set a *DBI* disconnect callback, to make sure the physical SQLite
222 # file is still there (i.e. the test does not attempt to delete
223 # an open database, which fails on Win32)
e1ff35c4 224 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
a258bfc7 225 $dbh->{Callbacks} = {
d9c17594 226 connect => sub { $guard_cb->('connect') },
227 disconnect => sub { $guard_cb->('disconnect') },
228 DESTROY => sub { $guard_cb->('DESTROY') },
a258bfc7 229 };
230 }
231 },
232 %args,
233 });
579ca3f7 234}
235
d9c17594 236sub __mk_disconnect_guard {
0d8817bc 237 return if DBIx::Class::_ENV_::PEEPEENESS; # leaks handles, delaying DESTROY, can't work right
d12d8272 238
d9c17594 239 my $db_file = shift;
240 return unless -f $db_file;
241
242 my $orig_inode = (stat($db_file))[1]
243 or return;
244
245 my $clan_connect_caller = '*UNKNOWN*';
246 my $i;
247 while ( my ($pack, $file, $line) = caller(++$i) ) {
248 next if $file eq __FILE__;
249 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
250 $clan_connect_caller = "$file line $line";
251 }
252
253 my $failed_once = 0;
254 my $connected = 1;
255
256 return sub {
257 return if $failed_once;
258
259 my $event = shift;
260 if ($event eq 'connect') {
261 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
262 $connected = 1;
263 return;
264 }
265 elsif ($event eq 'disconnect') {
266 $connected = 0;
267 }
268 elsif ($event eq 'DESTROY' and ! $connected ) {
269 return;
270 }
271
272 my $fail_reason;
273 if (! -e $db_file) {
274 $fail_reason = 'is missing';
275 }
276 else {
277 my $cur_inode = (stat($db_file))[1];
278
279 if ($orig_inode != $cur_inode) {
2525160d 280 my @inodes = ($orig_inode, $cur_inode);
281 # unless this is a fixed perl (P5RT#84590) pack/unpack before display
282 # to match the unsigned longs returned by `stat`
283 @inodes = map { unpack ('L', pack ('l', $_) ) } @inodes
284 unless $Config{st_ino_size};
285
286 $fail_reason = sprintf
287 'was recreated (initially inode %s, now %s)',
288 @inodes
289 ;
d9c17594 290 }
291 }
292
293 if ($fail_reason) {
294 $failed_once++;
295
296 require Test::Builder;
297 my $t = Test::Builder->new;
298 local $Test::Builder::Level = $Test::Builder::Level + 3;
299 $t->ok (0,
300 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
301 . 'of DBI handle - a strong indicator that the database file was tampered with while '
302 . 'still being open. This action would fail massively if running under Win32, hence '
303 . 'we make sure it fails on any OS :)'
304 );
305 }
306
307 return; # this empty return is a DBI requirement
308 };
309}
310
65d35121 311my $weak_registry = {};
312
579ca3f7 313sub init_schema {
314 my $self = shift;
315 my %args = @_;
316
317 my $schema;
d7a58a29 318
640ac94c 319 if ($args{compose_connection}) {
320 $schema = DBICTest::Schema->compose_connection(
481df957 321 'DBICTest', $self->_database(%args)
640ac94c 322 );
323 } else {
324 $schema = DBICTest::Schema->compose_namespace('DBICTest');
325 }
a258bfc7 326
2bf79155 327 if( $args{storage_type}) {
d7a58a29 328 $schema->storage_type($args{storage_type});
329 }
a258bfc7 330
579ca3f7 331 if ( !$args{no_connect} ) {
481df957 332 $schema = $schema->connect($self->_database(%args));
3943fd63 333 }
a258bfc7 334
17e7d7f0 335 if ( !$args{no_deploy} ) {
89cf6a70 336 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
337 __PACKAGE__->populate_schema( $schema )
338 if( !$args{no_populate} );
17e7d7f0 339 }
65d35121 340
341 populate_weakregistry ( $weak_registry, $schema->storage )
342 if $INC{'Test/Builder.pm'} and $schema->storage;
343
17e7d7f0 344 return $schema;
345}
346
65d35121 347END {
348 assert_empty_weakregistry($weak_registry, 'quiet');
349}
350
17e7d7f0 351=head2 deploy_schema
352
353 DBICTest->deploy_schema( $schema );
354
8273e845 355This method does one of two things to the schema. It can either call
356the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
357variable is set, otherwise the default is to read in the t/lib/sqlite.sql
358file and execute the SQL within. Either way you end up with a fresh set
17e7d7f0 359of tables for testing.
360
361=cut
362
363sub deploy_schema {
364 my $self = shift;
89cf6a70 365 my $schema = shift;
366 my $args = shift || {};
17e7d7f0 367
f8200928 368 local $schema->storage->{debug}
369 if ($ENV{TRAVIS}||'') eq 'true';
370
8273e845 371 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
06e15b8e 372 $schema->deploy($args);
17e7d7f0 373 } else {
de306d4b 374 my $filename = Path::Class::File->new(__FILE__)->dir
375 ->file('sqlite.sql')->stringify;
376 my $sql = do { local (@ARGV, $/) = $filename ; <> };
ebf846e8 377 for my $chunk ( split (/;\s*\n+/, $sql) ) {
378 if ( $chunk =~ / ^ (?! --\s* ) \S /xm ) { # there is some real sql in the chunk - a non-space at the start of the string which is not a comment
856e2d17 379 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
ebf846e8 380 }
381 }
17e7d7f0 382 }
89cf6a70 383 return;
17e7d7f0 384}
385
386=head2 populate_schema
387
388 DBICTest->populate_schema( $schema );
389
8273e845 390After you deploy your schema you can use this method to populate
17e7d7f0 391the tables with test data.
392
393=cut
394
395sub populate_schema {
396 my $self = shift;
397 my $schema = shift;
398
f8200928 399 local $schema->storage->{debug}
400 if ($ENV{TRAVIS}||'') eq 'true';
401
972015a7 402 $schema->populate('Genre', [
403 [qw/genreid name/],
404 [qw/1 emo /],
405 ]);
406
17e7d7f0 407 $schema->populate('Artist', [
77211009 408 [ qw/artistid name/ ],
409 [ 1, 'Caterwauler McCrae' ],
410 [ 2, 'Random Boy Band' ],
411 [ 3, 'We Are Goth' ],
17e7d7f0 412 ]);
413
414 $schema->populate('CD', [
972015a7 415 [ qw/cdid artist title year genreid/ ],
416 [ 1, 1, "Spoonful of bees", 1999, 1 ],
17e7d7f0 417 [ 2, 1, "Forkful of bees", 2001 ],
418 [ 3, 1, "Caterwaulin' Blues", 1997 ],
419 [ 4, 2, "Generic Manufactured Singles", 2001 ],
420 [ 5, 3, "Come Be Depressed With Us", 1998 ],
421 ]);
422
423 $schema->populate('LinerNotes', [
424 [ qw/liner_id notes/ ],
425 [ 2, "Buy Whiskey!" ],
426 [ 4, "Buy Merch!" ],
427 [ 5, "Kill Yourself!" ],
428 ]);
429
430 $schema->populate('Tag', [
431 [ qw/tagid cd tag/ ],
432 [ 1, 1, "Blue" ],
433 [ 2, 2, "Blue" ],
434 [ 3, 3, "Blue" ],
435 [ 4, 5, "Blue" ],
436 [ 5, 2, "Cheesy" ],
437 [ 6, 4, "Cheesy" ],
438 [ 7, 5, "Cheesy" ],
439 [ 8, 2, "Shiny" ],
440 [ 9, 4, "Shiny" ],
441 ]);
442
443 $schema->populate('TwoKeys', [
444 [ qw/artist cd/ ],
445 [ 1, 1 ],
446 [ 1, 2 ],
447 [ 2, 2 ],
448 ]);
449
450 $schema->populate('FourKeys', [
3bd6e3e0 451 [ qw/foo bar hello goodbye sensors/ ],
452 [ 1, 2, 3, 4, 'online' ],
453 [ 5, 4, 3, 6, 'offline' ],
17e7d7f0 454 ]);
455
456 $schema->populate('OneKey', [
457 [ qw/id artist cd/ ],
458 [ 1, 1, 1 ],
459 [ 2, 1, 2 ],
460 [ 3, 2, 2 ],
461 ]);
462
463 $schema->populate('SelfRef', [
464 [ qw/id name/ ],
465 [ 1, 'First' ],
466 [ 2, 'Second' ],
467 ]);
468
469 $schema->populate('SelfRefAlias', [
470 [ qw/self_ref alias/ ],
471 [ 1, 2 ]
472 ]);
473
474 $schema->populate('ArtistUndirectedMap', [
475 [ qw/id1 id2/ ],
476 [ 1, 2 ]
477 ]);
478
479 $schema->populate('Producer', [
480 [ qw/producerid name/ ],
481 [ 1, 'Matt S Trout' ],
482 [ 2, 'Bob The Builder' ],
483 [ 3, 'Fred The Phenotype' ],
484 ]);
485
486 $schema->populate('CD_to_Producer', [
487 [ qw/cd producer/ ],
488 [ 1, 1 ],
489 [ 1, 2 ],
490 [ 1, 3 ],
491 ]);
8273e845 492
8871d4ad 493 $schema->populate('TreeLike', [
61177e44 494 [ qw/id parent name/ ],
972015a7 495 [ 1, undef, 'root' ],
8871d4ad 496 [ 2, 1, 'foo' ],
497 [ 3, 2, 'bar' ],
498 [ 6, 2, 'blop' ],
499 [ 4, 3, 'baz' ],
500 [ 5, 4, 'quux' ],
501 [ 7, 3, 'fong' ],
502 ]);
4b8dcc58 503
17e7d7f0 504 $schema->populate('Track', [
505 [ qw/trackid cd position title/ ],
506 [ 4, 2, 1, "Stung with Success"],
507 [ 5, 2, 2, "Stripy"],
508 [ 6, 2, 3, "Sticky Honey"],
509 [ 7, 3, 1, "Yowlin"],
510 [ 8, 3, 2, "Howlin"],
511 [ 9, 3, 3, "Fowlin"],
512 [ 10, 4, 1, "Boring Name"],
513 [ 11, 4, 2, "Boring Song"],
514 [ 12, 4, 3, "No More Ideas"],
515 [ 13, 5, 1, "Sad"],
516 [ 14, 5, 2, "Under The Weather"],
517 [ 15, 5, 3, "Suicidal"],
518 [ 16, 1, 1, "The Bees Knees"],
519 [ 17, 1, 2, "Apiary"],
520 [ 18, 1, 3, "Beehind You"],
521 ]);
4b8dcc58 522
ae515736 523 $schema->populate('Event', [
ff8a6e3b 524 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
525 [ 1, '2006-04-25 22:24:33', '2006-06-22 21:00:05', '2006-07-23', '2006-05-22 19:05:07', '2006-04-21 18:04:06'],
ae515736 526 ]);
527
17e7d7f0 528 $schema->populate('Link', [
54e0bd06 529 [ qw/id url title/ ],
530 [ 1, '', 'aaa' ]
17e7d7f0 531 ]);
e673f011 532
17e7d7f0 533 $schema->populate('Bookmark', [
534 [ qw/id link/ ],
535 [ 1, 1 ]
536 ]);
78060df8 537
538 $schema->populate('Collection', [
539 [ qw/collectionid name/ ],
540 [ 1, "Tools" ],
541 [ 2, "Body Parts" ],
542 ]);
8273e845 543
78060df8 544 $schema->populate('TypedObject', [
545 [ qw/objectid type value/ ],
546 [ 1, "pointy", "Awl" ],
547 [ 2, "round", "Bearing" ],
548 [ 3, "pointy", "Knife" ],
549 [ 4, "pointy", "Tooth" ],
550 [ 5, "round", "Head" ],
551 ]);
89cf6a70 552 $schema->populate('CollectionObject', [
553 [ qw/collection object/ ],
554 [ 1, 1 ],
555 [ 1, 2 ],
556 [ 1, 3 ],
557 [ 2, 4 ],
558 [ 2, 5 ],
559 ]);
78060df8 560
561 $schema->populate('Owners', [
bed3a173 562 [ qw/id name/ ],
78060df8 563 [ 1, "Newton" ],
564 [ 2, "Waltham" ],
565 ]);
566
567 $schema->populate('BooksInLibrary', [
cda5e082 568 [ qw/id owner title source price/ ],
569 [ 1, 1, "Programming Perl", "Library", 23 ],
570 [ 2, 1, "Dynamical Systems", "Library", 37 ],
571 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],
78060df8 572 ]);
1c339d71 573}
4b8dcc58 574
510ca912 5751;