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