add cookbook example for multi-step prefetch
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI.pm
CommitLineData
8b445e33 1package DBIx::Class::Storage::DBI;
2
20a2c954 3use strict;
4use warnings;
8b445e33 5use DBI;
aeaf3ce2 6use SQL::Abstract::Limit;
28927b50 7use DBIx::Class::Storage::DBI::Cursor;
92b858c9 8use IO::File;
8b445e33 9
bd7efd39 10BEGIN {
11
cb5f2eea 12package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
bd7efd39 13
14use base qw/SQL::Abstract::Limit/;
15
54540863 16sub 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
23sub _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
32sub _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
48sub _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
2a816814 65sub _table {
bd7efd39 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
76sub _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;
73856587 82
54540863 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 }
73856587 90 push(@sqlf, $join_clause);
91
bd7efd39 92 if (ref $to eq 'ARRAY') {
93 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
94 } else {
96cdbbab 95 push(@sqlf, $self->_make_as($to));
bd7efd39 96 }
97 push(@sqlf, ' ON ', $self->_join_condition($on));
98 }
99 return join('', @sqlf);
100}
101
102sub _make_as {
103 my ($self, $from) = @_;
54540863 104 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
2a816814 105 reverse each %{$self->_skip_options($from)});
73856587 106}
107
108sub _skip_options {
54540863 109 my ($self, $hash) = @_;
110 my $clean_hash = {};
111 $clean_hash->{$_} = $hash->{$_}
112 for grep {!/^-/} keys %$hash;
113 return $clean_hash;
bd7efd39 114}
115
116sub _join_condition {
117 my ($self, $cond) = @_;
5efe4c79 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 }
bd7efd39 127}
128
2a816814 129sub _quote {
130 my ($self, $label) = @_;
131 return '' unless defined $label;
132 return $self->SUPER::_quote($label);
133}
134
bd7efd39 135} # End of BEGIN block
136
8b445e33 137use base qw/DBIx::Class/;
138
438adc0e 139__PACKAGE__->load_components(qw/Exception AccessorGroup/);
8b445e33 140
223b8fe3 141__PACKAGE__->mk_group_accessors('simple' =>
92b858c9 142 qw/connect_info _dbh _sql_maker debug debugfh cursor on_connect_do transaction_depth/);
8091aa91 143
8b445e33 144sub new {
223b8fe3 145 my $new = bless({}, ref $_[0] || $_[0]);
28927b50 146 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
d79f59b9 147 $new->transaction_depth(0);
5e65c358 148 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
149 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
92b858c9 150 $new->debugfh(IO::File->new($1, 'w')||die "Cannot open trace file $1");
151 } else {
152 $new->debugfh(IO::File->new('>&STDERR'));
153 }
28927b50 154 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
223b8fe3 155 return $new;
8b445e33 156}
157
8b445e33 158=head1 NAME
159
160DBIx::Class::Storage::DBI - DBI storage handler
161
162=head1 SYNOPSIS
163
164=head1 DESCRIPTION
165
166This class represents the connection to the database
167
168=head1 METHODS
169
8b445e33 170=cut
171
d7c4c15c 172=head2 on_connect_do
173
174Executes the sql statements given as a listref on every db connect.
175
92b858c9 176=head2 debug
177
178Causes SQL trace information to be emitted on C<debugfh> filehandle
179(or C<STDERR> if C<debugfh> has not specifically been set).
180
181=head2 debugfh
182
183Sets or retrieves the filehandle used for trace/debug output. This
184should be an IO::Handle compatible object (only the C<print> method is
185used). Initially set to be STDERR - although see information on the
186L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
187
d7c4c15c 188=cut
189
8b445e33 190sub dbh {
191 my ($self) = @_;
192 my $dbh;
193 unless (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping) {
194 $self->_populate_dbh;
195 }
196 return $self->_dbh;
197}
198
48c69e7c 199sub sql_maker {
200 my ($self) = @_;
fdc1c3d0 201 unless ($self->_sql_maker) {
bd7efd39 202 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
48c69e7c 203 }
204 return $self->_sql_maker;
205}
206
8b445e33 207sub _populate_dbh {
208 my ($self) = @_;
209 my @info = @{$self->connect_info || []};
210 $self->_dbh($self->_connect(@info));
d7c4c15c 211
212 # if on-connect sql statements are given execute them
213 foreach my $sql_statement (@{$self->on_connect_do || []}) {
214 $self->_dbh->do($sql_statement);
215 }
8b445e33 216}
217
218sub _connect {
219 my ($self, @info) = @_;
220 return DBI->connect(@info);
221}
222
8091aa91 223=head2 txn_begin
8b445e33 224
8091aa91 225Calls begin_work on the current dbh.
8b445e33 226
227=cut
228
8091aa91 229sub txn_begin {
d79f59b9 230 my $self = shift;
231 $self->dbh->begin_work if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
8091aa91 232}
8b445e33 233
8091aa91 234=head2 txn_commit
8b445e33 235
8091aa91 236Issues a commit against the current dbh.
8b445e33 237
8091aa91 238=cut
239
240sub txn_commit {
d79f59b9 241 my $self = shift;
242 if ($self->{transaction_depth} == 0) {
243 $self->dbh->commit unless $self->dbh->{AutoCommit};
8091aa91 244 }
245 else {
d79f59b9 246 $self->dbh->commit if --$self->{transaction_depth} == 0;
8091aa91 247 }
248}
249
250=head2 txn_rollback
251
252Issues a rollback against the current dbh.
8b445e33 253
254=cut
255
8091aa91 256sub txn_rollback {
d79f59b9 257 my $self = shift;
258 if ($self->{transaction_depth} == 0) {
259 $self->dbh->rollback unless $self->dbh->{AutoCommit};
8091aa91 260 }
261 else {
d79f59b9 262 --$self->{transaction_depth} == 0 ? $self->dbh->rollback : die $@;
8091aa91 263 }
264}
8b445e33 265
223b8fe3 266sub _execute {
267 my ($self, $op, $extra_bind, $ident, @args) = @_;
268 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
944f30bf 269 unshift(@bind, @$extra_bind) if $extra_bind;
92b858c9 270 $self->debugfh->print("$sql: @bind\n") if $self->debug;
2f5911b2 271 my $sth = $self->sth($sql,$op);
438adc0e 272 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
273 my $rv = $sth->execute(@bind);
223b8fe3 274 return (wantarray ? ($rv, $sth, @bind) : $rv);
275}
276
8b445e33 277sub insert {
278 my ($self, $ident, $to_insert) = @_;
20a2c954 279 $self->throw( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
a4b2f17b 280 unless ($self->_execute('insert' => [], $ident, $to_insert));
8b445e33 281 return $to_insert;
282}
283
284sub update {
223b8fe3 285 return shift->_execute('update' => [], @_);
8b445e33 286}
287
288sub delete {
223b8fe3 289 return shift->_execute('delete' => [], @_);
8b445e33 290}
291
de705b51 292sub _select {
8b445e33 293 my ($self, $ident, $select, $condition, $attrs) = @_;
223b8fe3 294 my $order = $attrs->{order_by};
295 if (ref $condition eq 'SCALAR') {
296 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
297 }
54540863 298 if (exists $attrs->{group_by}) {
299 $order = { group_by => $attrs->{group_by},
300 ($order ? (order_by => $order) : ()) };
301 }
5c91499f 302 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
9229f20a 303 if ($attrs->{software_limit} ||
304 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
305 $attrs->{software_limit} = 1;
5c91499f 306 } else {
307 push @args, $attrs->{rows}, $attrs->{offset};
308 }
de705b51 309 return $self->_execute(@args);
310}
311
312sub select {
313 my $self = shift;
314 my ($ident, $select, $condition, $attrs) = @_;
cb5f2eea 315 return $self->cursor->new($self, \@_, $attrs);
8b445e33 316}
317
1a14aa3f 318sub select_single {
de705b51 319 my $self = shift;
320 my ($rv, $sth, @bind) = $self->_select(@_);
1a14aa3f 321 return $sth->fetchrow_array;
322}
323
8b445e33 324sub sth {
cb5f2eea 325 my ($self, $sql) = @_;
91fa659e 326 # 3 is the if_active parameter which avoids active sth re-use
327 return $self->dbh->prepare_cached($sql, {}, 3);
8b445e33 328}
329
a953d8d9 330=head2 columns_info_for
331
332Returns database type info for a given table columns.
333
334=cut
335
336sub columns_info_for {
337 my ($self, $table) = @_;
a953d8d9 338 my %result;
103e3e03 339 if ( $self->dbh->can( 'column_info' ) ){
340 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
341 $sth->execute();
342 while ( my $info = $sth->fetchrow_hashref() ){
343 my %column_info;
a953d8d9 344 $column_info{data_type} = $info->{TYPE_NAME};
345 $column_info{size} = $info->{COLUMN_SIZE};
346 $column_info{is_nullable} = $info->{NULLABLE};
103e3e03 347 $result{$info->{COLUMN_NAME}} = \%column_info;
348 }
349 }else{
350 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
351 $sth->execute;
352 my @columns = @{$sth->{NAME}};
353 for my $i ( 0 .. $#columns ){
354 $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
a953d8d9 355 }
a953d8d9 356 }
357 return \%result;
358}
359
8b445e33 3601;
361
92b858c9 362=head1 ENVIRONMENT VARIABLES
363
364=head2 DBIX_CLASS_STORAGE_DBI_DEBUG
365
366If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
367is produced (as when the L<debug> method is set).
368
369If the value is of the form C<1=/path/name> then the trace output is
370written to the file C</path/name>.
371
8b445e33 372=head1 AUTHORS
373
daec44b8 374Matt S. Trout <mst@shadowcatsystems.co.uk>
8b445e33 375
9f19b1d6 376Andy Grundman <andy@hybridized.org>
377
8b445e33 378=head1 LICENSE
379
380You may distribute this code under the same terms as Perl itself.
381
382=cut
383