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