check database driver dependencies for tests
[dbsrgits/DBIx-Class.git] / t / 73oracle.t
1 use strict;
2 use warnings;
3
4 use Test::Exception;
5 use Test::More;
6 use Sub::Name;
7 use Try::Tiny;
8 use DBIx::Class::Optional::Dependencies ();
9
10 use lib qw(t/lib);
11 use DBICTest;
12 use DBIC::SqlMakerTest;
13
14 plan skip_all => 'Test needs ' . DBIx::Class::Optional::Dependencies->req_missing_for ('test_rdbms_oracle')
15   unless DBIx::Class::Optional::Dependencies->req_ok_for ('test_rdbms_oracle');
16
17 $ENV{NLS_SORT} = "BINARY";
18 $ENV{NLS_COMP} = "BINARY";
19 $ENV{NLS_LANG} = "AMERICAN";
20
21 my ($dsn,  $user,  $pass)  = @ENV{map { "DBICTEST_ORA_${_}" }  qw/DSN USER PASS/};
22
23 # optional:
24 my ($dsn2, $user2, $pass2) = @ENV{map { "DBICTEST_ORA_EXTRAUSER_${_}" } qw/DSN USER PASS/};
25
26 plan skip_all => 'Set $ENV{DBICTEST_ORA_DSN}, _USER and _PASS to run this test.'
27   unless ($dsn && $user && $pass);
28
29 {
30   package    # hide from PAUSE
31     DBICTest::Schema::ArtistFQN;
32
33   use base 'DBIx::Class::Core';
34
35   __PACKAGE__->table(
36     $ENV{DBICTEST_ORA_USER}
37       ? (uc $ENV{DBICTEST_ORA_USER}) . '.artist'
38       : '??_no_user_??'
39   );
40   __PACKAGE__->add_columns(
41     'artistid' => {
42       data_type         => 'integer',
43       is_auto_increment => 1,
44     },
45     'name' => {
46       data_type   => 'varchar',
47       size        => 100,
48       is_nullable => 1,
49     },
50     'autoinc_col' => {
51       data_type         => 'integer',
52       is_auto_increment => 1,
53     },
54     'default_value_col' => {
55       data_type           => 'varchar',
56       size                => 100,
57       is_nullable         => 0,
58       retrieve_on_insert  => 1,
59     }
60   );
61   __PACKAGE__->set_primary_key(qw/ artistid autoinc_col /);
62
63   1;
64 }
65
66 DBICTest::Schema->load_classes('ArtistFQN');
67
68 # This is in Core now, but it's here just to test that it doesn't break
69 DBICTest::Schema::Artist->load_components('PK::Auto');
70 # These are compat shims for PK::Auto...
71 DBICTest::Schema::CD->load_components('PK::Auto::Oracle');
72 DBICTest::Schema::Track->load_components('PK::Auto::Oracle');
73
74
75 # check if we indeed do support stuff
76 my $v = do {
77   my $v = DBICTest::Schema->connect($dsn, $user, $pass)->storage->_dbh_get_info(18);
78   $v =~ /^(\d+)\.(\d+)/
79     or die "Unparseable Oracle server version: $v\n";
80
81   sprintf('%d.%03d', $1, $2);
82 };
83
84 my $test_server_supports_only_orajoins = $v < 9;
85
86 # TODO find out which version supports the RETURNING syntax
87 # 8i (8.1) has it and earlier docs are a 404 on oracle.com
88 my $test_server_supports_insert_returning = $v >= 8.001;
89
90 is (
91   DBICTest::Schema->connect($dsn, $user, $pass)->storage->_use_insert_returning,
92   $test_server_supports_insert_returning,
93   'insert returning capability guessed correctly'
94 );
95
96 ##########
97 # the recyclebin (new for 10g) sometimes comes in the way
98 my $on_connect_sql = $v >= 10 ? ["ALTER SESSION SET recyclebin = OFF"] : [];
99
100 # iterate all tests on following options
101 my @tryopt = (
102   { on_connect_do => $on_connect_sql },
103   { quote_char => '"', on_connect_do => $on_connect_sql },
104 );
105
106 # keep a database handle open for cleanup
107 my ($dbh, $dbh2);
108
109 my $schema;
110 for my $use_insert_returning ($test_server_supports_insert_returning ? (1,0) : (0) ) {
111   for my $force_ora_joins ($test_server_supports_only_orajoins ? (0) : (0,1) ) {
112
113     no warnings qw/once/;
114     local *DBICTest::Schema::connection = subname 'DBICTest::Schema::connection' => sub {
115       my $s = shift->next::method (@_);
116       $s->storage->_use_insert_returning ($use_insert_returning);
117       $s->storage->sql_maker_class('DBIx::Class::SQLMaker::OracleJoins') if $force_ora_joins;
118       $s;
119     };
120
121     for my $opt (@tryopt) {
122       # clean all cached sequences from previous run
123       for (map { values %{DBICTest::Schema->source($_)->columns_info} } (qw/Artist CD Track/) ) {
124         delete $_->{sequence};
125       }
126
127       my $schema = DBICTest::Schema->connect($dsn, $user, $pass, $opt);
128
129       $dbh = $schema->storage->dbh;
130       my $q = $schema->storage->sql_maker->quote_char || '';
131
132       do_creates($dbh, $q);
133
134       _run_tests($schema, $opt);
135     }
136   }
137 }
138
139 sub _run_tests {
140   my ($schema, $opt) = @_;
141
142   my $q = $schema->storage->sql_maker->quote_char || '';
143
144 # test primary key handling with multiple triggers
145   my ($new, $seq);
146
147   my $new_artist = $schema->resultset('Artist')->create({ name => 'foo' });
148   my $new_cd     = $schema->resultset('CD')->create({ artist => 1, title => 'EP C', year => '2003' });
149
150   SKIP: {
151     skip 'not detecting sequences when using INSERT ... RETURNING', 4
152       if $schema->storage->_use_insert_returning;
153
154     is($new_artist->artistid, 1, "Oracle Auto-PK worked for standard sqlt-like trigger");
155     $seq = $new_artist->result_source->column_info('artistid')->{sequence};
156     $seq = $$seq if ref $seq;
157     like ($seq, qr/\.${q}artist_pk_seq${q}$/, 'Correct PK sequence selected for sqlt-like trigger');
158
159     is($new_cd->cdid, 1, 'Oracle Auto-PK worked - using scalar ref as table name/custom weird trigger');
160     $seq = $new_cd->result_source->column_info('cdid')->{sequence};
161     $seq = $$seq if ref $seq;
162     like ($seq, qr/\.${q}cd_seq${q}$/, 'Correct PK sequence selected for custom trigger');
163   }
164
165 # test PKs again with fully-qualified table name
166   my $artistfqn_rs = $schema->resultset('ArtistFQN');
167   my $artist_rsrc = $artistfqn_rs->result_source;
168
169   delete $artist_rsrc->column_info('artistid')->{sequence};
170   $new = $artistfqn_rs->create( { name => 'bar' } );
171
172   is_deeply( {map { $_ => $new->$_ } $artist_rsrc->primary_columns},
173     { artistid => 2, autoinc_col => 2},
174     "Oracle Multi-Auto-PK worked with fully-qualified tablename" );
175
176
177   delete $artist_rsrc->column_info('artistid')->{sequence};
178   $new = $artistfqn_rs->create( { name => 'bar', autoinc_col => 1000 } );
179
180   is( $new->artistid, 3, "Oracle Auto-PK worked with fully-qualified tablename" );
181   is( $new->autoinc_col, 1000, "Oracle Auto-Inc overruled with fully-qualified tablename");
182
183
184   is( $new->default_value_col, 'default_value', $schema->storage->_use_insert_returning
185     ? 'Check retrieve_on_insert on default_value_col with INSERT ... RETURNING'
186     : 'Check retrieve_on_insert on default_value_col without INSERT ... RETURNING'
187   );
188
189   SKIP: {
190     skip 'not detecting sequences when using INSERT ... RETURNING', 1
191       if $schema->storage->_use_insert_returning;
192
193     $seq = $new->result_source->column_info('artistid')->{sequence};
194     $seq = $$seq if ref $seq;
195     like ($seq, qr/\.${q}artist_pk_seq${q}$/, 'Correct PK sequence selected for sqlt-like trigger');
196   }
197
198
199 # test LIMIT support
200   for (1..6) {
201     $schema->resultset('Artist')->create({ name => 'Artist ' . $_ });
202   }
203   my $it = $schema->resultset('Artist')->search( { name => { -like => 'Artist %' } }, {
204     rows => 3,
205     offset => 4,
206     order_by => 'artistid'
207   });
208
209   is( $it->count, 2, "LIMIT count past end of RS ok" );
210   is( $it->next->name, "Artist 5", "iterator->next ok" );
211   is( $it->next->name, "Artist 6", "iterator->next ok" );
212   is( $it->next, undef, "next past end of resultset ok" );
213
214 # test identifiers over the 30 char limit
215   lives_ok {
216     my @results = $schema->resultset('CD')->search(undef, {
217       prefetch => 'very_long_artist_relationship',
218       rows => 3,
219       offset => 0,
220     })->all;
221     ok( scalar @results > 0, 'limit with long identifiers returned something');
222   } 'limit with long identifiers executed successfully';
223
224
225 # test rel names over the 30 char limit
226   my $query = $schema->resultset('Artist')->search({
227     artistid => 1
228   }, {
229     prefetch => 'cds_very_very_very_long_relationship_name'
230   });
231
232   lives_and {
233     is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
234   } 'query with rel name over 30 chars survived and worked';
235
236 # test rel names over the 30 char limit using group_by and join
237   {
238     my @group_cols = ( 'me.name' );
239     my $query = $schema->resultset('Artist')->search({
240       artistid => 1
241     }, {
242       select => \@group_cols,
243       as => [map { /^\w+\.(\w+)$/ } @group_cols],
244       join => [qw( cds_very_very_very_long_relationship_name )],
245       group_by => \@group_cols,
246     });
247
248     lives_and {
249       my @got = $query->get_column('name')->all();
250       is_deeply \@got, [$new_artist->name];
251     } 'query with rel name over 30 chars worked on join, group_by for me col';
252
253     lives_and {
254       is $query->count(), 1
255     } 'query with rel name over 30 chars worked on join, group_by, count for me col';
256   }
257   {
258     my @group_cols = ( 'cds_very_very_very_long_relationship_name.title' );
259     my $query = $schema->resultset('Artist')->search({
260       artistid => 1
261     }, {
262       select => \@group_cols,
263       as => [map { /^\w+\.(\w+)$/ } @group_cols],
264       join => [qw( cds_very_very_very_long_relationship_name )],
265       group_by => \@group_cols,
266     });
267
268     lives_and {
269       my @got = $query->get_column('title')->all();
270       is_deeply \@got, [$new_cd->title];
271     } 'query with rel name over 30 chars worked on join, group_by for long rel col';
272
273     lives_and {
274       is $query->count(), 1
275     } 'query with rel name over 30 chars worked on join, group_by, count for long rel col';
276   }
277
278   # rel name over 30 char limit with user condition
279   # This requires walking the SQLA data structure.
280   {
281     $query = $schema->resultset('Artist')->search({
282       'cds_very_very_very_long_relationship_name.title' => 'EP C'
283     }, {
284       prefetch => 'cds_very_very_very_long_relationship_name'
285     });
286
287     lives_and {
288       is $query->first->cds_very_very_very_long_relationship_name->first->cdid, 1
289     } 'query with rel name over 30 chars and user condition survived and worked';
290   }
291
292
293 # test join with row count ambiguity
294   my $cd = $schema->resultset('CD')->next;
295   my $track = $cd->create_related('tracks', { position => 1, title => 'Track1'} );
296   my $tjoin = $schema->resultset('Track')->search({ 'me.title' => 'Track1'}, {
297     join => 'cd', rows => 2
298   });
299
300   ok(my $row = $tjoin->next);
301
302   is($row->title, 'Track1', "ambiguous column ok");
303
304
305
306 # check count distinct with multiple columns
307   my $other_track = $schema->resultset('Track')->create({ cd => $cd->cdid, position => 1, title => 'Track2' });
308
309   my $tcount = $schema->resultset('Track')->search(
310     {},
311     {
312       select => [ qw/position title/ ],
313       distinct => 1,
314     }
315   );
316   is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
317
318   $tcount = $schema->resultset('Track')->search(
319     {},
320     {
321       columns => [ qw/position title/ ],
322       distinct => 1,
323     }
324   );
325   is($tcount->count, 2, 'multiple column COUNT DISTINCT ok');
326
327   $tcount = $schema->resultset('Track')->search(
328     {},
329     {
330       group_by => [ qw/position title/ ]
331     }
332   );
333   is($tcount->count, 2, 'multiple column COUNT DISTINCT using column syntax ok');
334
335
336 # check group_by
337   my $g_rs = $schema->resultset('Track')->search( undef, { columns=>[qw/trackid position/], group_by=> [ qw/trackid position/ ] , rows => 2, offset => 1 });
338   is( scalar $g_rs->all, 1, "Group by with limit OK" );
339
340
341 # test with_deferred_fk_checks
342   lives_ok {
343     $schema->storage->with_deferred_fk_checks(sub {
344       $schema->resultset('Track')->create({
345         trackid => 999, cd => 999, position => 1, title => 'deferred FK track'
346       });
347       $schema->resultset('CD')->create({
348         artist => 1, cdid => 999, year => '2003', title => 'deferred FK cd'
349       });
350     });
351   } 'with_deferred_fk_checks code survived';
352
353   is eval { $schema->resultset('Track')->find(999)->title }, 'deferred FK track',
354     'code in with_deferred_fk_checks worked';
355
356   throws_ok {
357     $schema->resultset('Track')->create({
358       trackid => 1, cd => 9999, position => 1, title => 'Track1'
359     });
360   } qr/constraint/i, 'with_deferred_fk_checks is off';
361
362
363 # test auto increment using sequences WITHOUT triggers
364   for (1..5) {
365     my $st = $schema->resultset('SequenceTest')->create({ name => 'foo' });
366     is($st->pkid1, $_, "Oracle Auto-PK without trigger: First primary key");
367     is($st->pkid2, $_ + 9, "Oracle Auto-PK without trigger: Second primary key");
368     is($st->nonpkid, $_ + 19, "Oracle Auto-PK without trigger: Non-primary key");
369   }
370   my $st = $schema->resultset('SequenceTest')->create({ name => 'foo', pkid1 => 55 });
371   is($st->pkid1, 55, "Oracle Auto-PK without trigger: First primary key set manually");
372
373
374 # test BLOBs
375   SKIP: {
376   TODO: {
377     my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
378     $binstr{'large'} = $binstr{'small'} x 1024;
379
380     my $maxloblen = (length $binstr{'large'}) + 5;
381     note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
382     local $dbh->{'LongReadLen'} = $maxloblen;
383
384     my $rs = $schema->resultset('BindType');
385
386     if ($DBD::Oracle::VERSION eq '1.23') {
387       throws_ok { $rs->create({ id => 1, blob => $binstr{large} }) }
388         qr/broken/,
389         'throws on blob insert with DBD::Oracle == 1.23';
390
391       skip 'buggy BLOB support in DBD::Oracle 1.23', 1;
392     }
393
394     # disable BLOB mega-output
395     my $orig_debug = $schema->storage->debug;
396     $schema->storage->debug (0);
397
398     local $TODO = 'Something is confusing column bindtype assignment when quotes are active'
399                 . ': https://rt.cpan.org/Ticket/Display.html?id=64206'
400       if $q;
401
402     my $id;
403     foreach my $size (qw( small large )) {
404       $id++;
405
406       my $str = $binstr{$size};
407       lives_ok {
408         $rs->create( { 'id' => $id, blob => "blob:$str", clob => "clob:$str" } )
409       } "inserted $size without dying";
410
411       my %kids = %{$schema->storage->_dbh->{CachedKids}};
412       my @objs = $rs->search({ blob => "blob:$str", clob => "clob:$str" })->all;
413       is_deeply (
414         $schema->storage->_dbh->{CachedKids},
415         \%kids,
416         'multi-part LOB equality query was not cached',
417       ) if $size eq 'large';
418       is @objs, 1, 'One row found matching on both LOBs';
419       ok (try { $objs[0]->blob }||'' eq "blob:$str", 'blob inserted/retrieved correctly');
420       ok (try { $objs[0]->clob }||'' eq "clob:$str", 'clob inserted/retrieved correctly');
421
422       TODO: {
423         local $TODO = '-like comparison on blobs not tested before ora 10 (fails on 8i)'
424           if $schema->storage->_server_info->{normalized_dbms_version} < 10;
425
426         lives_ok {
427           @objs = $rs->search({ clob => { -like => 'clob:%' } })->all;
428           ok (@objs, 'rows found matching CLOB with a LIKE query');
429         } 'Query with like on blob succeeds';
430       }
431
432       ok(my $subq = $rs->search(
433         { blob => "blob:$str", clob => "clob:$str" },
434         {
435           from => \ "(SELECT * FROM ${q}bindtype_test${q} WHERE ${q}id${q} != ?) ${q}me${q}",
436           bind => [ [ undef => 12345678 ] ],
437         }
438       )->get_column('id')->as_query);
439
440       @objs = $rs->search({ id => { -in => $subq } })->all;
441       is (@objs, 1, 'One row found matching on both LOBs as a subquery');
442
443       lives_ok {
444         $rs->search({ blob => "blob:$str", clob => "clob:$str" })
445           ->update({ blob => 'updated blob', clob => 'updated clob' });
446       } 'blob UPDATE with WHERE clause survived';
447
448       @objs = $rs->search({ blob => "updated blob", clob => 'updated clob' })->all;
449       is @objs, 1, 'found updated row';
450       ok (try { $objs[0]->blob }||'' eq "updated blob", 'blob updated/retrieved correctly');
451       ok (try { $objs[0]->clob }||'' eq "updated clob", 'clob updated/retrieved correctly');
452
453       lives_ok {
454         $rs->search({ blob => "updated blob", clob => "updated clob" })
455           ->delete;
456       } 'blob DELETE with WHERE clause survived';
457       @objs = $rs->search({ blob => "updated blob", clob => 'updated clob' })->all;
458       is @objs, 0, 'row deleted successfully';
459     }
460
461     $schema->storage->debug ($orig_debug);
462   }}
463
464 # test populate (identity, success and error handling)
465   my $art_rs = $schema->resultset('Artist');
466
467   my $seq_pos = $art_rs->get_column('artistid')->max;
468   ok($seq_pos, 'Starting with something in the artist table');
469
470
471   my $pop_rs = $schema->resultset('Artist')->search(
472     { name => { -like => 'pop_art_%' } },
473     { order_by => 'artistid' }
474   );
475
476   $art_rs->delete;
477   lives_ok {
478     $pop_rs->populate([
479       map { +{ name => "pop_art_$_" } }
480       (1,2,3)
481     ]);
482
483     is_deeply (
484       [ $pop_rs->get_column('artistid')->all ],
485       [ map { $seq_pos + $_ } (1,2,3) ],
486       'Sequence works after empty-table insertion'
487     );
488   } 'Populate without identity does not throw';
489
490   lives_ok {
491     $pop_rs->populate([
492       map { +{ artistid => $_, name => "pop_art_$_" } }
493       (1,2,3)
494     ]);
495
496     is_deeply (
497       [ $pop_rs->get_column('artistid')->all ],
498       [ 1,2,3, map { $seq_pos + $_ } (1,2,3) ],
499       'Explicit id population works'
500     );
501   } 'Populate with identity does not throw';
502
503   throws_ok {
504     $pop_rs->populate([
505       map { +{ artistid => $_, name => "pop_art_$_" } }
506       (200, 1, 300)
507     ]);
508   } qr/unique constraint.+populate slice.+name => "pop_art_1"/s, 'Partially failed populate throws';
509
510   is_deeply (
511     [ $pop_rs->get_column('artistid')->all ],
512     [ 1,2,3, map { $seq_pos + $_ } (1,2,3) ],
513     'Partially failed populate did not alter table contents'
514   );
515
516 # test complex join (exercise orajoins)
517   lives_ok {
518     my @hri = $schema->resultset('CD')->search(
519       { 'artist.name' => 'pop_art_1', 'me.cdid' => { '!=', 999} },
520       { join => 'artist', prefetch => 'tracks', rows => 4, order_by => 'tracks.trackid' }
521     )->hri_dump->all;
522
523     my $expect = [{
524       artist => 1,
525       cdid => 1,
526       genreid => undef,
527       single_track => undef,
528       title => "EP C",
529       tracks => [
530         {
531           cd => 1,
532           last_updated_at => undef,
533           last_updated_on => undef,
534           position => 1,
535           title => "Track1",
536           trackid => 1
537         },
538         {
539           cd => 1,
540           last_updated_at => undef,
541           last_updated_on => undef,
542           position => 1,
543           title => "Track2",
544           trackid => 2
545         },
546       ],
547       year => 2003
548     }];
549
550     is_deeply (
551       \@hri,
552       $expect,
553       'Correct set of data prefetched',
554     );
555
556   } 'complex prefetch ok';
557
558 # test sequence detection from a different schema
559   SKIP: {
560   TODO: {
561     skip ((join '',
562       'Set DBICTEST_ORA_EXTRAUSER_DSN, _USER and _PASS to a *DIFFERENT* Oracle user',
563       ' to run the cross-schema sequence detection test.'),
564     1) unless $dsn2 && $user2 && $user2 ne $user;
565
566     skip 'not detecting cross-schema sequence name when using INSERT ... RETURNING', 1
567       if $schema->storage->_use_insert_returning;
568
569     # Oracle8i Reference Release 2 (8.1.6)
570     #   http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76961/ch294.htm#993
571     # Oracle Database Reference 10g Release 2 (10.2)
572     #   http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#sthref1297
573     local $TODO = "On Oracle8i all_triggers view is empty, i don't yet know why..."
574       if $schema->storage->_server_info->{normalized_dbms_version} < 9;
575
576     my $schema2 = $schema->connect($dsn2, $user2, $pass2, $opt);
577     my $dbh2 = $schema2->storage->dbh;
578
579     # create identically named tables/sequences in the other schema
580     do_creates($dbh2, $q);
581
582     # grand select privileges to the 2nd user
583     $dbh->do("GRANT INSERT ON ${q}artist${q} TO " . uc $user2);
584     $dbh->do("GRANT SELECT ON ${q}artist${q} TO " . uc $user2);
585     $dbh->do("GRANT SELECT ON ${q}artist_pk_seq${q} TO " . uc $user2);
586     $dbh->do("GRANT SELECT ON ${q}artist_autoinc_seq${q} TO " . uc $user2);
587
588     # test with a fully qualified table (user1/schema prepended)
589     my $rs2 = $schema2->resultset('ArtistFQN');
590     delete $rs2->result_source->column_info('artistid')->{sequence};
591
592     lives_and {
593       my $row = $rs2->create({ name => 'From Different Schema' });
594       ok $row->artistid;
595     } 'used autoinc sequence across schemas';
596
597     # now quote the sequence name (do_creates always uses an lc name)
598     my $q_seq = $q
599       ? '"artist_pk_seq"'
600       : '"ARTIST_PK_SEQ"'
601     ;
602     delete $rs2->result_source->column_info('artistid')->{sequence};
603     $dbh->do(qq{
604       CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
605       BEFORE INSERT ON ${q}artist${q}
606       FOR EACH ROW
607       BEGIN
608         IF :new.${q}artistid${q} IS NULL THEN
609           SELECT $q_seq.nextval
610           INTO :new.${q}artistid${q}
611           FROM DUAL;
612         END IF;
613       END;
614     });
615
616
617     lives_and {
618       my $row = $rs2->create({ name => 'From Different Schema With Quoted Sequence' });
619       ok $row->artistid;
620     } 'used quoted autoinc sequence across schemas';
621
622     is_deeply $rs2->result_source->column_info('artistid')->{sequence},
623       \( (uc $user) . ".$q_seq"),
624       'quoted sequence name correctly extracted';
625
626     # try an insert operation on the default user2 artist
627     my $art1 = $schema->resultset('Artist');
628     my $art2 = $schema2->resultset('Artist');
629     my $art1_count = $art1->count || 0;
630     my $art2_count = $art2->count;
631
632     is( $art2_count, 0, 'No artists created yet in second schema' );
633
634     delete $art2->result_source->column_info('artistid')->{sequence};
635     my $new_art = $art2->create({ name => '2nd best' });
636
637     is ($art1->count, $art1_count, 'No new rows in main schema');
638     is ($art2->count, 1, 'One artist create in 2nd schema');
639
640     is( $new_art->artistid, 1, 'Expected first PK' );
641
642     do_clean ($dbh2);
643   }}
644
645   do_clean ($dbh);
646 }
647
648 done_testing;
649
650 sub do_creates {
651   my ($dbh, $q) = @_;
652
653   do_clean($dbh);
654
655   $dbh->do("CREATE SEQUENCE ${q}artist_autoinc_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
656   $dbh->do("CREATE SEQUENCE ${q}artist_pk_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
657   $dbh->do("CREATE SEQUENCE ${q}cd_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
658   $dbh->do("CREATE SEQUENCE ${q}track_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
659
660   $dbh->do("CREATE SEQUENCE ${q}nonpkid_seq${q} START WITH 20 MAXVALUE 999999 MINVALUE 0");
661   # this one is always quoted as per manually specified sequence =>
662   $dbh->do('CREATE SEQUENCE "pkid1_seq" START WITH 1 MAXVALUE 999999 MINVALUE 0');
663   # this one is always unquoted as per manually specified sequence =>
664   $dbh->do("CREATE SEQUENCE pkid2_seq START WITH 10 MAXVALUE 999999 MINVALUE 0");
665
666   $dbh->do("CREATE TABLE ${q}artist${q} (${q}artistid${q} NUMBER(12), ${q}name${q} VARCHAR(255),${q}default_value_col${q} VARCHAR(255) DEFAULT 'default_value', ${q}autoinc_col${q} NUMBER(12), ${q}rank${q} NUMBER(38), ${q}charfield${q} VARCHAR2(10))");
667   $dbh->do("ALTER TABLE ${q}artist${q} ADD (CONSTRAINT ${q}artist_pk${q} PRIMARY KEY (${q}artistid${q}))");
668
669   $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))");
670   $dbh->do("ALTER TABLE ${q}sequence_test${q} ADD (CONSTRAINT ${q}sequence_test_constraint${q} PRIMARY KEY (${q}pkid1${q}, ${q}pkid2${q}))");
671
672   # table cd will be unquoted => Oracle will see it as uppercase
673   $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))");
674   $dbh->do("ALTER TABLE cd ADD (CONSTRAINT ${q}cd_pk${q} PRIMARY KEY (${q}cdid${q}))");
675
676   $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)");
677   $dbh->do("ALTER TABLE ${q}track${q} ADD (CONSTRAINT ${q}track_pk${q} PRIMARY KEY (${q}trackid${q}))");
678
679   $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, ${q}a_memo${q} integer NULL)");
680
681   $dbh->do(qq{
682     CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_auto${q}
683     BEFORE INSERT ON ${q}artist${q}
684     FOR EACH ROW
685     BEGIN
686       IF :new.${q}autoinc_col${q} IS NULL THEN
687         SELECT ${q}artist_autoinc_seq${q}.nextval
688         INTO :new.${q}autoinc_col${q}
689         FROM DUAL;
690       END IF;
691     END;
692   });
693
694   $dbh->do(qq{
695     CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
696     BEFORE INSERT ON ${q}artist${q}
697     FOR EACH ROW
698     BEGIN
699       IF :new.${q}artistid${q} IS NULL THEN
700         SELECT ${q}artist_pk_seq${q}.nextval
701         INTO :new.${q}artistid${q}
702         FROM DUAL;
703       END IF;
704     END;
705   });
706
707   $dbh->do(qq{
708     CREATE OR REPLACE TRIGGER ${q}cd_insert_trg${q}
709     BEFORE INSERT OR UPDATE ON cd
710     FOR EACH ROW
711
712     DECLARE
713     tmpVar NUMBER;
714
715     BEGIN
716       tmpVar := 0;
717
718       IF :new.${q}cdid${q} IS NULL THEN
719         SELECT ${q}cd_seq${q}.nextval
720         INTO tmpVar
721         FROM dual;
722
723         :new.${q}cdid${q} := tmpVar;
724       END IF;
725     END;
726   });
727
728   $dbh->do(qq{
729     CREATE OR REPLACE TRIGGER ${q}track_insert_trg${q}
730     BEFORE INSERT ON ${q}track${q}
731     FOR EACH ROW
732     BEGIN
733       IF :new.${q}trackid${q} IS NULL THEN
734         SELECT ${q}track_seq${q}.nextval
735         INTO :new.${q}trackid${q}
736         FROM DUAL;
737       END IF;
738     END;
739   });
740 }
741
742 # clean up our mess
743 sub do_clean {
744
745   my $dbh = shift || return;
746
747   for my $q ('', '"') {
748     my @clean = (
749       "DROP TRIGGER ${q}track_insert_trg${q}",
750       "DROP TRIGGER ${q}cd_insert_trg${q}",
751       "DROP TRIGGER ${q}artist_insert_trg_auto${q}",
752       "DROP TRIGGER ${q}artist_insert_trg_pk${q}",
753       "DROP SEQUENCE ${q}nonpkid_seq${q}",
754       "DROP SEQUENCE ${q}pkid2_seq${q}",
755       "DROP SEQUENCE ${q}pkid1_seq${q}",
756       "DROP SEQUENCE ${q}track_seq${q}",
757       "DROP SEQUENCE ${q}cd_seq${q}",
758       "DROP SEQUENCE ${q}artist_autoinc_seq${q}",
759       "DROP SEQUENCE ${q}artist_pk_seq${q}",
760       "DROP TABLE ${q}bindtype_test${q}",
761       "DROP TABLE ${q}sequence_test${q}",
762       "DROP TABLE ${q}track${q}",
763       "DROP TABLE ${q}cd${q}",
764       "DROP TABLE ${q}artist${q}",
765     );
766     eval { $dbh -> do ($_) } for @clean;
767   }
768 }
769
770 END {
771   for ($dbh, $dbh2) {
772     next unless $_;
773     local $SIG{__WARN__} = sub {};
774     do_clean($_);
775     $_->disconnect;
776   }
777 }