1 package # hide from PAUSE
8 use DBICTest::Util qw/populate_weakregistry assert_empty_weakregistry/;
10 use Path::Class::File ();
14 DBICTest - Library to be used by DBIx::Class test scripts.
22 my $schema = DBICTest->init_schema();
26 This module provides the basic utilities to write tests against
33 my $schema = DBICTest->init_schema(
36 storage_type=>'::DBI::Replicated',
38 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
42 This method removes the test SQLite database in t/var/DBIxClass.db
43 and then creates a new, empty database.
45 This method will call deploy_schema() by default, unless the
46 no_deploy flag is set.
48 Also, by default, this method will call populate_schema() by
49 default, unless the no_deploy or no_populate flags are set.
54 return $ENV{"DBICTEST_DSN"} ? 1:0;
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;
66 return $self->_sqlite_dbfilename if $args{sqlite_use_file} or $ENV{"DBICTEST_SQLITE_USE_FILE"};
74 if ($ENV{DBICTEST_DSN}) {
76 (map { $ENV{"DBICTEST_${_}"} || '' } qw/DSN DBUSER DBPASS/),
77 { AutoCommit => 1, %args },
80 my $db_file = $self->_sqlite_dbname(%args);
82 for ($db_file, "${db_file}-journal") {
85 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
89 return ("dbi:SQLite:${db_file}", '', '', {
92 # this is executed on every connect, and thus installs a disconnect/DESTROY
93 # guard for every new $dbh
94 on_connect_do => sub {
96 my $dbh = $storage->_get_dbh;
99 $dbh->do ('PRAGMA synchronous = OFF');
101 # set a *DBI* disconnect callback, to make sure the physical SQLite
102 # file is still there (i.e. the test does not attempt to delete
103 # an open database, which fails on Win32)
104 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
105 $dbh->{Callbacks} = {
106 connect => sub { $guard_cb->('connect') },
107 disconnect => sub { $guard_cb->('disconnect') },
108 DESTROY => sub { $guard_cb->('DESTROY') },
116 sub __mk_disconnect_guard {
117 return if DBIx::Class::_ENV_::PEEPEENESS(); # leaks handles, delaying DESTROY, can't work right
120 return unless -f $db_file;
122 my $orig_inode = (stat($db_file))[1]
125 my $clan_connect_caller = '*UNKNOWN*';
127 while ( my ($pack, $file, $line) = caller(++$i) ) {
128 next if $file eq __FILE__;
129 next if $pack =~ /^DBIx::Class|^Try::Tiny/;
130 $clan_connect_caller = "$file line $line";
137 return if $failed_once;
140 if ($event eq 'connect') {
141 # this is necessary in case we are disconnected and connected again, all within the same $dbh object
145 elsif ($event eq 'disconnect') {
148 elsif ($event eq 'DESTROY' and ! $connected ) {
154 $fail_reason = 'is missing';
157 my $cur_inode = (stat($db_file))[1];
159 if ($orig_inode != $cur_inode) {
160 # pack/unpack to match the unsigned longs returned by `stat`
161 $fail_reason = sprintf 'was recreated (initially inode %s, now %s)', (
162 map { unpack ('L', pack ('l', $_) ) } ($orig_inode, $cur_inode )
170 require Test::Builder;
171 my $t = Test::Builder->new;
172 local $Test::Builder::Level = $Test::Builder::Level + 3;
174 "$db_file originally created at $clan_connect_caller $fail_reason before $event "
175 . 'of DBI handle - a strong indicator that the database file was tampered with while '
176 . 'still being open. This action would fail massively if running under Win32, hence '
177 . 'we make sure it fails on any OS :)'
181 return; # this empty return is a DBI requirement
185 my $weak_registry = {};
193 if ($args{compose_connection}) {
194 $schema = DBICTest::Schema->compose_connection(
195 'DBICTest', $self->_database(%args)
198 $schema = DBICTest::Schema->compose_namespace('DBICTest');
201 if( $args{storage_type}) {
202 $schema->storage_type($args{storage_type});
205 if ( !$args{no_connect} ) {
206 $schema = $schema->connect($self->_database(%args));
209 if ( !$args{no_deploy} ) {
210 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
211 __PACKAGE__->populate_schema( $schema )
212 if( !$args{no_populate} );
215 populate_weakregistry ( $weak_registry, $schema->storage )
216 if $INC{'Test/Builder.pm'} and $schema->storage;
222 assert_empty_weakregistry($weak_registry, 'quiet');
227 DBICTest->deploy_schema( $schema );
229 This method does one of two things to the schema. It can either call
230 the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
231 variable is set, otherwise the default is to read in the t/lib/sqlite.sql
232 file and execute the SQL within. Either way you end up with a fresh set
233 of tables for testing.
240 my $args = shift || {};
242 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
243 $schema->deploy($args);
245 my $filename = Path::Class::File->new(__FILE__)->dir
246 ->file('sqlite.sql')->stringify;
247 my $sql = do { local (@ARGV, $/) = $filename ; <> };
248 for my $chunk ( split (/;\s*\n+/, $sql) ) {
249 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
250 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
257 =head2 populate_schema
259 DBICTest->populate_schema( $schema );
261 After you deploy your schema you can use this method to populate
262 the tables with test data.
266 sub populate_schema {
270 $schema->populate('Genre', [
275 $schema->populate('Artist', [
276 [ qw/artistid name/ ],
277 [ 1, 'Caterwauler McCrae' ],
278 [ 2, 'Random Boy Band' ],
279 [ 3, 'We Are Goth' ],
282 $schema->populate('CD', [
283 [ qw/cdid artist title year genreid/ ],
284 [ 1, 1, "Spoonful of bees", 1999, 1 ],
285 [ 2, 1, "Forkful of bees", 2001 ],
286 [ 3, 1, "Caterwaulin' Blues", 1997 ],
287 [ 4, 2, "Generic Manufactured Singles", 2001 ],
288 [ 5, 3, "Come Be Depressed With Us", 1998 ],
291 $schema->populate('LinerNotes', [
292 [ qw/liner_id notes/ ],
293 [ 2, "Buy Whiskey!" ],
295 [ 5, "Kill Yourself!" ],
298 $schema->populate('Tag', [
299 [ qw/tagid cd tag/ ],
311 $schema->populate('TwoKeys', [
318 $schema->populate('FourKeys', [
319 [ qw/foo bar hello goodbye sensors/ ],
320 [ 1, 2, 3, 4, 'online' ],
321 [ 5, 4, 3, 6, 'offline' ],
324 $schema->populate('OneKey', [
325 [ qw/id artist cd/ ],
331 $schema->populate('SelfRef', [
337 $schema->populate('SelfRefAlias', [
338 [ qw/self_ref alias/ ],
342 $schema->populate('ArtistUndirectedMap', [
347 $schema->populate('Producer', [
348 [ qw/producerid name/ ],
349 [ 1, 'Matt S Trout' ],
350 [ 2, 'Bob The Builder' ],
351 [ 3, 'Fred The Phenotype' ],
354 $schema->populate('CD_to_Producer', [
361 $schema->populate('TreeLike', [
362 [ qw/id parent name/ ],
363 [ 1, undef, 'root' ],
372 $schema->populate('Track', [
373 [ qw/trackid cd position title/ ],
374 [ 4, 2, 1, "Stung with Success"],
375 [ 5, 2, 2, "Stripy"],
376 [ 6, 2, 3, "Sticky Honey"],
377 [ 7, 3, 1, "Yowlin"],
378 [ 8, 3, 2, "Howlin"],
379 [ 9, 3, 3, "Fowlin"],
380 [ 10, 4, 1, "Boring Name"],
381 [ 11, 4, 2, "Boring Song"],
382 [ 12, 4, 3, "No More Ideas"],
384 [ 14, 5, 2, "Under The Weather"],
385 [ 15, 5, 3, "Suicidal"],
386 [ 16, 1, 1, "The Bees Knees"],
387 [ 17, 1, 2, "Apiary"],
388 [ 18, 1, 3, "Beehind You"],
391 $schema->populate('Event', [
392 [ qw/id starts_at created_on varchar_date varchar_datetime skip_inflation/ ],
393 [ 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 $schema->populate('Link', [
397 [ qw/id url title/ ],
401 $schema->populate('Bookmark', [
406 $schema->populate('Collection', [
407 [ qw/collectionid name/ ],
412 $schema->populate('TypedObject', [
413 [ qw/objectid type value/ ],
414 [ 1, "pointy", "Awl" ],
415 [ 2, "round", "Bearing" ],
416 [ 3, "pointy", "Knife" ],
417 [ 4, "pointy", "Tooth" ],
418 [ 5, "round", "Head" ],
420 $schema->populate('CollectionObject', [
421 [ qw/collection object/ ],
429 $schema->populate('Owners', [
435 $schema->populate('BooksInLibrary', [
436 [ qw/id owner title source price/ ],
437 [ 1, 1, "Programming Perl", "Library", 23 ],
438 [ 2, 1, "Dynamical Systems", "Library", 37 ],
439 [ 3, 2, "Best Recipe Cookbook", "Library", 65 ],