Working HAVING, DBD::SQLite returns duff data so tests don't pass yet
[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;
701da8c4 9use Carp::Clan qw/DBIx::Class/;
8b445e33 10
bd7efd39 11BEGIN {
12
cb5f2eea 13package DBIC::SQL::Abstract; # Would merge upstream, but nate doesn't reply :(
bd7efd39 14
15use base qw/SQL::Abstract::Limit/;
16
54540863 17sub select {
18 my ($self, $table, $fields, $where, $order, @rest) = @_;
19 @rest = (-1) unless defined $rest[0];
8839560b 20 local $self->{having_bind} = [];
21 my ($sql, @ret) = $self->SUPER::select($table,
22 $self->_recurse_fields($fields), $where, $order, @rest);
23 return wantarray ? ($sql, @ret, @{$self->{having_bind}}) : $sql;
54540863 24}
25
26sub _emulate_limit {
27 my $self = shift;
28 if ($_[3] == -1) {
29 return $_[1].$self->_order_by($_[2]);
30 } else {
31 return $self->SUPER::_emulate_limit(@_);
32 }
33}
34
35sub _recurse_fields {
36 my ($self, $fields) = @_;
37 my $ref = ref $fields;
38 return $self->_quote($fields) unless $ref;
39 return $$fields if $ref eq 'SCALAR';
40
41 if ($ref eq 'ARRAY') {
42 return join(', ', map { $self->_recurse_fields($_) } @$fields);
43 } elsif ($ref eq 'HASH') {
44 foreach my $func (keys %$fields) {
45 return $self->_sqlcase($func)
46 .'( '.$self->_recurse_fields($fields->{$func}).' )';
47 }
48 }
49}
50
51sub _order_by {
52 my $self = shift;
53 my $ret = '';
8839560b 54 my @extra;
54540863 55 if (ref $_[0] eq 'HASH') {
56 if (defined $_[0]->{group_by}) {
57 $ret = $self->_sqlcase(' group by ')
58 .$self->_recurse_fields($_[0]->{group_by});
59 }
8839560b 60 if (defined $_[0]->{having}) {
61 my $frag;
62 ($frag, @extra) = $self->_recurse_where($_[0]->{having});
63 push(@{$self->{having_bind}}, @extra);
64 $ret .= $self->_sqlcase(' having ').$frag;
65 }
54540863 66 if (defined $_[0]->{order_by}) {
67 $ret .= $self->SUPER::_order_by($_[0]->{order_by});
68 }
69 } else {
70 $ret = $self->SUPER::_order_by(@_);
71 }
72 return $ret;
73}
74
f48dd03f 75sub _order_directions {
76 my ($self, $order) = @_;
77 $order = $order->{order_by} if ref $order eq 'HASH';
78 return $self->SUPER::_order_directions($order);
79}
80
2a816814 81sub _table {
bd7efd39 82 my ($self, $from) = @_;
83 if (ref $from eq 'ARRAY') {
84 return $self->_recurse_from(@$from);
85 } elsif (ref $from eq 'HASH') {
86 return $self->_make_as($from);
87 } else {
88 return $from;
89 }
90}
91
92sub _recurse_from {
93 my ($self, $from, @join) = @_;
94 my @sqlf;
95 push(@sqlf, $self->_make_as($from));
96 foreach my $j (@join) {
97 my ($to, $on) = @$j;
73856587 98
54540863 99 # check whether a join type exists
100 my $join_clause = '';
101 if (ref($to) eq 'HASH' and exists($to->{-join_type})) {
102 $join_clause = ' '.uc($to->{-join_type}).' JOIN ';
103 } else {
104 $join_clause = ' JOIN ';
105 }
73856587 106 push(@sqlf, $join_clause);
107
bd7efd39 108 if (ref $to eq 'ARRAY') {
109 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
110 } else {
96cdbbab 111 push(@sqlf, $self->_make_as($to));
bd7efd39 112 }
113 push(@sqlf, ' ON ', $self->_join_condition($on));
114 }
115 return join('', @sqlf);
116}
117
118sub _make_as {
119 my ($self, $from) = @_;
54540863 120 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
2a816814 121 reverse each %{$self->_skip_options($from)});
73856587 122}
123
124sub _skip_options {
54540863 125 my ($self, $hash) = @_;
126 my $clean_hash = {};
127 $clean_hash->{$_} = $hash->{$_}
128 for grep {!/^-/} keys %$hash;
129 return $clean_hash;
bd7efd39 130}
131
132sub _join_condition {
133 my ($self, $cond) = @_;
5efe4c79 134 if (ref $cond eq 'HASH') {
135 my %j;
136 for (keys %$cond) { my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; };
137 return $self->_recurse_where(\%j);
138 } elsif (ref $cond eq 'ARRAY') {
139 return join(' OR ', map { $self->_join_condition($_) } @$cond);
140 } else {
141 die "Can't handle this yet!";
142 }
bd7efd39 143}
144
2a816814 145sub _quote {
146 my ($self, $label) = @_;
147 return '' unless defined $label;
41728a6e 148 return $label unless $self->{quote_char};
2a816814 149 return $self->SUPER::_quote($label);
150}
151
f66596f9 152sub _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
7be93b07 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#
164sub limit_dialect {
165 my $self = shift;
166 $self->{limit_dialect} = shift if @_;
167 return $self->{limit_dialect};
168}
169
486ad69b 170package DBIx::Class::Storage::DBI::DebugCallback;
171
172sub print {
173 my ($self, $string) = @_;
174 $string =~ m/^(\w+)/;
175 ${$self}->($1, $string);
176}
177
bd7efd39 178} # End of BEGIN block
179
8b445e33 180use base qw/DBIx::Class/;
181
1f692767 182__PACKAGE__->load_components(qw/AccessorGroup/);
8b445e33 183
223b8fe3 184__PACKAGE__->mk_group_accessors('simple' =>
5ef3e508 185 qw/connect_info _dbh _sql_maker _connection_pid debug debugfh cursor
186 on_connect_do transaction_depth/);
8091aa91 187
8b445e33 188sub new {
223b8fe3 189 my $new = bless({}, ref $_[0] || $_[0]);
28927b50 190 $new->cursor("DBIx::Class::Storage::DBI::Cursor");
d79f59b9 191 $new->transaction_depth(0);
5e65c358 192 if (defined($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG}) &&
193 ($ENV{DBIX_CLASS_STORAGE_DBI_DEBUG} =~ /=(.+)$/)) {
701da8c4 194 $new->debugfh(IO::File->new($1, 'w')||croak "Cannot open trace file $1");
92b858c9 195 } else {
196 $new->debugfh(IO::File->new('>&STDERR'));
197 }
28927b50 198 $new->debug(1) if $ENV{DBIX_CLASS_STORAGE_DBI_DEBUG};
223b8fe3 199 return $new;
8b445e33 200}
201
8b445e33 202=head1 NAME
203
204DBIx::Class::Storage::DBI - DBI storage handler
205
206=head1 SYNOPSIS
207
208=head1 DESCRIPTION
209
210This class represents the connection to the database
211
212=head1 METHODS
213
8b445e33 214=cut
215
d7c4c15c 216=head2 on_connect_do
217
218Executes the sql statements given as a listref on every db connect.
219
92b858c9 220=head2 debug
221
222Causes SQL trace information to be emitted on C<debugfh> filehandle
223(or C<STDERR> if C<debugfh> has not specifically been set).
224
225=head2 debugfh
226
227Sets or retrieves the filehandle used for trace/debug output. This
228should be an IO::Handle compatible object (only the C<print> method is
229used). Initially set to be STDERR - although see information on the
230L<DBIX_CLASS_STORAGE_DBI_DEBUG> environment variable.
231
486ad69b 232=head2 debugcb
233
234Sets a callback to be executed each time a statement is run; takes a sub
235reference. Overrides debugfh. Callback is executed as $sub->($op, $info)
236where $op is SELECT/INSERT/UPDATE/DELETE and $info is what would normally
237be printed.
238
d7c4c15c 239=cut
240
486ad69b 241sub debugcb {
242 my ($self, $cb) = @_;
243 my $cb_obj = bless(\$cb, 'DBIx::Class::Storage::DBI::DebugCallback');
244 $self->debugfh($cb_obj);
245}
246
412db1f4 247sub disconnect {
248 my ($self) = @_;
249
92925617 250 if( $self->connected ) {
251 $self->_dbh->rollback unless $self->_dbh->{AutoCommit};
252 $self->_dbh->disconnect;
253 $self->_dbh(undef);
254 }
412db1f4 255}
256
257sub connected {
8b445e33 258 my ($self) = @_;
412db1f4 259
8b445e33 260 my $dbh;
412db1f4 261 (($dbh = $self->_dbh) && $dbh->FETCH('Active') && $dbh->ping)
262}
263
264sub ensure_connected {
265 my ($self) = @_;
266
267 unless ($self->connected) {
8b445e33 268 $self->_populate_dbh;
269 }
412db1f4 270}
271
272sub dbh {
273 my ($self) = @_;
274
5ef3e508 275 $self->_dbh(undef)
276 if $self->_connection_pid && $self->_connection_pid != $$;
412db1f4 277 $self->ensure_connected;
8b445e33 278 return $self->_dbh;
279}
280
48c69e7c 281sub sql_maker {
282 my ($self) = @_;
fdc1c3d0 283 unless ($self->_sql_maker) {
bd7efd39 284 $self->_sql_maker(new DBIC::SQL::Abstract( limit_dialect => $self->dbh ));
48c69e7c 285 }
286 return $self->_sql_maker;
287}
288
8b445e33 289sub _populate_dbh {
290 my ($self) = @_;
291 my @info = @{$self->connect_info || []};
292 $self->_dbh($self->_connect(@info));
843f8ecd 293 my $driver = $self->_dbh->{Driver}->{Name};
34470972 294 eval "require DBIx::Class::Storage::DBI::${driver}";
295 unless ($@) {
843f8ecd 296 bless $self, "DBIx::Class::Storage::DBI::${driver}";
297 }
d7c4c15c 298 # if on-connect sql statements are given execute them
299 foreach my $sql_statement (@{$self->on_connect_do || []}) {
300 $self->_dbh->do($sql_statement);
301 }
5ef3e508 302
303 $self->_connection_pid($$);
8b445e33 304}
305
306sub _connect {
307 my ($self, @info) = @_;
5ef3e508 308
309 if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
310 my $old_connect_via = $DBI::connect_via;
311 $DBI::connect_via = 'connect';
312 my $dbh = DBI->connect(@info);
313 $DBI::connect_via = $old_connect_via;
314 return $dbh;
315 }
316
e571e823 317 my $dbh = DBI->connect(@info);
318 croak "DBI Connection failed: $DBI::errstr"
319 unless $dbh;
320 $dbh;
8b445e33 321}
322
8091aa91 323=head2 txn_begin
8b445e33 324
8091aa91 325Calls begin_work on the current dbh.
8b445e33 326
327=cut
328
8091aa91 329sub txn_begin {
d79f59b9 330 my $self = shift;
331 $self->dbh->begin_work if $self->{transaction_depth}++ == 0 and $self->dbh->{AutoCommit};
8091aa91 332}
8b445e33 333
8091aa91 334=head2 txn_commit
8b445e33 335
8091aa91 336Issues a commit against the current dbh.
8b445e33 337
8091aa91 338=cut
339
340sub txn_commit {
d79f59b9 341 my $self = shift;
342 if ($self->{transaction_depth} == 0) {
343 $self->dbh->commit unless $self->dbh->{AutoCommit};
8091aa91 344 }
345 else {
d79f59b9 346 $self->dbh->commit if --$self->{transaction_depth} == 0;
8091aa91 347 }
348}
349
350=head2 txn_rollback
351
352Issues a rollback against the current dbh.
8b445e33 353
354=cut
355
8091aa91 356sub txn_rollback {
d79f59b9 357 my $self = shift;
358 if ($self->{transaction_depth} == 0) {
359 $self->dbh->rollback unless $self->dbh->{AutoCommit};
8091aa91 360 }
361 else {
d79f59b9 362 --$self->{transaction_depth} == 0 ? $self->dbh->rollback : die $@;
8091aa91 363 }
364}
8b445e33 365
223b8fe3 366sub _execute {
367 my ($self, $op, $extra_bind, $ident, @args) = @_;
368 my ($sql, @bind) = $self->sql_maker->$op($ident, @args);
944f30bf 369 unshift(@bind, @$extra_bind) if $extra_bind;
f59ffc79 370 if ($self->debug) {
371 my @debug_bind = map { defined $_ ? $_ : 'NULL' } @bind;
372 $self->debugfh->print("$sql: @debug_bind\n");
373 }
2f5911b2 374 my $sth = $self->sth($sql,$op);
dec2517f 375 croak "no sth generated via sql: $sql" unless $sth;
438adc0e 376 @bind = map { ref $_ ? ''.$_ : $_ } @bind; # stringify args
701da8c4 377 my $rv;
378 if ($sth) {
379 $rv = $sth->execute(@bind);
380 } else {
381 croak "'$sql' did not generate a statement.";
382 }
223b8fe3 383 return (wantarray ? ($rv, $sth, @bind) : $rv);
384}
385
8b445e33 386sub insert {
387 my ($self, $ident, $to_insert) = @_;
701da8c4 388 croak( "Couldn't insert ".join(', ', map "$_ => $to_insert->{$_}", keys %$to_insert)." into ${ident}" )
a4b2f17b 389 unless ($self->_execute('insert' => [], $ident, $to_insert));
8b445e33 390 return $to_insert;
391}
392
393sub update {
223b8fe3 394 return shift->_execute('update' => [], @_);
8b445e33 395}
396
397sub delete {
223b8fe3 398 return shift->_execute('delete' => [], @_);
8b445e33 399}
400
de705b51 401sub _select {
8b445e33 402 my ($self, $ident, $select, $condition, $attrs) = @_;
223b8fe3 403 my $order = $attrs->{order_by};
404 if (ref $condition eq 'SCALAR') {
405 $order = $1 if $$condition =~ s/ORDER BY (.*)$//i;
406 }
8839560b 407 if (exists $attrs->{group_by} || $attrs->{having}) {
54540863 408 $order = { group_by => $attrs->{group_by},
8839560b 409 having => $attrs->{having},
54540863 410 ($order ? (order_by => $order) : ()) };
411 }
5c91499f 412 my @args = ('select', $attrs->{bind}, $ident, $select, $condition, $order);
9229f20a 413 if ($attrs->{software_limit} ||
414 $self->sql_maker->_default_limit_syntax eq "GenericSubQ") {
415 $attrs->{software_limit} = 1;
5c91499f 416 } else {
417 push @args, $attrs->{rows}, $attrs->{offset};
418 }
de705b51 419 return $self->_execute(@args);
420}
421
422sub select {
423 my $self = shift;
424 my ($ident, $select, $condition, $attrs) = @_;
cb5f2eea 425 return $self->cursor->new($self, \@_, $attrs);
8b445e33 426}
427
6157db4f 428# Need to call finish() to work round broken DBDs
429
1a14aa3f 430sub select_single {
de705b51 431 my $self = shift;
432 my ($rv, $sth, @bind) = $self->_select(@_);
6157db4f 433 my @row = $sth->fetchrow_array;
434 $sth->finish();
435 return @row;
1a14aa3f 436}
437
8b445e33 438sub sth {
cb5f2eea 439 my ($self, $sql) = @_;
91fa659e 440 # 3 is the if_active parameter which avoids active sth re-use
441 return $self->dbh->prepare_cached($sql, {}, 3);
8b445e33 442}
443
a953d8d9 444=head2 columns_info_for
445
446Returns database type info for a given table columns.
447
448=cut
449
450sub columns_info_for {
451 my ($self, $table) = @_;
a953d8d9 452 my %result;
103e3e03 453 if ( $self->dbh->can( 'column_info' ) ){
454 my $sth = $self->dbh->column_info( undef, undef, $table, '%' );
455 $sth->execute();
456 while ( my $info = $sth->fetchrow_hashref() ){
457 my %column_info;
a953d8d9 458 $column_info{data_type} = $info->{TYPE_NAME};
459 $column_info{size} = $info->{COLUMN_SIZE};
460 $column_info{is_nullable} = $info->{NULLABLE};
103e3e03 461 $result{$info->{COLUMN_NAME}} = \%column_info;
462 }
463 }else{
464 my $sth = $self->dbh->prepare("SELECT * FROM $table WHERE 1=0");
465 $sth->execute;
466 my @columns = @{$sth->{NAME}};
467 for my $i ( 0 .. $#columns ){
468 $result{$columns[$i]}{data_type} = $sth->{TYPE}->[$i];
a953d8d9 469 }
a953d8d9 470 }
471 return \%result;
472}
473
843f8ecd 474sub last_insert_id {
475 my ($self, $row) = @_;
476
477 return $self->dbh->func('last_insert_rowid');
478
479}
480
481
482
92925617 483sub DESTROY { shift->disconnect }
484
8b445e33 4851;
486
92b858c9 487=head1 ENVIRONMENT VARIABLES
488
489=head2 DBIX_CLASS_STORAGE_DBI_DEBUG
490
491If C<DBIX_CLASS_STORAGE_DBI_DEBUG> is set then SQL trace information
492is produced (as when the L<debug> method is set).
493
494If the value is of the form C<1=/path/name> then the trace output is
495written to the file C</path/name>.
496
8b445e33 497=head1 AUTHORS
498
daec44b8 499Matt S. Trout <mst@shadowcatsystems.co.uk>
8b445e33 500
9f19b1d6 501Andy Grundman <andy@hybridized.org>
502
8b445e33 503=head1 LICENSE
504
505You may distribute this code under the same terms as Perl itself.
506
507=cut
508