2cb7480e135bc0b3988fecf9a5d5c4fd2f2b4980
[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}_trigger
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         ],
185         drop  => [qw/oracle_loader_test1 oracle_loader_test9 oracle_loader_test10/],
186         count => 7 + 31 * 2,
187         run   => sub {
188             my ($monikers, $classes);
189             ($schema, $monikers, $classes) = @_;
190
191             SKIP: {
192                 if (my $source = $monikers->{loader_test1s}) {
193                     is $schema->source($source)->column_info('id')->{sequence},
194                         'loader_test1s_id_seq',
195                         'Oracle sequence detection';
196                 }
197                 else {
198                     skip 'not running common tests', 1;
199                 }
200             }
201
202             my $class = $classes->{oracle_loader_test1};
203
204             my $filename = $schema->loader->get_dump_filename($class);
205             my $code = slurp_file $filename;
206
207             like $code, qr/^=head1 NAME\n\n^$class - oracle_loader_test1 table comment\n\n^=cut\n/m,
208                 'table comment';
209
210             like $code, qr/^=head2 value\n\n(.+:.+\n)+\noracle_loader_test1\.value column comment\n\n/m,
211                 'column comment and attrs';
212
213             # test on delete/update fk clause introspection
214             ok ((my $rel_info = $schema->source('OracleLoaderTest10')->relationship_info('nine')),
215                 'got rel info');
216
217             is $rel_info->{attrs}{on_delete}, 'SET NULL',
218                 'ON DELETE clause introspected correctly';
219
220             is $rel_info->{attrs}{on_update}, 'NO ACTION',
221                 'ON UPDATE clause set to NO ACTION by default';
222
223             is $rel_info->{attrs}{is_deferrable}, 1,
224                 'DEFERRABLE clause introspected correctly';
225
226             SKIP: {
227                 skip 'Set the DBICTEST_ORA_EXTRAUSER_DSN, _USER and _PASS environment variables to run the cross-schema relationship tests', 31 * 2
228                     unless $ENV{DBICTEST_ORA_EXTRAUSER_DSN};
229
230                 $extra_schema = $schema->clone;
231                 $extra_schema->connection(@ENV{map "DBICTEST_ORA_EXTRAUSER_$_",
232                     qw/DSN USER PASS/
233                 });
234
235                 my $dbh1 = $schema->storage->dbh;
236                 my $dbh2 = $extra_schema->storage->dbh;
237
238                 my ($schema1) = $dbh1->selectrow_array('SELECT USER FROM DUAL');
239                 my ($schema2) = $dbh2->selectrow_array('SELECT USER FROM DUAL');
240
241                 $dbh1->do(<<'EOF');
242                     CREATE TABLE oracle_loader_test4 (
243                         id INT NOT NULL PRIMARY KEY,
244                         value VARCHAR(100)
245                     )
246 EOF
247
248                 $dbh1->do($_) for $auto_inc_cb->(lc "${schema1}.oracle_loader_test4", 'id');
249
250                 $dbh1->do("GRANT ALL ON oracle_loader_test4 TO $schema2");
251                 $dbh1->do("GRANT ALL ON oracle_loader_test4_id_seq TO $schema2");
252
253                 $dbh1->do(<<"EOF");
254                     CREATE TABLE oracle_loader_test5 (
255                         id INT NOT NULL PRIMARY KEY,
256                         value VARCHAR(100),
257                         four_id INT REFERENCES ${schema1}.oracle_loader_test4 (id),
258                         CONSTRAINT ora_loader5_uniq UNIQUE (four_id)
259                     )
260 EOF
261                 $dbh1->do($_) for $auto_inc_cb->('oracle_loader_test5', 'id');
262                 $dbh1->do("GRANT ALL ON oracle_loader_test5 TO $schema2");
263                 $dbh1->do("GRANT ALL ON oracle_loader_test5_id_seq TO $schema2");
264
265                 $dbh2->do(<<"EOF");
266                     CREATE TABLE oracle_loader_test5 (
267                         pk INT NOT NULL PRIMARY KEY,
268                         value VARCHAR(100),
269                         four_id INT REFERENCES ${schema1}.oracle_loader_test4 (id),
270                         CONSTRAINT ora_loader5_uniq UNIQUE (four_id)
271                     )
272 EOF
273                 $dbh2->do($_) for $auto_inc_cb->('oracle_loader_test5', 'pk');
274                 $dbh2->do("GRANT ALL ON oracle_loader_test5 TO $schema1");
275                 $dbh2->do("GRANT ALL ON oracle_loader_test5_pk_seq TO $schema1");
276
277                 $dbh2->do(<<"EOF");
278                     CREATE TABLE oracle_loader_test6 (
279                         id INT NOT NULL PRIMARY KEY,
280                         value VARCHAR(100),
281                         oracle_loader_test4_id INT REFERENCES ${schema1}.oracle_loader_test4 (id)
282                     )
283 EOF
284                 $dbh2->do($_) for $auto_inc_cb->('oracle_loader_test6', 'id');
285                 $dbh2->do("GRANT ALL ON oracle_loader_test6 to $schema1");
286                 $dbh2->do("GRANT ALL ON oracle_loader_test6_id_seq TO $schema1");
287
288                 $dbh2->do(<<"EOF");
289                     CREATE TABLE oracle_loader_test7 (
290                         id INT NOT NULL PRIMARY KEY,
291                         value VARCHAR(100),
292                         six_id INT UNIQUE REFERENCES ${schema2}.oracle_loader_test6 (id)
293                     )
294 EOF
295                 $dbh2->do($_) for $auto_inc_cb->('oracle_loader_test7', 'id');
296                 $dbh2->do("GRANT ALL ON oracle_loader_test7 to $schema1");
297                 $dbh2->do("GRANT ALL ON oracle_loader_test7_id_seq TO $schema1");
298
299                 $dbh1->do(<<"EOF");
300                     CREATE TABLE oracle_loader_test8 (
301                         id INT NOT NULL PRIMARY KEY,
302                         value VARCHAR(100),
303                         oracle_loader_test7_id INT REFERENCES ${schema2}.oracle_loader_test7 (id)
304                     )
305 EOF
306                 $dbh1->do($_) for $auto_inc_cb->('oracle_loader_test8', 'id');
307                 $dbh1->do("GRANT ALL ON oracle_loader_test8 to $schema2");
308                 $dbh1->do("GRANT ALL ON oracle_loader_test8_id_seq TO $schema2");
309
310                 # We add schema to moniker_parts, so make a monikers hash for
311                 # the tests, of the form schemanum.tablenum
312                 my $schema1_moniker = join '', map ucfirst lc, split_name to_identifier $schema1;
313                 my $schema2_moniker = join '', map ucfirst lc, split_name to_identifier $schema2;
314
315                 my %monikers;
316                 $monikers{'1.5'} = $schema1_moniker . 'OracleLoaderTest5';
317                 $monikers{'2.5'} = $schema2_moniker . 'OracleLoaderTest5';
318
319                 foreach my $db_schema ([$schema1, $schema2], '%') {
320                     lives_and {
321                         rmtree EXTRA_DUMP_DIR;
322
323                         my @warns;
324                         local $SIG{__WARN__} = sub {
325                             push @warns, $_[0] unless $_[0] =~ /\bcollides\b/;
326                         };
327
328                         make_schema_at(
329                             'OracleMultiSchema',
330                             {
331                                 naming => 'current',
332                                 db_schema => $db_schema,
333                                 dump_directory => EXTRA_DUMP_DIR,
334                                 quiet => 1,
335                             },
336                             [ $dsn, $user, $password ],
337                         );
338
339                         diag join "\n", @warns if @warns;
340
341                         is @warns, 0;
342                     } qq{dumped schema for "$schema1" and "$schema2" schemas with no warnings};
343
344                     my ($test_schema, $rsrc, $rs, $row, %uniqs, $rel_info);
345
346                     lives_and {
347                         ok $test_schema = OracleMultiSchema->connect($dsn, $user, $password);
348                     } 'connected test schema';
349
350                     lives_and {
351                         ok $rsrc = $test_schema->source('OracleLoaderTest4');
352                     } 'got source for table in schema1';
353
354                     is try { $rsrc->column_info('id')->{is_auto_increment} }, 1,
355                         'column in schema1';
356
357                     is try { $rsrc->column_info('id')->{sequence} }, lc "${schema1}.oracle_loader_test4_id_seq",
358                         'sequence in schema1';
359
360                     is try { $rsrc->column_info('value')->{data_type} }, 'varchar2',
361                         'column in schema1';
362
363                     is try { $rsrc->column_info('value')->{size} }, 100,
364                         'column in schema1';
365
366                     lives_and {
367                         ok $rs = $test_schema->resultset('OracleLoaderTest4');
368                     } 'got resultset for table in schema1';
369
370                     lives_and {
371                         ok $row = $rs->create({ value => 'foo' });
372                     } 'executed SQL on table in schema1';
373
374                     my $schema1_identifier = join '_', map lc, split_name to_identifier $schema1;
375
376                     $rel_info = try { $rsrc->relationship_info(
377                         $schema1_identifier . '_oracle_loader_test5'
378                     ) };
379
380                     is_deeply $rel_info->{cond}, {
381                         'foreign.four_id' => 'self.id'
382                     }, 'relationship in schema1';
383
384                     is $rel_info->{attrs}{accessor}, 'single',
385                         'relationship in schema1';
386
387                     is $rel_info->{attrs}{join_type}, 'LEFT',
388                         'relationship in schema1';
389
390                     lives_and {
391                         ok $rsrc = $test_schema->source($monikers{'1.5'});
392                     } 'got source for table in schema1';
393
394                     %uniqs = try { $rsrc->unique_constraints };
395
396                     is keys %uniqs, 2,
397                         'got unique and primary constraint in schema1';
398
399                     delete $uniqs{primary};
400
401                     is_deeply ((values %uniqs)[0], ['four_id'],
402                         'correct unique constraint in schema1');
403
404                     lives_and {
405                         ok $rsrc = $test_schema->source('OracleLoaderTest6');
406                     } 'got source for table in schema2';
407
408                     is try { $rsrc->column_info('id')->{is_auto_increment} }, 1,
409                         'column in schema2 introspected correctly';
410
411                     is try { $rsrc->column_info('value')->{data_type} }, 'varchar2',
412                         'column in schema2 introspected correctly';
413
414                     is try { $rsrc->column_info('value')->{size} }, 100,
415                         'column in schema2 introspected correctly';
416
417                     lives_and {
418                         ok $rs = $test_schema->resultset('OracleLoaderTest6');
419                     } 'got resultset for table in schema2';
420
421                     lives_and {
422                         ok $row = $rs->create({ value => 'foo' });
423                     } 'executed SQL on table in schema2';
424
425                     $rel_info = try { $rsrc->relationship_info('oracle_loader_test7') };
426
427                     is_deeply $rel_info->{cond}, {
428                         'foreign.six_id' => 'self.id'
429                     }, 'relationship in schema2';
430
431                     is $rel_info->{attrs}{accessor}, 'single',
432                         'relationship in schema2';
433
434                     is $rel_info->{attrs}{join_type}, 'LEFT',
435                         'relationship in schema2';
436
437                     lives_and {
438                         ok $rsrc = $test_schema->source('OracleLoaderTest7');
439                     } 'got source for table in schema2';
440
441                     %uniqs = try { $rsrc->unique_constraints };
442
443                     is keys %uniqs, 2,
444                         'got unique and primary constraint in schema2';
445
446                     delete $uniqs{primary};
447
448                     is_deeply ((values %uniqs)[0], ['six_id'],
449                         'correct unique constraint in schema2');
450
451                     lives_and {
452                         ok $test_schema->source('OracleLoaderTest6')
453                             ->has_relationship('oracle_loader_test4');
454                     } 'cross-schema relationship in multi-db_schema';
455
456                     lives_and {
457                         ok $test_schema->source('OracleLoaderTest4')
458                             ->has_relationship('oracle_loader_test6s');
459                     } 'cross-schema relationship in multi-db_schema';
460
461                     lives_and {
462                         ok $test_schema->source('OracleLoaderTest8')
463                             ->has_relationship('oracle_loader_test7');
464                     } 'cross-schema relationship in multi-db_schema';
465
466                     lives_and {
467                         ok $test_schema->source('OracleLoaderTest7')
468                             ->has_relationship('oracle_loader_test8s');
469                     } 'cross-schema relationship in multi-db_schema';
470                 }
471             }
472         },
473     },
474 );
475
476 if( !$dsn || !$user ) {
477     $tester->skip_tests('You need to set the DBICTEST_ORA_DSN, _USER, and _PASS environment variables');
478 }
479 elsif (!DBIx::Class::Optional::Dependencies->req_ok_for ('rdbms_oracle')) {
480     $tester->skip_tests('You need to install ' . DBIx::Class::Optional::Dependencies->req_missing_for ('rdbms_oracle'));
481 }
482 else {
483     $tester->run_tests();
484 }
485
486 END {
487     if (not $ENV{SCHEMA_LOADER_TESTS_NOCLEANUP}) {
488         if (my $dbh2 = try { $extra_schema->storage->dbh }) {
489             my $dbh1 = $schema->storage->dbh;
490
491             try {
492                 $dbh1->do($_) for $auto_inc_drop_cb->('oracle_loader_test8', 'id');
493                 $dbh2->do($_) for $auto_inc_drop_cb->('oracle_loader_test7', 'id');
494                 $dbh2->do($_) for $auto_inc_drop_cb->('oracle_loader_test6', 'id');
495                 $dbh2->do($_) for $auto_inc_drop_cb->('oracle_loader_test5', 'pk');
496                 $dbh1->do($_) for $auto_inc_drop_cb->('oracle_loader_test5', 'id');
497                 $dbh1->do($_) for $auto_inc_drop_cb->('oracle_loader_test4', 'id');
498             }
499             catch {
500                 die "Error dropping sequences for cross-schema test tables: $_";
501             };
502
503             try {
504                 $dbh1->do('DROP TABLE oracle_loader_test8');
505                 $dbh2->do('DROP TABLE oracle_loader_test7');
506                 $dbh2->do('DROP TABLE oracle_loader_test6');
507                 $dbh2->do('DROP TABLE oracle_loader_test5');
508                 $dbh1->do('DROP TABLE oracle_loader_test5');
509                 $dbh1->do('DROP TABLE oracle_loader_test4');
510             }
511             catch {
512                 die "Error dropping cross-schema test tables: $_";
513             };
514         }
515
516         rmtree EXTRA_DUMP_DIR;
517     }
518 }
519 # vim:et sw=4 sts=4 tw=0: