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