The fix in f9b5239ac was both shortsighted and insufficient
[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;
5e782048 5use base qw/DBIx::Class::Storage::DBI/;
6use mro 'c3';
7use DBIx::Class::Carp;
b7b18f32 8use Scope::Guard ();
6298a324 9use Context::Preserve 'preserve_context';
ed7ab0f4 10use Try::Tiny;
00a28188 11use List::Util 'first';
fd323bf1 12use namespace::clean;
18360aed 13
6a247f33 14__PACKAGE__->sql_limit_dialect ('RowNum');
2b8cc2f2 15__PACKAGE__->sql_quote_char ('"');
5e782048 16__PACKAGE__->sql_maker_class('DBIx::Class::SQLMaker::Oracle');
17__PACKAGE__->datetime_parser_type('DateTime::Format::Oracle');
18
19sub __cache_queries_with_max_lob_parts { 2 }
6a247f33 20
7137528d 21=head1 NAME
22
7a84c41b 23DBIx::Class::Storage::DBI::Oracle::Generic - Oracle Support for DBIx::Class
7137528d 24
25=head1 SYNOPSIS
26
d88ecca6 27 # In your result (table) classes
28 use base 'DBIx::Class::Core';
2e46b6eb 29 __PACKAGE__->add_columns({ id => { sequence => 'mysequence', auto_nextval => 1 } });
7137528d 30 __PACKAGE__->set_primary_key('id');
7137528d 31
c0024355 32 # Somewhere in your Code
33 # add some data to a table with a hierarchical relationship
34 $schema->resultset('Person')->create ({
35 firstname => 'foo',
36 lastname => 'bar',
37 children => [
38 {
39 firstname => 'child1',
40 lastname => 'bar',
41 children => [
42 {
43 firstname => 'grandchild',
44 lastname => 'bar',
45 }
46 ],
47 },
48 {
49 firstname => 'child2',
50 lastname => 'bar',
51 },
52 ],
53 });
54
55 # select from the hierarchical relationship
56 my $rs = $schema->resultset('Person')->search({},
57 {
58 'start_with' => { 'firstname' => 'foo', 'lastname' => 'bar' },
e6600283 59 'connect_by' => { 'parentid' => { '-prior' => { -ident => 'personid' } },
25ca709b 60 'order_siblings_by' => { -asc => 'name' },
c0024355 61 };
62 );
63
64 # this will select the whole tree starting from person "foo bar", creating
65 # following query:
66 # SELECT
67 # me.persionid me.firstname, me.lastname, me.parentid
68 # FROM
69 # person me
70 # START WITH
71 # firstname = 'foo' and lastname = 'bar'
72 # CONNECT BY
e6600283 73 # parentid = prior personid
c0024355 74 # ORDER SIBLINGS BY
75 # firstname ASC
76
7137528d 77=head1 DESCRIPTION
78
6c0230de 79This class implements base Oracle support. The subclass
80L<DBIx::Class::Storage::DBI::Oracle::WhereJoins> is for C<(+)> joins in Oracle
86b23415 81versions before 9.0.
7137528d 82
83=head1 METHODS
84
85=cut
86
bf51641f 87sub _determine_supports_insert_returning {
88 my $self = shift;
89
90# TODO find out which version supports the RETURNING syntax
91# 8i has it and earlier docs are a 404 on oracle.com
92
93 return 1
94 if $self->_server_info->{normalized_dbms_version} >= 8.001;
95
96 return 0;
97}
98
99__PACKAGE__->_use_insert_returning_bound (1);
100
dd2600c6 101sub deployment_statements {
102 my $self = shift;;
103 my ($schema, $type, $version, $dir, $sqltargs, @rest) = @_;
104
105 $sqltargs ||= {};
dd2600c6 106
96736321 107 if (
108 ! exists $sqltargs->{producer_args}{oracle_version}
109 and
110 my $dver = $self->_server_info->{dbms_version}
111 ) {
112 $sqltargs->{producer_args}{oracle_version} = $dver;
113 }
a4433d8e 114
38aead8e 115 $self->next::method($schema, $type, $version, $dir, $sqltargs, @rest);
dd2600c6 116}
117
18360aed 118sub _dbh_last_insert_id {
2e46b6eb 119 my ($self, $dbh, $source, @columns) = @_;
120 my @ids = ();
121 foreach my $col (@columns) {
122 my $seq = ($source->column_info($col)->{sequence} ||= $self->get_autoinc_seq($source,$col));
07cda1c5 123 my $id = $self->_sequence_fetch( 'CURRVAL', $seq );
2e46b6eb 124 push @ids, $id;
125 }
126 return @ids;
18360aed 127}
128
129sub _dbh_get_autoinc_seq {
130 my ($self, $dbh, $source, $col) = @_;
131
032b2366 132 my $sql_maker = $self->sql_maker;
07cda1c5 133 my ($ql, $qr) = map { $_ ? (quotemeta $_) : '' } $sql_maker->_quote_chars;
cb464582 134
e6dd7b42 135 my $source_name;
032b2366 136 if ( ref $source->name eq 'SCALAR' ) {
137 $source_name = ${$source->name};
07cda1c5 138
139 # the ALL_TRIGGERS match further on is case sensitive - thus uppercase
140 # stuff unless it is already quoted
141 $source_name = uc ($source_name) if $source_name !~ /\"/;
e6dd7b42 142 }
143 else {
032b2366 144 $source_name = $source->name;
07cda1c5 145 $source_name = uc($source_name) unless $ql;
e6dd7b42 146 }
38aead8e 147
032b2366 148 # trigger_body is a LONG
149 local $dbh->{LongReadLen} = 64 * 1024 if ($dbh->{LongReadLen} < 64 * 1024);
150
151 # disable default bindtype
152 local $sql_maker->{bindtype} = 'normal';
153
154 # look up the correct sequence automatically
07cda1c5 155 my ( $schema, $table ) = $source_name =~ /( (?:${ql})? \w+ (?:${qr})? ) \. ( (?:${ql})? \w+ (?:${qr})? )/x;
a6646e1b 156
157 # if no explicit schema was requested - use the default schema (which in the case of Oracle is the db user)
fcb52f08 158 $schema ||= \'= USER';
a6646e1b 159
032b2366 160 my ($sql, @bind) = $sql_maker->select (
161 'ALL_TRIGGERS',
07cda1c5 162 [qw/TRIGGER_BODY TABLE_OWNER TRIGGER_NAME/],
032b2366 163 {
630eee41 164 OWNER => $schema,
07cda1c5 165 TABLE_NAME => $table || $source_name,
166 TRIGGERING_EVENT => { -like => '%INSERT%' }, # this will also catch insert_or_update
167 TRIGGER_TYPE => { -like => '%BEFORE%' }, # we care only about 'before' triggers
168 STATUS => 'ENABLED',
032b2366 169 },
170 );
e6dd7b42 171
6f5f880d 172 # to find all the triggers that mention the column in question a simple
173 # regex grep since the trigger_body above is a LONG and hence not searchable
630eee41 174 # via -like
6f5f880d 175 my @triggers = ( map
176 { my %inf; @inf{qw/body schema name/} = @$_; \%inf }
177 ( grep
07cda1c5 178 { $_->[0] =~ /\:new\.${ql}${col}${qr} | \:new\.$col/xi }
6f5f880d 179 @{ $dbh->selectall_arrayref( $sql, {}, @bind ) }
180 )
181 );
182
630eee41 183 # extract all sequence names mentioned in each trigger, throw away
184 # triggers without apparent sequences
185 @triggers = map {
186 my @seqs = $_->{body} =~ / ( [\.\w\"\-]+ ) \. nextval /xig;
187 @seqs
188 ? { %$_, sequences => \@seqs }
189 : ()
190 ;
191 } @triggers;
6f5f880d 192
193 my $chosen_trigger;
194
195 # if only one trigger matched things are easy
196 if (@triggers == 1) {
197
198 if ( @{$triggers[0]{sequences}} == 1 ) {
199 $chosen_trigger = $triggers[0];
200 }
201 else {
202 $self->throw_exception( sprintf (
e705f529 203 "Unable to introspect trigger '%s' for column '%s.%s' (references multiple sequences). "
6f5f880d 204 . "You need to specify the correct 'sequence' explicitly in '%s's column_info.",
205 $triggers[0]{name},
206 $source_name,
207 $col,
208 $col,
209 ) );
210 }
211 }
212 # got more than one matching trigger - see if we can narrow it down
213 elsif (@triggers > 1) {
df6e3f5c 214
6f5f880d 215 my @candidates = grep
216 { $_->{body} =~ / into \s+ \:new\.$col /xi }
217 @triggers
218 ;
df6e3f5c 219
6f5f880d 220 if (@candidates == 1 && @{$candidates[0]{sequences}} == 1) {
221 $chosen_trigger = $candidates[0];
df6e3f5c 222 }
6f5f880d 223 else {
224 $self->throw_exception( sprintf (
e705f529 225 "Unable to reliably select a BEFORE INSERT trigger for column '%s.%s' (possibilities: %s). "
6f5f880d 226 . "You need to specify the correct 'sequence' explicitly in '%s's column_info.",
227 $source_name,
228 $col,
229 ( join ', ', map { "'$_->{name}'" } @triggers ),
230 $col,
231 ) );
232 }
233 }
234
235 if ($chosen_trigger) {
236 my $seq_name = $chosen_trigger->{sequences}[0];
237
238 $seq_name = "$chosen_trigger->{schema}.$seq_name"
239 unless $seq_name =~ /\./;
df6e3f5c 240
07cda1c5 241 return \$seq_name if $seq_name =~ /\"/; # may already be quoted in-trigger
df6e3f5c 242 return $seq_name;
18360aed 243 }
6f5f880d 244
245 $self->throw_exception( sprintf (
e705f529 246 "No suitable BEFORE INSERT triggers found for column '%s.%s'. "
6f5f880d 247 . "You need to specify the correct 'sequence' explicitly in '%s's column_info.",
248 $source_name,
249 $col,
250 $col,
251 ));
18360aed 252}
253
2e46b6eb 254sub _sequence_fetch {
255 my ( $self, $type, $seq ) = @_;
07cda1c5 256
257 # use the maker to leverage quoting settings
e6f3272b 258 my $sth = $self->_dbh->prepare_cached(
259 $self->sql_maker->select('DUAL', [ ref $seq ? \"$$seq.$type" : "$seq.$type" ] )
260 );
261 $sth->execute;
262 my ($id) = $sth->fetchrow_array;
263 $sth->finish;
2e46b6eb 264 return $id;
265}
266
6dc4be0f 267sub _ping {
c2481821 268 my $self = shift;
7ba7a57d 269
6dc4be0f 270 my $dbh = $self->_dbh or return 0;
7ba7a57d 271
6dc4be0f 272 local $dbh->{RaiseError} = 1;
ecdf1ac8 273 local $dbh->{PrintError} = 0;
c2d7baef 274
52b420dd 275 return try {
ecdf1ac8 276 $dbh->do('select 1 from dual');
52b420dd 277 1;
ed7ab0f4 278 } catch {
52b420dd 279 0;
6dc4be0f 280 };
c2481821 281}
282
d789fa99 283sub _dbh_execute {
9930caaf 284 #my ($self, $dbh, $sql, $bind, $bind_attrs) = @_;
7d534e68 285 my ($self, $sql, $bind) = @_[0,2,3];
a6ae092b 286
4b8a53ea 287 # Turn off sth caching for multi-part LOBs. See _prep_for_execute below
a6ae092b 288 local $self->{disable_sth_caching} = 1 if first {
289 ($_->[0]{_ora_lob_autosplit_part}||0)
290 >
291 (__cache_queries_with_max_lob_parts - 1)
292 } @$bind;
d789fa99 293
4f661051 294 my $next = $self->next::can;
87560ef9 295
a6ae092b 296 # if we are already in a txn we can't retry anything
297 return shift->$next(@_)
298 if $self->transaction_depth;
299
7d534e68 300 # cheat the blockrunner we are just about to create
301 # we do want to rerun things regardless of outer state
a6ae092b 302 local $self->{_in_do_block};
303
304 return DBIx::Class::Storage::BlockRunner->new(
305 storage => $self,
a6ae092b 306 wrap_txn => 0,
307 retry_handler => sub {
308 # ORA-01003: no statement parsed (someone changed the table somehow,
309 # invalidating your cursor.)
7d534e68 310 if (
311 $_[0]->failed_attempt_count == 1
312 and
313 $_[0]->last_exception =~ /ORA-01003/
314 and
315 my $dbh = $_[0]->storage->_dbh
316 ) {
317 delete $dbh->{CachedKids}{$sql};
318 return 1;
319 }
320 else {
321 return 0;
52b420dd 322 }
a6ae092b 323 },
7d534e68 324 )->run( $next, @_ );
d789fa99 325}
326
52cef7e3 327sub _dbh_execute_for_fetch {
a5a27e7a 328 #my ($self, $sth, $tuple_status, @extra) = @_;
329
52cef7e3 330 # DBD::Oracle warns loudly on partial execute_for_fetch failures
a5a27e7a 331 local $_[1]->{PrintWarn} = 0;
332
333 shift->next::method(@_);
334}
335
7137528d 336=head2 get_autoinc_seq
337
338Returns the sequence name for an autoincrement column
339
340=cut
341
18360aed 342sub get_autoinc_seq {
343 my ($self, $source, $col) = @_;
d4daee7b 344
373940e1 345 $self->dbh_do('_dbh_get_autoinc_seq', $source, $col);
18360aed 346}
347
8f7e044c 348=head2 datetime_parser_type
349
350This sets the proper DateTime::Format module for use with
351L<DBIx::Class::InflateColumn::DateTime>.
352
9900b569 353=head2 connect_call_datetime_setup
d2a3958e 354
355Used as:
356
9900b569 357 on_connect_call => 'datetime_setup'
d2a3958e 358
8384a713 359In L<connect_info|DBIx::Class::Storage::DBI/connect_info> to set the session nls
360date, and timestamp values for use with L<DBIx::Class::InflateColumn::DateTime>
361and the necessary environment variables for L<DateTime::Format::Oracle>, which
362is used by it.
d2a3958e 363
82f6f45f 364Maximum allowable precision is used, unless the environment variables have
365already been set.
d2a3958e 366
9900b569 367These are the defaults used:
368
369 $ENV{NLS_DATE_FORMAT} ||= 'YYYY-MM-DD HH24:MI:SS';
370 $ENV{NLS_TIMESTAMP_FORMAT} ||= 'YYYY-MM-DD HH24:MI:SS.FF';
371 $ENV{NLS_TIMESTAMP_TZ_FORMAT} ||= 'YYYY-MM-DD HH24:MI:SS.FF TZHTZM';
372
d9e53b85 373To get more than second precision with L<DBIx::Class::InflateColumn::DateTime>
374for your timestamps, use something like this:
375
376 use Time::HiRes 'time';
377 my $ts = DateTime->from_epoch(epoch => time);
378
d2a3958e 379=cut
380
9900b569 381sub connect_call_datetime_setup {
d2a3958e 382 my $self = shift;
d2a3958e 383
384 my $date_format = $ENV{NLS_DATE_FORMAT} ||= 'YYYY-MM-DD HH24:MI:SS';
385 my $timestamp_format = $ENV{NLS_TIMESTAMP_FORMAT} ||=
386 'YYYY-MM-DD HH24:MI:SS.FF';
387 my $timestamp_tz_format = $ENV{NLS_TIMESTAMP_TZ_FORMAT} ||=
388 'YYYY-MM-DD HH24:MI:SS.FF TZHTZM';
389
7a84c41b 390 $self->_do_query(
d7a58a29 391 "alter session set nls_date_format = '$date_format'"
392 );
7a84c41b 393 $self->_do_query(
d7a58a29 394 "alter session set nls_timestamp_format = '$timestamp_format'"
395 );
7a84c41b 396 $self->_do_query(
d7a58a29 397 "alter session set nls_timestamp_tz_format='$timestamp_tz_format'"
398 );
d2a3958e 399}
400
0e773352 401### Note originally by Ron "Quinn" Straight <quinnfazigu@gmail.org>
402### http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git;a=commitdiff;h=5db2758de644d53e07cd3e05f0e9037bf40116fc
403#
404# Handle LOB types in Oracle. Under a certain size (4k?), you can get away
405# with the driver assuming your input is the deprecated LONG type if you
406# encode it as a hex string. That ain't gonna fly at larger values, where
407# you'll discover you have to do what this does.
408#
409# This method had to be overridden because we need to set ora_field to the
410# actual column, and that isn't passed to the call (provided by Storage) to
411# bind_attribute_by_data_type.
412#
413# According to L<DBD::Oracle>, the ora_field isn't always necessary, but
414# adding it doesn't hurt, and will save your bacon if you're modifying a
415# table with more than one LOB column.
416#
417sub _dbi_attrs_for_bind {
418 my ($self, $ident, $bind) = @_;
00a28188 419
0e773352 420 my $attrs = $self->next::method($ident, $bind);
421
422 for my $i (0 .. $#$attrs) {
423 if (keys %{$attrs->[$i]||{}} and my $col = $bind->[$i][0]{dbic_colname}) {
424 $attrs->[$i]{ora_field} = $col;
425 }
426 }
5db2758d 427
0e773352 428 $attrs;
429}
5db2758d 430
0e773352 431sub bind_attribute_by_data_type {
432 my ($self, $dt) = @_;
433
8892d8e5 434 if ($self->_is_lob_type($dt)) {
435
436 # this is a hot-ish codepath, store an escape-flag in the DBD namespace, so that
437 # things like Class::Unload work (unlikely but possible)
438 unless ($DBD::Oracle::__DBIC_DBD_VERSION_CHECK_OK__) {
439
440 # no earlier - no later
441 if ($DBD::Oracle::VERSION eq '1.23') {
442 $self->throw_exception(
443 "BLOB/CLOB support in DBD::Oracle == 1.23 is broken, use an earlier or later ".
444 "version (https://rt.cpan.org/Public/Bug/Display.html?id=46016)"
445 );
446 }
447
448 $DBD::Oracle::__DBIC_DBD_VERSION_CHECK_OK__ = 1;
0e773352 449 }
5db2758d 450
0e773352 451 return {
452 ora_type => $self->_is_text_lob_type($dt)
d7a58a29 453 ? DBD::Oracle::ORA_CLOB()
454 : DBD::Oracle::ORA_BLOB()
0e773352 455 };
d7a58a29 456 }
8892d8e5 457 else {
458 return undef;
459 }
5db2758d 460}
461
00a28188 462# Handle blob columns in WHERE.
463#
464# For equality comparisons:
465#
466# We split data intended for comparing to a LOB into 2000 character chunks and
467# compare them using dbms_lob.substr on the LOB column.
468#
469# We turn off DBD::Oracle LOB binds for these partial LOB comparisons by passing
470# dbd_attrs => undef, because these are regular varchar2 comparisons and
471# otherwise the query will fail.
472#
473# Since the most common comparison size is likely to be under 4000 characters
474# (TEXT comparisons previously deployed to other RDBMSes) we disable
475# prepare_cached for queries with more than two part comparisons to a LOB
476# column. This is done in _dbh_execute (above) which was previously overridden
477# to gracefully recover from an Oracle error. This is to be careful to not
478# exhaust your application's open cursor limit.
479#
480# See:
481# http://itcareershift.com/blog1/2011/02/21/oracle-max-number-of-open-cursors-complete-reference-for-the-new-oracle-dba/
482# on the open_cursor limit.
483#
484# For everything else:
485#
486# We assume that everything that is not a LOB comparison, will most likely be a
487# LIKE query or some sort of function invocation. This may prove to be a naive
488# assumption in the future, but for now it should cover the two most likely
489# things users would want to do with a BLOB or CLOB, an equality test or a LIKE
490# query (on a CLOB.)
491#
492# For these expressions, the bind must NOT have the attributes of a LOB bind for
493# DBD::Oracle, otherwise the query will fail. This is done by passing
494# dbd_attrs => undef.
495
496sub _prep_for_execute {
497 my $self = shift;
498 my ($op) = @_;
499
00819de0 500 return $self->next::method(@_)
501 if $op eq 'insert';
00a28188 502
00819de0 503 my ($sql, $bind) = $self->next::method(@_);
00a28188 504
00819de0 505 my $lob_bind_indices = { map {
506 (
5e782048 507 $bind->[$_][0]{sqlt_datatype}
00819de0 508 and
509 $self->_is_lob_type($bind->[$_][0]{sqlt_datatype})
510 ) ? ( $_ => 1 ) : ()
511 } ( 0 .. $#$bind ) };
00a28188 512
00819de0 513 return ($sql, $bind) unless %$lob_bind_indices;
00a28188 514
00819de0 515 my ($final_sql, @final_binds);
516 if ($op eq 'update') {
e705f529 517 $self->throw_exception('Update with complex WHERE clauses involving BLOB columns currently not supported')
5e782048 518 if $sql =~ /\bWHERE\b .+ \bWHERE\b/xs;
519
e12571af 520 my $where_sql;
521 ($final_sql, $where_sql) = $sql =~ /^ (.+?) ( \bWHERE\b .+) /xs;
00819de0 522
523 if (my $set_bind_count = $final_sql =~ y/?//) {
5e782048 524
00819de0 525 delete $lob_bind_indices->{$_} for (0 .. ($set_bind_count - 1));
5e782048 526
00819de0 527 # bail if only the update part contains blobs
528 return ($sql, $bind) unless %$lob_bind_indices;
529
530 @final_binds = splice @$bind, 0, $set_bind_count;
531 $lob_bind_indices = { map
532 { $_ - $set_bind_count => $lob_bind_indices->{$_} }
533 keys %$lob_bind_indices
534 };
535 }
e12571af 536
537 # if we got that far - assume the where SQL is all we got
538 # (the first part is already shoved into $final_sql)
539 $sql = $where_sql;
5e782048 540 }
00819de0 541 elsif ($op ne 'select' and $op ne 'delete') {
5e782048 542 $self->throw_exception("Unsupported \$op: $op");
543 }
544
00819de0 545 my @sql_parts = split /\?/, $sql;
546
5e782048 547 my $col_equality_re = qr/ (?<=\s) ([\w."]+) (\s*=\s*) $/x;
548
549 for my $b_idx (0 .. $#$bind) {
550 my $bound = $bind->[$b_idx];
551
00819de0 552 if (
553 $lob_bind_indices->{$b_idx}
554 and
555 my ($col, $eq) = $sql_parts[0] =~ $col_equality_re
556 ) {
557 my $data = $bound->[1];
00a28188 558
00819de0 559 $data = "$data" if ref $data;
00a28188 560
00819de0 561 my @parts = unpack '(a2000)*', $data;
00a28188 562
00819de0 563 my @sql_frag;
00a28188 564
00819de0 565 for my $idx (0..$#parts) {
566 push @sql_frag, sprintf (
567 'UTL_RAW.CAST_TO_VARCHAR2(RAWTOHEX(DBMS_LOB.SUBSTR(%s, 2000, %d))) = ?',
568 $col, ($idx*2000 + 1),
569 );
570 }
00a28188 571
00819de0 572 my $sql_frag = '( ' . (join ' AND ', @sql_frag) . ' )';
00a28188 573
00819de0 574 $sql_parts[0] =~ s/$col_equality_re/$sql_frag/;
00a28188 575
00819de0 576 $final_sql .= shift @sql_parts;
00a28188 577
00819de0 578 for my $idx (0..$#parts) {
579 push @final_binds, [
00a28188 580 {
581 %{ $bound->[0] },
00819de0 582 _ora_lob_autosplit_part => $idx,
00a28188 583 dbd_attrs => undef,
584 },
00819de0 585 $parts[$idx]
00a28188 586 ];
587 }
588 }
589 else {
00819de0 590 $final_sql .= shift(@sql_parts) . '?';
591 push @final_binds, $lob_bind_indices->{$b_idx}
592 ? [
593 {
594 %{ $bound->[0] },
595 dbd_attrs => undef,
596 },
597 $bound->[1],
598 ] : $bound
599 ;
00a28188 600 }
601 }
5e782048 602
603 if (@sql_parts > 1) {
604 carp "There are more placeholders than binds, this should not happen!";
605 @sql_parts = join ('?', @sql_parts);
606 }
607
00819de0 608 $final_sql .= $sql_parts[0];
00a28188 609
00819de0 610 return ($final_sql, \@final_binds);
00a28188 611}
612
613# Savepoints stuff.
614
90d7422f 615sub _exec_svp_begin {
d7a58a29 616 my ($self, $name) = @_;
90d7422f 617 $self->_dbh->do("SAVEPOINT $name");
1816be4f 618}
619
281719d2 620# Oracle automatically releases a savepoint when you start another one with the
621# same name.
90d7422f 622sub _exec_svp_release { 1 }
281719d2 623
90d7422f 624sub _exec_svp_rollback {
d7a58a29 625 my ($self, $name) = @_;
90d7422f 626 $self->_dbh->do("ROLLBACK TO SAVEPOINT $name")
281719d2 627}
628
6c0230de 629=head2 relname_to_table_alias
630
631L<DBIx::Class> uses L<DBIx::Class::Relationship> names as table aliases in
632queries.
633
634Unfortunately, Oracle doesn't support identifiers over 30 chars in length, so
af0edca1 635the L<DBIx::Class::Relationship> name is shortened and appended with half of an
636MD5 hash.
6c0230de 637
638See L<DBIx::Class::Storage/"relname_to_table_alias">.
639
640=cut
641
642sub relname_to_table_alias {
643 my $self = shift;
644 my ($relname, $join_count) = @_;
645
646 my $alias = $self->next::method(@_);
647
19c4cc62 648 # we need to shorten here in addition to the shortening in SQLA itself,
d07f715d 649 # since the final relnames are crucial for the join optimizer
19c4cc62 650 return $self->sql_maker->_shorten_identifier($alias);
6c0230de 651}
652
6c0bb6a7 653=head2 with_deferred_fk_checks
654
655Runs a coderef between:
656
657 alter session set constraints = deferred
658 ...
659 alter session set constraints = immediate
660
b7b18f32 661to defer foreign key checks.
662
663Constraints must be declared C<DEFERRABLE> for this to work.
6c0bb6a7 664
665=cut
666
667sub with_deferred_fk_checks {
668 my ($self, $sub) = @_;
b7b18f32 669
670 my $txn_scope_guard = $self->txn_scope_guard;
671
6c0bb6a7 672 $self->_do_query('alter session set constraints = deferred');
54161a15 673
b7b18f32 674 my $sg = Scope::Guard->new(sub {
675 $self->_do_query('alter session set constraints = immediate');
676 });
281719d2 677
6298a324 678 return
679 preserve_context { $sub->() } after => sub { $txn_scope_guard->commit };
281719d2 680}
681
c0024355 682=head1 ATTRIBUTES
683
684Following additional attributes can be used in resultsets.
685
6b2fbbf0 686=head2 connect_by or connect_by_nocycle
c0024355 687
688=over 4
689
690=item Value: \%connect_by
691
692=back
693
694A hashref of conditions used to specify the relationship between parent rows
695and child rows of the hierarchy.
696
6b2fbbf0 697
c0024355 698 connect_by => { parentid => 'prior personid' }
699
700 # adds a connect by statement to the query:
701 # SELECT
702 # me.persionid me.firstname, me.lastname, me.parentid
703 # FROM
704 # person me
705 # CONNECT BY
706 # parentid = prior persionid
8273e845 707
c0024355 708
6b2fbbf0 709 connect_by_nocycle => { parentid => 'prior personid' }
2ba03b16 710
6b2fbbf0 711 # adds a connect by statement to the query:
712 # SELECT
713 # me.persionid me.firstname, me.lastname, me.parentid
714 # FROM
715 # person me
716 # CONNECT BY NOCYCLE
717 # parentid = prior persionid
2ba03b16 718
719
c0024355 720=head2 start_with
721
722=over 4
723
724=item Value: \%condition
725
726=back
727
728A hashref of conditions which specify the root row(s) of the hierarchy.
729
730It uses the same syntax as L<DBIx::Class::ResultSet/search>
731
732 start_with => { firstname => 'Foo', lastname => 'Bar' }
733
734 # SELECT
735 # me.persionid me.firstname, me.lastname, me.parentid
736 # FROM
737 # person me
738 # START WITH
739 # firstname = 'foo' and lastname = 'bar'
740 # CONNECT BY
741 # parentid = prior persionid
742
743=head2 order_siblings_by
744
745=over 4
746
747=item Value: ($order_siblings_by | \@order_siblings_by)
748
749=back
750
751Which column(s) to order the siblings by.
752
753It uses the same syntax as L<DBIx::Class::ResultSet/order_by>
754
755 'order_siblings_by' => 'firstname ASC'
756
757 # SELECT
758 # me.persionid me.firstname, me.lastname, me.parentid
759 # FROM
760 # person me
761 # CONNECT BY
762 # parentid = prior persionid
763 # ORDER SIBLINGS BY
764 # firstname ASC
765
7a84c41b 766=head1 AUTHOR
18360aed 767
00a28188 768See L<DBIx::Class/AUTHOR> and L<DBIx::Class/CONTRIBUTORS>.
18360aed 769
770=head1 LICENSE
771
772You may distribute this code under the same terms as Perl itself.
773
774=cut
7137528d 775
7761;
00a28188 777# vim:sts=2 sw=2: