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