SQLMaker is a proper C3-enabled class, do not use SUPER::
[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
261 my $sql_maker = $self->sql_maker;
262 my ($id) = $self->_get_dbh->selectrow_array ($sql_maker->select('DUAL', [ ref $seq ? \"$$seq.$type" : "$seq.$type" ] ) );
2e46b6eb 263 return $id;
264}
265
6dc4be0f 266sub _ping {
c2481821 267 my $self = shift;
7ba7a57d 268
6dc4be0f 269 my $dbh = $self->_dbh or return 0;
7ba7a57d 270
6dc4be0f 271 local $dbh->{RaiseError} = 1;
ecdf1ac8 272 local $dbh->{PrintError} = 0;
c2d7baef 273
52b420dd 274 return try {
ecdf1ac8 275 $dbh->do('select 1 from dual');
52b420dd 276 1;
ed7ab0f4 277 } catch {
52b420dd 278 0;
6dc4be0f 279 };
c2481821 280}
281
d789fa99 282sub _dbh_execute {
0e773352 283 my ($self, $dbh, $sql, @args) = @_;
d789fa99 284
87560ef9 285 my (@res, $tried);
cca282b6 286 my $want = wantarray;
4f661051 287 my $next = $self->next::can;
87560ef9 288 do {
52b420dd 289 try {
00a28188 290 my $exec = sub {
291 # Turn off sth caching for multi-part LOBs. See _prep_for_execute above.
292 local $self->{disable_sth_caching} = 1
293 if first {
294 ($_->[0]{_ora_lob_autosplit_part}||0)
295 > (__cache_queries_with_max_lob_parts-1)
296 } @{ $args[0] };
297
298 $self->$next($dbh, $sql, @args)
299 };
dd415de8 300
cca282b6 301 if (!defined $want) {
dd415de8 302 $exec->();
303 }
cca282b6 304 elsif (! $want) {
dd415de8 305 $res[0] = $exec->();
306 }
307 else {
308 @res = $exec->();
309 }
87560ef9 310
311 $tried++;
52b420dd 312 }
313 catch {
87560ef9 314 if (! $tried and $_ =~ /ORA-01003/) {
0f0abc97 315 # ORA-01003: no statement parsed (someone changed the table somehow,
316 # invalidating your cursor.)
0f0abc97 317 delete $dbh->{CachedKids}{$sql};
d789fa99 318 }
52b420dd 319 else {
320 $self->throw_exception($_);
321 }
322 };
87560ef9 323 } while (! $tried++);
d789fa99 324
cca282b6 325 return wantarray ? @res : $res[0];
d789fa99 326}
327
a5a27e7a 328sub _dbh_execute_array {
329 #my ($self, $sth, $tuple_status, @extra) = @_;
330
331 # DBD::Oracle warns loudly on partial execute_array failures
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
423 for my $i (0 .. $#$attrs) {
424 if (keys %{$attrs->[$i]||{}} and my $col = $bind->[$i][0]{dbic_colname}) {
425 $attrs->[$i]{ora_field} = $col;
426 }
427 }
5db2758d 428
0e773352 429 $attrs;
430}
5db2758d 431
0e773352 432my $dbd_loaded;
433sub bind_attribute_by_data_type {
434 my ($self, $dt) = @_;
435
436 $dbd_loaded ||= do {
437 require DBD::Oracle;
438 if ($DBD::Oracle::VERSION eq '1.23') {
439 $self->throw_exception(
440 "BLOB/CLOB support in DBD::Oracle == 1.23 is broken, use an earlier or later ".
441 "version.\n\nSee: https://rt.cpan.org/Public/Bug/Display.html?id=46016\n"
442 );
443 }
444 1;
445 };
5db2758d 446
0e773352 447 if ($self->_is_lob_type($dt)) {
448 return {
449 ora_type => $self->_is_text_lob_type($dt)
d7a58a29 450 ? DBD::Oracle::ORA_CLOB()
451 : DBD::Oracle::ORA_BLOB()
0e773352 452 };
d7a58a29 453 }
5db2758d 454}
455
00a28188 456# Handle blob columns in WHERE.
457#
458# For equality comparisons:
459#
460# We split data intended for comparing to a LOB into 2000 character chunks and
461# compare them using dbms_lob.substr on the LOB column.
462#
463# We turn off DBD::Oracle LOB binds for these partial LOB comparisons by passing
464# dbd_attrs => undef, because these are regular varchar2 comparisons and
465# otherwise the query will fail.
466#
467# Since the most common comparison size is likely to be under 4000 characters
468# (TEXT comparisons previously deployed to other RDBMSes) we disable
469# prepare_cached for queries with more than two part comparisons to a LOB
470# column. This is done in _dbh_execute (above) which was previously overridden
471# to gracefully recover from an Oracle error. This is to be careful to not
472# exhaust your application's open cursor limit.
473#
474# See:
475# http://itcareershift.com/blog1/2011/02/21/oracle-max-number-of-open-cursors-complete-reference-for-the-new-oracle-dba/
476# on the open_cursor limit.
477#
478# For everything else:
479#
480# We assume that everything that is not a LOB comparison, will most likely be a
481# LIKE query or some sort of function invocation. This may prove to be a naive
482# assumption in the future, but for now it should cover the two most likely
483# things users would want to do with a BLOB or CLOB, an equality test or a LIKE
484# query (on a CLOB.)
485#
486# For these expressions, the bind must NOT have the attributes of a LOB bind for
487# DBD::Oracle, otherwise the query will fail. This is done by passing
488# dbd_attrs => undef.
489
490sub _prep_for_execute {
491 my $self = shift;
492 my ($op) = @_;
493
494 my ($sql, $bind) = $self->next::method(@_);
495
5e782048 496 return ($sql, $bind) if $op eq 'insert';
00a28188 497
5e782048 498 my $blob_bind_index;
499 for (0 .. $#$bind) {
500 $blob_bind_index->{$_} = 1 if $self->_is_lob_type(
501 $bind->[$_][0]{sqlt_datatype}
502 );
503 }
00a28188 504
5e782048 505 return ($sql, $bind) unless $blob_bind_index;
00a28188 506
5e782048 507 my (@sql_parts, $new_sql, @new_binds);
508
509 if ($op eq 'select' || $op eq 'delete') {
510 @sql_parts = split /\?/, $sql;
511 }
512 elsif ($op eq 'update') {
513 $self->throw_exception('Update with complex WHERE clauses currently not supported')
514 if $sql =~ /\bWHERE\b .+ \bWHERE\b/xs;
515
516 my ($set_part, $where_part) = $sql =~ /^ (.+?) ( \bWHERE\b .+) /xs;
517
518 my $set_bind_count = $set_part =~ y/?//;
519 @new_binds = splice @$bind, 0, $set_bind_count;
520
521 @sql_parts = split /\?/, $where_part;
522 $new_sql = $set_part;
523 }
524 else {
525 $self->throw_exception("Unsupported \$op: $op");
526 }
527
528 my $col_equality_re = qr/ (?<=\s) ([\w."]+) (\s*=\s*) $/x;
529
530 for my $b_idx (0 .. $#$bind) {
531 my $bound = $bind->[$b_idx];
532
533 if ($blob_bind_index->{$b_idx}) {
534 if (my ($col, $eq) = $sql_parts[0] =~ $col_equality_re) {
00a28188 535 my $data = $bound->[1];
536
537 $data = "$data" if ref $data;
538
539 my @parts = unpack '(a2000)*', $data;
540
541 my @sql_frag;
542
543 for my $idx (0..$#parts) {
5e782048 544 push @sql_frag, sprintf (
545 'UTL_RAW.CAST_TO_VARCHAR2(RAWTOHEX(DBMS_LOB.SUBSTR(%s, 2000, %d))) = ?',
546 $col, ($idx*2000 + 1),
547 );
00a28188 548 }
549
550 my $sql_frag = '( ' . (join ' AND ', @sql_frag) . ' )';
551
5e782048 552 $sql_parts[0] =~ s/$col_equality_re/$sql_frag/;
00a28188 553
5e782048 554 $new_sql .= shift @sql_parts;
00a28188 555
556 for my $idx (0..$#parts) {
557 push @new_binds, [
558 {
559 %{ $bound->[0] },
560 _ora_lob_autosplit_part => $idx,
561 dbd_attrs => undef,
562 },
563 $parts[$idx]
564 ];
565 }
566 }
567 else {
5e782048 568 $new_sql .= shift(@sql_parts) . '?';
00a28188 569
570 push @new_binds, [
571 {
572 %{ $bound->[0] },
573 dbd_attrs => undef,
574 },
575 $bound->[1],
576 ];
577 }
578 }
579 else {
5e782048 580 $new_sql .= shift(@sql_parts) . '?';
00a28188 581 push @new_binds, $bound;
582 }
583 }
5e782048 584
585 if (@sql_parts > 1) {
586 carp "There are more placeholders than binds, this should not happen!";
587 @sql_parts = join ('?', @sql_parts);
588 }
589
590 $new_sql .= $sql_parts[0];
00a28188 591
592 return ($new_sql, \@new_binds);
593}
594
595# Savepoints stuff.
596
90d7422f 597sub _exec_svp_begin {
d7a58a29 598 my ($self, $name) = @_;
90d7422f 599 $self->_dbh->do("SAVEPOINT $name");
1816be4f 600}
601
281719d2 602# Oracle automatically releases a savepoint when you start another one with the
603# same name.
90d7422f 604sub _exec_svp_release { 1 }
281719d2 605
90d7422f 606sub _exec_svp_rollback {
d7a58a29 607 my ($self, $name) = @_;
90d7422f 608 $self->_dbh->do("ROLLBACK TO SAVEPOINT $name")
281719d2 609}
610
6c0230de 611=head2 relname_to_table_alias
612
613L<DBIx::Class> uses L<DBIx::Class::Relationship> names as table aliases in
614queries.
615
616Unfortunately, Oracle doesn't support identifiers over 30 chars in length, so
af0edca1 617the L<DBIx::Class::Relationship> name is shortened and appended with half of an
618MD5 hash.
6c0230de 619
620See L<DBIx::Class::Storage/"relname_to_table_alias">.
621
622=cut
623
624sub relname_to_table_alias {
625 my $self = shift;
626 my ($relname, $join_count) = @_;
627
628 my $alias = $self->next::method(@_);
629
19c4cc62 630 # we need to shorten here in addition to the shortening in SQLA itself,
631 # since the final relnames are a crucial for the join optimizer
632 return $self->sql_maker->_shorten_identifier($alias);
6c0230de 633}
634
6c0bb6a7 635=head2 with_deferred_fk_checks
636
637Runs a coderef between:
638
639 alter session set constraints = deferred
640 ...
641 alter session set constraints = immediate
642
b7b18f32 643to defer foreign key checks.
644
645Constraints must be declared C<DEFERRABLE> for this to work.
6c0bb6a7 646
647=cut
648
649sub with_deferred_fk_checks {
650 my ($self, $sub) = @_;
b7b18f32 651
652 my $txn_scope_guard = $self->txn_scope_guard;
653
6c0bb6a7 654 $self->_do_query('alter session set constraints = deferred');
54161a15 655
b7b18f32 656 my $sg = Scope::Guard->new(sub {
657 $self->_do_query('alter session set constraints = immediate');
658 });
281719d2 659
6298a324 660 return
661 preserve_context { $sub->() } after => sub { $txn_scope_guard->commit };
281719d2 662}
663
c0024355 664=head1 ATTRIBUTES
665
666Following additional attributes can be used in resultsets.
667
6b2fbbf0 668=head2 connect_by or connect_by_nocycle
c0024355 669
670=over 4
671
672=item Value: \%connect_by
673
674=back
675
676A hashref of conditions used to specify the relationship between parent rows
677and child rows of the hierarchy.
678
6b2fbbf0 679
c0024355 680 connect_by => { parentid => 'prior personid' }
681
682 # adds a connect by statement to the query:
683 # SELECT
684 # me.persionid me.firstname, me.lastname, me.parentid
685 # FROM
686 # person me
687 # CONNECT BY
688 # parentid = prior persionid
6b2fbbf0 689
c0024355 690
6b2fbbf0 691 connect_by_nocycle => { parentid => 'prior personid' }
2ba03b16 692
6b2fbbf0 693 # adds a connect by statement to the query:
694 # SELECT
695 # me.persionid me.firstname, me.lastname, me.parentid
696 # FROM
697 # person me
698 # CONNECT BY NOCYCLE
699 # parentid = prior persionid
2ba03b16 700
701
c0024355 702=head2 start_with
703
704=over 4
705
706=item Value: \%condition
707
708=back
709
710A hashref of conditions which specify the root row(s) of the hierarchy.
711
712It uses the same syntax as L<DBIx::Class::ResultSet/search>
713
714 start_with => { firstname => 'Foo', lastname => 'Bar' }
715
716 # SELECT
717 # me.persionid me.firstname, me.lastname, me.parentid
718 # FROM
719 # person me
720 # START WITH
721 # firstname = 'foo' and lastname = 'bar'
722 # CONNECT BY
723 # parentid = prior persionid
724
725=head2 order_siblings_by
726
727=over 4
728
729=item Value: ($order_siblings_by | \@order_siblings_by)
730
731=back
732
733Which column(s) to order the siblings by.
734
735It uses the same syntax as L<DBIx::Class::ResultSet/order_by>
736
737 'order_siblings_by' => 'firstname ASC'
738
739 # SELECT
740 # me.persionid me.firstname, me.lastname, me.parentid
741 # FROM
742 # person me
743 # CONNECT BY
744 # parentid = prior persionid
745 # ORDER SIBLINGS BY
746 # firstname ASC
747
7a84c41b 748=head1 AUTHOR
18360aed 749
00a28188 750See L<DBIx::Class/AUTHOR> and L<DBIx::Class/CONTRIBUTORS>.
18360aed 751
752=head1 LICENSE
753
754You may distribute this code under the same terms as Perl itself.
755
756=cut
7137528d 757
7581;
00a28188 759# vim:sts=2 sw=2: