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