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