remove some Win32 workarounds in tests from cygwin
[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 BLOBs
376   SKIP: {
377   TODO: {
378     my %binstr = ( 'small' => join('', map { chr($_) } ( 1 .. 127 )) );
379     $binstr{'large'} = $binstr{'small'} x 1024;
380
381     my $maxloblen = (length $binstr{'large'}) + 5;
382     note "Localizing LongReadLen to $maxloblen to avoid truncation of test data";
383     local $dbh->{'LongReadLen'} = $maxloblen;
384
385     my $rs = $schema->resultset('BindType');
386
387     if ($DBD::Oracle::VERSION eq '1.23') {
388       throws_ok { $rs->create({ id => 1, blob => $binstr{large} }) }
389         qr/broken/,
390         'throws on blob insert with DBD::Oracle == 1.23';
391
392       skip 'buggy BLOB support in DBD::Oracle 1.23', 1;
393     }
394
395     # disable BLOB mega-output
396     my $orig_debug = $schema->storage->debug;
397
398     local $TODO = 'Something is confusing column bindtype assignment when quotes are active'
399                 . ': https://rt.cpan.org/Ticket/Display.html?id=64206'
400       if $q;
401
402     my $id;
403     foreach my $size (qw( small large )) {
404       $id++;
405
406       if ($size eq 'small') {
407         $schema->storage->debug($orig_debug);
408       }
409       elsif ($size eq 'large') {
410         $schema->storage->debug(0);
411       }
412
413       my $str = $binstr{$size};
414       lives_ok {
415         $rs->create( { 'id' => $id, blob => "blob:$str", clob => "clob:$str" } )
416       } "inserted $size without dying";
417
418       my %kids = %{$schema->storage->_dbh->{CachedKids}};
419       my @objs = $rs->search({ blob => "blob:$str", clob => "clob:$str" })->all;
420       is_deeply (
421         $schema->storage->_dbh->{CachedKids},
422         \%kids,
423         'multi-part LOB equality query was not cached',
424       ) if $size eq 'large';
425       is @objs, 1, 'One row found matching on both LOBs';
426       ok (try { $objs[0]->blob }||'' eq "blob:$str", 'blob inserted/retrieved correctly');
427       ok (try { $objs[0]->clob }||'' eq "clob:$str", 'clob inserted/retrieved correctly');
428
429       TODO: {
430         local $TODO = '-like comparison on blobs not tested before ora 10 (fails on 8i)'
431           if $schema->storage->_server_info->{normalized_dbms_version} < 10;
432
433         lives_ok {
434           @objs = $rs->search({ clob => { -like => 'clob:%' } })->all;
435           ok (@objs, 'rows found matching CLOB with a LIKE query');
436         } 'Query with like on blob succeeds';
437       }
438
439       ok(my $subq = $rs->search(
440         { blob => "blob:$str", clob => "clob:$str" },
441         {
442           from => \ "(SELECT * FROM ${q}bindtype_test${q} WHERE ${q}id${q} != ?) ${q}me${q}",
443           bind => [ [ undef => 12345678 ] ],
444         }
445       )->get_column('id')->as_query);
446
447       @objs = $rs->search({ id => { -in => $subq } })->all;
448       is (@objs, 1, 'One row found matching on both LOBs as a subquery');
449
450       lives_ok {
451         $rs->search({ id => $id, blob => "blob:$str", clob => "clob:$str" })
452           ->update({ blob => 'updated blob', clob => 'updated clob' });
453       } 'blob UPDATE with blobs in WHERE clause survived';
454
455       @objs = $rs->search({ blob => "updated blob", clob => 'updated clob' })->all;
456       is @objs, 1, 'found updated row';
457       ok (try { $objs[0]->blob }||'' eq "updated blob", 'blob updated/retrieved correctly');
458       ok (try { $objs[0]->clob }||'' eq "updated clob", 'clob updated/retrieved correctly');
459
460       lives_ok {
461         $rs->search({ id => $id  })
462           ->update({ blob => 're-updated blob', clob => 're-updated clob' });
463       } 'blob UPDATE without blobs in WHERE clause survived';
464
465       @objs = $rs->search({ blob => 're-updated blob', clob => 're-updated clob' })->all;
466       is @objs, 1, 'found updated row';
467       ok (try { $objs[0]->blob }||'' eq 're-updated blob', 'blob updated/retrieved correctly');
468       ok (try { $objs[0]->clob }||'' eq 're-updated clob', 'clob updated/retrieved correctly');
469
470       lives_ok {
471         $rs->search({ blob => "re-updated blob", clob => "re-updated clob" })
472           ->delete;
473       } 'blob DELETE with WHERE clause survived';
474       @objs = $rs->search({ blob => "re-updated blob", clob => 're-updated clob' })->all;
475       is @objs, 0, 'row deleted successfully';
476     }
477
478     $schema->storage->debug ($orig_debug);
479   }}
480
481 # test populate (identity, success and error handling)
482   my $art_rs = $schema->resultset('Artist');
483
484   my $seq_pos = $art_rs->get_column('artistid')->max;
485   ok($seq_pos, 'Starting with something in the artist table');
486
487
488   my $pop_rs = $schema->resultset('Artist')->search(
489     { name => { -like => 'pop_art_%' } },
490     { order_by => 'artistid' }
491   );
492
493   $art_rs->delete;
494   lives_ok {
495     $pop_rs->populate([
496       map { +{ name => "pop_art_$_" } }
497       (1,2,3)
498     ]);
499
500     is_deeply (
501       [ $pop_rs->get_column('artistid')->all ],
502       [ map { $seq_pos + $_ } (1,2,3) ],
503       'Sequence works after empty-table insertion'
504     );
505   } 'Populate without identity does not throw';
506
507   lives_ok {
508     $pop_rs->populate([
509       map { +{ artistid => $_, name => "pop_art_$_" } }
510       (1,2,3)
511     ]);
512
513     is_deeply (
514       [ $pop_rs->get_column('artistid')->all ],
515       [ 1,2,3, map { $seq_pos + $_ } (1,2,3) ],
516       'Explicit id population works'
517     );
518   } 'Populate with identity does not throw';
519
520   throws_ok {
521     $pop_rs->populate([
522       map { +{ artistid => $_, name => "pop_art_$_" } }
523       (200, 1, 300)
524     ]);
525   } qr/unique constraint.+populate slice.+name => "pop_art_1"/s, 'Partially failed populate throws';
526
527   is_deeply (
528     [ $pop_rs->get_column('artistid')->all ],
529     [ 1,2,3, map { $seq_pos + $_ } (1,2,3) ],
530     'Partially failed populate did not alter table contents'
531   );
532
533 # test complex join (exercise orajoins)
534   lives_ok {
535     my @hri = $schema->resultset('CD')->search(
536       { 'artist.name' => 'pop_art_1', 'me.cdid' => { '!=', 999} },
537       { join => 'artist', prefetch => 'tracks', rows => 4, order_by => 'tracks.trackid' }
538     )->hri_dump->all;
539
540     my $expect = [{
541       artist => 1,
542       cdid => 1,
543       genreid => undef,
544       single_track => undef,
545       title => "EP C",
546       tracks => [
547         {
548           cd => 1,
549           last_updated_at => undef,
550           last_updated_on => undef,
551           position => 1,
552           title => "Track1",
553           trackid => 1
554         },
555         {
556           cd => 1,
557           last_updated_at => undef,
558           last_updated_on => undef,
559           position => 1,
560           title => "Track2",
561           trackid => 2
562         },
563       ],
564       year => 2003
565     }];
566
567     is_deeply (
568       \@hri,
569       $expect,
570       'Correct set of data prefetched',
571     );
572
573   } 'complex prefetch ok';
574
575 # test sequence detection from a different schema
576   SKIP: {
577   TODO: {
578     skip ((join '',
579       'Set DBICTEST_ORA_EXTRAUSER_DSN, _USER and _PASS to a *DIFFERENT* Oracle user',
580       ' to run the cross-schema sequence detection test.'),
581     1) unless $dsn2 && $user2 && $user2 ne $user;
582
583     skip 'not detecting cross-schema sequence name when using INSERT ... RETURNING', 1
584       if $schema->storage->_use_insert_returning;
585
586     # Oracle8i Reference Release 2 (8.1.6)
587     #   http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76961/ch294.htm#993
588     # Oracle Database Reference 10g Release 2 (10.2)
589     #   http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_2107.htm#sthref1297
590     local $TODO = "On Oracle8i all_triggers view is empty, i don't yet know why..."
591       if $schema->storage->_server_info->{normalized_dbms_version} < 9;
592
593     my $schema2 = $schema->connect($dsn2, $user2, $pass2, $opt);
594     my $dbh2 = $schema2->storage->dbh;
595
596     # create identically named tables/sequences in the other schema
597     do_creates($dbh2, $q);
598
599     # grand select privileges to the 2nd user
600     $dbh->do("GRANT INSERT ON ${q}artist${q} TO " . uc $user2);
601     $dbh->do("GRANT SELECT ON ${q}artist${q} TO " . uc $user2);
602     $dbh->do("GRANT SELECT ON ${q}artist_pk_seq${q} TO " . uc $user2);
603     $dbh->do("GRANT SELECT ON ${q}artist_autoinc_seq${q} TO " . uc $user2);
604
605     # test with a fully qualified table (user1/schema prepended)
606     my $rs2 = $schema2->resultset('ArtistFQN');
607     delete $rs2->result_source->column_info('artistid')->{sequence};
608
609     lives_and {
610       my $row = $rs2->create({ name => 'From Different Schema' });
611       ok $row->artistid;
612     } 'used autoinc sequence across schemas';
613
614     # now quote the sequence name (do_creates always uses an lc name)
615     my $q_seq = $q
616       ? '"artist_pk_seq"'
617       : '"ARTIST_PK_SEQ"'
618     ;
619     delete $rs2->result_source->column_info('artistid')->{sequence};
620     $dbh->do(qq{
621       CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
622       BEFORE INSERT ON ${q}artist${q}
623       FOR EACH ROW
624       BEGIN
625         IF :new.${q}artistid${q} IS NULL THEN
626           SELECT $q_seq.nextval
627           INTO :new.${q}artistid${q}
628           FROM DUAL;
629         END IF;
630       END;
631     });
632
633
634     lives_and {
635       my $row = $rs2->create({ name => 'From Different Schema With Quoted Sequence' });
636       ok $row->artistid;
637     } 'used quoted autoinc sequence across schemas';
638
639     is_deeply $rs2->result_source->column_info('artistid')->{sequence},
640       \( (uc $user) . ".$q_seq"),
641       'quoted sequence name correctly extracted';
642
643     # try an insert operation on the default user2 artist
644     my $art1 = $schema->resultset('Artist');
645     my $art2 = $schema2->resultset('Artist');
646     my $art1_count = $art1->count || 0;
647     my $art2_count = $art2->count;
648
649     is( $art2_count, 0, 'No artists created yet in second schema' );
650
651     delete $art2->result_source->column_info('artistid')->{sequence};
652     my $new_art = $art2->create({ name => '2nd best' });
653
654     is ($art1->count, $art1_count, 'No new rows in main schema');
655     is ($art2->count, 1, 'One artist create in 2nd schema');
656
657     is( $new_art->artistid, 1, 'Expected first PK' );
658
659     do_clean ($dbh2);
660   }}
661
662   do_clean ($dbh);
663 }
664
665 done_testing;
666
667 sub do_creates {
668   my ($dbh, $q) = @_;
669
670   do_clean($dbh);
671
672   $dbh->do("CREATE SEQUENCE ${q}artist_autoinc_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
673   $dbh->do("CREATE SEQUENCE ${q}artist_pk_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
674   $dbh->do("CREATE SEQUENCE ${q}cd_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
675   $dbh->do("CREATE SEQUENCE ${q}track_seq${q} START WITH 1 MAXVALUE 999999 MINVALUE 0");
676
677   $dbh->do("CREATE SEQUENCE ${q}nonpkid_seq${q} START WITH 20 MAXVALUE 999999 MINVALUE 0");
678   # this one is always quoted as per manually specified sequence =>
679   $dbh->do('CREATE SEQUENCE "pkid1_seq" START WITH 1 MAXVALUE 999999 MINVALUE 0');
680   # this one is always unquoted as per manually specified sequence =>
681   $dbh->do("CREATE SEQUENCE pkid2_seq START WITH 10 MAXVALUE 999999 MINVALUE 0");
682
683   $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))");
684   $dbh->do("ALTER TABLE ${q}artist${q} ADD (CONSTRAINT ${q}artist_pk${q} PRIMARY KEY (${q}artistid${q}))");
685
686   $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))");
687   $dbh->do("ALTER TABLE ${q}sequence_test${q} ADD (CONSTRAINT ${q}sequence_test_constraint${q} PRIMARY KEY (${q}pkid1${q}, ${q}pkid2${q}))");
688
689   # table cd will be unquoted => Oracle will see it as uppercase
690   $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))");
691   $dbh->do("ALTER TABLE cd ADD (CONSTRAINT ${q}cd_pk${q} PRIMARY KEY (${q}cdid${q}))");
692
693   $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)");
694   $dbh->do("ALTER TABLE ${q}track${q} ADD (CONSTRAINT ${q}track_pk${q} PRIMARY KEY (${q}trackid${q}))");
695
696   $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)");
697
698   $dbh->do(qq{
699     CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_auto${q}
700     BEFORE INSERT ON ${q}artist${q}
701     FOR EACH ROW
702     BEGIN
703       IF :new.${q}autoinc_col${q} IS NULL THEN
704         SELECT ${q}artist_autoinc_seq${q}.nextval
705         INTO :new.${q}autoinc_col${q}
706         FROM DUAL;
707       END IF;
708     END;
709   });
710
711   $dbh->do(qq{
712     CREATE OR REPLACE TRIGGER ${q}artist_insert_trg_pk${q}
713     BEFORE INSERT ON ${q}artist${q}
714     FOR EACH ROW
715     BEGIN
716       IF :new.${q}artistid${q} IS NULL THEN
717         SELECT ${q}artist_pk_seq${q}.nextval
718         INTO :new.${q}artistid${q}
719         FROM DUAL;
720       END IF;
721     END;
722   });
723
724   $dbh->do(qq{
725     CREATE OR REPLACE TRIGGER ${q}cd_insert_trg${q}
726     BEFORE INSERT OR UPDATE ON cd
727     FOR EACH ROW
728
729     DECLARE
730     tmpVar NUMBER;
731
732     BEGIN
733       tmpVar := 0;
734
735       IF :new.${q}cdid${q} IS NULL THEN
736         SELECT ${q}cd_seq${q}.nextval
737         INTO tmpVar
738         FROM dual;
739
740         :new.${q}cdid${q} := tmpVar;
741       END IF;
742     END;
743   });
744
745   $dbh->do(qq{
746     CREATE OR REPLACE TRIGGER ${q}track_insert_trg${q}
747     BEFORE INSERT ON ${q}track${q}
748     FOR EACH ROW
749     BEGIN
750       IF :new.${q}trackid${q} IS NULL THEN
751         SELECT ${q}track_seq${q}.nextval
752         INTO :new.${q}trackid${q}
753         FROM DUAL;
754       END IF;
755     END;
756   });
757 }
758
759 # clean up our mess
760 sub do_clean {
761
762   my $dbh = shift || return;
763
764   for my $q ('', '"') {
765     my @clean = (
766       "DROP TRIGGER ${q}track_insert_trg${q}",
767       "DROP TRIGGER ${q}cd_insert_trg${q}",
768       "DROP TRIGGER ${q}artist_insert_trg_auto${q}",
769       "DROP TRIGGER ${q}artist_insert_trg_pk${q}",
770       "DROP SEQUENCE ${q}nonpkid_seq${q}",
771       "DROP SEQUENCE ${q}pkid2_seq${q}",
772       "DROP SEQUENCE ${q}pkid1_seq${q}",
773       "DROP SEQUENCE ${q}track_seq${q}",
774       "DROP SEQUENCE ${q}cd_seq${q}",
775       "DROP SEQUENCE ${q}artist_autoinc_seq${q}",
776       "DROP SEQUENCE ${q}artist_pk_seq${q}",
777       "DROP TABLE ${q}bindtype_test${q}",
778       "DROP TABLE ${q}sequence_test${q}",
779       "DROP TABLE ${q}track${q}",
780       "DROP TABLE ${q}cd${q}",
781       "DROP TABLE ${q}artist${q}",
782     );
783     eval { $dbh -> do ($_) } for @clean;
784   }
785 }
786
787 END {
788   for ($dbh, $dbh2) {
789     next unless $_;
790     local $SIG{__WARN__} = sub {};
791     do_clean($_);
792     $_->disconnect;
793   }
794 }