Smarter todoification (this doesn't sound like a bad idea for CPAN in general)
[dbsrgits/DBIx-Class.git] / t / 71mysql.t
CommitLineData
70350518 1use strict;
68de9438 2use warnings;
70350518 3
4use Test::More;
74de7c2c 5use Test::Exception;
da6a5860 6
7use DBI::Const::GetInfoType;
8use Scalar::Util qw/weaken/;
199fbc45 9use DBIx::Class::Optional::Dependencies ();
da6a5860 10
70350518 11use lib qw(t/lib);
12use DBICTest;
aa82ce29 13use DBIC::SqlMakerTest;
0567538f 14
199fbc45 15plan 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');
17
0567538f 18my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MYSQL_${_}" } qw/DSN USER PASS/};
19
70350518 20plan skip_all => 'Set $ENV{DBICTEST_MYSQL_DSN}, _USER and _PASS to run this test'
0567538f 21 unless ($dsn && $user);
22
5f6bada6 23my $schema = DBICTest::Schema->connect($dsn, $user, $pass, { quote_names => 1 });
0567538f 24
3ff5b740 25my $dbh = $schema->storage->dbh;
0567538f 26
27$dbh->do("DROP TABLE IF EXISTS artist;");
28
a0dd8679 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));");
0567538f 30
74de7c2c 31$dbh->do("DROP TABLE IF EXISTS cd;");
32
e0d56e26 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);");
74de7c2c 34
35$dbh->do("DROP TABLE IF EXISTS producer;");
36
37$dbh->do("CREATE TABLE producer (producerid INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, name TEXT);");
38
39$dbh->do("DROP TABLE IF EXISTS cd_to_producer;");
40
41$dbh->do("CREATE TABLE cd_to_producer (cd INTEGER,producer INTEGER);");
42
bed3a173 43$dbh->do("DROP TABLE IF EXISTS owners;");
44
45$dbh->do("CREATE TABLE owners (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL);");
46
47$dbh->do("DROP TABLE IF EXISTS books;");
48
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);");
50
0567538f 51#'dbi:mysql:host=localhost;database=dbic_test', 'dbic_test', '');
52
8273e845 53# make sure sqlt_type overrides work (::Storage::DBI::mysql does this)
adbf0c89 54{
55 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
56
57 ok (!$schema->storage->_dbh, 'definitely not connected');
58 is ($schema->storage->sqlt_type, 'MySQL', 'sqlt_type correct pre-connection');
59}
60
3ff5b740 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');
0567538f 63
64# test primary key handling
3ff5b740 65my $new = $schema->resultset('Artist')->create({ name => 'foo' });
0567538f 66ok($new->artistid, "Auto-PK worked");
67
68# test LIMIT support
69for (1..6) {
3ff5b740 70 $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
0567538f 71}
3ff5b740 72my $it = $schema->resultset('Artist')->search( {},
0567538f 73 { rows => 3,
74 offset => 2,
75 order_by => 'artistid' }
76);
fb4b58e8 77is( $it->count, 3, "LIMIT count ok" ); # ask for 3 rows out of 7 artists
0567538f 78is( $it->next->name, "Artist 2", "iterator->next ok" );
79$it->next;
80$it->next;
81is( $it->next, undef, "next past end of resultset ok" );
82
e5372da4 83# Limit with select-lock
84lives_ok {
85 $schema->txn_do (sub {
86 isa_ok (
87 $schema->resultset('Artist')->find({artistid => 1}, {for => 'update', rows => 1}),
88 'DBICTest::Schema::Artist',
89 );
90 });
91} 'Limited FOR UPDATE select works';
92
4e0a89e4 93# shared-lock
94lives_ok {
95 $schema->txn_do (sub {
96 isa_ok (
97 $schema->resultset('Artist')->find({artistid => 1}, {for => 'shared'}),
98 'DBICTest::Schema::Artist',
99 );
100 });
101} 'LOCK IN SHARE MODE select works';
102
a953d8d9 103my $test_type_info = {
104 'artistid' => {
103e3e03 105 'data_type' => 'INT',
106 'is_nullable' => 0,
fc22fbac 107 'size' => 11,
108 'default_value' => undef,
a953d8d9 109 },
110 'name' => {
103e3e03 111 'data_type' => 'VARCHAR',
a953d8d9 112 'is_nullable' => 1,
a0dd8679 113 'size' => 100,
fc22fbac 114 'default_value' => undef,
103e3e03 115 },
39da2a2b 116 'rank' => {
117 'data_type' => 'INT',
118 'is_nullable' => 0,
119 'size' => 11,
120 'default_value' => 13,
121 },
103e3e03 122 'charfield' => {
637219ab 123 'data_type' => 'CHAR',
103e3e03 124 'is_nullable' => 1,
fc22fbac 125 'size' => 10,
126 'default_value' => undef,
103e3e03 127 },
a953d8d9 128};
129
bed3a173 130$schema->populate ('Owners', [
131 [qw/id name /],
132 [qw/1 wiggle/],
133 [qw/2 woggle/],
134 [qw/3 boggle/],
135]);
136
137$schema->populate ('BooksInLibrary', [
138 [qw/source owner title /],
13a2f031 139 [qw/Library 1 secrets1/],
140 [qw/Eatery 1 secrets2/],
141 [qw/Library 2 secrets3/],
bed3a173 142]);
143
13a2f031 144#
8273e845 145# try a distinct + prefetch on tables with identically named columns
13a2f031 146# (mysql doesn't seem to like subqueries with equally named columns)
147#
bed3a173 148
d758ec36 149{
13a2f031 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 }
154 );
155 my $owners2 = $schema->resultset ('Owners')->search ({ id => { -in => $owners->get_column ('me.id')->as_query }});
156 for ($owners, $owners2) {
b5963465 157 is ($_->all, 2, 'Prefetched grouped search returns correct number of rows');
158 is ($_->count, 2, 'Prefetched grouped search returns correct count');
13a2f031 159 }
160
d758ec36 161 # try a ->belongs_to direction (no select collapse)
b5963465 162 my $books = $schema->resultset ('BooksInLibrary')->search (
163 { 'owner.name' => 'wiggle' },
164 { prefetch => 'owner', distinct => 1 }
165 );
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');
13a2f031 170 }
171}
bed3a173 172
5db49b9a 173SKIP: {
af1f4f84 174 my $norm_version = $schema->storage->_server_info->{normalized_dbms_version}
175 or skip "Cannot determine MySQL server version", 1;
a953d8d9 176
af1f4f84 177 if ($norm_version < 5.000003_01) {
5db49b9a 178 $test_type_info->{charfield}->{data_type} = 'VARCHAR';
179 }
a953d8d9 180
3ff5b740 181 my $type_info = $schema->storage->columns_info_for('artist');
5db49b9a 182 is_deeply($type_info, $test_type_info, 'columns_info_for - column data types');
183}
a953d8d9 184
6a999241 185my $cd = $schema->resultset ('CD')->create ({});
186my $producer = $schema->resultset ('Producer')->create ({});
187lives_ok { $cd->set_producers ([ $producer ]) } 'set_relationship doesnt die';
188
aa82ce29 189{
190 my $artist = $schema->resultset('Artist')->next;
191 my $cd = $schema->resultset('CD')->next;
192 $cd->set_from_related ('artist', $artist);
193 $cd->update;
194
195 my $rs = $schema->resultset('CD')->search ({}, { prefetch => 'artist' });
196
197 lives_ok sub {
198 my $cd = $rs->next;
199 is ($cd->artist->name, $artist->name, 'Prefetched artist');
200 }, 'join does not throw (mysql 3 test)';
201
202 # induce a jointype override, make sure it works even if we don't have mysql3
39712b48 203 my $needs_inner_join = $schema->storage->sql_maker->needs_inner_join;
204 $schema->storage->sql_maker->needs_inner_join(1);
aa82ce29 205 is_same_sql_bind (
206 $rs->as_query,
207 '(
5f6bada6 208 SELECT `me`.`cdid`, `me`.`artist`, `me`.`title`, `me`.`year`, `me`.`genreid`, `me`.`single_track`,
209 `artist`.`artistid`, `artist`.`name`, `artist`.`rank`, `artist`.`charfield`
210 FROM cd `me`
211 INNER JOIN `artist` `artist` ON `artist`.`artistid` = `me`.`artist`
aa82ce29 212 )',
213 [],
9acb6956 214 'overridden default join type works',
aa82ce29 215 );
39712b48 216 $schema->storage->sql_maker->needs_inner_join($needs_inner_join);
aa82ce29 217}
6a999241 218
55cfbb70 219## Can we properly deal with the null search problem?
a7e65bb5 220##
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)
0fde80d9 223#
224# There is now a built-in function to do this, test that everything works
225# with it (ribasushi, 2009/07/03)
55cfbb70 226
227NULLINSEARCH: {
97a0a148 228 my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, { on_connect_call => 'set_strict_mode' });
8de9298c 229
230 $ansi_schema->resultset('Artist')->create ({ name => 'last created artist' });
6a999241 231
232 ok my $artist1_rs = $ansi_schema->resultset('Artist')->search({artistid=>6666})
233 => 'Created an artist resultset of 6666';
234
55cfbb70 235 is $artist1_rs->count, 0
6a999241 236 => 'Got no returned rows';
374dd926 237
6a999241 238 ok my $artist2_rs = $ansi_schema->resultset('Artist')->search({artistid=>undef})
239 => 'Created an artist resultset of undef';
74de7c2c 240
6a999241 241 is $artist2_rs->count, 0
242 => 'got no rows';
74de7c2c 243
6a999241 244 my $artist = $artist2_rs->single;
55cfbb70 245
5083f7de 246 is $artist => undef,
6a999241 247 => 'Nothing Found!';
74de7c2c 248}
aa82ce29 249
0ce4ab92 250# check for proper grouped counts
251{
9f775126 252 my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, {
253 on_connect_call => 'set_strict_mode',
254 quote_char => '`',
9f775126 255 });
0ce4ab92 256 my $rs = $ansi_schema->resultset('CD');
257
258 my $years;
259 $years->{$_->year|| scalar keys %$years}++ for $rs->all; # NULL != NULL, thus the keys eval
260
261 lives_ok ( sub {
262 is (
263 $rs->search ({}, { group_by => 'year'})->count,
264 scalar keys %$years,
265 'grouped count correct',
266 );
267 }, 'Grouped count does not throw');
9f775126 268
269 lives_ok( sub {
270 $ansi_schema->resultset('Owners')->search({}, {
271 join => 'books', group_by => [ 'me.id', 'books.id' ]
272 })->count();
273 }, 'count on grouped columns with the same name does not throw');
0ce4ab92 274}
275
45150bc4 276# a more contrived^Wcomplicated self-referential double-subquery test
277{
278 my $rs = $schema->resultset('Artist')->search({ name => { -like => 'baby_%' } });
279
280 $rs->populate([map { [$_] } ('name', map { "baby_$_" } (1..10) ) ]);
281
282 my ($count_sql, @count_bind) = @${$rs->count_rs->as_query};
283
284 my $complex_rs = $schema->resultset('Artist')->search(
285 { artistid => {
286 -in => $rs->get_column('artistid')
287 ->as_query
288 } },
289 );
290
291 $complex_rs->update({ name => \[ "CONCAT( `name`, '_bell_out_of_', $count_sql )", @count_bind ] });
292
293 for (1..10) {
294 is (
295 $schema->resultset('Artist')->search({ name => "baby_${_}_bell_out_of_10" })->count,
296 1,
297 "Correctly updated babybell $_",
298 );
299 }
300
f4fdfd69 301 is ($rs->count, 10, '10 artists present');
45150bc4 302
303 my $orig_debug = $schema->storage->debug;
304 $schema->storage->debug(1);
f4fdfd69 305 my $query_count;
45150bc4 306 $schema->storage->debugcb(sub { $query_count++ });
f4fdfd69 307
308 $query_count = 0;
45150bc4 309 $complex_rs->delete;
45150bc4 310
311 is ($query_count, 1, 'One delete query fired');
f4fdfd69 312 is ($rs->count, 0, '10 Artists correctly deleted');
313
314 $rs->create({
315 name => 'baby_with_cd',
316 cds => [ { title => 'babeeeeee', year => 2013 } ],
317 });
318 is ($rs->count, 1, 'Artist with cd created');
319
320 $query_count = 0;
321 $schema->resultset('CD')->search_related('artist',
322 { 'artist.name' => { -like => 'baby_with_%' } }
323 )->delete;
324 is ($query_count, 1, 'And one more delete query fired');
325 is ($rs->count, 0, 'Artist with cd deleted');
326
327 $schema->storage->debugcb(undef);
328 $schema->storage->debug($orig_debug);
45150bc4 329}
330
e0d56e26 331ZEROINSEARCH: {
332 my $cds_per_year = {
333 2001 => 2,
334 2002 => 1,
335 2005 => 3,
336 };
337
338 my $rs = $schema->resultset ('CD');
339 $rs->delete;
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" });
343 }
344 }
345
346 is ($rs->count, 6, 'CDs created successfully');
347
348 $rs = $rs->search ({}, {
ca458871 349 select => [ \ 'YEAR(year)' ], as => ['y'], distinct => 1,
e0d56e26 350 });
351
352 is_deeply (
ca458871 353 [ sort ($rs->get_column ('y')->all) ],
e0d56e26 354 [ sort keys %$cds_per_year ],
355 'Years group successfully',
356 );
357
358 $rs->create ({ artist => 1, year => '0-1-1', title => 'Jesus Rap' });
359
360 is_deeply (
ca458871 361 [ sort $rs->get_column ('y')->all ],
e0d56e26 362 [ 0, sort keys %$cds_per_year ],
363 'Zero-year groups successfully',
364 );
365
8273e845 366 # convoluted search taken verbatim from list
e0d56e26 367 my $restrict_rs = $rs->search({ -and => [
368 year => { '!=', 0 },
369 year => { '!=', undef }
370 ]});
371
372 is_deeply (
373 [ $restrict_rs->get_column('y')->all ],
374 [ $rs->get_column ('y')->all ],
375 'Zero year was correctly excluded from resultset',
376 );
377}
10176e1f 378
f98120e4 379# make sure find hooks determine driver
380{
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');
384}
385
386# make sure the mysql_auto_reconnect buggery is avoided
387{
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' );
391
da6a5860 392 # Make sure hardcore forking action still works even if mysql_auto_reconnect
393 # is true (test inspired by ether)
394
395 my $schema_autorecon = DBICTest::Schema->connect($dsn, $user, $pass, { mysql_auto_reconnect => 1 });
396 my $orig_dbh = $schema_autorecon->storage->_get_dbh;
397 weaken $orig_dbh;
398
399 ok ($orig_dbh, 'Got weak $dbh ref');
400 ok ($orig_dbh->{mysql_auto_reconnect}, 'mysql_auto_reconnect is properly set if explicitly requested' );
401
402 my $rs = $schema_autorecon->resultset('Artist');
403
7be5717e 404 my ($parent_in, $child_out);
405 pipe( $parent_in, $child_out ) or die "Pipe open failed: $!";
da6a5860 406 my $pid = fork();
407 if (! defined $pid ) {
408 die "fork() failed: $!"
409 }
410 elsif ($pid) {
7be5717e 411 close $child_out;
412
da6a5860 413 # sanity check
414 $schema_autorecon->storage->dbh_do(sub {
415 is ($_[1], $orig_dbh, 'Storage holds correct $dbh in parent');
416 });
417
418 # kill our $dbh
419 $schema_autorecon->storage->_dbh(undef);
e0b2dc74 420
4ca1fd6f 421 {
e0b2dc74 422 local $TODO = "Perl $] is known to leak like a sieve"
0d8817bc 423 if DBIx::Class::_ENV_::PEEPEENESS;
e0b2dc74 424
425 ok (! defined $orig_dbh, 'Parent $dbh handle is gone');
426 }
da6a5860 427 }
428 else {
7be5717e 429 close $parent_in;
da6a5860 430
431 #simulate a subtest to not confuse the parent TAP emission
7be5717e 432 my $tb = Test::More->builder;
433 $tb->reset;
434 for (qw/output failure_output todo_output/) {
435 close $tb->$_;
436 open ($tb->$_, '>&', $child_out);
437 }
438
439 # wait for parent to kill its $dbh
440 sleep 1;
da6a5860 441
da6a5860 442 # try to do something dbic-esque
443 $rs->create({ name => "Hardcore Forker $$" });
444
4ca1fd6f 445 {
e0b2dc74 446 local $TODO = "Perl $] is known to leak like a sieve"
0d8817bc 447 if DBIx::Class::_ENV_::PEEPEENESS;
e0b2dc74 448
449 ok (! defined $orig_dbh, 'DBIC operation triggered reconnect - old $dbh is gone');
450 }
da6a5860 451
7be5717e 452 done_testing;
da6a5860 453 exit 0;
454 }
455
7be5717e 456 while (my $ln = <$parent_in>) {
457 print " $ln";
458 }
da6a5860 459 wait;
460 ok(!$?, 'Child subtests passed');
461
462 ok ($rs->find({ name => "Hardcore Forker $pid" }), 'Expected row created');
f98120e4 463}
10176e1f 464
aa82ce29 465done_testing;