/
DBI.pm
2690 lines (2031 loc) · 67.9 KB
/
DBI.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package DBIx::Class::Storage::DBI;
# -*- mode: cperl; cperl-indent-level: 2 -*-
use strict;
use warnings;
use base qw/DBIx::Class::Storage::DBIHacks DBIx::Class::Storage/;
use mro 'c3';
use Carp::Clan qw/^DBIx::Class/;
use DBI;
use DBIx::Class::Storage::DBI::Cursor;
use DBIx::Class::Storage::Statistics;
use Scalar::Util qw/refaddr weaken reftype blessed/;
use Data::Dumper::Concise 'Dumper';
use Sub::Name 'subname';
use Try::Tiny;
use File::Path 'make_path';
use namespace::clean;
__PACKAGE__->mk_group_accessors('simple' => qw/
_connect_info _dbi_connect_info _dbic_connect_attributes _driver_determined
_dbh _server_info_hash _conn_pid _conn_tid _sql_maker _sql_maker_opts
transaction_depth _dbh_autocommit savepoints
/);
# the values for these accessors are picked out (and deleted) from
# the attribute hashref passed to connect_info
my @storage_options = qw/
on_connect_call on_disconnect_call on_connect_do on_disconnect_do
disable_sth_caching unsafe auto_savepoint
/;
__PACKAGE__->mk_group_accessors('simple' => @storage_options);
# default cursor class, overridable in connect_info attributes
__PACKAGE__->cursor_class('DBIx::Class::Storage::DBI::Cursor');
__PACKAGE__->mk_group_accessors('inherited' => qw/
sql_maker_class
_supports_insert_returning
/);
__PACKAGE__->sql_maker_class('DBIx::Class::SQLAHacks');
# Each of these methods need _determine_driver called before itself
# in order to function reliably. This is a purely DRY optimization
my @rdbms_specific_methods = qw/
deployment_statements
sqlt_type
sql_maker
build_datetime_parser
datetime_parser_type
insert
insert_bulk
update
delete
select
select_single
/;
for my $meth (@rdbms_specific_methods) {
my $orig = __PACKAGE__->can ($meth)
or next;
no strict qw/refs/;
no warnings qw/redefine/;
*{__PACKAGE__ ."::$meth"} = subname $meth => sub {
if (not $_[0]->_driver_determined) {
$_[0]->_determine_driver;
goto $_[0]->can($meth);
}
$orig->(@_);
};
}
=head1 NAME
DBIx::Class::Storage::DBI - DBI storage handler
=head1 SYNOPSIS
my $schema = MySchema->connect('dbi:SQLite:my.db');
$schema->storage->debug(1);
my @stuff = $schema->storage->dbh_do(
sub {
my ($storage, $dbh, @args) = @_;
$dbh->do("DROP TABLE authors");
},
@column_list
);
$schema->resultset('Book')->search({
written_on => $schema->storage->datetime_parser->format_datetime(DateTime->now)
});
=head1 DESCRIPTION
This class represents the connection to an RDBMS via L<DBI>. See
L<DBIx::Class::Storage> for general information. This pod only
documents DBI-specific methods and behaviors.
=head1 METHODS
=cut
sub new {
my $new = shift->next::method(@_);
$new->transaction_depth(0);
$new->_sql_maker_opts({});
$new->{savepoints} = [];
$new->{_in_dbh_do} = 0;
$new->{_dbh_gen} = 0;
# read below to see what this does
$new->_arm_global_destructor;
$new;
}
# This is hack to work around perl shooting stuff in random
# order on exit(). If we do not walk the remaining storage
# objects in an END block, there is a *small but real* chance
# of a fork()ed child to kill the parent's shared DBI handle,
# *before perl reaches the DESTROY in this package*
# Yes, it is ugly and effective.
{
my %seek_and_destroy;
sub _arm_global_destructor {
my $self = shift;
my $key = Scalar::Util::refaddr ($self);
$seek_and_destroy{$key} = $self;
Scalar::Util::weaken ($seek_and_destroy{$key});
}
END {
local $?; # just in case the DBI destructor changes it somehow
# destroy just the object if not native to this process/thread
$_->_preserve_foreign_dbh for (grep
{ defined $_ }
values %seek_and_destroy
);
}
}
sub DESTROY {
my $self = shift;
# destroy just the object if not native to this process/thread
$self->_preserve_foreign_dbh;
# some databases need this to stop spewing warnings
if (my $dbh = $self->_dbh) {
try {
%{ $dbh->{CachedKids} } = ();
$dbh->disconnect;
};
}
$self->_dbh(undef);
}
sub _preserve_foreign_dbh {
my $self = shift;
return unless $self->_dbh;
$self->_verify_tid;
return unless $self->_dbh;
$self->_verify_pid;
}
# handle pid changes correctly - do not destroy parent's connection
sub _verify_pid {
my $self = shift;
return if ( defined $self->_conn_pid and $self->_conn_pid == $$ );
$self->_dbh->{InactiveDestroy} = 1;
$self->_dbh(undef);
$self->{_dbh_gen}++;
return;
}
# very similar to above, but seems to FAIL if I set InactiveDestroy
sub _verify_tid {
my $self = shift;
if ( ! defined $self->_conn_tid ) {
return; # no threads
}
elsif ( $self->_conn_tid == threads->tid ) {
return; # same thread
}
#$self->_dbh->{InactiveDestroy} = 1; # why does t/51threads.t fail...?
$self->_dbh(undef);
$self->{_dbh_gen}++;
return;
}
=head2 connect_info
This method is normally called by L<DBIx::Class::Schema/connection>, which
encapsulates its argument list in an arrayref before passing them here.
The argument list may contain:
=over
=item *
The same 4-element argument set one would normally pass to
L<DBI/connect>, optionally followed by
L<extra attributes|/DBIx::Class specific connection attributes>
recognized by DBIx::Class:
$connect_info_args = [ $dsn, $user, $password, \%dbi_attributes?, \%extra_attributes? ];
=item *
A single code reference which returns a connected
L<DBI database handle|DBI/connect> optionally followed by
L<extra attributes|/DBIx::Class specific connection attributes> recognized
by DBIx::Class:
$connect_info_args = [ sub { DBI->connect (...) }, \%extra_attributes? ];
=item *
A single hashref with all the attributes and the dsn/user/password
mixed together:
$connect_info_args = [{
dsn => $dsn,
user => $user,
password => $pass,
%dbi_attributes,
%extra_attributes,
}];
$connect_info_args = [{
dbh_maker => sub { DBI->connect (...) },
%dbi_attributes,
%extra_attributes,
}];
This is particularly useful for L<Catalyst> based applications, allowing the
following config (L<Config::General> style):
<Model::DB>
schema_class App::DB
<connect_info>
dsn dbi:mysql:database=test
user testuser
password TestPass
AutoCommit 1
</connect_info>
</Model::DB>
The C<dsn>/C<user>/C<password> combination can be substituted by the
C<dbh_maker> key whose value is a coderef that returns a connected
L<DBI database handle|DBI/connect>
=back
Please note that the L<DBI> docs recommend that you always explicitly
set C<AutoCommit> to either I<0> or I<1>. L<DBIx::Class> further
recommends that it be set to I<1>, and that you perform transactions
via our L<DBIx::Class::Schema/txn_do> method. L<DBIx::Class> will set it
to I<1> if you do not do explicitly set it to zero. This is the default
for most DBDs. See L</DBIx::Class and AutoCommit> for details.
=head3 DBIx::Class specific connection attributes
In addition to the standard L<DBI|DBI/ATTRIBUTES_COMMON_TO_ALL_HANDLES>
L<connection|DBI/Database_Handle_Attributes> attributes, DBIx::Class recognizes
the following connection options. These options can be mixed in with your other
L<DBI> connection attributes, or placed in a separate hashref
(C<\%extra_attributes>) as shown above.
Every time C<connect_info> is invoked, any previous settings for
these options will be cleared before setting the new ones, regardless of
whether any options are specified in the new C<connect_info>.
=over
=item on_connect_do
Specifies things to do immediately after connecting or re-connecting to
the database. Its value may contain:
=over
=item a scalar
This contains one SQL statement to execute.
=item an array reference
This contains SQL statements to execute in order. Each element contains
a string or a code reference that returns a string.
=item a code reference
This contains some code to execute. Unlike code references within an
array reference, its return value is ignored.
=back
=item on_disconnect_do
Takes arguments in the same form as L</on_connect_do> and executes them
immediately before disconnecting from the database.
Note, this only runs if you explicitly call L</disconnect> on the
storage object.
=item on_connect_call
A more generalized form of L</on_connect_do> that calls the specified
C<connect_call_METHOD> methods in your storage driver.
on_connect_do => 'select 1'
is equivalent to:
on_connect_call => [ [ do_sql => 'select 1' ] ]
Its values may contain:
=over
=item a scalar
Will call the C<connect_call_METHOD> method.
=item a code reference
Will execute C<< $code->($storage) >>
=item an array reference
Each value can be a method name or code reference.
=item an array of arrays
For each array, the first item is taken to be the C<connect_call_> method name
or code reference, and the rest are parameters to it.
=back
Some predefined storage methods you may use:
=over
=item do_sql
Executes a SQL string or a code reference that returns a SQL string. This is
what L</on_connect_do> and L</on_disconnect_do> use.
It can take:
=over
=item a scalar
Will execute the scalar as SQL.
=item an arrayref
Taken to be arguments to L<DBI/do>, the SQL string optionally followed by the
attributes hashref and bind values.
=item a code reference
Will execute C<< $code->($storage) >> and execute the return array refs as
above.
=back
=item datetime_setup
Execute any statements necessary to initialize the database session to return
and accept datetime/timestamp values used with
L<DBIx::Class::InflateColumn::DateTime>.
Only necessary for some databases, see your specific storage driver for
implementation details.
=back
=item on_disconnect_call
Takes arguments in the same form as L</on_connect_call> and executes them
immediately before disconnecting from the database.
Calls the C<disconnect_call_METHOD> methods as opposed to the
C<connect_call_METHOD> methods called by L</on_connect_call>.
Note, this only runs if you explicitly call L</disconnect> on the
storage object.
=item disable_sth_caching
If set to a true value, this option will disable the caching of
statement handles via L<DBI/prepare_cached>.
=item limit_dialect
Sets the limit dialect. This is useful for JDBC-bridge among others
where the remote SQL-dialect cannot be determined by the name of the
driver alone. See also L<SQL::Abstract::Limit>.
=item quote_char
Specifies what characters to use to quote table and column names. If
you use this you will want to specify L</name_sep> as well.
C<quote_char> expects either a single character, in which case is it
is placed on either side of the table/column name, or an arrayref of length
2 in which case the table/column name is placed between the elements.
For example under MySQL you should use C<< quote_char => '`' >>, and for
SQL Server you should use C<< quote_char => [qw/[ ]/] >>.
=item name_sep
This only needs to be used in conjunction with C<quote_char>, and is used to
specify the character that separates elements (schemas, tables, columns) from
each other. In most cases this is simply a C<.>.
The consequences of not supplying this value is that L<SQL::Abstract>
will assume DBIx::Class' uses of aliases to be complete column
names. The output will look like I<"me.name"> when it should actually
be I<"me"."name">.
=item unsafe
This Storage driver normally installs its own C<HandleError>, sets
C<RaiseError> and C<ShowErrorStatement> on, and sets C<PrintError> off on
all database handles, including those supplied by a coderef. It does this
so that it can have consistent and useful error behavior.
If you set this option to a true value, Storage will not do its usual
modifications to the database handle's attributes, and instead relies on
the settings in your connect_info DBI options (or the values you set in
your connection coderef, in the case that you are connecting via coderef).
Note that your custom settings can cause Storage to malfunction,
especially if you set a C<HandleError> handler that suppresses exceptions
and/or disable C<RaiseError>.
=item auto_savepoint
If this option is true, L<DBIx::Class> will use savepoints when nesting
transactions, making it possible to recover from failure in the inner
transaction without having to abort all outer transactions.
=item cursor_class
Use this argument to supply a cursor class other than the default
L<DBIx::Class::Storage::DBI::Cursor>.
=back
Some real-life examples of arguments to L</connect_info> and
L<DBIx::Class::Schema/connect>
# Simple SQLite connection
->connect_info([ 'dbi:SQLite:./foo.db' ]);
# Connect via subref
->connect_info([ sub { DBI->connect(...) } ]);
# Connect via subref in hashref
->connect_info([{
dbh_maker => sub { DBI->connect(...) },
on_connect_do => 'alter session ...',
}]);
# A bit more complicated
->connect_info(
[
'dbi:Pg:dbname=foo',
'postgres',
'my_pg_password',
{ AutoCommit => 1 },
{ quote_char => q{"}, name_sep => q{.} },
]
);
# Equivalent to the previous example
->connect_info(
[
'dbi:Pg:dbname=foo',
'postgres',
'my_pg_password',
{ AutoCommit => 1, quote_char => q{"}, name_sep => q{.} },
]
);
# Same, but with hashref as argument
# See parse_connect_info for explanation
->connect_info(
[{
dsn => 'dbi:Pg:dbname=foo',
user => 'postgres',
password => 'my_pg_password',
AutoCommit => 1,
quote_char => q{"},
name_sep => q{.},
}]
);
# Subref + DBIx::Class-specific connection options
->connect_info(
[
sub { DBI->connect(...) },
{
quote_char => q{`},
name_sep => q{@},
on_connect_do => ['SET search_path TO myschema,otherschema,public'],
disable_sth_caching => 1,
},
]
);
=cut
sub connect_info {
my ($self, $info) = @_;
return $self->_connect_info if !$info;
$self->_connect_info($info); # copy for _connect_info
$info = $self->_normalize_connect_info($info)
if ref $info eq 'ARRAY';
for my $storage_opt (keys %{ $info->{storage_options} }) {
my $value = $info->{storage_options}{$storage_opt};
$self->$storage_opt($value);
}
# Kill sql_maker/_sql_maker_opts, so we get a fresh one with only
# the new set of options
$self->_sql_maker(undef);
$self->_sql_maker_opts({});
for my $sql_maker_opt (keys %{ $info->{sql_maker_options} }) {
my $value = $info->{sql_maker_options}{$sql_maker_opt};
$self->_sql_maker_opts->{$sql_maker_opt} = $value;
}
my %attrs = (
%{ $self->_default_dbi_connect_attributes || {} },
%{ $info->{attributes} || {} },
);
my @args = @{ $info->{arguments} };
$self->_dbi_connect_info([@args,
%attrs && !(ref $args[0] eq 'CODE') ? \%attrs : ()]);
# FIXME - dirty:
# save attributes them in a separate accessor so they are always
# introspectable, even in case of a CODE $dbhmaker
$self->_dbic_connect_attributes (\%attrs);
return $self->_connect_info;
}
sub _normalize_connect_info {
my ($self, $info_arg) = @_;
my %info;
my @args = @$info_arg; # take a shallow copy for further mutilation
# combine/pre-parse arguments depending on invocation style
my %attrs;
if (ref $args[0] eq 'CODE') { # coderef with optional \%extra_attributes
%attrs = %{ $args[1] || {} };
@args = $args[0];
}
elsif (ref $args[0] eq 'HASH') { # single hashref (i.e. Catalyst config)
%attrs = %{$args[0]};
@args = ();
if (my $code = delete $attrs{dbh_maker}) {
@args = $code;
my @ignored = grep { delete $attrs{$_} } (qw/dsn user password/);
if (@ignored) {
carp sprintf (
'Attribute(s) %s in connect_info were ignored, as they can not be applied '
. "to the result of 'dbh_maker'",
join (', ', map { "'$_'" } (@ignored) ),
);
}
}
else {
@args = delete @attrs{qw/dsn user password/};
}
}
else { # otherwise assume dsn/user/password + \%attrs + \%extra_attrs
%attrs = (
% { $args[3] || {} },
% { $args[4] || {} },
);
@args = @args[0,1,2];
}
$info{arguments} = \@args;
my @storage_opts = grep exists $attrs{$_},
@storage_options, 'cursor_class';
@{ $info{storage_options} }{@storage_opts} =
delete @attrs{@storage_opts} if @storage_opts;
my @sql_maker_opts = grep exists $attrs{$_},
qw/limit_dialect quote_char name_sep/;
@{ $info{sql_maker_options} }{@sql_maker_opts} =
delete @attrs{@sql_maker_opts} if @sql_maker_opts;
$info{attributes} = \%attrs if %attrs;
return \%info;
}
sub _default_dbi_connect_attributes {
return {
AutoCommit => 1,
RaiseError => 1,
PrintError => 0,
};
}
=head2 on_connect_do
This method is deprecated in favour of setting via L</connect_info>.
=cut
=head2 on_disconnect_do
This method is deprecated in favour of setting via L</connect_info>.
=cut
sub _parse_connect_do {
my ($self, $type) = @_;
my $val = $self->$type;
return () if not defined $val;
my @res;
if (not ref($val)) {
push @res, [ 'do_sql', $val ];
} elsif (ref($val) eq 'CODE') {
push @res, $val;
} elsif (ref($val) eq 'ARRAY') {
push @res, map { [ 'do_sql', $_ ] } @$val;
} else {
$self->throw_exception("Invalid type for $type: ".ref($val));
}
return \@res;
}
=head2 dbh_do
Arguments: ($subref | $method_name), @extra_coderef_args?
Execute the given $subref or $method_name using the new exception-based
connection management.
The first two arguments will be the storage object that C<dbh_do> was called
on and a database handle to use. Any additional arguments will be passed
verbatim to the called subref as arguments 2 and onwards.
Using this (instead of $self->_dbh or $self->dbh) ensures correct
exception handling and reconnection (or failover in future subclasses).
Your subref should have no side-effects outside of the database, as
there is the potential for your subref to be partially double-executed
if the database connection was stale/dysfunctional.
Example:
my @stuff = $schema->storage->dbh_do(
sub {
my ($storage, $dbh, @cols) = @_;
my $cols = join(q{, }, @cols);
$dbh->selectrow_array("SELECT $cols FROM foo");
},
@column_list
);
=cut
sub dbh_do {
my $self = shift;
my $code = shift;
my $dbh = $self->_get_dbh;
return $self->$code($dbh, @_)
if ( $self->{_in_dbh_do} || $self->{transaction_depth} );
local $self->{_in_dbh_do} = 1;
# take a ref instead of a copy, to preserve coderef @_ aliasing semantics
my $args = \@_;
return try {
$self->$code ($dbh, @$args);
} catch {
$self->throw_exception($_) if $self->connected;
# We were not connected - reconnect and retry, but let any
# exception fall right through this time
carp "Retrying $code after catching disconnected exception: $_"
if $ENV{DBIC_DBIRETRY_DEBUG};
$self->_populate_dbh;
$self->$code($self->_dbh, @$args);
};
}
# This is basically a blend of dbh_do above and DBIx::Class::Storage::txn_do.
# It also informs dbh_do to bypass itself while under the direction of txn_do,
# via $self->{_in_dbh_do} (this saves some redundant eval and errorcheck, etc)
sub txn_do {
my $self = shift;
my $coderef = shift;
ref $coderef eq 'CODE' or $self->throw_exception
('$coderef must be a CODE reference');
return $coderef->(@_) if $self->{transaction_depth} && ! $self->auto_savepoint;
local $self->{_in_dbh_do} = 1;
my @result;
my $want_array = wantarray;
my $tried = 0;
while(1) {
my $exception;
# take a ref instead of a copy, to preserve coderef @_ aliasing semantics
my $args = \@_;
try {
$self->_get_dbh;
$self->txn_begin;
if($want_array) {
@result = $coderef->(@$args);
}
elsif(defined $want_array) {
$result[0] = $coderef->(@$args);
}
else {
$coderef->(@$args);
}
$self->txn_commit;
} catch {
$exception = $_;
};
if(! defined $exception) { return $want_array ? @result : $result[0] }
if($tried++ || $self->connected) {
my $rollback_exception;
try { $self->txn_rollback } catch { $rollback_exception = shift };
if(defined $rollback_exception) {
my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
$self->throw_exception($exception) # propagate nested rollback
if $rollback_exception =~ /$exception_class/;
$self->throw_exception(
"Transaction aborted: ${exception}. "
. "Rollback failed: ${rollback_exception}"
);
}
$self->throw_exception($exception)
}
# We were not connected, and was first try - reconnect and retry
# via the while loop
carp "Retrying $coderef after catching disconnected exception: $exception"
if $ENV{DBIC_DBIRETRY_DEBUG};
$self->_populate_dbh;
}
}
=head2 disconnect
Our C<disconnect> method also performs a rollback first if the
database is not in C<AutoCommit> mode.
=cut
sub disconnect {
my ($self) = @_;
if( $self->_dbh ) {
my @actions;
push @actions, ( $self->on_disconnect_call || () );
push @actions, $self->_parse_connect_do ('on_disconnect_do');
$self->_do_connection_actions(disconnect_call_ => $_) for @actions;
$self->_dbh_rollback unless $self->_dbh_autocommit;
%{ $self->_dbh->{CachedKids} } = ();
$self->_dbh->disconnect;
$self->_dbh(undef);
$self->{_dbh_gen}++;
}
}
=head2 with_deferred_fk_checks
=over 4
=item Arguments: C<$coderef>
=item Return Value: The return value of $coderef
=back
Storage specific method to run the code ref with FK checks deferred or
in MySQL's case disabled entirely.
=cut
# Storage subclasses should override this
sub with_deferred_fk_checks {
my ($self, $sub) = @_;
$sub->();
}
=head2 connected
=over
=item Arguments: none
=item Return Value: 1|0
=back
Verifies that the current database handle is active and ready to execute
an SQL statement (e.g. the connection did not get stale, server is still
answering, etc.) This method is used internally by L</dbh>.
=cut
sub connected {
my $self = shift;
return 0 unless $self->_seems_connected;
#be on the safe side
local $self->_dbh->{RaiseError} = 1;
return $self->_ping;
}
sub _seems_connected {
my $self = shift;
$self->_preserve_foreign_dbh;
my $dbh = $self->_dbh
or return 0;
return $dbh->FETCH('Active');
}
sub _ping {
my $self = shift;
my $dbh = $self->_dbh or return 0;
return $dbh->ping;
}
sub ensure_connected {
my ($self) = @_;
unless ($self->connected) {
$self->_populate_dbh;
}
}
=head2 dbh
Returns a C<$dbh> - a data base handle of class L<DBI>. The returned handle
is guaranteed to be healthy by implicitly calling L</connected>, and if
necessary performing a reconnection before returning. Keep in mind that this
is very B<expensive> on some database engines. Consider using L</dbh_do>
instead.
=cut
sub dbh {
my ($self) = @_;
if (not $self->_dbh) {
$self->_populate_dbh;
} else {
$self->ensure_connected;
}
return $self->_dbh;
}
# this is the internal "get dbh or connect (don't check)" method
sub _get_dbh {
my $self = shift;
$self->_preserve_foreign_dbh;
$self->_populate_dbh unless $self->_dbh;
return $self->_dbh;
}
sub _sql_maker_args {
my ($self) = @_;
return (
bindtype=>'columns',
array_datatypes => 1,
limit_dialect => $self->_get_dbh,
%{$self->_sql_maker_opts}
);
}
sub sql_maker {
my ($self) = @_;
unless ($self->_sql_maker) {
my $sql_maker_class = $self->sql_maker_class;
$self->ensure_class_loaded ($sql_maker_class);
$self->_sql_maker($sql_maker_class->new( $self->_sql_maker_args ));
}
return $self->_sql_maker;
}
# nothing to do by default
sub _rebless {}
sub _init {}
sub _populate_dbh {
my ($self) = @_;
my @info = @{$self->_dbi_connect_info || []};
$self->_dbh(undef); # in case ->connected failed we might get sent here
$self->_server_info_hash (undef);
$self->_dbh($self->_connect(@info));
$self->_conn_pid($$);
$self->_conn_tid(threads->tid) if $INC{'threads.pm'};
$self->_determine_driver;
# Always set the transaction depth on connect, since
# there is no transaction in progress by definition
$self->{transaction_depth} = $self->_dbh_autocommit ? 0 : 1;
$self->_run_connection_actions unless $self->{_in_determine_driver};
}
sub _run_connection_actions {
my $self = shift;
my @actions;
push @actions, ( $self->on_connect_call || () );
push @actions, $self->_parse_connect_do ('on_connect_do');