Add all storage instances to the test suite leaktracing pool
[dbsrgits/DBIx-Class.git] / t / 73oracle.t
CommitLineData
4bea1fe7 1use strict;
2use warnings;
3
4use Test::Exception;
5use Test::More;
6use Sub::Name;
00a28188 7use Try::Tiny;
199fbc45 8use DBIx::Class::Optional::Dependencies ();
4bea1fe7 9
10use lib qw(t/lib);
11use DBICTest;
12use DBIC::SqlMakerTest;
13
4bea1fe7 14my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_ORA_${_}" } qw/DSN USER PASS/};
15
16# optional:
17my ($dsn2, $user2, $pass2) = @ENV{map { "DBICTEST_ORA_EXTRAUSER_${_}" } qw/DSN USER PASS/};
18
19plan skip_all => 'Set $ENV{DBICTEST_ORA_DSN}, _USER and _PASS to run this test.'
20 unless ($dsn && $user && $pass);
21
e6983054 22plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_rdbms_oracle')
23 unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_rdbms_oracle');
24
25$ENV{NLS_SORT} = "BINARY";
26$ENV{NLS_COMP} = "BINARY";
27$ENV{NLS_LANG} = "AMERICAN";
28
cb464582 29{
30 package # hide from PAUSE
31 DBICTest::Schema::ArtistFQN;
32
33 use base 'DBIx::Class::Core';
34
35 __PACKAGE__->table(
a6646e1b 36 $ENV{DBICTEST_ORA_USER}
07cda1c5 37 ? (uc $ENV{DBICTEST_ORA_USER}) . '.artist'
a6646e1b 38 : '??_no_user_??'
cb464582 39 );
40 __PACKAGE__->add_columns(
07cda1c5 41 'artistid' => {
42 data_type => 'integer',
43 is_auto_increment => 1,
44 },
45 'name' => {
46 data_type => 'varchar',
47 size => 100,
48 is_nullable => 1,
49 },
50 'autoinc_col' => {
51 data_type => 'integer',
52 is_auto_increment => 1,
53 },
8b9473f5 54 'default_value_col' => {
55 data_type => 'varchar',
56 size => 100,
57 is_nullable => 0,
58 retrieve_on_insert => 1,
59 }
cb464582 60 );
bf51641f 61 __PACKAGE__->set_primary_key(qw/ artistid autoinc_col /);
cb464582 62
63 1;
64}
65
cb464582 66DBICTest::Schema->load_classes('ArtistFQN');
0567538f 67
07cda1c5 68# This is in Core now, but it's here just to test that it doesn't break
69DBICTest::Schema::Artist->load_components('PK::Auto');
70# These are compat shims for PK::Auto...
71DBICTest::Schema::CD->load_components('PK::Auto::Oracle');
72DBICTest::Schema::Track->load_components('PK::Auto::Oracle');
ba12b23f 73
0567538f 74
bf51641f 75# check if we indeed do support stuff
f116ff4e 76my $v = do {
77 my $v = DBICTest::Schema->connect($dsn, $user, $pass)->storage->_dbh_get_info(18);
bf51641f 78 $v =~ /^(\d+)\.(\d+)/
79 or die "Unparseable Oracle server version: $v\n";
80
f116ff4e 81 sprintf('%d.%03d', $1, $2);
82};
83
538878de 84my $test_server_supports_only_orajoins = $v < 9;
f116ff4e 85
bf51641f 86# TODO find out which version supports the RETURNING syntax
86b23415 87# 8i (8.1) has it and earlier docs are a 404 on oracle.com
f116ff4e 88my $test_server_supports_insert_returning = $v >= 8.001;
89
bf51641f 90is (
91 DBICTest::Schema->connect($dsn, $user, $pass)->storage->_use_insert_returning,
92 $test_server_supports_insert_returning,
93 'insert returning capability guessed correctly'
94);
95
f116ff4e 96##########
538878de 97# the recyclebin (new for 10g) sometimes comes in the way
98my $on_connect_sql = $v >= 10 ? ["ALTER SESSION SET recyclebin = OFF"] : [];
f116ff4e 99
100# iterate all tests on following options
101my @tryopt = (
102 { on_connect_do => $on_connect_sql },
103 { quote_char => '"', on_connect_do => $on_connect_sql },
104);
105
106# keep a database handle open for cleanup
107my ($dbh, $dbh2);
108
bf51641f 109my $schema;
f116ff4e 110for my $use_insert_returning ($test_server_supports_insert_returning ? (1,0) : (0) ) {
111 for my $force_ora_joins ($test_server_supports_only_orajoins ? (0) : (0,1) ) {
112
6892eb09 113 no warnings qw/once redefine/;
114 my $old_connection = DBICTest::Schema->can('connection');
f116ff4e 115 local *DBICTest::Schema::connection = subname 'DBICTest::Schema::connection' => sub {
6892eb09 116 my $s = shift->$old_connection (@_);
f116ff4e 117 $s->storage->_use_insert_returning ($use_insert_returning);
118 $s->storage->sql_maker_class('DBIx::Class::SQLMaker::OracleJoins') if $force_ora_joins;
119 $s;
120 };
121
122 for my $opt (@tryopt) {
123 # clean all cached sequences from previous run
124 for (map { values %{DBICTest::Schema->source($_)->columns_info} } (qw/Artist CD Track/) ) {
125 delete $_->{sequence};
126 }
bf51641f 127
f116ff4e 128 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opt);
07cda1c5 129
f116ff4e 130 $dbh = $schema->storage->dbh;
131 my $q = $schema->storage->sql_maker->quote_char || '';
bf51641f 132
f116ff4e 133 do_creates($dbh, $q);
bf51641f 134
f116ff4e 135 _run_tests($schema, $opt);
136 }
bf51641f 137 }
138}
07cda1c5 139
bf51641f 140sub _run_tests {
141 my ($schema, $opt) = @_;
07cda1c5 142
bf51641f 143 my $q = $schema->storage->sql_maker->quote_char || '';
ab4f4e4c 144
145# test primary key handling with multiple triggers
07cda1c5 146 my ($new, $seq);
0567538f 147
bf51641f 148 my $new_artist = $schema->resultset('Artist')->create({ name => 'foo' });
149 my $new_cd = $schema->resultset('CD')->create({ artist => 1, title => 'EP C', year => '2003' });
6f5f880d 150
bf51641f 151 SKIP: {
152 skip 'not detecting sequences when using INSERT ... RETURNING', 4
153 if $schema->storage->_use_insert_returning;
154
155 is($new_artist->artistid, 1, "Oracle Auto-PK worked for standard sqlt-like trigger");
156 $seq = $new_artist->result_source->column_info('artistid')->{sequence};
157 $seq = $$seq if ref $seq;
158 like ($seq, qr/\.${q}artist_pk_seq${q}$/, 'Correct PK sequence selected for sqlt-like trigger');
159
160 is($new_cd->cdid, 1, 'Oracle Auto-PK worked - using scalar ref as table name/custom weird trigger');
161 $seq = $new_cd->result_source->column_info('cdid')->{sequence};
162 $seq = $$seq if ref $seq;
163 like ($seq, qr/\.${q}cd_seq${q}$/, 'Correct PK sequence selected for custom trigger');
164 }
e6dd7b42 165
07cda1c5 166# test PKs again with fully-qualified table name
167 my $artistfqn_rs = $schema->resultset('ArtistFQN');
168 my $artist_rsrc = $artistfqn_rs->result_source;
ab4f4e4c 169
07cda1c5 170 delete $artist_rsrc->column_info('artistid')->{sequence};
171 $new = $artistfqn_rs->create( { name => 'bar' } );
ab4f4e4c 172
bf51641f 173 is_deeply( {map { $_ => $new->$_ } $artist_rsrc->primary_columns},
174 { artistid => 2, autoinc_col => 2},
175 "Oracle Multi-Auto-PK worked with fully-qualified tablename" );
cb464582 176
ab4f4e4c 177
07cda1c5 178 delete $artist_rsrc->column_info('artistid')->{sequence};
179 $new = $artistfqn_rs->create( { name => 'bar', autoinc_col => 1000 } );
180
181 is( $new->artistid, 3, "Oracle Auto-PK worked with fully-qualified tablename" );
182 is( $new->autoinc_col, 1000, "Oracle Auto-Inc overruled with fully-qualified tablename");
bf51641f 183
8b9473f5 184
185 is( $new->default_value_col, 'default_value', $schema->storage->_use_insert_returning
186 ? 'Check retrieve_on_insert on default_value_col with INSERT ... RETURNING'
187 : 'Check retrieve_on_insert on default_value_col without INSERT ... RETURNING'
188 );
189
bf51641f 190 SKIP: {
191 skip 'not detecting sequences when using INSERT ... RETURNING', 1
192 if $schema->storage->_use_insert_returning;
193
194 $seq = $new->result_source->column_info('artistid')->{sequence};
195 $seq = $$seq if ref $seq;
196 like ($seq, qr/\.${q}artist_pk_seq${q}$/, 'Correct PK sequence selected for sqlt-like trigger');
197 }
ab4f4e4c 198
ab4f4e4c 199
200# test LIMIT support
07cda1c5 201 for (1..6) {
ab4f4e4c 202 $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
07cda1c5 203 }
204 my $it = $schema->resultset('Artist')->search( { name => { -like => 'Artist %' } }, {
205 rows => 3,
206 offset => 4,
207 order_by => 'artistid'
208 });
209
210 is( $it->count, 2, "LIMIT count past end of RS ok" );
211 is( $it->next->name, "Artist 5", "iterator->next ok" );
212 is( $it->next->name, "Artist 6", "iterator->next ok" );
213 is( $it->next, undef, "next past end of resultset ok" );
214
07cda1c5 215# test identifiers over the 30 char limit
216 lives_ok {
217 my @results = $schema->resultset('CD')->search(undef, {
218 prefetch => 'very_long_artist_relationship',
219 rows => 3,
220 offset => 0,
221 })->all;
222 ok( scalar @results > 0, 'limit with long identifiers returned something');
223 } 'limit with long identifiers executed successfully';
ab4f4e4c 224
ab4f4e4c 225
62d4dbae 226# test rel names over the 30 char limit
ab4f4e4c 227 my $query = $schema->resultset('Artist')->search({
228 artistid => 1
6c0230de 229 }, {
230 prefetch => 'cds_very_very_very_long_relationship_name'
231 });
232
233 lives_and {
07cda1c5 234 is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
ab4f4e4c 235 } 'query with rel name over 30 chars survived and worked';
236
19c4cc62 237# test rel names over the 30 char limit using group_by and join
238 {
239 my @group_cols = ( 'me.name' );
240 my $query = $schema->resultset('Artist')->search({
241 artistid => 1
242 }, {
243 select => \@group_cols,
244 as => [map { /^\w+\.(\w+)$/ } @group_cols],
245 join => [qw( cds_very_very_very_long_relationship_name )],
246 group_by => \@group_cols,
247 });
248
249 lives_and {
250 my @got = $query->get_column('name')->all();
251 is_deeply \@got, [$new_artist->name];
252 } 'query with rel name over 30 chars worked on join, group_by for me col';
253
254 lives_and {
255 is $query->count(), 1
256 } 'query with rel name over 30 chars worked on join, group_by, count for me col';
257 }
258 {
259 my @group_cols = ( 'cds_very_very_very_long_relationship_name.title' );
260 my $query = $schema->resultset('Artist')->search({
261 artistid => 1
262 }, {
263 select => \@group_cols,
264 as => [map { /^\w+\.(\w+)$/ } @group_cols],
265 join => [qw( cds_very_very_very_long_relationship_name )],
266 group_by => \@group_cols,
267 });
268
269 lives_and {
270 my @got = $query->get_column('title')->all();
271 is_deeply \@got, [$new_cd->title];
272 } 'query with rel name over 30 chars worked on join, group_by for long rel col';
273
274 lives_and {
275 is $query->count(), 1
276 } 'query with rel name over 30 chars worked on join, group_by, count for long rel col';
277 }
278
ab4f4e4c 279 # rel name over 30 char limit with user condition
280 # This requires walking the SQLA data structure.
281 {
ab4f4e4c 282 $query = $schema->resultset('Artist')->search({
283 'cds_very_very_very_long_relationship_name.title' => 'EP C'
284 }, {
285 prefetch => 'cds_very_very_very_long_relationship_name'
286 });
287
288 lives_and {
289 is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
290 } 'query with rel name over 30 chars and user condition survived and worked';
291 }
07cda1c5 292
6c0230de 293
9900b569 294# test join with row count ambiguity
07cda1c5 295 my $cd = $schema->resultset('CD')->next;
296 my $track = $cd->create_related('tracks', { position => 1, title => 'Track1'} );
297 my $tjoin = $schema->resultset('Track')->search({ 'me.title' => 'Track1'}, {
298 join => 'cd', rows => 2
299 });
d2a3958e 300
07cda1c5 301 ok(my $row = $tjoin->next);
302
303 is($row->title, 'Track1', "ambiguous column ok");
2660b14e 304
d2a3958e 305
2660b14e 306
286f32b3 307# check count distinct with multiple columns
07cda1c5 308 my $other_track = $schema->resultset('Track')->create({ cd => $cd->cdid, position => 1, title => 'Track2' });
11d68671 309
07cda1c5 310 my $tcount = $schema->resultset('Track')->search(
311 {},
312 {
313 select => [ qw/position title/ ],
314 distinct => 1,
315 }
316 );
317 is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
11d68671 318
07cda1c5 319 $tcount = $schema->resultset('Track')->search(
320 {},
321 {
322 columns => [ qw/position title/ ],
323 distinct => 1,
324 }
325 );
326 is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
286f32b3 327
07cda1c5 328 $tcount = $schema->resultset('Track')->search(
329 {},
330 {
331 group_by => [ qw/position title/ ]
332 }
333 );
334 is($tcount->count, 2, 'multiple column COUNT DISTINCT using column syntax ok');
2660b14e 335
e8e971f2 336
07cda1c5 337# check group_by
338 my $g_rs = $schema->resultset('Track')->search( undef, { columns=>[qw/trackid position/], group_by=> [ qw/trackid position/ ] , rows => 2, offset => 1 });
339 is( scalar $g_rs->all, 1, "Group by with limit OK" );
340
bd691933 341
b7b18f32 342# test with_deferred_fk_checks
07cda1c5 343 lives_ok {
344 $schema->storage->with_deferred_fk_checks(sub {
345 $schema->resultset('Track')->create({
346 trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
347 });
348 $schema->resultset('CD')->create({
349 artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
350 });
b7b18f32 351 });
07cda1c5 352 } 'with_deferred_fk_checks code survived';
b7b18f32 353
07cda1c5 354 is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
8b9473f5 355 'code in with_deferred_fk_checks worked';
07cda1c5 356
357 throws_ok {
358 $schema->resultset('Track')->create({
359 trackid => 1, cd => 9999, position => 1, title => 'Track1'
360 });
361 } qr/constraint/i, 'with_deferred_fk_checks is off';
b7b18f32 362
b7b18f32 363
ccd6f984 364# test auto increment using sequences WITHOUT triggers
07cda1c5 365 for (1..5) {
39b8d119 366 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
367 is($st->pkid1, $_, "Oracle Auto-PK without trigger: First primary key");
368 is($st->pkid2, $_ + 9, "Oracle Auto-PK without trigger: Second primary key");
369 is($st->nonpkid, $_ + 19, "Oracle Auto-PK without trigger: Non-primary key");
07cda1c5 370 }
371 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
372 is($st->pkid1, 55, "Oracle Auto-PK without trigger: First primary key set manually");
373
ccd6f984 374
12e05c15 375# test BLOBs
07cda1c5 376 SKIP: {
377 TODO: {
378 my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
379 $binstr{'large'} = $binstr{'small'} x 1024;
8068691e 380
00a28188 381 my $maxloblen = (length $binstr{'large'}) + 5;
07cda1c5 382 note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
383 local $dbh->{'LongReadLen'} = $maxloblen;
5db2758d 384
07cda1c5 385 my $rs = $schema->resultset('BindType');
5db2758d 386
07cda1c5 387 if ($DBD::Oracle::VERSION eq '1.23') {
388 throws_ok { $rs->create({ id => 1, blob => $binstr{large} }) }
389 qr/broken/,
390 'throws on blob insert with DBD::Oracle == 1.23';
5db2758d 391
00a28188 392 skip 'buggy BLOB support in DBD::Oracle 1.23', 1;
07cda1c5 393 }
5db2758d 394
07cda1c5 395 # disable BLOB mega-output
396 my $orig_debug = $schema->storage->debug;
f3f6c13a 397
07cda1c5 398 local $TODO = 'Something is confusing column bindtype assignment when quotes are active'
86b23415 399 . ': https://rt.cpan.org/Ticket/Display.html?id=64206'
07cda1c5 400 if $q;
5db2758d 401
00a28188 402 my $id;
403 foreach my $size (qw( small large )) {
404 $id++;
d7f20fdf 405
00819de0 406 if ($size eq 'small') {
407 $schema->storage->debug($orig_debug);
408 }
409 elsif ($size eq 'large') {
410 $schema->storage->debug(0);
411 }
412
00a28188 413 my $str = $binstr{$size};
414 lives_ok {
415 $rs->create( { 'id' => $id, blob => "blob:$str", clob => "clob:$str" } )
416 } "inserted $size without dying";
417
5e782048 418 my %kids = %{$schema->storage->_dbh->{CachedKids}};
00a28188 419 my @objs = $rs->search({ blob => "blob:$str", clob => "clob:$str" })->all;
5e782048 420 is_deeply (
421 $schema->storage->_dbh->{CachedKids},
422 \%kids,
423 'multi-part LOB equality query was not cached',
424 ) if $size eq 'large';
425 is @objs, 1, 'One row found matching on both LOBs';
00a28188 426 ok (try { $objs[0]->blob }||'' eq "blob:$str", 'blob inserted/retrieved correctly');
427 ok (try { $objs[0]->clob }||'' eq "clob:$str", 'clob inserted/retrieved correctly');
428
b1efaea0 429 TODO: {
430 local $TODO = '-like comparison on blobs not tested before ora 10 (fails on 8i)'
431 if $schema->storage->_server_info->{normalized_dbms_version} < 10;
432
433 lives_ok {
434 @objs = $rs->search({ clob => { -like => 'clob:%' } })->all;
435 ok (@objs, 'rows found matching CLOB with a LIKE query');
436 } 'Query with like on blob succeeds';
437 }
00a28188 438
5e782048 439 ok(my $subq = $rs->search(
440 { blob => "blob:$str", clob => "clob:$str" },
441 {
442 from => \ "(SELECT * FROM ${q}bindtype_test${q} WHERE ${q}id${q} != ?) ${q}me${q}",
443 bind => [ [ undef => 12345678 ] ],
444 }
445 )->get_column('id')->as_query);
00a28188 446
447 @objs = $rs->search({ id => { -in => $subq } })->all;
448 is (@objs, 1, 'One row found matching on both LOBs as a subquery');
5e782048 449
450 lives_ok {
00819de0 451 $rs->search({ id => $id, blob => "blob:$str", clob => "clob:$str" })
5e782048 452 ->update({ blob => 'updated blob', clob => 'updated clob' });
e12571af 453 } 'blob UPDATE with blobs in WHERE clause survived';
5e782048 454
455 @objs = $rs->search({ blob => "updated blob", clob => 'updated clob' })->all;
456 is @objs, 1, 'found updated row';
457 ok (try { $objs[0]->blob }||'' eq "updated blob", 'blob updated/retrieved correctly');
458 ok (try { $objs[0]->clob }||'' eq "updated clob", 'clob updated/retrieved correctly');
459
460 lives_ok {
e12571af 461 $rs->search({ id => $id })
462 ->update({ blob => 're-updated blob', clob => 're-updated clob' });
463 } 'blob UPDATE without blobs in WHERE clause survived';
464
465 @objs = $rs->search({ blob => 're-updated blob', clob => 're-updated clob' })->all;
466 is @objs, 1, 'found updated row';
467 ok (try { $objs[0]->blob }||'' eq 're-updated blob', 'blob updated/retrieved correctly');
468 ok (try { $objs[0]->clob }||'' eq 're-updated clob', 'clob updated/retrieved correctly');
469
470 lives_ok {
471 $rs->search({ blob => "re-updated blob", clob => "re-updated clob" })
5e782048 472 ->delete;
473 } 'blob DELETE with WHERE clause survived';
e12571af 474 @objs = $rs->search({ blob => "re-updated blob", clob => 're-updated clob' })->all;
5e782048 475 is @objs, 0, 'row deleted successfully';
d7f20fdf 476 }
f3f6c13a 477
07cda1c5 478 $schema->storage->debug ($orig_debug);
479 }}
480
a5a27e7a 481# test populate (identity, success and error handling)
482 my $art_rs = $schema->resultset('Artist');
483
484 my $seq_pos = $art_rs->get_column('artistid')->max;
485 ok($seq_pos, 'Starting with something in the artist table');
486
487
488 my $pop_rs = $schema->resultset('Artist')->search(
489 { name => { -like => 'pop_art_%' } },
490 { order_by => 'artistid' }
491 );
492
493 $art_rs->delete;
494 lives_ok {
495 $pop_rs->populate([
496 map { +{ name => "pop_art_$_" } }
497 (1,2,3)
498 ]);
499
500 is_deeply (
501 [ $pop_rs->get_column('artistid')->all ],
502 [ map { $seq_pos + $_ } (1,2,3) ],
503 'Sequence works after empty-table insertion'
504 );
505 } 'Populate without identity does not throw';
506
507 lives_ok {
508 $pop_rs->populate([
509 map { +{ artistid => $_, name => "pop_art_$_" } }
510 (1,2,3)
511 ]);
512
513 is_deeply (
514 [ $pop_rs->get_column('artistid')->all ],
515 [ 1,2,3, map { $seq_pos + $_ } (1,2,3) ],
516 'Explicit id population works'
517 );
518 } 'Populate with identity does not throw';
519
520 throws_ok {
521 $pop_rs->populate([
522 map { +{ artistid => $_, name => "pop_art_$_" } }
523 (200, 1, 300)
524 ]);
525 } qr/unique constraint.+populate slice.+name => "pop_art_1"/s, 'Partially failed populate throws';
526
527 is_deeply (
528 [ $pop_rs->get_column('artistid')->all ],
529 [ 1,2,3, map { $seq_pos + $_ } (1,2,3) ],
530 'Partially failed populate did not alter table contents'
531 );
5db2758d 532
f116ff4e 533# test complex join (exercise orajoins)
534 lives_ok {
535 my @hri = $schema->resultset('CD')->search(
536 { 'artist.name' => 'pop_art_1', 'me.cdid' => { '!=', 999} },
537 { join => 'artist', prefetch => 'tracks', rows => 4, order_by => 'tracks.trackid' }
538 )->hri_dump->all;
539
540 my $expect = [{
541 artist => 1,
542 cdid => 1,
543 genreid => undef,
544 single_track => undef,
545 title => "EP C",
546 tracks => [
547 {
548 cd => 1,
549 last_updated_at => undef,
550 last_updated_on => undef,
551 position => 1,
552 title => "Track1",
553 trackid => 1
554 },
555 {
556 cd => 1,
557 last_updated_at => undef,
558 last_updated_on => undef,
559 position => 1,
560 title => "Track2",
561 trackid => 2
562 },
563 ],
564 year => 2003
565 }];
566
567 is_deeply (
568 \@hri,
569 $expect,
570 'Correct set of data prefetched',
571 );
572
573 } 'complex prefetch ok';
574
df6e3f5c 575# test sequence detection from a different schema
07cda1c5 576 SKIP: {
577 TODO: {
578 skip ((join '',
579 'Set DBICTEST_ORA_EXTRAUSER_DSN, _USER and _PASS to a *DIFFERENT* Oracle user',
bf51641f 580 ' to run the cross-schema sequence detection test.'),
07cda1c5 581 1) unless $dsn2 && $user2 && $user2 ne $user;
9d7d2f00 582
bf51641f 583 skip 'not detecting cross-schema sequence name when using INSERT ... RETURNING', 1
584 if $schema->storage->_use_insert_returning;
585
8b9473f5 586 # Oracle8i Reference Release 2 (8.1.6)
07cda1c5 587 # http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76961/ch294.htm#993
588 # Oracle Database Reference 10g Release 2 (10.2)
589 # http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#sthref1297
590 local $TODO = "On Oracle8i all_triggers view is empty, i don't yet know why..."
591 if $schema->storage->_server_info->{normalized_dbms_version} < 9;
606b30c3 592
bf51641f 593 my $schema2 = $schema->connect($dsn2, $user2, $pass2, $opt);
a6646e1b 594 my $dbh2 = $schema2->storage->dbh;
df6e3f5c 595
a6646e1b 596 # create identically named tables/sequences in the other schema
597 do_creates($dbh2, $q);
df6e3f5c 598
a6646e1b 599 # grand select privileges to the 2nd user
600 $dbh->do("GRANT INSERT ON ${q}artist${q} TO " . uc $user2);
8b9473f5 601 $dbh->do("GRANT SELECT ON ${q}artist${q} TO " . uc $user2);
a6646e1b 602 $dbh->do("GRANT SELECT ON ${q}artist_pk_seq${q} TO " . uc $user2);
603 $dbh->do("GRANT SELECT ON ${q}artist_autoinc_seq${q} TO " . uc $user2);
df6e3f5c 604
a6646e1b 605 # test with a fully qualified table (user1/schema prepended)
606 my $rs2 = $schema2->resultset('ArtistFQN');
607 delete $rs2->result_source->column_info('artistid')->{sequence};
df6e3f5c 608
07cda1c5 609 lives_and {
a6646e1b 610 my $row = $rs2->create({ name => 'From Different Schema' });
07cda1c5 611 ok $row->artistid;
612 } 'used autoinc sequence across schemas';
613
614 # now quote the sequence name (do_creates always uses an lc name)
615 my $q_seq = $q
616 ? '"artist_pk_seq"'
617 : '"ARTIST_PK_SEQ"'
618 ;
a6646e1b 619 delete $rs2->result_source->column_info('artistid')->{sequence};
620 $dbh->do(qq{
07cda1c5 621 CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
622 BEFORE INSERT ON ${q}artist${q}
623 FOR EACH ROW
624 BEGIN
625 IF :new.${q}artistid${q} IS NULL THEN
626 SELECT $q_seq.nextval
627 INTO :new.${q}artistid${q}
628 FROM DUAL;
629 END IF;
630 END;
631 });
72044892 632
72044892 633
07cda1c5 634 lives_and {
a6646e1b 635 my $row = $rs2->create({ name => 'From Different Schema With Quoted Sequence' });
07cda1c5 636 ok $row->artistid;
637 } 'used quoted autoinc sequence across schemas';
72044892 638
a6646e1b 639 is_deeply $rs2->result_source->column_info('artistid')->{sequence},
640 \( (uc $user) . ".$q_seq"),
07cda1c5 641 'quoted sequence name correctly extracted';
a6646e1b 642
643 # try an insert operation on the default user2 artist
644 my $art1 = $schema->resultset('Artist');
645 my $art2 = $schema2->resultset('Artist');
646 my $art1_count = $art1->count || 0;
647 my $art2_count = $art2->count;
648
649 is( $art2_count, 0, 'No artists created yet in second schema' );
650
651 delete $art2->result_source->column_info('artistid')->{sequence};
652 my $new_art = $art2->create({ name => '2nd best' });
653
654 is ($art1->count, $art1_count, 'No new rows in main schema');
655 is ($art2->count, 1, 'One artist create in 2nd schema');
656
657 is( $new_art->artistid, 1, 'Expected first PK' );
658
659 do_clean ($dbh2);
07cda1c5 660 }}
661
662 do_clean ($dbh);
663}
df6e3f5c 664
86cc4156 665done_testing;
666
df6e3f5c 667sub do_creates {
07cda1c5 668 my ($dbh, $q) = @_;
669
670 do_clean($dbh);
671
672 $dbh->do("CREATE SEQUENCE ${q}artist_autoinc_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
673 $dbh->do("CREATE SEQUENCE ${q}artist_pk_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
674 $dbh->do("CREATE SEQUENCE ${q}cd_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
675 $dbh->do("CREATE SEQUENCE ${q}track_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
676
677 $dbh->do("CREATE SEQUENCE ${q}nonpkid_seq${q} START WITH 20 MAXVALUE 999999 MINVALUE 0");
678 # this one is always quoted as per manually specified sequence =>
679 $dbh->do('CREATE SEQUENCE "pkid1_seq" START WITH 1 MAXVALUE 999999 MINVALUE 0');
680 # this one is always unquoted as per manually specified sequence =>
df6e3f5c 681 $dbh->do("CREATE SEQUENCE pkid2_seq START WITH 10 MAXVALUE 999999 MINVALUE 0");
df6e3f5c 682
8b9473f5 683 $dbh->do("CREATE TABLE ${q}artist${q} (${q}artistid${q} NUMBER(12), ${q}name${q} VARCHAR(255),${q}default_value_col${q} VARCHAR(255) DEFAULT 'default_value', ${q}autoinc_col${q} NUMBER(12), ${q}rank${q} NUMBER(38), ${q}charfield${q} VARCHAR2(10))");
07cda1c5 684 $dbh->do("ALTER TABLE ${q}artist${q} ADD (CONSTRAINT ${q}artist_pk${q} PRIMARY KEY (${q}artistid${q}))");
df6e3f5c 685
07cda1c5 686 $dbh->do("CREATE TABLE ${q}sequence_test${q} (${q}pkid1${q} NUMBER(12), ${q}pkid2${q} NUMBER(12), ${q}nonpkid${q} NUMBER(12), ${q}name${q} VARCHAR(255))");
687 $dbh->do("ALTER TABLE ${q}sequence_test${q} ADD (CONSTRAINT ${q}sequence_test_constraint${q} PRIMARY KEY (${q}pkid1${q}, ${q}pkid2${q}))");
df6e3f5c 688
07cda1c5 689 # table cd will be unquoted => Oracle will see it as uppercase
690 $dbh->do("CREATE TABLE cd (${q}cdid${q} NUMBER(12), ${q}artist${q} NUMBER(12), ${q}title${q} VARCHAR(255), ${q}year${q} VARCHAR(4), ${q}genreid${q} NUMBER(12), ${q}single_track${q} NUMBER(12))");
691 $dbh->do("ALTER TABLE cd ADD (CONSTRAINT ${q}cd_pk${q} PRIMARY KEY (${q}cdid${q}))");
df6e3f5c 692
3d98c75e 693 $dbh->do("CREATE TABLE ${q}track${q} (${q}trackid${q} NUMBER(12), ${q}cd${q} NUMBER(12) REFERENCES CD(${q}cdid${q}) DEFERRABLE, ${q}position${q} NUMBER(12), ${q}title${q} VARCHAR(255), ${q}last_updated_on${q} DATE, ${q}last_updated_at${q} DATE)");
07cda1c5 694 $dbh->do("ALTER TABLE ${q}track${q} ADD (CONSTRAINT ${q}track_pk${q} PRIMARY KEY (${q}trackid${q}))");
df6e3f5c 695
f3a9ea3d 696 $dbh->do("CREATE TABLE ${q}bindtype_test${q} (${q}id${q} integer NOT NULL PRIMARY KEY, ${q}bytea${q} integer NULL, ${q}blob${q} blob NULL, ${q}clob${q} clob NULL, ${q}a_memo${q} integer NULL)");
12e05c15 697
df6e3f5c 698 $dbh->do(qq{
07cda1c5 699 CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_auto${q}
700 BEFORE INSERT ON ${q}artist${q}
ab4f4e4c 701 FOR EACH ROW
702 BEGIN
07cda1c5 703 IF :new.${q}autoinc_col${q} IS NULL THEN
704 SELECT ${q}artist_autoinc_seq${q}.nextval
705 INTO :new.${q}autoinc_col${q}
ab4f4e4c 706 FROM DUAL;
707 END IF;
708 END;
709 });
07cda1c5 710
ab4f4e4c 711 $dbh->do(qq{
07cda1c5 712 CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
713 BEFORE INSERT ON ${q}artist${q}
df6e3f5c 714 FOR EACH ROW
715 BEGIN
07cda1c5 716 IF :new.${q}artistid${q} IS NULL THEN
717 SELECT ${q}artist_pk_seq${q}.nextval
718 INTO :new.${q}artistid${q}
df6e3f5c 719 FROM DUAL;
720 END IF;
721 END;
722 });
07cda1c5 723
df6e3f5c 724 $dbh->do(qq{
07cda1c5 725 CREATE OR REPLACE TRIGGER ${q}cd_insert_trg${q}
df6e3f5c 726 BEFORE INSERT OR UPDATE ON cd
727 FOR EACH ROW
07cda1c5 728
6f5f880d 729 DECLARE
730 tmpVar NUMBER;
731
df6e3f5c 732 BEGIN
6f5f880d 733 tmpVar := 0;
734
07cda1c5 735 IF :new.${q}cdid${q} IS NULL THEN
736 SELECT ${q}cd_seq${q}.nextval
6f5f880d 737 INTO tmpVar
738 FROM dual;
739
07cda1c5 740 :new.${q}cdid${q} := tmpVar;
df6e3f5c 741 END IF;
742 END;
743 });
07cda1c5 744
df6e3f5c 745 $dbh->do(qq{
07cda1c5 746 CREATE OR REPLACE TRIGGER ${q}track_insert_trg${q}
747 BEFORE INSERT ON ${q}track${q}
df6e3f5c 748 FOR EACH ROW
749 BEGIN
07cda1c5 750 IF :new.${q}trackid${q} IS NULL THEN
751 SELECT ${q}track_seq${q}.nextval
752 INTO :new.${q}trackid${q}
df6e3f5c 753 FROM DUAL;
754 END IF;
755 END;
756 });
757}
758
0567538f 759# clean up our mess
07cda1c5 760sub do_clean {
761
762 my $dbh = shift || return;
763
764 for my $q ('', '"') {
765 my @clean = (
766 "DROP TRIGGER ${q}track_insert_trg${q}",
767 "DROP TRIGGER ${q}cd_insert_trg${q}",
768 "DROP TRIGGER ${q}artist_insert_trg_auto${q}",
769 "DROP TRIGGER ${q}artist_insert_trg_pk${q}",
770 "DROP SEQUENCE ${q}nonpkid_seq${q}",
771 "DROP SEQUENCE ${q}pkid2_seq${q}",
772 "DROP SEQUENCE ${q}pkid1_seq${q}",
773 "DROP SEQUENCE ${q}track_seq${q}",
774 "DROP SEQUENCE ${q}cd_seq${q}",
775 "DROP SEQUENCE ${q}artist_autoinc_seq${q}",
776 "DROP SEQUENCE ${q}artist_pk_seq${q}",
777 "DROP TABLE ${q}bindtype_test${q}",
778 "DROP TABLE ${q}sequence_test${q}",
779 "DROP TABLE ${q}track${q}",
780 "DROP TABLE ${q}cd${q}",
781 "DROP TABLE ${q}artist${q}",
782 );
783 eval { $dbh -> do ($_) } for @clean;
784 }
785}
786
3ff5b740 787END {
a6646e1b 788 for ($dbh, $dbh2) {
789 next unless $_;
07cda1c5 790 local $SIG{__WARN__} = sub {};
a6646e1b 791 do_clean($_);
792 $_->disconnect;
df6e3f5c 793 }
3ff5b740 794}