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