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