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