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