Switch the shortener (used only by oracle) reqs to an optional dependency
[dbsrgits/DBIx-Class.git] / t / 73oracle.t
1 {
2   package    # hide from PAUSE
3     DBICTest::Schema::ArtistFQN;
4
5   use base 'DBIx::Class::Core';
6
7   __PACKAGE__->table(
8     $ENV{DBICTEST_ORA_USER}
9       ? (uc $ENV{DBICTEST_ORA_USER}) . '.artist'
10       : '??_no_user_??'
11   );
12   __PACKAGE__->add_columns(
13     'artistid' => {
14       data_type         => 'integer',
15       is_auto_increment => 1,
16     },
17     'name' => {
18       data_type   => 'varchar',
19       size        => 100,
20       is_nullable => 1,
21     },
22     'autoinc_col' => {
23       data_type         => 'integer',
24       is_auto_increment => 1,
25     },
26   );
27   __PACKAGE__->set_primary_key(qw/ artistid autoinc_col /);
28
29   1;
30 }
31
32 use strict;
33 use warnings;
34
35 use Test::Exception;
36 use Test::More;
37 use Sub::Name;
38
39 use lib qw(t/lib);
40 use DBICTest;
41 use DBIC::SqlMakerTest;
42
43 plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_rdbms_oracle')
44   unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_rdbms_oracle');
45
46 $ENV{NLS_SORT} = "BINARY";
47 $ENV{NLS_COMP} = "BINARY";
48 $ENV{NLS_LANG} = "AMERICAN";
49
50 my ($dsn,  $user,  $pass)  = @ENV{map { "DBICTEST_ORA_${_}" }  qw/DSN USER PASS/};
51
52 # optional:
53 my ($dsn2, $user2, $pass2) = @ENV{map { "DBICTEST_ORA_EXTRAUSER_${_}" } qw/DSN USER PASS/};
54
55 plan skip_all => 'Set $ENV{DBICTEST_ORA_DSN}, _USER and _PASS to run this test.'
56   unless ($dsn && $user && $pass);
57
58 DBICTest::Schema->load_classes('ArtistFQN');
59
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');
65
66
67 ##########
68 # recyclebin sometimes comes in the way
69 my $on_connect_sql = ["ALTER SESSION SET recyclebin = OFF"];
70
71 # iterate all tests on following options
72 my @tryopt = (
73   { on_connect_do => $on_connect_sql },
74   { quote_char => '"', on_connect_do => $on_connect_sql, },
75 );
76
77 # keep a database handle open for cleanup
78 my ($dbh, $dbh2);
79
80 # test insert returning
81
82 # check if we indeed do support stuff
83 my $test_server_supports_insert_returning = do {
84   my $v = DBICTest::Schema->connect($dsn, $user, $pass)
85                    ->storage
86                     ->_get_dbh
87                      ->get_info(18);
88   $v =~ /^(\d+)\.(\d+)/
89     or die "Unparseable Oracle server version: $v\n";
90
91 # TODO find out which version supports the RETURNING syntax
92 # 8i has it and earlier docs are a 404 on oracle.com
93   ( $1 > 8 || ($1 == 8 && $2 >= 1) ) ? 1 : 0;
94 };
95 is (
96   DBICTest::Schema->connect($dsn, $user, $pass)->storage->_use_insert_returning,
97   $test_server_supports_insert_returning,
98   'insert returning capability guessed correctly'
99 );
100
101 my $schema;
102 for my $use_insert_returning ($test_server_supports_insert_returning
103   ? (1,0)
104   : (0)
105 ) {
106
107   no warnings qw/once/;
108   local *DBICTest::Schema::connection = subname 'DBICTest::Schema::connection' => sub {
109     my $s = shift->next::method (@_);
110     $s->storage->_use_insert_returning ($use_insert_returning);
111     $s;
112   };
113
114   for my $opt (@tryopt) {
115     # clean all cached sequences from previous run
116     for (map { values %{DBICTest::Schema->source($_)->columns_info} } (qw/Artist CD Track/) ) {
117       delete $_->{sequence};
118     }
119
120     my $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opt);
121
122     $dbh = $schema->storage->dbh;
123     my $q = $schema->storage->sql_maker->quote_char || '';
124
125     do_creates($dbh, $q);
126
127     _run_tests($schema, $opt);
128   }
129 }
130
131 sub _run_tests {
132   my ($schema, $opt) = @_;
133
134   my $q = $schema->storage->sql_maker->quote_char || '';
135
136 # test primary key handling with multiple triggers
137   my ($new, $seq);
138
139   my $new_artist = $schema->resultset('Artist')->create({ name => 'foo' });
140   my $new_cd     = $schema->resultset('CD')->create({ artist => 1, title => 'EP C', year => '2003' });
141
142   SKIP: {
143     skip 'not detecting sequences when using INSERT ... RETURNING', 4
144       if $schema->storage->_use_insert_returning;
145
146     is($new_artist->artistid, 1, "Oracle Auto-PK worked for standard sqlt-like trigger");
147     $seq = $new_artist->result_source->column_info('artistid')->{sequence};
148     $seq = $$seq if ref $seq;
149     like ($seq, qr/\.${q}artist_pk_seq${q}$/, 'Correct PK sequence selected for sqlt-like trigger');
150
151     is($new_cd->cdid, 1, 'Oracle Auto-PK worked - using scalar ref as table name/custom weird trigger');
152     $seq = $new_cd->result_source->column_info('cdid')->{sequence};
153     $seq = $$seq if ref $seq;
154     like ($seq, qr/\.${q}cd_seq${q}$/, 'Correct PK sequence selected for custom trigger');
155   }
156
157 # test PKs again with fully-qualified table name
158   my $artistfqn_rs = $schema->resultset('ArtistFQN');
159   my $artist_rsrc = $artistfqn_rs->result_source;
160
161   delete $artist_rsrc->column_info('artistid')->{sequence};
162   $new = $artistfqn_rs->create( { name => 'bar' } );
163
164   is_deeply( {map { $_ => $new->$_ } $artist_rsrc->primary_columns},
165     { artistid => 2, autoinc_col => 2},
166     "Oracle Multi-Auto-PK worked with fully-qualified tablename" );
167
168
169   delete $artist_rsrc->column_info('artistid')->{sequence};
170   $new = $artistfqn_rs->create( { name => 'bar', autoinc_col => 1000 } );
171
172   is( $new->artistid, 3, "Oracle Auto-PK worked with fully-qualified tablename" );
173   is( $new->autoinc_col, 1000, "Oracle Auto-Inc overruled with fully-qualified tablename");
174
175   SKIP: {
176     skip 'not detecting sequences when using INSERT ... RETURNING', 1
177       if $schema->storage->_use_insert_returning;
178
179     $seq = $new->result_source->column_info('artistid')->{sequence};
180     $seq = $$seq if ref $seq;
181     like ($seq, qr/\.${q}artist_pk_seq${q}$/, 'Correct PK sequence selected for sqlt-like trigger');
182   }
183
184
185 # test LIMIT support
186   for (1..6) {
187     $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
188   }
189   my $it = $schema->resultset('Artist')->search( { name => { -like => 'Artist %' } }, {
190     rows => 3,
191     offset => 4,
192     order_by => 'artistid'
193   });
194
195   is( $it->count, 2, "LIMIT count past end of RS ok" );
196   is( $it->next->name, "Artist 5", "iterator->next ok" );
197   is( $it->next->name, "Artist 6", "iterator->next ok" );
198   is( $it->next, undef, "next past end of resultset ok" );
199
200
201 # test identifiers over the 30 char limit
202   lives_ok {
203     my @results = $schema->resultset('CD')->search(undef, {
204       prefetch => 'very_long_artist_relationship',
205       rows => 3,
206       offset => 0,
207     })->all;
208     ok( scalar @results > 0, 'limit with long identifiers returned something');
209   } 'limit with long identifiers executed successfully';
210
211
212 # test rel names over the 30 char limit
213   my $query = $schema->resultset('Artist')->search({
214     artistid => 1
215   }, {
216     prefetch => 'cds_very_very_very_long_relationship_name'
217   });
218
219   lives_and {
220     is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
221   } 'query with rel name over 30 chars survived and worked';
222
223   # rel name over 30 char limit with user condition
224   # This requires walking the SQLA data structure.
225   {
226     local $TODO = 'user condition on rel longer than 30 chars';
227
228     $query = $schema->resultset('Artist')->search({
229       'cds_very_very_very_long_relationship_name.title' => 'EP C'
230     }, {
231       prefetch => 'cds_very_very_very_long_relationship_name'
232     });
233
234     lives_and {
235       is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
236     } 'query with rel name over 30 chars and user condition survived and worked';
237   }
238
239
240 # test join with row count ambiguity
241   my $cd = $schema->resultset('CD')->next;
242   my $track = $cd->create_related('tracks', { position => 1, title => 'Track1'} );
243   my $tjoin = $schema->resultset('Track')->search({ 'me.title' => 'Track1'}, {
244     join => 'cd', rows => 2
245   });
246
247   ok(my $row = $tjoin->next);
248
249   is($row->title, 'Track1', "ambiguous column ok");
250
251
252
253 # check count distinct with multiple columns
254   my $other_track = $schema->resultset('Track')->create({ cd => $cd->cdid, position => 1, title => 'Track2' });
255
256   my $tcount = $schema->resultset('Track')->search(
257     {},
258     {
259       select => [ qw/position title/ ],
260       distinct => 1,
261     }
262   );
263   is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
264
265   $tcount = $schema->resultset('Track')->search(
266     {},
267     {
268       columns => [ qw/position title/ ],
269       distinct => 1,
270     }
271   );
272   is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
273
274   $tcount = $schema->resultset('Track')->search(
275     {},
276     {
277       group_by => [ qw/position title/ ]
278     }
279   );
280   is($tcount->count, 2, 'multiple column COUNT DISTINCT using column syntax ok');
281
282
283 # check group_by
284   my $g_rs = $schema->resultset('Track')->search( undef, { columns=>[qw/trackid position/], group_by=> [ qw/trackid position/ ] , rows => 2, offset => 1 });
285   is( scalar $g_rs->all, 1, "Group by with limit OK" );
286
287
288 # test with_deferred_fk_checks
289   lives_ok {
290     $schema->storage->with_deferred_fk_checks(sub {
291       $schema->resultset('Track')->create({
292         trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
293       });
294       $schema->resultset('CD')->create({
295         artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
296       });
297     });
298   } 'with_deferred_fk_checks code survived';
299
300   is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
301     'code in with_deferred_fk_checks worked'; 
302
303   throws_ok {
304     $schema->resultset('Track')->create({
305       trackid => 1, cd => 9999, position => 1, title => 'Track1'
306     });
307   } qr/constraint/i, 'with_deferred_fk_checks is off';
308
309
310 # test auto increment using sequences WITHOUT triggers
311   for (1..5) {
312     my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
313     is($st->pkid1, $_, "Oracle Auto-PK without trigger: First primary key");
314     is($st->pkid2, $_ + 9, "Oracle Auto-PK without trigger: Second primary key");
315     is($st->nonpkid, $_ + 19, "Oracle Auto-PK without trigger: Non-primary key");
316   }
317   my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
318   is($st->pkid1, 55, "Oracle Auto-PK without trigger: First primary key set manually");
319
320
321 # test BLOBs
322   SKIP: {
323   TODO: {
324     my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
325     $binstr{'large'} = $binstr{'small'} x 1024;
326
327     my $maxloblen = length $binstr{'large'};
328     note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
329     local $dbh->{'LongReadLen'} = $maxloblen;
330
331     my $rs = $schema->resultset('BindType');
332     my $id = 0;
333
334     if ($DBD::Oracle::VERSION eq '1.23') {
335       throws_ok { $rs->create({ id => 1, blob => $binstr{large} }) }
336         qr/broken/,
337         'throws on blob insert with DBD::Oracle == 1.23';
338
339       skip 'buggy BLOB support in DBD::Oracle 1.23', 7;
340     }
341
342     # disable BLOB mega-output
343     my $orig_debug = $schema->storage->debug;
344     $schema->storage->debug (0);
345
346     local $TODO = 'Something is confusing column bindtype assignment when quotes are active'
347       if $q;
348
349     foreach my $type (qw( blob clob )) {
350       foreach my $size (qw( small large )) {
351         $id++;
352
353         lives_ok { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) }
354         "inserted $size $type without dying";
355         ok($rs->find($id)->$type eq $binstr{$size}, "verified inserted $size $type" );
356       }
357     }
358
359     $schema->storage->debug ($orig_debug);
360   }}
361
362
363 # test sequence detection from a different schema
364   SKIP: {
365   TODO: {
366     skip ((join '',
367       'Set DBICTEST_ORA_EXTRAUSER_DSN, _USER and _PASS to a *DIFFERENT* Oracle user',
368       ' to run the cross-schema sequence detection test.'),
369     1) unless $dsn2 && $user2 && $user2 ne $user;
370
371     skip 'not detecting cross-schema sequence name when using INSERT ... RETURNING', 1
372       if $schema->storage->_use_insert_returning;
373
374     # Oracle8i Reference Release 2 (8.1.6) 
375     #   http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76961/ch294.htm#993
376     # Oracle Database Reference 10g Release 2 (10.2)
377     #   http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#sthref1297
378     local $TODO = "On Oracle8i all_triggers view is empty, i don't yet know why..."
379       if $schema->storage->_server_info->{normalized_dbms_version} < 9;
380
381     my $schema2 = $schema->connect($dsn2, $user2, $pass2, $opt);
382     my $dbh2 = $schema2->storage->dbh;
383
384     # create identically named tables/sequences in the other schema
385     do_creates($dbh2, $q);
386
387     # grand select privileges to the 2nd user
388     $dbh->do("GRANT INSERT ON ${q}artist${q} TO " . uc $user2);
389     $dbh->do("GRANT SELECT ON ${q}artist_pk_seq${q} TO " . uc $user2);
390     $dbh->do("GRANT SELECT ON ${q}artist_autoinc_seq${q} TO " . uc $user2);
391
392     # test with a fully qualified table (user1/schema prepended)
393     my $rs2 = $schema2->resultset('ArtistFQN');
394     delete $rs2->result_source->column_info('artistid')->{sequence};
395
396     lives_and {
397       my $row = $rs2->create({ name => 'From Different Schema' });
398       ok $row->artistid;
399     } 'used autoinc sequence across schemas';
400
401     # now quote the sequence name (do_creates always uses an lc name)
402     my $q_seq = $q
403       ? '"artist_pk_seq"'
404       : '"ARTIST_PK_SEQ"'
405     ;
406     delete $rs2->result_source->column_info('artistid')->{sequence};
407     $dbh->do(qq{
408       CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
409       BEFORE INSERT ON ${q}artist${q}
410       FOR EACH ROW
411       BEGIN
412         IF :new.${q}artistid${q} IS NULL THEN
413           SELECT $q_seq.nextval
414           INTO :new.${q}artistid${q}
415           FROM DUAL;
416         END IF;
417       END;
418     });
419
420
421     lives_and {
422       my $row = $rs2->create({ name => 'From Different Schema With Quoted Sequence' });
423       ok $row->artistid;
424     } 'used quoted autoinc sequence across schemas';
425
426     is_deeply $rs2->result_source->column_info('artistid')->{sequence},
427       \( (uc $user) . ".$q_seq"),
428       'quoted sequence name correctly extracted';
429
430     # try an insert operation on the default user2 artist
431     my $art1 = $schema->resultset('Artist');
432     my $art2 = $schema2->resultset('Artist');
433     my $art1_count = $art1->count || 0;
434     my $art2_count = $art2->count;
435
436     is( $art2_count, 0, 'No artists created yet in second schema' );
437
438     delete $art2->result_source->column_info('artistid')->{sequence};
439     my $new_art = $art2->create({ name => '2nd best' });
440
441     is ($art1->count, $art1_count, 'No new rows in main schema');
442     is ($art2->count, 1, 'One artist create in 2nd schema');
443
444     is( $new_art->artistid, 1, 'Expected first PK' );
445
446     do_clean ($dbh2);
447   }}
448
449   do_clean ($dbh);
450 }
451
452 done_testing;
453
454 sub do_creates {
455   my ($dbh, $q) = @_;
456
457   do_clean($dbh);
458
459   $dbh->do("CREATE SEQUENCE ${q}artist_autoinc_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
460   $dbh->do("CREATE SEQUENCE ${q}artist_pk_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
461   $dbh->do("CREATE SEQUENCE ${q}cd_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
462   $dbh->do("CREATE SEQUENCE ${q}track_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
463
464   $dbh->do("CREATE SEQUENCE ${q}nonpkid_seq${q} START WITH 20 MAXVALUE 999999 MINVALUE 0");
465   # this one is always quoted as per manually specified sequence =>
466   $dbh->do('CREATE SEQUENCE "pkid1_seq" START WITH 1 MAXVALUE 999999 MINVALUE 0');
467   # this one is always unquoted as per manually specified sequence =>
468   $dbh->do("CREATE SEQUENCE pkid2_seq START WITH 10 MAXVALUE 999999 MINVALUE 0");
469
470   $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))");
471   $dbh->do("ALTER TABLE ${q}artist${q} ADD (CONSTRAINT ${q}artist_pk${q} PRIMARY KEY (${q}artistid${q}))");
472
473   $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))");
474   $dbh->do("ALTER TABLE ${q}sequence_test${q} ADD (CONSTRAINT ${q}sequence_test_constraint${q} PRIMARY KEY (${q}pkid1${q}, ${q}pkid2${q}))");
475
476   # table cd will be unquoted => Oracle will see it as uppercase
477   $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))");
478   $dbh->do("ALTER TABLE cd ADD (CONSTRAINT ${q}cd_pk${q} PRIMARY KEY (${q}cdid${q}))");
479
480   $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)");
481   $dbh->do("ALTER TABLE ${q}track${q} ADD (CONSTRAINT ${q}track_pk${q} PRIMARY KEY (${q}trackid${q}))");
482
483   $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)");
484
485   $dbh->do(qq{
486     CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_auto${q}
487     BEFORE INSERT ON ${q}artist${q}
488     FOR EACH ROW
489     BEGIN
490       IF :new.${q}autoinc_col${q} IS NULL THEN
491         SELECT ${q}artist_autoinc_seq${q}.nextval
492         INTO :new.${q}autoinc_col${q}
493         FROM DUAL;
494       END IF;
495     END;
496   });
497
498   $dbh->do(qq{
499     CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
500     BEFORE INSERT ON ${q}artist${q}
501     FOR EACH ROW
502     BEGIN
503       IF :new.${q}artistid${q} IS NULL THEN
504         SELECT ${q}artist_pk_seq${q}.nextval
505         INTO :new.${q}artistid${q}
506         FROM DUAL;
507       END IF;
508     END;
509   });
510
511   $dbh->do(qq{
512     CREATE OR REPLACE TRIGGER ${q}cd_insert_trg${q}
513     BEFORE INSERT OR UPDATE ON cd
514     FOR EACH ROW
515
516     DECLARE
517     tmpVar NUMBER;
518
519     BEGIN
520       tmpVar := 0;
521
522       IF :new.${q}cdid${q} IS NULL THEN
523         SELECT ${q}cd_seq${q}.nextval
524         INTO tmpVar
525         FROM dual;
526
527         :new.${q}cdid${q} := tmpVar;
528       END IF;
529     END;
530   });
531
532   $dbh->do(qq{
533     CREATE OR REPLACE TRIGGER ${q}track_insert_trg${q}
534     BEFORE INSERT ON ${q}track${q}
535     FOR EACH ROW
536     BEGIN
537       IF :new.${q}trackid${q} IS NULL THEN
538         SELECT ${q}track_seq${q}.nextval
539         INTO :new.${q}trackid${q}
540         FROM DUAL;
541       END IF;
542     END;
543   });
544 }
545
546 # clean up our mess
547 sub do_clean {
548
549   my $dbh = shift || return;
550
551   for my $q ('', '"') {
552     my @clean = (
553       "DROP TRIGGER ${q}track_insert_trg${q}",
554       "DROP TRIGGER ${q}cd_insert_trg${q}",
555       "DROP TRIGGER ${q}artist_insert_trg_auto${q}",
556       "DROP TRIGGER ${q}artist_insert_trg_pk${q}",
557       "DROP SEQUENCE ${q}nonpkid_seq${q}",
558       "DROP SEQUENCE ${q}pkid2_seq${q}",
559       "DROP SEQUENCE ${q}pkid1_seq${q}",
560       "DROP SEQUENCE ${q}track_seq${q}",
561       "DROP SEQUENCE ${q}cd_seq${q}",
562       "DROP SEQUENCE ${q}artist_autoinc_seq${q}",
563       "DROP SEQUENCE ${q}artist_pk_seq${q}",
564       "DROP TABLE ${q}bindtype_test${q}",
565       "DROP TABLE ${q}sequence_test${q}",
566       "DROP TABLE ${q}track${q}",
567       "DROP TABLE ${q}cd${q}",
568       "DROP TABLE ${q}artist${q}",
569     );
570     eval { $dbh -> do ($_) } for @clean;
571   }
572 }
573
574 END {
575   for ($dbh, $dbh2) {
576     next unless $_;
577     local $SIG{__WARN__} = sub {};
578     do_clean($_);
579     $_->disconnect;
580   }
581 }