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