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