Can not return from within a try block
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / Oracle / Generic.pm
CommitLineData
18360aed 1package DBIx::Class::Storage::DBI::Oracle::Generic;
2
3use strict;
4use warnings;
b7b18f32 5use Scope::Guard ();
6use Context::Preserve ();
ed7ab0f4 7use Try::Tiny;
18360aed 8
7137528d 9=head1 NAME
10
7a84c41b 11DBIx::Class::Storage::DBI::Oracle::Generic - Oracle Support for DBIx::Class
7137528d 12
13=head1 SYNOPSIS
14
d88ecca6 15 # In your result (table) classes
16 use base 'DBIx::Class::Core';
2e46b6eb 17 __PACKAGE__->add_columns({ id => { sequence => 'mysequence', auto_nextval => 1 } });
7137528d 18 __PACKAGE__->set_primary_key('id');
19 __PACKAGE__->sequence('mysequence');
20
21=head1 DESCRIPTION
22
6c0230de 23This class implements base Oracle support. The subclass
24L<DBIx::Class::Storage::DBI::Oracle::WhereJoins> is for C<(+)> joins in Oracle
25versions before 9.
7137528d 26
27=head1 METHODS
28
29=cut
30
db56cf3d 31use base qw/DBIx::Class::Storage::DBI/;
2ad62d97 32use mro 'c3';
18360aed 33
dd2600c6 34sub deployment_statements {
35 my $self = shift;;
36 my ($schema, $type, $version, $dir, $sqltargs, @rest) = @_;
37
38 $sqltargs ||= {};
032b2366 39 my $quote_char = $self->schema->storage->sql_maker->quote_char;
40 $sqltargs->{quote_table_names} = $quote_char ? 1 : 0;
41 $sqltargs->{quote_field_names} = $quote_char ? 1 : 0;
dd2600c6 42
9780718f 43 my $oracle_version = try { $self->_get_dbh->get_info(18) };
a4433d8e 44
45 $sqltargs->{producer_args}{oracle_version} = $oracle_version;
46
38aead8e 47 $self->next::method($schema, $type, $version, $dir, $sqltargs, @rest);
dd2600c6 48}
49
18360aed 50sub _dbh_last_insert_id {
2e46b6eb 51 my ($self, $dbh, $source, @columns) = @_;
52 my @ids = ();
53 foreach my $col (@columns) {
54 my $seq = ($source->column_info($col)->{sequence} ||= $self->get_autoinc_seq($source,$col));
55 my $id = $self->_sequence_fetch( 'currval', $seq );
56 push @ids, $id;
57 }
58 return @ids;
18360aed 59}
60
61sub _dbh_get_autoinc_seq {
62 my ($self, $dbh, $source, $col) = @_;
63
032b2366 64 my $sql_maker = $self->sql_maker;
cb464582 65
e6dd7b42 66 my $source_name;
032b2366 67 if ( ref $source->name eq 'SCALAR' ) {
68 $source_name = ${$source->name};
e6dd7b42 69 }
70 else {
032b2366 71 $source_name = $source->name;
e6dd7b42 72 }
3963bf4c 73 $source_name = uc($source_name) unless $sql_maker->quote_char;
38aead8e 74
032b2366 75 # trigger_body is a LONG
76 local $dbh->{LongReadLen} = 64 * 1024 if ($dbh->{LongReadLen} < 64 * 1024);
77
78 # disable default bindtype
79 local $sql_maker->{bindtype} = 'normal';
80
81 # look up the correct sequence automatically
82 my ( $schema, $table ) = $source_name =~ /(\w+)\.(\w+)/;
83 my ($sql, @bind) = $sql_maker->select (
84 'ALL_TRIGGERS',
85 ['trigger_body'],
86 {
87 $schema ? (owner => $schema) : (),
88 table_name => $table || $source_name,
cc42fa9a 89 triggering_event => { -like => '%INSERT%' },
032b2366 90 status => 'ENABLED',
91 },
92 );
93 my $sth = $dbh->prepare($sql);
94 $sth->execute (@bind);
e6dd7b42 95
18360aed 96 while (my ($insert_trigger) = $sth->fetchrow_array) {
852a66f6 97 return $1 if $insert_trigger =~ m!("?\w+"?)\.nextval!i; # col name goes here???
18360aed 98 }
4f2b3017 99 $self->throw_exception("Unable to find a sequence INSERT trigger on table '$source_name'.");
18360aed 100}
101
2e46b6eb 102sub _sequence_fetch {
103 my ( $self, $type, $seq ) = @_;
9ae966b9 104 my ($id) = $self->_get_dbh->selectrow_array("SELECT ${seq}.${type} FROM DUAL");
2e46b6eb 105 return $id;
106}
107
6dc4be0f 108sub _ping {
c2481821 109 my $self = shift;
7ba7a57d 110
6dc4be0f 111 my $dbh = $self->_dbh or return 0;
7ba7a57d 112
6dc4be0f 113 local $dbh->{RaiseError} = 1;
ecdf1ac8 114 local $dbh->{PrintError} = 0;
c2d7baef 115
52b420dd 116 return try {
ecdf1ac8 117 $dbh->do('select 1 from dual');
52b420dd 118 1;
ed7ab0f4 119 } catch {
52b420dd 120 0;
6dc4be0f 121 };
c2481821 122}
123
d789fa99 124sub _dbh_execute {
125 my $self = shift;
126 my ($dbh, $op, $extra_bind, $ident, $bind_attributes, @args) = @_;
127
dd415de8 128 my (@res, $retried);
129 my $wantarray = wantarray();
4f661051 130 my $next = $self->next::can;
66efa982 131 while (1) {
52b420dd 132 try {
dd415de8 133 my $exec = sub { $self->$next($dbh, $op, $extra_bind, $ident, $bind_attributes, @args) };
134
135 if (!defined $wantarray) {
136 $exec->();
137 }
138 elsif (! $wantarray) {
139 $res[0] = $exec->();
140 }
141 else {
142 @res = $exec->();
143 }
52b420dd 144 }
145 catch {
66efa982 146 if (!$retried++ and $_ =~ /ORA-01003/) {
0f0abc97 147 # ORA-01003: no statement parsed (someone changed the table somehow,
148 # invalidating your cursor.)
149 my ($sql, $bind) = $self->_prep_for_execute($op, $extra_bind, $ident, \@args);
150 delete $dbh->{CachedKids}{$sql};
d789fa99 151 }
52b420dd 152 else {
153 $self->throw_exception($_);
154 }
155 };
66efa982 156 }
dd415de8 157
158 return $wantarray ? @res : $res[0];
d789fa99 159}
160
7137528d 161=head2 get_autoinc_seq
162
163Returns the sequence name for an autoincrement column
164
165=cut
166
18360aed 167sub get_autoinc_seq {
168 my ($self, $source, $col) = @_;
d4daee7b 169
373940e1 170 $self->dbh_do('_dbh_get_autoinc_seq', $source, $col);
18360aed 171}
172
8f7e044c 173=head2 datetime_parser_type
174
175This sets the proper DateTime::Format module for use with
176L<DBIx::Class::InflateColumn::DateTime>.
177
178=cut
179
180sub datetime_parser_type { return "DateTime::Format::Oracle"; }
181
9900b569 182=head2 connect_call_datetime_setup
d2a3958e 183
184Used as:
185
9900b569 186 on_connect_call => 'datetime_setup'
d2a3958e 187
8384a713 188In L<connect_info|DBIx::Class::Storage::DBI/connect_info> to set the session nls
189date, and timestamp values for use with L<DBIx::Class::InflateColumn::DateTime>
190and the necessary environment variables for L<DateTime::Format::Oracle>, which
191is used by it.
d2a3958e 192
82f6f45f 193Maximum allowable precision is used, unless the environment variables have
194already been set.
d2a3958e 195
9900b569 196These are the defaults used:
197
198 $ENV{NLS_DATE_FORMAT} ||= 'YYYY-MM-DD HH24:MI:SS';
199 $ENV{NLS_TIMESTAMP_FORMAT} ||= 'YYYY-MM-DD HH24:MI:SS.FF';
200 $ENV{NLS_TIMESTAMP_TZ_FORMAT} ||= 'YYYY-MM-DD HH24:MI:SS.FF TZHTZM';
201
d9e53b85 202To get more than second precision with L<DBIx::Class::InflateColumn::DateTime>
203for your timestamps, use something like this:
204
205 use Time::HiRes 'time';
206 my $ts = DateTime->from_epoch(epoch => time);
207
d2a3958e 208=cut
209
9900b569 210sub connect_call_datetime_setup {
d2a3958e 211 my $self = shift;
d2a3958e 212
213 my $date_format = $ENV{NLS_DATE_FORMAT} ||= 'YYYY-MM-DD HH24:MI:SS';
214 my $timestamp_format = $ENV{NLS_TIMESTAMP_FORMAT} ||=
215 'YYYY-MM-DD HH24:MI:SS.FF';
216 my $timestamp_tz_format = $ENV{NLS_TIMESTAMP_TZ_FORMAT} ||=
217 'YYYY-MM-DD HH24:MI:SS.FF TZHTZM';
218
7a84c41b 219 $self->_do_query(
d7a58a29 220 "alter session set nls_date_format = '$date_format'"
221 );
7a84c41b 222 $self->_do_query(
d7a58a29 223 "alter session set nls_timestamp_format = '$timestamp_format'"
224 );
225 $self->_do_query(
226 "alter session set nls_timestamp_tz_format='$timestamp_tz_format'"
227 );
d2a3958e 228}
229
5db2758d 230=head2 source_bind_attributes
231
232Handle LOB types in Oracle. Under a certain size (4k?), you can get away
233with the driver assuming your input is the deprecated LONG type if you
234encode it as a hex string. That ain't gonna fly at larger values, where
235you'll discover you have to do what this does.
236
237This method had to be overridden because we need to set ora_field to the
238actual column, and that isn't passed to the call (provided by Storage) to
239bind_attribute_by_data_type.
240
241According to L<DBD::Oracle>, the ora_field isn't always necessary, but
242adding it doesn't hurt, and will save your bacon if you're modifying a
243table with more than one LOB column.
244
245=cut
246
e6dd7b42 247sub source_bind_attributes
5db2758d 248{
d7a58a29 249 require DBD::Oracle;
250 my $self = shift;
251 my($source) = @_;
5db2758d 252
d7a58a29 253 my %bind_attributes;
5db2758d 254
d7a58a29 255 foreach my $column ($source->columns) {
256 my $data_type = $source->column_info($column)->{data_type} || '';
257 next unless $data_type;
5db2758d 258
d7a58a29 259 my %column_bind_attrs = $self->bind_attribute_by_data_type($data_type);
5db2758d 260
d7a58a29 261 if ($data_type =~ /^[BC]LOB$/i) {
931e5d43 262 if ($DBD::Oracle::VERSION eq '1.23') {
263 $self->throw_exception(
264"BLOB/CLOB support in DBD::Oracle == 1.23 is broken, use an earlier or later ".
555cc3f4 265"version.\n\nSee: https://rt.cpan.org/Public/Bug/Display.html?id=46016\n"
931e5d43 266 );
267 }
268
d7a58a29 269 $column_bind_attrs{'ora_type'} = uc($data_type) eq 'CLOB'
270 ? DBD::Oracle::ORA_CLOB()
271 : DBD::Oracle::ORA_BLOB()
272 ;
273 $column_bind_attrs{'ora_field'} = $column;
274 }
5db2758d 275
d7a58a29 276 $bind_attributes{$column} = \%column_bind_attrs;
277 }
5db2758d 278
d7a58a29 279 return \%bind_attributes;
5db2758d 280}
281
1816be4f 282sub _svp_begin {
d7a58a29 283 my ($self, $name) = @_;
284 $self->_get_dbh->do("SAVEPOINT $name");
1816be4f 285}
286
281719d2 287# Oracle automatically releases a savepoint when you start another one with the
288# same name.
289sub _svp_release { 1 }
290
291sub _svp_rollback {
d7a58a29 292 my ($self, $name) = @_;
293 $self->_get_dbh->do("ROLLBACK TO SAVEPOINT $name")
281719d2 294}
295
6c0230de 296=head2 relname_to_table_alias
297
298L<DBIx::Class> uses L<DBIx::Class::Relationship> names as table aliases in
299queries.
300
301Unfortunately, Oracle doesn't support identifiers over 30 chars in length, so
af0edca1 302the L<DBIx::Class::Relationship> name is shortened and appended with half of an
303MD5 hash.
6c0230de 304
305See L<DBIx::Class::Storage/"relname_to_table_alias">.
306
307=cut
308
309sub relname_to_table_alias {
310 my $self = shift;
311 my ($relname, $join_count) = @_;
312
313 my $alias = $self->next::method(@_);
314
315 return $alias if length($alias) <= 30;
316
af0edca1 317 # get a base64 md5 of the alias with join_count
318 require Digest::MD5;
319 my $ctx = Digest::MD5->new;
320 $ctx->add($alias);
321 my $md5 = $ctx->b64digest;
6c0230de 322
f098ade6 323 # remove alignment mark just in case
324 $md5 =~ s/=*\z//;
325
af0edca1 326 # truncate and prepend to truncated relname without vowels
327 (my $devoweled = $relname) =~ s/[aeiou]//g;
909668fe 328 my $shortened = substr($devoweled, 0, 18);
6c0230de 329
909668fe 330 my $new_alias =
331 $shortened . '_' . substr($md5, 0, 30 - length($shortened) - 1);
332
333 return $new_alias;
6c0230de 334}
335
6c0bb6a7 336=head2 with_deferred_fk_checks
337
338Runs a coderef between:
339
340 alter session set constraints = deferred
341 ...
342 alter session set constraints = immediate
343
b7b18f32 344to defer foreign key checks.
345
346Constraints must be declared C<DEFERRABLE> for this to work.
6c0bb6a7 347
348=cut
349
350sub with_deferred_fk_checks {
351 my ($self, $sub) = @_;
b7b18f32 352
353 my $txn_scope_guard = $self->txn_scope_guard;
354
6c0bb6a7 355 $self->_do_query('alter session set constraints = deferred');
b7b18f32 356
357 my $sg = Scope::Guard->new(sub {
358 $self->_do_query('alter session set constraints = immediate');
359 });
360
361 return Context::Preserve::preserve_context(sub { $sub->() },
362 after => sub { $txn_scope_guard->commit });
6c0bb6a7 363}
364
7a84c41b 365=head1 AUTHOR
18360aed 366
7a84c41b 367See L<DBIx::Class/CONTRIBUTORS>.
18360aed 368
369=head1 LICENSE
370
371You may distribute this code under the same terms as Perl itself.
372
373=cut
7137528d 374
3751;