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