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