improvements for MSSQL driver via DBD::ADO
[dbsrgits/DBIx-Class.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;
65d35121 8use DBICTest::Util qw/populate_weakregistry assert_empty_weakregistry/;
a258bfc7 9use Carp;
de306d4b 10use Path::Class::File ();
17e7d7f0 11
12=head1 NAME
13
14DBICTest - 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;
8273e845 21
17e7d7f0 22 my $schema = DBICTest->init_schema();
23
24=head1 DESCRIPTION
25
8273e845 26This module provides the basic utilities to write tests against
17e7d7f0 27DBIx::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,
2bf79155 36 storage_type=>'::DBI::Replicated',
cb6ec758 37 storage_type_args=>{
d7a58a29 38 balancer_type=>'DBIx::Class::Storage::DBI::Replicated::Balancer::Random'
cb6ec758 39 },
17e7d7f0 40 );
41
8273e845 42This method removes the test SQLite database in t/var/DBIxClass.db
17e7d7f0 43and then creates a new, empty database.
44
8273e845 45This method will call deploy_schema() by default, unless the
17e7d7f0 46no_deploy flag is set.
47
8273e845 48Also, by default, this method will call populate_schema() by
17e7d7f0 49default, unless the no_deploy or no_populate flags are set.
50
51=cut
1c339d71 52
857d66ca 53sub has_custom_dsn {
d7a58a29 54 return $ENV{"DBICTEST_DSN"} ? 1:0;
857d66ca 55}
56
57sub _sqlite_dbfilename {
de306d4b 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;
bcb3e850 61}
62
63sub _sqlite_dbname {
481df957 64 my $self = shift;
65 my %args = @_;
39b80a73 66 return $self->_sqlite_dbfilename if (
67 defined $args{sqlite_use_file} ? $args{sqlite_use_file} : $ENV{'DBICTEST_SQLITE_USE_FILE'}
68 );
d7a58a29 69 return ":memory:";
857d66ca 70}
71
579ca3f7 72sub _database {
17e7d7f0 73 my $self = shift;
481df957 74 my %args = @_;
17e7d7f0 75
a258bfc7 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);
17e7d7f0 83
a258bfc7 84 for ($db_file, "${db_file}-journal") {
85 next unless -e $_;
86 unlink ($_) or carp (
70c28808 87 "Unable to unlink existing test database file $_ ($!), creation of fresh database / further tests may fail!"
a258bfc7 88 );
89 }
17e7d7f0 90
a258bfc7 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)
d9c17594 106 if (my $guard_cb = __mk_disconnect_guard($db_file)) {
a258bfc7 107 $dbh->{Callbacks} = {
d9c17594 108 connect => sub { $guard_cb->('connect') },
109 disconnect => sub { $guard_cb->('disconnect') },
110 DESTROY => sub { $guard_cb->('DESTROY') },
a258bfc7 111 };
112 }
113 },
114 %args,
115 });
579ca3f7 116}
117
d9c17594 118sub __mk_disconnect_guard {
e0b2dc74 119 return if DBIx::Class::_ENV_::PEEPEENESS(); # leaks handles, delaying DESTROY, can't work right
d12d8272 120
d9c17594 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
65d35121 187my $weak_registry = {};
188
579ca3f7 189sub init_schema {
190 my $self = shift;
191 my %args = @_;
192
193 my $schema;
d7a58a29 194
640ac94c 195 if ($args{compose_connection}) {
196 $schema = DBICTest::Schema->compose_connection(
481df957 197 'DBICTest', $self->_database(%args)
640ac94c 198 );
199 } else {
200 $schema = DBICTest::Schema->compose_namespace('DBICTest');
201 }
a258bfc7 202
2bf79155 203 if( $args{storage_type}) {
d7a58a29 204 $schema->storage_type($args{storage_type});
205 }
a258bfc7 206
579ca3f7 207 if ( !$args{no_connect} ) {
481df957 208 $schema = $schema->connect($self->_database(%args));
3943fd63 209 }
a258bfc7 210
17e7d7f0 211 if ( !$args{no_deploy} ) {
89cf6a70 212 __PACKAGE__->deploy_schema( $schema, $args{deploy_args} );
213 __PACKAGE__->populate_schema( $schema )
214 if( !$args{no_populate} );
17e7d7f0 215 }
65d35121 216
217 populate_weakregistry ( $weak_registry, $schema->storage )
218 if $INC{'Test/Builder.pm'} and $schema->storage;
219
17e7d7f0 220 return $schema;
221}
222
65d35121 223END {
224 assert_empty_weakregistry($weak_registry, 'quiet');
225}
226
17e7d7f0 227=head2 deploy_schema
228
229 DBICTest->deploy_schema( $schema );
230
8273e845 231This method does one of two things to the schema. It can either call
232the experimental $schema->deploy() if the DBICTEST_SQLT_DEPLOY environment
233variable is set, otherwise the default is to read in the t/lib/sqlite.sql
234file and execute the SQL within. Either way you end up with a fresh set
17e7d7f0 235of tables for testing.
236
237=cut
238
239sub deploy_schema {
240 my $self = shift;
89cf6a70 241 my $schema = shift;
242 my $args = shift || {};
17e7d7f0 243
8273e845 244 if ($ENV{"DBICTEST_SQLT_DEPLOY"}) {
06e15b8e 245 $schema->deploy($args);
17e7d7f0 246 } else {
de306d4b 247 my $filename = Path::Class::File->new(__FILE__)->dir
248 ->file('sqlite.sql')->stringify;
249 my $sql = do { local (@ARGV, $/) = $filename ; <> };
ebf846e8 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
856e2d17 252 $schema->storage->dbh_do(sub { $_[1]->do($chunk) }) or print "Error on SQL: $chunk\n";
ebf846e8 253 }
254 }
17e7d7f0 255 }
89cf6a70 256 return;
17e7d7f0 257}
258
259=head2 populate_schema
260
261 DBICTest->populate_schema( $schema );
262
8273e845 263After you deploy your schema you can use this method to populate
17e7d7f0 264the tables with test data.
265
266=cut
267
268sub populate_schema {
269 my $self = shift;
270 my $schema = shift;
271
972015a7 272 $schema->populate('Genre', [
273 [qw/genreid name/],
274 [qw/1 emo /],
275 ]);
276
17e7d7f0 277 $schema->populate('Artist', [
77211009 278 [ qw/artistid name/ ],
279 [ 1, 'Caterwauler McCrae' ],
280 [ 2, 'Random Boy Band' ],
281 [ 3, 'We Are Goth' ],
17e7d7f0 282 ]);
283
284 $schema->populate('CD', [
972015a7 285 [ qw/cdid artist title year genreid/ ],
286 [ 1, 1, "Spoonful of bees", 1999, 1 ],
17e7d7f0 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', [
3bd6e3e0 321 [ qw/foo bar hello goodbye sensors/ ],
322 [ 1, 2, 3, 4, 'online' ],
323 [ 5, 4, 3, 6, 'offline' ],
17e7d7f0 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 ]);
8273e845 362
8871d4ad 363 $schema->populate('TreeLike', [
61177e44 364 [ qw/id parent name/ ],
972015a7 365 [ 1, undef, 'root' ],
8871d4ad 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 ]);
4b8dcc58 373
17e7d7f0 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 ]);
4b8dcc58 392
ae515736 393 $schema->populate('Event', [
ff8a6e3b 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'],
ae515736 396 ]);
397
17e7d7f0 398 $schema->populate('Link', [
54e0bd06 399 [ qw/id url title/ ],
400 [ 1, '', 'aaa' ]
17e7d7f0 401 ]);
e673f011 402
17e7d7f0 403 $schema->populate('Bookmark', [
404 [ qw/id link/ ],
405 [ 1, 1 ]
406 ]);
78060df8 407
408 $schema->populate('Collection', [
409 [ qw/collectionid name/ ],
410 [ 1, "Tools" ],
411 [ 2, "Body Parts" ],
412 ]);
8273e845 413
78060df8 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 ]);
89cf6a70 422 $schema->populate('CollectionObject', [
423 [ qw/collection object/ ],
424 [ 1, 1 ],
425 [ 1, 2 ],
426 [ 1, 3 ],
427 [ 2, 4 ],
428 [ 2, 5 ],
429 ]);
78060df8 430
431 $schema->populate('Owners', [
bed3a173 432 [ qw/id name/ ],
78060df8 433 [ 1, "Newton" ],
434 [ 2, "Waltham" ],
435 ]);
436
437 $schema->populate('BooksInLibrary', [
cda5e082 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 ],
78060df8 442 ]);
1c339d71 443}
4b8dcc58 444
510ca912 4451;