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