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