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