Fix failures with DBICTEST_SQLITE_USE_FILE=1 introduced by 50261284
[dbsrgits/DBIx-Class-Historic.git] / t / lib / DBICTest.pm
1 package # hide from PAUSE
2     DBICTest;
3
4 use strict;
5 use warnings;
6 use DBICTest::RunMode;
7 use DBICTest::Schema;
8 use DBICTest::Util qw/populate_weakregistry assert_empty_weakregistry/;
9 use Carp;
10 use Path::Class::File ();
11
12 =head1 NAME
13
14 DBICTest - Library to be used by DBIx::Class test scripts.
15
16 =head1 SYNOPSIS
17
18   use lib qw(t/lib);
19   use DBICTest;
20   use Test::More;
21
22   my $schema = DBICTest->init_schema();
23
24 =head1 DESCRIPTION
25
26 This module provides the basic utilities to write tests against
27 DBIx::Class.
28
29 =head1 METHODS
30
31 =head2 init_schema
32
33   my $schema = DBICTest->init_schema(
34     no_deploy=>1,
35     no_populate=>1,
36     storage_type=>'::DBI::Replicated',
37     storage_type_args=>{
38       balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
39     },
40   );
41
42 This method removes the test SQLite database in t/var/DBIxClass.db
43 and then creates a new, empty database.
44
45 This method will call deploy_schema() by default, unless the
46 no_deploy flag is set.
47
48 Also, by default, this method will call populate_schema() by
49 default, unless the no_deploy or no_populate flags are set.
50
51 =cut
52
53 sub has_custom_dsn {
54     return $ENV{"DBICTEST_DSN"} ? 1:0;
55 }
56
57 sub _sqlite_dbfilename {
58     my $dir = Path::Class::File->new(__FILE__)->dir->parent->subdir('var');
59     $dir->mkpath unless -d "$dir";
60     return $dir->file('DBIxClass.db')->stringify;
61 }
62
63 sub _sqlite_dbname {
64     my $self = shift;
65     my %args = @_;
66     return $self->_sqlite_dbfilename if (
67       defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
68     );
69     return ":memory:";
70 }
71
72 sub _database {
73     my $self = shift;
74     my %args = @_;
75
76     if ($ENV{DBICTEST_DSN}) {
77       return (
78         (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
79         { AutoCommit => 1, %args },
80       );
81     }
82     my $db_file = $self->_sqlite_dbname(%args);
83
84     for ($db_file, "${db_file}-journal") {
85       next unless -e $_;
86       unlink ($_) or carp (
87         "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
88       );
89     }
90
91     return ("dbi:SQLite:${db_file}", '', '', {
92       AutoCommit => 1,
93
94       # this is executed on every connect, and thus installs a disconnect/DESTROY
95       # guard for every new $dbh
96       on_connect_do => sub {
97         my $storage = shift;
98         my $dbh = $storage->_get_dbh;
99
100         # no fsync on commit
101         $dbh->do ('PRAGMA synchronous = OFF');
102
103         # set a *DBI* disconnect callback, to make sure the physical SQLite
104         # file is still there (i.e. the test does not attempt to delete
105         # an open database, which fails on Win32)
106         if (my $guard_cb = __mk_disconnect_guard($db_file)) {
107           $dbh->{Callbacks} = {
108             connect => sub { $guard_cb->('connect') },
109             disconnect => sub { $guard_cb->('disconnect') },
110             DESTROY => sub { $guard_cb->('DESTROY') },
111           };
112         }
113       },
114       %args,
115     });
116 }
117
118 sub __mk_disconnect_guard {
119   return if DBIx::Class::_ENV_::PEEPEENESS(); # leaks handles, delaying DESTROY, can't work right
120
121   my $db_file = shift;
122   return unless -f $db_file;
123
124   my $orig_inode = (stat($db_file))[1]
125     or return;
126
127   my $clan_connect_caller = '*UNKNOWN*';
128   my $i;
129   while ( my ($pack, $file, $line) = caller(++$i) ) {
130     next if $file eq __FILE__;
131     next if $pack =~ /^DBIx::Class|^Try::Tiny/;
132     $clan_connect_caller = "$file line $line";
133   }
134
135   my $failed_once = 0;
136   my $connected = 1;
137
138   return sub {
139     return if $failed_once;
140
141     my $event = shift;
142     if ($event eq 'connect') {
143       # this is necessary in case we are disconnected and connected again, all within the same $dbh object
144       $connected = 1;
145       return;
146     }
147     elsif ($event eq 'disconnect') {
148       $connected = 0;
149     }
150     elsif ($event eq 'DESTROY' and ! $connected ) {
151       return;
152     }
153
154     my $fail_reason;
155     if (! -e $db_file) {
156       $fail_reason = 'is missing';
157     }
158     else {
159       my $cur_inode = (stat($db_file))[1];
160
161       if ($orig_inode != $cur_inode) {
162         # pack/unpack to match the unsigned longs returned by `stat`
163         $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
164           map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
165         );
166       }
167     }
168
169     if ($fail_reason) {
170       $failed_once++;
171
172       require Test::Builder;
173       my $t = Test::Builder->new;
174       local $Test::Builder::Level = $Test::Builder::Level + 3;
175       $t->ok (0,
176         "$db_file originally created at $clan_connect_caller $fail_reason before $event "
177       . 'of DBI handle - a strong indicator that the database file was tampered with while '
178       . 'still being open. This action would fail massively if running under Win32, hence '
179       . 'we make sure it fails on any OS :)'
180       );
181     }
182
183     return; # this empty return is a DBI requirement
184   };
185 }
186
187 my $weak_registry = {};
188
189 sub init_schema {
190     my $self = shift;
191     my %args = @_;
192
193     my $schema;
194
195     if ($args{compose_connection}) {
196       $schema = DBICTest::Schema->compose_connection(
197                   'DBICTest', $self->_database(%args)
198                 );
199     } else {
200       $schema = DBICTest::Schema->compose_namespace('DBICTest');
201     }
202
203     if( $args{storage_type}) {
204       $schema->storage_type($args{storage_type});
205     }
206
207     if ( !$args{no_connect} ) {
208       $schema = $schema->connect($self->_database(%args));
209     }
210
211     if ( !$args{no_deploy} ) {
212         __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
213         __PACKAGE__->populate_schema( $schema )
214          if( !$args{no_populate} );
215     }
216
217     populate_weakregistry ( $weak_registry, $schema->storage )
218       if $INC{'Test/Builder.pm'} and $schema->storage;
219
220     return $schema;
221 }
222
223 END {
224     assert_empty_weakregistry($weak_registry, 'quiet');
225 }
226
227 =head2 deploy_schema
228
229   DBICTest->deploy_schema( $schema );
230
231 This method does one of two things to the schema.  It can either call
232 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
233 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
234 file and execute the SQL within. Either way you end up with a fresh set
235 of tables for testing.
236
237 =cut
238
239 sub deploy_schema {
240     my $self = shift;
241     my $schema = shift;
242     my $args = shift || {};
243
244     if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
245         $schema->deploy($args);
246     } else {
247         my $filename = Path::Class::File->new(__FILE__)->dir
248           ->file('sqlite.sql')->stringify;
249         my $sql = do { local (@ARGV, $/) = $filename ; <> };
250         for my $chunk ( split (/;\s*\n+/, $sql) ) {
251           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
252             $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
253           }
254         }
255     }
256     return;
257 }
258
259 =head2 populate_schema
260
261   DBICTest->populate_schema( $schema );
262
263 After you deploy your schema you can use this method to populate
264 the tables with test data.
265
266 =cut
267
268 sub populate_schema {
269     my $self = shift;
270     my $schema = shift;
271
272     $schema->populate('Genre', [
273       [qw/genreid name/],
274       [qw/1       emo  /],
275     ]);
276
277     $schema->populate('Artist', [
278         [ qw/artistid name/ ],
279         [ 1, 'Caterwauler McCrae' ],
280         [ 2, 'Random Boy Band' ],
281         [ 3, 'We Are Goth' ],
282     ]);
283
284     $schema->populate('CD', [
285         [ qw/cdid artist title year genreid/ ],
286         [ 1, 1, "Spoonful of bees", 1999, 1 ],
287         [ 2, 1, "Forkful of bees", 2001 ],
288         [ 3, 1, "Caterwaulin' Blues", 1997 ],
289         [ 4, 2, "Generic Manufactured Singles", 2001 ],
290         [ 5, 3, "Come Be Depressed With Us", 1998 ],
291     ]);
292
293     $schema->populate('LinerNotes', [
294         [ qw/liner_id notes/ ],
295         [ 2, "Buy Whiskey!" ],
296         [ 4, "Buy Merch!" ],
297         [ 5, "Kill Yourself!" ],
298     ]);
299
300     $schema->populate('Tag', [
301         [ qw/tagid cd tag/ ],
302         [ 1, 1, "Blue" ],
303         [ 2, 2, "Blue" ],
304         [ 3, 3, "Blue" ],
305         [ 4, 5, "Blue" ],
306         [ 5, 2, "Cheesy" ],
307         [ 6, 4, "Cheesy" ],
308         [ 7, 5, "Cheesy" ],
309         [ 8, 2, "Shiny" ],
310         [ 9, 4, "Shiny" ],
311     ]);
312
313     $schema->populate('TwoKeys', [
314         [ qw/artist cd/ ],
315         [ 1, 1 ],
316         [ 1, 2 ],
317         [ 2, 2 ],
318     ]);
319
320     $schema->populate('FourKeys', [
321         [ qw/foo bar hello goodbye sensors/ ],
322         [ 1, 2, 3, 4, 'online' ],
323         [ 5, 4, 3, 6, 'offline' ],
324     ]);
325
326     $schema->populate('OneKey', [
327         [ qw/id artist cd/ ],
328         [ 1, 1, 1 ],
329         [ 2, 1, 2 ],
330         [ 3, 2, 2 ],
331     ]);
332
333     $schema->populate('SelfRef', [
334         [ qw/id name/ ],
335         [ 1, 'First' ],
336         [ 2, 'Second' ],
337     ]);
338
339     $schema->populate('SelfRefAlias', [
340         [ qw/self_ref alias/ ],
341         [ 1, 2 ]
342     ]);
343
344     $schema->populate('ArtistUndirectedMap', [
345         [ qw/id1 id2/ ],
346         [ 1, 2 ]
347     ]);
348
349     $schema->populate('Producer', [
350         [ qw/producerid name/ ],
351         [ 1, 'Matt S Trout' ],
352         [ 2, 'Bob The Builder' ],
353         [ 3, 'Fred The Phenotype' ],
354     ]);
355
356     $schema->populate('CD_to_Producer', [
357         [ qw/cd producer/ ],
358         [ 1, 1 ],
359         [ 1, 2 ],
360         [ 1, 3 ],
361     ]);
362
363     $schema->populate('TreeLike', [
364         [ qw/id parent name/ ],
365         [ 1, undef, 'root' ],
366         [ 2, 1, 'foo'  ],
367         [ 3, 2, 'bar'  ],
368         [ 6, 2, 'blop' ],
369         [ 4, 3, 'baz'  ],
370         [ 5, 4, 'quux' ],
371         [ 7, 3, 'fong'  ],
372     ]);
373
374     $schema->populate('Track', [
375         [ qw/trackid cd  position title/ ],
376         [ 4, 2, 1, "Stung with Success"],
377         [ 5, 2, 2, "Stripy"],
378         [ 6, 2, 3, "Sticky Honey"],
379         [ 7, 3, 1, "Yowlin"],
380         [ 8, 3, 2, "Howlin"],
381         [ 9, 3, 3, "Fowlin"],
382         [ 10, 4, 1, "Boring Name"],
383         [ 11, 4, 2, "Boring Song"],
384         [ 12, 4, 3, "No More Ideas"],
385         [ 13, 5, 1, "Sad"],
386         [ 14, 5, 2, "Under The Weather"],
387         [ 15, 5, 3, "Suicidal"],
388         [ 16, 1, 1, "The Bees Knees"],
389         [ 17, 1, 2, "Apiary"],
390         [ 18, 1, 3, "Beehind You"],
391     ]);
392
393     $schema->populate('Event', [
394         [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
395         [ 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'],
396     ]);
397
398     $schema->populate('Link', [
399         [ qw/id url title/ ],
400         [ 1, '', 'aaa' ]
401     ]);
402
403     $schema->populate('Bookmark', [
404         [ qw/id link/ ],
405         [ 1, 1 ]
406     ]);
407
408     $schema->populate('Collection', [
409         [ qw/collectionid name/ ],
410         [ 1, "Tools" ],
411         [ 2, "Body Parts" ],
412     ]);
413
414     $schema->populate('TypedObject', [
415         [ qw/objectid type value/ ],
416         [ 1, "pointy", "Awl" ],
417         [ 2, "round", "Bearing" ],
418         [ 3, "pointy", "Knife" ],
419         [ 4, "pointy", "Tooth" ],
420         [ 5, "round", "Head" ],
421     ]);
422     $schema->populate('CollectionObject', [
423         [ qw/collection object/ ],
424         [ 1, 1 ],
425         [ 1, 2 ],
426         [ 1, 3 ],
427         [ 2, 4 ],
428         [ 2, 5 ],
429     ]);
430
431     $schema->populate('Owners', [
432         [ qw/id name/ ],
433         [ 1, "Newton" ],
434         [ 2, "Waltham" ],
435     ]);
436
437     $schema->populate('BooksInLibrary', [
438         [ qw/id owner title source price/ ],
439         [ 1, 1, "Programming Perl", "Library", 23 ],
440         [ 2, 1, "Dynamical Systems", "Library",  37 ],
441         [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],
442     ]);
443 }
444
445 1;