Major overhaul of select/as resolution handling (fixes RT#61235)
[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       ? $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('artistid');
28
29   1;
30 }
31
32 use strict;
33 use warnings;
34
35 use Test::Exception;
36 use Test::More;
37
38 use lib qw(t/lib);
39 use DBICTest;
40 use DBIC::SqlMakerTest;
41
42 my ($dsn,  $user,  $pass)  = @ENV{map { "DBICTEST_ORA_${_}" }  qw/DSN USER PASS/};
43
44 # optional:
45 my ($dsn2, $user2, $pass2) = @ENV{map { "DBICTEST_ORA_EXTRAUSER_${_}" } qw/DSN USER PASS/};
46
47 plan skip_all => 'Set $ENV{DBICTEST_ORA_DSN}, _USER and _PASS to run this test. ' .
48   'Warning: This test drops and creates tables called \'artist\', \'cd\', \'track\' and \'sequence_test\''.
49   ' as well as following sequences: \'pkid1_seq\', \'pkid2_seq\' and \'nonpkid_seq\''
50   unless ($dsn && $user && $pass);
51
52 DBICTest::Schema->load_classes('ArtistFQN');
53 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
54
55 note "Oracle Version: " . $schema->storage->_server_info->{dbms_version};
56
57 my $dbh = $schema->storage->dbh;
58
59 do_creates($dbh);
60
61 {
62     # Swiped from t/bindtype_columns.t to avoid creating my own Resultset.
63
64     local $SIG{__WARN__} = sub {};
65     eval { $dbh->do('DROP TABLE bindtype_test') };
66
67     $dbh->do(qq[
68         CREATE TABLE bindtype_test
69         (
70             id              integer      NOT NULL   PRIMARY KEY,
71             bytea           integer      NULL,
72             blob            blob         NULL,
73             clob            clob         NULL
74         )
75     ],{ RaiseError => 1, PrintError => 1 });
76 }
77
78 # This is in Core now, but it's here just to test that it doesn't break
79 $schema->class('Artist')->load_components('PK::Auto');
80 # These are compat shims for PK::Auto...
81 $schema->class('CD')->load_components('PK::Auto::Oracle');
82 $schema->class('Track')->load_components('PK::Auto::Oracle');
83
84
85 # test primary key handling with multiple triggers
86 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
87 is($new->artistid, 1, "Oracle Auto-PK worked for sqlt-like trigger");
88
89 like ($new->result_source->column_info('artistid')->{sequence}, qr/\.artist_pk_seq$/, 'Correct PK sequence selected for sqlt-like trigger');
90
91 $new = $schema->resultset('CD')->create({ artist => 1, title => 'foo', year => '2003' });
92 is($new->cdid, 1, "Oracle Auto-PK worked for custom trigger");
93
94 like ($new->result_source->column_info('cdid')->{sequence}, qr/\.cd_seq$/, 'Correct PK sequence selected for custom trigger');
95
96 # test again with fully-qualified table name
97 my $artistfqn_rs = $schema->resultset('ArtistFQN');
98 my $artist_rsrc = $artistfqn_rs->result_source;
99
100 delete $artist_rsrc->column_info('artistid')->{sequence};
101
102 $new = $artistfqn_rs->create( { name => 'bar' } );
103 is( $new->artistid, 2, "Oracle Auto-PK worked with fully-qualified tablename" );
104
105 delete $artist_rsrc->column_info('artistid')->{sequence};
106
107 $new = $artistfqn_rs->create( { name => 'bar', autoinc_col => 1000 } );
108 is( $new->artistid, 3, "Oracle Auto-PK worked with fully-qualified tablename" );
109 is( $new->autoinc_col, 1000, "Oracle Auto-Inc overruled with fully-qualified tablename");
110
111 like ($artist_rsrc->column_info('artistid')->{sequence}, qr/\.artist_pk_seq$/, 'Still correct PK sequence');
112
113 # test LIMIT support
114 for (1..6) {
115     $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
116 }
117 my $it = $schema->resultset('Artist')->search( { name => { -like => 'Artist %' }},
118     { rows => 3,
119       offset => 4,
120       order_by => 'artistid' }
121 );
122 is( $it->count, 2, "LIMIT count past end of RS ok" );
123 is( $it->next->name, "Artist 5", "iterator->next ok" );
124 is( $it->next->name, "Artist 6", "iterator->next ok" );
125 is( $it->next, undef, "next past end of resultset ok" );
126
127 my $cd = $schema->resultset('CD')->create({ artist => 1, title => 'EP C', year => '2003' });
128 is($cd->cdid, 2, "Oracle Auto-PK worked - using scalar ref as table name");
129
130 # test rel names over the 30 char limit
131 {
132   my $query = $schema->resultset('Artist')->search({
133     artistid => 1
134   }, {
135     prefetch => 'cds_very_very_very_long_relationship_name'
136   });
137
138   lives_and {
139     is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 2
140   } 'query with rel name over 30 chars survived and worked';
141
142   # rel name over 30 char limit with user condition
143   # This requires walking the SQLA data structure.
144   {
145     local $TODO = 'user condition on rel longer than 30 chars';
146
147     $query = $schema->resultset('Artist')->search({
148       'cds_very_very_very_long_relationship_name.title' => 'EP C'
149     }, {
150       prefetch => 'cds_very_very_very_long_relationship_name'
151     });
152
153     lives_and {
154       is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
155     } 'query with rel name over 30 chars and user condition survived and worked';
156   }
157 }
158
159 # test join with row count ambiguity
160
161 my $track = $schema->resultset('Track')->create({ cd => $cd->cdid,
162     position => 1, title => 'Track1' });
163 my $tjoin = $schema->resultset('Track')->search({ 'me.title' => 'Track1'},
164         { join => 'cd',
165           rows => 2 }
166 );
167
168 ok(my $row = $tjoin->next);
169
170 is($row->title, 'Track1', "ambiguous column ok");
171
172 # check count distinct with multiple columns
173 my $other_track = $schema->resultset('Track')->create({ cd => $cd->cdid, position => 1, title => 'Track2' });
174
175 my $tcount = $schema->resultset('Track')->search(
176   {},
177   {
178     select => [ qw/position title/ ],
179     distinct => 1,
180   }
181 );
182 is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
183
184 $tcount = $schema->resultset('Track')->search(
185   {},
186   {
187     columns => [ qw/position title/ ],
188     distinct => 1,
189   }
190 );
191 is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
192
193 $tcount = $schema->resultset('Track')->search(
194   {},
195   {
196      group_by => [ qw/position title/ ]
197   }
198 );
199 is($tcount->count, 2, 'multiple column COUNT DISTINCT using column syntax ok');
200
201 {
202   my $rs = $schema->resultset('Track')->search( undef, { columns=>[qw/trackid position/], group_by=> [ qw/trackid position/ ] , rows => 2, offset=>1 });
203   my @results = $rs->all;
204   is( scalar @results, 1, "Group by with limit OK" );
205 }
206
207 # test identifiers over the 30 char limit
208 {
209   lives_ok {
210     my @results = $schema->resultset('CD')->search(undef, {
211       prefetch => 'very_long_artist_relationship',
212       rows => 3,
213       offset => 0,
214     })->all;
215     ok( scalar @results > 0, 'limit with long identifiers returned something');
216   } 'limit with long identifiers executed successfully';
217 }
218
219 # test with_deferred_fk_checks
220 lives_ok {
221   $schema->storage->with_deferred_fk_checks(sub {
222     $schema->resultset('Track')->create({
223       trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
224     });
225     $schema->resultset('CD')->create({
226       artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
227     });
228   });
229 } 'with_deferred_fk_checks code survived';
230
231 is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
232    'code in with_deferred_fk_checks worked'; 
233
234 throws_ok {
235   $schema->resultset('Track')->create({
236     trackid => 1, cd => 9999, position => 1, title => 'Track1'
237   });
238 } qr/constraint/i, 'with_deferred_fk_checks is off';
239
240 # test auto increment using sequences WITHOUT triggers
241 for (1..5) {
242     my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
243     is($st->pkid1, $_, "Oracle Auto-PK without trigger: First primary key");
244     is($st->pkid2, $_ + 9, "Oracle Auto-PK without trigger: Second primary key");
245     is($st->nonpkid, $_ + 19, "Oracle Auto-PK without trigger: Non-primary key");
246 }
247 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
248 is($st->pkid1, 55, "Oracle Auto-PK without trigger: First primary key set manually");
249
250 SKIP: {
251   my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
252   $binstr{'large'} = $binstr{'small'} x 1024;
253
254   my $maxloblen = length $binstr{'large'};
255   note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
256   local $dbh->{'LongReadLen'} = $maxloblen;
257
258   my $rs = $schema->resultset('BindType');
259   my $id = 0;
260
261   if ($DBD::Oracle::VERSION eq '1.23') {
262     throws_ok { $rs->create({ id => 1, blob => $binstr{large} }) }
263       qr/broken/,
264       'throws on blob insert with DBD::Oracle == 1.23';
265
266     skip 'buggy BLOB support in DBD::Oracle 1.23', 7;
267   }
268
269   # disable BLOB mega-output
270   my $orig_debug = $schema->storage->debug;
271   $schema->storage->debug (0);
272
273   foreach my $type (qw( blob clob )) {
274     foreach my $size (qw( small large )) {
275       $id++;
276
277       lives_ok { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) }
278       "inserted $size $type without dying";
279
280       ok($rs->find($id)->$type eq $binstr{$size}, "verified inserted $size $type" );
281     }
282   }
283
284   $schema->storage->debug ($orig_debug);
285 }
286
287
288 ### test hierarchical queries
289 if ( $schema->storage->isa('DBIx::Class::Storage::DBI::Oracle::Generic') ) {
290     my $source = $schema->source('Artist');
291
292     $source->add_column( 'parentid' );
293
294     $source->add_relationship('children', 'DBICTest::Schema::Artist',
295         { 'foreign.parentid' => 'self.artistid' },
296         {
297             accessor => 'multi',
298             join_type => 'LEFT',
299             cascade_delete => 1,
300             cascade_copy => 1,
301         } );
302     $source->add_relationship('parent', 'DBICTest::Schema::Artist',
303         { 'foreign.artistid' => 'self.parentid' },
304         { accessor => 'single' } );
305     DBICTest::Schema::Artist->add_column( 'parentid' );
306     DBICTest::Schema::Artist->has_many(
307         children => 'DBICTest::Schema::Artist',
308         { 'foreign.parentid' => 'self.artistid' }
309     );
310     DBICTest::Schema::Artist->belongs_to(
311         parent => 'DBICTest::Schema::Artist',
312         { 'foreign.artistid' => 'self.parentid' }
313     );
314
315     $schema->resultset('Artist')->create ({
316         name => 'root',
317         rank => 1,
318         cds => [],
319         children => [
320             {
321                 name => 'child1',
322                 rank => 2,
323                 children => [
324                     {
325                         name => 'grandchild',
326                         rank => 3,
327                         cds => [
328                             {
329                                 title => "grandchilds's cd" ,
330                                 year => '2008',
331                                 tracks => [
332                                     {
333                                         position => 1,
334                                         title => 'Track 1 grandchild',
335                                     }
336                                 ],
337                             }
338                         ],
339                         children => [
340                             {
341                                 name => 'greatgrandchild',
342                                 rank => 3,
343                             }
344                         ],
345                     }
346                 ],
347             },
348             {
349                 name => 'child2',
350                 rank => 3,
351             },
352         ],
353     });
354
355     $schema->resultset('Artist')->create(
356         {
357             name     => 'cycle-root',
358             children => [
359                 {
360                     name     => 'cycle-child1',
361                     children => [ { name => 'cycle-grandchild' } ],
362                 },
363                 { name => 'cycle-child2' },
364             ],
365         }
366     );
367
368     $schema->resultset('Artist')->find({ name => 'cycle-root' })
369       ->update({ parentid => { -ident => 'artistid' } });
370
371     # select the whole tree
372     {
373       my $rs = $schema->resultset('Artist')->search({}, {
374         start_with => { name => 'root' },
375         connect_by => { parentid => { -prior => { -ident => 'artistid' } } },
376       });
377
378       is_same_sql_bind (
379         $rs->as_query,
380         '(
381           SELECT me.artistid, me.name, me.rank, me.charfield, me.parentid
382             FROM artist me
383           START WITH name = ?
384           CONNECT BY parentid = PRIOR artistid 
385         )',
386         [ [ name => 'root'] ],
387       );
388       is_deeply (
389         [ $rs->get_column ('name')->all ],
390         [ qw/root child1 grandchild greatgrandchild child2/ ],
391         'got artist tree',
392       );
393
394
395       is_same_sql_bind (
396         $rs->count_rs->as_query,
397         '(
398           SELECT COUNT( * )
399             FROM artist me
400           START WITH name = ?
401           CONNECT BY parentid = PRIOR artistid 
402         )',
403         [ [ name => 'root'] ],
404       );
405
406       is( $rs->count, 5, 'Connect By count ok' );
407     }
408
409     # use order siblings by statement
410     SKIP: {
411       # http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a85397/state21b.htm#2066123
412       skip q{Oracle8i doesn't support ORDER SIBLINGS BY}, 1
413         if $schema->storage->_server_info->{normalized_dbms_version} < 9;
414
415       my $rs = $schema->resultset('Artist')->search({}, {
416         start_with => { name => 'root' },
417         connect_by => { parentid => { -prior => { -ident =>  'artistid' } } },
418         order_siblings_by => { -desc => 'name' },
419       });
420
421       is_same_sql_bind (
422         $rs->as_query,
423         '(
424           SELECT me.artistid, me.name, me.rank, me.charfield, me.parentid
425             FROM artist me
426           START WITH name = ?
427           CONNECT BY parentid = PRIOR artistid 
428           ORDER SIBLINGS BY name DESC
429         )',
430         [ [ name => 'root'] ],
431       );
432
433       is_deeply (
434         [ $rs->get_column ('name')->all ],
435         [ qw/root child2 child1 grandchild greatgrandchild/ ],
436         'Order Siblings By ok',
437       );
438     }
439
440     # get the root node
441     {
442       my $rs = $schema->resultset('Artist')->search({ parentid => undef }, {
443         start_with => { name => 'root' },
444         connect_by => { parentid => { -prior => { -ident => 'artistid' } } },
445       });
446
447       is_same_sql_bind (
448         $rs->as_query,
449         '(
450           SELECT me.artistid, me.name, me.rank, me.charfield, me.parentid
451             FROM artist me
452           WHERE ( parentid IS NULL )
453           START WITH name = ?
454           CONNECT BY parentid = PRIOR artistid 
455         )',
456         [ [ name => 'root'] ],
457       );
458
459       is_deeply(
460         [ $rs->get_column('name')->all ],
461         [ 'root' ],
462         'found root node',
463       );
464     }
465
466     # combine a connect by with a join
467     SKIP: {
468       # http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a85397/state21b.htm#2066123
469       skip q{Oracle8i doesn't support connect by with join}, 1
470         if $schema->storage->_server_info->{normalized_dbms_version} < 9;
471
472       my $rs = $schema->resultset('Artist')->search(
473         {'cds.title' => { -like => '%cd'} },
474         {
475           join => 'cds',
476           start_with => { 'me.name' => 'root' },
477           connect_by => { parentid => { -prior => { -ident => 'artistid' } } },
478         }
479       );
480
481       is_same_sql_bind (
482         $rs->as_query,
483         '(
484           SELECT me.artistid, me.name, me.rank, me.charfield, me.parentid
485             FROM artist me
486             LEFT JOIN cd cds ON cds.artist = me.artistid
487           WHERE ( cds.title LIKE ? )
488           START WITH me.name = ?
489           CONNECT BY parentid = PRIOR artistid 
490         )',
491         [ [ 'cds.title' => '%cd' ], [ 'me.name' => 'root' ] ],
492       );
493
494       is_deeply(
495         [ $rs->get_column('name')->all ],
496         [ 'grandchild' ],
497         'Connect By with a join result name ok'
498       );
499
500
501       is_same_sql_bind (
502         $rs->count_rs->as_query,
503         '(
504           SELECT COUNT( * )
505             FROM artist me
506             LEFT JOIN cd cds ON cds.artist = me.artistid
507           WHERE ( cds.title LIKE ? )
508           START WITH me.name = ?
509           CONNECT BY parentid = PRIOR artistid 
510         )',
511         [ [ 'cds.title' => '%cd' ], [ 'me.name' => 'root' ] ],
512       );
513
514       is( $rs->count, 1, 'Connect By with a join; count ok' );
515     }
516
517     # combine a connect by with order_by
518     {
519       my $rs = $schema->resultset('Artist')->search({}, {
520         start_with => { name => 'root' },
521         connect_by => { parentid => { -prior => { -ident => 'artistid' } } },
522         order_by => { -asc => [ 'LEVEL', 'name' ] },
523       });
524
525       is_same_sql_bind (
526         $rs->as_query,
527         '(
528           SELECT me.artistid, me.name, me.rank, me.charfield, me.parentid
529           FROM artist me
530           START WITH name = ?
531           CONNECT BY parentid = PRIOR artistid 
532           ORDER BY LEVEL ASC, name ASC
533         )',
534         [ [ name => 'root' ] ],
535       );
536
537
538       # Don't use "$rs->get_column ('name')->all" they build a query arround the $rs.
539       #   If $rs has a order by, the order by is in the subquery and this doesn't work with Oracle 8i.
540       # TODO: write extra test and fix order by handling on Oracle 8i
541       is_deeply (
542         [ map { $_->[1] } $rs->cursor->all ],
543         [ qw/root child1 child2 grandchild greatgrandchild/ ],
544         'Connect By with a order_by - result name ok (without get_column)'
545       );
546
547       SKIP: {
548           skip q{Connect By with a order_by - result name ok (with get_column), Oracle8i doesn't support order by in a subquery},1
549             if $schema->storage->_server_info->{normalized_dbms_version} < 9;
550           is_deeply (
551             [  $rs->get_column ('name')->all ],
552             [ qw/root child1 child2 grandchild greatgrandchild/ ],
553             'Connect By with a order_by - result name ok (with get_column)'
554           );
555       }
556     }
557
558
559     # limit a connect by
560     SKIP: {
561       skip q{Oracle8i doesn't support order by in a subquery}, 1
562         if $schema->storage->_server_info->{normalized_dbms_version} < 9;
563
564       my $rs = $schema->resultset('Artist')->search({}, {
565         start_with => { name => 'root' },
566         connect_by => { parentid => { -prior => { -ident => 'artistid' } } },
567         order_by => { -asc => 'name' },
568         rows => 2,
569       });
570
571       is_same_sql_bind (
572         $rs->as_query,
573         '(
574             SELECT artistid, name, rank, charfield, parentid FROM (
575               SELECT
576                   me.artistid,
577                   me.name,
578                   me.rank,
579                   me.charfield,
580                   me.parentid
581                 FROM artist me
582               START WITH name = ?
583               CONNECT BY parentid = PRIOR artistid
584               ORDER BY name ASC 
585             ) me
586             WHERE ROWNUM <= 2
587         )',
588         [ [ name => 'root' ] ],
589       );
590
591       is_deeply (
592         [ $rs->get_column ('name')->all ],
593         [qw/child1 child2/],
594         'LIMIT a Connect By query - correct names'
595       );
596
597       is_same_sql_bind (
598         $rs->count_rs->as_query,
599         '(
600           SELECT COUNT( * ) FROM (
601             SELECT artistid
602               FROM (
603                 SELECT
604                   me.artistid
605                 FROM artist me 
606                 START WITH name = ? 
607                 CONNECT BY parentid = PRIOR artistid
608               ) me
609             WHERE ROWNUM <= 2
610           ) me
611         )',
612         [ [ name => 'root' ] ],
613       );
614
615       is( $rs->count, 2, 'Connect By; LIMIT count ok' );
616     }
617
618     # combine a connect_by with group_by and having
619     {
620       my $rs = $schema->resultset('Artist')->search({}, {
621         select => { count => 'rank', -as => 'cnt' },
622         start_with => { name => 'root' },
623         connect_by => { parentid => { -prior => { -ident => 'artistid' } } },
624         group_by => ['rank'],
625         having => \[ 'count(rank) < ?', [ cnt => 2 ] ],
626       });
627
628       is_same_sql_bind (
629         $rs->as_query,
630         '(
631             SELECT COUNT(rank) AS cnt
632             FROM artist me
633             START WITH name = ?
634             CONNECT BY parentid = PRIOR artistid
635             GROUP BY rank HAVING count(rank) < ?
636         )',
637         [ [ name => 'root' ], [ cnt => 2 ] ],
638       );
639
640       is_deeply (
641         [ $rs->get_column ('cnt')->all ],
642         [1, 1],
643         'Group By a Connect By query - correct values'
644       );
645     }
646
647
648     # select the whole cycle tree without nocylce
649     {
650       my $rs = $schema->resultset('Artist')->search({}, {
651         start_with => { name => 'cycle-root' },
652         connect_by => { parentid => { -prior => { -ident => 'artistid' } } },
653       });
654       eval { $rs->get_column ('name')->all };
655       if ( $@ =~ /ORA-01436/ ){ # ORA-01436:  CONNECT BY loop in user data
656         pass "connect by initify loop detection without nocycle";
657       }else{
658         fail "connect by initify loop detection without nocycle, not detected by oracle";
659       }
660     }
661
662     # select the whole cycle tree with nocylce
663     SKIP: {
664       # http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a85397/expressi.htm#1023748
665       skip q{Oracle8i doesn't support connect by nocycle}, 1
666         if $schema->storage->_server_info->{normalized_dbms_version} < 9;
667
668       my $rs = $schema->resultset('Artist')->search({}, {
669         start_with => { name => 'cycle-root' },
670         '+select'  => \ 'CONNECT_BY_ISCYCLE',
671         '+as'      => [ 'connector' ],
672         connect_by_nocycle => { parentid => { -prior => { -ident => 'artistid' } } },
673       });
674
675       is_same_sql_bind (
676         $rs->as_query,
677         '(
678           SELECT me.artistid, me.name, me.rank, me.charfield, me.parentid, CONNECT_BY_ISCYCLE
679             FROM artist me
680           START WITH name = ?
681           CONNECT BY NOCYCLE parentid = PRIOR artistid 
682         )',
683         [ [ name => 'cycle-root'] ],
684       );
685       is_deeply (
686         [ $rs->get_column ('name')->all ],
687         [ qw/cycle-root cycle-child1 cycle-grandchild cycle-child2/ ],
688         'got artist tree with nocycle (name)',
689       );
690       is_deeply (
691         [ $rs->get_column ('connector')->all ],
692         [ qw/1 0 0 0/ ],
693         'got artist tree with nocycle (CONNECT_BY_ISCYCLE)',
694       );
695
696
697       is_same_sql_bind (
698         $rs->count_rs->as_query,
699         '(
700           SELECT COUNT( * )
701             FROM artist me
702           START WITH name = ?
703           CONNECT BY NOCYCLE parentid = PRIOR artistid 
704         )',
705         [ [ name => 'cycle-root'] ],
706       );
707
708       is( $rs->count, 4, 'Connect By Nocycle count ok' );
709     }
710 }
711
712 my $schema2;
713
714 # test sequence detection from a different schema
715 SKIP: {
716 TODO: {
717   skip ((join '',
718 'Set DBICTEST_ORA_EXTRAUSER_DSN, _USER and _PASS to a *DIFFERENT* Oracle user',
719 ' to run the cross-schema autoincrement test.'),
720     1) unless $dsn2 && $user2 && $user2 ne $user;
721
722   # Oracle8i Reference Release 2 (8.1.6) 
723   #   http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76961/ch294.htm#993
724   # Oracle Database Reference 10g Release 2 (10.2)
725   #   http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#sthref1297
726   local $TODO = "On Oracle8i all_triggers view is empty, i don't yet know why..."
727     if $schema->storage->_server_info->{normalized_dbms_version} < 9;
728
729   $schema2 = DBICTest::Schema->connect($dsn2, $user2, $pass2);
730
731   my $schema1_dbh  = $schema->storage->dbh;
732
733   $schema1_dbh->do("GRANT INSERT ON artist TO $user2");
734   $schema1_dbh->do("GRANT SELECT ON artist_pk_seq TO $user2");
735
736   my $rs = $schema2->resultset('ArtistFQN');
737
738   # first test with unquoted (default) sequence name in trigger body
739
740   lives_and {
741     my $row = $rs->create({ name => 'From Different Schema' });
742     ok $row->artistid;
743   } 'used autoinc sequence across schemas';
744
745   # now quote the sequence name
746   $schema1_dbh->do(qq{
747     CREATE OR REPLACE TRIGGER artist_insert_trg_pk
748     BEFORE INSERT ON artist
749     FOR EACH ROW
750     BEGIN
751       IF :new.artistid IS NULL THEN
752         SELECT "ARTIST_PK_SEQ".nextval
753         INTO :new.artistid
754         FROM DUAL;
755       END IF;
756     END;
757   });
758
759   # sequence is cached in the rsrc
760   delete $rs->result_source->column_info('artistid')->{sequence};
761
762   lives_and {
763     my $row = $rs->create({ name => 'From Different Schema With Quoted Sequence' });
764     ok $row->artistid;
765   } 'used quoted autoinc sequence across schemas';
766
767   my $schema_name = uc $user;
768
769   is $rs->result_source->column_info('artistid')->{sequence},
770     qq[${schema_name}."ARTIST_PK_SEQ"],
771     'quoted sequence name correctly extracted';
772 } }
773
774 done_testing;
775
776 sub do_creates {
777   my $dbh = shift;
778
779   eval {
780     $dbh->do("DROP SEQUENCE artist_autoinc_seq");
781     $dbh->do("DROP SEQUENCE artist_pk_seq");
782     $dbh->do("DROP SEQUENCE cd_seq");
783     $dbh->do("DROP SEQUENCE track_seq");
784     $dbh->do("DROP SEQUENCE pkid1_seq");
785     $dbh->do("DROP SEQUENCE pkid2_seq");
786     $dbh->do("DROP SEQUENCE nonpkid_seq");
787     $dbh->do("DROP TABLE artist");
788     $dbh->do("DROP TABLE sequence_test");
789     $dbh->do("DROP TABLE track");
790     $dbh->do("DROP TABLE cd");
791   };
792   $dbh->do("CREATE SEQUENCE artist_autoinc_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
793   $dbh->do("CREATE SEQUENCE artist_pk_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
794   $dbh->do("CREATE SEQUENCE cd_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
795   $dbh->do("CREATE SEQUENCE track_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
796   $dbh->do("CREATE SEQUENCE pkid1_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
797   $dbh->do("CREATE SEQUENCE pkid2_seq START WITH 10 MAXVALUE 999999 MINVALUE 0");
798   $dbh->do("CREATE SEQUENCE nonpkid_seq START WITH 20 MAXVALUE 999999 MINVALUE 0");
799
800   $dbh->do("CREATE TABLE artist (artistid NUMBER(12), parentid NUMBER(12), name VARCHAR(255), autoinc_col NUMBER(12), rank NUMBER(38), charfield VARCHAR2(10))");
801   $dbh->do("ALTER TABLE artist ADD (CONSTRAINT artist_pk PRIMARY KEY (artistid))");
802
803   $dbh->do("CREATE TABLE sequence_test (pkid1 NUMBER(12), pkid2 NUMBER(12), nonpkid NUMBER(12), name VARCHAR(255))");
804   $dbh->do("ALTER TABLE sequence_test ADD (CONSTRAINT sequence_test_constraint PRIMARY KEY (pkid1, pkid2))");
805
806   $dbh->do("CREATE TABLE cd (cdid NUMBER(12), artist NUMBER(12), title VARCHAR(255), year VARCHAR(4), genreid NUMBER(12), single_track NUMBER(12))");
807   $dbh->do("ALTER TABLE cd ADD (CONSTRAINT cd_pk PRIMARY KEY (cdid))");
808
809   $dbh->do("CREATE TABLE track (trackid NUMBER(12), cd NUMBER(12) REFERENCES cd(cdid) DEFERRABLE, position NUMBER(12), title VARCHAR(255), last_updated_on DATE, last_updated_at DATE, small_dt DATE)");
810   $dbh->do("ALTER TABLE track ADD (CONSTRAINT track_pk PRIMARY KEY (trackid))");
811
812   $dbh->do(qq{
813     CREATE OR REPLACE TRIGGER artist_insert_trg_auto
814     BEFORE INSERT ON artist
815     FOR EACH ROW
816     BEGIN
817       IF :new.autoinc_col IS NULL THEN
818         SELECT artist_autoinc_seq.nextval
819         INTO :new.autoinc_col
820         FROM DUAL;
821       END IF;
822     END;
823   });
824   $dbh->do(qq{
825     CREATE OR REPLACE TRIGGER artist_insert_trg_pk
826     BEFORE INSERT ON artist
827     FOR EACH ROW
828     BEGIN
829       IF :new.artistid IS NULL THEN
830         SELECT artist_pk_seq.nextval
831         INTO :new.artistid
832         FROM DUAL;
833       END IF;
834     END;
835   });
836   $dbh->do(qq{
837     CREATE OR REPLACE TRIGGER cd_insert_trg
838     BEFORE INSERT OR UPDATE ON cd
839     FOR EACH ROW
840     DECLARE
841     tmpVar NUMBER;
842
843     BEGIN
844       tmpVar := 0;
845
846       IF :new.cdid IS NULL THEN
847         SELECT cd_seq.nextval
848         INTO tmpVar
849         FROM dual;
850
851         :new.cdid := tmpVar;
852       END IF;
853     END;
854   });
855   $dbh->do(qq{
856     CREATE OR REPLACE TRIGGER track_insert_trg
857     BEFORE INSERT ON track
858     FOR EACH ROW
859     BEGIN
860       IF :new.trackid IS NULL THEN
861         SELECT track_seq.nextval
862         INTO :new.trackid
863         FROM DUAL;
864       END IF;
865     END;
866   });
867 }
868
869 # clean up our mess
870 END {
871   for my $dbh (map $_->storage->dbh, grep $_, ($schema, $schema2)) {
872     eval {
873       $dbh->do("DROP SEQUENCE artist_autoinc_seq");
874       $dbh->do("DROP SEQUENCE artist_pk_seq");
875       $dbh->do("DROP SEQUENCE cd_seq");
876       $dbh->do("DROP SEQUENCE track_seq");
877       $dbh->do("DROP SEQUENCE pkid1_seq");
878       $dbh->do("DROP SEQUENCE pkid2_seq");
879       $dbh->do("DROP SEQUENCE nonpkid_seq");
880       $dbh->do("DROP TABLE artist");
881       $dbh->do("DROP TABLE sequence_test");
882       $dbh->do("DROP TABLE track");
883       $dbh->do("DROP TABLE cd");
884       $dbh->do("DROP TABLE bindtype_test");
885     };
886   }
887 }