7 use DBI::Const::GetInfoType;
8 use Scalar::Util qw/weaken/;
9 use DBIx::Class::Optional::Dependencies ();
13 use DBIC::SqlMakerTest;
15 plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_rdbms_mysql')
16 unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_rdbms_mysql');
18 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MYSQL_${_}" } qw/DSN USER PASS/};
20 plan skip_all => 'Set $ENV{DBICTEST_MYSQL_DSN}, _USER and _PASS to run this test'
21 unless ($dsn && $user);
23 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, { quote_names => 1 });
25 my $dbh = $schema->storage->dbh;
27 $dbh->do("DROP TABLE IF EXISTS artist;");
29 $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));");
31 $dbh->do("DROP TABLE IF EXISTS cd;");
33 $dbh->do("CREATE TABLE cd (cdid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, artist INTEGER, title TEXT, year DATE, genreid INTEGER, single_track INTEGER);");
35 $dbh->do("DROP TABLE IF EXISTS producer;");
37 $dbh->do("CREATE TABLE producer (producerid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, name TEXT);");
39 $dbh->do("DROP TABLE IF EXISTS cd_to_producer;");
41 $dbh->do("CREATE TABLE cd_to_producer (cd INTEGER,producer INTEGER);");
43 $dbh->do("DROP TABLE IF EXISTS owners;");
45 $dbh->do("CREATE TABLE owners (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL);");
47 $dbh->do("DROP TABLE IF EXISTS books;");
49 $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);");
51 #'dbi:mysql:host=localhost;database=dbic_test', 'dbic_test', '');
53 # make sure sqlt_type overrides work (::Storage::DBI::mysql does this)
55 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
57 ok (!$schema->storage->_dbh, 'definitely not connected');
58 is ($schema->storage->sqlt_type, 'MySQL', 'sqlt_type correct pre-connection');
61 # This is in Core now, but it's here just to test that it doesn't break
62 $schema->class('Artist')->load_components('PK::Auto');
64 # test primary key handling
65 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
66 ok($new->artistid, "Auto-PK worked");
70 $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
72 my $it = $schema->resultset('Artist')->search( {},
75 order_by => 'artistid' }
77 is( $it->count, 3, "LIMIT count ok" ); # ask for 3 rows out of 7 artists
78 is( $it->next->name, "Artist 2", "iterator->next ok" );
81 is( $it->next, undef, "next past end of resultset ok" );
83 # Limit with select-lock
85 $schema->txn_do (sub {
87 $schema->resultset('Artist')->find({artistid => 1}, {for => 'update', rows => 1}),
88 'DBICTest::Schema::Artist',
91 } 'Limited FOR UPDATE select works';
95 $schema->txn_do (sub {
97 $schema->resultset('Artist')->find({artistid => 1}, {for => 'shared'}),
98 'DBICTest::Schema::Artist',
101 } 'LOCK IN SHARE MODE select works';
103 my $test_type_info = {
105 'data_type' => 'INT',
108 'default_value' => undef,
111 'data_type' => 'VARCHAR',
114 'default_value' => undef,
117 'data_type' => 'INT',
120 'default_value' => 13,
123 'data_type' => 'CHAR',
126 'default_value' => undef,
130 $schema->populate ('Owners', [
137 $schema->populate ('BooksInLibrary', [
138 [qw/source owner title /],
139 [qw/Library 1 secrets1/],
140 [qw/Eatery 1 secrets2/],
141 [qw/Library 2 secrets3/],
145 # try a distinct + prefetch on tables with identically named columns
146 # (mysql doesn't seem to like subqueries with equally named columns)
150 # try a ->has_many direction (due to a 'multi' accessor the select/group_by group is collapsed)
151 my $owners = $schema->resultset ('Owners')->search (
152 { 'books.id' => { '!=', undef }},
153 { prefetch => 'books', distinct => 1 }
155 my $owners2 = $schema->resultset ('Owners')->search ({ id => { -in => $owners->get_column ('me.id')->as_query }});
156 for ($owners, $owners2) {
157 is ($_->all, 2, 'Prefetched grouped search returns correct number of rows');
158 is ($_->count, 2, 'Prefetched grouped search returns correct count');
161 # try a ->belongs_to direction (no select collapse)
162 my $books = $schema->resultset ('BooksInLibrary')->search (
163 { 'owner.name' => 'wiggle' },
164 { prefetch => 'owner', distinct => 1 }
166 my $books2 = $schema->resultset ('BooksInLibrary')->search ({ id => { -in => $books->get_column ('me.id')->as_query }});
167 for ($books, $books2) {
168 is ($_->all, 1, 'Prefetched grouped search returns correct number of rows');
169 is ($_->count, 1, 'Prefetched grouped search returns correct count');
174 my $norm_version = $schema->storage->_server_info->{normalized_dbms_version}
175 or skip "Cannot determine MySQL server version", 1;
177 if ($norm_version < 5.000003_01) {
178 $test_type_info->{charfield}->{data_type} = 'VARCHAR';
181 my $type_info = $schema->storage->columns_info_for('artist');
182 is_deeply($type_info, $test_type_info, 'columns_info_for - column data types');
185 my $cd = $schema->resultset ('CD')->create ({});
186 my $producer = $schema->resultset ('Producer')->create ({});
187 lives_ok { $cd->set_producers ([ $producer ]) } 'set_relationship doesnt die';
190 my $artist = $schema->resultset('Artist')->next;
191 my $cd = $schema->resultset('CD')->next;
192 $cd->set_from_related ('artist', $artist);
195 my $rs = $schema->resultset('CD')->search ({}, { prefetch => 'artist' });
199 is ($cd->artist->name, $artist->name, 'Prefetched artist');
200 }, 'join does not throw (mysql 3 test)';
202 # induce a jointype override, make sure it works even if we don't have mysql3
203 my $needs_inner_join = $schema->storage->sql_maker->needs_inner_join;
204 $schema->storage->sql_maker->needs_inner_join(1);
208 SELECT `me`.`cdid`, `me`.`artist`, `me`.`title`, `me`.`year`, `me`.`genreid`, `me`.`single_track`,
209 `artist`.`artistid`, `artist`.`name`, `artist`.`rank`, `artist`.`charfield`
211 INNER JOIN `artist` `artist` ON `artist`.`artistid` = `me`.`artist`
214 'overridden default join type works',
216 $schema->storage->sql_maker->needs_inner_join($needs_inner_join);
219 ## Can we properly deal with the null search problem?
221 ## Only way is to do a SET SQL_AUTO_IS_NULL = 0; on connect
222 ## But I'm not sure if we should do this or not (Ash, 2008/06/03)
224 # There is now a built-in function to do this, test that everything works
225 # with it (ribasushi, 2009/07/03)
228 my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, { on_connect_call => 'set_strict_mode' });
230 $ansi_schema->resultset('Artist')->create ({ name => 'last created artist' });
232 ok my $artist1_rs = $ansi_schema->resultset('Artist')->search({artistid=>6666})
233 => 'Created an artist resultset of 6666';
235 is $artist1_rs->count, 0
236 => 'Got no returned rows';
238 ok my $artist2_rs = $ansi_schema->resultset('Artist')->search({artistid=>undef})
239 => 'Created an artist resultset of undef';
241 is $artist2_rs->count, 0
244 my $artist = $artist2_rs->single;
250 # check for proper grouped counts
252 my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, {
253 on_connect_call => 'set_strict_mode',
256 my $rs = $ansi_schema->resultset('CD');
259 $years->{$_->year|| scalar keys %$years}++ for $rs->all; # NULL != NULL, thus the keys eval
263 $rs->search ({}, { group_by => 'year'})->count,
265 'grouped count correct',
267 }, 'Grouped count does not throw');
270 $ansi_schema->resultset('Owners')->search({}, {
271 join => 'books', group_by => [ 'me.id', 'books.id' ]
273 }, 'count on grouped columns with the same name does not throw');
276 # a more contrived^Wcomplicated self-referential double-subquery test
278 my $rs = $schema->resultset('Artist')->search({ name => { -like => 'baby_%' } });
280 $rs->populate([map { [$_] } ('name', map { "baby_$_" } (1..10) ) ]);
282 my ($count_sql, @count_bind) = @${$rs->count_rs->as_query};
284 my $complex_rs = $schema->resultset('Artist')->search(
286 -in => $rs->get_column('artistid')
291 $complex_rs->update({ name => \[ "CONCAT( `name`, '_bell_out_of_', $count_sql )", @count_bind ] });
295 $schema->resultset('Artist')->search({ name => "baby_${_}_bell_out_of_10" })->count,
297 "Correctly updated babybell $_",
301 is ($rs->count, 10, '10 artists present');
303 my $orig_debug = $schema->storage->debug;
304 $schema->storage->debug(1);
306 $schema->storage->debugcb(sub { $query_count++ });
311 is ($query_count, 1, 'One delete query fired');
312 is ($rs->count, 0, '10 Artists correctly deleted');
315 name => 'baby_with_cd',
316 cds => [ { title => 'babeeeeee', year => 2013 } ],
318 is ($rs->count, 1, 'Artist with cd created');
321 $schema->resultset('CD')->search_related('artist',
322 { 'artist.name' => { -like => 'baby_with_%' } }
324 is ($query_count, 1, 'And one more delete query fired');
325 is ($rs->count, 0, 'Artist with cd deleted');
327 $schema->storage->debugcb(undef);
328 $schema->storage->debug($orig_debug);
338 my $rs = $schema->resultset ('CD');
340 for my $y (keys %$cds_per_year) {
341 for my $c (1 .. $cds_per_year->{$y} ) {
342 $rs->create ({ title => "CD $y-$c", artist => 1, year => "$y-01-01" });
346 is ($rs->count, 6, 'CDs created successfully');
348 $rs = $rs->search ({}, {
349 select => [ \ 'YEAR(year)' ], as => ['y'], distinct => 1,
353 [ sort ($rs->get_column ('y')->all) ],
354 [ sort keys %$cds_per_year ],
355 'Years group successfully',
358 $rs->create ({ artist => 1, year => '0-1-1', title => 'Jesus Rap' });
361 [ sort $rs->get_column ('y')->all ],
362 [ 0, sort keys %$cds_per_year ],
363 'Zero-year groups successfully',
366 # convoluted search taken verbatim from list
367 my $restrict_rs = $rs->search({ -and => [
369 year => { '!=', undef }
373 [ $restrict_rs->get_column('y')->all ],
374 [ $rs->get_column ('y')->all ],
375 'Zero year was correctly excluded from resultset',
379 # make sure find hooks determine driver
381 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
382 $schema->resultset("Artist")->find(4);
383 isa_ok($schema->storage->sql_maker, 'DBIx::Class::SQLMaker::MySQL');
386 # make sure the mysql_auto_reconnect buggery is avoided
388 local $ENV{MOD_PERL} = 'boogiewoogie';
389 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
390 ok (! $schema->storage->_get_dbh->{mysql_auto_reconnect}, 'mysql_auto_reconnect unset regardless of ENV' );
392 # Make sure hardcore forking action still works even if mysql_auto_reconnect
393 # is true (test inspired by ether)
395 my $schema_autorecon = DBICTest::Schema->connect($dsn, $user, $pass, { mysql_auto_reconnect => 1 });
396 my $orig_dbh = $schema_autorecon->storage->_get_dbh;
399 ok ($orig_dbh, 'Got weak $dbh ref');
400 ok ($orig_dbh->{mysql_auto_reconnect}, 'mysql_auto_reconnect is properly set if explicitly requested' );
402 my $rs = $schema_autorecon->resultset('Artist');
404 my ($parent_in, $child_out);
405 pipe( $parent_in, $child_out ) or die "Pipe open failed: $!";
407 if (! defined $pid ) {
408 die "fork() failed: $!"
414 $schema_autorecon->storage->dbh_do(sub {
415 is ($_[1], $orig_dbh, 'Storage holds correct $dbh in parent');
419 $schema_autorecon->storage->_dbh(undef);
422 local $TODO = "Perl $] is known to leak like a sieve"
423 if DBIx::Class::_ENV_::PEEPEENESS;
425 ok (! defined $orig_dbh, 'Parent $dbh handle is gone');
431 #simulate a subtest to not confuse the parent TAP emission
432 my $tb = Test::More->builder;
434 for (qw/output failure_output todo_output/) {
436 open ($tb->$_, '>&', $child_out);
439 # wait for parent to kill its $dbh
442 # try to do something dbic-esque
443 $rs->create({ name => "Hardcore Forker $$" });
446 local $TODO = "Perl $] is known to leak like a sieve"
447 if DBIx::Class::_ENV_::PEEPEENESS;
449 ok (! defined $orig_dbh, 'DBIC operation triggered reconnect - old $dbh is gone');
456 while (my $ln = <$parent_in>) {
460 ok(!$?, 'Child subtests passed');
462 ok ($rs->find({ name => "Hardcore Forker $pid" }), 'Expected row created');