d4588c52e84e1b22ca3928290d08532e91efa8d1
[dbsrgits/DBIx-Class.git] / t / 746sybase.t
1 use DBIx::Class::Optional::Dependencies -skip_all_without => 'test_rdbms_ase';
2
3 use strict;
4 use warnings;
5 no warnings 'uninitialized';
6
7 use Test::More;
8 use Test::Exception;
9 use lib qw(t/lib);
10 use DBICTest;
11
12 my @storage_types = (
13   'DBI::Sybase::ASE',
14   'DBI::Sybase::ASE::NoBindVars',
15 );
16 eval "require DBIx::Class::Storage::$_;" or die $@
17   for @storage_types;
18
19 my $schema;
20 my $storage_idx = -1;
21
22 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_SYBASE_${_}" } qw/DSN USER PASS/};
23
24 sub get_schema {
25   DBICTest::Schema->connect($dsn, $user, $pass, {
26     on_connect_call => [
27       [ blob_setup => log_on_update => 1 ], # this is a safer option
28     ],
29   });
30 }
31
32 my $ping_count = 0;
33 {
34   my $ping = DBIx::Class::Storage::DBI::Sybase::ASE->can('_ping');
35   *DBIx::Class::Storage::DBI::Sybase::ASE::_ping = sub {
36     $ping_count++;
37     goto $ping;
38   };
39 }
40
41 for my $storage_type (@storage_types) {
42   $storage_idx++;
43
44   unless ($storage_type eq 'DBI::Sybase::ASE') { # autodetect
45     DBICTest::Schema->storage_type("::$storage_type");
46   }
47
48   $schema = get_schema();
49
50   $schema->storage->ensure_connected;
51
52   if ($storage_idx == 0 &&
53       $schema->storage->isa('DBIx::Class::Storage::DBI::Sybase::ASE::NoBindVars')) {
54       # no placeholders in this version of Sybase or DBD::Sybase (or using FreeTDS)
55       skip "Skipping entire test for $storage_type - no placeholder support", 1;
56       next;
57   }
58
59   isa_ok( $schema->storage, "DBIx::Class::Storage::$storage_type" );
60
61   $schema->storage->_dbh->disconnect;
62   lives_ok (sub { $schema->storage->dbh }, 'reconnect works');
63
64   $schema->storage->dbh_do (sub {
65       my ($storage, $dbh) = @_;
66       eval { $dbh->do("DROP TABLE artist") };
67       $dbh->do(<<'SQL');
68 CREATE TABLE artist (
69    artistid INT IDENTITY PRIMARY KEY,
70    name VARCHAR(100),
71    rank INT DEFAULT 13 NOT NULL,
72    charfield CHAR(10) NULL
73 )
74 SQL
75   });
76
77   my %seen_id;
78
79 # so we start unconnected
80   $schema->storage->disconnect;
81
82 # test primary key handling
83   my $new = $schema->resultset('Artist')->create({ name => 'foo' });
84   like $new->artistid, qr/^\d+\z/, 'Auto-PK returned a number';
85   ok($new->artistid > 0, "Auto-PK worked");
86
87   $seen_id{$new->artistid}++;
88
89 # check redispatch to storage-specific insert when auto-detected storage
90   if ($storage_type eq 'DBI::Sybase::ASE') {
91     DBICTest::Schema->storage_type('::DBI');
92     $schema = get_schema();
93   }
94
95   $new = $schema->resultset('Artist')->create({ name => 'Artist 1' });
96   is ( $seen_id{$new->artistid}, undef, 'id for Artist 1 is unique' );
97   $seen_id{$new->artistid}++;
98
99 # inserts happen in a txn, so we make sure it still works inside a txn too
100   $schema->txn_begin;
101
102   for (2..6) {
103     $new = $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
104     is ( $seen_id{$new->artistid}, undef, "id for Artist $_ is unique" );
105     $seen_id{$new->artistid}++;
106   }
107
108   $schema->txn_commit;
109
110 # test simple count
111   is ($schema->resultset('Artist')->count, 7, 'count(*) of whole table ok');
112
113 # test LIMIT support
114   my $it = $schema->resultset('Artist')->search({
115     artistid => { '>' => 0 }
116   }, {
117     rows => 3,
118     order_by => 'artistid',
119   });
120
121   is( $it->count, 3, "LIMIT count ok" );
122
123   is( $it->next->name, "foo", "iterator->next ok" );
124   $it->next;
125   is( $it->next->name, "Artist 2", "iterator->next ok" );
126   is( $it->next, undef, "next past end of resultset ok" );
127
128 # now try with offset
129   $it = $schema->resultset('Artist')->search({}, {
130     rows => 3,
131     offset => 3,
132     order_by => 'artistid',
133   });
134
135   is( $it->count, 3, "LIMIT with offset count ok" );
136
137   is( $it->next->name, "Artist 3", "iterator->next ok" );
138   $it->next;
139   is( $it->next->name, "Artist 5", "iterator->next ok" );
140   is( $it->next, undef, "next past end of resultset ok" );
141
142 # now try a grouped count
143   $schema->resultset('Artist')->create({ name => 'Artist 6' })
144     for (1..6);
145
146   $it = $schema->resultset('Artist')->search({}, {
147     group_by => 'name'
148   });
149
150   is( $it->count, 7, 'COUNT of GROUP_BY ok' );
151
152 # do an IDENTITY_INSERT
153   {
154     no warnings 'redefine';
155
156     my @debug_out;
157     local $schema->storage->{debug} = 1;
158     local $schema->storage->debugobj->{callback} = sub {
159       push @debug_out, $_[1];
160     };
161
162     my $txn_used = 0;
163     my $txn_commit = \&DBIx::Class::Storage::DBI::txn_commit;
164     local *DBIx::Class::Storage::DBI::txn_commit = sub {
165       $txn_used = 1;
166       goto &$txn_commit;
167     };
168
169     $schema->resultset('Artist')
170       ->create({ artistid => 999, name => 'mtfnpy' });
171
172     ok((grep /IDENTITY_INSERT/i, @debug_out), 'IDENTITY_INSERT used');
173
174     SKIP: {
175       skip 'not testing lack of txn on IDENTITY_INSERT with NoBindVars', 1
176         if $storage_type =~ /NoBindVars/i;
177
178       is $txn_used, 0, 'no txn on insert with IDENTITY_INSERT';
179     }
180   }
181
182 # do an IDENTITY_UPDATE
183   {
184     my @debug_out;
185     local $schema->storage->{debug} = 1;
186     local $schema->storage->debugobj->{callback} = sub {
187       push @debug_out, $_[1];
188     };
189
190     lives_and {
191       $schema->resultset('Artist')
192         ->find(999)->update({ artistid => 555 });
193       ok((grep /IDENTITY_UPDATE/i, @debug_out));
194     } 'IDENTITY_UPDATE used';
195     $ping_count-- if $@;
196   }
197
198   my $bulk_rs = $schema->resultset('Artist')->search({
199     name => { -like => 'bulk artist %' }
200   });
201
202 # test _insert_bulk using populate.
203   SKIP: {
204     skip '_insert_bulk not supported', 4
205       unless $storage_type !~ /NoBindVars/i;
206
207     lives_ok {
208       $schema->resultset('Artist')->populate([
209         {
210           name => 'bulk artist 1',
211           charfield => 'foo',
212         },
213         {
214           name => 'bulk artist 2',
215           charfield => 'foo',
216         },
217         {
218           name => 'bulk artist 3',
219           charfield => 'foo',
220         },
221       ]);
222     } '_insert_bulk via populate';
223
224     is $bulk_rs->count, 3, 'correct number inserted via _insert_bulk';
225
226     is ((grep $_->charfield eq 'foo', $bulk_rs->all), 3,
227       'column set correctly via _insert_bulk');
228
229     my %bulk_ids;
230     @bulk_ids{map $_->artistid, $bulk_rs->all} = ();
231
232     is ((scalar keys %bulk_ids), 3,
233       'identities generated correctly in _insert_bulk');
234
235     $bulk_rs->delete;
236   }
237
238 # make sure _insert_bulk works a second time on the same connection
239   SKIP: {
240     skip '_insert_bulk not supported', 3
241       unless $storage_type !~ /NoBindVars/i;
242
243     lives_ok {
244       $schema->resultset('Artist')->populate([
245         {
246           name => 'bulk artist 1',
247           charfield => 'bar',
248         },
249         {
250           name => 'bulk artist 2',
251           charfield => 'bar',
252         },
253         {
254           name => 'bulk artist 3',
255           charfield => 'bar',
256         },
257       ]);
258     } '_insert_bulk via populate called a second time';
259
260     is $bulk_rs->count, 3,
261       'correct number inserted via _insert_bulk';
262
263     is ((grep $_->charfield eq 'bar', $bulk_rs->all), 3,
264       'column set correctly via _insert_bulk');
265
266     $bulk_rs->delete;
267   }
268
269 # test invalid _insert_bulk (missing required column)
270 #
271 # There should be a rollback, reconnect and the next valid _insert_bulk should
272 # succeed.
273   throws_ok {
274     $schema->resultset('Artist')->populate([
275       {
276         charfield => 'foo',
277       }
278     ]);
279   } qr/no value or default|does not allow null|placeholders/i,
280 # The second pattern is the error from fallback to regular array insert on
281 # incompatible charset.
282 # The third is for ::NoBindVars with no syb_has_blk.
283   '_insert_bulk with missing required column throws error';
284
285 # now test _insert_bulk with IDENTITY_INSERT
286   SKIP: {
287     skip '_insert_bulk not supported', 3
288       unless $storage_type !~ /NoBindVars/i;
289
290     lives_ok {
291       $schema->resultset('Artist')->populate([
292         {
293           artistid => 2001,
294           name => 'bulk artist 1',
295           charfield => 'foo',
296         },
297         {
298           artistid => 2002,
299           name => 'bulk artist 2',
300           charfield => 'foo',
301         },
302         {
303           artistid => 2003,
304           name => 'bulk artist 3',
305           charfield => 'foo',
306         },
307       ]);
308     } '_insert_bulk with IDENTITY_INSERT via populate';
309
310     is $bulk_rs->count, 3,
311       'correct number inserted via _insert_bulk with IDENTITY_INSERT';
312
313     is ((grep $_->charfield eq 'foo', $bulk_rs->all), 3,
314       'column set correctly via _insert_bulk with IDENTITY_INSERT');
315
316     $bulk_rs->delete;
317   }
318
319 # test correlated subquery
320   my $subq = $schema->resultset('Artist')->search({ artistid => { '>' => 3 } })
321     ->get_column('artistid')
322     ->as_query;
323   my $subq_rs = $schema->resultset('Artist')->search({
324     artistid => { -in => $subq }
325   });
326   is $subq_rs->count, 11, 'correlated subquery';
327
328 # mostly stolen from the blob stuff Nniuq wrote for t/73oracle.t
329   SKIP: {
330     skip 'TEXT/IMAGE support does not work with FreeTDS', 22
331       if $schema->storage->_using_freetds;
332
333     my $dbh = $schema->storage->_dbh;
334     {
335       local $SIG{__WARN__} = sub {};
336       eval { $dbh->do('DROP TABLE bindtype_test') };
337
338       $dbh->do(qq[
339         CREATE TABLE bindtype_test
340         (
341           id     INT   IDENTITY PRIMARY KEY,
342           bytea  IMAGE NULL,
343           blob   IMAGE NULL,
344           clob   TEXT  NULL,
345           a_memo IMAGE NULL
346         )
347       ],{ RaiseError => 1, PrintError => 0 });
348     }
349
350     my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
351     $binstr{'large'} = $binstr{'small'} x 1024;
352
353     my $maxloblen = length $binstr{'large'};
354
355     if (not $schema->storage->_using_freetds) {
356       $dbh->{'LongReadLen'} = $maxloblen * 2;
357     } else {
358       $dbh->do("set textsize ".($maxloblen * 2));
359     }
360
361     my $rs = $schema->resultset('BindType');
362     my $last_id;
363
364     foreach my $type (qw(blob clob)) {
365       foreach my $size (qw(small large)) {
366         no warnings 'uninitialized';
367
368         my $created;
369         lives_ok {
370           $created = $rs->create( { $type => $binstr{$size} } )
371         } "inserted $size $type without dying";
372
373         $last_id = $created->id if $created;
374
375         lives_and {
376           ok($rs->find($last_id)->$type eq $binstr{$size})
377         } "verified inserted $size $type";
378       }
379     }
380
381     $rs->delete;
382
383     # blob insert with explicit PK
384     # also a good opportunity to test IDENTITY_INSERT
385     lives_ok {
386       $rs->create( { id => 1, blob => $binstr{large} } )
387     } 'inserted large blob without dying with manual PK';
388
389     lives_and {
390       ok($rs->find(1)->blob eq $binstr{large})
391     } 'verified inserted large blob with manual PK';
392
393     # try a blob update
394     my $new_str = $binstr{large} . 'mtfnpy';
395
396     # check redispatch to storage-specific update when auto-detected storage
397     if ($storage_type eq 'DBI::Sybase::ASE') {
398       DBICTest::Schema->storage_type('::DBI');
399       $schema = get_schema();
400     }
401
402     lives_ok {
403       $rs->search({ id => 1 })->update({ blob => $new_str })
404     } 'updated blob successfully';
405
406     lives_and {
407       ok($rs->find(1)->blob eq $new_str)
408     } 'verified updated blob';
409
410     # try a blob update with IDENTITY_UPDATE
411     lives_and {
412       $new_str = $binstr{large} . 'hlagh';
413       $rs->find(1)->update({ id => 999, blob => $new_str });
414       ok($rs->find(999)->blob eq $new_str);
415     } 'verified updated blob with IDENTITY_UPDATE';
416
417     ## try multi-row blob update
418     # first insert some blobs
419     $new_str = $binstr{large} . 'foo';
420     lives_and {
421       $rs->delete;
422       $rs->create({ blob => $binstr{large} }) for (1..2);
423       $rs->update({ blob => $new_str });
424       is((grep $_->blob eq $new_str, $rs->all), 2);
425     } 'multi-row blob update';
426
427     $rs->delete;
428
429     # now try _insert_bulk with blobs and only blobs
430     $new_str = $binstr{large} . 'bar';
431     lives_ok {
432       $rs->populate([
433         {
434           blob => $binstr{large},
435           clob => $new_str,
436         },
437         {
438           blob => $binstr{large},
439           clob => $new_str,
440         },
441       ]);
442     } '_insert_bulk with blobs does not die';
443
444     is((grep $_->blob eq $binstr{large}, $rs->all), 2,
445       'IMAGE column set correctly via _insert_bulk');
446
447     is((grep $_->clob eq $new_str, $rs->all), 2,
448       'TEXT column set correctly via _insert_bulk');
449
450     # now try _insert_bulk with blobs and a non-blob which also happens to be an
451     # identity column
452     SKIP: {
453       skip 'no _insert_bulk without placeholders', 4
454         if $storage_type =~ /NoBindVars/i;
455
456       $rs->delete;
457       $new_str = $binstr{large} . 'bar';
458       lives_ok {
459         $rs->populate([
460           {
461             id => 1,
462             bytea => 1,
463             blob => $binstr{large},
464             clob => $new_str,
465             a_memo => 2,
466           },
467           {
468             id => 2,
469             bytea => 1,
470             blob => $binstr{large},
471             clob => $new_str,
472             a_memo => 2,
473           },
474         ]);
475       } '_insert_bulk with blobs and explicit identity does NOT die';
476
477       is((grep $_->blob eq $binstr{large}, $rs->all), 2,
478         'IMAGE column set correctly via _insert_bulk with identity');
479
480       is((grep $_->clob eq $new_str, $rs->all), 2,
481         'TEXT column set correctly via _insert_bulk with identity');
482
483       is_deeply [ map $_->id, $rs->all ], [ 1,2 ],
484         'explicit identities set correctly via _insert_bulk with blobs';
485     }
486
487     lives_and {
488       $rs->delete;
489       $rs->create({ blob => $binstr{large} }) for (1..2);
490       $rs->update({ blob => undef });
491       is((grep !defined($_->blob), $rs->all), 2);
492     } 'blob update to NULL';
493   }
494
495 # test MONEY column support (and some other misc. stuff)
496   $schema->storage->dbh_do (sub {
497       my ($storage, $dbh) = @_;
498       eval { $dbh->do("DROP TABLE money_test") };
499       $dbh->do(<<'SQL');
500 CREATE TABLE money_test (
501    id INT IDENTITY PRIMARY KEY,
502    amount MONEY DEFAULT $999.99 NULL
503 )
504 SQL
505   });
506
507   my $rs = $schema->resultset('Money');
508
509 # test insert with defaults
510   lives_and {
511     $rs->create({});
512     is((grep $_->amount == 999.99, $rs->all), 1);
513   } 'insert with all defaults works';
514   $rs->delete;
515
516 # test insert transaction when there's an active cursor
517   {
518     my $artist_rs = $schema->resultset('Artist');
519     $artist_rs->first;
520     lives_ok {
521       my $row = $schema->resultset('Money')->create({ amount => 100 });
522       $row->delete;
523     } 'inserted a row with an active cursor';
524     $ping_count-- if $@; # dbh_do calls ->connected
525   }
526
527 # test insert in an outer transaction when there's an active cursor
528   {
529     local $TODO = 'this should work once we have eager cursors';
530
531 # clear state, or we get a deadlock on $row->delete
532 # XXX figure out why this happens
533     $schema->storage->disconnect;
534
535     lives_ok {
536       $schema->txn_do(sub {
537         my $artist_rs = $schema->resultset('Artist');
538         $artist_rs->first;
539         my $row = $schema->resultset('Money')->create({ amount => 100 });
540         $row->delete;
541       });
542     } 'inserted a row with an active cursor in outer txn';
543     $ping_count-- if $@; # dbh_do calls ->connected
544   }
545
546 # Now test money values.
547   my $row;
548   lives_ok {
549     $row = $rs->create({ amount => 100 });
550   } 'inserted a money value';
551
552   cmp_ok eval { $rs->find($row->id)->amount }, '==', 100,
553     'money value round-trip';
554
555   lives_ok {
556     $row->update({ amount => 200 });
557   } 'updated a money value';
558
559   cmp_ok eval { $rs->find($row->id)->amount }, '==', 200,
560     'updated money value round-trip';
561
562   lives_ok {
563     $row->update({ amount => undef });
564   } 'updated a money value to NULL';
565
566   lives_and {
567     my $null_amount = $rs->find($row->id)->amount;
568     is $null_amount, undef;
569   } 'updated money value to NULL round-trip';
570
571 # Test computed columns and timestamps
572   $schema->storage->dbh_do (sub {
573       my ($storage, $dbh) = @_;
574       eval { $dbh->do("DROP TABLE computed_column_test") };
575       $dbh->do(<<'SQL');
576 CREATE TABLE computed_column_test (
577    id INT IDENTITY PRIMARY KEY,
578    a_computed_column AS getdate(),
579    a_timestamp timestamp,
580    charfield VARCHAR(20) DEFAULT 'foo'
581 )
582 SQL
583   });
584
585   require DBICTest::Schema::ComputedColumn;
586   $schema->register_class(
587     ComputedColumn => 'DBICTest::Schema::ComputedColumn'
588   );
589
590   ok (($rs = $schema->resultset('ComputedColumn')),
591     'got rs for ComputedColumn');
592
593   lives_ok { $row = $rs->create({}) }
594     'empty insert for a table with computed columns survived';
595
596   lives_ok {
597     $row->update({ charfield => 'bar' })
598   } 'update of a table with computed columns survived';
599 }
600
601 is $ping_count, 0, 'no pings';
602
603 # if tests passed and did so under a non-C lang - let's rerun the test
604 if (Test::Builder->new->is_passing and $ENV{LANG} and $ENV{LANG} ne 'C') {
605   my $oldlang = $ENV{LANG};
606   local $ENV{LANG} = 'C';
607
608   pass ("Your lang is set to $oldlang - retesting with C");
609
610   local $ENV{PATH};
611   my @cmd = map { $_ =~ /(.+)/ } ($^X, __FILE__);
612
613   # this is cheating, and may even hang here and there (testing on windows passed fine)
614   # will be replaced with Test::SubExec::Noninteractive in due course
615   require IPC::Open2;
616   IPC::Open2::open2(my $out, undef, @cmd);
617   while (my $ln = <$out>) {
618     print "   $ln";
619   }
620
621   wait;
622   ok (! $?, "Wstat $? from: @cmd");
623 }
624
625 done_testing;
626
627 # clean up our mess
628 END {
629   if (my $dbh = eval { $schema->storage->_dbh }) {
630     eval { $dbh->do("DROP TABLE $_") }
631       for qw/artist bindtype_test money_test computed_column_test/;
632   }
633
634   undef $schema;
635 }