1e31e8cc2d1fb49fcec80fdac51ff610e06ea41a
[dbsrgits/DBIx-Class.git] / t / 71mysql.t
1 use strict;
2 use warnings;
3
4 use Test::More;
5 use Test::Exception;
6
7 use DBI::Const::GetInfoType;
8 use Scalar::Util qw/weaken/;
9 use DBIx::Class::Optional::Dependencies ();
10
11 use lib qw(t/lib);
12 use DBICTest;
13 use DBIC::SqlMakerTest;
14
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');
17
18 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MYSQL_${_}" } qw/DSN USER PASS/};
19
20 plan skip_all => 'Set $ENV{DBICTEST_MYSQL_DSN}, _USER and _PASS to run this test'
21   unless ($dsn && $user);
22
23 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, { quote_names => 1 });
24
25 my $dbh = $schema->storage->dbh;
26
27 $dbh->do("DROP TABLE IF EXISTS artist;");
28
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));");
30
31 $dbh->do("DROP TABLE IF EXISTS cd;");
32
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);");
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
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
51 #'dbi:mysql:host=localhost;database=dbic_test', 'dbic_test', '');
52
53 # make sure sqlt_type overrides work (::Storage::DBI::mysql does this)
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
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');
63
64 # test primary key handling
65 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
66 ok($new->artistid, "Auto-PK worked");
67
68 # test LIMIT support
69 for (1..6) {
70     $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
71 }
72 my $it = $schema->resultset('Artist')->search( {},
73     { rows => 3,
74       offset => 2,
75       order_by => 'artistid' }
76 );
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" );
79 $it->next;
80 $it->next;
81 is( $it->next, undef, "next past end of resultset ok" );
82
83 # Limit with select-lock
84 lives_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
93 # shared-lock
94 lives_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
103 my $test_type_info = {
104     'artistid' => {
105         'data_type' => 'INT',
106         'is_nullable' => 0,
107         'size' => 11,
108         'default_value' => undef,
109     },
110     'name' => {
111         'data_type' => 'VARCHAR',
112         'is_nullable' => 1,
113         'size' => 100,
114         'default_value' => undef,
115     },
116     'rank' => {
117         'data_type' => 'INT',
118         'is_nullable' => 0,
119         'size' => 11,
120         'default_value' => 13,
121     },
122     'charfield' => {
123         'data_type' => 'CHAR',
124         'is_nullable' => 1,
125         'size' => 10,
126         'default_value' => undef,
127     },
128 };
129
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   /],
139   [qw/Library 1     secrets1/],
140   [qw/Eatery  1     secrets2/],
141   [qw/Library 2     secrets3/],
142 ]);
143
144 #
145 # try a distinct + prefetch on tables with identically named columns
146 # (mysql doesn't seem to like subqueries with equally named columns)
147 #
148
149 {
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) {
157     is ($_->all, 2, 'Prefetched grouped search returns correct number of rows');
158     is ($_->count, 2, 'Prefetched grouped search returns correct count');
159   }
160
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 }
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');
170   }
171 }
172
173 SKIP: {
174     my $norm_version = $schema->storage->_server_info->{normalized_dbms_version}
175       or skip "Cannot determine MySQL server version", 1;
176
177     if ($norm_version < 5.000003_01) {
178         $test_type_info->{charfield}->{data_type} = 'VARCHAR';
179     }
180
181     my $type_info = $schema->storage->columns_info_for('artist');
182     is_deeply($type_info, $test_type_info, 'columns_info_for - column data types');
183 }
184
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';
188
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
203   local $schema->storage->sql_maker->{_default_jointype} = 'inner';
204   is_same_sql_bind (
205     $rs->as_query,
206     '(
207       SELECT `me`.`cdid`, `me`.`artist`, `me`.`title`, `me`.`year`, `me`.`genreid`, `me`.`single_track`,
208              `artist`.`artistid`, `artist`.`name`, `artist`.`rank`, `artist`.`charfield`
209         FROM cd `me`
210         INNER JOIN `artist` `artist` ON `artist`.`artistid` = `me`.`artist`
211     )',
212     [],
213     'overridden default join type works',
214   );
215 }
216
217 ## Can we properly deal with the null search problem?
218 ##
219 ## Only way is to do a SET SQL_AUTO_IS_NULL = 0; on connect
220 ## But I'm not sure if we should do this or not (Ash, 2008/06/03)
221 #
222 # There is now a built-in function to do this, test that everything works
223 # with it (ribasushi, 2009/07/03)
224
225 NULLINSEARCH: {
226     my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, { on_connect_call => 'set_strict_mode' });
227
228     $ansi_schema->resultset('Artist')->create ({ name => 'last created artist' });
229
230     ok my $artist1_rs = $ansi_schema->resultset('Artist')->search({artistid=>6666})
231       => 'Created an artist resultset of 6666';
232
233     is $artist1_rs->count, 0
234       => 'Got no returned rows';
235
236     ok my $artist2_rs = $ansi_schema->resultset('Artist')->search({artistid=>undef})
237       => 'Created an artist resultset of undef';
238
239     is $artist2_rs->count, 0
240       => 'got no rows';
241
242     my $artist = $artist2_rs->single;
243
244     is $artist => undef,
245       => 'Nothing Found!';
246 }
247
248 # check for proper grouped counts
249 {
250   my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, {
251     on_connect_call => 'set_strict_mode',
252     quote_char => '`',
253   });
254   my $rs = $ansi_schema->resultset('CD');
255
256   my $years;
257   $years->{$_->year|| scalar keys %$years}++ for $rs->all;  # NULL != NULL, thus the keys eval
258
259   lives_ok ( sub {
260     is (
261       $rs->search ({}, { group_by => 'year'})->count,
262       scalar keys %$years,
263       'grouped count correct',
264     );
265   }, 'Grouped count does not throw');
266
267   lives_ok( sub {
268     $ansi_schema->resultset('Owners')->search({}, {
269       join => 'books', group_by => [ 'me.id', 'books.id' ]
270     })->count();
271   }, 'count on grouped columns with the same name does not throw');
272 }
273
274 # a more contrived^Wcomplicated self-referential double-subquery test
275 {
276   my $rs = $schema->resultset('Artist')->search({ name => { -like => 'baby_%' } });
277
278   $rs->populate([map { [$_] } ('name', map { "baby_$_" } (1..10) ) ]);
279
280   my ($count_sql, @count_bind) = @${$rs->count_rs->as_query};
281
282   my $complex_rs = $schema->resultset('Artist')->search(
283     { artistid => {
284       -in => $rs->get_column('artistid')
285                   ->as_query
286     } },
287   );
288
289   $complex_rs->update({ name => \[ "CONCAT( `name`, '_bell_out_of_', $count_sql )", @count_bind ] });
290
291   for (1..10) {
292     is (
293       $schema->resultset('Artist')->search({ name => "baby_${_}_bell_out_of_10" })->count,
294       1,
295       "Correctly updated babybell $_",
296     );
297   }
298
299   is ($rs->count, 10, '10 artists present');
300
301   my $orig_debug = $schema->storage->debug;
302   $schema->storage->debug(1);
303   my $query_count;
304   $schema->storage->debugcb(sub { $query_count++ });
305
306   $query_count = 0;
307   $complex_rs->delete;
308
309   is ($query_count, 1, 'One delete query fired');
310   is ($rs->count, 0, '10 Artists correctly deleted');
311
312   $rs->create({
313     name => 'baby_with_cd',
314     cds => [ { title => 'babeeeeee', year => 2013 } ],
315   });
316   is ($rs->count, 1, 'Artist with cd created');
317
318   $query_count = 0;
319   $schema->resultset('CD')->search_related('artist',
320     { 'artist.name' => { -like => 'baby_with_%' } }
321   )->delete;
322   is ($query_count, 1, 'And one more delete query fired');
323   is ($rs->count, 0, 'Artist with cd deleted');
324
325   $schema->storage->debugcb(undef);
326   $schema->storage->debug($orig_debug);
327 }
328
329 ZEROINSEARCH: {
330   my $cds_per_year = {
331     2001 => 2,
332     2002 => 1,
333     2005 => 3,
334   };
335
336   my $rs = $schema->resultset ('CD');
337   $rs->delete;
338   for my $y (keys %$cds_per_year) {
339     for my $c (1 .. $cds_per_year->{$y} ) {
340       $rs->create ({ title => "CD $y-$c", artist => 1, year => "$y-01-01" });
341     }
342   }
343
344   is ($rs->count, 6, 'CDs created successfully');
345
346   $rs = $rs->search ({}, {
347     select => [ \ 'YEAR(year)' ], as => ['y'], distinct => 1,
348   });
349
350   is_deeply (
351     [ sort ($rs->get_column ('y')->all) ],
352     [ sort keys %$cds_per_year ],
353     'Years group successfully',
354   );
355
356   $rs->create ({ artist => 1, year => '0-1-1', title => 'Jesus Rap' });
357
358   is_deeply (
359     [ sort $rs->get_column ('y')->all ],
360     [ 0, sort keys %$cds_per_year ],
361     'Zero-year groups successfully',
362   );
363
364   # convoluted search taken verbatim from list
365   my $restrict_rs = $rs->search({ -and => [
366     year => { '!=', 0 },
367     year => { '!=', undef }
368   ]});
369
370   is_deeply (
371     [ $restrict_rs->get_column('y')->all ],
372     [ $rs->get_column ('y')->all ],
373     'Zero year was correctly excluded from resultset',
374   );
375 }
376
377 # make sure find hooks determine driver
378 {
379   my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
380   $schema->resultset("Artist")->find(4);
381   isa_ok($schema->storage->sql_maker, 'DBIx::Class::SQLMaker::MySQL');
382 }
383
384 # make sure the mysql_auto_reconnect buggery is avoided
385 {
386   local $ENV{MOD_PERL} = 'boogiewoogie';
387   my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
388   ok (! $schema->storage->_get_dbh->{mysql_auto_reconnect}, 'mysql_auto_reconnect unset regardless of ENV' );
389
390   # Make sure hardcore forking action still works even if mysql_auto_reconnect
391   # is true (test inspired by ether)
392
393   my $schema_autorecon = DBICTest::Schema->connect($dsn, $user, $pass, { mysql_auto_reconnect => 1 });
394   my $orig_dbh = $schema_autorecon->storage->_get_dbh;
395   weaken $orig_dbh;
396
397   ok ($orig_dbh, 'Got weak $dbh ref');
398   ok ($orig_dbh->{mysql_auto_reconnect}, 'mysql_auto_reconnect is properly set if explicitly requested' );
399
400   my $rs = $schema_autorecon->resultset('Artist');
401
402   my ($parent_in, $child_out);
403   pipe( $parent_in, $child_out ) or die "Pipe open failed: $!";
404   my $pid = fork();
405   if (! defined $pid ) {
406     die "fork() failed: $!"
407   }
408   elsif ($pid) {
409     close $child_out;
410
411     # sanity check
412     $schema_autorecon->storage->dbh_do(sub {
413       is ($_[1], $orig_dbh, 'Storage holds correct $dbh in parent');
414     });
415
416     # kill our $dbh
417     $schema_autorecon->storage->_dbh(undef);
418
419     {
420       local $TODO = "Perl $] is known to leak like a sieve"
421         if DBIx::Class::_ENV_::PEEPEENESS;
422
423       ok (! defined $orig_dbh, 'Parent $dbh handle is gone');
424     }
425   }
426   else {
427     close $parent_in;
428
429     #simulate a  subtest to not confuse the parent TAP emission
430     my $tb = Test::More->builder;
431     $tb->reset;
432     for (qw/output failure_output todo_output/) {
433       close $tb->$_;
434       open ($tb->$_, '>&', $child_out);
435     }
436
437     # wait for parent to kill its $dbh
438     sleep 1;
439
440     # try to do something dbic-esque
441     $rs->create({ name => "Hardcore Forker $$" });
442
443     {
444       local $TODO = "Perl $] is known to leak like a sieve"
445         if DBIx::Class::_ENV_::PEEPEENESS;
446
447       ok (! defined $orig_dbh, 'DBIC operation triggered reconnect - old $dbh is gone');
448     }
449
450     done_testing;
451     exit 0;
452   }
453
454   while (my $ln = <$parent_in>) {
455     print "   $ln";
456   }
457   wait;
458   ok(!$?, 'Child subtests passed');
459
460   ok ($rs->find({ name => "Hardcore Forker $pid" }), 'Expected row created');
461 }
462
463 done_testing;