3cad11516b5ad114203cd8e7d05fa4cfd196738b
[dbsrgits/DBIx-Class-Historic.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   my $b36sum = Math::Base36::encode_base36(
149     Math::BigInt->from_hex (
150       '0x' . Digest::MD5::md5_hex ($to_shorten)
151     )
152   );
153
154   # switch from perl to java
155   # get run-length
156   my ($concat_len, @lengths);
157   for (@keywords) {
158     $_ = ucfirst (lc ($_));
159     $_ =~ s/\_+(\w)/uc ($1)/eg;
160
161     push @lengths, length ($_);
162     $concat_len += $lengths[-1];
163   }
164
165   # if we are still too long - try to disemvowel non-capitals (not keyword starts)
166   if ($concat_len > $max_trunc) {
167     $concat_len = 0;
168     @lengths = ();
169
170     for (@keywords) {
171       $_ =~ s/[aeiou]//g;
172
173       push @lengths, length ($_);
174       $concat_len += $lengths[-1];
175     }
176   }
177
178   # still too long - just start cutting proportionally
179   if ($concat_len > $max_trunc) {
180     my $trim_ratio = $max_trunc / $concat_len;
181
182     for my $i (0 .. $#keywords) {
183       $keywords[$i] = substr ($keywords[$i], 0, int ($trim_ratio * $lengths[$i] ) );
184     }
185   }
186
187   my $fin = join ('', @keywords);
188   my $fin_len = length $fin;
189
190   return sprintf ('%s_%s',
191     $fin,
192     substr ($b36sum, 0, $max_len - $fin_len - 1),
193   );
194 }
195
196 sub _unqualify_colname {
197   my ($self, $fqcn) = @_;
198
199   return $self->_shorten_identifier($self->next::method($fqcn));
200 }
201
202 #
203 # Oracle has a different INSERT...RETURNING syntax
204 #
205
206 sub _insert_returning {
207   my ($self, $options) = @_;
208
209   my $f = $options->{returning};
210
211   my ($f_list, @f_names) = do {
212     if (! ref $f) {
213       (
214         $self->_quote($f),
215         $f,
216       )
217     }
218     elsif (ref $f eq 'ARRAY') {
219       (
220         (join ', ', map { $self->_quote($_) } @$f),
221         @$f,
222       )
223     }
224     elsif (ref $f eq 'SCALAR') {
225       (
226         $$f,
227         $$f,
228       )
229     }
230     else {
231       $self->throw_exception("Unsupported INSERT RETURNING option $f");
232     }
233   };
234
235   my $rc_ref = $options->{returning_container}
236     or $self->throw_exception('No returning container supplied for IR values');
237
238   @$rc_ref = (undef) x @f_names;
239
240   return (
241     ( join (' ',
242       $self->_sqlcase(' returning'),
243       $f_list,
244       $self->_sqlcase('into'),
245       join (', ', ('?') x @f_names ),
246     )),
247     map {
248       $self->{bindtype} eq 'columns'
249         ? [ $f_names[$_] => \$rc_ref->[$_] ]
250         : \$rc_ref->[$_]
251     } (0 .. $#f_names),
252   );
253 }
254
255 1;