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