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