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