Wrap DBI->connnect and ->sth calls in eval to properly throw an exception.
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI.pm
1 package DBIx::Class::Storage::DBI;
2
3 use base 'DBIx::Class::Storage';
4
5 use strict;
6 use warnings;
7 use DBI;
8 use SQL::Abstract::Limit;
9 use DBIx::Class::Storage::DBI::Cursor;
10 use IO::File;
11 use Carp::Clan qw/DBIx::Class/;
12
13 BEGIN {
14
15 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
16
17 use base qw/SQL::Abstract::Limit/;
18
19 sub select {
20   my ($self, $table, $fields, $where, $order, @rest) = @_;
21   $table = $self->_quote($table) unless ref($table);
22   @rest = (-1) unless defined $rest[0];
23   local $self->{having_bind} = [];
24   my ($sql, @ret) = $self->SUPER::select(
25     $table, $self->_recurse_fields($fields), $where, $order, @rest
26   );
27   return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
28 }
29
30 sub insert {
31   my $self = shift;
32   my $table = shift;
33   $table = $self->_quote($table) unless ref($table);
34   $self->SUPER::insert($table, @_);
35 }
36
37 sub update {
38   my $self = shift;
39   my $table = shift;
40   $table = $self->_quote($table) unless ref($table);
41   $self->SUPER::update($table, @_);
42 }
43
44 sub delete {
45   my $self = shift;
46   my $table = shift;
47   $table = $self->_quote($table) unless ref($table);
48   $self->SUPER::delete($table, @_);
49 }
50
51 sub _emulate_limit {
52   my $self = shift;
53   if ($_[3] == -1) {
54     return $_[1].$self->_order_by($_[2]);
55   } else {
56     return $self->SUPER::_emulate_limit(@_);
57   }
58 }
59
60 sub _recurse_fields {
61   my ($self, $fields) = @_;
62   my $ref = ref $fields;
63   return $self->_quote($fields) unless $ref;
64   return $$fields if $ref eq 'SCALAR';
65
66   if ($ref eq 'ARRAY') {
67     return join(', ', map { $self->_recurse_fields($_) } @$fields);
68   } elsif ($ref eq 'HASH') {
69     foreach my $func (keys %$fields) {
70       return $self->_sqlcase($func)
71         .'( '.$self->_recurse_fields($fields->{$func}).' )';
72     }
73   }
74 }
75
76 sub _order_by {
77   my $self = shift;
78   my $ret = '';
79   my @extra;
80   if (ref $_[0] eq 'HASH') {
81     if (defined $_[0]->{group_by}) {
82       $ret = $self->_sqlcase(' group by ')
83                .$self->_recurse_fields($_[0]->{group_by});
84     }
85     if (defined $_[0]->{having}) {
86       my $frag;
87       ($frag, @extra) = $self->_recurse_where($_[0]->{having});
88       push(@{$self->{having_bind}}, @extra);
89       $ret .= $self->_sqlcase(' having ').$frag;
90     }
91     if (defined $_[0]->{order_by}) {
92       $ret .= $self->SUPER::_order_by($_[0]->{order_by});
93     }
94   } elsif(ref $_[0] eq 'SCALAR') {
95     $ret = $self->_sqlcase(' order by ').${ $_[0] };
96   } else {
97     $ret = $self->SUPER::_order_by(@_);
98   }
99   return $ret;
100 }
101
102 sub _order_directions {
103   my ($self, $order) = @_;
104   $order = $order->{order_by} if ref $order eq 'HASH';
105   return $self->SUPER::_order_directions($order);
106 }
107
108 sub _table {
109   my ($self, $from) = @_;
110   if (ref $from eq 'ARRAY') {
111     return $self->_recurse_from(@$from);
112   } elsif (ref $from eq 'HASH') {
113     return $self->_make_as($from);
114   } else {
115     return $from; # would love to quote here but _table ends up getting called
116                   # twice during an ->select without a limit clause due to
117                   # the way S::A::Limit->select works. should maybe consider
118                   # bypassing this and doing S::A::select($self, ...) in
119                   # our select method above. meantime, quoting shims have
120                   # been added to select/insert/update/delete here
121   }
122 }
123
124 sub _recurse_from {
125   my ($self, $from, @join) = @_;
126   my @sqlf;
127   push(@sqlf, $self->_make_as($from));
128   foreach my $j (@join) {
129     my ($to, $on) = @$j;
130
131     # check whether a join type exists
132     my $join_clause = '';
133     if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
134       $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
135     } else {
136       $join_clause = ' JOIN ';
137     }
138     push(@sqlf, $join_clause);
139
140     if (ref $to eq 'ARRAY') {
141       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
142     } else {
143       push(@sqlf, $self->_make_as($to));
144     }
145     push(@sqlf, ' ON ', $self->_join_condition($on));
146   }
147   return join('', @sqlf);
148 }
149
150 sub _make_as {
151   my ($self, $from) = @_;
152   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
153                      reverse each %{$self->_skip_options($from)});
154 }
155
156 sub _skip_options {
157   my ($self, $hash) = @_;
158   my $clean_hash = {};
159   $clean_hash->{$_} = $hash->{$_}
160     for grep {!/^-/} keys %$hash;
161   return $clean_hash;
162 }
163
164 sub _join_condition {
165   my ($self, $cond) = @_;
166   if (ref $cond eq 'HASH') {
167     my %j;
168     for (keys %$cond) {
169       my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
170     };
171     return $self->_recurse_where(\%j);
172   } elsif (ref $cond eq 'ARRAY') {
173     return join(' OR ', map { $self->_join_condition($_) } @$cond);
174   } else {
175     die "Can't handle this yet!";
176   }
177 }
178
179 sub _quote {
180   my ($self, $label) = @_;
181   return '' unless defined $label;
182   return "*" if $label eq '*';
183   return $label unless $self->{quote_char};
184   if(ref $self->{quote_char} eq "ARRAY"){
185     return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
186       if !defined $self->{name_sep};
187     my $sep = $self->{name_sep};
188     return join($self->{name_sep},
189         map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1]  }
190        split(/\Q$sep\E/,$label));
191   }
192   return $self->SUPER::_quote($label);
193 }
194
195 sub _RowNum {
196    my $self = shift;
197    my $c;
198    $_[0] =~ s/SELECT (.*?) FROM/
199      'SELECT '.join(', ', map { $_.' AS col'.++$c } split(', ', $1)).' FROM'/e;
200    $self->SUPER::_RowNum(@_);
201 }
202
203 # Accessor for setting limit dialect. This is useful
204 # for JDBC-bridge among others where the remote SQL-dialect cannot
205 # be determined by the name of the driver alone.
206 #
207 sub limit_dialect {
208     my $self = shift;
209     $self->{limit_dialect} = shift if @_;
210     return $self->{limit_dialect};
211 }
212
213 sub quote_char {
214     my $self = shift;
215     $self->{quote_char} = shift if @_;
216     return $self->{quote_char};
217 }
218
219 sub name_sep {
220     my $self = shift;
221     $self->{name_sep} = shift if @_;
222     return $self->{name_sep};
223 }
224
225
226
227
228 package DBIx::Class::Storage::DBI::DebugCallback;
229
230 sub print {
231   my ($self, $string) = @_;
232   $string =~ m/^(\w+)/;
233   ${$self}->($1, $string);
234 }
235
236 } # End of BEGIN block
237
238 use base qw/DBIx::Class/;
239
240 __PACKAGE__->load_components(qw/AccessorGroup/);
241
242 __PACKAGE__->mk_group_accessors('simple' =>
243   qw/connect_info _dbh _sql_maker _conn_pid _conn_tid debug debugfh
244      cursor on_connect_do transaction_depth/);
245
246 sub new {
247   my $new = bless({}, ref $_[0] || $_[0]);
248   $new->cursor("DBIx::Class::Storage::DBI::Cursor");
249   $new->transaction_depth(0);
250   if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
251      ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
252     $new->debugfh(IO::File->new($1, 'w'))
253       or $new->throw_exception("Cannot open trace file $1");
254   } else {
255     $new->debugfh(IO::File->new('>&STDERR'));
256   }
257   $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
258   return $new;
259 }
260
261 sub throw_exception {
262   my ($self, $msg) = @_;
263   croak($msg);
264 }
265
266 =head1 NAME
267
268 DBIx::Class::Storage::DBI - DBI storage handler
269
270 =head1 SYNOPSIS
271
272 =head1 DESCRIPTION
273
274 This class represents the connection to the database
275
276 =head1 METHODS
277
278 =cut
279
280 =head2 on_connect_do
281
282 Executes the sql statements given as a listref on every db connect.
283
284 =head2 debug
285
286 Causes SQL trace information to be emitted on C<debugfh> filehandle
287 (or C<STDERR> if C<debugfh> has not specifically been set).
288
289 =head2 debugfh
290
291 Sets or retrieves the filehandle used for trace/debug output.  This
292 should be an IO::Handle compatible object (only the C<print> method is
293 used).  Initially set to be STDERR - although see information on the
294 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
295
296 =head2 debugcb
297
298 Sets a callback to be executed each time a statement is run; takes a sub
299 reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
300 where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
301 be printed.
302
303 =cut
304
305 sub debugcb {
306   my ($self, $cb) = @_;
307   my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
308   $self->debugfh($cb_obj);
309 }
310
311 sub disconnect {
312   my ($self) = @_;
313
314   if( $self->connected ) {
315     $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
316     $self->_dbh->disconnect;
317     $self->_dbh(undef);
318   }
319 }
320
321 sub connected {
322   my ($self) = @_;
323
324   if(my $dbh = $self->_dbh) {
325       if(defined $self->_conn_tid && $self->_conn_tid != threads->tid) {
326           $self->_sql_maker(undef);
327           return $self->_dbh(undef);
328       }
329       elsif($self->_conn_pid != $$) {
330           $self->_dbh->{InactiveDestroy} = 1;
331           $self->_sql_maker(undef);
332           return $self->_dbh(undef)
333       }
334       return ($dbh->FETCH('Active') && $dbh->ping);
335   }
336
337   return 0;
338 }
339
340 sub ensure_connected {
341   my ($self) = @_;
342
343   unless ($self->connected) {
344     $self->_populate_dbh;
345   }
346 }
347
348 sub dbh {
349   my ($self) = @_;
350
351   $self->ensure_connected;
352   return $self->_dbh;
353 }
354
355 sub sql_maker {
356   my ($self) = @_;
357   unless ($self->_sql_maker) {
358     $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
359   }
360   return $self->_sql_maker;
361 }
362
363 sub _populate_dbh {
364   my ($self) = @_;
365   my @info = @{$self->connect_info || []};
366   $self->_dbh($self->_connect(@info));
367   my $driver = $self->_dbh->{Driver}->{Name};
368   eval "require DBIx::Class::Storage::DBI::${driver}";
369   unless ($@) {
370     bless $self, "DBIx::Class::Storage::DBI::${driver}";
371   }
372   # if on-connect sql statements are given execute them
373   foreach my $sql_statement (@{$self->on_connect_do || []}) {
374     $self->_dbh->do($sql_statement);
375   }
376
377   $self->_conn_pid($$);
378   $self->_conn_tid(threads->tid) if $INC{'threads.pm'};
379 }
380
381 sub _connect {
382   my ($self, @info) = @_;
383
384   $self->throw_exception("You failed to provide any connection info")
385       if !@info;
386
387   my ($old_connect_via, $dbh);
388
389   if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
390       $old_connect_via = $DBI::connect_via;
391       $DBI::connect_via = 'connect';
392   }
393
394   eval {
395     if(ref $info[0] eq 'CODE') {
396         $dbh = &{$info[0]};
397     }
398     else {
399         $dbh = DBI->connect(@info);
400     }
401   };
402
403   $DBI::connect_via = $old_connect_via if $old_connect_via;
404
405   if (!$dbh || $@) {
406     $self->throw_exception("DBI Connection failed: " . ($@ || $DBI::errstr));
407   }
408
409   $dbh;
410 }
411
412 =head2 txn_begin
413
414 Calls begin_work on the current dbh.
415
416 See L<DBIx::Class::Schema> for the txn_do() method, which allows for
417 an entire code block to be executed transactionally.
418
419 =cut
420
421 sub txn_begin {
422   my $self = shift;
423   $self->dbh->begin_work
424     if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
425 }
426
427 =head2 txn_commit
428
429 Issues a commit against the current dbh.
430
431 =cut
432
433 sub txn_commit {
434   my $self = shift;
435   if ($self->{transaction_depth} == 0) {
436     $self->dbh->commit unless $self->dbh->{AutoCommit};
437   }
438   else {
439     $self->dbh->commit if --$self->{transaction_depth} == 0;
440   }
441 }
442
443 =head2 txn_rollback
444
445 Issues a rollback against the current dbh. A nested rollback will
446 throw a L<DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION> exception,
447 which allows the rollback to propagate to the outermost transaction.
448
449 =cut
450
451 sub txn_rollback {
452   my $self = shift;
453
454   eval {
455     if ($self->{transaction_depth} == 0) {
456       $self->dbh->rollback unless $self->dbh->{AutoCommit};
457     }
458     else {
459       --$self->{transaction_depth} == 0 ?
460         $self->dbh->rollback :
461         die DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION->new;
462     }
463   };
464
465   if ($@) {
466     my $error = $@;
467     my $exception_class = "DBIx::Class::Storage::NESTED_ROLLBACK_EXCEPTION";
468     $error =~ /$exception_class/ and $self->throw_exception($error);
469     $self->{transaction_depth} = 0;          # ensure that a failed rollback
470     $self->throw_exception($error);          # resets the transaction depth
471   }
472 }
473
474 sub _execute {
475   my ($self, $op, $extra_bind, $ident, @args) = @_;
476   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
477   unshift(@bind, @$extra_bind) if $extra_bind;
478   if ($self->debug) {
479       my @debug_bind = map { defined $_ ? qq{`$_'} : q{`NULL'} } @bind;
480       $self->debugfh->print("$sql: " . join(', ', @debug_bind) . "\n");
481   }
482   my $sth = eval { $self->sth($sql,$op) };
483
484   if (!$sth || $@) {
485     $self->throw_exception('no sth generated via sql (' . ($@ || $self->_dbh->errstr) . "): $sql");
486   }
487
488   @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
489   my $rv;
490   if ($sth) {
491     $rv = eval { $sth->execute(@bind) };
492
493     if ($@ || !$rv) {
494       $self->throw_exception("Error executing '$sql': ".($@ || $sth->errstr));
495     }
496   } else {
497     $self->throw_exception("'$sql' did not generate a statement.");
498   }
499   return (wantarray ? ($rv, $sth, @bind) : $rv);
500 }
501
502 sub insert {
503   my ($self, $ident, $to_insert) = @_;
504   $self->throw_exception(
505     "Couldn't insert ".join(', ',
506       map "$_ => $to_insert->{$_}", keys %$to_insert
507     )." into ${ident}"
508   ) unless ($self->_execute('insert' => [], $ident, $to_insert));
509   return $to_insert;
510 }
511
512 sub update {
513   return shift->_execute('update' => [], @_);
514 }
515
516 sub delete {
517   return shift->_execute('delete' => [], @_);
518 }
519
520 sub _select {
521   my ($self, $ident, $select, $condition, $attrs) = @_;
522   my $order = $attrs->{order_by};
523   if (ref $condition eq 'SCALAR') {
524     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
525   }
526   if (exists $attrs->{group_by} || $attrs->{having}) {
527     $order = {
528       group_by => $attrs->{group_by},
529       having => $attrs->{having},
530       ($order ? (order_by => $order) : ())
531     };
532   }
533   my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
534   if ($attrs->{software_limit} ||
535       $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
536         $attrs->{software_limit} = 1;
537   } else {
538     push @args, $attrs->{rows}, $attrs->{offset};
539   }
540   return $self->_execute(@args);
541 }
542
543 sub select {
544   my $self = shift;
545   my ($ident, $select, $condition, $attrs) = @_;
546   return $self->cursor->new($self, \@_, $attrs);
547 }
548
549 # Need to call finish() to work round broken DBDs
550
551 sub select_single {
552   my $self = shift;
553   my ($rv, $sth, @bind) = $self->_select(@_);
554   my @row = $sth->fetchrow_array;
555   $sth->finish();
556   return @row;
557 }
558
559 sub sth {
560   my ($self, $sql) = @_;
561   # 3 is the if_active parameter which avoids active sth re-use
562   return $self->dbh->prepare_cached($sql, {}, 3);
563 }
564
565 =head2 columns_info_for
566
567 Returns database type info for a given table columns.
568
569 =cut
570
571 sub columns_info_for {
572   my ($self, $table) = @_;
573
574   if ($self->dbh->can('column_info')) {
575     my %result;
576     my $old_raise_err = $self->dbh->{RaiseError};
577     my $old_print_err = $self->dbh->{PrintError};
578     $self->dbh->{RaiseError} = 1;
579     $self->dbh->{PrintError} = 0;
580     eval {
581       my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
582       $sth->execute();
583       while ( my $info = $sth->fetchrow_hashref() ){
584         my %column_info;
585         $column_info{data_type}   = $info->{TYPE_NAME};
586         $column_info{size}      = $info->{COLUMN_SIZE};
587         $column_info{is_nullable}   = $info->{NULLABLE} ? 1 : 0;
588         $column_info{default_value} = $info->{COLUMN_DEF};
589
590         $result{$info->{COLUMN_NAME}} = \%column_info;
591       }
592     };
593     $self->dbh->{RaiseError} = $old_raise_err;
594     $self->dbh->{PrintError} = $old_print_err;
595     return \%result if !$@;
596   }
597
598   my %result;
599   my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
600   $sth->execute;
601   my @columns = @{$sth->{NAME_lc}};
602   for my $i ( 0 .. $#columns ){
603     my %column_info;
604     my $type_num = $sth->{TYPE}->[$i];
605     my $type_name;
606     if(defined $type_num && $self->dbh->can('type_info')) {
607       my $type_info = $self->dbh->type_info($type_num);
608       $type_name = $type_info->{TYPE_NAME} if $type_info;
609     }
610     $column_info{data_type} = $type_name ? $type_name : $type_num;
611     $column_info{size} = $sth->{PRECISION}->[$i];
612     $column_info{is_nullable} = $sth->{NULLABLE}->[$i] ? 1 : 0;
613
614     if ($column_info{data_type} =~ m/^(.*?)\((.*?)\)$/) {
615       $column_info{data_type} = $1;
616       $column_info{size}    = $2;
617     }
618
619     $result{$columns[$i]} = \%column_info;
620   }
621
622   return \%result;
623 }
624
625 sub last_insert_id {
626   my ($self, $row) = @_;
627     
628   return $self->dbh->func('last_insert_rowid');
629
630 }
631
632 sub sqlt_type { shift->dbh->{Driver}->{Name} }
633
634 sub deployment_statements {
635   my ($self, $schema, $type, $sqltargs) = @_;
636   $type ||= $self->sqlt_type;
637   eval "use SQL::Translator";
638   $self->throw_exception("Can't deploy without SQL::Translator: $@") if $@;
639   eval "use SQL::Translator::Parser::DBIx::Class;";
640   $self->throw_exception($@) if $@;
641   eval "use SQL::Translator::Producer::${type};";
642   $self->throw_exception($@) if $@;
643   my $tr = SQL::Translator->new(%$sqltargs);
644   SQL::Translator::Parser::DBIx::Class::parse( $tr, $schema );
645   return "SQL::Translator::Producer::${type}"->can('produce')->($tr);
646 }
647
648 sub deploy {
649   my ($self, $schema, $type, $sqltargs) = @_;
650   foreach my $statement ( $self->deployment_statements($schema, $type, $sqltargs) ) {
651     for ( split(";\n", $statement)) {
652       $self->debugfh->print("$_\n") if $self->debug;
653       $self->dbh->do($_) or warn "SQL was:\n $_";
654     }
655   }
656 }
657
658 sub DESTROY { shift->disconnect }
659
660 1;
661
662 =head1 ENVIRONMENT VARIABLES
663
664 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
665
666 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
667 is produced (as when the L<debug> method is set).
668
669 If the value is of the form C<1=/path/name> then the trace output is
670 written to the file C</path/name>.
671
672 =head1 AUTHORS
673
674 Matt S. Trout <mst@shadowcatsystems.co.uk>
675
676 Andy Grundman <andy@hybridized.org>
677
678 =head1 LICENSE
679
680 You may distribute this code under the same terms as Perl itself.
681
682 =cut
683