Release 0.07038
[dbsrgits/DBIx-Class-Schema-Loader.git] / lib / DBIx / Class / Schema / Loader / DBI / Oracle.pm
1 package DBIx::Class::Schema::Loader::DBI::Oracle;
2
3 use strict;
4 use warnings;
5 use base 'DBIx::Class::Schema::Loader::DBI::Component::QuotedDefault';
6 use mro 'c3';
7 use Try::Tiny;
8 use DBIx::Class::Schema::Loader::Utils qw/sigwarn_silencer/;
9 use namespace::clean;
10
11 our $VERSION = '0.07038';
12
13 =head1 NAME
14
15 DBIx::Class::Schema::Loader::DBI::Oracle - DBIx::Class::Schema::Loader::DBI
16 Oracle Implementation.
17
18 =head1 DESCRIPTION
19
20 See L<DBIx::Class::Schema::Loader> and L<DBIx::Class::Schema::Loader::Base>.
21
22 =cut
23
24 sub _setup {
25     my $self = shift;
26
27     $self->next::method(@_);
28
29     my ($current_schema) = $self->dbh->selectrow_array('SELECT USER FROM DUAL');
30
31     $self->db_schema([ $current_schema ]) unless $self->db_schema;
32
33     if (@{ $self->db_schema } == 1 && $self->db_schema->[0] ne '%'
34         && lc($self->db_schema->[0]) ne lc($current_schema)) {
35         $self->dbh->do('ALTER SESSION SET current_schema=' . $self->db_schema->[0]);
36     }
37
38     if (not defined $self->preserve_case) {
39         $self->preserve_case(0);
40     }
41     elsif ($self->preserve_case) {
42         $self->schema->storage->sql_maker->quote_char('"');
43         $self->schema->storage->sql_maker->name_sep('.');
44     }
45 }
46
47 sub _build_name_sep { '.' }
48
49 sub _system_schemas {
50     my $self = shift;
51
52     # From http://www.adp-gmbh.ch/ora/misc/known_schemas.html
53
54     return ($self->next::method(@_), qw/ANONYMOUS APEX_PUBLIC_USER APEX_030200 APPQOSSYS CTXSYS DBSNMP DIP DMSYS EXFSYS LBACSYS MDDATA MDSYS MGMT_VIEW OLAPSYS ORACLE_OCM ORDDATA ORDPLUGINS ORDSYS OUTLN SI_INFORMTN_SCHEMA SPATIAL_CSW_ADMIN_USR SPATIAL_WFS_ADMIN_USR SYS SYSMAN SYSTEM TRACESRV MTSSYS OASPUBLIC OWBSYS OWBSYS_AUDIT WEBSYS WK_PROXY WKSYS WK_TEST WMSYS XDB OSE$HTTP$ADMIN AURORA$JIS$UTILITY$ AURORA$ORB$UNAUTHENTICATED/, qr/^FLOWS_\d\d\d\d\d\d\z/);
55 }
56
57 sub _system_tables {
58     my $self = shift;
59
60     return ($self->next::method(@_), 'PLAN_TABLE');
61 }
62
63 sub _dbh_tables {
64     my ($self, $schema) = @_;
65
66     return $self->dbh->tables(undef, $schema, '%', 'TABLE,VIEW');
67 }
68
69 sub _filter_tables {
70     my $self = shift;
71
72     # silence a warning from older DBD::Oracles in tests
73     local $SIG{__WARN__} = sigwarn_silencer(
74         qr/^Field \d+ has an Oracle type \(\d+\) which is not explicitly supported/
75     );
76
77     return $self->next::method(@_);
78 }
79
80 sub _table_fk_info {
81     my $self = shift;
82     my ($table) = @_;
83
84     my $rels = $self->next::method(@_);
85
86     my $deferrable_sth = $self->dbh->prepare_cached(<<'EOF');
87 select deferrable from all_constraints
88 where owner = ? and table_name = ? and constraint_name = ?
89 EOF
90
91     foreach my $rel (@$rels) {
92         # Oracle does not have update rules
93         $rel->{attrs}{on_update} = 'NO ACTION';;
94
95         # DBD::Oracle's foreign_key_info does not return DEFERRABILITY, so we get it ourselves
96         my ($deferrable) = $self->dbh->selectrow_array(
97             $deferrable_sth, undef, $table->schema, $table->name, $rel->{_constraint_name}
98         );
99
100         $rel->{attrs}{is_deferrable} = $deferrable && $deferrable =~ /^DEFERRABLE/i ? 1 : 0;
101     }
102
103     return $rels;
104 }
105
106 sub _table_uniq_info {
107     my ($self, $table) = @_;
108
109     my $sth = $self->dbh->prepare_cached(<<'EOF', {}, 1);
110 SELECT ac.constraint_name, acc.column_name
111 FROM all_constraints ac, all_cons_columns acc
112 WHERE acc.table_name=? AND acc.owner = ?
113     AND ac.table_name = acc.table_name AND ac.owner = acc.owner
114     AND acc.constraint_name = ac.constraint_name
115     AND ac.constraint_type='U'
116 ORDER BY acc.position
117 EOF
118
119     $sth->execute($table->name, $table->schema);
120
121     my %constr_names;
122
123     while(my $constr = $sth->fetchrow_arrayref) {
124         my $constr_name = $self->_lc($constr->[0]);
125         my $constr_col  = $self->_lc($constr->[1]);
126         push @{$constr_names{$constr_name}}, $constr_col;
127     }
128
129     my @uniqs = map { [ $_ => $constr_names{$_} ] } keys %constr_names;
130     return \@uniqs;
131 }
132
133 sub _table_comment {
134     my $self = shift;
135     my ($table) = @_;
136
137     my $table_comment = $self->next::method(@_);
138
139     return $table_comment if $table_comment;
140
141     ($table_comment) = $self->dbh->selectrow_array(<<'EOF', {}, $table->schema, $table->name);
142 SELECT comments FROM all_tab_comments
143 WHERE owner = ?
144   AND table_name = ?
145   AND (table_type = 'TABLE' OR table_type = 'VIEW')
146 EOF
147
148     return $table_comment
149 }
150
151 sub _column_comment {
152     my $self = shift;
153     my ($table, $column_number, $column_name) = @_;
154
155     my $column_comment = $self->next::method(@_);
156
157     return $column_comment if $column_comment;
158
159     ($column_comment) = $self->dbh->selectrow_array(<<'EOF', {}, $table->schema, $table->name, $self->_uc($column_name));
160 SELECT comments FROM all_col_comments
161 WHERE owner = ?
162   AND table_name = ?
163   AND column_name = ?
164 EOF
165
166     return $column_comment
167 }
168
169 sub _columns_info_for {
170     my $self = shift;
171     my ($table) = @_;
172
173     my $result = $self->next::method(@_);
174
175     local $self->dbh->{LongReadLen} = 1_000_000;
176     local $self->dbh->{LongTruncOk} = 1;
177
178     my $sth = $self->dbh->prepare_cached(<<'EOF', {}, 1);
179 SELECT trigger_body
180 FROM all_triggers
181 WHERE table_name = ? AND table_owner = ?
182 AND upper(trigger_type) LIKE '%BEFORE EACH ROW%' AND lower(triggering_event) LIKE '%insert%'
183 EOF
184
185     $sth->execute($table->name, $table->schema);
186
187     while (my ($trigger_body) = $sth->fetchrow_array) {
188         if (my ($seq_schema, $seq_name) = $trigger_body =~ /(?:"?(\w+)"?\.)?"?(\w+)"?\.nextval/i) {
189             if (my ($col_name) = $trigger_body =~ /:new\.(\w+)/i) {
190                 $col_name = $self->_lc($col_name);
191
192                 $result->{$col_name}{is_auto_increment} = 1;
193
194                 $seq_schema = $self->_lc($seq_schema || $table->schema);
195                 $seq_name   = $self->_lc($seq_name);
196
197                 $result->{$col_name}{sequence} = ($self->qualify_objects ? ($seq_schema . '.') : '') . $seq_name;
198             }
199         }
200     }
201
202     # Old DBD::Oracle report the size in (UTF-16) bytes, not characters
203     my $nchar_size_factor = $DBD::Oracle::VERSION >= 1.52 ? 1 : 2;
204
205     while (my ($col, $info) = each %$result) {
206         no warnings 'uninitialized';
207
208         my $sth = $self->dbh->prepare_cached(<<'EOF', {}, 1);
209 SELECT data_type, data_length
210 FROM all_tab_columns
211 WHERE column_name = ? AND table_name = ? AND owner = ?
212 EOF
213         $sth->execute($self->_uc($col), $table->name, $table->schema);
214         my ($data_type, $data_length) = $sth->fetchrow_array;
215         $sth->finish;
216         $data_type = lc $data_type;
217
218         if ($data_type =~ /^(?:n(?:var)?char2?|u?rowid|nclob|timestamp\(\d+\)(?: with(?: local)? time zone)?|binary_(?:float|double))\z/i) {
219             $info->{data_type} = $data_type;
220
221             if ($data_type =~ /^u?rowid\z/i) {
222                 $info->{size} = $data_length;
223             }
224         }
225
226         if ($info->{data_type} =~ /^(?:n?[cb]lob|long(?: raw)?|bfile|date|binary_(?:float|double)|rowid)\z/i) {
227             delete $info->{size};
228         }
229
230         if ($info->{data_type} =~ /^n(?:var)?char2?\z/i) {
231             if (ref $info->{size}) {
232                 $info->{size} = $info->{size}[0] / 8;
233             }
234             else {
235                 $info->{size} = $info->{size} / $nchar_size_factor;
236             }
237         }
238         elsif ($info->{data_type} =~ /^(?:var)?char2?\z/i) {
239             if (ref $info->{size}) {
240                 $info->{size} = $info->{size}[0];
241             }
242         }
243         elsif (lc($info->{data_type}) =~ /^(?:number|decimal)\z/i) {
244             $info->{original}{data_type} = 'number';
245             $info->{data_type}           = 'numeric';
246
247             if (try { $info->{size}[0] == 38 && $info->{size}[1] == 0 }) {
248                 $info->{original}{size} = $info->{size};
249
250                 $info->{data_type} = 'integer';
251                 delete $info->{size};
252             }
253         }
254         elsif (my ($precision) = $info->{data_type} =~ /^timestamp\((\d+)\)(?: with (?:local )?time zone)?\z/i) {
255             $info->{data_type} = join ' ', $info->{data_type} =~ /[a-z]+/ig;
256
257             if ($precision == 6) {
258                 delete $info->{size};
259             }
260             else {
261                 $info->{size} = $precision;
262             }
263         }
264         elsif ($info->{data_type} =~ /timestamp/i && ref $info->{size} && $info->{size}[0] == 0) {
265             my $size = $info->{size}[1];
266             delete $info->{size};
267             $info->{size} = $size unless $size == 6;
268         }
269         elsif (($precision) = $info->{data_type} =~ /^interval year\((\d+)\) to month\z/i) {
270             $info->{data_type} = join ' ', $info->{data_type} =~ /[a-z]+/ig;
271
272             if ($precision == 2) {
273                 delete $info->{size};
274             }
275             else {
276                 $info->{size} = $precision;
277             }
278         }
279         elsif (my ($day_precision, $second_precision) = $info->{data_type} =~ /^interval day\((\d+)\) to second\((\d+)\)\z/i) {
280             $info->{data_type} = join ' ', $info->{data_type} =~ /[a-z]+/ig;
281
282             if ($day_precision == 2 && $second_precision == 6) {
283                 delete $info->{size};
284             }
285             else {
286                 $info->{size} = [ $day_precision, $second_precision ];
287             }
288         }
289         elsif ($info->{data_type} =~ /^interval year to month\z/i && ref $info->{size}) {
290             my $precision = $info->{size}[0];
291
292             if ($precision == 2) {
293                 delete $info->{size};
294             }
295             else {
296                 $info->{size} = $precision;
297             }
298         }
299         elsif ($info->{data_type} =~ /^interval day to second\z/i && ref $info->{size}) {
300             if ($info->{size}[0] == 2 && $info->{size}[1] == 6) {
301                 delete $info->{size};
302             }
303         }
304         elsif (lc($info->{data_type}) eq 'float') {
305             $info->{original}{data_type} = 'float';
306             $info->{original}{size}      = $info->{size};
307
308             if ($info->{size} <= 63) {
309                 $info->{data_type} = 'real';
310             }
311             else {
312                 $info->{data_type} = 'double precision';
313             }
314             delete $info->{size};
315         }
316         elsif (lc($info->{data_type}) eq 'double precision') {
317             $info->{original}{data_type} = 'float';
318
319             my $size = try { $info->{size}[0] };
320
321             $info->{original}{size} = $size;
322
323             if ($size <= 63) {
324                 $info->{data_type} = 'real';
325             }
326             delete $info->{size};
327         }
328         elsif (lc($info->{data_type}) eq 'urowid' && $info->{size} == 4000) {
329             delete $info->{size};
330         }
331         elsif ($info->{data_type} eq '-9104') {
332             $info->{data_type} = 'rowid';
333             delete $info->{size};
334         }
335         elsif ($info->{data_type} eq '-2') {
336             $info->{data_type} = 'raw';
337             $info->{size} = try { $info->{size}[0] / 2 };
338         }
339         elsif (lc($info->{data_type}) eq 'date') {
340             $info->{data_type}           = 'datetime';
341             $info->{original}{data_type} = 'date';
342         }
343         elsif (lc($info->{data_type}) eq 'binary_float') {
344             $info->{data_type}           = 'real';
345             $info->{original}{data_type} = 'binary_float';
346         }
347         elsif (lc($info->{data_type}) eq 'binary_double') {
348             $info->{data_type}           = 'double precision';
349             $info->{original}{data_type} = 'binary_double';
350         }
351
352         # DEFAULT could be missed by ::DBI because of ORA-24345
353         if (not defined $info->{default_value}) {
354             local $self->dbh->{LongReadLen} = 1_000_000;
355             local $self->dbh->{LongTruncOk} = 1;
356             my $sth = $self->dbh->prepare_cached(<<'EOF', {}, 1);
357 SELECT data_default
358 FROM all_tab_columns
359 WHERE column_name = ? AND table_name = ? AND owner = ?
360 EOF
361             $sth->execute($self->_uc($col), $table->name, $table->schema);
362             my ($default) = $sth->fetchrow_array;
363             $sth->finish;
364
365             # this is mostly copied from ::DBI::QuotedDefault
366             if (defined $default) {
367                 s/^\s+//, s/\s+\z// for $default;
368
369                 if ($default =~ /^'(.*?)'\z/) {
370                     $info->{default_value} = $1;
371                 }
372                 elsif ($default =~ /^(-?\d.*?)\z/) {
373                     $info->{default_value} = $1;
374                 }
375                 elsif ($default =~ /^NULL\z/i) {
376                     my $null = 'null';
377                     $info->{default_value} = \$null;
378                 }
379                 elsif ($default ne '') {
380                     my $val = $default;
381                     $info->{default_value} = \$val;
382                 }
383             }
384         }
385
386         if ((try { lc(${ $info->{default_value} }) }||'') eq 'sysdate') {
387             my $current_timestamp  = 'current_timestamp';
388             $info->{default_value} = \$current_timestamp;
389
390             my $sysdate = 'sysdate';
391             $info->{original}{default_value} = \$sysdate;
392         }
393     }
394
395     return $result;
396 }
397
398 sub _dbh_column_info {
399     my $self  = shift;
400     my ($dbh) = @_;
401
402     # try to avoid ORA-24345
403     local $dbh->{LongReadLen} = 1_000_000;
404     local $dbh->{LongTruncOk} = 1;
405
406     return $self->next::method(@_);
407 }
408
409 =head1 SEE ALSO
410
411 L<DBIx::Class::Schema::Loader>, L<DBIx::Class::Schema::Loader::Base>,
412 L<DBIx::Class::Schema::Loader::DBI>
413
414 =head1 AUTHOR
415
416 See L<DBIx::Class::Schema::Loader/AUTHOR> and L<DBIx::Class::Schema::Loader/CONTRIBUTORS>.
417
418 =head1 LICENSE
419
420 This library is free software; you can redistribute it and/or modify it under
421 the same terms as Perl itself.
422
423 =cut
424
425 1;
426 # vim:et sts=4 sw=4 tw=0: