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