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