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