Factor SQL-standard deferred FK checks into a component
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / SetConstraintsDeferred.pm
1 package DBIx::Class::Storage::DBI::SetConstraintsDeferred;
2
3 use strict;
4 use warnings;
5
6 use base 'DBIx::Class::Storage::DBI';
7 use mro 'c3';
8
9 use Scope::Guard ();
10 use Context::Preserve 'preserve_context';
11
12 use namespace::clean;
13
14 =head1 NAME
15
16 DBIx::Class::Storage::DBI::SetConstraintsDeferred - Storage component for deferred constraints via C<SET CONSTRAINTS>
17
18 =head1 DESCRIPTION
19
20 This component implements L<DBIx::Class::Storage::DBI/with_deferred_fk_checks>
21 by wrapping the the coderef in C<SET CONSTRAINTS ALL DEFERRED> and
22 C<SET CONSTRAINTS ALL IMMEDIATE>.
23
24 =cut
25
26 sub with_deferred_fk_checks {
27   my ($self, $sub) = @_;
28
29   my $txn_scope_guard = $self->txn_scope_guard;
30
31   $self->_do_query('SET CONSTRAINTS ALL DEFERRED');
32
33   return preserve_context {
34     my $inner_self = $self; # avoid nested closure leak on 5.8
35     my $sg = Scope::Guard->new(sub {
36       $inner_self->_do_query('SET CONSTRAINTS ALL IMMEDIATE');
37     });
38     $sub->()
39   } after => sub { $txn_scope_guard->commit };
40 }
41
42 =head1 FURTHER QUESTIONS?
43
44 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
45
46 =head1 COPYRIGHT AND LICENSE
47
48 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
49 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
50 redistribute it and/or modify it under the same terms as the
51 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
52
53 =cut
54
55 1;