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