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