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