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