160d885f5224555a762b7fdf31b676a686f567d8
[dbsrgits/DBIx-Class-Schema-Loader.git] / t / 10_05ora_common.t
1 use strict;
2 use warnings;
3 use Test::More;
4 use Test::Exception;
5 use DBIx::Class::Optional::Dependencies;
6 use DBIx::Class::Schema::Loader 'make_schema_at';
7 use DBIx::Class::Schema::Loader::Utils qw/slurp_file split_name/;
8 use Try::Tiny;
9 use File::Path 'rmtree';
10 use String::ToIdentifier::EN::Unicode 'to_identifier';
11 use namespace::clean;
12
13 use lib qw(t/lib);
14 use dbixcsl_common_tests ();
15 use dbixcsl_test_dir '$tdir';
16
17 use constant EXTRA_DUMP_DIR => "$tdir/ora_extra_dump";
18
19 my $dsn      = $ENV{DBICTEST_ORA_DSN} || '';
20 my $user     = $ENV{DBICTEST_ORA_USER} || '';
21 my $password = $ENV{DBICTEST_ORA_PASS} || '';
22
23 my ($schema, $extra_schema); # for cleanup in END for extra tests
24
25 my $auto_inc_cb = sub {
26     my ($table, $col) = @_;
27     return (
28         qq{ CREATE SEQUENCE ${table}_${col}_seq START WITH 1 INCREMENT BY 1},
29         qq{
30             CREATE OR REPLACE TRIGGER ${table}_${col}_trg
31             BEFORE INSERT ON ${table}
32             FOR EACH ROW
33             BEGIN
34                 SELECT ${table}_${col}_seq.nextval INTO :NEW.${col} FROM dual;
35             END;
36         }
37     );
38 };
39
40 my $auto_inc_drop_cb = sub {
41     my ($table, $col) = @_;
42     return qq{ DROP SEQUENCE ${table}_${col}_seq };
43 };
44
45 my $tester = dbixcsl_common_tests->new(
46     vendor      => 'Oracle',
47     auto_inc_pk => 'INTEGER NOT NULL PRIMARY KEY',
48     auto_inc_cb => $auto_inc_cb,
49     auto_inc_drop_cb => $auto_inc_drop_cb,
50     preserve_case_mode_is_exclusive => 1,
51     quote_char                      => '"',
52     default_is_deferrable => 0,
53     default_on_delete_clause => 'NO ACTION',
54     default_on_update_clause => 'NO ACTION',
55     dsn         => $dsn,
56     user        => $user,
57     password    => $password,
58     data_types  => {
59         # From:
60         # http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements001.htm#i54330
61         #
62         # These tests require at least Oracle 9.2, because of the VARCHAR to
63         # VARCHAR2 casting.
64         #
65         # Character Types
66         'char'         => { data_type => 'char',      size => 1  },
67         'char(11)'     => { data_type => 'char',      size => 11 },
68         'nchar'        => { data_type => 'nchar',     size => 1  },
69         'national character'
70                        => { data_type => 'nchar',     size => 1  },
71         'nchar(11)'    => { data_type => 'nchar',     size => 11 },
72         'national character(11)'
73                        => { data_type => 'nchar',     size => 11 },
74         'varchar(20)'  => { data_type => 'varchar2',  size => 20 },
75         'varchar2(20)' => { data_type => 'varchar2',  size => 20 },
76         'nvarchar2(20)'=> { data_type => 'nvarchar2', size => 20 },
77         'national character varying(20)'
78                        => { data_type => 'nvarchar2', size => 20 },
79
80         # Numeric Types
81         #
82         # integer/decimal/numeric is alised to NUMBER
83         #
84         'integer'      => { data_type => 'integer', original => { data_type => 'number', size => [38,0] } },
85         'int'          => { data_type => 'integer', original => { data_type => 'number', size => [38,0] } },
86         'smallint'     => { data_type => 'integer', original => { data_type => 'number', size => [38,0] } },
87
88         # very long DEFAULT throws an ORA-24345
89         "number(15) DEFAULT to_number(decode(substrb(userenv('CLIENT_INFO'),1,1),' ',null,substrb(userenv('CLIENT_INFO'),1,10)))" => {
90             data_type => 'numeric', size => [15,0], original => { data_type => 'number' },
91             default_value => \"to_number(decode(substrb(userenv('CLIENT_INFO'),1,1),' ',null,substrb(userenv('CLIENT_INFO'),1,10)))"
92         },
93
94         'decimal'      => { data_type => 'integer', original => { data_type => 'number', size => [38,0] } },
95         'dec'          => { data_type => 'integer', original => { data_type => 'number', size => [38,0] } },
96         'numeric'      => { data_type => 'integer', original => { data_type => 'number', size => [38,0] } },
97
98         'decimal(3)'   => { data_type => 'numeric', size => [3,0], original => { data_type => 'number' } },
99         'dec(3)'       => { data_type => 'numeric', size => [3,0], original => { data_type => 'number' } },
100         'numeric(3)'   => { data_type => 'numeric', size => [3,0], original => { data_type => 'number' } },
101
102         'decimal(3,3)' => { data_type => 'numeric', size => [3,3], original => { data_type => 'number' } },
103         'dec(3,3)'     => { data_type => 'numeric', size => [3,3], original => { data_type => 'number' } },
104         'numeric(3,3)' => { data_type => 'numeric', size => [3,3], original => { data_type => 'number' } },
105
106         'binary_float'  => { data_type => 'real',             original => { data_type => 'binary_float'  } },
107         'binary_double' => { data_type => 'double precision', original => { data_type => 'binary_double' } },
108
109         # these are not mentioned in the summary chart, must be aliased
110         real            => { data_type => 'real',             original => { data_type => 'float', size => 63  } },
111         'float(63)'     => { data_type => 'real',             original => { data_type => 'float', size => 63  } },
112         'float(64)'     => { data_type => 'double precision', original => { data_type => 'float', size => 64  } },
113         'float(126)'    => { data_type => 'double precision', original => { data_type => 'float', size => 126 } },
114         float           => { data_type => 'double precision', original => { data_type => 'float', size => 126 } },
115
116         # Blob Types
117         'raw(50)'      => { data_type => 'raw', size => 50 },
118         'clob'         => { data_type => 'clob' },
119         'nclob'        => { data_type => 'nclob' },
120         'blob'         => { data_type => 'blob' },
121         'bfile'        => { data_type => 'bfile' },
122         'long'         => { data_type => 'long' },
123         'long raw'     => { data_type => 'long raw' },
124
125         # Datetime Types
126         'date'         => { data_type => 'datetime', original => { data_type => 'date' } },
127         'date default sysdate'
128                        => { data_type => 'datetime', default_value => \'current_timestamp',
129                             original  => { data_type => 'date', default_value => \'sysdate' } },
130         'timestamp'    => { data_type => 'timestamp' },
131         'timestamp default current_timestamp'
132                        => { data_type => 'timestamp', default_value => \'current_timestamp' },
133         'timestamp(3)' => { data_type => 'timestamp', size => 3 },
134         'timestamp with time zone'
135                        => { data_type => 'timestamp with time zone' },
136         'timestamp(3) with time zone'
137                        => { data_type => 'timestamp with time zone', size => 3 },
138         'timestamp with local time zone'
139                        => { data_type => 'timestamp with local time zone' },
140         'timestamp(3) with local time zone'
141                        => { data_type => 'timestamp with local time zone', size => 3 },
142         'interval year to month'
143                        => { data_type => 'interval year to month' },
144         'interval year(3) to month'
145                        => { data_type => 'interval year to month', size => 3 },
146         'interval day to second'
147                        => { data_type => 'interval day to second' },
148         'interval day(3) to second'
149                        => { data_type => 'interval day to second', size => [3,6] },
150         'interval day to second(3)'
151                        => { data_type => 'interval day to second', size => [2,3] },
152         'interval day(3) to second(3)'
153                        => { data_type => 'interval day to second', size => [3,3] },
154
155         # Other Types
156         'rowid'        => { data_type => 'rowid' },
157         'urowid'       => { data_type => 'urowid' },
158         'urowid(3333)' => { data_type => 'urowid', size => 3333 },
159     },
160     extra => {
161         create => [
162             q{
163                 CREATE TABLE oracle_loader_test1 (
164                     id NUMBER(11),
165                     value VARCHAR2(100)
166                 )
167             },
168             q{ COMMENT ON TABLE oracle_loader_test1 IS 'oracle_loader_test1 table comment' },
169             q{ COMMENT ON COLUMN oracle_loader_test1.value IS 'oracle_loader_test1.value column comment' },
170             # 4 through 8 are used for the multi-schema tests
171             q{
172                 create table oracle_loader_test9 (
173                     id int primary key
174                 )
175             },
176             q{
177                 create table oracle_loader_test10 (
178                     id int primary key,
179                     nine_id int,
180                     foreign key (nine_id) references oracle_loader_test9(id)
181                         on delete set null deferrable
182                 )
183             },
184             q{
185                 create table oracle_loader_test11 (
186                     id int primary key disable,
187                     ten_id int unique disable,
188                     foreign key (ten_id) references oracle_loader_test10(id) disable
189                 )
190             },
191             $auto_inc_cb->('oracle_loader_test11', 'id'),
192             'alter trigger oracle_loader_test11_id_trg disable',
193         ],
194         drop  => [qw/oracle_loader_test1 oracle_loader_test9 oracle_loader_test10 oracle_loader_test11/],
195         count => 10 + 31 * 2,  # basic + cross-schema * 2
196         run   => sub {
197             my ($monikers, $classes);
198             ($schema, $monikers, $classes) = @_;
199
200             SKIP: {
201                 if (my $source = $monikers->{loader_test1s}) {
202                     is $schema->source($source)->column_info('id')->{sequence},
203                         'loader_test1s_id_seq',
204                         'Oracle sequence detection';
205                 }
206                 else {
207                     skip 'not running common tests', 1;
208                 }
209             }
210
211             my $class = $classes->{oracle_loader_test1};
212
213             my $filename = $schema->loader->get_dump_filename($class);
214             my $code = slurp_file $filename;
215
216             like $code, qr/^=head1 NAME\n\n^$class - oracle_loader_test1 table comment\n\n^=cut\n/m,
217                 'table comment';
218
219             like $code, qr/^=head2 value\n\n(.+:.+\n)+\noracle_loader_test1\.value column comment\n\n/m,
220                 'column comment and attrs';
221
222             # test on delete/update fk clause introspection
223             ok ((my $rel_info = $schema->source('OracleLoaderTest10')->relationship_info('nine')),
224                 'got rel info');
225
226             is $rel_info->{attrs}{on_delete}, 'SET NULL',
227                 'ON DELETE clause introspected correctly';
228
229             is $rel_info->{attrs}{on_update}, 'NO ACTION',
230                 'ON UPDATE clause set to NO ACTION by default';
231
232             is $rel_info->{attrs}{is_deferrable}, 1,
233                 'DEFERRABLE clause introspected correctly';
234
235             my $source11 = $schema->source('OracleLoaderTest11');
236
237             # DBD::Oracle < 1.76 doesn't filter out disabled primary keys
238             my $uniqs = eval { DBD::Oracle->VERSION('1.76') } ? [] : ['primary'];
239             is_deeply [keys %{{$source11->unique_constraints}}], $uniqs,
240                 'Disabled unique constraints not loaded';
241
242             ok !$source11->relationship_info('ten'),
243                 'Disabled FK not loaded';
244
245             ok !$source11->column_info('id')->{is_auto_increment},
246                 'Disabled autoinc trigger not loaded';
247
248             SKIP: {
249                 skip 'Set the DBICTEST_ORA_EXTRAUSER_DSN, _USER and _PASS environment variables to run the cross-schema relationship tests', 31 * 2
250                     unless $ENV{DBICTEST_ORA_EXTRAUSER_DSN};
251
252                 $extra_schema = $schema->clone;
253                 $extra_schema->connection(@ENV{map "DBICTEST_ORA_EXTRAUSER_$_",
254                     qw/DSN USER PASS/
255                 });
256
257                 my $dbh1 = $schema->storage->dbh;
258                 my $dbh2 = $extra_schema->storage->dbh;
259
260                 my ($schema1) = $dbh1->selectrow_array('SELECT USER FROM DUAL');
261                 my ($schema2) = $dbh2->selectrow_array('SELECT USER FROM DUAL');
262
263                 $dbh1->do(<<'EOF');
264                     CREATE TABLE oracle_loader_test4 (
265                         id INT NOT NULL PRIMARY KEY,
266                         value VARCHAR(100)
267                     )
268 EOF
269
270                 $dbh1->do($_) for $auto_inc_cb->(lc "${schema1}.oracle_loader_test4", 'id');
271
272                 $dbh1->do("GRANT ALL ON oracle_loader_test4 TO $schema2");
273                 $dbh1->do("GRANT ALL ON oracle_loader_test4_id_seq TO $schema2");
274
275                 $dbh1->do(<<"EOF");
276                     CREATE TABLE oracle_loader_test5 (
277                         id INT NOT NULL PRIMARY KEY,
278                         value VARCHAR(100),
279                         four_id INT REFERENCES ${schema1}.oracle_loader_test4 (id),
280                         CONSTRAINT ora_loader5_uniq UNIQUE (four_id)
281                     )
282 EOF
283                 $dbh1->do($_) for $auto_inc_cb->('oracle_loader_test5', 'id');
284                 $dbh1->do("GRANT ALL ON oracle_loader_test5 TO $schema2");
285                 $dbh1->do("GRANT ALL ON oracle_loader_test5_id_seq TO $schema2");
286
287                 $dbh2->do(<<"EOF");
288                     CREATE TABLE oracle_loader_test5 (
289                         pk INT NOT NULL PRIMARY KEY,
290                         value VARCHAR(100),
291                         four_id INT REFERENCES ${schema1}.oracle_loader_test4 (id),
292                         CONSTRAINT ora_loader5_uniq UNIQUE (four_id)
293                     )
294 EOF
295                 $dbh2->do($_) for $auto_inc_cb->('oracle_loader_test5', 'pk');
296                 $dbh2->do("GRANT ALL ON oracle_loader_test5 TO $schema1");
297                 $dbh2->do("GRANT ALL ON oracle_loader_test5_pk_seq TO $schema1");
298
299                 $dbh2->do(<<"EOF");
300                     CREATE TABLE oracle_loader_test6 (
301                         id INT NOT NULL PRIMARY KEY,
302                         value VARCHAR(100),
303                         oracle_loader_test4_id INT REFERENCES ${schema1}.oracle_loader_test4 (id)
304                     )
305 EOF
306                 $dbh2->do($_) for $auto_inc_cb->('oracle_loader_test6', 'id');
307                 $dbh2->do("GRANT ALL ON oracle_loader_test6 to $schema1");
308                 $dbh2->do("GRANT ALL ON oracle_loader_test6_id_seq TO $schema1");
309
310                 $dbh2->do(<<"EOF");
311                     CREATE TABLE oracle_loader_test7 (
312                         id INT NOT NULL PRIMARY KEY,
313                         value VARCHAR(100),
314                         six_id INT UNIQUE REFERENCES ${schema2}.oracle_loader_test6 (id)
315                     )
316 EOF
317                 $dbh2->do($_) for $auto_inc_cb->('oracle_loader_test7', 'id');
318                 $dbh2->do("GRANT ALL ON oracle_loader_test7 to $schema1");
319                 $dbh2->do("GRANT ALL ON oracle_loader_test7_id_seq TO $schema1");
320
321                 $dbh1->do(<<"EOF");
322                     CREATE TABLE oracle_loader_test8 (
323                         id INT NOT NULL PRIMARY KEY,
324                         value VARCHAR(100),
325                         oracle_loader_test7_id INT REFERENCES ${schema2}.oracle_loader_test7 (id)
326                     )
327 EOF
328                 $dbh1->do($_) for $auto_inc_cb->('oracle_loader_test8', 'id');
329                 $dbh1->do("GRANT ALL ON oracle_loader_test8 to $schema2");
330                 $dbh1->do("GRANT ALL ON oracle_loader_test8_id_seq TO $schema2");
331
332                 # We add schema to moniker_parts, so make a monikers hash for
333                 # the tests, of the form schemanum.tablenum
334                 my $schema1_moniker = join '', map ucfirst lc, split_name to_identifier $schema1;
335                 my $schema2_moniker = join '', map ucfirst lc, split_name to_identifier $schema2;
336
337                 my %monikers;
338                 $monikers{'1.5'} = $schema1_moniker . 'OracleLoaderTest5';
339                 $monikers{'2.5'} = $schema2_moniker . 'OracleLoaderTest5';
340
341                 foreach my $db_schema ([$schema1, $schema2], '%') {
342                     lives_and {
343                         rmtree EXTRA_DUMP_DIR;
344
345                         my @warns;
346                         local $SIG{__WARN__} = sub {
347                             push @warns, $_[0] unless $_[0] =~ /\bcollides\b/;
348                         };
349
350                         make_schema_at(
351                             'OracleMultiSchema',
352                             {
353                                 naming => 'current',
354                                 db_schema => $db_schema,
355                                 dump_directory => EXTRA_DUMP_DIR,
356                                 quiet => 1,
357                             },
358                             [ $dsn, $user, $password ],
359                         );
360
361                         diag join "\n", @warns if @warns;
362
363                         is @warns, 0;
364                     } qq{dumped schema for "$schema1" and "$schema2" schemas with no warnings};
365
366                     my ($test_schema, $rsrc, $rs, $row, %uniqs, $rel_info);
367
368                     lives_and {
369                         ok $test_schema = OracleMultiSchema->connect($dsn, $user, $password);
370                     } 'connected test schema';
371
372                     lives_and {
373                         ok $rsrc = $test_schema->source('OracleLoaderTest4');
374                     } 'got source for table in schema1';
375
376                     is try { $rsrc->column_info('id')->{is_auto_increment} }, 1,
377                         'column in schema1';
378
379                     is try { $rsrc->column_info('id')->{sequence} }, lc "${schema1}.oracle_loader_test4_id_seq",
380                         'sequence in schema1';
381
382                     is try { $rsrc->column_info('value')->{data_type} }, 'varchar2',
383                         'column in schema1';
384
385                     is try { $rsrc->column_info('value')->{size} }, 100,
386                         'column in schema1';
387
388                     lives_and {
389                         ok $rs = $test_schema->resultset('OracleLoaderTest4');
390                     } 'got resultset for table in schema1';
391
392                     lives_and {
393                         ok $row = $rs->create({ value => 'foo' });
394                     } 'executed SQL on table in schema1';
395
396                     my $schema1_identifier = join '_', map lc, split_name to_identifier $schema1;
397
398                     $rel_info = try { $rsrc->relationship_info(
399                         $schema1_identifier . '_oracle_loader_test5'
400                     ) };
401
402                     is_deeply $rel_info->{cond}, {
403                         'foreign.four_id' => 'self.id'
404                     }, 'relationship in schema1';
405
406                     is $rel_info->{attrs}{accessor}, 'single',
407                         'relationship in schema1';
408
409                     is $rel_info->{attrs}{join_type}, 'LEFT',
410                         'relationship in schema1';
411
412                     lives_and {
413                         ok $rsrc = $test_schema->source($monikers{'1.5'});
414                     } 'got source for table in schema1';
415
416                     %uniqs = try { $rsrc->unique_constraints };
417
418                     is keys %uniqs, 2,
419                         'got unique and primary constraint in schema1';
420
421                     delete $uniqs{primary};
422
423                     is_deeply ((values %uniqs)[0], ['four_id'],
424                         'correct unique constraint in schema1');
425
426                     lives_and {
427                         ok $rsrc = $test_schema->source('OracleLoaderTest6');
428                     } 'got source for table in schema2';
429
430                     is try { $rsrc->column_info('id')->{is_auto_increment} }, 1,
431                         'column in schema2 introspected correctly';
432
433                     is try { $rsrc->column_info('value')->{data_type} }, 'varchar2',
434                         'column in schema2 introspected correctly';
435
436                     is try { $rsrc->column_info('value')->{size} }, 100,
437                         'column in schema2 introspected correctly';
438
439                     lives_and {
440                         ok $rs = $test_schema->resultset('OracleLoaderTest6');
441                     } 'got resultset for table in schema2';
442
443                     lives_and {
444                         ok $row = $rs->create({ value => 'foo' });
445                     } 'executed SQL on table in schema2';
446
447                     $rel_info = try { $rsrc->relationship_info('oracle_loader_test7') };
448
449                     is_deeply $rel_info->{cond}, {
450                         'foreign.six_id' => 'self.id'
451                     }, 'relationship in schema2';
452
453                     is $rel_info->{attrs}{accessor}, 'single',
454                         'relationship in schema2';
455
456                     is $rel_info->{attrs}{join_type}, 'LEFT',
457                         'relationship in schema2';
458
459                     lives_and {
460                         ok $rsrc = $test_schema->source('OracleLoaderTest7');
461                     } 'got source for table in schema2';
462
463                     %uniqs = try { $rsrc->unique_constraints };
464
465                     is keys %uniqs, 2,
466                         'got unique and primary constraint in schema2';
467
468                     delete $uniqs{primary};
469
470                     is_deeply ((values %uniqs)[0], ['six_id'],
471                         'correct unique constraint in schema2');
472
473                     lives_and {
474                         ok $test_schema->source('OracleLoaderTest6')
475                             ->has_relationship('oracle_loader_test4');
476                     } 'cross-schema relationship in multi-db_schema';
477
478                     lives_and {
479                         ok $test_schema->source('OracleLoaderTest4')
480                             ->has_relationship('oracle_loader_test6s');
481                     } 'cross-schema relationship in multi-db_schema';
482
483                     lives_and {
484                         ok $test_schema->source('OracleLoaderTest8')
485                             ->has_relationship('oracle_loader_test7');
486                     } 'cross-schema relationship in multi-db_schema';
487
488                     lives_and {
489                         ok $test_schema->source('OracleLoaderTest7')
490                             ->has_relationship('oracle_loader_test8s');
491                     } 'cross-schema relationship in multi-db_schema';
492                 }
493             }
494         },
495     },
496 );
497
498 if( !$dsn || !$user ) {
499     $tester->skip_tests('You need to set the DBICTEST_ORA_DSN, _USER, and _PASS environment variables');
500 }
501 elsif (!DBIx::Class::Optional::Dependencies->req_ok_for ('rdbms_oracle')) {
502     $tester->skip_tests('You need to install ' . DBIx::Class::Optional::Dependencies->req_missing_for ('rdbms_oracle'));
503 }
504 else {
505     $tester->run_tests();
506 }
507
508 END {
509     if (not $ENV{SCHEMA_LOADER_TESTS_NOCLEANUP}) {
510         if (my $dbh1 = try { $schema->storage->dbh }) {
511             $dbh1->do($_) for $auto_inc_drop_cb->('oracle_loader_test11','id');
512
513             if (my $dbh2 = try { $extra_schema->storage->dbh }) {
514
515                 try {
516                     $dbh1->do($_) for $auto_inc_drop_cb->('oracle_loader_test8', 'id');
517                     $dbh2->do($_) for $auto_inc_drop_cb->('oracle_loader_test7', 'id');
518                     $dbh2->do($_) for $auto_inc_drop_cb->('oracle_loader_test6', 'id');
519                     $dbh2->do($_) for $auto_inc_drop_cb->('oracle_loader_test5', 'pk');
520                     $dbh1->do($_) for $auto_inc_drop_cb->('oracle_loader_test5', 'id');
521                     $dbh1->do($_) for $auto_inc_drop_cb->('oracle_loader_test4', 'id');
522                 }
523                 catch {
524                     die "Error dropping sequences for cross-schema test tables: $_";
525                 };
526
527                 try {
528                     $dbh1->do('DROP TABLE oracle_loader_test8');
529                     $dbh2->do('DROP TABLE oracle_loader_test7');
530                     $dbh2->do('DROP TABLE oracle_loader_test6');
531                     $dbh2->do('DROP TABLE oracle_loader_test5');
532                     $dbh1->do('DROP TABLE oracle_loader_test5');
533                     $dbh1->do('DROP TABLE oracle_loader_test4');
534                 }
535                 catch {
536                     die "Error dropping cross-schema test tables: $_";
537                 };
538             }
539         }
540         rmtree EXTRA_DUMP_DIR;
541     }
542 }
543 # vim:et sw=4 sts=4 tw=0: