Add PRIOR as special and unary op to SQLAHacks::Oracle and use _recurse_where to...
[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   );
23   __PACKAGE__->set_primary_key('artistid');
24
25   1;
26 }
27
28 use strict;
29 use warnings;
30
31 use Test::Exception;
32 use Test::More;
33 use lib qw(t/lib);
34 use DBICTest;
35
36 my ($dsn, $user, $pass) = @ENV{map { "DBICTEST_ORA_${_}" } qw/DSN USER PASS/};
37
38 plan skip_all => 'Set $ENV{DBICTEST_ORA_DSN}, _USER and _PASS to run this test. ' .
39   'Warning: This test drops and creates tables called \'artist\', \'cd\', \'track\' and \'sequence_test\''.
40   ' as well as following sequences: \'pkid1_seq\', \'pkid2_seq\' and \'nonpkid_seq\''
41   unless ($dsn && $user && $pass);
42
43 DBICTest::Schema->load_classes('ArtistFQN');
44 my $schema = DBICTest::Schema->connect($dsn, $user, $pass);
45
46 my $dbh = $schema->storage->dbh;
47
48 if ( $schema->storage->isa('DBIx::Class::Storage::DBI::Oracle::Generic') ) {
49     plan tests => 46;
50 }
51 else {
52     plan tests => 36;
53 }
54
55
56 eval {
57   $dbh->do("DROP SEQUENCE artist_seq");
58   $dbh->do("DROP SEQUENCE cd_seq");
59   $dbh->do("DROP SEQUENCE track_seq");
60   $dbh->do("DROP SEQUENCE pkid1_seq");
61   $dbh->do("DROP SEQUENCE pkid2_seq");
62   $dbh->do("DROP SEQUENCE nonpkid_seq");
63   $dbh->do("DROP TABLE artist");
64   $dbh->do("DROP TABLE sequence_test");
65   $dbh->do("DROP TABLE cd");
66   $dbh->do("DROP TABLE track");
67 };
68 $dbh->do("CREATE SEQUENCE artist_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
69 $dbh->do("CREATE SEQUENCE cd_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
70 $dbh->do("CREATE SEQUENCE track_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
71 $dbh->do("CREATE SEQUENCE pkid1_seq START WITH 1 MAXVALUE 999999 MINVALUE 0");
72 $dbh->do("CREATE SEQUENCE pkid2_seq START WITH 10 MAXVALUE 999999 MINVALUE 0");
73 $dbh->do("CREATE SEQUENCE nonpkid_seq START WITH 20 MAXVALUE 999999 MINVALUE 0");
74 $dbh->do("CREATE TABLE artist (artistid NUMBER(12), parentid NUMBER(12), name VARCHAR(255), rank NUMBER(38), charfield VARCHAR2(10))");
75 $dbh->do("CREATE TABLE sequence_test (pkid1 NUMBER(12), pkid2 NUMBER(12), nonpkid NUMBER(12), name VARCHAR(255))");
76 $dbh->do("CREATE TABLE cd (cdid NUMBER(12), artist NUMBER(12), title VARCHAR(255), year VARCHAR(4), single_track NUMBER(12), genreid NUMBER(12))");
77 $dbh->do("CREATE TABLE track (trackid NUMBER(12), cd NUMBER(12), position NUMBER(12), title VARCHAR(255), last_updated_on DATE, last_updated_at DATE, small_dt DATE)");
78
79 $dbh->do("ALTER TABLE artist ADD (CONSTRAINT artist_pk PRIMARY KEY (artistid))");
80 $dbh->do("ALTER TABLE cd ADD (CONSTRAINT cd_pk PRIMARY KEY (cdid))");
81 $dbh->do("ALTER TABLE track ADD (CONSTRAINT track_pk PRIMARY KEY (trackid))");
82 $dbh->do("ALTER TABLE sequence_test ADD (CONSTRAINT sequence_test_constraint PRIMARY KEY (pkid1, pkid2))");
83 $dbh->do(qq{
84   CREATE OR REPLACE TRIGGER artist_insert_trg
85   BEFORE INSERT ON artist
86   FOR EACH ROW
87   BEGIN
88     IF :new.artistid IS NULL THEN
89       SELECT artist_seq.nextval
90       INTO :new.artistid
91       FROM DUAL;
92     END IF;
93   END;
94 });
95 $dbh->do(qq{
96   CREATE OR REPLACE TRIGGER cd_insert_trg
97   BEFORE INSERT ON cd
98   FOR EACH ROW
99   BEGIN
100     IF :new.cdid IS NULL THEN
101       SELECT cd_seq.nextval
102       INTO :new.cdid
103       FROM DUAL;
104     END IF;
105   END;
106 });
107 $dbh->do(qq{
108   CREATE OR REPLACE TRIGGER cd_insert_trg
109   BEFORE INSERT ON cd
110   FOR EACH ROW
111   BEGIN
112     IF :new.cdid IS NULL THEN
113       SELECT cd_seq.nextval
114       INTO :new.cdid
115       FROM DUAL;
116     END IF;
117   END;
118 });
119 $dbh->do(qq{
120   CREATE OR REPLACE TRIGGER track_insert_trg
121   BEFORE INSERT ON track
122   FOR EACH ROW
123   BEGIN
124     IF :new.trackid IS NULL THEN
125       SELECT track_seq.nextval
126       INTO :new.trackid
127       FROM DUAL;
128     END IF;
129   END;
130 });
131
132 {
133     # Swiped from t/bindtype_columns.t to avoid creating my own Resultset.
134
135     local $SIG{__WARN__} = sub {};
136     eval { $dbh->do('DROP TABLE bindtype_test') };
137
138     $dbh->do(qq[
139         CREATE TABLE bindtype_test
140         (
141             id              integer      NOT NULL   PRIMARY KEY,
142             bytea           integer      NULL,
143             blob            blob         NULL,
144             clob            clob         NULL
145         )
146     ],{ RaiseError => 1, PrintError => 1 });
147 }
148
149 # This is in Core now, but it's here just to test that it doesn't break
150 $schema->class('Artist')->load_components('PK::Auto');
151 # These are compat shims for PK::Auto...
152 $schema->class('CD')->load_components('PK::Auto::Oracle');
153 $schema->class('Track')->load_components('PK::Auto::Oracle');
154
155 # test primary key handling
156 my $new = $schema->resultset('Artist')->create({ name => 'foo' });
157 is($new->artistid, 1, "Oracle Auto-PK worked");
158
159 my $cd = $schema->resultset('CD')->create({ artist => 1, title => 'EP C', year => '2003' });
160 is($new->artistid, 1, "Oracle Auto-PK worked - using scalar ref as table name");
161
162 # test again with fully-qualified table name
163 $new = $schema->resultset('ArtistFQN')->create( { name => 'bar' } );
164 is( $new->artistid, 2, "Oracle Auto-PK worked with fully-qualified tablename" );
165
166 # test join with row count ambiguity
167
168 my $track = $schema->resultset('Track')->create({ cd => $cd->cdid,
169     position => 1, title => 'Track1' });
170 my $tjoin = $schema->resultset('Track')->search({ 'me.title' => 'Track1'},
171         { join => 'cd',
172           rows => 2 }
173 );
174
175 ok(my $row = $tjoin->next);
176
177 is($row->title, 'Track1', "ambiguous column ok");
178
179 # check count distinct with multiple columns
180 my $other_track = $schema->resultset('Track')->create({ cd => $cd->cdid, position => 1, title => 'Track2' });
181
182 my $tcount = $schema->resultset('Track')->search(
183   {},
184   {
185     select => [ qw/position title/ ],
186     distinct => 1,
187   }
188 );
189 is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
190
191 $tcount = $schema->resultset('Track')->search(
192   {},
193   {
194     columns => [ qw/position title/ ],
195     distinct => 1,
196   }
197 );
198 is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
199
200 $tcount = $schema->resultset('Track')->search(
201   {},
202   {
203      group_by => [ qw/position title/ ]
204   }
205 );
206 is($tcount->count, 2, 'multiple column COUNT DISTINCT using column syntax ok');
207
208 # test LIMIT support
209 for (1..6) {
210     $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
211 }
212 my $it = $schema->resultset('Artist')->search( {},
213     { rows => 3,
214       offset => 3,
215       order_by => 'artistid' }
216 );
217 is( $it->count, 3, "LIMIT count ok" );
218 is( $it->next->name, "Artist 2", "iterator->next ok" );
219 $it->next;
220 $it->next;
221 is( $it->next, undef, "next past end of resultset ok" );
222
223 {
224   my $rs = $schema->resultset('Track')->search( undef, { columns=>[qw/trackid position/], group_by=> [ qw/trackid position/ ] , rows => 2, offset=>1 });
225   my @results = $rs->all;
226   is( scalar @results, 1, "Group by with limit OK" );
227 }
228
229 # test auto increment using sequences WITHOUT triggers
230 for (1..5) {
231     my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
232     is($st->pkid1, $_, "Oracle Auto-PK without trigger: First primary key");
233     is($st->pkid2, $_ + 9, "Oracle Auto-PK without trigger: Second primary key");
234     is($st->nonpkid, $_ + 19, "Oracle Auto-PK without trigger: Non-primary key");
235 }
236 my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
237 is($st->pkid1, 55, "Oracle Auto-PK without trigger: First primary key set manually");
238
239 SKIP: {
240         skip 'buggy BLOB support in DBD::Oracle 1.23', 8
241           if $DBD::Oracle::VERSION == 1.23;
242
243         my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
244         $binstr{'large'} = $binstr{'small'} x 1024;
245
246         my $maxloblen = length $binstr{'large'};
247         note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
248         local $dbh->{'LongReadLen'} = $maxloblen;
249
250         my $rs = $schema->resultset('BindType');
251         my $id = 0;
252
253         foreach my $type (qw( blob clob )) {
254                 foreach my $size (qw( small large )) {
255                         $id++;
256
257                         lives_ok { $rs->create( { 'id' => $id, $type => $binstr{$size} } ) }
258                                 "inserted $size $type without dying";
259                         ok($rs->find($id)->$type eq $binstr{$size}, "verified inserted $size $type" );
260                 }
261         }
262 }
263
264 # test hierarchical querys
265 if ( $schema->storage->isa('DBIx::Class::Storage::DBI::Oracle::Generic') ) {
266     my $source = $schema->source('Artist');
267
268     $source->add_column( 'parentid' );
269
270     $source->add_relationship('children', 'DBICTest::Schema::Artist',
271         { 'foreign.parentid' => 'self.artistid' },
272         {
273             accessor => 'multi',
274             join_type => 'LEFT',
275             cascade_delete => 1,
276             cascade_copy => 1,
277         } );
278     $source->add_relationship('parent', 'DBICTest::Schema::Artist',
279         { 'foreign.artistid' => 'self.parentid' },
280         { accessor => 'single' } );
281     DBICTest::Schema::Artist->add_column( 'parentid' );
282     DBICTest::Schema::Artist->has_many(
283         children => 'DBICTest::Schema::Artist',
284         { 'foreign.parentid' => 'self.artistid' }
285     );
286     DBICTest::Schema::Artist->belongs_to(
287         parent => 'DBICTest::Schema::Artist',
288         { 'foreign.artistid' => 'self.parentid' }
289     );
290
291     $schema->resultset('Artist')->create ({
292         name => 'root',
293         cds => [],
294         children => [
295             {
296                 name => 'child1',
297                 children => [
298                     {
299                         name => 'grandchild',
300                         cds => [
301                             {
302                                 title => "grandchilds's cd" ,
303                                 year => '2008',
304                                 tracks => [
305                                     {
306                                         position => 1,
307                                         title => 'Track 1 grandchild',
308                                     }
309                                 ],
310                             }
311                         ],
312                         children => [
313                             {
314                                 name => 'greatgrandchild',
315                             }
316                         ],
317                     }
318                 ],
319             },
320             {
321                 name => 'child2',
322             },
323         ],
324     });
325
326     {
327       # select the whole tree
328       my $rs = $schema->resultset('Artist')->search({},
329                               {
330                                 'start_with' => { 'name' => 'root' },
331                                 'connect_by' => { 'parentid' => { '-prior' => \'artistid' } },
332                               });
333 =pod
334     SELECT
335         COUNT( * )
336     FROM
337         artist me
338     START WITH
339         name = ?
340     CONNECT BY
341         parentid = prior artistid
342
343     Parameters: 'root'
344 =cut
345       is( $rs->count, 5, 'Connect By count ok' );
346       my $ok = 1;
347 =pod
348     SELECT
349         me.artistid, me.name, me.rank, me.charfield, me.parentid
350     FROM
351         artist me
352     START WITH
353         name = ?
354     CONNECT BY
355         parentid = prior artistid
356
357     Parameters: 'root'
358 =cut
359       foreach my $node_name (qw(root child1 grandchild greatgrandchild child2)) {
360         $ok = 0 if $rs->next->name ne $node_name;
361       }
362       ok( $ok, 'got artist tree');
363     }
364
365     {
366       # use order siblings by statement
367       my $rs = $schema->resultset('Artist')->search({},
368                               {
369                                 'start_with' => { 'name' => 'root' },
370                                 'connect_by' => { 'parentid' => { '-prior' => \'artistid' } },
371                                 'order_siblings_by' => 'name DESC',
372                               });
373       my $ok = 1;
374 =pod
375     SELECT
376         me.artistid, me.name, me.rank, me.charfield, me.parentid
377     FROM
378         artist me
379     START WITH
380         name = ?
381     CONNECT BY
382         parentid = prior artistid
383     ORDER SIBLINGS BY
384         name DESC
385
386     Parameters: 'root'
387 =cut
388       foreach my $node_name (qw(root child2 child1 grandchild greatgrandchild)) {
389         $ok = 0 if $rs->next->name ne $node_name;
390       }
391       ok( $ok, 'Order Siblings By ok');
392     }
393
394     {
395       # get the root node
396       my $rs = $schema->resultset('Artist')->search({ parentid => undef },
397                               {
398                                 'start_with' => { 'name' => 'greatgrandchild' },
399                                 'connect_by' => { '-prior' => [  \'parentid', \'artistid' ] } ,
400                               });
401 =pod
402     SELECT
403         COUNT( * )
404     FROM
405         artist me
406     WHERE
407         ( parentid IS NULL )
408     START WITH
409         name = ?
410     CONNECT BY
411         prior parentid = artistid
412
413     Parameters: 'greatgrandchild'
414 =cut
415       is( $rs->count, 1, 'root node count ok' );
416 =pod
417     SELECT
418         me.artistid, me.name, me.rank, me.charfield, me.parentid
419     FROM
420         artist me
421     WHERE
422         ( parentid IS NULL )
423     START WITH
424         name = ?
425     CONNECT BY
426         prior parentid = artistid
427
428     Parameters: 'greatgrandchild'
429 =cut
430       ok( $rs->next->name eq 'root', 'found root node');
431     }
432
433     {
434       # combine a connect by with a join
435       my $rs = $schema->resultset('Artist')->search({'cds.title' => { 'like' => '%cd'}},
436                               {
437                                 'join' => 'cds',
438                                 'start_with' => { 'name' => 'root' },
439                                 'connect_by' => { 'parentid' => { '-prior' => \'artistid' } },
440                               });
441 =pod
442     SELECT
443         COUNT( * )
444     FROM
445         artist me
446     LEFT JOIN
447         cd cds ON cds.artist = me.artistid
448     WHERE
449         ( cds.title LIKE ? )
450     START WITH
451         name = ?
452     CONNECT BY
453         parentid = prior artistid
454
455     Parameters: '%cd', 'root'
456 =cut
457       is( $rs->count, 1, 'Connect By with a join; count ok' );
458 =pod
459     SELECT
460         me.artistid, me.name, me.rank, me.charfield, me.parentid
461     FROM
462         artist me
463     LEFT JOIN
464         cd cds ON cds.artist = me.artistid
465     WHERE
466         ( cds.title LIKE ? )
467     START WITH
468         name = ?
469     CONNECT BY
470         parentid = prior artistid
471
472     Parameters: '%cd', 'root'
473 =cut
474       ok( $rs->next->name eq 'grandchild', 'Connect By with a join; result name ok')
475     }
476
477     {
478       # combine a connect by with order_by
479       my $rs = $schema->resultset('Artist')->search({},
480                               {
481                                 'start_with' => { 'name' => 'greatgrandchild' },
482                                 'connect_by' => { '-prior' => [ \'parentid', \'artistid' ] },
483                                 'order_by' => 'name ASC',
484                               });
485       my $ok = 1;
486 =pod
487     SELECT
488         me.artistid, me.name, me.rank, me.charfield, me.parentid
489     FROM
490         artist me
491     START WITH
492         name = ?
493     CONNECT BY
494         prior parentid = artistid
495     ORDER BY
496         name ASC
497
498     Parameters: 'greatgrandchild'
499 =cut
500       foreach my $node_name (qw(child1 grandchild greatgrandchild root)) {
501         $ok = 0 if $rs->next->name ne $node_name;
502       }
503       ok( $ok, 'Connect By with a order_by; result name ok');
504     }
505
506     {
507       # limit a connect by
508       my $rs = $schema->resultset('Artist')->search({},
509                               {
510                                 'start_with' => { 'name' => 'greatgrandchild' },
511                                 'connect_by' => { '-prior' => [ \'parentid', \'artistid' ] },
512                                 'order_by' => 'name ASC',
513                                 'rows' => 2,
514                                 'page' => 1,
515                               });
516 =pod
517     SELECT
518         COUNT( * )
519     FROM
520         artist me
521     START WITH
522         name = ?
523     CONNECT BY
524         prior parentid = artistid
525
526     Parameters: 'greatgrandchild'
527 =cut
528       is( $rs->count(), 2, 'Connect By; LIMIT count ok' );
529       my $ok = 1;
530 =pod
531     SELECT
532         *
533     FROM
534         (
535             SELECT
536                 A.*,ROWNUM r
537             FROM
538                 (
539                     SELECT
540                         me.artistid AS col1, me.name AS col2, me.rank AS col3, me.charfield AS col4, me.parentid AS col5
541                     FROM
542                         artist me
543                     START WITH
544                         name = ?
545                     CONNECT BY
546                         prior parentid = artistid
547                     ORDER BY
548                         name ASC
549                 ) A
550             WHERE
551                 ROWNUM < 3
552         ) B
553     WHERE
554         r >= 1
555     Parameters: 'greatgrandchild'
556 =cut
557       foreach my $node_name (qw(child1 grandchild)) {
558         $ok = 0 if $rs->next->name ne $node_name;
559       }
560       ok( $ok, 'LIMIT a Connect By query ok');
561     }
562 }
563
564 # clean up our mess
565 END {
566     if($schema && ($dbh = $schema->storage->dbh)) {
567         $dbh->do("DROP SEQUENCE artist_seq");
568         $dbh->do("DROP SEQUENCE cd_seq");
569         $dbh->do("DROP SEQUENCE track_seq");
570         $dbh->do("DROP SEQUENCE pkid1_seq");
571         $dbh->do("DROP SEQUENCE pkid2_seq");
572         $dbh->do("DROP SEQUENCE nonpkid_seq");
573         $dbh->do("DROP TABLE artist");
574         $dbh->do("DROP TABLE sequence_test");
575         $dbh->do("DROP TABLE cd");
576         $dbh->do("DROP TABLE track");
577         $dbh->do("DROP TABLE bindtype_test");
578     }
579 }
580