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