t/50fork.t made a little more resilient
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI.pm
CommitLineData
8b445e33 1package DBIx::Class::Storage::DBI;
2
a62cf8d4 3use base 'DBIx::Class::Storage';
4
20a2c954 5use strict;
6use warnings;
8b445e33 7use DBI;
aeaf3ce2 8use SQL::Abstract::Limit;
28927b50 9use DBIx::Class::Storage::DBI::Cursor;
92b858c9 10use IO::File;
701da8c4 11use Carp::Clan qw/DBIx::Class/;
8b445e33 12
bd7efd39 13BEGIN {
14
cb5f2eea 15package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
bd7efd39 16
17use base qw/SQL::Abstract::Limit/;
18
54540863 19sub select {
20 my ($self, $table, $fields, $where, $order, @rest) = @_;
21 @rest = (-1) unless defined $rest[0];
22 $self->SUPER::select($table, $self->_recurse_fields($fields),
23 $where, $order, @rest);
24}
25
26sub _emulate_limit {
27 my $self = shift;
28 if ($_[3] == -1) {
29 return $_[1].$self->_order_by($_[2]);
30 } else {
31 return $self->SUPER::_emulate_limit(@_);
32 }
33}
34
35sub _recurse_fields {
36 my ($self, $fields) = @_;
37 my $ref = ref $fields;
38 return $self->_quote($fields) unless $ref;
39 return $$fields if $ref eq 'SCALAR';
40
41 if ($ref eq 'ARRAY') {
42 return join(', ', map { $self->_recurse_fields($_) } @$fields);
43 } elsif ($ref eq 'HASH') {
44 foreach my $func (keys %$fields) {
45 return $self->_sqlcase($func)
46 .'( '.$self->_recurse_fields($fields->{$func}).' )';
47 }
48 }
49}
50
51sub _order_by {
52 my $self = shift;
53 my $ret = '';
54 if (ref $_[0] eq 'HASH') {
55 if (defined $_[0]->{group_by}) {
56 $ret = $self->_sqlcase(' group by ')
57 .$self->_recurse_fields($_[0]->{group_by});
58 }
59 if (defined $_[0]->{order_by}) {
60 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
61 }
62 } else {
63 $ret = $self->SUPER::_order_by(@_);
64 }
65 return $ret;
66}
67
f48dd03f 68sub _order_directions {
69 my ($self, $order) = @_;
70 $order = $order->{order_by} if ref $order eq 'HASH';
71 return $self->SUPER::_order_directions($order);
72}
73
2a816814 74sub _table {
bd7efd39 75 my ($self, $from) = @_;
76 if (ref $from eq 'ARRAY') {
77 return $self->_recurse_from(@$from);
78 } elsif (ref $from eq 'HASH') {
79 return $self->_make_as($from);
80 } else {
81 return $from;
82 }
83}
84
85sub _recurse_from {
86 my ($self, $from, @join) = @_;
87 my @sqlf;
88 push(@sqlf, $self->_make_as($from));
89 foreach my $j (@join) {
90 my ($to, $on) = @$j;
73856587 91
54540863 92 # check whether a join type exists
93 my $join_clause = '';
94 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
95 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
96 } else {
97 $join_clause = ' JOIN ';
98 }
73856587 99 push(@sqlf, $join_clause);
100
bd7efd39 101 if (ref $to eq 'ARRAY') {
102 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
103 } else {
96cdbbab 104 push(@sqlf, $self->_make_as($to));
bd7efd39 105 }
106 push(@sqlf, ' ON ', $self->_join_condition($on));
107 }
108 return join('', @sqlf);
109}
110
111sub _make_as {
112 my ($self, $from) = @_;
54540863 113 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
2a816814 114 reverse each %{$self->_skip_options($from)});
73856587 115}
116
117sub _skip_options {
54540863 118 my ($self, $hash) = @_;
119 my $clean_hash = {};
120 $clean_hash->{$_} = $hash->{$_}
121 for grep {!/^-/} keys %$hash;
122 return $clean_hash;
bd7efd39 123}
124
125sub _join_condition {
126 my ($self, $cond) = @_;
5efe4c79 127 if (ref $cond eq 'HASH') {
128 my %j;
129 for (keys %$cond) { my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; };
130 return $self->_recurse_where(\%j);
131 } elsif (ref $cond eq 'ARRAY') {
132 return join(' OR ', map { $self->_join_condition($_) } @$cond);
133 } else {
134 die "Can't handle this yet!";
135 }
bd7efd39 136}
137
2a816814 138sub _quote {
139 my ($self, $label) = @_;
140 return '' unless defined $label;
2437a1e3 141 return "*" if $label eq '*';
41728a6e 142 return $label unless $self->{quote_char};
2437a1e3 143 if(ref $self->{quote_char} eq "ARRAY"){
144 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
145 if !defined $self->{name_sep};
146 my $sep = $self->{name_sep};
147 return join($self->{name_sep},
148 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
149 split(/\Q$sep\E/,$label));
150 }
2a816814 151 return $self->SUPER::_quote($label);
152}
153
f66596f9 154sub _RowNum {
155 my $self = shift;
156 my $c;
157 $_[0] =~ s/SELECT (.*?) FROM/
158 'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
159 $self->SUPER::_RowNum(@_);
160}
161
7be93b07 162# Accessor for setting limit dialect. This is useful
163# for JDBC-bridge among others where the remote SQL-dialect cannot
164# be determined by the name of the driver alone.
165#
166sub limit_dialect {
167 my $self = shift;
168 $self->{limit_dialect} = shift if @_;
169 return $self->{limit_dialect};
170}
171
2437a1e3 172sub quote_char {
173 my $self = shift;
174 $self->{quote_char} = shift if @_;
175 return $self->{quote_char};
176}
177
178sub name_sep {
179 my $self = shift;
180 $self->{name_sep} = shift if @_;
181 return $self->{name_sep};
182}
183
184
185
186
486ad69b 187package DBIx::Class::Storage::DBI::DebugCallback;
188
189sub print {
190 my ($self, $string) = @_;
191 $string =~ m/^(\w+)/;
192 ${$self}->($1, $string);
193}
194
bd7efd39 195} # End of BEGIN block
196
8b445e33 197use base qw/DBIx::Class/;
198
1f692767 199__PACKAGE__->load_components(qw/AccessorGroup/);
8b445e33 200
223b8fe3 201__PACKAGE__->mk_group_accessors('simple' =>
5ef3e508 202 qw/connect_info _dbh _sql_maker _connection_pid debug debugfh cursor
203 on_connect_do transaction_depth/);
8091aa91 204
8b445e33 205sub new {
223b8fe3 206 my $new = bless({}, ref $_[0] || $_[0]);
28927b50 207 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
d79f59b9 208 $new->transaction_depth(0);
5e65c358 209 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
210 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
701da8c4 211 $new->debugfh(IO::File->new($1, 'w')||croak "Cannot open trace file $1");
92b858c9 212 } else {
213 $new->debugfh(IO::File->new('>&STDERR'));
214 }
28927b50 215 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
223b8fe3 216 return $new;
8b445e33 217}
218
8b445e33 219=head1 NAME
220
221DBIx::Class::Storage::DBI - DBI storage handler
222
223=head1 SYNOPSIS
224
225=head1 DESCRIPTION
226
227This class represents the connection to the database
228
229=head1 METHODS
230
8b445e33 231=cut
232
d7c4c15c 233=head2 on_connect_do
234
235Executes the sql statements given as a listref on every db connect.
236
92b858c9 237=head2 debug
238
239Causes SQL trace information to be emitted on C<debugfh> filehandle
240(or C<STDERR> if C<debugfh> has not specifically been set).
241
242=head2 debugfh
243
244Sets or retrieves the filehandle used for trace/debug output. This
245should be an IO::Handle compatible object (only the C<print> method is
246used). Initially set to be STDERR - although see information on the
247L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
248
486ad69b 249=head2 debugcb
250
251Sets a callback to be executed each time a statement is run; takes a sub
252reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
253where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
254be printed.
255
d7c4c15c 256=cut
257
486ad69b 258sub debugcb {
259 my ($self, $cb) = @_;
260 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
261 $self->debugfh($cb_obj);
262}
263
412db1f4 264sub disconnect {
265 my ($self) = @_;
266
92925617 267 if( $self->connected ) {
268 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
269 $self->_dbh->disconnect;
270 $self->_dbh(undef);
271 }
412db1f4 272}
273
274sub connected {
8b445e33 275 my ($self) = @_;
412db1f4 276
8b445e33 277 my $dbh;
412db1f4 278 (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping)
279}
280
281sub ensure_connected {
282 my ($self) = @_;
283
284 unless ($self->connected) {
8b445e33 285 $self->_populate_dbh;
286 }
412db1f4 287}
288
289sub dbh {
290 my ($self) = @_;
291
d1b9a425 292 if($self->_connection_pid && $self->_connection_pid != $$) {
293 $self->_dbh->{InactiveDestroy} = 1;
294 $self->_dbh(undef)
295 }
412db1f4 296 $self->ensure_connected;
8b445e33 297 return $self->_dbh;
298}
299
48c69e7c 300sub sql_maker {
301 my ($self) = @_;
fdc1c3d0 302 unless ($self->_sql_maker) {
bd7efd39 303 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
48c69e7c 304 }
305 return $self->_sql_maker;
306}
307
8b445e33 308sub _populate_dbh {
309 my ($self) = @_;
310 my @info = @{$self->connect_info || []};
311 $self->_dbh($self->_connect(@info));
d7c4c15c 312
313 # if on-connect sql statements are given execute them
314 foreach my $sql_statement (@{$self->on_connect_do || []}) {
315 $self->_dbh->do($sql_statement);
316 }
5ef3e508 317
318 $self->_connection_pid($$);
8b445e33 319}
320
321sub _connect {
322 my ($self, @info) = @_;
5ef3e508 323
324 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
325 my $old_connect_via = $DBI::connect_via;
326 $DBI::connect_via = 'connect';
327 my $dbh = DBI->connect(@info);
328 $DBI::connect_via = $old_connect_via;
329 return $dbh;
330 }
331
332 DBI->connect(@info);
8b445e33 333}
334
8091aa91 335=head2 txn_begin
8b445e33 336
8091aa91 337Calls begin_work on the current dbh.
8b445e33 338
339=cut
340
8091aa91 341sub txn_begin {
d79f59b9 342 my $self = shift;
343 $self->dbh->begin_work if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
8091aa91 344}
8b445e33 345
8091aa91 346=head2 txn_commit
8b445e33 347
8091aa91 348Issues a commit against the current dbh.
8b445e33 349
8091aa91 350=cut
351
352sub txn_commit {
d79f59b9 353 my $self = shift;
354 if ($self->{transaction_depth} == 0) {
355 $self->dbh->commit unless $self->dbh->{AutoCommit};
8091aa91 356 }
357 else {
d79f59b9 358 $self->dbh->commit if --$self->{transaction_depth} == 0;
8091aa91 359 }
360}
361
362=head2 txn_rollback
363
364Issues a rollback against the current dbh.
8b445e33 365
366=cut
367
8091aa91 368sub txn_rollback {
d79f59b9 369 my $self = shift;
a62cf8d4 370
371 eval {
372 if ($self->{transaction_depth} == 0) {
373 $self->dbh->rollback unless $self->dbh->{AutoCommit};
374 }
375 else {
376 --$self->{transaction_depth} == 0 ?
377 $self->dbh->rollback :
378 die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
379 }
380 };
381
382 if ($@) {
383 my $error = $@;
384 my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
385 $error =~ /$exception_class/ and $self->throw_exception($error);
386 $self->{transaction_depth} = 0; # ensure that a failed rollback
387 $self->throw_exception($error); # resets the transaction depth
8091aa91 388 }
389}
8b445e33 390
223b8fe3 391sub _execute {
392 my ($self, $op, $extra_bind, $ident, @args) = @_;
393 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
944f30bf 394 unshift(@bind, @$extra_bind) if $extra_bind;
f59ffc79 395 if ($self->debug) {
396 my @debug_bind = map { defined $_ ? $_ : 'NULL' } @bind;
397 $self->debugfh->print("$sql: @debug_bind\n");
398 }
2f5911b2 399 my $sth = $self->sth($sql,$op);
dec2517f 400 croak "no sth generated via sql: $sql" unless $sth;
438adc0e 401 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
701da8c4 402 my $rv;
403 if ($sth) {
404 $rv = $sth->execute(@bind);
405 } else {
406 croak "'$sql' did not generate a statement.";
407 }
223b8fe3 408 return (wantarray ? ($rv, $sth, @bind) : $rv);
409}
410
8b445e33 411sub insert {
412 my ($self, $ident, $to_insert) = @_;
701da8c4 413 croak( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
a4b2f17b 414 unless ($self->_execute('insert' => [], $ident, $to_insert));
8b445e33 415 return $to_insert;
416}
417
418sub update {
223b8fe3 419 return shift->_execute('update' => [], @_);
8b445e33 420}
421
422sub delete {
223b8fe3 423 return shift->_execute('delete' => [], @_);
8b445e33 424}
425
de705b51 426sub _select {
8b445e33 427 my ($self, $ident, $select, $condition, $attrs) = @_;
223b8fe3 428 my $order = $attrs->{order_by};
429 if (ref $condition eq 'SCALAR') {
430 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
431 }
54540863 432 if (exists $attrs->{group_by}) {
433 $order = { group_by => $attrs->{group_by},
434 ($order ? (order_by => $order) : ()) };
435 }
5c91499f 436 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
9229f20a 437 if ($attrs->{software_limit} ||
438 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
439 $attrs->{software_limit} = 1;
5c91499f 440 } else {
441 push @args, $attrs->{rows}, $attrs->{offset};
442 }
de705b51 443 return $self->_execute(@args);
444}
445
446sub select {
447 my $self = shift;
448 my ($ident, $select, $condition, $attrs) = @_;
cb5f2eea 449 return $self->cursor->new($self, \@_, $attrs);
8b445e33 450}
451
6157db4f 452# Need to call finish() to work round broken DBDs
453
1a14aa3f 454sub select_single {
de705b51 455 my $self = shift;
456 my ($rv, $sth, @bind) = $self->_select(@_);
6157db4f 457 my @row = $sth->fetchrow_array;
458 $sth->finish();
459 return @row;
1a14aa3f 460}
461
8b445e33 462sub sth {
cb5f2eea 463 my ($self, $sql) = @_;
91fa659e 464 # 3 is the if_active parameter which avoids active sth re-use
465 return $self->dbh->prepare_cached($sql, {}, 3);
8b445e33 466}
467
a953d8d9 468=head2 columns_info_for
469
470Returns database type info for a given table columns.
471
472=cut
473
474sub columns_info_for {
475 my ($self, $table) = @_;
a953d8d9 476 my %result;
103e3e03 477 if ( $self->dbh->can( 'column_info' ) ){
478 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
479 $sth->execute();
480 while ( my $info = $sth->fetchrow_hashref() ){
481 my %column_info;
a953d8d9 482 $column_info{data_type} = $info->{TYPE_NAME};
483 $column_info{size} = $info->{COLUMN_SIZE};
484 $column_info{is_nullable} = $info->{NULLABLE};
103e3e03 485 $result{$info->{COLUMN_NAME}} = \%column_info;
486 }
487 }else{
488 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
489 $sth->execute;
490 my @columns = @{$sth->{NAME}};
491 for my $i ( 0 .. $#columns ){
492 $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
a953d8d9 493 }
a953d8d9 494 }
495 return \%result;
496}
497
92925617 498sub DESTROY { shift->disconnect }
499
8b445e33 5001;
501
92b858c9 502=head1 ENVIRONMENT VARIABLES
503
504=head2 DBIX_CLASS_STORAGE_DBI_DEBUG
505
506If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
507is produced (as when the L<debug> method is set).
508
509If the value is of the form C<1=/path/name> then the trace output is
510written to the file C</path/name>.
511
8b445e33 512=head1 AUTHORS
513
daec44b8 514Matt S. Trout <mst@shadowcatsystems.co.uk>
8b445e33 515
9f19b1d6 516Andy Grundman <andy@hybridized.org>
517
8b445e33 518=head1 LICENSE
519
520You may distribute this code under the same terms as Perl itself.
521
522=cut
523