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