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