Switch all double-optdeps calls to a single invocation in lib/
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLMaker / Oracle.pm
1 package # Hide from PAUSE
2   DBIx::Class::SQLMaker::Oracle;
3
4 use warnings;
5 use strict;
6
7 BEGIN {
8   require DBIx::Class::Optional::Dependencies;
9   if (my $missing = DBIx::Class::Optional::Dependencies->req_missing_for ('id_shortener') ) {
10     die "The following extra modules are required for Oracle-based Storages: $missing\n";
11   }
12 }
13
14 use base 'DBIx::Class::SQLMaker';
15
16 sub new {
17   my $self = shift;
18   my %opts = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
19   push @{$opts{special_ops}}, {
20     regex => qr/^prior$/i,
21     handler => '_where_field_PRIOR',
22   };
23
24   $self->next::method(\%opts);
25 }
26
27 sub _assemble_binds {
28   my $self = shift;
29   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where oracle_connect_by group having order limit/);
30 }
31
32
33 sub _parse_rs_attrs {
34     my $self = shift;
35     my ($rs_attrs) = @_;
36
37     my ($cb_sql, @cb_bind) = $self->_connect_by($rs_attrs);
38     push @{$self->{oracle_connect_by_bind}}, @cb_bind;
39
40     my $sql = $self->next::method(@_);
41
42     return "$cb_sql $sql";
43 }
44
45 sub _connect_by {
46     my ($self, $attrs) = @_;
47
48     my $sql = '';
49     my @bind;
50
51     if ( ref($attrs) eq 'HASH' ) {
52         if ( $attrs->{'start_with'} ) {
53             my ($ws, @wb) = $self->_recurse_where( $attrs->{'start_with'} );
54             $sql .= $self->_sqlcase(' start with ') . $ws;
55             push @bind, @wb;
56         }
57         if ( my $connect_by = $attrs->{'connect_by'} || $attrs->{'connect_by_nocycle'} ) {
58             my ($connect_by_sql, @connect_by_sql_bind) = $self->_recurse_where( $connect_by );
59             $sql .= sprintf(" %s %s",
60                 ( $attrs->{'connect_by_nocycle'} ) ? $self->_sqlcase('connect by nocycle')
61                     : $self->_sqlcase('connect by'),
62                 $connect_by_sql,
63             );
64             push @bind, @connect_by_sql_bind;
65         }
66         if ( $attrs->{'order_siblings_by'} ) {
67             $sql .= $self->_order_siblings_by( $attrs->{'order_siblings_by'} );
68         }
69     }
70
71     return wantarray ? ($sql, @bind) : $sql;
72 }
73
74 sub _order_siblings_by {
75     my ( $self, $arg ) = @_;
76
77     my ( @sql, @bind );
78     for my $c ( $self->_order_by_chunks($arg) ) {
79         if (ref $c) {
80             push @sql, shift @$c;
81             push @bind, @$c;
82         }
83         else {
84             push @sql, $c;
85         }
86     }
87
88     my $sql =
89       @sql
90       ? sprintf( '%s %s', $self->_sqlcase(' order siblings by'), join( ', ', @sql ) )
91       : '';
92
93     return wantarray ? ( $sql, @bind ) : $sql;
94 }
95
96 # we need to add a '=' only when PRIOR is used against a column directly
97 # i.e. when it is invoked by a special_op callback
98 sub _where_field_PRIOR {
99   my ($self, $lhs, $op, $rhs) = @_;
100   my ($sql, @bind) = $self->_recurse_where ($rhs);
101
102   $sql = sprintf ('%s = %s %s ',
103     $self->_convert($self->_quote($lhs)),
104     $self->_sqlcase ($op),
105     $sql
106   );
107
108   return ($sql, @bind);
109 }
110
111 # use this codepath to hook all identifiers and mangle them if necessary
112 # this is invoked regardless of quoting being on or off
113 sub _quote {
114   my ($self, $label) = @_;
115
116   return '' unless defined $label;
117   return ${$label} if ref($label) eq 'SCALAR';
118
119   $label =~ s/ ( [^\.]{31,} ) /$self->_shorten_identifier($1)/gxe;
120
121   $self->next::method($label);
122 }
123
124 # this takes an identifier and shortens it if necessary
125 # optionally keywords can be passed as an arrayref to generate useful
126 # identifiers
127 sub _shorten_identifier {
128   my ($self, $to_shorten, $keywords) = @_;
129
130   # 30 characters is the identifier limit for Oracle
131   my $max_len = 30;
132   # we want at least 10 characters of the base36 md5
133   my $min_entropy = 10;
134
135   my $max_trunc = $max_len - $min_entropy - 1;
136
137   return $to_shorten
138     if length($to_shorten) <= $max_len;
139
140   $self->throw_exception("'keywords' needs to be an arrayref")
141     if defined $keywords && ref $keywords ne 'ARRAY';
142
143   # if no keywords are passed use the identifier as one
144   my @keywords = @{$keywords || []};
145   @keywords = $to_shorten unless @keywords;
146
147   # get a base36 md5 of the identifier
148   require Digest::MD5;
149   require Math::BigInt;
150   require Math::Base36;
151   my $b36sum = Math::Base36::encode_base36(
152     Math::BigInt->from_hex (
153       '0x' . Digest::MD5::md5_hex ($to_shorten)
154     )
155   );
156
157   # switch from perl to java
158   # get run-length
159   my ($concat_len, @lengths);
160   for (@keywords) {
161     $_ = ucfirst (lc ($_));
162     $_ =~ s/\_+(\w)/uc ($1)/eg;
163
164     push @lengths, length ($_);
165     $concat_len += $lengths[-1];
166   }
167
168   # if we are still too long - try to disemvowel non-capitals (not keyword starts)
169   if ($concat_len > $max_trunc) {
170     $concat_len = 0;
171     @lengths = ();
172
173     for (@keywords) {
174       $_ =~ s/[aeiou]//g;
175
176       push @lengths, length ($_);
177       $concat_len += $lengths[-1];
178     }
179   }
180
181   # still too long - just start cutting proportionally
182   if ($concat_len > $max_trunc) {
183     my $trim_ratio = $max_trunc / $concat_len;
184
185     for my $i (0 .. $#keywords) {
186       $keywords[$i] = substr ($keywords[$i], 0, int ($trim_ratio * $lengths[$i] ) );
187     }
188   }
189
190   my $fin = join ('', @keywords);
191   my $fin_len = length $fin;
192
193   return sprintf ('%s_%s',
194     $fin,
195     substr ($b36sum, 0, $max_len - $fin_len - 1),
196   );
197 }
198
199 sub _unqualify_colname {
200   my ($self, $fqcn) = @_;
201
202   return $self->_shorten_identifier($self->next::method($fqcn));
203 }
204
205 #
206 # Oracle has a different INSERT...RETURNING syntax
207 #
208
209 sub _insert_returning {
210   my ($self, $options) = @_;
211
212   my $f = $options->{returning};
213
214   my ($f_list, @f_names) = do {
215     if (! ref $f) {
216       (
217         $self->_quote($f),
218         $f,
219       )
220     }
221     elsif (ref $f eq 'ARRAY') {
222       (
223         (join ', ', map { $self->_quote($_) } @$f),
224         @$f,
225       )
226     }
227     elsif (ref $f eq 'SCALAR') {
228       (
229         $$f,
230         $$f,
231       )
232     }
233     else {
234       $self->throw_exception("Unsupported INSERT RETURNING option $f");
235     }
236   };
237
238   my $rc_ref = $options->{returning_container}
239     or $self->throw_exception('No returning container supplied for IR values');
240
241   @$rc_ref = (undef) x @f_names;
242
243   return (
244     ( join (' ',
245       $self->_sqlcase(' returning'),
246       $f_list,
247       $self->_sqlcase('into'),
248       join (', ', ('?') x @f_names ),
249     )),
250     map {
251       $self->{bindtype} eq 'columns'
252         ? [ $f_names[$_] => \$rc_ref->[$_] ]
253         : \$rc_ref->[$_]
254     } (0 .. $#f_names),
255   );
256 }
257
258 1;