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