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