1 BEGIN { do "./t/lib/ANFANG.pm" or die ( $@ || $! ) }
2 use DBIx::Class::Optional::Dependencies -skip_all_without => 'test_rdbms_mysql';
12 use DBI::Const::GetInfoType;
13 use Scalar::Util qw/weaken/;
15 use DBICTest::Util 'PEEPEENESS';
18 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MYSQL_${_}" } qw/DSN USER PASS/};
20 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, { quote_names => 1 });
22 my $dbh = $schema->storage->dbh;
24 $dbh->do("DROP TABLE IF EXISTS artist;");
26 $dbh->do("CREATE TABLE artist (artistid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), rank INTEGER NOT NULL DEFAULT '13', charfield CHAR(10));");
28 $dbh->do("DROP TABLE IF EXISTS cd;");
30 $dbh->do("CREATE TABLE cd (cdid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, artist INTEGER, title TEXT, year DATE, genreid INTEGER, single_track INTEGER);");
32 $dbh->do("DROP TABLE IF EXISTS producer;");
34 $dbh->do("CREATE TABLE producer (producerid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, name TEXT);");
36 $dbh->do("DROP TABLE IF EXISTS cd_to_producer;");
38 $dbh->do("CREATE TABLE cd_to_producer (cd INTEGER,producer INTEGER);");
40 $dbh->do("DROP TABLE IF EXISTS owners;");
42 $dbh->do("CREATE TABLE owners (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL);");
44 $dbh->do("DROP TABLE IF EXISTS books;");
46 $dbh->do("CREATE TABLE books (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, source VARCHAR(100) NOT NULL, owner integer NOT NULL, title varchar(100) NOT NULL, price integer);");
48 #'dbi:mysql:host=localhost;database=dbic_test', 'dbic_test', '');
50 # make sure sqlt_type overrides work (::Storage::DBI::mysql does this)
52 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
54 ok (!$schema->storage->_dbh, 'definitely not connected');
55 is ($schema->storage->sqlt_type, 'MySQL', 'sqlt_type correct pre-connection');
58 # This is in Core now, but it's here just to test that it doesn't break
59 $schema->class('Artist')->load_components('PK::Auto');
61 # test primary key handling
62 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
63 ok($new->artistid, "Auto-PK worked");
67 $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
69 my $it = $schema->resultset('Artist')->search( {},
72 order_by => 'artistid' }
74 is( $it->count, 3, "LIMIT count ok" ); # ask for 3 rows out of 7 artists
75 is( $it->next->name, "Artist 2", "iterator->next ok" );
78 is( $it->next, undef, "next past end of resultset ok" );
80 # Limit with select-lock
82 $schema->txn_do (sub {
84 $schema->resultset('Artist')->find({artistid => 1}, {for => 'update', rows => 1}),
85 'DBICTest::Schema::Artist',
88 } 'Limited FOR UPDATE select works';
92 $schema->txn_do (sub {
94 $schema->resultset('Artist')->find({artistid => 1}, {for => 'shared'}),
95 'DBICTest::Schema::Artist',
98 } 'LOCK IN SHARE MODE select works';
100 my ($int_type_name, @undef_default) = DBIx::Class::_ENV_::STRESSTEST_COLUMN_INFO_UNAWARE_STORAGE
102 : ( 'INT', default_value => undef )
105 my $test_type_info = {
107 'data_type' => $int_type_name,
113 'data_type' => 'VARCHAR',
119 'data_type' => $int_type_name,
122 DBIx::Class::_ENV_::STRESSTEST_COLUMN_INFO_UNAWARE_STORAGE ? () : ( 'default_value' => '13' ),
125 'data_type' => 'CHAR',
132 $schema->populate ('Owners', [
139 $schema->populate ('BooksInLibrary', [
140 [qw/source owner title /],
141 [qw/Library 1 secrets1/],
142 [qw/Eatery 1 secrets2/],
143 [qw/Library 2 secrets3/],
147 # try a distinct + prefetch on tables with identically named columns
148 # (mysql doesn't seem to like subqueries with equally named columns)
152 # try a ->has_many direction (due to a 'multi' accessor the select/group_by group is collapsed)
153 my $owners = $schema->resultset ('Owners')->search (
154 { 'books.id' => { '!=', undef }},
155 { prefetch => 'books', distinct => 1 }
157 my $owners2 = $schema->resultset ('Owners')->search ({ id => { -in => $owners->get_column ('me.id')->as_query }});
158 for ($owners, $owners2) {
159 is ($_->all, 2, 'Prefetched grouped search returns correct number of rows');
160 is ($_->count, 2, 'Prefetched grouped search returns correct count');
163 # try a ->belongs_to direction (no select collapse)
164 my $books = $schema->resultset ('BooksInLibrary')->search (
165 { 'owner.name' => 'wiggle' },
166 { prefetch => 'owner', distinct => 1 }
168 my $books2 = $schema->resultset ('BooksInLibrary')->search ({ id => { -in => $books->get_column ('me.id')->as_query }});
169 for ($books, $books2) {
170 is ($_->all, 1, 'Prefetched grouped search returns correct number of rows');
171 is ($_->count, 1, 'Prefetched grouped search returns correct count');
176 my $norm_version = $schema->storage->_server_info->{normalized_dbms_version}
177 or skip "Cannot determine MySQL server version", 1;
179 if ($norm_version < 5.000003_01) {
180 $test_type_info->{charfield}->{data_type} = 'VARCHAR';
183 if (DBIx::Class::_ENV_::STRESSTEST_COLUMN_INFO_UNAWARE_STORAGE) {
184 $_->{data_type} = lc $_->{data_type} for values %$test_type_info;
187 my $type_info = $schema->storage->columns_info_for('artist');
188 is_deeply($type_info, $test_type_info, 'columns_info_for - column data types');
191 my $cd = $schema->resultset ('CD')->create ({});
192 my $producer = $schema->resultset ('Producer')->create ({});
193 lives_ok { $cd->set_producers ([ $producer ]) } 'set_relationship doesnt die';
196 my $artist = $schema->resultset('Artist')->next;
197 my $cd = $schema->resultset('CD')->next;
198 $cd->set_from_related ('artist', $artist);
201 my $rs = $schema->resultset('CD')->search ({}, { prefetch => 'artist' });
205 is ($cd->artist->name, $artist->name, 'Prefetched artist');
206 }, 'join does not throw (mysql 3 test)';
209 ## Can we properly deal with the null search problem?
211 ## Only way is to do a SET SQL_AUTO_IS_NULL = 0; on connect
212 ## But I'm not sure if we should do this or not (Ash, 2008/06/03)
214 # There is now a built-in function to do this, test that everything works
215 # with it (ribasushi, 2009/07/03)
218 my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, { on_connect_call => 'set_strict_mode' });
220 $ansi_schema->resultset('Artist')->create ({ name => 'last created artist' });
222 ok my $artist1_rs = $ansi_schema->resultset('Artist')->search({artistid=>6666})
223 => 'Created an artist resultset of 6666';
225 is $artist1_rs->count, 0
226 => 'Got no returned rows';
228 ok my $artist2_rs = $ansi_schema->resultset('Artist')->search({artistid=>undef})
229 => 'Created an artist resultset of undef';
231 is $artist2_rs->count, 0
234 my $artist = $artist2_rs->single;
240 # check for proper grouped counts
242 my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, {
243 on_connect_call => 'set_strict_mode',
246 my $rs = $ansi_schema->resultset('CD');
249 $years->{$_->year|| scalar keys %$years}++ for $rs->all; # NULL != NULL, thus the keys eval
253 $rs->search ({}, { group_by => 'year'})->count,
255 'grouped count correct',
257 }, 'Grouped count does not throw');
260 $ansi_schema->resultset('Owners')->search({}, {
261 join => 'books', group_by => [ 'me.id', 'books.id' ]
263 }, 'count on grouped columns with the same name does not throw');
266 # a more contrived^Wcomplicated self-referential double-subquery test
268 my $rs = $schema->resultset('Artist')->search({ name => { -like => 'baby_%' } });
270 $rs->populate([map { [$_] } ('name', map { "baby_$_" } (1..10) ) ]);
272 my ($count_sql, @count_bind) = @${$rs->count_rs->as_query};
274 my $complex_rs = $schema->resultset('Artist')->search(
276 -in => $rs->get_column('artistid')
281 $complex_rs->update({ name => \[ "CONCAT( `name`, '_bell_out_of_', $count_sql )", @count_bind ] });
285 $schema->resultset('Artist')->search({ name => "baby_${_}_bell_out_of_10" })->count,
287 "Correctly updated babybell $_",
291 is ($rs->count, 10, '10 artists present');
293 $schema->is_executed_querycount( sub {
295 }, 1, 'One delete query fired' );
296 is ($rs->count, 0, '10 Artists correctly deleted');
299 name => 'baby_with_cd',
300 cds => [ { title => 'babeeeeee', year => 2013 } ],
302 is ($rs->count, 1, 'Artist with cd created');
305 $schema->is_executed_querycount( sub {
306 $schema->resultset('CD')->search_related('artist',
307 { 'artist.name' => { -like => 'baby_with_%' } }
309 }, 1, 'And one more delete query fired');
310 is ($rs->count, 0, 'Artist with cd deleted');
320 my $rs = $schema->resultset ('CD');
322 for my $y (keys %$cds_per_year) {
323 for my $c (1 .. $cds_per_year->{$y} ) {
324 $rs->create ({ title => "CD $y-$c", artist => 1, year => "$y-01-01" });
328 is ($rs->count, 6, 'CDs created successfully');
330 $rs = $rs->search ({}, {
331 select => [ \ 'YEAR(year)' ], as => ['y'], distinct => 1,
334 my $y_rs = $rs->get_column ('y');
336 warnings_exist { is_deeply (
337 [ sort ($y_rs->all) ],
338 [ sort keys %$cds_per_year ],
339 'Years group successfully',
341 \QUse of distinct => 1 while selecting anything other than a column \E
342 \Qdeclared on the primary ResultSource is deprecated\E
343 /x, 'deprecation warning';
346 $rs->create ({ artist => 1, year => '0-1-1', title => 'Jesus Rap' });
350 [ 0, sort keys %$cds_per_year ],
351 'Zero-year groups successfully',
354 # convoluted search taken verbatim from list
355 my $restrict_rs = $rs->search({ -and => [
357 year => { '!=', undef }
360 warnings_exist { is_deeply (
361 [ sort $restrict_rs->get_column('y')->all ],
363 'Zero year was correctly excluded from resultset',
365 \QUse of distinct => 1 while selecting anything other than a column \E
366 \Qdeclared on the primary ResultSource is deprecated\E
367 /x, 'deprecation warning';
370 # make sure find hooks determine driver
372 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
373 $schema->resultset("Artist")->find(4);
374 isa_ok($schema->storage->sql_maker, 'DBIx::Class::SQLMaker::MySQL');
377 # make sure the mysql_auto_reconnect buggery is avoided
379 local $ENV{MOD_PERL} = 'boogiewoogie';
380 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
381 ok (! $schema->storage->_get_dbh->{mysql_auto_reconnect}, 'mysql_auto_reconnect unset regardless of ENV' );
383 # Make sure hardcore forking action still works even if mysql_auto_reconnect
384 # is true (test inspired by ether)
386 my $schema_autorecon = DBICTest::Schema->connect($dsn, $user, $pass, { mysql_auto_reconnect => 1 });
387 my $orig_dbh = $schema_autorecon->storage->_get_dbh;
390 ok ($orig_dbh, 'Got weak $dbh ref');
391 ok ($orig_dbh->{mysql_auto_reconnect}, 'mysql_auto_reconnect is properly set if explicitly requested' );
393 my $rs = $schema_autorecon->resultset('Artist');
395 my ($parent_in, $child_out);
396 pipe( $parent_in, $child_out ) or die "Pipe open failed: $!";
398 if (! defined $pid ) {
399 die "fork() failed: $!"
405 $schema_autorecon->storage->dbh_do(sub {
406 is ($_[1], $orig_dbh, 'Storage holds correct $dbh in parent');
410 $schema_autorecon->storage->_dbh(undef);
413 local $TODO = "Perl $] is known to leak like a sieve"
416 ok (! defined $orig_dbh, 'Parent $dbh handle is gone');
422 #simulate a subtest to not confuse the parent TAP emission
423 my $tb = Test::More->builder;
425 for (qw/output failure_output todo_output/) {
427 open ($tb->$_, '>&', $child_out);
430 # wait for parent to kill its $dbh
433 # try to do something dbic-esque
434 $rs->create({ name => "Hardcore Forker $$" });
437 local $TODO = "Perl $] is known to leak like a sieve"
440 ok (! defined $orig_dbh, 'DBIC operation triggered reconnect - old $dbh is gone');
447 while (my $ln = <$parent_in>) {
451 ok(!$?, 'Child subtests passed');
453 ok ($rs->find({ name => "Hardcore Forker $pid" }), 'Expected row created');
456 # Ensure disappearing RDBMS does not leave the storage in an inconsistent state
457 # Unlike the test in storage/reconnect.t we test live RDBMS-side disconnection
463 my $g = $schema->txn_scope_guard;
465 is( $schema->storage->transaction_depth, 1, "Expected txn depth" );
467 $schema->storage->_dbh->do("SELECT SLEEP(2)");
471 $schema->txn_do(sub {
472 is( $schema->storage->transaction_depth, 1, "Expected txn depth" );
473 $schema->storage->_dbh->do("SELECT SLEEP(2)")
479 my $g = $schema->txn_scope_guard;
481 $schema->txn_do(sub {
482 is( $schema->storage->transaction_depth, 2, "Expected txn depth" );
483 $schema->storage->_dbh->do("SELECT SLEEP(2)")
487 # version needed for the "read_timeout" feature
488 DBIx::Class::Optional::Dependencies->skip_without( 'DBD::mysql>=4.023' );
490 note( "Testing with " . B::Deparse->new->coderef2text($cref) );
492 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, {
493 mysql_read_timeout => 1,
496 ok( !$schema->storage->connected, 'Not connected' );
498 is( $schema->storage->transaction_depth, undef, "Start with unknown txn depth" );
502 } qr/Rollback failed/;
504 ok( !$schema->storage->connected, 'Not connected as a result of failed rollback' );
506 is( $schema->storage->transaction_depth, undef, "Depth expectedly unknown after failed rollbacks" );
508 ok( $schema->resultset('Artist')->count, 'query works after the fact' );