Merge 'trunk' into 'DBIx-Class-resultset'
[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; # Temporary. Merge upstream.
12
13 use base qw/SQL::Abstract::Limit/;
14
15 sub _table {
16   my ($self, $from) = @_;
17   if (ref $from eq 'ARRAY') {
18     return $self->_recurse_from(@$from);
19   } elsif (ref $from eq 'HASH') {
20     return $self->_make_as($from);
21   } else {
22     return $from;
23   }
24 }
25
26 sub _recurse_from {
27   my ($self, $from, @join) = @_;
28   my @sqlf;
29   push(@sqlf, $self->_make_as($from));
30   foreach my $j (@join) {
31     my ($to, $on) = @$j;
32
33         # check whether a join type exists
34         my $join_clause = '';
35         if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
36                 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
37         } else {
38                 $join_clause = ' JOIN ';
39         }
40     push(@sqlf, $join_clause);
41
42     if (ref $to eq 'ARRAY') {
43       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
44     } else {
45       push(@sqlf, $self->_make_as($to));
46     }
47     push(@sqlf, ' ON ', $self->_join_condition($on));
48   }
49   return join('', @sqlf);
50 }
51
52 sub _make_as {
53   my ($self, $from) = @_;
54         return join(' ', map { $self->_quote($_) }
55                            reverse each %{$self->_skip_options($from)});
56 }
57
58 sub _skip_options {
59         my ($self, $hash) = @_;
60         my $clean_hash = {};
61         $clean_hash->{$_} = $hash->{$_}
62                 for grep {!/^-/} keys %$hash;
63         return $clean_hash;
64 }
65
66 sub _join_condition {
67   my ($self, $cond) = @_;
68   die "no chance" unless ref $cond eq 'HASH';
69   my %j;
70   for (keys %$cond) { my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; };
71   return $self->_recurse_where(\%j);
72 }
73
74 sub _quote {
75   my ($self, $label) = @_;
76   return '' unless defined $label;
77   return $self->SUPER::_quote($label);
78 }
79
80 } # End of BEGIN block
81
82 use base qw/DBIx::Class/;
83
84 __PACKAGE__->load_components(qw/Exception AccessorGroup/);
85
86 __PACKAGE__->mk_group_accessors('simple' =>
87   qw/connect_info _dbh _sql_maker debug cursor/);
88
89 our $TRANSACTION = 0;
90
91 sub new {
92   my $new = bless({}, ref $_[0] || $_[0]);
93   $new->cursor("DBIx::Class::Storage::DBI::Cursor");
94   $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
95   return $new;
96 }
97
98 =head1 NAME 
99
100 DBIx::Class::Storage::DBI - DBI storage handler
101
102 =head1 SYNOPSIS
103
104 =head1 DESCRIPTION
105
106 This class represents the connection to the database
107
108 =head1 METHODS
109
110 =cut
111
112 sub dbh {
113   my ($self) = @_;
114   my $dbh;
115   unless (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping) {
116     $self->_populate_dbh;
117   }
118   return $self->_dbh;
119 }
120
121 sub sql_maker {
122   my ($self) = @_;
123   unless ($self->_sql_maker) {
124     $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
125   }
126   return $self->_sql_maker;
127 }
128
129 sub _populate_dbh {
130   my ($self) = @_;
131   my @info = @{$self->connect_info || []};
132   $self->_dbh($self->_connect(@info));
133 }
134
135 sub _connect {
136   my ($self, @info) = @_;
137   return DBI->connect(@info);
138 }
139
140 =head2 txn_begin
141
142 Calls begin_work on the current dbh.
143
144 =cut
145
146 sub txn_begin {
147   $_[0]->dbh->begin_work if $TRANSACTION++ == 0 and $_[0]->dbh->{AutoCommit};
148 }
149
150 =head2 txn_commit
151
152 Issues a commit against the current dbh.
153
154 =cut
155
156 sub txn_commit {
157   if ($TRANSACTION == 0) {
158     $_[0]->dbh->commit;
159   }
160   else {
161     $_[0]->dbh->commit if --$TRANSACTION == 0;    
162   }
163 }
164
165 =head2 txn_rollback
166
167 Issues a rollback against the current dbh.
168
169 =cut
170
171 sub txn_rollback {
172   if ($TRANSACTION == 0) {
173     $_[0]->dbh->rollback;
174   }
175   else {
176     --$TRANSACTION == 0 ? $_[0]->dbh->rollback : die $@;    
177   }
178 }
179
180 sub _execute {
181   my ($self, $op, $extra_bind, $ident, @args) = @_;
182   my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
183   unshift(@bind, @$extra_bind) if $extra_bind;
184   warn "$sql: @bind" if $self->debug;
185   my $sth = $self->sth($sql,$op);
186   @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
187   my $rv = $sth->execute(@bind);
188   return (wantarray ? ($rv, $sth, @bind) : $rv);
189 }
190
191 sub insert {
192   my ($self, $ident, $to_insert) = @_;
193   $self->throw( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
194     unless ($self->_execute('insert' => [], $ident, $to_insert));
195   return $to_insert;
196 }
197
198 sub update {
199   return shift->_execute('update' => [], @_);
200 }
201
202 sub delete {
203   return shift->_execute('delete' => [], @_);
204 }
205
206 sub _select {
207   my ($self, $ident, $select, $condition, $attrs) = @_;
208   my $order = $attrs->{order_by};
209   if (ref $condition eq 'SCALAR') {
210     $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
211   }
212   my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
213   if ($attrs->{software_limit} ||
214       $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
215         $attrs->{software_limit} = 1;
216   } else {
217     push @args, $attrs->{rows}, $attrs->{offset};
218   }
219   return $self->_execute(@args);
220 }
221
222 sub select {
223   my $self = shift;
224   my ($ident, $select, $condition, $attrs) = @_;
225   my ($rv, $sth, @bind) = $self->_select(@_);
226   return $self->cursor->new($sth, \@bind, $attrs);
227 }
228
229 sub select_single {
230   my $self = shift;
231   my ($rv, $sth, @bind) = $self->_select(@_);
232   return $sth->fetchrow_array;
233 }
234
235 sub sth {
236   my ($self, $sql, $op) = @_;
237   my $meth = (defined $op && $op ne 'select' ? 'prepare_cached' : 'prepare');
238   return $self->dbh->$meth($sql);
239 }
240
241 1;
242
243 =head1 AUTHORS
244
245 Matt S. Trout <mst@shadowcatsystems.co.uk>
246
247 Andy Grundman <andy@hybridized.org>
248
249 =head1 LICENSE
250
251 You may distribute this code under the same terms as Perl itself.
252
253 =cut
254