10 use DBIC::SqlMakerTest;
12 plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_rdbms_oracle')
13 unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_rdbms_oracle');
15 $ENV{NLS_SORT} = "BINARY";
16 $ENV{NLS_COMP} = "BINARY";
17 $ENV{NLS_LANG} = "AMERICAN";
19 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_ORA_${_}" } qw/DSN USER PASS/};
22 my ($dsn2, $user2, $pass2) = @ENV{map { "DBICTEST_ORA_EXTRAUSER_${_}" } qw/DSN USER PASS/};
24 plan skip_all => 'Set $ENV{DBICTEST_ORA_DSN}, _USER and _PASS to run this test.'
25 unless ($dsn && $user && $pass);
28 package # hide from PAUSE
29 DBICTest::Schema::ArtistFQN;
31 use base 'DBIx::Class::Core';
34 $ENV{DBICTEST_ORA_USER}
35 ? (uc $ENV{DBICTEST_ORA_USER}) . '.artist'
38 __PACKAGE__->add_columns(
40 data_type => 'integer',
41 is_auto_increment => 1,
44 data_type => 'varchar',
49 data_type => 'integer',
50 is_auto_increment => 1,
53 __PACKAGE__->set_primary_key(qw/ artistid autoinc_col /);
58 DBICTest::Schema->load_classes('ArtistFQN');
60 # This is in Core now, but it's here just to test that it doesn't break
61 DBICTest::Schema::Artist->load_components('PK::Auto');
62 # These are compat shims for PK::Auto...
63 DBICTest::Schema::CD->load_components('PK::Auto::Oracle');
64 DBICTest::Schema::Track->load_components('PK::Auto::Oracle');
67 # check if we indeed do support stuff
69 my $v = DBICTest::Schema->connect($dsn, $user, $pass)->storage->_dbh_get_info(18);
71 or die "Unparseable Oracle server version: $v\n";
73 sprintf('%d.%03d', $1, $2);
76 # while 8i (8.1) does not document support for ansi joins, and the the drivers do not use
77 # them because performance sucks, there is strong evidence they are in fact supported
78 # means we can test 'em :)
79 my $test_server_supports_only_orajoins = $v < 8.001;
81 # TODO find out which version supports the RETURNING syntax
82 # 8i (8.1) has it and earlier docs are a 404 on oracle.com
83 my $test_server_supports_insert_returning = $v >= 8.001;
86 DBICTest::Schema->connect($dsn, $user, $pass)->storage->_use_insert_returning,
87 $test_server_supports_insert_returning,
88 'insert returning capability guessed correctly'
92 # recyclebin sometimes comes in the way
93 my $on_connect_sql = ["ALTER SESSION SET recyclebin = OFF"];
95 # iterate all tests on following options
97 { on_connect_do => $on_connect_sql },
98 { quote_char => '"', on_connect_do => $on_connect_sql },
101 # keep a database handle open for cleanup
105 for my $use_insert_returning ($test_server_supports_insert_returning ? (1,0) : (0) ) {
106 for my $force_ora_joins ($test_server_supports_only_orajoins ? (0) : (0,1) ) {
108 no warnings qw/once/;
109 local *DBICTest::Schema::connection = subname 'DBICTest::Schema::connection' => sub {
110 my $s = shift->next::method (@_);
111 $s->storage->_use_insert_returning ($use_insert_returning);
112 $s->storage->sql_maker_class('DBIx::Class::SQLMaker::OracleJoins') if $force_ora_joins;
116 for my $opt (@tryopt) {
117 # clean all cached sequences from previous run
118 for (map { values %{DBICTest::Schema->source($_)->columns_info} } (qw/Artist CD Track/) ) {
119 delete $_->{sequence};
122 my $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opt);
124 $dbh = $schema->storage->dbh;
125 my $q = $schema->storage->sql_maker->quote_char || '';
127 do_creates($dbh, $q);
129 _run_tests($schema, $opt);
135 my ($schema, $opt) = @_;
137 my $q = $schema->storage->sql_maker->quote_char || '';
139 # test primary key handling with multiple triggers
142 my $new_artist = $schema->resultset('Artist')->create({ name => 'foo' });
143 my $new_cd = $schema->resultset('CD')->create({ artist => 1, title => 'EP C', year => '2003' });
146 skip 'not detecting sequences when using INSERT ... RETURNING', 4
147 if $schema->storage->_use_insert_returning;
149 is($new_artist->artistid, 1, "Oracle Auto-PK worked for standard sqlt-like trigger");
150 $seq = $new_artist->result_source->column_info('artistid')->{sequence};
151 $seq = $$seq if ref $seq;
152 like ($seq, qr/\.${q}artist_pk_seq${q}$/, 'Correct PK sequence selected for sqlt-like trigger');
154 is($new_cd->cdid, 1, 'Oracle Auto-PK worked - using scalar ref as table name/custom weird trigger');
155 $seq = $new_cd->result_source->column_info('cdid')->{sequence};
156 $seq = $$seq if ref $seq;
157 like ($seq, qr/\.${q}cd_seq${q}$/, 'Correct PK sequence selected for custom trigger');
160 # test PKs again with fully-qualified table name
161 my $artistfqn_rs = $schema->resultset('ArtistFQN');
162 my $artist_rsrc = $artistfqn_rs->result_source;
164 delete $artist_rsrc->column_info('artistid')->{sequence};
165 $new = $artistfqn_rs->create( { name => 'bar' } );
167 is_deeply( {map { $_ => $new->$_ } $artist_rsrc->primary_columns},
168 { artistid => 2, autoinc_col => 2},
169 "Oracle Multi-Auto-PK worked with fully-qualified tablename" );
172 delete $artist_rsrc->column_info('artistid')->{sequence};
173 $new = $artistfqn_rs->create( { name => 'bar', autoinc_col => 1000 } );
175 is( $new->artistid, 3, "Oracle Auto-PK worked with fully-qualified tablename" );
176 is( $new->autoinc_col, 1000, "Oracle Auto-Inc overruled with fully-qualified tablename");
179 skip 'not detecting sequences when using INSERT ... RETURNING', 1
180 if $schema->storage->_use_insert_returning;
182 $seq = $new->result_source->column_info('artistid')->{sequence};
183 $seq = $$seq if ref $seq;
184 like ($seq, qr/\.${q}artist_pk_seq${q}$/, 'Correct PK sequence selected for sqlt-like trigger');
190 $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
192 my $it = $schema->resultset('Artist')->search( { name => { -like => 'Artist %' } }, {
195 order_by => 'artistid'
198 is( $it->count, 2, "LIMIT count past end of RS ok" );
199 is( $it->next->name, "Artist 5", "iterator->next ok" );
200 is( $it->next->name, "Artist 6", "iterator->next ok" );
201 is( $it->next, undef, "next past end of resultset ok" );
203 # test identifiers over the 30 char limit
205 my @results = $schema->resultset('CD')->search(undef, {
206 prefetch => 'very_long_artist_relationship',
210 ok( scalar @results > 0, 'limit with long identifiers returned something');
211 } 'limit with long identifiers executed successfully';
214 # test rel names over the 30 char limit
215 my $query = $schema->resultset('Artist')->search({
218 prefetch => 'cds_very_very_very_long_relationship_name'
222 is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
223 } 'query with rel name over 30 chars survived and worked';
225 # test rel names over the 30 char limit using group_by and join
227 my @group_cols = ( 'me.name' );
228 my $query = $schema->resultset('Artist')->search({
231 select => \@group_cols,
232 as => [map { /^\w+\.(\w+)$/ } @group_cols],
233 join => [qw( cds_very_very_very_long_relationship_name )],
234 group_by => \@group_cols,
238 my @got = $query->get_column('name')->all();
239 is_deeply \@got, [$new_artist->name];
240 } 'query with rel name over 30 chars worked on join, group_by for me col';
243 is $query->count(), 1
244 } 'query with rel name over 30 chars worked on join, group_by, count for me col';
247 my @group_cols = ( 'cds_very_very_very_long_relationship_name.title' );
248 my $query = $schema->resultset('Artist')->search({
251 select => \@group_cols,
252 as => [map { /^\w+\.(\w+)$/ } @group_cols],
253 join => [qw( cds_very_very_very_long_relationship_name )],
254 group_by => \@group_cols,
258 my @got = $query->get_column('title')->all();
259 is_deeply \@got, [$new_cd->title];
260 } 'query with rel name over 30 chars worked on join, group_by for long rel col';
263 is $query->count(), 1
264 } 'query with rel name over 30 chars worked on join, group_by, count for long rel col';
267 # rel name over 30 char limit with user condition
268 # This requires walking the SQLA data structure.
270 $query = $schema->resultset('Artist')->search({
271 'cds_very_very_very_long_relationship_name.title' => 'EP C'
273 prefetch => 'cds_very_very_very_long_relationship_name'
277 is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
278 } 'query with rel name over 30 chars and user condition survived and worked';
282 # test join with row count ambiguity
283 my $cd = $schema->resultset('CD')->next;
284 my $track = $cd->create_related('tracks', { position => 1, title => 'Track1'} );
285 my $tjoin = $schema->resultset('Track')->search({ 'me.title' => 'Track1'}, {
286 join => 'cd', rows => 2
289 ok(my $row = $tjoin->next);
291 is($row->title, 'Track1', "ambiguous column ok");
295 # check count distinct with multiple columns
296 my $other_track = $schema->resultset('Track')->create({ cd => $cd->cdid, position => 1, title => 'Track2' });
298 my $tcount = $schema->resultset('Track')->search(
301 select => [ qw/position title/ ],
305 is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
307 $tcount = $schema->resultset('Track')->search(
310 columns => [ qw/position title/ ],
314 is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
316 $tcount = $schema->resultset('Track')->search(
319 group_by => [ qw/position title/ ]
322 is($tcount->count, 2, 'multiple column COUNT DISTINCT using column syntax ok');
326 my $g_rs = $schema->resultset('Track')->search( undef, { columns=>[qw/trackid position/], group_by=> [ qw/trackid position/ ] , rows => 2, offset => 1 });
327 is( scalar $g_rs->all, 1, "Group by with limit OK" );
330 # test with_deferred_fk_checks
332 $schema->storage->with_deferred_fk_checks(sub {
333 $schema->resultset('Track')->create({
334 trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
336 $schema->resultset('CD')->create({
337 artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
340 } 'with_deferred_fk_checks code survived';
342 is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
343 'code in with_deferred_fk_checks worked';
346 $schema->resultset('Track')->create({
347 trackid => 1, cd => 9999, position => 1, title => 'Track1'
349 } qr/constraint/i, 'with_deferred_fk_checks is off';
352 # test auto increment using sequences WITHOUT triggers
354 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
355 is($st->pkid1, $_, "Oracle Auto-PK without trigger: First primary key");
356 is($st->pkid2, $_ + 9, "Oracle Auto-PK without trigger: Second primary key");
357 is($st->nonpkid, $_ + 19, "Oracle Auto-PK without trigger: Non-primary key");
359 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
360 is($st->pkid1, 55, "Oracle Auto-PK without trigger: First primary key set manually");
366 my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
367 $binstr{'large'} = $binstr{'small'} x 1024;
369 my $maxloblen = length $binstr{'large'};
370 note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
371 local $dbh->{'LongReadLen'} = $maxloblen;
373 my $rs = $schema->resultset('BindType');
376 if ($DBD::Oracle::VERSION eq '1.23') {
377 throws_ok { $rs->create({ id => 1, blob => $binstr{large} }) }
379 'throws on blob insert with DBD::Oracle == 1.23';
381 skip 'buggy BLOB support in DBD::Oracle 1.23', 7;
384 # disable BLOB mega-output
385 my $orig_debug = $schema->storage->debug;
386 $schema->storage->debug (0);
388 local $TODO = 'Something is confusing column bindtype assignment when quotes are active'
389 . ': https://rt.cpan.org/Ticket/Display.html?id=64206'
392 foreach my $type (qw( blob clob )) {
393 foreach my $size (qw( small large )) {
396 lives_ok { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) }
397 "inserted $size $type without dying";
398 ok($rs->find($id)->$type eq $binstr{$size}, "verified inserted $size $type" );
402 $schema->storage->debug ($orig_debug);
405 # test populate (identity, success and error handling)
406 my $art_rs = $schema->resultset('Artist');
408 my $seq_pos = $art_rs->get_column('artistid')->max;
409 ok($seq_pos, 'Starting with something in the artist table');
412 my $pop_rs = $schema->resultset('Artist')->search(
413 { name => { -like => 'pop_art_%' } },
414 { order_by => 'artistid' }
420 map { +{ name => "pop_art_$_" } }
425 [ $pop_rs->get_column('artistid')->all ],
426 [ map { $seq_pos + $_ } (1,2,3) ],
427 'Sequence works after empty-table insertion'
429 } 'Populate without identity does not throw';
433 map { +{ artistid => $_, name => "pop_art_$_" } }
438 [ $pop_rs->get_column('artistid')->all ],
439 [ 1,2,3, map { $seq_pos + $_ } (1,2,3) ],
440 'Explicit id population works'
442 } 'Populate with identity does not throw';
446 map { +{ artistid => $_, name => "pop_art_$_" } }
449 } qr/unique constraint.+populate slice.+name => "pop_art_1"/s, 'Partially failed populate throws';
452 [ $pop_rs->get_column('artistid')->all ],
453 [ 1,2,3, map { $seq_pos + $_ } (1,2,3) ],
454 'Partially failed populate did not alter table contents'
457 # test complex join (exercise orajoins)
459 my @hri = $schema->resultset('CD')->search(
460 { 'artist.name' => 'pop_art_1', 'me.cdid' => { '!=', 999} },
461 { join => 'artist', prefetch => 'tracks', rows => 4, order_by => 'tracks.trackid' }
468 single_track => undef,
473 last_updated_at => undef,
474 last_updated_on => undef,
481 last_updated_at => undef,
482 last_updated_on => undef,
494 'Correct set of data prefetched',
497 } 'complex prefetch ok';
499 # test sequence detection from a different schema
503 'Set DBICTEST_ORA_EXTRAUSER_DSN, _USER and _PASS to a *DIFFERENT* Oracle user',
504 ' to run the cross-schema sequence detection test.'),
505 1) unless $dsn2 && $user2 && $user2 ne $user;
507 skip 'not detecting cross-schema sequence name when using INSERT ... RETURNING', 1
508 if $schema->storage->_use_insert_returning;
510 # Oracle8i Reference Release 2 (8.1.6)
511 # http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76961/ch294.htm#993
512 # Oracle Database Reference 10g Release 2 (10.2)
513 # http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#sthref1297
514 local $TODO = "On Oracle8i all_triggers view is empty, i don't yet know why..."
515 if $schema->storage->_server_info->{normalized_dbms_version} < 9;
517 my $schema2 = $schema->connect($dsn2, $user2, $pass2, $opt);
518 my $dbh2 = $schema2->storage->dbh;
520 # create identically named tables/sequences in the other schema
521 do_creates($dbh2, $q);
523 # grand select privileges to the 2nd user
524 $dbh->do("GRANT INSERT ON ${q}artist${q} TO " . uc $user2);
525 $dbh->do("GRANT SELECT ON ${q}artist_pk_seq${q} TO " . uc $user2);
526 $dbh->do("GRANT SELECT ON ${q}artist_autoinc_seq${q} TO " . uc $user2);
528 # test with a fully qualified table (user1/schema prepended)
529 my $rs2 = $schema2->resultset('ArtistFQN');
530 delete $rs2->result_source->column_info('artistid')->{sequence};
533 my $row = $rs2->create({ name => 'From Different Schema' });
535 } 'used autoinc sequence across schemas';
537 # now quote the sequence name (do_creates always uses an lc name)
542 delete $rs2->result_source->column_info('artistid')->{sequence};
544 CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
545 BEFORE INSERT ON ${q}artist${q}
548 IF :new.${q}artistid${q} IS NULL THEN
549 SELECT $q_seq.nextval
550 INTO :new.${q}artistid${q}
558 my $row = $rs2->create({ name => 'From Different Schema With Quoted Sequence' });
560 } 'used quoted autoinc sequence across schemas';
562 is_deeply $rs2->result_source->column_info('artistid')->{sequence},
563 \( (uc $user) . ".$q_seq"),
564 'quoted sequence name correctly extracted';
566 # try an insert operation on the default user2 artist
567 my $art1 = $schema->resultset('Artist');
568 my $art2 = $schema2->resultset('Artist');
569 my $art1_count = $art1->count || 0;
570 my $art2_count = $art2->count;
572 is( $art2_count, 0, 'No artists created yet in second schema' );
574 delete $art2->result_source->column_info('artistid')->{sequence};
575 my $new_art = $art2->create({ name => '2nd best' });
577 is ($art1->count, $art1_count, 'No new rows in main schema');
578 is ($art2->count, 1, 'One artist create in 2nd schema');
580 is( $new_art->artistid, 1, 'Expected first PK' );
595 $dbh->do("CREATE SEQUENCE ${q}artist_autoinc_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
596 $dbh->do("CREATE SEQUENCE ${q}artist_pk_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
597 $dbh->do("CREATE SEQUENCE ${q}cd_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
598 $dbh->do("CREATE SEQUENCE ${q}track_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
600 $dbh->do("CREATE SEQUENCE ${q}nonpkid_seq${q} START WITH 20 MAXVALUE 999999 MINVALUE 0");
601 # this one is always quoted as per manually specified sequence =>
602 $dbh->do('CREATE SEQUENCE "pkid1_seq" START WITH 1 MAXVALUE 999999 MINVALUE 0');
603 # this one is always unquoted as per manually specified sequence =>
604 $dbh->do("CREATE SEQUENCE pkid2_seq START WITH 10 MAXVALUE 999999 MINVALUE 0");
606 $dbh->do("CREATE TABLE ${q}artist${q} (${q}artistid${q} NUMBER(12), ${q}name${q} VARCHAR(255), ${q}autoinc_col${q} NUMBER(12), ${q}rank${q} NUMBER(38), ${q}charfield${q} VARCHAR2(10))");
607 $dbh->do("ALTER TABLE ${q}artist${q} ADD (CONSTRAINT ${q}artist_pk${q} PRIMARY KEY (${q}artistid${q}))");
609 $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))");
610 $dbh->do("ALTER TABLE ${q}sequence_test${q} ADD (CONSTRAINT ${q}sequence_test_constraint${q} PRIMARY KEY (${q}pkid1${q}, ${q}pkid2${q}))");
612 # table cd will be unquoted => Oracle will see it as uppercase
613 $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))");
614 $dbh->do("ALTER TABLE cd ADD (CONSTRAINT ${q}cd_pk${q} PRIMARY KEY (${q}cdid${q}))");
616 $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)");
617 $dbh->do("ALTER TABLE ${q}track${q} ADD (CONSTRAINT ${q}track_pk${q} PRIMARY KEY (${q}trackid${q}))");
619 $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)");
622 CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_auto${q}
623 BEFORE INSERT ON ${q}artist${q}
626 IF :new.${q}autoinc_col${q} IS NULL THEN
627 SELECT ${q}artist_autoinc_seq${q}.nextval
628 INTO :new.${q}autoinc_col${q}
635 CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
636 BEFORE INSERT ON ${q}artist${q}
639 IF :new.${q}artistid${q} IS NULL THEN
640 SELECT ${q}artist_pk_seq${q}.nextval
641 INTO :new.${q}artistid${q}
648 CREATE OR REPLACE TRIGGER ${q}cd_insert_trg${q}
649 BEFORE INSERT OR UPDATE ON cd
658 IF :new.${q}cdid${q} IS NULL THEN
659 SELECT ${q}cd_seq${q}.nextval
663 :new.${q}cdid${q} := tmpVar;
669 CREATE OR REPLACE TRIGGER ${q}track_insert_trg${q}
670 BEFORE INSERT ON ${q}track${q}
673 IF :new.${q}trackid${q} IS NULL THEN
674 SELECT ${q}track_seq${q}.nextval
675 INTO :new.${q}trackid${q}
685 my $dbh = shift || return;
687 for my $q ('', '"') {
689 "DROP TRIGGER ${q}track_insert_trg${q}",
690 "DROP TRIGGER ${q}cd_insert_trg${q}",
691 "DROP TRIGGER ${q}artist_insert_trg_auto${q}",
692 "DROP TRIGGER ${q}artist_insert_trg_pk${q}",
693 "DROP SEQUENCE ${q}nonpkid_seq${q}",
694 "DROP SEQUENCE ${q}pkid2_seq${q}",
695 "DROP SEQUENCE ${q}pkid1_seq${q}",
696 "DROP SEQUENCE ${q}track_seq${q}",
697 "DROP SEQUENCE ${q}cd_seq${q}",
698 "DROP SEQUENCE ${q}artist_autoinc_seq${q}",
699 "DROP SEQUENCE ${q}artist_pk_seq${q}",
700 "DROP TABLE ${q}bindtype_test${q}",
701 "DROP TABLE ${q}sequence_test${q}",
702 "DROP TABLE ${q}track${q}",
703 "DROP TABLE ${q}cd${q}",
704 "DROP TABLE ${q}artist${q}",
706 eval { $dbh -> do ($_) } for @clean;
713 local $SIG{__WARN__} = sub {};