Debugging/trace output control. Allows redirection to different filehandle, more...
[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
10 BEGIN {
11
12 package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
13
14 use base qw/SQL::Abstract::Limit/;
15
16 sub select {
17   my ($self, $table, $fields, $where, $order, @rest) = @_;
18   @rest = (-1) unless defined $rest[0];
19   $self->SUPER::select($table, $self->_recurse_fields($fields), 
20                          $where, $order, @rest);
21 }
22
23 sub _emulate_limit {
24   my $self = shift;
25   if ($_[3] == -1) {
26     return $_[1].$self->_order_by($_[2]);
27   } else {
28     return $self->SUPER::_emulate_limit(@_);
29   }
30 }
31
32 sub _recurse_fields {
33   my ($self, $fields) = @_;
34   my $ref = ref $fields;
35   return $self->_quote($fields) unless $ref;
36   return $$fields if $ref eq 'SCALAR';
37
38   if ($ref eq 'ARRAY') {
39     return join(', ', map { $self->_recurse_fields($_) } @$fields);
40   } elsif ($ref eq 'HASH') {
41     foreach my $func (keys %$fields) {
42       return $self->_sqlcase($func)
43         .'( '.$self->_recurse_fields($fields->{$func}).' )';
44     }
45   }
46 }
47
48 sub _order_by {
49   my $self = shift;
50   my $ret = '';
51   if (ref $_[0] eq 'HASH') {
52     if (defined $_[0]->{group_by}) {
53       $ret = $self->_sqlcase(' group by ')
54                .$self->_recurse_fields($_[0]->{group_by});
55     }
56     if (defined $_[0]->{order_by}) {
57       $ret .= $self->SUPER::_order_by($_[0]->{order_by});
58     }
59   } else {
60     $ret = $self->SUPER::_order_by(@_);
61   }
62   return $ret;
63 }
64
65 sub _table {
66   my ($self, $from) = @_;
67   if (ref $from eq 'ARRAY') {
68     return $self->_recurse_from(@$from);
69   } elsif (ref $from eq 'HASH') {
70     return $self->_make_as($from);
71   } else {
72     return $from;
73   }
74 }
75
76 sub _recurse_from {
77   my ($self, $from, @join) = @_;
78   my @sqlf;
79   push(@sqlf, $self->_make_as($from));
80   foreach my $j (@join) {
81     my ($to, $on) = @$j;
82
83     # check whether a join type exists
84     my $join_clause = '';
85     if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
86       $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
87     } else {
88       $join_clause = ' JOIN ';
89     }
90     push(@sqlf, $join_clause);
91
92     if (ref $to eq 'ARRAY') {
93       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
94     } else {
95       push(@sqlf, $self->_make_as($to));
96     }
97     push(@sqlf, ' ON ', $self->_join_condition($on));
98   }
99   return join('', @sqlf);
100 }
101
102 sub _make_as {
103   my ($self, $from) = @_;
104   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
105                            reverse each %{$self->_skip_options($from)});
106 }
107
108 sub _skip_options {
109   my ($self, $hash) = @_;
110   my $clean_hash = {};
111   $clean_hash->{$_} = $hash->{$_}
112     for grep {!/^-/} keys %$hash;
113   return $clean_hash;
114 }
115
116 sub _join_condition {
117   my ($self, $cond) = @_;
118   if (ref $cond eq 'HASH') {
119     my %j;
120     for (keys %$cond) { my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; };
121     return $self->_recurse_where(\%j);
122   } elsif (ref $cond eq 'ARRAY') {
123     return join(' OR ', map { $self->_join_condition($_) } @$cond);
124   } else {
125     die "Can't handle this yet!";
126   }
127 }
128
129 sub _quote {
130   my ($self, $label) = @_;
131   return '' unless defined $label;
132   return $self->SUPER::_quote($label);
133 }
134
135 } # End of BEGIN block
136
137 use base qw/DBIx::Class/;
138
139 __PACKAGE__->load_components(qw/Exception AccessorGroup/);
140
141 __PACKAGE__->mk_group_accessors('simple' =>
142   qw/connect_info _dbh _sql_maker debug debugfh cursor on_connect_do transaction_depth/);
143
144 sub new {
145   my $new = bless({}, ref $_[0] || $_[0]);
146   $new->cursor("DBIx::Class::Storage::DBI::Cursor");
147   $new->transaction_depth(0);
148   if ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/) {
149     $new->debugfh(IO::File->new($1, 'w')||die "Cannot open trace file $1");
150   } else {
151     $new->debugfh(IO::File->new('>&STDERR'));
152   }
153   $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
154   return $new;
155 }
156
157 =head1 NAME 
158
159 DBIx::Class::Storage::DBI - DBI storage handler
160
161 =head1 SYNOPSIS
162
163 =head1 DESCRIPTION
164
165 This class represents the connection to the database
166
167 =head1 METHODS
168
169 =cut
170
171 =head2 on_connect_do
172
173 Executes the sql statements given as a listref on every db connect.
174
175 =head2 debug
176
177 Causes SQL trace information to be emitted on C<debugfh> filehandle
178 (or C<STDERR> if C<debugfh> has not specifically been set).
179
180 =head2 debugfh
181
182 Sets or retrieves the filehandle used for trace/debug output.  This
183 should be an IO::Handle compatible object (only the C<print> method is
184 used).  Initially set to be STDERR - although see information on the
185 L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
186
187 =cut
188
189 sub dbh {
190   my ($self) = @_;
191   my $dbh;
192   unless (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping) {
193     $self->_populate_dbh;
194   }
195   return $self->_dbh;
196 }
197
198 sub sql_maker {
199   my ($self) = @_;
200   unless ($self->_sql_maker) {
201     $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
202   }
203   return $self->_sql_maker;
204 }
205
206 sub _populate_dbh {
207   my ($self) = @_;
208   my @info = @{$self->connect_info || []};
209   $self->_dbh($self->_connect(@info));
210
211   # if on-connect sql statements are given execute them
212   foreach my $sql_statement (@{$self->on_connect_do || []}) {
213     $self->_dbh->do($sql_statement);
214   }
215 }
216
217 sub _connect {
218   my ($self, @info) = @_;
219   return DBI->connect(@info);
220 }
221
222 =head2 txn_begin
223
224 Calls begin_work on the current dbh.
225
226 =cut
227
228 sub txn_begin {
229   my $self = shift;
230   $self->dbh->begin_work if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
231 }
232
233 =head2 txn_commit
234
235 Issues a commit against the current dbh.
236
237 =cut
238
239 sub txn_commit {
240   my $self = shift;
241   if ($self->{transaction_depth} == 0) {
242     $self->dbh->commit unless $self->dbh->{AutoCommit};
243   }
244   else {
245     $self->dbh->commit if --$self->{transaction_depth} == 0;    
246   }
247 }
248
249 =head2 txn_rollback
250
251 Issues a rollback against the current dbh.
252
253 =cut
254
255 sub txn_rollback {
256   my $self = shift;
257   if ($self->{transaction_depth} == 0) {
258     $self->dbh->rollback unless $self->dbh->{AutoCommit};
259   }
260   else {
261     --$self->{transaction_depth} == 0 ? $self->dbh->rollback : die $@;    
262   }
263 }
264
265 sub _execute {
266   my ($self, $op, $extra_bind, $ident, @args) = @_;
267   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
268   unshift(@bind, @$extra_bind) if $extra_bind;
269   $self->debugfh->print("$sql: @bind\n") if $self->debug;
270   my $sth = $self->sth($sql,$op);
271   @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
272   my $rv = $sth->execute(@bind);
273   return (wantarray ? ($rv, $sth, @bind) : $rv);
274 }
275
276 sub insert {
277   my ($self, $ident, $to_insert) = @_;
278   $self->throw( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
279     unless ($self->_execute('insert' => [], $ident, $to_insert));
280   return $to_insert;
281 }
282
283 sub update {
284   return shift->_execute('update' => [], @_);
285 }
286
287 sub delete {
288   return shift->_execute('delete' => [], @_);
289 }
290
291 sub _select {
292   my ($self, $ident, $select, $condition, $attrs) = @_;
293   my $order = $attrs->{order_by};
294   if (ref $condition eq 'SCALAR') {
295     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
296   }
297   if (exists $attrs->{group_by}) {
298     $order = { group_by => $attrs->{group_by},
299                ($order ? (order_by => $order) : ()) };
300   }
301   my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
302   if ($attrs->{software_limit} ||
303       $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
304         $attrs->{software_limit} = 1;
305   } else {
306     push @args, $attrs->{rows}, $attrs->{offset};
307   }
308   return $self->_execute(@args);
309 }
310
311 sub select {
312   my $self = shift;
313   my ($ident, $select, $condition, $attrs) = @_;
314   return $self->cursor->new($self, \@_, $attrs);
315 }
316
317 sub select_single {
318   my $self = shift;
319   my ($rv, $sth, @bind) = $self->_select(@_);
320   return $sth->fetchrow_array;
321 }
322
323 sub sth {
324   my ($self, $sql) = @_;
325   # 3 is the if_active parameter which avoids active sth re-use
326   return $self->dbh->prepare_cached($sql, {}, 3);
327 }
328
329 =head2 columns_info_for
330
331 Returns database type info for a given table columns.
332
333 =cut
334
335 sub columns_info_for {
336     my ($self, $table) = @_;
337     my %result;
338     if ( $self->dbh->can( 'column_info' ) ){
339         my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
340         $sth->execute();
341         while ( my $info = $sth->fetchrow_hashref() ){
342             my %column_info;
343             $column_info{data_type} = $info->{TYPE_NAME};
344             $column_info{size} = $info->{COLUMN_SIZE};
345             $column_info{is_nullable} = $info->{NULLABLE};
346             $result{$info->{COLUMN_NAME}} = \%column_info;
347         }
348     }else{
349         my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
350         $sth->execute;
351         my @columns = @{$sth->{NAME}};
352         for my $i ( 0 .. $#columns ){
353             $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
354         }
355     }
356     return \%result;
357 }
358
359 1;
360
361 =head1 ENVIRONMENT VARIABLES
362
363 =head2 DBIX_CLASS_STORAGE_DBI_DEBUG
364
365 If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
366 is produced (as when the L<debug> method is set).
367
368 If the value is of the form C<1=/path/name> then the trace output is
369 written to the file C</path/name>.
370
371 =head1 AUTHORS
372
373 Matt S. Trout <mst@shadowcatsystems.co.uk>
374
375 Andy Grundman <andy@hybridized.org>
376
377 =head1 LICENSE
378
379 You may distribute this code under the same terms as Perl itself.
380
381 =cut
382