Extra test for mysql_auto_reconnect and fork
[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
10 use lib qw(t/lib);
11 use DBICTest;
12 use DBIC::SqlMakerTest;
13
14 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_MYSQL_${_}" } qw/DSN USER PASS/};
15
16 #warn "$dsn $user $pass";
17
18 plan skip_all => 'Set $ENV{DBICTEST_MYSQL_DSN}, _USER and _PASS to run this test'
19   unless ($dsn && $user);
20
21 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
22
23 my $dbh = $schema->storage->dbh;
24
25 $dbh->do("DROP TABLE IF EXISTS artist;");
26
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));");
28
29 $dbh->do("DROP TABLE IF EXISTS cd;");
30
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);");
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
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
49 #'dbi:mysql:host=localhost;database=dbic_test', 'dbic_test', '');
50
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
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');
61
62 # test primary key handling
63 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
64 ok($new->artistid, "Auto-PK worked");
65
66 # test LIMIT support
67 for (1..6) {
68     $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
69 }
70 my $it = $schema->resultset('Artist')->search( {},
71     { rows => 3,
72       offset => 2,
73       order_by => 'artistid' }
74 );
75 is( $it->count, 3, "LIMIT count ok" );  # ask for 3 rows out of 7 artists
76 is( $it->next->name, "Artist 2", "iterator->next ok" );
77 $it->next;
78 $it->next;
79 is( $it->next, undef, "next past end of resultset ok" );
80
81 # Limit with select-lock
82 lives_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
91 # shared-lock
92 lives_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
101 my $test_type_info = {
102     'artistid' => {
103         'data_type' => 'INT',
104         'is_nullable' => 0,
105         'size' => 11,
106         'default_value' => undef,
107     },
108     'name' => {
109         'data_type' => 'VARCHAR',
110         'is_nullable' => 1,
111         'size' => 100,
112         'default_value' => undef,
113     },
114     'rank' => {
115         'data_type' => 'INT',
116         'is_nullable' => 0,
117         'size' => 11,
118         'default_value' => 13,
119     },
120     'charfield' => {
121         'data_type' => 'CHAR',
122         'is_nullable' => 1,
123         'size' => 10,
124         'default_value' => undef,
125     },
126 };
127
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   /],
137   [qw/Library 1     secrets1/],
138   [qw/Eatery  1     secrets2/],
139   [qw/Library 2     secrets3/],
140 ]);
141
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 #
146
147 {
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) {
155     is ($_->all, 2, 'Prefetched grouped search returns correct number of rows');
156     is ($_->count, 2, 'Prefetched grouped search returns correct count');
157   }
158
159   # try a ->belongs_to direction (no select collapse)
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');
168   }
169 }
170
171 SKIP: {
172     my $mysql_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} );
173     skip "Cannot determine MySQL server version", 1 if !$mysql_version;
174
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
180     if( ($v1 < 5) || ($v1 == 5 && $v2 == 0 && $v3 <= 3) ) {
181         $test_type_info->{charfield}->{data_type} = 'VARCHAR';
182     }
183
184     my $type_info = $schema->storage->columns_info_for('artist');
185     is_deeply($type_info, $test_type_info, 'columns_info_for - column data types');
186 }
187
188 my $cd = $schema->resultset ('CD')->create ({});
189 my $producer = $schema->resultset ('Producer')->create ({});
190 lives_ok { $cd->set_producers ([ $producer ]) } 'set_relationship doesnt die';
191
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
206   local $schema->storage->sql_maker->{_default_jointype} = 'inner';
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 }
219
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
243 ## Can we properly deal with the null search problem?
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)
247 #
248 # There is now a built-in function to do this, test that everything works
249 # with it (ribasushi, 2009/07/03)
250
251 NULLINSEARCH: {
252     my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, { on_connect_call => 'set_strict_mode' });
253
254     $ansi_schema->resultset('Artist')->create ({ name => 'last created artist' });
255
256     ok my $artist1_rs = $ansi_schema->resultset('Artist')->search({artistid=>6666})
257       => 'Created an artist resultset of 6666';
258
259     is $artist1_rs->count, 0
260       => 'Got no returned rows';
261
262     ok my $artist2_rs = $ansi_schema->resultset('Artist')->search({artistid=>undef})
263       => 'Created an artist resultset of undef';
264
265     is $artist2_rs->count, 0
266       => 'got no rows';
267
268     my $artist = $artist2_rs->single;
269
270     is $artist => undef
271       => 'Nothing Found!';
272 }
273
274 # check for proper grouped counts
275 {
276   my $ansi_schema = DBICTest::Schema->connect ($dsn, $user, $pass, {
277     on_connect_call => 'set_strict_mode',
278     quote_char => '`',
279   });
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');
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
300 }
301
302 ZEROINSEARCH: {
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 ({}, {
320     select => [ \ 'YEAR(year)' ], as => ['y'], distinct => 1,
321   });
322
323   is_deeply (
324     [ sort ($rs->get_column ('y')->all) ],
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 (
332     [ sort $rs->get_column ('y')->all ],
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 }
349
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
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);
387     ok (! defined $orig_dbh, 'Parent $dbh handle is gone');
388   }
389   else {
390     # wait for parent to kill its $dbh
391     sleep 1;
392
393     #simulate a  subtest to not confuse the parent TAP emission
394     Test::More->builder->reset;
395     Test::More->builder->plan('no_plan');
396     Test::More->builder->_indent(' ' x 4);
397
398     ok ($orig_dbh, 'Now dead $dbh is still there for the child');
399
400     # try to do something dbic-esque
401     $rs->create({ name => "Hardcore Forker $$" });
402
403     ok (! defined $orig_dbh, 'DBIC operation triggered reconnect - old $dbh is gone');
404
405     exit 0;
406   }
407
408   wait;
409   ok(!$?, 'Child subtests passed');
410
411   ok ($rs->find({ name => "Hardcore Forker $pid" }), 'Expected row created');
412 }
413
414 done_testing;